Skip to content

🤯 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.

⚡️ perf(desktop): reduce cold-start critical path (#17811)

Innei68f4e84fe982
diff --git a/.agents/skills/spa-routes/SKILL.md b/.agents/skills/spa-routes/SKILL.md
index 2dce7cfe4b0..45b55bef73b 100644
--- a/.agents/skills/spa-routes/SKILL.md
+++ b/.agents/skills/spa-routes/SKILL.md
@@ -14,7 +14,7 @@ SPA structure:
This project uses a **roots vs features** split: `src/routes/` only holds page segments; business logic and UI live in `src/features/` by domain.
-**Agent constraint — desktop router parity:** Edits to the desktop route tree must update **both** `src/spa/router/desktopRouter.config.tsx` and `src/spa/router/desktopRouter.config.desktop.tsx` in the same change (same paths, nesting, index routes, and segment registration). Updating only one causes drift; the missing tree can fail to register routes and surface as a **blank screen** or broken navigation on the affected build.
+**Agent constraint — shared desktop router:** Common Web/Electron paths, nesting, metadata, lazy loaders, and preload groups belong in `src/spa/router/desktopRouter.shared.tsx`. The two `desktopRouter.config*` files are thin platform adapters; change them only for genuine runtime differences. Do not duplicate a common route in both adapters.
## When to Use This Skill
@@ -76,27 +76,28 @@ Each feature should:
- Layout: `export { default } from '@/features/MyFeature/MyLayout'` or compose a few feature components + `<Outlet />`.
- Page: import from `@/features/MyFeature` (or a specific subpath) and render; no business logic in the route file.
-5. **Register the route (desktop — two files, always)**
- - **`desktopRouter.config.tsx`:** Add the segment with `dynamicElement` / `dynamicLayout` pointing at route modules (e.g. `@/routes/(main)/my-feature`).
- - **`desktopRouter.config.desktop.tsx`:** Mirror the **same** `RouteObject` shape: identical `path` / `index` / parent-child structure. Use the static imports and elements already used in that file (see neighboring routes). Do **not** register in only one of these files.
- - **Mobile-only flows:** use `mobileRouter.config.tsx` instead (no need to duplicate into the desktop pair unless the route truly exists on both).
+5. **Register the route in the correct definition layer**
+ - **Shared Web/Electron route:** add the segment once in `desktopRouter.shared.tsx` with `dynamicElement` / `dynamicLayout`. Put its `preloadId` there as part of the shared lazy-loader definition.
+ - **Web-only or Electron-only route:** add it to the corresponding thin `desktopRouter.config.tsx` adapter. Keep platform-only differences explicit and small.
+ - **Mobile-only flow:** use `mobileRouter.config.tsx`; mobile does not consume the shared desktop tree.
---
-## 3a. Desktop router pair (`desktopRouter.config` × 2)
+## 3a. Shared desktop route definition and platform adapters
-| File | Role |
-| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
-| `desktopRouter.config.tsx` | Dynamic imports via `dynamicElement` / `dynamicLayout` — code-splitting; used by `entry.web.tsx` and `entry.desktop.tsx`. |
-| `desktopRouter.config.desktop.tsx` | Same route tree with **synchronous** imports — kept for Electron / local parity and predictable bundling. |
+| File | Role |
+| ---------------------------------- | --------------------------------------------------------------------------------------------------------------- |
+| `desktopRouter.shared.tsx` | Single source of truth for common paths, nesting, metadata, lazy imports, and prioritized route preload groups. |
+| `desktopRouter.config.tsx` | Thin Web adapter: mounts the common content tree at `/` and adds Web-only routes. |
+| `desktopRouter.config.desktop.tsx` | Thin Electron adapter: injects per-tab Home behavior, TabHost root stubs, and Electron-only onboarding. |
-Anything that changes the tree (new segment, renamed `path`, moved layout, new child route) must be reflected in **both** files in one PR or commit. Remove routes from both when deleting.
+Add or remove common routes only in `desktopRouter.shared.tsx`. Keep `desktopRouter.sync.test.tsx` passing so path behavior, lazy boundaries, preload ownership, and the intentional platform differences remain verified.
---
## 3b. Other `.desktop.{ts,tsx}` variants inside `src/routes/`
-The router pair is **not** the only `.desktop` variant pattern in this repo. Some route trees colocate a `<name>.desktop.{ts,tsx}` next to its base `<name>.{ts,tsx}` — Vite's resolver swaps in the `.desktop` file for Electron builds. Same drift risk as the router pair: editing only one side can break Electron silently.
+The thin router adapters are not duplicated trees. Other route modules may still colocate a `<name>.desktop.{ts,tsx}` next to a base `<name>.{ts,tsx}`; Vite's resolver swaps in the `.desktop` file for Electron builds. Those paired module implementations still carry a drift risk.
Known variants today:
diff --git a/AGENTS.md b/AGENTS.md
index 97bc1e6d3ab..0b9b0b3b9d7 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -62,7 +62,7 @@ When adding or changing SPA routes:
1. In `src/routes/`, add only the route segment files (layout + page) that delegate to features.
2. Implement layout and page content under `src/features/<Domain>/` and export from there.
3. In route files, use `import { X } from '@/features/<Domain>'` (or `import Y from '@/features/<Domain>/...'`). Do not add new `features/` folders inside `src/routes/`.
-4. **Register desktop content routes in the `createMainAreaChildren()` twins:** the main-area content tree is built by `createMainAreaChildren()`, which exists in both `src/spa/router/desktopRouter.config.tsx` and `src/spa/router/desktopRouter.config.desktop.tsx` and must stay in sync (same paths and nesting). Web mounts these children under the root router; electron mounts them in per-tab memory routers via `src/spa/router/tabRouter.tsx`, so the electron root config's `/` children are intentionally slim stubs. Updating only one twin can cause **blank screens**. `desktopRouter.sync.test.tsx` guards builder parity — keep it passing.
+4. **Register shared desktop content routes once:** add common Web/Electron paths, nesting, metadata, lazy loaders, and `preloadId` values in `src/spa/router/desktopRouter.shared.tsx`. The thin `desktopRouter.config.tsx` and `desktopRouter.config.desktop.tsx` files contain only runtime differences: Web mounts the content tree directly, while Electron keeps slim root stubs and mounts the same tree in per-tab memory routers through `src/spa/router/tabRouter.tsx`. Add code to a platform adapter only when the route is genuinely platform-specific. `desktopRouter.sync.test.tsx` guards the shared behavior and explicit differences — keep it passing.
See the **spa-routes** skill for the full convention and file-division rules.
diff --git a/apps/desktop/WindowOverlayCapture.md b/apps/desktop/WindowOverlayCapture.md
index 54897275815..c1f8b088487 100644
--- a/apps/desktop/WindowOverlayCapture.md
+++ b/apps/desktop/WindowOverlayCapture.md
@@ -358,7 +358,7 @@
| 方案 | 优点 | 缺点 | 建议 |
| ------------------ | -------------------------------- | -------------------------------- | ---------------- |
| 独立静态 HTML 页面 | 轻量、与业务隔离、最接近 demo | 与现有 React/i18n / 业务状态脱节 | 仅适合 spike |
-| 独立桌面 SPA 路由 | 可复用现有构建、i18n、业务事件链 | 需要维护 desktop router 双配置 | **推荐生产使用** |
+| 独立桌面 SPA 路由 | 可复用现有构建、i18n、业务事件链 | 需要声明清晰的平台差分 | **推荐生产使用** |
若采用 SPA 路由,建议新增:
@@ -366,15 +366,15 @@
| ------------------------------------------------------- | ------------------------------------ |
| `src/routes/(desktop)/screen-capture-overlay/index.tsx` | overlay 页面入口;仅负责挂载 UI 组件 |
| `src/features/DesktopScreenCaptureOverlay/*` | 业务组件、hooks、样式 |
-| `src/spa/router/desktopRouter.config.tsx` | 动态路由配置 |
-| `src/spa/router/desktopRouter.config.desktop.tsx` | 同步路由配置 |
+| `src/spa/router/desktopRouter.shared.tsx` | Web/Electron 共用路由定义 |
+| `src/spa/router/desktopRouter.config.desktop.tsx` | Electron 独有路由差分 |
必须注意:
-| 规则 | 说明 |
-| -------------------------------- | ------------------------------------ |
-| 两份 desktop router 必须同时更新 | 否则 Electron 本地构建可能出现空白页 |
-| overlay route 应保持极薄 | 不在 route 文件中堆叠业务逻辑 |
+| 规则 | 说明 |
+| ---------------------------- | ----------------------------- |
+| 共用路由只在 shared 文件注册 | 避免 Web/Electron 路由树漂移 |
+| overlay route 应保持极薄 | 不在 route 文件中堆叠业务逻辑 |
## 14. 托盘入口的真实接入点
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index c29ea2f24a6..48d7f033633 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -91,7 +91,6 @@
"drizzle-orm": "^0.45.2",
"electron": "43.2.0",
"electron-builder": "26.14.0",
- "electron-is": "^3.0.0",
"electron-store": "^8.2.0",
"electron-updater": "^6.8.9",
"electron-window-state": "^5.0.3",
@@ -101,7 +100,6 @@
"fast-glob": "^3.3.3",
"fetch-socks": "^1.3.3",
"fflate": "^0.8.3",
- "fix-path": "^5.0.0",
"get-port-please": "^3.2.0",
"happy-dom": "^20.10.6",
"http-proxy-agent": "^7.0.2",
diff --git a/apps/desktop/src/main/const/env.ts b/apps/desktop/src/main/const/env.ts
index 5b259b3293e..7c2e715a0c8 100644
--- a/apps/desktop/src/main/const/env.ts
+++ b/apps/desktop/src/main/const/env.ts
@@ -1,8 +1,7 @@
import os from 'node:os';
-import * as electronIs from 'electron-is';
-
import { getDesktopEnv } from '@/env';
+import * as electronIs from '@/utils/platform';
export const isDev = electronIs.dev();
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index f745f78ce6f..96e61410fd3 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -3,7 +3,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { type DeviceControlDeps, executeDeviceRpc as runDeviceRpc } from '@lobechat/device-control';
+import type { DeviceControlDeps } from '@lobechat/device-control';
import type { AgentRunRequestMessage, GatewayMcpParams } from '@lobechat/device-gateway-client';
import type {
EditLocalFileParams,
@@ -21,7 +21,6 @@ import type {
RunCommandParams,
WriteLocalFileParams,
} from '@lobechat/electron-client-ipc';
-import { scanHeterogeneousAgentsOnHost } from '@lobechat/heterogeneous-agents/scanHost';
import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';
import GatewayConnectionService from '@/services/gatewayConnectionSrv';
@@ -195,7 +194,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
// ─── Lifecycle ───
- afterAppReady() {
+ afterFirstFrame() {
const srv = this.service;
srv.loadOrCreateDeviceId();
@@ -414,6 +413,7 @@ export default class GatewayConnectionCtr extends ControllerModule {
* desktop main process and the CLI daemon share one device RPC surface.
*/
private async executeDeviceRpc(method: string, params: unknown): Promise<unknown> {
+ const { executeDeviceRpc: runDeviceRpc } = await import('@lobechat/device-control');
return runDeviceRpc(method, params, this.deviceControlDeps);
}
@@ -572,6 +572,8 @@ export default class GatewayConnectionCtr extends ControllerModule {
}
case 'scanHeterogeneousAgents': {
+ const { scanHeterogeneousAgentsOnHost } =
+ await import('@lobechat/heterogeneous-agents/scanHost');
const agents = await scanHeterogeneousAgentsOnHost();
const result = { agents };
return { content: JSON.stringify(result), state: result, success: true };
diff --git a/apps/desktop/src/main/controllers/GitCtr.ts b/apps/desktop/src/main/controllers/GitCtr.ts
index 04f400d9160..f38969b7892 100644
--- a/apps/desktop/src/main/controllers/GitCtr.ts
+++ b/apps/desktop/src/main/controllers/GitCtr.ts
@@ -19,33 +19,12 @@ import type {
GitWorkingTreeStatus,
GitWorktreeListItem,
} from '@lobechat/electron-client-ipc';
-import {
- addGitWorktree as runAddGitWorktree,
- checkoutGitBranch as runCheckoutGitBranch,
- deleteGitBranch as runDeleteGitBranch,
- type DeviceGitInfo,
- getGitAheadBehind as computeGitAheadBehind,
- getGitBranch as computeGitBranch,
- getGitBranchDiff as runGitBranchDiff,
- getGitWorkingTreeFiles as computeGitWorkingTreeFiles,
- getGitWorkingTreePatches as computeGitWorkingTreePatches,
- getGitWorkingTreeStatus as computeGitWorkingTreeStatus,
- getLinkedPullRequest as computeLinkedPullRequest,
- gitInfo as computeGitInfo,
- listGitBranches as computeListGitBranches,
- listGitRemoteBranches as computeListGitRemoteBranches,
- listGitWorktrees as computeListGitWorktrees,
- pullGitBranch as runPullGitBranch,
- pushGitBranch as runPushGitBranch,
- removeGitWorktree as runRemoveGitWorktree,
- renameGitBranch as runRenameGitBranch,
- revertGitFile as runRevertGitFile,
-} from '@lobechat/local-file-shell';
-
-import { detectRepoType } from '@/utils/git';
+import type { DeviceGitInfo } from '@lobechat/local-file-shell/git';
import { ControllerModule, IpcMethod } from './index';
+const loadGit = () => import('@lobechat/local-file-shell/git');
+
/**
* GitController
*
@@ -58,16 +37,19 @@ export default class GitController extends ControllerModule {
@IpcMethod()
async detectRepoType(dirPath: string): Promise<'git' | 'github' | undefined> {
+ const { detectRepoType } = await loadGit();
return detectRepoType(dirPath);
}
@IpcMethod()
async getGitBranch(dirPath: string): Promise<GitBranchInfo> {
+ const { getGitBranch: computeGitBranch } = await loadGit();
return computeGitBranch(dirPath);
}
@IpcMethod()
async gitInfo(params: { isGithub?: boolean; scope: string }): Promise<DeviceGitInfo> {
+ const { gitInfo: computeGitInfo } = await loadGit();
return computeGitInfo(params);
}
@@ -77,46 +59,55 @@ export default class GitController extends ControllerModule {
path: string;
pullRequestNumber?: number;
}): Promise<GitLinkedPullRequestResult> {
+ const { getLinkedPullRequest: computeLinkedPullRequest } = await loadGit();
return computeLinkedPullRequest(payload);
}
@IpcMethod()
async listGitBranches(dirPath: string): Promise<GitBranchListItem[]> {
+ const { listGitBranches: computeListGitBranches } = await loadGit();
return computeListGitBranches(dirPath);
}
@IpcMethod()
async listGitRemoteBranches(dirPath: string): Promise<GitRemoteBranchListItem[]> {
+ const { listGitRemoteBranches: computeListGitRemoteBranches } = await loadGit();
return computeListGitRemoteBranches(dirPath);
}
@IpcMethod()
async listGitWorktrees(dirPath: string): Promise<GitWorktreeListItem[]> {
+ const { listGitWorktrees: computeListGitWorktrees } = await loadGit();
return computeListGitWorktrees(dirPath);
}
@IpcMethod()
async getGitWorkingTreeStatus(dirPath: string): Promise<GitWorkingTreeStatus> {
+ const { getGitWorkingTreeStatus: computeGitWorkingTreeStatus } = await loadGit();
return computeGitWorkingTreeStatus(dirPath);
}
@IpcMethod()
async getGitWorkingTreeFiles(dirPath: string): Promise<GitWorkingTreeFiles> {
+ const { getGitWorkingTreeFiles: computeGitWorkingTreeFiles } = await loadGit();
return computeGitWorkingTreeFiles(dirPath);
}
@IpcMethod()
async getGitWorkingTreePatches(dirPath: string): Promise<GitWorkingTreePatches> {
+ const { getGitWorkingTreePatches: computeGitWorkingTreePatches } = await loadGit();
return computeGitWorkingTreePatches(dirPath);
}
@IpcMethod()
async getGitBranchDiff(payload: GetGitBranchDiffPayload): Promise<GitBranchDiffPatches> {
+ const { getGitBranchDiff: runGitBranchDiff } = await loadGit();
return runGitBranchDiff(payload);
}
@IpcMethod()
async getGitAheadBehind(dirPath: string): Promise<GitAheadBehind> {
+ const { getGitAheadBehind: computeGitAheadBehind } = await loadGit();
return computeGitAheadBehind(dirPath);
}
@@ -126,6 +117,7 @@ export default class GitController extends ControllerModule {
create?: boolean;
path: string;
}): Promise<GitCheckoutResult> {
+ const { checkoutGitBranch: runCheckoutGitBranch } = await loadGit();
return runCheckoutGitBranch(payload);
}
@@ -135,11 +127,13 @@ export default class GitController extends ControllerModule {
path: string;
to: string;
}): Promise<GitRenameBranchResult> {
+ const { renameGitBranch: runRenameGitBranch } = await loadGit();
return runRenameGitBranch(payload);
}
@IpcMethod()
async deleteGitBranch(payload: { branch: string; path: string }): Promise<GitDeleteBranchResult> {
+ const { deleteGitBranch: runDeleteGitBranch } = await loadGit();
return runDeleteGitBranch(payload);
}
@@ -148,6 +142,7 @@ export default class GitController extends ControllerModule {
path: string;
worktreePath: string;
}): Promise<GitRemoveWorktreeResult> {
+ const { removeGitWorktree: runRemoveGitWorktree } = await loadGit();
return runRemoveGitWorktree(payload);
}
@@ -157,21 +152,25 @@ export default class GitController extends ControllerModule {
path: string;
worktreePath: string;
}): Promise<GitAddWorktreeResult> {
+ const { addGitWorktree: runAddGitWorktree } = await loadGit();
return runAddGitWorktree(payload);
}
@IpcMethod()
async pullGitBranch(payload: { path: string }): Promise<GitPullResult> {
+ const { pullGitBranch: runPullGitBranch } = await loadGit();
return runPullGitBranch(payload);
}
@IpcMethod()
async pushGitBranch(payload: { path: string }): Promise<GitPushResult> {
+ const { pushGitBranch: runPushGitBranch } = await loadGit();
return runPushGitBranch(payload);
}
@IpcMethod()
async revertGitFile(payload: { filePath: string; path: string }): Promise<GitFileRevertResult> {
+ const { revertGitFile: runRevertGitFile } = await loadGit();
return runRevertGitFile(payload);
}
}
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
index d17bbd7fdd7..c3d77a03f80 100644
--- a/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentCtr.ts
@@ -1,2097 +1,98 @@
-import type { ChildProcess } from 'node:child_process';
-import { spawn } from 'node:child_process';
-import { randomUUID } from 'node:crypto';
-import { existsSync, unlinkSync } from 'node:fs';
-import { access, appendFile, mkdir, unlink, writeFile } from 'node:fs/promises';
-import os from 'node:os';
-import path from 'node:path';
-import type { Readable, Writable } from 'node:stream';
-import { finished as streamFinished } from 'node:stream/promises';
-
-import type {
- ClaudeCodeQuotaSnapshot,
- CodexQuotaSnapshot,
- CodexRateLimitResetResult,
- HeterogeneousAgentSessionError,
- HeterogeneousCliAgentType,
-} from '@lobechat/electron-client-ipc';
-import {
- AMP_CLI_INSTALL_COMMANDS,
- AMP_CLI_INSTALL_DOCS_URL,
- CLAUDE_CODE_CLI_INSTALL_COMMANDS,
- CLAUDE_CODE_CLI_INSTALL_DOCS_URL,
- CODEX_CLI_INSTALL_COMMANDS,
- CODEX_CLI_INSTALL_DOCS_URL,
- HeterogeneousAgentSessionErrorCode,
- OPENCODE_CLI_INSTALL_COMMANDS,
- OPENCODE_CLI_INSTALL_DOCS_URL,
-} from '@lobechat/electron-client-ipc';
-import type { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';
-import type { McpToolResult } from '@lobechat/heterogeneous-agents/builtinMcp';
-import { LobeBuiltinMcpServer } from '@lobechat/heterogeneous-agents/builtinMcp';
-import { listHeterogeneousAgentModels } from '@lobechat/heterogeneous-agents/models';
-import type { HeteroExecImageRef } from '@lobechat/heterogeneous-agents/protocol';
-import {
- buildHeteroExecStdinPayload,
- buildHeterogeneousPrompt,
-} from '@lobechat/heterogeneous-agents/protocol';
-import {
- CLAUDE_CODE_QUOTA_FRESH_MS,
- createQuotaCacheKey,
- fetchClaudeCodeQuota,
- QuotaSnapshotCache,
- readClaudeCodeIdentity,
-} from '@lobechat/heterogeneous-agents/quota-sampler';
-import type { AgentStreamEvent, UsageData } from '@lobechat/heterogeneous-agents/spawn';
-import {
- AgentStreamPipeline,
- buildAgentInput,
- ClaudeAgentSdkSession,
- createFileStoreImageUploader,
- ensureClaudeCodeResumeTranscript,
- readCodexSessionModel,
- resolveCliSpawnPlan,
- resolveCodexInitialModel,
-} from '@lobechat/heterogeneous-agents/spawn';
-import type {
- HeterogeneousAgentModelCatalog,
- HeteroSessionImportMessage,
- ListHeterogeneousAgentModelsParams,
-} from '@lobechat/types';
-import { app as electronApp, BrowserWindow } from 'electron';
-
-import { HETERO_AGENT_FILES_DIR, HETERO_AGENT_TRACING_DIR } from '@/const/heteroAgent';
-import { detectHeterogeneousCliCommand } from '@/modules/binaries';
-import { resolveCliScript } from '@/modules/cliEmbedding';
-import { getHeterogeneousAgentDriver } from '@/modules/heterogeneousAgent';
-import { buildBrowserMcpTools } from '@/modules/heterogeneousAgent/browserMcpTools';
-import {
- consumeCodexRateLimitResetCredit as consumeCodexRateLimitResetCreditRequest,
- fetchCodexQuota,
-} from '@/modules/heterogeneousAgent/codexQuota';
-import { createLambdaFileStorePort } from '@/modules/heterogeneousAgent/fileStorePort';
-import type {
- HeterogeneousAgentBuildPlan,
- HeterogeneousAgentImageAttachment,
-} from '@/modules/heterogeneousAgent/types';
-import { buildProxyEnv } from '@/modules/networkProxy/envBuilder';
-import { createLogger } from '@/utils/logger';
-
-import BrowserControlCtr from './BrowserControlCtr';
+import type HeterogeneousAgentImplementation from './HeterogeneousAgentImpl';
import { ControllerModule, IpcMethod } from './index';
-import RemoteServerConfigCtr from './RemoteServerConfigCtr';
-
-const logger = createLogger('controllers:HeterogeneousAgentCtr');
-
-// Anthropic auth env vars that must NOT be inherited from the desktop process
-// when spawning a local CLI agent. A developer with `ANTHROPIC_API_KEY` (or an
-// auth token / base url) exported in their shell would otherwise have it
-// forwarded to `claude`, which then switches from its own subscription login to
-// that key — an expired / wrong key surfaces as a baffling "Invalid API key"
-// and the run exits non-zero. Agents that genuinely want an API key still set
-// it through `session.env`, which is spread AFTER the inherited env below and
-// therefore wins.
-const STRIPPED_INHERITED_ENV_KEYS = [
- 'ANTHROPIC_API_KEY',
- 'ANTHROPIC_AUTH_TOKEN',
- 'ANTHROPIC_BASE_URL',
-] as const;
-
-/**
- * Inherited `process.env` with the Anthropic auth vars removed. Keep this pure
- * and exported so the "never leak host Anthropic creds into the CLI" invariant
- * can be unit-tested directly.
- */
-export const buildInheritedSpawnEnv = (
- sourceEnv: NodeJS.ProcessEnv = process.env,
-): NodeJS.ProcessEnv => {
- const env = { ...sourceEnv };
- for (const key of STRIPPED_INHERITED_ENV_KEYS) delete env[key];
- return env;
-};
-const CODEX_RESUME_THREAD_NOT_FOUND_PATTERNS = [
- /no conversation found/i,
- /thread .*not found/i,
- /conversation .*not found/i,
- /resume.*not found/i,
-] as const;
-const CLI_AUTH_REQUIRED_PATTERNS = [
- /failed to authenticate/i,
- /invalid authentication credentials/i,
- /authentication[_ ]error/i,
- /not authenticated/i,
- /\bunauthorized\b/i,
- /\b401\b/,
-] as const;
-const AMP_AUTH_REQUIRED_PATTERNS = [/please (?:log|sign) in/i, /amp_api_key/i] as const;
-const CODEX_RESUME_CWD_MISMATCH_PATTERNS = [
- /working directory/i,
- /\bcwd\b/i,
- /different directory/i,
- /directory.*mismatch/i,
-] as const;
-
-/** Directory under appStoragePath for caching downloaded files */
-const FILE_CACHE_DIR = HETERO_AGENT_FILES_DIR;
-const CLI_TRACE_DIR = '.heerogeneous-tracing';
-const CODEX_STDERR_STATUS_LINE = 'Reading prompt from stdin...';
-const CODEX_WARN_LOG_PATTERN = /^\d{4}-\d{2}-\d{2}T\S+\s+WARN\s+/;
-const CODEX_LOG_PATTERN = /^\d{4}-\d{2}-\d{2}T\S+\s+(?:DEBUG|ERROR|INFO|TRACE|WARN)\s+/;
-const CLI_ERROR_LINE_PATTERN = /^(?:error:|Error:|Usage:)/;
-const HETERO_SESSION_COMPLETE_GRACE_MS = 1_000;
-const CLAUDE_CODE_SDK_LAB_ENABLED_VALUES = new Set(['1', 'true', 'yes', 'on']);
-
-const waitForHeteroSessionCompleteGrace = () =>
- new Promise<void>((resolve) => setTimeout(resolve, HETERO_SESSION_COMPLETE_GRACE_MS));
-
-// ─── IPC types ───
-
-interface StartSessionParams {
- /** Agent type key (e.g., 'claude-code'). Defaults to 'claude-code'. */
- agentType?: HeterogeneousCliAgentType;
- /** Additional CLI arguments */
- args?: string[];
- /** Command to execute */
- command: string;
- /** Working directory */
- cwd?: string;
- /** Environment variables */
- env?: Record<string, string>;
- /** Session ID to resume (for multi-turn) */
- resumeSessionId?: string;
- /** Run claude-code prompts through the Claude Agent SDK instead of CLI spawn (lab preference) */
- useClaudeCodeSdk?: boolean;
-}
-
-interface StartSessionResult {
- sessionId: string;
-}
-
-/** Run identity the browser MCP tools need to reach the right in-app page. */
-interface BrowserRunBinding {
- agentId?: string;
- topicId?: string;
-}
-
-interface SendPromptParams {
- /**
- * Agent this run belongs to. Rides along to the renderer so it can tell
- * whether revealing the browser panel would yank the user's view to a run
- * they aren't watching.
- */
- agentId?: string;
- /** Image attachments to include in the prompt (downloaded from url, cached by id) */
- imageList?: HeterogeneousAgentImageAttachment[];
- /**
- * Renderer-side operation id stamped onto every emitted `AgentStreamEvent`.
- * Required: producer-side conversion is the V3 contract — by the time events
- * reach the renderer they must already carry the operation they belong to.
- */
- operationId: string;
- prompt: string;
- /**
- * Prior conversation turns used to rebuild a Claude Code transcript that the
- * CLI garbage-collected (`cleanupPeriodDays`, default 30 days). Only consumed
- * when resuming and the on-disk transcript is missing — see
- * `ensureClaudeCodeResumeTranscript`. Without it, `--resume <staleId>` fails
- * with "No conversation found with session ID".
- */
- resumeReplayMessages?: HeteroSessionImportMessage[];
- sessionId: string;
- /** Extra context injected before the user prompt without mutating the prompt text. */
- systemContext?: string;
- /**
- * Topic this run belongs to. Binds the op to its in-app browser session
- * (`topic:<topicId>`) so the browser MCP tools act on the right page.
- *
- * Not to be confused with `sessionId`, which is the CC/Codex agent session —
- * a different namespace entirely.
- */
- topicId?: string;
-}
-
-interface CancelSessionParams {
- sessionId: string;
-}
-
-interface SubmitInterventionParams {
- cancelled?: boolean;
- /** When set, signals user-cancelled or timeout — the bridge resolves with isError. */
- cancelReason?: 'timeout' | 'user_cancelled';
- /** Operation id stamped on the request the renderer is responding to. */
- operationId: string;
- /** Structured user answer; ignored when `cancelled` is true. */
- result?: unknown;
- /** Correlation key carried on the original `agent_intervention_request`. */
- toolCallId: string;
-}
-
-interface StopSessionParams {
- sessionId: string;
-}
-
-interface GetSessionInfoParams {
- sessionId: string;
-}
-
-interface GetCodexQuotaParams {
- command?: string;
- env?: Record<string, string>;
- force?: boolean;
-}
-
-interface ConsumeCodexRateLimitResetCreditParams {
- command?: string;
- creditId?: string;
- env?: Record<string, string>;
- idempotencyKey: string;
-}
-
-interface GetClaudeCodeQuotaParams {
- env?: Record<string, string>;
- force?: boolean;
-}
-
-interface SessionInfo {
- agentSessionId?: string;
-}
-
-// ─── Internal session tracking ───
-interface AgentSession {
- agentSessionId?: string;
- agentType: HeterogeneousCliAgentType;
- args: string[];
- /**
- * True when *we* initiated the kill (cancelSession / stopSession / before-quit).
- * The `exit` handler uses this to route signal-induced non-zero exits through
- * the `complete` broadcast instead of surfacing them as runtime errors —
- * SIGINT(130) / SIGTERM(143) / SIGKILL(137) from our own kill paths are
- * intentional, not agent failures.
- */
- cancelledByUs?: boolean;
- command: string;
- cwd?: string;
- env?: Record<string, string>;
- model?: string;
- modelSource?: string;
- modelVerificationLastAttemptAt?: number;
- modelVerificationLastAttemptSessionId?: string;
- process?: ChildProcess;
- /**
- * Absolute CLI path resolved by spawn preflight detection. Used for spawn()
- * when the configured command is bare: detection can find the CLI through
- * the login-shell PATH or a well-known install location (e.g. an app-bundled
- * Codex CLI) that plain spawn() with the inherited env can't resolve.
- */
- resolvedCommandPath?: string;
- /**
- * PATH the preflight detector used to resolve `resolvedCommandPath`, set only
- * when it fell back to the login-shell PATH. Merged into the child PATH at
- * spawn so a `#!/usr/bin/env node` shim still finds its interpreter — the
- * shim resolving in preflight doesn't guarantee `node` is on the leaner
- * inherited PATH (Finder-launched Electron).
- */
- resolvedCommandSearchPath?: string;
- resumeSessionId?: string;
- sdkSession?: ClaudeAgentSdkSession;
- sessionId: string;
- useClaudeCodeSdk?: boolean;
- verifiedModel?: string;
- verifiedModelContextWindow?: number;
- verifiedModelProvider?: string;
- verifiedModelSessionId?: string;
- verifiedModelSourceFile?: string;
-}
-
-type SessionErrorPayload = HeterogeneousAgentSessionError | string;
-
-interface CliTraceSession {
- dir: string;
- writeQueue: Promise<void>;
-}
+type Implementation = HeterogeneousAgentImplementation;
/**
- * External Agent Controller — manages external agent CLI processes via Electron IPC.
- *
- * Agent-agnostic: delegates spawn-plan construction and stdout framing to a
- * per-agent driver so Claude Code, Codex, and future CLIs can differ in
- * prompt transport, resume semantics, and raw stream shape without turning
- * this controller into a giant `switch`.
- *
- * Lifecycle: startSession → sendPrompt → (heteroAgentEvent broadcasts) → stopSession
+ * Registers the stable heterogeneous-agent IPC surface without evaluating the
+ * CLI adapters, stream pipeline, quota samplers, and MCP implementation during
+ * application startup. The implementation is loaded exactly once on first use.
*/
-interface InterventionSlot {
- bridge: AskUserBridge;
- /** Resolves once bridge.events() iterator ends (after `cancelAll`). */
- pumpDone?: Promise<void>;
- /** Path to the per-op temp `mcp.json` we wrote for `--mcp-config`. */
- tmpConfigPath: string;
-}
-
export default class HeterogeneousAgentCtr extends ControllerModule {
static override readonly groupName = 'heterogeneousAgent';
- private sessions = new Map<string, AgentSession>();
- /**
- * Per-operation AskUserQuestion bridge state. Keyed by `operationId` so the
- * `submitIntervention` IPC can route an answer to the right pending MCP
- * handler regardless of which `sessionId` it belongs to (one session can
- * fire many ops over its lifetime).
- */
- private opIdToIntervention = new Map<string, InterventionSlot>();
- /**
- * Op → run identity for browser MCP tool session resolution. The main process
- * otherwise has no idea which topic an operation belongs to, and the browser
- * session is keyed by topic (`topic:<topicId>`).
- */
- private opIdToBrowserBinding = new Map<string, BrowserRunBinding>();
- /** Lazy single MCP server, started on first claude-code prompt. */
- private builtinMcpServer?: LobeBuiltinMcpServer;
- private builtinMcpStartPromise?: Promise<LobeBuiltinMcpServer>;
- // Fresh window sits under the renderer's 2-minute auto-refresh so each
- // scheduled poll reaches the usage API instead of a cache echo.
- private readonly claudeCodeQuotaCache = new QuotaSnapshotCache<ClaudeCodeQuotaSnapshot>({
- freshMs: CLAUDE_CODE_QUOTA_FRESH_MS,
- });
- private readonly codexQuotaCache = new QuotaSnapshotCache<CodexQuotaSnapshot>();
-
- private get remoteServerConfigCtr() {
- return this.app.getController(RemoteServerConfigCtr);
- }
-
- /**
- * Uploads a base64 tool_result image (CC `Read` on an image file) to the file
- * store, so the persisted event carries a `{ fileId, url }` reference instead
- * of heavy base64. Mirrors what `lh hetero exec` does for the gateway path.
- */
- private uploadResultImage = createFileStoreImageUploader(() =>
- createLambdaFileStorePort({
- getAccessToken: () => this.remoteServerConfigCtr.getAccessToken(),
- getServerUrl: async () => (await this.remoteServerConfigCtr.getRemoteServerUrl()) ?? null,
- }),
- );
-
- private resolveSessionCommand(session: AgentSession): string {
- const resolvedCommand = session.command.trim();
- if (resolvedCommand) return resolvedCommand;
-
- switch (session.agentType) {
- case 'amp': {
- return 'amp';
- }
- case 'codex': {
- return 'codex';
- }
- case 'opencode': {
- return 'opencode';
- }
- default: {
- return 'claude';
- }
- }
- }
-
- private buildAmpCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {
- const command = this.resolveSessionCommand(session);
-
- return {
- agentType: 'amp',
- code: HeterogeneousAgentSessionErrorCode.CliNotFound,
- command,
- docsUrl: AMP_CLI_INSTALL_DOCS_URL,
- installCommands: AMP_CLI_INSTALL_COMMANDS,
- message: `Amp CLI was not found. Install it and make sure \`${command}\` can be executed.`,
- };
- }
-
- private buildCodexCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {
- const command = this.resolveSessionCommand(session);
-
- return {
- agentType: 'codex',
- code: HeterogeneousAgentSessionErrorCode.CliNotFound,
- command,
- docsUrl: CODEX_CLI_INSTALL_DOCS_URL,
- installCommands: CODEX_CLI_INSTALL_COMMANDS,
- message: `Codex CLI was not found. Install it and make sure \`${command}\` can be executed.`,
- };
- }
-
- private buildClaudeCodeCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {
- const command = this.resolveSessionCommand(session);
-
- return {
- agentType: 'claude-code',
- code: HeterogeneousAgentSessionErrorCode.CliNotFound,
- command,
- docsUrl: CLAUDE_CODE_CLI_INSTALL_DOCS_URL,
- installCommands: CLAUDE_CODE_CLI_INSTALL_COMMANDS,
- message: `Claude Code CLI was not found. Install it and make sure \`${command}\` can be executed.`,
- };
- }
-
- private buildOpenCodeCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {
- const command = this.resolveSessionCommand(session);
-
- return {
- agentType: 'opencode',
- code: HeterogeneousAgentSessionErrorCode.CliNotFound,
- command,
- docsUrl: OPENCODE_CLI_INSTALL_DOCS_URL,
- installCommands: OPENCODE_CLI_INSTALL_COMMANDS,
- message: `OpenCode CLI was not found. Install it and make sure \`${command}\` can be executed.`,
- };
- }
-
- private buildCliMissingError(session: AgentSession): HeterogeneousAgentSessionError | undefined {
- switch (session.agentType) {
- case 'amp': {
- return this.buildAmpCliMissingError(session);
- }
- case 'claude-code': {
- return this.buildClaudeCodeCliMissingError(session);
- }
- case 'codex': {
- return this.buildCodexCliMissingError(session);
- }
- case 'opencode': {
- return this.buildOpenCodeCliMissingError(session);
- }
- default: {
- return;
- }
- }
- }
-
- private buildCliAuthRequiredError(
- session: AgentSession,
- stderr: string,
- ): HeterogeneousAgentSessionError | undefined {
- const command = this.resolveSessionCommand(session);
-
- switch (session.agentType) {
- case 'amp': {
- return {
- agentType: 'amp',
- code: HeterogeneousAgentSessionErrorCode.AuthRequired,
- command,
- docsUrl: AMP_CLI_INSTALL_DOCS_URL,
- message:
- 'Amp could not authenticate. Run `amp login` or configure AMP_API_KEY, then retry.',
- stderr,
- };
- }
- case 'claude-code': {
- return {
- agentType: 'claude-code',
- code: HeterogeneousAgentSessionErrorCode.AuthRequired,
- command,
- docsUrl: CLAUDE_CODE_CLI_INSTALL_DOCS_URL,
- message:
- 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',
- stderr,
- };
- }
- case 'codex': {
- return {
- agentType: 'codex',
- code: HeterogeneousAgentSessionErrorCode.AuthRequired,
- command,
- docsUrl: CODEX_CLI_INSTALL_DOCS_URL,
- message:
- 'Codex could not authenticate. Sign in again or refresh its credentials, then retry.',
- stderr,
- };
- }
- case 'opencode': {
- return {
- agentType: 'opencode',
- code: HeterogeneousAgentSessionErrorCode.AuthRequired,
- command,
- docsUrl: OPENCODE_CLI_INSTALL_DOCS_URL,
- message:
- 'OpenCode could not authenticate. Sign in again or refresh its credentials, then retry.',
- stderr,
- };
- }
- default: {
- return;
- }
- }
- }
-
- private getErrorMessage(error: unknown): string | undefined {
- return typeof error === 'string'
- ? error
- : error instanceof Error
- ? error.message
- : typeof error === 'object' &&
- error &&
- 'message' in error &&
- typeof error.message === 'string'
- ? error.message
- : undefined;
- }
-
- private buildCodexResumeError(
- code:
- | typeof HeterogeneousAgentSessionErrorCode.ResumeCwdMismatch
- | typeof HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,
- stderr: string,
- session: AgentSession,
- ): HeterogeneousAgentSessionError {
- const message =
- code === HeterogeneousAgentSessionErrorCode.ResumeCwdMismatch
- ? 'The saved Codex thread can only be resumed from its original working directory.'
- : 'The saved Codex thread could not be found, so it can no longer be resumed.';
-
- return {
- agentType: 'codex',
- code,
- command: session.command,
- message,
- resumeSessionId: session.resumeSessionId,
- stderr,
- workingDirectory: session.cwd,
- };
- }
-
- private getCodexResumeError(
- error: unknown,
- session: AgentSession,
- ): HeterogeneousAgentSessionError | undefined {
- if (session.agentType !== 'codex' || !session.resumeSessionId) return;
-
- const message = this.getErrorMessage(error);
-
- if (!message) return;
-
- if (CODEX_RESUME_CWD_MISMATCH_PATTERNS.some((pattern) => pattern.test(message))) {
- return this.buildCodexResumeError(
- HeterogeneousAgentSessionErrorCode.ResumeCwdMismatch,
- message,
- session,
- );
- }
-
- if (CODEX_RESUME_THREAD_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(message))) {
- return this.buildCodexResumeError(
- HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,
- message,
- session,
- );
- }
- }
-
- private getCliAuthRequiredError(
- error: unknown,
- session: AgentSession,
- ): HeterogeneousAgentSessionError | undefined {
- const message = this.getErrorMessage(error);
-
- if (!message) return;
- const patterns =
- session.agentType === 'amp'
- ? [...CLI_AUTH_REQUIRED_PATTERNS, ...AMP_AUTH_REQUIRED_PATTERNS]
- : CLI_AUTH_REQUIRED_PATTERNS;
- if (!patterns.some((pattern) => pattern.test(message))) return;
-
- return this.buildCliAuthRequiredError(session, message);
- }
-
- private getSessionErrorPayload(error: unknown, session: AgentSession): SessionErrorPayload {
- if (typeof error === 'object' && error && 'code' in error && error.code === 'ENOENT') {
- const cliMissingError = this.buildCliMissingError(session);
- if (cliMissingError) return cliMissingError;
- }
-
- const resumeError = this.getCodexResumeError(error, session);
- if (resumeError) return resumeError;
-
- const authRequiredError = this.getCliAuthRequiredError(error, session);
- if (authRequiredError) return authRequiredError;
-
- return error instanceof Error ? error.message : String(error);
- }
-
- private getRelevantCodexStderr(stderr: string): string {
- const keptLines: string[] = [];
- let droppingWarnBlock = false;
-
- for (const line of stderr.split(/\r?\n/)) {
- const trimmed = line.trim();
- if (!trimmed || trimmed === CODEX_STDERR_STATUS_LINE) {
- continue;
- }
-
- if (CODEX_WARN_LOG_PATTERN.test(trimmed)) {
- droppingWarnBlock = true;
- continue;
- }
-
- if (CODEX_LOG_PATTERN.test(trimmed)) {
- droppingWarnBlock = false;
- keptLines.push(line);
- continue;
- }
-
- if (droppingWarnBlock && !CLI_ERROR_LINE_PATTERN.test(trimmed)) {
- continue;
- }
-
- droppingWarnBlock = false;
- keptLines.push(line);
- }
-
- return keptLines.join('\n').trim();
- }
-
- private getExitErrorMessage(
- code: number | null,
- session: AgentSession,
- stderrOutput: string,
- ): string {
- const relevantStderr =
- session.agentType === 'codex' ? this.getRelevantCodexStderr(stderrOutput) : stderrOutput;
-
- return relevantStderr || `Agent exited with code ${code}`;
- }
-
- private async getSpawnPreflightError(
- session: AgentSession,
- ): Promise<HeterogeneousAgentSessionError | undefined> {
- const defaultCommand =
- session.agentType === 'amp'
- ? 'amp'
- : session.agentType === 'claude-code'
- ? 'claude'
- : session.agentType === 'codex'
- ? 'codex'
- : session.agentType === 'opencode'
- ? 'opencode'
- : undefined;
- if (!defaultCommand) return;
-
- const command = this.resolveSessionCommand(session);
- const status =
- command === defaultCommand
- ? await this.app.binaryManager?.detect?.(defaultCommand, true)
- : await detectHeterogeneousCliCommand(session.agentType, command);
-
- if (!status || status.available) {
- // Spawn through the detector-resolved absolute path when the configured
- // command is bare — detection may have located the CLI somewhere plain
- // spawn() can't (login-shell PATH, app-bundled Codex CLI, …).
- const useResolvedPath = Boolean(status?.path) && !command.includes(path.sep);
- session.resolvedCommandPath = useResolvedPath ? status!.path : undefined;
- // Carry the login-shell PATH the detector resolved through, so a
- // `#!/usr/bin/env node` shim spawned by absolute path still finds `node`.
- session.resolvedCommandSearchPath = useResolvedPath ? status!.resolvedPathEnv : undefined;
- return;
- }
-
- return this.buildCliMissingError(session);
- }
-
- /**
- * Global env override (`LOBE_CLAUDE_CODE_SDK`) for the SDK runtime; the
- * per-user Labs toggle arrives per session as `session.useClaudeCodeSdk`.
- */
- private get isClaudeCodeSdkLabEnabled(): boolean {
- return CLAUDE_CODE_SDK_LAB_ENABLED_VALUES.has(
- String(process.env.LOBE_CLAUDE_CODE_SDK ?? '').toLowerCase(),
- );
- }
-
- private buildSessionSpawnEnv(session: AgentSession): NodeJS.ProcessEnv {
- // Forward the user's proxy settings to the CLI/SDK subprocess. The
- // main-process undici dispatcher doesn't reach child processes — they need
- // env vars.
- const proxyEnv = buildProxyEnv(this.app.storeManager.get('networkProxy'));
- const inheritedEnv = buildInheritedSpawnEnv();
- // When preflight resolved the CLI via the login-shell PATH, spawn with
- // that PATH (a superset of the inherited one) so a `#!/usr/bin/env node`
- // shim finds its interpreter. `session.env` still wins if it sets PATH.
- if (session.resolvedCommandSearchPath) inheritedEnv.PATH = session.resolvedCommandSearchPath;
- return { ...inheritedEnv, ...proxyEnv, ...session.env };
- }
-
- private get shouldTraceCliOutput(): boolean {
- if (process.env.NODE_ENV === 'test') return false;
- // Dev builds always trace. Packaged builds trace only when the user has
- // flipped the Help-menu developer toggle — so production issues can be
- // captured on demand without polluting normal runs.
- if (!electronApp.isPackaged) return true;
- return this.app.storeManager.get('heteroTracingEnabled', false);
- }
-
- /**
- * Root directory for CLI trace sessions.
- *
- * When the user has explicitly opted in via the `heteroTracingEnabled`
- * Help-menu toggle, centralize traces under the app storage dir
- * (`<appStoragePath>/heteroAgent/tracing`) — this is the only path packaged
- * builds ever trace through, and it keeps traces out of the user's real
- * project directory while staying reachable from one stable Help-menu entry.
- *
- * Otherwise (a plain dev run with the toggle off) keep writing into the
- * working directory (`cwd/.heerogeneous-tracing`) — devs expect traces to
- * show up alongside the repo they're running in.
- */
- private resolveTraceRootDir(cwd: string): string {
- if (this.app.storeManager.get('heteroTracingEnabled', false)) {
- return path.join(this.app.appStoragePath, HETERO_AGENT_TRACING_DIR);
- }
- return path.join(cwd, CLI_TRACE_DIR);
- }
-
- private formatTraceTimestamp(date: Date): string {
- const pad = (value: number) => value.toString().padStart(2, '0');
-
- return [
- date.getFullYear(),
- pad(date.getMonth() + 1),
- pad(date.getDate()),
- '-',
- pad(date.getHours()),
- pad(date.getMinutes()),
- pad(date.getSeconds()),
- ].join('');
- }
-
- private sanitizeTracePathSegment(value: string): string {
- const sanitized = value
- .replaceAll(path.sep, '-')
- .replaceAll(/[^\w.-]+/g, '-')
- .replaceAll(/^-+|-+$/g, '')
- .slice(0, 80);
-
- return sanitized || 'unknown';
- }
-
- private getAttachmentTraceSummary(image: HeterogeneousAgentImageAttachment) {
- let urlKind = 'unknown';
-
- try {
- urlKind = new URL(image.url).protocol.replace(/:$/, '') || urlKind;
- } catch {
- urlKind = image.url.startsWith('data:') ? 'data' : 'unknown';
- }
-
- return {
- id: image.id,
- urlKind,
- };
- }
-
- private async createCliTraceSession({
- cliArgs,
- cwd,
- imageList,
- session,
- stdinPayload,
- }: {
- cliArgs: string[];
- cwd: string;
- imageList: HeterogeneousAgentImageAttachment[];
- session: AgentSession;
- stdinPayload?: string;
- }): Promise<CliTraceSession | undefined> {
- if (!this.shouldTraceCliOutput) return;
-
- // Don't materialize the cwd via mkdir — if the caller passed a stale or
- // typo'd path, we want spawn() to fail loudly instead of silently running
- // the agent in an empty auto-created directory.
- try {
- await access(cwd);
- } catch {
- return;
- }
-
- const createdAt = new Date();
- const rootDir = this.resolveTraceRootDir(cwd);
- const agentDir = path.join(rootDir, this.sanitizeTracePathSegment(session.agentType));
- const traceId = `${this.formatTraceTimestamp(createdAt)}-${this.sanitizeTracePathSegment(
- session.sessionId,
- )}`;
- const dir = path.join(agentDir, traceId);
-
- try {
- await mkdir(dir, { recursive: true });
- await writeFile(path.join(rootDir, '.last-live-trace'), `${dir}\n`);
- await writeFile(path.join(dir, 'stdout.jsonl'), '');
- await writeFile(path.join(dir, 'stderr.log'), '');
- if (stdinPayload !== undefined) {
- await writeFile(path.join(dir, 'stdin.txt'), '');
- }
- await writeFile(
- path.join(dir, 'meta.json'),
- `${JSON.stringify(
- {
- agentSessionId: session.agentSessionId,
- agentType: session.agentType,
- args: cliArgs,
- attachments: imageList.map((image) => this.getAttachmentTraceSummary(image)),
- command: session.command,
- createdAt: createdAt.toISOString(),
- cwd,
- envKeys: session.env ? Object.keys(session.env).sort() : [],
- model: session.model,
- modelSource: session.modelSource,
- resumeSessionId: session.resumeSessionId,
- sessionId: session.sessionId,
- stdinBytes: stdinPayload === undefined ? 0 : Buffer.byteLength(stdinPayload),
- stdinFile: stdinPayload === undefined ? undefined : 'stdin.txt',
- stderrFile: 'stderr.log',
- stdoutFile: 'stdout.jsonl',
- verifiedModel: session.verifiedModel,
- verifiedModelContextWindow: session.verifiedModelContextWindow,
- verifiedModelProvider: session.verifiedModelProvider,
- verifiedModelSessionId: session.verifiedModelSessionId,
- verifiedModelSourceFile: session.verifiedModelSourceFile,
- },
- null,
- 2,
- )}\n`,
- );
-
- return { dir, writeQueue: Promise.resolve() };
- } catch (error) {
- logger.warn('Failed to initialize CLI trace directory:', error);
- }
- }
-
- private queueCliTraceWrite(
- trace: CliTraceSession | undefined,
- write: () => Promise<void>,
- ): Promise<void> | undefined {
- if (!trace) return;
-
- trace.writeQueue = trace.writeQueue.then(write).catch((error) => {
- logger.warn('Failed to write CLI trace file:', error);
- });
-
- return trace.writeQueue;
- }
-
- private appendCliTraceFile(
- trace: CliTraceSession | undefined,
- fileName: string,
- data: Buffer | string,
- ): Promise<void> | undefined {
- if (!trace) return;
-
- const filePath = path.join(trace.dir, fileName);
-
- return this.queueCliTraceWrite(trace, () => appendFile(filePath, data));
- }
-
- private writeCliTraceFile(
- trace: CliTraceSession | undefined,
- fileName: string,
- data: string,
- ): Promise<void> | undefined {
- if (!trace) return;
-
- const filePath = path.join(trace.dir, fileName);
+ private implementationPromise?: Promise<Implementation>;
- return this.queueCliTraceWrite(trace, () => writeFile(filePath, data));
- }
-
- private writeCliTraceJson(
- trace: CliTraceSession | undefined,
- fileName: string,
- payload: unknown,
- ): Promise<void> | undefined {
- return this.writeCliTraceFile(trace, fileName, `${JSON.stringify(payload, null, 2)}\n`);
- }
-
- private async flushCliTrace(trace: CliTraceSession | undefined): Promise<void> {
- await trace?.writeQueue;
- }
-
- // ─── Broadcast ───
-
- private broadcast<T>(channel: string, data: T) {
- for (const win of BrowserWindow.getAllWindows()) {
- if (!win.isDestroyed()) {
- win.webContents.send(channel, data);
- }
- }
- }
-
- // ─── AskUserQuestion MCP server () ───
-
- /**
- * Lazy single-instance MCP server for CC's AskUserQuestion replacement.
- * First claude-code prompt triggers `start()`; subsequent prompts reuse
- * the same listener. Concurrent first-callers de-dupe via the in-flight
- * promise so we don't bind two ports.
- */
- private async ensureBuiltinMcpServerStarted(): Promise<LobeBuiltinMcpServer> {
- if (this.builtinMcpServer) return this.builtinMcpServer;
- if (!this.builtinMcpStartPromise) {
- this.builtinMcpStartPromise = (async () => {
- const server = new LobeBuiltinMcpServer({
- // In-app browser control tools ride the same per-op MCP server so
- // CC can drive the browser sidebar ( M3, hetero path).
- extraTools: buildBrowserMcpTools((operationId, apiName, args) =>
- this.runBrowserMcpTool(operationId, apiName, args),
- ),
- });
- await server.start();
- this.builtinMcpServer = server;
- logger.info('AskUserQuestion MCP server started:', server.url);
- return server;
- })().catch((err) => {
- // Reset so a later sendPrompt can retry; surface the error.
- this.builtinMcpStartPromise = undefined;
- logger.error('Failed to start AskUserQuestion MCP server:', err);
- throw err;
- });
- }
- return this.builtinMcpStartPromise;
- }
-
- /**
- * Register a per-op AskUserQuestion bridge, write its temp `mcp.json`,
- * and stash it for the spawn path. The actual bridge event pump is started
- * from `handleSpawnedAgentProcess`, where it can share the stdout broadcast
- * queue instead of racing the adapter pipeline as a second producer.
- */
- private async setupInterventionForOp(
- operationId: string,
- browserBinding?: BrowserRunBinding,
- ): Promise<{ bridge: AskUserBridge; cleanup: () => Promise<void>; tmpConfigPath: string }> {
- const server = await this.ensureBuiltinMcpServerStarted();
- const bridge = server.registerOperation(operationId);
- if (browserBinding?.agentId || browserBinding?.topicId) {
- this.opIdToBrowserBinding.set(operationId, browserBinding);
- }
- const tmpConfigPath = path.join(os.tmpdir(), `lobe-cc-mcp-${operationId}.json`);
-
- // `alwaysLoad: true` is the undocumented CC flag that promotes our
- // server's tool out of the deferred set so the model calls it directly
- // (no ToolSearch hop). See spike notes — falls back to the
- // 2-hop ToolSearch path if a future CC drops the flag, no breakage.
- const config = {
- mcpServers: {
- lobe_cc: {
- alwaysLoad: true,
- type: 'http' as const,
- url: server.urlForOperation(operationId),
- },
- },
- };
- await writeFile(tmpConfigPath, JSON.stringify(config), 'utf8');
-
- const slot: InterventionSlot = { bridge, tmpConfigPath };
- this.opIdToIntervention.set(operationId, slot);
-
- const cleanup = async () => {
- // Unregistering on the server cancels all bridge pendings AND closes
- // the events iterator (cancelAll fires from within unregisterOperation).
- this.builtinMcpServer?.unregisterOperation(operationId);
- await slot.pumpDone;
- this.opIdToIntervention.delete(operationId);
- this.opIdToBrowserBinding.delete(operationId);
- await unlink(tmpConfigPath).catch(() => {
- /* file may already be gone if app crashed mid-prompt */
+ private getImplementation = (): Promise<Implementation> => {
+ this.implementationPromise ??= import('./HeterogeneousAgentImpl')
+ .then(({ default: Implementation }) => {
+ const implementation = new Implementation(this.app);
+ implementation.afterAppReady();
+ return implementation;
+ })
+ .catch((error) => {
+ this.implementationPromise = undefined;
+ throw error;
});
- };
-
- return { bridge, cleanup, tmpConfigPath };
- }
-
- /**
- * Execute one in-app browser api call on behalf of a CC MCP tool. Forwards
- * through `BrowserControlCtr.runGatewayToolCall` — the same funnel cloud
- * gateway calls use — so the renderer-side `browserExecutor` (webview
- * mount, snapshot refs, cursor overlay) stays the single source of truth.
- */
- private async runBrowserMcpTool(
- operationId: string,
- apiName: string,
- args: Record<string, unknown>,
- ): Promise<McpToolResult> {
- const binding = this.opIdToBrowserBinding.get(operationId);
- if (!binding?.agentId || !binding.topicId) {
- return {
- content: [
- {
- text: 'The in-app browser is not available for this run (no topic binding). Continue without it.',
- type: 'text',
- },
- ],
- isError: true,
- };
- }
-
- const result = await this.app.getController(BrowserControlCtr).runGatewayToolCall(apiName, {
- ...args,
- __agentId: binding.agentId,
- __topicId: binding.topicId,
- });
-
- const text =
- result.content ?? result.error?.message ?? (result.success ? 'OK' : 'Browser action failed');
- const content: McpToolResult['content'] = [{ text, type: 'text' }];
-
- // Screenshot: hand the image back as an MCP image block so CC can
- // actually see the page (unlike the homogeneous runtime's text-only echo).
- if (apiName === 'screenshot') {
- const dataUrl = (result.state as { dataUrl?: string } | undefined)?.dataUrl;
- const match =
- typeof dataUrl === 'string' ? dataUrl.match(/^data:(image\/[\w.+-]+);base64,(.+)$/) : null;
- if (match) content.push({ data: match[2], mimeType: match[1], type: 'image' });
- }
- return { content, isError: !result.success };
- }
-
- // ─── File cache ───
-
- private get fileCacheDir(): string {
- return path.join(this.app.appStoragePath, FILE_CACHE_DIR);
- }
-
- /**
- * Build a Claude Code stream-json user message with text + base64 images.
- * Semantic context is assembled by the shared prompt engine before the
- * provider-specific serializer runs.
- */
- private async buildStreamJsonInput(
- prompt: string,
- imageList: HeterogeneousAgentImageAttachment[] = [],
- systemContext?: string,
- ): Promise<string> {
- const promptInput = buildHeterogeneousPrompt({ imageList, prompt, systemContext });
- const plan = await buildAgentInput('claude-code', promptInput, {
- cacheDir: this.fileCacheDir,
- });
- return plan.stdin;
- }
-
- // ─── IPC methods ───
+ return this.implementationPromise;
+ };
- /**
- * Create a session (stores config, process spawned on sendPrompt).
- */
@IpcMethod()
- async startSession(params: StartSessionParams): Promise<StartSessionResult> {
- const sessionId = randomUUID();
- const agentType = params.agentType || 'claude-code';
- getHeterogeneousAgentDriver(agentType);
-
- this.sessions.set(sessionId, {
- // If resuming, pre-set the agent session ID so sendPrompt adds --resume
- agentSessionId: params.resumeSessionId,
- agentType,
- args: params.args || [],
- command: params.command,
- cwd: params.cwd,
- env: params.env,
- sessionId,
- resumeSessionId: params.resumeSessionId,
- useClaudeCodeSdk: params.useClaudeCodeSdk,
- });
-
- logger.info('Session created:', { agentType, sessionId });
- return { sessionId };
+ async startSession(...args: Parameters<Implementation['startSession']>) {
+ return (await this.getImplementation()).startSession(...args);
}
- /**
- * Send a prompt to an agent session.
- *
- * Spawns the CLI process with preset flags. Pipes each stdout chunk through
- * the shared `AgentStreamPipeline` (JSONL → adapter → toStreamEvent) and
- * broadcasts the resulting `AgentStreamEvent`s on `heteroAgentEvent`.
- */
@IpcMethod()
- async sendPrompt(params: SendPromptParams): Promise<void> {
- const session = this.sessions.get(params.sessionId);
- if (!session) throw new Error(`Session not found: ${params.sessionId}`);
-
- const preflightError = await this.getSpawnPreflightError(session);
- if (preflightError) {
- this.broadcast('heteroAgentSessionError', {
- error: preflightError,
- sessionId: session.sessionId,
- });
- throw new Error(preflightError.message);
- }
-
- // Revive a Claude Code session whose local transcript the CLI already
- // garbage-collected (`cleanupPeriodDays`, default 30 days). Rebuilding it
- // from the turns LobeHub still holds turns a hard
- // "No conversation found with session ID" into a normal `--resume` that
- // hydrates the native history. No-ops when the transcript still exists.
- // MUST run before the Claude SDK early return — both transports read the
- // same on-disk transcript for resume.
- if (
- session.agentType === 'claude-code' &&
- session.agentSessionId &&
- session.cwd &&
- params.resumeReplayMessages?.length
- ) {
- try {
- const ensured = await ensureClaudeCodeResumeTranscript({
- cwd: session.cwd,
- messages: params.resumeReplayMessages,
- sessionId: session.agentSessionId,
- });
- if (ensured.written)
- logger.info('Rebuilt GC-ed Claude Code transcript for resume:', {
- path: ensured.path,
- turns: params.resumeReplayMessages.length,
- });
- } catch (error) {
- // Never block the run on this — worst case CC starts a fresh session.
- logger.warn('Failed to rebuild Claude Code resume transcript:', error);
- }
- }
-
- if (
- session.agentType === 'claude-code' &&
- (session.useClaudeCodeSdk || this.isClaudeCodeSdkLabEnabled)
- ) {
- return this.sendPromptWithClaudeSdk(params, session);
- }
-
- // Stand up the AskUserQuestion MCP bridge for claude-code prompts BEFORE
- // building the spawn plan so the driver can wire the temp config path
- // into `--mcp-config`. Codex / future agents skip this entirely.
- const intervention =
- session.agentType === 'claude-code'
- ? await this.setupInterventionForOp(params.operationId, {
- agentId: params.agentId,
- topicId: params.topicId,
- }).catch((err) => {
- logger.warn('Failed to set up AskUserQuestion bridge — proceeding without it:', err);
- return undefined;
- })
- : undefined;
-
- let spawnPlan;
- let traceSession;
- let cwd: string;
- let initialCumulativeUsage: UsageData | undefined;
- let spawnEnv: NodeJS.ProcessEnv;
- try {
- const driver = getHeterogeneousAgentDriver(session.agentType);
- const promptInput = buildHeterogeneousPrompt({
- imageList: params.imageList,
- prompt: params.prompt,
- systemContext: params.systemContext,
- });
- spawnPlan = await driver.buildSpawnPlan({
- args: session.args,
- helpers: {
- buildAgentInput: async (agentType, input) => {
- try {
- return await buildAgentInput(agentType, input, { cacheDir: this.fileCacheDir });
- } catch (error) {
- logger.error('Failed to prepare heterogeneous agent input:', error);
- throw new Error(
- `Failed to attach image(s) to CLI: ${this.getErrorMessage(error) || 'Unknown error'}`,
- { cause: error },
- );
- }
- },
- },
- mcpConfigPath: intervention?.tmpConfigPath,
- promptInput,
- resumeSessionId: session.agentSessionId,
- });
-
- // Fall back to the user's Desktop so the process never inherits
- // the Electron parent's cwd (which is `/` when launched from Finder).
- cwd = session.cwd || electronApp.getPath('desktop');
-
- spawnEnv = this.buildSessionSpawnEnv(session);
-
- if (session.agentType === 'codex') {
- const initialModel = await resolveCodexInitialModel({
- args: spawnPlan.args,
- env: spawnEnv,
- });
- if (initialModel?.model) {
- session.model = initialModel.model;
- session.modelSource = initialModel.source;
- }
-
- if (session.agentSessionId) {
- initialCumulativeUsage = (
- await readCodexSessionModel(session.agentSessionId, { env: spawnEnv })
- )?.cumulativeUsage;
- }
- }
-
- traceSession = await this.createCliTraceSession({
- cliArgs: spawnPlan.args,
- cwd,
- imageList: params.imageList ?? [],
- session,
- stdinPayload: spawnPlan.stdinPayload,
- });
- } catch (err) {
- // We never made it to spawn — the `proc.on('exit')` cleanup path
- // won't run, so tear the intervention bridge down right here.
- if (intervention) {
- await intervention.cleanup().catch((cleanupErr) => {
- logger.warn('AskUserQuestion cleanup error during pre-spawn failure:', cleanupErr);
- });
- }
- throw err;
- }
- const useStdin = spawnPlan.stdinPayload !== undefined;
- const cliArgs = spawnPlan.args;
- const resolvedCliSpawnPlan = await resolveCliSpawnPlan(
- session.resolvedCommandPath ?? session.command,
- cliArgs,
- );
-
- logger.info(
- 'Spawning agent:',
- resolvedCliSpawnPlan.command,
- resolvedCliSpawnPlan.args.join(' '),
- `(cwd: ${cwd})`,
- );
-
- // `detached: true` on Unix puts the child in a new process group so we
- // can SIGINT/SIGKILL the whole tree (claude + any tool subprocesses)
- // via `process.kill(-pid, sig)` on cancel. Without this, SIGINT to just
- // the claude binary can leave bash/grep/etc. tool children running and
- // the CLI hung waiting on them. Windows has different semantics — use
- // taskkill /T /F there; no detached flag needed.
- const spawnOptions = {
- cwd,
- detached: process.platform !== 'win32',
- // Strip host Anthropic creds from the inherited env so a developer's
- // shell `ANTHROPIC_API_KEY` can't hijack the CLI's own auth. `session.env`
- // is spread last, so an agent that explicitly configures a key still wins.
- env: spawnEnv,
- stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'] as ['pipe' | 'ignore', 'pipe', 'pipe'],
- };
-
- return new Promise<void>((resolve, reject) => {
- const proc = spawn(resolvedCliSpawnPlan.command, resolvedCliSpawnPlan.args, spawnOptions);
- this.handleSpawnedAgentProcess({
- cwd,
- intervention,
- params,
- proc,
- reject,
- resolve,
- session,
- initialCumulativeUsage,
- spawnEnv,
- traceSession,
- useStdin,
- spawnPlan,
- });
- });
- }
-
- private async sendPromptWithClaudeSdk(
- params: SendPromptParams,
- session: AgentSession,
- ): Promise<void> {
- const cwd = session.cwd || electronApp.getPath('desktop');
- const spawnEnv = this.buildSessionSpawnEnv(session);
- const commandPath = session.resolvedCommandPath ?? this.resolveSessionCommand(session);
- const stdinPayload = await this.buildStreamJsonInput(
- params.prompt,
- params.imageList ?? [],
- params.systemContext,
- );
- const traceSession = await this.createCliTraceSession({
- cliArgs: ['sdk-stream', ...session.args],
- cwd,
- imageList: params.imageList ?? [],
- session,
- stdinPayload,
- });
-
- void this.writeCliTraceFile(traceSession, 'stdin.txt', stdinPayload);
-
- const sdkSession = new ClaudeAgentSdkSession({
- args: session.args,
- commandPath,
- cwd,
- env: spawnEnv,
- onEvents: async (events) => {
- for (const event of events) {
- this.broadcast('heteroAgentEvent', {
- event,
- sessionId: session.sessionId,
- });
- }
- },
- onRawMessage: (line) => this.appendCliTraceFile(traceSession, 'stdout.jsonl', line),
- onRuntimeStatus: (status) => {
- this.broadcast('heteroAgentRuntimeStatus', status);
- },
- onSessionId: (agentSessionId) => {
- if (agentSessionId !== session.agentSessionId) session.agentSessionId = agentSessionId;
- },
- onStderr: (data) => this.appendCliTraceFile(traceSession, 'stderr.log', data),
- operationId: params.operationId,
- resumeSessionId: session.agentSessionId,
- sessionId: session.sessionId,
- stdinPayload,
- uploadImage: this.uploadResultImage,
- });
-
- session.sdkSession = sdkSession;
-
- logger.info('Starting Claude Code SDK session:', {
- commandPath,
- cwd,
- sessionId: session.sessionId,
- });
-
- try {
- await sdkSession.run();
- session.sdkSession = undefined;
- void this.writeCliTraceJson(traceSession, 'exit.json', {
- finishedAt: new Date().toISOString(),
- transport: 'claude-sdk',
- });
- await this.flushCliTrace(traceSession);
- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
- } catch (error) {
- session.sdkSession = undefined;
- logger.error('Claude SDK session error:', error);
- void this.writeCliTraceJson(traceSession, 'process-error.json', {
- message: error instanceof Error ? error.message : String(error),
- name: error instanceof Error ? error.name : 'Error',
- transport: 'claude-sdk',
- });
- await this.flushCliTrace(traceSession);
-
- if (session.cancelledByUs) {
- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
- return;
- }
-
- const sessionError = this.getSessionErrorPayload(error, session);
- this.broadcast('heteroAgentSessionError', {
- error: sessionError,
- sessionId: session.sessionId,
- });
- throw new Error(typeof sessionError === 'string' ? sessionError : sessionError.message, {
- cause: error,
- });
- }
- }
-
- private async verifyCodexSessionModel({
- env,
- pipeline,
- session,
- traceSession,
- }: {
- env: NodeJS.ProcessEnv;
- pipeline: AgentStreamPipeline;
- session: AgentSession;
- traceSession: CliTraceSession | undefined;
- }): Promise<AgentStreamEvent[]> {
- if (
- session.agentType !== 'codex' ||
- !pipeline.sessionId ||
- session.verifiedModelSessionId === pipeline.sessionId
- ) {
- return [];
- }
-
- const now = Date.now();
- if (
- session.modelVerificationLastAttemptSessionId === pipeline.sessionId &&
- session.modelVerificationLastAttemptAt &&
- now - session.modelVerificationLastAttemptAt < 1000
- ) {
- return [];
- }
- session.modelVerificationLastAttemptSessionId = pipeline.sessionId;
- session.modelVerificationLastAttemptAt = now;
-
- const sessionModel = await readCodexSessionModel(pipeline.sessionId, { env });
- if (!sessionModel?.model) return [];
-
- const previousModel = session.model;
- session.verifiedModel = sessionModel.model;
- session.verifiedModelContextWindow = sessionModel.contextWindow;
- session.verifiedModelProvider = sessionModel.provider;
- session.verifiedModelSessionId = pipeline.sessionId;
- session.verifiedModelSourceFile = sessionModel.sourceFile;
-
- void this.writeCliTraceJson(traceSession, 'model.json', {
- initialModel: previousModel,
- initialModelSource: session.modelSource,
- sessionId: pipeline.sessionId,
- verifiedAt: new Date().toISOString(),
- verifiedContextWindow: sessionModel.contextWindow,
- verifiedLine: sessionModel.line,
- verifiedModel: sessionModel.model,
- verifiedModelProvider: sessionModel.provider,
- verifiedSourceFile: sessionModel.sourceFile,
- });
-
- if (previousModel === sessionModel.model) return [];
-
- session.model = sessionModel.model;
- session.modelSource = 'codex-session';
- return pipeline.configureSession({ model: sessionModel.model });
- }
-
- private handleSpawnedAgentProcess({
- cwd,
- initialCumulativeUsage,
- intervention,
- params,
- proc,
- reject,
- resolve,
- session,
- spawnEnv,
- spawnPlan,
- traceSession,
- useStdin,
- }: {
- cwd: string;
- intervention?: Awaited<ReturnType<HeterogeneousAgentCtr['setupInterventionForOp']>>;
- params: SendPromptParams;
- proc: ChildProcess;
- reject: (reason?: unknown) => void;
- resolve: () => void;
- session: AgentSession;
- initialCumulativeUsage?: UsageData | undefined;
- spawnEnv: NodeJS.ProcessEnv;
- spawnPlan: HeterogeneousAgentBuildPlan;
- traceSession: CliTraceSession | undefined;
- useStdin: boolean;
- }) {
- proc.on('error', (err) => {
- logger.error('Agent process error:', err);
- void this.writeCliTraceJson(traceSession, 'process-error.json', {
- message: err.message,
- name: err.name,
- });
- void this.flushCliTrace(traceSession);
- const sessionError = this.getSessionErrorPayload(err, session);
- this.broadcast('heteroAgentSessionError', {
- error: sessionError,
- sessionId: session.sessionId,
- });
- reject(new Error(typeof sessionError === 'string' ? sessionError : sessionError.message));
- });
-
- // In stdin mode, write the prepared payload and close stdin.
- if (useStdin && spawnPlan.stdinPayload !== undefined && proc.stdin) {
- void this.writeCliTraceFile(traceSession, 'stdin.txt', spawnPlan.stdinPayload);
- const stdin = proc.stdin as Writable;
- stdin.write(spawnPlan.stdinPayload, () => {
- stdin.end();
- });
- }
-
- session.process = proc;
-
- // Producer-side conversion (V3 contract): JSONL framing + adapter +
- // toStreamEvent all run inside the shared pipeline, so renderer + future
- // server `heteroIngest` see the same `AgentStreamEvent` wire shape with
- // no per-consumer adapter. The pipeline auto-wires the Codex
- // file-change diff/stat tracker when `agentType === 'codex'`, so this
- // controller stays agent-agnostic.
- const pipeline = new AgentStreamPipeline({
- agentType: session.agentType,
- cwd,
- initialCumulativeUsage,
- initialModel: session.model,
- operationId: params.operationId,
- uploadImage: this.uploadResultImage,
- });
- let stdoutBroadcastQueue: Promise<void> = Promise.resolve();
-
- const broadcastStreamEvents = (events: AgentStreamEvent[]) => {
- for (const event of events) {
- this.broadcast('heteroAgentEvent', {
- event,
- sessionId: session.sessionId,
- });
- }
- };
-
- const broadcastPipelineBatch = (produce: () => ReturnType<AgentStreamPipeline['push']>) => {
- stdoutBroadcastQueue = stdoutBroadcastQueue
- .then(async () => {
- const events = await produce();
- // Adapter-extracted CC/Codex session id powers `--resume` on the
- // next prompt; surface it through the existing `getSessionInfo`
- // IPC by mirroring the freshest value onto the session record.
- if (pipeline.sessionId && pipeline.sessionId !== session.agentSessionId) {
- session.agentSessionId = pipeline.sessionId;
- }
- events.push(
- ...(await this.verifyCodexSessionModel({
- env: spawnEnv,
- pipeline,
- session,
- traceSession,
- })),
- );
- broadcastStreamEvents(events);
- })
- .catch((error) => {
- logger.error('Failed to broadcast agent stream batch:', error);
- });
- };
-
- const broadcastBridgeEvent = (event: AgentStreamEvent) => {
- stdoutBroadcastQueue = stdoutBroadcastQueue
- .then(() => {
- broadcastStreamEvents([event]);
- })
- .catch((error) => {
- logger.error('Failed to broadcast AskUserQuestion bridge event:', error);
- });
- };
-
- if (intervention) {
- const pumpDone = (async () => {
- for await (const event of intervention.bridge.events()) {
- broadcastBridgeEvent(event);
- }
- await stdoutBroadcastQueue;
- })().catch((err) => {
- logger.warn('AskUserQuestion bridge pump error:', err);
- });
- const slot = this.opIdToIntervention.get(params.operationId);
- if (slot) slot.pumpDone = pumpDone;
- }
-
- // Stream stdout events through the producer pipeline.
- const stdout = proc.stdout as Readable;
- stdout.on('data', (chunk: Buffer) => {
- void this.appendCliTraceFile(traceSession, 'stdout.jsonl', chunk);
- broadcastPipelineBatch(() => pipeline.push(chunk));
- });
- stdout.on('end', () => {
- broadcastPipelineBatch(() => pipeline.flush());
- });
-
- // Capture stderr
- const stderrChunks: string[] = [];
- const stderr = proc.stderr as Readable;
- stderr.on('data', (chunk: Buffer) => {
- void this.appendCliTraceFile(traceSession, 'stderr.log', chunk);
- stderrChunks.push(chunk.toString('utf8'));
- });
-
- proc.on('exit', (code, signal) => {
- // Node may emit `'exit'` BEFORE stdio finishes draining (documented:
- // child_process docs note "stdio streams might still be open" at exit
- // time). Wait for stdout to fully end/close so the `stdout.on('end')`
- // handler has scheduled `pipeline.flush()` onto `stdoutBroadcastQueue`,
- // THEN wait for the queue itself to settle. Without this two-step
- // gate, trailing flushed events (final synthesized tool_end /
- // tool_result) would race against — and lose to — the
- // `heteroAgentSessionComplete` broadcast, leaving renderer-side
- // persistence to finalize on incomplete state.
- const stdoutDrained = streamFinished(stdout, { writable: false }).catch(() => {
- /* end / close / error are all "done"; we still want to settle. */
- });
-
- void stdoutDrained
- .then(() => stdoutBroadcastQueue)
- .finally(async () => {
- // Tear down the AskUserQuestion bridge / temp `mcp.json` for this
- // op. Pending MCP handlers get a `session_ended` cancellation so
- // they return cleanly even if CC was killed mid-tool-call.
- if (intervention) {
- await intervention.cleanup().catch((err) => {
- logger.warn('AskUserQuestion cleanup error:', err);
- });
- }
-
- void this.writeCliTraceJson(traceSession, 'exit.json', {
- code,
- finishedAt: new Date().toISOString(),
- signal,
- });
- await this.flushCliTrace(traceSession);
- await waitForHeteroSessionCompleteGrace();
-
- logger.info('Agent process exited:', { code, sessionId: session.sessionId, signal });
- session.process = undefined;
-
- // If *we* killed it (cancel / stop / before-quit), treat the non-zero
- // exit as a clean shutdown — surfacing it as an error would make a
- // user-initiated cancel look like an agent failure, and an Electron
- // shutdown affecting OTHER running CC sessions would pollute their
- // topics with a misleading "Agent exited with code 143" message.
- if (session.cancelledByUs) {
- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
- resolve();
- return;
- }
-
- if (code === 0) {
- this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
- resolve();
- } else {
- const stderrOutput = stderrChunks.join('').trim();
- const errorMsg = this.getExitErrorMessage(code, session, stderrOutput);
- const sessionError = this.getSessionErrorPayload(errorMsg, session);
- this.broadcast('heteroAgentSessionError', {
- error: sessionError,
- sessionId: session.sessionId,
- });
- reject(
- new Error(typeof sessionError === 'string' ? sessionError : sessionError.message),
- );
- }
- });
- });
+ async sendPrompt(...args: Parameters<Implementation['sendPrompt']>) {
+ return (await this.getImplementation()).sendPrompt(...args);
}
- /**
- * Get session info (agent's internal session ID for multi-turn resume).
- */
@IpcMethod()
- async getSessionInfo(params: GetSessionInfoParams): Promise<SessionInfo> {
- const session = this.sessions.get(params.sessionId);
- return { agentSessionId: session?.agentSessionId };
+ async getSessionInfo(...args: Parameters<Implementation['getSessionInfo']>) {
+ return (await this.getImplementation()).getSessionInfo(...args);
}
- /** Query OpenCode's model catalog using the same cwd/env rules as a real local session. */
@IpcMethod()
- async listModels(
- params: ListHeterogeneousAgentModelsParams,
- ): Promise<HeterogeneousAgentModelCatalog> {
- const env = {
- ...buildInheritedSpawnEnv(),
- ...buildProxyEnv(this.app.storeManager.get('networkProxy')),
- ...params.env,
- };
-
- return listHeterogeneousAgentModels({
- ...params,
- cwd: params.cwd || electronApp.getPath('desktop'),
- env,
- });
+ async listModels(...args: Parameters<Implementation['listModels']>) {
+ return (await this.getImplementation()).listModels(...args);
}
@IpcMethod()
- async getCodexQuota(params: GetCodexQuotaParams = {}): Promise<CodexQuotaSnapshot> {
- const command = params.command?.trim() || 'codex';
- const sourceEnv = {
- ...buildProxyEnv(this.app.storeManager.get('networkProxy')),
- ...params.env,
- };
- const sourceKey = createQuotaCacheKey('codex', command, sourceEnv);
-
- return this.codexQuotaCache.get(
- sourceKey,
- async () => {
- const status = await detectHeterogeneousCliCommand('codex', command);
- const env = {
- ...(status.resolvedPathEnv ? { PATH: status.resolvedPathEnv } : {}),
- ...sourceEnv,
- };
-
- return fetchCodexQuota({
- command: status.available && status.path ? status.path : command,
- env: Object.keys(env).length > 0 ? env : undefined,
- });
- },
- { force: params.force },
- );
+ async getCodexQuota(...args: Parameters<Implementation['getCodexQuota']>) {
+ return (await this.getImplementation()).getCodexQuota(...args);
}
- /**
- * Redeem one earned Codex rate-limit reset, then bypass the quota cache so
- * every renderer receives the post-reset windows and remaining inventory.
- */
@IpcMethod()
async consumeCodexRateLimitResetCredit(
- params: ConsumeCodexRateLimitResetCreditParams,
- ): Promise<CodexRateLimitResetResult> {
- const command = params.command?.trim() || 'codex';
- const sourceEnv = {
- ...buildProxyEnv(this.app.storeManager.get('networkProxy')),
- ...params.env,
- };
- const sourceKey = createQuotaCacheKey('codex', command, sourceEnv);
- const status = await detectHeterogeneousCliCommand('codex', command);
- const env = {
- ...(status.resolvedPathEnv ? { PATH: status.resolvedPathEnv } : {}),
- ...sourceEnv,
- };
- const requestOptions = {
- command: status.available && status.path ? status.path : command,
- env: Object.keys(env).length > 0 ? env : undefined,
- };
-
- const outcome = await consumeCodexRateLimitResetCreditRequest({
- ...requestOptions,
- creditId: params.creditId,
- idempotencyKey: params.idempotencyKey,
- });
- this.codexQuotaCache.invalidate(sourceKey);
- const quota = await this.codexQuotaCache.get(sourceKey, () => fetchCodexQuota(requestOptions), {
- force: true,
- });
-
- return { outcome, quota };
+ ...args: Parameters<Implementation['consumeCodexRateLimitResetCredit']>
+ ) {
+ return (await this.getImplementation()).consumeCodexRateLimitResetCredit(...args);
}
- /**
- * Read the Claude Code subscription quota. No CLI is spawned: the quota
- * comes from Anthropic's OAuth usage API using the local `claude` login,
- * and the request goes through the app's global proxy dispatcher.
- */
- /**
- * Identity of the Claude login a spawn with this env would use. Pure local
- * file read (`.claude.json` of the resolved profile) — cheap enough to call
- * once per run for usage→account attribution; never touches the network.
- */
@IpcMethod()
- async getClaudeCodeIdentity(params: { env?: Record<string, string> } = {}) {
- return readClaudeCodeIdentity({ env: params.env });
+ async getClaudeCodeIdentity(...args: Parameters<Implementation['getClaudeCodeIdentity']>) {
+ return (await this.getImplementation()).getClaudeCodeIdentity(...args);
}
@IpcMethod()
- async getClaudeCodeQuota(
- params: GetClaudeCodeQuotaParams = {},
- ): Promise<ClaudeCodeQuotaSnapshot> {
- const sourceKey = createQuotaCacheKey('claude-code', params.env);
-
- return this.claudeCodeQuotaCache.get(
- sourceKey,
- () => fetchClaudeCodeQuota({ env: params.env }),
- { force: params.force },
- );
+ async getClaudeCodeQuota(...args: Parameters<Implementation['getClaudeCodeQuota']>) {
+ return (await this.getImplementation()).getClaudeCodeQuota(...args);
}
- /**
- * Signal the whole process tree spawned by this session.
- *
- * On Unix the child was spawned with `detached: true`, so negating the pid
- * signals the process group — reaching tool subprocesses (bash, grep, etc.)
- * that would otherwise orphan after a parent-only kill. Falls back to the
- * direct signal if the group kill raises (ESRCH when the leader is already
- * gone). On Windows we shell out to `taskkill /T /F` which walks the tree.
- */
- private killProcessTree(proc: ChildProcess, signal: NodeJS.Signals): void {
- if (!proc.pid || proc.killed) return;
-
- if (process.platform === 'win32') {
- try {
- spawn('taskkill', ['/pid', String(proc.pid), '/T', '/F'], { stdio: 'ignore' });
- } catch (err) {
- logger.warn('taskkill failed:', err);
- }
- return;
- }
-
- try {
- process.kill(-proc.pid, signal);
- } catch {
- try {
- proc.kill(signal);
- } catch {
- // already exited
- }
- }
- }
-
- /**
- * Cancel an ongoing session: SIGINT the CC tree, escalate to SIGKILL after
- * 2s if the CLI hasn't exited (some tool calls swallow SIGINT). The
- * `exit` handler on the spawned proc broadcasts completion and clears
- * `session.process`, so the escalation is a no-op when the graceful path
- * already landed.
- */
@IpcMethod()
- async cancelSession(params: CancelSessionParams): Promise<void> {
- const session = this.sessions.get(params.sessionId);
- if (!session) return;
-
- session.cancelledByUs = true;
- if (session.sdkSession) {
- session.sdkSession.close();
- return;
- }
-
- if (!session.process || session.process.killed) return;
- const proc = session.process;
- this.killProcessTree(proc, 'SIGINT');
-
- setTimeout(() => {
- if (session.process === proc && !proc.killed) {
- logger.warn('Session did not exit after SIGINT, escalating to SIGKILL:', params.sessionId);
- this.killProcessTree(proc, 'SIGKILL');
- }
- }, 2000);
+ async cancelSession(...args: Parameters<Implementation['cancelSession']>) {
+ return (await this.getImplementation()).cancelSession(...args);
}
- /**
- * Stop and clean up a session.
- */
@IpcMethod()
- async stopSession(params: StopSessionParams): Promise<void> {
- const session = this.sessions.get(params.sessionId);
- if (!session) return;
-
- if (session.sdkSession) {
- session.cancelledByUs = true;
- session.sdkSession.close();
- }
-
- if (session.process && !session.process.killed) {
- session.cancelledByUs = true;
- const proc = session.process;
- this.killProcessTree(proc, 'SIGTERM');
- setTimeout(() => {
- if (session.process === proc && !proc.killed) {
- this.killProcessTree(proc, 'SIGKILL');
- }
- }, 3000);
- }
-
- this.sessions.delete(params.sessionId);
+ async stopSession(...args: Parameters<Implementation['stopSession']>) {
+ return (await this.getImplementation()).stopSession(...args);
}
@IpcMethod()
- async respondPermission(): Promise<void> {
- // No-op for CLI mode (permissions handled by --permission-mode flag)
+ async respondPermission(...args: Parameters<Implementation['respondPermission']>) {
+ return (await this.getImplementation()).respondPermission(...args);
}
- /**
- * Renderer → main: deliver the user's answer to a pending CC AskUserQuestion
- * (or signal cancellation). The matching bridge resolves its blocked
- * `pending()` Promise, the local MCP handler returns to CC, and CC's
- * `tool_result` flows back through the normal stream pipeline.
- *
- * Idempotent — late submissions for already-resolved tool calls are no-ops.
- * No-op when called for an unknown opId; the bridge may have been cleaned
- * up already (op finished / cancelled).
- */
@IpcMethod()
- async submitIntervention(params: SubmitInterventionParams): Promise<void> {
- const slot = this.opIdToIntervention.get(params.operationId);
- if (!slot) {
- logger.warn('submitIntervention: no active intervention for operationId', params.operationId);
- return;
- }
- slot.bridge.resolve(params.toolCallId, {
- cancelReason: params.cancelled ? (params.cancelReason ?? 'user_cancelled') : undefined,
- cancelled: params.cancelled,
- result: params.result,
- });
- }
-
- /**
- * Synchronously unlink every pending intervention's temp `mcp.json`. The
- * async exit-handler cleanup loses to Electron's main-process teardown
- * often enough that we'd leak `lobe-cc-mcp-<opId>.json` files into
- * `os.tmpdir()` on real shutdowns; sync unlink here is the only reliable
- * guarantee. Safe to call multiple times.
- */
- private unlinkPendingInterventionConfigsSync = (): void => {
- for (const [, intervention] of this.opIdToIntervention) {
- try {
- unlinkSync(intervention.tmpConfigPath);
- } catch {
- /* file may already be gone — fine */
- }
- }
- };
-
- /**
- * Cleanup on app quit. `before-quit` covers the user-driven Cmd+Q /
- * `app.quit()` path; SIGTERM / SIGINT cover external kills (test
- * harnesses, OS shutdown) where Electron's lifecycle events never fire.
- */
- afterAppReady() {
- electronApp.on('before-quit', () => {
- this.unlinkPendingInterventionConfigsSync();
- for (const [, session] of this.sessions) {
- if (session.sdkSession) {
- session.cancelledByUs = true;
- session.sdkSession.close();
- }
- if (session.process && !session.process.killed) {
- session.cancelledByUs = true;
- this.killProcessTree(session.process, 'SIGTERM');
- }
- }
- this.sessions.clear();
- // The exit handlers will tear each per-op intervention down, but if
- // CC's stdio close races shutdown we'd leave the MCP server bound to
- // a port. Stopping it here cancels every still-pending bridge with
- // `session_ended` and closes the listener.
- void this.builtinMcpServer?.stop().catch((err) => {
- logger.warn('AskUserQuestion MCP server stop error:', err);
- });
- });
-
- const onSignal = (signal: NodeJS.Signals) => {
- this.unlinkPendingInterventionConfigsSync();
- // Defer to Electron's normal quit flow so the rest of the app gets a
- // chance to tear down. The `before-quit` handler above is idempotent.
- try {
- electronApp.quit();
- } catch {
- /* during late shutdown app.quit may throw — fine */
- }
- // Last-resort exit if Electron is wedged and won't quit on its own.
- setTimeout(() => process.exit(signal === 'SIGINT' ? 130 : 143), 1000).unref();
- };
- process.on('SIGTERM', onSignal);
- process.on('SIGINT', onSignal);
+ async submitIntervention(...args: Parameters<Implementation['submitIntervention']>) {
+ return (await this.getImplementation()).submitIntervention(...args);
}
- /**
- * Spawn the embedded CLI's `hetero exec` for gateway-driven agent runs.
- * The bundled CLI handles everything downstream — no local
- * AgentStreamPipeline or IPC broadcast needed. Mirrors
- * `spawnHeteroSandbox()` on the server side.
- *
- * Resolves only after the child either starts or fails to start. Node reports
- * failures such as an inaccessible cwd asynchronously through `error`, so an
- * eager accepted ack would strand the server operation without a producer.
- */
- spawnLhHeteroExec(params: {
- agentType: string;
- /** Resolved `lh hetero exec` wrapper args. */
- args?: string[];
- cwd?: string;
- /** Image attachments (signed URLs) appended as image content blocks. */
- imageList?: HeteroExecImageRef[];
- jwt: string;
- operationId: string;
- prompt: string;
- resumeSessionId?: string;
- serverUrl: string;
- systemContext?: string;
- topicId: string;
- }): Promise<{ reason?: string; status: 'accepted' | 'rejected' }> {
- const {
- agentType,
- args: extraArgs,
- cwd,
- imageList,
- jwt,
- operationId,
- prompt,
- resumeSessionId,
- serverUrl,
- systemContext,
- topicId,
- } = params;
- const workDir = cwd ?? process.cwd();
-
- // When CLI tracing is enabled (dev builds, or the Help-menu toggle in
- // packaged builds), have `lh hetero exec` persist the agent process's RAW
- // stream-json (pre-adapter) on this device. The remote-device path
- // otherwise leaves no local record — the CLI consumes stdout internally and
- // only POSTs adapted events to the server — so without this there's nothing
- // to inspect when a remote run misbehaves.
- const rawDumpDir = this.shouldTraceCliOutput ? this.resolveTraceRootDir(workDir) : undefined;
-
- const args = [
- 'hetero',
- 'exec',
- '--type',
- agentType,
- '--operation-id',
- operationId,
- '--topic',
- topicId,
- '--render',
- 'none',
- '--input-json',
- '-',
- '--cwd',
- workDir,
- ...(resumeSessionId ? ['--resume', resumeSessionId] : []),
- ...(rawDumpDir ? ['--raw-dump', rawDumpDir] : []),
- ...(extraArgs ?? []),
- ];
-
- const stdinPayload = buildHeteroExecStdinPayload({ imageList, prompt, systemContext });
- const cliScript = resolveCliScript();
- if (!existsSync(cliScript)) {
- return Promise.resolve({
- reason: `Embedded CLI not found at ${cliScript}`,
- status: 'rejected',
- });
- }
-
- const env = {
- ...process.env,
- ...buildProxyEnv(this.app.storeManager.get('networkProxy')),
- ELECTRON_RUN_AS_NODE: '1',
- LOBEHUB_JWT: jwt,
- LOBEHUB_SERVER: serverUrl,
- };
-
- logger.info('spawnLhHeteroExec: type=%s op=%s topic=%s', agentType, operationId, topicId);
-
- // Execute the CLI shipped with this desktop build. A bare `lh` would prefer
- // an older global install earlier on PATH, letting model discovery report a
- // capability that the actual execution runtime does not support.
- const child = spawn(process.execPath, [cliScript, ...args], {
- cwd: workDir,
- env,
- stdio: ['pipe', 'inherit', 'inherit'],
- });
-
- child.on('exit', (code, signal) => {
- logger.info('spawnLhHeteroExec: exited — op=%s code=%s signal=%s', operationId, code, signal);
- });
-
- return new Promise((resolve) => {
- let settled = false;
- const settle = (result: { reason?: string; status: 'accepted' | 'rejected' }) => {
- if (settled) return;
- settled = true;
- resolve(result);
- };
-
- child.stdin.once('error', (err) => {
- logger.error(
- 'spawnLhHeteroExec: stdin write failed — op=%s error=%s',
- operationId,
- err.message,
- );
- settle({ reason: err.message, status: 'rejected' });
- });
-
- child.once('spawn', () => {
- try {
- child.stdin.write(stdinPayload);
- child.stdin.end();
- settle({ status: 'accepted' });
- } catch (err) {
- const reason = err instanceof Error ? err.message : String(err);
- logger.error(
- 'spawnLhHeteroExec: stdin write threw — op=%s error=%s',
- operationId,
- reason,
- );
- settle({ reason, status: 'rejected' });
- }
- });
-
- child.once('error', (err) => {
- logger.error('spawnLhHeteroExec: spawn failed — %s', err.message);
- settle({ reason: err.message, status: 'rejected' });
- });
- });
+ spawnLhHeteroExec(...args: Parameters<Implementation['spawnLhHeteroExec']>) {
+ return this.getImplementation().then((implementation) =>
+ implementation.spawnLhHeteroExec(...args),
+ );
}
}
diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
new file mode 100644
index 00000000000..6708ac854c0
--- /dev/null
+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts
@@ -0,0 +1,2090 @@
+import type { ChildProcess } from 'node:child_process';
+import { spawn } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { existsSync, unlinkSync } from 'node:fs';
+import { access, appendFile, mkdir, unlink, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import type { Readable, Writable } from 'node:stream';
+import { finished as streamFinished } from 'node:stream/promises';
+
+import type {
+ ClaudeCodeQuotaSnapshot,
+ CodexQuotaSnapshot,
+ CodexRateLimitResetResult,
+ HeterogeneousAgentSessionError,
+ HeterogeneousCliAgentType,
+} from '@lobechat/electron-client-ipc';
+import {
+ AMP_CLI_INSTALL_COMMANDS,
+ AMP_CLI_INSTALL_DOCS_URL,
+ CLAUDE_CODE_CLI_INSTALL_COMMANDS,
+ CLAUDE_CODE_CLI_INSTALL_DOCS_URL,
+ CODEX_CLI_INSTALL_COMMANDS,
+ CODEX_CLI_INSTALL_DOCS_URL,
+ HeterogeneousAgentSessionErrorCode,
+ OPENCODE_CLI_INSTALL_COMMANDS,
+ OPENCODE_CLI_INSTALL_DOCS_URL,
+} from '@lobechat/electron-client-ipc/types/heterogeneous-agent';
+import type { AskUserBridge } from '@lobechat/heterogeneous-agents/askUser';
+import type {
+ LobeBuiltinMcpServer,
+ McpToolResult,
+} from '@lobechat/heterogeneous-agents/builtinMcp';
+import { listHeterogeneousAgentModels } from '@lobechat/heterogeneous-agents/models';
+import type { HeteroExecImageRef } from '@lobechat/heterogeneous-agents/protocol';
+import {
+ buildHeteroExecStdinPayload,
+ buildHeterogeneousPrompt,
+} from '@lobechat/heterogeneous-agents/protocol';
+import {
+ CLAUDE_CODE_QUOTA_FRESH_MS,
+ createQuotaCacheKey,
+ fetchClaudeCodeQuota,
+ QuotaSnapshotCache,
+ readClaudeCodeIdentity,
+} from '@lobechat/heterogeneous-agents/quota-sampler';
+import type { AgentStreamEvent, UsageData } from '@lobechat/heterogeneous-agents/spawn';
+import {
+ AgentStreamPipeline,
+ buildAgentInput,
+ ClaudeAgentSdkSession,
+ createFileStoreImageUploader,
+ ensureClaudeCodeResumeTranscript,
+ readCodexSessionModel,
+ resolveCliSpawnPlan,
+ resolveCodexInitialModel,
+} from '@lobechat/heterogeneous-agents/spawn';
+import type {
+ HeterogeneousAgentModelCatalog,
+ HeteroSessionImportMessage,
+ ListHeterogeneousAgentModelsParams,
+} from '@lobechat/types';
+import { app as electronApp, BrowserWindow } from 'electron';
+
+import { HETERO_AGENT_FILES_DIR, HETERO_AGENT_TRACING_DIR } from '@/const/heteroAgent';
+import type { App } from '@/core/App';
+import { detectHeterogeneousCliCommand } from '@/modules/binaries';
+import { resolveCliScript } from '@/modules/cliEmbedding';
+import { getHeterogeneousAgentDriver } from '@/modules/heterogeneousAgent';
+import {
+ consumeCodexRateLimitResetCredit as consumeCodexRateLimitResetCreditRequest,
+ fetchCodexQuota,
+} from '@/modules/heterogeneousAgent/codexQuota';
+import { createLambdaFileStorePort } from '@/modules/heterogeneousAgent/fileStorePort';
+import type {
+ HeterogeneousAgentBuildPlan,
+ HeterogeneousAgentImageAttachment,
+} from '@/modules/heterogeneousAgent/types';
+import { buildProxyEnv } from '@/modules/networkProxy/envBuilder';
+import { createLogger } from '@/utils/logger';
+
+import BrowserControlCtr from './BrowserControlCtr';
+import RemoteServerConfigCtr from './RemoteServerConfigCtr';
+
+const logger = createLogger('controllers:HeterogeneousAgentCtr');
+
+// Anthropic auth env vars that must NOT be inherited from the desktop process
+// when spawning a local CLI agent. A developer with `ANTHROPIC_API_KEY` (or an
+// auth token / base url) exported in their shell would otherwise have it
+// forwarded to `claude`, which then switches from its own subscription login to
+// that key — an expired / wrong key surfaces as a baffling "Invalid API key"
+// and the run exits non-zero. Agents that genuinely want an API key still set
+// it through `session.env`, which is spread AFTER the inherited env below and
+// therefore wins.
+const STRIPPED_INHERITED_ENV_KEYS = [
+ 'ANTHROPIC_API_KEY',
+ 'ANTHROPIC_AUTH_TOKEN',
+ 'ANTHROPIC_BASE_URL',
+] as const;
+
+/**
+ * Inherited `process.env` with the Anthropic auth vars removed. Keep this pure
+ * and exported so the "never leak host Anthropic creds into the CLI" invariant
+ * can be unit-tested directly.
+ */
+export const buildInheritedSpawnEnv = (
+ sourceEnv: NodeJS.ProcessEnv = process.env,
+): NodeJS.ProcessEnv => {
+ const env = { ...sourceEnv };
+ for (const key of STRIPPED_INHERITED_ENV_KEYS) delete env[key];
+ return env;
+};
+const CODEX_RESUME_THREAD_NOT_FOUND_PATTERNS = [
+ /no conversation found/i,
+ /thread .*not found/i,
+ /conversation .*not found/i,
+ /resume.*not found/i,
+] as const;
+const CLI_AUTH_REQUIRED_PATTERNS = [
+ /failed to authenticate/i,
+ /invalid authentication credentials/i,
+ /authentication[_ ]error/i,
+ /not authenticated/i,
+ /\bunauthorized\b/i,
+ /\b401\b/,
+] as const;
+const AMP_AUTH_REQUIRED_PATTERNS = [/please (?:log|sign) in/i, /amp_api_key/i] as const;
+const CODEX_RESUME_CWD_MISMATCH_PATTERNS = [
+ /working directory/i,
+ /\bcwd\b/i,
+ /different directory/i,
+ /directory.*mismatch/i,
+] as const;
+
+/** Directory under appStoragePath for caching downloaded files */
+const FILE_CACHE_DIR = HETERO_AGENT_FILES_DIR;
+const CLI_TRACE_DIR = '.heerogeneous-tracing';
+const CODEX_STDERR_STATUS_LINE = 'Reading prompt from stdin...';
+const CODEX_WARN_LOG_PATTERN = /^\d{4}-\d{2}-\d{2}T\S+\s+WARN\s+/;
+const CODEX_LOG_PATTERN = /^\d{4}-\d{2}-\d{2}T\S+\s+(?:DEBUG|ERROR|INFO|TRACE|WARN)\s+/;
+const CLI_ERROR_LINE_PATTERN = /^(?:error:|Error:|Usage:)/;
+const HETERO_SESSION_COMPLETE_GRACE_MS = 1_000;
+const CLAUDE_CODE_SDK_LAB_ENABLED_VALUES = new Set(['1', 'true', 'yes', 'on']);
+
+const waitForHeteroSessionCompleteGrace = () =>
+ new Promise<void>((resolve) => setTimeout(resolve, HETERO_SESSION_COMPLETE_GRACE_MS));
+
+// ─── IPC types ───
+
+interface StartSessionParams {
+ /** Agent type key (e.g., 'claude-code'). Defaults to 'claude-code'. */
+ agentType?: HeterogeneousCliAgentType;
+ /** Additional CLI arguments */
+ args?: string[];
+ /** Command to execute */
+ command: string;
+ /** Working directory */
+ cwd?: string;
+ /** Environment variables */
+ env?: Record<string, string>;
+ /** Session ID to resume (for multi-turn) */
+ resumeSessionId?: string;
+ /** Run claude-code prompts through the Claude Agent SDK instead of CLI spawn (lab preference) */
+ useClaudeCodeSdk?: boolean;
+}
+
+export interface StartSessionResult {
+ sessionId: string;
+}
+
+/** Run identity the browser MCP tools need to reach the right in-app page. */
+interface BrowserRunBinding {
+ agentId?: string;
+ topicId?: string;
+}
+
+interface SendPromptParams {
+ /**
+ * Agent this run belongs to. Rides along to the renderer so it can tell
+ * whether revealing the browser panel would yank the user's view to a run
+ * they aren't watching.
+ */
+ agentId?: string;
+ /** Image attachments to include in the prompt (downloaded from url, cached by id) */
+ imageList?: HeterogeneousAgentImageAttachment[];
+ /**
+ * Renderer-side operation id stamped onto every emitted `AgentStreamEvent`.
+ * Required: producer-side conversion is the V3 contract — by the time events
+ * reach the renderer they must already carry the operation they belong to.
+ */
+ operationId: string;
+ prompt: string;
+ /**
+ * Prior conversation turns used to rebuild a Claude Code transcript that the
+ * CLI garbage-collected (`cleanupPeriodDays`, default 30 days). Only consumed
+ * when resuming and the on-disk transcript is missing — see
+ * `ensureClaudeCodeResumeTranscript`. Without it, `--resume <staleId>` fails
+ * with "No conversation found with session ID".
+ */
+ resumeReplayMessages?: HeteroSessionImportMessage[];
+ sessionId: string;
+ /** Extra context injected before the user prompt without mutating the prompt text. */
+ systemContext?: string;
+ /**
+ * Topic this run belongs to. Binds the op to its in-app browser session
+ * (`topic:<topicId>`) so the browser MCP tools act on the right page.
+ *
+ * Not to be confused with `sessionId`, which is the CC/Codex agent session —
+ * a different namespace entirely.
+ */
+ topicId?: string;
+}
+
+interface CancelSessionParams {
+ sessionId: string;
+}
+
+interface SubmitInterventionParams {
+ cancelled?: boolean;
+ /** When set, signals user-cancelled or timeout — the bridge resolves with isError. */
+ cancelReason?: 'timeout' | 'user_cancelled';
+ /** Operation id stamped on the request the renderer is responding to. */
+ operationId: string;
+ /** Structured user answer; ignored when `cancelled` is true. */
+ result?: unknown;
+ /** Correlation key carried on the original `agent_intervention_request`. */
+ toolCallId: string;
+}
+
+interface StopSessionParams {
+ sessionId: string;
+}
+
+interface GetSessionInfoParams {
+ sessionId: string;
+}
+
+interface GetCodexQuotaParams {
+ command?: string;
+ env?: Record<string, string>;
+ force?: boolean;
+}
+
+interface ConsumeCodexRateLimitResetCreditParams {
+ command?: string;
+ creditId?: string;
+ env?: Record<string, string>;
+ idempotencyKey: string;
+}
+
+interface GetClaudeCodeQuotaParams {
+ env?: Record<string, string>;
+ force?: boolean;
+}
+
+export interface SessionInfo {
+ agentSessionId?: string;
+}
+
+// ─── Internal session tracking ───
+
+interface AgentSession {
+ agentSessionId?: string;
+ agentType: HeterogeneousCliAgentType;
+ args: string[];
+ /**
+ * True when *we* initiated the kill (cancelSession / stopSession / before-quit).
+ * The `exit` handler uses this to route signal-induced non-zero exits through
+ * the `complete` broadcast instead of surfacing them as runtime errors —
+ * SIGINT(130) / SIGTERM(143) / SIGKILL(137) from our own kill paths are
+ * intentional, not agent failures.
+ */
+ cancelledByUs?: boolean;
+ command: string;
+ cwd?: string;
+ env?: Record<string, string>;
+ model?: string;
+ modelSource?: string;
+ modelVerificationLastAttemptAt?: number;
+ modelVerificationLastAttemptSessionId?: string;
+ process?: ChildProcess;
+ /**
+ * Absolute CLI path resolved by spawn preflight detection. Used for spawn()
+ * when the configured command is bare: detection can find the CLI through
+ * the login-shell PATH or a well-known install location (e.g. an app-bundled
+ * Codex CLI) that plain spawn() with the inherited env can't resolve.
+ */
+ resolvedCommandPath?: string;
+ /**
+ * PATH the preflight detector used to resolve `resolvedCommandPath`, set only
+ * when it fell back to the login-shell PATH. Merged into the child PATH at
+ * spawn so a `#!/usr/bin/env node` shim still finds its interpreter — the
+ * shim resolving in preflight doesn't guarantee `node` is on the leaner
+ * inherited PATH (Finder-launched Electron).
+ */
+ resolvedCommandSearchPath?: string;
+ resumeSessionId?: string;
+ sdkSession?: ClaudeAgentSdkSession;
+ sessionId: string;
+ useClaudeCodeSdk?: boolean;
+ verifiedModel?: string;
+ verifiedModelContextWindow?: number;
+ verifiedModelProvider?: string;
+ verifiedModelSessionId?: string;
+ verifiedModelSourceFile?: string;
+}
+
+type SessionErrorPayload = HeterogeneousAgentSessionError | string;
+
+interface CliTraceSession {
+ dir: string;
+ writeQueue: Promise<void>;
+}
+
+/**
+ * External Agent Controller — manages external agent CLI processes via Electron IPC.
+ *
+ * Agent-agnostic: delegates spawn-plan construction and stdout framing to a
+ * per-agent driver so Claude Code, Codex, and future CLIs can differ in
+ * prompt transport, resume semantics, and raw stream shape without turning
+ * this controller into a giant `switch`.
+ *
+ * Lifecycle: startSession → sendPrompt → (heteroAgentEvent broadcasts) → stopSession
+ */
+interface InterventionSlot {
+ bridge: AskUserBridge;
+ /** Resolves once bridge.events() iterator ends (after `cancelAll`). */
+ pumpDone?: Promise<void>;
+ /** Path to the per-op temp `mcp.json` we wrote for `--mcp-config`. */
+ tmpConfigPath: string;
+}
+
+export default class HeterogeneousAgentCtr {
+ constructor(public app: App) {}
+
+ private sessions = new Map<string, AgentSession>();
+ /**
+ * Per-operation AskUserQuestion bridge state. Keyed by `operationId` so the
+ * `submitIntervention` IPC can route an answer to the right pending MCP
+ * handler regardless of which `sessionId` it belongs to (one session can
+ * fire many ops over its lifetime).
+ */
+ private opIdToIntervention = new Map<string, InterventionSlot>();
+ /**
+ * Op → run identity for browser MCP tool session resolution. The main process
+ * otherwise has no idea which topic an operation belongs to, and the browser
+ * session is keyed by topic (`topic:<topicId>`).
+ */
+ private opIdToBrowserBinding = new Map<string, BrowserRunBinding>();
+ /** Lazy single MCP server, started on first claude-code prompt. */
+ private builtinMcpServer?: LobeBuiltinMcpServer;
+ private builtinMcpStartPromise?: Promise<LobeBuiltinMcpServer>;
+ // Fresh window sits under the renderer's 2-minute auto-refresh so each
+ // scheduled poll reaches the usage API instead of a cache echo.
+ private readonly claudeCodeQuotaCache = new QuotaSnapshotCache<ClaudeCodeQuotaSnapshot>({
+ freshMs: CLAUDE_CODE_QUOTA_FRESH_MS,
+ });
+ private readonly codexQuotaCache = new QuotaSnapshotCache<CodexQuotaSnapshot>();
+
+ private get remoteServerConfigCtr() {
+ return this.app.getController(RemoteServerConfigCtr);
+ }
+
+ /**
+ * Uploads a base64 tool_result image (CC `Read` on an image file) to the file
+ * store, so the persisted event carries a `{ fileId, url }` reference instead
+ * of heavy base64. Mirrors what `lh hetero exec` does for the gateway path.
+ */
+ private uploadResultImage = createFileStoreImageUploader(() =>
+ createLambdaFileStorePort({
+ getAccessToken: () => this.remoteServerConfigCtr.getAccessToken(),
+ getServerUrl: async () => (await this.remoteServerConfigCtr.getRemoteServerUrl()) ?? null,
+ }),
+ );
+
+ private resolveSessionCommand(session: AgentSession): string {
+ const resolvedCommand = session.command.trim();
+ if (resolvedCommand) return resolvedCommand;
+
+ switch (session.agentType) {
+ case 'amp': {
+ return 'amp';
+ }
+ case 'codex': {
+ return 'codex';
+ }
+ case 'opencode': {
+ return 'opencode';
+ }
+ default: {
+ return 'claude';
+ }
+ }
+ }
+
+ private buildAmpCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {
+ const command = this.resolveSessionCommand(session);
+
+ return {
+ agentType: 'amp',
+ code: HeterogeneousAgentSessionErrorCode.CliNotFound,
+ command,
+ docsUrl: AMP_CLI_INSTALL_DOCS_URL,
+ installCommands: AMP_CLI_INSTALL_COMMANDS,
+ message: `Amp CLI was not found. Install it and make sure \`${command}\` can be executed.`,
+ };
+ }
+
+ private buildCodexCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {
+ const command = this.resolveSessionCommand(session);
+
+ return {
+ agentType: 'codex',
+ code: HeterogeneousAgentSessionErrorCode.CliNotFound,
+ command,
+ docsUrl: CODEX_CLI_INSTALL_DOCS_URL,
+ installCommands: CODEX_CLI_INSTALL_COMMANDS,
+ message: `Codex CLI was not found. Install it and make sure \`${command}\` can be executed.`,
+ };
+ }
+
+ private buildClaudeCodeCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {
+ const command = this.resolveSessionCommand(session);
+
+ return {
+ agentType: 'claude-code',
+ code: HeterogeneousAgentSessionErrorCode.CliNotFound,
+ command,
+ docsUrl: CLAUDE_CODE_CLI_INSTALL_DOCS_URL,
+ installCommands: CLAUDE_CODE_CLI_INSTALL_COMMANDS,
+ message: `Claude Code CLI was not found. Install it and make sure \`${command}\` can be executed.`,
+ };
+ }
+
+ private buildOpenCodeCliMissingError(session: AgentSession): HeterogeneousAgentSessionError {
+ const command = this.resolveSessionCommand(session);
+
+ return {
+ agentType: 'opencode',
+ code: HeterogeneousAgentSessionErrorCode.CliNotFound,
+ command,
+ docsUrl: OPENCODE_CLI_INSTALL_DOCS_URL,
+ installCommands: OPENCODE_CLI_INSTALL_COMMANDS,
+ message: `OpenCode CLI was not found. Install it and make sure \`${command}\` can be executed.`,
+ };
+ }
+
+ private buildCliMissingError(session: AgentSession): HeterogeneousAgentSessionError | undefined {
+ switch (session.agentType) {
+ case 'amp': {
+ return this.buildAmpCliMissingError(session);
+ }
+ case 'claude-code': {
+ return this.buildClaudeCodeCliMissingError(session);
+ }
+ case 'codex': {
+ return this.buildCodexCliMissingError(session);
+ }
+ case 'opencode': {
+ return this.buildOpenCodeCliMissingError(session);
+ }
+ default: {
+ return;
+ }
+ }
+ }
+
+ private buildCliAuthRequiredError(
+ session: AgentSession,
+ stderr: string,
+ ): HeterogeneousAgentSessionError | undefined {
+ const command = this.resolveSessionCommand(session);
+
+ switch (session.agentType) {
+ case 'amp': {
+ return {
+ agentType: 'amp',
+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,
+ command,
+ docsUrl: AMP_CLI_INSTALL_DOCS_URL,
+ message:
+ 'Amp could not authenticate. Run `amp login` or configure AMP_API_KEY, then retry.',
+ stderr,
+ };
+ }
+ case 'claude-code': {
+ return {
+ agentType: 'claude-code',
+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,
+ command,
+ docsUrl: CLAUDE_CODE_CLI_INSTALL_DOCS_URL,
+ message:
+ 'Claude Code could not authenticate. Sign in again or refresh its credentials, then retry.',
+ stderr,
+ };
+ }
+ case 'codex': {
+ return {
+ agentType: 'codex',
+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,
+ command,
+ docsUrl: CODEX_CLI_INSTALL_DOCS_URL,
+ message:
+ 'Codex could not authenticate. Sign in again or refresh its credentials, then retry.',
+ stderr,
+ };
+ }
+ case 'opencode': {
+ return {
+ agentType: 'opencode',
+ code: HeterogeneousAgentSessionErrorCode.AuthRequired,
+ command,
+ docsUrl: OPENCODE_CLI_INSTALL_DOCS_URL,
+ message:
+ 'OpenCode could not authenticate. Sign in again or refresh its credentials, then retry.',
+ stderr,
+ };
+ }
+ default: {
+ return;
+ }
+ }
+ }
+
+ private getErrorMessage(error: unknown): string | undefined {
+ return typeof error === 'string'
+ ? error
+ : error instanceof Error
+ ? error.message
+ : typeof error === 'object' &&
+ error &&
+ 'message' in error &&
+ typeof error.message === 'string'
+ ? error.message
+ : undefined;
+ }
+
+ private buildCodexResumeError(
+ code:
+ | typeof HeterogeneousAgentSessionErrorCode.ResumeCwdMismatch
+ | typeof HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,
+ stderr: string,
+ session: AgentSession,
+ ): HeterogeneousAgentSessionError {
+ const message =
+ code === HeterogeneousAgentSessionErrorCode.ResumeCwdMismatch
+ ? 'The saved Codex thread can only be resumed from its original working directory.'
+ : 'The saved Codex thread could not be found, so it can no longer be resumed.';
+
+ return {
+ agentType: 'codex',
+ code,
+ command: session.command,
+ message,
+ resumeSessionId: session.resumeSessionId,
+ stderr,
+ workingDirectory: session.cwd,
+ };
+ }
+
+ private getCodexResumeError(
+ error: unknown,
+ session: AgentSession,
+ ): HeterogeneousAgentSessionError | undefined {
+ if (session.agentType !== 'codex' || !session.resumeSessionId) return;
+
+ const message = this.getErrorMessage(error);
+
+ if (!message) return;
+
+ if (CODEX_RESUME_CWD_MISMATCH_PATTERNS.some((pattern) => pattern.test(message))) {
+ return this.buildCodexResumeError(
+ HeterogeneousAgentSessionErrorCode.ResumeCwdMismatch,
+ message,
+ session,
+ );
+ }
+
+ if (CODEX_RESUME_THREAD_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(message))) {
+ return this.buildCodexResumeError(
+ HeterogeneousAgentSessionErrorCode.ResumeThreadNotFound,
+ message,
+ session,
+ );
+ }
+ }
+
+ private getCliAuthRequiredError(
+ error: unknown,
+ session: AgentSession,
+ ): HeterogeneousAgentSessionError | undefined {
+ const message = this.getErrorMessage(error);
+
+ if (!message) return;
+ const patterns =
+ session.agentType === 'amp'
+ ? [...CLI_AUTH_REQUIRED_PATTERNS, ...AMP_AUTH_REQUIRED_PATTERNS]
+ : CLI_AUTH_REQUIRED_PATTERNS;
+ if (!patterns.some((pattern) => pattern.test(message))) return;
+
+ return this.buildCliAuthRequiredError(session, message);
+ }
+
+ private getSessionErrorPayload(error: unknown, session: AgentSession): SessionErrorPayload {
+ if (typeof error === 'object' && error && 'code' in error && error.code === 'ENOENT') {
+ const cliMissingError = this.buildCliMissingError(session);
+ if (cliMissingError) return cliMissingError;
+ }
+
+ const resumeError = this.getCodexResumeError(error, session);
+ if (resumeError) return resumeError;
+
+ const authRequiredError = this.getCliAuthRequiredError(error, session);
+ if (authRequiredError) return authRequiredError;
+
+ return error instanceof Error ? error.message : String(error);
+ }
+
+ private getRelevantCodexStderr(stderr: string): string {
+ const keptLines: string[] = [];
+ let droppingWarnBlock = false;
+
+ for (const line of stderr.split(/\r?\n/)) {
+ const trimmed = line.trim();
+ if (!trimmed || trimmed === CODEX_STDERR_STATUS_LINE) {
+ continue;
+ }
+
+ if (CODEX_WARN_LOG_PATTERN.test(trimmed)) {
+ droppingWarnBlock = true;
+ continue;
+ }
+
+ if (CODEX_LOG_PATTERN.test(trimmed)) {
+ droppingWarnBlock = false;
+ keptLines.push(line);
+ continue;
+ }
+
+ if (droppingWarnBlock && !CLI_ERROR_LINE_PATTERN.test(trimmed)) {
+ continue;
+ }
+
+ droppingWarnBlock = false;
+ keptLines.push(line);
+ }
+
+ return keptLines.join('\n').trim();
+ }
+
+ private getExitErrorMessage(
+ code: number | null,
+ session: AgentSession,
+ stderrOutput: string,
+ ): string {
+ const relevantStderr =
+ session.agentType === 'codex' ? this.getRelevantCodexStderr(stderrOutput) : stderrOutput;
+
+ return relevantStderr || `Agent exited with code ${code}`;
+ }
+
+ private async getSpawnPreflightError(
+ session: AgentSession,
+ ): Promise<HeterogeneousAgentSessionError | undefined> {
+ const defaultCommand =
+ session.agentType === 'amp'
+ ? 'amp'
+ : session.agentType === 'claude-code'
+ ? 'claude'
+ : session.agentType === 'codex'
+ ? 'codex'
+ : session.agentType === 'opencode'
+ ? 'opencode'
+ : undefined;
+ if (!defaultCommand) return;
+
+ const command = this.resolveSessionCommand(session);
+ const status =
+ command === defaultCommand
+ ? await this.app.binaryManager?.detect?.(defaultCommand, true)
+ : await detectHeterogeneousCliCommand(session.agentType, command);
+
+ if (!status || status.available) {
+ // Spawn through the detector-resolved absolute path when the configured
+ // command is bare — detection may have located the CLI somewhere plain
+ // spawn() can't (login-shell PATH, app-bundled Codex CLI, …).
+ const useResolvedPath = Boolean(status?.path) && !command.includes(path.sep);
+ session.resolvedCommandPath = useResolvedPath ? status!.path : undefined;
+ // Carry the login-shell PATH the detector resolved through, so a
+ // `#!/usr/bin/env node` shim spawned by absolute path still finds `node`.
+ session.resolvedCommandSearchPath = useResolvedPath ? status!.resolvedPathEnv : undefined;
+ return;
+ }
+
+ return this.buildCliMissingError(session);
+ }
+
+ /**
+ * Global env override (`LOBE_CLAUDE_CODE_SDK`) for the SDK runtime; the
+ * per-user Labs toggle arrives per session as `session.useClaudeCodeSdk`.
+ */
+ private get isClaudeCodeSdkLabEnabled(): boolean {
+ return CLAUDE_CODE_SDK_LAB_ENABLED_VALUES.has(
+ String(process.env.LOBE_CLAUDE_CODE_SDK ?? '').toLowerCase(),
+ );
+ }
+
+ private buildSessionSpawnEnv(session: AgentSession): NodeJS.ProcessEnv {
+ // Forward the user's proxy settings to the CLI/SDK subprocess. The
+ // main-process undici dispatcher doesn't reach child processes — they need
+ // env vars.
+ const proxyEnv = buildProxyEnv(this.app.storeManager.get('networkProxy'));
+ const inheritedEnv = buildInheritedSpawnEnv();
+ // When preflight resolved the CLI via the login-shell PATH, spawn with
+ // that PATH (a superset of the inherited one) so a `#!/usr/bin/env node`
+ // shim finds its interpreter. `session.env` still wins if it sets PATH.
+ if (session.resolvedCommandSearchPath) inheritedEnv.PATH = session.resolvedCommandSearchPath;
+ return { ...inheritedEnv, ...proxyEnv, ...session.env };
+ }
+
+ private get shouldTraceCliOutput(): boolean {
+ if (process.env.NODE_ENV === 'test') return false;
+ // Dev builds always trace. Packaged builds trace only when the user has
+ // flipped the Help-menu developer toggle — so production issues can be
+ // captured on demand without polluting normal runs.
+ if (!electronApp.isPackaged) return true;
+ return this.app.storeManager.get('heteroTracingEnabled', false);
+ }
+
+ /**
+ * Root directory for CLI trace sessions.
+ *
+ * When the user has explicitly opted in via the `heteroTracingEnabled`
+ * Help-menu toggle, centralize traces under the app storage dir
+ * (`<appStoragePath>/heteroAgent/tracing`) — this is the only path packaged
+ * builds ever trace through, and it keeps traces out of the user's real
+ * project directory while staying reachable from one stable Help-menu entry.
+ *
+ * Otherwise (a plain dev run with the toggle off) keep writing into the
+ * working directory (`cwd/.heerogeneous-tracing`) — devs expect traces to
+ * show up alongside the repo they're running in.
+ */
+ private resolveTraceRootDir(cwd: string): string {
+ if (this.app.storeManager.get('heteroTracingEnabled', false)) {
+ return path.join(this.app.appStoragePath, HETERO_AGENT_TRACING_DIR);
+ }
+ return path.join(cwd, CLI_TRACE_DIR);
+ }
+
+ private formatTraceTimestamp(date: Date): string {
+ const pad = (value: number) => value.toString().padStart(2, '0');
+
+ return [
+ date.getFullYear(),
+ pad(date.getMonth() + 1),
+ pad(date.getDate()),
+ '-',
+ pad(date.getHours()),
+ pad(date.getMinutes()),
+ pad(date.getSeconds()),
+ ].join('');
+ }
+
+ private sanitizeTracePathSegment(value: string): string {
+ const sanitized = value
+ .replaceAll(path.sep, '-')
+ .replaceAll(/[^\w.-]+/g, '-')
+ .replaceAll(/^-+|-+$/g, '')
+ .slice(0, 80);
+
+ return sanitized || 'unknown';
+ }
+
+ private getAttachmentTraceSummary(image: HeterogeneousAgentImageAttachment) {
+ let urlKind = 'unknown';
+
+ try {
+ urlKind = new URL(image.url).protocol.replace(/:$/, '') || urlKind;
+ } catch {
+ urlKind = image.url.startsWith('data:') ? 'data' : 'unknown';
+ }
+
+ return {
+ id: image.id,
+ urlKind,
+ };
+ }
+
+ private async createCliTraceSession({
+ cliArgs,
+ cwd,
+ imageList,
+ session,
+ stdinPayload,
+ }: {
+ cliArgs: string[];
+ cwd: string;
+ imageList: HeterogeneousAgentImageAttachment[];
+ session: AgentSession;
+ stdinPayload?: string;
+ }): Promise<CliTraceSession | undefined> {
+ if (!this.shouldTraceCliOutput) return;
+
+ // Don't materialize the cwd via mkdir — if the caller passed a stale or
+ // typo'd path, we want spawn() to fail loudly instead of silently running
+ // the agent in an empty auto-created directory.
+ try {
+ await access(cwd);
+ } catch {
+ return;
+ }
+
+ const createdAt = new Date();
+ const rootDir = this.resolveTraceRootDir(cwd);
+ const agentDir = path.join(rootDir, this.sanitizeTracePathSegment(session.agentType));
+ const traceId = `${this.formatTraceTimestamp(createdAt)}-${this.sanitizeTracePathSegment(
+ session.sessionId,
+ )}`;
+ const dir = path.join(agentDir, traceId);
+
+ try {
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(rootDir, '.last-live-trace'), `${dir}\n`);
+ await writeFile(path.join(dir, 'stdout.jsonl'), '');
+ await writeFile(path.join(dir, 'stderr.log'), '');
+ if (stdinPayload !== undefined) {
+ await writeFile(path.join(dir, 'stdin.txt'), '');
+ }
+ await writeFile(
+ path.join(dir, 'meta.json'),
+ `${JSON.stringify(
+ {
+ agentSessionId: session.agentSessionId,
+ agentType: session.agentType,
+ args: cliArgs,
+ attachments: imageList.map((image) => this.getAttachmentTraceSummary(image)),
+ command: session.command,
+ createdAt: createdAt.toISOString(),
+ cwd,
+ envKeys: session.env ? Object.keys(session.env).sort() : [],
+ model: session.model,
+ modelSource: session.modelSource,
+ resumeSessionId: session.resumeSessionId,
+ sessionId: session.sessionId,
+ stdinBytes: stdinPayload === undefined ? 0 : Buffer.byteLength(stdinPayload),
+ stdinFile: stdinPayload === undefined ? undefined : 'stdin.txt',
+ stderrFile: 'stderr.log',
+ stdoutFile: 'stdout.jsonl',
+ verifiedModel: session.verifiedModel,
+ verifiedModelContextWindow: session.verifiedModelContextWindow,
+ verifiedModelProvider: session.verifiedModelProvider,
+ verifiedModelSessionId: session.verifiedModelSessionId,
+ verifiedModelSourceFile: session.verifiedModelSourceFile,
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+
+ return { dir, writeQueue: Promise.resolve() };
+ } catch (error) {
+ logger.warn('Failed to initialize CLI trace directory:', error);
+ }
+ }
+
+ private queueCliTraceWrite(
+ trace: CliTraceSession | undefined,
+ write: () => Promise<void>,
+ ): Promise<void> | undefined {
+ if (!trace) return;
+
+ trace.writeQueue = trace.writeQueue.then(write).catch((error) => {
+ logger.warn('Failed to write CLI trace file:', error);
+ });
+
+ return trace.writeQueue;
+ }
+
+ private appendCliTraceFile(
+ trace: CliTraceSession | undefined,
+ fileName: string,
+ data: Buffer | string,
+ ): Promise<void> | undefined {
+ if (!trace) return;
+
+ const filePath = path.join(trace.dir, fileName);
+
+ return this.queueCliTraceWrite(trace, () => appendFile(filePath, data));
+ }
+
+ private writeCliTraceFile(
+ trace: CliTraceSession | undefined,
+ fileName: string,
+ data: string,
+ ): Promise<void> | undefined {
+ if (!trace) return;
+
+ const filePath = path.join(trace.dir, fileName);
+
+ return this.queueCliTraceWrite(trace, () => writeFile(filePath, data));
+ }
+
+ private writeCliTraceJson(
+ trace: CliTraceSession | undefined,
+ fileName: string,
+ payload: unknown,
+ ): Promise<void> | undefined {
+ return this.writeCliTraceFile(trace, fileName, `${JSON.stringify(payload, null, 2)}\n`);
+ }
+
+ private async flushCliTrace(trace: CliTraceSession | undefined): Promise<void> {
+ await trace?.writeQueue;
+ }
+
+ // ─── Broadcast ───
+
+ private broadcast<T>(channel: string, data: T) {
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (!win.isDestroyed()) {
+ win.webContents.send(channel, data);
+ }
+ }
+ }
+
+ // ─── AskUserQuestion MCP server () ───
+
+ /**
+ * Lazy single-instance MCP server for CC's AskUserQuestion replacement.
+ * First claude-code prompt triggers `start()`; subsequent prompts reuse
+ * the same listener. Concurrent first-callers de-dupe via the in-flight
+ * promise so we don't bind two ports.
+ */
+ private async ensureBuiltinMcpServerStarted(): Promise<LobeBuiltinMcpServer> {
+ if (this.builtinMcpServer) return this.builtinMcpServer;
+ if (!this.builtinMcpStartPromise) {
+ this.builtinMcpStartPromise = (async () => {
+ const [{ LobeBuiltinMcpServer }, { buildBrowserMcpTools }] = await Promise.all([
+ import('@lobechat/heterogeneous-agents/builtinMcp'),
+ import('@/modules/heterogeneousAgent/browserMcpTools'),
+ ]);
+ const server = new LobeBuiltinMcpServer({
+ // In-app browser control tools ride the same per-op MCP server so
+ // CC can drive the browser sidebar ( M3, hetero path).
+ extraTools: buildBrowserMcpTools((operationId, apiName, args) =>
+ this.runBrowserMcpTool(operationId, apiName, args),
+ ),
+ });
+ await server.start();
+ this.builtinMcpServer = server;
+ logger.info('AskUserQuestion MCP server started:', server.url);
+ return server;
+ })().catch((err) => {
+ // Reset so a later sendPrompt can retry; surface the error.
+ this.builtinMcpStartPromise = undefined;
+ logger.error('Failed to start AskUserQuestion MCP server:', err);
+ throw err;
+ });
+ }
+ return this.builtinMcpStartPromise;
+ }
+
+ /**
+ * Register a per-op AskUserQuestion bridge, write its temp `mcp.json`,
+ * and stash it for the spawn path. The actual bridge event pump is started
+ * from `handleSpawnedAgentProcess`, where it can share the stdout broadcast
+ * queue instead of racing the adapter pipeline as a second producer.
+ */
+ private async setupInterventionForOp(
+ operationId: string,
+ browserBinding?: BrowserRunBinding,
+ ): Promise<{ bridge: AskUserBridge; cleanup: () => Promise<void>; tmpConfigPath: string }> {
+ const server = await this.ensureBuiltinMcpServerStarted();
+ const bridge = server.registerOperation(operationId);
+ if (browserBinding?.agentId || browserBinding?.topicId) {
+ this.opIdToBrowserBinding.set(operationId, browserBinding);
+ }
+ const tmpConfigPath = path.join(os.tmpdir(), `lobe-cc-mcp-${operationId}.json`);
+
+ // `alwaysLoad: true` is the undocumented CC flag that promotes our
+ // server's tool out of the deferred set so the model calls it directly
+ // (no ToolSearch hop). See spike notes — falls back to the
+ // 2-hop ToolSearch path if a future CC drops the flag, no breakage.
+ const config = {
+ mcpServers: {
+ lobe_cc: {
+ alwaysLoad: true,
+ type: 'http' as const,
+ url: server.urlForOperation(operationId),
+ },
+ },
+ };
+ await writeFile(tmpConfigPath, JSON.stringify(config), 'utf8');
+
+ const slot: InterventionSlot = { bridge, tmpConfigPath };
+ this.opIdToIntervention.set(operationId, slot);
+
+ const cleanup = async () => {
+ // Unregistering on the server cancels all bridge pendings AND closes
+ // the events iterator (cancelAll fires from within unregisterOperation).
+ this.builtinMcpServer?.unregisterOperation(operationId);
+ await slot.pumpDone;
+ this.opIdToIntervention.delete(operationId);
+ this.opIdToBrowserBinding.delete(operationId);
+ await unlink(tmpConfigPath).catch(() => {
+ /* file may already be gone if app crashed mid-prompt */
+ });
+ };
+
+ return { bridge, cleanup, tmpConfigPath };
+ }
+
+ /**
+ * Execute one in-app browser api call on behalf of a CC MCP tool. Forwards
+ * through `BrowserControlCtr.runGatewayToolCall` — the same funnel cloud
+ * gateway calls use — so the renderer-side `browserExecutor` (webview
+ * mount, snapshot refs, cursor overlay) stays the single source of truth.
+ */
+ private async runBrowserMcpTool(
+ operationId: string,
+ apiName: string,
+ args: Record<string, unknown>,
+ ): Promise<McpToolResult> {
+ const binding = this.opIdToBrowserBinding.get(operationId);
+ if (!binding?.agentId || !binding.topicId) {
+ return {
+ content: [
+ {
+ text: 'The in-app browser is not available for this run (no topic binding). Continue without it.',
+ type: 'text',
+ },
+ ],
+ isError: true,
+ };
+ }
+
+ const result = await this.app.getController(BrowserControlCtr).runGatewayToolCall(apiName, {
+ ...args,
+ __agentId: binding.agentId,
+ __topicId: binding.topicId,
+ });
+
+ const text =
+ result.content ?? result.error?.message ?? (result.success ? 'OK' : 'Browser action failed');
+ const content: McpToolResult['content'] = [{ text, type: 'text' }];
+
+ // Screenshot: hand the image back as an MCP image block so CC can
+ // actually see the page (unlike the homogeneous runtime's text-only echo).
+ if (apiName === 'screenshot') {
+ const dataUrl = (result.state as { dataUrl?: string } | undefined)?.dataUrl;
+ const match =
+ typeof dataUrl === 'string' ? dataUrl.match(/^data:(image\/[\w.+-]+);base64,(.+)$/) : null;
+ if (match) content.push({ data: match[2], mimeType: match[1], type: 'image' });
+ }
+
+ return { content, isError: !result.success };
+ }
+
+ // ─── File cache ───
+
+ private get fileCacheDir(): string {
+ return path.join(this.app.appStoragePath, FILE_CACHE_DIR);
+ }
+
+ /**
+ * Build a Claude Code stream-json user message with text + base64 images.
+ * Semantic context is assembled by the shared prompt engine before the
+ * provider-specific serializer runs.
+ */
+ private async buildStreamJsonInput(
+ prompt: string,
+ imageList: HeterogeneousAgentImageAttachment[] = [],
+ systemContext?: string,
+ ): Promise<string> {
+ const promptInput = buildHeterogeneousPrompt({ imageList, prompt, systemContext });
+ const plan = await buildAgentInput('claude-code', promptInput, {
+ cacheDir: this.fileCacheDir,
+ });
+ return plan.stdin;
+ }
+
+ // ─── IPC methods ───
+
+ /**
+ * Create a session (stores config, process spawned on sendPrompt).
+ */
+ async startSession(params: StartSessionParams): Promise<StartSessionResult> {
+ const sessionId = randomUUID();
+ const agentType = params.agentType || 'claude-code';
+ getHeterogeneousAgentDriver(agentType);
+
+ this.sessions.set(sessionId, {
+ // If resuming, pre-set the agent session ID so sendPrompt adds --resume
+ agentSessionId: params.resumeSessionId,
+ agentType,
+ args: params.args || [],
+ command: params.command,
+ cwd: params.cwd,
+ env: params.env,
+ sessionId,
+ resumeSessionId: params.resumeSessionId,
+ useClaudeCodeSdk: params.useClaudeCodeSdk,
+ });
+
+ logger.info('Session created:', { agentType, sessionId });
+ return { sessionId };
+ }
+
+ /**
+ * Send a prompt to an agent session.
+ *
+ * Spawns the CLI process with preset flags. Pipes each stdout chunk through
+ * the shared `AgentStreamPipeline` (JSONL → adapter → toStreamEvent) and
+ * broadcasts the resulting `AgentStreamEvent`s on `heteroAgentEvent`.
+ */
+ async sendPrompt(params: SendPromptParams): Promise<void> {
+ const session = this.sessions.get(params.sessionId);
+ if (!session) throw new Error(`Session not found: ${params.sessionId}`);
+
+ const preflightError = await this.getSpawnPreflightError(session);
+ if (preflightError) {
+ this.broadcast('heteroAgentSessionError', {
+ error: preflightError,
+ sessionId: session.sessionId,
+ });
+ throw new Error(preflightError.message);
+ }
+
+ // Revive a Claude Code session whose local transcript the CLI already
+ // garbage-collected (`cleanupPeriodDays`, default 30 days). Rebuilding it
+ // from the turns LobeHub still holds turns a hard
+ // "No conversation found with session ID" into a normal `--resume` that
+ // hydrates the native history. No-ops when the transcript still exists.
+ // MUST run before the Claude SDK early return — both transports read the
+ // same on-disk transcript for resume.
+ if (
+ session.agentType === 'claude-code' &&
+ session.agentSessionId &&
+ session.cwd &&
+ params.resumeReplayMessages?.length
+ ) {
+ try {
+ const ensured = await ensureClaudeCodeResumeTranscript({
+ cwd: session.cwd,
+ messages: params.resumeReplayMessages,
+ sessionId: session.agentSessionId,
+ });
+ if (ensured.written)
+ logger.info('Rebuilt GC-ed Claude Code transcript for resume:', {
+ path: ensured.path,
+ turns: params.resumeReplayMessages.length,
+ });
+ } catch (error) {
+ // Never block the run on this — worst case CC starts a fresh session.
+ logger.warn('Failed to rebuild Claude Code resume transcript:', error);
+ }
+ }
+
+ if (
+ session.agentType === 'claude-code' &&
+ (session.useClaudeCodeSdk || this.isClaudeCodeSdkLabEnabled)
+ ) {
+ return this.sendPromptWithClaudeSdk(params, session);
+ }
+
+ // Stand up the AskUserQuestion MCP bridge for claude-code prompts BEFORE
+ // building the spawn plan so the driver can wire the temp config path
+ // into `--mcp-config`. Codex / future agents skip this entirely.
+ const intervention =
+ session.agentType === 'claude-code'
+ ? await this.setupInterventionForOp(params.operationId, {
+ agentId: params.agentId,
+ topicId: params.topicId,
+ }).catch((err) => {
+ logger.warn('Failed to set up AskUserQuestion bridge — proceeding without it:', err);
+ return undefined;
+ })
+ : undefined;
+
+ let spawnPlan;
+ let traceSession;
+ let cwd: string;
+ let initialCumulativeUsage: UsageData | undefined;
+ let spawnEnv: NodeJS.ProcessEnv;
+ try {
+ const driver = getHeterogeneousAgentDriver(session.agentType);
+ const promptInput = buildHeterogeneousPrompt({
+ imageList: params.imageList,
+ prompt: params.prompt,
+ systemContext: params.systemContext,
+ });
+ spawnPlan = await driver.buildSpawnPlan({
+ args: session.args,
+ helpers: {
+ buildAgentInput: async (agentType, input) => {
+ try {
+ return await buildAgentInput(agentType, input, { cacheDir: this.fileCacheDir });
+ } catch (error) {
+ logger.error('Failed to prepare heterogeneous agent input:', error);
+ throw new Error(
+ `Failed to attach image(s) to CLI: ${this.getErrorMessage(error) || 'Unknown error'}`,
+ { cause: error },
+ );
+ }
+ },
+ },
+ mcpConfigPath: intervention?.tmpConfigPath,
+ promptInput,
+ resumeSessionId: session.agentSessionId,
+ });
+
+ // Fall back to the user's Desktop so the process never inherits
+ // the Electron parent's cwd (which is `/` when launched from Finder).
+ cwd = session.cwd || electronApp.getPath('desktop');
+
+ spawnEnv = this.buildSessionSpawnEnv(session);
+
+ if (session.agentType === 'codex') {
+ const initialModel = await resolveCodexInitialModel({
+ args: spawnPlan.args,
+ env: spawnEnv,
+ });
+ if (initialModel?.model) {
+ session.model = initialModel.model;
+ session.modelSource = initialModel.source;
+ }
+
+ if (session.agentSessionId) {
+ initialCumulativeUsage = (
+ await readCodexSessionModel(session.agentSessionId, { env: spawnEnv })
+ )?.cumulativeUsage;
+ }
+ }
+
+ traceSession = await this.createCliTraceSession({
+ cliArgs: spawnPlan.args,
+ cwd,
+ imageList: params.imageList ?? [],
+ session,
+ stdinPayload: spawnPlan.stdinPayload,
+ });
+ } catch (err) {
+ // We never made it to spawn — the `proc.on('exit')` cleanup path
+ // won't run, so tear the intervention bridge down right here.
+ if (intervention) {
+ await intervention.cleanup().catch((cleanupErr) => {
+ logger.warn('AskUserQuestion cleanup error during pre-spawn failure:', cleanupErr);
+ });
+ }
+ throw err;
+ }
+ const useStdin = spawnPlan.stdinPayload !== undefined;
+ const cliArgs = spawnPlan.args;
+ const resolvedCliSpawnPlan = await resolveCliSpawnPlan(
+ session.resolvedCommandPath ?? session.command,
+ cliArgs,
+ );
+
+ logger.info(
+ 'Spawning agent:',
+ resolvedCliSpawnPlan.command,
+ resolvedCliSpawnPlan.args.join(' '),
+ `(cwd: ${cwd})`,
+ );
+
+ // `detached: true` on Unix puts the child in a new process group so we
+ // can SIGINT/SIGKILL the whole tree (claude + any tool subprocesses)
+ // via `process.kill(-pid, sig)` on cancel. Without this, SIGINT to just
+ // the claude binary can leave bash/grep/etc. tool children running and
+ // the CLI hung waiting on them. Windows has different semantics — use
+ // taskkill /T /F there; no detached flag needed.
+ const spawnOptions = {
+ cwd,
+ detached: process.platform !== 'win32',
+ // Strip host Anthropic creds from the inherited env so a developer's
+ // shell `ANTHROPIC_API_KEY` can't hijack the CLI's own auth. `session.env`
+ // is spread last, so an agent that explicitly configures a key still wins.
+ env: spawnEnv,
+ stdio: [useStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'] as ['pipe' | 'ignore', 'pipe', 'pipe'],
+ };
+
+ return new Promise<void>((resolve, reject) => {
+ const proc = spawn(resolvedCliSpawnPlan.command, resolvedCliSpawnPlan.args, spawnOptions);
+ this.handleSpawnedAgentProcess({
+ cwd,
+ intervention,
+ params,
+ proc,
+ reject,
+ resolve,
+ session,
+ initialCumulativeUsage,
+ spawnEnv,
+ traceSession,
+ useStdin,
+ spawnPlan,
+ });
+ });
+ }
+
+ private async sendPromptWithClaudeSdk(
+ params: SendPromptParams,
+ session: AgentSession,
+ ): Promise<void> {
+ const cwd = session.cwd || electronApp.getPath('desktop');
+ const spawnEnv = this.buildSessionSpawnEnv(session);
+ const commandPath = session.resolvedCommandPath ?? this.resolveSessionCommand(session);
+ const stdinPayload = await this.buildStreamJsonInput(
+ params.prompt,
+ params.imageList ?? [],
+ params.systemContext,
+ );
+ const traceSession = await this.createCliTraceSession({
+ cliArgs: ['sdk-stream', ...session.args],
+ cwd,
+ imageList: params.imageList ?? [],
+ session,
+ stdinPayload,
+ });
+
+ void this.writeCliTraceFile(traceSession, 'stdin.txt', stdinPayload);
+
+ const sdkSession = new ClaudeAgentSdkSession({
+ args: session.args,
+ commandPath,
+ cwd,
+ env: spawnEnv,
+ onEvents: async (events) => {
+ for (const event of events) {
+ this.broadcast('heteroAgentEvent', {
+ event,
+ sessionId: session.sessionId,
+ });
+ }
+ },
+ onRawMessage: (line) => this.appendCliTraceFile(traceSession, 'stdout.jsonl', line),
+ onRuntimeStatus: (status) => {
+ this.broadcast('heteroAgentRuntimeStatus', status);
+ },
+ onSessionId: (agentSessionId) => {
+ if (agentSessionId !== session.agentSessionId) session.agentSessionId = agentSessionId;
+ },
+ onStderr: (data) => this.appendCliTraceFile(traceSession, 'stderr.log', data),
+ operationId: params.operationId,
+ resumeSessionId: session.agentSessionId,
+ sessionId: session.sessionId,
+ stdinPayload,
+ uploadImage: this.uploadResultImage,
+ });
+
+ session.sdkSession = sdkSession;
+
+ logger.info('Starting Claude Code SDK session:', {
+ commandPath,
+ cwd,
+ sessionId: session.sessionId,
+ });
+
+ try {
+ await sdkSession.run();
+ session.sdkSession = undefined;
+ void this.writeCliTraceJson(traceSession, 'exit.json', {
+ finishedAt: new Date().toISOString(),
+ transport: 'claude-sdk',
+ });
+ await this.flushCliTrace(traceSession);
+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ } catch (error) {
+ session.sdkSession = undefined;
+ logger.error('Claude SDK session error:', error);
+ void this.writeCliTraceJson(traceSession, 'process-error.json', {
+ message: error instanceof Error ? error.message : String(error),
+ name: error instanceof Error ? error.name : 'Error',
+ transport: 'claude-sdk',
+ });
+ await this.flushCliTrace(traceSession);
+
+ if (session.cancelledByUs) {
+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ return;
+ }
+
+ const sessionError = this.getSessionErrorPayload(error, session);
+ this.broadcast('heteroAgentSessionError', {
+ error: sessionError,
+ sessionId: session.sessionId,
+ });
+ throw new Error(typeof sessionError === 'string' ? sessionError : sessionError.message, {
+ cause: error,
+ });
+ }
+ }
+
+ private async verifyCodexSessionModel({
+ env,
+ pipeline,
+ session,
+ traceSession,
+ }: {
+ env: NodeJS.ProcessEnv;
+ pipeline: AgentStreamPipeline;
+ session: AgentSession;
+ traceSession: CliTraceSession | undefined;
+ }): Promise<AgentStreamEvent[]> {
+ if (
+ session.agentType !== 'codex' ||
+ !pipeline.sessionId ||
+ session.verifiedModelSessionId === pipeline.sessionId
+ ) {
+ return [];
+ }
+
+ const now = Date.now();
+ if (
+ session.modelVerificationLastAttemptSessionId === pipeline.sessionId &&
+ session.modelVerificationLastAttemptAt &&
+ now - session.modelVerificationLastAttemptAt < 1000
+ ) {
+ return [];
+ }
+ session.modelVerificationLastAttemptSessionId = pipeline.sessionId;
+ session.modelVerificationLastAttemptAt = now;
+
+ const sessionModel = await readCodexSessionModel(pipeline.sessionId, { env });
+ if (!sessionModel?.model) return [];
+
+ const previousModel = session.model;
+ session.verifiedModel = sessionModel.model;
+ session.verifiedModelContextWindow = sessionModel.contextWindow;
+ session.verifiedModelProvider = sessionModel.provider;
+ session.verifiedModelSessionId = pipeline.sessionId;
+ session.verifiedModelSourceFile = sessionModel.sourceFile;
+
+ void this.writeCliTraceJson(traceSession, 'model.json', {
+ initialModel: previousModel,
+ initialModelSource: session.modelSource,
+ sessionId: pipeline.sessionId,
+ verifiedAt: new Date().toISOString(),
+ verifiedContextWindow: sessionModel.contextWindow,
+ verifiedLine: sessionModel.line,
+ verifiedModel: sessionModel.model,
+ verifiedModelProvider: sessionModel.provider,
+ verifiedSourceFile: sessionModel.sourceFile,
+ });
+
+ if (previousModel === sessionModel.model) return [];
+
+ session.model = sessionModel.model;
+ session.modelSource = 'codex-session';
+ return pipeline.configureSession({ model: sessionModel.model });
+ }
+
+ private handleSpawnedAgentProcess({
+ cwd,
+ initialCumulativeUsage,
+ intervention,
+ params,
+ proc,
+ reject,
+ resolve,
+ session,
+ spawnEnv,
+ spawnPlan,
+ traceSession,
+ useStdin,
+ }: {
+ cwd: string;
+ intervention?: Awaited<ReturnType<HeterogeneousAgentCtr['setupInterventionForOp']>>;
+ params: SendPromptParams;
+ proc: ChildProcess;
+ reject: (reason?: unknown) => void;
+ resolve: () => void;
+ session: AgentSession;
+ initialCumulativeUsage?: UsageData | undefined;
+ spawnEnv: NodeJS.ProcessEnv;
+ spawnPlan: HeterogeneousAgentBuildPlan;
+ traceSession: CliTraceSession | undefined;
+ useStdin: boolean;
+ }) {
+ proc.on('error', (err) => {
+ logger.error('Agent process error:', err);
+ void this.writeCliTraceJson(traceSession, 'process-error.json', {
+ message: err.message,
+ name: err.name,
+ });
+ void this.flushCliTrace(traceSession);
+ const sessionError = this.getSessionErrorPayload(err, session);
+ this.broadcast('heteroAgentSessionError', {
+ error: sessionError,
+ sessionId: session.sessionId,
+ });
+ reject(new Error(typeof sessionError === 'string' ? sessionError : sessionError.message));
+ });
+
+ // In stdin mode, write the prepared payload and close stdin.
+ if (useStdin && spawnPlan.stdinPayload !== undefined && proc.stdin) {
+ void this.writeCliTraceFile(traceSession, 'stdin.txt', spawnPlan.stdinPayload);
+ const stdin = proc.stdin as Writable;
+ stdin.write(spawnPlan.stdinPayload, () => {
+ stdin.end();
+ });
+ }
+
+ session.process = proc;
+
+ // Producer-side conversion (V3 contract): JSONL framing + adapter +
+ // toStreamEvent all run inside the shared pipeline, so renderer + future
+ // server `heteroIngest` see the same `AgentStreamEvent` wire shape with
+ // no per-consumer adapter. The pipeline auto-wires the Codex
+ // file-change diff/stat tracker when `agentType === 'codex'`, so this
+ // controller stays agent-agnostic.
+ const pipeline = new AgentStreamPipeline({
+ agentType: session.agentType,
+ cwd,
+ initialCumulativeUsage,
+ initialModel: session.model,
+ operationId: params.operationId,
+ uploadImage: this.uploadResultImage,
+ });
+ let stdoutBroadcastQueue: Promise<void> = Promise.resolve();
+
+ const broadcastStreamEvents = (events: AgentStreamEvent[]) => {
+ for (const event of events) {
+ this.broadcast('heteroAgentEvent', {
+ event,
+ sessionId: session.sessionId,
+ });
+ }
+ };
+
+ const broadcastPipelineBatch = (produce: () => ReturnType<AgentStreamPipeline['push']>) => {
+ stdoutBroadcastQueue = stdoutBroadcastQueue
+ .then(async () => {
+ const events = await produce();
+ // Adapter-extracted CC/Codex session id powers `--resume` on the
+ // next prompt; surface it through the existing `getSessionInfo`
+ // IPC by mirroring the freshest value onto the session record.
+ if (pipeline.sessionId && pipeline.sessionId !== session.agentSessionId) {
+ session.agentSessionId = pipeline.sessionId;
+ }
+ events.push(
+ ...(await this.verifyCodexSessionModel({
+ env: spawnEnv,
+ pipeline,
+ session,
+ traceSession,
+ })),
+ );
+ broadcastStreamEvents(events);
+ })
+ .catch((error) => {
+ logger.error('Failed to broadcast agent stream batch:', error);
+ });
+ };
+
+ const broadcastBridgeEvent = (event: AgentStreamEvent) => {
+ stdoutBroadcastQueue = stdoutBroadcastQueue
+ .then(() => {
+ broadcastStreamEvents([event]);
+ })
+ .catch((error) => {
+ logger.error('Failed to broadcast AskUserQuestion bridge event:', error);
+ });
+ };
+
+ if (intervention) {
+ const pumpDone = (async () => {
+ for await (const event of intervention.bridge.events()) {
+ broadcastBridgeEvent(event);
+ }
+ await stdoutBroadcastQueue;
+ })().catch((err) => {
+ logger.warn('AskUserQuestion bridge pump error:', err);
+ });
+ const slot = this.opIdToIntervention.get(params.operationId);
+ if (slot) slot.pumpDone = pumpDone;
+ }
+
+ // Stream stdout events through the producer pipeline.
+ const stdout = proc.stdout as Readable;
+ stdout.on('data', (chunk: Buffer) => {
+ void this.appendCliTraceFile(traceSession, 'stdout.jsonl', chunk);
+ broadcastPipelineBatch(() => pipeline.push(chunk));
+ });
+ stdout.on('end', () => {
+ broadcastPipelineBatch(() => pipeline.flush());
+ });
+
+ // Capture stderr
+ const stderrChunks: string[] = [];
+ const stderr = proc.stderr as Readable;
+ stderr.on('data', (chunk: Buffer) => {
+ void this.appendCliTraceFile(traceSession, 'stderr.log', chunk);
+ stderrChunks.push(chunk.toString('utf8'));
+ });
+
+ proc.on('exit', (code, signal) => {
+ // Node may emit `'exit'` BEFORE stdio finishes draining (documented:
+ // child_process docs note "stdio streams might still be open" at exit
+ // time). Wait for stdout to fully end/close so the `stdout.on('end')`
+ // handler has scheduled `pipeline.flush()` onto `stdoutBroadcastQueue`,
+ // THEN wait for the queue itself to settle. Without this two-step
+ // gate, trailing flushed events (final synthesized tool_end /
+ // tool_result) would race against — and lose to — the
+ // `heteroAgentSessionComplete` broadcast, leaving renderer-side
+ // persistence to finalize on incomplete state.
+ const stdoutDrained = streamFinished(stdout, { writable: false }).catch(() => {
+ /* end / close / error are all "done"; we still want to settle. */
+ });
+
+ void stdoutDrained
+ .then(() => stdoutBroadcastQueue)
+ .finally(async () => {
+ // Tear down the AskUserQuestion bridge / temp `mcp.json` for this
+ // op. Pending MCP handlers get a `session_ended` cancellation so
+ // they return cleanly even if CC was killed mid-tool-call.
+ if (intervention) {
+ await intervention.cleanup().catch((err) => {
+ logger.warn('AskUserQuestion cleanup error:', err);
+ });
+ }
+
+ void this.writeCliTraceJson(traceSession, 'exit.json', {
+ code,
+ finishedAt: new Date().toISOString(),
+ signal,
+ });
+ await this.flushCliTrace(traceSession);
+ await waitForHeteroSessionCompleteGrace();
+
+ logger.info('Agent process exited:', { code, sessionId: session.sessionId, signal });
+ session.process = undefined;
+
+ // If *we* killed it (cancel / stop / before-quit), treat the non-zero
+ // exit as a clean shutdown — surfacing it as an error would make a
+ // user-initiated cancel look like an agent failure, and an Electron
+ // shutdown affecting OTHER running CC sessions would pollute their
+ // topics with a misleading "Agent exited with code 143" message.
+ if (session.cancelledByUs) {
+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ resolve();
+ return;
+ }
+
+ if (code === 0) {
+ this.broadcast('heteroAgentSessionComplete', { sessionId: session.sessionId });
+ resolve();
+ } else {
+ const stderrOutput = stderrChunks.join('').trim();
+ const errorMsg = this.getExitErrorMessage(code, session, stderrOutput);
+ const sessionError = this.getSessionErrorPayload(errorMsg, session);
+ this.broadcast('heteroAgentSessionError', {
+ error: sessionError,
+ sessionId: session.sessionId,
+ });
+ reject(
+ new Error(typeof sessionError === 'string' ? sessionError : sessionError.message),
+ );
+ }
+ });
+ });
+ }
+
+ /**
+ * Get session info (agent's internal session ID for multi-turn resume).
+ */
+ async getSessionInfo(params: GetSessionInfoParams): Promise<SessionInfo> {
+ const session = this.sessions.get(params.sessionId);
+ return { agentSessionId: session?.agentSessionId };
+ }
+
+ /** Query OpenCode's model catalog using the same cwd/env rules as a real local session. */
+ async listModels(
+ params: ListHeterogeneousAgentModelsParams,
+ ): Promise<HeterogeneousAgentModelCatalog> {
+ const env = {
+ ...buildInheritedSpawnEnv(),
+ ...buildProxyEnv(this.app.storeManager.get('networkProxy')),
+ ...params.env,
+ };
+
+ return listHeterogeneousAgentModels({
+ ...params,
+ cwd: params.cwd || electronApp.getPath('desktop'),
+ env,
+ });
+ }
+
+ async getCodexQuota(params: GetCodexQuotaParams = {}): Promise<CodexQuotaSnapshot> {
+ const command = params.command?.trim() || 'codex';
+ const sourceEnv = {
+ ...buildProxyEnv(this.app.storeManager.get('networkProxy')),
+ ...params.env,
+ };
+ const sourceKey = createQuotaCacheKey('codex', command, sourceEnv);
+
+ return this.codexQuotaCache.get(
+ sourceKey,
+ async () => {
+ const status = await detectHeterogeneousCliCommand('codex', command);
+ const env = {
+ ...(status.resolvedPathEnv ? { PATH: status.resolvedPathEnv } : {}),
+ ...sourceEnv,
+ };
+
+ return fetchCodexQuota({
+ command: status.available && status.path ? status.path : command,
+ env: Object.keys(env).length > 0 ? env : undefined,
+ });
+ },
+ { force: params.force },
+ );
+ }
+
+ /**
+ * Redeem one earned Codex rate-limit reset, then bypass the quota cache so
+ * every renderer receives the post-reset windows and remaining inventory.
+ */
+ async consumeCodexRateLimitResetCredit(
+ params: ConsumeCodexRateLimitResetCreditParams,
+ ): Promise<CodexRateLimitResetResult> {
+ const command = params.command?.trim() || 'codex';
+ const sourceEnv = {
+ ...buildProxyEnv(this.app.storeManager.get('networkProxy')),
+ ...params.env,
+ };
+ const sourceKey = createQuotaCacheKey('codex', command, sourceEnv);
+ const status = await detectHeterogeneousCliCommand('codex', command);
+ const env = {
+ ...(status.resolvedPathEnv ? { PATH: status.resolvedPathEnv } : {}),
+ ...sourceEnv,
+ };
+ const requestOptions = {
+ command: status.available && status.path ? status.path : command,
+ env: Object.keys(env).length > 0 ? env : undefined,
+ };
+
+ const outcome = await consumeCodexRateLimitResetCreditRequest({
+ ...requestOptions,
+ creditId: params.creditId,
+ idempotencyKey: params.idempotencyKey,
+ });
+ this.codexQuotaCache.invalidate(sourceKey);
+ const quota = await this.codexQuotaCache.get(sourceKey, () => fetchCodexQuota(requestOptions), {
+ force: true,
+ });
+
+ return { outcome, quota };
+ }
+
+ /**
+ * Read the Claude Code subscription quota. No CLI is spawned: the quota
+ * comes from Anthropic's OAuth usage API using the local `claude` login,
+ * and the request goes through the app's global proxy dispatcher.
+ */
+ /**
+ * Identity of the Claude login a spawn with this env would use. Pure local
+ * file read (`.claude.json` of the resolved profile) — cheap enough to call
+ * once per run for usage→account attribution; never touches the network.
+ */
+ async getClaudeCodeIdentity(params: { env?: Record<string, string> } = {}) {
+ return readClaudeCodeIdentity({ env: params.env });
+ }
+
+ async getClaudeCodeQuota(
+ params: GetClaudeCodeQuotaParams = {},
+ ): Promise<ClaudeCodeQuotaSnapshot> {
+ const sourceKey = createQuotaCacheKey('claude-code', params.env);
+
+ return this.claudeCodeQuotaCache.get(
+ sourceKey,
+ () => fetchClaudeCodeQuota({ env: params.env }),
+ { force: params.force },
+ );
+ }
+
+ /**
+ * Signal the whole process tree spawned by this session.
+ *
+ * On Unix the child was spawned with `detached: true`, so negating the pid
+ * signals the process group — reaching tool subprocesses (bash, grep, etc.)
+ * that would otherwise orphan after a parent-only kill. Falls back to the
+ * direct signal if the group kill raises (ESRCH when the leader is already
+ * gone). On Windows we shell out to `taskkill /T /F` which walks the tree.
+ */
+ private killProcessTree(proc: ChildProcess, signal: NodeJS.Signals): void {
+ if (!proc.pid || proc.killed) return;
+
+ if (process.platform === 'win32') {
+ try {
+ spawn('taskkill', ['/pid', String(proc.pid), '/T', '/F'], { stdio: 'ignore' });
+ } catch (err) {
+ logger.warn('taskkill failed:', err);
+ }
+ return;
+ }
+
+ try {
+ process.kill(-proc.pid, signal);
+ } catch {
+ try {
+ proc.kill(signal);
+ } catch {
+ // already exited
+ }
+ }
+ }
+
+ /**
+ * Cancel an ongoing session: SIGINT the CC tree, escalate to SIGKILL after
+ * 2s if the CLI hasn't exited (some tool calls swallow SIGINT). The
+ * `exit` handler on the spawned proc broadcasts completion and clears
+ * `session.process`, so the escalation is a no-op when the graceful path
+ * already landed.
+ */
+ async cancelSession(params: CancelSessionParams): Promise<void> {
+ const session = this.sessions.get(params.sessionId);
+ if (!session) return;
+
+ session.cancelledByUs = true;
+ if (session.sdkSession) {
+ session.sdkSession.close();
+ return;
+ }
+
+ if (!session.process || session.process.killed) return;
+ const proc = session.process;
+ this.killProcessTree(proc, 'SIGINT');
+
+ setTimeout(() => {
+ if (session.process === proc && !proc.killed) {
+ logger.warn('Session did not exit after SIGINT, escalating to SIGKILL:', params.sessionId);
+ this.killProcessTree(proc, 'SIGKILL');
+ }
+ }, 2000);
+ }
+
+ /**
+ * Stop and clean up a session.
+ */
+ async stopSession(params: StopSessionParams): Promise<void> {
+ const session = this.sessions.get(params.sessionId);
+ if (!session) return;
+
+ if (session.sdkSession) {
+ session.cancelledByUs = true;
+ session.sdkSession.close();
+ }
+
+ if (session.process && !session.process.killed) {
+ session.cancelledByUs = true;
+ const proc = session.process;
+ this.killProcessTree(proc, 'SIGTERM');
+ setTimeout(() => {
+ if (session.process === proc && !proc.killed) {
+ this.killProcessTree(proc, 'SIGKILL');
+ }
+ }, 3000);
+ }
+
+ this.sessions.delete(params.sessionId);
+ }
+
+ async respondPermission(): Promise<void> {
+ // No-op for CLI mode (permissions handled by --permission-mode flag)
+ }
+
+ /**
+ * Renderer → main: deliver the user's answer to a pending CC AskUserQuestion
+ * (or signal cancellation). The matching bridge resolves its blocked
+ * `pending()` Promise, the local MCP handler returns to CC, and CC's
+ * `tool_result` flows back through the normal stream pipeline.
+ *
+ * Idempotent — late submissions for already-resolved tool calls are no-ops.
+ * No-op when called for an unknown opId; the bridge may have been cleaned
+ * up already (op finished / cancelled).
+ */
+ async submitIntervention(params: SubmitInterventionParams): Promise<void> {
+ const slot = this.opIdToIntervention.get(params.operationId);
+ if (!slot) {
+ logger.warn('submitIntervention: no active intervention for operationId', params.operationId);
+ return;
+ }
+ slot.bridge.resolve(params.toolCallId, {
+ cancelReason: params.cancelled ? (params.cancelReason ?? 'user_cancelled') : undefined,
+ cancelled: params.cancelled,
+ result: params.result,
+ });
+ }
+
+ /**
+ * Synchronously unlink every pending intervention's temp `mcp.json`. The
+ * async exit-handler cleanup loses to Electron's main-process teardown
+ * often enough that we'd leak `lobe-cc-mcp-<opId>.json` files into
+ * `os.tmpdir()` on real shutdowns; sync unlink here is the only reliable
+ * guarantee. Safe to call multiple times.
+ */
+ private unlinkPendingInterventionConfigsSync = (): void => {
+ for (const [, intervention] of this.opIdToIntervention) {
+ try {
+ unlinkSync(intervention.tmpConfigPath);
+ } catch {
+ /* file may already be gone — fine */
+ }
+ }
+ };
+
+ /**
+ * Cleanup on app quit. `before-quit` covers the user-driven Cmd+Q /
+ * `app.quit()` path; SIGTERM / SIGINT cover external kills (test
+ * harnesses, OS shutdown) where Electron's lifecycle events never fire.
+ */
+ afterAppReady() {
+ electronApp.on('before-quit', () => {
+ this.unlinkPendingInterventionConfigsSync();
+ for (const [, session] of this.sessions) {
+ if (session.sdkSession) {
+ session.cancelledByUs = true;
+ session.sdkSession.close();
+ }
+ if (session.process && !session.process.killed) {
+ session.cancelledByUs = true;
+ this.killProcessTree(session.process, 'SIGTERM');
+ }
+ }
+ this.sessions.clear();
+ // The exit handlers will tear each per-op intervention down, but if
+ // CC's stdio close races shutdown we'd leave the MCP server bound to
+ // a port. Stopping it here cancels every still-pending bridge with
+ // `session_ended` and closes the listener.
+ void this.builtinMcpServer?.stop().catch((err) => {
+ logger.warn('AskUserQuestion MCP server stop error:', err);
+ });
+ });
+
+ const onSignal = (signal: NodeJS.Signals) => {
+ this.unlinkPendingInterventionConfigsSync();
+ // Defer to Electron's normal quit flow so the rest of the app gets a
+ // chance to tear down. The `before-quit` handler above is idempotent.
+ try {
+ electronApp.quit();
+ } catch {
+ /* during late shutdown app.quit may throw — fine */
+ }
+ // Last-resort exit if Electron is wedged and won't quit on its own.
+ setTimeout(() => process.exit(signal === 'SIGINT' ? 130 : 143), 1000).unref();
+ };
+ process.on('SIGTERM', onSignal);
+ process.on('SIGINT', onSignal);
+ }
+
+ /**
+ * Spawn the embedded CLI's `hetero exec` for gateway-driven agent runs.
+ * The bundled CLI handles everything downstream — no local
+ * AgentStreamPipeline or IPC broadcast needed. Mirrors
+ * `spawnHeteroSandbox()` on the server side.
+ *
+ * Resolves only after the child either starts or fails to start. Node reports
+ * failures such as an inaccessible cwd asynchronously through `error`, so an
+ * eager accepted ack would strand the server operation without a producer.
+ */
+ spawnLhHeteroExec(params: {
+ agentType: string;
+ /** Resolved `lh hetero exec` wrapper args. */
+ args?: string[];
+ cwd?: string;
+ /** Image attachments (signed URLs) appended as image content blocks. */
+ imageList?: HeteroExecImageRef[];
+ jwt: string;
+ operationId: string;
+ prompt: string;
+ resumeSessionId?: string;
+ serverUrl: string;
+ systemContext?: string;
+ topicId: string;
+ }): Promise<{ reason?: string; status: 'accepted' | 'rejected' }> {
+ const {
+ agentType,
+ args: extraArgs,
+ cwd,
+ imageList,
+ jwt,
+ operationId,
+ prompt,
+ resumeSessionId,
+ serverUrl,
+ systemContext,
+ topicId,
+ } = params;
+ const workDir = cwd ?? process.cwd();
+
+ // When CLI tracing is enabled (dev builds, or the Help-menu toggle in
+ // packaged builds), have `lh hetero exec` persist the agent process's RAW
+ // stream-json (pre-adapter) on this device. The remote-device path
+ // otherwise leaves no local record — the CLI consumes stdout internally and
+ // only POSTs adapted events to the server — so without this there's nothing
+ // to inspect when a remote run misbehaves.
+ const rawDumpDir = this.shouldTraceCliOutput ? this.resolveTraceRootDir(workDir) : undefined;
+
+ const args = [
+ 'hetero',
+ 'exec',
+ '--type',
+ agentType,
+ '--operation-id',
+ operationId,
+ '--topic',
+ topicId,
+ '--render',
+ 'none',
+ '--input-json',
+ '-',
+ '--cwd',
+ workDir,
+ ...(resumeSessionId ? ['--resume', resumeSessionId] : []),
+ ...(rawDumpDir ? ['--raw-dump', rawDumpDir] : []),
+ ...(extraArgs ?? []),
+ ];
+
+ const stdinPayload = buildHeteroExecStdinPayload({ imageList, prompt, systemContext });
+ const cliScript = resolveCliScript();
+ if (!existsSync(cliScript)) {
+ return Promise.resolve({
+ reason: `Embedded CLI not found at ${cliScript}`,
+ status: 'rejected',
+ });
+ }
+
+ const env = {
+ ...process.env,
+ ...buildProxyEnv(this.app.storeManager.get('networkProxy')),
+ ELECTRON_RUN_AS_NODE: '1',
+ LOBEHUB_JWT: jwt,
+ LOBEHUB_SERVER: serverUrl,
+ };
+
+ logger.info('spawnLhHeteroExec: type=%s op=%s topic=%s', agentType, operationId, topicId);
+
+ // Execute the CLI shipped with this desktop build. A bare `lh` would prefer
+ // an older global install earlier on PATH, letting model discovery report a
+ // capability that the actual execution runtime does not support.
+ const child = spawn(process.execPath, [cliScript, ...args], {
+ cwd: workDir,
+ env,
+ stdio: ['pipe', 'inherit', 'inherit'],
+ });
+
+ child.on('exit', (code, signal) => {
+ logger.info('spawnLhHeteroExec: exited — op=%s code=%s signal=%s', operationId, code, signal);
+ });
+
+ return new Promise((resolve) => {
+ let settled = false;
+ const settle = (result: { reason?: string; status: 'accepted' | 'rejected' }) => {
+ if (settled) return;
+ settled = true;
+ resolve(result);
+ };
+
+ child.stdin.once('error', (err) => {
+ logger.error(
+ 'spawnLhHeteroExec: stdin write failed — op=%s error=%s',
+ operationId,
+ err.message,
+ );
+ settle({ reason: err.message, status: 'rejected' });
+ });
+
+ child.once('spawn', () => {
+ try {
+ child.stdin.write(stdinPayload);
+ child.stdin.end();
+ settle({ status: 'accepted' });
+ } catch (err) {
+ const reason = err instanceof Error ? err.message : String(err);
+ logger.error(
+ 'spawnLhHeteroExec: stdin write threw — op=%s error=%s',
+ operationId,
+ reason,
+ );
+ settle({ reason, status: 'rejected' });
+ }
+ });
+
+ child.once('error', (err) => {
+ logger.error('spawnLhHeteroExec: spawn failed — %s', err.message);
+ settle({ reason: err.message, status: 'rejected' });
+ });
+ });
+ }
+}
diff --git a/apps/desktop/src/main/controllers/LocalFileCtr.ts b/apps/desktop/src/main/controllers/LocalFileCtr.ts
index d1720f49860..43a5d59808d 100644
--- a/apps/desktop/src/main/controllers/LocalFileCtr.ts
+++ b/apps/desktop/src/main/controllers/LocalFileCtr.ts
@@ -2,11 +2,7 @@ import { constants } from 'node:fs';
import { access, readFile, realpath, stat } from 'node:fs/promises';
import path from 'node:path';
-import {
- defaultSearchProjectFiles,
- prepareSkillDirectory,
- type SkillDirectoryDeps,
-} from '@lobechat/device-control';
+import type { SkillDirectoryDeps } from '@lobechat/device-control';
import {
type AuditSafePathsParams,
type AuditSafePathsResult,
@@ -49,18 +45,16 @@ import {
import {
editLocalFile,
expandTilde,
- type FileResult,
listLocalFiles,
moveLocalFiles,
readLocalFile,
renameLocalFile,
resolveAgainstCwd,
- type SearchOptions,
writeLocalFile,
-} from '@lobechat/local-file-shell';
+} from '@lobechat/local-file-shell/file';
+import type { FileResult, SearchOptions } from '@lobechat/local-file-shell/types';
import { resolveMimeType } from '@lobechat/utils/mimeType';
import { dialog, shell } from 'electron';
-import { execa } from 'execa';
import ContentSearchService from '@/services/contentSearchSrv';
import FileSearchService from '@/services/fileSearchSrv';
@@ -607,6 +601,7 @@ export default class LocalFileCtr extends ControllerModule {
async handlePrepareSkillDirectory(
params: PrepareSkillDirectoryParams,
): Promise<PrepareSkillDirectoryResult> {
+ const { prepareSkillDirectory } = await import('@lobechat/device-control/skill-directory');
return prepareSkillDirectory(params, this.getSkillDirectoryDeps());
}
@@ -642,6 +637,7 @@ export default class LocalFileCtr extends ControllerModule {
@IpcMethod()
async getProjectFileIndex(params: ProjectFileIndexParams = {}): Promise<ProjectFileIndexResult> {
+ const { execa } = await import('execa');
const requestedScope = params.scope || process.cwd();
const startedAt = Date.now();
@@ -799,6 +795,8 @@ export default class LocalFileCtr extends ControllerModule {
@IpcMethod()
async searchProjectFiles(params: ProjectFileSearchParams): Promise<ProjectFileSearchResult> {
const startedAt = Date.now();
+ const { defaultSearchProjectFiles } =
+ await import('@lobechat/device-control/project-file-index');
const result = await defaultSearchProjectFiles(params);
logger.debug('Project file search completed', {
diff --git a/apps/desktop/src/main/controllers/McpCtr.ts b/apps/desktop/src/main/controllers/McpCtr.ts
index 47bc88f6da0..b574e3ee8f0 100644
--- a/apps/desktop/src/main/controllers/McpCtr.ts
+++ b/apps/desktop/src/main/controllers/McpCtr.ts
@@ -8,7 +8,7 @@ import superjson from 'superjson';
import FileService from '@/services/fileSrv';
import { createLogger } from '@/utils/logger';
-import { MCPClient, MCPConnectionError } from '../libs/mcp/client';
+import type { MCPClient } from '../libs/mcp/client';
import type {
AudioContent,
ImageContent,
@@ -21,6 +21,7 @@ import { ControllerModule, IpcMethod } from './index';
const execPromise = promisify(exec);
const logger = createLogger('controllers:McpCtr');
+const loadMcpClient = () => import('../libs/mcp/client');
/**
* Desktop-only copy of `@lobechat/types`'s `CheckMcpInstallResult`.
@@ -232,6 +233,7 @@ export default class McpCtr extends ControllerModule {
}
private async createClient(params: MCPClientParams) {
+ const { MCPClient } = await loadMcpClient();
const client = new MCPClient(params);
await client.initialize();
return client;
@@ -334,6 +336,7 @@ export default class McpCtr extends ControllerModule {
});
} catch (error) {
// If it's an MCPConnectionError with stderr logs, enhance the error message
+ const { MCPConnectionError } = await loadMcpClient();
if (error instanceof MCPConnectionError && error.stderrLogs.length > 0) {
const stderrOutput = error.stderrLogs.join('\n');
const enhancedError = new Error(
@@ -473,6 +476,7 @@ export default class McpCtr extends ControllerModule {
};
} catch (error) {
// If it's an MCPConnectionError with stderr logs, enhance the error message
+ const { MCPConnectionError } = await loadMcpClient();
if (error instanceof MCPConnectionError && error.stderrLogs.length > 0) {
const stderrOutput = error.stderrLogs.join('\n');
const enhancedError = new Error(
diff --git a/apps/desktop/src/main/controllers/NetworkProxyCtr.ts b/apps/desktop/src/main/controllers/NetworkProxyCtr.ts
index f64580a9e41..13fb7d3f9f2 100644
--- a/apps/desktop/src/main/controllers/NetworkProxyCtr.ts
+++ b/apps/desktop/src/main/controllers/NetworkProxyCtr.ts
@@ -4,12 +4,8 @@ import { isEqual, merge } from 'es-toolkit/compat';
import { defaultProxySettings } from '@/const/store';
import { createLogger } from '@/utils/logger';
-import type { ProxyTestResult } from '../modules/networkProxy';
-import {
- ProxyConfigValidator,
- ProxyConnectionTester,
- ProxyDispatcherManager,
-} from '../modules/networkProxy';
+import type { ProxyTestResult } from '../modules/networkProxy/tester';
+import { ProxyConfigValidator } from '../modules/networkProxy/validator';
import { ControllerModule, IpcMethod } from './index';
// Create logger
@@ -70,6 +66,7 @@ export default class NetworkProxyCtr extends ControllerModule {
}
// Apply proxy settings
+ const { ProxyDispatcherManager } = await import('../modules/networkProxy/dispatcher');
await ProxyDispatcherManager.applyProxySettings(newConfig);
// Save to storage
@@ -93,6 +90,7 @@ export default class NetworkProxyCtr extends ControllerModule {
@IpcMethod()
async testProxyConnection(url: string): Promise<{ message?: string; success: boolean }> {
try {
+ const { ProxyConnectionTester } = await import('../modules/networkProxy/tester');
const result = await ProxyConnectionTester.testConnection(url);
if (result.success) {
@@ -119,6 +117,7 @@ export default class NetworkProxyCtr extends ControllerModule {
testUrl?: string;
}): Promise<ProxyTestResult> {
try {
+ const { ProxyConnectionTester } = await import('../modules/networkProxy/tester');
return await ProxyConnectionTester.testProxyConfig(config, testUrl);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
@@ -145,11 +144,23 @@ export default class NetworkProxyCtr extends ControllerModule {
const validation = ProxyConfigValidator.validate(networkProxy);
if (!validation.isValid) {
logger.warn('Invalid stored proxy configuration, using defaults:', validation.errors);
+ const { ProxyDispatcherManager } = await import('../modules/networkProxy/dispatcher');
await ProxyDispatcherManager.applyProxySettings(defaultProxySettings);
return;
}
+ // A fresh Electron process already uses direct connections. Avoid loading
+ // the full undici proxy implementation on the default startup path.
+ if (!networkProxy.enableProxy) {
+ logger.info('Initial proxy settings applied successfully', {
+ enableProxy: false,
+ proxyType: networkProxy.proxyType,
+ });
+ return;
+ }
+
// Apply proxy settings
+ const { ProxyDispatcherManager } = await import('../modules/networkProxy/dispatcher');
await ProxyDispatcherManager.applyProxySettings(networkProxy);
logger.info('Initial proxy settings applied successfully', {
@@ -160,6 +171,7 @@ export default class NetworkProxyCtr extends ControllerModule {
logger.error('Failed to apply initial proxy settings:', error);
// Use default settings on error
try {
+ const { ProxyDispatcherManager } = await import('../modules/networkProxy/dispatcher');
await ProxyDispatcherManager.applyProxySettings(defaultProxySettings);
logger.info('Fallback to default proxy settings');
} catch (fallbackError) {
diff --git a/apps/desktop/src/main/controllers/NotificationCtr.ts b/apps/desktop/src/main/controllers/NotificationCtr.ts
index ad9131bd70d..e01c4a2cb76 100644
--- a/apps/desktop/src/main/controllers/NotificationCtr.ts
+++ b/apps/desktop/src/main/controllers/NotificationCtr.ts
@@ -3,10 +3,10 @@ import type {
ShowDesktopNotificationParams,
} from '@lobechat/electron-client-ipc';
import { app, Notification } from 'electron';
-import * as electronIs from 'electron-is';
import { getIpcContext } from '@/utils/ipc';
import { createLogger } from '@/utils/logger';
+import * as electronIs from '@/utils/platform';
import { ControllerModule, IpcMethod } from './index';
diff --git a/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts b/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts
index de48fffc08a..f70c9916f16 100644
--- a/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts
+++ b/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts
@@ -1,7 +1,7 @@
import querystring from 'node:querystring';
import { URL } from 'node:url';
-import type { DataSyncConfig } from '@lobechat/electron-client-ipc';
+import type { DataSyncConfig, DesktopBootstrapIdentity } from '@lobechat/electron-client-ipc';
import { safeStorage, session as electronSession } from 'electron';
import { OFFICIAL_CLOUD_SERVER } from '@/const/env';
@@ -181,6 +181,37 @@ export default class RemoteServerConfigCtr extends ControllerModule {
*/
private lastRefreshAt?: number;
+ /**
+ * Resolve the cache-partition identity synchronously for the renderer preload.
+ * This deliberately avoids `getUserState()`: the encrypted OIDC token already
+ * contains the stable subject required for local isolation.
+ */
+ getDesktopBootstrapIdentity(): DesktopBootstrapIdentity {
+ if (!this.encryptedAccessToken) this.loadTokensFromStore();
+
+ if (!this.encryptedAccessToken) return { isIdentityResolved: true };
+
+ try {
+ const accessToken = safeStorage.isEncryptionAvailable()
+ ? safeStorage.decryptString(Buffer.from(this.encryptedAccessToken, 'base64'))
+ : this.encryptedAccessToken;
+ const parts = accessToken.split('.');
+ if (parts.length !== 3) return { isIdentityResolved: false };
+
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')) as {
+ sub?: unknown;
+ };
+ if (typeof payload.sub !== 'string' || payload.sub.length === 0) {
+ return { isIdentityResolved: false };
+ }
+
+ return { isIdentityResolved: true, userId: payload.sub };
+ } catch (error) {
+ logger.warn('Failed to resolve Desktop bootstrap identity from access token:', error);
+ return { isIdentityResolved: false };
+ }
+ }
+
/**
* Promise representing the ongoing token refresh operation.
* Used to prevent concurrent refreshes and allow callers to wait.
diff --git a/apps/desktop/src/main/controllers/ShellCommandCtr.ts b/apps/desktop/src/main/controllers/ShellCommandCtr.ts
index 2e17919e4dc..2d764ac8974 100644
--- a/apps/desktop/src/main/controllers/ShellCommandCtr.ts
+++ b/apps/desktop/src/main/controllers/ShellCommandCtr.ts
@@ -14,7 +14,7 @@ import {
runCommand,
setWindowsShellPreference,
ShellProcessManager,
-} from '@lobechat/local-file-shell';
+} from '@lobechat/local-file-shell/shell';
import { createLogger } from '@/utils/logger';
diff --git a/apps/desktop/src/main/controllers/SystemCtr.ts b/apps/desktop/src/main/controllers/SystemCtr.ts
index b2016243cf6..20b6a35d8f0 100644
--- a/apps/desktop/src/main/controllers/SystemCtr.ts
+++ b/apps/desktop/src/main/controllers/SystemCtr.ts
@@ -1,14 +1,10 @@
+import { access, readdir } from 'node:fs/promises';
import process from 'node:process';
import type { ElectronAppState, ThemeMode } from '@lobechat/electron-client-ipc';
-import { getShellInfo } from '@lobechat/local-file-shell';
import { app, dialog, nativeTheme, shell } from 'electron';
-import * as electronIs from 'electron-is';
-import { getFonts2 } from 'font-list';
-import { pathExists, readdir } from 'fs-extra';
import { legacyLocalDbDir } from '@/const/dir';
-import { detectRepoType } from '@/utils/git';
import { createLogger } from '@/utils/logger';
import {
getAccessibilityStatus,
@@ -19,6 +15,7 @@ import {
requestMicrophoneAccess,
requestScreenCaptureAccess,
} from '@/utils/permissions';
+import * as electronIs from '@/utils/platform';
import { getSystemLanguage, resolveUILocale } from '@/utils/system-language';
import { ControllerModule, IpcMethod } from './index';
@@ -48,6 +45,7 @@ export default class SystemController extends ControllerModule {
*/
@IpcMethod()
async getAppState(): Promise<ElectronAppState> {
+ const { getShellInfo } = await import('@lobechat/local-file-shell/shell');
const platform = process.platform;
const arch = process.arch;
@@ -200,6 +198,7 @@ export default class SystemController extends ControllerModule {
}
const folderPath = result.filePaths[0];
+ const { detectRepoType } = await import('@lobechat/local-file-shell/git');
const repoType = await detectRepoType(folderPath);
try {
@@ -226,7 +225,8 @@ export default class SystemController extends ControllerModule {
@IpcMethod()
async getSystemMonospaceFonts(): Promise<SystemMonospaceFont[]> {
if (!this.systemMonospaceFontsPromise) {
- this.systemMonospaceFontsPromise = getFonts2()
+ this.systemMonospaceFontsPromise = import('font-list')
+ .then(({ getFonts2 }) => getFonts2())
.then((fonts) => {
const families = new Map<string, SystemMonospaceFont>();
@@ -282,12 +282,12 @@ export default class SystemController extends ControllerModule {
*/
@IpcMethod()
async hasLegacyLocalDb(): Promise<boolean> {
- if (!(await pathExists(legacyLocalDbDir))) return false;
-
try {
+ await access(legacyLocalDbDir);
const entries = await readdir(legacyLocalDbDir);
return entries.length > 0;
- } catch {
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
// If directory exists but cannot be read, treat as "used" to surface guidance.
return true;
}
diff --git a/apps/desktop/src/main/controllers/UpdaterCtr.ts b/apps/desktop/src/main/controllers/UpdaterCtr.ts
index 375f4808f83..01d136ba513 100644
--- a/apps/desktop/src/main/controllers/UpdaterCtr.ts
+++ b/apps/desktop/src/main/controllers/UpdaterCtr.ts
@@ -9,13 +9,20 @@ const logger = createLogger('controllers:UpdaterCtr');
export default class UpdaterCtr extends ControllerModule {
static override readonly groupName = 'autoUpdate';
+
+ private getUpdaterManager() {
+ return this.app.updaterManager
+ ? Promise.resolve(this.app.updaterManager)
+ : this.app.getUpdaterManager();
+ }
+
/**
* Check for updates
*/
@IpcMethod()
async checkForUpdates() {
logger.info('Check for updates requested');
- await this.app.updaterManager.checkForUpdates({ manual: true });
+ await (await this.getUpdaterManager()).checkForUpdates({ manual: true });
}
/**
@@ -24,25 +31,25 @@ export default class UpdaterCtr extends ControllerModule {
@IpcMethod()
async downloadUpdate() {
logger.info('Download update requested');
- await this.app.updaterManager.downloadUpdate();
+ await (await this.getUpdaterManager()).downloadUpdate();
}
/**
* Quit application and install update
*/
@IpcMethod()
- quitAndInstallUpdate() {
+ async quitAndInstallUpdate() {
logger.info('Quit and install update requested');
- this.app.updaterManager.installNow();
+ (await this.getUpdaterManager()).installNow();
}
/**
* Install update on next startup
*/
@IpcMethod()
- installLater() {
+ async installLater() {
logger.info('Install later requested');
- this.app.updaterManager.installLater();
+ (await this.getUpdaterManager()).installLater();
}
@IpcMethod()
@@ -70,11 +77,11 @@ export default class UpdaterCtr extends ControllerModule {
logger.info(`Set update channel requested: ${channel}`);
this.app.storeManager.set('updateChannel', channel);
- this.app.updaterManager.switchChannel(channel);
+ (await this.getUpdaterManager()).switchChannel(channel);
}
@IpcMethod()
async getUpdaterState(): Promise<UpdaterState> {
- return this.app.updaterManager.getUpdaterState();
+ return (await this.getUpdaterManager()).getUpdaterState();
}
}
diff --git a/apps/desktop/src/main/controllers/WorkspaceCtr.ts b/apps/desktop/src/main/controllers/WorkspaceCtr.ts
index ae66c5f4f27..fc1307ae579 100644
--- a/apps/desktop/src/main/controllers/WorkspaceCtr.ts
+++ b/apps/desktop/src/main/controllers/WorkspaceCtr.ts
@@ -1,9 +1,4 @@
import type { WorkspaceScanDeps } from '@lobechat/device-control';
-import {
- initWorkspace as runInitWorkspace,
- listProjectSkills as runListProjectSkills,
- statPath as runStatPath,
-} from '@lobechat/device-control/workspace';
import {
type InitWorkspaceParams,
type InitWorkspaceResult,
@@ -35,11 +30,14 @@ export default class WorkspaceCtr extends ControllerModule {
@IpcMethod()
async listProjectSkills(params: ListProjectSkillsParams): Promise<ListProjectSkillsResult> {
+ const { listProjectSkills: runListProjectSkills } =
+ await import('@lobechat/device-control/workspace');
return runListProjectSkills(params, this.scanDeps);
}
@IpcMethod()
async initWorkspace(params: InitWorkspaceParams): Promise<InitWorkspaceResult> {
+ const { initWorkspace: runInitWorkspace } = await import('@lobechat/device-control/workspace');
return runInitWorkspace(params, this.scanDeps);
}
@@ -47,6 +45,7 @@ export default class WorkspaceCtr extends ControllerModule {
async statPath(params: {
path: string;
}): Promise<{ exists: boolean; isDirectory: boolean; repoType?: 'git' | 'github' }> {
+ const { statPath: runStatPath } = await import('@lobechat/device-control/workspace');
return runStatPath(params);
}
diff --git a/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts
index 8ee954f91ad..8dc5265d2bc 100644
--- a/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/AuthCtr.test.ts
@@ -47,8 +47,8 @@ vi.mock('electron', () => ({
},
}));
-// Mock electron-is
-vi.mock('electron-is', () => ({
+// Mock platform detection
+vi.mock('@/utils/platform', () => ({
macOS: vi.fn(() => false),
windows: vi.fn(() => false),
linux: vi.fn(() => false),
diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
index cb46adb2b5e..35c199945c6 100644
--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts
@@ -165,7 +165,7 @@ vi.mock('@/utils/logger', () => ({
}),
}));
-vi.mock('electron-is', () => ({
+vi.mock('@/utils/platform', () => ({
macOS: vi.fn(() => false),
windows: vi.fn(() => false),
linux: vi.fn(() => false),
@@ -324,7 +324,7 @@ describe('GatewayConnectionCtr', () => {
});
ctr = new GatewayConnectionCtr(mockApp);
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
const options = MockGatewayClient.lastOptions;
@@ -344,7 +344,7 @@ describe('GatewayConnectionCtr', () => {
});
ctr = new GatewayConnectionCtr(mockApp);
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
expect(MockGatewayClient.lastOptions.gatewayUrl).toBe('http://localhost:8787');
@@ -353,7 +353,7 @@ describe('GatewayConnectionCtr', () => {
it('should return success:false when no access token', async () => {
// Prevent auto-connect, then set up providers manually
vi.mocked(mockRemoteServerConfigCtr.isRemoteServerConfigured).mockResolvedValueOnce(false);
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
vi.mocked(mockRemoteServerConfigCtr.getAccessToken).mockResolvedValueOnce(null);
@@ -365,7 +365,7 @@ describe('GatewayConnectionCtr', () => {
it('should persist gatewayEnabled=true on connect', async () => {
vi.mocked(mockRemoteServerConfigCtr.isRemoteServerConfigured).mockResolvedValueOnce(false);
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
mockStoreSet.mockClear();
@@ -374,7 +374,7 @@ describe('GatewayConnectionCtr', () => {
});
it('should no-op when already connected', async () => {
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
const firstClient = MockGatewayClient.lastInstance;
firstClient!.simulateConnected();
@@ -386,7 +386,7 @@ describe('GatewayConnectionCtr', () => {
});
it('should broadcast status changes: disconnected → connecting → connected', async () => {
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
expect(mockBroadcast).toHaveBeenCalledWith('gatewayConnectionStatusChanged', {
status: 'connecting',
@@ -403,7 +403,7 @@ describe('GatewayConnectionCtr', () => {
describe('disconnect', () => {
it('should disconnect client and set status to disconnected', async () => {
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
const client = MockGatewayClient.lastInstance!;
client.simulateConnected();
@@ -418,7 +418,7 @@ describe('GatewayConnectionCtr', () => {
});
it('should persist gatewayEnabled=false on disconnect', async () => {
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
MockGatewayClient.lastInstance!.simulateConnected();
mockStoreSet.mockClear();
@@ -428,7 +428,7 @@ describe('GatewayConnectionCtr', () => {
});
it('should not trigger reconnect after intentional disconnect', async () => {
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
const client = MockGatewayClient.lastInstance!;
client.simulateConnected();
@@ -446,9 +446,9 @@ describe('GatewayConnectionCtr', () => {
// ─── Auto-Connect ───
- describe('afterAppReady (auto-connect)', () => {
+ describe('afterFirstFrame (auto-connect)', () => {
it('should auto-connect when server is configured and token exists', async () => {
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
expect(MockGatewayClient.lastInstance).not.toBeNull();
@@ -462,7 +462,7 @@ describe('GatewayConnectionCtr', () => {
});
ctr = new GatewayConnectionCtr(mockApp);
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
expect(MockGatewayClient.lastInstance).toBeNull();
@@ -471,7 +471,7 @@ describe('GatewayConnectionCtr', () => {
it('should skip auto-connect when remote server not configured', async () => {
vi.mocked(mockRemoteServerConfigCtr.isRemoteServerConfigured).mockResolvedValueOnce(false);
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
expect(MockGatewayClient.lastInstance).toBeNull();
@@ -480,7 +480,7 @@ describe('GatewayConnectionCtr', () => {
it('should skip auto-connect when no access token', async () => {
vi.mocked(mockRemoteServerConfigCtr.getAccessToken).mockResolvedValueOnce(null);
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
expect(MockGatewayClient.lastInstance).toBeNull();
@@ -488,7 +488,7 @@ describe('GatewayConnectionCtr', () => {
it('should create device ID on first launch and persist it', () => {
mockStoreGet.mockReturnValue(undefined);
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
expect(mockStoreSet).toHaveBeenCalledWith('gatewayDeviceId', 'mock-device-uuid');
});
@@ -500,7 +500,7 @@ describe('GatewayConnectionCtr', () => {
return undefined;
});
ctr = new GatewayConnectionCtr(mockApp);
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
expect(mockStoreSet).not.toHaveBeenCalledWith('gatewayDeviceId', expect.anything());
});
@@ -510,7 +510,7 @@ describe('GatewayConnectionCtr', () => {
describe('reconnection', () => {
it('should broadcast reconnecting status when client emits reconnecting', async () => {
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
const client = MockGatewayClient.lastInstance!;
client.simulateConnected();
@@ -528,7 +528,7 @@ describe('GatewayConnectionCtr', () => {
describe('tool call routing', () => {
async function connectAndOpen() {
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
const client = MockGatewayClient.lastInstance!;
client.simulateConnected();
@@ -722,7 +722,7 @@ describe('GatewayConnectionCtr', () => {
describe('message API routing', () => {
async function connectAndOpen() {
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
const client = MockGatewayClient.lastInstance!;
client.simulateConnected();
@@ -784,7 +784,7 @@ describe('GatewayConnectionCtr', () => {
describe('auth_expired handling', () => {
it('should refresh token and reconnect on auth_expired', async () => {
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
const client1 = MockGatewayClient.lastInstance!;
client1.simulateConnected();
@@ -804,7 +804,7 @@ describe('GatewayConnectionCtr', () => {
success: false,
});
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
const client = MockGatewayClient.lastInstance!;
client.simulateConnected();
@@ -823,7 +823,7 @@ describe('GatewayConnectionCtr', () => {
describe('agent run routing', () => {
async function connectAndOpen() {
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
const client = MockGatewayClient.lastInstance!;
client.simulateConnected();
@@ -995,7 +995,7 @@ describe('GatewayConnectionCtr', () => {
}
async function connectAndOpen() {
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
const client = MockGatewayClient.lastInstance!;
client.simulateConnected();
@@ -1118,7 +1118,7 @@ describe('GatewayConnectionCtr', () => {
describe('platform capability probing', () => {
async function connectAndOpen() {
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
const client = MockGatewayClient.lastInstance!;
client.simulateConnected();
@@ -1250,7 +1250,7 @@ describe('GatewayConnectionCtr', () => {
it('should return current status', async () => {
expect(await ctr.getConnectionStatus()).toEqual({ status: 'disconnected' });
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
await vi.advanceTimersByTimeAsync(0);
expect(await ctr.getConnectionStatus()).toEqual({ status: 'connecting' });
@@ -1267,7 +1267,7 @@ describe('GatewayConnectionCtr', () => {
return undefined;
});
ctr = new GatewayConnectionCtr(mockApp);
- ctr.afterAppReady();
+ ctr.afterFirstFrame();
const info = await ctr.getDeviceInfo();
expect(info).toEqual({
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
index 4e7b09842d2..5f2fd6b0802 100644
--- a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentCtr.test.ts
@@ -12,7 +12,7 @@ import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ip
import { app as electronAppMock } from 'electron';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import HeterogeneousAgentCtr from '../HeterogeneousAgentCtr';
+import HeterogeneousAgentCtr from '../HeterogeneousAgentImpl';
vi.mock('node:os', async () => {
const actual = await vi.importActual<typeof os>('node:os');
diff --git a/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentLazyCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentLazyCtr.test.ts
new file mode 100644
index 00000000000..315c3846959
--- /dev/null
+++ b/apps/desktop/src/main/controllers/__tests__/HeterogeneousAgentLazyCtr.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { App } from '@/core/App';
+
+import HeterogeneousAgentCtr from '../HeterogeneousAgentCtr';
+
+const implementationMocks = vi.hoisted(() => ({
+ afterAppReady: vi.fn(),
+ constructor: vi.fn(),
+ startSession: vi.fn(async (..._args: unknown[]) => ({ sessionId: 'session-1' })),
+}));
+
+vi.mock('../HeterogeneousAgentImpl', () => ({
+ default: class MockHeterogeneousAgentImplementation {
+ constructor(app: App) {
+ implementationMocks.constructor(app);
+ }
+
+ afterAppReady() {
+ implementationMocks.afterAppReady();
+ }
+
+ startSession(...args: unknown[]) {
+ return implementationMocks.startSession(...args);
+ }
+ },
+}));
+
+describe('HeterogeneousAgentCtr lazy implementation', () => {
+ it('defers the heavy implementation and initializes it exactly once on first use', async () => {
+ const app = {} as App;
+ const controller = new HeterogeneousAgentCtr(app);
+
+ expect(implementationMocks.constructor).not.toHaveBeenCalled();
+ expect(implementationMocks.afterAppReady).not.toHaveBeenCalled();
+
+ await expect((controller as any).startSession({ prompt: 'first' })).resolves.toEqual({
+ sessionId: 'session-1',
+ });
+ await (controller as any).startSession({ prompt: 'second' });
+
+ expect(implementationMocks.constructor).toHaveBeenCalledOnce();
+ expect(implementationMocks.constructor).toHaveBeenCalledWith(app);
+ expect(implementationMocks.afterAppReady).toHaveBeenCalledOnce();
+ expect(implementationMocks.startSession).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.ts
index d97a8a42851..420c305dbae 100644
--- a/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.ts
@@ -42,8 +42,8 @@ vi.mock('electron', () => {
};
});
-// Mock electron-is
-vi.mock('electron-is', () => ({
+// Mock platform detection
+vi.mock('@/utils/platform', () => ({
linux: vi.fn(() => false),
macOS: vi.fn(() => false),
windows: vi.fn(() => false),
@@ -108,7 +108,7 @@ describe('NotificationCtr', () => {
});
it('should set app user model ID on Windows', async () => {
- const { windows } = await import('electron-is');
+ const { windows } = await import('@/utils/platform');
const { app, Notification } = await import('electron');
vi.mocked(windows).mockReturnValue(true);
vi.mocked(Notification.isSupported).mockReturnValue(true);
@@ -121,7 +121,7 @@ describe('NotificationCtr', () => {
});
it('should handle macOS platform', async () => {
- const { macOS } = await import('electron-is');
+ const { macOS } = await import('@/utils/platform');
const { Notification } = await import('electron');
vi.mocked(macOS).mockReturnValue(true);
vi.mocked(Notification.isSupported).mockReturnValue(true);
@@ -206,7 +206,7 @@ describe('NotificationCtr', () => {
});
it('should use low urgency on Linux to prevent GNOME Shell freeze', async () => {
- const { linux } = await import('electron-is');
+ const { linux } = await import('@/utils/platform');
const { Notification } = await import('electron');
vi.mocked(linux).mockReturnValue(true);
vi.mocked(Notification.isSupported).mockReturnValue(true);
@@ -293,7 +293,7 @@ describe('NotificationCtr', () => {
it('should bounce dock on macOS when attention is requested', async () => {
const { app, Notification } = await import('electron');
- const { macOS } = await import('electron-is');
+ const { macOS } = await import('@/utils/platform');
vi.mocked(macOS).mockReturnValue(true);
vi.mocked(Notification.isSupported).mockReturnValue(true);
mockBrowserWindow.isVisible.mockReturnValue(false);
diff --git a/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts
index 036e128d2fd..2d5eb84d1ab 100644
--- a/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts
@@ -184,6 +184,30 @@ describe('RemoteServerConfigCtr', () => {
});
});
+ describe('getDesktopBootstrapIdentity', () => {
+ const createAccessToken = (sub: string) =>
+ ['header', Buffer.from(JSON.stringify({ sub })).toString('base64url'), 'signature'].join('.');
+
+ it('returns the OIDC subject without requesting full user state', async () => {
+ await controller.saveTokens(createAccessToken('user-bootstrap'), 'refresh-token');
+
+ expect(controller.getDesktopBootstrapIdentity()).toEqual({
+ isIdentityResolved: true,
+ userId: 'user-bootstrap',
+ });
+ });
+
+ it('resolves to signed-out when no encrypted token exists', () => {
+ expect(controller.getDesktopBootstrapIdentity()).toEqual({ isIdentityResolved: true });
+ });
+
+ it('keeps the cache scope untrusted when the stored token cannot identify a subject', async () => {
+ await controller.saveTokens('not-a-jwt', 'refresh-token');
+
+ expect(controller.getDesktopBootstrapIdentity()).toEqual({ isIdentityResolved: false });
+ });
+ });
+
describe('getAccessToken', () => {
it('should return decrypted access token', async () => {
const { safeStorage } = await import('electron');
diff --git a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts
index 6953d127404..bad82868716 100644
--- a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts
@@ -92,8 +92,8 @@ vi.mock('electron', () => ({
},
}));
-// Mock electron-is
-vi.mock('electron-is', () => ({
+// Mock platform detection
+vi.mock('@/utils/platform', () => ({
macOS: vi.fn(() => true),
}));
@@ -216,7 +216,7 @@ describe('SystemController', () => {
});
it('should return true on non-macOS when requesting accessibility access', async () => {
- const { macOS } = await import('electron-is');
+ const { macOS } = await import('@/utils/platform');
vi.mocked(macOS).mockReturnValue(false);
// Clear the injected module to simulate non-macOS behavior
__setMacPermissionsModule(null);
@@ -275,7 +275,7 @@ describe('SystemController', () => {
});
it('should return true on non-macOS', async () => {
- const { macOS } = await import('electron-is');
+ const { macOS } = await import('@/utils/platform');
const { shell } = await import('electron');
vi.mocked(macOS).mockReturnValue(false);
// Clear the injected module to simulate non-macOS behavior
@@ -314,7 +314,7 @@ describe('SystemController', () => {
});
it('should return true on non-macOS and not open settings', async () => {
- const { macOS } = await import('electron-is');
+ const { macOS } = await import('@/utils/platform');
vi.mocked(macOS).mockReturnValue(false);
const result = await invokeIpc('system.requestScreenAccess');
@@ -349,7 +349,7 @@ describe('SystemController', () => {
});
it('should return true on non-macOS', async () => {
- const { macOS } = await import('electron-is');
+ const { macOS } = await import('@/utils/platform');
vi.mocked(macOS).mockReturnValue(false);
const result = await invokeIpc('system.getFullDiskAccessStatus');
diff --git a/apps/desktop/src/main/controllers/__tests__/UpdaterCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/UpdaterCtr.test.ts
index fad8ab0cc83..83c97c1d537 100644
--- a/apps/desktop/src/main/controllers/__tests__/UpdaterCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/UpdaterCtr.test.ts
@@ -77,15 +77,15 @@ describe('UpdaterCtr', () => {
});
describe('quitAndInstallUpdate', () => {
- it('should call updaterManager.installNow', () => {
- updaterCtr.quitAndInstallUpdate();
+ it('should call updaterManager.installNow', async () => {
+ await updaterCtr.quitAndInstallUpdate();
expect(mockInstallNow).toHaveBeenCalled();
});
});
describe('installLater', () => {
- it('should call updaterManager.installLater', () => {
- updaterCtr.installLater();
+ it('should call updaterManager.installLater', async () => {
+ await updaterCtr.installLater();
expect(mockInstallLater).toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/main/controllers/index.ts b/apps/desktop/src/main/controllers/index.ts
index d575358c7b6..05d2119bef7 100644
--- a/apps/desktop/src/main/controllers/index.ts
+++ b/apps/desktop/src/main/controllers/index.ts
@@ -39,9 +39,10 @@ export const createProtocolHandler = (urlType: string) => (action: string) =>
protocolDecorator(urlType, action);
interface IControllerModule {
- afterAppReady?: () => void;
+ afterAppReady?: () => Promise<void> | void;
+ afterFirstFrame?: () => Promise<void> | void;
app: App;
- beforeAppReady?: () => void;
+ beforeAppReady?: () => Promise<void> | void;
}
export class ControllerModule extends IpcService implements IControllerModule {
diff --git a/apps/desktop/src/main/core/App.ts b/apps/desktop/src/main/core/App.ts
index 4edef2c1f83..0c32f08c4b5 100644
--- a/apps/desktop/src/main/core/App.ts
+++ b/apps/desktop/src/main/core/App.ts
@@ -1,16 +1,17 @@
import os from 'node:os';
import path from 'node:path';
+import type { DesktopBootProfilePayload } from '@lobechat/electron-client-ipc';
import type { ElectronIPCEventHandler } from '@lobechat/electron-server-ipc';
import { ElectronIPCServer } from '@lobechat/electron-server-ipc';
-import { app, nativeTheme, protocol } from 'electron';
-import * as electronIs from 'electron-is';
+import { app, ipcMain, nativeTheme, protocol } from 'electron';
import { name } from '@/../../package.json';
import { binDir, buildDir } from '@/const/dir';
import { isDev } from '@/const/env';
import type { IControlModule } from '@/controllers';
import AuthCtr from '@/controllers/AuthCtr';
+import RemoteServerConfigCtr from '@/controllers/RemoteServerConfigCtr';
import {
astSearchBinaries,
type BinaryCategory,
@@ -25,6 +26,8 @@ import { generateCliWrapper, getCliWrapperDir } from '@/modules/cliEmbedding';
import { ScreenCaptureManager } from '@/modules/screenCapture/ScreenCaptureManager';
import type { IServiceModule, ServiceLifecycle, ServiceModule } from '@/services';
import { createLogger } from '@/utils/logger';
+import * as electronIs from '@/utils/platform';
+import { refreshShellPath } from '@/utils/shellPath';
import { BrowserManager } from './browser/BrowserManager';
import { backendProxyProtocolManager } from './infrastructure/BackendProxyProtocolManager';
@@ -36,12 +39,13 @@ import { ProtocolManager } from './infrastructure/ProtocolManager';
import { RendererUrlManager } from './infrastructure/RendererUrlManager';
import { StaticFileServerManager } from './infrastructure/StaticFileServerManager';
import { StoreManager } from './infrastructure/StoreManager';
-import { UpdaterManager } from './infrastructure/UpdaterManager';
+import type { UpdaterManager } from './infrastructure/UpdaterManager';
import { MenuManager } from './ui/MenuManager';
import { ShortcutManager } from './ui/ShortcutManager';
import { TrayManager } from './ui/TrayManager';
const logger = createLogger('core:App');
+const mainProcessStartedAt = Date.now() - process.uptime() * 1000;
export type IPCEventMap = Map<string, { controller: any; methodName: string }>;
export type ShortcutMethodMap = Map<string, () => Promise<void>>;
@@ -56,7 +60,7 @@ export class App {
menuManager: MenuManager;
i18n: I18nManager;
storeManager: StoreManager;
- updaterManager: UpdaterManager;
+ updaterManager!: UpdaterManager;
shortcutManager: ShortcutManager;
trayManager: TrayManager;
staticFileServerManager: StaticFileServerManager;
@@ -127,6 +131,8 @@ export class App {
logger.debug(`Loading ${controllers.length} controllers`);
controllers.forEach((controller) => this.addController(controller));
+ this.initializeBootstrapIpc();
+ this.initializeBootProfileIpc();
// load services
const services: IServiceModule[] = importAll(
@@ -141,7 +147,6 @@ export class App {
this.i18n = new I18nManager(this);
this.browserManager = new BrowserManager(this);
this.menuManager = new MenuManager(this);
- this.updaterManager = new UpdaterManager(this);
this.shortcutManager = new ShortcutManager(this);
this.trayManager = new TrayManager(this);
this.staticFileServerManager = new StaticFileServerManager(this);
@@ -231,12 +236,72 @@ export class App {
this.initDevBranding();
- // ==============
- await this.ipcServer.start();
- logger.debug('IPC server started');
+ // The CLI socket is independent from renderer navigation. Start it in
+ // parallel instead of placing it on the first-window critical path.
+ const ipcServerPromise = this.ipcServer
+ .start()
+ .then(() => {
+ logger.debug('IPC server started');
+ })
+ .catch((error) => {
+ logger.error('Failed to start IPC server:', error);
+ });
- // Initialize app
+ // Reach Electron ready state, then create the main BrowserWindow before
+ // native menus, local-file services, tray and updater initialization.
await this.makeAppReady();
+ await this.browserManager.initializeBrowsers();
+ await this.runControllerHooks('afterAppReady');
+
+ const initializeNativeShell = async () => {
+ await Promise.all([
+ this.i18n.init(),
+ this.staticFileServerManager.initialize(),
+ ipcServerPromise,
+ this.getUpdaterManager(),
+ ]);
+ this.menuManager.initialize();
+ };
+
+ // Set global application exit state and lifecycle listeners immediately.
+ this.isQuiting = false;
+
+ app.on('window-all-closed', () => {
+ if (electronIs.windows() || process.platform === 'linux') {
+ logger.info(`All windows closed, quitting application (${process.platform})`);
+ app.quit();
+ }
+ });
+
+ app.on('activate', this.onActivate);
+
+ // Deep links should be actionable as soon as the main window exists.
+ void this.protocolManager.processPendingUrls().catch((error) => {
+ logger.error('Failed to process pending protocol URLs:', error);
+ });
+
+ // Work that can trigger disk, network, native permission, or UI setup is
+ // delayed until Chromium presents its first frame, preventing contention
+ // with bundle parsing and the first React commit.
+ void this.initializeAfterFirstFrame(initializeNativeShell).catch((error) => {
+ logger.error('Post-first-frame initialization failed:', error);
+ });
+
+ logger.info('Application bootstrap scheduled');
+ };
+
+ private initializeAfterFirstFrame = async (initializeNativeShell: () => Promise<void>) => {
+ await this.browserManager.waitForMainWindowFirstFrame();
+
+ // GUI-launched apps do not inherit the user's login-shell PATH. Resolve it
+ // asynchronously after the first frame so shell startup never blocks the
+ // main process -> renderer navigation critical path.
+ void refreshShellPath().catch((error) => {
+ logger.warn('Failed to refresh PATH from the login shell:', error);
+ });
+
+ await Promise.all([initializeNativeShell(), this.runControllerHooks('afterFirstFrame')]);
+ this.shortcutManager.initialize();
// Generate CLI wrapper for terminal usage
generateCliWrapper().catch((error) => {
@@ -257,40 +322,14 @@ export class App {
logger.warn('[agent-browser] background ensure failed:', error);
});
- // Initialize i18n. Note: app.getLocale() must be called after app.whenReady() to get the correct value
- await this.i18n.init();
- this.menuManager.initialize();
-
- // Initialize static file manager
- await this.staticFileServerManager.initialize();
-
- // Initialize global shortcuts: globalShortcut must be called after app.whenReady()
- this.shortcutManager.initialize();
-
- await this.browserManager.initializeBrowsers();
-
// Initialize tray manager on all platforms (macOS menu bar, Windows / Linux tray).
this.trayManager.initializeTrays();
// Initialize updater manager
await this.updaterManager.initialize();
+ this.screenCaptureManager.prewarmPermissionCheck();
- // Set global application exit state
- this.isQuiting = false;
-
- app.on('window-all-closed', () => {
- if (electronIs.windows() || process.platform === 'linux') {
- logger.info(`All windows closed, quitting application (${process.platform})`);
- app.quit();
- }
- });
-
- app.on('activate', this.onActivate);
-
- // Process any pending protocol URLs after everything is ready
- await this.protocolManager.processPendingUrls();
-
- logger.info('Application bootstrap completed');
+ logger.info('Post-first-frame initialization completed');
};
getService<T>(serviceClass: Class<T>): T {
@@ -301,6 +340,21 @@ export class App {
return this.controllers.get(controllerClass);
}
+ private updaterManagerPromise?: Promise<UpdaterManager>;
+
+ getUpdaterManager = async (): Promise<UpdaterManager> => {
+ if (this.updaterManager) return this.updaterManager;
+
+ this.updaterManagerPromise ??= import('./infrastructure/UpdaterManager').then(
+ ({ UpdaterManager }) => {
+ this.updaterManager = new UpdaterManager(this);
+ return this.updaterManager;
+ },
+ );
+
+ return this.updaterManagerPromise;
+ };
+
/**
* Handle protocol request by dispatching to registered handlers
* @param urlType Protocol URL type (e.g., 'plugin')
@@ -345,16 +399,18 @@ export class App {
*/
private makeAppReady = async () => {
logger.debug('Preparing application ready state');
- this.controllers.forEach((controller) => {
- if (typeof controller.beforeAppReady === 'function') {
+ await Promise.all(
+ [...this.controllers.values()].map(async (controller) => {
+ if (typeof controller.beforeAppReady !== 'function') return;
+
try {
- controller.beforeAppReady();
+ await controller.beforeAppReady();
} catch (error) {
logger.error(`Error in controller.beforeAppReady:`, error);
console.error(`[App] Error in controller.beforeAppReady:`, error);
}
- }
- });
+ }),
+ );
// refs: https://github.com/lobehub/lobe-chat/pull/7883
// https://github.com/electron/electron/issues/46538#issuecomment-2808806722
@@ -366,19 +422,23 @@ export class App {
await app.whenReady();
logger.debug('Application ready');
- this.controllers.forEach((controller) => {
- if (typeof controller.afterAppReady === 'function') {
+ logger.info('Application ready state completed');
+ };
+
+ private runControllerHooks = async (hookName: 'afterAppReady' | 'afterFirstFrame') => {
+ await Promise.all(
+ [...this.controllers.values()].map(async (controller) => {
+ const hook = controller[hookName];
+ if (typeof hook !== 'function') return;
+
try {
- controller.afterAppReady();
+ await hook.call(controller);
} catch (error) {
- logger.error(`Error in controller.afterAppReady:`, error);
- console.error(`[App] Error in controller.beforeAppReady:`, error);
+ logger.error(`Error in controller.${hookName}:`, error);
+ console.error(`[App] Error in controller.${hookName}:`, error);
}
- }
- });
- this.screenCaptureManager.prewarmPermissionCheck();
-
- logger.info('Application ready state completed');
+ }),
+ );
};
// ============= helper ============= //
@@ -460,6 +520,46 @@ export class App {
this.ipcServer = new ElectronIPCServer(ipcId, ipcServerEvents);
}
+ private initializeBootstrapIpc() {
+ ipcMain.on('desktop:get-bootstrap-identity', (event) => {
+ const controller = this.getController(RemoteServerConfigCtr);
+ event.returnValue = controller?.getDesktopBootstrapIdentity() ?? {
+ isIdentityResolved: false,
+ };
+ });
+ }
+
+ private initializeBootProfileIpc() {
+ ipcMain.on('desktop:boot-profile-ready', (_event, payload: DesktopBootProfilePayload) => {
+ if (process.env.LOBE_DESKTOP_BOOT_PROFILE !== '1') return;
+
+ const values = [
+ payload?.navigationStartedAt,
+ payload?.domContentLoadedMs,
+ payload?.loadingScreenRemovedMs,
+ payload?.firstVisibleFrameMs,
+ ];
+ if (!values.every((value) => Number.isFinite(value) && value >= 0)) return;
+
+ const processToNavigationMs = payload.navigationStartedAt - mainProcessStartedAt;
+ const navigationToDomContentLoadedMs = payload.domContentLoadedMs;
+ const domContentLoadedToLoadingRemovedMs =
+ payload.loadingScreenRemovedMs - payload.domContentLoadedMs;
+ const loadingRemovedToVisibleFrameMs =
+ payload.firstVisibleFrameMs - payload.loadingScreenRemovedMs;
+
+ console.info(
+ `__LOBE_DESKTOP_BOOT_PROFILE__${JSON.stringify({
+ domContentLoadedToLoadingRemovedMs,
+ loadingRemovedToVisibleFrameMs,
+ navigationToDomContentLoadedMs,
+ processToNavigationMs,
+ totalMs: processToNavigationMs + payload.firstVisibleFrameMs,
+ })}`,
+ );
+ });
+ }
+
// Add before-quit handler function
private handleBeforeQuit = () => {
logger.info('Application is preparing to quit');
diff --git a/apps/desktop/src/main/core/__tests__/App.test.ts b/apps/desktop/src/main/core/__tests__/App.test.ts
index 22ff8dc12db..4132cdc72c8 100644
--- a/apps/desktop/src/main/core/__tests__/App.test.ts
+++ b/apps/desktop/src/main/core/__tests__/App.test.ts
@@ -1,4 +1,4 @@
-import { app as electronApp } from 'electron';
+import { app as electronApp, ipcMain } from 'electron';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
// Import after mocks are set up
@@ -68,7 +68,7 @@ vi.mock('~common/routes', () => ({
}));
// Mock other dependencies
-vi.mock('electron-is', () => ({
+vi.mock('@/utils/platform', () => ({
macOS: vi.fn(() => false),
windows: vi.fn(() => false),
}));
@@ -208,4 +208,19 @@ describe('App', () => {
expect(destroy).toHaveBeenCalledOnce();
});
});
+
+ describe('desktop bootstrap identity', () => {
+ it('responds through the registered controller without an elided runtime symbol', () => {
+ appInstance = new App();
+ const listener = vi
+ .mocked(ipcMain.on)
+ .mock.calls.findLast(
+ ([channel]) => channel === 'desktop:get-bootstrap-identity',
+ )?.[1] as (event: { returnValue?: unknown }) => void;
+ const event: { returnValue?: unknown } = {};
+
+ expect(() => listener(event)).not.toThrow();
+ expect(event.returnValue).toEqual({ isIdentityResolved: true });
+ });
+ });
});
diff --git a/apps/desktop/src/main/core/browser/Browser.ts b/apps/desktop/src/main/core/browser/Browser.ts
index caaec3510d6..926caa9c2b1 100644
--- a/apps/desktop/src/main/core/browser/Browser.ts
+++ b/apps/desktop/src/main/core/browser/Browser.ts
@@ -84,6 +84,11 @@ export default class Browser {
private readonly themeManager: WindowThemeManager;
private _browserWindow?: BrowserWindow;
+ private hasPresentedFirstFrame = false;
+ private resolveFirstFrame!: () => void;
+ private readonly firstFramePromise = new Promise<void>((resolve) => {
+ this.resolveFirstFrame = resolve;
+ });
readonly identifier: string;
readonly options: BrowserWindowOpts;
@@ -250,14 +255,12 @@ export default class Browser {
}
private initiateContentLoading(): void {
- logger.debug(`[${this.identifier}] Initiating placeholder and URL loading sequence.`);
- this.loadPlaceholder().then(() => {
- this.loadUrl(this.options.path).catch((e) => {
- logger.error(
- `[${this.identifier}] Initial loadUrl error for path '${this.options.path}':`,
- e,
- );
- });
+ logger.debug(`[${this.identifier}] Loading initial renderer URL directly.`);
+ this.loadUrl(this.options.path).catch((e) => {
+ logger.error(
+ `[${this.identifier}] Initial loadUrl error for path '${this.options.path}':`,
+ e,
+ );
});
}
@@ -330,6 +333,8 @@ export default class Browser {
logger.debug(`[${this.identifier}] Setting up 'ready-to-show' event listener.`);
browserWindow.once('ready-to-show', () => {
logger.debug(`[${this.identifier}] Window 'ready-to-show' event fired.`);
+ this.hasPresentedFirstFrame = true;
+ this.resolveFirstFrame();
if (this.options.showOnInit) {
logger.debug(`Showing window ${this.identifier} because showOnInit is true.`);
this.show();
@@ -515,6 +520,21 @@ export default class Browser {
logger.debug(`[${this.identifier}] Splash screen placeholder loaded.`);
};
+ /** Wait until Chromium has produced a presentable frame, with a safety timeout. */
+ waitForFirstFrame = async (timeoutMs: number = 5000): Promise<void> => {
+ if (this.hasPresentedFirstFrame) return;
+
+ let timeout: NodeJS.Timeout | undefined;
+ await Promise.race([
+ this.firstFramePromise,
+ new Promise<void>((resolve) => {
+ timeout = setTimeout(resolve, timeoutMs);
+ timeout.unref?.();
+ }),
+ ]);
+ if (timeout) clearTimeout(timeout);
+ };
+
loadUrl = async (path: string): Promise<void> => {
const initUrl = await this.app.buildRendererUrl(path);
const urlWithLocale = this.buildUrlWithLocale(initUrl);
diff --git a/apps/desktop/src/main/core/browser/BrowserManager.ts b/apps/desktop/src/main/core/browser/BrowserManager.ts
index 074b994568d..022b0b69679 100644
--- a/apps/desktop/src/main/core/browser/BrowserManager.ts
+++ b/apps/desktop/src/main/core/browser/BrowserManager.ts
@@ -50,6 +50,10 @@ export class BrowserManager {
window.focus();
}
+ waitForMainWindowFirstFrame(timeoutMs?: number): Promise<void> {
+ return this.getMainWindow().waitForFirstFrame(timeoutMs);
+ }
+
broadcastToAllWindows = <T extends MainBroadcastEventKey>(
event: T,
data: MainBroadcastParams<T>,
diff --git a/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts b/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
index b7050b0fbe5..ec985a355ea 100644
--- a/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
+++ b/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
@@ -236,7 +236,7 @@ describe('Browser', () => {
} as unknown as AppCore;
browser = new Browser(defaultOptions, mockApp);
- // The constructor triggers an async placeholder->loadUrl chain; stub it to avoid cross-test flakiness.
+ // The constructor starts the initial renderer navigation asynchronously.
autoLoadUrlSpy = vi.spyOn(browser, 'loadUrl').mockResolvedValue(undefined as any);
});
@@ -293,6 +293,17 @@ describe('Browser', () => {
it('should create BrowserWindow on construction', () => {
expect(MockBrowserWindow).toHaveBeenCalled();
});
+
+ it('loads the renderer directly without a splash-page navigation', async () => {
+ await vi.waitFor(() => {
+ expect(mockBrowserWindow.loadURL).toHaveBeenCalledWith(
+ 'http://localhost:3000/test?lng=en-US',
+ );
+ });
+
+ expect(mockBrowserWindow.loadURL).toHaveBeenCalledTimes(1);
+ expect(mockBrowserWindow.loadFile).not.toHaveBeenCalledWith('/mock/resources/splash.html');
+ });
});
describe('browserWindow getter', () => {
diff --git a/apps/desktop/src/main/core/browser/__tests__/BrowserManager.test.ts b/apps/desktop/src/main/core/browser/__tests__/BrowserManager.test.ts
index c9f21d914b4..5f98bb0ca5a 100644
--- a/apps/desktop/src/main/core/browser/__tests__/BrowserManager.test.ts
+++ b/apps/desktop/src/main/core/browser/__tests__/BrowserManager.test.ts
@@ -29,6 +29,7 @@ const { MockBrowser, mockAppBrowsers, mockWindowTemplates } = vi.hoisted(() => {
loadUrl: vi.fn().mockResolvedValue(undefined),
options,
show: vi.fn(),
+ waitForFirstFrame: vi.fn().mockResolvedValue(undefined),
webContents: browserWindow.webContents,
};
});
@@ -159,6 +160,14 @@ describe('BrowserManager', () => {
});
});
+ it('waits for the main window first frame before deferred initialization', async () => {
+ const mainWindow = manager.getMainWindow();
+
+ await manager.waitForMainWindowFirstFrame(2500);
+
+ expect(mainWindow.waitForFirstFrame).toHaveBeenCalledWith(2500);
+ });
+
describe('retrieveByIdentifier', () => {
it('should return existing browser', () => {
// First call creates the browser
diff --git a/apps/desktop/src/main/core/infrastructure/I18nManager.ts b/apps/desktop/src/main/core/infrastructure/I18nManager.ts
index 55bed1d0081..786e8dcf648 100644
--- a/apps/desktop/src/main/core/infrastructure/I18nManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/I18nManager.ts
@@ -1,4 +1,4 @@
-import i18next from 'i18next';
+import type { i18n as I18NextInstance } from 'i18next';
import type { App } from '@/core/App';
import { loadResources } from '@/locales/resources';
@@ -9,25 +9,38 @@ import { resolveUILocale } from '@/utils/system-language';
const logger = createLogger('core:I18nManager');
export class I18nManager {
- private i18n: typeof i18next;
+ private i18n?: I18NextInstance;
+ private initializationPromise?: Promise<I18NextInstance>;
private initialized: boolean = false;
private app: App;
constructor(app: App) {
logger.debug('Initializing I18nManager');
this.app = app;
- this.i18n = i18next.createInstance();
}
/**
* Initialize i18next instance
*/
- async init(lang?: string) {
+ async init(lang?: string): Promise<I18NextInstance> {
if (this.initialized) {
logger.debug('I18nManager already initialized, skipping');
- return this.i18n;
+ return this.getI18n();
}
+ this.initializationPromise ??= this.initialize(lang).catch((error) => {
+ this.initializationPromise = undefined;
+ throw error;
+ });
+
+ return this.initializationPromise;
+ }
+
+ private initialize = async (lang?: string): Promise<I18NextInstance> => {
+ const { default: i18next } = await import('i18next');
+ const i18n = i18next.createInstance();
+ this.i18n = i18n;
+
// Priority: parameter language > stored locale > system language
const storedLocale = this.app.storeManager.get('locale', 'auto') as string;
const defaultLanguage = lang || resolveUILocale(storedLocale);
@@ -36,7 +49,7 @@ export class I18nManager {
`Initializing i18n, app locale: ${defaultLanguage}, stored locale: ${storedLocale}`,
);
- await this.i18n.init({
+ await i18n.init({
defaultNS: 'menu',
fallbackLng: 'en',
// Load resources as needed
@@ -51,30 +64,36 @@ export class I18nManager {
partialBundledLanguages: true,
});
- logger.info(`i18n initialized, language: ${this.i18n.language}`);
+ logger.info(`i18n initialized, language: ${i18n.language}`);
// Preload base namespaces
- await this.loadLocale(this.i18n.language);
+ await this.loadLocale(i18n.language);
this.initialized = true;
this.refreshMainUI();
// Listen for language change events
- this.i18n.on('languageChanged', this.handleLanguageChanged);
+ i18n.on('languageChanged', this.handleLanguageChanged);
+ return i18n;
+ };
+
+ private getI18n = (): I18NextInstance => {
+ if (!this.i18n) throw new Error('I18nManager has not been initialized');
return this.i18n;
- }
+ };
/**
* Basic translation function
*/
t = (key: string, options?: any) => {
- const result = this.i18n.t(key, options) as string;
+ const i18n = this.getI18n();
+ const result = i18n.t(key, options) as string;
// If translation result is the same as key, translation might be missing
if (result === key) {
- logger.warn(`${this.i18n.language} key: ${key} is not found`);
+ logger.warn(`${i18n.language} key: ${key} is not found`);
}
return result;
@@ -105,7 +124,7 @@ export class I18nManager {
* Get current language
*/
getCurrentLanguage() {
- return this.i18n.language;
+ return this.getI18n().language;
}
/**
@@ -119,7 +138,7 @@ export class I18nManager {
await this.init();
}
- await this.i18n.changeLanguage(lng);
+ await this.getI18n().changeLanguage(lng);
// Language change event will trigger handleLanguageChanged
}
@@ -163,7 +182,7 @@ export class I18nManager {
logger.debug(`Loading namespace: ${lng}/${ns}`);
const resources = await loadResources(lng, ns);
- this.i18n.addResourceBundle(lng, ns, resources, true, true);
+ this.getI18n().addResourceBundle(lng, ns, resources, true, true);
return true;
} catch (error) {
logger.error(`Failed to load namespace: ${lng}/${ns}`, error);
diff --git a/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts
index 425f09d99d9..6da550f7911 100644
--- a/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/RendererProtocolManager.ts
@@ -1,9 +1,9 @@
+import { existsSync } from 'node:fs';
import { readFile, stat } from 'node:fs/promises';
import path from 'node:path';
import { tryGetMimeType } from '@lobechat/utils/mimeType';
import { app, protocol } from 'electron';
-import { pathExistsSync } from 'fs-extra';
import { createLogger } from '@/utils/logger';
@@ -126,7 +126,7 @@ export class StaticRendererFallback implements RendererFallbackStrategy {
this.rendererDir = rendererDir;
this.resolveRendererFilePath = resolveRendererFilePath;
- if (!pathExistsSync(this.rendererDir)) {
+ if (!existsSync(this.rendererDir)) {
this.logger.warn(`Renderer directory not found: ${this.rendererDir}`);
}
}
diff --git a/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts b/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts
index a4d930197ee..555256588ff 100644
--- a/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/RendererUrlManager.ts
@@ -1,7 +1,6 @@
+import { existsSync } from 'node:fs';
import path from 'node:path';
-import { pathExistsSync } from 'fs-extra';
-
import { rendererDir } from '@/const/dir';
import { isDev } from '@/const/env';
import { getDesktopEnv } from '@/env';
@@ -77,7 +76,7 @@ export class RendererUrlManager {
// Static assets: direct file mapping
if (pathname.startsWith('/assets/') || path.extname(pathname)) {
const filePath = path.join(rendererDir, pathname);
- return pathExistsSync(filePath) ? filePath : null;
+ return existsSync(filePath) ? filePath : null;
}
// Overlay entry (separate MPA page)
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts
index 81814f1b9f2..58ac440f99e 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/BackendProxyProtocolManager.test.ts
@@ -10,7 +10,7 @@ interface RequestInitWithDuplex extends RequestInit {
type FetchMock = (input: RequestInfo | URL, init?: RequestInitWithDuplex) => Promise<Response>;
-vi.mock('electron-is', () => ({
+vi.mock('@/utils/platform', () => ({
dev: vi.fn(() => false),
macOS: vi.fn(() => false),
windows: vi.fn(() => false),
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/I18nManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/I18nManager.test.ts
index 7a07fe9f185..19acb6121b1 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/I18nManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/I18nManager.test.ts
@@ -93,8 +93,8 @@ describe('I18nManager', () => {
});
describe('constructor', () => {
- it('should create i18next instance', () => {
- expect(mockCreateInstance).toHaveBeenCalled();
+ it('should defer creating the i18next instance until initialization', () => {
+ expect(mockCreateInstance).not.toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/RendererProtocolManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/RendererProtocolManager.test.ts
index 57894dc4cf1..a1339e83ad9 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/RendererProtocolManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/RendererProtocolManager.test.ts
@@ -42,8 +42,8 @@ vi.mock('electron', () => ({
protocol: mockProtocol,
}));
-vi.mock('fs-extra', () => ({
- pathExistsSync: mockPathExistsSync,
+vi.mock('node:fs', () => ({
+ existsSync: mockPathExistsSync,
}));
vi.mock('node:fs/promises', () => ({
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/RendererUrlManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/RendererUrlManager.test.ts
index 440b279f3ef..fd205572bcf 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/RendererUrlManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/RendererUrlManager.test.ts
@@ -16,8 +16,8 @@ vi.mock('electron', () => ({
},
}));
-vi.mock('fs-extra', () => ({
- pathExistsSync: (...args: any[]) => mockPathExistsSync(...args),
+vi.mock('node:fs', () => ({
+ existsSync: (...args: any[]) => mockPathExistsSync(...args),
}));
vi.mock('@/const/dir', () => ({
diff --git a/apps/desktop/src/main/index.test.ts b/apps/desktop/src/main/index.test.ts
new file mode 100644
index 00000000000..5d27c575cf9
--- /dev/null
+++ b/apps/desktop/src/main/index.test.ts
@@ -0,0 +1,47 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { appBootstrap, appConstructor, installProcessErrorHandlers } = vi.hoisted(() => ({
+ appBootstrap: vi.fn(),
+ appConstructor: vi.fn(),
+ installProcessErrorHandlers: vi.fn(),
+}));
+
+vi.mock('./pre-app-init', () => ({}));
+
+vi.mock('./core/App', () => ({
+ App: class {
+ bootstrap = appBootstrap;
+
+ constructor() {
+ appConstructor();
+ }
+ },
+}));
+
+vi.mock('./process-error-handlers', () => ({ installProcessErrorHandlers }));
+
+const bootstrapKey = '__LOBEHUB_DESKTOP_MAIN_BOOTSTRAPPED__';
+const mainProcessGlobal = globalThis as typeof globalThis & Record<string, boolean | undefined>;
+
+describe('main process entry', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.resetModules();
+ delete mainProcessGlobal[bootstrapKey];
+ });
+
+ afterEach(() => {
+ delete mainProcessGlobal[bootstrapKey];
+ });
+
+ it('initializes the application only once when the entry module is evaluated again', async () => {
+ await import('./index');
+
+ vi.resetModules();
+ await import('./index');
+
+ expect(installProcessErrorHandlers).toHaveBeenCalledTimes(1);
+ expect(appConstructor).toHaveBeenCalledTimes(1);
+ expect(appBootstrap).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 0d71b9abb97..b82859a50cd 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -1,15 +1,25 @@
import './pre-app-init';
-import fixPath from 'fix-path';
-
import { App } from './core/App';
import { installProcessErrorHandlers } from './process-error-handlers';
-// Guard the main process against transient network blips (Wi-Fi/VPN switch,
-// system sleep) emitted by Electron's net stack as uncaught exceptions.
-installProcessErrorHandlers();
+const mainBootstrapKey = '__LOBEHUB_DESKTOP_MAIN_BOOTSTRAPPED__' as const;
+const mainProcessGlobal = globalThis as typeof globalThis & {
+ [mainBootstrapKey]?: boolean;
+};
+
+// Rolldown may make a deferred CommonJS chunk reference exports that remain in
+// the main entry. Electron does not cache its entry exactly like a normal CJS
+// require, so that back-reference can evaluate this module again. Keep the
+// entry side effects idempotent as a correctness backstop while shared modules
+// are assigned to neutral chunks in the Vite config.
+if (!mainProcessGlobal[mainBootstrapKey]) {
+ mainProcessGlobal[mainBootstrapKey] = true;
-const app = new App();
+ // Guard the main process against transient network blips (Wi-Fi/VPN switch,
+ // system sleep) emitted by Electron's net stack as uncaught exceptions.
+ installProcessErrorHandlers();
-fixPath();
-app.bootstrap();
+ const app = new App();
+ void app.bootstrap();
+}
diff --git a/apps/desktop/src/main/menus/impls/macOS.test.ts b/apps/desktop/src/main/menus/impls/macOS.test.ts
index 6b4bdc1025e..4071fa0f635 100644
--- a/apps/desktop/src/main/menus/impls/macOS.test.ts
+++ b/apps/desktop/src/main/menus/impls/macOS.test.ts
@@ -31,7 +31,7 @@ vi.mock('electron', () => ({
},
}));
-vi.mock('electron-is', () => ({
+vi.mock('@/utils/platform', () => ({
macOS: vi.fn(() => true),
}));
diff --git a/apps/desktop/src/main/modules/terminal/index.ts b/apps/desktop/src/main/modules/terminal/index.ts
index 710ef76598f..217fa1a245b 100644
--- a/apps/desktop/src/main/modules/terminal/index.ts
+++ b/apps/desktop/src/main/modules/terminal/index.ts
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
import fs from 'node:fs/promises';
import os from 'node:os';
-import { detectWindowsShell } from '@lobechat/local-file-shell';
+import { detectWindowsShell } from '@lobechat/local-file-shell/shell';
import type { IPty } from '@lydell/node-pty';
import { spawn } from '@lydell/node-pty';
diff --git a/apps/desktop/src/main/pre-app-init.ts b/apps/desktop/src/main/pre-app-init.ts
index 9e30ab31d79..48459157f4c 100644
--- a/apps/desktop/src/main/pre-app-init.ts
+++ b/apps/desktop/src/main/pre-app-init.ts
@@ -1,7 +1,8 @@
import path from 'node:path';
import { app } from 'electron';
-import * as electronIs from 'electron-is';
+
+import * as electronIs from '@/utils/platform';
// Must run BEFORE any module captures `app.getPath('userData')` (e.g. `@/const/dir`
// reads it at top level). Once a path is read, `setName` / `setPath` no-op for it.
diff --git a/apps/desktop/src/main/services/__tests__/fileSearchSrv.test.ts b/apps/desktop/src/main/services/__tests__/fileSearchSrv.test.ts
index 2f6999da7d8..71e17fcb9c4 100644
--- a/apps/desktop/src/main/services/__tests__/fileSearchSrv.test.ts
+++ b/apps/desktop/src/main/services/__tests__/fileSearchSrv.test.ts
@@ -1,4 +1,4 @@
-import type { FileResult, SearchOptions } from '@lobechat/local-file-shell';
+import type { FileResult, SearchOptions } from '@lobechat/local-file-shell/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { App } from '@/core/App';
@@ -6,7 +6,7 @@ import type { App } from '@/core/App';
import FileSearchService from '../fileSearchSrv';
// Mock the fileSearch module
-vi.mock('@lobechat/local-file-shell', () => {
+vi.mock('@lobechat/local-file-shell/file-search', () => {
const MockFileSearchImpl = vi.fn().mockImplementation(() => ({
search: vi.fn(),
checkSearchServiceStatus: vi.fn(),
@@ -47,7 +47,7 @@ describe('FileSearchService', () => {
fileSearchService = new FileSearchService(mockApp);
// Get the mock implementation instance
- mockImpl = (fileSearchService as any).impl;
+ mockImpl = await (fileSearchService as any).getImpl();
});
describe('search', () => {
diff --git a/apps/desktop/src/main/services/contentSearchSrv.ts b/apps/desktop/src/main/services/contentSearchSrv.ts
index a558191b293..c1039fcdae4 100644
--- a/apps/desktop/src/main/services/contentSearchSrv.ts
+++ b/apps/desktop/src/main/services/contentSearchSrv.ts
@@ -1,9 +1,8 @@
-import {
- type BaseContentSearch,
- createContentSearchImpl,
- type GrepContentParams,
- type GrepContentResult,
-} from '@lobechat/local-file-shell';
+import type {
+ BaseContentSearch,
+ GrepContentParams,
+ GrepContentResult,
+} from '@lobechat/local-file-shell/content-search';
import { ServiceModule } from './index';
@@ -13,20 +12,26 @@ import { ServiceModule } from './index';
* sunk into the shared `@lobechat/local-file-shell` package.
*/
export default class ContentSearchService extends ServiceModule {
- private impl: BaseContentSearch = createContentSearchImpl();
+ private implPromise?: Promise<BaseContentSearch>;
+
+ private getImpl(): Promise<BaseContentSearch> {
+ this.implPromise ??= import('@lobechat/local-file-shell/content-search').then(
+ ({ createContentSearchImpl }) => createContentSearchImpl(),
+ );
+ return this.implPromise;
+ }
async grep(params: GrepContentParams): Promise<GrepContentResult> {
// Lazily wire the desktop BinaryManager so we don't hit the
// class-field init-before-super-constructor gotcha. The manager already
// satisfies the minimal `ToolDetector` contract (only `getBestTool` is
// consumed by the search impls).
- if (this.app?.binaryManager) {
- this.impl.setToolDetector(this.app.binaryManager);
- }
- return this.impl.grep(params);
+ const impl = await this.getImpl();
+ if (this.app?.binaryManager) impl.setToolDetector(this.app.binaryManager);
+ return impl.grep(params);
}
async checkToolAvailable(tool: string): Promise<boolean> {
- return this.impl.checkToolAvailable(tool);
+ return (await this.getImpl()).checkToolAvailable(tool);
}
}
diff --git a/apps/desktop/src/main/services/fileSearchSrv.ts b/apps/desktop/src/main/services/fileSearchSrv.ts
index 253988c7dbc..4fdb1606ab5 100644
--- a/apps/desktop/src/main/services/fileSearchSrv.ts
+++ b/apps/desktop/src/main/services/fileSearchSrv.ts
@@ -1,11 +1,10 @@
-import {
- type BaseFileSearch,
- createFileSearchModule,
- type FileResult,
- type GlobFilesParams,
- type GlobFilesResult,
- type SearchOptions,
-} from '@lobechat/local-file-shell';
+import type {
+ BaseFileSearch,
+ FileResult,
+ GlobFilesParams,
+ GlobFilesResult,
+ SearchOptions,
+} from '@lobechat/local-file-shell/file-search';
import { ServiceModule } from './index';
@@ -15,30 +14,39 @@ import { ServiceModule } from './index';
* `@lobechat/local-file-shell`.
*/
export default class FileSearchService extends ServiceModule {
- private impl: BaseFileSearch = createFileSearchModule();
+ private implPromise?: Promise<BaseFileSearch>;
+
+ private getImpl(): Promise<BaseFileSearch> {
+ this.implPromise ??= import('@lobechat/local-file-shell/file-search').then(
+ ({ createFileSearchModule }) => createFileSearchModule(),
+ );
+ return this.implPromise;
+ }
async search(
query: string,
options: Omit<SearchOptions, 'keywords'> = {},
): Promise<FileResult[]> {
+ const impl = await this.getImpl();
if (this.app?.binaryManager) {
- this.impl.setToolDetector(this.app.binaryManager);
+ impl.setToolDetector(this.app.binaryManager);
}
- return this.impl.search({ ...options, keywords: query });
+ return impl.search({ ...options, keywords: query });
}
async checkSearchServiceStatus(): Promise<boolean> {
- return this.impl.checkSearchServiceStatus();
+ return (await this.getImpl()).checkSearchServiceStatus();
}
async updateSearchIndex(path?: string): Promise<boolean> {
- return this.impl.updateSearchIndex(path);
+ return (await this.getImpl()).updateSearchIndex(path);
}
async glob(params: GlobFilesParams): Promise<GlobFilesResult> {
+ const impl = await this.getImpl();
if (this.app?.binaryManager) {
- this.impl.setToolDetector(this.app.binaryManager);
+ impl.setToolDetector(this.app.binaryManager);
}
- return this.impl.glob(params);
+ return impl.glob(params);
}
}
diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
index 6aa5753b521..114a110e0d3 100644
--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts
+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
@@ -9,6 +9,7 @@ import type {
} from '@lobechat/device-control';
import type {
AgentRunRequestMessage,
+ GatewayClient,
GatewayMcpParams,
MessageApiRequestMessage,
RpcRequestMessage,
@@ -16,11 +17,8 @@ import type {
ToolCallRequestMessage,
ToolCallResponseMessage,
} from '@lobechat/device-gateway-client';
-import { GatewayClient } from '@lobechat/device-gateway-client';
import type { IdentitySource } from '@lobechat/device-identity';
-import { deriveDeviceId, deriveScopedFallbackId } from '@lobechat/device-identity';
import type { GatewayConnectionStatus } from '@lobechat/electron-client-ipc';
-import { getShellInfo } from '@lobechat/local-file-shell';
import { app, powerSaveBlocker } from 'electron';
import { isDev } from '@/const/env';
@@ -260,7 +258,10 @@ export default class GatewayConnectionService extends ServiceModule {
* because it hashes the OS machine id; falls back to the stored random UUID
* when the machine id is unavailable. Caches the result for this session.
*/
- resolveDeviceIdentity(userId: string): { deviceId: string; identitySource: IdentitySource } {
+ async resolveDeviceIdentity(
+ userId: string,
+ ): Promise<{ deviceId: string; identitySource: IdentitySource }> {
+ const { deriveDeviceId } = await import('@lobechat/device-identity');
const fallbackId = this.app.storeManager.get('gatewayDeviceId') as string | undefined;
const identity = deriveDeviceId(userId, { fallbackId });
this.deviceId = identity.deviceId;
@@ -373,7 +374,7 @@ export default class GatewayConnectionService extends ServiceModule {
// registry before opening the WS, so the device row exists by the time the
// gateway reports it online.
if (userId) {
- const identity = this.resolveDeviceIdentity(userId);
+ const identity = await this.resolveDeviceIdentity(userId);
await this.deviceRegistrar?.({
deviceId: identity.deviceId,
hostname: os.hostname(),
@@ -384,6 +385,7 @@ export default class GatewayConnectionService extends ServiceModule {
});
}
+ const { GatewayClient } = await import('@lobechat/device-gateway-client');
const client = new GatewayClient({
channel: isDev ? 'desktop-dev' : 'desktop',
connectionId: this.getConnectionId(),
@@ -508,7 +510,10 @@ export default class GatewayConnectionService extends ServiceModule {
* enrolled into a workspace — via desktop share or `lh connect --workspace` —
* resolves to one workspace device.
*/
- private resolveWorkspaceDeviceIdentity(workspaceId: string): EnrollWorkspaceResult {
+ private async resolveWorkspaceDeviceIdentity(
+ workspaceId: string,
+ ): Promise<EnrollWorkspaceResult> {
+ const { deriveDeviceId, deriveScopedFallbackId } = await import('@lobechat/device-identity');
// Fallback machines (no readable machine id) must still derive a STABLE
// workspace id — the identity-only probe, the real enroll, and restore
// checks each re-derive it. Namespace the persisted install UUID rather
@@ -529,8 +534,9 @@ export default class GatewayConnectionService extends ServiceModule {
// Re-enroll replaces the previous share connection instead of stacking one.
await this.closeWorkspaceClient(workspaceId);
- const identity = this.resolveWorkspaceDeviceIdentity(workspaceId);
+ const identity = await this.resolveWorkspaceDeviceIdentity(workspaceId);
+ const { GatewayClient } = await import('@lobechat/device-gateway-client');
const client = new GatewayClient({
channel: isDev ? 'desktop-dev' : 'desktop',
// Reuse the install's connectionId: the gateway dedupes stale sockets per
@@ -599,7 +605,7 @@ export default class GatewayConnectionService extends ServiceModule {
if (this.workspaceClients.has(workspaceId)) continue;
try {
- const identity = this.resolveWorkspaceDeviceIdentity(workspaceId);
+ const identity = await this.resolveWorkspaceDeviceIdentity(workspaceId);
const registered = await this.workspaceDeviceChecker?.(workspaceId, identity.deviceId);
if (registered === false) {
@@ -682,6 +688,7 @@ export default class GatewayConnectionService extends ServiceModule {
private async handleSystemInfoRequest(client: GatewayClient, request: SystemInfoRequestMessage) {
logger.info(`Received system_info_request: requestId=${request.requestId}`);
+ const { getShellInfo } = await import('@lobechat/local-file-shell/shell');
client.sendSystemInfoResponse({
requestId: request.requestId,
result: {
diff --git a/apps/desktop/src/main/utils/git.ts b/apps/desktop/src/main/utils/git.ts
index 917dca901fb..a844803b8ec 100644
--- a/apps/desktop/src/main/utils/git.ts
+++ b/apps/desktop/src/main/utils/git.ts
@@ -3,4 +3,4 @@
* `@lobechat/local-file-shell` so desktop, the device RPC, and the CLI share one
* copy; re-exported here to keep existing `@/utils/git` import sites stable.
*/
-export { detectRepoType, resolveCommonGitDir, resolveGitDir } from '@lobechat/local-file-shell';
+export { detectRepoType, resolveCommonGitDir, resolveGitDir } from '@lobechat/local-file-shell/git';
diff --git a/apps/desktop/src/main/utils/logger.ts b/apps/desktop/src/main/utils/logger.ts
index fe2c6380fcb..95dba0a02fe 100644
--- a/apps/desktop/src/main/utils/logger.ts
+++ b/apps/desktop/src/main/utils/logger.ts
@@ -1,4 +1,4 @@
-import { setLoggerFactory } from '@lobechat/local-file-shell';
+import { setLoggerFactory } from '@lobechat/local-file-shell/logger';
import debug from 'debug';
import { app } from 'electron';
import electronLog from 'electron-log';
diff --git a/apps/desktop/src/main/utils/permissions.ts b/apps/desktop/src/main/utils/permissions.ts
index 3a02f875dad..c904f277e3b 100644
--- a/apps/desktop/src/main/utils/permissions.ts
+++ b/apps/desktop/src/main/utils/permissions.ts
@@ -6,10 +6,10 @@
* It must be dynamically imported to prevent loading errors on Windows/Linux.
*/
import { shell } from 'electron';
-import * as electronIs from 'electron-is';
import type * as MacPermissions from 'node-mac-permissions';
import { createLogger } from './logger';
+import * as electronIs from './platform';
// Type definitions - use module types when available, fallback to local definition
// Note: We don't import the module statically, so we need local type definitions
@@ -81,11 +81,7 @@ const logger = createLogger('utils:permissions');
* Permission status mapping between node-mac-permissions and our internal representation
*/
export type PermissionStatus =
- | 'authorized'
- | 'denied'
- | 'not-determined'
- | 'restricted'
- | 'granted'; // alias for authorized
+ 'authorized' | 'denied' | 'not-determined' | 'restricted' | 'granted'; // alias for authorized
/**
* Normalize permission status to a consistent format
diff --git a/apps/desktop/src/main/utils/platform.test.ts b/apps/desktop/src/main/utils/platform.test.ts
new file mode 100644
index 00000000000..d8a34e73c2f
--- /dev/null
+++ b/apps/desktop/src/main/utils/platform.test.ts
@@ -0,0 +1,21 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { dev, linux, macOS, windows } from './platform';
+
+describe('platform detection', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('honors an explicit development override', () => {
+ vi.stubEnv('ELECTRON_IS_DEV', '1');
+ expect(dev()).toBe(true);
+
+ vi.stubEnv('ELECTRON_IS_DEV', '0');
+ expect(dev()).toBe(false);
+ });
+
+ it('reports exactly one current operating system', () => {
+ expect([linux(), macOS(), windows()].filter(Boolean)).toHaveLength(1);
+ });
+});
diff --git a/apps/desktop/src/main/utils/platform.ts b/apps/desktop/src/main/utils/platform.ts
new file mode 100644
index 00000000000..0be2a4ad640
--- /dev/null
+++ b/apps/desktop/src/main/utils/platform.ts
@@ -0,0 +1,14 @@
+const getDevelopmentOverride = (): boolean | undefined => {
+ if (!('ELECTRON_IS_DEV' in process.env)) return undefined;
+ return Number.parseInt(process.env.ELECTRON_IS_DEV ?? '', 10) === 1;
+};
+
+export const dev = (): boolean =>
+ getDevelopmentOverride() ??
+ Boolean(process.defaultApp || /node_modules[\\/]electron[\\/]/.test(process.execPath));
+
+export const linux = (): boolean => process.platform === 'linux';
+
+export const macOS = (): boolean => process.platform === 'darwin';
+
+export const windows = (): boolean => process.platform === 'win32';
diff --git a/apps/desktop/src/main/utils/shellPath.test.ts b/apps/desktop/src/main/utils/shellPath.test.ts
new file mode 100644
index 00000000000..e09dbd42549
--- /dev/null
+++ b/apps/desktop/src/main/utils/shellPath.test.ts
@@ -0,0 +1,64 @@
+import { execFile } from 'node:child_process';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { refreshShellPath } from './shellPath';
+
+vi.mock('node:child_process', () => ({ execFile: vi.fn() }));
+
+const execFileMock = vi.mocked(execFile) as unknown as ReturnType<typeof vi.fn>;
+
+describe('refreshShellPath', () => {
+ const originalPath = process.env.PATH;
+ const originalShell = process.env.SHELL;
+
+ beforeEach(() => {
+ process.env.PATH = '/usr/bin:/bin';
+ process.env.SHELL = '/bin/zsh';
+ execFileMock.mockReset();
+ });
+
+ afterEach(() => {
+ process.env.PATH = originalPath;
+ process.env.SHELL = originalShell;
+ });
+
+ it('updates PATH from the login shell output', async () => {
+ execFileMock.mockImplementation((_file, _args, _options, callback) => {
+ callback(
+ null,
+ 'shell startup output\n__LOBE_SHELL_PATH__/opt/homebrew/bin:/usr/bin__LOBE_SHELL_PATH__',
+ '',
+ );
+ });
+
+ await refreshShellPath();
+
+ expect(process.env.PATH).toBe('/opt/homebrew/bin:/usr/bin');
+ expect(execFileMock).toHaveBeenCalledWith(
+ '/bin/zsh',
+ expect.arrayContaining(['-ilc']),
+ expect.objectContaining({ timeout: 5000 }),
+ expect.any(Function),
+ );
+ });
+
+ it('preserves PATH when the login shell returns no delimited value', async () => {
+ execFileMock.mockImplementation((_file, _args, _options, callback) => {
+ callback(null, 'shell startup output only', '');
+ });
+
+ await refreshShellPath();
+
+ expect(process.env.PATH).toBe('/usr/bin:/bin');
+ });
+
+ it('rejects without replacing PATH when shell startup fails', async () => {
+ execFileMock.mockImplementation((_file, _args, _options, callback) => {
+ callback(new Error('shell failed'), '', '');
+ });
+
+ await expect(refreshShellPath()).rejects.toThrow('shell failed');
+ expect(process.env.PATH).toBe('/usr/bin:/bin');
+ });
+});
diff --git a/apps/desktop/src/main/utils/shellPath.ts b/apps/desktop/src/main/utils/shellPath.ts
new file mode 100644
index 00000000000..2ea0ab5df26
--- /dev/null
+++ b/apps/desktop/src/main/utils/shellPath.ts
@@ -0,0 +1,45 @@
+import { execFile } from 'node:child_process';
+
+const SHELL_PATH_DELIMITER = '__LOBE_SHELL_PATH__';
+const SHELL_PATH_TIMEOUT_MS = 5000;
+
+const runLoginShell = (shell: string): Promise<string> =>
+ new Promise((resolve, reject) => {
+ execFile(
+ shell,
+ ['-ilc', `printf '${SHELL_PATH_DELIMITER}%s${SHELL_PATH_DELIMITER}' "$PATH"; exit`],
+ {
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ DISABLE_AUTO_UPDATE: 'true',
+ ZSH_TMUX_AUTOSTART: 'false',
+ ZSH_TMUX_AUTOSTARTED: 'true',
+ },
+ timeout: SHELL_PATH_TIMEOUT_MS,
+ },
+ (error, stdout) => {
+ if (error) {
+ reject(error);
+ return;
+ }
+
+ resolve(stdout);
+ },
+ );
+ });
+
+/**
+ * Refresh PATH from the user's login shell without blocking Electron's main
+ * thread. The existing PATH is retained when the shell cannot be resolved or
+ * returns no usable value.
+ */
+export const refreshShellPath = async (): Promise<void> => {
+ if (process.platform === 'win32') return;
+
+ const shell = process.env.SHELL || (process.platform === 'darwin' ? '/bin/zsh' : '/bin/sh');
+ const stdout = await runLoginShell(shell);
+ const [, shellPath] = stdout.split(SHELL_PATH_DELIMITER);
+
+ if (shellPath?.trim()) process.env.PATH = shellPath.trim();
+};
diff --git a/apps/desktop/src/preload/bootProfiler.ts b/apps/desktop/src/preload/bootProfiler.ts
new file mode 100644
index 00000000000..71c84c285d2
--- /dev/null
+++ b/apps/desktop/src/preload/bootProfiler.ts
@@ -0,0 +1,59 @@
+import type { DesktopBootProfilePayload } from '@lobechat/electron-client-ipc';
+import { ipcRenderer } from 'electron';
+
+const PROFILE_FLAG = 'LOBE_DESKTOP_BOOT_PROFILE';
+
+const afterVisibleFrame = (callback: () => void) => {
+ if (typeof window.requestAnimationFrame !== 'function') {
+ window.setTimeout(callback, 0);
+ return;
+ }
+
+ window.requestAnimationFrame(() => window.requestAnimationFrame(callback));
+};
+
+/**
+ * Test-only packaged-startup probe. It runs in preload so observation begins
+ * before the route bundle evaluates and does not alter the production path
+ * unless the explicit profiling environment flag is present.
+ */
+export const setupBootProfiler = () => {
+ if (process.env[PROFILE_FLAG] !== '1') return;
+
+ let reported = false;
+ const report = (loadingScreenRemovedMs: number) => {
+ if (reported) return;
+ reported = true;
+
+ afterVisibleFrame(() => {
+ const navigation = performance.getEntriesByType('navigation')[0] as
+ PerformanceNavigationTiming | undefined;
+ const payload: DesktopBootProfilePayload = {
+ domContentLoadedMs: navigation?.domContentLoadedEventEnd ?? 0,
+ firstVisibleFrameMs: performance.now(),
+ loadingScreenRemovedMs,
+ navigationStartedAt: performance.timeOrigin,
+ };
+ ipcRenderer.send('desktop:boot-profile-ready', payload);
+ });
+ };
+
+ window.addEventListener(
+ 'DOMContentLoaded',
+ () => {
+ const loadingScreen = document.getElementById('loading-screen');
+ if (!loadingScreen) {
+ report(performance.now());
+ return;
+ }
+
+ const observer = new MutationObserver(() => {
+ if (document.getElementById('loading-screen')) return;
+ observer.disconnect();
+ report(performance.now());
+ });
+ observer.observe(document.documentElement, { childList: true, subtree: true });
+ },
+ { once: true },
+ );
+};
diff --git a/apps/desktop/src/preload/electronApi.test.ts b/apps/desktop/src/preload/electronApi.test.ts
index d9c0b7ee889..183ca1c065e 100644
--- a/apps/desktop/src/preload/electronApi.test.ts
+++ b/apps/desktop/src/preload/electronApi.test.ts
@@ -6,6 +6,7 @@ import type { SetupElectronApiFunction } from './electronApi';
const mockElectronAPI = { someAPI: 'mock-electron-api' };
const mockContextBridgeExposeInMainWorld = vi.fn();
const mockIpcRendererOn = vi.fn();
+const mockIpcRendererSendSync = vi.fn();
vi.mock('electron', () => ({
contextBridge: {
@@ -13,6 +14,7 @@ vi.mock('electron', () => ({
},
ipcRenderer: {
on: mockIpcRendererOn,
+ sendSync: mockIpcRendererSendSync,
},
}));
@@ -57,11 +59,23 @@ describe('setupElectronApi', () => {
expect(call).toBeTruthy();
expect(call?.[1]).toMatchObject({
invoke: mockInvoke,
+ getDesktopBootstrapIdentity: expect.any(Function),
onScreenCaptureSession: expect.any(Function),
onStreamInvoke: mockOnStreamInvoke,
});
});
+ it('reads the bootstrap identity synchronously before renderer initialization', () => {
+ const identity = { isIdentityResolved: true, userId: 'user-1' };
+ mockIpcRendererSendSync.mockReturnValue(identity);
+ setupElectronApi();
+
+ const exposedAPI = mockContextBridgeExposeInMainWorld.mock.calls[1][1];
+
+ expect(exposedAPI.getDesktopBootstrapIdentity()).toEqual(identity);
+ expect(mockIpcRendererSendSync).toHaveBeenCalledWith('desktop:get-bootstrap-identity');
+ });
+
it('should expose lobeEnv with darwinMajorVersion, isMacTahoe, platform and version info', () => {
setupElectronApi();
diff --git a/apps/desktop/src/preload/electronApi.ts b/apps/desktop/src/preload/electronApi.ts
index f6f1b4d21fd..52b53f87373 100644
--- a/apps/desktop/src/preload/electronApi.ts
+++ b/apps/desktop/src/preload/electronApi.ts
@@ -31,6 +31,7 @@ export const setupElectronApi = () => {
}
contextBridge.exposeInMainWorld('electronAPI', {
+ getDesktopBootstrapIdentity: () => ipcRenderer.sendSync('desktop:get-bootstrap-identity'),
invoke,
onScreenCaptureSession: (listener: (session: ScreenCaptureSession) => void) => {
screenCaptureSessionListeners.add(listener);
diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.ts
index 2bd879dbed5..ca172f994c7 100644
--- a/apps/desktop/src/preload/index.ts
+++ b/apps/desktop/src/preload/index.ts
@@ -1,7 +1,9 @@
+import { setupBootProfiler } from './bootProfiler';
import { setupElectronApi } from './electronApi';
import { setupRouteInterceptors } from './routeInterceptor';
const setupPreload = () => {
+ setupBootProfiler();
setupElectronApi();
// Setup route interception logic
diff --git a/apps/desktop/vite.main.config.ts b/apps/desktop/vite.main.config.ts
index aa605e4a86d..2e61be7f800 100644
--- a/apps/desktop/vite.main.config.ts
+++ b/apps/desktop/vite.main.config.ts
@@ -53,18 +53,24 @@ export default defineConfig(async (env) => {
],
output: {
assetFileNames: 'chunks/[name]-[hash].[ext]',
- // Prevent shared deps from being bundled into index.js to avoid side-effect pollution.
- // Pattern: when a module is imported by both the main bundle (statically) and a
- // dynamic-import chunk (lazy loader), rolldown places it in main and makes the
- // chunk back-reference `require("./index.js")`. Electron's main entry isn't in
- // Node's CJS cache, so that require recompiles `index.js` from scratch — which
- // re-runs `new App()` at top-level and triggers `protocol.registerSchemesAsPrivileged`
- // *after* the app is ready → throw.
+ // Keep Electron's side-effectful entry as a tiny bootstrap and put the
+ // application graph in a normal CommonJS chunk. Electron evaluates its entry
+ // outside the usual CJS cache path; when a deferred chunk back-references
+ // `index.js`, the entry can otherwise run again after app.ready. A regular
+ // `main-app` chunk is cached by Node, so lazy features can safely reuse any
+ // module from the eager graph without re-running `new App()`.
//
- // Same root cause as the original `debug` regression fixed in #11827. Isolate
- // each shared module into its own vendor chunk so both ends reference the vendor
- // chunk instead of back-referencing main.
+ // This is intentionally one architectural boundary rather than a growing list
+ // of shared vendor packages. Forcing Ajv, semver, env schemas, and similar
+ // dependencies into manual chunks de-optimizes tree-shaking and increases the
+ // amount of JavaScript parsed before renderer navigation.
manualChunks(id: string) {
+ const normalizedId = id.replaceAll('\\', '/').split('?')[0];
+
+ if (/apps\/desktop\/src\/main\/core\/App\.ts$/.test(normalizedId)) {
+ return 'main-app';
+ }
+
if (id.includes('node_modules/debug')) {
return 'vendor-debug';
}
@@ -89,7 +95,6 @@ export default defineConfig(async (env) => {
// Split i18n json resources by namespace (ns), not by locale.
// Example: ".../resources/locales/zh-CN/common.json?import" -> "locales-common"
- const normalizedId = id.replaceAll('\\', '/').split('?')[0];
const match = normalizedId.match(/\/locales\/[^/]+\/([^/]+)\.json$/);
if (match?.[1]) return `locales-${match[1]}`;
diff --git a/apps/desktop/vite.renderer.config.ts b/apps/desktop/vite.renderer.config.ts
index 611c344c8d5..842f5cf0b7f 100644
--- a/apps/desktop/vite.renderer.config.ts
+++ b/apps/desktop/vite.renderer.config.ts
@@ -8,6 +8,8 @@ import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';
import {
+ createSharedRolldownOutput,
+ sharedModulePreload,
sharedOptimizeDeps,
sharedRendererDefine,
sharedRendererPlugins,
@@ -220,7 +222,7 @@ export default defineConfig(async (env) => {
base: '/',
build: {
minify: true,
- modulePreload: { polyfill: false },
+ modulePreload: { ...sharedModulePreload, polyfill: false },
outDir: RENDERER_OUT_DIR,
reportCompressedSize: false,
rolldownOptions: {
@@ -229,6 +231,7 @@ export default defineConfig(async (env) => {
overlay: path.resolve(__dirname, 'overlay.html'),
popup: path.resolve(__dirname, 'popup.html'),
},
+ output: createSharedRolldownOutput({ strictExecutionOrder: true }),
},
sourcemap: false,
target: RENDERER_CHROME_TARGET,
diff --git a/apps/desktop/vitest.config.mts b/apps/desktop/vitest.config.mts
index 1f96271a558..3cdbde1a607 100644
--- a/apps/desktop/vitest.config.mts
+++ b/apps/desktop/vitest.config.mts
@@ -1,21 +1,12 @@
-import { resolve } from 'node:path';
+import path from 'node:path';
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
alias: {
- '@': resolve(__dirname, './src/main'),
- '~common': resolve(__dirname, './src/common'),
- '@lobechat/device-control': resolve(__dirname, '../../packages/device-control/src'),
- '@lobechat/device-control/workspace': resolve(
- __dirname,
- '../../packages/device-control/src/workspace',
- ),
- // Not hoisted to the (super)project root node_modules, so resolve it to
- // workspace source like the packages above.
- '@lobechat/device-identity': resolve(__dirname, '../../packages/device-identity/src'),
- '@lobechat/local-file-shell': resolve(__dirname, '../../packages/local-file-shell/src'),
+ '@': path.resolve(__dirname, './src/main'),
+ '~common': path.resolve(__dirname, './src/common'),
},
coverage: {
all: false,
diff --git a/packages/device-control/package.json b/packages/device-control/package.json
index 76f59ffc5ef..223c01b6d92 100644
--- a/packages/device-control/package.json
+++ b/packages/device-control/package.json
@@ -5,6 +5,8 @@
"sideEffects": false,
"exports": {
".": "./src/index.ts",
+ "./project-file-index": "./src/projectFileIndex.ts",
+ "./skill-directory": "./src/skillDirectory.ts",
"./workspace": "./src/workspace.ts"
},
"main": "./src/index.ts",
diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.ts
index 8a34a2d915a..7f3a17c779d 100644
--- a/packages/device-control/src/dispatch.ts
+++ b/packages/device-control/src/dispatch.ts
@@ -1,3 +1,4 @@
+import { moveLocalFiles, renameLocalFile, writeLocalFile } from '@lobechat/local-file-shell/file';
import {
addGitWorktree,
checkoutGitBranch,
@@ -12,15 +13,12 @@ import {
listGitBranches,
listGitRemoteBranches,
listGitWorktrees,
- moveLocalFiles,
pullGitBranch,
pushGitBranch,
removeGitWorktree,
renameGitBranch,
- renameLocalFile,
revertGitFile,
- writeLocalFile,
-} from '@lobechat/local-file-shell';
+} from '@lobechat/local-file-shell/git';
import { getClaudeCodeQuota, type GetClaudeCodeQuotaParams } from './claudeCodeQuota';
import { prepareSkillDirectory } from './skillDirectory';
diff --git a/packages/device-control/src/workspace.ts b/packages/device-control/src/workspace.ts
index 1156a13350b..c8df3453c88 100644
--- a/packages/device-control/src/workspace.ts
+++ b/packages/device-control/src/workspace.ts
@@ -2,7 +2,7 @@ import { readdir, readFile, stat } from 'node:fs/promises';
import * as os from 'node:os';
import path from 'node:path';
-import { detectRepoType } from '@lobechat/local-file-shell';
+import { detectRepoType } from '@lobechat/local-file-shell/git';
import matter from 'gray-matter';
import type {
diff --git a/packages/electron-client-ipc/package.json b/packages/electron-client-ipc/package.json
index 6e749ad10a8..8a68a51a617 100644
--- a/packages/electron-client-ipc/package.json
+++ b/packages/electron-client-ipc/package.json
@@ -2,6 +2,11 @@
"name": "@lobechat/electron-client-ipc",
"version": "1.0.0",
"private": true,
+ "exports": {
+ ".": "./src/index.ts",
+ "./types": "./src/types/index.ts",
+ "./types/heterogeneous-agent": "./src/types/heterogeneousAgent.ts"
+ },
"main": "src/index.ts",
"types": "src/index.ts",
"dependencies": {
diff --git a/packages/electron-client-ipc/src/ipc.ts b/packages/electron-client-ipc/src/ipc.ts
index 6116e88a22f..191077b198c 100644
--- a/packages/electron-client-ipc/src/ipc.ts
+++ b/packages/electron-client-ipc/src/ipc.ts
@@ -1,4 +1,8 @@
-import type { ScreenCaptureSession, StreamInvokeRequestParams } from './types';
+import type {
+ DesktopBootstrapIdentity,
+ ScreenCaptureSession,
+ StreamInvokeRequestParams,
+} from './types';
type IpcInvoke = <T = unknown>(event: string, ...data: unknown[]) => Promise<T>;
@@ -45,6 +49,7 @@ let cachedProxy: DesktopIpcServices | null = null;
declare global {
interface Window {
electronAPI?: {
+ getDesktopBootstrapIdentity?: () => DesktopBootstrapIdentity;
invoke?: IpcInvoke;
onScreenCaptureSession?: (listener: (session: ScreenCaptureSession) => void) => () => void;
onStreamInvoke: (
diff --git a/packages/electron-client-ipc/src/types/bootstrap.ts b/packages/electron-client-ipc/src/types/bootstrap.ts
new file mode 100644
index 00000000000..8bc033ae27b
--- /dev/null
+++ b/packages/electron-client-ipc/src/types/bootstrap.ts
@@ -0,0 +1,18 @@
+/**
+ * Minimal identity information required before React mounts on Desktop.
+ *
+ * The user id is derived from the safe-storage-protected OIDC access token in
+ * the main process. It selects an isolated local cache partition only; server
+ * authorization continues to validate the token independently.
+ */
+export interface DesktopBootstrapIdentity {
+ isIdentityResolved: boolean;
+ userId?: string;
+}
+
+export interface DesktopBootProfilePayload {
+ domContentLoadedMs: number;
+ firstVisibleFrameMs: number;
+ loadingScreenRemovedMs: number;
+ navigationStartedAt: number;
+}
diff --git a/packages/electron-client-ipc/src/types/index.ts b/packages/electron-client-ipc/src/types/index.ts
index 8563febfff6..e8f93185d5f 100644
--- a/packages/electron-client-ipc/src/types/index.ts
+++ b/packages/electron-client-ipc/src/types/index.ts
@@ -1,4 +1,5 @@
export * from './binary';
+export * from './bootstrap';
export * from './browserControl';
export * from './browserSidebar';
export * from './contextMenu';
diff --git a/packages/local-file-shell/package.json b/packages/local-file-shell/package.json
index 7f0018fccc7..a9959aa6cb1 100644
--- a/packages/local-file-shell/package.json
+++ b/packages/local-file-shell/package.json
@@ -3,6 +3,16 @@
"version": "1.0.0",
"private": true,
"sideEffects": false,
+ "exports": {
+ ".": "./src/index.ts",
+ "./content-search": "./src/contentSearch/index.ts",
+ "./file": "./src/file/index.ts",
+ "./file-search": "./src/fileSearch/index.ts",
+ "./git": "./src/git/index.ts",
+ "./logger": "./src/logger.ts",
+ "./shell": "./src/shell/index.ts",
+ "./types": "./src/types.ts"
+ },
"main": "./src/index.ts",
"types": "./src/index.ts",
"dependencies": {
diff --git a/packages/local-file-shell/src/contentSearch/index.ts b/packages/local-file-shell/src/contentSearch/index.ts
index 84b7494db77..d071d185847 100644
--- a/packages/local-file-shell/src/contentSearch/index.ts
+++ b/packages/local-file-shell/src/contentSearch/index.ts
@@ -6,6 +6,7 @@ import { LinuxContentSearchImpl } from './impl/linux';
import { MacOSContentSearchImpl } from './impl/macOS';
import { WindowsContentSearchImpl } from './impl/windows';
+export type { GrepContentParams, GrepContentResult } from '../types';
export { BaseContentSearch } from './base';
export { LinuxContentSearchImpl } from './impl/linux';
export { MacOSContentSearchImpl } from './impl/macOS';
diff --git a/packages/local-file-shell/src/fileSearch/index.ts b/packages/local-file-shell/src/fileSearch/index.ts
index 434d6dc5486..c261f3c9e58 100644
--- a/packages/local-file-shell/src/fileSearch/index.ts
+++ b/packages/local-file-shell/src/fileSearch/index.ts
@@ -8,6 +8,12 @@ import { WindowsSearchServiceImpl } from './impl/windows';
const logger = createLogger('fileSearch:factory');
+export type {
+ FileResult,
+ GlobFilesParams,
+ GlobFilesResult,
+ SearchFilesParams as SearchOptions,
+} from '../types';
export { BaseFileSearch } from './base';
export const createFileSearchModule = (toolDetector?: ToolDetector) => {
diff --git a/packages/local-file-shell/src/index.ts b/packages/local-file-shell/src/index.ts
index 45da6b7529b..76322ad751d 100644
--- a/packages/local-file-shell/src/index.ts
+++ b/packages/local-file-shell/src/index.ts
@@ -1,6 +1,6 @@
export * from './contentSearch';
export * from './file';
-export * from './fileSearch';
+export { BaseFileSearch, createFileSearchModule } from './fileSearch';
export * from './git';
export { createLogger, type Logger, type LoggerFactory, setLoggerFactory } from './logger';
export * from './shell';
diff --git a/packages/utils/src/mimeType.ts b/packages/utils/src/mimeType.ts
index 410504a2936..fca0627988b 100644
--- a/packages/utils/src/mimeType.ts
+++ b/packages/utils/src/mimeType.ts
@@ -1,4 +1,3 @@
-import { fileTypeFromBuffer } from 'file-type';
import mime from 'mime';
// Extensions where mime-db has no entry (or a wrong one) but a specific
@@ -98,6 +97,7 @@ export const tryGetMimeType = (filePath: string): string | undefined => {
* 3. No extension mapping → sniff-based fallback.
*/
export const resolveMimeType = async (filePath: string, buffer: Uint8Array): Promise<string> => {
+ const { fileTypeFromBuffer } = await import('file-type');
const detected = await fileTypeFromBuffer(buffer);
if (detected?.mime) return detected.mime;
diff --git a/src/features/Workspace/workspaceAwarePath.ts b/src/features/Workspace/workspaceAwarePath.ts
index dd5d8a12464..0f01004420f 100644
--- a/src/features/Workspace/workspaceAwarePath.ts
+++ b/src/features/Workspace/workspaceAwarePath.ts
@@ -23,7 +23,7 @@ const isPersonalPath = (to: string): boolean => PERSONAL_PATH_REGEX.test(to);
/**
* Settings sub-paths that have a `/:workspaceSlug/settings/<tab>` mirror in
* the SPA routers. Kept in sync with the workspace settings subtree in
- * `src/spa/router/{desktopRouter.config,desktopRouter.config.desktop,mobileRouter.config}.tsx`.
+ * `src/spa/router/desktopRouter.shared.tsx` and `mobileRouter.config.tsx`.
*
* Tabs absent from this set (profile, llm, messenger, referral, system-tools,
* security, sync, plugin, tts, hotkey, agent, about, common, system-agent, ...)
diff --git a/src/layout/GlobalProvider/SWRMutateInitializer.desktop.tsx b/src/layout/GlobalProvider/SWRMutateInitializer.desktop.tsx
index 56f4a55d28c..bfe939e10a7 100644
--- a/src/layout/GlobalProvider/SWRMutateInitializer.desktop.tsx
+++ b/src/layout/GlobalProvider/SWRMutateInitializer.desktop.tsx
@@ -5,6 +5,7 @@ import { type PropsWithChildren, useEffect } from 'react';
import { useSWRConfig } from 'swr';
import { setScopedMutate } from '@/libs/swr';
+import { applyDesktopBootstrapIdentity } from '@/spa/initialize/desktopIdentity';
/**
* Initialize scoped mutate for use outside React components (e.g., Zustand stores)
@@ -19,6 +20,9 @@ const SWRMutateInitializer = ({ children }: PropsWithChildren) => {
useWatchBroadcast('remoteServerConfigUpdated', () => {
try {
+ // Token changes can switch the local cache partition. Apply the new
+ // safe-storage identity before revalidating any SWR key.
+ applyDesktopBootstrapIdentity();
const result = mutate(() => true, undefined, { revalidate: true });
void result?.catch?.(() => {});
} catch {
diff --git a/src/layout/SPAGlobalProvider/index.test.tsx b/src/layout/SPAGlobalProvider/index.test.tsx
index 41df64289ef..a2a7c75592a 100644
--- a/src/layout/SPAGlobalProvider/index.test.tsx
+++ b/src/layout/SPAGlobalProvider/index.test.tsx
@@ -2,7 +2,7 @@
* @vitest-environment happy-dom
*/
import { render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
+import { type ReactNode, useEffect } from 'react';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { setPostRenderReady } from '@/spa/atoms/app';
@@ -265,6 +265,38 @@ describe('SPAGlobalProvider', () => {
expect(await screen.findByTestId('dev-dock')).toBeInTheDocument();
});
+ it('does not remount application providers when DevDock becomes available', async () => {
+ vi.stubEnv('PROD', true);
+ const mounted = vi.fn();
+ const unmounted = vi.fn();
+ const ProviderProbe = () => {
+ useEffect(() => {
+ mounted();
+ return unmounted;
+ }, []);
+ return <div data-testid="provider-probe" />;
+ };
+
+ const view = render(
+ <DevDockLayout>
+ <ProviderProbe />
+ </DevDockLayout>,
+ );
+ expect(mounted).toHaveBeenCalledOnce();
+
+ canAccessDevDock.mockReturnValue(true);
+ setDevDockUnlocked(true);
+ view.rerender(
+ <DevDockLayout>
+ <ProviderProbe />
+ </DevDockLayout>,
+ );
+
+ expect(await screen.findByTestId('dev-dock')).toBeInTheDocument();
+ expect(mounted).toHaveBeenCalledOnce();
+ expect(unmounted).not.toHaveBeenCalled();
+ });
+
it('mounts global interaction hosts with the application shell', () => {
render(
<SPAGlobalProvider>
diff --git a/src/layout/SPAGlobalProvider/index.tsx b/src/layout/SPAGlobalProvider/index.tsx
index 85d1ff0655a..f9aaaf48104 100644
--- a/src/layout/SPAGlobalProvider/index.tsx
+++ b/src/layout/SPAGlobalProvider/index.tsx
@@ -43,14 +43,14 @@ const devDockLayoutStyle: CSSProperties = {
export const DevDockLayout = memo<PropsWithChildren>(({ children }) => {
const mounted = useDevDockMounted();
- if (!mounted) return children;
-
return (
<>
<div style={devDockLayoutStyle}>{children}</div>
- <Suspense>
- <DevDock />
- </Suspense>
+ {mounted && (
+ <Suspense>
+ <DevDock />
+ </Suspense>
+ )}
</>
);
});
@@ -66,42 +66,40 @@ const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {
(serverConfig?.isMobile ?? typeof __MOBILE__ !== 'undefined') ? __MOBILE__ : false;
const content = (
- <QueryProvider>
- <AuthProvider>
- <MarketAuthProvider isDesktop={isDesktop}>
- <StoreInitialization />
-
- {isDesktop && <ServerVersionOutdatedAlert />}
- <FaviconProvider>
- {postRenderReady && (
- <Suspense>
- <DynamicFavicon />
- </Suspense>
- )}
- <GroupWizardProvider>
- <DragUploadProvider>
- <LazyMotion features={domMax}>
- <TooltipGroup layoutAnimation={false}>
- <StyleProvider speedy={import.meta.env.PROD}>
- <LobeAnalyticsProviderWrapper>
- <CacheHydrationGate>{children}</CacheHydrationGate>
- </LobeAnalyticsProviderWrapper>
- </StyleProvider>
- </TooltipGroup>
- <ModalHost />
- <BaseModalHost />
- <ToastHost />
- <ContextMenuHost />
- <Suspense>
- <ImperativeMountHost />
- </Suspense>
- </LazyMotion>
- </DragUploadProvider>
- </GroupWizardProvider>
- </FaviconProvider>
- </MarketAuthProvider>
- </AuthProvider>
- </QueryProvider>
+ <AuthProvider>
+ <MarketAuthProvider isDesktop={isDesktop}>
+ <StoreInitialization />
+
+ {isDesktop && <ServerVersionOutdatedAlert />}
+ <FaviconProvider>
+ {postRenderReady && (
+ <Suspense>
+ <DynamicFavicon />
+ </Suspense>
+ )}
+ <GroupWizardProvider>
+ <DragUploadProvider>
+ <LazyMotion features={domMax}>
+ <TooltipGroup layoutAnimation={false}>
+ <StyleProvider speedy={import.meta.env.PROD}>
+ <LobeAnalyticsProviderWrapper>
+ <CacheHydrationGate>{children}</CacheHydrationGate>
+ </LobeAnalyticsProviderWrapper>
+ </StyleProvider>
+ </TooltipGroup>
+ <ModalHost />
+ <BaseModalHost />
+ <ToastHost />
+ <ContextMenuHost />
+ <Suspense>
+ <ImperativeMountHost />
+ </Suspense>
+ </LazyMotion>
+ </DragUploadProvider>
+ </GroupWizardProvider>
+ </FaviconProvider>
+ </MarketAuthProvider>
+ </AuthProvider>
);
return (
@@ -112,7 +110,9 @@ const SPAGlobalProvider = memo<PropsWithChildren>(({ children }) => {
isMobile={isMobile}
serverConfig={serverConfig?.config}
>
- <DevDockLayout>{content}</DevDockLayout>
+ <QueryProvider>
+ <DevDockLayout>{content}</DevDockLayout>
+ </QueryProvider>
</ServerConfigStoreProvider>
</AppTheme>
</Locale>
diff --git a/src/libs/swr/useCacheScope.test.ts b/src/libs/swr/useCacheScope.test.ts
index d44e94ef277..fec698b0bf4 100644
--- a/src/libs/swr/useCacheScope.test.ts
+++ b/src/libs/swr/useCacheScope.test.ts
@@ -10,7 +10,7 @@ import {
let mockUserId: string | null | undefined = undefined;
let mockIsAuthLoaded = false;
-let mockIsUserStateInit = false;
+let mockIsIdentityResolved = false;
let mockWorkspaceId: string | null = null;
let mockIsDesktop = false;
@@ -22,7 +22,7 @@ vi.mock('@lobechat/const', () => ({
vi.mock('@/store/user', () => ({
getUserStoreState: () => ({
isLoaded: mockIsAuthLoaded,
- isUserStateInit: mockIsUserStateInit,
+ isIdentityResolved: mockIsIdentityResolved,
user: { id: mockUserId },
}),
}));
@@ -64,7 +64,7 @@ describe('activeScopeKey + optimistic scope', () => {
localStorage.clear();
mockUserId = undefined;
mockIsAuthLoaded = false;
- mockIsUserStateInit = false;
+ mockIsIdentityResolved = false;
mockWorkspaceId = null;
mockIsDesktop = false;
});
@@ -97,15 +97,22 @@ describe('activeScopeKey + optimistic scope', () => {
expect(getCacheScope()).toBe('anon:personal');
});
- it('getCacheScope keeps the persisted scope on desktop until user state initializes', () => {
- // desktop hardcodes isLoaded=true on mount; userId lands with useInitUserState
+ it('getCacheScope keeps the persisted scope on desktop until bootstrap identity resolves', () => {
localStorage.setItem('lobehub:active-scope', 'user_abc:w1');
mockIsDesktop = true;
mockIsAuthLoaded = true;
- mockIsUserStateInit = false;
+ mockIsIdentityResolved = false;
expect(getCacheScope()).toBe('user_abc:w1');
});
+ it('getCacheScope uses the bootstrap user before full user-state initialization', () => {
+ localStorage.setItem('lobehub:active-scope', 'stale_user:w1');
+ mockIsDesktop = true;
+ mockIsIdentityResolved = true;
+ mockUserId = 'bootstrap_user';
+ expect(getCacheScope()).toBe('bootstrap_user:personal');
+ });
+
it('clearActiveScopeKey removes the persisted scope (logout)', () => {
localStorage.setItem('lobehub:active-scope', 'user_abc:personal');
clearActiveScopeKey();
@@ -118,7 +125,7 @@ describe('activeScopeKey + optimistic scope', () => {
describe('isScopeTrusted', () => {
beforeEach(() => {
mockIsAuthLoaded = false;
- mockIsUserStateInit = false;
+ mockIsIdentityResolved = false;
mockIsDesktop = false;
});
@@ -132,17 +139,17 @@ describe('isScopeTrusted', () => {
expect(isScopeTrusted()).toBe(true);
});
- it('on desktop, is untrusted until user state initializes even though isLoaded is true', () => {
+ it('on desktop, is untrusted until the preload identity resolves', () => {
mockIsDesktop = true;
mockIsAuthLoaded = true;
- mockIsUserStateInit = false;
+ mockIsIdentityResolved = false;
expect(isScopeTrusted()).toBe(false);
});
- it('on desktop, is trusted once user state initializes', () => {
+ it('on desktop, is trusted from bootstrap without waiting for full user state', () => {
mockIsDesktop = true;
mockIsAuthLoaded = true;
- mockIsUserStateInit = true;
+ mockIsIdentityResolved = true;
expect(isScopeTrusted()).toBe(true);
});
});
diff --git a/src/libs/swr/useCacheScope.ts b/src/libs/swr/useCacheScope.ts
index adb9ef22bb9..7d92c5cc3fb 100644
--- a/src/libs/swr/useCacheScope.ts
+++ b/src/libs/swr/useCacheScope.ts
@@ -85,17 +85,15 @@ export const isAnonymousScope = (scope: string): boolean => scope.startsWith(`${
*
* - Web (Better-Auth): `isLoaded` flips when the session request settles, at
* which point `user` is populated (or confirmed empty). It is the signal.
- * - Desktop: `DesktopAuthProvider` hardcodes `isLoaded` to `true` on mount
- * because the server trusts `DESKTOP_USER_ID`, but `userId` only lands when
- * the async `useInitUserState` fetch resolves. `isUserStateInit` is the
- * signal there; using `isLoaded` would declare the anonymous boot scope
- * trustworthy and let that window's writes orphan into the `anon` partition.
+ * - Desktop: preload derives the OIDC subject from safe storage before React
+ * mounts. `isIdentityResolved` therefore selects the trusted cache partition
+ * without serializing first paint behind the full `getUserState()` request.
* - No-auth self-host: `isLoaded` is `true` on mount and `useInitUserState`
* never runs, so `userId` stays undefined forever and `anon` is the real,
* durable scope. `isDesktop` is false there, so `isLoaded` applies.
*/
const isIdentityResolved = (s: UserStore): boolean =>
- isDesktop ? s.isUserStateInit : Boolean(authSelectors.isLoaded(s));
+ isDesktop ? Boolean(s.isIdentityResolved) : Boolean(authSelectors.isLoaded(s));
/**
* The effective cache scope for the *current* moment.
diff --git a/src/spa/entry.desktop.tsx b/src/spa/entry.desktop.tsx
index 3ed712c2d00..849a4cea960 100644
--- a/src/spa/entry.desktop.tsx
+++ b/src/spa/entry.desktop.tsx
@@ -9,10 +9,12 @@ import { createElectronLocalDatabaseAdapter } from '@/libs/localDatabase/electro
import { createAppRouter } from '@/utils/router';
import { startAppInitialization } from './initialize/bootstrap';
+import { applyDesktopBootstrapIdentity } from './initialize/desktopIdentity';
import { desktopRoutes } from './router/desktopRouter.config';
import { createSPARoot } from './runtime';
registerLocalDatabaseAdapter(createElectronLocalDatabaseAdapter());
+applyDesktopBootstrapIdentity();
bootTiming.mark('bundle-eval');
startAppInitialization();
diff --git a/src/spa/initialize/desktopIdentity.test.ts b/src/spa/initialize/desktopIdentity.test.ts
new file mode 100644
index 00000000000..24ef24f0d83
--- /dev/null
+++ b/src/spa/initialize/desktopIdentity.test.ts
@@ -0,0 +1,60 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useUserStore } from '@/store/user';
+
+import { applyDesktopBootstrapIdentity } from './desktopIdentity';
+
+describe('applyDesktopBootstrapIdentity', () => {
+ beforeEach(() => {
+ delete window.electronAPI;
+ useUserStore.setState({
+ isIdentityResolved: undefined,
+ isLoaded: undefined,
+ isSignedIn: undefined,
+ user: undefined,
+ });
+ });
+
+ it('selects the signed-in cache identity before full user state is loaded', () => {
+ applyDesktopBootstrapIdentity({ isIdentityResolved: true, userId: 'user-1' });
+
+ expect(useUserStore.getState()).toMatchObject({
+ isIdentityResolved: true,
+ isLoaded: true,
+ isSignedIn: true,
+ user: { id: 'user-1' },
+ });
+ expect(useUserStore.getState().isUserStateInit).toBe(false);
+ });
+
+ it('clears the previous user when safe storage resolves signed-out', () => {
+ useUserStore.setState({ isSignedIn: true, user: { id: 'old-user' } as any });
+
+ applyDesktopBootstrapIdentity({ isIdentityResolved: true });
+
+ expect(useUserStore.getState()).toMatchObject({
+ isIdentityResolved: true,
+ isSignedIn: false,
+ user: undefined,
+ });
+ });
+
+ it('reads the identity through the preload bridge by default', () => {
+ const getDesktopBootstrapIdentity = vi.fn(() => ({
+ isIdentityResolved: true,
+ userId: 'bridge-user',
+ }));
+ window.electronAPI = {
+ getDesktopBootstrapIdentity,
+ onStreamInvoke: vi.fn(),
+ };
+
+ applyDesktopBootstrapIdentity();
+
+ expect(getDesktopBootstrapIdentity).toHaveBeenCalledOnce();
+ expect(useUserStore.getState().user?.id).toBe('bridge-user');
+ });
+});
diff --git a/src/spa/initialize/desktopIdentity.ts b/src/spa/initialize/desktopIdentity.ts
new file mode 100644
index 00000000000..8a20cbae23c
--- /dev/null
+++ b/src/spa/initialize/desktopIdentity.ts
@@ -0,0 +1,27 @@
+import type { DesktopBootstrapIdentity } from '@lobechat/electron-client-ipc';
+
+import { useUserStore } from '@/store/user';
+import type { LobeUser } from '@/types/user';
+
+export const applyDesktopBootstrapIdentity = (
+ identity:
+ DesktopBootstrapIdentity | undefined = window.electronAPI?.getDesktopBootstrapIdentity?.(),
+): void => {
+ if (!identity) return;
+
+ const state = useUserStore.getState();
+ const nextUser = identity.userId
+ ? state.user?.id === identity.userId
+ ? state.user
+ : ({ id: identity.userId } as LobeUser)
+ : identity.isIdentityResolved
+ ? undefined
+ : state.user;
+
+ useUserStore.setState({
+ isIdentityResolved: identity.isIdentityResolved,
+ isLoaded: true,
+ isSignedIn: identity.isIdentityResolved ? Boolean(identity.userId) : state.isSignedIn,
+ user: nextUser,
+ });
+};
diff --git a/src/spa/initialize/routePreload.ts b/src/spa/initialize/routePreload.ts
index 409f2a4e5db..e18ecb778a3 100644
--- a/src/spa/initialize/routePreload.ts
+++ b/src/spa/initialize/routePreload.ts
@@ -303,7 +303,7 @@ export const createRoutePreloadScheduler = (
let routePreloadStarted = false;
export const startRoutePreload = () => {
- if (routePreloadStarted || typeof window === 'undefined' || __ELECTRON__) return;
+ if (routePreloadStarted || typeof window === 'undefined') return;
routePreloadStarted = true;
const tasks = __MOBILE__ ? createMobileRoutePreloadTasks() : createWebRoutePreloadTasks();
diff --git a/src/spa/router/DesktopHomeRoute.tsx b/src/spa/router/DesktopHomeRoute.tsx
new file mode 100644
index 00000000000..8bb44b403a7
--- /dev/null
+++ b/src/spa/router/DesktopHomeRoute.tsx
@@ -0,0 +1,12 @@
+'use client';
+
+import DesktopHome from '@/routes/(main)/home';
+import DesktopHomeLayout from '@/routes/(main)/home/_layout';
+
+const DesktopHomeRoute = () => (
+ <DesktopHomeLayout>
+ <DesktopHome />
+ </DesktopHomeLayout>
+);
+
+export default DesktopHomeRoute;
diff --git a/src/spa/router/desktopRouter.bootInitOrder.test.ts b/src/spa/router/desktopRouter.bootInitOrder.test.ts
index cd389eecf5e..61261a24cc9 100644
--- a/src/spa/router/desktopRouter.bootInitOrder.test.ts
+++ b/src/spa/router/desktopRouter.bootInitOrder.test.ts
@@ -1,7 +1,7 @@
// Import ORDER is load-bearing and must not be reshuffled: the desktop boot
// evaluates the navigation facade (`NavigatorRegistrar.desktop` → `appNavigate`
// → `activeTabNavigate`) before the router config. If any of those statically
-// pull `desktopRouter.config` back in, the config twin runs its top-level
+// pull `desktopRouter.config` back in, the Electron adapter runs its top-level
// `redirectElement(...)` while `@/utils/router` is still initializing and hits
// a jsx-runtime TDZ ("Cannot access '_jsxDEV' before initialization"), leaving
// the renderer white-screened. This test wires that order up so a regression in
diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsx
index 7060eb5e973..9210300335a 100644
--- a/src/spa/router/desktopRouter.config.desktop.tsx
+++ b/src/spa/router/desktopRouter.config.desktop.tsx
@@ -1,923 +1,47 @@
'use client';
-import {
- BrainCircuit,
- Download,
- FilePenIcon,
- Image,
- LibraryBigIcon,
- MessageSquarePlus,
- Settings,
- ShapesIcon,
-} from 'lucide-react';
import type { RouteObject } from 'react-router';
-import {
- BusinessDesktopRoutesWithMainLayout,
- BusinessDesktopRoutesWithoutMainLayout,
- BusinessResourceRoutes,
-} from '@/business/client/BusinessDesktopRoutes';
-import { agentDocumentRouteMeta } from '@/features/AgentDocumentPage/routeMeta';
-import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';
-import { agentsRouteMeta } from '@/features/AgentViewAll/routeMeta';
-import { pageRouteMeta } from '@/features/Pages/routeMeta';
-import {
- acceptanceRouteMeta,
- verifyReportsRouteMeta,
- verifyRouteMeta,
-} from '@/features/Verify/routeMeta';
-import { workspaceHomeRouteMeta } from '@/features/Workspace/routeMeta';
-import DesktopOnboarding from '@/routes/(desktop)/desktop-onboarding';
-// Layouts — sync import (Electron local, no network overhead).
-// Unlike the web router, Electron intentionally does not register idle preload groups.
-import DesktopMainLayout from '@/routes/(main)/_layout';
-import ImagePage from '@/routes/(main)/(create)/image';
-import DesktopImageLayout from '@/routes/(main)/(create)/image/_layout';
-import VideoPage from '@/routes/(main)/(create)/video';
-import DesktopVideoLayout from '@/routes/(main)/(create)/video/_layout';
-import TaskWorkspaceLayout from '@/routes/(main)/(task-workspace)/_layout';
-import WorkspaceSlugLayout from '@/routes/(main)/[workspaceSlug]/_layout';
-import WorkspaceSlugSettingsIndexPage from '@/routes/(main)/[workspaceSlug]/settings';
-import WorkspaceSlugSettingsContentLayout from '@/routes/(main)/[workspaceSlug]/settings/_content-layout';
-import WorkspaceSlugSettingsLayout from '@/routes/(main)/[workspaceSlug]/settings/_layout';
-import WorkspaceSlugSettingsApiKeyPage from '@/routes/(main)/[workspaceSlug]/settings/apikey';
-import WorkspaceSlugSettingsAuditLogPage from '@/routes/(main)/[workspaceSlug]/settings/audit-log';
-import WorkspaceSlugSettingsBillingPage from '@/routes/(main)/[workspaceSlug]/settings/billing';
-import WorkspaceSlugSettingsBudgetPage from '@/routes/(main)/[workspaceSlug]/settings/budget';
-import WorkspaceSlugSettingsConnectorPage from '@/routes/(main)/[workspaceSlug]/settings/connector';
-import WorkspaceSlugSettingsCredentialPage from '@/routes/(main)/[workspaceSlug]/settings/credential';
-import WorkspaceSlugSettingsCreditsPage from '@/routes/(main)/[workspaceSlug]/settings/credits';
-import WorkspaceSlugSettingsDevicesPage from '@/routes/(main)/[workspaceSlug]/settings/devices';
-import WorkspaceSlugSettingsGeneralPage from '@/routes/(main)/[workspaceSlug]/settings/general';
-import WorkspaceSlugSettingsMembersPage from '@/routes/(main)/[workspaceSlug]/settings/members';
-import WorkspaceSlugSettingsNotificationPage from '@/routes/(main)/[workspaceSlug]/settings/notification';
-import WorkspaceSlugSettingsOAuthAppsPage from '@/routes/(main)/[workspaceSlug]/settings/oauth-apps';
-import WorkspaceSlugSettingsPlansPage from '@/routes/(main)/[workspaceSlug]/settings/plans';
-import WorkspaceSlugSettingsProviderPage from '@/routes/(main)/[workspaceSlug]/settings/provider';
-import WorkspaceSlugSettingsServiceModelPage from '@/routes/(main)/[workspaceSlug]/settings/service-model';
-import WorkspaceSlugSettingsSkillPage from '@/routes/(main)/[workspaceSlug]/settings/skill';
-import WorkspaceSlugSettingsStatisticsPage from '@/routes/(main)/[workspaceSlug]/settings/statistics';
-import WorkspaceSlugSettingsStoragePage from '@/routes/(main)/[workspaceSlug]/settings/storage';
-import WorkspaceSlugSettingsUsagePage from '@/routes/(main)/[workspaceSlug]/settings/usage';
-import AcceptanceWorkspace from '@/routes/(main)/acceptance';
-import AcceptanceEmptyPage from '@/routes/(main)/acceptance/empty';
-// Pages — sync import
-import AgentPage from '@/routes/(main)/agent';
-import DesktopChatLayout from '@/routes/(main)/agent/_layout';
-import DesktopAgentChatLayout from '@/routes/(main)/agent/(chat)/_layout';
-import AgentChannelPage from '@/routes/(main)/agent/channel';
-import AgentChannelPlatformPage from '@/routes/(main)/agent/channel/[platform]';
-import AgentDocumentsIndexRoute from '@/routes/(main)/agent/docs';
-import AgentDocumentLayout from '@/routes/(main)/agent/docs/_layout';
-import AgentDocumentRoute from '@/routes/(main)/agent/docs/[docId]';
-import {
- agentChannelRouteMeta,
- agentPermissionRouteMeta,
- agentProfileRouteMeta,
- agentRouteMeta,
- agentStatisticsRouteMeta,
- topicsRouteMeta,
-} from '@/routes/(main)/agent/features/routeMeta';
-import AgentPermissionPage from '@/routes/(main)/agent/permission';
-import AgentProfilePage from '@/routes/(main)/agent/profile';
-import AgentStatisticsPage from '@/routes/(main)/agent/statistics';
-import AgentTaskDetailRoute from '@/routes/(main)/agent/task/[taskId]';
-import AgentScopedTasksRoute from '@/routes/(main)/agent/tasks';
-import AgentTopicsPage from '@/routes/(main)/agent/topics';
-import AgentsViewAllRoute from '@/routes/(main)/agents';
-import CommunityLayout from '@/routes/(main)/community/_layout';
-import CommunityDetailLayout from '@/routes/(main)/community/(detail)/_layout';
-import CommunityDetailAgentPage from '@/routes/(main)/community/(detail)/agent';
-import CommunityDetailGroupAgentPage from '@/routes/(main)/community/(detail)/group_agent';
-import CommunityDetailMcpPage from '@/routes/(main)/community/(detail)/mcp';
-import CommunityDetailModelPage from '@/routes/(main)/community/(detail)/model';
-import CommunityDetailOrganizationPage from '@/routes/(main)/community/(detail)/organization';
-import CommunityDetailProviderPage from '@/routes/(main)/community/(detail)/provider';
-import CommunityDetailSkillPage from '@/routes/(main)/community/(detail)/skill';
-import CommunityDetailUserPage from '@/routes/(main)/community/(detail)/user';
-import CommunityDetailWorkspacePage from '@/routes/(main)/community/(detail)/workspace';
-import CommunityDetailWorkspaceSettingsPage from '@/routes/(main)/community/(detail)/workspace/settings';
-import CommunityListLayout from '@/routes/(main)/community/(list)/_layout';
-import CommunityListHomePage from '@/routes/(main)/community/(list)/(home)';
-import CommunityListAgentPage from '@/routes/(main)/community/(list)/agent';
-import CommunityListAgentLayout from '@/routes/(main)/community/(list)/agent/_layout';
-import CommunityListMcpPage from '@/routes/(main)/community/(list)/mcp';
-import CommunityListMcpLayout from '@/routes/(main)/community/(list)/mcp/_layout';
-import CommunityListModelPage from '@/routes/(main)/community/(list)/model';
-import CommunityListModelLayout from '@/routes/(main)/community/(list)/model/_layout';
-import CommunityListProviderPage from '@/routes/(main)/community/(list)/provider';
-import CommunityListSkillPage from '@/routes/(main)/community/(list)/skill';
-import CommunityListSkillLayout from '@/routes/(main)/community/(list)/skill/_layout';
-import DownloadsPage from '@/routes/(main)/downloads';
-import EvalOverviewPage from '@/routes/(main)/eval';
-import EvalLayout from '@/routes/(main)/eval/_layout';
-import EvalHomeLayout from '@/routes/(main)/eval/(home)/_layout';
-import EvalBenchmarkDetailPage from '@/routes/(main)/eval/bench/[benchmarkId]';
-import EvalBenchLayout from '@/routes/(main)/eval/bench/[benchmarkId]/_layout';
-import EvalDatasetDetailPage from '@/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]';
-import EvalRunDetailPage from '@/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]';
-import EvalCaseDetailPage from '@/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]';
-import EvalExperimentDetailPage from '@/routes/(main)/eval/experiments/[experimentId]';
-import GroupPage from '@/routes/(main)/group';
-import DesktopGroupLayout from '@/routes/(main)/group/_layout';
-import { groupProfileRouteMeta, groupRouteMeta } from '@/routes/(main)/group/features/routeMeta';
-import GroupProfilePage from '@/routes/(main)/group/profile';
-import DesktopHome from '@/routes/(main)/home';
-import DesktopHomeLayout from '@/routes/(main)/home/_layout';
-import DesktopMemoryLayout from '@/routes/(main)/memory/_layout';
-import MemoryHomePage from '@/routes/(main)/memory/(home)';
-import MemoryActivitiesPage from '@/routes/(main)/memory/activities';
-import MemoryContextsPage from '@/routes/(main)/memory/contexts';
-import MemoryExperiencesPage from '@/routes/(main)/memory/experiences';
-import MemoryIdentitiesPage from '@/routes/(main)/memory/identities';
-import MemoryPreferencesPage from '@/routes/(main)/memory/preferences';
-import PageIndexPage from '@/routes/(main)/page';
-import DesktopPageLayout from '@/routes/(main)/page/_layout';
-import PageDetailPage from '@/routes/(main)/page/[id]';
-import ResourceLayout from '@/routes/(main)/resource/_layout';
-import ResourceHomePage from '@/routes/(main)/resource/(home)';
-import ResourceHomeLayout from '@/routes/(main)/resource/(home)/_layout';
-import ResourceLibraryPage from '@/routes/(main)/resource/library';
-import ResourceLibraryLayout from '@/routes/(main)/resource/library/_layout';
-import ResourceLibrarySlugPage from '@/routes/(main)/resource/library/[slug]';
-import SettingsTabPage from '@/routes/(main)/settings';
-import SettingsLayout from '@/routes/(main)/settings/_layout';
-import { settingsRouteMeta } from '@/routes/(main)/settings/features/routeMeta';
-import { ProviderDetailPage, ProviderLayout } from '@/routes/(main)/settings/provider';
-import TaskDetailRoute from '@/routes/(main)/task/[taskId]';
-import AllTasksPage from '@/routes/(main)/tasks';
-import VerifyWorkspace from '@/routes/(main)/verify';
-import VerifyEmptyPage from '@/routes/(main)/verify/empty';
-import AcceptanceReportPage from '@/routes/acceptance/[acceptanceId]';
-import SharePagePage from '@/routes/share/page/[id]';
-import { sharePageRouteMeta } from '@/routes/share/page/[id]/routeMeta';
-import ShareTopicPage from '@/routes/share/t/[id]';
-import ShareTopicLayout from '@/routes/share/t/[id]/_layout';
-import { shareTopicRouteMeta } from '@/routes/share/t/[id]/routeMeta';
-import VerifyReportPage from '@/routes/verify/[runId]';
-import { routeMeta } from '@/spa/router/routeMeta';
-import { SettingsTabs } from '@/store/global/initialState';
-import { ErrorBoundary, redirectElement } from '@/utils/router';
-
-/**
- * Children shared between `/` and `/:workspaceSlug` for the Electron build.
- * Mirror of the async `sharedMainAreaChildren` — paths must match (the router
- * sync test enforces this).
- */
-export const sharedMainAreaChildren: RouteObject[] = [
- // Chat routes (agent)
- {
- children: [
- {
- element: redirectElement('..'),
- index: true,
- },
- {
- children: [
- {
- children: [
- {
- element: <AgentPage />,
- handle: { meta: agentRouteMeta },
- index: true,
- },
- {
- element: <AgentPage />,
- handle: { meta: agentRouteMeta },
- path: ':topicId',
- },
- ],
- element: <DesktopAgentChatLayout />,
- },
- {
- children: [
- {
- element: <AgentDocumentsIndexRoute />,
- index: true,
- },
- {
- element: <AgentDocumentRoute />,
- handle: { meta: agentDocumentRouteMeta },
- path: ':docId',
- },
- ],
- element: <AgentDocumentLayout />,
- path: 'docs',
- },
- {
- element: <AgentProfilePage />,
- handle: { meta: agentProfileRouteMeta },
- path: 'profile',
- },
- {
- element: <AgentChannelPage />,
- handle: { meta: agentChannelRouteMeta },
- path: 'channel',
- },
- {
- element: <AgentChannelPlatformPage />,
- handle: { meta: agentChannelRouteMeta },
- path: 'channel/:platform',
- },
- {
- element: <AgentTopicsPage />,
- handle: { meta: topicsRouteMeta },
- path: 'topics',
- },
- {
- element: <AgentStatisticsPage />,
- handle: { meta: agentStatisticsRouteMeta },
- path: 'statistics',
- },
- // Legacy `/agent/:aid/stats` URLs — kept for deep-links.
- { element: redirectElement('../statistics'), path: 'stats' },
- {
- element: <AgentPermissionPage />,
- handle: { meta: agentPermissionRouteMeta },
- path: 'permission',
- },
- {
- element: <AgentScopedTasksRoute />,
- handle: { meta: tasksRouteMeta },
- path: 'tasks',
- },
- {
- element: <AgentTaskDetailRoute />,
- handle: { meta: taskRouteMeta },
- path: 'task/:taskId',
- },
- ],
- element: <DesktopChatLayout />,
- errorElement: <ErrorBoundary />,
- path: ':aid',
- },
- ],
- path: 'agent',
- },
-
- // Group chat routes
- {
- children: [
- {
- element: redirectElement('..'),
- index: true,
- },
- {
- children: [
- {
- element: <GroupPage />,
- handle: { meta: groupRouteMeta },
- index: true,
- },
- {
- element: <GroupProfilePage />,
- handle: { meta: groupProfileRouteMeta },
- path: 'profile',
- },
- {
- element: <GroupPage />,
- handle: { meta: groupRouteMeta },
- path: ':topicId',
- },
- ],
- element: <DesktopGroupLayout />,
- errorElement: <ErrorBoundary />,
- path: ':gid',
- },
- ],
- path: 'group',
- },
-
- // Discover routes with nested structure
- {
- children: [
- {
- element: <CommunityDetailWorkspaceSettingsPage />,
- path: 'workspace/settings',
- },
- // List routes (with ListLayout)
- {
- children: [
- {
- children: [
- {
- element: <CommunityListAgentPage />,
- handle: {
- meta: routeMeta({
- icon: ShapesIcon,
- titleKey: 'navigation.discoverAssistants',
- }),
- },
- index: true,
- },
- ],
- element: <CommunityListAgentLayout />,
- path: 'agent',
- },
- {
- children: [
- {
- element: <CommunityListModelPage />,
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverModels' }),
- },
- index: true,
- },
- ],
- element: <CommunityListModelLayout />,
- path: 'model',
- },
- {
- element: <CommunityListProviderPage />,
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverProviders' }),
- },
- path: 'provider',
- },
- {
- children: [
- {
- element: <CommunityListSkillPage />,
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discover' }),
- },
- index: true,
- },
- ],
- element: <CommunityListSkillLayout />,
- path: 'skill',
- },
- {
- children: [
- {
- element: <CommunityListMcpPage />,
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverMcp' }),
- },
- index: true,
- },
- ],
- element: <CommunityListMcpLayout />,
- path: 'mcp',
- },
- {
- element: <CommunityDetailWorkspacePage />,
- path: 'workspace',
- },
- {
- element: <CommunityListHomePage />,
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discover' }),
- },
- index: true,
- },
- ],
- element: <CommunityListLayout />,
- },
- // Detail routes (with DetailLayout)
- {
- children: [
- {
- element: <CommunityDetailAgentPage />,
- path: 'agent/:slug',
- },
- {
- element: <CommunityDetailGroupAgentPage />,
- path: 'group_agent/:slug',
- },
- {
- element: <CommunityDetailModelPage />,
- path: 'model/:slug',
- },
- {
- element: <CommunityDetailProviderPage />,
- path: 'provider/:slug',
- },
- {
- element: <CommunityDetailSkillPage />,
- path: 'skill/:slug',
- },
- {
- element: <CommunityDetailMcpPage />,
- path: 'mcp/:slug',
- },
- {
- element: <CommunityDetailUserPage />,
- path: 'user/:slug',
- },
- {
- element: <CommunityDetailOrganizationPage />,
- path: 'org/:slug',
- },
- ],
- element: <CommunityDetailLayout />,
- },
- ],
- element: <CommunityLayout />,
- errorElement: <ErrorBoundary />,
- path: 'community',
- },
-
- // Resource routes
- {
- children: [
- // Home routes (resource list)
- {
- children: [
- {
- element: <ResourceHomePage />,
- handle: {
- meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.resources' }),
- },
- index: true,
- },
- ...BusinessResourceRoutes,
- ],
- element: <ResourceHomeLayout />,
- },
- // Library routes (knowledge base detail)
- {
- children: [
- {
- element: <ResourceLibraryPage />,
- handle: {
- meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),
- },
- index: true,
- },
- {
- element: <ResourceLibrarySlugPage />,
- handle: {
- meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),
- },
- path: ':slug',
- },
- ],
- element: <ResourceLibraryLayout />,
- path: 'library/:id',
- },
- ],
- element: <ResourceLayout />,
- errorElement: <ErrorBoundary />,
- path: 'resource',
- },
-
- // Memory routes
- {
- children: [
- {
- element: <MemoryHomePage />,
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),
- },
- index: true,
- },
- {
- element: <MemoryIdentitiesPage />,
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryIdentities' }),
- },
- path: 'identities',
- },
- {
- element: <MemoryContextsPage />,
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryContexts' }),
- },
- path: 'contexts',
- },
- {
- element: <MemoryPreferencesPage />,
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryPreferences' }),
- },
- path: 'preferences',
- },
- {
- element: <MemoryExperiencesPage />,
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryExperiences' }),
- },
- path: 'experiences',
- },
- {
- element: <MemoryActivitiesPage />,
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),
- },
- path: 'activities',
- },
- ],
- element: <DesktopMemoryLayout />,
- errorElement: <ErrorBoundary />,
- path: 'memory',
- },
-
- // Video routes
- {
- children: [
- {
- element: <VideoPage />,
- index: true,
- },
- ],
- element: <DesktopVideoLayout />,
- errorElement: <ErrorBoundary />,
- path: 'video',
- },
-
- // Image routes
- {
- children: [
- {
- element: <ImagePage />,
- handle: {
- meta: routeMeta({ icon: Image, titleKey: 'navigation.image' }),
- },
- index: true,
- },
- ],
- element: <DesktopImageLayout />,
- errorElement: <ErrorBoundary />,
- path: 'image',
- },
-
- ...BusinessDesktopRoutesWithMainLayout,
-
- // Eval routes
- {
- children: [
- // Home (overview)
- {
- children: [
- {
- element: <EvalOverviewPage />,
- index: true,
- },
- {
- element: <EvalExperimentDetailPage />,
- path: 'experiments/:experimentId',
- },
- ],
- element: <EvalHomeLayout />,
- },
- // Bench routes (with dedicated sidebar)
- {
- children: [
- {
- element: <EvalBenchmarkDetailPage />,
- index: true,
- },
- {
- children: [
- {
- element: <EvalRunDetailPage />,
- index: true,
- },
- {
- element: <EvalCaseDetailPage />,
- path: 'cases/:caseId',
- },
- ],
- path: 'runs/:runId',
- },
- {
- element: <EvalDatasetDetailPage />,
- path: 'datasets/:datasetId',
- },
- ],
- element: <EvalBenchLayout />,
- path: 'bench/:benchmarkId',
- },
- ],
- element: <EvalLayout />,
- errorElement: <ErrorBoundary />,
- path: 'eval',
- },
-
- // Agents view-all route (flat list of workspace/private agents)
- {
- children: [
- {
- element: <AgentsViewAllRoute />,
- handle: { meta: agentsRouteMeta },
- index: true,
- },
- ],
- errorElement: <ErrorBoundary resetPath=".." />,
- path: 'agents',
- },
-
- // Task workspace routes (cross-agent)
- {
- children: [
- {
- children: [
- {
- element: <AllTasksPage />,
- handle: { meta: tasksRouteMeta },
- index: true,
- },
- ],
- errorElement: <ErrorBoundary resetPath=".." />,
- path: 'tasks',
- },
- {
- children: [
- {
- element: <TaskDetailRoute />,
- handle: { meta: taskRouteMeta },
- path: ':taskId',
- },
- ],
- errorElement: <ErrorBoundary resetPath="../tasks" />,
- path: 'task',
- },
- ],
- element: <TaskWorkspaceLayout />,
- },
-
- // Pages routes
- {
- children: [
- {
- element: <PageIndexPage />,
- handle: {
- meta: routeMeta({ icon: FilePenIcon, titleKey: 'navigation.pages' }),
- },
- index: true,
- },
- {
- element: <PageDetailPage />,
- handle: { meta: pageRouteMeta },
- path: ':id',
- },
- ],
- element: <DesktopPageLayout />,
- errorElement: <ErrorBoundary />,
- path: 'page',
- },
-];
-
-export const createMainAreaChildren = (): RouteObject[] => [
- ...sharedMainAreaChildren,
-
- // Downloads page (personal-only — never mirrored under /:workspaceSlug)
- {
- element: <DownloadsPage />,
- errorElement: <ErrorBoundary />,
- handle: { meta: routeMeta({ icon: Download, titleKey: 'navigation.downloads' }) },
- path: 'downloads',
- },
-
- // Settings routes (personal-only — never mirrored under /:workspaceSlug)
- {
- children: [
- {
- element: redirectElement('/settings/profile'),
- index: true,
- },
- // Provider routes with nested structure
- {
- children: [
- {
- element: redirectElement('/settings/provider/all'),
- index: true,
- },
- {
- element: <ProviderDetailPage />,
- handle: {
- meta: routeMeta({ icon: Settings, titleKey: 'navigation.provider' }),
- },
- path: ':providerId',
- },
- ],
- element: <ProviderLayout />,
- handle: {
- meta: routeMeta({ icon: Settings, titleKey: 'navigation.provider' }),
- },
- path: 'provider',
- },
- {
- element: <SettingsTabPage />,
- handle: { settingsTab: SettingsTabs.Memory },
- path: 'memory',
- },
- {
- element: redirectElement('/settings/credential'),
- path: 'creds',
- },
- // Other settings tabs
- {
- element: <SettingsTabPage />,
- handle: { meta: settingsRouteMeta },
- path: ':tab',
- },
- // Tabs that need a sub-segment (e.g. /settings/messenger/discord) reuse
- // the same tab page; nested feature components read `:sub` via useParams.
- {
- element: <SettingsTabPage />,
- handle: { meta: settingsRouteMeta },
- path: ':tab/:sub',
- },
- ],
- element: <SettingsLayout />,
- errorElement: <ErrorBoundary />,
- path: 'settings',
- },
-
- // Workspace slug routes — `/:workspaceSlug/*` mirrors the shared main area.
- // Must come AFTER all reserved root paths so they don't shadow e.g. /agent.
- {
- children: [
- // Workspace home — rendered as tab content (mirrors `/` index). Each tab
- // owns its location, so the home element only mounts inside a home tab.
- {
- element: (
- <DesktopHomeLayout>
- <DesktopHome />
- </DesktopHomeLayout>
- ),
- handle: { meta: workspaceHomeRouteMeta },
- index: true,
- },
- ...sharedMainAreaChildren,
- // Workspace settings — `/:slug/settings/*`. Dedicated layout with
- // its own sidebar (workspace avatar + 6 tabs + back-to-chat), fully
- // decoupled from personal `/settings/*`.
- {
- children: [
- { element: <WorkspaceSlugSettingsIndexPage />, index: true },
- // Full-bleed tabs render directly inside the workspace settings
- // shell (sidebar + outlet) — they own their internal layout.
- { element: <WorkspaceSlugSettingsProviderPage />, path: 'provider' },
- { element: <WorkspaceSlugSettingsSkillPage />, path: 'skill' },
- { element: <WorkspaceSlugSettingsConnectorPage />, path: 'connector' },
- // Padded tabs share a centered, max-width container layout.
- {
- children: [
- { element: <WorkspaceSlugSettingsGeneralPage />, path: 'general' },
- { element: <WorkspaceSlugSettingsMembersPage />, path: 'members' },
- { element: <WorkspaceSlugSettingsNotificationPage />, path: 'notification' },
- { element: <WorkspaceSlugSettingsStatisticsPage />, path: 'statistics' },
- // Legacy `/:slug/settings/stats` URLs — kept for deep-links.
- { element: redirectElement('../statistics'), path: 'stats' },
- { element: <WorkspaceSlugSettingsPlansPage />, path: 'plans' },
- { element: <WorkspaceSlugSettingsBillingPage />, path: 'billing' },
- { element: <WorkspaceSlugSettingsBudgetPage />, path: 'budget' },
- { element: <WorkspaceSlugSettingsCreditsPage />, path: 'credits' },
- { element: <WorkspaceSlugSettingsUsagePage />, path: 'usage' },
- { element: <WorkspaceSlugSettingsServiceModelPage />, path: 'service-model' },
- { element: <WorkspaceSlugSettingsCredentialPage />, path: 'credential' },
- // Legacy `/:slug/settings/creds` URLs — kept for deep-links.
- { element: redirectElement('../credential'), path: 'creds' },
- { element: <WorkspaceSlugSettingsApiKeyPage />, path: 'apikey' },
- { element: <WorkspaceSlugSettingsOAuthAppsPage />, path: 'oauth-apps' },
- { element: <WorkspaceSlugSettingsOAuthAppsPage />, path: 'oauth-apps/:sub' },
- { element: <WorkspaceSlugSettingsAuditLogPage />, path: 'audit-log' },
- { element: <WorkspaceSlugSettingsStoragePage />, path: 'storage' },
- { element: <WorkspaceSlugSettingsDevicesPage />, path: 'devices' },
- ],
- element: <WorkspaceSlugSettingsContentLayout />,
- },
- ],
- element: <WorkspaceSlugSettingsLayout />,
- errorElement: <ErrorBoundary />,
- path: 'settings',
- },
- // Legacy `/:slug/billing/*` URLs — redirect to `/:slug/settings/*`.
- {
- children: [
- { element: redirectElement('../settings/plans'), path: 'plans' },
- { element: redirectElement('../settings/usage'), path: 'usage' },
- { element: redirectElement('../settings/credits'), path: 'credits' },
- { element: redirectElement('../settings/billing'), path: 'billing' },
- ],
- path: 'billing',
- },
- ],
- element: <WorkspaceSlugLayout />,
- errorElement: <ErrorBoundary />,
- path: ':workspaceSlug',
- },
+import { dynamicElement, ErrorBoundary } from '@/utils/router';
- // Default route - home page (rendered as tab content)
- {
- element: (
- <DesktopHomeLayout>
- <DesktopHome />
- </DesktopHomeLayout>
+import {
+ createMainAreaRouteFactory,
+ createSharedDesktopRoutes,
+ type MainAreaRouteOptions,
+} from './desktopRouter.shared';
+
+export { sharedMainAreaChildren } from './desktopRouter.shared';
+
+const mainAreaRouteOptions: MainAreaRouteOptions = {
+ createHomeElement: () => dynamicElement(() => import('./DesktopHomeRoute'), 'Desktop > Home'),
+ createWorkspaceSettingsIndexElement: () =>
+ dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings'),
+ 'Desktop > Workspace > Settings > Index',
),
- handle: {
- meta: routeMeta({
- icon: MessageSquarePlus,
- tabTitleKey: 'navigation.newChat',
- titleKey: 'navigation.home',
- }),
- },
- index: true,
- },
- // Catch-all route
- {
- element: redirectElement('/'),
- path: '*',
- },
-];
+};
+
+export const createMainAreaChildren = createMainAreaRouteFactory(mainAreaRouteOptions);
-// Meta-resolution route tree consumed by the desktop tab bar / recently-viewed
-// panels. Twin-identical to the async config so `matchRouteMeta` resolves every
-// tab url's static meta — the `/` root router below only hosts the TabHost shell
-// (slim null-stub children with no meta), so the consumers must match against
-// this populated tree, never `desktopRoutes`.
+// The Electron root router contains only TabHost stubs, so tab titles and
+// recently-viewed entries resolve metadata against this complete content tree.
export const mainAreaMetaRoutes: RouteObject[] = [
{ children: createMainAreaChildren(), path: '/' },
];
-// Desktop router configuration — all sync imports for Electron local build.
-// The `/` route only hosts the TabHost shell; page content lives in per-tab
-// routers built from `createMainAreaChildren()` (see `tabRouter.tsx`).
-export const desktopRoutes: RouteObject[] = [
- {
- children: [
- { element: null, index: true },
- { element: null, path: '*' },
- ],
- element: <DesktopMainLayout />,
- errorElement: <ErrorBoundary />,
- path: '/',
- },
-
- ...BusinessDesktopRoutesWithoutMainLayout,
-
- // Share topic route (outside main layout)
- {
- children: [
- {
- element: <ShareTopicPage />,
- handle: { meta: shareTopicRouteMeta },
- path: ':id',
- },
- ],
- element: <ShareTopicLayout />,
- path: '/share/t',
- },
-
- // Share page route (outside main layout)
- {
- children: [
- {
- element: <SharePagePage />,
- handle: { meta: sharePageRouteMeta },
- path: ':id',
- },
- ],
- path: '/share/page',
- },
-
- // Verify report workspace — standalone master-detail (outside main layout)
- {
- children: [
- { element: <VerifyEmptyPage />, index: true },
- {
- element: <VerifyReportPage />,
- handle: { meta: verifyRouteMeta },
- path: ':runId',
- },
- ],
- element: <VerifyWorkspace />,
- errorElement: <ErrorBoundary />,
- handle: { meta: verifyReportsRouteMeta },
- path: '/verify',
- },
-
- // Subject-level delivery acceptance — the verify workspace's twin: a
- // master-detail with the acceptance list on the left.
- {
- children: [
- { element: <AcceptanceEmptyPage />, index: true },
- {
- element: <AcceptanceReportPage />,
- handle: { meta: acceptanceRouteMeta },
- path: ':acceptanceId',
- },
- {
- element: <AcceptanceReportPage />,
- handle: { meta: acceptanceRouteMeta },
- path: ':acceptanceId/check/:checkId',
- },
- ],
- element: <AcceptanceWorkspace />,
+export const desktopRoutes: RouteObject[] = createSharedDesktopRoutes({
+ // Page content is mounted by per-tab memory routers. The root owns only the
+ // persistent TabHost shell and must not render a second copy of the pages.
+ mainAreaChildren: [
+ { element: null, index: true },
+ { element: null, path: '*' },
+ ],
+ onboardingRoute: {
+ element: dynamicElement(
+ () => import('@/routes/(desktop)/desktop-onboarding'),
+ 'Desktop > Desktop Onboarding',
+ ),
errorElement: <ErrorBoundary />,
- handle: { meta: acceptanceRouteMeta },
- path: '/acceptance',
+ path: '/desktop-onboarding',
},
-];
-
-// Desktop owns its onboarding flow. Web-only onboarding routes are intentionally
-// absent from Electron so personal onboarding redirects fail visibly instead of
-// looping back into desktop login.
-desktopRoutes.push({
- element: <DesktopOnboarding />,
- errorElement: <ErrorBoundary />,
- path: '/desktop-onboarding',
});
diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsx
index d46aaea541b..69850394a00 100644
--- a/src/spa/router/desktopRouter.config.tsx
+++ b/src/spa/router/desktopRouter.config.tsx
@@ -1,1132 +1,30 @@
'use client';
-import {
- BrainCircuit,
- Download,
- FilePenIcon,
- Image,
- LibraryBigIcon,
- MessageSquarePlus,
- Settings,
- ShapesIcon,
-} from 'lucide-react';
-import { type RouteObject } from 'react-router';
+import type { RouteObject } from 'react-router';
-import {
- BusinessDesktopRoutesWithMainLayout,
- BusinessDesktopRoutesWithoutMainLayout,
- BusinessResourceRoutes,
-} from '@/business/client/BusinessDesktopRoutes';
-import { agentDocumentRouteMeta } from '@/features/AgentDocumentPage/routeMeta';
-import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';
-import { agentsRouteMeta } from '@/features/AgentViewAll/routeMeta';
-import { pageRouteMeta } from '@/features/Pages/routeMeta';
import {
acceptanceRouteMeta,
verifyReportsRouteMeta,
verifyRouteMeta,
} from '@/features/Verify/routeMeta';
-import { workspaceHomeRouteMeta } from '@/features/Workspace/routeMeta';
-import {
- agentChannelRouteMeta,
- agentPermissionRouteMeta,
- agentProfileRouteMeta,
- agentRouteMeta,
- agentStatisticsRouteMeta,
- topicsRouteMeta,
-} from '@/routes/(main)/agent/features/routeMeta';
-import { groupProfileRouteMeta, groupRouteMeta } from '@/routes/(main)/group/features/routeMeta';
-import { settingsRouteMeta } from '@/routes/(main)/settings/features/routeMeta';
import { sharePageRouteMeta } from '@/routes/share/page/[id]/routeMeta';
import { shareTopicRouteMeta } from '@/routes/share/t/[id]/routeMeta';
import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';
-import { routeMeta } from '@/spa/router/routeMeta';
-import { SettingsTabs } from '@/store/global/initialState';
-import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';
-
-const agentChatElement = dynamicElement(
- () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/(main)/agent')),
- 'Desktop > Chat',
- { preloadId: 'agent' },
-);
+import { dynamicElement, ErrorBoundary } from '@/utils/router';
-const groupChatElement = dynamicElement(
- () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/(main)/group')),
- 'Desktop > Agent Group',
- { preloadId: 'group' },
-);
-
-/**
- * Children shared between the root tree (`/`) and the workspace tree
- * (`/:workspaceSlug`). Personal-only segments (settings, index, catch-all,
- * the workspace-slug block itself) are NOT included.
- *
- * Index redirects inside this list use **relative paths** so they resolve
- * correctly under both `/` (→ `/`) and `/:workspaceSlug` (→ `/:workspaceSlug`).
- */
-export const sharedMainAreaChildren: RouteObject[] = [
- // Chat routes (agent)
- {
- children: [
- {
- element: redirectElement('..'),
- index: true,
- },
- {
- children: [
- {
- children: [
- {
- element: agentChatElement,
- handle: { meta: agentRouteMeta },
- index: true,
- },
- {
- element: agentChatElement,
- handle: { meta: agentRouteMeta },
- path: ':topicId',
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/agent/(chat)/_layout'),
- 'Desktop > Chat > ChatLayout',
- { preloadId: 'agent' },
- ),
- },
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/agent/docs'),
- 'Desktop > Chat > DocumentsIndex',
- ),
- index: true,
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/agent/docs/[docId]'),
- 'Desktop > Chat > Document',
- ),
- handle: { meta: agentDocumentRouteMeta },
- path: ':docId',
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/agent/docs/_layout'),
- 'Desktop > Chat > DocumentLayout',
- ),
- path: 'docs',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/agent/profile'),
- 'Desktop > Chat > Profile',
- ),
- handle: { meta: agentProfileRouteMeta },
- path: 'profile',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/agent/channel'),
- 'Desktop > Chat > Channel',
- ),
- handle: { meta: agentChannelRouteMeta },
- path: 'channel',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/agent/channel/[platform]'),
- 'Desktop > Chat > Channel Platform',
- ),
- handle: { meta: agentChannelRouteMeta },
- path: 'channel/:platform',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/agent/topics'),
- 'Desktop > Chat > Topics',
- ),
- handle: { meta: topicsRouteMeta },
- path: 'topics',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/agent/statistics'),
- 'Desktop > Chat > Statistics',
- ),
- handle: { meta: agentStatisticsRouteMeta },
- path: 'statistics',
- },
- // Legacy `/agent/:aid/stats` URLs — kept for deep-links.
- {
- element: redirectElement('../statistics'),
- path: 'stats',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/agent/permission'),
- 'Desktop > Chat > Permission',
- ),
- handle: { meta: agentPermissionRouteMeta },
- path: 'permission',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/agent/tasks'),
- 'Desktop > Chat > Tasks',
- ),
- handle: { meta: tasksRouteMeta },
- path: 'tasks',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/agent/task/[taskId]'),
- 'Desktop > Chat > Task Detail',
- ),
- handle: { meta: taskRouteMeta },
- path: 'task/:taskId',
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/agent/_layout'),
- 'Desktop > Chat > Layout',
- { preloadId: 'agent' },
- ),
- errorElement: <ErrorBoundary />,
- path: ':aid',
- },
- ],
- path: 'agent',
- },
+import { createMainAreaRouteFactory, createSharedDesktopRoutes } from './desktopRouter.shared';
- // Group chat routes
- {
- children: [
- {
- element: redirectElement('..'),
- index: true,
- },
- {
- children: [
- {
- element: groupChatElement,
- handle: { meta: groupRouteMeta },
- index: true,
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/group/profile'),
- 'Desktop > Agent Group > Profile',
- ),
- handle: { meta: groupProfileRouteMeta },
- path: 'profile',
- },
- {
- element: groupChatElement,
- handle: { meta: groupRouteMeta },
- path: ':topicId',
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/group/_layout'),
- 'Desktop > Group > Layout',
- { preloadId: 'group' },
- ),
- errorElement: <ErrorBoundary />,
- path: ':gid',
- },
- ],
- path: 'group',
- },
-
- // Discover routes with nested structure
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/workspace/settings'),
- 'Desktop > Discover > Workspace > Settings',
- ),
- path: 'workspace/settings',
- },
- // List routes (with ListLayout)
- {
- children: [
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/agent'),
- 'Desktop > Discover > List > Agent',
- ),
- handle: {
- meta: routeMeta({
- icon: ShapesIcon,
- titleKey: 'navigation.discoverAssistants',
- }),
- },
- index: true,
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/agent/_layout'),
- 'Desktop > Discover > List > Agent > Layout',
- ),
- path: 'agent',
- },
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/model'),
- 'Desktop > Discover > List > Model',
- ),
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverModels' }),
- },
- index: true,
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/model/_layout'),
- 'Desktop > Discover > List > Model > Layout',
- ),
- path: 'model',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/provider'),
- 'Desktop > Discover > List > Provider',
- ),
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverProviders' }),
- },
- path: 'provider',
- },
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/skill'),
- 'Desktop > Discover > List > Skill',
- ),
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discover' }),
- },
- index: true,
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/skill/_layout'),
- 'Desktop > Discover > List > Skill > Layout',
- ),
- path: 'skill',
- },
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/mcp'),
- 'Desktop > Discover > List > MCP',
- ),
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverMcp' }),
- },
- index: true,
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/mcp/_layout'),
- 'Desktop > Discover > List > MCP > Layout',
- ),
- path: 'mcp',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/workspace'),
- 'Desktop > Discover > List > Workspace',
- ),
- path: 'workspace',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/(home)'),
- 'Desktop > Discover > List > Home',
- { preloadId: 'community' },
- ),
- handle: {
- meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discover' }),
- },
- index: true,
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/community/(list)/_layout'),
- 'Desktop > Discover > List > Layout',
- { preloadId: 'community' },
- ),
- },
- // Detail routes (with DetailLayout)
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/agent'),
- 'Desktop > Discover > Detail > Agent',
- ),
- path: 'agent/:slug',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/group_agent'),
- 'Desktop > Discover > Detail > Group Agent',
- ),
- path: 'group_agent/:slug',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/model'),
- 'Desktop > Discover > Detail > Model',
- ),
- path: 'model/:slug',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/provider'),
- 'Desktop > Discover > Detail > Provider',
- ),
- path: 'provider/:slug',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/skill'),
- 'Desktop > Discover > Detail > Skill',
- ),
- path: 'skill/:slug',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/mcp'),
- 'Desktop > Discover > Detail > MCP',
- ),
- path: 'mcp/:slug',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/user'),
- 'Desktop > Discover > Detail > User',
- ),
- path: 'user/:slug',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/organization'),
- 'Desktop > Discover > Detail > Organization',
- ),
- path: 'org/:slug',
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/community/(detail)/_layout'),
- 'Desktop > Discover > Detail > Layout',
- ),
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/community/_layout'),
- 'Desktop > Discover > Layout',
- { preloadId: 'community' },
- ),
- errorElement: <ErrorBoundary />,
- path: 'community',
- },
-
- // Resource routes
- {
- children: [
- // Home routes (resource list)
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/resource/(home)'),
- 'Desktop > Resource > Home',
- { preloadId: 'resource' },
- ),
- handle: {
- meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.resources' }),
- },
- index: true,
- },
- ...BusinessResourceRoutes,
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/resource/(home)/_layout'),
- 'Desktop > Resource > Home > Layout',
- { preloadId: 'resource' },
- ),
- },
- // Library routes (knowledge base detail)
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/resource/library'),
- 'Desktop > Resource > Library',
- ),
- handle: {
- meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),
- },
- index: true,
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/resource/library/[slug]'),
- 'Desktop > Resource > Library > Slug',
- ),
- handle: {
- meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),
- },
- path: ':slug',
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/resource/library/_layout'),
- 'Desktop > Resource > Library > Layout',
- ),
- path: 'library/:id',
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/resource/_layout'),
- 'Desktop > Resource > Layout',
- { preloadId: 'resource' },
- ),
- errorElement: <ErrorBoundary />,
- path: 'resource',
- },
-
- // Memory routes
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/memory/(home)'),
- 'Desktop > Memory > Home',
- { preloadId: 'memory' },
- ),
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),
- },
- index: true,
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/memory/identities'),
- 'Desktop > Memory > Identities',
- ),
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryIdentities' }),
- },
- path: 'identities',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/memory/contexts'),
- 'Desktop > Memory > Contexts',
- ),
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryContexts' }),
- },
- path: 'contexts',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/memory/preferences'),
- 'Desktop > Memory > Preferences',
- ),
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryPreferences' }),
- },
- path: 'preferences',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/memory/experiences'),
- 'Desktop > Memory > Experiences',
- ),
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryExperiences' }),
- },
- path: 'experiences',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/memory/activities'),
- 'Desktop > Memory > Activities',
- ),
- handle: {
- meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),
- },
- path: 'activities',
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/memory/_layout'),
- 'Desktop > Memory > Layout',
- { preloadId: 'memory' },
- ),
- errorElement: <ErrorBoundary />,
- path: 'memory',
- },
-
- // Video routes
- {
- children: [
- {
- element: dynamicElement(() => import('@/routes/(main)/(create)/video'), 'Desktop > Video', {
- preloadId: 'video',
- }),
- index: true,
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/(create)/video/_layout'),
- 'Desktop > Video > Layout',
- { preloadId: 'video' },
- ),
- errorElement: <ErrorBoundary />,
- path: 'video',
- },
-
- // Image routes
- {
- children: [
- {
- element: dynamicElement(() => import('@/routes/(main)/(create)/image'), 'Desktop > Image', {
- preloadId: 'image',
- }),
- handle: {
- meta: routeMeta({ icon: Image, titleKey: 'navigation.image' }),
- },
- index: true,
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/(create)/image/_layout'),
- 'Desktop > Image > Layout',
- { preloadId: 'image' },
- ),
- errorElement: <ErrorBoundary />,
- path: 'image',
- },
+export { sharedMainAreaChildren } from './desktopRouter.shared';
- ...BusinessDesktopRoutesWithMainLayout,
+export const createMainAreaChildren = createMainAreaRouteFactory();
- // Eval routes
- {
- children: [
- // Home (overview)
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/eval'),
- 'Desktop > Eval > Overview',
- { preloadId: 'eval' },
- ),
- index: true,
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/eval/experiments/[experimentId]'),
- 'Desktop > Eval > Experiment Detail',
- ),
- path: 'experiments/:experimentId',
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/eval/(home)/_layout'),
- 'Desktop > Eval > Home > Layout',
- { preloadId: 'eval' },
- ),
- },
- // Bench routes (with dedicated sidebar)
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/eval/bench/[benchmarkId]'),
- 'Desktop > Eval > Benchmark Detail',
- ),
- index: true,
- },
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]'),
- 'Desktop > Eval > Run Detail',
- ),
- index: true,
- },
- {
- element: dynamicElement(
- () =>
- import('@/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]'),
- 'Desktop > Eval > Case Detail',
- ),
- path: 'cases/:caseId',
- },
- ],
- path: 'runs/:runId',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]'),
- 'Desktop > Eval > Dataset Detail',
- ),
- path: 'datasets/:datasetId',
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/eval/bench/[benchmarkId]/_layout'),
- 'Desktop > Eval > Bench > Layout',
- ),
- path: 'bench/:benchmarkId',
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/eval/_layout'),
- 'Desktop > Eval > Layout',
- { preloadId: 'eval' },
- ),
- errorElement: <ErrorBoundary />,
- path: 'eval',
- },
-
- // Agents view-all route (flat list of workspace/private agents)
- {
- children: [
- {
- element: dynamicElement(() => import('@/routes/(main)/agents'), 'Desktop > Agents', {
- preloadId: 'agents',
- }),
- handle: { meta: agentsRouteMeta },
- index: true,
- },
- ],
- errorElement: <ErrorBoundary resetPath=".." />,
- path: 'agents',
- },
-
- // Task workspace routes (cross-agent)
- {
- children: [
- {
- children: [
- {
- element: dynamicElement(() => import('@/routes/(main)/tasks'), 'Desktop > Tasks', {
- preloadId: 'tasks',
- }),
- handle: { meta: tasksRouteMeta },
- index: true,
- },
- ],
- errorElement: <ErrorBoundary resetPath=".." />,
- path: 'tasks',
- },
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/task/[taskId]'),
- 'Desktop > Task Detail',
- ),
- handle: { meta: taskRouteMeta },
- path: ':taskId',
- },
- ],
- errorElement: <ErrorBoundary resetPath="../tasks" />,
- path: 'task',
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/(task-workspace)/_layout'),
- 'Desktop > Task Workspace > Layout',
- { preloadId: 'tasks' },
- ),
- },
-
- // Pages routes
- {
- children: [
- {
- element: dynamicElement(() => import('@/routes/(main)/page'), 'Desktop > Page', {
- preloadId: 'page',
- }),
- handle: {
- meta: routeMeta({ icon: FilePenIcon, titleKey: 'navigation.pages' }),
- },
- index: true,
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/page/[id]'),
- 'Desktop > Page > Detail',
- ),
- handle: { meta: pageRouteMeta },
- path: ':id',
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/page/_layout'),
- 'Desktop > Page > Layout',
- { preloadId: 'page' },
- ),
- errorElement: <ErrorBoundary />,
- path: 'page',
- },
-];
-
-export const createMainAreaChildren = (): RouteObject[] => [
- ...sharedMainAreaChildren,
-
- // Downloads page (personal-only — never mirrored under /:workspaceSlug)
- {
- element: dynamicElement(() => import('@/routes/(main)/downloads'), 'Desktop > Downloads'),
- errorElement: <ErrorBoundary />,
- handle: { meta: routeMeta({ icon: Download, titleKey: 'navigation.downloads' }) },
- path: 'downloads',
- },
-
- // Settings routes (personal-only — never mirrored under /:workspaceSlug)
- {
- children: [
- {
- element: redirectElement('/settings/profile'),
- index: true,
- },
- // Provider routes with nested structure
- {
- children: [
- {
- element: redirectElement('/settings/provider/all'),
- index: true,
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/settings/provider').then((m) => m.ProviderDetailPage),
- 'Desktop > Settings > Provider > Detail',
- ),
- handle: {
- meta: routeMeta({ icon: Settings, titleKey: 'navigation.provider' }),
- },
- path: ':providerId',
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/settings/provider').then((m) => m.ProviderLayout),
- 'Desktop > Settings > Provider > Layout',
- ),
- handle: {
- meta: routeMeta({ icon: Settings, titleKey: 'navigation.provider' }),
- },
- path: 'provider',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/settings'),
- 'Desktop > Settings > Memory',
- ),
- handle: { settingsTab: SettingsTabs.Memory },
- path: 'memory',
- },
- {
- element: redirectElement('/settings/credential'),
- path: 'creds',
- },
- // Other settings tabs
- {
- element: dynamicElement(
- () => import('@/routes/(main)/settings'),
- 'Desktop > Settings > Tab',
- ),
- handle: { meta: settingsRouteMeta },
- path: ':tab',
- },
- // Tabs that need a sub-segment (e.g. /settings/messenger/discord) reuse
- // the same tab page; nested feature components read `:sub` via useParams.
- {
- element: dynamicElement(
- () => import('@/routes/(main)/settings'),
- 'Desktop > Settings > Tab > Sub',
- ),
- handle: { meta: settingsRouteMeta },
- path: ':tab/:sub',
- },
- ],
- element: dynamicElement(
- () => import('@/routes/(main)/settings/_layout'),
- 'Desktop > Settings > Layout',
- ),
- errorElement: <ErrorBoundary />,
- path: 'settings',
- },
-
- // Workspace slug routes — `/:workspaceSlug/*` mirrors the shared main area.
- // Must come AFTER all reserved root paths so they don't shadow e.g. /agent.
- {
- children: [
- // Workspace home — handled by the persistent `DesktopHomeLayout` at
- // the outer main layout (mirrors how `/` index is empty here). Adding
- // an element would render Home twice on top of `DesktopHomeLayout`.
- {
- handle: { meta: workspaceHomeRouteMeta },
- index: true,
- },
- ...sharedMainAreaChildren,
- // Workspace settings — `/:slug/settings/*`. Dedicated layout with its
- // own sidebar (workspace avatar + 6 tabs + back-to-chat), fully
- // decoupled from personal `/settings/*`.
- {
- children: [
- {
- element: redirectElement('general'),
- index: true,
- },
- // Full-bleed tabs render directly inside the workspace settings
- // shell (sidebar + outlet) — they own their internal layout.
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/provider'),
- 'Desktop > Workspace > Settings > Provider',
- ),
- path: 'provider',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/skill'),
- 'Desktop > Workspace > Settings > Skill',
- { preloadId: 'settings' },
- ),
- path: 'skill',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/connector'),
- 'Desktop > Workspace > Settings > Connector',
- { preloadId: 'settings' },
- ),
- path: 'connector',
- },
- // Padded tabs share a centered, max-width container layout.
- {
- children: [
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/general'),
- 'Desktop > Workspace > Settings > General',
- ),
- path: 'general',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/members'),
- 'Desktop > Workspace > Settings > Members',
- ),
- path: 'members',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/notification'),
- 'Desktop > Workspace > Settings > Notification',
- ),
- path: 'notification',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/statistics'),
- 'Desktop > Workspace > Settings > Statistics',
- ),
- path: 'statistics',
- },
- // Legacy `/:slug/settings/stats` URLs — kept for deep-links.
- {
- element: redirectElement('../statistics'),
- path: 'stats',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/plans'),
- 'Desktop > Workspace > Settings > Plans',
- ),
- path: 'plans',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/billing'),
- 'Desktop > Workspace > Settings > Billing',
- ),
- path: 'billing',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/budget'),
- 'Desktop > Workspace > Settings > Budget',
- ),
- path: 'budget',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/credits'),
- 'Desktop > Workspace > Settings > Credits',
- ),
- path: 'credits',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/usage'),
- 'Desktop > Workspace > Settings > Usage',
- ),
- path: 'usage',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/service-model'),
- 'Desktop > Workspace > Settings > Service Model',
- ),
- path: 'service-model',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/credential'),
- 'Desktop > Workspace > Settings > Credential',
- ),
- path: 'credential',
- },
- // Legacy `/:slug/settings/creds` URLs — kept for deep-links.
- {
- element: redirectElement('../credential'),
- path: 'creds',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/apikey'),
- 'Desktop > Workspace > Settings > API Key',
- ),
- path: 'apikey',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/oauth-apps'),
- 'Desktop > Workspace > Settings > OAuth Apps',
- ),
- path: 'oauth-apps',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/oauth-apps'),
- 'Desktop > Workspace > Settings > OAuth App Detail',
- ),
- path: 'oauth-apps/:sub',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/audit-log'),
- 'Desktop > Workspace > Settings > Audit Log',
- ),
- path: 'audit-log',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/storage'),
- 'Desktop > Workspace > Settings > Storage',
- ),
- path: 'storage',
- },
- {
- element: dynamicElement(
- () => import('@/routes/(main)/[workspaceSlug]/settings/devices'),
- 'Desktop > Workspace > Settings > Devices',
- ),
- path: 'devices',
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/[workspaceSlug]/settings/_content-layout'),
- 'Desktop > Workspace > Settings > Content Layout',
- { preloadId: 'settings' },
- ),
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/[workspaceSlug]/settings/_layout'),
- 'Desktop > Workspace > Settings > Layout',
- { preloadId: 'settings' },
- ),
- errorElement: <ErrorBoundary />,
- path: 'settings',
- },
- // Legacy `/:slug/billing/*` URLs — redirect to the corresponding
- // `/:slug/settings/*` page. Kept for deep-links and bookmarks.
- {
- children: [
- { element: redirectElement('../settings/plans'), path: 'plans' },
- { element: redirectElement('../settings/usage'), path: 'usage' },
- { element: redirectElement('../settings/credits'), path: 'credits' },
- { element: redirectElement('../settings/billing'), path: 'billing' },
- ],
- path: 'billing',
- },
- ],
- element: dynamicLayout(
- () => import('@/routes/(main)/[workspaceSlug]/_layout'),
- 'Desktop > Workspace > Layout',
- ),
- errorElement: <ErrorBoundary />,
- path: ':workspaceSlug',
- },
-
- // Default route - home page (handled by persistent layout)
- {
- handle: {
- meta: routeMeta({
- icon: MessageSquarePlus,
- tabTitleKey: 'navigation.newChat',
- titleKey: 'navigation.home',
- }),
- },
- index: true,
- },
- // Catch-all route
- {
- element: redirectElement('/'),
- path: '*',
- },
-];
-
-// Meta-resolution route tree consumed by the desktop tab bar / recently-viewed
-// panels. Twin-identical to the `.desktop` config so `matchRouteMeta` resolves
-// every tab url's static meta on both the web and electron builds — the
-// electron root router's `/` children are slim stubs with no meta, so the
-// consumers must match against this populated tree, never `desktopRoutes`.
+// Electron consumers resolve tab metadata against the same complete content
+// tree. The Web root also renders this tree directly.
export const mainAreaMetaRoutes: RouteObject[] = [
{ children: createMainAreaChildren(), path: '/' },
];
-// Desktop router configuration (declarative mode)
-export const desktopRoutes: RouteObject[] = [
- {
- children: createMainAreaChildren(),
- element: dynamicLayout(() => import('@/routes/(main)/_layout'), 'Desktop > Main > Layout'),
- errorElement: <ErrorBoundary />,
- path: '/',
- },
- // Onboarding route (outside main layout)
-
- ...BusinessDesktopRoutesWithoutMainLayout,
-
+const webOnlyRoutes: RouteObject[] = [
// Share topic route (outside main layout)
{
children: [
@@ -1158,7 +56,6 @@ export const desktopRoutes: RouteObject[] = [
path: '/share/page',
},
- // Messenger verify route (outside main layout)
{
element: dynamicElement(() => import('@/routes/verify-im'), 'Desktop > VerifyIm'),
errorElement: <ErrorBoundary />,
@@ -1222,8 +119,12 @@ export const desktopRoutes: RouteObject[] = [
},
];
-desktopRoutes.push({
- element: dynamicElement(() => import('@/routes/onboarding'), 'Desktop > Onboarding'),
- errorElement: <ErrorBoundary />,
- path: '/onboarding',
+export const desktopRoutes: RouteObject[] = createSharedDesktopRoutes({
+ mainAreaChildren: createMainAreaChildren(),
+ onboardingRoute: {
+ element: dynamicElement(() => import('@/routes/onboarding'), 'Desktop > Onboarding'),
+ errorElement: <ErrorBoundary />,
+ path: '/onboarding',
+ },
+ platformRoutes: webOnlyRoutes,
});
diff --git a/src/spa/router/desktopRouter.meta.desktop.test.ts b/src/spa/router/desktopRouter.meta.desktop.test.ts
index 05391ada225..c2e1893c02b 100644
--- a/src/spa/router/desktopRouter.meta.desktop.test.ts
+++ b/src/spa/router/desktopRouter.meta.desktop.test.ts
@@ -5,12 +5,12 @@ import { matchRouteMeta } from '@/features/Electron/titlebar/TabBar/resolveRoute
import { mainAreaMetaRoutes } from './desktopRouter.config.desktop';
-// vitest does not apply the platformResolve vite plugin, so the electron twin
+// vitest does not apply the platformResolve Vite plugin, so the Electron adapter
// must be imported by its explicit `.desktop` path. This guards Critical 1: the
// electron root router's `/` children are slim null stubs with zero meta, so a
// meta tree that aliased those stubs would silently degrade every tab title to
// brand and every icon to the Circle fallback on the packaged app.
-describe('mainAreaMetaRoutes (electron twin)', () => {
+describe('mainAreaMetaRoutes (Electron adapter)', () => {
it('uses New Chat for the personal Home tab without changing its document title', () => {
const { static: staticMeta } = matchRouteMeta(mainAreaMetaRoutes, '/');
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
new file mode 100644
index 00000000000..72c1ff82de8
--- /dev/null
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -0,0 +1,1147 @@
+'use client';
+
+import {
+ BrainCircuit,
+ Download,
+ FilePenIcon,
+ Image,
+ LibraryBigIcon,
+ MessageSquarePlus,
+ Settings,
+ ShapesIcon,
+} from 'lucide-react';
+import type { ReactElement } from 'react';
+import type { RouteObject } from 'react-router';
+
+import {
+ BusinessDesktopRoutesWithMainLayout,
+ BusinessDesktopRoutesWithoutMainLayout,
+ BusinessResourceRoutes,
+} from '@/business/client/BusinessDesktopRoutes';
+import { agentDocumentRouteMeta } from '@/features/AgentDocumentPage/routeMeta';
+import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';
+import { agentsRouteMeta } from '@/features/AgentViewAll/routeMeta';
+import { pageRouteMeta } from '@/features/Pages/routeMeta';
+import { workspaceHomeRouteMeta } from '@/features/Workspace/routeMeta';
+import {
+ agentChannelRouteMeta,
+ agentPermissionRouteMeta,
+ agentProfileRouteMeta,
+ agentRouteMeta,
+ agentStatisticsRouteMeta,
+ topicsRouteMeta,
+} from '@/routes/(main)/agent/features/routeMeta';
+import { groupProfileRouteMeta, groupRouteMeta } from '@/routes/(main)/group/features/routeMeta';
+import { settingsRouteMeta } from '@/routes/(main)/settings/features/routeMeta';
+import { loadRouteWithBuiltinToolSurfaces } from '@/spa/initialize/toolSurfaces';
+import { routeMeta } from '@/spa/router/routeMeta';
+import { SettingsTabs } from '@/store/global/initialState';
+import { dynamicElement, dynamicLayout, ErrorBoundary, redirectElement } from '@/utils/router';
+
+const agentChatElement = dynamicElement(
+ () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/(main)/agent')),
+ 'Desktop > Chat',
+ { preloadId: 'agent' },
+);
+
+const groupChatElement = dynamicElement(
+ () => loadRouteWithBuiltinToolSurfaces(() => import('@/routes/(main)/group')),
+ 'Desktop > Agent Group',
+ { preloadId: 'group' },
+);
+
+export interface MainAreaRouteOptions {
+ /** Electron renders Home inside each tab router; Web renders it beside the router outlet. */
+ createHomeElement?: () => ReactElement;
+ /** Electron keeps the workspace settings redirect behind its own lazy route module. */
+ createWorkspaceSettingsIndexElement?: () => ReactElement;
+}
+
+/**
+ * Children shared between the root tree (`/`) and the workspace tree
+ * (`/:workspaceSlug`). Personal-only segments (settings, index, catch-all,
+ * the workspace-slug block itself) are NOT included.
+ *
+ * Index redirects inside this list use **relative paths** so they resolve
+ * correctly under both `/` (→ `/`) and `/:workspaceSlug` (→ `/:workspaceSlug`).
+ */
+export const sharedMainAreaChildren: RouteObject[] = [
+ // Chat routes (agent)
+ {
+ children: [
+ {
+ element: redirectElement('..'),
+ index: true,
+ },
+ {
+ children: [
+ {
+ children: [
+ {
+ element: agentChatElement,
+ handle: { meta: agentRouteMeta },
+ index: true,
+ },
+ {
+ element: agentChatElement,
+ handle: { meta: agentRouteMeta },
+ path: ':topicId',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/agent/(chat)/_layout'),
+ 'Desktop > Chat > ChatLayout',
+ { preloadId: 'agent' },
+ ),
+ },
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/docs'),
+ 'Desktop > Chat > DocumentsIndex',
+ ),
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/docs/[docId]'),
+ 'Desktop > Chat > Document',
+ ),
+ handle: { meta: agentDocumentRouteMeta },
+ path: ':docId',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/agent/docs/_layout'),
+ 'Desktop > Chat > DocumentLayout',
+ ),
+ path: 'docs',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/profile'),
+ 'Desktop > Chat > Profile',
+ ),
+ handle: { meta: agentProfileRouteMeta },
+ path: 'profile',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/channel'),
+ 'Desktop > Chat > Channel',
+ ),
+ handle: { meta: agentChannelRouteMeta },
+ path: 'channel',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/channel/[platform]'),
+ 'Desktop > Chat > Channel Platform',
+ ),
+ handle: { meta: agentChannelRouteMeta },
+ path: 'channel/:platform',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/topics'),
+ 'Desktop > Chat > Topics',
+ ),
+ handle: { meta: topicsRouteMeta },
+ path: 'topics',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/statistics'),
+ 'Desktop > Chat > Statistics',
+ ),
+ handle: { meta: agentStatisticsRouteMeta },
+ path: 'statistics',
+ },
+ // Legacy `/agent/:aid/stats` URLs — kept for deep-links.
+ {
+ element: redirectElement('../statistics'),
+ path: 'stats',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/permission'),
+ 'Desktop > Chat > Permission',
+ ),
+ handle: { meta: agentPermissionRouteMeta },
+ path: 'permission',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/tasks'),
+ 'Desktop > Chat > Tasks',
+ ),
+ handle: { meta: tasksRouteMeta },
+ path: 'tasks',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/task/[taskId]'),
+ 'Desktop > Chat > Task Detail',
+ ),
+ handle: { meta: taskRouteMeta },
+ path: 'task/:taskId',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/agent/_layout'),
+ 'Desktop > Chat > Layout',
+ { preloadId: 'agent' },
+ ),
+ errorElement: <ErrorBoundary />,
+ path: ':aid',
+ },
+ ],
+ path: 'agent',
+ },
+
+ // Group chat routes
+ {
+ children: [
+ {
+ element: redirectElement('..'),
+ index: true,
+ },
+ {
+ children: [
+ {
+ element: groupChatElement,
+ handle: { meta: groupRouteMeta },
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/group/profile'),
+ 'Desktop > Agent Group > Profile',
+ ),
+ handle: { meta: groupProfileRouteMeta },
+ path: 'profile',
+ },
+ {
+ element: groupChatElement,
+ handle: { meta: groupRouteMeta },
+ path: ':topicId',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/group/_layout'),
+ 'Desktop > Group > Layout',
+ { preloadId: 'group' },
+ ),
+ errorElement: <ErrorBoundary />,
+ path: ':gid',
+ },
+ ],
+ path: 'group',
+ },
+
+ // Discover routes with nested structure
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/workspace/settings'),
+ 'Desktop > Discover > Workspace > Settings',
+ ),
+ path: 'workspace/settings',
+ },
+ // List routes (with ListLayout)
+ {
+ children: [
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/agent'),
+ 'Desktop > Discover > List > Agent',
+ ),
+ handle: {
+ meta: routeMeta({
+ icon: ShapesIcon,
+ titleKey: 'navigation.discoverAssistants',
+ }),
+ },
+ index: true,
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/agent/_layout'),
+ 'Desktop > Discover > List > Agent > Layout',
+ ),
+ path: 'agent',
+ },
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/model'),
+ 'Desktop > Discover > List > Model',
+ ),
+ handle: {
+ meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverModels' }),
+ },
+ index: true,
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/model/_layout'),
+ 'Desktop > Discover > List > Model > Layout',
+ ),
+ path: 'model',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/provider'),
+ 'Desktop > Discover > List > Provider',
+ ),
+ handle: {
+ meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverProviders' }),
+ },
+ path: 'provider',
+ },
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/skill'),
+ 'Desktop > Discover > List > Skill',
+ ),
+ handle: {
+ meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discover' }),
+ },
+ index: true,
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/skill/_layout'),
+ 'Desktop > Discover > List > Skill > Layout',
+ ),
+ path: 'skill',
+ },
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/mcp'),
+ 'Desktop > Discover > List > MCP',
+ ),
+ handle: {
+ meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discoverMcp' }),
+ },
+ index: true,
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/mcp/_layout'),
+ 'Desktop > Discover > List > MCP > Layout',
+ ),
+ path: 'mcp',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/workspace'),
+ 'Desktop > Discover > List > Workspace',
+ ),
+ path: 'workspace',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/(home)'),
+ 'Desktop > Discover > List > Home',
+ { preloadId: 'community' },
+ ),
+ handle: {
+ meta: routeMeta({ icon: ShapesIcon, titleKey: 'navigation.discover' }),
+ },
+ index: true,
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(list)/_layout'),
+ 'Desktop > Discover > List > Layout',
+ { preloadId: 'community' },
+ ),
+ },
+ // Detail routes (with DetailLayout)
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/agent'),
+ 'Desktop > Discover > Detail > Agent',
+ ),
+ path: 'agent/:slug',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/group_agent'),
+ 'Desktop > Discover > Detail > Group Agent',
+ ),
+ path: 'group_agent/:slug',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/model'),
+ 'Desktop > Discover > Detail > Model',
+ ),
+ path: 'model/:slug',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/provider'),
+ 'Desktop > Discover > Detail > Provider',
+ ),
+ path: 'provider/:slug',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/skill'),
+ 'Desktop > Discover > Detail > Skill',
+ ),
+ path: 'skill/:slug',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/mcp'),
+ 'Desktop > Discover > Detail > MCP',
+ ),
+ path: 'mcp/:slug',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/user'),
+ 'Desktop > Discover > Detail > User',
+ ),
+ path: 'user/:slug',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/organization'),
+ 'Desktop > Discover > Detail > Organization',
+ ),
+ path: 'org/:slug',
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/(detail)/_layout'),
+ 'Desktop > Discover > Detail > Layout',
+ ),
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/community/_layout'),
+ 'Desktop > Discover > Layout',
+ { preloadId: 'community' },
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'community',
+ },
+
+ // Resource routes
+ {
+ children: [
+ // Home routes (resource list)
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/resource/(home)'),
+ 'Desktop > Resource > Home',
+ { preloadId: 'resource' },
+ ),
+ handle: {
+ meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.resources' }),
+ },
+ index: true,
+ },
+ ...BusinessResourceRoutes,
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/resource/(home)/_layout'),
+ 'Desktop > Resource > Home > Layout',
+ { preloadId: 'resource' },
+ ),
+ },
+ // Library routes (knowledge base detail)
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/resource/library'),
+ 'Desktop > Resource > Library',
+ ),
+ handle: {
+ meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),
+ },
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/resource/library/[slug]'),
+ 'Desktop > Resource > Library > Slug',
+ ),
+ handle: {
+ meta: routeMeta({ icon: LibraryBigIcon, titleKey: 'navigation.knowledgeBase' }),
+ },
+ path: ':slug',
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/resource/library/_layout'),
+ 'Desktop > Resource > Library > Layout',
+ ),
+ path: 'library/:id',
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/resource/_layout'),
+ 'Desktop > Resource > Layout',
+ { preloadId: 'resource' },
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'resource',
+ },
+
+ // Memory routes
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/memory/(home)'),
+ 'Desktop > Memory > Home',
+ { preloadId: 'memory' },
+ ),
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),
+ },
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/memory/identities'),
+ 'Desktop > Memory > Identities',
+ ),
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryIdentities' }),
+ },
+ path: 'identities',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/memory/contexts'),
+ 'Desktop > Memory > Contexts',
+ ),
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryContexts' }),
+ },
+ path: 'contexts',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/memory/preferences'),
+ 'Desktop > Memory > Preferences',
+ ),
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryPreferences' }),
+ },
+ path: 'preferences',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/memory/experiences'),
+ 'Desktop > Memory > Experiences',
+ ),
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memoryExperiences' }),
+ },
+ path: 'experiences',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/memory/activities'),
+ 'Desktop > Memory > Activities',
+ ),
+ handle: {
+ meta: routeMeta({ icon: BrainCircuit, titleKey: 'navigation.memory' }),
+ },
+ path: 'activities',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/memory/_layout'),
+ 'Desktop > Memory > Layout',
+ { preloadId: 'memory' },
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'memory',
+ },
+
+ // Video routes
+ {
+ children: [
+ {
+ element: dynamicElement(() => import('@/routes/(main)/(create)/video'), 'Desktop > Video', {
+ preloadId: 'video',
+ }),
+ index: true,
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/(create)/video/_layout'),
+ 'Desktop > Video > Layout',
+ { preloadId: 'video' },
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'video',
+ },
+
+ // Image routes
+ {
+ children: [
+ {
+ element: dynamicElement(() => import('@/routes/(main)/(create)/image'), 'Desktop > Image', {
+ preloadId: 'image',
+ }),
+ handle: {
+ meta: routeMeta({ icon: Image, titleKey: 'navigation.image' }),
+ },
+ index: true,
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/(create)/image/_layout'),
+ 'Desktop > Image > Layout',
+ { preloadId: 'image' },
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'image',
+ },
+
+ ...BusinessDesktopRoutesWithMainLayout,
+
+ // Eval routes
+ {
+ children: [
+ // Home (overview)
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval'),
+ 'Desktop > Eval > Overview',
+ { preloadId: 'eval' },
+ ),
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/experiments/[experimentId]'),
+ 'Desktop > Eval > Experiment Detail',
+ ),
+ path: 'experiments/:experimentId',
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/(home)/_layout'),
+ 'Desktop > Eval > Home > Layout',
+ { preloadId: 'eval' },
+ ),
+ },
+ // Bench routes (with dedicated sidebar)
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/bench/[benchmarkId]'),
+ 'Desktop > Eval > Benchmark Detail',
+ ),
+ index: true,
+ },
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]'),
+ 'Desktop > Eval > Run Detail',
+ ),
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () =>
+ import('@/routes/(main)/eval/bench/[benchmarkId]/runs/[runId]/cases/[caseId]'),
+ 'Desktop > Eval > Case Detail',
+ ),
+ path: 'cases/:caseId',
+ },
+ ],
+ path: 'runs/:runId',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/bench/[benchmarkId]/datasets/[datasetId]'),
+ 'Desktop > Eval > Dataset Detail',
+ ),
+ path: 'datasets/:datasetId',
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/bench/[benchmarkId]/_layout'),
+ 'Desktop > Eval > Bench > Layout',
+ ),
+ path: 'bench/:benchmarkId',
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/eval/_layout'),
+ 'Desktop > Eval > Layout',
+ { preloadId: 'eval' },
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'eval',
+ },
+
+ // Agents view-all route (flat list of workspace/private agents)
+ {
+ children: [
+ {
+ element: dynamicElement(() => import('@/routes/(main)/agents'), 'Desktop > Agents', {
+ preloadId: 'agents',
+ }),
+ handle: { meta: agentsRouteMeta },
+ index: true,
+ },
+ ],
+ errorElement: <ErrorBoundary resetPath=".." />,
+ path: 'agents',
+ },
+
+ // Task workspace routes (cross-agent)
+ {
+ children: [
+ {
+ children: [
+ {
+ element: dynamicElement(() => import('@/routes/(main)/tasks'), 'Desktop > Tasks', {
+ preloadId: 'tasks',
+ }),
+ handle: { meta: tasksRouteMeta },
+ index: true,
+ },
+ ],
+ errorElement: <ErrorBoundary resetPath=".." />,
+ path: 'tasks',
+ },
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/task/[taskId]'),
+ 'Desktop > Task Detail',
+ ),
+ handle: { meta: taskRouteMeta },
+ path: ':taskId',
+ },
+ ],
+ errorElement: <ErrorBoundary resetPath="../tasks" />,
+ path: 'task',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/(task-workspace)/_layout'),
+ 'Desktop > Task Workspace > Layout',
+ { preloadId: 'tasks' },
+ ),
+ },
+
+ // Pages routes
+ {
+ children: [
+ {
+ element: dynamicElement(() => import('@/routes/(main)/page'), 'Desktop > Page', {
+ preloadId: 'page',
+ }),
+ handle: {
+ meta: routeMeta({ icon: FilePenIcon, titleKey: 'navigation.pages' }),
+ },
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/page/[id]'),
+ 'Desktop > Page > Detail',
+ ),
+ handle: { meta: pageRouteMeta },
+ path: ':id',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/page/_layout'),
+ 'Desktop > Page > Layout',
+ { preloadId: 'page' },
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'page',
+ },
+];
+
+const createMainAreaChildrenDefinition = (options: MainAreaRouteOptions = {}): RouteObject[] => [
+ ...sharedMainAreaChildren,
+
+ // Downloads page (personal-only — never mirrored under /:workspaceSlug)
+ {
+ element: dynamicElement(() => import('@/routes/(main)/downloads'), 'Desktop > Downloads'),
+ errorElement: <ErrorBoundary />,
+ handle: { meta: routeMeta({ icon: Download, titleKey: 'navigation.downloads' }) },
+ path: 'downloads',
+ },
+
+ // Settings routes (personal-only — never mirrored under /:workspaceSlug)
+ {
+ children: [
+ {
+ element: redirectElement('/settings/profile'),
+ index: true,
+ },
+ // Provider routes with nested structure
+ {
+ children: [
+ {
+ element: redirectElement('/settings/provider/all'),
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/settings/provider').then((m) => m.ProviderDetailPage),
+ 'Desktop > Settings > Provider > Detail',
+ ),
+ handle: {
+ meta: routeMeta({ icon: Settings, titleKey: 'navigation.provider' }),
+ },
+ path: ':providerId',
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/settings/provider').then((m) => m.ProviderLayout),
+ 'Desktop > Settings > Provider > Layout',
+ ),
+ handle: {
+ meta: routeMeta({ icon: Settings, titleKey: 'navigation.provider' }),
+ },
+ path: 'provider',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/settings'),
+ 'Desktop > Settings > Memory',
+ ),
+ handle: { settingsTab: SettingsTabs.Memory },
+ path: 'memory',
+ },
+ {
+ element: redirectElement('/settings/credential'),
+ path: 'creds',
+ },
+ // Other settings tabs
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/settings'),
+ 'Desktop > Settings > Tab',
+ ),
+ handle: { meta: settingsRouteMeta },
+ path: ':tab',
+ },
+ // Tabs that need a sub-segment (e.g. /settings/messenger/discord) reuse
+ // the same tab page; nested feature components read `:sub` via useParams.
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/settings'),
+ 'Desktop > Settings > Tab > Sub',
+ ),
+ handle: { meta: settingsRouteMeta },
+ path: ':tab/:sub',
+ },
+ ],
+ element: dynamicElement(
+ () => import('@/routes/(main)/settings/_layout'),
+ 'Desktop > Settings > Layout',
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'settings',
+ },
+
+ // Workspace slug routes — `/:workspaceSlug/*` mirrors the shared main area.
+ // Must come AFTER all reserved root paths so they don't shadow e.g. /agent.
+ {
+ children: [
+ // Web renders Home beside the router outlet; Electron injects a per-tab
+ // Home element because each tab owns an independent memory router.
+ {
+ element: options.createHomeElement?.(),
+ handle: { meta: workspaceHomeRouteMeta },
+ index: true,
+ },
+ ...sharedMainAreaChildren,
+ // Workspace settings — `/:slug/settings/*`. Dedicated layout with its
+ // own sidebar (workspace avatar + 6 tabs + back-to-chat), fully
+ // decoupled from personal `/settings/*`.
+ {
+ children: [
+ {
+ element: options.createWorkspaceSettingsIndexElement?.() ?? redirectElement('general'),
+ index: true,
+ },
+ // Full-bleed tabs render directly inside the workspace settings
+ // shell (sidebar + outlet) — they own their internal layout.
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/provider'),
+ 'Desktop > Workspace > Settings > Provider',
+ ),
+ path: 'provider',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/skill'),
+ 'Desktop > Workspace > Settings > Skill',
+ { preloadId: 'settings' },
+ ),
+ path: 'skill',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/connector'),
+ 'Desktop > Workspace > Settings > Connector',
+ { preloadId: 'settings' },
+ ),
+ path: 'connector',
+ },
+ // Padded tabs share a centered, max-width container layout.
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/general'),
+ 'Desktop > Workspace > Settings > General',
+ ),
+ path: 'general',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/members'),
+ 'Desktop > Workspace > Settings > Members',
+ ),
+ path: 'members',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/notification'),
+ 'Desktop > Workspace > Settings > Notification',
+ ),
+ path: 'notification',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/statistics'),
+ 'Desktop > Workspace > Settings > Statistics',
+ ),
+ path: 'statistics',
+ },
+ // Legacy `/:slug/settings/stats` URLs — kept for deep-links.
+ {
+ element: redirectElement('../statistics'),
+ path: 'stats',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/plans'),
+ 'Desktop > Workspace > Settings > Plans',
+ ),
+ path: 'plans',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/billing'),
+ 'Desktop > Workspace > Settings > Billing',
+ ),
+ path: 'billing',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/budget'),
+ 'Desktop > Workspace > Settings > Budget',
+ ),
+ path: 'budget',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/credits'),
+ 'Desktop > Workspace > Settings > Credits',
+ ),
+ path: 'credits',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/usage'),
+ 'Desktop > Workspace > Settings > Usage',
+ ),
+ path: 'usage',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/service-model'),
+ 'Desktop > Workspace > Settings > Service Model',
+ ),
+ path: 'service-model',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/credential'),
+ 'Desktop > Workspace > Settings > Credential',
+ ),
+ path: 'credential',
+ },
+ // Legacy `/:slug/settings/creds` URLs — kept for deep-links.
+ {
+ element: redirectElement('../credential'),
+ path: 'creds',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/apikey'),
+ 'Desktop > Workspace > Settings > API Key',
+ ),
+ path: 'apikey',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/oauth-apps'),
+ 'Desktop > Workspace > Settings > OAuth Apps',
+ ),
+ path: 'oauth-apps',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/oauth-apps'),
+ 'Desktop > Workspace > Settings > OAuth App Detail',
+ ),
+ path: 'oauth-apps/:sub',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/audit-log'),
+ 'Desktop > Workspace > Settings > Audit Log',
+ ),
+ path: 'audit-log',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/storage'),
+ 'Desktop > Workspace > Settings > Storage',
+ ),
+ path: 'storage',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/devices'),
+ 'Desktop > Workspace > Settings > Devices',
+ ),
+ path: 'devices',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/_content-layout'),
+ 'Desktop > Workspace > Settings > Content Layout',
+ { preloadId: 'settings' },
+ ),
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/_layout'),
+ 'Desktop > Workspace > Settings > Layout',
+ { preloadId: 'settings' },
+ ),
+ errorElement: <ErrorBoundary />,
+ path: 'settings',
+ },
+ // Legacy `/:slug/billing/*` URLs — redirect to the corresponding
+ // `/:slug/settings/*` page. Kept for deep-links and bookmarks.
+ {
+ children: [
+ { element: redirectElement('../settings/plans'), path: 'plans' },
+ { element: redirectElement('../settings/usage'), path: 'usage' },
+ { element: redirectElement('../settings/credits'), path: 'credits' },
+ { element: redirectElement('../settings/billing'), path: 'billing' },
+ ],
+ path: 'billing',
+ },
+ ],
+ element: dynamicLayout(
+ () => import('@/routes/(main)/[workspaceSlug]/_layout'),
+ 'Desktop > Workspace > Layout',
+ ),
+ errorElement: <ErrorBoundary />,
+ path: ':workspaceSlug',
+ },
+
+ // Web leaves this element empty; Electron injects the per-tab Home route.
+ {
+ element: options.createHomeElement?.(),
+ handle: {
+ meta: routeMeta({
+ icon: MessageSquarePlus,
+ tabTitleKey: 'navigation.newChat',
+ titleKey: 'navigation.home',
+ }),
+ },
+ index: true,
+ },
+ // Catch-all route
+ {
+ element: redirectElement('/'),
+ path: '*',
+ },
+];
+
+/**
+ * Creates one stable lazy-element tree per runtime while returning a fresh
+ * top-level array for every React Router instance. This prevents per-tab
+ * router creation from registering duplicate preload loaders.
+ */
+export const createMainAreaRouteFactory = (options: MainAreaRouteOptions = {}) => {
+ const routes = createMainAreaChildrenDefinition(options);
+
+ return (): RouteObject[] => [...routes];
+};
+
+export interface SharedDesktopRouteOptions {
+ mainAreaChildren: RouteObject[];
+ onboardingRoute: RouteObject;
+ /** Routes that intentionally exist on only one runtime, such as Web `/verify-im`. */
+ platformRoutes?: RouteObject[];
+}
+
+/**
+ * Builds the common Web/Electron top-level route tree. Platform entry files
+ * supply only the root children, runtime-only routes, and onboarding route.
+ */
+export const createSharedDesktopRoutes = ({
+ mainAreaChildren,
+ onboardingRoute,
+ platformRoutes = [],
+}: SharedDesktopRouteOptions): RouteObject[] => [
+ {
+ children: mainAreaChildren,
+ element: dynamicLayout(() => import('@/routes/(main)/_layout'), 'Desktop > Main > Layout'),
+ errorElement: <ErrorBoundary />,
+ path: '/',
+ },
+ ...BusinessDesktopRoutesWithoutMainLayout,
+ ...platformRoutes,
+ onboardingRoute,
+];
diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsx
index 6cf7cbbcc8d..f972bf029f7 100644
--- a/src/spa/router/desktopRouter.sync.test.tsx
+++ b/src/spa/router/desktopRouter.sync.test.tsx
@@ -7,294 +7,229 @@ import { describe, expect, it } from 'vitest';
import { WORKSPACE_SETTINGS_TABS } from '@/features/Workspace/workspaceAwarePath';
-import { createMainAreaChildren, desktopRoutes } from './desktopRouter.config';
-
-/**
- * Known path pairs that intentionally differ between web and desktop (Electron).
- * Map: desktop path → web path
- */
-const KNOWN_DIVERGENCES: Record<string, string> = {
- '/desktop-onboarding': '/onboarding',
+import {
+ createMainAreaChildren as createWebMainAreaChildren,
+ desktopRoutes as webDesktopRoutes,
+} from './desktopRouter.config';
+import {
+ createMainAreaChildren as createElectronMainAreaChildren,
+ desktopRoutes as electronDesktopRoutes,
+} from './desktopRouter.config.desktop';
+
+type MainAreaFactory = () => RouteObject[];
+
+const mainAreaVariants: Array<[string, MainAreaFactory]> = [
+ ['Web', createWebMainAreaChildren],
+ ['Electron', createElectronMainAreaChildren],
+];
+
+const createMainAreaRoutes = (factory: MainAreaFactory): RouteObject[] => [
+ { children: factory(), path: '/' },
+];
+
+const findWorkspaceSettingsRoute = (factory: MainAreaFactory) => {
+ const workspaceRoute = factory().find((route) => route.path === ':workspaceSlug');
+ return workspaceRoute?.children?.find((route) => route.path === 'settings');
};
-/**
- * Web-only routes intentionally absent from Electron (no in-app entry points there).
- * Paths are flat `path: '...'` literals extracted from both configs.
- */
-const WEB_ONLY_PATHS = new Set([
- '/onboarding',
- // Messenger link flow — web/CLI only (the verify workspace + acceptance
- // pages ship on Electron too, so they are synced, not listed here)
- '/verify-im',
-]);
-
-/** Extra `index: true` routes present only on web. */
-const WEB_ONLY_INDEX_DELTA = 0;
-
-/**
- * The Electron `/` route hosts only the TabHost shell; its children are two
- * slim stubs (`{ index }` + `{ path: '*' }`). The stub index route has no web
- * counterpart (web's `/` renders `createMainAreaChildren()` directly), so the
- * desktop config carries exactly one extra `index: true`.
- */
-const DESKTOP_ROOT_STUB_INDEX_ROUTES = 1;
-
-/** handle.meta blobs present only on web. */
-const WEB_ONLY_HANDLE_METAS = new Set<string>([]);
-
-function extractIndexCount(source: string) {
- return [...source.matchAll(/index:\s*true/g)].length;
+const collectPaths = (routes: RouteObject[]): string[] =>
+ routes.flatMap((route) =>
+ route.path
+ ? [route.path, ...collectPaths(route.children ?? [])]
+ : collectPaths(route.children ?? []),
+ );
+
+const routeShape = (routes: RouteObject[]): unknown =>
+ routes.map((route) => ({
+ children: route.children ? routeShape(route.children) : undefined,
+ index: route.index === true || undefined,
+ path: route.path,
+ }));
+
+async function readRouterSources() {
+ return Promise.all(
+ [
+ 'desktopRouter.shared.tsx',
+ 'desktopRouter.config.tsx',
+ 'desktopRouter.config.desktop.tsx',
+ ].map((filename) => readFile(path.join(process.cwd(), 'src/spa/router', filename), 'utf8')),
+ );
}
-function extractHandleMetas(source: string) {
- const metas: string[] = [];
- const marker = 'handle:';
-
- let cursor = source.indexOf(marker);
- while (cursor !== -1) {
- const braceStart = source.indexOf('{', cursor + marker.length);
- let depth = 0;
- let end = braceStart;
- for (; end < source.length; end += 1) {
- const char = source[end];
- if (char === '{') depth += 1;
- else if (char === '}') {
- depth -= 1;
- if (depth === 0) break;
- }
- }
-
- metas.push(source.slice(braceStart, end + 1).replaceAll(/\s+/g, ' '));
- cursor = source.indexOf(marker, end + 1);
- }
-
- return metas.sort();
-}
-
-function extractPaths(source: string) {
- return [...source.matchAll(/path:\s*'([^']+)'/g)].map((match) => match[1]);
-}
-
-function normalizePaths(paths: string[]) {
- return [...new Set(paths.map((path) => KNOWN_DIVERGENCES[path] ?? path))]
- .filter((path) => !WEB_ONLY_PATHS.has(path))
- .sort();
-}
-
-async function readDesktopRouterSources() {
- return Promise.all([
- readFile(path.join(process.cwd(), 'src/spa/router/desktopRouter.config.tsx'), 'utf8'),
- readFile(path.join(process.cwd(), 'src/spa/router/desktopRouter.config.desktop.tsx'), 'utf8'),
- ]);
-}
-
-describe('desktopRouter config sync', () => {
- it('matches the nested acceptance check route', () => {
- const matches = matchRoutes(desktopRoutes, '/acceptance/acceptance-1/check/check-1');
+describe('desktop router shared definition', () => {
+ it('matches the nested acceptance check route on Web only', () => {
+ const matches = matchRoutes(webDesktopRoutes, '/acceptance/acceptance-1/check/check-1');
expect(matches?.at(-1)?.route.path).toBe(':acceptanceId/check/:checkId');
expect(matches?.at(-1)?.params).toMatchObject({
acceptanceId: 'acceptance-1',
checkId: 'check-1',
});
+ expect(electronDesktopRoutes.some((route) => route.path === '/acceptance')).toBe(false);
});
- // Regression for agent sub-page tab titles show section and agent name (not bare "LobeHub"): these pages rendered a bare "LobeHub" tab title
- // because no route in the matched chain declared a handle.meta.
- it.each([
- '/agent/agent-1/profile',
- '/agent/agent-1/channel',
- '/agent/agent-1/channel/slack',
- '/agent/agent-1/statistics',
- '/group/group-1/profile',
- ])('%s declares route meta so the tab title is not bare branding', (pathname) => {
- const matches = matchRoutes(desktopRoutes, pathname);
-
- expect(matches, `${pathname} must match a route`).toBeTruthy();
-
- const meta = matches!
- .map((match) => (match.route.handle as { meta?: unknown } | undefined)?.meta)
- .findLast(Boolean);
- expect(meta, `${pathname} must declare handle.meta`).toBeDefined();
- });
+ it.each(mainAreaVariants)(
+ '%s agent sub-pages declare route meta so tab titles are not bare branding',
+ (_, createMainAreaChildren) => {
+ for (const pathname of [
+ '/agent/agent-1/profile',
+ '/agent/agent-1/channel',
+ '/agent/agent-1/channel/slack',
+ '/agent/agent-1/statistics',
+ '/group/group-1/profile',
+ ]) {
+ const matches = matchRoutes(createMainAreaRoutes(createMainAreaChildren), pathname);
+ const meta = matches
+ ?.map((match) => (match.route.handle as { meta?: unknown } | undefined)?.meta)
+ .findLast(Boolean);
+
+ expect(matches, `${pathname} must match a route`).toBeTruthy();
+ expect(meta, `${pathname} must declare handle.meta`).toBeDefined();
+ }
+ },
+ );
- // `/agent/:aid/stats` was renamed to `statistics`; bookmarks, shared links and
- // restored Electron tabs still carry the old segment and must not 404.
- it('keeps the legacy agent stats path matching so deep-links still resolve', () => {
- const matches = matchRoutes(desktopRoutes, '/agent/agent-1/stats');
+ it.each(mainAreaVariants)('%s keeps legacy agent stats deep-links matching', (_, factory) => {
+ const matches = matchRoutes(createMainAreaRoutes(factory), '/agent/agent-1/stats');
expect(matches?.at(-1)?.route.path).toBe('stats');
});
- it('personal memory settings route is not shadowed by workspace memory route', () => {
- const matches = matchRoutes(desktopRoutes, '/settings/memory');
- const paths = matches?.map((match) => match.route.path);
-
- expect(paths).toContain('settings');
- expect(paths).not.toContain(':workspaceSlug');
- expect(paths?.at(-1)).toBe('memory');
- expect(matches?.at(-1)?.route.handle).toMatchObject({ settingsTab: 'memory' });
- });
-
- it('desktop (sync) route paths must match web (async) route paths', async () => {
- const [asyncSource, syncSource] = await readDesktopRouterSources();
-
- const asyncPaths = normalizePaths(extractPaths(asyncSource));
- const syncPaths = normalizePaths(extractPaths(syncSource));
-
- const missingInSync = asyncPaths.filter((p) => !syncPaths.includes(p));
- const extraInSync = syncPaths.filter((p) => !asyncPaths.includes(p));
- const asyncIndexCount = extractIndexCount(asyncSource);
- const syncIndexCount = extractIndexCount(syncSource);
-
- expect(missingInSync, `Missing in desktop config: ${missingInSync.join(', ')}`).toEqual([]);
- expect(extraInSync, `Extra in desktop config: ${extraInSync.join(', ')}`).toEqual([]);
- expect(syncIndexCount, 'Desktop config index route count must match async config').toBe(
- asyncIndexCount - WEB_ONLY_INDEX_DELTA + DESKTOP_ROOT_STUB_INDEX_ROUTES,
- );
- });
-
- it('route handle.meta declarations must match between web and desktop configs', async () => {
- const [asyncSource, syncSource] = await readDesktopRouterSources();
-
- const asyncMetas = extractHandleMetas(asyncSource).filter(
- (meta) => !WEB_ONLY_HANDLE_METAS.has(meta),
- );
- const syncMetas = extractHandleMetas(syncSource);
-
- expect(asyncMetas.length, 'Async config must declare at least one handle.meta').toBeGreaterThan(
- 0,
- );
- expect(syncMetas, 'Desktop config handle.meta declarations must match async config').toEqual(
- asyncMetas,
+ it.each(mainAreaVariants)(
+ '%s personal memory settings are not shadowed by workspace memory routes',
+ (_, factory) => {
+ const matches = matchRoutes(createMainAreaRoutes(factory), '/settings/memory');
+ const paths = matches?.map((match) => match.route.path);
+
+ expect(paths).toContain('settings');
+ expect(paths).not.toContain(':workspaceSlug');
+ expect(paths?.at(-1)).toBe('memory');
+ expect(matches?.at(-1)?.route.handle).toMatchObject({ settingsTab: 'memory' });
+ },
+ );
+
+ it('generates identical main-area path and nesting behavior for Web and Electron', () => {
+ expect(routeShape(createElectronMainAreaChildren())).toEqual(
+ routeShape(createWebMainAreaChildren()),
);
});
- it('electron `/` route children are the slim TabHost stubs', async () => {
- const [, syncSource] = await readDesktopRouterSources();
- const collapsed = syncSource.replaceAll(/\s+/g, ' ');
-
- expect(collapsed).toMatch(
- /children:\s*\[\s*\{\s*element:\s*null,\s*index:\s*true\s*\},\s*\{\s*element:\s*null,\s*path:\s*'\*'\s*\},?\s*\]/,
- );
- });
-
- it('index-element divergence: electron index routes render home, web index routes are element-less', async () => {
- const [asyncSource, syncSource] = await readDesktopRouterSources();
- const collapsedSync = syncSource.replaceAll(/\s+/g, ' ');
-
- // Electron builder mounts the home element on the root + workspace index routes.
- const homeElementMatches = [
- ...collapsedSync.matchAll(/<DesktopHomeLayout>\s*<DesktopHome \/>\s*<\/DesktopHomeLayout>/g),
+ it('keeps all route modules behind lazy import boundaries', async () => {
+ const sources = await readRouterSources();
+ const combinedSource = sources.join('\n');
+ const eagerDefaultRouteImports = [
+ ...combinedSource.matchAll(/^import\s+[A-Z]\w*\s+from\s+'@\/routes\//gm),
+ ];
+ const lazyRouteImports = [
+ ...combinedSource.matchAll(
+ /(?:dynamicElement|dynamicLayout)\(\s*\(\) => (?:loadRouteWithBuiltinToolSurfaces\(\(\) => )?import\(['"]@\/routes\//g,
+ ),
];
- expect(homeElementMatches).toHaveLength(2);
-
- // Web builder never renders home via the router (it uses the always-mounted
- // sibling). Comments may mention the component name, so match the JSX element.
- expect(asyncSource).not.toContain('<DesktopHome');
-
- // Structural check: the web `createMainAreaChildren()` index routes carry no element.
- const webChildren = createMainAreaChildren();
- const webRootIndex = webChildren.find((route) => route.index);
- expect(webRootIndex?.element).toBeUndefined();
- const webWorkspace = webChildren.find((route) => route.path === ':workspaceSlug');
- const webWorkspaceIndex = webWorkspace?.children?.find((route) => route.index);
- expect(webWorkspaceIndex?.element).toBeUndefined();
+ expect(eagerDefaultRouteImports).toHaveLength(0);
+ expect(combinedSource).not.toContain(
+ "import { ProviderDetailPage, ProviderLayout } from '@/routes/(main)/settings/provider'",
+ );
+ expect(lazyRouteImports.length).toBeGreaterThan(100);
});
- it('workspace settings tree is registered with all tabs in both configs', async () => {
- const [asyncSource, syncSource] = await readDesktopRouterSources();
-
- const requiredImportTargets = [
- '@/routes/(main)/[workspaceSlug]/settings/_layout',
- '@/routes/(main)/[workspaceSlug]/settings/general',
- '@/routes/(main)/[workspaceSlug]/settings/members',
- '@/routes/(main)/[workspaceSlug]/settings/plans',
- '@/routes/(main)/[workspaceSlug]/settings/billing',
- '@/routes/(main)/[workspaceSlug]/settings/credits',
- '@/routes/(main)/[workspaceSlug]/settings/usage',
- '@/routes/(main)/[workspaceSlug]/settings/skill',
- '@/routes/(main)/[workspaceSlug]/settings/connector',
- '@/routes/(main)/[workspaceSlug]/settings/oauth-apps',
- '@/routes/(main)/[workspaceSlug]/settings/audit-log',
- ];
+ it('owns prioritized preload registration only in the shared route definition', async () => {
+ const [sharedSource, webSource, electronSource] = await readRouterSources();
- for (const target of requiredImportTargets) {
- expect(asyncSource, `async config missing ${target}`).toContain(`import('${target}')`);
- expect(syncSource, `sync config missing ${target}`).toContain(`from '${target}'`);
- }
-
- // Old billing route directory is gone in both configs
- expect(asyncSource).not.toContain('@/routes/(main)/[workspaceSlug]/billing/_layout');
- expect(asyncSource).not.toContain('@/routes/(main)/[workspaceSlug]/billing/plans');
- expect(syncSource).not.toContain('@/routes/(main)/[workspaceSlug]/billing/_layout');
- expect(syncSource).not.toContain('@/routes/(main)/[workspaceSlug]/billing/plans');
-
- // Legacy /:slug/billing/* redirects still exist (string match — the
- // `path: 'billing'` block under `:workspaceSlug` is preserved as redirects)
- expect(asyncSource).toContain("redirectElement('../settings/plans')");
- expect(syncSource).toContain("redirectElement('../settings/plans')");
+ expect([...sharedSource.matchAll(/preloadId:\s*'[^']+'/g)].length).toBeGreaterThan(0);
+ expect(webSource).not.toContain('preloadId:');
+ expect(electronSource).not.toContain('preloadId:');
});
- it('keeps workspace-aware settings tabs aligned with registered workspace routes', () => {
- const rootRoute = desktopRoutes.find((route) => route.path === '/');
- const workspaceRoute = rootRoute?.children?.find((route) => route.path === ':workspaceSlug');
- const settingsRoute = workspaceRoute?.children?.find((route) => route.path === 'settings');
-
- expect(settingsRoute, 'Workspace settings route must exist').toBeDefined();
-
- const collectPaths = (routes: RouteObject[]): string[] =>
- routes.flatMap((route) =>
- route.path
- ? [route.path, ...collectPaths(route.children ?? [])]
- : collectPaths(route.children ?? []),
- );
- const registeredTabs = [
- ...new Set(
- collectPaths(settingsRoute?.children ?? []).map(
- (registeredPath) => registeredPath.split('/')[0],
- ),
- ),
- ].sort();
- const workspaceAwareTabs = [...WORKSPACE_SETTINGS_TABS].sort();
+ it('does not opt Electron out of the post-render route preload scheduler', async () => {
+ const source = await readFile(
+ path.join(process.cwd(), 'src/spa/initialize/routePreload.ts'),
+ 'utf8',
+ );
- expect(
- workspaceAwareTabs,
- 'WORKSPACE_SETTINGS_TABS must exactly match the registered workspace settings routes',
- ).toEqual(registeredTabs);
+ expect(source).not.toContain("typeof window === 'undefined' || __ELECTRON__");
});
- it('workspace OAuth apps list and detail routes are registered', () => {
- const listMatches = matchRoutes(desktopRoutes, '/acme/settings/oauth-apps');
- const detailMatches = matchRoutes(desktopRoutes, '/acme/settings/oauth-apps/client-1');
-
- expect(listMatches?.at(-1)?.route.path).toBe('oauth-apps');
- expect(detailMatches?.at(-1)?.route.path).toBe('oauth-apps/:sub');
- expect(detailMatches?.at(-1)?.params).toMatchObject({ sub: 'client-1', workspaceSlug: 'acme' });
+ it('keeps platform differences limited to root composition and runtime-only routes', () => {
+ const webRoot = webDesktopRoutes.find((route) => route.path === '/');
+ const electronRoot = electronDesktopRoutes.find((route) => route.path === '/');
+ const webPaths = webDesktopRoutes.map((route) => route.path);
+ const electronPaths = electronDesktopRoutes.map((route) => route.path);
+
+ expect(webRoot?.children).toHaveLength(createWebMainAreaChildren().length);
+ expect(electronRoot?.children).toMatchObject([
+ { element: null, index: true },
+ { element: null, path: '*' },
+ ]);
+ expect(webPaths).toContain('/verify-im');
+ expect(webPaths).toContain('/share/t');
+ expect(webPaths).toContain('/share/page');
+ expect(webPaths).toContain('/verify');
+ expect(webPaths).toContain('/acceptance');
+ expect(webPaths).toContain('/onboarding');
+ expect(webPaths).not.toContain('/desktop-onboarding');
+ expect(electronPaths).not.toContain('/verify-im');
+ expect(electronPaths).not.toContain('/share/t');
+ expect(electronPaths).not.toContain('/share/page');
+ expect(electronPaths).not.toContain('/verify');
+ expect(electronPaths).not.toContain('/acceptance');
+ expect(electronPaths).not.toContain('/onboarding');
+ expect(electronPaths).toContain('/desktop-onboarding');
});
- it('both configs import and spread BusinessResourceRoutes into /resource children', async () => {
- const [asyncSource, syncSource] = await readDesktopRouterSources();
+ it('injects Home only into Electron per-tab content routes', () => {
+ const webChildren = createWebMainAreaChildren();
+ const electronChildren = createElectronMainAreaChildren();
+ const webWorkspace = webChildren.find((route) => route.path === ':workspaceSlug');
+ const electronWorkspace = electronChildren.find((route) => route.path === ':workspaceSlug');
- expect(asyncSource).toContain('BusinessResourceRoutes');
- expect(syncSource).toContain('BusinessResourceRoutes');
- expect(asyncSource).toContain('...BusinessResourceRoutes');
- expect(syncSource).toContain('...BusinessResourceRoutes');
+ expect(webChildren.find((route) => route.index)?.element).toBeUndefined();
+ expect(webWorkspace?.children?.find((route) => route.index)?.element).toBeUndefined();
+ expect(electronChildren.find((route) => route.index)?.element).toBeDefined();
+ expect(electronWorkspace?.children?.find((route) => route.index)?.element).toBeDefined();
});
- it('task list and detail desktop routes share one workspace layout', async () => {
- const [asyncSource, syncSource] = await readDesktopRouterSources();
-
- expect(asyncSource).toContain("import('@/routes/(main)/(task-workspace)/_layout')");
- expect(syncSource).toContain("from '@/routes/(main)/(task-workspace)/_layout'");
- expect(asyncSource).toContain("import('@/routes/(main)/agent/task/[taskId]')");
- expect(syncSource).toContain("from '@/routes/(main)/agent/task/[taskId]'");
- expect(asyncSource).not.toContain("import('@/routes/(main)/task-workspace/_layout')");
- expect(syncSource).not.toContain("from '@/routes/(main)/task-workspace/_layout'");
- expect(asyncSource).not.toContain("import('@/routes/(main)/tasks/_layout')");
- expect(asyncSource).not.toContain("import('@/routes/(main)/task/_layout')");
- expect(syncSource).not.toContain("from '@/routes/(main)/tasks/_layout'");
- expect(syncSource).not.toContain("from '@/routes/(main)/task/_layout'");
+ it.each(mainAreaVariants)(
+ '%s registers every workspace-aware settings tab',
+ (_, createMainAreaChildren) => {
+ const settingsRoute = findWorkspaceSettingsRoute(createMainAreaChildren);
+ const registeredTabs = [
+ ...new Set(
+ collectPaths(settingsRoute?.children ?? []).map(
+ (registeredPath) => registeredPath.split('/')[0],
+ ),
+ ),
+ ].sort();
+
+ expect(settingsRoute, 'Workspace settings route must exist').toBeDefined();
+ expect(registeredTabs).toEqual([...WORKSPACE_SETTINGS_TABS].sort());
+ },
+ );
+
+ it.each(mainAreaVariants)(
+ '%s registers workspace OAuth app list and detail routes',
+ (_, factory) => {
+ const routes = createMainAreaRoutes(factory);
+ const listMatches = matchRoutes(routes, '/acme/settings/oauth-apps');
+ const detailMatches = matchRoutes(routes, '/acme/settings/oauth-apps/client-1');
+
+ expect(listMatches?.at(-1)?.route.path).toBe('oauth-apps');
+ expect(detailMatches?.at(-1)?.route.path).toBe('oauth-apps/:sub');
+ expect(detailMatches?.at(-1)?.params).toMatchObject({
+ sub: 'client-1',
+ workspaceSlug: 'acme',
+ });
+ },
+ );
+
+ it('keeps business resource and task routes in the shared definition', async () => {
+ const [sharedSource] = await readRouterSources();
+
+ expect(sharedSource).toContain('...BusinessResourceRoutes');
+ expect(sharedSource).toContain("import('@/routes/(main)/(task-workspace)/_layout')");
+ expect(sharedSource).toContain("import('@/routes/(main)/agent/task/[taskId]')");
+ expect(sharedSource).not.toContain("import('@/routes/(main)/task-workspace/_layout')");
+ expect(sharedSource).not.toContain("import('@/routes/(main)/tasks/_layout')");
+ expect(sharedSource).not.toContain("import('@/routes/(main)/task/_layout')");
});
});
diff --git a/src/store/user/slices/auth/initialState.ts b/src/store/user/slices/auth/initialState.ts
index 9ba2da2e42a..b905e5eedf9 100644
--- a/src/store/user/slices/auth/initialState.ts
+++ b/src/store/user/slices/auth/initialState.ts
@@ -8,7 +8,10 @@ export interface UserAuthState {
* Whether user registered with email/password (credential login)
*/
hasPasswordAccount?: boolean;
+ /** Whether the current local cache identity has been authoritatively selected. */
+ isIdentityResolved?: boolean;
isLoaded?: boolean;
+
isLoadedAuthProviders?: boolean;
isSignedIn?: boolean;
diff --git a/src/store/user/slices/common/action.ts b/src/store/user/slices/common/action.ts
index c03e6d95bd6..f5c122695e5 100644
--- a/src/store/user/slices/common/action.ts
+++ b/src/store/user/slices/common/action.ts
@@ -152,6 +152,8 @@ export class CommonActionImpl {
isShowPWAGuide: data.canEnablePWAGuide,
isUserCanEnableTrace: data.canEnableTrace,
isUserHasConversation: data.hasConversation,
+ isIdentityResolved: true,
+ isSignedIn: Boolean(data.userId) || this.#get().isSignedIn,
isUserStateInit: true,
isUserStateInitError: undefined,
onboarding: data.onboarding,