Skip to content

AI-native design editor. Open-source Figma alternative.

feat: continue saved Claude Code chats through ACP session/resume (#1718)

Victor Shymko064402c2fe8d
diff --git a/changes/1718/added.md b/changes/1718/added.md
new file mode 100644
index 000000000..a2cf29a8c
--- /dev/null
+++ b/changes/1718/added.md
@@ -0,0 +1 @@
+- On desktop, a Claude Code or Codex conversation reopened from chat history continues in the agent's own session, so the agent remembers what was said, instead of being read-only.
diff --git a/packages/core/src/ai/providers.ts b/packages/core/src/ai/providers.ts
index 2bd905cd3..b75d671f0 100644
--- a/packages/core/src/ai/providers.ts
+++ b/packages/core/src/ai/providers.ts
@@ -20,6 +20,11 @@ export interface ACPAgentDef {
* which the desktop shell scope pins under `<command>-sign-in`.
*/
signIn?: { via: 'acp'; method: string } | { via: 'terminal'; method: string; args: string[] }
+ /**
+ * Whether a saved chat continues the agent's own session through ACP `session/resume`, so the
+ * agent keeps what was said. Set only for agents whose adapter is known to resume reliably.
+ */
+ resumesSessions?: boolean
}
export const ACP_AGENTS: ACPAgentDef[] = [
@@ -36,7 +41,8 @@ export const ACP_AGENTS: ACPAgentDef[] = [
via: 'terminal',
method: 'claude-ai-login',
args: ['--cli', 'auth', 'login', '--claudeai']
- }
+ },
+ resumesSessions: true
},
{
id: 'codex',
@@ -47,7 +53,8 @@ export const ACP_AGENTS: ACPAgentDef[] = [
adapterPackage: '@agentclientprotocol/codex-acp',
setupURL: 'https://developers.openai.com/codex/cli',
installCommand: 'npm i -g @agentclientprotocol/codex-acp',
- signIn: { via: 'acp', method: 'chat-gpt' }
+ signIn: { via: 'acp', method: 'chat-gpt' },
+ resumesSessions: true
},
{
id: 'gemini-cli',
diff --git a/packages/docs/development/ai-chat.md b/packages/docs/development/ai-chat.md
index bda49ce52..55f3f3c16 100644
--- a/packages/docs/development/ai-chat.md
+++ b/packages/docs/development/ai-chat.md
@@ -79,6 +79,8 @@ A reply that finished or failed on its own, rather than one you stopped or one c
An ACP agent calls OpenPencil's tools through the MCP server, and its replies keep their edits the same way. The ACP transport (`transports/acp.ts`) starts a run for each reply with `startAgentRun`, without the built-in chat's agent presence, since the agent shows through its MCP session, and ends it however the reply ends. Each MCP tool call carries the chat id from the agent's `x-openpencil-chat` header and the call's id in the agent's conversation, which Codex sends as `_meta.callId` and Claude Code as `_meta["claudecode/toolUseId"]`. While the reply goes on, a call that edits the chat's own document joins the run through `runEditorTool`, which `automation/bridge/tool-handlers.ts` calls with the reply, so Revert, Restore, and the undone marks work as for a provider model.
+Each request while the agent starts must answer within `AGENT_START_TIMEOUT_MS`, and Stop stops an agent that is still starting, so a message never waits on an agent that does not answer; either way the agent never gets the message.
+
## Undo and the model
A turn keeps the reply's calls and their undo entries. On every undo history change, each turn works out which of its calls are undone with `UndoManager.stateOf`: an entry on the redo stack is undone, one on the undo stack applied. An entry that left the history keeps its last state; undone and then cleared from Redo by a new edit, it stays undone. Changes are written to the reply's metadata, and the transcript reads only the metadata.
@@ -91,6 +93,8 @@ Edit → Undo and the chat's **Revert changes** therefore end in the same state:
A reply's metadata (`chat/metadata.ts`) keeps whether you stopped it, and its edits with those undone and what the model was last told. Conversations save messages with `structuredClone`, so metadata is written from the plain message, never from the chat's reactive copy. Reopening a conversation settles any reply saved mid-way. The undo history does not survive closing a document, so a reopened reply keeps its marks but offers no Revert or Restore.
+A reopened ACP or Pi conversation is read-only, since the conversation's context lives in the agent's own session, except with an agent whose `ACPAgentDef` sets `resumesSessions`: Claude Code and Codex. Once the agent starts answering a prompt, the ACP transport reports the agent's session id, since neither agent can resume a session that never took one, which the conversation saves as `agentSession`, and a later chat on the same agent continues it through ACP `session/resume` in the same agent workspace, without the instructions again and without replaying the transcript the chat already shows (`agents/acp/session.ts`, `chat/history/controller.ts`). A session the agent can no longer resume fails the message instead of starting a new session that would not know the conversation; the conversation forgets it, and the chat takes no more messages and shows as read-only. A conversation continued on another agent or model forgets its session too, and a session started on a conversation that already has messages is never saved, since it missed some of them.
+
## Compaction
A compaction is a message in the conversation (`chat/compaction/marker.ts`): a user message whose text is the summary and whose metadata marks it, so the transcript draws a divider and any backend that knows nothing of compaction still reads the summary. `messagesSinceCompaction` gives what a model reads, from the latest marker on; the tool loop sends only that. Undo notes still cover edits before it, which the summary describes as made. Saved conversations keep every message, so nothing changes in storage.
diff --git a/src/app/ai/agents/acp/process.ts b/src/app/ai/agents/acp/process.ts
index 3b8465c87..7f39029d1 100644
--- a/src/app/ai/agents/acp/process.ts
+++ b/src/app/ai/agents/acp/process.ts
@@ -8,6 +8,13 @@ export type TauriChild = {
kill(): Promise<void>
}
+/** A started agent: its process, and the pipes the ACP connection reads and writes. */
+export interface ACPProcess {
+ child: TauriChild
+ input: WritableStream<Uint8Array>
+ output: ReadableStream<Uint8Array>
+}
+
type ACPProcessOptions = {
command: string
args: string[]
@@ -22,7 +29,7 @@ export async function spawnACPProcess({
logId,
destroying,
onUnexpectedClose
-}: ACPProcessOptions) {
+}: ACPProcessOptions): Promise<ACPProcess> {
const resolved = resolvePlatformCommand(commandName, args)
const command = Command.create(resolved.command, resolved.args, {
encoding: 'raw',
diff --git a/src/app/ai/agents/acp/session.ts b/src/app/ai/agents/acp/session.ts
new file mode 100644
index 000000000..31433ff7c
--- /dev/null
+++ b/src/app/ai/agents/acp/session.ts
@@ -0,0 +1,87 @@
+import type { ClientSideConnection, InitializeResponse, McpServer } from '@agentclientprotocol/sdk'
+
+import { acpAgentFor } from '@open-pencil/core/constants'
+import type { ACPAgentDef, ACPAgentID, AIProviderID } from '@open-pencil/core/constants'
+
+import type { OwnToolsLink } from './tools'
+
+/** What an agent session needs to open, whether it starts or continues a saved one. */
+export interface AgentSessionRequest {
+ cwd: string
+ mcpServers: McpServer[]
+ meta: OwnToolsLink['meta']
+ /** The session a saved chat ran in, which the agent continues instead of starting anew. */
+ resume: string | null
+}
+
+export interface OpenedAgentSession {
+ sessionId: string
+ model: string | null
+ /** Whether the agent continued a saved session, which already holds the instructions. */
+ resumed: boolean
+}
+
+type SessionConnection = Pick<ClientSideConnection, 'newSession' | 'unstable_resumeSession'>
+
+/** ACP's `auth_required` error, which an agent returns for a session before sign-in. */
+export function isAuthRequiredError(e: unknown): boolean {
+ return typeof e === 'object' && e !== null && 'code' in e && e.code === -32000
+}
+
+/** The ACP agent a provider runs, when OpenPencil continues that agent's saved sessions. */
+export function resumingAgent(providerID: AIProviderID): ACPAgentID | null {
+ const agent = acpAgentFor(providerID)
+ return agent?.resumesSessions ? agent.id : null
+}
+
+function canResume(agentDef: ACPAgentDef, initialized: InitializeResponse): boolean {
+ return (
+ agentDef.resumesSessions === true &&
+ Boolean(initialized.agentCapabilities?.sessionCapabilities?.resume)
+ )
+}
+
+/** The agent cannot continue the saved session, which a new session would not know. */
+export class AgentSessionResumeError extends Error {
+ constructor(agentDef: ACPAgentDef, cause?: unknown) {
+ super(
+ `${agentDef.name} could not continue this conversation's session. Start a new chat to continue working.`,
+ { cause }
+ )
+ this.name = 'AgentSessionResumeError'
+ }
+}
+
+/**
+ * Starts the agent's session, or continues the saved one through `session/resume`, which keeps
+ * the agent's context without replaying the transcript the chat already shows.
+ */
+export async function openAgentSession(
+ connection: SessionConnection,
+ agentDef: ACPAgentDef,
+ initialized: InitializeResponse,
+ { cwd, mcpServers, meta, resume }: AgentSessionRequest
+): Promise<OpenedAgentSession> {
+ if (resume === null) {
+ const result = await connection.newSession({ cwd, mcpServers, _meta: meta })
+ return {
+ sessionId: result.sessionId,
+ model: result.models?.currentModelId ?? null,
+ resumed: false
+ }
+ }
+ // The agent no longer offers resume, as after a downgrade: a new session would lose the context.
+ if (!canResume(agentDef, initialized)) throw new AgentSessionResumeError(agentDef)
+ try {
+ const result = await connection.unstable_resumeSession({
+ sessionId: resume,
+ cwd,
+ mcpServers,
+ _meta: meta
+ })
+ return { sessionId: resume, model: result.models?.currentModelId ?? null, resumed: true }
+ } catch (e) {
+ if (isAuthRequiredError(e)) throw e
+ throw new AgentSessionResumeError(agentDef, e)
+ }
+}
diff --git a/src/app/ai/chat/history/controller.ts b/src/app/ai/chat/history/controller.ts
index 6f1228591..497564dcc 100644
--- a/src/app/ai/chat/history/controller.ts
+++ b/src/app/ai/chat/history/controller.ts
@@ -1,5 +1,6 @@
import type { UIMessage } from 'ai'
-import { ref, shallowRef } from 'vue'
+import { omit } from 'es-toolkit'
+import { computed, ref, shallowRef } from 'vue'
import { chatDocumentId, resolveChatDocumentId, type ChatDocumentEditor } from './document'
import { createConversationStore } from './idb'
@@ -7,6 +8,7 @@ import { restoreMessages } from './messages'
import { createHistoryPersistence } from './persistence'
import { createHistorySession } from './session'
import type {
+ AgentSessionRef,
Conversation,
ConversationMeta,
ConversationStore,
@@ -23,6 +25,8 @@ export function createConversationHistory<TChat extends HistoryChat>(
const messages = shallowRef<UIMessage[]>([])
const conversations = ref<ConversationMeta[]>([])
const readOnly = ref(false)
+ /** The live chat's agent could not continue the saved session, so that chat takes no more. */
+ const chatEnded = ref(false)
const busy = ref(false)
let ownerRecoveryId: string | null = null
// Weak, so the history does not keep a closed document's editor alive.
@@ -58,6 +62,7 @@ export function createConversationHistory<TChat extends HistoryChat>(
conversations.value = await store.list()
}
function detach() {
+ chatEnded.value = false
return session.detach(flush)
}
@@ -129,25 +134,64 @@ export function createConversationHistory<TChat extends HistoryChat>(
await refresh()
}
+ /** The saved agent session the chat's agent continues, when it is that agent's. */
+ function resumableSession(conversation: Conversation | null): string | null {
+ const saved = conversation?.agentSession
+ return saved && saved.agent === runtime.resumingAgent() ? saved.id : null
+ }
+ const continuesAgentSession = computed(() => resumableSession(current.value) !== null)
+ /**
+ * A saved transcript no chat can continue: it ran on an external agent, or the chat now runs on
+ * one, and that agent does not continue its saved session.
+ */
+ const agentReadOnly = computed(() => {
+ const conversation = current.value
+ if (!conversation?.messages.length || continuesAgentSession.value) return false
+ return runtime.backend() !== 'direct' || conversation.backend !== 'direct'
+ })
+
+ /** Saves or forgets the session a conversation's agent runs in, while it is current. */
+ function recordAgentSession(conversationId: string, agentSession: AgentSessionRef | null) {
+ const conversation = current.value
+ if (!conversation || conversation.id !== conversationId) return
+ const saved = conversation.agentSession
+ if (saved?.agent === agentSession?.agent && saved?.id === agentSession?.id) return
+ current.value = agentSession
+ ? { ...conversation, agentSession }
+ : omit(conversation, ['agentSession'])
+ void flush().catch(() => undefined)
+ }
+
function ensureChat() {
return serialize(async () => {
if (readOnly.value && owner?.deref() === runtime.getEditor()) return null
await loadDocument()
- // A restored transcript does not restore an external agent session.
- if (
- current.value?.messages.length &&
- !session.chat &&
- (runtime.backend() !== 'direct' || current.value.backend !== 'direct')
- )
- return null
+ const resume = resumableSession(current.value)
+ if (chatEnded.value) await detach()
+ if (!session.chat && agentReadOnly.value) return null
const editor = runtime.getEditor()
- const next = await runtime.ensureChat(messages.value, current.value?.id)
+ const conversation = current.value
+ // Only a session that sees the whole conversation is saved to continue it.
+ const recordsFor =
+ conversation && (resume !== null || !messages.value.length) ? conversation.id : null
+ const next = await runtime.ensureChat(messages.value, conversation?.id, {
+ resume,
+ record: (agentSession) => {
+ if (recordsFor !== null) recordAgentSession(recordsFor, agentSession)
+ // The resume failed; the conversation turns read-only once its failure is shown.
+ if (agentSession === null && conversation?.id === current.value?.id)
+ chatEnded.value = true
+ }
+ })
if (runtime.getEditor() !== editor) {
await next?.stop()
await runtime.resetChat()
return null
}
- if (next) session.attach(next, flush)
+ if (!next) return null
+ session.attach(next, flush)
+ // A session that missed what this chat adds must not be continued; kept until the chat starts.
+ if (conversation?.agentSession && resume === null) recordAgentSession(conversation.id, null)
return next
})
}
@@ -199,6 +243,9 @@ export function createConversationHistory<TChat extends HistoryChat>(
messages,
conversations,
readOnly,
+ continuesAgentSession,
+ agentReadOnly,
+ chatEnded,
busy,
storageError,
initialize,
diff --git a/src/app/ai/chat/history/types.ts b/src/app/ai/chat/history/types.ts
index 4dc891854..30bf28b7b 100644
--- a/src/app/ai/chat/history/types.ts
+++ b/src/app/ai/chat/history/types.ts
@@ -1,6 +1,8 @@
import type { Chat } from '@ai-sdk/vue'
import type { UIMessage } from 'ai'
+import type { ACPAgentID } from '@open-pencil/core/constants'
+
import type { AttachmentPresentation } from '@/app/ai/attachment/presentation/types'
import type { ToolChange } from '@/app/ai/tools/changes/types'
@@ -8,11 +10,31 @@ import type { ChatDocumentEditor } from './document'
export type HistoryChat = Pick<Chat<UIMessage>, 'messages' | 'status' | 'stop'>
+/** The external agent session a conversation ran in, which that agent can continue. */
+export interface AgentSessionRef {
+ agent: ACPAgentID
+ id: string
+}
+
+/** How a chat continues a conversation's agent session and reports the one it runs in. */
+export interface AgentSessionLink {
+ /** The saved session the agent continues, or null to start a new one. */
+ resume: string | null
+ /** Saves the session the agent runs in, or forgets the saved one it can no longer continue. */
+ record(session: AgentSessionRef | null): void
+}
+
export interface HistoryRuntime<TChat extends HistoryChat> {
getEditor(): ChatDocumentEditor
- ensureChat(messages?: UIMessage[], sessionId?: string): Promise<TChat | null>
+ ensureChat(
+ messages?: UIMessage[],
+ sessionId?: string,
+ agentSession?: AgentSessionLink
+ ): Promise<TChat | null>
resetChat(): Promise<void>
backend(): ConversationMeta['backend']
+ /** The agent the chat runs on, when it continues saved sessions. */
+ resumingAgent(): ACPAgentID | null
profileId(): string | null
}
@@ -26,6 +48,8 @@ export interface ConversationMeta {
updatedAt: string
profileId: string | null
backend: 'direct' | 'acp' | 'harness'
+ /** Absent until an agent that resumes sessions ran a turn, and in older conversations. */
+ agentSession?: AgentSessionRef
interrupted: boolean
}
diff --git a/src/app/ai/chat/session.ts b/src/app/ai/chat/session.ts
index 72100b180..80837aa56 100644
--- a/src/app/ai/chat/session.ts
+++ b/src/app/ai/chat/session.ts
@@ -38,6 +38,7 @@ import { buildPiMCPServers } from '@/app/integrations/mcp'
import { trackUsage } from '@/app/telemetry'
import { createTraceStore } from './history/idb'
+import type { AgentSessionLink } from './history/types'
import { updateMessage } from './metadata'
import { createRunRecorder } from './trace/recorder'
@@ -55,13 +56,23 @@ type ChatSessionOptions = {
export async function createACPTransport(
providerID: AIProviderID,
store?: EditorStore,
- onUsage?: (usage: AgentTurnUsage) => void
+ onUsage?: (usage: AgentTurnUsage) => void,
+ agentSession?: AgentSessionLink
) {
const agentDef = acpAgentFor(providerID)
if (!agentDef) throw new Error(`Unknown ACP agent: ${providerID}`)
// A folder of its own, not the home folder, whose project settings the agent would read.
- return new ACPChatTransport({ agentDef, cwd: await agentWorkspace(), store, onUsage })
+ // Claude keeps its sessions per folder, so resuming one needs the same folder every time.
+ return new ACPChatTransport({
+ agentDef,
+ cwd: await agentWorkspace(),
+ store,
+ onUsage,
+ resume: agentSession?.resume ?? null,
+ onSession:
+ agentSession && ((id) => agentSession.record(id === null ? null : { agent: agentDef.id, id }))
+ })
}
/**
@@ -151,13 +162,22 @@ export function createChatSessionManager({
if (errors.length) throw new AggregateError(errors, 'Agent transport teardown failed')
}
- async function createActiveACPTransport(store: EditorStore, context: AIDiagnosticContext) {
+ /** `provider` is the one the chat chose, which a profile change while the agent starts keeps. */
+ async function createActiveACPTransport(
+ store: EditorStore,
+ context: AIDiagnosticContext,
+ provider: AIProviderID,
+ agentSession?: AgentSessionLink
+ ) {
await destroyAgentTransports()
await assertAgentReady('acp')
- const provider = providerID.value
// An agent's turn counts as one step of the model it names, or of the agent itself.
- const transport = await createACPTransport(provider, store, ({ model, ...tokens }) =>
- recordModelStepCompleted({ provider, model: model ?? provider, ...tokens }, context)
+ const transport = await createACPTransport(
+ provider,
+ store,
+ ({ model, ...tokens }) =>
+ recordModelStepCompleted({ provider, model: model ?? provider, ...tokens }, context),
+ agentSession
)
acpTransportInstance = transport
return transport as ChatTransport<UIMessage>
@@ -234,7 +254,8 @@ export function createChatSessionManager({
async function ensureChat(
initialMessages?: UIMessage[],
- sessionId = crypto.randomUUID()
+ sessionId = crypto.randomUUID(),
+ agentSession?: AgentSessionLink
): Promise<Chat<UIMessage> | null> {
await credentialsReady
if (!isConfigured.value) return null
@@ -254,7 +275,12 @@ export function createChatSessionManager({
let agentKind: 'acp' | 'harness' | null = null
if (isACPProvider.value) {
agentKind = 'acp'
- transport = await createActiveACPTransport(store, diagnosticContext)
+ transport = await createActiveACPTransport(
+ store,
+ diagnosticContext,
+ chatProviderID,
+ agentSession
+ )
} else if (isHarnessProvider.value) {
agentKind = 'harness'
transport = await createActiveHarnessTransport(sessionId, diagnosticContext)
diff --git a/src/app/ai/chat/use.ts b/src/app/ai/chat/use.ts
index 8f3ea5ff1..a0bb8ff5c 100644
--- a/src/app/ai/chat/use.ts
+++ b/src/app/ai/chat/use.ts
@@ -1,5 +1,6 @@
import { IS_BROWSER } from '@open-pencil/core/constants'
+import { resumingAgent } from '@/app/ai/agents/acp/session'
import { createConversationHistory } from '@/app/ai/chat/history/controller'
import { propertiesTab } from '@/app/ai/chat/panel'
import { createChatSessionManager } from '@/app/ai/chat/session'
@@ -49,7 +50,8 @@ const history = createConversationHistory({
backend: () => {
if (isACPProvider.value) return 'acp'
return isHarnessProvider.value ? 'harness' : 'direct'
- }
+ },
+ resumingAgent: () => resumingAgent(providerID.value)
})
registerAIChatEffects(chatSession.markTransportDirty)
diff --git a/src/app/ai/transports/acp.ts b/src/app/ai/transports/acp.ts
index 6076e0360..b3de255e0 100644
--- a/src/app/ai/transports/acp.ts
+++ b/src/app/ai/transports/acp.ts
@@ -3,10 +3,12 @@ import type {
Client,
Agent,
SessionNotification,
+ SessionUpdate,
RequestPermissionRequest,
RequestPermissionResponse,
Usage
} from '@agentclientprotocol/sdk'
+import { promiseTimeout } from '@vueuse/core'
import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'
import * as v from 'valibot'
@@ -16,8 +18,13 @@ import { parseAuthStatusUpdate } from '@/app/ai/agents/acp/auth/status'
import { setAgentCommands } from '@/app/ai/agents/acp/commands'
import { createUpdateMapper } from '@/app/ai/agents/acp/events'
import { requestPermissionFromUser } from '@/app/ai/agents/acp/permission'
-import { spawnACPProcess } from '@/app/ai/agents/acp/process'
-import { createOwnToolApproval, linkOwnTools } from '@/app/ai/agents/acp/tools'
+import { spawnACPProcess, type ACPProcess } from '@/app/ai/agents/acp/process'
+import {
+ AgentSessionResumeError,
+ isAuthRequiredError,
+ openAgentSession
+} from '@/app/ai/agents/acp/session'
+import { createOwnToolApproval, linkOwnTools, type OwnToolsLink } from '@/app/ai/agents/acp/tools'
import { agentAccounts } from '@/app/ai/agents/setup/accounts'
import { resolveSpawnCommand } from '@/app/ai/agents/setup/discovery'
import { AgentNotInstalledError } from '@/app/ai/agents/setup/readiness'
@@ -28,7 +35,39 @@ import { getAutomationAuthToken } from '@/app/automation/mcp/spawn'
import { describeDiagnosticError, recordACPTransportFailure } from '@/app/diagnostics'
import type { EditorStore } from '@/app/editor/active-store'
-type TauriChild = Awaited<ReturnType<typeof spawnACPProcess>>['child']
+type TauriChild = ACPProcess['child']
+
+/** What starting an agent reaches outside the transport, which tests replace. */
+export interface ACPStartup {
+ resolveCommand: typeof resolveSpawnCommand
+ spawn: typeof spawnACPProcess
+ authToken: typeof getAutomationAuthToken
+ linkTools: typeof linkOwnTools
+}
+
+const DEFAULT_STARTUP: ACPStartup = {
+ resolveCommand: resolveSpawnCommand,
+ spawn: spawnACPProcess,
+ authToken: getAutomationAuthToken,
+ linkTools: linkOwnTools
+}
+
+/**
+ * Updates that belong to a turn the agent took, after which it can continue the session even if
+ * the turn is cut off. Claude Code and Codex cannot resume a session that never took a prompt, and
+ * both send command, usage, and session info updates before they take one.
+ */
+const TURN_UPDATES: ReadonlySet<SessionUpdate['sessionUpdate']> = new Set([
+ 'user_message_chunk',
+ 'agent_message_chunk',
+ 'agent_thought_chunk',
+ 'tool_call',
+ 'tool_call_update',
+ 'plan'
+])
+
+/** How long each startup request may take; resuming starts the agent's CLI, which is slowest. */
+const AGENT_START_TIMEOUT_MS = 60_000
interface ACPSession {
connection: ClientSideConnection
@@ -40,6 +79,8 @@ interface ACPSession {
dead: boolean
/** The model the agent says it uses, once it has said; Codex names it, Claude in its usage. */
model: string | null
+ /** Whether the agent continued a saved session, which already holds the instructions. */
+ resumed: boolean
}
/** One agent turn's tokens, as an ACP agent reports them with its answer to the prompt. */
@@ -104,11 +145,6 @@ export function formatConnectionError(e: unknown, agentDef?: ACPAgentDef): strin
return msg
}
-/** ACP's `auth_required` error, which an agent returns for a new session before sign-in. */
-function isAuthRequiredError(e: unknown): boolean {
- return typeof e === 'object' && e !== null && 'code' in e && e.code === -32000
-}
-
/** The agent never opened its session with OpenPencil's MCP server, so it has no design tools. */
function toolsUnreachableError(agentDef: ACPAgentDef, reason: string | null): Error {
return new Error(
@@ -117,6 +153,11 @@ function toolsUnreachableError(agentDef: ACPAgentDef, reason: string | null): Er
)
}
+/** Closes a tools link that opens after the startup gave up, so it does not stay open. */
+function stopWhenLinked(linking: Promise<OwnToolsLink>): void {
+ linking.then((late) => late.stop()).catch(() => undefined)
+}
+
function startupError(error: unknown, agentDef: ACPAgentDef): Error {
recordACPTransportFailure({ operation: 'start', ...describeDiagnosticError(error) })
return new Error(formatConnectionError(error, agentDef))
@@ -148,6 +189,11 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
/** The chat's document, where each reply's run records the edits the agent makes in it. */
private store: EditorStore | null
private onUsage: ((usage: AgentTurnUsage) => void) | null
+ /** The agent session the next start continues: a saved chat's, then the one a turn ran in. */
+ private resume: string | null
+ private onSession: ((sessionId: string | null) => void) | null
+ private startup: ACPStartup
+ private startTimeoutMs: number
constructor(options: {
agentDef: ACPAgentDef
@@ -155,11 +201,24 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
store?: EditorStore
/** Told each turn's tokens, which the Usage settings count with the chat's other models. */
onUsage?: (usage: AgentTurnUsage) => void
+ /** A saved chat's agent session, which the agent continues when it resumes sessions. */
+ resume?: string | null
+ /**
+ * Told the agent's session once a prompt went to it, so the chat can be continued later,
+ * and null when the saved session can no longer be continued.
+ */
+ onSession?: (sessionId: string | null) => void
+ startup?: ACPStartup
+ startTimeoutMs?: number
}) {
this.agentDef = options.agentDef
this.cwd = options.cwd ?? '.'
this.store = options.store ?? null
this.onUsage = options.onUsage ?? null
+ this.resume = options.resume ?? null
+ this.onSession = options.onSession ?? null
+ this.startup = options.startup ?? DEFAULT_STARTUP
+ this.startTimeoutMs = options.startTimeoutMs ?? AGENT_START_TIMEOUT_MS
}
async sendMessages({
@@ -180,7 +239,7 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
}
if (!this.session) {
- const started = await this.spawnAgent()
+ const started = await this.spawnAgent(abortSignal)
// Destroyed between startup and here: the agent is still `starting`, so stop it.
if (this.destroying) {
await started.child.kill().catch(() => undefined)
@@ -188,7 +247,7 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
}
this.session = started
this.starting = null
- this.sentContext = false
+ this.sentContext = started.resumed
}
const carriesContext = !this.sentContext
@@ -220,6 +279,7 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
session.onUpdate = (params) => {
if (closed) return
+ if (TURN_UPDATES.has(params.update.sessionUpdate)) this.recordSession(sessionId)
for (const chunk of mapper.map(params.update)) controller.enqueue(chunk)
}
@@ -246,6 +306,7 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
})
// The prompt answers once the agent's turn is over; nothing else ends the reply.
.then((result) => {
+ this.recordSession(sessionId)
if (result.usage) this.onUsage?.(agentTurnUsage(result.usage, session.model))
finish(result.stopReason === 'end_turn' ? 'stop' : 'other')
return undefined
@@ -261,6 +322,13 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
})
}
+ /** Keeps the session that took a prompt, which the agent continues when it starts again. */
+ private recordSession(sessionId: string): void {
+ if (!this.agentDef.resumesSessions || this.resume === sessionId) return
+ this.resume = sessionId
+ this.onSession?.(sessionId)
+ }
+
async reconnectToStream(): Promise<ReadableStream<UIMessageChunk> | null> {
return null
}
@@ -277,11 +345,38 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
}
}
- private async spawnAgent(): Promise<ACPSession> {
- let process: Awaited<ReturnType<typeof spawnACPProcess>>
- try {
- process = await spawnACPProcess({
- command: await resolveSpawnCommand(this.agentDef),
+ /**
+ * Starts the agent and its session. Stop ends the startup at any step, and each step must answer
+ * within the deadline; either way the agent stops and never gets the message.
+ */
+ private async spawnAgent(abortSignal?: AbortSignal): Promise<ACPSession> {
+ const stoppedByUser = new Promise<never>((_, reject) => {
+ const stop = () => reject(new Error('The reply was stopped while the agent was starting.'))
+ if (abortSignal?.aborted) stop()
+ else abortSignal?.addEventListener('abort', stop, { once: true })
+ })
+ stoppedByUser.catch(() => undefined)
+ const startTimeoutMs = this.startTimeoutMs
+ const agentName = this.agentDef.name
+ const bounded = <T>(request: Promise<T>, ...also: Promise<never>[]): Promise<T> =>
+ Promise.race([
+ request,
+ stoppedByUser,
+ ...also,
+ promiseTimeout(startTimeoutMs).then((): never => {
+ throw new Error(`${agentName} did not answer while starting.`)
+ })
+ ])
+
+ // Aborted once the startup gave up, by Stop or the deadline, so a lookup still running launches nothing.
+ const gaveUp = new AbortController()
+ const spawning = (async () => {
+ const command = await this.startup.resolveCommand(this.agentDef)
+ if (gaveUp.signal.aborted || abortSignal?.aborted) {
+ throw new Error('The reply was stopped before the agent started.')
+ }
+ return this.startup.spawn({
+ command,
args: this.agentDef.args,
logId: this.agentDef.id,
destroying: () => this.destroying,
@@ -291,7 +386,14 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
this.session = null
}
})
+ })()
+ let process: ACPProcess
+ try {
+ process = await bounded(spawning)
} catch (e) {
+ gaveUp.abort()
+ // A process that starts after the startup gave up must not keep running.
+ void spawning.then((late) => late.child.kill()).catch(() => undefined)
recordACPTransportFailure({ operation: 'start', ...describeDiagnosticError(e) })
if (e instanceof AgentNotInstalledError) throw e
const message = e instanceof Error ? e.message : String(e)
@@ -348,80 +450,68 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {
throw new Error('The agent stopped while it was starting.')
})
stopped.catch(() => undefined)
- const untilStopped = <T>(request: Promise<T>): Promise<T> => Promise.race([request, stopped])
- let automationAuthToken: string | null
- try {
- automationAuthToken = await getAutomationAuthToken()
- } catch (e) {
+ const untilStopped = <T>(request: Promise<T>): Promise<T> => bounded(request, stopped)
+ // What startup opened so far, which a failed step closes along with the agent.
+ let release: (() => void) | null = null
+ const abandon = async (reason: Error): Promise<never> => {
+ release?.()
await child.kill().catch(() => undefined)
- throw startupError(e, this.agentDef)
+ throw reason
}
-
- try {
- await untilStopped(
- connection.initialize({
- protocolVersion: PROTOCOL_VERSION,
- clientCapabilities: {}
- })
- )
- } catch (e) {
- await child.kill().catch(() => undefined)
- throw startupError(e, this.agentDef)
+ /** One startup step: when it fails or never answers, the agent stops and never gets a prompt. */
+ const step = async <T>(request: Promise<T>, failed?: (error: unknown) => void): Promise<T> => {
+ try {
+ return await untilStopped(request)
+ } catch (e) {
+ failed?.(e)
+ return abandon(startupError(e, this.agentDef))
+ }
}
- // The agent must reach OpenPencil's tools before it gets a prompt.
- let tools: Awaited<ReturnType<typeof linkOwnTools>>
- try {
- tools = await linkOwnTools(automationAuthToken)
- } catch (e) {
- // An outside MCP connection whose credential cannot be read fails here.
- await child.kill().catch(() => undefined)
- throw startupError(e, this.agentDef)
- }
+ const automationAuthToken = await step(this.startup.authToken())
+ const initialized = await step(
+ connection.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
+ )
+
+ // The agent must reach OpenPencil's tools before it gets a prompt. An outside MCP connection
+ // whose credential cannot be read fails here.
+ const linking = this.startup.linkTools(automationAuthToken)
+ release = () => stopWhenLinked(linking)
+ const tools = await step(linking)
+ release = () => tools.stop()
onUpdate = ({ update }) => tools.noteUpdate(update)
- let sessionResult
- try {
- sessionResult = await untilStopped(
- connection.newSession({
- cwd: this.cwd,
- mcpServers: tools.mcpServers,
- _meta: tools.meta
- })
- )
- } catch (e) {
- tools.stop()
- await child.kill().catch(() => undefined)
- throw startupError(e, this.agentDef)
- }
+ const opened = await step(
+ openAgentSession(connection, this.agentDef, initialized, {
+ cwd: this.cwd,
+ mcpServers: tools.mcpServers,
+ meta: tools.meta,
+ resume: this.resume
+ }),
+ (e) => {
+ // The saved conversation goes back to read-only; this chat keeps failing, never starting anew.
+ if (e instanceof AgentSessionResumeError) this.onSession?.(null)
+ }
+ )
- let outcome: Awaited<ReturnType<typeof tools.outcome>>
- try {
- outcome = await untilStopped(tools.outcome())
- } catch (e) {
- tools.stop()
- throw startupError(e, this.agentDef)
- }
+ const outcome = await step(tools.outcome())
// Destroyed while starting, as when the chat closes: the agent must not get a prompt.
- if (this.destroying) {
- await child.kill().catch(() => undefined)
- throw new Error('The chat closed while its agent was starting.')
- }
+ if (this.destroying) await abandon(new Error('The chat closed while its agent was starting.'))
if (outcome.connected === false) {
- await child.kill().catch(() => undefined)
const error = toolsUnreachableError(this.agentDef, outcome.reason)
recordACPTransportFailure({ operation: 'start', ...describeDiagnosticError(error) })
- throw error
+ await abandon(error)
}
onUpdate = null
const session: ACPSession = {
connection,
- sessionId: sessionResult.sessionId,
+ sessionId: opened.sessionId,
chat: tools.chat,
child,
dead: false,
- model: sessionResult.models?.currentModelId ?? null,
+ model: opened.model,
+ resumed: opened.resumed,
get onUpdate() {
return onUpdate
},
diff --git a/src/components/chat/ChatPanel.vue b/src/components/chat/ChatPanel.vue
index 7ae8a6808..e998c9794 100644
--- a/src/components/chat/ChatPanel.vue
+++ b/src/components/chat/ChatPanel.vue
@@ -170,7 +170,7 @@ const historyOptions = computed(() => {
}))
})
const agentHistoryReadOnly = computed(
- () => !chat.value && messages.value.length > 0 && history.current.value?.backend !== 'direct'
+ () => history.agentReadOnly.value && (!chat.value || history.chatEnded.value)
)
/** Set while the conversation changes, so stopping its reply does not send what waits. */
let queueHeld = false
diff --git a/tests/app/ai/agents/acp/session.test.ts b/tests/app/ai/agents/acp/session.test.ts
new file mode 100644
index 000000000..1afbec5bb
--- /dev/null
+++ b/tests/app/ai/agents/acp/session.test.ts
@@ -0,0 +1,113 @@
+import { expect, test } from 'bun:test'
+
+import type {
+ InitializeResponse,
+ NewSessionRequest,
+ ResumeSessionRequest
+} from '@agentclientprotocol/sdk'
+
+import { ACP_AGENTS } from '@open-pencil/core/constants'
+
+import {
+ AgentSessionResumeError,
+ openAgentSession,
+ resumingAgent
+} from '@/app/ai/agents/acp/session'
+import { OWN_TOOLS_ALLOWED } from '@/app/ai/agents/acp/tools'
+
+import { expectDefined } from '#tests/helpers/assert'
+
+const resuming = expectDefined(
+ ACP_AGENTS.find((agent) => agent.resumesSessions),
+ 'an agent that resumes sessions'
+)
+const notResuming = expectDefined(
+ ACP_AGENTS.find((agent) => !agent.resumesSessions),
+ 'an agent that does not resume sessions'
+)
+
+const resumes: InitializeResponse = {
+ protocolVersion: 1,
+ agentCapabilities: { sessionCapabilities: { resume: {} } }
+}
+const request = { cwd: '/workspace', mcpServers: [], meta: OWN_TOOLS_ALLOWED }
+
+interface FakeConnectionOptions {
+ resumeError?: Error
+}
+
+function connection({ resumeError }: FakeConnectionOptions = {}) {
+ const created: NewSessionRequest[] = []
+ const resumed: ResumeSessionRequest[] = []
+ return {
+ created,
+ resumed,
+ async newSession(params: NewSessionRequest) {
+ created.push(params)
+ return { sessionId: 'new-session', models: { currentModelId: 'opus', availableModels: [] } }
+ },
+ async unstable_resumeSession(params: ResumeSessionRequest) {
+ resumed.push(params)
+ if (resumeError) throw resumeError
+ return { models: { currentModelId: 'sonnet', availableModels: [] } }
+ }
+ }
+}
+
+test('only agents that resume sessions continue saved chats', () => {
+ expect(resumingAgent(`acp:${resuming.id}`)).toBe(resuming.id)
+ expect(resumingAgent('acp:claude-code')).toBe('claude-code')
+ expect(resumingAgent('acp:codex')).toBe('codex')
+ expect(resumingAgent(`acp:${notResuming.id}`)).toBeNull()
+ expect(resumingAgent('anthropic')).toBeNull()
+})
+
+test('a chat without a saved session starts a new one', async () => {
+ const fake = connection()
+ const opened = await openAgentSession(fake, resuming, resumes, { ...request, resume: null })
+ expect(opened).toEqual({ sessionId: 'new-session', model: 'opus', resumed: false })
+ expect(fake.created).toEqual([{ cwd: '/workspace', mcpServers: [], _meta: OWN_TOOLS_ALLOWED }])
+ expect(fake.resumed).toEqual([])
+})
+
+test('a saved session resumes with the same folder and OpenPencil tools', async () => {
+ const fake = connection()
+ const opened = await openAgentSession(fake, resuming, resumes, { ...request, resume: 'saved' })
+ expect(opened).toEqual({ sessionId: 'saved', model: 'sonnet', resumed: true })
+ expect(fake.resumed).toEqual([
+ { sessionId: 'saved', cwd: '/workspace', mcpServers: [], _meta: OWN_TOOLS_ALLOWED }
+ ])
+ expect(fake.created).toEqual([])
+})
+
+test('a saved session never silently becomes a new one', async () => {
+ const withoutCapability = connection()
+ const noResume: InitializeResponse = { protocolVersion: 1 }
+ await expect(
+ openAgentSession(withoutCapability, resuming, noResume, { ...request, resume: 's' })
+ ).rejects.toBeInstanceOf(AgentSessionResumeError)
+ await expect(
+ openAgentSession(withoutCapability, notResuming, resumes, { ...request, resume: 's' })
+ ).rejects.toBeInstanceOf(AgentSessionResumeError)
+ expect(withoutCapability.created).toEqual([])
+ expect(withoutCapability.resumed).toEqual([])
+
+ const unknownSession = new Error('No conversation found')
+ const missing = connection({ resumeError: unknownSession })
+ const failure = await openAgentSession(missing, resuming, resumes, {
+ ...request,
+ resume: 's'
+ }).catch((error: unknown) => error)
+ expect(failure).toBeInstanceOf(AgentSessionResumeError)
+ expect(failure).not.toBe(unknownSession)
+ expect(failure instanceof Error && failure.cause).toBe(unknownSession)
+ expect(missing.created).toEqual([])
+})
+
+test('a resume that needs sign-in keeps the sign-in error', async () => {
+ const authRequired = Object.assign(new Error('Authentication required'), { code: -32000 })
+ const fake = connection({ resumeError: authRequired })
+ await expect(openAgentSession(fake, resuming, resumes, { ...request, resume: 's' })).rejects.toBe(
+ authRequired
+ )
+})
diff --git a/tests/engine/app/chat/history/continuation.test.ts b/tests/app/ai/chat/history/continuation.test.ts
similarity index 100%
rename from tests/engine/app/chat/history/continuation.test.ts
rename to tests/app/ai/chat/history/continuation.test.ts
diff --git a/tests/app/ai/chat/history/controller.test.ts b/tests/app/ai/chat/history/controller.test.ts
new file mode 100644
index 000000000..f325b4b82
--- /dev/null
+++ b/tests/app/ai/chat/history/controller.test.ts
@@ -0,0 +1,361 @@
+import 'fake-indexeddb/auto'
+import { expect, test } from 'bun:test'
+
+import type { UIMessage } from 'ai'
+import { reactive } from 'vue'
+
+import type { ACPAgentID } from '@open-pencil/core/constants'
+
+import { createConversationHistory } from '@/app/ai/chat/history/controller'
+import type { ChatDocumentEditor } from '@/app/ai/chat/history/document'
+import { createConversationStore } from '@/app/ai/chat/history/idb'
+import type { AgentSessionLink } from '@/app/ai/chat/history/types'
+
+import { expectDefined } from '#tests/helpers/assert'
+
+function editor(): ChatDocumentEditor {
+ const id = crypto.randomUUID()
+ return {
+ state: { documentName: 'Test document' },
+ getRecoveryId: () => id,
+ getSourceIdentity: () => ({ path: null, handle: null }),
+ getDocumentFilePath: () => null,
+ getStorageBinding: () => null
+ }
+}
+
+test('adopting recovery in the same editor loads its selection instead of moving old chats', async () => {
+ const store = createConversationStore()
+ const active = editor()
+ const history = createConversationHistory(
+ {
+ getEditor: () => active,
+ ensureChat: async () => null,
+ profileId: () => null,
+ resetChat: async () => undefined,
+ backend: () => 'direct',
+ resumingAgent: () => null
+ },
+ store
+ )
+ await history.initialize()
+ const original = history.current.value
+ if (!original) throw new Error('Missing draft')
+ await history.rename(original.id, 'Existing chat')
+ const recoveryId = crypto.randomUUID()
+ const restoredId = crypto.randomUUID()
+ await store.write({
+ ...original,
+ id: restoredId,
+ documentId: `recovery:${recoveryId}`,
+ title: 'Recovered chat',
+ titleSource: 'manual'
+ })
+ await store.select(`recovery:${recoveryId}`, restoredId)
+ active.getRecoveryId = () => recoveryId
+ await history.initialize()
+ expect(history.current.value?.id).toBe(restoredId)
+ expect((await store.read(original.id))?.documentId).toBe(original.documentId)
+})
+
+function fixture() {
+ let activeEditor = editor()
+ let failWrites = false
+ let resets = 0
+ const store = createConversationStore()
+ const chat = reactive({
+ messages: [] as UIMessage[],
+ status: 'ready' as const,
+ stop: async () => undefined
+ })
+ const history = createConversationHistory(
+ {
+ getEditor: () => activeEditor,
+ ensureChat: async () => chat,
+ resetChat: async () => {
+ resets++
+ },
+ profileId: () => null,
+ backend: () => 'direct',
+ resumingAgent: () => null
+ },
+ {
+ ...store,
+ write: async (row) => {
+ if (failWrites) throw new DOMException('Storage full', 'QuotaExceededError')
+ await store.write(row)
+ }
+ }
+ )
+ return {
+ history,
+ store,
+ chat,
+ setFail: (value: boolean) => {
+ failWrites = value
+ },
+ getResets: () => resets,
+ switchEditor: () => {
+ activeEditor = editor()
+ }
+ }
+}
+
+test('failed flush keeps the current conversation and blocks switching until retry succeeds', async () => {
+ const f = fixture()
+ await f.history.ensureChat()
+ const id = f.history.current.value?.id
+ f.chat.messages = [
+ { id: 'message', role: 'user', parts: [{ type: 'text', text: 'Keep this draft' }] }
+ ]
+ f.setFail(true)
+ await expect(f.history.newChat()).rejects.toThrow('Storage full')
+ expect(f.history.current.value?.id).toBe(id)
+ expect(f.history.messages.value[0]?.id).toBe('message')
+ expect(f.history.storageError.value).toBe(true)
+ f.setFail(false)
+ await f.history.newChat()
+ expect(f.history.current.value?.id).not.toBe(id)
+ expect(f.history.storageError.value).toBe(false)
+ if (!id) throw new Error('Missing conversation')
+ expect((await f.store.read(id))?.messages[0]?.message.id).toBe('message')
+})
+
+test('queued chat switches finish on the last requested conversation without losing transcripts', async () => {
+ const f = fixture()
+ await f.history.initialize()
+ const first = f.history.current.value?.id
+ if (first) await f.history.rename(first, 'First')
+ await f.history.newChat()
+ const second = f.history.current.value?.id
+ if (second) await f.history.rename(second, 'Second')
+ if (!first || !second) throw new Error('Missing conversation')
+ await Promise.all(
+ Array.from({ length: 20 }, (_, index) => f.history.open(index % 2 === 0 ? first : second))
+ )
+ const current = expectDefined(f.history.current.value, 'current conversation')
+ expect(current.id).toBe(second)
+ expect(await f.store.getSelected(current.documentId)).toBe(second)
+ expect(await f.store.read(first)).not.toBeNull()
+ expect(f.history.busy.value).toBe(false)
+})
+
+test('opening the panel and repeatedly creating drafts does not persist empty chats', async () => {
+ const f = fixture()
+ await f.history.initialize()
+ const documentId = f.history.current.value?.documentId
+ await f.history.newChat()
+ await f.history.newChat()
+ expect(await f.store.list(documentId)).toEqual([])
+ if (!documentId) throw new Error('Missing document')
+ expect(await f.store.getSelected(documentId)).toBeNull()
+})
+
+test('a pending transport is rejected when the active document changes', async () => {
+ let activeEditor = editor()
+ const pending = Promise.withResolvers<{
+ messages: UIMessage[]
+ status: 'ready'
+ stop: () => Promise<void>
+ }>()
+ const started = Promise.withResolvers<undefined>()
+ let stops = 0
+ const history = createConversationHistory(
+ {
+ getEditor: () => activeEditor,
+ ensureChat: () => {
+ started.resolve(undefined)
+ return pending.promise
+ },
+ profileId: () => null,
+ resetChat: async () => undefined,
+ backend: () => 'direct',
+ resumingAgent: () => null
+ },
+ createConversationStore()
+ )
+ const initializing = history.ensureChat()
+ await started.promise
+ activeEditor = editor()
+ pending.resolve({
+ messages: [],
+ status: 'ready',
+ stop: async () => {
+ stops++
+ }
+ })
+ expect(await initializing).toBeNull()
+ expect(stops).toBe(1)
+})
+
+/** A Claude Code chat whose history holds `saved`, with `agent` as the chat's current agent. */
+async function agentFixture(initialAgent: ACPAgentID | null, saved?: { messages: UIMessage[] }) {
+ const active = editor()
+ let agent = initialAgent
+ let starts = true
+ const store = createConversationStore()
+ const chat = reactive({
+ messages: [] as UIMessage[],
+ status: 'ready' as const,
+ stop: async () => undefined
+ })
+ const links: (AgentSessionLink | undefined)[] = []
+ const history = createConversationHistory(
+ {
+ getEditor: () => active,
+ ensureChat: async (messages, _sessionId, link) => {
+ links.push(link)
+ if (!starts) return null
+ chat.messages = messages ?? []
+ return chat
+ },
+ resetChat: async () => undefined,
+ profileId: () => null,
+ backend: () => 'acp',
+ resumingAgent: () => agent
+ },
+ store
+ )
+ await history.initialize()
+ const draft = expectDefined(history.current.value, 'draft conversation')
+ if (saved) {
+ await store.write({
+ ...draft,
+ title: 'Saved agent chat',
+ titleSource: 'manual',
+ backend: 'acp',
+ agentSession: { agent: 'claude-code', id: 'claude-session' },
+ messages: saved.messages.map((message) => ({ message, attachments: [] }))
+ })
+ // Away and back, so the saved row is what opens.
+ await history.newChat()
+ await history.open(draft.id)
+ }
+ return {
+ history,
+ store,
+ chat,
+ links,
+ id: draft.id,
+ switchAgent: (next: ACPAgentID | null) => {
+ agent = next
+ },
+ /** Whether the next chat starts, or fails as for an unconfigured provider. */
+ setStarts: (next: boolean) => {
+ starts = next
+ }
+ }
+}
+
+const savedMessage: UIMessage = {
+ id: 'saved',
+ role: 'user',
+ parts: [{ type: 'text', text: 'Make the hero bigger' }]
+}
+
+test('a saved agent conversation continues in its session with the agent that resumes it', async () => {
+ const f = await agentFixture('claude-code', { messages: [savedMessage] })
+ expect(f.history.continuesAgentSession.value).toBe(true)
+ expect(f.history.agentReadOnly.value).toBe(false)
+ expect(await f.history.ensureChat()).toBe(f.chat)
+ expect(f.links.at(-1)?.resume).toBe('claude-session')
+ expect(f.chat.messages.map((message) => message.id)).toEqual(['saved'])
+})
+
+test('a saved agent conversation stays read-only for an agent that cannot resume it', async () => {
+ const f = await agentFixture(null, { messages: [savedMessage] })
+ expect(f.history.continuesAgentSession.value).toBe(false)
+ expect(f.history.agentReadOnly.value).toBe(true)
+ expect(await f.history.ensureChat()).toBeNull()
+ expect(f.links).toEqual([])
+})
+
+test('the agent session a turn ran in is saved with its conversation', async () => {
+ const f = await agentFixture('claude-code')
+ await f.history.ensureChat()
+ const link = expectDefined(f.links.at(-1), 'agent session link')
+ expect(link.resume).toBeNull()
+ f.chat.messages = [savedMessage]
+ link.record({ agent: 'claude-code', id: 'new-session' })
+ await f.history.flush()
+ expect((await f.store.read(f.id))?.agentSession).toEqual({
+ agent: 'claude-code',
+ id: 'new-session'
+ })
+ expect(f.history.continuesAgentSession.value).toBe(true)
+})
+
+test('a session reported after switching conversations is not saved on the new one', async () => {
+ const f = await agentFixture('claude-code')
+ await f.history.ensureChat()
+ const link = expectDefined(f.links.at(-1), 'agent session link')
+ f.chat.messages = [savedMessage]
+ await f.history.newChat()
+ const other = expectDefined(f.history.current.value, 'new conversation')
+ link.record({ agent: 'claude-code', id: 'late-session' })
+ await f.history.flush()
+ expect(f.history.current.value?.agentSession).toBeUndefined()
+ expect((await f.store.read(f.id))?.agentSession).toBeUndefined()
+ expect(other.id).not.toBe(f.id)
+})
+
+test('a saved session the agent can no longer continue is forgotten', async () => {
+ const f = await agentFixture('claude-code', { messages: [savedMessage] })
+ await f.history.ensureChat()
+ expectDefined(f.links.at(-1), 'agent session link').record(null)
+ await f.history.flush()
+ expect((await f.store.read(f.id))?.agentSession).toBeUndefined()
+ expect(f.history.continuesAgentSession.value).toBe(false)
+})
+
+test('a saved session stays read-only for another agent that resumes its own sessions', async () => {
+ const f = await agentFixture('codex', { messages: [savedMessage] })
+ expect(f.history.continuesAgentSession.value).toBe(false)
+ expect(f.history.agentReadOnly.value).toBe(true)
+ expect(await f.history.ensureChat()).toBeNull()
+ expect(f.links).toEqual([])
+})
+
+test('a saved session is kept until a chat on another agent starts', async () => {
+ const f = await agentFixture('claude-code')
+ await f.history.ensureChat()
+ f.chat.messages = [savedMessage]
+ expectDefined(f.links.at(-1), 'agent session link').record({ agent: 'claude-code', id: 'kept' })
+ f.switchAgent('codex')
+ f.setStarts(false)
+ expect(await f.history.ensureChat()).toBeNull()
+ expect(f.history.current.value?.agentSession).toEqual({ agent: 'claude-code', id: 'kept' })
+ f.setStarts(true)
+ expect(await f.history.ensureChat()).toBe(f.chat)
+ expect(f.history.current.value?.agentSession).toBeUndefined()
+})
+
+test('a chat whose saved session could not be continued takes no more messages', async () => {
+ const f = await agentFixture('claude-code', { messages: [savedMessage] })
+ await f.history.ensureChat()
+ expectDefined(f.links.at(-1), 'agent session link').record(null)
+ expect(f.history.chatEnded.value).toBe(true)
+ expect(f.history.agentReadOnly.value).toBe(true)
+ expect(await f.history.ensureChat()).toBeNull()
+ expect(f.links).toHaveLength(1)
+ // A new chat starts clean.
+ await f.history.newChat()
+ expect(f.history.chatEnded.value).toBe(false)
+})
+
+test('a conversation continued on another agent no longer resumes the saved session', async () => {
+ const f = await agentFixture('claude-code', { messages: [savedMessage] })
+ await f.history.ensureChat()
+ f.switchAgent(null)
+ await f.history.ensureChat()
+ await f.history.flush()
+ expect((await f.store.read(f.id))?.agentSession).toBeUndefined()
+ // Back on Claude Code, the new session missed the turns in between, so it is not saved.
+ f.switchAgent('claude-code')
+ await f.history.ensureChat()
+ const link = expectDefined(f.links.at(-1), 'agent session link')
+ expect(link.resume).toBeNull()
+ link.record({ agent: 'claude-code', id: 'partial-session' })
+ await f.history.flush()
+ expect((await f.store.read(f.id))?.agentSession).toBeUndefined()
+})
diff --git a/tests/engine/app/chat/history/idb.test.ts b/tests/app/ai/chat/history/idb.test.ts
similarity index 100%
rename from tests/engine/app/chat/history/idb.test.ts
rename to tests/app/ai/chat/history/idb.test.ts
diff --git a/tests/app/ai/transports/acp.test.ts b/tests/app/ai/transports/acp.test.ts
new file mode 100644
index 000000000..0ba4030ea
--- /dev/null
+++ b/tests/app/ai/transports/acp.test.ts
@@ -0,0 +1,317 @@
+import { expect, test } from 'bun:test'
+
+import {
+ AgentSideConnection,
+ ndJsonStream,
+ PROTOCOL_VERSION,
+ type Agent,
+ type NewSessionRequest,
+ type ResumeSessionRequest
+} from '@agentclientprotocol/sdk'
+import type { UIMessage, UIMessageChunk } from 'ai'
+
+import { ACP_AGENTS } from '@open-pencil/core/constants'
+
+import { OWN_TOOLS_ALLOWED } from '@/app/ai/agents/acp/tools'
+import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt'
+import { ACPChatTransport, type ACPStartup } from '@/app/ai/transports/acp'
+import { createDeferred } from '@/app/runtime/deferred'
+
+import { expectDefined } from '#tests/helpers/assert'
+
+const resuming = expectDefined(
+ ACP_AGENTS.find((agent) => agent.resumesSessions),
+ 'an agent that resumes sessions'
+)
+
+interface FakeAgentOptions {
+ /** False for an agent that runs but never answers a new session. */
+ answersSessions?: boolean
+ /** Refuses every resume, as for a session the agent no longer has. */
+ resumeFails?: boolean
+ /** True for an automation token that is never read, as with a credential prompt left open. */
+ tokenHangs?: boolean
+ /**
+ * How the agent's turn ends: `refused` fails before the agent takes the prompt, `cut-off` fails
+ * after it started answering. Either way it first sends updates that are not part of a turn.
+ */
+ turn?: 'answered' | 'refused' | 'cut-off'
+ /** True for a command lookup that waits until `finishLookup`, as a slow PATH search does. */
+ lookupWaits?: boolean
+}
+
+/** In-memory ACP agents, one per start, that record what the transport asks of them. */
+function fakeAgents({
+ answersSessions = true,
+ resumeFails = false,
+ tokenHangs = false,
+ turn = 'answered',
+ lookupWaits = false
+}: FakeAgentOptions = {}) {
+ const lookup = createDeferred<undefined>()
+ const prompts: string[] = []
+ const created: NewSessionRequest[] = []
+ const resumed: ResumeSessionRequest[] = []
+ const sessionRequested = createDeferred<undefined>()
+ const killed = createDeferred<undefined>()
+ let kills = 0
+ let spawns = 0
+ let crashLatest: (() => void) | null = null
+
+ const spawn: ACPStartup['spawn'] = async (options) => {
+ spawns++
+ const toAgent = new TransformStream<Uint8Array, Uint8Array>()
+ const toClient = new TransformStream<Uint8Array, Uint8Array>()
+ const agent: Agent = {
+ async initialize() {
+ return {
+ protocolVersion: PROTOCOL_VERSION,
+ agentCapabilities: { sessionCapabilities: { resume: {} } }
+ }
+ },
+ async newSession(params) {
+ created.push(params)
+ sessionRequested.resolve(undefined)
+ if (!answersSessions) return createDeferred<never>().promise
+ return { sessionId: `session-${created.length}` }
+ },
+ async unstable_resumeSession(params) {
+ resumed.push(params)
+ if (resumeFails) throw new Error('No conversation found')
+ return {}
+ },
+ async prompt(params) {
+ const [part] = params.prompt
+ prompts.push(part?.type === 'text' ? part.text : '')
+ const { sessionId } = params
+ await connection.sessionUpdate({
+ sessionId,
+ update: { sessionUpdate: 'available_commands_update', availableCommands: [] }
+ })
+ if (turn === 'refused') throw new Error('The prompt never reached the model')
+ if (turn === 'cut-off') {
+ await connection.sessionUpdate({
+ sessionId,
+ update: {
+ sessionUpdate: 'agent_message_chunk',
+ content: { type: 'text', text: 'On it' }
+ }
+ })
+ throw new Error('The turn broke off')
+ }
+ return { stopReason: 'end_turn' }
+ },
+ async authenticate() {
+ return {}
+ },
+ cancel: async () => undefined
+ }
+ const connection = new AgentSideConnection(
+ () => agent,
+ ndJsonStream(toClient.writable, toAgent.readable)
+ )
+ // Ending the pipe ends what the client reads, as a process that exits does.
+ const output = new TransformStream<Uint8Array, Uint8Array>()
+ const stop = new AbortController()
+ toClient.readable
+ .pipeTo(output.writable, { signal: stop.signal, preventCancel: true })
+ .catch(() => undefined)
+ crashLatest = () => {
+ stop.abort()
+ options.onUnexpectedClose()
+ }
+ return {
+ child: {
+ write: async () => undefined,
+ kill: async () => {
+ kills++
+ stop.abort()
+ killed.resolve(undefined)
+ }
+ },
+ input: toAgent.writable,
+ output: output.readable
+ }
+ }
+
+ const startup: ACPStartup = {
+ resolveCommand: async (agent) => {
+ if (lookupWaits) await lookup.promise
+ return agent.command
+ },
+ spawn,
+ authToken: async () => (tokenHangs ? createDeferred<never>().promise : null),
+ linkTools: async () => ({
+ chat: 'chat',
+ mcpServers: [],
+ meta: OWN_TOOLS_ALLOWED,
+ noteUpdate: () => undefined,
+ outcome: async () => ({ connected: true }),
+ stop: () => undefined
+ })
+ }
+ return {
+ startup,
+ prompts,
+ created,
+ resumed,
+ sessionRequested: sessionRequested.promise,
+ killed: killed.promise,
+ kills: () => kills,
+ spawns: () => spawns,
+ finishLookup: () => lookup.resolve(undefined),
+ crash: () => expectDefined(crashLatest, 'a started agent')()
+ }
+}
+
+function message(role: UIMessage['role'], text: string): UIMessage {
+ return { id: crypto.randomUUID(), role, parts: [{ type: 'text', text }] }
+}
+
+/** Sends `text` after `history` and waits for the reply to end. */
+async function send(
+ transport: ACPChatTransport,
+ text: string,
+ history: UIMessage[] = [],
+ abortSignal?: AbortSignal
+): Promise<UIMessageChunk[]> {
+ const reply = await transport.sendMessages({
+ trigger: 'submit-message',
+ chatId: 'chat',
+ messageId: undefined,
+ messages: [...history, message('user', text)],
+ abortSignal
+ })
+ const chunks: UIMessageChunk[] = []
+ await reply.pipeTo(new WritableStream({ write: (chunk) => void chunks.push(chunk) }))
+ return chunks
+}
+
+function transport(
+ agents: ReturnType<typeof fakeAgents>,
+ options: { resume?: string; startTimeoutMs?: number } = {}
+) {
+ const sessions: (string | null)[] = []
+ const created = new ACPChatTransport({
+ agentDef: resuming,
+ startup: agents.startup,
+ resume: options.resume,
+ startTimeoutMs: options.startTimeoutMs ?? 1_000,
+ onSession: (id) => sessions.push(id)
+ })
+ return { transport: created, sessions }
+}
+
+test('a new session gets the instructions once and is reported once the agent answers', async () => {
+ const agents = fakeAgents()
+ const { transport: chat, sessions } = transport(agents)
+ await send(chat, 'first')
+ await send(chat, 'second', [message('user', 'first'), message('assistant', 'done')])
+ expect(agents.created).toHaveLength(1)
+ expect(agents.prompts[0]?.startsWith(SYSTEM_PROMPT)).toBe(true)
+ expect(agents.prompts[0]?.endsWith('first')).toBe(true)
+ expect(agents.prompts[1]).toBe('second')
+ expect(sessions).toEqual(['session-1'])
+ await chat.destroy()
+})
+
+test('a saved session resumes without the instructions or the transcript', async () => {
+ const agents = fakeAgents()
+ const { transport: chat, sessions } = transport(agents, { resume: 'saved' })
+ await send(chat, 'next', [message('user', 'earlier'), message('assistant', 'reply')])
+ expect(agents.resumed.map((request) => request.sessionId)).toEqual(['saved'])
+ expect(agents.created).toEqual([])
+ expect(agents.prompts).toEqual(['next'])
+ expect(sessions).toEqual([])
+ await chat.destroy()
+})
+
+test('an agent that exits continues the same session when it starts again', async () => {
+ const agents = fakeAgents()
+ const { transport: chat } = transport(agents)
+ await send(chat, 'first')
+ agents.crash()
+ await send(chat, 'second', [message('user', 'first'), message('assistant', 'done')])
+ expect(agents.created).toHaveLength(1)
+ expect(agents.resumed.map((request) => request.sessionId)).toEqual(['session-1'])
+ expect(agents.prompts[1]).toBe('second')
+ await chat.destroy()
+})
+
+test('a saved session the agent cannot continue is forgotten and no new session starts', async () => {
+ const agents = fakeAgents({ resumeFails: true })
+ const { transport: chat, sessions } = transport(agents, { resume: 'saved' })
+ await expect(send(chat, 'next')).rejects.toBeInstanceOf(Error)
+ expect(sessions).toEqual([null])
+ expect(agents.created).toEqual([])
+ expect(agents.prompts).toEqual([])
+})
+
+test('an agent that never answers while starting does not keep the message waiting', async () => {
+ const agents = fakeAgents({ answersSessions: false })
+ const { transport: chat } = transport(agents, { startTimeoutMs: 20 })
+ await expect(send(chat, 'first')).rejects.toBeInstanceOf(Error)
+ expect(agents.kills()).toBeGreaterThan(0)
+ expect(agents.prompts).toEqual([])
+})
+
+test('stopping while the agent starts stops the agent before it gets the message', async () => {
+ const agents = fakeAgents({ answersSessions: false })
+ const { transport: chat } = transport(agents)
+ const stop = new AbortController()
+ const sending = send(chat, 'first', [], stop.signal)
+ await agents.sessionRequested
+ stop.abort()
+ await expect(sending).rejects.toBeInstanceOf(Error)
+ expect(agents.kills()).toBeGreaterThan(0)
+ expect(agents.prompts).toEqual([])
+})
+
+test('a reply stopped before the agent starts launches no agent', async () => {
+ const agents = fakeAgents()
+ const { transport: chat } = transport(agents)
+ const stop = new AbortController()
+ stop.abort()
+ await expect(send(chat, 'first', [], stop.signal)).rejects.toBeInstanceOf(Error)
+ expect(agents.spawns()).toBe(0)
+ expect(agents.prompts).toEqual([])
+})
+
+test('a command lookup that finishes after the deadline launches no agent', async () => {
+ const agents = fakeAgents({ lookupWaits: true })
+ const { transport: chat } = transport(agents, { startTimeoutMs: 20 })
+ await expect(send(chat, 'first')).rejects.toBeInstanceOf(Error)
+ agents.finishLookup()
+ // A task boundary runs everything the finished lookup queued, including a spawn.
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0)
+ })
+ expect(agents.spawns()).toBe(0)
+})
+
+test('a session is not saved when its first prompt fails before the agent takes it', async () => {
+ const agents = fakeAgents({ turn: 'refused' })
+ const { transport: chat, sessions } = transport(agents)
+ const reply = await send(chat, 'first')
+ expect(agents.prompts).toHaveLength(1)
+ expect(reply).toContainEqual(expect.objectContaining({ type: 'error' }))
+ expect(reply).toContainEqual({ type: 'finish', finishReason: 'error' })
+ expect(sessions).toEqual([])
+ await chat.destroy()
+})
+
+test('a session is saved once the agent answers, even when the turn is cut off', async () => {
+ const agents = fakeAgents({ turn: 'cut-off' })
+ const { transport: chat, sessions } = transport(agents)
+ await send(chat, 'first')
+ expect(sessions).toEqual(['session-1'])
+ await chat.destroy()
+})
+
+test('a startup step outside the agent connection is bounded by the deadline too', async () => {
+ const agents = fakeAgents({ tokenHangs: true })
+ const { transport: chat } = transport(agents, { startTimeoutMs: 20 })
+ await expect(send(chat, 'first')).rejects.toBeInstanceOf(Error)
+ await agents.killed
+ expect(agents.prompts).toEqual([])
+})
diff --git a/tests/engine/app/chat/history/controller.test.ts b/tests/engine/app/chat/history/controller.test.ts
deleted file mode 100644
index 23d4b33ee..000000000
--- a/tests/engine/app/chat/history/controller.test.ts
+++ /dev/null
@@ -1,183 +0,0 @@
-import 'fake-indexeddb/auto'
-import { expect, test } from 'bun:test'
-
-import type { UIMessage } from 'ai'
-import { reactive } from 'vue'
-
-import { createConversationHistory } from '@/app/ai/chat/history/controller'
-import type { ChatDocumentEditor } from '@/app/ai/chat/history/document'
-import { createConversationStore } from '@/app/ai/chat/history/idb'
-
-import { expectDefined } from '#tests/helpers/assert'
-
-function editor(): ChatDocumentEditor {
- const id = crypto.randomUUID()
- return {
- state: { documentName: 'Test document' },
- getRecoveryId: () => id,
- getSourceIdentity: () => ({ path: null, handle: null }),
- getDocumentFilePath: () => null,
- getStorageBinding: () => null
- }
-}
-
-test('adopting recovery in the same editor loads its selection instead of moving old chats', async () => {
- const store = createConversationStore()
- const active = editor()
- const history = createConversationHistory(
- {
- getEditor: () => active,
- ensureChat: async () => null,
- profileId: () => null,
- resetChat: async () => undefined,
- backend: () => 'direct'
- },
- store
- )
- await history.initialize()
- const original = history.current.value
- if (!original) throw new Error('Missing draft')
- await history.rename(original.id, 'Existing chat')
- const recoveryId = crypto.randomUUID()
- const restoredId = crypto.randomUUID()
- await store.write({
- ...original,
- id: restoredId,
- documentId: `recovery:${recoveryId}`,
- title: 'Recovered chat',
- titleSource: 'manual'
- })
- await store.select(`recovery:${recoveryId}`, restoredId)
- active.getRecoveryId = () => recoveryId
- await history.initialize()
- expect(history.current.value?.id).toBe(restoredId)
- expect((await store.read(original.id))?.documentId).toBe(original.documentId)
-})
-
-function fixture() {
- let activeEditor = editor()
- let failWrites = false
- let resets = 0
- const store = createConversationStore()
- const chat = reactive({
- messages: [] as UIMessage[],
- status: 'ready' as const,
- stop: async () => undefined
- })
- const history = createConversationHistory(
- {
- getEditor: () => activeEditor,
- ensureChat: async () => chat,
- resetChat: async () => {
- resets++
- },
- profileId: () => null,
- backend: () => 'direct'
- },
- {
- ...store,
- write: async (row) => {
- if (failWrites) throw new DOMException('Storage full', 'QuotaExceededError')
- await store.write(row)
- }
- }
- )
- return {
- history,
- store,
- chat,
- setFail: (value: boolean) => {
- failWrites = value
- },
- getResets: () => resets,
- switchEditor: () => {
- activeEditor = editor()
- }
- }
-}
-
-test('failed flush keeps the current conversation and blocks switching until retry succeeds', async () => {
- const f = fixture()
- await f.history.ensureChat()
- const id = f.history.current.value?.id
- f.chat.messages = [
- { id: 'message', role: 'user', parts: [{ type: 'text', text: 'Keep this draft' }] }
- ]
- f.setFail(true)
- await expect(f.history.newChat()).rejects.toThrow('Storage full')
- expect(f.history.current.value?.id).toBe(id)
- expect(f.history.messages.value[0]?.id).toBe('message')
- expect(f.history.storageError.value).toBe(true)
- f.setFail(false)
- await f.history.newChat()
- expect(f.history.current.value?.id).not.toBe(id)
- expect(f.history.storageError.value).toBe(false)
- if (!id) throw new Error('Missing conversation')
- expect((await f.store.read(id))?.messages[0]?.message.id).toBe('message')
-})
-
-test('queued chat switches finish on the last requested conversation without losing transcripts', async () => {
- const f = fixture()
- await f.history.initialize()
- const first = f.history.current.value?.id
- if (first) await f.history.rename(first, 'First')
- await f.history.newChat()
- const second = f.history.current.value?.id
- if (second) await f.history.rename(second, 'Second')
- if (!first || !second) throw new Error('Missing conversation')
- await Promise.all(
- Array.from({ length: 20 }, (_, index) => f.history.open(index % 2 === 0 ? first : second))
- )
- const current = expectDefined(f.history.current.value, 'current conversation')
- expect(current.id).toBe(second)
- expect(await f.store.getSelected(current.documentId)).toBe(second)
- expect(await f.store.read(first)).not.toBeNull()
- expect(f.history.busy.value).toBe(false)
-})
-
-test('opening the panel and repeatedly creating drafts does not persist empty chats', async () => {
- const f = fixture()
- await f.history.initialize()
- const documentId = f.history.current.value?.documentId
- await f.history.newChat()
- await f.history.newChat()
- expect(await f.store.list(documentId)).toEqual([])
- if (!documentId) throw new Error('Missing document')
- expect(await f.store.getSelected(documentId)).toBeNull()
-})
-
-test('a pending transport is rejected when the active document changes', async () => {
- let activeEditor = editor()
- const pending = Promise.withResolvers<{
- messages: UIMessage[]
- status: 'ready'
- stop: () => Promise<void>
- }>()
- const started = Promise.withResolvers<undefined>()
- let stops = 0
- const history = createConversationHistory(
- {
- getEditor: () => activeEditor,
- ensureChat: () => {
- started.resolve(undefined)
- return pending.promise
- },
- profileId: () => null,
- resetChat: async () => undefined,
- backend: () => 'direct'
- },
- createConversationStore()
- )
- const initializing = history.ensureChat()
- await started.promise
- activeEditor = editor()
- pending.resolve({
- messages: [],
- status: 'ready',
- stop: async () => {
- stops++
- }
- })
- expect(await initializing).toBeNull()
- expect(stops).toBe(1)
-})
diff --git a/tools/checks/test-homes/engine-baseline.txt b/tools/checks/test-homes/engine-baseline.txt
index 042063c1d..037f3d326 100644
--- a/tools/checks/test-homes/engine-baseline.txt
+++ b/tools/checks/test-homes/engine-baseline.txt
@@ -19,9 +19,6 @@ tests/engine/app/automation/mcp-runtime.test.ts
tests/engine/app/automation/mcp-vite-plugin.test.ts
tests/engine/app/automation/portless-route.test.ts
tests/engine/app/cache.test.ts
-tests/engine/app/chat/history/continuation.test.ts
-tests/engine/app/chat/history/controller.test.ts
-tests/engine/app/chat/history/idb.test.ts
tests/engine/app/chat/step-limit.test.ts
tests/engine/app/chat/tool-access.test.ts
tests/engine/app/chat/tool-state.test.ts