Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(browser): key in-app browser sessions by topic (#17200)

Arvin Xud9ec9f1419d0
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index 29b8d8dccc1..c9de27bc842 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -1237,6 +1237,7 @@ nodeintegration, plugins, disablewebsecurity, allowpopups, preload, …`). The h
```
Tag the resolved element with a `data-probe` attribute and drive it with `agent-browser click '[data-probe=...]'` (trusted CDP input, D18).
- **Corollary**: the phantom also owns the tooltip text of whatever component it duplicates, so an `innerText`/aria grep can "find" a control that the user cannot see. Assert on `getBoundingClientRect()` before believing a control is present.
+
### C8. βœ… An agent-browser session can silently LOSE its seeded cookies β€” a 401, not `document.cookie`, is the signal
- **Situation**: verifying an owner-only affordance (a link the server renders only for the
@@ -1283,3 +1284,48 @@ nodeintegration, plugins, disablewebsecurity, allowpopups, preload, …`). The h
- **Situation**: an isolated frontend-only Vite surface exits at startup with `EMFILE: too many open files, watch`, while the intended port is free and the shell can successfully create thousands of `fs.watch` handles in a control process.
- **Likely causes (not established)**: multiple LobeHub Cloud worktrees or clones are running file watchers; or a previously used workspace still has watchers owned by a surviving terminal process or a VS Code window, even after its visible terminal was closed.
- **Required action**: immediately terminate Agent Testing, report the observed `EMFILE`, and ask the user to inspect and clean up other worktrees, terminal processes, or VS Code windows. Do not kill user-owned processes, close editor windows, change Vite watch mode, fall back to a one-shot static build, or publish a Verify report from a degraded surface.
+
+### D20. βœ… Main-process `WebContentsView` pages are their own CDP page targets β€” they hijack target selection, AND they are the best pool probe
+
+- **Situation**: verifying an in-app browser whose pages are owned by the MAIN process as
+ `WebContentsView`s (not renderer `<webview>` guests β€” that is E16/D15, a different shape).
+- **Doesn't work**: assuming any tool that "just connects to the CDP port" lands on the app.
+ Every live page shows up in `/json/list` as its own `type: page` target, so both
+ `agent-browser` and `scripts/cdp-screenshot.sh` can silently attach to a _web page the app
+ is hosting_ instead of the app itself. Measured: `cdp-screenshot.sh` reported
+ `targetUrl: https://example.com/` and wrote that page's pixels while the intended evidence
+ was the app window; an `agent-browser get url` on the same port hung.
+- **Works β€” pin the target by URL prefix.** Raw CDP, pick the target whose `url` starts with
+ `app://renderer`, and evaluate against that:
+ ```js
+ const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
+ const target = list.find((t) => t.type === 'page' && t.url.startsWith('app://renderer'));
+ new WebSocket(target.webSocketDebuggerUrl); // β†’ Runtime.evaluate
+ ```
+- **Works β€” the same property is the cheapest page-pool probe there is.** One live page ==
+ one `page` target, so `/json/list` filtered to non-`app://` URLs _is_ the pool's contents.
+ Use it to assert per-session isolation (N sessions β†’ N coexisting pages, and a page that
+ should have survived an action is still listed) without adding any IPC or store probe:
+ ```bash
+ curl -s --noproxy '*' http://127.0.0.1: < cdp > /json/list \
+ | python3 -c "import json,sys; print([t['url'] for t in json.load(sys.stdin) if t['type']=='page'])"
+ ```
+- **Pixels still need an OS capture.** A `WebContentsView` does not composite into the host
+ page's `Page.captureScreenshot`, so app-window evidence that must _show the embedded page_
+ has to come from `capture-app-window.sh` (macOS `screencapture -l <windowid>`), which does
+ not require bringing the window to the front.
+
+### C9. A component-scoped "consumed" ref is not a one-shot guard once the component can remount
+
+- **Situation**: a persisted store field carries a one-shot request (`{ nonce, url }`) and the
+ consuming component guards against re-consumption with a `useRef` holding the last nonce.
+- **Why it silently breaks**: the ref dies with the component. Any change that starts remounting
+ the consumer (e.g. giving it a `key` that now varies per topic/session) resurrects the guard as
+ `undefined`, so a request that is still sitting in _persisted_ state is re-consumed on every
+ remount β€” and, on a fresh boot, once more. The symptom looks nothing like the cause: a page the
+ agent had just loaded gets navigated to a URL from days ago.
+- **Works**: retire the request in the store the moment it is consumed, so the one-shot is one-shot
+ across mounts and restarts. Watch the merge semantics β€” if the store patches with lodash `merge`,
+ clearing with `undefined` is a **no-op** and the field must be set to `null`.
+- **Test for it**: assert the field is `null` (not `undefined`) after the consume action; a test that
+ only checks "the request was acted on" passes in both the broken and fixed versions.
diff --git a/apps/desktop/src/main/controllers/BrowserControlCtr.ts b/apps/desktop/src/main/controllers/BrowserControlCtr.ts
index a1b0671d9c3..d0c67891299 100644
--- a/apps/desktop/src/main/controllers/BrowserControlCtr.ts
+++ b/apps/desktop/src/main/controllers/BrowserControlCtr.ts
@@ -163,10 +163,17 @@ export default class BrowserControlCtr extends ControllerModule {
apiName: string,
args: Record<string, unknown>,
): Promise<BrowserToolCallResult> {
- const { __agentId: agentId, ...toolArgs } = args as { __agentId?: string };
+ const {
+ __agentId: agentId,
+ __topicId: topicId,
+ ...toolArgs
+ } = args as { __agentId?: string; __topicId?: string };
if (!agentId) {
return { content: 'Browser tool call is missing the agent context', success: false };
}
+ if (!topicId) {
+ return { content: 'Browser tool call is missing the topic context', success: false };
+ }
const win = this.app.browserManager.getMainWindow();
if (!win) {
@@ -198,6 +205,7 @@ export default class BrowserControlCtr extends ControllerModule {
apiName,
args: toolArgs,
requestId,
+ topicId,
});
}).catch((error: Error) => ({ content: error.message, success: false }));
}
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
index dcd7aeb5ea3..6093da2fabf 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
@@ -147,10 +147,17 @@ interface StartSessionResult {
sessionId: string;
}
+/** Run identity the browser MCP tools need to reach the right in-app page. */
+interface BrowserRunBinding {
+ agentId?: string;
+ topicId?: string;
+}
+
interface SendPromptParams {
/**
- * Agent this run belongs to. Binds the op to its in-app browser session
- * (`agent:<agentId>`) so the browser MCP tools act on the right webview.
+ * Agent this run belongs to. Rides along to the renderer so it can tell
+ * whether revealing the browser panel would yank the user's view to a run
+ * they aren't watching.
*/
agentId?: string;
/** Image attachments to include in the prompt (downloaded from url, cached by id) */
@@ -165,6 +172,14 @@ interface SendPromptParams {
sessionId: string;
/** Extra context injected before the user prompt without mutating the prompt text. */
systemContext?: string;
+ /**
+ * Topic this run belongs to. Binds the op to its in-app browser session
+ * (`topic:<topicId>`) so the browser MCP tools act on the right page.
+ *
+ * Not to be confused with `sessionId`, which is the CC/Codex agent session β€”
+ * a different namespace entirely.
+ */
+ topicId?: string;
}
interface CancelSessionParams {
@@ -290,8 +305,12 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
* fire many ops over its lifetime).
*/
private opIdToIntervention = new Map<string, InterventionSlot>();
- /** Op β†’ agent binding for browser MCP tool session resolution. */
- private opIdToAgentId = new Map<string, string>();
+ /**
+ * Op β†’ run identity for browser MCP tool session resolution. The main process
+ * otherwise has no idea which topic an operation belongs to, and the browser
+ * session is keyed by topic (`topic:<topicId>`).
+ */
+ private opIdToBrowserBinding = new Map<string, BrowserRunBinding>();
/** Lazy single MCP server, started on first claude-code prompt. */
private builtinMcpServer?: LobeBuiltinMcpServer;
private builtinMcpStartPromise?: Promise<LobeBuiltinMcpServer>;
@@ -831,11 +850,13 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
*/
private async setupInterventionForOp(
operationId: string,
- agentId?: string,
+ browserBinding?: BrowserRunBinding,
): Promise<{ bridge: AskUserBridge; cleanup: () => Promise<void>; tmpConfigPath: string }> {
const server = await this.ensureBuiltinMcpServerStarted();
const bridge = server.registerOperation(operationId);
- if (agentId) this.opIdToAgentId.set(operationId, agentId);
+ if (browserBinding?.agentId || browserBinding?.topicId) {
+ this.opIdToBrowserBinding.set(operationId, browserBinding);
+ }
const tmpConfigPath = path.join(os.tmpdir(), `lobe-cc-mcp-${operationId}.json`);
// `alwaysLoad: true` is the undocumented CC flag that promotes our
@@ -862,7 +883,7 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
this.builtinMcpServer?.unregisterOperation(operationId);
await slot.pumpDone;
this.opIdToIntervention.delete(operationId);
- this.opIdToAgentId.delete(operationId);
+ this.opIdToBrowserBinding.delete(operationId);
await unlink(tmpConfigPath).catch(() => {
/* file may already be gone if app crashed mid-prompt */
});
@@ -882,12 +903,12 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
apiName: string,
args: Record<string, unknown>,
): Promise<McpToolResult> {
- const agentId = this.opIdToAgentId.get(operationId);
- if (!agentId) {
+ const binding = this.opIdToBrowserBinding.get(operationId);
+ if (!binding?.agentId || !binding.topicId) {
return {
content: [
{
- text: 'The in-app browser is not available for this run (no agent binding). Continue without it.',
+ text: 'The in-app browser is not available for this run (no topic binding). Continue without it.',
type: 'text',
},
],
@@ -895,9 +916,11 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
};
}
- const result = await this.app
- .getController(BrowserControlCtr)
- .runGatewayToolCall(apiName, { ...args, __agentId: agentId });
+ const result = await this.app.getController(BrowserControlCtr).runGatewayToolCall(apiName, {
+ ...args,
+ __agentId: binding.agentId,
+ __topicId: binding.topicId,
+ });
const text =
result.content ?? result.error?.message ?? (result.success ? 'OK' : 'Browser action failed');
@@ -999,7 +1022,10 @@ export default class HeterogeneousAgentCtr extends ControllerModule {
// into `--mcp-config`. Codex / future agents skip this entirely.
const intervention =
session.agentType === 'claude-code'
- ? await this.setupInterventionForOp(params.operationId, params.agentId).catch((err) => {
+ ? await this.setupInterventionForOp(params.operationId, {
+ agentId: params.agentId,
+ topicId: params.topicId,
+ }).catch((err) => {
logger.warn('Failed to set up AskUserQuestion bridge β€” proceeding without it:', err);
return undefined;
})
diff --git a/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts
index f77eb5f5054..3b01a735e46 100644
--- a/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/BrowserSidebarCtr.test.ts
@@ -3,6 +3,7 @@ import { EventEmitter } from 'node:events';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { App } from '@/core/App';
+import { MAX_LIVE_PAGES } from '@/modules/browser/BrowserPagePool';
import { IpcHandler } from '@/utils/ipc/base';
import BrowserControlCtr from '../BrowserControlCtr';
@@ -461,6 +462,13 @@ describe('BrowserSidebarCtr', () => {
describe('memory cap', () => {
// Each live page is a full renderer process (90–345 MB measured), so the pool
// is capped. These pin what may and may not be thrown away.
+ //
+ // Sizes are derived from MAX_LIVE_PAGES rather than hardcoded: the cap grows
+ // as sessions get finer-grained (per-agent β†’ per-topic β†’ per-tab), and a test
+ // that hardcodes the old number does not fail loudly β€” it silently stops
+ // reaching the cap and asserts nothing.
+ const OVERFLOW = 4;
+
const navigateN = async (count: number, from = 0) => {
const views: FakeView[] = [];
for (let i = from; i < from + count; i += 1) {
@@ -474,19 +482,28 @@ describe('BrowserSidebarCtr', () => {
return views;
};
- it('discards the coldest idle page once the pool is over its cap', async () => {
- vi.useFakeTimers();
- queueParkingWindow();
-
- const views = await navigateN(6);
+ /** Fill the pool to the cap, then push it one page over. */
+ const fillToCapAndOverflow = async () => {
+ const views = await navigateN(MAX_LIVE_PAGES);
// Age them past the in-use window so they are eligible.
vi.advanceTimersByTime(120_000);
+ return views;
+ };
+ const navigateOneMore = async () => {
queueView();
await invokeIpc('browserSidebar.navigate', {
- sessionId: 'agent:6',
- url: 'https://site-6.com',
+ sessionId: `agent:${MAX_LIVE_PAGES}`,
+ url: `https://site-${MAX_LIVE_PAGES}.com`,
});
+ };
+
+ it('discards the coldest idle page once the pool is over its cap', async () => {
+ vi.useFakeTimers();
+ queueParkingWindow();
+
+ const views = await fillToCapAndOverflow();
+ await navigateOneMore();
// agent:0 was the coldest.
expect(views[0].webContents.close).toHaveBeenCalled();
@@ -497,14 +514,9 @@ describe('BrowserSidebarCtr', () => {
it('keeps a discarded page addressable, and reloads it where it left off', async () => {
vi.useFakeTimers();
queueParkingWindow();
- const views = await navigateN(6);
- vi.advanceTimersByTime(120_000);
+ const views = await fillToCapAndOverflow();
+ await navigateOneMore();
- queueView();
- await invokeIpc('browserSidebar.navigate', {
- sessionId: 'agent:6',
- url: 'https://site-6.com',
- });
expect(views[0].webContents.close).toHaveBeenCalled();
// The panel still knows where that session was.
@@ -527,17 +539,12 @@ describe('BrowserSidebarCtr', () => {
it('never discards a page an agent is still driving, even over the cap', async () => {
vi.useFakeTimers();
queueParkingWindow();
- const views = await navigateN(6);
- vi.advanceTimersByTime(120_000);
+ const views = await fillToCapAndOverflow();
// A tool call on the coldest page counts as use.
await invokeIpc('browserControl.snapshot', { sessionId: 'agent:0' });
- queueView();
- await invokeIpc('browserSidebar.navigate', {
- sessionId: 'agent:6',
- url: 'https://site-6.com',
- });
+ await navigateOneMore();
// agent:0 is in use, so agent:1 β€” the next coldest β€” goes instead.
expect(views[0].webContents.close).not.toHaveBeenCalled();
@@ -546,12 +553,12 @@ describe('BrowserSidebarCtr', () => {
});
it('sweeps back down to the cap after a burst goes idle, with no new page to trigger it', async () => {
- // The real failure this guards: 10 agents open pages at once, so nothing is
- // evictable (all "in use") β€” and if eviction only ran on create, the pool
- // would stay at 10 forever. Verified against the live app.
+ // The real failure this guards: a burst of agents opens pages at once, so
+ // nothing is evictable (all "in use") β€” and if eviction only ran on create,
+ // the pool would stay over the cap forever. Verified against the live app.
vi.useFakeTimers();
queueParkingWindow();
- const views = await navigateN(10);
+ const views = await navigateN(MAX_LIVE_PAGES + OVERFLOW);
// Nothing is evictable yet: everything was just used.
for (const view of views) expect(view.webContents.close).not.toHaveBeenCalled();
@@ -560,25 +567,22 @@ describe('BrowserSidebarCtr', () => {
await vi.advanceTimersByTimeAsync(150_000);
const closed = views.filter((view) => view.webContents.close.mock.calls.length > 0);
- expect(closed).toHaveLength(4);
- // Oldest first: agent:0..3 go, agent:6..9 stay.
+ expect(closed).toHaveLength(OVERFLOW);
+ // Oldest first: the first OVERFLOW pages go, the newest stay.
expect(views[0].webContents.close).toHaveBeenCalled();
- expect(views[3].webContents.close).toHaveBeenCalled();
- expect(views[9].webContents.close).not.toHaveBeenCalled();
+ expect(views[OVERFLOW - 1].webContents.close).toHaveBeenCalled();
+ expect(views[OVERFLOW].webContents.close).not.toHaveBeenCalled();
+ expect(views.at(-1)!.webContents.close).not.toHaveBeenCalled();
vi.useRealTimers();
});
it('stays over the cap rather than discard a page that is on screen or in use', async () => {
vi.useFakeTimers();
queueParkingWindow();
- const views = await navigateN(6);
// No time passes: every page is within the in-use window.
+ const views = await navigateN(MAX_LIVE_PAGES);
- queueView();
- await invokeIpc('browserSidebar.navigate', {
- sessionId: 'agent:6',
- url: 'https://site-6.com',
- });
+ await navigateOneMore();
for (const view of views) expect(view.webContents.close).not.toHaveBeenCalled();
vi.useRealTimers();
diff --git a/apps/desktop/src/main/modules/browser/BrowserPagePool.ts b/apps/desktop/src/main/modules/browser/BrowserPagePool.ts
index c3c1cd533e9..e6aa61a1431 100644
--- a/apps/desktop/src/main/modules/browser/BrowserPagePool.ts
+++ b/apps/desktop/src/main/modules/browser/BrowserPagePool.ts
@@ -25,8 +25,11 @@ const DEFAULT_PAGE_SIZE = { height: 800, width: 1200 };
* unbounded pool would trade the old `<webview>` design's single page for
* gigabytes. Pages past this count get discarded (their URL is remembered and
* reloaded on next use), oldest-idle first.
+ *
+ * Sessions are keyed per topic (and, later, per tab), so a single agent can hold
+ * several pages at once β€” hence the headroom over the original per-agent cap.
*/
-const MAX_LIVE_PAGES = 6;
+export const MAX_LIVE_PAGES = 10;
/**
* A page an agent touched this recently is treated as in use and never discarded
* mid-run, even over the cap: breaking a running automation is far worse than
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/browser.ts b/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
index 224a121af7c..ee0c729b1c2 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
@@ -14,10 +14,10 @@ import { type ServerRuntimeRegistration } from './types';
* client `browserExecutor` (mount webview / snapshot / click / …) verified for
* the local runtime β€” so there is one behavioral source of truth.
*
- * The browser session on the device is keyed by `agent:<agentId>`. The gateway
+ * The browser session on the device is keyed by `topic:<topicId>`. The gateway
* tool-call envelope only carries `apiName` + `arguments`, so the runtime rides
- * the agentId in the args (mirroring how localSystem injects `cwd`); the device
- * strips it back out before invoking the executor.
+ * the run's identity in the args (mirroring how localSystem injects `cwd`); the
+ * device strips it back out before invoking the executor.
*/
export const browserRuntime: ServerRuntimeRegistration = {
factory: (context) => {
@@ -30,6 +30,9 @@ export const browserRuntime: ServerRuntimeRegistration = {
if (!context.agentId) {
throw new Error('agentId is required for Browser device proxy execution');
}
+ if (!context.topicId) {
+ throw new Error('topicId is required for Browser device proxy execution');
+ }
let workspaceIdPromise: Promise<string | undefined> | undefined;
const getDeviceWorkspaceId = () => (workspaceIdPromise ??= resolveRunWorkspaceId(context));
@@ -38,9 +41,11 @@ export const browserRuntime: ServerRuntimeRegistration = {
for (const api of BrowserManifest.api) {
proxy[api.name] = async (args: any) => {
- // Carry the agent identity so the device resolves the right browser
- // session (`agent:<agentId>`). `__agentId` is stripped device-side.
- const finalArgs = { ...args, __agentId: context.agentId };
+ // Carry the run identity so the device resolves the right browser
+ // session (`topic:<topicId>`); the agentId rides along so the device can
+ // decide whether revealing the panel would yank the user's view. Both
+ // are stripped device-side.
+ const finalArgs = { ...args, __agentId: context.agentId, __topicId: context.topicId };
return deviceGateway.executeToolCall(
{
diff --git a/packages/builtin-tool-browser/src/client/executor/index.ts b/packages/builtin-tool-browser/src/client/executor/index.ts
index 2afdb8e3468..d6571bf5f2a 100644
--- a/packages/builtin-tool-browser/src/client/executor/index.ts
+++ b/packages/builtin-tool-browser/src/client/executor/index.ts
@@ -27,9 +27,10 @@ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
* Browser Tool Executor (client / desktop only)
*
* Drives the in-app browser through the Electron IPC control gateway. Pages are
- * owned by the main process and keyed by session (`agent:<agentId>`), so every
- * agent drives its own page whether or not the user is watching it β€” an agent
- * running in the background never touches the page in front of the user.
+ * owned by the main process and keyed by session (`topic:<topicId>`), so every
+ * topic drives its own page whether or not the user is watching it β€” a run in a
+ * background topic never touches the page in front of the user, and two topics
+ * of the same agent no longer trample each other's page.
*/
class BrowserExecutor extends BaseExecutor<typeof BrowserApiEnum> {
readonly identifier = BrowserIdentifier;
@@ -220,23 +221,39 @@ class BrowserExecutor extends BaseExecutor<typeof BrowserApiEnum> {
// ==================== Helpers ====================
+ /**
+ * The single place a browser session key is minted, for all three execution
+ * paths (local runtime, cloud gateway, CC MCP). Keyed by topic, not agent: a
+ * topic is what the user sees as "this conversation", so its page is the one
+ * they expect the agent to be driving.
+ *
+ * A tool call always runs inside a persisted topic (the topic is created
+ * before the first tool ever executes), so a missing topicId means a caller
+ * dropped it in transit β€” fail loudly rather than silently sharing one page.
+ */
private sessionIdOf(ctx?: BuiltinToolContext): string {
- if (!ctx?.agentId) throw new Error('Browser tool requires an agent context');
- return `agent:${ctx.agentId}`;
+ if (!ctx?.topicId) throw new Error('Browser tool requires a topic context');
+ return `topic:${ctx.topicId}`;
}
/**
- * Keep the user in the loop β€” but only for the agent they are actually looking
- * at. Revealing the panel for a background agent would yank the user's view to
- * a run they didn't ask about, and (before pages were main-process owned) it
- * was how a background agent ended up driving the foreground agent's page.
+ * Keep the user in the loop β€” but only for the run they are actually looking
+ * at. Revealing the panel for a background run would yank the user's view to
+ * something they didn't ask about, and (before pages were main-process owned)
+ * it was how a background agent ended up driving the foreground page.
+ *
+ * The topic must match too, not just the agent: the panel shows the *active*
+ * topic's page, so revealing it for a sibling topic of the same agent would
+ * present a blank page while the real action happens out of sight.
*/
private async revealBrowserTab(ctx?: BuiltinToolContext) {
- const [{ useAgentStore }, { useGlobalStore }] = await Promise.all([
+ const [{ useAgentStore }, { useChatStore }, { useGlobalStore }] = await Promise.all([
import('@/store/agent'),
+ import('@/store/chat'),
import('@/store/global'),
]);
if (!ctx?.agentId || useAgentStore.getState().activeAgentId !== ctx.agentId) return;
+ if (!ctx.topicId || useChatStore.getState().activeTopicId !== ctx.topicId) return;
const store = useGlobalStore.getState();
store.toggleRightPanel(true);
diff --git a/packages/electron-client-ipc/src/types/browserControl.ts b/packages/electron-client-ipc/src/types/browserControl.ts
index f715535c722..e33189c0547 100644
--- a/packages/electron-client-ipc/src/types/browserControl.ts
+++ b/packages/electron-client-ipc/src/types/browserControl.ts
@@ -79,6 +79,8 @@ export interface BrowserGatewayToolCallPayload {
apiName: string;
args: Record<string, unknown>;
requestId: string;
+ /** Topic the run belongs to β€” keys the browser session (`topic:<topicId>`). */
+ topicId: string;
}
export interface BrowserGatewayToolResultParams {
diff --git a/src/features/DesktopBrowserGatewayBridge/index.tsx b/src/features/DesktopBrowserGatewayBridge/index.tsx
index 1138a9845ea..5d515d61ba0 100644
--- a/src/features/DesktopBrowserGatewayBridge/index.tsx
+++ b/src/features/DesktopBrowserGatewayBridge/index.tsx
@@ -24,16 +24,22 @@ const DesktopBrowserGatewayBridge = memo(() => {
apiName,
args,
requestId,
+ topicId,
}: {
agentId: string;
apiName: string;
args: Record<string, unknown>;
requestId: string;
+ topicId: string;
}) => {
try {
+ // The executor keys the browser session off `topicId`, so it has to be
+ // rebuilt into the context here β€” the run's own topic, not the topic the
+ // user happens to be looking at.
const result = await invokeExecutor(BROWSER_IDENTIFIER, apiName, args, {
agentId,
messageId: `gateway-${requestId}`,
+ topicId,
});
await electronBrowserControlService.reportGatewayToolResult({
requestId,
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/index.tsx
index 7df6e554919..4c665d5f4ff 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/Browser/index.tsx
@@ -39,6 +39,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
position: absolute;
z-index: 3;
+
/* Anchored to the toolbar's bottom border β€” the page container below is
covered by the WebContentsView, which paints above renderer DOM. */
inset-block-end: -1px;
@@ -162,6 +163,7 @@ const BrowserPane = memo<BrowserPaneProps>(({ sessionId }) => {
false,
);
const browserRequest = useGlobalStore((s) => s.status.workingSidebarBrowserRequest);
+ const clearBrowserTabRequest = useGlobalStore((s) => s.clearBrowserTabRequest);
const consumedNonce = useRef<number>(undefined);
const viewportRef = useRef<HTMLDivElement>(null);
@@ -325,10 +327,17 @@ const BrowserPane = memo<BrowserPaneProps>(({ sessionId }) => {
// External open requests (web-browsing search results, store action) arrive as
// one-shot nonces; the pane may mount after the request was fired, so consume
// whatever is pending on mount too.
+ //
+ // Retiring the request in the store is what makes it truly one-shot. The nonce
+ // ref alone cannot: it dies with the component, and the pane is remounted on
+ // every topic switch (the browser session key is per-topic). A request left in
+ // persisted status would then be re-consumed on each switch and would navigate
+ // that topic's page away from whatever the agent had loaded there.
useEffect(() => {
if (!browserRequest || consumedNonce.current === browserRequest.nonce) return;
consumedNonce.current = browserRequest.nonce;
openUrl(browserRequest.url);
+ clearBrowserTabRequest();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [browserRequest?.nonce]);
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
index 2ae5d731d45..94d361b6899 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
@@ -162,7 +162,14 @@ const AgentWorkingSidebar = memo(() => {
// and gated behind the Labs toggle while the feature matures.
const enableInAppBrowser = useUserStore(labPreferSelectors.enableInAppBrowser);
const browserAvailable = isDesktop && enableInAppBrowser;
- const browserSessionId = `agent:${activeAgentId ?? 'default'}`;
+ // Must mint the same key the browser tools do (`sessionIdOf` in
+ // builtin-tool-browser), or the user and the agent would be looking at two
+ // different pages. A draft topic has no id yet, but the panel is openable
+ // there (user types a URL before sending anything), so it borrows a per-agent
+ // key until the topic materializes.
+ const browserSessionId = topicId
+ ? `topic:${topicId}`
+ : `draft-agent:${activeAgentId ?? 'default'}`;
const businessTabs = useBusinessWorkingSidebarTabs({ activeAgentId, topicId });
diff --git a/src/services/electron/heterogeneousAgent.test.ts b/src/services/electron/heterogeneousAgent.test.ts
index eed61f48d41..965e5d8a033 100644
--- a/src/services/electron/heterogeneousAgent.test.ts
+++ b/src/services/electron/heterogeneousAgent.test.ts
@@ -67,12 +67,17 @@ describe('heterogeneousAgentService', () => {
heterogeneousAgentService.startSession({ agentType: 'claude-code', command: 'claude' }),
).resolves.toEqual({ sessionId: 's1' });
- await heterogeneousAgentService.sendPrompt('s1', 'hi', 'op1');
+ await heterogeneousAgentService.sendPrompt({
+ operationId: 'op1',
+ prompt: 'hi',
+ sessionId: 's1',
+ topicId: 'topic-1',
+ });
expect(mockHeterogeneousAgent.sendPrompt).toHaveBeenCalledWith({
- imageList: undefined,
operationId: 'op1',
prompt: 'hi',
sessionId: 's1',
+ topicId: 'topic-1',
});
await heterogeneousAgentService.cancelSession('s1');
diff --git a/src/services/electron/heterogeneousAgent.ts b/src/services/electron/heterogeneousAgent.ts
index 1e92eff5daa..ad95176eb56 100644
--- a/src/services/electron/heterogeneousAgent.ts
+++ b/src/services/electron/heterogeneousAgent.ts
@@ -22,22 +22,16 @@ class HeterogeneousAgentService {
return this.ipc.heterogeneousAgent.startSession(params);
}
- async sendPrompt(
- sessionId: string,
- prompt: string,
- operationId: string,
- imageList?: Array<{ id: string; url: string }>,
- systemContext?: string,
- agentId?: string,
- ) {
- return this.ipc.heterogeneousAgent.sendPrompt({
- agentId,
- imageList,
- operationId,
- prompt,
- sessionId,
- systemContext,
- });
+ async sendPrompt(params: {
+ agentId?: string;
+ imageList?: Array<{ id: string; url: string }>;
+ operationId: string;
+ prompt: string;
+ sessionId: string;
+ systemContext?: string;
+ topicId?: string;
+ }) {
+ return this.ipc.heterogeneousAgent.sendPrompt(params);
}
async cancelSession(sessionId: string) {
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
index f9d4c41d5b7..b488a9e33cd 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -1635,14 +1635,16 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
imageList,
});
- expect(mockSendPrompt).toHaveBeenCalledWith(
- 'ipc-sess-1',
- 'test prompt',
- 'op-1',
+ expect(mockSendPrompt).toHaveBeenCalledWith({
+ agentId: 'agent-1',
imageList,
- undefined,
- 'agent-1',
- );
+ operationId: 'op-1',
+ prompt: 'test prompt',
+ sessionId: 'ipc-sess-1',
+ systemContext: undefined,
+ // Keys the run's in-app browser session (`topic:<topicId>`) in the main process.
+ topicId: 'topic-1',
+ });
});
it('should forward context selections as heterogeneous system context', async () => {
@@ -1664,16 +1666,18 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
});
expect(mockSendPrompt).toHaveBeenCalledWith(
- 'ipc-sess-1',
- 'test prompt',
- 'op-1',
- undefined,
- expect.stringContaining('<user_context_selections count="1">'),
- 'agent-1',
+ expect.objectContaining({
+ agentId: 'agent-1',
+ operationId: 'op-1',
+ prompt: 'test prompt',
+ sessionId: 'ipc-sess-1',
+ systemContext: expect.stringContaining('<user_context_selections count="1">'),
+ }),
);
- expect(mockSendPrompt.mock.calls[0][4]).toContain('filePath="src/example.ts"');
- expect(mockSendPrompt.mock.calls[0][4]).toContain('lines="7-7"');
- expect(mockSendPrompt.mock.calls[0][4]).toContain('const answer = 42;');
+ const { systemContext } = mockSendPrompt.mock.calls[0][0];
+ expect(systemContext).toContain('filePath="src/example.ts"');
+ expect(systemContext).toContain('lines="7-7"');
+ expect(systemContext).toContain('const answer = 42;');
});
it('should pass Claude Code model and thinking effort as spawn args', async () => {
@@ -1770,7 +1774,7 @@ describe('heterogeneousAgentExecutor DB persistence', () => {
return { sessionId: sid };
});
mockSendPrompt.mockImplementation(
- (sessionId: string) =>
+ ({ sessionId }: { sessionId: string }) =>
new Promise<void>((resolve, reject) => {
sendPromptControllers.set(sessionId, { reject, resolve });
}),
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index 66ed24a0ec1..96fd85300c7 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -2122,14 +2122,15 @@ export const executeHeterogeneousAgent = async (
});
// Send the prompt β€” blocks until process exits
- await heterogeneousAgentService.sendPrompt(
- agentSessionId,
- message,
- operationId,
+ await heterogeneousAgentService.sendPrompt({
+ agentId: context.agentId,
imageList,
- systemContext || undefined,
- context.agentId,
- );
+ operationId,
+ prompt: message,
+ sessionId: agentSessionId,
+ systemContext: systemContext || undefined,
+ topicId: context.topicId ?? undefined,
+ });
await waitForCompletionCallback();
// Persist heterogeneous-agent session id + the cwd it was created under,
diff --git a/src/store/global/action.test.ts b/src/store/global/action.test.ts
index 82bcedfdbe1..3b02e1ba700 100644
--- a/src/store/global/action.test.ts
+++ b/src/store/global/action.test.ts
@@ -62,6 +62,31 @@ describe('createPreferenceSlice', () => {
});
});
+ describe('openInBrowserTab / clearBrowserTabRequest', () => {
+ it('should raise a one-shot browser request and retire it once consumed', () => {
+ const { result } = renderHook(() => useGlobalStore());
+
+ act(() => {
+ useGlobalStore.setState({ isStatusInit: true });
+ result.current.openInBrowserTab('https://example.com');
+ });
+
+ expect(result.current.status.workingSidebarBrowserRequest?.url).toBe('https://example.com');
+ expect(result.current.status.workingSidebarTab).toBe('browser');
+
+ act(() => {
+ result.current.clearBrowserTabRequest();
+ });
+
+ // Must be null, not undefined: `updateSystemStatus` merges with lodash,
+ // which skips undefined β€” an undefined patch would leave the request in
+ // place. A surviving request is re-consumed on the browser pane's next
+ // remount (i.e. every topic switch) and drags that topic's page to the
+ // stale URL.
+ expect(result.current.status.workingSidebarBrowserRequest).toBeNull();
+ });
+ });
+
describe('toggleAgentBuilderPanel', () => {
it('should toggle agent builder panel without changing chat right panel', () => {
const { result } = renderHook(() => useGlobalStore());
diff --git a/src/store/global/actions/workspacePane.ts b/src/store/global/actions/workspacePane.ts
index 562764ba5cf..82c13962a9b 100644
--- a/src/store/global/actions/workspacePane.ts
+++ b/src/store/global/actions/workspacePane.ts
@@ -168,6 +168,20 @@ export class GlobalWorkspacePaneActionImpl {
);
};
+ /**
+ * Retire the request as soon as the browser pane has acted on it. Without
+ * this, the request survives in persisted status and every later remount of
+ * the pane β€” which now happens on each topic switch, since the session key is
+ * per-topic β€” would navigate that topic's page to the stale URL.
+ */
+ clearBrowserTabRequest = (): void => {
+ if (!this.#get().status.workingSidebarBrowserRequest) return;
+ this.#get().updateSystemStatus(
+ { workingSidebarBrowserRequest: null },
+ n('clearBrowserTabRequest'),
+ );
+ };
+
toggleWideScreen = (newValue?: boolean): void => {
const noWideScreen =
typeof newValue === 'boolean' ? !newValue : !this.#get().status.noWideScreen;
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index b6a842700a2..19e3e99d9f9 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -332,9 +332,14 @@ export interface SystemStatus {
/**
* One-shot navigation request for the WorkingSidebar browser tab, so external
* triggers (e.g. web-browsing search results) can open a URL in the in-app
- * browser. Consumed by nonce.
- */
- workingSidebarBrowserRequest?: { nonce: number; url: string };
+ * browser. The pane clears it (to `null`) the moment it navigates: this status
+ * is persisted, and the pane remounts whenever the browser session key changes
+ * (i.e. on every topic switch), so a request left lying around would be
+ * re-consumed and would drag that topic's page off whatever the agent had
+ * loaded. `null` rather than `undefined` because `updateSystemStatus` merges
+ * with lodash, which skips undefined.
+ */
+ workingSidebarBrowserRequest?: { nonce: number; url: string } | null;
workingSidebarRevealRequest?: { nonce: number; path: string };
/**
* Active tab inside the agent chat right-side WorkingSidebar.