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(remote-agent): 修复经分享供应商无法分叉 Codex 任务

davidb1e0ef6a084b
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyGuestRoute.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyGuestRoute.test.ts
index 6a202475f9..d1b0c1818a 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyGuestRoute.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyGuestRoute.test.ts
@@ -179,6 +179,17 @@ describe('Codex proxy guard for shared-provider guests', () => {
expect(await statusOf(guard({ model: 'shared-model' }, ctx('/responses', { 'thread-id': 'owner-thread' })))).toBe(403);
});
+ // A guest Codex fork binds its proxy to the fork host's own key, which is never registered:
+ // thread/fork and rollback need no upstream, so every request must be refused, including
+ // control-plane GETs and headers that name another guest's registered thread.
+ it('refuses everything for a proxy bound to an unregistered guest session', async () => {
+ const guard = createCodexGuestRoutingGuard('shared-a', 'env-key', 'local-fork:00000000-0000-4000-8000-000000000000');
+ expect(await statusOf(guard({ model: 'shared-model' }, ctx('/responses')))).toBe(403);
+ expect(await statusOf(guard(undefined, ctx('/models', {}, 'GET')))).toBe(403);
+ expect(await statusOf(guard({ model: 'shared-model' }, ctx('/responses', { 'thread-id': 'guest-thread' })))).toBe(403);
+ expect(await statusOf(guard({ model: 'other-model' }, ctx(`${CODEX_CUSTOM_PROVIDER_ROUTE_ROOT}/0123456789abcdef0123/responses`)))).toBe(403);
+ });
+
it('routes an unresolved request straight to the default upstream only when that is the shared provider', async () => {
const gateway = createCodexGuestRoutingGuard('xd', 'env-key');
// 模型核对按 xd 的目录:这里的 fixture 没有 xd 模型,所以推理请求被拒;非推理路径只看默认路由。
diff --git a/apps/desktop/src/main/maker-ipc/fork.ts b/apps/desktop/src/main/maker-ipc/fork.ts
index c357fcec29..f86ffb549e 100644
--- a/apps/desktop/src/main/maker-ipc/fork.ts
+++ b/apps/desktop/src/main/maker-ipc/fork.ts
@@ -12,6 +12,7 @@
* fork 点支持 user / assistant 消息 (语义区别见 forkSessionAtMessage doc)。
*/
+import { remoteAgentErrorCode } from '@cindy/device-link';
import { ipcMain } from 'electron';
import { createLogger } from '../logger.js';
@@ -60,13 +61,18 @@ export function registerMakerForkIpc(): void {
return session;
} catch (error) {
const code = (error as { code?: string }).code;
- log.warn('side chat creation failed', { sourceSessionId: sid, code });
+ const message = error instanceof Error ? error.message : String(error);
+ log.warn('side chat creation failed', { sourceSessionId: sid, code, error: message });
if (code === 'SOURCE_NOT_FOUND') throwIpcError('NOT_FOUND', 'Source task is unavailable');
if (code === 'REMOTE_NOT_SUPPORTED') throwIpcError('UNSUPPORTED_CAPABILITY', 'Native history is on another execution host');
if (code === 'NO_PRIOR_ASSISTANT' || code === 'SOURCE_NEVER_RAN') {
throwIpcError('NO_PRIOR_ASSISTANT', 'Wait for the first completed reply');
}
- throwIpcError('PRECONDITION_FAILED', 'Could not create a side chat from this history');
+ // 远程 Agent 的错误码带给界面,让它说清是哪台电脑、什么原因(与分叉同一套提示)。
+ const remoteCode = remoteAgentErrorCode(message);
+ throwIpcError('PRECONDITION_FAILED', remoteCode
+ ? `[${remoteCode}] Could not create a side chat from this history`
+ : 'Could not create a side chat from this history');
}
});
ipcMain.handle(
diff --git a/apps/desktop/src/main/remote-agent/__tests__/groupRelayClaudeFork.e2e.test.ts b/apps/desktop/src/main/remote-agent/__tests__/groupRelayClaudeFork.e2e.test.ts
new file mode 100644
index 0000000000..195cab9f0b
--- /dev/null
+++ b/apps/desktop/src/main/remote-agent/__tests__/groupRelayClaudeFork.e2e.test.ts
@@ -0,0 +1,207 @@
+/**
+ * 受邀者经供应商组分叉真实 Claude Code 任务:
+ * 受邀者 G ⇄ 组所在电脑 O(createRemoteAgentHost + groupRelay) ⇄ 组内电脑 M(真 Claude Code + 假 Anthropic 网关)
+ * 三端同进程、经 JSON 往返模拟设备互联。
+ *
+ * Bug:组内电脑上原生分叉失败(如锚点不在会话记录里)时,报错被组内电脑写成「请求失败」、再被组所在电脑
+ * 换成「暂时不可用」,受邀者只看到「电脑连不上」,任何一端都查不到原因。groupRelay.test.ts 的分叉用假 Agent,
+ * 覆盖不到真实原生分叉与它的失败。最小失败输入:锚点 uuid 不在会话里。tier: e2e(真实 CLI);
+ * 依赖 apps/claude-code-bin,缺失时跳过。
+ */
+import fs from 'node:fs';
+import { createServer, type Server } from 'node:http';
+import os from 'node:os';
+import path from 'node:path';
+
+import { ClaudeCodeAgent, type AgentDeps, type AgentEvent, type Logger } from '@cindy/maker-core';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+
+import { RemoteAgentPoller } from '../controller/poller';
+import { RemoteAgentRunClient } from '../controller/runClient';
+import { createRemoteAgentHost, type GroupRelayMember, type RemoteAgentGroupRelayDeps } from '../host/runHost';
+import { hostedStartOptions } from '../host/service';
+
+const REPO = path.resolve(__dirname, '../../../../../..');
+const ARCH = `${process.platform}-${process.arch}`;
+const CLAUDE = path.join(REPO, 'apps', 'claude-code-bin', ARCH, process.platform === 'win32' ? 'claude.exe' : 'claude');
+const available = fs.existsSync(CLAUDE);
+const MODEL = 'claude-sonnet-4-5';
+const GUEST = 'share-guest-a';
+const OWNER_DEVICE = 'group-owner';
+const MEMBER: GroupRelayMember = { memberKey: 'device:member:gateway', agentDeviceId: 'member', providerId: 'shared-gateway', sameAccount: true };
+
+const noopLogger: Logger = {
+ trace: () => {}, debug: () => {}, info: () => {}, warn: () => {}, error: () => {}, fatal: () => {},
+ child: () => noopLogger,
+};
+
+function text(value: string): string {
+ return [
+ { type: 'message_start', message: { id: 'msg_text', type: 'message', role: 'assistant', model: MODEL, content: [], stop_reason: null, usage: { input_tokens: 10, output_tokens: 0 } } },
+ { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
+ { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: value } },
+ { type: 'content_block_stop', index: 0 },
+ { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 3 } },
+ { type: 'message_stop' },
+ ].map((event) => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join('');
+}
+
+const roundTrip = <T>(value: T): T => JSON.parse(JSON.stringify(value ?? null)) as T;
+
+describe.skipIf(!available)('a shared user forks a real Claude Code task through a provider group', () => {
+ let server: Server;
+ let endpoint = '';
+ let root = '';
+
+ beforeAll(async () => {
+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-cc-group-fork-')));
+ // Claude Code 读写 ~/.claude:指向临时目录,不碰开发机的真实配置。
+ const home = path.join(root, 'home');
+ fs.mkdirSync(home, { recursive: true });
+ for (const key of ['HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA']) vi.stubEnv(key, home);
+ server = createServer((req, res) => {
+ req.resume();
+ req.on('end', () => {
+ if (req.url?.includes('count_tokens')) {
+ res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ input_tokens: 100 }));
+ return;
+ }
+ res.writeHead(200, { 'content-type': 'text/event-stream' }).end(text('hello back'));
+ });
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ endpoint = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
+ });
+
+ afterAll(async () => {
+ vi.unstubAllEnvs();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ // 异步等待 CLI 退出并释放 Windows 文件句柄。
+ await fs.promises.rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
+ });
+
+ it('forks on the member that ran it, and reports a failed native fork as such instead of an unavailable computer', { timeout: 180_000 }, async () => {
+ const deps: AgentDeps = {
+ auth: {
+ getState: async () => ({ authenticated: true, identity: 'test', authSource: 'api-key' as const }),
+ triggerLogin: async () => ({ authenticated: true }),
+ logout: async () => {},
+ getAuthEnv: async () => ({ ANTHROPIC_API_KEY: 'fake-test-key' }),
+ },
+ runtimeConfig: { endpoint },
+ binaryPath: CLAUDE,
+ logger: noopLogger,
+ };
+ const agent = new ClaudeCodeAgent(deps);
+ const ownerWarnings: Array<{ msg: string; data?: unknown }> = [];
+ const memberWarnings: Array<{ msg: string; data?: unknown }> = [];
+ const member = createRemoteAgentHost({
+ isAgentAvailable: (kind) => kind === 'claude-code',
+ startHosted: (input) => agent.startSession(hostedStartOptions(input)),
+ forkHosted: (_kind, opts) => agent.forkSdkSession(opts),
+ isControllerAuthorized: () => true,
+ controllerTrust: () => 'owner',
+ providerAccess: { resolve: async (_kind, _model, providerId) => providerId ?? MEMBER.providerId, isAllowed: () => true },
+ bindGuestProviderRoute: async () => ({ routeToken: 'route', modelIds: [MODEL], release: () => {} }),
+ captureOwner: () => 'owner',
+ isOwnerCurrent: () => true,
+ runsRoot: path.join(root, 'member'),
+ log: { info: () => {}, warn: (msg, data) => { memberWarnings.push({ msg, data }); } },
+ });
+ // 组内电脑经设备互联回的错误:与生产 device-link/dispatch.ts 一样,不带远程 Agent 码的报错一律换成「请求失败」。
+ const poller = new RemoteAgentPoller(async (args) => {
+ try {
+ return roundTrip(await member.handle(OWNER_DEVICE, roundTrip(args[0])));
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ throw new Error(/^\[REMOTE_AGENT_[A-Z_]+\]/.test(message) ? message : '[REMOTE_AGENT_UNAVAILABLE] remote agent request failed');
+ }
+ });
+ let planned = false;
+ const relay = {
+ plan: vi.fn(async () => {
+ if (planned) return null;
+ planned = true;
+ return { kind: 'member' as const, ...MEMBER };
+ }),
+ connect: vi.fn(() => ({ invoke: poller.invoke, poller })),
+ noteStartFailure: vi.fn(() => false),
+ noteRunFailure: vi.fn(() => false),
+ trackRun: vi.fn(() => ({ setRunning: vi.fn(), release: vi.fn() })),
+ forget: vi.fn(async () => {}),
+ } satisfies RemoteAgentGroupRelayDeps;
+ const owner = createRemoteAgentHost({
+ // 组所在电脑不必装组内电脑的 Agent。
+ isAgentAvailable: () => false,
+ startHosted: async () => { throw new Error('the group owner does not run this task'); },
+ isControllerAuthorized: () => true,
+ controllerTrust: (controller) => (controller.startsWith('share-') ? 'guest' : 'owner'),
+ providerAccess: { resolve: async (_kind, _model, providerId) => providerId ?? 'shared', isAllowed: () => true },
+ bindGuestProviderRoute: async () => ({ routeToken: 'route', modelIds: [MODEL], release: () => {} }),
+ groupRelay: relay,
+ captureOwner: () => 'owner',
+ isOwnerCurrent: () => true,
+ runsRoot: path.join(root, 'owner'),
+ log: { info: () => {}, warn: (msg, data) => { ownerWarnings.push({ msg, data }); } },
+ });
+
+ const guestPoller = new RemoteAgentPoller(async (args) => roundTrip(await owner.handle(GUEST, roundTrip(args[0]))));
+ const events: AgentEvent[] = [];
+ let turnDone: () => void = () => {};
+ const turn = new Promise<void>((resolve) => { turnDone = resolve; });
+ let seq = 0;
+ const client = new RemoteAgentRunClient('11111111-1111-4111-8111-000000000001', guestPoller, {
+ onEvent: (event) => {
+ events.push(event as AgentEvent);
+ if ((event as AgentEvent).type === 'done') turnDone();
+ },
+ onState: () => undefined,
+ onRequest: async () => ({ type: 'callback', value: undefined }),
+ onWs: () => undefined,
+ onClosed: () => undefined,
+ }, () => `22222222-2222-4222-8222-${String(++seq).padStart(12, '0')}`);
+ const project = path.join(root, 'guest-project');
+ fs.mkdirSync(project, { recursive: true });
+ try {
+ const started = await client.open('claude-code', {
+ sessionId: 'guest-task',
+ virtualWorkspace: true,
+ options: { model: MODEL, permissionMode: 'bypassPermissions' },
+ workspace: { workingDir: project, platform: process.platform, shell: process.platform === 'win32' ? 'powershell' : 'zsh' },
+ projectFiles: [],
+ ancestorFiles: [],
+ personal: { files: [] },
+ mcpServers: [],
+ });
+ await client.call('send', [{ content: 'Say hello.', attachments: [] }, {}]);
+ await turn;
+ await client.close('close', 'navigation');
+ expect(events.some((event) => event.type === 'error')).toBe(false);
+ // 与控制端落库一致:助手文本行的 agentMeta.uuid 就是分叉锚点。
+ const anchor = events.filter((event) => event.type === 'text').map((event) => event.agentMeta?.uuid)
+ .find((uuid): uuid is string => typeof uuid === 'string');
+ expect(anchor).toBeDefined();
+ const fork = (upToMessageId: string, newSessionId: string) => owner.handle(GUEST, roundTrip({
+ op: 'fork', sourceSessionId: 'guest-task', newSessionId, agentKind: 'claude-code',
+ sourceSdkSessionId: started.id, model: MODEL, upToMessageId,
+ }));
+
+ await expect(fork(anchor!, 'guest-child')).resolves.toMatchObject({ newSdkSessionId: expect.any(String) });
+
+ const missing = '00000000-0000-4000-8000-000000000000';
+ const failure = await fork(missing, 'guest-child-2').then(() => null, (error: unknown) => error as Error);
+ expect(failure?.message).toMatch(/^\[REMOTE_AGENT_FORK_FAILED\]/);
+ // 原因只留在各自电脑的日志里:组内电脑记原生报错,组所在电脑记转发失败。
+ expect(memberWarnings).toEqual([expect.objectContaining({
+ msg: 'remote agent: native fork failed',
+ data: expect.objectContaining({ error: expect.objectContaining({ message: expect.stringContaining(missing) }) }),
+ })]);
+ expect(ownerWarnings).toEqual([expect.objectContaining({
+ msg: 'remote agent: a computer in the provider group could not fork the shared task',
+ data: expect.objectContaining({ error: expect.objectContaining({ code: 'REMOTE_AGENT_FORK_FAILED' }) }),
+ })]);
+ } finally {
+ for (const host of [owner, member]) { await host.abortAll(); host.dispose(); }
+ }
+ });
+});
diff --git a/apps/desktop/src/main/remote-agent/host/runHost.ts b/apps/desktop/src/main/remote-agent/host/runHost.ts
index fc421c443e..5ad70809d5 100644
--- a/apps/desktop/src/main/remote-agent/host/runHost.ts
+++ b/apps/desktop/src/main/remote-agent/host/runHost.ts
@@ -37,6 +37,7 @@ import {
parseRemoteAgentReply,
parseRemoteAgentRequest,
parseRemoteAgentForkResult,
+ remoteAgentErrorCode,
type RemoteAgentForkResult,
type RemoteAgentCaps,
type RemoteAgentErrorInfo,
@@ -2395,29 +2396,50 @@ export function createRemoteAgentHost(deps: RemoteAgentHostDeps) {
reshareKey: reshareKeyForGuest(controller),
}]));
} catch (error) {
+ // 受邀者只看到中性错误;原始原因只记在本机,组主人排查时才有据可查。
+ deps.log?.warn('remote agent: a computer in the provider group could not fork the shared task', {
+ to: member.agentDeviceId,
+ error: remoteAgentErrorInfo(error),
+ });
const safe = relayErrorForGuest(relayErrorInfoFrom(error)) ?? RELAY_UNAVAILABLE_ERROR;
fail(safe.code, safe.message);
}
} else {
- if (!deps.forkHosted || !deps.isAgentAvailable(request.agentKind)) {
+ if (!deps.forkHosted) {
fail('REMOTE_AGENT_PEER_TOO_OLD', 'update Cindy on the computer running this task to fork it');
}
+ if (!deps.isAgentAvailable(request.agentKind)) {
+ fail('REMOTE_AGENT_UNSUPPORTED', 'this agent is not available on the computer running this task');
+ }
const workingDir = path.join(shadowSessionRoot(controller, hostSessionId), 'fs', 'workspace', ...Array.from({ length: MAX_ANCESTOR_LEVELS }, () => 'p'));
// Idle runs may have released their shadow workspace; native history is retained.
const native = await withShadowLock(hostSessionId, async () => {
await fsp.mkdir(workingDir, { recursive: true });
assertProvider();
- return deps.forkHosted!(request.agentKind, {
- sourceSdkSessionId: request.sourceSdkSessionId,
- model: request.model,
- providerId: providerId ?? request.providerId,
- upToMessageId: request.upToMessageId,
- lastTurnId: request.lastTurnId,
- tailTurnsToDrop: request.tailTurnsToDrop,
- forkAtTimestampMs: request.forkAtTimestampMs,
- workingDir,
- ...(guest ? { hostedGuestHome: guestHomeFor(scope) } : {}),
- });
+ try {
+ return await deps.forkHosted!(request.agentKind, {
+ sourceSdkSessionId: request.sourceSdkSessionId,
+ model: request.model,
+ providerId: providerId ?? request.providerId,
+ upToMessageId: request.upToMessageId,
+ lastTurnId: request.lastTurnId,
+ tailTurnsToDrop: request.tailTurnsToDrop,
+ forkAtTimestampMs: request.forkAtTimestampMs,
+ workingDir,
+ ...(guest ? { hostedGuestHome: guestHomeFor(scope) } : {}),
+ });
+ } catch (error) {
+ if (error instanceof Error && /^\[REMOTE_AGENT_[A-Z_]+\]/.test(error.message)) throw error;
+ // Agent 自己的分叉失败不是「电脑连不上」:给专门的码,组转发也不会把它换成「暂时不可用」。
+ // 原始报错可能带本机路径,只记本机日志。
+ deps.log?.warn('remote agent: native fork failed', {
+ agentKind: request.agentKind,
+ error: remoteAgentErrorInfo(error),
+ });
+ // 包在 Agent 报错里的远程 Agent 码(如 CodexForkError 的 cause)保留下来,正文换成中性说明。
+ const nested = error instanceof Error ? remoteAgentErrorCode(error.message) : null;
+ fail(nested ?? 'REMOTE_AGENT_FORK_FAILED', 'the conversation could not be forked on the computer running this task');
+ }
});
result = {
newSdkSessionId: native.newSdkSessionId,
diff --git a/apps/desktop/src/renderer/features/right-sidebar/lib/openSideChatTab.ts b/apps/desktop/src/renderer/features/right-sidebar/lib/openSideChatTab.ts
index a07c6cf165..667a27ca1d 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/lib/openSideChatTab.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/lib/openSideChatTab.ts
@@ -12,7 +12,7 @@ import { createLogger } from '@/lib/logger';
import { createCoalescedRefresh } from '@/lib/coalescedRefresh';
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent, isDataOwnerPushCurrent } from '@/contexts/dataOwnerGeneration';
import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';
-import { isSharedTaskPeer } from '@cindy/device-link';
+import { isSharedTaskPeer, remoteAgentErrorCode } from '@cindy/device-link';
import type { Session } from '@/lib/ccAgent.types';
import { addTab, closeTab, ensureHydrated, getBucket, setActiveTab, subscribe } from '../store';
import { mergeSidebarWindowBack } from './mergeSidebarWindowBack';
@@ -182,11 +182,14 @@ export async function openSideChatTab(
return true;
} catch (error) {
const code = extractIpcError(error)?.code;
- log.warn('open failed', { code });
+ const remoteCode = remoteAgentErrorCode(error instanceof Error ? error.message : String(error));
+ log.warn('open failed', { code, remoteCode });
const key = code === 'NO_PRIOR_ASSISTANT' ? 'notReady'
: code === 'UNSUPPORTED_CAPABILITY' ? 'unsupported'
: code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED' ? 'updateHost' : 'failed';
- toast.error(i18n.t(`chat.sideChat.${key}`));
+ toast.error(key === 'failed' && remoteCode
+ ? i18n.t(`chat.remoteError.${remoteCode}`, { defaultValue: i18n.t('chat.sideChat.failed') })
+ : i18n.t(`chat.sideChat.${key}`));
return false;
}
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index eff8d2e207..2075ae0a96 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -12368,6 +12368,7 @@
"REMOTE_AGENT_UNSUPPORTED": "This Agent isn't available on the other computer. Install or sign in to it there, or pick another Agent.",
"REMOTE_AGENT_INVALID": "Something went wrong talking to the computer running the Agent. Try again; if it keeps happening, update Cindy on both computers.",
"REMOTE_AGENT_PROVIDER_NOT_ALLOWED": "That computer hasn’t granted you remote access to this provider or the selected model. Ask its owner to adjust access in Remote & Sharing, or pick another model.",
+ "REMOTE_AGENT_FORK_FAILED": "The computer running the Agent couldn’t start a new session from here. Try again, or try a different message.",
"REMOTE_AGENT_SHARE_PAUSED": "The owner has paused this share for you, so these models can’t be used until it’s resumed. Switch to another model to continue.",
"REMOTE_AGENT_SHARE_REMOVED": "This share is no longer available (the owner removed it or you left). Switch to another model to continue.",
"REMOTE_AGENT_SHARE_UNAVAILABLE": "The shared provider is temporarily unavailable. The owner's computer may be offline, or sharing is turned off for now. Try again later, or switch to another model to continue.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index ef86e6424f..7335ccf27e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -12329,6 +12329,7 @@
"REMOTE_AGENT_UNSUPPORTED": "相手のパソコンではこの Agent を使えません。そのパソコンでインストールまたはサインインするか、別の Agent を選んでください。",
"REMOTE_AGENT_INVALID": "Agent を実行しているパソコンとの通信でエラーが発生しました。もう一度お試しください。続く場合は両方のパソコンの Cindy を最新版に更新してください。",
"REMOTE_AGENT_PROVIDER_NOT_ALLOWED": "そのパソコンでは、このプロバイダーまたは選択したモデルのリモート利用が許可されていません。提供者に「リモートと共有」で利用範囲を変更してもらうか、別のモデルを選んでください。",
+ "REMOTE_AGENT_FORK_FAILED": "Agent を実行しているパソコンで、ここから新しいセッションを始められませんでした。もう一度試すか、別のメッセージでお試しください。",
"REMOTE_AGENT_SHARE_PAUSED": "共有した人があなたへの共有を一時停止したため、再開されるまでこれらのモデルは使えません。別のモデルに切り替えて続けられます。",
"REMOTE_AGENT_SHARE_REMOVED": "この共有は利用できなくなりました(共有した人が削除したか、あなたが退出しました)。別のモデルに切り替えて続けられます。",
"REMOTE_AGENT_SHARE_UNAVAILABLE": "共有されたプロバイダーは一時的に利用できません。共有した人のパソコンがオフラインか、共有が一時的にオフになっている可能性があります。後でもう一度試すか、別のモデルに切り替えて続けられます。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index e0bdf41b61..993a1a499d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -12329,6 +12329,7 @@
"REMOTE_AGENT_UNSUPPORTED": "상대 컴퓨터에서는 이 Agent를 사용할 수 없습니다. 그 컴퓨터에서 설치하거나 로그인한 뒤 다시 시도하거나, 다른 Agent를 선택하세요.",
"REMOTE_AGENT_INVALID": "Agent를 실행하는 컴퓨터와 통신하는 중 오류가 발생했습니다. 다시 시도하고, 계속되면 두 컴퓨터의 Cindy를 모두 최신 버전으로 업데이트하세요.",
"REMOTE_AGENT_PROVIDER_NOT_ALLOWED": "그 컴퓨터에서 이 제공자 또는 선택한 모델의 원격 사용을 허용하지 않았습니다. 제공자에게 원격 및 공유에서 사용 범위를 조정해 달라고 요청하거나 다른 모델을 선택하세요.",
+ "REMOTE_AGENT_FORK_FAILED": "Agent를 실행하는 컴퓨터에서 여기서 새 세션을 시작하지 못했습니다. 다시 시도하거나 다른 메시지로 시도해 주세요.",
"REMOTE_AGENT_SHARE_PAUSED": "공유한 사람이 나에 대한 공유를 일시 중지해서 재개될 때까지 이 모델을 사용할 수 없습니다. 다른 모델로 바꿔 계속할 수 있습니다.",
"REMOTE_AGENT_SHARE_REMOVED": "이 공유는 더 이상 사용할 수 없습니다(공유한 사람이 삭제했거나 내가 나갔습니다). 다른 모델로 바꿔 계속할 수 있습니다.",
"REMOTE_AGENT_SHARE_UNAVAILABLE": "공유된 제공자를 일시적으로 사용할 수 없습니다. 공유한 사람의 컴퓨터가 오프라인이거나 공유가 잠시 꺼져 있을 수 있습니다. 나중에 다시 시도하거나 다른 모델로 바꿔 계속할 수 있습니다.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 751df5ec8e..5f2871767a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -12329,6 +12329,7 @@
"REMOTE_AGENT_UNSUPPORTED": "那台电脑上这个 Agent 不可用。在那台电脑上安装或登录后再试,或换一个 Agent。",
"REMOTE_AGENT_INVALID": "和运行 Agent 的电脑通信出错。请重试;如果一直出现,请把两台电脑上的 Cindy 都更新到最新版。",
"REMOTE_AGENT_PROVIDER_NOT_ALLOWED": "那台电脑未向你开放这个供应商或所选模型。请让电脑主人在「远程与分享」中调整开放范围,或换一个模型。",
+ "REMOTE_AGENT_FORK_FAILED": "运行 Agent 的电脑没能从这里开启新任务。请重试,或换一条消息再试。",
"REMOTE_AGENT_SHARE_PAUSED": "对方已暂停对你的分享,恢复前不能使用这些模型。可以换成其他模型继续。",
"REMOTE_AGENT_SHARE_REMOVED": "这个分享已不可用(对方删除了分享或你已退出)。可以换成其他模型继续。",
"REMOTE_AGENT_SHARE_UNAVAILABLE": "分享的供应商暂时不可用:对方电脑可能不在线,或对方暂时关闭了分享。可以稍后再试,或换成其他模型继续。",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 8f666862f1..fe5e664322 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -12328,6 +12328,7 @@
"REMOTE_AGENT_UNSUPPORTED": "那臺電腦上這個 Agent 無法使用。在那臺電腦上安裝或登入後再試,或換一個 Agent。",
"REMOTE_AGENT_INVALID": "與執行 Agent 的電腦通訊時出錯。請重試;如果持續出現,請把兩臺電腦上的 Cindy 都更新到最新版。",
"REMOTE_AGENT_PROVIDER_NOT_ALLOWED": "那臺電腦未向你開放這個供應商或所選模型。請讓電腦主人在「遠端與分享」中調整開放範圍,或換一個模型。",
+ "REMOTE_AGENT_FORK_FAILED": "執行 Agent 的電腦沒能從這裡開啟新任務。請重試,或換一則訊息再試。",
"REMOTE_AGENT_SHARE_PAUSED": "對方已暫停對你的分享,恢復前不能使用這些模型。可以換成其他模型繼續。",
"REMOTE_AGENT_SHARE_REMOVED": "這個分享已無法使用(對方刪除了分享或你已退出)。可以換成其他模型繼續。",
"REMOTE_AGENT_SHARE_UNAVAILABLE": "分享的供應商暫時無法使用:對方電腦可能不在線,或對方暫時關閉了分享。可以稍後再試,或換成其他模型繼續。",
diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index a1a667195f..3f5bf5d6e2 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -623,6 +623,7 @@
"REMOTE_AGENT_UNSUPPORTED": "This Agent isn't available on the other computer. Install or sign in to it there, or pick another Agent.",
"REMOTE_AGENT_INVALID": "Something went wrong talking to the computer running the Agent. Try again; if it keeps happening, update Cindy on both computers.",
"REMOTE_AGENT_PROVIDER_NOT_ALLOWED": "That computer hasn’t allowed remote use of this provider. On that computer, turn on “Allow remote use” in Settings → Providers, or pick another model.",
+ "REMOTE_AGENT_FORK_FAILED": "The computer running the Agent couldn’t start a new session from here. Try again, or try a different message.",
"REMOTE_AGENT_SHARE_PAUSED": "The owner has paused this share for you, so these models can’t be used until it’s resumed. Switch to another model to continue.",
"REMOTE_AGENT_SHARE_REMOVED": "This share is no longer available (the owner removed it or you left). Switch to another model to continue.",
"REMOTE_AGENT_SHARE_UNAVAILABLE": "The shared provider is temporarily unavailable. The owner's computer may be offline, or sharing is turned off for now. Try again later, or switch to another model to continue."
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index 82121080f1..f5557db0fc 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -623,6 +623,7 @@
"REMOTE_AGENT_UNSUPPORTED": "相手のパソコンではこの Agent を使えません。そのパソコンでインストールまたはサインインするか、別の Agent を選んでください。",
"REMOTE_AGENT_INVALID": "Agent を実行しているパソコンとの通信でエラーが発生しました。もう一度お試しください。続く場合は両方のパソコンの Cindy を最新版に更新してください。",
"REMOTE_AGENT_PROVIDER_NOT_ALLOWED": "そのパソコンでは、このプロバイダーのリモート利用が許可されていません。そのパソコンの「設定 → モデルプロバイダー」で「リモート利用を許可」をオンにするか、別のモデルを選んでください。",
+ "REMOTE_AGENT_FORK_FAILED": "Agent を実行しているパソコンで、ここから新しいセッションを始められませんでした。もう一度試すか、別のメッセージでお試しください。",
"REMOTE_AGENT_SHARE_PAUSED": "共有した人があなたへの共有を一時停止したため、再開されるまでこれらのモデルは使えません。別のモデルに切り替えて続けられます。",
"REMOTE_AGENT_SHARE_REMOVED": "この共有は利用できなくなりました(共有した人が削除したか、あなたが退出しました)。別のモデルに切り替えて続けられます。",
"REMOTE_AGENT_SHARE_UNAVAILABLE": "共有されたプロバイダーは一時的に利用できません。共有した人のパソコンがオフラインか、共有が一時的にオフになっている可能性があります。後でもう一度試すか、別のモデルに切り替えて続けられます。"
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index d861d3fb6c..edbe6d6abb 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -619,6 +619,7 @@
"REMOTE_AGENT_UNSUPPORTED": "상대 컴퓨터에서는 이 Agent를 사용할 수 없습니다. 그 컴퓨터에서 설치하거나 로그인한 뒤 다시 시도하거나, 다른 Agent를 선택하세요.",
"REMOTE_AGENT_INVALID": "Agent를 실행하는 컴퓨터와 통신하는 중 오류가 발생했습니다. 다시 시도하고, 계속되면 두 컴퓨터의 Cindy를 모두 최신 버전으로 업데이트하세요.",
"REMOTE_AGENT_PROVIDER_NOT_ALLOWED": "그 컴퓨터에서 이 제공자의 원격 사용을 허용하지 않았습니다. 그 컴퓨터의 설정 → 모델 제공자에서 원격 사용 허용을 켜거나 다른 모델을 선택하세요.",
+ "REMOTE_AGENT_FORK_FAILED": "Agent를 실행하는 컴퓨터에서 여기서 새 세션을 시작하지 못했습니다. 다시 시도하거나 다른 메시지로 시도해 주세요.",
"REMOTE_AGENT_SHARE_PAUSED": "공유한 사람이 나에 대한 공유를 일시 중지해서 재개될 때까지 이 모델을 사용할 수 없습니다. 다른 모델로 바꿔 계속할 수 있습니다.",
"REMOTE_AGENT_SHARE_REMOVED": "이 공유는 더 이상 사용할 수 없습니다(공유한 사람이 삭제했거나 내가 나갔습니다). 다른 모델로 바꿔 계속할 수 있습니다.",
"REMOTE_AGENT_SHARE_UNAVAILABLE": "공유된 제공자를 일시적으로 사용할 수 없습니다. 공유한 사람의 컴퓨터가 오프라인이거나 공유가 잠시 꺼져 있을 수 있습니다. 나중에 다시 시도하거나 다른 모델로 바꿔 계속할 수 있습니다."
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index 92ae324ec6..8cfa21b20d 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -619,6 +619,7 @@
"REMOTE_AGENT_UNSUPPORTED": "那台电脑上这个 Agent 不可用。在那台电脑上安装或登录后再试,或换一个 Agent。",
"REMOTE_AGENT_INVALID": "和运行 Agent 的电脑通信出错。请重试;如果一直出现,请把两台电脑上的 Cindy 都更新到最新版。",
"REMOTE_AGENT_PROVIDER_NOT_ALLOWED": "那台电脑没有允许远程调用这个供应商。请在那台电脑的「设置 → 模型供应商」里打开「允许被远程调用」,或换一个模型。",
+ "REMOTE_AGENT_FORK_FAILED": "运行 Agent 的电脑没能从这里开启新任务。请重试,或换一条消息再试。",
"REMOTE_AGENT_SHARE_PAUSED": "对方已暂停对你的分享,恢复前不能使用这些模型。可以换成其他模型继续。",
"REMOTE_AGENT_SHARE_REMOVED": "这个分享已不可用(对方删除了分享或你已退出)。可以换成其他模型继续。",
"REMOTE_AGENT_SHARE_UNAVAILABLE": "分享的供应商暂时不可用:对方电脑可能不在线,或对方暂时关闭了分享。可以稍后再试,或换成其他模型继续。"
diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.json
index 3479ab4794..9e2bfdfa64 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/session.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json
@@ -623,6 +623,7 @@
"REMOTE_AGENT_UNSUPPORTED": "那臺電腦上這個 Agent 無法使用。在那臺電腦上安裝或登入後再試,或換一個 Agent。",
"REMOTE_AGENT_INVALID": "與執行 Agent 的電腦通訊時出錯。請重試;如果持續出現,請把兩臺電腦上的 Cindy 都更新到最新版。",
"REMOTE_AGENT_PROVIDER_NOT_ALLOWED": "那臺電腦沒有允許遠端呼叫這個供應商。請在那臺電腦的「設定 → 模型供應商」裡開啟「允許遠端呼叫」,或換一個模型。",
+ "REMOTE_AGENT_FORK_FAILED": "執行 Agent 的電腦沒能從這裡開啟新任務。請重試,或換一則訊息再試。",
"REMOTE_AGENT_SHARE_PAUSED": "對方已暫停對你的分享,恢復前不能使用這些模型。可以換成其他模型繼續。",
"REMOTE_AGENT_SHARE_REMOVED": "這個分享已無法使用(對方刪除了分享或你已退出)。可以換成其他模型繼續。",
"REMOTE_AGENT_SHARE_UNAVAILABLE": "分享的供應商暫時無法使用:對方電腦可能不在線,或對方暫時關閉了分享。可以稍後再試,或換成其他模型繼續。"
diff --git a/packages/device-link/src/remoteAgent.ts b/packages/device-link/src/remoteAgent.ts
index 41f2de2287..0de88fa84f 100644
--- a/packages/device-link/src/remoteAgent.ts
+++ b/packages/device-link/src/remoteAgent.ts
@@ -89,6 +89,8 @@ export const REMOTE_AGENT_ERROR_CODES = [
'REMOTE_AGENT_PROVIDER_NOT_ALLOWED',
// 供应商组转来的受邀者任务:这台电脑的主人没有同意这个受邀者经组使用(只回给打开时带了 reshareKey 的组所在电脑)。
'REMOTE_AGENT_RESHARE_NOT_ALLOWED',
+ // 那台电脑上的 Agent 分叉原生历史失败(电脑本身在线)。旧版控制端不认识,按通用分叉失败提示。
+ 'REMOTE_AGENT_FORK_FAILED',
] as const;
export type RemoteAgentErrorCode = (typeof REMOTE_AGENT_ERROR_CODES)[number];
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index cb7bc0db4d..b6e7472837 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -24394,13 +24394,18 @@ describe('CodexAgent native fork anchor events', () => {
describe('CodexAgent.forkSdkSession', () => {
// Review #6563: exercise createHost/spawn configuration, which a mocked getHost
// bypasses. A shared subscription needs the same scoped proxy as a guest turn.
+ // The fake mirrors Desktop's guest gate (maker-host prepareCodexExtraSpawnConfig): a shared-provider
+ // host also needs a guest session. Forks used to omit it, so every Codex fork through a shared
+ // provider failed with "requires its own session-bound scoped proxy".
it('starts shared-subscription forks with their own proxy scope and retires it', async () => {
MockCodexTransport.userAgent = 'mock-codex/0.153.4';
const home = await fs.mkdtemp(path.join(os.tmpdir(), 'codex-guest-fork-'));
tempRoots.push(home);
const onHostRetired = vi.fn(async () => {});
const prepare = vi.fn<NonNullable<AgentDeps['prepareCodexExtraSpawnConfig']>>(async (_providers, ctx) => {
- if (!ctx?.accountHostKey) throw Object.assign(new Error('shared-provider Codex host requires its own scoped proxy'), { codexSpawnConfigFatal: true });
+ if (ctx?.deviceHostedGuestProviderId !== undefined && (!ctx.deviceHostedGuestSessionId?.trim() || !ctx.accountHostKey)) {
+ throw Object.assign(new Error('shared-provider Codex host requires its own session-bound scoped proxy'), { codexSpawnConfigFatal: true });
+ }
return { extraArgs: [], extraEnv: {}, onHostRetired };
});
MockCodexTransport.onCreate = transport => transport.setMockResponse('account/login/start', {
@@ -24418,7 +24423,13 @@ describe('CodexAgent.forkSdkSession', () => {
accountHostKey: expect.stringMatching(/^local-fork:/),
runtimeCodexHome: path.join(home, 'codex'),
deviceHostedGuestProviderId: 'openai',
+ deviceHostedGuestModelIds: ['gpt-5.4'],
}));
+ // The guest session is this one-shot fork host's own key (never registered as a guest
+ // session; codexProxyGuestRoute.test.ts covers that the guard then refuses everything).
+ const spawnCtx = prepare.mock.calls[0]?.[1];
+ expect(spawnCtx?.deviceHostedGuestSessionId).toMatch(/^local-fork:[0-9a-f-]{36}$/);
+ expect(spawnCtx?.accountHostKey?.startsWith(`${spawnCtx.deviceHostedGuestSessionId}:`)).toBe(true);
expect(createdTransports).toHaveLength(1);
expect(createdTransports[0].closed).toBe(true);
expect(onHostRetired).toHaveBeenCalledOnce();
@@ -24441,6 +24452,16 @@ describe('CodexAgent.forkSdkSession', () => {
expect(resolveCodexThreadStorage).not.toHaveBeenCalled();
expect(prepareCodexResumeSession).not.toHaveBeenCalled();
});
+ // Fail closed: without the shared provider a guest fork would start an ordinary host that
+ // can use the owner's own login.
+ it('refuses a guest fork that has no shared provider before starting any host', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, undefined, { userAgent: 'mock-codex/0.153.4' });
+ await expect(agent.forkSdkSession({ sourceSdkSessionId: 'guest-source', upToMessageId: undefined,
+ lastTurnId: 'guest-turn', hostedGuestHome: path.join(os.tmpdir(), 'guest-fork-fixture') }))
+ .rejects.toThrow(/requires the shared provider/);
+ expect(host.getHost).not.toHaveBeenCalled();
+ });
it('reads cross-account fork boundaries and records the child in the source index', async () => {
const recordCodexThreadLocation = vi.fn(async () => {});
const agent = new CodexAgent(createDeps({}, {
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 85dd6ba703..11e22dc2b0 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -15098,6 +15098,8 @@ assertRouteCurrent();
});
try {
const guestCodexHome = opts.hostedGuestHome ? path.join(opts.hostedGuestHome, 'codex') : undefined;
+ // 受邀者的 fork 只能走分享的供应商:没有供应商时不退回成普通 host(那会用上本机用户的登录)。
+ if (guestCodexHome && !opts.providerId) throw new Error('shared-provider Codex fork requires the shared provider');
const forkStorage = guestCodexHome
? { historyHome: guestCodexHome, sqliteHome: guestCodexHome }
: await this.deps.resolveCodexThreadStorage?.(opts.sourceSdkSessionId);
@@ -15131,7 +15133,14 @@ assertRouteCurrent();
...(forkAccountId ? { providerId: forkAccountId } : {}),
...(forkSqliteHome ? { sqliteHome: forkSqliteHome } : {}),
...(forkStorage ? { historyHome: forkStorage.historyHome } : {}),
- ...(guestCodexHome && opts.providerId ? { deviceHostedGuestProviderId: opts.providerId } : {}),
+ // 受邀者的 fork 同样要有独占的、按会话收窄的 proxy。fork 只做 thread/fork 与 rollback、
+ // 不跑 turn:会话 id 用这次 fork 独有、不登记的 key,受邀者守门因此拒绝它经分享供应商发出的
+ // 任何请求,不会借到源任务或其他受邀者的授权。
+ ...(guestCodexHome && opts.providerId ? {
+ deviceHostedGuestProviderId: opts.providerId,
+ deviceHostedGuestSessionId: forkBaseHostKey,
+ deviceHostedGuestModelIds: opts.model ? [opts.model] : [],
+ } : {}),
routeIsCurrent: selection.isCurrent,
routeSignal: forkRouteSignal,
...(selection.policy === 'isolated' ? { localAuthPolicy: selection.policy } : {}),
diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjs
index ef70617b44..50caa20f01 100644
--- a/scripts/test-workspaces.config.mjs
+++ b/scripts/test-workspaces.config.mjs
@@ -97,6 +97,8 @@ const makerPiManagerIntegrationInclude = [
];
const desktopE2eInclude = [
'src/main/maker-host/__tests__/*.e2e.test.ts',
+ // Guest fork through a provider group with a real Claude Code; skipped without apps/claude-code-bin.
+ 'src/main/remote-agent/__tests__/groupRelayClaudeFork.e2e.test.ts',
];
const mobileGuardInclude = [
// Swift/delegate authorization, recording lifecycle, and native clipping are cross-runtime contracts.