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): 支持协同会话切换 Agent (#6051)

DavidShenXD91fc8b11e958
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index cbad5e6e7c..530e9ecf2d 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -1323,7 +1323,10 @@ describe('session runtime control wiring', () => {
expect(setModel).toContain('finalPressureContextTokens = contextTokens');
expect(setModel).toContain('runtimeRouteChanged || piConfigurationRefresh || confirmedContextWindow !== undefined');
expect(setModel).toContain('targetContextWindow = finalPiWindow');
- expect(setModel).toContain("if (!isDeviceLinkInvoke() && runtimeAgentKind === 'pi') {");
+ expect(setModel).toContain('orcaRemoteLead: sessions.orcaRemoteLead');
+ expect(setModel).toMatch(
+ /if \(!isDeviceLinkInvoke\(\) && runtimeAgentKind === 'pi' &&\s*!runtimeStatus\.orcaRole && !parseOrcaRemoteLead\(runtimeStatus\.orcaRemoteLead\)\) \{\s*targetContextWindow = confirmedContextWindow \?\? targetContextWindow;/,
+ );
expect(setModel).toContain('planUserRuntimeModelSwitch({');
expect(setModel).not.toContain(
"runtimeAgentKind !== 'pi' || isDeviceLinkInvoke() || !!runtimeStatus.remoteHostId",
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index 4591cfc3a7..d085060698 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -14,6 +14,7 @@ import {
import { CODEX_RESUME_NOT_READY_WIRE_MESSAGE } from '@cindy/maker-shared/agent-input-projection';
import { formatQuotesForSend, stripChatQuoteMarkerLines } from '@cindy/maker-shared/chat-quotes';
import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue';
+import { parseOrcaRemoteLead } from '../../../shared/orcaRemoteWorker';
import { describe, expect, it, vi } from 'vitest';
import { AUTO_REVIEW_DELEGATED_CONTINUATION } from '../autoReviewUserIntent.js';
import {
@@ -29,12 +30,22 @@ import {
import type { MakerSessionCreateOpts } from '../sessionRequest';
import { CredentialModeSwitchBusyError } from '../../maker-host/codex-credential-switch';
import path from 'node:path';
+import os from 'node:os';
+import { readFileSync } from 'node:fs';
+import ts from 'typescript';
import { createWorkingDirectoryRecovery } from '../workingDirectoryRecovery';
import { createPreflightHarness, filesystemError } from './helpers/workingDirectoryPreflightHarness';
import { buildCindyMakeTaskNote } from '../../cindy-make/taskNote';
import { getResolvedMainLocale } from '../../i18n';
import { buildMobileClientPromptNote } from '../mobileClientPromptNote';
import { buildUiLanguageErrorNote } from '../uiLanguageErrorNote';
+import {
+ applyPendingAgentSwitchIfIdle,
+ createPendingAgentSwitchRegistry,
+ performSessionAgentSwitch,
+ type AgentSwitchSessionRow,
+ type MakerSessionAgentSwitchHandlerDeps,
+} from '../sessionAgentSwitchHandler';
function uiLanguageNote(): string {
return buildUiLanguageErrorNote(getResolvedMainLocale());
@@ -3333,6 +3344,148 @@ describe('session-agent-switch handoff injection', () => {
expect(bootstrapSession).not.toHaveBeenCalled();
});
+ const remoteLead = JSON.stringify({ leadDeviceId: 'lead-device', leadSessionId: 'lead-1', workerLabel: 'developer' });
+ const pendingGuardCases = [
+ { name: 'lead', orcaRole: 'lead', orcaRemoteLead: null, blocks: true },
+ { name: 'worker', orcaRole: 'worker', orcaRemoteLead: null, blocks: true },
+ { name: 'execution-device worker', orcaRole: null, orcaRemoteLead: remoteLead, blocks: true },
+ { name: 'released execution-device worker', orcaRole: null, orcaRemoteLead: JSON.stringify({ ...JSON.parse(remoteLead), releasedAt: 1 }), blocks: true },
+ { name: 'ordinary task with Orca input label', orcaRole: null, orcaRemoteLead: null, blocks: false },
+ { name: 'invalid remote binding', orcaRole: null, orcaRemoteLead: '{}', blocks: false },
+ ].flatMap((identity) => [true, false].flatMap((hasLive) =>
+ (['claude-code', 'codex', 'pi'] as const).map((targetAgentKind) => ({ ...identity, hasLive, targetAgentKind })),
+ ));
+ it.each(pendingGuardCases)(
+ 'queue/resume retained switch guard: $name live=$hasLive target=$targetAgentKind',
+ async ({ orcaRole, orcaRemoteLead, blocks, hasLive, targetAgentKind }) => {
+ const register = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');
+ const start = register.indexOf(' applyPendingAgentSwitch: async (sessionId, options) => {');
+ expect(start).toBeGreaterThan(0);
+ const adapter = register.slice(start, register.indexOf(' prepareUnhealthySession:', start));
+ const pending = new Map([['session-1', { targetAgentKind }]]);
+ const beforeSend = vi.fn(async () => undefined);
+ const bindings = {
+ // UI-origin cross-engine preparation can return without clearing the intent.
+ applyPendingAgentSwitchIfIdle: vi.fn(async () => undefined),
+ agentSwitchDeps: {}, agentSwitchPending: pending,
+ getSessionRowSnapshotStrict: vi.fn(async () => ({ orcaRole, orcaRemoteLead })),
+ parseOrcaRemoteLead,
+ throwIpcError: (code: string, message: string) => { throw Object.assign(new Error(message), { code }); },
+ providerGroupService: { beforeSend }, agentInputCoordinatorHolder: null,
+ log: { warn: vi.fn() },
+ };
+ const compiled = ts.transpileModule(`return ({${adapter}}).applyPendingAgentSwitch;`,
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ const applyPendingAgentSwitch = new Function(...Object.keys(bindings), compiled)(...Object.values(bindings));
+ const { deps, session } = createDeps({ applyPendingAgentSwitch });
+ if (!hasLive) vi.mocked(deps.getSession).mockReturnValue(undefined);
+ const transaction = createMakerSendTransaction(deps);
+ const send = () => transaction.sendToAgentAccepted('session-1', { type: 'user', content: 'Queued Orca input' },
+ { agentKind: 'codex', workingDir: 'C:/repo' }, {
+ origin: { kind: 'orca', senderLabel: 'Lead', displayText: 'Queued Orca input' },
+ persistUserMessage: { clientId: 'queued-orca-1', content: 'Queued Orca input' },
+ });
+ if (!blocks) {
+ await send();
+ expect(pending.has('session-1')).toBe(true);
+ expect(deps.createDbMessage).toHaveBeenCalledTimes(1);
+ return;
+ }
+ await expect(send()).rejects.toThrow('Agent switch is still pending');
+ expect(pending.has('session-1')).toBe(true);
+ expect(deps.getSession).not.toHaveBeenCalled();
+ expect(deps.bootstrapSession).not.toHaveBeenCalled();
+ expect(deps.createDbMessage).not.toHaveBeenCalled();
+ expect(session.send).not.toHaveBeenCalled();
+ expect(beforeSend).not.toHaveBeenCalled();
+ // Once recovery finishes, the very same queue/resume transaction can send.
+ bindings.applyPendingAgentSwitchIfIdle.mockImplementation(async () => { pending.clear(); });
+ await send();
+ expect(deps.createDbMessage).toHaveBeenCalledTimes(1);
+ expect(bindings.getSessionRowSnapshotStrict).toHaveBeenCalledTimes(1);
+ },
+ );
+
+ const orcaAgentKinds = ['claude-code', 'codex', 'pi'] as const;
+ const orcaSwitchCases = (['lead', 'worker'] as const).flatMap((role) =>
+ orcaAgentKinds.flatMap((from) => orcaAgentKinds.filter((to) => to !== from).flatMap((to) =>
+ [true, false].map((hasLive) => ({ role, from, to, hasLive, name: `${role}: ${from} → ${to}, live=${hasLive}` })),
+ )),
+ );
+ it.each(orcaSwitchCases)('Orca queued/cold-resume $name applies the real switch before sending with role and history', async ({ role, from, to, hasLive }) => {
+ const pendingSwitches = createPendingAgentSwitchRegistry();
+ const previous = createSession({ agentKind: from });
+ let current: MakerSendTransactionSession | undefined = hasLive ? previous : undefined;
+ let row: AgentSwitchSessionRow = {
+ id: 'session-1', agentKind: from === 'claude-code' ? 'cc' : from, model: 'source-model',
+ providerId: 'source-provider', status: 'active', remoteHostId: null,
+ orcaRole: role, sdkSessionId: 'source-native-session',
+ };
+ let handoff: string | null = null;
+ const switchDeps: MakerSessionAgentSwitchHandlerDeps = {
+ pendingSwitches,
+ getSessionRow: async () => ({ ...row }),
+ getLiveSession: () => current,
+ closeSession: vi.fn(async () => { current = undefined; }),
+ listMessagesForHandoff: async () => [{ role: 'user', content: 'Existing collaboration progress', createdAt: 1 }],
+ applyAgentSwitchToDb: vi.fn(async (_id, patch) => {
+ row = { ...row, ...patch, providerId: patch.providerId ?? null, sdkSessionId: patch.sdkSessionId ?? null };
+ }),
+ setSessionProvider: vi.fn(),
+ insertBoundaryMessage: vi.fn(async () => 'switch-boundary'),
+ applyResumeFallbackAtomically: vi.fn(async () => { throw new Error('fresh target has no parked session to recover'); }),
+ setPendingHandoff: (_id, text) => { handoff = text; },
+ bootstrapSwitchedSession: vi.fn(async () => { throw new Error('queue must bootstrap through the send transaction'); }),
+ withCloseSuppressed: (_id, fn) => fn(),
+ log: { info: vi.fn(), warn: vi.fn() },
+ };
+ await performSessionAgentSwitch(switchDeps, {
+ sessionId: 'session-1', targetAgentKind: to, model: 'target-model', providerId: 'target-provider',
+ });
+ expect(switchDeps.closeSession).not.toHaveBeenCalled();
+ const { deps } = createDeps({
+ getSession: () => current,
+ applyPendingAgentSwitch: (id, options) => applyPendingAgentSwitchIfIdle(switchDeps, id, options),
+ reconcileCreateOptsWithDb: vi.fn(async (_id, opts) => {
+ opts.agentKind = row.agentKind === 'cc' ? 'claude-code' : row.agentKind as AgentKind;
+ opts.model = row.model ?? undefined;
+ opts.providerId = row.providerId;
+ opts.resumeSessionId = row.sdkSessionId ?? undefined;
+ }),
+ synthesizeOrcaVendorOptionsFromDb: vi.fn(async (_id, opts) => { opts.orcaRole = role; return true; }),
+ bootstrapSession: vi.fn(async (opts) => {
+ current = createSession({ agentKind: opts.agentKind as AgentKind, workDir: opts.workingDir });
+ return { session: current, didInjectOrcaInstructions: true, didInjectProjectContext: false };
+ }),
+ peekPendingHandoff: async () => handoff,
+ consumePendingHandoff: vi.fn(() => { handoff = null; }),
+ });
+ const transaction = createMakerSendTransaction(deps);
+ const origin = { kind: 'orca', senderLabel: role === 'worker' ? 'Lead' : 'Worker', displayText: 'Continue collaboration' } as const;
+ const result = await transaction.sendToAgentAccepted('session-1', { type: 'user', content: origin.displayText },
+ { agentKind: from, workingDir: path.join(os.tmpdir(), 'orca-switch-fixture'), resumeSessionId: 'source-native-session' }, {
+ origin, persistUserMessage: { clientId: 'orca-queued-input', content: origin.displayText },
+ });
+ expect(result).toMatchObject({ accepted: true });
+ expect(pendingSwitches.get('session-1')).toBeUndefined();
+ expect(previous.send).not.toHaveBeenCalled();
+ expect(current?.agentKind).toBe(to);
+ expect(row.orcaRole).toBe(role);
+ expect(deps.bootstrapSession).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({
+ agentKind: to, model: 'target-model', providerId: 'target-provider', resumeSessionId: undefined, orcaRole: role,
+ }));
+ expect(deps.markOrcaRoleIfNeeded).toHaveBeenCalledWith('session-1', role);
+ const sent = vi.mocked(current!.send).mock.calls[0];
+ expect((sent[0] as UserMessage).content).toContain('Existing collaboration progress');
+ expect((sent[0] as UserMessage).content).toContain(origin.displayText);
+ expect(sent[1]?.origin).toEqual(origin);
+ expect(deps.createDbMessage).toHaveBeenCalledWith('session-1', expect.objectContaining({
+ content: origin.displayText, agentMeta: expect.objectContaining({ origin }),
+ }), undefined);
+ expect(deps.consumePendingHandoff).toHaveBeenCalledExactlyOnceWith('session-1');
+ expect(handoff).toBeNull();
+ });
+
it('排队 drain 端到端:切换在派发时刻落实(关旧引擎)→ createOpts 按 DB 对齐新引擎 → 交接注入新引擎首条 + scheduler origin 透传', async () => {
// 复刻 coordinator drain 一条排队 scheduler 心跳时对 sendToAgentAccepted 的调用:
// 入队的是裸 prompt(不含交接)+ 旧引擎(claude-code)createOpts。drain 时会话已
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts
index 2d11195a87..8fd565efad 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaInterAgentDispatcher.test.ts
@@ -22,17 +22,18 @@ vi.mock('../../logger.js', () => ({
}));
interface TestSessionMeta {
- agentKind: 'codex';
+ agentKind: 'claude-code' | 'codex' | 'pi';
workDir: string;
model: string;
}
function createLiveSession(
send: (message: UserMessage, opts?: SessionSendOptions) => Promise<SessionSendResult>,
+ agentKind: TestSessionMeta['agentKind'] = 'codex',
) {
return {
id: 'target-session',
- agentKind: 'codex' as const,
+ agentKind,
isTurnRunning: vi.fn(() => false),
send: vi.fn(send),
};
@@ -563,9 +564,13 @@ describe('Orca lead/worker dispatcher', () => {
expect(rollback).toHaveBeenCalledTimes(1);
});
- it('leaves lazy-resume turn capture to sendToSessionInternal', async () => {
+ it.each(['claude-code', 'codex', 'pi'] as const)('leaves lazy-resume turn capture to sendToSessionInternal and reports its %s Agent', async (agentKind) => {
const h = createHarness({
getLiveSession: vi.fn(() => null),
+ sendToSessionInternal: vi.fn(async () => ({
+ ok: true, targetSessionId: 'target-session', agentKind, wakeKind: 'resumed',
+ targetTitle: 'Resumed target', targetLastUserSendAt: null,
+ } as const)),
});
const result = await h.dispatcher.dispatchOrEnqueueOrcaInterAgentMessage({
@@ -576,7 +581,7 @@ describe('Orca lead/worker dispatcher', () => {
meta: { source: 'orca', context: 'resume-test' },
});
- expect(result).toMatchObject({ ok: true, mode: 'dispatched' });
+ expect(result).toMatchObject({ ok: true, mode: 'dispatched', agentKind });
expect(h.deps.sendToSessionInternal).toHaveBeenCalledWith(expect.objectContaining({
targetSessionId: 'target-session',
clientId: 'client-1',
@@ -1019,3 +1024,121 @@ it.each(['Do not publish', ''])('ordinary live continuation retains the last acc
const result=await h.dispatcher.dispatchOrEnqueueOrcaInterAgentMessage({targetSessionId:'target-session',rawContent:'Publish now',source:'lead',senderLabel:'Lead',meta:{source:'orca',context:'ordinary-live'}});
expect(result.ok).toBe(true);
});
+
+const switchAgentKinds = ['claude-code', 'codex', 'pi'] as const;
+const directSwitchCases = (['lead', 'worker'] as const).flatMap((source) =>
+ switchAgentKinds.flatMap((from) => switchAgentKinds.filter((to) => to !== from).map((to) => ({
+ source, from, to, name: `${source} delivery: ${from} → ${to}`,
+ }))),
+);
+it('passes the dispatcher Agent receipt through the host worker adapter', async () => {
+ const register = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');
+ const start = register.indexOf(' dispatchWorkerMessage: async ({');
+ const end = register.indexOf(' reserveWorkerMessage:', start);
+ expect(start).toBeGreaterThan(0);
+ expect(end).toBeGreaterThan(start);
+ const dispatched = vi.fn(async () => ({
+ ok: true, mode: 'dispatched', agentKind: 'pi', clientId: 'worker-input',
+ dispatchOutcome: { kind: 'session-dispatch', source: 'orca', dispatched: true },
+ }));
+ const compiled = ts.transpileModule(`return ({${register.slice(start, end)}}).dispatchWorkerMessage;`,
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ const dispatchWorkerMessage = new Function('dispatchOrEnqueueOrcaInterAgentMessage', compiled)(dispatched);
+ await expect(dispatchWorkerMessage({
+ targetSessionId: 'worker-session', message: 'Continue', workerId: 'worker-1',
+ dispatchMeta: { source: 'orca', context: 'switched-agent-receipt' },
+ })).resolves.toMatchObject({ ok: true, agentKind: 'pi' });
+});
+
+it.each(directSwitchCases)('applies a deferred Agent switch before direct $name', async ({ source, from, to }) => {
+ const switched = createLiveSession(async (_message, opts) => {
+ await opts?.onAccepted?.();
+ return { accepted: true };
+ }, to);
+ let current: ReturnType<typeof createLiveSession>;
+ let handoff: string | null = null;
+ const consume = vi.fn(() => { handoff = null; });
+ const h = createHarness({
+ applyPendingAgentSwitch: vi.fn(async () => {
+ h.order.push('apply-switch');
+ if (current !== switched) handoff = 'History from the previous engine';
+ current = switched;
+ }),
+ getLiveSession: () => current,
+ hasPendingAgentSwitch: () => false,
+ peekPendingHandoff: async () => handoff,
+ consumePendingHandoff: consume,
+ });
+ const previous = createLiveSession(async () => { throw new Error('must not send to the previous Agent'); }, from);
+ current = previous;
+
+ const message = {
+ targetSessionId: 'target-session',
+ rawContent: 'Continue on the new engine',
+ source,
+ senderLabel: 'Lead',
+ meta: { source: 'orca', context: 'agent-switch-boundary' },
+ };
+ const result = await h.dispatcher.dispatchOrEnqueueOrcaInterAgentMessage(message);
+
+ expect(result).toMatchObject({ ok: true, mode: 'dispatched', agentKind: to });
+ expect(h.deps.applyPendingAgentSwitch).toHaveBeenCalledWith('target-session');
+ expect(previous.send).not.toHaveBeenCalled();
+ expect(current.agentKind).toBe(to);
+ const content = switched.send.mock.calls[0]?.[0].content;
+ expect(content).toContain('History from the previous engine');
+ expect(content).toContain(source === 'lead' ? '[From Orca Lead]' : '[From Orca Worker]');
+ expect(content).toContain(message.rawContent);
+ expect(consume).toHaveBeenCalledExactlyOnceWith('target-session');
+ expect(h.deps.createDbMessage).toHaveBeenCalledWith('target-session', expect.objectContaining({
+ content: JSON.stringify({ orcaSource: source, content: message.rawContent }),
+ }));
+ await h.dispatcher.dispatchOrEnqueueOrcaInterAgentMessage(message);
+ expect(switched.send.mock.calls[1]?.[0].content).not.toContain('History from the previous engine');
+ expect(consume).toHaveBeenCalledTimes(1);
+});
+
+it.each([true, false])('blocks delivery and resume when a failed switch retains its intent (live=%s)', async (hasLive) => {
+ const accepted = vi.fn();
+ const h = createHarness({
+ applyPendingAgentSwitch: vi.fn(async () => undefined),
+ hasPendingAgentSwitch: () => true,
+ });
+ if (!hasLive) vi.mocked(h.deps.getLiveSession).mockReturnValue(undefined);
+ const result = await h.dispatcher.dispatchOrEnqueueOrcaInterAgentMessage({
+ targetSessionId: 'target-session', rawContent: 'Retry after recovery', source: 'lead', senderLabel: 'Lead',
+ meta: { source: 'orca', context: 'pending-switch' }, onAccepted: accepted,
+ });
+ expect(result).toMatchObject({ ok: false, dispatchOutcome: { code: 'SEND_FAILED' } });
+ expect(h.deps.hasPendingAgentSwitch?.('target-session')).toBe(true);
+ expect(h.liveSession.send).not.toHaveBeenCalled();
+ expect(h.deps.sendToSessionInternal).not.toHaveBeenCalled();
+ expect(h.deps.createDbMessage).not.toHaveBeenCalled();
+ expect(accepted).not.toHaveBeenCalled();
+});
+
+it.each(['rejected', 'throw', 'running'] as const)('keeps history for retry after %s direct delivery', async (failure) => {
+ const consume = vi.fn();
+ const h = createHarness({
+ peekPendingHandoff: async () => 'Pending history',
+ consumePendingHandoff: consume,
+ });
+ h.liveSession.send.mockImplementation(async () => {
+ if (failure === 'rejected') return { accepted: false, reason: 'cancelled-before-dispatch' };
+ if (failure === 'running') throw Object.assign(new Error('already running'), { code: 'SESSION_RUNNING' });
+ throw new Error('transport failed');
+ });
+ const result = await h.dispatcher.dispatchOrEnqueueOrcaInterAgentMessage({
+ targetSessionId: 'target-session', rawContent: 'Continue', source: 'lead', senderLabel: 'Lead',
+ meta: { source: 'orca', context: 'handoff-retry' },
+ });
+ expect(result.ok).toBe(failure === 'running');
+ expect(h.liveSession.send.mock.calls[0]?.[0].content).toContain('Pending history');
+ expect(consume).not.toHaveBeenCalled();
+ expect(h.deps.createDbMessage).not.toHaveBeenCalled();
+ if (failure === 'running') {
+ expect(result).toMatchObject({ mode: 'queued' });
+ expect(firstQueuedItem(h.queuedItems).text).not.toContain('Pending history');
+ expect(firstQueuedItem(h.queuedItems).persistedContent).not.toContain('Pending history');
+ }
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts
new file mode 100644
index 0000000000..2a63c84f91
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaModelSelectionIntent.test.ts
@@ -0,0 +1,157 @@
+import { readFileSync } from 'node:fs';
+import ts from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+import { applyPendingAgentSwitchIfIdle, createPendingAgentSwitchRegistry, type MakerSessionAgentSwitchHandlerDeps } from '../sessionAgentSwitchHandler';
+import { parseOrcaRemoteLead } from '../../../shared/orcaRemoteWorker';
+
+// Execute the actual picker admission branches (local and agent-device), with
+// everything after admission represented by applyLive. No Electron bootstrap.
+const source = ts.createSourceFile('register.ts', readFileSync(new URL('../register.ts', import.meta.url), 'utf8'),
+ ts.ScriptTarget.Latest, true);
+const branches: string[] = [];
+const confirmationChecks: string[] = [];
+let applySelectionAdapter = '';
+let piWindowOverride = '';
+function visit(node: ts.Node) {
+ if (ts.isPropertyAssignment(node)) {
+ if (node.name.getText(source) === 'confirmedTargetPressure' && node.initializer.getText(source).includes('runtimeStatus.orcaRole')) {
+ confirmationChecks.push(node.initializer.getText(source));
+ }
+ if (node.name.getText(source) === 'selectSameAgentModel') applySelectionAdapter = node.initializer.getText(source);
+ }
+ if (ts.isIfStatement(node) && node.expression.getText(source).includes('!internalOptions.applyingUserSelectionOnSend')
+ && node.thenStatement.getText(source).includes('pendingUntilSend: true')) {
+ branches.push(node.getText(source));
+ }
+ if (ts.isIfStatement(node) && node.thenStatement.getText(source).includes('targetContextWindow = confirmedContextWindow ?? targetContextWindow')) {
+ piWindowOverride = node.getText(source);
+ }
+ ts.forEachChild(node, visit);
+}
+visit(source);
+const remoteLead = { leadDeviceId: 'lead-device', leadSessionId: 'lead-session', workerLabel: 'worker' };
+const orcaIdentities = [
+ { orcaRole: 'lead' },
+ { orcaRole: 'worker' },
+ { orcaRole: null, orcaRemoteLead: JSON.stringify(remoteLead) },
+];
+
+describe('Orca model-only picker intent admission', () => {
+ it.each(['lead', 'worker'] as const)('stages %s model and axes on both execution locations until send', async orcaRole => {
+ expect(branches).toHaveLength(2);
+ for (const branch of branches) {
+ const onOtherDevice = !branch.includes('!runtimeStatus.remoteHostId');
+ const pending = new Map();
+ const applyLive = vi.fn(() => ({ deferred: false, superseded: false }));
+ const changed = vi.fn();
+ const runtimeStatus = { orcaRole, remoteHostId: null, agentDeviceId: onOtherDevice ? 'other' : null,
+ agentKind: 'codex', model: 'old', providerId: 'old-provider', effort: 'low', fastMode: false };
+ const internalOptions = { source: 'user', applyingUserSelectionOnSend: false };
+ const bindings = {
+ internalOptions, runtimeStatus, sessionId: 's1', model: 'new',
+ targetProviderId: 'provider', effectiveProviderId: 'provider', currentProviderId: 'old-provider',
+ agentKind: 'codex', dbToMakerAgentKind: (kind: string) => kind,
+ targetEffort: 'high', targetFastMode: true, targetContextWindow: undefined,
+ confirmedContextWindow: 200000 as number | undefined,
+ atomicSelection: { effort: 'high', fastMode: true },
+ assertRuntimeOwnerCurrent: vi.fn(), assertSharedTaskCurrent: { admit: vi.fn() },
+ assertAgentDeviceRouteUsable: vi.fn(), supersededByOwnerBoundary: () => false,
+ clearPendingCredentialSwitchForSession: vi.fn(), agentSwitchPending: pending,
+ agentSwitchDeps: { onPendingSwitchChanged: changed },
+ projectPendingAgentSwitchIntent: (intent: unknown) => intent,
+ wakeSessionInputAfterCredentialSwitch: vi.fn(),
+ isDeviceLinkInvoke: () => true, markRemoteSettingPersistedInsideHandler: vi.fn(), applyLive,
+ };
+ const compiled = ts.transpileModule(`return async () => { ${branch}; return applyLive(); };`,
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ const run = () => new Function(...Object.keys(bindings), compiled)(...Object.values(bindings))();
+ expect(await run()).toMatchObject({ deferred: true, pendingUntilSend: true });
+ expect(pending.get('s1')).toMatchObject({ sameAgentSelection: true, targetAgentKind: 'codex',
+ model: 'new', providerId: 'provider', effort: 'high', fastMode: true });
+ expect(changed).toHaveBeenCalledTimes(1);
+ expect(applyLive).not.toHaveBeenCalled();
+ expect(runtimeStatus.model).toBe('old');
+ if (!onOtherDevice) {
+ expect(pending.get('s1').confirmedContextWindow).toBe(200000);
+ // Axis-only restaging retains this route's receipt; a different route
+ // must not inherit acknowledgement from the previous selection.
+ bindings.confirmedContextWindow = undefined;
+ await run();
+ expect(pending.get('s1').confirmedContextWindow).toBe(200000);
+ bindings.model = 'another-model';
+ await run();
+ expect(pending.get('s1')).not.toHaveProperty('confirmedContextWindow');
+ }
+ if (onOtherDevice) expect(bindings.assertAgentDeviceRouteUsable).toHaveBeenCalledWith('other', 'codex', 'new', 'provider');
+ // Use the real send boundary: a running turn keeps the intent, the next
+ // idle send applies it once instead of staging it again.
+ let running = true;
+ const deps = {
+ pendingSwitches: { get: (id: string) => pending.get(id), clear: (id: string) => pending.delete(id) },
+ getLiveSession: () => ({ isTurnRunning: () => running }),
+ selectSameAgentModel: async (_id: string, _intent: unknown, applyNow: boolean) => {
+ internalOptions.applyingUserSelectionOnSend = applyNow;
+ return run();
+ },
+ log: { info: vi.fn(), warn: vi.fn() },
+ } as unknown as MakerSessionAgentSwitchHandlerDeps;
+ await applyPendingAgentSwitchIfIdle(deps, 's1');
+ expect(applyLive).not.toHaveBeenCalled();
+ expect(pending.has('s1')).toBe(true);
+ running = false;
+ await applyPendingAgentSwitchIfIdle(deps, 's1');
+ expect(pending.has('s1')).toBe(false);
+ await applyPendingAgentSwitchIfIdle(deps, 's1');
+ expect(applyLive).toHaveBeenCalledTimes(1);
+ expect(changed).toHaveBeenCalledTimes(onOtherDevice ? 1 : 3);
+ }
+ });
+
+ it.each([undefined, 400000, 200000])('authorizes Orca local/final Pi rebuild only for the checked window: %s', confirmed => {
+ expect(confirmationChecks).toHaveLength(2);
+ for (const expression of confirmationChecks) {
+ const check = new Function('runtimeStatus', 'internalOptions', 'isDeviceLinkInvoke',
+ 'confirmedContextWindow', 'targetContextWindow', 'finalPiWindow', 'parseOrcaRemoteLead', `return ${expression};`);
+ for (const identity of orcaIdentities) {
+ for (const remote of [false, true]) {
+ expect(check(identity, { source: 'user', applyingUserSelectionOnSend: true },
+ () => remote, confirmed, 200000, 200000, parseOrcaRemoteLead)).toBe(!remote && confirmed === 200000);
+ }
+ }
+ expect(check({ orcaRole: null }, { source: 'user', applyingUserSelectionOnSend: true },
+ () => false, confirmed, 200000, 200000, parseOrcaRemoteLead)).toBe(true);
+ }
+ });
+
+ it('keeps the verified Pi window for execution-device Workers instead of trusting an old confirmation', () => {
+ expect(piWindowOverride).not.toBe('');
+ const check = new Function('runtimeStatus', 'isDeviceLinkInvoke', 'runtimeAgentKind',
+ 'confirmedContextWindow', 'targetContextWindow', 'parseOrcaRemoteLead',
+ `${piWindowOverride}; return targetContextWindow;`);
+ for (const identity of orcaIdentities) {
+ expect(check(identity, () => false, 'pi', 400000, 200000, parseOrcaRemoteLead)).toBe(200000);
+ expect(check(identity, () => false, 'pi', 400000, undefined, parseOrcaRemoteLead)).toBeUndefined();
+ }
+ expect(check({ orcaRole: null }, () => false, 'pi', 400000, 200000, parseOrcaRemoteLead)).toBe(400000);
+ });
+
+ it('retains intent when the send-time window still needs confirmation and retries with the new receipt', async () => {
+ const pending = createPendingAgentSwitchRegistry();
+ const apply = vi.fn(async (_id: string, _model: string, _provider: unknown, selection: { confirmedContextWindow?: number }) =>
+ selection.confirmedContextWindow === 200000 ? { deferred: false } :
+ { deferred: false, contextWindowConfirmationRequired: 200000 });
+ const bindings = { applySessionRuntimeSelection: apply,
+ throwIpcError: (_code: string, message: string) => { throw new Error(message); } };
+ const code = ts.transpileModule(`return ${applySelectionAdapter};`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ const selectSameAgentModel = new Function(...Object.keys(bindings), code)(...Object.values(bindings));
+ pending.set('s1', { sameAgentSelection: true, targetAgentKind: 'codex', model: 'small', providerId: 'provider' });
+ const deps = { pendingSwitches: pending, getLiveSession: () => undefined, selectSameAgentModel,
+ log: { info: vi.fn(), warn: vi.fn() } } as unknown as MakerSessionAgentSwitchHandlerDeps;
+ await expect(applyPendingAgentSwitchIfIdle(deps, 's1')).rejects.toThrow('select the model again');
+ expect(pending.get('s1')).toBeDefined();
+ pending.set('s1', { ...pending.get('s1')!, confirmedContextWindow: 200000 });
+ await applyPendingAgentSwitchIfIdle(deps, 's1');
+ expect(pending.get('s1')).toBeUndefined();
+ expect(apply.mock.calls[1][3]).toMatchObject({ confirmedContextWindow: 200000 });
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteModelWindowSelection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteModelWindowSelection.test.ts
new file mode 100644
index 0000000000..04db0e66f3
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteModelWindowSelection.test.ts
@@ -0,0 +1,185 @@
+import { readFileSync } from 'node:fs';
+import ts from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+import type { ProviderView } from '@cindy/model-providers';
+import { resolveVerifiedContextWindow } from '../../../shared/sessionContextWindow';
+import { createContextOverflowRollover } from '../contextOverflowRollover';
+import { applyPendingAgentSwitchIfIdle, createPendingAgentSwitchRegistry, projectPendingAgentSwitchIntent,
+ type MakerSessionAgentSwitchHandlerDeps, type PendingAgentSwitchIntent } from '../sessionAgentSwitchHandler';
+
+// Run the production remote-selection adapter, send boundary and window rollover
+// together. Only device I/O, native processes and persistent writes are replaced.
+const source = ts.createSourceFile('register.ts', readFileSync(new URL('../register.ts', import.meta.url), 'utf8'),
+ ts.ScriptTarget.Latest, true);
+let remoteSelection = '';
+let selectionAdapter = '';
+function visit(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'applyAgentDeviceRuntimeSelection') {
+ remoteSelection = node.initializer!.getText(source);
+ }
+ if (ts.isPropertyAssignment(node) && node.name.getText(source) === 'selectSameAgentModel') {
+ selectionAdapter = node.initializer.getText(source);
+ }
+ ts.forEachChild(node, visit);
+}
+visit(source);
+const compile = (expression: string, bindings: Record<string, unknown>) => {
+ const js = ts.transpileModule(`return ${expression};`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ return new Function(...Object.keys(bindings), js)(...Object.values(bindings));
+};
+
+function setup(agent: 'cc' | 'codex' | 'pi' = 'codex', role: string | null = 'worker', cold = false) {
+ const agentKind = agent === 'cc' ? 'claude-code' : agent;
+ const state = { tokens: 1000, window: 200000, verified: true };
+ const row = { status: 'active', orcaRole: role, agentKind: agent, model: 'old', providerId: 'provider',
+ agentDeviceId: 'executor', effort: 'high', fastMode: false, remoteHostId: null, sdkSessionId: 'native', clearedAt: null };
+ const runtime = { isTurnRunning: () => false, getUsageSnapshot: () => ({ contextTokens: state.tokens, contextWindow: 1000000 }),
+ setModel: vi.fn(), setFastMode: vi.fn(), requiresModelSwitchRebuild: vi.fn(async () => false) };
+ let live: typeof runtime | undefined = cold ? undefined : runtime;
+ const close = vi.fn(async () => { live = undefined; });
+ const rebuild = vi.fn();
+ const pending = createPendingAgentSwitchRegistry();
+ const log = { info: vi.fn(), warn: vi.fn(), debug: vi.fn() };
+ const rollover = createContextOverflowRollover({
+ getSessionRow: async () => ({ ...row, contextTokens: state.tokens, contextWindow: 1000000 }),
+ getLiveSession: () => live, rehydrateColdPiRuntimeForWindowVerification: async () => { live = runtime; },
+ drainPersistQueue: async () => {}, closeSession: close, commitRebuild: rebuild,
+ listMessages: async () => [{ role: 'user', content: 'history', clientId: 'u1', createdAt: 1 }],
+ findLatestRebuildMeta: async () => null, setPendingHandoff: vi.fn(),
+ replayUserMessage: async () => ({ accepted: true }),
+ withCloseSuppressed: async (_id, run) => run(), log,
+ });
+ const readProviders = vi.fn(async (): Promise<ProviderView[]> => [{
+ id: 'provider', routing: { [agentKind]: {} }, models: { [agentKind]: [
+ { id: 'new', contextWindow: state.window, contextWindowVerified: state.verified },
+ ] },
+ } as unknown as ProviderView]);
+ const persist = vi.fn(async () => {});
+ const throwIpcError = (code: string, message: string): never => { throw new Error(`[${code}] ${message}`); };
+ const bindings = {
+ maker: { getSession: () => live, closeSession: close }, agentSwitchPending: pending,
+ hasSessionProvider: () => false, getSessionProvider: () => 'provider', normalizeSessionProviderId: (id: unknown) => id,
+ dbToMakerAgentKind: () => agentKind, isSessionInTurn: () => false,
+ assertAgentDeviceRouteUsable: vi.fn(async () => {}), readUsableAgentDeviceProviders: readProviders,
+ resolveVerifiedContextWindow, contextOverflowRolloverHolder: rollover,
+ agentSwitchDeps: { onPendingSwitchChanged: vi.fn() }, projectPendingAgentSwitchIntent,
+ wakeSessionInputAfterCredentialSwitch: vi.fn(), persistSessionFields: persist,
+ setSessionProvider: vi.fn(), setSessionEffort: vi.fn(), setSessionFastMode: vi.fn(), getSessionEffort: () => 'high',
+ recordUserSessionRuntimeMutation: () => 1, broadcastSessionRuntimeProjection: async () => {},
+ withRehydrateCloseSuppressed: async (_id: string, run: () => unknown) => run(), throwIpcError, log,
+ };
+ const applyRemote = compile(remoteSelection, bindings);
+ const assertRuntimeOwnerCurrent = vi.fn();
+ const selectSameAgentModel = compile(selectionAdapter, { throwIpcError,
+ applySessionRuntimeSelection: (sessionId: string, model: string, providerId: unknown,
+ selection: { effort: string; fastMode: boolean; confirmedContextWindow?: number }, internalOptions: unknown) => applyRemote({
+ sessionId, model, providerId, atomicSelection: selection, internalOptions, runtimeStatus: row,
+ confirmedContextWindow: selection.confirmedContextWindow, assertRuntimeOwnerCurrent,
+ assertSharedTaskCurrent: { admit: vi.fn() }, supersededByOwnerBoundary: () => false,
+ }),
+ });
+ const deps = { pendingSwitches: pending, getLiveSession: () => live, selectSameAgentModel, log } as unknown as MakerSessionAgentSwitchHandlerDeps;
+ const stage = (confirmedContextWindow?: number) => selectSameAgentModel('s1', {
+ sameAgentSelection: true, targetAgentKind: agentKind, model: 'new', providerId: 'provider', effort: 'high', fastMode: false,
+ ...(confirmedContextWindow !== undefined ? { confirmedContextWindow } : {}),
+ } satisfies PendingAgentSwitchIntent, false);
+ return { state, stage, send: () => applyPendingAgentSwitchIfIdle(deps, 's1'),
+ readProviders, pending, runtime, close, rebuild, persist, rollover, assertRuntimeOwnerCurrent };
+}
+
+describe('Orca remote-Agent window protection at send', () => {
+ const cases = (['cc', 'codex', 'pi'] as const).flatMap(agent => ['lead', 'worker'].flatMap(role =>
+ [false, true].map(cold => ({ agent, role, cold }))));
+ it.each(cases)('rechecks pressure for $agent $role cold=$cold and retains an unconfirmed intent', async ({ agent, role, cold }) => {
+ const h = setup(agent, role, cold);
+ await h.stage();
+ expect(h.readProviders).not.toHaveBeenCalled();
+ // A running turn can grow after selection, before the next dispatch.
+ h.state.tokens = 190000;
+ await expect(h.send()).rejects.toThrow('select the model again');
+ expect(h.readProviders).toHaveBeenCalledWith('executor', agent === 'cc' ? 'claude-code' : agent, 'new', 'provider');
+ expect(h.pending.get('s1')).toBeDefined();
+ expect(h.runtime.setModel).not.toHaveBeenCalled();
+ expect(h.close).not.toHaveBeenCalled();
+ expect(h.rebuild).not.toHaveBeenCalled();
+ expect(h.persist).not.toHaveBeenCalled();
+ // Lower pressure allows retry without losing or duplicating the selection.
+ h.state.tokens = 1000;
+ await h.send();
+ expect(h.pending.get('s1')).toBeUndefined();
+ expect(h.persist).toHaveBeenCalledOnce();
+ if (!cold || agent === 'pi') {
+ expect(h.runtime.setModel).toHaveBeenCalledExactlyOnceWith('new', { providerId: 'provider', effort: 'high' });
+ } else {
+ expect(h.runtime.setModel).not.toHaveBeenCalled();
+ }
+ });
+
+ it('does not treat an unverified catalog window or its old acknowledgement as permission to rebuild', async () => {
+ const h = setup();
+ await h.stage(200000);
+ h.state.verified = false;
+ h.state.tokens = 190000;
+ await h.send();
+ expect(h.readProviders).toHaveBeenCalledOnce();
+ expect(h.close).not.toHaveBeenCalled();
+ expect(h.rebuild).not.toHaveBeenCalled();
+ expect(h.runtime.setModel).toHaveBeenCalledOnce();
+ expect(h.pending.get('s1')).toBeUndefined();
+ });
+
+ it('preserves ordinary task selection without adding the Orca send-time catalog read', async () => {
+ const h = setup('codex', null);
+ await h.stage();
+ await h.send();
+ expect(h.readProviders).not.toHaveBeenCalled();
+ expect(h.runtime.setModel).toHaveBeenCalledOnce();
+ expect(h.persist).toHaveBeenCalledOnce();
+ });
+
+ it('does not persist a cold selection if the owner changes during window verification', async () => {
+ const h = setup('codex', 'worker', true);
+ await h.stage();
+ vi.spyOn(h.rollover, 'prepareModelWindowSwitch').mockImplementation(async () => {
+ h.assertRuntimeOwnerCurrent.mockImplementation(() => { throw new Error('owner changed'); });
+ return 'not-needed';
+ });
+ await expect(h.send()).rejects.toThrow('owner changed');
+ expect(h.pending.get('s1')).toBeDefined();
+ expect(h.persist).not.toHaveBeenCalled();
+ });
+
+ it('does not substitute a stale acknowledged window for the fresh execution-device catalog', async () => {
+ const h = setup();
+ await h.stage(1000000);
+ h.state.tokens = 190000;
+ await expect(h.send()).rejects.toThrow('select the model again');
+ expect(h.close).not.toHaveBeenCalled();
+ expect(h.rebuild).not.toHaveBeenCalled();
+ await h.stage(200000);
+ await h.send();
+ expect(h.rebuild).toHaveBeenCalledOnce();
+ expect(h.runtime.setModel).not.toHaveBeenCalled();
+ expect(h.pending.get('s1')).toBeUndefined();
+ });
+
+ it.each(['unknown-context', 'in-flight', 'remote-unsupported'] as const)('keeps the intent and route on %s', async prepared => {
+ const h = setup();
+ vi.spyOn(h.rollover, 'prepareModelWindowSwitch').mockResolvedValue(prepared);
+ await h.stage();
+ await expect(h.send()).rejects.toThrow('could not be verified');
+ expect(h.pending.get('s1')).toBeDefined();
+ expect(h.persist).not.toHaveBeenCalled();
+ expect(h.runtime.setModel).not.toHaveBeenCalled();
+ });
+
+ it('does not mutate the route when the execution computer cannot be rechecked', async () => {
+ const h = setup();
+ await h.stage();
+ h.readProviders.mockRejectedValueOnce(new Error('executor unavailable'));
+ await expect(h.send()).rejects.toThrow('executor unavailable');
+ expect(h.pending.get('s1')).toBeDefined();
+ expect(h.runtime.setModel).not.toHaveBeenCalled();
+ expect(h.persist).not.toHaveBeenCalled();
+ });
+});
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 40ad97e89d..b187dea297 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteWorkerRuntime.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteWorkerRuntime.test.ts
@@ -26,9 +26,11 @@ interface FakeHistoryMessage {
}
interface FakeDevice {
+ agentKind?: string;
offline: boolean;
running: boolean;
receipts: Record<string, string>;
+ acceptedAgents: Record<string, string>;
assistant: { id: string; content: unknown } | null;
terminalError: boolean;
history?: FakeHistoryMessage[];
@@ -43,6 +45,7 @@ function setup(device: Partial<FakeDevice> = {}) {
offline: false,
running: false,
receipts: {},
+ acceptedAgents: {},
assistant: { id: 'msg-0', content: '旧回复' },
terminalError: false,
enqueued: [],
@@ -50,7 +53,7 @@ function setup(device: Partial<FakeDevice> = {}) {
released: 0,
...device,
};
- const invoke = vi.fn(async (_deviceId: string, channel: string, args: unknown[]) => {
+ const invoke = vi.fn(async (_deviceId: string, channel: string, args: unknown[]): Promise<unknown> => {
if (state.offline) throw new Error('[DEVICE_OFFLINE] target offline');
switch (channel) {
case 'maker:list-active':
@@ -62,7 +65,7 @@ function setup(device: Partial<FakeDevice> = {}) {
return {
id: 'remote-1',
status: 'active',
- agentKind: 'cc',
+ agentKind: state.agentKind ?? 'cc',
workingDir: '/Users/demo/Interviews',
model: 'claude-opus-5-5',
effort: 'high',
@@ -99,6 +102,11 @@ function setup(device: Partial<FakeDevice> = {}) {
state.enqueued.push(args[1]);
state.receipts[(args[1] as { clientId: string }).clientId] = 'pending';
return {};
+ case 'local-db:messages:around-client-id': {
+ const clientId = args[1] as string;
+ const agentKind = state.acceptedAgents[clientId];
+ return agentKind ? [{ clientId, role: 'user', agentKind }] : [];
+ }
case 'maker:input:get-projection': {
const ids = (args[1] as { deliveryClientIds: string[] }).deliveryClientIds;
return {
@@ -146,7 +154,7 @@ describe('orca remote worker runtime', () => {
const { runtime, state } = setup();
await expect(
runtime.dispatch({ proxySessionId: 'proxy-1', rawContent: '转写这段访谈', clientId: 'c-1' }),
- ).resolves.toEqual({ ok: true, mode: 'dispatched' });
+ ).resolves.toEqual({ ok: true, mode: 'queued', agentKind: 'claude-code' });
expect(state.enqueued).toHaveLength(1);
expect(state.enqueued[0]).toMatchObject({
clientId: 'c-1',
@@ -393,16 +401,67 @@ describe('orca remote worker runtime', () => {
expect(runtime.hasPendingReport('proxy-1')).toBe(false);
});
- it('treats a lost enqueue reply as delivered when the device already holds the message', async () => {
+ it.each(['cc', 'codex', 'pi'])('does not claim Agent %s accepted when the enqueue reply is lost and delivery is pending', async (agentKind) => {
const lost = Object.assign(new Error('[INVOKE_TIMEOUT] no reply'), { inFlight: true });
- const { runtime, state } = setup({ enqueueError: lost, receipts: { 'c-1': 'pending' } });
+ const { runtime, state, invoke } = setup({ agentKind, enqueueError: lost, receipts: { 'c-1': 'pending' } });
await expect(
runtime.dispatch({ proxySessionId: 'proxy-1', rawContent: 'x', clientId: 'c-1' }),
- ).resolves.toEqual({ ok: true, mode: 'dispatched' });
+ ).resolves.toEqual({ ok: true, mode: 'queued', agentKind: agentKind === 'cc' ? 'claude-code' : agentKind });
+ expect(invoke.mock.calls.filter(([, channel]) => channel === 'maker:input:enqueue')).toHaveLength(1);
expect(state.enqueued).toHaveLength(0);
expect(runtime.hasPendingReport('proxy-1')).toBe(true);
});
+ const kinds = ['cc', 'codex', 'pi'] as const;
+ it.each(kinds.flatMap(from => kinds.filter(to => to !== from).map(to => ({ from, to }))))(
+ 'reports the accepted input Agent after a pending $from → $to switch, even if the task switches again', async ({ from, to }) => {
+ const { runtime, state, invoke } = setup({ agentKind: from });
+ const original = invoke.getMockImplementation()!;
+ invoke.mockImplementation(async (deviceId, channel, args) => {
+ const result = await original(deviceId, channel, args);
+ if (channel === 'maker:input:enqueue') {
+ state.acceptedAgents['c-1'] = to;
+ state.receipts['c-1'] = 'accepted';
+ state.agentKind = from; // A later switch must not relabel this accepted input.
+ }
+ return result;
+ });
+ await expect(runtime.dispatch({ proxySessionId: 'proxy-1', rawContent: 'task', clientId: 'c-1' }))
+ .resolves.toMatchObject({ ok: true, mode: 'dispatched', agentKind: to === 'cc' ? 'claude-code' : to });
+ expect(state.enqueued[0]).toMatchObject({ createOpts: { agentKind: from === 'cc' ? 'claude-code' : from } });
+ expect(invoke).toHaveBeenCalledWith('mac-mini', 'local-db:messages:around-client-id',
+ ['remote-1', 'c-1', { radius: 0, contentCharLimit: 1 }]);
+ },
+ );
+
+ it.each(['read-failed', 'old-peer', 'wrong-client', 'wrong-role'])('keeps delivered input queued when accepted-Agent evidence is %s', async reason => {
+ const { runtime, state, invoke } = setup();
+ const original = invoke.getMockImplementation()!;
+ invoke.mockImplementation(async (deviceId, channel, args) => {
+ if (channel === 'local-db:messages:around-client-id') {
+ if (reason === 'read-failed') throw new Error('[INVOKE_TIMEOUT] no reply');
+ return [{ clientId: reason === 'wrong-client' ? 'other' : 'c-1',
+ role: reason === 'wrong-role' ? 'assistant' : 'user',
+ ...(reason === 'old-peer' ? {} : { agentKind: 'pi' }) }];
+ }
+ return original(deviceId, channel, args);
+ });
+ await expect(runtime.dispatch({ proxySessionId: 'proxy-1', rawContent: 'task', clientId: 'c-1' }))
+ .resolves.toMatchObject({ ok: true, mode: 'queued' });
+ expect(state.enqueued).toHaveLength(1);
+ expect(runtime.hasPendingReport('proxy-1')).toBe(true);
+ expect(runtime.isReachable('proxy-1')).toBe(true);
+ });
+
+ it('recovers the accepting Agent after a lost enqueue acknowledgement without resending', async () => {
+ const lost = Object.assign(new Error('[INVOKE_TIMEOUT] no reply'), { inFlight: true });
+ const { runtime, invoke } = setup({ agentKind: 'cc', enqueueError: lost,
+ receipts: { 'c-1': 'accepted' }, acceptedAgents: { 'c-1': 'pi' } });
+ await expect(runtime.dispatch({ proxySessionId: 'proxy-1', rawContent: 'task', clientId: 'c-1' }))
+ .resolves.toMatchObject({ ok: true, mode: 'dispatched', agentKind: 'pi' });
+ expect(invoke.mock.calls.filter(([, channel]) => channel === 'maker:input:enqueue')).toHaveLength(1);
+ });
+
it('does not re-report an already bridged reply and ends with an error when no new reply appears', async () => {
const { runtime, deps, state } = setup({ assistant: { id: 'msg-0', content: '旧回复' } });
await runtime.dispatch({ proxySessionId: 'proxy-1', rawContent: 'x', 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 efb33dbda0..e6f610aa54 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteWorkers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaRemoteWorkers.test.ts
@@ -57,6 +57,7 @@ function setup(opts: {
getTeamService?: () => OrcaTeamService | null;
} = {}) {
const devices = opts.devices ?? [device({})];
+ const acceptedInputs = new Map<string, string>();
const remoteInvoke = vi.fn(async (deviceId: string, channel: string, args: unknown[]) => {
const custom = await opts.handle?.(deviceId, channel, args);
if (custom) return custom;
@@ -75,7 +76,13 @@ function setup(opts: {
case 'local-db:history:messages':
return ok({ items: [], terminal: null });
case 'maker:input:enqueue':
+ acceptedInputs.set((args[1] as { clientId: string }).clientId, 'cc');
return ok({});
+ case 'local-db:messages:around-client-id': {
+ const clientId = args[1] as string;
+ const agentKind = acceptedInputs.get(clientId);
+ return ok(agentKind ? [{ clientId, role: 'user', agentKind }] : []);
+ }
case 'maker:abort-session':
return ok(undefined);
case 'maker:orca:remote-worker:release':
@@ -775,6 +782,58 @@ describe('wrapTeamDeps', () => {
workers.stop();
});
+ const remoteAgentKinds = ['claude-code', 'codex', 'pi'] as const;
+ const remoteSwitchCases = remoteAgentKinds.flatMap(from => remoteAgentKinds
+ .filter(to => to !== from).flatMap(to => ['dispatch', 'interrupt', 'queued'].map(mode => ({ from, to, mode }))));
+ it.each(remoteSwitchCases)('returns the execution device Agent after $from → $to ($mode)', async ({ from, to, mode }) => {
+ let dispatchCount = 0;
+ const acceptedInputs = new Map<string, string>();
+ const { workers, remoteInvoke } = await trackedWorker({ handle: (_device, channel, args) => {
+ if (channel === 'local-db:sessions:get') return ok({ status: 'active',
+ agentKind: from === 'claude-code' ? 'cc' : from,
+ workingDir: '/remote/work', model: 'remote-model' });
+ if (channel === 'maker:input:enqueue') {
+ dispatchCount += 1;
+ if (dispatchCount === 1 || mode !== 'queued') {
+ acceptedInputs.set((args[1] as { clientId: string }).clientId, dispatchCount === 1 ? from : to);
+ }
+ return ok({});
+ }
+ if (channel === 'local-db:messages:around-client-id') {
+ const clientId = args[1] as string;
+ const agentKind = acceptedInputs.get(clientId);
+ return ok(agentKind ? [{ clientId, role: 'user', agentKind }] : []);
+ }
+ if (channel === 'maker:list-active') return ok({ format: 'active-sessions-v2',
+ sessions: [{ sessionId: 'remote-1', isTurnRunning: mode === 'queued' }] });
+ return undefined;
+ } });
+ try {
+ // The pending switch commits only when the execution device consumes the
+ // second input. Both the proxy and the pre-enqueue session row remain old.
+ const wrapped = workers.wrapTeamDeps(baseDeps());
+ const params = { targetSessionId: 'proxy-1', workerId: 'w-1', message: 'Continue',
+ dispatchMeta: { source: 'mcp', context: 'send_to_worker' } };
+ const first = await wrapped.dispatchWorkerMessage(params);
+ expect(first).toMatchObject({ ok: true, mode: 'dispatched', agentKind: from });
+ if (mode === 'queued') await workers.runtime.pollNow();
+ const result = await (mode === 'interrupt'
+ ? wrapped.reserveWorkerMessage(params)
+ : wrapped.dispatchWorkerMessage(params));
+ if (mode === 'queued') {
+ expect(result).toMatchObject({ ok: true, mode: 'queued' });
+ expect(result).not.toHaveProperty('agentKind');
+ } else {
+ expect(result).toMatchObject({ ok: true, mode: 'dispatched', agentKind: to });
+ }
+ const enqueueCalls = remoteInvoke.mock.calls.filter(([, channel]) => channel === 'maker:input:enqueue');
+ expect(enqueueCalls).toHaveLength(2);
+ expect(enqueueCalls[1]![2][1]).toMatchObject({ createOpts: { agentKind: from } });
+ // Enqueue is still the old projection response; acceptance evidence comes
+ // from the existing message lookup, never from a second enqueue.
+ } finally { workers.stop(); }
+ });
+
it('fails the dispatch when the device is offline instead of queueing it', async () => {
let offline = false;
const { workers } = await trackedWorker({
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
index 809e956895..94f49061e6 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
@@ -391,6 +391,47 @@ function createDeps(overrides: Partial<OrcaTeamServiceDeps> = {}) {
}
describe('OrcaTeamService', () => {
+ const receiptAgentKinds = ['claude-code', 'codex', 'pi'] as const;
+ const receiptCases = receiptAgentKinds.flatMap((from) =>
+ receiptAgentKinds.filter((to) => to !== from).flatMap((to) =>
+ (['dispatched', 'queued'] as const).map((mode) => ({ from, to, mode })),
+ ),
+ );
+ it.each(receiptCases)('maps the $mode Agent receipt for $from → $to without reporting an uncommitted switch', async ({ from, to, mode }) => {
+ const { deps, service, setWorker } = createDeps();
+ const worker = createWorker();
+ setWorker({ ...worker, session: { ...worker.session, agentKind: from } });
+ vi.mocked(deps.dispatchWorkerMessage).mockImplementation(async (params) => {
+ if (mode === 'dispatched') await params.onAccepted?.();
+ return {
+ ok: true, mode, agentKind: to, clientId: 'receipt-input',
+ dispatchOutcome: {
+ kind: 'session-dispatch', source: params.dispatchMeta.source, dispatched: true,
+ ...(mode === 'queued' ? { wakeKind: 'queued' as const } : {}),
+ },
+ targetTitle: 'Worker', targetLastUserSendAt: null,
+ };
+ });
+ const result = await service.sendToWorker({
+ callerLeadSessionId: 'lead-1', targetSessionId: 'worker-session-1', message: 'Continue on the selected Agent',
+ });
+ expect(result).toMatchObject({ ok: true, agentKind: mode === 'dispatched' ? to : from });
+ if (mode === 'queued') {
+ expect(result).toMatchObject({ wakeKind: 'queued', queuedMessageId: 'receipt-input' });
+ expect(deps.updateWorkerStatus).not.toHaveBeenCalled();
+ }
+ });
+
+ it('retains the snapshot Agent for dispatch adapters without an Agent receipt', async () => {
+ const { service, setWorker } = createDeps();
+ const worker = createWorker();
+ setWorker({ ...worker, session: { ...worker.session, agentKind: 'pi' } });
+ await expect(service.dispatchWorkerTask({
+ targetSessionId: 'worker-session-1', message: 'Continue',
+ dispatchMeta: { source: 'orca', context: 'legacy-agent-receipt' },
+ })).resolves.toMatchObject({ dispatched: true, agentKind: 'pi' });
+ });
+
it.each(['send', 'interrupt'].flatMap(action => ['initial', 'lookup', 'restore', 'accept', 'queued', 'healthy'].map(phase => ({action,phase}))))(
'preserves plugin authority for public $action across $phase', async ({action,phase}) => {
let revoked = phase === 'initial', nativeCalls = 0;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
index d10a39a913..0ee8db1b70 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
@@ -15,6 +15,7 @@ import {
import { createAgentHandoffPendingRegistry } from '../agentHandoff';
import { MAKER_INVOKE } from '../channels';
import { IpcHarness } from './helpers/ipcHarness';
+import { runDeviceLinkInvokeContext } from '../../device-link/invoke-context';
function makeRow(overrides: Partial<AgentSwitchSessionRow> = {}): AgentSwitchSessionRow {
return {
@@ -78,6 +79,76 @@ const validParams = {
providerId: null,
};
+const orcaAgents = [
+ { kind: 'claude-code', dbKind: 'cc', model: 'claude-fable-5', providerId: 'anthropic' },
+ { kind: 'codex', dbKind: 'codex', model: 'gpt-6-astra', providerId: 'openai' },
+ { kind: 'pi', dbKind: 'pi', model: 'gpt-6-astra', providerId: 'openai' },
+] as const;
+const orcaSwitchCases = (['lead', 'worker'] as const).flatMap((role) =>
+ orcaAgents.flatMap((from) => orcaAgents.filter((to) => to.kind !== from.kind).map((to) => ({
+ role, from, to, name: `${role}: ${from.kind} → ${to.kind}`,
+ }))),
+);
+
+describe('Orca three-Agent switching', () => {
+ it.each(orcaSwitchCases)('$name stages until idle, preserves its role, and resumes the parked source on return', async ({ role, from, to }) => {
+ let row = makeRow({ agentKind: from.dbKind, model: from.model, providerId: from.providerId, orcaRole: role });
+ let running = true;
+ const pendingSwitches = createPendingAgentSwitchRegistry();
+ const parked = new Map<string, string>();
+ const { deps } = makeDeps({
+ pendingSwitches,
+ getSessionRow: vi.fn(async () => ({ ...row })),
+ getLiveSession: vi.fn(() => ({ isTurnRunning: () => running })),
+ findParkedEngineSession: vi.fn(async (_id, kind) => {
+ const sdkSessionId = parked.get(kind);
+ return sdkSessionId ? { sdkSessionId, watermarkCreatedAt: 0, watermarkRowid: 0 } : null;
+ }),
+ applyAgentSwitchToDb: vi.fn(async (_id, patch) => {
+ row = { ...row, ...patch, providerId: patch.providerId ?? null, sdkSessionId: patch.sdkSessionId ?? null };
+ }),
+ insertBoundaryMessage: vi.fn(async (_id, boundary) => {
+ if (boundary.fromSdkSessionId) parked.set(boundary.fromAgentKind, boundary.fromSdkSessionId);
+ return `boundary-${parked.size}`;
+ }),
+ bootstrapSwitchedSession: vi.fn(async () => { row.sdkSessionId ??= `native-${row.agentKind}`; }),
+ });
+
+ await expect(performSessionAgentSwitch(deps, {
+ sessionId: 's1', targetAgentKind: to.kind, model: to.model, providerId: to.providerId,
+ })).resolves.toMatchObject({ deferred: true, switched: false });
+ await applyPendingAgentSwitchIfIdle(deps, 's1', { bootstrapAfterSwitch: true });
+ expect(row).toMatchObject({ agentKind: from.dbKind, sdkSessionId: 'sdk-old', orcaRole: role });
+ expect(deps.closeSession).not.toHaveBeenCalled();
+ expect(pendingSwitches.get('s1')?.targetAgentKind).toBe(to.kind);
+
+ running = false;
+ await applyPendingAgentSwitchIfIdle(deps, 's1', { bootstrapAfterSwitch: true });
+ expect(row).toMatchObject({ agentKind: to.dbKind, model: to.model, providerId: to.providerId, orcaRole: role, sdkSessionId: `native-${to.dbKind}` });
+ expect(pendingSwitches.get('s1')).toBeUndefined();
+ expect(deps.closeSession).toHaveBeenCalledExactlyOnceWith('s1');
+ expect(deps.bootstrapSwitchedSession).toHaveBeenCalledExactlyOnceWith('s1');
+ expect(deps.applyAgentSwitchToDb).toHaveBeenCalledWith('s1', expect.objectContaining({ agentKind: to.dbKind, sdkSessionId: null }));
+ expect(deps.insertBoundaryMessage).toHaveBeenLastCalledWith('s1', expect.objectContaining({
+ fromAgentKind: from.dbKind, toAgentKind: to.dbKind, fromSdkSessionId: 'sdk-old',
+ consumed: false, resumed: false, handoff: expect.stringContaining('你好'),
+ }));
+
+ await performSessionAgentSwitch(deps, {
+ sessionId: 's1', targetAgentKind: from.kind, model: from.model, providerId: from.providerId,
+ });
+ await applyPendingAgentSwitchIfIdle(deps, 's1', { bootstrapAfterSwitch: true });
+ expect(row).toMatchObject({ agentKind: from.dbKind, model: from.model, providerId: from.providerId, orcaRole: role, sdkSessionId: 'sdk-old' });
+ expect(pendingSwitches.get('s1')).toBeUndefined();
+ expect(deps.insertBoundaryMessage).toHaveBeenLastCalledWith('s1', expect.objectContaining({
+ fromAgentKind: to.dbKind, toAgentKind: from.dbKind, resumed: true, consumed: false,
+ handoff: expect.stringContaining('now it is switching back to you'),
+ }));
+ expect(deps.closeSession).toHaveBeenCalledTimes(2);
+ expect(deps.bootstrapSwitchedSession).toHaveBeenCalledTimes(2);
+ });
+});
+
describe('same-engine selection at send', () => {
function selectionHarness() {
const pending = createPendingAgentSwitchRegistry();
@@ -401,11 +472,19 @@ describe('performSessionAgentSwitch', () => {
expect(calls).toEqual([]);
});
- it('远程会话与 Orca 会话抛 UNSUPPORTED_CAPABILITY', async () => {
+ it('远程会话仍拒绝切换,Orca Lead/Worker 复用跨引擎交接事务', async () => {
const remote = makeDeps({ getSessionRow: vi.fn(async () => makeRow({ remoteHostId: 'host-1' })) });
await expect(performSessionAgentSwitch(remote.deps, validParams)).rejects.toThrow(/UNSUPPORTED_CAPABILITY/);
const orca = makeDeps({ getSessionRow: vi.fn(async () => makeRow({ orcaRole: 'lead' })) });
- await expect(performSessionAgentSwitch(orca.deps, validParams)).rejects.toThrow(/UNSUPPORTED_CAPABILITY/);
+ await expect(performSessionAgentSwitch(orca.deps, validParams)).resolves.toMatchObject({
+ switched: true,
+ agentKind: 'codex',
+ model: 'gpt-5.5',
+ });
+ expect(orca.deps.applyAgentSwitchToDb).toHaveBeenCalledWith('s1', expect.objectContaining({
+ agentKind: 'codex',
+ model: 'gpt-5.5',
+ }));
});
it('同引擎目标 = no-op 成功,不发生任何状态变更', async () => {
@@ -1392,8 +1471,13 @@ describe('远程 Agent:选模型时换 Agent 所在电脑', () => {
})).resolves.toMatchObject({ switched: true });
});
- it('协同任务:用户换位置、登记意图、换模型或换引擎一律拒绝,即使带着组的标记', async () => {
- const row = { orcaRole: 'worker' as const, model: 'anthropic/claude-opus-5-5[1m]' };
+ it.each([
+ { orcaRole: 'worker' },
+ { orcaRole: null, orcaRemoteLead: JSON.stringify({ leadDeviceId: 'lead-device', leadSessionId: 'lead-1', workerLabel: 'worker' }) },
+ { orcaRole: null, orcaRemoteLead: JSON.stringify({ leadDeviceId: 'lead-device', leadSessionId: 'lead-1', workerLabel: 'worker', releasedAt: 1 }) },
+ ])('rejects user relocation while preserving harness/model selection: %j', async (identity) => {
+ const row = { ...identity, model: 'anthropic/claude-opus-5-5[1m]' };
+ const { agentDeviceId: _omit, ...withoutLocation } = backToTaskComputer;
const userMove = relocationHarness(row);
await expect(performSessionAgentSwitch(userMove.deps, { ...backToTaskComputer, agentDeviceId: 'office-pc' }))
.rejects.toThrow(/UNSUPPORTED_CAPABILITY/);
@@ -1405,21 +1489,18 @@ describe('远程 Agent:选模型时换 Agent 所在电脑', () => {
})).rejects.toThrow(/UNSUPPORTED_CAPABILITY/);
const otherModel = relocationHarness(row);
await expect(performSessionAgentSwitch(otherModel.deps, {
- ...backToTaskComputer,
+ ...withoutLocation,
model: 'claude-sonnet-5',
- agentDeviceId: 'office-pc',
applyNow: true,
- providerGroupRelocation: true,
- })).rejects.toThrow(/UNSUPPORTED_CAPABILITY/);
+ })).resolves.toMatchObject({ switched: false });
const otherEngine = relocationHarness(row);
await expect(performSessionAgentSwitch(otherEngine.deps, {
- ...backToTaskComputer,
+ ...withoutLocation,
targetAgentKind: 'codex',
- agentDeviceId: 'office-pc',
applyNow: true,
- providerGroupRelocation: true,
- })).rejects.toThrow(/UNSUPPORTED_CAPABILITY/);
- for (const h of [userMove, staged, otherModel, otherEngine]) expect(h.calls).toEqual([]);
+ })).resolves.toMatchObject({ switched: true });
+ expect(userMove.calls).toEqual([]);
+ expect(staged.calls).toEqual([]);
});
it('非法位置参数被拒绝', async () => {
@@ -1444,6 +1525,22 @@ describe('远程 Agent:选模型时换 Agent 所在电脑', () => {
agentDeviceId: null,
});
});
+
+ it('passes a local window acknowledgement to same-Agent selection but rejects remote claims', async () => {
+ const h = relocationHarness({ orcaRole: 'worker', agentDeviceId: null });
+ const ipc = new IpcHarness();
+ registerMakerSessionAgentSwitchHandler(ipc, h.deps);
+ const select = (confirmedContextWindow: unknown) => ipc.invoke(MAKER_INVOKE.SWITCH_SESSION_AGENT,
+ 's1', 'claude-code', 'small-model', 'xd', 'high', false, { confirmedContextWindow });
+ await select(200000);
+ expect(h.pending.get('s1')?.confirmedContextWindow).toBe(200000);
+ await expect(runDeviceLinkInvokeContext({ controllerDeviceId: 'controller', channel: MAKER_INVOKE.SWITCH_SESSION_AGENT },
+ () => select(100000))).rejects.toThrow(/PRECONDITION_FAILED/);
+ for (const invalid of [0, -1, 1.5, Number.NaN, '200000']) {
+ await expect(select(invalid)).rejects.toThrow(/INVALID_PARAMS/);
+ }
+ expect(h.pending.get('s1')?.confirmedContextWindow).toBe(200000);
+ });
});
describe('换到供应商组那一项:由组选一台能用的电脑(provider-groups.md §6)', () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeHarnessSelection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeHarnessSelection.test.ts
index 1d5e0542fd..b637403439 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeHarnessSelection.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeHarnessSelection.test.ts
@@ -237,9 +237,39 @@ describe('runtime harness selection', () => {
},
);
+ it.each([
+ { orcaRole: 'lead', running: false },
+ { orcaRole: 'lead', running: true },
+ { orcaRole: 'worker', running: false },
+ { orcaRole: 'worker', running: true },
+ ])('stages an Orca harness choice until the next send: %j', async ({ orcaRole, running }) => {
+ const h = setup(running);
+ h.pending.set('s1', { targetAgentKind: 'pi', model: 'old-choice', providerId: null });
+ const read = h.switchDeps.getSessionRow;
+ h.switchDeps.getSessionRow = async (id) => ({ ...(await read(id))!, orcaRole });
+
+ expect(await setSessionRuntimeHarness(h.deps, request)).toMatchObject({
+ ok: true,
+ status: 'deferred',
+ effectiveBoundary: 'next_send',
+ generation: 5,
+ effectiveProfile: h.effective,
+ pendingMutation: {
+ source: 'agent',
+ profile: { agentKind: 'codex', model: 'gpt-6-astra', providerId: 'openai' },
+ },
+ });
+ expect(h.pending.get('s1')).toMatchObject({
+ targetAgentKind: 'codex', model: 'gpt-6-astra', providerId: 'openai',
+ });
+ expect(h.close).not.toHaveBeenCalled();
+ expect(h.persist).not.toHaveBeenCalled();
+ });
+
it.each([
{ remoteHostId: 'ssh-host' },
- { orcaRole: 'lead' },
+ { remoteHostId: 'ssh-host', orcaRole: 'lead' },
+ { remoteHostId: 'ssh-host', orcaRole: 'worker' },
{ source: 'review' },
{ status: 'deleted' },
{ status: 'archived' },
diff --git a/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts b/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts
index 5ad87f95da..9448b9e472 100644
--- a/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaInterAgentDispatcher.ts
@@ -25,6 +25,7 @@ import type {
ControlSteerOutcome,
} from './agent-input-coordinator.js';
import { runAcceptedCallback, runAcceptedRollback } from './acceptedCallbackRunner.js';
+import { prependHandoffToUserMessage } from './agentHandoff.js';
const defaultLog = createLogger('maker-ipc');
@@ -38,6 +39,8 @@ export type DispatchOrcaInterAgentMessageResult =
| {
ok: true;
mode: OrcaInterAgentDispatchMode;
+ /** Runtime that accepted the message; queued messages have not switched yet. */
+ agentKind?: AgentKind;
clientId: string;
dispatchOutcome: CollabDispatchSuccessOutcome | CollabDispatchQueuedOutcome;
targetTitle?: string | null;
@@ -152,6 +155,11 @@ export interface OrcaInterAgentDispatcherDeps<TSessionMeta> {
getSessionMeta: (sessionId: string) => Promise<TSessionMeta | null>;
getSessionRowSnapshot: (sessionId: string) => Promise<OrcaInterAgentSessionRowSnapshot | null>;
getLiveSession: (sessionId: string) => PersistedUserMessageSession | null | undefined;
+ /** Apply a deferred route while the per-session send lock is held. */
+ applyPendingAgentSwitch?: (sessionId: string) => Promise<void>;
+ hasPendingAgentSwitch?: (sessionId: string) => boolean;
+ peekPendingHandoff?: (sessionId: string) => Promise<string | null>;
+ consumePendingHandoff?: (sessionId: string) => void;
/** Uses the input coordinator's steer guards and preserves uncertain-delivery ownership. */
steerControlInput?: (
sessionId: string,
@@ -473,6 +481,7 @@ export function createOrcaInterAgentDispatcher<TSessionMeta>(
// The message joined the running turn. Accepted/commit callbacks claim a new
// turn's running/auto-bridge identity, so they deliberately never run here.
return { ok: true, mode: 'steered', clientId,
+ ...(liveTurn.agentKind ? { agentKind: liveTurn.agentKind } : {}),
dispatchOutcome: { kind: 'session-dispatch', source: params.meta.source, dispatched: true },
...dispatchReceipt };
}
@@ -547,6 +556,7 @@ export function createOrcaInterAgentDispatcher<TSessionMeta>(
return {
ok: true,
mode: result.wakeKind === 'queued' ? 'queued' : 'dispatched',
+ ...(result.wakeKind !== 'queued' ? { agentKind: result.agentKind } : {}),
clientId,
dispatchOutcome: result.wakeKind === 'queued'
? makeQueuedDispatchOutcome(params.meta.source)
@@ -567,6 +577,14 @@ export function createOrcaInterAgentDispatcher<TSessionMeta>(
});
};
const dispatchLive = async (): Promise<DispatchOrcaInterAgentMessageResult | null> => {
+ // Orca delivery bypasses the ordinary renderer send transaction. Apply
+ // the same deferred route boundary before reading the live session.
+ await deps.applyPendingAgentSwitch?.(params.targetSessionId);
+ // Cross-engine preparation may retain the intent without throwing. Never
+ // deliver to the old runtime, or bypass an unfinished recovery by resuming.
+ if (deps.hasPendingAgentSwitch?.(params.targetSessionId)) {
+ throw new Error('Agent switch is still pending; retry the send after recovery');
+ }
await deps.prepareUnhealthySession?.(params.targetSessionId);
const live = deps.getLiveSession(params.targetSessionId);
if (!live) return null;
@@ -593,7 +611,9 @@ export function createOrcaInterAgentDispatcher<TSessionMeta>(
log,
);
}
- return { ok: true, mode: 'dispatched', clientId, dispatchOutcome: result.dispatchOutcome, ...dispatchReceipt };
+ return { ok: true, mode: 'dispatched', clientId,
+ ...(live.agentKind ? { agentKind: live.agentKind } : {}),
+ dispatchOutcome: result.dispatchOutcome, ...dispatchReceipt };
}
if (result.dispatchOutcome.kind === 'host-send' && result.dispatchOutcome.code === 'SESSION_RUNNING') {
await rollbackAcceptedForRequeue();
@@ -783,26 +803,36 @@ async function sendPersistedUserMessageToSession<TSessionMeta>(
const { session, dbContent, agentMessage, clientId = deps.createId(), source, context, origin, onAccepted } = params;
let turnChangeSetStarted = false;
const humanIntent = restoreAutoReviewUserIntent(await deps.readAutoReviewHistory?.(session.id) ?? []);
+ const pendingHandoff = await deps.peekPendingHandoff?.(session.id);
+ const outgoingMessage = pendingHandoff
+ ? prependHandoffToUserMessage(agentMessage, pendingHandoff) as UserMessage
+ : agentMessage;
const result = await resolveCollabDispatchResult(
- () => session.send(agentMessage, {
- planMode: false,
- throwOnStartFailure: true,
- [AUTO_REVIEW_SOURCE_CONTENT]: '',
- [AUTO_REVIEW_USER_INTENT]: humanIntent,
- [AUTO_REVIEW_DELEGATED_CONTINUATION]: true,
- onAccepted: async () => {
- // maker-core 会在 vendor handle.send 前 await 此 hook;必须先落库,再运行 accepted 副作用。
- await deps.createDbMessage(session.id, {
- clientId,
- role: 'user',
- content: dbContent,
- agentMeta: { ...(origin ? { origin } : {}), autoReviewUserText: { kind: 'delegated-continuation' }, delivery: 'turn' },
- });
- await deps.beginDirectTurnChangeSet(session.id, clientId);
- turnChangeSetStarted = true;
- await runAcceptedCallback(onAccepted, session.id, clientId, deps.log ?? defaultLog);
- },
- }),
+ async () => {
+ const sendResult = await session.send(outgoingMessage, {
+ planMode: false,
+ throwOnStartFailure: true,
+ [AUTO_REVIEW_SOURCE_CONTENT]: '',
+ [AUTO_REVIEW_USER_INTENT]: humanIntent,
+ [AUTO_REVIEW_DELEGATED_CONTINUATION]: true,
+ onAccepted: async () => {
+ // maker-core 会在 vendor handle.send 前 await 此 hook;必须先落库,再运行 accepted 副作用。
+ await deps.createDbMessage(session.id, {
+ clientId,
+ role: 'user',
+ content: dbContent,
+ agentMeta: { ...(origin ? { origin } : {}), autoReviewUserText: { kind: 'delegated-continuation' }, delivery: 'turn' },
+ });
+ await deps.beginDirectTurnChangeSet(session.id, clientId);
+ turnChangeSetStarted = true;
+ await runAcceptedCallback(onAccepted, session.id, clientId, deps.log ?? defaultLog);
+ },
+ });
+ // Keep the handoff for retries until the target actually accepts it. It is
+ // model-only context: dbContent and any requeued message stay unchanged.
+ if (pendingHandoff && sendResult.accepted) deps.consumePendingHandoff?.(session.id);
+ return sendResult;
+ },
{ source, context },
);
if (turnChangeSetStarted && !result.dispatched) {
diff --git a/apps/desktop/src/main/maker-ipc/orcaRemoteWorkerRuntime.ts b/apps/desktop/src/main/maker-ipc/orcaRemoteWorkerRuntime.ts
index 92a7fb89cd..ddbedb7e5f 100644
--- a/apps/desktop/src/main/maker-ipc/orcaRemoteWorkerRuntime.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaRemoteWorkerRuntime.ts
@@ -43,7 +43,12 @@ export interface RemoteWorkerTurnEnd {
}
export type RemoteWorkerDispatchResult =
- | { ok: true; mode: 'dispatched' | 'queued' }
+ | {
+ ok: true;
+ mode: 'dispatched' | 'queued';
+ /** Accepted input's Agent; queued deliveries retain the pre-enqueue Agent. */
+ agentKind: AgentInputCreateOpts['agentKind'];
+ }
| {
ok: false;
code: 'DEVICE_UNREACHABLE' | 'SESSION_NOT_FOUND' | 'SEND_FAILED';
@@ -656,10 +661,11 @@ export function createOrcaRemoteWorkerRuntime(deps: OrcaRemoteWorkerRuntimeDeps)
}
const baseline = state.awaiting?.baselineMessageId ?? (await lastAssistantMessage(ref)).id;
if (!current(state)) throw new Error('remote worker owner changed');
+ const createOpts = createOptsFromRow(row);
const item = buildRemoteWorkerQueuedMessage({
clientId: params.clientId,
rawContent: params.rawContent,
- createOpts: createOptsFromRow(row),
+ createOpts,
createdAt: new Date(deps.now()).toISOString(),
});
prepared = {
@@ -683,11 +689,31 @@ export function createOrcaRemoteWorkerRuntime(deps: OrcaRemoteWorkerRuntimeDeps)
}
if (!current(state) || state.awaiting !== prepared)
throw new Error('remote worker owner or dispatch changed');
- const accept = (): RemoteWorkerDispatchResult => {
+ const accept = async (): Promise<RemoteWorkerDispatchResult> => {
setReachable(ref.deviceId, true);
- const mode = state.inTurn ? 'queued' : 'dispatched';
schedule();
- return { ok: true, mode };
+ // Enqueue only acknowledges durable delivery. The send boundary can
+ // still be applying a harness switch; neither the earlier session row
+ // nor the last running-state poll identifies the accepting runtime.
+ // Read the engine stamped on this exact accepted input, even if the
+ // session has since switched again. Missing/old-peer evidence stays
+ // queued and must never turn an already delivered input into a retry.
+ try {
+ const rows = await deps.invoke(ref.deviceId, 'local-db:messages:around-client-id', [
+ ref.remoteSessionId, params.clientId, { radius: 0, contentCharLimit: 1 },
+ ]) as Array<{ clientId?: unknown; role?: unknown; agentKind?: unknown }>;
+ const accepted = Array.isArray(rows)
+ ? rows.find((entry) => entry.clientId === params.clientId && entry.role === 'user')
+ : undefined;
+ const kind = accepted?.agentKind;
+ if (kind === 'cc' || kind === 'claude-code' || kind === 'codex' || kind === 'pi') {
+ return { ok: true, mode: 'dispatched', agentKind: agentKindOf(kind === 'cc' ? 'claude-code' : kind) };
+ }
+ } catch {
+ // The input may still be queued, or this read may be unavailable.
+ // Existing polling owns recovery; do not re-enqueue or tear down the link.
+ }
+ return { ok: true, mode: 'queued', agentKind: createOpts.agentKind };
};
try {
await deps.invoke(ref.deviceId, 'maker:input:enqueue', [ref.remoteSessionId, item]);
diff --git a/apps/desktop/src/main/maker-ipc/orcaRemoteWorkers.ts b/apps/desktop/src/main/maker-ipc/orcaRemoteWorkers.ts
index 858c1bad79..e184d06c9e 100644
--- a/apps/desktop/src/main/maker-ipc/orcaRemoteWorkers.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaRemoteWorkers.ts
@@ -708,6 +708,7 @@ export function createOrcaRemoteWorkers(deps: OrcaRemoteWorkersDeps) {
return {
ok: true,
mode: result.mode,
+ ...(result.mode !== 'queued' ? { agentKind: result.agentKind } : {}),
clientId,
dispatchOutcome:
result.mode === 'queued'
diff --git a/apps/desktop/src/main/maker-ipc/orcaTeamService.ts b/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
index d9df6fa136..f42ff8de12 100644
--- a/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
@@ -94,6 +94,8 @@ export type DispatchWorkerMessageResult =
| {
ok: true;
mode: 'dispatched' | 'queued' | 'steered';
+ /** Accepting runtime locally; remote delivery reports the execution device's Agent at enqueue. */
+ agentKind?: AgentKind;
/** 底层 dispatcher 为该消息生成的 clientId;queued 模式下即队列内寻址句柄。 */
clientId: string;
dispatchOutcome: CollabDispatchSuccessOutcome | CollabDispatchQueuedOutcome;
@@ -893,7 +895,7 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
return {
dispatched: true,
dispatchOutcome: result.dispatchOutcome as CollabDispatchSuccessOutcome,
- agentKind: target.session.agentKind,
+ agentKind: result.agentKind ?? target.session.agentKind,
wakeKind:
result.mode === 'steered'
? 'steered'
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index c7aede1230..5f3b2afa34 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -7684,13 +7684,26 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
model: string,
providerId: string | null,
): Promise<void> {
+ await readUsableAgentDeviceProviders(deviceId, agent, model, providerId);
+ }
+
+ async function readUsableAgentDeviceProviders(
+ deviceId: string,
+ agent: AgentKind,
+ model: string,
+ providerId: string | null,
+ ): Promise<ProviderView[]> {
+ let views: ProviderView[] = [];
const checked = await checkDeviceRoute(
- () => readDeviceProviderViews(remoteBackgroundInvoke, deviceId),
+ async () => {
+ views = await readDeviceProviderViews(remoteBackgroundInvoke, deviceId);
+ return views;
+ },
agent,
providerId,
model,
);
- if (!checked) return;
+ if (!checked) return views;
// 分享来的供应商连不上(分享者电脑离线,或分享在服务端已暂停而 relay 只回离线):用分享专属
// 文案,不让受邀者去「那台电脑」上操作。
const rejection = checked === 'unreachable' && isProviderShareAgentDeviceId(deviceId)
@@ -9966,6 +9979,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
status: sessions.status,
remoteHostId: sessions.remoteHostId,
orcaRole: sessions.orcaRole,
+ orcaRemoteLead: sessions.orcaRemoteLead,
sdkSessionId: sessions.sdkSessionId,
source: sessions.source,
agentDeviceId: sessions.agentDeviceId,
@@ -10071,11 +10085,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const result = await applySessionRuntimeSelection(sessionId, intent.model, intent.providerId, {
effort: (intent.effort ?? null) as SessionRuntimeProfile['effort'],
fastMode: intent.fastMode ?? false,
- // 只有 Agent 在另一台电脑运行的任务会在意图里带确认过的目标窗口。
+ // Preserve the exact window acknowledged by the picker until send.
...(intent.confirmedContextWindow ? { confirmedContextWindow: intent.confirmedContextWindow } : {}),
}, { source: 'user', sessionLockHeld: true, applyingUserSelectionOnSend: applyNow,
runtimeSource: intent.runtimeSource, configStaged: intent.configStaged === true,
assertSelectionCurrent, beforeMutation });
+ if (result.contextWindowConfirmationRequired !== undefined) {
+ throwIpcError('PRECONDITION_FAILED', 'Model context window changed or was unknown; select the model again to confirm');
+ }
return result;
},
onPendingSwitchChanged: (sessionId, intent) => {
@@ -13253,6 +13270,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
getSessionMeta: (sessionId) => maker.getSessionMeta(sessionId).catch(() => null),
getSessionRowSnapshot,
getLiveSession: (sessionId) => maker.getSession(sessionId),
+ applyPendingAgentSwitch: (sessionId) =>
+ applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId, { bootstrapAfterSwitch: true }),
+ hasPendingAgentSwitch: (sessionId) => !!agentSwitchPending.get(sessionId),
+ peekPendingHandoff: (sessionId) => agentHandoffPending.peek(sessionId),
+ consumePendingHandoff: (sessionId) => agentHandoffPending.consume(sessionId),
shouldQueueNewTurn: (sessionId): boolean => inputCoordinator.shouldQueueNewTurn(sessionId),
steerControlInput: (sessionId, item, expectedTurn) =>
inputCoordinator.steerControlInput(sessionId, { item }, expectedTurn),
@@ -13878,6 +13900,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
ok: true,
mode: result.mode,
clientId: result.clientId,
+ ...(result.agentKind ? { agentKind: result.agentKind } : {}),
dispatchOutcome: result.dispatchOutcome,
targetTitle: result.targetTitle ?? null,
targetLastUserSendAt: result.targetLastUserSendAt ?? null,
@@ -16156,6 +16179,16 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
(await readSessionSource(sessionId)) === CINDY_MAKE_SESSION_SOURCE,
applyPendingAgentSwitch: async (sessionId, options) => {
await applyPendingAgentSwitchIfIdle(agentSwitchDeps, sessionId);
+ // Queued Orca delivery and resume both use this transaction. A failed
+ // cross-engine preparation may retain its intent without throwing.
+ if (agentSwitchPending.get(sessionId)) {
+ const row = await getSessionRowSnapshotStrict(sessionId);
+ // Execution-device Workers have an authoritative remote Lead binding,
+ // not an orca_role. Do not use the incoming message's origin as identity.
+ if (row?.orcaRole || parseOrcaRemoteLead(row?.orcaRemoteLead)) {
+ throwIpcError('PRECONDITION_FAILED', 'Agent switch is still pending; retry the send after recovery');
+ }
+ }
// 已归组的任务所在那台现在不能用时,先换到组里下一台再发(失败不影响这次发送);离线时先等它恢复,
// 等的时候进行中行显示「重新连接中 n/5」。
await providerGroupService?.beforeSend(sessionId, {
@@ -19913,7 +19946,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
sessionId, model, providerId, atomicSelection, internalOptions, runtimeStatus,
assertRuntimeOwnerCurrent, assertSharedTaskCurrent, supersededByOwnerBoundary,
} = input;
- const targetContextWindow = typeof input.confirmedContextWindow === 'number' && input.confirmedContextWindow > 0
+ let targetContextWindow = typeof input.confirmedContextWindow === 'number' && input.confirmedContextWindow > 0
? input.confirmedContextWindow
: undefined;
const currentProviderId = hasSessionProvider(sessionId)
@@ -19931,8 +19964,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
: ((runtimeStatus.effort ?? null) as SessionRuntimeProfile['effort']);
const targetFastMode = atomicSelection?.fastMode ?? runtimeStatus.fastMode;
const agentKind = dbToMakerAgentKind(runtimeStatus.agentKind as 'cc' | 'codex' | 'pi');
- if (internalOptions.source === 'user' && !internalOptions.applyingUserSelectionOnSend &&
- !runtimeStatus.orcaRole) {
+ if (internalOptions.source === 'user' && !internalOptions.applyingUserSelectionOnSend) {
assertRuntimeOwnerCurrent();
assertSharedTaskCurrent.admit();
// 那台的目录里没有这个模型(例如控制端列的是任务所在电脑的目录):现在就拒绝,
@@ -19961,7 +19993,19 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return response;
}
if (supersededByOwnerBoundary()) return { deferred: false, superseded: true };
- const live = maker.getSession(sessionId);
+ const orcaSelectionOnSend = !!runtimeStatus.orcaRole && internalOptions.source === 'user' &&
+ internalOptions.applyingUserSelectionOnSend === true;
+ if (orcaSelectionOnSend && runtimeStatus.agentDeviceId) {
+ // Selection-time metadata may be absent or stale after a queued turn. Read
+ // the execution computer again; an acknowledgement is not window metadata.
+ const providers = await readUsableAgentDeviceProviders(
+ runtimeStatus.agentDeviceId, agentKind, model, targetProviderId,
+ );
+ if (supersededByOwnerBoundary()) return { deferred: false, superseded: true };
+ assertRuntimeOwnerCurrent();
+ targetContextWindow = resolveVerifiedContextWindow({ providers }, agentKind, targetProviderId, model) ?? undefined;
+ }
+ let live = maker.getSession(sessionId);
if (live && isSessionInTurn(sessionId)) {
// 自动跟随(渠道默认 / 回退)在回合中不改;用户的选择由发送边界在回合外落地。
if (internalOptions.source !== 'user') return { deferred: false, superseded: true };
@@ -19969,13 +20013,19 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
assertSharedTaskCurrent.admit();
// 换到上下文更小的模型:与本机任务同一套保护——占用超过目标窗口的安全线时先把对话交接
- // 成摘要、关掉当前会话,下一次发送按新模型重新开始。目标窗口来自那台的目录(点选时已确认)。
+ // 成摘要、关掉当前会话,下一次发送按新模型重新开始。Orca 发送前重读目标窗口,
+ // 只有本机确认的具体窗口仍匹配时才允许重建,冷恢复也经过同一保护。
let rebuiltForWindow = false;
- if (live && targetContextWindow && contextOverflowRolloverHolder) {
+ if (orcaSelectionOnSend && targetContextWindow && !contextOverflowRolloverHolder) {
+ throwIpcError('PRECONDITION_FAILED', 'model window switch protection is unavailable; runtime selection was not changed');
+ }
+ if ((live || orcaSelectionOnSend) && targetContextWindow && contextOverflowRolloverHolder) {
const prepared = await contextOverflowRolloverHolder.prepareModelWindowSwitch(sessionId, {
contextWindow: targetContextWindow,
recheckTargetPressure: true,
- confirmedTargetPressure: internalOptions.applyingUserSelectionOnSend === true,
+ confirmedTargetPressure: orcaSelectionOnSend
+ ? input.confirmedContextWindow === targetContextWindow
+ : internalOptions.applyingUserSelectionOnSend === true,
assertCanCommit: () => {
assertRuntimeOwnerCurrent();
assertSharedTaskCurrent.admit();
@@ -19987,7 +20037,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (prepared === 'confirmation-required') {
return { deferred: false, superseded: false, contextWindowConfirmationRequired: targetContextWindow };
}
+ if (orcaSelectionOnSend && prepared !== 'not-needed' && prepared !== 'rebuilt') {
+ throwIpcError('PRECONDITION_FAILED', 'model window switch could not be verified; runtime selection was not changed');
+ }
+ if (orcaSelectionOnSend) {
+ if (supersededByOwnerBoundary()) return { deferred: false, superseded: true };
+ assertRuntimeOwnerCurrent();
+ assertSharedTaskCurrent.admit();
+ }
rebuiltForWindow = prepared === 'rebuilt';
+ // Cold Pi verification can attach a runtime; use that handle for setModel.
+ if (orcaSelectionOnSend && !rebuiltForWindow) live = maker.getSession(sessionId);
}
if (live && !rebuiltForWindow) {
// 那台的 Agent 认为需要换进程(跨来源等)时关掉本次连接,下一次发送按新路由重新启动
@@ -20149,6 +20209,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
.drizzle.select({
status: sessions.status,
orcaRole: sessions.orcaRole,
+ orcaRemoteLead: sessions.orcaRemoteLead,
agentKind: sessions.agentKind,
remoteHostId: sessions.remoteHostId,
agentDeviceId: sessions.agentDeviceId,
@@ -20355,11 +20416,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// A picker click records intent only. Keep the persisted route and native binding
// authoritative until a real send holds this same lock and consumes the final choice.
if (internalOptions.source === 'user' && !internalOptions.applyingUserSelectionOnSend &&
- !runtimeStatus.remoteHostId && !runtimeStatus.orcaRole) {
+ !runtimeStatus.remoteHostId) {
if (internalOptions.beforeMutation) await internalOptions.beforeMutation();
assertRuntimeOwnerCurrent();
assertSharedTaskCurrent.admit();
clearPendingCredentialSwitchForSession(sessionId, { wake: false });
+ const previousIntent = agentSwitchPending.get(sessionId);
+ const selectedProviderId = effectiveProviderId === undefined ? currentProviderId : effectiveProviderId;
+ const acknowledgedWindow = confirmedContextWindow ?? (
+ previousIntent?.sameAgentSelection && previousIntent.model === model &&
+ previousIntent.targetAgentKind === dbToMakerAgentKind(runtimeStatus.agentKind) &&
+ previousIntent.providerId === selectedProviderId ? previousIntent.confirmedContextWindow : undefined);
const intent = {
...(internalOptions.runtimeSource ? { runtimeSource: internalOptions.runtimeSource } : {}),
...(internalOptions.configStaged === true ? { configStaged: true } : {}),
@@ -20369,6 +20436,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
providerId: effectiveProviderId === undefined ? currentProviderId : effectiveProviderId,
effort: atomicSelection ? atomicSelection.effort ?? undefined : runtimeStatus.effort ?? undefined,
fastMode: atomicSelection?.fastMode ?? runtimeStatus.fastMode,
+ ...(acknowledgedWindow !== undefined ? { confirmedContextWindow: acknowledgedWindow } : {}),
};
agentSwitchPending.set(sessionId, intent);
agentSwitchDeps.onPendingSwitchChanged?.(sessionId, projectPendingAgentSwitchIntent(intent));
@@ -20708,7 +20776,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// A remote Pi confirmation may name the smaller window verified by the
// previous final get_state. Re-run the catalog-window preflight first;
// only the next final Pi verification may consume that confirmation.
- if (!isDeviceLinkInvoke() && runtimeAgentKind === 'pi') {
+ if (!isDeviceLinkInvoke() && runtimeAgentKind === 'pi' &&
+ !runtimeStatus.orcaRole && !parseOrcaRemoteLead(runtimeStatus.orcaRemoteLead)) {
targetContextWindow = confirmedContextWindow ?? targetContextWindow;
}
const persistedContextTokens =
@@ -20780,7 +20849,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
contextWindow: targetContextWindow!,
recheckTargetPressure: true,
confirmedTargetPressure:
- (internalOptions.source === 'user' && internalOptions.applyingUserSelectionOnSend === true) ||
+ (internalOptions.source === 'user' && internalOptions.applyingUserSelectionOnSend === true &&
+ !runtimeStatus.orcaRole && !parseOrcaRemoteLead(runtimeStatus.orcaRemoteLead)) ||
(!isDeviceLinkInvoke() && confirmedContextWindow === targetContextWindow),
onConfirmationRequired: (contextTokens) => {
confirmationContextTokens = contextTokens;
@@ -21169,7 +21239,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
contextWindow: finalPiWindow,
recheckTargetPressure: true,
confirmedTargetPressure:
- (internalOptions.source === 'user' && internalOptions.applyingUserSelectionOnSend === true) ||
+ (internalOptions.source === 'user' && internalOptions.applyingUserSelectionOnSend === true &&
+ !runtimeStatus.orcaRole && !parseOrcaRemoteLead(runtimeStatus.orcaRemoteLead)) ||
(!isDeviceLinkInvoke() && confirmedContextWindow === finalPiWindow),
onConfirmationRequired: (contextTokens) => {
finalPressureContextTokens = contextTokens;
diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
index df9b369e5f..466c04f53c 100644
--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
@@ -22,7 +22,8 @@
* 下一条消息走既有 lazy-create 路径重试并复用其错误呈现(resume 模式先走
* 上述回落再降级)。
*
- * 边界:远程会话(remoteHostId)与 Orca 协同会话不支持切换(UNSUPPORTED_CAPABILITY);
+ * 边界:远程会话(remoteHostId)仍不支持切换(UNSUPPORTED_CAPABILITY)。Orca Lead/Worker
+ * 复用同一交接与停泊事务,协同身份由 vendorOptions/DB 在重建时恢复。
* turn 进行中登记 pending 推迟到下一条消息发送时刻执行。
*
* 远程 Agent 换电脑(agentDeviceId 变化,null = 任务所在电脑):原生会话记录在原来运行 Agent
@@ -31,7 +32,8 @@
*/
import type { AgentKind } from '@cindy/maker-core';
-import { getDeviceLinkInvokeContext } from '../device-link/invoke-context.js';
+import { getDeviceLinkInvokeContext, isDeviceLinkInvoke } from '../device-link/invoke-context.js';
+import { parseOrcaRemoteLead } from '../../shared/orcaRemoteWorker.js';
import { createSharedTaskSettingGuard } from './sharedTaskSetting.js';
import { MAKER_INVOKE } from './channels.js';
@@ -117,6 +119,8 @@ export interface AgentSwitchSessionRow {
status: string;
remoteHostId: string | null;
orcaRole: string | null;
+ /** Execution-device Worker binding; these tasks have no local orcaRole. */
+ orcaRemoteLead?: string | null;
sdkSessionId: string | null;
source?: string | null;
/** Agent 在哪台电脑运行(null / 缺省 = 任务所在电脑)。 */
@@ -332,7 +336,8 @@ export interface PendingAgentSwitchIntent {
fastMode?: boolean;
/**
* Agent 在另一台电脑运行的任务:点选时按那台的目录确认过的目标上下文窗口。本机目录里没有
- * 那台的模型,发送时据此做「换小窗口前先交接」。本机任务不设。
+ * 那台的模型,发送时据此做「换小窗口前先交接」。本机 Orca 也保留选择时核对的窗口,
+ * 发送时必须与实际目标窗口匹配,不能把 deferred 当作任意窗口的确认。
*/
confirmedContextWindow?: number;
/** 选择同时换 Agent 所在电脑(null = 任务所在电脑);缺省 = 位置不变。 */
@@ -525,6 +530,8 @@ export async function performSessionAgentSwitch(
/** 目标引擎下应生效的 effort / fastMode(renderer 按目标目录与预设解析好带入)。 */
effort?: unknown;
fastMode?: unknown;
+ /** Local picker acknowledgement of this route's checked context window. */
+ confirmedContextWindow?: unknown;
/**
* 选择的 Agent 位置(远程 Agent):undefined = 保持任务当前位置(内部调用与不认识该字段的
* 旧控制端都走这里,不做推断),null = 任务所在电脑,字符串 = 同账号另一台电脑。
@@ -567,6 +574,11 @@ export async function performSessionAgentSwitch(
): Promise<SessionAgentSwitchResult> {
const { sessionId, targetAgentKind, model, providerId, signal } = params;
throwIfAgentSwitchAborted(signal);
+ const confirmedContextWindow = params.confirmedContextWindow;
+ if (confirmedContextWindow !== undefined &&
+ (typeof confirmedContextWindow !== 'number' || !Number.isSafeInteger(confirmedContextWindow) || confirmedContextWindow <= 0)) {
+ throwIpcError('INVALID_PARAMS', 'confirmedContextWindow must be a positive integer');
+ }
if (typeof sessionId !== 'string' || sessionId.length === 0) {
throwIpcError('INVALID_PARAMS', 'sessionId required');
}
@@ -624,17 +636,18 @@ export async function performSessionAgentSwitch(
// SSH 远程会话:agent 进程在远端机器,cc-manager 链路仅覆盖 Claude,v1 不支持切换。
throwIpcError('UNSUPPORTED_CAPABILITY', 'agent switch is not supported for remote sessions');
}
- // 供应商组换电脑:同引擎同模型、只换位置。协同任务只放行这一种(内部 applyNow 调用)。
+ // Orca may switch harness/model, but Agent relocation remains an internal
+ // provider-group operation so the workflow's execution-device contract stays
+ // under the group scheduler.
const providerGroupRelocationOnly =
params.providerGroupRelocation === true &&
params.applyNow === true &&
normalizeDbAgentKind(row.agentKind) === makerToDbAgentKind(targetAgentKind) &&
row.model === model;
- if (row.orcaRole && !providerGroupRelocationOnly) {
- // Orca lead/worker:协同运行时对 agent 形态有独立契约(docs/dev-rules/orca-team-architecture.md),不掺和。
- throwIpcError('UNSUPPORTED_CAPABILITY', 'agent switch is not supported for Orca sessions');
+ if ((row.orcaRole || parseOrcaRemoteLead(row.orcaRemoteLead)) &&
+ params.agentDeviceId !== undefined && !providerGroupRelocationOnly) {
+ throwIpcError('UNSUPPORTED_CAPABILITY', 'agent relocation is not supported for Orca sessions');
}
-
if (params.beforeMutation) await params.beforeMutation();
params.assertSelectionCurrent?.();
@@ -718,6 +731,7 @@ export async function performSessionAgentSwitch(
...(typeof params.effort === 'string' ? { effort: params.effort } : {}),
...(typeof params.fastMode === 'boolean' ? { fastMode: params.fastMode } : {}),
sameAgentSelection: true,
+ ...(confirmedContextWindow !== undefined ? { confirmedContextWindow } : {}),
...(params.runtimeSource ? { runtimeSource: params.runtimeSource } : {}),
...(params.configStaged === true ? { configStaged: true } : {}),
}, params.applyNow === true, params.assertSelectionCurrent, params.beforeMutation);
@@ -1278,6 +1292,13 @@ export function registerMakerSessionAgentSwitchHandler(
options?: unknown,
) => {
const context = getDeviceLinkInvokeContext();
+ const confirmedContextWindow = options && typeof options === 'object' && !Array.isArray(options)
+ ? (options as { confirmedContextWindow?: unknown }).confirmedContextWindow : undefined;
+ // Same trust boundary as SET_MODEL: remote controllers cannot authorize a
+ // destructive local-context rebuild by supplying a confirmation number.
+ if (isDeviceLinkInvoke() && confirmedContextWindow !== undefined) {
+ throwIpcError('PRECONDITION_FAILED', 'remote model-window confirmation is unsupported');
+ }
const agentDeviceId =
options && typeof options === 'object' && !Array.isArray(options) && 'agentDeviceId' in options
? (options as { agentDeviceId?: unknown }).agentDeviceId
@@ -1294,6 +1315,7 @@ export function registerMakerSessionAgentSwitchHandler(
providerId,
effort,
fastMode,
+ ...(confirmedContextWindow !== undefined ? { confirmedContextWindow } : {}),
...(agentDeviceId !== undefined ? { agentDeviceId } : {}),
assertSelectionCurrent: guard.admit,
});
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 0e1c06e3f1..9d48200132 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -7028,7 +7028,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
effort?: string,
fastMode?: boolean,
// 远程 Agent:同时换 Agent 所在电脑(null = 任务所在电脑)。不传 = 位置不变。
- options?: { agentDeviceId?: string | null },
+ options?: { agentDeviceId?: string | null; confirmedContextWindow?: number },
): Promise<{
switched: boolean;
agentKind: 'claude-code' | 'codex' | 'pi';
diff --git a/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts b/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts
index 25dbdacc9a..49528798db 100644
--- a/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts
+++ b/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts
@@ -236,9 +236,10 @@ describe('ChatInput model source switching wiring', () => {
expect(shrinkGate).toContain("typeof contextTokens === 'number'");
expect(shrinkGate).toContain('const hasVerifiedUsage = trustedContextTokens !== undefined;');
expect(zeroUsagePass).toBeGreaterThan(legacyPiGuard);
- expect(shrinkGate).toContain('return true;');
+ expect(shrinkGate).toContain('return acceptedWindow;');
+ expect(shrinkGate).toContain('stagingSameAgentSelection && hasVerifiedTargetWindow && hasVerifiedUsage');
expect(guard).toContain(
- "if (!requireDestructiveConfirmation && verdict.level === 'ok') return true;",
+ "if (!requireDestructiveConfirmation && verdict.level === 'ok') return acceptedWindow;",
);
expect(remoteBlock).toBeLessThan(warningPath);
expect(remoteBlock).toBeLessThan(confirmPath);
diff --git a/apps/desktop/src/renderer/__tests__/orcaModelWindowSelection.test.ts b/apps/desktop/src/renderer/__tests__/orcaModelWindowSelection.test.ts
new file mode 100644
index 0000000000..fac795f169
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/orcaModelWindowSelection.test.ts
@@ -0,0 +1,155 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import ts from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+import { assessModelSwitchContext, MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT,
+ shouldBlockLegacyRemotePiModelWindowSwitch } from '../../shared/modelSwitchAssessment';
+
+// Exercise the production preflight and staging callback together, without mounting
+// the editor or starting native agents. Side effects remain observable at the IPC boundary.
+const source = ts.createSourceFile('ChatInput.tsx', readFileSync(resolve(__dirname,
+ '../components/new-chat/ChatInput.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+const callbacks = new Map<string, string>();
+function visit(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && node.initializer && ts.isCallExpression(node.initializer) &&
+ ['confirmModelSwitchContextGuard', 'performAgentSwitch'].includes(node.name.getText(source))) {
+ callbacks.set(node.name.getText(source), node.initializer.arguments[0].getText(source));
+ }
+ ts.forEachChild(node, visit);
+}
+visit(source);
+
+function setup(options: { agent?: string; role?: string; used?: number; current?: number;
+ target?: number; remote?: boolean; hostGuard?: boolean; displayedAgent?: string } = {}) {
+ const agent = options.agent ?? 'codex';
+ const switchSessionAgent = vi.fn(async () => ({ deferred: true, switched: false }));
+ const release = vi.fn();
+ const finish = vi.fn();
+ const confirmDialog = vi.fn(async () => false);
+ const context = { contextTokens: options.used ?? 240000, contextWindow: options.current ?? 1000000, isRunning: false };
+ const bindings = {
+ sessionId: 's1', sessionOrcaRole: options.role ?? 'worker', settingsLocked: false,
+ runtimeAgentKind: agent, currentModelAgentKind: options.displayedAgent ?? agent,
+ activeModel: 'old-model', effectiveSourceId: 'old-provider', activeEffort: 'high',
+ deviceLinkDeviceId: options.remote ? 'remote' : undefined, remoteHostId: null,
+ currentSessionIdRef: { current: 's1' },
+ agentLocationAware: false, agentDeviceId: null, effectiveAgentDeviceId: null,
+ providers: [], remoteProviders: { providers: [] }, modelMemory: null,
+ ccCaps: { capabilities: {} }, codexCaps: { capabilities: {} },
+ piCaps: { capabilities: { supportsModelWindowSwitchGuard: options.hostGuard !== false } },
+ makerChatStore: { getSnapshot: () => ({ agentStatus: context }), getAgentSwitchIntent: () => null,
+ getAgentSwitchIntentRev: () => 0, noteAgentSwitchIntent: vi.fn() },
+ getSessionDeviceId: () => options.remote ? 'remote' : undefined,
+ hasPendingAgentSendDispatch: () => false, nextAgentSwitchWriteSeq: () => 1, getAgentSwitchWriteSeq: () => 1,
+ beginAgentSwitchOperation: () => finish, reserveAgentSwitchExclusive: () => ({ ready: Promise.resolve(), release }),
+ isSessionScopeCurrent: (a: string, b: string) => a === b,
+ effectiveSourceIdForModel: (_providers: unknown, id: string) => id,
+ resolveProviderModelContextWindow: vi.fn(() => options.target ?? 200000),
+ assessModelSwitchContext, MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT, shouldBlockLegacyRemotePiModelWindowSwitch,
+ confirmDialog, t: (key: string) => key, toast: { error: vi.fn(), warning: vi.fn(), success: vi.fn() },
+ resolveModelEfforts: () => ({ efforts: ['high'], defaultEffort: 'high' }),
+ resolveRequestedEffort: () => 'high', getRememberedEffort: () => undefined, resolveFastSupported: () => false,
+ makerApiFor: () => ({ switchSessionAgent }), makerApiForDevice: () => ({ switchSessionAgent }),
+ resolveAgentSwitchAckAction: () => 'apply-intent', isAgentSwitchEchoConfigConsistent: () => true,
+ syncSessionDraftModelPrefs: vi.fn(), mapIpcErrorToI18nKey: (error: unknown) => { throw error; },
+ };
+ const compiled = ts.transpileModule(`const confirmModelSwitchContextGuard = ${callbacks.get('confirmModelSwitchContextGuard')};
+ return ${callbacks.get('performAgentSwitch')};`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ const pick = new Function(...Object.keys(bindings), compiled)(...Object.values(bindings));
+ return { pick, switchSessionAgent, bindings, confirmDialog, release, finish };
+}
+
+describe('Orca same-Agent window preflight', () => {
+ it.each(['claude-code', 'codex', 'pi'])('%s overflow must be confirmed before staging for either role', async agent => {
+ for (const role of ['lead', 'worker']) {
+ const h = setup({ agent, role });
+ expect(await h.pick(agent, 'small', 'provider')).toBe(false);
+ expect(h.confirmDialog).toHaveBeenCalledOnce();
+ expect(h.switchSessionAgent).not.toHaveBeenCalled();
+ expect(h.bindings.makerChatStore.noteAgentSwitchIntent).not.toHaveBeenCalled();
+ expect(h.bindings.syncSessionDraftModelPrefs).not.toHaveBeenCalled();
+ expect(h.release).toHaveBeenCalledOnce();
+ expect(h.finish).toHaveBeenCalledOnce();
+
+ h.confirmDialog.mockResolvedValue(true);
+ expect(await h.pick(agent, 'small', 'provider')).toBe(true);
+ expect(h.switchSessionAgent).toHaveBeenCalledWith('s1', agent, 'small', 'provider', 'high', false,
+ { confirmedContextWindow: 200000 });
+ }
+ });
+
+ it.each([100000, 150000, 180000])('allows existing local warning semantics at %i tokens', async used => {
+ const h = setup({ used });
+ expect(await h.pick('codex', 'small', 'provider')).toBe(true);
+ expect(h.confirmDialog).not.toHaveBeenCalled();
+ expect(h.bindings.toast.warning).toHaveBeenCalledTimes(used >= 140000 ? 1 : 0);
+ });
+
+ it('does not prompt for same/expanded windows or effort-only changes', async () => {
+ for (const target of [1000000, 2000000]) {
+ const h = setup({ target, used: 1200000 });
+ expect(await h.pick('codex', 'large', 'provider')).toBe(true);
+ expect(h.confirmDialog).not.toHaveBeenCalled();
+ }
+ const h = setup();
+ expect(await h.pick('codex', 'old-model', 'old-provider', { effort: 'high', fastMode: false })).toBe(true);
+ expect(h.confirmDialog).not.toHaveBeenCalled();
+ expect(h.bindings.resolveProviderModelContextWindow).not.toHaveBeenCalled();
+ });
+
+ it('checks a same-id model on a different provider, using the runtime Agent even with a cross-Agent preview', async () => {
+ const h = setup({ displayedAgent: 'pi' });
+ expect(await h.pick('codex', 'old-model', 'small-provider')).toBe(false);
+ expect(h.bindings.resolveProviderModelContextWindow).toHaveBeenCalledWith({
+ providers: [], providerId: 'small-provider', modelId: 'old-model', agentKind: 'codex',
+ });
+ expect(h.switchSessionAgent).not.toHaveBeenCalled();
+ });
+
+ it.each(['claude-code', 'codex', 'pi'])('blocks a pressured device-link %s selection before staging', async agent => {
+ for (const used of [180000, 240000]) {
+ const h = setup({ remote: true, agent, used });
+ expect(await h.pick(agent, 'small', 'provider')).toBe(false);
+ expect(h.confirmDialog).not.toHaveBeenCalled();
+ expect(h.switchSessionAgent).not.toHaveBeenCalled();
+ expect(h.bindings.toast.error).toHaveBeenCalledOnce();
+ }
+ });
+
+ it('retains legacy Pi protection and does not guard a true cross-Agent handoff', async () => {
+ const h = setup({ remote: true, agent: 'pi', hostGuard: false, used: 10000 });
+ expect(await h.pick('pi', 'small', 'provider')).toBe(false);
+ expect(h.switchSessionAgent).not.toHaveBeenCalled();
+ expect(await h.pick('codex', 'small', 'provider')).toBe(true);
+ expect(h.confirmDialog).not.toHaveBeenCalled();
+ });
+
+ it('does not register a choice if the user leaves the session during confirmation', async () => {
+ const h = setup();
+ h.confirmDialog.mockImplementation(async () => { h.bindings.currentSessionIdRef.current = 's2'; return true; });
+ expect(await h.pick('codex', 'small', 'provider')).toBe(false);
+ expect(h.switchSessionAgent).not.toHaveBeenCalled();
+ expect(h.release).toHaveBeenCalledOnce();
+ });
+
+ it('does not turn an unknown target window into acknowledgement', async () => {
+ const h = setup({ target: Number.NaN });
+ expect(await h.pick('codex', 'unknown', 'provider')).toBe(true);
+ expect(h.switchSessionAgent).toHaveBeenCalledWith('s1', 'codex', 'unknown', 'provider', 'high', false);
+ });
+
+ it('rechecks a pending route when selected again, while axis-only edits skip the dialog', async () => {
+ const h = setup();
+ h.bindings.makerChatStore.getAgentSwitchIntent = () => ({ target: 'codex', model: 'old-model', providerId: 'old-provider' }) as never;
+ // The callback holds the same store object; a send rejected for a changed
+ // window must be recoverable by selecting the pending model again.
+ expect(await h.pick('codex', 'old-model', 'old-provider')).toBe(false);
+ h.confirmDialog.mockResolvedValue(true);
+ expect(await h.pick('codex', 'old-model', 'old-provider')).toBe(true);
+ expect(h.switchSessionAgent).toHaveBeenLastCalledWith('s1', 'codex', 'old-model', 'old-provider', 'high', false,
+ { confirmedContextWindow: 200000 });
+ h.confirmDialog.mockClear();
+ expect(await h.pick('codex', 'old-model', 'old-provider', { effort: 'high', axesOnly: true })).toBe(true);
+ expect(h.confirmDialog).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/remoteAgentRelocationWiring.test.ts b/apps/desktop/src/renderer/__tests__/remoteAgentRelocationWiring.test.ts
index e1c1e3d3fb..29150ada79 100644
--- a/apps/desktop/src/renderer/__tests__/remoteAgentRelocationWiring.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteAgentRelocationWiring.test.ts
@@ -63,7 +63,14 @@ describe('ChatInput:换位置进切换事务', () => {
'overrides?.agentDeviceId !== undefined ? overrides.agentDeviceId : pendingAgentDeviceId;',
);
expect(chatInputSource).toContain('requestedAgentDeviceId !== agentDeviceId');
- expect(chatInputSource).toContain('{ agentDeviceId: relocateTo },');
+ const start = chatInputSource.indexOf('const switchOptions = {');
+ expect(start).toBeGreaterThan(0);
+ const options = chatInputSource.slice(start, chatInputSource.indexOf('};', start));
+ expect(options).toContain('...(relocateTo !== undefined ? { agentDeviceId: relocateTo } : {})');
+ expect(options).toContain('!deviceLinkDeviceId && confirmedContextWindow !== undefined');
+ const invoke = chatInputSource.indexOf('await switchApi.switchSessionAgent(', start);
+ expect(invoke).toBeGreaterThan(start);
+ expect(chatInputSource.slice(invoke, chatInputSource.indexOf(')', invoke))).toContain('switchOptions,');
});
it('回声匹配把位置算进意图;登记时写入位置;换电脑不写本机新建任务记忆', () => {
@@ -84,7 +91,7 @@ describe('ChatInput:换位置进切换事务', () => {
it('只对本机任务、或支持远程 Agent 的被控端任务开放,且要能走切换事务', () => {
expect(chatInputSource).toContain(
- 'if (!sessionId || !agentLocationAware || remoteHostId || !sessionEngineFilter) return undefined;',
+ 'if (!sessionId || !agentLocationAware || remoteHostId || !sessionEngineFilter ||\n sessionOrcaRole !== null || sessionOrcaRemoteWorker) return undefined;',
);
expect(chatInputSource).toContain('agentDeviceId: selection.agentDevice?.deviceId ?? null,');
});
diff --git a/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts b/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts
index e099c16dad..68fef629e8 100644
--- a/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sessionAgentSwitchRemoteRouting.test.ts
@@ -10,6 +10,7 @@
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
+import ts from 'typescript';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { Session } from '@/lib/ccAgent.types';
@@ -908,9 +909,35 @@ describe('ChatInput 的入口门控与调用路由', () => {
expect(body).toContain('co.fastMode = !!row.fastMode;');
});
- it('Orca 与角色未加载会话都 fail-closed:只有完整元数据确认非协同后开放入口', () => {
- expect(source).toContain('sessionOrcaRole === null &&');
- // 会话视图必须保留 undefined 未知态,不能在完整 session 回流前冒充「非协同」。
+ it('Orca 会话复用切换入口,角色未加载仍保留未知态', () => {
+ expect(source).not.toContain('sessionOrcaRole === null &&');
+ const expression = source.match(/const sessionAgentSwitchSupported =\s*([\s\S]*?);/)?.[1];
+ expect(expression).toBeDefined();
+ const supported = new Function('sessionOrcaRole', 'runtimeAgentKind', 'deviceLinkDeviceId',
+ 'ccSupportsSessionAgentSwitch', 'codexSupportsSessionAgentSwitch', `return ${expression};`);
+ for (const role of [null, 'lead', 'worker']) {
+ expect(supported(role, 'codex', null, false, false)).toBe(true);
+ expect(supported(role, undefined, null, true, true)).toBe(false);
+ expect(supported(role, 'codex', 'host', false, false)).toBe(false);
+ expect(supported(role, 'codex', 'host', false, true)).toBe(true);
+ }
+ expect(supported(undefined, 'codex', null, true, true)).toBe(false);
+ const remoteOptions = source.slice(source.indexOf('const sessionRemoteAgentOptions ='),
+ source.indexOf('// composer pill 尾部引擎小标'));
+ expect(remoteOptions).toContain('sessionOrcaRole !== null || sessionOrcaRemoteWorker) return undefined;');
+ expect(remoteOptions).toContain(' sessionOrcaRole,');
+ expect(remoteOptions).toContain(' sessionOrcaRemoteWorker,');
+ const relocationGuard = remoteOptions.match(/if \(([\s\S]*?)\) return undefined;/)?.[1];
+ expect(relocationGuard).toBeDefined();
+ const hidden = new Function('sessionOrcaRole', 'sessionOrcaRemoteWorker',
+ `const sessionId = 's1', agentLocationAware = true, remoteHostId = null, sessionEngineFilter = {};
+ return !!(${relocationGuard});`);
+ expect(hidden(null, false)).toBe(false);
+ for (const role of [null, 'lead', 'worker', undefined]) {
+ expect(hidden(role, true)).toBe(true);
+ }
+ expect(hidden(undefined, false)).toBe(true);
+ // 会话视图必须保留 undefined 未知态,避免在完整 session 回流前冒充具体身份。
const viewSource = readFileSync(
resolve(process.cwd(), 'src/renderer/features/cc-agent/CCAgentSessionView.tsx'),
'utf8',
@@ -918,6 +945,7 @@ describe('ChatInput 的入口门控与调用路由', () => {
expect(viewSource).toContain(
'sessionOrcaRole={session ? (session.orcaRole ?? null) : undefined}',
);
+ expect(viewSource).toContain('sessionOrcaRemoteWorker={!!session?.orcaRemoteLead}');
});
it('本地与远程会话打开时都读回 main 权威意图,并经新鲜度守卫过滤过期响应', () => {
@@ -979,10 +1007,11 @@ describe('ChatInput 的入口门控与调用路由', () => {
'const exclusiveTurn = reserveAgentSwitchExclusive(sourceSessionId);',
);
const invoke = source.indexOf(
- // 换电脑时多带一个位置参数,两种调用形态共用同一个 result。
- 'const result = relocateTo !== undefined',
+ // 带可选参数与不带参数的调用都必须在同一串行位置内完成。
+ 'await switchApi.switchSessionAgent(',
reservation,
);
+ const invokeWithoutOptions = source.indexOf('await switchApi.switchSessionAgent(', invoke + 1);
const scopeGuard = source.indexOf(
'if (!isSessionScopeCurrent(sourceSessionId, currentSessionIdRef.current)) return false;',
invoke,
@@ -992,7 +1021,8 @@ describe('ChatInput 的入口门控与调用路由', () => {
const release = source.indexOf('exclusiveTurn.release();', reselect);
expect(reservation).toBeGreaterThanOrEqual(0);
expect(invoke).toBeGreaterThan(reservation);
- expect(scopeGuard).toBeGreaterThan(invoke);
+ expect(invokeWithoutOptions).toBeGreaterThan(invoke);
+ expect(scopeGuard).toBeGreaterThan(invokeWithoutOptions);
expect(reselect).toBeGreaterThan(scopeGuard);
expect(staleGuard).toBeGreaterThan(reselect);
expect(release).toBeGreaterThan(reselect);
@@ -1116,6 +1146,36 @@ describe('ChatInput 的入口门控与调用路由', () => {
);
});
+ it.each(['lead', 'worker'])('Desktop Orca %s routes same-Agent model and provider picks through the switch intent', async sessionOrcaRole => {
+ const parsed = ts.createSourceFile('ChatInput.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+ const callbacks = new Map<string, string>();
+ function visit(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && node.initializer && ts.isCallExpression(node.initializer)
+ && ['performModelChange', 'performProviderChange'].includes(node.name.getText(parsed))) {
+ callbacks.set(node.name.getText(parsed), node.initializer.arguments[0].getText(parsed));
+ }
+ ts.forEachChild(node, visit);
+ }
+ visit(parsed);
+ const switchAgent = vi.fn(async () => true);
+ const bindings = { sessionOrcaRole, settingsLocked: false, sessionId: 's1',
+ sessionAgentSwitchSupported: true, remoteHostId: null, runtimeAgentKind: 'codex',
+ makerChatStore: { getAgentSwitchIntent: () => null }, performAgentSwitch: switchAgent,
+ effectiveSourceId: 'provider-old', activeModel: 'model-old' };
+ function callback(name: string) {
+ expect(callbacks.has(name)).toBe(true);
+ const compiled = ts.transpileModule(`return ${callbacks.get(name)};`,
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ return new Function(...Object.keys(bindings), compiled)(...Object.values(bindings));
+ }
+ expect(await callback('performModelChange')('model-new')).toBe(true);
+ expect(switchAgent).toHaveBeenLastCalledWith('codex', 'model-new', 'provider-old');
+ expect(await callback('performProviderChange')('provider-new', 'model-new', 'high', undefined, true)).toBe(true);
+ expect(switchAgent).toHaveBeenLastCalledWith('codex', 'model-new', 'provider-new', { effort: 'high', fastMode: true });
+ switchAgent.mockResolvedValue(false);
+ expect(await callback('performModelChange')('rejected-model')).toBe(false);
+ });
+
it('await 返回后做会话作用域校验:旧会话响应不得借最新 ref 写进当前会话', () => {
// `return false` 而不是裸 return:见下一条 —— 这是「没把选择落到会话上」的出口之一。
expect(source).toContain(
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index d48b1c1515..18eadea757 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -522,12 +522,11 @@ interface ChatInputProps {
runtimePending?: SessionRuntimePendingProjection | null;
/**
* 会话的 Orca 角色(lead / worker;null = 已确认非协同;undefined = 元数据未加载)。
- * 协同运行时对 agent 形态有独立
- * 契约(docs/dev-rules/orca-team-architecture.md),被控端的 session-agent-switch handler
- * 对任何带 orcaRole 的会话一律拒 UNSUPPORTED_CAPABILITY —— 入口据此隐藏,不给用户
- * 一个点了必失败的控件(与手机端 supportsMobileSessionAgentSwitch 同口径)。
+ * Orca Lead/Worker 复用统一的延迟交接切换事务;该字段仍用于协同面板与身份展示。
*/
sessionOrcaRole?: string | null;
+ /** Execution-device Worker binding, independent of the local Orca role. */
+ sessionOrcaRemoteWorker?: boolean;
/** Initial workingDir from session data. */
initialWorkingDir?: string | null;
/**
@@ -1182,6 +1181,7 @@ export function ChatInput({
runtimeEffective,
runtimePending,
sessionOrcaRole,
+ sessionOrcaRemoteWorker,
initialWorkingDir,
remoteHostId,
deviceLinkDeviceId: _deviceLinkDeviceId,
@@ -1867,8 +1867,7 @@ export function ChatInput({
// 一个会随机吞掉模型重选的入口。本机会话恒可用——main 与 renderer 同版本,不能因
// capabilities 还没加载完而闪掉入口。
// SSH 远程(remoteHostId)是另一套引擎生命周期,继续不支持,由调用点单独排除。
- // Orca 会话(lead / worker)同样排除:被控端 handler 对带 orcaRole 的会话一律拒
- // UNSUPPORTED_CAPABILITY。角色未加载(undefined)也 fail-closed,避免冷启动短暂露出入口。
+ // Orca 可原地切换 Agent;角色未加载(undefined)仍 fail-closed,避免冷启动短暂露出入口。
// 切换事务与 SET_MODEL 都由**任务所在的被控电脑**执行,这两个能力位按它判定,不跟着模型目录
// 走:Agent 在第三台电脑(目录读那台)且那台离线时,仍要能在这里把 Agent 改回被控电脑。
// 目录本就在被控电脑时与上面同一份缓存;本机会话不读(下面 !deviceLinkDeviceId 直接放行)。
@@ -1892,8 +1891,11 @@ export function ChatInput({
const remoteAtomicModelSelectionSupported =
hostCcCaps.capabilities?.supportsSessionAgentSwitchCas === true ||
hostCodexCaps.capabilities?.supportsSessionAgentSwitchCas === true;
+ // Orca Lead/Worker keeps its workflow identity in the session row and vendor
+ // options; it can therefore use the same deferred handoff transaction as a
+ // normal session. Remote sessions remain gated by their host capabilities.
const sessionAgentSwitchSupported =
- sessionOrcaRole === null &&
+ sessionOrcaRole !== undefined && runtimeAgentKind != null &&
(!deviceLinkDeviceId || ccSupportsSessionAgentSwitch || codexSupportsSessionAgentSwitch);
// 切换写入的串行链与写序号都按 session 存在**模块级**协调层(agentSwitchCoordinator),
@@ -6432,6 +6434,7 @@ export function ChatInput({
(await performAgentSwitchRef.current(intent.target, intent.model, intent.providerId, {
fastMode: enabled,
effort: intent.effort as Effort | undefined,
+ axesOnly: true,
})) !== false
);
}
@@ -6483,6 +6486,7 @@ export function ChatInput({
verifiedTargetContextWindow?: number,
verifiedContextTokens?: number,
requireDestructiveConfirmation = false,
+ stagingSameAgentSelection = false,
): Promise<boolean | number> => {
if (!sessionId) return true;
// Main owns SSH Codex window protection and deferred application. A new/failed
@@ -6504,30 +6508,32 @@ export function ChatInput({
?.supportsModelWindowSwitchGuard === true;
if (
!requireDestructiveConfirmation &&
+ !stagingSameAgentSelection &&
remoteDeviceId &&
runtimeAgentKind === 'pi' &&
remotePiWindowGuardSupported
) {
return true;
}
+ const targetAgentKind = stagingSameAgentSelection ? runtimeAgentKind : currentModelAgentKind;
const targetRouteProviderId =
- targetProviderId !== undefined && currentModelAgentKind
+ targetProviderId !== undefined && targetAgentKind
? effectiveSourceIdForModel(
providers,
targetProviderId,
newModelId,
- currentModelAgentKind,
+ targetAgentKind,
)
: null;
const targetContextWindow =
verifiedTargetContextWindow ??
(targetProviderId !== undefined
- ? targetRouteProviderId && currentModelAgentKind
+ ? targetRouteProviderId && targetAgentKind
? resolveProviderModelContextWindow({
providers,
providerId: targetRouteProviderId,
modelId: newModelId,
- agentKind: currentModelAgentKind,
+ agentKind: targetAgentKind,
})
: undefined
: getModelById(newModelId, remoteDeviceId)?.contextWindow);
@@ -6544,6 +6550,8 @@ export function ChatInput({
? contextTokens
: undefined;
const hasVerifiedUsage = trustedContextTokens !== undefined;
+ const acceptedWindow = stagingSameAgentSelection && hasVerifiedTargetWindow && hasVerifiedUsage
+ ? targetContextWindow! : true;
if (requireDestructiveConfirmation && (!hasVerifiedTargetWindow || !hasVerifiedUsage)) {
return false;
}
@@ -6566,12 +6574,12 @@ export function ChatInput({
hasVerifiedWindows &&
targetContextWindow >= currentContextWindow
) {
- return true;
+ return acceptedWindow;
}
// Other SSH harnesses retain their existing admission until adapted separately.
if (remoteHostId && (!hasVerifiedWindows || !hasVerifiedUsage)) return false;
if (!requireDestructiveConfirmation && (!trustedContextTokens || trustedContextTokens <= 0)) {
- return true;
+ return acceptedWindow;
}
const contextTokensForAssessment = trustedContextTokens ?? 0;
const verdict = assessModelSwitchContext({
@@ -6580,7 +6588,7 @@ export function ChatInput({
// 切窗安全线独立于各 harness 的日常 auto-compaction 设置。
autoCompactThresholdPct: MODEL_WINDOW_SWITCH_FORCE_REBUILD_PCT,
});
- if (!requireDestructiveConfirmation && verdict.level === 'ok') return true;
+ if (!requireDestructiveConfirmation && verdict.level === 'ok') return acceptedWindow;
const fmtTokens = (n: number): string =>
n >= 1_000_000
? `${(n / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`
@@ -6607,7 +6615,7 @@ export function ChatInput({
toast.warning(t('newChat.chatInput.modelSwitchContextGuard.warnToast', vars), {
duration: 4000,
});
- return true;
+ return acceptedWindow;
}
// Local overflow (≥100%): host performs a bounded handoff before switching.
const accepted = await confirmDialog({
@@ -6726,6 +6734,8 @@ export function ChatInput({
overrides?: {
effort?: Effort;
fastMode?: boolean;
+ /** Editing only axes keeps the existing route's window acknowledgement. */
+ axesOnly?: boolean;
/**
* 远程 Agent:这一行属于哪台电脑的目录(null = 本机)。与任务当前所在电脑不同 = 连 Agent
* 的运行位置一起换。不传 = 沿用已登记的换位置意图,没有就是位置不变。
@@ -6755,6 +6765,21 @@ export function ChatInput({
const exclusiveTurn = reserveAgentSwitchExclusive(sourceSessionId);
try {
await exclusiveTurn.ready;
+ let confirmedContextWindow: number | undefined;
+ // Same-Agent Orca picks stage instead of calling SET_MODEL. Keep its window
+ // preflight before registration, including same-id provider changes. Effort/
+ // Fast edits of an already selected route do not need another confirmation.
+ if (sessionOrcaRole && targetAgentKind === runtimeAgentKind && !overrides?.axesOnly &&
+ (targetAgentKind !== currentModelAgentKind || newModelId !== activeModel ||
+ providerId !== effectiveSourceId || makerChatStore.getAgentSwitchIntent(sourceSessionId))) {
+ const proceed = await confirmModelSwitchContextGuard(
+ newModelId, deviceLinkDeviceId ?? getSessionDeviceId(sourceSessionId),
+ providerId, undefined, undefined, false, true,
+ );
+ if (!proceed || !isSessionScopeCurrent(sourceSessionId, currentSessionIdRef.current) ||
+ writeSeq !== getAgentSwitchWriteSeq(sourceSessionId)) return false;
+ if (typeof proceed === 'number') confirmedContextWindow = proceed;
+ }
// 远程 Agent:这次选择落在哪台电脑。左侧栏点了另一台电脑的目录就用那台;否则沿用已登记
// 的换位置意图 —— 意图期内在同一份目录里改选,不能被当成原来那台的选择。与任务当前
// 所在电脑相同 = 位置不变,不带给 main(旧被控端 / 内部调用同样不带)。被控电脑上的任务
@@ -6832,7 +6857,11 @@ export function ChatInput({
const switchApi = deviceLinkDeviceId
? makerApiForDevice(deviceLinkDeviceId)
: makerApiFor(sourceSessionId);
- const result = relocateTo !== undefined
+ const switchOptions = {
+ ...(relocateTo !== undefined ? { agentDeviceId: relocateTo } : {}),
+ ...(!deviceLinkDeviceId && confirmedContextWindow !== undefined ? { confirmedContextWindow } : {}),
+ };
+ const result = Object.keys(switchOptions).length > 0
? await switchApi.switchSessionAgent(
sourceSessionId,
targetAgentKind,
@@ -6840,7 +6869,7 @@ export function ChatInput({
providerId,
newEffort,
targetFast,
- { agentDeviceId: relocateTo },
+ switchOptions,
)
: await switchApi.switchSessionAgent(
sourceSessionId,
@@ -7054,6 +7083,12 @@ export function ChatInput({
[
sessionId,
settingsLocked,
+ sessionOrcaRole,
+ runtimeAgentKind,
+ currentModelAgentKind,
+ activeModel,
+ effectiveSourceId,
+ confirmModelSwitchContextGuard,
activeEffort,
resolveModelEfforts,
getRememberedEffort,
@@ -7216,8 +7251,9 @@ export function ChatInput({
[agentDeviceId, intentAgentDeviceId, deviceLinkDeviceId, deviceLinkDeviceName, confirmDialog, t],
);
const sessionRemoteAgentOptions = useMemo<RemoteAgentSelectorOptions | undefined>(() => {
- // 本机任务,或被控电脑支持远程 Agent 的被控端任务;且会话内能走切换事务(SSH / 协同任务不行)。
- if (!sessionId || !agentLocationAware || remoteHostId || !sessionEngineFilter) return undefined;
+ // 本机或能力已确认的被控端任务可换电脑;SSH / Orca 不开放位置选择。
+ if (!sessionId || !agentLocationAware || remoteHostId || !sessionEngineFilter ||
+ sessionOrcaRole !== null || sessionOrcaRemoteWorker) return undefined;
if (!remoteAgentDevices || (remoteAgentDevices.length === 0 && !effectiveAgentDeviceId)) {
return undefined;
}
@@ -7253,6 +7289,8 @@ export function ChatInput({
taskComputerModelMemory,
remoteHostId,
sessionEngineFilter,
+ sessionOrcaRole,
+ sessionOrcaRemoteWorker,
remoteAgentDevices,
effectiveAgentDeviceId,
intentAgentDeviceId,
@@ -7284,8 +7322,8 @@ export function ChatInput({
? (sessionFavoriteAnchor?.uid ?? null)
: selectedFavoriteUid;
- // 会话内拿不到跨引擎切换事务(SSH 远程会话 / 被控端不支持 session-agent-switch /
- // Orca 会话)时,统一面板**不能**摆出其它引擎的行:useUnifiedRowActions.selectRow 只有在
+ // 会话内拿不到跨引擎切换事务(SSH 远程会话 / 被控端不支持 session-agent-switch)
+ // 时,统一面板**不能**摆出其它引擎的行:useUnifiedRowActions.selectRow 只有在
// 传了 sessionEngineFilter 时才把跨引擎行改道给切换事务,没有它时跨引擎行会被当普通选中
// 交给单引擎链路(onProviderChange 只换 model / provider),等于把另一个引擎的模型
// 直接塞进当前会话。与旧面板同待遇:这类会话把联合列表锁定在当前引擎(旧版本来就是
@@ -7293,11 +7331,8 @@ export function ChatInput({
//
// 锁定用的必须是**已确认**的会话引擎,不能用 vendorKey 派生的 agentKind:
// CCAgentSessionView 的 vendorKey 走 dbToMakerAgentKind(session?.agentKind),元数据到达
- // 前回退成 'cc'。而 sessionOrcaRole 在同一窗口里是 undefined(≠ null)→
- // sessionAgentSwitchSupported=false → 没有 sessionEngineFilter → 走到这条锁定分支。
- // 两件事撞在一起的后果不是"闪一下":Codex 会话会摆出一张**纯 Claude** 的列表,而且此时
- // 没有跨引擎兜底,点任意一行都会把 Claude 模型经 onProviderChange 塞进 Codex 会话
- // (bug4)。所以身份未确认时不锁 —— 回落旧面板一帧,等 runtimeAgentKind 落地再进统一面板。
+ // 前回退成 'cc'。身份未确认时不锁,先保留兼容列表,等 runtimeAgentKind 落地再进入
+ // 统一面板的当前引擎路由。
const sessionEngineConfirmed = !sessionId || runtimeAgentKind != null;
const inSessionEngineLocked = Boolean(sessionId) && !sessionEngineFilter;
const lockedSessionAgentKind =
@@ -7724,6 +7759,7 @@ export function ChatInput({
(await performAgentSwitch(intent.target, intent.model, intent.providerId, {
effort: newEffort,
fastMode: intent.fastMode,
+ axesOnly: true,
})) !== false
);
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 200a8c544a..92f421ee26 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -5649,9 +5649,9 @@ function CCAgentSessionContent({
runtimeAgentKind={session ? dbToMakerAgentKind(session.agentKind) : null}
runtimeEffective={session?.runtimeEffective}
runtimePending={session?.runtimePending}
- // 协同会话不参与跨引擎切换;session 未加载时保留 undefined 未知态,
- // 仅在完整元数据确认非 Orca 后传 null 开放入口。
+ // session 未加载时保留 undefined 未知态;Orca 原地切换与换电脑分别门控。
sessionOrcaRole={session ? (session.orcaRole ?? null) : undefined}
+ sessionOrcaRemoteWorker={!!session?.orcaRemoteLead}
initialWorkingDir={session?.workingDir}
remoteHostId={session?.remoteHostId ?? null}
deviceLinkDeviceId={rightSidebarDeviceLinkDeviceId}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 7969365138..4f0615e77a 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -6333,7 +6333,7 @@ interface ElectronAPI {
effort?: string,
fastMode?: boolean,
/** 远程 Agent:同时换 Agent 所在电脑(null = 任务所在电脑)。不传 = 位置不变。 */
- options?: { agentDeviceId?: string | null },
+ options?: { agentDeviceId?: string | null; confirmedContextWindow?: number },
) => Promise<{
switched: boolean;
agentKind: 'claude-code' | 'codex' | 'pi';
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index ca88e9a0f3..4bccdf1c1d 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -379,6 +379,7 @@ import {
} from '@/session/sessionAgentSwitch';
import { formatProviderAccountLabel, resolveSessionUsageAccount } from '@/session/sessionUsageAccount';
import { useRemoteAgentCatalogs } from '@/session/useRemoteAgentCatalogs';
+import { isProviderShareAgentDeviceId } from '@/session/providerShareAgentDevice';
import { useSessionProviderGroup } from '@/session/useSessionProviderGroup';
import {
drainComposerAnnotationSubmissions,
@@ -2638,18 +2639,24 @@ function SessionScreenContent() {
const composerSwitchesAgent = composerDisplayAgentKind !== sessionAgentKind;
const sessionAgentSwitchSupported = !!currentSession
&& supportsMobileSessionAgentSwitch(currentSession, capabilities);
+ // Orca 的同引擎模型选择也只登记意图,保留当前执行单元直到下一次发送。
+ const orcaModelSelectionUsesIntent = !!currentSession?.orcaRole && sessionAgentSwitchSupported;
// 远程 Agent:模型列表在被控电脑自己的供应商之外,另列同账号其他电脑上开放了远程调用的供应商
// (与桌面同一套,2026-10-07 产品裁决)。选另一台电脑的模型 = 把 Agent 挪过去,先二次确认;
- // 同一台电脑内换模型直接切。共享任务访客不能换电脑(被控端拒绝),SSH / Orca 任务不支持切换;
+ // 同一台电脑内换模型直接切。共享任务访客与 Orca 成员不能换电脑,SSH 不支持切换;
// 旧被控端不投影 agentDeviceId 字段、也不认换位置参数,这些情况维持原有调用与展示。
const agentLocationMovable = sessionAgentSwitchSupported
&& !isSharedTaskPeer(deviceId)
&& !!currentSession
+ && !currentSession.orcaRole
+ && !currentSession.orcaRemoteLead
&& Object.prototype.hasOwnProperty.call(currentSession, 'agentDeviceId');
/** Agent 现在所在的电脑(null = 被控电脑)。 */
const currentAgentDeviceId = sessionAgentRunsOnOtherComputer(currentSession)
? currentSession!.agentDeviceId!
: null;
+ // Orca 只禁换位置;Agent 已在其他电脑时,仍保留那台电脑的目录供原地选模。
+ const orcaRemoteAgentDeviceId = currentSession?.orcaRole ? currentAgentDeviceId : null;
/** 下一条消息时 Agent 所在的电脑(挂着换位置的意图就按意图)。 */
const nextAgentDeviceId = effectiveAgentDeviceId(currentSession, agentSwitchIntent);
const remoteAgentKeepDeviceIds = useMemo(
@@ -2666,6 +2673,25 @@ function SessionScreenContent() {
keepDeviceIds: remoteAgentKeepDeviceIds,
keepOnly: !(agentLocationMovable && modelSheetOpen),
});
+ const modelSheetRemoteCatalogs = useMemo(
+ () => orcaRemoteAgentDeviceId
+ ? remoteAgentCatalogs.filter((catalog) => catalog.deviceId === orcaRemoteAgentDeviceId)
+ : remoteAgentCatalogs,
+ [orcaRemoteAgentDeviceId, remoteAgentCatalogs],
+ );
+ // `share:<id>` is a virtual catalog owned by the controlled computer; it is
+ // not a device-link peer that the phone can open directly.
+ const modelCapabilitiesDeviceId = orcaRemoteAgentDeviceId
+ && !isProviderShareAgentDeviceId(orcaRemoteAgentDeviceId)
+ ? orcaRemoteAgentDeviceId
+ : deviceId;
+ const loadComposerAgentCapabilities = useCallback(
+ (agent: MobileSessionAgentKind, catalogDeviceId: string | null = orcaRemoteAgentDeviceId) =>
+ (catalogDeviceId && !isProviderShareAgentDeviceId(catalogDeviceId)
+ ? executionMakerForDevice(catalogDeviceId)
+ : maker).getCapabilities(agent),
+ [executionMakerForDevice, maker, orcaRemoteAgentDeviceId],
+ );
// 供应商组(provider-groups.md §10):这个任务此刻归哪个组,选择器每次打开问一次被控电脑。归组的任务在组那一项里
// 选模型 = 留在此刻运行的那台只换模型(不弹换电脑确认);挂着换电脑的意图时下一条消息就不在原处,不按组显示。
const currentProviderId = currentSession?.providerId ?? null;
@@ -3568,9 +3594,9 @@ function SessionScreenContent() {
setAlternateCapabilitiesAgentKind(targetAgentKind);
// 跨 Agent 面板打开前就静默预取另一侧能力;缓存命中时当帧可浏览,miss 才显示
// loading。与当前 Agent 共用同一代际缓存,登出 / device revision 后不会复活旧快照。
- const cacheKey = buildAgentCapabilitiesCacheKey(deviceId, targetAgentKind);
- const generation = getAgentCapabilitiesGeneration(deviceId);
- const unsubscribe = subscribeAgentCapabilities(deviceId, targetAgentKind, (next) => {
+ const cacheKey = buildAgentCapabilitiesCacheKey(modelCapabilitiesDeviceId, targetAgentKind);
+ const generation = getAgentCapabilitiesGeneration(modelCapabilitiesDeviceId);
+ const unsubscribe = subscribeAgentCapabilities(modelCapabilitiesDeviceId, targetAgentKind, (next) => {
if (cancelled) return;
setAlternateCapabilitiesAgentKind(targetAgentKind);
setAlternateCapabilities(next);
@@ -3587,30 +3613,30 @@ function SessionScreenContent() {
}
setAlternateCapabilitiesError(null);
void withTransientRemoteRetry(async () => {
- await openLink(deviceId);
- return maker.getCapabilities(targetAgentKind);
+ await openLink(modelCapabilitiesDeviceId);
+ return loadComposerAgentCapabilities(targetAgentKind);
})
.then((result) => {
if (alternateCapabilitiesLoadSeqRef.current !== seq) return;
const normalized = normalizeMobileAgentCapabilities(result);
if (normalized) {
- commitAgentCapabilities(deviceId, targetAgentKind, generation, normalized);
+ commitAgentCapabilities(modelCapabilitiesDeviceId, targetAgentKind, generation, normalized);
} else {
- if (!isAgentCapabilitiesGenerationCurrent(deviceId, generation)) return;
+ if (!isAgentCapabilitiesGenerationCurrent(modelCapabilitiesDeviceId, generation)) return;
if (!cached) setAlternateCapabilities(null);
setAlternateCapabilitiesError(t('session.common.capabilitiesUnsupported'));
}
})
.catch((err) => {
if (alternateCapabilitiesLoadSeqRef.current !== seq) return;
- if (!isAgentCapabilitiesGenerationCurrent(deviceId, generation)) return;
+ if (!isAgentCapabilitiesGenerationCurrent(modelCapabilitiesDeviceId, generation)) return;
if (!cached) setAlternateCapabilities(null);
setAlternateCapabilitiesError(formatRemoteError(err));
})
.finally(() => {
if (
alternateCapabilitiesLoadSeqRef.current === seq
- && isAgentCapabilitiesGenerationCurrent(deviceId, generation)
+ && isAgentCapabilitiesGenerationCurrent(modelCapabilitiesDeviceId, generation)
) setAlternateCapabilitiesLoading(false);
});
return () => {
@@ -3626,6 +3652,8 @@ function SessionScreenContent() {
openLink,
sessionAgentKind,
sessionAgentSwitchSupported,
+ modelCapabilitiesDeviceId,
+ loadComposerAgentCapabilities,
]);
useEffect(() => {
@@ -8339,6 +8367,34 @@ function SessionScreenContent() {
]);
}, [currentSession?.contextTokens, t]);
+ // Staging cannot rely on SET_MODEL reporting a window error: the actual switch
+ // runs on a later send. Reject a known pressured shrink before writing intent,
+ // and retain the legacy-host guard for unknown windows and Pi.
+ const canStageOrcaModelSelection = useCallback((
+ targetAgentKind: MobileSessionAgentKind,
+ targetContextWindow: number | undefined,
+ hostGuardSupported: boolean,
+ ): boolean => {
+ if (!orcaModelSelectionUsesIntent || targetAgentKind !== sessionAgentKind) return true;
+ const contextTokens = currentSession?.contextTokens;
+ const currentContextWindow = currentSession?.contextWindow;
+ const pressuredShrink =
+ typeof contextTokens === 'number' && Number.isFinite(contextTokens) &&
+ typeof targetContextWindow === 'number' && Number.isFinite(targetContextWindow) &&
+ targetContextWindow > 0 && contextTokens / targetContextWindow >= 0.9 &&
+ !(typeof currentContextWindow === 'number' && Number.isFinite(currentContextWindow) &&
+ currentContextWindow > 0 && targetContextWindow >= currentContextWindow);
+ if (pressuredShrink || shouldBlockLegacyRemoteModelWindowSwitch({
+ hostGuardSupported, agentKind: targetAgentKind, contextTokens,
+ currentContextWindow, targetContextWindow,
+ })) {
+ showRemoteModelWindowUnsupported(targetContextWindow);
+ return false;
+ }
+ return true;
+ }, [orcaModelSelectionUsesIntent, sessionAgentKind, currentSession?.contextTokens,
+ currentSession?.contextWindow, showRemoteModelWindowUnsupported]);
+
const setComposerModel = useCallback(async (args: {
model: string;
providerId?: string;
@@ -8412,7 +8468,9 @@ function SessionScreenContent() {
hostName: controlledComputerName,
});
if (!location) return;
- if (modelSheetAgentKind !== sessionAgentKind || location.agentDeviceId !== undefined) {
+ if (orcaModelSelectionUsesIntent || modelSheetAgentKind !== sessionAgentKind || location.agentDeviceId !== undefined) {
+ if (!canStageOrcaModelSelection(modelSheetAgentKind, row.model.contextWindow,
+ modelSheetCapabilities?.supportsModelWindowSwitchGuard === true)) return;
await writeSessionAgentSwitchIntent({
targetAgentKind: modelSheetAgentKind,
model: next.model,
@@ -8461,6 +8519,8 @@ function SessionScreenContent() {
modelSheetAgentKind,
modelSheetCapabilities,
modelSheetSelection,
+ orcaModelSelectionUsesIntent,
+ canStageOrcaModelSelection,
remoteAgentDeviceName,
runControlAction,
sessionAgentKind,
@@ -8482,7 +8542,8 @@ function SessionScreenContent() {
: composerDeviceProviders.providers;
const capability = resolveAgentCapability(catalogProviders, config.providerId, config.modelId, config.agent);
if (!capability) return false;
- const targetCapabilities = normalizeMobileAgentCapabilities(await maker.getCapabilities(config.agent));
+ const targetCapabilities = normalizeMobileAgentCapabilities(
+ await loadComposerAgentCapabilities(config.agent, catalogDeviceId));
if (!targetCapabilities || deviceIdRef.current !== deviceId) return false;
if (config.fast && (!capability.supportsFastMode || !targetCapabilities.hasFastMode)) return false;
// 与任务当前所在电脑不同 = 连 Agent 的运行位置一起换(先确认,下一条消息生效);
@@ -8506,8 +8567,10 @@ function SessionScreenContent() {
if (applied) setModelSheetAgentKind(config.agent);
return applied;
}
- if (relocates) {
- // 同引擎换电脑:原生会话在原来那台、接不上,同样走下一条消息生效的切换意图。
+ if (relocates || orcaModelSelectionUsesIntent) {
+ // 同引擎换电脑或 Orca 换模型均走下一条消息生效的切换意图。
+ if (!canStageOrcaModelSelection(config.agent, capability.contextWindow,
+ targetCapabilities.supportsModelWindowSwitchGuard === true)) return false;
const applied = await writeSessionAgentSwitchIntent({
targetAgentKind: config.agent,
model: config.modelId,
@@ -8535,7 +8598,7 @@ function SessionScreenContent() {
}, [canUseRemoteSessionControls,currentSession,controlBusy,composerDeviceProviders.providers,maker,
sessionAgentKind,sessionAgentSwitchSupported,agentSwitchIntent,writeSessionAgentSwitchIntent,
runControlAction,setComposerModel,sessionId,deviceId,agentLocationMovable,remoteAgentCatalogs,
- remoteAgentDeviceName,controlledComputerName]);
+ remoteAgentDeviceName,controlledComputerName,orcaModelSelectionUsesIntent,canStageOrcaModelSelection,loadComposerAgentCapabilities]);
const selectComposerFlatModel = useCallback((option: MobileModelOption) => {
setModelSheetOpen(false);
@@ -8561,7 +8624,9 @@ function SessionScreenContent() {
hostName: controlledComputerName,
});
if (!location) return;
- if (location.agentDeviceId !== undefined) {
+ if (location.agentDeviceId !== undefined || orcaModelSelectionUsesIntent) {
+ if (!canStageOrcaModelSelection(sessionAgentKind, option.contextWindow,
+ modelSheetCapabilities?.supportsModelWindowSwitchGuard === true)) return;
await writeSessionAgentSwitchIntent({
targetAgentKind: sessionAgentKind,
model: option.id,
@@ -8586,7 +8651,7 @@ function SessionScreenContent() {
},
);
})();
- }, [agentLocationMovable, agentSwitchIntent, canUseRemoteSessionControls, controlledComputerName, currentSession, modelSheetAgentKind, modelSheetCapabilities, modelSheetSelection?.effort, modelSheetSelection?.fastMode, remoteAgentDeviceName, runControlAction, sessionAgentKind, setComposerModel, writeSessionAgentSwitchIntent]);
+ }, [agentLocationMovable, agentSwitchIntent, canUseRemoteSessionControls, controlledComputerName, currentSession, modelSheetAgentKind, modelSheetCapabilities, modelSheetSelection?.effort, modelSheetSelection?.fastMode, orcaModelSelectionUsesIntent, remoteAgentDeviceName, runControlAction, sessionAgentKind, setComposerModel, writeSessionAgentSwitchIntent, canStageOrcaModelSelection]);
const browseComposerModelAgent = useCallback(async (next: MobileSessionAgentKind) => {
if (next === modelSheetAgentKind) return true;
if (next !== sessionAgentKind) {
@@ -8599,10 +8664,10 @@ function SessionScreenContent() {
}, [agentSwitchIntent, modelSheetAgentKind, sessionAgentKind, sessionAgentSwitchSupported]);
const changeComposerSelectedEffort = useCallback((effort: string) => {
if (!canConfigureSessionModel) return;
- // 跨引擎 intent,或已登记「改回被控电脑」的同引擎 intent:改 intent 本身(带着位置),
+ // 跨引擎、换位置或 Orca 同引擎 intent:改 intent 本身(保留已有位置),
// 否则 setEffort 的值会在发送时被 intent 里的旧值盖回。
if (
- (modelSheetAgentKind !== sessionAgentKind || intentChangesAgentLocation(agentSwitchIntent))
+ (orcaModelSelectionUsesIntent || modelSheetAgentKind !== sessionAgentKind || intentChangesAgentLocation(agentSwitchIntent))
&& agentSwitchIntent?.targetAgentKind === modelSheetAgentKind
) {
void writeSessionAgentSwitchIntent({ ...agentSwitchIntent, effort });
@@ -8611,11 +8676,11 @@ function SessionScreenContent() {
if (modelSheetAgentKind === sessionAgentKind) {
void runControlAction(() => maker.setEffort(sessionId, effort), { effort });
}
- }, [agentSwitchIntent, canConfigureSessionModel, maker, modelSheetAgentKind, runControlAction, sessionAgentKind, sessionId, writeSessionAgentSwitchIntent]);
+ }, [agentSwitchIntent, canConfigureSessionModel, maker, modelSheetAgentKind, orcaModelSelectionUsesIntent, runControlAction, sessionAgentKind, sessionId, writeSessionAgentSwitchIntent]);
const changeComposerSelectedFastMode = useCallback((enabled: boolean) => {
if (!canConfigureSessionModel) return;
if (
- (modelSheetAgentKind !== sessionAgentKind || intentChangesAgentLocation(agentSwitchIntent))
+ (orcaModelSelectionUsesIntent || modelSheetAgentKind !== sessionAgentKind || intentChangesAgentLocation(agentSwitchIntent))
&& agentSwitchIntent?.targetAgentKind === modelSheetAgentKind
) {
void writeSessionAgentSwitchIntent({ ...agentSwitchIntent, fastMode: enabled });
@@ -8624,7 +8689,7 @@ function SessionScreenContent() {
if (modelSheetAgentKind === sessionAgentKind) {
void runControlAction(() => maker.setFastMode(sessionId, enabled), { fastMode: enabled });
}
- }, [agentSwitchIntent, canConfigureSessionModel, maker, modelSheetAgentKind, runControlAction, sessionAgentKind, sessionId, writeSessionAgentSwitchIntent]);
+ }, [agentSwitchIntent, canConfigureSessionModel, maker, modelSheetAgentKind, orcaModelSelectionUsesIntent, runControlAction, sessionAgentKind, sessionId, writeSessionAgentSwitchIntent]);
const toggleComposerModelPicker = useCallback(() => {
if (!canConfigureSessionModel) {
setModelSheetOpen(false);
@@ -9860,19 +9925,19 @@ function SessionScreenContent() {
<ModelPickerSheet
unified={{
currentSelection: { agentKind: sessionAgentKind, activeModelId: currentSession.model, selectedProviderId: currentSession.providerId ?? null, selectedEffort: currentSession.effort ?? '', selectedFastMode: !!currentSession.fastMode },
- scope: JSON.stringify([auth.user?.id, deviceId]),
+ scope: JSON.stringify([auth.user?.id, deviceId, orcaRemoteAgentDeviceId]),
agents: sessionAgentSwitchSupported ? ['claude-code','codex','pi'] : [sessionAgentKind],
loadCapabilities: async agent => {
- const result = normalizeMobileAgentCapabilities(await maker.getCapabilities(agent));
+ const result = normalizeMobileAgentCapabilities(await loadComposerAgentCapabilities(agent));
if (!result) throw new Error('Capabilities unavailable');
return result;
},
onSelect: selectUnifiedComposerModel,
// 远程 Agent:其他电脑上开放了远程调用的供应商接在后面,每个供应商一段、标题带电脑名。
- ...(agentLocationMovable
+ ...(agentLocationMovable || orcaRemoteAgentDeviceId
? {
remote: {
- catalogs: remoteAgentCatalogs,
+ catalogs: modelSheetRemoteCatalogs,
selectedDeviceId: nextAgentDeviceId,
// 供应商组:组里其他电脑收进组那一项;归组的任务在组那一项里选模型留在此刻运行的那台。
hostDeviceId: deviceId,
@@ -9895,15 +9960,15 @@ function SessionScreenContent() {
apiKeyStatus={deviceApiKeyStatus}
capabilities={modelSheetCapabilities}
disabled={controlBusy || !canUseRemoteSessionControls}
- emptyHint={composerDeviceProviders.error && !composerDeviceProviders.unsupported
+ emptyHint={!orcaRemoteAgentDeviceId && composerDeviceProviders.error && !composerDeviceProviders.unsupported
? humanizeRemoteError(composerDeviceProviders.error)
: modelSheetCapabilitiesError ?? undefined}
- flatOptions={modelSheetRuntimeOptions.modelOptions}
+ flatOptions={orcaRemoteAgentDeviceId ? [] : modelSheetRuntimeOptions.modelOptions}
providersReady={composerDeviceProviders.ready}
- providersUnsupported={composerDeviceProviders.unsupported}
+ providersUnsupported={orcaRemoteAgentDeviceId ? false : composerDeviceProviders.unsupported}
modelVisibilityOverrides={composerDeviceProviders.modelVisibilityOverrides}
keyboardAvoidingBehavior={nativeShellLayout.keyboardAvoidingBehavior}
- loading={composerDeviceProviders.loading || modelSheetCapabilitiesLoading}
+ loading={(orcaRemoteAgentDeviceId ? currentAgentCatalog.loading : composerDeviceProviders.loading) || modelSheetCapabilitiesLoading}
loadingHint={modelSheetCapabilitiesLoading
? t('session.screen.readingCapabilities', { agent: mobileAgentLabel(modelSheetAgentKind) })
: undefined}
@@ -9918,7 +9983,7 @@ function SessionScreenContent() {
permissionDisabled={controlBusy || !canUseRemoteSessionControls}
permissionOptions={runtimeOptions.permissionOptions}
pricing={deviceModelPricing}
- providers={composerDeviceProviders.providers}
+ providers={orcaRemoteAgentDeviceId ? [] : composerDeviceProviders.providers}
selectedEffort={modelSheetSelection.effort}
selectedFastMode={modelSheetSelection.fastMode}
selectedProviderId={modelSheetSelection.providerId}
diff --git a/apps/mobile/src/__tests__/modelPickerHarnessSwitch.test.ts b/apps/mobile/src/__tests__/modelPickerHarnessSwitch.test.ts
index 3e13c7b8ff..6878ef326f 100644
--- a/apps/mobile/src/__tests__/modelPickerHarnessSwitch.test.ts
+++ b/apps/mobile/src/__tests__/modelPickerHarnessSwitch.test.ts
@@ -8,15 +8,17 @@ vi.mock('react-native', () => ({ Alert: { alert: vi.fn() } }));
import { confirmAgentLocationForPick } from '@/session/sessionAgentSwitchConfirmation';
const source = ts.createSourceFile('screen.tsx', readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
-let callback: ts.Expression | undefined;
+const callbacks = new Map<string, string>();
+const callbackNames = ['loadComposerAgentCapabilities', 'canStageOrcaModelSelection', 'selectUnifiedComposerModel'];
function visit(node: ts.Node) {
- if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'selectUnifiedComposerModel') {
- callback = (node.initializer as ts.CallExpression).arguments[0];
+ if (ts.isVariableDeclaration(node) && callbackNames.includes(node.name.getText(source))) {
+ callbacks.set(node.name.getText(source), (node.initializer as ts.CallExpression).arguments[0].getText(source));
}
ts.forEachChild(node, visit);
}
visit(source);
-const js = ts.transpileModule(`const select = ${callback!.getText(source)};`, {compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
+const js = ts.transpileModule(callbackNames.map(name => `const ${name} = ${callbacks.get(name)};`).join('\n'),
+ {compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
const studioProviders = [{ id: 'studio-account' }];
function harness(
confirmed = true,
@@ -34,7 +36,13 @@ function harness(
buttons?.[confirmed ? 1 : 0]?.onPress?.();
});
const resolveAgentCapability = vi.fn(() => ({ supportsFastMode: true }));
+ const getCapabilities = vi.fn(async () => ({ hasFastMode: true }));
+ const getRemoteCapabilities = vi.fn(async () => ({ hasFastMode: true }));
+ const executionMakerForDevice = vi.fn((_deviceId: string) => ({ getCapabilities: getRemoteCapabilities }));
const env = {
+ // These fixtures exercise ordinary tasks; Orca admission has its own suite.
+ orcaModelSelectionUsesIntent:false,orcaRemoteAgentDeviceId:null,executionMakerForDevice,
+ isProviderShareAgentDeviceId:(id:unknown)=>typeof id === 'string' && id.startsWith('share:'),
agentLocationMovable:true,
remoteAgentCatalogs:[{ deviceId:'device-studio-mac', name:'工作室 Mac', status:'ready', providers:studioProviders }],
remoteAgentDeviceName:(id:string)=>id === 'device-studio-mac' ? '工作室 Mac' : id,
@@ -44,7 +52,7 @@ function harness(
canUseRemoteSessionControls:true,
currentSession:{effort:'low',fastMode:false,agentKind:'codex',model:'current-model',providerId:null,agentDeviceId:null,...session},controlBusy:false,
composerDeviceProviders:{providers:[]}, resolveAgentCapability,
- normalizeMobileAgentCapabilities:(x:unknown)=>x, maker:{getCapabilities:async()=>({hasFastMode:true}),setEffort:vi.fn(),setFastMode:vi.fn()},
+ normalizeMobileAgentCapabilities:(x:unknown)=>x, maker:{getCapabilities,setEffort:vi.fn(),setFastMode:vi.fn()},
deviceId:'device',deviceIdRef:{current:'device'},sessionAgentKind:'codex',sessionAgentSwitchSupported:true,
confirmMobileSessionAgentSwitch,
writeSessionAgentSwitchIntent,
@@ -52,10 +60,11 @@ function harness(
runControlAction:async(action:()=>Promise<boolean>,patch:any)=>{const ok=await action();if(ok)state.intent=patch.agentSwitchIntent;return ok;},
...overrides,
};
- const render = () => new Function(...Object.keys(env), 'agentSwitchIntent', `${js}; return select;`)(...Object.values(env),state.intent);
+ const render = () => new Function(...Object.keys(env), 'agentSwitchIntent', `${js}; return selectUnifiedComposerModel;`)(...Object.values(env),state.intent);
return {
state, render, setModelSheetAgentKind, writeSessionAgentSwitchIntent, setComposerModel,
confirmMobileSessionAgentSwitch, relocationAlert, resolveAgentCapability,
+ getCapabilities, getRemoteCapabilities, executionMakerForDevice,
};
}
const config = {agent:'pi',providerId:'account',modelId:'model',effort:'high',fast:false};
@@ -88,6 +97,9 @@ it('switches directly between models of the same computer', async () => {
expect(h.setComposerModel).toHaveBeenCalledWith(expect.objectContaining({ model: 'model', providerId: 'studio-account' }));
// 能力按这一行所属电脑的目录核对。
expect(h.resolveAgentCapability).toHaveBeenCalledWith(studioProviders, 'studio-account', 'model', 'codex');
+ expect(h.executionMakerForDevice).toHaveBeenCalledWith(studio.deviceId);
+ expect(h.getRemoteCapabilities).toHaveBeenCalledWith('codex');
+ expect(h.getCapabilities).not.toHaveBeenCalled();
});
it('asks before moving the Agent to another computer and registers the move', async () => {
const h = harness();
@@ -119,6 +131,8 @@ it('asks before moving a remote Agent back to the controlled computer', async ()
expect(h.writeSessionAgentSwitchIntent).toHaveBeenCalledWith(expect.objectContaining({
targetAgentKind: 'codex', model: 'model', providerId: 'account', agentDeviceId: null,
}));
+ expect(h.getCapabilities).toHaveBeenCalledWith('codex');
+ expect(h.getRemoteCapabilities).not.toHaveBeenCalled();
});
it('confirms a cross-engine move to another computer only once', async () => {
const h = harness();
diff --git a/apps/mobile/src/__tests__/orcaModelSelection.test.ts b/apps/mobile/src/__tests__/orcaModelSelection.test.ts
new file mode 100644
index 0000000000..9745964f1d
--- /dev/null
+++ b/apps/mobile/src/__tests__/orcaModelSelection.test.ts
@@ -0,0 +1,221 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import ts from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+import { confirmAgentLocationForPick } from '@/session/sessionAgentSwitchConfirmation';
+import { shouldBlockLegacyRemoteModelWindowSwitch } from '@cindy/maker-shared/agent-capabilities';
+
+vi.mock('react-native', () => ({ Alert: { alert: vi.fn() } }));
+
+// Run the production callbacks without mounting native controls or remote services.
+const source = ts.createSourceFile('session.tsx', readFileSync(
+ resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8',
+), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
+const callbacks = new Map<string, string>();
+let intentGate = '';
+let remoteCatalogGate = '';
+function visit(node: ts.Node) {
+ if (ts.isVariableDeclaration(node) && node.initializer) {
+ const name = node.name.getText(source);
+ if (name === 'orcaModelSelectionUsesIntent') intentGate = node.initializer.getText(source);
+ if (name === 'orcaRemoteAgentDeviceId') remoteCatalogGate = node.initializer.getText(source);
+ if (ts.isCallExpression(node.initializer) && ['useCallback', 'useMemo'].includes(node.initializer.expression.getText(source))) {
+ callbacks.set(name, node.initializer.arguments[0].getText(source));
+ }
+ }
+ ts.forEachChild(node, visit);
+}
+visit(source);
+
+function setup(orcaRole: 'lead' | 'worker' | null, supported = true, agentDeviceId: string | null = null,
+ windowState: { agent?: string; used?: number; current?: number; target?: number; hostGuard?: boolean } = {}) {
+ const selection = { model: 'new-model', providerId: 'provider', effort: 'high', fastMode: true };
+ const write = vi.fn(async (_intent: unknown) => true);
+ const setModel = vi.fn(async () => true);
+ const runControlAction = vi.fn(async (action: () => Promise<unknown>) => action());
+ const remoteCapabilities = vi.fn(async (_agent: string): Promise<unknown> => undefined);
+ const bindings = {
+ currentSession: { orcaRole, agentDeviceId, agentKind: windowState.agent ?? 'codex', model: 'old-model', effort: 'low', fastMode: false,
+ contextTokens: windowState.used, contextWindow: windowState.current },
+ currentAgentDeviceId: agentDeviceId,
+ remoteAgentCatalogs: ['current', 'other'].map(deviceId => ({ deviceId, providers: [] })),
+ sessionAgentSwitchSupported: supported, sessionAgentKind: windowState.agent ?? 'codex', modelSheetAgentKind: windowState.agent ?? 'codex',
+ canUseRemoteSessionControls: true, canConfigureSessionModel: true, controlBusy: false,
+ sessionId: 's1', deviceId: 'host', deviceIdRef: { current: 'host' },
+ agentLocationMovable: false, controlledComputerName: 'Host', remoteAgentDeviceName: vi.fn(),
+ agentSwitchIntent: { targetAgentKind: 'codex', ...selection },
+ modelSheetSelection: selection, modelSheetCapabilities: { supportsModelWindowSwitchGuard: windowState.hostGuard !== false },
+ sessionMirrorAccessors: {}, composerDeviceProviders: { providers: [] },
+ resolveRowSelection: () => selection, reconcileRuntimeDraftWithCapabilities: () => selection,
+ resolveAgentCapability: () => ({ supportsFastMode: true, contextWindow: windowState.target ?? 200000 }),
+ normalizeMobileAgentCapabilities: (value: unknown) => value ?? ({ hasFastMode: true, supportsModelWindowSwitchGuard: windowState.hostGuard !== false }),
+ maker: { getCapabilities: vi.fn(), setEffort: vi.fn(), setFastMode: vi.fn() },
+ executionMakerForDevice: vi.fn((_id: string) => ({ getCapabilities: remoteCapabilities })),
+ isProviderShareAgentDeviceId: (id: unknown) => typeof id === 'string' && id.startsWith('share:'),
+ confirmAgentLocationForPick, intentChangesAgentLocation: () => false,
+ confirmMobileSessionAgentSwitch: vi.fn(async () => true),
+ shouldBlockLegacyRemoteModelWindowSwitch, showRemoteModelWindowUnsupported: vi.fn(),
+ writeSessionAgentSwitchIntent: write, setComposerModel: setModel, runControlAction,
+ setModelSheetOpen: vi.fn(), setModelSheetAgentKind: vi.fn(),
+ };
+ const names = ['selectComposerModelRow', 'selectUnifiedComposerModel', 'selectComposerFlatModel',
+ 'changeComposerSelectedEffort', 'changeComposerSelectedFastMode'];
+ const compiled = ts.transpileModule(`const orcaModelSelectionUsesIntent = ${intentGate};
+ const orcaRemoteAgentDeviceId = ${remoteCatalogGate};
+ const loadComposerAgentCapabilities = ${callbacks.get('loadComposerAgentCapabilities')};
+ const canStageOrcaModelSelection = ${callbacks.get('canStageOrcaModelSelection')};
+ return {${names.map(name => `${name}: ${callbacks.get(name)}`).join(',')}, loadComposerAgentCapabilities,
+ catalogs: (${callbacks.get('modelSheetRemoteCatalogs')})()};`,
+ { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ const handlers = new Function(...Object.keys(bindings), compiled)(...Object.values(bindings));
+ return { handlers, write, setModel, runControlAction, bindings, selection, remoteCapabilities };
+}
+
+const picks = [
+ ['selectComposerModelRow', { model: { id: 'new-model', contextWindow: 200000 } }, 'provider'],
+ ['selectUnifiedComposerModel', { agent: 'codex', modelId: 'new-model', providerId: 'provider', effort: 'high', fast: true }, 'provider'],
+ ['selectComposerFlatModel', { id: 'new-model', contextWindow: 200000 }, null],
+] as const;
+
+describe('Orca model-only selection', () => {
+ it.each(['claude-code', 'codex', 'pi'])('loads and selects %s using the current execution computer capabilities', async agent => {
+ const h = setup('worker', true, 'current', { used: 1000, current: 1000000 });
+ h.bindings.maker.getCapabilities.mockRejectedValue(new Error('target harness is not registered on host'));
+ h.remoteCapabilities.mockResolvedValue({ hasFastMode: true, supportsModelWindowSwitchGuard: true });
+ await expect(h.handlers.loadComposerAgentCapabilities(agent)).resolves.toMatchObject({ hasFastMode: true });
+ await expect(h.handlers.selectUnifiedComposerModel({ agent, modelId: 'new-model', providerId: 'provider',
+ effort: 'high', fast: true }, { deviceId: 'current' })).resolves.toBe(true);
+ expect(h.remoteCapabilities).toHaveBeenCalledWith(agent);
+ expect(h.bindings.executionMakerForDevice).toHaveBeenCalledWith('current');
+ expect(h.bindings.maker.getCapabilities).not.toHaveBeenCalled();
+ expect(h.write).toHaveBeenCalledWith(expect.objectContaining({ targetAgentKind: agent }));
+ expect(h.write.mock.calls[0][0]).not.toHaveProperty('agentDeviceId');
+ });
+
+ it('reads capabilities for a share catalog through the controlled computer', async () => {
+ const h = setup('worker', true, 'share:share-1');
+ h.bindings.maker.getCapabilities.mockResolvedValue({ hasFastMode: true, supportsModelWindowSwitchGuard: true });
+ await expect(h.handlers.loadComposerAgentCapabilities('codex')).resolves.toMatchObject({ hasFastMode: true });
+ expect(h.bindings.executionMakerForDevice).not.toHaveBeenCalled();
+ expect(h.bindings.maker.getCapabilities).toHaveBeenCalledWith('codex');
+ });
+
+ it('uses the selected computer Fast support instead of borrowing it from the task host', async () => {
+ const h = setup('worker', true, 'current');
+ h.remoteCapabilities.mockResolvedValue({ hasFastMode: false, supportsModelWindowSwitchGuard: true });
+ await expect(h.handlers.selectUnifiedComposerModel({ agent: 'codex', modelId: 'new-model', providerId: 'provider',
+ effort: 'high', fast: true }, { deviceId: 'current' })).resolves.toBe(false);
+ expect(h.write).not.toHaveBeenCalled();
+ expect(h.bindings.maker.getCapabilities).not.toHaveBeenCalled();
+ });
+ it.each(['claude-code', 'codex', 'pi'])('guards all pickers before staging a pressured %s shrink', async agent => {
+ for (const role of ['lead', 'worker'] as const) {
+ for (const hostGuard of [true, false]) {
+ for (const used of [180000, 240000]) {
+ for (const [name, input] of picks) {
+ const h = setup(role, true, null, { agent, used, current: 1000000, hostGuard });
+ await h.handlers[name]({ ...input, ...(name === 'selectUnifiedComposerModel' ? { agent } : {}) });
+ await vi.waitFor(() => expect(h.bindings.showRemoteModelWindowUnsupported).toHaveBeenCalledWith(200000));
+ expect(h.write).not.toHaveBeenCalled();
+ expect(h.setModel).not.toHaveBeenCalled();
+ expect(h.runControlAction).not.toHaveBeenCalled();
+ expect(h.bindings.currentSession.model).toBe('old-model');
+ }
+ }
+ }
+ }
+ });
+
+ it.each([
+ { used: 179999, current: 1000000 },
+ { used: 240000, current: 200000 },
+ { used: 240000, current: 100000 },
+ { used: undefined, current: undefined },
+ ])('keeps supported-host low-pressure, same/expanded and unknown windows selectable: %j', async state => {
+ for (const [name, input] of picks) {
+ const h = setup('worker', true, null, state);
+ await h.handlers[name](input);
+ await vi.waitFor(() => expect(h.write).toHaveBeenCalledTimes(1));
+ expect(h.bindings.showRemoteModelWindowUnsupported).not.toHaveBeenCalled();
+ }
+ });
+
+ it('keeps legacy unknown-window and Pi checks before intent registration', async () => {
+ for (const agent of ['claude-code', 'codex', 'pi']) {
+ const h = setup('lead', true, null, { agent, hostGuard: false });
+ expect(await h.handlers.selectUnifiedComposerModel({ ...picks[1][1], agent })).toBe(false);
+ expect(h.write).not.toHaveBeenCalled();
+ expect(h.bindings.showRemoteModelWindowUnsupported).toHaveBeenCalledOnce();
+ }
+ });
+
+ it('uses the chosen remote catalog window instead of the host catalog', async () => {
+ const h = setup('worker', true, 'current', { used: 240000, current: 1000000, target: 200000 });
+ expect(await h.handlers.selectUnifiedComposerModel(picks[1][1], { deviceId: 'current' })).toBe(false);
+ expect(h.write).not.toHaveBeenCalled();
+ expect(h.bindings.showRemoteModelWindowUnsupported).toHaveBeenCalledWith(200000);
+ });
+
+ it('does not apply the same-Agent window guard to cross-Agent picks or pending effort/Fast edits', async () => {
+ const h = setup('worker', true, null, { used: 240000, current: 1000000 });
+ expect(await h.handlers.selectUnifiedComposerModel({ ...picks[1][1], agent: 'pi' })).toBe(true);
+ h.handlers.changeComposerSelectedEffort('medium');
+ h.handlers.changeComposerSelectedFastMode(false);
+ expect(h.write).toHaveBeenCalledTimes(3);
+ expect(h.bindings.showRemoteModelWindowUnsupported).not.toHaveBeenCalled();
+ });
+
+ it.each(['lead', 'worker'] as const)('keeps only the current remote catalog and selects in place for %s', async role => {
+ const h = setup(role, true, 'current');
+ expect(h.handlers.catalogs.map((item: { deviceId: string }) => item.deviceId)).toEqual(['current']);
+ expect(await h.handlers.selectUnifiedComposerModel(picks[1][1], { deviceId: 'current' })).toBe(true);
+ expect(h.write).toHaveBeenCalledWith({ targetAgentKind: 'codex', model: 'new-model',
+ providerId: 'provider', effort: 'high', fastMode: true });
+ for (const deviceId of [null, 'other']) {
+ expect(await h.handlers.selectUnifiedComposerModel(picks[1][1], { deviceId })).toBe(false);
+ }
+ expect(h.write).toHaveBeenCalledTimes(1);
+ expect(h.setModel).not.toHaveBeenCalled();
+ expect(h.bindings.currentSession.agentDeviceId).toBe('current');
+ });
+
+ it.each(['lead', 'worker'] as const)('stages all three model pickers for %s without patching the current runtime', async role => {
+ for (const [name, input, providerId] of picks) {
+ const h = setup(role);
+ await h.handlers[name](input);
+ await vi.waitFor(() => expect(h.write).toHaveBeenCalledTimes(1));
+ expect(h.write).toHaveBeenCalledWith({ targetAgentKind: 'codex', model: 'new-model',
+ providerId, effort: 'high', fastMode: true });
+ expect(h.setModel).not.toHaveBeenCalled();
+ expect(h.runControlAction).not.toHaveBeenCalled();
+ expect(h.bindings.currentSession.model).toBe('old-model');
+ }
+ });
+
+ it.each([['lead', false], [null, true]] as const)('preserves legacy model routing for role=%s supported=%s', async (role, supported) => {
+ for (const [name, input] of picks) {
+ const h = setup(role, supported);
+ await h.handlers[name](input);
+ await vi.waitFor(() => expect(h.setModel).toHaveBeenCalledTimes(1));
+ expect(h.write).not.toHaveBeenCalled();
+ }
+ });
+
+ it('does not fall back to setModel when the switch intent is rejected', async () => {
+ const h = setup('worker');
+ h.write.mockResolvedValue(false);
+ expect(await h.handlers.selectUnifiedComposerModel(picks[1][1])).toBe(false);
+ expect(h.setModel).not.toHaveBeenCalled();
+ expect(h.runControlAction).not.toHaveBeenCalled();
+ });
+
+ it.each(['lead', 'worker'] as const)('updates effort and Fast on the pending model for %s', role => {
+ const h = setup(role);
+ h.handlers.changeComposerSelectedEffort('medium');
+ h.handlers.changeComposerSelectedFastMode(false);
+ expect(h.write).toHaveBeenNthCalledWith(1, { ...h.bindings.agentSwitchIntent, effort: 'medium' });
+ expect(h.write).toHaveBeenNthCalledWith(2, { ...h.bindings.agentSwitchIntent, fastMode: false });
+ expect(h.bindings.maker.setEffort).not.toHaveBeenCalled();
+ expect(h.bindings.maker.setFastMode).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/src/__tests__/sessionAgentSwitch.test.ts b/apps/mobile/src/__tests__/sessionAgentSwitch.test.ts
index bd8acb110a..3a7983c20c 100644
--- a/apps/mobile/src/__tests__/sessionAgentSwitch.test.ts
+++ b/apps/mobile/src/__tests__/sessionAgentSwitch.test.ts
@@ -62,7 +62,7 @@ describe('mobile session Agent switch contract', () => {
})).toEqual({ targetAgentKind: 'pi', model: 'gpt-5.5', providerId: 'openai' });
});
- it('requires host capability and excludes SSH / Orca sessions', () => {
+ it('requires host capability, allows Orca, and excludes SSH sessions', () => {
const supported: MobileAgentCapabilities = {
availableModels: [],
effortLevels: [],
@@ -73,7 +73,8 @@ describe('mobile session Agent switch contract', () => {
};
expect(supportsMobileSessionAgentSwitch({ remoteHostId: null, orcaRole: null }, supported)).toBe(true);
expect(supportsMobileSessionAgentSwitch({ remoteHostId: 'ssh-1', orcaRole: null }, supported)).toBe(false);
- expect(supportsMobileSessionAgentSwitch({ remoteHostId: null, orcaRole: 'lead' }, supported)).toBe(false);
+ expect(supportsMobileSessionAgentSwitch({ remoteHostId: null, orcaRole: 'lead' }, supported)).toBe(true);
+ expect(supportsMobileSessionAgentSwitch({ remoteHostId: null, orcaRole: 'worker' }, supported)).toBe(true);
expect(supportsMobileSessionAgentSwitch(
{ remoteHostId: null, orcaRole: null },
{ ...supported, supportsSessionAgentSwitch: false },
diff --git a/apps/mobile/src/__tests__/sessionAgentSwitchConfirmation.test.ts b/apps/mobile/src/__tests__/sessionAgentSwitchConfirmation.test.ts
index 611bc9c11d..c381b8f259 100644
--- a/apps/mobile/src/__tests__/sessionAgentSwitchConfirmation.test.ts
+++ b/apps/mobile/src/__tests__/sessionAgentSwitchConfirmation.test.ts
@@ -106,4 +106,16 @@ describe('confirmAgentLocationForPick (remote Agent)', () => {
}, showAlert)).resolves.toBeNull();
expect(showAlert).not.toHaveBeenCalled();
});
+
+ it('keeps an immovable remote Agent on its current computer, even with a stale relocation intent', async () => {
+ const showAlert = vi.fn();
+ const fixed = { ...base, movable: false, session: { agentDeviceId: 'device-studio-mac' },
+ intent: { targetAgentKind: 'codex' as const, model: 'm', providerId: null, agentDeviceId: 'other' } };
+ await expect(confirmAgentLocationForPick({ ...fixed, catalogDeviceId: 'device-studio-mac' }, showAlert))
+ .resolves.toEqual({});
+ for (const catalogDeviceId of [null, 'other']) {
+ await expect(confirmAgentLocationForPick({ ...fixed, catalogDeviceId }, showAlert)).resolves.toBeNull();
+ }
+ expect(showAlert).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts b/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts
index a272639435..61adc4418a 100644
--- a/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts
+++ b/apps/mobile/src/__tests__/sessionAgentSwitchWiring.test.ts
@@ -76,13 +76,28 @@ describe('session Agent switch UI wiring', () => {
// 唯一写出口把 intent 的位置作为第 7 参转给被控端;没有位置时不发(旧 6 参 wire)。
expect(writer).toContain('nextIntent.agentDeviceId !== undefined');
expect(writer).toContain('? { agentDeviceId: nextIntent.agentDeviceId }');
- // 共享任务访客不能挪 Agent 位置,SSH / Orca 不支持切换,旧被控端不投影位置字段。
+ // Orca 可以切 Agent,但和共享任务访客一样不能挪运行位置。
expect(source).toContain('const agentLocationMovable = sessionAgentSwitchSupported');
+ const locationGate = source.slice(source.indexOf('const agentLocationMovable ='),
+ source.indexOf('/** Agent 现在所在的电脑'));
+ expect(locationGate).toContain('&& !currentSession.orcaRole');
+ expect(locationGate).toContain('&& !currentSession.orcaRemoteLead');
+ const expression = locationGate.match(/const agentLocationMovable = ([\s\S]*?);/)?.[1];
+ expect(expression).toBeDefined();
+ const movable = new Function('currentSession',
+ `const sessionAgentSwitchSupported = true, deviceId = 'host', isSharedTaskPeer = () => false;
+ return !!(${expression});`);
+ const worker = { agentDeviceId: null, orcaRole: null,
+ orcaRemoteLead: { leadDeviceId: 'lead', leadSessionId: 'lead-s1', workerLabel: 'worker' } };
+ expect(movable(worker)).toBe(false);
+ expect(movable({ ...worker, orcaRemoteLead: { ...worker.orcaRemoteLead, releasedAt: 1 } })).toBe(false);
+ expect(movable({ ...worker, orcaRemoteLead: null })).toBe(true);
+ expect(movable(null)).toBe(false);
expect(source).toContain("&& !isSharedTaskPeer(deviceId)");
expect(source).toContain("Object.prototype.hasOwnProperty.call(currentSession, 'agentDeviceId')");
// 模型列表另列其他电脑的供应商,选中态跟着下一条消息时 Agent 所在的电脑。
expect(source).toContain(
- 'catalogs: remoteAgentCatalogs,\n selectedDeviceId: nextAgentDeviceId,',
+ 'catalogs: modelSheetRemoteCatalogs,\n selectedDeviceId: nextAgentDeviceId,',
);
// 供应商组:归组的任务在组那一项里选模型留在此刻运行的那台;挂着换电脑的意图时不按组显示。
expect(source).toContain('providerGroup: remoteProviderGroup,');
@@ -126,7 +141,7 @@ describe('session Agent switch UI wiring', () => {
source.indexOf('const toggleComposerModelPicker'),
);
expect(toggles.match(
- /\(modelSheetAgentKind !== sessionAgentKind \|\| intentChangesAgentLocation\(agentSwitchIntent\)\)/g,
+ /\(orcaModelSelectionUsesIntent \|\| modelSheetAgentKind !== sessionAgentKind \|\| intentChangesAgentLocation\(agentSwitchIntent\)\)/g,
)).toHaveLength(2);
// 模型药丸按 Agent 所在电脑的目录显示,带远程标记;读屏标签读出那台电脑。
@@ -139,7 +154,11 @@ describe('session Agent switch UI wiring', () => {
const source = readSource('app/sessions/[sessionId].tsx');
expect(source).toContain('agentKind={modelSheetAgentKind}');
expect(source).toContain('capabilities={modelSheetCapabilities}');
- expect(source).toContain('flatOptions={modelSheetRuntimeOptions.modelOptions}');
+ expect(source).toContain('flatOptions={orcaRemoteAgentDeviceId ? [] : modelSheetRuntimeOptions.modelOptions}');
+ expect(source).toContain('providers={orcaRemoteAgentDeviceId ? [] : composerDeviceProviders.providers}');
+ expect(source).toContain('providersUnsupported={orcaRemoteAgentDeviceId ? false : composerDeviceProviders.unsupported}');
+ expect(source).toContain('...(agentLocationMovable || orcaRemoteAgentDeviceId');
+ expect(source).toContain('remoteAgentCatalogs.filter((catalog) => catalog.deviceId === orcaRemoteAgentDeviceId)');
expect(source).toContain('selectedProviderId={modelSheetSelection.providerId}');
expect(source).toContain('agentKind={agentSwitchIntent.targetAgentKind}');
});
diff --git a/apps/mobile/src/session/sessionAgentSwitch.ts b/apps/mobile/src/session/sessionAgentSwitch.ts
index 8ec3cd6ffc..182b7aeb03 100644
--- a/apps/mobile/src/session/sessionAgentSwitch.ts
+++ b/apps/mobile/src/session/sessionAgentSwitch.ts
@@ -53,14 +53,13 @@ export function sessionAgentKind(session: Pick<RemoteSession, 'agentKind'>): Mob
: 'claude-code';
}
-/** 手机是否应展示 Agent 分段;远程 SSH / Orca 会话继续保持单 Agent。 */
+/** 手机是否应展示 Agent 分段;远程 SSH 仍由被控端能力限制。 */
export function supportsMobileSessionAgentSwitch(
session: Pick<RemoteSession, 'remoteHostId' | 'orcaRole'>,
capabilities: MobileAgentCapabilities | null,
): boolean {
return capabilities?.supportsSessionAgentSwitch === true
- && !session.remoteHostId
- && !session.orcaRole;
+ && !session.remoteHostId;
}
export function mobileAgentLabel(agentKind: MobileSessionAgentKind): string {
diff --git a/apps/mobile/src/session/sessionAgentSwitchConfirmation.ts b/apps/mobile/src/session/sessionAgentSwitchConfirmation.ts
index 8c7b9fbed9..883ecc5d07 100644
--- a/apps/mobile/src/session/sessionAgentSwitchConfirmation.ts
+++ b/apps/mobile/src/session/sessionAgentSwitchConfirmation.ts
@@ -53,7 +53,7 @@ export type AgentLocationPatch = { agentDeviceId?: string | null };
/**
* 远程 Agent:选中一行模型时 Agent 的运行位置怎么处理(规则见 resolveAgentLocationPick)。
* 换到另一台电脑(或改回被控电脑)先确认;取消 = null,调用方什么都不改。
- * movable = false(访客 / 不支持切换 / 旧被控端)时只接受被控电脑自己的目录。
+ * movable = false 时只接受 Agent 当前所在电脑的目录,既不搬回被控电脑也不换到其他电脑。
*/
export async function confirmAgentLocationForPick(
input: {
@@ -69,8 +69,8 @@ export async function confirmAgentLocationForPick(
},
showAlert: ShowAlert = Alert.alert,
): Promise<AgentLocationPatch | null> {
- if (!input.movable) return input.catalogDeviceId === null ? {} : null;
const pick = resolveAgentLocationPick(input);
+ if (!input.movable) return pick.relocateTo === undefined ? {} : null;
if (pick.needsConfirm) {
const target = input.catalogDeviceId
? { kind: 'device' as const, name: input.deviceName(input.catalogDeviceId) }
diff --git a/docs/dev-rules/orca-team-architecture.md b/docs/dev-rules/orca-team-architecture.md
index 8c1b076c99..f48e00c9b5 100644
--- a/docs/dev-rules/orca-team-architecture.md
+++ b/docs/dev-rules/orca-team-architecture.md
@@ -388,13 +388,13 @@ Worker turn 被 vendor 报终止型 error,但 interrupted-turn auto-resume 仍
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 没有 `send_to_lead` 桥,也不支持 steer / 队列编辑。界面:创建弹窗的「运行设备」只在本机 Lead 上出现(`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 的位置;选了远程就不提供运行设备,选了运行设备回到任务所在电脑。远程选择不写本机 Worker 偏好,档位记在本机为那台单独记的一份(`agentDeviceModelMemory`)。手机同口径(`useOrcaWorkerForm` 的 `agentDeviceId`,模型面板 `remote` 与新建任务同一份 `useRemoteAgentCatalogs`),被控电脑声明 `supportsOrcaWorkerAgentDevice` 时新建任务的远程供应商与协同不再互斥。Lead 的 `list_available_models` 可按 `agent_device_id` 列那里的模型并给出 `locations`,`create_worker` / `create_workers` 用同一个 `agent_device_id`。Worker 列表投影 `session.agentDeviceId`,桌面 Worker 头像叠与远程任务同款的单波纹 + 点;手机 Worker 行保持原来的状态圆点,不加远程标识(2026-10-11 用户要求维持原样)。已开始的 Worker 不能由用户中途换位置(协同任务不换模型);供应商组为它换电脑是唯一例外,见第 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 与运行设备 Worker 不能再指定另一台(`INVALID_PARAMS`),插件任务只能跟 Lead 或留在任务所在电脑。入口一处一套:桌面「创建 Worker / 开启协同」弹窗与新建任务用同一个模型面板,任务所在电脑的供应商之后列其他电脑与分享(`useWorkerAgentDevices`),选中哪一行 Worker 的 Agent 就在哪运行,默认选中 Lead 的位置;选了远程就不提供运行设备,选了运行设备回到任务所在电脑。远程选择不写本机 Worker 偏好,档位记在本机为那台单独记的一份(`agentDeviceModelMemory`)。手机同口径(`useOrcaWorkerForm` 的 `agentDeviceId`,模型面板 `remote` 与新建任务同一份 `useRemoteAgentCatalogs`),被控电脑声明 `supportsOrcaWorkerAgentDevice` 时新建任务的远程供应商与协同不再互斥。Lead 的 `list_available_models` 可按 `agent_device_id` 列那里的模型并给出 `locations`,`create_worker` / `create_workers` 用同一个 `agent_device_id`。Worker 列表投影 `session.agentDeviceId`,桌面 Worker 头像叠与远程任务同款的单波纹 + 点;手机 Worker 行保持原来的状态圆点,不加远程标识(2026-10-11 用户要求维持原样)。已开始的 Worker 不能由用户中途换 Agent 位置;Agent/模型选择在下一次发送边界应用;供应商组为它换电脑是唯一例外,见第 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`)。要点:
- **新 Worker 也分配**:Worker 的任务记录由启动这一步写入,分配时还读不到,`applyProviderGroupAssignment` 用启动参数作为「从没运行过」的快照(`assignBeforeStart` 的 `startRow`);记录已存在时以记录为准。
- **跟 Lead 就是跟 Lead 的组**:Lead 有组绑定、Worker 选的位置就是 Lead 现在所在且来源没另选(或选的就是 Lead 现在的来源 / 组那一项)、同一种 Agent 时,Worker 改用组那一项(本机的组:任务所在电脑 + 组的供应商;另一台电脑上的组:那台 + 组的供应商),再由组按策略选电脑;组那一项不提供该模型或读不到时照旧跟 Lead 所在那台。`list_available_models` 不指定位置时同口径。实现:`OrcaLeadSessionSnapshot.providerGroupEntry`、`leadProviderGroupFollowCandidate`。
- - **只放行组的换位置**:`performSessionAgentSwitch` 对协同任务仍拒绝用户发起的切换,只接受 main 内部带 `providerGroupRelocation` 的 applyNow 调用,且引擎与模型都不变;该标记不从 IPC 读取。
+ - **只放行组的换位置**:`performSessionAgentSwitch` 允许协同任务在原 Agent 位置切换 Agent/模型;显式改变 `agentDeviceId` 仍只接受 main 内部带 `providerGroupRelocation` 的 applyNow 调用,且引擎与模型都不变;该标记不从 IPC 读取。
- **换电脑资格与等额度恢复分开**:组的 `isFailoverEligible` 用 `isProviderGroupFailoverEligible`(Worker 可换),额度恢复后自动继续仍用 `isUsageLimitAutoResumeEligible`(Worker 不等,失败交给 Lead)。
- **换过去仍是成员**:`bootstrapSwitchedSession` 对协同任务调 `synthesizeOrcaVendorOptionsFromDb`,新会话带着协同身份、提示词与 `cindy_orca` / `orca_worker_bridge`,不靠下一次发送二次重启。
- **Worker 终态按换电脑那次登记结算**(与 5a 同一原则):输入协调器登记「先不呈现」期间,Worker 的终态不调 `handleWorkerTerminalTurn`,而是按登记 id 暂存(`provider-group/heldWorkerTerminals.ts`;error 事件随 error 行一起暂存,只以 done 收尾的失败在 terminal 末尾暂存)。换成了(续跑已发出)丢掉,auto-bridge pending 保留到续跑那一轮的产品终态再回报;没换成、迟迟没有结局或有人接手时恰好一次回报这次异常终止,账号已切换则不回报。迟到的旧结算只认自己那次登记。
@@ -492,9 +492,19 @@ Codex thread start / resume 成功后必须注册 `threadId -> session context`
历史问题:`renderOrcaLeadSystemPrompt`(`packages/orca-workflow/src/orca-bridge-prompt.ts`)的 Lead prompt 用裸工具名引用 `get_workspace_info` / `worker_status` / `read_worker`,而这些过去只在 Claude-lead 专属的 `orca_bridge` 里、Codex Lead 看不到,会制造稳定噪音。统一后这 3 个诊断工具以**同名裸工具**桥入全局可见的 `cindy_orca`,Claude 与 Codex Lead 都能解析到真实工具,噪音消除。Lead prompt 继续只用裸工具名;新增流控文案只声明 `interrupt_worker`、`get_worker_queue_status`、`merge_queued_messages` 的选择与原子性边界,并按 [`maker-core-and-agent-behavior.md`](maker-core-and-agent-behavior.md) §4 保持 system 段改动最小、用快照测试锁定。
-#### 6. Model 不可中途换,effort 可调(状态:不变量)
+#### 6. Agent/模型选择在发送边界应用(状态:不变量)
-对同一个 live worker session,中途换 model 应视为重建执行单元,不是普通请求参数。原因:model 切换会破坏 prompt/cache 前缀稳定,Claude SDK 也可能解析失败。effort 是 per-turn 参数,可以中途调。创建执行单元前可以选 model/effort;运行中 effort 可调,model 不可调。
+Lead/Worker 可在 Claude Code、Codex、Pi 三者间双向切换并选择模型;选择先登记为 pending intent,不打断当前轮次。跨 Agent 切换在下一次发送前关闭旧 runtime 并重建,保留协同身份;协同直发先调用 `applyPendingAgentSwitchIfIdle`,队列出队与恢复继续复用统一发送事务。已派发的本地回执使用实际接受消息的 runtime 的 Agent,不能返回切换前的 Worker 快照;仍在队列中的消息沿用当前 Agent,不预报尚未执行的切换。SSH 任务仍不支持跨 Agent 切换,用户不能借此改变 Agent 位置。effort 仍是 per-turn 参数。实现见 `sessionAgentSwitchHandler.ts`、`orcaInterAgentDispatcher.ts`、`orcaTeamService.ts` 与 `register.ts`;三者六个方向与 Lead/Worker 的回归见 `sessionAgentSwitchHandler.test.ts`、`orcaInterAgentDispatcher.test.ts`、`orcaTeamService.test.ts` 和 `makerSendTransaction.test.ts`。
+
+运行设备 Worker 的派发仍经 `maker:input:enqueue`,成功只确认投递到那台电脑,不等于模型已经执行。投递后经已有 `local-db:messages:around-client-id` 按该输入的 `clientId` 读取单条消息(`radius: 0`,正文限 1 字符);非 queued 回执的 Agent 取接受输入时写入的消息行 `agentKind`(`cc` 归一为 `claude-code`),不取入队前或之后的任务配置。尚未接受、旧端缺少引擎字段或读取失败时只回 queued,不预报待切换引擎,也不把已投递输入变成失败重派。普通派发与打断改派复用这一口径;不增加 wire 字段或改变共享链路。运行设备出队、恢复发送时,统一事务同时识别本机 `orcaRole` 与持久化的 `orcaRemoteLead`;切换应用后意图仍在则拒绝发送到旧 Agent,不信任输入来源标签来判断身份。失败只阻断该任务本次发送,不断开共享链路、不影响其他 Worker。回归见 `orcaRemoteWorkers.test.ts`、`orcaRemoteWorkerRuntime.test.ts` 与 `makerSendTransaction.test.ts`。
+
+执行设备上的真实 Worker 同样受原地切换边界约束:切换 handler 从任务行读取 `orcaRemoteLead`,用户不能通过显式 `agentDeviceId` 将它迁到第三台电脑;同位置的三 Agent/模型切换仍允许。既有供应商组内部立即换位置例外保持不变。手机模型面板在 Orca Agent 已位于另一台电脑时,目标 Harness 的预取、能力缓存、面板加载和选中校验均从那台电脑读取;切换意图仍交给任务所属电脑执行,不因此开放换电脑。
+Desktop 与 Mobile 同时按已有的 `orcaRemoteLead` 投影隐藏换电脑入口,不把执行设备 Worker 的空 `orcaRole` 误认为普通任务,也不改变其协同角色。旧控制端仍由上述主进程拒绝迁移,不增加 wire 字段。
+
+Desktop Orca 同 Agent 选模继续复用普通任务的窗口检查与确认弹窗,将本次核对的具体窗口随本机切换意图保留。未知窗口只表示选择可以暂存,不等于同意重建;发送前需要重建时,确认窗口必须匹配当时核实的窗口(含 Pi 最终窗口)。未匹配则保留意图、停止发送;重新选择该模型会重新检查。仅调整 effort/Fast 保留同一路由的确认,换模型/来源不能继承。device-link 不接受控制端提交窗口确认数字,普通任务原有行为保持不变。回归见 `orcaModelWindowSelection.test.ts`、`orcaModelSelectionIntent.test.ts` 和 Mobile `orcaModelSelection.test.ts`。
+执行设备上只有 `orcaRemoteLead` 的 Worker 同样遵守上述窗口确认要求:初次检查与 Pi 最终窗口检查均不能使用普通任务的发送时默认确认;Pi 也不能用旧确认数字覆盖当前核实的窗口。
+
+Orca Agent 在另一台电脑时,同 Agent 选择在发送边界重读执行电脑的授权目录,按同一来源与模型的已核实窗口检查当前占用;不能把点选时的确认值当成最新窗口或默认确认。在线与冷恢复均走已有窗口交接入口,需要交接但确认值与最新窗口不符、目录不可读或交接未完成时保留意图、不落库新选择。目录仍无已核实窗口时沿用热切语义,不拿旧确认值猜测窗口并重建。窗口核实后的提交再次校验任务归属;失败只阻断该任务的本次发送,不重连、不重派,不影响共享链路上的其它任务。回归见 `orcaRemoteModelWindowSelection.test.ts`。
Worker 创建与默认模型继承边界对历史短 ID 做 provider-aware 兼容:优先保留目标路由上
可用的精确 ID;只有精确匹配失败、候选来源属于 managed Gateway、且
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 7af4bc6a80..2b2af9200a 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -929,6 +929,18 @@ handler 无 sender 依赖;不加入共享任务访客白名单,不进入自
## 协同远端 Worker:Worker 在另一台电脑运行
+Orca 原地 Agent 切换补充边界:执行设备任务按既有 `orca_remote_lead` 判定,
+与 `orca_role` 一样拒绝用户换 Agent 位置,不新增 wire 字段或版本要求。
+Mobile 对已在另一台电脑运行的 Orca Agent,按所展示的模型目录所在电脑查询
+`maker:get-capabilities`;登记切换仍发给任务所在电脑。旧端保持原能力校验,
+不会因目标电脑未注册该 Harness 而回退到别的电脑执行。
+
+Desktop 本机 `maker:switch-session-agent` 的可选第 7 参增加
+`confirmedContextWindow`(正整数),仅供同 Agent 选模保留已核对的窗口。
+Renderer 与本机 Host 同包升级;不向 device-link 发送该字段,Host 对远程传入
+显式拒绝,沿用 SET_MODEL 的本机确认边界。无此字段仍可登记选择,但 Orca
+发送时若需要未确认的窗口重建,会保留意图并拒绝发送,用户可重新选择后确认。
+
与上一节方向相反:协同的 Lead 与团队留在 A,单个 Worker 的任务、目录、命令与文件都在 B(运行设备)。
B 上的 Worker 是一条普通任务,`sessions.orca_remote_lead`(migration 0124,JSON 见
`apps/desktop/src/shared/orcaRemoteWorker.ts`)记录派活电脑与 Lead;派活、停止与回报复用现有会话通道。