AI-native design editor. Open-source Figma alternative.
feat(app): record runtime errors in diagnostics and make events readable (#874)
Danila Poyarkova50444c265f5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3494ee9f6..562498daa 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,7 @@### Added+- Diagnose failures from Settings → Diagnostics. Uncaught errors, unhandled rejections, component errors, failed AI chats, and AI tool calls that broke inside OpenPencil are recorded with their message and stack, and other failed tool calls as warnings. Messages and stacks are scrubbed of URL queries and credentials, API keys and tokens, email addresses, and home folder names, and provider errors keep no message. Each event has a specific label, such as *Tool: render · 162 ms* or *Error: TypeError*, expands to its details, and can be filtered by level and category and paged; copied diagnostics include the app version and browser.- Import `resolvePasteTarget` from `@open-pencil/core/editor` to place ordinary pasted or dropped content in an embedding app in the same container the editor would choose. It takes the editor `createEditor` returns. Replacement paste is not covered: it inserts into the selected target's parent.- Import `flattenNodesToVectorProps`, `outlineStrokeNodesToVectorProps`, and the `VectorFlattenProps` type from `@open-pencil/core/canvas` to compute Flatten and Outline stroke geometry in an embedding app without going through the editor's own write path.- Check designs from the new Lint tab in the right panel: issues on the page, in the selection, or across the document are grouped by rule, hovering one highlights its layer on the canvas, clicking selects it and brings it into view, and one-click fixes bind colors to the variable they match and round subpixel geometry for a row or a whole group, and snap radius, spacing, and small text to the scale, convert groups to frames, and delete hidden layers one row at a time. Rules can be turned off individually or switched between the Recommended, Strict, and Accessibility presets.diff --git a/packages/core/src/tools/ai-adapter.ts b/packages/core/src/tools/ai-adapter.tsindex 42160aa08..024cd515f 100644--- a/packages/core/src/tools/ai-adapter.ts+++ b/packages/core/src/tools/ai-adapter.ts@@ -17,6 +17,8 @@ export interface ToolLogEntry {args: Record<string, unknown>result: unknownerror?: string+ /** What the tool threw, kept for diagnostics; the model gets only `error`. */+ cause?: unknowntimestamp: numberdurationMs: numbermutates: boolean@@ -113,14 +115,14 @@ function emitToolLog(figma: FigmaAPI,nodeBefore: Record<string, unknown> | undefined,execResult: unknown,- error?: string+ failure?: { error: string; cause: unknown }): void {if (!options.onToolLog) returnlet nodeAfter: Record<string, unknown> | undefinedlet unchangedProps: string[] | undefined- if (def.mutates && !error) {+ if (def.mutates && !failure) {nodeAfter = captureNodeSnapshot(figma, args)if (nodeBefore && nodeAfter) {unchangedProps = detectUnchangedProps(def.name, args, nodeBefore, nodeAfter)@@ -131,7 +133,8 @@ function emitToolLog(tool: def.name,args,result: execResult,- error,+ error: failure?.error,+ cause: failure?.cause,timestamp: startTime,durationMs: Date.now() - startTime,mutates: !!def.mutates,@@ -141,6 +144,12 @@ function emitToolLog(})}+/** Most tools report a failure by returning `{ error }` rather than throwing. */+function returnedError(result: unknown): string | undefined {+ if (typeof result !== 'object' || result === null || !('error' in result)) return undefined+ return typeof result.error === 'string' ? result.error : undefined+}+function isImageOutput(output: unknown): output is { base64: string; mimeType: string; [key: string]: unknown } {@@ -185,14 +194,27 @@ export function toolsToAI(const ids = extractNodeIds(execResult)if (ids.length > 0) options.onFlashNodes(ids)}- emitToolLog(options, def, args, startTime, figma, nodeBefore, execResult)+ const error = returnedError(execResult)+ emitToolLog(+ options,+ def,+ args,+ startTime,+ figma,+ nodeBefore,+ execResult,+ error === undefined ? undefined : { error, cause: undefined }+ )if (options.getStepBudget) {execResult = appendStepWarning(execResult, options.getStepBudget())}return execResult} catch (err) {const errorMsg = err instanceof Error ? err.message : String(err)- emitToolLog(options, def, args, startTime, figma, nodeBefore, null, errorMsg)+ emitToolLog(options, def, args, startTime, figma, nodeBefore, null, {+ error: errorMsg,+ cause: err+ })return { error: errorMsg }} finally {await options.onAfterExecute?.(def)diff --git a/packages/core/tests/tools/ai-adapter.test.ts b/packages/core/tests/tools/ai-adapter.test.tsindex 0077c8332..53458602d 100644--- a/packages/core/tests/tools/ai-adapter.test.ts+++ b/packages/core/tests/tools/ai-adapter.test.ts@@ -4,7 +4,7 @@ import { toolModelMessageSchema } from 'ai'import * as v from 'valibot'import { FigmaAPI } from '@open-pencil/core/figma-api'-import { defineTool, toolsToAI } from '@open-pencil/core/tools'+import { defineTool, toolsToAI, type ToolLogEntry } from '@open-pencil/core/tools'import { SceneGraph } from '@open-pencil/scene-graph'type ToolFactory = Parameters<typeof toolsToAI>[2]['tool']@@ -76,3 +76,58 @@ describe('AI adapter model output', () => {expect(adapt(output).toModelOutput({ output })).toEqual({ type: 'json', value: output })})})++type ExecutableTool = {+ execute(args: Record<string, unknown>, options: { toolCallId: string }): Promise<unknown>+}++function hasExecute(value: unknown): value is ExecutableTool {+ return (+ typeof value === 'object' &&+ value !== null &&+ 'execute' in value &&+ typeof value.execute === 'function'+ )+}++async function runLogged(execute: () => unknown) {+ const def = defineTool({+ name: 'logged_tool',+ description: 'Runs the given body',+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({}),+ execute+ })+ const figma = new FigmaAPI(new SceneGraph())+ const entries: ToolLogEntry[] = []+ const tools = toolsToAI(+ [def],+ { getFigma: () => figma, onToolLog: (entry) => entries.push(entry) },+ { tool }+ )+ const adapted: unknown = tools.logged_tool+ if (!hasExecute(adapted)) throw new Error('logged_tool has no execute')+ const result = await adapted.execute({}, { toolCallId: 'call' })+ return { result, entries }+}++describe('AI adapter tool log', () => {+ test('gives the model the message and the log what was thrown', async () => {+ const thrown = new TypeError('stops.map is not a function')+ const { result, entries } = await runLogged(() => {+ throw thrown+ })+ expect(result).toEqual({ error: 'stops.map is not a function' })+ expect(entries).toMatchObject([{ error: 'stops.map is not a function', cause: thrown }])+ })++ test('logs a returned error as a failure, like a thrown one', async () => {+ const { entries } = await runLogged(() => ({ id: '999:999', error: 'Node "999:999" not found' }))+ expect(entries).toMatchObject([{ error: 'Node "999:999" not found', cause: undefined }])+ })++ test('logs a result without an error as a success', async () => {+ const { entries } = await runLogged(() => ({ id: '1:2', name: 'Card' }))+ expect(entries[0]?.error).toBeUndefined()+ })+})diff --git a/packages/vue/src/i18n/locales/de/diagnostics.json b/packages/vue/src/i18n/locales/de/diagnostics.jsonindex f56eb6ad4..b7d9114a0 100644--- a/packages/vue/src/i18n/locales/de/diagnostics.json+++ b/packages/vue/src/i18n/locales/de/diagnostics.json@@ -13,14 +13,12 @@"usageHistory": "Nutzungsverlauf","usageHistoryDescription": "Lokale Zusammenfassungen der AI-Nutzung speichern.","title": "Diagnose",- "modelStepCompleted": "KI-Modellschritt abgeschlossen","chatCompleted": "KI-Chat abgeschlossen","chatFailed": "KI-Chat fehlgeschlagen","storageFailed": "Speichervorgang fehlgeschlagen","documentFailed": "Dokumentvorgang fehlgeschlagen","acpFailed": "ACP-Transport fehlgeschlagen","mcpFailed": "MCP-Verbindung fehlgeschlagen",- "technicalEvent": "Technisches Ereignis","retention": "Aufbewahrungsdauer der Diagnose","retentionDescription": "Bis zu dieser Anzahl aktueller Ereignisse lokal speichern.","description": "Technische Ereignisse lokal speichern, um OpenPencil zu unterstützen. Prompts, Designinhalte, Zugangsdaten und API-Schlüssel werden ausgeschlossen.",@@ -32,5 +30,39 @@"copied": "Diagnosedaten in die Zwischenablage kopiert.","copyFailed": "Diagnosedaten konnten nicht in die Zwischenablage kopiert werden.","retentionCustom": "Eigener Wert…",- "retentionRange": "Gib eine ganze Zahl von {min} bis {max} ein."+ "retentionRange": "Gib eine ganze Zahl von {min} bis {max} ein.",+ "modelStep": "Modellschritt · {model}",+ "modelStepTokens": "{input} ein · {output} aus Tokens",+ "toolCompleted": "Werkzeug: {tool}",+ "toolFailed": "Werkzeug fehlgeschlagen: {tool}",+ "durationMs": "{ms} ms",+ "runtimeError": "Fehler: {name}",+ "preparationDocumentOpen": "Dokument öffnen",+ "preparationDocumentReload": "Dokument neu laden",+ "preparationRecoveryRestore": "Wiederhergestelltes Dokument öffnen",+ "preparationStorageOpen": "Aus Cloud-Speicher öffnen",+ "preparationPageSwitch": "Seite wechseln",+ "preparationFontRetry": "Schriften erneut laden",+ "preparationDomImport": "HTML importieren",+ "preparationDemoLoad": "Demodokument laden",+ "preparationCompleted": "Abgeschlossen · {duration}",+ "preparationCancelled": "Abgebrochen: {reason} · {duration}",+ "preparationFailed": "Fehlgeschlagen: {code} · {duration}",+ "filterLevel": "Ereignisstufe",+ "filterAll": "Alle",+ "filterProblems": "Fehler und Warnungen",+ "filterCategory": "Ereigniskategorie",+ "allCategories": "Alle Kategorien",+ "categoryAI": "KI",+ "categoryDocument": "Dokument",+ "categoryRenderer": "Renderer",+ "categoryStorage": "Speicher",+ "categorySync": "Synchronisierung",+ "categoryMCP": "MCP",+ "categoryRecovery": "Wiederherstellung",+ "categoryPerformance": "Leistung",+ "categoryRuntime": "Laufzeit",+ "noMatchingEvents": "Keine Ereignisse entsprechen diesen Filtern.",+ "showMore": "Mehr anzeigen",+ "showingEvents": "{shown} von {total}"}diff --git a/packages/vue/src/i18n/locales/es/diagnostics.json b/packages/vue/src/i18n/locales/es/diagnostics.jsonindex 64506dc24..5e3b0952a 100644--- a/packages/vue/src/i18n/locales/es/diagnostics.json+++ b/packages/vue/src/i18n/locales/es/diagnostics.json@@ -13,14 +13,12 @@"usageHistory": "Historial de uso","usageHistoryDescription": "Conserva resúmenes locales del uso de AI.","title": "Diagnóstico",- "modelStepCompleted": "Paso del modelo de AI completado","chatCompleted": "Chat de AI completado","chatFailed": "Chat de AI fallido","storageFailed": "Operación de almacenamiento fallida","documentFailed": "Operación de documento fallida","acpFailed": "Transporte ACP fallido","mcpFailed": "Conexión MCP fallida",- "technicalEvent": "Evento técnico","retention": "Retención de diagnósticos","retentionDescription": "Conserva localmente hasta este número de eventos recientes.","description": "Guarda eventos técnicos localmente para ayudar a solucionar problemas de OpenPencil. Se excluyen prompts, contenido de diseño, credenciales y claves API.",@@ -32,5 +30,39 @@"copied": "Diagnóstico copiado al portapapeles.","copyFailed": "No se pudo copiar el diagnóstico al portapapeles.","retentionCustom": "Personalizado…",- "retentionRange": "Introduce un número entero entre {min} y {max}."+ "retentionRange": "Introduce un número entero entre {min} y {max}.",+ "modelStep": "Paso del modelo · {model}",+ "modelStepTokens": "{input} de entrada · {output} de salida",+ "toolCompleted": "Herramienta: {tool}",+ "toolFailed": "Falló la herramienta: {tool}",+ "durationMs": "{ms} ms",+ "runtimeError": "Error: {name}",+ "preparationDocumentOpen": "Abrir documento",+ "preparationDocumentReload": "Recargar documento",+ "preparationRecoveryRestore": "Restaurar documento recuperado",+ "preparationStorageOpen": "Abrir desde el almacenamiento en la nube",+ "preparationPageSwitch": "Cambiar de página",+ "preparationFontRetry": "Reintentar fuentes",+ "preparationDomImport": "Importar HTML",+ "preparationDemoLoad": "Cargar documento de demostración",+ "preparationCompleted": "Completado · {duration}",+ "preparationCancelled": "Cancelado: {reason} · {duration}",+ "preparationFailed": "Error: {code} · {duration}",+ "filterLevel": "Nivel del evento",+ "filterAll": "Todos",+ "filterProblems": "Errores y advertencias",+ "filterCategory": "Categoría del evento",+ "allCategories": "Todas las categorías",+ "categoryAI": "IA",+ "categoryDocument": "Documento",+ "categoryRenderer": "Renderizador",+ "categoryStorage": "Almacenamiento",+ "categorySync": "Sincronización",+ "categoryMCP": "MCP",+ "categoryRecovery": "Recuperación",+ "categoryPerformance": "Rendimiento",+ "categoryRuntime": "Ejecución",+ "noMatchingEvents": "Ningún evento coincide con estos filtros.",+ "showMore": "Mostrar más",+ "showingEvents": "{shown} de {total}"}diff --git a/packages/vue/src/i18n/locales/fr/diagnostics.json b/packages/vue/src/i18n/locales/fr/diagnostics.jsonindex 182edfb84..a1077b374 100644--- a/packages/vue/src/i18n/locales/fr/diagnostics.json+++ b/packages/vue/src/i18n/locales/fr/diagnostics.json@@ -13,14 +13,12 @@"usageHistory": "Historique d’utilisation","usageHistoryDescription": "Conserver les résumés locaux de l’utilisation de l’IA.","title": "Diagnostics",- "modelStepCompleted": "Étape du modèle IA terminée","chatCompleted": "Chat IA terminé","chatFailed": "Échec du chat IA","storageFailed": "Échec de l’opération de stockage","documentFailed": "Échec de l’opération sur le document","acpFailed": "Échec du transport ACP","mcpFailed": "Échec de la connexion MCP",- "technicalEvent": "Événement technique","retention": "Rétention des diagnostics","retentionDescription": "Conservez localement jusqu’à ce nombre d’événements récents.","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.",@@ -32,5 +30,39 @@"copied": "Diagnostics copiés dans le presse-papiers.","copyFailed": "Impossible de copier les diagnostics dans le presse-papiers.","retentionCustom": "Personnalisé…",- "retentionRange": "Saisissez un nombre entier entre {min} et {max}."+ "retentionRange": "Saisissez un nombre entier entre {min} et {max}.",+ "modelStep": "Étape du modèle · {model}",+ "modelStepTokens": "{input} en entrée · {output} en sortie",+ "toolCompleted": "Outil : {tool}",+ "toolFailed": "Échec de l’outil : {tool}",+ "durationMs": "{ms} ms",+ "runtimeError": "Erreur : {name}",+ "preparationDocumentOpen": "Ouvrir le document",+ "preparationDocumentReload": "Recharger le document",+ "preparationRecoveryRestore": "Restaurer le document récupéré",+ "preparationStorageOpen": "Ouvrir depuis le stockage cloud",+ "preparationPageSwitch": "Changer de page",+ "preparationFontRetry": "Recharger les polices",+ "preparationDomImport": "Importer du HTML",+ "preparationDemoLoad": "Charger le document de démonstration",+ "preparationCompleted": "Terminé · {duration}",+ "preparationCancelled": "Annulé : {reason} · {duration}",+ "preparationFailed": "Échec : {code} · {duration}",+ "filterLevel": "Niveau de l’événement",+ "filterAll": "Tous",+ "filterProblems": "Erreurs et avertissements",+ "filterCategory": "Catégorie de l’événement",+ "allCategories": "Toutes les catégories",+ "categoryAI": "IA",+ "categoryDocument": "Document",+ "categoryRenderer": "Moteur de rendu",+ "categoryStorage": "Stockage",+ "categorySync": "Synchronisation",+ "categoryMCP": "MCP",+ "categoryRecovery": "Récupération",+ "categoryPerformance": "Performances",+ "categoryRuntime": "Exécution",+ "noMatchingEvents": "Aucun événement ne correspond à ces filtres.",+ "showMore": "Afficher plus",+ "showingEvents": "{shown} sur {total}"}diff --git a/packages/vue/src/i18n/locales/it/diagnostics.json b/packages/vue/src/i18n/locales/it/diagnostics.jsonindex a3a89da21..68bab82c6 100644--- a/packages/vue/src/i18n/locales/it/diagnostics.json+++ b/packages/vue/src/i18n/locales/it/diagnostics.json@@ -13,14 +13,12 @@"usageHistory": "Cronologia utilizzo","usageHistoryDescription": "Conserva i riepiloghi locali dell’utilizzo dell’AI.","title": "Diagnostica",- "modelStepCompleted": "Passaggio del modello AI completato","chatCompleted": "Chat AI completata","chatFailed": "Chat AI non riuscita","storageFailed": "Operazione di archiviazione non riuscita","documentFailed": "Operazione sul documento non riuscita","acpFailed": "Trasporto ACP non riuscito","mcpFailed": "Connessione MCP non riuscita",- "technicalEvent": "Evento tecnico","retention": "Conservazione diagnostica","retentionDescription": "Conserva localmente fino a questo numero di eventi recenti.","description": "Conserva localmente gli eventi tecnici per aiutare a risolvere i problemi di OpenPencil. Prompt, contenuti di design, credenziali e chiavi API sono esclusi.",@@ -32,5 +30,39 @@"copied": "Diagnostica copiata negli appunti.","copyFailed": "Impossibile copiare la diagnostica negli appunti.","retentionCustom": "Personalizzato…",- "retentionRange": "Inserisci un numero intero da {min} a {max}."+ "retentionRange": "Inserisci un numero intero da {min} a {max}.",+ "modelStep": "Passaggio del modello · {model}",+ "modelStepTokens": "{input} in ingresso · {output} in uscita",+ "toolCompleted": "Strumento: {tool}",+ "toolFailed": "Strumento non riuscito: {tool}",+ "durationMs": "{ms} ms",+ "runtimeError": "Errore: {name}",+ "preparationDocumentOpen": "Apri documento",+ "preparationDocumentReload": "Ricarica documento",+ "preparationRecoveryRestore": "Ripristina documento recuperato",+ "preparationStorageOpen": "Apri dallo spazio di archiviazione cloud",+ "preparationPageSwitch": "Cambia pagina",+ "preparationFontRetry": "Riprova i font",+ "preparationDomImport": "Importa HTML",+ "preparationDemoLoad": "Carica documento demo",+ "preparationCompleted": "Completato · {duration}",+ "preparationCancelled": "Annullato: {reason} · {duration}",+ "preparationFailed": "Non riuscito: {code} · {duration}",+ "filterLevel": "Livello dell’evento",+ "filterAll": "Tutti",+ "filterProblems": "Errori e avvisi",+ "filterCategory": "Categoria dell’evento",+ "allCategories": "Tutte le categorie",+ "categoryAI": "IA",+ "categoryDocument": "Documento",+ "categoryRenderer": "Renderer",+ "categoryStorage": "Archiviazione",+ "categorySync": "Sincronizzazione",+ "categoryMCP": "MCP",+ "categoryRecovery": "Ripristino",+ "categoryPerformance": "Prestazioni",+ "categoryRuntime": "Runtime",+ "noMatchingEvents": "Nessun evento corrisponde a questi filtri.",+ "showMore": "Mostra altro",+ "showingEvents": "{shown} di {total}"}diff --git a/packages/vue/src/i18n/locales/ja/diagnostics.json b/packages/vue/src/i18n/locales/ja/diagnostics.jsonindex 9b48f3d71..91736342b 100644--- a/packages/vue/src/i18n/locales/ja/diagnostics.json+++ b/packages/vue/src/i18n/locales/ja/diagnostics.json@@ -13,14 +13,12 @@"usageHistory": "使用履歴","usageHistoryDescription": "AIの使用状況の概要を端末に保存します。","title": "診断",- "modelStepCompleted": "AIモデルのステップ完了","chatCompleted": "AIチャット完了","chatFailed": "AIチャット失敗","storageFailed": "ストレージ操作失敗","documentFailed": "ドキュメント操作失敗","acpFailed": "ACPトランスポート失敗","mcpFailed": "MCP接続失敗",- "technicalEvent": "技術イベント","retention": "診断データの保持数","retentionDescription": "この数までの最新イベントを端末に保存します。","description": "OpenPencilのトラブルシューティングに役立つ技術イベントを端末に保存します。プロンプト、デザイン内容、認証情報、APIキーは除外されます。",@@ -32,5 +30,39 @@"copied": "診断データをクリップボードにコピーしました。","copyFailed": "診断データをクリップボードにコピーできませんでした。","retentionCustom": "カスタム…",- "retentionRange": "{min} から {max} までの整数を入力してください。"+ "retentionRange": "{min} から {max} までの整数を入力してください。",+ "modelStep": "モデルのステップ · {model}",+ "modelStepTokens": "入力 {input} · 出力 {output} トークン",+ "toolCompleted": "ツール: {tool}",+ "toolFailed": "ツールが失敗しました: {tool}",+ "durationMs": "{ms} ms",+ "runtimeError": "エラー: {name}",+ "preparationDocumentOpen": "ドキュメントを開く",+ "preparationDocumentReload": "ドキュメントを再読み込み",+ "preparationRecoveryRestore": "復元したドキュメントを開く",+ "preparationStorageOpen": "クラウドストレージから開く",+ "preparationPageSwitch": "ページを切り替え",+ "preparationFontRetry": "フォントを再試行",+ "preparationDomImport": "HTML をインポート",+ "preparationDemoLoad": "デモドキュメントを読み込む",+ "preparationCompleted": "完了 · {duration}",+ "preparationCancelled": "キャンセル: {reason} · {duration}",+ "preparationFailed": "失敗: {code} · {duration}",+ "filterLevel": "イベントのレベル",+ "filterAll": "すべて",+ "filterProblems": "エラーと警告",+ "filterCategory": "イベントのカテゴリ",+ "allCategories": "すべてのカテゴリ",+ "categoryAI": "AI",+ "categoryDocument": "ドキュメント",+ "categoryRenderer": "レンダラー",+ "categoryStorage": "ストレージ",+ "categorySync": "同期",+ "categoryMCP": "MCP",+ "categoryRecovery": "復元",+ "categoryPerformance": "パフォーマンス",+ "categoryRuntime": "ランタイム",+ "noMatchingEvents": "このフィルターに一致するイベントはありません。",+ "showMore": "さらに表示",+ "showingEvents": "{total} 件中 {shown} 件"}diff --git a/packages/vue/src/i18n/locales/pl/diagnostics.json b/packages/vue/src/i18n/locales/pl/diagnostics.jsonindex 00673201d..855e58264 100644--- a/packages/vue/src/i18n/locales/pl/diagnostics.json+++ b/packages/vue/src/i18n/locales/pl/diagnostics.json@@ -13,14 +13,12 @@"usageHistory": "Historia użycia","usageHistoryDescription": "Zachowuj lokalne podsumowania użycia AI.","title": "Diagnostyka",- "modelStepCompleted": "Ukończono krok modelu AI","chatCompleted": "Ukończono czat AI","chatFailed": "Czat AI nie powiódł się","storageFailed": "Operacja przechowywania nie powiodła się","documentFailed": "Operacja dokumentu nie powiodła się","acpFailed": "Transport ACP nie powiódł się","mcpFailed": "Połączenie MCP nie powiodło się",- "technicalEvent": "Zdarzenie techniczne","retention": "Retencja diagnostyki","retentionDescription": "Zachowuj lokalnie do tej liczby ostatnich zdarzeń.","description": "Zapisuj lokalnie zdarzenia techniczne, aby ułatwić rozwiązywanie problemów z OpenPencil. Prompty, zawartość projektu, dane logowania i klucze API są wykluczone.",@@ -32,5 +30,39 @@"copied": "Skopiowano dane diagnostyczne do schowka.","copyFailed": "Nie można skopiować danych diagnostycznych do schowka.","retentionCustom": "Własna wartość…",- "retentionRange": "Wpisz liczbę całkowitą od {min} do {max}."+ "retentionRange": "Wpisz liczbę całkowitą od {min} do {max}.",+ "modelStep": "Krok modelu · {model}",+ "modelStepTokens": "{input} wej. · {output} wyj. tokenów",+ "toolCompleted": "Narzędzie: {tool}",+ "toolFailed": "Narzędzie nie powiodło się: {tool}",+ "durationMs": "{ms} ms",+ "runtimeError": "Błąd: {name}",+ "preparationDocumentOpen": "Otwórz dokument",+ "preparationDocumentReload": "Wczytaj dokument ponownie",+ "preparationRecoveryRestore": "Przywróć odzyskany dokument",+ "preparationStorageOpen": "Otwórz z magazynu w chmurze",+ "preparationPageSwitch": "Przełącz stronę",+ "preparationFontRetry": "Ponów wczytywanie czcionek",+ "preparationDomImport": "Importuj HTML",+ "preparationDemoLoad": "Wczytaj dokument demonstracyjny",+ "preparationCompleted": "Ukończono · {duration}",+ "preparationCancelled": "Anulowano: {reason} · {duration}",+ "preparationFailed": "Niepowodzenie: {code} · {duration}",+ "filterLevel": "Poziom zdarzenia",+ "filterAll": "Wszystkie",+ "filterProblems": "Błędy i ostrzeżenia",+ "filterCategory": "Kategoria zdarzenia",+ "allCategories": "Wszystkie kategorie",+ "categoryAI": "AI",+ "categoryDocument": "Dokument",+ "categoryRenderer": "Renderer",+ "categoryStorage": "Pamięć",+ "categorySync": "Synchronizacja",+ "categoryMCP": "MCP",+ "categoryRecovery": "Odzyskiwanie",+ "categoryPerformance": "Wydajność",+ "categoryRuntime": "Środowisko uruchomieniowe",+ "noMatchingEvents": "Żadne zdarzenia nie pasują do tych filtrów.",+ "showMore": "Pokaż więcej",+ "showingEvents": "{shown} z {total}"}diff --git a/packages/vue/src/i18n/locales/ru/diagnostics.json b/packages/vue/src/i18n/locales/ru/diagnostics.jsonindex 5d342cee8..050dec156 100644--- a/packages/vue/src/i18n/locales/ru/diagnostics.json+++ b/packages/vue/src/i18n/locales/ru/diagnostics.json@@ -13,14 +13,12 @@"usageHistory": "История использования","usageHistoryDescription": "Сохранять локальные сводки использования AI.","title": "Диагностика",- "modelStepCompleted": "Шаг AI-модели завершён","chatCompleted": "AI-чат завершён","chatFailed": "Ошибка AI-чата","storageFailed": "Ошибка операции хранения","documentFailed": "Ошибка операции с документом","acpFailed": "Ошибка транспорта ACP","mcpFailed": "Ошибка подключения MCP",- "technicalEvent": "Техническое событие","retention": "Срок хранения диагностики","retentionDescription": "Сохранять локально не более этого числа последних событий.","description": "Сохраняйте технические события локально для диагностики OpenPencil. Промпты, содержимое дизайна, учётные данные и API-ключи не сохраняются.",@@ -32,5 +30,39 @@"copied": "Диагностические данные скопированы в буфер обмена.","copyFailed": "Не удалось скопировать диагностические данные в буфер обмена.","retentionCustom": "Своё значение…",- "retentionRange": "Введите целое число от {min} до {max}."+ "retentionRange": "Введите целое число от {min} до {max}.",+ "modelStep": "Шаг модели · {model}",+ "modelStepTokens": "{input} на входе · {output} на выходе",+ "toolCompleted": "Инструмент: {tool}",+ "toolFailed": "Сбой инструмента: {tool}",+ "durationMs": "{ms} мс",+ "runtimeError": "Ошибка: {name}",+ "preparationDocumentOpen": "Открытие документа",+ "preparationDocumentReload": "Перезагрузка документа",+ "preparationRecoveryRestore": "Восстановление документа",+ "preparationStorageOpen": "Открытие из облачного хранилища",+ "preparationPageSwitch": "Переход на страницу",+ "preparationFontRetry": "Повторная загрузка шрифтов",+ "preparationDomImport": "Импорт HTML",+ "preparationDemoLoad": "Загрузка демо-документа",+ "preparationCompleted": "Готово · {duration}",+ "preparationCancelled": "Отменено: {reason} · {duration}",+ "preparationFailed": "Ошибка: {code} · {duration}",+ "filterLevel": "Уровень события",+ "filterAll": "Все",+ "filterProblems": "Ошибки и предупреждения",+ "filterCategory": "Категория события",+ "allCategories": "Все категории",+ "categoryAI": "ИИ",+ "categoryDocument": "Документ",+ "categoryRenderer": "Рендеринг",+ "categoryStorage": "Хранилище",+ "categorySync": "Синхронизация",+ "categoryMCP": "MCP",+ "categoryRecovery": "Восстановление",+ "categoryPerformance": "Производительность",+ "categoryRuntime": "Среда выполнения",+ "noMatchingEvents": "Нет событий, подходящих под эти фильтры.",+ "showMore": "Показать ещё",+ "showingEvents": "{shown} из {total}"}diff --git a/packages/vue/src/i18n/locales/zh-cn/diagnostics.json b/packages/vue/src/i18n/locales/zh-cn/diagnostics.jsonindex b20cb1233..f38bede49 100644--- a/packages/vue/src/i18n/locales/zh-cn/diagnostics.json+++ b/packages/vue/src/i18n/locales/zh-cn/diagnostics.json@@ -13,14 +13,12 @@"usageHistory": "使用历史","usageHistoryDescription": "保留本地 AI 使用摘要。","title": "诊断",- "modelStepCompleted": "AI 模型步骤已完成","chatCompleted": "AI 聊天已完成","chatFailed": "AI 聊天失败","storageFailed": "存储操作失败","documentFailed": "文档操作失败","acpFailed": "ACP 传输失败","mcpFailed": "MCP 连接失败",- "technicalEvent": "技术事件","retention": "诊断数据保留量","retentionDescription": "在本地保留不超过此数量的最新事件。","description": "在本地保存技术事件,帮助排查 OpenPencil 问题。不保存提示词、设计内容、凭据和 API 密钥。",@@ -32,5 +30,39 @@"copied": "诊断数据已复制到剪贴板。","copyFailed": "无法将诊断数据复制到剪贴板。","retentionCustom": "自定义…",- "retentionRange": "请输入 {min} 到 {max} 之间的整数。"+ "retentionRange": "请输入 {min} 到 {max} 之间的整数。",+ "modelStep": "模型步骤 · {model}",+ "modelStepTokens": "输入 {input} · 输出 {output} 个令牌",+ "toolCompleted": "工具:{tool}",+ "toolFailed": "工具失败:{tool}",+ "durationMs": "{ms} 毫秒",+ "runtimeError": "错误:{name}",+ "preparationDocumentOpen": "打开文档",+ "preparationDocumentReload": "重新加载文档",+ "preparationRecoveryRestore": "恢复已找回的文档",+ "preparationStorageOpen": "从云存储打开",+ "preparationPageSwitch": "切换页面",+ "preparationFontRetry": "重试字体",+ "preparationDomImport": "导入 HTML",+ "preparationDemoLoad": "加载演示文档",+ "preparationCompleted": "已完成 · {duration}",+ "preparationCancelled": "已取消:{reason} · {duration}",+ "preparationFailed": "失败:{code} · {duration}",+ "filterLevel": "事件级别",+ "filterAll": "全部",+ "filterProblems": "错误和警告",+ "filterCategory": "事件类别",+ "allCategories": "所有类别",+ "categoryAI": "AI",+ "categoryDocument": "文档",+ "categoryRenderer": "渲染器",+ "categoryStorage": "存储",+ "categorySync": "同步",+ "categoryMCP": "MCP",+ "categoryRecovery": "恢复",+ "categoryPerformance": "性能",+ "categoryRuntime": "运行时",+ "noMatchingEvents": "没有符合这些筛选条件的事件。",+ "showMore": "显示更多",+ "showingEvents": "{shown} / {total}"}diff --git a/packages/vue/src/i18n/messages/diagnostics.ts b/packages/vue/src/i18n/messages/diagnostics.tsindex 4f8a01692..ffa784098 100644--- a/packages/vue/src/i18n/messages/diagnostics.ts+++ b/packages/vue/src/i18n/messages/diagnostics.ts@@ -13,14 +13,46 @@ export const diagnosticsMessageDefaults = {usageNotReported: 'Not reported',usageCacheNote: 'Cache values are shown only when the provider reports them.',title: 'Diagnostics',- modelStepCompleted: 'AI model step completed',chatCompleted: 'AI chat completed',chatFailed: 'AI chat failed',storageFailed: 'Storage operation failed',documentFailed: 'Document operation failed',acpFailed: 'ACP transport failed',mcpFailed: 'MCP connection failed',- technicalEvent: 'Technical event',+ modelStep: params('Model step · {model}'),+ modelStepTokens: params('{input} in · {output} out tokens'),+ toolCompleted: params('Tool: {tool}'),+ toolFailed: params('Tool failed: {tool}'),+ durationMs: params('{ms} ms'),+ runtimeError: params('Error: {name}'),+ preparationDocumentOpen: 'Open document',+ preparationDocumentReload: 'Reload document',+ preparationRecoveryRestore: 'Restore recovered document',+ preparationStorageOpen: 'Open from cloud storage',+ preparationPageSwitch: 'Switch page',+ preparationFontRetry: 'Retry fonts',+ preparationDomImport: 'Import HTML',+ preparationDemoLoad: 'Load demo document',+ preparationCompleted: params('Completed · {duration}'),+ preparationCancelled: params('Cancelled: {reason} · {duration}'),+ preparationFailed: params('Failed: {code} · {duration}'),+ filterLevel: 'Event level',+ filterAll: 'All',+ filterProblems: 'Errors and warnings',+ filterCategory: 'Event category',+ allCategories: 'All categories',+ categoryAI: 'AI',+ categoryDocument: 'Document',+ categoryRenderer: 'Renderer',+ categoryStorage: 'Storage',+ categorySync: 'Sync',+ categoryMCP: 'MCP',+ categoryRecovery: 'Recovery',+ categoryPerformance: 'Performance',+ categoryRuntime: 'Runtime',+ noMatchingEvents: 'No events match these filters.',+ showMore: 'Show more',+ showingEvents: params('{shown} of {total}'),retention: 'Diagnostics retention',retentionCustom: 'Custom…',retentionRange: params('Enter a whole number from {min} to {max}.'),diff --git a/src/app/ai/chat/transports.ts b/src/app/ai/chat/transports.tsindex a8e696eaa..5391d1929 100644--- a/src/app/ai/chat/transports.ts+++ b/src/app/ai/chat/transports.ts@@ -25,6 +25,7 @@ import { createCanvasJSXPreview } from '@/app/ai/preview/canvas'import { createAITools, endRun, recordStep, runPageId, startRun } from '@/app/ai/tools'import { enabledAIToolDefinitions } from '@/app/ai/tools/catalog'import { aiToolOverrides } from '@/app/ai/tools/preferences'+import { diagnosticErrorDetails } from '@/app/diagnostics'import {recordChatCompleted,recordChatFailed,@@ -345,12 +346,8 @@ export function createChatSessionManager({const reportedError = activeProviderError ?? erroractiveProviderError = nullfailure.value = classifyAIChatError(reportedError)- recordChatFailed(- {- errorName: reportedError instanceof Error ? reportedError.name : 'unknown'- },- diagnosticContext- )+ const { errorName, errorCode, message, stack } = diagnosticErrorDetails(reportedError)+ recordChatFailed({ errorName, errorCode, message, stack }, diagnosticContext)},onFinish: (event) => handleChatFinish(diagnosticContext, event)})diff --git a/src/app/ai/tools/index.ts b/src/app/ai/tools/index.tsindex b78cf6382..05019293d 100644--- a/src/app/ai/tools/index.ts+++ b/src/app/ai/tools/index.ts@@ -121,7 +121,8 @@ export function createAITools(store: EditorStore, diagnosticContext?: AIDiagnostmutates: entry.mutates,failed: Boolean(entry.error)},- diagnosticContext+ diagnosticContext,+ entry.cause)},getStepBudget: () => stepBudget(store)diff --git a/src/app/diagnostics/environment.ts b/src/app/diagnostics/environment.tsnew file mode 100644index 000000000..38f2ad0b1--- /dev/null+++ b/src/app/diagnostics/environment.ts@@ -0,0 +1,12 @@+import { IS_TAURI } from '@/constants'++/** What a copied report needs to reproduce a problem: which build, shell, and browser. */+export function diagnosticsEnvironment() {+ return {+ app: typeof __OPENPENCIL_APP_VERSION__ === 'string' ? __OPENPENCIL_APP_VERSION__ : 'unknown',+ shell: IS_TAURI ? 'desktop' : 'browser',+ userAgent: typeof navigator === 'undefined' ? null : navigator.userAgent,+ language: typeof navigator === 'undefined' ? null : navigator.language,+ exportedAt: new Date().toISOString()+ }+}diff --git a/src/app/diagnostics/error.ts b/src/app/diagnostics/error.tsindex 5dc57d2e5..cce47c6b0 100644--- a/src/app/diagnostics/error.ts+++ b/src/app/diagnostics/error.ts@@ -1,3 +1,5 @@+import { REDACTED, scrubDiagnosticText } from './scrub'+export type DiagnosticErrorInfo = {errorName: stringerrorCode: string | null@@ -20,3 +22,65 @@ export function describeDiagnosticError(error: unknown): DiagnosticErrorInfo {const code = 'code' in error && typeof error.code === 'string' ? error.code : nullreturn { errorName: error.name || 'Error', errorCode: code, retryable: isRetryableError(error) }}++export type DiagnosticErrorDetails = DiagnosticErrorInfo & {+ message: string | null+ stack: string | null+}++const MAX_MESSAGE_LENGTH = 500+const MAX_STACK_LINES = 25+const MAX_STACK_LENGTH = 4000++/**+ * AI SDK and provider errors (`AI_APICallError`, `AI_InvalidPromptError`, …) and errors that+ * carry a response can quote prompts, responses, or request URLs in their message.+ */+function mayQuoteContent(error: Error): boolean {+ return error.name.startsWith('AI_') || 'responseBody' in error || 'requestBodyValues' in error+}++/**+ * Errors the engine raises on its own bugs, such as `x.map is not a function`. Their messages+ * name code, not content, unlike the errors a tool throws on purpose, which quote its input.+ */+export function isInternalError(error: unknown): error is Error {+ return (+ error instanceof TypeError || error instanceof ReferenceError || error instanceof RangeError+ )+}++/**+ * The metadata of `describeDiagnosticError`, plus the message and stack of a runtime failure,+ * scrubbed by `scrubDiagnosticText` and bounded in length.+ * A provider error keeps its stack but not its message, which can quote user content; V8 and+ * Bun repeat the message on the stack's first line, so it is removed there too.+ */+export function diagnosticErrorDetails(error: unknown): DiagnosticErrorDetails {+ const info = describeDiagnosticError(error)+ if (!(error instanceof Error)) {+ return {+ ...info,+ message: typeof error === 'string' ? storedMessage(error) : null,+ stack: null+ }+ }+ if (!mayQuoteContent(error)) {+ return {+ ...info,+ message: storedMessage(error.message),+ stack: error.stack ? storedStack(error.stack) : null+ }+ }+ const stack = error.message ? error.stack?.replaceAll(error.message, REDACTED) : error.stack+ return { ...info, message: null, stack: stack ? storedStack(stack) : null }+}++function storedMessage(message: string): string | null {+ return scrubDiagnosticText(message).slice(0, MAX_MESSAGE_LENGTH) || null+}++function storedStack(stack: string): string {+ const lines = scrubDiagnosticText(stack).split('\n').slice(0, MAX_STACK_LINES)+ return lines.join('\n').slice(0, MAX_STACK_LENGTH)+}diff --git a/src/app/diagnostics/events/ai.ts b/src/app/diagnostics/events/ai.tsindex c8d5343d5..1eddfd81b 100644--- a/src/app/diagnostics/events/ai.ts+++ b/src/app/diagnostics/events/ai.ts@@ -1,8 +1,15 @@+import { pick } from 'es-toolkit'import * as v from 'valibot'+import { describeDiagnosticError, diagnosticErrorDetails, isInternalError } from '../error'import { recordDiagnostic } from '../recorder'import { isUsageEnabled } from '../settings'-import type { DiagnosticEvent, DiagnosticValue } from '../types'+import type {+ DiagnosticEvent,+ DiagnosticEventInput,+ DiagnosticLevel,+ DiagnosticValue+} from '../types'const modelStepSchema = v.object({provider: v.string(),@@ -14,12 +21,20 @@ const modelStepSchema = v.object({})const chatCompletedSchema = v.object({ finishReason: v.nullable(v.string()) })-const chatFailedSchema = v.object({ errorName: v.string() })+const chatFailedSchema = v.object({+ errorName: v.string(),+ errorCode: v.optional(v.nullable(v.string())),+ message: v.optional(v.nullable(v.string())),+ stack: v.optional(v.nullable(v.string()))+})const toolCompletedSchema = v.object({tool: v.string(),durationMs: v.number(),mutates: v.boolean(),- failed: v.boolean()+ failed: v.boolean(),+ errorName: v.optional(v.string()),+ message: v.optional(v.nullable(v.string())),+ stack: v.optional(v.nullable(v.string()))})export type AIDiagnosticContext = Pick<DiagnosticEvent, 'sessionId' | 'runId'>@@ -28,7 +43,8 @@ function recordAIEvent(name: 'model.step.completed' | 'chat.completed' | 'chat.failed' | 'tool.completed',attributes: Record<string, DiagnosticValue>,schema: v.GenericSchema,- context: AIDiagnosticContext = {}+ context: AIDiagnosticContext = {},+ level: DiagnosticLevel = name === 'chat.failed' ? 'error' : 'info'): void {const parsed = v.safeParse(schema, attributes)if (!parsed.success) {@@ -40,10 +56,10 @@ function recordAIEvent(recordDiagnostic({...context,category: 'ai',- level: name === 'chat.failed' ? 'error' : 'info',+ level,name,attributes: output- } satisfies Omit<DiagnosticEvent, 'id' | 'timestamp'>)+ } satisfies DiagnosticEventInput)}export function recordModelStepCompleted(@@ -67,9 +83,31 @@ export function recordChatFailed(recordAIEvent('chat.failed', input, chatFailedSchema, context)}+type ToolOutcome = { level: DiagnosticLevel; details: Record<string, DiagnosticValue> }++/**+ * A failed call is a warning, since models often call a tool wrongly, and keeps only the+ * error's name: its message quotes the call's input. A bug in OpenPencil is an error and+ * keeps its message and stack, which name code rather than content.+ */+function toolOutcome(failed: boolean, cause: unknown): ToolOutcome {+ if (!failed) return { level: 'info', details: {} }+ if (isInternalError(cause)) {+ return {+ level: 'error',+ details: pick(diagnosticErrorDetails(cause), ['errorName', 'message', 'stack'])+ }+ }+ // A tool that returned `{ error }` threw nothing.+ const details = cause === undefined ? {} : pick(describeDiagnosticError(cause), ['errorName'])+ return { level: 'warning', details }+}+export function recordToolCompleted(- input: v.InferOutput<typeof toolCompletedSchema>,- context?: AIDiagnosticContext+ input: Omit<v.InferOutput<typeof toolCompletedSchema>, 'errorName' | 'message' | 'stack'>,+ context?: AIDiagnosticContext,+ cause?: unknown): void {- recordAIEvent('tool.completed', input, toolCompletedSchema, context)+ const { level, details } = toolOutcome(input.failed, cause)+ recordAIEvent('tool.completed', { ...input, ...details }, toolCompletedSchema, context, level)}diff --git a/src/app/diagnostics/events/document.ts b/src/app/diagnostics/events/document.tsindex 9ab8ce2ab..3a2d30fc3 100644--- a/src/app/diagnostics/events/document.ts+++ b/src/app/diagnostics/events/document.ts@@ -1,7 +1,7 @@import * as v from 'valibot'import { recordDiagnostic } from '../recorder'-import type { DiagnosticEvent } from '../types'+import type { DiagnosticEventInput } from '../types'const documentFailureSchema = v.object({operation: v.picklist(['open', 'save', 'import', 'export']),@@ -19,5 +19,5 @@ export function recordDocumentFailure(input: v.InferOutput<typeof documentFailurlevel: 'error',name: 'document.operation.failed',attributes: parsed.output- } satisfies Omit<DiagnosticEvent, 'id' | 'timestamp'>)+ } satisfies DiagnosticEventInput)}diff --git a/src/app/diagnostics/events/index.ts b/src/app/diagnostics/events/index.tsindex 3f7d87ea7..42d81fc70 100644--- a/src/app/diagnostics/events/index.ts+++ b/src/app/diagnostics/events/index.ts@@ -1,6 +1,7 @@export { recordChatCompleted, recordChatFailed, recordModelStepCompleted } from './ai'export { recordDocumentFailure } from './document'export { preparationDurationBucket, recordPreparationOutcome } from './preparation'+export { recordRuntimeError, type RuntimeErrorSource } from './runtime'export { recordStorageFailure } from './storage'export { recordACPTransportFailure, recordMCPConnectionFailure } from './transport'export { storageOperationForJob } from './storage-operation'diff --git a/src/app/diagnostics/events/preparation.ts b/src/app/diagnostics/events/preparation.tsindex 7e5168e53..e1372afaa 100644--- a/src/app/diagnostics/events/preparation.ts+++ b/src/app/diagnostics/events/preparation.ts@@ -1,42 +1,27 @@import * as v from 'valibot'-import type {- EditorPreparationCancelReason,- EditorPreparationFailure,- EditorPreparationKind,- EditorPreparationPhase+import {+ EDITOR_PREPARATION_CANCEL_REASONS,+ EDITOR_PREPARATION_FAILURE_CODES,+ EDITOR_PREPARATION_KINDS,+ EDITOR_PREPARATION_PHASES,+ type EditorPreparationCancelReason,+ type EditorPreparationFailure,+ type EditorPreparationKind,+ type EditorPreparationPhase} from '@/app/editor/preparation/types'import { recordDiagnostic } from '../recorder'-import type { DiagnosticEvent } from '../types'+import type { DiagnosticEventInput } from '../types'const durationBuckets = ['under-100ms', '100ms-1s', '1s-5s', '5s-30s', 'over-30s'] as constconst preparationSchema = v.object({- kind: v.picklist([- 'document-open',- 'document-reload',- 'recovery-restore',- 'storage-open',- 'page-switch',- 'font-retry',- 'dom-import'- ]),+ kind: v.picklist(EDITOR_PREPARATION_KINDS),outcome: v.picklist(['completed', 'cancelled', 'failed']),- cancellationReason: v.nullable(v.picklist(['superseded', 'tab-closed', 'user'])),- failureCode: v.nullable(- v.picklist(['read-failed', 'decode-failed', 'font-failed', 'layout-failed', 'render-failed'])- ),- terminalPhase: v.picklist([- 'reading',- 'decoding',- 'materializing',- 'populating-page',- 'resolving-fonts',- 'resolving-fallbacks',- 'layout',- 'preparing-render'- ]),+ cancellationReason: v.nullable(v.picklist(EDITOR_PREPARATION_CANCEL_REASONS)),+ failureCode: v.nullable(v.picklist(EDITOR_PREPARATION_FAILURE_CODES)),+ terminalPhase: v.picklist(EDITOR_PREPARATION_PHASES),durationBucket: v.picklist(durationBuckets)})@@ -68,5 +53,5 @@ export function recordPreparationOutcome(input: PreparationDiagnosticInput): voilevel: input.outcome === 'failed' ? 'error' : 'info',name: 'editor.preparation.finished',attributes: parsed.output- } satisfies Omit<DiagnosticEvent, 'id' | 'timestamp'>)+ } satisfies DiagnosticEventInput)}diff --git a/src/app/diagnostics/events/runtime.ts b/src/app/diagnostics/events/runtime.tsnew file mode 100644index 000000000..72de8b318--- /dev/null+++ b/src/app/diagnostics/events/runtime.ts@@ -0,0 +1,55 @@+import { diagnosticErrorDetails } from '../error'+import { recordDiagnostic } from '../recorder'++/** Where an uncaught failure surfaced: the window, an unhandled rejection, or a Vue component. */+export type RuntimeErrorSource = 'window' | 'rejection' | 'vue'++/**+ * A render loop can throw every frame, sometimes alternating between errors; one record per+ * distinct error per window is enough. Keys are kept in insertion order, oldest first.+ */+const REPEAT_WINDOW_MS = 2000+const MAX_TRACKED_ERRORS = 50+const recentErrors = new Map<string, number>()++/** Whether `key` was recorded within the window; remembers it as recorded now if not. */+function isRepeat(key: string, now: number): boolean {+ for (const [recentKey, at] of recentErrors) {+ if (now - at < REPEAT_WINDOW_MS) break+ recentErrors.delete(recentKey)+ }+ if (recentErrors.has(key)) return true+ recentErrors.set(key, now)+ if (recentErrors.size > MAX_TRACKED_ERRORS) {+ const [oldest] = recentErrors.keys()+ recentErrors.delete(oldest)+ }+ return false+}++/**+ * Record an uncaught error with its scrubbed message and stack. `info` is Vue's hint about+ * where a component error happened, such as `render function` or `watcher callback`.+ */+export function recordRuntimeError(+ error: unknown,+ source: RuntimeErrorSource,+ info?: string+): void {+ const details = diagnosticErrorDetails(error)+ const key = `${source}\n${details.errorName}\n${details.message ?? ''}\n${details.stack ?? ''}`+ if (isRepeat(key, Date.now())) return+ recordDiagnostic({+ category: 'runtime',+ level: 'error',+ name: 'runtime.error',+ attributes: {+ source,+ errorName: details.errorName,+ errorCode: details.errorCode,+ message: details.message,+ stack: details.stack,+ info: info ?? null+ }+ })+}diff --git a/src/app/diagnostics/events/storage.ts b/src/app/diagnostics/events/storage.tsindex 179cbb394..3b5129225 100644--- a/src/app/diagnostics/events/storage.ts+++ b/src/app/diagnostics/events/storage.ts@@ -1,7 +1,7 @@import * as v from 'valibot'import { recordDiagnostic } from '../recorder'-import type { DiagnosticEvent } from '../types'+import type { DiagnosticEventInput } from '../types'const storageFailureSchema = v.object({operation: v.picklist(['upload', 'download', 'delete', 'list']),@@ -18,5 +18,5 @@ export function recordStorageFailure(input: v.InferOutput<typeof storageFailureSlevel: 'error',name: 'storage.operation.failed',attributes: parsed.output- } satisfies Omit<DiagnosticEvent, 'id' | 'timestamp'>)+ } satisfies DiagnosticEventInput)}diff --git a/src/app/diagnostics/events/transport.ts b/src/app/diagnostics/events/transport.tsindex d56507ea3..12b890174 100644--- a/src/app/diagnostics/events/transport.ts+++ b/src/app/diagnostics/events/transport.ts@@ -1,7 +1,7 @@import * as v from 'valibot'import { recordDiagnostic } from '../recorder'-import type { DiagnosticEvent } from '../types'+import type { DiagnosticEventInput } from '../types'const mcpFailureSchema = v.object({operation: v.picklist(['connect', 'request', 'disconnect']),@@ -25,7 +25,7 @@ export function recordMCPConnectionFailure(input: v.InferOutput<typeof mcpFailurlevel: 'error',name: 'mcp.connection.failed',attributes: parsed.output- } satisfies Omit<DiagnosticEvent, 'id' | 'timestamp'>)+ } satisfies DiagnosticEventInput)}export function recordACPTransportFailure(input: v.InferOutput<typeof acpFailureSchema>): void {@@ -36,5 +36,5 @@ export function recordACPTransportFailure(input: v.InferOutput<typeof acpFailurelevel: 'error',name: 'acp.transport.failed',attributes: parsed.output- } satisfies Omit<DiagnosticEvent, 'id' | 'timestamp'>)+ } satisfies DiagnosticEventInput)}diff --git a/src/app/diagnostics/index.ts b/src/app/diagnostics/index.tsindex 3ec3c7a23..448ae2910 100644--- a/src/app/diagnostics/index.ts+++ b/src/app/diagnostics/index.ts@@ -7,10 +7,11 @@ export {recordModelStepCompleted,preparationDurationBucket,recordPreparationOutcome,+ recordRuntimeError,recordStorageFailure,storageOperationForJob} from './events'-export { describeDiagnosticError } from './error'+export { describeDiagnosticError, diagnosticErrorDetails } from './error'export { summarizeDiagnosticEvent } from './summary'export type { DiagnosticEventSummary } from './summary'export { diagnostics } from './recorder'diff --git a/src/app/diagnostics/recorder.ts b/src/app/diagnostics/recorder.tsindex 5bc0a3675..2b3854e49 100644--- a/src/app/diagnostics/recorder.ts+++ b/src/app/diagnostics/recorder.ts@@ -74,8 +74,9 @@ export const diagnostics = {await pendingWritesreturn store === memoryStore ? memoryStore.list() : getStore().list()},- async export(): Promise<string> {- return JSON.stringify(await this.list(), null, 2)+ /** The stored events, after `environment`, the context a report needs to reproduce them. */+ async export(environment: Record<string, unknown> = {}): Promise<string> {+ return JSON.stringify({ environment, events: await this.list() }, null, 2)},async prune(retention: DiagnosticsRetention): Promise<void> {memoryEvents = memoryEvents.slice(-retention)diff --git a/src/app/diagnostics/scrub.ts b/src/app/diagnostics/scrub.tsnew file mode 100644index 000000000..e7670f6ba--- /dev/null+++ b/src/app/diagnostics/scrub.ts@@ -0,0 +1,87 @@+/** A pattern and what replaces each match, applied with `String.replace`. */+type ScrubRule = readonly [pattern: RegExp, replacement: string | ((match: string) => string)]++export const REDACTED = '[redacted]'++/** Queries, fragments, and inline credentials, which carry keys, tokens, and document names. */+const URL_RULES: ScrubRule[] = [+ [/\b((?:https?|tauri|file):\/\/[^\s?#'")]*)[?#][^\s'")]*/g, '$1'],+ // A query on a bare path or file name, such as `/Designs/app.fig?token=…`. It needs a+ // `name=` after the `?`, so optional chaining such as `a.b?.c` in a message stays.+ [/([^\s?'"(]*[/.][^\s?#'")]*)\?[\w.~%-]+=[^\s'")]*/g, '$1'],+ [/(\/\/)[^/\s:@]+:[^/\s@]+@/g, `$1${REDACTED}@`]+]++/** A path segment that reads as a key: very long, or long and mixing cases and digits. */+function looksLikeToken(segment: string): boolean {+ if (segment.length >= 40) return true+ return (+ segment.length >= 16 && /\d/.test(segment) && /[a-z]/.test(segment) && /[A-Z]/.test(segment)+ )+}++/** A long run is a key or encoded content, unless it is a path such as a stack frame's. */+function redactLongRun(run: string): string {+ if (!run.includes('/')) return REDACTED+ return run+ .split('/')+ .map((segment) => (looksLikeToken(segment) ? REDACTED : segment))+ .join('/')+}++/**+ * Credentials the shape rules below miss, after gitleaks (MIT, https://github.com/gitleaks/gitleaks):+ * AWS access key IDs are too short for the long-run rule, and a JWT's dots split it into runs+ * while its payload can name the user.+ */+const CREDENTIAL_RULES: ScrubRule[] = [+ [+ /-----BEGIN[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----[\s\S]*?-----END[ A-Z0-9_-]{0,100}PRIVATE KEY(?: BLOCK)?-----/g,+ REDACTED+ ],+ [/\beyJ[\w-]{10,}\.eyJ[\w-]{10,}\.[\w-]{10,}/g, REDACTED],+ [/\b(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z2-7]{16}\b/g, REDACTED],+ // An `Authorization` header value in any scheme; a bearer token anywhere.+ [/(\bAuthorization["']?\s*[:=]\s*["']?(?:Basic|Bearer|Token)?\s*)[^\s"',]+/gi, `$1${REDACTED}`],+ [/\bBearer\s+(?!\[redacted\])\S+/gi, `Bearer ${REDACTED}`],+ // Assignments such as `api_key=…` or `password: …`. A bare `key` or `token` counts only+ // with `=`, since messages such as `Missing key: fills` name code, not secrets.+ [+ /\b((?:api[_-]?key|(?:access|refresh)[_-]?token|(?:client[_-]?)?secret|passw(?:or)?d)\s*[=:]\s*)["']?[^\s&,"']+["']?/gi,+ `$1${REDACTED}`+ ],+ [/\b((?:key|token)\s*=\s*)["']?[^\s&,"']+["']?/gi, `$1${REDACTED}`],+ // Prefixed keys such as `sk-ant-…`, `sk-proj-…`, `sk_live_…`, and `rk_live_…`.+ [/\b(?:sk|pk|rk|key|token|secret)[-_][\w-]{8,}/gi, REDACTED],+ [/[A-Za-z0-9+/_-]{40,}={0,2}/g, redactLongRun]+]++/**+ * Details that identify a person. A domain needs a letter TLD, so `[email protected]` stays. A home+ * folder name may contain spaces when a path continues after it, as in `/Users/Jane Doe/app`.+ */+const PERSONAL_RULES: ScrubRule[] = [+ [/[\w.+-]+@[\w-]+(?:\.[\w-]+)*\.[A-Za-z]{2,}\b/g, REDACTED],+ [/(\/(?:Users|home)\/)[\w .-]{1,64}?(?=\/)/g, '$1~'],+ [/(\/(?:Users|home)\/)[^/\s]+/g, '$1~'],+ [/([A-Za-z]:\\Users\\)[\w .-]{1,64}?(?=\\)/g, '$1~'],+ [/([A-Za-z]:\\Users\\)[^\\\s]+/g, '$1~']+]++// URL rules run first, so that `user:pass@host` is not left half-redacted as an email.+const RULES: readonly ScrubRule[] = [...URL_RULES, ...CREDENTIAL_RULES, ...PERSONAL_RULES]++function applyRule(text: string, [pattern, replacement]: ScrubRule): string {+ return typeof replacement === 'string'+ ? text.replace(pattern, replacement)+ : text.replace(pattern, replacement)+}++/**+ * Remove what could unlock an account or identify a person from an error message or stack+ * before it is stored: URL queries and credentials, keys and tokens, emails, and the user's+ * name in home folder paths.+ */+export function scrubDiagnosticText(text: string): string {+ return RULES.reduce(applyRule, text)+}diff --git a/src/app/diagnostics/settings/recent.ts b/src/app/diagnostics/settings/recent.tsindex 02961e4bf..f2e3014c1 100644--- a/src/app/diagnostics/settings/recent.ts+++ b/src/app/diagnostics/settings/recent.ts@@ -1,23 +1,61 @@import { tryOnScopeDispose } from '@vueuse/core'-import { ref } from 'vue'+import { computed, ref, shallowRef, watch } from 'vue'-import { diagnostics, type DiagnosticEventSummary } from '@/app/diagnostics'+import {+ diagnostics,+ type DiagnosticCategory,+ type DiagnosticEvent,+ type DiagnosticEventSummary+} from '@/app/diagnostics'+/** Rows shown at first and added by each "Show more". */+export const DIAGNOSTICS_PAGE_SIZE = 20++/** `problems` keeps warnings and errors. */+export type DiagnosticsLevelFilter = 'all' | 'problems'++/**+ * Recently recorded events, newest first, filtered by level and category and shown a page at+ * a time. Only the shown page is summarized, since retention allows thousands of events.+ */export function useRecentDiagnostics(- summarize: (events: Awaited<ReturnType<typeof diagnostics.list>>) => DiagnosticEventSummary[],+ summarize: (event: DiagnosticEvent) => DiagnosticEventSummary,refreshStats: () => Promise<void>) {- const recentEvents = ref<DiagnosticEventSummary[]>([])+ const events = shallowRef<DiagnosticEvent[]>([])+ const level = ref<DiagnosticsLevelFilter>('all')+ const category = ref<DiagnosticCategory | 'all'>('all')+ const limit = ref(DIAGNOSTICS_PAGE_SIZE)let version = 0let disposed = falseasync function refresh() {const request = ++version- const events = await diagnostics.list()- if (!disposed && request === version) recentEvents.value = summarize(events.slice(0, 20))+ const listed = await diagnostics.list()+ if (!disposed && request === version) events.value = listed+ }++ const categories = computed(() => [...new Set(events.value.map((event) => event.category))])+ const matching = computed(() =>+ events.value.filter(+ (event) =>+ (level.value === 'all' || event.level === 'warning' || event.level === 'error') &&+ (category.value === 'all' || event.category === category.value)+ )+ )+ const visible = computed(() => matching.value.slice(0, limit.value).map(summarize))+ const hasMore = computed(() => matching.value.length > limit.value)++ function showMore(): void {+ limit.value += DIAGNOSTICS_PAGE_SIZE}+ // A new filter starts from the first page.+ watch([level, category], () => {+ limit.value = DIAGNOSTICS_PAGE_SIZE+ })+const unsubscribe = diagnostics.subscribe(() => {void refresh()void refreshStats()@@ -28,7 +66,17 @@ export function useRecentDiagnostics(unsubscribe()})+ // Events recorded before the panel opened count too.void refresh()+ void refreshStats()- return { recentEvents }+ return {+ visible,+ total: computed(() => matching.value.length),+ hasMore,+ showMore,+ level,+ category,+ categories+ }}diff --git a/src/app/diagnostics/summary.ts b/src/app/diagnostics/summary.tsindex 48c8d9e01..0cf052e8d 100644--- a/src/app/diagnostics/summary.ts+++ b/src/app/diagnostics/summary.ts@@ -1,31 +1,179 @@-import type { DiagnosticEvent } from './types'+import type { EditorPreparationKind } from '@/app/editor/preparation/types'++import type {+ DiagnosticAttributes,+ DiagnosticEvent,+ DiagnosticEventName,+ DiagnosticValue+} from './types'export type DiagnosticEventSummary = {+ id: stringcategory: stringlabel: string+ /** A short line under the label, such as a duration or an error message. */+ detail: string | nulllevel: DiagnosticEvent['level']timestamp: number+ /** Every recorded field, for the expanded row. */+ fields: [name: string, value: string][]+ stack: string | null+}++/** The diagnostics messages a summary reads; the app's `diagnostics` i18n namespace has them. */+export interface DiagnosticLabels {+ chatCompleted: string+ chatFailed: string+ storageFailed: string+ documentFailed: string+ acpFailed: string+ mcpFailed: string+ modelStep: (values: { model: string }) => string+ modelStepTokens: (values: { input: string; output: string }) => string+ toolCompleted: (values: { tool: string }) => string+ toolFailed: (values: { tool: string }) => string+ durationMs: (values: { ms: number }) => string+ runtimeError: (values: { name: string }) => string+ preparationDocumentOpen: string+ preparationDocumentReload: string+ preparationRecoveryRestore: string+ preparationStorageOpen: string+ preparationPageSwitch: string+ preparationFontRetry: string+ preparationDomImport: string+ preparationDemoLoad: string+ preparationCompleted: (values: { duration: string }) => string+ preparationCancelled: (values: { reason: string; duration: string }) => string+ preparationFailed: (values: { code: string; duration: string }) => string+}++function text(value: DiagnosticValue | undefined): string | null {+ return value === undefined || value === null || value === '' ? null : String(value)+}++/** `errorName: message`, or whichever of the two was recorded. */+function errorDetail(attributes: DiagnosticAttributes): string | null {+ const name = text(attributes.errorName)+ const message = text(attributes.message)+ if (name && message) return `${name}: ${message}`+ return message ?? name ?? text(attributes.errorCode)+}++type Description = [label: string, detail: string | null]+type Describe = (attributes: DiagnosticAttributes, labels: DiagnosticLabels) => Description++const PREPARATION_LABELS = {+ 'document-open': 'preparationDocumentOpen',+ 'document-reload': 'preparationDocumentReload',+ 'recovery-restore': 'preparationRecoveryRestore',+ 'storage-open': 'preparationStorageOpen',+ 'page-switch': 'preparationPageSwitch',+ 'font-retry': 'preparationFontRetry',+ 'dom-import': 'preparationDomImport',+ 'demo-load': 'preparationDemoLoad'+} as const satisfies Record<EditorPreparationKind, keyof DiagnosticLabels>++/** Preparation records a duration bucket rather than the exact time. */+const DURATION_BUCKETS: Record<string, string> = {+ 'under-100ms': '< 100 ms',+ '100ms-1s': '0.1–1 s',+ '1s-5s': '1–5 s',+ '5s-30s': '5–30 s',+ 'over-30s': '> 30 s'+}++function isPreparationKind(kind: string): kind is EditorPreparationKind {+ return Object.hasOwn(PREPARATION_LABELS, kind)+}++function preparationOutcome(attributes: DiagnosticAttributes, labels: DiagnosticLabels): string {+ const bucket = text(attributes.durationBucket)+ const duration = (bucket && DURATION_BUCKETS[bucket]) ?? bucket ?? '?'+ switch (attributes.outcome) {+ case 'failed':+ return labels.preparationFailed({ code: text(attributes.failureCode) ?? '?', duration })+ case 'cancelled':+ return labels.preparationCancelled({+ reason: text(attributes.cancellationReason) ?? '?',+ duration+ })+ default:+ return labels.preparationCompleted({ duration })+ }+}++const describePreparation: Describe = (attributes, labels) => {+ const kind = text(attributes.kind) ?? '?'+ const label = isPreparationKind(kind) ? labels[PREPARATION_LABELS[kind]] : kind+ return [label, preparationOutcome(attributes, labels)]+}++/** Typed by event name, so a newly recorded event cannot reach Settings without a label. */+const DESCRIBE: Record<DiagnosticEventName, Describe> = {+ 'model.step.completed': (attributes, labels) => [+ labels.modelStep({ model: text(attributes.model) ?? '?' }),+ labels.modelStepTokens({+ input: text(attributes.inputTokens) ?? '?',+ output: text(attributes.outputTokens) ?? '?'+ })+ ],+ 'tool.completed': (attributes, labels) => {+ const tool = text(attributes.tool) ?? '?'+ const label =+ attributes.failed === true ? labels.toolFailed({ tool }) : labels.toolCompleted({ tool })+ const ms = attributes.durationMs+ const duration = typeof ms === 'number' ? labels.durationMs({ ms: Math.round(ms) }) : null+ return [label, text(attributes.message) ? errorDetail(attributes) : duration]+ },+ 'chat.completed': (attributes, labels) => [labels.chatCompleted, text(attributes.finishReason)],+ 'chat.failed': (attributes, labels) => [labels.chatFailed, errorDetail(attributes)],+ 'runtime.error': (attributes, labels) => [+ labels.runtimeError({ name: text(attributes.errorName) ?? 'Error' }),+ text(attributes.message)+ ],+ 'editor.preparation.finished': describePreparation,+ 'storage.operation.failed': (attributes, labels) => [+ labels.storageFailed,+ errorDetail(attributes)+ ],+ 'document.operation.failed': (attributes, labels) => [+ labels.documentFailed,+ errorDetail(attributes)+ ],+ 'acp.transport.failed': (attributes, labels) => [labels.acpFailed, errorDetail(attributes)],+ 'mcp.connection.failed': (attributes, labels) => [labels.mcpFailed, errorDetail(attributes)]+}++function isRecordedEventName(name: string): name is DiagnosticEventName {+ return Object.hasOwn(DESCRIBE, name)}-const labelKeys: Record<string, string> = {- 'model.step.completed': 'diagnosticsModelStepCompleted',- 'chat.completed': 'diagnosticsChatCompleted',- 'chat.failed': 'diagnosticsChatFailed',- 'storage.operation.failed': 'diagnosticsStorageFailed',- 'document.operation.failed': 'diagnosticsDocumentFailed',- 'acp.transport.failed': 'diagnosticsACPFailed',- 'mcp.connection.failed': 'diagnosticsMCPFailed'+function describe(event: DiagnosticEvent, labels: DiagnosticLabels): Description {+ // Events stored by an older version may have a name this one no longer records.+ if (!isRecordedEventName(event.name)) return [event.name, null]+ return DESCRIBE[event.name](event.attributes, labels)}export function summarizeDiagnosticEvent(event: DiagnosticEvent,- labels: Partial<Record<string, unknown>>+ labels: DiagnosticLabels): DiagnosticEventSummary {- const labelKey = labelKeys[event.name]- const localizedLabel = labelKey ? labels[labelKey] : undefined- const fallback = labels.diagnosticsTechnicalEvent- let label = 'Technical event'- if (typeof fallback === 'string') label = fallback- if (typeof localizedLabel === 'string') label = localizedLabel- return { category: event.category, label, level: event.level, timestamp: event.timestamp }+ const [label, detail] = describe(event, labels)+ const { stack, ...rest } = event.attributes+ const fields = Object.entries(rest).flatMap(([name, value]): [string, string][] => {+ const shown = text(value)+ return shown === null ? [] : [[name, shown]]+ })+ if (event.durationMs !== undefined) fields.push(['durationMs', String(event.durationMs)])+ if (event.runId) fields.push(['runId', event.runId])+ return {+ id: event.id,+ category: event.category,+ label,+ detail,+ level: event.level,+ timestamp: event.timestamp,+ fields,+ stack: text(stack)+ }}diff --git a/src/app/diagnostics/types.ts b/src/app/diagnostics/types.tsindex 54ca02af7..f6579cf49 100644--- a/src/app/diagnostics/types.ts+++ b/src/app/diagnostics/types.ts@@ -15,11 +15,25 @@ export type DiagnosticLevel = 'debug' | 'info' | 'warning' | 'error'export type DiagnosticValue = string | number | boolean | nullexport type DiagnosticAttributes = Readonly<Record<string, DiagnosticValue>>+/** Every event the app records; Settings needs a label for each (`summary.ts`). */+export type DiagnosticEventName =+ | 'model.step.completed'+ | 'chat.completed'+ | 'chat.failed'+ | 'tool.completed'+ | 'runtime.error'+ | 'editor.preparation.finished'+ | 'document.operation.failed'+ | 'storage.operation.failed'+ | 'mcp.connection.failed'+ | 'acp.transport.failed'+export type DiagnosticEvent = {id: stringtimestamp: numbercategory: DiagnosticCategorylevel: DiagnosticLevel+ /** A `DiagnosticEventName`, or an older name read back from storage. */name: stringsessionId?: stringrunId?: string@@ -27,7 +41,8 @@ export type DiagnosticEvent = {attributes: DiagnosticAttributes}-export type DiagnosticEventInput = Omit<DiagnosticEvent, 'id' | 'timestamp'> & {+export type DiagnosticEventInput = Omit<DiagnosticEvent, 'id' | 'timestamp' | 'name'> & {+ name: DiagnosticEventNametimestamp?: number}diff --git a/src/app/editor/preparation/types.ts b/src/app/editor/preparation/types.tsindex 1cd9a9164..bc479a2f5 100644--- a/src/app/editor/preparation/types.ts+++ b/src/app/editor/preparation/types.ts@@ -1,22 +1,29 @@-export type EditorPreparationKind =- | 'document-open'- | 'document-reload'- | 'recovery-restore'- | 'storage-open'- | 'page-switch'- | 'font-retry'- | 'dom-import'- | 'demo-load'+// Listed as values so diagnostics can validate recorded events against the same set.+export const EDITOR_PREPARATION_KINDS = [+ 'document-open',+ 'document-reload',+ 'recovery-restore',+ 'storage-open',+ 'page-switch',+ 'font-retry',+ 'dom-import',+ 'demo-load'+] as const-export type EditorPreparationPhase =- | 'reading'- | 'decoding'- | 'materializing'- | 'populating-page'- | 'resolving-fonts'- | 'resolving-fallbacks'- | 'layout'- | 'preparing-render'+export type EditorPreparationKind = (typeof EDITOR_PREPARATION_KINDS)[number]++export const EDITOR_PREPARATION_PHASES = [+ 'reading',+ 'decoding',+ 'materializing',+ 'populating-page',+ 'resolving-fonts',+ 'resolving-fallbacks',+ 'layout',+ 'preparing-render'+] as const++export type EditorPreparationPhase = (typeof EDITOR_PREPARATION_PHASES)[number]export interface EditorPreparationProgress {completed: number@@ -48,12 +55,22 @@ export interface EditorPreparationUpdate {unit?: EditorPreparationProgress['unit']}-export type EditorPreparationCancelReason = 'superseded' | 'tab-closed' | 'user'+export const EDITOR_PREPARATION_CANCEL_REASONS = ['superseded', 'tab-closed', 'user'] as const++export type EditorPreparationCancelReason = (typeof EDITOR_PREPARATION_CANCEL_REASONS)[number]++export const EDITOR_PREPARATION_FAILURE_CODES = [+ 'read-failed',+ 'decode-failed',+ 'font-failed',+ 'layout-failed',+ 'render-failed'+] as constexport interface EditorPreparationFailure {id: numberkind: EditorPreparationKind- code: 'read-failed' | 'decode-failed' | 'font-failed' | 'layout-failed' | 'render-failed'+ code: (typeof EDITOR_PREPARATION_FAILURE_CODES)[number]message: stringretryable: boolean}diff --git a/src/app/shell/ui.ts b/src/app/shell/ui.tsindex 1ffc634f4..eca8c78af 100644--- a/src/app/shell/ui.ts+++ b/src/app/shell/ui.ts@@ -1,6 +1,7 @@import { useEventListener } from '@vueuse/core'import { ref } from 'vue'+import { recordRuntimeError } from '@/app/diagnostics'import { isTauri } from '@/app/tauri/env'import type { ToastProgress, ToastVariant } from '@/components/ui/feedback/toast'@@ -131,9 +132,11 @@ function setupGlobalErrorHandler() {errorHandlersInitialized = trueuseEventListener(window, 'error', (e) => {+ recordRuntimeError(e.error ?? e.message, 'window')error(e.message || 'An unexpected error occurred')})useEventListener(window, 'unhandledrejection', (e) => {+ recordRuntimeError(e.reason, 'rejection')const msg = e.reason instanceof Error ? e.reason.message : String(e.reason)error(msg || 'An unexpected error occurred')})diff --git a/src/boot.ts b/src/boot.tsindex a2f7ace20..4e399c6a0 100644--- a/src/boot.ts+++ b/src/boot.ts@@ -4,6 +4,7 @@ import { createApp, nextTick } from 'vue'import { createRetainedScopePlugin } from '@open-pencil/vue'import './app.css'+import { recordRuntimeError } from '@/app/diagnostics'import { preloadFonts } from '@/app/editor/fonts'import { observeBootErrors } from '@/app/shell/support/boot'import { reportBootFailure } from '@/app/shell/support/gate'@@ -31,6 +32,11 @@ export async function boot(): Promise<void> {await reportBootFailure(failure.error)return}+ // Component errors after boot reach only this handler, not the window; keep them diagnosable.+ app.config.errorHandler = (error, _instance, info) => {+ recordRuntimeError(error, 'vue', info)+ console.error(error)+ }if (!IS_TAURI) {void import('virtual:pwa-register').then(({ registerSW }) => {diff --git a/src/components/settings/diagnostics/DiagnosticsEventList.vue b/src/components/settings/diagnostics/DiagnosticsEventList.vuenew file mode 100644index 000000000..a414dfe04--- /dev/null+++ b/src/components/settings/diagnostics/DiagnosticsEventList.vue@@ -0,0 +1,123 @@+<script setup lang="ts">+import { CollapsibleContent, CollapsibleRoot, CollapsibleTrigger } from 'reka-ui'+import { computed } from 'vue'++import { useI18n } from '@open-pencil/vue'++import { summarizeDiagnosticEvent, type DiagnosticCategory } from '@/app/diagnostics'+import { useRecentDiagnostics } from '@/app/diagnostics/settings/recent'+import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppSelect from '@/components/ui/select/AppSelect.vue'+import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'+import { collapsibleContentMotion } from '@/theme/collapsible/collapsible'++const { refreshStats } = defineProps<{ refreshStats: () => Promise<void> }>()+const { diagnostics: messages } = useI18n()++const { visible, total, hasMore, showMore, level, category, categories } = useRecentDiagnostics(+ (event) => summarizeDiagnosticEvent(event, messages.value),+ refreshStats+)++const levelOptions = computed(() => [+ { value: 'all', label: messages.value.filterAll },+ { value: 'problems', label: messages.value.filterProblems }+])+const levelModel = computed({+ get: () => level.value,+ set: (value: string) => {+ level.value = value === 'problems' ? 'problems' : 'all'+ }+})++const CATEGORY_LABELS: Record<DiagnosticCategory, keyof typeof messages.value> = {+ ai: 'categoryAI',+ document: 'categoryDocument',+ renderer: 'categoryRenderer',+ storage: 'categoryStorage',+ sync: 'categorySync',+ mcp: 'categoryMCP',+ recovery: 'categoryRecovery',+ performance: 'categoryPerformance',+ runtime: 'categoryRuntime'+}++function categoryLabel(name: DiagnosticCategory): string {+ const label = messages.value[CATEGORY_LABELS[name]]+ return typeof label === 'string' ? label : name+}++const categoryOptions = computed(() => [+ { value: 'all' as const, label: messages.value.allCategories },+ ...categories.value.map((name) => ({ value: name, label: categoryLabel(name) }))+])+</script>++<template>+ <div class="space-y-2" data-slot="diagnostics-events">+ <div class="flex flex-wrap items-center justify-between gap-2">+ <SegmentedControl+ v-model="levelModel"+ :options="levelOptions"+ :label="messages.filterLevel"+ size="sm"+ />+ <AppSelect+ v-model="category"+ :options="categoryOptions"+ :label="messages.filterCategory"+ :ui="{ trigger: 'w-40' }"+ />+ </div>+ <SettingsGroup v-if="visible.length">+ <CollapsibleRoot v-for="event in visible" :key="event.id" data-slot="diagnostics-event">+ <CollapsibleTrigger+ class="flex w-full cursor-pointer items-center justify-between gap-3 px-3 py-2 text-left text-[11px] hover:bg-hover"+ >+ <span class="flex min-w-0 items-center gap-2">+ <icon-lucide-circle-alert+ v-if="event.level === 'error'"+ class="size-3.5 shrink-0 text-error"+ />+ <icon-lucide-triangle-alert+ v-else-if="event.level === 'warning'"+ class="size-3.5 shrink-0 text-warning"+ />+ <icon-lucide-info v-else class="size-3.5 shrink-0 text-muted" />+ <span class="min-w-0">+ <span class="block truncate text-surface">{{ event.label }}</span>+ <span v-if="event.detail" class="block truncate text-[10px] text-muted">{{+ event.detail+ }}</span>+ </span>+ </span>+ <span class="shrink-0 text-muted">{{+ new Date(event.timestamp).toLocaleTimeString()+ }}</span>+ </CollapsibleTrigger>+ <CollapsibleContent :class="collapsibleContentMotion">+ <div class="space-y-1.5 px-3 pb-2.5 pl-8.5 font-mono text-[10px] text-muted">+ <dl class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5">+ <template v-for="[name, value] in event.fields" :key="name">+ <dt>{{ name }}</dt>+ <dd class="min-w-0 break-words text-surface">{{ value }}</dd>+ </template>+ </dl>+ <pre+ v-if="event.stack"+ class="scrollbar-thin max-h-48 overflow-auto rounded border border-border bg-input p-2 whitespace-pre"+ >{{ event.stack }}</pre>+ </div>+ </CollapsibleContent>+ </CollapsibleRoot>+ </SettingsGroup>+ <p v-else class="px-1 text-[11px] text-muted">{{ messages.noMatchingEvents }}</p>+ <div v-if="hasMore" class="flex items-center justify-between text-[11px] text-muted">+ <span>{{ messages.showingEvents({ shown: visible.length, total }) }}</span>+ <AppButton size="xs" color="neutral" variant="ghost" @click="showMore">{{+ messages.showMore+ }}</AppButton>+ </div>+ </div>+</template>diff --git a/src/components/settings/diagnostics/DiagnosticsSettingsPanel.vue b/src/components/settings/diagnostics/DiagnosticsSettingsPanel.vueindex f12169abc..127fbd4a1 100644--- a/src/components/settings/diagnostics/DiagnosticsSettingsPanel.vue+++ b/src/components/settings/diagnostics/DiagnosticsSettingsPanel.vue@@ -3,7 +3,8 @@ import { computed, ref } from 'vue'import { useI18n } from '@open-pencil/vue'-import { diagnostics, summarizeDiagnosticEvent } from '@/app/diagnostics'+import { diagnostics } from '@/app/diagnostics'+import { diagnosticsEnvironment } from '@/app/diagnostics/environment'import {DIAGNOSTICS_RETENTION_MAX,DIAGNOSTICS_RETENTION_MIN,@@ -11,8 +12,8 @@ import {pruneDiagnostics,useDiagnosticsSettings} from '@/app/diagnostics/settings'-import { useRecentDiagnostics } from '@/app/diagnostics/settings/recent'import { toast } from '@/app/shell/ui'+import DiagnosticsEventList from '@/components/settings/diagnostics/DiagnosticsEventList.vue'import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'import SettingsRow from '@/components/settings/layout/SettingsRow.vue'import SettingsSection from '@/components/settings/layout/SettingsSection.vue'@@ -32,10 +33,6 @@ const {diagnosticsRetention,refreshDiagnosticsStats} = useDiagnosticsSettings()-const { recentEvents } = useRecentDiagnostics(- (events) => events.map((event) => summarizeDiagnosticEvent(event, diagnosticMessages.value)),- refreshDiagnosticsStats-)const retentionValue = computed({get: () => diagnosticsRetention.value,@@ -58,7 +55,7 @@ async function clearDiagnostics() {}async function exportDiagnostics() {- const text = await diagnostics.export()+ const text = await diagnostics.export(diagnosticsEnvironment())try {await navigator.clipboard.writeText(text)toast.info(diagnosticMessages.value.copied)@@ -113,25 +110,7 @@ async function exportDiagnostics() {/></SettingsRow></SettingsGroup>- <SettingsGroup v-if="recentEvents.length">- <div- v-for="event in recentEvents"- :key="`${event.timestamp}-${event.label}`"- class="flex items-center justify-between gap-3 px-3 py-2 text-[11px]"- >- <span class="flex min-w-0 items-center gap-2">- <icon-lucide-circle-alert- v-if="event.level === 'error'"- class="size-3.5 shrink-0 text-error"- />- <icon-lucide-info v-else class="size-3.5 shrink-0 text-muted" />- <span class="truncate text-surface">{{ event.label }}</span>- </span>- <span class="shrink-0 text-muted">{{- new Date(event.timestamp).toLocaleTimeString()- }}</span>- </div>- </SettingsGroup>+ <DiagnosticsEventList :refresh-stats="refreshDiagnosticsStats" /><div class="flex items-center justify-between text-[11px] text-muted"><span>{{diagnosticMessages.eventCount({diff --git a/tests/app/diagnostics/error.test.ts b/tests/app/diagnostics/error.test.tsnew file mode 100644index 000000000..ede5cd32c--- /dev/null+++ b/tests/app/diagnostics/error.test.ts@@ -0,0 +1,66 @@+import { describe, expect, test } from 'bun:test'++import { diagnosticErrorDetails } from '@/app/diagnostics/error'++function errorWith(message: string, stack: string, name = 'TypeError'): Error {+ const error = new Error(message)+ error.name = name+ error.stack = stack+ return error+}++describe('diagnostic error details', () => {+ test('keeps a runtime error’s message and stack', () => {+ const error = errorWith(+ 'Attempting to define property on object that is not extensible.',+ 'TypeError: Attempting to define property\n at merge (http://localhost:1420/src/app/ai/chat/stream.ts:12:4)'+ )+ expect(diagnosticErrorDetails(error)).toMatchObject({+ errorName: 'TypeError',+ message: 'Attempting to define property on object that is not extensible.',+ stack: expect.stringContaining('src/app/ai/chat/stream.ts:12:4')+ })+ })++ test('scrubs the message and the stack', () => {+ const error = errorWith(+ 'fetch https://api.example.com/v1/chat?key=abc123 failed',+ ' at load (file:///Users/jane/Projects/app/src/x.ts:1:1)'+ )+ expect(diagnosticErrorDetails(error)).toMatchObject({+ message: 'fetch https://api.example.com/v1/chat failed',+ stack: ' at load (file:///Users/~/Projects/app/src/x.ts:1:1)'+ })+ })++ test('drops the message of an AI SDK error, which can quote the prompt, from its stack too', () => {+ const message = 'Invalid prompt: the user asked for a "secret plan"'+ const error = errorWith(+ message,+ `AI_InvalidPromptError: ${message}\n at standardize (prompt.ts:4:2)`,+ 'AI_InvalidPromptError'+ )+ expect(diagnosticErrorDetails(error)).toMatchObject({+ errorName: 'AI_InvalidPromptError',+ message: null,+ stack: 'AI_InvalidPromptError: [redacted]\n at standardize (prompt.ts:4:2)'+ })+ })++ test('bounds the message and the stack', () => {+ const lines = Array.from({ length: 60 }, (_, i) => ` at frame${i} (app.ts:${i}:1)`)+ const details = diagnosticErrorDetails(+ errorWith('x'.repeat(30) + ' '.repeat(1) + 'y '.repeat(400), lines.join('\n'))+ )+ expect(details.message?.length).toBeLessThanOrEqual(500)+ expect(details.stack?.split('\n')).toHaveLength(25)+ })++ test('describes thrown values that are not errors', () => {+ expect(diagnosticErrorDetails('plain failure')).toMatchObject({+ errorName: 'UnknownError',+ message: 'plain failure',+ stack: null+ })+ })+})diff --git a/tests/app/diagnostics/events/ai.test.ts b/tests/app/diagnostics/events/ai.test.tsnew file mode 100644index 000000000..7e6c82ce7--- /dev/null+++ b/tests/app/diagnostics/events/ai.test.ts@@ -0,0 +1,41 @@+import 'fake-indexeddb/auto'+import { beforeEach, expect, test } from 'bun:test'++import { diagnostics } from '@/app/diagnostics'+import { recordToolCompleted } from '@/app/diagnostics/events/ai'++const run = { tool: 'render', durationMs: 12, mutates: true }++beforeEach(async () => {+ await diagnostics.clear()+})++test('a tool that broke inside the engine is an error with its message and stack', async () => {+ recordToolCompleted({ ...run, failed: true }, {}, new TypeError('stops.map is not a function'))++ const [event] = await diagnostics.list()+ expect(event.level).toBe('error')+ expect(event.attributes).toMatchObject({+ errorName: 'TypeError',+ message: 'stops.map is not a function'+ })+ expect(String(event.attributes.stack)).toContain('TypeError')+})++test('a tool the model called wrongly is a warning without the message', async () => {+ recordToolCompleted({ ...run, failed: true }, {}, new Error('Node "Pricing card" not found'))++ const [event] = await diagnostics.list()+ expect(event.level).toBe('warning')+ expect(event.attributes.errorName).toBe('Error')+ expect(event.attributes.message).toBeUndefined()+ expect(event.attributes.stack).toBeUndefined()+})++test('a tool that succeeded is info', async () => {+ recordToolCompleted({ ...run, failed: false })++ const [event] = await diagnostics.list()+ expect(event.level).toBe('info')+ expect(event.attributes.errorName).toBeUndefined()+})diff --git a/tests/app/diagnostics/events/preparation.test.ts b/tests/app/diagnostics/events/preparation.test.tsnew file mode 100644index 000000000..97a63a521--- /dev/null+++ b/tests/app/diagnostics/events/preparation.test.ts@@ -0,0 +1,26 @@+import 'fake-indexeddb/auto'+import { beforeEach, expect, test } from 'bun:test'++import { diagnostics, recordPreparationOutcome } from '@/app/diagnostics'+import { EDITOR_PREPARATION_KINDS } from '@/app/editor/preparation/types'++beforeEach(async () => {+ await diagnostics.clear()+})++test.each(EDITOR_PREPARATION_KINDS)('records a finished %s preparation', async (kind) => {+ recordPreparationOutcome({+ kind,+ outcome: 'completed',+ cancellationReason: null,+ failureCode: null,+ terminalPhase: 'preparing-render',+ durationMs: 250+ })++ const [event] = await diagnostics.list()+ expect(event).toMatchObject({+ name: 'editor.preparation.finished',+ attributes: { kind, outcome: 'completed', durationBucket: '100ms-1s' }+ })+})diff --git a/tests/app/diagnostics/events/runtime.test.ts b/tests/app/diagnostics/events/runtime.test.tsnew file mode 100644index 000000000..e5d04efec--- /dev/null+++ b/tests/app/diagnostics/events/runtime.test.ts@@ -0,0 +1,50 @@+import 'fake-indexeddb/auto'+import { beforeEach, expect, test } from 'bun:test'++import { diagnostics } from '@/app/diagnostics'+import { recordRuntimeError } from '@/app/diagnostics/events/runtime'++beforeEach(async () => {+ await diagnostics.clear()+})++test('records an uncaught error with its details', async () => {+ const error = new TypeError('Attempting to define property on object that is not extensible.')+ recordRuntimeError(error, 'vue', 'render function')++ const [event] = await diagnostics.list()+ expect(event).toMatchObject({+ category: 'runtime',+ level: 'error',+ name: 'runtime.error',+ attributes: {+ source: 'vue',+ errorName: 'TypeError',+ message: 'Attempting to define property on object that is not extensible.',+ info: 'render function'+ }+ })+ expect(event.attributes.stack).toContain('TypeError')+})++test('records one of a burst of identical errors, and each distinct one', async () => {+ const error = new Error('loop')+ for (let i = 0; i < 5; i++) recordRuntimeError(error, 'window')+ recordRuntimeError(new Error('other'), 'window')++ // Both can share a millisecond, so their stored order is not fixed.+ const messages = (await diagnostics.list()).map((event) => String(event.attributes.message))+ expect(messages.toSorted()).toEqual(['loop', 'other'])+})++test('records an alternating pair of repeating errors once each', async () => {+ const first = new Error('first')+ const second = new Error('second')+ for (let i = 0; i < 4; i++) {+ recordRuntimeError(first, 'window')+ recordRuntimeError(second, 'window')+ }++ const messages = (await diagnostics.list()).map((event) => String(event.attributes.message))+ expect(messages.toSorted()).toEqual(['first', 'second'])+})diff --git a/tests/app/diagnostics/scrub.test.ts b/tests/app/diagnostics/scrub.test.tsnew file mode 100644index 000000000..7ee04715a--- /dev/null+++ b/tests/app/diagnostics/scrub.test.ts@@ -0,0 +1,103 @@+import { describe, expect, test } from 'bun:test'++import { scrubDiagnosticText } from '@/app/diagnostics/scrub'++// Fake credentials are assembled from parts so that no complete key appears in the source,+// which secret scanners would flag.+const fake = {+ aws: ['AKIA', 'QYLPMN5HHHFPZAM2'].join(''),+ github: ['ghp_', 'a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8'].join(''),+ slack: ['xoxb', '1234567890', '0987654321', 'AbCdEfGhIjKlMnOpQrStUvWx'].join('-'),+ openai: ['sk', 'proj', 'Zx9Yw8Vu7Ts6Rq5Po4Nm3Lk2Ji1HgFeDcBa0'].join('-'),+ anthropic: ['sk', 'ant', 'api03', 'A'.repeat(93)].join('-'),+ stripe: ['sk', 'live', '51H8xYzAbCdEfGhIjKlMn'].join('_'),+ jwt: [+ 'eyJhbGciOiJIUzI1NiJ9',+ 'eyJzdWIiOiJqYW5lQGV4YW1wbGUuY29tIn0',+ 'dozjgNryP4J3jVmNHl0w5N'+ ].join('.'),+ privateKey: [pemMarker('BEGIN'), 'MIIEpAIBAAKCAQEA3Tz2mr7SZiAMfQyuvBjM', pemMarker('END')].join(+ '\n'+ )+}++function pemMarker(edge: 'BEGIN' | 'END'): string {+ return ['-----', edge, ' RSA PRIVATE', ' KEY-----'].join('')+}++describe('scrubDiagnosticText', () => {+ test.each(Object.entries(fake))('redacts a %s credential', (_kind, secret) => {+ const scrubbed = scrubDiagnosticText(`Request failed with ${secret} attached`)+ expect(scrubbed).not.toContain(secret)+ expect(scrubbed).toStartWith('Request failed with ')+ expect(scrubbed).toEndWith(' attached')+ })++ test.each([+ [+ 'a URL query and fragment',+ 'fetch https://api.example.com/v1/chat?key=abc123&doc=Secret%20Plan#part failed',+ 'fetch https://api.example.com/v1/chat failed'+ ],+ [+ 'a query on a bare path, keeping ordinary question marks',+ 'Failed to load /Designs/app.fig?token=abc123. Retry? Maybe',+ 'Failed to load /Designs/app.fig Retry? Maybe'+ ],+ [+ 'credentials in a URL',+ 'GET https://admin:[email protected]/x',+ 'GET https://[redacted]@example.com/x'+ ],+ ['a bearer token', 'Authorization: Bearer abc.def', 'Authorization: Bearer [redacted]'],+ [+ 'a Basic authorization value',+ 'Authorization: Basic dXNlcjpwYXNz rejected',+ 'Authorization: Basic [redacted] rejected'+ ],+ [+ 'credential assignments',+ 'api_key=short password: hunter2 key=abc client_secret="xyz"',+ 'api_key=[redacted] password: [redacted] key=[redacted] client_secret=[redacted]'+ ],+ [+ 'a key that contains slashes',+ ['Upload ', 'Zx9Yw8Vu7Ts6Rq5Po4Nm3', '/', 'Lk2Ji1HgFeDcBa0aB3cD4eF5', ' rejected'].join(''),+ 'Upload [redacted]/[redacted] rejected'+ ],+ [+ 'a home folder name with a space',+ 'at /Users/Jane Doe/app/x.ts:1:1 and C:\\Users\\Jane Doe\\app\\y.ts:2:2',+ 'at /Users/~/app/x.ts:1:1 and C:\\Users\\~\\app\\y.ts:2:2'+ ],+ ['an email address', 'No account for [email protected].', 'No account for [redacted].'],+ [+ 'the user name in home folders',+ 'at file:///Users/jane/app/x.ts:1:1 and C:\\Users\\jane\\app\\y.ts:2:2 and /home/jane/z.ts',+ 'at file:///Users/~/app/x.ts:1:1 and C:\\Users\\~\\app\\y.ts:2:2 and /home/~/z.ts'+ ]+ ])('removes %s', (_case, text, scrubbed) => {+ expect(scrubDiagnosticText(text)).toBe(scrubbed)+ })++ test.each([+ "undefined is not an object (evaluating 'node.parent?.children')",+ 'Missing key: fills',+ 'Basic authentication is not supported',+ 'Retry? Maybe later'+ ])('keeps ordinary text: %s', (text) => {+ expect(scrubDiagnosticText(text)).toBe(text)+ })++ test('keeps code locations, package versions, and Safari stack frames', () => {+ const stack = [+ 'TypeError: stops.map is not a function',+ ' at gradient (http://localhost:1420/packages/design-jsx/src/paints.ts:69:20)',+ ' at connect (http://localhost:1420/src/app/ai/models/settings/profile-editor/connection.ts:12:3)',+ ' at render (http://localhost:1420/src/components/libraries/review/LibraryComparisonPreview.vue:40:7)',+ ' at node_modules/.bun/[email protected]/node_modules/vue/dist/vue.js:12:3',+ 'merge@http://localhost:1420/src/app/ai/chat/stream.ts:12:4'+ ].join('\n')+ expect(scrubDiagnosticText(stack)).toBe(stack)+ })+})diff --git a/tests/app/diagnostics/summary.test.ts b/tests/app/diagnostics/summary.test.tsnew file mode 100644index 000000000..50c26527b--- /dev/null+++ b/tests/app/diagnostics/summary.test.ts@@ -0,0 +1,132 @@+import { describe, expect, test } from 'bun:test'++import { diagnosticsMessages } from '@open-pencil/vue'++import { summarizeDiagnosticEvent } from '@/app/diagnostics'+import type { DiagnosticEvent } from '@/app/diagnostics/types'++function event(fields: Partial<DiagnosticEvent>): DiagnosticEvent {+ return {+ id: 'event',+ timestamp: 0,+ category: 'ai',+ level: 'info',+ name: 'chat.completed',+ attributes: {},+ ...fields+ }+}++const summarize = (fields: Partial<DiagnosticEvent>) =>+ summarizeDiagnosticEvent(event(fields), diagnosticsMessages.get())++describe('diagnostic event summaries', () => {+ test.each([+ [+ {+ name: 'tool.completed',+ attributes: { tool: 'render', durationMs: 161.6, mutates: true, failed: false }+ },+ 'Tool: render',+ '162 ms'+ ],+ [+ {+ name: 'tool.completed',+ attributes: { tool: 'eval', durationMs: 3, mutates: true, failed: true }+ },+ 'Tool failed: eval',+ '3 ms'+ ],+ [+ {+ name: 'tool.completed',+ level: 'error' as const,+ attributes: {+ tool: 'render',+ durationMs: 3,+ mutates: true,+ failed: true,+ errorName: 'TypeError',+ message: 'stops.map is not a function'+ }+ },+ 'Tool failed: render',+ 'TypeError: stops.map is not a function'+ ],+ [+ {+ name: 'model.step.completed',+ attributes: { model: 'claude', inputTokens: 120, outputTokens: 30 }+ },+ 'Model step · claude',+ '120 in · 30 out tokens'+ ],+ [+ {+ name: 'chat.failed',+ level: 'error' as const,+ attributes: { errorName: 'TypeError', message: 'not extensible' }+ },+ 'AI chat failed',+ 'TypeError: not extensible'+ ],+ [+ {+ name: 'runtime.error',+ category: 'runtime' as const,+ level: 'error' as const,+ attributes: { errorName: 'TypeError', message: 'boom' }+ },+ 'Error: TypeError',+ 'boom'+ ],+ [+ {+ name: 'editor.preparation.finished',+ category: 'document' as const,+ attributes: { kind: 'page-switch', outcome: 'completed', durationBucket: '100ms-1s' }+ },+ 'Switch page',+ 'Completed · 0.1–1 s'+ ],+ [+ {+ name: 'editor.preparation.finished',+ category: 'document' as const,+ level: 'error' as const,+ attributes: {+ kind: 'document-open',+ outcome: 'failed',+ failureCode: 'decode-failed',+ durationBucket: 'over-30s'+ }+ },+ 'Open document',+ 'Failed: decode-failed · > 30 s'+ ],+ // An event an older version recorded keeps its own name.+ [{ name: 'preparation.outcome', attributes: {} }, 'preparation.outcome', null]+ ])('%#: %o', (fields, label, detail) => {+ expect(summarize(fields)).toMatchObject({ label, detail })+ })++ test('lists the recorded fields and keeps the stack apart', () => {+ const summary = summarize({+ name: 'runtime.error',+ runId: 'run-1',+ attributes: {+ errorName: 'TypeError',+ message: 'boom',+ stack: 'TypeError: boom\n at x',+ info: null+ }+ })+ expect(summary.fields).toEqual([+ ['errorName', 'TypeError'],+ ['message', 'boom'],+ ['runId', 'run-1']+ ])+ expect(summary.stack).toBe('TypeError: boom\n at x')+ })+})diff --git a/tests/e2e/chat/streaming/reply.webkit.spec.ts b/tests/e2e/chat/streaming/reply.webkit.spec.tsnew file mode 100644index 000000000..0c0569757--- /dev/null+++ b/tests/e2e/chat/streaming/reply.webkit.spec.ts@@ -0,0 +1,16 @@+import { CanvasHelper } from '#tests/helpers/canvas'+import { test, expect } from '#tests/helpers/chat/fixture'+import { finishReasoning, installReasoningTransport } from '#tests/helpers/chat/reasoning'++test('streams reasoning and a reply in WebKit without page errors', async ({+ configuredChat: chat,+ page+}) => {+ const canvas = new CanvasHelper(page)+ await installReasoningTransport(page)+ await chat.submit('Inspect the layout')+ await expect(page.locator('[data-slot="chat-reasoning-trigger"]').last()).toBeVisible()+ await finishReasoning(page)+ await expect(chat.assistantMessage()).toContainText('Finished inspecting')+ canvas.assertNoErrors()+})diff --git a/tests/e2e/settings/diagnostics.spec.ts b/tests/e2e/settings/diagnostics.spec.tsindex c872aba46..1d2462271 100644--- a/tests/e2e/settings/diagnostics.spec.ts+++ b/tests/e2e/settings/diagnostics.spec.ts@@ -1,10 +1,26 @@import type { Page } from '@playwright/test'--import type { DiagnosticEvent } from '@/app/diagnostics/types'+import * as v from 'valibot'import { CanvasHelper } from '#tests/helpers/canvas'import { expect, test } from '#tests/helpers/chat/fixture'+/** The JSON that Copy diagnostics puts on the clipboard, as far as these tests read it. */+const ReportJSON = v.pipe(+ v.string(),+ v.parseJson(),+ v.object({+ environment: v.object({ app: v.string(), shell: v.string() }),+ events: v.array(+ v.object({+ name: v.string(),+ sessionId: v.optional(v.string()),+ runId: v.optional(v.string()),+ attributes: v.record(v.string(), v.unknown())+ })+ )+ })+)+test('Settings exports correlated chat telemetry without conversation content', async ({configuredChat: chat,page,@@ -21,7 +37,8 @@ test('Settings exports correlated chat telemetry without conversation content',await page.getByRole('button', { name: 'Copy diagnostics', exact: true }).click()await expect(page.getByText('Diagnostics copied to clipboard.', { exact: true })).toBeVisible()const text = await page.evaluate(() => navigator.clipboard.readText())- const events: DiagnosticEvent[] = JSON.parse(text)+ const { environment, events } = v.parse(ReportJSON, text)+ expect(environment).toMatchObject({ app: expect.any(String), shell: 'browser' })const completed = events.filter((event) => event.name === 'chat.completed')expect(completed).toHaveLength(2)expect(completed[0].sessionId).toEqual(expect.any(String))@@ -82,3 +99,43 @@ test('diagnostics retention offers presets and accepts a bounded custom value',await expect(retention).toHaveText('1000')await expect(row.getByRole('spinbutton')).toHaveCount(0)})++test('uncaught errors are listed with their stack and can be filtered and copied', async ({+ configuredChat: chat,+ page,+ context+}) => {+ await context.grantPermissions(['clipboard-read', 'clipboard-write'])+ await chat.submit('A request that records info events')+ await expect(chat.assistantMessage()).toBeVisible()+ await page.evaluate(() => {+ setTimeout(() => {+ throw new TypeError('Attempting to define property on object that is not extensible.')+ })+ })+ await openDiagnostics(page)++ const events = page.locator('[data-slot="diagnostics-events"]')+ const failure = events.getByRole('button', { name: /Error: TypeError/ })+ await expect(failure).toContainText(+ 'Attempting to define property on object that is not extensible.'+ )+ await failure.click()+ await expect(events.locator('pre')).toContainText('TypeError')+ // Events recorded before Settings opened are counted.+ await expect(page.getByText(/^[1-9]\d* events · /)).toBeVisible()++ // Info events such as the completed chat drop out when only problems are shown.+ await expect(events.getByRole('button', { name: /AI chat completed/ })).toBeVisible()+ await events.getByRole('button', { name: 'Errors and warnings' }).click()+ await expect(events.getByRole('button', { name: /AI chat completed/ })).toHaveCount(0)+ await expect(failure).toBeVisible()++ await page.getByRole('button', { name: 'Copy diagnostics', exact: true }).click()+ // The clipboard outlives the test's page, so read it only once this copy has finished.+ await expect(page.getByText('Diagnostics copied to clipboard.', { exact: true })).toBeVisible()+ const report = v.parse(ReportJSON, await page.evaluate(() => navigator.clipboard.readText()))+ const runtime = report.events.find((event) => event.name === 'runtime.error')+ expect(runtime?.attributes).toMatchObject({ source: 'window', errorName: 'TypeError' })+ expect(String(runtime?.attributes.stack)).toContain('TypeError')+})diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex 084a0f2d2..c7d3d8701 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -83,7 +83,7 @@ ja:diagnostics.chatFailedja:diagnostics.descriptionja:diagnostics.eventCountja:diagnostics.mcpFailed-ja:diagnostics.modelStepCompleted+ja:diagnostics.preparationDomImportja:diagnostics.usageDescriptionja:diagnostics.usageHistoryDescriptionja:editor.showUI@@ -227,7 +227,7 @@ zh-cn:diagnostics.chatFailedzh-cn:diagnostics.descriptionzh-cn:diagnostics.eventCountzh-cn:diagnostics.mcpFailed-zh-cn:diagnostics.modelStepCompleted+zh-cn:diagnostics.preparationDomImportzh-cn:diagnostics.usageDescriptionzh-cn:diagnostics.usageHistoryDescriptionzh-cn:files.browserFileAPINotSupporteddiff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txtindex 93daa39d7..7ceba100e 100644--- a/tools/checks/i18n/translation-baseline.txt+++ b/tools/checks/i18n/translation-baseline.txt@@ -1,11 +1,11 @@de:ai.chatSettingsde:ai.completions-de:ai.thinkingMinimalde:ai.modelAgentConnectionde:ai.modelCapabilityVisionShortde:ai.modelNamede:ai.modelRoleVisionde:ai.responses+de:ai.thinkingMinimalde:automation.mcpFailureDetailsde:automation.portde:automation.status@@ -15,6 +15,9 @@ de:code.sourceDesignJSXde:code.sourceHTMLCSSde:code.sourceTailwindJSXde:common.ok+de:diagnostics.categoryMCP+de:diagnostics.categoryRenderer+de:diagnostics.durationMsde:menu.textde:panels.alphade:panels.blendModeNormal@@ -63,6 +66,9 @@ es:code.sourceDesignJSXes:code.sourceHTMLCSSes:code.sourceTailwindJSXes:common.tokens+es:diagnostics.categoryMCP+es:diagnostics.durationMs+es:diagnostics.runtimeErrores:panels.autoes:panels.blendModeColores:panels.blendModeNormal@@ -86,11 +92,11 @@ es:storage.providerBackblazees:storage.providerR2es:variableTypes.colorfr:ai.completions-fr:ai.thinkingMinimalfr:ai.modelAgentConnectionfr:ai.modelCapabilityVisionShortfr:ai.modelRoleVisionfr:ai.responses+fr:ai.thinkingMinimalfr:automation.portfr:automation.versionfr:code.editorDesignLabel@@ -98,6 +104,9 @@ fr:code.sourceDesignJSXfr:code.sourceHTMLCSSfr:code.sourceTailwindJSXfr:common.ok+fr:diagnostics.categoryDocument+fr:diagnostics.categoryMCP+fr:diagnostics.durationMsfr:designCheck.scopeDocumentfr:designCheck.scopePagefr:designCheck.suggestions@@ -157,6 +166,10 @@ it:code.sourceDesignJSXit:code.sourceHTMLCSSit:code.sourceTailwindJSXit:common.ok+it:diagnostics.categoryMCP+it:diagnostics.categoryRenderer+it:diagnostics.categoryRuntime+it:diagnostics.durationMsit:menu.fileit:panels.aiit:panels.auto@@ -182,6 +195,9 @@ ja:code.editorDesignLabelja:code.sourceDesignJSXja:code.sourceHTMLCSSja:code.sourceTailwindJSX+ja:diagnostics.categoryAI+ja:diagnostics.categoryMCP+ja:diagnostics.durationMsja:panels.aija:panels.colorFormatHsbja:panels.colorFormatHsl@@ -202,6 +218,10 @@ pl:code.sourceDesignJSXpl:code.sourceHTMLCSSpl:code.sourceTailwindJSXpl:common.ok+pl:diagnostics.categoryAI+pl:diagnostics.categoryMCP+pl:diagnostics.categoryRenderer+pl:diagnostics.durationMspl:panels.aipl:panels.autopl:panels.chroma@@ -225,6 +245,7 @@ ru:code.editorDesignLabelru:code.sourceDesignJSXru:code.sourceHTMLCSSru:code.sourceTailwindJSX+ru:diagnostics.categoryMCPru:panels.airu:panels.colorFormatHsbru:panels.colorFormatHsl@@ -241,6 +262,8 @@ zh-cn:code.editorDesignLabelzh-cn:code.sourceDesignJSXzh-cn:code.sourceHTMLCSSzh-cn:code.sourceTailwindJSX+zh-cn:diagnostics.categoryAI+zh-cn:diagnostics.categoryMCPzh-cn:panels.aizh-cn:panels.colorFormatHsbzh-cn:panels.colorFormatHsl