Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
test(desktop): cover Pi stop switch recovery (#3066)
nanacof2606c7c3b4e
diff --git a/apps/desktop/src/main/__tests__/fork.test.ts b/apps/desktop/src/main/__tests__/fork.test.tsindex 1c44f07892..179ef532ad 100644--- a/apps/desktop/src/main/__tests__/fork.test.ts+++ b/apps/desktop/src/main/__tests__/fork.test.ts@@ -342,6 +342,71 @@ describe('forkSessionAtMessage', () => {expect(result.parentSessionId).toBe('src-session');});+ it('pi path: creates a new SDK session but leaves business-session activation to first-send lazy-create', async () => {+ const target = makeMessageRow({ id: 'target-user', role: 'user', createdAt: 3000 });+ const priorUser = makeMessageRow({+ id: 'user-1',+ role: 'user',+ content: '"hi"',+ createdAt: 2000,+ });+ const priorAssistant = makeMessageRow({+ id: 'asst-1',+ role: 'assistant',+ content: '"hi back"',+ createdAt: 2500,+ });++ selectQueue.push([makeSourceRow({+ agentKind: 'pi',+ model: 'chatgpt/gpt-5.5',+ providerId: 'openai',+ sdkSessionId: 'pi-session-source',+ })]);+ selectQueue.push([target]);+ selectQueue.push([priorUser, priorAssistant]);+ selectQueue.push([makeSourceRow({+ agentKind: 'pi',+ model: 'chatgpt/gpt-5.5',+ providerId: 'openai',+ sdkSessionId: 'pi-session-forked',+ parentSessionId: 'src-session',+ forkedAtMessageId: 'target-user',+ })]);+ queryMock.mockResolvedValue([+ { role: 'user', content: '"later"' },+ { role: 'user', content: '"target"' },+ ]);+ forkSdkSessionMock.mockResolvedValue({+ newSdkSessionId: 'pi-session-forked',+ uuidMap: new Map<string, string>(),+ });++ const result = await forkSessionAtMessage('src-session', 'target-user');++ expect(forkSdkSessionMock).toHaveBeenCalledOnce();+ expect(forkSdkSessionMock).toHaveBeenCalledWith('pi', {+ sourceSdkSessionId: 'pi-session-source',+ upToMessageId: undefined,+ tailTurnsToDrop: 2,+ title: '[Fork] Project A',+ workingDir: '/work',+ remoteHostId: null,+ });+ const txArgs = txCalls.find((call) => call.name === 'fork.session')?.args as {+ newSession: Record<string, unknown>;+ };+ expect(txArgs.newSession).toMatchObject({+ agentKind: 'pi',+ model: 'chatgpt/gpt-5.5',+ providerId: 'openai',+ sdkSessionId: 'pi-session-forked',+ parentSessionId: 'src-session',+ forkedAtMessageId: 'target-user',+ });+ expect(result.parentSessionId).toBe('src-session');+ });+it('codex path: maps preparation or thread/fork failures to a diagnosable error', async () => {const target = makeMessageRow({ id: 'target-user', role: 'user', createdAt: 3000 });selectQueue.push([makeSourceRow({diff --git a/apps/desktop/src/main/__tests__/rewind.test.ts b/apps/desktop/src/main/__tests__/rewind.test.tsindex 6f85c0bdf7..c6d6721c63 100644--- a/apps/desktop/src/main/__tests__/rewind.test.ts+++ b/apps/desktop/src/main/__tests__/rewind.test.ts@@ -43,7 +43,7 @@ const writeWorktreeTreeForPathsMock = vi.fn();const gitExecMock = vi.fn();type FakeSession = {- agentKind: 'claude-code' | 'codex';+ agentKind: 'claude-code' | 'codex' | 'pi';sdkSessionId: string;workDir: string;remoteHostId: string | null;@@ -66,10 +66,15 @@ const getSessionMock = vi.fn(() => fakeSession);const getSessionMetaMock = vi.fn(async () =>fakeSession ? { sdkSessionId: fakeSession.sdkSessionId } : null,);-function useFakeSession(agentKind: 'claude-code' | 'codex') {+function useFakeSession(agentKind: 'claude-code' | 'codex' | 'pi') {fakeSession = {agentKind,- sdkSessionId: agentKind === 'codex' ? 'codex-thread-old' : 'sdk-uuid-old',+ sdkSessionId:+ agentKind === 'codex'+ ? 'codex-thread-old'+ : agentKind === 'pi'+ ? 'pi-session-old'+ : 'sdk-uuid-old',workDir: '/repo',remoteHostId: null,isTurnRunning: isTurnRunningMock,@@ -920,6 +925,38 @@ describe('commitRewindAtMessage', () => {expect(result.id).toBe('sess-1');});+ it('Pi: executes rewind after lazy activation establishes a live session', async () => {+ fakeSession = undefined;+ await expect(+ commitRewindAtMessage('sess-1', 'client-id'),+ ).rejects.toMatchObject({ code: 'NO_LIVE_QUERY' });+ expect(commitRewindFilesMock).not.toHaveBeenCalled();+ expect(txCalls).toHaveLength(0);+ getSessionMock.mockClear();++ useFakeSession('pi');+ commitRewindFilesMock.mockResolvedValueOnce({ sdkSessionId: 'pi-session-rewound' });+ selectQueue.push([makeUserMessageRow({ agentMeta: null })]);+ selectQueue.push([]);+ selectQueue.push([+ makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 }),+ makeUserMessageRow({ clientId: 'later-user', createdAt: 5000 }),+ ]);+ selectQueue.push([makeSessionRow({ agentKind: 'pi', sdkSessionId: 'pi-session-rewound' })]);++ const result = await commitRewindAtMessage('sess-1', 'client-id');++ expect(getSessionMock).toHaveBeenCalledTimes(2);+ expect(getSessionMock).toHaveBeenLastCalledWith('sess-1');+ expect(commitRewindFilesMock).toHaveBeenCalledOnce();+ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 2 });+ expect(txCalls.find((call) => call.name === 'rewind.commit')?.args).toMatchObject({+ sessionId: 'sess-1',+ sdkSessionId: 'pi-session-rewound',+ });+ expect(result.id).toBe('sess-1');+ });+it('Codex: previews file rewind savepoints before commit (legacy numstat 方向对调)', async () => {useFakeSession('codex');detectCwdMock.mockResolvedValueOnce({ gitInstalled: true, isGitRepo: true, repoRoot: '/repo', isInsideWorktree: false });diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.tsindex 63a24c11b5..75596d9644 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts@@ -4801,6 +4801,7 @@ describe('AgentInputCoordinator stop and drain boundaries', () => {it.each([{ agentKind: 'claude-code' as const, providerId: 'xd', model: 'claude-opus-5' },{ agentKind: 'codex' as const, providerId: 'xd', model: 'gpt-5.5' },+ { agentKind: 'pi' as const, providerId: 'openai', model: 'chatgpt/gpt-5.5' },])('invalidates an old abort token when $agentKind starts a new turn after a non-preserving stop',async ({ agentKind, providerId, model }) => {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.tsindex eb44d81547..38265ffef8 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts@@ -977,6 +977,58 @@ describe('maker SEND transaction', () => {expect(lazySession.send).toHaveBeenCalled();});+ it('activates a forked Pi business session once with the latest DB route on its first send', async () => {+ const lazySession = createSession({+ id: 'forked-pi-session',+ agentKind: 'pi',+ workDir: 'D:\\forked-pi',+ });+ const reconcileCreateOptsWithDb = vi.fn(async (_sessionId, createOpts) => {+ createOpts.agentKind = 'pi';+ createOpts.model = 'gpt-5.5';+ createOpts.providerId = 'xd';+ createOpts.resumeSessionId = 'pi-fork-jsonl';+ });+ const { deps } = createDeps({+ getSession: vi.fn(() => undefined),+ reconcileCreateOptsWithDb,+ bootstrapSession: vi.fn(async () => ({+ session: lazySession,+ didInjectOrcaInstructions: false,+ didInjectProjectContext: false,+ })),+ });+ const transaction = createMakerSendTransaction(deps);+ const staleCreateOpts: MakerSessionCreateOpts = {+ id: 'forked-pi-session',+ agentKind: 'pi',+ workingDir: 'D:\\forked-pi',+ model: 'chatgpt/gpt-5.5',+ providerId: 'openai',+ resumeSessionId: 'stale-pi-session',+ };++ await expect(+ transaction.sendToAgentAccepted('forked-pi-session', 'first fork message', staleCreateOpts),+ ).resolves.toMatchObject({+ accepted: true,+ outcome: { kind: 'session-dispatch', dispatched: true },+ });++ expect(reconcileCreateOptsWithDb).toHaveBeenCalledOnce();+ expect(deps.bootstrapSession).toHaveBeenCalledOnce();+ expect(deps.bootstrapSession).toHaveBeenCalledWith(expect.objectContaining({+ id: 'forked-pi-session',+ agentKind: 'pi',+ model: 'gpt-5.5',+ providerId: 'xd',+ resumeSessionId: 'pi-fork-jsonl',+ }));+ expect(deps.broadcastSessionCreated).toHaveBeenCalledOnce();+ expect(lazySession.send).toHaveBeenCalledOnce();+ expect(lazySession.send).toHaveBeenCalledWith('first fork message', expect.anything());+ });+it('returns lazy-create failure without dispatching when bootstrap fails', async () => {const { deps } = createDeps({getSession: vi.fn(() => undefined),diff --git a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.tsindex ead5cbf7ef..907f60a12d 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts@@ -7,9 +7,27 @@ import {} from '../../maker-host/session-provider-store.js';import { applyRuntimeSetModelChange, type RuntimeSetModelMaker } from '../runtimeSetModel.js';+const sessionProviderWriteObserver = vi.hoisted(() => ({+ current: null as ((sessionId: string, providerId: string | null) => void) | null,+}));++vi.mock('../../maker-host/session-provider-store.js', async (importOriginal) => {+ const actual = await importOriginal<+ typeof import('../../maker-host/session-provider-store.js')+ >();+ return {+ ...actual,+ setSessionProvider: (sessionId: string, providerId: string | null) => {+ actual.setSessionProvider(sessionId, providerId);+ sessionProviderWriteObserver.current?.(sessionId, providerId);+ },+ };+});+const touchedSessions = new Set<string>();afterEach(() => {+ sessionProviderWriteObserver.current = null;for (const sessionId of touchedSessions) {clearSessionProvider(sessionId);}@@ -736,6 +754,50 @@ describe('applyRuntimeSetModelChange', () => {expect(getSessionProvider(sessionId)).toBe('xd');});+ it('closes a stopped Pi runtime before publishing the new route and waking its queued first send', async () => {+ const sessionId = rememberSession('runtime-set-model-pi-stop-switch');+ setSessionProvider(sessionId, 'openai');+ const order: string[] = [];+ const closeSession = vi.fn(async () => {+ order.push('close');+ expect(getSessionProvider(sessionId)).toBe('openai');+ });+ sessionProviderWriteObserver.current = (writtenSessionId, providerId) => {+ if (writtenSessionId === sessionId && providerId === 'xd') order.push('route');+ };+ const wakeSessionInputQueue = vi.fn(() => {+ order.push('wake');+ expect(getSessionProvider(sessionId)).toBe('xd');+ });+ const maker: RuntimeSetModelMaker = {+ getSession: () => ({+ agentKind: 'pi',+ remoteHostId: null,+ model: 'chatgpt/gpt-5.5',+ setModel: vi.fn(async () => {}),+ }),+ listActiveSessions: () => [+ { id: sessionId, agentKind: 'pi', remoteHostId: null, isTurnRunning: () => false },+ ],+ closeSession,+ };++ await expect(applyRuntimeSetModelChange({+ maker,+ sessionId,+ model: 'gpt-5.5',+ providerId: 'xd',+ clearPendingCredentialSwitch: vi.fn((_sid, opts) => {+ expect(opts).toEqual({ wake: false });+ }),+ wakeSessionInputQueue,+ })).resolves.toEqual({ status: 'applied' });++ expect(order).toEqual(['close', 'route', 'wake']);+ expect(closeSession).toHaveBeenCalledOnce();+ expect(wakeSessionInputQueue).toHaveBeenCalledOnce();+ });+it('falls back to the busy throw when no pending channel is injected', async () => {// 老调用方(未注入 registerPendingCredentialSwitch)保持旧 fail-closed 语义。const sessionId = rememberSession('runtime-set-model-defer-no-channel');