🤯 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): export a diagnostics bundle and time-box debug logs (#22966)
YuTengjingb9ca7eff592e
diff --git a/.agents/acceptance/references/multi-instance.md b/.agents/acceptance/references/multi-instance.mdindex de529a08335..09e390f3a2d 100644--- a/.agents/acceptance/references/multi-instance.md+++ b/.agents/acceptance/references/multi-instance.md@@ -175,8 +175,8 @@ state sync (they aren't). Two correct patterns:agent-browser --session s9223 --cdp 9223 snapshot -iagent-browser --session s9224 --cdp 9224 snapshot -i-# ✅ or reset between targets (slower, serial)-agent-browser close --all && agent-browser --cdp 9223 get url+# ✅ or reset one session between targets (slower, serial; never `close --all`)+agent-browser --session s9223 close && agent-browser --session s9223 --cdp 9223 get url```Raw `curl http://localhost:<port>/json/list` always shows a port's true targetdiff --git a/.agents/acceptance/references/probe-field-notes.md b/.agents/acceptance/references/probe-field-notes.mdindex aa973801700..b8dcd25cb2c 100644--- a/.agents/acceptance/references/probe-field-notes.md+++ b/.agents/acceptance/references/probe-field-notes.md@@ -256,7 +256,7 @@ executionTarget: 'local'` in `agencyConfig`) + one message per case asking CC to);r.status; // 401 → re-seed; 200 → the session is live```- Recover with `agent-browser close --all` + `setup-auth.sh web-seed`, then re-open the route.+ Recover with `agent-browser --session <name> close` + `setup-auth.sh web-seed`, then re-open the route.After re-seeding, the same bundle returned `isOwner: true` with the owner-only link rendered —the code was correct all along.- **Why it matters**: an auth-scoped assertion (owner-only / permission-gated UI) fails@@ -844,7 +844,7 @@ nodeintegration, plugins, disablewebsecurity, allowpopups, preload, …`). The hnext on 33803, vite on 32459) — never hardcode 3010; re-run`scripts/test-env.sh` after the server is up, it reads the ports-file. Andthe `os error 35` agent-browser daemon wedge (D8) recovers with- `agent-browser close --all` + re-running `setup-auth.sh web-seed`.+ `agent-browser --session <name> close` + re-running `setup-auth.sh web-seed`.### E30. ✅ "Failed to fetch dynamically imported module" points at the WRONG file — the failure is downstreamdiff --git a/.agents/acceptance/scripts/electron-dev.sh b/.agents/acceptance/scripts/electron-dev.shindex 9b322fcc306..020a99782cb 100755--- a/.agents/acceptance/scripts/electron-dev.sh+++ b/.agents/acceptance/scripts/electron-dev.sh@@ -312,7 +312,7 @@ do_stop() {fifi- agent-browser --session "edev$CDP_PORT" --cdp "$CDP_PORT" close --all 2>/dev/null || true+ agent-browser --session "edev$CDP_PORT" --cdp "$CDP_PORT" close 2>/dev/null || truerm -f "$PIDFILE"# Pool mode: capture the (freshly rotated) login before touching the userData,diff --git a/.agents/skills/acceptance/references/probe-mock-patterns.md b/.agents/skills/acceptance/references/probe-mock-patterns.mdindex 1beb21811c9..a407f6f80f9 100644--- a/.agents/skills/acceptance/references/probe-mock-patterns.md+++ b/.agents/skills/acceptance/references/probe-mock-patterns.md@@ -272,7 +272,8 @@ derive(item))`) captures the value at first render. When a persisted cache hydracan leave the socket half-consumed, after which every later `screenshot` fails(`Resource temporarily unavailable` / `CDP response channel closed`) while`eval`/`get url` keep working — **not** a display-sleep or permission issue. Reset- with `agent-browser close --all`, or skip the daemon entirely (D6).+ only the wedged session with `agent-browser --session <name> close` (`close --all`+ also kills other agents' sessions), or skip the daemon entirely (D6).- **D6. WORKS — raw-CDP screenshot bypasses the daemon.** The bundled`bash "$SKILL_DIR/scripts/cdp-screenshot.sh" [--port <n>] [--out x.png] [--full] [--check]`opens its own WebSocket to the target, doesdiff --git a/.agents/skills/acceptance/surfaces/electron.md b/.agents/skills/acceptance/surfaces/electron.mdindex 326ff1a126c..6a544dfebcc 100644--- a/.agents/skills/acceptance/surfaces/electron.md+++ b/.agents/skills/acceptance/surfaces/electron.md@@ -69,7 +69,7 @@ agent-browser --cdp 9222 eval "JSON.stringify(window.__ERRORS__)" # → text evi```bashDT_ID=$(curl -s http://localhost:9222/json/list | python3 -c "import json,sys; ts=json.load(sys.stdin); print(next(t['id'] for t in ts if t['type']=='page' and t['url'].startswith('devtools://')))")curl -s "http://localhost:9222/json/close/$DT_ID" > /dev/null- agent-browser close --all && agent-browser --cdp 9222 get url+ agent-browser --session <name> close && agent-browser --session <name> --cdp 9222 get url```- **Clean up all processes when done.** `pkill -f "Electron"` only kills the maindiff --git a/apps/desktop/src/main/controllers/SystemCtr.ts b/apps/desktop/src/main/controllers/SystemCtr.tsindex 588c9f542c0..035576fce99 100644--- a/apps/desktop/src/main/controllers/SystemCtr.ts+++ b/apps/desktop/src/main/controllers/SystemCtr.ts@@ -1,8 +1,11 @@import { access, readdir } from 'node:fs/promises';+import os from 'node:os';import process from 'node:process';import type {+ DebugLoggingDuration,DebugLoggingSettings,+ DiagnosticsBundleResult,ElectronAppState,RemoteDebuggingSettings,ThemeMode,@@ -10,7 +13,10 @@ import type {import { app, dialog, nativeTheme, shell } from 'electron';import { legacyLocalDbDir } from '@/const/dir';+import { setDebugLogging } from '@/modules/debugLogging';+import { writeDiagnosticsBundle } from '@/modules/diagnostics/bundle';import { getRemoteDebuggingLaunchState, REMOTE_DEBUGGING_PORT } from '@/modules/remoteDebugging';+import { BUILD_CHANNEL } from '@/modules/updater/configs';import { createLogger } from '@/utils/logger';import {getAccessibilityStatus,@@ -22,7 +28,7 @@ import {requestScreenCaptureAccess,} from '@/utils/permissions';import * as electronIs from '@/utils/platform';-import { applyDebugLogging, getStructuredLogDirectory } from '@/utils/structuredLog';+import { flushStructuredLogs, getStructuredLogDirectory } from '@/utils/structuredLog';import { getSystemLanguage, resolveUILocale } from '@/utils/system-language';import { safeGetPath } from '@/utils/user-path';@@ -211,17 +217,20 @@ export default class SystemController extends ControllerModule {*/@IpcMethod()getDebugLoggingSettings(): DebugLoggingSettings {+ const enabled = this.app.storeManager.get('debugLoggingEnabled', false);+ const expiresAt = enabled ? this.app.storeManager.get('debugLoggingExpiresAt') : undefined;return {alwaysOn: !app.isPackaged,- enabled: this.app.storeManager.get('debugLoggingEnabled', false),+ enabled,+ ...(expiresAt === undefined ? undefined : { expiresAt }),};}+ /** Turns debug logging off, or on for a duration; a timed one turns itself off quietly. */@IpcMethod()- setDebugLoggingEnabled(enabled: boolean): DebugLoggingSettings {- this.app.storeManager.set('debugLoggingEnabled', enabled);- applyDebugLogging(enabled);- logger.info(`Debug logging ${enabled ? 'enabled' : 'disabled'}`);+ setDebugLogging(duration: DebugLoggingDuration | 'off'): DebugLoggingSettings {+ setDebugLogging(this.app.storeManager, duration);+ logger.info(`Debug logging set to ${duration}`);return this.getDebugLoggingSettings();}@@ -251,6 +260,68 @@ export default class SystemController extends ControllerModule {if (error) logger.warn(`Failed to open log directory: ${error}`);}+ /**+ * Writes a zip of the last day of logs plus app and system details to Downloads+ * (the log directory when Downloads is unavailable) and selects it in the file+ * manager, so a user can attach one file to a report.+ */+ @IpcMethod()+ async exportDiagnostics(): Promise<DiagnosticsBundleResult> {+ const logDirectory = getStructuredLogDirectory();+ if (!logDirectory) throw new Error('Structured logs are not open');+ // Queued lines would otherwise miss the bundle, including the click that made it.+ await flushStructuredLogs();++ const options = { logDirectory, now: new Date(), systemInfo: this.getDiagnosticsSystemInfo() };+ const downloads = safeGetPath('downloads');+ let result: DiagnosticsBundleResult | undefined;+ if (downloads) {+ // Downloads can resolve yet be missing or unwritable (redirected, sandboxed, removed).+ result = await writeDiagnosticsBundle({ ...options, outputDirectory: downloads }).catch(+ (error) => {+ logger.warn('Diagnostics could not be written to Downloads; using the log folder', error);+ return undefined;+ },+ );+ }+ result ??= await writeDiagnosticsBundle({ ...options, outputDirectory: logDirectory });+ shell.showItemInFolder(result.filePath);+ logger.info(`Diagnostics exported: ${result.fileName} (${result.size} bytes)`);+ return result;+ }++ /** `system.json` in the diagnostics zip; no host name, account or user content. */+ private getDiagnosticsSystemInfo() {+ const cpus = os.cpus();+ return {+ app: {+ buildChannel: BUILD_CHANNEL,+ isPackaged: app.isPackaged,+ locale: app.getLocale(),+ updateChannel: this.app.storeManager.get('updateChannel'),+ version: app.getVersion(),+ },+ debugLogging: this.getDebugLoggingSettings(),+ os: {+ arch: process.arch,+ cpu: cpus[0]?.model,+ cpuCount: cpus.length,+ freeMemory: os.freemem(),+ platform: process.platform,+ release: os.release(),+ totalMemory: os.totalmem(),+ uptimeSeconds: Math.round(os.uptime()),+ version: os.version(),+ },+ remoteDebugging: this.getRemoteDebuggingSettings(),+ runtime: {+ chrome: process.versions.chrome,+ electron: process.versions.electron,+ node: process.versions.node,+ },+ };+ }+@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 edbdb30c0bc..d35d9fd53a7 100644--- a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts@@ -59,6 +59,7 @@ vi.mock('electron', () => ({getLocale: vi.fn(() => 'en-US'),getPath: vi.fn((name: string) => `/mock/path/${name}`),getPreferredSystemLanguages: vi.fn(() => ['en-US']),+ getVersion: vi.fn(() => '2.0.0'),isPackaged: false,},desktopCapturer: {@@ -78,6 +79,7 @@ vi.mock('electron', () => ({shell: {openExternal: vi.fn().mockResolvedValue(undefined),openPath: vi.fn().mockResolvedValue(''),+ showItemInFolder: vi.fn(),},systemPreferences: {askForMediaAccess: vi.fn(async () => true),@@ -87,11 +89,24 @@ vi.mock('electron', () => ({}));const structuredLogMock = vi.hoisted(() => ({- applyDebugLogging: vi.fn(),+ flushStructuredLogs: vi.fn(async () => {}),getStructuredLogDirectory: vi.fn(() => '/mock/path/userData/logs'),}));vi.mock('@/utils/structuredLog', () => structuredLogMock);+const debugLoggingMock = vi.hoisted(() => ({ setDebugLogging: vi.fn() }));+vi.mock('@/modules/debugLogging', () => debugLoggingMock);++const diagnosticsBundleMock = vi.hoisted(() => ({+ writeDiagnosticsBundle: vi.fn(async ({ outputDirectory }: { outputDirectory: string }) => ({+ fileName: 'LobeHub-diagnostics-20261113-080000.zip',+ filePath: `${outputDirectory}/LobeHub-diagnostics-20261113-080000.zip`,+ size: 2048,+ })),+}));+vi.mock('@/modules/diagnostics/bundle', () => diagnosticsBundleMock);+vi.mock('@/modules/updater/configs', () => ({ BUILD_CHANNEL: 'stable' }));+const remoteDebuggingMock = vi.hoisted(() => ({REMOTE_DEBUGGING_PORT: 9222,getRemoteDebuggingLaunchState: vi.fn(() => ({ active: false, openedByLaunchOption: false })),@@ -246,14 +261,61 @@ describe('SystemController', () => {});});- it('persists the switch and applies it to the running log sink', async () => {+ it('reports when a timed setting turns itself off', async () => {+ mockStoreManager.get.mockReturnValueOnce(true).mockReturnValueOnce(1_800_000_000_000);++ expect(await invokeIpc('system.getDebugLoggingSettings')).toEqual({+ alwaysOn: false,+ enabled: true,+ expiresAt: 1_800_000_000_000,+ });+ });++ it('applies the chosen duration and returns the new state', async () => {mockStoreManager.get.mockReturnValueOnce(true);- const result = await invokeIpc('system.setDebugLoggingEnabled', true);+ const result = await invokeIpc('system.setDebugLogging', '24h');++ expect(debugLoggingMock.setDebugLogging).toHaveBeenCalledWith(mockStoreManager, '24h');+ expect(result).toMatchObject({ alwaysOn: false, enabled: true });+ });- expect(mockStoreManager.set).toHaveBeenCalledWith('debugLoggingEnabled', true);- expect(structuredLogMock.applyDebugLogging).toHaveBeenCalledWith(true);- expect(result).toEqual({ alwaysOn: false, enabled: true });+ it('exports the diagnostics zip to Downloads and selects it', async () => {+ const { shell } = await import('electron');++ const result = await invokeIpc('system.exportDiagnostics');++ expect(structuredLogMock.flushStructuredLogs).toHaveBeenCalled();+ expect(diagnosticsBundleMock.writeDiagnosticsBundle).toHaveBeenCalledWith(+ expect.objectContaining({+ logDirectory: '/mock/path/userData/logs',+ outputDirectory: '/mock/path/downloads',+ systemInfo: expect.objectContaining({+ app: expect.objectContaining({ isPackaged: true }),+ os: expect.objectContaining({ platform: process.platform }),+ }),+ }),+ );+ expect(shell.showItemInFolder).toHaveBeenCalledWith(+ '/mock/path/downloads/LobeHub-diagnostics-20261113-080000.zip',+ );+ expect(result).toMatchObject({ size: 2048 });+ });++ it('falls back to the log folder when Downloads cannot be written', async () => {+ const { shell } = await import('electron');+ diagnosticsBundleMock.writeDiagnosticsBundle.mockRejectedValueOnce(+ Object.assign(new Error('EACCES'), { code: 'EACCES' }),+ );++ await invokeIpc('system.exportDiagnostics');++ expect(diagnosticsBundleMock.writeDiagnosticsBundle).toHaveBeenLastCalledWith(+ expect.objectContaining({ outputDirectory: '/mock/path/userData/logs' }),+ );+ expect(shell.showItemInFolder).toHaveBeenCalledWith(+ '/mock/path/userData/logs/LobeHub-diagnostics-20261113-080000.zip',+ );});it('opens the structured log directory', async () => {diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.tsindex 7f21db2ba7b..74f294ab639 100644--- a/apps/desktop/src/main/core/App.ts+++ b/apps/desktop/src/main/core/App.ts@@ -25,6 +25,7 @@ import {runtimeEnvironmentBinaries,} from '@/modules/binaries';import { generateCliWrapper, getCliWrapperDir } from '@/modules/cliEmbedding';+import { syncDebugLogging } from '@/modules/debugLogging';import { PermissionGuide } from '@/modules/permissionGuide/PermissionGuide';import { applyRemoteDebuggingSwitch } from '@/modules/remoteDebugging';import { ScreenCaptureManager } from '@/modules/screenCapture/ScreenCaptureManager';@@ -34,7 +35,6 @@ 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';@@ -130,7 +130,7 @@ export class App {logger.debug('Initializing App');// Initialize store managerthis.storeManager = new StoreManager(this);- applyDebugLogging(this.storeManager.get('debugLoggingEnabled', false));+ syncDebugLogging(this.storeManager);this.rendererUrlManager = new RendererUrlManager();// Wire the backend reverse-proxy as an `app://` interceptor: keepsdiff --git a/apps/desktop/src/main/modules/debugLogging/index.test.ts b/apps/desktop/src/main/modules/debugLogging/index.test.tsnew file mode 100644index 00000000000..08bda6c733c--- /dev/null+++ b/apps/desktop/src/main/modules/debugLogging/index.test.ts@@ -0,0 +1,98 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ DEBUG_LOGGING_DURATION_MS,+ resetDebugLoggingForTest,+ setDebugLogging,+ syncDebugLogging,+} from './index';++const { applyDebugLogging } = vi.hoisted(() => ({ applyDebugLogging: vi.fn() }));+vi.mock('@/utils/structuredLog', () => ({ applyDebugLogging }));+vi.mock('@/utils/logger', () => ({+ createLogger: () => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }),+}));++const createStore = (initial: Record<string, unknown> = {}) => {+ const data = new Map(Object.entries(initial));+ return {+ data,+ delete: vi.fn((key: string) => void data.delete(key)),+ get: vi.fn((key: string, fallback?: unknown) => (data.has(key) ? data.get(key) : fallback)),+ set: vi.fn((key: string, value: unknown) => void data.set(key, value)),+ } as any;+};++const NOW = Date.parse('2026-11-13T08:00:00.000Z');+const DAY = DEBUG_LOGGING_DURATION_MS['24h'];++describe('debug logging duration', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(NOW);+ applyDebugLogging.mockClear();+ });++ afterEach(() => {+ resetDebugLoggingForTest();+ vi.useRealTimers();+ });++ it('turns on for 24 hours, then turns itself off', () => {+ const store = createStore();++ setDebugLogging(store, '24h', NOW);++ expect(store.data.get('debugLoggingEnabled')).toBe(true);+ expect(store.data.get('debugLoggingExpiresAt')).toBe(NOW + DAY);+ expect(applyDebugLogging).toHaveBeenLastCalledWith(true);++ vi.advanceTimersByTime(DAY);++ expect(store.data.get('debugLoggingEnabled')).toBe(false);+ expect(store.data.has('debugLoggingExpiresAt')).toBe(false);+ expect(applyDebugLogging).toHaveBeenLastCalledWith(false);+ });++ it('stays on without an expiry when set to always', () => {+ const store = createStore({ debugLoggingExpiresAt: NOW + 10 });++ setDebugLogging(store, 'always', NOW);+ vi.advanceTimersByTime(DAY * 30);++ expect(store.data.get('debugLoggingEnabled')).toBe(true);+ expect(store.data.has('debugLoggingExpiresAt')).toBe(false);+ expect(applyDebugLogging).toHaveBeenLastCalledWith(true);+ });++ // Settings saved before durations existed have no expiry and keep their state.+ it('keeps a legacy enabled setting on at launch', () => {+ const store = createStore({ debugLoggingEnabled: true });++ syncDebugLogging(store, NOW);++ expect(store.data.get('debugLoggingEnabled')).toBe(true);+ expect(applyDebugLogging).toHaveBeenLastCalledWith(true);+ });++ it('turns off at launch when the duration ended while the app was closed', () => {+ const store = createStore({ debugLoggingEnabled: true, debugLoggingExpiresAt: NOW - 1 });++ syncDebugLogging(store, NOW);++ expect(store.data.get('debugLoggingEnabled')).toBe(false);+ expect(store.data.has('debugLoggingExpiresAt')).toBe(false);+ expect(applyDebugLogging).toHaveBeenLastCalledWith(false);+ });++ it('cancels the pending expiry when turned off early', () => {+ const store = createStore();+ setDebugLogging(store, '24h', NOW);++ setDebugLogging(store, 'off', NOW + 1000);+ setDebugLogging(store, 'always', NOW + 2000);+ vi.advanceTimersByTime(DAY);++ expect(store.data.get('debugLoggingEnabled')).toBe(true);+ });+});diff --git a/apps/desktop/src/main/modules/debugLogging/index.ts b/apps/desktop/src/main/modules/debugLogging/index.tsnew file mode 100644index 00000000000..20e1a166e41--- /dev/null+++ b/apps/desktop/src/main/modules/debugLogging/index.ts@@ -0,0 +1,68 @@+import type { DebugLoggingDuration } from '@lobechat/electron-client-ipc';++import type { StoreManager } from '@/core/infrastructure/StoreManager';+import { createLogger } from '@/utils/logger';+import { applyDebugLogging } from '@/utils/structuredLog';++const logger = createLogger('modules:debugLogging');++/** Lifetime of a timed Debug logs setting; `'always'` has none. */+export const DEBUG_LOGGING_DURATION_MS: Record<Exclude<DebugLoggingDuration, 'always'>, number> = {+ '24h': 24 * 60 * 60 * 1000,+};++/** `setTimeout` overflows above 2^31-1 ms (~24.8 days) and would fire at once. */+const MAX_TIMER_MS = 2_147_483_647;++type DebugLoggingStore = Pick<StoreManager, 'delete' | 'get' | 'set'>;++let expiryTimer: ReturnType<typeof setTimeout> | undefined;++const clearExpiryTimer = () => {+ if (expiryTimer) clearTimeout(expiryTimer);+ expiryTimer = undefined;+};++/**+ * Applies the persisted Debug logs setting to this run. A timed setting that has+ * passed its expiry is turned off here, at launch or when its timer fires, without+ * a notification: the Settings row shows the current state.+ */+export const syncDebugLogging = (store: DebugLoggingStore, now = Date.now()) => {+ clearExpiryTimer();+ const enabled = store.get('debugLoggingEnabled', false);+ const expiresAt = store.get('debugLoggingExpiresAt');++ if (enabled && expiresAt !== undefined && expiresAt <= now) {+ store.set('debugLoggingEnabled', false);+ store.delete('debugLoggingExpiresAt');+ applyDebugLogging(false);+ logger.info('Debug logging turned off after its duration ended');+ return;+ }++ applyDebugLogging(enabled);+ if (enabled && expiresAt !== undefined) {+ // A longer wait re-arms itself when the capped timer fires.+ expiryTimer = setTimeout(+ () => syncDebugLogging(store),+ Math.min(expiresAt - now, MAX_TIMER_MS),+ );+ expiryTimer.unref?.();+ }+};++/** Turns debug logging off, or on for `duration`. */+export const setDebugLogging = (+ store: DebugLoggingStore,+ duration: DebugLoggingDuration | 'off',+ now = Date.now(),+) => {+ store.set('debugLoggingEnabled', duration !== 'off');+ if (duration === 'off' || duration === 'always') store.delete('debugLoggingExpiresAt');+ else store.set('debugLoggingExpiresAt', now + DEBUG_LOGGING_DURATION_MS[duration]);+ syncDebugLogging(store, now);+};++/** Test-only: drop a pending expiry timer. */+export const resetDebugLoggingForTest = clearExpiryTimer;diff --git a/apps/desktop/src/main/modules/diagnostics/bundle.test.ts b/apps/desktop/src/main/modules/diagnostics/bundle.test.tsnew file mode 100644index 00000000000..306106df7ab--- /dev/null+++ b/apps/desktop/src/main/modules/diagnostics/bundle.test.ts@@ -0,0 +1,166 @@+import { mkdir, mkdtemp, open, readFile, rename, rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { strFromU8, unzipSync } from 'fflate';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import {+ collectRecentLogLines,+ getDiagnosticsFileName,+ openGenerations,+ writeDiagnosticsBundle,+} from './bundle';++const NOW = new Date('2026-11-13T08:00:00.000Z');+const HOUR = 60 * 60 * 1000;++const record = (msg: string, hoursAgo: number) =>+ JSON.stringify({+ level: 'info',+ msg,+ pid: 1,+ process: 'main',+ ts: new Date(NOW.getTime() - hoursAgo * HOUR).toISOString(),+ });++describe('writeDiagnosticsBundle', () => {+ let root: string;+ let logDirectory: string;++ beforeEach(async () => {+ root = await mkdtemp(path.join(os.tmpdir(), 'lobe-diagnostics-'));+ logDirectory = path.join(root, 'logs');+ await mkdir(logDirectory);+ });++ afterEach(async () => {+ await rm(root, { force: true, recursive: true });+ });++ it('zips the last day of logs across rotated files, oldest first, with manifest and system info', async () => {+ await writeFile(+ path.join(logDirectory, 'main.jsonl.2'),+ `${record('two days ago', 48)}\n${record('older rotation', 20)}\n`,+ );+ await writeFile(path.join(logDirectory, 'main.jsonl.1'), `${record('newer rotation', 5)}\n`);+ await writeFile(+ path.join(logDirectory, 'main.jsonl'),+ `${record('live', 0.1)}\n{"ts":"torn line\n`,+ );+ await writeFile(path.join(logDirectory, 'manifest.json'), '{"pid":1}\n');++ const result = await writeDiagnosticsBundle({+ logDirectory,+ now: NOW,+ outputDirectory: root,+ systemInfo: { app: { version: '2.0.0' } },+ });++ expect(result.fileName).toBe(getDiagnosticsFileName(NOW));+ expect(result.filePath).toBe(path.join(root, result.fileName));++ const entries = unzipSync(new Uint8Array(await readFile(result.filePath)));+ expect(Object.keys(entries).sort()).toEqual(['main.jsonl', 'manifest.json', 'system.json']);++ const main = strFromU8(entries['main.jsonl']).trim().split('\n');+ expect(main.map((line) => line.match(/"msg":"([^"]+)"/)?.[1] ?? line)).toEqual([+ 'older rotation',+ 'newer rotation',+ 'live',+ '{"ts":"torn line',+ ]);+ expect(strFromU8(entries['manifest.json'])).toBe('{"pid":1}\n');+ expect(JSON.parse(strFromU8(entries['system.json']))).toEqual({+ app: { version: '2.0.0' },+ exportedAt: NOW.toISOString(),+ logsSince: new Date(NOW.getTime() - 24 * HOUR).toISOString(),+ });+ });++ it('still writes system info when no log has been recorded yet', async () => {+ const result = await writeDiagnosticsBundle({+ logDirectory,+ now: NOW,+ outputDirectory: root,+ systemInfo: {},+ });++ const entries = unzipSync(new Uint8Array(await readFile(result.filePath)));+ expect(Object.keys(entries)).toEqual(['system.json']);+ expect(result.size).toBeGreaterThan(0);+ });+});++describe('collectRecentLogLines', () => {+ let logDirectory: string;++ beforeEach(async () => {+ logDirectory = await mkdtemp(path.join(os.tmpdir(), 'lobe-diagnostics-rotate-'));+ });++ afterEach(async () => {+ await rm(logDirectory, { force: true, recursive: true });+ });++ it('keeps every generation when the writer rotates after the files are opened', async () => {+ const file = (suffix = '') => path.join(logDirectory, `main.jsonl${suffix}`);+ await writeFile(file('.2'), `${record('gen 2', 3)}\n`);+ await writeFile(file('.1'), `${record('gen 1', 2)}\n`);+ await writeFile(file(), `${record('live', 1)}\n`);++ const handles = await openGenerations(logDirectory, 'main.jsonl');+ // The writer's rotate(): every generation moves up by one and a fresh live file starts.+ await rename(file('.2'), file('.3'));+ await rename(file('.1'), file('.2'));+ await rename(file(), file('.1'));+ await writeFile(file(), `${record('after rotation', 0)}\n`);++ const content = await collectRecentLogLines(handles, NOW.getTime() - 24 * HOUR);+ expect(+ content+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line).msg),+ ).toEqual(['gen 2', 'gen 1', 'live']);+ });++ it('retakes the snapshot when the writer rotates between opening two files', async () => {+ const file = (suffix = '') => path.join(logDirectory, `main.jsonl${suffix}`);+ await writeFile(file('.2'), `${record('gen 2', 3)}\n`);+ await writeFile(file('.1'), `${record('gen 1', 2)}\n`);+ await writeFile(file(), `${record('live', 1)}\n`);++ let rotated = false;+ const openFile = async (filePath: string) => {+ const handle = await open(filePath, 'r');+ // Rotate right after `.2` is opened: the next open of `.1` then gets the old live+ // file, so a single pass would lose "gen 1".+ if (!rotated && filePath === file('.2')) {+ rotated = true;+ await rename(file('.2'), file('.3'));+ await rename(file('.1'), file('.2'));+ await rename(file(), file('.1'));+ await writeFile(file(), `${record('after rotation', 0)}\n`);+ }+ return handle;+ };++ const handles = await openGenerations(logDirectory, 'main.jsonl', openFile);+ const content = await collectRecentLogLines(handles, NOW.getTime() - 24 * HOUR);+ expect(+ content+ .trim()+ .split('\n')+ .map((line) => JSON.parse(line).msg),+ ).toEqual(['gen 2', 'gen 1', 'live', 'after rotation']);+ });+});++describe('getDiagnosticsFileName', () => {+ it('stamps the local time', () => {+ expect(getDiagnosticsFileName(new Date(2026, 10, 3, 9, 5, 7))).toBe(+ 'LobeHub-diagnostics-20261103-090507.zip',+ );+ });+});diff --git a/apps/desktop/src/main/modules/diagnostics/bundle.ts b/apps/desktop/src/main/modules/diagnostics/bundle.tsnew file mode 100644index 00000000000..28db964c748--- /dev/null+++ b/apps/desktop/src/main/modules/diagnostics/bundle.ts@@ -0,0 +1,193 @@+import { access, type FileHandle, open, readFile, stat, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { createInterface } from 'node:readline';++import type { DiagnosticsBundleResult } from '@lobechat/electron-client-ipc';+import { strToU8, zip, type Zippable } from 'fflate';++import {+ getLogFileName,+ LOG_MANIFEST_FILE,+ LOG_PROCESSES,+ MAX_LOG_GENERATIONS,+} from '@/utils/structuredLog/layout';++/** Log lines older than this stay out of the bundle; one day covers "it broke earlier today". */+export const DIAGNOSTICS_LOG_WINDOW_MS = 24 * 60 * 60 * 1000;++const pad = (value: number) => String(value).padStart(2, '0');++/** `LobeHub-diagnostics-20261113-153012.zip`, in local time so it matches the user's clock. */+export const getDiagnosticsFileName = (now: Date) =>+ `LobeHub-diagnostics-${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.zip`;++const exists = async (filePath: string) => {+ try {+ await access(filePath);+ return true;+ } catch {+ return false;+ }+};++const SNAPSHOT_ATTEMPTS = 5;+const SNAPSHOT_RETRY_MS = 20;++type OpenFile = (filePath: string) => Promise<FileHandle>;++const openOrSkip = (openFile: OpenFile, filePath: string) =>+ openFile(filePath).catch(() => undefined);++/** Every opened handle still is the file at its path, and no missing path has appeared. */+const isConsistentSnapshot = async (paths: string[], handles: (FileHandle | undefined)[]) => {+ const [opened, current] = await Promise.all([+ Promise.all(handles.map((handle) => handle?.stat().then(({ ino }) => ino))),+ Promise.all(+ paths.map((filePath) =>+ stat(filePath).then(+ ({ ino }) => ino,+ () => undefined,+ ),+ ),+ ),+ ]);+ return opened.every((ino, index) => ino === current[index]);+};++const closeAll = (handles: (FileHandle | undefined)[]) =>+ Promise.all(handles.map((handle) => handle?.close().catch(() => undefined)));++/**+ * Opens a process's log files, oldest first: `main.jsonl.3` … `main.jsonl.1`, then+ * `main.jsonl`, as one snapshot. The writer may rotate (rename every generation up by+ * one) at any moment; an open handle keeps reading the file it was opened on, so once+ * all are open no generation can be skipped or read twice. A rotation that lands+ * between the opens is detected by comparing each handle with its path, and the+ * snapshot is retaken.+ */+export const openGenerations = async (+ logDirectory: string,+ fileName: string,+ openFile: OpenFile = (filePath) => open(filePath, 'r'),+) => {+ const paths = [+ ...Array.from({ length: MAX_LOG_GENERATIONS }, (_, index) =>+ path.join(logDirectory, `${fileName}.${MAX_LOG_GENERATIONS - index}`),+ ),+ path.join(logDirectory, fileName),+ ];++ let handles: (FileHandle | undefined)[] = [];+ for (let attempt = 1; attempt <= SNAPSHOT_ATTEMPTS; attempt += 1) {+ handles = [];+ for (const filePath of paths) handles.push(await openOrSkip(openFile, filePath));+ if (attempt === SNAPSHOT_ATTEMPTS || (await isConsistentSnapshot(paths, handles))) break;+ await closeAll(handles);+ await new Promise((resolve) => setTimeout(resolve, SNAPSHOT_RETRY_MS));+ }+ // After the last attempt the snapshot is kept as is: a bundle with a possible gap+ // during sustained rotation is more useful than no bundle.+ return handles.filter((handle): handle is FileHandle => handle !== undefined);+};++const readTimestamp = (line: string) => {+ // Records start with `{"…","ts":"…"}`; parsing is the only reliable read of `ts`.+ try {+ const ts = (JSON.parse(line) as { ts?: unknown }).ts;+ return typeof ts === 'string' ? Date.parse(ts) : Number.NaN;+ } catch {+ return Number.NaN;+ }+};++/**+ * Concatenates a process's JSONL records written at or after `since`, oldest first.+ * A line without a readable timestamp (a torn write at a crash) is kept: it is+ * usually the most interesting one.+ */+export const collectRecentLogLines = async (handles: FileHandle[], since: number) => {+ const lines: string[] = [];+ try {+ for (const handle of handles) {+ const reader = createInterface({+ crlfDelay: Infinity,+ input: handle.createReadStream({ encoding: 'utf8' }),+ });+ for await (const line of reader) {+ if (!line) continue;+ const ts = readTimestamp(line);+ if (Number.isNaN(ts) || ts >= since) lines.push(line);+ }+ }+ } finally {+ // Streams close their handle when they end; this closes the ones a failure left unread.+ await Promise.all(handles.map((handle) => handle.close().catch(() => undefined)));+ }+ return lines.length > 0 ? `${lines.join('\n')}\n` : '';+};++const zipAsync = (files: Zippable) =>+ new Promise<Uint8Array>((resolve, reject) => {+ zip(files, { level: 6 }, (error, data) => (error ? reject(error) : resolve(data)));+ });++export interface BuildDiagnosticsBundleOptions {+ logDirectory: string;+ now?: Date;+ /** Written as `system.json`: app version, OS and settings that matter for a report. */+ systemInfo: Record<string, unknown>;+ windowMs?: number;+}++/**+ * Zips the last day of `main.jsonl` / `renderer.jsonl` (across rotated files), the+ * current `manifest.json` and `system.json`. Records are already secret-redacted+ * when written (`structuredLog/record.ts`).+ */+export const buildDiagnosticsBundle = async ({+ logDirectory,+ now = new Date(),+ systemInfo,+ windowMs = DIAGNOSTICS_LOG_WINDOW_MS,+}: BuildDiagnosticsBundleOptions) => {+ const since = now.getTime() - windowMs;+ const files: Zippable = {+ 'system.json': strToU8(+ `${JSON.stringify(+ { ...systemInfo, exportedAt: now.toISOString(), logsSince: new Date(since).toISOString() },+ null,+ 2,+ )}\n`,+ ),+ };++ const manifestPath = path.join(logDirectory, LOG_MANIFEST_FILE);+ if (await exists(manifestPath)) files[LOG_MANIFEST_FILE] = await readFile(manifestPath);++ for (const process of LOG_PROCESSES) {+ const fileName = getLogFileName(process);+ const content = await collectRecentLogLines(+ await openGenerations(logDirectory, fileName),+ since,+ );+ if (content) files[fileName] = strToU8(content);+ }++ return zipAsync(files);+};++export interface WriteDiagnosticsBundleOptions extends BuildDiagnosticsBundleOptions {+ outputDirectory: string;+}++export const writeDiagnosticsBundle = async ({+ outputDirectory,+ ...options+}: WriteDiagnosticsBundleOptions): Promise<DiagnosticsBundleResult> => {+ const now = options.now ?? new Date();+ const data = await buildDiagnosticsBundle({ ...options, now });+ const fileName = getDiagnosticsFileName(now);+ const filePath = path.join(outputDirectory, fileName);+ await writeFile(filePath, data);+ return { fileName, filePath, size: (await stat(filePath)).size };+};diff --git a/apps/desktop/src/main/types/store.ts b/apps/desktop/src/main/types/store.tsindex a9d77fd2439..d539d45791c 100644--- a/apps/desktop/src/main/types/store.ts+++ b/apps/desktop/src/main/types/store.ts@@ -20,6 +20,11 @@ export interface ElectronMainStore {* `<userData>/logs/*.jsonl`. Dev builds always do.*/debugLoggingEnabled: boolean;+ /**+ * Epoch milliseconds at which `debugLoggingEnabled` turns itself off. Absent means it+ * stays on until the user turns it off (`modules/debugLogging`).+ */+ debugLoggingExpiresAt?: number;/*** Explicit completion state for the multi-step desktop onboarding flow.* Undefined preserves the legacy behavior for users who completed onboardingdiff --git a/locales/en-US/common.json b/locales/en-US/common.jsonindex 292f9a8b1e2..c54865e66f5 100644--- a/locales/en-US/common.json+++ b/locales/en-US/common.json@@ -214,6 +214,10 @@"delete": "Delete","deleteHistoryMigrating": "Chat history is still migrating. It can be deleted once the migration finishes — please try again in a few minutes.","deleteSharedContentOwnerOnly": "Can't delete: this includes other members' topics, comments, or tasks. Ask a workspace owner to delete it.",+ "diagnostics.export.action": "Export Diagnostics",+ "diagnostics.export.failed": "Couldn't export diagnostics. Try again.",+ "diagnostics.export.success": "Diagnostics exported",+ "diagnostics.export.successDesc": "Saved {{fileName}} and selected it in its folder.","document": "User Manual","download": "Download","downloadingUpdate": "Downloading {{percent}}%",@@ -240,6 +244,9 @@"feedback.errors.submitFailed": "Submit failed. Try again.","feedback.errors.teamNotFound": "Configuration error","feedback.errors.uploadFailed": "Upload failed",+ "feedback.fields.diagnostics.exported": "Exported {{fileName}}",+ "feedback.fields.diagnostics.hint": "Includes the last 24 hours of logs, the app version and system details. After exporting, email the file to <email>{{email}}</email>.",+ "feedback.fields.diagnostics.label": "Diagnostics (optional)","feedback.fields.message.label": "Message","feedback.fields.message.maxLength": "Message must be 5000 characters or less","feedback.fields.message.placeholder": "Tell us more...",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 136822137bf..67d4cd15385 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1430,17 +1430,25 @@"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.desc": "Record more detailed logs while you reproduce a problem. Debug logs use more disk space and may include file paths and web addresses.","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.openDirectory": "Open Log Folder",+ "settingAbout.debugLogs.option.24h": "On for 24 hours",+ "settingAbout.debugLogs.option.always": "Always on",+ "settingAbout.debugLogs.option.off": "Off",+ "settingAbout.debugLogs.status.always": "On until you turn it off. Debug logs use more disk space.",+ "settingAbout.debugLogs.status.hours_one": "On. Turns off automatically in {{count}} hour.",+ "settingAbout.debugLogs.status.hours_other": "On. Turns off automatically in {{count}} hours.",+ "settingAbout.debugLogs.status.soon": "On. Turns off automatically within the hour.","settingAbout.debugLogs.title": "Debug Logs",- "settingAbout.diagnostics.title": "Diagnostics",+ "settingAbout.debugLogs.updateFailed": "Couldn't change debug logs. Try again.",+ "settingAbout.diagnostics.bundle.desc": "Packs the last 24 hours of logs with the app version and system details into one file. Attach it when you report a problem.",+ "settingAbout.diagnostics.bundle.title": "Diagnostics Package",+ "settingAbout.remoteDebugging.activeDesc": "On: programs on this computer can control LobeHub through port {{port}}. Turn it off when you finish debugging.","settingAbout.remoteDebugging.confirm.content": "After you restart LobeHub, programs on this computer can connect to port {{port}}, control LobeHub windows, and read your signed-in session and data. The port opens on every launch until you turn this off. Turn it on only while debugging.","settingAbout.remoteDebugging.confirm.ok": "Allow","settingAbout.remoteDebugging.confirm.title": "Allow remote debugging?",- "settingAbout.remoteDebugging.desc": "Let developer tools on this computer connect to LobeHub on port {{port}} and read app state.",+ "settingAbout.remoteDebugging.desc": "For developers troubleshooting LobeHub. When on, other programs on this computer can control LobeHub and read your signed-in session and data. Keep it off for everyday use.","settingAbout.remoteDebugging.launchOptionDesc": "Remote debugging was turned on by a launch option for this session.","settingAbout.remoteDebugging.restartToApply": "Restart LobeHub to apply this change.","settingAbout.remoteDebugging.title": "Remote Debugging",diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.jsonindex e1dfff8cf3b..80042adccf6 100644--- a/locales/zh-CN/common.json+++ b/locales/zh-CN/common.json@@ -214,6 +214,10 @@"delete": "删除","deleteHistoryMigrating": "聊天记录正在迁移中,迁移完成后即可删除,请几分钟后再试","deleteSharedContentOwnerOnly": "无法删除:包含其他成员的话题、评论或任务。请联系工作区所有者删除。",+ "diagnostics.export.action": "导出诊断包",+ "diagnostics.export.failed": "诊断包导出失败,请重试。",+ "diagnostics.export.success": "诊断包已导出",+ "diagnostics.export.successDesc": "已保存 {{fileName}},并在文件夹中选中。","document": "使用文档","download": "下载","downloadingUpdate": "正在下载 {{percent}}%",@@ -240,6 +244,9 @@"feedback.errors.submitFailed": "提交失败,请重试","feedback.errors.teamNotFound": "配置错误","feedback.errors.uploadFailed": "上传失败",+ "feedback.fields.diagnostics.exported": "已导出 {{fileName}}",+ "feedback.fields.diagnostics.hint": "包含最近 24 小时的日志、应用版本和系统信息。导出后,请把文件发送到 <email>{{email}}</email>。",+ "feedback.fields.diagnostics.label": "诊断包(可选)","feedback.fields.message.label": "详细信息","feedback.fields.message.maxLength": "详细信息不能超过 5000 个字符","feedback.fields.message.placeholder": "请详细描述您的问题、建议或反馈...",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 45e84f3f347..7bdf1c0d458 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1430,17 +1430,25 @@"serviceModel.topicAutoSummary.desc": "针对滚动 24 小时内创建、消息已停止更新一小时的话题自动生成摘要。","serviceModel.voice.desc": "把语音消息转成文字,供只接收文字的外部 Agent 使用","serviceModel.voice.title": "语音",- "settingAbout.debugLogs.desc": "额外记录详细的调试日志。复现问题时开启,结束后关闭:调试日志占用更多磁盘空间,并可能包含文件路径和网址。",+ "settingAbout.debugLogs.desc": "复现问题时开启,记录更详细的日志。调试日志会占用更多磁盘空间,并可能包含文件路径和网址。","settingAbout.debugLogs.devDesc": "开发版始终记录调试日志。",- "settingAbout.debugLogs.directory": "日志文件",- "settingAbout.debugLogs.openDirectory": "打开文件夹",- "settingAbout.debugLogs.openDirectoryDesc": "反馈问题时可附上这些文件。",+ "settingAbout.debugLogs.openDirectory": "打开日志文件夹",+ "settingAbout.debugLogs.option.24h": "开启 24 小时",+ "settingAbout.debugLogs.option.always": "一直开启",+ "settingAbout.debugLogs.option.off": "关闭",+ "settingAbout.debugLogs.status.always": "一直开启,直到你手动关闭。调试日志会占用更多磁盘空间。",+ "settingAbout.debugLogs.status.hours_one": "已开启,{{count}} 小时后自动关闭。",+ "settingAbout.debugLogs.status.hours_other": "已开启,{{count}} 小时后自动关闭。",+ "settingAbout.debugLogs.status.soon": "已开启,1 小时内自动关闭。","settingAbout.debugLogs.title": "调试日志",- "settingAbout.diagnostics.title": "诊断",+ "settingAbout.debugLogs.updateFailed": "调试日志设置失败,请重试。",+ "settingAbout.diagnostics.bundle.desc": "把最近 24 小时的日志、应用版本和系统信息打包成一个文件,反馈问题时附上它。",+ "settingAbout.diagnostics.bundle.title": "诊断包",+ "settingAbout.remoteDebugging.activeDesc": "已开启:本机程序可以通过端口 {{port}} 控制 LobeHub。调试结束后请关闭。","settingAbout.remoteDebugging.confirm.content": "重启 LobeHub 后,本机上的程序可以通过端口 {{port}} 控制 LobeHub 窗口,并读取你的登录状态和数据。关闭前每次启动都会开放该端口,请仅在调试时开启。","settingAbout.remoteDebugging.confirm.ok": "允许","settingAbout.remoteDebugging.confirm.title": "允许远程调试?",- "settingAbout.remoteDebugging.desc": "允许本机的开发者工具通过端口 {{port}} 连接 LobeHub 并读取应用状态。",+ "settingAbout.remoteDebugging.desc": "供开发者排查问题使用。开启后,本机上的其他程序可以控制 LobeHub,并读取你的登录状态和数据。日常使用请保持关闭。","settingAbout.remoteDebugging.launchOptionDesc": "本次运行已通过启动参数开启远程调试。","settingAbout.remoteDebugging.restartToApply": "重启 LobeHub 后生效。","settingAbout.remoteDebugging.title": "远程调试",diff --git a/packages/electron-client-ipc/src/types/system.ts b/packages/electron-client-ipc/src/types/system.tsindex c698120a29a..82ac8d8a9e7 100644--- a/packages/electron-client-ipc/src/types/system.ts+++ b/packages/electron-client-ipc/src/types/system.ts@@ -45,10 +45,30 @@ export interface RemoteDebuggingSettings {port: number;}+/**+ * How long Settings → About → Debug logs stays on: `'24h'` turns itself off a day+ * later, `'always'` stays on until the user turns it off.+ */+export type DebugLoggingDuration = '24h' | 'always';+/** Settings → About → Debug logs. */export interface DebugLoggingSettings {- /** Dev builds record `debug` regardless of `enabled`, so the switch is shown on and locked. */+ /** Dev builds record `debug` regardless of `enabled`, so the control is shown on and locked. */alwaysOn: boolean;/** Whether packaged builds also write `debug` records to `<userData>/logs/*.jsonl`. */enabled: boolean;+ /**+ * Epoch milliseconds at which debug logging turns itself off. Absent while it is+ * off or set to stay on (`'always'`, also every setting saved before durations existed).+ */+ expiresAt?: number;+}++/** A diagnostics zip written by Settings → About → Diagnostics or the feedback dialog. */+export interface DiagnosticsBundleResult {+ fileName: string;+ /** Absolute path; the file is already selected in Finder / Explorer. */+ filePath: string;+ /** Zip size in bytes. */+ size: number;}diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.tsindex 91f74fd3b29..3a72038af1f 100644--- a/packages/locales/src/default/common.ts+++ b/packages/locales/src/default/common.ts@@ -300,11 +300,19 @@ export default {'favorite.section': 'Favorites','favorite.updateError': "Couldn't update your favorites. Try again.",'feedback': 'Feedback',+ 'diagnostics.export.action': 'Export Diagnostics',+ 'diagnostics.export.failed': "Couldn't export diagnostics. Try again.",+ 'diagnostics.export.success': 'Diagnostics exported',+ 'diagnostics.export.successDesc': 'Saved {{fileName}} and selected it in its folder.','feedback.emailContact': 'You can also email us at <email>{{email}}</email>','feedback.errors.fileTooLarge': 'File exceeds 5MB','feedback.errors.submitFailed': 'Submit failed. Try again.','feedback.errors.teamNotFound': 'Configuration error','feedback.errors.uploadFailed': 'Upload failed',+ 'feedback.fields.diagnostics.exported': 'Exported {{fileName}}',+ 'feedback.fields.diagnostics.hint':+ 'Includes the last 24 hours of logs, the app version and system details. After exporting, email the file to <email>{{email}}</email>.',+ 'feedback.fields.diagnostics.label': 'Diagnostics (optional)','feedback.fields.message.label': 'Message','feedback.fields.message.maxLength': 'Message must be 5000 characters or less','feedback.fields.message.placeholder': 'Tell us more...',diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 502201d038b..0a808a3eda5 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -1446,19 +1446,30 @@ export default {'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.',+ 'Record more detailed logs while you reproduce a problem. Debug logs use more disk space and may include file paths and web addresses.','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.openDirectory': 'Open Log Folder','settingAbout.debugLogs.title': 'Debug Logs',- 'settingAbout.diagnostics.title': 'Diagnostics',+ 'settingAbout.debugLogs.option.24h': 'On for 24 hours',+ 'settingAbout.debugLogs.option.always': 'Always on',+ 'settingAbout.debugLogs.option.off': 'Off',+ 'settingAbout.debugLogs.status.always':+ 'On until you turn it off. Debug logs use more disk space.',+ 'settingAbout.debugLogs.status.hours_one': 'On. Turns off automatically in {{count}} hour.',+ 'settingAbout.debugLogs.status.hours_other': 'On. Turns off automatically in {{count}} hours.',+ 'settingAbout.debugLogs.status.soon': 'On. Turns off automatically within the hour.',+ 'settingAbout.debugLogs.updateFailed': "Couldn't change debug logs. Try again.",+ 'settingAbout.diagnostics.bundle.desc':+ 'Packs the last 24 hours of logs with the app version and system details into one file. Attach it when you report a problem.',+ 'settingAbout.diagnostics.bundle.title': 'Diagnostics Package',+ 'settingAbout.remoteDebugging.activeDesc':+ 'On: programs on this computer can control LobeHub through port {{port}}. Turn it off when you finish debugging.','settingAbout.remoteDebugging.confirm.content':'After you restart LobeHub, programs on this computer can connect to port {{port}}, control LobeHub windows, and read your signed-in session and data. The port opens on every launch until you turn this off. Turn it on only while debugging.','settingAbout.remoteDebugging.confirm.ok': 'Allow','settingAbout.remoteDebugging.confirm.title': 'Allow remote debugging?','settingAbout.remoteDebugging.desc':- 'Let developer tools on this computer connect to LobeHub on port {{port}} and read app state.',+ 'For developers troubleshooting LobeHub. When on, other programs on this computer can control LobeHub and read your signed-in session and data. Keep it off for everyday use.','settingAbout.remoteDebugging.launchOptionDesc':'Remote debugging was turned on by a launch option for this session.','settingAbout.remoteDebugging.restartToApply': 'Restart LobeHub to apply this change.',diff --git a/src/components/FeedbackModal/DiagnosticsField.tsx b/src/components/FeedbackModal/DiagnosticsField.tsxnew file mode 100644index 00000000000..3b07ae96610--- /dev/null+++ b/src/components/FeedbackModal/DiagnosticsField.tsx@@ -0,0 +1,65 @@+'use client';++import { BRANDING_EMAIL } from '@lobechat/business-const';+import { Button, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';+import { Form } from '@lobehub/ui/form';+import { CircleCheck, PackageOpen } from 'lucide-react';+import { memo } from 'react';+import { Trans, useTranslation } from 'react-i18next';++import { useExportDiagnostics } from '@/features/Electron/system/useExportDiagnostics';++/**+ * Desktop: lets a reporter export the diagnostics zip from the dialog they are+ * already in. The zip stays on their computer (it carries file paths and URLs);+ * the hint says where to send it.+ */+const DiagnosticsField = memo(() => {+ const { t } = useTranslation('common');+ const { exportDiagnostics, exporting, result } = useExportDiagnostics();++ return (+ <Form.Field label={t('feedback.fields.diagnostics.label')} style={{ marginBottom: 0 }}>+ <Flexbox gap={8}>+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>+ <Button+ icon={<Icon icon={PackageOpen} />}+ loading={exporting}+ onClick={exportDiagnostics}+ >+ {t('diagnostics.export.action')}+ </Button>+ {result && (+ <Flexbox horizontal align={'center'} gap={4} style={{ minWidth: 0 }}>+ <Icon color={cssVar.colorSuccess} icon={CircleCheck} size={14} />+ <Text ellipsis fontSize={12} type={'secondary'}>+ {t('feedback.fields.diagnostics.exported', { fileName: result.fileName })}+ </Text>+ </Flexbox>+ )}+ </Flexbox>+ <Text fontSize={12} type={'secondary'}>+ <Trans+ i18nKey="feedback.fields.diagnostics.hint"+ ns="common"+ values={{ email: BRANDING_EMAIL.business }}+ components={{+ email: (+ <a+ href={`mailto:${BRANDING_EMAIL.business}`}+ rel="noopener noreferrer"+ style={{ color: 'inherit', textDecoration: 'underline' }}+ target="_blank"+ />+ ),+ }}+ />+ </Text>+ </Flexbox>+ </Form.Field>+ );+});++DiagnosticsField.displayName = 'DiagnosticsField';++export default DiagnosticsField;diff --git a/src/components/FeedbackModal/FeedbackContent.tsx b/src/components/FeedbackModal/FeedbackContent.tsxindex 865474e7a17..91fa0c5f104 100644--- a/src/components/FeedbackModal/FeedbackContent.tsx+++ b/src/components/FeedbackModal/FeedbackContent.tsx@@ -1,6 +1,7 @@'use client';import { BRANDING_EMAIL } from '@lobechat/business-const';+import { isDesktop } from '@lobechat/const';import { Button, Flexbox, Icon, Input, toast, Upload, useModalContext } from '@lobehub/ui';import { Form, useForm, useWatch } from '@lobehub/ui/form';import { ImagePlus, Send } from 'lucide-react';@@ -13,6 +14,7 @@ import { useFileStore } from '@/store/file';import { userProfileSelectors } from '@/store/user/selectors';import { useUserStore } from '@/store/user/store';+import DiagnosticsField from './DiagnosticsField';import type { FeedbackInitialValues } from './types';interface FeedbackContentProps {@@ -184,6 +186,8 @@ const FeedbackContent = memo<FeedbackContentProps>(({ initialValues }) => {{t('feedback.fields.screenshot.hint')}</p></Form.Field>++ {isDesktop && <DiagnosticsField />}</Form><Flexbox horizontal gap={8} justify="flex-end">diff --git a/src/components/Skeleton/Settings/tabs/Advanced.tsx b/src/components/Skeleton/Settings/tabs/Advanced.tsxindex 6d6b39afbef..57c77427dce 100644--- a/src/components/Skeleton/Settings/tabs/Advanced.tsx+++ b/src/components/Skeleton/Settings/tabs/Advanced.tsx@@ -8,7 +8,7 @@ import { SettingsFormSkeleton, SWITCH_CONTROL } from '../Section';import { useSkeletonText } from '../useSkeletonText';import type { SettingsTabSkeleton } from './types';-/** Tools group (dev mode + gateway mode when enabled) and, on desktop, the update channel. */+/** Tools group (dev mode, gateway mode when enabled; on desktop the diagnostics package, debug logs and remote debugging) and, on desktop, the update channel. */const Body = () => {const text = useSkeletonText('setting');const enableGatewayMode = useServerConfigStore(serverConfigSelectors.enableGatewayMode);@@ -34,6 +34,28 @@ const Body = () => {},]: []),+ ...(isDesktop+ ? [+ {+ control: { height: 32, width: 300 },+ desc: text('settingAbout.diagnostics.bundle.desc', 280, 12),+ label: text('settingAbout.diagnostics.bundle.title', 96),+ minWidth: undefined,+ },+ {+ control: { height: 32, width: 160 },+ desc: text('settingAbout.debugLogs.desc', 280, 12),+ label: text('settingAbout.debugLogs.title', 96),+ minWidth: undefined,+ },+ {+ control: SWITCH_CONTROL,+ desc: text('settingAbout.remoteDebugging.desc', 280, 12),+ label: text('settingAbout.remoteDebugging.title', 96),+ minWidth: undefined,+ },+ ]+ : []),],title: text('tab.advanced.toolsAndDiagnostics.title', 160, 16),},diff --git a/src/features/Electron/system/useExportDiagnostics.ts b/src/features/Electron/system/useExportDiagnostics.tsnew file mode 100644index 00000000000..e9342d49f70--- /dev/null+++ b/src/features/Electron/system/useExportDiagnostics.ts@@ -0,0 +1,40 @@+import type { DiagnosticsBundleResult } from '@lobechat/electron-client-ipc';+import { toast } from '@lobehub/ui';+import { useCallback, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { desktopSettingsService } from '@/services/electron/settings';++/**+ * Desktop: writes the diagnostics zip and selects it in Finder / Explorer. Shared by+ * Settings → About → Diagnostics and the feedback dialog; the returned `result`+ * lets the caller show which file to attach.+ */+export const useExportDiagnostics = () => {+ const { t } = useTranslation('common');+ const inFlightRef = useRef(false);+ const [exporting, setExporting] = useState(false);+ const [result, setResult] = useState<DiagnosticsBundleResult>();++ const exportDiagnostics = useCallback(async () => {+ if (inFlightRef.current) return;+ inFlightRef.current = true;+ setExporting(true);+ try {+ const next = await desktopSettingsService.exportDiagnostics();+ setResult(next);+ toast.success({+ description: t('diagnostics.export.successDesc', { fileName: next.fileName }),+ title: t('diagnostics.export.success'),+ });+ } catch (error) {+ console.error('[Diagnostics] export failed', error);+ toast.error(t('diagnostics.export.failed'));+ } finally {+ inFlightRef.current = false;+ setExporting(false);+ }+ }, [t]);++ return { exportDiagnostics, exporting, result };+};diff --git a/src/features/Settings/about/features/DebugLogs.tsx b/src/features/Settings/about/features/DebugLogs.tsxdeleted file mode 100644index 0665dde7daa..00000000000--- a/src/features/Settings/about/features/DebugLogs.tsx+++ /dev/null@@ -1,92 +0,0 @@-'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';--import { useRemoteDebuggingItem } from './useRemoteDebuggingItem';--/**- * 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 remoteDebuggingItem = useRemoteDebuggingItem();-- 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,- },- ...(remoteDebuggingItem ? [remoteDebuggingItem] : []),- ],- 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 381c81f5132..cb60baaa40f 100644--- a/src/features/Settings/about/index.tsx+++ b/src/features/Settings/about/index.tsx@@ -4,7 +4,6 @@ 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;@@ -18,7 +17,6 @@ const Page = ({ mobile, showSettingHeader = true }: PageProps) => {{showSettingHeader && <SettingHeader title={t('tab.about')} />}<About mobile={mobile} /><Analytics />- <DebugLogs /></>);};diff --git a/src/features/Settings/advanced/index.tsx b/src/features/Settings/advanced/index.tsxindex c35cd22681a..feae11a3d37 100644--- a/src/features/Settings/advanced/index.tsx+++ b/src/features/Settings/advanced/index.tsx@@ -18,6 +18,9 @@ import { useUserStore } from '@/store/user';import { settingsSelectors } from '@/store/user/selectors';import { type UserGeneralConfig } from '@/types/user/settings';+import { useDiagnosticsItems } from './useDiagnosticsItems';+import { useRemoteDebuggingItem } from './useRemoteDebuggingItem';+type UpdateChannelValue = 'canary' | 'stable';const Page = memo<{ showSettingHeader?: boolean }>(({ showSettingHeader = true }) => {@@ -47,6 +50,8 @@ const Page = memo<{ showSettingHeader?: boolean }>(({ showSettingHeader = true }});const enableGatewayMode = useServerConfigStore(serverConfigSelectors.enableGatewayMode);+ const diagnosticsItems = useDiagnosticsItems<UserGeneralConfig>();+ const remoteDebuggingItem = useRemoteDebuggingItem<UserGeneralConfig>();const [channel, setChannel] = useState<UpdateChannelValue>('stable');@@ -124,6 +129,8 @@ const Page = memo<{ showSettingHeader?: boolean }>(({ showSettingHeader = true }} satisfies FormFieldProps<UserGeneralConfig>,]: []),+ ...diagnosticsItems,+ ...(remoteDebuggingItem ? [remoteDebuggingItem] : []),],extra: loading && <Spin size="small" style={{ opacity: 0.5 }} />,title: t('tab.advanced.toolsAndDiagnostics.title'),diff --git a/src/features/Settings/advanced/useDiagnosticsItems.tsx b/src/features/Settings/advanced/useDiagnosticsItems.tsxnew file mode 100644index 00000000000..340144d32d2--- /dev/null+++ b/src/features/Settings/advanced/useDiagnosticsItems.tsx@@ -0,0 +1,128 @@+'use client';++import { isDesktop } from '@lobechat/const';+import type { DebugLoggingDuration, DebugLoggingSettings } from '@lobechat/electron-client-ipc';+import { Button, Flexbox, Select, toast } from '@lobehub/ui';+import { type FormFieldProps, type FormValues } from '@lobehub/ui/form';+import { FolderOpen, PackageOpen } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';+import useSWR from 'swr';++import { useExportDiagnostics } from '@/features/Electron/system/useExportDiagnostics';+import { SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';+import { desktopSettingsService } from '@/services/electron/settings';++type DebugLoggingChoice = DebugLoggingDuration | 'off';++const HOUR_MS = 60 * 60 * 1000;+const REFRESH_TIMED_MS = 60 * 1000;++/** The clock reading the remaining time is measured against, taken when the setting was read. */+type DebugLoggingState = DebugLoggingSettings & { readAt: number };++const fetchDebugLoggingSettings = async (): Promise<DebugLoggingState> => ({+ ...(await desktopSettingsService.getDebugLoggingSettings()),+ readAt: Date.now(),+});++const toChoice = (data: DebugLoggingSettings): DebugLoggingChoice => {+ if (data.alwaysOn) return 'always';+ if (!data.enabled) return 'off';+ return data.expiresAt === undefined ? 'always' : '24h';+};++/**+ * Desktop-only Settings → Advanced diagnostics rows. Exporting the diagnostics zip is+ * the main action; the raw log folder stays one click away for people who want the+ * files. Debug logs run for 24 hours or until turned off, and a timed run ends quietly:+ * the row's description is the only place that shows how long it has left.+ */+export const useDiagnosticsItems = <Values extends FormValues>(): FormFieldProps<Values>[] => {+ const { t } = useTranslation(['setting', 'common']);+ const [updating, setUpdating] = useState(false);+ const { exportDiagnostics, exporting } = useExportDiagnostics();++ const { data, mutate } = useSWR(+ isDesktop ? 'desktop-debug-logging-settings' : null,+ fetchDebugLoggingSettings,+ // A timed run is re-read every minute so the remaining time counts down and the row+ // flips to Off when the main process ends it; SWR pauses this while the window is hidden.+ { refreshInterval: (latest) => (latest?.expiresAt === undefined ? 0 : REFRESH_TIMED_MS) },+ );++ if (!isDesktop) return [];++ const choice = data ? toChoice(data) : undefined;++ const debugLogsDesc = (() => {+ if (!data || choice === 'off') return t('settingAbout.debugLogs.desc');+ if (data.alwaysOn) return t('settingAbout.debugLogs.devDesc');+ if (data.expiresAt === undefined) return t('settingAbout.debugLogs.status.always');+ const hours = Math.round((data.expiresAt - data.readAt) / HOUR_MS);+ return hours >= 1+ ? t('settingAbout.debugLogs.status.hours', { count: hours })+ : t('settingAbout.debugLogs.status.soon');+ })();++ return [+ {+ children: (+ <Flexbox horizontal gap={8} wrap={'wrap'}>+ <Button icon={FolderOpen} onClick={() => desktopSettingsService.openLogDirectory()}>+ {t('settingAbout.debugLogs.openDirectory')}+ </Button>+ <Button+ icon={PackageOpen}+ loading={exporting}+ type={'primary'}+ onClick={exportDiagnostics}+ >+ {t('diagnostics.export.action', { ns: 'common' })}+ </Button>+ </Flexbox>+ ),+ desc: t('settingAbout.diagnostics.bundle.desc'),+ label: (+ <SettingsSearchAnchor id={'advanced-diagnostics'}>+ {t('settingAbout.diagnostics.bundle.title')}+ </SettingsSearchAnchor>+ ),+ minWidth: undefined,+ },+ {+ children: (+ <Select+ disabled={!data || data.alwaysOn}+ loading={updating}+ style={{ minWidth: 160 }}+ value={choice}+ options={[+ { label: t('settingAbout.debugLogs.option.off'), value: 'off' },+ { label: t('settingAbout.debugLogs.option.24h'), value: '24h' },+ { label: t('settingAbout.debugLogs.option.always'), value: 'always' },+ ]}+ onChange={async (next: DebugLoggingChoice) => {+ setUpdating(true);+ try {+ const settings = await desktopSettingsService.setDebugLogging(next);+ await mutate({ ...settings, readAt: Date.now() }, { revalidate: false });+ } catch (error) {+ console.error('[Diagnostics] failed to update debug logs', error);+ toast.error(t('settingAbout.debugLogs.updateFailed'));+ } finally {+ setUpdating(false);+ }+ }}+ />+ ),+ desc: debugLogsDesc,+ label: (+ <SettingsSearchAnchor id={'advanced-debug-logs'}>+ {t('settingAbout.debugLogs.title')}+ </SettingsSearchAnchor>+ ),+ minWidth: undefined,+ },+ ];+};diff --git a/src/features/Settings/about/features/useRemoteDebuggingItem.tsx b/src/features/Settings/advanced/useRemoteDebuggingItem.tsxsimilarity index 81%rename from src/features/Settings/about/features/useRemoteDebuggingItem.tsxrename to src/features/Settings/advanced/useRemoteDebuggingItem.tsxindex bc435e0c29d..82ab1ffe3ce 100644--- a/src/features/Settings/about/features/useRemoteDebuggingItem.tsx+++ b/src/features/Settings/advanced/useRemoteDebuggingItem.tsx@@ -2,7 +2,7 @@import { isDesktop } from '@lobechat/const';import { confirmModal, Switch } from '@lobehub/ui';-import { type FormFieldProps } from '@lobehub/ui/form';+import { type FormFieldProps, type FormValues } from '@lobehub/ui/form';import { useState } from 'react';import { useTranslation } from 'react-i18next';import useSWR from 'swr';@@ -11,12 +11,14 @@ import { SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';import { desktopSettingsService } from '@/services/electron/settings';/**- * Desktop-only Diagnostics row: persist the Chromium DevTools protocol (CDP) port for+ * Desktop-only Settings → Advanced row (kept out of About, where everyday users look+ * for logs): persist the Chromium DevTools protocol (CDP) port for* every launch, so agents can drive a packaged build. Chromium reads the switch only at* startup, so the row says when a change still needs a restart. A launch option that* already opened CDP shows the switch on and locked.*/-export const useRemoteDebuggingItem = (): FormFieldProps | undefined => {+export const useRemoteDebuggingItem = <Values extends FormValues>():+ FormFieldProps<Values> | undefined => {const { t } = useTranslation('setting');const [updating, setUpdating] = useState(false);@@ -43,7 +45,9 @@ export const useRemoteDebuggingItem = (): FormFieldProps | undefined => {? t('settingAbout.remoteDebugging.launchOptionDesc'): data && data.enabled !== data.active? t('settingAbout.remoteDebugging.restartToApply')- : t('settingAbout.remoteDebugging.desc', { port });+ : data?.active+ ? t('settingAbout.remoteDebugging.activeDesc', { port })+ : t('settingAbout.remoteDebugging.desc');return {children: (@@ -70,7 +74,7 @@ export const useRemoteDebuggingItem = (): FormFieldProps | undefined => {),desc,label: (- <SettingsSearchAnchor id={'about-remote-debugging'}>+ <SettingsSearchAnchor id={'advanced-remote-debugging'}>{t('settingAbout.remoteDebugging.title')}</SettingsSearchAnchor>),diff --git a/src/features/SettingsSearch/items.ts b/src/features/SettingsSearch/items.tsindex 86f012e1398..974208a3aa7 100644--- a/src/features/SettingsSearch/items.ts+++ b/src/features/SettingsSearch/items.ts@@ -359,18 +359,27 @@ export const SETTINGS_SEARCH_ITEMS: SettingsSearchItem[] = [visible: (ctx) => ctx.isDesktop,},{- anchor: 'about-debug-logs',+ anchor: 'advanced-diagnostics',+ descKey: 'settingAbout.diagnostics.bundle.desc',+ keywords: ['diagnostics', 'export', 'logs', 'report', 'bug', 'feedback', 'zip'],+ labelKey: 'settingAbout.diagnostics.bundle.title',+ tab: SettingsTabs.Advanced,+ visible: (ctx) => ctx.isDesktop,+ },+ {+ anchor: 'advanced-debug-logs',descKey: 'settingAbout.debugLogs.desc',keywords: ['debug', 'logs', 'log level', 'diagnostics', 'troubleshoot'],labelKey: 'settingAbout.debugLogs.title',- tab: SettingsTabs.About,+ tab: SettingsTabs.Advanced,visible: (ctx) => ctx.isDesktop,},{- anchor: 'about-remote-debugging',+ anchor: 'advanced-remote-debugging',+ descKey: 'settingAbout.remoteDebugging.desc',keywords: ['remote debugging', 'cdp', 'devtools', 'diagnostics', 'debug port'],labelKey: 'settingAbout.remoteDebugging.title',- tab: SettingsTabs.About,+ tab: SettingsTabs.Advanced,visible: (ctx) => ctx.isDesktop,},{diff --git a/src/services/electron/settings.ts b/src/services/electron/settings.tsindex 36ee1d66faf..f0af29c7712 100644--- a/src/services/electron/settings.ts+++ b/src/services/electron/settings.ts@@ -1,4 +1,5 @@import {+ type DebugLoggingDuration,type NetworkProxySettings,type ShortcutUpdateResult,type WindowsShellMode,@@ -22,10 +23,17 @@ class DesktopSettingsService {};/**- * Turn `debug` records in `<userData>/logs/*.jsonl` on or off for packaged builds+ * Turn `debug` records in `<userData>/logs/*.jsonl` off, or on for a duration, in packaged builds*/- setDebugLoggingEnabled = async (enabled: boolean) => {- return ensureElectronIpc().system.setDebugLoggingEnabled(enabled);+ setDebugLogging = async (duration: DebugLoggingDuration | 'off') => {+ return ensureElectronIpc().system.setDebugLogging(duration);+ };++ /**+ * Zip the last day of logs with app and system details, and select it in the file manager+ */+ exportDiagnostics = async () => {+ return ensureElectronIpc().system.exportDiagnostics();};/**diff --git a/src/spa/entry.desktop.tsx b/src/spa/entry.desktop.tsxindex a1cbbc927a5..32c414d10cf 100644--- a/src/spa/entry.desktop.tsx+++ b/src/spa/entry.desktop.tsx@@ -12,6 +12,7 @@ import { createAppRouter } from '@/utils/router';import BootShell from './BootShell';import { isMainLayoutLocation } from './BootShell/routeScope';import { startAppInitialization } from './initialize/bootstrap';+import { installPlainDebugConsole } from './initialize/debugConsole';import { applyDesktopBootstrapIdentity } from './initialize/desktopIdentity';import { reserveTitleBarForFloatingLayers } from './initialize/floatingLayers';import { desktopRoutes } from './router/desktopRouter.config';@@ -22,6 +23,8 @@ import { createSPARoot } from './runtime';// within seconds instead of waiting for the mount-stage timeout.rendererOtaService.bootPing('loaded').catch(() => {});+// Ahead of the first `debug` line, so `renderer.jsonl` never records raw `%c` / `%s` formats.+installPlainDebugConsole();registerLocalDatabaseAdapter(createElectronLocalDatabaseAdapter());// Must stay synchronous and ahead of the first render: `useCacheScope` reads// `isIdentityResolved` to pick the cache partition, and on desktop preload isdiff --git a/src/spa/initialize/debugConsole.test.ts b/src/spa/initialize/debugConsole.test.tsnew file mode 100644index 00000000000..fea0576eef8--- /dev/null+++ b/src/spa/initialize/debugConsole.test.ts@@ -0,0 +1,76 @@+// Vitest resolves `debug` to its Node build (ANSI colors); the app bundles the browser one.+import type DebugModule from 'debug';+import browserDebug from 'debug/src/browser.js';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { formatConsoleArgs, installPlainDebugConsole } from './debugConsole';++describe('formatConsoleArgs', () => {+ // The arguments `debug` hands to `console.debug` for+ // `log('[completeOperation] operation %s (type=%s) completed, duration=%dms', id, type, ms)`;+ // `renderer.jsonl` used to record them space-joined and unformatted.+ it('formats a colored `debug` line into plain text', () => {+ expect(+ formatConsoleArgs([+ '%clobe-store:operation %c[completeOperation] operation %s (type=%s) completed, duration=%dms%c +1ms',+ 'color: #33CC99',+ 'color: inherit',+ 'op_3HRIYF1B',+ 'sendMessage',+ 1627,+ 'color: #33CC99',+ ]),+ ).toBe(+ 'lobe-store:operation [completeOperation] operation op_3HRIYF1B (type=sendMessage) completed, duration=1627ms +1ms',+ );+ });++ it('serializes objects for %o / %O and appends leftover arguments', () => {+ expect(formatConsoleArgs(['loaded %o in %fms', { a: 1 }, 1.5, 'extra', { b: [2] }])).toBe(+ 'loaded {"a":1} in 1.5ms extra {"b":[2]}',+ );+ });++ it('keeps %% literal and leaves specifiers without arguments untouched', () => {+ expect(formatConsoleArgs(['100%% done %s'])).toBe('100% done %s');+ });++ it('survives circular objects and errors', () => {+ const circular: Record<string, unknown> = { name: 'x' };+ circular.self = circular;+ const error = new Error('boom');+ error.stack = 'Error: boom\n at test';++ expect(formatConsoleArgs(['state %O', circular])).toBe(+ 'state {"name":"x","self":"[Circular]"}',+ );+ expect(formatConsoleArgs([error])).toBe('Error: boom\n at test');+ });+});++describe('installPlainDebugConsole', () => {+ const debug = browserDebug as typeof DebugModule;+ const originalLog = debug.log;++ afterEach(() => {+ debug.log = originalLog;+ debug.disable();+ vi.restoreAllMocks();+ });++ it('prints `debug` output as one formatted string', () => {+ const consoleDebug = vi.spyOn(console, 'debug').mockImplementation(() => {});+ installPlainDebugConsole(debug);+ debug.enable('lobe-test:*');+ const log = debug('lobe-test:format');+ log.useColors = true;++ log('operation %s took %dms', 'op_abc', 12);++ expect(consoleDebug).toHaveBeenCalledTimes(1);+ const [line, ...rest] = consoleDebug.mock.calls[0];+ expect(rest).toEqual([]);+ expect(line).toMatch(/^lobe-test:format operation op_abc took 12ms \+\d+m?s$/);+ expect(line).not.toContain('%');+ });+});diff --git a/src/spa/initialize/debugConsole.ts b/src/spa/initialize/debugConsole.tsnew file mode 100644index 00000000000..de4c69b874e--- /dev/null+++ b/src/spa/initialize/debugConsole.ts@@ -0,0 +1,79 @@+import debug from 'debug';++const MAX_VALUE_LENGTH = 2000;++const stringifyObject = (value: object) => {+ if (value instanceof Error) return value.stack || `${value.name}: ${value.message}`;+ const seen = new WeakSet<object>();+ try {+ const json = JSON.stringify(value, (_key, item: unknown) => {+ if (typeof item === 'bigint') return `${item}n`;+ if (typeof item === 'object' && item !== null) {+ if (seen.has(item)) return '[Circular]';+ seen.add(item);+ }+ return item;+ });+ return json ?? String(value);+ } catch {+ return String(value);+ }+};++const stringifyValue = (value: unknown): string => {+ const text = typeof value === 'object' && value !== null ? stringifyObject(value) : String(value);+ return text.length > MAX_VALUE_LENGTH ? `${text.slice(0, MAX_VALUE_LENGTH)}…` : text;+};++const toInteger = (value: unknown) => {+ const number = Number(value);+ return Number.isFinite(number) ? String(Math.trunc(number)) : 'NaN';+};++/**+ * Formats console arguments the way DevTools renders them, as one plain line:+ * `%s` / `%d` / `%i` / `%f` / `%o` / `%O` / `%j` take the next argument, `%c` drops+ * its CSS argument, `%%` is a literal `%`, and leftover arguments are appended.+ */+export const formatConsoleArgs = (args: unknown[]): string => {+ const [first, ...rest] = args;+ if (typeof first !== 'string') return args.map(stringifyValue).join(' ');++ let index = 0;+ const text = first.replaceAll(/%([%Ocdfijos])/g, (match, specifier: string) => {+ if (specifier === '%') return '%';+ if (index >= rest.length) return match;+ const value = rest[index++];+ switch (specifier) {+ case 'c': {+ return '';+ }+ case 'd':+ case 'i': {+ return toInteger(value);+ }+ case 'f': {+ return String(Number(value));+ }+ default: {+ return stringifyValue(value);+ }+ }+ });++ return [text, ...rest.slice(index).map(stringifyValue)].join(' ');+};++/**+ * Desktop only: the main process records every renderer console line into+ * `renderer.jsonl` from Electron's `console-message` event, which carries the raw+ * format string and its arguments joined by spaces (`%clobe-store %c… %s color: …`).+ * The argument boundaries are gone by then, so `debug` output is formatted here,+ * before it reaches the console. DevTools shows these lines without colors.+ */+export const installPlainDebugConsole = (target: Pick<typeof debug, 'log'> = debug) => {+ target.log = (...args: unknown[]) => {+ // eslint-disable-next-line no-console+ console.debug(formatConsoleArgs(args));+ };+};