Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): cindy_browser 跨 session 串扰——tool-call 时解析 agent session (#743)

Chris Zhang8ab86f08b97a
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts
index b4f195181e..baa61586db 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/codexHttpBridge.test.ts
@@ -51,6 +51,22 @@ async function readRpcResponse(resp: Response): Promise<unknown> {
return JSON.parse(eventPayload ?? text);
}
+/**
+ * Every JSON-RPC response in the reply, not just the first. A batched request
+ * comes back as one SSE `data:` event per response, so `readRpcResponse`
+ * (first event only) cannot see the whole batch.
+ */
+async function readAllRpcResponses(resp: Response): Promise<unknown[]> {
+ const text = await resp.text();
+ const payloads = text
+ .split(/\r?\n/)
+ .filter((line) => line.startsWith('data: '))
+ .map((line) => JSON.parse(line.slice('data: '.length)) as unknown);
+ if (payloads.length > 0) return payloads.flat();
+ const parsed = JSON.parse(text) as unknown;
+ return Array.isArray(parsed) ? parsed : [parsed];
+}
+
describe('codexHttpBridge', () => {
let bridge: CodexHttpBridge | null = null;
@@ -121,6 +137,380 @@ describe('codexHttpBridge', () => {
});
});
+ it('keeps the thread context when a batch sibling omits the thread id', async () => {
+ // Regression: a JSON-RPC batch carrying a notification (no
+ // params._meta.threadId) alongside a well-attributed tools/call used to
+ // collapse extractCodexThreadId() to undefined for the WHOLE batch, so the
+ // transport ran without runWithLiziMcpSessionContext. Providers reading the
+ // context (cindy_browser's __mcpSessionId) then fell back to host-side
+ // UI-focus inference — the cross-session routing bug, via batches.
+ bridge = await startCodexHttpBridge({
+ serverFactories: { cindy_test: createTestServer },
+ logger: noopLogger(),
+ });
+ bridge.registerThreadContext('thread-batch', {
+ agentKind: 'codex',
+ sessionId: 'session-batch',
+ workingDir: '/repo',
+ vendorOptions: {},
+ });
+
+ const baseHeaders = {
+ authorization: `Bearer ${bridge.token}`,
+ accept: 'application/json, text/event-stream',
+ 'content-type': 'application/json',
+ };
+ const initResp = await fetch(bridge.url('cindy_test'), {
+ method: 'POST',
+ headers: baseHeaders,
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'initialize',
+ params: {
+ protocolVersion: '2024-11-05',
+ capabilities: {},
+ clientInfo: { name: 'test-client', version: '1.0.0' },
+ },
+ }),
+ });
+ const mcpSessionId = initResp.headers.get('mcp-session-id');
+ expect(mcpSessionId).toBeTruthy();
+ await initResp.text();
+
+ const callResp = await fetch(bridge.url('cindy_test'), {
+ method: 'POST',
+ headers: { ...baseHeaders, 'mcp-session-id': mcpSessionId ?? '' },
+ body: JSON.stringify([
+ // Contextless sibling — legitimate per MCP, must be ignored here.
+ { jsonrpc: '2.0', method: 'notifications/progress', params: {} },
+ {
+ jsonrpc: '2.0',
+ id: 2,
+ method: 'tools/call',
+ params: {
+ name: 'current_session',
+ arguments: {},
+ _meta: { threadId: 'thread-batch' },
+ },
+ },
+ ]),
+ });
+
+ expect(callResp.status).toBe(200);
+ // 'no-session' here would mean the ALS context was dropped.
+ expect(await readRpcResponse(callResp)).toMatchObject({
+ id: 2,
+ result: { content: [{ type: 'text', text: 'session-batch' }] },
+ });
+ });
+
+ it('drops the thread context when a batched tool call itself lacks a thread id', async () => {
+ // The permissiveness above stops at tools/call: an unattributed tool call
+ // must NOT inherit a sibling's session. findBlockedToolCall fail-closes
+ // this shape only for servers with a pluginId, so this server (no pluginId)
+ // proves the guard also lives in extractCodexThreadId.
+ bridge = await startCodexHttpBridge({
+ serverFactories: { cindy_test: createTestServer },
+ logger: noopLogger(),
+ });
+ bridge.registerThreadContext('thread-batch', {
+ agentKind: 'codex',
+ sessionId: 'session-batch',
+ workingDir: '/repo',
+ vendorOptions: {},
+ });
+
+ const baseHeaders = {
+ authorization: `Bearer ${bridge.token}`,
+ accept: 'application/json, text/event-stream',
+ 'content-type': 'application/json',
+ };
+ const initResp = await fetch(bridge.url('cindy_test'), {
+ method: 'POST',
+ headers: baseHeaders,
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'initialize',
+ params: {
+ protocolVersion: '2024-11-05',
+ capabilities: {},
+ clientInfo: { name: 'test-client', version: '1.0.0' },
+ },
+ }),
+ });
+ const mcpSessionId = initResp.headers.get('mcp-session-id');
+ expect(mcpSessionId).toBeTruthy();
+ await initResp.text();
+
+ const callResp = await fetch(bridge.url('cindy_test'), {
+ method: 'POST',
+ headers: { ...baseHeaders, 'mcp-session-id': mcpSessionId ?? '' },
+ body: JSON.stringify([
+ {
+ jsonrpc: '2.0',
+ id: 2,
+ method: 'tools/call',
+ params: {
+ name: 'current_session',
+ arguments: {},
+ _meta: { threadId: 'thread-batch' },
+ },
+ },
+ {
+ jsonrpc: '2.0',
+ id: 3,
+ method: 'tools/call',
+ // No _meta.threadId — poisons the batch on purpose.
+ params: { name: 'current_session', arguments: {} },
+ },
+ ]),
+ });
+
+ expect(callResp.status).toBe(200);
+ const results = (await readAllRpcResponses(callResp)) as Array<{
+ id?: number;
+ result?: { content?: Array<{ text?: string }> };
+ }>;
+ expect(results.length).toBeGreaterThan(0);
+ // No response may report the sibling's session — the batch is unattributed.
+ for (const entry of results) {
+ expect(entry.result?.content?.[0]?.text).not.toBe('session-batch');
+ }
+ // And the well-formed call did run, just without a context.
+ expect(
+ results.find((entry) => entry.id === 2)?.result?.content?.[0]?.text,
+ ).toBe('no-session');
+ });
+
+ it('a sibling naming another thread cannot degrade a well-attributed call', async () => {
+ // Sibling attribution must never win over the tool call's own: otherwise a
+ // stray notification carrying some other threadId would strip the ALS
+ // context and re-open the UI-focus fallback.
+ bridge = await startCodexHttpBridge({
+ serverFactories: { cindy_test: createTestServer },
+ logger: noopLogger(),
+ });
+ for (const [threadId, sessionId] of [
+ ['thread-x', 'session-x'],
+ ['thread-y', 'session-y'],
+ ]) {
+ bridge.registerThreadContext(threadId!, {
+ agentKind: 'codex',
+ sessionId: sessionId!,
+ workingDir: '/repo',
+ vendorOptions: {},
+ });
+ }
+
+ const baseHeaders = {
+ authorization: `Bearer ${bridge.token}`,
+ accept: 'application/json, text/event-stream',
+ 'content-type': 'application/json',
+ };
+ const initResp = await fetch(bridge.url('cindy_test'), {
+ method: 'POST',
+ headers: baseHeaders,
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'initialize',
+ params: {
+ protocolVersion: '2024-11-05',
+ capabilities: {},
+ clientInfo: { name: 'test-client', version: '1.0.0' },
+ },
+ }),
+ });
+ const mcpSessionId = initResp.headers.get('mcp-session-id');
+ await initResp.text();
+
+ const callResp = await fetch(bridge.url('cindy_test'), {
+ method: 'POST',
+ headers: { ...baseHeaders, 'mcp-session-id': mcpSessionId ?? '' },
+ body: JSON.stringify([
+ // Notification pointing at a DIFFERENT registered thread.
+ {
+ jsonrpc: '2.0',
+ method: 'notifications/progress',
+ params: { _meta: { threadId: 'thread-y' } },
+ },
+ {
+ jsonrpc: '2.0',
+ id: 2,
+ method: 'tools/call',
+ params: {
+ name: 'current_session',
+ arguments: {},
+ _meta: { threadId: 'thread-x' },
+ },
+ },
+ ]),
+ });
+
+ expect(callResp.status).toBe(200);
+ expect(await readRpcResponse(callResp)).toMatchObject({
+ id: 2,
+ result: { content: [{ type: 'text', text: 'session-x' }] },
+ });
+ });
+
+ it('siblings disagreeing among themselves still cannot strip a call context', async () => {
+ // Two non-tool siblings naming DIFFERENT threads used to short-circuit the
+ // scan to undefined before the tools/call could claim the request — and
+ // hasAmbiguousThreadContext ignores non-tool messages, so nothing rejected
+ // it either: it just ran contextless, back to UI focus.
+ bridge = await startCodexHttpBridge({
+ serverFactories: { cindy_test: createTestServer },
+ logger: noopLogger(),
+ });
+ for (const [threadId, sessionId] of [
+ ['thread-x', 'session-x'],
+ ['thread-y', 'session-y'],
+ ['thread-z', 'session-z'],
+ ]) {
+ bridge.registerThreadContext(threadId!, {
+ agentKind: 'codex',
+ sessionId: sessionId!,
+ workingDir: '/repo',
+ vendorOptions: {},
+ });
+ }
+
+ const baseHeaders = {
+ authorization: `Bearer ${bridge.token}`,
+ accept: 'application/json, text/event-stream',
+ 'content-type': 'application/json',
+ };
+ const initResp = await fetch(bridge.url('cindy_test'), {
+ method: 'POST',
+ headers: baseHeaders,
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'initialize',
+ params: {
+ protocolVersion: '2024-11-05',
+ capabilities: {},
+ clientInfo: { name: 'test-client', version: '1.0.0' },
+ },
+ }),
+ });
+ const mcpSessionId = initResp.headers.get('mcp-session-id');
+ await initResp.text();
+
+ const callResp = await fetch(bridge.url('cindy_test'), {
+ method: 'POST',
+ headers: { ...baseHeaders, 'mcp-session-id': mcpSessionId ?? '' },
+ body: JSON.stringify([
+ {
+ jsonrpc: '2.0',
+ method: 'notifications/progress',
+ params: { _meta: { threadId: 'thread-y' } },
+ },
+ {
+ jsonrpc: '2.0',
+ method: 'notifications/progress',
+ params: { _meta: { threadId: 'thread-z' } },
+ },
+ {
+ jsonrpc: '2.0',
+ id: 2,
+ method: 'tools/call',
+ params: {
+ name: 'current_session',
+ arguments: {},
+ _meta: { threadId: 'thread-x' },
+ },
+ },
+ ]),
+ });
+
+ expect(callResp.status).toBe(200);
+ expect(await readRpcResponse(callResp)).toMatchObject({
+ id: 2,
+ result: { content: [{ type: 'text', text: 'session-x' }] },
+ });
+ });
+
+ it('fail-closes a batch whose tool calls name two different threads', async () => {
+ // Two registered+enabled threads coalesced into one batch: the per-call
+ // policy checks pass, and extractCodexThreadId rightly refuses to pick a
+ // context — but running contextless would route through the focused UI
+ // session. Refusing to pick must therefore mean refusing to run.
+ bridge = await startCodexHttpBridge({
+ serverFactories: { lizi_test: createTestServer },
+ pluginIdByServerName: { lizi_test: 'ssh' },
+ logger: noopLogger(),
+ });
+ for (const [threadId, sessionId] of [
+ ['thread-one', 'session-one'],
+ ['thread-two', 'session-two'],
+ ]) {
+ bridge.registerThreadContext(threadId!, {
+ agentKind: 'codex',
+ sessionId: sessionId!,
+ workingDir: '/repo',
+ // Plugin enabled on BOTH threads — findBlockedToolCall has no reason to
+ // block either call on its own.
+ vendorOptions: {},
+ });
+ }
+
+ const baseHeaders = {
+ authorization: `Bearer ${bridge.token}`,
+ accept: 'application/json, text/event-stream',
+ 'content-type': 'application/json',
+ };
+ const initResp = await fetch(bridge.url('lizi_test'), {
+ method: 'POST',
+ headers: baseHeaders,
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'initialize',
+ params: {
+ protocolVersion: '2024-11-05',
+ capabilities: {},
+ clientInfo: { name: 'test-client', version: '1.0.0' },
+ },
+ }),
+ });
+ const mcpSessionId = initResp.headers.get('mcp-session-id');
+ await initResp.text();
+
+ const callResp = await fetch(bridge.url('lizi_test'), {
+ method: 'POST',
+ headers: { ...baseHeaders, 'mcp-session-id': mcpSessionId ?? '' },
+ body: JSON.stringify(
+ ['thread-one', 'thread-two'].map((threadId, i) => ({
+ jsonrpc: '2.0',
+ id: i + 2,
+ method: 'tools/call',
+ params: {
+ name: 'current_session',
+ arguments: {},
+ _meta: { threadId },
+ },
+ })),
+ ),
+ });
+
+ expect(callResp.status).toBe(200);
+ const results = (await readAllRpcResponses(callResp)) as Array<{
+ id?: number;
+ result?: { isError?: boolean; content?: Array<{ text?: string }> };
+ }>;
+ expect(results).toHaveLength(2);
+ for (const entry of results) {
+ // Rejected outright — and in particular NOT executed contextless, which
+ // is what 'no-session' (or either session id) here would mean.
+ expect(entry.result?.isError).toBe(true);
+ expect(entry.result?.content?.[0]?.text).toMatch(/more than one session/);
+ }
+ });
+
it('blocks a tool call using the policy frozen on its Codex thread', async () => {
bridge = await startCodexHttpBridge({
serverFactories: { lizi_test: createTestServer },
diff --git a/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts b/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts
index 8d95a39819..67f2b6ae00 100644
--- a/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts
+++ b/apps/desktop/src/main/mcp-integrations/codexHttpBridge.ts
@@ -434,24 +434,46 @@ async function dispatchToTransport(opts: DispatchOpts): Promise<void> {
/** One policy-controlled tools/call that must not reach its MCP transport. */
interface BlockedToolCall {
- reason: 'disabled' | 'missing_thread_context';
+ reason: 'disabled' | 'missing_thread_context' | 'ambiguous_thread_context';
context?: LiziMcpSessionContext;
}
+/**
+ * `tools/call`s from two different Codex threads coalesced into one JSON-RPC
+ * batch. There is no single session context the request could run under, and
+ * `extractCodexThreadId` correctly refuses to pick one — but "no context" means
+ * the transport would run both calls with an EMPTY AsyncLocalStorage context,
+ * and every provider that reads it (cindy_browser's `__mcpSessionId`, …) would
+ * fall back to host-side UI-focus inference. That is the exact cross-session
+ * mis-routing this boundary exists to prevent, so refusing to pick has to mean
+ * refusing to run — fail closed, not fail open to whatever the user is looking
+ * at. (Both threads being registered and enabled means the per-call checks
+ * below cannot catch this shape.)
+ */
+function hasAmbiguousThreadContext(messages: unknown[]): boolean {
+ let seen: string | undefined;
+ for (const message of messages) {
+ if (!isToolCallMessage(message)) continue;
+ const threadId = extractCodexThreadIdFromMessage(message);
+ // Undefined is `missing_thread_context`'s job, not ambiguity's.
+ if (!threadId) continue;
+ if (seen && seen !== threadId) return true;
+ seen = threadId;
+ }
+ return false;
+}
+
function findBlockedToolCall(
body: unknown,
threadContextStore: ReturnType<typeof createCodexMcpThreadContextStore>,
pluginId: string,
): BlockedToolCall | undefined {
const messages = Array.isArray(body) ? body : [body];
+ if (hasAmbiguousThreadContext(messages)) {
+ return { reason: 'ambiguous_thread_context' };
+ }
for (const message of messages) {
- if (
- message === null ||
- typeof message !== 'object' ||
- (message as { method?: unknown }).method !== 'tools/call'
- ) {
- continue;
- }
+ if (!isToolCallMessage(message)) continue;
// Resolve each tools/call independently. Batch siblings such as MCP
// notifications may legitimately omit threadId and must not make a
// disabled call fail open.
@@ -480,7 +502,9 @@ function writeBlockedToolCallResponse(
): void {
const message = reason === 'disabled'
? `Built-in tool "${pluginId}" is disabled for this session. Enable it in Settings and start a new session to apply the change.`
- : `Built-in tool "${pluginId}" could not verify this session's tool policy. Start a new session and try again.`;
+ : reason === 'ambiguous_thread_context'
+ ? `Built-in tool "${pluginId}" received calls from more than one session in a single batch and cannot tell them apart. Retry the calls one session at a time.`
+ : `Built-in tool "${pluginId}" could not verify this session's tool policy. Start a new session and try again.`;
const disabledResult = (id: unknown) => ({
jsonrpc: '2.0',
id: id ?? null,
@@ -526,16 +550,74 @@ async function readJsonBody(
return JSON.parse(text);
}
+/**
+ * Resolve the single thread context this whole HTTP request should run under
+ * (used to wrap the transport in `runWithLiziMcpSessionContext`).
+ *
+ * Batch siblings such as MCP notifications legitimately omit
+ * `params._meta.threadId` — `findBlockedToolCall` already says so, and resolves
+ * each `tools/call` independently for exactly that reason. If such a sibling
+ * were allowed to collapse the whole batch to `undefined`, a perfectly
+ * well-attributed `tools/call` would run with NO AsyncLocalStorage context, and
+ * every built-in provider that reads it (cindy_browser's `__mcpSessionId`,
+ * cindy_android, …) would silently fall back to host-side UI-focus inference —
+ * i.e. the cross-session routing bug, just reachable only via batches. So
+ * threadId-less non-tool messages are skipped here.
+ *
+ * Still conservative where attribution actually matters:
+ * - a `tools/call` WITHOUT a threadId → `undefined`; never run an
+ * unattributed tool call under a sibling's session. (`findBlockedToolCall`
+ * fail-closes this shape too, but only for servers that carry a pluginId,
+ * so the guard has to live here as well.)
+ * - `tools/call`s naming two different threads → `undefined`; genuinely
+ * ambiguous, there is no single correct context to pick. For
+ * policy-controlled servers `findBlockedToolCall` turns that into an
+ * outright rejection (`ambiguous_thread_context`), because running such a
+ * batch contextless is what mis-routes it to the focused UI session.
+ *
+ * A `tools/call`'s own attribution ALWAYS wins over its siblings', including
+ * when the siblings disagree among themselves: nothing a non-tool message
+ * carries may degrade a well-attributed call to "no context", because
+ * `hasAmbiguousThreadContext` only inspects `tools/call`s and would not reject
+ * the request either — it would just run contextless, back to UI focus. Sibling
+ * ids therefore matter only when the request carries no tool call at all.
+ *
+ * Note this does change behaviour for tool-free requests: a threadId-less
+ * sibling no longer suppresses a sibling that does carry an id (previously ANY
+ * id-less message collapsed the result to `undefined`). Conflicting sibling ids
+ * still yield `undefined`. Tool-free requests invoke no tool, so nothing reads
+ * the context they run under; resolving it is simply closer to what the client
+ * actually declared.
+ */
function extractCodexThreadId(body: unknown): string | undefined {
const messages = Array.isArray(body) ? body : [body];
- let out: string | undefined;
+ let fromToolCall: string | undefined;
+ let fromSibling: string | undefined;
+ let siblingsDisagree = false;
for (const message of messages) {
const threadId = extractCodexThreadIdFromMessage(message);
- if (!threadId) return undefined;
- if (out && out !== threadId) return undefined;
- out = threadId;
+ if (isToolCallMessage(message)) {
+ if (!threadId) return undefined;
+ if (fromToolCall && fromToolCall !== threadId) return undefined;
+ fromToolCall = threadId;
+ continue;
+ }
+ if (!threadId) continue;
+ // Recorded, not returned: a sibling disagreement must not short-circuit the
+ // scan before a tools/call later in the batch gets to claim the request.
+ if (fromSibling && fromSibling !== threadId) siblingsDisagree = true;
+ fromSibling = threadId;
}
- return out;
+ if (fromToolCall) return fromToolCall;
+ return siblingsDisagree ? undefined : fromSibling;
+}
+
+function isToolCallMessage(message: unknown): boolean {
+ return (
+ message !== null &&
+ typeof message === 'object' &&
+ (message as { method?: unknown }).method === 'tools/call'
+ );
}
function extractCodexThreadIdFromMessage(message: unknown): string | undefined {
diff --git a/packages/lizi-mcps/src/__tests__/providersBrowserSession.test.ts b/packages/lizi-mcps/src/__tests__/providersBrowserSession.test.ts
new file mode 100644
index 0000000000..e93d07b7df
--- /dev/null
+++ b/packages/lizi-mcps/src/__tests__/providersBrowserSession.test.ts
@@ -0,0 +1,86 @@
+// cindy_browser provider 的 __mcpSessionId 注入契约:
+// - sessionId 必须在 tool-call 时解析(AsyncLocalStorage 优先,闭包 ctx 兜底),
+// 不能在 server factory 期绑死 —— Codex HTTP bridge 的 factory 阶段 ctx 是
+// 全局空值,绑死会让 Codex agent 的浏览器请求退回 host 端 UI-焦点推断,
+// tab 落进用户正在看的无关 session(跨会话串扰的主根因)。
+// - 两条路径都解析不到 sessionId 时原样透传请求(host 端 fallback 生效)。
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createLiziMcpProviders } from '../providers.js';
+import { runWithLiziMcpSessionContext } from '../session-context.js';
+
+// 捕获 createBrowserMcpServer 收到的 deps(含 wrap 后的 getRuntime),
+// 不真的起 McpServer。
+const capturedDeps: Array<{ getRuntime(): { call(req: unknown): unknown } }> = [];
+vi.mock('../browser/index.js', () => ({
+ createBrowserMcpServer: (deps: { getRuntime(): { call(req: unknown): unknown } }) => {
+ capturedDeps.push(deps);
+ return { __fake: 'mcp-server' };
+ },
+}));
+
+// capturedDeps 是模块级的,必须每条用例前清空:某条用例在 pop 之前就失败退出
+// 时会留下残条,后续用例 pop 到上一条的 deps → 顺序依赖 / 偶发失败。
+beforeEach(() => {
+ capturedDeps.length = 0;
+ vi.clearAllMocks();
+});
+
+function buildWrappedRuntime(factoryCtx: {
+ agentKind: string;
+ workingDir: string;
+ sessionId?: string;
+}) {
+ const innerCall = vi.fn(async (req: unknown) => ({ ok: true, req }));
+ const provider = createLiziMcpProviders({
+ browser: { getRuntime: () => ({ call: innerCall }) as never },
+ }).find((p) => p.name === 'cindy_browser');
+ expect(provider).toBeDefined();
+ provider!.toClaudeSdkConfig(factoryCtx);
+ // 恰好一条:配合 beforeEach 的清空,断言本次 factory 调用就是这条 deps 的来源,
+ // 而不是盲目 pop 一个可能来自别处的残留。
+ expect(capturedDeps).toHaveLength(1);
+ return { runtime: capturedDeps[0]!.getRuntime(), innerCall };
+}
+
+describe('cindy_browser provider — __mcpSessionId 注入', () => {
+ it('Claude 路径:factory ctx 自带 sessionId,直接注入', async () => {
+ const { runtime, innerCall } = buildWrappedRuntime({
+ agentKind: 'claude-code',
+ workingDir: '/w',
+ sessionId: 'claude-session',
+ });
+ await runtime.call({ action: 'status' });
+ expect(innerCall).toHaveBeenCalledWith({
+ action: 'status',
+ __mcpSessionId: 'claude-session',
+ });
+ });
+
+ it('Codex 路径:factory ctx 为空,tool-call 时从 AsyncLocalStorage 取', async () => {
+ const { runtime, innerCall } = buildWrappedRuntime({
+ agentKind: 'codex',
+ workingDir: '',
+ // Codex HTTP bridge factory 阶段没有 sessionId。
+ });
+ await runWithLiziMcpSessionContext(
+ { agentKind: 'codex', workingDir: '/w', sessionId: 'codex-thread-session' },
+ () => runtime.call({ action: 'open', url: 'https://x.test' }),
+ );
+ expect(innerCall).toHaveBeenCalledWith({
+ action: 'open',
+ url: 'https://x.test',
+ __mcpSessionId: 'codex-thread-session',
+ });
+ });
+
+ it('两条路径都无 sessionId 时原样透传(host 端 fallback 生效)', async () => {
+ const { runtime, innerCall } = buildWrappedRuntime({
+ agentKind: 'codex',
+ workingDir: '',
+ });
+ await runtime.call({ action: 'status' });
+ expect(innerCall).toHaveBeenCalledWith({ action: 'status' });
+ });
+});
diff --git a/packages/lizi-mcps/src/providers.ts b/packages/lizi-mcps/src/providers.ts
index 2da177944b..51e1f011a9 100644
--- a/packages/lizi-mcps/src/providers.ts
+++ b/packages/lizi-mcps/src/providers.ts
@@ -118,9 +118,14 @@ export function createLiziMcpProviders(
// `runtime.call(req)` 内部把 `__mcpSessionId` 挂到 req 上。vendored runtime
// 不识别这个字段会忽略;host 端 RsbWebviewBackend 优先读它,fallback 才走
// `getActiveSessionId`(给非 MCP 路径,如设置页直接调 status 用)。
+ //
+ // sessionId 必须在 **tool-call 时** 解析,不能只在 factory 期读闭包:Codex
+ // HTTP bridge 的 server factory 阶段 ctx 是全局空值(sessionId undefined),
+ // 真实 session 由 bridge 按 params._meta.threadId 在 tool-call 时写进
+ // AsyncLocalStorage。factory 期绑死闭包会让 Codex agent 的所有浏览器请求
+ // 退回 UI-焦点推断 → tab 落进用户正在看的无关 session。
toClaudeSdkConfig: (ctx) => {
const baseDeps = opts.browser!;
- const sessionId = ctx.sessionId;
return {
type: 'sdk',
name: 'cindy_browser',
@@ -128,16 +133,18 @@ export function createLiziMcpProviders(
...baseDeps,
getRuntime: () => {
const inner = baseDeps.getRuntime();
- if (!sessionId) return inner;
return {
- call: (req) =>
- inner.call({
+ call: (req) => {
+ const sessionId = resolveLiziMcpSessionContext(ctx).sessionId;
+ if (!sessionId) return inner.call(req);
+ return inner.call({
...req,
// Extra field on the request — vendored runtime ignores
// unknown keys, host RsbWebviewBackend reads it as the
// authoritative agent session.
__mcpSessionId: sessionId,
- } as typeof req),
+ } as typeof req);
+ },
};
},
}),