diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 543be7d..8c2ee9f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -63,6 +63,27 @@ jobs: holmes/tests/run-work-activity-tests.sh holmes/tests/run-extension-installer-tests.sh + - name: Test app launching, MCP transport and Ollama client settings + run: | + holmes/tests/run-app-launcher-tests.sh + holmes/tests/run-app-launch-intent-tests.sh + holmes/tests/run-mcp-http-transport-tests.sh + holmes/tests/run-ollama-capability-cache-tests.sh + holmes/tests/run-ollama-settings-tests.sh + + - name: Test task pipeline reliability + run: | + holmes/tests/run-computer-use-run-tests.sh + holmes/tests/run-approval-queue-tests.sh + holmes/tests/run-ax-element-search-tests.sh + holmes/tests/run-text-entry-tests.sh + holmes/tests/run-model-json-tests.sh + + - name: Test browser bridge reliability + run: | + holmes/tests/run-browser-bridge-extension-tests.sh + holmes/tests/run-browser-bridge-soak.sh + - name: Upload build log if: always() uses: actions/upload-artifact@v4 diff --git a/holmes/holmes-extension/automation.js b/holmes/holmes-extension/automation.js index a6342fa..62aaecb 100644 --- a/holmes/holmes-extension/automation.js +++ b/holmes/holmes-extension/automation.js @@ -343,6 +343,104 @@ self.HolmesAutomation = (function () { var PAGE_ACTIONS = { click: 1, fillField: 1, readSelection: 1, extract: 1, scrollTo: 1, waitForSelector: 1 }; + // Tunables (tests shorten them through self.__holmesBridgeConfig). Local to this + // closure so they never collide with the worker's own names. + var TUNING = (typeof self !== "undefined" && self.__holmesBridgeConfig) || {}; + // A PNG of a Retina viewport is easily 5 to 15 MB of base64; results travel + // over the loopback bridge, so screenshots are JPEG and kept under this size. + var MAX_SCREENSHOT_CHARS = Number(TUNING.maxScreenshotChars) || 4 * 1024 * 1024; + var SCREENSHOT_MAX_WIDTH = 1600; + // How long navigate waits for the page to finish loading. Below the app's 20s + // result timeout so a slow page reports loaded:false instead of timing out. + var NAVIGATE_TIMEOUT_MS = Number(TUNING.navigateTimeoutMs) || 15000; + + // Resolves when the tab reports status "complete" after arm() (so a completion + // from the page being replaced is ignored), when it closes, or at the timeout. + // Listeners are attached before navigation starts so a fast load is never missed. + function waitForTabComplete(tabId, timeoutMs, targetUrl) { + var started = Date.now(), armed = false, done = false, timer = null, finish; + // Chrome resolves tabs.update before the new load begins, while the tab still + // reports the PREVIOUS page as complete. So "complete" only counts once this + // navigation was seen loading, or when the tab is complete at the target URL + // with nothing pending (which also covers same document navigations). + var sawLoading = false; + function sameUrl(a, b) { + try { return new URL(a).href === new URL(b).href; } catch (e) { return a === b; } + } + function landedOn(tab) { + return !!tab && tab.status === "complete" && !tab.pendingUrl && !!targetUrl && sameUrl(tab.url, targetUrl); + } + var promise = new Promise(function (resolve) { finish = resolve; }); + function settle(result) { + if (done) return; + done = true; + if (timer) clearTimeout(timer); + try { chrome.tabs.onUpdated.removeListener(onUpdated); } catch (_) { /* ignore */ } + try { chrome.tabs.onRemoved.removeListener(onRemoved); } catch (_) { /* ignore */ } + result.waitedMs = Date.now() - started; + finish(result); + } + function onUpdated(id, info, tab) { + if (id !== tabId || !info) return; + if (info.status === "loading") { sawLoading = true; return; } + if (!armed) return; + if ((info.status === "complete" && sawLoading) || landedOn(tab)) settle({ complete: true }); + } + function onRemoved(id) { + if (id === tabId) settle({ complete: false, closed: true }); + } + chrome.tabs.onUpdated.addListener(onUpdated); + chrome.tabs.onRemoved.addListener(onRemoved); + timer = setTimeout(function () { settle({ complete: false, timedOut: true }); }, timeoutMs); + return { + promise: promise, + arm: async function () { + armed = true; + try { + var tab = await chrome.tabs.get(tabId); + if (tab && tab.status === "complete" && (sawLoading || landedOn(tab))) settle({ complete: true }); + } catch (e) { + settle({ complete: false, closed: true }); + } + }, + cancel: function () { settle({ complete: false, cancelled: true }); } + }; + } + + function toBase64(buffer) { + var bytes = new Uint8Array(buffer), binary = ""; + for (var i = 0; i < bytes.length; i += 0x8000) { + binary += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000)); + } + return btoa(binary); + } + + // Downscales a captured image to at most SCREENSHOT_MAX_WIDTH wide and re-encodes + // it as JPEG until it fits. Null when the worker has no OffscreenCanvas. + async function downscaleDataUrl(dataUrl, maxChars) { + try { + if (typeof OffscreenCanvas !== "function" || typeof createImageBitmap !== "function") return null; + var blob = await (await fetch(dataUrl)).blob(); + var bitmap = await createImageBitmap(blob); + var scale = Math.min(1, SCREENSHOT_MAX_WIDTH / bitmap.width); + var width = Math.max(1, Math.round(bitmap.width * scale)); + var height = Math.max(1, Math.round(bitmap.height * scale)); + var canvas = new OffscreenCanvas(width, height); + canvas.getContext("2d").drawImage(bitmap, 0, 0, width, height); + if (bitmap.close) bitmap.close(); + var quality = 0.7, out = ""; + for (;;) { + var jpeg = await canvas.convertToBlob({ type: "image/jpeg", quality: quality }); + out = "data:image/jpeg;base64," + toBase64(await jpeg.arrayBuffer()); + if (out.length <= maxChars || quality <= 0.3) break; + quality -= 0.2; + } + return { dataUrl: out, width: width, height: height }; + } catch (e) { + return null; + } + } + async function resolveTabId(params) { if (params && typeof params.tabId === "number" && params.tabId >= 0) return params.tabId; try { @@ -379,8 +477,25 @@ self.HolmesAutomation = (function () { if (!params.url) return { ok: false, error: "navigate requires a url" }; var navTabId = await resolveTabId(params); if (navTabId < 0) return { ok: false, error: "no target tab" }; - var navTab = await chrome.tabs.update(navTabId, { url: String(params.url) }); - return { ok: true, tabId: navTab.id, url: String(params.url) }; + // Resolving right after tabs.update let the next command (click, extract) + // run against the page being replaced. Wait for the load, bounded. + var loading = waitForTabComplete(navTabId, NAVIGATE_TIMEOUT_MS, String(params.url)); + var navTab; + try { + navTab = await chrome.tabs.update(navTabId, { url: String(params.url) }); + } catch (e) { + loading.cancel(); + throw e; + } + await loading.arm(); + var loaded = await loading.promise; + if (loaded.closed) { + return { ok: false, tabId: navTabId, url: String(params.url), error: "the tab was closed while navigating" }; + } + var landed = null; + try { landed = await chrome.tabs.get(navTabId); } catch (_) { /* closed after load */ } + return { ok: true, tabId: navTab.id, url: (landed && landed.url) || String(params.url), + title: landed ? landed.title : undefined, loaded: !!loaded.complete, waitedMs: loaded.waitedMs }; } case "openTab": { @@ -407,8 +522,20 @@ self.HolmesAutomation = (function () { var windowId = shotTab ? shotTab.windowId : undefined; // captureVisibleTab grabs the ACTIVE tab of the window; note that if the // requested tab isn't active this returns whatever is frontmost there. - var dataUrl = await chrome.tabs.captureVisibleTab(windowId, { format: "png" }); - return { ok: true, tabId: shotTab ? shotTab.id : -1, format: "png", dataUrl: dataUrl, bytes: dataUrl ? dataUrl.length : 0 }; + var quality = 70; + var dataUrl = await chrome.tabs.captureVisibleTab(windowId, { format: "jpeg", quality: quality }); + var downscaled = false; + if (dataUrl && dataUrl.length > MAX_SCREENSHOT_CHARS) { + var scaled = await downscaleDataUrl(dataUrl, MAX_SCREENSHOT_CHARS); + if (scaled && scaled.dataUrl.length < dataUrl.length) { dataUrl = scaled.dataUrl; downscaled = true; } + } + // No canvas in this worker: fall back to recapturing at lower quality. + while (!downscaled && dataUrl && dataUrl.length > MAX_SCREENSHOT_CHARS && quality > 30) { + quality -= 20; + dataUrl = await chrome.tabs.captureVisibleTab(windowId, { format: "jpeg", quality: quality }); + } + return { ok: true, tabId: shotTab ? shotTab.id : -1, format: "jpeg", quality: quality, downscaled: downscaled, + dataUrl: dataUrl, bytes: dataUrl ? dataUrl.length : 0 }; } default: { diff --git a/holmes/holmes-extension/background.js b/holmes/holmes-extension/background.js index 7779b75..a8941e2 100644 --- a/holmes/holmes-extension/background.js +++ b/holmes/holmes-extension/background.js @@ -37,6 +37,45 @@ const HEARTBEAT_ALARM_MINUTES = 0.5; // evictions (which is exactly why the alarm above exists), but cheap when it works. const HEARTBEAT_SUPPLEMENT_MS = 15000; +// Tunables. Tests shorten them through self.__holmesBridgeConfig; the browser never +// sets that global, so production always runs with these defaults. +const CONFIG_OVERRIDES = (typeof self !== "undefined" && self.__holmesBridgeConfig) || {}; +const CONFIG = Object.assign({ + // How often a heartbeat re-probes the active tab's content script. + heartbeatProbeMs: 15000, + // Seconds the bridge may hold GET /commands open. Chrome kills a worker whose + // fetch waits 30s for a response, so the hold and its timeout stay below that. + longPollSeconds: 20, + // Gap between polls when the app does not support long polling, or did not + // actually hold this poll. + pollIdleMs: COMMAND_POLL_MS, + // An empty long poll answered faster than this was not really held (the bridge + // was at its long poll cap); wait pollIdleMs rather than re-polling at once. + longPollMinMs: 1000, + // First retry delay after a failed poll; doubles up to 30s. + pollErrorBackoffMs: 1000, + // While commands are active, call a cheap extension API this often (resets the + // MV3 idle timer) for keepaliveWindowMs after the last command activity. + keepaliveMs: 20000, + keepaliveWindowMs: 120000, + // Result POST retry schedule: one attempt plus one per delay. + resultRetryDelaysMs: [250, 1000, 3000], + // The bridge accepts 16 MB of result; stay a little under it. + maxResultBytes: 16 * 1024 * 1024 - 64 * 1024, + // Commands for different tabs run concurrently, up to this many at once. + maxConcurrentCommands: 4, + // After Holmes activates a background composer tab, how often and how long to + // wait for the page to report itself visible before inserting. + visibilityPollMs: 50, + visibilityTimeoutMs: 2000, + // Longest wait for a content script to answer a compose read or insert. Below + // the app's 20s result timeout, so a silent page frees its slot and lane. + composeMessageTimeoutMs: 10000 +}, CONFIG_OVERRIDES); +// Every request to the bridge is bounded. A stalled app must never park a worker. +CONFIG.fetchTimeoutMs = Object.assign({ heartbeat: 5000, relay: 5000, commands: 28000, result: 15000 }, + CONFIG_OVERRIDES.fetchTimeoutMs || {}); + // MARK: - Token // Returns the persisted token, creating it on first call. Concurrent callers can race @@ -69,10 +108,16 @@ function browserInstance() { return browserInstancePromise; } -chrome.runtime.onInstalled.addListener(() => { +chrome.runtime.onInstalled.addListener((details) => { ensureToken().then((t) => { console.log("[Holmes] extension installed; token " + (t ? "ready" : "UNAVAILABLE")); }); + // Chrome only runs manifest content scripts on pages loaded AFTER install or + // update. Tabs that were already open keep no script (fresh install) or an + // orphaned one (update/reload) that can no longer reach this worker, so inject + // again. A browser update needs nothing: its tabs reload with the scripts. + const reason = details && details.reason; + if (reason === "install" || reason === "update") reinjectContentScripts(); ensureCommandLoop(); ensureHeartbeatLoop(); }); @@ -83,6 +128,182 @@ chrome.runtime.onStartup.addListener(() => { ensureHeartbeatLoop(); }); +// MARK: - Content script injection and health + +function manifestContentScripts() { + try { return chrome.runtime.getManifest().content_scripts || []; } catch (_) { return []; } +} + +function isInjectableTab(tab) { + return !!tab && typeof tab.id === "number" && !tab.discarded && /^https?:\/\//i.test(tab.url || ""); +} + +function isMissingReceiver(error) { + const text = String(error && error.message ? error.message : error); + return /receiving end does not exist|could not establish connection/i.test(text); +} + +// fetch() with a hard deadline. Aborts the request (so the socket is released) and +// rejects even if the underlying fetch ignores the abort. +async function fetchWithTimeout(url, init, ms) { + const controller = typeof AbortController === "function" ? new AbortController() : null; + let timer; + const expiry = new Promise((_, reject) => { + timer = setTimeout(() => { + if (controller) { try { controller.abort(); } catch (_) { /* ignore */ } } + reject(new Error("request to " + url + " timed out after " + ms + "ms")); + }, ms); + }); + try { + const options = Object.assign({}, init, controller ? { signal: controller.signal } : {}); + return await Promise.race([fetch(url, options), expiry]); + } finally { + clearTimeout(timer); + } +} + +function delay(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +function withTimeout(promise, ms, label) { + let timer; + const expiry = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error((label || "operation") + " timed out after " + ms + "ms")), ms); + }); + return Promise.race([promise, expiry]).finally(() => clearTimeout(timer)); +} + +// Injects this extension's content scripts into one tab exactly as the manifest +// declares them: same order, same world, and document_start entries immediately. +// Each entry is attempted even if an earlier one failed. Returns how many landed. +async function injectContentScripts(tabId) { + let injected = 0; + for (const entry of manifestContentScripts()) { + const files = (entry.js || []).slice(); + if (!files.length) continue; + const details = { target: { tabId }, files }; + if (entry.world === "MAIN") details.world = "MAIN"; + if (entry.run_at === "document_start") details.injectImmediately = true; + try { + await chrome.scripting.executeScript(details); + injected++; + } catch (e) { + // Restricted page, a tab that closed, or a page blocking one world. + } + } + return injected; +} + +async function reinjectContentScripts() { + let tabs = []; + try { tabs = await chrome.tabs.query({ url: ["http://*/*", "https://*/*"] }); } catch (_) { return; } + for (const tab of tabs) { + if (isInjectableTab(tab)) await injectContentScripts(tab.id); + } +} + +// Asks the active tab's content script whether it is alive, so the app can tell a +// healthy page from one whose script went missing while this worker keeps beating. +// A missing script in a normal page is reinjected once per tab per worker lifetime. +// Keyed by tab and page origin, so a tab that later navigates to a normal page is +// judged afresh. +const reinjectedTabs = new Set(); +// Pages where injection itself was refused (Chrome Web Store, the PDF viewer and +// other protected pages). Those are restricted, not a missing content script, and +// must never make the app tell the user to refresh. +const injectionBlockedTabs = new Set(); + +function probeKey(tab) { + let origin = ""; + try { origin = new URL(tab.url).origin; } catch (_) { origin = String(tab.url || ""); } + return tab.id + "|" + origin; +} +let lastProbe = { at: 0, value: null }; + +async function probeActiveTab() { + const now = Date.now(); + if (lastProbe.value && now - lastProbe.at < CONFIG.heartbeatProbeMs) return lastProbe.value; + let value; + try { + const tabs = await chrome.tabs.query({ active: true, lastFocusedWindow: true }); + const tab = tabs && tabs[0]; + if (!tab || typeof tab.id !== "number") { + value = { script: "none" }; + } else if (!isInjectableTab(tab)) { + value = { script: "restricted" }; + } else { + try { + const reply = await withTimeout(chrome.tabs.sendMessage(tab.id, { type: "holmes:ping" }), 1500, "ping"); + value = { script: reply && reply.ok ? "ok" : "missing" }; + } catch (e) { + const key = probeKey(tab); + if (isMissingReceiver(e) && injectionBlockedTabs.has(key)) { + value = { script: "restricted" }; + } else if (isMissingReceiver(e) && !reinjectedTabs.has(key)) { + reinjectedTabs.add(key); + if ((await injectContentScripts(tab.id)) > 0) { + value = { script: "reinjected" }; + } else { + injectionBlockedTabs.add(key); + value = { script: "restricted" }; + } + } else { + value = { script: "missing" }; + } + } + } + } catch (_) { + value = { script: "none" }; + } + lastProbe = { at: now, value }; + return value; +} + +// Waits until a just activated tab's content script reports the page visible and +// active. tabs.update resolves before the page's visibilityState flips, and the +// composer (correctly) refuses a hidden page, so inserting immediately raced it. +// Bounded by visibilityTimeoutMs. A content script too old to answer holmes:ping +// replies undefined and is not waited on. +async function waitForTabVisible(tabId) { + const deadline = Date.now() + CONFIG.visibilityTimeoutMs; + for (;;) { + try { + const reply = await withTimeout(chrome.tabs.sendMessage(tabId, { type: "holmes:ping" }), 1000, "visibility ping"); + if (reply === undefined) return true; + if (reply && reply.visible === true && reply.isActiveTab !== false) return true; + } catch (e) { + // A missing receiver is surfaced by the real message that follows. + if (isMissingReceiver(e)) return true; + } + if (Date.now() >= deadline) return false; + await delay(CONFIG.visibilityPollMs); + } +} + +async function browserFocused() { + try { + const win = await chrome.windows.getLastFocused(); + return !!(win && win.focused); + } catch (_) { + return false; + } +} + +function extensionVersion() { + try { return chrome.runtime.getManifest().version || ""; } catch (_) { return ""; } +} + +function browserName() { + try { + const brands = (typeof navigator !== "undefined" && navigator.userAgentData && navigator.userAgentData.brands) || []; + const named = brands.map(b => b.brand).find(b => !/chromium|not.?a.?brand/i.test(b)); + return named || ""; + } catch (_) { + return ""; + } +} + // MARK: - Active tab tracking // Queried rather than cached: after the worker is evicted a cached id would be stale, @@ -186,11 +407,11 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { payload.tabId = sender.tab.id; payload.windowId = sender.tab.windowId; payload.isActiveTab = true; - const res = await fetch(ENDPOINT, { + const res = await fetchWithTimeout(ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json", "X-Holmes-Token": token }, body: JSON.stringify(payload) - }); + }, CONFIG.fetchTimeoutMs.relay); sendResponse({ ok: res.ok, status: res.status }); } catch (e) { sendResponse({ ok: false, error: String(e && e.message ? e.message : e) }); @@ -204,6 +425,16 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { return true; } + // A visible, active tab pings periodically. Any message wakes an evicted MV3 + // worker and resets its idle timer, so this keeps command delivery alive while + // the user is actually looking at a page. + if (msg.type === "holmes:keepalive") { + ensureCommandLoop(); + ensureHeartbeatAlarm(); + sendResponse({ ok: true }); + return false; + } + // The popup arms adoption by making one authenticated request from the extension // origin (a heartbeat), which the Mac app adopts if the user opened the pairing // window in Settings. Nothing here can pair on its own — the human still arms it. @@ -211,11 +442,11 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { (async () => { const token = await ensureToken(); try { - const res = await fetch("http://127.0.0.1:5766/heartbeat", { + const res = await fetchWithTimeout(HEARTBEAT_ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json", "X-Holmes-Token": token }, body: "{}" - }); + }, CONFIG.fetchTimeoutMs.heartbeat); sendResponse({ ok: res.ok, status: res.status }); } catch (e) { sendResponse({ ok: false, error: String(e && e.message ? e.message : e) }); @@ -254,11 +485,20 @@ async function sendHeartbeat() { const token = await ensureToken(); if (!token) return; try { - await fetch(HEARTBEAT_ENDPOINT, { + // The beat says which browser instance this is, whether it has OS focus (the + // app routes commands that name no browser to the one in front), and whether + // the active tab's content script is alive. + const [instanceId, focused, activeTab] = await Promise.all([ + browserInstance().catch(() => ""), browserFocused(), probeActiveTab() + ]); + await fetchWithTimeout(HEARTBEAT_ENDPOINT, { method: "POST", - headers: { "Content-Type": "application/json", "X-Holmes-Token": token }, - body: "{}" - }); + headers: { + "Content-Type": "application/json", "X-Holmes-Token": token, + "X-Holmes-Browser-Instance": instanceId, "X-Holmes-Browser-Focused": focused ? "1" : "0" + }, + body: JSON.stringify({ instanceId, focused, activeTab, version: extensionVersion(), browser: browserName() }) + }, CONFIG.fetchTimeoutMs.heartbeat); } catch (e) { // Holmes app not running / port closed — expected, stay quiet. } @@ -325,69 +565,401 @@ if (chrome.alarms && chrome.alarms.onAlarm) { // worker always restarts the loop. When the Holmes app isn't listening the GET simply // fails and is swallowed, costing nothing. -let commandTimer = null; +// Delivery is a long poll: GET /commands asks the bridge to hold the request until a +// command arrives (or ~20s pass), so a command reaches a live worker immediately +// instead of on the next 2s tick. The loop re-polls as soon as each poll returns; +// against an older app without long polling it falls back to the 2s idle gap, and +// when Holmes is not running it backs off. A watchdog interval restarts the loop if +// it ever stops, and every fetch carries a timeout so the in-flight flag always clears. + +let commandLoopRunning = false; +let commandWatchdog = null; let commandPollInFlight = false; +let commandPollStartedAt = 0; +let lastCommandActivityAt = 0; +let runningCommandCount = 0; +let selfKeepaliveTimer = null; function ensureCommandLoop() { - if (commandTimer !== null) return; - commandTimer = setInterval(pollCommands, COMMAND_POLL_MS); - pollCommands(); + if (commandWatchdog === null) { + commandWatchdog = setInterval(() => { if (!commandLoopRunning) runCommandLoop(); }, COMMAND_POLL_MS); + } + if (!commandLoopRunning) runCommandLoop(); } +async function runCommandLoop() { + if (commandLoopRunning) return; + commandLoopRunning = true; + let failures = 0; + try { + for (;;) { + const outcome = await pollCommands(); + if (outcome === "longpoll") { failures = 0; continue; } + if (outcome === "error") { + failures++; + await delay(Math.min(CONFIG.pollErrorBackoffMs * Math.pow(2, Math.min(failures - 1, 5)), 30000)); + continue; + } + failures = 0; + await delay(CONFIG.pollIdleMs); // "idle" (no long poll support) or "busy" + } + } catch (e) { + // Unexpected failure (timers unavailable, worker shutting down). The watchdog + // interval restarts the loop; never spin here. + } finally { + commandLoopRunning = false; + } +} + +// One poll. Resolves "longpoll" | "idle" | "busy" | "error"; never throws. async function pollCommands() { - if (commandPollInFlight) return; + if (commandPollInFlight && Date.now() - commandPollStartedAt < CONFIG.fetchTimeoutMs.commands + 5000) return "busy"; commandPollInFlight = true; + commandPollStartedAt = Date.now(); try { const token = await ensureToken(); - if (!token) return; + if (!token) return "error"; + const [instanceId, focused] = await Promise.all([browserInstance().catch(() => ""), browserFocused()]); let res; try { - res = await fetch(COMMANDS_ENDPOINT, { + res = await fetchWithTimeout(COMMANDS_ENDPOINT, { method: "GET", - headers: { "X-Holmes-Token": token, "Accept": "application/json", "X-Holmes-Browser-Instance": await browserInstance() } - }); + headers: { + "X-Holmes-Token": token, "Accept": "application/json", + "X-Holmes-Browser-Instance": instanceId, "X-Holmes-Browser-Focused": focused ? "1" : "0", + "X-Holmes-Long-Poll": String(CONFIG.longPollSeconds) + } + }, CONFIG.fetchTimeoutMs.commands); } catch (e) { - return; // Holmes app not running / port closed — expected, stay quiet. + return "error"; // Holmes app not running, port closed, or the poll timed out. } - if (!res.ok) return; // 401 (wrong token), 404 (older app without the channel), etc. + if (!res.ok) return "error"; // 401 (wrong token), 404 (older app without the channel), etc. + const longPoll = !!(res.headers && typeof res.headers.get === "function" && res.headers.get("X-Holmes-Long-Poll") === "1"); let data; - try { data = await res.json(); } catch (e) { return; } + try { data = await res.json(); } catch (e) { return "error"; } const commands = Array.isArray(data) ? data : (data && Array.isArray(data.commands) ? data.commands : []); - for (const cmd of commands) { - await runOneCommand(cmd, token); - } + if (commands.length) noteCommandActivity(); + // Dispatch without waiting: each tab has its own serial lane and an overall cap + // bounds concurrency, so a long waitForSelector never stalls other tabs or the + // next poll. + for (const cmd of commands) scheduleCommand(cmd, token); + // Commands arrived: poll again right away, follow ups are likely. + if (commands.length) return "longpoll"; + // An empty answer only counts as a long poll if the bridge said it held it AND + // it really took a while. Otherwise wait, so several browsers over the bridge's + // long poll cap never spin both sides. + return longPoll && Date.now() - commandPollStartedAt >= CONFIG.longPollMinMs ? "longpoll" : "idle"; + } catch (e) { + return "error"; } finally { commandPollInFlight = false; } } +// Commands are "expected" for a while after one arrives: the model usually sends a +// follow up. Calling any extension API resets the MV3 idle timer, so a cheap call on +// an interval keeps the worker (and its long poll) alive until things go quiet. +function noteCommandActivity() { + lastCommandActivityAt = Date.now(); + if (selfKeepaliveTimer !== null) return; + selfKeepaliveTimer = setInterval(() => { + if (runningCommandCount === 0 && Date.now() - lastCommandActivityAt > CONFIG.keepaliveWindowMs) { + clearInterval(selfKeepaliveTimer); + selfKeepaliveTimer = null; + return; + } + try { Promise.resolve(chrome.runtime.getPlatformInfo()).catch(() => {}); } catch (_) { /* ignore */ } + }, CONFIG.keepaliveMs); +} + +// MARK: - Per tab scheduling +// +// Commands used to run strictly one after another, so one waitForSelector (up to +// 15s) delayed every other command past the app's result timeout. Now each target +// tab has a serial lane (two commands for the same page still run in order) and +// lanes run in parallel up to maxConcurrentCommands. +const commandLanes = new Map(); +let busyCommandSlots = 0; +const commandSlotWaiters = []; + +function acquireCommandSlot() { + if (busyCommandSlots < CONFIG.maxConcurrentCommands) { + busyCommandSlots++; + return { immediate: true, ready: Promise.resolve() }; + } + return { immediate: false, ready: new Promise(resolve => commandSlotWaiters.push(resolve)) }; +} + +function releaseCommandSlot() { + const next = commandSlotWaiters.shift(); + if (next) next(); else busyCommandSlots--; +} + +function commandLane(cmd) { + const params = (cmd && cmd.params) || {}; + if (typeof params.tabId === "number") return Promise.resolve("tab:" + params.tabId); + if (cmd && cmd.action === "fill_email_draft") { + try { + const identity = JSON.parse(params.expected && params.expected.identity); + if (Array.isArray(identity) && Number.isInteger(identity[2])) return Promise.resolve("tab:" + identity[2]); + } catch (_) { /* fall through to the active tab */ } + } + if (cmd && (cmd.action === "openTab" || cmd.action === "listTabs")) return Promise.resolve("browser"); + return activeTabId().then(id => (id >= 0 ? "tab:" + id : "browser")); +} + +// Tells the app a delivered command has started running after waiting its turn, +// so time spent queued in the browser does not count against its result timeout. +function postStarted(cmd, token) { + const body = { id: cmd.id, action: cmd.action, session: cmd.session, _holmesStarted: true, at: Date.now() }; + postResult(body, token); +} + +// Lane assignment is serialized in arrival order. Resolving the active tab takes +// an await, so without this a later command with an explicit tabId could claim the +// same lane first and run before an earlier navigate for that tab. +let laneAssignments = Promise.resolve(); + +function scheduleCommand(cmd, token) { + const assigned = laneAssignments.then(async () => { + const lane = await commandLane(cmd); + const previous = commandLanes.get(lane); + let release; + const turn = new Promise(resolve => { release = resolve; }); + const tail = (previous || Promise.resolve()).then(() => turn); + commandLanes.set(lane, tail); + return { lane, previous, tail, release }; + }); + laneAssignments = assigned.catch(() => {}); + return (async () => { + const { lane, previous, tail, release } = await assigned; + if (previous) await previous; + const slot = acquireCommandSlot(); + await slot.ready; + try { + if ((previous || !slot.immediate) && cmd && cmd.id !== undefined) postStarted(cmd, token); + await runOneCommand(cmd, token); + } finally { + releaseCommandSlot(); + release(); + if (commandLanes.get(lane) === tail) commandLanes.delete(lane); + } + })().catch(() => { /* runOneCommand reports its own failures */ }); +} + +// MARK: - Idempotent execution +// +// A command id can reach this worker more than once: the bridge requeues a command +// whose poll response was lost, and an evicted worker restarts mid-command. Running +// fill_field or click twice is exactly the bug, so every command is recorded in a +// ledger keyed by app launch session plus id, kept in chrome.storage.session (which +// survives worker restarts but not a browser restart) with an in-memory fallback. +// • done → the stored result is posted again; nothing re-runs. +// • running → in this worker life: the live run will post. From a previous life: +// report "interrupted" rather than guess whether it took effect. +const LEDGER_KEY = "holmesCommandLedger"; +const LEDGER_LIMIT = 100; +const LEDGER_TTL_MS = 10 * 60 * 1000; +// chrome.storage.session holds 10 MB in total, and every command rewrites the +// ledger. So entries keep a compact outcome only, and the whole ledger stays +// within a byte budget far below the quota. +const LEDGER_REPLAY_BYTES = 4 * 1024; +const LEDGER_BUDGET_BYTES = 512 * 1024; +const ledgerMemory = new Map(); +const runningCommandKeys = new Set(); +let ledgerWrites = Promise.resolve(); + +function ledgerKey(cmd) { + return (cmd && typeof cmd.session === "string" ? cmd.session : "nosession") + ":" + cmd.id; +} + +function sessionArea() { + try { return chrome.storage && chrome.storage.session ? chrome.storage.session : null; } catch (_) { return null; } +} + +function pruneLedger(ledger) { + const now = Date.now(); + const keys = Object.keys(ledger).filter(key => ledger[key] && now - (ledger[key].at || 0) < LEDGER_TTL_MS); + keys.sort((a, b) => (ledger[b].at || 0) - (ledger[a].at || 0)); + const kept = {}; + let bytes = 2; + for (const key of keys.slice(0, LEDGER_LIMIT)) { + let size = 0; + try { size = JSON.stringify(ledger[key]).length + key.length + 4; } catch (_) { continue; } + if (bytes + size > LEDGER_BUDGET_BYTES) break; + bytes += size; + kept[key] = ledger[key]; + } + return kept; +} + +// After a failed write: keep the newer half (and always `keep`) and try again. +function shrinkLedger(ledger, keep) { + const keys = Object.keys(ledger).sort((a, b) => (ledger[b].at || 0) - (ledger[a].at || 0)); + const kept = {}; + for (const key of keys.slice(0, Math.floor(keys.length / 2))) kept[key] = ledger[key]; + if (ledger[keep]) kept[keep] = ledger[keep]; + return kept; +} + +async function ledgerEntry(key) { + if (ledgerMemory.has(key)) return ledgerMemory.get(key); + const area = sessionArea(); + if (!area) return null; + try { + await ledgerWrites; + const stored = await area.get(LEDGER_KEY); + const ledger = (stored && stored[LEDGER_KEY]) || {}; + return ledger[key] || null; + } catch (_) { + return null; + } +} + +// Serialized so concurrent commands never overwrite each other's entries. +function recordLedger(key, entry) { + ledgerMemory.set(key, entry); + if (ledgerMemory.size > LEDGER_LIMIT) ledgerMemory.delete(ledgerMemory.keys().next().value); + const area = sessionArea(); + if (!area) return Promise.resolve(); + ledgerWrites = ledgerWrites.then(async () => { + try { + const stored = await area.get(LEDGER_KEY); + let ledger = pruneLedger(Object.assign((stored && stored[LEDGER_KEY]) || {}, { [key]: entry })); + // A failed write used to be swallowed, so "running" markers silently stopped + // persisting. Shrink and retry; the memory ledger covers a final failure. + for (let attempt = 0; attempt < 3; attempt++) { + try { + await area.set({ [LEDGER_KEY]: ledger }); + return; + } catch (e) { + ledger = shrinkLedger(ledger, key); + } + } + } catch (_) { /* storage unavailable: the memory ledger still dedupes */ } + }); + return ledgerWrites; +} + +// Keeps a result for replay when it is small enough; a large one (a screenshot) +// is replaced by an honest note rather than replayed as a success without data. +function replayableOutcome(outcome) { + let size = 0; + try { size = JSON.stringify(outcome).length; } catch (_) { size = Infinity; } + if (size <= LEDGER_REPLAY_BYTES) return outcome; + // Keep the summary (ok, counts, short strings) and drop bulky payloads such as + // extracted elements or screenshot data. + const compact = { replayTruncated: true, + note: "the earlier result was " + size + " bytes; only its summary was kept for replay, so request the data again if it is still needed" }; + for (const [name, value] of Object.entries(outcome || {})) { + if (value === null || typeof value === "boolean" || typeof value === "number") compact[name] = value; + else if (typeof value === "string" && value.length <= 300) compact[name] = value; + } + return compact; +} + async function runOneCommand(cmd, token) { const id = cmd && cmd.id !== undefined ? cmd.id : null; const action = cmd && cmd.action; + const session = cmd && typeof cmd.session === "string" ? cmd.session : undefined; + const key = id !== null ? ledgerKey(cmd) : null; + + if (key !== null) { + if (runningCommandKeys.has(key)) return; // already running here; that run posts the result + // Claim the key BEFORE any await: a second copy of this id in another lane + // could otherwise pass the check above while this one reads the ledger. + runningCommandKeys.add(key); + const prior = await ledgerEntry(key); + if (prior && prior.state === "done") { + runningCommandKeys.delete(key); + await postResult(Object.assign({ id, action, session, at: Date.now(), replayed: true }, prior.result), token); + return; + } + if (prior && prior.state === "running") { + const interrupted = { ok: false, interrupted: true, + error: "interrupted: the browser extension restarted while running this command, so it was not run again. Check the page before retrying." }; + await recordLedger(key, { state: "done", action, at: Date.now(), result: interrupted }); + runningCommandKeys.delete(key); + await postResult(Object.assign({ id, action, session, at: Date.now() }, interrupted), token); + return; + } + // Recorded before anything runs, so a restart mid-command is detectable. + await recordLedger(key, { state: "running", action, at: Date.now() }); + } let outcome; + runningCommandCount++; try { outcome = action === "read_email_compose" || action === "fill_email_draft" ? await emailComposeCommand(cmd) : await HolmesAutomation.execute(cmd); } catch (e) { outcome = { ok: false, error: String(e && e.message ? e.message : e) }; + } finally { + runningCommandCount--; + noteCommandActivity(); } - const body = Object.assign({ id, action, at: Date.now() }, outcome); - try { - await fetch(RESULT_ENDPOINT, { - method: "POST", - headers: { "Content-Type": "application/json", "X-Holmes-Token": token }, - body: JSON.stringify(body) - }); - } catch (e) { - // The app went away between GET and POST — drop the result rather than retry-storm. + if (key !== null) { + await recordLedger(key, { state: "done", action, at: Date.now(), result: replayableOutcome(outcome) }); + runningCommandKeys.delete(key); + } + // The session echo lets the app ignore a result meant for a previous launch. + const body = Object.assign({ id, action, session, at: Date.now() }, outcome); + await postResult(body, token); +} + +function byteLength(text) { + try { return new TextEncoder().encode(text).length; } catch (_) { return text.length; } +} + +// A result the bridge cannot take is replaced by a small, explicit error, so the +// app reports "too large" instead of timing out on a result that never arrived. +function compactSizeError(body, bytes, limit) { + return JSON.stringify({ + id: body.id, action: body.action, session: body.session, at: Date.now(), ok: false, + error: "result too large (" + bytes + " bytes; the Holmes bridge accepts " + limit + "). Narrow the selector or request less.", + bytes, limit + }); +} + +// POSTs one command result. Transient failures (network error, timeout, 5xx) are +// retried with backoff; a 413 is answered with a compact size error; an auth or +// protocol refusal is not retried. Never throws. Resolves true once delivered. +async function postResult(body, token) { + const bytes = byteLength(JSON.stringify(body)); + let text = bytes > CONFIG.maxResultBytes ? compactSizeError(body, bytes, CONFIG.maxResultBytes) : JSON.stringify(body); + const delays = CONFIG.resultRetryDelaysMs || []; + for (let attempt = 0; attempt <= delays.length; attempt++) { + let status = 0; + let limit = CONFIG.maxResultBytes; + try { + const res = await fetchWithTimeout(RESULT_ENDPOINT, { + method: "POST", + headers: { "Content-Type": "application/json", "X-Holmes-Token": token }, + body: text + }, CONFIG.fetchTimeoutMs.result); + status = res.status; + if (res.ok) return true; + if (status === 413) { + try { const info = await res.json(); if (info && Number(info.limit) > 0) limit = Number(info.limit); } catch (_) { /* ignore */ } + } + } catch (e) { + status = 0; // network failure or timeout: retry below + } + if (status === 413) { + if (byteLength(text) < 4096) return false; // even the compact error was refused + text = compactSizeError(body, bytes, limit); + continue; // resend the small version right away + } + if (status === 400 || status === 401 || status === 403 || status === 404) return false; + if (attempt < delays.length) await delay(delays[attempt]); } + return false; } async function emailComposeCommand(cmd) { @@ -407,6 +979,9 @@ async function emailComposeCommand(cmd) { await chrome.windows.update(tab.windowId, { focused: true }); await chrome.tabs.update(tab.id, { active: true }); await notifyActive(tab.id, true); + if (!(await waitForTabVisible(tab.id))) { + return { ok: false, refused: true, reason: "The composer tab did not become visible after Holmes switched to it." }; + } } else { const tabs = await chrome.tabs.query({ active: true, lastFocusedWindow: true }); tab = tabs && tabs[0]; @@ -418,10 +993,12 @@ async function emailComposeCommand(cmd) { } const environment = { tabId: tab.id, windowId: tab.windowId, instanceId }; if (await activeTabId() !== tab.id) return { ok: false, refused: true, reason: "The active tab changed." }; - const result = await chrome.tabs.sendMessage(tab.id, { + // Bounded: a content script that never answers must not pin a command slot, + // block this tab's lane, or keep the worker awake indefinitely. + const result = await withTimeout(chrome.tabs.sendMessage(tab.id, { type: cmd.action === "read_email_compose" ? "holmes:readEmailCompose" : "holmes:fillEmailDraft", environment, body: params.body, expected: params.expected - }); + }), CONFIG.composeMessageTimeoutMs, "compose message"); // A tab switch while the response was in flight invalidates a refresh. The // page writer separately validates the exact identity before any mutation. if (cmd.action === "read_email_compose" && await activeTabId() !== tab.id) { diff --git a/holmes/holmes-extension/content.js b/holmes/holmes-extension/content.js index 00efdd7..7155d9d 100644 --- a/holmes/holmes-extension/content.js +++ b/holmes/holmes-extension/content.js @@ -22,9 +22,20 @@ (function () { "use strict"; - // Content scripts can be injected twice (bfcache restore, extension reload). - if (window.__holmesContentScript) return; - window.__holmesContentScript = true; + // Content scripts can be injected twice: bfcache restores, and the worker + // reinjecting already open tabs after an install or update. A second copy defers + // to a LIVE first copy, but takes over from an orphan left behind by the previous + // extension version: that copy's runtime is gone, so it can never send again. + // (An older build stored a plain `true` here; that copy is orphaned by definition.) + var RUNTIME = (typeof chrome !== "undefined" && chrome.runtime) || null; + var existingCopy = window.__holmesContentScript; + if (existingCopy && typeof existingCopy === "object" && typeof existingCopy.alive === "function" && existingCopy.alive()) return; + try { if (existingCopy && typeof existingCopy.teardown === "function") existingCopy.teardown(); } catch (_) { /* ignore */ } + var tornDown = false; + window.__holmesContentScript = { + alive: function () { return !tornDown && runtimeAlive(); }, + teardown: function () { teardown(); } + }; // MARK: - Configuration @@ -2537,7 +2548,59 @@ var transportMode = hasRuntime() ? "relay" : "fetch"; function hasRuntime() { - return typeof chrome !== "undefined" && chrome.runtime && chrome.runtime.id; + return runtimeAlive(); + } + + // MARK: - Lifecycle (orphan detection) + // + // After the extension reloads or updates, this copy's runtime is invalidated + // (chrome.runtime.id becomes undefined) but its timers and listeners keep running, + // silently failing every send while the worker's own heartbeats keep the app + // saying "connected". Detect that on every activity and stop quietly; the worker + // reinjects a fresh copy, which takes over the page. + + function runtimeAlive() { + try { return !!(RUNTIME && RUNTIME.id); } catch (_) { return false; } + } + + var HAD_RUNTIME = runtimeAlive(); + + function teardown() { + if (tornDown) return; + tornDown = true; + try { if (heartbeatTimer) clearInterval(heartbeatTimer); } catch (_) { /* ignore */ } + try { if (keepaliveTimer) clearInterval(keepaliveTimer); } catch (_) { /* ignore */ } + try { if (flushTimer) clearTimeout(flushTimer); } catch (_) { /* ignore */ } + try { if (mutationObserver) mutationObserver.disconnect(); } catch (_) { /* ignore */ } + heartbeatTimer = null; + keepaliveTimer = null; + flushTimer = null; + } + + // True once this copy is stopped. Only a copy that HAD a runtime can be orphaned; + // a runtime-less (userscript) build keeps its direct transport. + function checkOrphaned() { + if (!tornDown && HAD_RUNTIME && !runtimeAlive()) teardown(); + return tornDown; + } + + // An evicted MV3 worker only wakes for events. While the user is looking at this + // tab, ping it so queued browser commands are picked up promptly. + var KEEPALIVE_MS = (window.__holmesContentConfig && Number(window.__holmesContentConfig.keepaliveMs)) || 20000; + var keepaliveTimer = null; + + function armKeepalive() { + if (!HAD_RUNTIME || tornDown) return; + try { if (keepaliveTimer) clearInterval(keepaliveTimer); } catch (_) { /* ignore */ } + keepaliveTimer = setInterval(function () { + if (checkOrphaned()) return; + if (document.visibilityState !== "visible" || !IS_ACTIVE_TAB) return; + try { + RUNTIME.sendMessage({ type: "holmes:keepalive" }, function () { void (RUNTIME && RUNTIME.lastError); }); + } catch (_) { + checkOrphaned(); + } + }, KEEPALIVE_MS); } function loadToken() { @@ -2571,7 +2634,7 @@ } function sendViaRelay(json) { - if (!hasRuntime()) return; + if (!hasRuntime()) { checkOrphaned(); return; } try { chrome.runtime.sendMessage({ type: "holmes:post", body: json }, function (res) { void chrome.runtime.lastError; @@ -2637,6 +2700,7 @@ var lastURL = location.href; function capture(force) { + if (checkOrphaned()) return; try { // Honor the per-site "Don't read this site" switch BEFORE any extraction runs: // an excluded host builds no payload and sends nothing at all. @@ -2659,6 +2723,7 @@ } function schedule(force) { + if (checkOrphaned()) return; if (flushTimer) return; var since = Date.now() - lastPostAt; var wait = Math.max(COALESCE_MS, MIN_POST_INTERVAL_MS - since); @@ -2754,6 +2819,15 @@ chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) { if (!msg || typeof msg.type !== "string") return false; + // Liveness and visibility probe from the worker: heartbeat health checks + // and the wait for a just activated tab to become visible before insert. + if (msg.type === "holmes:ping") { + if (tornDown) return false; + sendResponse({ ok: true, visible: document.visibilityState === "visible", isActiveTab: IS_ACTIVE_TAB, + focused: typeof document.hasFocus === "function" ? document.hasFocus() : false }); + return false; + } + if (msg.type === "holmes:readEmailCompose" || msg.type === "holmes:fillEmailDraft") { if (isExcludedHost() || !IS_ACTIVE_TAB || document.visibilityState !== "visible") { sendResponse({ ok: false, refused: true, reason: "The composer is no longer in the active tab." }); @@ -2839,9 +2913,11 @@ var heartbeatTimer = null; var heartbeatBeats = 0; function armHeartbeat() { + if (tornDown) return; try { if (heartbeatTimer) clearInterval(heartbeatTimer); } catch (e) { /* ignore */ } var period = effectiveHeartbeat(); heartbeatTimer = setInterval(function () { + if (checkOrphaned()) return; heartbeatBeats++; var forceResend = heartbeatBeats % Math.max(1, Math.round(FORCE_RESEND_MS / period)) === 0; if (forceResend) lastHash = ""; @@ -2896,6 +2972,7 @@ // that restarted mid-session gets the current page back without the user touching it. // Re-armable so the options page's heartbeat-interval setting takes effect live. armHeartbeat(); + armKeepalive(); } try { diff --git a/holmes/holmes-extension/manifest.json b/holmes/holmes-extension/manifest.json index dea4d10..1195119 100644 --- a/holmes/holmes-extension/manifest.json +++ b/holmes/holmes-extension/manifest.json @@ -1,7 +1,7 @@ { "manifest_version": 3, "name": "Holmes", - "version": "2.2", + "version": "2.3", "description": "Gives Holmes an exact, literal read of the page you are actually looking at.", "permissions": ["tabs", "storage", "scripting", "activeTab", "alarms"], "host_permissions": [ diff --git a/holmes/holmes-extension/options.js b/holmes/holmes-extension/options.js index 860cb45..856a0fb 100644 --- a/holmes/holmes-extension/options.js +++ b/holmes/holmes-extension/options.js @@ -12,6 +12,16 @@ var TOKEN_KEY = "holmesToken"; var el = function (id) { return document.getElementById(id); }; + var REQUEST_TIMEOUT_MS = 3000; + + // Every bridge request is bounded, so a hung app shows a status instead of a + // page stuck on "checking…". + function fetchWithTimeout(url, init) { + var controller = typeof AbortController === "function" ? new AbortController() : null; + var timer = setTimeout(function () { if (controller) controller.abort(); }, REQUEST_TIMEOUT_MS); + var options = Object.assign({}, init || {}, controller ? { signal: controller.signal } : {}); + return fetch(url, options).finally(function () { clearTimeout(timer); }); + } var token = ""; var revealed = false; @@ -45,16 +55,17 @@ async function checkPairing() { setPair("amber", "warn", "checking…", "Checking the Holmes bridge on 127.0.0.1:5766…"); - var healthOk = false; - try { var r = await fetch(HEALTH_URL, { method: "GET" }); healthOk = r.ok; } - catch (e) { healthOk = false; } + var healthOk = false, healthTimedOut = false; + try { var r = await fetchWithTimeout(HEALTH_URL, { method: "GET" }); healthOk = r.ok; } + catch (e) { healthOk = false; healthTimedOut = !!(e && e.name === "AbortError"); } if (!healthOk) { - setPair("red", "err", "offline", "Holmes isn’t running. Start the Holmes app to pair."); + if (healthTimedOut) setPair("red", "err", "not responding", "Holmes is running but not answering on 127.0.0.1:5766. Quit and reopen Holmes."); + else setPair("red", "err", "offline", "Holmes isn’t running. Start the Holmes app to pair."); return; } var status = 0, netErr = false; try { - var r2 = await fetch(HEARTBEAT_URL, { + var r2 = await fetchWithTimeout(HEARTBEAT_URL, { method: "POST", headers: { "Content-Type": "application/json", "X-Holmes-Token": token || "" }, body: "{}" diff --git a/holmes/holmes-extension/popup.js b/holmes/holmes-extension/popup.js index 00fabef..fbe4bab 100644 --- a/holmes/holmes-extension/popup.js +++ b/holmes/holmes-extension/popup.js @@ -14,6 +14,16 @@ var TOKEN_KEY = "holmesToken"; var el = function (id) { return document.getElementById(id); }; + var REQUEST_TIMEOUT_MS = 3000; + + // Every bridge request is bounded, so a hung app shows a status instead of a + // popup stuck on "checking…". + function fetchWithTimeout(url, init) { + var controller = typeof AbortController === "function" ? new AbortController() : null; + var timer = setTimeout(function () { if (controller) controller.abort(); }, REQUEST_TIMEOUT_MS); + var options = Object.assign({}, init || {}, controller ? { signal: controller.signal } : {}); + return fetch(url, options).finally(function () { clearTimeout(timer); }); + } var currentTab = null; var currentHost = ""; @@ -58,13 +68,15 @@ setConn("amber", "warn", "checking…", "Checking whether Holmes is listening on 127.0.0.1:5766…", false); - var healthOk = false; - try { var r = await fetch(HEALTH_URL, { method: "GET" }); healthOk = r.ok; } - catch (e) { healthOk = false; } + var healthOk = false, healthTimedOut = false; + try { var r = await fetchWithTimeout(HEALTH_URL, { method: "GET" }); healthOk = r.ok; } + catch (e) { healthOk = false; healthTimedOut = !!(e && e.name === "AbortError"); } if (!healthOk) { - setConn("red", "err", "offline", - "Holmes isn’t running. Start the Holmes app, then reopen this popup.", false); + setConn("red", "err", healthTimedOut ? "not responding" : "offline", + healthTimedOut + ? "Holmes is running but not answering on 127.0.0.1:5766. Quit and reopen Holmes." + : "Holmes isn’t running. Start the Holmes app, then reopen this popup.", false); return; } @@ -73,7 +85,7 @@ var token = await getToken(); var status = 0, netErr = false; try { - var r2 = await fetch(HEARTBEAT_URL, { + var r2 = await fetchWithTimeout(HEARTBEAT_URL, { method: "POST", headers: { "Content-Type": "application/json", "X-Holmes-Token": token || "" }, body: "{}" diff --git a/holmes/holmes.xcodeproj/project.pbxproj b/holmes/holmes.xcodeproj/project.pbxproj index 86d0705..a6c1478 100644 --- a/holmes/holmes.xcodeproj/project.pbxproj +++ b/holmes/holmes.xcodeproj/project.pbxproj @@ -8,6 +8,12 @@ /* Begin PBXBuildFile section */ AA000001000000000000114 /* ActionRunEvidence.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000114 /* ActionRunEvidence.swift */; }; + B7A500010000000000000006 /* ModelJSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7A500020000000000000006 /* ModelJSON.swift */; }; + B7A500010000000000000005 /* TextEntrySupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7A500020000000000000005 /* TextEntrySupport.swift */; }; + B7A500010000000000000004 /* AutonomousRunTally.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7A500020000000000000004 /* AutonomousRunTally.swift */; }; + B7A500010000000000000003 /* AXElementSearch.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7A500020000000000000003 /* AXElementSearch.swift */; }; + B7A500010000000000000002 /* ApprovalQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7A500020000000000000002 /* ApprovalQueue.swift */; }; + B7A500010000000000000001 /* ComputerUseRunRegistry.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7A500020000000000000001 /* ComputerUseRunRegistry.swift */; }; AA000001000000000000113 /* EmailDraftCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000113 /* EmailDraftCoordinator.swift */; }; AA000001000000000000112 /* EmailDrafting.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000112 /* EmailDrafting.swift */; }; AA000001000000000000111 /* EmailDraftIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000111 /* EmailDraftIntent.swift */; }; @@ -15,8 +21,8 @@ AA000001000000000000109 /* EmailComposeSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000109 /* EmailComposeSnapshot.swift */; }; AA000001000000000000108 /* WorkActivity.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000108 /* WorkActivity.swift */; }; AA000001000000000000107 /* GuidedDemoWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000107 /* GuidedDemoWindow.swift */; }; - AA000001000000000000108 /* LaunchIntroView.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000108 /* LaunchIntroView.swift */; }; - AA000001000000000000109 /* holmes-launch-intro.mov in Resources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000109 /* holmes-launch-intro.mov */; }; + B7A500010000000000000F01 /* LaunchIntroView.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7A500020000000000000F01 /* LaunchIntroView.swift */; }; + B7A500010000000000000F02 /* holmes-launch-intro.mov in Resources */ = {isa = PBXBuildFile; fileRef = B7A500020000000000000F02 /* holmes-launch-intro.mov */; }; AA000001000000000000106 /* GuidedDemoView.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000106 /* GuidedDemoView.swift */; }; AA000001000000000000105 /* GuidedDemo.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000105 /* GuidedDemo.swift */; }; AA000001000000000000104 /* AppLaunchIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA000002000000000000104 /* AppLaunchIntent.swift */; }; @@ -121,6 +127,12 @@ /* Begin PBXFileReference section */ AA000002000000000000114 /* ActionRunEvidence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ActionRunEvidence.swift; sourceTree = ""; }; + B7A500020000000000000006 /* ModelJSON.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelJSON.swift; sourceTree = ""; }; + B7A500020000000000000005 /* TextEntrySupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TextEntrySupport.swift; sourceTree = ""; }; + B7A500020000000000000004 /* AutonomousRunTally.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AutonomousRunTally.swift; sourceTree = ""; }; + B7A500020000000000000003 /* AXElementSearch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AXElementSearch.swift; sourceTree = ""; }; + B7A500020000000000000002 /* ApprovalQueue.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ApprovalQueue.swift; sourceTree = ""; }; + B7A500020000000000000001 /* ComputerUseRunRegistry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComputerUseRunRegistry.swift; sourceTree = ""; }; AA000002000000000000113 /* EmailDraftCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmailDraftCoordinator.swift; sourceTree = ""; }; AA000002000000000000112 /* EmailDrafting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmailDrafting.swift; sourceTree = ""; }; AA000002000000000000111 /* EmailDraftIntent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmailDraftIntent.swift; sourceTree = ""; }; @@ -128,8 +140,8 @@ AA000002000000000000109 /* EmailComposeSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EmailComposeSnapshot.swift; sourceTree = ""; }; AA000002000000000000108 /* WorkActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkActivity.swift; sourceTree = ""; }; AA000002000000000000107 /* GuidedDemoWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GuidedDemoWindow.swift; sourceTree = ""; }; - AA000002000000000000108 /* LaunchIntroView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LaunchIntroView.swift; sourceTree = ""; }; - AA000002000000000000109 /* holmes-launch-intro.mov */ = {isa = PBXFileReference; lastKnownFileType = video.quicktime; path = "holmes-launch-intro.mov"; sourceTree = ""; }; + B7A500020000000000000F01 /* LaunchIntroView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LaunchIntroView.swift; sourceTree = ""; }; + B7A500020000000000000F02 /* holmes-launch-intro.mov */ = {isa = PBXFileReference; lastKnownFileType = video.quicktime; path = "holmes-launch-intro.mov"; sourceTree = ""; }; AA000002000000000000106 /* GuidedDemoView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GuidedDemoView.swift; sourceTree = ""; }; AA000002000000000000105 /* GuidedDemo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GuidedDemo.swift; sourceTree = ""; }; AA000002000000000000104 /* AppLaunchIntent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppLaunchIntent.swift; sourceTree = ""; }; @@ -371,6 +383,12 @@ AA000002000000000000112 /* EmailDrafting.swift */, AA000002000000000000113 /* EmailDraftCoordinator.swift */, AA000002000000000000114 /* ActionRunEvidence.swift */, + B7A500020000000000000006 /* ModelJSON.swift */, + B7A500020000000000000005 /* TextEntrySupport.swift */, + B7A500020000000000000004 /* AutonomousRunTally.swift */, + B7A500020000000000000003 /* AXElementSearch.swift */, + B7A500020000000000000002 /* ApprovalQueue.swift */, + B7A500020000000000000001 /* ComputerUseRunRegistry.swift */, AA000002000000000000105 /* GuidedDemo.swift */, AA000005000000000000030 /* Setup */, AA000002000000000000103 /* AppLauncher.swift */, @@ -448,7 +466,7 @@ AA000002000000000000035 /* Info.plist */, AA000002000000000000036 /* holmes.entitlements */, AA000002000000000000040 /* noireye.json */, - AA000002000000000000109 /* holmes-launch-intro.mov */, + B7A500020000000000000F02 /* holmes-launch-intro.mov */, ); path = Resources; sourceTree = ""; @@ -457,7 +475,7 @@ isa = PBXGroup; children = ( AA000002000000000000107 /* GuidedDemoWindow.swift */, - AA000002000000000000108 /* LaunchIntroView.swift */, + B7A500020000000000000F01 /* LaunchIntroView.swift */, AA000002000000000000106 /* GuidedDemoView.swift */, AA000002000000000000011 /* OnboardingFlow.swift */, AA000002000000000000012 /* OnboardingViewModel.swift */, @@ -582,7 +600,7 @@ files = ( AA000001000000000000034 /* Assets.xcassets in Resources */, AA000001000000000000038 /* noireye.json in Resources */, - AA000001000000000000109 /* holmes-launch-intro.mov in Resources */, + B7A500010000000000000F02 /* holmes-launch-intro.mov in Resources */, AA000001000000000000101 /* holmes-extension in Resources */, AA000001000000000000102 /* Fonts in Resources */, ); @@ -596,7 +614,7 @@ buildActionMask = 2147483647; files = ( AA000001000000000000107 /* GuidedDemoWindow.swift in Sources */, - AA000001000000000000108 /* LaunchIntroView.swift in Sources */, + B7A500010000000000000F01 /* LaunchIntroView.swift in Sources */, AA000001000000000000106 /* GuidedDemoView.swift in Sources */, AA000001000000000000108 /* WorkActivity.swift in Sources */, AA000001000000000000109 /* EmailComposeSnapshot.swift in Sources */, @@ -605,6 +623,12 @@ AA000001000000000000112 /* EmailDrafting.swift in Sources */, AA000001000000000000113 /* EmailDraftCoordinator.swift in Sources */, AA000001000000000000114 /* ActionRunEvidence.swift in Sources */, + B7A500010000000000000006 /* ModelJSON.swift in Sources */, + B7A500010000000000000005 /* TextEntrySupport.swift in Sources */, + B7A500010000000000000004 /* AutonomousRunTally.swift in Sources */, + B7A500010000000000000003 /* AXElementSearch.swift in Sources */, + B7A500010000000000000002 /* ApprovalQueue.swift in Sources */, + B7A500010000000000000001 /* ComputerUseRunRegistry.swift in Sources */, AA000001000000000000105 /* GuidedDemo.swift in Sources */, AA000001000000000000001 /* holmesApp.swift in Sources */, AA000001000000000000097 /* ExtensionInstaller.swift in Sources */, diff --git a/holmes/holmes/App/holmesApp.swift b/holmes/holmes/App/holmesApp.swift index a5484bb..a826025 100644 --- a/holmes/holmes/App/holmesApp.swift +++ b/holmes/holmes/App/holmesApp.swift @@ -797,7 +797,7 @@ struct PrivacySettingsView: View { ProgressView() .controlSize(.small) } else { - Button(bridge.pairedToken == nil ? "Pair browser extension" : "Re-pair browser extension") { + Button(bridge.pairedToken == nil ? "Pair browser extension" : "Pair another browser") { bridge.beginPairing() } } @@ -817,6 +817,33 @@ struct PrivacySettingsView: View { .help("Copies the bundled extension to a folder, opens the browser's Extensions page for Load unpacked, and opens the pairing window.") } + // One row per paired browser. Pairing another browser keeps these; + // Remove is how a stale or unwanted pairing is revoked. + if let fresh = bridge.recentlyPairedExtension { + Text("Just paired: \(fresh.label) · token …\(fresh.tokenSuffix). If you didn't just pair this browser, remove it below.") + .font(NoirFonts.caption()) + .foregroundColor(.orange) + .fixedSize(horizontal: false, vertical: true) + } + if !bridge.pairedExtensions.isEmpty { + VStack(alignment: .leading, spacing: 4) { + ForEach(bridge.pairedExtensions) { paired in + HStack(spacing: 8) { + Text("\(paired.label) · token …\(paired.tokenSuffix)") + .font(NoirFonts.caption()) + if let seen = paired.lastSeen { + Text("seen \(seen, style: .relative) ago") + .font(NoirFonts.caption()) + .foregroundColor(.secondary) + } + Spacer(minLength: 0) + Button("Remove") { bridge.removePairedExtension(paired.token) } + .controlSize(.small) + } + } + } + } + VStack(alignment: .leading, spacing: 8) { Text(ExtensionInstaller.displayPath) .font(NoirFonts.font(size: 12, design: .monospaced)) @@ -897,8 +924,12 @@ struct PrivacySettingsView: View { guard PermissionManager.checkAccessibilityPermission() else { return "Drawing + speech OK. Accessibility isn\u{2019}t granted (or is stale) — grant it via Open Settings above, then click Relaunch Holmes." } - engine.beginRun() // clear any stale kill flag so the test event can post - let outcome = await engine.perform(action: "hold_key", input: ["text": "shift", "duration": 0.05]) + // A run of its own (fresh kill switch), always ended so self tests never pile up. + let testRun = engine.beginRun() + defer { engine.endRun(testRun) } + let outcome = await ComputerUseRunScope.$token.withValue(testRun) { + await engine.perform(action: "hold_key", input: ["text": "shift", "duration": 0.05]) + } if outcome.isRefused { return "Drawing + speech OK. Computer control is OFF — turn it on above." } @@ -912,17 +943,20 @@ struct PrivacySettingsView: View { private var bridgeIcon: String { if bridge.lastError != nil { return "exclamationmark.triangle.fill" } + if bridge.isExtensionConnected && bridge.isPageContextStale { return "exclamationmark.circle.fill" } return bridge.isExtensionConnected ? "checkmark.circle.fill" : "xmark.circle.fill" } private var bridgeColor: Color { if bridge.lastError != nil { return .red } + if bridge.isExtensionConnected && bridge.isPageContextStale { return .orange } return bridge.isExtensionConnected ? .green : .orange } private var bridgeStatus: String { if bridge.lastError != nil { return "Not listening" } if bridge.isPairing { return "Pairing — waiting for the extension" } + if bridge.isExtensionConnected && bridge.isPageContextStale { return "Extension connected, page context stale" } if bridge.isExtensionConnected { return "Extension connected" } // Not connected: name WHICH failure it is, so the short line is actionable // instead of an ambiguous "Waiting…". A token being rejected outranks @@ -940,11 +974,14 @@ struct PrivacySettingsView: View { return "\(error) — Holmes can't read pages until this is resolved." } if bridge.isPairing { - return "Pairing is open for the next couple of minutes: the next extension to post to 127.0.0.1:\(BrowserBridge.port) is adopted and remembered. A web page can't take it — only an extension origin (or a local client you point at the token) may pair." + return "Pairing is open for the next couple of minutes: the next extension to post to 127.0.0.1:\(BrowserBridge.port) is adopted and remembered alongside any browsers already paired. Web pages cannot pair. Any browser extension, or another app on this Mac that imitates one, could claim this window, so open it only while you are pairing Holmes and remove any browser below that you don't recognize." } if bridge.unauthorizedRequests > 0 { return "\(bridge.unauthorizedRequests) request\(bridge.unauthorizedRequests == 1 ? "" : "s") rejected: something is posting to 127.0.0.1:\(BrowserBridge.port) with a token Holmes doesn't know. If that's your extension, click Pair browser extension — Holmes never adopts a secret on its own, because every process on this Mac can reach a loopback port." } + if bridge.isExtensionConnected && bridge.isPageContextStale { + return "Listening on 127.0.0.1:\(BrowserBridge.port). The extension's background worker is connected, but the tab in front is not sending page context (its content script is missing or was orphaned by an extension update). Refresh that tab; Holmes will read it again on the next post." + } if bridge.isExtensionConnected { let paired = bridge.pairedToken == nil ? "" : " Paired with the extension's own token." return "Listening on 127.0.0.1:\(BrowserBridge.port), loopback only.\(paired)" diff --git a/holmes/holmes/Core/AXElementSearch.swift b/holmes/holmes/Core/AXElementSearch.swift new file mode 100644 index 0000000..11cc287 --- /dev/null +++ b/holmes/holmes/Core/AXElementSearch.swift @@ -0,0 +1,194 @@ +import Foundation + +// MARK: - AXElementSearch +// +// Pure pieces of Accessibility element lookup, kept free of AX types so they +// can be tested with a fake tree: +// • a BOUNDED breadth first walk. A real app's tree (a browser, Xcode, a +// long chat) can hold tens of thousands of elements, and every attribute +// read is a cross process round trip, so an unbounded recursive walk could +// stall for many seconds. Depth and visited element count are capped. +// • label ranking. A control is identified by its title, description, help +// text or identifier (icon buttons usually have only a description). An +// exact match beats a case insensitive match beats a substring match, so +// "Reply" presses Reply, not "Reply All" that happened to come first. + +enum AXLabelMatch: Int, Comparable { + case substring = 1 + case caseInsensitive = 2 + case exact = 3 + + static func < (lhs: AXLabelMatch, rhs: AXLabelMatch) -> Bool { lhs.rawValue < rhs.rawValue } +} + +/// The accessible names of one element. Help text is a sentence ABOUT a +/// control ("Send the message now"), so it only counts as a match when it +/// equals the requested label; a substring of it must never pick a control. +struct AXNames { + var title: String? + var description: String? + var help: String? + var identifier: String? + var placeholder: String? + + init(title: String? = nil, description: String? = nil, help: String? = nil, + identifier: String? = nil, placeholder: String? = nil) { + self.title = title + self.description = description + self.help = help + self.identifier = identifier + self.placeholder = placeholder + } + + var substringNames: [String?] { [title, description, identifier, placeholder] } + var exactOnlyNames: [String?] { [help] } + /// What a person sees as the control's name, for the commit gate. + var visibleName: String { + [title, description].compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) } + .filter { !$0.isEmpty }.joined(separator: " ") + } +} + +/// What happened when Holmes tried to press a named control. +enum AXPressOutcome: Equatable { + case pressed(matched: String) + case notFound + case failed(code: Int32) + /// The label matched a send/submit class control and the press was not + /// confirmed; nothing was pressed. + case needsConfirmation(matched: String) +} + +/// The commit gate for a control that was actually MATCHED. The requested +/// label alone is not enough: "later" substring matches "Send later". +enum CommitControlGate { + private static let commitRegex = try! NSRegularExpression( + pattern: #"\b(send|submit|post|publish|tweet|reply|confirm|pay|buy|order|delete|archive|trash|purchase|accept|share|discard|remove|don'?t save)\b"#, + options: [.caseInsensitive]) + + static func looksLikeCommit(_ text: String) -> Bool { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return false } + return commitRegex.firstMatch(in: trimmed, range: NSRange(trimmed.startIndex..., in: trimmed)) != nil + } + + /// True when pressing the matched control needs the user's confirmation. + static func pressNeedsConfirmation(requested: String, matched: AXNames, userConfirmed: Bool) -> Bool { + guard !userConfirmed else { return false } + return looksLikeCommit(requested) || looksLikeCommit(matched.visibleName) + } +} + +enum AXElementSearch { + static let defaultMaxDepth = 30 + static let defaultMaxNodes = 3000 + + /// Label match against an element's names, with help text exact only. + static func labelMatch(_ label: String, in names: AXNames) -> AXLabelMatch? { + let loose = labelMatch(label, names: names.substringNames) + guard let strict = labelMatch(label, names: names.exactOnlyNames), strict != .substring else { return loose } + return max(loose ?? strict, strict) + } + + /// The strongest match of `label` against any of an element's names. + static func labelMatch(_ label: String, names: [String?]) -> AXLabelMatch? { + let wanted = label.trimmingCharacters(in: .whitespacesAndNewlines) + guard !wanted.isEmpty else { return nil } + var best: AXLabelMatch? + for raw in names { + guard let name = raw?.trimmingCharacters(in: .whitespacesAndNewlines), !name.isEmpty else { continue } + let match: AXLabelMatch? + if name == wanted { + match = .exact + } else if name.compare(wanted, options: [.caseInsensitive]) == .orderedSame { + match = .caseInsensitive + } else if name.range(of: wanted, options: [.caseInsensitive, .diacriticInsensitive]) != nil { + match = .substring + } else { + match = nil + } + if let match, best.map({ match > $0 }) ?? true { best = match } + if best == .exact { return best } + } + return best + } + + /// Score for "the field to type into". A text AREA (a message or document + /// body) always outranks a text FIELD (a toolbar search box) of the same + /// label quality, so a shallow search field never wins over the body just + /// because a breadth first walk meets it first. With a hint, label quality + /// comes first and the area preference breaks ties. + static func textEntryScore(role: String, hint: String?, names: () -> AXNames) -> Int? { + let isArea = role == "AXTextArea" + guard isArea || role == "AXTextField" else { return nil } + let areaBonus = isArea ? 1 : 0 + guard let hint else { return 1 + areaBonus } + guard let match = labelMatch(hint, in: names()) else { return nil } + return match.rawValue * 2 + areaBonus + } + + /// The score at which a text entry search can stop: a text area (no hint), + /// or an exact label match on a text area (hint). + static func textEntryStopScore(hasHint: Bool) -> Int { + hasHint ? AXLabelMatch.exact.rawValue * 2 + 1 : 2 + } + + struct Result { + let node: Node? + let visited: Int + /// True when the walk stopped at a limit before seeing the whole tree. + let truncated: Bool + } + + /// Breadth first search for the highest scoring node. `score` returns nil + /// for a non match; a score of `stopScore` or more ends the walk at once. + /// Earlier nodes win ties (they are closer to the root). + static func best(from root: Node, + maxDepth: Int = defaultMaxDepth, + maxNodes: Int = defaultMaxNodes, + stopScore: Int = Int.max, + shouldStop: () -> Bool = { false }, + children: (Node) -> [Node], + score: (Node) -> Int?) -> Result { + var frontier: [(node: Node, depth: Int)] = [(root, 0)] + var head = 0 + var visited = 0 + var bestNode: Node? + var bestScore = Int.min + var truncated = false + while head < frontier.count { + // A wall clock budget bounds the WHOLE walk: attribute reads on + // already queued nodes are IPC calls too, not just child reads. + if shouldStop() { + truncated = true + break + } + if visited >= maxNodes { + truncated = true + break + } + let (node, depth) = frontier[head] + head += 1 + visited += 1 + if let value = score(node), value > bestScore { + bestScore = value + bestNode = node + if value >= stopScore { break } + } + if depth >= maxDepth { + // Children are not read past the limit: each read is an IPC call. + truncated = true + continue + } + for child in children(node) { + frontier.append((child, depth + 1)) + } + // Release consumed prefix occasionally so a wide tree stays cheap. + if head > 1024 { + frontier.removeFirst(head) + head = 0 + } + } + return Result(node: bestNode, visited: visited, truncated: truncated) + } +} diff --git a/holmes/holmes/Core/ActionExecutor.swift b/holmes/holmes/Core/ActionExecutor.swift index 7dcc2a7..9c4e1e0 100644 --- a/holmes/holmes/Core/ActionExecutor.swift +++ b/holmes/holmes/Core/ActionExecutor.swift @@ -4,11 +4,25 @@ import AppKit // MARK: - ActionExecutor // Uses macOS Accessibility API to actually control apps on screen. // Requires Accessibility permission (already in entitlements). +// +// Threading: the async entry points are nonisolated, so their blocking AX IPC +// and event posting run on the concurrency pool, never the main thread, and +// they wait with Task.sleep. NSAppleScript is the exception: it is only ever +// executed on the main actor (see runAppleScript). +// +// Honesty: every text entry returns a TextEntryResult. A field whose value can +// be read back is VERIFIED; otherwise the result is "unverified", never a +// silent success. Nothing presses ⌘A unless the caller explicitly asks to +// replace the field's contents. final class ActionExecutor { static let shared = ActionExecutor() private init() {} + /// Pause between synthetic key events so the target app's event queue + /// keeps up with long text. + private static let keyEventPacingNanoseconds: UInt64 = 6_000_000 + // MARK: - Type text into the focused element of the frontmost app /// True when the app's focused AX element accepts text (a text area/field @@ -28,146 +42,111 @@ final class ActionExecutor { return settable.boolValue } - @discardableResult - func typeIntoFocusedField(in app: NSRunningApplication, text: String) -> Bool { - let axApp = AXUIElementCreateApplication(app.processIdentifier) - AXUIElementSetMessagingTimeout(axApp, 1.0) // a stalled app must not freeze Holmes for the 6 s default per call - - // Find focused UI element - var focusedRef: CFTypeRef? - guard AXUIElementCopyAttributeValue(axApp, kAXFocusedUIElementAttribute as CFString, &focusedRef) == .success, - let focused = focusedRef - else { - // Try to focus the main window's text area first - return typeViaKeyboard(text: text) + /// Sets the focused field's value through Accessibility (verified by reading + /// it back), or types it with keyboard events when the value isn't settable. + func typeIntoFocusedField(in app: NSRunningApplication, text: String) async -> TextEntryResult { + guard let element = focusedElement(of: app.processIdentifier) else { + return await typeViaKeyboard(text: text, verifyIn: nil) } - let element = focused as! AXUIElement - - // Check if it's settable var settable: DarwinBoolean = false AXUIElementIsAttributeSettable(element, kAXValueAttribute as CFString, &settable) - - if settable.boolValue { - // Set value directly (fastest, works for most fields) - let result = AXUIElementSetAttributeValue(element, kAXValueAttribute as CFString, text as CFTypeRef) - if result == .success { - return true - } + if settable.boolValue, + AXUIElementSetAttributeValue(element, kAXValueAttribute as CFString, text as CFTypeRef) == .success { + if TextEntryVerifier.fieldValue(Self.stringValue(of: element), contains: text) { return .verified } + // Typing now could enter the text twice if the set did land. + return .unverified("the field accepted the text but did not report it back") } - // Fallback: simulate keyboard typing - return typeViaKeyboard(text: text) + return await typeViaKeyboard(text: text, verifyIn: element) } // MARK: - Click a button by label in the frontmost app - @discardableResult - func clickButton(label: String, in app: NSRunningApplication) -> Bool { + /// Roles a "press the control named X" request may target. + private static let pressableRoles: Set = [ + kAXButtonRole as String, kAXMenuButtonRole as String, kAXPopUpButtonRole as String, + kAXCheckBoxRole as String, kAXRadioButtonRole as String, kAXMenuItemRole as String, "AXLink" + ] + + /// Presses the best matching control (exact, then case insensitive, then + /// substring across title/description/identifier/placeholder; help text + /// only when it equals the label). The commit gate runs on the MATCHED + /// control: unless `allowCommit`, a send/submit class control is not + /// pressed and `.needsConfirmation` names it. `.pressed` only when AXPress + /// itself reported success. Bounded tree walk with blocking IPC: call it + /// OFF the main thread. + func pressControl(label: String, in app: NSRunningApplication, allowCommit: Bool) -> AXPressOutcome { let axApp = AXUIElementCreateApplication(app.processIdentifier) AXUIElementSetMessagingTimeout(axApp, 1.0) // a stalled app must not freeze Holmes for the 6 s default per call - if let button = findElement(in: axApp, role: kAXButtonRole, label: label) { - AXUIElementPerformAction(button, kAXPressAction as CFString) - return true + guard let button = findElement(in: axApp, roles: Self.pressableRoles, label: label) else { return .notFound } + let names = Self.names(of: button) + let matched = names.visibleName.isEmpty ? label : names.visibleName + if CommitControlGate.pressNeedsConfirmation(requested: label, matched: names, userConfirmed: allowCommit) { + return .needsConfirmation(matched: matched) + } + let result = AXUIElementPerformAction(button, kAXPressAction as CFString) + guard result == .success else { + print("[Holmes] AXPress on “\(label)” failed: AXError \(result.rawValue)") + return .failed(code: result.rawValue) } - return false + return .pressed(matched: matched) } // MARK: - Find and focus a text field in an app, then type - @discardableResult - func focusAndType(in app: NSRunningApplication, fieldHint: String? = nil, text: String) -> Bool { + /// Nonisolated async: runs on the concurrency pool, never the main thread, + /// and waits for focus with Task.sleep instead of blocking a thread. + func focusAndType(in app: NSRunningApplication, fieldHint: String? = nil, text: String) async -> TextEntryResult { let axApp = AXUIElementCreateApplication(app.processIdentifier) AXUIElementSetMessagingTimeout(axApp, 1.0) // a stalled app must not freeze Holmes for the 6 s default per call - // Try to find a text area / text field - let roles = [kAXTextAreaRole, kAXTextFieldRole] - for role in roles { - if let field = findElement(in: axApp, role: role, label: fieldHint) { - // Focus it - AXUIElementSetAttributeValue(field, kAXFocusedAttribute as CFString, true as CFTypeRef) - // Small delay for focus to settle - Thread.sleep(forTimeInterval: 0.1) - // Set value - var settable: DarwinBoolean = false - AXUIElementIsAttributeSettable(field, kAXValueAttribute as CFString, &settable) - if settable.boolValue { - AXUIElementSetAttributeValue(field, kAXValueAttribute as CFString, text as CFTypeRef) - return true - } + // One bounded walk that prefers a text area (the body) over a text + // field (a search box) at equal label quality. + if let field = findTextEntryField(in: axApp, hint: fieldHint) { + AXUIElementSetAttributeValue(field, kAXFocusedAttribute as CFString, true as CFTypeRef) + // Small delay for focus to settle, without blocking a thread. + try? await Task.sleep(nanoseconds: 100_000_000) + guard !Task.isCancelled else { return .failed("Stopped.") } + var settable: DarwinBoolean = false + AXUIElementIsAttributeSettable(field, kAXValueAttribute as CFString, &settable) + if settable.boolValue, + AXUIElementSetAttributeValue(field, kAXValueAttribute as CFString, text as CFTypeRef) == .success { + return TextEntryVerifier.fieldValue(Self.stringValue(of: field), contains: text) + ? .verified + : .unverified("the field accepted the text but did not report it back") } } // Fallback to clipboard paste - return pasteText(text, into: app) + return await pasteText(text, into: app) } // MARK: - Paste via clipboard (most reliable cross-app method) - func pasteText(_ text: String, into app: NSRunningApplication) -> Bool { - // Save current clipboard - let pasteboard = NSPasteboard.general - let previousContents = pasteboard.string(forType: .string) - - // Set our text - pasteboard.clearContents() - pasteboard.setString(text, forType: .string) - - // Bring app to front and simulate Cmd+A (select all) then paste + /// Activates the app and pastes at the cursor (never select all first). + func pasteText(_ text: String, into app: NSRunningApplication) async -> TextEntryResult { app.activate() - Thread.sleep(forTimeInterval: 0.15) - - // Simulate Cmd+V - let src = CGEventSource(stateID: .hidSystemState) - let vKeyDown = CGEvent(keyboardEventSource: src, virtualKey: 0x09, keyDown: true) - let vKeyUp = CGEvent(keyboardEventSource: src, virtualKey: 0x09, keyDown: false) - vKeyDown?.flags = .maskCommand - vKeyUp?.flags = .maskCommand - vKeyDown?.post(tap: .cghidEventTap) - vKeyUp?.post(tap: .cghidEventTap) - - // Restore clipboard after short delay - DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { - if let prev = previousContents { - pasteboard.clearContents() - pasteboard.setString(prev, forType: .string) - } - } - return true + try? await Task.sleep(nanoseconds: 150_000_000) + guard !Task.isCancelled else { return .failed("Stopped.") } + return await pasteFromClipboard(text, field: focusedElement(of: app.processIdentifier), replaceExisting: false) } - // MARK: - Send message in a specific app - // MARK: - Main entry point - /// Puts text into the frontmost/target app's message field. + /// Puts text into the target app's message field. Never presses Send. /// For iMessage/Messages: uses AX + CGEvent (no Automation permission required). - /// For Electron apps (Discord, Slack): uses AppleScript. - func sendMessageInApp(_ appName: String, message: String) -> Bool { - let lower = appName.lowercased() - - // iMessage / Messages.app — use AX to find text area, then CGEvent paste - // This avoids needing Automation permission which AppleScript requires. - if lower.contains("messages") { + /// For other apps (Discord, Slack, Teams): AppleScript activation and paste. + /// `replaceExisting` selects all first; only pass true when the caller + /// really means to wipe what is already in the field. + func sendMessageInApp(_ appName: String, message: String, replaceExisting: Bool = false) async -> TextEntryResult { + if appName.lowercased().contains("messages") { guard let app = runningApp(named: appName) ?? runningApp(named: "Messages") else { - return typeViaKeyboard(text: message) + // Typing blind into whatever has focus is not "sending". + return .failed("Messages is not running") } - return pasteIntoMessagesApp(app, message: message) + return await pasteIntoMessagesApp(app, message: message, replaceExisting: replaceExisting) } - - // Electron apps (Discord, Slack, Teams) — clipboard + AppleScript - let safe = message.replacingOccurrences(of: "\\", with: "\\\\") - .replacingOccurrences(of: "\"", with: "\\\"") - let simpleScript = """ -set the clipboard to "\(safe)" -tell application "\(appName)" to activate -delay 0.5 -tell application "System Events" - keystroke "a" using command down - delay 0.1 - keystroke "v" using command down -end tell -""" - return runAppleScript(simpleScript) + return await pasteIntoApp(named: appName, text: message, replaceExisting: replaceExisting) } /// Stages text into the target app at the CURRENT cursor position — activate @@ -175,153 +154,261 @@ end tell /// can run long after the draft's original context: a select-all there could /// replace unrelated content wholesale (e.g. a Google Doc focused in the same /// browser that once showed Gmail). Never presses Send/Return. - func stageTextInApp(_ appName: String, text: String) -> Bool { - let lower = appName.lowercased() + func stageTextInApp(_ appName: String, text: String) async -> TextEntryResult { + await sendMessageInApp(appName, message: text, replaceExisting: false) + } - if lower.contains("messages") { - guard let app = runningApp(named: appName) ?? runningApp(named: "Messages") else { - return typeViaKeyboard(text: text) - } - return pasteIntoMessagesApp(app, message: text, replaceExisting: false) + /// AppleScript path: the clipboard is snapshotted in full, set by the + /// script (message and app name escaped as AppleScript literals), the app is + /// activated, and System Events pastes. The snapshot is restored once the + /// paste is confirmed or after a longer adaptive delay. + private func pasteIntoApp(named appName: String, text: String, replaceExisting: Bool) async -> TextEntryResult { + let pasteboard = NSPasteboard.general + let snapshot = PasteboardSnapshot(capturing: pasteboard) + let prepare = """ + set holmesTargetApp to \(AppleScriptText.literal(appName)) + set the clipboard to \(AppleScriptText.literal(text)) + tell application holmesTargetApp to activate + """ + guard await runAppleScript(prepare) else { + await restore(snapshot, onlyIfChangeCountIs: nil) + return .failed("AppleScript could not put the text on the clipboard or activate \(appName)") } - - let safe = text.replacingOccurrences(of: "\\", with: "\\\\") - .replacingOccurrences(of: "\"", with: "\\\"") - let script = """ -set the clipboard to "\(safe)" -tell application "\(appName)" to activate -delay 0.5 -tell application "System Events" - keystroke "v" using command down -end tell -""" - return runAppleScript(script) + let ownChangeCount = pasteboard.changeCount + try? await Task.sleep(nanoseconds: 500_000_000) + guard !Task.isCancelled else { + await restore(snapshot, onlyIfChangeCountIs: ownChangeCount) + return .failed("Stopped.") + } + let field = runningApp(named: appName).flatMap { focusedElement(of: $0.processIdentifier) } + let before = field.flatMap(Self.stringValue(of:)) + let keystrokes = replaceExisting + ? "keystroke \"a\" using command down\n delay 0.1\n keystroke \"v\" using command down" + : "keystroke \"v\" using command down" + guard await runAppleScript("tell application \"System Events\"\n \(keystrokes)\nend tell") else { + await restore(snapshot, onlyIfChangeCountIs: ownChangeCount) + return .failed("System Events could not paste into \(appName)") + } + return await confirmPaste(text, field: field, before: before, replaced: replaceExisting, + snapshot: snapshot, ownChangeCount: ownChangeCount) } /// AX-based paste for Messages.app — no Automation permission needed. /// `replaceExisting: false` skips the Cmd+A so the paste lands at the cursor. - private func pasteIntoMessagesApp(_ app: NSRunningApplication, message: String, replaceExisting: Bool = true) -> Bool { - // 1. Set clipboard - let pasteboard = NSPasteboard.general - let prev = pasteboard.string(forType: .string) - pasteboard.clearContents() - pasteboard.setString(message, forType: .string) - - // 2. Bring Messages to front + private func pasteIntoMessagesApp(_ app: NSRunningApplication, message: String, replaceExisting: Bool) async -> TextEntryResult { app.activate(options: [.activateIgnoringOtherApps]) - Thread.sleep(forTimeInterval: 0.4) + try? await Task.sleep(nanoseconds: 400_000_000) + guard !Task.isCancelled else { return .failed("Stopped.") } - // 3. Try to AX-focus the text input area let axApp = AXUIElementCreateApplication(app.processIdentifier) AXUIElementSetMessagingTimeout(axApp, 1.0) // a stalled app must not freeze Holmes for the 6 s default per call - if let textArea = findTextAreaDeep(in: axApp) { + var field = findElement(in: axApp, roles: [kAXTextAreaRole as String], label: nil) + if let textArea = field { AXUIElementSetAttributeValue(textArea, kAXFocusedAttribute as CFString, true as CFTypeRef) - Thread.sleep(forTimeInterval: 0.15) + try? await Task.sleep(nanoseconds: 150_000_000) + } else { + field = focusedElement(of: app.processIdentifier) } + return await pasteFromClipboard(message, field: field, replaceExisting: replaceExisting) + } - // 4. Cmd+A to clear any existing draft, then Cmd+V to paste - let src = CGEventSource(stateID: .hidSystemState) - func post(_ key: CGKeyCode, flags: CGEventFlags = []) { - let d = CGEvent(keyboardEventSource: src, virtualKey: key, keyDown: true) - let u = CGEvent(keyboardEventSource: src, virtualKey: key, keyDown: false) - d?.flags = flags; u?.flags = flags - d?.post(tap: .cghidEventTap) - Thread.sleep(forTimeInterval: 0.04) - u?.post(tap: .cghidEventTap) - Thread.sleep(forTimeInterval: 0.04) + /// CGEvent paste with a full clipboard snapshot. + private func pasteFromClipboard(_ text: String, field: AXUIElement?, replaceExisting: Bool) async -> TextEntryResult { + let pasteboard = NSPasteboard.general + let snapshot = PasteboardSnapshot(capturing: pasteboard) + pasteboard.clearContents() + guard pasteboard.setString(text, forType: .string) else { + await restore(snapshot, onlyIfChangeCountIs: nil) + return .failed("couldn't put the text on the clipboard") } + let ownChangeCount = pasteboard.changeCount + let before = field.flatMap(Self.stringValue(of:)) if replaceExisting { - post(0x00, flags: .maskCommand) // Cmd+A (select all in input) + guard await postKey(0x00, flags: .maskCommand) else { // Cmd+A, only when asked + await restore(snapshot, onlyIfChangeCountIs: ownChangeCount) + return .failed("couldn't create keyboard events (is Accessibility granted?)") + } } - post(0x09, flags: .maskCommand) // Cmd+V (paste) + guard await postKey(0x09, flags: .maskCommand) else { // Cmd+V + await restore(snapshot, onlyIfChangeCountIs: ownChangeCount) + return .failed("couldn't create keyboard events (is Accessibility granted?)") + } + return await confirmPaste(text, field: field, before: before, replaced: replaceExisting, + snapshot: snapshot, ownChangeCount: ownChangeCount) + } - // 5. Restore clipboard after a delay - DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { - if let prev { - pasteboard.clearContents() - pasteboard.setString(prev, forType: .string) + /// Polls the field for the pasted text. Confirmed: restore the clipboard + /// now. Unconfirmed: leave the text on the clipboard a while longer (a slow + /// app may still be reading it), then restore, and say it is unverified. + private func confirmPaste(_ text: String, field: AXUIElement?, before: String?, replaced: Bool, + snapshot: PasteboardSnapshot, ownChangeCount: Int) async -> TextEntryResult { + if let field { + let alreadyThere = !replaced && TextEntryVerifier.fieldValue(before, contains: text) + for _ in 0..<15 { + try? await Task.sleep(nanoseconds: 100_000_000) + let value = Self.stringValue(of: field) + if TextEntryVerifier.fieldValue(value, contains: text), !alreadyThere || value != before { + await restore(snapshot, onlyIfChangeCountIs: ownChangeCount) + return .verified + } + if Task.isCancelled { break } } } - return true + let delay = TextEntryVerifier.unconfirmedRestoreDelay(forLength: text.count) + Task.detached(priority: .utility) { [self] in + try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) + await self.restore(snapshot, onlyIfChangeCountIs: ownChangeCount) + } + return .unverified(field == nil + ? "the paste was sent, but the target field does not expose its contents" + : "the paste was sent, but the text did not show up in the field's value") } + /// Restores the user's clipboard unless someone else changed it since + /// Holmes borrowed it (then theirs is newer and must be kept). + @MainActor + private func restore(_ snapshot: PasteboardSnapshot, onlyIfChangeCountIs expected: Int?) { + let pasteboard = NSPasteboard.general + if let expected, pasteboard.changeCount != expected { return } + snapshot.restore(to: pasteboard) + } + + /// NSAppleScript is not thread safe and must only run on the main actor. + /// Scripts here are short (no `delay`); waits happen in Swift. + @MainActor private func runAppleScript(_ source: String) -> Bool { var error: NSDictionary? - if let script = NSAppleScript(source: source) { - let result = script.executeAndReturnError(&error) - if let err = error { - print("[Holmes] AppleScript error: \(err)") - return false - } - print("[Holmes] AppleScript executed — result: \(result.stringValue ?? "ok")") - return true + guard let script = NSAppleScript(source: source) else { return false } + let result = script.executeAndReturnError(&error) + if let err = error { + print("[Holmes] AppleScript error: \(err)") + return false } - return false + print("[Holmes] AppleScript executed — result: \(result.stringValue ?? "ok")") + return true } // MARK: - Helpers - private func typeViaKeyboard(text: String) -> Bool { - let src = CGEventSource(stateID: .hidSystemState) - for char in text.unicodeScalars { - let keyDown = CGEvent(keyboardEventSource: src, virtualKey: 0, keyDown: true) - let keyUp = CGEvent(keyboardEventSource: src, virtualKey: 0, keyDown: false) - keyDown?.keyboardSetUnicodeString(stringLength: 1, unicodeString: [UniChar(char.value)]) - keyUp?.keyboardSetUnicodeString(stringLength: 1, unicodeString: [UniChar(char.value)]) - keyDown?.post(tap: .cghidEventTap) - keyUp?.post(tap: .cghidEventTap) - } + private func postKey(_ key: CGKeyCode, flags: CGEventFlags = []) async -> Bool { + let source = CGEventSource(stateID: .hidSystemState) + guard let down = CGEvent(keyboardEventSource: source, virtualKey: key, keyDown: true), + let up = CGEvent(keyboardEventSource: source, virtualKey: key, keyDown: false) else { return false } + down.flags = flags + up.flags = flags + down.post(tap: .cghidEventTap) + try? await Task.sleep(nanoseconds: 40_000_000) + up.post(tap: .cghidEventTap) + try? await Task.sleep(nanoseconds: 40_000_000) return true } - private func findElement(in element: AXUIElement, role: String, label: String?) -> AXUIElement? { - var roleRef: CFTypeRef? - AXUIElementCopyAttributeValue(element, kAXRoleAttribute as CFString, &roleRef) - if let r = roleRef as? String, r == role { - if let label { - var titleRef: CFTypeRef? - AXUIElementCopyAttributeValue(element, kAXTitleAttribute as CFString, &titleRef) - if let title = titleRef as? String, title.lowercased().contains(label.lowercased()) { - return element - } - } else { - return element + /// Types with keyboard events carrying whole UTF-16 chunks (surrogate pairs + /// and grapheme clusters never split), paced so fast text isn't dropped. + /// Verified only when `element` exposes its value and it contains the text. + private func typeViaKeyboard(text: String, verifyIn element: AXUIElement?) async -> TextEntryResult { + let chunks = KeyboardText.utf16Chunks(text) + guard !chunks.isEmpty else { return .verified } + let source = CGEventSource(stateID: .hidSystemState) + for chunk in chunks { + guard !Task.isCancelled else { return .failed("Stopped before all of the text was typed.") } + guard let down = CGEvent(keyboardEventSource: source, virtualKey: 0, keyDown: true), + let up = CGEvent(keyboardEventSource: source, virtualKey: 0, keyDown: false) else { + return .failed("couldn't create keyboard events (is Accessibility granted?)") } + down.keyboardSetUnicodeString(stringLength: chunk.count, unicodeString: chunk) + up.keyboardSetUnicodeString(stringLength: chunk.count, unicodeString: chunk) + down.post(tap: .cghidEventTap) + try? await Task.sleep(nanoseconds: Self.keyEventPacingNanoseconds) + up.post(tap: .cghidEventTap) + try? await Task.sleep(nanoseconds: Self.keyEventPacingNanoseconds) } - - var childrenRef: CFTypeRef? - guard AXUIElementCopyAttributeValue(element, kAXChildrenAttribute as CFString, &childrenRef) == .success, - let children = childrenRef as? [AXUIElement] - else { return nil } - - for child in children { - if let found = findElement(in: child, role: role, label: label) { - return found + if let element { + for _ in 0..<5 { + if TextEntryVerifier.fieldValue(Self.stringValue(of: element), contains: text) { return .verified } + try? await Task.sleep(nanoseconds: 100_000_000) } } - return nil + return .unverified(element == nil + ? "keystrokes were sent, but no focused field could be read back" + : "keystrokes were sent, but the text did not show up in the field's value") + } + + private func focusedElement(of pid: pid_t) -> AXUIElement? { + let axApp = AXUIElementCreateApplication(pid) + AXUIElementSetMessagingTimeout(axApp, 1.0) + var focusedRef: CFTypeRef? + guard AXUIElementCopyAttributeValue(axApp, kAXFocusedUIElementAttribute as CFString, &focusedRef) == .success, + let focused = focusedRef, CFGetTypeID(focused) == AXUIElementGetTypeID() else { return nil } + let element = focused as! AXUIElement + AXUIElementSetMessagingTimeout(element, 1.0) + return element } - private func findTextAreaDeep(in element: AXUIElement, depth: Int = 0) -> AXUIElement? { - guard depth < 12 else { return nil } + private static func stringValue(of element: AXUIElement) -> String? { + stringAttribute(element, kAXValueAttribute as String) + } - var roleRef: CFTypeRef? - AXUIElementCopyAttributeValue(element, kAXRoleAttribute as CFString, &roleRef) - if let role = roleRef as? String, role == kAXTextAreaRole as String { - return element + /// Wall clock budget for one element lookup, on top of the depth and + /// element count limits in AXElementSearch. + private static let searchTimeBudget: TimeInterval = 2.5 + + /// Bounded breadth first lookup. With a label, the best ranked match wins + /// (exact title/description/help/identifier/placeholder beats case + /// insensitive beats substring); without one, the first element of a role. + private func findElement(in root: AXUIElement, roles: Set, label: String?) -> AXUIElement? { + findBest(in: root, stopScore: label == nil ? 1 : AXLabelMatch.exact.rawValue) { role, names in + guard roles.contains(role) else { return nil } + guard let label else { return 1 } + return AXElementSearch.labelMatch(label, in: names())?.rawValue } + } - var childrenRef: CFTypeRef? - guard AXUIElementCopyAttributeValue(element, kAXChildrenAttribute as CFString, &childrenRef) == .success, - let children = childrenRef as? [AXUIElement] - else { return nil } + /// The field ax_type should fill: text areas beat text fields. + private func findTextEntryField(in root: AXUIElement, hint: String?) -> AXUIElement? { + findBest(in: root, stopScore: AXElementSearch.textEntryStopScore(hasHint: hint != nil)) { role, names in + AXElementSearch.textEntryScore(role: role, hint: hint, names: names) + } + } - for child in children { - if let found = findTextAreaDeep(in: child, depth: depth + 1) { - return found - } + /// Bounded walk scoring each element by role and (lazily read) names. + private func findBest(in root: AXUIElement, stopScore: Int, + score: (String, () -> AXNames) -> Int?) -> AXUIElement? { + let deadline = Date().addingTimeInterval(Self.searchTimeBudget) + let result = AXElementSearch.best( + from: root, + stopScore: stopScore, + shouldStop: { Date() >= deadline }, + children: { element in + guard Date() < deadline else { return [] } + var childrenRef: CFTypeRef? + guard AXUIElementCopyAttributeValue(element, kAXChildrenAttribute as CFString, &childrenRef) == .success, + let children = childrenRef as? [AXUIElement] else { return [] } + for child in children { AXUIElementSetMessagingTimeout(child, 1.0) } + return children + }, + score: { element in + guard let role = Self.stringAttribute(element, kAXRoleAttribute as String) else { return nil } + return score(role) { Self.names(of: element) } + }) + if result.node == nil, result.truncated { + print("[Holmes] AX lookup stopped at its limit after \(result.visited) elements") } - return nil + return result.node + } + + private static func names(of element: AXUIElement) -> AXNames { + AXNames(title: stringAttribute(element, kAXTitleAttribute as String), + description: stringAttribute(element, kAXDescriptionAttribute as String), + help: stringAttribute(element, kAXHelpAttribute as String), + identifier: stringAttribute(element, "AXIdentifier"), + placeholder: stringAttribute(element, kAXPlaceholderValueAttribute as String)) + } + + private static func stringAttribute(_ element: AXUIElement, _ attribute: String) -> String? { + var ref: CFTypeRef? + guard AXUIElementCopyAttributeValue(element, attribute as CFString, &ref) == .success else { return nil } + return ref as? String } func runningApp(named name: String) -> NSRunningApplication? { diff --git a/holmes/holmes/Core/ApprovalQueue.swift b/holmes/holmes/Core/ApprovalQueue.swift new file mode 100644 index 0000000..2c3bfa7 --- /dev/null +++ b/holmes/holmes/Core/ApprovalQueue.swift @@ -0,0 +1,248 @@ +import Foundation + +// Result of a user approving/dismissing an agent tool call. +enum AgentDecision { + case approved(text: String) // `text` carries any edits the user made in the preview + case dismissed + /// Nobody answered an unattended (autonomous) approval before its deadline. + /// Callers treat it like a dismissal but report it as a timeout. + case timedOut +} + +/// Deadline policy for approvals raised by work nobody is watching. +enum ApprovalScope { + /// When set, every approval raised in this task resolves `.timedOut` after + /// this many seconds without an answer. Autonomous playbook runs set it; a + /// user initiated request leaves it nil and may keep waiting. + @TaskLocal static var unattendedTimeout: TimeInterval? + + /// The deadline autonomous runs use. A static var so tests can shorten it. + nonisolated(unsafe) static var defaultUnattendedTimeout: TimeInterval = 120 + + static let timedOutMessage = "Timed out waiting for approval" +} + +/// Lets a tool call learn that one of ITS approvals timed out, so the model is +/// told "timed out waiting for approval" instead of "the user declined". +final class ApprovalTimeoutFlag: @unchecked Sendable { + private let lock = NSLock() + private var flagged = false + func markTimedOut() { lock.lock(); flagged = true; lock.unlock() } + var timedOut: Bool { lock.lock(); defer { lock.unlock() }; return flagged } +} + +enum ApprovalTimeoutTracking { + @TaskLocal static var flag: ApprovalTimeoutFlag? + + /// Runs `operation` with a fresh flag and reports whether any approval + /// raised inside it timed out. + static func run(_ operation: () async -> T) async -> (result: T, timedOut: Bool) { + let flag = ApprovalTimeoutFlag() + let result = await $flag.withValue(flag) { await operation() } + return (result, flag.timedOut) + } +} + +// MARK: - ApprovalQueue +// +// FIFO of approval requests. Exactly one is presented at a time; a second +// request arriving while the first is showing WAITS instead of dismissing it +// (which a waiting run used to read as "declined"). When the current one +// resolves, the next is presented. A cancelled request leaves the queue (or +// the screen) without touching anyone else's decision. + +@MainActor +final class ApprovalQueue { + private struct Entry { + let id: UUID + let item: Item + let resolve: (AgentDecision) -> Void + var deadline: Task? + } + + private var current: Entry? + private var waiting: [Entry] = [] + + /// Presents `item` (a new current request), or hides the card with nil. + var onPresent: (Item?) -> Void = { _ in } + /// Called before a timed out request resolves, for user visible status. + var onTimeout: (Item) -> Void = { _ in } + + init() {} + + var currentID: UUID? { current?.id } + var currentItem: Item? { current?.item } + var queuedCount: Int { waiting.count } + var isIdle: Bool { current == nil && waiting.isEmpty } + + func contains(_ id: UUID) -> Bool { + current?.id == id || waiting.contains { $0.id == id } + } + + /// Suspends until the request is approved, dismissed, cancelled (the + /// awaiting task) or timed out. + func decide(id: UUID, item: Item, timeout: TimeInterval?) async -> AgentDecision { + guard !Task.isCancelled else { return .dismissed } + return await withTaskCancellationHandler { + await withCheckedContinuation { (continuation: CheckedContinuation) in + guard !Task.isCancelled else { + continuation.resume(returning: .dismissed) + return + } + enqueue(id: id, item: item, timeout: timeout) { continuation.resume(returning: $0) } + } + } onCancel: { + Task { @MainActor in self.cancel(id: id) } + } + } + + func enqueue(id: UUID, item: Item, timeout: TimeInterval?, resolve: @escaping (AgentDecision) -> Void) { + var entry = Entry(id: id, item: item, resolve: resolve) + if let timeout, timeout.isFinite { + // The deadline runs from ENQUEUE: an unattended request waiting + // behind a user's card still frees its playbook slot on time. + let nanoseconds = UInt64(max(0, timeout) * 1_000_000_000) + entry.deadline = Task { @MainActor [weak self] in + try? await Task.sleep(nanoseconds: nanoseconds) + guard !Task.isCancelled else { return } + self?.timeOut(id: id) + } + } + if current == nil { + current = entry + onPresent(item) + } else { + waiting.append(entry) + } + } + + /// Resolves the presented request (Approve / Dismiss) and presents the next. + func resolveCurrent(_ decision: AgentDecision) { + guard let entry = current else { return } + finish(entry, decision) + } + + /// Removes a request wherever it is, resolving it `.dismissed`. + func cancel(id: UUID) { + resolve(id: id, .dismissed) + } + + /// Dismisses everything, current first, then the queue in order. + func dismissAll() { + let all = (current.map { [$0] } ?? []) + waiting + waiting.removeAll() + current = nil + for entry in all { + entry.deadline?.cancel() + entry.resolve(.dismissed) + } + onPresent(nil) + } + + private func timeOut(id: UUID) { + guard let entry = current?.id == id ? current : waiting.first(where: { $0.id == id }) else { return } + onTimeout(entry.item) + resolve(id: id, .timedOut) + } + + private func resolve(id: UUID, _ decision: AgentDecision) { + if let entry = current, entry.id == id { + finish(entry, decision) + } else if let index = waiting.firstIndex(where: { $0.id == id }) { + let entry = waiting.remove(at: index) + entry.deadline?.cancel() + entry.resolve(decision) + } + } + + private func finish(_ entry: Entry, _ decision: AgentDecision) { + entry.deadline?.cancel() + // Advance BEFORE resuming the waiter so a caller that immediately asks + // again queues behind the next request instead of jumping it. + if waiting.isEmpty { + current = nil + onPresent(nil) + } else { + let next = waiting.removeFirst() + current = next + onPresent(next.item) + } + entry.resolve(decision) + } +} + +// MARK: - ApprovalCardArbiter +// +// ONE floating card is shared by queued approvals (decide) and direct proposals +// (command bar results, meeting joins). The arbiter remembers which kind is on +// screen so neither can orphan the other: +// • a direct proposal arriving over a queued approval PARKS that approval; it +// is shown again as soon as the direct card closes, so its run never hangs; +// • a queue change (a timeout, a resolve) only ever replaces or hides the +// card when that card IS the queue's approval, never a direct card or a +// draft the user is looking at. + +@MainActor +final class ApprovalCardArbiter { + enum Showing: Equatable { + case none + case approval(UUID) + case direct(UUID) + } + + private(set) var showing: Showing = .none + let queue: ApprovalQueue + private let idOf: (Item) -> UUID + + /// Puts an item on the card. + var show: (Item) -> Void = { _ in } + /// Closes the card after the approval it showed went away. + var hide: () -> Void = {} + + init(queue: ApprovalQueue, id: @escaping (Item) -> UUID) { + self.queue = queue + self.idOf = id + queue.onPresent = { [weak self] item in self?.queuePresented(item) } + } + + /// The queue head's id while that head is the card on screen. + var showingApprovalID: UUID? { + guard case .approval(let id) = showing, id == queue.currentID else { return nil } + return id + } + + var isShowingDirect: Bool { + if case .direct = showing { return true } + return false + } + + private func queuePresented(_ item: Item?) { + // A direct card is on screen: the head waits (parked) until it closes. + if isShowingDirect { return } + if let item { + showing = .approval(idOf(item)) + show(item) + } else if case .approval = showing { + // Only close the card when it was the approval that just went away. + showing = .none + hide() + } + } + + /// Shows a card that is not part of the approval queue. + func proposeDirect(_ item: Item) { + showing = .direct(idOf(item)) + show(item) + } + + /// The direct card closed: bring back a parked approval, if any. + func directClosed() { + guard isShowingDirect else { return } + if let head = queue.currentItem { + showing = .approval(idOf(head)) + show(head) + } else { + showing = .none + } + } +} diff --git a/holmes/holmes/Core/AutonomousRunTally.swift b/holmes/holmes/Core/AutonomousRunTally.swift new file mode 100644 index 0000000..4cc1321 --- /dev/null +++ b/holmes/holmes/Core/AutonomousRunTally.swift @@ -0,0 +1,78 @@ +import Foundation + +// MARK: - AutonomousRunTally +// +// Honest accounting for an autonomous plan. A step that failed even after its +// retry is skipped so one flaky control cannot kill the whole task, but a +// skipped step is REQUIRED work that did not happen: the run must finish as a +// failure that names the step, never as a plain "done". + +struct AutonomousRunTally { + struct Skipped: Equatable { + let summary: String + let reason: String + } + + let plannedSteps: Int + private(set) var completed = 0 + private(set) var skipped: [Skipped] = [] + /// Steps that ran but whose effect could not be confirmed. + private(set) var unverified: [Skipped] = [] + + init(plannedSteps: Int) { + self.plannedSteps = plannedSteps + } + + mutating func recordCompleted(_ count: Int = 1) { + completed += max(0, count) + } + + mutating func recordSkipped(summary: String, reason: String) { + skipped.append(Skipped(summary: summary, reason: reason)) + } + + mutating func recordUnverified(summary: String, reason: String) { + unverified.append(Skipped(summary: summary, reason: reason)) + } + + /// No required step was skipped. Unverified steps do not fail a run, but + /// they keep the note from reading as a plain "done". + var succeeded: Bool { skipped.isEmpty } + var isFullyVerified: Bool { skipped.isEmpty && unverified.isEmpty } + + /// The run's outcome note: "done", or a failure that names what was skipped. + var note: String { + guard let first = skipped.first else { + guard let firstUnverified = unverified.first else { return "done" } + let count = unverified.count + let steps = count == 1 ? "1 step" : "\(count) steps" + let reason = Self.clip(firstUnverified.reason, 120) + return "Done, but \(steps) could not be verified, starting with “\(Self.clip(firstUnverified.summary, 60))”" + + (reason.isEmpty ? "" : " (\(reason))") + } + let count = skipped.count + let steps = count == 1 ? "1 required step was" : "\(count) required steps were" + let reason = Self.clip(first.reason, 120) + return "Failed: \(steps) skipped, starting with “\(Self.clip(first.summary, 60))”" + + (reason.isEmpty ? "" : " (\(reason))") + } + + func notifyBody(undoAvailable: Bool) -> String { + let undo = undoAvailable ? " Undo is available in the Holmes panel." : "" + guard !succeeded else { + guard let firstUnverified = unverified.first else { + return "\(completed) of \(plannedSteps) steps completed.\(undo)" + } + return "\(completed) of \(plannedSteps) steps completed, \(unverified.count) unverified " + + "(“\(Self.clip(firstUnverified.summary, 50))”). Check them.\(undo)" + } + let count = skipped.count + return "Failed: \(completed) of \(plannedSteps) steps completed, \(count) skipped " + + "(“\(Self.clip(skipped[0].summary, 50))”).\(undo)" + } + + private static func clip(_ text: String, _ limit: Int) -> String { + let flat = text.replacingOccurrences(of: "\n", with: " ").trimmingCharacters(in: .whitespacesAndNewlines) + return flat.count > limit ? String(flat.prefix(limit)) + "…" : flat + } +} diff --git a/holmes/holmes/Core/Autonomy/ActionPlanner.swift b/holmes/holmes/Core/Autonomy/ActionPlanner.swift index da2a7bb..aae75f2 100644 --- a/holmes/holmes/Core/Autonomy/ActionPlanner.swift +++ b/holmes/holmes/Core/Autonomy/ActionPlanner.swift @@ -73,6 +73,12 @@ struct ActionPlan { @MainActor enum ActionPlanner { + /// A plan, or the user facing reason there is none. + enum PlanResult { + case plan(ActionPlan) + case failure(String) + } + /// Hard cap on plan length. The prompt asks for 2–6 steps; anything the /// model returns beyond this is dropped rather than trusted — a 40-step /// "plan" is a wandering agent, not a plan. @@ -83,12 +89,13 @@ enum ActionPlanner { private static let screenTextCap = 4000 /// Asks the local model to produce an ordered plan for accomplishing the - /// playbook's goal given the current context + recent memory. Returns nil - /// on any failure (Ollama not ready, transport, unparseable or empty plan) - /// — callers treat nil as "don't act". + /// playbook's goal given the current context + recent memory. An unreadable + /// reply gets ONE short repair request; any failure (Ollama not ready, + /// transport, unparseable or empty plan) comes back as a user facing + /// reason, also shown on the owning WorkActivity, and callers don't act. /// /// This does NOT execute — it only plans. - static func plan(playbookId: String, goal: String, context: PlaybookContext) async -> ActionPlan? { + static func plan(playbookId: String, goal: String, context: PlaybookContext) async -> PlanResult { // Recent memory: a compact digest so the plan knows what the user has // been working on (e.g. "reply to Ada's thread" resolves to the thread // Holmes just watched them read). MemoryStore is an actor; digest("") @@ -119,24 +126,59 @@ enum ActionPlanner { schema: planSchema, priority: .agent ) + } catch is CancellationError { + return .failure("Stopped.") } catch { print("[Holmes] ActionPlanner: plan request failed — \(error.localizedDescription)") - return nil + return failure("Couldn't plan this automation: \(error.localizedDescription)") } - guard let steps = parseSteps(raw: raw), !steps.isEmpty else { - print("[Holmes] ActionPlanner: unparseable or empty plan for \(playbookId)") - return nil + let parsed = await ModelJSONRepair.parse( + raw, what: "plan", + attempt: { reply in parsePlan(raw: reply) }, + repair: { broken in + progress("Repairing an unreadable plan") + return try await OllamaClient.shared.complete( + system: "You fix malformed JSON. Reply with exactly one valid JSON object.", + user: ModelJSONRepair.repairPrompt(for: broken, shape: planShape), + maxTokens: 2048, + asJSON: true, + schema: planSchema, + priority: .agent) + }) + guard let (steps, rationale) = parsed.value else { + let reason = parsed.failure ?? "The local model's plan was unreadable." + print("[Holmes] ActionPlanner: \(reason) (playbook \(playbookId))") + return failure(reason) + } + guard !steps.isEmpty else { + return failure("The local model's plan had no steps to run.") } + if parsed.repaired { print("[Holmes] ActionPlanner: plan for \(playbookId) parsed after one repair") } - return ActionPlan( + return .plan(ActionPlan( goal: goal, steps: steps, knownAddresses: knownAddresses, - rationale: parseRationale(raw: raw) - ) + rationale: rationale + )) + } + + /// Records a planning failure where the user can see it (notch / panel) + /// instead of only the console. + private static func failure(_ reason: String) -> PlanResult { + progress(reason) + return .failure(reason) + } + + private static func progress(_ detail: String) { + guard let id = WorkActivityScope.id else { return } + WorkActivityCenter.shared.update(id, phase: .working, detail: detail) } + /// The reply shape restated for the repair request. + private static let planShape = #"{"steps":[{"action":"verb","input":{},"backend":"computer","reversible":true,"summary":"one line"}],"rationale":"short paragraph"}"# + // MARK: - Prompts /// The JSON schema Ollama's grammar enforces on the reply. It mirrors the @@ -243,32 +285,18 @@ enum ActionPlanner { // MARK: - Defensive parsing - /// The reply should be exactly the described object, but strip the classic - /// failure modes anyway (code fences, leading prose before the brace) so a - /// degraded reply still parses instead of nil-ing the whole plan. - private static func jsonObject(from raw: String) -> [String: Any]? { - var text = raw.trimmingCharacters(in: .whitespacesAndNewlines) - if text.hasPrefix("```") { - // ```json\n{...}\n``` → keep the middle. - text = text - .replacingOccurrences(of: "```json", with: "") - .replacingOccurrences(of: "```", with: "") - .trimmingCharacters(in: .whitespacesAndNewlines) - } - // Tolerate stray prose around the object by slicing brace-to-brace. - if let first = text.firstIndex(of: "{"), let last = text.lastIndex(of: "}"), first < last { - text = String(text[first...last]) - } - guard let data = text.data(using: .utf8), - let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] + /// The reply should be exactly the described object, but a degraded reply + /// (code fences, prose before or after, braces in that prose) still parses: + /// ModelJSON finds the first balanced object that carries a steps array. + private static func parsePlan(raw: String) -> (steps: [PlannedStep], rationale: String)? { + guard let object = ModelJSON.firstObject(in: raw, where: { $0["steps"] is [Any] }), + let steps = parseSteps(object: object) else { return nil } - return object + return (steps, (object["rationale"] as? String) ?? "") } - private static func parseSteps(raw: String) -> [PlannedStep]? { - guard let object = jsonObject(from: raw), - let items = object["steps"] as? [[String: Any]] - else { return nil } + private static func parseSteps(object: [String: Any]) -> [PlannedStep]? { + guard let items = object["steps"] as? [[String: Any]] else { return nil } var steps: [PlannedStep] = [] for item in items.prefix(maxSteps) { @@ -318,7 +346,4 @@ enum ActionPlanner { return backend.isEmpty ? "computer" : backend } - private static func parseRationale(raw: String) -> String { - (jsonObject(from: raw)?["rationale"] as? String) ?? "" - } } diff --git a/holmes/holmes/Core/Autonomy/AutonomousActionRunner.swift b/holmes/holmes/Core/Autonomy/AutonomousActionRunner.swift index 0d44276..e7a4cc6 100644 --- a/holmes/holmes/Core/Autonomy/AutonomousActionRunner.swift +++ b/holmes/holmes/Core/Autonomy/AutonomousActionRunner.swift @@ -62,6 +62,9 @@ final class AutonomousActionRunner { @ObservationIgnored private var notificationPermissionRequested = false @ObservationIgnored private var runTask: Task? @ObservationIgnored private var runActivityID: UUID? + /// This run's own computer control session: its kill switch and screenshot + /// are never shared with (or reset by) any other run. + @ObservationIgnored private var runToken: ComputerUseRunToken? enum RunOutcome: Equatable { case succeeded @@ -88,14 +91,14 @@ final class AutonomousActionRunner { func cancelCurrentRun() { guard let runTask else { return } runTask.cancel() - ComputerUseEngine.shared.cancelRun() + if let runToken { ComputerUseEngine.shared.cancelRun(runToken) } } private var workWasCancelled: Bool { Task.isCancelled || WorkActivityScope.id.map { !WorkActivityCenter.shared.isActive($0) } == true } - private var shouldStopRun: Bool { workWasCancelled || ComputerUseEngine.shared.isCancelled } + private var shouldStopRun: Bool { workWasCancelled || ComputerUseEngine.shared.isCancelled(runToken) } private func progress(_ detail: String, phase: WorkActivityCenter.Phase = .working, fraction: Double? = nil) { guard let id = WorkActivityScope.id else { return } @@ -149,10 +152,16 @@ final class AutonomousActionRunner { // Own the single-flight slot before the first preflight/MCP await. isRunning = true runActivityID = id + // Fresh actuator session owned by this run alone: a new kill switch and + // no stale screenshot, without resetting any other run in flight. + let token = ComputerUseEngine.shared.beginRun() + runToken = token WorkActivityCenter.shared.update(id, phase: .preparing, detail: "Checking the plan") let task = Task { @MainActor in await WorkActivityScope.$id.withValue(id) { - await self.execute(plan, playbookId: playbookId, level: level) + await ComputerUseRunScope.$token.withValue(token) { + await self.execute(plan, playbookId: playbookId, level: level) + } } } runTask = task @@ -165,6 +174,8 @@ final class AutonomousActionRunner { defer { runTask = nil runActivityID = nil + runToken = nil + ComputerUseEngine.shared.endRun(token) isRunning = false } let result = await withTaskCancellationHandler { @@ -175,9 +186,9 @@ final class AutonomousActionRunner { let outcome: RunOutcome = Task.isCancelled || !WorkActivityCenter.shared.isActive(id) ? .cancelled : result if inheritedID == nil { WorkActivityCenter.shared.finish(id, outcome: outcome.activityOutcome, - summary: outcome.succeeded ? "Completed: \(shorten(plan.goal, max: 100))" : outcome.summary) + summary: outcome.succeeded ? successSummary(plan, max: 100) : outcome.summary) } - statusLine = outcome.succeeded ? "Done: \(shorten(plan.goal, max: 80))" : outcome.summary + statusLine = outcome.succeeded ? successSummary(plan, max: 80) : outcome.summary return outcome } @@ -257,9 +268,6 @@ final class AutonomousActionRunner { guard !workWasCancelled else { return .cancelled } AutonomyGate.recordAct(playbookId: playbookId) // consume rate budget once per started run statusLine = "Running: \(shorten(plan.goal, max: 80))" - // Fresh actuator session: clears a stale ⌘⌥Esc flag and the stale - // screenshot so nothing maps coordinates against an old frame. - ComputerUseEngine.shared.beginRun() ScreenGlowController.shared.set(state: .thinking, origin: PlaybookEngine.shared.glowOrigin) // Speak the opening intent — "On it — ." — so the run announces @@ -271,9 +279,15 @@ final class AutonomousActionRunner { // the run (BackendRouter's userConfirmed contract names this exact case). let wholePlanApproved: Bool if level == .confirm { - guard await approveWholePlan(plan, playbookId: playbookId, composioApps: composioApps) else { + switch await approveWholePlan(plan, playbookId: playbookId, composioApps: composioApps) { + case .approved: + break + case .declined: return await finishRun(plan: plan, playbookId: playbookId, executed: 0, succeeded: false, note: "declined", notifyBody: nil) + case .timedOut: + return await finishApprovalTimeout(plan: plan, playbookId: playbookId, executed: 0, + what: "the plan") } wholePlanApproved = true } else { @@ -281,7 +295,9 @@ final class AutonomousActionRunner { } var executedCount = 0 - var failedStepCount = 0 // steps that failed even after a retry — skipped, not fatal + // Steps that failed even after a retry are skipped, not fatal, but a + // skipped step is required work that did not happen: the tally fails the run. + var tally = AutonomousRunTally(plannedSteps: plan.steps.count) undoActionsForLastRun = [] for segment in Self.segmentize(plan.steps) { @@ -298,10 +314,9 @@ final class AutonomousActionRunner { // for itself. (.confirm already approved the whole plan.) var confirmed = wholePlanApproved if !confirmed, BackendRouter.requiresConfirmation(step, composioApps: composioApps) { - guard await approveStep(step) else { - return await finishRun(plan: plan, playbookId: playbookId, executed: executedCount, - succeeded: false, note: "step declined", - notifyBody: "You declined “\(shorten(step.summary, max: 60))”. The run stopped there.") + if let stop = await stopUnlessApproved(await approveStep(step), step: step, plan: plan, + playbookId: playbookId, executed: executedCount) { + return stop } confirmed = true } @@ -324,10 +339,9 @@ final class AutonomousActionRunner { // pre-check missed (dispatch-time knowledge). Honor its // protocol: raise the card now and retry exactly once. if !result.ok, result.text.hasPrefix(BackendRouter.confirmMarker), !confirmed { - guard await approveStep(step) else { - return await finishRun(plan: plan, playbookId: playbookId, executed: executedCount, - succeeded: false, note: "step declined", - notifyBody: "You declined “\(shorten(step.summary, max: 60))”. The run stopped there.") + if let stop = await stopUnlessApproved(await approveStep(step), step: step, plan: plan, + playbookId: playbookId, executed: executedCount) { + return stop } result = await BackendRouter.run(step, composioApps: composioApps, userConfirmed: true) if shouldStopRun { @@ -348,7 +362,7 @@ final class AutonomousActionRunner { let retrySafe = !BackendRouter.requiresConfirmation(step, composioApps: composioApps) && step.action != "type" && step.action != "applescript" && step.action != "ax_type" if !result.ok, !retrySafe { - failedStepCount += 1 + tally.recordSkipped(summary: step.summary, reason: result.text) await logExecutedStep(step, playbookId: playbookId, level: level, via: "router", ok: false, confirmed: confirmed, note: result.text) continue @@ -363,14 +377,17 @@ final class AutonomousActionRunner { if retry.ok { result = retry } else { - failedStepCount += 1 + tally.recordSkipped(summary: step.summary, reason: retry.text) await logExecutedStep(step, playbookId: playbookId, level: level, via: "router", ok: false, confirmed: confirmed, note: retry.text) continue } } await logExecutedStep(step, playbookId: playbookId, level: level, via: "router", - ok: true, confirmed: confirmed, note: nil) + ok: true, confirmed: confirmed, note: result.unverified ? result.text : nil) + if result.unverified { + tally.recordUnverified(summary: step.summary, reason: result.text) + } statusLine = shorten(result.text, max: 100) collectUndo(for: step, routerUndo: result.undo) executedCount += 1 @@ -382,10 +399,9 @@ final class AutonomousActionRunner { // still re-confirm the actual send at execution time. if !wholePlanApproved { for step in steps where BackendRouter.requiresConfirmation(step, composioApps: composioApps) { - guard await approveStep(step) else { - return await finishRun(plan: plan, playbookId: playbookId, executed: executedCount, - succeeded: false, note: "step declined", - notifyBody: "You declined “\(shorten(step.summary, max: 60))”. The run stopped there.") + if let stop = await stopUnlessApproved(await approveStep(step), step: step, plan: plan, + playbookId: playbookId, executed: executedCount) { + return stop } } } @@ -419,11 +435,10 @@ final class AutonomousActionRunner { } } - let undoHint = undoActionsForLastRun.isEmpty ? "" : " Undo is available in the Holmes panel." - let skipHint = failedStepCount == 0 ? "" : " \(failedStepCount) step\(failedStepCount == 1 ? "" : "s") skipped." + tally.recordCompleted(executedCount) return await finishRun(plan: plan, playbookId: playbookId, executed: executedCount, - succeeded: failedStepCount == 0, note: failedStepCount == 0 ? "done" : "\(failedStepCount) step(s) could not be completed", - notifyBody: "\(executedCount) of \(plan.steps.count) steps completed.\(skipHint)\(undoHint)") + succeeded: tally.succeeded, note: tally.note, + notifyBody: tally.notifyBody(undoAvailable: !undoActionsForLastRun.isEmpty)) } // MARK: - Undo @@ -438,13 +453,17 @@ final class AutonomousActionRunner { isUndoing = true defer { isUndoing = false } statusLine = "Undoing: \(shorten(run.goal, max: 80))" - // Undo is user-initiated — clear a stale kill flag so it can post events. - ComputerUseEngine.shared.beginRun() + // Undo is user initiated: it gets its own run, so a stale kill switch + // from an earlier run cannot block it and stop all still reaches it. + let undoToken = ComputerUseEngine.shared.beginRun() + defer { ComputerUseEngine.shared.endRun(undoToken) } var attempted = 0 for action in undoActionsForLastRun.reversed() { - if ComputerUseEngine.shared.isCancelled { break } - await action.body() + if ComputerUseEngine.shared.isCancelled(undoToken) { break } + await ComputerUseRunScope.$token.withValue(undoToken) { + await action.body() + } attempted += 1 await MemoryStore.shared.record( kind: "action", @@ -580,29 +599,15 @@ final class AutonomousActionRunner { case .cancelled: return "Stopped." case .text(let text): + // Every local model failure, refusal, unverified action and limit + // now arrives as .failed (handled above), so .text is a real result. + // Matching its prose against failure prefixes only misread genuine + // answers such as "The local model finished the move" as failures. statusLine = shorten(text, max: 160) - // Honest accounting: a local-model failure (Ollama down, model not - // pulled, busy GPU, HTTP error, truncation) or an explicit - // model-reported inability used to come back as "success" (the run - // then notified "completed" over work that never happened). These - // prefixes are exactly the ones HolmesBrain.run produces. - if Self.modelFailurePrefixes.contains(where: { text.hasPrefix($0) }) { - return shorten(text, max: 160) - } return nil } } - /// Leading text of every failure string HolmesBrain.run(goal:) can return in - /// place of a result. Keep in sync with its catch arms. - private static let modelFailurePrefixes: [String] = [ - "Local model error", // .http / .unsupported / .truncated - "Holmes declined:", // .refused - "Ollama isn't running", // .serverUnreachable - "The local model", // .modelMissing / .busy - "Action failed:" // transport and any other thrown error - ] - // MARK: - Preflight /// The verbs the app lane can actually execute (BackendRouter.runApp). @@ -687,8 +692,8 @@ final class AutonomousActionRunner { /// ones are visible at a glance. Edits to the preview text are ignored — /// the card shows a RENDERING of the steps, it is not the steps. private func approveWholePlan(_ plan: ActionPlan, playbookId: String, - composioApps: [String]) async -> Bool { - guard !shouldStopRun else { return false } + composioApps: [String]) async -> Approval { + guard !shouldStopRun else { return .declined } progress("Review the plan to continue", phase: .waitingForUser) let listing = plan.steps.enumerated() .map { index, step in @@ -714,17 +719,14 @@ final class AutonomousActionRunner { preview: preview, appName: "your Mac", actionType: .agentToolCall) - switch await ConfirmationBus.shared.decide(action) { - case .approved: return !shouldStopRun - case .dismissed: return false - } + return approval(from: await ConfirmationBus.shared.decide(action)) } /// .auto level: ONE card for the single gate-flagged step. Approve runs /// just this step; Dismiss stops the whole run (later steps almost always /// depend on the declined one). - private func approveStep(_ step: PlannedStep) async -> Bool { - guard !shouldStopRun else { return false } + private func approveStep(_ step: PlannedStep) async -> Approval { + guard !shouldStopRun else { return .declined } progress(shorten(step.summary, max: 80), phase: .waitingForUser) let preview = """ \(step.summary) @@ -739,12 +741,46 @@ final class AutonomousActionRunner { preview: preview, appName: frontApp.isEmpty ? "your Mac" : frontApp, actionType: .agentToolCall) - switch await ConfirmationBus.shared.decide(action) { - case .approved: return !shouldStopRun - case .dismissed: return false + return approval(from: await ConfirmationBus.shared.decide(action)) + } + + private enum Approval { case approved, declined, timedOut } + + private func approval(from decision: AgentDecision) -> Approval { + switch decision { + case .approved: return shouldStopRun ? .declined : .approved + case .dismissed: return .declined + case .timedOut: + // Nobody is watching this run: say so in the notch instead of + // silently holding the playbook slot. + progress(ApprovalScope.timedOutMessage, phase: .working) + return .timedOut + } + } + + /// nil when the step was approved; otherwise the finished outcome to return. + private func stopUnlessApproved(_ approval: Approval, step: PlannedStep, plan: ActionPlan, + playbookId: String, executed: Int) async -> RunOutcome? { + switch approval { + case .approved: + return nil + case .declined: + return await finishRun(plan: plan, playbookId: playbookId, executed: executed, + succeeded: false, note: "step declined", + notifyBody: "You declined “\(shorten(step.summary, max: 60))”. The run stopped there.") + case .timedOut: + return await finishApprovalTimeout(plan: plan, playbookId: playbookId, executed: executed, + what: "“\(shorten(step.summary, max: 60))”") } } + private func finishApprovalTimeout(plan: ActionPlan, playbookId: String, executed: Int, + what: String) async -> RunOutcome { + await finishRun(plan: plan, playbookId: playbookId, executed: executed, + succeeded: false, note: ApprovalScope.timedOutMessage, + notifyBody: "Nobody approved \(what) in time, so nothing more was run.") + } + // MARK: - Memory + notifications + bookkeeping /// Every EXECUTED step becomes a durable "action" row: what (summary/verb), @@ -794,7 +830,7 @@ final class AutonomousActionRunner { succeeded: finalSucceeded, note: note) statusLine = finalSucceeded - ? "Done: \(shorten(plan.goal, max: 80))" + ? (note == "done" ? "Done: \(shorten(plan.goal, max: 80))" : "\(shorten(note, max: 120))") : "Stopped (\(note)): \(shorten(plan.goal, max: 60))" await MemoryStore.shared.record( kind: "action", @@ -825,6 +861,14 @@ final class AutonomousActionRunner { return outcome } + /// "Completed: goal", or the unverified note when a step could not be confirmed. + private func successSummary(_ plan: ActionPlan, max: Int) -> String { + if let note = lastRun?.note, note != "done", lastRun?.goal == plan.goal { + return shorten(note, max: max + 60) + } + return (max >= 100 ? "Completed: " : "Done: ") + shorten(plan.goal, max: max) + } + // Same UNUserNotificationCenter idiom as PlaybookEngine / MeetingJoinEngine: // one authorization request per session, nil trigger = fire immediately. private func requestNotificationPermissionIfNeeded() { diff --git a/holmes/holmes/Core/Autonomy/BackendRouter.swift b/holmes/holmes/Core/Autonomy/BackendRouter.swift index bfaca15..ba5324f 100644 --- a/holmes/holmes/Core/Autonomy/BackendRouter.swift +++ b/holmes/holmes/Core/Autonomy/BackendRouter.swift @@ -57,11 +57,16 @@ enum BackendRouter { let ok: Bool let text: String let undo: (() async -> Void)? + /// The step ran but its effect could not be read back (text typed into + /// a field that does not expose its value). Not a failure, not a plain + /// success: the run summary reports it as unverified. + let unverified: Bool - init(ok: Bool, text: String, undo: (() async -> Void)? = nil) { + init(ok: Bool, text: String, undo: (() async -> Void)? = nil, unverified: Bool = false) { self.ok = ok self.text = text self.undo = undo + self.unverified = unverified } } @@ -408,16 +413,26 @@ enum BackendRouter { if matchesSendVerb(label), !userConfirmed { return needsConfirm(step, "pressing “\(label)” looks like a send/submit-class action") } - return await MainActor.run { - guard let app = runningApp(named: appName) else { - return StepResult(ok: false, text: "App '\(appName)' is not running.") - } - let ok = ActionExecutor.shared.clickButton(label: label, in: app) - diag("ax_press '\(label)' in \(appName) ok=\(ok)") - return StepResult( - ok: ok, - text: ok ? "Pressed “\(label)” in \(appName)." - : "No accessible button labeled “\(label)” in \(appName) — a visible click may be needed instead.") + guard let app = runningApp(named: appName) else { + return StepResult(ok: false, text: "App '\(appName)' is not running.") + } + // The lookup is a bounded tree walk of blocking IPC calls: run it on + // the concurrency pool so a slow app never stalls the main thread. + // The send gate also runs on the control the label actually MATCHED: + // "later" can land on "Send later", which must hold for a confirm. + let outcome = await Task.detached(priority: .userInitiated) { + ActionExecutor.shared.pressControl(label: label, in: app, allowCommit: userConfirmed) + }.value + diag("ax_press '\(label)' in \(appName) outcome=\(outcome)") + switch outcome { + case .pressed(let matched): + return StepResult(ok: true, text: "Pressed “\(matched)” in \(appName).") + case .needsConfirmation(let matched): + return needsConfirm(step, "“\(label)” matched “\(matched)”, a send/submit-class control") + case .notFound: + return StepResult(ok: false, text: "Couldn't find a control labeled “\(label)” in \(appName). A visible click may be needed instead.") + case .failed(let code): + return StepResult(ok: false, text: "The control labeled “\(label)” in \(appName) refused the press (AXError \(code)).") } } @@ -431,16 +446,20 @@ enum BackendRouter { return StepResult(ok: false, text: "ax_type needs {\"app\":\"AppName\",\"text\":\"…\"} (optional \"fieldHint\").") } let fieldHint = (input["fieldHint"] as? String) ?? (input["field"] as? String) - return await MainActor.run { - guard let app = runningApp(named: appName) else { - return StepResult(ok: false, text: "App '\(appName)' is not running.") - } - let ok = ActionExecutor.shared.focusAndType(in: app, fieldHint: fieldHint, text: text) - diag("ax_type into \(appName) ok=\(ok)") - return StepResult( - ok: ok, - text: ok ? "Typed into \(appName) via Accessibility." - : "Couldn't find a writable field in \(appName)\(fieldHint.map { " matching “\($0)”" } ?? "").") + guard let app = runningApp(named: appName) else { + return StepResult(ok: false, text: "App '\(appName)' is not running.") + } + // focusAndType is nonisolated async, so its tree walk runs off the main thread. + let entry = await ActionExecutor.shared.focusAndType(in: app, fieldHint: fieldHint, text: text) + diag("ax_type into \(appName) result=\(entry)") + switch entry { + case .verified: + return StepResult(ok: true, text: "Typed into \(appName) via Accessibility (verified).") + case .unverified(let why): + return StepResult(ok: true, text: "Typed into \(appName), but it could not be verified: \(why)", unverified: true) + case .failed(let why): + return StepResult(ok: false, + text: "Couldn't type into \(appName)\(fieldHint.map { " field “\($0)”" } ?? ""): \(why)") } } diff --git a/holmes/holmes/Core/BrowserBridge.swift b/holmes/holmes/Core/BrowserBridge.swift index 40da4c7..bd2e4c2 100644 --- a/holmes/holmes/Core/BrowserBridge.swift +++ b/holmes/holmes/Core/BrowserBridge.swift @@ -53,8 +53,16 @@ enum BridgeProtocol { static let tokenHeader = "X-Holmes-Token" /// Lowercased form used for header lookup (HTTP headers are case-insensitive). static let tokenHeaderKey = "x-holmes-token" - /// Hard ceiling on a single payload. A full DOM extract is ~50-200 KB. + /// Hard ceiling on a single page context payload. A full DOM extract is ~50-200 KB. static let maxBodyBytes = 512 * 1024 + /// Ceiling for POST /command-result. Results legitimately carry screenshots and + /// large extracts, which the 512 KB context cap rejected and the extension then + /// reported as a timeout. Still bounded so a runaway result cannot exhaust memory. + static let maxCommandResultBytes = 16 * 1024 * 1024 + /// An oversize body is read and discarded up to this many bytes before the 413 + /// goes out, so the client sees the status instead of a reset connection. + /// Anything larger is refused without draining. + static let maxDrainBytes = 64 * 1024 * 1024 /// Per-recv/send socket timeout. Long enough for a 512 KB body over loopback, /// short enough that a silent client releases its slot promptly. static let socketTimeoutSeconds = 5 @@ -64,6 +72,11 @@ enum BridgeProtocol { /// Concurrent request handlers. The extension uses one connection at a time; /// this is headroom, not a throughput knob. static let maxConcurrentClients = 8 + /// How long the accept loop waits for a free handler before answering 503. + static let slotWaitSeconds: Double = 2 + /// Paired extension tokens kept at once (one per browser or profile). Pairing + /// one more than this forgets the least recently seen. + static let maxPairedExtensions = 8 // ── Browser-automation command channel ────────────────────────── // The Mac app is the PRODUCER: it leaves commands at GET /commands, which the @@ -78,18 +91,324 @@ enum BridgeProtocol { /// Hard cap on commands sitting unfetched. enqueue is rejected past this so a /// disconnected extension can't let the queue grow without bound. static let maxPendingCommands = 32 - /// A command the extension never fetched is dropped after this. The enqueue - /// await keeps its own (shorter) timeout as the real backstop; this just stops - /// an ancient command from ever being handed to a briefly-revived worker. - static let commandQueueTTL: TimeInterval = 30 - /// How long enqueueBrowserCommand awaits a result before giving up and - /// returning {"error":"timeout"}, so a stalled extension can't hang a producer. + /// How long a command may sit UNFETCHED before the producer gives up with the + /// distinct `extension_asleep` error. An MV3 worker that was evicted is only + /// woken by its alarm or a content script ping, so this is deliberately longer + /// than the result timeout: slow pickup is a different failure from a command + /// that was received and never answered. + static let commandUndeliveredTimeout: TimeInterval = 45 + /// Kept for callers that still read the old name. Same value as above. + static let commandQueueTTL: TimeInterval = commandUndeliveredTimeout + /// How long enqueueBrowserCommand awaits a result AFTER the extension fetched + /// the command, before returning {"error":"timeout"}. Measured from delivery, + /// not enqueue, so time spent waiting for a sleeping worker never eats into + /// the time the page has to run the action. static let commandResultTimeout: TimeInterval = 20 + /// Longest a GET /commands long poll is held open. It returns the moment a + /// command for that browser is enqueued. Kept under 30s because Chrome kills + /// an MV3 worker whose fetch has waited 30s for a response. + static let longPollMaxSeconds: TimeInterval = 22 + /// Long polls each hold a handler slot, so only a few may wait at once; any + /// extra poll is answered immediately instead of starving heartbeats. + static let maxConcurrentLongPolls = 3 + /// A browser instance that has not polled or beaten within this window is not + /// considered when routing a command that names no browser. + static let instanceFreshness: TimeInterval = 40 + /// Request header the extension sets to ask for a long poll (seconds). + static let longPollHeaderKey = "x-holmes-long-poll" + static let instanceHeaderKey = "x-holmes-browser-instance" + static let focusedHeaderKey = "x-holmes-browser-focused" +} + +/// Exponential backoff with a ceiling. Used for accept() failures (so a broken +/// listening socket cannot spin a core at 100%) and for retrying bind(). +struct BridgeBackoff { + let base: TimeInterval + let cap: TimeInterval + private(set) var consecutiveFailures = 0 + + init(base: TimeInterval, cap: TimeInterval) { + self.base = base + self.cap = cap + } + + /// Records one failure and returns how long to wait before trying again. + mutating func failure() -> TimeInterval { + consecutiveFailures += 1 + let exponent = Double(min(consecutiveFailures - 1, 30)) + return min(cap, base * pow(2, exponent)) + } + + mutating func success() { consecutiveFailures = 0 } +} + +/// One authorized request that proves an extension is alive, handed from the +/// socket layer to the main actor: which token authenticated it, the browser +/// instance and focus it reported, and (for heartbeats) its body. +struct BridgeSighting: Sendable { + let token: String + let instance: String? + let focused: Bool? + let body: Data? +} + +/// The browser command queue, shared by the main actor (producer) and the socket +/// layer (GET /commands). Guarded by a condition lock instead of main actor +/// isolation: a poll must never wait on a busy main thread, and a long poll has to +/// sleep until a command arrives without holding anything but its own socket. +final class BrowserCommandQueue: @unchecked Sendable { + struct Delivery { + let id: Int + let action: String + let params: [String: Any] + } + + enum State: Equatable { + case pending(since: Date) + case delivered(since: Date) + } + + private struct Entry { + let id: Int + let action: String + let params: [String: Any] + let target: String? + let enqueuedAt: Date + var deliveredAt: Date? + let cancellation: BrowserCommandCancellation + } + + private struct Sighting { + var lastSeen: Date + var activeAt: Date + } + + /// Random per app launch. Echoed by the extension so a result for command 7 of + /// a previous launch can never complete command 7 of this one, and so the + /// worker's idempotency cache never replays an old launch's result. + let session: String + private let condition = NSCondition() + private var pending: [Entry] = [] + private var delivered: [Int: Entry] = [:] + private var sightings: [String: Sighting] = [:] + private var activeLongPolls = 0 + private let maxPending: Int + private let longPollCap: TimeInterval + + init(session: String = UUID().uuidString, + maxPending: Int = BridgeProtocol.maxPendingCommands, + longPollCap: TimeInterval = BridgeProtocol.longPollMaxSeconds) { + self.session = session + self.maxPending = maxPending + self.longPollCap = longPollCap + } + + var pendingIDs: [Int] { + condition.lock(); defer { condition.unlock() } + return pending.map(\.id) + } + + /// Long polls currently held open. Tests wait on this instead of sleeping. + var heldLongPollCount: Int { + condition.lock(); defer { condition.unlock() } + return activeLongPolls + } + + var deliveredIDs: [Int] { + condition.lock(); defer { condition.unlock() } + return delivered.keys.sorted() + } + + /// False when the queue is full. Wakes every waiting long poll. + func enqueue(id: Int, action: String, params: [String: Any], cancellation: BrowserCommandCancellation) -> Bool { + condition.lock(); defer { condition.unlock() } + pending.removeAll { $0.cancellation.isCancelled } + guard pending.count < maxPending else { return false } + pending.append(Entry(id: id, action: action, params: params, + target: params["_browserInstanceID"] as? String, + enqueuedAt: Date(), deliveredAt: nil, cancellation: cancellation)) + condition.broadcast() + return true + } + + func state(of id: Int) -> State? { + condition.lock(); defer { condition.unlock() } + if let entry = delivered[id], let at = entry.deliveredAt { return .delivered(since: at) } + if let entry = pending.first(where: { $0.id == id }) { return .pending(since: entry.enqueuedAt) } + return nil + } + + func remove(_ id: Int) { + condition.lock(); defer { condition.unlock() } + pending.removeAll { $0.id == id } + delivered.removeValue(forKey: id) + } + + /// The worker reported that a delivered command actually started running (it + /// may have waited behind another command for the same tab). Restart the result + /// clock so queueing inside the browser is not counted against the page. + func markStarted(_ id: Int) { + condition.lock(); defer { condition.unlock() } + if delivered[id] != nil { delivered[id]?.deliveredAt = Date() } + } + + /// Puts delivered commands back at the front of the queue, e.g. when the poll + /// response could not be written because the extension hung up. + func requeue(_ ids: [Int]) { + guard !ids.isEmpty else { return } + condition.lock(); defer { condition.unlock() } + var restored: [Entry] = [] + for id in ids { + guard var entry = delivered.removeValue(forKey: id), !entry.cancellation.isCancelled else { continue } + entry.deliveredAt = nil + restored.append(entry) + } + pending.insert(contentsOf: restored.sorted { $0.id < $1.id }, at: 0) + condition.broadcast() + } + + /// Records that a browser instance is alive (it polled or beat). `focused` + /// is the worker's own report that one of its windows has OS focus. + func noteSeen(instance: String?, focused: Bool?) { + guard let instance, !instance.isEmpty else { return } + condition.lock(); defer { condition.unlock() } + noteSeenLocked(instance: instance, focused: focused, at: Date()) + } + + /// The app saw this instance's page while its browser was the frontmost app. + func noteForeground(instance: String, at date: Date = Date()) { + guard !instance.isEmpty else { return } + condition.lock(); defer { condition.unlock() } + var sighting = sightings[instance] ?? Sighting(lastSeen: date, activeAt: date) + sighting.lastSeen = max(sighting.lastSeen, date) + sighting.activeAt = max(sighting.activeAt, date) + sightings[instance] = sighting + condition.broadcast() + } + + /// Seeds a remembered instance (from a previous launch) with a tiny preference + /// over instances that have never been in front, without marking it alive. + func rememberInstance(_ instance: String) { + guard !instance.isEmpty else { return } + condition.lock(); defer { condition.unlock() } + if sightings[instance] == nil { + sightings[instance] = Sighting(lastSeen: .distantPast, activeAt: Date(timeIntervalSince1970: 1)) + } + } + + /// The browser instance a command without `_browserInstanceID` goes to: the + /// live instance most recently in front, falling back to the most recently + /// seen one. Nil when no instance is known to be alive. + /// True when this instance polled, beat or posted context within the freshness + /// window during this launch. A remembered instance from a previous launch is not. + func isFresh(_ instance: String) -> Bool { + condition.lock(); defer { condition.unlock() } + guard let sighting = sightings[instance] else { return false } + return Date().timeIntervalSince(sighting.lastSeen) < BridgeProtocol.instanceFreshness + } + + var preferredInstance: String? { + condition.lock(); defer { condition.unlock() } + return routeTargetLocked(now: Date()) + } + + /// Drains the commands deliverable to `instance`. With `wait > 0` this is a + /// long poll: it blocks (without touching the main thread) until a command + /// arrives, the wait elapses, or `clientGone` reports the extension hung up. + func drain(instance: String?, focused: Bool?, wait: TimeInterval, + clientGone: () -> Bool = { false }) -> [Delivery] { + drainDetailed(instance: instance, focused: focused, wait: wait, clientGone: clientGone).batch + } + + /// Same as drain, plus whether the request was actually held as a long poll. + /// A poll refused a hold (the long poll cap was reached) must not be told it + /// was held, or the worker would re-poll at once and spin. + func drainDetailed(instance: String?, focused: Bool?, wait: TimeInterval, + clientGone: () -> Bool = { false }) -> (batch: [Delivery], held: Bool) { + condition.lock() + let start = Date() + if let instance, !instance.isEmpty { noteSeenLocked(instance: instance, focused: focused, at: start) } + var deadline = start + var holdsLongPoll = false + if wait > 0 && activeLongPolls < BridgeProtocol.maxConcurrentLongPolls { + activeLongPolls += 1 + holdsLongPoll = true + deadline = start.addingTimeInterval(min(wait, longPollCap)) + } + defer { + if holdsLongPoll { activeLongPolls -= 1 } + condition.unlock() + } + while true { + let batch = takeDeliverableLocked(instance: instance) + if !batch.isEmpty { return (batch, holdsLongPoll) } + let now = Date() + if now >= deadline { return ([], holdsLongPoll) } + _ = condition.wait(until: min(deadline, now.addingTimeInterval(0.5))) + if clientGone() { return ([], holdsLongPoll) } + if let instance, !instance.isEmpty { + noteSeenLocked(instance: instance, focused: nil, at: Date()) + } + } + } + + static func encode(_ batch: [Delivery], session: String) -> Data { + let array: [[String: Any]] = batch.map { + ["id": $0.id, "action": $0.action, "params": $0.params, "session": session] + } + guard JSONSerialization.isValidJSONObject(array), + let data = try? JSONSerialization.data(withJSONObject: array) else { + return Data("[]".utf8) + } + return data + } + + private func noteSeenLocked(instance: String, focused: Bool?, at date: Date) { + var sighting = sightings[instance] ?? Sighting(lastSeen: date, activeAt: .distantPast) + sighting.lastSeen = date + if focused == true { sighting.activeAt = date } + sightings[instance] = sighting + } + + private func routeTargetLocked(now: Date) -> String? { + let fresh = sightings.filter { now.timeIntervalSince($0.value.lastSeen) < BridgeProtocol.instanceFreshness } + return fresh.max { lhs, rhs in + if lhs.value.activeAt != rhs.value.activeAt { return lhs.value.activeAt < rhs.value.activeAt } + if lhs.value.lastSeen != rhs.value.lastSeen { return lhs.value.lastSeen < rhs.value.lastSeen } + return lhs.key < rhs.key + }?.key + } + + private func takeDeliverableLocked(instance: String?) -> [Delivery] { + pending.removeAll { $0.cancellation.isCancelled } + guard !pending.isEmpty else { return [] } + let route = routeTargetLocked(now: Date()) + let now = Date() + var batch: [Delivery] = [] + var remaining: [Entry] = [] + for var entry in pending { + let deliverable: Bool + if let target = entry.target { + deliverable = target == instance + } else { + deliverable = route == nil || route == instance + } + if deliverable { + entry.deliveredAt = now + delivered[entry.id] = entry + batch.append(Delivery(id: entry.id, action: entry.action, params: entry.params)) + } else { + remaining.append(entry) + } + } + pending = remaining + return batch + } } /// Cancellation handlers run outside the main actor. Mark synchronously so a /// polling drain can refuse a cancelled command before its actor cleanup runs. -private final class BrowserCommandCancellation: @unchecked Sendable { +final class BrowserCommandCancellation: @unchecked Sendable { private let lock = NSLock() private var cancelled = false @@ -145,6 +464,38 @@ final class BrowserBridge { @ObservationIgnored private var lastForegroundBrowserInstance: String? private(set) var emailComposeUnavailableReason: String? private(set) var extensionVersion: String? + /// True while the extension's worker is alive (heartbeats arrive) but the page + /// itself is not sending context: the active tab's content script is missing + /// or orphaned. isExtensionConnected keeps its worker-liveness meaning for + /// existing callers; this is the extra truth the UI must not paper over. + private(set) var isPageContextStale = false + /// The worker's latest report about the active tab's content script. + @ObservationIgnored private var lastActiveTabProbe: (script: String, at: Date)? + /// When isExtensionConnected last turned true. + @ObservationIgnored private var connectedSince: Date? + /// A page context post from an extension too old to draft email was seen. + @ObservationIgnored private var observedLegacyProtocol = false + /// Where the last foreground browser instance is remembered across launches. + @ObservationIgnored private var instanceDefaults: UserDefaults? = .standard + static let lastInstanceDefaultsKey = "HolmesLastForegroundBrowserInstance" + /// Legacy extensions (no active tab probe): how long a frontmost browser may + /// stay silent while its worker beats before the page counts as stale. + static let pageContextTimeout: TimeInterval = 180 + + /// One state for the notch and Settings, so they never claim a full connection + /// from worker heartbeats alone or hide a bridge that is not listening. + enum LinkState: Equatable { + case notListening(String) + case disconnected + case connected + case pageContextStale + } + + var linkState: LinkState { + if !isRunning, let lastError { return .notListening(lastError) } + guard isExtensionConnected else { return .disconnected } + return isPageContextStale ? .pageContextStale : .connected + } private static let composeReloadMessage = "Reload Holmes on chrome://extensions, then refresh Gmail to enable email drafting." // ── Observable state the UI reads ─────────────────────────────── @@ -175,10 +526,29 @@ final class BrowserBridge { /// it into the extension; never logged in full. let token: String - /// The token the extension presented while the user had pairing armed. - /// Surfaced in Settings so "paired with an extension" is visible state, not - /// something the user has to infer from traffic. - private(set) var pairedToken: String? + /// Every extension the user paired, one per browser or profile. Surfaced in + /// Settings (with Remove) so "paired" is visible state, not something the user + /// has to infer from traffic. Pairing a new browser never drops the others. + private(set) var pairedExtensions: [PairedExtension] = [] + + /// The most recently active paired token. Kept for callers that only need to + /// know whether anything is paired at all. + var pairedToken: String? { + pairedExtensions.max { ($0.lastSeen ?? $0.pairedAt) < ($1.lastSeen ?? $1.pairedAt) }?.token + } + + @ObservationIgnored private var pairingStore = PairedExtensionStore.files + + /// The token adopted most recently, and when. Pairing trusts an Origin header + /// that a local app could forge, and any installed extension can claim an armed + /// window, so a new pairing is surfaced in Settings and the notch for ten + /// minutes, where an unexpected one is visible and can be removed. + private var lastPairedToken: String? + private var lastPairedAt: Date? + var recentlyPairedExtension: PairedExtension? { + guard let token = lastPairedToken, let at = lastPairedAt, Date().timeIntervalSince(at) < 600 else { return nil } + return pairedExtensions.first { $0.token == token } + } /// When the user-armed pairing window closes. Nil once it has expired or been /// consumed. Observable so Settings can count it down. @@ -244,105 +614,161 @@ final class BrowserBridge { private var lastBrowserApp = "your browser" // ── Browser-automation command queue (producer side) ──────────── - // All @MainActor state, per the actor's invariant. The socket layer reaches - // it through the two closures wired in start(): a synchronous main-actor hop - // for the GET /commands drain, and a fire-and-forget hop for the result POST. - private struct PendingBrowserCommand { - let id: Int - let action: String // wire (camelCase) action name automation.js expects - let params: [String: Any] - let enqueuedAt: Date - let cancellation: BrowserCommandCancellation - } - /// Commands waiting for the extension to fetch them via GET /commands. - private var pendingCommands: [PendingBrowserCommand] = [] + // The queue itself lives in BrowserCommandQueue behind a lock, so GET /commands + // never waits for the main thread. The continuations stay @MainActor state. + @ObservationIgnored let commandQueue = BrowserCommandQueue() /// Includes delivered commands while their producer still awaits a result. private var commandCancellations: [Int: BrowserCommandCancellation] = [:] /// The awaiting continuations, keyed by command id. Exactly one of {result - /// POST, cancellation, enqueue timeout, TTL expiry} resumes each — all via removeValue, so - /// a continuation can never be resumed twice. + /// POST, cancellation, delivery timeout, undelivered timeout} resumes each, all + /// via removeValue, so a continuation can never be resumed twice. private var commandContinuations: [Int: CheckedContinuation<[String: Any], Never>] = [:] /// Monotonic id source. A plain incrementing Int (not a UUID/Date) so echoed /// results can never collide, and so ids stay small and legible on the wire. private var nextCommandID = 1 + /// Ids that already resolved with a timeout. A result that arrives for one of + /// these later is logged and ignored; it never resolves or re-enqueues anything. + @ObservationIgnored private var expiredCommandIDs: [Int] = [] + /// How many late results were ignored. Surfaced for diagnostics and tests. + private(set) var lateResultsIgnored = 0 + /// Overridable so tests can exercise both deadlines without waiting a minute. + @ObservationIgnored var commandResultTimeout = BridgeProtocol.commandResultTimeout + @ObservationIgnored var commandUndeliveredTimeout = BridgeProtocol.commandUndeliveredTimeout + /// Port to bind. The real app always uses 5766; tests bind an ephemeral port. + @ObservationIgnored private var listenPort: UInt16 = BridgeProtocol.port + /// The port actually bound (differs from listenPort only when that is 0). + private(set) var boundPort: UInt16? private init() { token = BridgeToken.loadOrCreate() - pairedToken = BridgeToken.loadPaired() + pairedExtensions = pairingStore.load() + loadRememberedInstance() + } + + /// Restores the browser instance that was last in front, so the first compose + /// refresh after an app restart targets it instead of claiming a reload is needed. + private func loadRememberedInstance() { + guard let remembered = instanceDefaults?.string(forKey: Self.lastInstanceDefaultsKey), !remembered.isEmpty else { return } + lastForegroundBrowserInstance = remembered + commandQueue.rememberInstance(remembered) + } + + private func rememberForeground(_ instance: String, fromApp: Bool) { + guard !instance.isEmpty else { return } + if lastForegroundBrowserInstance != instance { + lastForegroundBrowserInstance = instance + instanceDefaults?.set(instance, forKey: Self.lastInstanceDefaultsKey) + } + if fromApp { commandQueue.noteForeground(instance: instance) } } #if DEBUG /// Isolated integration harness: real queue/parser, fake OS identity and no - /// token files, listening sockets, browser access or app activation. - init(testToken: String, environment: ContextEnvironment) { + /// token files, browser access or app activation. `port` 0 binds an ephemeral + /// loopback port when a test calls start(). + init(testToken: String, environment: ContextEnvironment, port: UInt16 = 0, + pairingStore: PairedExtensionStore = .memory()) { token = testToken contextEnvironment = environment + listenPort = port + self.pairingStore = pairingStore + pairedExtensions = pairingStore.load() + instanceDefaults = nil + } + func testUseInstanceDefaults(_ defaults: UserDefaults) { + instanceDefaults = defaults + loadRememberedInstance() } + func testSighting(_ sighting: BridgeSighting) { noteSighting(sighting) } + func testRefreshConnectionState(now: Date) { refreshConnectionState(now: now) } func testIngest(_ data: Data) -> LiveContext? { ingest(data) } func testDrainCommands(instance: String?) -> Data { drainCommandsJSON(forInstance: instance) } func testCommandResult(_ data: Data) { recordCommandResult(data) } - var testPendingCommandIDs: [Int] { pendingCommands.map(\.id) } + var testPendingCommandIDs: [Int] { commandQueue.pendingIDs } + var testHeldLongPollCount: Int { commandQueue.heldLongPollCount } var testAwaitingCommandCount: Int { commandContinuations.count } var testTrackedCommandCount: Int { commandCancellations.count } #endif // MARK: - Lifecycle - /// Binds + listens. Safe to call repeatedly; a second call is a no-op. + /// True between start() and stop(), whether or not the bind succeeded yet. + @ObservationIgnored private var wantsRunning = false + /// Pending background bind retry after the port was unavailable. + @ObservationIgnored private var bindRetryTask: Task? + /// Delay schedule for bind retries. Tests shorten it. + @ObservationIgnored var bindBackoff = BridgeBackoff(base: 2, cap: 60) + + /// Binds + listens. Safe to call repeatedly; a second call is a no-op. If the + /// port is taken, the reason is published through lastError (Settings and the + /// notch show it) and the bind is retried in the background with backoff. func start() { + wantsRunning = true guard !isRunning else { return } + // Every callback hops to the main actor fire-and-forget. None of them + // blocks the socket thread: GET /commands reads the lock-guarded queue + // directly, so a busy main thread can no longer fill the handler slots. let server = BridgeServer( - port: Self.port, + port: listenPort, token: token, - pairedToken: pairedToken, + pairedTokens: pairedExtensions.map(\.token), maxBodyBytes: Self.maxBodyBytes, - onPayload: { data in - Task { @MainActor in BrowserBridge.shared.ingest(data) } + commandQueue: commandQueue, + onPayload: { [weak self] data in + Task { @MainActor in self?.ingest(data) } }, - onHeartbeat: { - Task { @MainActor in BrowserBridge.shared.noteHeartbeat() } + onSighting: { [weak self] sighting in + Task { @MainActor in self?.noteSighting(sighting) } }, - onUnauthorized: { path in - Task { @MainActor in BrowserBridge.shared.noteUnauthorized(path) } + onUnauthorized: { [weak self] path in + Task { @MainActor in self?.noteUnauthorized(path) } }, - onPaired: { secret in - Task { @MainActor in BrowserBridge.shared.notePaired(secret) } + onPaired: { [weak self] secret in + Task { @MainActor in self?.notePaired(secret) } }, - onCommandsPoll: { instance in - // Called on a background client queue. The queue is @MainActor - // state, and GET /commands must return its bytes synchronously, - // so hop to main and block. This can't deadlock: no main-actor - // code ever waits on the client queue, so there is no reentrancy. - if Thread.isMainThread { - return MainActor.assumeIsolated { BrowserBridge.shared.drainCommandsJSON(forInstance: instance) } - } - return DispatchQueue.main.sync { - MainActor.assumeIsolated { BrowserBridge.shared.drainCommandsJSON(forInstance: instance) } - } - }, - onCommandResult: { data in - Task { @MainActor in BrowserBridge.shared.recordCommandResult(data) } + onCommandResult: { [weak self] data in + Task { @MainActor in self?.recordCommandResult(data) } } ) switch server.startListening() { - case .success: + case .success(let port): self.server = server + boundPort = port isRunning = true lastError = nil - print("[Bridge] Listening on http://127.0.0.1:\(Self.port) (loopback only, token required)") + print("[Bridge] Listening on http://127.0.0.1:\(port) (loopback only, token required)") print("[Bridge] Token file: \(Self.tokenFileURL.path)") + bindBackoff.success() + bindRetryTask?.cancel() + bindRetryTask = nil startWatchdog() case .failure(let message): - lastError = message - print("[Bridge] NOT listening — \(message)") + let delay = bindBackoff.failure() + lastError = "\(message) Retrying in \(Int(delay.rounded(.up)))s." + print("[Bridge] NOT listening — \(message) (retry in \(delay)s)") + scheduleBindRetry(after: delay) + } + } + + private func scheduleBindRetry(after delay: TimeInterval) { + bindRetryTask?.cancel() + bindRetryTask = Task { @MainActor [weak self] in + try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) + guard let self, !Task.isCancelled, self.wantsRunning, !self.isRunning else { return } + self.bindRetryTask = nil + self.start() } } func stop() { + wantsRunning = false + bindRetryTask?.cancel() + bindRetryTask = nil server?.stopListening() server = nil + boundPort = nil watchdog?.invalidate() watchdog = nil isRunning = false @@ -360,8 +786,7 @@ final class BrowserBridge { } } - private func refreshConnectionState() { - let now = Date() + private func refreshConnectionState(now: Date = Date()) { // Liveness comes from EITHER signal: a recent /heartbeat, OR a recent real // /context POST. A page actively posting context is obviously connected even // if a bare heartbeat was missed, so we don't demand both. (ingest() also @@ -375,6 +800,7 @@ final class BrowserBridge { consecutiveStaleTicks = 0 if !isExtensionConnected { isExtensionConnected = true + connectedSince = now print("[Bridge] Extension connected") } } else { @@ -387,6 +813,7 @@ final class BrowserBridge { print("[Bridge] Extension disconnected") } } + refreshPageContextState(now: now) // An expired pairing window has to stop reading as open in Settings. The // socket layer enforces the deadline itself; this only republishes it. if let ends = pairingWindowEnds, ends <= Date() { @@ -404,11 +831,10 @@ final class BrowserBridge { /// an authorization — a loopback port is reachable by every process on this /// Mac, and by any page that can talk to one. /// - /// Arming also DROPS the current pairing, so re-installing the extension (new - /// random secret) is a two-click recovery rather than a permanent lockout. + /// Arming does NOT drop existing pairings: a second browser (or a re-installed + /// extension with a new random secret) is added alongside the others. A stale + /// pairing is removed explicitly from Settings. func beginPairing() { - pairedToken = nil - BridgeToken.clearPaired() let deadline = Date().addingTimeInterval(Self.pairingWindowSeconds) pairingWindowEnds = deadline server?.openPairingWindow(until: deadline) @@ -439,8 +865,8 @@ final class BrowserBridge { func enqueueBrowserCommand(_ action: String, _ params: [String: Any]) async -> [String: Any] { guard !Task.isCancelled else { return Self.cancelledCommandResult } expireStaleCommands() - guard pendingCommands.count < BridgeProtocol.maxPendingCommands else { - return ["error": "browser command queue is full (\(BridgeProtocol.maxPendingCommands) pending) — the extension may be disconnected"] + guard JSONSerialization.isValidJSONObject(params) else { + return ["error": "invalid_params", "message": "The browser command parameters are not valid JSON."] } let id = nextCommandID nextCommandID += 1 @@ -452,15 +878,15 @@ final class BrowserBridge { return } // Registration and enqueue are synchronous on the main actor; - // a result cannot arrive before its continuation is registered. + // a result cannot arrive before its continuation is registered, + // because results are recorded on the main actor too. + guard commandQueue.enqueue(id: id, action: action, params: params, cancellation: cancellation) else { + continuation.resume(returning: Self.queueFullResult) + return + } commandContinuations[id] = continuation commandCancellations[id] = cancellation - pendingCommands.append(PendingBrowserCommand(id: id, action: action, params: params, - enqueuedAt: Date(), cancellation: cancellation)) - Task { @MainActor [weak self] in - try? await Task.sleep(nanoseconds: UInt64(BridgeProtocol.commandResultTimeout * 1_000_000_000)) - self?.timeoutCommand(id) - } + Task { @MainActor [weak self] in await self?.superviseCommand(id) } } }, onCancel: { [weak self] in cancellation.cancel() @@ -478,8 +904,16 @@ final class BrowserBridge { emailComposeUnavailableReason = "Return to the email composer to refresh its contents." return nil } - guard let instance = lastForegroundBrowserInstance else { - emailComposeUnavailableReason = isExtensionConnected ? Self.composeReloadMessage + // The instance comes from a foreground context post, a focused heartbeat or + // poll, or the one remembered from the previous launch. Only an extension + // that really is too old (or missing from the page) is told to reload. + // The remembered browser wins only while it is alive this launch. A browser + // that was switched away from, or an extension reinstalled with a new + // instance, must not make the refresh wait out the undelivered deadline. + let liveRemembered = lastForegroundBrowserInstance.flatMap { commandQueue.isFresh($0) ? $0 : nil } + guard let instance = liveRemembered ?? commandQueue.preferredInstance ?? lastForegroundBrowserInstance else { + emailComposeUnavailableReason = observedLegacyProtocol ? Self.composeReloadMessage + : isExtensionConnected ? "Click into your email tab in the browser so Holmes can find it, then try again." : "Connect the Holmes browser extension, then refresh Gmail to enable email drafting." return nil } @@ -488,7 +922,7 @@ final class BrowserBridge { guard result["ok"] as? Bool == true, let payload = result["payload"] as? [String: Any], let data = try? JSONSerialization.data(withJSONObject: payload) else { - emailComposeUnavailableReason = (result["reason"] as? String) ?? Self.composeReloadMessage + emailComposeUnavailableReason = Self.browserFailureMessage(result) return nil } // onLiveContext runs synchronously inside ingest. An observer may publish @@ -526,8 +960,9 @@ final class BrowserBridge { if result["cancelled"] as? Bool == true { throw CancellationError() } guard result["ok"] as? Bool == true, result["inserted"] as? Bool == true, result["identity"] as? String == expected.identity else { - throw EmailComposeError.unavailable((result["reason"] ?? result["error"]) as? String - ?? "The composer could not confirm insertion. Your draft is still available to copy.") + throw EmailComposeError.unavailable(result["reason"] != nil || result["error"] != nil + ? Self.browserFailureMessage(result) + : "The composer could not confirm insertion. Your draft is still available to copy.") } return true } @@ -536,31 +971,12 @@ final class BrowserBridge { /// expects — `[{"id":Int,"action":String,"params":{…}}]`, or `[]` when empty. /// Fetching is destructive: a command is delivered exactly once. private func drainCommandsJSON(forInstance instance: String?) -> Data { - // A GET /commands only reaches here past the token gate, and the extension's - // worker polls it every ~2s while alive. That poll is therefore an - // independent, focus-proof proof of life: treat it as a heartbeat so an - // actively-polling extension stays "connected" even if its bare /heartbeat - // POSTs are somehow dropped. (Post-eviction the poll stops, so the - // chrome.alarms heartbeat remains the real backstop — this only strengthens - // the alive-worker case.) + // A GET /commands only reaches here past the token gate, so it is an + // independent, focus-proof proof of life: treat it as a heartbeat. noteHeartbeat() expireStaleCommands() - guard !pendingCommands.isEmpty else { return Data("[]".utf8) } - let batch = pendingCommands.filter { - guard !$0.cancellation.isCancelled else { return false } - guard let target = $0.params["_browserInstanceID"] as? String else { return true } - return target == instance - } - let delivered = Set(batch.map(\.id)) - pendingCommands.removeAll { delivered.contains($0.id) } - let array: [[String: Any]] = batch.map { - ["id": $0.id, "action": $0.action, "params": $0.params] - } - guard JSONSerialization.isValidJSONObject(array), - let data = try? JSONSerialization.data(withJSONObject: array) else { - return Data("[]".utf8) - } - return data + let batch = commandQueue.drain(instance: instance, focused: nil, wait: 0) + return BrowserCommandQueue.encode(batch, session: commandQueue.session) } /// Records a POST /command-result body, ignoring unrequested or late results. @@ -573,41 +989,100 @@ final class BrowserBridge { print("[Bridge] Dropped a command-result that wasn't a JSON object with an id") return } - guard let cancellation = commandCancellations[id] else { return } + // A result stamped with another launch's session belongs to a command this + // launch never issued, even if the numeric id happens to match. + if let session = object["session"] as? String, session != commandQueue.session { return } + if object["_holmesStarted"] as? Bool == true { + commandQueue.markStarted(id) + return + } + guard let cancellation = commandCancellations[id] else { + if expiredCommandIDs.contains(id) { + lateResultsIgnored += 1 + print("[Bridge] Ignored a late result for command \(id); it already timed out and is not re-run") + } + return + } finishCommand(id, result: cancellation.isCancelled ? Self.cancelledCommandResult : object) } private static var cancelledCommandResult: [String: Any] { ["error": "cancelled", "cancelled": true] } + static var queueFullResult: [String: Any] { + ["error": "queue_full", + "message": "Holmes already has \(BridgeProtocol.maxPendingCommands) browser commands waiting. The extension may be disconnected; wait a moment and try again."] + } + + static func extensionAsleepResult(after seconds: TimeInterval) -> [String: Any] { + ["error": "extension_asleep", "undelivered": true, + "message": "The Holmes browser extension did not pick up this command within \(Int(seconds))s. Its background worker may be asleep or the browser may be closed. Click into a browser tab, then try again. The command was never run."] + } + + static func deliveredTimeoutResult(after seconds: TimeInterval) -> [String: Any] { + ["error": "timeout", "delivered": true, + "message": "The browser received this command but did not report a result within \(Int(seconds))s. It may still have run, so check the page before retrying."] + } + + /// Watches one command's two deadlines: undelivered (the worker never fetched + /// it) and delivered (fetched but no result). Resolves the awaiter exactly once. + private func superviseCommand(_ id: Int) async { + while commandContinuations[id] != nil { + if commandCancellations[id]?.isCancelled == true { + finishCommand(id, result: Self.cancelledCommandResult) + return + } + let now = Date() + let deadline: Date + switch commandQueue.state(of: id) { + case .pending(let since)?: + deadline = since.addingTimeInterval(commandUndeliveredTimeout) + if now >= deadline { + expireCommand(id, result: Self.extensionAsleepResult(after: commandUndeliveredTimeout)) + return + } + case .delivered(let since)?: + deadline = since.addingTimeInterval(commandResultTimeout) + if now >= deadline { + expireCommand(id, result: Self.deliveredTimeoutResult(after: commandResultTimeout)) + return + } + case nil: + // Not in the queue but still awaited: only a cancellation drop can + // do that, and the branch above handles it. Never hang regardless. + expireCommand(id, result: Self.deliveredTimeoutResult(after: commandResultTimeout)) + return + } + let pause = max(0.01, min(0.25, deadline.timeIntervalSince(now))) + try? await Task.sleep(nanoseconds: UInt64(pause * 1_000_000_000)) + } + } + /// Removing a queued command prevents future delivery. A command already /// delivered may have written its body; cancellation cannot roll that back. private func finishCommand(_ id: Int, result: [String: Any]) { - pendingCommands.removeAll { $0.id == id } + commandQueue.remove(id) commandCancellations.removeValue(forKey: id) commandContinuations.removeValue(forKey: id)?.resume(returning: result) } - /// Resolves an awaiting continuation with a timeout and clears the command. - /// Safe to call for an id already resolved — removeValue makes it a no-op. - private func timeoutCommand(_ id: Int) { + /// Resolves with a timeout style result and remembers the id, so a result that + /// shows up afterwards is recognised as late instead of silently vanishing. + private func expireCommand(_ id: Int, result: [String: Any]) { let cancelled = commandCancellations[id]?.isCancelled == true - finishCommand(id, result: cancelled ? Self.cancelledCommandResult : ["error": "timeout"]) + guard commandContinuations[id] != nil else { return } + if !cancelled { + expiredCommandIDs.append(id) + if expiredCommandIDs.count > 256 { expiredCommandIDs.removeFirst(expiredCommandIDs.count - 256) } + } + finishCommand(id, result: cancelled ? Self.cancelledCommandResult : result) } - /// Drops commands the extension never fetched within the TTL, resolving any - /// still-parked awaiter so a disconnected extension can't hang producers - /// forever. (The enqueue await's own timeout is the primary backstop; this is - /// belt-and-suspenders and also reclaims the pending slot sooner.) + /// Resolves cancelled awaiters promptly. Deadlines are enforced per command by + /// superviseCommand, so nothing else is needed here. private func expireStaleCommands() { for id in commandCancellations.filter({ $0.value.isCancelled }).map(\.key) { finishCommand(id, result: Self.cancelledCommandResult) } - let cutoff = Date().addingTimeInterval(-BridgeProtocol.commandQueueTTL) - guard pendingCommands.contains(where: { $0.enqueuedAt < cutoff }) else { return } - let stale = pendingCommands.filter { $0.enqueuedAt < cutoff } - for command in stale { - finishCommand(command.id, result: ["error": "expired before the extension fetched it"]) - } } /// The echoed id comes back as a JSON number (or, defensively, a string). @@ -626,7 +1101,69 @@ final class BrowserBridge { // A fresh beat clears any accumulated stale count so the hysteresis window // always starts over from a known-good state. consecutiveStaleTicks = 0 - if !isExtensionConnected { isExtensionConnected = true } + if !isExtensionConnected { + isExtensionConnected = true + connectedSince = Date() + } + } + + /// Page context health. With the worker's active tab probe, stale means the + /// probe found no content script and no page has posted since. Without a probe + /// (older extension), stale means a browser is in front yet its page has been + /// silent for pageContextTimeout while the worker keeps beating. + private func refreshPageContextState(now: Date) { + let stale: Bool + if !isExtensionConnected { + stale = false + } else if let probe = lastActiveTabProbe { + stale = probe.script == "missing" && (lastContextPost.map { $0 < probe.at } ?? true) + } else { + let frontIsBrowser = Self.isBrowserName((contextEnvironment.frontmost()?.name ?? "").lowercased()) + let quietSince = lastContextPost ?? connectedSince + stale = frontIsBrowser && (quietSince.map { now.timeIntervalSince($0) > Self.pageContextTimeout } ?? false) + } + guard stale != isPageContextStale else { return } + isPageContextStale = stale + print(stale ? "[Bridge] Extension worker is alive but the page is not sending context" + : "[Bridge] Page context is flowing again") + } + + /// Turns a failed browser command result into one accurate, actionable line. + /// Only a content script that is genuinely missing or orphaned is told to reload. + nonisolated static func browserFailureMessage(_ result: [String: Any]) -> String { + let error = result["error"] as? String ?? "" + let reason = result["reason"] as? String ?? "" + let text = (reason + " " + error).lowercased() + switch error { + case "extension_asleep": + return "The Holmes extension isn't picking up requests right now (its background worker may be asleep). Click into your browser tab, then try again." + case "timeout": + return "Your browser received the request but didn't answer in time. Click into the email tab, then try again." + case "queue_full": + return "Holmes has too many browser requests waiting. Wait a few seconds, then try again." + case "cancelled": + return "The request was cancelled." + default: + break + } + if text.contains("receiving end does not exist") || text.contains("could not establish connection") + || text.contains("content script is missing") { + return "Holmes isn't loaded in that tab. Refresh the email tab; if that doesn't help, reload Holmes on chrome://extensions." + } + if text.contains("result too large") { + return "The browser's answer was too large to send. Try again with a smaller page or selection." + } + if text.contains("no longer in the active tab") || text.contains("active tab changed") + || text.contains("no active browser tab") || text.contains("did not become visible") { + return "Bring the email tab to the front in your browser, then try again." + } + if text.contains("no active compose window") || text.contains("compose reader did not respond") || text.contains("no composer") { + return "Open the email you're writing in the browser, then try again." + } + if !reason.isEmpty { return reason } + if let message = result["message"] as? String, !message.isEmpty { return message } + if !error.isEmpty { return "The browser couldn't finish that request: \(error)" } + return "The browser didn't return a composer reading. Try again." } private func noteUnauthorized(_ path: String) { @@ -639,10 +1176,63 @@ final class BrowserBridge { /// immediately — pairing is one-shot by construction. private func notePaired(_ secret: String) { pairingWindowEnds = nil - guard pairedToken != secret else { return } - pairedToken = secret - BridgeToken.savePaired(secret) - print("[Bridge] Paired with an extension (token …\(secret.suffix(4)))") + guard !pairedExtensions.contains(where: { $0.token == secret }) else { return } + let now = Date() + pairedExtensions.append(PairedExtension(token: secret, label: "Browser extension", instanceID: nil, + pairedAt: now, lastSeen: now)) + if pairedExtensions.count > BridgeProtocol.maxPairedExtensions { + pairedExtensions.sort { ($0.lastSeen ?? $0.pairedAt) > ($1.lastSeen ?? $1.pairedAt) } + pairedExtensions.removeLast(pairedExtensions.count - BridgeProtocol.maxPairedExtensions) + server?.setPairedTokens(pairedExtensions.map(\.token)) + } + pairingStore.save(pairedExtensions) + lastPairedToken = secret + lastPairedAt = now + print("[Bridge] Paired with an extension (token …\(secret.suffix(4))); \(pairedExtensions.count) paired") + } + + /// Forgets one paired extension (Settings ▸ Remove). Its token is refused from + /// the next request on; the other pairings are untouched. + func removePairedExtension(_ token: String) { + pairedExtensions.removeAll { $0.token == token } + server?.setPairedTokens(pairedExtensions.map(\.token)) + pairingStore.save(pairedExtensions) + } + + /// A heartbeat or poll authenticated with a paired token: keeps the connection + /// fresh and labels that pairing with the browser instance it came from. + private func noteSighting(_ sighting: BridgeSighting) { + noteHeartbeat() + // A worker reporting OS focus identifies the browser in front, even when no + // page has posted context since Holmes launched. + if sighting.focused == true, let instance = sighting.instance, !instance.isEmpty { + rememberForeground(instance, fromApp: false) + } + if let body = sighting.body, !body.isEmpty, + let object = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any], + let activeTab = object["activeTab"] as? [String: Any], + let script = activeTab["script"] as? String { + lastActiveTabProbe = (script, Date()) + refreshPageContextState(now: Date()) + } + guard let index = pairedExtensions.firstIndex(where: { $0.token == sighting.token }) else { return } + var entry = pairedExtensions[index] + let now = Date() + var persist = entry.lastSeen.map { now.timeIntervalSince($0) > 600 } ?? true + if let instance = sighting.instance, !instance.isEmpty, entry.instanceID != instance { + entry.instanceID = instance + persist = true + } + if let instance = entry.instanceID, let bundle = browserBundlesByInstance[instance], + let name = contextEnvironment.nameForBundle(bundle), entry.label != name { + entry.label = name + persist = true + } + let refreshVisible = entry.lastSeen.map { now.timeIntervalSince($0) > 5 } ?? true + entry.lastSeen = now + guard persist || refreshVisible else { return } + pairedExtensions[index] = entry + if persist { pairingStore.save(pairedExtensions) } } /// Parses the payload ON THE MAIN ACTOR (so it can read the frontmost app) and @@ -654,6 +1244,7 @@ final class BrowserBridge { // — is proof the extension is alive and posting, so it counts as an independent // liveness signal for refreshConnectionState(). lastContextPost = Date() + refreshPageContextState(now: Date()) guard var payload = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { print("[Bridge] Dropped a payload that wasn't a JSON object (\(data.count) bytes)") @@ -667,7 +1258,10 @@ final class BrowserBridge { if let isActiveTab = payload["isActiveTab"] as? Bool, !isActiveTab { return nil } if let visible = payload["visible"] as? Bool, !visible { return nil } if (payload["emailComposeProtocolVersion"] as? Int ?? 0) < 1 { + observedLegacyProtocol = true emailComposeUnavailableReason = Self.composeReloadMessage + } else { + observedLegacyProtocol = false } let instanceID = payload["browserInstanceId"] as? String ?? "" if payload["capturedAt"] != nil { @@ -702,7 +1296,7 @@ final class BrowserBridge { browserBundlesByInstance[instanceID] = bundle } guard browserBundlesByInstance[instanceID] == bundle else { return nil } - lastForegroundBrowserInstance = instanceID + rememberForeground(instanceID, fromApp: true) } else { // Holmes's review card owns focus. Keep only the previously // identified originating browser, not a background browser's tab. @@ -807,25 +1401,46 @@ enum BridgeToken { return value } - static func savePaired(_ secret: String) { + /// Every paired extension (paired_tokens.json, 0600). Migrates the single + /// paired_token file an older build wrote. + static var pairedListURL: URL { directory.appendingPathComponent("paired_tokens.json", isDirectory: false) } + + static func loadPairedExtensions() -> [PairedExtension] { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + if let data = try? Data(contentsOf: pairedListURL), + let list = try? decoder.decode([PairedExtension].self, from: data) { + try? FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: pairedListURL.path) + return list.filter { $0.token.count >= 16 } + } + guard let legacy = loadPaired() else { return [] } + let migrated = [PairedExtension(token: legacy, label: "Browser extension", instanceID: nil, + pairedAt: Date(), lastSeen: nil)] + savePairedExtensions(migrated) + return migrated + } + + static func savePairedExtensions(_ list: [PairedExtension]) { let fm = FileManager.default if !fm.fileExists(atPath: directory.path) { try? fm.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) } - // Replace rather than append: exactly one extension is paired at a time. - try? fm.removeItem(at: pairedFileURL) - if !fm.createFile(atPath: pairedFileURL.path, contents: Data(secret.utf8), - attributes: [.posixPermissions: 0o600]) { - print("[Bridge] WARNING: couldn't persist the pairing at \(pairedFileURL.path) — it will be re-established next launch") + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + guard let data = try? encoder.encode(list) else { return } + // Write beside the target with 0600 from the start, then rename over it, so + // the secrets are never world readable and a crash never leaves half a file. + let temporary = directory.appendingPathComponent(".paired_tokens.\(UUID().uuidString).tmp") + guard fm.createFile(atPath: temporary.path, contents: data, attributes: [.posixPermissions: 0o600]), + rename(temporary.path, pairedListURL.path) == 0 else { + try? fm.removeItem(at: temporary) + print("[Bridge] WARNING: couldn't persist pairings at \(pairedListURL.path); they will need pairing again next launch") + return } - } - - /// Forgets the current pairing. Called when the user arms a new pairing window - /// so a re-installed extension (which has a brand-new random secret) can claim - /// the bridge instead of being locked out by the old one. - static func clearPaired() { - try? FileManager.default.removeItem(at: pairedFileURL) + // The list is now authoritative; a leftover single token file must not + // resurrect a pairing the user removed. + try? fm.removeItem(at: pairedFileURL) } static func loadOrCreate() -> String { @@ -857,6 +1472,36 @@ enum BridgeToken { } } +/// One paired extension. The token is the secret the extension minted; label and +/// instance are learned from its traffic so Settings can say which browser it is. +struct PairedExtension: Codable, Equatable, Identifiable, Sendable { + var token: String + var label: String + var instanceID: String? + var pairedAt: Date + var lastSeen: Date? + var id: String { token } + /// Last four characters, safe to show in Settings. + var tokenSuffix: String { String(token.suffix(4)) } +} + +/// Where pairings are persisted. The app uses the 0600 files; tests use memory so +/// they never touch the user's real pairing. +struct PairedExtensionStore { + let load: () -> [PairedExtension] + let save: ([PairedExtension]) -> Void + + static var files: PairedExtensionStore { + PairedExtensionStore(load: BridgeToken.loadPairedExtensions, save: BridgeToken.savePairedExtensions) + } + + static func memory(_ initial: [PairedExtension] = []) -> PairedExtensionStore { + final class Box { var value: [PairedExtension]; init(_ value: [PairedExtension]) { self.value = value } } + let box = Box(initial) + return PairedExtensionStore(load: { box.value }, save: { box.value = $0 }) + } +} + // MARK: - BridgeServer // The raw BSD-socket HTTP layer (no entitlements needed; the app is unsandboxed). // Deliberately OUTSIDE the main actor: accept()/recv() block. It authenticates, @@ -866,29 +1511,28 @@ enum BridgeToken { private final class BridgeServer: @unchecked Sendable { enum StartResult { - case success + case success(UInt16) case failure(String) } private let port: UInt16 private let token: String private let maxBodyBytes: Int + /// Read directly (lock guarded) by GET /commands. No main thread involved. + private let commandQueue: BrowserCommandQueue private let onPayload: @Sendable (Data) -> Void - private let onHeartbeat: @Sendable () -> Void + private let onSighting: @Sendable (BridgeSighting) -> Void private let onUnauthorized: @Sendable (String) -> Void private let onPaired: @Sendable (String) -> Void - /// Synchronously drains + returns the queued commands as the JSON array - /// background.js expects. Called on the client queue; hops to the main actor. - private let onCommandsPoll: @Sendable (String?) -> Data /// Hands off a POST /command-result body (fire-and-forget, like onPayload). private let onCommandResult: @Sendable (Data) -> Void private let lock = NSLock() private var serverFD: Int32 = -1 private var running = false - /// The extension's own secret. Read and written under `lock` because every - /// connection is handled on its own queue. - private var pairedToken: String? + /// The paired extensions' own secrets (one per browser). Read and written under + /// `lock` because every connection is handled on its own queue. + private var pairedTokens: Set /// Deadline of the user-armed pairing window. Nil (or past) means the ONLY /// accepted secrets are the issued token and the one already paired — no /// caller can talk its way into the bridge on its own initiative. @@ -905,23 +1549,23 @@ private final class BridgeServer: @unchecked Sendable { init(port: UInt16, token: String, - pairedToken: String?, + pairedTokens: [String], maxBodyBytes: Int, + commandQueue: BrowserCommandQueue, onPayload: @escaping @Sendable (Data) -> Void, - onHeartbeat: @escaping @Sendable () -> Void, + onSighting: @escaping @Sendable (BridgeSighting) -> Void, onUnauthorized: @escaping @Sendable (String) -> Void, onPaired: @escaping @Sendable (String) -> Void, - onCommandsPoll: @escaping @Sendable (String?) -> Data, onCommandResult: @escaping @Sendable (Data) -> Void) { self.port = port self.token = token - self.pairedToken = pairedToken + self.pairedTokens = Set(pairedTokens) self.maxBodyBytes = maxBodyBytes + self.commandQueue = commandQueue self.onPayload = onPayload - self.onHeartbeat = onHeartbeat + self.onSighting = onSighting self.onUnauthorized = onUnauthorized self.onPaired = onPaired - self.onCommandsPoll = onCommandsPoll self.onCommandResult = onCommandResult } @@ -949,14 +1593,25 @@ private final class BridgeServer: @unchecked Sendable { } } guard bound == 0 else { + let code = errno close(fd) - return .failure("bind() failed on 127.0.0.1:\(port) (errno \(errno)) — is another Holmes running?") + if code == EADDRINUSE { + return .failure("Port \(port) on 127.0.0.1 is already in use by another app (is another copy of Holmes running?).") + } + return .failure("bind() failed on 127.0.0.1:\(port) (errno \(code)).") } guard listen(fd, 16) == 0 else { close(fd) return .failure("listen() failed: \(errno)") } + var boundAddress = sockaddr_in() + var boundLength = socklen_t(MemoryLayout.size) + let named = withUnsafeMutablePointer(to: &boundAddress) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { getsockname(fd, $0, &boundLength) } + } + let actualPort = named == 0 ? UInt16(bigEndian: boundAddress.sin_port) : port + lock.lock() serverFD = fd running = true @@ -965,7 +1620,7 @@ private final class BridgeServer: @unchecked Sendable { DispatchQueue.global(qos: .utility).async { [weak self] in self?.acceptLoop() } - return .success + return .success(actualPort) } func stopListening() { @@ -988,13 +1643,25 @@ private final class BridgeServer: @unchecked Sendable { } private func acceptLoop() { + // accept() can fail repeatedly (EMFILE when the process is out of file + // descriptors, ECONNABORTED storms). Retrying instantly spun a core at 100%; + // back off exponentially up to a second and reset on the next success. + var backoff = BridgeBackoff(base: 0.01, cap: 1) while isRunning { let fd = listeningFD guard fd >= 0 else { break } let clientFD = accept(fd, nil, nil) guard clientFD >= 0 else { - if isRunning { continue } else { break } + let code = errno + guard isRunning else { break } + let delay = backoff.failure() + if backoff.consecutiveFailures == 1 || backoff.consecutiveFailures % 100 == 0 { + print("[Bridge] accept() failed (errno \(code)); backing off \(delay)s") + } + usleep(UInt32(delay * 1_000_000)) + continue } + backoff.success() // SO_NOSIGPIPE: a browser that disconnects mid-write must not raise // SIGPIPE and kill the whole app — send() returns EPIPE instead. var on: Int32 = 1 @@ -1013,7 +1680,16 @@ private final class BridgeServer: @unchecked Sendable { // client queue. Blocking the accept loop instead means a flood of // stalled connections queues in the listen backlog and dies there. let slots = clientSlots - slots.wait() + // Non-blocking: waiting here (even 2s) ran connections through one at a + // time, so a backlog pushed later requests past the extension's fetch + // timeout before they ever saw a 503. + guard slots.wait(timeout: .now()) == .success else { + // Every handler is busy (stalled clients). Answer this one with an + // immediate 503 and keep accepting. + Self.refuseBusy(clientFD) + close(clientFD) + continue + } clientQueue.async { [weak self] in // Held by the closure, not by self, so the permit is returned even // if the server was torn down while this connection was queued. @@ -1061,7 +1737,7 @@ private final class BridgeServer: @unchecked Sendable { return } - guard tokenMatches(request.headers[BridgeProtocol.tokenHeaderKey], origin: origin) else { + guard let matchedToken = authenticatedToken(request.headers[BridgeProtocol.tokenHeaderKey], origin: origin) else { onUnauthorized(path) writeJSON(fd, status: "401 Unauthorized", origin: origin, object: [ "error": "Missing or invalid \(BridgeProtocol.tokenHeader)", @@ -1073,7 +1749,10 @@ private final class BridgeServer: @unchecked Sendable { // Heartbeats keep `isExtensionConnected` true while the user reads a page // that produces no new context. if path == "/heartbeat" { - onHeartbeat() + let instance = request.headers[BridgeProtocol.instanceHeaderKey] + let focused = Self.focusedFlag(request.headers[BridgeProtocol.focusedHeaderKey]) + commandQueue.noteSeen(instance: instance, focused: focused) + onSighting(BridgeSighting(token: matchedToken, instance: instance, focused: focused, body: request.body)) writeJSON(fd, status: "200 OK", origin: origin, object: ["ok": true]) return } @@ -1083,9 +1762,26 @@ private final class BridgeServer: @unchecked Sendable { // GET /commands → drain + return the queued commands as JSON. // POST /command-result → hand the structured outcome to the producer. if request.method == "GET" && path == BridgeProtocol.commandsPath { + // Proof of life, same as a heartbeat. The watchdog keeps the extension + // "connected" while its worker is polling. + let instance = request.headers[BridgeProtocol.instanceHeaderKey] + let focused = Self.focusedFlag(request.headers[BridgeProtocol.focusedHeaderKey]) + onSighting(BridgeSighting(token: matchedToken, instance: instance, focused: focused, body: nil)) + let wait = max(0, min(Double(request.headers[BridgeProtocol.longPollHeaderKey] ?? "") ?? 0, + BridgeProtocol.longPollMaxSeconds)) + let (batch, held) = commandQueue.drainDetailed(instance: instance, focused: focused, wait: wait, + clientGone: { Self.peerClosed(fd) }) var headers = corsHeaders(origin: origin) headers["Content-Type"] = "application/json" - write(fd, status: "200 OK", headers: headers, body: onCommandsPoll(request.headers["x-holmes-browser-instance"])) + // "1" only when this request was really held. A poll over the long poll + // cap gets "0" so the worker waits its idle gap instead of spinning. + headers["X-Holmes-Long-Poll"] = held ? "1" : "0" + let body = BrowserCommandQueue.encode(batch, session: commandQueue.session) + // The extension hung up while we waited: hand the commands to the next + // poll instead of losing them in a dead socket. + if !write(fd, status: "200 OK", headers: headers, body: body) { + commandQueue.requeue(batch.map(\.id)) + } return } if request.method == "POST" && path == BridgeProtocol.commandResultPath { @@ -1127,66 +1823,74 @@ private final class BridgeServer: @unchecked Sendable { /// never seen is adopted ONLY inside the window the user armed in Settings — /// see the pairing note at the top of this file. Every comparison is /// constant-time so the port can't be used to guess a token one byte at a time. - private func tokenMatches(_ provided: String?, origin: String?) -> Bool { - guard let provided else { return false } + /// Returns the secret that authenticated the request (the issued token or one + /// of the paired ones), or nil. Every comparison is constant-time. + private func authenticatedToken(_ provided: String?, origin: String?) -> String? { + guard let provided else { return nil } let candidate = provided.trimmingCharacters(in: .whitespaces) - if constantTimeEqual(candidate, token) { return true } + if constantTimeEqual(candidate, token) { return token } lock.lock() - let known = pairedToken + let known = pairedTokens let pairingOpen = (pairingWindowEnds.map { $0 > Date() }) ?? false lock.unlock() - if let known { return constantTimeEqual(candidate, known) } + // Compare against every paired token without an early exit. + var matched: String? + for secret in known where constantTimeEqual(candidate, secret) { matched = secret } + if let matched { return matched } - // Unknown secret, and the user hasn't armed pairing: reject. This is the - // whole fix — adopting here on first contact meant any local process, or - // any page that could clear the preflight, could claim the bridge, lock the - // real extension out permanently, and then feed .exact context straight - // into an agent that holds tool access. - guard pairingOpen else { return false } + // Unknown secret, and the user hasn't armed pairing: reject. Adopting on + // first contact meant any local process, or any page that could clear the + // preflight, could claim the bridge and feed .exact context straight into + // an agent that holds tool access. + guard pairingOpen else { return nil } // Shape check, so a stray probe with an empty or junk header can't consume // the armed window. guard (16...256).contains(candidate.count), candidate.unicodeScalars.allSatisfy({ $0.value > 0x20 && $0.value < 0x7F }) - else { return false } + else { return nil } - // Even inside the window, page JavaScript can never pair: an http(s) - // Origin means the request came from a site, not from the Holmes - // extension's background worker. No Origin at all is fine — that is a - // native client, which the user armed the window for. + // Even inside the window only a browser EXTENSION may pair. An http(s) + // Origin is page JavaScript, and no Origin at all is a native process: + // any app on this Mac could otherwise claim the window the user opened + // for their browser. Native tools use the issued token instead. guard Self.mayPair(origin: origin) else { - print("[Bridge] Refused to pair with origin \(origin ?? "?") — only extension origins may pair") - return false + print("[Bridge] Refused to pair with origin \(origin ?? "none") — only extension origins may pair") + return nil } lock.lock() // Re-check under the lock: two concurrent requests must not both pair. - if let raced = pairedToken { - lock.unlock() - return constantTimeEqual(candidate, raced) - } guard (pairingWindowEnds.map { $0 > Date() }) ?? false else { + let raced = pairedTokens.first { constantTimeEqual(candidate, $0) } lock.unlock() - return false + return raced } - pairedToken = candidate + pairedTokens.insert(candidate) pairingWindowEnds = nil // one-shot: the window closes the moment it is used lock.unlock() onPaired(candidate) - return true + return candidate } - /// Opens the user-armed adoption window (called from Settings). + /// Opens the user-armed adoption window (called from Settings). Existing + /// pairings stay valid. func openPairingWindow(until deadline: Date) { lock.lock() - pairedToken = nil pairingWindowEnds = deadline lock.unlock() } + /// Replaces the accepted paired tokens (after Settings removed one). + func setPairedTokens(_ tokens: [String]) { + lock.lock() + pairedTokens = Set(tokens) + lock.unlock() + } + /// Closes it — on cancel, on expiry, or after a successful pairing. func closePairingWindow() { lock.lock() @@ -1194,14 +1898,17 @@ private final class BridgeServer: @unchecked Sendable { lock.unlock() } - /// Origins allowed to pair. NO Origin header at all means a native client - /// (curl, another Mac app) — permitted, because the user armed the window for - /// exactly that. Any browser-supplied origin must be an extension: a site - /// origin is page JavaScript, and "null" is an opaque browser origin (sandboxed - /// iframe, file://), which is page JavaScript wearing a disguise. - private static func mayPair(origin: String?) -> Bool { + /// Origins allowed to pair: browser extension origins only. Chrome, Comet, Arc, + /// Brave, Edge and other Chromium browsers all post from chrome-extension://. + /// No Origin is a native process, a site origin is page JavaScript, and "null" + /// is an opaque browser origin (sandboxed iframe, file://); none may pair. + /// This keeps web pages out. It does not prove the caller is Holmes: a native + /// process can send any Origin header and every installed extension has an + /// extension origin. The real guards are that the user arms a short one shot + /// window and that the resulting pairing is shown in Settings for removal. + static func mayPair(origin: String?) -> Bool { guard let origin = origin?.trimmingCharacters(in: .whitespaces), - !origin.isEmpty else { return true } + !origin.isEmpty else { return false } return isExtensionOrigin(origin) } @@ -1268,10 +1975,27 @@ private final class BridgeServer: @unchecked Sendable { if !key.isEmpty { headers[key] = value } } + // Command results may be large (screenshots, extracts); page context may not. + let bareRequestPath = path.components(separatedBy: "?").first ?? path + let limit = (method == "POST" && bareRequestPath == BridgeProtocol.commandResultPath) + ? BridgeProtocol.maxCommandResultBytes : maxBodyBytes let contentLength = Int(headers["content-length"] ?? "") ?? 0 - guard contentLength >= 0, contentLength <= maxBodyBytes else { + guard contentLength >= 0 else { return nil } + guard contentLength <= limit else { + // Drain first (bounded by size and the request deadline). Replying 413 + // and closing with unread bytes makes the kernel reset the connection, + // which the extension saw as a network error and surfaced as a timeout. + let alreadyRead = buffer.count - buffer.distance(from: buffer.startIndex, to: end.upperBound) + var remaining = contentLength - alreadyRead + if contentLength <= BridgeProtocol.maxDrainBytes { + while remaining > 0, Date() < deadline { + let n = recv(fd, &chunk, min(chunk.count, remaining), 0) + if n <= 0 { break } + remaining -= n + } + } writeJSON(fd, status: "413 Payload Too Large", origin: headers["origin"], - object: ["error": "Body exceeds \(maxBodyBytes) bytes"]) + object: ["error": "Body exceeds \(limit) bytes", "limit": limit, "received": contentLength]) return nil } @@ -1279,16 +2003,12 @@ private final class BridgeServer: @unchecked Sendable { // before that point yields a truncated payload, which is not a request: // drop the connection rather than handing half a DOM to the parser. var body = Data(buffer[end.upperBound...]) + body.reserveCapacity(contentLength) while body.count < contentLength { guard Date() < deadline else { return nil } let n = recv(fd, &chunk, chunk.count, 0) if n <= 0 { return nil } body.append(contentsOf: chunk[0.. maxBodyBytes { - writeJSON(fd, status: "413 Payload Too Large", origin: headers["origin"], - object: ["error": "Body exceeds \(maxBodyBytes) bytes"]) - return nil - } } if contentLength > 0 { body = body.prefix(contentLength) } @@ -1324,7 +2044,10 @@ private final class BridgeServer: @unchecked Sendable { write(fd, status: status, headers: headers, body: body) } - private func write(_ fd: Int32, status: String, headers: [String: String], body: Data) { + /// True when every byte was handed to the kernel and the peer had not already + /// hung up. A long poll uses this to requeue commands it could not deliver. + @discardableResult + private func write(_ fd: Int32, status: String, headers: [String: String], body: Data) -> Bool { var head = "HTTP/1.1 \(status)\r\n" var headers = headers headers["Content-Length"] = "\(body.count)" @@ -1332,16 +2055,44 @@ private final class BridgeServer: @unchecked Sendable { for (key, value) in headers { head += "\(key): \(value)\r\n" } head += "\r\n" + if Self.peerClosed(fd) { return false } var out = Data(head.utf8) out.append(body) - out.withUnsafeBytes { raw in - guard let base = raw.bindMemory(to: UInt8.self).baseAddress else { return } + return out.withUnsafeBytes { raw -> Bool in + guard let base = raw.bindMemory(to: UInt8.self).baseAddress else { return false } var sent = 0 while sent < out.count { let n = send(fd, base + sent, out.count - sent, 0) - if n <= 0 { break } + if n <= 0 { return false } sent += n } + return true } } + + /// The worker's "one of my windows has OS focus" header, or nil when absent. + static func focusedFlag(_ value: String?) -> Bool? { + guard let value = value?.trimmingCharacters(in: .whitespaces).lowercased(), !value.isEmpty else { return nil } + return value == "1" || value == "true" + } + + /// Minimal 503 for a connection that arrived while every handler was busy. + static func refuseBusy(_ fd: Int32) { + let reply = "HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\nRetry-After: 1\r\n\r\n" + _ = reply.withCString { send(fd, $0, strlen($0), 0) } + } + + /// Non-blocking check for a client that already closed its end. A readable + /// socket that yields zero bytes on a peek is an orderly shutdown. + static func peerClosed(_ fd: Int32) -> Bool { + var descriptor = pollfd(fd: fd, events: Int16(POLLIN), revents: 0) + let ready = poll(&descriptor, 1, 0) + guard ready > 0 else { return false } + if descriptor.revents & Int16(POLLHUP | POLLERR | POLLNVAL) != 0 { return true } + var byte: UInt8 = 0 + let peeked = recv(fd, &byte, 1, MSG_PEEK | MSG_DONTWAIT) + if peeked == 0 { return true } + if peeked < 0 { return errno != EAGAIN && errno != EWOULDBLOCK } + return false + } } diff --git a/holmes/holmes/Core/ComputerUseEngine.swift b/holmes/holmes/Core/ComputerUseEngine.swift index d758339..67b3186 100644 --- a/holmes/holmes/Core/ComputerUseEngine.swift +++ b/holmes/holmes/Core/ComputerUseEngine.swift @@ -96,29 +96,58 @@ final class ComputerUseEngine { // MARK: - Session kill switch - /// Set by the global ⌘⌥Esc hotkey (and any "Stop" affordance) to abort an - /// in-flight run. Checked at the top of every `perform` — i.e. before any - /// event is posted — so the very next primitive the model asks for returns a - /// terminal outcome and the loop winds down. Reset by `beginRun()`. - private(set) var isCancelled: Bool = false - - /// The most recent frame the model was shown. A click/type/scroll is mapped - /// through THIS capture's geometry, so coordinates are always interpreted in - /// the pixel space of the screenshot the model actually reasoned about (never - /// a fresher frame the model hasn't seen). Reset by `beginRun()`. - private var lastCapture: ComputerUseCapture? - - /// Clears the kill flag and the stale capture at the start of a user-initiated - /// run. Called by HolmesBrain.run(goal:) — the only path that offers `computer`. - func beginRun() { - isCancelled = false - lastCapture = nil - } - - /// Flips the kill flag. Idempotent and safe to call from the hotkey handler - /// mid-run; the in-flight primitive finishes, and the next one aborts. + /// Kill switches and screenshots are owned PER RUN (see + /// ComputerUseRunRegistry). The run acting right now is the task local + /// `ComputerUseRunScope.token`; work with no token shares one unscoped slot. + private let runs = ComputerUseRunRegistry() + + private var currentRunToken: ComputerUseRunToken? { ComputerUseRunScope.token } + + /// True when the run in scope was stopped (by its owner, or by ⌘⌥Esc / + /// Pause, which stop every run). Checked at the top of every `perform`, + /// before any event is posted, so the next primitive returns a terminal + /// outcome and the loop winds down. + var isCancelled: Bool { runs.isCancelled(currentRunToken) } + + func isCancelled(_ token: ComputerUseRunToken?) -> Bool { runs.isCancelled(token) } + + /// The most recent frame THIS run's model was shown. A click/type/scroll is + /// mapped through this capture's geometry, so coordinates are interpreted in + /// the pixel space of the screenshot the model actually reasoned about, never + /// a fresher frame, and never a frame another concurrent run captured. + private var lastCapture: ComputerUseCapture? { + get { runs.capture(for: currentRunToken) } + set { runs.setCapture(newValue, for: currentRunToken) } + } + + /// Starts a fresh run with its own kill switch and no capture. A run begun + /// while another run is in scope is nested in it, so stopping the outer run + /// stops this one too. Never resets any other run. Pair with `endRun`, and + /// perform the run's work inside `ComputerUseRunScope.$token.withValue`. + @discardableResult + func beginRun() -> ComputerUseRunToken { + if currentRunToken == nil { + // A user initiated action with no run of its own re arms only the + // shared unscoped slot. + runs.resetUnscoped() + } + return runs.begin(parent: currentRunToken) + } + + func endRun(_ token: ComputerUseRunToken) { + runs.end(token) + } + + /// Stop all: flips the kill switch of EVERY run. Idempotent and safe to call + /// from the ⌘⌥Esc handler mid run; each in flight primitive finishes, and + /// the next one aborts. func cancelRun() { - isCancelled = true + runs.cancelAll() + } + + /// Stops one run (and anything nested in it), leaving other runs alone. + func cancelRun(_ token: ComputerUseRunToken) { + runs.cancel(token) } // MARK: - Permissions (refuse, never force-enable) diff --git a/holmes/holmes/Core/ComputerUseRunRegistry.swift b/holmes/holmes/Core/ComputerUseRunRegistry.swift new file mode 100644 index 0000000..bd95de3 --- /dev/null +++ b/holmes/holmes/Core/ComputerUseRunRegistry.swift @@ -0,0 +1,130 @@ +import Foundation + +// MARK: - Computer use run ownership +// +// Every computer control session (a user request, an autonomous plan, an undo) +// owns a token. The kill switch and the "last screenshot the model saw" belong +// to that token, never to the whole process: starting a second run must not +// disarm ⌘⌥Esc for a run that is already in flight, and a click must never be +// mapped through a screenshot another run captured. +// +// A run started while another run is in scope becomes its CHILD (the runner's +// model segment drives HolmesBrain.run), so cancelling the parent stops the +// nested session as well. Stop all (⌘⌥Esc, Pause, sleep) cancels every token. + +struct ComputerUseRunToken: Hashable, Sendable { + let id: UUID + init() { id = UUID() } +} + +/// The run the current task is acting for. Set with +/// `ComputerUseRunScope.$token.withValue(token) { … }`; task locals flow through +/// awaits, child tasks and the model client's tool callbacks. +enum ComputerUseRunScope { + @TaskLocal static var token: ComputerUseRunToken? +} + +@MainActor +final class ComputerUseRunRegistry { + private struct Entry { + let parent: ComputerUseRunToken? + var cancelled = false + var capture: Capture? + } + + private var entries: [ComputerUseRunToken: Entry] = [:] + /// Runs holding a capture, oldest first. Only CAPTURES are bounded (they + /// are full screenshots); a run's kill switch entry lives until `end`, so a + /// long run can never be evicted and misread as cancelled. + private var captureOrder: [ComputerUseRunToken] = [] + /// Work that runs with no token in scope (a Settings self test, a + /// standalone key press) shares one slot so a screenshot then click still + /// map against the same frame, exactly like the historical single run. + let unscoped = ComputerUseRunToken() + /// Most runs that keep a screenshot at once. + private let capacity: Int + + init(capacity: Int = 64) { + self.capacity = max(4, capacity) + } + + var activeCount: Int { entries.count } + + /// Registers a fresh run. It starts uncancelled with no capture, and never + /// touches any other run's state. + @discardableResult + func begin(parent: ComputerUseRunToken? = nil) -> ComputerUseRunToken { + let token = ComputerUseRunToken() + let knownParent = parent.flatMap { entries[$0] == nil ? nil : $0 } + entries[token] = Entry(parent: knownParent) + return token + } + + func end(_ token: ComputerUseRunToken) { + entries.removeValue(forKey: token) + captureOrder.removeAll { $0 == token } + } + + /// Cancels one run (and, through `isCancelled`, every run nested in it). + func cancel(_ token: ComputerUseRunToken) { + if token == unscoped { + unscopedCancelled = true + return + } + entries[token]?.cancelled = true + } + + /// Stop all: every registered run and the unscoped slot. + func cancelAll() { + for key in entries.keys { entries[key]?.cancelled = true } + unscopedCancelled = true + } + + /// Re-arms only the unscoped slot (a user initiated action with no run + /// of its own). Registered runs are untouched. + func resetUnscoped() { + unscopedCancelled = false + unscopedCapture = nil + } + + private var unscopedCancelled = false + private var unscopedCapture: Capture? + + func isCancelled(_ token: ComputerUseRunToken?) -> Bool { + guard let token, token != unscoped else { return unscopedCancelled } + var cursor: ComputerUseRunToken? = token + var hops = 0 + while let current = cursor, hops <= entries.count { + guard let entry = entries[current] else { + // An ended run can no longer act; a parent that ended does not + // cancel a child that is still running. + return current == token + } + if entry.cancelled { return true } + cursor = entry.parent + hops += 1 + } + return false + } + + func capture(for token: ComputerUseRunToken?) -> Capture? { + guard let token, token != unscoped else { return unscopedCapture } + return entries[token]?.capture + } + + func setCapture(_ capture: Capture?, for token: ComputerUseRunToken?) { + guard let token, token != unscoped else { + unscopedCapture = capture + return + } + guard entries[token] != nil else { return } + entries[token]?.capture = capture + captureOrder.removeAll { $0 == token } + guard capture != nil else { return } + captureOrder.append(token) + while captureOrder.count > capacity { + let oldest = captureOrder.removeFirst() + entries[oldest]?.capture = nil + } + } +} diff --git a/holmes/holmes/Core/HolmesAgent.swift b/holmes/holmes/Core/HolmesAgent.swift index 11101c4..5e5c9f4 100644 --- a/holmes/holmes/Core/HolmesAgent.swift +++ b/holmes/holmes/Core/HolmesAgent.swift @@ -968,10 +968,11 @@ final class HolmesAgent { } private static func parseEnrichment(_ raw: String) -> Enrichment? { - guard let start = raw.firstIndex(of: "{"), let end = raw.lastIndex(of: "}"), start < end, - let data = String(raw[start...end]).data(using: .utf8), - let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] - else { return nil } + // First balanced object carrying an enrichment field; trailing prose + // with its own braces no longer breaks a first "{" to last "}" slice. + guard let object = ModelJSON.firstObject(in: raw, where: { object in + ["goal", "lastMessageGist", "headline"].contains { object[$0] is String } + }) else { return nil } func string(_ key: String) -> String { (object[key] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines) } diff --git a/holmes/holmes/Core/HolmesBrain.swift b/holmes/holmes/Core/HolmesBrain.swift index 855b0af..c4d83f9 100644 --- a/holmes/holmes/Core/HolmesBrain.swift +++ b/holmes/holmes/Core/HolmesBrain.swift @@ -133,6 +133,21 @@ final class HolmesBrain { narrateAloud: Bool = true, log: @escaping @MainActor (String) -> Void) async -> RunResult { guard !Task.isCancelled else { return .cancelled } + // Every run owns its computer control kill switch and screenshot, so a + // second request can never disarm ⌘⌥Esc for, or map clicks through the + // frame of, a run already in flight. + let engine = ComputerUseEngine.shared + let runToken = engine.beginRun() + defer { engine.endRun(runToken) } + return await ComputerUseRunScope.$token.withValue(runToken) { + await runInScope(goal: goal, narrateAloud: narrateAloud, log: log) + } + } + + private func runInScope(goal: String, + narrateAloud: Bool, + log: @escaping @MainActor (String) -> Void) async -> RunResult { + guard !Task.isCancelled else { return .cancelled } guard OllamaConfig.isConfigured else { return .notConfigured } let narrates = narrateAloud && ClickyController.shared.narrateActionsEnabled @@ -151,29 +166,35 @@ final class HolmesBrain { // model's job. A master-switch refusal also falls through: type_text, // MCP and browser tools need no switch, so the model may still succeed. if let (appName, text) = Self.typeIntoAppIntent(in: goal), Self.isExactInstalledApp(appName) { - ComputerUseEngine.shared.beginRun() let opened = await ComputerUseEngine.shared.perform(action: "open_app", input: ["name": appName]) if !opened.isRefused && !opened.isError { do { try await Task.sleep(nanoseconds: 900_000_000) } catch { return .cancelled } guard !Task.isCancelled else { return .cancelled } - let approved = await approve(title: "Type into \(appName)", preview: text, app: appName) - guard !Task.isCancelled, let approvedText = approved else { return .cancelled } - var typed = false + let tracked = await ApprovalTimeoutTracking.run { + await approve(title: "Type into \(appName)", preview: text, app: appName) + } + if tracked.timedOut { return .failed(ApprovalScope.timedOutMessage + ". Nothing was typed.") } + guard !Task.isCancelled, let approvedText = tracked.result else { return .cancelled } + var entry = TextEntryResult.failed("the app isn't running") if let running = ActionExecutor.shared.runningApp(named: appName) { - typed = await typeIntoApp(running, text: approvedText) + entry = await typeIntoAppResult(running, text: approvedText) + } + let result: String + switch entry { + case .verified: result = "Opened \(appName) and typed it." + case .unverified: result = "Opened \(appName) and typed it, but couldn't confirm the text landed. Check the app." + case .failed: result = "Opened \(appName) but couldn't type into it — click into a note or field and try again." } - let result = typed ? "Opened \(appName) and typed it." : "Opened \(appName) but couldn't type into it — click into a note or field and try again." guard !Task.isCancelled else { return .cancelled } log(result) if narrates { SpeechSynthesizer.shared.enqueue(result, priority: .utterance) } - return typed ? .text(result) : .failed(result) + return entry.succeeded ? .text(result) : .failed(result) } // Refused or unknown app — let the model interpret the whole goal. } if let appName = Self.openAppIntent(in: goal), Self.isExactInstalledApp(appName) { - ComputerUseEngine.shared.beginRun() let outcome = await ComputerUseEngine.shared.perform(action: "open_app", input: ["name": appName]) guard !Task.isCancelled else { return .cancelled } if !outcome.isRefused && !outcome.isError { @@ -197,10 +218,9 @@ final class HolmesBrain { // Pin this run's screenshot resolution BEFORE building `builtinTools` and // the system prompt, so the `computer` tool's declared pixel space // (W×H in its description) equals the pixel dims every screenshot in the - // run is resized to. Reset the computer engine's kill flag + stale - // capture for a fresh session. + // run is resized to. The computer engine's kill switch and capture are + // already fresh: `run` opened this session's own run token. WindowCapture.resolveForCurrentRun() - ComputerUseEngine.shared.beginRun() let tools = builtinTools + Self.relevantMCPTools(MCPClient.shared.toolDefs(), for: goal) // The system prompt is split into the stable guidelines and the per-run // screen context. There is no prompt cache to protect with a local @@ -282,6 +302,9 @@ final class HolmesBrain { return .failed("The local model \(model) isn't downloaded — download it in Settings ▸ Local Model, then try again.") } catch OllamaClient.AgentError.busy { return .failed("The local model is busy — try again in a moment.") + } catch let OllamaClient.AgentError.timedOut(detail) { + // OllamaClient already asked OllamaServer to re-probe the server. + return .failed("The local model stopped responding (\(detail)). Check the app before retrying.") } catch OllamaClient.AgentError.truncated { return .failed("Local model error: the model ran out of output tokens before finishing. Try a shorter goal, or raise the output/context limits in Settings ▸ Local Model.") } catch OllamaClient.AgentError.notConfigured { @@ -932,7 +955,17 @@ final class HolmesBrain { } } + /// Dispatches one tool call. When an approval it raised timed out, the + /// model hears exactly that, never "the user declined". private func runTool(name: String, input: [String: Any]) async -> OllamaClient.ToolResult { + let tracked = await ApprovalTimeoutTracking.run { await dispatchTool(name: name, input: input) } + guard tracked.timedOut else { return tracked.result } + return OllamaClient.ToolResult( + "\(ApprovalScope.timedOutMessage): nobody answered the approval card in time, so \(name) was not run. Do not retry it; end your turn and report that approval timed out.", + isError: true) + } + + private func dispatchTool(name: String, input: [String: Any]) async -> OllamaClient.ToolResult { switch name { case "read_screen": return readScreen() case "zoom_screen": return await zoomScreen(input) @@ -1035,27 +1068,34 @@ final class HolmesBrain { guard let running = ActionExecutor.shared.runningApp(named: app) else { return OllamaClient.ToolResult("Could not find app '\(app)' to type into. Open it first with the computer tool's open_app.", isError: true) } - let ok = await typeIntoApp(running, text: approved) - return OllamaClient.ToolResult(ok ? "Typed the text into \(app)." : "Failed to type into \(app).", isError: !ok) + let entry = await typeIntoAppResult(running, text: approved) + return OllamaClient.ToolResult(entry.describe(action: "Typed the text", app: app), isError: !entry.succeeded) } /// Activates the app, makes sure something editable has focus (a fresh /// Notes/TextEdit window with no document swallows keystrokes — ⌘N fixes /// that), then types. func typeIntoApp(_ app: NSRunningApplication, text: String) async -> Bool { - guard !Task.isCancelled else { return false } + await typeIntoAppResult(app, text: text).succeeded + } + + /// Same as typeIntoApp, but says whether the text was verified in the field. + func typeIntoAppResult(_ app: NSRunningApplication, text: String) async -> TextEntryResult { + let stopped = TextEntryResult.failed("Stopped.") + guard !Task.isCancelled else { return stopped } app.activate(options: [.activateIgnoringOtherApps]) do { try await Task.sleep(nanoseconds: 450_000_000) } - catch { return false } - guard !Task.isCancelled else { return false } + catch { return stopped } + guard !Task.isCancelled else { return stopped } let editors: Set = ["com.apple.Notes", "com.apple.TextEdit", "com.apple.iWork.Pages", "com.apple.Stickies"] if let bundle = app.bundleIdentifier, editors.contains(bundle), !ActionExecutor.shared.hasEditableFocus(in: app) { _ = await ComputerUseEngine.shared.perform(action: "key", input: ["text": "cmd+n"]) do { try await Task.sleep(nanoseconds: 600_000_000) } - catch { return false } + catch { return stopped } } - guard !Task.isCancelled else { return false } - return await offMain { ActionExecutor.shared.typeIntoFocusedField(in: app, text: text) } + guard !Task.isCancelled else { return stopped } + // Nonisolated async: the AX work and paced key events run off the main thread. + return await ActionExecutor.shared.typeIntoFocusedField(in: app, text: text) } private func sendMessage(_ input: [String: Any]) async -> OllamaClient.ToolResult { @@ -1068,8 +1108,10 @@ final class HolmesBrain { return OllamaClient.ToolResult("User declined to send the message.") } guard !Task.isCancelled else { return OllamaClient.ToolResult("Stopped", isError: true) } - let ok = await offMain { ActionExecutor.shared.sendMessageInApp(app, message: approved) } - return OllamaClient.ToolResult(ok ? "Placed the message into \(app)'s input field." : "Failed to send.", isError: !ok) + // Places the text at the cursor (no select all). AppleScript inside runs on the main actor. + let entry = await ActionExecutor.shared.sendMessageInApp(app, message: approved) + return OllamaClient.ToolResult(entry.describe(action: "Placed the message into the input field", app: app), + isError: !entry.succeeded) } private func openURL(_ input: [String: Any]) async -> OllamaClient.ToolResult { @@ -1096,8 +1138,20 @@ final class HolmesBrain { return OllamaClient.ToolResult("Could not find app '\(app)'.", isError: true) } guard !Task.isCancelled else { return OllamaClient.ToolResult("Stopped", isError: true) } - let ok = await offMain { ActionExecutor.shared.clickButton(label: label, in: running) } - return OllamaClient.ToolResult(ok ? "Clicked '\(label)'." : "Could not find a button labeled '\(label)'.", isError: !ok) + // The user approved clicking "label". If that label only fuzzily + // matched a send/submit class control, do not press it on this approval. + let allowCommit = CommitControlGate.looksLikeCommit(label) + let outcome = await offMain { ActionExecutor.shared.pressControl(label: label, in: running, allowCommit: allowCommit) } + switch outcome { + case .pressed(let matched): + return OllamaClient.ToolResult("Clicked '\(matched)'.") + case .needsConfirmation(let matched): + return OllamaClient.ToolResult("Did not click: '\(label)' matched '\(matched)', which sends or commits. Ask for that control by its exact name so the user can approve it.", isError: true) + case .notFound: + return OllamaClient.ToolResult("Could not find a button labeled '\(label)'.", isError: true) + case .failed(let code): + return OllamaClient.ToolResult("The button labeled '\(label)' refused the press (AXError \(code)).", isError: true) + } } /// The producer half of the browser-automation channel: maps a model @@ -1269,6 +1323,14 @@ final class HolmesBrain { switch await ConfirmationBus.shared.decide(action) { case .approved(let text): return Task.isCancelled ? nil : text case .dismissed: return nil + case .timedOut: + // Only unattended (autonomous) work sets a deadline; show why it + // stopped, and let the tool call report a timeout, not a decline. + ApprovalTimeoutTracking.flag?.markTimedOut() + if let activity = WorkActivityScope.id { + WorkActivityCenter.shared.update(activity, phase: .working, detail: ApprovalScope.timedOutMessage) + } + return nil } } diff --git a/holmes/holmes/Core/ModelJSON.swift b/holmes/holmes/Core/ModelJSON.swift new file mode 100644 index 0000000..aa22f17 --- /dev/null +++ b/holmes/holmes/Core/ModelJSON.swift @@ -0,0 +1,181 @@ +import Foundation + +// MARK: - ModelJSON +// +// One robust reader for JSON a local model wrote. Grammar constrained output is +// usually clean, but a degraded reply wraps the object in code fences, leads +// with prose, trails prose that itself contains braces ("{…} Hope that helps +// {smile}"), or puts raw newlines inside string values. Slicing from the first +// "{" to the LAST "}" breaks on every one of those; this scanner finds each +// balanced top level object, respecting strings and escapes, and returns the +// first one the caller accepts. + +enum ModelJSON { + /// Longest reply scanned, and most object starts retried, so a pathological + /// reply cannot turn parsing into quadratic work. + static let maxScannedCharacters = 200_000 + static let maxCandidates = 64 + + /// The first JSON object in `raw` that parses and satisfies `accept`. + static func firstObject(in raw: String, + where accept: ([String: Any]) -> Bool = { _ in true }) -> [String: Any]? { + let text = raw.count > maxScannedCharacters ? String(raw.prefix(maxScannedCharacters)) : raw + if let object = scan(text, accept: accept) { return object } + // A fence marker can sit inside the scanned region in odd ways (a + // backtick run glued to the brace); retry once without fence lines. + let unfenced = stripCodeFences(text) + return unfenced == text ? nil : scan(unfenced, accept: accept) + } + + /// Every balanced top level object candidate text, in order of appearance. + static func objectCandidates(in raw: String) -> [String] { + var results: [String] = [] + var searchFrom = raw.startIndex + var attempts = 0 + while attempts < maxCandidates, let start = raw[searchFrom...].firstIndex(of: "{") { + attempts += 1 + if let range = balancedObjectRange(in: raw, startingAt: start) { + results.append(String(raw[range])) + searchFrom = range.upperBound + } else { + searchFrom = raw.index(after: start) + } + } + return results + } + + /// Removes Markdown code fence lines (```json, ```), wherever they appear. + static func stripCodeFences(_ raw: String) -> String { + raw.components(separatedBy: "\n") + .filter { !$0.trimmingCharacters(in: .whitespaces).hasPrefix("```") } + .joined(separator: "\n") + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + private static func scan(_ raw: String, accept: ([String: Any]) -> Bool) -> [String: Any]? { + var searchFrom = raw.startIndex + var attempts = 0 + while attempts < maxCandidates, let start = raw[searchFrom...].firstIndex(of: "{") { + attempts += 1 + if let range = balancedObjectRange(in: raw, startingAt: start) { + let candidate = normalizeNewlinesInsideStrings(String(raw[range])) + if let data = candidate.data(using: .utf8), + let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], + accept(object) { + return object + } + } + // Retry from the next brace: prose like "use {this} form: {…}" + // must not hide the real object behind a non JSON brace pair, and a + // rejected wrapper may still contain the object the caller wants. + searchFrom = raw.index(after: start) + } + return nil + } + + /// The balanced `{…}` beginning at `start`, string and escape aware so braces + /// inside JSON string values cannot unbalance the scan. + static func balancedObjectRange(in raw: String, startingAt start: String.Index) -> Range? { + guard start < raw.endIndex, raw[start] == "{" else { return nil } + var depth = 0 + var inString = false + var escaped = false + var index = start + while index < raw.endIndex { + let character = raw[index] + if escaped { + escaped = false + } else if inString { + if character == "\\" { escaped = true } + else if character == "\"" { inString = false } + } else { + switch character { + case "\"": inString = true + case "{": depth += 1 + case "}": + depth -= 1 + if depth == 0 { return start.. String { + var out = String() + out.reserveCapacity(candidate.count + 8) + var inString = false + var escaped = false + for character in candidate { + if escaped { + escaped = false + out.append(character) + continue + } + if inString { + switch character { + case "\\": escaped = true; out.append(character) + case "\"": inString = false; out.append(character) + case "\n": out.append("\\n") + case "\r": out.append("\\r") + case "\t": out.append("\\t") + default: out.append(character) + } + } else { + if character == "\"" { inString = true } + out.append(character) + } + } + return out + } +} + +// MARK: - One repair attempt + +enum ModelJSONRepair { + struct Outcome { + let value: Value? + /// True when the value came from the repair reply. + let repaired: Bool + /// A user facing reason when both attempts failed. + let failure: String? + } + + /// Parses `raw`; when that fails, asks for ONE repaired reply and parses it. + /// Never loops: a model that cannot produce the shape twice is reported. + static func parse(_ raw: String, + what: String, + attempt: (String) -> Value?, + repair: (String) async throws -> String) async -> Outcome { + if let value = attempt(raw) { return Outcome(value: value, repaired: false, failure: nil) } + let repairedRaw: String + do { + repairedRaw = try await repair(raw) + } catch is CancellationError { + return Outcome(value: nil, repaired: false, failure: "Stopped.") + } catch { + return Outcome(value: nil, repaired: false, + failure: "The local model's \(what) was unreadable, and the repair request failed: \(error.localizedDescription)") + } + if let value = attempt(repairedRaw) { return Outcome(value: value, repaired: true, failure: nil) } + return Outcome(value: nil, repaired: false, + failure: "The local model returned an unreadable \(what) twice. Nothing was run.") + } + + /// The short repair prompt: the broken reply goes back with the one job of + /// returning the same content as a single valid JSON object. + static func repairPrompt(for raw: String, shape: String) -> String { + """ + Your previous reply could not be parsed as JSON. Return the SAME content as ONE valid JSON object with this shape and nothing else, no prose and no code fences: + \(shape) + + Previous reply: + \(String(raw.prefix(6000))) + """ + } +} diff --git a/holmes/holmes/Core/OllamaClient.swift b/holmes/holmes/Core/OllamaClient.swift index f6b027e..923d3b2 100644 --- a/holmes/holmes/Core/OllamaClient.swift +++ b/holmes/holmes/Core/OllamaClient.swift @@ -87,6 +87,9 @@ actor OllamaClient { case busy /// Kept for API parity (a hosted model can decline); never thrown here. case refused(String) + /// No response in time, or the stream went silent mid answer. The + /// request is safe to try again once the server answers. + case timedOut(String) var errorDescription: String? { switch self { @@ -99,6 +102,7 @@ actor OllamaClient { case .truncated: return "The model ran out of output tokens before answering" case .busy: return "The local model is busy" case .refused(let m): return m + case .timedOut(let m): return "The local model stopped responding (\(m)). Holmes is rechecking the Ollama server; try again in a moment." } } } @@ -386,7 +390,10 @@ actor OllamaClient { // A thinking-capable model may deliberate even with // think:false (qwen3-vl's thinking tags do); leave // headroom so the answer is not guillotined. - numPredict: OllamaConfig.agentNumPredict + (caps.thinking ? 1536 : 0)) + numPredict: OllamaConfig.agentNumPredict + (caps.thinking ? 1536 : 0), + // Never retry once a tool has taken effect in this + // session: the failure is surfaced instead. + allowTransientRetry: toolCalls == 0) release() } catch { release() @@ -489,36 +496,67 @@ actor OllamaClient { /// `{"action":"screenshot"}` (bare computer-tool arguments). Returns nil for /// anything that is not unambiguously a call to one of `tools`. nonisolated static func toolCallFromContent(_ text: String, tools: [ToolDef]) -> ToolCall? { - // The whole message (after fence stripping) must BE the JSON object. A - // final prose answer that merely quotes an example call ("I clicked - // using {"action":…} and it worked") must not be re-executed. - let t = stripCodeFences(text).trimmingCharacters(in: .whitespacesAndNewlines) - guard t.hasPrefix("{"), t.hasSuffix("}") else { return nil } - let candidate = t - guard let data = candidate.data(using: .utf8), - let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return nil } let names = tools.map { $0.name } func match(_ raw: String) -> String? { if names.contains(raw) { return raw } return names.first { $0.lowercased() == raw.lowercased() } } - // {"name": …, "parameters"/"arguments"/"input": {…}} - for key in ["name", "tool", "function", "tool_name"] { - if let raw = obj[key] as? String, let name = match(raw) { - let args = (obj["parameters"] as? [String: Any]) ?? (obj["arguments"] as? [String: Any]) - ?? (obj["input"] as? [String: Any]) ?? [:] - return ToolCall(id: nil, name: name, arguments: args) + func namedCall(_ obj: [String: Any]) -> ToolCall? { + // {"name": …, "parameters"/"arguments"/"input": {…}} + for key in ["name", "tool", "function", "tool_name"] { + if let raw = obj[key] as? String, let name = match(raw) { + let args = (obj["parameters"] as? [String: Any]) ?? (obj["arguments"] as? [String: Any]) + ?? (obj["input"] as? [String: Any]) ?? [:] + return ToolCall(id: nil, name: name, arguments: args) + } } + // {"function": {"name": …, "arguments": {…}}} + if let fn = obj["function"] as? [String: Any], let raw = fn["name"] as? String, let name = match(raw) { + return ToolCall(id: nil, name: name, arguments: (fn["arguments"] as? [String: Any]) ?? [:]) + } + return nil } - // {"function": {"name": …, "arguments": {…}}} - if let fn = obj["function"] as? [String: Any], let raw = fn["name"] as? String, let name = match(raw) { - return ToolCall(id: nil, name: name, arguments: (fn["arguments"] as? [String: Any]) ?? [:]) - } - // Bare computer-tool arguments. - if obj["action"] is String, let name = match("computer") { - return ToolCall(id: nil, name: name, arguments: obj) + + // Only a message that IS a call is one: the whole message, or a code + // fence that ends the message after at most a short lead in. A final + // answer that quotes a past call ("Opened it with {…open_app…}.") must + // never be re executed. + guard let (obj, nothingBefore) = callObject(in: text) else { return nil } + if let call = namedCall(obj) { return call } + // Bare computer arguments carry no tool name: only with no lead in. + guard nothingBefore, obj["action"] is String, let name = match("computer") else { return nil } + return ToolCall(id: nil, name: name, arguments: obj) + } + + /// Longest sentence allowed before a fenced tool call ("I'll take a screenshot first."). + nonisolated static let maxToolCallLeadIn = 160 + + /// The JSON object a message consists of: the entire message, or the body + /// of a code fence that closes the message (nothing after it) with at most + /// `maxToolCallLeadIn` characters before it. `nothingBefore` is false when + /// a lead in precedes the fence. + nonisolated static func callObject(in text: String) -> (object: [String: Any], nothingBefore: Bool)? { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + var body = trimmed + var leadIn = "" + if let open = trimmed.range(of: "```") { + leadIn = String(trimmed[.. ChatReply { + numPredict: Int, + allowTransientRetry: Bool = false) async throws -> ChatReply { var body: [String: Any] = [ "model": model, "messages": messages, @@ -802,15 +842,32 @@ actor OllamaClient { var thinking = "" var rawToolCalls: [[String: Any]] = [] var doneReason = "stop" + var receivedAny = false + var retried = false - try await streamNDJSON(path: "/api/chat", body: body) { chunk in - if let message = chunk["message"] as? [String: Any] { - if let c = message["content"] as? String { content += c } - if let t = message["thinking"] as? String { thinking += t } - if let calls = message["tool_calls"] as? [[String: Any]] { rawToolCalls += calls } - } - if (chunk["done"] as? Bool) == true { - doneReason = (chunk["done_reason"] as? String) ?? "stop" + while true { + do { + try await streamNDJSON(path: "/api/chat", body: body) { chunk in + receivedAny = true + if let message = chunk["message"] as? [String: Any] { + if let c = message["content"] as? String { content += c } + if let t = message["thinking"] as? String { thinking += t } + if let calls = message["tool_calls"] as? [[String: Any]] { rawToolCalls += calls } + } + if (chunk["done"] as? Bool) == true { + doneReason = (chunk["done_reason"] as? String) ?? "stop" + } + } + break + } catch let error as AgentError { + // One short retry for a dropped/refused connection that produced + // nothing yet. Timeouts, HTTP errors and partial streams are not + // retried: they are reported so the user can decide. + guard allowTransientRetry, !retried, !receivedAny, Self.isTransientConnectionFailure(error) else { + throw error + } + retried = true + try await Task.sleep(nanoseconds: UInt64(max(0, OllamaConfig.transientRetryDelay) * 1_000_000_000)) } } @@ -883,8 +940,27 @@ actor OllamaClient { let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] throw Self.mapHTTP(status: status, json: json, data: data, body: body) } + // Stall watchdog: once output has started, silence longer than + // streamStallTimeout cancels the transfer and reports a timeout. The + // first byte may still take as long as a cold model load needs. + let activity = StreamActivity() + let stallLimit = max(0.05, OllamaConfig.streamStallTimeout) + let transfer = bytes.task + let watchdog = Task.detached { + let tick = UInt64(min(1.0, stallLimit / 4) * 1_000_000_000) + while !Task.isCancelled { + try? await Task.sleep(nanoseconds: tick) + if let idle = activity.secondsSinceLastChunk(), idle > stallLimit { + activity.markStalled() + transfer.cancel() + return + } + } + } + defer { watchdog.cancel() } do { for try await line in bytes.lines { + activity.touch() guard let data = line.data(using: .utf8), let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { continue } if let err = obj["error"] as? String { @@ -895,13 +971,39 @@ actor OllamaClient { } onChunk(obj) } + if activity.didStall { throw Self.stalled(after: stallLimit) } } catch let e as AgentError { throw e } catch { + if activity.didStall { throw Self.stalled(after: stallLimit) } throw try Self.mapTransport(error) } } + nonisolated private static func stalled(after seconds: TimeInterval) -> AgentError { + OllamaConfig.onModelTransportFailure?() + return .timedOut("no output for \(Int(seconds.rounded())) seconds") + } + + nonisolated static func isTransientConnectionFailure(_ error: AgentError) -> Bool { + if case .serverUnreachable = error { return true } + return false + } + + /// Last streamed chunk time, shared with the stall watchdog task. + private final class StreamActivity: @unchecked Sendable { + private let lock = NSLock() + private var lastChunk: Date? + private var stalled = false + func touch() { lock.lock(); lastChunk = Date(); lock.unlock() } + func secondsSinceLastChunk() -> TimeInterval? { + lock.lock(); defer { lock.unlock() } + return lastChunk.map { Date().timeIntervalSince($0) } + } + func markStalled() { lock.lock(); stalled = true; lock.unlock() } + var didStall: Bool { lock.lock(); defer { lock.unlock() }; return stalled } + } + private func makeRequest(path: String, body: [String: Any], timeout: TimeInterval) throws -> URLRequest { guard let url = URL(string: path, relativeTo: OllamaConfig.baseURL)?.absoluteURL else { throw AgentError.transport("bad url") @@ -923,7 +1025,13 @@ actor OllamaClient { if u.code == .cancelled { throw CancellationError() } switch u.code { case .cannotConnectToHost, .networkConnectionLost, .cannotFindHost, .notConnectedToInternet: + OllamaConfig.onModelTransportFailure?() return .serverUnreachable(u.localizedDescription) + case .timedOut: + // User visible and retryable by the user, never silently retried + // (another full wait). The server status is refreshed right away. + OllamaConfig.onModelTransportFailure?() + return .timedOut("no response for \(Int(OllamaConfig.requestTimeout)) seconds") default: break } } diff --git a/holmes/holmes/Core/OllamaConfig.swift b/holmes/holmes/Core/OllamaConfig.swift index 8f70885..5aec28d 100644 --- a/holmes/holmes/Core/OllamaConfig.swift +++ b/holmes/holmes/Core/OllamaConfig.swift @@ -268,6 +268,36 @@ enum OllamaConfig { /// before the first byte arrives. static let requestTimeout: TimeInterval = 600 + /// Longest silence tolerated BETWEEN streamed chunks once output has + /// started. Long generations stay possible (there is no total cap beyond + /// requestTimeout's idle limit), but a server that stops mid answer is + /// noticed in 90 seconds instead of 10 minutes. A var so tests can shorten it. + static var streamStallTimeout: TimeInterval = 90 + + /// Pause before the single retry of a dropped or refused connection. + static var transientRetryDelay: TimeInterval = 0.5 + + /// Called when a model request times out, stalls or loses the server, so + /// the server status is re-probed at once. OllamaServer installs it on the + /// main thread; the model client and its stall watchdog call it from other + /// threads, so every read and write goes through a lock. + static var onModelTransportFailure: (@Sendable () -> Void)? { + get { transportFailureHook.value } + set { transportFailureHook.value = newValue } + } + + private static let transportFailureHook = LockedHook() + + /// A lock protected optional closure, safe to set and read from any thread. + final class LockedHook: @unchecked Sendable { + private let lock = NSLock() + private var stored: (@Sendable () -> Void)? + var value: (@Sendable () -> Void)? { + get { lock.lock(); defer { lock.unlock() }; return stored } + set { lock.lock(); stored = newValue; lock.unlock() } + } + } + /// Oldest server that returns tool-call ids (needed to pair results). static let minimumServerVersion = "0.12.10" diff --git a/holmes/holmes/Core/OllamaServer.swift b/holmes/holmes/Core/OllamaServer.swift index c0f6685..a96a4d5 100644 --- a/holmes/holmes/Core/OllamaServer.swift +++ b/holmes/holmes/Core/OllamaServer.swift @@ -121,6 +121,11 @@ final class OllamaServer { Task { @MainActor in self?.configurationDidChange() } } } + // A model request that timed out or lost its connection re-probes the + // server immediately, so the status and readiness gates catch up now. + OllamaConfig.onModelTransportFailure = { + Task { @MainActor in await OllamaServer.shared.refreshAfterFailure() } + } } // MARK: - Lifecycle diff --git a/holmes/holmes/Core/Playbooks/PlaybookEngine.swift b/holmes/holmes/Core/Playbooks/PlaybookEngine.swift index 35aa0da..41f9dec 100644 --- a/holmes/holmes/Core/Playbooks/PlaybookEngine.swift +++ b/holmes/holmes/Core/Playbooks/PlaybookEngine.swift @@ -397,6 +397,11 @@ final class PlaybookEngine { let work = Task { @MainActor in var succeeded = false let report: (Bool) -> Void = { succeeded = $0 } + // A background fire has nobody watching: its approval cards time + // out instead of holding the single playbook slot forever. A manual + // run was started by the user, who may take their time. + let approvalDeadline: TimeInterval? = manual ? nil : ApprovalScope.defaultUnattendedTimeout + await ApprovalScope.$unattendedTimeout.withValue(approvalDeadline) { await WorkActivityScope.$id.withValue(activity) { guard !Task.isCancelled else { return } // === AUTONOMY ROUTING === @@ -445,6 +450,7 @@ final class PlaybookEngine { } } } + } let cancelled = Task.isCancelled || self.fireID != runID if inherited == nil { if cancelled { WorkActivityCenter.shared.cancel(activity) } @@ -657,8 +663,14 @@ final class PlaybookEngine { return } let goal = playbook.makeGoal(ctx) - guard let plan = await ActionPlanner.plan(playbookId: playbook.id, goal: goal, context: ctx) else { - print("[Holmes] Playbook '\(playbook.id)' autonomy — no plan produced") + let plan: ActionPlan + switch await ActionPlanner.plan(playbookId: playbook.id, goal: goal, context: ctx) { + case .plan(let produced): + plan = produced + case .failure(let reason): + // Shown as this playbook's result in the notch, not just the console. + print("[Holmes] Playbook '\(playbook.id)' autonomy — no plan produced: \(reason)") + failureSummary = reason glow(.off) onCompletion?(false) return diff --git a/holmes/holmes/Core/Playbooks/TriggerBrain.swift b/holmes/holmes/Core/Playbooks/TriggerBrain.swift index fc39085..30b3d24 100644 --- a/holmes/holmes/Core/Playbooks/TriggerBrain.swift +++ b/holmes/holmes/Core/Playbooks/TriggerBrain.swift @@ -415,17 +415,12 @@ final class TriggerBrain { /// and raw newlines inside string values. Any failure returns nil (= none): /// malformed input can only cost a missed detection, never a false fire. static func parse(_ raw: String) -> Verdict? { - var searchFrom = raw.startIndex - while let candidateRange = nextJSONObjectRange(in: raw, from: searchFrom) { - let candidate = normalizeNewlinesInsideStrings(String(raw[candidateRange])) - if let data = candidate.data(using: .utf8), - let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], - let verdict = verdict(from: object) { - return verdict - } - searchFrom = raw.index(after: candidateRange.lowerBound) - } - return nil + var found: Verdict? + _ = ModelJSON.firstObject(in: raw, where: { object in + found = verdict(from: object) + return found != nil + }) + return found } private static func verdict(from object: [String: Any]) -> Verdict? { @@ -467,69 +462,6 @@ final class TriggerBrain { /// Returns the first balanced `{...}` in the text — string- and escape-aware, /// so braces inside JSON string values can't unbalance the scan. static func extractFirstJSONObject(from raw: String) -> String? { - guard let range = nextJSONObjectRange(in: raw, from: raw.startIndex) else { return nil } - return String(raw[range]) - } - - /// The first balanced `{...}` at or after `from` — the scanner behind - /// extractFirstJSONObject, generalized so parse() can retry past a - /// non-JSON `{...}` embedded in prose. - private static func nextJSONObjectRange(in raw: String, from: String.Index) -> Range? { - guard let start = raw[from...].firstIndex(of: "{") else { return nil } - var depth = 0 - var inString = false - var escaped = false - var index = start - while index < raw.endIndex { - let character = raw[index] - if escaped { - escaped = false - } else if inString { - if character == "\\" { escaped = true } - else if character == "\"" { inString = false } - } else { - switch character { - case "\"": inString = true - case "{": depth += 1 - case "}": - depth -= 1 - if depth == 0 { return start.. String { - var out = String() - out.reserveCapacity(candidate.count + 8) - var inString = false - var escaped = false - for character in candidate { - if escaped { - escaped = false - out.append(character) - continue - } - if inString { - switch character { - case "\\": escaped = true; out.append(character) - case "\"": inString = false; out.append(character) - case "\n": out.append("\\n") - case "\r": out.append("\\r") - case "\t": out.append("\\t") - default: out.append(character) - } - } else { - if character == "\"" { inString = true } - out.append(character) - } - } - return out + ModelJSON.objectCandidates(in: raw).first } } diff --git a/holmes/holmes/Core/TextEntrySupport.swift b/holmes/holmes/Core/TextEntrySupport.swift new file mode 100644 index 0000000..b0fb7d3 --- /dev/null +++ b/holmes/holmes/Core/TextEntrySupport.swift @@ -0,0 +1,160 @@ +import AppKit +import Foundation + +// MARK: - Text entry support +// +// Small, testable pieces behind ActionExecutor's typing, pasting and +// AppleScript paths. Kept free of AX and CGEvent so they run in unit tests. + +/// What actually happened when Holmes tried to put text into another app. +enum TextEntryResult: Equatable { + /// The field's value was read back and contains the text. + case verified + /// The events were delivered but the field does not expose its value, so + /// Holmes cannot prove the text landed. Never reported as plain success. + case unverified(String) + case failed(String) + + var succeeded: Bool { + if case .failed = self { return false } + return true + } + + var isVerified: Bool { self == .verified } + + /// One sentence for a tool result or status line. + func describe(action: String, app: String) -> String { + switch self { + case .verified: return "\(action) in \(app) (verified)." + case .unverified(let why): return "\(action) in \(app), but it could not be verified: \(why)" + case .failed(let why): return "Couldn't \(action.lowercased()) in \(app): \(why)" + } + } +} + +// MARK: - AppleScript string literals + +enum AppleScriptText { + /// An AppleScript EXPRESSION that evaluates to exactly `text`: quotes and + /// backslashes are escaped, and control characters (which cannot appear + /// raw inside an AppleScript string) are joined in as `linefeed`, + /// `return`, `tab` or `(character id N)`. Safe for app names and message + /// bodies alike; a crafted name can never close the string and inject code. + static func literal(_ text: String) -> String { + var parts: [String] = [] + var run = "" + func flush() { + if !run.isEmpty { parts.append("\"" + run + "\""); run = "" } + } + for scalar in text.unicodeScalars { + switch scalar { + case "\\": run += "\\\\" + case "\"": run += "\\\"" + case "\n": flush(); parts.append("linefeed") + case "\r": flush(); parts.append("return") + case "\t": flush(); parts.append("tab") + default: + if scalar.value < 0x20 || scalar.value == 0x7F || (0x80...0x9F).contains(scalar.value) + || scalar.value == 0x2028 || scalar.value == 0x2029 { + flush() + parts.append("(character id \(scalar.value))") + } else { + run.unicodeScalars.append(scalar) + } + } + } + flush() + return parts.isEmpty ? "\"\"" : parts.joined(separator: " & ") + } +} + +// MARK: - Keyboard text chunks + +enum KeyboardText { + /// CGEventKeyboardSetUnicodeString accepts at most 20 UTF-16 units per event. + static let maxUnitsPerEvent = 20 + + /// Splits text into UTF-16 chunks for keyboard events without ever + /// separating a surrogate pair (emoji and other non BMP characters), and + /// keeping whole grapheme clusters together whenever they fit. + static func utf16Chunks(_ text: String, maxUnits: Int = maxUnitsPerEvent) -> [[UniChar]] { + let limit = max(2, maxUnits) + var chunks: [[UniChar]] = [] + var current: [UniChar] = [] + func append(_ units: [UniChar]) { + if current.count + units.count > limit, !current.isEmpty { + chunks.append(current) + current = [] + } + current += units + } + for character in text { + let units = Array(String(character).utf16) + if units.count <= limit { + append(units) + } else { + // A cluster longer than one event: split between scalars, which + // never cuts a surrogate pair. + for scalar in character.unicodeScalars { + append(Array(String(scalar).utf16)) + } + } + } + if !current.isEmpty { chunks.append(current) } + return chunks + } +} + +// MARK: - Verification and clipboard timing + +enum TextEntryVerifier { + /// True when a field's read back value contains the text Holmes entered. + /// Line endings and Unicode normalization differ between apps, so both + /// sides are normalized first. + static func fieldValue(_ value: String?, contains typed: String) -> Bool { + guard let value else { return false } + func normalize(_ s: String) -> String { + s.replacingOccurrences(of: "\r\n", with: "\n") + .replacingOccurrences(of: "\r", with: "\n") + .precomposedStringWithCanonicalMapping + } + let wanted = normalize(typed) + guard !wanted.isEmpty else { return true } + return normalize(value).contains(wanted) + } + + /// How long to keep Holmes' text on the clipboard when the paste could + /// not be confirmed: long enough for a slow app to read a large paste. + static func unconfirmedRestoreDelay(forLength length: Int) -> TimeInterval { + min(4.0, 1.5 + Double(max(0, length)) / 4000.0) + } +} + +// MARK: - Pasteboard snapshot + +/// Every item and every type on a pasteboard, so borrowing the clipboard for a +/// paste can hand back images, files and rich text, not just plain text. +struct PasteboardSnapshot { + let items: [[(type: NSPasteboard.PasteboardType, data: Data)]] + + init(capturing pasteboard: NSPasteboard) { + items = (pasteboard.pasteboardItems ?? []).map { item in + item.types.compactMap { type in item.data(forType: type).map { (type, $0) } } + } + } + + var isEmpty: Bool { items.isEmpty } + + /// Puts the captured items back. Returns the pasteboard's new change count. + @discardableResult + func restore(to pasteboard: NSPasteboard) -> Int { + pasteboard.clearContents() + let restored: [NSPasteboardItem] = items.map { entries in + let item = NSPasteboardItem() + for entry in entries { item.setData(entry.data, forType: entry.type) } + return item + } + if !restored.isEmpty { pasteboard.writeObjects(restored) } + return pasteboard.changeCount + } +} diff --git a/holmes/holmes/Views/Confirmation/ConfirmationView.swift b/holmes/holmes/Views/Confirmation/ConfirmationView.swift index 44d612e..ee1553b 100644 --- a/holmes/holmes/Views/Confirmation/ConfirmationView.swift +++ b/holmes/holmes/Views/Confirmation/ConfirmationView.swift @@ -36,11 +36,7 @@ struct PendingAction: Identifiable { } } -// Result of a user approving/dismissing an agent tool call. -enum AgentDecision { - case approved(text: String) // `text` carries any edits the user made in the preview - case dismissed -} +// AgentDecision and the approval FIFO live in Core/ApprovalQueue.swift. // MARK: - ConfirmationBus // HolmesAgent posts here when it detects something actionable. @@ -50,7 +46,13 @@ enum AgentDecision { @Observable final class ConfirmationBus { static let shared = ConfirmationBus() - private init() {} + private init() { + cards.show = { [weak self] action in self?.presentCard(action) } + cards.hide = { [weak self] in self?.closeApprovalCard() } + approvals.onTimeout = { action in + print("[Holmes] Approval timed out: \(action.title)") + } + } var pendingAction: PendingAction? = nil var isShowing: Bool = false @@ -69,10 +71,25 @@ final class ConfirmationBus { /// panel card and this card must always show the same words. var isShowingReply: Bool = false - // Set while an agent tool call awaits the user's decision (see `decide`). - @ObservationIgnored private var decisionHandler: ((AgentDecision) -> Void)? + // Agent tool calls awaiting the user's decision, one card at a time (see `decide`). + @ObservationIgnored private let approvals = ApprovalQueue() + /// Which kind of card is on screen, so a direct proposal parks (never + /// orphans) a queued approval and a timeout only closes its own card. + @ObservationIgnored private lazy var cards = ApprovalCardArbiter(queue: approvals, id: { $0.id }) + /// True when the showing card is the approval at the head of the queue. + private var showingQueuedApproval: Bool { + guard let current = cards.showingApprovalID else { return false } + return pendingAction?.id == current + } + + /// Shows a card that is not an awaited approval (command bar result, meeting + /// join). A queued approval on screen is parked and returns when this closes. func propose(_ action: PendingAction) { + cards.proposeDirect(action) + } + + private func presentCard(_ action: PendingAction) { // A live approval outranks a proactive draft — push the draft back in line. if let draft = pendingDraft { draftQueue.insert(draft, at: 0) @@ -186,30 +203,27 @@ final class ConfirmationBus { /// Proposes an action and suspends until the user approves or dismisses it. /// Used by the agentic loop to gate side-effecting tool calls. - func decide(_ action: PendingAction) async -> AgentDecision { - guard !Task.isCancelled else { return .dismissed } - // If a decision is already pending (two confirmations overlapped — e.g. a - // calendar task raising a card while another autonomous step is still - // awaiting one), resolve the OLD handler as .dismissed FIRST. Otherwise the - // earlier continuation is orphaned and its await never resumes — the run - // that was waiting on it hangs forever and looks like "approve failed". - if let stale = decisionHandler { - decisionHandler = nil - stale(.dismissed) + /// + /// Overlapping requests QUEUE (FIFO): a second card waits until the first is + /// answered, so one run can never read another run's arrival as "declined". + /// Cancelling the awaiting task removes its card whether it is showing or + /// still queued. `timeout` (or the task's ApprovalScope.unattendedTimeout, + /// set by autonomous playbook runs) resolves `.timedOut` when nobody answers. + func decide(_ action: PendingAction, timeout: TimeInterval? = nil) async -> AgentDecision { + await approvals.decide(id: action.id, item: action, + timeout: timeout ?? ApprovalScope.unattendedTimeout) + } + + /// Hides the approval card once the queue is empty, then lets a queued + /// playbook draft take the panel. + private func closeApprovalCard() { + isShowingReply = false + pendingAction = nil + if pendingDraft == nil { + isShowing = false + ConfirmationWindowController.shared.hide() } - guard !Task.isCancelled else { return .dismissed } - return await withTaskCancellationHandler(operation: { - await withCheckedContinuation { cont in - guard !Task.isCancelled else { cont.resume(returning: .dismissed); return } - decisionHandler = { cont.resume(returning: $0) } - propose(action) - } - }, onCancel: { - Task { @MainActor in - guard self.pendingAction?.id == action.id else { return } - self.dismiss() - } - }) + showNextDraftSoon() } /// Closes the showing card. For drafts this only CLOSES the popup by @@ -218,9 +232,10 @@ final class ConfirmationBus { /// Pass `removeDraft: true` only where removal is what the user expects: /// the post-action completion (Copy/Insert/Open succeeded). func dismiss(removeDraft: Bool = false) { - if let handler = decisionHandler { - decisionHandler = nil - handler(.dismissed) + if showingQueuedApproval { + // The queue presents the next waiting approval, or closes the card. + approvals.resolveCurrent(.dismissed) + return } if let draft = pendingDraft { if removeDraft { @@ -235,6 +250,11 @@ final class ConfirmationBus { isShowing = false pendingAction = nil ConfirmationWindowController.shared.hide() + if cards.isShowingDirect { + // Re shows an approval that was parked behind the direct card. + cards.directClosed() + if pendingAction != nil { return } + } showNextDraftSoon() } @@ -257,14 +277,9 @@ final class ConfirmationBus { func execute() { // Agent-loop path: hand the (possibly edited) text back to the awaiting loop // and let it perform the real call. Do NOT run ActionExecutor here. - if let handler = decisionHandler { - decisionHandler = nil + if showingQueuedApproval { let text = pendingAction?.preview ?? "" - isShowing = false - pendingAction = nil - ConfirmationWindowController.shared.hide() - handler(.approved(text: text)) - showNextDraftSoon() + approvals.resolveCurrent(.approved(text: text)) return } @@ -272,14 +287,22 @@ final class ConfirmationBus { action.isExecuting = true pendingAction = action - DispatchQueue.global(qos: .userInitiated).async { + // On the main actor: the text entry itself is nonisolated async (off + // main), and any AppleScript it needs runs back on the main actor. + Task { @MainActor in var success = false + var verified = true switch action.actionType { case .typeMessage: - success = ActionExecutor.shared.sendMessageInApp(action.appName, message: action.preview) + // The user approved placing EXACTLY this message in the field, + // so an existing draft there is replaced (select all, then paste). + let entry = await ActionExecutor.shared.sendMessageInApp(action.appName, message: action.preview, + replaceExisting: true) + success = entry.succeeded + verified = entry.isVerified case .openURL: if let url = URL(string: action.preview) { - DispatchQueue.main.async { NSWorkspace.shared.open(url) } + NSWorkspace.shared.open(url) success = true } case .runScript: @@ -288,21 +311,21 @@ final class ConfirmationBus { // Handled via decisionHandler above; unreachable here. success = false case .openMeeting: - DispatchQueue.main.async { - if let meeting = action.meeting { - MeetingJoinEngine.shared.joinMeeting(meeting) - } else if let url = action.meetingURL { - NSWorkspace.shared.open(url) - } + if let meeting = action.meeting { + MeetingJoinEngine.shared.joinMeeting(meeting) + } else if let url = action.meetingURL { + NSWorkspace.shared.open(url) } success = true } - DispatchQueue.main.async { + do { guard ConfirmationBus.shared.pendingAction?.id == action.id else { return } let completed: String switch action.actionType { - case .typeMessage: completed = "✓ Inserted in \(action.appName)" + case .typeMessage: + completed = verified ? "✓ Inserted in \(action.appName)" + : "Sent to \(action.appName), but couldn't confirm it landed. Check the field." case .openMeeting: completed = "✓ Opening meeting" case .openURL: completed = "✓ Opened link" default: completed = "✓ Completed" @@ -610,18 +633,19 @@ struct ConfirmationView: View { private func insertDraft(_ draft: ProactiveDraft, appName: String) { draftIsExecuting = true let text = draftBody - DispatchQueue.global(qos: .userInitiated).async { - let ok = ActionExecutor.shared.stageTextInApp(appName, text: text) - DispatchQueue.main.async { - // The card may have moved on (dismissed, next draft shown) while - // staging ran — never write result state onto a different card. - guard bus.pendingDraft?.id == draft.id else { return } - draftIsExecuting = false - if ok { - finishDraft(draft, result: "✓ Staged in \(appName) — you press Send") - } else { - draftResult = "Failed to insert into \(appName)" - } + Task { @MainActor in + let entry = await ActionExecutor.shared.stageTextInApp(appName, text: text) + // The card may have moved on (dismissed, next draft shown) while + // staging ran — never write result state onto a different card. + guard bus.pendingDraft?.id == draft.id else { return } + draftIsExecuting = false + switch entry { + case .verified: + finishDraft(draft, result: "✓ Staged in \(appName) — you press Send") + case .unverified: + finishDraft(draft, result: "Staged in \(appName), but couldn't confirm it landed. Check before you send.") + case .failed: + draftResult = "Failed to insert into \(appName)" } } } diff --git a/holmes/holmes/Views/Confirmation/ReplyReadyCard.swift b/holmes/holmes/Views/Confirmation/ReplyReadyCard.swift index d0b9a9d..f627e90 100644 --- a/holmes/holmes/Views/Confirmation/ReplyReadyCard.swift +++ b/holmes/holmes/Views/Confirmation/ReplyReadyCard.swift @@ -293,14 +293,11 @@ struct ReplyReadyCard: View { } } - /// ActionExecutor sleeps and waits on another process, so it must never run - /// on the main thread. Only strings cross the boundary. + /// ActionExecutor's text entry is nonisolated async: its waits and AX work + /// run off the main thread, and its AppleScript runs on the main actor. + /// Only strings cross the boundary. nonisolated private static func stage(text: String, into app: String) async -> Bool { - await withCheckedContinuation { continuation in - DispatchQueue.global(qos: .userInitiated).async { - continuation.resume(returning: ActionExecutor.shared.stageTextInApp(app, text: text)) - } - } + await ActionExecutor.shared.stageTextInApp(app, text: text).succeeded } private func copyBody() { diff --git a/holmes/holmes/Views/MainPanel/AgentMemoryCard.swift b/holmes/holmes/Views/MainPanel/AgentMemoryCard.swift index afe0510..1cfa7dd 100644 --- a/holmes/holmes/Views/MainPanel/AgentMemoryCard.swift +++ b/holmes/holmes/Views/MainPanel/AgentMemoryCard.swift @@ -551,7 +551,20 @@ struct MemoryRowView: View { struct ExtensionStatusRow: View { @State private var bridge = BrowserBridge.shared - @State private var connected = false + @State private var state: BrowserBridge.LinkState = .disconnected + + private var connected: Bool { state == .connected } + + private var label: String { + switch state { + case .connected: + return bridge.recentlyPairedExtension.map { "Browser extension connected (new pairing: \($0.label))" } + ?? "Browser extension connected" + case .pageContextStale: return "Extension connected, but this tab isn't sending page context. Refresh the tab." + case .notListening(let reason): return "Browser bridge not listening: \(reason)" + case .disconnected: return "Browser extension not connected — context is OCR-guessed" + } + } var body: some View { HStack(spacing: 6) { @@ -559,9 +572,7 @@ struct ExtensionStatusRow: View { .font(NoirFonts.font(size: 9, weight: .bold, design: .monospaced)) .foregroundColor(connected ? NoirColors.success : memoryAmber) - Text(connected - ? "Browser extension connected" - : "Browser extension not connected — context is OCR-guessed") + Text(label) .font(NoirFonts.font(size: 10, weight: .regular, design: .default)) .foregroundColor(connected ? NoirColors.textSecondary : memoryAmber.opacity(0.85)) .lineLimit(2) @@ -569,19 +580,33 @@ struct ExtensionStatusRow: View { Spacer(minLength: 0) } - .help(connected ? Self.connectedHelp : Self.disconnectedHelp) + .help(help) .task { // Connectivity is "did the extension post within the heartbeat // window", so it goes stale on the clock rather than on an event — // poll it, otherwise the row would keep claiming "connected" long // after the browser was quit. while !Task.isCancelled { - connected = bridge.isExtensionConnected + state = bridge.linkState try? await Task.sleep(nanoseconds: 3_000_000_000) } } } + private var help: String { + switch state { + case .connected: return Self.connectedHelp + case .pageContextStale: return Self.staleHelp + case .notListening, .disconnected: return Self.disconnectedHelp + } + } + + private static let staleHelp = """ + The extension's background worker is talking to Holmes, but the page in \ + front is not sending its contents (its content script is missing or was \ + left behind by an extension update). Refresh the tab so Holmes can read it. + """ + private static let connectedHelp = """ The Holmes extension is POSTing page context to localhost:5766. \ Facts about the page are read from the DOM, so Holmes can quote them exactly. diff --git a/holmes/tests/AXElementSearchTests.swift b/holmes/tests/AXElementSearchTests.swift new file mode 100644 index 0000000..c90eebf --- /dev/null +++ b/holmes/tests/AXElementSearchTests.swift @@ -0,0 +1,154 @@ +import Foundation + +final class FakeElement { + let role: String + let title: String? + let descriptionText: String? + let help: String? + let identifier: String? + var children: [FakeElement] = [] + init(_ role: String, title: String? = nil, description: String? = nil, help: String? = nil, identifier: String? = nil) { + self.role = role + self.title = title + self.descriptionText = description + self.help = help + self.identifier = identifier + } + var names: AXNames { AXNames(title: title, description: descriptionText, help: help, identifier: identifier) } +} + +@main +struct AXElementSearchTests { + static func main() { + var checks = 0 + func expect(_ value: @autoclosure () -> Bool, _ message: String) { + precondition(value(), message) + checks += 1 + } + func findButton(_ label: String, in root: FakeElement, maxDepth: Int = 30, maxNodes: Int = 3000) -> AXElementSearch.Result { + AXElementSearch.best(from: root, maxDepth: maxDepth, maxNodes: maxNodes, + stopScore: AXLabelMatch.exact.rawValue, + children: { $0.children }, + score: { node in + guard node.role == "AXButton" else { return nil } + return AXElementSearch.labelMatch(label, in: node.names)?.rawValue + }) + } + + // Ranking: the old title substring match pressed the first "Reply…" it met. + let window = FakeElement("AXWindow") + let replyAll = FakeElement("AXButton", title: "Reply All") + let reply = FakeElement("AXButton", title: "Reply") + window.children = [replyAll, reply] + expect(findButton("Reply", in: window).node === reply, "An exact title beats an earlier substring match") + expect(findButton("reply all", in: window).node === replyAll, "A case insensitive full match beats substring matches") + expect(findButton("All", in: window).node === replyAll, "A substring still matches when nothing better exists") + + let toolbar = FakeElement("AXToolbar") + let icon = FakeElement("AXButton", description: "Send") + let helpOnly = FakeElement("AXButton", help: "Archive message") + let idOnly = FakeElement("AXButton", identifier: "composeButton") + toolbar.children = [icon, helpOnly, idOnly] + expect(findButton("Send", in: toolbar).node === icon, "An icon button is found by its AXDescription") + expect(findButton("Archive message", in: toolbar).node === helpOnly, "A control is found by its AXHelp") + expect(findButton("composeButton", in: toolbar).node === idOnly, "A control is found by its AXIdentifier") + expect(findButton("Delete", in: toolbar).node == nil, "No match returns nil rather than a guess") + expect(AXElementSearch.labelMatch(" ", names: ["Send"]) == nil, "A blank label never matches") + expect(AXElementSearch.labelMatch("send", names: ["Send later", "SEND"]) == .caseInsensitive, + "The strongest match across all names wins") + + // Bounds: a pathological tree cannot stall the caller. + let deepRoot = FakeElement("AXGroup") + var cursor = deepRoot + for level in 1...200 { + let next = FakeElement(level == 150 ? "AXButton" : "AXGroup", title: level == 150 ? "Deep" : nil) + cursor.children = [next] + cursor = next + } + let deep = findButton("Deep", in: deepRoot, maxDepth: 40) + expect(deep.node == nil && deep.truncated && deep.visited <= 41, "Depth is bounded (visited \(deep.visited))") + + let wideRoot = FakeElement("AXWindow") + wideRoot.children = (0..<20_000).map { _ in FakeElement("AXStaticText") } + wideRoot.children.append(FakeElement("AXButton", title: "Last")) + let wide = findButton("Last", in: wideRoot, maxNodes: 500) + expect(wide.node == nil && wide.truncated && wide.visited == 500, "Visited element count is bounded (visited \(wide.visited))") + + var scored = 0 + let early = AXElementSearch.best(from: window, stopScore: AXLabelMatch.exact.rawValue, + children: { $0.children }, + score: { node -> Int? in + scored += 1 + return node === replyAll ? AXLabelMatch.exact.rawValue : nil + }) + expect(early.node === replyAll && scored == 2, "An exact match ends the walk immediately") + + // ax_type with no field hint: the message body, not a shallow search field. + let composeWindow = FakeElement("AXWindow") + let composeToolbar = FakeElement("AXToolbar") + let searchField = FakeElement("AXTextField", description: "Search") + composeToolbar.children = [searchField] + let split = FakeElement("AXSplitGroup") + let scroll = FakeElement("AXScrollArea") + let body = FakeElement("AXTextArea", description: "Message body") + scroll.children = [body] + split.children = [scroll] + composeWindow.children = [composeToolbar, split] + func findTextEntry(_ hint: String?) -> FakeElement? { + AXElementSearch.best(from: composeWindow, + stopScore: AXElementSearch.textEntryStopScore(hasHint: hint != nil), + children: { $0.children }, + score: { node in + AXElementSearch.textEntryScore(role: node.role, hint: hint, names: { node.names }) + }).node + } + expect(findTextEntry(nil) === body, "With no hint, a deeper text area beats a shallower search field") + expect(findTextEntry("Search") === searchField, "A hint naming the search field still selects it") + expect(findTextEntry("message") === body, "A hint matching the body selects the body") + expect(AXElementSearch.textEntryScore(role: "AXButton", hint: nil, names: { AXNames() }) == nil, + "Only text areas and text fields are typing targets") + + // Help text is exact only: "message" must not pick a control whose help is "Send the message". + let helpBar = FakeElement("AXToolbar") + let sendIcon = FakeElement("AXButton", help: "Send the message") + helpBar.children = [sendIcon] + expect(findButton("message", in: helpBar).node == nil, "A substring of help text never selects a control") + expect(findButton("send the message", in: helpBar).node === sendIcon, "Help text still matches in full") + + // The commit gate runs on the MATCHED control, not only the requested label. + let later = FakeElement("AXButton", title: "Send later") + let laterBar = FakeElement("AXToolbar") + laterBar.children = [later] + let matchedLater = findButton("later", in: laterBar).node + expect(matchedLater === later, "A harmless looking label can substring match a send control") + expect(CommitControlGate.pressNeedsConfirmation(requested: "later", matched: later.names, userConfirmed: false), + "Pressing the matched Send later control needs confirmation") + expect(CommitControlGate.pressNeedsConfirmation(requested: "message", + matched: AXNames(description: "Send"), userConfirmed: false), + "An icon button described as Send needs confirmation") + expect(!CommitControlGate.pressNeedsConfirmation(requested: "later", matched: later.names, userConfirmed: true), + "An approved press goes through") + expect(!CommitControlGate.pressNeedsConfirmation(requested: "Save draft", + matched: AXNames(title: "Save Draft"), userConfirmed: false), + "A non commit control presses freely") + expect(CommitControlGate.pressNeedsConfirmation(requested: "Don't Save", + matched: AXNames(title: "Don’t Save"), userConfirmed: false) + || CommitControlGate.looksLikeCommit("Don't Save"), + "Don't Save counts as a commit") + + // The time budget stops the whole walk, including scoring of nodes + // already queued, not only further child reads. + let budgetRoot = FakeElement("AXWindow") + budgetRoot.children = (0..<50).map { _ in FakeElement("AXStaticText") } + var scoredBeforeBudget = 0 + var budgetChecks = 0 + let budgeted = AXElementSearch.best(from: budgetRoot, + shouldStop: { budgetChecks += 1; return budgetChecks > 5 }, + children: { $0.children }, + score: { _ -> Int? in scoredBeforeBudget += 1; return nil }) + expect(budgeted.truncated && budgeted.visited == 5 && scoredBeforeBudget == 5, + "An expired budget ends the walk before scoring more queued elements (scored \(scoredBeforeBudget))") + + print("Passed \(checks) bounded accessibility search and label ranking checks") + } +} diff --git a/holmes/tests/ApprovalQueueTests.swift b/holmes/tests/ApprovalQueueTests.swift new file mode 100644 index 0000000..aceaefd --- /dev/null +++ b/holmes/tests/ApprovalQueueTests.swift @@ -0,0 +1,182 @@ +import Foundation + +@main +struct ApprovalQueueTests { + @MainActor static func main() async throws { + var checks = 0 + func expect(_ value: @autoclosure () -> Bool, _ message: String) { + precondition(value(), message) + checks += 1 + } + func label(_ decision: AgentDecision?) -> String { + switch decision { + case .approved(let text)?: return "approved:\(text)" + case .dismissed?: return "dismissed" + case .timedOut?: return "timedOut" + case nil: return "pending" + } + } + + // Two overlapping approvals: the second must queue, not dismiss the first. + let queue = ApprovalQueue() + var shown: [String?] = [] + queue.onPresent = { shown.append($0) } + var firstDecision: AgentDecision? + var secondDecision: AgentDecision? + let firstID = UUID(), secondID = UUID() + let first = Task { @MainActor in + firstDecision = await queue.decide(id: firstID, item: "first run", timeout: nil) + } + try await eventually { queue.currentID == firstID } + let second = Task { @MainActor in + secondDecision = await queue.decide(id: secondID, item: "second run", timeout: nil) + } + try await eventually { queue.queuedCount == 1 } + expect(firstDecision == nil, "A new approval must not resolve the pending one (it used to read as declined)") + expect(queue.currentItem == "first run" && shown == ["first run"], "The first card stays on screen while the second waits") + queue.resolveCurrent(.approved(text: "ok")) + await first.value + expect(label(firstDecision) == "approved:ok", "The first run receives the user's actual answer") + expect(queue.currentItem == "second run" && shown.last == "second run", "The next approval is shown after the current resolves") + queue.resolveCurrent(.dismissed) + await second.value + expect(label(secondDecision) == "dismissed" && queue.isIdle && shown.last! == nil, + "Resolving the last approval hides the card") + + // Cancellation removes only the cancelled task's card. + var keptDecision: AgentDecision? + let keptID = UUID(), queuedID = UUID(), showingID = UUID() + let kept = Task { @MainActor in keptDecision = await queue.decide(id: keptID, item: "kept", timeout: nil) } + try await eventually { queue.currentID == keptID } + let queuedTask = Task { @MainActor in await queue.decide(id: queuedID, item: "queued then cancelled", timeout: nil) } + try await eventually { queue.queuedCount == 1 } + queuedTask.cancel() + let queuedValue = await queuedTask.value + expect(label(queuedValue) == "dismissed", "A cancelled queued approval resolves dismissed") + try await eventually { queue.queuedCount == 0 } + expect(queue.currentID == keptID && keptDecision == nil, "Cancelling a queued card leaves the showing card alone") + queue.resolveCurrent(.approved(text: "")) + await kept.value + let showingTask = Task { @MainActor in await queue.decide(id: showingID, item: "showing then cancelled", timeout: nil) } + try await eventually { queue.currentID == showingID } + showingTask.cancel() + let showingValue = await showingTask.value + expect(label(showingValue) == "dismissed", "A cancelled showing approval resolves dismissed") + try await eventually { queue.isIdle } + expect(shown.last! == nil, "Cancelling the showing card hides it") + let alreadyCancelled = Task { @MainActor in await queue.decide(id: UUID(), item: "never", timeout: nil) } + alreadyCancelled.cancel() + let alreadyCancelledValue = await alreadyCancelled.value + expect(label(alreadyCancelledValue) == "dismissed" && queue.isIdle, "An already cancelled request never shows") + + // Unattended deadline: an autonomous approval nobody answers times out, + // even while it waits behind a user initiated card with no deadline. + var timedOutItems: [String] = [] + queue.onTimeout = { timedOutItems.append($0) } + var userDecision: AgentDecision? + let userID = UUID() + let user = Task { @MainActor in userDecision = await queue.decide(id: userID, item: "user", timeout: nil) } + try await eventually { queue.currentID == userID } + let started = Date() + let unattended = Task { @MainActor in + await ApprovalScope.$unattendedTimeout.withValue(0.15) { + await queue.decide(id: UUID(), item: "playbook", timeout: ApprovalScope.unattendedTimeout) + } + } + let unattendedDecision = await unattended.value + let waited = Date().timeIntervalSince(started) + expect(label(unattendedDecision) == "timedOut" && waited >= 0.1 && waited < 5, + "An unattended approval resolves timedOut at its deadline (took \(waited)s)") + expect(timedOutItems == ["playbook"], "A timeout reports which approval expired for the status line") + expect(queue.currentID == userID && userDecision == nil, "A user initiated approval keeps waiting without a deadline") + let showingUnattended = Task { @MainActor in await queue.decide(id: UUID(), item: "second playbook", timeout: 0.1) } + queue.resolveCurrent(.approved(text: "user ok")) + await user.value + expect(label(userDecision) == "approved:user ok", "The user card still resolves normally") + let showingUnattendedValue = await showingUnattended.value + expect(label(showingUnattendedValue) == "timedOut" && queue.isIdle, + "A showing unattended approval times out and hides its card") + expect(ApprovalScope.defaultUnattendedTimeout == 120, "Autonomous approvals default to a 120 second deadline") + + // One shared card: direct proposals and queued approvals. + struct Card { let id = UUID(); let name: String } + let cardQueue = ApprovalQueue() + let arbiter = ApprovalCardArbiter(queue: cardQueue, id: { $0.id }) + var onScreen: [String] = [] + var hides = 0 + arbiter.show = { onScreen.append($0.name) } + arbiter.hide = { hides += 1 } + + // Scenario 1: a direct proposal over a user approval (no deadline). + let userCard = Card(name: "user approval") + var userCardDecision: AgentDecision? + let userCardTask = Task { @MainActor in + userCardDecision = await cardQueue.decide(id: userCard.id, item: userCard, timeout: nil) + } + try await eventually { arbiter.showingApprovalID == userCard.id } + let meeting = Card(name: "meeting join") + arbiter.proposeDirect(meeting) + expect(onScreen.last == "meeting join" && arbiter.showingApprovalID == nil, + "A direct proposal takes the card and parks the approval") + arbiter.directClosed() + expect(onScreen.last == "user approval" && arbiter.showingApprovalID == userCard.id, + "When the direct card closes, the parked approval is shown again instead of hanging") + cardQueue.resolveCurrent(.approved(text: "yes")) + await userCardTask.value + expect(label(userCardDecision) == "approved:yes" && hides == 1 && arbiter.showing == .none, + "The re shown approval still resolves its run and closes the card") + + // Scenario 2: a playbook approval times out while the user looks at a direct card. + let commandResult = Card(name: "command bar result") + arbiter.proposeDirect(commandResult) + let playbookCard = Card(name: "playbook approval") + let hidesBeforeTimeout = hides + let timedOutCard = await cardQueue.decide(id: playbookCard.id, item: playbookCard, timeout: 0.1) + expect(label(timedOutCard) == "timedOut", "The parked playbook approval still times out") + expect(hides == hidesBeforeTimeout && onScreen.last == "command bar result" && arbiter.isShowingDirect, + "A timeout never closes a direct card the user is looking at") + arbiter.directClosed() + expect(arbiter.showing == .none && onScreen.last == "command bar result", + "Closing the direct card afterwards shows nothing stale") + + // Scenario 3: a queued playbook approval behind a showing user approval times out. + let front = Card(name: "front") + let frontTask = Task { @MainActor in await cardQueue.decide(id: front.id, item: front, timeout: nil) } + try await eventually { arbiter.showingApprovalID == front.id } + let hidesBeforeQueuedTimeout = hides + let behind = Card(name: "behind") + let behindDecision = await cardQueue.decide(id: behind.id, item: behind, timeout: 0.1) + expect(label(behindDecision) == "timedOut" && hides == hidesBeforeQueuedTimeout + && arbiter.showingApprovalID == front.id, + "A queued approval timing out leaves the showing approval on screen") + cardQueue.resolveCurrent(.dismissed) + _ = await frontTask.value + + // A timed out approval inside a tool call is reported as a timeout, not a decline. + let tracked = await ApprovalTimeoutTracking.run { () -> String in + let answer = await ApprovalQueue().decide(id: UUID(), item: "tool approval", timeout: 0.05) + if case .timedOut = answer { ApprovalTimeoutTracking.flag?.markTimedOut() } + return label(answer) + } + expect(tracked.result == "timedOut" && tracked.timedOut, "A timeout inside a tracked tool call is recorded") + let declinedQueue = ApprovalQueue() + let declined = await ApprovalTimeoutTracking.run { () -> String in + let pending = Task { @MainActor in await declinedQueue.decide(id: UUID(), item: "declined", timeout: nil) } + try? await eventually { !declinedQueue.isIdle } + declinedQueue.resolveCurrent(.dismissed) + return label(await pending.value) + } + expect(declined.result == "dismissed" && !declined.timedOut, "A real decline is not reported as a timeout") + expect(ApprovalTimeoutTracking.flag == nil, "Tracking is scoped to the tool call") + + print("Passed \(checks) approval queue, cancellation and unattended timeout checks") + } + + @MainActor static func eventually(_ predicate: () -> Bool) async throws { + for _ in 0..<400 { + if predicate() { return } + try await Task.sleep(nanoseconds: 5_000_000) + } + preconditionFailure("Timed out waiting for the approval queue") + } +} diff --git a/holmes/tests/AutonomousRunTallyTests.swift b/holmes/tests/AutonomousRunTallyTests.swift new file mode 100644 index 0000000..841cc87 --- /dev/null +++ b/holmes/tests/AutonomousRunTallyTests.swift @@ -0,0 +1,46 @@ +import Foundation + +@main +struct AutonomousRunTallyTests { + static func main() { + var checks = 0 + func expect(_ value: @autoclosure () -> Bool, _ message: String) { + precondition(value(), message) + checks += 1 + } + + var clean = AutonomousRunTally(plannedSteps: 2) + clean.recordCompleted() + clean.recordCompleted() + expect(clean.succeeded && clean.note == "done", "A run with every step completed succeeds") + expect(clean.notifyBody(undoAvailable: true) == "2 of 2 steps completed. Undo is available in the Holmes panel.", + "A clean run reports its steps and undo") + + var skipped = AutonomousRunTally(plannedSteps: 4) + skipped.recordCompleted(3) + skipped.recordSkipped(summary: "Press Reply in Mail", reason: "No accessible button labeled “Reply” in Mail") + expect(!skipped.succeeded, "A skipped required step fails the run") + expect(skipped.note.hasPrefix("Failed: 1 required step was skipped"), "The note says the run failed: \(skipped.note)") + expect(skipped.note.contains("Press Reply in Mail") && skipped.note.contains("No accessible button"), + "The note names the skipped step and why") + expect(skipped.notifyBody(undoAvailable: false).hasPrefix("Failed: 3 of 4 steps completed, 1 skipped"), + "The notification never reads as success when a step was skipped") + + skipped.recordSkipped(summary: "Type the reply", reason: "") + expect(skipped.note.hasPrefix("Failed: 2 required steps were skipped"), "Several skips are counted") + + var unsure = AutonomousRunTally(plannedSteps: 2) + unsure.recordCompleted(2) + unsure.recordUnverified(summary: "Type the reply into Slack", reason: "the field does not expose its contents") + expect(unsure.succeeded && !unsure.isFullyVerified, "An unverified step is not a failure, and not fully verified") + expect(unsure.note != "done" && unsure.note.hasPrefix("Done, but 1 step could not be verified") + && unsure.note.contains("Type the reply into Slack"), + "An unverified step is named in the note, never a plain done: \(unsure.note)") + expect(unsure.notifyBody(undoAvailable: false) == "2 of 2 steps completed, 1 unverified (“Type the reply into Slack”). Check them.", + "The notification says which step is unverified") + unsure.recordSkipped(summary: "Press Send", reason: "not found") + expect(!unsure.succeeded && unsure.note.hasPrefix("Failed:"), "A skipped step still fails the run even with unverified steps") + + print("Passed \(checks) autonomous run tally checks") + } +} diff --git a/holmes/tests/BridgeLoopbackSupport.swift b/holmes/tests/BridgeLoopbackSupport.swift new file mode 100644 index 0000000..fe9a0ad --- /dev/null +++ b/holmes/tests/BridgeLoopbackSupport.swift @@ -0,0 +1,92 @@ +import Foundation + +// A tiny blocking HTTP/1.1 client over real loopback sockets. Used by the bridge +// socket tests and the soak test so they exercise the production BridgeServer +// parser, auth, long poll and body limits exactly as the extension does. + +struct LoopbackResponse { + let status: Int + let headers: [String: String] + let body: Data + var json: Any? { try? JSONSerialization.jsonObject(with: body) } +} + +enum LoopbackHTTP { + /// Sends one request and reads the whole response. Returns nil on a connection + /// failure (refused, reset before any response, timeout). + static func request(port: UInt16, method: String, path: String, headers: [String: String] = [:], + body: Data = Data(), timeout: TimeInterval = 10) -> LoopbackResponse? { + let fd = socket(AF_INET, SOCK_STREAM, 0) + guard fd >= 0 else { return nil } + defer { close(fd) } + var on: Int32 = 1 + setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &on, socklen_t(MemoryLayout.size)) + var tv = timeval(tv_sec: Int(timeout), tv_usec: Int32((timeout - floor(timeout)) * 1_000_000)) + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, socklen_t(MemoryLayout.size)) + setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, socklen_t(MemoryLayout.size)) + var addr = sockaddr_in() + addr.sin_family = sa_family_t(AF_INET) + addr.sin_port = port.bigEndian + addr.sin_addr.s_addr = INADDR_LOOPBACK.bigEndian + let connected = withUnsafePointer(to: &addr) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(fd, $0, socklen_t(MemoryLayout.size)) } + } + guard connected == 0 else { return nil } + var head = "\(method) \(path) HTTP/1.1\r\nHost: 127.0.0.1:\(port)\r\nConnection: close\r\n" + var allHeaders = headers + if method != "GET" || !body.isEmpty { allHeaders["Content-Length"] = "\(body.count)" } + for (key, value) in allHeaders { head += "\(key): \(value)\r\n" } + head += "\r\n" + var out = Data(head.utf8) + out.append(body) + let sentAll = out.withUnsafeBytes { raw -> Bool in + guard let base = raw.bindMemory(to: UInt8.self).baseAddress else { return false } + var sent = 0 + while sent < out.count { + let n = send(fd, base + sent, out.count - sent, 0) + if n <= 0 { return false } + sent += n + } + return true + } + _ = sentAll // a server that answers 413 early may stop reading; still read its reply + var buffer = Data() + var chunk = [UInt8](repeating: 0, count: 64 * 1024) + while true { + let n = recv(fd, &chunk, chunk.count, 0) + if n <= 0 { break } + buffer.append(contentsOf: chunk[0..= 2, let status = Int(parts[1]) else { return nil } + var parsed: [String: String] = [:] + for line in lines.dropFirst() { + guard let colon = line.firstIndex(of: ":") else { continue } + parsed[line[..(_ work: @escaping @Sendable () -> T) async -> T { + await withCheckedContinuation { continuation in + DispatchQueue.global(qos: .userInitiated).async { continuation.resume(returning: work()) } + } + } +} + +/// A lock protected box for values written from background threads. +final class LockedBox: @unchecked Sendable { + private let lock = NSLock() + private var stored: Value + init(_ value: Value) { stored = value } + var value: Value { + get { lock.lock(); defer { lock.unlock() }; return stored } + set { lock.lock(); stored = newValue; lock.unlock() } + } + func mutate(_ change: (inout Value) -> Void) { lock.lock(); change(&stored); lock.unlock() } +} diff --git a/holmes/tests/BridgeLoopbackTests.swift b/holmes/tests/BridgeLoopbackTests.swift new file mode 100644 index 0000000..8e66c11 --- /dev/null +++ b/holmes/tests/BridgeLoopbackTests.swift @@ -0,0 +1,475 @@ +import Foundation + +// Real loopback socket tests for BrowserBridge + BridgeServer. The production +// server is bound to an ephemeral 127.0.0.1 port through the DEBUG constructor; no +// token files, browsers or app activation are involved. + +enum BridgeLoopbackTests { + static let token = "loopback-test-token-0001" + + @MainActor static func makeBridge(frontmost: @escaping () -> BrowserBridge.AppIdentity? = { + .init(name: "Google Chrome", bundleIdentifier: "com.google.Chrome") + }) -> (BrowserBridge, UInt16) { + let environment = BrowserBridge.ContextEnvironment(frontmost: frontmost, ownBundleIdentifier: "test.holmes", + nameForBundle: { $0 == "com.google.Chrome" ? "Google Chrome" : "Comet" }) + let bridge = BrowserBridge(testToken: token, environment: environment, port: 0) + bridge.start() + guard let port = bridge.boundPort, bridge.isRunning else { fatalError("Loopback bridge did not start: \(bridge.lastError ?? "?")") } + return (bridge, port) + } + + static func poll(_ port: UInt16, instance: String, wait: Int = 0, token: String = token, + timeout: TimeInterval = 10) -> (LoopbackResponse?, [[String: Any]]) { + var headers = ["X-Holmes-Token": token, "X-Holmes-Browser-Instance": instance] + if wait > 0 { headers["X-Holmes-Long-Poll"] = "\(wait)" } + let response = LoopbackHTTP.request(port: port, method: "GET", path: "/commands", headers: headers, timeout: timeout) + return (response, (response?.json as? [[String: Any]]) ?? []) + } + + static func postResult(_ port: UInt16, _ object: [String: Any], token: String = token) -> LoopbackResponse? { + let body = (try? JSONSerialization.data(withJSONObject: object)) ?? Data() + return LoopbackHTTP.request(port: port, method: "POST", path: "/command-result", + headers: ["X-Holmes-Token": token, "Content-Type": "application/json"], body: body) + } + + @MainActor static func waitUntil(_ label: String, timeout: TimeInterval = 5, _ condition: () -> Bool) async { + let deadline = Date().addingTimeInterval(timeout) + while !condition() { + if Date() > deadline { fatalError("Timed out waiting for: \(label)") } + try? await Task.sleep(nanoseconds: 10_000_000) + } + } + + /// Queue, long poll and delivery deadline behavior over real sockets. + @MainActor static func runCommandChannel(check: (Bool, String) -> Void) async { + let (bridge, port) = makeBridge() + defer { bridge.stop() } + + let health = await LoopbackHTTP.background { LoopbackHTTP.request(port: port, method: "GET", path: "/health") } + check(health?.status == 200, "Health probe answers without a token over a real socket") + let unauthorized = await LoopbackHTTP.background { poll(port, instance: "inst-a", token: "wrong-token-000000000").0 } + check(unauthorized?.status == 401, "GET /commands without the token is rejected") + + // Long poll: the request is already waiting when the command is enqueued and + // must return right away with it instead of at the end of the hold. + let longPollStart = Date() + // Blocking socket work runs on a Dispatch thread so a narrow Swift task pool (CI runners) never starves. + let longPoll = Task { await LoopbackHTTP.background { poll(port, instance: "inst-a", wait: 15) } } + try? await Task.sleep(nanoseconds: 300_000_000) + let producer = Task { @MainActor in await bridge.enqueueBrowserCommand("listTabs", ["_browserInstanceID": "inst-a"]) } + let (longPollResponse, delivered) = await longPoll.value + let longPollSeconds = Date().timeIntervalSince(longPollStart) + check(longPollResponse?.status == 200 && delivered.count == 1 && longPollSeconds < 3, + "Long poll returns as soon as a command is enqueued (\(String(format: "%.2f", longPollSeconds))s)") + check(longPollResponse?.headers["x-holmes-long-poll"] == "1", "Server advertises long poll support") + check(delivered.first?["session"] as? String == bridge.commandQueue.session, "Delivered command carries the launch session") + let id = delivered.first?["id"] as? Int ?? -1 + let posted = await LoopbackHTTP.background { postResult(port, ["id": id, "ok": true, "tabs": [Any](), + "session": bridge.commandQueue.session]) } + check(posted?.status == 200, "Result POST accepted") + let producerResult = await producer.value + check(producerResult["ok"] as? Bool == true, "Producer resolves with the posted result") + + // A long poll with nothing to deliver ends at its hold time, not never. + let idleStart = Date() + let idle = await LoopbackHTTP.background { poll(port, instance: "inst-a", wait: 1) } + let idleSeconds = Date().timeIntervalSince(idleStart) + check(idle.0?.status == 200 && idle.1.isEmpty && idleSeconds >= 0.9 && idleSeconds < 3, + "Idle long poll is held for the requested wait then returns an empty array") + + // A busy main thread must not stall GET /commands. The old handler blocked on + // DispatchQueue.main.sync and would take the whole sleep to answer. + let busyProducer = Task { @MainActor in await bridge.enqueueBrowserCommand("listTabs", ["_browserInstanceID": "inst-busy"]) } + await waitUntil("busy command queued") { bridge.testPendingCommandIDs.count == 1 } + let busyTiming = LockedBox<(TimeInterval, Int)?>(nil) + DispatchQueue.global().asyncAfter(deadline: .now() + 0.2) { + let start = Date() + let (_, commands) = poll(port, instance: "inst-busy") + busyTiming.value = (Date().timeIntervalSince(start), commands.count) + } + usleep(2_500_000) // the main thread is deliberately blocked + await waitUntil("busy poll finished") { busyTiming.value != nil } + let (busySeconds, busyCount) = busyTiming.value! + check(busyCount == 1 && busySeconds < 1.5, + "GET /commands answers while the main thread is blocked (\(String(format: "%.2f", busySeconds))s)") + let busyID = bridge.commandQueue.deliveredIDs.first ?? -1 + _ = await LoopbackHTTP.background { postResult(port, ["id": busyID, "ok": true]) } + check((await busyProducer.value)["ok"] as? Bool == true, "Busy main thread command still completes") + + // Deadlines: undelivered gets the distinct asleep error. + bridge.commandUndeliveredTimeout = 0.6 + bridge.commandResultTimeout = 0.8 + let asleepStart = Date() + let asleep = await bridge.enqueueBrowserCommand("listTabs", ["_browserInstanceID": "never-polls"]) + check(asleep["error"] as? String == "extension_asleep" && asleep["undelivered"] as? Bool == true + && Date().timeIntervalSince(asleepStart) < 2, + "Never fetched command fails as extension_asleep, not a generic timeout") + + // The result clock starts at delivery, not at enqueue. + let slowStart = Date() + let slow = Task { @MainActor in await bridge.enqueueBrowserCommand("fillField", ["_browserInstanceID": "inst-slow", "value": "x"]) } + try? await Task.sleep(nanoseconds: 450_000_000) + let slowDelivered = await LoopbackHTTP.background { poll(port, instance: "inst-slow").1 } + check(slowDelivered.count == 1, "Slow worker fetches the command before the undelivered deadline") + let slowResult = await slow.value + let slowSeconds = Date().timeIntervalSince(slowStart) + check(slowResult["error"] as? String == "timeout" && slowResult["delivered"] as? Bool == true && slowSeconds >= 1.15, + "Delivered command times out measured from delivery (\(String(format: "%.2f", slowSeconds))s)") + let slowID = slowDelivered.first?["id"] as? Int ?? -1 + _ = await LoopbackHTTP.background { postResult(port, ["id": slowID, "ok": true, "filled": true]) } + await waitUntil("late result recorded") { bridge.lateResultsIgnored == 1 } + check(bridge.testPendingCommandIDs.isEmpty && bridge.testAwaitingCommandCount == 0 && bridge.commandQueue.deliveredIDs.isEmpty, + "Late result after a timeout is logged and ignored without re-enqueueing") + + // A started ack from a worker that queued the command behind another one + // restarts the result clock. + let queued = Task { @MainActor in await bridge.enqueueBrowserCommand("click", ["_browserInstanceID": "inst-slow", "selector": "a"]) } + let queuedDelivered = await LoopbackHTTP.background { poll(port, instance: "inst-slow").1 } + let queuedID = queuedDelivered.first?["id"] as? Int ?? -1 + try? await Task.sleep(nanoseconds: 600_000_000) + _ = await LoopbackHTTP.background { postResult(port, ["id": queuedID, "_holmesStarted": true]) } + try? await Task.sleep(nanoseconds: 500_000_000) + check(bridge.testAwaitingCommandCount == 1, "Started ack keeps a command queued in the browser from timing out") + _ = await LoopbackHTTP.background { postResult(port, ["id": queuedID, "ok": true, "clicked": true]) } + check((await queued.value)["clicked"] as? Bool == true, "Command that started late still delivers its result") + + // A result from another launch's session never completes this launch's id. + bridge.commandResultTimeout = 3 + let foreign = Task { @MainActor in await bridge.enqueueBrowserCommand("click", ["_browserInstanceID": "inst-s", "selector": "b"]) } + let foreignID = await LoopbackHTTP.background { poll(port, instance: "inst-s").1.first?["id"] as? Int ?? -1 } + _ = await LoopbackHTTP.background { postResult(port, ["id": foreignID, "ok": true, "session": "previous-launch"]) } + try? await Task.sleep(nanoseconds: 200_000_000) + check(bridge.testAwaitingCommandCount == 1, "Result stamped with another session is ignored") + _ = await LoopbackHTTP.background { postResult(port, ["id": foreignID, "ok": true, "session": bridge.commandQueue.session]) } + check((await foreign.value)["ok"] as? Bool == true, "Matching session completes the command") + + // A long poll whose client hangs up must not swallow a later command. + bridge.commandUndeliveredTimeout = 5 + LoopbackHTTP.abandon(port: port, path: "/commands", headers: ["X-Holmes-Token": token, + "X-Holmes-Browser-Instance": "inst-h", "X-Holmes-Long-Poll": "20"], after: 0.2) + try? await Task.sleep(nanoseconds: 1_300_000_000) + let afterHangup = Task { @MainActor in await bridge.enqueueBrowserCommand("listTabs", ["_browserInstanceID": "inst-h"]) } + await waitUntil("hangup command queued") { bridge.testPendingCommandIDs.count == 1 } + try? await Task.sleep(nanoseconds: 300_000_000) + let rescued = await LoopbackHTTP.background { poll(port, instance: "inst-h").1 } + check(rescued.count == 1, "Abandoned long poll does not consume a command enqueued after the hangup") + _ = await LoopbackHTTP.background { postResult(port, ["id": rescued.first?["id"] as? Int ?? -1, "ok": true]) } + _ = await afterHangup.value + } + + /// Body limits: /context stays small, /command-result takes large results, and + /// an oversize body always gets a readable 413 instead of a reset connection. + @MainActor static func runBodyLimits(check: (Bool, String) -> Void) async { + let (bridge, port) = makeBridge() + defer { bridge.stop() } + bridge.commandResultTimeout = 10 + + let big = Task { @MainActor in await bridge.enqueueBrowserCommand("screenshotTab", ["_browserInstanceID": "inst-big"]) } + let bigID = await LoopbackHTTP.background { poll(port, instance: "inst-big").1.first?["id"] as? Int ?? -1 } + let twoMegabytes = String(repeating: "A", count: 2 * 1024 * 1024) + let accepted = await LoopbackHTTP.background { postResult(port, ["id": bigID, "ok": true, "dataUrl": twoMegabytes]) } + check(accepted?.status == 200, "A 2 MB command result is accepted (the old 512 KB cap returned 413)") + check(((await big.value)["dataUrl"] as? String)?.count == twoMegabytes.count, "The large result reaches the producer intact") + + let oversize = Data(repeating: 0x41, count: BridgeProtocol.maxCommandResultBytes + 1024) + let rejected = await LoopbackHTTP.background { + LoopbackHTTP.request(port: port, method: "POST", path: "/command-result", + headers: ["X-Holmes-Token": token, "Content-Type": "application/json"], body: oversize, timeout: 20) + } + check(rejected?.status == 413, "A result over the 16 MB cap gets a readable 413 after the body is drained") + check((rejected?.json as? [String: Any])?["limit"] as? Int == BridgeProtocol.maxCommandResultBytes, + "The 413 names the limit so the extension can explain the size") + + let bigContext = Data(repeating: 0x41, count: BridgeProtocol.maxBodyBytes + 1) + let contextRejected = await LoopbackHTTP.background { + LoopbackHTTP.request(port: port, method: "POST", path: "/context", + headers: ["X-Holmes-Token": token, "Content-Type": "application/json"], body: bigContext) + } + check(contextRejected?.status == 413, "Page context keeps its 512 KB cap") + let after = await LoopbackHTTP.background { LoopbackHTTP.request(port: port, method: "GET", path: "/health") } + check(after?.status == 200, "The server keeps serving after oversize requests") + } + + /// accept/bind resilience and handler slot limits. + @MainActor static func runLifecycle(check: (Bool, String) -> Void) async { + var backoff = BridgeBackoff(base: 0.01, cap: 1) + let delays = (0..<10).map { _ in backoff.failure() } + check(delays[0] == 0.01 && delays[1] == 0.02 && delays[2] == 0.04 && delays.last == 1 && delays.allSatisfy { $0 <= 1 }, + "accept() failures back off exponentially and are capped at 1s instead of spinning") + backoff.success() + check(backoff.failure() == 0.01, "A successful accept resets the backoff") + + // Port already taken: the error is published and the bind retried. + let (holder, port) = makeBridge() + let environment = BrowserBridge.ContextEnvironment(frontmost: { nil }, ownBundleIdentifier: "test.holmes", nameForBundle: { _ in nil }) + let contender = BrowserBridge(testToken: token, environment: environment, port: port) + contender.bindBackoff = BridgeBackoff(base: 0.2, cap: 0.4) + contender.start() + check(!contender.isRunning && contender.lastError?.contains("already in use") == true, + "A taken port is reported through lastError: \(contender.lastError ?? "nil")") + holder.stop() + await waitUntil("contender binds after the port frees", timeout: 5) { contender.isRunning } + check(contender.lastError == nil && contender.boundPort == port, "Background bind retry recovers and clears the error") + let recovered = await LoopbackHTTP.background { LoopbackHTTP.request(port: port, method: "GET", path: "/health") } + check(recovered?.status == 200, "The retried listener serves requests") + + // Long polls are capped so they can never occupy every handler slot. + let holds = (0.. (Int, TimeInterval) in + let start = Date() + let response = LoopbackHTTP.request(port: port, method: "GET", path: "/health", timeout: 8) + return (response?.status ?? -1, Date().timeIntervalSince(start)) + } } + } + var backlogResults: [(Int, TimeInterval)] = [] + for request in backlog { backlogResults.append(await request.value) } + let slowest = backlogResults.map(\.1).max() ?? 99 + check(backlogResults.allSatisfy { $0.0 == 503 } && slowest < 1.0, + "With every handler stalled a backlog of 5 requests all get 503 within \(String(format: "%.2f", slowest))s") + idle.forEach { close($0) } + try? await Task.sleep(nanoseconds: 300_000_000) + let healthy = await LoopbackHTTP.background { LoopbackHTTP.request(port: port, method: "GET", path: "/health") } + check(healthy?.status == 200, "Service resumes once stalled clients go away") + contender.stop() + } + + static func beat(_ port: UInt16, secret: String, origin: String?, instance: String? = nil, focused: Bool? = nil) -> Int { + var headers = ["X-Holmes-Token": secret, "Content-Type": "application/json"] + if let origin { headers["Origin"] = origin } + if let instance { headers["X-Holmes-Browser-Instance"] = instance } + if let focused { headers["X-Holmes-Browser-Focused"] = focused ? "1" : "0" } + return LoopbackHTTP.request(port: port, method: "POST", path: "/heartbeat", headers: headers, + body: Data("{}".utf8))?.status ?? -1 + } + + /// Several paired browsers, extension origin pairing, removal, and routing of + /// commands that name no browser. + @MainActor static func runPairing(check: (Bool, String) -> Void) async { + let store = PairedExtensionStore.memory() + let environment = BrowserBridge.ContextEnvironment(frontmost: { .init(name: "Google Chrome", bundleIdentifier: "com.google.Chrome") }, + ownBundleIdentifier: "test.holmes", nameForBundle: { _ in nil }) + let bridge = BrowserBridge(testToken: token, environment: environment, port: 0, pairingStore: store) + bridge.start() + let port = bridge.boundPort! + let chrome = "chrome-extension-secret-0001", comet = "comet-extension-secret-00002" + + check(await LoopbackHTTP.background { beat(port, secret: chrome, origin: "chrome-extension://abc") } == 401, + "An unknown token is refused while pairing is not armed") + bridge.beginPairing() + check(await LoopbackHTTP.background { beat(port, secret: chrome, origin: nil) } == 401, + "A native client with no Origin cannot claim the pairing window") + check(await LoopbackHTTP.background { beat(port, secret: chrome, origin: "https://evil.example") } == 401, + "A web page origin cannot claim the pairing window") + check(bridge.isPairing, "Refused attempts do not consume the window") + check(await LoopbackHTTP.background { beat(port, secret: chrome, origin: "chrome-extension://abc", instance: "chrome-inst") } == 200, + "An extension origin pairs inside the window") + await waitUntil("chrome paired") { bridge.pairedExtensions.count == 1 } + check(bridge.recentlyPairedExtension?.token == chrome, + "The newly paired browser is surfaced right after adoption so an unexpected pairing is visible") + check(!bridge.isPairing, "The window closes after one adoption") + + bridge.beginPairing() + check(await LoopbackHTTP.background { beat(port, secret: comet, origin: "chrome-extension://def", instance: "comet-inst") } == 200, + "A second browser pairs in a new window") + await waitUntil("comet paired") { bridge.pairedExtensions.count == 2 } + check(await LoopbackHTTP.background { beat(port, secret: chrome, origin: "chrome-extension://abc", instance: "chrome-inst") } == 200, + "Pairing another browser keeps the first token valid") + await waitUntil("instances labelled") { bridge.pairedExtensions.allSatisfy { $0.instanceID != nil } } + check(store.load().count == 2 && Set(store.load().compactMap(\.instanceID)) == ["chrome-inst", "comet-inst"], + "Both pairings are persisted with their browser instance") + + // Routing: a command that names no browser goes to the one most recently + // in front, not to whichever polls first. + _ = await LoopbackHTTP.background { beat(port, secret: comet, origin: "chrome-extension://def", instance: "comet-inst", focused: true) } + try? await Task.sleep(nanoseconds: 20_000_000) + _ = await LoopbackHTTP.background { beat(port, secret: chrome, origin: "chrome-extension://abc", instance: "chrome-inst", focused: false) } + let generic = Task { @MainActor in await bridge.enqueueBrowserCommand("listTabs", [:]) } + await waitUntil("generic queued") { bridge.testPendingCommandIDs.count == 1 } + let chromeFirst = await LoopbackHTTP.background { poll(port, instance: "chrome-inst", token: chrome).1 } + check(chromeFirst.isEmpty, "A background browser polling first does not take a generic command") + let cometGot = await LoopbackHTTP.background { poll(port, instance: "comet-inst", token: comet).1 } + check(cometGot.count == 1, "The most recently focused browser receives the generic command") + _ = await LoopbackHTTP.background { postResult(port, ["id": cometGot.first?["id"] as? Int ?? -1, "ok": true], token: comet) } + _ = await generic.value + _ = await LoopbackHTTP.background { beat(port, secret: chrome, origin: "chrome-extension://abc", instance: "chrome-inst", focused: true) } + let secondGeneric = Task { @MainActor in await bridge.enqueueBrowserCommand("listTabs", [:]) } + await waitUntil("second generic queued") { bridge.testPendingCommandIDs.count == 1 } + let cometSecond = await LoopbackHTTP.background { poll(port, instance: "comet-inst", token: comet).1 } + let chromeSecond = await LoopbackHTTP.background { poll(port, instance: "chrome-inst", token: chrome).1 } + check(cometSecond.isEmpty && chromeSecond.count == 1, "Focusing the other browser moves generic commands to it") + _ = await LoopbackHTTP.background { postResult(port, ["id": chromeSecond.first?["id"] as? Int ?? -1, "ok": true], token: chrome) } + _ = await secondGeneric.value + bridge.stop() + + // A relaunch keeps both pairings; removing one refuses only that token. + let relaunched = BrowserBridge(testToken: token, environment: environment, port: 0, pairingStore: store) + relaunched.start() + let relaunchPort = relaunched.boundPort! + let chromeAfterRelaunch = await LoopbackHTTP.background { beat(relaunchPort, secret: chrome, origin: "chrome-extension://abc") } + let cometAfterRelaunch = await LoopbackHTTP.background { beat(relaunchPort, secret: comet, origin: "chrome-extension://def") } + check(chromeAfterRelaunch == 200 && cometAfterRelaunch == 200, "Both pairings survive a relaunch") + relaunched.removePairedExtension(chrome) + check(await LoopbackHTTP.background { beat(relaunchPort, secret: chrome, origin: "chrome-extension://abc") } == 401, + "A removed pairing is refused") + let cometAfterRemoval = await LoopbackHTTP.background { beat(relaunchPort, secret: comet, origin: "chrome-extension://def") } + check(cometAfterRemoval == 200 && store.load().map(\.token) == [comet], "Removing one pairing keeps the other") + relaunched.stop() + } + + /// Page context health, instance tracking without a context post, persistence + /// across launches, and accurate per error messages. + @MainActor static func runLiveness(check: (Bool, String) -> Void) async { + var frontmost = BrowserBridge.AppIdentity(name: "Google Chrome", bundleIdentifier: "com.google.Chrome") + let environment = BrowserBridge.ContextEnvironment(frontmost: { frontmost }, ownBundleIdentifier: "test.holmes", + nameForBundle: { _ in "Google Chrome" }) + func sighting(_ instance: String, focused: Bool? = nil, script: String? = nil) -> BridgeSighting { + let body = script.map { try! JSONSerialization.data(withJSONObject: ["activeTab": ["script": $0]]) } + return BridgeSighting(token: token, instance: instance, focused: focused, body: body) + } + let page = try! JSONSerialization.data(withJSONObject: ["app": "Chrome", "site": "example.test", "url": "https://example.test/a", + "title": "Example page", "headline": "Reading Example page", "isActiveTab": true, "visible": true, "focused": true, + "browserInstanceId": "chrome-inst", "emailComposeProtocolVersion": 1]) + + let bridge = BrowserBridge(testToken: token, environment: environment) + bridge.testSighting(sighting("chrome-inst", focused: true, script: "missing")) + check(bridge.isExtensionConnected && bridge.isPageContextStale && bridge.linkState == .pageContextStale, + "Worker heartbeats with an orphaned active tab read as page context stale, not fully connected") + _ = bridge.testIngest(page) + check(!bridge.isPageContextStale && bridge.linkState == .connected, "A page context post clears the stale state") + bridge.testSighting(sighting("chrome-inst", script: "restricted")) + check(!bridge.isPageContextStale, "A browser internal page is not stale") + bridge.testSighting(sighting("chrome-inst", script: "ok")) + check(!bridge.isPageContextStale, "A live content script is not stale") + + let legacy = BrowserBridge(testToken: token, environment: environment) + legacy.testSighting(sighting("old-inst")) + legacy.testRefreshConnectionState(now: Date().addingTimeInterval(BrowserBridge.pageContextTimeout + 20)) + check(legacy.isExtensionConnected && legacy.isPageContextStale, + "Without a probe, a frontmost browser whose page stays silent while the worker beats is stale") + frontmost = .init(name: "Notes", bundleIdentifier: "com.apple.Notes") + legacy.testSighting(sighting("old-inst")) + legacy.testRefreshConnectionState(now: Date().addingTimeInterval(BrowserBridge.pageContextTimeout + 20)) + check(!legacy.isPageContextStale, "A silent page is not stale while the user is in another app") + frontmost = .init(name: "Google Chrome", bundleIdentifier: "com.google.Chrome") + + // After an app restart no context has posted yet; a focused heartbeat is + // enough to target the right browser instead of saying reload. + let defaults = UserDefaults(suiteName: "holmes.bridge.tests.\(UUID().uuidString)")! + let restarted = BrowserBridge(testToken: token, environment: environment) + restarted.testUseInstanceDefaults(defaults) + restarted.testSighting(sighting("comet-inst", focused: true)) + check(defaults.string(forKey: BrowserBridge.lastInstanceDefaultsKey) == "comet-inst", + "The browser instance seen in front is persisted") + restarted.commandResultTimeout = 5 + let read = Task { @MainActor in await restarted.refreshEmailComposeContext() } + await waitUntil("refresh targets instance") { restarted.testPendingCommandIDs.count == 1 } + let delivered = try! JSONSerialization.jsonObject(with: restarted.testDrainCommands(instance: "comet-inst")) as! [[String: Any]] + check(delivered.count == 1, "A compose refresh after restart targets the instance from heartbeats") + restarted.testCommandResult(try! JSONSerialization.data(withJSONObject: ["id": delivered[0]["id"]!, "ok": false, + "error": "Could not establish connection. Receiving end does not exist."])) + check(await read.value == nil && restarted.emailComposeUnavailableReason?.contains("chrome://extensions") == true + && restarted.emailComposeUnavailableReason?.contains("Refresh the email tab") == true, + "A genuinely missing content script gets refresh then reload advice") + + let relaunched = BrowserBridge(testToken: token, environment: environment) + relaunched.testUseInstanceDefaults(defaults) + relaunched.commandUndeliveredTimeout = 0.3 + let asleep = await relaunched.refreshEmailComposeContext() + check(asleep == nil && relaunched.emailComposeUnavailableReason?.contains("isn't picking up requests") == true + && relaunched.emailComposeUnavailableReason?.contains("chrome://extensions") == false, + "A remembered instance whose worker never polls is reported as asleep, not as needing reload") + + let messages: [([String: Any], String)] = [ + (["error": "timeout"], "didn't answer in time"), + (["error": "queue_full"], "too many browser requests"), + (["ok": false, "refused": true, "reason": "The composer is no longer in the active tab."], "Bring the email tab to the front"), + (["ok": false, "refused": true, "reason": "No active compose window."], "Open the email you're writing"), + (["ok": false, "error": "result too large (20000000 bytes)"], "too large"), + (["ok": false, "refused": true, "reason": "The draft belongs to another browser session."], "another browser session") + ] + for (result, expected) in messages { + let message = BrowserBridge.browserFailureMessage(result) + check(message.contains(expected) && !message.contains("chrome://extensions"), + "\(result) maps to an accurate message without reload advice") + } + + // The remembered browser (comet-inst, from the previous launch) is not alive + // now; a different browser is polling. Refresh must target the live one + // instead of waiting out the undelivered deadline for a dead instance. + let switched = BrowserBridge(testToken: token, environment: environment) + switched.testUseInstanceDefaults(defaults) + switched.commandQueue.noteSeen(instance: "new-inst", focused: false) + switched.commandUndeliveredTimeout = 1 + switched.commandResultTimeout = 5 + let switchedRead = Task { @MainActor in await switched.refreshEmailComposeContext() } + await waitUntil("switched refresh queued") { switched.testPendingCommandIDs.count == 1 } + let toLive = try! JSONSerialization.jsonObject(with: switched.testDrainCommands(instance: "new-inst")) as! [[String: Any]] + check(toLive.count == 1, "A remembered browser that is not alive this launch does not win over the live one") + if let id = toLive.first?["id"] { + switched.testCommandResult(try! JSONSerialization.data(withJSONObject: ["id": id, "ok": false, "error": "timeout"])) + } + _ = await switchedRead.value + } +} + +extension LoopbackHTTP { + /// Connects and sends nothing, holding a server handler slot until closed. + static func openIdle(port: UInt16) -> Int32 { + let fd = socket(AF_INET, SOCK_STREAM, 0) + var addr = sockaddr_in() + addr.sin_family = sa_family_t(AF_INET) + addr.sin_port = port.bigEndian + addr.sin_addr.s_addr = INADDR_LOOPBACK.bigEndian + _ = withUnsafePointer(to: &addr) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(fd, $0, socklen_t(MemoryLayout.size)) } + } + return fd + } + + /// Opens a request, then closes the socket without reading the response. + static func abandon(port: UInt16, path: String, headers: [String: String], after delay: TimeInterval) { + DispatchQueue.global().async { + let fd = socket(AF_INET, SOCK_STREAM, 0) + guard fd >= 0 else { return } + var addr = sockaddr_in() + addr.sin_family = sa_family_t(AF_INET) + addr.sin_port = port.bigEndian + addr.sin_addr.s_addr = INADDR_LOOPBACK.bigEndian + _ = withUnsafePointer(to: &addr) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(fd, $0, socklen_t(MemoryLayout.size)) } + } + var head = "GET \(path) HTTP/1.1\r\nHost: 127.0.0.1\r\n" + for (key, value) in headers { head += "\(key): \(value)\r\n" } + head += "\r\n" + _ = head.withCString { send(fd, $0, strlen($0), 0) } + Thread.sleep(forTimeInterval: delay) + close(fd) + } + } +} diff --git a/holmes/tests/BridgeSoak.swift b/holmes/tests/BridgeSoak.swift new file mode 100644 index 0000000..5048d15 --- /dev/null +++ b/holmes/tests/BridgeSoak.swift @@ -0,0 +1,202 @@ +import Foundation + +// Bridge reliability soak: N command round trips through the REAL BrowserBridge +// server on a loopback port, driven by a simulated extension worker that long polls, +// gets evicted for seconds at a time, drops and retries result posts, posts +// duplicates, while the main thread is repeatedly blocked. Prints the success rate +// and exits nonzero unless every round trip succeeds. + +struct SplitMix64 { + private var state: UInt64 + init(seed: UInt64) { state = seed } + mutating func next() -> UInt64 { + state &+= 0x9E37_79B9_7F4A_7C15 + var z = state + z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9 + z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB + return z ^ (z >> 31) + } + mutating func unit() -> Double { Double(next() >> 11) / Double(1 << 53) } +} + +final class SoakStats: @unchecked Sendable { + private let lock = NSLock() + private var counters: [String: Int] = [:] + func bump(_ key: String, by amount: Int = 1) { lock.lock(); counters[key, default: 0] += amount; lock.unlock() } + subscript(_ key: String) -> Int { lock.lock(); defer { lock.unlock() }; return counters[key, default: 0] } +} + +/// A fake MV3 worker speaking the production wire protocol over real sockets. +final class SimulatedWorker: @unchecked Sendable { + let port: UInt16 + let token: String + let instance = "soak-instance" + let stats: SoakStats + private let random: LockedBox + private let evictedUntil = LockedBox(Date.distantPast) + private let stopped = LockedBox(false) + private let executors = DispatchQueue(label: "soak.worker.executors", attributes: .concurrent) + + init(port: UInt16, token: String, seed: UInt64, stats: SoakStats) { + self.port = port + self.token = token + self.stats = stats + random = LockedBox(SplitMix64(seed: seed)) + } + + private func roll() -> Double { + var value = 0.0 + random.mutate { value = $0.unit() } + return value + } + + private var isEvicted: Bool { Date() < evictedUntil.value } + + func start() { + Thread.detachNewThread { [self] in pollLoop() } + Thread.detachNewThread { [self] in heartbeatLoop() } + } + + func stop() { stopped.value = true } + + private func headers() -> [String: String] { + ["X-Holmes-Token": token, "X-Holmes-Browser-Instance": instance, "X-Holmes-Browser-Focused": "1"] + } + + private func heartbeatLoop() { + while !stopped.value { + if !isEvicted { + var beat = headers() + beat["Content-Type"] = "application/json" + let body = Data(#"{"activeTab":{"script":"ok"}}"#.utf8) + _ = LoopbackHTTP.request(port: port, method: "POST", path: "/heartbeat", headers: beat, body: body, timeout: 5) + } + usleep(1_000_000) + } + } + + private func pollLoop() { + while !stopped.value { + if isEvicted { usleep(50_000); continue } + var request = headers() + request["X-Holmes-Long-Poll"] = "20" + guard let response = LoopbackHTTP.request(port: port, method: "GET", path: "/commands", + headers: request, timeout: 28), + response.status == 200, + let commands = response.json as? [[String: Any]] else { + stats.bump("pollFailures") + usleep(200_000) + continue + } + stats.bump("polls") + for command in commands { execute(command) } + // Eviction: MV3 kills the worker; nothing polls until it is woken again. + if roll() < 0.06 { + let gap = 1 + roll() * 3 + evictedUntil.value = Date().addingTimeInterval(gap) + stats.bump("evictions") + } + } + } + + private func execute(_ command: [String: Any]) { + let workMicros = UInt32(roll() * 40_000) + let dropFirstPost = roll() < 0.10 + let duplicatePost = roll() < 0.05 + executors.async { [self] in + usleep(workMicros) + let params = command["params"] as? [String: Any] ?? [:] + var result: [String: Any] = ["id": command["id"] ?? -1, "action": command["action"] ?? "", + "ok": true, "echo": params["n"] ?? -1] + if let session = command["session"] { result["session"] = session } + let body = (try? JSONSerialization.data(withJSONObject: result)) ?? Data() + var postHeaders = headers() + postHeaders["Content-Type"] = "application/json" + if dropFirstPost { + // The first POST is lost (worker hiccup); the retry with backoff lands. + stats.bump("droppedFirstPosts") + usleep(200_000) + } + var attempts = 0 + while attempts < 4 { + attempts += 1 + if let response = LoopbackHTTP.request(port: port, method: "POST", path: "/command-result", + headers: postHeaders, body: body, timeout: 10), + response.status == 200 { break } + stats.bump("resultRetries") + usleep(UInt32(250_000 * attempts)) + } + if duplicatePost { + // Idempotent re-delivery of a stored result must be harmless. + _ = LoopbackHTTP.request(port: port, method: "POST", path: "/command-result", + headers: postHeaders, body: body, timeout: 10) + stats.bump("duplicatePosts") + } + } + } +} + +@main struct BridgeSoak { + @MainActor static func main() async { + setbuf(stdout, nil) + let total = Int(ProcessInfo.processInfo.environment["SOAK_COMMANDS"] ?? "") ?? 200 + let seed = UInt64(ProcessInfo.processInfo.environment["SOAK_SEED"] ?? "") ?? 20260913 + let concurrency = 4 + let token = "soak-test-token-000000001" + let environment = BrowserBridge.ContextEnvironment(frontmost: { .init(name: "Google Chrome", bundleIdentifier: "com.google.Chrome") }, + ownBundleIdentifier: "test.holmes", nameForBundle: { _ in "Google Chrome" }) + let bridge = BrowserBridge(testToken: token, environment: environment, port: 0) + bridge.start() + guard let port = bridge.boundPort else { + print("Bridge soak: server did not start (\(bridge.lastError ?? "unknown"))") + exit(1) + } + let stats = SoakStats() + let worker = SimulatedWorker(port: port, token: token, seed: seed, stats: stats) + worker.start() + + // Busy main thread: repeatedly block the main actor for up to ~0.9s. + let blocker = Task { @MainActor in + var generator = SplitMix64(seed: seed ^ 0xFFFF) + while !Task.isCancelled { + try? await Task.sleep(nanoseconds: 700_000_000) + usleep(UInt32(200_000 + generator.unit() * 700_000)) + stats.bump("mainThreadStalls") + } + } + + let started = Date() + var failures: [String] = [] + var succeeded = 0 + await withTaskGroup(of: (Int, [String: Any]).self) { group in + var next = 0 + func launch(_ index: Int) { + group.addTask { @MainActor in + // Every fifth command names no browser and relies on routing. + var params: [String: Any] = ["n": index] + if index % 5 != 0 { params["_browserInstanceID"] = worker.instance } + return (index, await bridge.enqueueBrowserCommand("extract", params)) + } + } + while next < min(concurrency, total) { launch(next); next += 1 } + for await (index, result) in group { + if result["ok"] as? Bool == true, result["echo"] as? Int == index { + succeeded += 1 + } else { + failures.append("#\(index): \(result)") + } + if next < total { launch(next); next += 1 } + } + } + blocker.cancel() + worker.stop() + let seconds = Date().timeIntervalSince(started) + let rate = Double(succeeded) / Double(total) * 100 + print(String(format: "Bridge soak: %d/%d command round trips succeeded (%.1f%%) in %.1fs", succeeded, total, rate, seconds)) + print(" evictions \(stats["evictions"]), main thread stalls \(stats["mainThreadStalls"]), dropped first result posts \(stats["droppedFirstPosts"]), duplicate result posts \(stats["duplicatePosts"]), result retries \(stats["resultRetries"]), polls \(stats["polls"]), poll failures \(stats["pollFailures"])") + print(" late results ignored \(bridge.lateResultsIgnored), pending \(bridge.testPendingCommandIDs.count), awaiting \(bridge.testAwaitingCommandCount)") + for failure in failures.prefix(10) { print(" FAILED \(failure)") } + bridge.stop() + exit(succeeded == total ? 0 : 1) + } +} diff --git a/holmes/tests/BrowserBridgeBackgroundTests.cjs b/holmes/tests/BrowserBridgeBackgroundTests.cjs new file mode 100644 index 0000000..5f066ed --- /dev/null +++ b/holmes/tests/BrowserBridgeBackgroundTests.cjs @@ -0,0 +1,780 @@ +// Runs the production MV3 worker (background.js + automation.js) against a mock +// chrome.* surface. No browser, no network: fetch is a scripted fake. +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); + +const extension = path.resolve(__dirname, '../holmes-extension'); +const manifest = JSON.parse(fs.readFileSync(path.join(extension, 'manifest.json'), 'utf8')); +let checks = 0; +function check(condition, description) { checks++; assert.ok(condition, description); console.log('PASS ' + description); } +// The test's own waits keep node alive; only the worker's timers are unref'd. +const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); +async function until(label, condition, timeout = 3000) { + const start = Date.now(); + while (!condition()) { + if (Date.now() - start > timeout) throw new Error('Timed out waiting for: ' + label); + await sleep(5); + } +} + +function event() { + const listeners = []; + return { listeners, addListener(fn) { listeners.push(fn); }, removeListener(fn) { const i = listeners.indexOf(fn); if (i >= 0) listeners.splice(i, 1); }, + emit(...args) { return listeners.map(fn => fn(...args)); } }; +} + +// Creates one isolated worker. `options.fetch(url, init)` scripts the bridge. +function loadWorker(options = {}) { + const tabs = new Map((options.tabs || [{ id: 17, windowId: 23, url: 'https://mail.example.test/', status: 'complete', active: true }]) + .map(tab => [tab.id, Object.assign({ status: 'complete', active: false }, tab)])); + const log = { fetches: [], injections: [], messages: [], updates: [], platformInfo: 0 }; + // Passing options.storage shares chrome.storage between two workers, which is how + // a test simulates the same browser after its MV3 worker was evicted and restarted. + const storage = options.storage || { local: new Map([['holmesToken', 'synthetic-token'], ['holmesBrowserInstance', 'test-profile']]), session: new Map() }; + // `quota` mimics chrome.storage.session's byte cap: a set that would exceed it + // throws and changes nothing, as Chrome does. + const area = (map, quota) => ({ + async get(keys) { + const list = keys == null ? [...map.keys()] : Array.isArray(keys) ? keys : typeof keys === 'string' ? [keys] : Object.keys(keys); + const out = {}; for (const key of list) if (map.has(key)) out[key] = structuredClone(map.get(key)); return out; + }, + async set(values) { + if (quota) { + const next = new Map(map); + for (const [key, value] of Object.entries(values)) next.set(key, value); + if (JSON.stringify([...next]).length > quota) { + log.sessionSetFailures = (log.sessionSetFailures || 0) + 1; + throw new Error('QUOTA_BYTES quota exceeded'); + } + } + for (const [key, value] of Object.entries(values)) map.set(key, structuredClone(value)); + }, + async remove(keys) { for (const key of [].concat(keys)) map.delete(key); } + }); + const events = { + installed: event(), startup: event(), message: event(), activated: event(), updated: event(), + removed: event(), focus: event(), alarm: event(), storageChanged: event() + }; + const timers = { + setTimeout: (fn, ms, ...args) => { const t = setTimeout(fn, ms, ...args); if (t.unref) t.unref(); return t; }, + setInterval: (fn, ms, ...args) => { const t = setInterval(fn, ms, ...args); if (t.unref) t.unref(); return t; }, + clearTimeout, clearInterval + }; + const chrome = { + runtime: { + id: 'synthetic-extension', lastError: undefined, + getManifest: () => manifest, + getPlatformInfo: async () => { log.platformInfo++; return { os: 'mac' }; }, + onInstalled: events.installed, onStartup: events.startup, onMessage: events.message + }, + storage: { local: area(storage.local), session: options.noSessionStorage ? undefined : area(storage.session, options.sessionQuotaBytes), onChanged: events.storageChanged }, + alarms: { onAlarm: events.alarm, get: (name, cb) => cb(undefined), create() {} }, + scripting: { + async executeScript(details) { + log.injections.push(details); + if (options.executeScript) return options.executeScript(details, tabs); + return [{ result: undefined }]; + } + }, + tabs: { + onActivated: events.activated, onUpdated: events.updated, onRemoved: events.removed, + async query(filter = {}) { + if (options.queryDelayMs) await sleep(options.queryDelayMs); + let list = [...tabs.values()]; + if (filter.active) list = list.filter(tab => tab.active); + if (filter.url) { + const patterns = [].concat(filter.url).map(p => p.split('://')[0]); + list = list.filter(tab => patterns.some(scheme => tab.url.startsWith(scheme + '://'))); + } + return list; + }, + async get(id) { if (!tabs.has(id)) throw new Error('No tab with id: ' + id); return tabs.get(id); }, + async update(id, props) { + log.updates.push({ id, props }); + const tab = tabs.get(id); + if (props.active) { for (const other of tabs.values()) if (other.windowId === tab.windowId) other.active = false; tab.active = true; } + if (props.url) { + // lazyNavigate mirrors real Chrome: update resolves before the new load + // starts, so the tab still reports the old page as complete. + if (!options.lazyNavigate) { tab.url = props.url; tab.status = 'loading'; } + if (options.onNavigate) options.onNavigate(tab, events, props.url); + } + return tab; + }, + async create(props) { const id = 100 + tabs.size; const tab = { id, windowId: 23, url: props.url, status: 'loading', active: props.active !== false }; tabs.set(id, tab); return tab; }, + async sendMessage(tabId, message) { + log.messages.push({ tabId, message }); + if (options.sendMessage) return options.sendMessage(tabId, message, tabs); + if (message.type === 'holmes:ping') return { ok: true, visible: true, isActiveTab: true }; + return { ok: true }; + }, + async captureVisibleTab(windowId, opts) { + log.captures = log.captures || []; + log.captures.push(opts); + return options.capture ? options.capture(opts) : 'data:image/jpeg;base64,AAAA'; + } + }, + windows: { + onFocusChanged: events.focus, + async get(id) { return { id, type: 'normal', focused: true }; }, + async getLastFocused() { return { id: 23, type: 'normal', focused: options.focused !== false }; }, + async update(id, props) { log.updates.push({ window: id, props }); return { id }; } + } + }; + const context = vm.createContext(Object.assign({ + console: options.quiet === false ? console : { log() {}, warn() {}, error() {}, info() {} }, + crypto: { randomUUID: () => 'uuid-' + Math.random().toString(16).slice(2) }, + AbortController, URL, TextEncoder, structuredClone, Blob, Response, + chrome, + fetch: async (url, init = {}) => { + const entry = { url, init, aborted: false }; + log.fetches.push(entry); + if (init.signal) init.signal.addEventListener('abort', () => { entry.aborted = true; }); + const handler = options.fetch || (() => ({ status: 200, body: [] })); + const reply = await handler(url, init, entry); + if (reply instanceof Error) throw reply; + const status = reply.status || 200; + const headers = new Map(Object.entries(reply.headers || {}).map(([k, v]) => [k.toLowerCase(), v])); + return { ok: status >= 200 && status < 300, status, headers: { get: key => headers.get(String(key).toLowerCase()) || null }, + json: async () => reply.body, text: async () => JSON.stringify(reply.body) }; + }, + __holmesBridgeConfig: Object.assign({ pollIdleMs: 40, pollErrorBackoffMs: 40, heartbeatProbeMs: 0, visibilityPollMs: 10 }, options.config || {}) + }, timers)); + context.self = context; + context.importScripts = (...files) => { for (const file of files) vm.runInContext(fs.readFileSync(path.join(extension, file), 'utf8'), context, { filename: file }); }; + vm.runInContext(fs.readFileSync(path.join(extension, 'background.js'), 'utf8'), context, { filename: 'background.js' }); + // Stops a finished test's worker from doing real work: every later fetch fails + // fast, so its loops fall back to their error backoff. + const dispose = () => { options.fetch = () => new Error('disposed'); }; + return { context, chrome, tabs, log, events, storage, dispose }; +} + +// A fetch that never answers on its own and rejects only when aborted. +function hangUntilAborted(init) { + return new Promise((_, reject) => { + if (init.signal) init.signal.addEventListener('abort', () => reject(new Error('The operation was aborted.'))); + }); +} + +async function transportTests() { + // Heartbeat with a server that accepts the connection and never answers. + let worker = loadWorker({ + config: { fetchTimeoutMs: { heartbeat: 60, relay: 60, commands: 80, result: 60 }, pollErrorBackoffMs: 30 }, + fetch: (url, init) => hangUntilAborted(init) + }); + const beat = await Promise.race([worker.context.sendHeartbeat().then(() => 'done'), sleep(600).then(() => 'hung')]); + check(beat === 'done' && worker.log.fetches.some(f => f.url.endsWith('/heartbeat') && f.aborted), + 'A heartbeat to a stalled bridge is aborted by its timeout instead of hanging'); + + const relayed = await Promise.race([ + new Promise(resolve => worker.events.message.emit({ type: 'holmes:post', body: '{}' }, { tab: { id: 17, windowId: 23 } }, resolve)), + sleep(600).then(() => 'hung') + ]); + check(relayed !== 'hung' && relayed.ok === false && worker.log.fetches.some(f => f.url.endsWith('/context') && f.aborted), + 'A relayed page context post times out and reports failure to the page'); + + await until('two command polls', () => worker.log.fetches.filter(f => f.url.endsWith('/commands')).length >= 2, 1500); + const polls = worker.log.fetches.filter(f => f.url.endsWith('/commands')); + check(polls[0].aborted, 'A stalled command poll is aborted by its timeout'); + check(polls.length >= 2, 'The in flight flag clears after an aborted poll so polling continues'); + check(Number(polls[0].init.headers['X-Holmes-Long-Poll']) > 0, 'Command polls ask the bridge to long poll'); + worker.dispose(); + + // A server that supports long polling: the worker re-polls right away. + worker = loadWorker({ + config: { pollIdleMs: 400, longPollMinMs: 20 }, + fetch: async url => { + if (!url.endsWith('/commands')) return { status: 200, body: {} }; + await sleep(30); + return { status: 200, body: [], headers: { 'X-Holmes-Long-Poll': '1' } }; + } + }); + await sleep(300); + const longPolls = worker.log.fetches.filter(f => f.url.endsWith('/commands')).length; + check(longPolls >= 4, `With long poll support the worker re-polls immediately (${longPolls} polls in 300ms)`); + worker.dispose(); + + // An older app without long polling: idle interval, not a tight loop. + worker = loadWorker({ + config: { pollIdleMs: 150 }, + fetch: async url => ({ status: 200, body: [] }) + }); + await sleep(320); + const idlePolls = worker.log.fetches.filter(f => f.url.endsWith('/commands')).length; + check(idlePolls >= 2 && idlePolls <= 4, `Without long poll support polls keep an idle interval (${idlePolls} polls in 320ms)`); + worker.dispose(); + + // Holmes not running: failed polls back off instead of spinning. + worker = loadWorker({ config: { pollErrorBackoffMs: 100 }, fetch: () => new Error('Failed to fetch') }); + await sleep(350); + const failedPolls = worker.log.fetches.filter(f => f.url.endsWith('/commands')).length; + check(failedPolls >= 1 && failedPolls <= 6, `Failed polls back off (${failedPolls} attempts in 350ms)`); + worker.dispose(); + + // After a command arrives the worker keeps itself awake for a while, then stops. + let served = false; + worker = loadWorker({ + config: { keepaliveMs: 40, keepaliveWindowMs: 400 }, + fetch: async url => { + if (url.endsWith('/commands')) { + await sleep(20); + if (!served) { served = true; return { status: 200, body: [{ id: 1, action: 'listTabs', params: {}, session: 's1' }], headers: { 'X-Holmes-Long-Poll': '1' } }; } + return { status: 200, body: [], headers: { 'X-Holmes-Long-Poll': '1' } }; + } + return { status: 200, body: {} }; + } + }); + await until('command result posted', () => worker.log.fetches.some(f => f.url.endsWith('/command-result')), 1500); + await sleep(200); + const awake = worker.log.platformInfo; + check(awake >= 2, `The worker keeps itself awake after receiving a command (${awake} keepalive calls)`); + await sleep(700); + const settled = worker.log.platformInfo; + await sleep(200); + check(worker.log.platformInfo === settled, 'The self keepalive stops once commands have gone quiet'); + worker.dispose(); +} + +const receivingEndMissing = () => new Error('Could not establish connection. Receiving end does not exist.'); + +async function reinjectionTests() { + const worker = loadWorker({ + fetch: () => ({ status: 503, body: {} }), + tabs: [ + { id: 1, windowId: 23, url: 'https://open-before-install.test/', active: true }, + { id: 2, windowId: 23, url: 'chrome://settings/' }, + { id: 3, windowId: 23, url: 'http://discarded.test/', discarded: true }, + { id: 4, windowId: 23, url: 'https://second.test/' } + ], + executeScript(details) { if (details.target.tabId === 4 && details.world === 'MAIN') throw new Error('Cannot access contents of the page'); return [{}]; } + }); + worker.events.installed.emit({ reason: 'update', previousVersion: '2.2' }); + await until('reinjection finished', () => worker.log.injections.filter(i => i.target.tabId === 1).length >= 2); + await sleep(30); + const tab1 = worker.log.injections.filter(i => i.target.tabId === 1); + check(tab1[0].files.join() === 'history-hook.js' && tab1[0].world === 'MAIN' && tab1[0].injectImmediately === true, + 'Update reinjects the MAIN world history hook first, as at document_start'); + check(tab1[1].files.join() === 'email-compose.js,content.js' && (tab1[1].world === undefined || tab1[1].world === 'ISOLATED'), + 'Then the isolated world scripts in manifest order'); + check(!worker.log.injections.some(i => i.target.tabId === 2 || i.target.tabId === 3), + 'Restricted and discarded tabs are skipped'); + check(worker.log.injections.filter(i => i.target.tabId === 4).length === 2, + 'A failure injecting one script does not stop the rest for that tab or other tabs'); + const before = worker.log.injections.length; + worker.events.installed.emit({ reason: 'chrome_update' }); + await sleep(30); + check(worker.log.injections.length === before, 'A browser update does not reinject (manifest scripts already ran)'); +} + +async function probeTests() { + const heartbeats = []; + let pingMode = 'missing'; + const worker = loadWorker({ + config: { heartbeatProbeMs: 0 }, + fetch(url, init) { + if (url.endsWith('/heartbeat')) heartbeats.push(JSON.parse(init.body || '{}')); + return { status: url.endsWith('/commands') ? 503 : 200, body: {} }; + }, + tabs: [{ id: 9, windowId: 23, url: 'https://orphaned.test/', active: true }], + sendMessage(tabId, message) { + if (message.type !== 'holmes:ping') return { ok: true }; + if (pingMode === 'missing') throw receivingEndMissing(); + return { ok: true, visible: true, isActiveTab: true }; + } + }); + await until('first heartbeat', () => heartbeats.some(h => h.activeTab)); + const first = heartbeats.find(h => h.activeTab); + check(first.instanceId === 'test-profile' && typeof first.focused === 'boolean', 'Heartbeat body names the browser instance and focus'); + check(first.activeTab.script === 'missing' || first.activeTab.script === 'reinjected', + 'An active tab whose content script is gone is reported, not hidden behind worker heartbeats'); + await until('self heal injection', () => worker.log.injections.some(i => i.target.tabId === 9)); + check(worker.log.injections.filter(i => i.target.tabId === 9 && i.world === 'MAIN').length === 1, + 'The worker reinjects a missing active tab once'); + pingMode = 'ok'; + heartbeats.length = 0; + await worker.context.sendHeartbeat(); + check(heartbeats.at(-1).activeTab.script === 'ok', 'A live content script reports ok'); + worker.tabs.get(9).url = 'chrome://newtab/'; + await worker.context.sendHeartbeat(); + check(heartbeats.at(-1).activeTab.script === 'restricted', 'A browser page is restricted, not missing'); + const beat = worker.log.fetches.findLast(f => f.url.endsWith('/heartbeat')); + check(beat.init.headers['X-Holmes-Browser-Instance'] === 'test-profile' && beat.init.headers['X-Holmes-Browser-Focused'] === '1', + 'Heartbeat headers carry the instance and focus for routing'); +} + +// Serves each queued command once through a long polling /commands, then idles. +function commandFeed(commands) { + const queue = commands.slice(); + return async () => { + await sleep(15); + return { status: 200, body: queue.length ? [queue.shift()] : [], headers: { 'X-Holmes-Long-Poll': '1' } }; + }; +} + +function resultPosts(worker, id) { + return worker.log.fetches.filter(f => f.url.endsWith('/command-result')) + .map(f => ({ entry: f, body: JSON.parse(f.init.body) })) + .filter(p => id === undefined || p.body.id === id); +} + +async function resultDeliveryTests() { + // A result POST that fails is retried with backoff until it lands. + let attempts = 0; + let feed = commandFeed([{ id: 7, action: 'listTabs', params: {}, session: 's1' }]); + let worker = loadWorker({ + config: { resultRetryDelaysMs: [20, 40, 80] }, + fetch: async (url) => { + if (url.endsWith('/commands')) return feed(); + if (url.endsWith('/command-result')) { + attempts++; + if (attempts === 1) return new Error('Failed to fetch'); + if (attempts === 2) return { status: 503, body: {} }; + return { status: 200, body: { ok: true } }; + } + return { status: 200, body: {} }; + } + }); + await until('result delivered after retries', () => attempts >= 3, 2000); + await sleep(150); + const posts = resultPosts(worker, 7); + check(posts.length === 3 && posts.every(p => p.body.ok === true && p.body.session === 's1'), + `A failed result POST is retried with backoff until it lands (${posts.length} attempts)`); + worker.dispose(); + + // A refused token is not retried. + let unauthorized = 0; + feed = commandFeed([{ id: 8, action: 'listTabs', params: {} }]); + worker = loadWorker({ + config: { resultRetryDelaysMs: [20, 40, 80] }, + fetch: async (url) => { + if (url.endsWith('/commands')) return feed(); + if (url.endsWith('/command-result')) { unauthorized++; return { status: 401, body: {} }; } + return { status: 200, body: {} }; + } + }); + await until('401 result attempt', () => unauthorized >= 1, 2000); + await sleep(250); + check(unauthorized === 1, 'A 401 result POST is not retried'); + worker.dispose(); + + // The bridge answers 413: the worker sends a compact error explaining the size. + const huge = 'X'.repeat(200000); + let bigAttempts = 0; + feed = commandFeed([{ id: 9, action: 'extract', params: { selector: 'p' }, session: 's1' }]); + worker = loadWorker({ + executeScript: details => details.func ? [{ result: { ok: true, count: 1, elements: [{ text: huge }] } }] : [{}], + fetch: async (url, init) => { + if (url.endsWith('/commands')) return feed(); + if (url.endsWith('/command-result')) { + bigAttempts++; + return init.body.length > 100000 ? { status: 413, body: { error: 'Body exceeds', limit: 100000 } } : { status: 200, body: { ok: true } }; + } + return { status: 200, body: {} }; + } + }); + await until('compact error posted', () => resultPosts(worker, 9).length >= 2, 2000); + const compact = resultPosts(worker, 9).at(-1); + check(compact.entry.init.body.length < 4096 && compact.body.ok === false && /too large/i.test(compact.body.error) + && compact.body.bytes > 200000 && compact.body.session === 's1', + 'After a 413 the worker posts a compact error that names the result size'); + worker.dispose(); + + // A result already over the configured cap is never sent in full. + feed = commandFeed([{ id: 10, action: 'extract', params: { selector: 'p' } }]); + worker = loadWorker({ + config: { maxResultBytes: 50000 }, + executeScript: details => details.func ? [{ result: { ok: true, count: 1, elements: [{ text: huge }] } }] : [{}], + fetch: async (url) => url.endsWith('/commands') ? feed() : { status: 200, body: { ok: true } } + }); + await until('proactive compact error', () => resultPosts(worker, 10).length >= 1, 2000); + await sleep(50); + const proactive = resultPosts(worker, 10); + check(proactive.length === 1 && proactive[0].body.ok === false && proactive[0].entry.init.body.length < 4096, + 'A result over the size cap is replaced by a compact error before sending'); + worker.dispose(); + + // Screenshots are JPEG, stepping quality down until they fit. + feed = commandFeed([{ id: 11, action: 'screenshotTab', params: {} }]); + worker = loadWorker({ + config: { maxScreenshotChars: 45000 }, + capture: opts => 'data:image/jpeg;base64,' + 'A'.repeat((opts.quality || 100) * 1000), + fetch: async (url) => url.endsWith('/commands') ? feed() : { status: 200, body: { ok: true } } + }); + await until('screenshot result', () => resultPosts(worker, 11).length >= 1, 2000); + const shot = resultPosts(worker, 11)[0].body; + const qualities = worker.log.captures.map(c => c.quality); + check(worker.log.captures.every(c => c.format === 'jpeg') && shot.format === 'jpeg', + 'screenshot_tab captures JPEG instead of PNG'); + check(shot.ok === true && shot.dataUrl.length <= 45000 && qualities[0] > qualities.at(-1), + `screenshot_tab compresses until the image fits (qualities ${qualities.join(', ')})`); + worker.dispose(); +} + +async function idempotencyTests() { + const fill = (id, session = 's1') => ({ id, action: 'fillField', params: { selector: '#to', value: 'boss@example.test' }, session }); + let executions = 0; + const executeScript = details => { + if (!details.func) return [{}]; + executions++; + return [{ result: { ok: true, filled: { tag: 'input', id: 'to' }, length: 17 } }]; + }; + const okResults = async () => ({ status: 200, body: { ok: true } }); + + // The same command id delivered twice (a requeue after a lost poll response) + // runs once; the second delivery gets the stored result again. + let feed = commandFeed([fill(21), fill(21)]); + let worker = loadWorker({ executeScript, fetch: async url => url.endsWith('/commands') ? feed() : okResults() }); + await until('two results for id 21', () => resultPosts(worker, 21).length >= 2, 2000); + let posts = resultPosts(worker, 21); + check(executions === 1, `A redelivered command id executes once (${executions} executions)`); + check(posts[1].body.ok === true && posts[1].body.filled.id === 'to' && posts[1].body.session === 's1', + 'The redelivery re-posts the stored result instead of re-running fill_field'); + worker.dispose(); + + // Across a worker restart (same chrome.storage.session) the result is replayed. + const shared = { local: new Map([['holmesToken', 'synthetic-token'], ['holmesBrowserInstance', 'test-profile']]), session: new Map() }; + executions = 0; + feed = commandFeed([fill(22)]); + worker = loadWorker({ storage: shared, executeScript, fetch: async url => url.endsWith('/commands') ? feed() : okResults() }); + await until('first life result', () => resultPosts(worker, 22).length >= 1, 2000); + await sleep(50); + worker.dispose(); + feed = commandFeed([fill(22), fill(22, 's2')]); + worker = loadWorker({ storage: shared, executeScript, fetch: async url => url.endsWith('/commands') ? feed() : okResults() }); + await until('second life results', () => resultPosts(worker, 22).length >= 2, 2000); + posts = resultPosts(worker, 22); + check(executions === 2 && posts[0].body.ok === true, + 'After a worker restart the same id and session is replayed from session storage, not re-run'); + check(posts[1].body.session === 's2', 'The same numeric id from a new app launch is a different command and runs'); + worker.dispose(); + + // A command the previous worker started but never finished is not re-run blindly. + executions = 0; + const interrupted = { local: new Map(shared.local), session: new Map() }; + interrupted.session.set('holmesCommandLedger', { 's1:23': { state: 'running', action: 'fillField', at: Date.now() } }); + feed = commandFeed([fill(23)]); + worker = loadWorker({ storage: interrupted, executeScript, fetch: async url => url.endsWith('/commands') ? feed() : okResults() }); + await until('interrupted result', () => resultPosts(worker, 23).length >= 1, 2000); + posts = resultPosts(worker, 23); + check(executions === 0 && posts[0].body.ok === false && /interrupted/i.test(posts[0].body.error), + 'A command interrupted by a worker restart reports that instead of running twice'); + worker.dispose(); + + // Without chrome.storage.session (older Chrome) the in-memory ledger still dedupes. + executions = 0; + feed = commandFeed([fill(24), fill(24)]); + worker = loadWorker({ noSessionStorage: true, executeScript, fetch: async url => url.endsWith('/commands') ? feed() : okResults() }); + await until('memory ledger results', () => resultPosts(worker, 24).length >= 2, 2000); + check(executions === 1, 'Without session storage a redelivered id still executes once'); + worker.dispose(); +} + +async function concurrencyTests() { + const spans = []; + const delays = { '#slow': 300, '#first': 200, '#second': 10, '#fast': 10, '.capped': 100 }; + const executeScript = async details => { + if (!details.func) return [{}]; + const params = details.args[1] || {}; + const span = { tab: details.target.tabId, selector: params.selector, start: Date.now() }; + spans.push(span); + await sleep(delays[params.selector] || 10); + span.end = Date.now(); + return [{ result: { ok: true, count: 0, elements: [], selector: params.selector } }]; + }; + const tabs = [1, 2, 3, 4, 5, 6].map(id => ({ id, windowId: 23, url: 'https://tab' + id + '.test/', active: id === 1 })); + function batchFeed(batch) { + let served = false; + return async () => { + await sleep(15); + if (served) return { status: 200, body: [], headers: { 'X-Holmes-Long-Poll': '1' } }; + served = true; + return { status: 200, body: batch, headers: { 'X-Holmes-Long-Poll': '1' } }; + }; + } + const extract = (id, tabId, selector) => ({ id, action: 'extract', params: { tabId, selector }, session: 's1' }); + + // A long command on one tab does not stall a command for another tab. + let feed = batchFeed([extract(31, 1, '#slow'), extract(32, 2, '#fast')]); + let worker = loadWorker({ tabs, executeScript, fetch: async url => url.endsWith('/commands') ? feed() : { status: 200, body: { ok: true } } }); + await until('both results', () => resultPosts(worker, 31).some(p => !p.body._holmesStarted) && resultPosts(worker, 32).length >= 1, 3000); + const slowDone = worker.log.fetches.findIndex(f => f.url.endsWith('/command-result') && JSON.parse(f.init.body).id === 31 && !JSON.parse(f.init.body)._holmesStarted); + const fastDone = worker.log.fetches.findIndex(f => f.url.endsWith('/command-result') && JSON.parse(f.init.body).id === 32); + check(fastDone < slowDone, 'A fast command on another tab finishes while a slow one is still running'); + worker.dispose(); + + // Commands for the same tab still run strictly in order. + spans.length = 0; + feed = batchFeed([extract(33, 3, '#first'), extract(34, 3, '#second')]); + worker = loadWorker({ tabs, executeScript, fetch: async url => url.endsWith('/commands') ? feed() : { status: 200, body: { ok: true } } }); + await until('same tab results', () => resultPosts(worker, 34).some(p => !p.body._holmesStarted), 3000); + const first = spans.find(s => s.selector === '#first'), second = spans.find(s => s.selector === '#second'); + check(second.start >= first.end, 'Commands for the same tab run one at a time, in order'); + check(resultPosts(worker, 34).some(p => p.body._holmesStarted === true), + 'A command that waited behind another tells the app when it actually starts'); + worker.dispose(); + + // An overall cap bounds how many run at once. + spans.length = 0; + feed = batchFeed([1, 2, 3, 4, 5, 6].map(tab => extract(40 + tab, tab, '.capped'))); + worker = loadWorker({ tabs, config: { maxConcurrentCommands: 2 }, executeScript, + fetch: async url => url.endsWith('/commands') ? feed() : { status: 200, body: { ok: true } } }); + await until('capped results', () => [41, 42, 43, 44, 45, 46].every(id => resultPosts(worker, id).some(p => !p.body._holmesStarted)), 4000); + // True peak concurrency: sweep start and end instants (ends first on ties). + // Counting every span that overlaps a given span overcounts staggered runs. + const instants = spans.flatMap(span => [{ t: span.start, d: 1 }, { t: span.end, d: -1 }]) + .sort((a, b) => a.t - b.t || a.d - b.d); + let running = 0, peak = 0; + for (const instant of instants) { running += instant.d; peak = Math.max(peak, running); } + check(peak === 2, `No more than the configured number of commands run at once (peak ${peak})`); + worker.dispose(); +} + +async function visibilityTests() { + const expected = { identity: JSON.stringify(['test-profile', 23, 17, 'document', 'account', 1]), recipients: [], cc: [], bcc: [], subject: 's', body: '', bodyReadable: true, bodyIsEmpty: true }; + const tabs = [{ id: 17, windowId: 23, url: 'https://mail.example.test/', active: false }, { id: 28, windowId: 23, url: 'https://other.test/', active: true }]; + + // The tab becomes visible a little after activation; insertion waits for it. + let pings = 0, pingsBeforeFill = -1; + let worker = loadWorker({ + tabs, config: { visibilityPollMs: 10, visibilityTimeoutMs: 1000 }, + fetch: async () => ({ status: 503, body: {} }), + sendMessage(tabId, message) { + if (message.type === 'holmes:ping') { pings++; return { ok: true, visible: pings > 3, isActiveTab: pings > 3 }; } + if (message.type === 'holmes:fillEmailDraft') { pingsBeforeFill = pings; return { ok: true, inserted: true, identity: message.expected.identity }; } + return {}; + } + }); + let result = await worker.context.emailComposeCommand({ action: 'fill_email_draft', params: { body: 'Reviewed', expected } }); + check(result.ok === true && pingsBeforeFill >= 4, `Insert into a background tab waits until the tab reports visible (${pingsBeforeFill} pings first)`); + worker.dispose(); + + // A tab that never becomes visible is refused within a bounded time, never written. + let fills = 0; + worker = loadWorker({ + tabs: tabs.map(t => Object.assign({}, t)), config: { visibilityPollMs: 10, visibilityTimeoutMs: 150 }, + fetch: async () => ({ status: 503, body: {} }), + sendMessage(tabId, message) { + if (message.type === 'holmes:ping') return { ok: true, visible: false, isActiveTab: true }; + if (message.type === 'holmes:fillEmailDraft') { fills++; return { ok: true, inserted: true, identity: message.expected.identity }; } + return {}; + } + }); + const started = Date.now(); + result = await worker.context.emailComposeCommand({ action: 'fill_email_draft', params: { body: 'Reviewed', expected } }); + check(result.ok === false && /did not become visible/i.test(result.reason) && fills === 0 && Date.now() - started < 1000, + 'A tab that never becomes visible is refused within the bound and nothing is inserted'); + worker.dispose(); +} + +async function navigateTests() { + // navigate resolves once the tab finishes loading. + let worker = loadWorker({ + fetch: async () => ({ status: 503, body: {} }), + onNavigate(tab, events) { + setTimeout(() => { tab.status = 'complete'; events.updated.emit(tab.id, { status: 'complete' }, tab); }, 150); + } + }); + let started = Date.now(); + let result = await worker.context.HolmesAutomation.execute({ action: 'navigate', params: { url: 'https://example.test/next', tabId: 17 } }); + let elapsed = Date.now() - started; + check(result.ok === true && result.loaded === true && elapsed >= 140, `navigate waits for the page to finish loading (${elapsed}ms)`); + worker.dispose(); + + // A page that never finishes loading still resolves, bounded, and says so. + worker = loadWorker({ config: { navigateTimeoutMs: 120 }, fetch: async () => ({ status: 503, body: {} }), onNavigate() {} }); + started = Date.now(); + result = await worker.context.HolmesAutomation.execute({ action: 'navigate', params: { url: 'https://slow.test/', tabId: 17 } }); + elapsed = Date.now() - started; + check(result.ok === true && result.loaded === false && elapsed < 1000, `navigate gives up waiting after its bound (${elapsed}ms)`); + worker.dispose(); + + // Closing the tab mid navigation ends the wait with an error. + worker = loadWorker({ + fetch: async () => ({ status: 503, body: {} }), + onNavigate(tab, events) { setTimeout(() => events.removed.emit(tab.id, {}), 40); } + }); + result = await worker.context.HolmesAutomation.execute({ action: 'navigate', params: { url: 'https://gone.test/', tabId: 17 } }); + check(result.ok === false && /closed/i.test(result.error), 'A tab closed during navigation reports an error instead of waiting'); + worker.dispose(); +} + +async function longPollSpinTests() { + // Five paired browsers against a bridge that holds only three long polls. The + // other two get an immediate empty answer; they must wait instead of spinning. + let held = 0; + const polls = [0, 0, 0, 0, 0]; + const workers = polls.map((_, index) => loadWorker({ + config: { pollIdleMs: 200, longPollMinMs: 150 }, + fetch: async url => { + if (!url.endsWith('/commands')) return { status: 200, body: {} }; + polls[index]++; + if (held < 3) { + held++; + await sleep(300); + held--; + } else { + await sleep(1); + } + return { status: 200, body: [], headers: { 'X-Holmes-Long-Poll': '1' } }; + } + })); + await sleep(1000); + workers.forEach(worker => worker.dispose()); + const total = polls.reduce((a, b) => a + b, 0); + check(total < 60, `Empty long polls that return immediately back off instead of spinning (${total} polls from 5 workers in 1s)`); +} + +async function ledgerRaceTests() { + // Two copies of one command id land in different tab lanes at the same moment. + // Only one may run; the check and the running marker must not race. + let executions = 0; + const executeScript = async details => { + if (!details.func) return [{}]; + executions++; + await sleep(50); + return [{ result: { ok: true, filled: { tag: 'input' }, length: 1 } }]; + }; + const tabs = [{ id: 1, windowId: 23, url: 'https://a.test/', active: true }, { id: 2, windowId: 23, url: 'https://b.test/' }]; + let served = false; + const worker = loadWorker({ tabs, executeScript, fetch: async url => { + if (!url.endsWith('/commands')) return { status: 200, body: { ok: true } }; + await sleep(15); + if (served) return { status: 200, body: [], headers: { 'X-Holmes-Long-Poll': '1' } }; + served = true; + const copy = tabId => ({ id: 51, action: 'fillField', params: { tabId, selector: '#a', value: 'x' }, session: 's1' }); + return { status: 200, body: [copy(1), copy(2)], headers: { 'X-Holmes-Long-Poll': '1' } }; + } }); + await until('result for 51', () => resultPosts(worker, 51).some(p => !p.body._holmesStarted), 2000); + await sleep(200); + check(executions === 1, `Two copies of one id in different lanes execute once (${executions} executions)`); + worker.dispose(); +} + +async function ledgerQuotaTests() { + // 60 large extract results (200 KB each) must not grow the replay ledger past + // chrome.storage.session's 10 MB quota, where writes fail silently. + const text = 'L'.repeat(200 * 1024); + const commands = Array.from({ length: 60 }, (_, i) => ({ id: 300 + i, action: 'extract', params: { selector: 'p' }, session: 's1' })); + const feed = commandFeed(commands); + const worker = loadWorker({ + sessionQuotaBytes: 10 * 1024 * 1024, + executeScript: details => details.func ? [{ result: { ok: true, count: 1, elements: [{ text }] } }] : [{}], + fetch: async url => url.endsWith('/commands') ? feed() : { status: 200, body: { ok: true } } + }); + await until('all quota results', () => worker.log.fetches.filter(f => f.url.endsWith('/command-result')).length >= 60, 30000); + await sleep(200); + const stored = worker.storage.session.get('holmesCommandLedger') || {}; + const bytes = JSON.stringify(stored).length; + const failures = worker.log.sessionSetFailures || 0; + check(failures === 0 && bytes < 1024 * 1024, + `Large results keep the ledger small and every session write succeeds (${bytes} bytes, ${failures} failed writes)`); + const newest = stored['s1:359']; + check(newest && newest.state === 'done' && newest.result && newest.result.ok === true && JSON.stringify(newest.result).length < 8192, + 'The newest command stays in the ledger with a compact outcome'); + worker.dispose(); +} + +async function laneOrderTests() { + // A command without tabId (needs an active tab lookup) arrives before one with + // tabId for the same tab. Lanes must be assigned in arrival order. + const spans = []; + const executeScript = async details => { + if (!details.func) return [{}]; + const params = details.args[1] || {}; + const span = { selector: params.selector, start: Date.now() }; + spans.push(span); + await sleep(params.selector === '#first' ? 120 : 10); + span.end = Date.now(); + return [{ result: { ok: true, count: 0, elements: [] } }]; + }; + let served = false; + const worker = loadWorker({ queryDelayMs: 40, executeScript, fetch: async url => { + if (!url.endsWith('/commands')) return { status: 200, body: { ok: true } }; + await sleep(15); + if (served) return { status: 200, body: [], headers: { 'X-Holmes-Long-Poll': '1' } }; + served = true; + return { status: 200, headers: { 'X-Holmes-Long-Poll': '1' }, body: [ + { id: 61, action: 'extract', params: { selector: '#first' }, session: 's1' }, + { id: 62, action: 'extract', params: { tabId: 17, selector: '#second' }, session: 's1' } + ] }; + } }); + await until('lane order results', () => spans.length === 2 && spans.every(s => s.end), 3000); + const first = spans.find(s => s.selector === '#first'), second = spans.find(s => s.selector === '#second'); + check(second.start >= first.end, 'A command with an explicit tabId waits behind an earlier command for the same active tab'); + worker.dispose(); +} + +async function composeTimeoutTests() { + // A content script that never answers must not pin a command slot, block its + // lane and keep the worker awake forever. + const worker = loadWorker({ + config: { composeMessageTimeoutMs: 100 }, + fetch: async () => ({ status: 503, body: {} }), + sendMessage(tabId, message) { + if (message.type === 'holmes:readEmailCompose') return new Promise(() => {}); + return { ok: true, visible: true, isActiveTab: true }; + } + }); + const started = Date.now(); + const outcome = await Promise.race([ + worker.context.emailComposeCommand({ action: 'read_email_compose' }).then(result => ({ result }), error => ({ error })), + sleep(1500).then(() => 'hung') + ]); + const text = outcome === 'hung' ? 'hung' + : String((outcome.error && outcome.error.message) || (outcome.result && (outcome.result.error || outcome.result.reason))); + check(outcome !== 'hung' && Date.now() - started < 1000 && /timed out/i.test(text), + `A silent content script cannot hold a compose command open (${text})`); + worker.dispose(); +} + +async function navigateEarlyTests() { + const quiet = async () => ({ status: 503, body: {} }); + // The old page still reports complete right after tabs.update; the new load + // starts 50ms later and finishes at 200ms. + let worker = loadWorker({ + lazyNavigate: true, fetch: quiet, + onNavigate(tab, events, url) { + setTimeout(() => { tab.pendingUrl = url; tab.status = 'loading'; events.updated.emit(tab.id, { status: 'loading' }, tab); }, 50); + setTimeout(() => { tab.url = url; delete tab.pendingUrl; tab.status = 'complete'; events.updated.emit(tab.id, { status: 'complete' }, tab); }, 200); + } + }); + let started = Date.now(); + let result = await worker.context.HolmesAutomation.execute({ action: 'navigate', params: { url: 'https://example.test/next', tabId: 17 } }); + let elapsed = Date.now() - started; + check(result.ok === true && result.loaded === true && elapsed >= 190 && result.url === 'https://example.test/next', + `navigate ignores the previous page's complete status and waits for the new load (${elapsed}ms)`); + worker.dispose(); + + // Same document navigation: no loading phase, the URL simply changes. + worker = loadWorker({ + lazyNavigate: true, config: { navigateTimeoutMs: 2000 }, fetch: quiet, + onNavigate(tab, events, url) { tab.url = url; events.updated.emit(tab.id, { url }, tab); } + }); + started = Date.now(); + result = await worker.context.HolmesAutomation.execute({ action: 'navigate', params: { url: 'https://mail.example.test/#inbox', tabId: 17 } }); + elapsed = Date.now() - started; + check(result.ok === true && result.loaded === true && elapsed < 500, `A same document navigation still resolves promptly (${elapsed}ms)`); + worker.dispose(); +} + +module.exports = { loadWorker, check, sleep, until, receivingEndMissing }; + +if (require.main === module) { + (async () => { + // Worker timers are unref'd; keep node alive until every suite has finished so + // a test awaiting only those timers can never exit early and look like a pass. + setInterval(() => {}, 1000); + const only = process.argv[2]; + const suites = { reinjectionTests, probeTests, transportTests, resultDeliveryTests, idempotencyTests, + concurrencyTests, visibilityTests, navigateTests, longPollSpinTests, ledgerRaceTests, ledgerQuotaTests, laneOrderTests, composeTimeoutTests, navigateEarlyTests }; + for (const [name, suite] of Object.entries(suites)) { + if (only && name !== only) continue; + await suite(); + } + console.log(`Browser bridge worker: ${checks} checks passed (mock chrome, scripted bridge).`); + // Simulated workers keep polling forever; exit explicitly on pass and on failure. + process.exit(0); + })().catch(error => { console.error(error); process.exit(1); }); +} diff --git a/holmes/tests/BrowserBridgeContentTests.cjs b/holmes/tests/BrowserBridgeContentTests.cjs new file mode 100644 index 0000000..84c904c --- /dev/null +++ b/holmes/tests/BrowserBridgeContentTests.cjs @@ -0,0 +1,106 @@ +// Content script lifecycle against jsdom: double injection, orphaning after an +// extension reload, takeover by a fresh injection, ping and worker keepalive. +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { JSDOM } = require('jsdom'); + +const extension = path.resolve(__dirname, '../holmes-extension'); +const source = fs.readFileSync(path.join(extension, 'content.js'), 'utf8'); +let checks = 0; +function check(condition, description) { checks++; assert.ok(condition, description); console.log('PASS ' + description); } +const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); + +function runtimeMock(id, log) { + const listeners = []; + return { + listeners, + runtime: { + id, lastError: undefined, + getManifest: () => ({ version: '2.3' }), + onMessage: { addListener(fn) { listeners.push(fn); } }, + sendMessage(message, callback) { + if (!this.id) throw new Error('Extension context invalidated.'); + log.push(message); + if (message.type === 'holmes:hello') callback && callback({ token: 't', tabId: 5, windowId: 6, instanceId: 'inst', isActiveTab: true }); + else if (callback) callback({ ok: true }); + } + } + }; +} + +function page(options = {}) { + const dom = new JSDOM('Example

Hello world, this is a page.

', + { url: 'https://example.test/article', pretendToBeVisual: true, runScripts: 'outside-only' }); + const w = dom.window; + const live = new Set(); + const originalSet = w.setInterval.bind(w), originalClear = w.clearInterval.bind(w); + w.setInterval = (fn, ms) => { const id = originalSet(fn, ms); live.add(id); return id; }; + w.clearInterval = id => { live.delete(id); originalClear(id); }; + const log = []; + const first = runtimeMock('extension-v1', log); + w.chrome = { runtime: first.runtime, storage: { local: { get(keys, cb) { cb({}); } }, onChanged: { addListener() {} } } }; + w.fetch = async () => ({ ok: true, status: 200 }); + if (options.config) w.__holmesContentConfig = options.config; + return { + dom, w, log, live, first, + load() { w.eval(source); }, + message(listeners, msg) { + let response; + for (const listener of listeners) listener(msg, {}, value => { if (response === undefined) response = value; }); + return response; + }, + close() { dom.window.close(); } + }; +} + +(async () => { + // Double injection is a no-op while the first copy is alive. + let p = page(); + p.load(); + const listenerCount = p.first.listeners.length; + const intervalCount = p.live.size; + p.load(); + check(listenerCount > 0 && p.first.listeners.length === listenerCount && p.live.size === intervalCount, + 'Injecting content.js twice into a live page registers listeners and timers once'); + const ping = p.message(p.first.listeners, { type: 'holmes:ping' }); + check(ping && ping.ok === true && typeof ping.visible === 'boolean' && typeof ping.isActiveTab === 'boolean', + 'The content script answers holmes:ping with its visibility and active state'); + + // The extension reloads: the old runtime is invalidated. The next activity must + // stop the orphan quietly instead of throwing or pretending to send. + p.first.runtime.id = undefined; + p.w.document.dispatchEvent(new p.w.Event('focusin')); + await sleep(450); + check(p.live.size === 0, 'An orphaned content script clears its intervals'); + const sentBefore = p.log.length; + p.w.document.dispatchEvent(new p.w.Event('focusin')); + await sleep(300); + check(p.log.length === sentBefore, 'An orphaned content script sends nothing further'); + check(p.w.__holmesContentScript && p.w.__holmesContentScript.alive() === false, 'The guard reports the orphan as dead'); + + // A reinjected copy from the reloaded extension takes over the same page. + const second = runtimeMock('extension-v2', p.log); + p.w.chrome = { runtime: second.runtime, storage: p.w.chrome.storage }; + p.load(); + check(second.listeners.length > 0 && p.live.size > 0, 'A reinjected content script takes over from the orphan'); + check(p.log.some(m => m.type === 'holmes:hello'), 'The new copy says hello to the reloaded worker'); + check(p.w.__holmesContentScript.alive() === true, 'The guard now belongs to the live copy'); + p.close(); + + // Keepalive pings keep an MV3 worker awake while this tab is visible and active. + p = page({ config: { keepaliveMs: 40 } }); + p.load(); + await sleep(220); + const keepalives = p.log.filter(m => m.type === 'holmes:keepalive').length; + check(keepalives >= 2, `A visible active tab pings the worker to keep it awake (${keepalives} pings)`); + Object.defineProperty(p.w.document, 'visibilityState', { value: 'hidden', configurable: true }); + const hiddenStart = p.log.filter(m => m.type === 'holmes:keepalive').length; + await sleep(200); + check(p.log.filter(m => m.type === 'holmes:keepalive').length === hiddenStart, 'A hidden tab does not keep the worker awake'); + p.close(); + + console.log(`Browser bridge content script: ${checks} checks passed (jsdom, mock runtime).`); + // jsdom windows keep their own timers; exit explicitly so a pass never hangs. + process.exit(0); +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/holmes/tests/BrowserBridgeProbeTests.cjs b/holmes/tests/BrowserBridgeProbeTests.cjs new file mode 100644 index 0000000..c0814cc --- /dev/null +++ b/holmes/tests/BrowserBridgeProbeTests.cjs @@ -0,0 +1,50 @@ +// Active tab probe classification: a page that blocks script injection (Chrome +// Web Store, the PDF viewer, other protected pages) is restricted, not a missing +// content script that the app would tell the user to refresh. +const { loadWorker, check, until, receivingEndMissing } = require('./BrowserBridgeBackgroundTests.cjs'); + +function probeWorker(tab, executeScript) { + const heartbeats = []; + let injections = 0; + const worker = loadWorker({ + config: { heartbeatProbeMs: 0 }, + tabs: [tab], + fetch(url, init) { + if (url.endsWith('/heartbeat')) heartbeats.push(JSON.parse(init.body || '{}')); + return { status: url.endsWith('/commands') ? 503 : 200, body: {} }; + }, + executeScript(details) { injections++; return executeScript(details); }, + sendMessage(tabId, message) { + if (message.type === 'holmes:ping') throw receivingEndMissing(); + return { ok: true }; + } + }); + return { worker, heartbeats, injections: () => injections }; +} + +(async () => { + setInterval(() => {}, 1000); + let passed = 0; + + const store = probeWorker({ id: 5, windowId: 23, url: 'https://chromewebstore.google.com/detail/x', active: true }, + () => { throw new Error('The extensions gallery cannot be scripted.'); }); + await until('first store probe', () => store.heartbeats.some(h => h.activeTab)); + await store.worker.context.sendHeartbeat(); + const storeScripts = store.heartbeats.filter(h => h.activeTab).map(h => h.activeTab.script); + check(storeScripts.length >= 2 && storeScripts.every(s => s === 'restricted'), + `A page that blocks injection is reported restricted, not missing (${storeScripts.join(', ')})`); + passed++; + store.worker.dispose(); + + const normal = probeWorker({ id: 6, windowId: 23, url: 'https://normal.test/', active: true }, () => [{}]); + await until('first normal probe', () => normal.heartbeats.some(h => h.activeTab)); + await normal.worker.context.sendHeartbeat(); + const normalScripts = normal.heartbeats.filter(h => h.activeTab).map(h => h.activeTab.script); + check(normal.injections() > 0 && normalScripts.at(-1) === 'missing', + `A normal page that still does not answer after a successful reinjection is missing (${normalScripts.join(', ')})`); + passed++; + normal.worker.dispose(); + + console.log(`Browser bridge probe: ${passed} checks passed (mock chrome).`); + process.exit(0); +})().catch(error => { console.error(error); process.exit(1); }); diff --git a/holmes/tests/BrowserComposeBridgeTests.swift b/holmes/tests/BrowserComposeBridgeTests.swift index 276f4ee..bc9eef0 100644 --- a/holmes/tests/BrowserComposeBridgeTests.swift +++ b/holmes/tests/BrowserComposeBridgeTests.swift @@ -227,5 +227,18 @@ import Foundation && bridge.testAwaitingCommandCount == 0 && bridge.testTrackedCommandCount == 0, "All cancellation paths leave no command available for a later poll") print("Browser compose bridge: \(checks) checks passed using production Swift parser, queue, refresh and insertion code") + + var socketChecks = 0 + func socketCheck(_ value: Bool, _ message: String) { + socketChecks += 1 + precondition(value, message) + print("PASS \(message)") + } + await BridgeLoopbackTests.runCommandChannel(check: socketCheck) + await BridgeLoopbackTests.runBodyLimits(check: socketCheck) + await BridgeLoopbackTests.runLifecycle(check: socketCheck) + await BridgeLoopbackTests.runPairing(check: socketCheck) + await BridgeLoopbackTests.runLiveness(check: socketCheck) + print("Browser bridge loopback sockets: \(socketChecks) checks passed against the real server on an ephemeral port") } } diff --git a/holmes/tests/ComputerUseRunRegistryTests.swift b/holmes/tests/ComputerUseRunRegistryTests.swift new file mode 100644 index 0000000..2b3ad2d --- /dev/null +++ b/holmes/tests/ComputerUseRunRegistryTests.swift @@ -0,0 +1,77 @@ +import Foundation + +@main +struct ComputerUseRunRegistryTests { + @MainActor static func main() async { + var checks = 0 + func expect(_ value: @autoclosure () -> Bool, _ message: String) { + precondition(value(), message) + checks += 1 + } + + let runs = ComputerUseRunRegistry() + let first = runs.begin() + runs.setCapture("frame seen by the first run", for: first) + runs.cancel(first) + expect(runs.isCancelled(first), "Cancelling a run arms its kill switch") + + // The regression: beginning a second run used to reset one global kill + // flag and one global screenshot for every run in flight. + let second = runs.begin() + expect(runs.isCancelled(first), "Starting another run must not disarm the kill switch of a run in flight") + expect(!runs.isCancelled(second), "A new run starts uncancelled") + expect(runs.capture(for: first) == "frame seen by the first run", + "Starting another run must not clear the first run's screenshot") + expect(runs.capture(for: second) == nil, "A new run never inherits another run's screenshot") + runs.setCapture("frame seen by the second run", for: second) + expect(runs.capture(for: first) == "frame seen by the first run", + "A screenshot taken by one run must never become the mapping frame of another") + + // Nested sessions follow their parent. + let parent = runs.begin() + let child = runs.begin(parent: parent) + expect(!runs.isCancelled(child), "A child run starts live") + runs.cancel(parent) + expect(runs.isCancelled(child), "Cancelling a plan also stops the model session nested in it") + let sibling = runs.begin() + runs.cancel(sibling) + let otherChild = runs.begin(parent: second) + expect(!runs.isCancelled(otherChild) && !runs.isCancelled(second), + "Cancelling one run leaves unrelated runs and their children live") + + // Stop all reaches every run, including ones that started later than an earlier stop. + runs.cancelAll() + expect([first, second, parent, child, sibling, otherChild].allSatisfy { runs.isCancelled($0) }, + "Stop all cancels every registered run") + expect(runs.isCancelled(nil), "Stop all also cancels unscoped work") + runs.resetUnscoped() + expect(!runs.isCancelled(nil) && runs.isCancelled(second), + "Re arming unscoped work never revives a cancelled run") + + let ended = runs.begin() + runs.end(ended) + expect(runs.isCancelled(ended) && runs.capture(for: ended) == nil, + "An ended run can no longer act or keep a capture") + + // A long run must never be evicted and then read as cancelled, however + // many short runs (Settings self tests, requests) start after it. + let bounded = ComputerUseRunRegistry(capacity: 4) + let longRun = bounded.begin() + bounded.setCapture(0, for: longRun) + var shortRuns: [ComputerUseRunToken] = [] + for index in 1...100 { + let run = bounded.begin() + bounded.setCapture(index, for: run) + shortRuns.append(run) + } + expect(!bounded.isCancelled(longRun), "A live run started before 100 others is still live, not evicted into cancelled") + expect(bounded.capture(for: longRun) == nil && bounded.capture(for: shortRuns.last!) == 100, + "Only screenshots are bounded: the oldest capture is dropped") + bounded.cancelAll() + expect(bounded.isCancelled(longRun), "Stop all still reaches the long run") + for run in shortRuns { bounded.end(run) } + expect(bounded.activeCount == 1, "Ended runs leave the table; the live one stays") + + print("Passed \(checks) computer use run ownership checks") + } +} diff --git a/holmes/tests/EmailComposeBackgroundTests.cjs b/holmes/tests/EmailComposeBackgroundTests.cjs index 595b3e6..cd2f6c6 100644 --- a/holmes/tests/EmailComposeBackgroundTests.cjs +++ b/holmes/tests/EmailComposeBackgroundTests.cjs @@ -11,6 +11,7 @@ const tabs = new Map([[17, { id: 17, windowId: 23 }], [28, { id: 28, windowId: 2 const messages = [], requests = [], activations = []; const context = vm.createContext({ console, crypto: { randomUUID: () => 'test-profile' }, setInterval: () => 1, + setTimeout: (fn, ms) => { const timer = setTimeout(fn, ms); timer.unref(); return timer; }, clearTimeout, AbortController, importScripts() {}, HolmesAutomation: { async execute() { genericExecutions++; return { ok: true }; } }, fetch: async (url, options) => { requests.push({ url, options }); return { ok: true, json: async () => [] }; }, @@ -25,6 +26,7 @@ const context = vm.createContext({ async sendMessage(tabId, message) { messages.push({ tabId, message }); if (message.type === 'holmes:active') return {}; + if (message.type === 'holmes:ping') return { ok: true, visible: true, isActiveTab: true }; if (changeDuringRead && message.type === 'holmes:readEmailCompose') active = 28; return message.type === 'holmes:readEmailCompose' ? { ok: true, payload: { capturedAt: Date.now() } } : { ok: true, inserted: true, identity: message.expected.identity }; diff --git a/holmes/tests/ModelJSONTests.swift b/holmes/tests/ModelJSONTests.swift new file mode 100644 index 0000000..b620566 --- /dev/null +++ b/holmes/tests/ModelJSONTests.swift @@ -0,0 +1,66 @@ +import Foundation + +@main +struct ModelJSONTests { + static func main() async { + var checks = 0 + func expect(_ value: @autoclosure () -> Bool, _ message: String) { + precondition(value(), message) + checks += 1 + } + func hasSteps(_ object: [String: Any]) -> Bool { object["steps"] is [Any] } + + // The first "{" to last "}" slice these replies used to get is invalid JSON. + let trailingBraces = #"{"steps":[{"action":"open_app"}],"rationale":"ok"} Let me know if {anything} else is needed."# + expect(ModelJSON.firstObject(in: trailingBraces, where: hasSteps) != nil, + "Trailing prose containing braces must not break the plan") + let leadingBraces = #"I used the {steps} format: {"steps":[{"action":"key","input":{"text":"cmd+s"}}],"rationale":"save"}"# + let leading = ModelJSON.firstObject(in: leadingBraces, where: hasSteps) + expect((leading?["steps"] as? [[String: Any]])?.first?["action"] as? String == "key", + "Leading prose containing braces must not hide the object") + let fenced = "Here is the plan:\n```json\n{\"steps\":[],\"rationale\":\"a } inside a string\"}\n```\nDone." + expect(ModelJSON.firstObject(in: fenced)?["rationale"] as? String == "a } inside a string", + "Code fences, surrounding prose and braces inside strings are tolerated") + let escaped = #"{"summary":"say \"hi {there}\"","n":1}"# + expect(ModelJSON.firstObject(in: escaped)?["n"] as? Int == 1, "Escaped quotes inside strings keep the scan balanced") + let rawNewline = "{\"goal\":\"line one\nline two\",\"headline\":\"\"}" + expect(ModelJSON.firstObject(in: rawNewline)?["goal"] as? String == "line one\nline two", + "Raw newlines inside string values are tolerated") + let two = #"{"note":"first"} and {"steps":[1]}"# + expect(ModelJSON.firstObject(in: two, where: hasSteps)?["steps"] != nil, + "A rejected first object does not stop the search for an accepted one") + expect(ModelJSON.firstObject(in: "I could not make a plan.") == nil, "Prose without an object yields nil") + expect(ModelJSON.firstObject(in: #"{"steps": [ "#) == nil, "A truncated object yields nil") + expect(ModelJSON.firstObject(in: #"a stray { brace, then {"ok":true}"#)?["ok"] as? Bool == true, + "An unbalanced stray brace before the object is skipped") + expect(ModelJSON.objectCandidates(in: #"x {"a":1} y {"b":{"c":2}} z"#) == [#"{"a":1}"#, #"{"b":{"c":2}}"#], + "Candidates are the balanced top level objects in order") + + // One repair attempt, surfaced honestly when it also fails. + var repairCalls = 0 + let repaired = await ModelJSONRepair.parse("not json", what: "plan", + attempt: { ModelJSON.firstObject(in: $0, where: hasSteps) }, + repair: { _ in repairCalls += 1; return #"{"steps":[{"action":"open_app"}]}"# }) + expect(repaired.value != nil && repaired.repaired && repairCalls == 1, "An unreadable reply is repaired once") + repairCalls = 0 + let clean = await ModelJSONRepair.parse(trailingBraces, what: "plan", + attempt: { ModelJSON.firstObject(in: $0, where: hasSteps) }, + repair: { _ in repairCalls += 1; return "" }) + expect(clean.value != nil && !clean.repaired && repairCalls == 0, "A readable reply never costs a repair request") + let failed = await ModelJSONRepair.parse("nope", what: "plan", + attempt: { ModelJSON.firstObject(in: $0, where: hasSteps) }, + repair: { _ in repairCalls += 1; return "still nope" }) + expect(failed.value == nil && failed.failure?.contains("unreadable plan twice") == true && repairCalls == 1, + "Two unreadable replies give a user facing failure and no retry loop") + struct Offline: Error {} + let transport = await ModelJSONRepair.parse("nope", what: "plan", + attempt: { ModelJSON.firstObject(in: $0, where: hasSteps) }, + repair: { _ in throw Offline() }) + expect(transport.value == nil && transport.failure?.contains("repair request failed") == true, + "A failed repair request is reported, not swallowed") + expect(ModelJSONRepair.repairPrompt(for: "broken", shape: "{\"steps\":[]}").contains("broken"), + "The repair prompt carries the broken reply") + + print("Passed \(checks) model JSON extraction and repair checks") + } +} diff --git a/holmes/tests/OllamaWorkActivityTests.swift b/holmes/tests/OllamaWorkActivityTests.swift index 491bf1b..085a5f0 100644 --- a/holmes/tests/OllamaWorkActivityTests.swift +++ b/holmes/tests/OllamaWorkActivityTests.swift @@ -10,6 +10,8 @@ final class WorkModelProtocol: URLProtocol { var doneReason = "stop" var tool: String? var networkFailure = false + var urlError: URLError.Code? + var stallAfterFirstChunk = false } private static let lock = NSLock() @@ -97,6 +99,21 @@ final class WorkModelProtocol: URLProtocol { client?.urlProtocol(self, didFailWithError: URLError(.cannotConnectToHost)) return } + if let code = reply.urlError { + client?.urlProtocol(self, didFailWithError: URLError(code)) + return + } + if reply.stallAfterFirstChunk { + // One real chunk, then silence with the connection left open. + let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: "HTTP/1.1", + headerFields: ["Content-Type": "application/x-ndjson"])! + var data = try! JSONSerialization.data(withJSONObject: [ + "message": ["role": "assistant", "content": "partial"], "done": false]) + data.append(10) + client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: data) + return + } if reply.status != 200 { respondJSON(["error": "Controlled server failure"], status: reply.status) return @@ -135,6 +152,13 @@ final class WorkModelProtocol: URLProtocol { } } +final class LockedCounter: @unchecked Sendable { + private let lock = NSLock() + private var value = 0 + func increment() { lock.lock(); value += 1; lock.unlock() } + var count: Int { lock.lock(); defer { lock.unlock() }; return value } +} + @main struct OllamaWorkActivityTests { @MainActor static func main() async throws { @@ -161,6 +185,8 @@ struct OllamaWorkActivityTests { OllamaConfig.updateReadiness(ready: wasReady, problem: previousProblem) OllamaConfig.onSettingsChanged = settingsCallback OllamaConfig.onStatusChanged = statusCallback + OllamaConfig.onModelTransportFailure = nil + OllamaConfig.streamStallTimeout = 90 } OllamaConfig.host = "http://work-activity.invalid:11434" OllamaConfig.model = "work-test" @@ -245,13 +271,14 @@ struct OllamaWorkActivityTests { let afterStop = try await client.complete(system: "Test", user: "after-stop", priority: .agent) expect(afterStop == "Still works" && center.activeCount == 0, "A stopped request must release the gate for the next user") - for (key, reply) in [ - ("empty", WorkModelProtocol.Reply(text: "")), - ("truncated", WorkModelProtocol.Reply(text: "", doneReason: "length")), - ("server-error", WorkModelProtocol.Reply(status: 500)), - ("network-error", WorkModelProtocol.Reply(networkFailure: true)) + for (key, replies) in [ + ("empty", [WorkModelProtocol.Reply(text: "")]), + ("truncated", [WorkModelProtocol.Reply(text: "", doneReason: "length")]), + ("server-error", [WorkModelProtocol.Reply(status: 500)]), + // A refused connection is retried once, then reported. + ("network-error", [WorkModelProtocol.Reply(networkFailure: true), WorkModelProtocol.Reply(networkFailure: true)]) ] { - WorkModelProtocol.configure(key, [reply]) + WorkModelProtocol.configure(key, replies) do { _ = try await client.complete(system: "Test", user: key, priority: .agent) fatalError("\(key) must fail") @@ -321,6 +348,85 @@ struct OllamaWorkActivityTests { _ = try await busyAgent.value center.finish(busyAgentID, outcome: .success, summary: "Finished") + expect(WorkModelProtocol.count("network-error") == 2 && WorkModelProtocol.count("server-error") == 1, + "Only a connection failure is retried, exactly once") + + // Transient connection loss before any output: one retry recovers. + let refreshes = LockedCounter() + OllamaConfig.onModelTransportFailure = { refreshes.increment() } + OllamaConfig.transientRetryDelay = 0.05 + WorkModelProtocol.configure("flaky", [.init(networkFailure: true), .init(text: "Recovered")]) + let recovered = try await client.complete(system: "Test", user: "flaky", priority: .agent) + expect(recovered == "Recovered" && WorkModelProtocol.count("flaky") == 2, + "A dropped connection is retried once with a short backoff") + + // Never retry after a tool took effect in the session. + let toolParent = center.begin(title: "Tool then a lost connection") + WorkModelProtocol.configure("tool-then-drop", [.init(text: "", tool: "probe"), .init(networkFailure: true)]) + var toolRuns = 0 + do { + _ = try await WorkActivityScope.$id.withValue(toolParent) { + try await client.runAgent(system: "Test", userText: "tool-then-drop", + tools: [.init(name: "probe", description: "Side effect", inputSchema: [:])], + maxIterations: 3, runTool: { _, _ in + await MainActor.run { toolRuns += 1 } + return OllamaClient.ToolResult("Did it") + }) + } + fatalError("A lost connection after a tool must be reported") + } catch OllamaClient.AgentError.serverUnreachable { + expect(WorkModelProtocol.count("tool-then-drop") == 2 && toolRuns == 1, + "No request is retried once a tool has run in the session") + } + center.finish(toolParent, outcome: .failure, summary: "Lost the server") + + // A timeout is user visible, not retried, and refreshes server status. + let refreshesBeforeTimeout = refreshes.count + WorkModelProtocol.configure("timeout", [.init(urlError: .timedOut)]) + do { + _ = try await client.complete(system: "Test", user: "timeout", priority: .agent) + fatalError("A timed out request must fail") + } catch let OllamaClient.AgentError.timedOut(detail) { + let message = OllamaClient.AgentError.timedOut(detail).localizedDescription + expect(WorkModelProtocol.count("timeout") == 1 && message.contains("try again"), + "A timeout is classified as its own retryable, user visible error and not retried silently") + expect(refreshes.count > refreshesBeforeTimeout, "A timeout asks for a server status refresh") + expect(center.completion?.outcome == .failure, "A timeout finishes the fallback activity as a visible failure") + } + + // A stream that goes silent mid answer times out on the stall limit. + OllamaConfig.streamStallTimeout = 0.3 + let refreshesBeforeStall = refreshes.count + WorkModelProtocol.configure("stall", [.init(stallAfterFirstChunk: true)]) + let stallStarted = Date() + do { + _ = try await client.complete(system: "Test", user: "stall", priority: .agent) + fatalError("A stalled stream must fail") + } catch OllamaClient.AgentError.timedOut { + let waited = Date().timeIntervalSince(stallStarted) + expect(waited >= 0.25 && waited < 10, "The stall timeout fires between chunks, not after the total request timeout (\(waited)s)") + expect(refreshes.count > refreshesBeforeStall && WorkModelProtocol.count("stall") == 1, + "A stall refreshes server status and is not retried") + } + OllamaConfig.streamStallTimeout = 90 + OllamaConfig.transientRetryDelay = 0.5 + WorkModelProtocol.configure("after-stall", [.init(text: "Still serving")]) + let afterStall = try await client.complete(system: "Test", user: "after-stall", priority: .agent) + expect(afterStall == "Still serving", "A stalled request releases the GPU gate for the next request") + + // The failure hook is set on one thread and called from others. + let hookCalls = LockedCounter() + DispatchQueue.concurrentPerform(iterations: 400) { index in + if index % 2 == 0 { + OllamaConfig.onModelTransportFailure = { hookCalls.increment() } + } else { + OllamaConfig.onModelTransportFailure?() + } + } + OllamaConfig.onModelTransportFailure = nil + expect(OllamaConfig.onModelTransportFailure == nil && hookCalls.count <= 200, + "Concurrent sets and calls of the transport failure hook are synchronized") + OllamaConfig.updateReadiness(ready: false, problem: "Ollama is stopped") do { _ = try await client.complete(system: "Test", user: "not-ready", priority: .agent) diff --git a/holmes/tests/TextEntrySupportTests.swift b/holmes/tests/TextEntrySupportTests.swift new file mode 100644 index 0000000..85d17bf --- /dev/null +++ b/holmes/tests/TextEntrySupportTests.swift @@ -0,0 +1,92 @@ +import AppKit +import Foundation + +@main +struct TextEntrySupportTests { + static func main() { + var checks = 0 + func expect(_ value: @autoclosure () -> Bool, _ message: String) { + precondition(value(), message) + checks += 1 + } + + // AppleScript literals. The old escaping left newlines and control + // characters raw (a compile error) and never escaped the app name. + expect(AppleScriptText.literal("") == "\"\"", "Empty text is an empty literal") + expect(AppleScriptText.literal(#"say "hi" \ bye"#) == #""say \"hi\" \\ bye""#, "Quotes and backslashes are escaped") + expect(AppleScriptText.literal("one\ntwo") == #""one" & linefeed & "two""#, "Newlines join in as linefeed") + expect(AppleScriptText.literal("a\rb\tc") == #""a" & return & "b" & tab & "c""#, "Return and tab join in by name") + expect(AppleScriptText.literal("bell\u{7}") == #""bell" & (character id 7)"#, "Other control characters use character id") + let hostileName = #"Notes" to quit"# + "\n" + #"do shell script "echo pwned"# + let hostile = AppleScriptText.literal(hostileName) + expect(!hostile.contains("\n") && hostile.hasPrefix(#""Notes\" to quit""#), "A crafted app name cannot close the string: \(hostile)") + + // Round trip through the real AppleScript compiler (offline, no apps): + // the expression must evaluate to exactly the original text. + for sample in ["plain", #"quote " and \ backslash"#, "line one\nline two\r\nend", "tab\there", "emoji 😀 ok", + "bell\u{7} and nul\u{1}", "\n\nstarts and ends with newlines\n", hostileName] { + var error: NSDictionary? + let script = NSAppleScript(source: "return " + AppleScriptText.literal(sample)) + let value = script?.executeAndReturnError(&error).stringValue + expect(error == nil && value == sample, + "AppleScript literal round trips exactly: \(sample.debugDescription) gave \(String(describing: value)) \(String(describing: error))") + } + + // UTF-16 keyboard chunks. The old code sent UniChar(scalar.value), + // truncating every emoji to a garbage BMP character. + let emoji = "a😀b" + let chunks = KeyboardText.utf16Chunks(emoji, maxUnits: 2) + expect(chunks == [[0x61], [0xD83D, 0xDE00], [0x62]], "A surrogate pair is never split across events: \(chunks)") + let mixed = "Hi 👋🏽 from 🇺🇸 and 👨‍👩‍👧‍👦, café ok " + String(repeating: "x", count: 45) + let mixedChunks = KeyboardText.utf16Chunks(mixed) + expect(mixedChunks.flatMap { $0 } == Array(mixed.utf16), "Chunks reassemble to the exact UTF-16 text") + expect(mixedChunks.allSatisfy { $0.count <= 20 && !$0.isEmpty }, "Each chunk fits one keyboard event") + expect(mixedChunks.allSatisfy { !UTF16.isLeadSurrogate($0.last!) && !UTF16.isTrailSurrogate($0.first!) }, + "No chunk starts or ends inside a surrogate pair") + let hugeCluster = "e" + String(repeating: "\u{301}", count: 30) + let hugeChunks = KeyboardText.utf16Chunks(hugeCluster) + expect(hugeChunks.flatMap { $0 } == Array(hugeCluster.utf16) && hugeChunks.allSatisfy { $0.count <= 20 }, + "A cluster longer than one event is split between scalars") + expect(KeyboardText.utf16Chunks("").isEmpty, "Empty text posts no events") + + // Read back verification. + expect(TextEntryVerifier.fieldValue("Hello\r\nworld and more", contains: "Hello\nworld"), "Line endings are normalized") + expect(TextEntryVerifier.fieldValue("cafe\u{301}", contains: "café"), "Unicode normalization is ignored") + expect(!TextEntryVerifier.fieldValue("", contains: "text") && !TextEntryVerifier.fieldValue(nil, contains: "text"), + "An empty or unreadable field is not verified") + expect(TextEntryVerifier.unconfirmedRestoreDelay(forLength: 10) >= 1.5 + && TextEntryVerifier.unconfirmedRestoreDelay(forLength: 1_000_000) == 4.0, + "An unconfirmed paste keeps the clipboard longer, adaptively and bounded") + expect(TextEntryResult.unverified("no value").succeeded && !TextEntryResult.unverified("no value").isVerified, + "Unverified is distinct from verified success") + expect(!TextEntryResult.failed("x").succeeded, "Failed is a failure") + + // Pasteboard snapshot: every item and type comes back, not just text. + let board = NSPasteboard(name: NSPasteboard.Name("holmes-tests-\(UUID().uuidString)")) + defer { board.releaseGlobally() } + board.clearContents() + let first = NSPasteboardItem() + first.setString("plain text", forType: .string) + first.setData(Data("{\\rtf1 rich}".utf8), forType: .rtf) + let second = NSPasteboardItem() + second.setData(Data([0x89, 0x50, 0x4E, 0x47]), forType: .png) + board.writeObjects([first, second]) + let snapshot = PasteboardSnapshot(capturing: board) + board.clearContents() + board.setString("Holmes borrowed the clipboard", forType: .string) + snapshot.restore(to: board) + let items = board.pasteboardItems ?? [] + expect(items.count == 2, "Both clipboard items are restored") + expect(items.first?.string(forType: .string) == "plain text" + && items.first?.data(forType: .rtf) == Data("{\\rtf1 rich}".utf8), + "Every type of the first item is restored") + expect(items.last?.data(forType: .png) == Data([0x89, 0x50, 0x4E, 0x47]), "A non text item is restored") + board.clearContents() + let emptySnapshot = PasteboardSnapshot(capturing: board) + board.setString("temp", forType: .string) + emptySnapshot.restore(to: board) + expect(emptySnapshot.isEmpty && (board.pasteboardItems ?? []).isEmpty, "An empty clipboard is restored as empty") + + print("Passed \(checks) AppleScript escaping, keyboard chunking, verification and clipboard checks") + } +} diff --git a/holmes/tests/ToolCallRecoveryTests.swift b/holmes/tests/ToolCallRecoveryTests.swift new file mode 100644 index 0000000..c0efd4b --- /dev/null +++ b/holmes/tests/ToolCallRecoveryTests.swift @@ -0,0 +1,61 @@ +import Foundation + +@main +struct ToolCallRecoveryTests { + static func main() { + var checks = 0 + func expect(_ value: @autoclosure () -> Bool, _ message: String) { + precondition(value(), message) + checks += 1 + } + let tools = [ + OllamaClient.ToolDef(name: "computer", description: "Pixel control", inputSchema: [:]), + OllamaClient.ToolDef(name: "open_app", description: "Launch an app", inputSchema: [:]) + ] + func recover(_ text: String) -> OllamaClient.ToolCall? { + OllamaClient.toolCallFromContent(text, tools: tools) + } + + // Recovered: the message IS a call. + let whole = recover(#"{"name":"open_app","parameters":{"name":"Finder"}}"#) + expect(whole?.name == "open_app" && whole?.arguments["name"] as? String == "Finder", "A whole message call is recovered") + let fenced = recover("I'll take a screenshot first.\n```json\n{\"name\": \"computer\", \"arguments\": {\"action\": \"screenshot\"}}\n```") + expect(fenced?.name == "computer" && fenced?.arguments["action"] as? String == "screenshot", + "A code fence after a short lead in is recovered") + let function = recover("Calling it:\n```\n{\"function\":{\"name\":\"computer\",\"arguments\":{\"action\":\"key\",\"text\":\"cmd+s\"}}}\n```") + expect(function?.name == "computer" && function?.arguments["text"] as? String == "cmd+s", + "The nested function form is recovered from a fence") + let upper = recover("```json {\"tool\":\"OPEN_APP\",\"input\":{\"name\":\"Mail\"}}```") + expect(upper?.name == "open_app" && upper?.arguments["name"] as? String == "Mail", + "A one line fence matches the offered tool name case insensitively") + let unterminated = recover("```json\n{\"name\":\"open_app\",\"parameters\":{\"name\":\"Notes\"}}") + expect(unterminated?.arguments["name"] as? String == "Notes", "A fence left open at the end of the message is recovered") + let bare = recover(#"{"action":"screenshot"}"#) + expect(bare?.name == "computer", "A message that is only bare computer arguments is still recovered") + + // Not recovered: prose that mentions or quotes a call. + expect(recover(#"Opened it with {"name":"open_app","parameters":{"name":"Notes"}}."#) == nil, + "A final answer quoting a past call in prose is never re executed") + expect(recover(#"{"name":"open_app","parameters":{"name":"Notes"}} Opening Notes now."#) == nil, + "A call followed by prose is not a call") + expect(recover(#"Use the {tool} form: {"tool":"open_app","input":{"name":"Mail"}} and wait."#) == nil, + "A call embedded mid sentence is not a call") + expect(recover("Done.\n```json\n{\"name\":\"open_app\",\"parameters\":{\"name\":\"Notes\"}}\n```\nThat opened Notes for you.") == nil, + "A fence followed by more prose is an example, not a call") + let longLeadIn = String(repeating: "I reviewed everything carefully. ", count: 7) + expect(recover(longLeadIn + "\n```json\n{\"name\":\"open_app\",\"parameters\":{}}\n```") == nil, + "A fence after a long answer is not recovered") + expect(recover("Here:\n```json\n{\"action\":\"left_click\",\"coordinate\":[1,2]}\n```") == nil, + "Bare arguments after a lead in are not re executed") + expect(recover("```json\n{\"name\":\"delete_everything\",\"arguments\":{}}\n```") == nil, + "A call to a tool that was not offered is never recovered") + expect(recover(#"I clicked using {"action":"left_click","coordinate":[1,2]} and it worked."#) == nil, + "Bare arguments quoted inside a prose answer are not re executed") + expect(recover("All done, the file is saved.") == nil, "Plain prose has no tool call") + let noComputer = OllamaClient.toolCallFromContent(#"{"action":"screenshot"}"#, + tools: [OllamaClient.ToolDef(name: "open_app", description: "", inputSchema: [:])]) + expect(noComputer == nil, "Bare arguments need the computer tool to be offered") + + print("Passed \(checks) tool call recovery checks") + } +} diff --git a/holmes/tests/run-approval-queue-tests.sh b/holmes/tests/run-approval-queue-tests.sh new file mode 100755 index 0000000..63153f7 --- /dev/null +++ b/holmes/tests/run-approval-queue-tests.sh @@ -0,0 +1,11 @@ +#!/bin/bash +set -euo pipefail +approval_repo_root=$(cd "$(dirname "$0")/../.." && pwd) +approval_test_dir=$(mktemp -d "${TMPDIR:-/tmp}/holmes-approval-queue.XXXXXX") +trap 'rm -rf "$approval_test_dir"' EXIT +cd "$approval_repo_root" +xcrun swiftc -swift-version 5 \ + holmes/holmes/Core/ApprovalQueue.swift \ + holmes/tests/ApprovalQueueTests.swift \ + -o "$approval_test_dir/approval-queue-tests" +"$approval_test_dir/approval-queue-tests" diff --git a/holmes/tests/run-ax-element-search-tests.sh b/holmes/tests/run-ax-element-search-tests.sh new file mode 100755 index 0000000..8e4adb0 --- /dev/null +++ b/holmes/tests/run-ax-element-search-tests.sh @@ -0,0 +1,16 @@ +#!/bin/bash +set -euo pipefail +ax_search_repo_root=$(cd "$(dirname "$0")/../.." && pwd) +ax_search_test_dir=$(mktemp -d "${TMPDIR:-/tmp}/holmes-ax-search.XXXXXX") +trap 'rm -rf "$ax_search_test_dir"' EXIT +cd "$ax_search_repo_root" +xcrun swiftc -swift-version 5 \ + holmes/holmes/Core/AXElementSearch.swift \ + holmes/tests/AXElementSearchTests.swift \ + -o "$ax_search_test_dir/ax-element-search-tests" +"$ax_search_test_dir/ax-element-search-tests" +xcrun swiftc -swift-version 5 \ + holmes/holmes/Core/AutonomousRunTally.swift \ + holmes/tests/AutonomousRunTallyTests.swift \ + -o "$ax_search_test_dir/autonomous-run-tally-tests" +"$ax_search_test_dir/autonomous-run-tally-tests" diff --git a/holmes/tests/run-browser-bridge-extension-tests.sh b/holmes/tests/run-browser-bridge-extension-tests.sh new file mode 100755 index 0000000..4272f00 --- /dev/null +++ b/holmes/tests/run-browser-bridge-extension-tests.sh @@ -0,0 +1,19 @@ +#!/bin/bash +# Extension side of the browser bridge: worker transport and lifecycle against a +# mock chrome.* surface, and content script lifecycle in jsdom. No browser needed. +set -euo pipefail +bridge_extension_root=$(cd "$(dirname "$0")/../.." && pwd) +bridge_extension_dir=$(mktemp -d "${TMPDIR:-/tmp}/holmes-bridge-extension.XXXXXX") +trap 'rm -rf "$bridge_extension_dir"' EXIT +cd "$bridge_extension_root" +for script in background.js content.js automation.js popup.js options.js history-hook.js email-compose.js; do + node --check "holmes/holmes-extension/$script" +done +node -e 'JSON.parse(require("fs").readFileSync("holmes/holmes-extension/manifest.json", "utf8"))' +if [ -z "${COMPOSE_NODE_MODULES:-}" ]; then + npm install --prefix "$bridge_extension_dir" --no-audit --no-fund --silent jsdom@26.1.0 + COMPOSE_NODE_MODULES="$bridge_extension_dir/node_modules" +fi +node holmes/tests/BrowserBridgeBackgroundTests.cjs +node holmes/tests/BrowserBridgeProbeTests.cjs +NODE_PATH="$COMPOSE_NODE_MODULES" node holmes/tests/BrowserBridgeContentTests.cjs diff --git a/holmes/tests/run-browser-bridge-soak.sh b/holmes/tests/run-browser-bridge-soak.sh new file mode 100755 index 0000000..ad45322 --- /dev/null +++ b/holmes/tests/run-browser-bridge-soak.sh @@ -0,0 +1,20 @@ +#!/bin/bash +# Bridge reliability soak: 200 command round trips (SOAK_COMMANDS to change) through +# the real BrowserBridge server with a simulated, periodically evicted worker and a +# repeatedly blocked main thread. Fails unless every round trip succeeds. +set -euo pipefail +soak_repo_root=$(cd "$(dirname "$0")/../.." && pwd) +soak_test_dir=$(mktemp -d "${TMPDIR:-/tmp}/holmes-bridge-soak.XXXXXX") +trap 'rm -rf "$soak_test_dir"' EXIT +cd "$soak_repo_root" +xcrun swiftc -D DEBUG -swift-version 5 \ + holmes/holmes/Core/EmailComposeSnapshot.swift \ + holmes/holmes/Core/ContextEngine.swift \ + holmes/holmes/Core/LiveContext.swift \ + holmes/holmes/Core/BrowserBridge.swift \ + holmes/holmes/Core/Setup/ExtensionInstaller.swift \ + holmes/tests/BrowserComposeTestSupport.swift \ + holmes/tests/BridgeLoopbackSupport.swift \ + holmes/tests/BridgeSoak.swift \ + -o "$soak_test_dir/bridge-soak" +"$soak_test_dir/bridge-soak" | grep -v '^\[Bridge\]' diff --git a/holmes/tests/run-browser-compose-bridge-tests.sh b/holmes/tests/run-browser-compose-bridge-tests.sh index 9924916..4e74abe 100755 --- a/holmes/tests/run-browser-compose-bridge-tests.sh +++ b/holmes/tests/run-browser-compose-bridge-tests.sh @@ -11,6 +11,8 @@ xcrun swiftc -D DEBUG -swift-version 5 \ holmes/holmes/Core/BrowserBridge.swift \ holmes/holmes/Core/Setup/ExtensionInstaller.swift \ holmes/tests/BrowserComposeTestSupport.swift \ + holmes/tests/BridgeLoopbackSupport.swift \ + holmes/tests/BridgeLoopbackTests.swift \ holmes/tests/BrowserComposeBridgeTests.swift \ -o "$bridge_test_dir/bridge-tests" "$bridge_test_dir/bridge-tests" diff --git a/holmes/tests/run-computer-use-run-tests.sh b/holmes/tests/run-computer-use-run-tests.sh new file mode 100755 index 0000000..deeb86d --- /dev/null +++ b/holmes/tests/run-computer-use-run-tests.sh @@ -0,0 +1,11 @@ +#!/bin/bash +set -euo pipefail +run_registry_repo_root=$(cd "$(dirname "$0")/../.." && pwd) +run_registry_test_dir=$(mktemp -d "${TMPDIR:-/tmp}/holmes-computer-use-runs.XXXXXX") +trap 'rm -rf "$run_registry_test_dir"' EXIT +cd "$run_registry_repo_root" +xcrun swiftc -swift-version 5 \ + holmes/holmes/Core/ComputerUseRunRegistry.swift \ + holmes/tests/ComputerUseRunRegistryTests.swift \ + -o "$run_registry_test_dir/computer-use-run-tests" +"$run_registry_test_dir/computer-use-run-tests" diff --git a/holmes/tests/run-guided-demo-tests.sh b/holmes/tests/run-guided-demo-tests.sh index e2be41f..54f874f 100755 --- a/holmes/tests/run-guided-demo-tests.sh +++ b/holmes/tests/run-guided-demo-tests.sh @@ -8,6 +8,7 @@ xcrun swiftc -swift-version 5 \ holmes/holmes/Core/OllamaConfig.swift \ holmes/holmes/Core/WorkActivity.swift \ holmes/holmes/Core/OllamaClient.swift \ + holmes/holmes/Core/ModelJSON.swift \ holmes/holmes/Core/AppLauncher.swift \ holmes/holmes/Core/GuidedDemo.swift \ holmes/tests/GuidedDemoTests.swift \ diff --git a/holmes/tests/run-mcp-http-transport-tests.sh b/holmes/tests/run-mcp-http-transport-tests.sh index f940d2a..675ddea 100755 --- a/holmes/tests/run-mcp-http-transport-tests.sh +++ b/holmes/tests/run-mcp-http-transport-tests.sh @@ -8,6 +8,7 @@ xcrun swiftc -swift-version 5 \ holmes/holmes/Core/OllamaConfig.swift \ holmes/holmes/Core/WorkActivity.swift \ holmes/holmes/Core/OllamaClient.swift \ + holmes/holmes/Core/ModelJSON.swift \ holmes/holmes/Core/MCPModels.swift \ holmes/holmes/Core/MCPClient.swift \ holmes/tests/MCPHTTPTransportTests.swift \ diff --git a/holmes/tests/run-model-json-tests.sh b/holmes/tests/run-model-json-tests.sh new file mode 100755 index 0000000..a585295 --- /dev/null +++ b/holmes/tests/run-model-json-tests.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail +model_json_repo_root=$(cd "$(dirname "$0")/../.." && pwd) +model_json_test_dir=$(mktemp -d "${TMPDIR:-/tmp}/holmes-model-json.XXXXXX") +trap 'rm -rf "$model_json_test_dir"' EXIT +cd "$model_json_repo_root" +xcrun swiftc -swift-version 5 \ + holmes/holmes/Core/ModelJSON.swift \ + holmes/tests/ModelJSONTests.swift \ + -o "$model_json_test_dir/model-json-tests" +"$model_json_test_dir/model-json-tests" +xcrun swiftc -swift-version 5 \ + holmes/holmes/Core/OllamaConfig.swift \ + holmes/holmes/Core/WorkActivity.swift \ + holmes/holmes/Core/OllamaClient.swift \ + holmes/holmes/Core/ModelJSON.swift \ + holmes/tests/ToolCallRecoveryTests.swift \ + -o "$model_json_test_dir/tool-call-recovery-tests" +"$model_json_test_dir/tool-call-recovery-tests" diff --git a/holmes/tests/run-ollama-capability-cache-tests.sh b/holmes/tests/run-ollama-capability-cache-tests.sh index 3df2b9a..34445d2 100755 --- a/holmes/tests/run-ollama-capability-cache-tests.sh +++ b/holmes/tests/run-ollama-capability-cache-tests.sh @@ -8,6 +8,7 @@ xcrun swiftc -swift-version 5 \ holmes/holmes/Core/OllamaConfig.swift \ holmes/holmes/Core/WorkActivity.swift \ holmes/holmes/Core/OllamaClient.swift \ + holmes/holmes/Core/ModelJSON.swift \ holmes/tests/OllamaCapabilityCacheTests.swift \ -o "$capability_test_dir/ollama-capability-cache-tests" "$capability_test_dir/ollama-capability-cache-tests" diff --git a/holmes/tests/run-text-entry-tests.sh b/holmes/tests/run-text-entry-tests.sh new file mode 100755 index 0000000..63cc650 --- /dev/null +++ b/holmes/tests/run-text-entry-tests.sh @@ -0,0 +1,11 @@ +#!/bin/bash +set -euo pipefail +text_entry_repo_root=$(cd "$(dirname "$0")/../.." && pwd) +text_entry_test_dir=$(mktemp -d "${TMPDIR:-/tmp}/holmes-text-entry.XXXXXX") +trap 'rm -rf "$text_entry_test_dir"' EXIT +cd "$text_entry_repo_root" +xcrun swiftc -swift-version 5 \ + holmes/holmes/Core/TextEntrySupport.swift \ + holmes/tests/TextEntrySupportTests.swift \ + -o "$text_entry_test_dir/text-entry-tests" +"$text_entry_test_dir/text-entry-tests" diff --git a/holmes/tests/run-work-activity-tests.sh b/holmes/tests/run-work-activity-tests.sh index 116b8fa..ef8cc61 100755 --- a/holmes/tests/run-work-activity-tests.sh +++ b/holmes/tests/run-work-activity-tests.sh @@ -28,6 +28,7 @@ xcrun swiftc -swift-version 5 \ holmes/holmes/Core/WorkActivity.swift \ holmes/holmes/Core/OllamaConfig.swift \ holmes/holmes/Core/OllamaClient.swift \ + holmes/holmes/Core/ModelJSON.swift \ holmes/tests/OllamaWorkActivityTests.swift \ -o "$work_test_dir/ollama-work-tests" "$work_test_dir/ollama-work-tests"