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(orca): UI 创建 Worker 时按需交接 Lead 上下文 (#2589)

Dash150f2545d190
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 10fa5185ff..a309094c90 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -32,6 +32,7 @@ import { createOrcaWorkerBridgeMcpProvider, type OrcaBridgeMcpDeps } from '@cind
import { LspServerPool, type IOSSimulatorMcpCallContext } from '@cindy/mcps';
import { createMessage } from '../localDb/ipc/messages.js';
+import { getMessagesForHistory } from '../localDb/chatHistoryReader.js';
import { getWorkerLink, updateWorkerStatus } from '../localDb/orcaTeamStore.js';
import { cleanupSessionTempAttachments } from '../maker-ipc/normalizeAttachments.js';
import { markKnownOrcaWorkerSession } from '../maker-ipc/orcaManualInterrupt.js';
@@ -805,6 +806,31 @@ export function getMaker(): Maker {
return { makerMemoryEnabled: createOpts.makerMemoryEnabled === true };
},
orcaTeamStore: orcaTeamStoreAdapter,
+ readLeadHistory: async ({ leadSessionId, fromMs, limit, cursor }) => {
+ const page = await getMessagesForHistory({
+ sessionIds: [leadSessionId],
+ workdir: null,
+ fromMs,
+ toMs: null,
+ agentKind: null,
+ roles: ['user', 'assistant'],
+ includeRewound: false,
+ limit,
+ cursor,
+ order: 'asc',
+ });
+ return {
+ items: page.items.map((item) => ({
+ id: item.id,
+ role: item.role === 'assistant' ? 'assistant' as const : 'user' as const,
+ content: item.content,
+ agentMeta: item.agentMeta,
+ createdAt: item.createdAt,
+ })),
+ nextCursor: page.nextCursor,
+ hasMore: page.hasMore,
+ };
+ },
dispatchInterAgentMessage,
} satisfies OrcaBridgeMcpDeps;
const orcaWorkerBridgeProvider = createOrcaWorkerBridgeMcpProvider(orcaBridgeDeps);
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index fdbcc6c2be..e5c56b1ba4 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -201,6 +201,9 @@ function createHarness(opts?: {
const onUserMessagePersisted = vi.fn<
NonNullable<AgentInputCoordinatorDeps['onUserMessagePersisted']>
>(() => {});
+ const onUserMessageQueryable = vi.fn<
+ NonNullable<AgentInputCoordinatorDeps['onUserMessageQueryable']>
+ >(() => {});
const onUserMessagePersistenceFailed = vi.fn<
NonNullable<AgentInputCoordinatorDeps['onUserMessagePersistenceFailed']>
>(() => {});
@@ -296,6 +299,7 @@ function createHarness(opts?: {
onUndispatchedUserTurn,
onUserMessagePersisting,
onUserMessagePersisted,
+ onUserMessageQueryable,
onUserMessagePersistenceFailed,
onAcceptedQueuedMessage,
onDispatchedUserTurn,
@@ -332,6 +336,7 @@ function createHarness(opts?: {
onUndispatchedUserTurn,
onUserMessagePersisting,
onUserMessagePersisted,
+ onUserMessageQueryable,
onUserMessagePersistenceFailed,
onAcceptedQueuedMessage,
onDispatchedUserTurn,
@@ -3609,9 +3614,22 @@ describe('AgentInputCoordinator send transaction', () => {
expect(mocks.createMessage).toHaveBeenCalledTimes(1);
expect(shouldBroadcastResult).toBe(false);
+ expect(h.onUserMessageQueryable).not.toHaveBeenCalled();
expect(latestProjection(h.projections).pendingQueue).toEqual([]);
});
+ it('notifies queryability only after an accepted row survives the clear generation', async () => {
+ const h = createHarness();
+ const sid = 'queryable-after-persist';
+ const first = makeItem('q-1', 'first');
+
+ h.coordinator.enqueue(sid, first);
+ await flush();
+
+ expect(h.onUserMessagePersisted).toHaveBeenCalledWith(sid, expect.objectContaining(first));
+ expect(h.onUserMessageQueryable).toHaveBeenCalledWith(sid, expect.objectContaining(first));
+ });
+
it('settles a persistence failure after clear without treating the row as durable', async () => {
const h = createHarness();
const sid = 'clear-during-persist-failure';
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts
index 40c80f23c6..bb5cdb2252 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaLifecycleService.test.ts
@@ -570,6 +570,7 @@ describe('OrcaLifecycleService', () => {
ok: true,
workerId: 'worker-1',
dispatched: false,
+ uiAssignmentSnapshotBeforeMs: expect.any(Number),
});
expect(calls).toEqual([
@@ -585,7 +586,7 @@ describe('OrcaLifecycleService', () => {
});
it('keeps the worker role slug as the default label when a delegate task exists', async () => {
- const { calls, service } = createDeps();
+ const { calls, deps, service } = createDeps();
await expect(
service.enableTeam({
@@ -610,6 +611,53 @@ describe('OrcaLifecycleService', () => {
'broadcastSessionCreated:worker-session-1',
'broadcastOrcaWorkerChanged:lead-1',
]);
+ expect(deps.dispatchWorkerTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: expect.stringContaining('[Orca UI Assignment]'),
+ dispatchMeta: expect.objectContaining({
+ context: 'enable_collab_mode/worker-session-1/delegate_task',
+ }),
+ }),
+ );
+ const dispatchedMessage = vi.mocked(deps.dispatchWorkerTask).mock.calls[0]?.[0].message;
+ expect(dispatchedMessage).toContain('Task:\nReview PR #42 now');
+ expect(dispatchedMessage).toContain('Lead session id: "lead-1"');
+ expect(dispatchedMessage).toContain('orca_worker_bridge.read_lead_history');
+ expect(dispatchedMessage).toContain('If the task is self-contained, proceed directly');
+ expect(dispatchedMessage).toContain(
+ "do not assume the process cwd is the Lead's active worktree",
+ );
+ });
+
+ it('initializes a deferred-task Worker with the ready placeholder without dispatching the task', async () => {
+ const { calls, deps, service } = createDeps();
+
+ await expect(
+ service.enableTeam({
+ leadSessionId: 'lead-1',
+ workerAgent: 'codex',
+ role: 'Code Review',
+ delegateTask: 'Review the attached spec',
+ deferDelegateTask: true,
+ }),
+ ).resolves.toMatchObject({
+ ok: true,
+ workerId: 'worker-1',
+ dispatched: false,
+ });
+
+ expect(calls).toEqual([
+ 'createActiveTeam:lead-1',
+ 'createWorkerInTeam:team-1:code-review',
+ 'setSessionOrcaRole:lead-1:lead',
+ 'clearKnownNonOrcaSession:lead-1',
+ 'setLeadVendorOptions:lead-1:worker-session-1',
+ 'sendWorkerReadyPlaceholder:enable_collab_mode:enable_collab_mode/worker-session-1/worker-ready-placeholder',
+ 'broadcastSessionCreated:worker-session-1',
+ 'broadcastOrcaWorkerChanged:lead-1',
+ ]);
+ expect(deps.dispatchWorkerTask).not.toHaveBeenCalled();
+ expect(deps.sendWorkerReadyPlaceholder).toHaveBeenCalledOnce();
});
it('falls back to worker when the worker role cannot produce a label slug', async () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaUiAssignmentHistoryGate.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaUiAssignmentHistoryGate.test.ts
new file mode 100644
index 0000000000..2118852aec
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaUiAssignmentHistoryGate.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ createOrcaUiAssignmentDispatchClaims,
+ createOrcaUiAssignmentHistoryGate,
+} from '../orcaUiAssignmentHistoryGate';
+
+describe('Orca UI assignment history gate', () => {
+ it('returns immediately when the Lead input is already queryable', async () => {
+ const hasUserMessageSince = vi.fn().mockResolvedValue(true);
+ const gate = createOrcaUiAssignmentHistoryGate({ hasUserMessageSince });
+
+ await expect(gate.waitUntilQueryable('lead-1', 123)).resolves.toBe(true);
+ expect(hasUserMessageSince).toHaveBeenCalledWith('lead-1', 123);
+ });
+
+ it('does not miss persistence that happens while the initial DB query is in flight', async () => {
+ let finishQuery!: (value: boolean) => void;
+ const hasUserMessageSince = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise<boolean>((resolve) => {
+ finishQuery = resolve;
+ }),
+ )
+ .mockResolvedValueOnce(true);
+ const gate = createOrcaUiAssignmentHistoryGate({ hasUserMessageSince });
+
+ const pending = gate.waitUntilQueryable('lead-1', 123);
+ gate.notifyUserMessagePersisted('lead-1');
+ finishQuery(false);
+
+ await expect(pending).resolves.toBe(true);
+ expect(hasUserMessageSince).toHaveBeenCalledTimes(2);
+ });
+
+ it('rechecks the DB after a persistence notification instead of treating it as proof', async () => {
+ const hasUserMessageSince = vi
+ .fn()
+ .mockResolvedValueOnce(false)
+ .mockResolvedValueOnce(false)
+ .mockResolvedValueOnce(true);
+ const gate = createOrcaUiAssignmentHistoryGate({ hasUserMessageSince });
+
+ const pending = gate.waitUntilQueryable('lead-1', 123);
+ await vi.waitFor(() => expect(hasUserMessageSince).toHaveBeenCalledTimes(1));
+ gate.notifyUserMessagePersisted('lead-1');
+ await vi.waitFor(() => expect(hasUserMessageSince).toHaveBeenCalledTimes(2));
+ gate.notifyUserMessagePersisted('lead-1');
+
+ await expect(pending).resolves.toBe(true);
+ expect(hasUserMessageSince).toHaveBeenCalledTimes(3);
+ });
+
+ it('fails closed after the bounded wait when no Lead input becomes queryable', async () => {
+ vi.useFakeTimers();
+ const hasUserMessageSince = vi.fn().mockResolvedValue(false);
+ const gate = createOrcaUiAssignmentHistoryGate({ hasUserMessageSince, timeoutMs: 1_000 });
+
+ const pending = gate.waitUntilQueryable('lead-1', 123);
+ await vi.advanceTimersByTimeAsync(1_000);
+ await expect(pending).resolves.toBe(false);
+ expect(hasUserMessageSince).toHaveBeenCalledTimes(2);
+ vi.useRealTimers();
+ });
+});
+
+describe('Orca UI assignment dispatch claims', () => {
+ const assignment = {
+ leadSessionId: 'lead-1',
+ workerSessionId: 'worker-1',
+ snapshotBeforeMs: 123,
+ };
+
+ it('shares one dispatch across concurrent and later calls for the same assignment', async () => {
+ let finishDispatch!: (value: string) => void;
+ const dispatch = vi.fn(
+ () =>
+ new Promise<string>((resolve) => {
+ finishDispatch = resolve;
+ }),
+ );
+ const claims = createOrcaUiAssignmentDispatchClaims();
+
+ const first = claims.runOnce(assignment, dispatch);
+ const concurrent = claims.runOnce(assignment, dispatch);
+ await vi.waitFor(() => expect(dispatch).toHaveBeenCalledTimes(1));
+ finishDispatch('accepted');
+
+ await expect(Promise.all([first, concurrent])).resolves.toEqual(['accepted', 'accepted']);
+ await expect(claims.runOnce(assignment, dispatch)).resolves.toBe('accepted');
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not conflate assignments from different snapshots', async () => {
+ const dispatch = vi.fn().mockResolvedValue('accepted');
+ const claims = createOrcaUiAssignmentDispatchClaims();
+
+ await claims.runOnce(assignment, dispatch);
+ await claims.runOnce({ ...assignment, snapshotBeforeMs: 124 }, dispatch);
+
+ expect(dispatch).toHaveBeenCalledTimes(2);
+ });
+
+ it('shares a rejected dispatch without retrying the same assignment', async () => {
+ const failure = new Error('dispatch failed');
+ const dispatch = vi.fn().mockRejectedValue(failure);
+ const claims = createOrcaUiAssignmentDispatchClaims();
+
+ const first = claims.runOnce(assignment, dispatch);
+ const concurrent = claims.runOnce(assignment, dispatch);
+
+ const outcomes = await Promise.allSettled([first, concurrent]);
+ expect(outcomes).toEqual([
+ { status: 'rejected', reason: failure },
+ { status: 'rejected', reason: failure },
+ ]);
+ await expect(claims.runOnce(assignment, dispatch)).rejects.toBe(failure);
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaUiAssignmentWiring.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaUiAssignmentWiring.test.ts
new file mode 100644
index 0000000000..8909e17d0c
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaUiAssignmentWiring.test.ts
@@ -0,0 +1,61 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const registerSource = readFileSync(resolve(__dirname, '..', 'register.ts'), 'utf8');
+const lifecycleSource = readFileSync(resolve(__dirname, '..', 'orcaLifecycleService.ts'), 'utf8');
+const sessionViewSource = readFileSync(
+ resolve(
+ __dirname,
+ '..',
+ '..',
+ '..',
+ 'renderer',
+ 'features',
+ 'cc-agent',
+ 'CCAgentSessionView.tsx',
+ ),
+ 'utf8',
+);
+
+describe('Orca UI assignment wiring', () => {
+ it('waits for queryable Lead history before sending the deferred task', () => {
+ const start = registerSource.indexOf('MAKER_INVOKE.WORKER_DISPATCH_UI_ASSIGNMENT');
+ const end = registerSource.indexOf('async function clearLeadOrcaRoleState', start);
+ const handler = registerSource.slice(start, end);
+
+ const wait = handler.indexOf('orcaUiAssignmentHistoryGate.waitUntilQueryable(');
+ const claim = handler.indexOf('orcaUiAssignmentDispatchClaims.runOnce(');
+ const dispatch = handler.indexOf('orcaTeamService.sendToWorker({');
+ expect(start).toBeGreaterThan(-1);
+ expect(wait).toBeGreaterThan(-1);
+ expect(claim).toBeGreaterThan(wait);
+ expect(dispatch).toBeGreaterThan(claim);
+ expect(handler).toContain('buildUiAssignmentInitialTask({');
+ });
+
+ it('queries user rows after the handoff snapshot and observes durable persistence', () => {
+ const gateStart = registerSource.indexOf(
+ 'const orcaUiAssignmentHistoryGate = createOrcaUiAssignmentHistoryGate({',
+ );
+ const gateEnd = registerSource.indexOf('const orcaLifecycleService', gateStart);
+ const gate = registerSource.slice(gateStart, gateEnd);
+ expect(gate).toContain('fromMs: snapshotBeforeMs');
+ expect(gate).toContain("roles: ['user']");
+ expect(lifecycleSource).toContain('uiAssignmentSnapshotBeforeMs: Date.now()');
+ expect(registerSource).toContain(
+ 'orcaUiAssignmentHistoryGate.notifyUserMessagePersisted(sessionId);',
+ );
+ expect(registerSource).toContain(
+ 'const orcaUiAssignmentDispatchClaims = createOrcaUiAssignmentDispatchClaims();',
+ );
+ });
+
+ it('keeps the Worker resumable and recovers a persisted pending receipt on Lead mount', () => {
+ expect(lifecycleSource).toContain('!normalized.initialTask || params.deferDelegateTask');
+ expect(sessionViewSource).toContain('getRecoverableDeferredUiAssignment({');
+ expect(sessionViewSource).toContain("remoteRouteUnavailable: remoteConn !== 'connected'");
+ expect(sessionViewSource).toContain('dispatchDeferredUiAssignment(sessionId, undefined).catch');
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index 86e98e1504..f248bd428f 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -392,6 +392,8 @@ export interface AgentInputCoordinatorDeps {
onUserMessagePersisting?: (sessionId: string, item: AgentInputQueuedMessage) => void;
/** Called after the durable user row exists; ownership of staged attachments may be released. */
onUserMessagePersisted?: (sessionId: string, item: AgentInputQueuedMessage) => void;
+ /** Called only after the durable row also survives the current clear/rewind generation. */
+ onUserMessageQueryable?: (sessionId: string, item: AgentInputQueuedMessage) => void;
/**
* Called when the user-row write failed. A queued turn remains retryable;
* an accepted steer does not, because replay could duplicate model input.
@@ -3300,6 +3302,7 @@ export class AgentInputCoordinator {
active.persisted = true;
active.persisting = false;
active.dispatchLifecycle = 'awaiting-dispatch-hooks';
+ this.notifyUserMessageQueryable(sessionId, head);
// 跨过 DB 持久化边界即刻收窄快照:此后崩溃属 interrupted-turn
// 辖区,若等到下一次 emit(turn done)才写,长 turn 内崩溃会把
// 已送达的消息二次恢复(issue #761)。
@@ -4592,6 +4595,18 @@ export class AgentInputCoordinator {
}
}
+ private notifyUserMessageQueryable(sessionId: string, item: AgentInputQueuedMessage): void {
+ try {
+ this.deps.onUserMessageQueryable?.(sessionId, item);
+ } catch (err) {
+ log.warn('onUserMessageQueryable failed', {
+ sessionId,
+ clientId: item.clientId,
+ error: errorMessage(err),
+ });
+ }
+ }
+
private notifyUserMessagePersisting(sessionId: string, item: AgentInputQueuedMessage): void {
try {
this.deps.onUserMessagePersisting?.(sessionId, item);
@@ -4697,6 +4712,7 @@ export class AgentInputCoordinator {
if (!this.isTurnGenerationCurrent(sessionId, active)) return 'stale';
active.persisted = true;
active.persisting = false;
+ this.notifyUserMessageQueryable(sessionId, item);
// 同 drain onPersisted:steer 消息落库后立即收窄快照,避免长 turn 内崩溃二次恢复。
this.maybePersistQueueSnapshot(sessionId);
this.settlePendingTerminalEventAfterPersist(sessionId, active);
diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.ts
index 0b10c848fa..270525789f 100644
--- a/apps/desktop/src/main/maker-ipc/channels.ts
+++ b/apps/desktop/src/main/maker-ipc/channels.ts
@@ -580,6 +580,8 @@ export const MAKER_INVOKE = {
PROJECT_AUTOMATION_REMOVE_SCHEDULE: 'maker:project-automation:remove-schedule',
// multi-worker Phase 1
WORKER_CREATE: 'maker:worker:create',
+ /** 新建 Lead 的首条输入 accepted 后,派发此前延后的 UI initial_task。 */
+ WORKER_DISPATCH_UI_ASSIGNMENT: 'maker:worker:dispatch-ui-assignment',
WORKER_LIST: 'maker:worker:list',
WORKER_SWITCH_FOCUS: 'maker:worker:switch-focus',
WORKER_IDLE: 'maker:worker:idle',
diff --git a/apps/desktop/src/main/maker-ipc/orcaLifecycleService.ts b/apps/desktop/src/main/maker-ipc/orcaLifecycleService.ts
index 35f83c582f..0695d7a404 100644
--- a/apps/desktop/src/main/maker-ipc/orcaLifecycleService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaLifecycleService.ts
@@ -1,6 +1,7 @@
import type { AgentKind } from '@cindy/maker-core';
import { createHostSendFailure } from '../maker-host/send-outcome.js';
+import { buildUiAssignmentInitialTask } from './orcaUiAssignment.js';
import type { DispatchWorkerTaskResult, OrcaWorkerEffort } from './orcaTeamService.js';
import { normalizeOrcaWorkerLabel } from './orcaWorkerCreationService.js';
import type {
@@ -28,6 +29,8 @@ export interface OrcaEnableTeamParams {
/** 显式选定的模型来源;语义见 OrcaWorkerCreateParams.providerId。 */
providerId?: string | null;
delegateTask?: string;
+ /** UI 新建 Lead 时先建 Worker,把首任务留到 Lead 首条输入可查询后再派。 */
+ deferDelegateTask?: boolean;
/** 本次首个 Worker 权限;缺省读取 Worker 创建偏好。显式值同时更新后续默认。 */
workerPermissionMode?: OrcaWorkerPermissionMode;
}
@@ -64,6 +67,8 @@ export type OrcaEnableTeamResult =
workerSessionId: string;
workerId: string;
dispatched: boolean;
+ /** 由 Worker 所在主机生成,供后续 history gate 避免跨设备时钟偏差。 */
+ uiAssignmentSnapshotBeforeMs: number;
workerPermissionMode: OrcaWorkerPermissionMode;
dispatchOutcome?: DispatchWorkerTaskResult['dispatchOutcome'];
}
@@ -373,13 +378,16 @@ export function createOrcaLifecycleService(deps: OrcaLifecycleDeps): OrcaLifecyc
}
let dispatchResult: DispatchWorkerTaskResult | undefined;
- if (normalized.initialTask) {
+ if (normalized.initialTask && !params.deferDelegateTask) {
dispatchResult = await dispatchInitialTask({
workerSessionId: created.workerSessionId,
- message: normalized.initialTask,
+ message: buildUiAssignmentInitialTask({
+ leadSessionId: params.leadSessionId,
+ initialTask: normalized.initialTask,
+ }),
context: `enable_collab_mode/${created.workerSessionId}/delegate_task`,
});
- } else {
+ } else if (!normalized.initialTask || params.deferDelegateTask) {
try {
await deps.sendWorkerReadyPlaceholder({
workerSessionId: created.workerSessionId,
@@ -407,6 +415,7 @@ export function createOrcaLifecycleService(deps: OrcaLifecycleDeps): OrcaLifecyc
workerSessionId: created.workerSessionId,
workerId: created.workerId,
dispatched: dispatchResult?.dispatched ?? false,
+ uiAssignmentSnapshotBeforeMs: Date.now(),
workerPermissionMode,
...(dispatchResult ? { dispatchOutcome: dispatchResult.dispatchOutcome } : {}),
};
diff --git a/apps/desktop/src/main/maker-ipc/orcaUiAssignment.ts b/apps/desktop/src/main/maker-ipc/orcaUiAssignment.ts
new file mode 100644
index 0000000000..e88dc6c44f
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/orcaUiAssignment.ts
@@ -0,0 +1,26 @@
+/**
+ * UI 直接创建 Worker 时,Lead 没有参与派单 turn;把按需回查线索放进同一条 initial task,
+ * 既不唤醒 Lead,也不改变 MCP create_worker 已由 Lead 写好上下文的任务正文。
+ */
+export function buildUiAssignmentInitialTask(params: {
+ leadSessionId: string;
+ initialTask: string;
+ snapshotBeforeMs?: number;
+}): string {
+ return [
+ '[Orca UI Assignment]',
+ '',
+ 'Task:',
+ params.initialTask,
+ '',
+ 'Context handoff:',
+ 'This Worker was created directly from the collaboration UI. The task may depend on work already in progress in the Lead session.',
+ `Lead session id: ${JSON.stringify(params.leadSessionId)}`,
+ ...(params.snapshotBeforeMs !== undefined
+ ? [`snapshot_before_ms: ${params.snapshotBeforeMs}`]
+ : []),
+ 'Decide whether that context is needed before acting. If the task refers to current work, continuing work, this PR, or another relative scope, call orca_worker_bridge.read_lead_history with your worker_id. When snapshot_before_ms is present, pass it as from_ms. Page through next_cursor when has_more is true.',
+ 'Use those tools only when needed. If the task is self-contained, proceed directly without reading the Lead history.',
+ "For code work, recover the intended repository, worktree, branch, and review range from the Lead's context and verify them on disk; do not assume the process cwd is the Lead's active worktree.",
+ ].join('\n');
+}
diff --git a/apps/desktop/src/main/maker-ipc/orcaUiAssignmentHistoryGate.ts b/apps/desktop/src/main/maker-ipc/orcaUiAssignmentHistoryGate.ts
new file mode 100644
index 0000000000..bc0bf85128
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/orcaUiAssignmentHistoryGate.ts
@@ -0,0 +1,93 @@
+export interface OrcaUiAssignmentHistoryGate {
+ /** 等到目标 Lead 至少有一条 snapshot 之后的 user 消息可查询。 */
+ waitUntilQueryable(leadSessionId: string, snapshotBeforeMs: number): Promise<boolean>;
+ /** 用户消息落库后通知等待者;调用点必须位于 durable persist 回调。 */
+ notifyUserMessagePersisted(leadSessionId: string): void;
+}
+
+export interface OrcaUiAssignmentDispatchClaims {
+ /** 同一份 UI assignment 在 Main 进程生命周期内只执行一次,并发调用共享同一结果。 */
+ runOnce<T>(
+ params: { leadSessionId: string; workerSessionId: string; snapshotBeforeMs: number },
+ dispatch: () => Promise<T>,
+ ): Promise<T>;
+}
+
+export function createOrcaUiAssignmentDispatchClaims(): OrcaUiAssignmentDispatchClaims {
+ const claims = new Map<string, Promise<unknown>>();
+
+ return {
+ runOnce(params, dispatch) {
+ const key = JSON.stringify([
+ params.leadSessionId,
+ params.workerSessionId,
+ params.snapshotBeforeMs,
+ ]);
+ const existing = claims.get(key);
+ if (existing) return existing as ReturnType<typeof dispatch>;
+
+ // 先登记 promise,再在 microtask 中派发,避免同一事件循环内的两个窗口都穿透。
+ // 已完成的 claim 也刻意保留:结果不确定时,重试仍不能冒险重复投递。
+ const claimed = Promise.resolve().then(dispatch);
+ claims.set(key, claimed);
+ return claimed;
+ },
+ };
+}
+
+export function createOrcaUiAssignmentHistoryGate(deps: {
+ hasUserMessageSince: (leadSessionId: string, snapshotBeforeMs: number) => Promise<boolean>;
+ timeoutMs?: number;
+}): OrcaUiAssignmentHistoryGate {
+ const waiters = new Map<string, Set<() => void>>();
+ const timeoutMs = deps.timeoutMs ?? 30_000;
+
+ const removeWaiter = (leadSessionId: string, resolve: () => void) => {
+ const current = waiters.get(leadSessionId);
+ current?.delete(resolve);
+ if (current?.size === 0) waiters.delete(leadSessionId);
+ };
+
+ return {
+ async waitUntilQueryable(leadSessionId, snapshotBeforeMs) {
+ const deadline = Date.now() + timeoutMs;
+ while (true) {
+ let notify!: () => void;
+ const persisted = new Promise<void>((resolve) => {
+ notify = resolve;
+ });
+ const current = waiters.get(leadSessionId) ?? new Set<() => void>();
+ current.add(notify);
+ waiters.set(leadSessionId, current);
+
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ // 先登记 waiter 再查 DB:消息若恰在查询期间落库,通知不会丢;若更早已落库,
+ // 查询直接命中。notify 只是“值得复查”的提示,不是可查询性的证据——同 session
+ // 的其它消息也会触发通知,且 clear/rewind 可能紧跟在 durable write 之后。
+ if (await deps.hasUserMessageSince(leadSessionId, snapshotBeforeMs)) return true;
+ const remainingMs = deadline - Date.now();
+ if (remainingMs <= 0) return false;
+ const notified = await Promise.race([
+ persisted.then(() => true),
+ new Promise<false>((resolve) => {
+ timer = setTimeout(() => resolve(false), remainingMs);
+ }),
+ ]);
+ if (!notified) {
+ // deadline 边沿再查一次,覆盖 commit 与 timeout 同拍、通知尚未执行的情况。
+ return deps.hasUserMessageSince(leadSessionId, snapshotBeforeMs);
+ }
+ } finally {
+ if (timer) clearTimeout(timer);
+ removeWaiter(leadSessionId, notify);
+ }
+ // 被通知后重新登记 waiter + 查 DB;绝不把 callback 本身当成历史可见性。
+ }
+ },
+
+ notifyUserMessagePersisted(leadSessionId) {
+ for (const resolve of waiters.get(leadSessionId) ?? []) resolve();
+ },
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 4faaff94f5..ceda46f646 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -153,6 +153,7 @@ import * as imageCacheStore from '../imageCacheStore.js';
import * as cindyChatAttachments from '../cindy-media/chatAttachments.js';
import { materializeGeneratedImage } from '../cindy-media/generatedMedia.js';
import { getDbClient } from '../localDb/client/current.js';
+import { getMessagesForHistory } from '../localDb/chatHistoryReader.js';
import {
awaitAgentInputQueueSnapshotPersistence,
loadAgentInputQueueSnapshot,
@@ -593,6 +594,11 @@ import {
} from '../agent-island/notificationPolicy.js';
import { getAgentIslandService } from '../agent-island/service.js';
import { createOrcaLifecycleService, ORCA_WORKER_READY_MESSAGE } from './orcaLifecycleService.js';
+import { buildUiAssignmentInitialTask } from './orcaUiAssignment.js';
+import {
+ createOrcaUiAssignmentDispatchClaims,
+ createOrcaUiAssignmentHistoryGate,
+} from './orcaUiAssignmentHistoryGate.js';
import { throwOrcaServiceFailure } from './orcaServiceFailure.js';
import {
createOrcaTeamService,
@@ -1462,6 +1468,7 @@ interface OrcaCollabService {
workerSessionId: string;
workerId: string;
dispatched: boolean;
+ uiAssignmentSnapshotBeforeMs: number;
workerPermissionMode: OrcaWorkerPermissionMode;
dispatchOutcome?: CollabDispatchOutcome;
}>;
@@ -1662,6 +1669,8 @@ interface EnableOrcaOptions {
providerId?: string | null;
/** Worker 创建默认权限;缺省沿用当前偏好,显式值会更新偏好。 */
workerPermissionMode?: OrcaWorkerPermissionMode;
+ /** 新建 Lead 专用:先建 Worker,等首条 Lead 输入 accepted 且可查询后再派任务。 */
+ deferDelegateTask?: boolean;
}
let orcaCollabServiceHolder: OrcaCollabService | null = null;
@@ -5472,6 +5481,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 新控制端只有看到此位才允许给被控端 Orca Team 选择 Worker Full access。
// 旧 desktop 缺省为 false,避免显式 bypassPermissions 被旧 handler 静默忽略。
supportsOrcaWorkerPermissionMode: true,
+ // 新控制端只有看到此位,才会让被控端延后 UI initial_task 并在 Lead 首条
+ // 输入 accepted 且历史可查询后走 WORKER_DISPATCH_UI_ASSIGNMENT;旧端继续即时派发。
+ supportsDeferredOrcaUiAssignment: true,
// 调度更新支持 intervalMs:null 的显式清空表达(IPC 入口归一化成引擎的
// 「带 key 的 undefined」)。旧 desktop 缺省为 false——旧引擎会把 null 当
// 已设间隔算出 now+null 立即触发,mobile 必须据此回退旧 wire 形态(省略
@@ -7690,6 +7702,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
workerSessionId: string;
workerId: string;
dispatched: boolean;
+ uiAssignmentSnapshotBeforeMs: number;
workerPermissionMode: OrcaWorkerPermissionMode;
dispatchOutcome?: CollabDispatchOutcome;
}> {
@@ -7704,6 +7717,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
fast: opts.fast,
providerId: opts.providerId,
delegateTask: opts.delegateTask,
+ deferDelegateTask: opts.deferDelegateTask,
workerPermissionMode: opts.workerPermissionMode,
});
if (!result.ok) throwOrcaServiceFailure(result);
@@ -7720,6 +7734,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
workerSessionId: result.workerSessionId,
workerId: result.workerId,
dispatched: result.dispatched,
+ uiAssignmentSnapshotBeforeMs: result.uiAssignmentSnapshotBeforeMs,
workerPermissionMode: result.workerPermissionMode,
...(result.dispatchOutcome ? { dispatchOutcome: result.dispatchOutcome } : {}),
};
@@ -8890,6 +8905,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
fast?: unknown;
providerId?: unknown;
workerPermissionMode?: unknown;
+ deferDelegateTask?: unknown;
};
const workerAgent: AgentKind =
body.workerAgent === 'codex' ? 'codex' : body.workerAgent === 'pi' ? 'pi' : 'claude-code';
@@ -8900,6 +8916,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
) {
throwIpcError('INVALID_PARAMS', 'workerPermissionMode must be auto or bypassPermissions');
}
+ if (body.deferDelegateTask !== undefined && typeof body.deferDelegateTask !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'deferDelegateTask must be a boolean');
+ }
return enableOrcaInternal(leadSessionId, {
workerAgent,
delegateTask,
@@ -8914,10 +8933,75 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
? body.providerId.trim()
: undefined,
workerPermissionMode: body.workerPermissionMode,
+ deferDelegateTask: body.deferDelegateTask,
});
},
);
+ ipcMain.handle(
+ MAKER_INVOKE.WORKER_DISPATCH_UI_ASSIGNMENT,
+ async (
+ _e,
+ leadSessionId: unknown,
+ workerSessionId: unknown,
+ initialTask: unknown,
+ snapshotBeforeMs: unknown,
+ waitForLeadHistory: unknown,
+ ) => {
+ if (typeof leadSessionId !== 'string' || leadSessionId.length === 0) {
+ throwIpcError('INVALID_PARAMS', 'leadSessionId required');
+ }
+ if (typeof workerSessionId !== 'string' || workerSessionId.length === 0) {
+ throwIpcError('INVALID_PARAMS', 'workerSessionId required');
+ }
+ if (typeof initialTask !== 'string' || initialTask.trim().length === 0) {
+ throwIpcError('INVALID_PARAMS', 'initialTask required');
+ }
+ if (
+ typeof snapshotBeforeMs !== 'number' ||
+ !Number.isFinite(snapshotBeforeMs) ||
+ snapshotBeforeMs < 0
+ ) {
+ throwIpcError('INVALID_PARAMS', 'snapshotBeforeMs must be a non-negative number');
+ }
+ if (typeof waitForLeadHistory !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'waitForLeadHistory must be a boolean');
+ }
+ if (waitForLeadHistory) {
+ const queryable = await orcaUiAssignmentHistoryGate.waitUntilQueryable(
+ leadSessionId,
+ snapshotBeforeMs,
+ );
+ if (!queryable) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'Lead input was not queryable before the UI assignment deadline',
+ );
+ }
+ }
+ return orcaUiAssignmentDispatchClaims.runOnce(
+ {
+ leadSessionId,
+ workerSessionId,
+ snapshotBeforeMs,
+ },
+ async () => {
+ const result = await orcaTeamService.sendToWorker({
+ callerLeadSessionId: leadSessionId,
+ targetSessionId: workerSessionId,
+ message: buildUiAssignmentInitialTask({
+ leadSessionId,
+ initialTask: initialTask.trim(),
+ snapshotBeforeMs,
+ }),
+ });
+ if (!result.ok) throwOrcaServiceFailure(result);
+ return result;
+ },
+ );
+ },
+ );
+
/**
* clearLeadOrcaRoleState — 把一个 Lead session 的协同身份彻底清干净:DB orca_role=null
* (setSessionOrcaRole 会同时广播 { orcaRole: null } patch,renderer 的 collabEnabled 翻 false)、
@@ -9375,6 +9459,25 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
});
+ const orcaUiAssignmentHistoryGate = createOrcaUiAssignmentHistoryGate({
+ hasUserMessageSince: async (leadSessionId, snapshotBeforeMs) => {
+ const page = await getMessagesForHistory({
+ sessionIds: [leadSessionId],
+ workdir: null,
+ fromMs: snapshotBeforeMs,
+ toMs: null,
+ agentKind: null,
+ roles: ['user'],
+ includeRewound: false,
+ limit: 1,
+ cursor: null,
+ order: 'asc',
+ });
+ return page.items.length > 0;
+ },
+ });
+ const orcaUiAssignmentDispatchClaims = createOrcaUiAssignmentDispatchClaims();
+
const orcaLifecycleService = createOrcaLifecycleService({
getActiveTeamByLead,
createActiveTeam: async (leadSessionId) => createActiveTeam({ leadSessionId }),
@@ -10835,6 +10938,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// durable transcript row.
void queuedAttachmentOwnership.settleDurable(sessionId, item.clientId);
},
+ onUserMessageQueryable: (sessionId) => {
+ orcaUiAssignmentHistoryGate.notifyUserMessagePersisted(sessionId);
+ },
onUserMessagePersistenceFailed: (sessionId, item, opts) => {
settleQueuedAttachmentPersistenceFailure(sessionId, item.clientId, opts.retainForRetry);
},
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 7db53e86bb..fb35f27b8d 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -5371,15 +5371,35 @@ contextBridge.exposeInMainWorld('electronAPI', {
providerId?: string | null;
/** Worker 创建默认权限;缺省沿用当前偏好,显式值会更新偏好。 */
workerPermissionMode?: 'auto' | 'bypassPermissions';
+ /** 新建 Lead 专用:等首条输入 accepted 且可查询后再派任务。 */
+ deferDelegateTask?: boolean;
},
// main handler 实际返回 teamId(见 enableOrcaInternal);此前类型写成 workflowId 是漂移。
): Promise<{
teamId: string;
workerSessionId: string;
workerId: string;
+ dispatched: boolean;
workerPermissionMode: 'auto' | 'bypassPermissions';
+ uiAssignmentSnapshotBeforeMs: number;
}> => ipcRenderer.invoke('maker:session:enable-orca', leadSessionId, opts),
+ dispatchOrcaUiAssignment: (
+ leadSessionId: string,
+ workerSessionId: string,
+ initialTask: string,
+ snapshotBeforeMs: number,
+ waitForLeadHistory: boolean,
+ ): Promise<unknown> =>
+ ipcRenderer.invoke(
+ 'maker:worker:dispatch-ui-assignment',
+ leadSessionId,
+ workerSessionId,
+ initialTask,
+ snapshotBeforeMs,
+ waitForLeadHistory,
+ ),
+
/**
* F-COLLAB: 关闭 lead session 的当前协同 workflow。
* 后端会 abort+close 所有 Worker session、把 workflow 标 completed、
diff --git a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
index f33a013ecc..2d10e4b96b 100644
--- a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
+++ b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
@@ -163,7 +163,11 @@ describe('ChatInput session switch focus contract', () => {
expect(chatInputSource).toContain('onAccepted: markRecentPluginUsage');
expect(successfulSendBlock).toContain('markRecentPluginUsage();');
expect(newMakerDraftRouteSource.match(/opts\?\.onAccepted\?\.\(\);/g)).toHaveLength(3);
- expect(worktreeSendBlock).toContain('if (accepted) opts?.onAccepted?.();');
+ expect(worktreeSendBlock).toContain('if (accepted) {');
+ expect(worktreeSendBlock).toContain('opts?.onAccepted?.();');
+ expect(worktreeSendBlock).toContain(
+ 'dispatchDeferredUiAssignment(newSession.id, deferredUiAssignment)',
+ );
});
it('optimistically clears device-link composer state before awaiting send and restores without dropping newer input', () => {
diff --git a/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts b/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts
index 6f06d6cde2..8772877f7c 100644
--- a/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts
+++ b/apps/desktop/src/renderer/__tests__/makerTransportRouting.test.ts
@@ -24,6 +24,7 @@ function stubElectron() {
closeSession: vi.fn(),
compactSession: vi.fn().mockResolvedValue({ tokensBefore: 100, estimatedTokensAfter: 20 }),
enableOrca: vi.fn(),
+ dispatchOrcaUiAssignment: vi.fn(),
disableOrca: vi.fn(),
regenerateSessionTitle: vi.fn().mockResolvedValue({ title: 'local title' }),
plugins: { getState: vi.fn().mockResolvedValue({ effectiveEnabled: true }) },
@@ -73,6 +74,7 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {
api.closeSession('rs');
api.compactSession('rs', 'focus on API design');
api.enableOrca('rs', { workerAgent: 'codex' });
+ api.dispatchOrcaUiAssignment('rs', 'worker-1', 'Review this PR', 123, true);
api.disableOrca('rs');
api.input.compact(
'rs',
@@ -96,6 +98,13 @@ describe('makerApiFor 路由(完整对等会话级操作)', () => {
'rs',
{ workerAgent: 'codex' },
]);
+ expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:worker:dispatch-ui-assignment', [
+ 'rs',
+ 'worker-1',
+ 'Review this PR',
+ 123,
+ true,
+ ]);
expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:session:disable-orca', ['rs']);
expect(invoke).toHaveBeenCalledWith('dev-1', 'maker:input:compact', [
'rs',
diff --git a/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts b/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts
index dbc6bc8eb7..9c91e1cd81 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerOrcaCreateOrder.test.ts
@@ -201,7 +201,7 @@ describe('NewMakerDraftRoute Orca worker create order', () => {
expect(
slashDispatchBranch.match(/piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS/g),
- ).toHaveLength(2);
+ ).toHaveLength(3);
});
it('refreshes the remote mirror even when the remote enableOrca reports failure', () => {
@@ -211,7 +211,7 @@ describe('NewMakerDraftRoute Orca worker create order', () => {
const body = remoteCollabHandoffSource.slice(
remoteCollabHandoffSource.indexOf('export async function enableRemoteCollabForSession('),
);
- const returnAt = body.indexOf('return { focusWorkerSessionId:');
+ const returnAt = body.indexOf('return withDeferredAssignment(');
const finallyAt = body.indexOf('} finally {');
expect(returnAt).toBeGreaterThan(-1);
expect(finallyAt).toBeGreaterThan(returnAt);
@@ -222,17 +222,23 @@ describe('NewMakerDraftRoute Orca worker create order', () => {
// 草稿里持久化的来源/模型按**目标设备**的目录收窄:device-link 分支必须用
// deviceProviders,拿控制端的 localProviders 收窄等于用错机器的目录。
const collapsed = source.replace(/\s+/g, ' ');
- const remoteNarrowing =
+ expect(
collapsed.match(
- /draftEnableOrcaOptions\( effectiveCollab, deviceProviders, !deviceProvidersLoading, \)/g,
- ) ?? [];
- expect(remoteNarrowing).toHaveLength(2);
- // 本机 / SSH 的四条路径仍按控制端目录收窄,不能被一起改掉。
+ /draftEnableOrcaOptions\( effectiveCollab, deviceProviders, !deviceProvidersLoading, true, \)/g,
+ ) ?? [],
+ ).toHaveLength(2);
+ // 本机 / SSH 仍按控制端目录收窄。五条创建即发送/目标路径都要求 deferred handoff;
+ // 「添加远程项目」只迁移未发送的 composer 草稿,不能提前派 Worker 任务。
+ expect(
+ collapsed.match(
+ /draftEnableOrcaOptions\( effectiveCollab, localProviders, !localProvidersLoading, true, \)/g,
+ ) ?? [],
+ ).toHaveLength(3);
expect(
collapsed.match(
- /draftEnableOrcaOptions\(\s*effectiveCollab,\s*localProviders,\s*!localProvidersLoading,?\s*\)/g,
+ /draftEnableOrcaOptions\(\s*effectiveCollab, localProviders, !localProvidersLoading\)/g,
) ?? [],
- ).toHaveLength(4);
+ ).toHaveLength(1);
});
it('re-validates the worker agent against the target device catalog', () => {
@@ -364,8 +370,10 @@ describe('NewMakerDraftRoute Orca worker create order', () => {
expect(send).toBeLessThan(unlock);
// sendMessage 失败时 resolve false 而不抛错 —— 必须 await 且经 deliver 判定,
// 裸调 + 立刻丢副本会让正文从界面和磁盘上一起消失(codex P1 第五轮)。
- expect(branch).toContain('await deliverRecoverableHandoff(sessionId, () =>');
+ expect(branch).toContain('const delivered = await deliverRecoverableHandoff(sessionId, () =>');
expect(branch).toContain('sendMessage(');
+ expect(branch.indexOf('if (delivered) {')).toBeGreaterThan(send);
+ expect(branch).toContain('dispatchDeferredUiAssignment(sessionId, deferredUiAssignment)');
});
it('新建目标:锁从消费一路盖到 setGoal 结束,setGoal 成功后才清副本', () => {
@@ -388,6 +396,8 @@ describe('NewMakerDraftRoute Orca worker create order', () => {
expect(awaitCollab).toBeLessThan(setGoal);
// setGoal 抛错时副本必须留着 → 它必须包在 deliver 的回调里(抛错就到不了 forget)。
expect(forget).toBeLessThan(setGoal);
+ expect(branch.indexOf('if (delivered) {')).toBeGreaterThan(setGoal);
+ expect(branch).toContain('dispatchDeferredUiAssignment(sessionId, deferredUiAssignment)');
expect(setGoal).toBeLessThan(unlock);
});
diff --git a/apps/desktop/src/renderer/__tests__/remoteCollabHandoff.test.ts b/apps/desktop/src/renderer/__tests__/remoteCollabHandoff.test.ts
index cd1b9337db..0595d0a988 100644
--- a/apps/desktop/src/renderer/__tests__/remoteCollabHandoff.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteCollabHandoff.test.ts
@@ -59,7 +59,11 @@ describe('enableRemoteCollabForSession', () => {
});
it('成功路径:回传 worker session,并 fire-and-forget 刷镜像', async () => {
- enableOrca.mockResolvedValue({ workerSessionId: 'worker-1' });
+ enableOrca.mockResolvedValue({
+ workerSessionId: 'worker-1',
+ dispatched: false,
+ uiAssignmentSnapshotBeforeMs: 456,
+ });
await expect(enableRemoteCollabForSession(params)).resolves.toEqual({
focusWorkerSessionId: 'worker-1',
@@ -69,6 +73,78 @@ describe('enableRemoteCollabForSession', () => {
expect(listWorkersByLead).not.toHaveBeenCalled();
});
+ it('新被控端延后 UI 派单,并返回 accepted 后使用的远程交接凭据', async () => {
+ getCapabilities.mockResolvedValue({
+ supportsOrcaWorkerPermissionMode: true,
+ supportsDeferredOrcaUiAssignment: true,
+ });
+ enableOrca.mockResolvedValue({
+ workerSessionId: 'worker-1',
+ dispatched: false,
+ uiAssignmentSnapshotBeforeMs: 456,
+ });
+ const options = {
+ workerAgent: 'codex' as const,
+ delegateTask: ' Review this PR ',
+ deferDelegateTask: true,
+ };
+
+ await expect(enableRemoteCollabForSession({ ...params, options })).resolves.toEqual({
+ focusWorkerSessionId: 'worker-1',
+ deferredUiAssignment: {
+ workerSessionId: 'worker-1',
+ initialTask: 'Review this PR',
+ snapshotBeforeMs: 456,
+ deviceId: 'dev-1',
+ },
+ });
+ expect(enableOrca).toHaveBeenCalledWith('lead-1', {
+ ...options,
+ delegateTask: 'Review this PR',
+ });
+ });
+
+ it('旧被控端删除 defer 字段并沿用 enableOrca 即时派单', async () => {
+ getCapabilities.mockResolvedValue({ supportsOrcaWorkerPermissionMode: true });
+ enableOrca.mockResolvedValue({ workerSessionId: 'worker-1' });
+
+ await expect(
+ enableRemoteCollabForSession({
+ ...params,
+ pendingLeadInput: 'Continue the sidebar work',
+ options: {
+ workerAgent: 'codex',
+ delegateTask: 'Review this PR',
+ deferDelegateTask: true,
+ },
+ }),
+ ).resolves.toEqual({ focusWorkerSessionId: 'worker-1' });
+ expect(enableOrca).toHaveBeenCalledWith('lead-1', {
+ workerAgent: 'codex',
+ delegateTask: expect.stringContaining(
+ 'Review this PR\n\nPending Lead input:',
+ ),
+ });
+ });
+
+ it('capability 与 mutation 间降级时,以实际旧响应为准,不二次派单', async () => {
+ getCapabilities.mockResolvedValue({
+ supportsOrcaWorkerPermissionMode: true,
+ supportsDeferredOrcaUiAssignment: true,
+ });
+ // 旧 handler 会忽略 deferDelegateTask、即时派单,且不会返回新字段。
+ enableOrca.mockResolvedValue({ workerSessionId: 'worker-1', dispatched: true });
+
+ await expect(enableRemoteCollabForSession({
+ ...params,
+ options: {
+ workerAgent: 'codex',
+ delegateTask: 'Review this PR',
+ deferDelegateTask: true,
+ },
+ })).resolves.toEqual({ focusWorkerSessionId: 'worker-1' });
+ });
+
it('权威失败(如 PRECONDITION_FAILED):原样抛出,不回查', async () => {
enableOrca.mockRejectedValue(new Error('[PRECONDITION_FAILED] collaboration is disabled'));
@@ -88,6 +164,27 @@ describe('enableRemoteCollabForSession', () => {
expect(listWorkersByLead).toHaveBeenCalledWith('lead-1');
});
+ it('deferred enable 超时后只报告派单终态不确定,不冒险二次派发', async () => {
+ getCapabilities.mockResolvedValue({
+ supportsOrcaWorkerPermissionMode: true,
+ supportsDeferredOrcaUiAssignment: true,
+ });
+ enableOrca.mockRejectedValue(timeoutError());
+ listWorkersByLead.mockResolvedValue([{ sessionId: 'worker-late', id: 'w1', status: 'idle' }]);
+
+ await expect(enableRemoteCollabForSession({
+ ...params,
+ options: {
+ workerAgent: 'codex',
+ delegateTask: 'Review this PR',
+ deferDelegateTask: true,
+ },
+ })).resolves.toEqual({
+ focusWorkerSessionId: 'worker-late',
+ assignmentUnconfirmed: true,
+ });
+ });
+
it('隧道超时 + 被控端确实没建成:fail-closed 抛原始超时', async () => {
enableOrca.mockRejectedValue(timeoutError());
listWorkersByLead.mockResolvedValue([]);
diff --git a/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts b/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts
index 4058104a62..9a5fb3fa21 100644
--- a/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts
@@ -97,7 +97,9 @@ describe('CCAgentSessionView 接线不变式', () => {
expect(sessionViewSrc).toContain(
"const dispatch = pending.deliveryMode === 'steer' ? steerMessage : sendMessage;",
);
- expect(sessionViewSrc).toContain('if (accepted) pending.onDeferredAccepted?.();');
+ expect(sessionViewSrc).toContain('if (accepted) {');
+ expect(sessionViewSrc).toContain('pending.onDeferredAccepted?.();');
+ expect(sessionViewSrc).toContain('dispatchDeferredUiAssignment(sessionId, undefined).catch');
expect(sessionViewSrc).toContain(
'...(opts?.onDeferredAccepted ? { onDeferredAccepted: opts.onDeferredAccepted } : {})',
);
diff --git a/apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.ts b/apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.ts
index 2a3188548a..075ea6c9a4 100644
--- a/apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.ts
+++ b/apps/desktop/src/renderer/__tests__/reviewCommandDispatch.test.ts
@@ -19,7 +19,8 @@ describe('/review command dispatch', () => {
expect(dispatchSource).toContain('await window.electronAPI.maker.startReview({');
expect(dispatchSource).toContain('return { handled: true, accepted: true, message }');
expect(dispatchSource).toContain('return { handled: true, accepted: false, message }');
- expect(sessionViewSource).toContain('if (slashDispatch.handled) return slashDispatch.accepted');
+ expect(sessionViewSource).toContain('if (slashDispatch.handled) {');
+ expect(sessionViewSource).toContain('waitForLeadHistory: false');
expect(dispatchSource.indexOf('.startReview({')).toBeLessThan(
dispatchSource.indexOf('void dispatchCommand(hit'),
);
@@ -62,6 +63,8 @@ describe('/review command dispatch', () => {
});
it('only clears a deferred composer after Main accepts the Review', () => {
- expect(dispatchSource).toContain('if (slashDispatch.accepted) pending.onDeferredAccepted?.();');
+ expect(dispatchSource).toContain('if (slashDispatch.accepted) {');
+ expect(dispatchSource).toContain('pending.onDeferredAccepted?.();');
+ expect(dispatchSource).toContain('waitForLeadHistory: false');
});
});
diff --git a/apps/desktop/src/renderer/contexts/AuthContext.tsx b/apps/desktop/src/renderer/contexts/AuthContext.tsx
index 000f296f94..e914298fd6 100644
--- a/apps/desktop/src/renderer/contexts/AuthContext.tsx
+++ b/apps/desktop/src/renderer/contexts/AuthContext.tsx
@@ -37,6 +37,7 @@ import { isGhostPanelWindow } from '@/lib/ghostPanelWindow';
import { setNewMakerDraftOwner } from '@/state/newMakerDraft';
import { setComposerDraftOwner } from '@/lib/composerDraftStore';
import { setPendingHandoffOwner } from '@/state/pendingFirstMessage';
+import { setDeferredUiAssignmentOwner } from '@/features/cc-agent/deferredUiAssignment';
import { invalidateProvidersSnapshot } from '@/lib/providersSnapshotStore';
import { preloadLocalCatalogSnapshot } from '@/lib/localCatalogSnapshot';
import { getDataOwnerGeneration, setDataOwnerGeneration } from './dataOwnerGeneration';
@@ -181,6 +182,7 @@ export function AuthProvider({
setNewMakerDraftOwner(state.dataOwnerId);
setComposerDraftOwner(state.dataOwnerId);
setPendingHandoffOwner(state.dataOwnerId);
+ setDeferredUiAssignmentOwner(state.dataOwnerId);
setUserPromptOwner(state.dataOwnerId);
if (ownerChanged) {
setMemorySettingsOwner(state.dataOwnerId);
@@ -350,6 +352,7 @@ export function AuthProvider({
activeDataOwnerGenerationRef.current = state.ownerGeneration;
setComposerDraftOwner(state.dataOwnerId);
setPendingHandoffOwner(state.dataOwnerId);
+ setDeferredUiAssignmentOwner(state.dataOwnerId);
setMode(state.mode);
setDataOwnerId(state.dataOwnerId);
setCanEnterApp(state.canEnterApp);
@@ -364,6 +367,7 @@ export function AuthProvider({
activeDataOwnerGenerationRef.current = state.ownerGeneration;
setComposerDraftOwner(state.dataOwnerId);
setPendingHandoffOwner(state.dataOwnerId);
+ setDeferredUiAssignmentOwner(state.dataOwnerId);
setMode(state.mode);
setDataOwnerId(state.dataOwnerId);
setCanEnterApp(state.canEnterApp);
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 4a5f2459d0..c08c057ee8 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -219,6 +219,11 @@ import { getCollaborationStartErrorMessage } from './collaborationErrors';
import { useCollabProjectPolicy } from './hooks/useCollabProjectPolicy';
import { resolveCollabEntryPolicy } from './collabEntryPolicy';
import { consumePendingRemoteCollab, enableRemoteCollabForSession } from './remoteCollabHandoff';
+import {
+ dispatchDeferredUiAssignment,
+ getRecoverableDeferredUiAssignment,
+ type DeferredUiAssignment,
+} from './deferredUiAssignment';
import { shouldFallbackVendorModel } from './lib/vendorModelFallback';
import { localizeAgentStatus } from './lib/localizeAgentStatus';
import { createSessionRefreshSequence } from './lib/sessionRefreshSequence';
@@ -1420,6 +1425,31 @@ export function CCAgentSessionView({
updateQueueItem,
chatDisplaySnapshot,
} = useCCAgentChat(sessionId, handleTitleUpdate, { chatRealtime });
+ useEffect(() => {
+ if (!sessionId || !isOrcaLeadSessionView || !historyLoaded) return;
+ const recoveredAssignment = getRecoverableDeferredUiAssignment({
+ leadSessionId: sessionId,
+ messages,
+ deviceId: remoteDeviceId,
+ remoteRouteUnavailable: remoteConn !== 'connected',
+ });
+ if (!recoveredAssignment) return;
+ // Renderer may exit after the Lead input becomes durable but before the accepted callback
+ // starts the second-stage Worker dispatch. A persisted pending receipt is safe to consume once
+ // this Lead's history has loaded a user row; the main-side gate still enforces snapshot time.
+ void dispatchDeferredUiAssignment(sessionId, undefined).catch((err) => {
+ log.error('recover persisted deferred Worker assignment after session mount failed', err);
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ });
+ }, [
+ historyLoaded,
+ isOrcaLeadSessionView,
+ messages,
+ remoteConn,
+ remoteDeviceId,
+ sessionId,
+ t,
+ ]);
// 展示引擎可乐观跟随 intent;真实 event reducer 仍只读 store.agentKind。
const displayAgentKind = agentSwitchIntent?.target ?? dbToMakerAgentKind(session?.agentKind);
// 真实会话 agentKind(pending switch intent 不影响)——压缩分流必须用它,
@@ -2620,7 +2650,18 @@ export function CCAgentSessionView({
},
);
if (slashDispatch.handled) {
- if (slashDispatch.accepted) pending.onDeferredAccepted?.();
+ if (slashDispatch.accepted) {
+ pending.onDeferredAccepted?.();
+ const resumedSessionId = sessionId;
+ if (resumedSessionId) {
+ void dispatchDeferredUiAssignment(resumedSessionId, undefined, {
+ waitForLeadHistory: false,
+ }).catch((err) => {
+ log.error('recover deferred Worker assignment after slash command failed', err);
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ });
+ }
+ }
return;
}
@@ -2683,7 +2724,16 @@ export function CCAgentSessionView({
}
: undefined,
);
- if (accepted) pending.onDeferredAccepted?.();
+ if (accepted) {
+ pending.onDeferredAccepted?.();
+ const resumedSessionId = sessionId;
+ if (resumedSessionId) {
+ void dispatchDeferredUiAssignment(resumedSessionId, undefined).catch((err) => {
+ log.error('recover deferred Worker assignment after user message failed', err);
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ });
+ }
+ }
} catch (error) {
log.warn(
'pending send after working directory selection failed:',
@@ -2818,7 +2868,17 @@ export function CCAgentSessionView({
: await maybeDispatchDesktopSlashCommand(message, files, {
piRuntimeRetryDelaysMs: PI_RUNTIME_SKILL_RETRY_DELAYS_MS,
});
- if (slashDispatch.handled) return slashDispatch.accepted;
+ if (slashDispatch.handled) {
+ if (slashDispatch.accepted && sessionId) {
+ void dispatchDeferredUiAssignment(sessionId, undefined, {
+ waitForLeadHistory: false,
+ }).catch((err) => {
+ log.error('recover deferred Worker assignment after slash command failed', err);
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ });
+ }
+ return slashDispatch.accepted;
+ }
message = slashDispatch.message;
if (message !== originalMessage && opts) {
opts = {
@@ -2942,7 +3002,7 @@ export function CCAgentSessionView({
...(opts?.onDeferredAccepted ? { onDeferredAccepted: opts.onDeferredAccepted } : {}),
};
if (deliveryMode === 'steer') {
- return steerMessage(
+ const accepted = await steerMessage(
message,
model,
effort,
@@ -2952,8 +3012,15 @@ export function CCAgentSessionView({
mentions,
sendOptions,
);
+ if (accepted && sessionId) {
+ void dispatchDeferredUiAssignment(sessionId, undefined).catch((err) => {
+ log.error('recover deferred Worker assignment after user message failed', err);
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ });
+ }
+ return accepted;
}
- return sendMessage(
+ const accepted = await sendMessage(
message,
model,
effort,
@@ -2963,6 +3030,13 @@ export function CCAgentSessionView({
mentions,
sendOptions,
);
+ if (accepted && sessionId) {
+ void dispatchDeferredUiAssignment(sessionId, undefined).catch((err) => {
+ log.error('recover deferred Worker assignment after user message failed', err);
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ });
+ }
+ return accepted;
},
[
maybeDispatchDesktopSlashCommand,
@@ -3352,6 +3426,7 @@ export function CCAgentSessionView({
}
pendingConsumedRef.current = true;
void (async () => {
+ let deferredUiAssignment = pending.deferredUiAssignment;
// device-link 草稿开了协同:先把协同开起来,再发首轮 —— 否则 Lead 的第一个 turn
// 拿不到 cindy_orca 工具。等待放在这里而不是 draft route,是为了不让「对端会话已
// 建好、用户输入还只在内存里」的窗口跟着一次可能 30s 的隧道往返一起变长(见
@@ -3366,7 +3441,7 @@ export function CCAgentSessionView({
if (holdComposer) setRemoteHandoffPreparing(true);
try {
if (pending.remoteCollab) {
- const ok = await consumePendingRemoteCollab(pending.remoteCollab, {
+ const remoteCollab = await consumePendingRemoteCollab(pending.remoteCollab, {
leadSessionId: sessionId,
logTag: 'pending first message',
onFailed: (err) =>
@@ -3376,8 +3451,11 @@ export function CCAgentSessionView({
continueAsSingleSession: true,
}),
),
+ onAssignmentUnconfirmed: () =>
+ toast.error(t('newChat.collaboration.assignmentFailed')),
});
- if (ok) {
+ if (remoteCollab.ok) {
+ deferredUiAssignment = remoteCollab.deferredUiAssignment;
void sessionsStore.forceRefresh('active');
void revealOrcaWorkersTab(sessionId).catch((revealErr) => {
log.warn('revealOrcaWorkersTab after pending collab failed', revealErr);
@@ -3405,6 +3483,19 @@ export function CCAgentSessionView({
});
}
await deliverRecoverableHandoff(sessionId, () => true);
+ if (slashDispatch.accepted) {
+ void dispatchDeferredUiAssignment(sessionId, deferredUiAssignment, {
+ // Desktop slash commands are consumed by their own handlers and intentionally do
+ // not create a normal Lead user-history row. The command's accepted result is the
+ // ordering boundary for the independent Worker assignment.
+ waitForLeadHistory: false,
+ }).catch((err) => {
+ log.error('deferred Worker assignment after slash command failed', err);
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ });
+ } else if (deferredUiAssignment) {
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ }
return;
}
const pendingAgentReferences = pending.agentReferences
@@ -3431,7 +3522,7 @@ export function CCAgentSessionView({
: undefined;
// 必须 await:sendMessage 在设备离线 / 访问被撤销 / 远端 enqueue 拒绝时不抛错,
// 而是 resolve false —— 不等它就丢副本,正文会从界面和磁盘上一起消失(codex P1)。
- await deliverRecoverableHandoff(sessionId, () =>
+ const delivered = await deliverRecoverableHandoff(sessionId, () =>
sendMessage(
pendingText,
session.model,
@@ -3461,6 +3552,14 @@ export function CCAgentSessionView({
: undefined,
),
);
+ if (delivered) {
+ void dispatchDeferredUiAssignment(sessionId, deferredUiAssignment).catch((err) => {
+ log.error('deferred Worker assignment after first message failed', err);
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ });
+ } else if (deferredUiAssignment) {
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ }
} finally {
if (holdComposer) setRemoteHandoffPreparing(false);
}
@@ -3494,6 +3593,7 @@ export function CCAgentSessionView({
}
pendingGoalConsumedRef.current = true;
void (async () => {
+ let deferredUiAssignment: DeferredUiAssignment | undefined;
// 锁必须覆盖**从消费 pendingGoal 到 setGoal 结束**的全程,不能只包住开协同那段:
// 前面的 subscribe 与后面的 setGoal 同样是隧道 invoke、同样可能走到 30s 超时,
// 锁在它们之外的话,这两个窗口里用户补发的消息会抢在目标首轮之前跑
@@ -3510,7 +3610,7 @@ export function CCAgentSessionView({
}
// 与首条消息同款:目标首轮同样要排在协同之后(见上方 pending 消费的注释)。
if (pendingGoal.remoteCollab) {
- const ok = await consumePendingRemoteCollab(pendingGoal.remoteCollab, {
+ const remoteCollab = await consumePendingRemoteCollab(pendingGoal.remoteCollab, {
leadSessionId: sessionId,
logTag: 'pending goal',
onFailed: (err) =>
@@ -3520,8 +3620,11 @@ export function CCAgentSessionView({
continueAsSingleSession: true,
}),
),
+ onAssignmentUnconfirmed: () =>
+ toast.error(t('newChat.collaboration.assignmentFailed')),
});
- if (ok) {
+ if (remoteCollab.ok) {
+ deferredUiAssignment = remoteCollab.deferredUiAssignment;
void sessionsStore.forceRefresh('active');
void revealOrcaWorkersTab(sessionId).catch((revealErr) => {
log.warn('revealOrcaWorkersTab after pending goal collab failed', revealErr);
@@ -3531,7 +3634,7 @@ export function CCAgentSessionView({
// 与首条消息同一条路:交付成功才丢副本。setGoal 失败会抛错,
// deliver 里 forget 根本执行不到,副本自然保留 —— 目标正文是用户敲的,
// 留着下次进本会话回填,比只弹一句"失败"更有用。
- await deliverRecoverableHandoff(sessionId, async () => {
+ const delivered = await deliverRecoverableHandoff(sessionId, async () => {
await goalApiFor(sessionId).setGoal({
sessionId,
objective: pendingGoal.objective,
@@ -3539,10 +3642,19 @@ export function CCAgentSessionView({
});
return true;
});
+ if (delivered) {
+ void dispatchDeferredUiAssignment(sessionId, deferredUiAssignment).catch((err) => {
+ log.error('deferred Worker assignment after goal failed', err);
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ });
+ }
toast.success(t('goal.toast.set'));
} catch (err) {
log.warn('pending goal setGoal failed:', err);
toast.error(t('goal.toast.failed'));
+ if (deferredUiAssignment) {
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ }
} finally {
setRemoteHandoffPreparing(false);
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index 76c120b7ab..913ff81b8e 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -130,6 +130,12 @@ import { useCrossAgentMigrationDialog } from '@/hooks/useCrossAgentConvertPrompt
import { getCollaborationStartErrorMessage } from './collaborationErrors';
import { resolveCollabEntryPolicy } from './collabEntryPolicy';
import { useCollabProjectPolicy } from './hooks/useCollabProjectPolicy';
+import {
+ createDeferredUiAssignment,
+ dispatchDeferredUiAssignment,
+ rememberDeferredUiAssignment,
+ type DeferredUiAssignment,
+} from './deferredUiAssignment';
import { CrossAgentConvertDialog } from '@/components/ui/cross-agent-convert-dialog';
import type { MakerVendor } from '@/lib/ccAgent.types';
import {
@@ -364,6 +370,7 @@ function draftEnableOrcaOptions(
collab: CollabDraft,
providers: ProviderView[],
providersReady: boolean,
+ deferDelegateTask = false,
) {
const preferredAgent: 'claude-code' | 'codex' | 'pi' =
collab.worker === 'codex' ? 'codex' : collab.worker === 'pi' ? 'pi' : 'claude-code';
@@ -392,7 +399,8 @@ function draftEnableOrcaOptions(
workerAgent,
role: cfg.role,
label: createWorkerLabel(cfg.role, []),
- delegateTask: cfg.initialTask || undefined,
+ delegateTask: cfg.initialTask,
+ ...(deferDelegateTask ? { deferDelegateTask: true } : {}),
workerPermissionMode: cfg.workerPermissionMode,
};
}
@@ -428,7 +436,8 @@ function draftEnableOrcaOptions(
effort: cfg.effort as 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | undefined,
fast: cfg.fast,
providerId,
- delegateTask: cfg.initialTask || undefined,
+ delegateTask: cfg.initialTask,
+ ...(deferDelegateTask ? { deferDelegateTask: true } : {}),
workerPermissionMode: cfg.workerPermissionMode,
};
}
@@ -3284,10 +3293,12 @@ export function NewMakerDraftRoute() {
? {
remoteCollab: {
deviceId,
+ pendingLeadInput: message,
options: draftEnableOrcaOptions(
effectiveCollab,
deviceProviders,
!deviceProvidersLoading,
+ true,
),
},
}
@@ -3487,16 +3498,25 @@ export function NewMakerDraftRoute() {
// 才进入 1.6s 平滑期, overlay 从 "空 ChatView" 自然过渡到 "已在
// streaming 的 ChatView", 不暴露中间空窗。clear 时机见本 async 块末尾。
+ let deferredUiAssignment: DeferredUiAssignment | undefined;
if (shouldEnableCollab) {
try {
+ const orcaOptions = draftEnableOrcaOptions(
+ effectiveCollab,
+ localProviders,
+ !localProvidersLoading,
+ true,
+ );
const result = await window.electronAPI.maker.enableOrca(
newSession.id,
- draftEnableOrcaOptions(
- effectiveCollab,
- localProviders,
- !localProvidersLoading,
- ),
+ orcaOptions,
);
+ deferredUiAssignment = createDeferredUiAssignment({
+ options: orcaOptions,
+ workerSessionId: result.workerSessionId,
+ snapshotBeforeMs: result.uiAssignmentSnapshotBeforeMs,
+ });
+ rememberDeferredUiAssignment(newSession.id, deferredUiAssignment);
// worktree 创建在后台完成,组件可能已经切走;这里读取当前 URL,
// 避免用 render 时捕获的旧路由误判。
if (getCurrentRoutePath() === `/cc-agent/${newSession.id}`) {
@@ -3538,7 +3558,17 @@ export function NewMakerDraftRoute() {
: {}),
},
);
- if (accepted) opts?.onAccepted?.();
+ if (accepted) {
+ opts?.onAccepted?.();
+ void dispatchDeferredUiAssignment(newSession.id, deferredUiAssignment).catch(
+ (err) => {
+ log.error('[draft worktree send] deferred Worker assignment failed', err);
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ },
+ );
+ } else if (deferredUiAssignment) {
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ }
// sendMessage 会先同步 push user message,再异步返回 enqueue 是否接受。
// await 完成时 messages 已经有 user bubble + isStreaming=true,
// 此时 clear 让 worktreePreparing 进入 1.6s 平滑期 (overlay 自然
@@ -3613,12 +3643,25 @@ export function NewMakerDraftRoute() {
// 不阻断 send 流程。worker 类型由 popover 选择,失败回退到单 session 路由。
let orcaNavTarget: string | null = null;
let orcaWorkersRevealState: { focusWorkerSessionId: string } | null = null;
+ let deferredUiAssignment: DeferredUiAssignment | undefined;
if (shouldEnableCollab) {
try {
+ const orcaOptions = draftEnableOrcaOptions(
+ effectiveCollab,
+ localProviders,
+ !localProvidersLoading,
+ true,
+ );
const result = await window.electronAPI.maker.enableOrca(
newSession.id,
- draftEnableOrcaOptions(effectiveCollab, localProviders, !localProvidersLoading),
+ orcaOptions,
);
+ deferredUiAssignment = createDeferredUiAssignment({
+ options: orcaOptions,
+ workerSessionId: result.workerSessionId,
+ snapshotBeforeMs: result.uiAssignmentSnapshotBeforeMs,
+ });
+ rememberDeferredUiAssignment(newSession.id, deferredUiAssignment);
orcaNavTarget = `/cc-agent/${newSession.id}`;
orcaWorkersRevealState = { focusWorkerSessionId: result.workerSessionId };
} catch (err) {
@@ -3642,6 +3685,7 @@ export function NewMakerDraftRoute() {
...(opts?.slashCommandRanges !== undefined
? { slashCommandRanges: opts.slashCommandRanges }
: {}),
+ ...(deferredUiAssignment ? { deferredUiAssignment } : {}),
});
opts?.onAccepted?.();
// 草稿已经成功移交给新会话(setPending),清掉 NEW_MAKER_DRAFT_KEY
@@ -4017,10 +4061,12 @@ export function NewMakerDraftRoute() {
? {
remoteCollab: {
deviceId,
+ pendingLeadInput: objective,
options: draftEnableOrcaOptions(
effectiveCollab,
deviceProviders,
!deviceProvidersLoading,
+ true,
),
},
}
@@ -4195,12 +4241,25 @@ export function NewMakerDraftRoute() {
// session 不匹配返回 stale-context(codex P2)——与 Send 路径同口径,把 reveal
// 塞进 navigate state,由 CCAgentSessionView mount 后消费。
let orcaWorkersRevealState: { focusWorkerSessionId: string } | null = null;
+ let deferredUiAssignment: DeferredUiAssignment | undefined;
if (shouldEnableCollab) {
try {
+ const orcaOptions = draftEnableOrcaOptions(
+ effectiveCollab,
+ localProviders,
+ !localProvidersLoading,
+ true,
+ );
const result = await window.electronAPI.maker.enableOrca(
newSession.id,
- draftEnableOrcaOptions(effectiveCollab, localProviders, !localProvidersLoading),
+ orcaOptions,
);
+ deferredUiAssignment = createDeferredUiAssignment({
+ options: orcaOptions,
+ workerSessionId: result.workerSessionId,
+ snapshotBeforeMs: result.uiAssignmentSnapshotBeforeMs,
+ });
+ rememberDeferredUiAssignment(newSession.id, deferredUiAssignment);
orcaWorkersRevealState = { focusWorkerSessionId: result.workerSessionId };
} catch (err) {
log.error('[draft goal] enableOrca failed (continuing as single session)', err);
@@ -4212,11 +4271,18 @@ export function NewMakerDraftRoute() {
// setGoal 内部 ensureSession(拉起 agent)+ 发首轮(带目标指令)。
try {
await window.electronAPI.maker.setGoal({ sessionId: newSession.id, objective, limits });
+ void dispatchDeferredUiAssignment(newSession.id, deferredUiAssignment).catch((err) => {
+ log.error('[draft goal] deferred Worker assignment failed', err);
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ });
} catch (err) {
// 首轮没发出去 → 下面的 autoNameSession 也不会跑,权威标题永不回流。
// 不撤回的话标题预览会永久盖着 DB 里的哨兵(理由同 worktree 分支的
// restoreFirstMessageDraft)。异常照旧抛给调用方展示。
if (optimisticGoalTitle) emitAutoTitlePreviewCleared(newSession.id);
+ if (deferredUiAssignment) {
+ toast.error(t('newChat.collaboration.assignmentFailed'));
+ }
throw err;
}
// 自动起名:/goal 新建的会话不经普通发送路径,scheduleAutoName 漏触发 → 标题会停在默认。
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/deferredUiAssignment.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/deferredUiAssignment.test.ts
new file mode 100644
index 0000000000..4e4b7f5c0b
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/deferredUiAssignment.test.ts
@@ -0,0 +1,302 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const remoteDispatch = vi.fn();
+vi.mock('@/lib/makerTransport', () => ({
+ makerApiForDevice: () => ({ dispatchOrcaUiAssignment: remoteDispatch }),
+}));
+
+import {
+ createDeferredUiAssignment,
+ dispatchDeferredUiAssignment,
+ getRecoverableDeferredUiAssignment,
+ rememberDeferredUiAssignment,
+ setDeferredUiAssignmentOwner,
+} from '../deferredUiAssignment';
+
+const localDispatch = vi.fn();
+const storage = new Map<string, string>();
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ storage.clear();
+ vi.stubGlobal('window', {
+ electronAPI: { maker: { dispatchOrcaUiAssignment: localDispatch } },
+ localStorage: {
+ getItem: (key: string) => storage.get(key) ?? null,
+ setItem: (key: string, value: string) => storage.set(key, value),
+ removeItem: (key: string) => storage.delete(key),
+ },
+ });
+ setDeferredUiAssignmentOwner('owner-1');
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('deferredUiAssignment', () => {
+ it('只为显式 defer 的非空 initial_task 建立交接凭据', () => {
+ expect(
+ createDeferredUiAssignment({
+ options: {
+ workerAgent: 'codex',
+ delegateTask: ' Review this PR ',
+ deferDelegateTask: true,
+ },
+ workerSessionId: 'worker-1',
+ snapshotBeforeMs: 123,
+ }),
+ ).toEqual({
+ workerSessionId: 'worker-1',
+ initialTask: 'Review this PR',
+ snapshotBeforeMs: 123,
+ });
+ expect(
+ createDeferredUiAssignment({
+ options: { workerAgent: 'codex', delegateTask: 'Review this PR' },
+ workerSessionId: 'worker-1',
+ snapshotBeforeMs: 123,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('accepted 后按交接归属派给本机或指定被控端', async () => {
+ await dispatchDeferredUiAssignment('lead-1', {
+ workerSessionId: 'worker-local',
+ initialTask: 'Review local',
+ snapshotBeforeMs: 101,
+ });
+ await dispatchDeferredUiAssignment('lead-2', {
+ workerSessionId: 'worker-remote',
+ initialTask: 'Review remote',
+ snapshotBeforeMs: 202,
+ deviceId: 'dev-1',
+ });
+
+ expect(localDispatch).toHaveBeenCalledWith(
+ 'lead-1',
+ 'worker-local',
+ 'Review local',
+ 101,
+ true,
+ );
+ expect(remoteDispatch).toHaveBeenCalledWith(
+ 'lead-2',
+ 'worker-remote',
+ 'Review remote',
+ 202,
+ true,
+ );
+ });
+
+ it('可为不会写入 Lead history 的已消费命令跳过历史门控', async () => {
+ await dispatchDeferredUiAssignment(
+ 'lead-1',
+ {
+ workerSessionId: 'worker-1',
+ initialTask: 'Review independently',
+ snapshotBeforeMs: 303,
+ },
+ { waitForLeadHistory: false },
+ );
+
+ expect(localDispatch).toHaveBeenCalledWith(
+ 'lead-1',
+ 'worker-1',
+ 'Review independently',
+ 303,
+ false,
+ );
+ });
+
+ it('持久化 pending 凭据供下一条 accepted 输入恢复,派发前先阻止自动重试', async () => {
+ const assignment = {
+ workerSessionId: 'worker-1',
+ initialTask: 'Review after restart',
+ snapshotBeforeMs: 404,
+ };
+ rememberDeferredUiAssignment('lead-1', assignment);
+
+ localDispatch.mockRejectedValueOnce(new Error('response lost'));
+ await expect(dispatchDeferredUiAssignment('lead-1', undefined)).rejects.toThrow(
+ 'response lost',
+ );
+ await dispatchDeferredUiAssignment('lead-1', undefined);
+
+ // 第一次 invoke 可能已被 host 接受,uncertain 状态不会在下一次自动重试。
+ expect(localDispatch).toHaveBeenCalledTimes(1);
+ });
+
+ it('只用 snapshot 之后已持久化的 Lead user history 恢复 pending 凭据', () => {
+ rememberDeferredUiAssignment('lead-1', {
+ workerSessionId: 'worker-1',
+ initialTask: 'Review after restart',
+ snapshotBeforeMs: 1_000,
+ });
+
+ expect(
+ getRecoverableDeferredUiAssignment({
+ leadSessionId: 'lead-1',
+ messages: [
+ { role: 'user', createdAt: new Date(1_100).toISOString(), isPendingPersist: true },
+ ],
+ remoteRouteUnavailable: false,
+ }),
+ ).toBeUndefined();
+ expect(
+ getRecoverableDeferredUiAssignment({
+ leadSessionId: 'lead-1',
+ messages: [
+ { role: 'user', createdAt: new Date(999).toISOString() },
+ { role: 'assistant', createdAt: new Date(1_100).toISOString() },
+ ],
+ remoteRouteUnavailable: false,
+ }),
+ ).toBeUndefined();
+ expect(
+ getRecoverableDeferredUiAssignment({
+ leadSessionId: 'lead-1',
+ messages: [{ role: 'user', createdAt: new Date(1_000).toISOString() }],
+ remoteRouteUnavailable: false,
+ }),
+ ).toEqual(expect.objectContaining({ workerSessionId: 'worker-1' }));
+ });
+
+ it('远程 receipt 等归属设备恢复在线后才允许消费', () => {
+ rememberDeferredUiAssignment('lead-remote', {
+ workerSessionId: 'worker-remote',
+ initialTask: 'Review remotely',
+ snapshotBeforeMs: 1_000,
+ deviceId: 'device-1',
+ });
+ const history = [{ role: 'user', createdAt: new Date(1_100).toISOString() }];
+
+ expect(
+ getRecoverableDeferredUiAssignment({
+ leadSessionId: 'lead-remote',
+ messages: history,
+ remoteRouteUnavailable: false,
+ }),
+ ).toBeUndefined();
+ expect(
+ getRecoverableDeferredUiAssignment({
+ leadSessionId: 'lead-remote',
+ messages: history,
+ deviceId: 'device-1',
+ remoteRouteUnavailable: true,
+ }),
+ ).toBeUndefined();
+ expect(
+ getRecoverableDeferredUiAssignment({
+ leadSessionId: 'lead-remote',
+ messages: history,
+ deviceId: 'device-1',
+ remoteRouteUnavailable: false,
+ }),
+ ).toEqual(expect.objectContaining({ deviceId: 'device-1' }));
+ });
+
+ it('不恢复无 receipt 或已进入 uncertain 的派单', async () => {
+ expect(
+ getRecoverableDeferredUiAssignment({
+ leadSessionId: 'lead-missing',
+ messages: [{ role: 'user', createdAt: new Date(2_000).toISOString() }],
+ remoteRouteUnavailable: false,
+ }),
+ ).toBeUndefined();
+
+ rememberDeferredUiAssignment('lead-uncertain', {
+ workerSessionId: 'worker-uncertain',
+ initialTask: 'Review once',
+ snapshotBeforeMs: 1_000,
+ });
+ localDispatch.mockRejectedValueOnce(new Error('response lost'));
+ await expect(dispatchDeferredUiAssignment('lead-uncertain', undefined)).rejects.toThrow(
+ 'response lost',
+ );
+ expect(
+ getRecoverableDeferredUiAssignment({
+ leadSessionId: 'lead-uncertain',
+ messages: [{ role: 'user', createdAt: new Date(2_000).toISOString() }],
+ remoteRouteUnavailable: false,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('显式 receipt 与恢复入口并发时,同一 Lead 只派一次', async () => {
+ let release!: () => void;
+ localDispatch.mockImplementationOnce(
+ () => new Promise<void>((resolve) => { release = resolve; }),
+ );
+ const assignment = {
+ workerSessionId: 'worker-1',
+ initialTask: 'Review once',
+ snapshotBeforeMs: 505,
+ };
+ rememberDeferredUiAssignment('lead-1', assignment);
+
+ const explicit = dispatchDeferredUiAssignment('lead-1', assignment);
+ const recovered = dispatchDeferredUiAssignment('lead-1', undefined);
+ expect(localDispatch).toHaveBeenCalledTimes(1);
+ release();
+ await Promise.all([explicit, recovered]);
+
+ expect(localDispatch).toHaveBeenCalledTimes(1);
+ });
+
+ it('派发成功后到达的 stale 显式 receipt 不会再次派单', async () => {
+ const assignment = {
+ workerSessionId: 'worker-stale',
+ initialTask: 'Review once',
+ snapshotBeforeMs: 606,
+ };
+ rememberDeferredUiAssignment('lead-stale', assignment);
+
+ await dispatchDeferredUiAssignment('lead-stale', undefined);
+ await dispatchDeferredUiAssignment('lead-stale', assignment);
+
+ expect(localDispatch).toHaveBeenCalledTimes(1);
+ });
+
+ it('持久存储不可用且首个响应丢失时,内存 claim 仍阻止 stale receipt 重试', async () => {
+ const assignment = {
+ workerSessionId: 'worker-quota',
+ initialTask: 'Review at most once',
+ snapshotBeforeMs: 707,
+ };
+ vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {
+ throw new Error('quota exceeded');
+ });
+ localDispatch.mockRejectedValueOnce(new Error('response lost'));
+
+ await expect(
+ dispatchDeferredUiAssignment('lead-quota', assignment),
+ ).rejects.toThrow('response lost');
+ await dispatchDeferredUiAssignment('lead-quota', assignment);
+
+ expect(localDispatch).toHaveBeenCalledTimes(1);
+ });
+
+ it('读取时把超过七天的 initial_task 从持久存储清掉', async () => {
+ storage.set(
+ 'xdt:deferredUiAssignment:v1:owner-1',
+ JSON.stringify({
+ 'lead-1': {
+ assignment: {
+ workerSessionId: 'worker-1',
+ initialTask: 'expired task',
+ snapshotBeforeMs: 1,
+ },
+ state: 'pending',
+ createdAt: 1,
+ },
+ }),
+ );
+ vi.spyOn(Date, 'now').mockReturnValue(8 * 24 * 60 * 60 * 1000);
+
+ await dispatchDeferredUiAssignment('lead-1', undefined);
+
+ expect(localDispatch).not.toHaveBeenCalled();
+ expect(storage.has('xdt:deferredUiAssignment:v1:owner-1')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/draftWorkerHandoff.test.ts b/apps/desktop/src/renderer/features/cc-agent/__tests__/draftWorkerHandoff.test.ts
new file mode 100644
index 0000000000..3657c19e2d
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/draftWorkerHandoff.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildDraftWorkerInitialTask } from '../draftWorkerHandoff';
+
+describe('buildDraftWorkerInitialTask', () => {
+ it('includes pending Lead input for a controlled device that cannot query it yet', () => {
+ expect(buildDraftWorkerInitialTask(' Review the current work ', ' Implement sidebar filters '))
+ .toBe(`Review the current work
+
+Pending Lead input:
+The Lead has not sent this input yet, so it is not available in Lead session history. Use it only as context for the Worker task above; do not treat it as a replacement task.
+Implement sidebar filters`);
+ });
+
+ it('keeps a self-contained Worker task unchanged when there is no pending Lead input', () => {
+ expect(buildDraftWorkerInitialTask(' Review PR #42 ', ' ')).toBe('Review PR #42');
+ });
+
+ it('does not turn the pending Lead input into a Worker task', () => {
+ expect(buildDraftWorkerInitialTask(' ', 'Implement sidebar filters')).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/deferredUiAssignment.ts b/apps/desktop/src/renderer/features/cc-agent/deferredUiAssignment.ts
new file mode 100644
index 0000000000..aaeb4b16c4
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/deferredUiAssignment.ts
@@ -0,0 +1,195 @@
+import { makerApiForDevice } from '@/lib/makerTransport';
+
+type EnableOrcaOptions = Parameters<typeof window.electronAPI.maker.enableOrca>[1];
+
+export interface DeferredUiAssignment {
+ workerSessionId: string;
+ initialTask: string;
+ /** Worker 创建完成、Lead 首条输入开始之前的本地时间。 */
+ snapshotBeforeMs: number;
+ /** 非空时经 device-link 派给被控端 Worker;缺省走本机 maker。 */
+ deviceId?: string;
+}
+
+const STORAGE_KEY = 'xdt:deferredUiAssignment:v1';
+const STORAGE_TTL_MS = 7 * 24 * 60 * 60 * 1000;
+let activeDataOwnerId: string | null = null;
+const dispatchesInFlight = new Map<string, Promise<void>>();
+const consumedAssignments = new Set<string>();
+
+interface StoredAssignment {
+ assignment: DeferredUiAssignment;
+ state: 'pending' | 'uncertain';
+ createdAt: number;
+}
+
+function storageKey(): string {
+ return activeDataOwnerId
+ ? `${STORAGE_KEY}:${encodeURIComponent(activeDataOwnerId)}`
+ : STORAGE_KEY;
+}
+
+function assignmentKey(leadSessionId: string, workerSessionId: string): string {
+ return `${activeDataOwnerId ?? ''}\u0000${leadSessionId}\u0000${workerSessionId}`;
+}
+
+function readTable(): Record<string, StoredAssignment> {
+ try {
+ const raw = window.localStorage.getItem(storageKey());
+ if (!raw) return {};
+ const parsed = JSON.parse(raw) as Record<string, Partial<StoredAssignment>>;
+ const now = Date.now();
+ const table = Object.fromEntries(
+ Object.entries(parsed).filter(([, value]) =>
+ !!value?.assignment
+ && (value.state === 'pending' || value.state === 'uncertain')
+ && typeof value.createdAt === 'number'
+ && now - value.createdAt <= STORAGE_TTL_MS),
+ ) as Record<string, StoredAssignment>;
+ // Initial tasks are user-authored text. Enforce the declared TTL on read as well as write so
+ // an owner with no later assignments does not retain expired/corrupt content indefinitely.
+ if (Object.keys(table).length !== Object.keys(parsed).length) writeTable(table);
+ return table;
+ } catch {
+ writeTable({});
+ return {};
+ }
+}
+
+function writeTable(table: Record<string, StoredAssignment>): void {
+ try {
+ if (Object.keys(table).length === 0) window.localStorage.removeItem(storageKey());
+ else window.localStorage.setItem(storageKey(), JSON.stringify(table));
+ } catch {
+ // Best-effort recovery only; storage failure must not block the Lead send.
+ }
+}
+
+export function setDeferredUiAssignmentOwner(ownerId: string | null): void {
+ activeDataOwnerId = ownerId;
+}
+
+/** Persist before the Lead delivery boundary so a failed send or renderer restart cannot orphan it. */
+export function rememberDeferredUiAssignment(
+ leadSessionId: string,
+ assignment: DeferredUiAssignment | undefined,
+): void {
+ if (!assignment) return;
+ consumedAssignments.delete(assignmentKey(leadSessionId, assignment.workerSessionId));
+ const table = readTable();
+ table[leadSessionId] = { assignment, state: 'pending', createdAt: Date.now() };
+ writeTable(table);
+}
+
+/**
+ * enableOrca 已建好 Worker、但本次明确要求延后派单时,保存最小交接凭据。
+ * raw initialTask 保留到 accepted 点再由 main 包装 UI handoff,避免 renderer
+ * 复制 prompt 规则。
+ */
+export function createDeferredUiAssignment(params: {
+ options: EnableOrcaOptions;
+ workerSessionId: string;
+ snapshotBeforeMs: number;
+ deviceId?: string;
+}): DeferredUiAssignment | undefined {
+ if (params.options.deferDelegateTask !== true) return undefined;
+ const initialTask = params.options.delegateTask?.trim();
+ if (!initialTask) return undefined;
+ return {
+ workerSessionId: params.workerSessionId,
+ initialTask,
+ snapshotBeforeMs: params.snapshotBeforeMs,
+ ...(params.deviceId ? { deviceId: params.deviceId } : {}),
+ };
+}
+
+export function getRecoverableDeferredUiAssignment(params: {
+ leadSessionId: string;
+ messages: ReadonlyArray<{
+ role: string;
+ createdAt?: string;
+ isPendingPersist?: boolean;
+ }>;
+ /** Current device route after sticky-origin recovery; undefined means local/unresolved. */
+ deviceId?: string;
+ remoteRouteUnavailable: boolean;
+}): DeferredUiAssignment | undefined {
+ const stored = readTable()[params.leadSessionId];
+ if (stored?.state !== 'pending') return undefined;
+ if (
+ stored.assignment.deviceId
+ && (
+ stored.assignment.deviceId !== params.deviceId
+ || params.remoteRouteUnavailable
+ )
+ ) {
+ return undefined;
+ }
+ const hasDurableUserAfterSnapshot = params.messages.some((message) => {
+ if (message.role !== 'user' || message.isPendingPersist === true) return false;
+ const createdAtMs = typeof message.createdAt === 'string'
+ ? Date.parse(message.createdAt)
+ : Number.NaN;
+ return Number.isFinite(createdAtMs)
+ && createdAtMs >= stored.assignment.snapshotBeforeMs;
+ });
+ return hasDurableUserAfterSnapshot ? stored.assignment : undefined;
+}
+
+/** Lead 首条输入 accepted 后才调用;此时 history 查询已能看到该输入。 */
+export function dispatchDeferredUiAssignment(
+ leadSessionId: string,
+ assignment: DeferredUiAssignment | undefined,
+ options: { waitForLeadHistory?: boolean } = {},
+): Promise<void> {
+ const existing = dispatchesInFlight.get(leadSessionId);
+ if (existing) return existing;
+
+ const operation = (async () => {
+ const table = readTable();
+ const stored = table[leadSessionId];
+ // The persisted state is authoritative even when a caller still holds the original in-memory
+ // receipt. Once an earlier invoke is uncertain, a stale explicit receipt must not retry it.
+ if (stored?.state === 'uncertain') return;
+ if (
+ !stored
+ && assignment
+ && consumedAssignments.has(assignmentKey(leadSessionId, assignment.workerSessionId))
+ ) return;
+ const target = stored?.state === 'pending' ? stored.assignment : assignment;
+ if (!target) return;
+ // Persist the ambiguity boundary before the invoke. A crash or lost response after this point
+ // must never cause an automatic retry of a task that may already be running.
+ table[leadSessionId] = {
+ assignment: target,
+ state: 'uncertain',
+ createdAt: stored?.createdAt ?? Date.now(),
+ };
+ writeTable(table);
+ // Memory is the final at-most-once fence when localStorage is unavailable/full. Claim before
+ // the invoke because a rejection may mean “response lost after host acceptance”, not failure.
+ consumedAssignments.add(assignmentKey(leadSessionId, target.workerSessionId));
+ const maker = target.deviceId
+ ? makerApiForDevice(target.deviceId)
+ : window.electronAPI.maker;
+ await maker.dispatchOrcaUiAssignment(
+ leadSessionId,
+ target.workerSessionId,
+ target.initialTask,
+ target.snapshotBeforeMs,
+ options.waitForLeadHistory !== false,
+ );
+ const latest = readTable();
+ if (latest[leadSessionId]?.assignment.workerSessionId === target.workerSessionId) {
+ delete latest[leadSessionId];
+ writeTable(latest);
+ }
+ })();
+ dispatchesInFlight.set(leadSessionId, operation);
+ void operation.finally(() => {
+ if (dispatchesInFlight.get(leadSessionId) === operation) {
+ dispatchesInFlight.delete(leadSessionId);
+ }
+ }).catch(() => undefined);
+ return operation;
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/draftWorkerHandoff.ts b/apps/desktop/src/renderer/features/cc-agent/draftWorkerHandoff.ts
new file mode 100644
index 0000000000..14f7d5f3bf
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/draftWorkerHandoff.ts
@@ -0,0 +1,25 @@
+/**
+ * New-task flows create the Worker before the Lead's first input is sent. Older controlled
+ * devices cannot defer assignment until that input is queryable, so preserve the pending text
+ * inline for that mixed-version path. New peers use the Worker-scoped Lead history bridge.
+ *
+ * pendingLeadInput is context only: without an explicit Worker task it cannot start new work.
+ */
+export function buildDraftWorkerInitialTask(
+ initialTask: string | undefined,
+ pendingLeadInput: string | undefined,
+): string | undefined {
+ const task = initialTask?.trim();
+ if (!task) return undefined;
+
+ const pending = pendingLeadInput?.trim();
+ if (!pending) return task;
+
+ return [
+ task,
+ '',
+ 'Pending Lead input:',
+ 'The Lead has not sent this input yet, so it is not available in Lead session history. Use it only as context for the Worker task above; do not treat it as a replacement task.',
+ pending,
+ ].join('\n');
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/remoteCollabHandoff.ts b/apps/desktop/src/renderer/features/cc-agent/remoteCollabHandoff.ts
index 4f0801a8d2..4541601866 100644
--- a/apps/desktop/src/renderer/features/cc-agent/remoteCollabHandoff.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/remoteCollabHandoff.ts
@@ -38,6 +38,12 @@ import {
orcaWorkflowsForDevice,
} from '@/lib/makerTransport';
import { extractIpcError } from '@/utils/ipcError';
+import {
+ createDeferredUiAssignment,
+ rememberDeferredUiAssignment,
+ type DeferredUiAssignment,
+} from './deferredUiAssignment';
+import { buildDraftWorkerInitialTask } from './draftWorkerHandoff';
const log = createLogger('remoteCollabHandoff');
@@ -47,10 +53,13 @@ function remoteWorkerPermissionModeUnsupportedError(): Error {
);
}
-async function assertRemoteWorkerPermissionModeSupport(
+async function readRemoteCollabCapabilities(
deviceId: string,
workerAgent: EnableOrcaOptions['workerAgent'],
-): Promise<void> {
+): Promise<{
+ supportsOrcaWorkerPermissionMode?: boolean;
+ supportsDeferredOrcaUiAssignment?: boolean;
+}> {
const raw = await agentCapabilitiesForDevice(deviceId, workerAgent);
if (
!raw
@@ -60,6 +69,7 @@ async function assertRemoteWorkerPermissionModeSupport(
) {
throw remoteWorkerPermissionModeUnsupportedError();
}
+ return raw;
}
/**
@@ -168,6 +178,8 @@ export interface RemoteCollabEnableParams {
* 在被控端多半不存在,会撞它的精确 preflight。
*/
options: EnableOrcaOptions;
+ /** 新建 Lead 的待发送输入,仅供不支持 deferred handoff 的老被控端兼容。 */
+ pendingLeadInput?: string;
/** 日志前缀,用于区分是哪条创建路径(如 'draft send' / 'draft goal')。 */
logTag: string;
}
@@ -185,17 +197,78 @@ export interface RemoteCollabEnableParams {
*/
export async function enableRemoteCollabForSession(
p: RemoteCollabEnableParams,
-): Promise<{ focusWorkerSessionId: string }> {
+): Promise<{
+ focusWorkerSessionId: string;
+ deferredUiAssignment?: DeferredUiAssignment;
+ assignmentUnconfirmed?: boolean;
+}> {
// 弹窗展示时的 capability 只是一份快照。真正 mutation 前重新向同一被控端确认,
// 防止断线重连后设备降级到旧版本、把显式权限字段静默忽略。
- await assertRemoteWorkerPermissionModeSupport(p.deviceId, p.options.workerAgent);
+ const capabilities = await readRemoteCollabCapabilities(p.deviceId, p.options.workerAgent);
+ const deferDelegateTask =
+ p.options.deferDelegateTask === true
+ && capabilities.supportsDeferredOrcaUiAssignment === true;
+ // 老被控端没有 deferred capability:删掉新字段,沿用它的 enableOrca 即时派单。
+ // 不能在新通道失败后再回退即时派发,否则响应丢失时会把同一任务派两遍。
+ // Even when the capability probe says “new”, preserve the pending Lead text on the wire:
+ // the peer may reconnect/downgrade between capability and mutation. A new handler defers this
+ // wrapped text until history is ready; an old handler still receives the context it cannot query.
+ const enableOptions = (() => {
+ const compatible = { ...p.options };
+ compatible.delegateTask = buildDraftWorkerInitialTask(
+ compatible.delegateTask,
+ p.pendingLeadInput,
+ );
+ if (!deferDelegateTask) delete compatible.deferDelegateTask;
+ return compatible;
+ })();
+ const withDeferredAssignment = (
+ workerSessionId: string,
+ snapshotBeforeMs: number | null,
+ assignmentUnconfirmed = false,
+ ) => {
+ const deferredUiAssignment = deferDelegateTask && snapshotBeforeMs !== null
+ ? createDeferredUiAssignment({
+ // The later assignment can rely on queryable history, so retain the user's raw task;
+ // the legacy Pending Lead input wrapper above exists only for the one-shot enable wire.
+ options: p.options,
+ workerSessionId,
+ snapshotBeforeMs,
+ deviceId: p.deviceId,
+ })
+ : undefined;
+ rememberDeferredUiAssignment(p.leadSessionId, deferredUiAssignment);
+ return {
+ focusWorkerSessionId: workerSessionId,
+ ...(deferredUiAssignment ? { deferredUiAssignment } : {}),
+ ...(assignmentUnconfirmed ? { assignmentUnconfirmed: true } : {}),
+ };
+ };
try {
- const result = await makerApiForDevice(p.deviceId).enableOrca(p.leadSessionId, p.options);
- return { focusWorkerSessionId: result.workerSessionId };
+ const result = await makerApiForDevice(p.deviceId).enableOrca(
+ p.leadSessionId,
+ enableOptions,
+ );
+ return withDeferredAssignment(
+ result.workerSessionId,
+ result.dispatched === false && Number.isFinite(result.uiAssignmentSnapshotBeforeMs)
+ ? result.uiAssignmentSnapshotBeforeMs
+ : null,
+ );
} catch (err) {
if (!isAmbiguousTimeout(err)) throw err;
const recovered = await recoverTimedOutTeam(p);
- if (recovered) return recovered;
+ // enableOrca 响应丢失时拿不到被控端时间;这些 defer 调用只用于刚创建、尚无历史的
+ // Lead,0 可安全表达「等第一条 user 行」,同时不依赖控制端/被控端时钟同步。
+ // 响应丢失时无法证明实际被控端采用了 deferred handler,也无法证明任务尚未派发。
+ // 只恢复 Team 可见性,不生成可二次派发的 receipt。
+ if (recovered) {
+ return withDeferredAssignment(
+ recovered.focusWorkerSessionId,
+ null,
+ deferDelegateTask,
+ );
+ }
throw err;
} finally {
// 被控端刚建出的 worker session 还没进控制端注册表。fire-and-forget(见文件头 ②)。
@@ -222,25 +295,29 @@ export async function enableRemoteCollabForSession(
* 返回 true 表示协同已就绪(调用方据此展开协同 tab)。
*/
export async function consumePendingRemoteCollab(
- pending: { deviceId: string; options: Record<string, unknown> },
+ pending: { deviceId: string; options: Record<string, unknown>; pendingLeadInput?: string },
ctx: {
leadSessionId: string;
logTag: string;
/** 失败时的用户可见提示;调用方注入以复用视图的 i18n / toast。 */
onFailed: (err: unknown) => void;
+ /** Team 已建成,但延迟派单响应丢失,不能安全重试。 */
+ onAssignmentUnconfirmed?: () => void;
},
-): Promise<boolean> {
+): Promise<{ ok: boolean; deferredUiAssignment?: DeferredUiAssignment }> {
try {
- await enableRemoteCollabForSession({
+ const result = await enableRemoteCollabForSession({
deviceId: pending.deviceId,
leadSessionId: ctx.leadSessionId,
options: pending.options as Parameters<typeof window.electronAPI.maker.enableOrca>[1],
+ pendingLeadInput: pending.pendingLeadInput,
logTag: ctx.logTag,
});
- return true;
+ if (result.assignmentUnconfirmed) ctx.onAssignmentUnconfirmed?.();
+ return { ok: true, deferredUiAssignment: result.deferredUiAssignment };
} catch (err) {
log.error(`[${ctx.logTag}] remote enableOrca failed (continuing as single session)`, err);
ctx.onFailed(err);
- return false;
+ return { ok: false };
}
}
diff --git a/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts b/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts
index fd0159dc98..a1581b737c 100644
--- a/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts
+++ b/apps/desktop/src/renderer/hooks/useAgentCapabilities.ts
@@ -115,6 +115,8 @@ export interface AgentCapabilities {
* device-link 老被控端无此字段 → undefined,控制端必须阻止开启协同并提示升级。
*/
supportsOrcaWorkerPermissionMode?: boolean;
+ /** 被控端支持把 UI initial_task 延后到 Lead 首条输入 accepted 后派发。 */
+ supportsDeferredOrcaUiAssignment?: boolean;
/**
* 手动压缩会话上下文能力(pi 原生 compact)。与 maker-core Capabilities.manualCompact
* 同形;device-link 老被控端序列化的 capabilities 无此字段 → undefined = 不支持。
@@ -261,6 +263,7 @@ function parseAgentCapabilities(value: unknown): AgentCapabilities {
!isOptionalBoolean(value.supportsSessionAgentSwitch) ||
!isOptionalBoolean(value.supportsSessionAgentSwitchCas) ||
!isOptionalBoolean(value.supportsOrcaWorkerPermissionMode) ||
+ !isOptionalBoolean(value.supportsDeferredOrcaUiAssignment) ||
!isOptionalCapabilityStatus(value.manualCompact)
) {
throw new Error('Invalid agent capabilities response');
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index c0ffc79942..84553ef5cd 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5709,6 +5709,7 @@
"startFailed": "Failed to start collaboration",
"startFailedContinue": "Failed to start collaboration. Continuing as a single session.",
"createWorkerRefreshFailed": "Unable to refresh Worker status. Please try again.",
+ "assignmentFailed": "The Worker was created, but task assignment could not be confirmed. Check the Worker pane before trying again.",
"openHint": "Bring in a Worker to help",
"disabledHint": "Collaboration is disabled. Enable it in settings.",
"unavailableHint": "Unable to verify the collaboration setting. Try again shortly.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 4006ef96bf..cbdcfba50b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5707,6 +5707,7 @@
"startFailed": "協同の開始に失敗しました",
"startFailedContinue": "協同の開始に失敗しました。単一セッションとして続行します。",
"createWorkerRefreshFailed": "Worker の状態を更新できませんでした。もう一度お試しください。",
+ "assignmentFailed": "Worker は作成されましたが、タスクが割り当てられたか確認できません。再試行する前に Worker パネルを確認してください。",
"openHint": "Worker を呼んで協同する",
"disabledHint": "協同モードは無効です。設定で有効にしてください。",
"unavailableHint": "協同設定を確認できません。しばらくしてから再試行してください。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index ab41fb9d8e..a5064ff810 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5707,6 +5707,7 @@
"startFailed": "협업을 시작하지 못했습니다",
"startFailedContinue": "협업을 시작하지 못했습니다. 단일 세션으로 계속합니다.",
"createWorkerRefreshFailed": "Worker 상태를 새로 고칠 수 없습니다. 다시 시도해 주세요.",
+ "assignmentFailed": "Worker를 만들었지만 작업 할당 여부를 확인할 수 없습니다. 다시 시도하기 전에 Worker 패널을 확인하세요.",
"openHint": "Worker 를 불러 함께 작업",
"disabledHint": "협업 모드가 비활성화되어 있습니다. 설정에서 활성화하세요.",
"unavailableHint": "협업 설정을 확인할 수 없습니다. 잠시 후 다시 시도하세요.",
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 e91472b54f..838da83c28 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5703,6 +5703,7 @@
"startFailed": "开启协同失败",
"startFailedContinue": "开启协同失败,已改为单任务继续",
"createWorkerRefreshFailed": "Worker 状态刷新失败,请稍后重试",
+ "assignmentFailed": "Worker 已创建,但无法确认任务是否派发成功。请先查看 Worker 面板,再决定是否重试",
"openHint": "召集 Worker 协作",
"disabledHint": "协同模式已关闭,请在设置中重新启用",
"unavailableHint": "暂时无法确认协同设置,请稍后重试",
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 b46ec0dfe9..661a2faee4 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -5706,6 +5706,7 @@
"startFailed": "開啟協同失敗",
"startFailedContinue": "開啟協同失敗,已改為單任務繼續",
"createWorkerRefreshFailed": "Worker 狀態重新整理失敗,請稍後重試",
+ "assignmentFailed": "Worker 已建立,但無法確認任務是否派發成功。請先查看 Worker 面板,再決定是否重試",
"openHint": "召集 Worker 協作",
"disabledHint": "協同模式已關閉,請在設定中重新啟用",
"unavailableHint": "暫時無法確認協同設定,請稍後重試",
diff --git a/apps/desktop/src/renderer/lib/makerTransport.ts b/apps/desktop/src/renderer/lib/makerTransport.ts
index 9cc4a355d7..d18c90aa91 100644
--- a/apps/desktop/src/renderer/lib/makerTransport.ts
+++ b/apps/desktop/src/renderer/lib/makerTransport.ts
@@ -72,6 +72,7 @@ export interface RoutableMaker {
// (压缩的是被控端的会话上下文,控制端本机无该 live 会话,固定调本机必 null 静默失败)。
compactSession: FullMaker['compactSession'];
enableOrca: FullMaker['enableOrca'];
+ dispatchOrcaUiAssignment: FullMaker['dispatchOrcaUiAssignment'];
disableOrca: FullMaker['disableOrca'];
input: Pick<
FullMaker['input'],
@@ -174,6 +175,9 @@ function remoteMakerApi(deviceId: string): RoutableMaker {
instructions === undefined ? [sessionId] : [sessionId, instructions],
)) as FullMaker['compactSession'],
enableOrca: t('maker:session:enable-orca') as FullMaker['enableOrca'],
+ dispatchOrcaUiAssignment: t(
+ 'maker:worker:dispatch-ui-assignment',
+ ) as FullMaker['dispatchOrcaUiAssignment'],
disableOrca: t('maker:session:disable-orca') as FullMaker['disableOrca'],
input: {
enqueue: t('maker:input:enqueue') as FullMaker['input']['enqueue'],
@@ -210,9 +214,13 @@ export function makerApiForDevice(deviceId: string): RoutableMaker {
export function agentCapabilitiesForDevice(
deviceId: string,
agentKind: 'claude-code' | 'codex' | 'pi',
-): Promise<{ supportsOrcaWorkerPermissionMode?: boolean }> {
+): Promise<{
+ supportsOrcaWorkerPermissionMode?: boolean;
+ supportsDeferredOrcaUiAssignment?: boolean;
+}> {
return invokeRemote(deviceId, 'maker:get-capabilities', [agentKind]) as Promise<{
supportsOrcaWorkerPermissionMode?: boolean;
+ supportsDeferredOrcaUiAssignment?: boolean;
}>;
}
diff --git a/apps/desktop/src/renderer/state/pendingFirstMessage.ts b/apps/desktop/src/renderer/state/pendingFirstMessage.ts
index 4657dccb17..1a5cfde84b 100644
--- a/apps/desktop/src/renderer/state/pendingFirstMessage.ts
+++ b/apps/desktop/src/renderer/state/pendingFirstMessage.ts
@@ -19,6 +19,7 @@
import type { AttachedFile, MentionedResource } from '@/lib/fileTypes';
import type { PastedTextRange, SlashCommandRange } from '@/lib/imageRef';
import type { AgentInputReference } from '@cindy/maker-shared/agent-input-projection';
+import type { DeferredUiAssignment } from '@/features/cc-agent/deferredUiAssignment';
/**
* device-link 草稿开了协同时,把「开协同」这件事一起交接给 SessionView(issue #1170)。
@@ -34,6 +35,8 @@ export interface PendingRemoteCollab {
deviceId: string;
/** enableOrca 入参,已按被控端的模型 / 供应商目录收窄。 */
options: Record<string, unknown>;
+ /** 老被控端不支持延迟派单时,保留新建 Lead 的待发送输入作为兼容上下文。 */
+ pendingLeadInput?: string;
}
export interface PendingPayload {
@@ -47,6 +50,8 @@ export interface PendingPayload {
slashCommandRanges?: SlashCommandRange[];
/** 非空 = 发首轮之前先在被控端开协同(见 PendingRemoteCollab)。 */
remoteCollab?: PendingRemoteCollab;
+ /** 本机 Worker 已创建但尚未派单;首条消息 accepted 后再派。 */
+ deferredUiAssignment?: DeferredUiAssignment;
/** 调试用——createPending 时刻,过期清理时可参考(目前未做 GC,实际场景 navigate 立即消费)。 */
createdAt: number;
}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 17938290ac..fbaba79d02 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4939,14 +4939,26 @@ interface ElectronAPI {
providerId?: string | null;
/** Worker 创建默认权限;缺省沿用当前偏好,显式值会更新偏好。 */
workerPermissionMode?: 'auto' | 'bypassPermissions';
+ /** 新建 Lead 专用:等首条输入 accepted 且可查询后再派任务。 */
+ deferDelegateTask?: boolean;
},
) => Promise<{
teamId: string;
workerSessionId: string;
workerId: string;
+ dispatched: boolean;
workerPermissionMode: 'auto' | 'bypassPermissions';
+ uiAssignmentSnapshotBeforeMs: number;
}>;
+ dispatchOrcaUiAssignment: (
+ leadSessionId: string,
+ workerSessionId: string,
+ initialTask: string,
+ snapshotBeforeMs: number,
+ waitForLeadHistory: boolean,
+ ) => Promise<unknown>;
+
/**
* F-COLLAB: 关闭 lead session 当前的协同 workflow。
* 销毁所有 Worker session 的 SDK 进程,DB 标 workflow completed +
diff --git a/docs/dev-rules/orca-team-architecture.md b/docs/dev-rules/orca-team-architecture.md
index 87260fee40..64f201ba4a 100644
--- a/docs/dev-rules/orca-team-architecture.md
+++ b/docs/dev-rules/orca-team-architecture.md
@@ -129,6 +129,31 @@ Worker 权限是 **Worker 创建偏好**,与 Agent、模型、effort、Fast
- 工具可见性不是权限边界:`providers.ts` 的 `cindy_orca` provider 没有 per-role `isEnabled` gate,普通 session / worker / lead 的差异必须由 handler 和 host service 拒绝。
- Codex 场景的真实 session 身份来自 MCP request context;`session-context.ts` 用 `AsyncLocalStorage` 提供 `withLiziMcpSessionContext` / `resolveLiziMcpSessionContext`,不能依赖全局 fallback 猜身份。
- renderer 开启协同走 `CCAgentSessionView.tsx` 的 `requestEnableCollab`,MCP 工具通过 `cindy_orca` callback 进入同一组 service。
+- renderer 通过 UI 开启协同且填写了首个任务时,`OrcaLifecycleService.enableTeam` 复用既有
+ `initial_task` 正文,并附带 Lead session id 与按需回查说明。已有 Lead 会话继续即时派单;
+ 新建任务页先用 ready placeholder 建立可恢复的 Worker agent history,但不派发用户任务;等首条
+ 普通输入/目标已被宿主接受且 user history 可查询后,
+ 再通过 `maker:worker:dispatch-ui-assignment` 派发同一份 `initial_task`。Desktop slash command
+ 是被独立 handler 消费、不会形成普通 user history 的控制动作,因此以 command accepted
+ 作为排序边界,不等待不存在的 history 行;command rejected 或普通输入/目标交付失败时
+ 不派 Worker,并明确提示用户到 Worker 面板确认状态。
+- 二段派单凭据在 Lead 首条输入 accepted 前持久化;若 renderer 在 accepted 后、实际 invoke 前退出,
+ Lead 会话重新挂载并读到 user history 后会自动消费仍为 `pending` 的凭据。invoke 前先转为
+ `uncertain`,配合进程内 tombstone,保证响应丢失、重启恢复和迟到 receipt 不会自动重复派单。
+ 多个窗口可能同时恢复同一条 `pending`,因此 Main 进程还要按 Lead、Worker 与快照时间建立
+ 共享 claim;同一 assignment 的并发或后续请求共用第一次派发结果,最终只调用一次 Worker
+ 投递。
+- Worker 侧按需查询统一走 `orca_worker_bridge.read_lead_history`:工具从已认证的
+ `worker_id + worker session` 归属反查唯一 Lead,调用方不能指定任意 session;只返回
+ `user/assistant`、排除 rewound、限制单页数量并保持 `(createdAt,rowid)` 游标分页。它不
+ create/resume Lead,也不发送消息,所以本机与 SSH Worker 都能在不唤醒 Lead 的前提下读取
+ 同一份上下文。Worker 只有在任务依赖「当前工作/继续/这个 PR」等相对范围时才查询;
+ 自包含任务直接执行。没有显式 Worker 任务时不会用 Lead 输入擅自起任务;该 handoff 也不
+ 改写 MCP `create_worker` / `create_workers` 已由 Lead 组织好的 `initial_task`。
+- device-link 只有在被控端 capability 与本次 `enableOrca` 成功响应都证明支持 deferred
+ handoff(含 `dispatched=false` 与宿主时间戳)时才建立二段派单凭据;旧端继续即时派单,
+ 并为兼容保留待发送 Lead 文本。二段派单发生隧道超时时不自动重试,也不把模糊终态说成
+ 失败,避免同一任务重复执行;UI 引导用户先查看 Worker 面板。
### Codex Lead 机制
diff --git a/packages/device-link/src/__tests__/allowlist.test.ts b/packages/device-link/src/__tests__/allowlist.test.ts
index f3824430c8..d9520fae7b 100644
--- a/packages/device-link/src/__tests__/allowlist.test.ts
+++ b/packages/device-link/src/__tests__/allowlist.test.ts
@@ -83,6 +83,7 @@ describe('REMOTE_INVOKE_ALLOWLIST', () => {
'maker:schedule:create',
'maker:schedule:get-runtime-state',
'maker:worker:create',
+ 'maker:worker:dispatch-ui-assignment',
'maker:session:enable-orca',
'maker:rewind:commit',
'maker:fork',
@@ -385,6 +386,12 @@ describe('INVOKE_TIMEOUT_OVERRIDES_MS', () => {
// 严格大于 10min,锁住「带余量」的语义,防止回退成无余量的同值。
expect(INVOKE_TIMEOUT_OVERRIDES_MS['maker:compact-session']).toBeGreaterThan(10 * 60_000);
});
+
+ it('UI Worker 派单超时必须大于 Lead history gate 的 30s 执行预算', () => {
+ expect(
+ INVOKE_TIMEOUT_OVERRIDES_MS['maker:worker:dispatch-ui-assignment'],
+ ).toBeGreaterThan(30_000);
+ });
});
describe('computeAllowlistHash', () => {
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index 9b8a6ee1c6..d36ac48555 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -343,6 +343,7 @@ const EXTENDED_INVOKE_CHANNELS: readonly string[] = [
'maker:project-automation:remove-schedule',
// —— Orca 协同(Lead 控多 Worker;在被控端进程内编排)——
'maker:worker:create',
+ 'maker:worker:dispatch-ui-assignment',
'maker:worker:list',
'maker:worker:switch-focus',
'maker:worker:idle',
@@ -620,6 +621,9 @@ export const INVOKE_TIMEOUT_OVERRIDES_MS: Readonly<Record<string, number>> = {
// 10min,压缩恰好到预算上限时会先 INVOKE_TIMEOUT,被误判为「设备无响应」并
// 可能触发 peer-link 恢复(codex P2)——同 desktop-cmd:run 模式加 1min 余量。
'maker:compact-session': 11 * 60_000,
+ // 被控端先等 Lead history 最多 30s,再 resume/queue Worker;默认 30s 会与服务端
+ // deadline 对撞,把边沿成功误报成 DEVICE_LINK_TIMEOUT。留出派发和回程余量。
+ 'maker:worker:dispatch-ui-assignment': 65_000,
// listing tier 轻量 DB 读:毫秒级查询,12s 仍等不到只能是链路问题,快速失败喂给熔断器。
// 12s 同时覆盖被控端冷启动 DB 迁移的常见时长(那类失败是快速返回的 DbClient not ready,
// 不吃满超时),不会误伤首拉重试。
diff --git a/packages/orca-workflow/src/__tests__/orca-bridge-mcp.test.ts b/packages/orca-workflow/src/__tests__/orca-bridge-mcp.test.ts
index 039a5340c9..e29ce33065 100644
--- a/packages/orca-workflow/src/__tests__/orca-bridge-mcp.test.ts
+++ b/packages/orca-workflow/src/__tests__/orca-bridge-mcp.test.ts
@@ -379,6 +379,81 @@ describe('orca_worker_bridge MCP helpers', () => {
}
});
+ it('reads only the owning Lead history without creating or waking the Lead', async () => {
+ const workerLink: OrcaWorkerLink = {
+ workerId: 'worker-1',
+ workflowId: 'workflow-1',
+ workerSessionId: 'worker-session-1',
+ leadSessionId: 'lead-1',
+ leadSession: {
+ sessionId: 'lead-1',
+ agentKind: 'claude-code',
+ workingDir: '/repo',
+ model: 'claude-opus-4-7',
+ },
+ };
+ const base = makeProvider({ workerLink });
+ const readLeadHistory = vi.fn().mockResolvedValue({
+ items: [{
+ id: 'message-1',
+ role: 'user',
+ content: { text: 'Review this worktree' },
+ agentMeta: null,
+ createdAt: 456,
+ }],
+ hasMore: true,
+ nextCursor: { createdAt: 456, id: 'message-1', rowid: 17 },
+ });
+ const provider = createOrcaWorkerBridgeMcpProvider({
+ getMaker: () => base.maker as unknown as Maker,
+ logger: makeLogger(),
+ persistUserMessage: vi.fn(),
+ wireSession: vi.fn(),
+ readLeadHistory,
+ orcaTeamStore: {
+ getWorkerLink: vi.fn(async () => workerLink),
+ updateWorkerStatus: vi.fn(),
+ },
+ });
+ const server = getServer(provider, {
+ agentKind: 'codex',
+ workingDir: '/repo',
+ sessionId: 'worker-session-1',
+ vendorOptions: {
+ orcaRole: 'worker',
+ orcaWorkerId: 'worker-1',
+ orcaWorkerSessionId: 'worker-session-1',
+ },
+ });
+
+ const result = parseToolJson(await server._registeredTools.read_lead_history.handler({
+ worker_id: 'worker-1',
+ from_ms: 123,
+ limit: 50,
+ cursor: { created_at_ms: 234, id: 'previous', rowid: 9 },
+ }));
+
+ expect(readLeadHistory).toHaveBeenCalledWith({
+ leadSessionId: 'lead-1',
+ fromMs: 123,
+ limit: 50,
+ cursor: { createdAt: 234, id: 'previous', rowid: 9 },
+ });
+ expect(result).toMatchObject({
+ worker_id: 'worker-1',
+ lead_session_id: 'lead-1',
+ has_more: true,
+ next_cursor: { created_at_ms: 456, id: 'message-1', rowid: 17 },
+ });
+ expect(base.createSessionCalls).toEqual([]);
+
+ expect(expectToolError(await server._registeredTools.read_lead_history.handler({
+ worker_id: 'forged-worker',
+ limit: 50,
+ }))).toMatchObject({ error: 'worker identity mismatch' });
+ expect(readLeadHistory).toHaveBeenCalledTimes(1);
+ });
+
function makeWorkerBridgeLeadHarness(lead: FakeSession) {
const logger = makeLogger();
const workerLink: OrcaWorkerLink = {
diff --git a/packages/orca-workflow/src/index.ts b/packages/orca-workflow/src/index.ts
index 5f5967a583..690f4deab2 100644
--- a/packages/orca-workflow/src/index.ts
+++ b/packages/orca-workflow/src/index.ts
@@ -4,6 +4,9 @@ export {
formatAgentMessage,
formatOrcaCommunicationMessage,
type OrcaBridgeMcpDeps,
+ type OrcaLeadHistoryCursor,
+ type OrcaLeadHistoryMessage,
+ type OrcaLeadHistoryPage,
type OrcaLeadVendorOptions,
type OrcaPersistedSession,
type OrcaTeamStore,
diff --git a/packages/orca-workflow/src/orca-bridge-mcp.ts b/packages/orca-workflow/src/orca-bridge-mcp.ts
index 385dc453b5..47375bee0c 100644
--- a/packages/orca-workflow/src/orca-bridge-mcp.ts
+++ b/packages/orca-workflow/src/orca-bridge-mcp.ts
@@ -53,6 +53,26 @@ export interface OrcaTeamStore {
updateWorkerStatus: (workerId: string, status: OrcaWorkerStatus) => Promise<void>;
}
+export interface OrcaLeadHistoryCursor {
+ createdAt: number;
+ id: string;
+ rowid?: number;
+}
+
+export interface OrcaLeadHistoryMessage {
+ id: string;
+ role: 'user' | 'assistant';
+ content: unknown;
+ agentMeta: unknown;
+ createdAt: number;
+}
+
+export interface OrcaLeadHistoryPage {
+ items: OrcaLeadHistoryMessage[];
+ nextCursor: OrcaLeadHistoryCursor | null;
+ hasMore: boolean;
+}
+
interface CapturedSessionEntry {
sessionId: string;
session: Session | null;
@@ -122,6 +142,16 @@ export interface OrcaBridgeMcpDeps {
makerMemoryEnabled?: boolean;
}>;
orcaTeamStore?: OrcaTeamStore;
+ /**
+ * Worker-scoped read-only transcript access. The bridge resolves the owning Lead from the
+ * attested Worker link; callers never choose an arbitrary session id.
+ */
+ readLeadHistory?: (params: {
+ leadSessionId: string;
+ fromMs: number | null;
+ limit: number;
+ cursor: OrcaLeadHistoryCursor | null;
+ }) => Promise<OrcaLeadHistoryPage>;
dispatchInterAgentMessage?: (params: {
targetSessionId: string;
rawContent: string;
@@ -818,6 +848,79 @@ export function createOrcaWorkerBridgeMcpProvider(deps: OrcaBridgeMcpDeps): McpP
},
);
+ server.tool(
+ 'read_lead_history',
+ 'Read user/assistant transcript rows from your owning Lead without waking or modifying the Lead. Use only when an [Orca UI Assignment] depends on Lead context. You MUST pass your worker_id.',
+ {
+ worker_id: z.string().min(1).describe('Required. Your assigned worker_id.'),
+ from_ms: z
+ .number()
+ .int()
+ .nonnegative()
+ .optional()
+ .describe('Optional inclusive Unix-ms lower bound, such as the UI assignment snapshot_before_ms.'),
+ limit: z.number().int().min(1).max(200).default(100),
+ cursor: z
+ .object({
+ created_at_ms: z.number().int().nonnegative(),
+ id: z.string().min(1),
+ rowid: z.number().int().positive().optional(),
+ })
+ .optional()
+ .describe('next_cursor from the previous page.'),
+ },
+ async ({ worker_id, from_ms, limit, cursor }) => {
+ const resolved = await resolveWorkerLink(deps, ctx, worker_id);
+ if (!resolved.ok) return text(resolved.error, true);
+ if (!deps.readLeadHistory) {
+ return text({ error: 'lead history unavailable' }, true);
+ }
+ let page: OrcaLeadHistoryPage;
+ try {
+ page = await deps.readLeadHistory({
+ leadSessionId: resolved.link.leadSessionId,
+ fromMs: from_ms ?? null,
+ limit,
+ cursor: cursor
+ ? {
+ createdAt: cursor.created_at_ms,
+ id: cursor.id,
+ ...(cursor.rowid !== undefined ? { rowid: cursor.rowid } : {}),
+ }
+ : null,
+ });
+ } catch (err) {
+ log.warn('read lead history failed', {
+ workerId: resolved.link.workerId,
+ leadSessionId: resolved.link.leadSessionId,
+ errorName: err instanceof Error ? err.name : undefined,
+ });
+ return text({ error: 'lead history read failed' }, true);
+ }
+ return text({
+ worker_id: resolved.link.workerId,
+ lead_session_id: resolved.link.leadSessionId,
+ messages: page.items.map((item) => ({
+ id: item.id,
+ role: item.role,
+ content: item.content,
+ agent_meta: item.agentMeta,
+ created_at_ms: item.createdAt,
+ })),
+ has_more: page.hasMore,
+ next_cursor: page.nextCursor
+ ? {
+ created_at_ms: page.nextCursor.createdAt,
+ id: page.nextCursor.id,
+ ...(page.nextCursor.rowid !== undefined
+ ? { rowid: page.nextCursor.rowid }
+ : {}),
+ }
+ : null,
+ });
+ },
+ );
+
server.tool(
'read_lead',
'You MUST pass your worker_id (see the Bridge note at the end of the most recent lead message). Read captured output from the lead session.',
diff --git a/packages/orca-workflow/src/orca-bridge-prompt.ts b/packages/orca-workflow/src/orca-bridge-prompt.ts
index 5f26f30b2f..c565a8084e 100644
--- a/packages/orca-workflow/src/orca-bridge-prompt.ts
+++ b/packages/orca-workflow/src/orca-bridge-prompt.ts
@@ -91,7 +91,7 @@ export function renderOrcaWorkerSystemPrompt(meta: OrcaWorkerPromptMeta): string
const lines = [
`You are a worker agent in an Orca multi-agent workflow. Identity: worker_id=${meta.workerId}, session_id=${meta.sessionId}, workflow_id=${meta.workflowId}, lead_session_id=${meta.leadSessionId}.`,
'',
- 'Tools: send_to_lead, read_lead, lead_status. ALWAYS pass the worker_id parameter on send_to_lead / read_lead / lead_status. Get the value from the "Bridge note" line at the end of the most recent lead message, or from your system prompt Identity line. Never omit it.',
+ 'Tools: send_to_lead, read_lead_history, read_lead, lead_status. ALWAYS pass the worker_id parameter on every tool call. Get the value from the "Bridge note" line at the end of the most recent lead message, or from your system prompt Identity line. Never omit it.',
'',
'Messages from the lead arrive prefixed with [From Orca Lead]. Treat them as tasks or instructions from the lead, not user messages.',
'',
@@ -107,6 +107,7 @@ export function renderOrcaWorkerSystemPrompt(meta: OrcaWorkerPromptMeta): string
'8. Do not commit changes unless the lead explicitly asks you to. Leave diffs for lead/user review.',
'9. When first created, wait for the lead to assign a task. Do not proactively message the lead.',
'10. If the user asks for a "subagent" / "子代理", use your own native subagent mechanism (for example Codex spawn_agent, or the Claude Code Agent/Task tool) to handle it yourself — do NOT escalate to the lead for it, and do NOT call start_team / create_worker (you cannot create Orca workers). If you have no native subagent mechanism, tell the user so instead of substituting an Orca Worker or spawning processes yourself; an Orca Worker is never a substitute for a subagent.',
+ '11. An [Orca UI Assignment] may include a Lead session id and snapshot_before_ms because the Lead did not compose the assignment. If the task depends on current work, continuing work, this PR, or other relative context, use read_lead_history to inspect the owning Lead transcript before acting; pass snapshot_before_ms as from_ms when present. This read is scoped to your Lead and does not wake it. If the task is self-contained, proceed without reading history.',
];
return lines.join('\n');