Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复 Stop 后灵动岛误报完成 (#278)
Dash761f106f4cb6
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex 29c24e9ebd..ddceba9456 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -14,6 +14,8 @@ const sourcePath = resolve(__dirname, '..', 'maker-ipc', 'register.ts');const source = readFileSync(sourcePath, 'utf8').replace(/\r\n?/g, '\n');const usageSourcePath = resolve(__dirname, '..', 'maker-ipc', 'usage.ts');const usageSource = readFileSync(usageSourcePath, 'utf8').replace(/\r\n?/g, '\n');+const hookControlSourcePath = resolve(__dirname, '..', 'hook-control', 'ipc.ts');+const hookControlSource = readFileSync(hookControlSourcePath, 'utf8').replace(/\r\n?/g, '\n');describe('maker:event hot path ordering', () => {it('broadcasts EVENT before usage/context/island/idle side effects', () => {@@ -130,12 +132,23 @@ describe('maker:event hot path ordering', () => {expect(abortContext).toContain('isTerminalTurnErrorEvent(event)');});- it('isolates Agent Island interaction updates after renderer delivery', () => {+ it('rejects stale Agent Island interactions before renderer delivery', () => {const interactionListenerSource = extractInstallDesktopInteractionListenerSource();+ const epochCaptureIndex = interactionListenerSource.indexOf(+ 'getAgentIslandService()?.captureInteractionEpoch(session.id)',+ );+ const currentEpochCheckIndex = interactionListenerSource.indexOf(+ 'getAgentIslandService()?.isInteractionCurrent(',+ );+ const flushIndex = interactionListenerSource.indexOf('flushAssistantBlock(session.id);');const broadcastIndex = interactionListenerSource.indexOf('broadcastToAllWindows(MAKER_PUSH.INTERACTION_REQUEST');const pendingIndex = interactionListenerSource.indexOf('pendingInteractionResolvers.set(req.requestId, entry);');const islandIndex = interactionListenerSource.indexOf('handleAgentIslandInteractionAfterBroadcast(');+ expect(epochCaptureIndex).toBeGreaterThanOrEqual(0);+ expect(currentEpochCheckIndex).toBeGreaterThan(epochCaptureIndex);+ expect(flushIndex).toBeGreaterThan(currentEpochCheckIndex);+ expect(broadcastIndex).toBeGreaterThan(flushIndex);expect(broadcastIndex).toBeGreaterThanOrEqual(0);expect(pendingIndex).toBeGreaterThan(broadcastIndex);expect(islandIndex).toBeGreaterThan(pendingIndex);@@ -173,6 +186,77 @@ describe('maker:event hot path ordering', () => {expect(closeSessionHandler).not.toContain('handleSessionClosed');});+ it('marks Agent Island stopped before provider abort tails can arrive', () => {+ const coordinatorAbortStart = source.indexOf('abortSession: async (sessionId) => {');+ const coordinatorAbortEnd = source.indexOf('\n isTurnRunning:', coordinatorAbortStart);+ const coordinatorAbortSource = source.slice(coordinatorAbortStart, coordinatorAbortEnd);+ const directAbortStart = source.indexOf('ipcMain.handle(MAKER_INVOKE.ABORT_SESSION');+ const directAbortEnd = source.indexOf(+ '\n ipcMain.handle(MAKER_INVOKE.CLOSE_SESSION',+ directAbortStart,+ );+ const directAbortSource = source.slice(directAbortStart, directAbortEnd);+ const hookAbortStart = hookControlSource.indexOf('abortSession: async (sessionId) => {');+ const hookAbortEnd = hookControlSource.indexOf('\n // session.archive', hookAbortStart);+ const hookAbortSource = hookControlSource.slice(hookAbortStart, hookAbortEnd);++ expect(source).toContain('function handleAgentIslandSessionStopped(');+ expect(coordinatorAbortStart).toBeGreaterThanOrEqual(0);+ expect(coordinatorAbortEnd).toBeGreaterThan(coordinatorAbortStart);+ expectOrder(+ coordinatorAbortSource,+ 'const sess = maker.getSession(sessionId);',+ 'if (!sess) return;',+ );+ expectOrder(+ coordinatorAbortSource,+ 'if (!sess) return;',+ 'handleAgentIslandSessionStopped(sess);',+ );+ expectOrder(+ coordinatorAbortSource,+ 'handleAgentIslandSessionStopped(sess);',+ 'await sess.abort();',+ );+ expect(directAbortStart).toBeGreaterThanOrEqual(0);+ expect(directAbortEnd).toBeGreaterThan(directAbortStart);+ expectOrder(+ directAbortSource,+ 'const sess = maker.getSession(sessionId);',+ 'if (!sess) return;',+ );+ expectOrder(+ directAbortSource,+ 'if (!sess) return;',+ 'handleAgentIslandSessionStopped(sess);',+ );+ expectOrder(+ directAbortSource,+ 'handleAgentIslandSessionStopped(sess);',+ 'await sess.abort();',+ );+ expect(hookAbortStart).toBeGreaterThanOrEqual(0);+ expect(hookAbortEnd).toBeGreaterThan(hookAbortStart);+ expectOrder(+ hookAbortSource,+ 'const session = getMaker().getSession(sessionId);',+ 'if (!session) return;',+ );+ expectOrder(+ hookAbortSource,+ 'if (!session) return;',+ 'getAgentIslandService()?.handleSessionStopped(',+ );+ expect(hookAbortSource).toContain(+ "log.warn('Agent Island session stop update failed before hook provider abort'",+ );+ expectOrder(+ hookAbortSource,+ 'getAgentIslandService()?.handleSessionStopped(',+ 'await session.abort();',+ );+ });+it('keeps Codex subscription value out of real session cost totals', () => {const wireSessionSource = extractWireSessionSource();const codexDoneIndex = wireSessionSource.indexOf("event.type === 'done' && event.source === 'codex'");diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.tsindex 2d9d156516..d5202fc381 100644--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts@@ -251,11 +251,13 @@ describe('sendToSession ordering', () => {expect(createBranch).toContain("assertDesktopSendDispatched(sendResult, 'send_to_session create');");expect(liveBranch).toContain('const sendResult = await sendUserMessageWithAwaitedGitBaseline(');expect(liveBranch).toContain('live,');- expect(liveBranch).toContain('{ planMode: false, onAccepted: persistUserMessage },');+ expect(liveBranch).toContain('onAccepted: persistUserMessage,');+ expect(liveBranch).toContain('onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),');expect(liveBranch).toContain("assertDesktopSendDispatched(sendResult, 'send_to_session live');");expect(resumedBranch).toContain('const sendResult = await sendUserMessageWithAwaitedGitBaseline(');expect(resumedBranch).toContain('session,');- expect(resumedBranch).toContain('{ planMode: false, onAccepted: persistUserMessage },');+ expect(resumedBranch).toContain('onAccepted: persistUserMessage,');+ expect(resumedBranch).toContain('onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),');expect(resumedBranch).toContain("assertDesktopSendDispatched(sendResult, 'send_to_session resumed');");});@@ -315,9 +317,10 @@ describe('sendToSession ordering', () => {const acceptedBlock = extractBetween(createBranch,'onAccepted: async () => {',- ' },\n });',+ ' },\n onDispatching:',);- const sendCallEndNeedle = ' },\n });';+ const sendCallEndNeedle =+ ' onDispatching: () => dispatchAgentIslandUserPrompt(session.id),\n });';const afterSendResolves = createBranch.slice(createBranch.indexOf(sendCallEndNeedle) + sendCallEndNeedle.length,);@@ -365,6 +368,8 @@ describe('sendToSession ordering', () => {expect(makerSendCreateDbMessageBlock).not.toContain('notifyAgentIslandUserPrompt(');expect(makerSendPreviewHookBlock).toContain('previewUserPrompt: (session, content, options) => {');expect(makerSendPreviewHookBlock).toContain('notifyAgentIslandUserPrompt(session, content, options);');+ expect(makerSendPreviewHookBlock).toContain('dispatchUserPromptPreview: (sessionId) => {');+ expect(makerSendPreviewHookBlock).toContain('dispatchAgentIslandUserPrompt(sessionId);');expect(makerSendPreviewHookBlock).toContain('commitUserPromptPreview: (sessionId, clientId) => {');expect(makerSendPreviewHookBlock).toContain('rollbackUserPromptPreview: (sessionId, clientId, source) => {');});@@ -397,7 +402,8 @@ describe('sendToSession ordering', () => {expect(liveBranch).toContain('const sendResult = await sendUserMessageWithAwaitedGitBaseline(');expect(liveBranch).toContain('live,');- expect(liveBranch).toContain('{ planMode: false, onAccepted: persistUserMessage },');+ expect(liveBranch).toContain('onAccepted: persistUserMessage,');+ expect(liveBranch).toContain('onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),');expect(liveBranch).not.toContain('await persistUserMessage();');expect(liveBranch).toContain('if (isSessionRunningError(err))');expect(liveBranch).toContain('await enqueueSendToSessionMessage({');@@ -414,7 +420,8 @@ describe('sendToSession ordering', () => {expect(resumedBranch).toContain('const sendResult = await sendUserMessageWithAwaitedGitBaseline(');expect(resumedBranch).toContain('session,');- expect(resumedBranch).toContain('{ planMode: false, onAccepted: persistUserMessage },');+ expect(resumedBranch).toContain('onAccepted: persistUserMessage,');+ expect(resumedBranch).toContain('onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),');expect(resumedBranch).not.toContain('await persistUserMessage();');expect(resumedBranch).toContain('if (isSessionRunningError(err))');expect(resumedBranch).toContain('await enqueueSendToSessionMessage({');diff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.tsindex f9e50b3345..5c118765ab 100644--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts@@ -21,9 +21,22 @@ import {import { AGENT_ISLAND_DISPLAY_CONFIG } from '../displayConfig.js';import type { AgentIslandNativeFrame } from '../MacAgentIslandNativeHost.js';import { markAppContentWindow } from '../../windowFocusClassifier.js';+import type { AgentIslandService } from '../service.js';const REMOTE_DAEMON_CLOSED_REASON = 'remote_daemon_closed';+function handleInteractionRequestForTest(+ service: AgentIslandService,+ meta: Parameters<AgentIslandService['handleInteractionRequest']>[0],+ request: InteractionRequest,+): void {+ service.handleInteractionRequest(+ meta,+ request,+ service.captureInteractionEpoch(meta.sessionId),+ );+}+const mocks = vi.hoisted(() => ({getSessionRowSnapshot: vi.fn<() => Promise<{status: string;@@ -183,6 +196,18 @@ function doneEvent(): AgentEvent {};}+function cancelledDoneEvent(turnId?: string): AgentEvent {+ return {+ type: 'done',+ source: 'codex',+ data: {+ type: 'codex/event/task_complete',+ cancelled: true,+ ...(turnId ? { raw: { id: turnId } } : {}),+ },+ };+}+function textEvent(text: string, isFinal = false): AgentEvent {return {type: 'text',@@ -631,7 +656,7 @@ describe('AgentIslandService native publishing', () => {// passive 清点),不得向远端发 completed 收尾包 —— 会把手机列表行的等待授权// 指示误清成"已完成",且没有后续事件能补回。service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'run tests');- service.handleInteractionRequest(+ handleInteractionRequestForTest(service,{ sessionId: 's1' },{kind: 'permission',@@ -830,7 +855,7 @@ describe('AgentIslandService native publishing', () => {const sessionUpdate = { destination: 'session', type: 'addRules' };service.setPermissionResolver(resolver);- service.handleInteractionRequest(+ handleInteractionRequestForTest(service,{ sessionId: 's1' },{kind: 'permission',@@ -865,7 +890,7 @@ describe('AgentIslandService native publishing', () => {syncEnabledForTest(service, publish);service.setPermissionResolver(resolver);- service.handleInteractionRequest(+ handleInteractionRequestForTest(service,{ sessionId: 's1', agentKind: 'codex' },{kind: 'permission',@@ -907,7 +932,7 @@ describe('AgentIslandService native publishing', () => {});syncEnabledForTest(service, publish);- service.handleInteractionRequest(+ handleInteractionRequestForTest(service,{ sessionId: 's1', agentKind: 'codex' },{kind: 'permission',@@ -947,7 +972,7 @@ describe('AgentIslandService native publishing', () => {syncEnabledForTest(service, publish);service.setPermissionResolver(resolver);- service.handleInteractionRequest(+ handleInteractionRequestForTest(service,{ sessionId: 's1', agentKind: 'claude-code' },{kind: 'permission',@@ -956,7 +981,7 @@ describe('AgentIslandService native publishing', () => {input: { query: 'first' },},);- service.handleInteractionRequest(+ handleInteractionRequestForTest(service,{ sessionId: 's1', agentKind: 'claude-code' },{kind: 'permission',@@ -999,7 +1024,7 @@ describe('AgentIslandService native publishing', () => {});syncEnabledForTest(service, publish);- service.handleInteractionRequest(+ handleInteractionRequestForTest(service,{ sessionId: 's1', agentKind: 'claude-code' },{kind: 'permission',@@ -1008,7 +1033,7 @@ describe('AgentIslandService native publishing', () => {input: { query: 'first' },},);- service.handleInteractionRequest(+ handleInteractionRequestForTest(service,{ sessionId: 's1', agentKind: 'claude-code' },{kind: 'permission',@@ -1053,7 +1078,7 @@ describe('AgentIslandService native publishing', () => {});syncEnabledForTest(service, publish);- service.handleInteractionRequest(+ handleInteractionRequestForTest(service,{ sessionId: 's1', agentKind: 'claude-code' },{kind: 'permission',@@ -1857,6 +1882,484 @@ describe('AgentIslandService native publishing', () => {expect(playSound).toHaveBeenNthCalledWith(2, customSound('complete.wav'));});+ it('removes user-stopped sessions and ignores provider completion tails without playing completion sound', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {+ void state;+ void frameOrFrames;+ return true;+ });+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);+ const service = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, publish, playSound },+ });+ syncEnabledForTest(service, publish);+ service.setSoundSettings({+ enabled: true,+ sounds: {+ ...DEFAULT_AGENT_ISLAND_SOUND_SETTINGS.sounds,+ start: customSound('start.wav'),+ complete: customSound('complete.wav'),+ },+ });++ service.handleUserPrompt({ sessionId: 'codex-stop', agentKind: 'codex' }, 'run tests');+ service.handleUserPrompt({ sessionId: 'claude-stop', agentKind: 'claude-code' }, 'run tests');+ playSound.mockClear();++ service.handleSessionStopped('codex-stop');+ service.handleAgentEvent(+ { sessionId: 'codex-stop', agentKind: 'codex' },+ cancelledDoneEvent(),+ );+ service.handleSessionStopped('claude-stop');+ service.handleAgentEvent(+ { sessionId: 'claude-stop', agentKind: 'claude-code' },+ { type: 'status', source: 'claude-code', data: { isRunning: false, status: 'Done' } },+ );+ service.handleAgentEvent(+ { sessionId: 'claude-stop', agentKind: 'claude-code' },+ { type: 'done', source: 'claude-code', data: { reason: 'turn_interrupted' } },+ );++ expect(playSound).not.toHaveBeenCalled();+ expect(publish.mock.calls.at(-1)?.[0].sessions).toEqual([]);++ service.handleUserPrompt({ sessionId: 'claude-stop', agentKind: 'claude-code' }, 'run again');+ service.handleAgentEvent(+ { sessionId: 'claude-stop', agentKind: 'claude-code' },+ { type: 'status', source: 'claude-code', data: { isRunning: true, status: 'Thinking...' } },+ );+ service.handleAgentEvent(+ { sessionId: 'claude-stop', agentKind: 'claude-code' },+ { type: 'status', source: 'claude-code', data: { isRunning: false, status: 'Done' } },+ );++ expect(playSound).toHaveBeenCalledWith(customSound('complete.wav'));+ expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({+ sessionId: 'claude-stop',+ phase: 'completed',+ });+ });++ it('removes a cancelled run that has no explicit Stop boundary', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {+ void state;+ void frameOrFrames;+ return true;+ });+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);+ const service = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, publish, playSound },+ });+ syncEnabledForTest(service, publish);+ service.setSoundSettings({+ enabled: true,+ sounds: {+ ...DEFAULT_AGENT_ISLAND_SOUND_SETTINGS.sounds,+ start: customSound('start.wav'),+ complete: customSound('complete.wav'),+ },+ });+ const meta = { sessionId: 'codex-permission-tighten', agentKind: 'codex' as const };+ service.handleUserPrompt(meta, 'run tests');+ playSound.mockClear();++ service.handleAgentEvent(meta, cancelledDoneEvent());++ expect(playSound).not.toHaveBeenCalled();+ expect(publish.mock.calls.at(-1)?.[0].sessions).toEqual([]);+ });++ it('keeps a replacement turn running while ordinary completion tails from the stopped turn drain', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {+ void state;+ void frameOrFrames;+ return true;+ });+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);+ const service = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, publish, playSound },+ });+ syncEnabledForTest(service, publish);+ service.setSoundSettings({+ enabled: true,+ sounds: {+ ...DEFAULT_AGENT_ISLAND_SOUND_SETTINGS.sounds,+ start: customSound('start.wav'),+ complete: customSound('complete.wav'),+ },+ });+ const meta = { sessionId: 'claude-replacement', agentKind: 'claude-code' as const };+ service.handleUserPrompt(meta, 'first turn');+ service.handleSessionStopped(meta.sessionId);+ service.handleUserPrompt(meta, 'replacement turn');+ playSound.mockClear();++ service.handleAgentEvent(+ meta,+ { type: 'status', source: 'claude-code', data: { isRunning: false, status: 'Done' } },+ );+ service.handleAgentEvent(+ meta,+ { type: 'done', source: 'claude-code', data: { reason: 'turn_interrupted' } },+ );++ expect(playSound).not.toHaveBeenCalled();+ expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({+ sessionId: meta.sessionId,+ phase: 'running',+ });++ service.handleAgentEvent(+ meta,+ { type: 'status', source: 'claude-code', data: { isRunning: true, status: 'Thinking...' } },+ );+ service.handleAgentEvent(+ meta,+ { type: 'status', source: 'claude-code', data: { isRunning: false, status: 'Done' } },+ );++ expect(playSound).toHaveBeenCalledTimes(1);+ expect(playSound).toHaveBeenCalledWith(customSound('complete.wav'));+ expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({+ sessionId: meta.sessionId,+ phase: 'completed',+ });+ });++ it('accepts replacement-turn interaction requests before its running status arrives', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {+ void state;+ void frameOrFrames;+ return true;+ });+ const service = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, publish },+ });+ const resolver = vi.fn(() => true);+ const meta = { sessionId: 'replacement-interaction', agentKind: 'claude-code' as const };+ syncEnabledForTest(service, publish);+ service.setPermissionResolver(resolver);+ service.handleUserPrompt(meta, 'first turn');+ service.handleSessionStopped(meta.sessionId);+ service.handleUserPrompt(meta, 'replacement turn');+ service.handleUserPromptDispatching(meta.sessionId);++ handleInteractionRequestForTest(service,+ meta,+ {+ kind: 'permission',+ requestId: 'replacement-request',+ toolName: 'Bash',+ input: { command: 'pnpm test' },+ },+ );++ expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({+ sessionId: meta.sessionId,+ phase: 'needs-interaction',+ permissionAction: { requestId: 'replacement-request' },+ });++ service.handlePermissionAction({ requestId: 'replacement-request', action: 'allow' });++ expect(resolver).toHaveBeenCalledWith('replacement-request', {+ kind: 'permission',+ behavior: 'allow',+ permissionUpdates: undefined,+ });+ });++ it('rejects an interaction captured before the Stop and replacement prompt boundary', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {+ void state;+ void frameOrFrames;+ return true;+ });+ const service = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, publish },+ });+ const resolver = vi.fn(() => true);+ const meta = { sessionId: 'stale-interaction', agentKind: 'claude-code' as const };+ syncEnabledForTest(service, publish);+ service.setPermissionResolver(resolver);+ service.handleUserPrompt(meta, 'first turn');+ const staleInteractionEpoch = service.captureInteractionEpoch(meta.sessionId);+ service.handleSessionStopped(meta.sessionId);+ service.handleUserPrompt(meta, 'replacement turn');++ service.handleInteractionRequest(+ meta,+ {+ kind: 'permission',+ requestId: 'stale-request',+ toolName: 'Bash',+ input: { command: 'rm -rf build' },+ },+ staleInteractionEpoch,+ );++ expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({+ sessionId: meta.sessionId,+ phase: 'running',+ permissionAction: null,+ });++ service.handlePermissionAction({ requestId: 'stale-request', action: 'allow' });+ expect(resolver).not.toHaveBeenCalled();+ });++ it('rejects an old interaction that enters after replacement preview but before dispatch', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {+ void state;+ void frameOrFrames;+ return true;+ });+ const service = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, publish },+ });+ const meta = { sessionId: 'preview-race-interaction', agentKind: 'claude-code' as const };+ syncEnabledForTest(service, publish);+ service.handleUserPrompt(meta, 'first turn');+ service.handleSessionStopped(meta.sessionId);+ service.handleUserPrompt(meta, 'replacement turn');++ const staleEpoch = service.captureInteractionEpoch(meta.sessionId);+ expect(service.isInteractionCurrent(meta.sessionId, staleEpoch)).toBe(false);++ service.handleUserPromptDispatching(meta.sessionId);+ expect(service.isInteractionCurrent(meta.sessionId, staleEpoch)).toBe(false);+ expect(service.isInteractionCurrent(+ meta.sessionId,+ service.captureInteractionEpoch(meta.sessionId),+ )).toBe(true);+ });++ it('restores stop-tail suppression when a replacement prompt preview rolls back', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {+ void state;+ void frameOrFrames;+ return true;+ });+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);+ const service = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, publish, playSound },+ });+ syncEnabledForTest(service, publish);+ service.setSoundSettings({+ enabled: true,+ sounds: {+ ...DEFAULT_AGENT_ISLAND_SOUND_SETTINGS.sounds,+ start: customSound('start.wav'),+ complete: customSound('complete.wav'),+ },+ });+ const meta = { sessionId: 'rollback-stop', agentKind: 'claude-code' as const };+ service.handleUserPrompt(meta, 'run tests');+ service.handleSessionStopped(meta.sessionId);+ const stoppedInteractionEpoch = service.captureInteractionEpoch(meta.sessionId);+ playSound.mockClear();++ service.handleUserPrompt(meta, 'retry', { clientId: 'retry-client' });+ service.rollbackUserPrompt(meta.sessionId, 'retry-client');+ expect(service.captureInteractionEpoch(meta.sessionId)).toBe(stoppedInteractionEpoch);+ service.handleAgentEvent(+ meta,+ { type: 'status', source: 'claude-code', data: { isRunning: false, status: 'Done' } },+ );++ expect(playSound).not.toHaveBeenCalled();+ expect(publish.mock.calls.at(-1)?.[0].sessions).toEqual([]);+ });++ it('ignores a stale cancelled terminal event before a replacement turn dispatches', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {+ void state;+ void frameOrFrames;+ return true;+ });+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);+ const service = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, publish, playSound },+ });+ syncEnabledForTest(service, publish);+ service.setSoundSettings({+ enabled: true,+ sounds: {+ ...DEFAULT_AGENT_ISLAND_SOUND_SETTINGS.sounds,+ start: customSound('start.wav'),+ complete: customSound('complete.wav'),+ },+ });+ const meta = { sessionId: 'codex-stop', agentKind: 'codex' as const };+ service.handleUserPrompt(meta, 'run tests');+ service.handleAgentEvent(meta, {+ type: 'status',+ source: 'codex',+ data: { isRunning: true, status: 'Generating...', turnId: 'turn-stopped' },+ });+ service.handleSessionStopped(meta.sessionId, 'turn-stopped');+ service.handleUserPrompt(meta, 'replacement turn');+ playSound.mockClear();++ service.handleAgentEvent(meta, cancelledDoneEvent('turn-stopped'));++ expect(playSound).not.toHaveBeenCalled();+ expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({+ sessionId: meta.sessionId,+ phase: 'running',+ });+ });++ it('ignores an identified stopped-turn cancellation after the replacement is running', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {+ void state;+ void frameOrFrames;+ return true;+ });+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);+ const service = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, publish, playSound },+ });+ syncEnabledForTest(service, publish);+ const meta = { sessionId: 'codex-running-replacement', agentKind: 'codex' as const };+ service.handleUserPrompt(meta, 'first turn');+ service.handleAgentEvent(meta, {+ type: 'status',+ source: 'codex',+ data: { isRunning: true, status: 'Generating...', turnId: 'turn-stopped' },+ });+ service.handleSessionStopped(meta.sessionId, 'turn-stopped');+ service.handleUserPrompt(meta, 'replacement turn');+ service.handleUserPromptDispatching(meta.sessionId);+ service.handleAgentEvent(meta, {+ type: 'status',+ source: 'codex',+ data: { isRunning: true, status: 'Generating...', turnId: 'turn-replacement' },+ });+ playSound.mockClear();++ service.handleAgentEvent(meta, cancelledDoneEvent('turn-stopped'));++ expect(playSound).not.toHaveBeenCalled();+ expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({+ sessionId: meta.sessionId,+ phase: 'running',+ });+ });++ it('removes a replacement turn cancelled after its vendor dispatch boundary', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {+ void state;+ void frameOrFrames;+ return true;+ });+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);+ const service = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, publish, playSound },+ });+ syncEnabledForTest(service, publish);+ const meta = { sessionId: 'codex-replacement-cancelled', agentKind: 'codex' as const };+ service.handleUserPrompt(meta, 'first turn');+ service.handleAgentEvent(meta, {+ type: 'status',+ source: 'codex',+ data: { isRunning: true, status: 'Generating...', turnId: 'turn-stopped' },+ });+ service.handleSessionStopped(meta.sessionId, 'turn-stopped');+ service.handleUserPrompt(meta, 'replacement turn');+ service.handleUserPromptDispatching(meta.sessionId);+ playSound.mockClear();++ service.handleAgentEvent(meta, cancelledDoneEvent('turn-replacement'));++ expect(playSound).not.toHaveBeenCalled();+ expect(publish.mock.calls.at(-1)?.[0].sessions).toEqual([]);+ });++ it('clears an older provider turn id when a later stop cannot identify its turn', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {+ void state;+ void frameOrFrames;+ return true;+ });+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);+ const service = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, publish, playSound },+ });+ syncEnabledForTest(service, publish);+ const meta = { sessionId: 'codex-stop-without-turn-id', agentKind: 'codex' as const };+ service.handleUserPrompt(meta, 'first turn');+ service.handleSessionStopped(meta.sessionId, 'turn-from-earlier-stop');+ service.handleSessionStopped(meta.sessionId);+ service.handleUserPrompt(meta, 'replacement turn');+ service.handleUserPromptDispatching(meta.sessionId);+ playSound.mockClear();++ service.handleAgentEvent(meta, cancelledDoneEvent('turn-from-earlier-stop'));++ expect(playSound).not.toHaveBeenCalled();+ expect(publish.mock.calls.at(-1)?.[0].sessions).toEqual([]);+ });++ it('clears silenced-run bookkeeping when a session is stopped', async () => {+ const { AgentIslandService } = await import('../service.js');+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {+ void state;+ void frameOrFrames;+ return true;+ });+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);+ const service = new AgentIslandService({+ getMainWindow: () => null,+ nativeHost: { failed: false, publish, playSound },+ });+ syncEnabledForTest(service, publish);+ service.setSoundSettings({+ enabled: true,+ sounds: {+ ...DEFAULT_AGENT_ISLAND_SOUND_SETTINGS.sounds,+ start: customSound('start.wav'),+ },+ });+ const meta = { sessionId: 'silenced-stop', agentKind: 'claude-code' as const };+ service.handleScheduleEvent({+ type: 'silenced',+ scheduleId: 'schedule-1',+ runId: 'run-1',+ sessionId: meta.sessionId,+ });+ service.handleUserPrompt(meta, 'scheduled run');+ service.handleSessionStopped(meta.sessionId);+ playSound.mockClear();++ service.handleUserPrompt(meta, 'manual replacement');++ expect(playSound).toHaveBeenCalledWith(customSound('start.wav'));+ });+it('plays the completion sound when the completed visible session is smart-suppressed', async () => {const { AgentIslandService } = await import('../service.js');const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {@@ -2782,7 +3285,7 @@ describe('AgentIslandService native publishing', () => {input: { command: 'pnpm test' },displayName: 'Run command',};- service.handleInteractionRequest({ sessionId: 's1', agentKind: 'codex' }, request);+ handleInteractionRequestForTest(service, { sessionId: 's1', agentKind: 'codex' }, request);expect(publish.mock.calls.at(-1)?.[0]).toMatchObject({ mode: 'expanded' });expect(latestNativeFrame(publish)).toMatchObject({ width: 800 });@@ -3414,7 +3917,7 @@ describe('AgentIslandService native publishing', () => {displayName: 'Run command',};- service.handleInteractionRequest({ sessionId: 's1', agentKind: 'codex' }, request);+ handleInteractionRequestForTest(service, { sessionId: 's1', agentKind: 'codex' }, request);const framesById = new Map(latestNativeFrames(publish).map((frame) => [frame.displayId, frame]));expect(framesById.get(2)).toMatchObject({diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.tsindex d23707a477..46d39e098e 100644--- a/apps/desktop/src/main/agent-island/service.ts+++ b/apps/desktop/src/main/agent-island/service.ts@@ -231,10 +231,20 @@ export class AgentIslandService {private readonly silencedRunHadAttention = new Map<string, boolean>();private readonly silencedRunClearTimers = new Map<string, ReturnType<typeof setTimeout>>();private readonly mutedCompletionSoundSessionIds = new Set<string>();+ private readonly stoppedSessionIds = new Set<string>();+ private readonly replacementTurnPendingSessionIds = new Set<string>();+ private readonly replacementTurnDispatchingSessionIds = new Set<string>();+ private readonly stoppedProviderTurnIdBySession = new Map<string, string>();+ private readonly interactionEpochBySession = new Map<string, number>();+ private interactionEpochSequence = 0;private readonly sessionHadAttentionAtRunStart = new Map<string, boolean>();private readonly userPromptRollbackTokens = new Map<string, {state: AgentIslandUserPromptRollbackToken;attention: { existed: boolean; value: boolean };+ interactionEpoch: { existed: boolean; value: number };+ wasStopped: boolean;+ wasReplacementTurnPending: boolean;+ wasReplacementTurnDispatching: boolean;}>();private readonly deferredCompletions = new Map<string, { event: AgentEvent; suppressAttention: boolean }>();private readonly deferredRemoteAuthErrors = new Map<string, {@@ -542,6 +552,11 @@ export class AgentIslandService {this.silencedSessionRunIds.clear();this.silencedRunHadAttention.clear();this.mutedCompletionSoundSessionIds.clear();+ this.stoppedSessionIds.clear();+ this.replacementTurnPendingSessionIds.clear();+ this.replacementTurnDispatchingSessionIds.clear();+ this.stoppedProviderTurnIdBySession.clear();+ this.interactionEpochBySession.clear();this.sessionHadAttentionAtRunStart.clear();this.userPromptRollbackTokens.clear();this.deferredCompletions.clear();@@ -581,6 +596,49 @@ export class AgentIslandService {handleAgentEvent(meta: AgentIslandSessionMeta, event: AgentEvent): void {const hydrated = this.hydrateMeta(meta);+ const providerTurnId = providerTurnIdFromAgentEvent(event);+ const replacementPending =+ this.replacementTurnPendingSessionIds.has(hydrated.sessionId);+ const stoppedProviderTurnId =+ this.stoppedProviderTurnIdBySession.get(hydrated.sessionId);+ if (isCompletionDoneEvent(event) && providerTurnId && stoppedProviderTurnId) {+ if (providerTurnId === stoppedProviderTurnId) return;+ // A different provider turn id proves this terminal event belongs to the+ // replacement even if its running status has not reached Desktop yet.+ this.stoppedProviderTurnIdBySession.delete(hydrated.sessionId);+ if (replacementPending) {+ this.replacementTurnPendingSessionIds.delete(hydrated.sessionId);+ this.replacementTurnDispatchingSessionIds.delete(hydrated.sessionId);+ }+ }+ // Stop is applied synchronously by the main-process abort path. A provider+ // cancellation that arrives inside that boundary is only its terminal tail.+ // Outside a Stop/replacement boundary, cancellation can also be the sole+ // terminal event (for example Codex permission tightening), so it must close+ // the visible run without treating it as a successful completion.+ if (isCancelledTerminalEvent(event)) {+ if (this.stoppedSessionIds.has(hydrated.sessionId)) return;+ if (+ this.replacementTurnPendingSessionIds.has(hydrated.sessionId) &&+ !this.replacementTurnDispatchingSessionIds.has(hydrated.sessionId)+ ) return;+ this.handleSessionStopped(hydrated.sessionId, providerTurnId);+ return;+ }+ // Provider aborts can drain ordinary status/done events after the user has+ // already stopped the turn. Keep those tails from recreating a completed+ // island entry until a replacement prompt begins the restart handshake.+ if (this.stoppedSessionIds.has(hydrated.sessionId)) return;+ // Claude Code queues a new turn's running status behind any remaining+ // completion tail from the interrupted turn. Keep completion suppressed+ // after the replacement prompt until that FIFO start marker arrives.+ if (this.replacementTurnPendingSessionIds.has(hydrated.sessionId)) {+ if (isCompletionDoneEvent(event)) return;+ if (isRunningStatusEvent(event)) {+ this.replacementTurnPendingSessionIds.delete(hydrated.sessionId);+ this.replacementTurnDispatchingSessionIds.delete(hydrated.sessionId);+ }+ }if (this.deferredRemoteAuthErrors.has(hydrated.sessionId)) {// The failed turn's status Done/done tail is bookkeeping, not a user-visible// completion. A running status proves the replacement turn was accepted.@@ -693,6 +751,22 @@ export class AgentIslandService {handleUserPrompt(meta: AgentIslandSessionMeta, prompt: string, debugMeta: AgentIslandUserPromptDebugMeta = {}): void {const receivedAt = Date.now();const hydrated = this.hydrateMeta(meta);+ const previousInteractionEpoch = this.interactionEpochBySession.get(hydrated.sessionId);+ const wasStopped = this.stoppedSessionIds.has(hydrated.sessionId);+ const wasReplacementTurnPending = this.replacementTurnPendingSessionIds.has(hydrated.sessionId);+ const wasReplacementTurnDispatching =+ this.replacementTurnDispatchingSessionIds.has(hydrated.sessionId);+ const deferInteractionEpochUntilDispatch = wasStopped || wasReplacementTurnPending;+ if (!deferInteractionEpochUntilDispatch) {+ this.advanceInteractionEpoch(hydrated.sessionId);+ }+ if (wasStopped) {+ this.stoppedSessionIds.delete(hydrated.sessionId);+ this.replacementTurnPendingSessionIds.add(hydrated.sessionId);+ }+ if (deferInteractionEpochUntilDispatch) {+ this.replacementTurnDispatchingSessionIds.delete(hydrated.sessionId);+ }const rollbackKey = this.userPromptRollbackKey(hydrated.sessionId, debugMeta.clientId);if (rollbackKey) {this.userPromptRollbackTokens.set(rollbackKey, {@@ -700,6 +774,12 @@ export class AgentIslandService {attention: this.sessionHadAttentionAtRunStart.has(hydrated.sessionId)? { existed: true, value: this.sessionHadAttentionAtRunStart.get(hydrated.sessionId) ?? false }: { existed: false, value: false },+ interactionEpoch: previousInteractionEpoch === undefined+ ? { existed: false, value: 0 }+ : { existed: true, value: previousInteractionEpoch },+ wasStopped,+ wasReplacementTurnPending,+ wasReplacementTurnDispatching,});}this.clearCompletedSilencedRunForNewActivity(hydrated.sessionId);@@ -710,6 +790,18 @@ export class AgentIslandService {const changed = applyAgentIslandUserPrompt(this.state, hydrated, prompt, receivedAt);if (!changed) {if (rollbackKey) this.userPromptRollbackTokens.delete(rollbackKey);+ if (wasStopped) {+ this.stoppedSessionIds.add(hydrated.sessionId);+ }+ if (!wasReplacementTurnPending) {+ this.replacementTurnPendingSessionIds.delete(hydrated.sessionId);+ }+ if (wasReplacementTurnDispatching) {+ this.replacementTurnDispatchingSessionIds.add(hydrated.sessionId);+ } else {+ this.replacementTurnDispatchingSessionIds.delete(hydrated.sessionId);+ }+ this.restoreInteractionEpoch(hydrated.sessionId, previousInteractionEpoch);return;}this.ensureMetadata(hydrated.sessionId);@@ -735,11 +827,62 @@ export class AgentIslandService {} else {this.sessionHadAttentionAtRunStart.delete(sessionId);}+ if (snapshot.wasStopped) this.stoppedSessionIds.add(sessionId);+ else this.stoppedSessionIds.delete(sessionId);+ if (snapshot.wasReplacementTurnPending) this.replacementTurnPendingSessionIds.add(sessionId);+ else this.replacementTurnPendingSessionIds.delete(sessionId);+ if (snapshot.wasReplacementTurnDispatching) {+ this.replacementTurnDispatchingSessionIds.add(sessionId);+ } else {+ this.replacementTurnDispatchingSessionIds.delete(sessionId);+ }+ this.restoreInteractionEpoch(+ sessionId,+ snapshot.interactionEpoch.existed ? snapshot.interactionEpoch.value : undefined,+ );this.publish();}- handleInteractionRequest(meta: AgentIslandSessionMeta, request: InteractionRequest): void {+ /**+ * Captures the current user-turn boundary before interaction delivery. A+ * prompt dispatch or Stop advances the epoch, allowing an earlier request to+ * be rejected before it is surfaced.+ */+ captureInteractionEpoch(sessionId: string): number {+ const current = this.interactionEpochBySession.get(sessionId);+ if (current !== undefined) return current;+ return this.advanceInteractionEpoch(sessionId);+ }++ /**+ * Advances the replacement turn's interaction boundary at the last+ * synchronous point before Session invokes vendor code. A callback from the+ * stopped turn that began while the replacement was only previewed keeps the+ * older epoch; a callback from the dispatched replacement captures the new+ * one even if its running status has not reached Desktop yet.+ */+ handleUserPromptDispatching(sessionId: string): void {+ if (!this.replacementTurnPendingSessionIds.has(sessionId)) return;+ this.advanceInteractionEpoch(sessionId);+ this.replacementTurnDispatchingSessionIds.add(sessionId);+ }++ isInteractionCurrent(sessionId: string, interactionEpoch: number): boolean {+ if (this.interactionEpochBySession.get(sessionId) !== interactionEpoch) return false;+ if (this.stoppedSessionIds.has(sessionId)) return false;+ return (+ !this.replacementTurnPendingSessionIds.has(sessionId) ||+ this.replacementTurnDispatchingSessionIds.has(sessionId)+ );+ }++ handleInteractionRequest(+ meta: AgentIslandSessionMeta,+ request: InteractionRequest,+ interactionEpoch: number,+ ): void {const hydrated = this.hydrateMeta(meta);+ if (!this.isInteractionCurrent(hydrated.sessionId, interactionEpoch)) return;if (request.kind === 'permission') {this.permissionRequests.set(request.requestId, { sessionId: hydrated.sessionId, request });}@@ -800,6 +943,12 @@ export class AgentIslandService {}handleSessionClosed(sessionId: string): void {+ this.stoppedSessionIds.delete(sessionId);+ this.replacementTurnPendingSessionIds.delete(sessionId);+ this.replacementTurnDispatchingSessionIds.delete(sessionId);+ this.stoppedProviderTurnIdBySession.delete(sessionId);+ this.interactionEpochBySession.delete(sessionId);+ this.clearSilencedRunForSession(sessionId);this.sessionHadAttentionAtRunStart.delete(sessionId);for (const key of this.userPromptRollbackTokens.keys()) {if (key.startsWith(`${sessionId}:`)) {@@ -814,6 +963,49 @@ export class AgentIslandService {this.publish();}+ /**+ * Applies the user-visible Stop boundary before provider-specific abort tails+ * arrive. A stopped turn is neither a success nor an error, so it leaves no+ * completion card, unread attention, or completion sound behind.+ */+ handleSessionStopped(sessionId: string, providerTurnId: string | null = null): void {+ this.advanceInteractionEpoch(sessionId);+ this.stoppedProviderTurnIdBySession.delete(sessionId);+ if (providerTurnId) {+ this.stoppedProviderTurnIdBySession.set(sessionId, providerTurnId);+ }+ this.stoppedSessionIds.add(sessionId);+ this.replacementTurnPendingSessionIds.delete(sessionId);+ this.replacementTurnDispatchingSessionIds.delete(sessionId);+ this.clearSilencedRunForSession(sessionId);+ this.sessionHadAttentionAtRunStart.delete(sessionId);+ for (const key of this.userPromptRollbackTokens.keys()) {+ if (key.startsWith(`${sessionId}:`)) {+ this.userPromptRollbackTokens.delete(key);+ }+ }+ this.deferredCompletions.delete(sessionId);+ this.clearDeferredRemoteAuthError(sessionId);+ this.deletePermissionRequestsForSession(sessionId);+ const hadSession = this.state.sessions.has(sessionId);+ removeAgentIslandSession(this.state, sessionId);+ if (hadSession) this.publish();+ }++ private advanceInteractionEpoch(sessionId: string): number {+ this.interactionEpochSequence += 1;+ this.interactionEpochBySession.set(sessionId, this.interactionEpochSequence);+ return this.interactionEpochSequence;+ }++ private restoreInteractionEpoch(sessionId: string, epoch: number | undefined): void {+ if (epoch === undefined) {+ this.interactionEpochBySession.delete(sessionId);+ return;+ }+ this.interactionEpochBySession.set(sessionId, epoch);+ }+/*** badge 桥接来的会话已读信号(renderer → appBadgeService → 这里)。* source 默认 'passive'(fail-safe):renderer 未声明意图的清除一律当被动信号,@@ -1033,6 +1225,11 @@ export class AgentIslandService {this.clearSilencedScheduleRun(runId);}+ private clearSilencedRunForSession(sessionId: string): void {+ const runId = this.silencedSessionRunIds.get(sessionId);+ if (runId) this.clearSilencedScheduleRun(runId);+ }+private clearSilencedScheduleRun(runId: string): void {this.clearSilencedRunTimer(runId);const sessionId = this.silencedRunSessionIds.get(runId);@@ -1873,12 +2070,27 @@ function isCompletionDoneEvent(event: AgentEvent): boolean {return data?.isRunning === false && data.status === 'Done';}+function isCancelledTerminalEvent(event: AgentEvent): boolean {+ if (event.type !== 'done' && event.type !== 'status') return false;+ const data = event.data as { cancelled?: unknown } | undefined;+ return data?.cancelled === true;+}+function isRunningStatusEvent(event: AgentEvent): boolean {if (event.type !== 'status') return false;const data = event.data as { isRunning?: unknown } | undefined;return data?.isRunning === true;}+function providerTurnIdFromAgentEvent(event: AgentEvent): string | null {+ if (!event.data || typeof event.data !== 'object' || Array.isArray(event.data)) return null;+ const data = event.data as { turnId?: unknown; raw?: unknown };+ if (typeof data.turnId === 'string' && data.turnId) return data.turnId;+ if (!data.raw || typeof data.raw !== 'object' || Array.isArray(data.raw)) return null;+ const rawId = (data.raw as { id?: unknown }).id;+ return typeof rawId === 'string' && rawId ? rawId : null;+}+function isRemoteDaemonClosedErrorEvent(event: AgentEvent): boolean {if (event.type !== 'error') return false;const data = event.data as { reason?: unknown } | undefined;diff --git a/apps/desktop/src/main/hook-control/ipc.ts b/apps/desktop/src/main/hook-control/ipc.tsindex ce473c6d4b..bb0a71f9a6 100644--- a/apps/desktop/src/main/hook-control/ipc.ts+++ b/apps/desktop/src/main/hook-control/ipc.ts@@ -68,6 +68,7 @@ import { listRecentHookSessions } from './recentSessions.js';import { validateTelegramExternalUrl } from './telegramDeepLink.js';import { isAppContentWindow } from '../windowFocusClassifier.js';import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';+import { getAgentIslandService } from '../agent-island/service.js';const log = createLogger('hook-control');@@ -296,7 +297,20 @@ function ensureInstances(): { store: SlackHookStore; manager: HookControlManager},// task.cancel 的中断出口: 与用户手动 Stop 同一条 session.abort() 路径abortSession: async (sessionId) => {- await getMaker().getSession(sessionId)?.abort();+ const session = getMaker().getSession(sessionId);+ if (!session) return;+ try {+ getAgentIslandService()?.handleSessionStopped(+ sessionId,+ session.getCurrentTurnId?.() ?? null,+ );+ } catch (error) {+ log.warn('Agent Island session stop update failed before hook provider abort', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ await session.abort();},// session.archive 的归档出口: 与 device-link 远程归档同一条// patchSessionMetaInDb 路径(落库 + sessions:patched 广播, sidebar 即时移出)diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.tsindex 73ca4e277b..4834095ae9 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts@@ -15,8 +15,12 @@ function createSession(overrides: Partial<MakerSendTransactionSession> = {}): MaworkDir: 'C:\\repo',remoteHostId: null,isTurnRunning: vi.fn(() => false),- send: vi.fn(async (_message: UserMessage | string, opts?: { onAccepted?: () => Promise<void> }) => {+ send: vi.fn(async (+ _message: UserMessage | string,+ opts?: { onAccepted?: () => Promise<void>; onDispatching?: () => void },+ ) => {await opts?.onAccepted?.();+ opts?.onDispatching?.();return { accepted: true } satisfies SessionSendResult;}),...overrides,@@ -52,6 +56,7 @@ function createDeps(overrides: Partial<MakerSendTransactionDeps> = {}) {prepareSendUserMessage: vi.fn(async (_sessionId, message) => message as UserMessage | string),createDbMessage: vi.fn(async () => {}),previewUserPrompt: vi.fn(),+ dispatchUserPromptPreview: vi.fn(),commitUserPromptPreview: vi.fn(),rollbackUserPromptPreview: vi.fn(),isSessionRunningError: vi.fn(() => false),@@ -143,6 +148,7 @@ describe('maker SEND transaction', () => {{ shouldBroadcast },);expect(onPersisted).toHaveBeenCalled();+ expect(deps.dispatchUserPromptPreview).toHaveBeenCalledWith('session-1');expect(deps.commitUserPromptPreview).toHaveBeenCalledWith('session-1', 'client-1');expect(deps.rollbackUserPromptPreview).not.toHaveBeenCalled();});diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.tsindex 449b8aea14..3ec5f1f4e4 100644--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts@@ -123,6 +123,7 @@ export interface MakerSendTransactionDeps {content: unknown,options: { source: string; clientId?: string },): void;+ dispatchUserPromptPreview?(sessionId: string): void;commitUserPromptPreview?(sessionId: string, clientId: string | undefined): void;rollbackUserPromptPreview?(sessionId: string, clientId: string | undefined, source: string): void;isSessionRunningError(err: unknown): boolean;@@ -492,6 +493,11 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Makeawait persistUserMessage.onPersisted?.();}: undefined,+ onDispatching: () => {+ if (userPromptPreviewSessionId) {+ deps.dispatchUserPromptPreview?.(userPromptPreviewSessionId);+ }+ },});if (sendResult.accepted && interruptedAckAt !== null) {try {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 9d5a9184cf..29e43e55a4 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1667,10 +1667,15 @@ function isRemoteAuthRetryErrorEvent(function handleAgentIslandInteractionAfterBroadcast(session: { id: string; agentKind?: unknown; workDir?: unknown; workspaceKind?: unknown },request: InteractionRequest,+ interactionEpoch: number | null,): void {- if (!shouldNotifyAgentIslandForSession(session.id)) return;+ if (interactionEpoch === null || !shouldNotifyAgentIslandForSession(session.id)) return;try {- getAgentIslandService()?.handleInteractionRequest(sessionMetaForIsland(session), request);+ getAgentIslandService()?.handleInteractionRequest(+ sessionMetaForIsland(session),+ request,+ interactionEpoch,+ );} catch (error) {log.warn('Agent Island interaction update failed after maker interaction broadcast', {sessionId: session.id,@@ -1716,6 +1721,23 @@ function handleAgentIslandSessionClosedAfterCleanup(sessionId: string): void {}}+function handleAgentIslandSessionStopped(+ session: { id: string; getCurrentTurnId?: () => string | null },+): void {+ if (!shouldNotifyAgentIslandForSession(session.id)) return;+ try {+ getAgentIslandService()?.handleSessionStopped(+ session.id,+ session.getCurrentTurnId?.() ?? null,+ );+ } catch (error) {+ log.warn('Agent Island session stop update failed before provider abort', {+ sessionId: session.id,+ error: error instanceof Error ? error.message : String(error),+ });+ }+}+function shouldNotifyAgentIslandForSession(sessionId: string): boolean {return shouldNotifyAgentIslandForSessionByPolicy(AGENT_ISLAND_DISPLAY_CONFIG,@@ -1752,6 +1774,18 @@ function notifyAgentIslandUserPrompt(}}+function dispatchAgentIslandUserPrompt(sessionId: string): void {+ if (!shouldNotifyAgentIslandForSession(sessionId)) return;+ try {+ getAgentIslandService()?.handleUserPromptDispatching(sessionId);+ } catch (error) {+ log.warn('Agent Island prompt dispatch boundary update failed', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+}+function commitAgentIslandUserPrompt(sessionId: string, clientId: string | undefined): void {if (!shouldNotifyAgentIslandForSession(sessionId)) return;try {@@ -1869,9 +1903,22 @@ export function installDesktopInteractionListener(session: { id: string; setInteractionListener: (l: ((req: InteractionRequest) => Promise<InteractionDecision>) | null) => void },): void {session.setInteractionListener(async (req: InteractionRequest) => {+ const agentIslandInteractionEpoch = shouldNotifyAgentIslandForSession(session.id)+ ? getAgentIslandService()?.captureInteractionEpoch(session.id) ?? null+ : null;// F1-a Phase 2: interaction(ask_user / plan_review / permission)是 turn 暂停边界,// 且不走 onEvent —— 在这把在飞 assistant 文本落库,等价于 renderer 老逻辑在// ask_user_question / plan_review case 里的 mid-turn assistant 抢救(只入队、不阻塞)。+ if (+ agentIslandInteractionEpoch !== null &&+ shouldNotifyAgentIslandForSession(session.id) &&+ getAgentIslandService()?.isInteractionCurrent(+ session.id,+ agentIslandInteractionEpoch,+ ) === false+ ) {+ return defaultDecisionForPending(req.kind, 'stale_turn');+ }flushAssistantBlock(session.id);// F1-a Phase 5: ask_user / plan_review 的消息本身也收口 main 单点落库(单 persistId,// 修 F1 重复),persistId 盖进 payload 让 renderer 用同一 id 建气泡 + answered 回写命中。@@ -1905,6 +1952,7 @@ export function installDesktopInteractionListener(handleAgentIslandInteractionAfterBroadcast(session as { id: string; agentKind?: unknown; workDir?: unknown; workspaceKind?: unknown },req,+ agentIslandInteractionEpoch,);});});@@ -4237,6 +4285,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions// (jump/resume 分支是既有 session 重建,不在此发,见 wakeKind:'resumed' 分支。)broadcastSessionCreated(session.id);},+ onDispatching: () => dispatchAgentIslandUserPrompt(session.id),});if (createdPreviewStarted) {if (sendResult.accepted) {@@ -4407,7 +4456,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptionsconst sendResult = await sendUserMessageWithAwaitedGitBaseline(live,message,- { planMode: false, onAccepted: persistUserMessage },+ {+ planMode: false,+ onAccepted: persistUserMessage,+ onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),+ },);if (userPromptPreviewStarted) {if (sendResult.accepted) {@@ -4491,7 +4544,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptionsconst sendResult = await sendUserMessageWithAwaitedGitBaseline(session,message,- { planMode: false, onAccepted: persistUserMessage },+ {+ planMode: false,+ onAccepted: persistUserMessage,+ onDispatching: () => dispatchAgentIslandUserPrompt(targetSessionId),+ },);if (userPromptPreviewStarted) {if (sendResult.accepted) {@@ -5606,6 +5663,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptionspreviewUserPrompt: (session, content, options) => {notifyAgentIslandUserPrompt(session, content, options);},+ dispatchUserPromptPreview: (sessionId) => {+ dispatchAgentIslandUserPrompt(sessionId);+ },commitUserPromptPreview: (sessionId, clientId) => {commitAgentIslandUserPrompt(sessionId, clientId);},@@ -5801,6 +5861,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptionsmarkWorkerManualInterruptIfKnown(sessionId, 'input_stop');const sess = maker.getSession(sessionId);if (!sess) return;+ handleAgentIslandSessionStopped(sess);await sess.abort();cleanupPendingInteractionsForSession(sessionId, 'session_aborted');},@@ -6480,6 +6541,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptionssilentStopAutoResumeGuard.noteSessionReset(sessionId);const sess = maker.getSession(sessionId);if (!sess) return;+ handleAgentIslandSessionStopped(sess);// 用户 Stop 当前 turn → 若该会话有 active goal,先暂停目标(置 paused + 停续跑 + detach// 监听),**再** abort。这样 abort 产生的终止事件到来时目标已暂停、监听已摘,不会被误判成// 续跑(原本依赖 error 文案正则判 paused/blocked,不可靠)。null-safe;无 active goal 时 no-op。diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex 16b1b64f64..fc761f8d5f 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -662,6 +662,9 @@ export interface AgentSessionHandle {/** 中断当前 turn */abort(): Promise<void>;+ /** Provider turn identity when the adapter exposes one (currently Codex). */+ getCurrentTurnId?(): string | null;+/*** 停止会话内单个后台任务(SDK Query.stopTask 透传)。* 与 abort() 的区别:abort 是"用户 Stop"的全停语义(只连带 wake 型任务、并diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 810f0229f8..992f5e79db 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -4868,6 +4868,7 @@ describe('CodexAgent turn lifecycle', () => {turn: { id: 'turn-1' },});expect(handle.isTurnRunning?.()).toBe(true);+ expect(handle.getCurrentTurnId?.()).toBe('turn-1');handlers.error?.({threadId: 'start-thread-id',@@ -4877,6 +4878,7 @@ describe('CodexAgent turn lifecycle', () => {});expect(handle.isTurnRunning?.()).toBe(false);+ expect(handle.getCurrentTurnId?.()).toBeNull();const errorEvent = await nextEvent(iterator);const statusEvent = await nextEvent(iterator);expect(errorEvent).toMatchObject({diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 84a0c4b65b..0fcf9d6c9a 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -14,7 +14,8 @@* - ✅ oneShot: 走 host 临时 thread (起标题), Phase 4 删 SDK dep 后唯一通路** 输出契约:- * - 不在 AgentSessionHandle 上加 codex-only 方法+ * - AgentSessionHandle 只暴露 provider-neutral 的可选能力,不泄漏 Codex+ * thread / app-server 协议类型* - 事件流只 emit 已存在的 AgentEvent type union 成员* - renderer 不感知 thread_id / app-server 任何概念*/@@ -4267,6 +4268,10 @@ export class CodexAgent extends BaseAgent {}},+ getCurrentTurnId() {+ return currentTurnId;+ },+async close() {if (closed) return;closed = true;diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.tsindex 6e7c337fd0..dace0a5d10 100644--- a/packages/maker-core/src/maker.test.ts+++ b/packages/maker-core/src/maker.test.ts@@ -720,6 +720,33 @@ describe('Session turn send guard', () => {expect(handle.send).toHaveBeenCalledTimes(1);});+ it('runs onDispatching after acceptance and immediately before vendor send', async () => {+ const calls: string[] = [];+ const handle = createHandle({ id: 'thread-1' });+ handle.send = vi.fn(async () => {+ calls.push('vendor');+ });+ const session = new Session({+ id: 'session-1',+ agentKind: 'codex',+ workDir: '/repo',+ handle,+ capabilities: createAgent(async () => handle).capabilities,+ logger: createLogger(),+ });++ await expect(session.send('first', {+ onAccepted: () => {+ calls.push('accepted');+ },+ onDispatching: () => {+ calls.push('dispatching');+ },+ })).resolves.toEqual({ accepted: true });++ expect(calls).toEqual(['accepted', 'dispatching', 'vendor']);+ });+it('keeps the reservation while onAccepted is awaiting', async () => {let releaseAccepted!: () => void;const acceptedReady = new Promise<void>((resolve) => {diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 1861af1b2d..e0b87ca8c8 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -146,6 +146,11 @@ export interface SessionSendOptions extends SendOptions {* hook 完成后才启动 vendor handle。*/onAccepted?: () => void | Promise<void>;+ /**+ * vendor dispatch 前最后一个同步边界。用于让 host 在底层可能产生新 turn+ * callback 之前,精确切换自己的 turn-scoped 状态。+ */+ onDispatching?: () => void;}/**@@ -223,7 +228,7 @@ export class Session {const msg: UserMessage = typeof message === 'string'? { type: 'user', content: message }: message;- const { onAccepted, ...handleOpts } = opts ?? {};+ const { onAccepted, onDispatching, ...handleOpts } = opts ?? {};this.logger.debug('send', summarizeUserMessage(msg));this.ensureActive();if (this.isTurnRunning()) {@@ -267,6 +272,7 @@ export class Session {originInstalled = true;this.startEventLoopIfNeeded();try {+ onDispatching?.();await this.handle.send(msg, {...handleOpts,signal: reservation.abortController.signal,@@ -575,6 +581,10 @@ export class Session {return this.sendReservation !== null || this.isHandleTurnRunning();}+ getCurrentTurnId(): string | null {+ return this.handle.getCurrentTurnId?.() ?? null;+ }+/*** dryRun: 问 SDK 这次 rewind 会动哪些文件。返回 RewindFilesResult 给 UI 显示 diff。* SDK 软拒绝 (老 session 无 checkpointing) 包成 {canRewind:false, error}, 业务可继续。