Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 56 additions & 39 deletions src/main/agent/manager/directAcpAgentBackend.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type {
AssistantMessageBlock,
ChatMessageRecord,
DeepChatSessionState,
MessageStartResult
} from '@shared/types/agent-interface'
Expand All @@ -9,6 +10,7 @@ import type { AcpAgentRuntime, AcpAgentRuntimeSessionInput } from '@/agent/acp/i
import type {
SessionStatePort,
SessionTapePort,
SessionTranscriptPort,
SessionTranscriptReadPort
} from '@/session/data/contracts'
import type {
Expand All @@ -21,13 +23,8 @@ import type {
export interface DirectAcpAgentBackendOptions {
runtime: AcpAgentRuntime
sessionState: SessionStatePort
transcript: Pick<SessionTranscriptReadPort, 'getMessage' | 'hasMessages'> & {
updateAssistantContent(
messageId: string,
blocks: AssistantMessageBlock[],
metadata?: string
): void
}
transcript: Pick<SessionTranscriptReadPort, 'getMessage' | 'hasMessages'> &
Pick<SessionTranscriptPort, 'updateMessageContent'>
tape: Pick<SessionTapePort, 'linkSubagentTape'>
deleteDurableSession(sessionId: AppSessionId): Promise<void>
resolveInput(
Expand Down Expand Up @@ -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 => {
Expand All @@ -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<void> => {
let runtimeError: unknown
try {
Expand Down Expand Up @@ -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<MessageStartResult> {
Expand Down
2 changes: 1 addition & 1 deletion src/main/session/data/contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
27 changes: 14 additions & 13 deletions src/main/session/data/transcript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions src/renderer/api/ChatClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading