AI-native design editor. Open-source Figma alternative.
fix(ai): end a stopped chat reply cleanly (#1077)
Danila Poyarkovd5179446a44b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 50869a6e2..4139c6128 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -83,14 +83,14 @@- Build controls from scripts, tools, and design JSX. Scripts run by `eval`, `openpencil eval`, and app automation get an `openpencil` global next to `figma`, in the Figma API's style: `openpencil.setBehaviour(set, { kind: 'switch', values: { value: 'State' }, parts: { thumb: 'Thumb' }, states: 'Interaction' })` or `.bindValue()` and `.bindPart()` by property and slot names, `getBehaviour`, `behaviourKinds`, and `createSlot`. MCP and AI chat get `set_behaviour`, `get_behaviour`, and `create_slot`. Design JSX writes controls with Reka UI's element names, such as `<Switch.Root modelValue="State">` with `<Switch.Thumb>`, `<TextField.Input>`, and `<Tabs.List>`, in JSX strings or in TSX through the typed `Switch`, `Slider`, `Tabs`, and other namespaces `@open-pencil/design-jsx` exports, and exports components with behaviours the same way. A part holding layers with no layout of its own, such as a `Tabs.Content` panel, stacks them in a column that hugs them.- Open a `.fig`, `.pen`, or other supported document by dragging it onto the window, where it opens in a new tab as File → Open does. Images and SVG files dropped on the canvas are still placed, and other files report that they can't be opened instead of being ignored.- Pass an ID generator to `new SceneGraph()` from `@open-pencil/scene-graph` to choose the IDs of the nodes, variables, collections, and modes the graph creates, including modes added later with `createMode`; generated IDs skip any node, variable, collection, or mode ID already in the graph, and an exhausted generator throws instead of hanging. `createComponentPropertyId` gives new component properties the `prop:` IDs the editor, plugin API, and design JSX share.-- Diagnose failures from Settings → Diagnostics. Uncaught errors, unhandled rejections, component errors, failed AI chats, and AI tool calls that broke inside OpenPencil are recorded with their message and stack, and other failed tool calls as warnings. Messages and stacks are scrubbed of URL queries and credentials, API keys and tokens, email addresses, and home folder names, and provider errors keep no message. Each event has a specific label, such as *Tool: render · 162 ms* or *Error: TypeError*, expands to its details, and can be filtered by level and category and paged; copied diagnostics include the app version and browser.+- Diagnose failures from Settings → Diagnostics. Uncaught errors, unhandled rejections, component errors, failed and stopped AI chats, and AI tool calls that broke inside OpenPencil are recorded with their message and stack, and other failed tool calls as warnings. Messages and stacks are scrubbed of URL queries and credentials, API keys and tokens, email addresses, and home folder names, and provider errors keep no message. Each event has a specific label, such as *Tool: render · 162 ms* or *Error: TypeError*, expands to its details, and can be filtered by level and category and paged; copied diagnostics include the app version and browser.- Import `resolvePasteTarget` from `@open-pencil/core/editor` to place ordinary pasted or dropped content in an embedding app in the same container the editor would choose. It takes the editor `createEditor` returns. Replacement paste is not covered: it inserts into the selected target's parent.- Import `flattenNodesToVectorProps`, `outlineStrokeNodesToVectorProps`, and the `VectorFlattenProps` type from `@open-pencil/core/canvas` to compute Flatten and Outline stroke geometry in an embedding app without going through the editor's own write path.- Check designs from the new Lint tab in the right panel: issues on the page, in the selection, or across the document are grouped by rule, hovering one highlights its layer on the canvas, clicking selects it and brings it into view, and one-click fixes bind colors to the variable they match and round subpixel geometry for a row or a whole group, and snap radius, spacing, and small text to the scale, convert groups to frames, and delete hidden layers one row at a time. Rules can be turned off individually or switched between the Recommended, Strict, and Accessibility presets.- See which layer the code is about in the Code tab's Design JSX and Tailwind JSX: the element around the cursor marks its opening and closing tag and shows its layer on the canvas as a tinted box, apart from canvas hover, and design issues are underlined on the property that causes them, including while you edit Design JSX live.- Fix lint issues outside the app: `openpencil lint --fix -o fixed.fig` binds colors to the variable they match and rounds subpixel geometry, and the `lint` and `lint_fix` tools let MCP clients and AI chat check a page and apply those fixes, plus radius, spacing, text size, group-to-frame, and hidden-layer suggestions on request. Lint messages carry each fix as data in `fix` and `suggestions`.- Mark layers with errors and warnings on the canvas while you work, and pin those outside the view to the canvas edge in their direction, with matching marks in the Layers panel and error and warning counts in the page list; hover a marker or pin for its issues or click it to open them in Lint, and turn markers on or off with View → Design issues.-- Follow collaborators and their AI agents from the avatars in the toolbar: an avatar counts that person's agents, hovering lists what each is doing and on which page, and clicking follows. The view glides after whoever you follow, a frame in their color and a “Following …” bar show whom you follow, and Escape, clicking, scrolling, zooming, or switching pages stops it. Your own agents, the AI chat and MCP clients alike, are followed automatically while they work; turn this off with the crosshair button at the top of the AI panel. Your own avatar renames your agents and leaves the room.+- Follow collaborators and their AI agents from the avatars in the toolbar: an avatar counts that person's agents, hovering lists what each is doing and on which page, and clicking follows. The view glides after whoever you follow, a frame in their color and a “Following …” bar show whom you follow, and Escape, clicking, scrolling, zooming, or switching pages stops it. Your own agents, the AI chat and MCP clients alike, are followed automatically while they work, and following stops when they finish, are stopped, or fail; an agent you chose to follow keeps you with it while it rests. Turn automatic following off with the crosshair button at the top of the AI panel. Your own avatar renames your agents and leaves the room.- See where AI agents are working: the built-in AI chat, ACP and Pi harness chats, and every MCP client each show a cursor whose outlined label shows a sparkle and a callsign such as *Fern*, at the layers they read or edit, on whichever page those are, and an MCP agent leaves when its session ends. While the chat streams JSX, its cursor moves through the elements as they appear and outlines them. People's and agents' cursors glide to each new position instead of jumping. In a shared room, collaborators see each other's agents in the color of the person running them, and watch what the AI chat builds take shape on their own canvas while its JSX streams, not only once it is done.- Copy the document's variables as a CSS stylesheet or a Tailwind v4 theme from the variables dialog, or print them with `openpencil tokens`. Each collection's default mode goes in `:root` (or `@theme`, with a `@custom-variant` per mode), other modes override under their condition, `[data-theme="dark"]` unless the mode names a selector or `@media` query, and aliases stay `var()` references that follow the mode. Variables CSS cannot express, such as booleans, are named instead of written.- Import and export variables, text styles, and effect styles as W3C design tokens. **Export as design tokens** in the variables dialog's copy menu and `openpencil tokens --format dtcg --out <folder>` write one file per collection mode in the shape Figma imports, typography and shadow tokens for styles, and a DTCG resolver for tools such as Style Dictionary. **Import design tokens** reads files from Figma, a resolver with its files, Tokens Studio themes, or a zip of them, shows where each collection and mode goes before anything changes, updates variables and styles by name without deleting any, and undoes in one step; agents and MCP clients import with the `import_design_tokens` tool, and `design_to_tokens` takes `format: "dtcg"`.@@ -101,7 +101,7 @@- Choose how much an AI model thinks for each message from the chat composer, from Off to Extra high or the provider default. Anthropic, Google, DeepSeek, OpenAI, OpenRouter, and compatible models apply it, where reasoning effort previously reached only OpenAI and OpenRouter models. A model profile's thinking level, which replaces its free-text reasoning effort, sets the starting choice, and finished reasoning shows how long the model thought.- Read AI tool calls at a glance: each call shows a one-line summary and buttons that bring the layers it touched into view, even on another page. Expanded, it shows highlighted JSX, scripts, and JSON input and output, and exported images inline. A render call's JSX streams in as the model writes it, and a long run folds its earlier steps into one row that lists them by name and counts failures.- Review what each AI edit changed from its tool call in the chat: a before and after image split by a draggable divider, or the changed pixels highlighted, and a diff of the layers' JSX. Both are saved with the conversation. Settings → Chat → Change previews sets the image size (240, 480, or 960 px) or turns images off to keep only the JSX diff. The chat AI can check its own work the same way with `diff_changes`, which compares the page or a layer with its state before the run edited it as a patch that `diff_apply` can replay.-- Revert an AI reply's edits from the chat while nothing has been edited since, regenerate the last reply, retry a message that failed before any reply from the message or its error notice, or edit the last message and send it again; regenerating and resending undo the replaced reply's edits first when they can. A reverted reply stays in the chat, dimmed and marked *Changes reverted*, also after reopening the conversation, and your next message tells the AI that those edits are gone, so it does not build on them; **Restore changes** on the reply, or Edit → Redo, brings the edits back and removes the mark while nothing has been edited since.+- Revert an AI reply's edits from the chat while nothing has been edited since, regenerate the last reply, retry a message that failed before any reply from the message or its error notice, or edit the last message and send it again; regenerating and resending undo the replaced reply's edits first when they can. An edit a tool finishes after you stop a reply still counts as that reply's. A reverted reply stays in the chat, dimmed and marked *Changes reverted*, also after reopening the conversation, and your next message tells the AI that those edits are gone, so it does not build on them; **Restore changes** on the reply, or Edit → Redo, brings the edits back and removes the mark while nothing has been edited since.- Preview designs progressively on the canvas as direct AI providers stream JSX, without saving partial designs or adding intermediate undo steps. A preview stays with its page: it hides while you view another page and returns when you come back.- Write design trees as TSX with `@open-pencil/design-jsx` as the JSX import source, and render them with `renderTree`.- Swap the component behind an instance with `instance.swapComponent(component)` in the plugin API, as in Figma.@@ -205,6 +205,7 @@- Draw what a mask masks through the mask's opacity and layer blur, as Figma does, so a half-transparent or blurred mask fades or softens its layers instead of masking them fully. An outline mask ignores how opaque its fill is, and a luminance mask counts its opacity twice, as in Figma.- Import SVG files that start with an XML declaration or doctype, such as Illustrator and Inkscape exports, instead of reporting no supported elements.- Keep `fill-opacity` and `stroke-opacity` when importing SVG instead of drawing those paints opaque.+- Stopping an AI chat reply ends it cleanly. The reply is marked *Stopped*, its reasoning stops showing *Thinking…*, and a tool call that never reported back stops spinning and tells the AI on your next message whether it changed the document, also in conversations saved mid-reply. A tool already running finishes, and calls still waiting for their turn change nothing.- Keep an AI chat going when a script it runs through `eval` returns layers or pages inside an object or list, or values such as `NaN` or a `Map`; the reply used to stop with an invalid-prompt error. The model now gets such results as JSON.- Use an API key saved in Settings for the open AI chat right away, including when asking again after a failed request, instead of only after reloading; the failure's notice closes once the request is sent again.- Renaming a section title on the canvas keeps the title's size, weight, and place. Section titles draw in Inter SemiBold rather than an emboldened regular weight, and labels that are not rotated sit on whole pixels, so they stay crisp.diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.jsonindex 010ae44a0..a956bd224 100644--- a/packages/vue/src/i18n/locales/de/ai.json+++ b/packages/vue/src/i18n/locales/de/ai.json@@ -35,6 +35,7 @@"copyResponse": "Antwort kopieren","revertTurn": "Änderungen zurücknehmen","turnReverted": "Änderungen rückgängig gemacht",+ "turnStopped": "Gestoppt","restoreTurn": "Änderungen wiederherstellen","regenerate": "Neu generieren","revertAndRegenerate": "Zurücknehmen und neu generieren",diff --git a/packages/vue/src/i18n/locales/de/diagnostics.json b/packages/vue/src/i18n/locales/de/diagnostics.jsonindex b7d9114a0..805203160 100644--- a/packages/vue/src/i18n/locales/de/diagnostics.json+++ b/packages/vue/src/i18n/locales/de/diagnostics.json@@ -14,6 +14,7 @@"usageHistoryDescription": "Lokale Zusammenfassungen der AI-Nutzung speichern.","title": "Diagnose","chatCompleted": "KI-Chat abgeschlossen",+ "chatStopped": "KI-Chat gestoppt","chatFailed": "KI-Chat fehlgeschlagen","storageFailed": "Speichervorgang fehlgeschlagen","documentFailed": "Dokumentvorgang fehlgeschlagen",diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.jsonindex 1a76a4bf6..b327c2136 100644--- a/packages/vue/src/i18n/locales/es/ai.json+++ b/packages/vue/src/i18n/locales/es/ai.json@@ -35,6 +35,7 @@"copyResponse": "Copiar respuesta","revertTurn": "Revertir cambios","turnReverted": "Cambios revertidos",+ "turnStopped": "Detenida","restoreTurn": "Restaurar cambios","regenerate": "Regenerar","revertAndRegenerate": "Revertir y regenerar",diff --git a/packages/vue/src/i18n/locales/es/diagnostics.json b/packages/vue/src/i18n/locales/es/diagnostics.jsonindex 5e3b0952a..03e04295a 100644--- a/packages/vue/src/i18n/locales/es/diagnostics.json+++ b/packages/vue/src/i18n/locales/es/diagnostics.json@@ -14,6 +14,7 @@"usageHistoryDescription": "Conserva resúmenes locales del uso de AI.","title": "Diagnóstico","chatCompleted": "Chat de AI completado",+ "chatStopped": "Chat de IA detenido","chatFailed": "Chat de AI fallido","storageFailed": "Operación de almacenamiento fallida","documentFailed": "Operación de documento fallida",diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.jsonindex 7f7dbc5b4..eada484a0 100644--- a/packages/vue/src/i18n/locales/fr/ai.json+++ b/packages/vue/src/i18n/locales/fr/ai.json@@ -35,6 +35,7 @@"copyResponse": "Copier la réponse","revertTurn": "Annuler les modifications","turnReverted": "Modifications annulées",+ "turnStopped": "Arrêtée","restoreTurn": "Rétablir les modifications","regenerate": "Régénérer","revertAndRegenerate": "Annuler et régénérer",diff --git a/packages/vue/src/i18n/locales/fr/diagnostics.json b/packages/vue/src/i18n/locales/fr/diagnostics.jsonindex a1077b374..cfde11ee8 100644--- a/packages/vue/src/i18n/locales/fr/diagnostics.json+++ b/packages/vue/src/i18n/locales/fr/diagnostics.json@@ -14,6 +14,7 @@"usageHistoryDescription": "Conserver les résumés locaux de l’utilisation de l’IA.","title": "Diagnostics","chatCompleted": "Chat IA terminé",+ "chatStopped": "Chat IA arrêté","chatFailed": "Échec du chat IA","storageFailed": "Échec de l’opération de stockage","documentFailed": "Échec de l’opération sur le document",diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.jsonindex 47bd61d2a..78cb5abbe 100644--- a/packages/vue/src/i18n/locales/it/ai.json+++ b/packages/vue/src/i18n/locales/it/ai.json@@ -35,6 +35,7 @@"copyResponse": "Copia risposta","revertTurn": "Annulla le modifiche","turnReverted": "Modifiche annullate",+ "turnStopped": "Interrotta","restoreTurn": "Ripristina modifiche","regenerate": "Rigenera","revertAndRegenerate": "Annulla e rigenera",diff --git a/packages/vue/src/i18n/locales/it/diagnostics.json b/packages/vue/src/i18n/locales/it/diagnostics.jsonindex 68bab82c6..a1e23a87e 100644--- a/packages/vue/src/i18n/locales/it/diagnostics.json+++ b/packages/vue/src/i18n/locales/it/diagnostics.json@@ -14,6 +14,7 @@"usageHistoryDescription": "Conserva i riepiloghi locali dell’utilizzo dell’AI.","title": "Diagnostica","chatCompleted": "Chat AI completata",+ "chatStopped": "Chat AI interrotta","chatFailed": "Chat AI non riuscita","storageFailed": "Operazione di archiviazione non riuscita","documentFailed": "Operazione sul documento non riuscita",diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.jsonindex 6235d38cc..ebaa85a01 100644--- a/packages/vue/src/i18n/locales/ja/ai.json+++ b/packages/vue/src/i18n/locales/ja/ai.json@@ -35,6 +35,7 @@"copyResponse": "回答をコピー","revertTurn": "変更を元に戻す","turnReverted": "変更を取り消しました",+ "turnStopped": "停止しました","restoreTurn": "変更を元に戻す","regenerate": "再生成","revertAndRegenerate": "元に戻して再生成",diff --git a/packages/vue/src/i18n/locales/ja/diagnostics.json b/packages/vue/src/i18n/locales/ja/diagnostics.jsonindex 91736342b..216346c4e 100644--- a/packages/vue/src/i18n/locales/ja/diagnostics.json+++ b/packages/vue/src/i18n/locales/ja/diagnostics.json@@ -14,6 +14,7 @@"usageHistoryDescription": "AIの使用状況の概要を端末に保存します。","title": "診断","chatCompleted": "AIチャット完了",+ "chatStopped": "AIチャット停止","chatFailed": "AIチャット失敗","storageFailed": "ストレージ操作失敗","documentFailed": "ドキュメント操作失敗",diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.jsonindex de9178c3c..4e8add029 100644--- a/packages/vue/src/i18n/locales/pl/ai.json+++ b/packages/vue/src/i18n/locales/pl/ai.json@@ -35,6 +35,7 @@"copyResponse": "Kopiuj odpowiedź","revertTurn": "Cofnij zmiany","turnReverted": "Zmiany cofnięte",+ "turnStopped": "Zatrzymano","restoreTurn": "Przywróć zmiany","regenerate": "Wygeneruj ponownie","revertAndRegenerate": "Cofnij i wygeneruj ponownie",diff --git a/packages/vue/src/i18n/locales/pl/diagnostics.json b/packages/vue/src/i18n/locales/pl/diagnostics.jsonindex 855e58264..0c8aec5a0 100644--- a/packages/vue/src/i18n/locales/pl/diagnostics.json+++ b/packages/vue/src/i18n/locales/pl/diagnostics.json@@ -14,6 +14,7 @@"usageHistoryDescription": "Zachowuj lokalne podsumowania użycia AI.","title": "Diagnostyka","chatCompleted": "Ukończono czat AI",+ "chatStopped": "Czat AI zatrzymany","chatFailed": "Czat AI nie powiódł się","storageFailed": "Operacja przechowywania nie powiodła się","documentFailed": "Operacja dokumentu nie powiodła się",diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.jsonindex df35bc198..4f3c4e3fc 100644--- a/packages/vue/src/i18n/locales/ru/ai.json+++ b/packages/vue/src/i18n/locales/ru/ai.json@@ -35,6 +35,7 @@"copyResponse": "Копировать ответ","revertTurn": "Отменить изменения","turnReverted": "Изменения отменены",+ "turnStopped": "Остановлено","restoreTurn": "Вернуть изменения","regenerate": "Сгенерировать заново","revertAndRegenerate": "Отменить и сгенерировать заново",diff --git a/packages/vue/src/i18n/locales/ru/diagnostics.json b/packages/vue/src/i18n/locales/ru/diagnostics.jsonindex 050dec156..8aca8c074 100644--- a/packages/vue/src/i18n/locales/ru/diagnostics.json+++ b/packages/vue/src/i18n/locales/ru/diagnostics.json@@ -14,6 +14,7 @@"usageHistoryDescription": "Сохранять локальные сводки использования AI.","title": "Диагностика","chatCompleted": "AI-чат завершён",+ "chatStopped": "Чат ИИ остановлен","chatFailed": "Ошибка AI-чата","storageFailed": "Ошибка операции хранения","documentFailed": "Ошибка операции с документом",diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.jsonindex e55ee07b2..ef10a162e 100644--- a/packages/vue/src/i18n/locales/zh-cn/ai.json+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json@@ -35,6 +35,7 @@"copyResponse": "复制回答","revertTurn": "撤销更改","turnReverted": "已撤销更改",+ "turnStopped": "已停止","restoreTurn": "恢复更改","regenerate": "重新生成","revertAndRegenerate": "撤销并重新生成",diff --git a/packages/vue/src/i18n/locales/zh-cn/diagnostics.json b/packages/vue/src/i18n/locales/zh-cn/diagnostics.jsonindex f38bede49..95330d42c 100644--- a/packages/vue/src/i18n/locales/zh-cn/diagnostics.json+++ b/packages/vue/src/i18n/locales/zh-cn/diagnostics.json@@ -14,6 +14,7 @@"usageHistoryDescription": "保留本地 AI 使用摘要。","title": "诊断","chatCompleted": "AI 聊天已完成",+ "chatStopped": "AI 聊天已停止","chatFailed": "AI 聊天失败","storageFailed": "存储操作失败","documentFailed": "文档操作失败",diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.tsindex b9ba691f0..a3092b015 100644--- a/packages/vue/src/i18n/messages/ai.ts+++ b/packages/vue/src/i18n/messages/ai.ts@@ -82,6 +82,7 @@ export const aiMessageDefaults = {copyResponse: 'Copy response',revertTurn: 'Revert changes',turnReverted: 'Changes reverted',+ turnStopped: 'Stopped',restoreTurn: 'Restore changes',regenerate: 'Regenerate',revertAndRegenerate: 'Revert and regenerate',diff --git a/packages/vue/src/i18n/messages/diagnostics.ts b/packages/vue/src/i18n/messages/diagnostics.tsindex ffa784098..86d4d5945 100644--- a/packages/vue/src/i18n/messages/diagnostics.ts+++ b/packages/vue/src/i18n/messages/diagnostics.ts@@ -14,6 +14,7 @@ export const diagnosticsMessageDefaults = {usageCacheNote: 'Cache values are shown only when the provider reports them.',title: 'Diagnostics',chatCompleted: 'AI chat completed',+ chatStopped: 'AI chat stopped',chatFailed: 'AI chat failed',storageFailed: 'Storage operation failed',documentFailed: 'Document operation failed',diff --git a/src/app/ai/chat/history/messages.ts b/src/app/ai/chat/history/messages.tsindex aac4ae2a4..3c229760b 100644--- a/src/app/ai/chat/history/messages.ts+++ b/src/app/ai/chat/history/messages.ts@@ -6,6 +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 { readToolChange, setToolChange } from '@/app/ai/tools/changes/store'import type { ConversationMessage } from './types'@@ -36,7 +37,8 @@ export function restoreMessages(messages: ConversationMessage[]): UIMessage[] {setMessageAttachments(row.message.id, row.attachments)for (const change of row.toolChanges ?? []) setToolChange(change)}- return messages.map((row) => structuredClone(row.message))+ // Nothing runs in a reopened conversation; a reply saved mid-way no longer reads as running.+ return messages.map((row) => settleMessage(structuredClone(row.message), { stopped: false }))}export function fallbackTitle(messages: UIMessage[]): string {diff --git a/src/app/ai/chat/settle.ts b/src/app/ai/chat/settle.tsnew file mode 100644index 000000000..13fd7c381--- /dev/null+++ b/src/app/ai/chat/settle.ts@@ -0,0 +1,56 @@+import { isReasoningUIPart, isTextUIPart, isToolUIPart, type UIMessage } from 'ai'+import * as v from 'valibot'+import { toRaw } from 'vue'++/** A reply the user stopped is marked in its metadata, which conversations store. */+const StoppedMetadata = v.object({ stopped: v.literal(true) })++export function wasStopped(message: UIMessage): boolean {+ return v.is(StoppedMetadata, message.metadata)+}++export interface SettleOptions {+ /** Whether the user stopped the reply, rather than it failing or being cut off. */+ stopped: boolean+ /** Whether a call changed the document; unknown for a conversation reopened later. */+ changed?: (toolCallId: string) => boolean+}++function unfinishedCallError(toolCallId: string, changed: SettleOptions['changed']): string {+ if (!changed) return 'The reply ended before this call reported back.'+ return changed(toolCallId)+ ? 'The reply ended while this call ran. It changed the document, but its result never arrived.'+ : 'The reply ended before this call finished. It did not change the document.'+}++/**+ * A reply as it stands once it ended without finishing, stopped or failed: nothing in it still+ * reads as running. Reasoning and text are done, and a call that never reported back fails+ * with what happened to the document, which the model reads on the next request.+ */+export function settleMessage(live: UIMessage, { stopped, changed }: SettleOptions): UIMessage {+ // The chat's messages are reactive; the settled one is built from plain values, so the+ // conversation can still be saved with `structuredClone`.+ const message = toRaw(live)+ const parts = message.parts.map((part): UIMessage['parts'][number] => {+ if ((isReasoningUIPart(part) || isTextUIPart(part)) && part.state === 'streaming') {+ return { ...part, state: 'done' }+ }+ if (+ isToolUIPart(part) &&+ (part.state === 'input-streaming' || part.state === 'input-available')+ ) {+ return {+ ...part,+ state: 'output-error',+ input: part.input,+ errorText: unfinishedCallError(part.toolCallId, changed)+ }+ }+ return part+ })+ const unchanged = parts.every((part, index) => part === message.parts[index])+ if (unchanged && (!stopped || wasStopped(message))) return live+ const metadata = v.is(v.record(v.string(), v.unknown()), message.metadata) ? message.metadata : {}+ return { ...message, parts, metadata: stopped ? { ...metadata, stopped: true } : metadata }+}diff --git a/src/app/ai/chat/submission/use.ts b/src/app/ai/chat/submission/use.tsindex f88624089..f1061bd66 100644--- a/src/app/ai/chat/submission/use.ts+++ b/src/app/ai/chat/submission/use.ts@@ -17,8 +17,7 @@ import { prepareSubmittedImages } from '@/app/ai/chat/submission/images'import { chatToResend } from '@/app/ai/chat/submission/resend'import { useRevertRecords } from '@/app/ai/chat/submission/reverts'import type { ChatInstance, ChatSubmission } from '@/app/ai/chat/submission/types'-import { recordTurn, restoreTurn, revertTurn } from '@/app/ai/chat/turns'-import { runUndoEntries } from '@/app/ai/tools'+import { recordReplyTurn, restoreTurn, revertTurn } from '@/app/ai/chat/turns'import type { EditorStore } from '@/app/editor/active-store'interface SubmissionOptions extends SubmissionErrorOptions {@@ -57,9 +56,7 @@ export function useChatSubmission(options: SubmissionOptions) {const previous = lastAssistantId(chat)await send()const reply = lastAssistantId(chat)- if (!reply || reply === previous) return- const editor = options.getEditor()- recordTurn(reply, editor, runUndoEntries(editor))+ if (reply && reply !== previous) await recordReplyTurn(reply, options.getEditor())}async function sendText(diff --git a/src/app/ai/chat/transports.ts b/src/app/ai/chat/transports.tsindex 29ebbe826..a74222d9f 100644--- a/src/app/ai/chat/transports.ts+++ b/src/app/ai/chat/transports.ts@@ -23,13 +23,14 @@ 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, endRun, recordStep, startRun } from '@/app/ai/tools'+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 { diagnosticErrorDetails } from '@/app/diagnostics'import {recordChatCompleted,recordChatFailed,+ recordChatStopped,recordModelStepCompleted} from '@/app/diagnostics/events'import type { AIDiagnosticContext } from '@/app/diagnostics/events/ai'@@ -37,6 +38,7 @@ import type { getActiveEditorStore } from '@/app/editor/active-store'import { resumableTransport } from './history/continuation'import { maxAgentSteps } from './preferences'+import { settleMessage } from './settle'type EditorStore = ReturnType<typeof getActiveEditorStore>@@ -111,6 +113,8 @@ export function createToolLoopTransport({diagnosticContext = {}}: 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)@@ -129,15 +133,13 @@ export function createToolLoopTransport({tools,maxOutputTokens,prepareCall: (options) => {- const stepLimit = maxAgentSteps.valueconst enabledNames = new Set(enabledAIToolDefinitions(aiToolOverrides.value).map((tool) => tool.name))preview.clear()- startRun(store, stepLimit, effectiveModelID)return {...options,- stopWhen: stepCountIs(stepLimit),+ stopWhen: stepCountIs(currentRun(store).maxSteps),// Keep the full catalog for validating history; offer only enabled tools to this request.tools: Object.fromEntries(Object.entries(tools).filter(([name]) => enabledNames.has(name))),maxOutputTokens,@@ -146,7 +148,7 @@ export function createToolLoopTransport({},onFinish: () => {preview.clear()- endRun(store)+ endRun(store, run)},onStepFinish: ({ usage }) => {preview.clear()@@ -167,7 +169,7 @@ export function createToolLoopTransport({function handleError(error: unknown): string {preview.clear()- endRun(store)+ endRun(store, run)onError?.(error)return 'The provider rejected the request.'}@@ -178,8 +180,13 @@ export function createToolLoopTransport({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// Stopping a reply ends the run without onFinish.- if (options.abortSignal) useEventListener(options.abortSignal, 'abort', () => endRun(store))+ const { abortSignal } = options+ if (abortSignal?.aborted) endRun(store, started)+ else if (abortSignal) useEventListener(abortSignal, 'abort', () => endRun(store, started))// DirectChatTransport handles error chunks, but not a rejected underlying stream.return createUIMessageStream<UIMessage>({execute: async ({ writer }) => {@@ -191,6 +198,28 @@ export function createToolLoopTransport({})}+/**+ * A reply that ended unfinished is settled once its last edit landed, so it no longer reads as+ * running and the model learns which of its calls changed the document.+ */+async function settleEndedReply(+ chat: Chat<UIMessage>,+ store: EditorStore,+ messageId: string,+ stopped: boolean+): Promise<void> {+ const run = currentRun(store)+ await run.settled()+ chat.messages = chat.messages.map((message) =>+ message.id === messageId+ ? settleMessage(message, {+ stopped,+ changed: (toolCallId) => run.changedCalls.has(toolCallId)+ })+ : message+ )+}+export function createChatSessionManager({isConfigured,isACPProvider,@@ -227,7 +256,8 @@ export function createChatSessionManager({isError: boolean}): void {- if (!isAbort && !isDisconnect && !isError) {+ if (isAbort) recordChatStopped(context)+ else if (!isDisconnect && !isError) {recordChatCompleted({ finishReason: finishReason ?? null }, context)}}@@ -348,7 +378,7 @@ export function createChatSessionManager({if (isACPProvider.value) transport = await createActiveACPTransport()else if (isHarnessProvider.value) transport = await createActiveHarnessTransport(sessionId)else transport = await createTransport(store, diagnosticContext)- chat = new Chat<UIMessage>({+ const created: Chat<UIMessage> = new Chat<UIMessage>({transport: {sendMessages: (options) => {diagnosticContext.runId = crypto.randomUUID()@@ -364,8 +394,14 @@ export function createChatSessionManager({const { errorName, errorCode, message, stack } = diagnosticErrorDetails(reportedError)recordChatFailed({ errorName, errorCode, message, stack }, diagnosticContext)},- onFinish: (event) => handleChatFinish(diagnosticContext, event)+ onFinish: (event) => {+ handleChatFinish(diagnosticContext, event)+ if (event.isAbort || event.isDisconnect || event.isError) {+ void settleEndedReply(created, store, event.message.id, event.isAbort)+ }+ }})+ chat = createdcurrentChatStore = storetransportDirty = false}diff --git a/src/app/ai/chat/turns.ts b/src/app/ai/chat/turns.tsindex e0837a986..abd536e09 100644--- a/src/app/ai/chat/turns.ts+++ b/src/app/ai/chat/turns.ts@@ -4,6 +4,7 @@ import { shallowReactive, shallowRef, type ShallowRef } from 'vue'import type { UndoEntry } from '@open-pencil/scene-graph/undo'+import { currentRun } from '@/app/ai/tools'import type { EditorStore } from '@/app/editor/active-store'interface TurnRecord {@@ -69,6 +70,16 @@ export function recordTurn(else turns.set(messageId, { store, entries: [...entries], reverted: false })}+/**+ * Records a reply's turn from its run once the run's last edit landed, so an edit a stopped+ * reply's tool finishes afterwards still belongs to it.+ */+export async function recordReplyTurn(messageId: string, store: EditorStore): Promise<void> {+ const run = currentRun(store)+ await run.settled()+ recordTurn(messageId, store, run.undoEntries)+}+export interface TurnEdits {count: number/** Whether the turn's edits are still the newest on the undo stack, so undoing them touches nothing else. */diff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.tsindex 9f97c71e4..926cda148 100644--- a/src/app/ai/tools/index.ts+++ b/src/app/ai/tools/index.ts@@ -21,6 +21,7 @@ import { aiToolDefinitions } from './catalog'import { recordToolChange } from './changes/capture'import { createMutex } from './mutex'import {+ currentRun,markRunChange,markRunWork,moveRunToPage,@@ -32,6 +33,7 @@ import {} from './run'export {+ currentRun,didHitStepLimit,endRun,markRunPreview,@@ -81,11 +83,19 @@ export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnostexecuteTool: async (def, figma, args, { toolCallId }) => {const pageId = figma.currentPageIdif (!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) && !runBaseline(store, pageId)) {- recordRunBaseline(store, store.snapshotPage(pageId))+ if (toolChangesDocument(def) && !run.baselines.has(pageId)) {+ recordRunBaseline(run, store.snapshotPage(pageId))}const undoBefore = store.undo.peekUndo()const finishChange = store.captureDocumentChange(pageId)@@ -93,6 +103,7 @@ export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnostreturn 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({@@ -103,7 +114,7 @@ export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnost}// 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, `AI: ${def.name}`, undoBefore)+ recordRunUndoEntry(store, run, `AI: ${def.name}`, undoBefore)// View tools (selection, viewport, pages) cannot change the document.if (toolChangesDocument(def)) {try {@@ -118,9 +129,12 @@ export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnost}try {// `switch_page` moves the run, and the user's view with it.- if (figma.currentPageId !== pageId) await moveRunToPage(store, figma.currentPageId)+ if (figma.currentPageId !== pageId) {+ await moveRunToPage(store, run, figma.currentPageId)+ }} finally {release()+ run.endTool()}}},diff --git a/src/app/ai/tools/run.ts b/src/app/ai/tools/run.tsindex cc201b6f2..aa107b01e 100644--- a/src/app/ai/tools/run.ts+++ b/src/app/ai/tools/run.ts@@ -8,30 +8,61 @@ import { getActiveEditorStore } from '@/app/editor/active-store'import type { EditorStore } from '@/app/editor/active-store'import { addAgent, agentPlacement, type AgentHandle } from '@/app/presence/registry'-class RunState {+/**+ * One reply's run: the page it works on, its step budget, and the edits it made. It ends once,+ * finished, stopped, or failed; a tool that was already running finishes into the run it+ * started in, even after that run ended, so its edit stays part of that reply.+ */+export class Run {currentSteps = 0/** Captured for the message in progress; settings changes apply to the next one. */- maxSteps = DEFAULT_AGENT_STEPS+ readonly maxSteps: number/** The page the run works on. The user's navigation does not move it; the agent's does. */- pageId: string | null = null- /** The built-in chat as other people see it; one per document, kept between replies. */- agent: AgentHandle | null = null+ pageId: string/** Each page as it was before the run first edited it, for `diff_changes`. */- baselines = new Map<string, PageSnapshot>()+ readonly baselines = new Map<string, PageSnapshot>()/** Undo entries the run's edits pushed, oldest first, so its turn can be reverted. */- undoEntries: UndoEntry[] = []-- start(maxSteps: number, pageId: string): void {- this.currentSteps = 0+ readonly undoEntries: UndoEntry[] = []+ /** Tool calls that changed the document, which a stopped reply's transcript reports. */+ readonly changedCalls = new Set<string>()+ /** False once the reply finished, was stopped, or failed; its agent no longer moves. */+ active = true+ private toolsInFlight = 0+ private whenSettled: Promise<void> = Promise.resolve()+ private settle: () => void = () => undefined++ constructor(maxSteps: number, pageId: string) {this.maxSteps = resolveAgentStepLimit(maxSteps)this.pageId = pageId- this.baselines = new Map()- this.undoEntries = []}hitLimit(): boolean {return this.currentSteps >= this.maxSteps}++ /** A tool started editing for this run; `settled` waits until every such tool is done. */+ beginTool(): void {+ if (this.toolsInFlight++ === 0) {+ this.whenSettled = new Promise((resolve) => {+ this.settle = resolve+ })+ }+ }++ endTool(): void {+ if (--this.toolsInFlight === 0) this.settle()+ }++ /** Resolves once no tool of this run is still editing. */+ settled(): Promise<void> {+ return this.whenSettled+ }+}++class RunState {+ run = new Run(DEFAULT_AGENT_STEPS, '')+ /** The built-in chat as other people see it; one per document, kept between replies. */+ agent: AgentHandle | null = null}const runStates = new WeakMap<EditorStore, RunState>()@@ -45,17 +76,26 @@ function getRunState(store?: EditorStore): RunState {return created}-/** Begin a run on the page the user is viewing. */-export function startRun(store: EditorStore, maxSteps: number, model?: string): void {- const run = getRunState(store)- run.start(maxSteps, store.state.currentPageId)- run.agent ??= addAgent(store, 'chat', model)- run.agent.update({ status: 'thinking', model, pageId: store.state.currentPageId })+/** Begin a run on the page the user is viewing, as a message is sent. */+export function startRun(store: EditorStore, maxSteps: number, model?: string): Run {+ const state = getRunState(store)+ const pageId = store.state.currentPageId+ state.run = new Run(maxSteps, pageId)+ state.agent ??= addAgent(store, 'chat', model)+ state.agent.update({ status: 'thinking', model, pageId })+ return state.run}-/** The reply finished, failed, or was stopped: the agent stays listed but leaves the canvas. */-export function endRun(store: EditorStore): void {- getRunState(store).agent?.update({+/**+ * 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.+ */+export function endRun(store: EditorStore, run = currentRun(store)): void {+ const state = getRunState(store)+ if (!run.active) return+ run.active = false+ if (state.run !== run) return+ state.agent?.update({status: 'idle',cursor: undefined,selection: undefined,@@ -63,12 +103,23 @@ export function endRun(store: EditorStore): void {})}+/** The run of the reply in progress, or of the last one. */+export function currentRun(store: EditorStore): Run {+ return getRunState(store).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+}+/*** Point the run's agent at JSX it is still streaming: the element that appeared last, with* outlines of what it builds, until the tool runs and `markRunWork` names the real layers.*/export function markRunPreview(store: EditorStore, focus: PreviewFocus): void {- getRunState(store).agent?.update({+ agentAtWork(store)?.update({status: 'editing',cursor: { ...focus.cursor, pageId: runPageId(store) },selection: undefined,@@ -78,10 +129,10 @@ export function markRunPreview(store: EditorStore, focus: PreviewFocus): void {/** Point the run's agent at nodes a tool just created or changed. */export function markRunWork(store: EditorStore, nodeIds: string[]): void {- const run = getRunState(store)+ const agent = agentAtWork(store)const placement = agentPlacement(store, nodeIds, runPageId(store))- if (!run.agent || !placement) return- run.agent.update({ status: 'editing', ...placement })+ if (!agent || !placement) return+ agent.update({ status: 'editing', ...placement })}/**@@ -104,31 +155,32 @@ export function markRunChange(store: EditorStore, change: DocumentChange): void}export function recordStep(store?: EditorStore): void {- getRunState(store).currentSteps+++ getRunState(store).run.currentSteps++}export function stepBudget(store: EditorStore): StepBudget {- const { currentSteps, maxSteps } = getRunState(store)+ const { currentSteps, maxSteps } = getRunState(store).runreturn { current: currentSteps, max: maxSteps }}export function didHitStepLimit(store?: EditorStore): boolean {- return getRunState(store).hitLimit()+ return getRunState(store).run.hitLimit()}/** The run's page, or the viewed page when no run has started or its page was deleted. */export function runPageId(store: EditorStore): string {- const { pageId } = getRunState(store)+ const { pageId } = getRunState(store).runreturn pageId && store.graph.getNode(pageId)?.type === 'CANVAS'? pageId: store.state.currentPageId}/** 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, pageId: string): Promise<void> {- const run = getRunState(store)+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) returnrun.pageId = pageId- run.agent?.update({ pageId })+ getRunState(store).agent?.update({ pageId })if (store.state.currentPageId !== pageId) await store.switchPage(pageId)}@@ -138,14 +190,13 @@ export function runAgentId(store: EditorStore): string | undefined {}/** Keep `snapshot` as the run's starting state of its page unless the run already edited it. */-export function recordRunBaseline(store: EditorStore, snapshot: PageSnapshot): void {+export function recordRunBaseline(run: Run, snapshot: PageSnapshot): void {const pageId = snapshot.values().next().value?.id- const { baselines } = getRunState(store)- if (pageId && !baselines.has(pageId)) baselines.set(pageId, snapshot)+ if (pageId && !run.baselines.has(pageId)) run.baselines.set(pageId, snapshot)}export function runBaseline(store: EditorStore, pageId: string): PageSnapshot | null {- return getRunState(store).baselines.get(pageId) ?? null+ return getRunState(store).run.baselines.get(pageId) ?? null}/**@@ -154,16 +205,16 @@ export function runBaseline(store: EditorStore, pageId: string): PageSnapshot |*/export function recordRunUndoEntry(store: EditorStore,+ run: Run,label: string,previous: UndoEntry | undefined): void {const entry = store.undo.peekUndo()- const { undoEntries } = getRunState(store)- if (entry !== previous && entry?.label === label && !undoEntries.includes(entry)) {- undoEntries.push(entry)+ if (entry !== previous && entry?.label === label && !run.undoEntries.includes(entry)) {+ run.undoEntries.push(entry)}}export function runUndoEntries(store: EditorStore): readonly UndoEntry[] {- return getRunState(store).undoEntries+ return getRunState(store).run.undoEntries}diff --git a/src/app/diagnostics/events/ai.ts b/src/app/diagnostics/events/ai.tsindex 1eddfd81b..17dc3f8d6 100644--- a/src/app/diagnostics/events/ai.ts+++ b/src/app/diagnostics/events/ai.ts@@ -21,6 +21,7 @@ const modelStepSchema = v.object({})const chatCompletedSchema = v.object({ finishReason: v.nullable(v.string()) })+const chatStoppedSchema = v.object({})const chatFailedSchema = v.object({errorName: v.string(),errorCode: v.optional(v.nullable(v.string())),@@ -40,7 +41,12 @@ const toolCompletedSchema = v.object({export type AIDiagnosticContext = Pick<DiagnosticEvent, 'sessionId' | 'runId'>function recordAIEvent(- name: 'model.step.completed' | 'chat.completed' | 'chat.failed' | 'tool.completed',+ name:+ | 'model.step.completed'+ | 'chat.completed'+ | 'chat.stopped'+ | 'chat.failed'+ | 'tool.completed',attributes: Record<string, DiagnosticValue>,schema: v.GenericSchema,context: AIDiagnosticContext = {},@@ -76,6 +82,11 @@ export function recordChatCompleted(recordAIEvent('chat.completed', input, chatCompletedSchema, context)}+/** The person stopped the reply before it finished. */+export function recordChatStopped(context?: AIDiagnosticContext): void {+ recordAIEvent('chat.stopped', {}, chatStoppedSchema, context)+}+export function recordChatFailed(input: v.InferOutput<typeof chatFailedSchema>,context?: AIDiagnosticContextdiff --git a/src/app/diagnostics/events/index.ts b/src/app/diagnostics/events/index.tsindex 42d81fc70..e22e14cf0 100644--- a/src/app/diagnostics/events/index.ts+++ b/src/app/diagnostics/events/index.ts@@ -1,4 +1,9 @@-export { recordChatCompleted, recordChatFailed, recordModelStepCompleted } from './ai'+export {+ recordChatCompleted,+ recordChatFailed,+ recordChatStopped,+ recordModelStepCompleted+} from './ai'export { recordDocumentFailure } from './document'export { preparationDurationBucket, recordPreparationOutcome } from './preparation'export { recordRuntimeError, type RuntimeErrorSource } from './runtime'diff --git a/src/app/diagnostics/summary.ts b/src/app/diagnostics/summary.tsindex 0cf052e8d..5ec18382b 100644--- a/src/app/diagnostics/summary.ts+++ b/src/app/diagnostics/summary.ts@@ -23,6 +23,7 @@ export type DiagnosticEventSummary = {/** The diagnostics messages a summary reads; the app's `diagnostics` i18n namespace has them. */export interface DiagnosticLabels {chatCompleted: string+ chatStopped: stringchatFailed: stringstorageFailed: stringdocumentFailed: string@@ -126,6 +127,7 @@ const DESCRIBE: Record<DiagnosticEventName, Describe> = {return [label, text(attributes.message) ? errorDetail(attributes) : duration]},'chat.completed': (attributes, labels) => [labels.chatCompleted, text(attributes.finishReason)],+ 'chat.stopped': (_attributes, labels) => [labels.chatStopped, null],'chat.failed': (attributes, labels) => [labels.chatFailed, errorDetail(attributes)],'runtime.error': (attributes, labels) => [labels.runtimeError({ name: text(attributes.errorName) ?? 'Error' }),diff --git a/src/app/diagnostics/types.ts b/src/app/diagnostics/types.tsindex f6579cf49..b0cff2136 100644--- a/src/app/diagnostics/types.ts+++ b/src/app/diagnostics/types.ts@@ -19,6 +19,7 @@ export type DiagnosticAttributes = Readonly<Record<string, DiagnosticValue>>export type DiagnosticEventName =| 'model.step.completed'| 'chat.completed'+ | 'chat.stopped'| 'chat.failed'| 'tool.completed'| 'runtime.error'diff --git a/src/app/presence/registry.ts b/src/app/presence/registry.tsindex e647a4903..b42bf6070 100644--- a/src/app/presence/registry.ts+++ b/src/app/presence/registry.ts@@ -34,6 +34,8 @@ interface Presence {moving: boolean/** Our agents the person stopped following mid-work; following them again waits until they rest. */declined: Set<string>+ /** The agent Follow agents started following, which ends when it rests; null for one picked. */+ autoFollowed: string | null}const presences = new WeakMap<EditorStore, Presence>()@@ -49,7 +51,8 @@ export function presenceOf(store: EditorStore): Presence {followPage: null,switching: null,moving: false,- declined: new Set()+ declined: new Set(),+ autoFollowed: null}presences.set(store, presence)store.onEditorEvent('page:changed', () => {@@ -170,7 +173,9 @@ function isWorking(agent: AgentPresence): boolean {* With Follow agents on, the view follows our agents while they work: whichever starts first* when nobody is followed, and the next one at work once the followed agent rests. Following* starts with the run, so leaving the page or moving the view while the agent thinks counts as- * stopping, and an agent the person stopped following is left alone until it rests.+ * stopping, and an agent the person stopped following is left alone until it rests. When the+ * last one rests, as its reply finishes, stops, or fails, following ends; an agent the person+ * picked to follow keeps its followers while it rests.*/function autoFollow(store: EditorStore): void {const presence = presenceOf(store)@@ -178,16 +183,24 @@ function autoFollow(store: EditorStore): void {for (const id of presence.declined) {if (!working.some((agent) => agent.id === id)) presence.declined.delete(id)}- if (!appPreferences.value.chat.followAgents) returnconst target = presence.following.value+ if (target?.kind !== 'agent' || target.agentId !== presence.autoFollowed) {+ presence.autoFollowed = null+ }+ if (!appPreferences.value.chat.followAgents) returnif (target?.kind === 'person') returnif (target && working.some((agent) => agent.id === target.agentId)) return// A followed agent of someone else's is theirs to stop; only a resting one of ours hands over.if (target && !presence.agents.value.some((agent) => agent.id === target.agentId)) returnconst next = working.find((agent) => !presence.declined.has(agent.id))- if (!next) return- presence.following.value = { kind: 'agent', agentId: next.id }- presence.followPage = store.state.currentPageId+ if (next) {+ presence.following.value = { kind: 'agent', agentId: next.id }+ presence.autoFollowed = next.id+ presence.followPage = store.state.currentPageId+ } else if (presence.autoFollowed !== null && target?.agentId === presence.autoFollowed) {+ presence.autoFollowed = null+ stopFollowing(store, false)+ }}/** Starts following our agents at work right away, for when Follow agents is turned on. */@@ -314,6 +327,8 @@ export function follow(store: EditorStore, target: FollowTarget | null): void {}const presence = presenceOf(store)presence.following.value = target+ // Picked by the person, so it keeps following an agent that rests.+ presence.autoFollowed = nullpresence.followPage = store.state.currentPageIdkeepFollowing(store)}diff --git a/src/components/chat/ChatMessage.stories.ts b/src/components/chat/ChatMessage.stories.tsindex 33dffc8f6..c120fcdf5 100644--- a/src/components/chat/ChatMessage.stories.ts+++ b/src/components/chat/ChatMessage.stories.ts@@ -1,5 +1,6 @@import type { Meta, StoryObj } from '@storybook/vue3-vite'import type { UIMessage } from 'ai'+import { expect, within } from 'storybook/test'import ChatMessage from './ChatMessage.vue'@@ -29,6 +30,23 @@ const reasoningMessage: UIMessage = {]}+/** A reply stopped mid-call, as the chat settles it: nothing reads as running any more. */+const stoppedMessage: UIMessage = {+ id: 'stopped-message',+ role: 'assistant',+ metadata: { stopped: true },+ parts: [+ { type: 'reasoning', text: 'Laying out a month grid.', state: 'done' },+ {+ type: 'tool-render',+ toolCallId: 'stopped-call',+ state: 'output-error',+ input: { jsx: '<Frame name="Calendar" />' },+ errorText: 'The reply ended before this call finished. It did not change the document.'+ }+ ]+}+type ChatMessageStoryArgs = {message: UIMessagestreaming?: boolean@@ -53,3 +71,12 @@ export const User: Story = { args: { message: userMessage } }export const Assistant: Story = { args: { message: assistantMessage } }export const Reasoning: Story = { args: { message: reasoningMessage } }export const Streaming: Story = { args: { message: assistantMessage, streaming: true } }++export const Stopped: Story = {+ args: { message: stoppedMessage },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(canvas.getByText('Stopped')).toBeVisible()+ await expect(canvas.queryByText('Thinking…')).toBeNull()+ }+}diff --git a/src/components/chat/ChatMessage.vue b/src/components/chat/ChatMessage.vueindex fba4e15cb..d39a11b0e 100644--- a/src/components/chat/ChatMessage.vue+++ b/src/components/chat/ChatMessage.vue@@ -10,6 +10,7 @@ import { attachmentsForMessage } from '@/app/ai/attachment/presentation/store'import type { AttachmentPresentation } from '@/app/ai/attachment/presentation/types'import { reasoningDisplay } from '@/app/ai/chat/preferences'import { visibleUserMessageText } from '@/app/ai/chat/presentation'+import { wasStopped } from '@/app/ai/chat/settle'import { groupMessageParts, type MessagePartGroup } from '@/app/ai/chat/tool-calls/display'import { revertOf } from '@/app/ai/chat/turns'import AttachmentList from '@/components/chat/attachment/AttachmentList.vue'@@ -83,6 +84,7 @@ async function copyResponse(): Promise<void> {// The AI SDK updates parts in place and replaces only the message, so copy each part for// the cards' computed state to see the new values.const reverted = computed(() => revertOf(message) !== null)+const stopped = computed(() => wasStopped(message))// A request that failed once its reply had started leaves the reply without content.const empty = computed(() => message.parts.every((part) => part.type === 'step-start'))const groups = computed(() => groupMessageParts(message.parts.map((part) => ({ ...part }))))@@ -120,7 +122,7 @@ function groupKey(group: MessagePartGroup): string {v-else-if="isReasoningUIPart(group.part) && group.part.text":text="group.part.text":display="reasoningDisplay"- :streaming="group.part.state === 'streaming'"+ :streaming="streaming && group.part.state === 'streaming'":thinking-label="ai.thinking":reasoning-label="ai.reasoning":duration-label="(seconds) => ai.thoughtFor({ seconds })"@@ -155,6 +157,7 @@ function groupKey(group: MessagePartGroup): string {:can-regenerate="canRegenerate":empty="empty":reverted="reverted"+ :stopped="stopped"@regenerate="emit('regenerate')"@revert="emit('revert')"@restore="emit('restore')"diff --git a/src/components/chat/turn/ChatTurnActions.vue b/src/components/chat/turn/ChatTurnActions.vueindex ec863a57b..950d9b38b 100644--- a/src/components/chat/turn/ChatTurnActions.vue+++ b/src/components/chat/turn/ChatTurnActions.vue@@ -10,7 +10,8 @@ const {messageId,canRegenerate = false,empty = false,- reverted = false+ reverted = false,+ stopped = false} = defineProps<{messageId: stringcanRegenerate?: boolean@@ -18,6 +19,8 @@ const {empty?: boolean/** The reply's edits were reverted; it stays in the chat, marked. */reverted?: boolean+ /** The user stopped the reply before it finished. */+ stopped?: boolean}>()const emit = defineEmits<{ regenerate: []; revert: []; restore: [] }>()const { ai } = useI18n()@@ -29,10 +32,18 @@ const restorable = computed(() => edits.value?.restorable === true)<template><div- v-if="revertable || reverted || canRegenerate"+ v-if="stopped || revertable || reverted || canRegenerate"class="flex flex-wrap items-center gap-1"data-slot="chat-turn-actions">+ <span+ v-if="stopped"+ class="inline-flex items-center gap-1 px-2 text-[11px] text-muted"+ data-slot="chat-turn-stopped"+ >+ <icon-lucide-circle-stop class="size-3" aria-hidden="true" />+ {{ ai.turnStopped }}+ </span><AppButtonv-if="reverted && restorable"size="xs"diff --git a/tests/app/ai/chat/settle.test.ts b/tests/app/ai/chat/settle.test.tsnew file mode 100644index 000000000..5bf41d44c--- /dev/null+++ b/tests/app/ai/chat/settle.test.ts@@ -0,0 +1,91 @@+import { expect, test } from 'bun:test'++import type { UIMessage } from 'ai'+import { reactive, toRaw } from 'vue'++import { settleMessage, wasStopped } from '@/app/ai/chat/settle'++function reply(parts: UIMessage['parts'], metadata?: unknown): UIMessage {+ return { id: 'reply', role: 'assistant', parts, metadata }+}++const call = (toolCallId: string, state: 'input-streaming' | 'input-available') =>+ state === 'input-streaming'+ ? ({ type: 'tool-create_shape', toolCallId, state, input: undefined } as const)+ : ({ type: 'tool-create_shape', toolCallId, state, input: { type: 'RECTANGLE' } } as const)++test('a stopped reply no longer reads as running, and says which calls changed the document', () => {+ const settled = settleMessage(+ reply([+ { type: 'reasoning', text: 'Planning', state: 'streaming' },+ { type: 'text', text: 'Drawing', state: 'streaming' },+ call('landed', 'input-available'),+ call('waiting', 'input-streaming')+ ]),+ { stopped: true, changed: (toolCallId) => toolCallId === 'landed' }+ )++ expect(settled.parts).toMatchObject([+ { type: 'reasoning', state: 'done' },+ { type: 'text', state: 'done' },+ {+ toolCallId: 'landed',+ state: 'output-error',+ errorText: expect.stringContaining('It changed the document')+ },+ {+ toolCallId: 'waiting',+ state: 'output-error',+ errorText: expect.stringContaining('did not change the document')+ }+ ])+ expect(wasStopped(settled)).toBe(true)+})++test('a failed reply settles its parts without being marked stopped, keeping its metadata', () => {+ const settled = settleMessage(+ reply([{ type: 'reasoning', text: 'Planning', state: 'streaming' }], { reverted: true }),+ { stopped: false }+ )+ expect(settled.parts).toMatchObject([{ state: 'done' }])+ expect(settled.metadata).toEqual({ reverted: true })+ expect(wasStopped(settled)).toBe(false)+})++test('a reopened reply saved mid-call does not claim what the call did', () => {+ const [part] = settleMessage(reply([call('saved', 'input-available')]), { stopped: false }).parts+ expect(part).toMatchObject({+ state: 'output-error',+ errorText: expect.stringContaining('reported back')+ })+})++test('a finished reply is left as it is', () => {+ const finished = reply([+ { type: 'text', text: 'Done', state: 'done' },+ {+ type: 'tool-create_shape',+ toolCallId: 'done',+ state: 'output-available',+ input: { type: 'RECTANGLE' },+ output: { id: '0:1' }+ }+ ])+ expect(settleMessage(finished, { stopped: false })).toBe(finished)+})++test("a reply settled from the chat's reactive state can still be saved", () => {+ const chat = reactive({+ messages: [+ reply([+ { type: 'reasoning', text: 'Planning', state: 'streaming' },+ call('c', 'input-available')+ ])+ ]+ })+ const [message] = chat.messages+ if (!message) throw new Error('No message')+ const settled = settleMessage(message, { stopped: true, changed: () => false })+ // Conversations are saved with `structuredClone`, which cannot copy Vue's proxies.+ expect(() => structuredClone(toRaw(settled))).not.toThrow()+})diff --git a/tests/app/ai/tools/run.test.ts b/tests/app/ai/tools/run.test.tsindex 5203c33d5..fe894d4e8 100644--- a/tests/app/ai/tools/run.test.ts+++ b/tests/app/ai/tools/run.test.ts@@ -8,7 +8,7 @@ import { toRaw } from 'vue'import { FigmaAPI } from '@open-pencil/core/figma-api'import { createToolLoopTransport } from '@/app/ai/chat/transports'-import { endRun, markRunPreview, runPageId, startRun } from '@/app/ai/tools'+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 * as figmaFactory from '@/app/automation/bridge/figma-factory'@@ -254,3 +254,111 @@ test('the agent moves through streamed JSX, then onto the layers the tool made',store.preparationController.dispose()}})++const rectangleCall = (toolCallId: string, x: number): StreamChunk => ({+ type: 'tool-call',+ toolCallId,+ toolName: 'create_shape',+ input: JSON.stringify({ type: 'RECTANGLE', x, y: 0, width: 10, height: 10 })+})++/** Start one message whose model calls `calls` in one step, and read it in the background. */+async function startMessage(store: EditorStore, calls: StreamChunk[], signal: AbortSignal) {+ const model = new MockLanguageModelV4({+ doStream: async () => ({+ stream: simulateReadableStream<StreamChunk>({+ initialDelayInMs: null,+ chunkDelayInMs: null,+ chunks: [+ ...calls,+ {+ type: 'finish',+ finishReason: { unified: 'tool-calls', raw: undefined },+ usage: MOCK_USAGE+ }+ ]+ })+ })+ })+ const transport = createToolLoopTransport({+ store,+ providerID: 'openai',+ model,+ effectiveModelID: 'test',+ maxOutputTokens: 100,+ thinkingLevel: () => 'default'+ })+ const stream = await transport.sendMessages({+ trigger: 'submit-message',+ chatId: 'stop',+ messageId: undefined,+ abortSignal: signal,+ messages: [{ id: 'user', role: 'user', parts: [{ type: 'text', text: 'Draw' }] }]+ })+ const reader = stream.getReader()+ async function drain() {+ while (!(await reader.read()).done);+ }+ // Cancelling the reader on Stop rejects the read in progress; the read just ends.+ const reading = drain().catch(() => undefined)+ return { reader, reading }+}++/** Hold every layout mutation until `release`, reporting when the first one starts. */+function holdMutations(store: EditorStore) {+ let release: () => void = () => undefined+ const gate = new Promise<void>((resolve) => {+ release = resolve+ })+ let markStarted: () => void = () => undefined+ const started = new Promise<void>((resolve) => {+ markStarted = resolve+ })+ const run = store.runMutationWithLayout.bind(store)+ spyOn(store, 'runMutationWithLayout').mockImplementation(async (...args) => {+ markStarted()+ await gate+ return run(...args)+ })+ return { started, release }+}++test('a tool still running at Stop finishes into its reply without bringing the agent back', async () => {+ await withStore(async (store, { a }) => {+ const held = holdMutations(store)+ const controller = new AbortController()+ const { reader, reading } = await startMessage(+ store,+ [rectangleCall('first', 0), rectangleCall('second', 40)],+ controller.signal+ )+ await held.started+ const run = currentRun(store)++ controller.abort()+ void reader.cancel()+ await reading+ const agent = () => expectDefined(presenceOf(store).agents.value[0], 'agent')+ expect(agent()).toMatchObject({ status: 'idle', cursor: undefined })+ expect(presenceOf(store).following.value).toBeNull()++ held.release()+ await run.settled()+ // The running call's edit lands and stays this reply's; the one waiting its turn never runs.+ expect(store.graph.getChildren(a)).toHaveLength(1)+ expect(run.undoEntries).toHaveLength(1)+ expect([...run.changedCalls]).toEqual(['first'])+ expect(agent()).toMatchObject({ status: 'idle', cursor: undefined, selection: undefined })+ })+})++test('a reply stopped before it reaches the model leaves the agent at rest', async () => {+ await withStore(async (store) => {+ const controller = new AbortController()+ controller.abort()+ const { reading } = await startMessage(store, [rectangleCall('late', 0)], controller.signal)+ await reading+ expect(presenceOf(store).agents.value[0]?.status).toBe('idle')+ expect(currentRun(store).active).toBe(false)+ })+})diff --git a/tests/app/presence/auto-follow.test.ts b/tests/app/presence/auto-follow.test.tsindex 1076c6434..3a59315e8 100644--- a/tests/app/presence/auto-follow.test.ts+++ b/tests/app/presence/auto-follow.test.ts@@ -84,3 +84,24 @@ test('with Follow agents off, agents are followed only by clicking Follow', () =followWorkingAgents(store)expect(following(store)).toEqual({ kind: 'agent', agentId: agent.id })})++test('following that Follow agents started ends when the agent rests', () => {+ const { store, pageId } = setup()+ const agent = addAgent(store, 'chat')+ agent.update({ status: 'editing', cursor: { x: 10, y: 10, pageId } })+ expect(following(store)).toEqual({ kind: 'agent', agentId: agent.id })++ // A reply finishing, stopping, or failing all put the agent to rest.+ agent.update({ status: 'idle', cursor: undefined })+ expect(following(store)).toBeNull()+})++test('an agent the person picked to follow keeps its followers while it rests', () => {+ const { store, pageId } = setup()+ const agent = addAgent(store, 'chat')+ agent.update({ status: 'editing', cursor: { x: 10, y: 10, pageId } })+ follow(store, { kind: 'agent', agentId: agent.id })++ agent.update({ status: 'idle', cursor: undefined })+ expect(following(store)).toEqual({ kind: 'agent', agentId: agent.id })+})diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex 26cb4be08..0651fe24b 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -130,6 +130,7 @@ ja:designCheck.ruleTouchTargetSizeHelpja:diagnostics.acpFailedja:diagnostics.chatCompletedja:diagnostics.chatFailed+ja:diagnostics.chatStoppedja:diagnostics.descriptionja:diagnostics.eventCountja:diagnostics.mcpFailed@@ -328,6 +329,7 @@ zh-cn:designCheck.ruleTouchTargetSizeHelpzh-cn:diagnostics.acpFailedzh-cn:diagnostics.chatCompletedzh-cn:diagnostics.chatFailed+zh-cn:diagnostics.chatStoppedzh-cn:diagnostics.descriptionzh-cn:diagnostics.eventCountzh-cn:diagnostics.mcpFailed