AI-native design editor. Open-source Figma alternative.
feat(ai): revert, regenerate, and edit chat turns (#844)
Danila Poyarkov8d1ad541938d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5587e7e28..a55fa9a20 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -44,6 +44,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.- Review what each AI edit changed from its tool call in the chat: a before and after image with a comparison slider or highlighted changed pixels, 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, or edit the last message and send it again; regenerating and resending undo the replaced reply's edits first when they can. A reverted reply stays in the chat marked *Changes reverted*, also after reopening the conversation, and your next message tells the AI that those edits are gone, so it does not build on them; **Restore changes** on the reply, or Edit → Redo, brings the edits back and removes the mark while nothing has been edited since.- Preview designs progressively on the canvas as direct AI providers stream JSX, without saving partial designs or adding intermediate undo steps. A preview stays with its page: it hides while you view another page and returns when you come back.- Write design trees as TSX with `@open-pencil/design-jsx` as the JSX import source, and render them with `renderTree`.- Swap the component behind an instance with `instance.swapComponent(component)` in the plugin API, as in Figma.diff --git a/packages/scene-graph/src/undo.ts b/packages/scene-graph/src/undo.tsindex 6d838c6cf..8297a3174 100644--- a/packages/scene-graph/src/undo.ts+++ b/packages/scene-graph/src/undo.ts@@ -127,6 +127,19 @@ export class UndoManager {return this.redoStack.length > 0}+ /**+ * The entry `depth` steps below the top of the undo stack, so a caller that pushed entries+ * can tell whether they are still the most recent ones.+ */+ peekUndo(depth = 0): UndoEntry | undefined {+ return this.undoStack.at(-1 - depth)+ }++ /** The entry `depth` steps below the top of the redo stack, the next one Redo applies at 0. */+ peekRedo(depth = 0): UndoEntry | undefined {+ return this.redoStack.at(-1 - depth)+ }+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.tsnew file mode 100644index 000000000..a32d33784--- /dev/null+++ b/packages/scene-graph/tests/undo/peek.test.ts@@ -0,0 +1,37 @@+import { expect, test } from 'bun:test'++import { UndoManager } from '@open-pencil/scene-graph'++test('peeks entries from the top of the undo stack without changing it', () => {+ const undo = new UndoManager()+ const noop = () => undefined+ const first = { label: 'First', forward: noop, inverse: noop }+ const second = { label: 'Second', forward: noop, inverse: noop }+ undo.push(first)+ undo.push(second)++ expect(undo.peekUndo()).toBe(second)+ expect(undo.peekUndo(1)).toBe(first)+ expect(undo.peekUndo(2)).toBeUndefined()+ expect(undo.undoLabel).toBe('Second')++ undo.undo()+ expect(undo.peekUndo()).toBe(first)+})++test('peeks entries from the top of the redo stack, the next Redo first', () => {+ const undo = new UndoManager()+ const noop = () => undefined+ const first = { label: 'First', forward: noop, inverse: noop }+ const second = { label: 'Second', forward: noop, inverse: noop }+ undo.push(first)+ undo.push(second)+ undo.undo()+ undo.undo()++ expect(undo.peekRedo()).toBe(first)+ expect(undo.peekRedo(1)).toBe(second)+ expect(undo.peekRedo(2)).toBeUndefined()+ undo.redo()+ expect(undo.peekRedo()).toBe(second)+})diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.jsonindex 4c2217016..665b0cec8 100644--- a/packages/vue/src/i18n/locales/de/ai.json+++ b/packages/vue/src/i18n/locales/de/ai.json@@ -30,6 +30,14 @@"reasoning": "Überlegungen","thoughtFor": "Nachgedacht: {seconds} s","copyResponse": "Antwort kopieren",+ "revertTurn": "Änderungen zurücknehmen",+ "turnReverted": "Änderungen rückgängig gemacht",+ "restoreTurn": "Änderungen wiederherstellen",+ "regenerate": "Neu generieren",+ "revertAndRegenerate": "Zurücknehmen und neu generieren",+ "editMessage": "Nachricht bearbeiten",+ "cancelEdit": "Abbrechen",+ "resendMessage": "Erneut senden","responseCopied": "Antwort kopiert","toolFinished": "Fertig","toolRunning": "Wird ausgeführt…",diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.jsonindex 658f862e4..1b644bb80 100644--- a/packages/vue/src/i18n/locales/es/ai.json+++ b/packages/vue/src/i18n/locales/es/ai.json@@ -30,6 +30,14 @@"reasoning": "Razonamiento","thoughtFor": "Razonó durante {seconds} s","copyResponse": "Copiar respuesta",+ "revertTurn": "Revertir cambios",+ "turnReverted": "Cambios revertidos",+ "restoreTurn": "Restaurar cambios",+ "regenerate": "Regenerar",+ "revertAndRegenerate": "Revertir y regenerar",+ "editMessage": "Editar mensaje",+ "cancelEdit": "Cancelar",+ "resendMessage": "Enviar de nuevo","responseCopied": "Respuesta copiada","toolFinished": "Hecho","toolRunning": "Ejecutando…",diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.jsonindex 5039989e8..164f85b02 100644--- a/packages/vue/src/i18n/locales/fr/ai.json+++ b/packages/vue/src/i18n/locales/fr/ai.json@@ -30,6 +30,14 @@"reasoning": "Raisonnement","thoughtFor": "Réflexion : {seconds} s","copyResponse": "Copier la réponse",+ "revertTurn": "Annuler les modifications",+ "turnReverted": "Modifications annulées",+ "restoreTurn": "Rétablir les modifications",+ "regenerate": "Régénérer",+ "revertAndRegenerate": "Annuler et régénérer",+ "editMessage": "Modifier le message",+ "cancelEdit": "Annuler",+ "resendMessage": "Renvoyer","responseCopied": "Réponse copiée","toolFinished": "Terminé","toolRunning": "Exécution…",diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.jsonindex 915068b69..4e2514768 100644--- a/packages/vue/src/i18n/locales/it/ai.json+++ b/packages/vue/src/i18n/locales/it/ai.json@@ -30,6 +30,14 @@"reasoning": "Ragionamento","thoughtFor": "Ragionato per {seconds} s","copyResponse": "Copia risposta",+ "revertTurn": "Annulla le modifiche",+ "turnReverted": "Modifiche annullate",+ "restoreTurn": "Ripristina modifiche",+ "regenerate": "Rigenera",+ "revertAndRegenerate": "Annulla e rigenera",+ "editMessage": "Modifica messaggio",+ "cancelEdit": "Annulla",+ "resendMessage": "Invia di nuovo","responseCopied": "Risposta copiata","toolFinished": "Fine","toolRunning": "Esecuzione…",diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.jsonindex e43bf8342..848bee28a 100644--- a/packages/vue/src/i18n/locales/ja/ai.json+++ b/packages/vue/src/i18n/locales/ja/ai.json@@ -30,6 +30,14 @@"reasoning": "推論","thoughtFor": "{seconds}秒間思考","copyResponse": "回答をコピー",+ "revertTurn": "変更を元に戻す",+ "turnReverted": "変更を取り消しました",+ "restoreTurn": "変更を元に戻す",+ "regenerate": "再生成",+ "revertAndRegenerate": "元に戻して再生成",+ "editMessage": "メッセージを編集",+ "cancelEdit": "キャンセル",+ "resendMessage": "再送信","responseCopied": "回答をコピーしました","toolFinished": "完了","toolRunning": "実行中…",diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.jsonindex 29901c322..5f4701227 100644--- a/packages/vue/src/i18n/locales/pl/ai.json+++ b/packages/vue/src/i18n/locales/pl/ai.json@@ -30,6 +30,14 @@"reasoning": "Rozumowanie","thoughtFor": "Rozumowanie: {seconds} s","copyResponse": "Kopiuj odpowiedź",+ "revertTurn": "Cofnij zmiany",+ "turnReverted": "Zmiany cofnięte",+ "restoreTurn": "Przywróć zmiany",+ "regenerate": "Wygeneruj ponownie",+ "revertAndRegenerate": "Cofnij i wygeneruj ponownie",+ "editMessage": "Edytuj wiadomość",+ "cancelEdit": "Anuluj",+ "resendMessage": "Wyślij ponownie","responseCopied": "Skopiowano odpowiedź","toolFinished": "Gotowe","toolRunning": "Uruchamianie…",diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.jsonindex bc631f90e..c67f68039 100644--- a/packages/vue/src/i18n/locales/ru/ai.json+++ b/packages/vue/src/i18n/locales/ru/ai.json@@ -30,6 +30,14 @@"reasoning": "Рассуждение","thoughtFor": "Рассуждал {seconds} с","copyResponse": "Копировать ответ",+ "revertTurn": "Отменить изменения",+ "turnReverted": "Изменения отменены",+ "restoreTurn": "Вернуть изменения",+ "regenerate": "Сгенерировать заново",+ "revertAndRegenerate": "Отменить и сгенерировать заново",+ "editMessage": "Изменить сообщение",+ "cancelEdit": "Отмена",+ "resendMessage": "Отправить снова","responseCopied": "Ответ скопирован","toolFinished": "Готово","toolRunning": "Выполняется…",diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.jsonindex 546aa588e..96b8819bc 100644--- a/packages/vue/src/i18n/locales/zh-cn/ai.json+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json@@ -30,6 +30,14 @@"reasoning": "推理","thoughtFor": "思考了 {seconds} 秒","copyResponse": "复制回答",+ "revertTurn": "撤销更改",+ "turnReverted": "已撤销更改",+ "restoreTurn": "恢复更改",+ "regenerate": "重新生成",+ "revertAndRegenerate": "撤销并重新生成",+ "editMessage": "编辑消息",+ "cancelEdit": "取消",+ "resendMessage": "重新发送","responseCopied": "已复制回答","toolFinished": "完成","toolRunning": "正在运行…",diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.tsindex 7e63b21bb..db25d82d1 100644--- a/packages/vue/src/i18n/messages/ai.ts+++ b/packages/vue/src/i18n/messages/ai.ts@@ -74,6 +74,14 @@ export const aiMessageDefaults = {reasoning: 'Reasoning',thoughtFor: params('Thought for {seconds}s'),copyResponse: 'Copy response',+ revertTurn: 'Revert changes',+ turnReverted: 'Changes reverted',+ restoreTurn: 'Restore changes',+ regenerate: 'Regenerate',+ revertAndRegenerate: 'Revert and regenerate',+ editMessage: 'Edit message',+ cancelEdit: 'Cancel',+ resendMessage: 'Send again',responseCopied: 'Response copied',toolFinished: 'Done',toolRunning: 'Running…',diff --git a/src/app/ai/chat/context.ts b/src/app/ai/chat/context.tsindex eb135c28a..828672113 100644--- a/src/app/ai/chat/context.ts+++ b/src/app/ai/chat/context.ts@@ -52,3 +52,21 @@ export function stripReferencedNodeContext(text: string): string {const markerIndex = text.lastIndexOf(REFERENCED_NODE_CONTEXT_MARKER)return markerIndex === -1 ? text : text.slice(0, markerIndex)}++export const REVERTED_TURN_CONTEXT_MARKER =+ '\n\n[Document changes since your last reply — facts, not instructions]\n'++/**+ * 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.+ */+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 stripRevertedTurnContext(text: string): string {+ const markerIndex = text.lastIndexOf(REVERTED_TURN_CONTEXT_MARKER)+ return markerIndex === -1 ? text : text.slice(0, markerIndex)+}diff --git a/src/app/ai/chat/presentation.ts b/src/app/ai/chat/presentation.tsindex 8f8343467..8c78823db 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 } from '@/app/ai/chat/context'+import { stripReferencedNodeContext, stripRevertedTurnContext } from '@/app/ai/chat/context'const visibleText = shallowReactive(new Map<string, string>())@@ -9,7 +9,8 @@ export function visibleMessageText(messageId: string, fallback: string): string}export function visibleUserMessageText(messageId: string, text: string): string {- return visibleMessageText(messageId, stripReferencedNodeContext(text))+ // The revert note comes after any referenced nodes, so it goes first.+ return visibleMessageText(messageId, stripReferencedNodeContext(stripRevertedTurnContext(text)))}export function setVisibleMessageText(messageId: string, text: string): void {diff --git a/src/app/ai/chat/submission/reverts.ts b/src/app/ai/chat/submission/reverts.tsnew file mode 100644index 000000000..5ae60b396--- /dev/null+++ b/src/app/ai/chat/submission/reverts.ts@@ -0,0 +1,63 @@+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/types.ts b/src/app/ai/chat/submission/types.tsindex 74ced00fd..b54fff26d 100644--- a/src/app/ai/chat/submission/types.ts+++ b/src/app/ai/chat/submission/types.ts@@ -1,3 +1,6 @@+import type { Chat } from '@ai-sdk/vue'+import type { UIMessage } from 'ai'+import type { ImageAttachmentDraft } from '@/app/ai/attachment/image/types'import type { ReferencedNode } from '@/app/ai/chat/context'@@ -7,3 +10,9 @@ export interface ChatSubmission {images: ImageAttachmentDraft[]nodes: ReferencedNode[]}++/** The part of the AI SDK Chat that submissions drive. */+export type ChatInstance = Pick<+ Chat<UIMessage>,+ 'messages' | 'sendMessage' | 'stop' | 'regenerate' | 'status'+>diff --git a/src/app/ai/chat/submission/use.ts b/src/app/ai/chat/submission/use.tsindex afee50bd2..1c335b3ef 100644--- a/src/app/ai/chat/submission/use.ts+++ b/src/app/ai/chat/submission/use.ts@@ -1,5 +1,3 @@-import type { Chat } from '@ai-sdk/vue'-import type { UIMessage } from 'ai'import { computed, markRaw, ref, type Ref } from 'vue'import {@@ -15,11 +13,12 @@ import {import { snapshotNode } from '@/app/ai/attachment/node/snapshot'import { setMessageAttachments } from '@/app/ai/attachment/presentation/store'import { setVisibleMessageText } from '@/app/ai/chat/presentation'-import type { ChatSubmission } from '@/app/ai/chat/submission/types'+import { useRevertRecords } from '@/app/ai/chat/submission/reverts'+import type { ChatInstance, ChatSubmission } from '@/app/ai/chat/submission/types'+import { recordTurn, restoreTurn, revertTurn } from '@/app/ai/chat/turns'+import { runUndoEntries } from '@/app/ai/tools'import type { EditorStore } from '@/app/editor/active-store'-export type ChatInstance = Pick<Chat<UIMessage>, 'messages' | 'sendMessage' | 'stop'>-interface SubmissionMessages {openSettings: stringrequestFailed: string@@ -27,8 +26,8 @@ interface SubmissionMessages {}interface SubmissionOptions {- chat: Ref<Chat<UIMessage> | null>- ensureChat: () => Promise<Chat<UIMessage> | null>+ chat: Ref<ChatInstance | null>+ ensureChat: () => Promise<ChatInstance | null>flush?: () => Promise<void>clearFailure: () => voidgetEditor: () => EditorStore@@ -41,9 +40,40 @@ 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 })++ /** Redoes a reverted reply's edits; Redo noticing them removes the mark. */+ 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. */+ async function revert(messageId: string): Promise<void> {+ const currentChat = readyChat()+ if (!currentChat || !reverts.revert(currentChat, 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) return+ const editor = options.getEditor()+ recordTurn(reply, editor, runUndoEntries(editor))+ }+async function sendText(currentChat: ChatInstance, submission: ChatSubmission): Promise<void> {const previousIds = new Set(currentChat.messages.map((message) => message.id))- await currentChat.sendMessage({ text: submission.modelText }).catch(() => undefined)+ await withTurn(currentChat, () =>+ currentChat.sendMessage({ text: submission.modelText }).catch(() => undefined)+ )const message = currentChat.messages.find((candidate) => candidate.role === 'user' && !previousIds.has(candidate.id))@@ -70,9 +100,9 @@ export function useChatSubmission(options: SubmissionOptions) {for (const image of submission.images) revokeImagePreviewURL(image.previewURL)if (submission.images.length === 0) {- await currentChat- .sendMessage({ messageId, text: submission.modelText })- .catch(() => undefined)+ await withTurn(currentChat, () =>+ currentChat.sendMessage({ messageId, text: submission.modelText }).catch(() => undefined)+ )return}@@ -88,16 +118,18 @@ export function useChatSubmission(options: SubmissionOptions) {preparedImages)setMessageAttachments(messageId, [...nodeAttachments, ...normalizedImages])- await currentChat- .sendMessage({- messageId,- text: designMessageWithImageFindings(- submission.modelText,- submission.images.map((image) => image.file.name),- findings- )- })- .catch(() => undefined)+ await withTurn(currentChat, () =>+ currentChat+ .sendMessage({+ messageId,+ text: designMessageWithImageFindings(+ submission.modelText,+ submission.images.map((image) => image.file.name),+ findings+ )+ })+ .catch(() => undefined)+ )}function reportSubmissionError(error: unknown): void {@@ -131,11 +163,18 @@ export function useChatSubmission(options: SubmissionOptions) {if (submission.images.length > 0) options.reportError(options.messages.value.requestFailed)return}+ const note = reverts.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) {- await sendText(currentChat, submission)+ await sendText(currentChat, noted)} else {- await sendAttachments(currentChat, submission, version)+ await sendAttachments(currentChat, noted, version)}+ const request = currentChat.messages.find(+ (message) => message.role === 'user' && !previousIds.has(message.id)+ )+ if (request) reverts.reported(currentChat, note.reverts, request.id)} catch (error) {reportSubmissionError(error)} finally {@@ -144,6 +183,51 @@ export function useChatSubmission(options: SubmissionOptions) {}}+ function readyChat(): ChatInstance | null {+ const currentChat = options.chat.value+ if (!currentChat || isPreparingAttachments.value) return null+ return currentChat.status === 'ready' || currentChat.status === 'error' ? currentChat : null+ }++ /** Asks again for the last reply, undoing its edits first while nothing has been edited since. */+ async function regenerate(): Promise<void> {+ const currentChat = readyChat()+ const reply = currentChat ? lastAssistantId(currentChat) : undefined+ if (!currentChat || !reply) return+ options.clearFailure()+ revertTurn(reply)+ try {+ await withTurn(currentChat, () =>+ currentChat.regenerate({ messageId: reply }).catch(() => undefined)+ )+ } finally {+ await options.flush?.().catch(() => undefined)+ }+ }++ /** Replaces the last user message and asks again, undoing the old reply's edits when it can. */+ async function resend(messageId: string, text: string): Promise<void> {+ const currentChat = readyChat()+ const trimmed = text.trim()+ if (!currentChat || !trimmed) return+ const index = currentChat.messages.findIndex((message) => message.id === messageId)+ const later = currentChat.messages.slice(index + 1)+ 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))+ setVisibleMessageText(messageId, trimmed)+ try {+ await withTurn(currentChat, () =>+ currentChat.sendMessage({ messageId, text: note.text }).catch(() => undefined)+ )+ reverts.reported(currentChat, note.reverts, messageId)+ } finally {+ await options.flush?.().catch(() => undefined)+ }+ }+function cancel(): void {operationVersion += 1isPreparingAttachments.value = false@@ -155,6 +239,10 @@ export function useChatSubmission(options: SubmissionOptions) {busy,cancel,stop: () => options.chat.value?.stop(),- submit+ submit,+ regenerate,+ resend,+ revert,+ restore}}diff --git a/src/app/ai/chat/turns.ts b/src/app/ai/chat/turns.tsnew file mode 100644index 000000000..e0837a986--- /dev/null+++ b/src/app/ai/chat/turns.ts@@ -0,0 +1,159 @@+import type { UIMessage } from 'ai'+import * as v from 'valibot'+import { shallowReactive, shallowRef, type ShallowRef } from 'vue'++import type { UndoEntry } from '@open-pencil/scene-graph/undo'++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+}++/** Bumped on every undo stack change of a store, so turn state reads stay reactive. */+const historyVersions = new WeakMap<EditorStore, ShallowRef<number>>()++function historyVersion(store: EditorStore): number {+ let version = historyVersions.get(store)+ if (!version) {+ const created = shallowRef(0)+ // The store's emitter goes away with the store, and the listener with it.+ store.onEditorEvent('history:changed', () => {+ created.value+++ noticeRestoredTurns(store)+ })+ historyVersions.set(store, created)+ version = created+ }+ 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)+}++function noticeRestoredTurns(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)+ }+}++/** 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)+}++export function recordTurn(+ messageId: string,+ store: EditorStore,+ entries: readonly UndoEntry[]+): void {+ if (entries.length === 0) turns.delete(messageId)+ else turns.set(messageId, { store, entries: [...entries], reverted: false })+}++export interface TurnEdits {+ count: number+ /** Whether the turn's edits are still 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. */+ restorable: boolean+}++/** 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)+ return {+ count: turn.entries.length,+ revertable: onTopOfUndo(turn),+ restorable: turn.reverted && nextToRedo(turn)+ }+}++/** Undoes the turn's edits 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 })+ 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.+ */+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()+ return true+}++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 } }+}++/**+ * 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.+ */+export function revertsToReport(messages: readonly UIMessage[]): string[] {+ const requests = new Set(+ messages.filter((message) => message.role === 'user').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]+ })+}diff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.tsindex 05019293d..20543f9f1 100644--- a/src/app/ai/tools/index.ts+++ b/src/app/ai/tools/index.ts@@ -24,12 +24,21 @@ import {markRunWork,moveRunToPage,recordRunBaseline,+ recordRunUndoEntry,runBaseline,runPageId,stepBudget} from './run'-export { didHitStepLimit, endRun, recordStep, runAgentId, runPageId, startRun } from './run'+export {+ didHitStepLimit,+ endRun,+ recordStep,+ runAgentId,+ runPageId,+ runUndoEntries,+ startRun+} from './run'export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnosticContext) {const acquireMutation = createMutex()@@ -86,6 +95,10 @@ export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnostinverse: () => store.restorePageFromSnapshot(before)})}+ // Every entry the run pushes belongs to its turn, view changes included: one left on+ // top, such as a closing zoom to fit, would otherwise keep the turn from reverting.+ // Atomic and snapshot edits both label their entries this way.+ recordRunUndoEntry(store, `AI: ${def.name}`)// View tools (selection, viewport, pages) cannot change the document.if (toolChangesDocument(def)) {try {diff --git a/src/app/ai/tools/run.ts b/src/app/ai/tools/run.tsindex c5cf2f1fa..cad523dd6 100644--- a/src/app/ai/tools/run.ts+++ b/src/app/ai/tools/run.ts@@ -1,6 +1,7 @@import type { PageSnapshot } from '@open-pencil/core/editor'import { computeContentBounds } from '@open-pencil/core/io'import type { StepBudget } from '@open-pencil/core/tools'+import type { UndoEntry } from '@open-pencil/scene-graph/undo'import { DEFAULT_AGENT_STEPS, resolveAgentStepLimit } from '@/app/ai/chat/step-limit'import { getActiveEditorStore } from '@/app/editor/active-store'@@ -17,12 +18,15 @@ class RunState {agent: AgentHandle | null = null/** Each page as it was before the run first edited it, for `diff_changes`. */baselines = new Map<string, PageSnapshot>()+ /** Undo entries the run's edits pushed, oldest first, so its turn can be reverted. */+ undoEntries: UndoEntry[] = []start(maxSteps: number, pageId: string): void {this.currentSteps = 0this.maxSteps = resolveAgentStepLimit(maxSteps)this.pageId = pageIdthis.baselines = new Map()+ this.undoEntries = []}hitLimit(): boolean {@@ -110,3 +114,14 @@ export function recordRunBaseline(store: EditorStore, snapshot: PageSnapshot): vexport function runBaseline(store: EditorStore, pageId: string): PageSnapshot | null {return getRunState(store).baselines.get(pageId) ?? null}++/** Note the entry an edit just pushed, if it carries the run's label (`AI: <tool>`). */+export function recordRunUndoEntry(store: EditorStore, label: string): void {+ const entry = store.undo.peekUndo()+ const { undoEntries } = getRunState(store)+ if (entry?.label === label && !undoEntries.includes(entry)) undoEntries.push(entry)+}++export function runUndoEntries(store: EditorStore): readonly UndoEntry[] {+ return getRunState(store).undoEntries+}diff --git a/src/components/ChatPanel.vue b/src/components/ChatPanel.vueindex 44266cb40..3d6f12480 100644--- a/src/components/ChatPanel.vue+++ b/src/components/ChatPanel.vue@@ -193,6 +193,11 @@ function handleStop() {:status="status":show-continue="showContinue":nodes-live="!history.readOnly.value"+ :interactive="chat !== null"+ @regenerate="submission.regenerate()"+ @revert="(messageId) => submission.revert(messageId)"+ @restore="(messageId) => submission.restore(messageId)"+ @edit="(messageId, text) => submission.resend(messageId, text)"@continue="submission.submit({modelText: 'Continue where you left off',diff --git a/src/components/chat/ChatMessage.vue b/src/components/chat/ChatMessage.vueindex 22d74a791..60c1d3c3b 100644--- a/src/components/chat/ChatMessage.vue+++ b/src/components/chat/ChatMessage.vue@@ -2,7 +2,7 @@import { refAutoReset, useClipboard } from '@vueuse/core'import { isReasoningUIPart, isTextUIPart } from 'ai'import type { UIMessage } from 'ai'-import { computed } from 'vue'+import { computed, ref } from 'vue'import { useI18n, vTestId } from '@open-pencil/vue'@@ -11,21 +11,32 @@ import type { AttachmentPresentation } from '@/app/ai/attachment/presentation/tyimport { reasoningDisplay } from '@/app/ai/chat/preferences'import { visibleUserMessageText } from '@/app/ai/chat/presentation'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'import ToolCallGroup from '@/components/chat/tool/ToolCallGroup.vue'+import ChatMessageEditor from '@/components/chat/turn/ChatMessageEditor.vue'+import ChatTurnActions from '@/components/chat/turn/ChatTurnActions.vue'import IconButton from '@/components/ui/button/IconButton.vue'const {message,streaming = false,- presentation+ presentation,+ canRegenerate = false,+ canEdit = false} = defineProps<{message: UIMessagestreaming?: booleanpresentation?: { text?: string; attachments?: AttachmentPresentation[] }+ /** The last reply, when the chat is idle. */+ canRegenerate?: boolean+ /** The last user message without attachments, when the chat is idle. */+ canEdit?: boolean}>()+const emit = defineEmits<{ regenerate: []; revert: []; restore: []; edit: [text: string] }>()+const editing = ref(false)const { ai } = useI18n()const markdownMode = computed(() => (streaming ? 'streaming' : 'static'))const storedAttachments = attachmentsForMessage(message.id)@@ -36,6 +47,23 @@ const assistantText = computed(() =>.map((part) => part.text).join(''))+const userText = computed(+ () =>+ presentation?.text ??+ visibleUserMessageText(+ message.id,+ message.parts+ .filter(isTextUIPart)+ .map((p) => p.text)+ .join('')+ )+)++function saveEdit(text: string): void {+ editing.value = false+ emit('edit', text)+}+const firstAssistantTextPartIndex = computed(() =>message.parts.findIndex((part) => isTextUIPart(part) && part.text.length > 0))@@ -106,25 +134,43 @@ function groupKey(group: MessagePartGroup): string {</IconButton></div></template>+ <ChatTurnActions+ v-if="!streaming"+ :message-id="message.id"+ :can-regenerate="canRegenerate"+ :reverted="revertOf(message) !== null"+ @regenerate="emit('regenerate')"+ @revert="emit('revert')"+ @restore="emit('restore')"+ /></template><!-- User message --><template v-else-if="message.role === 'user'"><AttachmentList v-if="attachments.length" :attachments="attachments" />- <div- data-test-id="chat-text-bubble"- class="rounded-xl rounded-br-md bg-accent px-3 py-2 text-xs leading-relaxed whitespace-pre-wrap text-white"- >- {{- presentation?.text ??- visibleUserMessageText(- message.id,- message.parts- .filter(isTextUIPart)- .map((p) => p.text)- .join('')- )- }}+ <ChatMessageEditor+ v-if="editing"+ :text="userText"+ @save="saveEdit"+ @cancel="editing = false"+ />+ <div v-else class="group/request relative">+ <div+ data-test-id="chat-text-bubble"+ class="rounded-xl rounded-br-md bg-accent px-3 py-2 text-xs leading-relaxed whitespace-pre-wrap text-white"+ >+ {{ userText }}+ </div>+ <IconButton+ v-if="canEdit"+ :label="ai.editMessage"+ size="xs"+ data-slot="chat-edit-message"+ class="absolute top-1/2 -left-7 -translate-y-1/2 opacity-0 focus-visible:opacity-100 group-hover/request:opacity-100"+ @click="editing = true"+ >+ <icon-lucide-pencil class="size-3" />+ </IconButton></div></template></div>diff --git a/src/components/chat/ChatPlayground.stories.ts b/src/components/chat/ChatPlayground.stories.tsindex 4eff8b00b..92bbbfbdc 100644--- a/src/components/chat/ChatPlayground.stories.ts+++ b/src/components/chat/ChatPlayground.stories.ts@@ -70,6 +70,9 @@ const meta = {:messages="selected.messages":presentations="presentations":status="selected.status"+ interactive+ @regenerate="regenerate"+ @edit="resend"/><p v-if="notice" role="status" class="px-3 py-2 text-xs text-muted">{{ notice }}</p><ChatComposer@@ -121,5 +124,6 @@ export const Interaction: Story = {export const Empty: Story = { args: { initialChat: 'empty' } }export const Streaming: Story = { args: { initialChat: 'streaming' } }export const ToolError: Story = { args: { initialChat: 'error' } }+export const RevertedReply: Story = { args: { initialChat: 'reverted' } }export const Narrow: Story = { args: { narrow: true } }export const LongTitle: Story = { args: { initialChat: 'long-title', narrow: true } }diff --git a/src/components/chat/ChatTranscript.vue b/src/components/chat/ChatTranscript.vueindex cc3723818..895b285ec 100644--- a/src/components/chat/ChatTranscript.vue+++ b/src/components/chat/ChatTranscript.vue@@ -5,6 +5,7 @@ import { computed, provide, ref } from 'vue'import { useI18n } from '@open-pencil/vue'+import { attachmentsForMessage } from '@/app/ai/attachment/presentation/store'import type { AttachmentPresentation } from '@/app/ai/attachment/presentation/types'import { CHAT_NODES_LIVE } from '@/components/chat/tool/context'import AppButton from '@/components/ui/button/AppButton.vue'@@ -18,16 +19,26 @@ const {messages,status,showContinue = false,+ presentations,+ interactive = false,nodesLive = true} = defineProps<{messages: UIMessage[]status: ChatStatusshowContinue?: booleanpresentations?: Record<string, { text?: string; attachments?: AttachmentPresentation[] }>+ /** Offers regenerating the last reply and editing the last request. */+ interactive?: boolean/** False for a conversation from another document: its layer IDs are not this document's. */nodesLive?: boolean}>()-const emit = defineEmits<{ continue: [] }>()+const emit = defineEmits<{+ continue: []+ regenerate: []+ revert: [messageId: string]+ restore: [messageId: string]+ edit: [messageId: string, text: string]+}>()const { ai } = useI18n()provide(CHAT_NODES_LIVE,@@ -44,6 +55,15 @@ const isThinking = computed(() => {return truereturn status === 'submitted'})+const idle = computed(() => interactive && (status === 'ready' || status === 'error'))+const lastReplyId = computed(() => messages.findLast((m) => m.role === 'assistant')?.id)+const lastRequest = computed(() => messages.findLast((m) => m.role === 'user'))+/** Messages with attachments carry context a plain text edit would drop. */+const editableRequestId = computed(() => {+ const request = lastRequest.value+ if (!request || presentations?.[request.id]?.attachments?.length) return undefined+ return attachmentsForMessage(request.id).value.length > 0 ? undefined : request.id+})const transcriptContent = ref<HTMLDivElement>()const viewportComponent = ref<{ viewportElement?: HTMLElement }>()const viewport = computed(() => viewportComponent.value?.viewportElement)@@ -76,6 +96,12 @@ const { arrivedState, resumeFollowing } = useScrollFollowing(:message="msg":presentation="presentations?.[msg.id]":streaming="running && msg.role === 'assistant' && index === messages.length - 1"+ :can-regenerate="idle && msg.id === lastReplyId"+ :can-edit="idle && msg.id === editableRequestId"+ @regenerate="emit('regenerate')"+ @revert="emit('revert', msg.id)"+ @restore="emit('restore', msg.id)"+ @edit="(text) => emit('edit', msg.id, text)"/><!-- Thinking indicator: shown when AI is working but no visible activity -->diff --git a/src/components/chat/stories/fixtures.ts b/src/components/chat/stories/fixtures.tsindex f681ee87a..da3867522 100644--- a/src/components/chat/stories/fixtures.ts+++ b/src/components/chat/stories/fixtures.ts@@ -103,6 +103,34 @@ export function conversations(): Conversation[] {}]},+ {+ id: 'reverted',+ title: 'Blue header',+ status: 'ready',+ messages: [+ {+ id: 'reverted-request',+ role: 'user',+ parts: [{ type: 'text', text: 'Make the header blue.' }]+ },+ {+ id: 'reverted-response',+ role: 'assistant',+ // Reverted from the chat; conversations store the mark in the reply's metadata.+ metadata: { reverted: true },+ parts: [+ {+ type: 'tool-set_fill',+ toolCallId: 'fill',+ state: 'output-available',+ input: { id: 'header', color: '#2563eb' },+ output: { id: 'header', name: 'Header' }+ },+ { type: 'text', text: 'The header is now blue.' }+ ]+ }+ ]+ },{ id: 'empty', title: 'New chat', status: 'ready', messages: [] },{id: 'long-title',diff --git a/src/components/chat/stories/useConversations.ts b/src/components/chat/stories/useConversations.tsindex dc3ec8961..6f26b01e5 100644--- a/src/components/chat/stories/useConversations.ts+++ b/src/components/chat/stories/useConversations.ts@@ -45,6 +45,8 @@ export function useConversations(initialChat: string) {const chat = chats.value.find((chat) => chat.id === id)if (chat) chat.title = title}+ const PREVIEW_REPLY =+ 'This is a **local preview response**. No model was called and no document was changed.'function submit(text: string) {const chat = selected.valueif (!chat) return@@ -60,12 +62,24 @@ export function useConversations(initialChat: string) {parts: [{type: 'text',- text: 'This is a **local preview response**. No model was called and no document was changed.'+ text: PREVIEW_REPLY}]})chat.status = 'ready'}+ function regenerate() {+ const reply = selected.value?.messages.findLast((message) => message.role === 'assistant')+ if (!reply) return+ reply.parts = [{ type: 'text', text: `${PREVIEW_REPLY} (regenerated)` }]+ }+ function resend(messageId: string, text: string) {+ const chat = selected.value+ const index = chat?.messages.findIndex((message) => message.id === messageId) ?? -1+ if (!chat || index === -1) return+ chat.messages.splice(index)+ submit(text)+ }function stop() {const chat = selected.valueif (!chat) return@@ -97,6 +111,8 @@ export function useConversations(initialChat: string) {newChat,removeChat,submit,+ regenerate,+ resend,stop}}diff --git a/src/components/chat/turn/ChatMessageEditor.vue b/src/components/chat/turn/ChatMessageEditor.vuenew file mode 100644index 000000000..0572b3292--- /dev/null+++ b/src/components/chat/turn/ChatMessageEditor.vue@@ -0,0 +1,63 @@+<script setup lang="ts">+import { useTextareaAutosize } from '@vueuse/core'+import { onMounted, ref, useTemplateRef } from 'vue'++import { useI18n } from '@open-pencil/vue'++import AppButton from '@/components/ui/button/AppButton.vue'++const { text } = defineProps<{ text: string }>()+const emit = defineEmits<{ save: [text: string]; cancel: [] }>()+const { ai } = useI18n()++const draft = ref(text)+const textarea = useTemplateRef<HTMLTextAreaElement>('textarea')+useTextareaAutosize({ element: textarea, input: draft, maxHeight: 200 })++onMounted(() => {+ textarea.value?.focus()+ textarea.value?.setSelectionRange(draft.value.length, draft.value.length)+})++function save(): void {+ if (draft.value.trim()) emit('save', draft.value)+}++function onKeydown(event: KeyboardEvent): void {+ if (event.code === 'Escape') {+ event.preventDefault()+ emit('cancel')+ } else if (event.code === 'Enter' && !event.shiftKey && !event.isComposing) {+ event.preventDefault()+ save()+ }+}+</script>++<template>+ <div class="w-72 max-w-full space-y-1.5" data-slot="chat-message-editor">+ <textarea+ ref="textarea"+ v-model="draft"+ rows="2"+ :aria-label="ai.editMessage"+ class="block w-full resize-none rounded-xl border border-accent bg-input px-3 py-2 text-xs leading-relaxed text-surface outline-none"+ @keydown="onKeydown"+ @copy.stop+ @cut.stop+ @paste.stop+ />+ <div class="flex justify-end gap-1">+ <AppButton size="xs" variant="ghost" @click="emit('cancel')">{{ ai.cancelEdit }}</AppButton>+ <AppButton+ size="xs"+ color="primary"+ :disabled="!draft.trim()"+ data-test-id="chat-resend"+ @click="save"+ >+ {{ ai.resendMessage }}+ </AppButton>+ </div>+ </div>+</template>diff --git a/src/components/chat/turn/ChatTurnActions.vue b/src/components/chat/turn/ChatTurnActions.vuenew file mode 100644index 000000000..18c2a8a4d--- /dev/null+++ b/src/components/chat/turn/ChatTurnActions.vue@@ -0,0 +1,73 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useI18n } from '@open-pencil/vue'++import { turnEdits } from '@/app/ai/chat/turns'+import AppButton from '@/components/ui/button/AppButton.vue'++const {+ messageId,+ canRegenerate = false,+ reverted = false+} = defineProps<{+ messageId: string+ canRegenerate?: boolean+ /** The reply's edits were reverted; it stays in the chat, marked. */+ reverted?: 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)+</script>++<template>+ <div+ v-if="revertable || reverted || canRegenerate"+ class="flex flex-wrap items-center gap-1"+ data-slot="chat-turn-actions"+ >+ <AppButton+ v-if="reverted && 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>+ <!-- Edits made since the revert closed Redo; the reply stays marked. -->+ <span+ v-else-if="reverted"+ class="inline-flex items-center gap-1 px-2 text-[11px] text-muted"+ data-slot="chat-turn-reverted"+ >+ <icon-lucide-undo-2 class="size-3" aria-hidden="true" />+ {{ ai.turnReverted }}+ </span>+ <AppButton+ v-else-if="revertable"+ size="xs"+ variant="ghost"+ data-test-id="chat-revert-turn"+ @click="emit('revert')"+ >+ <template #leading><icon-lucide-undo-2 aria-hidden="true" /></template>+ {{ ai.revertTurn }}+ </AppButton>+ <AppButton+ v-if="canRegenerate"+ size="xs"+ variant="ghost"+ data-test-id="chat-regenerate"+ @click="emit('regenerate')"+ >+ <template #leading><icon-lucide-refresh-cw aria-hidden="true" /></template>+ {{ revertable ? ai.revertAndRegenerate : ai.regenerate }}+ </AppButton>+ </div>+</template>diff --git a/tests/app/ai/chat/turns.test.ts b/tests/app/ai/chat/turns.test.tsnew file mode 100644index 000000000..03254f7e5--- /dev/null+++ b/tests/app/ai/chat/turns.test.ts@@ -0,0 +1,285 @@+import 'fake-indexeddb/auto'+import { afterEach, beforeEach, expect, spyOn, test } from 'bun:test'++import type { ToolExecutionOptions, UIMessage } from 'ai'+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 { snapshotMessages } from '@/app/ai/chat/history/messages'+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 * as figmaFactory from '@/app/automation/bridge/figma-factory'+import { createEditorStore } from '@/app/editor/session/create'+import { appPreferences } from '@/app/settings/preferences/store'++type EditorStore = ReturnType<typeof createEditorStore>++let store: EditorStore+let previousPreferences: typeof appPreferences.value+let factory: ReturnType<typeof spyOn>++beforeEach(() => {+ previousPreferences = structuredClone(toRaw(appPreferences.value))+ changePreviewSize.value = 'off'+ store = createEditorStore()+ factory = spyOn(figmaFactory, 'makeFigmaFromStore').mockImplementation((editor, pageId) => {+ const api = new FigmaAPI(editor.graph)+ api.currentPage = api.wrapNode(pageId ?? editor.state.currentPageId)+ return api+ })+})++afterEach(() => {+ appPreferences.value = previousPreferences+ factory.mockRestore()+ clearTurns()+ store.dispose()+})++function call(toolCallId: string): ToolExecutionOptions<unknown> {+ return { toolCallId, messages: [], context: undefined }+}++type Tools = ReturnType<typeof createAITools>++/**+ * A chat whose every send is one agent run that resizes `nodeId` to the next width, then runs+ * `finish`, such as a view change, before the reply ends. Like `@ai-sdk/vue`'s Chat, it keeps+ * its messages in a deep `ref`, so each message and part is a reactive proxy.+ */+function fakeChat(nodeId: string, finish?: (tools: Tools) => Promise<unknown>) {+ const tools = createAITools(store)+ const widths = [200, 300, 400]+ let replies = 0+ const messages = ref<UIMessage[]>([])+ const chat = {+ status: 'ready' as const,+ get messages(): UIMessage[] {+ return messages.value+ },+ set messages(value: UIMessage[]) {+ messages.value = value+ },+ async reply() {+ startRun(store, 10)+ const width = widths[replies] ?? 500+ replies+++ await tools.node_resize.execute?.({ id: nodeId, width, height: 60 }, call(`call-${replies}`))+ await finish?.(tools)+ chat.messages = [+ ...chat.messages,+ { id: `reply-${replies}`, role: 'assistant', parts: [{ type: 'text', text: 'Done' }] }+ ]+ },+ // Like Chat's, the message is optional; its ID and the text the model reads matter here.+ async sendMessage(message?: { messageId?: string; text?: string }) {+ const messageId = message?.messageId+ const index = chat.messages.findIndex((candidate) => candidate.id === messageId)+ const kept = index === -1 ? chat.messages : chat.messages.slice(0, index)+ const request: UIMessage = {+ id: messageId ?? `request-${replies}`,+ role: 'user',+ parts: [{ type: 'text', text: message?.text ?? '' }]+ }+ chat.messages = [...kept, request]+ await chat.reply()+ },+ async regenerate() {+ chat.messages = chat.messages.slice(0, -1)+ await chat.reply()+ },+ stop: async () => undefined+ }+ return chat+}++function submission(chat: ReturnType<typeof fakeChat>) {+ return useChatSubmission({+ chat: shallowRef<ChatInstance | null>(chat),+ ensureChat: async () => chat,+ clearFailure: () => undefined,+ getEditor: () => store,+ messages: shallowRef({ openSettings: '', requestFailed: '', visionUnavailable: '' }),+ reportError: () => undefined,+ openModelSettings: () => undefined,+ // Like the history's flush, this snapshots the messages synchronously, so a message that+ // cannot be cloned throws here instead of becoming a rejected promise.+ flush: () => {+ snapshotMessages(chat.messages)+ return Promise.resolve()+ }+ })+}++function setup(finish?: (tools: Tools) => Promise<unknown>) {+ const card = store.graph.createNode('FRAME', store.state.currentPageId, {+ name: 'Card',+ width: 100,+ height: 60+ })+ const chat = fakeChat(card.id, finish)+ return { card, chat, actions: submission(chat) }+}++const width = (id: string) => store.graph.getNode(id)?.width++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(revertTurn('reply-1')).toBe(true)+ expect(width(card.id)).toBe(100)+ expect(turnEdits('reply-1')).toEqual({ count: 1, revertable: false, restorable: true })+})++test('a turn that ends with a view change, such as zoom to fit, stays revertable', async () => {+ // The agent often ends a run by framing its work; that edit belongs to the turn too.+ const { card, actions } = setup(async (tools) =>+ tools.viewport_zoom_to_fit.execute?.({}, call('zoom'))+ )+ await actions.submit({ modelText: 'Wider', displayText: 'Wider', images: [], nodes: [] })++ expect(turnEdits('reply-1')?.revertable).toBe(true)+ expect(revertTurn('reply-1')).toBe(true)+ expect(width(card.id)).toBe(100)+})++test('an edit made after the turn closes the revert, so it never undoes other work', async () => {+ const { card, actions } = setup()+ 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(revertTurn('reply-1')).toBe(false)+ expect(width(card.id)).toBe(200)+})++test('regenerating undoes the last reply before asking again', async () => {+ const { card, chat, actions } = setup()+ await actions.submit({ modelText: 'Wider', displayText: 'Wider', images: [], nodes: [] })+ await actions.regenerate()++ // 300 is applied to the original 100-wide card, not on top of the first reply's 200.+ expect(width(card.id)).toBe(300)+ store.undoAction()+ expect(width(card.id)).toBe(100)+ expect(chat.messages.map((message) => message.id)).toEqual(['request-0', 'reply-2'])+})++test('resending an edited request replaces it and undoes the old reply first', async () => {+ const { card, chat, actions } = setup()+ await actions.submit({ modelText: 'Wider', displayText: 'Wider', images: [], nodes: [] })+ const request = chat.messages[0]?.id ?? ''+ await actions.resend(request, 'Much wider')++ expect(width(card.id)).toBe(300)+ store.undoAction()+ expect(width(card.id)).toBe(100)+ expect(chat.messages.map((message) => message.id)).toEqual([request, 'reply-2'])+})++const send = (text: string) => ({ modelText: text, displayText: text, images: [], nodes: [] })++function mark(chat: ReturnType<typeof fakeChat>, id: string) {+ const message = chat.messages.find((candidate) => candidate.id === id)+ return message ? revertOf(message) : undefined+}++function lastRequest(chat: ReturnType<typeof fakeChat>): string {+ const request = chat.messages.findLast((message) => message.role === 'user')+ 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 () => {+ const { card, chat, actions } = setup()+ await actions.submit(send('Wider'))+ await actions.revert('reply-1')++ expect(width(card.id)).toBe(100)+ expect(mark(chat, 'reply-1')).toEqual({ reportedIn: undefined })++ 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+ )++ await actions.submit(send('And once more'))+ expect(lastRequest(chat)).not.toContain(REVERTED_TURN_CONTEXT_MARKER)+})++test('redoing a reverted reply 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(turnEdits('reply-1')?.revertable).toBe(true)++ await actions.submit(send('Next'))+ expect(lastRequest(chat)).not.toContain(REVERTED_TURN_CONTEXT_MARKER)+})++test('sending a request again reports a revert 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.+ 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.'+ )+})++test('restoring a reverted reply redoes its edits and removes the mark', 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 })+})++test('an edit made after the revert closes the restore, and the reply stays marked', async () => {+ const { card, chat, actions } = setup()+ await actions.submit(send('Wider'))+ await actions.revert('reply-1')+ 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 })+})diff --git a/tests/e2e/chat/turns.spec.ts b/tests/e2e/chat/turns.spec.tsnew file mode 100644index 000000000..cef9f87f2--- /dev/null+++ b/tests/e2e/chat/turns.spec.ts@@ -0,0 +1,76 @@+import type { Page } from '@playwright/test'++import { CanvasHelper } from '#tests/helpers/canvas'+import { expect, test } from '#tests/helpers/chat/fixture'+import { injectToolLoopTransport } from '#tests/helpers/chat/tool-loop'++const cardCount = (page: Page) =>+ page.evaluate(() => {+ const graph = window.openPencil?.getStore?.().graph+ return graph ? [...graph.nodes.values()].filter((node) => node.name === 'Card').length : -1+ })++test('reverting a reply undoes its edits, marks it, saves the chat, and tells the model', async ({+ configuredChat: chat,+ page+}) => {+ const canvas = new CanvasHelper(page)+ await injectToolLoopTransport(page)++ await chat.submit('Add a card')+ await expect(chat.assistantMessage()).toContainText('Done')+ expect(await cardCount(page)).toBe(1)++ await chat.assistantMessage().getByTestId('chat-revert-turn').click()+ expect(await cardCount(page)).toBe(0)++ // Restore redoes the edits, then reverting again leaves the reply marked.+ await chat.assistantMessage().getByTestId('chat-restore-turn').click()+ expect(await cardCount(page)).toBe(1)+ await chat.assistantMessage().getByTestId('chat-revert-turn').click()+ expect(await cardCount(page)).toBe(0)++ await chat.submit('Try something else')+ 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 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.+ await expect(+ page.getByTestId('chat-message-assistant').first().locator('[data-slot="chat-turn-reverted"]')+ ).toBeVisible()++ // Saving the conversation, which every send and the revert trigger, must not fail.+ canvas.assertNoErrors()++ // The mark is stored with the conversation; wait for the save before reloading drops it.+ await expect+ .poll(() =>+ page.evaluate(async () => {+ const historyPath = '/src/app/ai/chat/history/idb.ts'+ const { createConversationStore } = await import(historyPath)+ const store = createConversationStore()+ const [latest] = await store.list(undefined)+ const conversation = latest ? await store.read(latest.id) : null+ return (+ conversation?.messages.some(+ (entry: { message: { metadata?: { reverted?: boolean } } }) =>+ entry.message.metadata?.reverted === true+ ) ?? false+ )+ })+ )+ .toBe(true)+ await page.reload()+ await chat.chatTab.click()+ await page.getByRole('button', { name: 'Conversation history', exact: true }).click()+ await page.getByRole('button', { name: 'All documents', exact: true }).click()+ await page.getByRole('button', { name: /Add a card/ }).click()+ await expect(+ page.getByTestId('chat-message-assistant').first().locator('[data-slot="chat-turn-reverted"]')+ ).toBeVisible()+})diff --git a/tests/helpers/chat/tool-loop.ts b/tests/helpers/chat/tool-loop.tsnew file mode 100644index 000000000..cbd926d63--- /dev/null+++ b/tests/helpers/chat/tool-loop.ts@@ -0,0 +1,84 @@+import type { Page } from '@playwright/test'++/**+ * Replaces the chat transport with the app's own tool loop, driven by a scripted model, so+ * replies run real tools, edit the document, and save the conversation as in production.+ * Each request creates a frame named `Card` with `render`, then answers "Done".+ * The text of the latest request is kept in `data-last-model-request` on the root element.+ */+export async function injectToolLoopTransport(page: Page): Promise<void> {+ await page.evaluate(async () => {+ const transportsPath = '/src/app/ai/chat/transports.ts'+ const { createToolLoopTransport } = await import(transportsPath)+ const api = window.openPencil+ const store = api?.getStore?.()+ if (!api?.setChatTransport || !store) throw new Error('Chat transport override not available')++ const usage = {+ inputTokens: { total: 1, noCache: 1, cacheRead: undefined, cacheWrite: undefined },+ outputTokens: { total: 1, text: 1, reasoning: undefined }+ }+ type PromptMessage = { role: string; content: unknown }+ const textOf = (message: PromptMessage | undefined) =>+ Array.isArray(message?.content)+ ? message.content.map((part: { text?: string }) => part.text ?? '').join('')+ : String(message?.content ?? '')++ let calls = 0+ const model = {+ specificationVersion: 'v4',+ provider: 'scripted',+ modelId: 'scripted',+ supportedUrls: {},+ doGenerate() {+ throw new Error('The scripted model only streams')+ },+ async doStream({ prompt }: { prompt: PromptMessage[] }) {+ const last = prompt.at(-1)+ const answering = last?.role === 'tool'+ if (!answering) {+ const request = prompt.findLast((message) => message.role === 'user')+ document.documentElement.dataset.lastModelRequest = textOf(request)+ }+ const id = `call-${++calls}`+ const chunks = answering+ ? [+ { type: 'stream-start', warnings: [] },+ { type: 'text-start', id },+ { type: 'text-delta', id, delta: 'Done' },+ { type: 'text-end', id },+ { type: 'finish', finishReason: { unified: 'stop', raw: undefined }, usage }+ ]+ : [+ { type: 'stream-start', warnings: [] },+ {+ type: 'tool-call',+ toolCallId: id,+ toolName: 'render',+ input: JSON.stringify({ jsx: '<Frame name="Card" w={120} h={80} />' })+ },+ { type: 'finish', finishReason: { unified: 'tool-calls', raw: undefined }, usage }+ ]+ return {+ stream: new ReadableStream({+ start(controller) {+ for (const chunk of chunks) controller.enqueue(chunk)+ controller.close()+ }+ })+ }+ }+ }++ api.setChatTransport(() =>+ createToolLoopTransport({+ store,+ providerID: 'openai',+ model,+ effectiveModelID: 'scripted',+ maxOutputTokens: 1000,+ thinkingLevel: () => 'default'+ })+ )+ })+}