From 4d200eca1d2646c69d640d2a15ced8f972d7eac0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 15 Aug 2026 14:06:53 +0200 Subject: [PATCH] feat(server): let users withhold browser access from agents MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Agents could always drive the preview browser, with no way to say no. Adds Settings → Integrations → Browser → Agent browser access, on by default. Turning it off withholds the MCP credential in `prepareMcpSession`. That is the only place a credential is minted and the `/mcp` endpoint accepts nothing else, so one branch covers all five providers and any external MCP client — every adapter already treats a missing session as "no MCP server". The Codex developer instructions describing `preview_*` drop out with the tools. That is derived from the session's actual MCP configuration via the existing `hasConfiguredMcpServer`, not from a second read of the setting, so the prompt cannot describe tools the turn doesn't have. Leaving the text in would be worse than saying nothing: it steers the model away from Playwright and agent-browser, so it would talk the agent out of its only remaining browser automation. An unreadable settings file denies rather than propagating the error, which would mean adding ServerSettingsError to a union every caller handles. Denying is the safe direction: an explicit "off" silently becoming "on" would violate the user's choice, while the reverse costs one toolset and is visible at once. The toggle applies to sessions started from then on; a running agent keeps the tools it was given, which the UI states rather than implying otherwise. Co-Authored-By: Claude Opus 5 (1M context) --- .../provider/CodexDeveloperInstructions.ts | 32 +++++++++--- .../Layers/CodexSessionRuntime.test.ts | 38 +++++++++++--- .../provider/Layers/CodexSessionRuntime.ts | 17 +++++-- .../src/provider/Layers/ProviderService.ts | 51 ++++++++++++++++--- .../settings/IntegrationsSettings.tsx | 48 ++++++++++++++++- .../src/components/settings/settingsSearch.ts | 6 +++ packages/contracts/src/settings.ts | 13 +++++ 7 files changed, 181 insertions(+), 24 deletions(-) diff --git a/apps/server/src/provider/CodexDeveloperInstructions.ts b/apps/server/src/provider/CodexDeveloperInstructions.ts index aa7d106e10..7ce2e553e9 100644 --- a/apps/server/src/provider/CodexDeveloperInstructions.ts +++ b/apps/server/src/provider/CodexDeveloperInstructions.ts @@ -11,7 +11,19 @@ For browser work, first call \`preview_status\`. If no automation-capable previe Do not switch to global browser skills, Chrome, Node REPL browser automation, standalone Playwright, or agent-browser merely because the preview is initially closed or a first call fails. Use an alternative browser system only when the T3 preview tools are absent, the user explicitly requests another browser, or \`preview_open\` returns an explicit unsupported/unavailable error. A failed T3 preview tool call should be inspected and retried with corrected arguments when the error is actionable. `; -export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `# Plan Mode (Conversational) +/** + * The browser block is omitted entirely when the preview tools aren't attached. + * Describing `preview_*` tools that aren't in the turn's tool list would be + * worse than saying nothing: the instructions actively steer the model away + * from Playwright and agent-browser, so leaving them in would talk it out of + * the only browser automation it still has. + */ +const browserToolInstructions = (browserToolsAvailable: boolean): string => + browserToolsAvailable ? T3_CODE_BROWSER_TOOL_INSTRUCTIONS : ""; + +export const codexPlanModeDeveloperInstructions = ( + browserToolsAvailable: boolean, +): string => `# Plan Mode (Conversational) You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions. @@ -139,10 +151,12 @@ Do not ask "should I proceed?" in the final output. The user can easily switch o Only produce at most one \`\` block per turn, and only when you are presenting a complete spec. If the user stays in Plan mode and asks for revisions after a prior \`\`, any new \`\` must be a complete replacement. If the user indicates that the prior plan is not acceptable but does not provide enough information to produce a complete replacement, address the concern and continue planning without producing a \`\` block. If the follow-up neither requires changes nor calls the plan into question (e.g. clarifying question), answer it before the block, then reproduce the prior \`\` unchanged. -${T3_CODE_BROWSER_TOOL_INSTRUCTIONS} +${browserToolInstructions(browserToolsAvailable)} `; -export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `# Collaboration Mode: Default +export const codexDefaultModeDeveloperInstructions = ( + browserToolsAvailable: boolean, +): string => `# Collaboration Mode: Default You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active. @@ -153,7 +167,7 @@ Your active mode changes only when new developer instructions with a different \ Use the \`request_user_input\` tool only when it is listed in the available tools for this turn. In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message. -${T3_CODE_BROWSER_TOOL_INSTRUCTIONS} +${browserToolInstructions(browserToolsAvailable)} `; export interface CodexRuntimeInfo { @@ -169,11 +183,17 @@ function toSingleLine(value: string): string { export function buildCodexDeveloperInstructions( interactionMode: ProviderInteractionMode, runtime: CodexRuntimeInfo, + /** + * Whether the `t3-code` MCP server is attached to this turn. Callers derive + * it from the session's actual MCP configuration rather than re-reading the + * setting, so the prompt cannot claim tools the turn doesn't have. + */ + browserToolsAvailable = true, ): string { const base = interactionMode === "plan" - ? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS - : CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS; + ? codexPlanModeDeveloperInstructions(browserToolsAvailable) + : codexDefaultModeDeveloperInstructions(browserToolsAvailable); return `${base} In case you're asked: you are running in T3 Code through the Codex harness, as ${toSingleLine(runtime.model)} with ${toSingleLine(runtime.reasoningEffort)} reasoning effort. No need to mention this otherwise.`; diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts index 2a2de68392..a80ef2cf56 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts @@ -11,8 +11,8 @@ import * as EffectCodexSchema from "effect-codex-app-server/schema"; import { buildCodexDeveloperInstructions, - CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, - CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, + codexDefaultModeDeveloperInstructions, + codexPlanModeDeveloperInstructions, } from "../CodexDeveloperInstructions.ts"; import { codexSessionAppServerArgs } from "./codexLaunchArgs.ts"; import { @@ -255,7 +255,7 @@ describe("buildCodexDeveloperInstructions", () => { reasoningEffort: "high", }); - NodeAssert.ok(instructions.startsWith(CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS)); + NodeAssert.ok(instructions.startsWith(codexDefaultModeDeveloperInstructions(true))); NodeAssert.match(instructions, /T3 Code/); NodeAssert.match(instructions, /Codex harness/); NodeAssert.match(instructions, /as gpt-5\.3-codex with high reasoning effort/); @@ -267,7 +267,7 @@ describe("buildCodexDeveloperInstructions", () => { reasoningEffort: "medium", }); - NodeAssert.ok(instructions.startsWith(CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS)); + NodeAssert.ok(instructions.startsWith(codexPlanModeDeveloperInstructions(true))); NodeAssert.match(instructions, /as gpt-5\.3-codex with medium reasoning effort/); }); @@ -298,8 +298,8 @@ describe("buildCodexDeveloperInstructions", () => { describe("T3 browser developer instructions", () => { it("prefers the product-native preview tools in both collaboration modes", () => { for (const instructions of [ - CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS, - CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS, + codexDefaultModeDeveloperInstructions(true), + codexPlanModeDeveloperInstructions(true), ]) { NodeAssert.match(instructions, /t3-code/); NodeAssert.match(instructions, /preview_status/); @@ -307,6 +307,32 @@ describe("T3 browser developer instructions", () => { NodeAssert.match(instructions, /Do not switch to global browser skills/); } }); + + it("omits the browser block entirely when the preview tools are not attached", () => { + for (const instructions of [ + codexDefaultModeDeveloperInstructions(false), + codexPlanModeDeveloperInstructions(false), + ]) { + NodeAssert.doesNotMatch(instructions, /preview_status/); + NodeAssert.doesNotMatch(instructions, /preview_open/); + NodeAssert.doesNotMatch(instructions, /T3 Code collaborative browser/); + // Steering away from other browser automation must go with the tools; + // keeping it would leave the model talked out of its only option. + NodeAssert.doesNotMatch(instructions, /Do not switch to global browser skills/); + // The rest of the collaboration mode is untouched. + NodeAssert.match(instructions, //); + NodeAssert.match(instructions, /<\/collaboration_mode>/); + } + }); + + it("tracks the turn's MCP configuration rather than defaulting to on", () => { + const runtime = { model: "gpt-5.3-codex", reasoningEffort: "high" }; + NodeAssert.match(buildCodexDeveloperInstructions("default", runtime, true), /preview_open/); + NodeAssert.doesNotMatch( + buildCodexDeveloperInstructions("default", runtime, false), + /preview_open/, + ); + }); }); describe("hasConfiguredMcpServer", () => { diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.ts index 8f887c1b59..29bb992611 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts @@ -340,6 +340,7 @@ function buildCodexCollaborationMode(input: { readonly interactionMode?: ProviderInteractionMode; readonly model?: string; readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort; + readonly browserToolsAvailable?: boolean; }): EffectCodexSchema.V2TurnStartParams__CollaborationMode | undefined { if (input.interactionMode === undefined) { return undefined; @@ -351,10 +352,11 @@ function buildCodexCollaborationMode(input: { settings: { model, reasoning_effort: reasoningEffort, - developer_instructions: buildCodexDeveloperInstructions(input.interactionMode, { - model, - reasoningEffort, - }), + developer_instructions: buildCodexDeveloperInstructions( + input.interactionMode, + { model, reasoningEffort }, + input.browserToolsAvailable ?? true, + ), }, }; } @@ -371,6 +373,8 @@ export function buildTurnStartParams(input: { readonly serviceTier?: CodexServiceTier; readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort; readonly interactionMode?: ProviderInteractionMode; + /** Defaults to true so callers that predate the agent-access gate are unchanged. */ + readonly browserToolsAvailable?: boolean; }): Effect.Effect< CodexTurnStartParamsWithCollaborationMode, CodexErrors.CodexAppServerProtocolParseError @@ -391,6 +395,7 @@ export function buildTurnStartParams(input: { ...(input.interactionMode ? { interactionMode: input.interactionMode } : {}), ...(input.model ? { model: input.model } : {}), ...(input.effort ? { effort: input.effort } : {}), + browserToolsAvailable: input.browserToolsAvailable ?? true, }); return decodeCodexTurnStartParamsWithCollaborationMode({ @@ -1822,6 +1827,10 @@ export const makeCodexSessionRuntime = ( ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}), ...(input.effort ? { effort: input.effort } : {}), ...(input.interactionMode ? { interactionMode: input.interactionMode } : {}), + // Derived from the session's own MCP configuration rather than the + // setting, so the prompt describes the tools this turn actually + // has even if the setting changed after the session started. + browserToolsAvailable: hasConfiguredMcpServer(options.appServerArgs), }); const rawResponse = yield* client.raw.request("turn/start", params); const response = yield* decodeV2TurnStartResponse(rawResponse).pipe( diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index 2ac00873df..4974505d67 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -57,6 +57,7 @@ import * as ProviderEventLoggers from "./ProviderEventLoggers.ts"; import * as AnalyticsService from "../../telemetry/AnalyticsService.ts"; import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; import * as McpSessionRegistry from "../../mcp/McpSessionRegistry.ts"; +import * as ServerSettings from "../../serverSettings.ts"; const isModelSelection = Schema.is(ModelSelection); /** @@ -215,16 +216,52 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistry; const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory; + const serverSettings = yield* ServerSettings.ServerSettingsService; const runtimeEventPubSub = yield* PubSub.unbounded(); const nowIso = Effect.map(DateTime.now, DateTime.formatIso); + /** + * Attach the `t3-code` MCP server to the session that is about to start. + * + * This is the only place a credential is minted, so withholding one here is + * what disables agent browser access everywhere: every adapter already + * treats a missing session as "no MCP server", and the `/mcp` endpoint + * accepts nothing but tokens issued from this path. + */ + /** + * Deny on an unreadable settings file rather than letting the read failure + * escape: adding `ServerSettingsError` to `ProviderServiceError` would widen + * a union every caller handles, for a branch that only decides whether one + * optional toolset is attached. Denying is the safe direction — an explicit + * "off" silently becoming "on" would violate the user's stated choice, + * whereas the reverse costs an agent one toolset and is visible immediately. + */ + const agentBrowserAccessEnabled = serverSettings.getSettings.pipe( + Effect.map((settings) => settings.enableAgentBrowserAccess), + Effect.catch((cause) => + Effect.logWarning( + "Could not read server settings; withholding agent browser access for this session.", + { cause }, + ).pipe(Effect.as(false)), + ), + ); + const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) => - McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId }).pipe( - Effect.tap((credential) => - credential - ? Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config)) - : Effect.void, - ), - ); + Effect.gen(function* () { + if (!(yield* agentBrowserAccessEnabled)) { + // A stale session from before the toggle flipped would otherwise keep + // its tools for the rest of its life. + yield* Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId)); + return undefined; + } + const credential = yield* McpSessionRegistry.issueActiveMcpCredential({ + threadId, + providerInstanceId, + }); + if (credential) { + yield* Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config)); + } + return credential; + }); const clearMcpSession = (threadId: ThreadId) => McpSessionRegistry.revokeActiveMcpThread(threadId).pipe( Effect.tap(() => Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId))), diff --git a/apps/web/src/components/settings/IntegrationsSettings.tsx b/apps/web/src/components/settings/IntegrationsSettings.tsx index 1ffc7e3f3c..f3b773f7bc 100644 --- a/apps/web/src/components/settings/IntegrationsSettings.tsx +++ b/apps/web/src/components/settings/IntegrationsSettings.tsx @@ -10,6 +10,7 @@ import { DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW, DEFAULT_BROWSER_VIEWPORT, DEFAULT_PREVIEW_APPEARANCE, + DEFAULT_UNIFIED_SETTINGS, DEFAULT_PREVIEW_ZOOM_FACTOR, FILL_PREVIEW_VIEWPORT, PREVIEW_VIEWPORT_MAX_AREA, @@ -39,7 +40,11 @@ import { } from "../ui/select"; import { Switch } from "../ui/switch"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; -import { useClientSettings, useUpdatePrimarySettings } from "~/hooks/useSettings"; +import { + useClientSettings, + usePrimarySettings, + useUpdatePrimarySettings, +} from "~/hooks/useSettings"; import { SettingResetButton, @@ -350,6 +355,44 @@ function BrowserAppearanceSetting({ disabled }: { readonly disabled: boolean }) ); } +function AgentBrowserAccessSetting() { + const settings = usePrimarySettings(); + const updateSettings = useUpdatePrimarySettings(); + + return ( + + updateSettings({ + enableAgentBrowserAccess: DEFAULT_UNIFIED_SETTINGS.enableAgentBrowserAccess, + }) + } + /> + ) : null + } + control={ + + updateSettings({ enableAgentBrowserAccess: Boolean(checked) }) + } + aria-label="Allow agent browser access" + /> + } + /> + ); +} + function BrowserAutoShowFloatingPreviewSetting({ disabled }: { readonly disabled: boolean }) { const autoShow = useClientSettings((settings) => settings.browserAutoShowFloatingPreview); const updateSettings = useUpdatePrimarySettings(); @@ -425,6 +468,9 @@ export function IntegrationsSettingsPanel() { return ( + {/* Server-authoritative, so it stays editable on every client and sits + outside the block covering the desktop-only defaults. */} + {previewDefaultsDisabled ? ( {previewDefaults} ) : ( diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 83cf3de75d..e49f77a834 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -197,6 +197,12 @@ export const SETTINGS_SEARCH_ITEMS = [ title: "Providers", to: "/settings/providers", }, + { + id: "agent-browser-access", + title: "Agent browser access", + to: "/settings/integrations", + targetId: "browser", + }, { id: "browser-default-viewport", title: "Default browser viewport", diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 2410274f8f..143087b354 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -584,6 +584,18 @@ export const ServerSettings = Schema.Struct({ Schema.withDecodingDefault(Effect.succeed(false)), ), enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + /** + * Whether agents may drive the in-app preview browser. Turning this off + * withholds the MCP credential, so the `t3-code` server (and with it every + * `preview_*` tool) is never attached to a provider session, and the prompt + * text describing those tools is dropped along with them. The user's own + * browser panel is unaffected — this gates agent access only. + * + * Server-authoritative rather than client-local: tool injection and prompt + * construction both happen on the server, and the answer must not differ + * between a desktop window and a phone attached to the same server. + */ + enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), backgroundActivity: BackgroundActivitySettings, // Legacy flat fields retained for old settings files and old clients. New // consumers should resolve `backgroundActivity` instead. @@ -747,6 +759,7 @@ export const ServerSettingsPatch = Schema.Struct({ // Server settings enableLegacyTokenStreaming: Schema.optionalKey(Schema.Boolean), enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean), + enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean), backgroundActivity: Schema.optionalKey( Schema.Struct({ schemaVersion: Schema.optionalKey(Schema.Literal(1)),