fix(server): agent browser tools stop bloating history, fall back sensibly, and respect ownership #16956
Mergedjuliusmarmingemerged 8 commits into
main fromrefs/pull/16956/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge added labelsmacroscope-review
- apps/server/src/preview/ServerBrowser.ts line 1831Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1602,4 +1705,10 @@16021705 await resolveDialog(tab, input as PreviewAutomationDialogInput);16031706 return statusWithTitle(tab, request.agentSessionId);16041707 }1605- return tab.control.agent(request.agentSessionId!, async () => {1708+ const agentSessionId = request.agentSessionId!;1709+ // A tab this session did not open, while it cannot act there (another1710+ // agent's, or the user's while they drive): read it in place, without1711+ // queueing behind the human's input. Its own tabs keep the takeover1712+ // contract: a human taking control interrupts every agent call.1713+ if (1714+ READ_OPERATIONS.has(request.operation) &&
- apps/server/src/preview/ServerBrowser.ts lines 1825 to 1844Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1605 +1708,20 @@1605- return tab.control.agent(request.agentSessionId!, async () => {1708+ const agentSessionId = request.agentSessionId!;1709+ // A tab this session did not open, while it cannot act there (another1710+ // agent's, or the user's while they drive): read it in place, without1711+ // queueing behind the human's input. Its own tabs keep the takeover1712+ // contract: a human taking control interrupts every agent call.1713+ if (1714+ READ_OPERATIONS.has(request.operation) &&1715+ tab.control.agentId !== agentSessionId &&1716+ !tab.control.agentCanActNow(agentSessionId)1717+ ) {1718+ return tab.control.observe(async () => {1719+ if (tab.dialog)1720+ throw new BrowserControlInterrupted(1721+ "A browser dialog is pending. Read preview_status.",1722+ "dialogPending",1723+ );1724+ return executeTabOperation(tab, request);1725+ });1726+ }1727+ return tab.control.agent(agentSessionId, async () => {
- apps/server/src/mcp/toolkits/attachment/handlers.ts lines 61 to 61Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -79,0 +33,21 @@33+const UPLOAD_OWNER_TTL_MS = 24 * 60 * 60 * 1000;34+35+/** A thread owns its uploads across provider sessions; an outside client per MCP session. */36+const uploadOwner = McpInvocationContext.McpInvocationContext.pipe(37+ Effect.map((scope) => scope.thread?.threadId ?? scope.requestNamespace),38+);39+40+export const layer = McpToolAccess.toLayer(41+ AttachmentToolkit,42+ Effect.sync(() => {43+ // Which caller prepared each pending upload, so only that caller can discard it.44+ const uploadOwners = new Map<string, { readonly owner: string; readonly issuedAt: number }>();45+ return {46+ t3_attachment_prepare_upload: McpToolAccess.writes((input) =>47+ Effect.gen(function* () {48+ const result = yield* Upload.issueAttachmentUploadUrl(input.upload).pipe(49+ Effect.mapError(unavailable),50+ );51+ const now = yield* Clock.currentTimeMillis;52+ for (const [id, entry] of uploadOwners) {53+ if (now - entry.issuedAt > UPLOAD_OWNER_TTL_MS) uploadOwners.delete(id);
- apps/server/src/mcp/toolkits/attachment/handlers.ts line 52Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -75,5 +37,16 @@75- status: result.run.status,76- };77- }),78- ),79-});37+/**38+ * As long as the pending file can live. The sweep counts its 24 hours from when39+ * the upload finishes, which can be up to the upload URL's lifetime after issue.40+ */41+const UPLOAD_OWNER_TTL_MS = 24 * 60 * 60 * 1000 + ATTACHMENT_UPLOAD_URL_TTL_MS;42+43+/** A thread owns its uploads across provider sessions; an outside client per MCP session. */44+const uploadOwner = McpInvocationContext.McpInvocationContext.pipe(45+ Effect.map((scope) => scope.thread?.threadId ?? scope.requestNamespace),46+);47+48+export const layer = McpToolAccess.toLayer(49+ AttachmentToolkit,50+ Effect.sync(() => {51+ // Which caller prepared each pending upload, so only that caller can discard it.52+ const uploadOwners = new Map<string, { readonly owner: string; readonly issuedAt: number }>();
- apps/server/src/mcp/toolkits/attachment/handlers.ts lines 40 to 44Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -67,13 +37,8 @@67- ? new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message })68- : unavailable(),69- ),70- );71- return {72- threadId: projection.thread.id,73- messageId,74- runId: result.run.id,75- status: result.run.status,76- };77- }),78- ),79-});37+/**38+ * As long as the pending file can live. The sweep counts its 24 hours from when39+ * the upload finishes, which can be up to the upload URL's lifetime after issue.40+ */41+const UPLOAD_OWNER_TTL_MS = 24 * 60 * 60 * 1000 + ATTACHMENT_UPLOAD_URL_TTL_MS;42+43+/** A thread owns its uploads across provider sessions; an outside client per MCP session. */44+const uploadOwner = McpInvocationContext.McpInvocationContext.pipe(
juliusmarminge merged thisdbd8343
juliusmarminge closed this
Sign in to join this conversation.
Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
📝 Walkthrough
Walkthrough#
The changes add browser-profile reporting and profile selection to preview tools. They expand tab visibility and separate read access from action control. MCP snapshot images become opt-in, upload discards check ownership, and device screenshots require a matching open session. Browser instructions add a fallback condition after repeated preview failures.
Changes#
Preview tab access and browser profiles
packages/contracts/src/preview.ts,packages/contracts/src/rpc.ts,packages/client-runtime/src/state/preview.ts,apps/web/src/browser/BrowserProfileReporter.tsx,apps/web/src/AppRoot.tsx,apps/server/src/ws.ts,apps/server/src/preview/ServerBrowser.ts,apps/server/src/auth/*,apps/server/src/observability/RpcInstrumentation.ts,apps/server/src/preview/ServerBrowserStream.test.tspackages/contracts/src/previewAutomation.ts,apps/server/src/preview/ServerBrowser.ts,apps/server/src/preview/ServerBrowser.test.ts,apps/web/src/browser/ElectronBrowserHost.tsxpreview_openaccepts a profile ID or name. The server resolves reported profiles, uses the reported default when available, and returns profile metadata. The browser host supplies its configured default when no profile ID is provided.packages/contracts/src/previewAutomation.ts,apps/server/src/preview/ServerBrowser.ts,apps/server/src/preview/SessionControl.ts,apps/server/src/preview/ServerBrowser.test.ts,apps/server/src/preview/SessionControl.test.ts,apps/server/src/mcp/toolkits/preview/tools.tsMCP tool behavior
apps/server/src/mcp/McpHttpServer.ts,apps/server/src/mcp/McpHttpServer.test.ts,apps/server/src/mcp/toolkits/preview/tools.tsincludeImageis explicitly true, including for saved screenshots. The default is text-only, and tool metadata no longer marks snapshots read-only or idempotent.apps/server/src/mcp/toolkits/attachment/handlers.ts,apps/server/src/mcp/McpHttpServer.ts,apps/server/src/mcp/toolkits/core.test.tsinvalid_request; successful discards remove the ownership record.apps/server/src/mcp/toolkits/device/handlers.ts,apps/server/src/mcp/McpDeviceToolkit.test.tsdevice_screenshotselects the most recently opened matching device session in the current thread. Missing matches produce errors based on whether a device is open and whether the requested device is open on the selected host.Browser fallback guidance
packages/provider-core/src/server/orchestrationInstructions.tsPriority: ➖ Normal
Estimated code review effort: 4 (Complex) | ~50 minutes
Change: Bug fix · Severity of issue fixed: Medium
Sequence Diagram(s)#
Suggested reviewers:
maria-rcksMerge Risk: 🔵 Low · up to
2668aA separate MCP session using the same OAuth token can discard another session’s pending attachment, disrupting upload-dependent work. This is a bounded ownership issue to fix or explicitly accept before merge.
🚥 Pre-merge checks | ✅ 3 | ❌ 1
❌ Failed checks (1 warning)#
device_screenshotaccess control and caller-owned pending-upload discard tracking. These changes and their tests address MCP ownership work referenced as#15962. The directly linked acti…#15962, or link a direct coding issue that requires this ownership work.✅ Passed checks (3 passed)
#11295], [#16404], [#15798], and [#16701].preview_snapshotdefaults to text-only output and returns the saved path without inline image data unless `includeI…Full details: Out of Scope Changes check
Explanation
The PR adds
device_screenshotaccess control and caller-owned pending-upload discard tracking. These changes and their tests address MCP ownership work referenced as#15962. The directly linked active issues require snapshot handling, browser fallback and workflow selection, and preview tab/profile behavior. They do not require these device and attachment ownership changes.✨ Finishing Touches
📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.