Skip to content

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

feat(ai): save chat traces that rebuild every request, and diagnostics as files (#1159)

Danila Poyarkovf479428befa3
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index 00c54b5c0..6002f3bbc 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -83,6 +83,14 @@ body:
description: Attach relevant .fig/.pen/SVG files, screenshots, screen recordings, or link to a Figma file if possible.
placeholder: Drag files here or paste links.
+ - type: textarea
+ id: diagnostics
+ attributes:
+ label: Diagnostics
+ description: |
+ In the app, **Settings › Diagnostics › Save diagnostics…** saves recent technical events. It leaves out chat messages and tool payloads and scrubs keys and personal paths from error messages, but an error can still quote a name from your file, so skim it before attaching. For an AI chat problem, the conversation's **… › Save trace…** saves the whole conversation, including your prompts and tool output, so review it before attaching.
+ placeholder: Drag the saved .json files here.
+
- type: textarea
id: logs
attributes:
diff --git a/changes/1159/added.md b/changes/1159/added.md
new file mode 100644
index 000000000..7b8e5f710
--- /dev/null
+++ b/changes/1159/added.md
@@ -0,0 +1,2 @@
+- The conversation menu saves a chat's trace as a JSON file: every message, reasoning step, and tool call, and each run's model, settings, usage, timing, and errors, with enough to rebuild and check every request the model received.
+- Settings › Diagnostics saves the diagnostics report as a JSON file, next to Copy diagnostics.
diff --git a/packages/docs/development/ai-chat.md b/packages/docs/development/ai-chat.md
index 33e76ba18..0518b6fee 100644
--- a/packages/docs/development/ai-chat.md
+++ b/packages/docs/development/ai-chat.md
@@ -6,7 +6,7 @@ How the built-in AI chat turns a message into edits, how a reply ends, and how w
`src/app/ai/chat/submission/use.ts` sends a message through the AI SDK's `Chat`. Before sending, it appends notes for the model to the text: the layers you referenced, and the edits you undid or redid since the model last heard (`context.ts`). The transcript shows only what you wrote; `stripModelNotes` removes the notes. Notes go on the newest message only. Earlier messages never change, so the provider can keep caching the conversation up to the new message.
-`history/continuation.ts` leaves tool calls without a result out of the request. They stay in the saved transcript.
+`history/continuation.ts` (`requestMessages`) leaves tool calls without a result out of the request. They stay in the saved transcript.
## A run
@@ -55,3 +55,11 @@ Edit → Undo and the chat's **Revert changes** therefore end in the same state:
## 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.
+
+## Traces
+
+Save trace… in the conversation menu writes a file to reproduce what the agent did (`chat/trace/export.ts`). It holds the conversation's messages, its runs, and its diagnostic events.
+
+A run is one message sent and every step the model took to answer it (`chat/trace/recorder.ts`). It records the model and settings, the last message sent, and per step the response's finish reason, usage, warnings, and duration; a failed run keeps the error, and the step that failed is the one after the last recorded. Instructions and the tools offered are stored once under their fingerprints and shared by every run that used them.
+
+A step's request is not stored. It is the conversation through the run's last message, as `requestMessages` prepared it, plus the reply's earlier steps; `chat/trace/rebuild.ts` rebuilds it and compares its fingerprint with the one recorded when the step ran, so a rebuild that no longer matches what was sent is reported instead of replayed. Runs live in the chat database beside their conversation and are deleted with it.
diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.json
index 04efcaaec..766a9347a 100644
--- a/packages/vue/src/i18n/locales/de/ai.json
+++ b/packages/vue/src/i18n/locales/de/ai.json
@@ -166,6 +166,8 @@
"stopFollowingAgents": "Agenten bei der Arbeit nicht mehr folgen",
"allChats": "Alle Chats",
"renameChat": "Umbenennen",
+ "saveChatTrace": "Trace speichern…",
+ "chatTraceFailed": "Der Chat-Trace konnte nicht gespeichert werden.",
"deleteChat": "Löschen",
"chatTitle": "Chatname",
"saveChatTitle": "Speichern",
diff --git a/packages/vue/src/i18n/locales/de/diagnostics.json b/packages/vue/src/i18n/locales/de/diagnostics.json
index b7d45da4c..38e81b539 100644
--- a/packages/vue/src/i18n/locales/de/diagnostics.json
+++ b/packages/vue/src/i18n/locales/de/diagnostics.json
@@ -25,10 +25,12 @@
"description": "Technische Ereignisse lokal speichern, um OpenPencil zu unterstützen. Prompts, Designinhalte, Zugangsdaten und API-Schlüssel werden ausgeschlossen.",
"eventCount": "{count} Ereignisse · {size} KB",
"copy": "Diagnosedaten kopieren",
+ "save": "Diagnosedaten speichern…",
"clear": "Löschen",
"clearDescription": "Dadurch werden lokal gespeicherte Diagnosedaten von diesem Gerät entfernt.",
"cleared": "Diagnosedaten gelöscht.",
"copyFailed": "Diagnosedaten konnten nicht in die Zwischenablage kopiert werden.",
+ "saveFailed": "Diagnosedaten konnten nicht gespeichert werden.",
"retentionCustom": "Eigener Wert…",
"retentionRange": "Gib eine ganze Zahl von {min} bis {max} ein.",
"modelStep": "Modellschritt · {model}",
diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.json
index 673fdf776..45e39f523 100644
--- a/packages/vue/src/i18n/locales/es/ai.json
+++ b/packages/vue/src/i18n/locales/es/ai.json
@@ -166,6 +166,8 @@
"stopFollowingAgents": "Dejar de seguir a los agentes mientras trabajan",
"allChats": "Todos los chats",
"renameChat": "Renombrar",
+ "saveChatTrace": "Guardar traza…",
+ "chatTraceFailed": "No se pudo guardar la traza del chat.",
"deleteChat": "Eliminar",
"chatTitle": "Título del chat",
"saveChatTitle": "Guardar",
diff --git a/packages/vue/src/i18n/locales/es/diagnostics.json b/packages/vue/src/i18n/locales/es/diagnostics.json
index 674bf338f..c02fa9909 100644
--- a/packages/vue/src/i18n/locales/es/diagnostics.json
+++ b/packages/vue/src/i18n/locales/es/diagnostics.json
@@ -25,10 +25,12 @@
"description": "Guarda eventos técnicos localmente para ayudar a solucionar problemas de OpenPencil. Se excluyen prompts, contenido de diseño, credenciales y claves API.",
"eventCount": "{count} eventos · {size} KB",
"copy": "Copiar diagnóstico",
+ "save": "Guardar diagnóstico…",
"clear": "Borrar",
"clearDescription": "Esto elimina del dispositivo los eventos de diagnóstico almacenados localmente.",
"cleared": "Diagnóstico borrado.",
"copyFailed": "No se pudo copiar el diagnóstico al portapapeles.",
+ "saveFailed": "No se pudo guardar el diagnóstico.",
"retentionCustom": "Personalizado…",
"retentionRange": "Introduce un número entero entre {min} y {max}.",
"modelStep": "Paso del modelo · {model}",
diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.json
index e798c592a..857e14126 100644
--- a/packages/vue/src/i18n/locales/fr/ai.json
+++ b/packages/vue/src/i18n/locales/fr/ai.json
@@ -166,6 +166,8 @@
"stopFollowingAgents": "Ne plus suivre les agents pendant qu’ils travaillent",
"allChats": "Toutes les discussions",
"renameChat": "Renommer",
+ "saveChatTrace": "Enregistrer la trace…",
+ "chatTraceFailed": "Impossible d’enregistrer la trace de la conversation.",
"deleteChat": "Supprimer",
"chatTitle": "Titre de la discussion",
"saveChatTitle": "Enregistrer",
diff --git a/packages/vue/src/i18n/locales/fr/diagnostics.json b/packages/vue/src/i18n/locales/fr/diagnostics.json
index df38ae78b..1373e1d97 100644
--- a/packages/vue/src/i18n/locales/fr/diagnostics.json
+++ b/packages/vue/src/i18n/locales/fr/diagnostics.json
@@ -25,10 +25,12 @@
"description": "Stockez localement les événements techniques pour faciliter le dépannage d’OpenPencil. Les prompts, contenus de conception, identifiants et clés API sont exclus.",
"eventCount": "{count} événements · {size} Ko",
"copy": "Copier les diagnostics",
+ "save": "Enregistrer les diagnostics…",
"clear": "Effacer",
"clearDescription": "Cette action supprime de cet appareil les événements de diagnostic stockés localement.",
"cleared": "Diagnostics effacés.",
"copyFailed": "Impossible de copier les diagnostics dans le presse-papiers.",
+ "saveFailed": "Impossible d’enregistrer les diagnostics.",
"retentionCustom": "Personnalisé…",
"retentionRange": "Saisissez un nombre entier entre {min} et {max}.",
"modelStep": "Étape du modèle · {model}",
diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.json
index 9a3ff74c7..e2999a05c 100644
--- a/packages/vue/src/i18n/locales/it/ai.json
+++ b/packages/vue/src/i18n/locales/it/ai.json
@@ -166,6 +166,8 @@
"stopFollowingAgents": "Smetti di seguire gli agenti mentre lavorano",
"allChats": "Tutte le chat",
"renameChat": "Rinomina",
+ "saveChatTrace": "Salva traccia…",
+ "chatTraceFailed": "Impossibile salvare la traccia della chat.",
"deleteChat": "Elimina",
"chatTitle": "Titolo della chat",
"saveChatTitle": "Salva",
diff --git a/packages/vue/src/i18n/locales/it/diagnostics.json b/packages/vue/src/i18n/locales/it/diagnostics.json
index 972d0ab81..a7bc40a2e 100644
--- a/packages/vue/src/i18n/locales/it/diagnostics.json
+++ b/packages/vue/src/i18n/locales/it/diagnostics.json
@@ -25,10 +25,12 @@
"description": "Conserva localmente gli eventi tecnici per aiutare a risolvere i problemi di OpenPencil. Prompt, contenuti di design, credenziali e chiavi API sono esclusi.",
"eventCount": "{count} eventi · {size} KB",
"copy": "Copia diagnostica",
+ "save": "Salva diagnostica…",
"clear": "Cancella",
"clearDescription": "Questa operazione rimuove da questo dispositivo gli eventi diagnostici archiviati localmente.",
"cleared": "Diagnostica cancellata.",
"copyFailed": "Impossibile copiare la diagnostica negli appunti.",
+ "saveFailed": "Impossibile salvare la diagnostica.",
"retentionCustom": "Personalizzato…",
"retentionRange": "Inserisci un numero intero da {min} a {max}.",
"modelStep": "Passaggio del modello · {model}",
diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.json
index 27e543eda..2f5b16392 100644
--- a/packages/vue/src/i18n/locales/ja/ai.json
+++ b/packages/vue/src/i18n/locales/ja/ai.json
@@ -166,6 +166,8 @@
"stopFollowingAgents": "作業中のエージェントの追従を停止",
"allChats": "すべてのチャット",
"renameChat": "名前を変更",
+ "saveChatTrace": "トレースを保存…",
+ "chatTraceFailed": "チャットのトレースを保存できませんでした。",
"deleteChat": "削除",
"chatTitle": "チャットのタイトル",
"saveChatTitle": "保存",
diff --git a/packages/vue/src/i18n/locales/ja/diagnostics.json b/packages/vue/src/i18n/locales/ja/diagnostics.json
index be8d7fdc3..ad0342a99 100644
--- a/packages/vue/src/i18n/locales/ja/diagnostics.json
+++ b/packages/vue/src/i18n/locales/ja/diagnostics.json
@@ -25,10 +25,12 @@
"description": "OpenPencilのトラブルシューティングに役立つ技術イベントを端末に保存します。プロンプト、デザイン内容、認証情報、APIキーは除外されます。",
"eventCount": "{count} 件 · {size} KB",
"copy": "診断データをコピー",
+ "save": "診断データを保存…",
"clear": "消去",
"clearDescription": "このデバイスに保存されている診断イベントを削除します。",
"cleared": "診断データを消去しました。",
"copyFailed": "診断データをクリップボードにコピーできませんでした。",
+ "saveFailed": "診断データを保存できませんでした。",
"retentionCustom": "カスタム…",
"retentionRange": "{min} から {max} までの整数を入力してください。",
"modelStep": "モデルのステップ · {model}",
diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.json
index ac45cfa18..8328210f5 100644
--- a/packages/vue/src/i18n/locales/pl/ai.json
+++ b/packages/vue/src/i18n/locales/pl/ai.json
@@ -166,6 +166,8 @@
"stopFollowingAgents": "Przestań śledzić agentów podczas pracy",
"allChats": "Wszystkie czaty",
"renameChat": "Zmień nazwę",
+ "saveChatTrace": "Zapisz ślad…",
+ "chatTraceFailed": "Nie można zapisać śladu czatu.",
"deleteChat": "Usuń",
"chatTitle": "Tytuł czatu",
"saveChatTitle": "Zapisz",
diff --git a/packages/vue/src/i18n/locales/pl/diagnostics.json b/packages/vue/src/i18n/locales/pl/diagnostics.json
index 7f735df24..bd20c6422 100644
--- a/packages/vue/src/i18n/locales/pl/diagnostics.json
+++ b/packages/vue/src/i18n/locales/pl/diagnostics.json
@@ -25,10 +25,12 @@
"description": "Zapisuj lokalnie zdarzenia techniczne, aby ułatwić rozwiązywanie problemów z OpenPencil. Prompty, zawartość projektu, dane logowania i klucze API są wykluczone.",
"eventCount": "{count} zdarzeń · {size} KB",
"copy": "Kopiuj diagnostykę",
+ "save": "Zapisz diagnostykę…",
"clear": "Wyczyść",
"clearDescription": "Spowoduje to usunięcie lokalnie zapisanych zdarzeń diagnostycznych z tego urządzenia.",
"cleared": "Wyczyszczono dane diagnostyczne.",
"copyFailed": "Nie można skopiować danych diagnostycznych do schowka.",
+ "saveFailed": "Nie można zapisać danych diagnostycznych.",
"retentionCustom": "Własna wartość…",
"retentionRange": "Wpisz liczbę całkowitą od {min} do {max}.",
"modelStep": "Krok modelu · {model}",
diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.json
index c52a557cc..9739738ef 100644
--- a/packages/vue/src/i18n/locales/ru/ai.json
+++ b/packages/vue/src/i18n/locales/ru/ai.json
@@ -166,6 +166,8 @@
"stopFollowingAgents": "Не следовать за агентами во время работы",
"allChats": "Все чаты",
"renameChat": "Переименовать",
+ "saveChatTrace": "Сохранить трассировку…",
+ "chatTraceFailed": "Не удалось сохранить трассировку чата.",
"deleteChat": "Удалить",
"chatTitle": "Название чата",
"saveChatTitle": "Сохранить",
diff --git a/packages/vue/src/i18n/locales/ru/diagnostics.json b/packages/vue/src/i18n/locales/ru/diagnostics.json
index 0324f02f2..b4c7894e2 100644
--- a/packages/vue/src/i18n/locales/ru/diagnostics.json
+++ b/packages/vue/src/i18n/locales/ru/diagnostics.json
@@ -25,10 +25,12 @@
"description": "Сохраняйте технические события локально для диагностики OpenPencil. Промпты, содержимое дизайна, учётные данные и API-ключи не сохраняются.",
"eventCount": "События: {count} · {size} КБ",
"copy": "Скопировать диагностику",
+ "save": "Сохранить диагностику…",
"clear": "Очистить",
"clearDescription": "Локально сохранённые диагностические события будут удалены с этого устройства.",
"cleared": "Диагностические данные очищены.",
"copyFailed": "Не удалось скопировать диагностические данные в буфер обмена.",
+ "saveFailed": "Не удалось сохранить диагностические данные.",
"retentionCustom": "Своё значение…",
"retentionRange": "Введите целое число от {min} до {max}.",
"modelStep": "Шаг модели · {model}",
diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.json
index e22afaede..8d17abfa8 100644
--- a/packages/vue/src/i18n/locales/zh-cn/ai.json
+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json
@@ -166,6 +166,8 @@
"stopFollowingAgents": "停止在工作时跟随智能体",
"allChats": "所有聊天",
"renameChat": "重命名",
+ "saveChatTrace": "保存追踪记录…",
+ "chatTraceFailed": "无法保存聊天追踪记录。",
"deleteChat": "删除",
"chatTitle": "聊天标题",
"saveChatTitle": "保存",
diff --git a/packages/vue/src/i18n/locales/zh-cn/diagnostics.json b/packages/vue/src/i18n/locales/zh-cn/diagnostics.json
index ca43d66a0..2b7d5ba7b 100644
--- a/packages/vue/src/i18n/locales/zh-cn/diagnostics.json
+++ b/packages/vue/src/i18n/locales/zh-cn/diagnostics.json
@@ -25,10 +25,12 @@
"description": "在本地保存技术事件,帮助排查 OpenPencil 问题。不保存提示词、设计内容、凭据和 API 密钥。",
"eventCount": "{count} 个事件 · {size} KB",
"copy": "复制诊断数据",
+ "save": "保存诊断数据…",
"clear": "清除",
"clearDescription": "这会从此设备中删除本地保存的诊断事件。",
"cleared": "诊断数据已清除。",
"copyFailed": "无法将诊断数据复制到剪贴板。",
+ "saveFailed": "无法保存诊断数据。",
"retentionCustom": "自定义…",
"retentionRange": "请输入 {min} 到 {max} 之间的整数。",
"modelStep": "模型步骤 · {model}",
diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.ts
index d8696019c..da03334c0 100644
--- a/packages/vue/src/i18n/messages/ai.ts
+++ b/packages/vue/src/i18n/messages/ai.ts
@@ -27,6 +27,8 @@ export const aiMessageDefaults = {
stopFollowingAgents: 'Stop following agents as they work',
allChats: 'All chats',
renameChat: 'Rename',
+ saveChatTrace: 'Save trace…',
+ chatTraceFailed: 'The chat trace could not be saved.',
deleteChat: 'Delete',
chatTitle: 'Conversation title',
saveChatTitle: 'Save',
diff --git a/packages/vue/src/i18n/messages/diagnostics.ts b/packages/vue/src/i18n/messages/diagnostics.ts
index 046aa4a17..bbc86e7f5 100644
--- a/packages/vue/src/i18n/messages/diagnostics.ts
+++ b/packages/vue/src/i18n/messages/diagnostics.ts
@@ -66,10 +66,12 @@ export const diagnosticsMessageDefaults = {
usageHistoryDescription: 'Keep local AI usage summaries.',
eventCount: params('{count} events · {size} KB'),
copy: 'Copy diagnostics',
+ save: 'Save diagnostics…',
clear: 'Clear',
clearDescription: 'This removes locally stored diagnostic events from this device.',
cleared: 'Diagnostics cleared.',
copyFailed: 'Could not copy diagnostics to the clipboard.',
+ saveFailed: 'Could not save diagnostics.',
sharingTitle: 'Sharing with OpenPencil',
sharingDescription:
'What this app sends to the OpenPencil team. Your designs, file names, prompts, and keys are never sent.',
diff --git a/src/app/ai/chat/history/continuation.ts b/src/app/ai/chat/history/continuation.ts
index 315208402..5578f4419 100644
--- a/src/app/ai/chat/history/continuation.ts
+++ b/src/app/ai/chat/history/continuation.ts
@@ -1,24 +1,26 @@
import type { ChatTransport, UIMessage } from 'ai'
+/** The history a new request sends: partial tool activity stays in history, unpaired calls do not. */
+export function requestMessages(messages: UIMessage[]): UIMessage[] {
+ return messages
+ .map((message) => ({
+ ...message,
+ parts: message.parts.filter(
+ (part) =>
+ !('toolCallId' in part) ||
+ part.state === 'output-available' ||
+ part.state === 'output-error' ||
+ part.state === 'output-denied'
+ )
+ }))
+ .filter((message) => message.parts.length > 0)
+}
+
/** Preserve partial tool activity in history but omit unpaired calls from new requests. */
export function resumableTransport(transport: ChatTransport<UIMessage>): ChatTransport<UIMessage> {
return {
reconnectToStream: (options) => transport.reconnectToStream(options),
sendMessages: (options) =>
- transport.sendMessages({
- ...options,
- messages: options.messages
- .map((message) => ({
- ...message,
- parts: message.parts.filter(
- (part) =>
- !('toolCallId' in part) ||
- part.state === 'output-available' ||
- part.state === 'output-error' ||
- part.state === 'output-denied'
- )
- }))
- .filter((message) => message.parts.length > 0)
- })
+ transport.sendMessages({ ...options, messages: requestMessages(options.messages) })
}
}
diff --git a/src/app/ai/chat/history/idb.ts b/src/app/ai/chat/history/idb.ts
index e99c426cb..130e8dfd7 100644
--- a/src/app/ai/chat/history/idb.ts
+++ b/src/app/ai/chat/history/idb.ts
@@ -1,5 +1,6 @@
import type { DBSchema } from 'idb'
+import type { RunTrace, TraceAsset, TraceStore } from '@/app/ai/chat/trace/types'
import { APP_DATABASE_NAMES, defineAppDatabase, connectAppDatabase } from '@/app/storage/idb'
import { fromStorableBlobs, toStorableBlobs } from './blobs'
@@ -12,11 +13,15 @@ interface ChatDatabase extends DBSchema {
files: { key: string; value: FileSystemFileHandle }
deleted: { key: string; value: true }
selected: { key: string; value: string }
+ /** Each run a conversation sent, removed with the conversation (`@/app/ai/chat/trace`). */
+ runs: { key: [string, string]; value: RunTrace; indexes: { conversation: string } }
+ /** Instructions and tool sets runs share, under their fingerprints. */
+ traceAssets: { key: string; value: TraceAsset }
}
const definition = defineAppDatabase<ChatDatabase>({
name: APP_DATABASE_NAMES.chats,
- version: 3,
+ version: 4,
callbacks: {
upgrade(database, oldVersion) {
if (oldVersion < 1) {
@@ -28,6 +33,12 @@ const definition = defineAppDatabase<ChatDatabase>({
}
if (oldVersion < 2) database.createObjectStore('deleted')
if (oldVersion < 3) database.createObjectStore('files')
+ if (oldVersion < 4) {
+ database
+ .createObjectStore('runs', { keyPath: ['conversationId', 'runId'] })
+ .createIndex('conversation', 'conversationId')
+ database.createObjectStore('traceAssets')
+ }
}
}
})
@@ -91,12 +102,17 @@ export function createConversationStore(): ConversationStore {
},
async remove(id) {
const transaction = (await getDatabase()).transaction(
- ['conversations', 'messages', 'selected', 'deleted'],
+ ['conversations', 'messages', 'selected', 'deleted', 'runs'],
'readwrite'
)
await transaction.objectStore('deleted').put(true, id)
await transaction.objectStore('conversations').delete(id)
await transaction.objectStore('messages').delete(id)
+ let run = await transaction.objectStore('runs').index('conversation').openCursor(id)
+ while (run) {
+ await run.delete()
+ run = await run.continue()
+ }
let cursor = await transaction.objectStore('selected').openCursor()
while (cursor) {
if (cursor.value === id) await cursor.delete()
@@ -159,3 +175,31 @@ export function createConversationStore(): ConversationStore {
}
}
}
+
+/** Run traces live in the chat database, beside the conversations they belong to. */
+export function createTraceStore(): TraceStore {
+ const database = connectAppDatabase(definition)
+ const getDatabase = () => database.open()
+ return {
+ async putRun(run) {
+ const transaction = (await getDatabase()).transaction(['deleted', 'runs'], 'readwrite')
+ // A run still streaming when its conversation is deleted must not outlive it.
+ if (!(await transaction.objectStore('deleted').get(run.conversationId))) {
+ await transaction.objectStore('runs').put(run)
+ }
+ await transaction.done
+ },
+ async listRuns(conversationId) {
+ const runs = await (
+ await getDatabase()
+ ).getAllFromIndex('runs', 'conversation', conversationId)
+ return runs.toSorted((left, right) => left.startedAt.localeCompare(right.startedAt))
+ },
+ async putAsset(hash, asset) {
+ await (await getDatabase()).put('traceAssets', asset, hash)
+ },
+ async getAsset(hash) {
+ return (await getDatabase()).get('traceAssets', hash)
+ }
+ }
+}
diff --git a/src/app/ai/chat/trace/export.ts b/src/app/ai/chat/trace/export.ts
new file mode 100644
index 000000000..7dfbe1345
--- /dev/null
+++ b/src/app/ai/chat/trace/export.ts
@@ -0,0 +1,65 @@
+import type { UIMessage } from 'ai'
+import { omit } from 'es-toolkit/object'
+
+import { createTraceStore } from '@/app/ai/chat/history/idb'
+import { snapshotMessages } from '@/app/ai/chat/history/messages'
+import type { Conversation } from '@/app/ai/chat/history/types'
+import { diagnostics } from '@/app/diagnostics'
+import { diagnosticsEnvironment } from '@/app/diagnostics/environment'
+import { getExportBytes, saveExportedFile } from '@/app/document/export/files'
+import { downloadBlob } from '@/app/document/io/browser'
+
+import type { TraceAsset, TraceStore } from './types'
+
+export const CHAT_TRACE_FORMAT = 'openpencil-chat-trace'
+export const CHAT_TRACE_VERSION = 2
+
+/**
+ * A conversation as it ran, to reproduce what the agent did: every message part (text,
+ * reasoning, tool calls with their inputs and outputs), each run's steps with their model,
+ * settings, usage, and errors, the instructions and tools they were given, and the
+ * conversation's diagnostic events. A step's request is rebuilt from `messages` and checked
+ * against its fingerprint by `./rebuild`.
+ */
+export async function chatTrace(
+ conversation: Conversation,
+ messages: UIMessage[],
+ store: TraceStore = createTraceStore()
+) {
+ const runs = await store.listRuns(conversation.id)
+ const hashes = new Set(
+ runs.flatMap((run) => (run.tools ? [run.instructions, run.tools] : [run.instructions]))
+ )
+ const assets: Record<string, TraceAsset> = {}
+ for (const hash of hashes) {
+ const asset = await store.getAsset(hash)
+ if (asset) assets[hash] = asset
+ }
+ const events = (await diagnostics.list()).filter((event) => event.sessionId === conversation.id)
+ return JSON.stringify(
+ {
+ format: CHAT_TRACE_FORMAT,
+ version: CHAT_TRACE_VERSION,
+ environment: diagnosticsEnvironment(),
+ conversation: omit(conversation, ['messages']),
+ messages: snapshotMessages(messages),
+ runs,
+ assets,
+ events: events.toReversed()
+ },
+ null,
+ 2
+ )
+}
+
+/** Saves a conversation's trace where the person chooses; `false` means they cancelled. */
+export async function saveChatTrace(conversation: Conversation, messages: UIMessage[]) {
+ return saveExportedFile(
+ getExportBytes(await chatTrace(conversation, messages)),
+ `${conversation.title || 'Chat'} trace.json`,
+ 'JSON',
+ '.json',
+ 'application/json',
+ downloadBlob
+ )
+}
diff --git a/src/app/ai/chat/trace/fingerprint.ts b/src/app/ai/chat/trace/fingerprint.ts
new file mode 100644
index 000000000..0a259d2df
--- /dev/null
+++ b/src/app/ai/chat/trace/fingerprint.ts
@@ -0,0 +1,20 @@
+import { isPlainObject } from 'es-toolkit/predicate'
+import { fromUint8Array } from 'js-base64'
+
+/** Objects with their keys in code-point order, so key order never changes a fingerprint. */
+function sortedKeys(_key: string, value: unknown): unknown {
+ if (value instanceof Uint8Array) return { bytes: fromUint8Array(value) }
+ if (!isPlainObject(value)) return value
+ return Object.fromEntries(
+ Object.keys(value)
+ .toSorted()
+ .map((key) => [key, value[key]])
+ )
+}
+
+/** `sha256:<hex>` of a value's JSON, which already leaves absent fields out and URLs as text. */
+export async function fingerprint(value: unknown): Promise<string> {
+ const bytes = new TextEncoder().encode(JSON.stringify(value, sortedKeys))
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))
+ return `sha256:${Array.from(digest, (byte) => byte.toString(16).padStart(2, '0')).join('')}`
+}
diff --git a/src/app/ai/chat/trace/rebuild.ts b/src/app/ai/chat/trace/rebuild.ts
new file mode 100644
index 000000000..067f49642
--- /dev/null
+++ b/src/app/ai/chat/trace/rebuild.ts
@@ -0,0 +1,45 @@
+import { convertToModelMessages } from 'ai'
+import type { ModelMessage, ToolSet, UIMessage } from 'ai'
+
+import { requestMessages } from '@/app/ai/chat/history/continuation'
+
+import { fingerprint } from './fingerprint'
+import type { RunTrace } from './types'
+
+/** The reply's parts before its `step`th step, each of which starts with a `step-start` part. */
+function stepsBefore(reply: UIMessage, step: number): UIMessage | null {
+ let seen = 0
+ const end = reply.parts.findIndex((part) => part.type === 'step-start' && seen++ === step)
+ const parts = end === -1 ? reply.parts : reply.parts.slice(0, end)
+ return parts.length > 0 ? { ...reply, parts } : null
+}
+
+/**
+ * The messages a run's `step` sent to the model, rebuilt from the conversation: what the run
+ * sent, as `requestMessages` prepared it, then the reply's earlier steps.
+ */
+export async function rebuildStepMessages(
+ conversation: UIMessage[],
+ run: Pick<RunTrace, 'input'>,
+ step: number,
+ tools: ToolSet
+): Promise<ModelMessage[]> {
+ const through = conversation.findIndex((message) => message.id === run.input.through)
+ const sent = requestMessages(conversation.slice(0, through + 1))
+ const reply = conversation.at(through + 1)
+ const earlier = reply?.role === 'assistant' && step > 0 ? stepsBefore(reply, step) : null
+ return convertToModelMessages(earlier ? [...sent, earlier] : sent, { tools })
+}
+
+/** Whether the rebuilt request of a run's step is the one the model received. */
+export async function matchesRecordedStep(
+ conversation: UIMessage[],
+ run: RunTrace,
+ step: number,
+ tools: ToolSet
+): Promise<boolean> {
+ const recorded = run.steps.find((entry) => entry.index === step)
+ if (!recorded) return false
+ const rebuilt = await rebuildStepMessages(conversation, run, step, tools)
+ return (await fingerprint(rebuilt)) === recorded.request.hash
+}
diff --git a/src/app/ai/chat/trace/recorder.ts b/src/app/ai/chat/trace/recorder.ts
new file mode 100644
index 000000000..ca7df39c2
--- /dev/null
+++ b/src/app/ai/chat/trace/recorder.ts
@@ -0,0 +1,162 @@
+import { APICallError, asSchema } from 'ai'
+import type { StepResult, ToolSet, UIMessage } from 'ai'
+
+import { scrubDiagnosticText } from '@/app/diagnostics/scrub'
+
+import { fingerprint } from './fingerprint'
+import type { RunTrace, StepTrace, TraceAsset, TraceError, TraceStore } from './types'
+
+const MAX_RESPONSE_BODY = 4000
+
+type RunStart = Pick<RunTrace, 'conversationId' | 'runId' | 'model' | 'settings'> & {
+ instructions: string
+ /** The messages sent, after unfinished tool calls were left out. */
+ messages: UIMessage[]
+}
+
+export interface RunRecording {
+ /** The tools offered to this run. */
+ offer(tools: ToolSet): void
+ step(step: StepResult<ToolSet>): void
+ fail(error: unknown): void
+ end(outcome: 'completed' | 'stopped'): void
+}
+
+/**
+ * A provider's error text can echo a key or an account, and traces leave the device in bug
+ * reports, so it is scrubbed as diagnostics are.
+ */
+function traceError(error: unknown): TraceError {
+ const name = error instanceof Error ? error.name : 'Error'
+ const message = scrubDiagnosticText(error instanceof Error ? error.message : String(error))
+ if (!APICallError.isInstance(error)) return { name, message }
+ return {
+ name,
+ message,
+ statusCode: error.statusCode,
+ responseBody:
+ error.responseBody === undefined
+ ? undefined
+ : scrubDiagnosticText(error.responseBody).slice(0, MAX_RESPONSE_BODY)
+ }
+}
+
+async function toolsAsset(tools: ToolSet): Promise<TraceAsset> {
+ const entries = Object.entries(tools).toSorted(([left], [right]) => left.localeCompare(right))
+ return {
+ kind: 'tools',
+ tools: await Promise.all(
+ entries.map(async ([name, tool]) => ({
+ name,
+ // Our tools describe themselves in text; a description computed per call is not stored.
+ description: typeof tool.description === 'string' ? tool.description : undefined,
+ inputSchema: await asSchema(tool.inputSchema).jsonSchema
+ }))
+ )
+ }
+}
+
+/**
+ * Records each run of a conversation as references into its history, so a saved trace can
+ * rebuild every request the model received (`./rebuild`) without storing them again.
+ */
+export function createRunRecorder(store: TraceStore) {
+ const stored = new Set<string>()
+ // Writes land in order, and one failure does not stop the next.
+ let pending = Promise.resolve()
+
+ function write(operation: () => Promise<void>): void {
+ pending = pending.then(operation).catch((error: unknown) => {
+ console.warn('[Chat trace] Failed to record a run step', error)
+ })
+ }
+
+ async function storeAsset(asset: TraceAsset): Promise<string> {
+ const hash = await fingerprint(asset)
+ if (!stored.has(hash)) {
+ await store.putAsset(hash, asset)
+ stored.add(hash)
+ }
+ return hash
+ }
+
+ function start({ instructions, messages, ...run }: RunStart): RunRecording {
+ const trace: RunTrace = {
+ ...run,
+ startedAt: new Date().toISOString(),
+ instructions: '',
+ input: { through: messages.at(-1)?.id ?? null, messages: messages.length },
+ steps: [],
+ outcome: 'running'
+ }
+ let lastMark = performance.now()
+ const save = () => store.putRun(structuredClone(trace))
+ write(async () => {
+ trace.instructions = await storeAsset({ kind: 'instructions', text: instructions })
+ await save()
+ })
+
+ function finish(outcome: RunTrace['outcome'], error?: TraceError): void {
+ write(async () => {
+ if (trace.outcome !== 'running') return
+ trace.outcome = outcome
+ trace.endedAt = new Date().toISOString()
+ if (error) trace.error = error
+ await save()
+ })
+ }
+
+ return {
+ offer(tools) {
+ write(async () => {
+ trace.tools = await storeAsset(await toolsAsset(tools))
+ await save()
+ })
+ },
+ step(step) {
+ const now = performance.now()
+ const durationMs = Math.round(now - lastMark)
+ lastMark = now
+ const messages = step.request.messages ?? []
+ write(async () => {
+ const recorded: StepTrace = {
+ index: step.stepNumber,
+ finishedAt: new Date().toISOString(),
+ durationMs,
+ request: { hash: await fingerprint(messages), messages: messages.length },
+ response: {
+ id: step.response.id,
+ modelId: step.response.modelId,
+ finishReason: step.finishReason,
+ rawFinishReason: step.rawFinishReason
+ },
+ usage: {
+ inputTokens: step.usage.inputTokens ?? null,
+ outputTokens: step.usage.outputTokens ?? null,
+ reasoningTokens: step.usage.outputTokenDetails.reasoningTokens ?? null,
+ cacheReadTokens: step.usage.inputTokenDetails.cacheReadTokens ?? null,
+ cacheWriteTokens: step.usage.inputTokenDetails.cacheWriteTokens ?? null
+ },
+ warnings: step.warnings ?? []
+ }
+ trace.steps.push(recorded)
+ await save()
+ })
+ },
+ fail(error) {
+ finish('failed', traceError(error))
+ },
+ end(outcome) {
+ finish(outcome)
+ }
+ }
+ }
+
+ return {
+ start,
+ /** Resolves once every recorded write has landed. */
+ flush: () => pending
+ }
+}
+
+export type RunRecorder = ReturnType<typeof createRunRecorder>
diff --git a/src/app/ai/chat/trace/types.ts b/src/app/ai/chat/trace/types.ts
new file mode 100644
index 000000000..62ae8a27d
--- /dev/null
+++ b/src/app/ai/chat/trace/types.ts
@@ -0,0 +1,73 @@
+import type { CallWarning, FinishReason } from 'ai'
+
+import type { ThinkingLevel } from '@/app/ai/models/types'
+
+/** A tool as the model was offered it. */
+export interface TraceTool {
+ name: string
+ description?: string
+ inputSchema: unknown
+}
+
+/** Text or definitions every step of many runs shares, stored once under its fingerprint. */
+export type TraceAsset =
+ | { kind: 'instructions'; text: string }
+ | { kind: 'tools'; tools: TraceTool[] }
+
+/**
+ * One model call of a run. Its request is not stored: it is the conversation through the run's
+ * input plus the reply's earlier steps, and `request.hash` proves a rebuild matches it.
+ */
+export interface StepTrace {
+ index: number
+ finishedAt: string
+ durationMs: number
+ request: { hash: string; messages: number }
+ response: {
+ id: string
+ modelId: string
+ finishReason: FinishReason
+ rawFinishReason?: string
+ }
+ usage: {
+ inputTokens: number | null
+ outputTokens: number | null
+ reasoningTokens: number | null
+ cacheReadTokens: number | null
+ cacheWriteTokens: number | null
+ }
+ warnings: CallWarning[]
+}
+
+export interface TraceError {
+ name: string
+ message: string
+ statusCode?: number
+ responseBody?: string
+}
+
+/** One message sent to the model and every step it took to answer. */
+export interface RunTrace {
+ conversationId: string
+ runId: string
+ startedAt: string
+ endedAt?: string
+ model: { provider: string; id: string }
+ settings: { maxOutputTokens: number; maxSteps: number; thinking: ThinkingLevel; cache: boolean }
+ /** Fingerprints of the shared `TraceAsset`s the run used. */
+ instructions: string
+ tools?: string
+ /** The last conversation message sent; the request is everything through it. */
+ input: { through: string | null; messages: number }
+ steps: StepTrace[]
+ outcome: 'running' | 'completed' | 'stopped' | 'failed'
+ /** Why the run failed; the step that failed is `steps.length`. */
+ error?: TraceError
+}
+
+export interface TraceStore {
+ putRun(run: RunTrace): Promise<void>
+ listRuns(conversationId: string): Promise<RunTrace[]>
+ putAsset(hash: string, asset: TraceAsset): Promise<void>
+ getAsset(hash: string): Promise<TraceAsset | undefined>
+}
diff --git a/src/app/ai/chat/transports.ts b/src/app/ai/chat/transports.ts
index 0feb34f80..861cb2a4d 100644
--- a/src/app/ai/chat/transports.ts
+++ b/src/app/ai/chat/transports.ts
@@ -39,9 +39,12 @@ import type { getActiveEditorStore } from '@/app/editor/active-store'
import { trackUsage } from '@/app/telemetry'
import { resumableTransport } from './history/continuation'
+import { createTraceStore } from './history/idb'
import { updateMessage } from './metadata'
import { maxAgentSteps } from './preferences'
import { settleMessage } from './settle'
+import { createRunRecorder } from './trace/recorder'
+import type { RunRecorder, RunRecording } from './trace/recorder'
type EditorStore = ReturnType<typeof getActiveEditorStore>
@@ -64,6 +67,8 @@ export type ToolLoopTransportOptions = {
thinkingLevel: () => ThinkingLevel
onError?: (error: unknown) => void
diagnosticContext?: AIDiagnosticContext
+ /** Records each run so a saved trace can rebuild its requests. */
+ recorder?: RunRecorder
}
const ANTHROPIC_CACHE_CONTROL = {
@@ -113,7 +118,8 @@ export function createToolLoopTransport({
maxOutputTokens,
thinkingLevel,
onError,
- diagnosticContext = {}
+ diagnosticContext = {},
+ recorder
}: ToolLoopTransportOptions) {
const tools = createAITools(store, diagnosticContext)
// The reply in progress; a transport sends one message at a time.
@@ -130,21 +136,28 @@ export function createToolLoopTransport({
const cacheProviderOptions = supportsAnthropicCaching(providerID, effectiveModelID)
? ANTHROPIC_CACHE_CONTROL
: undefined
+ let recording: RunRecording | undefined
const agent = new ToolLoopAgent({
model,
instructions: SYSTEM_PROMPT,
tools,
maxOutputTokens,
+ // Kept only to fingerprint each step's request for its trace.
+ include: { requestMessages: recorder !== undefined },
prepareCall: (options) => {
const enabledNames = new Set(
enabledAIToolDefinitions(aiToolOverrides.value).map((tool) => tool.name)
)
preview.clear()
+ // Keep the full catalog for validating history; offer only enabled tools to this request.
+ const offered = Object.fromEntries(
+ Object.entries(tools).filter(([name]) => enabledNames.has(name))
+ )
+ recording?.offer(offered)
return {
...options,
stopWhen: stepCountIs(currentRun(store).maxSteps),
- // Keep the full catalog for validating history; offer only enabled tools to this request.
- tools: Object.fromEntries(Object.entries(tools).filter(([name]) => enabledNames.has(name))),
+ tools: offered,
maxOutputTokens,
...callSettings(providerID, cacheProviderOptions, thinkingLevel())
}
@@ -152,10 +165,13 @@ export function createToolLoopTransport({
onFinish: () => {
preview.clear()
endRun(store, run)
+ recording?.end('completed')
},
- onStepFinish: ({ usage }) => {
+ onStepFinish: (step) => {
+ const { usage } = step
preview.clear()
recordStep(store)
+ recording?.step(step)
recordModelStepCompleted(
{
provider: providerID,
@@ -173,6 +189,7 @@ export function createToolLoopTransport({
function handleError(error: unknown): string {
preview.clear()
endRun(store, run)
+ recording?.fail(error)
onError?.(error)
return 'The provider rejected the request.'
}
@@ -186,10 +203,32 @@ export function createToolLoopTransport({
// The run starts as the message is sent, so a Stop before the model is reached ends it.
const started = startRun(store, maxAgentSteps.value, effectiveModelID)
run = started
+ const { sessionId, runId } = diagnosticContext
+ const startedRecording =
+ sessionId && runId
+ ? recorder?.start({
+ conversationId: sessionId,
+ runId,
+ model: { provider: providerID, id: effectiveModelID },
+ settings: {
+ maxOutputTokens,
+ maxSteps: started.maxSteps,
+ thinking: thinkingLevel(),
+ cache: cacheProviderOptions !== undefined
+ },
+ instructions: SYSTEM_PROMPT,
+ messages: options.messages
+ })
+ : undefined
+ recording = startedRecording
// Stopping a reply ends the run without onFinish.
+ const stop = () => {
+ endRun(store, started)
+ startedRecording?.end('stopped')
+ }
const { abortSignal } = options
- if (abortSignal?.aborted) endRun(store, started)
- else if (abortSignal) useEventListener(abortSignal, 'abort', () => endRun(store, started))
+ if (abortSignal?.aborted) stop()
+ else if (abortSignal) useEventListener(abortSignal, 'abort', stop)
// DirectChatTransport handles error chunks, but not a rejected underlying stream.
return createUIMessageStream<UIMessage>({
execute: async ({ writer }) => {
@@ -235,6 +274,7 @@ export function createChatSessionManager({
let harnessTransportInstance: { stop(): Promise<void> } | null = null
let overrideTransport: (() => ChatTransport<UIMessage>) | null = null
let activeProviderError: unknown = null
+ const runRecorder = createRunRecorder(createTraceStore())
function captureProviderError(error: unknown): void {
activeProviderError ??= error
@@ -354,7 +394,8 @@ export function createChatSessionManager({
maxOutputTokens: runtime.role.profile.maxOutputTokens,
thinkingLevel: () => chatThinkingLevel.value,
onError: captureProviderError,
- diagnosticContext
+ diagnosticContext,
+ recorder: runRecorder
})
}
diff --git a/src/app/diagnostics/save.ts b/src/app/diagnostics/save.ts
new file mode 100644
index 000000000..9a0a02769
--- /dev/null
+++ b/src/app/diagnostics/save.ts
@@ -0,0 +1,17 @@
+import { getExportBytes, saveExportedFile } from '@/app/document/export/files'
+import { downloadBlob } from '@/app/document/io/browser'
+
+import { diagnosticsEnvironment } from './environment'
+import { diagnostics } from './recorder'
+
+/** Saves the diagnostics report Copy diagnostics copies; `false` means the person cancelled. */
+export async function saveDiagnosticsReport(): Promise<boolean> {
+ return saveExportedFile(
+ getExportBytes(await diagnostics.export(diagnosticsEnvironment())),
+ 'OpenPencil diagnostics.json',
+ 'JSON',
+ '.json',
+ 'application/json',
+ downloadBlob
+ )
+}
diff --git a/src/components/ChatPanel.vue b/src/components/ChatPanel.vue
index de7a7b1da..f6dfdb261 100644
--- a/src/components/ChatPanel.vue
+++ b/src/components/ChatPanel.vue
@@ -10,6 +10,7 @@ import { chatDocumentId } from '@/app/ai/chat/history/document'
import { useChatRunLocation } from '@/app/ai/chat/run-location'
import type { ChatSubmission } from '@/app/ai/chat/submission/types'
import { useChatSubmission } from '@/app/ai/chat/submission/use'
+import { saveChatTrace } from '@/app/ai/chat/trace/export'
import { useAIChat } from '@/app/ai/chat/use'
import { openAISetup } from '@/app/ai/models/settings/onboarding/dialog'
import { didHitStepLimit } from '@/app/ai/tools'
@@ -113,6 +114,16 @@ async function renameConversation(id: string, title: string) {
}
}
+async function saveTrace(id: string) {
+ const conversation = history.current.value
+ if (conversation?.id !== id) return
+ try {
+ await saveChatTrace(conversation, messages.value)
+ } catch {
+ toast.error(ai.value.chatTraceFailed)
+ }
+}
+
const failureMessage = computed(() => {
switch (chatFailure.value?.reason) {
case 'authentication':
@@ -218,6 +229,7 @@ function handleStop() {
@create="historyAction(history.newChat)"
@select="historyAction(() => history.open($event))"
@rename="renameConversation"
+ @save-trace="saveTrace"
@delete="historyAction(() => history.remove($event))"
>
<template #actions><FollowAgentsToggle /></template>
diff --git a/src/components/chat/ChatHistory.vue b/src/components/chat/ChatHistory.vue
index acd79a207..d2ab8e49a 100644
--- a/src/components/chat/ChatHistory.vue
+++ b/src/components/chat/ChatHistory.vue
@@ -39,6 +39,7 @@ const emit = defineEmits<{
select: [id: string]
create: []
rename: [id: string, title: string]
+ saveTrace: [id: string]
delete: [id: string]
}>()
const { ai } = useI18n()
@@ -182,6 +183,9 @@ function closeMenu(event: Event) {
@close-auto-focus="closeMenu"
>
<DropdownMenuItem :class="item" @select="rename">{{ ai.renameChat }}</DropdownMenuItem>
+ <DropdownMenuItem :class="item" @select="selectedId && emit('saveTrace', selectedId)">{{
+ ai.saveChatTrace
+ }}</DropdownMenuItem>
<DropdownMenuItem :class="item" @select="confirmDelete">{{
ai.deleteChat
}}</DropdownMenuItem>
diff --git a/src/components/settings/diagnostics/DiagnosticsSettingsPanel.vue b/src/components/settings/diagnostics/DiagnosticsSettingsPanel.vue
index 9b3089879..3b6697799 100644
--- a/src/components/settings/diagnostics/DiagnosticsSettingsPanel.vue
+++ b/src/components/settings/diagnostics/DiagnosticsSettingsPanel.vue
@@ -6,6 +6,7 @@ import { useI18n } from '@open-pencil/vue'
import { diagnostics } from '@/app/diagnostics'
import { diagnosticsEnvironment } from '@/app/diagnostics/environment'
+import { saveDiagnosticsReport } from '@/app/diagnostics/save'
import {
DIAGNOSTICS_RETENTION_MAX,
DIAGNOSTICS_RETENTION_MIN,
@@ -63,6 +64,14 @@ async function exportDiagnostics() {
toast.error(diagnosticMessages.value.copyFailed)
}
}
+
+async function saveDiagnostics() {
+ try {
+ await saveDiagnosticsReport()
+ } catch {
+ toast.error(diagnosticMessages.value.saveFailed)
+ }
+}
</script>
<template>
@@ -124,6 +133,10 @@ async function exportDiagnostics() {
><icon-lucide-check v-if="copied" /><icon-lucide-copy v-else /></template
>{{ copied ? common.copied : diagnosticMessages.copy }}</AppButton
>
+ <AppButton size="xs" color="neutral" variant="ghost" @click="saveDiagnostics"
+ ><template #leading><icon-lucide-download /></template
+ >{{ diagnosticMessages.save }}</AppButton
+ >
<AppButton
size="xs"
color="error"
diff --git a/tests/app/ai/chat/trace/export.test.ts b/tests/app/ai/chat/trace/export.test.ts
new file mode 100644
index 000000000..178c99d9d
--- /dev/null
+++ b/tests/app/ai/chat/trace/export.test.ts
@@ -0,0 +1,119 @@
+import { beforeEach, expect, test } from 'bun:test'
+
+import type { UIMessage } from 'ai'
+import * as v from 'valibot'
+
+import type { Conversation } from '@/app/ai/chat/history/types'
+import { chatTrace } from '@/app/ai/chat/trace/export'
+import type { RunTrace } from '@/app/ai/chat/trace/types'
+import { diagnostics, recordChatCompleted, recordModelStepCompleted } from '@/app/diagnostics'
+
+import { memoryTraceStore } from '#tests/helpers/chat/trace-store'
+
+const TraceJSON = v.pipe(
+ v.string(),
+ v.parseJson(),
+ v.object({
+ environment: v.object({ app: v.string(), shell: v.string() }),
+ conversation: v.record(v.string(), v.unknown()),
+ messages: v.array(
+ v.object({ message: v.looseObject({ id: v.string(), parts: v.array(v.unknown()) }) })
+ ),
+ runs: v.array(v.looseObject({ runId: v.string(), instructions: v.string() })),
+ assets: v.record(v.string(), v.looseObject({ kind: v.string() })),
+ events: v.array(v.object({ name: v.string(), sessionId: v.optional(v.string()) }))
+ })
+)
+
+function recordedRun(conversationId: string, runId: string): RunTrace {
+ return {
+ conversationId,
+ runId,
+ startedAt: '2026-10-13T10:01:00.000Z',
+ model: { provider: 'openrouter', id: 'anthropic/claude-sonnet-4.6' },
+ settings: { maxOutputTokens: 16000, maxSteps: 25, thinking: 'default', cache: true },
+ instructions: `sha256:${runId}-instructions`,
+ input: { through: 'request', messages: 1 },
+ steps: [],
+ outcome: 'completed'
+ }
+}
+
+const conversation: Conversation = {
+ id: 'conversation-one',
+ documentId: 'document',
+ documentName: 'Untitled',
+ title: 'Queue screen',
+ titleSource: 'manual',
+ createdAt: '2026-10-13T10:00:00.000Z',
+ updatedAt: '2026-10-13T10:05:00.000Z',
+ profileId: null,
+ backend: 'direct',
+ interrupted: false,
+ messages: []
+}
+
+const messages: UIMessage[] = [
+ { id: 'request', role: 'user', parts: [{ type: 'text', text: 'Add a queue screen' }] },
+ {
+ id: 'reply',
+ role: 'assistant',
+ parts: [
+ { type: 'reasoning', text: 'Reading the player first.' },
+ {
+ type: 'tool-eval',
+ toolCallId: 'call-1',
+ state: 'output-available',
+ input: { code: 'figma.currentPage.children.length' },
+ output: { result: 3 }
+ },
+ { type: 'text', text: 'Added the queue screen.' }
+ ]
+ }
+]
+
+beforeEach(async () => {
+ await diagnostics.clear()
+})
+
+test('a trace keeps every message part and its conversation’s runs and events', async () => {
+ const run = { sessionId: conversation.id, runId: 'run-one' }
+ recordModelStepCompleted(
+ {
+ provider: 'openrouter',
+ model: 'anthropic/claude-sonnet-4.6',
+ inputTokens: 10,
+ outputTokens: 2,
+ cacheReadTokens: null,
+ cacheWriteTokens: null
+ },
+ run
+ )
+ recordChatCompleted({ finishReason: 'stop' }, run)
+ recordChatCompleted({ finishReason: 'stop' }, { sessionId: 'another', runId: 'run-two' })
+
+ const traces = memoryTraceStore()
+ const own = recordedRun(conversation.id, 'run-one')
+ await traces.store.putRun(own)
+ await traces.store.putAsset(own.instructions, { kind: 'instructions', text: 'Design well.' })
+ const other = recordedRun('another', 'run-two')
+ await traces.store.putRun(other)
+ await traces.store.putAsset(other.instructions, { kind: 'instructions', text: 'Other.' })
+
+ const trace = v.parse(TraceJSON, await chatTrace(conversation, messages, traces.store))
+
+ expect(trace.conversation).toMatchObject({ id: conversation.id, title: 'Queue screen' })
+ expect(trace.conversation).not.toHaveProperty('messages')
+ expect<unknown[]>(trace.messages.map((row) => row.message)).toEqual(messages)
+ // Both events can share a millisecond, so their order is not part of the contract.
+ expect(trace.events.map((event) => event.name).toSorted()).toEqual([
+ 'chat.completed',
+ 'model.step.completed'
+ ])
+ expect(trace.events.every((event) => event.sessionId === conversation.id)).toBe(true)
+ // Only this conversation's runs, and only the assets they use.
+ expect(trace.runs.map((entry) => entry.runId)).toEqual(['run-one'])
+ expect(trace.assets).toEqual({
+ [own.instructions]: { kind: 'instructions', text: 'Design well.' }
+ })
+})
diff --git a/tests/app/ai/chat/trace/rebuild.test.ts b/tests/app/ai/chat/trace/rebuild.test.ts
new file mode 100644
index 000000000..4b0383cd0
--- /dev/null
+++ b/tests/app/ai/chat/trace/rebuild.test.ts
@@ -0,0 +1,136 @@
+import 'fake-indexeddb/auto'
+import { afterEach, expect, spyOn, test } from 'bun:test'
+
+import { readUIMessageStream, simulateReadableStream } from 'ai'
+import type { UIMessage } from 'ai'
+import { MockLanguageModelV4 } from 'ai/test'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+
+import { matchesRecordedStep, rebuildStepMessages } from '@/app/ai/chat/trace/rebuild'
+import { createRunRecorder } from '@/app/ai/chat/trace/recorder'
+import { createToolLoopTransport } from '@/app/ai/chat/transports'
+import { createAITools } from '@/app/ai/tools'
+import { aiToolOverrides } from '@/app/ai/tools/preferences'
+import * as figmaFactory from '@/app/automation/bridge/figma-factory'
+import { createEditorStore } from '@/app/editor/session/create'
+
+import { expectDefined } from '#tests/helpers/assert'
+import { memoryTraceStore } from '#tests/helpers/chat/trace-store'
+import { MOCK_USAGE } from '#tests/helpers/chat/usage'
+
+type StreamChunk =
+ Awaited<ReturnType<MockLanguageModelV4['doStream']>>['stream'] extends ReadableStream<infer Chunk>
+ ? Chunk
+ : never
+
+const rectangle = (id: string, x: number): StreamChunk[] => [
+ {
+ type: 'tool-call',
+ toolCallId: id,
+ toolName: 'create_shape',
+ input: JSON.stringify({ type: 'RECTANGLE', x, y: 0, width: 10, height: 10 })
+ },
+ { type: 'finish', finishReason: { unified: 'tool-calls', raw: undefined }, usage: MOCK_USAGE }
+]
+
+const STEPS: StreamChunk[][] = [
+ rectangle('call-a', 0),
+ [
+ { type: 'reasoning-start', id: 'think' },
+ { type: 'reasoning-delta', id: 'think', delta: 'One more beside it.' },
+ { type: 'reasoning-end', id: 'think' },
+ ...rectangle('call-b', 20)
+ ],
+ [
+ { type: 'text-start', id: 'reply' },
+ { type: 'text-delta', id: 'reply', delta: 'Drew two rectangles.' },
+ { type: 'text-end', id: 'reply' },
+ { type: 'finish', finishReason: { unified: 'stop', raw: undefined }, usage: MOCK_USAGE }
+ ]
+]
+
+const previousTools = aiToolOverrides.value
+afterEach(() => {
+ aiToolOverrides.value = previousTools
+})
+
+test('every recorded step rebuilds from the conversation to the request the model received', async () => {
+ const store = createEditorStore()
+ spyOn(figmaFactory, 'makeFigmaFromStore').mockImplementation((editor, pageId) => {
+ const api = new FigmaAPI(editor.graph)
+ api.currentPage = api.wrapNode(pageId ?? editor.state.currentPageId)
+ return api
+ })
+ store.preparationController.acknowledgePresentation(Number.MAX_SAFE_INTEGER)
+ aiToolOverrides.value = { create_shape: true }
+
+ let call = 0
+ const model = new MockLanguageModelV4({
+ doStream: async () => ({
+ stream: simulateReadableStream<StreamChunk>({
+ initialDelayInMs: null,
+ chunkDelayInMs: null,
+ chunks: STEPS[call++] ?? []
+ })
+ })
+ })
+ const traces = memoryTraceStore()
+ const recorder = createRunRecorder(traces.store)
+ const transport = createToolLoopTransport({
+ store,
+ providerID: 'openai',
+ model,
+ effectiveModelID: 'test',
+ maxOutputTokens: 100,
+ thinkingLevel: () => 'default',
+ diagnosticContext: { sessionId: 'conversation', runId: 'run' },
+ recorder
+ })
+ const earlier: UIMessage[] = [
+ { id: 'first', role: 'user', parts: [{ type: 'text', text: 'Hello' }] },
+ { id: 'answer', role: 'assistant', parts: [{ type: 'text', text: 'Hi' }] },
+ { id: 'request', role: 'user', parts: [{ type: 'text', text: 'Draw two rectangles' }] }
+ ]
+ const stream = await transport.sendMessages({
+ trigger: 'submit-message',
+ chatId: 'conversation',
+ messageId: undefined,
+ abortSignal: undefined,
+ messages: earlier
+ })
+ let reply: UIMessage | undefined
+ for await (const message of readUIMessageStream({ stream })) reply = message
+ await recorder.flush()
+
+ const run = expectDefined(traces.runs.get('run'))
+ expect(run.outcome).toBe('completed')
+ expect(run.input).toEqual({ through: 'request', messages: 3 })
+ expect(run.steps.map((step) => step.response.finishReason)).toEqual([
+ 'tool-calls',
+ 'tool-calls',
+ 'stop'
+ ])
+ expect(traces.assets.get(run.instructions)?.kind).toBe('instructions')
+ expect(traces.assets.get(expectDefined(run.tools))).toMatchObject({
+ kind: 'tools',
+ tools: expect.arrayContaining([expect.objectContaining({ name: 'create_shape' })])
+ })
+
+ const conversation = [...earlier, expectDefined(reply)]
+ const tools = createAITools(store)
+ for (const step of run.steps) {
+ expect(await matchesRecordedStep(conversation, run, step.index, tools)).toBe(true)
+ }
+ expect(run.steps.map((step) => step.request.messages)).toEqual([3, 5, 7])
+ // A conversation that changed since no longer rebuilds to what was sent.
+ const edited = conversation.with(2, {
+ id: 'request',
+ role: 'user',
+ parts: [{ type: 'text', text: 'Draw three rectangles' }]
+ })
+ expect(await matchesRecordedStep(edited, run, 0, tools)).toBe(false)
+ // The last step saw both tool calls and their results.
+ const last = await rebuildStepMessages(conversation, run, 2, tools)
+ expect(last.filter((message) => message.role === 'tool')).toHaveLength(2)
+})
diff --git a/tests/app/ai/chat/trace/recorder.test.ts b/tests/app/ai/chat/trace/recorder.test.ts
new file mode 100644
index 000000000..b45c7aa9e
--- /dev/null
+++ b/tests/app/ai/chat/trace/recorder.test.ts
@@ -0,0 +1,41 @@
+import { expect, test } from 'bun:test'
+
+import { APICallError } from 'ai'
+
+import { createRunRecorder } from '@/app/ai/chat/trace/recorder'
+
+import { expectDefined } from '#tests/helpers/assert'
+import { memoryTraceStore } from '#tests/helpers/chat/trace-store'
+
+const KEY = 'sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789'
+
+test('a failed run keeps the provider error with keys scrubbed', async () => {
+ const traces = memoryTraceStore()
+ const recorder = createRunRecorder(traces.store)
+ const run = recorder.start({
+ conversationId: 'conversation',
+ runId: 'run',
+ model: { provider: 'anthropic', id: 'claude-test' },
+ settings: { maxOutputTokens: 100, maxSteps: 5, thinking: 'default', cache: true },
+ instructions: 'Design well.',
+ messages: [{ id: 'request', role: 'user', parts: [{ type: 'text', text: 'Draw' }] }]
+ })
+
+ run.fail(
+ new APICallError({
+ message: `Invalid x-api-key: ${KEY}`,
+ url: 'https://api.anthropic.com/v1/messages',
+ requestBodyValues: {},
+ statusCode: 401,
+ responseBody: JSON.stringify({ error: { message: `Invalid x-api-key: ${KEY}` } })
+ })
+ )
+ await recorder.flush()
+
+ const recorded = expectDefined(traces.runs.get('run'))
+ expect(recorded.outcome).toBe('failed')
+ const error = expectDefined(recorded.error)
+ expect(error.statusCode).toBe(401)
+ expect(error.message).toContain('Invalid x-api-key')
+ expect(JSON.stringify(error)).not.toContain(KEY)
+})
diff --git a/tests/e2e/chat/history.spec.ts b/tests/e2e/chat/history.spec.ts
index e8589ea59..9d0b0e80a 100644
--- a/tests/e2e/chat/history.spec.ts
+++ b/tests/e2e/chat/history.spec.ts
@@ -34,7 +34,6 @@ test('multiple conversations preserve messages and manual titles', async ({
if (!triggerBox || !menuBox) throw new Error('Missing menu geometry')
expect(Math.abs(menuBox.x + menuBox.width - triggerBox.x - triggerBox.width)).toBeLessThan(2)
expect(Math.abs(menuBox.y - triggerBox.y - triggerBox.height - 6)).toBeLessThan(2)
- await expect(page.getByRole('menuitem')).toHaveText(['Rename', 'Delete'])
await page.getByRole('menuitem', { name: 'Rename', exact: true }).click()
await page.getByRole('textbox', { name: 'Conversation title' }).fill('First design')
await page.getByRole('button', { name: 'Save', exact: true }).click()
diff --git a/tests/e2e/chat/menu.spec.ts b/tests/e2e/chat/menu.spec.ts
index 945f9c744..2d0d1bca0 100644
--- a/tests/e2e/chat/menu.spec.ts
+++ b/tests/e2e/chat/menu.spec.ts
@@ -1,3 +1,7 @@
+import { readFile } from 'node:fs/promises'
+
+import * as v from 'valibot'
+
import { test, expect } from '#tests/helpers/chat/fixture'
test('mobile conversation menu stays attached to its trigger and inside the viewport', async ({
@@ -14,7 +18,6 @@ test('mobile conversation menu stays attached to its trigger and inside the view
await trigger.click()
const menu = page.getByRole('menu')
await expect(menu).toBeVisible()
- await expect(page.getByRole('menuitem')).toHaveText(['Rename', 'Delete'])
await expect
.poll(async () => {
const box = await menu.boundingBox()
@@ -63,3 +66,42 @@ test('deleting a conversation asks in a confirmation dialog', async ({
await expect(page.getByRole('button', { name: /Conversation to keep/ })).toBeVisible()
await expect(page.getByRole('button', { name: /Conversation to delete/ })).toHaveCount(0)
})
+
+const TraceJSON = v.pipe(
+ v.string(),
+ v.parseJson(),
+ v.object({
+ conversation: v.object({ id: v.string(), title: v.string() }),
+ messages: v.array(
+ v.object({ message: v.object({ role: v.string(), parts: v.array(v.unknown()) }) })
+ ),
+ events: v.array(v.object({ name: v.string(), sessionId: v.optional(v.string()) }))
+ })
+)
+
+test('a conversation saves its raw trace with tool calls and run events', async ({
+ configuredChat: chat,
+ page
+}) => {
+ // Without a save picker the browser downloads the file.
+ await page.evaluate(() => Reflect.deleteProperty(window, 'showSaveFilePicker'))
+ await chat.submit('Create a frame')
+ await expect(
+ chat.assistantMessage().getByRole('button', { name: /^Done Create Shape\b/ })
+ ).toBeVisible()
+
+ await page.getByRole('button', { name: 'Conversation actions' }).click()
+ const [download] = await Promise.all([
+ page.waitForEvent('download'),
+ page.getByRole('menuitem', { name: 'Save trace…' }).click()
+ ])
+
+ const path = await download.path()
+ const trace = v.parse(TraceJSON, await readFile(path, 'utf8'))
+ // Named after the conversation, as other exports are named after their layer or document.
+ expect(download.suggestedFilename()).toBe(`${trace.conversation.title} trace.json`)
+ expect(trace.messages.map((row) => row.message.role)).toEqual(['user', 'assistant'])
+ expect(JSON.stringify(trace.messages[1]?.message.parts)).toContain('"toolCallId"')
+ expect(trace.events.map((event) => event.name)).toContain('chat.completed')
+ expect(trace.events.every((event) => event.sessionId === trace.conversation.id)).toBe(true)
+})
diff --git a/tests/e2e/settings/diagnostics.spec.ts b/tests/e2e/settings/diagnostics.spec.ts
index 61a4360db..478f20fe9 100644
--- a/tests/e2e/settings/diagnostics.spec.ts
+++ b/tests/e2e/settings/diagnostics.spec.ts
@@ -1,3 +1,5 @@
+import { readFile } from 'node:fs/promises'
+
import type { Page } from '@playwright/test'
import * as v from 'valibot'
@@ -50,6 +52,24 @@ test('Settings exports correlated chat telemetry without conversation content',
expect(text).not.toContain('A second request')
})
+test('Settings saves the diagnostics report as a file', async ({ configuredChat: chat, page }) => {
+ // Without a save picker the browser downloads the file.
+ await page.evaluate(() => Reflect.deleteProperty(window, 'showSaveFilePicker'))
+ await chat.submit('A request to record')
+ await expect(chat.assistantMessage()).toBeVisible()
+ await openDiagnostics(page)
+
+ const [download] = await Promise.all([
+ page.waitForEvent('download'),
+ page.getByRole('button', { name: 'Save diagnostics…', exact: true }).click()
+ ])
+
+ expect(download.suggestedFilename()).toMatch(/\.json$/)
+ const { environment, events } = v.parse(ReportJSON, await readFile(await download.path(), 'utf8'))
+ expect(environment).toMatchObject({ shell: 'browser' })
+ expect(events.map((event) => event.name)).toContain('chat.completed')
+})
+
async function openDiagnostics(page: Page) {
await page.keyboard.press(process.platform === 'darwin' ? 'Meta+,' : 'Control+,')
await page.getByTestId('settings-section-diagnostics').click()
diff --git a/tests/engine/app/chat/history/idb.test.ts b/tests/engine/app/chat/history/idb.test.ts
index 7670fae08..12c7a9584 100644
--- a/tests/engine/app/chat/history/idb.test.ts
+++ b/tests/engine/app/chat/history/idb.test.ts
@@ -1,8 +1,9 @@
import 'fake-indexeddb/auto'
import { describe, expect, test } from 'bun:test'
-import { createConversationStore } from '@/app/ai/chat/history/idb'
+import { createConversationStore, createTraceStore } from '@/app/ai/chat/history/idb'
import type { Conversation } from '@/app/ai/chat/history/types'
+import type { RunTrace } from '@/app/ai/chat/trace/types'
function conversation(): Conversation {
return {
@@ -120,4 +121,40 @@ describe('conversation IndexedDB storage', () => {
expect(await store.getSelected(row.documentId)).toBeNull()
expect((await store.list(row.documentId)).map((meta) => meta.id)).toEqual([other.id])
})
+
+ test('keeps a conversation’s runs until the conversation is deleted, and not after', async () => {
+ const store = createConversationStore()
+ const traces = createTraceStore()
+ const saved = conversation()
+ await store.write(saved)
+ const run = (runId: string, startedAt: string): RunTrace => ({
+ conversationId: saved.id,
+ runId,
+ startedAt,
+ model: { provider: 'openai', id: 'test' },
+ settings: { maxOutputTokens: 100, maxSteps: 5, thinking: 'default', cache: false },
+ instructions: 'sha256:instructions',
+ input: { through: 'user', messages: 1 },
+ steps: [],
+ outcome: 'completed'
+ })
+ await traces.putRun(run('second', '2026-01-01T00:02:00.000Z'))
+ await traces.putRun(run('first', '2026-01-01T00:01:00.000Z'))
+ await traces.putAsset('sha256:instructions', { kind: 'instructions', text: 'Design well.' })
+
+ expect((await traces.listRuns(saved.id)).map((entry) => entry.runId)).toEqual([
+ 'first',
+ 'second'
+ ])
+ expect(await traces.getAsset('sha256:instructions')).toEqual({
+ kind: 'instructions',
+ text: 'Design well.'
+ })
+
+ await store.remove(saved.id)
+ expect(await traces.listRuns(saved.id)).toEqual([])
+ // A run still streaming when its conversation was deleted does not bring it back.
+ await traces.putRun(run('late', '2026-01-01T00:03:00.000Z'))
+ expect(await traces.listRuns(saved.id)).toEqual([])
+ })
})
diff --git a/tests/helpers/chat/trace-store.ts b/tests/helpers/chat/trace-store.ts
new file mode 100644
index 000000000..8e2cbbf87
--- /dev/null
+++ b/tests/helpers/chat/trace-store.ts
@@ -0,0 +1,22 @@
+import type { RunTrace, TraceAsset, TraceStore } from '@/app/ai/chat/trace/types'
+
+/** A `TraceStore` in memory, with its runs and assets open to inspection. */
+export function memoryTraceStore() {
+ const runs = new Map<string, RunTrace>()
+ const assets = new Map<string, TraceAsset>()
+ const store: TraceStore = {
+ async putRun(run) {
+ runs.set(run.runId, run)
+ },
+ async listRuns(conversationId) {
+ return [...runs.values()].filter((run) => run.conversationId === conversationId)
+ },
+ async putAsset(hash, asset) {
+ assets.set(hash, asset)
+ },
+ async getAsset(hash) {
+ return assets.get(hash)
+ }
+ }
+ return { store, runs, assets }
+}