Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复升级重启时的窗口销毁报错,补充开屏卡住诊断与 PID 复用误报处理
david195930415bad
diff --git a/apps/desktop/src/main/__tests__/mainWindowMaximizeRecovery.test.ts b/apps/desktop/src/main/__tests__/mainWindowMaximizeRecovery.test.tsindex 9b15d89870..cf3349b7f7 100644--- a/apps/desktop/src/main/__tests__/mainWindowMaximizeRecovery.test.ts+++ b/apps/desktop/src/main/__tests__/mainWindowMaximizeRecovery.test.ts@@ -424,11 +424,18 @@ describe('installMainWindowNativeRestoreIntent', () => {const windowListeners = new Map<string, Listener>();const webContentsListeners = new Map<string, Listener>();const windowMessageListeners = new Map<number, (wParam: Buffer, lParam: Buffer) => void>();+ const native = { destroyed: false };+ const assertAlive = () => {+ if (native.destroyed) throw new TypeError('Object has been destroyed');+ };const removeListener = vi.fn((event: string) => windowListeners.delete(event));const removeWebContentsListener = vi.fn((event: string) => webContentsListeners.delete(event));- const unhookWindowMessage = vi.fn((message: number) => windowMessageListeners.delete(message));+ const unhookWindowMessage = vi.fn((message: number) => {+ assertAlive();+ return windowMessageListeners.delete(message);+ });const win = {- isDestroyed: () => false,+ isDestroyed: () => native.destroyed,isVisible: () => true,isMaximized: () => true,isMinimized: () => false,@@ -448,6 +455,7 @@ describe('installMainWindowNativeRestoreIntent', () => {} as unknown as MaximizeRecoveryNativeWindow;return {win,+ native,windowListeners,webContentsListeners,windowMessageListeners,@@ -457,6 +465,19 @@ describe('installMainWindowNativeRestoreIntent', () => {};}+ // The main window disposes this from its 'closed' event, after the native window is gone.+ // Touching it then threw "Object has been destroyed" as an uncaughtException during the+ // Windows update relaunch (forceQuit destroys every window).+ it('disposes without touching a window that is already destroyed', () => {+ const h = createNativeHarness();+ const dispose = installMainWindowNativeRestoreIntent(h.win, vi.fn(), 'win32');++ h.native.destroyed = true;++ expect(() => dispose()).not.toThrow();+ expect(h.unhookWindowMessage).not.toHaveBeenCalled();+ });+it('marks Windows native restore gestures before unmaximize', () => {const h = createNativeHarness();const notify = vi.fn();diff --git a/apps/desktop/src/main/__tests__/startupDiagnostics.test.ts b/apps/desktop/src/main/__tests__/startupDiagnostics.test.tsindex c27e48d66c..59e93f2488 100644--- a/apps/desktop/src/main/__tests__/startupDiagnostics.test.ts+++ b/apps/desktop/src/main/__tests__/startupDiagnostics.test.ts@@ -215,6 +215,55 @@ describe('analyzePreviousRuns classification', () => {});});+// 实测 Windows 用户日志:10-14 写下的标记 pid 被别的进程复用,连续 9 天每次启动都报+// 「another instance appears to be running」,误导「旧进程残留」的排查,真实退出结论也丢了。+describe('resolveReusedPids', () => {+ const markerStartedAt = '2026-07-07T10:00:00.000Z';+ const startTimesOf = (entries: Array<[number, number]>) => async () => new Map(entries);+ const reusedAt = Date.parse('2026-07-16T08:00:00.000Z');++ it('PID 已被更晚启动的进程占用 → 按标记状态补出退出结论并清掉标记', async () => {+ const file = writeMarker({ pid: 2184, state: 'running', startedAt: markerStartedAt });+ const store = makeStore({ alivePids: [2184] });+ const stillRunning = store.analyzePreviousRuns();++ const resolved = await store.resolveReusedPids(stillRunning, startTimesOf([[2184, reusedAt]]));++ expect(resolved).toEqual([+ expect.objectContaining({ kind: 'abnormal', pidReusedSince: '2026-07-16T08:00:00.000Z' }),+ ]);+ expect(fs.existsSync(file)).toBe(false);+ });++ it('核对前旧实例已正常退出 → 按重读的 exited 标记判 clean,不误判 abnormal', async () => {+ writeMarker({ pid: 2186, state: 'running', startedAt: markerStartedAt });+ const store = makeStore({ alivePids: [2186] });+ const stillRunning = store.analyzePreviousRuns();+ writeMarker({ pid: 2186, state: 'exited', exitCode: 0, startedAt: markerStartedAt });++ const resolved = await store.resolveReusedPids(stillRunning, startTimesOf([[2186, reusedAt]]));++ expect(resolved).toEqual([expect.objectContaining({ kind: 'clean' })]);+ });++ it.each([+ ['启动时刻读不到', [] as Array<[number, number]>],+ [+ '占用者早于标记启动(就是写标记的实例)',+ [[2185, Date.parse(markerStartedAt) - 1_000]] as Array<[number, number]>,+ ],+ ])('%s → 保持 still-running,标记保留', async (_label, entries) => {+ const file = writeMarker({ pid: 2185, state: 'running', startedAt: markerStartedAt });+ const store = makeStore({ alivePids: [2185] });++ const resolved = await store.resolveReusedPids(store.analyzePreviousRuns(), startTimesOf(entries));++ expect(resolved).toEqual([expect.objectContaining({ kind: 'still-running' })]);+ expect(resolved[0].pidReusedSince).toBeUndefined();+ expect(fs.existsSync(file)).toBe(true);+ });+});+describe('scanCrashDumps', () => {it('finds nested .dmp files within window, sorted by mtime desc; ignores old and non-dmp', () => {const reportsDir = path.join(tmpDir, 'reports');diff --git a/apps/desktop/src/main/__tests__/startupGateStallReport.test.ts b/apps/desktop/src/main/__tests__/startupGateStallReport.test.tsnew file mode 100644index 0000000000..15b390efac--- /dev/null+++ b/apps/desktop/src/main/__tests__/startupGateStallReport.test.ts@@ -0,0 +1,86 @@+/**+ * 开屏卡住诊断的 main 入口:这一行写进 `renderer-guard`,会随「日志与反馈」离开用户机器+ * (docs/dev-rules/log-upload-and-redaction.md §1.2)。锁住两件事:+ * - 只认主窗口顶层 frame,且只写白名单字段——renderer 夹带的任何文本都不能落进日志;+ * - 进程内封顶,renderer 异常重载不会刷屏。+ */+import { describe, expect, it, vi } from 'vitest';++import type { StartupGateStallSnapshot } from '../../shared/startupGateStall';+import { createStartupGateStallReporter } from '../startupGateStallReport';++const snapshot: StartupGateStallSnapshot = {+ elapsedMs: 48_300,+ waitingMs: 20_400,+ documentVisible: true,+ authInitializing: false,+ authMode: 'cloud',+ authenticated: true,+ canEnterApp: true,+ envStatus: 'passed',+ localDbGate: 'ready',+ coverHeld: false,+ handoffPhase: 'boot',+ handoffBranch: 'none',+ brandStageMounted: true,+ brandAssetsReady: true,+ splashExited: false,+ splashExitCompleted: false,+ loginPanelMounted: false,+};++function setup(fromMainWindow = true) {+ const warn = vi.fn();+ const report = createStartupGateStallReporter({+ isMainWindowTopFrame: () => fromMainWindow,+ warn,+ });+ return { warn, report };+}++describe('startup gate stall report', () => {+ it('writes one whitelisted line for the main window', () => {+ const { warn, report } = setup();++ report({}, snapshot);++ expect(warn).toHaveBeenCalledOnce();+ expect(warn.mock.calls[0][0]).toBe(+ 'startup gate held for 20s (renderer up 48s): elapsedMs=48300 waitingMs=20400 ' ++ 'documentVisible=true ' ++ 'authInitializing=false authMode=cloud authenticated=true canEnterApp=true ' ++ 'envStatus=passed localDbGate=ready coverHeld=false handoffPhase=boot handoffBranch=none ' ++ 'brandStageMounted=true brandAssetsReady=true splashExited=false ' ++ 'splashExitCompleted=false loginPanelMounted=false',+ );+ });++ it.each([+ ['an extra field carrying text', { ...snapshot, note: 'C:\\Users\\alice\\secret.txt' }],+ ['a free-text enum value', { ...snapshot, envStatus: 'typed by user' }],+ ['a missing field', { ...snapshot, loginPanelMounted: undefined }],+ ['a non-integer duration', { ...snapshot, elapsedMs: 1.5 }],+ ])('drops a payload with %s', (_label, payload) => {+ const { warn, report } = setup();++ report({}, payload);++ expect(warn).not.toHaveBeenCalled();+ });++ it('ignores senders other than the main window top frame', () => {+ const { warn, report } = setup(false);++ report({}, snapshot);++ expect(warn).not.toHaveBeenCalled();+ });++ it('stops after three reports per process', () => {+ const { warn, report } = setup();++ for (let i = 0; i < 5; i += 1) report({}, snapshot);++ expect(warn).toHaveBeenCalledTimes(3);+ });+});diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex a537967ab9..392986fe30 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -540,6 +540,8 @@ import {import { onQuit, installQuitHandler } from './lifecycle';import { initStartupDiagnostics } from './startup-diagnostics';+import { createStartupGateStallReporter } from './startupGateStallReport';+import { STARTUP_GATE_STALL_CHANNEL } from '../shared/startupGateStall';import {installPowerEventDiagnostics,installWindowResponsivenessDiagnostics,@@ -4720,6 +4722,20 @@ const registerIpcHandlers = () => {event.returnValue = getAppDisplayVersionInfo();});+ // 开屏卡住诊断:renderer 的 r: 日志不进上传,这条快照由 main 校验后写进 renderer-guard。+ // 只在本机使用,不进 device-link 白名单。+ ipcMain.on(+ STARTUP_GATE_STALL_CHANNEL,+ createStartupGateStallReporter({+ isMainWindowTopFrame: (event) => {+ const { sender, senderFrame } = event as Electron.IpcMainEvent;+ const main = mainWindowRef && !mainWindowRef.isDestroyed() ? mainWindowRef : null;+ return main !== null && sender === main.webContents && senderFrame === sender.mainFrame;+ },+ warn: (message) => rendererGuardLog.warn(message),+ }),+ );+// Renderer → main 日志转发:走 unified logger 的 writeFromRenderer,// 让 main 的 level filter 生效(scope 加 r: 前缀以区分来源)。ipcMain.on(diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.tsindex ada7ece4f3..a4dd4456cd 100644--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts@@ -120,6 +120,7 @@ import { handleGhostSecretsRequest } from '../ghostSecretsEndpoint.js';import { ownerScopedGhostPartitionForInstalledGhost } from '../../ghostWebviewPartition.js';import {electronSandboxAdapter,+ ghostIdForLogicWebContents,invokeGhostMobileRelay,fetchGhostMobilePage,ensureGhostProtocolRegistered,@@ -770,6 +771,30 @@ describe('electronSandboxAdapter owner partition', () => {).not.toMatch(/^persist:/);handle.destroy();});++ // 更新重启的 forceQuit 先逐个 destroy 全部 BrowserWindow,before-quit 才 destroyAll;+ // 已销毁窗口再读 webContents 抛 Object has been destroyed,曾打断整个 destroyAll。+ it('收尾已被外部销毁的逻辑沙箱时不再访问窗口,且解除管子验身绑定', () => {+ const handle = electronSandboxAdapter.create(ghost('gone-first'));+ const win = harness.BrowserWindow.mock.results[0]!.value as {+ webContents: { id: number };+ isDestroyed: ReturnType<typeof vi.fn>;+ destroy: ReturnType<typeof vi.fn>;+ };+ const logicId = win.webContents.id;+ expect(ghostIdForLogicWebContents(logicId)).not.toBeNull();++ win.isDestroyed.mockReturnValue(true);+ Object.defineProperty(win, 'webContents', {+ get() {+ throw new TypeError('Object has been destroyed');+ },+ });++ expect(() => handle.destroy()).not.toThrow();+ expect(win.destroy).not.toHaveBeenCalled();+ expect(ghostIdForLogicWebContents(logicId)).toBeNull();+ });});describe('read-only agent model directory', () => {diff --git a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.tsindex 1395b1e2c8..ce205f9441 100644--- a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts+++ b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts@@ -911,6 +911,10 @@ async function serveGhostGallery(storagePart: string, protocolHost: string): Proclass ElectronSandboxHandle implements SandboxHandle {private win: BrowserWindow | null;+ // 建窗时记下:窗口可能先于 destroy() 被外部销毁(更新重启的 forceQuit 会逐个+ // destroy 全部 BrowserWindow),那时再读 win.webContents 会抛 Object has been+ // destroyed,打断 destroyAll 让后续沙箱与 Node runtime 都收不掉。+ private readonly logicWebContentsId: number;private goneCb: ((details: { reason: string }) => void) | null = null;private destroyed = false;@@ -937,8 +941,9 @@ class ElectronSandboxHandle implements SandboxHandle {devTools: !ghostSandboxDevToolsDisabled,},});- ghostWebContentsIds.add(this.win.webContents.id);- logicWebContentsToGhost.set(this.win.webContents.id, installedGhostStoragePart(ghost));+ this.logicWebContentsId = this.win.webContents.id;+ ghostWebContentsIds.add(this.logicWebContentsId);+ logicWebContentsToGhost.set(this.logicWebContentsId, installedGhostStoragePart(ghost));this.win.webContents.on('render-process-gone', (_event, details) => {if (this.destroyed) return;// 延迟一拍再收尸:不在 Chromium 事件分发中途销毁窗口(重入风险)。@@ -959,10 +964,8 @@ class ElectronSandboxHandle implements SandboxHandle {this.destroyed = true;const win = this.win;this.win = null;- if (win) {- logicWebContentsToGhost.delete(win.webContents.id);- if (!win.isDestroyed()) win.destroy();- }+ logicWebContentsToGhost.delete(this.logicWebContentsId);+ if (win && !win.isDestroyed()) win.destroy();}crashForTest(): void {diff --git a/apps/desktop/src/main/log-upload/sourceAllowlist.ts b/apps/desktop/src/main/log-upload/sourceAllowlist.tsindex ddebb7bab1..fd208338c1 100644--- a/apps/desktop/src/main/log-upload/sourceAllowlist.ts+++ b/apps/desktop/src/main/log-upload/sourceAllowlist.ts@@ -33,7 +33,9 @@ const ALLOWED_ROOT_SCOPES: readonly string[] = ['idleManager', // 空闲判定(自动更新重启时机依赖它)'app-presence', // 前后台/可见性状态机'appSessionState', // 应用级会话状态机(只记状态转换,不记内容)- // 渲染进程启动守卫 —— 白屏排查必需(preload-error / 加载失败 / boot guard 重试)。+ // 渲染进程启动守卫 —— 白屏排查必需(preload-error / 加载失败 / boot guard 重试),以及+ // 开屏卡住时的启动门快照(main 按 shared/startupGateStall.ts 白名单逐字段重建,只有布尔、+ // 固定枚举与有界毫秒数,多余字段整份丢弃)。// ⚠️ 只含这些无用户内容的加载失败信号:渲染进程 console 的转发**不在**这个 scope 下,// 它单独走 `renderer-console`(见下方 NOTABLE_DENIED_ROOTS)。两者曾共用同一个 scope,// 于是整类渲染进程 console 正文跟着被放行 —— 2026-08-04 用真实 dev 日志跑采集时发现。diff --git a/apps/desktop/src/main/mainWindowMaximizeRecovery.ts b/apps/desktop/src/main/mainWindowMaximizeRecovery.tsindex 6143af4628..2a4329d1e7 100644--- a/apps/desktop/src/main/mainWindowMaximizeRecovery.ts+++ b/apps/desktop/src/main/mainWindowMaximizeRecovery.ts@@ -161,6 +161,10 @@ export function installMainWindowNativeRestoreIntent(win.webContents.on('before-input-event', onBeforeInputEvent);return (): void => {+ // The caller unhooks from the window's 'closed' event, when the native window is already+ // gone: its listeners and message hook died with it, and calling into it throws+ // "Object has been destroyed" (seen as an uncaughtException during update relaunch).+ if (win.isDestroyed()) return;win.removeListener('will-move', onWillMove);win.removeListener('will-resize', onWillResize);win.unhookWindowMessage(WM_SYSCOMMAND);diff --git a/apps/desktop/src/main/ownerNamespaceMigration.ts b/apps/desktop/src/main/ownerNamespaceMigration.tsindex 831e2e52db..40387cbeb3 100644--- a/apps/desktop/src/main/ownerNamespaceMigration.ts+++ b/apps/desktop/src/main/ownerNamespaceMigration.ts@@ -1,5 +1,4 @@import { app } from 'electron';-import { execFile } from 'node:child_process';import { randomUUID } from 'node:crypto';import fsSync from 'node:fs';import fs from 'node:fs/promises';@@ -25,6 +24,7 @@ import {readBoundedFileNoFollowSync,} from './utils/readBoundedFile.js';import { readAtomicFileSync } from './utils/atomicWriteFile.js';+import { readProcessIdentities, type ProcessIdentitySnapshot } from './processIdentity.js';const CLAIM_MARKER = '.owner-namespace-claim-v1.json';const LEGACY_GHOST_RECOVERY_MARKER = '.legacy-ghost-recovery-v1.json';@@ -120,11 +120,6 @@ interface RegisteredInstanceCandidate {rootDir: string | undefined;}-interface ProcessIdentitySnapshot {- startedAtMs: number;- command: string;-}-type ProcessIdentityReader = (pid: number) => ProcessIdentitySnapshot | null;/** claim 被推迟(而非放弃)的原因;下次独占启动时自然重试完成。 */@@ -151,7 +146,6 @@ const log = createLogger('ownerNamespaceMigration');// sampling skew): a large window would permanently classify a PID reused// shortly after the record was written as the old Cindy process.const PID_REUSE_TOLERANCE_MS = 2_000;-const PROCESS_IDENTITY_QUERY_TIMEOUT_MS = 1_500;const STALE_PROCESS_PROOF_TTL_MS = 10_000;const legacyGhostMigrationResults = new Map<string,@@ -335,112 +329,6 @@ function isPidAliveDefault(pid: number): boolean {}}-function parseProcessIdentityOutput(raw: string): ProcessIdentitySnapshot | null {- const newline = raw.indexOf('\n');- if (newline < 0) return null;- const startedAtMs = Date.parse(raw.slice(0, newline).trim());- const command = raw.slice(newline + 1).trim();- if (!Number.isFinite(startedAtMs) || startedAtMs <= 0 || command.length === 0) return null;- return { startedAtMs, command };-}--function execFileUtf8(- file: string,- args: readonly string[],- options: {- maxBuffer: number;- env?: NodeJS.ProcessEnv;- windowsHide?: boolean;- },-): Promise<string> {- return new Promise((resolve, reject) => {- execFile(- file,- [...args],- {- ...options,- encoding: 'utf-8',- timeout: PROCESS_IDENTITY_QUERY_TIMEOUT_MS,- },- (error, stdout) => {- if (error) reject(error);- else resolve(stdout);- },- );- });-}--/** Read all candidate process identities asynchronously with one OS query per scan. */-async function readProcessIdentitiesDefault(- pids: readonly number[],-): Promise<ReadonlyMap<number, ProcessIdentitySnapshot | null>> {- const uniquePids = [...new Set(pids)].filter((pid) => Number.isInteger(pid) && pid > 0);- const result = new Map<number, ProcessIdentitySnapshot | null>();- if (uniquePids.length === 0) return result;- try {- if (process.platform === 'win32') {- const powershell = `${process.env.SystemRoot ?? 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;- const output = await execFileUtf8(- powershell,- [- '-NoProfile',- '-NonInteractive',- '-Command',- `$ids = @(${uniquePids.join(',')}); ` +- '$rows = Get-Process -Id $ids -ErrorAction Stop | ForEach-Object { ' +- '$command = if ($_.Path) { $_.Path } else { $_.ProcessName }; ' +- "[PSCustomObject]@{ pid = $_.Id; startedAt = $_.StartTime.ToUniversalTime().ToString('O'); command = $command } }; " +- '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); ' +- '$rows | ConvertTo-Json -Compress',- ],- {- maxBuffer: 16_384,- windowsHide: true,- },- );- const parsed = JSON.parse(output) as unknown;- const rows = Array.isArray(parsed) ? parsed : [parsed];- for (const row of rows) {- if (!row || typeof row !== 'object') continue;- const value = row as Record<string, unknown>;- const pid = value.pid;- const startedAtMs = typeof value.startedAt === 'string' ? Date.parse(value.startedAt) : NaN;- const command = value.command;- if (- typeof pid === 'number' &&- Number.isInteger(pid) &&- Number.isFinite(startedAtMs) &&- startedAtMs > 0 &&- typeof command === 'string' &&- command.length > 0- ) {- result.set(pid, { startedAtMs, command });- }- }- return result;- }-- const output = await execFileUtf8(- 'ps',- ['-p', uniquePids.join(','), '-o', 'pid=', '-o', 'lstart=', '-o', 'command='],- {- maxBuffer: 16_384,- env: { ...process.env, LC_ALL: 'C' },- },- );- for (const line of output.split('\n')) {- const match = /^\s*(\d+)\s+(.{24})\s+([\s\S]+)$/.exec(line.trimEnd());- if (!match) continue;- const pid = Number(match[1]);- const identity = parseProcessIdentityOutput(`${match[2]}\n${match[3]}`);- if (identity) result.set(pid, identity);- }- } catch {- // Missing entries keep the caller fail-closed when provenance is ambiguous.- }- return result;-}-function looksLikeCindyRuntime(command: string, rootDir?: string): boolean {const normalizedCommand = command.replaceAll('\\', '/').toLowerCase();const normalizedRoot = rootDir?.replaceAll('\\', '/').toLowerCase();@@ -479,7 +367,7 @@ async function readProcessIdentitiesForPids(pids: readonly number[],reader?: ProcessIdentityReader,): Promise<ReadonlyMap<number, ProcessIdentitySnapshot | null>> {- if (!reader) return readProcessIdentitiesDefault(pids);+ if (!reader) return readProcessIdentities(pids);return new Map(pids.map((pid) => [pid, readProcessIdentitySafely(reader, pid)] as const));}diff --git a/apps/desktop/src/main/processIdentity.ts b/apps/desktop/src/main/processIdentity.tsnew file mode 100644index 0000000000..2cf20dc912--- /dev/null+++ b/apps/desktop/src/main/processIdentity.ts@@ -0,0 +1,193 @@+import { execFile } from 'node:child_process';++/**+ * OS-reported identity of a live PID. A PID alone cannot tell an old Cindy process from an+ * unrelated program that later received the same number: macOS and Windows reuse PIDs+ * routinely. Kept dependency-free so early startup code can use it.+ */+export interface ProcessIdentitySnapshot {+ startedAtMs: number;+ command: string;+}++const PROCESS_IDENTITY_QUERY_TIMEOUT_MS = 1_500;++function parseProcessIdentityOutput(raw: string): ProcessIdentitySnapshot | null {+ const newline = raw.indexOf('\n');+ if (newline < 0) return null;+ const startedAtMs = Date.parse(raw.slice(0, newline).trim());+ const command = raw.slice(newline + 1).trim();+ if (!Number.isFinite(startedAtMs) || startedAtMs <= 0 || command.length === 0) return null;+ return { startedAtMs, command };+}++function execFileUtf8(+ file: string,+ args: readonly string[],+ options: {+ maxBuffer: number;+ env?: NodeJS.ProcessEnv;+ windowsHide?: boolean;+ timeoutMs?: number;+ },+): Promise<string> {+ const { timeoutMs = PROCESS_IDENTITY_QUERY_TIMEOUT_MS, ...execOptions } = options;+ return new Promise((resolve, reject) => {+ execFile(+ file,+ [...args],+ {+ ...execOptions,+ encoding: 'utf-8',+ timeout: timeoutMs,+ },+ (error, stdout) => {+ if (error) reject(error);+ else resolve(stdout);+ },+ );+ });+}++/**+ * Read all candidate process identities asynchronously with one OS query per scan.+ * PIDs whose identity cannot be read are absent from the result; callers must treat that+ * as "unknown", never as proof that the process is gone.+ */+export async function readProcessIdentities(+ pids: readonly number[],+): Promise<ReadonlyMap<number, ProcessIdentitySnapshot | null>> {+ const uniquePids = [...new Set(pids)].filter((pid) => Number.isInteger(pid) && pid > 0);+ const result = new Map<number, ProcessIdentitySnapshot | null>();+ if (uniquePids.length === 0) return result;+ try {+ if (process.platform === 'win32') {+ const powershell = `${process.env.SystemRoot ?? 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;+ const output = await execFileUtf8(+ powershell,+ [+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ `$ids = @(${uniquePids.join(',')}); ` ++ '$rows = Get-Process -Id $ids -ErrorAction Stop | ForEach-Object { ' ++ '$command = if ($_.Path) { $_.Path } else { $_.ProcessName }; ' ++ "[PSCustomObject]@{ pid = $_.Id; startedAt = $_.StartTime.ToUniversalTime().ToString('O'); command = $command } }; " ++ '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); ' ++ '$rows | ConvertTo-Json -Compress',+ ],+ {+ maxBuffer: 16_384,+ windowsHide: true,+ },+ );+ const parsed = JSON.parse(output) as unknown;+ const rows = Array.isArray(parsed) ? parsed : [parsed];+ for (const row of rows) {+ if (!row || typeof row !== 'object') continue;+ const value = row as Record<string, unknown>;+ const pid = value.pid;+ const startedAtMs = typeof value.startedAt === 'string' ? Date.parse(value.startedAt) : NaN;+ const command = value.command;+ if (+ typeof pid === 'number' &&+ Number.isInteger(pid) &&+ Number.isFinite(startedAtMs) &&+ startedAtMs > 0 &&+ typeof command === 'string' &&+ command.length > 0+ ) {+ result.set(pid, { startedAtMs, command });+ }+ }+ return result;+ }++ const output = await execFileUtf8(+ 'ps',+ ['-p', uniquePids.join(','), '-o', 'pid=', '-o', 'lstart=', '-o', 'command='],+ {+ maxBuffer: 16_384,+ env: { ...process.env, LC_ALL: 'C' },+ },+ );+ for (const line of output.split('\n')) {+ const match = /^\s*(\d+)\s+(.{24})\s+([\s\S]+)$/.exec(line.trimEnd());+ if (!match) continue;+ const pid = Number(match[1]);+ const identity = parseProcessIdentityOutput(`${match[2]}\n${match[3]}`);+ if (identity) result.set(pid, identity);+ }+ } catch {+ // Missing entries keep the caller fail-closed when provenance is ambiguous.+ }+ return result;+}++/**+ * Read only OS process start times, for background checks that run off the startup path.+ *+ * Unlike readProcessIdentities, Windows uses `Win32_Process.CreationDate`: `Get-Process`+ * cannot read `StartTime` of service or elevated processes from a non-elevated caller, and+ * those are exactly the programs that tend to inherit a PID for days. PIDs without a readable+ * start time are absent from the result and must be treated as "unknown".+ */+export async function readProcessStartTimes(+ pids: readonly number[],+ options: { timeoutMs: number },+): Promise<ReadonlyMap<number, number>> {+ const uniquePids = [...new Set(pids)].filter((pid) => Number.isInteger(pid) && pid > 0);+ const result = new Map<number, number>();+ if (uniquePids.length === 0) return result;+ try {+ if (process.platform === 'win32') {+ const powershell = `${process.env.SystemRoot ?? 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;+ const filter = uniquePids.map((pid) => `ProcessId=${pid}`).join(' OR ');+ const output = await execFileUtf8(+ powershell,+ [+ '-NoProfile',+ '-NonInteractive',+ '-Command',+ `$rows = @(Get-CimInstance -ClassName Win32_Process -Filter '${filter}' -ErrorAction Stop | ` ++ 'Where-Object { $_.CreationDate } | ForEach-Object { ' ++ "[PSCustomObject]@{ pid = [int]$_.ProcessId; startedAt = $_.CreationDate.ToUniversalTime().ToString('O') } }); " ++ '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); ' ++ 'ConvertTo-Json -InputObject $rows -Compress',+ ],+ { maxBuffer: 16_384, windowsHide: true, timeoutMs: options.timeoutMs },+ );+ const parsed = JSON.parse(output) as unknown;+ for (const row of Array.isArray(parsed) ? parsed : [parsed]) {+ if (!row || typeof row !== 'object') continue;+ const value = row as Record<string, unknown>;+ const startedAtMs = typeof value.startedAt === 'string' ? Date.parse(value.startedAt) : NaN;+ if (+ typeof value.pid === 'number' &&+ Number.isInteger(value.pid) &&+ Number.isFinite(startedAtMs) &&+ startedAtMs > 0+ ) {+ result.set(value.pid, startedAtMs);+ }+ }+ return result;+ }++ const output = await execFileUtf8(+ 'ps',+ ['-p', uniquePids.join(','), '-o', 'pid=', '-o', 'lstart='],+ { maxBuffer: 16_384, env: { ...process.env, LC_ALL: 'C' }, timeoutMs: options.timeoutMs },+ );+ for (const line of output.split('\n')) {+ const match = /^\s*(\d+)\s+(.{24})\s*$/.exec(line.trimEnd());+ if (!match) continue;+ const startedAtMs = Date.parse(match[2].trim());+ if (Number.isFinite(startedAtMs) && startedAtMs > 0)+ result.set(Number(match[1]), startedAtMs);+ }+ } catch {+ // Missing entries keep the caller fail-closed when provenance is ambiguous.+ }+ return result;+}diff --git a/apps/desktop/src/main/startup-diagnostics.ts b/apps/desktop/src/main/startup-diagnostics.tsindex 4241e41ba7..53d0d6a113 100644--- a/apps/desktop/src/main/startup-diagnostics.ts+++ b/apps/desktop/src/main/startup-diagnostics.ts@@ -32,19 +32,30 @@** 平台注记:process.kill(pid, 0) 探活在 macOS / Windows 均可用(Windows 上由* libuv 转 OpenProcess 探测);标记文件极小(<400B)、30s 一次写 userData,两端- * I/O 开销可忽略。pid 复用理论上可能让死进程被误判"还活着"而漏报一次,概率极低- * 且只影响诊断不影响功能,接受。+ * I/O 开销可忽略。pid 复用会让死进程被误判"还活着":实测 Windows 上一份旧标记被+ * 复用 pid 连续保留 9 天,每次启动都误报并存实例。启动后台用 OS 进程启动时刻核对+ * (resolveReusedPids),确认复用后补出该实例的退出结论并清掉标记。*/import { app, crashReporter } from 'electron';import fs from 'node:fs';import path from 'node:path';import { createLogger } from './logger';+import { readProcessStartTimes } from './processIdentity';const log = createLogger('startup-diagnostics');/** 心跳刷新间隔。30s:足够定位 hang 的时间窗,又不构成可感知的 I/O 负担。 */const HEARTBEAT_INTERVAL_MS = 30_000;+/**+ * 进程启动时刻与标记 startedAt 的比较容差:`ps` 只报到秒,再留一点采样偏差。+ * 写标记的进程启动必然早于 startedAt,因此容差只需覆盖精度,不必放大。+ */+const PID_REUSE_TOLERANCE_MS = 2_000;+/** PID 复用核对要拉起 PowerShell / ps,延后到启动高峰之后,不和首屏抢 CPU。 */+const PID_REUSE_CHECK_DELAY_MS = 15_000;+/** 后台核对不在启动关键路径上,给冷启动的 PowerShell 留足时间;超时按「读不到」处理。 */+const PID_REUSE_QUERY_TIMEOUT_MS = 10_000;/** crash dump 扫描回看窗口。 */const DUMP_SCAN_WINDOW_MS = 14 * 24 * 60 * 60 * 1000;/** dump 清单最多列几个(按 mtime 降序),防日志刷屏。 */@@ -81,6 +92,16 @@ export interface PreviousRunReport {kind: PreviousRunReportKind;file: string;marker?: RunMarker;+ /** 标记的 pid 仍存活、但已被这一时刻启动的另一个进程占用(PID 复用)。 */+ pidReusedSince?: string;+}++/** pid 已不属于写标记的实例时,按标记最后状态给出它的退出结论。 */+function classifyEndedRun(marker: RunMarker): PreviousRunReportKind {+ if (marker.state === 'exited') {+ return marker.exitCode != null && marker.exitCode !== 0 ? 'crash-exit' : 'clean';+ }+ return marker.state === 'shutdown-begin' ? 'shutdown-incomplete' : 'abnormal';}export interface RunMarkerStoreDeps {@@ -230,18 +251,65 @@ export class RunMarkerStore {reports.push({ kind: 'still-running', file, marker });continue;}- const kind: PreviousRunReportKind =- marker.state === 'exited'- ? (marker.exitCode != null && marker.exitCode !== 0 ? 'crash-exit' : 'clean')- : marker.state === 'shutdown-begin'- ? 'shutdown-incomplete'- : 'abnormal';- reports.push({ kind, file, marker });+ reports.push({ kind: classifyEndedRun(marker), file, marker });this.remove(file);}return reports;}+ /**+ * analyzePreviousRuns 只凭 PID 存活判 still-running。Windows / macOS 会复用 PID:旧实例+ * 早已退出、编号被别的程序占用时,它的标记会被永久保留,每次启动都误报「另一个实例在运行」,+ * 而它真正的退出结论永远不会出现。+ *+ * 用 OS 报告的进程启动时刻核对:写标记的进程启动时刻必然不晚于 marker.startedAt,当前占用+ * 该 PID 的进程若明显晚于它启动,就不可能是写标记的那个实例——按标记状态补出退出结论并清掉+ * 标记。读不到启动时刻或时刻对不上时保持 still-running,不臆断。+ *+ * 核对发生在启动之后:期间旧实例可能已正常退出并写下 exited,所以按此刻重读的标记下结论;+ * 标记已不在(被别的实例尸检清掉)就不再报。+ */+ async resolveReusedPids(+ stillRunning: readonly PreviousRunReport[],+ readStartTimes: (pids: readonly number[]) => Promise<ReadonlyMap<number, number>>,+ ): Promise<PreviousRunReport[]> {+ const pids = stillRunning.flatMap((r) => (r.marker ? [r.marker.pid] : []));+ if (pids.length === 0) return [...stillRunning];+ const startTimes = await readStartTimes(pids);+ return stillRunning.flatMap((report) => {+ if (!report.marker) return [report];+ const marker = this.readMarker(report.file);+ if (!marker || marker.pid !== report.marker.pid) return [];+ const ownerStartedAtMs = startTimes.get(marker.pid);+ const markerStartedAtMs = Date.parse(marker.startedAt);+ if (+ ownerStartedAtMs === undefined ||+ !Number.isFinite(markerStartedAtMs) ||+ ownerStartedAtMs <= markerStartedAtMs + PID_REUSE_TOLERANCE_MS+ ) {+ return [{ ...report, marker }];+ }+ this.remove(report.file);+ return [+ {+ kind: classifyEndedRun(marker),+ file: report.file,+ marker,+ pidReusedSince: new Date(ownerStartedAtMs).toISOString(),+ },+ ];+ });+ }++ private readMarker(file: string): RunMarker | null {+ try {+ const marker = JSON.parse(fs.readFileSync(file, 'utf8')) as RunMarker;+ return marker && typeof marker.pid === 'number' && marker.state ? marker : null;+ } catch {+ return null;+ }+ }+private remove(file: string): void {try {fs.unlinkSync(file);@@ -306,6 +374,12 @@ function logPreviousRunReports(reports: PreviousRunReport[]): boolean {let hadAbnormal = false;for (const r of reports) {const m = r.marker;+ if (r.pidReusedSince) {+ log.info(+ `[exit-diagnosis] pid=${m!.pid} now belongs to another process started at ${r.pidReusedSince}, ` ++ `not the v=${m!.version} instance started at ${m!.startedAt} — that instance is gone:`,+ );+ }switch (r.kind) {case 'clean':log.info(@@ -400,6 +474,23 @@ function logCrashDumpScan(hadAbnormal: boolean): void {}}+/**+ * still-running 的结论等 PID 复用核对完再记日志,避免先写一行「另一个实例在运行」的误报。+ * 核对出的退出结论只进日志、不回填 _previousRunReports:复用往往发生在很久以后,+ * 不应据此为一次陈旧的退出触发日志上报的原生崩溃兜底。+ */+function scheduleReusedPidCheck(store: RunMarkerStore, stillRunning: PreviousRunReport[]): void {+ const timer = setTimeout(() => {+ store+ .resolveReusedPids(stillRunning, (pids) =>+ readProcessStartTimes(pids, { timeoutMs: PID_REUSE_QUERY_TIMEOUT_MS }),+ )+ .then((resolved) => logPreviousRunReports(resolved))+ .catch((err) => log.warn('run marker pid reuse check failed (non-fatal)', err));+ }, PID_REUSE_CHECK_DELAY_MS);+ timer.unref?.();+}+/*** 启动诊断入口。必须在 app ready 之前、userData 定型之后调用(bootstrap-electron* 顶层满足两者)。幂等;整体 try/catch —— 诊断永不阻断启动。@@ -423,8 +514,10 @@ export function initStartupDiagnostics(): void {});const reports = store.analyzePreviousRuns();_previousRunReports = reports;- const hadAbnormal = logPreviousRunReports(reports);+ const stillRunning = reports.filter((r) => r.kind === 'still-running');+ const hadAbnormal = logPreviousRunReports(reports.filter((r) => r.kind !== 'still-running'));logCrashDumpScan(hadAbnormal);+ if (stillRunning.length > 0) scheduleReusedPidCheck(store, stillRunning);store.begin();_store = store;_heartbeatTimer = setInterval(() => _store?.heartbeat(), HEARTBEAT_INTERVAL_MS);diff --git a/apps/desktop/src/main/startupGateStallReport.ts b/apps/desktop/src/main/startupGateStallReport.tsnew file mode 100644index 0000000000..f5fe385812--- /dev/null+++ b/apps/desktop/src/main/startupGateStallReport.ts@@ -0,0 +1,35 @@+import {+ formatStartupGateStallSnapshot,+ parseStartupGateStallSnapshot,+} from '../shared/startupGateStall';++/**+ * 主窗口 renderer 每次加载最多上报一次;重载(boot guard 重试、用户 Ctrl+R)会再来。+ * 进程内封顶,防止 renderer 异常时刷屏。+ */+const MAX_REPORTS_PER_PROCESS = 3;++export interface StartupGateStallReporterDeps {+ /** 只认主窗口顶层 frame:只有主窗口挂开屏,其它窗口与 webview 的上报一律丢弃。 */+ isMainWindowTopFrame: (event: unknown) => boolean;+ /** 写到上传白名单内的 `renderer-guard`(见 log-upload/sourceAllowlist.ts)。 */+ warn: (message: string) => void;+}++export function createStartupGateStallReporter(+ deps: StartupGateStallReporterDeps,+): (event: unknown, payload: unknown) => void {+ let reports = 0;+ return (event, payload) => {+ if (reports >= MAX_REPORTS_PER_PROCESS) return;+ if (!deps.isMainWindowTopFrame(event)) return;+ const snapshot = parseStartupGateStallSnapshot(payload);+ if (!snapshot) return;+ reports += 1;+ deps.warn(+ `startup gate held for ${Math.round(snapshot.waitingMs / 1000)}s ` ++ `(renderer up ${Math.round(snapshot.elapsedMs / 1000)}s): ` ++ formatStartupGateStallSnapshot(snapshot),+ );+ };+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 8410ab1f24..c1a18ea3bb 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -30,6 +30,10 @@ import {type LoginItemState,} from '../shared/loginItem';import type { BotToolsetContext } from '../shared/botRemoteCapabilities';+import {+ STARTUP_GATE_STALL_CHANNEL,+ type StartupGateStallSnapshot,+} from '../shared/startupGateStall';import { contextBridge, ipcRenderer, webUtils } from 'electron';import { createChatFolderUpload } from './chatFolderUpload';import { DESKTOP_LOCAL, type RemoteDesktopApi } from '../shared/remoteDesktop';@@ -1226,6 +1230,10 @@ contextBridge.exposeInMainWorld('electronAPI', {msg: string,): void => ipcRenderer.send('renderer:log', level, scope, msg),+ /** 开屏卡住时上报一次启动门快照;main 校验字段后写进可上传的诊断日志。 */+ reportStartupGateStall: (snapshot: StartupGateStallSnapshot): void =>+ ipcRenderer.send(STARTUP_GATE_STALL_CHANNEL, snapshot),+localThemes: {listSync: (): LocalThemesResult => {try {diff --git a/apps/desktop/src/renderer/components/log-support/StartupLogSupport.tsx b/apps/desktop/src/renderer/components/log-support/StartupLogSupport.tsxindex bbbb051521..3a90512ee7 100644--- a/apps/desktop/src/renderer/components/log-support/StartupLogSupport.tsx+++ b/apps/desktop/src/renderer/components/log-support/StartupLogSupport.tsx@@ -9,22 +9,39 @@ import { useLoginHandoff } from '@/contexts/LoginHandoffContext';import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';import { OpenLogsRow, UploadLogsActionRow } from './LogSupportActions';import { useManualLogUpload } from './useManualLogUpload';+import { useStartupGateStallReport } from './useStartupGateStallReport';/** Outside startup/auth/database gates so the failure being diagnosed cannot hide the entry. */export function StartupLogSupport() {const { t } = useTranslation();const [open, setOpen] = useState(false);const upload = useManualLogUpload();- const { canEnterApp, isInitializing } = useAuth();- const { localDbGateStatus } = useAppShellCover();+ const { canEnterApp, isInitializing, isAuthenticated, mode } = useAuth();+ const { localDbGateStatus, coverHeld } = useAppShellCover();const { status } = useEnvCheck();- const { brandStageMounted } = useLoginHandoff();+ const { brandStageMounted, phase, branch, panelRevealed, startSignals } = useLoginHandoff();const visible =isInitializing ||!canEnterApp ||status !== 'passed' ||localDbGateStatus !== 'ready' ||brandStageMounted;+ // 登录面板已显示 = 等用户登录,不是卡住。只看挂载不够:未登录冷启动时登录页会先挂在开屏+ // 底下,此时开屏若卡住,用户看到的仍是开屏。+ const awaitingUserLogin = startSignals.loginPanelMounted && panelRevealed;+ useStartupGateStallReport(visible && !awaitingUserLogin, {+ authInitializing: isInitializing,+ authMode: mode,+ authenticated: isAuthenticated,+ canEnterApp,+ envStatus: status,+ localDbGate: localDbGateStatus,+ coverHeld,+ handoffPhase: phase,+ handoffBranch: branch ?? 'none',+ brandStageMounted,+ ...startSignals,+ });return (<>diff --git a/apps/desktop/src/renderer/components/log-support/__tests__/StartupLogSupport.test.tsx b/apps/desktop/src/renderer/components/log-support/__tests__/StartupLogSupport.test.tsxindex 8435f41733..543673cdb6 100644--- a/apps/desktop/src/renderer/components/log-support/__tests__/StartupLogSupport.test.tsx+++ b/apps/desktop/src/renderer/components/log-support/__tests__/StartupLogSupport.test.tsx@@ -6,10 +6,22 @@ import { initReactI18next } from 'react-i18next';import zhCN from '../../../i18n/locales/zh-CN/common.json';const mocks = vi.hoisted(() => ({- auth: { canEnterApp: false, isInitializing: false },- db: { localDbGateStatus: 'pending' },+ auth: { canEnterApp: false, isInitializing: false, isAuthenticated: false, mode: 'signed-out' },+ db: { localDbGateStatus: 'pending', coverHeld: false },env: { status: 'passed' },- handoff: { brandStageMounted: false },+ handoff: {+ brandStageMounted: false,+ phase: 'done',+ branch: null as string | null,+ panelRevealed: true,+ startSignals: {+ brandAssetsReady: true,+ splashExited: true,+ splashExitCompleted: true,+ loginPanelMounted: false,+ },+ },+ reportStartupGateStall: vi.fn(),error: vi.fn(),success: vi.fn(),openLogsDir: vi.fn(),@@ -36,9 +48,16 @@ beforeEach(() => {vi.clearAllMocks();mocks.auth.canEnterApp = false;mocks.auth.isInitializing = false;+ mocks.auth.isAuthenticated = false;+ mocks.auth.mode = 'signed-out';mocks.db.localDbGateStatus = 'pending';+ mocks.db.coverHeld = false;mocks.env.status = 'passed';mocks.handoff.brandStageMounted = false;+ mocks.handoff.phase = 'done';+ mocks.handoff.branch = null;+ mocks.handoff.panelRevealed = true;+ mocks.handoff.startSignals.loginPanelMounted = false;mocks.openLogsDir.mockResolvedValue({ success: true });mocks.uploadLogsNow.mockResolvedValue({ uploadCode: 'ABCD-EFGH', recordCount: 3 });mocks.writeText.mockResolvedValue(undefined);@@ -56,6 +75,7 @@ beforeEach(() => {uploadLogsNow: mocks.uploadLogsNow,getLogUploadSettings: mocks.getLogUploadSettings,onLogUploadSettingsChange: () => () => {},+ reportStartupGateStall: mocks.reportStartupGateStall,},});Object.defineProperty(navigator, 'clipboard', {@@ -222,3 +242,106 @@ describe('startup log support', () => {expect(screen.queryByRole('button', { name: zhCN.logSupport.title })).toBeNull();});});++// 用户卡在开屏、主进程日志却显示已登录且数据库就绪时,原先无从判断是哪个门没放行;+// renderer 日志又不进上传。超时后经 main 记一份启动门快照。+describe('startup gate stall report', () => {+ beforeEach(() => vi.useFakeTimers());+ afterEach(() => vi.useRealTimers());++ function signedInWithBrandStageStuck() {+ mocks.auth.canEnterApp = true;+ mocks.auth.isAuthenticated = true;+ mocks.auth.mode = 'cloud';+ mocks.db.localDbGateStatus = 'ready';+ mocks.handoff.brandStageMounted = true;+ mocks.handoff.phase = 'boot';+ mocks.handoff.panelRevealed = false;+ }++ it('reports the gate snapshot once when the startup cover stays past the threshold', () => {+ signedInWithBrandStageStuck();+ render(<StartupLogSupport />);++ act(() => vi.advanceTimersByTime(19_000));+ expect(mocks.reportStartupGateStall).not.toHaveBeenCalled();++ act(() => vi.advanceTimersByTime(60_000));+ expect(mocks.reportStartupGateStall).toHaveBeenCalledOnce();+ expect(mocks.reportStartupGateStall.mock.calls[0][0]).toMatchObject({+ authenticated: true,+ canEnterApp: true,+ envStatus: 'passed',+ localDbGate: 'ready',+ handoffPhase: 'boot',+ handoffBranch: 'none',+ brandStageMounted: true,+ loginPanelMounted: false,+ });+ });++ it.each([+ [+ 'the login panel is waiting for the user',+ () => {+ mocks.handoff.brandStageMounted = true;+ mocks.handoff.startSignals.loginPanelMounted = true;+ },+ ],+ ['startup finishes before the threshold', null],+ ])('does not report when %s', (_label, arrange) => {+ if (arrange) {+ arrange();+ render(<StartupLogSupport />);+ } else {+ signedInWithBrandStageStuck();+ const view = render(<StartupLogSupport />);+ act(() => vi.advanceTimersByTime(5_000));+ mocks.handoff.brandStageMounted = false;+ mocks.handoff.phase = 'done';+ view.rerender(<StartupLogSupport />);+ }++ act(() => vi.advanceTimersByTime(60_000));+ expect(mocks.reportStartupGateStall).not.toHaveBeenCalled();+ });++ // 未登录冷启动:登录页先挂在开屏底下,面板还没显示;开屏卡住时用户看到的仍是开屏。+ it('reports a stuck splash even while the login page is mounted underneath', () => {+ mocks.handoff.brandStageMounted = true;+ mocks.handoff.phase = 'boot';+ mocks.handoff.panelRevealed = false;+ mocks.handoff.startSignals.loginPanelMounted = true;+ render(<StartupLogSupport />);++ act(() => vi.advanceTimersByTime(20_000));+ expect(mocks.reportStartupGateStall).toHaveBeenCalledOnce();+ expect(mocks.reportStartupGateStall.mock.calls[0][0]).toMatchObject({+ handoffPhase: 'boot',+ loginPanelMounted: true,+ });+ });++ // 在登录页停留超过阈值后再登录:数据库准备的那一小段不能立刻被算成卡住。+ it('times the threshold from when waiting begins, not from page load', () => {+ mocks.handoff.brandStageMounted = true;+ mocks.handoff.startSignals.loginPanelMounted = true;+ const view = render(<StartupLogSupport />);+ act(() => vi.advanceTimersByTime(30_000));++ mocks.auth.canEnterApp = true;+ mocks.db.coverHeld = true;+ mocks.handoff.startSignals.loginPanelMounted = false;+ view.rerender(<StartupLogSupport />);+ act(() => vi.advanceTimersByTime(19_000));+ expect(mocks.reportStartupGateStall).not.toHaveBeenCalled();++ act(() => vi.advanceTimersByTime(1_000));+ expect(mocks.reportStartupGateStall).toHaveBeenCalledOnce();+ expect(mocks.reportStartupGateStall.mock.calls[0][0]).toMatchObject({+ elapsedMs: 50_000,+ waitingMs: 20_000,+ localDbGate: 'pending',+ });+ });+});diff --git a/apps/desktop/src/renderer/components/log-support/useStartupGateStallReport.ts b/apps/desktop/src/renderer/components/log-support/useStartupGateStallReport.tsnew file mode 100644index 0000000000..7ea89c82a7--- /dev/null+++ b/apps/desktop/src/renderer/components/log-support/useStartupGateStallReport.ts@@ -0,0 +1,42 @@+import { useEffect, useRef } from 'react';++import {+ STARTUP_GATE_STALL_AFTER_MS,+ type StartupGateStallSnapshot,+} from '../../../shared/startupGateStall';++export type StartupGateState = Omit<+ StartupGateStallSnapshot,+ 'elapsedMs' | 'waitingMs' | 'documentVisible'+>;++/**+ * 启动门挡住主界面超过阈值时,向 main 上报一次各启动门的状态。+ *+ * 用户反馈「卡在开屏」时,主进程日志可能一切正常(已登录、数据库就绪),却说不出是哪个门+ * 没放行。只认「等待中」:登录面板已显示说明是在等用户登录,不算卡住。阈值从这一段等待+ * 开始时算起——在登录页停留很久后再登录,数据库准备的那一小段不能立刻算超时。每次 renderer+ * 加载最多报一次,快照取上报那一刻的最新值。+ */+export function useStartupGateStallReport(waiting: boolean, state: StartupGateState): void {+ const loadedAtRef = useRef(Date.now());+ const stateRef = useRef(state);+ stateRef.current = state;+ const reportedRef = useRef(false);++ useEffect(() => {+ if (!waiting || reportedRef.current) return;+ const waitingSince = Date.now();+ const timer = window.setTimeout(() => {+ reportedRef.current = true;+ const now = Date.now();+ window.electronAPI?.reportStartupGateStall?.({+ ...stateRef.current,+ elapsedMs: now - loadedAtRef.current,+ waitingMs: now - waitingSince,+ documentVisible: document.visibilityState === 'visible',+ });+ }, STARTUP_GATE_STALL_AFTER_MS);+ return () => window.clearTimeout(timer);+ }, [waiting]);+}diff --git a/apps/desktop/src/renderer/contexts/LoginHandoffContext.tsx b/apps/desktop/src/renderer/contexts/LoginHandoffContext.tsxindex 1840b9a98b..c2742657c4 100644--- a/apps/desktop/src/renderer/contexts/LoginHandoffContext.tsx+++ b/apps/desktop/src/renderer/contexts/LoginHandoffContext.tsx@@ -72,6 +72,13 @@ export type LoginHandoffPhase =export type LoginHandoffBranch = 'unauthenticated' | 'authenticated' | null;export type LoginBrandLayout = 'splash' | 'login';+export interface LoginHandoffStartSignals {+ brandAssetsReady: boolean;+ splashExited: boolean;+ splashExitCompleted: boolean;+ loginPanelMounted: boolean;+}+export interface LoginHandoffContextValue {phase: LoginHandoffPhase;branch: LoginHandoffBranch;@@ -92,6 +99,8 @@ export interface LoginHandoffContextValue {panelRevealed: boolean;/** Slogan 已进入可见段(slogan/done)——必须最后出现。 */sloganRevealed: boolean;+ /** 推进锚收到情况,只读,供开屏卡住诊断判断停在哪一步。 */+ startSignals: LoginHandoffStartSignals;reportBrandAssetsReady: () => void;/** Splash 开始淡出;用于启动 handoff 时序,但不代表布局可以切换。 */reportSplashExited: () => void;@@ -118,6 +127,12 @@ const FALLBACK_VALUE: LoginHandoffContextValue = Object.freeze({brandExiting: false,panelRevealed: true,sloganRevealed: true,+ startSignals: Object.freeze({+ brandAssetsReady: true,+ splashExited: true,+ splashExitCompleted: true,+ loginPanelMounted: false,+ }),reportBrandAssetsReady: () => {},reportSplashExited: () => {},reportSplashExitCompleted: () => {},@@ -298,6 +313,12 @@ export function LoginHandoffProvider({brandExiting: phase === 'brand-exit',panelRevealed: phase === 'panel' || phase === 'slogan' || phase === 'done',sloganRevealed: phase === 'slogan' || phase === 'done',+ startSignals: {+ brandAssetsReady: brandReady,+ splashExited,+ splashExitCompleted,+ loginPanelMounted: panelMounted,+ },reportBrandAssetsReady,reportSplashExited,reportSplashExitCompleted,@@ -310,6 +331,7 @@ export function LoginHandoffProvider({branch,panelMounted,coverHeld,+ brandReady,splashExited,splashExitCompleted,panelBottomReserve,diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 89328c3c16..d9790b340e 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -19,6 +19,7 @@ type ModelAccessStatusPayload = import('../shared/modelAccess').ModelAccessStatutype AnalyticsSettingsPayload = import('../shared/analyticsSettings').AnalyticsSettingsPayload;type LogUploadSettingsPayload = import('../shared/logUpload').LogUploadSettingsPayload;type LogUploadResult = import('../shared/logUpload').LogUploadResult;+type StartupGateStallSnapshot = import('../shared/startupGateStall').StartupGateStallSnapshot;type CustomProviderUpdateOptions =import('../shared/customProviderUpdate').CustomProviderUpdateOptions;type CustomProviderUpdateResult =@@ -1226,6 +1227,9 @@ interface ElectronAPI {msg: string,) => void;+ /** 开屏卡住时上报一次启动门快照;main 校验字段后写进可上传的诊断日志。仅主窗 preload 提供。 */+ reportStartupGateStall?: (snapshot: StartupGateStallSnapshot) => void;+localThemes: {listSync: () => LocalThemesResult;list: () => Promise<LocalThemesResult>;diff --git a/apps/desktop/src/shared/startupGateStall.ts b/apps/desktop/src/shared/startupGateStall.tsnew file mode 100644index 0000000000..f377a0e2eb--- /dev/null+++ b/apps/desktop/src/shared/startupGateStall.ts@@ -0,0 +1,129 @@+/**+ * 启动门卡住诊断:主窗口停在开屏品牌页超过阈值时,renderer 上报一次各启动门的状态快照,+ * main 用 `renderer-guard` 写一行日志。+ *+ * 为什么要经 main 写:renderer 转发的日志一律带 `r:` 前缀,整类不进「日志与反馈」上传+ * (docs/dev-rules/log-upload-and-redaction.md §1.2)。用户卡在开屏时手里只有上传编号,+ * 只记在 renderer 里等于没记。+ *+ * 隐私边界:快照只有布尔、有限枚举和有界整数(毫秒数)。main 按本文件的白名单逐字段重建后再写,+ * 任何多余字段、非枚举字符串一律整份丢弃——这一行会离开用户机器,不能让 renderer 夹带内容。+ */++export const STARTUP_GATE_STALL_CHANNEL = 'startup-gate:stalled';++/** 开屏停留超过这么久才算卡住:正常冷启动(含数据库迁移)在 10 秒内完成。 */+export const STARTUP_GATE_STALL_AFTER_MS = 20_000;++const ENV_STATUSES = [+ 'idle',+ 'checking_update',+ 'updating',+ 'update_done',+ 'manifest_failed',+ 'download_failed',+ 'checking',+ 'downloading',+ 'passed',+ 'failed',+] as const;+const LOCAL_DB_GATE_STATUSES = ['pending', 'ready', 'fatal'] as const;+const AUTH_MODES = ['signed-out', 'local', 'cloud'] as const;+const HANDOFF_PHASES = [+ 'boot',+ 'settle',+ 'shift',+ 'awaiting-splash-exit',+ 'awaiting-panel',+ 'panel',+ 'slogan',+ 'brand-exit',+ 'done',+] as const;+const HANDOFF_BRANCHES = ['authenticated', 'unauthenticated', 'none'] as const;++export interface StartupGateStallSnapshot {+ /** renderer 启动到上报的毫秒数。 */+ elapsedMs: number;+ /** 这一段连续卡住(开屏在、且不是在等用户登录)到上报的毫秒数。 */+ waitingMs: number;+ /** 上报时窗口是否可见:隐藏窗口里的动画与计时会被节流。 */+ documentVisible: boolean;+ authInitializing: boolean;+ authMode: (typeof AUTH_MODES)[number];+ authenticated: boolean;+ canEnterApp: boolean;+ envStatus: (typeof ENV_STATUSES)[number];+ localDbGate: (typeof LOCAL_DB_GATE_STATUSES)[number];+ coverHeld: boolean;+ handoffPhase: (typeof HANDOFF_PHASES)[number];+ handoffBranch: (typeof HANDOFF_BRANCHES)[number];+ brandStageMounted: boolean;+ /** 品牌交接起播的三个推进锚(另一个是 auth 初始化完成)。 */+ brandAssetsReady: boolean;+ splashExited: boolean;+ splashExitCompleted: boolean;+ loginPanelMounted: boolean;+}++type FieldRule = { kind: 'boolean' } | { kind: 'enum'; values: readonly string[] } | { kind: 'ms' };++const FIELD_RULES: { readonly [K in keyof StartupGateStallSnapshot]: FieldRule } = {+ elapsedMs: { kind: 'ms' },+ waitingMs: { kind: 'ms' },+ documentVisible: { kind: 'boolean' },+ authInitializing: { kind: 'boolean' },+ authMode: { kind: 'enum', values: AUTH_MODES },+ authenticated: { kind: 'boolean' },+ canEnterApp: { kind: 'boolean' },+ envStatus: { kind: 'enum', values: ENV_STATUSES },+ localDbGate: { kind: 'enum', values: LOCAL_DB_GATE_STATUSES },+ coverHeld: { kind: 'boolean' },+ handoffPhase: { kind: 'enum', values: HANDOFF_PHASES },+ handoffBranch: { kind: 'enum', values: HANDOFF_BRANCHES },+ brandStageMounted: { kind: 'boolean' },+ brandAssetsReady: { kind: 'boolean' },+ splashExited: { kind: 'boolean' },+ splashExitCompleted: { kind: 'boolean' },+ loginPanelMounted: { kind: 'boolean' },+};++/** 一天的毫秒数:上限只为拒绝畸形值,真实上报在阈值附近。 */+const MAX_ELAPSED_MS = 24 * 60 * 60 * 1000;++/**+ * IPC 入口校验:键集合必须与白名单完全一致,每个值都落在规则内,否则返回 null。+ * 返回值按白名单重建,不复用入参对象。+ */+export function parseStartupGateStallSnapshot(input: unknown): StartupGateStallSnapshot | null {+ if (!input || typeof input !== 'object' || Array.isArray(input)) return null;+ const record = input as Record<string, unknown>;+ const fields = Object.keys(FIELD_RULES) as Array<keyof StartupGateStallSnapshot>;+ const keys = Object.keys(record);+ if (keys.length !== fields.length || !keys.every((key) => key in FIELD_RULES)) return null;+ const out: Record<string, unknown> = {};+ for (const field of fields) {+ const rule = FIELD_RULES[field];+ const value = record[field];+ if (rule.kind === 'boolean') {+ if (typeof value !== 'boolean') return null;+ } else if (rule.kind === 'enum') {+ if (typeof value !== 'string' || !rule.values.includes(value)) return null;+ } else if (+ typeof value !== 'number' ||+ !Number.isInteger(value) ||+ value < 0 ||+ value > MAX_ELAPSED_MS+ ) {+ return null;+ }+ out[field] = value;+ }+ return out as unknown as StartupGateStallSnapshot;+}++/** 固定字段顺序的 `key=value` 行,便于日志里横向比对多次上报。 */+export function formatStartupGateStallSnapshot(snapshot: StartupGateStallSnapshot): string {+ const fields = Object.keys(FIELD_RULES) as Array<keyof StartupGateStallSnapshot>;+ return fields.map((field) => `${field}=${String(snapshot[field])}`).join(' ');+}