Skip to content

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

feat(ai): show AI edits undone in the editor in the chat, and tell the AI (#1078)

Danila Poyarkovd874f1083e80
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9687c87a8..930a96b00 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -105,7 +105,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. 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.
+- 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. Edit → Undo counts the same as reverting: each AI edit you undo marks its tool call *Undone*, a reply with only some edits undone says how many, and a reply with all of them undone stays in the chat dimmed and marked *Changes reverted*, also after reopening the conversation. Your next message tells the AI which of its edits were undone or redone since it last heard, so it does not build on edits that are gone, and an edit undone while the AI is still working is noted on its next tool result. **Restore changes** on the reply, or Edit → Redo, brings undone edits back and removes their marks 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.
diff --git a/packages/docs/.vitepress/sidebars.ts b/packages/docs/.vitepress/sidebars.ts
index 649fec5ab..be4127c10 100644
--- a/packages/docs/.vitepress/sidebars.ts
+++ b/packages/docs/.vitepress/sidebars.ts
@@ -125,6 +125,7 @@ export const developmentSidebar = (
...(!prefix
? [
{ text: 'Roadmap', link: '/development/roadmap' },
+ { text: 'AI Chat Replies', link: '/development/ai-chat' },
{ text: 'Behaviours and Preview', link: '/development/behaviours-and-preview' },
{ text: 'Navigation Performance', link: '/development/navigation-performance' },
{ text: 'Renderer Lifecycle', link: '/development/renderer-lifecycle' },
diff --git a/packages/docs/development/ai-chat.md b/packages/docs/development/ai-chat.md
new file mode 100644
index 000000000..33e76ba18
--- /dev/null
+++ b/packages/docs/development/ai-chat.md
@@ -0,0 +1,57 @@
+# AI chat replies
+
+How the built-in AI chat turns a message into edits, how a reply ends, and how what happens to its edits afterwards reaches the transcript and the model. ACP and Pi chats share the transcript, the saved conversation, and the marks on a reply, but run their own tool loop and agent presence.
+
+## A message goes out
+
+`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` 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:
+
+- 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;
+- each page as it was before the run first edited it, for `diff_changes`;
+- every undo entry its calls pushed, with the tool and call that pushed it;
+- the calls that changed the document, and the undone calls it already told the model about.
+
+The chat's agent is one presence entry per document (`presence/registry.ts`). It shows as thinking when the run starts and points at the layers each call changed, on whichever page they are. With Follow agents on, following starts with the run and ends when the agent rests and none of your other agents is at work. An agent you chose to follow keeps you with it while it rests.
+
+## A tool call
+
+`tools/index.ts` runs every call through `executeCall`:
+
+- 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.
+- 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.
+
+## A reply ends
+
+A 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`):
+
+- 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;
+- a stopped reply is marked stopped.
+
+Diagnostics 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.
+
+## Undo and the model
+
+A turn keeps the reply's calls and their undo entries. On every undo history change, each turn works out which of its calls are undone with `UndoManager.stateOf`: an entry on the redo stack is undone, one on the undo stack applied. An entry that left the history keeps its last state; undone and then cleared from Redo by a new edit, it stays undone. Changes are written to the reply's metadata, and the transcript reads only the metadata.
+
+Edit → Undo and the chat's **Revert changes** therefore end in the same state: Revert undoes the reply's edits still applied, when they are the newest on the undo stack, and **Restore changes** redoes its undone edits, when Redo would bring exactly those back next.
+
+`undoToReport` compares each reply's undone calls with what the model was last told, and the next message carries the difference as a note. The report records the message that carried it. If that message is sent again, for example when you edit it, the report is made again.
+
+## Saved conversations
+
+A reply's metadata (`chat/metadata.ts`) keeps whether you stopped it, and its edits with those undone and what the model was last told. Conversations save messages with `structuredClone`, so metadata is written from the plain message, never from the chat's reactive copy. Reopening a conversation settles any reply saved mid-way. The undo history does not survive closing a document, so a reopened reply keeps its marks but offers no Revert or Restore.
diff --git a/packages/docs/programmable/ai-chat.md b/packages/docs/programmable/ai-chat.md
index 2b5d03493..076421003 100644
--- a/packages/docs/programmable/ai-chat.md
+++ b/packages/docs/programmable/ai-chat.md
@@ -82,7 +82,23 @@ The configurable tool catalog covers these categories; the tools offered to a mo
## Visual Verification
-The assistant can verify its work visually. When `export_image` is enabled, it can capture a screenshot after creating or modifying designs and checks the result against the original request. This catches layout issues, missing elements, and color mismatches that text-only responses would miss. `diff_visual`, enabled by default, compares an edited node with a reference copy and returns the changed pixels and region, so the assistant can confirm an edit stayed within its target.
+The assistant can verify its work visually. With `export_image`, on by default, it can capture a screenshot after creating or modifying designs and checks the result against the original request. This catches layout issues, missing elements, and color mismatches that text-only responses would miss. `diff_visual`, enabled by default, compares an edited node with a reference copy and returns the changed pixels and region, so the assistant can confirm an edit stayed within its target.
+
+## Stopping a reply
+
+**Stop** ends a reply at once. A tool call already running finishes, and its edit counts as part of the reply; calls still waiting for their turn change nothing. The reply is marked *Stopped*, its reasoning and any unfinished calls stop showing as running, and your next message tells the assistant whether those calls changed the document.
+
+## Undoing the assistant's edits
+
+Each tool call that changes the document is one step in Edit → Undo. Undoing it with <kbd>⌘</kbd><kbd>Z</kbd> marks the call *Undone* in the chat. A reply with only some edits undone says how many; one with all of them undone is dimmed and marked *Changes reverted*. Redo removes the marks. The marks are saved with the conversation.
+
+**Revert changes** on a reply undoes its edits while nothing has been edited since, and **Restore changes** brings undone edits back while Redo still can. **Regenerate** and editing your last message undo the replaced reply's edits first when they can.
+
+Your next message tells the assistant which of its edits you undid or redid, so it does not build on edits that are gone. If you undo the assistant's edits while it is still working, it hears about it with its next tool call.
+
+## Following the assistant
+
+With **Follow agents** on, the crosshair button at the top of the AI panel, your view follows the assistant while it works, including to another page when it edits layers there. Following ends when the reply finishes, is stopped, or fails. Clicking, scrolling, zooming, switching pages, or Escape stops following yourself.
## Example Prompts
@@ -101,6 +117,6 @@ The assistant can verify its work visually. When `export_image` is enabled, it c
- Select nodes before asking — the assistant knows what's selected.
- Be specific about colors, sizes, and positions for precise results.
- The assistant can modify multiple nodes in one message.
-- You can browse other pages while a reply runs: the assistant keeps working on the page where the message started, and its previews show when you return. While you're away, the chat says which page it is working on, with **Go to page** to return. If the assistant switches pages itself, your view follows.
-- Use "undo" in the editor if you don't like the result — AI mutations support full undo.
+- You can browse other pages while a reply runs: the assistant keeps working on the page where the message started, and its previews show when you return. While you're away, the chat says which page it is working on, with **Go to page** to return.
+- Undo anything you don't like with Edit → Undo or **Revert changes**; the chat and the assistant both see it.
- All layout is recomputed automatically after each tool execution.
diff --git a/packages/scene-graph/src/undo.ts b/packages/scene-graph/src/undo.ts
index 48a819d04..50e63bffb 100644
--- a/packages/scene-graph/src/undo.ts
+++ b/packages/scene-graph/src/undo.ts
@@ -169,6 +169,16 @@ export class UndoManager {
return this.redoStack.at(-1 - depth)
}
+ /**
+ * Whether `entry` is applied (on the undo stack) or undone (on the redo stack); null once it
+ * left the history, trimmed or dropped when an edit cleared Redo.
+ */
+ stateOf(entry: UndoEntry): 'applied' | 'undone' | null {
+ if (this.undoStack.includes(entry)) return 'applied'
+ if (this.redoStack.includes(entry)) return 'undone'
+ return null
+ }
+
get undoLabel(): string | null {
return this.undoStack.at(-1)?.label ?? null
}
diff --git a/packages/scene-graph/tests/undo/peek.test.ts b/packages/scene-graph/tests/undo/peek.test.ts
index a32d33784..03a9e22bb 100644
--- a/packages/scene-graph/tests/undo/peek.test.ts
+++ b/packages/scene-graph/tests/undo/peek.test.ts
@@ -35,3 +35,20 @@ test('peeks entries from the top of the redo stack, the next Redo first', () =>
undo.redo()
expect(undo.peekRedo()).toBe(second)
})
+
+test('stateOf says whether an entry is applied, undone, or gone from the history', () => {
+ const undo = new UndoManager()
+ const noop = () => undefined
+ const entry = (label: string) => ({ label, forward: noop, inverse: noop })
+ const first = entry('First')
+ const second = entry('Second')
+ undo.push(first)
+ undo.push(second)
+ undo.undo()
+ expect(undo.stateOf(first)).toBe('applied')
+ expect(undo.stateOf(second)).toBe('undone')
+
+ // A new edit clears Redo, so the undone entry leaves the history.
+ undo.push(entry('Third'))
+ expect(undo.stateOf(second)).toBeNull()
+})
diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.json
index a956bd224..f7a209bd1 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",
+ "turnPartlyUndone": "{undone} von {total} Änderungen rückgängig gemacht",
"turnStopped": "Gestoppt",
"restoreTurn": "Änderungen wiederherstellen",
"regenerate": "Neu generieren",
@@ -45,6 +46,7 @@
"resendMessage": "Erneut senden",
"responseCopied": "Antwort kopiert",
"toolFinished": "Fertig",
+ "toolUndone": "Rückgängig gemacht",
"toolRunning": "Wird ausgeführt…",
"toolError": "Fehler",
"toolInput": "Eingabe",
diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.json
index b327c2136..61814676c 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",
+ "turnPartlyUndone": "{undone} de {total} cambios deshechos",
"turnStopped": "Detenida",
"restoreTurn": "Restaurar cambios",
"regenerate": "Regenerar",
@@ -45,6 +46,7 @@
"resendMessage": "Enviar de nuevo",
"responseCopied": "Respuesta copiada",
"toolFinished": "Hecho",
+ "toolUndone": "Deshecho",
"toolRunning": "Ejecutando…",
"toolError": "Error",
"toolInput": "Entrada",
diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.json
index eada484a0..7ec93bf38 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",
+ "turnPartlyUndone": "{undone} modifications sur {total} annulées",
"turnStopped": "Arrêtée",
"restoreTurn": "Rétablir les modifications",
"regenerate": "Régénérer",
@@ -45,6 +46,7 @@
"resendMessage": "Renvoyer",
"responseCopied": "Réponse copiée",
"toolFinished": "Terminé",
+ "toolUndone": "Annulé",
"toolRunning": "Exécution…",
"toolError": "Erreur",
"toolInput": "Entrée",
diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.json
index 78cb5abbe..bc56a75d1 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",
+ "turnPartlyUndone": "{undone} di {total} modifiche annullate",
"turnStopped": "Interrotta",
"restoreTurn": "Ripristina modifiche",
"regenerate": "Rigenera",
@@ -45,6 +46,7 @@
"resendMessage": "Invia di nuovo",
"responseCopied": "Risposta copiata",
"toolFinished": "Fine",
+ "toolUndone": "Annullato",
"toolRunning": "Esecuzione…",
"toolError": "Errore",
"toolInput": "Dati in ingresso",
diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.json
index ebaa85a01..ef2486e39 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": "変更を取り消しました",
+ "turnPartlyUndone": "{total} 件中 {undone} 件の変更を取り消しました",
"turnStopped": "停止しました",
"restoreTurn": "変更を元に戻す",
"regenerate": "再生成",
@@ -45,6 +46,7 @@
"resendMessage": "再送信",
"responseCopied": "回答をコピーしました",
"toolFinished": "完了",
+ "toolUndone": "取り消し済み",
"toolRunning": "実行中…",
"toolError": "エラー",
"toolInput": "入力",
diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.json
index 4e8add029..5e02f2270 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",
+ "turnPartlyUndone": "Cofnięto {undone} z {total} zmian",
"turnStopped": "Zatrzymano",
"restoreTurn": "Przywróć zmiany",
"regenerate": "Wygeneruj ponownie",
@@ -45,6 +46,7 @@
"resendMessage": "Wyślij ponownie",
"responseCopied": "Skopiowano odpowiedź",
"toolFinished": "Gotowe",
+ "toolUndone": "Cofnięto",
"toolRunning": "Uruchamianie…",
"toolError": "Błąd",
"toolInput": "Wejście",
diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.json
index 4f3c4e3fc..d5467ce6d 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": "Изменения отменены",
+ "turnPartlyUndone": "Отменено изменений: {undone} из {total}",
"turnStopped": "Остановлено",
"restoreTurn": "Вернуть изменения",
"regenerate": "Сгенерировать заново",
@@ -45,6 +46,7 @@
"resendMessage": "Отправить снова",
"responseCopied": "Ответ скопирован",
"toolFinished": "Готово",
+ "toolUndone": "Отменено",
"toolRunning": "Выполняется…",
"toolError": "Ошибка",
"toolInput": "Вход",
diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.json
index ef10a162e..dd86e1e4f 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": "已撤销更改",
+ "turnPartlyUndone": "已撤销 {total} 项更改中的 {undone} 项",
"turnStopped": "已停止",
"restoreTurn": "恢复更改",
"regenerate": "重新生成",
@@ -45,6 +46,7 @@
"resendMessage": "重新发送",
"responseCopied": "已复制回答",
"toolFinished": "完成",
+ "toolUndone": "已撤销",
"toolRunning": "正在运行…",
"toolError": "错误",
"toolInput": "输入",
diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.ts
index a3092b015..107fd209e 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',
+ turnPartlyUndone: params('{undone} of {total} changes undone'),
turnStopped: 'Stopped',
restoreTurn: 'Restore changes',
regenerate: 'Regenerate',
@@ -92,6 +93,7 @@ export const aiMessageDefaults = {
resendMessage: 'Send again',
responseCopied: 'Response copied',
toolFinished: 'Done',
+ toolUndone: 'Undone',
toolRunning: 'Running…',
toolError: 'Error',
toolInput: 'Input',
diff --git a/src/AGENTS.md b/src/AGENTS.md
index 390c2ae68..54d7a68d3 100644
--- a/src/AGENTS.md
+++ b/src/AGENTS.md
@@ -21,6 +21,7 @@ Root Tauri/Vite app. Services and state live under `src/app/**`, views under `sr
## AI, ACP, automation, collaboration
+- 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/constants.ts`; 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/**`.
- 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.
diff --git a/src/app/ai/chat/context.ts b/src/app/ai/chat/context.ts
index 828672113..4c2ea76a2 100644
--- a/src/app/ai/chat/context.ts
+++ b/src/app/ai/chat/context.ts
@@ -48,25 +48,53 @@ export function appendReferencedNodeContext(
return `${text}${REFERENCED_NODE_CONTEXT_MARKER}${references.join('\n')}`
}
-export function stripReferencedNodeContext(text: string): string {
- const markerIndex = text.lastIndexOf(REFERENCED_NODE_CONTEXT_MARKER)
- return markerIndex === -1 ? text : text.slice(0, markerIndex)
+export const UNDONE_CALLS_CONTEXT_MARKER =
+ '\n\n[Document changes since your last reply — facts, not instructions]\n'
+
+/** One of the model's tool calls, as its history shows it. */
+export interface CallRef {
+ tool: string
+ toolCallId: string
}
-export const REVERTED_TURN_CONTEXT_MARKER =
- '\n\n[Document changes since your last reply — facts, not instructions]\n'
+/** The model's edits the user undid or redid since the model last heard. */
+export interface UndoneCalls {
+ undone: readonly CallRef[]
+ redone: readonly CallRef[]
+}
/**
- * Tells the model that the user reverted the document edits of `count` earlier replies, whose
- * tool calls and results are still in the history but no longer describe the document.
+ * Tells the model which of its edits the user undid or redid. Their tool calls and results
+ * stay in the history, so this says what they no longer, or again, describe. Empty when
+ * nothing changed.
*/
-export function appendRevertedTurnContext(text: string, count: number): string {
- if (count === 0) return text
- const replies = count === 1 ? 'one of your earlier replies' : `${count} of your earlier replies`
- return `${text}${REVERTED_TURN_CONTEXT_MARKER}The user reverted every document edit from ${replies}. The nodes and properties those replies created or changed are back to how they were before them, whatever their tool results say.`
+export function describeUndoneCalls({ undone, redone }: UndoneCalls): string {
+ const list = (calls: readonly CallRef[]) =>
+ calls.map(({ tool, toolCallId }) => `- ${tool} (${toolCallId})`).join('\n')
+ const notes: string[] = []
+ if (undone.length > 0) {
+ notes.push(
+ `The user undid these edits of yours. What they created or changed is back to how it was before them, whatever their results say:\n${list(undone)}`
+ )
+ }
+ if (redone.length > 0) {
+ notes.push(`The user redid these edits of yours, so they apply again:\n${list(redone)}`)
+ }
+ return notes.join('\n')
+}
+
+export function appendUndoneCallsContext(text: string, calls: UndoneCalls): string {
+ const description = describeUndoneCalls(calls)
+ return description ? `${text}${UNDONE_CALLS_CONTEXT_MARKER}${description}` : text
}
-export function stripRevertedTurnContext(text: string): string {
- const markerIndex = text.lastIndexOf(REVERTED_TURN_CONTEXT_MARKER)
- return markerIndex === -1 ? text : text.slice(0, markerIndex)
+/** Each note the chat adds to a request for the model only starts with one of these. */
+const MODEL_NOTE_MARKERS = [REFERENCED_NODE_CONTEXT_MARKER, UNDONE_CALLS_CONTEXT_MARKER]
+
+/** What the person wrote, without the notes the chat added for the model after it. */
+export function stripModelNotes(text: string): string {
+ const starts = MODEL_NOTE_MARKERS.map((marker) => text.indexOf(marker)).filter(
+ (index) => index !== -1
+ )
+ return starts.length === 0 ? text : text.slice(0, Math.min(...starts))
}
diff --git a/src/app/ai/chat/metadata.ts b/src/app/ai/chat/metadata.ts
new file mode 100644
index 000000000..533857f20
--- /dev/null
+++ b/src/app/ai/chat/metadata.ts
@@ -0,0 +1,61 @@
+import type { UIMessage } from 'ai'
+import * as v from 'valibot'
+import { toRaw } from 'vue'
+
+/**
+ * What the chat keeps about a reply in its message metadata, which conversations store, so
+ * the transcript shows the same after reopening: whether the user stopped it, and its edits
+ * with those undone and what the model was last told about them.
+ */
+
+const MetadataRecord = v.record(v.string(), v.unknown())
+
+/** A message's metadata as a record; the AI SDK leaves its type open. */
+export function messageMetadata(message: UIMessage): Record<string, unknown> {
+ return v.is(MetadataRecord, message.metadata) ? message.metadata : {}
+}
+
+/**
+ * The message with `patch` merged into its metadata. It is built from the plain message: the
+ * chat's messages are reactive, and a copy carrying Vue proxies cannot be saved.
+ */
+export function withMetadata(message: UIMessage, patch: Record<string, unknown>): UIMessage {
+ const raw = toRaw(message)
+ return { ...raw, metadata: { ...messageMetadata(raw), ...structuredClone(patch) } }
+}
+
+/** Replaces one of a chat's messages, by its ID. */
+export function updateMessage(
+ chat: { messages: UIMessage[] },
+ messageId: string,
+ change: (message: UIMessage) => UIMessage
+): void {
+ chat.messages = chat.messages.map((message) =>
+ message.id === messageId ? change(message) : message
+ )
+}
+
+const StoppedMetadata = v.object({ stopped: v.literal(true) })
+
+/** Whether the user stopped the reply before it finished. */
+export function wasStopped(message: UIMessage): boolean {
+ return v.is(StoppedMetadata, message.metadata)
+}
+
+/** A reply's edits, those undone, and what the model was last told and which message told it. */
+const ReplyUndoSchema = v.object({
+ edits: v.array(v.object({ tool: v.string(), toolCallId: v.string() })),
+ undone: v.array(v.string()),
+ reported: v.optional(v.object({ undone: v.array(v.string()), in: v.string() }))
+})
+
+export type ReplyUndo = v.InferOutput<typeof ReplyUndoSchema>
+
+export function undoOf(message: UIMessage): ReplyUndo | null {
+ const parsed = v.safeParse(ReplyUndoSchema, messageMetadata(message).undo)
+ return parsed.success ? parsed.output : null
+}
+
+export function withUndo(message: UIMessage, undo: ReplyUndo): UIMessage {
+ return withMetadata(message, { undo })
+}
diff --git a/src/app/ai/chat/presentation.ts b/src/app/ai/chat/presentation.ts
index 8c78823db..c380a482c 100644
--- a/src/app/ai/chat/presentation.ts
+++ b/src/app/ai/chat/presentation.ts
@@ -1,6 +1,6 @@
import { shallowReactive } from 'vue'
-import { stripReferencedNodeContext, stripRevertedTurnContext } from '@/app/ai/chat/context'
+import { stripModelNotes } from '@/app/ai/chat/context'
const visibleText = shallowReactive(new Map<string, string>())
@@ -9,8 +9,7 @@ export function visibleMessageText(messageId: string, fallback: string): string
}
export function visibleUserMessageText(messageId: string, text: string): string {
- // The revert note comes after any referenced nodes, so it goes first.
- return visibleMessageText(messageId, stripReferencedNodeContext(stripRevertedTurnContext(text)))
+ return visibleMessageText(messageId, stripModelNotes(text))
}
export function setVisibleMessageText(messageId: string, text: string): void {
diff --git a/src/app/ai/chat/settle.ts b/src/app/ai/chat/settle.ts
index 13fd7c381..573754437 100644
--- a/src/app/ai/chat/settle.ts
+++ b/src/app/ai/chat/settle.ts
@@ -1,13 +1,7 @@
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)
-}
+import { wasStopped, withMetadata } from '@/app/ai/chat/metadata'
export interface SettleOptions {
/** Whether the user stopped the reply, rather than it failing or being cut off. */
@@ -51,6 +45,6 @@ export function settleMessage(live: UIMessage, { stopped, changed }: SettleOptio
})
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 }
+ const settled = { ...message, parts }
+ return stopped ? withMetadata(settled, { stopped: true }) : settled
}
diff --git a/src/app/ai/chat/submission/reverts.ts b/src/app/ai/chat/submission/reverts.ts
deleted file mode 100644
index 5ae60b396..000000000
--- a/src/app/ai/chat/submission/reverts.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { tryOnScopeDispose } from '@vueuse/core'
-import type { UIMessage } from 'ai'
-import { toRaw, type Ref } from 'vue'
-
-import { appendRevertedTurnContext } from '@/app/ai/chat/context'
-import type { ChatInstance } from '@/app/ai/chat/submission/types'
-import {
- onTurnRestored,
- revertsToReport,
- revertTurn,
- withRevert,
- type Revert
-} from '@/app/ai/chat/turns'
-
-interface RevertRecordOptions {
- chat: Ref<ChatInstance | null>
- flush?: () => Promise<void>
-}
-
-/**
- * Keeps reverted replies marked in the chat and tells the model about them: a revert marks
- * the reply, the next request carries a note for each revert no request has reported yet, and
- * Redo bringing the edits back removes the mark.
- */
-export function useRevertRecords(options: RevertRecordOptions) {
- function mark(chat: ChatInstance, ids: readonly string[], revert: Revert | null): void {
- if (ids.length === 0) return
- const marked = new Set(ids)
- // The chat's messages are reactive; a copy of one would carry its proxied parts, which
- // saving the conversation cannot clone.
- chat.messages = chat.messages.map((message) =>
- marked.has(message.id) ? withRevert(toRaw(message), revert) : message
- )
- }
-
- const stopRestored = onTurnRestored((messageId) => {
- const chat = options.chat.value
- if (!chat?.messages.some((message) => message.id === messageId)) return
- mark(chat, [messageId], null)
- void options.flush?.().catch(() => undefined)
- })
- tryOnScopeDispose(stopRestored)
-
- /** Undoes a reply's edits and marks it; false when its edits are no longer on top. */
- function revert(chat: ChatInstance, messageId: string): boolean {
- if (!revertTurn(messageId)) return false
- mark(chat, [messageId], {})
- return true
- }
-
- /** `text` with a note about the reverts `history` has not reported, and those reverts. */
- function note(text: string, history: readonly UIMessage[]) {
- const reverts = revertsToReport(history)
- return { text: appendRevertedTurnContext(text, reverts.length), reverts }
- }
-
- /** Records that `request` carried the note about `reverts`. */
- function reported(chat: ChatInstance, reverts: readonly string[], request: string): void {
- mark(chat, reverts, { reportedIn: request })
- }
-
- return { revert, note, reported }
-}
diff --git a/src/app/ai/chat/submission/undone.ts b/src/app/ai/chat/submission/undone.ts
new file mode 100644
index 000000000..e4c3db28d
--- /dev/null
+++ b/src/app/ai/chat/submission/undone.ts
@@ -0,0 +1,83 @@
+import { tryOnScopeDispose } from '@vueuse/core'
+import type { UIMessage } from 'ai'
+import type { Ref } from 'vue'
+
+import { appendUndoneCallsContext } from '@/app/ai/chat/context'
+import { undoOf, updateMessage, withUndo, type ReplyUndo } from '@/app/ai/chat/metadata'
+import type { ChatInstance } from '@/app/ai/chat/submission/types'
+import {
+ onTurnUndoChanged,
+ recordReplyTurn,
+ undoToReport,
+ type UndoReport
+} from '@/app/ai/chat/turns'
+import type { EditorStore } from '@/app/editor/active-store'
+
+interface UndoRecordOptions {
+ chat: Ref<ChatInstance | null>
+ flush?: () => Promise<void>
+ getEditor: () => EditorStore
+}
+
+/**
+ * Keeps each reply's undone edits marked in the chat and tells the model about them. Undo and
+ * Redo in the editor, as much as the chat's Revert and Restore, mark the calls they touch;
+ * the next request carries a note with what changed since the model last heard.
+ */
+export function useUndoRecords(options: UndoRecordOptions) {
+ function update(
+ chat: ChatInstance,
+ messageId: string,
+ change: (undo: ReplyUndo) => ReplyUndo
+ ): void {
+ updateMessage(chat, messageId, (message) => {
+ const undo = undoOf(message)
+ return undo ? withUndo(message, change(undo)) : message
+ })
+ }
+
+ const stopUndo = onTurnUndoChanged((messageId, undone) => {
+ const chat = options.chat.value
+ if (!chat?.messages.some((message) => message.id === messageId)) return
+ update(chat, messageId, (undo) => ({ ...undo, undone: [...undone] }))
+ void options.flush?.().catch(() => undefined)
+ })
+ tryOnScopeDispose(stopUndo)
+
+ function lastAssistantId(chat: ChatInstance): string | undefined {
+ return chat.messages.findLast((message) => message.role === 'assistant')?.id
+ }
+
+ /** Runs one message and keeps its reply's edits, so they can be reverted and marked when undone. */
+ async function withTurn(chat: ChatInstance, send: () => Promise<void>): Promise<void> {
+ const previous = lastAssistantId(chat)
+ await send()
+ const reply = lastAssistantId(chat)
+ if (!reply || reply === previous) return
+ const undo = await recordReplyTurn(reply, options.getEditor())
+ if (!undo) return
+ updateMessage(chat, reply, (message) => withUndo(message, undo))
+ }
+
+ /** `text` with a note about the undone edits `history` has not reported, and those reports. */
+ function note(text: string, history: readonly UIMessage[]) {
+ const reports = undoToReport(history)
+ const calls = {
+ undone: reports.flatMap((report) => report.calls.undone),
+ redone: reports.flatMap((report) => report.calls.redone)
+ }
+ return { text: appendUndoneCallsContext(text, calls), reports }
+ }
+
+ /** Records that `request` told the model about `reports`. */
+ function reported(chat: ChatInstance, reports: readonly UndoReport[], request: string): void {
+ for (const report of reports) {
+ update(chat, report.messageId, (undo) => ({
+ ...undo,
+ reported: { undone: [...report.undone], in: request }
+ }))
+ }
+ }
+
+ return { withTurn, note, reported }
+}
diff --git a/src/app/ai/chat/submission/use.ts b/src/app/ai/chat/submission/use.ts
index f1061bd66..567d8a9f6 100644
--- a/src/app/ai/chat/submission/use.ts
+++ b/src/app/ai/chat/submission/use.ts
@@ -15,9 +15,9 @@ import { setVisibleMessageText } from '@/app/ai/chat/presentation'
import { reportSubmissionError, type SubmissionErrorOptions } from '@/app/ai/chat/submission/errors'
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 { recordReplyTurn, restoreTurn, revertTurn } from '@/app/ai/chat/turns'
+import { useUndoRecords } from '@/app/ai/chat/submission/undone'
+import { restoreTurn, revertTurn } from '@/app/ai/chat/turns'
import type { EditorStore } from '@/app/editor/active-store'
interface SubmissionOptions extends SubmissionErrorOptions {
@@ -32,33 +32,21 @@ export function useChatSubmission(options: SubmissionOptions) {
const isPreparingAttachments = ref(false)
let operationVersion = 0
- function lastAssistantId(chat: ChatInstance): string | undefined {
- return chat.messages.findLast((message) => message.role === 'assistant')?.id
- }
-
- const reverts = useRevertRecords({ chat: options.chat, flush: options.flush })
+ const undone = useUndoRecords(options)
+ const { withTurn } = undone
- /** Redoes a reverted reply's edits; Redo noticing them removes the mark. */
+ /** Redoes a reply's undone edits; Redo noticing them removes the marks. */
async function restore(messageId: string): Promise<void> {
if (!readyChat() || !restoreTurn(messageId)) return
await options.flush?.().catch(() => undefined)
}
- /** Undoes a reply's edits and marks it, so the chat and the next request both say so. */
+ /** Undoes a reply's edits; the history change marks them, for the chat and the next request. */
async function revert(messageId: string): Promise<void> {
- const currentChat = readyChat()
- if (!currentChat || !reverts.revert(currentChat, messageId)) return
+ if (!readyChat() || !revertTurn(messageId)) return
await options.flush?.().catch(() => undefined)
}
- /** Runs one message and keeps the undo entries its edits pushed, so the turn can be reverted. */
- async function withTurn(chat: ChatInstance, send: () => Promise<void>): Promise<void> {
- const previous = lastAssistantId(chat)
- await send()
- const reply = lastAssistantId(chat)
- if (reply && reply !== previous) await recordReplyTurn(reply, options.getEditor())
- }
-
async function sendText(
currentChat: ChatInstance,
submission: ChatSubmission,
@@ -170,7 +158,7 @@ export function useChatSubmission(options: SubmissionOptions) {
if (submission.images.length > 0) options.reportError(options.messages.value.requestFailed)
return false
}
- const note = reverts.note(submission.modelText, currentChat.messages)
+ const note = undone.note(submission.modelText, currentChat.messages)
const noted = { ...submission, modelText: note.text }
const previousIds = new Set(currentChat.messages.map((message) => message.id))
if (submission.images.length === 0 && submission.nodes.length === 0) {
@@ -181,7 +169,7 @@ export function useChatSubmission(options: SubmissionOptions) {
const request = currentChat.messages.find(
(message) => message.role === 'user' && !previousIds.has(message.id)
)
- if (request) reverts.reported(currentChat, note.reverts, request.id)
+ if (request) undone.reported(currentChat, note.reports, request.id)
return true
} catch (error) {
reportSubmissionError(options, error)
@@ -224,14 +212,14 @@ export function useChatSubmission(options: SubmissionOptions) {
if (index === -1 || later.some((message) => message.role === 'user')) return
options.clearFailure()
for (const message of later) if (message.role === 'assistant') revertTurn(message.id)
- // Replies after the edited message are replaced; the reverts it reported need a new report.
- const note = reverts.note(trimmed, currentChat.messages.slice(0, index))
+ // Replies after the edited message are replaced; what it reported needs a new report.
+ const note = undone.note(trimmed, currentChat.messages.slice(0, index))
setVisibleMessageText(messageId, trimmed)
try {
await withTurn(currentChat, () =>
currentChat.sendMessage({ messageId, text: note.text }).catch(() => undefined)
)
- reverts.reported(currentChat, note.reverts, messageId)
+ undone.reported(currentChat, note.reports, messageId)
} finally {
await options.flush?.().catch(() => undefined)
}
diff --git a/src/app/ai/chat/transports.ts b/src/app/ai/chat/transports.ts
index a74222d9f..40532c244 100644
--- a/src/app/ai/chat/transports.ts
+++ b/src/app/ai/chat/transports.ts
@@ -37,6 +37,7 @@ import type { AIDiagnosticContext } from '@/app/diagnostics/events/ai'
import type { getActiveEditorStore } from '@/app/editor/active-store'
import { resumableTransport } from './history/continuation'
+import { updateMessage } from './metadata'
import { maxAgentSteps } from './preferences'
import { settleMessage } from './settle'
@@ -210,13 +211,8 @@ async function settleEndedReply(
): 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
+ updateMessage(chat, messageId, (message) =>
+ settleMessage(message, { stopped, changed: (toolCallId) => run.changedCalls.has(toolCallId) })
)
}
diff --git a/src/app/ai/chat/turns.ts b/src/app/ai/chat/turns.ts
index abd536e09..5e7f0ee5b 100644
--- a/src/app/ai/chat/turns.ts
+++ b/src/app/ai/chat/turns.ts
@@ -1,20 +1,25 @@
import type { UIMessage } from 'ai'
-import * as v from 'valibot'
+import { isEqual } from 'es-toolkit'
import { shallowReactive, shallowRef, type ShallowRef } from 'vue'
-import type { UndoEntry } from '@open-pencil/scene-graph/undo'
-
+import type { UndoneCalls } from '@/app/ai/chat/context'
+import { undoOf, type ReplyUndo } from '@/app/ai/chat/metadata'
import { currentRun } from '@/app/ai/tools'
+import type { RunUndoCall } from '@/app/ai/tools/run'
import type { EditorStore } from '@/app/editor/active-store'
interface TurnRecord {
store: EditorStore
- /** The turn's undo entries, oldest first. */
- entries: readonly UndoEntry[]
- /** Set by `revertTurn`; cleared when Redo puts the entries back on top of the undo stack. */
- reverted: boolean
+ /** The reply's edits, oldest first. */
+ calls: readonly RunUndoCall[]
+ /** The calls whose edit is undone, as the undo history last showed them. */
+ undone: ReadonlySet<string>
}
+/** Keyed by the assistant message the turn produced. The undo stack lives as long as the session. */
+const turns = shallowReactive(new Map<string, TurnRecord>())
+const undoListeners = new Set<(messageId: string, undone: readonly string[]) => void>()
+
/** Bumped on every undo stack change of a store, so turn state reads stay reactive. */
const historyVersions = new WeakMap<EditorStore, ShallowRef<number>>()
@@ -25,7 +30,7 @@ function historyVersion(store: EditorStore): number {
// The store's emitter goes away with the store, and the listener with it.
store.onEditorEvent('history:changed', () => {
created.value++
- noticeRestoredTurns(store)
+ noticeUndoneCalls(store)
})
historyVersions.set(store, created)
version = created
@@ -33,93 +38,128 @@ function historyVersion(store: EditorStore): number {
return version.value
}
-/** Keyed by the assistant message the turn produced. The undo stack lives as long as the session. */
-const turns = shallowReactive(new Map<string, TurnRecord>())
-const restoredListeners = new Set<(messageId: string) => void>()
-
-/** Whether a reverted turn's entries are the next ones Redo applies, oldest first. */
-function nextToRedo({ entries, store }: TurnRecord): boolean {
- return entries.every((entry, index) => store.undo.peekRedo(index) === entry)
-}
-
-/** Whether the turn's entries are the newest on its store's undo stack, oldest deepest. */
-function onTopOfUndo({ entries, store }: TurnRecord): boolean {
- return entries.every((entry, index) => store.undo.peekUndo(entries.length - 1 - index) === entry)
+/**
+ * The calls whose edit is undone now. An edit that left the history keeps what it was last:
+ * undone and then dropped by a later edit stays undone, applied and trimmed stays applied.
+ */
+function undoneNow({ store, calls, undone }: TurnRecord): Set<string> {
+ return new Set(
+ calls
+ .filter(({ entry, toolCallId }) => {
+ const state = store.undo.stateOf(entry)
+ return state === 'undone' || (state === null && undone.has(toolCallId))
+ })
+ .map(({ toolCallId }) => toolCallId)
+ )
}
-function noticeRestoredTurns(store: EditorStore): void {
+/** Undo, Redo, or the chat's Revert and Restore changed which of a store's AI edits apply. */
+function noticeUndoneCalls(store: EditorStore): void {
for (const [messageId, turn] of turns) {
- if (turn.store !== store || !turn.reverted || !onTopOfUndo(turn)) continue
- turns.set(messageId, { ...turn, reverted: false })
- for (const listener of restoredListeners) listener(messageId)
+ if (turn.store !== store) continue
+ const undone = undoneNow(turn)
+ if (isEqual(undone, turn.undone)) continue
+ turns.set(messageId, { ...turn, undone })
+ for (const listener of undoListeners) listener(messageId, [...undone])
}
}
-/** Calls `listener` with a reverted turn's message when Redo brings its edits back. */
-export function onTurnRestored(listener: (messageId: string) => void): () => void {
- restoredListeners.add(listener)
- return () => restoredListeners.delete(listener)
+/** Calls `listener` with a reply and its undone calls whenever the history changes them. */
+export function onTurnUndoChanged(
+ listener: (messageId: string, undone: readonly string[]) => void
+): () => void {
+ undoListeners.add(listener)
+ return () => undoListeners.delete(listener)
}
export function recordTurn(
messageId: string,
store: EditorStore,
- entries: readonly UndoEntry[]
+ calls: readonly RunUndoCall[]
): void {
- if (entries.length === 0) turns.delete(messageId)
- else turns.set(messageId, { store, entries: [...entries], reverted: false })
+ if (calls.length === 0) {
+ turns.delete(messageId)
+ return
+ }
+ historyVersion(store)
+ const record: TurnRecord = {
+ store,
+ calls: [...calls],
+ undone: new Set()
+ }
+ turns.set(messageId, { ...record, undone: undoneNow(record) })
}
/**
* 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.
+ * reply's tool finishes afterwards still belongs to it. Returns what the reply's message
+ * keeps: its edits, those undone already, and those the run told the model about.
*/
-export async function recordReplyTurn(messageId: string, store: EditorStore): Promise<void> {
+export async function recordReplyTurn(
+ messageId: string,
+ store: EditorStore
+): Promise<ReplyUndo | null> {
const run = currentRun(store)
await run.settled()
- recordTurn(messageId, store, run.undoEntries)
+ recordTurn(messageId, store, run.undoCalls)
+ const turn = turns.get(messageId)
+ if (!turn) return null
+ return {
+ edits: turn.calls.map(({ tool, toolCallId }) => ({ tool, toolCallId })),
+ undone: [...turn.undone],
+ reported:
+ run.reportedUndone.size > 0 ? { undone: [...run.reportedUndone], in: messageId } : undefined
+ }
}
export interface TurnEdits {
count: number
- /** Whether the turn's edits are still the newest on the undo stack, so undoing them touches nothing else. */
+ undone: number
+ /** Whether the edits still applied are the newest on the undo stack, so undoing them touches nothing else. */
revertable: boolean
- /** Whether the turn was reverted and Redo would bring back exactly its edits next. */
+ /** Whether Redo would bring back exactly the undone edits next. */
restorable: boolean
}
+function split(turn: TurnRecord) {
+ const undone = turn.calls.filter((call) => turn.undone.has(call.toolCallId))
+ const applied = turn.calls.filter((call) => !turn.undone.has(call.toolCallId))
+ return { undone, applied }
+}
+
/** Reactive: follows both the recorded turns and the store's undo stack. */
export function turnEdits(messageId: string): TurnEdits | null {
const turn = turns.get(messageId)
if (!turn) return null
historyVersion(turn.store)
+ const { undone, applied } = split(turn)
+ const { undo } = turn.store
return {
- count: turn.entries.length,
- revertable: onTopOfUndo(turn),
- restorable: turn.reverted && nextToRedo(turn)
+ count: turn.calls.length,
+ undone: undone.length,
+ revertable:
+ applied.length > 0 &&
+ applied.every(({ entry }, index) => undo.peekUndo(applied.length - 1 - index) === entry),
+ restorable:
+ undone.length > 0 && undone.every(({ entry }, index) => undo.peekRedo(index) === entry)
}
}
-/** Undoes the turn's edits when nothing has been pushed on top of them. */
+/** Undoes the turn's edits still applied, when nothing has been pushed on top of them. */
export function revertTurn(messageId: string): boolean {
const turn = turns.get(messageId)
if (!turn || !turnEdits(messageId)?.revertable) return false
- // Each step undoes one of the turn's entries, newest first.
- for (const _entry of turn.entries) turn.store.undoAction()
- // Kept, so that Redo restoring the edits can be noticed.
- turns.set(messageId, { ...turn, reverted: true })
+ // Each step undoes one of the turn's entries, newest first; the history change marks them.
+ for (const _call of split(turn).applied) turn.store.undoAction()
return true
}
-/**
- * Redoes a reverted turn's edits while nothing has been edited since the revert. Listeners of
- * `onTurnRestored` hear about it as about any Redo that brings the edits back.
- */
+/** Redoes the turn's undone edits while nothing has been edited since they were undone. */
export function restoreTurn(messageId: string): boolean {
const turn = turns.get(messageId)
if (!turn || !turnEdits(messageId)?.restorable) return false
// Each step redoes one of the turn's entries, oldest first.
- for (const _entry of turn.entries) turn.store.redoAction()
+ for (const _call of split(turn).undone) turn.store.redoAction()
return true
}
@@ -127,44 +167,32 @@ export function clearTurns(): void {
turns.clear()
}
-/**
- * A reverted reply is marked in its message metadata, which conversations store, so the chat
- * still shows it after reopening. `reportedIn` is the user message whose request told the
- * model about it.
- */
-const RevertedMetadata = v.object({ reverted: v.literal(true), reportedIn: v.optional(v.string()) })
-
-export interface Revert {
- reportedIn?: string
-}
-
-export function revertOf(message: UIMessage): Revert | null {
- const parsed = v.safeParse(RevertedMetadata, message.metadata)
- return parsed.success ? { reportedIn: parsed.output.reportedIn } : null
-}
-
-/** The message with its revert mark replaced, or removed for `null`, keeping other metadata. */
-export function withRevert(message: UIMessage, revert: Revert | null): UIMessage {
- const metadata = v.is(v.record(v.string(), v.unknown()), message.metadata) ? message.metadata : {}
- const { reverted: _reverted, reportedIn: _reportedIn, ...rest } = metadata
- if (!revert) return { ...message, metadata: rest }
- const reported = revert.reportedIn === undefined ? {} : { reportedIn: revert.reportedIn }
- return { ...message, metadata: { ...rest, reverted: true, ...reported } }
+/** A reply whose undone edits changed since the model last heard, and how. */
+export interface UndoReport {
+ messageId: string
+ undone: readonly string[]
+ calls: UndoneCalls
}
/**
- * Reverted replies a request after `messages` must report: those that no request in
- * `messages` has reported. A message being sent again is left out of `messages`, so the
- * reverts it reported are reported again.
+ * What a request after `messages` must tell the model about undone edits: for each reply,
+ * those undone or redone since the model last heard. A report counts while the message that
+ * carried it is still in `messages`; one being sent again is left out, so it is made again.
*/
-export function revertsToReport(messages: readonly UIMessage[]): string[] {
- const requests = new Set(
- messages.filter((message) => message.role === 'user').map((message) => message.id)
- )
+export function undoToReport(messages: readonly UIMessage[]): UndoReport[] {
+ const ids = new Set(messages.map((message) => message.id))
return messages.flatMap((message) => {
- const revert = revertOf(message)
- if (!revert) return []
- const { reportedIn } = revert
- return reportedIn !== undefined && requests.has(reportedIn) ? [] : [message.id]
+ const undo = undoOf(message)
+ if (!undo) return []
+ const known = new Set(undo.reported && ids.has(undo.reported.in) ? undo.reported.undone : [])
+ const now = new Set(undo.undone)
+ const undone = undo.edits.filter(
+ (call) => now.has(call.toolCallId) && !known.has(call.toolCallId)
+ )
+ const redone = undo.edits.filter(
+ (call) => !now.has(call.toolCallId) && known.has(call.toolCallId)
+ )
+ if (undone.length === 0 && redone.length === 0) return []
+ return [{ messageId: message.id, undone: undo.undone, calls: { undone, redone } }]
})
}
diff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.ts
index 926cda148..f2794821c 100644
--- a/src/app/ai/tools/index.ts
+++ b/src/app/ai/tools/index.ts
@@ -1,4 +1,5 @@
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'
@@ -21,6 +22,7 @@ import { aiToolDefinitions } from './catalog'
import { recordToolChange } from './changes/capture'
import { createMutex } from './mutex'
import {
+ aiUndoLabel,
currentRun,
markRunChange,
markRunWork,
@@ -29,7 +31,8 @@ import {
recordRunUndoEntry,
runBaseline,
runPageId,
- stepBudget
+ stepBudget,
+ takeRunUndoNote
} from './run'
export {
@@ -44,6 +47,15 @@ export {
startRun
} from './run'
+/**
+ * A result with the run's note about edits the user undid meanwhile, so the model does not
+ * build on them; other results stay as they are.
+ */
+function withUndoNote(result: unknown, note: string): unknown {
+ if (!note) return result
+ return isPlainObject(result) ? { ...result, undoNote: note } : { result, undoNote: note }
+}
+
export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnosticContext) {
const acquireMutation = createMutex()
const libraryService = useLibraryService()
@@ -69,6 +81,71 @@ export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnost
)
}
+ /** 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,
{
@@ -80,64 +157,8 @@ export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnost
}
return figma
},
- executeTool: async (def, figma, args, { toolCallId }) => {
- 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: `AI: ${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, `AI: ${def.name}`, 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()
- }
- }
- },
+ executeTool: async (def, figma, args, options) =>
+ withUndoNote(await executeCall(def, figma, args, options), takeRunUndoNote(store)),
onAfterExecute: (def) => {
if (def.mutates && !isAtomicTool(def)) store.requestRender()
},
diff --git a/src/app/ai/tools/run.ts b/src/app/ai/tools/run.ts
index aa107b01e..e678f8da5 100644
--- a/src/app/ai/tools/run.ts
+++ b/src/app/ai/tools/run.ts
@@ -2,6 +2,7 @@ import type { DocumentChange, PageSnapshot } from '@open-pencil/core/editor'
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 { getActiveEditorStore } from '@/app/editor/active-store'
@@ -13,6 +14,16 @@ import { addAgent, agentPlacement, type AgentHandle } from '@/app/presence/regis
* 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.
*/
+/** An undo entry one of a run's tool calls pushed. */
+export interface RunUndoCall extends CallRef {
+ entry: UndoEntry
+}
+
+/** The label of an AI tool call's undo entry, which Edit → Undo shows. */
+export function aiUndoLabel(tool: string): string {
+ return `AI: ${tool}`
+}
+
export class Run {
currentSteps = 0
/** Captured for the message in progress; settings changes apply to the next one. */
@@ -21,8 +32,10 @@ export class Run {
pageId: string
/** Each page as it was before the run first edited it, for `diff_changes`. */
readonly baselines = new Map<string, PageSnapshot>()
- /** Undo entries the run's edits pushed, oldest first, so its turn can be reverted. */
- readonly undoEntries: UndoEntry[] = []
+ /** Undo entries the run's edits pushed, oldest first, with the calls that pushed them. */
+ readonly undoCalls: RunUndoCall[] = []
+ /** The run's own calls the model was told the user undid while the run went on. */
+ readonly reportedUndone = new Set<string>()
/** 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. */
@@ -206,15 +219,40 @@ export function runBaseline(store: EditorStore, pageId: string): PageSnapshot |
export function recordRunUndoEntry(
store: EditorStore,
run: Run,
- label: string,
+ call: CallRef,
previous: UndoEntry | undefined
): void {
const entry = store.undo.peekUndo()
- if (entry !== previous && entry?.label === label && !run.undoEntries.includes(entry)) {
- run.undoEntries.push(entry)
+ if (
+ entry &&
+ entry !== previous &&
+ entry.label === aiUndoLabel(call.tool) &&
+ !run.undoCalls.some((recorded) => recorded.entry === entry)
+ ) {
+ run.undoCalls.push({ ...call, entry })
}
}
export function runUndoEntries(store: EditorStore): readonly UndoEntry[] {
- return getRunState(store).run.undoEntries
+ return getRunState(store).run.undoCalls.map(({ entry }) => entry)
+}
+
+/**
+ * A note for the run's next tool result when the user undid or redid some of the run's own
+ * edits since the model last heard; empty when nothing changed. Taking it counts as telling.
+ */
+export function takeRunUndoNote(store: EditorStore, run = currentRun(store)): string {
+ const undone: CallRef[] = []
+ const redone: CallRef[] = []
+ for (const { entry, tool, toolCallId } of run.undoCalls) {
+ const state = store.undo.stateOf(entry)
+ if (state === 'undone' && !run.reportedUndone.has(toolCallId)) {
+ undone.push({ tool, toolCallId })
+ run.reportedUndone.add(toolCallId)
+ } else if (state === 'applied' && run.reportedUndone.has(toolCallId)) {
+ redone.push({ tool, toolCallId })
+ run.reportedUndone.delete(toolCallId)
+ }
+ }
+ return describeUndoneCalls({ undone, redone })
}
diff --git a/src/components/chat/ChatMessage.stories.ts b/src/components/chat/ChatMessage.stories.ts
index c120fcdf5..0da4e33e1 100644
--- a/src/components/chat/ChatMessage.stories.ts
+++ b/src/components/chat/ChatMessage.stories.ts
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from '@storybook/vue3-vite'
import type { UIMessage } from 'ai'
-import { expect, within } from 'storybook/test'
+import { expect } from 'storybook/test'
import ChatMessage from './ChatMessage.vue'
@@ -47,6 +47,38 @@ const stoppedMessage: UIMessage = {
]
}
+/** A reply with one of its two edits undone, by Undo in the editor or the chat's Revert. */
+const partlyUndoneMessage: UIMessage = {
+ id: 'partly-undone-message',
+ role: 'assistant',
+ metadata: {
+ undo: {
+ edits: [
+ { tool: 'node_resize', toolCallId: 'resize' },
+ { tool: 'set_opacity', toolCallId: 'fade' }
+ ],
+ undone: ['fade']
+ }
+ },
+ parts: [
+ {
+ type: 'tool-node_resize',
+ toolCallId: 'resize',
+ state: 'output-available',
+ input: { id: '0:1', width: 200, height: 60 },
+ output: { id: '0:1' }
+ },
+ {
+ type: 'tool-set_opacity',
+ toolCallId: 'fade',
+ state: 'output-available',
+ input: { id: '0:1', value: 0.5 },
+ output: { id: '0:1' }
+ },
+ { type: 'text', text: 'Widened the card and faded it.' }
+ ]
+}
+
type ChatMessageStoryArgs = {
message: UIMessage
streaming?: boolean
@@ -75,8 +107,21 @@ export const Streaming: Story = { args: { message: assistantMessage, streaming:
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()
+ await expect(canvasElement.querySelector('[data-slot="chat-turn-stopped"]')).toBeVisible()
+ // The stopped reply's reasoning no longer reads as running.
+ await expect(
+ canvasElement.querySelector('[data-slot="chat-reasoning-trigger"]')
+ ).not.toHaveAttribute('data-streaming')
+ }
+}
+
+export const PartlyUndone: Story = {
+ args: { message: partlyUndoneMessage },
+ play: async ({ canvasElement }) => {
+ await expect(canvasElement.querySelector('[data-slot="chat-turn-undone"]')).toBeVisible()
+ const undone = canvasElement.querySelectorAll(
+ '[data-slot="chat-tool-call"][data-undone="true"]'
+ )
+ await expect(undone).toHaveLength(1)
}
}
diff --git a/src/components/chat/ChatMessage.vue b/src/components/chat/ChatMessage.vue
index d39a11b0e..2a07af25b 100644
--- a/src/components/chat/ChatMessage.vue
+++ b/src/components/chat/ChatMessage.vue
@@ -8,11 +8,10 @@ import { useI18n, vTestId } from '@open-pencil/vue'
import { attachmentsForMessage } from '@/app/ai/attachment/presentation/store'
import type { AttachmentPresentation } from '@/app/ai/attachment/presentation/types'
+import { undoOf, wasStopped } from '@/app/ai/chat/metadata'
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'
import ChatMarkdown from '@/components/chat/ChatMarkdown.vue'
import ReasoningBlock from '@/components/chat/ReasoningBlock.vue'
@@ -83,7 +82,14 @@ 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 undo = computed(() => undoOf(message))
+const undoneCalls = computed(() => new Set(undo.value?.undone))
+const reverted = computed(
+ () =>
+ !!undo.value &&
+ undo.value.edits.length > 0 &&
+ undoneCalls.value.size === undo.value.edits.length
+)
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'))
@@ -115,6 +121,7 @@ function groupKey(group: MessagePartGroup): string {
<ToolCallGroup
v-if="group.kind === 'tools'"
:parts="group.parts.map(({ part }) => part)"
+ :undone="undoneCalls"
/>
<!-- Reasoning -->
@@ -158,6 +165,8 @@ function groupKey(group: MessagePartGroup): string {
:empty="empty"
:reverted="reverted"
:stopped="stopped"
+ :undone="undoneCalls.size"
+ :edits="undo?.edits.length ?? 0"
@regenerate="emit('regenerate')"
@revert="emit('revert')"
@restore="emit('restore')"
diff --git a/src/components/chat/ReasoningBlock.vue b/src/components/chat/ReasoningBlock.vue
index da90c92ca..e128e69b2 100644
--- a/src/components/chat/ReasoningBlock.vue
+++ b/src/components/chat/ReasoningBlock.vue
@@ -83,6 +83,7 @@ function updateOpen(value: boolean): void {
>
<CollapsibleTrigger
data-slot="chat-reasoning-trigger"
+ :data-streaming="streaming || undefined"
class="flex w-full cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-left text-[11px] text-muted hover:bg-hover hover:text-surface"
>
<icon-lucide-brain class="size-3.5 shrink-0 text-primary" aria-hidden="true" />
diff --git a/src/components/chat/tool/ToolCallCard.vue b/src/components/chat/tool/ToolCallCard.vue
index ac1ede341..c0f57e1fe 100644
--- a/src/components/chat/tool/ToolCallCard.vue
+++ b/src/components/chat/tool/ToolCallCard.vue
@@ -26,7 +26,8 @@ import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'
import { chatToolTheme } from '@/theme/chat/tool'
import { collapsibleContentMotion } from '@/theme/collapsible/collapsible'
-const { part } = defineProps<{ part: ToolCallPart }>()
+/** `undone`: the user undid the call's edit, by Undo or the chat's Revert. */
+const { part, undone = false } = defineProps<{ part: ToolCallPart; undone?: boolean }>()
const { ai } = useI18n()
const ui = chatToolTheme()
@@ -79,7 +80,12 @@ function json(value: unknown): string {
</script>
<template>
- <CollapsibleRoot :class="ui.root()" :data-tool-state="state" data-slot="chat-tool-call">
+ <CollapsibleRoot
+ :class="ui.root()"
+ :data-tool-state="state"
+ :data-undone="undone"
+ data-slot="chat-tool-call"
+ >
<!-- Start loading CodeMirror on hover, so it is ready by the time the call opens. -->
<CollapsibleTrigger
:class="ui.trigger()"
@@ -97,6 +103,10 @@ function json(value: unknown): string {
</span>
<span :class="ui.name()">{{ name }}</span>
<span :class="ui.summary()">{{ summary }}</span>
+ <span v-if="undone" :class="ui.undone()" data-slot="chat-tool-undone">
+ <icon-lucide-undo-2 :class="ui.undoneIcon()" aria-hidden="true" />
+ {{ ai.toolUndone }}
+ </span>
<icon-lucide-chevron-down v-if="expandable" :class="ui.chevron()" aria-hidden="true" />
</CollapsibleTrigger>
<CollapsibleContent :class="collapsibleContentMotion">
diff --git a/src/components/chat/tool/ToolCallGroup.vue b/src/components/chat/tool/ToolCallGroup.vue
index 5652ccb2a..bf37196f3 100644
--- a/src/components/chat/tool/ToolCallGroup.vue
+++ b/src/components/chat/tool/ToolCallGroup.vue
@@ -14,7 +14,8 @@ import { collapsibleContentMotion } from '@/theme/collapsible/collapsible'
/** Runs up to this long stay expanded; longer ones fold all but the latest call. */
const INLINE_CALLS = 3
-const { parts } = defineProps<{ parts: ToolCallPart[] }>()
+/** `undone`: the calls whose edit the user undid. */
+const { parts, undone } = defineProps<{ parts: ToolCallPart[]; undone?: ReadonlySet<string> }>()
const { ai } = useI18n()
const ui = chatToolTheme()
@@ -33,7 +34,12 @@ const label = computed(() => {
<template>
<div v-if="parts.length <= INLINE_CALLS" class="space-y-1.5">
- <ToolCallCard v-for="part in parts" :key="part.toolCallId" :part="part" />
+ <ToolCallCard
+ v-for="part in parts"
+ :key="part.toolCallId"
+ :part="part"
+ :undone="undone?.has(part.toolCallId)"
+ />
</div>
<div v-else class="space-y-1.5">
<CollapsibleRoot :class="ui.group()" data-slot="chat-tool-group">
@@ -48,10 +54,20 @@ const label = computed(() => {
</CollapsibleTrigger>
<CollapsibleContent :class="collapsibleContentMotion">
<div :class="ui.groupItems()">
- <ToolCallCard v-for="part in earlier" :key="part.toolCallId" :part="part" />
+ <ToolCallCard
+ v-for="part in earlier"
+ :key="part.toolCallId"
+ :part="part"
+ :undone="undone?.has(part.toolCallId)"
+ />
</div>
</CollapsibleContent>
</CollapsibleRoot>
- <ToolCallCard v-if="latest" :key="latest.toolCallId" :part="latest" />
+ <ToolCallCard
+ v-if="latest"
+ :key="latest.toolCallId"
+ :part="latest"
+ :undone="undone?.has(latest.toolCallId)"
+ />
</div>
</template>
diff --git a/src/components/chat/turn/ChatTurnActions.vue b/src/components/chat/turn/ChatTurnActions.vue
index 950d9b38b..4beb608e6 100644
--- a/src/components/chat/turn/ChatTurnActions.vue
+++ b/src/components/chat/turn/ChatTurnActions.vue
@@ -11,28 +11,34 @@ const {
canRegenerate = false,
empty = false,
reverted = false,
- stopped = false
+ stopped = false,
+ undone = 0,
+ edits = 0
} = defineProps<{
messageId: string
canRegenerate?: boolean
/** The reply failed before any content, so asking again is a retry. */
empty?: boolean
- /** The reply's edits were reverted; it stays in the chat, marked. */
+ /** Every edit of the reply was undone, by Undo or Revert; it stays in the chat, marked. */
reverted?: boolean
+ /** How many of the reply's edits are undone, and how many it made. */
+ undone?: number
+ edits?: number
/** The user stopped the reply before it finished. */
stopped?: boolean
}>()
const emit = defineEmits<{ regenerate: []; revert: []; restore: [] }>()
const { ai } = useI18n()
-const edits = computed(() => turnEdits(messageId))
-const revertable = computed(() => edits.value?.revertable === true)
-const restorable = computed(() => edits.value?.restorable === true)
+const turn = computed(() => turnEdits(messageId))
+const revertable = computed(() => turn.value?.revertable === true)
+const restorable = computed(() => turn.value?.restorable === true)
+const partlyUndone = computed(() => undone > 0 && undone < edits)
</script>
<template>
<div
- v-if="stopped || revertable || reverted || canRegenerate"
+ v-if="stopped || partlyUndone || revertable || reverted || canRegenerate"
class="flex flex-wrap items-center gap-1"
data-slot="chat-turn-actions"
>
@@ -44,17 +50,15 @@ const restorable = computed(() => edits.value?.restorable === true)
<icon-lucide-circle-stop class="size-3" aria-hidden="true" />
{{ ai.turnStopped }}
</span>
- <AppButton
- v-if="reverted && restorable"
- size="xs"
- variant="ghost"
- data-test-id="chat-restore-turn"
- @click="emit('restore')"
+ <!-- What is undone shows whether or not Redo can still bring it back. -->
+ <span
+ v-if="partlyUndone"
+ class="inline-flex items-center gap-1 px-2 text-[11px] text-muted"
+ data-slot="chat-turn-undone"
>
- <template #leading><icon-lucide-redo-2 aria-hidden="true" /></template>
- {{ ai.restoreTurn }}
- </AppButton>
- <!-- Edits made since the revert closed Redo; the reply stays marked. -->
+ <icon-lucide-undo-2 class="size-3" aria-hidden="true" />
+ {{ ai.turnPartlyUndone({ undone, total: edits }) }}
+ </span>
<span
v-else-if="reverted"
class="inline-flex items-center gap-1 px-2 text-[11px] text-muted"
@@ -64,7 +68,17 @@ const restorable = computed(() => edits.value?.restorable === true)
{{ ai.turnReverted }}
</span>
<AppButton
- v-else-if="revertable"
+ v-if="restorable"
+ size="xs"
+ variant="ghost"
+ data-test-id="chat-restore-turn"
+ @click="emit('restore')"
+ >
+ <template #leading><icon-lucide-redo-2 aria-hidden="true" /></template>
+ {{ ai.restoreTurn }}
+ </AppButton>
+ <AppButton
+ v-if="revertable"
size="xs"
variant="ghost"
data-test-id="chat-revert-turn"
diff --git a/src/theme/chat/tool.ts b/src/theme/chat/tool.ts
index 0b448b394..439b43e3a 100644
--- a/src/theme/chat/tool.ts
+++ b/src/theme/chat/tool.ts
@@ -2,7 +2,8 @@ import { tv } from 'tailwind-variants'
export const chatToolTheme = tv({
slots: {
- root: 'rounded-lg border border-border bg-canvas',
+ // An undone call's text dims to the muted color, which still reads at 4.5:1.
+ root: 'rounded-lg border border-border bg-canvas data-[undone=true]:**:text-muted',
trigger:
'flex w-full min-w-0 cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left hover:bg-hover disabled:cursor-default disabled:hover:bg-transparent',
status:
@@ -10,6 +11,8 @@ export const chatToolTheme = tv({
statusIcon: 'size-3',
name: 'shrink-0 text-[11px] font-medium text-surface',
summary: 'min-w-0 flex-1 truncate font-mono text-[10px] text-muted',
+ undone: 'inline-flex shrink-0 items-center gap-1 text-[10px] text-muted',
+ undoneIcon: 'size-3',
chevron:
'ml-auto size-3 shrink-0 text-muted transition-transform motion-reduce:transition-none [[data-state=open]>&]:rotate-180',
body: 'space-y-2 border-t border-border px-2 py-2 text-[10px]',
diff --git a/tests/app/ai/chat/settle.test.ts b/tests/app/ai/chat/settle.test.ts
index 5bf41d44c..e6cad1618 100644
--- a/tests/app/ai/chat/settle.test.ts
+++ b/tests/app/ai/chat/settle.test.ts
@@ -3,7 +3,8 @@ import { expect, test } from 'bun:test'
import type { UIMessage } from 'ai'
import { reactive, toRaw } from 'vue'
-import { settleMessage, wasStopped } from '@/app/ai/chat/settle'
+import { wasStopped } from '@/app/ai/chat/metadata'
+import { settleMessage } from '@/app/ai/chat/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/chat/turns.test.ts
index 23bc6ebcd..765528045 100644
--- a/tests/app/ai/chat/turns.test.ts
+++ b/tests/app/ai/chat/turns.test.ts
@@ -6,13 +6,14 @@ import { ref, shallowRef, toRaw } from 'vue'
import { FigmaAPI } from '@open-pencil/core/figma-api'
-import { REVERTED_TURN_CONTEXT_MARKER } from '@/app/ai/chat/context'
+import { UNDONE_CALLS_CONTEXT_MARKER } from '@/app/ai/chat/context'
import { snapshotMessages } from '@/app/ai/chat/history/messages'
+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, revertOf, revertTurn, turnEdits } from '@/app/ai/chat/turns'
-import { createAITools, startRun } from '@/app/ai/tools'
+import { clearTurns, revertTurn, turnEdits, undoToReport } from '@/app/ai/chat/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'
import { appPreferences } from '@/app/settings/preferences/store'
@@ -159,11 +160,11 @@ test('reverts a turn while its edits are the newest on the undo stack', async ()
const { card, actions } = setup()
await actions.submit({ modelText: 'Wider', displayText: 'Wider', images: [], nodes: [] })
expect(width(card.id)).toBe(200)
- expect(turnEdits('reply-1')).toEqual({ count: 1, revertable: true, restorable: false })
+ expect(turnEdits('reply-1')).toEqual({ count: 1, undone: 0, revertable: true, restorable: false })
expect(revertTurn('reply-1')).toBe(true)
expect(width(card.id)).toBe(100)
- expect(turnEdits('reply-1')).toEqual({ count: 1, revertable: false, restorable: true })
+ expect(turnEdits('reply-1')).toEqual({ count: 1, undone: 1, revertable: false, restorable: true })
})
test('a turn that ends with a view change, such as zoom to fit, stays revertable', async () => {
@@ -183,7 +184,12 @@ test('an edit made after the turn closes the revert, so it never undoes other wo
await actions.submit({ modelText: 'Wider', displayText: 'Wider', images: [], nodes: [] })
store.pushUndoEntry({ label: 'User edit', forward: () => undefined, inverse: () => undefined })
- expect(turnEdits('reply-1')).toEqual({ count: 1, revertable: false, restorable: false })
+ expect(turnEdits('reply-1')).toEqual({
+ count: 1,
+ undone: 0,
+ revertable: false,
+ restorable: false
+ })
expect(revertTurn('reply-1')).toBe(false)
expect(width(card.id)).toBe(200)
})
@@ -284,9 +290,10 @@ test('resending an edited request replaces it and undoes the old reply first', a
const send = (text: string) => ({ modelText: text, displayText: text, images: [], nodes: [] })
-function mark(chat: ReturnType<typeof fakeChat>, id: string) {
+/** The reply's undone calls, as its message keeps them. */
+function undone(chat: ReturnType<typeof fakeChat>, id: string) {
const message = chat.messages.find((candidate) => candidate.id === id)
- return message ? revertOf(message) : undefined
+ return message ? undoOf(message)?.undone : undefined
}
function lastRequest(chat: ReturnType<typeof fakeChat>): string {
@@ -294,89 +301,146 @@ function lastRequest(chat: ReturnType<typeof fakeChat>): string {
return request?.parts.map((part) => (part.type === 'text' ? part.text : '')).join('') ?? ''
}
-test('a reverted reply stays marked, and the next request tells the model once', async () => {
+test("undoing a reply's edit in the editor marks it, and the next request tells the model once", async () => {
const { card, chat, actions } = setup()
await actions.submit(send('Wider'))
- await actions.revert('reply-1')
+ store.undoAction()
expect(width(card.id)).toBe(100)
- expect(mark(chat, 'reply-1')).toEqual({ reportedIn: undefined })
+ expect(undone(chat, 'reply-1')).toEqual(['call-1'])
await actions.submit(send('Try again'))
- expect(lastRequest(chat)).toContain(REVERTED_TURN_CONTEXT_MARKER)
expect(lastRequest(chat)).toStartWith('Try again')
- expect(mark(chat, 'reply-1')?.reportedIn).toBe(
- chat.messages.findLast((message) => message.role === 'user')?.id
- )
+ expect(lastRequest(chat)).toContain(UNDONE_CALLS_CONTEXT_MARKER)
+ expect(lastRequest(chat)).toContain('- node_resize (call-1)')
await actions.submit(send('And once more'))
- expect(lastRequest(chat)).not.toContain(REVERTED_TURN_CONTEXT_MARKER)
+ expect(lastRequest(chat)).not.toContain(UNDONE_CALLS_CONTEXT_MARKER)
+})
+
+test('a reply with some edits undone marks only those, and can be restored or reverted', async () => {
+ const { card, chat, actions } = setup(async (tools) =>
+ tools.set_opacity.execute?.({ id: card.id, value: 0.5 }, call('fade'))
+ )
+ await actions.submit(send('Wider and fainter'))
+ store.undoAction()
+
+ expect(undone(chat, 'reply-1')).toEqual(['fade'])
+ expect(turnEdits('reply-1')).toEqual({ count: 2, undone: 1, revertable: true, restorable: true })
+ await actions.submit(send('Keep the width'))
+ expect(lastRequest(chat)).toContain('- set_opacity (fade)')
+ expect(lastRequest(chat)).not.toContain('node_resize')
})
-test('redoing a reverted reply removes its mark, so nothing is reported', async () => {
+test('redoing an undone edit removes its mark, so nothing is reported', async () => {
const { card, chat, actions } = setup()
await actions.submit(send('Wider'))
await actions.revert('reply-1')
store.redoAction()
expect(width(card.id)).toBe(200)
- expect(mark(chat, 'reply-1')).toBeNull()
+ expect(undone(chat, 'reply-1')).toEqual([])
expect(turnEdits('reply-1')?.revertable).toBe(true)
await actions.submit(send('Next'))
- expect(lastRequest(chat)).not.toContain(REVERTED_TURN_CONTEXT_MARKER)
+ expect(lastRequest(chat)).not.toContain(UNDONE_CALLS_CONTEXT_MARKER)
+})
+
+test('an edit the model heard was undone, redone since, is reported as applying again', () => {
+ const reply: UIMessage = {
+ id: 'reply',
+ role: 'assistant',
+ parts: [],
+ metadata: {
+ undo: {
+ edits: [
+ { tool: 'node_resize', toolCallId: 'resize' },
+ { tool: 'set_opacity', toolCallId: 'fade' }
+ ],
+ undone: ['fade'],
+ reported: { undone: ['resize'], in: 'request' }
+ }
+ }
+ }
+ const request: UIMessage = { id: 'request', role: 'user', parts: [] }
+
+ expect(undoToReport([reply, request])).toEqual([
+ {
+ messageId: 'reply',
+ undone: ['fade'],
+ calls: {
+ undone: [{ tool: 'set_opacity', toolCallId: 'fade' }],
+ redone: [{ tool: 'node_resize', toolCallId: 'resize' }]
+ }
+ }
+ ])
+ // Without the request that carried the report, the model never heard of the undo.
+ expect(undoToReport([reply])[0]?.calls.redone).toEqual([])
})
-test('sending a request again reports a revert from before it', async () => {
+test('sending a request again reports an undo from before it', async () => {
const { chat, actions } = setup()
await actions.submit(send('Wider'))
await actions.revert('reply-1')
await actions.submit(send('Taller'))
- // The second request already reported the revert; editing it sends the note again.
+ // The second request already reported the undo; editing it sends the note again.
const request = chat.messages.findLast((message) => message.role === 'user')?.id ?? ''
await actions.resend(request, 'Much taller')
expect(lastRequest(chat)).toStartWith('Much taller')
- expect(lastRequest(chat)).toContain(REVERTED_TURN_CONTEXT_MARKER)
-})
-
-test('an older reply reverted after later requests is still reported', async () => {
- const { card, chat, actions } = setup()
- await actions.submit(send('Wider'))
- await actions.submit(send('Even wider'))
- await actions.revert('reply-2')
- await actions.submit(send('Smaller then'))
- expect(lastRequest(chat)).toContain(REVERTED_TURN_CONTEXT_MARKER)
-
- // The third reply's edit is undone too, which leaves the first reply's on top.
- await actions.revert('reply-3')
- await actions.revert('reply-1')
- expect(width(card.id)).toBe(100)
- await actions.submit(send('Start over'))
- expect(lastRequest(chat)).toContain(
- 'The user reverted every document edit from 2 of your earlier replies.'
- )
+ expect(lastRequest(chat)).toContain('- node_resize (call-1)')
})
-test('restoring a reverted reply redoes its edits and removes the mark', async () => {
+test('restoring a reverted reply redoes its edits and removes the marks', async () => {
const { card, chat, actions } = setup()
await actions.submit(send('Wider'))
await actions.revert('reply-1')
await actions.restore('reply-1')
expect(width(card.id)).toBe(200)
- expect(mark(chat, 'reply-1')).toBeNull()
- expect(turnEdits('reply-1')).toEqual({ count: 1, revertable: true, restorable: false })
+ expect(undone(chat, 'reply-1')).toEqual([])
+ expect(turnEdits('reply-1')).toEqual({ count: 1, undone: 0, revertable: true, restorable: false })
})
-test('an edit made after the revert closes the restore, and the reply stays marked', async () => {
+test('an edit made after an undo closes the restore, and the edit stays marked undone', async () => {
const { card, chat, actions } = setup()
await actions.submit(send('Wider'))
- await actions.revert('reply-1')
+ store.undoAction()
store.pushUndoEntry({ label: 'User edit', forward: () => undefined, inverse: () => undefined })
expect(turnEdits('reply-1')?.restorable).toBe(false)
await actions.restore('reply-1')
expect(width(card.id)).toBe(100)
- expect(mark(chat, 'reply-1')).toEqual({ reportedIn: undefined })
+ expect(undone(chat, 'reply-1')).toEqual(['call-1'])
+})
+
+test('an edit undone while the agent works is noted on its next tool result', async () => {
+ const card = store.graph.createNode('FRAME', store.state.currentPageId, { name: 'Card' })
+ const tools = createAITools(store)
+ startRun(store, 10)
+ await tools.node_resize.execute?.({ id: card.id, width: 200, height: 60 }, call('resize'))
+ store.undoAction()
+
+ const result = await tools.get_node.execute?.({ id: card.id }, call('read'))
+ expect(result).toMatchObject({ undoNote: expect.stringContaining('- node_resize (resize)') })
+ // Told once: the next result carries no note.
+ const again = await tools.get_node.execute?.({ id: card.id }, call('read-again'))
+ expect(again).not.toHaveProperty('undoNote')
+
+ store.redoAction()
+ const redone = await tools.get_node.execute?.({ id: card.id }, call('read-redone'))
+ expect(redone).toMatchObject({ undoNote: expect.stringContaining('The user redid') })
+ endRun(store)
+})
+
+test('an undo the agent heard about while it worked is not reported again', async () => {
+ const { card, chat, actions } = setup(async (tools) => {
+ store.undoAction()
+ return tools.get_node.execute?.({ id: card.id }, call('look'))
+ })
+ await actions.submit(send('Wider'))
+ expect(undone(chat, 'reply-1')).toEqual(['call-1'])
+
+ await actions.submit(send('Next'))
+ expect(lastRequest(chat)).not.toContain(UNDONE_CALLS_CONTEXT_MARKER)
})
diff --git a/tests/app/ai/tools/run.test.ts b/tests/app/ai/tools/run.test.ts
index fe894d4e8..abb0faebc 100644
--- a/tests/app/ai/tools/run.test.ts
+++ b/tests/app/ai/tools/run.test.ts
@@ -346,7 +346,7 @@ test('a tool still running at Stop finishes into its reply without bringing the
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.undoCalls).toHaveLength(1)
expect([...run.changedCalls]).toEqual(['first'])
expect(agent()).toMatchObject({ status: 'idle', cursor: undefined, selection: undefined })
})
diff --git a/tests/e2e/chat/turns.spec.ts b/tests/e2e/chat/turns.spec.ts
index 6c6ff744e..60b3cb257 100644
--- a/tests/e2e/chat/turns.spec.ts
+++ b/tests/e2e/chat/turns.spec.ts
@@ -37,9 +37,8 @@ test('reverting a reply undoes its edits, marks it, saves the chat, and tells th
await expect(page.getByTestId('chat-message-assistant')).toHaveCount(2)
await expect(chat.assistantMessage()).toContainText('Done')
const request = await page.evaluate(() => document.documentElement.dataset.lastModelRequest)
- expect(request).toContain(
- 'The user reverted every document edit from one of your earlier replies'
- )
+ // The note names the undone call by its tool.
+ expect(request).toContain('- render (')
// The note is for the model only.
await expect(chat.userMessage()).toHaveText('Try something else')
// The second reply's edits closed Redo, so the first reply is marked instead.
@@ -61,8 +60,8 @@ test('reverting a reply undoes its edits, marks it, saves the chat, and tells th
const conversation = latest ? await store.read(latest.id) : null
return (
conversation?.messages.some(
- (entry: { message: { metadata?: { reverted?: boolean } } }) =>
- entry.message.metadata?.reverted === true
+ (entry: { message: { metadata?: { undo?: { undone?: string[] } } } }) =>
+ (entry.message.metadata?.undo?.undone?.length ?? 0) > 0
) ?? false
)
})
diff --git a/tests/engine/app/ai/context.test.ts b/tests/engine/app/ai/context.test.ts
index c39ca8a0f..3bfe817cc 100644
--- a/tests/engine/app/ai/context.test.ts
+++ b/tests/engine/app/ai/context.test.ts
@@ -6,7 +6,7 @@ import {
appendReferencedNodeContext,
MAX_REFERENCED_NODES,
resolveReferencedNodes,
- stripReferencedNodeContext
+ stripModelNotes
} from '@/app/ai/chat/context'
describe('AI chat node context', () => {
@@ -43,8 +43,8 @@ describe('AI chat node context', () => {
{ id: '1:2', type: 'FRAME', name: 'Hero' }
])
- expect(stripReferencedNodeContext(modelText)).toBe('Visible request')
- expect(stripReferencedNodeContext('No references')).toBe('No references')
+ expect(stripModelNotes(modelText)).toBe('Visible request')
+ expect(stripModelNotes('No references')).toBe('No references')
})
test('bounds the number of references', () => {