diff --git a/src/main/agent/manager/directAcpAgentBackend.ts b/src/main/agent/manager/directAcpAgentBackend.ts index 6a45bbcbdd..86ed314fa0 100644 --- a/src/main/agent/manager/directAcpAgentBackend.ts +++ b/src/main/agent/manager/directAcpAgentBackend.ts @@ -1,5 +1,6 @@ import type { AssistantMessageBlock, + ChatMessageRecord, DeepChatSessionState, MessageStartResult } from '@shared/types/agent-interface' @@ -9,6 +10,7 @@ import type { AcpAgentRuntime, AcpAgentRuntimeSessionInput } from '@/agent/acp/i import type { SessionStatePort, SessionTapePort, + SessionTranscriptPort, SessionTranscriptReadPort } from '@/session/data/contracts' import type { @@ -21,13 +23,8 @@ import type { export interface DirectAcpAgentBackendOptions { runtime: AcpAgentRuntime sessionState: SessionStatePort - transcript: Pick & { - updateAssistantContent( - messageId: string, - blocks: AssistantMessageBlock[], - metadata?: string - ): void - } + transcript: Pick & + Pick tape: Pick deleteDurableSession(sessionId: AppSessionId): Promise resolveInput( @@ -69,6 +66,21 @@ const toSessionState = async ( } } +function findPermission(message: ChatMessageRecord, toolCallId: string, requestId?: string) { + const blocks = JSON.parse(message.content) as AssistantMessageBlock[] + const matches = blocks.filter( + (block) => + block.type === 'action' && + block.action_type === 'tool_call_permission' && + block.tool_call?.id === toolCallId && + (requestId === undefined || block.extra?.permissionRequestId === requestId) + ) + if (matches.length !== 1) return null + const block = matches[0]! + const persistedId = block.extra?.permissionRequestId?.trim() + return persistedId ? { block, blocks, requestId: persistedId } : null +} + export const createDirectAcpAgentBackend = ( options: DirectAcpAgentBackendOptions ): DirectAcpSessionBackend => { @@ -78,6 +90,24 @@ export const createDirectAcpAgentBackend = ( return { input, instance: await runtime.getOrHydrate(input) } } + function closeOrphanedPermission( + sessionId: AppSessionId, + message: ChatMessageRecord, + blocks: AssistantMessageBlock[], + block: AssistantMessageBlock + ): boolean { + if ( + block.status !== 'pending' || + runtime.getHydrated(sessionId)?.getActiveGeneration()?.eventId === message.id + ) + return false + + // A missing waiter has no known decision. Close its prompt without recording a user denial. + block.status = 'error' + block.extra = { ...block.extra, needsUserAction: false } + return transcript.updateMessageContent(message.id, JSON.stringify(blocks), message.content) + } + const cleanupSession = async (sessionId: AppSessionId): Promise => { let runtimeError: unknown try { @@ -191,47 +221,34 @@ export const createDirectAcpAgentBackend = ( if (!message || message.sessionId !== sessionId || message.role !== 'assistant') { throw new Error(`Assistant message not found: ${messageId}`) } - const blocks = JSON.parse(message.content) as AssistantMessageBlock[] - const block = blocks.find( - (candidate) => - candidate.type === 'action' && - candidate.action_type === 'tool_call_permission' && - candidate.tool_call?.id === toolCallId - ) - const requestId = block?.extra?.permissionRequestId?.trim() - if (!requestId) { + const permission = findPermission(message, toolCallId, response.permissionRequestId) + if (!permission) { throw new Error(`ACP permission request not found for tool call: ${toolCallId}`) } - const resolved = runtime - .getHydrated(sessionId) - ?.resolvePermissionRequest(requestId, response.granted) - if (!resolved) throw new Error(`Unknown ACP permission request: ${requestId}`) - return { resumed: false } + const { block, blocks, requestId } = permission + if (block.status === (response.granted ? 'granted' : 'denied')) { + return { resumed: false, handledInline: true } + } + if ( + block.status !== 'pending' || + !runtime.getHydrated(sessionId)?.resolvePermissionRequest(requestId, response.granted) + ) { + closeOrphanedPermission(sessionId, message, blocks, block) + throw new Error(`Unknown ACP permission request: ${requestId}`) + } + return { resumed: false, handledInline: true } }, async dismiss(messageId: string, toolCallId: string) { const message = await transcript.getMessage(messageId) if (!message || message.sessionId !== sessionId || message.role !== 'assistant') { return false } - const blocks = JSON.parse(message.content) as AssistantMessageBlock[] - const block = blocks.find( - (candidate) => - candidate.type === 'action' && - candidate.action_type === 'tool_call_permission' && - candidate.tool_call?.id === toolCallId - ) - const requestId = block?.extra?.permissionRequestId?.trim() - if (!requestId) return false - if (runtime.getHydrated(sessionId)?.resolvePermissionRequest(requestId, false)) { + const permission = findPermission(message, toolCallId) + if (!permission || permission.block.status !== 'pending') return false + const { block, blocks, requestId } = permission + if (runtime.getHydrated(sessionId)?.resolvePermissionRequest(requestId, false)) return true - } - // No live ACP runtime can resolve the request: persist a durable denied - // block so the stale approval does not reappear after a reload. - if (!block) return false - block.status = 'denied' - block.extra = { ...block.extra, needsUserAction: false } - transcript.updateAssistantContent(messageId, blocks) - return true + return closeOrphanedPermission(sessionId, message, blocks, block) } }, async send(input): Promise { diff --git a/src/main/session/data/contracts.ts b/src/main/session/data/contracts.ts index dc8a7b331e..a41cb5186d 100644 --- a/src/main/session/data/contracts.ts +++ b/src/main/session/data/contracts.ts @@ -384,7 +384,7 @@ export interface SessionTranscriptPort { getMessageIds(sessionId: string): string[] getMessage(messageId: string): ChatMessageRecord | null getLastUserMessageBeforeOrAt(sessionId: string, orderSeq: number): ChatMessageRecord | null - updateMessageContent(messageId: string, content: string): void + updateMessageContent(messageId: string, content: string, expectedContent?: string): boolean getNextOrderSeq(sessionId: string): number deleteBySession(sessionId: string): void deleteMessage(messageId: string): void diff --git a/src/main/session/data/transcript.ts b/src/main/session/data/transcript.ts index 69cd6940b4..00e125d721 100644 --- a/src/main/session/data/transcript.ts +++ b/src/main/session/data/transcript.ts @@ -595,19 +595,20 @@ export class SessionTranscript implements SessionTranscriptPort, TapeTranscriptP return this.toRecord(row) } - updateMessageContent(messageId: string, content: string): void { - this.runInDatabaseTransaction(() => this.applyMessageContentUpdate(messageId, content)) - } - - private applyMessageContentUpdate(messageId: string, content: string): void { - const row = this.database.deepchatMessagesTable.get(messageId) - if (!row) { - return - } - this.commitReplacement( - this.terminalRecord({ ...this.recordFromRow(row), content, updatedAt: Date.now() }), - { reason: 'message_content_updated', revisionKind: 'record' } - ) + updateMessageContent(messageId: string, content: string, expectedContent?: string): boolean { + return this.runInDatabaseTransaction(() => { + const row = this.database.deepchatMessagesTable.get(messageId) + if ( + !row || + (expectedContent !== undefined && this.materializeContent(row) !== expectedContent) + ) + return false + this.commitReplacement( + this.terminalRecord({ ...this.recordFromRow(row), content, updatedAt: Date.now() }), + { reason: 'message_content_updated', revisionKind: 'record' } + ) + return true + }) } getNextOrderSeq(sessionId: string): number { diff --git a/src/renderer/api/ChatClient.ts b/src/renderer/api/ChatClient.ts index 18237d9509..33e3cc1e61 100644 --- a/src/renderer/api/ChatClient.ts +++ b/src/renderer/api/ChatClient.ts @@ -66,6 +66,7 @@ export function createChatClient(bridge: DeepchatBridge = getDeepchatBridge()) { return await bridge.invoke(chatRespondToolInteractionRoute.name, normalizedInput) } + /** Explicitly abandons a request. An unacknowledged response can still be retried. */ async function dismissToolInteraction(input: { sessionId: string messageId: string diff --git a/src/renderer/src/features/chat-page/composables/useToolInteraction.ts b/src/renderer/src/features/chat-page/composables/useToolInteraction.ts index 59e4d89223..779b422211 100644 --- a/src/renderer/src/features/chat-page/composables/useToolInteraction.ts +++ b/src/renderer/src/features/chat-page/composables/useToolInteraction.ts @@ -1,4 +1,4 @@ -import { computed, ref, shallowReactive, watch } from 'vue' +import { computed, ref, watch } from 'vue' import { projectPendingInteraction } from '@shared/chat/pendingInteraction' import { DEEPCHAT_ROUTE_INVOKE_CHANNEL } from '@shared/contracts/channels' import { staleDimInteractionMessages } from '@shared/dimQuestions' @@ -8,9 +8,6 @@ import type { ToolInteractionResponse, ToolInteractionResult } from '@shared/typ type MessageStore = ReturnType -// Answers may still be awaiting their batch result when the chat page is remounted. -const answeredNativeQuestions = shallowReactive(new Map>()) - type PendingInteractionView = { sessionId: string messageId: string @@ -40,11 +37,6 @@ type ChatClientLike = { toolCallId: string response: ToolInteractionResponse }) => Promise - dismissToolInteraction: (input: { - sessionId: string - messageId: string - toolCallId: string - }) => Promise<{ dismissed: boolean }> } type UseToolInteractionOptions = { @@ -86,14 +78,27 @@ function isStaleDimInteraction(error: unknown): boolean { * while the page composes the returned state into its plan and composer gates. */ export function useToolInteraction(options: UseToolInteractionOptions) { - const isHandlingInteraction = ref(false) + const { acknowledgedInteractions, inFlightInteractions } = options.messageStore watch( () => options.messageStore.messages, (messages) => { - if (answeredNativeQuestions.size === 0) return + const session = options.messageStore.committedSession + // Child approvals can still appear in an older parent progress snapshot. + if ( + !acknowledgedInteractions.size || + session?.sessionKind !== 'regular' || + session.parentSessionId + ) + return for (const message of messages) { - if (message.status !== 'pending') answeredNativeQuestions.delete(message.id) + if ( + message.sessionId === session.id && + message.status !== 'pending' && + acknowledgedInteractions.get(message.id)?.sessionId === session.id && + !options.messageStore.getAssistantMessageBlocks(message).some(projectPendingInteraction) + ) + acknowledgedInteractions.delete(message.id) } }, { immediate: true } @@ -106,7 +111,12 @@ export function useToolInteraction(options: UseToolInteractionOptions) { const staleInteractionKeys = ref>(new Set()) const interactionKey = ({ sessionId, messageId, toolCallId, block }: PendingInteractionView) => - `${sessionId}:${messageId}:${toolCallId}:${block.extra?.dimRequestId ?? ''}` + JSON.stringify([ + sessionId, + messageId, + toolCallId, + block.extra?.dimRequestId ?? block.extra?.permissionRequestId + ]) const markStale = (interaction: PendingInteractionView) => { const key = interactionKey(interaction) @@ -118,7 +128,7 @@ export function useToolInteraction(options: UseToolInteractionOptions) { const list: PendingInteractionView[] = [] for (const message of options.messageStore.messages) { - if (message.role !== 'assistant') continue + if (message.role !== 'assistant' || message.sessionId !== options.sessionId()) continue const blocks = options.messageStore.getAssistantMessageBlocks(message) for (const block of blocks) { @@ -126,7 +136,7 @@ export function useToolInteraction(options: UseToolInteractionOptions) { if (!pending) continue list.push({ - sessionId: options.sessionId(), + sessionId: message.sessionId, messageId: message.id, ...pending, block @@ -166,13 +176,23 @@ export function useToolInteraction(options: UseToolInteractionOptions) { const key = interactionKey(entry) return ( !staleInteractionKeys.value.has(key) && - !answeredNativeQuestions.get(entry.messageId)?.has(key) + !acknowledgedInteractions.get(entry.messageId)?.keys.has(key) ) }) }) const activePendingInteraction = computed(() => pendingInteractions.value[0] ?? null) + const isHandlingInteraction = computed(() => { + const interaction = activePendingInteraction.value + return ( + [...inFlightInteractions.values()].some( + (entry) => entry.displaySessionId === options.sessionId() + ) || + (interaction !== null && inFlightInteractions.has(interactionKey(interaction))) + ) + }) + async function onToolInteractionRespond(response: ToolInteractionResponse) { const interaction = activePendingInteraction.value if (!interaction || isHandlingInteraction.value) { @@ -184,79 +204,57 @@ export function useToolInteraction(options: UseToolInteractionOptions) { const isNativeQuestion = interaction.actionType === 'question_request' && typeof interaction.block.extra?.dimRequestId === 'string' - isHandlingInteraction.value = true + const key = interactionKey(interaction) + const token = Symbol() + inFlightInteractions.set(key, { + sessionId: interaction.sessionId, + messageId: interaction.messageId, + displaySessionId: sessionId, + token + }) + const ownsSubmission = () => inFlightInteractions.get(key)?.token === token const isCurrentView = () => options.canWriteSessionView(sessionId, requestId) - const refreshAfterResponse = async () => { - if (!isCurrentView()) return false - const restoredSession = await options.loadMessagesForSession(sessionId) - if (!isCurrentView()) return false - options.applyRestoredSessionSummary(restoredSession) - return true - } - const isStillPending = () => - pendingInteractions.value.some( - (entry) => interactionKey(entry) === interactionKey(interaction) - ) - // Best-effort durable close on the main-process transcript so the orphaned - // block stops blocking new turns and does not reappear after a session reload. - const dismissStale = async () => { - if (!isStillPending()) return - markStale(interaction) - try { - await options.chatClient.dismissToolInteraction({ - sessionId: interaction.sessionId, - messageId: interaction.messageId, - toolCallId: interaction.toolCallId - }) - } catch (error) { - console.error('[ChatPage] dismiss stale tool interaction failed:', error) - } - } try { + const permissionRequestId = interaction.block.extra?.permissionRequestId const result = await options.chatClient.respondToolInteraction({ sessionId: interaction.sessionId, messageId: interaction.messageId, toolCallId: interaction.toolCallId, - response + response: + response.kind === 'permission' && + typeof permissionRequestId === 'string' && + permissionRequestId + ? { ...response, permissionRequestId } + : response }) - if (isNativeQuestion) { - // The batch result can be blocked on a sibling question that the dock must show next. - if (!isCurrentView() || isStillPending()) { - const { messageId } = interaction - const keys = new Set(answeredNativeQuestions.get(messageId)) - answeredNativeQuestions.set(messageId, keys.add(interactionKey(interaction))) - } - return - } - const refreshed = await refreshAfterResponse() - if (!refreshed || result.handledInline || result.waitingForUserMessage) { - return + if (!ownsSubmission()) return + if ( + isNativeQuestion || + (interaction.actionType === 'tool_call_permission' && + (result.resumed || result.handledInline)) + ) { + const keys = new Set(acknowledgedInteractions.get(interaction.messageId)?.keys) + acknowledgedInteractions.set(interaction.messageId, { + sessionId: interaction.sessionId, + keys: keys.add(key) + }) } - // The main process resolves a handled interaction by persisting a - // non-pending block status. If it is still pending after the reload, its - // backing run is gone and the approval can never be closed here. Drop it - // so the UI advances to the next pending approval instead of staying stuck. - await dismissStale() } catch (error) { + if (!ownsSubmission()) return console.error('[ChatPage] respond tool interaction failed:', error) options.onResponseFailed?.(interaction, error) - if (isNativeQuestion) { - if (isStaleDimInteraction(error)) markStale(interaction) - return - } - // A rejected respond is itself a strong staleness signal (a resolvable - // interaction would not be rejected). Reload once and, if the interaction - // is still pending, release the UI from the uncloseable approval. - try { - const refreshed = await refreshAfterResponse() - if (refreshed) { - await dismissStale() + if (isStaleDimInteraction(error)) markStale(interaction) + } finally { + if (ownsSubmission() && !isNativeQuestion && isCurrentView()) { + try { + const restoredSession = await options.loadMessagesForSession(sessionId) + if (ownsSubmission() && isCurrentView()) + options.applyRestoredSessionSummary(restoredSession) + } catch (refreshError) { + console.error('[ChatPage] refresh after tool interaction response failed:', refreshError) } - } catch (refreshError) { - console.error('[ChatPage] refresh after failed tool interaction response:', refreshError) } - } finally { - isHandlingInteraction.value = false + if (ownsSubmission()) inFlightInteractions.delete(key) } } diff --git a/src/renderer/src/stores/ui/message.ts b/src/renderer/src/stores/ui/message.ts index 42a50ccfa9..cf63285e63 100644 --- a/src/renderer/src/stores/ui/message.ts +++ b/src/renderer/src/stores/ui/message.ts @@ -2,6 +2,7 @@ import { defineStore } from 'pinia' import { ref, shallowRef, + shallowReactive, computed, onScopeDispose, getCurrentScope, @@ -65,6 +66,16 @@ export const useMessageStore = defineStore('message', () => { // --- State --- const messageIds = ref([]) const messageCache = ref>(new Map()) + // Approvals can outlive a ChatPage while IPC responds or the transcript catches up. + const acknowledgedInteractions = shallowReactive( + new Map }>() + ) + const inFlightInteractions = shallowReactive( + new Map< + string, + { sessionId: string; messageId: string; displaySessionId: string; token: symbol } + >() + ) const lastPersistedRevision = ref(0) // Active selection may change before its message view is prepared. Keep the // committed owner separate so old and target-session records never mix. @@ -890,6 +901,10 @@ export const useMessageStore = defineStore('message', () => { } function removeMessages(sessionId: string, ids: string[]): void { + for (const id of ids) acknowledgedInteractions.delete(id) + for (const [key, entry] of inFlightInteractions) { + if (ids.includes(entry.messageId)) inFlightInteractions.delete(key) + } if (committedSessionId.value !== sessionId) return const removedIds = new Set(ids.filter((id) => messageCache.value.has(id))) if (removedIds.size === 0) return @@ -976,6 +991,8 @@ export const useMessageStore = defineStore('message', () => { committedSession.value = null messageIds.value = [] messageCache.value.clear() + acknowledgedInteractions.clear() + inFlightInteractions.clear() nextCursor.value = null hasMoreHistory.value = false isLoadingHistory.value = false @@ -1136,6 +1153,12 @@ export const useMessageStore = defineStore('message', () => { registerStoreCleanup(messageIpcBinding.cleanup) function purgeSessionTracking(sessionId: string): void { + for (const [id, entry] of acknowledgedInteractions) { + if (entry.sessionId === sessionId) acknowledgedInteractions.delete(id) + } + for (const [key, entry] of inFlightInteractions) { + if (entry.sessionId === sessionId) inFlightInteractions.delete(key) + } for (const [id, record] of messageCache.value) { if (record.sessionId === sessionId) { appliedStreamRevision.delete(id) @@ -1152,6 +1175,8 @@ export const useMessageStore = defineStore('message', () => { connect: messageIpcBinding.connect, messageIds, messageCache, + acknowledgedInteractions, + inFlightInteractions, isStreaming, streamingBlocks, currentStreamSessionId, diff --git a/src/shared/contracts/common.ts b/src/shared/contracts/common.ts index 61c77e4b64..cd948cd513 100644 --- a/src/shared/contracts/common.ts +++ b/src/shared/contracts/common.ts @@ -396,7 +396,8 @@ export const SendMessageInputSchema = z.object({ export const ToolInteractionResponseSchema = z.discriminatedUnion('kind', [ z.object({ kind: z.literal('permission'), - granted: z.boolean() + granted: z.boolean(), + permissionRequestId: z.string().min(1).optional() }), z.object({ kind: z.literal('question_option'), diff --git a/src/shared/types/agent-interface.d.ts b/src/shared/types/agent-interface.d.ts index e44ed9d4d4..ec64983de4 100644 --- a/src/shared/types/agent-interface.d.ts +++ b/src/shared/types/agent-interface.d.ts @@ -844,6 +844,7 @@ export type ToolInteractionResponse = | { kind: 'permission' granted: boolean + permissionRequestId?: string } | { kind: 'question_option' diff --git a/test/main/agent/manager/directAcpAgentBackend.test.ts b/test/main/agent/manager/directAcpAgentBackend.test.ts index d730578983..74a63ef2bf 100644 --- a/test/main/agent/manager/directAcpAgentBackend.test.ts +++ b/test/main/agent/manager/directAcpAgentBackend.test.ts @@ -76,12 +76,13 @@ function createHarness() { { type: 'action', action_type: 'tool_call_permission', + status: 'pending', tool_call: { id: 'tool-call' }, extra: { permissionRequestId: 'permission-request' } } ]) }), - updateAssistantContent: vi.fn() + updateMessageContent: vi.fn().mockReturnValue(true) } const tape = { linkSubagentTape: vi.fn().mockImplementation(async (input) => ({ @@ -253,7 +254,7 @@ describe('direct ACP agent backend', () => { kind: 'permission', granted: true }) - ).resolves.toEqual({ resumed: false }) + ).resolves.toEqual({ resumed: false, handledInline: true }) expect(harness.instance.resolvePermissionRequest).toHaveBeenCalledWith( 'permission-request', true @@ -321,42 +322,121 @@ describe('direct ACP agent backend', () => { expect(harness.instance.resolvePermissionRequest).not.toHaveBeenCalled() }) - it('rejects permission requests that are no longer hydrated', async () => { + it.each([true, false])( + 'repairs an orphan only after its turn ends (active=%s)', + async (active) => { + const harness = createHarness() + harness.instance.getActiveGeneration.mockReturnValue( + active ? { eventId: 'assistant', runId: 'run' } : null + ) + harness.instance.resolvePermissionRequest.mockReturnValueOnce(false) + const handle = harness.backend.open(sessionId, descriptor) + + await expect( + handle.toolInteractions.respond('assistant', 'tool-call', { + kind: 'permission', + granted: true + }) + ).rejects.toThrow('Unknown ACP permission request: permission-request') + + expect(harness.instance.resolvePermissionRequest).toHaveBeenCalledWith( + 'permission-request', + true + ) + expect(harness.instance.resolvePermissionRequest).toHaveBeenCalledTimes(1) + if (active) expect(harness.transcript.updateMessageContent).not.toHaveBeenCalled() + else { + const { content } = await harness.transcript.getMessage() + const [pending] = JSON.parse(content) + expect(harness.transcript.updateMessageContent).toHaveBeenCalledWith( + 'assistant', + JSON.stringify([ + { ...pending, status: 'error', extra: { ...pending.extra, needsUserAction: false } } + ]), + content + ) + } + } + ) + + it('acknowledges a repeated grant without changing the settled decision', async () => { const harness = createHarness() - harness.instance.resolvePermissionRequest.mockReturnValueOnce(false) - const handle = harness.backend.open(sessionId, descriptor) + const message = await harness.transcript.getMessage() + const [permission] = JSON.parse(message.content) + harness.transcript.getMessage.mockResolvedValue({ + ...message, + status: 'sent', + content: JSON.stringify([{ ...permission, status: 'granted' }]) + }) + const { toolInteractions } = harness.backend.open(sessionId, descriptor) await expect( - handle.toolInteractions.respond('assistant', 'tool-call', { + toolInteractions.respond('assistant', 'tool-call', { + kind: 'permission', + granted: true + }) + ).resolves.toEqual({ resumed: false, handledInline: true }) + await expect( + toolInteractions.respond('assistant', 'tool-call', { kind: 'permission', granted: false }) - ).rejects.toThrow('Unknown ACP permission request: permission-request') + ).rejects.toThrow('Unknown ACP permission request') + await expect(toolInteractions.dismiss('assistant', 'tool-call')).resolves.toBe(false) + expect(harness.instance.resolvePermissionRequest).not.toHaveBeenCalled() + expect(harness.transcript.updateMessageContent).not.toHaveBeenCalled() + }) - expect(harness.instance.resolvePermissionRequest).toHaveBeenCalledWith( - 'permission-request', - false + it('routes another approval on the same tool call to its own request', async () => { + const harness = createHarness() + const message = await harness.transcript.getMessage() + const [first] = JSON.parse(message.content) + harness.transcript.getMessage.mockResolvedValue({ + ...message, + content: JSON.stringify([ + { ...first, status: 'granted' }, + { ...first, extra: { permissionRequestId: 'second' } } + ]) + }) + const { toolInteractions } = harness.backend.open(sessionId, descriptor) + const allow = { kind: 'permission', granted: true } as const + + await expect(toolInteractions.respond('assistant', 'tool-call', allow)).rejects.toThrow( + 'ACP permission request not found' + ) + await expect(toolInteractions.dismiss('assistant', 'tool-call')).resolves.toBe(false) + await toolInteractions.respond('assistant', 'tool-call', { + ...allow, + permissionRequestId: 'permission-request' + }) + expect(harness.instance.resolvePermissionRequest).not.toHaveBeenCalled() + await toolInteractions.respond('assistant', 'tool-call', { + ...allow, + permissionRequestId: 'second' + }) + expect(harness.instance.resolvePermissionRequest).toHaveBeenCalledExactlyOnceWith( + 'second', + true ) }) - it('durably dismisses an ACP permission when the runtime is unavailable', async () => { + it('dismisses an orphan only while its stored content matches', async () => { const harness = createHarness() harness.runtime.getHydrated.mockReturnValue(undefined) - const handle = harness.backend.open(sessionId, descriptor) - - await expect(handle.toolInteractions.dismiss('assistant', 'tool-call')).resolves.toBe(true) - - expect(harness.transcript.updateAssistantContent).toHaveBeenCalledTimes(1) - const [messageId, blocks] = harness.transcript.updateAssistantContent.mock.calls[0] as [ - string, - AssistantMessageBlock[] - ] - expect(messageId).toBe('assistant') - const block = blocks.find( - (candidate) => candidate.type === 'action' && candidate.action_type === 'tool_call_permission' + const { toolInteractions } = harness.backend.open(sessionId, descriptor) + const { content } = await harness.transcript.getMessage() + const [pending] = JSON.parse(content) + harness.transcript.updateMessageContent.mockReturnValueOnce(false) + + await expect(toolInteractions.dismiss('assistant', 'tool-call')).resolves.toBe(false) + await expect(toolInteractions.dismiss('assistant', 'tool-call')).resolves.toBe(true) + expect(harness.transcript.updateMessageContent).toHaveBeenCalledWith( + 'assistant', + JSON.stringify([ + { ...pending, status: 'error', extra: { ...pending.extra, needsUserAction: false } } + ]), + content ) - expect(block?.status).toBe('denied') - expect(block?.extra?.needsUserAction).toBe(false) }) it('exposes direct transfer, pending, subagent, generation, and close facets', async () => { diff --git a/test/main/routes/contracts.test.ts b/test/main/routes/contracts.test.ts index 452ee8512c..72a728fcb3 100644 --- a/test/main/routes/contracts.test.ts +++ b/test/main/routes/contracts.test.ts @@ -1461,25 +1461,15 @@ describe('main kernel contracts', () => { customModels: [] }) - expect( - chatRespondToolInteractionRoute.input.parse({ + for (const permission of [{}, { permissionRequestId: 'acp-request-1' }]) { + const decision = { sessionId: 'session-1', messageId: 'message-1', toolCallId: 'tool-1', - response: { - kind: 'permission', - granted: true - } - }) - ).toEqual({ - sessionId: 'session-1', - messageId: 'message-1', - toolCallId: 'tool-1', - response: { - kind: 'permission', - granted: true + response: { kind: 'permission', granted: true, ...permission } } - }) + expect(chatRespondToolInteractionRoute.input.parse(decision)).toEqual(decision) + } expect(() => providersTestConnectionRoute.input.parse({ diff --git a/test/main/session/data/transcriptAtomicity.test.ts b/test/main/session/data/transcriptAtomicity.test.ts index fa9aff2c25..a6866527dc 100644 --- a/test/main/session/data/transcriptAtomicity.test.ts +++ b/test/main/session/data/transcriptAtomicity.test.ts @@ -79,6 +79,40 @@ describeIfSqlite('SessionTranscript keeps transcript and Tape writes atomic', () } } + it('preserves final output and status when repairing a stale permission snapshot', () => { + const { close, transcript } = createTranscript() + try { + const messageId = transcript.createAssistantMessage('s1', 1) + const permission = { + type: 'action', + action_type: 'tool_call_permission', + status: 'pending', + timestamp: 1 + } as const + transcript.updateAssistantContent(messageId, [permission]) + const stale = transcript.getMessage(messageId)!.content + transcript.finalizeAssistantMessage(messageId, [permission, ...blocks], '{}') + const final = transcript.getMessage(messageId)! + const closed = { ...permission, status: 'error' } + + expect(transcript.updateMessageContent(messageId, JSON.stringify([closed]), stale)).toBe( + false + ) + expect(transcript.getMessage(messageId)).toEqual(final) + const repaired = JSON.parse(final.content) + repaired[0].status = 'error' + expect( + transcript.updateMessageContent(messageId, JSON.stringify(repaired), final.content) + ).toBe(true) + expect(transcript.getMessage(messageId)).toMatchObject({ + status: 'sent', + content: JSON.stringify(repaired) + }) + } finally { + close() + } + }) + it('does not commit a user message whose Tape fact failed to append', () => { const { close, database, transcript, setTapeFailing } = createTranscript() try { diff --git a/test/renderer/components/ChatPage.test.ts b/test/renderer/components/ChatPage.test.ts index 35ec37d4ec..821e4ab4c1 100644 --- a/test/renderer/components/ChatPage.test.ts +++ b/test/renderer/components/ChatPage.test.ts @@ -123,6 +123,8 @@ const setup = async (options: SetupOptions = {}) => { selectSession: vi.fn().mockResolvedValue(undefined) }) const messageStore = reactive({ + acknowledgedInteractions: new Map(), + inFlightInteractions: new Map(), messages: options.messages ?? [ buildAssistantMessage([ { diff --git a/test/renderer/features/chat-page/composables/useToolInteraction.test.ts b/test/renderer/features/chat-page/composables/useToolInteraction.test.ts index 3a33a47aa9..ec6489c4ac 100644 --- a/test/renderer/features/chat-page/composables/useToolInteraction.test.ts +++ b/test/renderer/features/chat-page/composables/useToolInteraction.test.ts @@ -1,4 +1,4 @@ -import { effectScope, nextTick, ref } from 'vue' +import { effectScope, nextTick, ref, shallowReactive } from 'vue' import { beforeEach, describe, expect, it, vi } from 'vitest' import { useToolInteraction } from '@/features/chat-page/composables/useToolInteraction' import { createDeferred } from '../../../utils/deferred' @@ -6,24 +6,36 @@ import { createDeferred } from '../../../utils/deferred' function createAssistantMessage(id: string, blocks: unknown[], status = 'pending') { return { id, + sessionId: 's1', role: 'assistant', status, content: JSON.stringify(blocks) } } -function createHarness(messages: Array>, onResponseFailed?: any) { +function createHarness( + messages: Array>, + onResponseFailed?: any, + interactionState = { + acknowledgedInteractions: shallowReactive(new Map()), + inFlightInteractions: shallowReactive(new Map()) + } +) { const sessionId = ref('s1') + const sessionKind = ref('regular') const messageRecords = ref(messages) const messageStore = { + ...interactionState, + get committedSession() { + return { id: sessionId.value, sessionKind: sessionKind.value } + }, get messages() { return messageRecords.value }, getAssistantMessageBlocks: vi.fn((message: { content: string }) => JSON.parse(message.content)) } const chatClient = { - respondToolInteraction: vi.fn().mockResolvedValue({ handledInline: false }), - dismissToolInteraction: vi.fn().mockResolvedValue({ dismissed: true }) + respondToolInteraction: vi.fn().mockResolvedValue({ handledInline: false }) } const loadMessagesForSession = vi.fn().mockResolvedValue({ id: 'restored' }) const applyRestoredSessionSummary = vi.fn() @@ -50,6 +62,8 @@ function createHarness(messages: Array>, onResponseFaile return { toolInteraction, + interactionState, + sessionKind, sessionId, messageRecords, chatClient, @@ -142,10 +156,79 @@ describe('useToolInteraction', () => { harness.stop() }) - it('submits one response at a time and refreshes the current page session afterwards', async () => { + it.each(['parent', 'child'] as const)( + 'keeps the same child approval acknowledged when submitted from %s', + async (source) => { + const snapshot = (view: 'parent' | 'child', permissionRequestId: string) => { + const actionBlock = { + type: 'action', + action_type: 'tool_call_permission', + status: 'pending', + tool_call: { id: 'shared-call', name: 'agent', params: '{}' }, + extra: { permissionRequestId } + } + const waitingInteraction = { + type: 'permission', + messageId: 'CM', + toolCallId: 'shared-call', + actionBlock + } + const progress = { + type: 'tool_call', + tool_call: { name: 'subagent_orchestrator' }, + extra: { + subagentProgress: JSON.stringify({ + tasks: [{ sessionId: 'child', waitingInteraction }] + }) + } + } + const row = + view === 'child' + ? createAssistantMessage('CM', [actionBlock]) + : createAssistantMessage('PM', [progress]) + return { ...row, sessionId: view } + } + const first = snapshot(source, 'original') + const other = source === 'parent' ? 'child' : 'parent' + const harness = createHarness([first]) + harness.sessionId.value = source + harness.sessionKind.value = source === 'parent' ? 'regular' : 'subagent' + const allow = { kind: 'permission', granted: true } as const + harness.chatClient.respondToolInteraction.mockImplementationOnce(async () => { + // The submitting view can settle before the other projection is refreshed. + harness.messageRecords.value = [{ ...first, content: '[]', status: 'sent' }] + return { handledInline: true } + }) + await harness.toolInteraction.onToolInteractionRespond(allow) + harness.stop() + const mirrored = snapshot(other, 'original') + const next = createHarness([mirrored], undefined, harness.interactionState) + next.sessionId.value = other + next.sessionKind.value = other === 'parent' ? 'regular' : 'subagent' + next.messageRecords.value = [ + mirrored, + { ...createAssistantMessage('unrelated', [], 'sent'), sessionId: other } + ] + await nextTick() + expect(next.toolInteraction.activePendingInteraction.value).toBeNull() + await next.toolInteraction.onToolInteractionRespond(allow) + expect(next.chatClient.respondToolInteraction).not.toHaveBeenCalled() + next.messageRecords.value = [snapshot(other, 'next')] + await next.toolInteraction.onToolInteractionRespond(allow) + expect(next.chatClient.respondToolInteraction).toHaveBeenCalledExactlyOnceWith({ + sessionId: 'child', + messageId: 'CM', + toolCallId: 'shared-call', + response: { ...allow, permissionRequestId: 'next' } + }) + next.stop() + } + ) + + it('submits one decision across navigation while the first response is in flight', async () => { const response = createDeferred<{ handledInline?: boolean }>() const harness = createHarness([ - createAssistantMessage('m1', [ + createAssistantMessage('in-flight', [ { type: 'action', action_type: 'tool_call_permission', @@ -169,22 +252,68 @@ describe('useToolInteraction', () => { expect(harness.chatClient.respondToolInteraction).toHaveBeenCalledTimes(1) harness.sessionId.value = 's2' + harness.stop() + const restored = createHarness( + harness.messageRecords.value, + undefined, + harness.interactionState + ) + expect(restored.toolInteraction.isHandlingInteraction.value).toBe(true) + await restored.toolInteraction.onToolInteractionRespond({ kind: 'permission', granted: false }) + expect(restored.chatClient.respondToolInteraction).not.toHaveBeenCalled() + response.resolve({ handledInline: true }) await firstResponse expect(harness.chatClient.respondToolInteraction).toHaveBeenCalledWith({ sessionId: 's1', - messageId: 'm1', + messageId: 'in-flight', toolCallId: 'tool-1', response: { kind: 'permission', granted: true } }) expect(harness.loadMessagesForSession).not.toHaveBeenCalled() expect(harness.applyRestoredSessionSummary).not.toHaveBeenCalled() - expect(harness.toolInteraction.isHandlingInteraction.value).toBe(false) - harness.stop() + expect(restored.toolInteraction.isHandlingInteraction.value).toBe(false) + expect(restored.toolInteraction.activePendingInteraction.value).toBeNull() + restored.stop() }) - it('drops an unresolvable interaction when the client rejects', async () => { + it('ignores an old response after a session is removed and restored with the same IDs', async () => { + const messages = [ + createAssistantMessage('restored', [ + { + type: 'action', + action_type: 'tool_call_permission', + status: 'pending', + tool_call: { id: 'tool', name: 'agent', params: '{}' } + } + ]) + ] + const original = createHarness(messages) + const allow = { kind: 'permission', granted: true } as const + const first = createDeferred<{ resumed: boolean }>() + original.chatClient.respondToolInteraction.mockReturnValue(first.promise) + const oldResponse = original.toolInteraction.onToolInteractionRespond(allow) + original.stop() + original.interactionState.inFlightInteractions.clear() + const restored = createHarness(messages, undefined, original.interactionState) + const second = createDeferred<{ resumed: boolean }>() + restored.chatClient.respondToolInteraction.mockReturnValue(second.promise) + const newResponse = restored.toolInteraction.onToolInteractionRespond(allow) + + first.resolve({ resumed: true }) + await oldResponse + expect(original.loadMessagesForSession).not.toHaveBeenCalled() + expect(restored.toolInteraction.isHandlingInteraction.value).toBe(true) + expect(restored.toolInteraction.activePendingInteraction.value?.toolCallId).toBe('tool') + second.resolve({ resumed: false }) + await newResponse + expect(restored.toolInteraction.isHandlingInteraction.value).toBe(false) + expect(restored.toolInteraction.activePendingInteraction.value?.toolCallId).toBe('tool') + restored.stop() + }) + + it('keeps an approval retryable when the response fails', async () => { const error = new Error('response failed') const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined) const harness = createHarness([ @@ -204,16 +333,8 @@ describe('useToolInteraction', () => { granted: true } as any) - // A rejected respond is treated as a stale interaction: the page refreshes - // and, because the block is still pending, releases the approval UI. expect(harness.loadMessagesForSession).toHaveBeenCalledWith('s1') - expect(harness.chatClient.dismissToolInteraction).toHaveBeenCalledWith({ - sessionId: 's1', - messageId: 'm1', - toolCallId: 'tool-1' - }) - expect(harness.toolInteraction.pendingInteractions.value).toEqual([]) - expect(harness.toolInteraction.activePendingInteraction.value).toBeNull() + expect(harness.toolInteraction.activePendingInteraction.value?.toolCallId).toBe('tool-1') expect(harness.toolInteraction.isHandlingInteraction.value).toBe(false) expect(consoleError).toHaveBeenCalledWith('[ChatPage] respond tool interaction failed:', error) consoleError.mockRestore() @@ -261,7 +382,6 @@ describe('useToolInteraction', () => { expect.objectContaining({ toolCallId: 'tool-2', response }) ) expect(harness.toolInteraction.activePendingInteraction.value).toBeNull() - expect(harness.chatClient.dismissToolInteraction).not.toHaveBeenCalled() harness.messageRecords.value = [ createAssistantMessage( @@ -275,43 +395,47 @@ describe('useToolInteraction', () => { harness.stop() }) - it('releases a native question from a replaced scope without declining on the host', async () => { - const error = new Error( - "Error invoking remote method 'deepchat:route:invoke': Error: Native interaction belongs to a replaced session scope" - ) - const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined) - const onResponseFailed = vi.fn() - const harness = createHarness( - [ - createAssistantMessage('m1', [ - { - type: 'action', - action_type: 'question_request', - status: 'pending', - extra: { dimRequestId: 'replaced-request' }, - tool_call: { id: 'tool-1', name: 'ask_user', params: '{}' } - } - ]) - ], - onResponseFailed - ) - harness.chatClient.respondToolInteraction.mockRejectedValueOnce(error) + it.each(['question_request', 'tool_call_permission'] as const)( + 'releases a %s from a replaced scope without declining on the host', + async (actionType) => { + const error = new Error( + "Error invoking remote method 'deepchat:route:invoke': Error: Native interaction belongs to a replaced session scope" + ) + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const onResponseFailed = vi.fn() + const harness = createHarness( + [ + createAssistantMessage('m1', [ + { + type: 'action', + action_type: actionType, + status: 'pending', + extra: actionType === 'question_request' ? { dimRequestId: 'replaced-request' } : {}, + tool_call: { + id: 'replaced-tool', + name: actionType === 'question_request' ? 'ask_user' : 'agent', + params: '{}' + } + } + ]) + ], + onResponseFailed + ) + harness.chatClient.respondToolInteraction.mockRejectedValueOnce(error) - await harness.toolInteraction.onToolInteractionRespond({ - kind: 'question_option', - optionLabel: 'Yes' - }) + await harness.toolInteraction.onToolInteractionRespond( + actionType === 'question_request' + ? { kind: 'question_option', optionLabel: 'Yes' } + : { kind: 'permission', granted: true } + ) - expect(onResponseFailed).toHaveBeenCalledWith( - expect.objectContaining({ actionType: 'question_request' }), - error - ) - expect(harness.toolInteraction.activePendingInteraction.value).toBeNull() - expect(harness.toolInteraction.isHandlingInteraction.value).toBe(false) - expect(harness.chatClient.dismissToolInteraction).not.toHaveBeenCalled() - consoleError.mockRestore() - harness.stop() - }) + expect(onResponseFailed).toHaveBeenCalledWith(expect.objectContaining({ actionType }), error) + expect(harness.toolInteraction.activePendingInteraction.value).toBeNull() + expect(harness.toolInteraction.isHandlingInteraction.value).toBe(false) + consoleError.mockRestore() + harness.stop() + } + ) it('reports a rejected response to the page instead of only dropping the interaction', async () => { const error = new Error('response failed') @@ -345,14 +469,15 @@ describe('useToolInteraction', () => { harness.stop() }) - it('drops a responded interaction that stays pending after reload so the UI advances', async () => { + it('retries an unacknowledged Allow in its owning session and advances once acknowledged', async () => { const harness = createHarness([ - createAssistantMessage('m1', [ + createAssistantMessage('delegation', [ { type: 'action', action_type: 'tool_call_permission', status: 'pending', - tool_call: { id: 'tool-1', name: 'write_file', params: '{}' } + extra: { permissionRequestId: 'acp-request' }, + tool_call: { id: 'tool-1', name: 'agent', params: '{}' } } ]), createAssistantMessage('m2', [ @@ -364,22 +489,24 @@ describe('useToolInteraction', () => { } ]) ]) - // The main process returns without resolving the first interaction (its - // backing run is gone): the block stays pending after the reload. - harness.chatClient.respondToolInteraction.mockResolvedValue({ resumed: false }) - - await harness.toolInteraction.onToolInteractionRespond({ - kind: 'permission', - granted: true - } as any) + harness.chatClient.respondToolInteraction + .mockResolvedValueOnce({ resumed: false }) + .mockResolvedValueOnce({ resumed: true }) + const allow = { kind: 'permission', granted: true } as const + harness.sessionId.value = 's2' + expect(harness.toolInteraction.activePendingInteraction.value).toBeNull() + harness.sessionId.value = 's1' + await harness.toolInteraction.onToolInteractionRespond(allow) expect(harness.loadMessagesForSession).toHaveBeenCalledWith('s1') - // The stale approval is dropped, durably dismissed on the main process, and - // the next pending interaction surfaces. - expect(harness.chatClient.dismissToolInteraction).toHaveBeenCalledWith({ + expect(harness.toolInteraction.activePendingInteraction.value?.toolCallId).toBe('tool-1') + await harness.toolInteraction.onToolInteractionRespond(allow) + expect(harness.chatClient.respondToolInteraction).toHaveBeenCalledTimes(2) + expect(harness.chatClient.respondToolInteraction).toHaveBeenLastCalledWith({ sessionId: 's1', - messageId: 'm1', - toolCallId: 'tool-1' + messageId: 'delegation', + toolCallId: 'tool-1', + response: { ...allow, permissionRequestId: 'acp-request' } }) expect(harness.toolInteraction.pendingInteractions.value).toMatchObject([ { messageId: 'm2', toolCallId: 'tool-2', actionType: 'question_request' } @@ -426,7 +553,6 @@ describe('useToolInteraction', () => { expect(harness.toolInteraction.pendingInteractions.value).toEqual([]) expect(harness.toolInteraction.activePendingInteraction.value).toBeNull() - expect(harness.chatClient.dismissToolInteraction).not.toHaveBeenCalled() expect(harness.loadMessagesForSession).toHaveBeenCalledWith('s1') harness.stop() })