AI-native design editor. Open-source Figma alternative.
feat(ai): give coding agent replies undo, change review, and usage, through shared runners (#1386)
Danila Poyarkova6ae18be6baf
diff --git a/changes/1386/added.md b/changes/1386/added.mdnew file mode 100644index 000000000..1fd85e6ad--- /dev/null+++ b/changes/1386/added.md@@ -0,0 +1,3 @@+- Claude Code and Codex replies can revert and restore the edits they made, the chat marks the calls you undid, and their tool cards show what each call changed, as for provider models.+- Settings → Usage counts the tokens of Claude Code, Codex, and Pi replies, shows cached input and cache writes, and lists each model's input and output tokens.+- Pi replies show a run of thoughts as one, start new text after a tool call, and close their text when stopped.diff --git a/packages/core/src/io/formats/pdf/plan.ts b/packages/core/src/io/formats/pdf/plan.tsindex 111e40b81..54477a5f6 100644--- a/packages/core/src/io/formats/pdf/plan.ts+++ b/packages/core/src/io/formats/pdf/plan.ts@@ -31,11 +31,7 @@ export class PDFPlanError extends Error {}function pageIdOfNode(graph: SceneGraph, nodeId: string): string | null {- let node = graph.getNode(nodeId)- while (node && node.type !== 'CANVAS') {- node = node.parentId ? graph.getNode(node.parentId) : undefined- }- return node?.id ?? null+ return graph.closest(nodeId, (node) => node.type === 'CANVAS')?.id ?? null}function visibleChildren(graph: SceneGraph, pageId: string): string[] {diff --git a/packages/docs/.vitepress/theme/landing/stage/ai/useRecordedChat.ts b/packages/docs/.vitepress/theme/landing/stage/ai/useRecordedChat.tsindex febe4fa49..375a543c6 100644--- a/packages/docs/.vitepress/theme/landing/stage/ai/useRecordedChat.ts+++ b/packages/docs/.vitepress/theme/landing/stage/ai/useRecordedChat.ts@@ -5,7 +5,7 @@ import { computed, onScopeDispose, shallowRef } from 'vue'import { CHAPTERS } from '@open-pencil/demo-tools/chapters'-import { createToolLoopTransport } from '@/app/ai/chat/transports'+import { createToolLoopTransport } from '@/app/ai/transports/tool-loop'import type { EditorStore } from '@/app/editor/active-store'import { getTabForStore, switchTab } from '@/app/tabs'diff --git a/packages/docs/development/ai-chat.md b/packages/docs/development/ai-chat.mdindex 0518b6fee..935b4c28a 100644--- a/packages/docs/development/ai-chat.md+++ b/packages/docs/development/ai-chat.md@@ -6,11 +6,11 @@ How the built-in AI chat turns a message into edits, how a reply ends, and how w`src/app/ai/chat/submission/use.ts` sends a message through the AI SDK's `Chat`. Before sending, it appends notes for the model to the text: the layers you referenced, and the edits you undid or redid since the model last heard (`context.ts`). The transcript shows only what you wrote; `stripModelNotes` removes the notes. Notes go on the newest message only. Earlier messages never change, so the provider can keep caching the conversation up to the new message.-`history/continuation.ts` (`requestMessages`) leaves tool calls without a result out of the request. They stay in the saved transcript.+`chat/history/continuation.ts` (`requestMessages`) leaves tool calls without a result out of the request. They stay in the saved transcript.## A run-`transports.ts` starts a run (`tools/run.ts`) when the message is sent, before the model is reached, so a Stop at any point ends a run that exists. A `Run` belongs to one reply and holds:+`transports/tool-loop.ts` starts a run (`reply/run.ts`) when the message is sent, before the model is reached, so a Stop at any point ends a run that exists. A `Run` belongs to one reply and holds:- the page it works on, which your navigation does not move and the agent's `switch_page` does;- the step budget captured when the message started;@@ -22,10 +22,10 @@ The chat's agent is one presence entry per document (`presence/registry.ts`). It## A tool call-`tools/index.ts` runs every call through `executeCall`:+Every call of an OpenPencil tool, from the chat, a coding agent through MCP, or WebMCP, runs through `runEditorTool` (`tools/runner.ts`); `tools/index.ts` passes the chat's calls with their reply:-- Calls that change the document take a lock in turn, since whole-page snapshots must not interleave. A call that gets the lock after the reply ended changes nothing and returns an error.-- The document change is captured, pushed as one undo step labelled `aiUndoLabel(tool)`, and recorded on the call's own run, the one it started in, even if a later reply has begun.+- Calls that change a document take its lock in turn, since whole-page snapshots must not interleave. A reply's call that gets the lock after the reply ended changes nothing and returns an error.+- The document change is captured and pushed as one undo step. A reply's call labels it `aiUndoLabel(tool)` and records it on the call's own run, the one it started in, even if a later reply has begun; another client's call is labelled by its source, such as `Agent` or `WebMCP`.- The change is recorded for the chat's change review, and the agent points at it.- A call's result reaches the model as JSON. `eval` converts what a script returns, as MCP and the CLI print it.- If you undid or redid the run's own edits since the model last heard, the result carries an `undoNote` saying so.@@ -34,7 +34,7 @@ The chat's agent is one presence entry per document (`presence/registry.ts`). ItA run ends once, in one of three ways: finished (`onFinish`), failed (`handleError`), or stopped (the request's abort signal). The agent goes idle and its cursor leaves the canvas. A tool already running keeps going: its edit lands in its run, but cannot move the agent again.-When the chat's own `onFinish` reports a reply that was stopped, failed, or cut off, `settleEndedReply` waits for the run's last edit, then settles the message (`settle.ts`):+When the chat's own `onFinish` reports a reply that was stopped, failed, or cut off, `settleEndedReply` waits for the run's last edit, then settles the message (`reply/settle.ts`):- reasoning and text are marked done;- each call that never reported back fails with whether it changed the document, which the model reads next time;@@ -42,7 +42,11 @@ When the chat's own `onFinish` reports a reply that was stopped, failed, or cutDiagnostics record `chat.completed`, `chat.stopped`, or `chat.failed`.-`submission/undone.ts` records the reply's turn (`turns.ts`) once the run settles, so an edit landing after Stop belongs to the reply.+`reply/undo.ts` records the reply's turn (`reply/turns.ts`) once the run settles, so an edit landing after Stop belongs to the reply.++## An ACP reply++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.## Undo and the modeldiff --git a/packages/harness/src/backends/pi.ts b/packages/harness/src/backends/pi.tsindex 2245792ed..61ba74e30 100644--- a/packages/harness/src/backends/pi.ts+++ b/packages/harness/src/backends/pi.ts@@ -51,7 +51,19 @@ function mapPart(part: TextStreamPart<ToolSet>): BackendEvent | undefined {output: asJSONValue(part.output)}}- if (part.type === 'finish') return { type: 'finish', finishReason: part.finishReason }+ if (part.type === 'finish') {+ const usage = part.totalUsage+ return {+ type: 'finish',+ finishReason: part.finishReason,+ usage: {+ inputTokens: usage.inputTokens ?? null,+ outputTokens: usage.outputTokens ?? null,+ cacheReadTokens: usage.inputTokenDetails.cacheReadTokens ?? null,+ cacheWriteTokens: usage.inputTokenDetails.cacheWriteTokens ?? null+ }+ }+ }if (part.type === 'error') {return {type: 'error',diff --git a/packages/harness/src/backends/types.ts b/packages/harness/src/backends/types.tsindex d6e9bdb37..269b2c0a4 100644--- a/packages/harness/src/backends/types.ts+++ b/packages/harness/src/backends/types.ts@@ -2,6 +2,7 @@ import type {HarnessAdapterID,HarnessProviderCapability,HarnessSessionConfiguration,+ HarnessTurnUsage,JSONValue} from '../protocol'@@ -26,7 +27,7 @@ export type BackendEvent =| { type: 'reasoning-delta'; text: string }| { type: 'tool-call'; toolCallId: string; toolName: string; input: JSONValue }| { type: 'tool-result'; toolCallId: string; toolName: string; output: JSONValue }- | { type: 'finish'; finishReason: string }+ | { type: 'finish'; finishReason: string; usage?: HarnessTurnUsage }| { type: 'error'; message: string }export interface HarnessBackend {diff --git a/packages/harness/src/index.ts b/packages/harness/src/index.tsindex f74a749e4..885d3fe30 100644--- a/packages/harness/src/index.ts+++ b/packages/harness/src/index.ts@@ -16,6 +16,7 @@ export {type HarnessSessionConfiguration,type HarnessSidecarMessage,type HarnessTurnEvent,+ type HarnessTurnUsage,type JSONValue} from './protocol'export { HarnessSessionService } from './service'diff --git a/packages/harness/src/protocol.ts b/packages/harness/src/protocol.tsindex ccb11c9ce..a45adde2e 100644--- a/packages/harness/src/protocol.ts+++ b/packages/harness/src/protocol.ts@@ -46,12 +46,20 @@ export type HarnessRequest =| { id: string; method: 'session.destroy'; params: { sessionId: string } }| { id: string; method: 'service.shutdown'; params?: Record<string, never> }+/** A turn's tokens; input counts cached tokens too, which the cache fields break out. */+export interface HarnessTurnUsage {+ inputTokens: number | null+ outputTokens: number | null+ cacheReadTokens: number | null+ cacheWriteTokens: number | null+}+export type HarnessTurnEvent =| { type: 'text-delta'; text: string }| { type: 'reasoning-delta'; text: string }| { type: 'tool-call'; toolCallId: string; toolName: string; input: JSONValue }| { type: 'tool-result'; toolCallId: string; toolName: string; output: JSONValue }- | { type: 'finish'; finishReason: string }+ | { type: 'finish'; finishReason: string; usage?: HarnessTurnUsage }| { type: 'error'; message: string }export type HarnessSidecarMessage =diff --git a/packages/mcp/src/tool/registration.ts b/packages/mcp/src/tool/registration.tsindex c73ed588a..77615588c 100644--- a/packages/mcp/src/tool/registration.ts+++ b/packages/mcp/src/tool/registration.ts@@ -97,17 +97,29 @@ function descriptorByName(descriptors: readonly ToolDescriptor[]): Map<string, Treturn new Map(descriptors.map((descriptor) => [descriptor.name, descriptor]))}+/**+ * The id the agent gave a call in its own conversation, which an app chat shows it under: Codex+ * sends it as `callId`, Claude Code as `claudecode/toolUseId`.+ */+function agentCallId(meta: Record<string, unknown> | undefined): string | undefined {+ const id = meta?.callId ?? meta?.['claudecode/toolUseId']+ return typeof id === 'string' && id.length > 0 && id.length <= 128 ? id : undefined+}+export function registerTools(mcpServer: McpServer, options: RegisterToolsOptions): void {const { policy, sendRPC, agentSession } = options- // Sent with each tool call: the session, and the client's name once it has introduced itself.- const agent = () =>- agentSession- ? {- session: agentSession.id,- kind: agentSession.kind,- client: mcpServer.server.getClientVersion()?.name- }- : undefined+ // Sent with each tool call: the session, the client's name once it has introduced itself,+ // and for an app chat's agent, the chat and the call's id in it.+ const agent = (meta: Record<string, unknown> | undefined) => {+ if (!agentSession) return undefined+ const session = {+ session: agentSession.id,+ kind: agentSession.kind,+ client: mcpServer.server.getClientVersion()?.name+ }+ if (!agentSession.chat) return session+ return { ...session, chat: agentSession.chat, call: agentCallId(meta) }+ }const resolvedRoot = options.mcpRoot ? resolve(options.mcpRoot) : nullconst descriptors = descriptorByName(createToolDescriptors(resolvedRoot !== null))const register = <InputArgs extends v.GenericSchema>(@@ -143,7 +155,7 @@ export function registerTools(mcpServer: McpServer, options: RegisterToolsOptiondescription: def.description,inputSchema: v.strictObject({ ...def.input.entries, ...automationTargetSchema })},- async (args: Record<string, unknown>) => {+ async (args: Record<string, unknown>, context) => {try {const { target, args: toolArgs } = splitAutomationTarget(args)const filePath =@@ -157,7 +169,7 @@ export function registerTools(mcpServer: McpServer, options: RegisterToolsOption...target,name: def.name,args: toolArgs,- agent: agent(),+ agent: agent(context.mcpReq._meta),// A client limited to the selection says so, whatever the server's own scope....(policy.scope === 'selection' ? { scope: policy.scope } : {})}diff --git a/packages/vue/src/i18n/locales/de/diagnostics.json b/packages/vue/src/i18n/locales/de/diagnostics.jsonindex 38e81b539..b1949f225 100644--- a/packages/vue/src/i18n/locales/de/diagnostics.json+++ b/packages/vue/src/i18n/locales/de/diagnostics.json@@ -4,6 +4,8 @@"usageCompleted": "Abgeschlossen","usageInputTokens": "Eingabe-Tokens","usageOutputTokens": "Ausgabe-Tokens",+ "usageCachedInputTokens": "Zwischengespeicherte Eingabe-Tokens",+ "usageCacheWriteTokens": "In den Cache geschriebene Tokens","usageByModel": "Nach Modell","usageNoData": "Keine Nutzungsdaten aufgezeichnet.","usageNotReported": "Nicht gemeldet",diff --git a/packages/vue/src/i18n/locales/es/diagnostics.json b/packages/vue/src/i18n/locales/es/diagnostics.jsonindex c02fa9909..3332b9711 100644--- a/packages/vue/src/i18n/locales/es/diagnostics.json+++ b/packages/vue/src/i18n/locales/es/diagnostics.json@@ -4,6 +4,8 @@"usageCompleted": "Completadas","usageInputTokens": "Tokens de entrada","usageOutputTokens": "Tokens de salida",+ "usageCachedInputTokens": "Tokens de entrada en caché",+ "usageCacheWriteTokens": "Tokens escritos en caché","usageByModel": "Por modelo","usageNoData": "No hay datos de uso registrados.","usageNotReported": "No informado",diff --git a/packages/vue/src/i18n/locales/fr/diagnostics.json b/packages/vue/src/i18n/locales/fr/diagnostics.jsonindex 1373e1d97..9f204a2f7 100644--- a/packages/vue/src/i18n/locales/fr/diagnostics.json+++ b/packages/vue/src/i18n/locales/fr/diagnostics.json@@ -4,6 +4,8 @@"usageCompleted": "Terminées","usageInputTokens": "Tokens d’entrée","usageOutputTokens": "Tokens de sortie",+ "usageCachedInputTokens": "Tokens d’entrée en cache",+ "usageCacheWriteTokens": "Tokens écrits en cache","usageByModel": "Par modèle","usageNoData": "Aucune donnée d’utilisation enregistrée.","usageNotReported": "Non communiqué",diff --git a/packages/vue/src/i18n/locales/it/diagnostics.json b/packages/vue/src/i18n/locales/it/diagnostics.jsonindex a7bc40a2e..fe10af687 100644--- a/packages/vue/src/i18n/locales/it/diagnostics.json+++ b/packages/vue/src/i18n/locales/it/diagnostics.json@@ -4,6 +4,8 @@"usageCompleted": "Completate","usageInputTokens": "Token di input","usageOutputTokens": "Token di output",+ "usageCachedInputTokens": "Token di input in cache",+ "usageCacheWriteTokens": "Token scritti in cache","usageByModel": "Per modello","usageNoData": "Nessun dato di utilizzo registrato.","usageNotReported": "Non segnalato",diff --git a/packages/vue/src/i18n/locales/ja/diagnostics.json b/packages/vue/src/i18n/locales/ja/diagnostics.jsonindex ad0342a99..ac3182a72 100644--- a/packages/vue/src/i18n/locales/ja/diagnostics.json+++ b/packages/vue/src/i18n/locales/ja/diagnostics.json@@ -4,6 +4,8 @@"usageCompleted": "完了","usageInputTokens": "入力トークン","usageOutputTokens": "出力トークン",+ "usageCachedInputTokens": "キャッシュ済み入力トークン",+ "usageCacheWriteTokens": "キャッシュ書き込みトークン","usageByModel": "モデル別","usageNoData": "使用状況データはありません。","usageNotReported": "未報告",diff --git a/packages/vue/src/i18n/locales/pl/diagnostics.json b/packages/vue/src/i18n/locales/pl/diagnostics.jsonindex bd20c6422..e9ee9b366 100644--- a/packages/vue/src/i18n/locales/pl/diagnostics.json+++ b/packages/vue/src/i18n/locales/pl/diagnostics.json@@ -4,6 +4,8 @@"usageCompleted": "Ukończone","usageInputTokens": "Tokeny wejściowe","usageOutputTokens": "Tokeny wyjściowe",+ "usageCachedInputTokens": "Tokeny wejściowe z pamięci podręcznej",+ "usageCacheWriteTokens": "Tokeny zapisane w pamięci podręcznej","usageByModel": "Według modelu","usageNoData": "Brak zarejestrowanych danych użycia.","usageNotReported": "Nie zgłoszono",diff --git a/packages/vue/src/i18n/locales/ru/diagnostics.json b/packages/vue/src/i18n/locales/ru/diagnostics.jsonindex b4c7894e2..c01f3e705 100644--- a/packages/vue/src/i18n/locales/ru/diagnostics.json+++ b/packages/vue/src/i18n/locales/ru/diagnostics.json@@ -4,6 +4,8 @@"usageCompleted": "Завершённые","usageInputTokens": "Входные токены","usageOutputTokens": "Выходные токены",+ "usageCachedInputTokens": "Входные токены из кэша",+ "usageCacheWriteTokens": "Токены, записанные в кэш","usageByModel": "По модели","usageNoData": "Данных об использовании нет.","usageNotReported": "Не сообщается",diff --git a/packages/vue/src/i18n/locales/zh-cn/diagnostics.json b/packages/vue/src/i18n/locales/zh-cn/diagnostics.jsonindex 2b7d5ba7b..e999fc156 100644--- a/packages/vue/src/i18n/locales/zh-cn/diagnostics.json+++ b/packages/vue/src/i18n/locales/zh-cn/diagnostics.json@@ -4,6 +4,8 @@"usageCompleted": "已完成","usageInputTokens": "输入令牌","usageOutputTokens": "输出令牌",+ "usageCachedInputTokens": "缓存输入令牌",+ "usageCacheWriteTokens": "缓存写入令牌","usageByModel": "按模型","usageNoData": "暂无使用数据。","usageNotReported": "未报告",diff --git a/packages/vue/src/i18n/messages/diagnostics.ts b/packages/vue/src/i18n/messages/diagnostics.tsindex bbc86e7f5..17c113a01 100644--- a/packages/vue/src/i18n/messages/diagnostics.ts+++ b/packages/vue/src/i18n/messages/diagnostics.ts@@ -8,6 +8,8 @@ export const diagnosticsMessageDefaults = {usageCompleted: 'Completed',usageInputTokens: 'Input tokens',usageOutputTokens: 'Output tokens',+ usageCachedInputTokens: 'Cached input tokens',+ usageCacheWriteTokens: 'Cache write tokens',usageByModel: 'By model',usageNoData: 'No usage data recorded.',usageNotReported: 'Not reported',diff --git a/src/AGENTS.md b/src/AGENTS.mdindex 21c43b1dd..e726b17ef 100644--- a/src/AGENTS.md+++ b/src/AGENTS.md@@ -23,7 +23,9 @@ Root Tauri/Vite app. Services and state live under `src/app/**`, views under `sr- How a chat reply runs, ends, and reports undone edits to the model, and which file owns each step, is in `packages/docs/development/ai-chat.md`; keep it current when that flow changes.- `src/app/ai/tools/index.ts` binds Core ToolDefs to the active editor's `FigmaAPI`. The chat and ACP prompt compose the Core authoring reference rather than copying it (`packages/core/AGENTS.md`, Tools).-- ACP transport lives under `src/app/ai/acp/**`; provider definitions in `packages/core/src/ai/providers.ts`, exported from `@open-pencil/core/constants`; profiles in `src/app/ai/models/**`. Keep provider connections, reusable profiles, and role assignments separate, and resolve credentials lazily. ACP process changes require checking `desktop/capabilities/**`.+- A chat's backends are in `src/app/ai/transports/` (the tool loop, ACP, Pi), built on one reply's lifecycle in `src/app/ai/reply/` (run, turns, undo, settle, and `stream.ts` for an agent's chat parts); every OpenPencil tool call, from the chat, MCP, or WebMCP, runs through `runEditorTool` in `src/app/ai/tools/runner.ts` (`tests/app/automation/bridge/agent-replies.test.ts`).+- Coding agents live in `src/app/ai/agents/`: `setup/` finds and signs them in, `acp/` and `pi/` hold each protocol; a chat's agent reaches OpenPencil's MCP server through `linkChatAgent` in `src/app/integrations/mcp/link.ts`. ACP process changes require checking `desktop/capabilities/**`.+- Provider definitions are in `packages/core/src/ai/providers.ts`, exported from `@open-pencil/core/constants`; profiles and how a model is called in `src/app/ai/models/**`. Keep provider connections, reusable profiles, and role assignments separate, and resolve credentials lazily.- Browser-native WebMCP registration lives under `src/app/automation/webmcp/`, consumes per-tool exposure metadata, and is feature-detected through `document.modelContext`. App completion under `src/app/automation/execution/` loads fonts after commit.- Collaboration lives under `src/app/collab/**` on Yjs and awareness over a `CollabRoomTransport`: Trystero for peer-to-peer rooms, the Cloud relay (`transport/cloud.ts`) for Cloud documents. Preserve crypto-safe room IDs and peer cleanup. Room channels are named in `COLLAB_ACTIONS` from `@open-pencil/cloud/contract`, because the relay reads the document ones to persist rooms and drop viewer writes (`tests/integration/collab/cloud-relay.test.ts`).- Outside Cloud's own folders, app code reaches Cloud only through `@/app/cloud/integration` (and its `/storage` provider list) and components through `@/components/cloud/integration`; a `VITE_OPENPENCIL_CLOUD=off` build swaps both for their `off` stand-ins, which must keep the same names (`tests/app/cloud/integration/off.test.ts`), and must bundle no other Cloud module (`bun run check:cloud-off`).diff --git a/src/app/ai/acp/own-tools.ts b/src/app/ai/acp/own-tools.tsdeleted file mode 100644index d5b829748..000000000--- a/src/app/ai/acp/own-tools.ts+++ /dev/null@@ -1,80 +0,0 @@-import type { McpServer, SessionUpdate } from '@agentclientprotocol/sdk'-import { promiseTimeout } from '@vueuse/core'--import { OPEN_PENCIL_MCP_SERVER } from '@open-pencil/core/constants'-import { randomHex } from '@open-pencil/scene-graph/random'--import { textFromContent } from './map-update'--/**- * Lets the agent use OpenPencil's own tools without asking each time: their edits are undoable- * and stay in the document the chat works on. Claude's adapter passes these options to the- * Claude Agent SDK, where a bare server name allows every tool on it; other agents ignore it.- */-export const OWN_TOOLS_ALLOWED = {- claudeCode: { options: { allowedTools: [`mcp__${OPEN_PENCIL_MCP_SERVER}`] } }-}--/** How long an agent may take to reach OpenPencil's tools once its session starts. */-export const TOOLS_CONNECT_TIMEOUT_MS = 20_000--/** Whether an agent's session reached OpenPencil's tools; null when the server cannot tell. */-export type OwnToolsOutcome =- | { connected: true }- | { connected: false; reason: string | null }- | { connected: null }--/** What an agent's new session needs to reach OpenPencil's tools, and how to tell it did. */-export interface OwnToolsLink {- mcpServers: McpServer[]- meta: typeof OWN_TOOLS_ALLOWED- /** Reads an update sent before any prompt, where a failed tool call is a server that failed. */- noteUpdate(update: SessionUpdate): void- /** Waits, once the session exists, for the server to say the agent opened its MCP session. */- outcome(timeoutMs?: number): Promise<OwnToolsOutcome>- stop(): void-}--/**- * Names a new agent session to OpenPencil's MCP server by a chat id, so the server can report- * when this agent connects. Watch before creating the session: the agent connects during it.- */-export async function linkOwnTools(authorizationToken: string | null): Promise<OwnToolsLink> {- const [{ buildACPMCPServers }, { mcpRuntime }, { watchChatAgent }] = await Promise.all([- import('@/app/integrations/mcp'),- import('@/app/automation/mcp/runtime'),- import('@/app/automation/agents')- ])- const chat = randomHex(16)- // Built before watching, so a server list that fails to build leaves no chat waiting.- const mcpServers = await buildACPMCPServers({ authorizationToken, chat })- // An older MCP server reports no sessions, so only a current one can confirm the agent.- const watch = mcpRuntime.agentSessionEvents ? watchChatAgent(chat) : null- const failures: string[] = []- return {- mcpServers,- meta: OWN_TOOLS_ALLOWED,- noteUpdate(update) {- if (update.sessionUpdate !== 'tool_call' || update.status !== 'failed') return- const text = textFromContent(update.content ?? undefined)- if (text?.includes(OPEN_PENCIL_MCP_SERVER)) failures.push(text)- },- async outcome(timeoutMs = TOOLS_CONNECT_TIMEOUT_MS) {- if (!watch) return { connected: null }- try {- const connected = await Promise.race([- watch.connected.then(() => true),- promiseTimeout(timeoutMs).then(() => false)- ])- return connected- ? { connected: true }- : { connected: false, reason: failures.at(-1) ?? null }- } finally {- watch.stop()- }- },- stop() {- watch?.stop()- }- }-}diff --git a/src/app/ai/acp/auth/session.ts b/src/app/ai/agents/acp/auth/session.tssimilarity index 98%rename from src/app/ai/acp/auth/session.tsrename to src/app/ai/agents/acp/auth/session.tsindex 7b86263b2..b670f573d 100644--- a/src/app/ai/acp/auth/session.ts+++ b/src/app/ai/agents/acp/auth/session.ts@@ -4,10 +4,10 @@ import { promiseTimeout } from '@vueuse/core'import type { ACPAgentDef } from '@open-pencil/core/constants'-import { spawnACPProcess } from '@/app/ai/acp/process'+import { spawnACPProcess } from '@/app/ai/agents/acp/process'+import type { OwnToolsLink, OwnToolsOutcome } from '@/app/ai/agents/acp/tools'import { createDeferred, type Deferred } from '@/app/runtime/deferred'-import type { OwnToolsLink, OwnToolsOutcome } from '../own-tools'import {isSignedIn,parseAuthMethods,diff --git a/src/app/ai/acp/auth/status.ts b/src/app/ai/agents/acp/auth/status.tssimilarity index 100%rename from src/app/ai/acp/auth/status.tsrename to src/app/ai/agents/acp/auth/status.tsdiff --git a/src/app/ai/acp/auth/terminal.ts b/src/app/ai/agents/acp/auth/terminal.tssimilarity index 100%rename from src/app/ai/acp/auth/terminal.tsrename to src/app/ai/agents/acp/auth/terminal.tsdiff --git a/src/app/ai/acp/map-update.ts b/src/app/ai/agents/acp/events.tssimilarity index 71%rename from src/app/ai/acp/map-update.tsrename to src/app/ai/agents/acp/events.tsindex 572c7f1e8..8023a7da1 100644--- a/src/app/ai/acp/map-update.ts+++ b/src/app/ai/agents/acp/events.ts@@ -5,6 +5,8 @@ import * as v from 'valibot'import { OPEN_PENCIL_MCP_SERVER } from '@open-pencil/core/constants'import type { JSONObject } from '@open-pencil/scene-graph/primitives'+import { createReplyStream, type ReplyToolCall } from '@/app/ai/reply/stream'+type ToolCallReport = Extract<SessionUpdate, { sessionUpdate: 'tool_call' | 'tool_call_update' }>/**@@ -179,135 +181,61 @@ function toolResult(update: ToolCallReport, identity: ToolIdentity): ToolResult* call starts a new part and a run of thoughts shows as one.*/export function createUpdateMapper(idPrefix: string) {- let parts = 0- let text: string | null = null- let reasoning: string | null = null+ const stream = createReplyStream(idPrefix)const tools = new Map<string, ToolIdentity>()- function nextId(kind: string): string {- parts += 1- return `${idPrefix}-${kind}-${parts}`- }-- function closeText(chunks: UIMessageChunk[]): void {- if (text) chunks.push({ type: 'text-end', id: text })- text = null- }-- function closeReasoning(chunks: UIMessageChunk[]): void {- if (reasoning) chunks.push({ type: 'reasoning-end', id: reasoning })- reasoning = null- }-- function toolInput(update: ToolCallReport, identity: ToolIdentity): unknown {- return identity.input ?? update.rawInput+ function callOf(id: string, identity: ToolIdentity, title: string | undefined): ReplyToolCall {+ // The agent's own tools keep its title; OpenPencil's are named by the tool.+ return { id, name: identity.name, title: identity.kind === 'agent' ? title : undefined }}- function toolResultChunks(update: ToolCallReport, identity: ToolIdentity): UIMessageChunk[] {+ function resultChunks(update: ToolCallReport, identity: ToolIdentity): UIMessageChunk[] {if (update.status !== 'completed' && update.status !== 'failed') return []const result = toolResult(update, identity)- return [- result.ok- ? {- type: 'tool-output-available',- toolCallId: update.toolCallId,- output: result.output,- providerExecuted: true- }- : {- type: 'tool-output-error',- toolCallId: update.toolCallId,- errorText: result.errorText,- providerExecuted: true- }- ]+ return result.ok+ ? stream.toolResult(update.toolCallId, result.output)+ : stream.toolError(update.toolCallId, result.errorText)}function map(update: SessionUpdate): UIMessageChunk[] {- const chunks: UIMessageChunk[] = []switch (update.sessionUpdate) {- case 'agent_message_chunk': {- if (update.content.type !== 'text') {- console.warn('[ACP] Unhandled content type:', update.content.type)- break- }- if (!update.content.text) break- closeReasoning(chunks)- if (!text) {- text = nextId('text')- chunks.push({ type: 'text-start', id: text })- }- chunks.push({ type: 'text-delta', id: text, delta: update.content.text })- break- }- case 'agent_thought_chunk': {- if (update.content.type !== 'text' || !update.content.text) break- closeText(chunks)- if (!reasoning) {- reasoning = nextId('reasoning')- chunks.push({ type: 'reasoning-start', id: reasoning })- }- chunks.push({ type: 'reasoning-delta', id: reasoning, delta: update.content.text })- break- }+ case 'agent_message_chunk':+ if (update.content.type === 'text') return stream.text(update.content.text)+ console.warn('[ACP] Unhandled content type:', update.content.type)+ return []+ case 'agent_thought_chunk':+ return update.content.type === 'text' ? stream.thought(update.content.text) : []case 'tool_call': {- closeText(chunks)- closeReasoning(chunks)if (!update.title) console.warn('[ACP] Tool call without title:', update.toolCallId)const identity = identify(update)tools.set(update.toolCallId, identity)- const title = identity.kind === 'agent' ? update.title : undefined- chunks.push({- type: 'tool-input-start',- toolCallId: update.toolCallId,- toolName: identity.name,- providerExecuted: true,- title- })- const input = toolInput(update, identity)+ const call = callOf(update.toolCallId, identity, update.title)+ const chunks = stream.toolStart(call)+ const input = identity.input ?? update.rawInput// A call can arrive already finished, as Codex reports an MCP server that failed to start.const finished = update.status === 'completed' || update.status === 'failed'- if (input || finished) {- chunks.push({- type: 'tool-input-available',- toolCallId: update.toolCallId,- toolName: identity.name,- input: input ?? {},- providerExecuted: true,- title- })- }- chunks.push(...toolResultChunks(update, identity))- break+ if (input || finished) chunks.push(...stream.toolInput(call, input ?? {}))+ chunks.push(...resultChunks(update, identity))+ return chunks}case 'tool_call_update': {const identity = tools.get(update.toolCallId) ?? identify(update)+ const chunks: UIMessageChunk[] = []// Claude's adapter sends a call's complete input once it has streamed in.if (update.rawInput && identity.input === undefined) {- chunks.push({- type: 'tool-input-available',- toolCallId: update.toolCallId,- toolName: identity.name,- input: update.rawInput,- providerExecuted: true- })+ chunks.push(+ ...stream.toolInput(callOf(update.toolCallId, identity, undefined), update.rawInput)+ )}- chunks.push(...toolResultChunks(update, identity))- break+ chunks.push(...resultChunks(update, identity))+ return chunks}+ default:+ return []}- return chunks- }-- /** Closes the text or thought still open when the turn ends. */- function end(): UIMessageChunk[] {- const chunks: UIMessageChunk[] = []- closeText(chunks)- closeReasoning(chunks)- return chunks}- return { map, end }+ return { map, end: () => stream.end() }}export function textFromContent(content: JSONObject[] | undefined): string | undefined {diff --git a/src/app/ai/acp/permission.ts b/src/app/ai/agents/acp/permission.tssimilarity index 100%rename from src/app/ai/acp/permission.tsrename to src/app/ai/agents/acp/permission.tsdiff --git a/src/app/ai/acp/process.ts b/src/app/ai/agents/acp/process.tssimilarity index 100%rename from src/app/ai/acp/process.tsrename to src/app/ai/agents/acp/process.tsdiff --git a/src/app/ai/agents/acp/tools.ts b/src/app/ai/agents/acp/tools.tsnew file mode 100644index 000000000..ba84eaab9--- /dev/null+++ b/src/app/ai/agents/acp/tools.ts@@ -0,0 +1,61 @@+import type { McpServer, SessionUpdate } from '@agentclientprotocol/sdk'++import { OPEN_PENCIL_MCP_SERVER } from '@open-pencil/core/constants'++import { buildACPMCPServers } from '@/app/integrations/mcp'+import { linkChatAgent } from '@/app/integrations/mcp/link'++import { textFromContent } from './events'++/**+ * Lets the agent use OpenPencil's own tools without asking each time: their edits are undoable+ * and stay in the document the chat works on. Claude's adapter passes these options to the+ * Claude Agent SDK, where a bare server name allows every tool on it; other agents ignore it.+ */+export const OWN_TOOLS_ALLOWED = {+ claudeCode: { options: { allowedTools: [`mcp__${OPEN_PENCIL_MCP_SERVER}`] } }+}++/** Whether an agent's session reached OpenPencil's tools; null when the server cannot tell. */+export type OwnToolsOutcome =+ | { connected: true }+ | { connected: false; reason: string | null }+ | { connected: null }++/** What an ACP agent's new session needs to reach OpenPencil's tools, and how to tell it did. */+export interface OwnToolsLink {+ /** The id the agent's MCP session and tool calls carry, which ties them to this chat. */+ chat: string+ mcpServers: McpServer[]+ meta: typeof OWN_TOOLS_ALLOWED+ /** Reads an update sent before any prompt, where a failed tool call is a server that failed. */+ noteUpdate(update: SessionUpdate): void+ /** Waits, once the session exists, for the agent to open its MCP session. */+ outcome(): Promise<OwnToolsOutcome>+ stop(): void+}++/**+ * Links a new ACP session to OpenPencil's MCP server. Codex reports a server it could not start+ * as a failed tool call before any prompt, which gives the reason when the agent never connects.+ */+export async function linkOwnTools(authorizationToken: string | null): Promise<OwnToolsLink> {+ const link = await linkChatAgent((chat) => buildACPMCPServers({ authorizationToken, chat }))+ const failures: string[] = []+ return {+ chat: link.chat,+ mcpServers: link.servers,+ meta: OWN_TOOLS_ALLOWED,+ noteUpdate(update) {+ if (update.sessionUpdate !== 'tool_call' || update.status !== 'failed') return+ const text = textFromContent(update.content ?? undefined)+ if (text?.includes(OPEN_PENCIL_MCP_SERVER)) failures.push(text)+ },+ async outcome() {+ const connected = await link.connected()+ if (connected === null) return { connected: null }+ return connected ? { connected: true } : { connected: false, reason: failures.at(-1) ?? null }+ },+ stop: () => link.stop()+ }+}diff --git a/src/app/ai/harness/companion.ts b/src/app/ai/agents/pi/companion.tssimilarity index 100%rename from src/app/ai/harness/companion.tsrename to src/app/ai/agents/pi/companion.tsdiff --git a/src/app/ai/harness/process.ts b/src/app/ai/agents/pi/process.tssimilarity index 93%rename from src/app/ai/harness/process.tsrename to src/app/ai/agents/pi/process.tsindex b569811e1..ba9469ba9 100644--- a/src/app/ai/harness/process.ts+++ b/src/app/ai/agents/pi/process.ts@@ -2,6 +2,7 @@ import * as v from 'valibot'import type { HarnessSidecarMessage, JSONValue } from '@open-pencil/harness'+import { tokenUsageSchema } from '@/app/diagnostics/events/ai'import { resolvePlatformCommand } from '@/app/tauri/command'/** Any value `JSON.parse` produced is a JSONValue; only presence needs checking. */@@ -22,7 +23,12 @@ const HarnessTurnEventSchema = v.variant('type', [toolName: v.string(),output: jsonValue}),- v.object({ type: v.literal('finish'), finishReason: v.string() }),+ v.object({+ type: v.literal('finish'),+ finishReason: v.string(),+ // Companions before usage reporting send none.+ usage: v.optional(tokenUsageSchema)+ }),v.object({ type: v.literal('error'), message: v.string() })])diff --git a/src/app/ai/harness/pi-settings.ts b/src/app/ai/agents/pi/settings.tssimilarity index 100%rename from src/app/ai/harness/pi-settings.tsrename to src/app/ai/agents/pi/settings.tsdiff --git a/src/app/ai/agents/accounts.ts b/src/app/ai/agents/setup/accounts.tssimilarity index 96%rename from src/app/ai/agents/accounts.tsrename to src/app/ai/agents/setup/accounts.tsindex 3d2e4307b..d3bfc4633 100644--- a/src/app/ai/agents/accounts.ts+++ b/src/app/ai/agents/setup/accounts.ts@@ -7,9 +7,9 @@ import {signInWithAgent,type AgentAuthCheck,type ToolsProbe-} from '@/app/ai/acp/auth/session'-import type { AgentAuthMethod, AgentAuthStatus } from '@/app/ai/acp/auth/status'-import { startTerminalSignIn, type TerminalSignIn } from '@/app/ai/acp/auth/terminal'+} from '@/app/ai/agents/acp/auth/session'+import type { AgentAuthMethod, AgentAuthStatus } from '@/app/ai/agents/acp/auth/status'+import { startTerminalSignIn, type TerminalSignIn } from '@/app/ai/agents/acp/auth/terminal'/** What setup knows about the account a coding agent uses. */export interface AgentAccount {@@ -175,11 +175,11 @@ export function createAgentAccounts(options: {/** Starts a session as a chat does: in the agent workspace, linked to OpenPencil's tools. */const chatTools: ToolsProbe = {- cwd: async () => (await import('@/app/ai/agents/native')).agentWorkspace(),+ cwd: async () => (await import('@/app/ai/agents/setup/native')).agentWorkspace(),link: async () => {const [{ getAutomationAuthToken }, { linkOwnTools }] = await Promise.all([import('@/app/automation/mcp/spawn'),- import('@/app/ai/acp/own-tools')+ import('@/app/ai/agents/acp/tools')])return linkOwnTools(await getAutomationAuthToken())}diff --git a/src/app/ai/agents/companions.ts b/src/app/ai/agents/setup/companions.tssimilarity index 100%rename from src/app/ai/agents/companions.tsrename to src/app/ai/agents/setup/companions.tsdiff --git a/src/app/ai/agents/detection.ts b/src/app/ai/agents/setup/detection.tssimilarity index 98%rename from src/app/ai/agents/detection.tsrename to src/app/ai/agents/setup/detection.tsindex 1459ee14d..2fdf9d669 100644--- a/src/app/ai/agents/detection.ts+++ b/src/app/ai/agents/setup/detection.ts@@ -1,6 +1,6 @@import type { ACPAgentDef } from '@open-pencil/core/constants'-import { agentSetupView, type AgentSetupState, type PiSetupState } from './setup'+import { agentSetupView, type AgentSetupState, type PiSetupState } from './view'/** What setup found of an agent on this computer, shown before the person picks it. */export type AgentDetection =diff --git a/src/app/ai/agents/discovery.ts b/src/app/ai/agents/setup/discovery.tssimilarity index 99%rename from src/app/ai/agents/discovery.tsrename to src/app/ai/agents/setup/discovery.tsindex 7b39f2385..3d52adc93 100644--- a/src/app/ai/agents/discovery.ts+++ b/src/app/ai/agents/setup/discovery.ts@@ -11,7 +11,7 @@ import {HARNESS_EXECUTABLE,HARNESS_INSTALL_TARGET,HARNESS_PACKAGE-} from '@/app/ai/harness/companion'+} from '@/app/ai/agents/pi/companion'import { MCP_EXECUTABLE, MCP_INSTALL_TARGET, MCP_PACKAGE_NAME } from '@/app/automation/mcp/failure'import { detectUserAgent } from '@/app/tauri/command'diff --git a/src/app/ai/agents/native.ts b/src/app/ai/agents/setup/native.tssimilarity index 98%rename from src/app/ai/agents/native.tsrename to src/app/ai/agents/setup/native.tsindex 8a7d7c702..cd1f075c5 100644--- a/src/app/ai/agents/native.ts+++ b/src/app/ai/agents/setup/native.ts@@ -2,7 +2,7 @@ import * as v from 'valibot'import type { ACPAgentDef } from '@open-pencil/core/constants'-import { HARNESS_INSTALL_TARGET } from '@/app/ai/harness/companion'+import { HARNESS_INSTALL_TARGET } from '@/app/ai/agents/pi/companion'import { MCP_INSTALL_TARGET } from '@/app/automation/mcp/failure'import { resolvePlatformCommand } from '@/app/tauri/command'diff --git a/src/app/ai/acp/setup-prompt.ts b/src/app/ai/agents/setup/prompt.tssimilarity index 100%rename from src/app/ai/acp/setup-prompt.tsrename to src/app/ai/agents/setup/prompt.tsdiff --git a/src/app/ai/agents/readiness.ts b/src/app/ai/agents/setup/readiness.tssimilarity index 100%rename from src/app/ai/agents/readiness.tsrename to src/app/ai/agents/setup/readiness.tsdiff --git a/src/app/ai/agents/setup/use.ts b/src/app/ai/agents/setup/use.tsnew file mode 100644index 000000000..8c8529b89--- /dev/null+++ b/src/app/ai/agents/setup/use.ts@@ -0,0 +1,180 @@+import { computed, ref, toValue, watch, type MaybeRefOrGetter } from 'vue'++import { ACP_AGENTS, type ACPAgentDef, type ACPAgentID } from '@open-pencil/core/constants'++import { readPiAccount } from '@/app/ai/agents/pi/settings'++import { agentAccounts } from './accounts'+import { agentDiscovery } from './discovery'+import type { AgentSetupState, MCPServerSetupState, PiSetupState } from './view'++type AgentDiscovery = typeof agentDiscovery+type AgentAccounts = typeof agentAccounts++/** Setup state of the coding agents and Pi, for guided setup and model settings. */+export function useAgentSetup(+ discovery: AgentDiscovery = agentDiscovery,+ readPi: typeof readPiAccount = readPiAccount,+ accounts: AgentAccounts = agentAccounts+) {+ const piDefaultModel = ref<string | null>(null)+ const piSignedIn = ref<boolean | null>(null)+ const readingPi = ref(false)++ function agentID(providerID: string): ACPAgentID | null {+ return ACP_AGENTS.find((agent) => `acp:${agent.id}` === providerID)?.id ?? null+ }++ function agentSetup(providerID: string): AgentSetupState {+ const id = agentID(providerID)+ return {+ ...mcpServerSetup(),+ scanning: discovery.scanning.value,+ detected: discovery.agents.value.find((agent) => agent.definition.id === id) ?? null,+ adapterNeedsAdmin: discovery.adapterNeedsAdmin.value,+ installingAgent: discovery.installing.value === id,+ account: id ? accounts.account(id) : undefined+ }+ }++ function installedAgent(providerID: string): ACPAgentDef | undefined {+ const detected = agentSetup(providerID).detected+ return detected?.status === 'available' ? detected.definition : undefined+ }++ /**+ * Reads the account of each installed agent setup can sign in to, all at once. Others, such+ * as Gemini CLI, do not report a login, so starting them would show nothing.+ */+ function checkAccounts(): Promise<void> {+ const installed = discovery.agents.value.filter(+ (agent) => agent.status === 'available' && agent.definition.signIn+ )+ return Promise.all(installed.map((agent) => accounts.check(agent.definition))).then(+ () => undefined+ )+ }++ function piSetup(providerID: string): PiSetupState | undefined {+ if (providerID !== 'harness:pi') return undefined+ return {+ ...mcpServerSetup(),+ scanning: discovery.scanning.value || readingPi.value,+ companion: discovery.harnessAvailable.value,+ companionOutdated: discovery.harnessOutdated.value,+ companionCommand: discovery.harnessCommand.value,+ companionNeedsAdmin: discovery.harnessNeedsAdmin.value,+ companionInstallable: discovery.harnessInstallable.value,+ installingCompanion: discovery.installing.value === 'harness',+ defaultModel: piDefaultModel.value,+ signedIn: piSignedIn.value+ }+ }++ function mcpServerSetup(): MCPServerSetupState {+ return {+ supported: discovery.supported,+ checked: discovery.checked.value,+ bridge: discovery.canvasBridgeAvailable.value,+ bridgeOutdated: discovery.canvasBridgeOutdated.value,+ bridgeCommand: discovery.canvasBridgeCommand.value,+ npm: discovery.npmAvailable.value,+ bridgeNeedsAdmin: discovery.canvasBridgeNeedsAdmin.value,+ bridgeInstallable: discovery.canvasBridgeInstallable.value,+ installingBridge: discovery.installing.value === 'canvas',+ error: discovery.error.value+ }+ }++ async function installAgent(providerID: string): Promise<void> {+ if (providerID === 'harness:pi') return discovery.setupHarness()+ const detected = agentSetup(providerID).detected+ if (!detected) return+ await discovery.install(detected.definition.id)+ const installed = installedAgent(providerID)+ if (installed) await accounts.check(installed)+ }++ async function refreshAgents(): Promise<void> {+ if (!discovery.supported) return+ readingPi.value = true+ try {+ const [, account] = await Promise.all([discovery.refresh(true), readPi().catch(() => null)])+ piDefaultModel.value = account?.defaultModel ?? null+ piSignedIn.value = account?.signedIn ?? null+ } finally {+ readingPi.value = false+ }+ await checkAccounts()+ }++ function signInAgent(providerID: string): Promise<void> {+ const agent = installedAgent(providerID)+ return agent ? accounts.signIn(agent) : Promise.resolve()+ }++ function agentAction(providerID: string, run: (id: ACPAgentID) => Promise<void>) {+ const id = agentID(providerID)+ return id ? run(id) : Promise.resolve()+ }++ return {+ agentSetup,+ piSetup,+ mcpServerSetup,+ installAgent,+ refreshAgents,+ signInAgent,+ cancelAgentSignIn: (providerID: string) => agentAction(providerID, accounts.cancelSignIn),+ submitAgentSignInCode: (providerID: string, code: string) =>+ agentAction(providerID, (id) => accounts.submitCode(id, code)),+ setupCanvasBridge: () => discovery.setupCanvasBridge()+ }+}++/**+ * Pi's setup while `active`, checked each time it becomes active. Undefined outside the desktop+ * app, where Pi cannot run and there is nothing to check.+ */+export function usePiSetup(active: MaybeRefOrGetter<boolean>, setup = useAgentSetup()) {+ const state = computed(() => {+ const pi = toValue(active) ? setup.piSetup('harness:pi') : undefined+ return pi?.supported ? pi : undefined+ })+ watch(+ () => toValue(active),+ (on) => {+ if (on) void setup.refreshAgents()+ },+ { immediate: true }+ )+ return {+ state,+ refresh: setup.refreshAgents,+ installCompanion: () => setup.installAgent('harness:pi'),+ installBridge: setup.setupCanvasBridge+ }+}++/**+ * The MCP server's setup while `active`, checked each time it becomes active, so Settings → MCP+ * can install or update the server with one click.+ */+export function useMCPServerSetup(+ active: MaybeRefOrGetter<boolean>,+ discovery: AgentDiscovery = agentDiscovery+) {+ const setup = useAgentSetup(discovery)+ watch(+ () => toValue(active),+ (on) => {+ if (on) void discovery.refresh(true)+ },+ { immediate: true }+ )+ return {+ state: computed(() => setup.mcpServerSetup()),+ install: () => discovery.setupCanvasBridge(),+ check: () => discovery.refresh(true)+ }+}diff --git a/src/app/ai/agents/setup.ts b/src/app/ai/agents/setup/view.tssimilarity index 68%rename from src/app/ai/agents/setup.tsrename to src/app/ai/agents/setup/view.tsindex 789620ca9..9b913ff27 100644--- a/src/app/ai/agents/setup.ts+++ b/src/app/ai/agents/setup/view.ts@@ -1,17 +1,11 @@-import { computed, ref, toValue, watch, type MaybeRefOrGetter } from 'vue'+import { type ACPAgentDef } from '@open-pencil/core/constants'-import { ACP_AGENTS, type ACPAgentDef, type ACPAgentID } from '@open-pencil/core/constants'--import { isSignedIn } from '@/app/ai/acp/auth/status'-import { readPiAccount } from '@/app/ai/harness/pi-settings'+import { isSignedIn } from '@/app/ai/agents/acp/auth/status'import { MCP_INSTALL_COMMAND } from '@/app/automation/mcp/failure'import { detectUserAgent } from '@/app/tauri/command'-import { agentAccounts, type AgentAccount } from './accounts'-import { agentDiscovery, type DetectedAgent, type DiscoveryError } from './discovery'--type AgentDiscovery = typeof agentDiscovery-type AgentAccounts = typeof agentAccounts+import { type AgentAccount } from './accounts'+import { type DetectedAgent, type DiscoveryError } from './discovery'/** What setup knows about one coding agent and the MCP server it needs. */export interface AgentSetupState {@@ -378,171 +372,3 @@ export function piSetupView(setup: PiSetupState): PiSetupView {: []}}--/** Setup state of the coding agents and Pi, for guided setup and model settings. */-export function useAgentSetup(- discovery: AgentDiscovery = agentDiscovery,- readPi: typeof readPiAccount = readPiAccount,- accounts: AgentAccounts = agentAccounts-) {- const piDefaultModel = ref<string | null>(null)- const piSignedIn = ref<boolean | null>(null)- const readingPi = ref(false)-- function agentID(providerID: string): ACPAgentID | null {- return ACP_AGENTS.find((agent) => `acp:${agent.id}` === providerID)?.id ?? null- }-- function agentSetup(providerID: string): AgentSetupState {- const id = agentID(providerID)- return {- ...mcpServerSetup(),- scanning: discovery.scanning.value,- detected: discovery.agents.value.find((agent) => agent.definition.id === id) ?? null,- adapterNeedsAdmin: discovery.adapterNeedsAdmin.value,- installingAgent: discovery.installing.value === id,- account: id ? accounts.account(id) : undefined- }- }-- function installedAgent(providerID: string): ACPAgentDef | undefined {- const detected = agentSetup(providerID).detected- return detected?.status === 'available' ? detected.definition : undefined- }-- /**- * Reads the account of each installed agent setup can sign in to, all at once. Others, such- * as Gemini CLI, do not report a login, so starting them would show nothing.- */- function checkAccounts(): Promise<void> {- const installed = discovery.agents.value.filter(- (agent) => agent.status === 'available' && agent.definition.signIn- )- return Promise.all(installed.map((agent) => accounts.check(agent.definition))).then(- () => undefined- )- }-- function piSetup(providerID: string): PiSetupState | undefined {- if (providerID !== 'harness:pi') return undefined- return {- ...mcpServerSetup(),- scanning: discovery.scanning.value || readingPi.value,- companion: discovery.harnessAvailable.value,- companionOutdated: discovery.harnessOutdated.value,- companionCommand: discovery.harnessCommand.value,- companionNeedsAdmin: discovery.harnessNeedsAdmin.value,- companionInstallable: discovery.harnessInstallable.value,- installingCompanion: discovery.installing.value === 'harness',- defaultModel: piDefaultModel.value,- signedIn: piSignedIn.value- }- }-- function mcpServerSetup(): MCPServerSetupState {- return {- supported: discovery.supported,- checked: discovery.checked.value,- bridge: discovery.canvasBridgeAvailable.value,- bridgeOutdated: discovery.canvasBridgeOutdated.value,- bridgeCommand: discovery.canvasBridgeCommand.value,- npm: discovery.npmAvailable.value,- bridgeNeedsAdmin: discovery.canvasBridgeNeedsAdmin.value,- bridgeInstallable: discovery.canvasBridgeInstallable.value,- installingBridge: discovery.installing.value === 'canvas',- error: discovery.error.value- }- }-- async function installAgent(providerID: string): Promise<void> {- if (providerID === 'harness:pi') return discovery.setupHarness()- const detected = agentSetup(providerID).detected- if (!detected) return- await discovery.install(detected.definition.id)- const installed = installedAgent(providerID)- if (installed) await accounts.check(installed)- }-- async function refreshAgents(): Promise<void> {- if (!discovery.supported) return- readingPi.value = true- try {- const [, account] = await Promise.all([discovery.refresh(true), readPi().catch(() => null)])- piDefaultModel.value = account?.defaultModel ?? null- piSignedIn.value = account?.signedIn ?? null- } finally {- readingPi.value = false- }- await checkAccounts()- }-- function signInAgent(providerID: string): Promise<void> {- const agent = installedAgent(providerID)- return agent ? accounts.signIn(agent) : Promise.resolve()- }-- function agentAction(providerID: string, run: (id: ACPAgentID) => Promise<void>) {- const id = agentID(providerID)- return id ? run(id) : Promise.resolve()- }-- return {- agentSetup,- piSetup,- mcpServerSetup,- installAgent,- refreshAgents,- signInAgent,- cancelAgentSignIn: (providerID: string) => agentAction(providerID, accounts.cancelSignIn),- submitAgentSignInCode: (providerID: string, code: string) =>- agentAction(providerID, (id) => accounts.submitCode(id, code)),- setupCanvasBridge: () => discovery.setupCanvasBridge()- }-}--/**- * Pi's setup while `active`, checked each time it becomes active. Undefined outside the desktop- * app, where Pi cannot run and there is nothing to check.- */-export function usePiSetup(active: MaybeRefOrGetter<boolean>, setup = useAgentSetup()) {- const state = computed(() => {- const pi = toValue(active) ? setup.piSetup('harness:pi') : undefined- return pi?.supported ? pi : undefined- })- watch(- () => toValue(active),- (on) => {- if (on) void setup.refreshAgents()- },- { immediate: true }- )- return {- state,- refresh: setup.refreshAgents,- installCompanion: () => setup.installAgent('harness:pi'),- installBridge: setup.setupCanvasBridge- }-}--/**- * The MCP server's setup while `active`, checked each time it becomes active, so Settings → MCP- * can install or update the server with one click.- */-export function useMCPServerSetup(- active: MaybeRefOrGetter<boolean>,- discovery: AgentDiscovery = agentDiscovery-) {- const setup = useAgentSetup(discovery)- watch(- () => toValue(active),- (on) => {- if (on) void discovery.refresh(true)- },- { immediate: true }- )- return {- state: computed(() => setup.mcpServerSetup()),- install: () => discovery.setupCanvasBridge(),- check: () => discovery.refresh(true)- }-}diff --git a/src/app/ai/attachment/image/analyze.ts b/src/app/ai/attachment/image/analyze.tsindex 6dade2b32..4b541dfd5 100644--- a/src/app/ai/attachment/image/analyze.ts+++ b/src/app/ai/attachment/image/analyze.ts@@ -4,10 +4,10 @@ import { computeContentBounds } from '@open-pencil/core/io'import { IMAGE_ATTACHMENT_MAX_EDGE } from '@/app/ai/attachment/image/prepare'import type { PreparedImageAttachment } from '@/app/ai/attachment/image/types'-import { runtimeReasoningSettings } from '@/app/ai/chat/reasoning'import { createAIModelRuntime } from '@/app/ai/models'-import { boundedImageScale } from '@/app/ai/tools/vision'-import type { VisionModelDependencies } from '@/app/ai/vision-runtime'+import { runtimeReasoningSettings } from '@/app/ai/models/reasoning/settings'+import { boundedImageScale } from '@/app/ai/tools/vision/inspect'+import type { VisionModelDependencies } from '@/app/ai/tools/vision/runtime'import type { EditorStore } from '@/app/editor/active-store'const MAX_IMAGE_ANALYSIS_TOKENS = 1200diff --git a/src/app/ai/attachment/image/prepare.ts b/src/app/ai/attachment/image/prepare.tsindex 2267d1cff..c7bbdbbcc 100644--- a/src/app/ai/attachment/image/prepare.ts+++ b/src/app/ai/attachment/image/prepare.ts@@ -3,7 +3,7 @@ import type {PreparedImageAttachment} from '@/app/ai/attachment/image/types'import { IMAGE_ATTACHMENT_MEDIA_TYPES } from '@/app/ai/attachment/image/types'-import { boundedImageScale } from '@/app/ai/tools/vision'+import { boundedImageScale } from '@/app/ai/tools/vision/inspect'const MAX_IMAGE_FILE_BYTES = 20 * 1024 * 1024const MAX_IMAGE_PIXELS = 40_000_000diff --git a/src/app/ai/chat/history/messages.ts b/src/app/ai/chat/history/messages.tsindex 3c229760b..f793ffcce 100644--- a/src/app/ai/chat/history/messages.ts+++ b/src/app/ai/chat/history/messages.ts@@ -6,7 +6,7 @@ import {setMessageAttachments} from '@/app/ai/attachment/presentation/store'import { visibleMessageText, setVisibleMessageText } from '@/app/ai/chat/presentation'-import { settleMessage } from '@/app/ai/chat/settle'+import { settleMessage } from '@/app/ai/reply/settle'import { readToolChange, setToolChange } from '@/app/ai/tools/changes/store'import type { ConversationMessage } from './types'diff --git a/src/app/ai/chat/preferences.ts b/src/app/ai/chat/preferences.tsindex 2f0e2bf74..9e95b7bda 100644--- a/src/app/ai/chat/preferences.ts+++ b/src/app/ai/chat/preferences.ts@@ -1,13 +1,12 @@import { computed } from 'vue'+import { resolveAgentStepLimit } from '@/app/ai/reply/step-limit'import {appPreferences,type ChangePreviewSize,type ReasoningDisplay} from '@/app/settings/preferences/store'-import { resolveAgentStepLimit } from './step-limit'-export const maxAgentSteps = computed({get: () => resolveAgentStepLimit(appPreferences.value.chat.maxAgentSteps),set: (value: number) => {diff --git a/src/app/ai/chat/transports.ts b/src/app/ai/chat/session.tssimilarity index 56%rename from src/app/ai/chat/transports.tsrename to src/app/ai/chat/session.tsindex 019b8c135..a6d7c8f02 100644--- a/src/app/ai/chat/transports.ts+++ b/src/app/ai/chat/session.ts@@ -1,31 +1,21 @@import { Chat } from '@ai-sdk/vue'-import { useEventListener } from '@vueuse/core'-import { createUIMessageStream, DirectChatTransport, stepCountIs, ToolLoopAgent } from 'ai'-import type {- ChatTransport,- FinishReason,- LanguageModel,- ToolExecutionOptions,- UIMessage-} from 'ai'+import type { ChatTransport, FinishReason, UIMessage } from 'ai'import type { ComputedRef, Ref } from 'vue'import { ref } from 'vue'import { ACP_AGENTS } from '@open-pencil/core/constants'-import type { ACPAgentID, AIProviderID, ReasoningEffort } from '@open-pencil/core/constants'+import type { ACPAgentID, AIProviderID } from '@open-pencil/core/constants'-import { AgentSetupError, assertAgentReady } from '@/app/ai/agents/readiness'+import { AgentSetupError, assertAgentReady } from '@/app/ai/agents/setup/readiness'import { classifyAIChatError, type AIChatFailure } from '@/app/ai/chat/failure'-import { resolveLanguageModelID } from '@/app/ai/chat/model'-import { reasoningCallSettings, type AIProviderOptions } from '@/app/ai/chat/reasoning'import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt'import { chatThinkingLevel } from '@/app/ai/chat/thinking'import { createAIModelRuntime, resolveModelConnectionAPIKey } from '@/app/ai/models'-import type { ThinkingLevel } from '@/app/ai/models/types'-import { createRunPreview } from '@/app/ai/preview/run'-import { createAITools, currentRun, endRun, recordStep, startRun } from '@/app/ai/tools'-import { enabledAIToolDefinitions } from '@/app/ai/tools/catalog'-import { aiToolOverrides } from '@/app/ai/tools/preferences'+import { resolveLanguageModelID } from '@/app/ai/models/language-model'+import { settleMessage } from '@/app/ai/reply/settle'+import { currentRun } from '@/app/ai/tools'+import type { AgentTurnUsage } from '@/app/ai/transports/acp'+import { createToolLoopTransport } from '@/app/ai/transports/tool-loop'import { restAgents } from '@/app/automation/agents'import { diagnosticErrorDetails } from '@/app/diagnostics'import {@@ -38,13 +28,9 @@ import type { AIDiagnosticContext } from '@/app/diagnostics/events/ai'import type { getActiveEditorStore } from '@/app/editor/active-store'import { trackUsage } from '@/app/telemetry'-import { resumableTransport } from './history/continuation'import { createTraceStore } from './history/idb'import { updateMessage } from './metadata'-import { maxAgentSteps } from './preferences'-import { settleMessage } from './settle'import { createRunRecorder } from './trace/recorder'-import type { RunRecorder, RunRecording } from './trace/recorder'type EditorStore = ReturnType<typeof getActiveEditorStore>@@ -57,195 +43,19 @@ type ChatSessionOptions = {getActiveEditorStore: () => EditorStore}-export type ToolLoopTransportOptions = {- store: EditorStore- providerID: AIProviderID- model: LanguageModel- effectiveModelID: string- minReasoningEffort?: ReasoningEffort- maxOutputTokens: number- /** Read per request, so the composer's level applies to the next message. */- thinkingLevel: () => ThinkingLevel- onError?: (error: unknown) => void- diagnosticContext?: AIDiagnosticContext- /** Records each run so a saved trace can rebuild its requests. */- recorder?: RunRecorder-}--const ANTHROPIC_CACHE_CONTROL = {- anthropic: { cacheControl: { type: 'ephemeral' } }-} as const--function supportsAnthropicCaching(providerID: AIProviderID, modelID: string): boolean {- return (- providerID === 'anthropic' ||- providerID === 'anthropic-compatible' ||- (providerID === 'openrouter' && modelID.startsWith('anthropic/'))- )-}--function mergeProviderOptions(- cacheOptions: typeof ANTHROPIC_CACHE_CONTROL | undefined,- reasoningOptions: AIProviderOptions | undefined-): AIProviderOptions | undefined {- if (!cacheOptions && !reasoningOptions) return undefined- return { ...cacheOptions, ...reasoningOptions }-}--function callSettings(+export async function createACPTransport(providerID: AIProviderID,- cacheOptions: typeof ANTHROPIC_CACHE_CONTROL | undefined,- thinkingLevel: ThinkingLevel,- minReasoningEffort: ReasoningEffort | undefined+ store?: EditorStore,+ onUsage?: (usage: AgentTurnUsage) => void) {- const { reasoning, providerOptions } = reasoningCallSettings(- providerID,- thinkingLevel,- minReasoningEffort- )- return { reasoning, providerOptions: mergeProviderOptions(cacheOptions, providerOptions) }-}--export async function createACPTransport(providerID: AIProviderID) {const agentId = providerID.replace('acp:', '') as ACPAgentIDconst agentDef = ACP_AGENTS.find((a) => a.id === agentId)if (!agentDef) throw new Error(`Unknown ACP agent: ${agentId}`)- const { ACPChatTransport } = await import('@/app/ai/acp/transport')- const { agentWorkspace } = await import('@/app/ai/agents/native')+ const { ACPChatTransport } = await import('@/app/ai/transports/acp')+ const { agentWorkspace } = await import('@/app/ai/agents/setup/native')// A folder of its own, not the home folder, whose project settings the agent would read.- return new ACPChatTransport({ agentDef, cwd: await agentWorkspace() })-}--export function createToolLoopTransport({- store,- providerID,- model,- effectiveModelID,- minReasoningEffort,- maxOutputTokens,- thinkingLevel,- onError,- diagnosticContext = {},- recorder-}: ToolLoopTransportOptions) {- const tools = createAITools(store, diagnosticContext)- // The reply in progress; a transport sends one message at a time.- let run = currentRun(store)- // While JSX streams, the chat's agent moves through the elements as they appear, here and- // on the screens of everyone else in the room.- const preview = createRunPreview(store)- const renderTool = tools.render- renderTool.onInputStart = ({ toolCallId, abortSignal }) => preview.start(toolCallId, abortSignal)- renderTool.onInputDelta = ({ toolCallId, inputTextDelta }) =>- preview.delta(toolCallId, inputTextDelta)- renderTool.onInputAvailable = ({ toolCallId }: ToolExecutionOptions<unknown>) =>- preview.finish(toolCallId)- const cacheProviderOptions = supportsAnthropicCaching(providerID, effectiveModelID)- ? ANTHROPIC_CACHE_CONTROL- : undefined- let recording: RunRecording | undefined- const agent = new ToolLoopAgent({- model,- instructions: SYSTEM_PROMPT,- tools,- maxOutputTokens,- // Kept only to fingerprint each step's request for its trace.- include: { requestMessages: recorder !== undefined },- prepareCall: (options) => {- const enabledNames = new Set(- enabledAIToolDefinitions(aiToolOverrides.value).map((tool) => tool.name)- )- preview.clear()- // Keep the full catalog for validating history; offer only enabled tools to this request.- const offered = Object.fromEntries(- Object.entries(tools).filter(([name]) => enabledNames.has(name))- )- recording?.offer(offered)- return {- ...options,- stopWhen: stepCountIs(currentRun(store).maxSteps),- tools: offered,- maxOutputTokens,- ...callSettings(providerID, cacheProviderOptions, thinkingLevel(), minReasoningEffort)- }- },- onFinish: () => {- preview.clear()- endRun(store, run)- recording?.end('completed')- },- onStepFinish: (step) => {- const { usage } = step- preview.clear()- recordStep(store)- recording?.step(step)- recordModelStepCompleted(- {- provider: providerID,- model: effectiveModelID,- inputTokens: usage.inputTokens ?? null,- outputTokens: usage.outputTokens ?? null,- cacheReadTokens: usage.inputTokenDetails.cacheReadTokens ?? null,- cacheWriteTokens: usage.inputTokenDetails.cacheWriteTokens ?? null- },- diagnosticContext- )- }- })-- function handleError(error: unknown): string {- preview.clear()- endRun(store, run)- recording?.fail(error)- onError?.(error)- return 'The provider rejected the request.'- }- const transport = new DirectChatTransport({- agent,- onError: handleError- }) as ChatTransport<UIMessage>- return resumableTransport({- reconnectToStream: (options) => transport.reconnectToStream(options),- async sendMessages(options) {- // The run starts as the message is sent, so a Stop before the model is reached ends it.- const started = startRun(store, maxAgentSteps.value, effectiveModelID)- run = started- const { sessionId, runId } = diagnosticContext- const startedRecording =- sessionId && runId- ? recorder?.start({- conversationId: sessionId,- runId,- model: { provider: providerID, id: effectiveModelID },- settings: {- maxOutputTokens,- maxSteps: started.maxSteps,- thinking: thinkingLevel(),- cache: cacheProviderOptions !== undefined- },- instructions: SYSTEM_PROMPT,- messages: options.messages- })- : undefined- recording = startedRecording- // Stopping a reply ends the run without onFinish.- const stop = () => {- endRun(store, started)- startedRecording?.end('stopped')- }- const { abortSignal } = options- if (abortSignal?.aborted) stop()- else if (abortSignal) useEventListener(abortSignal, 'abort', stop)- // DirectChatTransport handles error chunks, but not a rejected underlying stream.- return createUIMessageStream<UIMessage>({- execute: async ({ writer }) => {- writer.merge(await transport.sendMessages(options))- },- onError: handleError- })- }- })+ return new ACPChatTransport({ agentDef, cwd: await agentWorkspace(), store, onUsage })}/**@@ -330,23 +140,27 @@ export function createChatSessionManager({if (errors.length) throw new AggregateError(errors, 'Agent transport teardown failed')}- async function createActiveACPTransport() {+ async function createActiveACPTransport(store: EditorStore, context: AIDiagnosticContext) {await destroyAgentTransports()await assertAgentReady('acp')- const transport = await createACPTransport(providerID.value)+ 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)+ )acpTransportInstance = transportreturn transport as ChatTransport<UIMessage>}- async function createActiveHarnessTransport(sessionId: string) {+ async function createActiveHarnessTransport(sessionId: string, context: AIDiagnosticContext) {await destroyAgentTransports()const runtime = await createAIModelRuntime('design')if (runtime?.kind !== 'harness') throw new Error('The Design agent is not configured for Pi')await assertAgentReady('pi')const [{ HarnessChatTransport }, { buildPiMCPServers }, { readPiAccount }] = await Promise.all([- import('@/app/ai/harness/transport'),+ import('@/app/ai/transports/pi'),import('@/app/integrations/mcp'),- import('@/app/ai/harness/pi-settings')+ import('@/app/ai/agents/pi/settings')])// A saved key is an AI Gateway key; without one, Pi uses the CLI's own sign-in.const apiKey = await resolveModelConnectionAPIKey(runtime.role.connection.id)@@ -375,7 +189,9 @@ export function createChatSessionManager({},apiKey? { OPENPENCIL_HARNESS_API_KEY: apiKey }- : { OPENPENCIL_HARNESS_AGENT_DIR: account?.agentDir ?? '' }+ : { OPENPENCIL_HARNESS_AGENT_DIR: account?.agentDir ?? '' },+ undefined,+ (usage) => recordModelStepCompleted({ provider: providerID.value, model, ...usage }, context))harnessTransportInstance = transportreturn transport as ChatTransport<UIMessage>@@ -428,10 +244,10 @@ export function createChatSessionManager({let agentKind: 'acp' | 'harness' | null = nullif (isACPProvider.value) {agentKind = 'acp'- transport = await createActiveACPTransport()+ transport = await createActiveACPTransport(store, diagnosticContext)} else if (isHarnessProvider.value) {agentKind = 'harness'- transport = await createActiveHarnessTransport(sessionId)+ transport = await createActiveHarnessTransport(sessionId, diagnosticContext)} else {transport = await createTransport(store, diagnosticContext)}diff --git a/src/app/ai/chat/submission/errors.ts b/src/app/ai/chat/submission/errors.tsindex 473bdf2dc..be4619098 100644--- a/src/app/ai/chat/submission/errors.ts+++ b/src/app/ai/chat/submission/errors.ts@@ -1,6 +1,6 @@import type { Ref } from 'vue'-import { AgentSetupError, type AgentSetupProblem } from '@/app/ai/agents/readiness'+import { AgentSetupError, type AgentSetupProblem } from '@/app/ai/agents/setup/readiness'import { VisionModelUnavailableError } from '@/app/ai/attachment/image/analyze'export interface SubmissionMessages {diff --git a/src/app/ai/chat/submission/use.ts b/src/app/ai/chat/submission/use.tsindex 567d8a9f6..0a71ae6d1 100644--- a/src/app/ai/chat/submission/use.ts+++ b/src/app/ai/chat/submission/use.ts@@ -16,8 +16,8 @@ import { reportSubmissionError, type SubmissionErrorOptions } from '@/app/ai/chaimport { prepareSubmittedImages } from '@/app/ai/chat/submission/images'import { chatToResend } from '@/app/ai/chat/submission/resend'import type { ChatInstance, ChatSubmission } from '@/app/ai/chat/submission/types'-import { useUndoRecords } from '@/app/ai/chat/submission/undone'-import { restoreTurn, revertTurn } from '@/app/ai/chat/turns'+import { restoreTurn, revertTurn } from '@/app/ai/reply/turns'+import { useUndoRecords } from '@/app/ai/reply/undo'import type { EditorStore } from '@/app/editor/active-store'interface SubmissionOptions extends SubmissionErrorOptions {diff --git a/src/app/ai/chat/use.ts b/src/app/ai/chat/use.tsindex 72f08b717..c883dee90 100644--- a/src/app/ai/chat/use.ts+++ b/src/app/ai/chat/use.ts@@ -3,6 +3,7 @@ import { ref } from 'vue'import { IS_BROWSER } from '@open-pencil/core/constants'import { createConversationHistory } from '@/app/ai/chat/history/controller'+import { createChatSessionManager } from '@/app/ai/chat/session'import {apiKeyStatus,browserCredentialsRemembered,@@ -21,7 +22,6 @@ import {resolveAPIKey,setAPIKey} from '@/app/ai/chat/storage'-import { createChatSessionManager } from '@/app/ai/chat/transports'import { designModelProfile } from '@/app/ai/models'import { exposeChatTransportOverride } from '@/app/browser-bridge'import { getActiveEditorStore } from '@/app/editor/active-store'diff --git a/src/app/ai/chat/connection-test.ts b/src/app/ai/models/connection-test.tssimilarity index 96%rename from src/app/ai/chat/connection-test.tsrename to src/app/ai/models/connection-test.tsindex 3a57e88c2..f80729794 100644--- a/src/app/ai/chat/connection-test.ts+++ b/src/app/ai/models/connection-test.ts@@ -1,7 +1,11 @@import { generateText } from 'ai'import { isInsufficientCreditError, providerErrorStatus } from '@/app/ai/chat/failure'-import { createLanguageModel, resolveLanguageModelID, type ModelConfig } from '@/app/ai/chat/model'+import {+ createLanguageModel,+ resolveLanguageModelID,+ type ModelConfig+} from '@/app/ai/models/language-model'import { isTauri } from '@/app/tauri/env'export type ProviderConnectionTestResult =diff --git a/src/app/ai/chat/model.ts b/src/app/ai/models/language-model.tssimilarity index 100%rename from src/app/ai/chat/model.tsrename to src/app/ai/models/language-model.tsdiff --git a/src/app/ai/chat/provider-models.ts b/src/app/ai/models/reasoning/floors.tssimilarity index 100%rename from src/app/ai/chat/provider-models.tsrename to src/app/ai/models/reasoning/floors.tsdiff --git a/src/app/ai/chat/reasoning.ts b/src/app/ai/models/reasoning/settings.tssimilarity index 100%rename from src/app/ai/chat/reasoning.tsrename to src/app/ai/models/reasoning/settings.tsdiff --git a/src/app/ai/models/runtime.ts b/src/app/ai/models/runtime.tsindex 4e3154600..dab96b34d 100644--- a/src/app/ai/models/runtime.ts+++ b/src/app/ai/models/runtime.ts@@ -3,8 +3,8 @@ import { ref } from 'vue'import type { ReasoningEffort } from '@open-pencil/core/constants'-import { createLanguageModel, resolveLanguageModelID } from '@/app/ai/chat/model'-import { resolveProviderModel } from '@/app/ai/chat/provider-models'+import { createLanguageModel, resolveLanguageModelID } from '@/app/ai/models/language-model'+import { resolveProviderModel } from '@/app/ai/models/reasoning/floors'import { modelConnection, resolveAIModelRole } from '@/app/ai/models/store'import type { AIModelConnection, AIModelRole, ResolvedAIModelRole } from '@/app/ai/models/types'import { appCredentialServices } from '@/app/settings/credentials/app'diff --git a/src/app/ai/models/settings/onboarding/connections.ts b/src/app/ai/models/settings/onboarding/connections.tsindex 29edc2498..8c894e730 100644--- a/src/app/ai/models/settings/onboarding/connections.ts+++ b/src/app/ai/models/settings/onboarding/connections.ts@@ -1,16 +1,16 @@import { tryOnScopeDispose } from '@vueuse/core'import { reactive } from 'vue'-import {- testProviderConnection,- type ProviderConnectionTestFailureReason-} from '@/app/ai/chat/connection-test'import {aiModelSettings,modelConnectionCredentialStatus,resolveModelConnectionAPIKey,type AIModelConnection} from '@/app/ai/models'+import {+ testProviderConnection,+ type ProviderConnectionTestFailureReason+} from '@/app/ai/models/connection-test'import type { OpenRouterKeyInfo } from '@/app/ai/providers/openrouter/key'import type { CredentialStatus } from '@/app/settings/credentials/types'diff --git a/src/app/ai/models/settings/onboarding/use.ts b/src/app/ai/models/settings/onboarding/use.tsindex 6157bc3c1..dda3cd10b 100644--- a/src/app/ai/models/settings/onboarding/use.ts+++ b/src/app/ai/models/settings/onboarding/use.ts@@ -3,8 +3,12 @@ import { computed, reactive, ref, watch } from 'vue'import { ACP_AGENTS, IS_TAURI } from '@open-pencil/core/constants'-import { codingAgentDetection, piDetection, type AgentDetection } from '@/app/ai/agents/detection'-import { useAgentSetup } from '@/app/ai/agents/setup'+import {+ codingAgentDetection,+ piDetection,+ type AgentDetection+} from '@/app/ai/agents/setup/detection'+import { useAgentSetup } from '@/app/ai/agents/setup/use'import { refreshAIProviderStatus } from '@/app/ai/chat/storage'import {aiModelSettings,diff --git a/src/app/ai/models/settings/profile-editor/connection.ts b/src/app/ai/models/settings/profile-editor/connection.tsindex 84def3e88..937bc4e89 100644--- a/src/app/ai/models/settings/profile-editor/connection.ts+++ b/src/app/ai/models/settings/profile-editor/connection.ts@@ -1,16 +1,16 @@import { tryOnScopeDispose } from '@vueuse/core'import { computed, ref, type Ref } from 'vue'-import {- testProviderConnection,- type ProviderConnectionTestFailureReason-} from '@/app/ai/chat/connection-test'import {findModelConnectionForDraft,modelConnectionCredentialStatus,resolveModelConnectionAPIKey,type AIModelProfileDraft} from '@/app/ai/models'+import {+ testProviderConnection,+ type ProviderConnectionTestFailureReason+} from '@/app/ai/models/connection-test'import type { CredentialStatus } from '@/app/settings/credentials/types'interface ConnectionOptions {diff --git a/src/app/ai/preview/run.ts b/src/app/ai/preview/run.tsindex 17da51768..81cdc9a2a 100644--- a/src/app/ai/preview/run.ts+++ b/src/app/ai/preview/run.ts@@ -1,7 +1,7 @@import { useEventListener } from '@vueuse/core'import { createCanvasJSXPreview } from '@/app/ai/preview/canvas'-import { markRunPreview, runAgentId, runPageId } from '@/app/ai/tools/run'+import { markRunPreview, runAgentId, runPageId } from '@/app/ai/reply/run'import type { EditorStore } from '@/app/editor/active-store'import { publishAgentPreview } from '@/app/presence/preview-stream'diff --git a/src/app/ai/tools/run.ts b/src/app/ai/reply/run.tssimilarity index 83%rename from src/app/ai/tools/run.tsrename to src/app/ai/reply/run.tsindex e678f8da5..a3ef37493 100644--- a/src/app/ai/tools/run.ts+++ b/src/app/ai/reply/run.ts@@ -3,8 +3,8 @@ import type { StepBudget } from '@open-pencil/core/tools'import type { UndoEntry } from '@open-pencil/scene-graph/undo'import { describeUndoneCalls, type CallRef } from '@/app/ai/chat/context'-import { DEFAULT_AGENT_STEPS, resolveAgentStepLimit } from '@/app/ai/chat/step-limit'import type { PreviewFocus } from '@/app/ai/preview/canvas'+import { DEFAULT_AGENT_STEPS, resolveAgentStepLimit } from '@/app/ai/reply/step-limit'import { getActiveEditorStore } from '@/app/editor/active-store'import type { EditorStore } from '@/app/editor/active-store'import { addAgent, agentPlacement, type AgentHandle } from '@/app/presence/registry'@@ -19,9 +19,12 @@ export interface RunUndoCall extends CallRef {entry: UndoEntry}+/** What a chat reply's undo entries start with, before the tool's name. */+export const AI_UNDO_PREFIX = 'AI'+/** The label of an AI tool call's undo entry, which Edit → Undo shows. */export function aiUndoLabel(tool: string): string {- return `AI: ${tool}`+ return `${AI_UNDO_PREFIX}: ${tool}`}export class Run {@@ -44,9 +47,16 @@ export class Run {private whenSettled: Promise<void> = Promise.resolve()private settle: () => void = () => undefined- constructor(maxSteps: number, pageId: string) {+ /**+ * Whether the built-in chat's agent shows the run's work on the canvas and follows its page+ * changes; an ACP agent's run shows through its own MCP session instead.+ */+ readonly presence: boolean++ constructor(maxSteps: number, pageId: string, presence = true) {this.maxSteps = resolveAgentStepLimit(maxSteps)this.pageId = pageId+ this.presence = presence}hitLimit(): boolean {@@ -99,6 +109,35 @@ export function startRun(store: EditorStore, maxSteps: number, model?: string):return state.run}+/** Each ACP chat's document, by the chat id its agent's MCP session carries. */+const agentChats = new Map<string, EditorStore>()++/**+ * Begin a run for an ACP chat's reply. Its agent shows through its MCP session instead of as+ * the built-in chat, and its tool calls find the run by `chat` (`agentReplyRun`).+ */+export function startAgentRun(store: EditorStore, chat: string): Run {+ const state = getRunState(store)+ state.run = new Run(DEFAULT_AGENT_STEPS, store.state.currentPageId, false)+ agentChats.set(chat, store)+ return state.run+}++/** The ACP chat is gone, so a late call from its agent belongs to no reply. */+export function forgetAgentChat(chat: string): void {+ agentChats.delete(chat)+}++/**+ * The reply an ACP agent's tool call belongs to: its chat's run while the reply goes on, when+ * the call edits the chat's own document. A call elsewhere stays an ordinary agent edit.+ */+export function agentReplyRun(store: EditorStore, chat: string | undefined): Run | null {+ if (!chat || agentChats.get(chat) !== store) return null+ const run = currentRun(store)+ return run.active ? run : null+}+/*** The reply finished, failed, or was stopped: the agent stays listed but leaves the canvas.* Only the first call counts, and a later run is not ended by an earlier one's late call.@@ -107,7 +146,7 @@ export function endRun(store: EditorStore, run = currentRun(store)): void {const state = getRunState(store)if (!run.active) returnrun.active = false- if (state.run !== run) return+ if (state.run !== run || !run.presence) returnstate.agent?.update({status: 'idle',cursor: undefined,@@ -124,7 +163,7 @@ export function currentRun(store: EditorStore): Run {/** Whether the agent may still show where it works: its run is the latest and still going. */function agentAtWork(store: EditorStore): AgentHandle | null {const { agent, run } = getRunState(store)- return run.active ? agent : null+ return run.active && run.presence ? agent : null}/**@@ -190,8 +229,9 @@ export function runPageId(store: EditorStore): string {/** Move the run to `pageId`, and the user's view with it, as the agent's `switch_page` does. */export async function moveRunToPage(store: EditorStore, run: Run, pageId: string): Promise<void> {- // A stopped reply's late `switch_page` no longer takes the view anywhere.- if (!run.active) return+ // A stopped reply's late `switch_page` no longer takes the view anywhere, and an ACP agent's+ // page change is its own MCP session's to show.+ if (!run.active || !run.presence) returnrun.pageId = pageIdgetRunState(store).agent?.update({ pageId })if (store.state.currentPageId !== pageId) await store.switchPage(pageId)diff --git a/src/app/ai/chat/settle.ts b/src/app/ai/reply/settle.tssimilarity index 100%rename from src/app/ai/chat/settle.tsrename to src/app/ai/reply/settle.tsdiff --git a/src/app/ai/chat/step-limit.ts b/src/app/ai/reply/step-limit.tssimilarity index 100%rename from src/app/ai/chat/step-limit.tsrename to src/app/ai/reply/step-limit.tsdiff --git a/src/app/ai/reply/stream.ts b/src/app/ai/reply/stream.tsnew file mode 100644index 000000000..000354dba--- /dev/null+++ b/src/app/ai/reply/stream.ts@@ -0,0 +1,103 @@+import type { UIMessageChunk } from 'ai'++/** A tool call as the chat shows it. */+export interface ReplyToolCall {+ id: string+ name: string+ /** The agent's own title, for its own tools; OpenPencil's are named by `name`. */+ title?: string+}++/**+ * Builds one reply's message chunks from what a coding agent reports. Consecutive text or+ * thought forms one part, which closes when anything else arrives, so text after a tool call+ * starts a new part and a run of thoughts shows as one.+ */+export function createReplyStream(idPrefix: string) {+ let parts = 0+ let text: string | null = null+ let reasoning: string | null = null++ function nextId(kind: string): string {+ parts += 1+ return `${idPrefix}-${kind}-${parts}`+ }++ function closeText(): UIMessageChunk[] {+ if (!text) return []+ const id = text+ text = null+ return [{ type: 'text-end', id }]+ }++ function closeReasoning(): UIMessageChunk[] {+ if (!reasoning) return []+ const id = reasoning+ reasoning = null+ return [{ type: 'reasoning-end', id }]+ }++ return {+ text(delta: string): UIMessageChunk[] {+ if (!delta) return []+ const chunks = closeReasoning()+ if (!text) {+ text = nextId('text')+ chunks.push({ type: 'text-start', id: text })+ }+ chunks.push({ type: 'text-delta', id: text, delta })+ return chunks+ },++ thought(delta: string): UIMessageChunk[] {+ if (!delta) return []+ const chunks = closeText()+ if (!reasoning) {+ reasoning = nextId('reasoning')+ chunks.push({ type: 'reasoning-start', id: reasoning })+ }+ chunks.push({ type: 'reasoning-delta', id: reasoning, delta })+ return chunks+ },++ /** A call begins; its input may follow. */+ toolStart({ id, name, title }: ReplyToolCall): UIMessageChunk[] {+ return [+ ...closeText(),+ ...closeReasoning(),+ { type: 'tool-input-start', toolCallId: id, toolName: name, providerExecuted: true, title }+ ]+ },++ /** A call's complete input, which may come with its start or after it. */+ toolInput({ id, name, title }: ReplyToolCall, input: unknown): UIMessageChunk[] {+ return [+ ...closeText(),+ ...closeReasoning(),+ {+ type: 'tool-input-available',+ toolCallId: id,+ toolName: name,+ input,+ providerExecuted: true,+ title+ }+ ]+ },++ toolResult(id: string, output: unknown): UIMessageChunk[] {+ return [{ type: 'tool-output-available', toolCallId: id, output, providerExecuted: true }]+ },++ toolError(id: string, errorText: string): UIMessageChunk[] {+ return [{ type: 'tool-output-error', toolCallId: id, errorText, providerExecuted: true }]+ },++ /** Closes the text or thought still open when the reply ends. */+ end(): UIMessageChunk[] {+ return [...closeText(), ...closeReasoning()]+ }+ }+}++export type ReplyStream = ReturnType<typeof createReplyStream>diff --git a/src/app/ai/chat/turns.ts b/src/app/ai/reply/turns.tssimilarity index 99%rename from src/app/ai/chat/turns.tsrename to src/app/ai/reply/turns.tsindex 5e7f0ee5b..5a4650335 100644--- a/src/app/ai/chat/turns.ts+++ b/src/app/ai/reply/turns.ts@@ -4,8 +4,8 @@ import { shallowReactive, shallowRef, type ShallowRef } from 'vue'import type { UndoneCalls } from '@/app/ai/chat/context'import { undoOf, type ReplyUndo } from '@/app/ai/chat/metadata'+import type { RunUndoCall } from '@/app/ai/reply/run'import { currentRun } from '@/app/ai/tools'-import type { RunUndoCall } from '@/app/ai/tools/run'import type { EditorStore } from '@/app/editor/active-store'interface TurnRecord {diff --git a/src/app/ai/chat/submission/undone.ts b/src/app/ai/reply/undo.tssimilarity index 99%rename from src/app/ai/chat/submission/undone.tsrename to src/app/ai/reply/undo.tsindex e4c3db28d..58f2709cc 100644--- a/src/app/ai/chat/submission/undone.ts+++ b/src/app/ai/reply/undo.ts@@ -10,7 +10,7 @@ import {recordReplyTurn,undoToReport,type UndoReport-} from '@/app/ai/chat/turns'+} from '@/app/ai/reply/turns'import type { EditorStore } from '@/app/editor/active-store'interface UndoRecordOptions {diff --git a/src/app/ai/tools/changes/images.ts b/src/app/ai/tools/changes/images.tsindex 3e4035735..b894ce4e7 100644--- a/src/app/ai/tools/changes/images.ts+++ b/src/app/ai/tools/changes/images.ts@@ -9,7 +9,7 @@ import {import type { SceneGraph } from '@open-pencil/scene-graph'import type { VisualBounds } from '@open-pencil/scene-graph/geometry'-import { boundedImageScale } from '@/app/ai/tools/vision'+import { boundedImageScale } from '@/app/ai/tools/vision/inspect'import type { EditorStore } from '@/app/editor/active-store'import type { ChangePreviewSize } from '@/app/settings/preferences/store'diff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.tsindex f2794821c..f01a52af3 100644--- a/src/app/ai/tools/index.ts+++ b/src/app/ai/tools/index.ts@@ -1,39 +1,24 @@import { tool } from 'ai'import { isPlainObject } from 'es-toolkit'-import { graphFromPageSnapshot, isEmptyDocumentChange } from '@open-pencil/core/editor'-import type { FigmaAPI } from '@open-pencil/core/figma-api'-import {- registerComponentCatalog,- isAtomicTool,- toolChangesDocument,- toolsToAI,- type ToolDef-} from '@open-pencil/core/tools'+import { graphFromPageSnapshot } from '@open-pencil/core/editor'+import { registerComponentCatalog, isAtomicTool, toolsToAI } from '@open-pencil/core/tools'-import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'-import { executeAtomicEditorTool } from '@/app/automation/execution/editor'-import { recordToolCompleted, type AIDiagnosticContext } from '@/app/diagnostics/events/ai'-import type { EditorStore } from '@/app/editor/active-store'-import { ensureGraphFonts } from '@/app/editor/fonts'-import { useLibraryService } from '@/app/libraries'--import { aiToolDefinitions } from './catalog'-import { recordToolChange } from './changes/capture'-import { createMutex } from './mutex'import {- aiUndoLabel,currentRun,- markRunChange,markRunWork,- moveRunToPage,- recordRunBaseline,- recordRunUndoEntry,runBaseline,runPageId,stepBudget,takeRunUndoNote-} from './run'+} from '@/app/ai/reply/run'+import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'+import { recordToolCompleted, type AIDiagnosticContext } from '@/app/diagnostics/events/ai'+import type { EditorStore } from '@/app/editor/active-store'+import { useLibraryService } from '@/app/libraries'++import { aiToolDefinitions } from './catalog'+import { runEditorTool } from './runner'export {currentRun,@@ -45,7 +30,7 @@ export {runPageId,runUndoEntries,startRun-} from './run'+} from '@/app/ai/reply/run'/*** A result with the run's note about edits the user undid meanwhile, so the model does not@@ -57,95 +42,10 @@ function withUndoNote(result: unknown, note: string): unknown {}export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnosticContext) {- const acquireMutation = createMutex()const libraryService = useLibraryService()libraryService.bindEditor(store)registerComponentCatalog(store.graph, libraryService)- async function runTool(- def: ToolDef,- figma: FigmaAPI,- args: Record<string, unknown>,- pageId: string- ): Promise<unknown> {- if (isAtomicTool(def)) {- return executeAtomicEditorTool(store, figma, def, args, { label: 'AI' })- }- return store.runMutationWithLayout(- () => def.execute(figma, args),- pageId,- async () => {- const pageNode = store.graph.getNode(pageId)- if (pageNode) await ensureGraphFonts(store.graph, pageNode.childIds, store.renderer)- }- )- }-- /** Runs one call; an edit is snapshotted, recorded for undo, and shown where it happened. */- async function executeCall(- def: ToolDef,- figma: FigmaAPI,- args: Record<string, unknown>,- { toolCallId }: { toolCallId: string }- ): Promise<unknown> {- const pageId = figma.currentPageId- if (!def.mutates) return def.execute(figma, args)- // The call belongs to the reply that made it, even if a later one starts meanwhile.- const run = currentRun(store)- // A step's calls may run concurrently; whole-page snapshots must not interleave.- const release = await acquireMutation()- // Stopped while waiting for its turn: the reply is over, so nothing more is edited.- if (!run.active) {- release()- return { error: 'Stopped before this call ran; nothing was changed.' }- }- run.beginTool()- // The run's first edit to a page keeps the whole page, which `changeBaseline` diffs.- if (toolChangesDocument(def) && !run.baselines.has(pageId)) {- recordRunBaseline(run, store.snapshotPage(pageId))- }- const undoBefore = store.undo.peekUndo()- const finishChange = store.captureDocumentChange(pageId)- try {- return await runTool(def, figma, args, pageId)- } finally {- const change = finishChange()- if (!isEmptyDocumentChange(change)) run.changedCalls.add(toolCallId)- // Atomic tools record their own undo entry; an edit that changed nothing records none.- if (!isAtomicTool(def) && !isEmptyDocumentChange(change)) {- store.pushUndoStep({- label: aiUndoLabel(def.name),- forward: () => store.restoreDocumentChange(change, 'after'),- inverse: () => store.restoreDocumentChange(change, 'before')- })- }- // Every entry the run pushes belongs to its turn; atomic and page edits both label- // their entries this way. View tools change nothing on the page and push none.- recordRunUndoEntry(store, run, { tool: def.name, toolCallId }, undoBefore)- // View tools (selection, viewport, pages) cannot change the document.- if (toolChangesDocument(def)) {- try {- recordToolChange(store, toolCallId, change)- } catch (error) {- // The change record is a review aid; the edit and its undo entry already stand.- console.warn('Could not record AI tool change', error)- }- // The agent shows where it edited, even on another page; layers the result names- // refine this once the call returns.- markRunChange(store, change)- }- try {- // `switch_page` moves the run, and the user's view with it.- if (figma.currentPageId !== pageId) {- await moveRunToPage(store, run, figma.currentPageId)- }- } finally {- release()- run.endTool()- }- }- }-return toolsToAI(aiToolDefinitions,{@@ -157,8 +57,18 @@ export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnost}return figma},- executeTool: async (def, figma, args, options) =>- withUndoNote(await executeCall(def, figma, args, options), takeRunUndoNote(store)),+ executeTool: async (def, figma, args, { toolCallId }) =>+ withUndoNote(+ // The call belongs to the reply that made it, even if a later one starts meanwhile.+ await runEditorTool({+ store,+ figma,+ def,+ args,+ reply: { run: currentRun(store), toolCallId }+ }),+ takeRunUndoNote(store)+ ),onAfterExecute: (def) => {if (def.mutates && !isAtomicTool(def)) store.requestRender()},diff --git a/src/app/ai/tools/runner.ts b/src/app/ai/tools/runner.tsnew file mode 100644index 000000000..da64380b3--- /dev/null+++ b/src/app/ai/tools/runner.ts@@ -0,0 +1,170 @@+import { isEmptyDocumentChange } from '@open-pencil/core/editor'+import type { FigmaAPI } from '@open-pencil/core/figma-api'+import { isAtomicTool, toolChangesDocument, type ToolDef } from '@open-pencil/core/tools'++import {+ AI_UNDO_PREFIX,+ markRunChange,+ moveRunToPage,+ recordRunBaseline,+ recordRunUndoEntry,+ type Run+} from '@/app/ai/reply/run'+import { AUTOMATION_UNDO_LABEL, executeAtomicEditorTool } from '@/app/automation/execution/editor'+import type { EditorStore } from '@/app/editor/active-store'+import { ensureGraphFonts } from '@/app/editor/fonts'++import { recordToolChange } from './changes/capture'+import { createMutex } from './mutex'++/** The reply a call belongs to: its run, and the call's id in the reply's transcript. */+export interface ReplyCall {+ run: Run+ toolCallId: string+}++/** One call of an OpenPencil tool, from the built-in chat, a coding agent, or another client. */+export interface EditorToolCall {+ store: EditorStore+ figma: FigmaAPI+ def: ToolDef+ args: Record<string, unknown>+ /** The chat reply the call belongs to; a call from an outside client belongs to none. */+ reply?: ReplyCall | null+ /** What a call outside a reply labels its undo entry with, such as `Agent` or `WebMCP`. */+ source?: string+ signal?: AbortSignal+ /** False once the call's document closed, so a late edit is not drawn. */+ isLive?: () => boolean+}++export const STOPPED_BEFORE_CALL = 'Stopped before this call ran; nothing was changed.'++/** Each document's edits run one at a time, since whole-page snapshots must not interleave. */+const editLocks = new WeakMap<EditorStore, () => Promise<() => void>>()++function editLock(store: EditorStore): () => Promise<() => void> {+ let lock = editLocks.get(store)+ if (!lock) {+ lock = createMutex()+ editLocks.set(store, lock)+ }+ return lock+}++/**+ * The page a call writes to: a parent or a replaced layer on another page puts the new layers+ * there, so that page lays out, loads their fonts, and records the change.+ */+function writtenPageId(figma: FigmaAPI, args: Record<string, unknown>): string {+ // As render places it: a replaced layer's parent wins over parent_id.+ const nodeId = args.replace_id ?? args.parent_id+ const page =+ typeof nodeId === 'string'+ ? figma.graph.closest(nodeId, (node) => node.type === 'CANVAS')+ : undefined+ return page?.id ?? figma.currentPageId+}++async function execute(call: EditorToolCall, pageId: string, prefix: string): Promise<unknown> {+ const { store, figma, def, args } = call+ if (isAtomicTool(def)) {+ return executeAtomicEditorTool(store, figma, def, args, {+ label: prefix,+ signal: call.signal,+ isLive: call.isLive+ })+ }+ return store.runMutationWithLayout(+ () => def.execute(figma, args),+ pageId,+ async () => {+ const page = store.graph.getNode(pageId)+ if (page) await ensureGraphFonts(store.graph, page.childIds, store.renderer)+ }+ )+}++/** Records a reply's call once it ran: its undo entry, its change, and where its agent worked. */+async function recordReplyCall(+ call: EditorToolCall,+ reply: ReplyCall,+ change: ReturnType<ReturnType<EditorStore['captureDocumentChange']>>,+ undoBefore: ReturnType<EditorStore['undo']['peekUndo']>,+ viewPageId: string+): Promise<void> {+ const { store, figma, def } = call+ const { run, toolCallId } = reply+ if (!isEmptyDocumentChange(change)) run.changedCalls.add(toolCallId)+ recordRunUndoEntry(store, run, { tool: def.name, toolCallId }, undoBefore)+ // View tools (selection, viewport, pages) cannot change the document.+ if (toolChangesDocument(def)) {+ try {+ recordToolChange(store, toolCallId, change)+ } catch (error) {+ // The change record is a review aid; the edit and its undo entry already stand.+ console.warn('Could not record AI tool change', error)+ }+ // The agent shows where it edited, even on another page; layers the result names refine+ // this once the call returns.+ markRunChange(store, change)+ }+ // `switch_page` moves the run, and the user's view with it.+ if (figma.currentPageId !== viewPageId) await moveRunToPage(store, run, figma.currentPageId)+}++/** Runs an edit while its document's lock is held, and records it. */+async function editAndRecord(call: EditorToolCall, reply: ReplyCall | null): Promise<unknown> {+ const { store, figma, def, args } = call+ const viewPageId = figma.currentPageId+ const pageId = writtenPageId(figma, args)+ // A reply's first edit to a page keeps the whole page, which `changeBaseline` diffs.+ if (reply && toolChangesDocument(def) && !reply.run.baselines.has(pageId)) {+ recordRunBaseline(reply.run, store.snapshotPage(pageId))+ }+ const prefix = reply ? AI_UNDO_PREFIX : (call.source ?? AUTOMATION_UNDO_LABEL)+ const undoBefore = store.undo.peekUndo()+ const finishChange = store.captureDocumentChange(pageId)+ try {+ return await execute(call, pageId, prefix)+ } finally {+ const change = finishChange()+ // Atomic tools record their own entry; an edit that changed nothing records none.+ if (!isAtomicTool(def) && !isEmptyDocumentChange(change)) {+ store.pushUndoStep({+ label: `${prefix}: ${def.name}`,+ forward: () => store.restoreDocumentChange(change, 'after'),+ inverse: () => store.restoreDocumentChange(change, 'before')+ })+ }+ if (reply) await recordReplyCall(call, reply, change, undoBefore, viewPageId)+ }+}++/**+ * Runs one call of an OpenPencil tool. An edit runs alone in its document, is recorded as one+ * undo entry, and, for a call that belongs to a chat reply, joins the reply's run so the reply+ * can revert it and the transcript shows what it changed.+ */+export async function runEditorTool(call: EditorToolCall): Promise<unknown> {+ const { store, figma, def, args } = call+ if (!def.mutates) return def.execute(figma, args)+ const reply = call.reply ?? null+ const release = await editLock(store)()+ // Whatever fails from here, the lock and the reply's count of running tools are released.+ let began = false+ try {+ // Cancelled while waiting for its turn, as a WebMCP call can be: nothing is edited.+ call.signal?.throwIfAborted()+ // Stopped while waiting for its turn: the reply is over, so nothing more is edited.+ if (reply && !reply.run.active) return { error: STOPPED_BEFORE_CALL }+ if (reply) {+ reply.run.beginTool()+ began = true+ }+ return await editAndRecord(call, reply)+ } finally {+ release()+ if (began) reply?.run.endTool()+ }+}diff --git a/src/app/ai/tools/vision.ts b/src/app/ai/tools/vision/inspect.tssimilarity index 95%rename from src/app/ai/tools/vision.tsrename to src/app/ai/tools/vision/inspect.tsindex 87f5292ea..463aea7ea 100644--- a/src/app/ai/tools/vision.ts+++ b/src/app/ai/tools/vision/inspect.ts@@ -4,10 +4,10 @@ import * as v from 'valibot'import { computeContentBounds } from '@open-pencil/core/io'-import { runtimeReasoningSettings } from '@/app/ai/chat/reasoning'import { createAIModelRuntime } from '@/app/ai/models'-import { runPageId } from '@/app/ai/tools/run'-import type { VisionModelDependencies } from '@/app/ai/vision-runtime'+import { runtimeReasoningSettings } from '@/app/ai/models/reasoning/settings'+import { runPageId } from '@/app/ai/reply/run'+import type { VisionModelDependencies } from '@/app/ai/tools/vision/runtime'import type { EditorStore } from '@/app/editor/active-store'const DEFAULT_VISION_MAX_EDGE = 1280diff --git a/src/app/ai/vision-runtime.ts b/src/app/ai/tools/vision/runtime.tssimilarity index 100%rename from src/app/ai/vision-runtime.tsrename to src/app/ai/tools/vision/runtime.tsdiff --git a/src/app/ai/acp/transport.ts b/src/app/ai/transports/acp.tssimilarity index 77%rename from src/app/ai/acp/transport.tsrename to src/app/ai/transports/acp.tsindex 657936758..d04eebb42 100644--- a/src/app/ai/acp/transport.ts+++ b/src/app/ai/transports/acp.ts@@ -4,30 +4,65 @@ import type {Agent,SessionNotification,RequestPermissionRequest,- RequestPermissionResponse+ RequestPermissionResponse,+ Usage} from '@agentclientprotocol/sdk'import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'+import * as v from 'valibot'import type { ACPAgentDef } from '@open-pencil/core/constants'+import { parseAuthStatusUpdate } from '@/app/ai/agents/acp/auth/status'+import { createUpdateMapper } from '@/app/ai/agents/acp/events'+import { spawnACPProcess } from '@/app/ai/agents/acp/process'+import { linkOwnTools } from '@/app/ai/agents/acp/tools'import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt'+import { endRun, forgetAgentChat, startAgentRun } from '@/app/ai/reply/run'import { describeDiagnosticError, recordACPTransportFailure } from '@/app/diagnostics'--import { parseAuthStatusUpdate } from './auth/status'-import { createUpdateMapper } from './map-update'-import { linkOwnTools } from './own-tools'-import { spawnACPProcess } from './process'+import type { EditorStore } from '@/app/editor/active-store'type TauriChild = Awaited<ReturnType<typeof spawnACPProcess>>['child']interface ACPSession {connection: ClientSideConnectionsessionId: string+ /** The id the agent's tool calls carry, which ties them to this chat's replies. */+ chat: stringchild: TauriChildonUpdate: ((params: SessionNotification) => void) | nulldead: boolean+ /** The model the agent says it uses, once it has said; Codex names it, Claude in its usage. */+ model: string | null+}++/** One agent turn's tokens, as an ACP agent reports them with its answer to the prompt. */+export interface AgentTurnUsage {+ model: string | null+ /** All input tokens, cached ones included, as the AI SDK counts a provider model's input. */+ inputTokens: number+ outputTokens: number+ cacheReadTokens: number | null+ cacheWriteTokens: number | null}+/**+ * The agents report fresh input apart from cache reads and writes; the chat's other models count+ * all of it as input, with the cached part broken out.+ */+export function agentTurnUsage(usage: Usage, model: string | null): AgentTurnUsage {+ const cacheReadTokens = usage.cachedReadTokens ?? null+ const cacheWriteTokens = usage.cachedWriteTokens ?? null+ return {+ model,+ inputTokens: usage.inputTokens + (cacheReadTokens ?? 0) + (cacheWriteTokens ?? 0),+ outputTokens: usage.outputTokens,+ cacheReadTokens,+ cacheWriteTokens+ }+}++const usageMetaSchema = v.object({ '_claude/model': v.string() })+function isMissingCommandError(message: string): boolean {const normalized = message.toLowerCase()return normalized.includes('enoent') || normalized.includes('program not found')@@ -103,9 +138,21 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {/** The agent while it starts, before it becomes the session, so destroying can stop it. */private starting: TauriChild | null = null- constructor(options: { agentDef: ACPAgentDef; cwd?: string }) {+ /** 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++ constructor(options: {+ agentDef: ACPAgentDef+ cwd?: string+ store?: EditorStore+ /** Told each turn's tokens, which the Usage settings count with the chat's other models. */+ onUsage?: (usage: AgentTurnUsage) => void+ }) {this.agentDef = options.agentDefthis.cwd = options.cwd ?? '.'+ this.store = options.store ?? null+ this.onUsage = options.onUsage ?? null}async sendMessages({@@ -148,10 +195,14 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {start: (controller) => {const mapper = createUpdateMapper(`turn-${Date.now()}`)let closed = false+ // The reply's run collects the edits the agent's calls make in the chat's document.+ const store = this.store+ const run = store ? startAgentRun(store, session.chat) : nullfunction finish(reason: 'stop' | 'other' | 'error', errorText?: string) {if (closed) returnclosed = true+ if (store && run) endRun(store, run)if (errorText) controller.enqueue({ type: 'error', errorText })for (const chunk of mapper.end()) controller.enqueue(chunk)controller.enqueue({ type: 'finish-step' })@@ -187,7 +238,11 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {prompt: [{ type: 'text', text: promptText }]})// The prompt answers once the agent's turn is over; nothing else ends the reply.- .then((result) => finish(result.stopReason === 'end_turn' ? 'stop' : 'other'))+ .then((result) => {+ if (result.usage) this.onUsage?.(agentTurnUsage(result.usage, session.model))+ finish(result.stopReason === 'end_turn' ? 'stop' : 'other')+ return undefined+ }).catch((e) => {recordACPTransportFailure({operation: 'message',@@ -209,6 +264,7 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {this.starting = nullawait starting?.kill().catch(() => undefined)if (this.session) {+ forgetAgentChat(this.session.chat)await this.session.child.kill()this.session = null}@@ -235,23 +291,31 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {const { child, input, output } = processconst stream = ndJsonStream(input, output)let onUpdate: ACPSession['onUpdate'] = null+ // Set once the session exists; the client reads it to record the model the agent names.+ let sessionRef: ACPSession | null = nullconst clientImpl: Client = {async requestPermission(params: RequestPermissionRequest): Promise<RequestPermissionResponse> {- const { requestPermissionFromUser } = await import('@/app/ai/acp/permission')+ const { requestPermissionFromUser } = await import('@/app/ai/agents/acp/permission')return requestPermissionFromUser(params)},async sessionUpdate(params: SessionNotification): Promise<void> {+ // Claude's adapter names its model only in its usage updates.+ const { update } = params+ if (update.sessionUpdate === 'usage_update') {+ const meta = v.safeParse(usageMetaSchema, update._meta)+ if (meta.success && sessionRef) sessionRef.model = meta.output['_claude/model']+ }onUpdate?.(params)},extNotification: async (method, params) => {const status = parseAuthStatusUpdate(method, params)if (!status) return- const { agentAccounts } = await import('@/app/ai/agents/accounts')+ const { agentAccounts } = await import('@/app/ai/agents/setup/accounts')agentAccounts.report(this.agentDef.id, status)}}@@ -334,8 +398,10 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {const session: ACPSession = {connection,sessionId: sessionResult.sessionId,+ chat: tools.chat,child,dead: false,+ model: sessionResult.models?.currentModelId ?? null,get onUpdate() {return onUpdate},@@ -344,6 +410,7 @@ export class ACPChatTransport implements ChatTransport<UIMessage> {}}+ sessionRef = sessionreturn session}}diff --git a/src/app/ai/harness/transport.ts b/src/app/ai/transports/pi.tssimilarity index 78%rename from src/app/ai/harness/transport.tsrename to src/app/ai/transports/pi.tsindex af3e2078b..d9a1d76ce 100644--- a/src/app/ai/harness/transport.ts+++ b/src/app/ai/transports/pi.ts@@ -3,18 +3,18 @@ import type { ChatTransport, UIMessage, UIMessageChunk } from 'ai'import type {HarnessSessionConfiguration,HarnessSidecarMessage,- HarnessTurnEvent+ HarnessTurnEvent,+ HarnessTurnUsage} from '@open-pencil/harness'-import { spawnHarnessProcess, type HarnessProcess } from './process'+import { spawnHarnessProcess, type HarnessProcess } from '@/app/ai/agents/pi/process'+import { createReplyStream, type ReplyStream } from '@/app/ai/reply/stream'interface PendingRequest {controller?: ReadableStreamDefaultController<UIMessageChunk>resolve: (message: HarnessSidecarMessage) => voidreject: (error: Error) => void- textId: string- textStarted: boolean- reasoningStarted: boolean+ stream: ReplyStream}function requestID(): string {@@ -30,6 +30,16 @@ function emit(pending: PendingRequest, ...chunks: UIMessageChunk[]): void {for (const chunk of chunks) pending.controller?.enqueue(chunk)}+/** Closes the reply's open text or thought, then finishes it. */+function finishReply(pending: PendingRequest): void {+ emit(+ pending,+ ...pending.stream.end(),+ { type: 'finish-step' },+ { type: 'finish', finishReason: 'stop' }+ )+}+/** Ends a reply's stream, once; later events for its turn go nowhere. */function close(pending: PendingRequest): void {const { controller } = pending@@ -37,40 +47,21 @@ function close(pending: PendingRequest): void {controller?.close()}-function mapEvent(event: HarnessTurnEvent, pending: PendingRequest): UIMessageChunk[] {- const chunks: UIMessageChunk[] = []- if (event.type === 'text-delta') {- if (!pending.textStarted) {- chunks.push({ type: 'text-start', id: pending.textId })- pending.textStarted = true- }- chunks.push({ type: 'text-delta', id: pending.textId, delta: event.text })- } else if (event.type === 'reasoning-delta') {- const id = `reasoning-${pending.textId}`- if (!pending.reasoningStarted) {- chunks.push({ type: 'reasoning-start', id })- pending.reasoningStarted = true- }- chunks.push({ type: 'reasoning-delta', id, delta: event.text })- } else if (event.type === 'tool-call') {- chunks.push({- type: 'tool-input-available',- toolCallId: event.toolCallId,- toolName: event.toolName,- input: event.input,- providerExecuted: true- })- } else if (event.type === 'tool-result') {- chunks.push({- type: 'tool-output-available',- toolCallId: event.toolCallId,- output: event.output,- providerExecuted: true- })- } else if (event.type === 'error') {- chunks.push({ type: 'error', errorText: event.message })+function mapEvent(event: HarnessTurnEvent, { stream }: PendingRequest): UIMessageChunk[] {+ switch (event.type) {+ case 'text-delta':+ return stream.text(event.text)+ case 'reasoning-delta':+ return stream.thought(event.text)+ case 'tool-call':+ return stream.toolInput({ id: event.toolCallId, name: event.toolName }, event.input)+ case 'tool-result':+ return stream.toolResult(event.toolCallId, event.output)+ case 'error':+ return [{ type: 'error', errorText: event.message }]+ default:+ return []}- return chunks}export class HarnessChatTransport implements ChatTransport<UIMessage> {@@ -83,7 +74,9 @@ export class HarnessChatTransport implements ChatTransport<UIMessage> {private readonly sessionId: string,private readonly configuration: HarnessSessionConfiguration,private readonly environment: Record<string, string>,- private readonly spawnProcess: typeof spawnHarnessProcess = spawnHarnessProcess+ private readonly spawnProcess: typeof spawnHarnessProcess = spawnHarnessProcess,+ /** Told each turn's tokens, which the Usage settings count with the chat's other models. */+ private readonly onUsage?: (usage: HarnessTurnUsage) => void) {}async sendMessages({@@ -124,7 +117,7 @@ export class HarnessChatTransport implements ChatTransport<UIMessage> {pending.controller = controlleremit(pending, { type: 'start' }, { type: 'start-step' })if (abortSignal?.aborted) {- emit(pending, { type: 'finish-step' }, { type: 'finish', finishReason: 'stop' })+ finishReply(pending)close(pending)return}@@ -135,7 +128,7 @@ export class HarnessChatTransport implements ChatTransport<UIMessage> {// A turn already answered has nothing to stop, and a cancel now would hit the next one.if (!this.pending.has(requestId)) returncancel()- emit(pending, { type: 'finish-step' }, { type: 'finish', finishReason: 'stop' })+ finishReply(pending)close(pending)},{ once: true }@@ -200,9 +193,7 @@ export class HarnessChatTransport implements ChatTransport<UIMessage> {return {resolve: () => undefined,reject: () => undefined,- textId: `text-${id}`,- textStarted: false,- reasoningStarted: false+ stream: createReplyStream(`turn-${id}`)}}@@ -216,9 +207,7 @@ export class HarnessChatTransport implements ChatTransport<UIMessage> {this.pending.set(id, {resolve,reject,- textId: `text-${id}`,- textStarted: false,- reasoningStarted: false+ stream: createReplyStream(`turn-${id}`)})void process.send({ id, ...request }).catch(reject)})@@ -246,6 +235,9 @@ export class HarnessChatTransport implements ChatTransport<UIMessage> {if (message.type === 'turn.event') {const pending = this.pending.get(message.id)if (pending) emit(pending, ...mapEvent(message.event, pending))+ if (pending && message.event.type === 'finish' && message.event.usage) {+ this.onUsage?.(message.event.usage)+ }} else {const pending = this.pending.get(message.id)if (pending) {@@ -255,11 +247,7 @@ export class HarnessChatTransport implements ChatTransport<UIMessage> {emit(pending, { type: 'error', errorText: error.message })pending.reject(error)} else {- if (pending.reasoningStarted) {- emit(pending, { type: 'reasoning-end', id: `reasoning-${pending.textId}` })- }- if (pending.textStarted) emit(pending, { type: 'text-end', id: pending.textId })- emit(pending, { type: 'finish-step' }, { type: 'finish', finishReason: 'stop' })+ finishReply(pending)pending.resolve(message)}close(pending)diff --git a/src/app/ai/transports/tool-loop.ts b/src/app/ai/transports/tool-loop.tsnew file mode 100644index 000000000..70cdcf50f--- /dev/null+++ b/src/app/ai/transports/tool-loop.ts@@ -0,0 +1,201 @@+import { useEventListener } from '@vueuse/core'+import { createUIMessageStream, DirectChatTransport, stepCountIs, ToolLoopAgent } from 'ai'+import type { ChatTransport, LanguageModel, ToolExecutionOptions, UIMessage } from 'ai'++import type { AIProviderID, ReasoningEffort } from '@open-pencil/core/constants'++import { resumableTransport } from '@/app/ai/chat/history/continuation'+import { maxAgentSteps } from '@/app/ai/chat/preferences'+import SYSTEM_PROMPT from '@/app/ai/chat/system-prompt'+import type { RunRecorder, RunRecording } from '@/app/ai/chat/trace/recorder'+import { reasoningCallSettings, type AIProviderOptions } from '@/app/ai/models/reasoning/settings'+import type { ThinkingLevel } from '@/app/ai/models/types'+import { createRunPreview } from '@/app/ai/preview/run'+import { createAITools, currentRun, endRun, recordStep, startRun } from '@/app/ai/tools'+import { enabledAIToolDefinitions } from '@/app/ai/tools/catalog'+import { aiToolOverrides } from '@/app/ai/tools/preferences'+import { recordModelStepCompleted } from '@/app/diagnostics/events'+import type { AIDiagnosticContext } from '@/app/diagnostics/events/ai'+import type { getActiveEditorStore } from '@/app/editor/active-store'++type EditorStore = ReturnType<typeof getActiveEditorStore>++export type ToolLoopTransportOptions = {+ store: EditorStore+ providerID: AIProviderID+ model: LanguageModel+ effectiveModelID: string+ minReasoningEffort?: ReasoningEffort+ maxOutputTokens: number+ /** Read per request, so the composer's level applies to the next message. */+ thinkingLevel: () => ThinkingLevel+ onError?: (error: unknown) => void+ diagnosticContext?: AIDiagnosticContext+ /** Records each run so a saved trace can rebuild its requests. */+ recorder?: RunRecorder+}++const ANTHROPIC_CACHE_CONTROL = {+ anthropic: { cacheControl: { type: 'ephemeral' } }+} as const++function supportsAnthropicCaching(providerID: AIProviderID, modelID: string): boolean {+ return (+ providerID === 'anthropic' ||+ providerID === 'anthropic-compatible' ||+ (providerID === 'openrouter' && modelID.startsWith('anthropic/'))+ )+}++function mergeProviderOptions(+ cacheOptions: typeof ANTHROPIC_CACHE_CONTROL | undefined,+ reasoningOptions: AIProviderOptions | undefined+): AIProviderOptions | undefined {+ if (!cacheOptions && !reasoningOptions) return undefined+ return { ...cacheOptions, ...reasoningOptions }+}++function callSettings(+ providerID: AIProviderID,+ cacheOptions: typeof ANTHROPIC_CACHE_CONTROL | undefined,+ thinkingLevel: ThinkingLevel,+ minReasoningEffort: ReasoningEffort | undefined+) {+ const { reasoning, providerOptions } = reasoningCallSettings(+ providerID,+ thinkingLevel,+ minReasoningEffort+ )+ return { reasoning, providerOptions: mergeProviderOptions(cacheOptions, providerOptions) }+}++export function createToolLoopTransport({+ store,+ providerID,+ model,+ effectiveModelID,+ minReasoningEffort,+ maxOutputTokens,+ thinkingLevel,+ onError,+ diagnosticContext = {},+ recorder+}: ToolLoopTransportOptions) {+ const tools = createAITools(store, diagnosticContext)+ // The reply in progress; a transport sends one message at a time.+ let run = currentRun(store)+ // While JSX streams, the chat's agent moves through the elements as they appear, here and+ // on the screens of everyone else in the room.+ const preview = createRunPreview(store)+ const renderTool = tools.render+ renderTool.onInputStart = ({ toolCallId, abortSignal }) => preview.start(toolCallId, abortSignal)+ renderTool.onInputDelta = ({ toolCallId, inputTextDelta }) =>+ preview.delta(toolCallId, inputTextDelta)+ renderTool.onInputAvailable = ({ toolCallId }: ToolExecutionOptions<unknown>) =>+ preview.finish(toolCallId)+ const cacheProviderOptions = supportsAnthropicCaching(providerID, effectiveModelID)+ ? ANTHROPIC_CACHE_CONTROL+ : undefined+ let recording: RunRecording | undefined+ const agent = new ToolLoopAgent({+ model,+ instructions: SYSTEM_PROMPT,+ tools,+ maxOutputTokens,+ // Kept only to fingerprint each step's request for its trace.+ include: { requestMessages: recorder !== undefined },+ prepareCall: (options) => {+ const enabledNames = new Set(+ enabledAIToolDefinitions(aiToolOverrides.value).map((tool) => tool.name)+ )+ preview.clear()+ // Keep the full catalog for validating history; offer only enabled tools to this request.+ const offered = Object.fromEntries(+ Object.entries(tools).filter(([name]) => enabledNames.has(name))+ )+ recording?.offer(offered)+ return {+ ...options,+ stopWhen: stepCountIs(currentRun(store).maxSteps),+ tools: offered,+ maxOutputTokens,+ ...callSettings(providerID, cacheProviderOptions, thinkingLevel(), minReasoningEffort)+ }+ },+ onFinish: () => {+ preview.clear()+ endRun(store, run)+ recording?.end('completed')+ },+ onStepFinish: (step) => {+ const { usage } = step+ preview.clear()+ recordStep(store)+ recording?.step(step)+ recordModelStepCompleted(+ {+ provider: providerID,+ model: effectiveModelID,+ inputTokens: usage.inputTokens ?? null,+ outputTokens: usage.outputTokens ?? null,+ cacheReadTokens: usage.inputTokenDetails.cacheReadTokens ?? null,+ cacheWriteTokens: usage.inputTokenDetails.cacheWriteTokens ?? null+ },+ diagnosticContext+ )+ }+ })++ function handleError(error: unknown): string {+ preview.clear()+ endRun(store, run)+ recording?.fail(error)+ onError?.(error)+ return 'The provider rejected the request.'+ }+ const transport = new DirectChatTransport({+ agent,+ onError: handleError+ }) as ChatTransport<UIMessage>+ return resumableTransport({+ reconnectToStream: (options) => transport.reconnectToStream(options),+ async sendMessages(options) {+ // The run starts as the message is sent, so a Stop before the model is reached ends it.+ const started = startRun(store, maxAgentSteps.value, effectiveModelID)+ run = started+ const { sessionId, runId } = diagnosticContext+ const startedRecording =+ sessionId && runId+ ? recorder?.start({+ conversationId: sessionId,+ runId,+ model: { provider: providerID, id: effectiveModelID },+ settings: {+ maxOutputTokens,+ maxSteps: started.maxSteps,+ thinking: thinkingLevel(),+ cache: cacheProviderOptions !== undefined+ },+ instructions: SYSTEM_PROMPT,+ messages: options.messages+ })+ : undefined+ recording = startedRecording+ // Stopping a reply ends the run without onFinish.+ const stop = () => {+ endRun(store, started)+ startedRecording?.end('stopped')+ }+ const { abortSignal } = options+ if (abortSignal?.aborted) stop()+ else if (abortSignal) useEventListener(abortSignal, 'abort', stop)+ // DirectChatTransport handles error chunks, but not a rejected underlying stream.+ return createUIMessageStream<UIMessage>({+ execute: async ({ writer }) => {+ writer.merge(await transport.sendMessages(options))+ },+ onError: handleError+ })+ }+ })+}diff --git a/src/app/automation/agents.ts b/src/app/automation/agents.tsindex 4c66e8507..67e63ee0c 100644--- a/src/app/automation/agents.ts+++ b/src/app/automation/agents.ts@@ -21,7 +21,10 @@ const agentSessionSchema = v.object({client: v.fallback(v.optional(v.pipe(v.string(), v.trim(), v.maxLength(MAX_NAME_LENGTH))),undefined- )+ ),+ /** The app chat whose agent made the call, and the call's id in that chat. */+ chat: v.fallback(v.optional(v.pipe(v.string(), v.regex(/^[0-9a-f]{16,64}$/))), undefined),+ call: v.fallback(v.optional(v.pipe(v.string(), v.minLength(1), v.maxLength(128))), undefined)})/** The MCP session a tool call came from, as the MCP server forwards it. */diff --git a/src/app/automation/bridge/tool-handlers.ts b/src/app/automation/bridge/tool-handlers.tsindex cf19db23a..cc01fc9d7 100644--- a/src/app/automation/bridge/tool-handlers.ts+++ b/src/app/automation/bridge/tool-handlers.ts@@ -1,28 +1,18 @@import type { FigmaAPI } from '@open-pencil/core/figma-api'-import {- ALL_TOOLS,- registerComponentCatalog,- isAtomicTool,- isToolExposed,- toolChangesDocument-} from '@open-pencil/core/tools'+import { ALL_TOOLS, registerComponentCatalog, isToolExposed } from '@open-pencil/core/tools'import type { JSONObject } from '@open-pencil/scene-graph/primitives'+import { agentReplyRun } from '@/app/ai/reply/run'+import { runEditorTool, type ReplyCall } from '@/app/ai/tools/runner'import {agentFinished,agentStarted,readAgentSession,- touchedNodeIds+ touchedNodeIds,+ type AgentSession} from '@/app/automation/agents'import { limitToSelection } from '@/app/automation/bridge/selection-scope'import type { AutomationTarget } from '@/app/automation/bridge/target'-import {- AUTOMATION_UNDO_LABEL,- automationUndoLabel,- executeAtomicEditorTool,- executeWithDocumentUndo-} from '@/app/automation/execution/editor'-import { ensureGraphFonts } from '@/app/editor/fonts'import { useLibraryService } from '@/app/libraries'type FigmaFactory = (store: AutomationTarget['store'], pageId?: string) => FigmaAPI@@ -41,7 +31,7 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {// A call from an MCP session shows as that session's agent, working where the call works.const session = readAgentSession((args as { agent?: unknown }).agent)const reply = session ? agentStarted(target.store, session, target.pageId) : 0- const response = await runTool(target, toolName, toolArgs)+ const response = await runTool(target, toolName, toolArgs, session)if (session) {agentFinished(target.store, session, {reply,@@ -53,10 +43,21 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {return { ok: true, result: response.result }}+ /**+ * An ACP chat's call during its reply belongs to the reply, as the built-in chat's calls do,+ * so the reply can revert it and the transcript marks it under the agent's own call id.+ */+ function replyOf(target: AutomationTarget, session: AgentSession | null): ReplyCall | null {+ if (session?.kind !== 'acp' || !session.call) return null+ const run = agentReplyRun(target.store, session.chat)+ return run ? { run, toolCallId: session.call } : null+ }+async function runTool(target: AutomationTarget,toolName: string,- toolArgs: Record<string, unknown>+ toolArgs: Record<string, unknown>,+ session: AgentSession | null): Promise<{ result: unknown; edited: boolean }> {const def = ALL_TOOLS.find((t) => t.name === toolName && isToolExposed(t, 'mcp'))if (!def) throw new Error(`Unknown tool: ${toolName}`)@@ -65,30 +66,13 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {libraryService.bindEditor(store)registerComponentCatalog(store.graph, libraryService)const figma = makeFigma(store, target.pageId)- let result: unknown- if (isAtomicTool(def)) {- result = await executeAtomicEditorTool(store, figma, def, toolArgs, {- label: AUTOMATION_UNDO_LABEL- })- } else if (def.mutates) {- const pageId = writtenPageId(store.graph, toolArgs) ?? figma.currentPageId- const mutate = () =>- store.runMutationWithLayout(- () => def.execute(figma, toolArgs),- pageId,- async () => {- const pageNode = store.graph.getNode(pageId)- if (pageNode) await ensureGraphFonts(store.graph, pageNode.childIds, store.renderer)- }- )- // View tools (selection, viewport, pages) leave the document and its history alone.- result = toolChangesDocument(def)- ? await executeWithDocumentUndo(store, pageId, automationUndoLabel(def.name), mutate)- : await mutate()- } else {- result = await def.execute(figma, toolArgs)- }-+ const result = await runEditorTool({+ store,+ figma,+ def,+ args: toolArgs,+ reply: replyOf(target, session)+ })if (def.mutates) {store.requestRender()store.flashNodes(extractNodeIds(result))@@ -97,26 +81,6 @@ export function createAutomationToolHandler(makeFigma: FigmaFactory) {}}-/**- * A parent or a replaced layer on another page puts the new layers there, so that page lays out,- * loads their fonts, and records the change in its history.- */-function writtenPageId(- graph: AutomationTarget['store']['graph'],- args: Record<string, unknown>-): string | null {- // As render places it: a replaced layer's parent wins over parent_id.- const nodeId = args.replace_id ?? args.parent_id- return typeof nodeId === 'string' ? pageIdOf(graph, nodeId) : null-}--function pageIdOf(graph: AutomationTarget['store']['graph'], nodeId: string): string | null {- let node = graph.getNode(nodeId)- while (node && node.type !== 'CANVAS')- node = node.parentId ? graph.getNode(node.parentId) : undefined- return node?.id ?? null-}-function extractNodeIds(result: unknown): string[] {if (!result || typeof result !== 'object') return []const obj = result as JSONObjectdiff --git a/src/app/automation/webmcp/runtime.ts b/src/app/automation/webmcp/runtime.tsindex 5fdacb081..df9abf8e1 100644--- a/src/app/automation/webmcp/runtime.ts+++ b/src/app/automation/webmcp/runtime.ts@@ -1,7 +1,7 @@+import { runEditorTool } from '@/app/ai/tools/runner'import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'import { resolveAutomationTarget } from '@/app/automation/bridge/target'import { createAutomationToolHandler } from '@/app/automation/bridge/tool-handlers'-import { executeAtomicEditorTool } from '@/app/automation/execution/editor'import type { EditorStore } from '@/app/editor/active-store'import { getTabById } from '@/app/tabs'@@ -28,17 +28,15 @@ export function startWebMCP(getStore: () => EditorStore): () => void {if (def.mutates) {return {ok: true,- result: await executeAtomicEditorTool(- target.store,- makeFigmaFromStore(target.store, target.pageId),+ result: await runEditorTool({+ store: target.store,+ figma: makeFigmaFromStore(target.store, target.pageId),def,args,- {- signal,- label: 'WebMCP',- isLive: () => getTabById(target.documentId)?.store === target.store- }- )+ source: 'WebMCP',+ signal,+ isLive: () => getTabById(target.documentId)?.store === target.store+ })}}return handleTool(target, { name: def.name, args })diff --git a/src/app/diagnostics/events/ai.ts b/src/app/diagnostics/events/ai.tsindex 17dc3f8d6..b4b6f1f8d 100644--- a/src/app/diagnostics/events/ai.ts+++ b/src/app/diagnostics/events/ai.ts@@ -11,15 +11,20 @@ import type {DiagnosticValue} from '../types'-const modelStepSchema = v.object({- provider: v.string(),- model: v.string(),+/** A model call's tokens; input counts cached tokens too, which the cache fields break out. */+export const tokenUsageSchema = v.object({inputTokens: v.nullable(v.number()),outputTokens: v.nullable(v.number()),cacheReadTokens: v.nullable(v.number()),cacheWriteTokens: v.nullable(v.number())})+const modelStepSchema = v.object({+ provider: v.string(),+ model: v.string(),+ ...tokenUsageSchema.entries+})+const chatCompletedSchema = v.object({ finishReason: v.nullable(v.string()) })const chatStoppedSchema = v.object({})const chatFailedSchema = v.object({diff --git a/src/app/integrations/mcp/link.ts b/src/app/integrations/mcp/link.tsnew file mode 100644index 000000000..e2969376f--- /dev/null+++ b/src/app/integrations/mcp/link.ts@@ -0,0 +1,56 @@+import { promiseTimeout } from '@vueuse/core'++import { randomHex } from '@open-pencil/scene-graph/random'++import { watchChatAgent } from '@/app/automation/agents'+import { mcpRuntime } from '@/app/automation/mcp/runtime'++/** How long an agent may take to reach OpenPencil's tools once its session starts. */+export const AGENT_CONNECT_TIMEOUT_MS = 20_000++/** A chat's agent, linked to OpenPencil's MCP server by the chat id its session carries. */+export interface ChatAgentLink<Servers> {+ /** The id the agent's MCP session and tool calls carry, which ties them to this chat. */+ chat: string+ /** The server entries to start the agent's session with, as the agent's protocol takes them. */+ servers: Servers+ /**+ * Waits, once the session exists, for the server to say the agent opened its MCP session:+ * true when it did, false when it did not in time, null when the server cannot tell.+ */+ connected(timeoutMs?: number): Promise<boolean | null>+ stop(): void+}++/**+ * Names a chat's agent to OpenPencil's MCP server, so the server can report when this agent+ * connects and which chat its tool calls belong to. Link before the agent's session starts: the+ * agent connects while it starts.+ */+export async function linkChatAgent<Servers>(+ buildServers: (chat: string) => Promise<Servers>+): Promise<ChatAgentLink<Servers>> {+ const chat = randomHex(16)+ // Built before watching, so a server list that fails to build leaves no chat waiting.+ const servers = await buildServers(chat)+ // An older MCP server reports no sessions, so only a current one can confirm the agent.+ const watch = mcpRuntime.agentSessionEvents ? watchChatAgent(chat) : null+ return {+ chat,+ servers,+ async connected(timeoutMs = AGENT_CONNECT_TIMEOUT_MS) {+ if (!watch) return null+ try {+ return await Promise.race([+ watch.connected.then(() => true),+ promiseTimeout(timeoutMs).then(() => false)+ ])+ } finally {+ watch.stop()+ }+ },+ stop() {+ watch?.stop()+ }+ }+}diff --git a/src/app/settings/automation.ts b/src/app/settings/automation.tsindex 384656d38..15425d381 100644--- a/src/app/settings/automation.ts+++ b/src/app/settings/automation.ts@@ -4,7 +4,7 @@ import * as v from 'valibot'import { allRules } from '@open-pencil/core/lint'import { AVAILABLE_LOCALES, locale, setLocale, type Locale } from '@open-pencil/vue'-import { agentStepLimitSchema } from '@/app/ai/chat/step-limit'+import { agentStepLimitSchema } from '@/app/ai/reply/step-limit'import { applySnappingPreferences, setDesignIssuesOnCanvas } from '@/app/settings/preferences/apply'import {ANIMATION_PREFERENCES,diff --git a/src/app/settings/preferences/store.ts b/src/app/settings/preferences/store.tsindex ad83a207b..67b07a31e 100644--- a/src/app/settings/preferences/store.ts+++ b/src/app/settings/preferences/store.ts@@ -5,7 +5,7 @@ import * as v from 'valibot'import { DEFAULT_SNAPPING_PREFERENCES, type SnappingPreferences } from '@open-pencil/core/editor'import { COMMENT_SORTS, type CommentSort } from '@open-pencil/scene-graph'-import { DEFAULT_AGENT_STEPS, resolveAgentStepLimit } from '@/app/ai/chat/step-limit'+import { DEFAULT_AGENT_STEPS, resolveAgentStepLimit } from '@/app/ai/reply/step-limit'import {DEFAULT_TOOLBAR_LAYOUT,normalizeToolbarLayout,diff --git a/src/app/usage/summarize.ts b/src/app/usage/summarize.tsindex 43975b22d..51e6f62e3 100644--- a/src/app/usage/summarize.ts+++ b/src/app/usage/summarize.ts@@ -1,11 +1,14 @@-import { sum } from 'es-toolkit'+import { groupBy, sum } from 'es-toolkit'import type { DiagnosticEvent } from '@/app/diagnostics/types'export type UsageModelSummary = {provider: stringmodel: string- requests: number+ /** Model calls: a built-in chat reply makes one per step, an agent reply one per turn. */+ steps: number+ inputTokens: number | null+ outputTokens: number | null}export type UsageSummary = {@@ -31,16 +34,21 @@ export function summarizeUsage(events: DiagnosticEvent[]): UsageSummary {const steps = events.filter((event) => event.name === 'model.step.completed')const completedRequests = events.filter((event) => event.name === 'chat.completed').lengthconst failedRequests = events.filter((event) => event.name === 'chat.failed').length- const modelCounts = new Map<string, UsageModelSummary>()-- for (const step of steps) {- const provider = String(step.attributes.provider ?? 'unknown')- const model = String(step.attributes.model ?? 'unknown')- const key = `${provider}\u0000${model}`- const current = modelCounts.get(key)- if (current) current.requests++- else modelCounts.set(key, { provider, model, requests: 1 })- }+ const byModel = groupBy(+ steps,+ (step) =>+ `${String(step.attributes.provider ?? 'unknown')}\u0000${String(step.attributes.model ?? 'unknown')}`+ )+ const models = Object.values(byModel).map((modelSteps) => {+ const first = modelSteps[0]?.attributes ?? {}+ return {+ provider: String(first.provider ?? 'unknown'),+ model: String(first.model ?? 'unknown'),+ steps: modelSteps.length,+ inputTokens: sumAttribute(modelSteps, 'inputTokens'),+ outputTokens: sumAttribute(modelSteps, 'outputTokens')+ }+ })return {requests: completedRequests + failedRequests,@@ -54,6 +62,11 @@ export function summarizeUsage(events: DiagnosticEvent[]): UsageSummary {(event) =>event.attributes.cacheReadTokens === null && event.attributes.cacheWriteTokens === null).length,- models: [...modelCounts.values()].sort((left, right) => right.requests - left.requests)+ models: models.sort(+ (left, right) =>+ (right.inputTokens ?? 0) ++ (right.outputTokens ?? 0) -+ ((left.inputTokens ?? 0) + (left.outputTokens ?? 0))+ )}}diff --git a/src/components/chat/ACPPermissionDialog.vue b/src/components/chat/ACPPermissionDialog.vueindex a43d9a8d9..37b3dae8c 100644--- a/src/components/chat/ACPPermissionDialog.vue+++ b/src/components/chat/ACPPermissionDialog.vue@@ -13,7 +13,7 @@ import {currentPermission,rejectCurrentPermission,respondToPermission-} from '@/app/ai/acp/permission'+} from '@/app/ai/agents/acp/permission'import { AppAlertDialogRoot } from '@/components/ui/dialog'const open = computed(() => currentPermission.value !== null)diff --git a/src/components/chat/turn/ChatTurnActions.vue b/src/components/chat/turn/ChatTurnActions.vueindex 4beb608e6..9ff636ee3 100644--- a/src/components/chat/turn/ChatTurnActions.vue+++ b/src/components/chat/turn/ChatTurnActions.vue@@ -3,7 +3,7 @@ import { computed } from 'vue'import { useI18n } from '@open-pencil/vue'-import { turnEdits } from '@/app/ai/chat/turns'+import { turnEdits } from '@/app/ai/reply/turns'import AppButton from '@/components/ui/button/AppButton.vue'const {diff --git a/src/components/settings/agents/AgentSetup.vue b/src/components/settings/agents/AgentSetup.vueindex ab8972908..48e0cde03 100644--- a/src/components/settings/agents/AgentSetup.vue+++ b/src/components/settings/agents/AgentSetup.vue@@ -6,8 +6,8 @@ import { computed } from 'vue'import type { ACPAgentDef } from '@open-pencil/core/constants'import { useI18n } from '@open-pencil/vue'-import { codingAgentGuideURL, codingAgentSetupPrompt } from '@/app/ai/acp/setup-prompt'-import { agentSetupView, type AgentSetupState } from '@/app/ai/agents/setup'+import { codingAgentGuideURL, codingAgentSetupPrompt } from '@/app/ai/agents/setup/prompt'+import { agentSetupView, type AgentSetupState } from '@/app/ai/agents/setup/view'import SettingsLink from '@/components/settings/layout/SettingsLink.vue'import AppButton from '@/components/ui/button/AppButton.vue'import AppAlert from '@/components/ui/feedback/AppAlert.vue'diff --git a/src/components/settings/agents/AgentSignInProgress.vue b/src/components/settings/agents/AgentSignInProgress.vueindex 345325389..7489a8df9 100644--- a/src/components/settings/agents/AgentSignInProgress.vue+++ b/src/components/settings/agents/AgentSignInProgress.vue@@ -4,7 +4,7 @@ import { ref } from 'vue'import { useI18n } from '@open-pencil/vue'-import type { AgentAccountView } from '@/app/ai/agents/setup'+import type { AgentAccountView } from '@/app/ai/agents/setup/view'import SettingsLink from '@/components/settings/layout/SettingsLink.vue'import AppButton from '@/components/ui/button/AppButton.vue'import AppInput from '@/components/ui/input/AppInput.vue'diff --git a/src/components/settings/agents/PiSetup.vue b/src/components/settings/agents/PiSetup.vueindex 1e78f3713..d2db39c5c 100644--- a/src/components/settings/agents/PiSetup.vue+++ b/src/components/settings/agents/PiSetup.vue@@ -4,7 +4,7 @@ import { computed } from 'vue'import { useI18n } from '@open-pencil/vue'-import { piSetupView, type CompanionCheck, type PiSetupState } from '@/app/ai/agents/setup'+import { piSetupView, type CompanionCheck, type PiSetupState } from '@/app/ai/agents/setup/view'import SettingsLink from '@/components/settings/layout/SettingsLink.vue'import AppButton from '@/components/ui/button/AppButton.vue'import AppAlert from '@/components/ui/feedback/AppAlert.vue'diff --git a/src/components/settings/agents/problem.ts b/src/components/settings/agents/problem.tsindex 9b296abec..a5d454a65 100644--- a/src/components/settings/agents/problem.ts+++ b/src/components/settings/agents/problem.ts@@ -1,6 +1,6 @@import { useI18n } from '@open-pencil/vue'-import type { SetupProblem } from '@/app/ai/agents/setup'+import type { SetupProblem } from '@/app/ai/agents/setup/view'/** The warning setup shows for a problem it cannot fix on its own. */export function useSetupProblemMessage() {diff --git a/src/components/settings/ai-setup/AISetupAccess.vue b/src/components/settings/ai-setup/AISetupAccess.vueindex 4c3840f7c..c953aa9c6 100644--- a/src/components/settings/ai-setup/AISetupAccess.vue+++ b/src/components/settings/ai-setup/AISetupAccess.vue@@ -4,7 +4,7 @@ import { ref } from 'vue'import { useI18n } from '@open-pencil/vue'-import type { AgentDetection } from '@/app/ai/agents/detection'+import type { AgentDetection } from '@/app/ai/agents/setup/detection'import { modelProviderName } from '@/app/ai/models/provider-name'import {ONBOARDING_AGENTS,diff --git a/src/components/settings/ai-setup/AISetupConnection.stories.ts b/src/components/settings/ai-setup/AISetupConnection.stories.tsindex 12e7adbc2..1fa413166 100644--- a/src/components/settings/ai-setup/AISetupConnection.stories.ts+++ b/src/components/settings/ai-setup/AISetupConnection.stories.ts@@ -3,9 +3,9 @@ import { expect, within } from 'storybook/test'import { ACP_AGENTS, type ACPAgentID } from '@open-pencil/core/constants'-import type { AgentAccount } from '@/app/ai/agents/accounts'-import type { DetectedAgent } from '@/app/ai/agents/discovery'-import type { AgentSetupState, PiSetupState } from '@/app/ai/agents/setup'+import type { AgentAccount } from '@/app/ai/agents/setup/accounts'+import type { DetectedAgent } from '@/app/ai/agents/setup/discovery'+import type { AgentSetupState, PiSetupState } from '@/app/ai/agents/setup/view'import AISetupConnection from './AISetupConnection.vue'diff --git a/src/components/settings/ai-setup/AISetupConnection.vue b/src/components/settings/ai-setup/AISetupConnection.vueindex 5f544facf..73a36a262 100644--- a/src/components/settings/ai-setup/AISetupConnection.vue+++ b/src/components/settings/ai-setup/AISetupConnection.vue@@ -5,7 +5,7 @@ import { computed } from 'vue'import { ACP_AGENTS, AI_PROVIDERS } from '@open-pencil/core/constants'import { useI18n } from '@open-pencil/vue'-import type { AgentSetupState, PiSetupState } from '@/app/ai/agents/setup'+import type { AgentSetupState, PiSetupState } from '@/app/ai/agents/setup/view'import { modelProviderName } from '@/app/ai/models/provider-name'import {serverPresetFor,diff --git a/src/components/settings/chat/ChatSettingsSection.vue b/src/components/settings/chat/ChatSettingsSection.vueindex 7bc893252..13c14e04f 100644--- a/src/components/settings/chat/ChatSettingsSection.vue+++ b/src/components/settings/chat/ChatSettingsSection.vue@@ -4,7 +4,7 @@ import { computed } from 'vue'import { useI18n } from '@open-pencil/vue'import { changePreviewSize, maxAgentSteps, reasoningDisplay } from '@/app/ai/chat/preferences'-import { AGENT_STEP_LIMIT_MIN, AGENT_STEP_LIMIT_MAX } from '@/app/ai/chat/step-limit'+import { AGENT_STEP_LIMIT_MIN, AGENT_STEP_LIMIT_MAX } from '@/app/ai/reply/step-limit'import { openToolAccessSettings } from '@/app/automation/tool-access/settings/use'import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'import SettingsRow from '@/components/settings/layout/SettingsRow.vue'diff --git a/src/components/settings/mcp/MCPFailureAlert.stories.ts b/src/components/settings/mcp/MCPFailureAlert.stories.tsindex 65ee85c2a..c558b64f1 100644--- a/src/components/settings/mcp/MCPFailureAlert.stories.ts+++ b/src/components/settings/mcp/MCPFailureAlert.stories.ts@@ -1,7 +1,7 @@import type { Meta, StoryObj } from '@storybook/vue3-vite'import { expect, userEvent, within } from 'storybook/test'-import type { MCPServerSetupState } from '@/app/ai/agents/setup'+import type { MCPServerSetupState } from '@/app/ai/agents/setup/view'import {MCP_INSTALL_COMMAND,type MCPFailure,diff --git a/src/components/settings/mcp/MCPFailureAlert.vue b/src/components/settings/mcp/MCPFailureAlert.vueindex eff475cc3..d0ba0b9e4 100644--- a/src/components/settings/mcp/MCPFailureAlert.vue+++ b/src/components/settings/mcp/MCPFailureAlert.vue@@ -5,7 +5,7 @@ import { computed, ref } from 'vue'import { useAutomationMessages, useI18n } from '@open-pencil/vue'-import { mcpServerSetupView, type MCPServerSetupState } from '@/app/ai/agents/setup'+import { mcpServerSetupView, type MCPServerSetupState } from '@/app/ai/agents/setup/view'import {restartFixesMCPFailure,type MCPFailure,diff --git a/src/components/settings/mcp/MCPSettingsPanel.vue b/src/components/settings/mcp/MCPSettingsPanel.vueindex b9a08e53f..f2fa1a51b 100644--- a/src/components/settings/mcp/MCPSettingsPanel.vue+++ b/src/components/settings/mcp/MCPSettingsPanel.vue@@ -8,7 +8,7 @@ import {useSettingsMessages} from '@open-pencil/vue'-import { useMCPServerSetup } from '@/app/ai/agents/setup'+import { useMCPServerSetup } from '@/app/ai/agents/setup/use'import { restartFixesMCPFailure } from '@/app/automation/mcp/failure'import {mcpAuthenticationEnabled,diff --git a/src/components/settings/models/ProfileEditor.vue b/src/components/settings/models/ProfileEditor.vueindex 556d67119..883ed559d 100644--- a/src/components/settings/models/ProfileEditor.vue+++ b/src/components/settings/models/ProfileEditor.vue@@ -4,7 +4,7 @@ import { computed, ref, useTemplateRef } from 'vue'import type { AIProviderID } from '@open-pencil/core/constants'import { useI18n } from '@open-pencil/vue'-import { usePiSetup } from '@/app/ai/agents/setup'+import { usePiSetup } from '@/app/ai/agents/setup/use'import { useModelProfileFeedback } from '@/app/ai/models/settings/profile-editor/feedback'import { useModelProfileEditor } from '@/app/ai/models/settings/profile-editor/use'import { thinkingLevelOptions as buildThinkingLevelOptions } from '@/app/ai/models/thinking'diff --git a/src/components/settings/provider/ProviderConnectionTestButton.vue b/src/components/settings/provider/ProviderConnectionTestButton.vueindex 17d69a843..e638debfd 100644--- a/src/components/settings/provider/ProviderConnectionTestButton.vue+++ b/src/components/settings/provider/ProviderConnectionTestButton.vue@@ -4,7 +4,7 @@ import { computed } from 'vue'import { useI18n } from '@open-pencil/vue'-import type { ProviderConnectionTestFailureReason } from '@/app/ai/chat/connection-test'+import type { ProviderConnectionTestFailureReason } from '@/app/ai/models/connection-test'import AppButton from '@/components/ui/button/AppButton.vue'import statusTheme from '@/theme/feedback/status'diff --git a/src/components/settings/usage/UsageSettingsPanel.vue b/src/components/settings/usage/UsageSettingsPanel.vueindex 56623e1ca..eb1c6962a 100644--- a/src/components/settings/usage/UsageSettingsPanel.vue+++ b/src/components/settings/usage/UsageSettingsPanel.vue@@ -1,4 +1,6 @@<script setup lang="ts">+import { computed } from 'vue'+import { useI18n } from '@open-pencil/vue'import { useUsageSettings } from '@/app/usage/settings/use'@@ -11,6 +13,19 @@ function formatTokenValue(value: number | null): string {}const { summary } = useUsageSettings()++const totals = computed(() => {+ const messages = diagnosticMessages.value+ const current = summary.value+ return [+ { label: messages.usageRequests, value: current.requests.toLocaleString() },+ { label: messages.usageCompleted, value: current.completedRequests.toLocaleString() },+ { label: messages.usageInputTokens, value: formatTokenValue(current.inputTokens) },+ { label: messages.usageOutputTokens, value: formatTokenValue(current.outputTokens) },+ { label: messages.usageCachedInputTokens, value: formatTokenValue(current.cacheReadTokens) },+ { label: messages.usageCacheWriteTokens, value: formatTokenValue(current.cacheWriteTokens) }+ ]+})</script><template>@@ -19,25 +34,9 @@ const { summary } = useUsageSettings()<template #description>{{ diagnosticMessages.usageDescription }}</template><div class="grid grid-cols-2 gap-2">- <div class="rounded border border-border p-3">- <div class="text-[10px] text-muted">{{ diagnosticMessages.usageRequests }}</div>- <div class="mt-1 text-sm font-semibold text-surface">{{ summary.requests }}</div>- </div>- <div class="rounded border border-border p-3">- <div class="text-[10px] text-muted">{{ diagnosticMessages.usageCompleted }}</div>- <div class="mt-1 text-sm font-semibold text-surface">{{ summary.completedRequests }}</div>- </div>- <div class="rounded border border-border p-3">- <div class="text-[10px] text-muted">{{ diagnosticMessages.usageInputTokens }}</div>- <div class="mt-1 text-sm font-semibold text-surface">- {{ formatTokenValue(summary.inputTokens) }}- </div>- </div>- <div class="rounded border border-border p-3">- <div class="text-[10px] text-muted">{{ diagnosticMessages.usageOutputTokens }}</div>- <div class="mt-1 text-sm font-semibold text-surface">- {{ formatTokenValue(summary.outputTokens) }}- </div>+ <div v-for="total in totals" :key="total.label" class="rounded border border-border p-3">+ <div class="text-[10px] text-muted">{{ total.label }}</div>+ <div class="mt-1 text-sm font-semibold text-surface">{{ total.value }}</div></div></div>@@ -49,10 +48,17 @@ const { summary } = useUsageSettings()<divv-for="model in summary.models":key="`${model.provider}-${model.model}`"- class="flex justify-between text-[11px]"+ class="flex justify-between gap-3 text-[11px]">- <span class="text-muted">{{ model.provider }} · {{ model.model }}</span>- <span class="text-surface">{{ model.requests }}</span>+ <span class="min-w-0 truncate text-muted">{{ model.provider }} · {{ model.model }}</span>+ <span class="shrink-0 text-surface tabular-nums">+ {{+ diagnosticMessages.modelStepTokens({+ input: formatTokenValue(model.inputTokens),+ output: formatTokenValue(model.outputTokens)+ })+ }}+ </span></div></div>diff --git a/tests/app/ai/acp/auth/session.test.ts b/tests/app/ai/agents/acp/auth/session.test.tssimilarity index 98%rename from tests/app/ai/acp/auth/session.test.tsrename to tests/app/ai/agents/acp/auth/session.test.tsindex 4dc4915ac..d1d0c0241 100644--- a/tests/app/ai/acp/auth/session.test.ts+++ b/tests/app/ai/agents/acp/auth/session.test.ts@@ -16,9 +16,9 @@ import {signInWithAgent,type AgentStreams,type ToolsProbe-} from '@/app/ai/acp/auth/session'-import { AUTH_STATUS_UPDATE_METHOD, type AgentAuthStatus } from '@/app/ai/acp/auth/status'-import type { OwnToolsOutcome } from '@/app/ai/acp/own-tools'+} from '@/app/ai/agents/acp/auth/session'+import { AUTH_STATUS_UPDATE_METHOD, type AgentAuthStatus } from '@/app/ai/agents/acp/auth/status'+import type { OwnToolsOutcome } from '@/app/ai/agents/acp/tools'import { createDeferred } from '@/app/runtime/deferred'import { expectDefined } from '#tests/helpers/assert'@@ -183,6 +183,7 @@ function toolsProbe(outcome: OwnToolsOutcome) {link: async () => {linked.push('link')return {+ chat: '0123456789abcdef',mcpServers: [{ type: 'http', name: 'open-pencil', url: 'http://127.0.0.1:7600/mcp', headers: [] }],diff --git a/tests/app/ai/acp/auth/status.test.ts b/tests/app/ai/agents/acp/auth/status.test.tssimilarity index 88%rename from tests/app/ai/acp/auth/status.test.tsrename to tests/app/ai/agents/acp/auth/status.test.tsindex 1e8df3a2d..91f131238 100644--- a/tests/app/ai/acp/auth/status.test.ts+++ b/tests/app/ai/agents/acp/auth/status.test.ts@@ -1,6 +1,10 @@import { expect, test } from 'bun:test'-import { isSignedIn, parseAuthStatusUpdate, type AgentAuthStatus } from '@/app/ai/acp/auth/status'+import {+ isSignedIn,+ parseAuthStatusUpdate,+ type AgentAuthStatus+} from '@/app/ai/agents/acp/auth/status'test('reads the login from an auth status update and nothing else', () => {const status: AgentAuthStatus = {diff --git a/tests/app/ai/acp/auth/terminal.test.ts b/tests/app/ai/agents/acp/auth/terminal.test.tssimilarity index 96%rename from tests/app/ai/acp/auth/terminal.test.tsrename to tests/app/ai/agents/acp/auth/terminal.test.tsindex 3759cc7b7..9a922d606 100644--- a/tests/app/ai/acp/auth/terminal.test.ts+++ b/tests/app/ai/agents/acp/auth/terminal.test.ts@@ -2,7 +2,11 @@ import { afterEach, describe, expect, test } from 'bun:test'import { ACP_AGENTS } from '@open-pencil/core/constants'-import { findSignInURL, startTerminalSignIn, stripTerminalCodes } from '@/app/ai/acp/auth/terminal'+import {+ findSignInURL,+ startTerminalSignIn,+ stripTerminalCodes+} from '@/app/ai/agents/acp/auth/terminal'import { expectDefined } from '#tests/helpers/assert'import { clearTauriMocks, mockTauriIPC } from '#tests/helpers/tauri/mocks'diff --git a/tests/app/ai/harness/pi-settings.test.ts b/tests/app/ai/agents/pi/settings.test.tssimilarity index 90%rename from tests/app/ai/harness/pi-settings.test.tsrename to tests/app/ai/agents/pi/settings.test.tsindex 392123e5b..e4d9d496d 100644--- a/tests/app/ai/harness/pi-settings.test.ts+++ b/tests/app/ai/agents/pi/settings.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from 'bun:test'-import { parsePiSettings } from '@/app/ai/harness/pi-settings'+import { parsePiSettings } from '@/app/ai/agents/pi/settings'describe('parsePiSettings', () => {test('reads the default model', () => {diff --git a/tests/app/ai/agents/accounts.test.ts b/tests/app/ai/agents/setup/accounts.test.tssimilarity index 96%rename from tests/app/ai/agents/accounts.test.tsrename to tests/app/ai/agents/setup/accounts.test.tsindex 76da20e01..688275c1e 100644--- a/tests/app/ai/agents/accounts.test.ts+++ b/tests/app/ai/agents/setup/accounts.test.ts@@ -2,10 +2,10 @@ import { describe, expect, mock, test } from 'bun:test'import { ACP_AGENTS, type ACPAgentDef } from '@open-pencil/core/constants'-import type { AgentAuthCheck } from '@/app/ai/acp/auth/session'-import type { AgentAuthStatus } from '@/app/ai/acp/auth/status'-import type { TerminalSignIn } from '@/app/ai/acp/auth/terminal'-import { createAgentAccounts } from '@/app/ai/agents/accounts'+import type { AgentAuthCheck } from '@/app/ai/agents/acp/auth/session'+import type { AgentAuthStatus } from '@/app/ai/agents/acp/auth/status'+import type { TerminalSignIn } from '@/app/ai/agents/acp/auth/terminal'+import { createAgentAccounts } from '@/app/ai/agents/setup/accounts'import { createDeferred } from '@/app/runtime/deferred'import { expectDefined } from '#tests/helpers/assert'diff --git a/tests/app/ai/agents/companions.test.ts b/tests/app/ai/agents/setup/companions.test.tssimilarity index 97%rename from tests/app/ai/agents/companions.test.tsrename to tests/app/ai/agents/setup/companions.test.tsindex c53270111..0fae8eccd 100644--- a/tests/app/ai/agents/companions.test.ts+++ b/tests/app/ai/agents/setup/companions.test.ts@@ -4,7 +4,7 @@ import {companionPackageManager,globalInstallCommand,isOutdatedCompanion-} from '@/app/ai/agents/companions'+} from '@/app/ai/agents/setup/companions'describe('isOutdatedCompanion', () => {test('requires the app’s major and minor version', () => {diff --git a/tests/app/ai/agents/detection.test.ts b/tests/app/ai/agents/setup/detection.test.tssimilarity index 95%rename from tests/app/ai/agents/detection.test.tsrename to tests/app/ai/agents/setup/detection.test.tsindex 739bfc0aa..b48988f1e 100644--- a/tests/app/ai/agents/detection.test.ts+++ b/tests/app/ai/agents/setup/detection.test.ts@@ -2,10 +2,10 @@ import { describe, expect, test } from 'bun:test'import { ACP_AGENTS } from '@open-pencil/core/constants'-import type { AgentAccount } from '@/app/ai/agents/accounts'-import { codingAgentDetection, piDetection } from '@/app/ai/agents/detection'-import type { DetectedAgent } from '@/app/ai/agents/discovery'-import type { AgentSetupState, PiSetupState } from '@/app/ai/agents/setup'+import type { AgentAccount } from '@/app/ai/agents/setup/accounts'+import { codingAgentDetection, piDetection } from '@/app/ai/agents/setup/detection'+import type { DetectedAgent } from '@/app/ai/agents/setup/discovery'+import type { AgentSetupState, PiSetupState } from '@/app/ai/agents/setup/view'import { expectDefined } from '#tests/helpers/assert'diff --git a/tests/app/ai/agents/discovery.test.ts b/tests/app/ai/agents/setup/discovery.test.tssimilarity index 99%rename from tests/app/ai/agents/discovery.test.tsrename to tests/app/ai/agents/setup/discovery.test.tsindex 0e02086f1..405e09e96 100644--- a/tests/app/ai/agents/discovery.test.ts+++ b/tests/app/ai/agents/setup/discovery.test.ts@@ -2,8 +2,8 @@ import { describe, expect, test, mock } from 'bun:test'import type { ACPAgentDef } from '@open-pencil/core/constants'-import { createAgentDiscovery, detectedAgents } from '@/app/ai/agents/discovery'-import type { AgentLookup } from '@/app/ai/agents/native'+import { createAgentDiscovery, detectedAgents } from '@/app/ai/agents/setup/discovery'+import type { AgentLookup } from '@/app/ai/agents/setup/native'import { createDeferred } from '@/app/runtime/deferred'// Installed companions report the version of the app under test, as matching ones do.diff --git a/tests/app/ai/agents/native.test.ts b/tests/app/ai/agents/setup/native.test.tssimilarity index 99%rename from tests/app/ai/agents/native.test.tsrename to tests/app/ai/agents/setup/native.test.tsindex 07e8b91ed..6f41fa4fd 100644--- a/tests/app/ai/agents/native.test.ts+++ b/tests/app/ai/agents/setup/native.test.ts@@ -4,7 +4,7 @@ import type { Channel } from '@tauri-apps/api/core'import { ACP_AGENTS } from '@open-pencil/core/constants'-import { installAgentAdapter, lookupAgents } from '@/app/ai/agents/native'+import { installAgentAdapter, lookupAgents } from '@/app/ai/agents/setup/native'import { createDeferred } from '@/app/runtime/deferred'import { expectDefined } from '#tests/helpers/assert'diff --git a/tests/app/ai/agents/readiness.test.ts b/tests/app/ai/agents/setup/readiness.test.tssimilarity index 92%rename from tests/app/ai/agents/readiness.test.tsrename to tests/app/ai/agents/setup/readiness.test.tsindex aca41eafb..9f8497d00 100644--- a/tests/app/ai/agents/readiness.test.ts+++ b/tests/app/ai/agents/setup/readiness.test.ts@@ -1,8 +1,8 @@import { describe, expect, test } from 'bun:test'-import { createAgentDiscovery } from '@/app/ai/agents/discovery'-import type { AgentLookup } from '@/app/ai/agents/native'-import { AgentSetupError, assertAgentReady } from '@/app/ai/agents/readiness'+import { createAgentDiscovery } from '@/app/ai/agents/setup/discovery'+import type { AgentLookup } from '@/app/ai/agents/setup/native'+import { AgentSetupError, assertAgentReady } from '@/app/ai/agents/setup/readiness'function discovery(lookup: () => Promise<AgentLookup>, enabled = true) {return createAgentDiscovery({ enabled, lookup, install: async () => undefined })diff --git a/tests/app/ai/agents/setup.test.ts b/tests/app/ai/agents/setup/use.test.tssimilarity index 98%rename from tests/app/ai/agents/setup.test.tsrename to tests/app/ai/agents/setup/use.test.tsindex da662417d..32392cae6 100644--- a/tests/app/ai/agents/setup.test.ts+++ b/tests/app/ai/agents/setup/use.test.ts@@ -4,20 +4,18 @@ import { nextTick, ref } from 'vue'import { ACP_AGENTS, type ACPAgentDef } from '@open-pencil/core/constants'-import { createAgentAccounts, type AgentAccount } from '@/app/ai/agents/accounts'-import { createAgentDiscovery, type DetectedAgent } from '@/app/ai/agents/discovery'-import type { AgentLookup } from '@/app/ai/agents/native'+import { createAgentAccounts, type AgentAccount } from '@/app/ai/agents/setup/accounts'+import { createAgentDiscovery, type DetectedAgent } from '@/app/ai/agents/setup/discovery'+import type { AgentLookup } from '@/app/ai/agents/setup/native'+import { useAgentSetup, useMCPServerSetup, usePiSetup } from '@/app/ai/agents/setup/use'import {agentSetupView,mcpServerSetupView,piSetupView,- useAgentSetup,- useMCPServerSetup,- usePiSetup,type AgentSetupState,type MCPServerSetupState,type PiSetupState-} from '@/app/ai/agents/setup'+} from '@/app/ai/agents/setup/view'import { MCP_INSTALL_COMMAND } from '@/app/automation/mcp/failure'function lookup(...commands: string[]): AgentLookup {diff --git a/tests/app/ai/chat/submission/use.test.ts b/tests/app/ai/chat/submission/use.test.tsindex 7878b3279..ee3367234 100644--- a/tests/app/ai/chat/submission/use.test.ts+++ b/tests/app/ai/chat/submission/use.test.ts@@ -4,7 +4,7 @@ import type { Chat } from '@ai-sdk/vue'import type { UIMessage } from 'ai'import { ref, shallowRef } from 'vue'-import { AgentSetupError } from '@/app/ai/agents/readiness'+import { AgentSetupError } from '@/app/ai/agents/setup/readiness'import { useChatSubmission } from '@/app/ai/chat/submission/use'import type { EditorStore } from '@/app/editor/active-store'diff --git a/tests/app/ai/chat/trace/rebuild.test.ts b/tests/app/ai/chat/trace/rebuild.test.tsindex 4b0383cd0..197d76b97 100644--- a/tests/app/ai/chat/trace/rebuild.test.ts+++ b/tests/app/ai/chat/trace/rebuild.test.ts@@ -9,9 +9,9 @@ import { FigmaAPI } from '@open-pencil/core/figma-api'import { matchesRecordedStep, rebuildStepMessages } from '@/app/ai/chat/trace/rebuild'import { createRunRecorder } from '@/app/ai/chat/trace/recorder'-import { createToolLoopTransport } from '@/app/ai/chat/transports'import { createAITools } from '@/app/ai/tools'import { aiToolOverrides } from '@/app/ai/tools/preferences'+import { createToolLoopTransport } from '@/app/ai/transports/tool-loop'import * as figmaFactory from '@/app/automation/bridge/figma-factory'import { createEditorStore } from '@/app/editor/session/create'diff --git a/tests/app/ai/chat/provider-models.test.ts b/tests/app/ai/models/reasoning/floors.test.tssimilarity index 98%rename from tests/app/ai/chat/provider-models.test.tsrename to tests/app/ai/models/reasoning/floors.test.tsindex 7e7bf1384..4bfe6dda7 100644--- a/tests/app/ai/chat/provider-models.test.ts+++ b/tests/app/ai/models/reasoning/floors.test.ts@@ -4,7 +4,7 @@ import {normalizeOpenRouterModel,resetOpenRouterModelsForTests,resolveProviderModel-} from '@/app/ai/chat/provider-models'+} from '@/app/ai/models/reasoning/floors'import { fetchStub } from '#tests/helpers/fetch'diff --git a/tests/app/ai/chat/reasoning.test.ts b/tests/app/ai/models/reasoning/settings.test.tssimilarity index 97%rename from tests/app/ai/chat/reasoning.test.tsrename to tests/app/ai/models/reasoning/settings.test.tsindex c693d8513..8dd651ad1 100644--- a/tests/app/ai/chat/reasoning.test.ts+++ b/tests/app/ai/models/reasoning/settings.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from 'bun:test'-import { reasoningCallSettings, runtimeReasoningSettings } from '@/app/ai/chat/reasoning'+import { reasoningCallSettings, runtimeReasoningSettings } from '@/app/ai/models/reasoning/settings'import type { DirectAIModelRuntime } from '@/app/ai/models/runtime'describe('reasoningCallSettings', () => {diff --git a/tests/app/ai/preview/run.test.ts b/tests/app/ai/preview/run.test.tsindex ab7bfcaa2..fd31d5f28 100644--- a/tests/app/ai/preview/run.test.ts+++ b/tests/app/ai/preview/run.test.ts@@ -3,7 +3,7 @@ import { afterEach, describe, expect, test } from 'bun:test'import { SceneGraph } from '@open-pencil/scene-graph'import { createRunPreview } from '@/app/ai/preview/run'-import { runAgentId, runPageId, startRun } from '@/app/ai/tools/run'+import { runAgentId, runPageId, startRun } from '@/app/ai/reply/run'import { createEditorStore } from '@/app/editor/session'import { onAgentPreview, type AgentPreviewEvent } from '@/app/presence/preview-stream'diff --git a/tests/app/ai/tools/run.test.ts b/tests/app/ai/reply/run.test.tssimilarity index 98%rename from tests/app/ai/tools/run.test.tsrename to tests/app/ai/reply/run.test.tsindex abb0faebc..07d7683b9 100644--- a/tests/app/ai/tools/run.test.ts+++ b/tests/app/ai/reply/run.test.ts@@ -7,10 +7,10 @@ import { toRaw } from 'vue'import { FigmaAPI } from '@open-pencil/core/figma-api'-import { createToolLoopTransport } from '@/app/ai/chat/transports'+import { markRunWork, runUndoEntries } from '@/app/ai/reply/run'import { currentRun, endRun, markRunPreview, runPageId, startRun } from '@/app/ai/tools'import { aiToolOverrides } from '@/app/ai/tools/preferences'-import { markRunWork, runUndoEntries } from '@/app/ai/tools/run'+import { createToolLoopTransport } from '@/app/ai/transports/tool-loop'import * as figmaFactory from '@/app/automation/bridge/figma-factory'import { createEditorStore } from '@/app/editor/session/create'import { presenceOf } from '@/app/presence/registry'diff --git a/tests/app/ai/chat/settle.test.ts b/tests/app/ai/reply/settle.test.tssimilarity index 98%rename from tests/app/ai/chat/settle.test.tsrename to tests/app/ai/reply/settle.test.tsindex e6cad1618..663168f8e 100644--- a/tests/app/ai/chat/settle.test.ts+++ b/tests/app/ai/reply/settle.test.ts@@ -4,7 +4,7 @@ import type { UIMessage } from 'ai'import { reactive, toRaw } from 'vue'import { wasStopped } from '@/app/ai/chat/metadata'-import { settleMessage } from '@/app/ai/chat/settle'+import { settleMessage } from '@/app/ai/reply/settle'function reply(parts: UIMessage['parts'], metadata?: unknown): UIMessage {return { id: 'reply', role: 'assistant', parts, metadata }diff --git a/tests/app/ai/chat/turns.test.ts b/tests/app/ai/reply/turns.test.tssimilarity index 99%rename from tests/app/ai/chat/turns.test.tsrename to tests/app/ai/reply/turns.test.tsindex 765528045..2bd4e1b06 100644--- a/tests/app/ai/chat/turns.test.ts+++ b/tests/app/ai/reply/turns.test.ts@@ -12,7 +12,7 @@ import { undoOf } from '@/app/ai/chat/metadata'import { changePreviewSize } from '@/app/ai/chat/preferences'import type { ChatInstance } from '@/app/ai/chat/submission/types'import { useChatSubmission } from '@/app/ai/chat/submission/use'-import { clearTurns, revertTurn, turnEdits, undoToReport } from '@/app/ai/chat/turns'+import { clearTurns, revertTurn, turnEdits, undoToReport } from '@/app/ai/reply/turns'import { createAITools, endRun, startRun } from '@/app/ai/tools'import * as figmaFactory from '@/app/automation/bridge/figma-factory'import { createEditorStore } from '@/app/editor/session/create'diff --git a/tests/app/ai/tools/runner.test.ts b/tests/app/ai/tools/runner.test.tsnew file mode 100644index 000000000..975c25569--- /dev/null+++ b/tests/app/ai/tools/runner.test.ts@@ -0,0 +1,59 @@+import 'fake-indexeddb/auto'+import { afterEach, beforeEach, expect, test } from 'bun:test'++import { ALL_TOOLS } from '@open-pencil/core/tools'+import { SceneGraph } from '@open-pencil/scene-graph'++import { runEditorTool } from '@/app/ai/tools/runner'+import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'+import { createEditorStore, type EditorStore } from '@/app/editor/session/create'+import { createDeferred } from '@/app/runtime/deferred'++import { expectDefined } from '#tests/helpers/assert'++let store: EditorStore++beforeEach(() => {+ // The automation FigmaAPI reads the viewport size from the window.+ Object.assign(globalThis, { window: { innerWidth: 1024, innerHeight: 768 } })+ store = createEditorStore(new SceneGraph())+})++afterEach(() => {+ store.dispose()+ Reflect.deleteProperty(globalThis, 'window')+})++test('a call cancelled while it waits for its turn edits nothing', async () => {+ const createShape = expectDefined(+ ALL_TOOLS.find((tool) => tool.name === 'create_shape'),+ 'create_shape'+ )+ const pageId = store.state.currentPageId+ const figma = makeFigmaFromStore(store, pageId)+ // A first edit holds the document's lock until the test lets it finish.+ const held = createDeferred<undefined>()+ const first = runEditorTool({+ store,+ figma,+ def: { ...createShape, execute: () => held.promise },+ args: {},+ source: 'WebMCP'+ })+ const cancel = new AbortController()+ const queued = runEditorTool({+ store,+ figma,+ def: createShape,+ args: { type: 'RECTANGLE', x: 0, y: 0, width: 40, height: 20 },+ source: 'WebMCP',+ signal: cancel.signal+ })+ cancel.abort()+ held.resolve(undefined)++ await first+ await expect(queued).rejects.toThrow()+ expect(store.graph.getChildren(pageId)).toEqual([])+ expect(store.undo.peekUndo()).toBeUndefined()+})diff --git a/tests/app/ai/harness/transport.test.ts b/tests/app/ai/transports/pi.test.tssimilarity index 72%rename from tests/app/ai/harness/transport.test.tsrename to tests/app/ai/transports/pi.test.tsindex ed8a6f1aa..82b7909d6 100644--- a/tests/app/ai/harness/transport.test.ts+++ b/tests/app/ai/transports/pi.test.ts@@ -1,8 +1,12 @@import { expect, test } from 'bun:test'-import type { HarnessSidecarMessage } from '@open-pencil/harness'+import type {+ HarnessSidecarMessage,+ HarnessTurnEvent,+ HarnessTurnUsage+} from '@open-pencil/harness'-import { HarnessChatTransport } from '@/app/ai/harness/transport'+import { HarnessChatTransport } from '@/app/ai/transports/pi'test('failed session stop kills the process without deleting resume state', async () => {let output: ReadableStreamDefaultController<HarnessSidecarMessage> | undefined@@ -117,8 +121,16 @@ function fakeCompanion({ turnsFail = false } = {}) {/** The turn's next event or its final answer, as the companion would send it. */text: (turn: string, text: string) =>output?.enqueue({ type: 'turn.event', id: turn, event: { type: 'text-delta', text } }),+ event: (turn: string, event: HarnessTurnEvent) =>+ output?.enqueue({ type: 'turn.event', id: turn, event }),complete: (turn: string) =>output?.enqueue({ type: 'response', id: turn, result: { completed: true } }),+ finish: (turn: string, usage?: HarnessTurnUsage) =>+ output?.enqueue({+ type: 'turn.event',+ id: turn,+ event: { type: 'finish', finishReason: 'stop', ...(usage ? { usage } : {}) }+ }),turns}}@@ -203,3 +215,61 @@ test('a turn the companion could not be sent ends with an error', async () => {expect(types.at(-1)).toBe('error')await transport.destroy()})++test("reports each turn's tokens, which older companions do not send", async () => {+ const companion = fakeCompanion()+ const reported: HarnessTurnUsage[] = []+ const transport = new HarnessChatTransport(+ 'usage-session',+ configuration,+ {},+ companion.spawn,+ (usage) => reported.push(usage)+ )+ const usage = { inputTokens: 1200, outputTokens: 40, cacheReadTokens: 1000, cacheWriteTokens: 0 }+ for (const turnUsage of [usage, undefined]) {+ const reader = (await send(transport)).getReader()+ await Promise.resolve()+ const turn = companion.turns.at(-1) ?? ''+ companion.finish(turn, turnUsage)+ companion.complete(turn)+ while (!(await reader.read()).done) {+ /* Drain the turn. */+ }+ }+ expect(reported).toEqual([usage])+ await transport.destroy()+})++test('text after a tool call starts a new part, and a stopped turn closes its text', async () => {+ const companion = fakeCompanion()+ const transport = new HarnessChatTransport('parts-session', configuration, {}, companion.spawn)+ const stop = new AbortController()+ const reader = (await send(transport, stop.signal)).getReader()+ await Promise.resolve()+ const turn = companion.turns.at(-1) ?? ''+ companion.text(turn, 'Looking.')+ companion.event(turn, {+ type: 'tool-call',+ toolCallId: 'call-1',+ toolName: 'mcp_open-pencil_get_page_tree',+ input: {}+ })+ companion.event(turn, {+ type: 'tool-result',+ toolCallId: 'call-1',+ toolName: 'mcp_open-pencil_get_page_tree',+ output: {}+ })+ companion.text(turn, 'Done')+ const types: string[] = []+ for (let read = await reader.read(); !read.done; read = await reader.read()) {+ types.push(read.value.type)+ // Stop once the second text arrived, as the person would while it streams.+ if (types.filter((type) => type === 'text-delta').length === 2) stop.abort()+ }+ expect(types.filter((type) => type === 'text-start')).toHaveLength(2)+ expect(types.filter((type) => type === 'text-end')).toHaveLength(2)+ expect(types.at(-1)).toBe('finish')+ await transport.destroy()+})diff --git a/tests/app/ai/chat/transports.test.ts b/tests/app/ai/transports/tool-loop.test.tssimilarity index 97%rename from tests/app/ai/chat/transports.test.tsrename to tests/app/ai/transports/tool-loop.test.tsindex 18268559a..403bd2bec 100644--- a/tests/app/ai/chat/transports.test.ts+++ b/tests/app/ai/transports/tool-loop.test.ts@@ -4,8 +4,8 @@ import { expect, test } from 'bun:test'import { simulateReadableStream } from 'ai'import { MockLanguageModelV4 } from 'ai/test'-import { createToolLoopTransport } from '@/app/ai/chat/transports'import type { ThinkingLevel } from '@/app/ai/models/types'+import { createToolLoopTransport } from '@/app/ai/transports/tool-loop'import { createEditorStore } from '@/app/editor/session/create'import { MOCK_USAGE } from '#tests/helpers/chat/usage'diff --git a/tests/app/automation/bridge/agent-replies.test.ts b/tests/app/automation/bridge/agent-replies.test.tsnew file mode 100644index 000000000..b26b4c729--- /dev/null+++ b/tests/app/automation/bridge/agent-replies.test.ts@@ -0,0 +1,111 @@+import 'fake-indexeddb/auto'+import { afterEach, beforeEach, describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'++import { endRun, forgetAgentChat, startAgentRun } from '@/app/ai/reply/run'+import { readToolChange } from '@/app/ai/tools/changes/store'+import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'+import { createAutomationCommandHandlers } from '@/app/automation/bridge/handlers'+import type { AutomationTarget } from '@/app/automation/bridge/target'+import { createEditorStore, type EditorStore } from '@/app/editor/session/create'++const { handleTargetCommand } = createAutomationCommandHandlers(makeFigmaFromStore)+const CHAT = '0123456789abcdef0123456789abcdef'+let stores: EditorStore[] = []++beforeEach(() => {+ // The automation FigmaAPI reads the viewport size from the window.+ Object.assign(globalThis, { window: { innerWidth: 1024, innerHeight: 768 } })+})++afterEach(() => {+ for (const store of stores) store.dispose()+ stores = []+ forgetAgentChat(CHAT)+ Reflect.deleteProperty(globalThis, 'window')+})++function document(): { store: EditorStore; target: AutomationTarget } {+ const store = createEditorStore(new SceneGraph())+ stores.push(store)+ const pageId = store.state.currentPageId+ return {+ store,+ target: { store, documentId: 'tab-1', documentName: 'Document', pageId, pageName: 'Page 1' }+ }+}++/** A rectangle made through MCP by the given agent session. */+function createRectangle(target: AutomationTarget, agent: Record<string, unknown>) {+ return handleTargetCommand(target, 'tool', {+ name: 'create_shape',+ args: { type: 'RECTANGLE', x: 0, y: 0, width: 40, height: 20 },+ agent: { session: 'session-1', ...agent }+ })+}++describe("an ACP chat's edits during its reply", () => {+ test('join the reply under the agent’s call id, labelled as the chat labels its edits', async () => {+ const { store, target } = document()+ const run = startAgentRun(store, CHAT)+ await createRectangle(target, { kind: 'acp', chat: CHAT, call: 'exec-1' })++ expect(run.undoCalls.map(({ tool, toolCallId }) => ({ tool, toolCallId }))).toEqual([+ { tool: 'create_shape', toolCallId: 'exec-1' }+ ])+ expect(run.changedCalls.has('exec-1')).toBe(true)+ expect(store.undo.peekUndo()?.label).toBe('AI: create_shape')+ // The card shows the change before and after, as for the built-in chat's calls.+ expect(readToolChange('exec-1')?.jsx.after).toContain('Rectangle')+ })++ test('include property edits, which push their own undo entry', async () => {+ const { store, target } = document()+ const created = (await createRectangle(target, { kind: 'mcp' })) as {+ result: { id: string }+ }+ const run = startAgentRun(store, CHAT)+ await handleTargetCommand(target, 'tool', {+ name: 'set_fill',+ args: { id: created.result.id, color: '#3b82f6' },+ agent: { session: 'session-1', kind: 'acp', chat: CHAT, call: 'toolu_fill' }+ })++ expect(store.undo.peekUndo()?.label).toBe('AI: set_fill')+ expect(run.undoCalls.map(({ toolCallId }) => toolCallId)).toEqual(['toolu_fill'])+ })++ test('a failed edit leaves the document free for the next one', async () => {+ const { store, target } = document()+ const run = startAgentRun(store, CHAT)+ const failed = handleTargetCommand(target, 'tool', {+ name: 'set_fill',+ args: { id: '0:404', color: '#3b82f6' },+ agent: { session: 'session-1', kind: 'acp', chat: CHAT, call: 'toolu_missing' }+ })+ await expect(failed).rejects.toThrow()+ await createRectangle(target, { kind: 'acp', chat: CHAT, call: 'toolu_next' })+ expect(run.undoCalls.map(({ toolCallId }) => toolCallId)).toEqual(['toolu_next'])+ })++ test('stay ordinary agent edits after the reply ended, from another chat, or elsewhere', async () => {+ const { store, target } = document()+ const other = document()+ const run = startAgentRun(store, CHAT)+ await createRectangle(target, { kind: 'mcp', call: 'other-1' })+ await createRectangle(target, { kind: 'acp', chat: 'fedcba9876543210', call: 'other-2' })+ await createRectangle(other.target, { kind: 'acp', chat: CHAT, call: 'other-3' })+ endRun(store, run)+ await createRectangle(target, { kind: 'acp', chat: CHAT, call: 'other-4' })++ expect(run.undoCalls).toEqual([])+ expect(['other-1', 'other-2', 'other-3', 'other-4'].map(readToolChange)).toEqual([+ null,+ null,+ null,+ null+ ])+ expect(store.undo.peekUndo()?.label).toStartWith('Agent')+ })+})diff --git a/tests/engine/acp/permission.test.ts b/tests/engine/acp/permission.test.tsindex 31c07ec2b..c287ffb5a 100644--- a/tests/engine/acp/permission.test.ts+++ b/tests/engine/acp/permission.test.ts@@ -8,7 +8,7 @@ import {requestPermissionFromUser,respondToPermission,rejectCurrentPermission-} from '@/app/ai/acp/permission'+} from '@/app/ai/agents/acp/permission'function makeRequest(options: { optionId: string; kind: string; name: string }[] = [diff --git a/tests/engine/acp/transport.test.ts b/tests/engine/acp/transport.test.tsindex 6316feb05..1e3db6685 100644--- a/tests/engine/acp/transport.test.ts+++ b/tests/engine/acp/transport.test.ts@@ -5,8 +5,8 @@ import { readUIMessageStream, type UIMessage, type UIMessageChunk } from 'ai'import type { ACPAgentDef } from '@open-pencil/core/constants'-import { createUpdateMapper } from '@/app/ai/acp/map-update'-import { formatConnectionError, buildCrashChunks } from '@/app/ai/acp/transport'+import { createUpdateMapper } from '@/app/ai/agents/acp/events'+import { agentTurnUsage, buildCrashChunks, formatConnectionError } from '@/app/ai/transports/acp'import { classifyToolState } from '@/components/chat/tool/state'import { expectDefined } from '#tests/helpers/assert'@@ -244,6 +244,52 @@ describe('an ACP turn in the chat', () => {})})+describe('an agent turn’s usage', () => {+ test('counts cached tokens as input, as the AI SDK does, and keeps them apart', () => {+ // As Codex and Claude Code report a short turn: fresh input apart from the cache.+ expect(+ agentTurnUsage(+ {+ inputTokens: 13808,+ cachedReadTokens: 12288,+ cachedWriteTokens: 0,+ outputTokens: 6,+ totalTokens: 26102+ },+ 'gpt-6.1-sol[low]'+ )+ ).toEqual({+ model: 'gpt-6.1-sol[low]',+ inputTokens: 26096,+ outputTokens: 6,+ cacheReadTokens: 12288,+ cacheWriteTokens: 0+ })+ expect(+ agentTurnUsage(+ {+ inputTokens: 2,+ cachedReadTokens: 12211,+ cachedWriteTokens: 28866,+ outputTokens: 6,+ totalTokens: 41085+ },+ null+ )+ ).toMatchObject({ model: null, inputTokens: 41079, cacheWriteTokens: 28866 })+ })++ test('leaves cache values unreported when the agent sends none', () => {+ expect(agentTurnUsage({ inputTokens: 10, outputTokens: 2, totalTokens: 12 }, null)).toEqual({+ model: null,+ inputTokens: 10,+ outputTokens: 2,+ cacheReadTokens: null,+ cacheWriteTokens: null+ })+ })+})+describe('formatConnectionError', () => {const claudeAgent: ACPAgentDef = {id: 'claude-code',diff --git a/tests/engine/app/ai/model/providers.test.ts b/tests/engine/app/ai/model/providers.test.tsindex 9f9576737..d434f1b61 100644--- a/tests/engine/app/ai/model/providers.test.ts+++ b/tests/engine/app/ai/model/providers.test.ts@@ -5,9 +5,9 @@ import type { LanguageModel } from 'ai'import { AI_PROVIDERS } from '@open-pencil/core/constants'import type { AIProviderID } from '@open-pencil/core/constants'-import { resolveLanguageModelID } from '@/app/ai/chat/model'-import { resolveProviderModel } from '@/app/ai/chat/provider-models'-import { reasoningCallSettings } from '@/app/ai/chat/reasoning'+import { resolveLanguageModelID } from '@/app/ai/models/language-model'+import { resolveProviderModel } from '@/app/ai/models/reasoning/floors'+import { reasoningCallSettings } from '@/app/ai/models/reasoning/settings'import type { ThinkingLevel } from '@/app/ai/models/types'import { createAnthropicCompatibleAdapter } from '@/app/ai/providers/compatible'import { modelProviderAdapter } from '@/app/ai/providers/registry'diff --git a/tests/engine/app/ai/vision.test.ts b/tests/engine/app/ai/vision.test.tsindex d06519883..c11a82028 100644--- a/tests/engine/app/ai/vision.test.ts+++ b/tests/engine/app/ai/vision.test.ts@@ -8,7 +8,7 @@ import {boundedImageScale,inspectRenderedDesign,type VisualInspectionDependencies-} from '@/app/ai/tools/vision'+} from '@/app/ai/tools/vision/inspect'import type { EditorStore } from '@/app/editor/session/create'import { asDouble } from '#tests/helpers/doubles'diff --git a/tests/engine/app/chat/step-limit.test.ts b/tests/engine/app/chat/step-limit.test.tsindex 39990e2bb..5d1c01e68 100644--- a/tests/engine/app/chat/step-limit.test.ts+++ b/tests/engine/app/chat/step-limit.test.ts@@ -8,10 +8,10 @@ import { toRaw } from 'vue'import { FigmaAPI } from '@open-pencil/core/figma-api'import { maxAgentSteps, reasoningDisplay } from '@/app/ai/chat/preferences'-import { DEFAULT_AGENT_STEPS, resolveAgentStepLimit } from '@/app/ai/chat/step-limit'-import { createToolLoopTransport } from '@/app/ai/chat/transports'+import { DEFAULT_AGENT_STEPS, resolveAgentStepLimit } from '@/app/ai/reply/step-limit'import { didHitStepLimit } from '@/app/ai/tools'import { aiToolOverrides } from '@/app/ai/tools/preferences'+import { createToolLoopTransport } from '@/app/ai/transports/tool-loop'import * as figmaFactory from '@/app/automation/bridge/figma-factory'import { createEditorStore } from '@/app/editor/session/create'import { appPreferences } from '@/app/settings/preferences/store'diff --git a/tests/engine/app/chat/tool-access.test.ts b/tests/engine/app/chat/tool-access.test.tsindex 4308d0d9c..84e8b508b 100644--- a/tests/engine/app/chat/tool-access.test.ts+++ b/tests/engine/app/chat/tool-access.test.ts@@ -4,8 +4,8 @@ import { expect, test } from 'bun:test'import { simulateReadableStream, type UIMessage } from 'ai'import { MockLanguageModelV4 } from 'ai/test'-import { createToolLoopTransport } from '@/app/ai/chat/transports'import { aiToolOverrides } from '@/app/ai/tools/preferences'+import { createToolLoopTransport } from '@/app/ai/transports/tool-loop'import { createEditorStore } from '@/app/editor/session/create'import { MOCK_USAGE } from '#tests/helpers/chat/usage'diff --git a/tests/engine/app/usage/summarize.test.ts b/tests/engine/app/usage/summarize.test.tsindex 2f8efe0e3..b459dbcf8 100644--- a/tests/engine/app/usage/summarize.test.ts+++ b/tests/engine/app/usage/summarize.test.ts@@ -24,7 +24,42 @@ describe('summarizeUsage', () => {expect(summary.inputTokens).toBe(100)expect(summary.outputTokens).toBe(20)expect(summary.cacheReadTokens).toBe(30)- expect(summary.models).toEqual([{ provider: 'openai', model: 'gpt-4o', requests: 1 }])+ expect(summary.models).toEqual([+ { provider: 'openai', model: 'gpt-4o', steps: 1, inputTokens: 100, outputTokens: 20 }+ ])+ })++ test('sums tokens per model, an agent turn counting as one step', () => {+ const step = (provider: string, model: string, inputTokens: number, outputTokens: number) =>+ event('model.step.completed', {+ provider,+ model,+ inputTokens,+ outputTokens,+ cacheReadTokens: null,+ cacheWriteTokens: null+ })+ const summary = summarizeUsage([+ step('openrouter', 'anthropic/claude-sonnet-5.5', 1000, 50),+ step('openrouter', 'anthropic/claude-sonnet-5.5', 2000, 70),+ step('acp:codex', 'gpt-6.1-sol[low]', 26102, 6)+ ])+ expect(summary.models).toEqual([+ {+ provider: 'acp:codex',+ model: 'gpt-6.1-sol[low]',+ steps: 1,+ inputTokens: 26102,+ outputTokens: 6+ },+ {+ provider: 'openrouter',+ model: 'anthropic/claude-sonnet-5.5',+ steps: 2,+ inputTokens: 3000,+ outputTokens: 120+ }+ ])})test('preserves unavailable telemetry as null', () => {diff --git a/tests/engine/mcp/server/index.test.ts b/tests/engine/mcp/server/index.test.tsindex 30a01f400..08d2b2807 100644--- a/tests/engine/mcp/server/index.test.ts+++ b/tests/engine/mcp/server/index.test.ts@@ -977,6 +977,33 @@ describe('MCP sessions as agents', () => {)})+ test("an ACP chat's tool call names the chat and the call's id in it", async () => {+ const chat = '0123456789abcdef0123456789abcdef'+ await withAgentClient(+ { [MCP_AGENT_HEADER]: 'acp', [MCP_CHAT_HEADER]: chat },+ async (client, browser) => {+ // Codex sends its call id as `callId`, Claude Code as `claudecode/toolUseId`.+ await client.callTool({+ name: 'get_page_tree',+ arguments: {},+ _meta: { callId: 'exec-1' }+ })+ await client.callTool({+ name: 'get_page_tree',+ arguments: {},+ _meta: { 'claudecode/toolUseId': 'toolu_1' }+ })+ const agents = browser.requests+ .filter((item) => item.command === 'tool')+ .map((item) => (item.args as { agent?: unknown }).agent)+ expect(agents).toMatchObject([+ { kind: 'acp', chat, call: 'exec-1' },+ { kind: 'acp', chat, call: 'toolu_1' }+ ])+ }+ )+ })+test('a chat header that is not a chat id is not forwarded', async () => {await withAgentClient({ [MCP_AGENT_HEADER]: 'acp', [MCP_CHAT_HEADER]: 'not hex' },diff --git a/tests/engine/tauri/acp-transport.test.ts b/tests/engine/tauri/acp-transport.test.tsindex 3c8630ed2..5b1e5d3ec 100644--- a/tests/engine/tauri/acp-transport.test.ts+++ b/tests/engine/tauri/acp-transport.test.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, test, vi } from 'bun:test'-import { createACPTransport } from '@/app/ai/chat/transports'+import { createACPTransport } from '@/app/ai/chat/session'import { clearTauriMocks, mockTauriIPC } from '#tests/helpers/tauri/mocks'diff --git a/tests/engine/tauri/command.test.ts b/tests/engine/tauri/command.test.tsindex 8b8342338..c269ca29b 100644--- a/tests/engine/tauri/command.test.ts+++ b/tests/engine/tauri/command.test.ts@@ -5,9 +5,9 @@ import * as v from 'valibot'import { ACP_AGENTS } from '@open-pencil/core/constants'-import { signInScope } from '@/app/ai/acp/auth/terminal'-import { bunInstallArgs, npmInstallArgs } from '@/app/ai/agents/native'-import { HARNESS_PACKAGE } from '@/app/ai/harness/companion'+import { signInScope } from '@/app/ai/agents/acp/auth/terminal'+import { HARNESS_PACKAGE } from '@/app/ai/agents/pi/companion'+import { bunInstallArgs, npmInstallArgs } from '@/app/ai/agents/setup/native'import { MCP_PACKAGE_NAME } from '@/app/automation/mcp/failure'import { resolvePlatformCommand, resolveScopedCommand } from '@/app/tauri/command'diff --git a/tests/engine/tauri/harness-process.test.ts b/tests/engine/tauri/harness-process.test.tsindex b5622964e..518700868 100644--- a/tests/engine/tauri/harness-process.test.ts+++ b/tests/engine/tauri/harness-process.test.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, test } from 'bun:test'-import { spawnHarnessProcess } from '@/app/ai/harness/process'+import { spawnHarnessProcess } from '@/app/ai/agents/pi/process'import { clearTauriMocks, mockTauriIPC } from '#tests/helpers/tauri/mocks'diff --git a/tests/engine/tauri/processes.test.ts b/tests/engine/tauri/processes.test.tsindex 87c234723..2f0777d4d 100644--- a/tests/engine/tauri/processes.test.ts+++ b/tests/engine/tauri/processes.test.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, test, vi } from 'bun:test'-import { spawnACPProcess } from '@/app/ai/acp/process'+import { spawnACPProcess } from '@/app/ai/agents/acp/process'import { clearTauriMocks, mockTauriIPC } from '#tests/helpers/tauri/mocks'diff --git a/tests/helpers/chat/render-stream/browser.ts b/tests/helpers/chat/render-stream/browser.tsindex 67dcbc9d1..73ac5e565 100644--- a/tests/helpers/chat/render-stream/browser.ts+++ b/tests/helpers/chat/render-stream/browser.ts@@ -1,4 +1,4 @@-import { createToolLoopTransport } from '@/app/ai/chat/transports'+import { createToolLoopTransport } from '@/app/ai/transports/tool-loop'import { createRenderStreamModel, type RenderStreamScenario } from './model'diff --git a/tests/helpers/chat/tool-loop.ts b/tests/helpers/chat/tool-loop.tsindex cbd926d63..c3be5a2f7 100644--- a/tests/helpers/chat/tool-loop.ts+++ b/tests/helpers/chat/tool-loop.ts@@ -8,7 +8,7 @@ import type { Page } from '@playwright/test'*/export async function injectToolLoopTransport(page: Page): Promise<void> {await page.evaluate(async () => {- const transportsPath = '/src/app/ai/chat/transports.ts'+ const transportsPath = '/src/app/ai/transports/tool-loop.ts'const { createToolLoopTransport } = await import(transportsPath)const api = window.openPencilconst store = api?.getStore?.()