🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(desktop): structured jsonl logs, query CLI and a debug logs setting (#22873)
YuTengjing4816a48eed76
diff --git a/.agents/skills/desktop/SKILL.md b/.agents/skills/desktop/SKILL.mdindex 9222c320685..8d4a8049c85 100644--- a/.agents/skills/desktop/SKILL.md+++ b/.agents/skills/desktop/SKILL.md@@ -14,6 +14,11 @@ LobeHub desktop is built on Electron with main-renderer architecture:2. **Renderer Process**: Reuses web code from `src/`3. **Preload Scripts** (`apps/desktop/src/preload`): Securely expose main process to renderer+Both processes log to `<userData>/logs/{main,renderer}.jsonl` in dev and packaged+builds (`apps/desktop/src/main/utils/structuredLog/`); read them with+`pnpm --dir apps/desktop logs list|query|follow` (filters: `--level`, `--since`,+`--operation op_…`, `--topic tpc_…`) instead of `tail`ing files.+## Adding New Desktop Features### 1. Create Controllerdiff --git a/apps/desktop/Development.md b/apps/desktop/Development.mdindex 2da36aca535..6d84b1d5dde 100644--- a/apps/desktop/Development.md+++ b/apps/desktop/Development.md@@ -416,37 +416,25 @@ await ipc.system.updateLocale('en-US');### 日志系统 (Logging)-日志系统提供统一的日志记录接口:--1. **日志工具**:- - 基于 debug 和 electron-log 实现- - 支持不同日志级别 (debug, info, warn, error, verbose)- - 根据环境自动调整日志行为--```typescript-// 创建日志记录器-export const createLogger = (namespace: string) => {- const debugLogger = debug(namespace);-- return {- debug: (message, ...args) => {- debugLogger(message, ...args);- },- error: (message, ...args) => {- if (process.env.NODE_ENV === 'production') {- electronLog.error(message, ...args);- }- debugLogger(`ERROR: ${message}`, ...args);- },- // 其他日志级别...- };-};+1. **写日志**:主进程用 `createLogger(namespace)`(`src/main/utils/logger.ts`),支持 debug、info、warn、error、verbose 五个级别。+2. **结构化日志**:dev 和打包版都写 `<userData>/logs/`(`src/main/utils/structuredLog/`):+ - `main.jsonl`:`createLogger` 全部级别、主进程直接 `console.*`、electron-updater、渲染进程崩溃+ - `renderer.jsonl`:每个应用窗口的 console(经 `webContents` 的 `console-message` 采集,不含 webview)+ - `manifest.json`:pid、启动 / 退出时间、版本;没有 `endedAt` 且进程不在说明崩溃或被杀+ - 默认级别:打包版 `info`,dev `debug`;打包版可在「设置 → 关于 → 调试日志」开启 debug(`debugLoggingEnabled`,立即生效);单文件 20MB 轮转,保留 3 代+ - 每行带 `ts`、`level`、`process`、`ns`、`msg`、`args`,并提取 `operationId`(`op_…`)/ `topicId`(`tpc_…`),用来与服务端 agent trace 对照+3. **查询**:`pnpm logs <list|query|follow>`++```bash+pnpm logs list # 本机所有带日志的 profile 与运行状态+pnpm logs query --level warn --since 30m # 最近 30 分钟 warn 及以上+pnpm logs query --operation op_xxx --json # 某次运行的客户端日志+pnpm logs follow --process renderer --ns Gateway # 实时跟随```-2. **日志配置**:- - 开发环境显示详细日志- - 生产环境记录到文件- - 支持命名空间隔离日志+未指定 `--profile` / `--dir` 时,自动选最近写入的 profile(打包版、默认 dev profile、仓库 `.cache/desktop-user-data*`)。++4. **兼容**:打包版仍按原样写 `~/Library/Logs/<appName>/main.log`(info 起,`pnpm log:auth` 依赖它)。### 自动更新 (Auto Updates)diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 87c2e83a470..4b77fb2be58 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -32,6 +32,7 @@"lint:style": "stylelint \"{src,tests}/**/*.{css,less}\" --fix --allow-empty-input","lint:ts": "eslint \"{src,tests}/**/*.{js,jsx,ts,tsx}\" --fix","log:auth": "node scripts/analyzeAuthLog.mjs",+ "logs": "node scripts/desktopLogs.mts","package:linux": "npm run build:main && electron-builder --linux --config electron-builder.mjs --publish never","package:local": "npm run build:main && electron-builder --dir --config electron-builder.mjs --c.mac.notarize=false -c.mac.identity=null --c.asar=false","package:local:reuse": "electron-builder --dir --config electron-builder.mjs --c.mac.notarize=false -c.mac.identity=null --c.asar=false",diff --git a/apps/desktop/scripts/__tests__/desktopLogs.test.mts b/apps/desktop/scripts/__tests__/desktopLogs.test.mtsnew file mode 100644index 00000000000..e3a514ed594--- /dev/null+++ b/apps/desktop/scripts/__tests__/desktopLogs.test.mts@@ -0,0 +1,199 @@+import { appendFile, mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import * as layout from '../../src/main/utils/structuredLog/layout';+import {+ createFollowCursors,+ describeRun,+ discoverLogDirectories,+ formatRecord,+ getLogFileName,+ LOG_DIRECTORY_NAME,+ LOG_LEVEL_RANK,+ LOG_MANIFEST_FILE,+ LOG_PROCESSES,+ type LogFilter,+ type LogRecord,+ matchesFilter,+ MAX_LOG_GENERATIONS,+ parseTimeBound,+ queryLogs,+ readAppended,+} from '../desktopLogs.mts';++let root: string;++beforeEach(async () => {+ root = await mkdtemp(path.join(os.tmpdir(), 'desktop-logs-cli-'));+});++afterEach(async () => {+ await rm(root, { force: true, recursive: true });+});++const record = (overrides: Partial<LogRecord>): LogRecord => ({+ level: 'info',+ msg: 'message',+ pid: 1,+ process: 'main',+ ts: '2026-11-12T10:00:00.000Z',+ ...overrides,+});+const toLine = (value: LogRecord) => `${JSON.stringify(value)}\n`;+const allProcesses: LogFilter = { processes: LOG_PROCESSES };++describe('layout parity', () => {+ it('reads the files the main process writes', () => {+ expect(LOG_DIRECTORY_NAME).toBe(layout.LOG_DIRECTORY_NAME);+ expect(LOG_MANIFEST_FILE).toBe(layout.LOG_MANIFEST_FILE);+ expect(LOG_PROCESSES).toEqual(layout.LOG_PROCESSES);+ expect(LOG_LEVEL_RANK).toEqual(layout.LOG_LEVEL_RANK);+ expect(MAX_LOG_GENERATIONS).toBe(layout.MAX_LOG_GENERATIONS);+ expect(getLogFileName('main')).toBe(layout.getLogFileName('main'));+ });+});++describe('matchesFilter', () => {+ const opRecord = record({+ level: 'warn',+ ns: 'Gateway',+ operationId: 'op_1_a',+ topicId: 'tpc_a',+ });+ const line = toLine(opRecord);++ it('applies level, namespace, process and id filters', () => {+ expect(matchesFilter(opRecord, line, { ...allProcesses, minLevel: 'info' })).toBe(true);+ expect(matchesFilter(opRecord, line, { ...allProcesses, minLevel: 'error' })).toBe(false);+ expect(matchesFilter(opRecord, line, { ...allProcesses, ns: 'gate' })).toBe(true);+ expect(matchesFilter(opRecord, line, { processes: ['renderer'] })).toBe(false);+ expect(matchesFilter(opRecord, line, { ...allProcesses, operationId: 'op_1_a' })).toBe(true);+ expect(matchesFilter(opRecord, line, { ...allProcesses, topicId: 'tpc_b' })).toBe(false);+ });++ it('finds a second id that only appears in the arguments', () => {+ const value = record({ args: [{ next: 'op_2_b' }], operationId: 'op_1_a' });+ expect(matchesFilter(value, toLine(value), { ...allProcesses, operationId: 'op_2_b' })).toBe(+ true,+ );+ });++ it('bounds by time, relative or absolute', () => {+ const now = Date.parse('2026-11-12T10:10:00.000Z');+ const since = parseTimeBound('5m', now);+ expect(matchesFilter(opRecord, line, { ...allProcesses, since })).toBe(false);+ expect(parseTimeBound('2026-11-12T10:00:00.000Z')).toBe(Date.parse(opRecord.ts));+ expect(() => parseTimeBound('soon')).toThrow(/Invalid time/);+ });+});++describe('queryLogs', () => {+ it('merges processes and rotated files in time order and keeps the last matches', async () => {+ const directory = path.join(root, 'logs');+ await mkdir(directory);+ await writeFile(+ path.join(directory, 'main.jsonl.1'),+ toLine(record({ msg: 'old main', ts: '2026-11-12T10:00:01.000Z' })),+ );+ await writeFile(+ path.join(directory, 'main.jsonl'),+ toLine(record({ msg: 'new main', ts: '2026-11-12T10:00:03.000Z' })) + 'not json\n',+ );+ await writeFile(+ path.join(directory, 'renderer.jsonl'),+ toLine(record({ msg: 'renderer', process: 'renderer', ts: '2026-11-12T10:00:02.000Z' })),+ );++ const all = await queryLogs(directory, allProcesses, 10);+ expect(all.map((match) => match.record.msg)).toEqual(['old main', 'renderer', 'new main']);++ const last = await queryLogs(directory, allProcesses, 2);+ expect(last.map((match) => match.record.msg)).toEqual(['renderer', 'new main']);+ });+});++describe('createFollowCursors', () => {+ it('hands lines written during the initial tail to follow, whole and once', async () => {+ const directory = path.join(root, 'logs');+ await mkdir(directory, { recursive: true });+ const file = path.join(directory, 'main.jsonl');+ const partial = toLine(record({ msg: 'mid-append', ts: '2026-11-12T10:00:01.000Z' }));+ await writeFile(+ file,+ toLine(record({ msg: 'before', ts: '2026-11-12T10:00:00.000Z' })) + partial.slice(0, 10),+ );+ const filter: LogFilter = { processes: ['main'] };++ const cursors = await createFollowCursors(directory, filter);+ await appendFile(+ file,+ partial.slice(10) + toLine(record({ msg: 'during tail', ts: '2026-11-12T10:00:02.000Z' })),+ );++ const tail = await queryLogs(directory, filter, 10, cursors);+ expect(tail.map((match) => match.record.msg)).toEqual(['before']);+ const followed = (await readAppended(file, cursors.get(file)!)).map(+ (line) => JSON.parse(line).msg,+ );+ expect(followed).toEqual(['mid-append', 'during tail']);+ });+});++describe('readAppended', () => {+ it('follows a file across rotation without losing the old tail', async () => {+ const file = path.join(root, 'main.jsonl');+ await writeFile(file, 'a\nb');+ const cursor = { offset: 0, remainder: '' };++ expect(await readAppended(file, cursor)).toEqual(['a']);+ await appendFile(file, '\nc\n');+ await rename(file, `${file}.1`);+ await writeFile(file, 'd\n');++ expect(await readAppended(file, cursor)).toEqual(['b', 'c', 'd']);+ });+});++describe('discoverLogDirectories', () => {+ it('finds a managed checkout profile above the working directory', async () => {+ const logs = path.join(root, '.cache', 'desktop-user-data', 'logs');+ await mkdir(logs, { recursive: true });+ await writeFile(path.join(logs, 'manifest.json'), '{}');+ const nested = path.join(root, 'lobehub', 'apps', 'desktop');+ await mkdir(nested, { recursive: true });++ expect(await discoverLogDirectories(nested)).toContain(logs);+ });+});++describe('describeRun', () => {+ const manifest = { isPackaged: false, pid: 7, startedAt: '', userData: '' };++ it('tells a running, exited and crashed run apart', () => {+ expect(describeRun(manifest, () => true)).toBe('running (pid 7)');+ expect(describeRun({ ...manifest, endedAt: 'T' }, () => true)).toBe('exited T');+ expect(describeRun({ ...manifest, endedAt: 'T', exitCode: 0 }, () => true)).toBe('exited T');+ expect(describeRun({ ...manifest, endedAt: 'T', exitCode: 7 }, () => false)).toBe(+ 'crashed (exit code 7) T',+ );+ expect(describeRun(manifest, () => false)).toBe('crashed or killed (pid 7)');+ });+});++describe('formatRecord', () => {+ it('prints one readable line', () => {+ expect(+ formatRecord(+ record({+ args: [{ a: 1 }],+ ns: 'Menu',+ source: 'app.ts:3',+ ts: '2026-11-12T10:00:00.123Z',+ }),+ ),+ ).toBe('10:00:00.123 INFO main [Menu] message [{"a":1}] (app.ts:3)');+ });+});diff --git a/apps/desktop/scripts/__tests__/devOrchestrator.test.mjs b/apps/desktop/scripts/__tests__/devOrchestrator.test.mjsindex b74d5faf79a..75f70203525 100644--- a/apps/desktop/scripts/__tests__/devOrchestrator.test.mjs+++ b/apps/desktop/scripts/__tests__/devOrchestrator.test.mjs@@ -239,12 +239,30 @@ describe('createDevOrchestrator', () => {h.orchestrator.shutdown(0);h.orchestrator.shutdown(1);- expect(h.options.exit).toHaveBeenCalledTimes(1);- expect(h.options.exit).toHaveBeenCalledWith(0);- expect(h.electronSpawns()[0].child.kill).toHaveBeenCalled();+ expect(h.electronSpawns()[0].child.kill).toHaveBeenCalledTimes(1);for (const { child } of h.viteChildren()) {expect(child.kill).toHaveBeenCalled();}+ // A group signal must not reach Electron too: its second SIGTERM is fatal.+ expect(h.electronSpawns()[0].opts.detached).toBe(process.platform !== 'win32');+ // Electron is still quitting: the launcher must outlive it.+ expect(h.options.exit).not.toHaveBeenCalled();++ h.electronSpawns()[0].child.emit('exit', 0);+ expect(h.options.exit).toHaveBeenCalledTimes(1);+ expect(h.options.exit).toHaveBeenCalledWith(0);+ });++ it('kills an electron whose quit hangs past the timeout', async () => {+ const h = createHarness({ electronQuitTimeoutMs: 5000 });+ h.orchestrator.start();+ await h.becomeReady();++ h.orchestrator.shutdown(0);+ await vi.advanceTimersByTimeAsync(5000);++ expect(h.electronSpawns()[0].child.kill).toHaveBeenLastCalledWith('SIGKILL');+ expect(h.options.exit).toHaveBeenCalledWith(0);});it('fails with exit(1) when the initial build never produces bundles', async () => {diff --git a/apps/desktop/scripts/desktopLogs.mts b/apps/desktop/scripts/desktopLogs.mtsnew file mode 100644index 00000000000..f62d2e82810--- /dev/null+++ b/apps/desktop/scripts/desktopLogs.mts@@ -0,0 +1,516 @@+/**+ * Query and follow the structured Desktop logs that the main process writes to+ * `<userData>/logs/{main,renderer}.jsonl` (`src/main/utils/structuredLog/`).+ *+ * node scripts/desktopLogs.mts list+ * node scripts/desktopLogs.mts query [filters] [--limit 200] [--json]+ * node scripts/desktopLogs.mts follow [filters] [--tail 20] [--json] [--duration 30s]+ *+ * Filters: --process main|renderer, --level debug|info|warn|error (lowest kept),+ * --since 10m|2h|1d|<ISO>, --until <same>, --ns <text>, --grep <text>,+ * --operation <op_…>, --topic <tpc_…>, --pid <n>.+ * Target: --profile <userData dir> | --dir <logs dir>; otherwise the profile+ * whose logs changed last among the packaged app, the default dev profile and+ * the checkout's managed profiles (`.cache/desktop-user-data*`).+ *+ * Only `node:` built-ins and erasable TypeScript, so it runs under plain `node`+ * even when the app itself does not start.+ */+import { createReadStream } from 'node:fs';+import { open, readdir, readFile, stat } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { createInterface } from 'node:readline';+import { pathToFileURL } from 'node:url';+import { parseArgs } from 'node:util';++// ─── Layout (pinned to src/main/utils/structuredLog/layout.ts by the test) ───++export const LOG_DIRECTORY_NAME = 'logs';+export const LOG_MANIFEST_FILE = 'manifest.json';+export const LOG_PROCESSES = ['main', 'renderer'] as const;+export const LOG_LEVEL_RANK: Record<string, number> = { debug: 10, error: 40, info: 20, warn: 30 };+export const MAX_LOG_GENERATIONS = 3;+export const getLogFileName = (process: string) => `${process}.jsonl`;++type LogProcess = (typeof LOG_PROCESSES)[number];++export interface LogRecord {+ args?: unknown[];+ level: string;+ msg: string;+ ns?: string;+ operationId?: string;+ pid: number;+ process: LogProcess;+ source?: string;+ topicId?: string;+ ts: string;+}++interface LogManifest {+ appVersion?: string;+ endedAt?: string;+ exitCode?: number;+ isPackaged: boolean;+ pid: number;+ startedAt: string;+ userData: string;+}++// ─── Filters ─────────────────────────────────────────────────────────++export interface LogFilter {+ grep?: string;+ minLevel?: string;+ ns?: string;+ operationId?: string;+ pid?: number;+ processes: readonly LogProcess[];+ since?: number;+ topicId?: string;+ until?: number;+}++const DURATION_UNITS: Record<string, number> = { d: 86_400_000, h: 3_600_000, m: 60_000, s: 1000 };++/** `10m` → ten minutes before `now`; anything else must parse as a date. */+export const parseTimeBound = (value: string, now = Date.now()): number => {+ const relative = /^(\d+(?:\.\d+)?)([dhms])$/.exec(value.trim());+ if (relative) return now - Number(relative[1]) * DURATION_UNITS[relative[2]];+ const absolute = Date.parse(value);+ if (Number.isNaN(absolute))+ throw new Error(`Invalid time: ${value} (use 10m, 2h, 1d or an ISO date)`);+ return absolute;+};++export const parseDuration = (value: string): number => {+ const match = /^(\d+(?:\.\d+)?)([dhms])$/.exec(value.trim());+ if (!match) throw new Error(`Invalid duration: ${value} (use 30s, 5m)`);+ return Number(match[1]) * DURATION_UNITS[match[2]];+};++/** The id fields hold the first id of a record; a substring check also finds the others. */+const mentions = (record: LogRecord, line: string, field: 'operationId' | 'topicId', id: string) =>+ record[field] === id || line.includes(id);++export const matchesFilter = (record: LogRecord, line: string, filter: LogFilter): boolean => {+ if (!filter.processes.includes(record.process)) return false;+ if (filter.minLevel && (LOG_LEVEL_RANK[record.level] ?? 0) < LOG_LEVEL_RANK[filter.minLevel])+ return false;+ if (filter.pid !== undefined && record.pid !== filter.pid) return false;+ if (filter.since !== undefined || filter.until !== undefined) {+ const time = Date.parse(record.ts);+ if (filter.since !== undefined && time < filter.since) return false;+ if (filter.until !== undefined && time > filter.until) return false;+ }+ if (filter.ns && !record.ns?.toLowerCase().includes(filter.ns.toLowerCase())) return false;+ if (filter.operationId && !mentions(record, line, 'operationId', filter.operationId))+ return false;+ if (filter.topicId && !mentions(record, line, 'topicId', filter.topicId)) return false;+ if (filter.grep && !line.toLowerCase().includes(filter.grep.toLowerCase())) return false;+ return true;+};++export const parseLine = (line: string): LogRecord | undefined => {+ if (!line.trim()) return undefined;+ try {+ const record = JSON.parse(line) as LogRecord;+ return typeof record.ts === 'string' && typeof record.msg === 'string' ? record : undefined;+ } catch {+ return undefined;+ }+};++// ─── Profiles ────────────────────────────────────────────────────────++const getAppDataDirectory = () => {+ const home = os.homedir();+ if (process.platform === 'darwin') return path.join(home, 'Library', 'Application Support');+ if (process.platform === 'win32')+ return process.env.APPDATA || path.join(home, 'AppData', 'Roaming');+ return process.env.XDG_CONFIG_HOME || path.join(home, '.config');+};++/** Profiles a managed dev runtime keeps per checkout and backend, under the checkout's `.cache/`. */+const MANAGED_PROFILE_NAMES = ['desktop-user-data', 'desktop-user-data-online'];++const exists = (target: string) =>+ stat(target).then(+ () => true,+ () => false,+ );++/** Every profile on this machine that has structured logs. */+export const discoverLogDirectories = async (cwd = process.cwd()): Promise<string[]> => {+ const candidates = new Set<string>();+ if (process.env.LOBE_DESKTOP_USER_DATA_DIR) {+ candidates.add(path.join(process.env.LOBE_DESKTOP_USER_DATA_DIR, LOG_DIRECTORY_NAME));+ }+ const appData = getAppDataDirectory();+ const entries = await readdir(appData).catch(() => [] as string[]);+ for (const entry of entries) {+ if (/^lobehub/i.test(entry)) candidates.add(path.join(appData, entry, LOG_DIRECTORY_NAME));+ }+ for (let directory = path.resolve(cwd); ; directory = path.dirname(directory)) {+ for (const name of MANAGED_PROFILE_NAMES) {+ candidates.add(path.join(directory, '.cache', name, LOG_DIRECTORY_NAME));+ }+ if (path.dirname(directory) === directory) break;+ }++ const found: string[] = [];+ for (const candidate of candidates) {+ if (await exists(path.join(candidate, LOG_MANIFEST_FILE))) found.push(candidate);+ }+ return found;+};++const readManifest = async (directory: string): Promise<LogManifest | undefined> => {+ try {+ return JSON.parse(await readFile(path.join(directory, LOG_MANIFEST_FILE), 'utf8'));+ } catch {+ return undefined;+ }+};++const lastWriteTime = async (directory: string) => {+ let latest = 0;+ for (const process of LOG_PROCESSES) {+ const stats = await stat(path.join(directory, getLogFileName(process))).catch(() => undefined);+ if (stats) latest = Math.max(latest, stats.mtimeMs);+ }+ if (!latest) latest = (await stat(path.join(directory, LOG_MANIFEST_FILE))).mtimeMs;+ return latest;+};++const isAlive = (pid: number) => {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return (error as NodeJS.ErrnoException).code === 'EPERM';+ }+};++export const describeRun = (manifest: LogManifest | undefined, alive: (pid: number) => boolean) => {+ if (!manifest) return 'no manifest';+ if (manifest.endedAt)+ return manifest.exitCode+ ? `crashed (exit code ${manifest.exitCode}) ${manifest.endedAt}`+ : `exited ${manifest.endedAt}`;+ return alive(manifest.pid)+ ? `running (pid ${manifest.pid})`+ : `crashed or killed (pid ${manifest.pid})`;+};++const resolveLogDirectory = async (values: { dir?: string; profile?: string }) => {+ if (values.dir) return path.resolve(values.dir);+ if (values.profile) return path.join(path.resolve(values.profile), LOG_DIRECTORY_NAME);+ const found = await discoverLogDirectories();+ if (found.length === 0) {+ throw new Error(+ 'No Desktop structured logs found. Start the app once, or pass --profile <userData> / --dir <logs dir>.',+ );+ }+ const times = await Promise.all(found.map(lastWriteTime));+ return found[times.indexOf(Math.max(...times))];+};++// ─── Reading ─────────────────────────────────────────────────────────++/** Oldest first: `main.jsonl.3` … `main.jsonl.1`, then the live file. */+export const getGenerationPaths = (directory: string, process: LogProcess) => {+ const live = path.join(directory, getLogFileName(process));+ const rotated = Array.from(+ { length: MAX_LOG_GENERATIONS },+ (_, index) => `${live}.${MAX_LOG_GENERATIONS - index}`,+ );+ return [...rotated, live];+};++interface Match {+ line: string;+ record: LogRecord;+}++/**+ * Last `limit` matches across processes and rotated files, oldest first. With+ * `cursors` (from `createFollowCursors`), each live file is read only up to its+ * cursor, so `follow` resumes exactly where this tail ends.+ */+export const queryLogs = async (+ directory: string,+ filter: LogFilter,+ limit: number,+ cursors?: Map<string, Cursor>,+): Promise<Match[]> => {+ const matches: Match[] = [];+ for (const process of filter.processes) {+ const kept: Match[] = [];+ for (const file of getGenerationPaths(directory, process)) {+ const stats = await stat(file).catch(() => undefined);+ if (!stats) continue;+ const cursor = cursors?.get(file);+ // A rotation since the cursor was taken means this live file is all new: follow reads it.+ if (cursor && (cursor.ino !== stats.ino || cursor.offset === 0)) continue;+ const input = createReadStream(file, cursor ? { end: cursor.offset - 1 } : undefined);+ const lines = createInterface({ crlfDelay: Infinity, input });+ for await (const line of lines) {+ const record = parseLine(line);+ if (!record || !matchesFilter(record, line, filter)) continue;+ kept.push({ line, record });+ if (kept.length > limit) kept.shift();+ }+ }+ matches.push(...kept);+ }+ // Stable sort keeps each file's order for records written in the same millisecond.+ matches.sort((a, b) => a.record.ts.localeCompare(b.record.ts));+ return matches.slice(-limit);+};++const LEVEL_LABEL: Record<string, string> = {+ debug: 'DEBUG',+ error: 'ERROR',+ info: 'INFO ',+ warn: 'WARN ',+};++export const formatRecord = (record: LogRecord) => {+ const time = record.ts.slice(11, 23);+ const ns = record.ns ? ` [${record.ns}]` : '';+ const args = record.args?.length ? ` ${JSON.stringify(record.args)}` : '';+ const source = record.source ? ` (${record.source})` : '';+ return `${time} ${LEVEL_LABEL[record.level] ?? record.level} ${record.process.padEnd(8)}${ns} ${record.msg}${args}${source}`;+};++// ─── Follow ──────────────────────────────────────────────────────────++interface Cursor {+ ino?: number;+ offset: number;+ remainder: string;+}++const readBytes = async (file: string, start: number, end: number) => {+ const handle = await open(file, 'r');+ try {+ const buffer = Buffer.alloc(end - start);+ await handle.read(buffer, 0, end - start, start);+ return buffer;+ } finally {+ await handle.close();+ }+};++const readRange = async (file: string, start: number, end: number) =>+ (await readBytes(file, start, end)).toString('utf8');++/** How far back `createFollowCursors` looks for a line boundary; records are capped well below it. */+const FOLLOW_ALIGN_BYTES = 256 * 1024;++/**+ * Reads what a live file gained since `cursor`. A new inode means the writer+ * rotated it: the unread tail of the old file (now `.1`) comes first, then the+ * new file from its start.+ */+export const readAppended = async (file: string, cursor: Cursor): Promise<string[]> => {+ const stats = await stat(file).catch(() => undefined);+ if (!stats) return [];+ let text = cursor.remainder;+ if (stats.ino !== cursor.ino || stats.size < cursor.offset) {+ if (cursor.ino !== undefined) {+ const rotated = await stat(`${file}.1`).catch(() => undefined);+ if (rotated && rotated.ino === cursor.ino && rotated.size > cursor.offset) {+ text += await readRange(`${file}.1`, cursor.offset, rotated.size);+ }+ cursor.offset = 0;+ }+ cursor.ino = stats.ino;+ }+ if (stats.size > cursor.offset) {+ text += await readRange(file, cursor.offset, stats.size);+ cursor.offset = stats.size;+ }+ const lines = text.split('\n');+ cursor.remainder = lines.pop() ?? '';+ return lines;+};++/**+ * Marks the current end of each live file, backed up to the last complete line+ * so a record mid-append is read whole by `follow` rather than split in two.+ * Taken before the initial tail so lines written during it are not skipped.+ */+export const createFollowCursors = async (directory: string, filter: LogFilter) => {+ const cursors = new Map<string, Cursor>();+ for (const process of filter.processes) {+ const file = path.join(directory, getLogFileName(process));+ const stats = await stat(file).catch(() => undefined);+ let offset = stats?.size ?? 0;+ if (offset > 0) {+ const start = Math.max(0, offset - FOLLOW_ALIGN_BYTES);+ const lastNewline = (await readBytes(file, start, offset)).lastIndexOf(0x0a);+ offset = lastNewline === -1 ? start : start + lastNewline + 1;+ }+ cursors.set(file, { ino: stats?.ino, offset, remainder: '' });+ }+ return cursors;+};++const FOLLOW_POLL_MS = 500;++const follow = async (+ cursors: Map<string, Cursor>,+ filter: LogFilter,+ print: (match: Match) => void,+ durationMs?: number,+) => {+ const deadline = durationMs === undefined ? undefined : Date.now() + durationMs;+ while (deadline === undefined || Date.now() < deadline) {+ const batch: Match[] = [];+ for (const [file, cursor] of cursors) {+ for (const line of await readAppended(file, cursor)) {+ const record = parseLine(line);+ if (record && matchesFilter(record, line, filter)) batch.push({ line, record });+ }+ }+ batch.sort((a, b) => a.record.ts.localeCompare(b.record.ts));+ batch.forEach(print);+ await new Promise((resolve) => setTimeout(resolve, FOLLOW_POLL_MS));+ }+};++// ─── CLI ─────────────────────────────────────────────────────────────++const USAGE = `Usage: desktopLogs <list|query|follow> [options]++ list Profiles with structured logs, newest first+ query Print matching records (oldest first)+ follow Print matching records as they are written++Filters: --process main|renderer --level debug|info|warn|error+ --since 10m|ISO --until 10m|ISO --ns TEXT --grep TEXT+ --operation op_… --topic tpc_… --pid N+Target: --profile USER_DATA_DIR | --dir LOGS_DIR+Output: --json --limit N (query, default 200) --tail N (follow, default 20)+ --duration 30s (follow: stop after this long)`;++const toFilter = (values: Record<string, string | boolean | undefined>): LogFilter => {+ const processes = values.process+ ? String(values.process)+ .split(',')+ .map((item) => item.trim())+ : [...LOG_PROCESSES];+ for (const item of processes) {+ if (!LOG_PROCESSES.includes(item as LogProcess)) throw new Error(`Unknown --process ${item}`);+ }+ if (values.level && !(String(values.level) in LOG_LEVEL_RANK)) {+ throw new Error(`Unknown --level ${String(values.level)}`);+ }+ const string = (key: string) => (values[key] === undefined ? undefined : String(values[key]));+ return {+ grep: string('grep'),+ minLevel: string('level'),+ ns: string('ns'),+ operationId: string('operation'),+ pid: values.pid === undefined ? undefined : Number(values.pid),+ processes: processes as LogProcess[],+ since: values.since === undefined ? undefined : parseTimeBound(String(values.since)),+ topicId: string('topic'),+ until: values.until === undefined ? undefined : parseTimeBound(String(values.until)),+ };+};++const main = async (argv: string[]) => {+ const { positionals, values } = parseArgs({+ allowPositionals: true,+ args: argv,+ options: {+ dir: { type: 'string' },+ duration: { type: 'string' },+ grep: { type: 'string' },+ help: { short: 'h', type: 'boolean' },+ json: { type: 'boolean' },+ level: { type: 'string' },+ limit: { type: 'string' },+ ns: { type: 'string' },+ operation: { type: 'string' },+ pid: { type: 'string' },+ process: { type: 'string' },+ profile: { type: 'string' },+ since: { type: 'string' },+ tail: { type: 'string' },+ topic: { type: 'string' },+ until: { type: 'string' },+ },+ });+ const [command] = positionals;+ if (values.help || !command) {+ console.log(USAGE);+ return;+ }++ if (command === 'list') {+ const found = await discoverLogDirectories();+ const rows = await Promise.all(+ found.map(async (directory) => ({+ directory,+ lastWrite: await lastWriteTime(directory),+ manifest: await readManifest(directory),+ })),+ );+ rows.sort((a, b) => b.lastWrite - a.lastWrite);+ if (values.json) {+ console.log(JSON.stringify(rows, null, 2));+ return;+ }+ if (rows.length === 0) console.log('No Desktop structured logs found.');+ for (const { directory, lastWrite, manifest } of rows) {+ const version = manifest?.appVersion ? ` v${manifest.appVersion}` : '';+ const kind = manifest?.isPackaged ? 'packaged' : 'dev';+ console.log(+ `${directory}\n ${kind}${version}, ${describeRun(manifest, isAlive)}, last write ${new Date(lastWrite).toISOString()}`,+ );+ }+ return;+ }++ if (command !== 'query' && command !== 'follow')+ throw new Error(`Unknown command: ${command}\n\n${USAGE}`);++ const directory = await resolveLogDirectory(values);+ const filter = toFilter(values);+ const print = ({ line, record }: Match) => console.log(values.json ? line : formatRecord(record));+ console.error(`# ${directory}`);++ if (command === 'query') {+ const limit = values.limit ? Number(values.limit) : 200;+ const matches = await queryLogs(directory, filter, limit);+ matches.forEach(print);+ if (filter.operationId && matches.length > 0) {+ console.error(+ `# Server side of this operation: the agent-tracing skill with ${filter.operationId}`,+ );+ }+ return;+ }++ const tail = values.tail ? Number(values.tail) : 20;+ const cursors = await createFollowCursors(directory, filter);+ if (tail > 0) (await queryLogs(directory, filter, tail, cursors)).forEach(print);+ await follow(+ cursors,+ filter,+ print,+ values.duration ? parseDuration(values.duration) : undefined,+ );+};++if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {+ main(process.argv.slice(2)).catch((error) => {+ console.error(error instanceof Error ? error.message : error);+ process.exit(1);+ });+}diff --git a/apps/desktop/scripts/devOrchestrator.mjs b/apps/desktop/scripts/devOrchestrator.mjsindex 00b21bae1fa..dc0eeed0d3c 100644--- a/apps/desktop/scripts/devOrchestrator.mjs+++ b/apps/desktop/scripts/devOrchestrator.mjs@@ -28,6 +28,7 @@ export function createDevOrchestrator({bundleQuietMs = 1000,initialBuildTimeoutMs = 120_000,restartDebounceMs = 400,+ electronQuitTimeoutMs = 10_000,spawn = nodeSpawn,existsSync = nodeExistsSync,rmSync = nodeRmSync,@@ -43,6 +44,7 @@ export function createDevOrchestrator({const children = [];let electron = null;+ let electronRunning = false;let restarting = false;let shuttingDown = false;let poll = null;@@ -53,14 +55,34 @@ export function createDevOrchestrator({const spawnVite = (args) =>spawn(nodeBin, [viteBin, ...args], { cwd: desktopRoot, stdio: 'inherit' });+ /**+ * Waits for Electron to finish its own quit (`app.quit()` on SIGTERM) before+ * exiting: a launcher that exits first lets the runtime supervisor kill the+ * app mid-shutdown, losing its last log lines and the clean-exit stamp in+ * `<userData>/logs/manifest.json`. A quit that hangs is killed after the timeout.+ */function shutdown(code) {if (shuttingDown) return;shuttingDown = true;clearInterval(poll);clearTimeout(debounce);- electron?.kill();for (const child of children) child.kill();- exit(code);+ if (!electron || !electronRunning) {+ exit(code);+ return;+ }+ const app = electron;+ const forceKill = setTimeout(() => {+ logError(`[desktop-dev] electron did not quit within ${electronQuitTimeoutMs}ms, killing it`);+ app.kill('SIGKILL');+ exit(code);+ }, electronQuitTimeoutMs);+ app.once('exit', (exitCode, signal) => {+ clearTimeout(forceKill);+ log(`[desktop-dev] electron quit (code ${exitCode}, signal ${signal})`);+ exit(code);+ });+ app.kill();}function startElectron() {@@ -69,6 +91,12 @@ export function createDevOrchestrator({log('[desktop-dev] starting electron');electron = spawn(electronBin, ['.', ...electronArgs], {cwd: desktopRoot,+ // Own process group: Chromium handles only the first SIGTERM/SIGINT gracefully+ // and resets the handler, so a group signal (Ctrl+C, `dev down`) plus the+ // `shutdown()` kill would hard-kill Electron mid-quit. Detached, it receives+ // exactly one signal, from `shutdown()`. Windows has no signals and would+ // open a new console window for a detached child.+ detached: process.platform !== 'win32',env: {...process.env,ELECTRON_RENDERER_URL: `http://127.0.0.1:${vitePort}`,@@ -76,7 +104,9 @@ export function createDevOrchestrator({},stdio: 'inherit',});+ electronRunning = true;electron.on('exit', (code) => {+ electronRunning = false;if (shuttingDown) return;if (restarting) {restarting = false;diff --git a/apps/desktop/src/main/const/store.ts b/apps/desktop/src/main/const/store.tsindex 80249511a62..83e5fdcfcea 100644--- a/apps/desktop/src/main/const/store.ts+++ b/apps/desktop/src/main/const/store.ts@@ -28,6 +28,7 @@ export const defaultProxySettings: NetworkProxySettings = {export const STORE_DEFAULTS: ElectronMainStore = {appTrayVisible: true,dataSyncConfig: { storageMode: 'cloud' },+ debugLoggingEnabled: false,encryptedTokens: {},gatewayDeviceId: '',gatewayEnabled: true,diff --git a/apps/desktop/src/main/controllers/SystemCtr.ts b/apps/desktop/src/main/controllers/SystemCtr.tsindex b30388a145e..e936ae0e55b 100644--- a/apps/desktop/src/main/controllers/SystemCtr.ts+++ b/apps/desktop/src/main/controllers/SystemCtr.ts@@ -1,7 +1,11 @@import { access, readdir } from 'node:fs/promises';import process from 'node:process';-import type { ElectronAppState, ThemeMode } from '@lobechat/electron-client-ipc';+import type {+ DebugLoggingSettings,+ ElectronAppState,+ ThemeMode,+} from '@lobechat/electron-client-ipc';import { app, dialog, nativeTheme, shell } from 'electron';import { legacyLocalDbDir } from '@/const/dir';@@ -16,6 +20,7 @@ import {requestScreenCaptureAccess,} from '@/utils/permissions';import * as electronIs from '@/utils/platform';+import { applyDebugLogging, getStructuredLogDirectory } from '@/utils/structuredLog';import { getSystemLanguage, resolveUILocale } from '@/utils/system-language';import { safeGetPath } from '@/utils/user-path';@@ -198,6 +203,35 @@ export default class SystemController extends ControllerModule {return openFullDiskAccessSettings();}+ /**+ * Settings → About → Debug logs. `alwaysOn` is true in dev, which records+ * `debug` regardless of the setting.+ */+ @IpcMethod()+ getDebugLoggingSettings(): DebugLoggingSettings {+ return {+ alwaysOn: !app.isPackaged,+ enabled: this.app.storeManager.get('debugLoggingEnabled', false),+ };+ }++ @IpcMethod()+ setDebugLoggingEnabled(enabled: boolean): DebugLoggingSettings {+ this.app.storeManager.set('debugLoggingEnabled', enabled);+ applyDebugLogging(enabled);+ logger.info(`Debug logging ${enabled ? 'enabled' : 'disabled'}`);+ return this.getDebugLoggingSettings();+ }++ /** Reveals `<userData>/logs/` so a user can attach the files to a bug report. */+ @IpcMethod()+ async openLogDirectory(): Promise<void> {+ const directory = getStructuredLogDirectory();+ if (!directory) return;+ const error = await shell.openPath(directory);+ if (error) logger.warn(`Failed to open log directory: ${error}`);+ }+@IpcMethod()openExternalLink(url: string) {return shell.openExternal(url);diff --git a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.tsindex ddbb63784a5..58bc4f0a1c3 100644--- a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts@@ -1,5 +1,5 @@import type { ThemeMode } from '@lobechat/electron-client-ipc';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { App } from '@/core/App';import type { IpcContext } from '@/utils/ipc';@@ -57,6 +57,7 @@ vi.mock('electron', () => ({getLocale: vi.fn(() => 'en-US'),getPath: vi.fn((name: string) => `/mock/path/${name}`),getPreferredSystemLanguages: vi.fn(() => ['en-US']),+ isPackaged: false,},desktopCapturer: {getSources: vi.fn(async () => []),@@ -74,6 +75,7 @@ vi.mock('electron', () => ({},shell: {openExternal: vi.fn().mockResolvedValue(undefined),+ openPath: vi.fn().mockResolvedValue(''),},systemPreferences: {askForMediaAccess: vi.fn(async () => true),@@ -82,6 +84,12 @@ vi.mock('electron', () => ({},}));+const structuredLogMock = vi.hoisted(() => ({+ applyDebugLogging: vi.fn(),+ getStructuredLogDirectory: vi.fn(() => '/mock/path/userData/logs'),+}));+vi.mock('@/utils/structuredLog', () => structuredLogMock);+// Mock platform detectionvi.mock('@/utils/platform', () => ({macOS: vi.fn(() => true),@@ -210,6 +218,44 @@ describe('SystemController', () => {});});+ describe('debug logging', () => {+ // `const/dir` reads `isPackaged` at import, so flip it only around these cases.+ beforeEach(async () => {+ const { app } = await import('electron');+ Object.assign(app, { isPackaged: true });+ });+ afterEach(async () => {+ const { app } = await import('electron');+ Object.assign(app, { isPackaged: false });+ });++ it('reports the persisted setting for a packaged build', async () => {+ mockStoreManager.get.mockReturnValueOnce(true);++ expect(await invokeIpc('system.getDebugLoggingSettings')).toEqual({+ alwaysOn: false,+ enabled: true,+ });+ });++ it('persists the switch and applies it to the running log sink', async () => {+ mockStoreManager.get.mockReturnValueOnce(true);++ const result = await invokeIpc('system.setDebugLoggingEnabled', true);++ expect(mockStoreManager.set).toHaveBeenCalledWith('debugLoggingEnabled', true);+ expect(structuredLogMock.applyDebugLogging).toHaveBeenCalledWith(true);+ expect(result).toEqual({ alwaysOn: false, enabled: true });+ });++ it('opens the structured log directory', async () => {+ const { shell } = await import('electron');+ await invokeIpc('system.openLogDirectory');++ expect(shell.openPath).toHaveBeenCalledWith('/mock/path/userData/logs');+ });+ });+describe('setLastWorkspaceSlug', () => {it("records the slug under the current account's entry", async () => {mockStoreManager.get.mockReturnValueOnce({ user_2: 'other' });diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.tsindex 603d636306b..e5968ae67f7 100644--- a/apps/desktop/src/main/core/App.ts+++ b/apps/desktop/src/main/core/App.ts@@ -33,6 +33,7 @@ import LocalDatabaseService from '@/services/LocalDatabaseSrv';import { createLogger } from '@/utils/logger';import * as electronIs from '@/utils/platform';import { refreshShellPath } from '@/utils/shellPath';+import { applyDebugLogging } from '@/utils/structuredLog';import { BrowserManager } from './browser/BrowserManager';import { backendProxyProtocolManager } from './infrastructure/BackendProxyProtocolManager';@@ -128,6 +129,7 @@ export class App {logger.debug('Initializing App');// Initialize store managerthis.storeManager = new StoreManager(this);+ applyDebugLogging(this.storeManager.get('debugLoggingEnabled', false));this.rendererUrlManager = new RendererUrlManager();// Wire the backend reverse-proxy as an `app://` interceptor: keepsdiff --git a/apps/desktop/src/main/core/browser/Browser.ts b/apps/desktop/src/main/core/browser/Browser.tsindex 08011f4f769..bac69549ff9 100644--- a/apps/desktop/src/main/core/browser/Browser.ts+++ b/apps/desktop/src/main/core/browser/Browser.ts@@ -765,7 +765,6 @@ export default class Browser {if (requestHeaders['Origin']) {originMap.set(details.id, requestHeaders['Origin']);delete requestHeaders['Origin'];- logger.debug(`[${this.identifier}] Removed Origin header for: ${details.url}`);}appendVercelCookie(requestHeaders);diff --git a/apps/desktop/src/main/index.test.ts b/apps/desktop/src/main/index.test.tsindex 5d27c575cf9..1422202f322 100644--- a/apps/desktop/src/main/index.test.ts+++ b/apps/desktop/src/main/index.test.ts@@ -1,10 +1,12 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-const { appBootstrap, appConstructor, installProcessErrorHandlers } = vi.hoisted(() => ({- appBootstrap: vi.fn(),- appConstructor: vi.fn(),- installProcessErrorHandlers: vi.fn(),-}));+const { appBootstrap, appConstructor, installProcessErrorHandlers, installStructuredLogging } =+ vi.hoisted(() => ({+ appBootstrap: vi.fn(),+ appConstructor: vi.fn(),+ installProcessErrorHandlers: vi.fn(),+ installStructuredLogging: vi.fn(),+ }));vi.mock('./pre-app-init', () => ({}));@@ -20,6 +22,8 @@ vi.mock('./core/App', () => ({vi.mock('./process-error-handlers', () => ({ installProcessErrorHandlers }));+vi.mock('./utils/structuredLog', () => ({ installStructuredLogging }));+const bootstrapKey = '__LOBEHUB_DESKTOP_MAIN_BOOTSTRAPPED__';const mainProcessGlobal = globalThis as typeof globalThis & Record<string, boolean | undefined>;@@ -40,6 +44,7 @@ describe('main process entry', () => {vi.resetModules();await import('./index');+ expect(installStructuredLogging).toHaveBeenCalledTimes(1);expect(installProcessErrorHandlers).toHaveBeenCalledTimes(1);expect(appConstructor).toHaveBeenCalledTimes(1);expect(appBootstrap).toHaveBeenCalledTimes(1);diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex b82859a50cd..51293c8b043 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -2,6 +2,7 @@ import './pre-app-init';import { App } from './core/App';import { installProcessErrorHandlers } from './process-error-handlers';+import { installStructuredLogging } from './utils/structuredLog';const mainBootstrapKey = '__LOBEHUB_DESKTOP_MAIN_BOOTSTRAPPED__' as const;const mainProcessGlobal = globalThis as typeof globalThis & {@@ -16,6 +17,10 @@ const mainProcessGlobal = globalThis as typeof globalThis & {if (!mainProcessGlobal[mainBootstrapKey]) {mainProcessGlobal[mainBootstrapKey] = true;+ // First, so the error handlers and every window's console land in+ // `<userData>/logs/*.jsonl`; lines logged while modules imported are buffered.+ installStructuredLogging();+// Guard the main process against transient network blips (Wi-Fi/VPN switch,// system sleep) emitted by Electron's net stack as uncaught exceptions.installProcessErrorHandlers();diff --git a/apps/desktop/src/main/modules/updater/electronUpdaterEngine.ts b/apps/desktop/src/main/modules/updater/electronUpdaterEngine.tsindex 14aa0d265b3..8fd990646a1 100644--- a/apps/desktop/src/main/modules/updater/electronUpdaterEngine.ts+++ b/apps/desktop/src/main/modules/updater/electronUpdaterEngine.ts@@ -3,17 +3,34 @@ import { autoUpdater } from 'electron-updater';import { isDev } from '@/const/env';import { getDesktopEnv } from '@/env';+import type { LogLevel } from '@/utils/structuredLog';+import { writeStructuredLog } from '@/utils/structuredLog';import { UPDATE_SERVER_URL } from './configs';import type { UpdateEngine } from './engine';autoUpdater.autoInstallOnAppQuit = false;+/**+ * electron-updater's own lines keep going to `main.log` (the update-test docs+ * grep it) and also reach `main.jsonl` with the rest of the main process.+ */+const toUpdaterLogger = (level: LogLevel) => (message?: unknown) => {+ log[level](message);+ writeStructuredLog({ level, message, ns: 'electron-updater', process: 'main' });+};+const updaterLogger = {+ debug: toUpdaterLogger('debug'),+ error: toUpdaterLogger('error'),+ info: toUpdaterLogger('info'),+ warn: toUpdaterLogger('warn'),+};+export const electronUpdaterEngine: UpdateEngine = {checkForUpdates: () => autoUpdater.checkForUpdates(),configure: (channel) => {log.transports.file.level = 'info';- autoUpdater.logger = log;+ autoUpdater.logger = updaterLogger;autoUpdater.autoDownload = false;autoUpdater.forceDevUpdateConfig = isDev || getDesktopEnv().FORCE_DEV_UPDATE_CONFIG;autoUpdater.allowPrerelease = channel !== 'stable';diff --git a/apps/desktop/src/main/types/store.ts b/apps/desktop/src/main/types/store.tsindex 18ebd290176..1438dad7c4c 100644--- a/apps/desktop/src/main/types/store.ts+++ b/apps/desktop/src/main/types/store.ts@@ -15,6 +15,11 @@ export interface ElectronMainStore {files?: { file: string; mime: string }[];};dataSyncConfig: DataSyncConfig;+ /**+ * Settings → About → Debug logs: packaged builds also write `debug` records to+ * `<userData>/logs/*.jsonl`. Dev builds always do.+ */+ debugLoggingEnabled: boolean;/*** Explicit completion state for the multi-step desktop onboarding flow.* Undefined preserves the legacy behavior for users who completed onboardingdiff --git a/apps/desktop/src/main/utils/logger.ts b/apps/desktop/src/main/utils/logger.tsindex 95dba0a02fe..0ba2beb979a 100644--- a/apps/desktop/src/main/utils/logger.ts+++ b/apps/desktop/src/main/utils/logger.ts@@ -5,6 +5,9 @@ import electronLog from 'electron-log';import { getDesktopEnv } from '@/env';+import type { LogLevel } from './structuredLog';+import { rawConsole, writeStructuredLog } from './structuredLog';+/*** Electron never sets `NODE_ENV` for packaged builds, and the main bundle reads* env through a `{ ...process.env }` spread, so no build-time define reaches it@@ -24,15 +27,25 @@ electronLog.transports.console.level = isPackagedBuild()? 'info' // Show info level and above in production environment: 'debug'; // Show more logs in development environment+/**+ * Every level reaches `<userData>/logs/main.jsonl` in dev and packaged builds,+ * independent of `DEBUG`; the terminal (`debug`) and `main.log` (electron-log)+ * outputs below keep their previous behavior.+ */+const record = (namespace: string, level: LogLevel, message: unknown, args: unknown[]) =>+ writeStructuredLog({ args, level, message, ns: namespace, process: 'main' });+// Create namespaced debuggerexport const createLogger = (namespace: string) => {const debugLogger = debug(namespace);return {debug: (message, ...args) => {+ record(namespace, 'debug', message, args);debugLogger(message, ...args);},error: (message, ...args) => {+ record(namespace, 'error', message, args);// A packaged build has no console anyone can read, so its errors must reach// the log file. Development keeps `console.error` — the terminal is where a// dev reads them, and electron-log's console transport would print a second@@ -40,10 +53,12 @@ export const createLogger = (namespace: string) => {if (isPackagedBuild()) {electronLog.error(`[${namespace}]`, message, ...args);} else {- console.error(message, ...args);+ // The raw method: the main-process console mirror would record this line twice.+ rawConsole.error(message, ...args);}},info: (message, ...args) => {+ record(namespace, 'info', message, args);if (isPackagedBuild()) {electronLog.info(`[${namespace}]`, message, ...args);}@@ -51,12 +66,14 @@ export const createLogger = (namespace: string) => {debugLogger(`INFO: ${message}`, ...args);},verbose: (message, ...args) => {+ record(namespace, 'debug', message, args);electronLog.verbose(message, ...args);if (getDesktopEnv().DEBUG_VERBOSE) {debugLogger(`VERBOSE: ${message}`, ...args);}},warn: (message, ...args) => {+ record(namespace, 'warn', message, args);if (isPackagedBuild()) {electronLog.warn(`[${namespace}]`, message, ...args);}diff --git a/apps/desktop/src/main/utils/structuredLog/capture.test.ts b/apps/desktop/src/main/utils/structuredLog/capture.test.tsnew file mode 100644index 00000000000..baaae9d5e88--- /dev/null+++ b/apps/desktop/src/main/utils/structuredLog/capture.test.ts@@ -0,0 +1,96 @@+import { EventEmitter } from 'node:events';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ captureMainConsole,+ captureRendererLogs,+ rawConsole,+ recordRendererConsoleMessage,+} from './capture';+import * as sink from './sink';++let write: ReturnType<typeof vi.spyOn>;++beforeEach(() => {+ write = vi.spyOn(sink, 'writeStructuredLog').mockImplementation(() => {});+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('recordRendererConsoleMessage', () => {+ it('maps the Chromium level, the [Tag] namespace and a query-free source', () => {+ recordRendererConsoleMessage('w3', {+ level: 'warning',+ lineNumber: 12,+ message: '[Gateway] Auth failed for operation op_1_a',+ sourceId: 'http://localhost:9926/src/store/gateway.ts?t=123&token=secret',+ });++ expect(write).toHaveBeenCalledWith({+ level: 'warn',+ message: 'Auth failed for operation op_1_a',+ ns: 'renderer:w3:Gateway',+ process: 'renderer',+ source: '/src/store/gateway.ts:12',+ });+ });+});++describe('captureRendererLogs', () => {+ it('records app windows only, not webview guests', () => {+ const app = new EventEmitter();+ captureRendererLogs(app as never);++ const createContents = (type: string, id: number) =>+ Object.assign(new EventEmitter(), { getType: () => type, id });+ const window = createContents('window', 1);+ const webview = createContents('webview', 2);+ app.emit('web-contents-created', {}, window);+ app.emit('web-contents-created', {}, webview);++ const details = { level: 'info', lineNumber: 1, message: 'hello', sourceId: '' };+ window.emit('console-message', details);+ webview.emit('console-message', details);+ window.emit('render-process-gone', {}, { exitCode: 1, reason: 'crashed' });++ expect(write).toHaveBeenCalledTimes(2);+ expect(write).toHaveBeenNthCalledWith(1, expect.objectContaining({ ns: 'renderer:w1' }));+ expect(write).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ level: 'error',+ message: 'renderer w1 gone: crashed',+ process: 'main',+ }),+ );+ });+});++describe('captureMainConsole', () => {+ it('mirrors direct console calls once, and rawConsole bypasses the mirror', () => {+ const saved = { ...console };+ const info = vi.spyOn(console, 'info').mockImplementation(() => {});+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ captureMainConsole();+ console.info('[Menu] Opening logs', { path: '/tmp' });+ rawConsole.error('already recorded');++ expect(info).toHaveBeenCalledWith('[Menu] Opening logs', { path: '/tmp' });+ expect(error).toHaveBeenCalledWith('already recorded');+ expect(write).toHaveBeenCalledTimes(1);+ expect(write).toHaveBeenCalledWith({+ args: [{ path: '/tmp' }],+ level: 'info',+ message: 'Opening logs',+ ns: 'Menu',+ process: 'main',+ });+ } finally {+ Object.assign(console, saved);+ }+ });+});diff --git a/apps/desktop/src/main/utils/structuredLog/capture.ts b/apps/desktop/src/main/utils/structuredLog/capture.tsnew file mode 100644index 00000000000..df0e81e35a4--- /dev/null+++ b/apps/desktop/src/main/utils/structuredLog/capture.ts@@ -0,0 +1,136 @@+import path from 'node:path';++import type { App, WebContents } from 'electron';++import type { LogLevel } from './layout';+import { splitConsoleTag } from './record';+import { writeStructuredLog } from './sink';++const CONSOLE_METHODS = {+ debug: 'debug',+ error: 'error',+ info: 'info',+ log: 'info',+ trace: 'debug',+ warn: 'warn',+} as const satisfies Partial<Record<keyof Console, LogLevel>>;++type ConsoleMethod = keyof typeof CONSOLE_METHODS;++/** The methods replaced by `captureMainConsole`; empty until it runs. */+const originals: Partial<Pick<Console, ConsoleMethod>> = {};++const callRaw =+ (method: ConsoleMethod) =>+ (...args: unknown[]) =>+ (originals[method] ?? console[method])(...args);++/**+ * Console methods that bypass the mirror. `createLogger` prints through these+ * so a line it already recorded is not recorded a second time.+ */+export const rawConsole: Pick<Console, ConsoleMethod> = {+ debug: callRaw('debug'),+ error: callRaw('error'),+ info: callRaw('info'),+ log: callRaw('log'),+ trace: callRaw('trace'),+ warn: callRaw('warn'),+};++/** Mirrors the main process's direct `console.*` calls into `main.jsonl`. */+export const captureMainConsole = () => {+ if (Object.keys(originals).length > 0) return;+ for (const [method, level] of Object.entries(CONSOLE_METHODS) as [ConsoleMethod, LogLevel][]) {+ const original = console[method].bind(console);+ originals[method] = original;+ console[method] = (...args: unknown[]) => {+ original(...args);+ const [first, ...rest] = args;+ const { message, ns } =+ typeof first === 'string' ? splitConsoleTag(first) : { message: first, ns: undefined };+ writeStructuredLog({+ args: rest,+ level,+ message,+ ns: ns ?? 'console',+ process: 'main',+ });+ };+ }+};++const RENDERER_LEVELS: Record<string, LogLevel> = {+ debug: 'debug',+ error: 'error',+ info: 'info',+ warning: 'warn',+};++/** Keeps the path of a script URL; its query string may carry tokens. */+const describeSource = (sourceUrl: string, lineNumber: number) => {+ if (!sourceUrl) return undefined;+ try {+ const url = new URL(sourceUrl);+ return `${url.protocol === 'file:' ? path.basename(url.pathname) : url.pathname}:${lineNumber}`;+ } catch {+ return `${sourceUrl.split('?')[0]}:${lineNumber}`;+ }+};++/** The subset of Electron's `WebContentsConsoleMessageEventParams` that is recorded. */+interface ConsoleMessageDetails {+ level: string;+ lineNumber: number;+ message: string;+ sourceId: string;+}++export const recordRendererConsoleMessage = (+ windowName: string,+ { level, lineNumber, message, sourceId }: ConsoleMessageDetails,+) => {+ const { message: text, ns } = splitConsoleTag(message);+ writeStructuredLog({+ level: RENDERER_LEVELS[level] ?? 'info',+ message: text,+ ns: ns ? `renderer:${windowName}:${ns}` : `renderer:${windowName}`,+ process: 'renderer',+ source: describeSource(sourceId, lineNumber),+ });+};++/**+ * App windows only: `webview` and other guest contents render third-party+ * pages whose console output is neither ours nor safe to keep.+ */+const isAppWindow = (contents: WebContents) => contents.getType() === 'window';++let rendererCaptured = false;++/**+ * Records every app window's console into `renderer.jsonl` from the main+ * process, so the renderer needs no logging bridge and dev and packaged builds+ * capture the same lines. A renderer crash is recorded in `main.jsonl`.+ */+export const captureRendererLogs = (app: Pick<App, 'on'>) => {+ if (rendererCaptured) return;+ rendererCaptured = true;+ app.on('web-contents-created', (_event, contents) => {+ if (!isAppWindow(contents)) return;+ const windowName = `w${contents.id}`;++ contents.on('console-message', (details) => {+ recordRendererConsoleMessage(windowName, details);+ });+ contents.on('render-process-gone', (_goneEvent, details) => {+ writeStructuredLog({+ args: [details],+ level: 'error',+ message: `renderer ${windowName} gone: ${details.reason}`,+ ns: 'renderer-lifecycle',+ process: 'main',+ });+ });+ });+};diff --git a/apps/desktop/src/main/utils/structuredLog/index.ts b/apps/desktop/src/main/utils/structuredLog/index.tsnew file mode 100644index 00000000000..c04d0d71210--- /dev/null+++ b/apps/desktop/src/main/utils/structuredLog/index.ts@@ -0,0 +1,49 @@+import { app } from 'electron';++import { captureMainConsole, captureRendererLogs } from './capture';+import { resolveLogLevel } from './layout';+import {+ closeStructuredLogsSync,+ openStructuredLogs,+ setStructuredLogLevel,+ writeStructuredLog,+} from './sink';++export { rawConsole } from './capture';+export type { LogLevel, LogProcess, LogRecord } from './layout';+export { flushStructuredLogs, getStructuredLogDirectory, writeStructuredLog } from './sink';++/**+ * Starts writing `<userData>/logs/{main,renderer}.jsonl` for this run, in dev and+ * packaged builds alike. Must run after `pre-app-init` pinned `userData`, so+ * every dev instance writes into its own profile.+ */+export const installStructuredLogging = () => {+ captureMainConsole();+ captureRendererLogs(app);+ // Stamp the clean exit as soon as Electron finishes quitting; `process.on('exit')`+ // in the sink runs again later and also covers exits that skip `quit`.+ app.once('quit', (_event, exitCode) => closeStructuredLogsSync({ exitCode }));+ openStructuredLogs({+ appVersion: app.getVersion(),+ isPackaged: app.isPackaged,+ minLevel: resolveLogLevel({ debugLogging: false, isPackaged: app.isPackaged }),+ userDataPath: app.getPath('userData'),+ })+ .then((manifest) =>+ writeStructuredLog({+ args: [{ appVersion: manifest.appVersion, isPackaged: manifest.isPackaged }],+ level: 'info',+ message: 'structured logging started',+ ns: 'structuredLog',+ process: 'main',+ }),+ )+ .catch((error) => {+ process.stderr.write(`[structuredLog] failed to open log files: ${String(error)}\n`);+ });+};++/** Applies the persisted Debug logs setting (`debugLoggingEnabled`) to this run. */+export const applyDebugLogging = (enabled: boolean) =>+ setStructuredLogLevel(resolveLogLevel({ debugLogging: enabled, isPackaged: app.isPackaged }));diff --git a/apps/desktop/src/main/utils/structuredLog/layout.test.ts b/apps/desktop/src/main/utils/structuredLog/layout.test.tsnew file mode 100644index 00000000000..4ef7bcdc9e7--- /dev/null+++ b/apps/desktop/src/main/utils/structuredLog/layout.test.ts@@ -0,0 +1,14 @@+import { describe, expect, it } from 'vitest';++import { resolveLogLevel } from './layout';++describe('resolveLogLevel', () => {+ it('keeps debug records out of packaged builds unless the user enables them', () => {+ expect(resolveLogLevel({ debugLogging: false, isPackaged: true })).toBe('info');+ expect(resolveLogLevel({ debugLogging: true, isPackaged: true })).toBe('debug');+ });++ it('records every level in dev regardless of the setting', () => {+ expect(resolveLogLevel({ debugLogging: false, isPackaged: false })).toBe('debug');+ });+});diff --git a/apps/desktop/src/main/utils/structuredLog/layout.ts b/apps/desktop/src/main/utils/structuredLog/layout.tsnew file mode 100644index 00000000000..183494e4584--- /dev/null+++ b/apps/desktop/src/main/utils/structuredLog/layout.ts@@ -0,0 +1,79 @@+/**+ * On-disk layout of the structured Desktop logs. `scripts/desktopLogs.mts` reads+ * the same files without importing this module (it runs under plain `node`), so+ * `scripts/__tests__/desktopLogs.test.mts` pins both copies to the same values.+ */++/** Directory under the profile (`app.getPath('userData')`), so each dev instance keeps its own logs. */+export const LOG_DIRECTORY_NAME = 'logs';+export const LOG_MANIFEST_FILE = 'manifest.json';++export const LOG_PROCESSES = ['main', 'renderer'] as const;+export type LogProcess = (typeof LOG_PROCESSES)[number];++export const getLogFileName = (process: LogProcess) => `${process}.jsonl`;++export const LOG_LEVELS = ['debug', 'info', 'warn', 'error'] as const;+export type LogLevel = (typeof LOG_LEVELS)[number];++export const LOG_LEVEL_RANK: Record<LogLevel, number> = {+ debug: 10,+ error: 40,+ info: 20,+ warn: 30,+};++/**+ * Live-file ceiling before rotation. Sized for the `debug` default: a smaller+ * file rotates the incident away before anyone reads it.+ */+export const MAX_LOG_BYTES = 20 * 1024 * 1024;+/** Rotated generations kept next to the live file (`main.jsonl.1` … `.3`, oldest last). */+export const MAX_LOG_GENERATIONS = 3;++/** One line of `main.jsonl` / `renderer.jsonl`. */+export interface LogRecord {+ appVersion?: string;+ /** Extra arguments after the message, JSON-safe and secret-redacted. */+ args?: unknown[];+ level: LogLevel;+ msg: string;+ /** Logger namespace (`createLogger(ns)`), the `[Tag]` prefix of a console line, or `renderer:<window>`. */+ ns?: string;+ /** First `op_…` id in the record; joins client logs with the server's agent trace. */+ operationId?: string;+ pid: number;+ process: LogProcess;+ /** Renderer only: script location of the console call. */+ source?: string;+ /** First `tpc_…` id in the record. */+ topicId?: string;+ ts: string;+}++export interface LogManifest {+ appVersion?: string;+ /** Set when the process exits; absent while the app runs or after a kill or hard crash. */+ endedAt?: string;+ /** Process exit code at `endedAt`; non-zero means the run ended in an error, not a clean quit. */+ exitCode?: number;+ files: Record<LogProcess, string>;+ isPackaged: boolean;+ pid: number;+ startedAt: string;+ userData: string;+}++/**+ * Packaged builds keep `info` and above unless the user turns on Settings →+ * About → Debug logs, like VS Code's default log level: `debug` is ~90% of the+ * volume, carries URLs, paths and config values, and is only needed while+ * reproducing a bug. Dev always records everything.+ */+export const resolveLogLevel = ({+ debugLogging,+ isPackaged,+}: {+ debugLogging: boolean;+ isPackaged: boolean;+}): LogLevel => (!isPackaged || debugLogging ? 'debug' : 'info');diff --git a/apps/desktop/src/main/utils/structuredLog/record.test.ts b/apps/desktop/src/main/utils/structuredLog/record.test.tsnew file mode 100644index 00000000000..95b254ab53a--- /dev/null+++ b/apps/desktop/src/main/utils/structuredLog/record.test.ts@@ -0,0 +1,188 @@+import { describe, expect, it } from 'vitest';++import {+ createLogRecord,+ MAX_RECORD_BYTES,+ serializeLogRecord,+ splitConsoleTag,+ toLogValue,+} from './record';++const now = new Date('2026-11-12T10:00:00.123Z');++describe('createLogRecord', () => {+ it('extracts the operation and topic ids a server trace is keyed by', () => {+ const operationId = 'op_1762900000000_agt_abc123_tpc_xyz789_Ab-d_12x';+ const record = createLogRecord({+ args: [{ operationId }],+ level: 'info',+ message: 'gateway connected',+ now,+ ns: 'Gateway',+ pid: 42,+ process: 'main',+ });++ expect(record).toEqual({+ args: [{ operationId }],+ level: 'info',+ msg: 'gateway connected',+ ns: 'Gateway',+ operationId,+ pid: 42,+ process: 'main',+ topicId: 'tpc_xyz789',+ ts: '2026-11-12T10:00:00.123Z',+ });+ });++ it('formats printf-style messages and drops the consumed arguments', () => {+ const record = createLogRecord({+ args: ['main', 12],+ level: 'debug',+ message: 'loaded %s in %dms',+ now,+ process: 'main',+ });++ expect(record.msg).toBe('loaded main in 12ms');+ expect(record.args).toBeUndefined();+ });++ it('keeps a non-string message as the first argument', () => {+ const record = createLogRecord({+ level: 'error',+ message: new Error('boom'),+ now,+ process: 'main',+ });++ expect(record.msg).toBe('');+ expect(record.args?.[0]).toMatchObject({ message: 'boom', name: 'Error' });+ });++ it('redacts bearer tokens, JWTs and secret-named fields', () => {+ const jwt = 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.abcdefghijklmnop';+ const record = createLogRecord({+ args: [{ accessToken: 'plain', headers: { authorization: 'x' }, note: jwt }],+ level: 'info',+ message: 'Authorization: Bearer abc.def-123',+ now,+ process: 'main',+ });++ expect(record.msg).toBe('Authorization: [REDACTED]');+ expect(record.args).toEqual([+ {+ accessToken: '[REDACTED]',+ headers: { authorization: '[REDACTED]' },+ note: '[REDACTED_JWT]',+ },+ ]);+ });+});++describe('createLogRecord secret redaction in text', () => {+ it('redacts secret-named fields that a format specifier prints', () => {+ const record = createLogRecord({+ args: [{ password: 'hunter2-fake', user: 'a' }],+ level: 'debug',+ message: 'login payload %O',+ now,+ process: 'main',+ });++ expect(record.msg).not.toContain('hunter2-fake');+ expect(record.msg).toContain('[REDACTED]');+ });++ it('redacts cookies, stringified secret fields and credential query parameters', () => {+ const message = [+ 'Cookie: session=fake-session; theme=dark',+ JSON.stringify({ apiKey: 'fake-api-key-value', host: 'example.com' }),+ 'GET https://example.com/v1?key=AIzaFakeKey&access_token=fake-token&page=2',+ ].join(' | ');+ const record = createLogRecord({ level: 'info', message, now, process: 'main' });++ for (const secret of ['fake-session', 'fake-api-key-value', 'AIzaFakeKey', 'fake-token'])+ expect(record.msg).not.toContain(secret);+ expect(record.msg).toContain('"host":"example.com"');+ expect(record.msg).toContain('page=2');+ });++ it('redacts URL userinfo but keeps the host', () => {+ const record = createLogRecord({+ level: 'debug',+ message: 'Testing proxy with URL: http://alice:[email protected]:8080',+ now,+ process: 'main',+ });++ expect(record.msg).toBe('Testing proxy with URL: http://[REDACTED]@proxy.example.com:8080');+ expect(+ createLogRecord({+ level: 'info',+ message: 'mailto [email protected] https://example.com/a@b',+ now,+ process: 'main',+ }).msg,+ ).toBe('mailto [email protected] https://example.com/a@b');+ });++ it('redacts numeric, uuid-like and quoted secret values', () => {+ const record = createLogRecord({+ level: 'debug',+ message:+ "password=123456 access_token=12345678-abcd-4321-8abc-123456789abc secret='FAKE PASS' token: 987654",+ now,+ process: 'main',+ });++ for (const secret of ['123456', '12345678-abcd', 'FAKE PASS', '987654'])+ expect(record.msg).not.toContain(secret);+ });++ it('keeps token counts and flags readable', () => {+ const record = createLogRecord({+ level: 'info',+ message: 'usage inputTokens: 532, outputTokens=40, tokenExpired: false',+ now,+ process: 'main',+ });++ expect(record.msg).toBe('usage inputTokens: 532, outputTokens=40, tokenExpired: false');+ });+});++describe('toLogValue', () => {+ it('survives circular references and bounds depth', () => {+ const value: Record<string, unknown> = { a: { b: { c: { d: { e: 1 } } } } };+ value.self = value;++ expect(toLogValue(value)).toEqual({ a: { b: { c: { d: '[Object]' } } }, self: '[Circular]' });+ });+});++describe('serializeLogRecord', () => {+ it('drops oversized args but keeps the message', () => {+ const record = createLogRecord({+ args: [Array.from({ length: 40 }, () => 'x'.repeat(3000))],+ level: 'info',+ message: 'huge payload',+ now,+ process: 'main',+ });+ const line = serializeLogRecord(record);++ expect(line.length).toBeLessThan(MAX_RECORD_BYTES);+ expect(JSON.parse(line)).toMatchObject({ msg: 'huge payload' });+ expect(JSON.parse(line).args[0]).toMatch(/^\[args dropped/);+ });+});++describe('splitConsoleTag', () => {+ it('turns a leading [Tag] into the namespace', () => {+ expect(splitConsoleTag('[Menu] Opening logs')).toEqual({ message: 'Opening logs', ns: 'Menu' });+ expect(splitConsoleTag('plain line')).toEqual({ message: 'plain line' });+ });+});diff --git a/apps/desktop/src/main/utils/structuredLog/record.ts b/apps/desktop/src/main/utils/structuredLog/record.tsnew file mode 100644index 00000000000..f7c4aa97aa3--- /dev/null+++ b/apps/desktop/src/main/utils/structuredLog/record.ts@@ -0,0 +1,186 @@+import { format } from 'node:util';++import type { LogLevel, LogProcess, LogRecord } from './layout';++const MAX_DEPTH = 4;+const MAX_STRING_LENGTH = 4000;+const MAX_ARRAY_ITEMS = 50;+const MAX_OBJECT_KEYS = 50;+/** A larger record keeps its message and loses its `args`, so one huge payload cannot flood the file. */+export const MAX_RECORD_BYTES = 64 * 1024;++/**+ * Server ids, `op_${Date.now()}_${agentId}_${topicId}_${nanoid}` and `tpc_…`+ * (`packages/database/src/utils/idGenerator.ts`). The topic pattern also matches+ * inside an operation id, so a record that only names the operation still+ * carries its topic.+ */+const OPERATION_ID_PATTERN = /(?<![\w-])op_[\w-]+/;+const TOPIC_ID_PATTERN = /(?<![A-Za-z0-9])tpc_[A-Za-z0-9]+/;++/**+ * A secret-named key in text. Plural `tokens` is excluded so usage counters such+ * as `inputTokens: 532` stay readable; every other secret key is redacted+ * whatever its value looks like, since a password or token can be all digits.+ */+const SECRET_KEY = String.raw`[\w-]*(?:token(?!s(?![a-z]))|secret|password|passwd|authorization|api[-_]?key|apikey|credential)[\w-]*`;++const SECRET_PATTERNS: [RegExp, string][] = [+ // A cookie header carries several `name=value` pairs; drop the whole value.+ [/(\b(?:set-)?cookie["']?\s*[:=]\s*["']?)[^"'\n]+/gi, '$1[REDACTED]'],+ // `"accessToken":"…"` in stringified JSON (`JSON.stringify(headers)`).+ [new RegExp(String.raw`("${SECRET_KEY}"\s*:\s*")[^"]*`, 'gi'), '$1[REDACTED]'],+ // `password=…`, `api_key: …`, and URL query parameters such as `?access_token=…`.+ // Boolean and null literals stay readable (`tokenExpired: false`); quoted values+ // are redacted whole.+ [+ new RegExp(+ String.raw`(\b${SECRET_KEY}\s*[=:]\s*)(?!(?:true|false|null|undefined)(?![\w-]))(?:(?:bearer|basic)\s+)?(?:"[^"]*"|'[^']*'|[^\s&;,"']+)`,+ 'gi',+ ),+ '$1[REDACTED]',+ ],+ // URL userinfo: authenticated proxy URLs (`http://user:pass@host`) reach debug lines.+ [/(\b[a-z][\d+.a-z-]*:\/\/)[^\s/?#@]+@/gi, '$1[REDACTED]@'],+ // Short query names that commonly carry credentials (`?key=AIza…`, presigned `sig=`).+ [/([?&](?:key|sig|signature|code)=)[^&\s"']+/gi, '$1[REDACTED]'],+ [/(bearer\s+)[\w.~+/-]+=*/gi, '$1[REDACTED]'],+ // JWTs: access/refresh tokens are the most likely secret to reach a log line.+ [/eyJ[\w-]{8,}\.[\w-]{8,}\.[\w-]{8,}/g, '[REDACTED_JWT]'],+ [/\bsk-[\w-]{16,}/g, '[REDACTED_KEY]'],+];+const SECRET_KEY_PATTERN = /token|secret|password|authorization|cookie|api[-_]?key/i;++export const redactSecrets = (value: string) =>+ SECRET_PATTERNS.reduce(+ (text, [pattern, replacement]) => text.replace(pattern, replacement),+ value,+ );++const truncate = (value: string) =>+ value.length > MAX_STRING_LENGTH+ ? `${value.slice(0, MAX_STRING_LENGTH)}…[${value.length - MAX_STRING_LENGTH} more chars]`+ : value;++/** Converts one log argument into a JSON-safe, bounded, secret-redacted value. */+export const toLogValue = (value: unknown, depth = 0, seen = new WeakSet<object>()): unknown => {+ if (typeof value === 'string') return truncate(redactSecrets(value));+ if (value === null || typeof value === 'number' || typeof value === 'boolean') return value;+ if (value === undefined) return '[undefined]';+ if (typeof value === 'bigint') return `${value}n`;+ if (typeof value === 'symbol' || typeof value === 'function') return String(value);++ const object = value as object;+ if (seen.has(object)) return '[Circular]';+ if (depth >= MAX_DEPTH) return Array.isArray(object) ? '[Array]' : '[Object]';+ seen.add(object);++ if (object instanceof Error) {+ const { cause, code } = object as Error & { code?: unknown };+ return {+ message: toLogValue(object.message, depth + 1, seen),+ name: object.name,+ ...(object.stack ? { stack: toLogValue(object.stack, depth + 1, seen) } : undefined),+ ...(code === undefined ? undefined : { code: toLogValue(code, depth + 1, seen) }),+ ...(cause === undefined ? undefined : { cause: toLogValue(cause, depth + 1, seen) }),+ };+ }+ if (object instanceof Date) return object.toISOString();+ if (Array.isArray(object)) {+ const items = object.slice(0, MAX_ARRAY_ITEMS).map((item) => toLogValue(item, depth + 1, seen));+ if (object.length > MAX_ARRAY_ITEMS) items.push(`[${object.length - MAX_ARRAY_ITEMS} more]`);+ return items;+ }+ if (object instanceof Map) return toLogValue(Object.fromEntries(object), depth, seen);+ if (object instanceof Set) return toLogValue([...object], depth, seen);+ if (ArrayBuffer.isView(object)) return `[${object.constructor.name} ${object.byteLength} bytes]`;++ const entries = Object.entries(object);+ const result: Record<string, unknown> = {};+ for (const [key, item] of entries.slice(0, MAX_OBJECT_KEYS)) {+ result[key] =+ SECRET_KEY_PATTERN.test(key) && typeof item === 'string'+ ? '[REDACTED]'+ : toLogValue(item, depth + 1, seen);+ }+ if (entries.length > MAX_OBJECT_KEYS)+ result['…'] = `${entries.length - MAX_OBJECT_KEYS} more keys`;+ return result;+};++const hasFormatSpecifier = (message: string) => /%[sdifjoOc%]/.test(message);++export interface CreateLogRecordInput {+ appVersion?: string;+ args?: unknown[];+ level: LogLevel;+ message: unknown;+ now?: Date;+ ns?: string;+ pid?: number;+ process: LogProcess;+ source?: string;+}++export const createLogRecord = ({+ appVersion,+ args = [],+ level,+ message,+ now = new Date(),+ ns,+ pid = globalThis.process.pid,+ process,+ source,+}: CreateLogRecordInput): LogRecord => {+ let msg: string;+ let rest = args;+ if (typeof message === 'string' && rest.length > 0 && hasFormatSpecifier(message)) {+ // `debug`-style `logger.debug('loaded %s in %dms', a, b)`: the formatted text is+ // what a reader greps for, and its arguments are consumed by the format.+ // Sanitize first: `%O` / `%j` would otherwise print secret-named fields verbatim.+ msg = format(message, ...rest.map((arg) => toLogValue(arg)));+ rest = [];+ } else if (typeof message === 'string') {+ msg = message;+ } else {+ msg = '';+ rest = [message, ...rest];+ }+ msg = truncate(redactSecrets(msg));++ const safeArgs = rest.map((arg) => toLogValue(arg));+ const haystack = safeArgs.length > 0 ? `${msg} ${JSON.stringify(safeArgs)}` : msg;+ const operationId = OPERATION_ID_PATTERN.exec(haystack)?.[0];+ const topicId = TOPIC_ID_PATTERN.exec(haystack)?.[0];++ return {+ ...(safeArgs.length > 0 ? { args: safeArgs } : undefined),+ ...(appVersion ? { appVersion } : undefined),+ level,+ msg,+ ...(ns ? { ns } : undefined),+ ...(operationId ? { operationId } : undefined),+ pid,+ process,+ ...(source ? { source } : undefined),+ ...(topicId ? { topicId } : undefined),+ ts: now.toISOString(),+ };+};++/** Serializes a record to one JSONL line, dropping `args` when the line would exceed the cap. */+export const serializeLogRecord = (record: LogRecord): string => {+ const line = JSON.stringify(record);+ if (line.length <= MAX_RECORD_BYTES || !record.args) return `${line}\n`;+ const { args: _args, ...rest } = record;+ return `${JSON.stringify({ ...rest, args: [`[args dropped: ${line.length} chars]`] })}\n`;+};++const TAG_PATTERN = /^\[([^\]]{1,80})\]\s*/;++/** `console.info('[Menu] Opening …')` → namespace `Menu`, message `Opening …`. */+export const splitConsoleTag = (message: string): { message: string; ns?: string } => {+ const match = TAG_PATTERN.exec(message);+ return match ? { message: message.slice(match[0].length), ns: match[1] } : { message };+};diff --git a/apps/desktop/src/main/utils/structuredLog/sink.test.ts b/apps/desktop/src/main/utils/structuredLog/sink.test.tsnew file mode 100644index 00000000000..f649a18dffc--- /dev/null+++ b/apps/desktop/src/main/utils/structuredLog/sink.test.ts@@ -0,0 +1,103 @@+import { mkdtemp, readFile, rm } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import {+ closeStructuredLogsSync,+ flushStructuredLogs,+ openStructuredLogs,+ resetStructuredLogsForTest,+ setStructuredLogLevel,+ writeStructuredLog,+} from './sink';++let userDataPath: string;++beforeEach(async () => {+ resetStructuredLogsForTest();+ userDataPath = await mkdtemp(path.join(os.tmpdir(), 'structured-log-sink-'));+});++afterEach(async () => {+ resetStructuredLogsForTest();+ await rm(userDataPath, { force: true, recursive: true });+});++const readRecords = async (file: string) =>+ (await readFile(path.join(userDataPath, 'logs', file), 'utf8'))+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line));++describe('structured log sink', () => {+ it('writes lines logged before opening, per process, at or above the minimum level', async () => {+ writeStructuredLog({+ level: 'info',+ message: 'logged while importing',+ ns: 'early',+ process: 'main',+ });+ writeStructuredLog({ level: 'debug', message: 'below minimum', process: 'main' });++ await openStructuredLogs({+ appVersion: '9.9.9',+ isPackaged: true,+ minLevel: 'info',+ userDataPath,+ });+ writeStructuredLog({ level: 'warn', message: 'window warning', process: 'renderer' });+ await flushStructuredLogs();++ expect(await readRecords('main.jsonl')).toEqual([+ expect.objectContaining({ appVersion: '9.9.9', msg: 'logged while importing', ns: 'early' }),+ ]);+ expect(await readRecords('renderer.jsonl')).toEqual([+ expect.objectContaining({ level: 'warn', msg: 'window warning', process: 'renderer' }),+ ]);+ });++ it('writes a manifest that is stamped with endedAt on a clean exit', async () => {+ await openStructuredLogs({+ isPackaged: false,+ minLevel: 'debug',+ now: () => new Date('2026-11-12T10:00:00.000Z'),+ userDataPath,+ });+ const manifestPath = path.join(userDataPath, 'logs', 'manifest.json');++ expect(JSON.parse(await readFile(manifestPath, 'utf8'))).toEqual({+ files: { main: 'main.jsonl', renderer: 'renderer.jsonl' },+ isPackaged: false,+ pid: process.pid,+ startedAt: '2026-11-12T10:00:00.000Z',+ userData: userDataPath,+ });++ closeStructuredLogsSync({ endedAt: new Date('2026-11-12T11:00:00.000Z'), exitCode: 0 });+ expect(JSON.parse(await readFile(manifestPath, 'utf8'))).toMatchObject({+ endedAt: '2026-11-12T11:00:00.000Z',+ exitCode: 0,+ });++ closeStructuredLogsSync({ endedAt: new Date('2026-11-12T11:00:01.000Z'), exitCode: 7 });+ expect(JSON.parse(await readFile(manifestPath, 'utf8'))).toMatchObject({ exitCode: 7 });+ });++ it('applies a level set before open to buffered startup lines, and changes it live', async () => {+ writeStructuredLog({ level: 'debug', message: 'startup debug', process: 'main' });+ setStructuredLogLevel('debug');+ await openStructuredLogs({ isPackaged: true, minLevel: 'info', userDataPath });++ setStructuredLogLevel('info');+ writeStructuredLog({ level: 'debug', message: 'after switching off', process: 'main' });+ writeStructuredLog({ level: 'info', message: 'still recorded', process: 'main' });+ await flushStructuredLogs();++ expect((await readRecords('main.jsonl')).map((record) => record.msg)).toEqual([+ 'startup debug',+ 'still recorded',+ ]);+ });+});diff --git a/apps/desktop/src/main/utils/structuredLog/sink.ts b/apps/desktop/src/main/utils/structuredLog/sink.tsnew file mode 100644index 00000000000..57678f17aaf--- /dev/null+++ b/apps/desktop/src/main/utils/structuredLog/sink.ts@@ -0,0 +1,178 @@+import { writeFileSync } from 'node:fs';+import { mkdir, writeFile } from 'node:fs/promises';+import path from 'node:path';++import type { LogLevel, LogManifest, LogProcess } from './layout';+import {+ getLogFileName,+ LOG_DIRECTORY_NAME,+ LOG_LEVEL_RANK,+ LOG_MANIFEST_FILE,+ LOG_PROCESSES,+} from './layout';+import { createLogRecord, serializeLogRecord } from './record';+import { JsonlLogWriter } from './writer';++/**+ * Records logged before `openStructuredLogs()` (module-scope logger calls run+ * while the main bundle is still importing) wait here, bounded, and reach the+ * file once it opens.+ */+const MAX_EARLY_LINES = 1000;++export interface LogEntry {+ args?: unknown[];+ level: LogLevel;+ message: unknown;+ ns?: string;+ process: LogProcess;+ source?: string;+}++export interface OpenStructuredLogsOptions {+ appVersion?: string;+ isPackaged: boolean;+ minLevel: LogLevel;+ now?: () => Date;+ userDataPath: string;+}++interface OpenState {+ appVersion?: string;+ manifest: LogManifest;+ manifestPath: string;+ minRank: number;+ writers: Record<LogProcess, JsonlLogWriter>;+}++let state: OpenState | undefined;+let earlyEntries: { entry: LogEntry; now: Date }[] = [];+/** A level set before the files open; it wins over `minLevel` at open time. */+let pendingMinLevel: LogLevel | undefined;++const writeEntry = (open: OpenState, entry: LogEntry, now: Date) => {+ if (LOG_LEVEL_RANK[entry.level] < open.minRank) return;+ const line = serializeLogRecord(createLogRecord({ ...entry, appVersion: open.appVersion, now }));+ open.writers[entry.process].write(line, { urgent: entry.level === 'error' });+};++/** Appends one record to `<userData>/logs/<process>.jsonl`. Never throws. */+export const writeStructuredLog = (entry: LogEntry) => {+ try {+ const now = new Date();+ if (state) {+ writeEntry(state, entry, now);+ } else if (earlyEntries.length < MAX_EARLY_LINES) {+ earlyEntries.push({ entry, now });+ }+ } catch {+ // Logging must not break the caller.+ }+};++export const getStructuredLogDirectory = () =>+ state ? path.dirname(state.manifestPath) : undefined;++/**+ * Opens the log files for this run and writes `manifest.json`, which lets+ * `scripts/desktopLogs.mts` find the files and tell a live run from a dead one.+ */+export const openStructuredLogs = async ({+ appVersion,+ isPackaged,+ minLevel,+ now = () => new Date(),+ userDataPath,+}: OpenStructuredLogsOptions) => {+ if (state) return state.manifest;++ const directory = path.join(userDataPath, LOG_DIRECTORY_NAME);+ await mkdir(directory, { recursive: true });++ const files = Object.fromEntries(+ LOG_PROCESSES.map((process) => [process, getLogFileName(process)]),+ ) as Record<LogProcess, string>;+ const manifest: LogManifest = {+ ...(appVersion ? { appVersion } : undefined),+ files,+ isPackaged,+ pid: process.pid,+ startedAt: now().toISOString(),+ userData: userDataPath,+ };+ const manifestPath = path.join(directory, LOG_MANIFEST_FILE);+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);++ const open: OpenState = {+ appVersion,+ manifest,+ manifestPath,+ minRank: LOG_LEVEL_RANK[pendingMinLevel ?? minLevel],+ writers: Object.fromEntries(+ LOG_PROCESSES.map((process) => [+ process,+ new JsonlLogWriter({ filePath: path.join(directory, files[process]), process }),+ ]),+ ) as Record<LogProcess, JsonlLogWriter>,+ };+ state = open;++ for (const { entry, now: at } of earlyEntries) writeEntry(open, entry, at);+ earlyEntries = [];++ process.once('exit', (exitCode) => closeStructuredLogsSync({ endedAt: now(), exitCode }));+ return manifest;+};++/**+ * Changes the lowest recorded level for the rest of the run. Before the files+ * open it applies to the buffered early lines too, so a user who enabled debug+ * logs also keeps the startup debug lines.+ */+export const setStructuredLogLevel = (level: LogLevel) => {+ if (state) state.minRank = LOG_LEVEL_RANK[level];+ else pendingMinLevel = level;+};++export const flushStructuredLogs = async () => {+ if (!state) return;+ await Promise.all(Object.values(state.writers).map((writer) => writer.flush()));+};++/**+ * Exit hook: flush what is queued and stamp `endedAt` with the exit code, so a+ * manifest without `endedAt` means a kill or hard crash and a non-zero+ * `exitCode` means the process exited on an error (an uncaught exception exits+ * through the same `exit` event). Runs on `quit` and again on `exit`; the last+ * call wins.+ */+export const closeStructuredLogsSync = ({+ endedAt = new Date(),+ exitCode,+}: { endedAt?: Date; exitCode?: number } = {}) => {+ if (!state) return;+ for (const writer of Object.values(state.writers)) writer.flushSync();+ try {+ writeFileSync(+ state.manifestPath,+ `${JSON.stringify(+ {+ ...state.manifest,+ endedAt: endedAt.toISOString(),+ ...(exitCode === undefined ? undefined : { exitCode }),+ },+ null,+ 2,+ )}\n`,+ );+ } catch {+ // Nothing left to report to at exit.+ }+};++/** Test-only: forget the open files and the early buffer. */+export const resetStructuredLogsForTest = () => {+ state = undefined;+ earlyEntries = [];+ pendingMinLevel = undefined;+};diff --git a/apps/desktop/src/main/utils/structuredLog/writer.test.ts b/apps/desktop/src/main/utils/structuredLog/writer.test.tsnew file mode 100644index 00000000000..6b57663fdeb--- /dev/null+++ b/apps/desktop/src/main/utils/structuredLog/writer.test.ts@@ -0,0 +1,90 @@+import { readFileSync } from 'node:fs';+import { mkdtemp, readFile, rm, stat } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { JsonlLogWriter } from './writer';++let directory: string;++beforeEach(async () => {+ directory = await mkdtemp(path.join(os.tmpdir(), 'structured-log-writer-'));+});++afterEach(async () => {+ await rm(directory, { force: true, recursive: true });+});++const line = (index: number) => `${JSON.stringify({ index, msg: 'x'.repeat(40) })}\n`;++describe('JsonlLogWriter', () => {+ it('appends queued lines in order', async () => {+ const filePath = path.join(directory, 'main.jsonl');+ const writer = new JsonlLogWriter({ filePath, process: 'main' });+ writer.write(line(1));+ writer.write(line(2));+ await writer.flush();++ expect(await readFile(filePath, 'utf8')).toBe(line(1) + line(2));+ });++ it('rotates past the size cap and keeps a bounded number of generations', async () => {+ const filePath = path.join(directory, 'main.jsonl');+ const writer = new JsonlLogWriter({+ filePath,+ maxBytes: line(0).length * 2,+ maxGenerations: 2,+ process: 'main',+ });+ for (let index = 0; index < 8; index += 1) {+ writer.write(line(index));+ await writer.flush();+ }++ expect(await readFile(filePath, 'utf8')).toBe(line(6) + line(7));+ expect(await readFile(`${filePath}.1`, 'utf8')).toBe(line(4) + line(5));+ expect(await readFile(`${filePath}.2`, 'utf8')).toBe(line(2) + line(3));+ await expect(stat(`${filePath}.3`)).rejects.toThrow();+ });++ it('drops lines past the pending cap and records how many', async () => {+ const filePath = path.join(directory, 'main.jsonl');+ const writer = new JsonlLogWriter({+ filePath,+ maxPendingBytes: line(0).length * 2,+ process: 'main',+ });+ for (let index = 0; index < 5; index += 1) writer.write(line(index));+ await writer.flush();++ const lines = (await readFile(filePath, 'utf8')).trim().split('\n');+ expect(lines.slice(0, 2)).toEqual([line(0).trim(), line(1).trim()]);+ expect(JSON.parse(lines[2])).toMatchObject({+ level: 'warn',+ msg: expect.stringContaining('dropped 3'),+ process: 'main',+ });+ });++ it('flushSync writes what is still queued, for the exit hook', async () => {+ const filePath = path.join(directory, 'main.jsonl');+ const writer = new JsonlLogWriter({ filePath, process: 'main' });+ writer.write(line(1));+ writer.flushSync();++ expect(await readFile(filePath, 'utf8')).toBe(line(1));+ });++ it('flushSync keeps a batch whose async append is still pending at exit', async () => {+ const filePath = path.join(directory, 'main.jsonl');+ const writer = new JsonlLogWriter({ filePath, process: 'main' });+ writer.write(line(1));+ const pending = writer.flush();+ writer.flushSync();++ expect(readFileSync(filePath, 'utf8')).toContain(line(1));+ await pending;+ });+});diff --git a/apps/desktop/src/main/utils/structuredLog/writer.ts b/apps/desktop/src/main/utils/structuredLog/writer.tsnew file mode 100644index 00000000000..a4d890451f1--- /dev/null+++ b/apps/desktop/src/main/utils/structuredLog/writer.ts@@ -0,0 +1,183 @@+import { appendFileSync } from 'node:fs';+import { appendFile, mkdir, rename, rm, stat } from 'node:fs/promises';+import path from 'node:path';++import type { LogProcess } from './layout';+import { MAX_LOG_BYTES, MAX_LOG_GENERATIONS } from './layout';+import { createLogRecord, serializeLogRecord } from './record';++/**+ * Past this many queued bytes new lines are dropped (and counted) instead of+ * growing the heap while the disk does not respond.+ */+const MAX_PENDING_BYTES = 4 * 1024 * 1024;+/** Batches lines so a chatty `debug` stream costs one append per window, not one per line. */+const FLUSH_DELAY_MS = 200;++export interface JsonlLogWriterOptions {+ filePath: string;+ flushDelayMs?: number;+ maxBytes?: number;+ maxGenerations?: number;+ maxPendingBytes?: number;+ /** Stamped on the writer's own dropped-lines warning so `desktop:logs` process filters keep it. */+ process: LogProcess;+}++/**+ * Buffered, size-rotated JSONL appender. `write()` only enqueues; one drain at a+ * time appends the batch with `fs/promises`, so a stalled disk backs lines up in+ * memory instead of blocking the main process event loop. `flushSync()` exists+ * only for the `process.on('exit')` hook, which cannot await.+ */+export class JsonlLogWriter {+ readonly filePath: string;+ private readonly flushDelayMs: number;+ private readonly maxBytes: number;+ private readonly maxGenerations: number;+ private readonly maxPendingBytes: number;+ private readonly process: LogProcess;++ private bytesWritten: number | undefined;+ private draining: Promise<void> | undefined;+ /** The batch `drain()` has taken but not yet confirmed on disk. */+ private inFlight: string | undefined;+ private droppedLines = 0;+ private pending: string[] = [];+ private pendingBytes = 0;+ private timer: ReturnType<typeof setTimeout> | undefined;++ constructor({+ filePath,+ flushDelayMs = FLUSH_DELAY_MS,+ maxBytes = MAX_LOG_BYTES,+ maxGenerations = MAX_LOG_GENERATIONS,+ maxPendingBytes = MAX_PENDING_BYTES,+ process,+ }: JsonlLogWriterOptions) {+ this.filePath = filePath;+ this.flushDelayMs = flushDelayMs;+ this.maxBytes = maxBytes;+ this.maxGenerations = maxGenerations;+ this.maxPendingBytes = maxPendingBytes;+ this.process = process;+ }++ /** Queues one complete line (ending in `\n`). `urgent` flushes on the next tick, for errors. */+ write(line: string, { urgent = false }: { urgent?: boolean } = {}) {+ if (this.pendingBytes >= this.maxPendingBytes) {+ this.droppedLines += 1;+ return;+ }+ this.pending.push(line);+ this.pendingBytes += Buffer.byteLength(line);+ this.schedule(urgent ? 0 : this.flushDelayMs);+ }++ /** Resolves once every line queued before the call is on disk. */+ async flush(): Promise<void> {+ if (this.timer) {+ clearTimeout(this.timer);+ this.timer = undefined;+ }+ while (this.draining || this.hasWork()) {+ this.draining ??= this.drain().finally(() => {+ this.draining = undefined;+ });+ await this.draining;+ }+ }++ /**+ * Synchronous last-chance write for `process.on('exit')`; skips rotation. It also+ * rewrites a batch whose async append has not resolved, because the process exits+ * before that append is known to land: a possible duplicate line beats a lost+ * final batch, which is usually the one that explains the exit.+ */+ flushSync() {+ const batch = [this.inFlight, this.takeBatch()].filter(Boolean).join('');+ this.inFlight = undefined;+ if (!batch) return;+ try {+ appendFileSync(this.filePath, batch);+ } catch {+ // Nowhere left to report a failed log write at exit.+ }+ }++ private hasWork() {+ return this.pending.length > 0 || this.droppedLines > 0;+ }++ private schedule(delayMs: number) {+ if (this.draining) return;+ if (this.timer) {+ if (delayMs > 0) return;+ clearTimeout(this.timer);+ }+ this.timer = setTimeout(() => {+ this.timer = undefined;+ void this.flush();+ }, delayMs);+ this.timer.unref?.();+ }++ private takeBatch(): string | undefined {+ if (!this.hasWork()) return undefined;+ const lines = this.pending;+ if (this.droppedLines > 0) {+ lines.push(+ serializeLogRecord(+ createLogRecord({+ level: 'warn',+ message: `dropped ${this.droppedLines} log lines while the disk was not keeping up`,+ ns: 'structuredLog',+ process: this.process,+ }),+ ),+ );+ }+ this.pending = [];+ this.pendingBytes = 0;+ this.droppedLines = 0;+ return lines.join('');+ }++ private async drain() {+ const batch = this.takeBatch();+ if (!batch) return;+ this.inFlight = batch;+ try {+ const size = Buffer.byteLength(batch);+ if (this.bytesWritten === undefined) {+ await mkdir(path.dirname(this.filePath), { recursive: true });+ this.bytesWritten = await stat(this.filePath).then(+ (stats) => stats.size,+ () => 0,+ );+ }+ if (this.bytesWritten > 0 && this.bytesWritten + size > this.maxBytes) await this.rotate();+ await appendFile(this.filePath, batch);+ this.bytesWritten += size;+ this.inFlight = undefined;+ } catch (error) {+ // A log write must never take the app down; the next batch retries the file.+ this.bytesWritten = undefined;+ this.inFlight = undefined;+ process.stderr.write(`[structuredLog] failed to write ${this.filePath}: ${String(error)}\n`);+ }+ }++ private async rotate() {+ await rm(`${this.filePath}.${this.maxGenerations}`, { force: true });+ for (let generation = this.maxGenerations - 1; generation >= 1; generation -= 1) {+ await rename(`${this.filePath}.${generation}`, `${this.filePath}.${generation + 1}`).catch(+ (error: NodeJS.ErrnoException) => {+ if (error.code !== 'ENOENT') throw error;+ },+ );+ }+ await rename(this.filePath, `${this.filePath}.1`);+ this.bytesWritten = 0;+ }+}diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 80f63873da8..cebe3d44ebc 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1377,6 +1377,13 @@"serviceModel.topicAutoSummary.desc": "Summarizes topics created in the rolling 24-hour window after one hour without message activity.","serviceModel.voice.desc": "Turns voice messages into text for external agents that only accept text","serviceModel.voice.title": "Voice",+ "settingAbout.debugLogs.desc": "Also record detailed debug logs. Turn on while reproducing an issue, then turn off: debug logs use more disk space and may include file paths and URLs.",+ "settingAbout.debugLogs.devDesc": "Development builds always record debug logs.",+ "settingAbout.debugLogs.directory": "Log Files",+ "settingAbout.debugLogs.openDirectory": "Open Folder",+ "settingAbout.debugLogs.openDirectoryDesc": "Attach these files when you report an issue.",+ "settingAbout.debugLogs.title": "Debug Logs",+ "settingAbout.diagnostics.title": "Diagnostics","settingAgent.agentTools.add": "Add Tool","settingAgent.agentTools.agentEmpty": "No agent-exclusive tools yet","settingAgent.agentTools.authorizedBy": "Authorized by {{name}}",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 23bc659f5ec..d0e02335663 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1377,6 +1377,13 @@"serviceModel.topicAutoSummary.desc": "针对滚动 24 小时内创建、消息已停止更新一小时的话题自动生成摘要。","serviceModel.voice.desc": "把语音消息转成文字,供只接收文字的外部 Agent 使用","serviceModel.voice.title": "语音",+ "settingAbout.debugLogs.desc": "额外记录详细的调试日志。复现问题时开启,结束后关闭:调试日志占用更多磁盘空间,并可能包含文件路径和网址。",+ "settingAbout.debugLogs.devDesc": "开发版始终记录调试日志。",+ "settingAbout.debugLogs.directory": "日志文件",+ "settingAbout.debugLogs.openDirectory": "打开文件夹",+ "settingAbout.debugLogs.openDirectoryDesc": "反馈问题时可附上这些文件。",+ "settingAbout.debugLogs.title": "调试日志",+ "settingAbout.diagnostics.title": "诊断","settingAgent.agentTools.add": "添加工具","settingAgent.agentTools.agentEmpty": "还没有 Agent 专属工具","settingAgent.agentTools.authorizedBy": "由 {{name}} 授权",diff --git a/packages/agent-gateway-client/src/client.ts b/packages/agent-gateway-client/src/client.tsindex 4f5767458d1..52258c01687 100644--- a/packages/agent-gateway-client/src/client.ts+++ b/packages/agent-gateway-client/src/client.ts@@ -1,3 +1,4 @@+import { logGatewayLifecycle } from './lifecycleLog';import { MirroredTerminalEchoGuard } from './mirroredTerminalEcho';import { isSessionTerminalEvent } from './terminalEvent';import type {@@ -100,6 +101,11 @@ export class AgentStreamClient extends TypedEmitter {this.terminalEchoGuard = new MirroredTerminalEchoGuard(options.operationId);}+ protected override emit(event: string, ...args: unknown[]): void {+ logGatewayLifecycle('AgentStreamClient', this.operationId, event, args);+ super.emit(event, ...args);+ }+// ─── Public API ───get connectionStatus(): ConnectionStatus {diff --git a/packages/agent-gateway-client/src/lifecycleLog.test.ts b/packages/agent-gateway-client/src/lifecycleLog.test.tsnew file mode 100644index 00000000000..56757ea21be--- /dev/null+++ b/packages/agent-gateway-client/src/lifecycleLog.test.ts@@ -0,0 +1,52 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { logGatewayLifecycle } from './lifecycleLog';++let info: ReturnType<typeof vi.spyOn>;++beforeEach(() => {+ info = vi.spyOn(console, 'info').mockImplementation(() => {});+});++afterEach(() => {+ vi.restoreAllMocks();+});++const event = (type: string, data?: unknown, operationId?: string) => ({+ data,+ operationId,+ stepIndex: 0,+ timestamp: 0,+ type,+});++describe('logGatewayLifecycle', () => {+ it('logs connection edges with the operation id', () => {+ logGatewayLifecycle('AgentStreamClient', 'op_1', 'status_changed', ['connected']);+ logGatewayLifecycle('AgentStreamClient', 'op_1', 'session_complete', [+ { source: 'raw_session_complete' },+ ]);+ logGatewayLifecycle('AgentStreamClient', 'op_1', 'auth_failed', ['expired']);++ expect(info.mock.calls.map(([line]) => line)).toEqual([+ '[AgentStreamClient] op_1 status_changed connected',+ '[AgentStreamClient] op_1 session_complete source=raw_session_complete',+ '[AgentStreamClient] op_1 auth_failed expired',+ ]);+ });++ it('logs only this operation’s terminal agent events', () => {+ logGatewayLifecycle('OperationClient', 'op_1', 'agent_event', [event('stream_chunk')]);+ logGatewayLifecycle('OperationClient', 'op_1', 'agent_event', [+ event('agent_runtime_end', { reason: 'done' }, 'op_member'),+ ]);+ logGatewayLifecycle('OperationClient', 'op_1', 'agent_event', [+ event('agent_runtime_end', { reason: 'done' }),+ ]);++ expect(info).toHaveBeenCalledTimes(1);+ expect(info).toHaveBeenCalledWith(+ '[OperationClient] op_1 terminal agent_runtime_end reason=done',+ );+ });+});diff --git a/packages/agent-gateway-client/src/lifecycleLog.ts b/packages/agent-gateway-client/src/lifecycleLog.tsnew file mode 100644index 00000000000..9c71f35885b--- /dev/null+++ b/packages/agent-gateway-client/src/lifecycleLog.ts@@ -0,0 +1,45 @@+import { isSessionTerminalEvent } from './terminalEvent';+import type { AgentStreamEvent } from './types';++/** Streaming events are too frequent to log; their lifecycle edges are not. */+const QUIET_EVENTS = new Set(['agent_event', 'connected', 'disconnected', 'resume_complete']);++const describeArgs = (event: string, args: unknown[]): string => {+ const [first] = args;+ if (event === 'status_changed' || event === 'auth_failed') return ` ${String(first)}`;+ if (event === 'reconnecting') return ` in ${String(first)}ms`;+ if (event === 'error') return ` ${first instanceof Error ? first.message : String(first)}`;+ if (event === 'session_complete') {+ const source = (first as { source?: unknown } | undefined)?.source;+ return source ? ` source=${String(source)}` : '';+ }+ return '';+};++/**+ * Logs a gateway stream's lifecycle with its operation id at `console.info`.+ * The Desktop main process records every window's console into+ * `renderer.jsonl`, and packaged builds keep only `info` and above unless the+ * user turns on debug logs; `info` keeps a user's connection history queryable+ * by the same `op_…` id the server's agent trace uses. Only lifecycle edges+ * are logged (a few lines per run), so the web console stays quiet.+ */+export const logGatewayLifecycle = (+ tag: string,+ operationId: string,+ event: string,+ args: unknown[],+) => {+ if (event === 'agent_event') {+ const agentEvent = args[0] as AgentStreamEvent | undefined;+ if (!agentEvent || !isSessionTerminalEvent(agentEvent)) return;+ if (agentEvent.operationId && agentEvent.operationId !== operationId) return;+ const reason = (agentEvent.data as { reason?: unknown } | undefined)?.reason;+ console.info(+ `[${tag}] ${operationId} terminal ${agentEvent.type}${reason ? ` reason=${String(reason)}` : ''}`,+ );+ return;+ }+ if (QUIET_EVENTS.has(event)) return;+ console.info(`[${tag}] ${operationId} ${event}${describeArgs(event, args)}`);+};diff --git a/packages/agent-gateway-client/src/mux/createOperationClient.ts b/packages/agent-gateway-client/src/mux/createOperationClient.tsindex 194cc1cde7d..1735ec2a710 100644--- a/packages/agent-gateway-client/src/mux/createOperationClient.ts+++ b/packages/agent-gateway-client/src/mux/createOperationClient.ts@@ -1,3 +1,4 @@+import { logGatewayLifecycle } from '../lifecycleLog';import type { AgentStreamClientEvents, ConnectionStatus } from '../types';import type { GatewayMuxClient } from './GatewayMuxClient';import type { OperationSubscription, ResumeCompleteInfo, ToolResultPayload } from './types';@@ -75,6 +76,7 @@ export const createOperationClient = (let status: ConnectionStatus = 'disconnected';const emit = (event: string, ...args: unknown[]): void => {+ logGatewayLifecycle('OperationClient', operationId, event, args);const set = listeners.get(event);if (!set) return;for (const listener of set) {diff --git a/packages/electron-client-ipc/src/types/system.ts b/packages/electron-client-ipc/src/types/system.tsindex d77b9eb45eb..961b3849385 100644--- a/packages/electron-client-ipc/src/types/system.ts+++ b/packages/electron-client-ipc/src/types/system.ts@@ -32,3 +32,11 @@ export type ThemeAppearance = 'dark' | 'light' | string;export type GuidedPermission = 'accessibility' | 'fullDisk' | 'inputMonitoring' | 'screen';export type PermissionGuideStatus = 'active' | 'dismissed' | 'granted';++/** Settings → About → Debug logs. */+export interface DebugLoggingSettings {+ /** Dev builds record `debug` regardless of `enabled`, so the switch is shown on and locked. */+ alwaysOn: boolean;+ /** Whether packaged builds also write `debug` records to `<userData>/logs/*.jsonl`. */+ enabled: boolean;+}diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 597b9fa4241..d940c14b83c 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -1358,6 +1358,14 @@ export default {'settingAgent.tag.placeholder': 'Enter tag','settingAgent.tag.title': 'Tag','settingAgent.title': 'Agent info',+ 'settingAbout.debugLogs.desc':+ 'Also record detailed debug logs. Turn on while reproducing an issue, then turn off: debug logs use more disk space and may include file paths and URLs.',+ 'settingAbout.debugLogs.devDesc': 'Development builds always record debug logs.',+ 'settingAbout.debugLogs.directory': 'Log Files',+ 'settingAbout.debugLogs.openDirectory': 'Open Folder',+ 'settingAbout.debugLogs.openDirectoryDesc': 'Attach these files when you report an issue.',+ 'settingAbout.debugLogs.title': 'Debug Logs',+ 'settingAbout.diagnostics.title': 'Diagnostics','settingAppearance.appTray.desc':'Show the LobeHub icon in the system tray or macOS menu bar. Disabling it also removes tray menu access.','settingAppearance.appTray.title': 'Show App Tray',diff --git a/src/features/Settings/about/features/DebugLogs.tsx b/src/features/Settings/about/features/DebugLogs.tsxnew file mode 100644index 00000000000..f1a7dee0dae--- /dev/null+++ b/src/features/Settings/about/features/DebugLogs.tsx@@ -0,0 +1,88 @@+'use client';++import { isDesktop } from '@lobechat/const';+import { Button, Switch } from '@lobehub/ui';+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/form';+import { FolderOpen } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import useSWR from 'swr';++import { FORM_STYLE } from '@/const/layoutTokens';+import { SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';+import { desktopSettingsService } from '@/services/electron/settings';++/**+ * Desktop-only: packaged builds record `info` and above by default; this switch+ * adds `debug` records while a user reproduces a bug. Dev builds always record+ * `debug`, so the switch shows on and locked there.+ */+const DebugLogs = memo(() => {+ const { t } = useTranslation('setting');+ const [updating, setUpdating] = useState(false);+ const form = useForm();++ const { data, mutate } = useSWR(+ isDesktop ? 'desktop-debug-logging-settings' : null,+ desktopSettingsService.getDebugLoggingSettings,+ { revalidateOnFocus: false },+ );++ if (!isDesktop) return null;++ const items: FormGroupItem = {+ children: [+ {+ children: (+ <Switch+ checked={data ? data.alwaysOn || data.enabled : false}+ disabled={!data || data.alwaysOn}+ loading={updating}+ onChange={async (checked: boolean) => {+ setUpdating(true);+ try {+ const next = await desktopSettingsService.setDebugLoggingEnabled(checked);+ await mutate(next, { revalidate: false });+ } finally {+ setUpdating(false);+ }+ }}+ />+ ),+ desc: data?.alwaysOn+ ? t('settingAbout.debugLogs.devDesc')+ : t('settingAbout.debugLogs.desc'),+ label: (+ <SettingsSearchAnchor id={'about-debug-logs'}>+ {t('settingAbout.debugLogs.title')}+ </SettingsSearchAnchor>+ ),+ minWidth: undefined,+ },+ {+ children: (+ <Button icon={FolderOpen} onClick={() => desktopSettingsService.openLogDirectory()}>+ {t('settingAbout.debugLogs.openDirectory')}+ </Button>+ ),+ desc: t('settingAbout.debugLogs.openDirectoryDesc'),+ label: t('settingAbout.debugLogs.directory'),+ minWidth: undefined,+ },+ ],+ title: t('settingAbout.diagnostics.title'),+ };++ return (+ <Form+ collapsible={false}+ form={form}+ items={[items]}+ itemsType={'group'}+ variant={'filled'}+ {...FORM_STYLE}+ />+ );+});++export default DebugLogs;diff --git a/src/features/Settings/about/index.tsx b/src/features/Settings/about/index.tsxindex cb60baaa40f..381c81f5132 100644--- a/src/features/Settings/about/index.tsx+++ b/src/features/Settings/about/index.tsx@@ -4,6 +4,7 @@ import SettingHeader from '@/features/Settings/features/SettingHeader';import About from './features/About';import Analytics from './features/Analytics';+import DebugLogs from './features/DebugLogs';interface PageProps {mobile?: boolean;@@ -17,6 +18,7 @@ const Page = ({ mobile, showSettingHeader = true }: PageProps) => {{showSettingHeader && <SettingHeader title={t('tab.about')} />}<About mobile={mobile} /><Analytics />+ <DebugLogs /></>);};diff --git a/src/features/SettingsSearch/items.ts b/src/features/SettingsSearch/items.tsindex ed5436e169d..809e6d922a0 100644--- a/src/features/SettingsSearch/items.ts+++ b/src/features/SettingsSearch/items.ts@@ -360,6 +360,14 @@ export const SETTINGS_SEARCH_ITEMS: SettingsSearchItem[] = [tab: SettingsTabs.Appearance,visible: (ctx) => ctx.isDesktop,},+ {+ anchor: 'about-debug-logs',+ descKey: 'settingAbout.debugLogs.desc',+ keywords: ['debug', 'logs', 'log level', 'diagnostics', 'troubleshoot'],+ labelKey: 'settingAbout.debugLogs.title',+ tab: SettingsTabs.About,+ visible: (ctx) => ctx.isDesktop,+ },{anchor: 'appearance-font-family',descKey: 'settingAppearance.font.fontFamily.desc',diff --git a/src/services/electron/settings.ts b/src/services/electron/settings.tsindex 16f13399243..9b7ea5e7a9d 100644--- a/src/services/electron/settings.ts+++ b/src/services/electron/settings.ts@@ -14,6 +14,27 @@ class DesktopSettingsService {return ensureElectronIpc().tray.getAppTrayVisible();};+ /**+ * Get the Debug logs setting (Settings → About)+ */+ getDebugLoggingSettings = async () => {+ return ensureElectronIpc().system.getDebugLoggingSettings();+ };++ /**+ * Turn `debug` records in `<userData>/logs/*.jsonl` on or off for packaged builds+ */+ setDebugLoggingEnabled = async (enabled: boolean) => {+ return ensureElectronIpc().system.setDebugLoggingEnabled(enabled);+ };++ /**+ * Reveal the desktop log directory in the system file manager+ */+ openLogDirectory = async () => {+ return ensureElectronIpc().system.openLogDirectory();+ };+/*** Get proxy settings*/