Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(editor): a diagnostic bundle, assembled from a registry rather than a list

esengine59ea43838eab
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index d1da8d8a5..4caa6935f 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -667,6 +667,28 @@ ipcMain.handle('app:installUpdate', async () => {
return installUpdate();
});
ipcMain.handle('diagnostics:openLogs', () => shell.openPath(logsDir()));
+
+/**
+ * Write a diagnostic bundle the renderer collected. Main picks the file and
+ * writes the text; WHAT goes in it is decided in the renderer, where the registry
+ * and the redaction level are — a second opinion about that, next to the
+ * filesystem, is the last place it should live.
+ */
+ipcMain.handle('diagnostics:saveBundle', async (_e, name: string, text: string) => {
+ if (!win) return { ok: false, error: 'no window' };
+ const res = await showSaveDialog(win, {
+ title: 'Export diagnostics',
+ defaultPath: name,
+ filters: [{ name: 'Estella diagnostics', extensions: ['json'] }],
+ });
+ if (res.canceled || !res.filePath) return { ok: false, canceled: true };
+ try {
+ await writeFile(res.filePath, text, 'utf8');
+ return { ok: true, file: res.filePath };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+});
ipcMain.on('engine:status', (_e, status: string) => console.log('[engine]', status));
// — The MCP endpoint an external agent attaches to (mcpEndpoint.ts) —
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index 10c70630c..390a8143e 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -87,6 +87,9 @@ const api = {
},
/** Open the local diagnostics log folder (main-process errors, crash dumps). */
openLogs: (): Promise<void> => ipcRenderer.invoke('diagnostics:openLogs'),
+ /** Write a bundle the renderer collected; main picks the file, nothing more. */
+ saveBundle: (name: string, text: string): Promise<{ ok: boolean; file?: string; canceled?: boolean; error?: string }> =>
+ ipcRenderer.invoke('diagnostics:saveBundle', name, text),
},
// — The MCP endpoint an external AI agent attaches to. Off unless asked for:
diff --git a/desktop/src/commands/editorCommands.ts b/desktop/src/commands/editorCommands.ts
index d79334a6a..8873ccc2b 100644
--- a/desktop/src/commands/editorCommands.ts
+++ b/desktop/src/commands/editorCommands.ts
@@ -36,6 +36,7 @@ import { confirm } from '@/components/confirm';
import { requestPluginPanelAction } from '@/plugins/panelActions';
import { t } from '@/i18n';
import { checkForUpdatesInteractive } from '@/update/updateToast';
+import { exportDiagnostics } from '@/diagnostics';
import type { ToolMode } from '@/types';
const editor = () => useEditorStore.getState();
@@ -636,6 +637,20 @@ commands.register({
category: t('cat.help'),
run: () => void checkForUpdatesInteractive(),
});
+commands.register({
+ id: 'help.exportDiagnostics',
+ label: t('menu.exportDiagnostics'),
+ category: t('cat.help'),
+ run: () => void exportDiagnostics('safe'),
+});
+// Not on the menu: carrying the project's own names and values out is a thing to
+// reach for deliberately, and the palette is where a deliberate reach lands.
+commands.register({
+ id: 'help.exportDiagnosticsFull',
+ label: t('menu.exportDiagnosticsFull'),
+ category: t('cat.help'),
+ run: () => void exportDiagnostics('full'),
+});
commands.register({
id: 'help.openLogs',
label: t('menu.openLogs'),
diff --git a/desktop/src/diagnostics/bundle.ts b/desktop/src/diagnostics/bundle.ts
new file mode 100644
index 000000000..a51ef8194
--- /dev/null
+++ b/desktop/src/diagnostics/bundle.ts
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file bundle.ts
+ * @brief Collect every registered section into one document.
+ *
+ * @details The exporter knows no section names — it walks the registry. A
+ * section that throws is named in `failedSections` and the rest are
+ * still collected: during an incident a bundle that is mostly present
+ * beats no bundle, and a collector that fails is itself a finding.
+ */
+import { diagnosticsRegistry } from './registry';
+import { resolve, type DetailLevel } from './redact';
+
+/** Bump when the shape changes, so a reader can tell what it is looking at. */
+export const BUNDLE_FORMAT = 1;
+
+export interface DiagnosticBundle {
+ kind: 'estella-diagnostic-bundle';
+ formatVersion: number;
+ createdAt: string;
+ /** Whether the user's own content travels with it — see redact.ts. */
+ detail: DetailLevel;
+ sections: Record<string, unknown>;
+ /** Sections whose collector threw, with the message. Absent facts, not empty ones. */
+ failedSections: Record<string, string>;
+}
+
+export function collectBundle(detail: DetailLevel, nowIso: string): DiagnosticBundle {
+ const sections: Record<string, unknown> = {};
+ const failedSections: Record<string, string> = {};
+ for (const section of diagnosticsRegistry.all()) {
+ try {
+ const raw = section.collect();
+ // Null means "nothing to say", which is not the same as an empty
+ // object and is left out rather than written as one.
+ if (raw !== null && raw !== undefined) sections[section.id] = resolve(raw, detail);
+ } catch (err) {
+ failedSections[section.id] = err instanceof Error ? err.message : String(err);
+ }
+ }
+ return {
+ kind: 'estella-diagnostic-bundle',
+ formatVersion: BUNDLE_FORMAT,
+ createdAt: nowIso,
+ detail,
+ sections,
+ failedSections,
+ };
+}
+
+/** The document, as it is written to disk or pasted into an issue. */
+export function serializeBundle(bundle: DiagnosticBundle): string {
+ return JSON.stringify(bundle, null, 2);
+}
+
+/** `estella-diagnostics-2026-08-08T21-30-00.json` — sorts by time, no colons
+ * (Windows rejects them in a filename). */
+export function bundleFileName(nowIso: string): string {
+ return `estella-diagnostics-${nowIso.replace(/[:.]/g, '-').replace(/Z$/, '')}.json`;
+}
diff --git a/desktop/src/diagnostics/export.ts b/desktop/src/diagnostics/export.ts
new file mode 100644
index 000000000..57927171a
--- /dev/null
+++ b/desktop/src/diagnostics/export.ts
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file export.ts
+ * @brief Collect, show what is about to leave, write it.
+ *
+ * @details The confirmation is not a formality. A bundle is something a studio
+ * hands to strangers, so the one decision that cannot be taken back —
+ * whether the user's own names and values travel with it — is made
+ * per export and in front of a summary, never remembered as a setting.
+ */
+import { collectBundle, serializeBundle, bundleFileName } from './bundle';
+import type { DetailLevel } from './redact';
+import { confirm } from '@/components/confirm';
+import { Toasts } from '@/store/Toasts';
+import { t } from '@/i18n';
+
+/** What the bundle turned out to hold, in one line the user reads before agreeing. */
+function summarize(sections: Record<string, unknown>, failed: Record<string, string>): string {
+ const names = Object.keys(sections);
+ const failedNames = Object.keys(failed);
+ const parts = [t('diag.summary.sections', { count: String(names.length), names: names.join(', ') })];
+ if (failedNames.length > 0) parts.push(t('diag.summary.failed', { names: failedNames.join(', ') }));
+ return parts.join('\n\n');
+}
+
+/**
+ * Export a bundle at the given detail level.
+ *
+ * Collected BEFORE the prompt so the summary describes the real document rather
+ * than a guess about it — and so a section that throws is visible while the user
+ * still has the choice to send it anyway.
+ */
+export async function exportDiagnostics(detail: DetailLevel): Promise<void> {
+ const bundle = collectBundle(detail, new Date().toISOString());
+ const ok = await confirm({
+ title: t(detail === 'full' ? 'diag.confirm.titleFull' : 'diag.confirm.title'),
+ body: `${t(detail === 'full' ? 'diag.confirm.bodyFull' : 'diag.confirm.body')}\n\n${summarize(bundle.sections, bundle.failedSections)}`,
+ confirmLabel: t('diag.confirm.export'),
+ danger: detail === 'full',
+ });
+ if (!ok) return;
+
+ const res = await window.estella?.app?.saveBundle?.(
+ bundleFileName(bundle.createdAt), serializeBundle(bundle));
+ if (!res || res.canceled) return;
+ if (!res.ok) {
+ Toasts.push(t('diag.failed', { error: res.error ?? '' }), 'error');
+ return;
+ }
+ Toasts.push(t('diag.saved'), 'success', 8000, {
+ label: t('diag.reveal'),
+ run: () => void window.estella?.shell?.showItem?.(res.file!),
+ });
+}
diff --git a/desktop/src/diagnostics/index.ts b/desktop/src/diagnostics/index.ts
new file mode 100644
index 000000000..c4fcc9e4d
--- /dev/null
+++ b/desktop/src/diagnostics/index.ts
@@ -0,0 +1,14 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file index.ts — diagnostics barrel. Importing it registers the core
+ * sections (./sections side effect) and exposes the registry a plugin
+ * contributes its own through.
+ */
+import './sections';
+
+export { diagnosticsRegistry, type DiagnosticSection } from './registry';
+export { collectBundle, serializeBundle, bundleFileName, BUNDLE_FORMAT, type DiagnosticBundle } from './bundle';
+export { exportDiagnostics } from './export';
+export { captureBuildStamp, captureAppVersion } from './sections';
+export { personal, resolve, placeholder, stableTag, type DetailLevel, type Personal } from './redact';
diff --git a/desktop/src/diagnostics/redact.ts b/desktop/src/diagnostics/redact.ts
new file mode 100644
index 000000000..b1abe2aa7
--- /dev/null
+++ b/desktop/src/diagnostics/redact.ts
@@ -0,0 +1,99 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file redact.ts
+ * @brief Marking the values in a diagnostic bundle that belong to the user's
+ * project rather than to the failure.
+ *
+ * @details An entity's name and a field's value are BOTH what a report needs to
+ * be reproducible and what a studio must not hand out with it. Asking a
+ * section to collect twice — once real, once scrubbed — makes the two
+ * drift on the first edit, so the marking rides on the VALUE: a section
+ * writes `personal(name)` once and the export decides.
+ *
+ * Placeholders are stable and derived from the value, so one name is the
+ * same placeholder everywhere it appears. Without that, "deleted X then
+ * undid X" and "deleted X then undid Y" read identically in a report,
+ * which is exactly the distinction a sequence exists to make.
+ */
+
+/** A value that identifies the user's project, not the failure. */
+export interface Personal<T = unknown> {
+ readonly __personal: true;
+ readonly value: T;
+ /** What the placeholder is called: `name`, `path`, `text`. */
+ readonly kind: string;
+}
+
+/** How much of the project a bundle carries. */
+export type DetailLevel = 'safe' | 'full';
+
+/**
+ * Mark a value as the user's, with the noun its placeholder should read as.
+ *
+ * The kind is not decoration: `path#3f2a` and `name#3f2a` in a report say which
+ * kind of thing went missing, and that is often the whole diagnosis.
+ */
+export function personal<T>(value: T, kind = 'value'): Personal<T> {
+ return { __personal: true, value, kind };
+}
+
+export function isPersonal(v: unknown): v is Personal {
+ return typeof v === 'object' && v !== null && (v as Personal).__personal === true;
+}
+
+/**
+ * FNV-1a over the value's string form — stable across runs and machines, because
+ * a per-session placeholder would make two reports of one bug incomparable.
+ *
+ * NOT a security boundary: a short hash of a guessed value confirms the guess.
+ * It defeats reading a project off a report, not an attacker checking a candidate.
+ */
+export function stableTag(value: unknown): string {
+ const text = typeof value === 'string' ? value : JSON.stringify(value) ?? String(value);
+ let h = 0x811c9dc5;
+ for (let i = 0; i < text.length; i++) {
+ h ^= text.charCodeAt(i);
+ h = Math.imul(h, 0x01000193) >>> 0;
+ }
+ return h.toString(16).padStart(8, '0').slice(0, 4);
+}
+
+/**
+ * What a personal value reads as when it is not carried: its kind, its stable
+ * tag, and the SHAPE of what was there — a number that was undefined and a
+ * number that was 0 are different bugs, and the shape survives redaction.
+ */
+export function placeholder(p: Personal): string {
+ const v = p.value;
+ const tag = `${p.kind}#${stableTag(v)}`;
+ if (v === null) return `${p.kind}#null`;
+ if (v === undefined) return `${p.kind}#undefined`;
+ if (typeof v === 'string') return `${tag}(len=${v.length})`;
+ if (typeof v === 'number' || typeof v === 'boolean') return `${p.kind}#${typeof v}`;
+ if (Array.isArray(v)) return `${tag}(array,len=${v.length})`;
+ return `${tag}(${typeof v})`;
+}
+
+/**
+ * Resolve every {@link Personal} in a collected tree for the given level. Walks
+ * plain objects and arrays only; anything else is replaced by its type name,
+ * because a bundle is a document and a live object handed to it would serialize
+ * the editor.
+ */
+export function resolve(value: unknown, level: DetailLevel, seen = new WeakSet<object>()): unknown {
+ if (isPersonal(value)) {
+ return level === 'full' ? resolve(value.value, level, seen) : placeholder(value);
+ }
+ if (value === null || typeof value !== 'object') {
+ return typeof value === 'function' ? '[function]' : value;
+ }
+ if (seen.has(value)) return '[circular]';
+ seen.add(value);
+ if (Array.isArray(value)) return value.map((v) => resolve(v, level, seen));
+ const proto = Object.getPrototypeOf(value) as object | null;
+ if (proto !== null && proto !== Object.prototype) return `[${value.constructor?.name ?? 'object'}]`;
+ const out: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(value)) out[k] = resolve(v, level, seen);
+ return out;
+}
diff --git a/desktop/src/diagnostics/registry.ts b/desktop/src/diagnostics/registry.ts
new file mode 100644
index 000000000..b2a23bd3c
--- /dev/null
+++ b/desktop/src/diagnostics/registry.ts
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file registry.ts
+ * @brief Who contributes what to a diagnostic bundle.
+ *
+ * @details The bundle must not be a function that lists its sources — a shape
+ * this repository has already been bitten by twice, most recently a
+ * native host restating a field list and dropping half of it. A
+ * subsystem registers what it can say; the exporter walks the registry.
+ *
+ * On ContributionRegistry like every other extension point, so a section
+ * is owned and retractable, and a plugin contributes through the same
+ * door core uses.
+ */
+import { ContributionRegistry, type Disposable, type Owner } from '@/contrib/ContributionRegistry';
+
+export interface DiagnosticSection {
+ /** Stable key this section appears under in the bundle: `engine`, `gpu`. */
+ id: string;
+ /**
+ * Collect this section, or `null` when there is nothing to say — omitted
+ * rather than written empty, since absent and empty are different facts.
+ * Wrap the user's own content in `personal()`; a throw lands in the bundle's
+ * `failedSections` and the other sections are still collected.
+ */
+ collect(): unknown;
+}
+
+class DiagnosticsRegistry {
+ private readonly sections = new ContributionRegistry<DiagnosticSection>('diagnostic section');
+
+ register(section: DiagnosticSection, owner: Owner = 'core'): Disposable {
+ return this.sections.register(owner, section);
+ }
+
+ all(): DiagnosticSection[] {
+ return [...this.sections.all()];
+ }
+
+ get(id: string): DiagnosticSection | undefined {
+ return this.sections.get(id);
+ }
+
+ disposeOwner(owner: Owner): void {
+ this.sections.disposeOwner(owner);
+ }
+}
+
+export const diagnosticsRegistry = new DiagnosticsRegistry();
diff --git a/desktop/src/diagnostics/sections.ts b/desktop/src/diagnostics/sections.ts
new file mode 100644
index 000000000..62b71e1b6
--- /dev/null
+++ b/desktop/src/diagnostics/sections.ts
@@ -0,0 +1,144 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file sections.ts
+ * @brief What core contributes to a diagnostic bundle. Registered as a side
+ * effect, like the settings and command registrations.
+ *
+ * @details Each section reads ONE existing source rather than restating it. The
+ * engine build stamp comes from the same manifest the boot guard reads,
+ * the counters from the same census the agent's `resource_census` tool
+ * reads, the log from the store the console renders.
+ */
+import { takeCensus } from 'esengine';
+import { diagnosticsRegistry } from './registry';
+import { personal } from './redact';
+import { EngineHost } from '@/engine/EngineHost';
+import { checkEngineBuild } from '@/engine/EngineGuard';
+import { ProjectStore } from '@/project/ProjectStore';
+import { LogStore } from '@/store/LogStore';
+import { settingsRegistry } from '@/settings/registry';
+import { useSettings } from '@/store/settingsStore';
+
+/**
+ * The build stamp, read once at boot and held — the same reason the renderer
+ * captures its identity at init. `checkEngineBuild` is a fetch, and the moment
+ * this answer is wanted is the worst moment to start one.
+ */
+let buildStamp: unknown = null;
+export function captureBuildStamp(): void {
+ void checkEngineBuild().then((guard) => {
+ buildStamp = guard.manifest
+ ? { ...guard.manifest, guard: guard.level, guardMessage: guard.message }
+ : { guard: guard.level, guardMessage: guard.message };
+ }).catch(() => { /* an unreadable manifest is itself reported by the guard */ });
+}
+
+/** Filled once at boot — `getVersion` is async and a crash is a bad time to await. */
+let appVersion: string | null = null;
+export function captureAppVersion(): void {
+ void window.estella?.getVersion?.().then((v: string) => { appVersion = v; }).catch(() => {});
+}
+
+diagnosticsRegistry.register({
+ id: 'editor',
+ collect: () => ({
+ version: appVersion,
+ platform: window.estella?.platform ?? null,
+ locale: navigator.language,
+ userAgent: navigator.userAgent,
+ screen: { w: window.screen?.width ?? 0, h: window.screen?.height ?? 0, dpr: window.devicePixelRatio },
+ uptimeSec: Math.round(performance.now() / 1000),
+ }),
+});
+
+diagnosticsRegistry.register({
+ id: 'engine',
+ collect: () => ({
+ build: buildStamp,
+ backend: EngineHost.activeBackend,
+ colorSpace: EngineHost.activeColorSpace,
+ booted: EngineHost.app !== null,
+ }),
+});
+
+/**
+ * The project, in the shape a reproduction needs: which scene, how big, how dirty.
+ *
+ * Names and paths are the user's, so they travel as placeholders unless the
+ * export is asked for the full thing.
+ */
+diagnosticsRegistry.register({
+ id: 'project',
+ collect: () => {
+ const p = ProjectStore.getSnapshot();
+ if (!p) return null;
+ return {
+ name: personal(p.name, 'project'),
+ currentScene: p.currentScene ? personal(p.currentScene, 'path') : null,
+ prefabEdit: p.prefabEdit ? personal(p.prefabEdit, 'path') : null,
+ defaultScene: p.defaultScene ? personal(p.defaultScene, 'path') : null,
+ };
+ },
+});
+
+/**
+ * The counters, from the census the engine already publishes — including its own
+ * `failedProbes`, because a counter that is ABSENT and one that is zero are
+ * different facts and a bundle that conflated them would be read wrong.
+ */
+diagnosticsRegistry.register({
+ id: 'census',
+ collect: () => {
+ const app = EngineHost.app;
+ if (!app) return null;
+ const c = takeCensus({ app });
+ const counters: Record<string, { value: number; tier: string; unit: string }> = {};
+ for (const [key, e] of c.entries) counters[key] = { value: e.value, tier: e.tier, unit: e.unit };
+ return { atMs: c.atMs, counters, failedProbes: c.failedProbes };
+ },
+});
+
+/**
+ * The tail of the console. Messages are the user's — they interpolate asset
+ * paths and entity names — so the text is personal while the level, source and
+ * ordering are not: "12 errors from the asset loader" survives redaction, which
+ * is most of what a first look needs.
+ */
+const LOG_TAIL = 200;
+
+diagnosticsRegistry.register({
+ id: 'log',
+ collect: () => {
+ const all = LogStore.getSnapshot();
+ const tail = all.slice(-LOG_TAIL);
+ return {
+ total: all.length,
+ shown: tail.length,
+ entries: tail.map((e) => ({
+ level: e.level,
+ time: e.time,
+ source: e.source,
+ message: personal(e.message, 'text'),
+ })),
+ };
+ },
+});
+
+/**
+ * Settings that differ from their default — the ones that can change behaviour,
+ * and a short list rather than the whole page. A value can be anything a project
+ * put there, so values are personal while the ids are not.
+ */
+diagnosticsRegistry.register({
+ id: 'settings',
+ collect: () => {
+ const changed: Record<string, unknown> = {};
+ const store = useSettings.getState();
+ for (const s of settingsRegistry.all()) {
+ if (!store.isChanged(s.id)) continue;
+ changed[s.id] = personal(store.getValue(s.id), 'value');
+ }
+ return Object.keys(changed).length > 0 ? changed : null;
+ },
+});
diff --git a/desktop/src/i18n/messages/logs.ts b/desktop/src/i18n/messages/logs.ts
index 9a5b0d1b3..df3082287 100644
--- a/desktop/src/i18n/messages/logs.ts
+++ b/desktop/src/i18n/messages/logs.ts
@@ -105,4 +105,36 @@ export const logsMessages = defineMessages({
// — Profiler: Systems section —
'prof.thisFrame': { en: 'this frame', zh: '当前帧' },
'prof.noSystemTimings': { en: 'No system timings yet.', zh: '暂无系统耗时数据。' },
+
+ // — Diagnostic bundle (Help ▸ Export Diagnostics) —
+ 'diag.confirm.title': { en: 'Export diagnostics', zh: '导出诊断信息' },
+ 'diag.confirm.body': {
+ en: 'A structured report of what this editor is and what it was doing: build, GPU, '
+ + 'backend, counters and the recent log. Your project\'s names, paths and values '
+ + 'travel as stable placeholders, so the same name reads the same everywhere '
+ + 'without saying what it is. No scenes, scripts or assets are included.',
+ zh: '一份结构化报告:这个编辑器是什么、当时在做什么——构建、GPU、后端、计数器与近期日志。'
+ + '你项目里的名字、路径与取值以稳定占位形式出现,所以同一个名字在各处读起来一致,'
+ + '但不会说出它是什么。不包含任何场景、脚本或资产。',
+ },
+ 'diag.confirm.titleFull': { en: 'Export diagnostics with project content', zh: '导出诊断信息(含项目内容)' },
+ 'diag.confirm.bodyFull': {
+ en: 'This one carries the real names, paths and values — everything the safe export '
+ + 'replaces with placeholders. Send it only where you would send the project '
+ + 'itself. Scenes, scripts and assets are still not included.',
+ zh: '这一份带着真实的名字、路径与取值——也就是脱敏版会替换成占位的全部内容。'
+ + '只发给你愿意把项目本身交给的人。场景、脚本与资产仍然不包含。',
+ },
+ 'diag.confirm.export': { en: 'Export', zh: '导出' },
+ 'diag.summary.sections': {
+ en: 'Includes {count} sections: {names}',
+ zh: '包含 {count} 个部分:{names}',
+ },
+ 'diag.summary.failed': {
+ en: 'Could not collect: {names}. That failure is itself in the report.',
+ zh: '未能采集:{names}。这个失败本身也会写进报告。',
+ },
+ 'diag.saved': { en: 'Diagnostics exported.', zh: '诊断信息已导出。' },
+ 'diag.reveal': { en: 'Show file', zh: '显示文件' },
+ 'diag.failed': { en: 'Could not write the diagnostics: {error}', zh: '写出诊断信息失败:{error}' },
});
diff --git a/desktop/src/i18n/messages/menu.ts b/desktop/src/i18n/messages/menu.ts
index 88abcd175..8e1b6ca26 100644
--- a/desktop/src/i18n/messages/menu.ts
+++ b/desktop/src/i18n/messages/menu.ts
@@ -28,6 +28,11 @@ export const menuMessages = defineMessages({
},
'menu.checkUpdates': { en: 'Check for Updates…', zh: '检查更新…' },
'menu.openLogs': { en: 'Open Log Folder', zh: '打开日志文件夹' },
+ 'menu.exportDiagnostics': { en: 'Export Diagnostics…', zh: '导出诊断信息…' },
+ 'menu.exportDiagnosticsFull': {
+ en: 'Export Diagnostics (with project content)…',
+ zh: '导出诊断信息(含项目内容)…',
+ },
'menu.keyboardShortcuts': { en: 'Keyboard Shortcuts', zh: '键盘快捷键' },
'toast.extractedSchemas': { en: 'Extracted component schemas', zh: '组件 Schema 已提取' },
diff --git a/desktop/src/layout/menus.ts b/desktop/src/layout/menus.ts
index ae4b72b57..e4cfbb46a 100644
--- a/desktop/src/layout/menus.ts
+++ b/desktop/src/layout/menus.ts
@@ -137,6 +137,7 @@ const BUILTIN_ITEMS: MenuContribution[] = [
cmd('help', 'about', 'help.checkUpdates'),
cmd('help', 'help', 'palette.open'),
cmd('help', 'help', 'help.shortcuts'),
+ cmd('help', 'diagnostics', 'help.exportDiagnostics'),
cmd('help', 'diagnostics', 'help.openLogs'),
];
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index 30153923b..fba9858b4 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -54,6 +54,7 @@ import { Particle, getComponent, takeCensus } from 'esengine';
import { actionNames, actionParams, conditionNames } from '@/ai/actionCatalog';
import { applyFxPreview, initFxPreviewEditRestart } from './engine/fxPreview';
import { commands } from './commands/registry';
+import { captureBuildStamp, captureAppVersion, collectBundle } from './diagnostics';
import { allEntitySources, sourceById, createFromSource, type TileGridConfig } from './engine/entitySources';
import { createTilemapFromTileset, createCollisionLayer } from './tilemap/createTilemap';
import { applySceneOps, type SceneOp } from './engine/sceneOps';
@@ -85,6 +86,11 @@ import { applySettings } from './store/settingsStore';
LogStore.install();
// Apply persisted editor settings (accent, UI scale, log cap) before first paint.
applySettings();
+// Read the identities a diagnostic bundle needs while they can still be asked
+// for: both are async, and the moment a report is wanted is the worst moment to
+// start awaiting one.
+captureAppVersion();
+captureBuildStamp();
// Live-sync the asset registry + Content Browser with on-disk changes (incl.
// edits made outside the editor) via the main-process project watcher.
initFsWatch();
@@ -339,6 +345,10 @@ function buildEditorAutomation(): unknown {
params: Object.fromEntries(actionNames().map((n) => [n, actionParams(n).map((p) => p.name)])),
}),
/** Dispatch any registered editor command by id (the UI's own channel). */
+ /** The diagnostic bundle, without writing a file — so a driver (or an agent
+ * looking at a stuck editor) can read what a report would have said. */
+ collectDiagnostics: (detail: 'safe' | 'full' = 'safe') =>
+ collectBundle(detail, new Date().toISOString()),
runCommand: (id: string) => commands.run(id),
/**
* The one door every plugin-contributed agent tool is dispatched through.
diff --git a/desktop/tests/diagnostic-bundle.test.ts b/desktop/tests/diagnostic-bundle.test.ts
new file mode 100644
index 000000000..284c8d4ee
--- /dev/null
+++ b/desktop/tests/diagnostic-bundle.test.ts
@@ -0,0 +1,130 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The diagnostic bundle: what it collects, and what it refuses to carry.
+ *
+ * Two properties do the work. A bundle is assembled from a REGISTRY, so a
+ * subsystem that has something to say is not also a line in an exporter
+ * that can be forgotten. And the user's own content is marked on the
+ * VALUE, so the safe export cannot drift from the real one — there is only
+ * one collector.
+ */
+import { describe, it, expect, afterEach } from 'vitest';
+import { diagnosticsRegistry } from '@/diagnostics/registry';
+import { collectBundle, serializeBundle, bundleFileName, BUNDLE_FORMAT } from '@/diagnostics/bundle';
+import { personal, resolve, placeholder, stableTag } from '@/diagnostics/redact';
+
+const AT = '2026-08-08T21:30:00.000Z';
+const disposers: { dispose(): void }[] = [];
+const section = (id: string, collect: () => unknown) => {
+ disposers.push(diagnosticsRegistry.register({ id, collect }, 'plugin:test'));
+};
+
+afterEach(() => {
+ diagnosticsRegistry.disposeOwner('plugin:test');
+ disposers.length = 0;
+});
+
+describe('a personal value', () => {
+ it('reads as the same placeholder everywhere it appears', () => {
+ // The whole point of a sequence is telling "deleted X then undid X" from
+ // "deleted X then undid Y". A per-occurrence placeholder erases exactly
+ // that, so equal values must produce equal tags.
+ const a = placeholder(personal('Player', 'name'));
+ const b = placeholder(personal('Player', 'name'));
+ expect(a).toBe(b);
+ expect(placeholder(personal('Enemy', 'name'))).not.toBe(a);
+ });
+
+ it('keeps the kind and the shape, which is often the diagnosis', () => {
+ expect(placeholder(personal('assets/x.png', 'path'))).toContain('path#');
+ expect(placeholder(personal('assets/x.png', 'path'))).toContain('len=12');
+ // Absent and zero are different bugs; redaction must not merge them.
+ expect(placeholder(personal(undefined, 'value'))).toBe('value#undefined');
+ expect(placeholder(personal(0, 'value'))).toBe('value#number');
+ expect(placeholder(personal(null, 'value'))).toBe('value#null');
+ });
+
+ it('is carried only at full detail', () => {
+ const tree = { keep: 1, mine: personal('Player', 'name') };
+ expect(resolve(tree, 'full')).toEqual({ keep: 1, mine: 'Player' });
+ expect((resolve(tree, 'safe') as { mine: string }).mine).toContain('name#');
+ expect(JSON.stringify(resolve(tree, 'safe'))).not.toContain('Player');
+ });
+
+ it('is resolved wherever it is nested', () => {
+ // A section returns a tree, not a flat record, so redaction that only
+ // looked at the top level would leak everything one level down.
+ const tree = { a: [{ b: { c: personal('secret', 'text') } }] };
+ expect(JSON.stringify(resolve(tree, 'safe'))).not.toContain('secret');
+ });
+
+ it('does not serialize live objects, or loop on a cycle', () => {
+ class Live { x = 1; }
+ const cyclic: Record<string, unknown> = { n: 1 };
+ cyclic.self = cyclic;
+ expect(resolve({ live: new Live() }, 'safe')).toEqual({ live: '[Live]' });
+ expect(resolve(cyclic, 'safe')).toEqual({ n: 1, self: '[circular]' });
+ expect(resolve({ f: () => 0 }, 'safe')).toEqual({ f: '[function]' });
+ });
+});
+
+describe('the bundle', () => {
+ it('is whatever registered, not a list the exporter keeps', () => {
+ section('probe', () => ({ hello: 'world' }));
+ const b = collectBundle('safe', AT);
+ expect(b.sections.probe).toEqual({ hello: 'world' });
+ expect(b.formatVersion).toBe(BUNDLE_FORMAT);
+ expect(b.createdAt).toBe(AT);
+ });
+
+ it('survives a section that throws, and says which', () => {
+ // During an incident a bundle that is mostly present beats no bundle, and
+ // the collector that failed is itself a finding.
+ section('good', () => ({ ok: true }));
+ section('bad', () => { throw new Error('probe exploded'); });
+ const b = collectBundle('safe', AT);
+ expect(b.sections.good).toEqual({ ok: true });
+ expect(b.sections.bad).toBeUndefined();
+ expect(b.failedSections.bad).toBe('probe exploded');
+ });
+
+ it('leaves out a section with nothing to say', () => {
+ // Absent and empty are different facts: "no project open" must not read
+ // as "a project with nothing in it".
+ section('quiet', () => null);
+ expect('quiet' in collectBundle('safe', AT).sections).toBe(false);
+ });
+
+ it('carries no personal value at safe detail, whichever section held it', () => {
+ section('leaky', () => ({ deep: { name: personal('MyGame', 'project') } }));
+ expect(serializeBundle(collectBundle('safe', AT))).not.toContain('MyGame');
+ expect(serializeBundle(collectBundle('full', AT))).toContain('MyGame');
+ });
+
+ it('names a file that sorts by time and is legal on Windows', () => {
+ const name = bundleFileName(AT);
+ expect(name).toMatch(/^estella-diagnostics-[\d-]+T[\d-]+\.json$/);
+ expect(name).not.toContain(':');
+ });
+});
+
+describe('the core sections', () => {
+ it('are registered by importing the barrel', async () => {
+ await import('@/diagnostics');
+ const ids = diagnosticsRegistry.all().map((s) => s.id);
+ expect(ids).toEqual(expect.arrayContaining(['editor', 'engine', 'project', 'census', 'log']));
+ });
+
+ it('have distinct ids, so none silently replaces another', () => {
+ const ids = diagnosticsRegistry.all().map((s) => s.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ });
+});
+
+describe('the stable tag', () => {
+ it('is the same across runs for the same value', () => {
+ expect(stableTag('Player')).toBe(stableTag('Player'));
+ expect(stableTag('Player')).toHaveLength(4);
+ });
+});
diff --git a/desktop/tests/menu-registry.test.ts b/desktop/tests/menu-registry.test.ts
index 58691ec1f..2a8f71d18 100644
--- a/desktop/tests/menu-registry.test.ts
+++ b/desktop/tests/menu-registry.test.ts
@@ -54,7 +54,8 @@ describe('menu registry', () => {
// dock tab and no chord of its own.
expect(layout('window')).toEqual(['agent.open', 'view.resetLayout', 'plugins.open', null, 'project.close']);
expect(layout('help')).toEqual([
- 'help.about', 'help.checkUpdates', null, 'palette.open', 'help.shortcuts', null, 'help.openLogs',
+ 'help.about', 'help.checkUpdates', null, 'palette.open', 'help.shortcuts', null,
+ 'help.exportDiagnostics', 'help.openLogs',
]);
});