diff --git a/CHANGELOG.md b/CHANGELOG.md index 03f7b2b4a..16deda556 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,7 @@ determines which versions can connect. ### Fixed +- Eliminated frequent false `"Page interaction coverage changed; wait and synchronize"` (`control_context_invalid` with `effect_state: "unknown"` and `IntentWal` tab freezes) across SPA sites and pages with dynamic subframes: separated same-document root URL updates (`Page.navigatedWithinDocument` and `FrameState.url`) from cross-document root destruction via `ChromiumCdp.onRouteChanged` / `CooperationController.invalidateRoute` (restoring `rootFrameId`, reconciling child frames across `soft_detached` reattach and post-dialog checks on same-document route updates, and stopping same-process child-iframe `DOM.documentUpdated` events from firing root `onDocumentChanged`) so live collectors stay available, multi-step inputs (`fill`, `scroll-to`, `wheel`, `press`, `select`, `click`, `drag`) and `bsk plan` batches survive same-pathname query/anchor updates (while consuming strict baselines for untargeted actions) and pathname/hash-router transitions revoke stale contexts cleanly after action settlement (`effect_state: "none"`), completed `fill` Step 3 across both `onBeforeNavigate` and instant-commit auto-submitting forms (`finalValueAlreadyNotified`) as well as post-input `Runtime.callFunctionOn` / `DOM.getBoxModel` visibility measurement across main and child frames, sequenced background `observeTab` behind `armCommittedFrame` while initializing collection leases on `COOPERATION_ARM` and `COOPERATION_RESUME` for newly mounted child frames, allowing `collectCooperationFrames` replacement passes past proven-hidden unobservable subframes, and isolating in-flight `state.working` operations and `target` contexts from non-owner `refresh` failures, and preserved explicit handler errors (`navigate`/`reload` errors and structured `result.data.reason` errors such as `download_capture_failed` and `fill_target_changed`) while revoking stale implicit `target` context auto-injection in `ImplicitScopeRegistry` (without dropping cached `last_vom` / alias hydration for `unchanged` and `delta` syncs) and allowing `navigate`/`reload`/`navigate_back`/`navigate_forward` recovery off `page_load_failed` error pages (#762). - Fixed `tool.wheel` skipping compositor paint readiness (`waitForInputPaint`) under `ToolDispatcher` persistent background leases on unfocused or minimized windows by decoupling `ReadyInput.hidden` (`lacksForegroundPresentation`) from temporary `restoreFocus` and wiring `windowsApi` in `ToolDispatcher`; stopped `target`-policy `--selector` actions in `CooperationController` from polluting `session.refStore`, emitting `used_ref` (while preserving `used_selector` on `--selector` action receipts without polluting `tool.drag`'s `DragResult` or `tool.press`'s `PressResult`), or leaking hallucinated `@eN` references in `handleSelect` custom-dropdown error messages (`withPinnedSelectorTargets`); refreshed live frame activity inside `CooperationController.beginDomMutation()` under `target` policy before scripted DOM writes while preserving `state.baseline` (`observation_id`) when pre-write validation fails with `effect_state: "none"`; fixed `clearRecordingForSession` to use the caller/dispatcher's `deps` (`RECORD_CANCEL` + `bypassOverlay(tabId, false)`), required explicit `isAgentWindowId` in `returnBorrowedTab` so returning a borrowed user tab never routes into another session's Agent Window, replaced module-global download locking with instance-scoped `DownloadConcurrencyGate` (`session_busy`, `effect_state: "none"`, `dispatched: false`), and cleaned up `observeIdentityStreaks`, `hoverLatches`, and `hoverBypassTabs` on session teardown and `tabs.onRemoved`; enabled Canvas `[visual:screenshot]` `@eN` parity on `cooperate sync`, budgeted the `renderDoubleLayer` `L2 page … occluded by L1` footer line within `maxTokens`, and moved popup `[expanded]` / `[has-submenu]` tags out of `vom.name` to post-quote VOM tags so custom dropdowns no longer emit duplicate `[expanded]` suffixes. - Eliminated redundant back-to-back frame collection sweeps in `guardedRunner.runBrowserMutation` (`action-guard.ts`), skipped mutation fencing on passive `inspect` probes in `handleFullPageScreenshot`, and raised the per-frame cooperation IPC reply deadline (`FRAME_REPLY_TIMEOUT_MS` / `OWNER_REPLY_MS`) from `1200ms` to `3000ms` so cold high-DPR / software-rasterized full-page captures and Tier-A overlay mounts do not spuriously fail with `FrameUnresponsiveError` (#761). - Added `--max-tokens` (`max_tokens` in MCP) to `bsk step`, `bsk plan`, `bsk_interact` (with `sync_after` or `until_visible`), and `bsk_plan`, forwarding it to the post-action `tool.cooperate` sync instead of hardcoding `None` so `--max-tokens` baselines stay reusable across `delta` and `unchanged` syncs without forcing an unbounded page re-capture (#755). diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index baabed307..e56c69072 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -31,6 +31,7 @@ CLI 和扩展可以分别发布,能否连接由协议兼容性决定。更新 ### 修复 +- 修复现代 SPA 页面与含动态子 ` +
+
Deep section
+ `); + }); + const runCli = async (...args: string[]) => { + try { + const { stdout } = await promisify(execFile)(executable, [...args, "--json"], { + env, + timeout: 25000, + }); + return { exitCode: 0, body: JSON.parse(stdout) }; + } catch (error) { + const failed = error as { code?: number; stdout?: string }; + if (failed.stdout) { + return { exitCode: failed.code ?? 1, body: JSON.parse(failed.stdout) }; + } + throw error; + } + }; + try { + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const url = `http://127.0.0.1:${(server.address() as { port: number }).port}/`; + let port = 0; + await expect + .poll( + async () => { + try { + port = JSON.parse( + await readFile(path.join(env.BSK_HOME, "daemon.json"), "utf8"), + ).ws_port; + return port; + } catch { + return 0; + } + }, + { timeout: 15000 }, + ) + .toBeGreaterThan(0); + const { copyPairingExtension, pairLocalBrowser } = await import( + new URL("../../../../evals/browser/local-pairing.mjs", import.meta.url).href + ); + const distPath = fileURLToPath(new URL("../../dist/chrome-mv3", import.meta.url)); + const extension = await copyPairingExtension( + distPath, + path.join(directory, "extension"), + port, + ); + const manifestPath = path.join(extension, "manifest.json"); + const manifest = JSON.parse(await readFile(manifestPath, "utf8")); + manifest.name = "BrowserSkill SPA coverage regression"; + await writeFile(manifestPath, JSON.stringify(manifest)); + const { withChrome } = await import( + new URL( + "../../../../evals/browser/cases/regression/snapshot-coordinates/chrome.mjs", + import.meta.url, + ).href + ); + const { createMcpRegressionClient } = await import( + new URL( + "../../../../evals/browser/cases/regression/cooperation/mcp-client.mjs", + import.meta.url, + ).href + ); + await withChrome( + { + executable: process.env.BSK_TEST_CHROME, + extensionPath: extension, + extensionViaCdp: process.env.BSK_TEST_LOAD_CDP === "1", + deviceScale: 1, + zoom: 1, + }, + async (send: BrowserSend) => { + const worker = await attachVideoBackground(send, manifest.name); + await pairLocalBrowser(send, { executable, env, worker }); + await expect + .poll(async () => (await runCli("browsers")).body.length, { timeout: 15000 }) + .toBeGreaterThan(0); + const mcp = await createMcpRegressionClient(executable, env); + let session: string | undefined; + try { + session = (await mcp.run("bsk_session", { action: "start" })).session_id; + const scope = ["--session", session!]; + await mcp.run("bsk_page", { action: "navigate", session, url }); + const synced = await mcp.run("bsk_session", { action: "sync", session }); + expect(synced.control_policy).toBe("target"); + const ctx = synced.context_id as string; + + // 1. `fill` triggering `history.replaceState(?q=...)` + subframe churn completes Step 3 + // (`change` event + readback), keeps IntentWal settled, and preserves `context_id`. + const filled = await runCli( + "fill", + "#search", + "--value", + "shoes", + ...scope, + "--context", + ctx, + ); + expect(filled.body).toMatchObject({ actual_value: "shoes", value_length: 5 }); + expect(filled.exitCode).toBe(0); + expect((await runCli("ledger", "status", ...scope)).body.frozen).toBe(false); + // Same-pathname query update still consumes the strict baseline for opaque untargeted input. + const untargetedAfterQuery = await runCli( + "press", + "Escape", + ...scope, + "--context", + ctx, + "--observation", + synced.observation_id as string, + ); + expect(untargetedAfterQuery.exitCode).not.toBe(0); + expect(untargetedAfterQuery.body.data).toMatchObject({ effect_state: "none" }); + + // 2. `scroll-to` triggering `history.replaceState(#deep-section)` completes visibility + // measurement and keeps `context_id` ready for subsequent actions. + const scrolled = await runCli("scroll-to", "#deep-section", ...scope, "--context", ctx); + expect(scrolled.exitCode).toBe(0); + expect(scrolled.body.height).toBeGreaterThan(0); + expect((await runCli("cooperate", "status", ...scope)).body).toMatchObject({ + ready: true, + state: { mode: "ready" }, + }); + + // 3. `bsk plan` chains `fill` (`replaceState`) -> `click` tab (`pushState(?view=...)`) + // -> `click` apply across a single pinned `context_id`. + const planned = await runCli( + "plan", + ...scope, + "--context", + ctx, + "--steps", + JSON.stringify([ + { action: "fill", selector: "#search", value: "boots" }, + { action: "click", selector: "#tab-anomalies" }, + { action: "click", selector: "#apply" }, + ]), + ); + expect(planned.exitCode, JSON.stringify(planned)).toBe(0); + expect(planned.body).toMatchObject({ ok: true, completed: 3 }); + const readStatus = await runCli("read", "--selector", "#status", ...scope); + expect(readStatus.body.items[0].values.text).toBe("applied:1:boots"); + expect((await runCli("ledger", "status", ...scope)).body.frozen).toBe(false); + + // 4. Clicking an SPA pathname link (`/orders`) completes its click receipt cleanly + // without freezing IntentWal or entering `unavailable`, then revokes the old context + // with `effect_state: "none"` for subsequent un-synced actions. + const routeCtx = planned.body.post.context_id as string; + const clickedRoute = await runCli( + "click", + "#spa-orders", + ...scope, + "--context", + routeCtx, + ); + expect(clickedRoute.exitCode).toBe(0); + expect((await runCli("ledger", "status", ...scope)).body.frozen).toBe(false); + expect((await runCli("cooperate", "status", ...scope)).body.state.mode).toBe("syncing"); + const staleAfterRoute = await runCli( + "click", + "#apply", + ...scope, + "--context", + routeCtx, + ); + expect(staleAfterRoute.exitCode).not.toBe(0); + expect(staleAfterRoute.body.data).toMatchObject({ + reason: "control_context_invalid", + effect_state: "none", + }); + expect((await runCli("ledger", "status", ...scope)).body.frozen).toBe(false); + + // 5. Navigating to a closed port preserves the real `Page.navigate` network error + // instead of masking it behind `Page interaction coverage changed`. + const ordersSync = await mcp.run("bsk_session", { action: "sync", session }); + const failedNav = await runCli( + "navigate", + `http://127.0.0.1:${closedPort}/`, + ...scope, + "--context", + ordersSync.context_id, + "--observation", + ordersSync.observation_id, + ); + expect(failedNav.exitCode).not.toBe(0); + expect(failedNav.body.code).toBe("cdp_failed"); + expect(failedNav.body.message).toContain("Page.navigate rejected"); + await runCli("ledger", "resolve", ...scope); + + // 6. Clicking a broken link (`ResponseBody::Ok` -> Chrome `page_load_failed` interstitial) + // recovers on the first `back` attempt even with an auto-injected implicit `target` context, + // and auto-submitting `fill` (`oninput="form.requestSubmit()"`) completes Step 3 cleanly. + await mcp.run("bsk_page", { action: "navigate", session, url }); + await mcp.run("bsk_session", { action: "sync", session }); + expect((await runCli("click", "#broken-link", ...scope)).exitCode).toBe(0); + await expect + .poll( + async () => { + const { targetInfos } = (await send("Target.getTargets")) as { + targetInfos: { type: string; url: string }[]; + }; + return targetInfos.some( + (info) => + info.type === "page" && + (info.url.includes("chromewebdata") || info.url.includes(`:${closedPort}/`)), + ); + }, + { timeout: 10000 }, + ) + .toBe(true); + await new Promise((resolve) => setTimeout(resolve, 150)); + const recoveredBack = await runCli("navigate-back", ...scope); + expect(recoveredBack.exitCode, JSON.stringify(recoveredBack)).toBe(0); + const otpSync = await mcp.run("bsk_session", { action: "sync", session }); + const otpFilled = await runCli( + "fill", + "#otp", + "--value", + "otp6", + ...scope, + "--context", + otpSync.context_id, + ); + expect(otpFilled.exitCode, JSON.stringify(otpFilled)).toBe(0); + expect(otpFilled.body).toMatchObject({ actual_value: "otp6", value_length: 4 }); + expect((await runCli("ledger", "status", ...scope)).body.frozen).toBe(false); + let doneSync = await mcp.run("bsk_session", { action: "sync", session }); + await expect + .poll( + async () => { + doneSync = await mcp.run("bsk_session", { action: "sync", session }); + return doneSync.observation?.text ?? ""; + }, + { timeout: 10000 }, + ) + .toContain("OTP Submitted"); + // Same-document `#top` navigate (`ToolNavigate` + unchanged `sync`) preserves `cached_vom`. + expect( + ( + await runCli( + "navigate", + `${url}done?otp=otp6#top`, + ...scope, + "--context", + doneSync.context_id, + "--observation", + doneSync.observation_id, + ) + ).exitCode, + ).toBe(0); + const hashSync = await mcp.run("bsk_session", { action: "sync", session }); + expect( + ( + await runCli( + "navigate", + `${url}done?otp=otp6#top`, + ...scope, + "--context", + hashSync.context_id, + "--observation", + hashSync.observation_id, + ) + ).exitCode, + ).toBe(0); + const unchangedAfterNav = await runCli("sync", ...scope); + expect(unchangedAfterNav.exitCode).toBe(0); + expect(unchangedAfterNav.body.vom).toContain("OTP Submitted"); + } finally { + if (session) await runCli("session", "stop", session).catch(() => {}); + await mcp.dispose(); + } + }, + ); + } finally { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + if (daemon.exitCode === null && daemon.signalCode === null) { + const exited = once(daemon, "exit"); + daemon.kill(); + await exited; + } + await rm(directory, { recursive: true, force: true }); + } + }, + 60000, +); diff --git a/apps/extension/src/cooperation/target-policy.test.ts b/apps/extension/src/cooperation/target-policy.test.ts index 34eb1b2e9..4b4860739 100644 --- a/apps/extension/src/cooperation/target-policy.test.ts +++ b/apps/extension/src/cooperation/target-policy.test.ts @@ -2126,3 +2126,111 @@ describe("text deltas under target control", () => { ); }); }); + +describe("same-document routes, concurrent background observation, and handler failure receipts", () => { + it("completes multi-step targeted actions across same-pathname query/hash updates and defers pathname route invalidation until settlement", async () => { + const f = await fixture("target"); + const stepReceipt = { tab_id: 7, actual_value: "shoes", value_length: 5 }; + const fillResult = await f.run({ ref: "e1" }, "tool.fill", async (runner) => { + await runner.beginDomMutation?.(); + await runner.send(7, "Input.insertText", { text: "shoes" }); + f.controller.invalidateRoute(7, "https://fixture.test/?q=shoes#results"); + await runner.send(7, "Runtime.callFunctionOn", { + objectId: "input-obj-1", + functionDeclaration: "function() { return true; }", + }); + return stepReceipt; + }); + expect(fillResult).toEqual(stepReceipt); + expect(f.controller.view(7)?.mode).toBe("ready"); + // Same-pathname query/hash update preserves target context for the next step. + expect(await f.run({ ref: "e1" }, "tool.click", async () => ({ tab_id: 7 }))).toEqual({ + tab_id: 7, + }); + + // Clicking an SPA link that changes pathname finishes cleanly, keeps mode out of + // `unavailable`, and revokes the old context with `effect_state: "none"` afterward. + const routeClick = await f.run({ ref: "e1" }, "tool.click", async (runner) => { + await runner.send(7, "Input.dispatchMouseEvent", { + type: "mousePressed", + button: "left", + x: 4, + y: 5, + }); + f.controller.invalidateRoute(7, "https://fixture.test/orders"); + await runner.send(7, "Input.dispatchMouseEvent", { + type: "mouseReleased", + button: "left", + x: 4, + y: 5, + }); + return { tab_id: 7, x: 4, y: 5 }; + }); + expect(routeClick).toEqual({ tab_id: 7, x: 4, y: 5 }); + expect(f.controller.view(7)?.mode).toBe("syncing"); + expect(await f.run({ ref: "e1" }, "tool.click")).toMatchObject({ + code: "permission_denied", + data: { reason: "control_context_invalid", effect_state: "none" }, + }); + }); + + it("isolates in-flight actions and target contexts from transient background observeTab failures while preserving structured handler errors", async () => { + const f = await fixture("target"); + // Transient subframe error during idle background `observeTab` recovers once collection succeeds. + f.readFrames.mockRejectedValueOnce(new Error("subframe temporarily unavailable")); + await f.controller.observeTab(7); + expect(f.controller.view(7)?.mode).toBe("unavailable"); + + // In-flight main-document action survives a concurrent background `observeTab` failure. + const fillReceipt = { tab_id: 7, actual_value: "ok", value_length: 2 }; + const completed = await f.run({ ref: "e1" }, "tool.fill", async (runner) => { + await runner.beginDomMutation?.(); + await runner.send(7, "Input.insertText", { text: "ok" }); + f.readFrames.mockRejectedValueOnce(new Error("background subframe replacing")); + await f.controller.observeTab(7); + await runner.send(7, "Runtime.callFunctionOn", { + objectId: "input-obj-2", + functionDeclaration: "function() { return true; }", + }); + return fillReceipt; + }); + expect(completed).toEqual(fillReceipt); + + // Structured handler error (e.g. failed download after `onBeforeNavigate`) is preserved, + // not overwritten with `Page interaction coverage changed`, while revoking old context. + const downloadError = { + code: "cdp_failed" as const, + message: "HTTP 500 instead of file attachment", + data: { + reason: "download_capture_failed", + phase: "execution", + effect_state: "unknown" as const, + }, + }; + const failedDownload = await f.run({ ref: "e1" }, "tool.download", async (runner) => { + await runner.send(7, "Input.dispatchMouseEvent", { + type: "mousePressed", + button: "left", + x: 4, + y: 5, + }); + f.controller.invalidate(7); + await runner.send(7, "Input.dispatchMouseEvent", { + type: "mouseReleased", + button: "left", + x: 4, + y: 5, + }); + return downloadError; + }); + expect(failedDownload).toMatchObject({ + code: "cdp_failed", + message: "HTTP 500 instead of file attachment", + data: { reason: "download_capture_failed", effect_state: "unknown" }, + }); + expect(await f.run({ ref: "e1" }, "tool.click")).toMatchObject({ + code: "permission_denied", + data: { reason: "control_context_invalid", effect_state: "none" }, + }); + }); +}); diff --git a/apps/extension/src/cooperation/types.ts b/apps/extension/src/cooperation/types.ts index 67d0b2908..82bc07824 100644 --- a/apps/extension/src/cooperation/types.ts +++ b/apps/extension/src/cooperation/types.ts @@ -61,6 +61,7 @@ export interface TextChange { export interface FrameState { document: string; + url?: string; /** Collector-local identity of the deep active element in this document. */ focus?: string; /** True only for the ordinary document focus, without a specific recipient. */ diff --git a/apps/extension/src/entrypoints/background.ts b/apps/extension/src/entrypoints/background.ts index 69dd20477..0b4e21721 100644 --- a/apps/extension/src/entrypoints/background.ts +++ b/apps/extension/src/entrypoints/background.ts @@ -180,6 +180,9 @@ export default defineBackground(() => { sessions.invalidateTabRefs(tabId); cooperation.invalidate(tabId); }, + onRouteChanged: (tabId, url) => { + cooperation.invalidateRoute(tabId, url); + }, onChildFramesInvalidated: (tabId, staleFrameIds) => { sessions.invalidateTabChildFrames(tabId, staleFrameIds); cooperation.invalidateChildFrames(tabId); diff --git a/apps/extension/src/tools/interaction.ts b/apps/extension/src/tools/interaction.ts index 02b92eb76..9a6324170 100644 --- a/apps/extension/src/tools/interaction.ts +++ b/apps/extension/src/tools/interaction.ts @@ -1677,22 +1677,53 @@ export async function handleFill( (clearBefore && params.value === "" && !valueAssigned) || (step1.write === "insert" && params.value !== ""); const notifyInput = !finalValueAlreadyNotified; - const verified = await nodeCdp.send>( - target.tabId, - "Runtime.callFunctionOn", - { - objectId, - functionDeclaration: FILL_STEP3_FUNCTION, - arguments: [ - { value: notifyInput }, - { value: step1.expected }, - { value: step1.isSensitive }, - { value: FILL_MAX_ACTUAL_VALUE_CHARS }, - ], - awaitPromise: true, - returnByValue: true, - }, - ); + let verified: FillScriptReply; + try { + verified = await nodeCdp.send>( + target.tabId, + "Runtime.callFunctionOn", + { + objectId, + functionDeclaration: FILL_STEP3_FUNCTION, + arguments: [ + { value: notifyInput }, + { value: step1.expected }, + { value: step1.isSensitive }, + { value: FILL_MAX_ACTUAL_VALUE_CHARS }, + ], + awaitPromise: true, + returnByValue: true, + }, + ); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + if ( + finalValueAlreadyNotified && + !deps.signal?.aborted && + (isStaleFrameHandleError(err) || + /Cannot find context|Execution context was destroyed|Inspected target navigated or closed/i.test( + msg, + )) + ) { + const chars = + !step1.isSensitive && step1.expected.length > FILL_MAX_ACTUAL_VALUE_CHARS + ? Array.from(step1.expected) + : null; + const actualValue = step1.isSensitive + ? undefined + : chars && chars.length > FILL_MAX_ACTUAL_VALUE_CHARS + ? chars.slice(0, FILL_MAX_ACTUAL_VALUE_CHARS).join("") + : step1.expected; + return attachDialogs(deps.cdp, target.tabId, dialogCursor, { + tab_id: target.tabId, + used_ref: node.usedRef, + used_selector: node.usedSelector, + value_length: step1.expected.length, + ...(actualValue !== undefined ? { actual_value: actualValue } : {}), + }); + } + throw err; + } if (throwIfAborted(deps.signal)) { return { code: "cancelled", message: "fill aborted" }; } diff --git a/crates/bsk-cli/src/daemon/scopes.rs b/crates/bsk-cli/src/daemon/scopes.rs index c15799793..741caf04d 100644 --- a/crates/bsk-cli/src/daemon/scopes.rs +++ b/crates/bsk-cli/src/daemon/scopes.rs @@ -140,6 +140,7 @@ struct ScopeSlot { struct TabContextCache { latest_ctx_id: Option, latest_short_ctx: Option, + implicit_ctx_usable: bool, latest_obs_id: Option, latest_short_obs: Option, last_vom: Option, @@ -162,6 +163,7 @@ struct SessionContextSlot { short_obs_ring: VecDeque<(String, String, Option)>, latest_ctx_id: Option, latest_short_ctx: Option, + implicit_ctx_usable: bool, latest_obs_id: Option, latest_short_obs: Option, last_vom: Option, @@ -594,14 +596,43 @@ impl ImplicitScopeRegistry { return slot .tabs .get(&tid) + .filter(|tab| tab.implicit_ctx_usable) .and_then(|tab| tab.latest_ctx_id.clone()); } - if slot.has_tab_history || !slot.tabs.is_empty() { + if slot.has_tab_history || !slot.tabs.is_empty() || !slot.implicit_ctx_usable { return None; } slot.latest_ctx_id.clone() } + /// Revoke implicit `context_id` auto-injection on `tab_id` (or the session's + /// active tab) when a full-page navigation settles or an action error proves + /// that the cached control context was revoked, while retaining `c` / `o` + /// aliases, predecessor IDs, and `last_vom` so subsequent `unchanged` / `delta` + /// `cooperate` syncs still hydrate cleanly. + pub fn clear_implicit_tab_context( + &self, + session_id: &SessionId, + tab_id: Option, + matching_ctx: Option<&str>, + ) { + let mut guard = self.inner.lock().expect("implicit scope registry poisoned"); + let Some(slot) = guard.sessions.get_mut(session_id) else { + return; + }; + let matches = + |current: &Option| matching_ctx.is_none() || current.as_deref() == matching_ctx; + if let Some(tid) = tab_id.or(slot.active_tab_id) + && let Some(tab) = slot.tabs.get_mut(&tid) + && matches(&tab.latest_ctx_id) + { + tab.implicit_ctx_usable = false; + } + if (tab_id.is_none() || slot.active_tab_id == tab_id) && matches(&slot.latest_ctx_id) { + slot.implicit_ctx_usable = false; + } + } + /// Track active-tab transitions (`tab_create`, `tab_select`, `tab_borrow`, /// `tab_close`, `tab_return`) so omitted `tab_id` never injects a previous /// tab's `context_id` onto a newly created/selected tab. @@ -766,6 +797,7 @@ impl ImplicitScopeRegistry { ); slot.latest_ctx_id = Some(ctx_id.to_string()); slot.latest_short_ctx = Some(short.clone()); + slot.implicit_ctx_usable = true; Some((short, ctx_id.to_string())) } else { None @@ -825,6 +857,7 @@ impl ImplicitScopeRegistry { if let Some((ref short, ref uuid)) = minted_ctx { tab_cache.latest_short_ctx = Some(short.clone()); tab_cache.latest_ctx_id = Some(uuid.clone()); + tab_cache.implicit_ctx_usable = true; } if let Some((ref short, ref uuid)) = minted_obs { tab_cache.latest_short_obs = Some(short.clone()); diff --git a/crates/bsk-cli/src/daemon/tool_pipeline.rs b/crates/bsk-cli/src/daemon/tool_pipeline.rs index 389026082..feb5917f4 100644 --- a/crates/bsk-cli/src/daemon/tool_pipeline.rs +++ b/crates/bsk-cli/src/daemon/tool_pipeline.rs @@ -255,6 +255,76 @@ async fn reconcile_completed_tool_rpc( .record_tab_transition(&tab.session_id, &tab.method, &tab.req_params, value); } if let Some((method, params)) = &plan.logged { + if let Some(sid) = params + .get("session_id") + .and_then(Value::as_str) + .filter(|s| !s.trim().is_empty()) + { + let req_tab_id = params.get("tab_id").and_then(Value::as_i64); + let req_ctx = params + .get("context_id") + .and_then(Value::as_str) + .filter(|s| !s.trim().is_empty()); + match body { + ResponseBody::Ok(val) + if matches!( + method, + Method::ToolNavigate + | Method::ToolReload + | Method::ToolNavigateBack + | Method::ToolNavigateForward + ) => + { + let tid = val.get("tab_id").and_then(Value::as_i64).or(req_tab_id); + state + .scopes + .clear_implicit_tab_context(&SessionId(sid.to_owned()), tid, None); + } + ResponseBody::Err(err) => { + let effect = err + .data + .as_ref() + .and_then(|d| d.get("effect_state")) + .and_then(Value::as_str); + let reason = err + .data + .as_ref() + .and_then(|d| d.get("reason")) + .and_then(Value::as_str); + let tid = err + .data + .as_ref() + .and_then(|d| d.get("tab_id")) + .and_then(Value::as_i64) + .or(req_tab_id); + if effect == Some("unknown") + || matches!(reason, Some("page_load_failed" | "frame_unobservable")) + { + state.scopes.clear_implicit_tab_context( + &SessionId(sid.to_owned()), + tid, + None, + ); + } else if matches!( + reason, + Some( + "control_context_invalid" + | "document_changed" + | "human_intervention" + | "control_held" + | "cooperation_sync_required" + ) + ) { + state.scopes.clear_implicit_tab_context( + &SessionId(sid.to_owned()), + tid, + req_ctx, + ); + } + } + _ => {} + } + } let hydrated_body; let body_for_log = if *method == Method::ToolCooperate && let ResponseBody::Ok(val) = body diff --git a/docs/dynamic-reading.md b/docs/dynamic-reading.md index f081cd4a8..f2d4e52ab 100644 --- a/docs/dynamic-reading.md +++ b/docs/dynamic-reading.md @@ -46,8 +46,11 @@ recycled row IDs, button meaning, price, recipient and input values with `expect Check all facts needed for a comparison, not just one chosen candidate. Restored values can match again; this is a value check, not a promise of unbroken history. -Main document navigation and SPA route changes invalidate old refs and context, -including away-and-back and hash routes. Child-frame reads use that ref's exact +Main document navigation and route-path SPA transitions invalidate +old refs and context (including away-and-back and hash-router paths) without +marking live document collectors unavailable, whereas same-pathname query or +fragment updates preserve reusable target-policy DOM contexts (while still +requiring a fresh strict observation for opaque untargeted actions). Child-frame reads use that ref's exact frame/session and current document identity. A changed or unavailable target document fails; unrelated unavailable frames need not make a main-document read stale. Selectors search the main document; use refs for nested frames and shadow