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): 支持 Worker 独立模型路由并修复容量恢复漏报

DavidShenc3aa84f84296
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 58492bd66e..a2b912edb5 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
@@ -51,7 +51,7 @@ import type {
AgentInputQueuedMessage,
} from '../../../shared/agentInputQueue.js';
import { HOST_ONLY_AGENT_PREFIX, USAGE_LIMIT_RESET_AUTO_RESUME_REASON, isAutomaticInputOriginKind } from '../../../shared/agentInputQueue.js';
-import { buildRemoteWorkerQueuedMessage } from '../orcaRemoteWorkerRuntime.js';
+import { buildRemoteWorkerQueuedMessage, createOrcaRemoteWorkerRuntime, type RemoteWorkerTurnEnd } from '../orcaRemoteWorkerRuntime.js';
import { stampMobileClientOrigin } from '../mobileClientPromptNote.js';
import {
CONTINUE_AFTER_APP_EXIT_PROMPT,
@@ -15439,3 +15439,84 @@ describe('Goal input boundary', () => {
expect(await gate.ensureGoalInputReady('goal-task')).toBe(true);
});
});
+
+// Regression through production coordinator + remote runtime. Unit, no real waits.
+// Orca contract 5a: a recoverable vendor boundary must not settle the Lead dispatch.
+// Existing coverage only polls after autoResume has already completed.
+it('keeps remote Lead reporting pending through real coordinator recovery stages', async () => {
+ vi.useFakeTimers();
+ const h = createHarness();
+ const sid = 'capacity-real-coordinator';
+ const takeover = { error: 'Selected model is at capacity.', reason: 'upstream-overload', attempt: 1, maxAttempts: 5, sessionTotal: 1 };
+ h.setResumableTurnErrorTakeover(takeover);
+ h.setResumableTurnErrorCandidate(() => true);
+ h.setHasAssistantProgressAfter(async () => true);
+ h.coordinator.enqueue(sid, makeItem('lead-input', 'original task'));
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+ h.setRunning(false);
+ h.coordinator.onTurnEvent(sid, 'error', takeover.error, { reason: takeover.reason });
+ await flush();
+ const backoff = h.coordinator.getProjection(sid);
+ expect(backoff.autoResumePending).toMatchObject({ attempt: 1 });
+ expect(backoff.turnInProgress).toBe(false);
+ const gate = deferred<void>(), entered = deferred<void>();
+ h.getSdkSessionId.mockImplementationOnce(async () => { entered.resolve(); await gate.promise; return 'sdk-session'; });
+ h.setRunning(true);
+ expect(await h.coordinator.autoRetryLastError(sid, takeover.sessionTotal)).toBe('resumed');
+ await flush();
+ h.setRunning(false);
+ const queued = h.coordinator.getProjection(sid);
+ expect(queued.autoResumePending).toBeUndefined();
+ expect(queued.turnInProgress).toBe(false);
+ expect(queued.pendingQueue.some(item => item.autoResume === true)).toBe(true);
+ h.coordinator.wakeSession(sid, 'probe-idle');
+ await entered.promise;
+ const preparing = h.coordinator.getProjection(sid);
+ expect(preparing.autoResumePending).toMatchObject({ attempt: 1 });
+ expect(preparing.turnInProgress).toBe(true);
+ gate.resolve();
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ h.setRunning(false);
+ h.coordinator.onTurnEvent(sid, 'done');
+ await flush();
+ const completed = h.coordinator.getProjection(sid);
+ expect(completed.turnInProgress).toBe(false);
+ for (const [phase, projection] of [['backoff', backoff], ['queued', queued], ['preparing', preparing]] as const) {
+ let currentProjection = projection;
+ let recovered = false;
+ const calls: RemoteWorkerTurnEnd[] = [];
+ const invoke = async (_device: string, channel: string, args: unknown[]): Promise<unknown> => {
+ if (channel === 'maker:list-active') return { sessions: [{ sessionId: sid, isTurnRunning: false }] };
+ if (channel === 'maker:input:get-projection') return { ...currentProjection, deliveryReceipts: [{ clientId: 'lead-input', state: 'accepted' }] };
+ if (channel === 'local-db:history:messages') {
+ const request = args[0] as { roles: string[] };
+ const rows = [
+ { id: 'u-1', clientId: 'lead-input', role: 'user', content: 'original task' },
+ { id: 'partial', role: 'assistant', content: 'Partial before capacity error' },
+ ...(recovered ? [
+ { id: 'u-continue', role: 'user', content: 'Continue', agentMeta: { autoResume: true } },
+ { id: 'final', role: 'assistant', content: 'FINAL_AFTER_CAPACITY_RECOVERY' },
+ ] : []),
+ ].filter(row => request.roles.includes(row.role)).reverse();
+ return { items: rows, hasMore: false, terminal: null };
+ }
+ throw new Error(channel);
+ };
+ const runtime = createOrcaRemoteWorkerRuntime({
+ invoke, deviceName: () => 'execution device', saveReport: async () => {},
+ onTurnStarted: async () => {}, captureTurnEnded: () => async turn => { calls.push(turn); return true; },
+ onWorkerStateChanged: () => {}, now: () => 1, setTimeout: () => 0, clearTimeout: () => {}, log: { info: () => {}, warn: () => {} },
+ });
+ runtime.track({ workerId: 'w', teamId: 't', leadSessionId: 'lead', proxySessionId: 'proxy', deviceId: 'execution', remoteSessionId: sid, lastBridgedMessageId: null, pendingReport: { clientIds: ['lead-input'], baselineMessageId: null } }, { workingDir: '/qa' });
+ await runtime.pollNow();
+ expect(calls, phase).toEqual([]);
+ currentProjection = completed;
+ recovered = true;
+ await runtime.pollNow();
+ await runtime.pollNow();
+ expect(calls, phase).toEqual([{ status: 'done', finalText: 'FINAL_AFTER_CAPACITY_RECOVERY' }]);
+ runtime.stop();
+ }
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteWorkerHost.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteWorkerHost.test.ts
index ad8d8e7525..27ebfa319d 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteWorkerHost.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteWorkerHost.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import {
ORCA_REMOTE_WORKER_CAPS_CHANNEL,
+ ORCA_REMOTE_WORKER_MODELS_CHANNEL,
ORCA_REMOTE_WORKER_OPEN_CHANNEL,
ORCA_REMOTE_WORKER_RELEASE_CHANNEL,
ORCA_REMOTE_WORKER_VERSION,
@@ -8,6 +9,7 @@ import {
import {
createOrcaRemoteWorkerHost,
+ createOrcaRemoteWorkerSessionOpener,
registerOrcaRemoteWorkerHandlers,
type OrcaRemoteWorkerCaller,
type OrcaRemoteWorkerExistingSession,
@@ -64,6 +66,54 @@ function setup(
}
describe('orca remote worker host', () => {
+ // Unit: discovery stays on the Worker host with the same caller boundary as
+ // open. The old coverage only exercised the local-model creation path.
+ it('serves Agent locations only to an authorized device caller', async () => {
+ const { deps } = setup();
+ deps.readModels = vi.fn(async input => ({ agentDeviceId: input.agentDeviceId ?? null,
+ locations: [{ agentDeviceId: 'provider-pc', name: 'Provider PC' }], codex: [{ id: 'remote-only', label: 'Remote model' }] }));
+ const host = createOrcaRemoteWorkerHost(deps);
+ expect(host.caps()).toMatchObject({ agentDevice: true });
+ await expect(host.models({ agent: 'codex', agentDeviceId: 'provider-pc' })).resolves.toMatchObject({ agentDeviceId: 'provider-pc', codex: [{ id: 'remote-only' }] });
+ const guest = createOrcaRemoteWorkerHost({ ...deps, getCaller: () => ({ controllerDeviceId: 'guest', sharedTask: {} }) });
+ await expect(guest.models({})).rejects.toThrow(/PERMISSION_DENIED/);
+ expect(deps.readModels).toHaveBeenCalledTimes(1);
+ });
+
+ it('persists the resolved remote Agent route with the Worker’s directory before bootstrap', async () => {
+ const row = { id: 'w_remote_1', agentKind: 'codex', model: 'remote-only', agentDeviceId: 'provider-pc',
+ providerId: 'openai', workingDir: '/worker/project', effort: 'low', fastMode: false };
+ const insertSession = vi.fn(), bootstrapSession = vi.fn(), broadcastSessionCreated = vi.fn();
+ const openSession = vi.fn(async (input, commit) => { expect(input.body).toMatchObject({
+ agentDeviceId: 'provider-pc', providerId: 'openai', model: 'remote-only', workingDir: '/worker/project' });
+ const value = await commit(row, () => {}); return { row, value }; });
+ const resolveAgentSelection = vi.fn(async input => ({ ...input, model: 'remote-only', providerId: 'openai' }));
+ const opener = createOrcaRemoteWorkerSessionOpener({
+ openSession: openSession as unknown as Parameters<typeof createOrcaRemoteWorkerSessionOpener>[0]['openSession'],
+ insertSession, bootstrapSession, broadcastSessionCreated, resolveAgentSelection,
+ });
+ await expect(opener({ ...request, agentKind: 'codex', permissionMode: 'auto', agentDeviceId: 'provider-pc', workingDir: '/worker/project' },
+ { leadDeviceId: 'lead-pc', leadDeviceName: 'Lead', leadSessionId: 'lead-1', leadTitle: 'Lead', workerLabel: 'test' })).resolves.toMatchObject({
+ agentDeviceId: 'provider-pc', providerId: 'openai', model: 'remote-only', workingDir: '/worker/project' });
+ expect(insertSession).toHaveBeenCalledWith(row);
+ expect(bootstrapSession).toHaveBeenCalledWith(row, expect.any(Function));
+ });
+ // Unit: an account switch during remote catalog admission cannot create a
+ // task in the next owner's database. Older coverage had no asynchronous route.
+ it('rejects an owner switch while resolving the model computer', async () => {
+ const openSession = vi.fn();
+ let current = true;
+ const opener = createOrcaRemoteWorkerSessionOpener({ openSession,
+ captureOwner: () => () => { if (!current) throw new Error('owner changed'); },
+ resolveAgentSelection: async input => { current = false; return input; },
+ insertSession: vi.fn(), bootstrapSession: vi.fn(), broadcastSessionCreated: vi.fn(),
+ });
+ await expect(opener({ ...request, agentKind: 'codex', permissionMode: 'auto', agentDeviceId: 'provider-pc' },
+ { leadDeviceId: 'lead-pc', leadDeviceName: 'Lead', leadSessionId: 'lead-1', leadTitle: 'Lead', workerLabel: 'test' }))
+ .rejects.toThrow('owner changed');
+ expect(openSession).not.toHaveBeenCalled();
+ });
+
it('only answers device-link callers', async () => {
const { host } = setup({ caller: null });
expect(() => host.caps()).toThrow(/PRECONDITION_FAILED/);
@@ -205,6 +255,7 @@ describe('orca remote worker host', () => {
expect([...handlers.keys()].sort()).toEqual(
[
ORCA_REMOTE_WORKER_CAPS_CHANNEL,
+ ORCA_REMOTE_WORKER_MODELS_CHANNEL,
ORCA_REMOTE_WORKER_OPEN_CHANNEL,
ORCA_REMOTE_WORKER_RELEASE_CHANNEL,
].sort(),
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteWorkerRuntime.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteWorkerRuntime.test.ts
index ab16bd9114..1b38fb0894 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteWorkerRuntime.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteWorkerRuntime.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
+import type { AgentInputProjection } from '../../../shared/agentInputQueue.js';
import {
createOrcaRemoteWorkerRuntime,
@@ -33,6 +34,7 @@ interface FakeDevice {
acceptedAgents: Record<string, string>;
assistant: { id: string; content: unknown } | null;
terminalError: boolean;
+ inputProjection?: Partial<AgentInputProjection>;
history?: FakeHistoryMessage[];
enqueueError?: Error & { inFlight?: boolean };
enqueued: unknown[];
@@ -110,6 +112,7 @@ function setup(device: Partial<FakeDevice> = {}) {
case 'maker:input:get-projection': {
const ids = (args[1] as { deliveryClientIds: string[] }).deliveryClientIds;
return {
+ ...state.inputProjection,
deliveryReceipts: ids.map((clientId) => ({
clientId,
state: state.receipts[clientId] ?? 'unknown',
@@ -503,6 +506,143 @@ describe('orca remote worker runtime', () => {
expect(deps.saveReport).toHaveBeenCalledWith('worker-1', null, 'final');
});
+ // Test value: dispatch/pollNow must keep the Lead input through overload recovery
+ // (Orca contract 5a and the 2026-10-21 capacity failure). The existing autoResume
+ // test polls only after the final. These unit cases poll during recovery first;
+ // they verify no premature report, then one recovered final or one surfaced error.
+ const recoveryInfo = { attempt: 1, maxAttempts: 5, sessionTotal: 1 };
+ const recoveringProjections: Array<{ phase: string; projection: Partial<AgentInputProjection> }> = [
+ { phase: 'backoff', projection: { autoResumePending: recoveryInfo } },
+ { phase: 'queued continuation', projection: { pendingQueue: [{
+ clientId: 'continue-1', autoResume: true, retrySourceClientId: 'c-1',
+ } as AgentInputProjection['pendingQueue'][number]] } },
+ { phase: 'dispatch preparation', projection: { autoResumePending: recoveryInfo, turnInProgress: true } },
+ { phase: 'vendor running after the idle snapshot', projection: { turnInProgress: true } },
+ { phase: 'usage reset wait', projection: { usageLimitWait: { resumeAt: 1_900_000_000_000 } } },
+ ];
+ it.each(recoveringProjections)('holds the dispatch during $phase and reports its recovered final once', async ({ projection }) => {
+ const { runtime, deps, state } = setup({ history: [] });
+ await runtime.dispatch({ proxySessionId: 'proxy-1', rawContent: 'Lead task', clientId: 'c-1' });
+ state.receipts['c-1'] = 'accepted';
+ state.history = [
+ { id: 'lead-input', clientId: 'c-1', role: 'user', content: 'Lead task' },
+ { id: 'partial', role: 'assistant', content: 'Progress before capacity error' },
+ ];
+ state.inputProjection = projection;
+ state.terminalError = true;
+ for (let i = 0; i < 16; i += 1) await runtime.pollNow();
+ expect(deps.onTurnEnded).not.toHaveBeenCalled();
+ expect(runtime.hasPendingReport('proxy-1')).toBe(true);
+ state.inputProjection = { turnInProgress: false };
+ state.terminalError = false;
+ state.history.push(
+ { id: 'continue', role: 'user', content: 'Continue', agentMeta: { autoResume: true } },
+ { id: 'final', role: 'assistant', content: 'Recovered final' },
+ );
+ await runtime.pollNow();
+ await runtime.pollNow();
+ expect(deps.onTurnEnded).toHaveBeenCalledExactlyOnceWith('proxy-1', { status: 'done', finalText: 'Recovered final' });
+ expect(deps.saveReport).toHaveBeenLastCalledWith('worker-1', null, 'final');
+ });
+
+ it('reports a surfaced recovery failure once when the execution host gives up', async () => {
+ const { runtime, deps, state } = setup({ inputProjection: { autoResumePending: recoveryInfo } });
+ await runtime.dispatch({ proxySessionId: 'proxy-1', rawContent: 'Lead task', clientId: 'c-1' });
+ state.receipts['c-1'] = 'accepted';
+ state.terminalError = true;
+ await runtime.pollNow();
+ expect(deps.onTurnEnded).not.toHaveBeenCalled();
+ state.inputProjection = { turnInProgress: false };
+ await runtime.pollNow();
+ await runtime.pollNow();
+ expect(deps.onTurnEnded).toHaveBeenCalledOnce();
+ expect(deps.onTurnEnded).toHaveBeenCalledWith('proxy-1', expect.objectContaining({ status: 'error' }));
+ expect(runtime.hasPendingReport('proxy-1')).toBe(false);
+ });
+
+ it.each([false, true])('discards the old history candidate when recovery starts during the history read (paged=%s)', async paged => {
+ const { runtime, deps, state, invoke } = setup();
+ await runtime.dispatch({ proxySessionId: 'proxy-1', rawContent: 'Lead task', clientId: 'c-1' });
+ state.receipts['c-1'] = 'accepted';
+ state.assistant = { id: 'partial', content: 'Progress before capacity error' };
+ if (paged) state.history = [
+ { id: 'lead-input', clientId: 'c-1', role: 'user', content: 'Lead task' },
+ ...Array.from({ length: 2001 }, (_, i): FakeHistoryMessage => ({ id: `partial-${i}`, role: 'assistant', content: 'Progress' })),
+ ];
+ const original = invoke.getMockImplementation()!;
+ let inject = true;
+ invoke.mockImplementation(async (deviceId, channel, args) => {
+ const result = await original(deviceId, channel, args);
+ if (inject && channel === 'local-db:history:messages' && (args[0] as { roles: string[] }).roles.includes('user')) {
+ inject = false;
+ state.inputProjection = { autoResumePending: recoveryInfo };
+ }
+ return result;
+ });
+ await runtime.pollNow();
+ expect(deps.onTurnEnded).not.toHaveBeenCalled();
+ state.inputProjection = {};
+ state.assistant = { id: 'final', content: 'Recovered final' };
+ state.history?.push({ id: 'final', role: 'assistant', content: 'Recovered final' });
+ await runtime.pollNow();
+ await runtime.pollNow();
+ expect(deps.onTurnEnded).toHaveBeenCalledExactlyOnceWith('proxy-1', { status: 'done', finalText: 'Recovered final' });
+ });
+
+ it('keeps a no-output recovery pending beyond the missing-reply budget', async () => {
+ const { runtime, deps, state } = setup({ assistant: null });
+ await runtime.dispatch({ proxySessionId: 'proxy-1', rawContent: 'Lead task', clientId: 'c-1' });
+ state.receipts['c-1'] = 'accepted';
+ state.inputProjection = { autoResumePending: recoveryInfo };
+ for (let i = 0; i < 16; i += 1) await runtime.pollNow();
+ expect(deps.onTurnEnded).not.toHaveBeenCalled();
+ state.inputProjection = {};
+ state.assistant = { id: 'final', content: 'Recovered first reply' };
+ await runtime.pollNow();
+ expect(deps.onTurnEnded).toHaveBeenCalledExactlyOnceWith('proxy-1', { status: 'done', finalText: 'Recovered first reply' });
+ });
+
+ it('keeps another Worker on the same execution device reporting while one is recovering', async () => {
+ const { runtime, deps, state, invoke } = setup();
+ const pendingReport = { clientIds: ['c-1'], baselineMessageId: null };
+ runtime.untrack('proxy-1');
+ runtime.track({ ...ref, pendingReport });
+ runtime.track({ ...ref, workerId: 'worker-2', proxySessionId: 'proxy-2', remoteSessionId: 'remote-2', pendingReport });
+ state.receipts['c-1'] = 'accepted';
+ state.assistant = { id: 'final', content: 'Other Worker result' };
+ const original = invoke.getMockImplementation()!;
+ invoke.mockImplementation(async (deviceId, channel, args) => {
+ const value = await original(deviceId, channel, args);
+ return channel === 'maker:input:get-projection' && args[0] === 'remote-1'
+ ? { ...(value as object), autoResumePending: recoveryInfo } : value;
+ });
+ await runtime.pollNow();
+ expect(runtime.hasPendingReport('proxy-1')).toBe(true);
+ expect(runtime.hasPendingReport('proxy-2')).toBe(false);
+ expect(deps.onTurnEnded).toHaveBeenCalledExactlyOnceWith('proxy-2', { status: 'done', finalText: 'Other Worker result' });
+ expect(invoke.mock.calls.filter(([, channel]) => channel === 'maker:list-active')).toHaveLength(1);
+ expect(invoke.mock.calls.some(([, channel]) => channel === 'maker:abort-session' || channel === 'maker:input:enqueue')).toBe(false);
+ });
+
+ it('does not hold an older completed Lead reply for a later phone input waiting to recover', async () => {
+ const { runtime, deps, state } = setup({ history: [] });
+ await runtime.dispatch({ proxySessionId: 'proxy-1', rawContent: 'Lead task', clientId: 'c-1' });
+ state.receipts['c-1'] = 'accepted';
+ state.history = [
+ { id: 'lead-input', clientId: 'c-1', role: 'user', content: 'Lead task' },
+ { id: 'lead-final', role: 'assistant', content: 'Lead final' },
+ { id: 'phone-input', clientId: 'phone-1', role: 'user', content: 'Phone task' },
+ ];
+ state.inputProjection = {
+ autoResumePending: recoveryInfo,
+ recovery: { kind: 'active-turn', item: { clientId: 'phone-1' } as AgentInputProjection['pendingQueue'][number] },
+ pendingQueue: [{ clientId: 'phone-continue', autoResume: true, retrySourceClientId: 'phone-1' } as AgentInputProjection['pendingQueue'][number]],
+ };
+ state.terminalError = true;
+ await runtime.pollNow();
+ expect(deps.onTurnEnded).toHaveBeenCalledExactlyOnceWith('proxy-1', { status: 'done', finalText: 'Lead final' });
+ });
+
it('retains a new dispatch accepted while reading the previous reply', async () => {
const { runtime, deps, state, invoke } = setup();
await runtime.dispatch({ proxySessionId: 'proxy-1', rawContent: 'First task', clientId: 'c-1' });
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteWorkers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteWorkers.test.ts
index 9a49037095..429fe7234b 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteWorkers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteWorkers.test.ts
@@ -209,6 +209,26 @@ describe('execution devices', () => {
});
describe('openRemoteWorker', () => {
+ // Unit: old execution hosts silently discard unknown model-location fields.
+ // Reject before open; a capable host must receive and return the exact route.
+ it.each([false, true])('negotiates the independent model computer (supported=%s)', async supported => {
+ const { workers, remoteInvoke } = setup({ handle: (_device, channel, args) => {
+ if (channel === 'maker:orca:remote-worker:caps') return ok({ version: 1, ...(supported ? { agentDevice: true } : {}) });
+ if (channel === 'maker:orca:remote-worker:open') return ok({ sessionId: (args[0] as {sessionId: string}).sessionId,
+ agentKind: 'codex', model: 'remote-only', workingDir: '/worker', agentDeviceId: 'provider-pc', providerId: 'openai' });
+ return undefined;
+ } });
+ try {
+ const result = await workers.openRemoteWorker({ ...openInput, agentDeviceId: 'provider-pc', model: 'remote-only' });
+ if (supported) {
+ expect(result).toMatchObject({ ok: true, model: 'remote-only', agentDeviceId: 'provider-pc', providerId: 'openai' });
+ expect(remoteInvoke.mock.calls.find(call => call[1] === 'maker:orca:remote-worker:open')?.[2][0]).toMatchObject({ agentDeviceId: 'provider-pc' });
+ } else {
+ expect(result).toMatchObject({ ok: false, errorCode: 'UNSUPPORTED_CAPABILITY' });
+ expect(remoteInvoke.mock.calls.some(call => call[1] === 'maker:orca:remote-worker:open')).toBe(false);
+ }
+ } finally { workers.stop(); }
+ });
it.each([
[false, true, false],
[true, false, true],
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
index 34efd19e89..4baf730b52 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaWorkerCreationService.test.ts
@@ -331,6 +331,8 @@ describe('orcaWorkerTitle', () => {
});
describe('Worker running on another device (execution device)', () => {
+ // Unit regression: a remote model must not move the Team or prevent a Worker
+ // from working on a third computer. The former guards rejected both inputs.
const remoteDeps = (overrides: Partial<OrcaWorkerCreationDeps> = {}) => createDeps({
openRemoteWorker: vi.fn(async (input) => ({
ok: true as const,
@@ -443,15 +445,12 @@ describe('Worker running on another device (execution device)', () => {
expect(deps.openRemoteWorker).not.toHaveBeenCalled();
});
- it.each([
- ['SSH', { remoteHostId: 'host-1' }],
- ['remote Agent', { agentDeviceId: 'device-b' }],
- ])('refuses to mix with a Lead on %s', async (_name, leadPatch) => {
+ it('keeps SSH execution on its original SSH host', async () => {
const { deps, service } = remoteDeps({
getLeadSessionRow: vi.fn(async () => ({
id: 'lead-1', agentKind: 'codex' as const, workspaceKind: 'project' as const, workingDir: '/repo',
model: 'gpt-5.5', effort: 'medium', permissionMode: 'default', fastMode: false, providerId: 'xd',
- remoteHostId: null, ...leadPatch,
+ remoteHostId: 'host-1',
})),
});
const result = await service.createWorker({
@@ -461,6 +460,24 @@ describe('Worker running on another device (execution device)', () => {
expect(deps.openRemoteWorker).not.toHaveBeenCalled();
});
+ it.each([undefined, null, 'provider-pc'])('places a remote-model Lead’s Worker on its work computer with Agent selection %s', async agentDeviceId => {
+ const { deps, service } = remoteDeps({
+ getLeadSessionRow: vi.fn(async () => ({ id: 'lead-1', agentKind: 'codex' as const,
+ workspaceKind: 'project' as const, workingDir: 'D:/lead', model: 'gpt-5.5',
+ effort: 'medium', permissionMode: 'default', fastMode: false, providerId: 'openai',
+ remoteHostId: null, agentDeviceId: 'lead-model-pc' })),
+ });
+ const result = await service.createWorker({ leadSessionId: 'lead-1', role: 'tester', label: 'mac',
+ agent: 'codex', executionDeviceId: 'mac', workingDir: '/Users/demo/project',
+ ...(agentDeviceId !== undefined ? { agentDeviceId } : {}) });
+ expect(result).toMatchObject({ ok: true, executionDeviceId: 'mac', workingDir: '/Users/demo/project' });
+ const opened = vi.mocked(deps.openRemoteWorker!).mock.calls[0]![0];
+ if (agentDeviceId === undefined) expect(opened).not.toHaveProperty('agentDeviceId');
+ else expect(opened.agentDeviceId).toBe(agentDeviceId);
+ expect(deps.bootstrapSession).not.toHaveBeenCalled();
+ expect(deps.getProviderRoutingContext).not.toHaveBeenCalled();
+ });
+
it('passes through device errors without recording a worker', async () => {
const { deps, service } = remoteDeps({
openRemoteWorker: vi.fn(async () => ({
@@ -626,7 +643,6 @@ describe('Worker of a lead whose agent runs on another computer', () => {
it.each([
['an SSH Lead', { lead: { remoteHostId: 'host-1' }, params: {} }],
- ['a run-on-device Worker', { lead: {}, params: { executionDeviceId: 'office' } }],
['a malformed id', { lead: {}, params: { agentDeviceId: 'bad id/..' } }],
])('rejects another computer for %s', async (_name, { lead, params }) => {
const { deps, service } = createDeps({
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 20cc09ec27..d34390d25f 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -4459,6 +4459,7 @@ export class AgentInputCoordinator {
return {
sessionId,
pendingQueue,
+ turnInProgress: this.isDispatchBoundaryBusy(sessionId, state),
// Modern projections always carry the explicit null token for a session
// that has never been cleared. Only an older controlled Desktop can
// omit the field at the wire boundary; keeping null here lets a remote
diff --git a/apps/desktop/src/main/maker-ipc/orcaRemoteWorkerHost.ts b/apps/desktop/src/main/maker-ipc/orcaRemoteWorkerHost.ts
index bb6b840cfa..fc30bd12d2 100644
--- a/apps/desktop/src/main/maker-ipc/orcaRemoteWorkerHost.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaRemoteWorkerHost.ts
@@ -8,14 +8,18 @@
*/
import {
ORCA_REMOTE_WORKER_CAPS_CHANNEL,
+ ORCA_REMOTE_WORKER_MODELS_CHANNEL,
ORCA_REMOTE_WORKER_OPEN_CHANNEL,
ORCA_REMOTE_WORKER_RELEASE_CHANNEL,
ORCA_REMOTE_WORKER_VERSION,
parseOrcaRemoteWorkerOpenRequest,
+ parseOrcaRemoteWorkerModelsRequest,
parseOrcaRemoteWorkerReleaseRequest,
type OrcaRemoteWorkerCaps,
type OrcaRemoteWorkerOpenRequest,
type OrcaRemoteWorkerOpenResult,
+ type OrcaRemoteWorkerModelsRequest,
+ type OrcaRemoteWorkerModelsResult,
} from '@cindy/device-link';
import type { OrcaRemoteLead } from '../../shared/orcaRemoteWorker.js';
@@ -28,15 +32,30 @@ export function createOrcaRemoteWorkerSessionOpener(deps: {
insertSession(row: OpenedSessionRow): Promise<void>;
bootstrapSession(row: OpenedSessionRow, assertCurrent: () => void): Promise<unknown>;
broadcastSessionCreated(sessionId: string): void;
+ isSelfDeviceId?(deviceId: string): boolean;
+ resolveAgentSelection?(request: OrcaRemoteWorkerOpenRequest): Promise<OrcaRemoteWorkerOpenRequest>;
+ captureOwner?(): () => void;
}): OrcaRemoteWorkerHostDeps['openSession'] {
return async (request, lead) => {
+ const assertOwner = deps.captureOwner?.() ?? (() => {});
+ assertOwner();
+ if (request.agentDeviceId && deps.isSelfDeviceId?.(request.agentDeviceId)) {
+ request = { ...request, agentDeviceId: null };
+ }
+ if (request.agentDeviceId) {
+ if (!deps.resolveAgentSelection) fail('UNSUPPORTED_CAPABILITY', 'remote Worker Agent selection is unavailable');
+ request = await deps.resolveAgentSelection(request);
+ assertOwner();
+ }
const { row } = await deps.openSession({
id: request.sessionId,
+ assertCurrent: assertOwner,
body: {
title: request.title,
agentKind: request.agentKind === 'claude-code' ? 'cc' : request.agentKind,
model: request.model,
providerId: request.providerId,
+ ...(request.agentDeviceId !== undefined ? { agentDeviceId: request.agentDeviceId } : {}),
effort: request.effort,
fastMode: request.fastMode,
permissionMode: request.permissionMode,
@@ -52,7 +71,8 @@ export function createOrcaRemoteWorkerSessionOpener(deps: {
});
deps.broadcastSessionCreated(row.id);
const agentKind = row.agentKind === 'cc' ? 'claude-code' : (row.agentKind as 'codex' | 'pi');
- return { workingDir: row.workingDir ?? '', model: row.model, agentKind, effort: row.effort, fastMode: row.fastMode };
+ return { workingDir: row.workingDir ?? '', model: row.model, agentKind, effort: row.effort, fastMode: row.fastMode,
+ ...(request.agentDeviceId !== undefined ? { agentDeviceId: row.agentDeviceId ?? null, providerId: row.providerId ?? null } : {}) };
};
}
@@ -71,11 +91,14 @@ export interface OrcaRemoteWorkerExistingSession {
agentKind: OrcaRemoteWorkerOpenResult['agentKind'];
effort?: string;
fastMode?: boolean | 'ultrafast';
+ agentDeviceId?: string | null;
+ providerId?: string | null;
}
export interface OrcaRemoteWorkerHostDeps {
getCaller(): OrcaRemoteWorkerCaller | null;
readSession(sessionId: string): Promise<OrcaRemoteWorkerExistingSession | null>;
+ readModels?(request: OrcaRemoteWorkerModelsRequest): Promise<OrcaRemoteWorkerModelsResult>;
/**
* 任务与远端 Worker 标记一起落库,再启动 Agent(复用普通开任务与模型准入)并广播。
* 未给 workingDir 时由本机按自身设置分配任务目录。
@@ -89,6 +112,8 @@ export interface OrcaRemoteWorkerHostDeps {
agentKind: OrcaRemoteWorkerOpenResult['agentKind'];
effort?: string;
fastMode?: boolean | 'ultrafast';
+ agentDeviceId?: string | null;
+ providerId?: string | null;
}>;
writeRemoteLead(sessionId: string, lead: OrcaRemoteLead): Promise<void>;
/** 同一任务 id 的 open / release 串行。 */
@@ -113,7 +138,13 @@ export function createOrcaRemoteWorkerHost(deps: OrcaRemoteWorkerHostDeps) {
return {
caps(): OrcaRemoteWorkerCaps {
requireCaller(deps);
- return { version: ORCA_REMOTE_WORKER_VERSION, workerBridge: true };
+ return { version: ORCA_REMOTE_WORKER_VERSION, workerBridge: true, ...(deps.readModels ? { agentDevice: true } : {}) };
+ },
+
+ async models(raw: unknown): Promise<OrcaRemoteWorkerModelsResult> {
+ requireCaller(deps);
+ if (!deps.readModels) fail('UNSUPPORTED_CAPABILITY', 'remote Worker model discovery is unavailable');
+ return deps.readModels(parseOrcaRemoteWorkerModelsRequest(raw));
},
async open(raw: unknown): Promise<OrcaRemoteWorkerOpenResult> {
@@ -140,6 +171,7 @@ export function createOrcaRemoteWorkerHost(deps: OrcaRemoteWorkerHostDeps) {
agentKind: existing.agentKind,
effort: existing.effort,
fastMode: existing.fastMode,
+ ...(request.agentDeviceId !== undefined ? { agentDeviceId: existing.agentDeviceId ?? null, providerId: existing.providerId ?? null } : {}),
};
}
fail('ALREADY_EXISTS', 'a different task already uses this id');
@@ -183,6 +215,7 @@ export function registerOrcaRemoteWorkerHandlers(
host: OrcaRemoteWorkerHost,
): void {
registry.handle(ORCA_REMOTE_WORKER_CAPS_CHANNEL, () => host.caps());
+ registry.handle(ORCA_REMOTE_WORKER_MODELS_CHANNEL, (_event, raw) => host.models(raw));
registry.handle(ORCA_REMOTE_WORKER_OPEN_CHANNEL, (_event, raw) => host.open(raw));
registry.handle(ORCA_REMOTE_WORKER_RELEASE_CHANNEL, (_event, raw) => host.release(raw));
}
diff --git a/apps/desktop/src/main/maker-ipc/orcaRemoteWorkerRuntime.ts b/apps/desktop/src/main/maker-ipc/orcaRemoteWorkerRuntime.ts
index 095d26e374..19a478d950 100644
--- a/apps/desktop/src/main/maker-ipc/orcaRemoteWorkerRuntime.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaRemoteWorkerRuntime.ts
@@ -19,6 +19,7 @@ import type { OrcaRemotePendingReport } from '../../shared/orcaRemoteWorker.js';
import type {
AgentInputCreateOpts,
+ AgentInputProjection,
AgentInputQueuedMessage,
} from '../../shared/agentInputQueue.js';
import type { HistoryCursor, HistoryMessage, HistoryPage } from '../localDb/chatHistoryReader.js';
@@ -345,16 +346,39 @@ export function createOrcaRemoteWorkerRuntime(deps: OrcaRemoteWorkerRuntimeDeps)
};
}
- async function deliveryStates(ref: RemoteWorkerRef, clientIds: string[]): Promise<string[]> {
+ async function readDelivery(ref: RemoteWorkerRef, clientIds: string[]): Promise<{
+ states: string[];
+ waitingForTurn: boolean;
+ }> {
const projection = (await deps.invoke(ref.deviceId, 'maker:input:get-projection', [
ref.remoteSessionId,
{ deliveryClientIds: clientIds },
- ])) as { deliveryReceipts?: Array<{ clientId?: unknown; state?: unknown }> };
+ ])) as Partial<Pick<AgentInputProjection,
+ 'turnInProgress' | 'autoResumePending' | 'usageLimitWait' | 'pendingQueue' | 'recovery'
+ >> & { deliveryReceipts?: Array<{ clientId?: unknown; state?: unknown }> };
const receipts = Array.isArray(projection?.deliveryReceipts) ? projection.deliveryReceipts : [];
- return clientIds.map((id) => {
+ const states = clientIds.map((id) => {
const receipt = receipts.find((entry) => entry.clientId === id);
return typeof receipt?.state === 'string' ? receipt.state : 'unknown';
});
+ const ownsInput = (item: AgentInputQueuedMessage): boolean => {
+ const sourceId = item.retrySourceClientId ?? item.supersedesUserClientId ?? item.clientId;
+ return typeof sourceId !== 'string' || clientIds.includes(sourceId);
+ };
+ // An unrelated phone input's recovery must not hold an older completed Lead reply.
+ const recovery = projection?.recovery;
+ const ownsRecovery = recovery?.kind !== 'active-turn' || ownsInput(recovery.item);
+ const pendingResume = Array.isArray(projection?.pendingQueue)
+ && projection.pendingQueue.some(item => item?.autoResume === true && ownsInput(item));
+ return {
+ states,
+ // autoResumePending covers backoff and preparation; it is absent while the
+ // hidden continuation is queued. turnInProgress also fences a stale idle
+ // snapshot while the vendor/dispatch/terminal-persistence boundary is busy.
+ waitingForTurn: projection?.turnInProgress === true || pendingResume || (ownsRecovery && (
+ !!projection?.autoResumePending || !!projection?.usageLimitWait
+ )),
+ };
}
async function replyForInputs(
@@ -438,6 +462,8 @@ export function createOrcaRemoteWorkerRuntime(deps: OrcaRemoteWorkerRuntimeDeps)
if (!awaiting?.terminalHandler) return;
const clientIds = awaiting.clientIds;
if (running) {
+ awaiting.historyScan = null;
+ awaiting.missingReplyPolls = 0;
if (!awaiting.startedNotified) {
awaiting.startedNotified = true;
awaiting.turnStartPromise = deps.onTurnStarted(state.ref.proxySessionId);
@@ -445,8 +471,14 @@ export function createOrcaRemoteWorkerRuntime(deps: OrcaRemoteWorkerRuntimeDeps)
}
return;
}
- const states = await deliveryStates(state.ref, clientIds);
+ const delivery = await readDelivery(state.ref, clientIds);
if (!current(state) || state.awaiting !== awaiting || awaiting.clientIds !== clientIds) return;
+ if (delivery.waitingForTurn) {
+ awaiting.historyScan = null;
+ awaiting.missingReplyPolls = 0;
+ return;
+ }
+ const { states } = delivery;
// 仍在运行设备的队列里(排在用户插话之后等),继续等。
if (states.some((value) => value === 'pending')) return;
if (states.every((value) => value === 'removed')) {
@@ -477,6 +509,16 @@ export function createOrcaRemoteWorkerRuntime(deps: OrcaRemoteWorkerRuntimeDeps)
);
// 历史读取期间又派入新任务时保留新的 awaiting,下一轮按完整输入集合复核。
if (!current(state) || state.awaiting !== awaiting || awaiting.clientIds !== clientIds) return;
+ // A retry can start while a history page is in flight. Recheck before using
+ // its candidate, even for a partial scan, so a pre-recovery cursor/text
+ // cannot survive into the completed continuation and hide its final reply.
+ const latest = await readDelivery(state.ref, clientIds);
+ if (!current(state) || state.awaiting !== awaiting || awaiting.clientIds !== clientIds) return;
+ if (latest.waitingForTurn || latest.states.some((value, index) => value !== states[index])) {
+ awaiting.historyScan = null;
+ awaiting.missingReplyPolls = 0;
+ return;
+ }
// 扫描预算不足不代表没有回复,保留当前游标与候选,下一轮继续。
if (!last.complete) return;
awaiting.historyScan = null;
@@ -731,9 +773,8 @@ export function createOrcaRemoteWorkerRuntime(deps: OrcaRemoteWorkerRuntimeDeps)
errorCode(err) === 'INVOKE_TIMEOUT' ||
(err as { inFlight?: unknown })?.inFlight === true
) {
- const [delivered] = await deliveryStates(ref, [params.clientId]).catch(() => [
- 'unknown',
- ]);
+ const delivery = await readDelivery(ref, [params.clientId]).catch(() => null);
+ const delivered = delivery?.states[0] ?? 'unknown';
if (delivered === 'pending' || delivered === 'accepted') return accept();
// 已发出但无法确认的请求保留身份,后续轮询核对,不让调用方重派同一工作。
if (delivered === 'unknown') return accept();
diff --git a/apps/desktop/src/main/maker-ipc/orcaRemoteWorkers.ts b/apps/desktop/src/main/maker-ipc/orcaRemoteWorkers.ts
index 1b700cbb88..e60f0f4c7b 100644
--- a/apps/desktop/src/main/maker-ipc/orcaRemoteWorkers.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaRemoteWorkers.ts
@@ -12,9 +12,13 @@ import { createId } from '@paralleldrive/cuid2';
import {
DeviceLinkError,
ORCA_REMOTE_WORKER_CAPS_CHANNEL,
+ ORCA_REMOTE_WORKER_MODELS_CHANNEL,
ORCA_REMOTE_WORKER_OPEN_CHANNEL,
type InvokeResultPayload,
type OrcaExecutionDeviceView,
+ type OrcaRemoteWorkerCaps,
+ type OrcaRemoteWorkerModelsRequest,
+ type OrcaRemoteWorkerModelsResult,
type OrcaRemoteWorkerOpenResult as DeviceOpenResult,
} from '@cindy/device-link';
import { isMobilePlatform } from '@cindy/maker-shared/device-list';
@@ -195,9 +199,9 @@ export function createOrcaRemoteWorkers(deps: OrcaRemoteWorkersDeps) {
return devices;
}
- async function probeSupported(deviceId: string): Promise<boolean | null> {
+ async function probeSupported(deviceId: string): Promise<OrcaRemoteWorkerCaps | false | null> {
try {
- await Promise.race([
+ const caps = await Promise.race([
invoke(deviceId, ORCA_REMOTE_WORKER_CAPS_CHANNEL, []),
new Promise((_, reject) =>
setTimeout(
@@ -206,7 +210,8 @@ export function createOrcaRemoteWorkers(deps: OrcaRemoteWorkersDeps) {
).unref?.(),
),
]);
- return true;
+ return caps && typeof caps === 'object' && 'version' in caps && caps.version === 1
+ ? caps as OrcaRemoteWorkerCaps : false;
} catch (err) {
return codeOf(err) === 'CHANNEL_NOT_ALLOWED' ? false : null;
}
@@ -352,12 +357,30 @@ export function createOrcaRemoteWorkers(deps: OrcaRemoteWorkersDeps) {
deviceId: device.deviceId,
name: device.name,
platform: device.platform,
- supported: supported[index] === true,
+ supported: supported[index] !== false,
+ ...((supported[index] as OrcaRemoteWorkerCaps)?.agentDevice === true ? { supportsAgentDevice: true } : {}),
},
],
)
.sort((a, b) => Number(b.supported) - Number(a.supported) || a.name.localeCompare(b.name));
},
+ async readModels(deviceId: string, request: OrcaRemoteWorkerModelsRequest): Promise<OrcaRemoteWorkerModelsResult> {
+ const owner = ownerToken();
+ assertOwner(owner);
+ const devices = await refreshDeviceNames();
+ assertOwner(owner);
+ if (!devices.some(device => device.deviceId === deviceId && isExecutionDeviceCandidate(device))) {
+ throw new Error('[REMOTE_AGENT_DEVICE_UNREACHABLE] Worker execution computer is unavailable');
+ }
+ try {
+ const result = await invoke(deviceId, ORCA_REMOTE_WORKER_MODELS_CHANNEL, [request]) as OrcaRemoteWorkerModelsResult;
+ assertOwner(owner);
+ return result;
+ } catch (error) {
+ if (codeOf(error) === 'CHANNEL_NOT_ALLOWED') throw new Error('[UNSUPPORTED_CAPABILITY] Update the Worker execution computer to select its remote providers');
+ throw error;
+ }
+ },
async openRemoteWorker(
input: Parameters<NonNullable<OrcaWorkerCreationDeps['openRemoteWorker']>>[0],
): Promise<OrcaRemoteWorkerOpenResult> {
@@ -390,6 +413,10 @@ export function createOrcaRemoteWorkers(deps: OrcaRemoteWorkersDeps) {
message: `${name} 当前不可达,Worker 没有创建。`,
};
}
+ if (input.agentDeviceId !== undefined && supported.agentDevice !== true) {
+ return { ok: false, errorCode: 'UNSUPPORTED_CAPABILITY',
+ message: `${name} 需要更新后才能为跨设备 Worker 选择 Agent 所在电脑。` };
+ }
const remoteSessionId = createId();
let opened: DeviceOpenResult | undefined;
let uncertainOpen = false;
@@ -403,6 +430,7 @@ export function createOrcaRemoteWorkers(deps: OrcaRemoteWorkersDeps) {
agentKind: input.agent,
...(input.model ? { model: input.model } : {}),
...(input.providerId ? { providerId: input.providerId } : {}),
+ ...(input.agentDeviceId !== undefined ? { agentDeviceId: input.agentDeviceId } : {}),
...(input.effort ? { effort: input.effort } : {}),
...(input.fast !== undefined ? { fastMode: input.fast } : {}),
permissionMode: input.permissionMode,
@@ -512,6 +540,8 @@ export function createOrcaRemoteWorkers(deps: OrcaRemoteWorkersDeps) {
agent,
model: opened.model,
workingDir: opened.workingDir,
+ ...(opened.agentDeviceId !== undefined ? { agentDeviceId: opened.agentDeviceId } : {}),
+ ...(opened.providerId !== undefined ? { providerId: opened.providerId } : {}),
};
},
diff --git a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
index 080b88961c..e6e26e6022 100644
--- a/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaWorkerCreationService.ts
@@ -206,7 +206,7 @@ export type OrcaWorkerCreationResult =
providerId: string | null;
role: string;
label: string;
- /** Worker 的 Agent 所在电脑(远程供应商);null = 任务所在电脑。运行设备 Worker 不带。 */
+ /** Worker 的 Agent 所在电脑;null = Worker 的任务所在电脑。 */
agentDeviceId?: string | null;
};
}
@@ -245,7 +245,7 @@ export interface OrcaWorkerCreateParams {
workerPermissionMode?: OrcaWorkerPermissionMode;
/**
* 运行设备:同账号另一台电脑的设备 id。指定时 Worker 的任务、目录与命令都在那台;
- * 缺省 = 与 Lead 同一台(现有行为)。与 SSH 远端 Lead、远程 Agent Lead 互斥。
+ * 缺省 = 与 Lead 的任务同一台。SSH Lead 不支持;远程 Agent Lead 可独立选工作电脑。
*/
executionDeviceId?: string;
/**
@@ -267,6 +267,8 @@ export type OrcaRemoteWorkerOpenResult =
agent: AgentKind;
model: string;
workingDir: string;
+ agentDeviceId?: string | null;
+ providerId?: string | null;
}
| {
ok: false;
@@ -383,6 +385,7 @@ export interface OrcaWorkerCreationDeps {
agent: AgentKind;
model?: string;
providerId?: string;
+ agentDeviceId?: string | null;
effort?: string;
fast?: boolean | 'ultrafast';
permissionMode: OrcaWorkerPermissionMode;
@@ -764,13 +767,12 @@ function resolveWorkerAgentDeviceId(
if (!AGENT_DEVICE_ID_PATTERN.test(deviceId)) {
return { ok: false, message: 'agent_device_id must be a device id or a shared provider id' };
}
- if (isSelfDeviceId?.(deviceId)) return { ok: true, agentDeviceId: null };
+ // For an execution-device Worker, an explicit id names a model computer
+ // relative to that execution host; the Lead’s own id is not its local route.
+ if (params.executionDeviceId === undefined && isSelfDeviceId?.(deviceId)) return { ok: true, agentDeviceId: null };
if (lead.remoteHostId) {
return { ok: false, message: 'Workers of an SSH Lead run their Agent on the SSH host; agent_device_id is not supported' };
}
- if (params.executionDeviceId !== undefined) {
- return { ok: false, message: 'execution_device_id and agent_device_id cannot be combined' };
- }
return { ok: true, agentDeviceId: deviceId };
}
@@ -856,11 +858,11 @@ export function createOrcaWorkerCreationService(deps: OrcaWorkerCreationDeps): O
if (!deps.openRemoteWorker || !deps.recordRemoteWorker || !deps.discardRemoteWorker) {
return { ok: false, errorCode: 'INVALID_PARAMS', message: 'this computer cannot run Workers on other devices' };
}
- if (lead.remoteHostId || lead.agentDeviceId) {
+ if (lead.remoteHostId) {
return {
ok: false,
errorCode: 'INVALID_PARAMS',
- message: 'a Lead on an SSH host or with its Agent on another computer cannot place Workers on other devices',
+ message: 'a Lead on an SSH host cannot place Workers on other devices',
};
}
let requestedDir: string | undefined;
@@ -945,6 +947,7 @@ export function createOrcaWorkerCreationService(deps: OrcaWorkerCreationDeps): O
agent: params.agent,
...(params.model !== undefined ? { model: params.model } : {}),
...(explicitSourceId ? { providerId: explicitSourceId } : {}),
+ ...(params.agentDeviceId !== undefined ? { agentDeviceId: params.agentDeviceId } : {}),
...(params.effort !== undefined ? { effort: params.effort } : {}),
...(params.fast !== undefined ? { fast: params.fast } : {}),
permissionMode,
@@ -1011,7 +1014,8 @@ export function createOrcaWorkerCreationService(deps: OrcaWorkerCreationDeps): O
model: opened.model,
effort: opened.proxySession.effort || null,
fastMode: opened.proxySession.fastMode,
- providerId: explicitSourceId ?? null,
+ providerId: opened.providerId ?? explicitSourceId ?? null,
+ ...(opened.agentDeviceId !== undefined ? { agentDeviceId: opened.agentDeviceId } : {}),
role,
label,
},
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 932269b85f..b7e9d755d9 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1456,7 +1456,7 @@ import {
resolveGhostUserHookModel,
withGhostUserHookModel,
} from '../cindy-brain/subscriptionGateway.js';
-import { createSessionExecutionResolver } from './sessionExecutionSelection.js';
+import { createSessionExecutionResolver, resolveSessionExecutionSelection } from './sessionExecutionSelection.js';
import { createGhostErrandRunner } from './ghostErrandRunner.js';
import {
createPluginTaskSession,
@@ -2879,6 +2879,8 @@ interface OrcaCollabService {
listAvailableModels: (params: {
agent?: AgentKind;
callerSessionId?: string;
+ /** Worker task/model discovery is owned by this execution computer. */
+ executionDeviceId?: string;
/** 列哪里的模型:缺省 = Lead 所在位置;null = 任务所在电脑;string = 那台电脑或分享。 */
agentDeviceId?: string | null;
}) => Promise<
@@ -9590,6 +9592,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return (await activeCompanionCloud()?.transfer(botId, targetDeviceId, companionSwitchOptions(options))) ?? { ok: false, code: 'NOT_ENABLED' };
});
registerOrcaRemoteWorkerHandlers(makerSessionRegistry, createOrcaRemoteWorkerHost({
+ readModels: async (request) => {
+ const owner = getCurrentDbClientSnapshot();
+ const result = await orcaCollabServiceHolder?.listAvailableModels({ ...request, agentDeviceId: request.agentDeviceId ?? null });
+ if (getCurrentDbClientSnapshot() !== owner) throwIpcError('PRECONDITION_FAILED', 'Worker account changed');
+ if (!result?.ok) throw new Error(`[${result?.errorCode ?? 'HOST_NOT_READY'}] ${result?.message ?? 'Worker model service is not ready'}`);
+ return result;
+ },
getCaller: () => {
const context = getDeviceLinkInvokeContext();
return context
@@ -9604,6 +9613,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const [row] = await getDbClient()
.drizzle.select({
orcaRemoteLead: sessions.orcaRemoteLead,
+ agentDeviceId: sessions.agentDeviceId,
+ providerId: sessions.providerId,
status: sessions.status,
workingDir: sessions.workingDir,
model: sessions.model,
@@ -9623,10 +9634,40 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
agentKind: row.agentKind === 'cc' ? 'claude-code' : (row.agentKind as 'codex' | 'pi'),
effort: row.effort,
fastMode: row.fastMode,
+ agentDeviceId: row.agentDeviceId,
+ providerId: row.providerId,
};
},
openSession: createOrcaRemoteWorkerSessionOpener({
openSession,
+ isSelfDeviceId: deviceId => deviceId === getSelfDeviceId(),
+ captureOwner: () => {
+ const owner = getCurrentDbClientSnapshot();
+ return () => { if (getCurrentDbClientSnapshot() !== owner) throwIpcError('PRECONDITION_FAILED', 'Worker account changed'); };
+ },
+ resolveAgentSelection: async request => {
+ const views = await readDeviceProviderViews(remoteBackgroundInvoke, request.agentDeviceId!);
+ const routing = deviceWorkerRoutingContext(views, request.agentKind);
+ const models = routing.remoteCodexModels ?? [];
+ const providers = routing.availability[request.agentKind];
+ const model = request.model ?? (request.providerId
+ ? providers.find(provider => provider.id === request.providerId)?.models[0]
+ : models[0]?.id);
+ try {
+ const selected = resolveSessionExecutionSelection({
+ selection: { agentKind: request.agentKind, model, providerId: request.providerId,
+ effort: request.effort, fastMode: request.fastMode },
+ availableAgents: [request.agentKind], availableModels: models, providerRouting: routing,
+ // The connected remote provider owns its credential; it validates the
+ // credential again when starting. Never require/copy this host's key.
+ hasCindyAiApiKey: true,
+ });
+ return { ...request, model: selected.model, providerId: selected.providerId ?? undefined,
+ effort: selected.effort, fastMode: selected.fastMode };
+ } catch (error) {
+ throwIpcError('INVALID_PARAMS', error instanceof Error ? error.message : 'Worker model is unavailable');
+ }
+ },
insertSession: async (row) => {
await getDbClient().drizzle.insert(sessions).values(row).run();
},
@@ -9642,6 +9683,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
workingDir: opened.workingDir ?? '',
model: opened.model,
providerId: opened.providerId,
+ agentDeviceId: opened.agentDeviceId ?? undefined,
effort: (opened.effort || undefined) as CreateOpts['effort'],
fastMode: opened.fastMode,
permissionMode: opened.permissionMode as CreateOpts['permissionMode'],
@@ -16906,8 +16948,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
};
}
},
- listAvailableModels: async ({ agent, callerSessionId, agentDeviceId: requestedAgentDeviceId }) => {
+ listAvailableModels: async ({ agent, callerSessionId, executionDeviceId, agentDeviceId: requestedAgentDeviceId }) => {
try {
+ if (executionDeviceId) {
+ if (!orcaRemoteWorkersForHost) throw new Error('[HOST_NOT_READY] Worker service is not ready');
+ const result = await orcaRemoteWorkersForHost.readModels(executionDeviceId, {
+ ...(agent ? { agent } : {}), agentDeviceId: requestedAgentDeviceId ?? null,
+ });
+ return { ok: true, ...result };
+ }
const agents: AgentKind[] = agent ? [agent] : ['codex', 'claude-code', 'pi'];
// SSH Lead 的 Worker 在 SSH 主机上运行 Agent,不能放到别的电脑:不列可选位置。
const sshLead = callerSessionId ? Boolean(await readSessionRemoteHostIdCached(callerSessionId)) : false;
@@ -16968,10 +17017,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
return { ok: true, agentDeviceId: null, ...(locations ? { locations } : {}), ...result };
} catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ const code = /^\[([A-Z_]+)\]/.exec(message)?.[1];
return {
ok: false,
- errorCode: 'INTERNAL',
- message: err instanceof Error ? err.message : String(err),
+ errorCode: executionDeviceId && code && (code === 'UNSUPPORTED_CAPABILITY' || code.startsWith('REMOTE_AGENT_'))
+ ? code : 'INTERNAL',
+ message,
};
}
},
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 86b653d7d3..2c458cebbf 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -6384,9 +6384,9 @@ function CCAgentSessionContent({
// openai-chat 桥接 Codex 只挂在本地 proxy),与 main 侧 remote-worker
// guard 同规则(codex review R28)。
sshRemote={!!session?.remoteHostId}
- // 首个 Worker 也可放到另一台电脑:仅本机 Lead(非 SSH、Agent 也在本机)。
+ // Lead 的 Agent 位置独立于 Worker 的工作电脑;SSH Lead 仍沿用原限制。
executionDevicesEnabled={
- !remoteDeviceId && !session?.remoteHostId && !session?.agentDeviceId
+ !remoteDeviceId && !session?.remoteHostId
}
// Worker 的 Agent 默认跟 Lead 的 Agent 所在电脑(远程供应商),模型目录也先按那台读;
// 面板里列出与输入框同一份其他电脑 / 分享的供应商,可以换到本机或别处。
diff --git a/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx b/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx
index 108951bf0e..0adbaf76a9 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CreateWorkerPopover.tsx
@@ -1,4 +1,6 @@
import { WorkerProjectField, useWorkerProjectSelection } from './WorkerProjectField';
+import { ORCA_REMOTE_WORKER_MODELS_CHANNEL } from '@cindy/device-link';
+import { orcaWorkflowsForDevice } from '@/lib/makerTransport';
import type { WorkerWorktreeRequest } from '../../../shared/orca-worker-project';
import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
import * as Dialog from '@radix-ui/react-dialog';
@@ -108,6 +110,7 @@ export interface ExecutionDeviceOption {
platform: string | null;
/** false = 版本过旧,不可选。 */
supported: boolean;
+ supportsAgentDevice?: boolean;
}
export function parseExecutionDevices(value: unknown): ExecutionDeviceOption[] {
@@ -122,6 +125,7 @@ export function parseExecutionDevices(value: unknown): ExecutionDeviceOption[] {
name: typeof row.name === 'string' && row.name ? row.name : row.deviceId,
platform: typeof row.platform === 'string' ? row.platform : null,
supported: row.supported === true,
+ ...(row.supportsAgentDevice === true ? { supportsAgentDevice: true } : {}),
},
];
});
@@ -151,7 +155,7 @@ export interface CreateWorkerPopoverProps {
sshRemote?: boolean;
/** 开启新协同时必须确认执行端支持权限偏好;已有旧版远程 Team 创建 Worker 仍兼容旧行为。 */
requireWorkerPermissionModeSupport?: boolean;
- /** 允许把 Worker 放到同账号另一台电脑运行(仅本机 Lead)。 */
+ /** 允许把 Worker 放到同账号另一台电脑运行(SSH Lead 除外)。 */
executionDevicesEnabled?: boolean;
/**
* Lead 的 Agent 所在电脑(远程供应商):string = 那台电脑或分享,null / 缺省 = 任务所在电脑。
@@ -201,6 +205,9 @@ export function CreateWorkerPopover({
const submittingRef = useRef(false);
const [executionDevices, setExecutionDevices] = useState<ExecutionDeviceOption[]>([]);
const [executionDeviceId, setExecutionDeviceId] = useState<string | null>(null);
+ const [executionAgentDevices, setExecutionAgentDevices] = useState<{
+ deviceId: string; devices: Array<{ deviceId: string; name: string }>;
+ } | null>(null);
const [remoteDirMode, setRemoteDirMode] = useState<'dialogue' | 'path'>('dialogue');
const [remoteDir, setRemoteDir] = useState('');
const [directoryPickerOpen, setDirectoryPickerOpen] = useState(false);
@@ -212,8 +219,12 @@ export function CreateWorkerPopover({
const modelSelectionScope = JSON.stringify([getDataOwnerGeneration().dataOwnerId, leadDeviceId ?? 'local']);
// 模型、供应商与能力按 Worker 的 Agent 实际运行的电脑读取:选了远程供应商读那台(或分享),
// 远程控制的 Lead 读它所在的电脑,选了运行设备则读运行设备。权限档始终跟 Lead 所在电脑走。
- const deviceId = agentDeviceId ?? leadDeviceId ?? executionDeviceId ?? undefined;
+ const workerHostDeviceId = executionDeviceId ?? leadDeviceId;
+ const deviceId = agentDeviceId ?? workerHostDeviceId ?? undefined;
const executionDevice = executionDevices.find((d) => d.deviceId === executionDeviceId) ?? null;
+ const agentDevices = executionDeviceId
+ ? executionAgentDevices?.deviceId === executionDeviceId ? executionAgentDevices.devices : []
+ : remoteAgentDevices;
const localProjectEnabled =
!!leadSessionId && !leadDeviceId && !sshRemote && !executionDeviceId && !isSidebarWindow();
const project = useWorkerProjectSelection(open, leadSessionId, localProjectEnabled);
@@ -255,11 +266,11 @@ export function CreateWorkerPopover({
&& taskHostCaps !== null
&& taskHostCaps?.supportsOrcaWorkerPermissionMode !== true;
// 能否给 Worker 单独选 Agent 所在电脑:本机任务恒可以;远程控制的任务要那台声明支持(老端会把
- // 字段静默丢掉)。SSH Lead 与运行设备 Worker 不适用。
+ // 字段静默丢掉)。跨设备 Worker 还要工作电脑声明独立 Agent 能力。
const agentLocationSelectable =
- remoteAgentDevices !== undefined
+ agentDevices !== undefined
&& sshRemote !== true
- && executionDeviceId === null
+ && (!executionDeviceId || executionDevice?.supportsAgentDevice === true)
&& (!leadDeviceId || hostCaps.capabilities?.supportsOrcaWorkerAgentDevice === true);
const activeModels = useMemo(() => {
return selectWorkerModels({
@@ -430,8 +441,8 @@ export function CreateWorkerPopover({
setPrefsRestored(true);
}, [leadDeviceId, modelSelectionScope, open, sshRemote]);
useEffect(() => {
- if (open && !modelSelectionChosenRef.current) setAgentDeviceId(leadAgentDeviceId ?? null);
- }, [leadAgentDeviceId, open]);
+ if (open && !executionDeviceId && !modelSelectionChosenRef.current) setAgentDeviceId(leadAgentDeviceId ?? null);
+ }, [leadAgentDeviceId, executionDeviceId, open]);
// 可选运行设备:每次打开读一次;读不到就只有这台电脑,不提示错误。
useEffect(() => {
@@ -440,7 +451,8 @@ export function CreateWorkerPopover({
return;
}
let disposed = false;
- void Promise.resolve(window.electronAPI?.localDb?.orcaWorkflows?.listExecutionDevices?.())
+ const workflows = leadDeviceId ? orcaWorkflowsForDevice(leadDeviceId) : window.electronAPI?.localDb?.orcaWorkflows;
+ void Promise.resolve(workflows?.listExecutionDevices?.())
.then((value) => {
if (!disposed) setExecutionDevices(parseExecutionDevices(value));
})
@@ -450,7 +462,21 @@ export function CreateWorkerPopover({
return () => {
disposed = true;
};
- }, [executionDevicesEnabled, open]);
+ }, [executionDevicesEnabled, leadDeviceId, open]);
+
+ useEffect(() => {
+ if (!open || !executionDeviceId || !executionDevice?.supportsAgentDevice) return;
+ let disposed = false;
+ void window.electronAPI.deviceLink.invoke(executionDeviceId, ORCA_REMOTE_WORKER_MODELS_CHANNEL, [{}])
+ .then((value) => {
+ const locations = (value as { locations?: Array<{ agentDeviceId: string; name: string }> }).locations ?? [];
+ if (!disposed) setExecutionAgentDevices({ deviceId: executionDeviceId,
+ devices: locations.filter(location => remoteAgentDevices?.some(device => device.deviceId === location.agentDeviceId))
+ .map(location => ({ deviceId: location.agentDeviceId, name: location.name })) });
+ })
+ .catch(() => { if (!disposed) setExecutionAgentDevices({ deviceId: executionDeviceId, devices: [] }); });
+ return () => { disposed = true; };
+ }, [executionDevice?.supportsAgentDevice, executionDeviceId, open, remoteAgentDevices]);
const selectExecutionDevice = useCallback(
(next: string | null) => {
@@ -458,9 +484,10 @@ export function CreateWorkerPopover({
restoredModelSelectionRef.current = false;
modelSelectionChosenRef.current = false;
setExecutionDeviceId(next);
+ setAgentDeviceId(next ? null : leadAgentDeviceIdRef.current);
setRemoteDirMode('dialogue');
setRemoteDir('');
- // 另一台电脑的模型目录没有本机的来源维度;回到这台电脑时恢复本机记忆的来源。
+ // 换工作电脑后重新按它的目录选择来源;回到 Lead 时恢复本机记忆。
setProviderSource(next || leadDeviceId ? null : prefs[agent].providerId);
},
[agent, executionDeviceId, leadDeviceId, prefs],
@@ -718,21 +745,21 @@ export function CreateWorkerPopover({
);
// 远程 Agent:模型面板左侧栏在任务所在电脑的供应商之后列出其他电脑与分享的供应商,选中那里的
- // 模型 = Worker 的 Agent 在那台运行(与新建任务同一套)。运行设备与它互斥,选了运行设备不列。
+ // 模型 = Worker 的 Agent 在那台运行(与新建任务同一套),工作电脑独立选择。
const remoteAgentOptions = useMemo<RemoteAgentSelectorOptions | undefined>(
() =>
- agentLocationSelectable && remoteAgentDevices && remoteAgentDevices.length > 0
+ agentLocationSelectable && agentDevices && (agentDevices.length > 0 || !!executionDeviceId)
? {
- devices: remoteAgentDevices,
+ devices: agentDevices,
selectedDeviceId: agentDeviceId,
- ...(leadDeviceId ? { homeDeviceId: leadDeviceId } : { localModelMemory: LOCAL_WORKER_MODEL_MEMORY }),
+ ...(workerHostDeviceId ? { homeDeviceId: workerHostDeviceId } : { localModelMemory: LOCAL_WORKER_MODEL_MEMORY }),
deviceModelMemory: agentDeviceModelMemoryAccessors,
}
: undefined,
- [agentDeviceId, agentLocationSelectable, leadDeviceId, remoteAgentDevices],
+ [agentDeviceId, agentLocationSelectable, workerHostDeviceId, agentDevices, executionDeviceId],
);
const agentDeviceName = agentDeviceId
- ? (remoteAgentDevices?.find((device) => device.deviceId === agentDeviceId)?.name ?? null)
+ ? (agentDevices?.find((device) => device.deviceId === agentDeviceId)?.name ?? null)
: null;
const activeRole = customRole || role;
@@ -743,7 +770,7 @@ export function CreateWorkerPopover({
: null;
// 选了 Lead 之外的位置、但任务所在电脑现在不能带这个字段(能力还在读 / 已降级):不能悄悄按 Lead 的位置建。
const agentLocationUnsendable =
- !agentLocationSelectable && agentDeviceId !== (leadAgentDeviceId ?? null);
+ !agentLocationSelectable && agentDeviceId !== (executionDeviceId ? null : leadAgentDeviceId ?? null);
const canCreate =
(!localProjectEnabled || project.ready) &&
!isSubmitting &&
@@ -989,8 +1016,8 @@ export function CreateWorkerPopover({
{localProjectEnabled && <WorkerProjectField selection={project} disabled={isSubmitting} />}
- {/* 运行设备与远程供应商互斥:Worker 的 Agent 已在另一台电脑时不提供运行设备。 */}
- {executionDevices.length > 0 && agentDeviceId === null ? (
+ {/* 工作电脑与 Agent 所在电脑独立选择。 */}
+ {executionDevices.length > 0 ? (
<ExecutionDeviceField
devices={executionDevices}
selectedId={executionDevice?.deviceId ?? null}
@@ -1031,6 +1058,7 @@ export function CreateWorkerPopover({
fastModeConfigurable={['codex', 'pi']}
unifiedAgents={pickerAgents}
onUnifiedSelect={deviceId && remoteProviders.unsupported ? undefined : (selection) => {
+ if (selection.agentDevice !== undefined && executionDeviceId && !agentLocationSelectable) return;
modelSelectionChosenRef.current = true;
restoredModelSelectionRef.current = false;
const nextAgent = selection.engine === 'cc' ? 'claude-code' : selection.engine;
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index b9f391b240..c8d3000b13 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -6167,9 +6167,9 @@ export function NewMakerDraftRoute() {
// SSH 远程草稿(draft.remoteHostId):worker 在远端 spawn,模型清单按 SSH
// 口径过滤,与本路由 ChatInput 候选及 main 侧 remote-worker guard 同口径。
sshRemote={!!effectiveRemoteHostId}
- // 首个 Worker 也可放到另一台电脑:仅本机草稿(非 SSH、非远程 Agent)。
+ // 本机草稿可独立选择 Worker 工作电脑,Agent 可在远端;SSH 沿用原限制。
executionDevicesEnabled={
- !effectiveDeviceLinkDeviceId && !effectiveRemoteHostId && !isAgentDeviceDraft
+ !effectiveDeviceLinkDeviceId && !effectiveRemoteHostId
}
// Worker 的 Agent 默认跟草稿选的 Agent 所在电脑(远程供应商),面板里列出与输入框同一份
// 其他电脑 / 分享的供应商,可以换到任务所在电脑或别处。
diff --git a/apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx b/apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx
index 1a31d9e7e5..e29d55abeb 100644
--- a/apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx
@@ -263,8 +263,8 @@ export function OrcaWorkerPanel({
onCreate={handleCreateWorker}
deviceId={deviceId ?? undefined}
sshRemote={sshRemote}
- // 仅任务与 Agent 均已确认在本机的 Lead 可选择 Worker 运行设备,与主进程限制一致。
- executionDevicesEnabled={deviceId === null && agentDeviceId === null && !sshRemote}
+ // 工作电脑与 Lead 的 Agent 位置独立;SSH 沿用原限制。
+ executionDevicesEnabled={deviceId === null && !sshRemote}
// Worker 的模型目录默认跟 Lead 的 Agent 所在电脑;可在面板里换到本机或其他电脑。控制端读不到
// 那台目录时(见 useWorkerAgentDevices)维持被控电脑的目录,Worker 跟 Lead。
leadAgentDeviceId={workerAgentDevices.leadAgentDeviceId}
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx
index 3d31f25e59..5022c0f658 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/CreateWorkerPopover.test.tsx
@@ -1734,6 +1734,33 @@ describe('CreateWorkerPopover execution device', () => {
expect(onCreate.mock.calls[0]![0]).not.toHaveProperty(field);
});
+ // Unit/jsdom: a remote-model Lead can place files on another host and select
+ // an independent model computer, without leaking the Lead's model location.
+ it('keeps the selected work host when choosing a remote model for its Worker', async () => {
+ listExecutionDevices.mockResolvedValue({ devices: [
+ { deviceId: 'mac-mini', name: 'Mac mini', supported: true, supportsAgentDevice: true },
+ ] });
+ const invoke = vi.fn(async () => ({ locations: [{ agentDeviceId: 'agent-pc', name: 'Agent PC' }] }));
+ Object.assign(window.electronAPI, { deviceLink: { invoke } });
+ mocks.remoteProviders = [{ id: 'openai', name: 'OpenAI', connected: true,
+ remoteInvocationEnabled: true, agents: ['codex'], models: { codex: [model('codex/gpt-5.5')] } }];
+ const onCreate = vi.fn();
+ render(<CreateWorkerPopover open leadSessionId="lead" leadAgentDeviceId="lead-model-pc"
+ remoteAgentDevices={[{deviceId: 'agent-pc', name: 'Agent PC'}]} executionDevicesEnabled onClose={vi.fn()} onCreate={onCreate} />);
+ const picker = await screen.findByRole('combobox', { name: 'orca.createWorker.executionDeviceLabel' });
+ fireEvent.keyDown(picker, { key: 'ArrowDown' });
+ fireEvent.click(await screen.findByRole('option', { name: /Mac mini/ }));
+ await waitFor(() => expect(invoke).toHaveBeenCalledWith('mac-mini', 'maker:orca:remote-worker:models', [{}]));
+ expect(mocks.deviceProvidersFor).toBe('mac-mini');
+ await waitFor(() => expect(screen.getByTestId('model-selector').dataset.remoteHome).toBe('mac-mini'));
+ fireEvent.click(screen.getByTestId('pick-remote-codex'));
+ expect(mocks.deviceProvidersFor).toBe('agent-pc');
+ fireEvent.click(screen.getByRole('button', { name: 'orca.createWorker.submit' }));
+ await waitFor(() => expect(onCreate).toHaveBeenCalledOnce());
+ expect(onCreate.mock.calls[0]![0]).toMatchObject({ executionDeviceId: 'mac-mini',
+ agentDeviceId: 'agent-pc', model: 'codex/gpt-5.5', providerId: 'openai' });
+ });
+
it('offers other computers only when enabled and the list is not empty', async () => {
const { unmount } = render(<CreateWorkerPopover open onClose={vi.fn()} onCreate={vi.fn()} />);
expect(listExecutionDevices).not.toHaveBeenCalled();
diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.ts
index 9da14c5368..7a6d386750 100644
--- a/apps/desktop/src/shared/agentInputQueue.ts
+++ b/apps/desktop/src/shared/agentInputQueue.ts
@@ -498,6 +498,8 @@ export function normalizeAgentInputClearBoundaryMs(value: unknown): number | nul
export interface AgentInputProjection {
sessionId: string;
+ /** Host still owns a turn/dispatch/interaction boundary. Older hosts may omit it. */
+ turnInProgress?: boolean;
pendingQueue: AgentInputQueuedMessage[];
/**
* 被控端最近一次 `/clear` 的权威毫秒 token。只在会话至少 clear 过一次时出现;
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 42ebec6451..92378838a3 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -2740,7 +2740,7 @@ function SessionScreenContent() {
&& !isSharedTaskPeer(deviceId)
&& collab.workerForm.agentLocationSelectable
&& collab.workerForm.modelPicker.open,
- controlledDeviceId: deviceId,
+ controlledDeviceId: collabWorkerDeviceId,
keepDeviceIds: workerAgentKeepDeviceIds,
});
// Agent 在另一台电脑时,模型 / 来源都属于那台的目录:展示与校验按那份,读不到时按加载中处理。
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index 80ca9ac16c..b74596ccca 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -1136,7 +1136,7 @@ export default function NewRemoteSessionScreen() {
);
const workerAgentCatalogs = useRemoteAgentCatalogs({
enabled: remoteAgentSupported && collabForm.agentLocationSelectable && collabForm.modelPicker.open,
- controlledDeviceId: selectedDeviceId,
+ controlledDeviceId: collabWorkerDeviceId,
keepDeviceIds: workerAgentKeepDeviceIds,
});
const remoteAgentCatalog = remoteAgentPick
diff --git a/apps/mobile/src/__tests__/useOrcaWorkerForm.test.tsx b/apps/mobile/src/__tests__/useOrcaWorkerForm.test.tsx
index cfd883ab7d..ab0af601ec 100644
--- a/apps/mobile/src/__tests__/useOrcaWorkerForm.test.tsx
+++ b/apps/mobile/src/__tests__/useOrcaWorkerForm.test.tsx
@@ -51,6 +51,25 @@ function ExecutionProbe({ maker, target, enabled = true }: { maker: MobileMakerT
return null;
}
+// Unit regression: a Worker on B may use C's provider, with model/effort kept
+// as one explicit route. Old execution hosts must retain the local-only form.
+it.each([false, true])('permits remote providers on the selected work computer only with support %s', async supported => {
+ const lead = { ...fakeMaker(), orca: { listExecutionDevices: vi.fn(async () => ({ devices: [
+ { deviceId: 'b', name: 'B', supported: true, ...(supported ? { supportsAgentDevice: true } : {}) },
+ ] })) } } as unknown as MobileMakerTransport;
+ const remote = fakeMaker();
+ function Host() { latest = useOrcaWorkerForm({ maker: lead, executionMakerForDevice: () => remote,
+ executionDevicesEnabled: true, agentLocationSelectable: true, leadAgentDeviceId: 'lead-model-pc',
+ prefsScope: 'user-1', active: true, setSheetOpen: () => undefined }); return null; }
+ await act(async () => { root.render(<Host />); await flush(); });
+ await act(async () => { latest!.patch({ executionDeviceId: 'b' }); await flush(); });
+ expect(latest!.agentLocationSelectable).toBe(supported);
+ await act(async () => { await latest!.modelPicker.select({ agent: 'codex', modelId: 'remote-only', providerId: 'remote-openai', effort: 'high', fast: false }, { deviceId: 'c' }); });
+ expect(latest!.form.executionDeviceId).toBe('b');
+ if (supported) expect(latest!.form).toMatchObject({ agentDeviceId: 'c', model: { id: 'remote-only', providerId: 'remote-openai', effort: 'high' } });
+ else expect(latest!.form.agentDeviceId).toBeUndefined();
+});
+
it('reads selectable devices from the Lead and reads Agent/model capabilities from the chosen device', async () => {
const lead = { ...fakeMaker(), listAvailableAgents: vi.fn(async () => ['codex']), orca: { listExecutionDevices: vi.fn(async () => ({ devices: [
{ deviceId: 'b', name: 'B', supported: true }, { deviceId: 'old', supported: false },
diff --git a/apps/mobile/src/session/orcaTeam.ts b/apps/mobile/src/session/orcaTeam.ts
index 6e921085e4..8edc96b57e 100644
--- a/apps/mobile/src/session/orcaTeam.ts
+++ b/apps/mobile/src/session/orcaTeam.ts
@@ -78,6 +78,7 @@ export function parseOrcaExecutionDevices(value: unknown): OrcaExecutionDeviceVi
name: typeof row.name === 'string' && row.name ? row.name : row.deviceId,
platform: typeof row.platform === 'string' ? row.platform : null,
supported: row.supported === true,
+ ...(row.supportsAgentDevice === true ? { supportsAgentDevice: true } : {}),
}];
});
}
diff --git a/apps/mobile/src/session/useSessionOrcaCollab.ts b/apps/mobile/src/session/useSessionOrcaCollab.ts
index 31124e5200..c81b52a697 100644
--- a/apps/mobile/src/session/useSessionOrcaCollab.ts
+++ b/apps/mobile/src/session/useSessionOrcaCollab.ts
@@ -299,14 +299,15 @@ export function useOrcaWorkerForm(params: {
const leadAgentDeviceIdRef = useRef(params.leadAgentDeviceId ?? null);
leadAgentDeviceIdRef.current = params.leadAgentDeviceId ?? null;
const agentLocationSelectableRef = useRef(params.agentLocationSelectable === true);
- agentLocationSelectableRef.current = params.agentLocationSelectable === true;
+ const leadLocationSelectableRef = useRef(params.agentLocationSelectable === true);
+ leadLocationSelectableRef.current = params.agentLocationSelectable === true;
/**
* 复位时 Worker 的 Agent 位置:跟 Lead。Lead 在另一台电脑时本机记忆的模型属于别的目录,
* 模型回到「默认」交给被控端按那台的目录解析(与桌面不指定模型时同口径)。
*/
const withLeadLocation = useCallback((value: OrcaWorkerFormValue): OrcaWorkerFormValue => {
const lead = leadAgentDeviceIdRef.current;
- const selectable = agentLocationSelectableRef.current;
+ const selectable = leadLocationSelectableRef.current;
return {
...value,
...(lead ? { model: null } : {}),
@@ -321,6 +322,9 @@ export function useOrcaWorkerForm(params: {
? params.executionMakerForDevice(form.executionDeviceId)
: maker, [form.executionDeviceId, maker, params.executionMakerForDevice]);
const [executionDevices, setExecutionDevices] = useState<OrcaExecutionDeviceView[]>([]);
+ const workerAgentLocationSelectable = params.agentLocationSelectable === true
+ && (!form.executionDeviceId || executionDevices.some(device => device.deviceId === form.executionDeviceId && device.supportsAgentDevice === true));
+ agentLocationSelectableRef.current = workerAgentLocationSelectable;
const [executionDevicesLoading, setExecutionDevicesLoading] = useState(false);
const [executionDevicesError, setExecutionDevicesError] = useState<string | null>(null);
const [customRoleMode, setCustomRoleMode] = useState(false);
@@ -578,7 +582,7 @@ export function useOrcaWorkerForm(params: {
touchedRef.current = true;
if ('executionDeviceId' in next && next.executionDeviceId !== formRef.current.executionDeviceId) {
convergeGenRef.current += 1;
- // 运行设备与远程供应商互斥:换运行设备时 Worker 的 Agent 回到任务所在的那台。
+ // 换工作电脑先回到它的本机默认;随后可单独选择它可调用的远程供应商。
setForm((current) => ({
...current,
...next,
@@ -586,12 +590,16 @@ export function useOrcaWorkerForm(params: {
modelSelectionExplicit: false,
remoteDirMode: 'dialogue',
remoteDir: '',
- agentDeviceId: current.agentDeviceId === undefined ? undefined : null,
+ agentDeviceId: next.executionDeviceId
+ ? executionDevices.some(device => device.deviceId === next.executionDeviceId && device.supportsAgentDevice === true) ? null : undefined
+ : params.agentLocationSelectable ? leadAgentDeviceIdRef.current : undefined,
}));
} else {
- setForm((current) => ({ ...current, ...next }));
+ setForm((current) => ({ ...current, ...next,
+ ...('agentDeviceId' in next && !agentLocationSelectableRef.current ? { agentDeviceId: undefined } : {}),
+ }));
}
- }, []);
+ }, [executionDevices, params.agentLocationSelectable]);
const changePermission = useCallback(async (mode: OrcaWorkerPermissionMode) => {
touchedRef.current = true;
@@ -610,6 +618,7 @@ export function useOrcaWorkerForm(params: {
source?: { deviceId: string | null },
): Promise<boolean> => {
if (!ALL_AGENTS.includes(config.agent as OrcaWorkerAgentKind)) return false;
+ if (source !== undefined && formRef.current.executionDeviceId && !agentLocationSelectableRef.current) return false;
touchedRef.current = true;
agentChosenRef.current = true;
convergeGenRef.current += 1;
@@ -670,11 +679,11 @@ export function useOrcaWorkerForm(params: {
agents,
pickerAgents,
valid: canSubmitOrcaWorkerForm(form, customRoleMode)
- && (!form.modelSelectionExplicit || params.agentLocationSelectable === true
- || form.agentDeviceId === undefined || form.agentDeviceId === (params.leadAgentDeviceId ?? null))
+ && (!form.modelSelectionExplicit || workerAgentLocationSelectable
+ || form.agentDeviceId === undefined || form.agentDeviceId === (form.executionDeviceId ? null : params.leadAgentDeviceId ?? null))
&& (!form.executionDeviceId || executionDevices.some((device) => device.deviceId === form.executionDeviceId && device.supported)),
- /** 模型选择器是否列出远程供应商(被控电脑支持给 Worker 选 Agent 位置,且没选运行设备)。 */
- agentLocationSelectable: params.agentLocationSelectable === true && !form.executionDeviceId,
+ /** 模型选择器是否列出远程供应商(Lead 与选定工作电脑均支持独立 Agent 位置)。 */
+ agentLocationSelectable: workerAgentLocationSelectable,
reset,
remember,
directoryPicker,
@@ -731,7 +740,7 @@ export function useSessionOrcaCollab(params: {
const workerForm = useOrcaWorkerForm({
maker,
executionMakerForDevice: params.executionMakerForDevice,
- executionDevicesEnabled: eligible && !session?.remoteHostId && !session?.agentDeviceId,
+ executionDevicesEnabled: eligible && !session?.remoteHostId,
prefsScope,
taskHostDeviceId: deviceId,
sshRemote: !!session?.remoteHostId,
diff --git a/docs/dev-rules/orca-team-architecture.md b/docs/dev-rules/orca-team-architecture.md
index 827200fffb..5f1478e0e5 100644
--- a/docs/dev-rules/orca-team-architecture.md
+++ b/docs/dev-rules/orca-team-architecture.md
@@ -381,6 +381,14 @@ Git worktree,不改变供应商、模型与 Worker 创建权限偏好。
5a. **自动续跑窗口内的 vendor 终态不是产品错误(状态:不变量)**<br>
Worker turn 被 vendor 报终止型 error,但 interrupted-turn auto-resume 仍 pending / deferred 时,不得 auto-bridge「异常终止」,也不得把 worker DB 标成 `error`。同一失败轮随后的 unclaimed `done`(Codex/Claude 的 error→done 尾巴)同样不是产品终态,不得 `handleWorkerTerminalTurn(status:'done')`:那会把仍在续跑的 worker 标成 done、清掉 auto-bridge runtime,并让后续 L3 surface 命中终态短路而漏报。零输出 / 纯 tool 失败轮没有 assistant persist id;用户接手还会 force-flush suppressed entry 并清 pending。这条失败轮 completion tail 必须独立于这两份状态,按失败轮的 `sessionTurnGeneration` 活到配对 `done` 被消费,且不得在用户 enqueue 时清掉。新 attempt 的 token-bearing running 才丢掉它,以免误伤续跑成功后的产品 `done`。没有配对 `done` 的旧 tail(SDK / event loop crash 等)不得靠 `status(true)` 无 token 一直活着:后续普通用户 / Orca 新 turn 常常没有 `turnAttemptToken`,其更大 generation 的 `done` 不是这条尾巴,必须照常 `handleWorkerTerminalTurn`。auto-bridge pending 必须保留,以便续跑成功后的真实 `done` 仍能桥接。仅当续跑耗尽、被拒绝、或作为产品失败 surface 时,才用当初压住的 terminal payload(含 capture 身份)恰好一次调用 `handleWorkerTerminalTurn`。flush / discard / 用户接手 / 手动 stop 不得走这条收口。实现指针:`register.ts` 的 event adapter、`autoResumeBookkeeping.ts` 的 `shouldSkipOrcaWorkerTerminal` / `noteFailedTurnCompletionTail` 与 suppressed-error surface 路径。
+跨设备自动回报遵守同一边界:`orcaRemoteWorkerRuntime.readDelivery` 检查运行设备投影的
+`turnInProgress`、`autoResumePending`、`usageLimitWait` 及队列里的隐藏 `autoResume` 输入。
+退避、排队或派发准备不能因 vendor 暂时空闲而回报进度、清除派活身份或累计缺少回复次数;
+历史读取后复核一次,若恢复已开始则丢弃该次候选和分页游标,待真正结束后从最新历史重读。
+后续插话的恢复按 `retrySourceClientId` / 输入身份隔离;宿主放弃恢复后仍按原错误边界收尾。
+旧端字段缺省保留兼容行为。回归见 `orcaRemoteWorkerRuntime.test.ts` 及
+`agent-input-coordinator.test.ts` 的真实协调器与轮询器组合用例。
+
6. **Lead 只能管理自己的排队消息,撤回必须结清 accepted 暂存(状态:不变量)**<br>
`get_worker_queue_status` / `update_queued_message` / `cancel_queued_message` 经 `resolveWorkerRef` 按 caller Lead 归属校验后,只允许操作目标 worker 队列中 `origin.kind='orca'` 的条目(worker 队列中的 orca 条目只可能来自其 Lead);队列可见性口径是「看得全、只能动自己的」(2026-07-21 产品决策)——用户手打与 scheduler 排队条目对 Lead 正文可见(供基于完整队列内容编排),pre-dispatch active / direct steering 条目也必须出现并标记 `consuming=true`,但非 Lead 条目不可改不可撤(`NOT_LEAD_MESSAGE`)。`get_workspace_info` 与 `get_worker_queue_status` 的 `queued_count` 都必须使用这份完整 inspection 的 `messages.length`,不能让 workspace 只数 pending。修改是整条正文替换,必须经 `rebuildQueuedOrcaLeadMessage` 按原派发格式重建 `text` / `persistedContent` / `chatMessage.content` / `origin.displayText`,身份字段(clientId / createOpts / createdAt / senderLabel)锚定原条目;不许直接调 coordinator 的 `updateText`(会破坏 orca 派发格式耦合)。撤回必须走 coordinator `remove`(触发 `onDiscardedQueuedMessage` → dispatcher 丢弃该 clientId 的 accepted 暂存回调,与 Stop 清队列同一条 settle 路径),否则 accepted 回调表泄漏。steering 中的条目一律拒绝(`MESSAGE_CONSUMING`)。实现指针:`orcaTeamService.ts` 的 `resolveLeadQueuedMessage` 与队列控制方法、`orcaInterAgentDispatcher.ts` 的 `rebuildQueuedOrcaLeadMessage`、`agent-input-coordinator.ts` 的 `replaceQueuedMessage`。
@@ -437,10 +445,10 @@ Worker turn 被 vendor 报终止型 error,但 interrupted-turn auto-resume 仍
Lead 派完活结束本轮时,团队仍在干活,这一轮不是完成:灵动岛保持 Lead 为运行中(不出完成卡片、不响完成音、不记未读),Work Louder 键盘、侧栏卡片与远程会话列表读同一份活动快照,因此一起保持运行中;renderer 不发完成通知(桌面/手机/飞书)、不亮完成角标。Worker 回报送达后 Lead 被唤起,那一轮的 done 才是团队完成。判据只有一份,在 Main:以「仍有 accepted 派活欠 Lead 回报」(auto-bridge pending)为准,最后一份回报送达或被丢弃(手动停止、归档等)时,若 Lead 空闲则补发被推迟的完成;renderer 不自行推算 Worker 状态,完成去抖落地时读灵动岛活动快照,Main 仍把该会话保持为 `running` 就不算完成(暂停的输入队列同样会让灵动岛保持运行中,但保留原有完成提醒,故排除)。Worker 自身仍不进灵动岛;Worker 的完成不单独通知,出错与需要确认以「Lead 标题 · Worker 标题」单独通知(桌面 / 飞书 / 手机推送,走同一个 `sendSessionEventNotification`;找不到 Lead 时退回 Worker 标题;只覆盖本机 Worker),点击按 Worker id 经 `resolveSessionRoute` 落到 Lead 并打开该 Worker。Worker 出错后 Lead 被唤起处理完还会有一条 Lead 完成通知,两条都保留。已知空档(用户接受):开启灵动岛时渲染端不弹系统横幅,而 Worker 不进灵动岛,这段时间 Worker 的出错 / 确认收不到桌面弹窗,飞书 / 手机推送不受影响。实现指针:`CCAgentSidebarUpper.tsx` 的 `fireSessionNotification`,`orcaLeadWorkerAttention.ts` 的 `shouldNotifyOrcaWorkerEvent` / `formatOrcaWorkerNotificationTitle` / `findOrcaLeadSessionIdForWorker`。已知边界(刻意不处理,保持简单):派给正忙 Worker、尚在其队列里未被接收的任务还没有待回报记录(Worker 正忙通常意味着已有同一 Lead 的待回报记录);静默完成(如静默的自动运行)不走推迟,Lead 活动会直接变为完成。实现指针:`orcaTeamService.ts` 的 `hasPendingWorkerReports` / `deletePendingReport` / `onLeadWorkerReportsSettled`,`register.ts` 的 `setCompletionDeferResolver` 与 `onLeadWorkerReportsSettled` wiring,`agent-island/service.ts` 的 `notifyQueueEmptied`,renderer `state/agentIslandActivity.ts` 的 `isSessionCompletionHeldByAgentIsland` 与 `useSessionRunningStatus.ts` 的 done debounce。
10. **远端 Worker 只在运行设备上跑(状态:不变量)**
- Worker 可以放到同账号另一台电脑(运行设备)上运行:真实任务在那台,本机只有一条不跑 Agent、`working_dir` 为空的代理任务行,`orca_workers.execution_device_id` / `remote_session_id` 记录位置。代理行承接计槽、状态机、auto-bridge 与归档,任何路径都不得在本机为它起 Agent(`bootstrapSession` 对远端 Worker 直接拒绝)、不得把它复制到其他电脑;派活、停止与存活查询经 `orcaRemoteWorkers.ts` 的 `wrapTeamDeps` 分流到运行设备,其余依赖原样透传,不另造状态机。回报靠轮询:派出的消息已进入对话(投递回执 accepted)且设备不在跑时,分页读取 user / assistant 历史,按派活 user 的 clientId 定位对应的最后一条 assistant 回复并按消息 id 去重;后续用户插话的回复和异常状态不得归给此前派活,历史读取期间的新派活不得被旧回报清除。每轮最多扫描 2000 行,预算不足时保留游标下一轮续读,不误判缺少回复;宿主 onAccepted / onAcceptedCommit 完成后才冻结回报身份并允许轮询收尾,accepted 回调失败恢复上一代等待状态,保存旧结果期间不得消费新派活身份或写入其捕获文本。同一远端 Worker 的 enqueue、accepted / commit 和身份确认复用现成 session 发送锁串行执行,避免并发回调与投递顺序错位。用户在运行设备上直接发的消息算插话,不触发回报。设备不可达只是运行期投影(`executionDevice.reachable`),不扩展 `OrcaWorkerStatus`;派活时不可达直接失败,不回退到本机。远端 Worker 通过运行设备转发四个既有 Worker 桥接工具,Lead 按同账号来源设备、真实任务、Worker 与 active team 核对归属;旧端没有该通道时保留自动回报。远端队列编辑仍不支持;send_to_lead 的 steer 由 Lead 所在电脑沿本机原有守卫判定。界面:创建弹窗的「运行设备」只在本机 Lead 上出现(`CreateWorkerPopover` 的 `executionDevicesEnabled`),复用标准下拉列表,以有界滚动和键盘按名称定位应对多设备;选了其他电脑后,工作目录提供「对话 / 指定目录」,「对话」不传 `workingDir`、在运行设备创建不绑定项目的任务,「指定目录」只使用那台电脑上的绝对路径。手机版的新任务「开启协同」与 Lead「创建 Worker」共用设备下拉列表和两种目录模式;设备列表从 Lead 所在电脑读取,Agent、模型和供应商目录从所选运行设备读取。协同面板对远端 Worker 展示运行设备上的真实任务(`RemoteWorkerSessionPane`,先登记归属再读写)。实现指针:`orcaRemoteWorkerRuntime.ts`、`orcaRemoteWorkers.ts`、`orcaWorkerCreationService.ts` 的 `createRemoteWorkerInTeam`、运行设备侧 `orcaRemoteWorkerHost.ts`;协议见 `protocol-compatibility.md`「协同远端 Worker」。
+ Worker 可以放到同账号另一台电脑(运行设备)上运行:真实任务在那台,本机只有一条不跑 Agent、`working_dir` 为空的代理任务行,`orca_workers.execution_device_id` / `remote_session_id` 记录位置。代理行承接计槽、状态机、auto-bridge 与归档,任何路径都不得在本机为它起 Agent(`bootstrapSession` 对远端 Worker 直接拒绝)、不得把它复制到其他电脑;派活、停止与存活查询经 `orcaRemoteWorkers.ts` 的 `wrapTeamDeps` 分流到运行设备,其余依赖原样透传,不另造状态机。回报靠轮询:派出的消息已进入对话(投递回执 accepted)且设备不在跑时,分页读取 user / assistant 历史,按派活 user 的 clientId 定位对应的最后一条 assistant 回复并按消息 id 去重;后续用户插话的回复和异常状态不得归给此前派活,历史读取期间的新派活不得被旧回报清除。每轮最多扫描 2000 行,预算不足时保留游标下一轮续读,不误判缺少回复;宿主 onAccepted / onAcceptedCommit 完成后才冻结回报身份并允许轮询收尾,accepted 回调失败恢复上一代等待状态,保存旧结果期间不得消费新派活身份或写入其捕获文本。同一远端 Worker 的 enqueue、accepted / commit 和身份确认复用现成 session 发送锁串行执行,避免并发回调与投递顺序错位。用户在运行设备上直接发的消息算插话,不触发回报。设备不可达只是运行期投影(`executionDevice.reachable`),不扩展 `OrcaWorkerStatus`;派活时不可达直接失败,不回退到本机。远端 Worker 通过运行设备转发四个既有 Worker 桥接工具,Lead 按同账号来源设备、真实任务、Worker 与 active team 核对归属;旧端没有该通道时保留自动回报。远端队列编辑仍不支持;send_to_lead 的 steer 由 Lead 所在电脑沿本机原有守卫判定。界面:创建弹窗的「运行设备」适用于桌面本机任务及手机控制的非 SSH Lead;桌面远控视角保留原目录读取边界,控制端自身不能经 device-link 读取自己的目录,跨设备派发仍可由 Lead 的 MCP 执行;Lead 的 Agent 在其他电脑运行也可派发跨设备 Worker。工作电脑与 Agent 所在电脑可独立选择,后者需工作电脑声明 `agentDevice` 能力。入口由 `CreateWorkerPopover.executionDevicesEnabled` 控制,复用标准下拉列表,以有界滚动和键盘按名称定位应对多设备;选了其他电脑后,工作目录提供「对话 / 指定目录」,「对话」不传 `workingDir`、在运行设备创建不绑定项目的任务,「指定目录」只使用那台电脑上的绝对路径。手机版的新任务「开启协同」与 Lead「创建 Worker」共用设备下拉列表和两种目录模式;设备列表从 Lead 所在电脑读取,Agent、模型和供应商目录从所选运行设备读取。协同面板对远端 Worker 展示运行设备上的真实任务(`RemoteWorkerSessionPane`,先登记归属再读写)。实现指针:`orcaRemoteWorkerRuntime.ts`、`orcaRemoteWorkers.ts`、`orcaWorkerCreationService.ts` 的 `createRemoteWorkerInTeam`、运行设备侧 `orcaRemoteWorkerHost.ts`;协议见 `protocol-compatibility.md`「协同远端 Worker」。
11. **Worker 的 Agent 位置:远程供应商与本机供应商一视同仁(状态:不变量,2026-10-10 用户裁决)**
- 与上一条「运行设备」不同,这里任务、目录、命令与文件都留在 Lead 所在电脑,只有 Worker 的 Agent 在另一台同账号电脑或分享来的供应商上运行(与普通任务的远程 Agent 同一机制,`sessions.agent_device_id`)。每个 Worker 可以单独选位置:`OrcaWorkerCreateParams.agentDeviceId` 不传 = 跟 Lead(旧调用方、旧控制端与 MCP 省略时都走这里),`null` = 任务所在电脑,string = 那台电脑或 `share:<id>`;等于本机设备 id 时按 `null`。模型与来源按 Worker 自己的位置读目录(那台只列允许被远程调用的供应商),只有与 Lead 同一位置时才沿用 Lead 的来源(来源 id 在不同电脑上不是一回事);Agent 在另一台时不按本机的 Cindy AI key 判预算模型。那台读不到目录在占槽与启动前失败(`REMOTE_AGENT_DEVICE_UNREACHABLE` / `REMOTE_AGENT_SHARE_*`),不回退到本机。SSH Lead 与运行设备 Worker 不能再指定另一台(`INVALID_PARAMS`),插件任务只能跟 Lead 或留在任务所在电脑。入口一处一套:桌面「创建 Worker / 开启协同」弹窗与新建任务用同一个模型面板,任务所在电脑的供应商之后列其他电脑与分享(`useWorkerAgentDevices`),选中哪一行 Worker 的 Agent 就在哪运行,默认选中 Lead 的位置;选了远程就不提供运行设备,选了运行设备回到任务所在电脑。桌面手动选择模型并提交创建后,在 `workerCreationPrefs.modelSelectionByHost` 按账号与任务所在电脑保存完整选择(Agent、模型、来源、Agent 所在电脑、推理强度与 Fast),下次打开优先恢复,不被 Lead 后续换模型或换位置覆盖;未手动选择时仍跟随 Lead 的位置,取消未提交的编辑不保存。旧版逐 Agent 记忆继续可读,不推测它原先属于哪台电脑;SSH 与运行设备的临时选择不写入这份位置记忆。远程选择不覆盖旧版逐 Agent 的本机目录记忆,模型行的档位预设仍使用 `agentDeviceModelMemory`。回归见 `CreateWorkerPopover.test.tsx` 的重新打开与任务所在电脑隔离用例。手机同样支持选择 Agent 位置(`useOrcaWorkerForm` 的 `agentDeviceId`,模型面板 `remote` 与新建任务同一份 `useRemoteAgentCatalogs`),通过 `orcaWorkerPrefs.modelSelectionByHost` 在手机本地按账号与任务所在电脑保存同样的完整选择,创建成功或确认新任务协同草稿后写回;异步读取不能覆盖已编辑的表单。恢复的来源或模型不可用时保留原路线,由界面阻止或宿主明确拒绝,不静默换到别处;旧端不能兑现位置时同样拒绝。回归见 `useOrcaWorkerForm.test.tsx` 与 `orcaTeam.test.ts`。被控电脑声明 `supportsOrcaWorkerAgentDevice` 时新建任务的远程供应商与协同不再互斥。Lead 的 `list_available_models` 可按 `agent_device_id` 列那里的模型并给出 `locations`,`create_worker` / `create_workers` 用同一个 `agent_device_id`。Worker 列表投影 `session.agentDeviceId`,桌面 Worker 头像叠与远程任务同款的单波纹 + 点;手机 Worker 行保持原来的状态圆点,不加远程标识(2026-10-11 用户要求维持原样)。已开始的 Lead 与 Worker 可以由用户在模型列表里换 Agent 位置(本机供应商、其他电脑、分享来的供应商一起列出),与普通任务同一套换电脑事务:选择先登记为意图,下一次发送边界全量交接后在新位置重建,协同身份不变(2026-10-16 用户裁决:任务都在本机,只换供应商所在电脑,不应排除)。运行设备 Worker 与 SSH 任务仍不开放;被控电脑上的协同任务暂不在控制端开放(旧版被控端会拒绝),手机端同样暂未开放。供应商组为任务换电脑见第 12 条。实现指针:`orcaWorkerCreationService.ts` 的 `resolveWorkerAgentDeviceId` / `agentDeviceCatalogFailure`,`register.ts` 的 `listWorkerAgentLocations` 与 `listAvailableModels`,renderer `CreateWorkerPopover.tsx`、`hooks/useWorkerAgentDevices.ts`;协议见 `protocol-compatibility.md`「协同 Worker 的 Agent 位置」。
+ 与上一条「运行设备」不同,这里任务、目录、命令与文件都留在 Lead 所在电脑,只有 Worker 的 Agent 在另一台同账号电脑或分享来的供应商上运行(与普通任务的远程 Agent 同一机制,`sessions.agent_device_id`)。每个 Worker 可以单独选位置:`OrcaWorkerCreateParams.agentDeviceId` 不传 = 跟 Lead(旧调用方、旧控制端与 MCP 省略时都走这里),`null` = 任务所在电脑,string = 那台电脑或 `share:<id>`;等于本机设备 id 时按 `null`。模型与来源按 Worker 自己的位置读目录(那台只列允许被远程调用的供应商),只有与 Lead 同一位置时才沿用 Lead 的来源(来源 id 在不同电脑上不是一回事);Agent 在另一台时不按本机的 Cindy AI key 判预算模型。那台读不到目录在占槽与启动前失败(`REMOTE_AGENT_DEVICE_UNREACHABLE` / `REMOTE_AGENT_SHARE_*`),不回退到本机。SSH Lead 不能指定另一台(`INVALID_PARAMS`);跨设备 Worker 创建时可以指定独立的 Agent 电脑,`agentDeviceId` 相对工作电脑解释,省略或 null 使用工作电脑默认,不继承 Lead。工作电脑先按所选供应商电脑的目录准入,复用普通任务的远程 Agent 与工具执行通道,不迁移工作目录,插件任务只能跟 Lead 或留在任务所在电脑。入口一处一套:桌面「创建 Worker / 开启协同」弹窗与新建任务用同一个模型面板,任务所在电脑的供应商之后列其他电脑与分享(`useWorkerAgentDevices`),选中哪一行 Worker 的 Agent 就在哪运行,默认选中 Lead 的位置;选择远程供应商后仍保留工作电脑入口;切换工作电脑先恢复该电脑本机默认,随后可选择它能调用的远程供应商或分享。旧版工作电脑不开放独立 Agent 位置,显式请求不能被静默忽略。桌面手动选择模型并提交创建后,在 `workerCreationPrefs.modelSelectionByHost` 按账号与任务所在电脑保存完整选择(Agent、模型、来源、Agent 所在电脑、推理强度与 Fast),下次打开优先恢复,不被 Lead 后续换模型或换位置覆盖;未手动选择时仍跟随 Lead 的位置,取消未提交的编辑不保存。旧版逐 Agent 记忆继续可读,不推测它原先属于哪台电脑;SSH 与运行设备的临时选择不写入这份位置记忆。远程选择不覆盖旧版逐 Agent 的本机目录记忆,模型行的档位预设仍使用 `agentDeviceModelMemory`。回归见 `CreateWorkerPopover.test.tsx` 的重新打开与任务所在电脑隔离用例。手机同样支持选择 Agent 位置(`useOrcaWorkerForm` 的 `agentDeviceId`,模型面板 `remote` 与新建任务同一份 `useRemoteAgentCatalogs`),通过 `orcaWorkerPrefs.modelSelectionByHost` 在手机本地按账号与任务所在电脑保存同样的完整选择,创建成功或确认新任务协同草稿后写回;异步读取不能覆盖已编辑的表单。恢复的来源或模型不可用时保留原路线,由界面阻止或宿主明确拒绝,不静默换到别处;旧端不能兑现位置时同样拒绝。回归见 `useOrcaWorkerForm.test.tsx` 与 `orcaTeam.test.ts`。被控电脑声明 `supportsOrcaWorkerAgentDevice` 时新建任务的远程供应商与协同不再互斥。Lead 的 `list_available_models` 可按 `agent_device_id` 列那里的模型并给出 `locations`,`create_worker` / `create_workers` 用同一个 `agent_device_id`。Worker 列表投影 `session.agentDeviceId`,桌面 Worker 头像叠与远程任务同款的单波纹 + 点;手机 Worker 行保持原来的状态圆点,不加远程标识(2026-10-11 用户要求维持原样)。已开始的 Lead 与 Worker 可以由用户在模型列表里换 Agent 位置(本机供应商、其他电脑、分享来的供应商一起列出),与普通任务同一套换电脑事务:选择先登记为意图,下一次发送边界全量交接后在新位置重建,协同身份不变(2026-10-16 用户裁决:任务都在本机,只换供应商所在电脑,不应排除)。运行设备 Worker 与 SSH 任务仍不开放;被控电脑上的协同任务暂不在控制端开放(旧版被控端会拒绝),手机端同样暂未开放。供应商组为任务换电脑见第 12 条。实现指针:`orcaWorkerCreationService.ts` 的 `resolveWorkerAgentDeviceId` / `agentDeviceCatalogFailure`,`register.ts` 的 `listWorkerAgentLocations` 与 `listAvailableModels`,renderer `CreateWorkerPopover.tsx`、`hooks/useWorkerAgentDevices.ts`;协议见 `protocol-compatibility.md`「协同 Worker 的 Agent 位置」。
12. **协同任务归供应商组,换电脑不丢回报(状态:不变量,2026-10-10 用户裁决)**
Lead 与 Worker 与普通任务一样归供应商组分配、出问题时自动换电脑(产品口径见 `docs/product-rules/provider-groups.md` §6.1「协同任务」),只有审查任务仍排除(`readProviderGroupSessionRow`)。要点:
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 1032877a2e..3d7b9db479 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -1446,11 +1446,15 @@ Codex 原生图片恢复(#6412)在既有 `maker:remote-agent:v1` 上追加
字段;这两个协议位是整台 A 的,控制端用 A 一定注册的 Claude Code 读(Worker 选的 Agent 可能只装在 Agent 所在
电脑上)。开启协同提交前再按能力核对一次,降级的 A 直接失败、不静默建错;控制端读不到 Lead 所在位置的目录时
(控制端自己、只有 A 收到的分享)维持 A 的目录、不发这个字段。A 在占槽与启动前读那台的目录,读不到回
- `REMOTE_AGENT_DEVICE_UNREACHABLE` / `REMOTE_AGENT_SHARE_*`;与运行设备(`executionDeviceId`)同给、SSH Lead 回
- `INVALID_PARAMS`。Worker 列表(`local-db:orca-workflows:list-workers-by-lead` 的 `session.agentDeviceId`)只在 Agent
+ `REMOTE_AGENT_DEVICE_UNREACHABLE` / `REMOTE_AGENT_SHARE_*`;SSH Lead 回
+ `INVALID_PARAMS`。与 `executionDeviceId` 同给时,位置相对工作电脑,省略或 null 使用该电脑默认;
+ Lead 的 Agent 在其他电脑运行不影响创建。工作电脑 `remote-worker:caps.agentDevice: true` 且 Lead 的
+ `execution-devices` 投影 `supportsAgentDevice: true` 才开放独立位置;显式字段发给旧端前返回
+ `UNSUPPORTED_CAPABILITY`,不静默建错。新增同账号 `maker:orca:remote-worker:models` 查询 `{agent?, agentDeviceId?}`,
+ 返回模型列表与 `locations`;共享访客不可调用。open 新增可选 `agentDeviceId`,回包可带准入后的
+ `agentDeviceId` / `providerId`;旧请求仍保持原行为。`list_available_models.execution_device_id` 从工作电脑读取目录。Worker 列表(`local-db:orca-workflows:list-workers-by-lead` 的 `session.agentDeviceId`)只在 Agent
不在任务所在电脑时带值,旧端忽略即可。Lead 的 MCP 工具同步:`list_available_models` 可选 `agent_device_id` 并返回
- `locations`,`create_worker` / `create_workers` 可选 `agent_device_id`(`"local"` = 任务所在电脑)。不新增 channel,
- allowlist 不变。回归见 `orcaWorkerCreationService.test.ts`、`CreateWorkerPopover.test.tsx`、Mobile
+ `locations`,`create_worker` / `create_workers` 可选 `agent_device_id`(`"local"` = 任务所在电脑)。同账号 allowlist 新增上述 models 查询;共享任务清单不变。回归见 `orcaWorkerCreationService.test.ts`、`CreateWorkerPopover.test.tsx`、Mobile
`orcaTeam.test.ts` / `useOrcaWorkerForm.test.tsx`。
- **账号余量**(2026-10-09):这一轮消耗的是 Agent 所在那台(B)的账号,桌面底部用量 chip 与手机任务菜单都改读 B 的
余量,不读任务所在电脑(本机或被控电脑)的同名账号。直接经 device-link 调 B 已有的 `maker:usage:*` 读取与推送
@@ -1581,6 +1585,13 @@ Codex 原生图片恢复(#6412)在既有 `maker:remote-agent:v1` 上追加
## 协同远端 Worker:Worker 在另一台电脑运行
+`maker:input:get-projection` 的既有输入投影可选增加 `turnInProgress`,由输入协调器按
+当前派发、运行、交互及终态持久化边界生成;它不表示 vendor 的 `isTurnRunning`。
+Lead 的自动回报同时识别既有 `autoResumePending`、`usageLimitWait` 和隐藏续跑队列,
+读取历史后再次核对投影,恢复期间保留原派活身份,不推进回报去重游标。旧查看端忽略新字段;
+新 Lead 连接旧运行端时仍使用既有恢复字段,完整的进行中边界核对需要运行端同时更新。
+只调整单个 Worker 的回报收尾,不改变通道、权限、relay、服务端或 Mobile 原生配置。
+
主动回报可选追加 `maker:orca:remote-worker:bridge`,仅同账号 allowlist;不进入共享任务、
供应商分享清单。运行设备从本机持久来源标记选定 Lead 电脑,传真实任务 ID、Lead ID、
四个既有 Worker 工具名之一与其原参数。Lead 从 server 盖章的来源设备 ID 反查 active team
@@ -1618,7 +1629,7 @@ B 上的 Worker 是一条普通任务,`sessions.orca_remote_lead`(migration 01
方案与产品决策见 [`../orca-cross-device-worker-plan.md`](../orca-cross-device-worker-plan.md)。
- **新增 channel**(`packages/device-link/src/orcaRemoteWorker.ts`,只进同账号 allowlist,不进共享任务清单):
- `maker:orca:remote-worker:caps`(能力探测,回 `{ version }`)、`…:open`(按 A 给定的任务 id 新建 Worker 任务,
+ `maker:orca:remote-worker:caps`(能力探测,回 `{ version, agentDevice? }`)、`…:models`(查询工作电脑的模型与 Agent 位置)、`…:open`(按 A 给定的任务 id 新建 Worker 任务,
幂等;超时 60s)、`…:release`(结束协同,任务与文件保留,幂等)。B 侧实现见
`apps/desktop/src/main/maker-ipc/orcaRemoteWorkerHost.ts`。
- **幂等 open 的终态检查**:同来源、同 Lead 且未 release 的已有任务也必须仍为 `active`;
diff --git a/docs/product-rules/agent-user-parity.md b/docs/product-rules/agent-user-parity.md
index 077fc80636..9181651067 100644
--- a/docs/product-rules/agent-user-parity.md
+++ b/docs/product-rules/agent-user-parity.md
@@ -49,6 +49,7 @@
| 任务 | 模型、推理强度、Fast | 有 | 无 |
| 任务 | 删除、Fork、Rewind、切换权限档、代用户确认权限或回答提问 | 无 | 无 |
| 协同 / Worker | 单个 / 批量创建、指定已有目录、查询实际目录与自有 worktree | 有 | 有(运行设备;新建 worktree 仅本机) |
+| 协同 / Worker | Lead 使用远程供应商时派发跨设备 Worker;独立选择工作电脑与模型电脑 | 有 | 有(`execution_device_id` + `agent_device_id`;目录查询支持同一工作电脑范围) |
| 协同 / Worker | 为 Worker 新建 worktree、指定源分支、归档时回收 | 有 | 无 |
| 定时任务 | 列出、详情、运行记录、修改、暂停、恢复、删除、立即运行 | 有 | 有(2026-10-14) |
| 定时任务 | 新建、安装检查脚本 | 有 | 无 |
diff --git a/packages/device-link/src/__tests__/orcaRemoteWorker.test.ts b/packages/device-link/src/__tests__/orcaRemoteWorker.test.ts
index 0755f7f59f..01b593d87a 100644
--- a/packages/device-link/src/__tests__/orcaRemoteWorker.test.ts
+++ b/packages/device-link/src/__tests__/orcaRemoteWorker.test.ts
@@ -3,6 +3,7 @@ import {
INVOKE_TIMEOUT_OVERRIDES_MS,
ORCA_REMOTE_WORKER_CAPS_CHANNEL,
ORCA_REMOTE_WORKER_BRIDGE_CHANNEL,
+ ORCA_REMOTE_WORKER_MODELS_CHANNEL,
ORCA_REMOTE_WORKER_OPEN_CHANNEL,
ORCA_REMOTE_WORKER_OPEN_TIMEOUT_MS,
ORCA_REMOTE_WORKER_RELEASE_CHANNEL,
@@ -10,6 +11,7 @@ import {
parseOrcaRemoteWorkerOpenRequest,
parseOrcaRemoteWorkerReleaseRequest,
parseOrcaRemoteWorkerBridgeRequest,
+ parseOrcaRemoteWorkerModelsRequest,
} from '../index.js';
const base = {
@@ -45,6 +47,7 @@ describe('orca remote worker channels', () => {
for (const channel of [
ORCA_REMOTE_WORKER_CAPS_CHANNEL,
ORCA_REMOTE_WORKER_BRIDGE_CHANNEL,
+ ORCA_REMOTE_WORKER_MODELS_CHANNEL,
ORCA_REMOTE_WORKER_OPEN_CHANNEL,
ORCA_REMOTE_WORKER_RELEASE_CHANNEL,
]) {
@@ -60,6 +63,11 @@ describe('orca remote worker channels', () => {
});
describe('parseOrcaRemoteWorkerOpenRequest', () => {
+ // Unit protocol regression: the execution computer must receive the selected
+ // model computer. Previously the parser silently dropped that route.
+ it.each([null, 'provider-pc', 'share:approved'])('preserves the independent Agent location %s', agentDeviceId => {
+ expect(parseOrcaRemoteWorkerOpenRequest({ ...base, agentDeviceId })).toMatchObject({ agentDeviceId });
+ });
it('keeps known fields, trims text and drops unknown fields', () => {
expect(
parseOrcaRemoteWorkerOpenRequest({
@@ -92,11 +100,21 @@ describe('parseOrcaRemoteWorkerOpenRequest', () => {
['missing worker label', { ...base, lead: { ...base.lead, workerLabel: '' } }],
['working dir with newline', { ...base, workingDir: '/tmp/a\nb' }],
['non-boolean fastMode', { ...base, fastMode: 'yes' }],
+ ['invalid model computer', { ...base, agentDeviceId: '../elsewhere' }],
])('rejects %s', (_name, input) => {
expect(() => parseOrcaRemoteWorkerOpenRequest(input)).toThrow(/\[INVALID_PARAMS\]/);
});
});
+describe('execution host model discovery', () => {
+ it('preserves remote scopes and rejects malformed inputs before discovery', () => {
+ expect(parseOrcaRemoteWorkerModelsRequest({})).toEqual({});
+ expect(parseOrcaRemoteWorkerModelsRequest({ agent: 'pi', agentDeviceId: 'provider-pc' })).toEqual({ agent: 'pi', agentDeviceId: 'provider-pc' });
+ expect(() => parseOrcaRemoteWorkerModelsRequest({ agentDeviceId: 42 })).toThrow(/INVALID_PARAMS/);
+ expect(() => parseOrcaRemoteWorkerModelsRequest({ agent: 'unknown' })).toThrow(/INVALID_PARAMS/);
+ });
+});
+
describe('parseOrcaRemoteWorkerReleaseRequest', () => {
it('accepts a safe session id only', () => {
expect(parseOrcaRemoteWorkerReleaseRequest({ sessionId: 'w_remote_1', x: 1 })).toEqual({
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index da685906a6..5099883bd9 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -31,6 +31,7 @@ import {
ORCA_EXECUTION_DEVICES_CHANNEL,
ORCA_REMOTE_WORKER_CAPS_CHANNEL,
ORCA_REMOTE_WORKER_BRIDGE_CHANNEL,
+ ORCA_REMOTE_WORKER_MODELS_CHANNEL,
ORCA_REMOTE_WORKER_OPEN_CHANNEL,
ORCA_REMOTE_WORKER_OPEN_TIMEOUT_MS,
ORCA_REMOTE_WORKER_RELEASE_CHANNEL,
@@ -450,6 +451,7 @@ const EXTENDED_INVOKE_CHANNELS: readonly string[] = [
// 老版本无 handler → CHANNEL_NOT_ALLOWED,控制端提示更新而不回退普通建任务。
ORCA_REMOTE_WORKER_CAPS_CHANNEL,
ORCA_REMOTE_WORKER_BRIDGE_CHANNEL,
+ ORCA_REMOTE_WORKER_MODELS_CHANNEL,
ORCA_REMOTE_WORKER_OPEN_CHANNEL,
ORCA_REMOTE_WORKER_RELEASE_CHANNEL,
// 远程控制 Lead 所在电脑时,读取那台视角下可选的运行设备(只读,真相在被控端)。
diff --git a/packages/device-link/src/orcaRemoteWorker.ts b/packages/device-link/src/orcaRemoteWorker.ts
index f399acc90e..3b4ee74a61 100644
--- a/packages/device-link/src/orcaRemoteWorker.ts
+++ b/packages/device-link/src/orcaRemoteWorker.ts
@@ -1,16 +1,18 @@
/**
* 协同远端 Worker(同账号):Lead 与团队留在发起电脑(控制端),单个 Worker 的任务、目录、
- * 命令与文件都在运行设备(被控端)上。运行设备上的 Worker 是一条普通任务,带「来自哪台
- * 电脑的协同」标记;派活、停止与自动回报复用现有会话通道;以下登记专用生命周期与桥接口:
+ * 命令与文件都在运行设备(被控端)上;Agent 可在独立选定的供应商电脑运行。运行设备上的
+ * Worker 带「来自哪台电脑的协同」标记;派活、停止与自动回报复用现有会话通道:
*
* - `caps`:能力探测。老版本没有该 channel → CHANNEL_NOT_ALLOWED,控制端据此提示更新,
* 不回退到普通建任务(普通任务没有防嵌套与来源标记)。
+ * - `models`:从运行设备的视角查询可用 Agent 位置和模型目录,需协商 agentDevice 能力。
* - `open`:按控制端给定的 sessionId 新建 Worker 任务,幂等(同一控制端重复 open 返回同一任务)。
* 来源电脑身份取 server 盖章的 src,不采信载荷自报。
* - `release`:通知运行设备这个 Worker 已结束协同,任务与文件保留。幂等。
* - `bridge`:运行设备向 Lead 转发四个既有 Worker 工具;只允许绑定的 Worker/active team。
*/
export const ORCA_REMOTE_WORKER_CAPS_CHANNEL = 'maker:orca:remote-worker:caps';
+export const ORCA_REMOTE_WORKER_MODELS_CHANNEL = 'maker:orca:remote-worker:models';
export const ORCA_REMOTE_WORKER_OPEN_CHANNEL = 'maker:orca:remote-worker:open';
export const ORCA_REMOTE_WORKER_RELEASE_CHANNEL = 'maker:orca:remote-worker:release';
/** Execution device → owning Lead. Never exposed to shared-task guests. */
@@ -30,6 +32,8 @@ export interface OrcaExecutionDeviceView {
platform: string | null;
/** false = 那台电脑版本过旧,不支持协同远端 Worker(显示为需要更新)。 */
supported: boolean;
+ /** The Lead and execution host support an independent remote Agent location. */
+ supportsAgentDevice?: boolean;
}
/** 运行设备上 open 可能要准备工作目录并启动 Agent,给足执行与回程余量。 */
@@ -45,6 +49,7 @@ export type OrcaRemoteWorkerPermissionMode =
export interface OrcaRemoteWorkerCaps {
version: number;
workerBridge?: true;
+ agentDevice?: boolean;
}
export const ORCA_REMOTE_WORKER_BRIDGE_TOOLS = ['send_to_lead', 'read_lead_history', 'read_lead', 'lead_status'] as const;
@@ -76,6 +81,27 @@ export function parseOrcaRemoteWorkerBridgeRequest(raw: unknown): OrcaRemoteWork
};
}
+export interface OrcaRemoteWorkerModelsRequest {
+ agent?: OrcaRemoteWorkerAgentKind;
+ /** Omitted/null means the execution computer, never the Lead’s Agent. */
+ agentDeviceId?: string | null;
+}
+
+export interface OrcaRemoteWorkerModelsResult {
+ agentDeviceId?: string | null;
+ locations?: Array<{ agentDeviceId: string; name: string }>;
+ codex?: OrcaRemoteWorkerModel[];
+ claude_code?: OrcaRemoteWorkerModel[];
+ pi?: OrcaRemoteWorkerModel[];
+}
+
+export interface OrcaRemoteWorkerModel {
+ id: string;
+ label: string;
+ providers?: Array<{ id: string; name: string }>;
+ defaultProviderId?: string | null;
+}
+
export interface OrcaRemoteWorkerOpenRequest {
/** 控制端生成的运行设备任务 id;同一 id 重复 open 幂等。 */
sessionId: string;
@@ -83,6 +109,8 @@ export interface OrcaRemoteWorkerOpenRequest {
/** 缺省 = 运行设备的默认模型与来源。 */
model?: string;
providerId?: string;
+ /** Agent location relative to the execution computer; absent/null is local there. */
+ agentDeviceId?: string | null;
effort?: string;
fastMode?: boolean | 'ultrafast';
permissionMode: OrcaRemoteWorkerPermissionMode;
@@ -105,6 +133,8 @@ export interface OrcaRemoteWorkerOpenResult {
effort?: string;
/** 运行设备实际保存的 Fast 状态;缺省 = 旧设备未返回。 */
fastMode?: boolean | 'ultrafast';
+ agentDeviceId?: string | null;
+ providerId?: string | null;
}
export interface OrcaRemoteWorkerReleaseRequest {
@@ -133,6 +163,25 @@ function requiredString(value: unknown, field: string, max = MAX_TEXT): string {
return parsed;
}
+function parseAgentDeviceId(value: unknown): string | null {
+ if (value === null) return null;
+ if (typeof value !== 'string' || !SAFE_ID.test(value.trim())) {
+ throw new Error('[INVALID_PARAMS] agentDeviceId must be a device or shared provider id');
+ }
+ return value.trim();
+}
+
+export function parseOrcaRemoteWorkerModelsRequest(raw: unknown): OrcaRemoteWorkerModelsRequest {
+ if (!isRecord(raw)) throw new Error('[INVALID_PARAMS] models request must be an object');
+ if (raw.agent !== undefined && !ORCA_REMOTE_WORKER_AGENT_KINDS.includes(raw.agent as OrcaRemoteWorkerAgentKind)) {
+ throw new Error('[INVALID_PARAMS] invalid Agent kind');
+ }
+ return {
+ ...(raw.agent !== undefined ? { agent: raw.agent as OrcaRemoteWorkerAgentKind } : {}),
+ ...(raw.agentDeviceId !== undefined ? { agentDeviceId: parseAgentDeviceId(raw.agentDeviceId) } : {}),
+ };
+}
+
export function isOrcaRemoteWorkerSessionId(value: unknown): value is string {
return typeof value === 'string' && SAFE_ID.test(value);
}
@@ -171,6 +220,7 @@ export function parseOrcaRemoteWorkerOpenRequest(raw: unknown): OrcaRemoteWorker
agentKind: agentKind as OrcaRemoteWorkerAgentKind,
...(model ? { model } : {}),
...(providerId ? { providerId } : {}),
+ ...(raw.agentDeviceId !== undefined ? { agentDeviceId: parseAgentDeviceId(raw.agentDeviceId) } : {}),
...(effort ? { effort } : {}),
...((typeof raw.fastMode === 'boolean' || raw.fastMode === 'ultrafast') ? { fastMode: raw.fastMode } : {}),
permissionMode: permissionMode as OrcaRemoteWorkerPermissionMode,
diff --git a/packages/lizi-mcps/src/__tests__/listAvailableModelsTool.test.ts b/packages/lizi-mcps/src/__tests__/listAvailableModelsTool.test.ts
index 7771ee25d5..4719b6767d 100644
--- a/packages/lizi-mcps/src/__tests__/listAvailableModelsTool.test.ts
+++ b/packages/lizi-mcps/src/__tests__/listAvailableModelsTool.test.ts
@@ -11,6 +11,22 @@ function parse(result: XdtHelperToolResult) {
}
describe('list_available_models tool', () => {
+ // Unit: choosing a remote Worker must discover from its work host rather
+ // than the Lead's model computer; unsupported peers retain their error code.
+ it('forwards independent work and model locations and preserves version errors', async () => {
+ const listAvailableModels = vi.fn(async () => ({ ok: false as const,
+ errorCode: 'UNSUPPORTED_CAPABILITY', message: 'update work host' }));
+ const registry = new XdtHelperToolRegistry();
+ registerListAvailableModelsTool(registry, {
+ getSessionContext: () => ({ sessionId: 'lead-1' }), listAvailableModels,
+ });
+ const result = parse(await registry.call('list_available_models', {
+ execution_device_id: 'worker-pc', agent_device_id: 'model-pc', agent: 'codex',
+ }));
+ expect(listAvailableModels).toHaveBeenCalledWith({ callerSessionId: 'lead-1',
+ executionDeviceId: 'worker-pc', agentDeviceId: 'model-pc', agent: 'codex' });
+ expect(result).toMatchObject({ ok: false, errorCode: 'UNSUPPORTED_CAPABILITY' });
+ });
it('returns provider-aware routes without removing the existing model fields', async () => {
const listAvailableModels = vi.fn(async () => ({
ok: true as const,
diff --git a/packages/lizi-mcps/src/xdt-helper/create_worker.ts b/packages/lizi-mcps/src/xdt-helper/create_worker.ts
index 93bb605877..b8e6d80e2c 100644
--- a/packages/lizi-mcps/src/xdt-helper/create_worker.ts
+++ b/packages/lizi-mcps/src/xdt-helper/create_worker.ts
@@ -135,7 +135,7 @@ export const createWorkerSpecSchema = z.object({
execution_device_id: z.string().trim().min(1).max(128).optional()
.describe('可选,运行设备:同账号另一台电脑的设备 id,只能取 get_workspace_info 返回的 execution_devices 中 supported=true 的 device_id。指定后 Worker 的任务、目录、命令与文件都在那台电脑;省略则与 Lead 同一台。那台离线、未开启远程控制或版本过旧时创建失败,不会回退到本机。'),
agent_device_id: z.string().trim().min(1).max(128).optional()
- .describe('可选,Worker 的 Agent 在哪运行(远程供应商):取 list_available_models 的 locations[].agent_device_id,"local" 为这台电脑;省略则与 Lead 相同。任务、目录与命令仍在这台电脑。不能与 execution_device_id 同用。'),
+ .describe('可选,Worker 的 Agent 位置:取 list_available_models 的 locations[].agent_device_id;"local" 为 Worker 工作电脑。指定 execution_device_id 时省略用那台的默认,否则省略跟 Lead。'),
}).strict();
export type CreateWorkerSpec = z.infer<typeof createWorkerSpecSchema>;
@@ -167,7 +167,7 @@ const DESCRIPTION = [
'- working_dir: 可选,Worker 所在主机上已存在的绝对目录。省略时继承 Lead 任务记录的工作目录(启动时的目录),不会跟随之后 cd 进入的 worktree。希望共用你当前的 worktree(含 git worktree add 自建的)时,请显式传其绝对路径;需要独立的新 worktree 时用 new_worktree。显式 working_dir / new_worktree 按会话权限审批。指定 execution_device_id 时目录属于那台电脑,省略由那台分配;校验失败不回退。',
'- new_worktree: 可选对象,为 Worker 新建自有 worktree;source_branch 可省略,默认目标目录当前分支或分离 HEAD 的提交。仅本机有提交的 Git 项目可用;SSH / execution_device_id 不支持,对话 Lead 需显式指定其他项目。返回 working_dir 为实际启动目录,worktree 包含自有检出目录和新分支;归档按普通任务规则回收,未提交改动先快照。',
'- execution_device_id: 可选,运行设备(同账号另一台电脑)的 device_id,只能取 get_workspace_info 的 execution_devices 里 supported=true 的值;指定后 Worker 的任务、目录、命令与文件都在那台电脑,结果仍自动回报给你。用户没有要求放到别的电脑时不要传。',
- '- agent_device_id: 可选,Worker 的 Agent 在哪运行(远程供应商,任务与文件仍在这台):取 list_available_models 的 locations[].agent_device_id,"local" 为这台电脑;省略与 Lead 相同。model / provider_id 要取 list_available_models 按同一位置列出的值。',
+ '- agent_device_id: 可选,Agent 使用哪台电脑的远程供应商;"local" 为 Worker 工作电脑。指定 execution_device_id 时先用同参数的 list_available_models 查 model / provider_id / locations;省略位置用工作电脑默认,否则跟 Lead。',
"- initial_task: 可选, 创建后立即派给 worker 的第一条消息;dispatch_outcome.wakeKind=queued 表示首条任务已成功入队(此时回传 queued_message_id, 被消费前可用 get_worker_queue_status / update_queued_message / cancel_queued_message / merge_queued_messages 管理);dispatch_outcome.kind='session-dispatch' 且 dispatched=false,或 kind='host-send' 且 accepted=false,表示 worker 已创建但首条任务未送达 / 派发失败",
'',
'【硬边界】',
diff --git a/packages/lizi-mcps/src/xdt-helper/list_available_models.ts b/packages/lizi-mcps/src/xdt-helper/list_available_models.ts
index ffc58e1c44..bdee8b83a9 100644
--- a/packages/lizi-mcps/src/xdt-helper/list_available_models.ts
+++ b/packages/lizi-mcps/src/xdt-helper/list_available_models.ts
@@ -74,6 +74,7 @@ export interface ListAvailableModelsDeps {
listAvailableModels: (params: {
agent?: 'claude-code' | 'codex' | 'pi';
callerSessionId?: string;
+ executionDeviceId?: string;
/** 列哪里的模型:省略 = Lead 所在位置;null = 任务所在电脑;string = 那台电脑或分享。 */
agentDeviceId?: string | null;
}) => Promise<ControlResult<{
@@ -98,7 +99,8 @@ const DESCRIPTION = [
'',
'参数:',
'- agent: 可选, codex / claude-code / pi; 不传返三者',
- '- agent_device_id: 可选, 列哪里的模型(Worker 的 Agent 可在别的电脑或分享来的供应商上运行): 取返回的 locations[].agent_device_id, "local" 为这台电脑; 不传列 Lead 所在位置',
+ '- execution_device_id: 可选, 查询该 Worker 工作电脑可用的模型与来源,取 execution_devices 的 device_id。',
+ '- agent_device_id: 可选, 模型所在位置: locations[].agent_device_id 或 "local"。指定 execution_device_id 时相对工作电脑,否则不传跟 Lead。',
'',
'返回值:',
'- agent_device_id: 本次列出的位置; locations: 其他可选位置 [{agent_device_id, name}]。create_worker 传同一个 agent_device_id 并用这里列出的 model / provider_id',
@@ -136,13 +138,16 @@ export function registerListAvailableModelsTool(
.min(1)
.max(128)
.optional()
- .describe('可选, 列哪里的模型: locations[].agent_device_id 或 "local"(这台电脑); 不传列 Lead 所在位置'),
+ .describe('可选, 模型位置: locations[].agent_device_id 或 "local";指定工作电脑时相对它,否则不传跟 Lead'),
+ execution_device_id: z.string().trim().min(1).max(128).optional()
+ .describe('可选,Worker 的工作电脑;查询它可用的模型与远程供应商'),
},
- handler: async ({ agent, agent_device_id }) => {
+ handler: async ({ agent, agent_device_id, execution_device_id }) => {
const callerSessionId = deps.getSessionContext?.().sessionId;
const result = await deps.listAvailableModels({
agent,
...(callerSessionId ? { callerSessionId } : {}),
+ ...(execution_device_id !== undefined ? { executionDeviceId: execution_device_id } : {}),
...toHostAgentDeviceId(agent_device_id),
});
if (!result.ok) {
@@ -151,7 +156,7 @@ export function registerListAvailableModelsTool(
}
// 那台电脑 / 分享不可用时保留原因,Lead 才能如实告诉用户。
return errorPayload(
- result.errorCode.startsWith('REMOTE_AGENT_') ? result.errorCode : 'INTERNAL',
+ result.errorCode.startsWith('REMOTE_AGENT_') || result.errorCode === 'UNSUPPORTED_CAPABILITY' ? result.errorCode : 'INTERNAL',
result.message,
);
}