Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(dev): 新 worktree 装完依赖即可用,开发版启动失败能看到原因 (#5815)

Dasha9a1ebc1a262
diff --git a/docs/dev-rules/desktop-development.md b/docs/dev-rules/desktop-development.md
index 45e25f2458..ea239fa1ea 100644
--- a/docs/dev-rules/desktop-development.md
+++ b/docs/dev-rules/desktop-development.md
@@ -43,6 +43,11 @@ pnpm restart:desktop:remote -- --shared
失败时把 `code` / `message` 交给用户。若有 `next=` 且用户没有点名必须共享,
可以执行那条 next 命令重试。不要给启动命令接会吞退出码的管道。
+Agent 没有 TTY 时,dev 会在新开的 Terminal(macOS)/cmd(Windows)窗口里运行。macOS 上
+该窗口的输出同时写入当前 checkout 的 `apps/desktop/logs/dev-terminal.log`(每次启动覆盖,
+只保留前 8MB,足够覆盖启动过程;之后的运行日志看按天轮转的 `main-*.log`),窗口关掉后仍可查;启动失败时命令会直接打印日志末尾,verdict 带 `log=` 指向该文件。
+排查启动失败先读这份日志,不要靠反复重启猜原因。
+
Desktop 连接的是你自己的 Cindy 云端账号(remote)。这与登录页中免 Cindy 账号的
「跳过登录」(应用内显示为「未登录」,无需账号即可使用本机 agent;代码内部标识仍为
`local` mode)不是同一个概念。Agent 不得自行改用
@@ -132,7 +137,11 @@ checkout 的启动器顶掉)。因此并行多开的标准姿势是:**每个
- **userData 冲突门**:目标 userData(按 `--isolated` 名字推导)已被其他 checkout 的
dev 实例占用时,restart 会在杀任何进程之前中止并列出占用进程——不代杀、不共库。
- 换一个沙箱名字,或由用户自己停掉那个实例后重试。检测靠 helper 进程命令行上的
+ verdict 为 `USERDATA_IN_USE` 并给出 `next=… --isolated=@worktree`:执行它即可改用本
+ worktree 自己的沙箱并行启动(首次需登录);或由用户自己停掉那个实例后重试。
+- **嵌套的托管 worktree 不算本 checkout**:`.cindy-worktrees/<name>` 位于主 checkout
+ 目录内,进程归属按命中的最深 worktree 判定。从主 checkout restart 不会停掉托管 worktree
+ 的实例,冲突门也会把它们当作其他 checkout。检测靠 helper 进程命令行上的
`--user-data-dir`,对方实例刚启动还没起 helper 时可能漏检,属尽力而为。
- **CDP 端口**:dev 的 remote-debugging-port 固定 9222,只有先起的实例能绑上。后起
实例需要 CDP 调试面时,用 `XDT_CDP_PORT=<端口>` 覆写(仅数字生效,dev-only)。
diff --git a/docs/dev-rules/development-workflow.md b/docs/dev-rules/development-workflow.md
index d05709dd70..32fb2991b2 100644
--- a/docs/dev-rules/development-workflow.md
+++ b/docs/dev-rules/development-workflow.md
@@ -20,7 +20,10 @@ worktree 会话契约、直推 `main` 的额外门禁与 review 严重度口径
- **你的编辑对运行中的 app 无效**:Vite HMR 只 watch 启动 dev 实例的那个 checkout,
worktree 下的改动既不热更也不随重启生效。「改了没反应」不是 bug。开发过程中的增量验证在本
worktree 内跑 `pnpm --filter desktop typecheck` / 定向 `vitest run`;**提交前仍须完成
- 第 2 节的提交前验证**。需要运行时验证时 commit + push 后交用户(你无法重启宿主)。
+ 第 2 节的提交前验证**。需要运行时验证时,在本 worktree 用
+ `pnpm restart:desktop:remote -- --isolated=@worktree` 起一个属于本 worktree 的独立实例
+ (不会停掉宿主,也不与其他 checkout 抢默认 `dev` 沙箱),成功以
+ `DESKTOP_DEV_VERDICT=ready` 为准,细则见 [`desktop-development.md`](desktop-development.md)。
- **宿主 app 日志不在你的 cwd 下**:dev 日志在启动 checkout(通常是 baseRepo)的
`apps/desktop/logs/`,读日志时拼 baseRepo 的绝对路径。
- **会话结束与工作区保留**:是否 commit 由用户或宿主工作流决定,不能仅因会话结束
diff --git a/docs/dev-rules/environment-setup.md b/docs/dev-rules/environment-setup.md
index be483affc8..2628e9ee77 100644
--- a/docs/dev-rules/environment-setup.md
+++ b/docs/dev-rules/environment-setup.md
@@ -30,8 +30,17 @@ pnpm install
自动补下载,仍无法准备才会中止 dev 启动并给出明确错误。
正常情况下无需手动安装二进制。
+postinstall 最后还会按 Electron `install.js` 的语义复核 `node_modules/electron/dist`,
+缺失或版本不符就补装(`node scripts/ensure-deps.mjs --electron-binary`;设置了
+`ELECTRON_SKIP_BINARY_DOWNLOAD` 或 `ELECTRON_OVERRIDE_DIST_PATH` 时跳过)。原因:pnpm 的
+side-effects cache 一旦记下「electron 已构建但没有产物」,同机之后每次安装都会跳过 Electron
+自己的 postinstall,留下缺 dist 的安装,桌面端单测会整片报 `Electron failed to install
+correctly`。`pnpm test:unit` 等 workspace 测试开跑前也会只读检查一次依赖与 Electron,
+未就绪时以 `DEPENDENCY_SETUP_INCOMPLETE` 直接给出处置命令,不再让几十个测试文件各自报错。
+
新 worktree 不共享 `node_modules`。确认 checkout 已完成且根 `package.json` 存在后,
-在该 worktree 内重新运行 `pnpm install`。
+在该 worktree 内重新运行 `pnpm install`;不要加 `--ignore-scripts`,上述补装都在安装
+脚本里完成。
Cindy Make 的设置入口和指令前置弹窗共用源码准备流程:切到 `cindy-personal` 后,
按锁文件预热包含开发依赖的 pnpm store 缓存,成功后才标记源码就绪。预热使用
diff --git a/package.json b/package.json
index 98015f2cb7..7a6a265501 100644
--- a/package.json
+++ b/package.json
@@ -100,7 +100,7 @@
"install:ripgrep": "node scripts/ensure-agent-binaries.mjs --kinds=ripgrep",
"install:pi": "node scripts/ensure-agent-binaries.mjs --kinds=pi",
"install:agent-binaries": "node scripts/ensure-agent-binaries.mjs",
- "postinstall": "node scripts/ensure-agent-binaries.mjs --best-effort && node scripts/fix-node-pty-perms.mjs",
+ "postinstall": "node scripts/ensure-agent-binaries.mjs --best-effort && node scripts/fix-node-pty-perms.mjs && node scripts/ensure-deps.mjs --electron-binary",
"dev:desktop": "node scripts/ensure-deps.mjs && node scripts/ensure-dev-runtime-assets.mjs && pnpm --filter desktop dev",
"dev:desktop:remote": "node scripts/ensure-deps.mjs && node scripts/ensure-dev-runtime-assets.mjs && pnpm --filter desktop dev:remote",
"restart:desktop:remote": "node scripts/desktop-restart-runner.mjs --wait-ready",
diff --git a/scripts/__tests__/ensure-deps.test.mjs b/scripts/__tests__/ensure-deps.test.mjs
index 8f4e1e3e58..e948f99534 100644
--- a/scripts/__tests__/ensure-deps.test.mjs
+++ b/scripts/__tests__/ensure-deps.test.mjs
@@ -5,7 +5,11 @@ import path from 'node:path';
import test from 'node:test';
import { spawnSync } from 'node:child_process';
-import { checkWorkspaceDependencies, resolvePnpmInstallInvocation } from '../ensure-deps.mjs';
+import {
+ checkWorkspaceDependencies,
+ electronBinaryCheckSkipReason,
+ resolvePnpmInstallInvocation,
+} from '../ensure-deps.mjs';
test('runs a native pnpm binary directly instead of feeding it to node', () => {
// pnpm 的原生二进制发行版把 npm_execpath 指向可执行文件本身;交给 node 会抛
@@ -114,3 +118,33 @@ test('workspace-only CLI fails without installing or deleting incomplete depende
assert.equal(fs.existsSync(path.join(root, 'installed')), false);
} finally { fs.rmSync(root, { recursive: true, force: true }); }
});
+
+
+test('postinstall Electron check honors CI stub and explicit skip', () => {
+ assert.equal(electronBinaryCheckSkipReason({}), null);
+ assert.equal(electronBinaryCheckSkipReason({ ELECTRON_SKIP_BINARY_DOWNLOAD: '1' }), 'ELECTRON_SKIP_BINARY_DOWNLOAD');
+ assert.equal(
+ electronBinaryCheckSkipReason({ ELECTRON_OVERRIDE_DIST_PATH: '/stub', ELECTRON_SKIP_BINARY_DOWNLOAD: '1' }),
+ 'ELECTRON_OVERRIDE_DIST_PATH',
+ );
+});
+
+test('electron-binary CLI leaves an incomplete install untouched when download is skipped', () => {
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-electron-skip-')));
+ try {
+ fs.mkdirSync(path.join(root, 'scripts/shared'), { recursive: true });
+ for (const file of ['ensure-deps.mjs', 'shared/pnpm-invocation.mjs']) {
+ fs.copyFileSync(new URL(`../${file}`, import.meta.url), path.join(root, 'scripts', file));
+ }
+ const electronDir = path.join(root, 'node_modules/electron');
+ fs.mkdirSync(electronDir, { recursive: true });
+ fs.writeFileSync(path.join(electronDir, 'package.json'), JSON.stringify({ name: 'electron', version: '1.0.0' }));
+ const result = spawnSync(process.execPath, [path.join(root, 'scripts/ensure-deps.mjs'), '--electron-binary'], {
+ // CI 本身设置了 ELECTRON_OVERRIDE_DIST_PATH,这里显式去掉,只验证跳过下载这一路。
+ encoding: 'utf8', env: { ...process.env, ELECTRON_OVERRIDE_DIST_PATH: '', ELECTRON_SKIP_BINARY_DOWNLOAD: '1' },
+ });
+ assert.equal(result.status, 0);
+ assert.match(result.stdout, /ELECTRON_SKIP_BINARY_DOWNLOAD/);
+ assert.deepEqual(fs.readdirSync(electronDir), ['package.json']);
+ } finally { fs.rmSync(root, { recursive: true, force: true }); }
+});
diff --git a/scripts/__tests__/restart-desktop-remote.test.mjs b/scripts/__tests__/restart-desktop-remote.test.mjs
index 427c35b9f7..5237d6e502 100644
--- a/scripts/__tests__/restart-desktop-remote.test.mjs
+++ b/scripts/__tests__/restart-desktop-remote.test.mjs
@@ -28,6 +28,10 @@ import {
formatDesktopStartupFailure,
inspectSharedUserDataRegion,
partitionDesktopDevProcesses,
+ commandBelongsToCheckout,
+ darwinTerminalLoggedCommand,
+ desktopDevTerminalLogPath,
+ readDesktopDevLogTail,
productionUserDataDir,
readDesktopStartupStatus,
parseWorktreePaths,
@@ -234,6 +238,31 @@ test("restart kill scope only targets the checkout that runs the script", () =>
assert.deepEqual(preserved.map((proc) => proc.pid), [2]);
});
+test("restart from the main checkout keeps dev instances of nested managed worktrees", () => {
+ const mainRoot = path.resolve("/repo/cindy-src");
+ const nestedRoot = path.join(mainRoot, ".cindy-worktrees", "fierce-newton");
+ const checkoutPaths = [mainRoot, nestedRoot];
+ const processes = [
+ { pid: 1, command: `${path.join(mainRoot, "node_modules/electron/dist/Electron.app/Contents/MacOS/Electron")} .` },
+ { pid: 2, command: `${path.join(nestedRoot, "node_modules/electron/dist/Electron.app/Contents/MacOS/Electron")} .` },
+ ];
+
+ const fromMain = partitionDesktopDevProcesses(processes, mainRoot, checkoutPaths);
+ assert.deepEqual(fromMain.targets.map((proc) => proc.pid), [1]);
+ assert.deepEqual(fromMain.preserved.map((proc) => proc.pid), [2]);
+ const fromNested = partitionDesktopDevProcesses(processes, nestedRoot, checkoutPaths);
+ assert.deepEqual(fromNested.targets.map((proc) => proc.pid), [2]);
+ assert.equal(commandBelongsToCheckout(processes[1].command, mainRoot, checkoutPaths), false);
+ assert.equal(
+ shouldRefuseHostedRestart(processes[1], { ownRootDir: mainRoot, isolated: true, checkoutPaths }),
+ false,
+ );
+ assert.equal(
+ shouldRefuseHostedRestart(processes[0], { ownRootDir: mainRoot, isolated: true, checkoutPaths }),
+ true,
+ );
+});
+
test("userData conflict detection matches exact sandbox dirs only", () => {
const helper =
"/repo/cindy-pi-sandbox/node_modules/electron/dist/Electron Helper (Renderer).app/Contents/MacOS/Electron Helper (Renderer) " +
@@ -1217,6 +1246,26 @@ test("isolated failures do not suggest another isolated start", () => {
assert.equal(verdict.mode, "isolated");
});
+test("userData conflicts in the shared dev sandbox suggest a per-worktree sandbox", () => {
+ const verdict = buildDesktopDevVerdictFromFailure(
+ new Error("Target userData is already in use by another checkout's dev instance: /x"),
+ { isolated: true, sandbox: "dev", code: "USERDATA_IN_USE" },
+ );
+ assert.equal(verdict.code, "USERDATA_IN_USE");
+ assert.equal(verdict.next, ISOLATED_RESTART_NEXT);
+});
+
+test("failure verdict carries the dev terminal log path", () => {
+ const verdict = buildDesktopDevVerdictFromFailure(new Error("boom"), {
+ isolated: true,
+ log: "/repo/cindy-feature/apps/desktop/logs/dev-terminal.log",
+ });
+ assert.match(
+ formatDesktopDevVerdict(verdict),
+ /^log=\/repo\/cindy-feature\/apps\/desktop\/logs\/dev-terminal\.log$/m,
+ );
+});
+
test("inferDesktopDevFailureCode reads tagged startup failures", () => {
assert.equal(inferDesktopDevFailureCode("[SINGLE_INSTANCE_OWNED] owned"), "SINGLE_INSTANCE_OWNED");
assert.equal(
@@ -1451,3 +1500,54 @@ test("darwinStaleDevEnvUnset keeps variables this launch forwards (isolated with
const forwarded = devEnvPrefix(env, "darwin");
for (const key of keys) assert.ok(!forwarded.includes(`${key}=`), `${key} both forwarded and unset`);
});
+
+test("darwin dev terminal output is recorded through script(1) under the checkout logs", () => {
+ const logPath = desktopDevTerminalLogPath("/repo/cindy feature");
+ assert.equal(logPath, path.join("/repo/cindy feature", "apps", "desktop", "logs", "dev-terminal.log"));
+ const command = darwinTerminalLoggedCommand("'node' 'runner.mjs' 'remote'", logPath, {
+ envPrefix: "XDT_ISOLATED='1' ",
+ maxBytes: 1024,
+ });
+ assert.match(command, /^\{ /);
+ assert.ok(command.includes(`head -c 1024 > '${logPath}'`), command);
+ // 环境变量前缀必须紧贴 script,才能传给 dev 进程。
+ assert.match(command, /; XDT_ISOLATED='1' \/usr\/bin\/script -q -F '[^']+dev-terminal\.log\.fifo' 'node' 'runner\.mjs' 'remote'; /);
+ assert.match(command, /\(exit \$cindyDevExit\); \}$/);
+});
+
+test("logged terminal command keeps the child exit code and caps the log size", {
+ skip: process.platform !== "darwin" ? "script(1) flags differ outside macOS" : false,
+}, () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cindy-dev-term-"));
+ try {
+ const logPath = path.join(dir, "dev-terminal.log");
+ const child = "sh -c 'i=0; while [ $i -lt 2000 ]; do echo line-$i-$CINDY_PROBE; i=$((i+1)); done; exit 4'";
+ const logged = darwinTerminalLoggedCommand(child, logPath, { envPrefix: "CINDY_PROBE='ok' ", maxBytes: 64 });
+ const result = spawnSync("/bin/sh", ["-c", `cd / && ${logged}; echo exit=$?`], {
+ encoding: "utf8",
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ assert.match(result.stdout, /exit=4\s*$/);
+ assert.equal(fs.statSync(logPath).size, 64);
+ assert.match(fs.readFileSync(logPath, "utf8"), /line-0-ok/);
+ assert.equal(fs.existsSync(`${logPath}.fifo`), false);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("readDesktopDevLogTail strips terminal control sequences and keeps the last lines", () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "cindy-dev-log-"));
+ try {
+ const logPath = path.join(dir, "dev-terminal.log");
+ fs.writeFileSync(
+ logPath,
+ "\x04\b\bstart\r\n\x1b[32mvite ready\x1b[0m\r\nprogress 1\rprogress 2\r\n\r\nError: boom\r\n",
+ );
+ assert.deepEqual(readDesktopDevLogTail(logPath), ["start", "vite ready", "progress 2", "Error: boom"]);
+ assert.deepEqual(readDesktopDevLogTail(logPath, 2), ["progress 2", "Error: boom"]);
+ assert.deepEqual(readDesktopDevLogTail(path.join(dir, "missing.log")), []);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjs
index ac4ed2de6b..530df077ec 100644
--- a/scripts/__tests__/test-workspaces.test.mjs
+++ b/scripts/__tests__/test-workspaces.test.mjs
@@ -33,6 +33,8 @@ import {
discoverTestFiles,
expandWorkspacePatterns,
filterRunsByWorkspace,
+ findDependencyInstallIssues,
+ selectionNeedsElectron,
isIgnoredFile,
mapWithConcurrency,
normalizeRelPath,
@@ -2225,10 +2227,11 @@ test("CLI runs independently while another worktree budget is held, and waits on
const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "test-lock-opt-in-")));
let heldLock;
try {
- for (const dir of [".git", "scripts/shared", "packages/sample"]) {
+ for (const dir of [".git", "scripts/shared", "packages/sample", "node_modules"]) {
fs.mkdirSync(path.join(root, dir), { recursive: true });
}
- for (const file of ["test-workspaces.mjs", "test-related.mjs", "shared/pnpm-invocation.mjs"]) {
+ fs.writeFileSync(path.join(root, "node_modules/.modules.yaml"), "{}");
+ for (const file of ["test-workspaces.mjs", "test-related.mjs", "ensure-deps.mjs", "shared/pnpm-invocation.mjs"]) {
fs.copyFileSync(path.join(ROOT, "scripts", file), path.join(root, "scripts", file));
}
// Both the holder and the real CLI child must use the same dispersed test
@@ -2299,3 +2302,38 @@ export const acquireTestGateLock = (options) => acquire({ ...options, ...${JSON.
fs.rmSync(root, { recursive: true, force: true });
}
});
+
+test("dependency preflight explains missing installs and incomplete Electron", () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "cindy-dep-preflight-"));
+ try {
+ assert.match(findDependencyInstallIssues(root, {})[0], /pnpm install/);
+
+ fs.mkdirSync(path.join(root, "node_modules/electron"), { recursive: true });
+ fs.writeFileSync(path.join(root, "node_modules/.modules.yaml"), "{}");
+ assert.match(findDependencyInstallIssues(root, {})[0], /node_modules\/electron/);
+ fs.writeFileSync(
+ path.join(root, "node_modules/electron/package.json"),
+ JSON.stringify({ name: "electron", version: "1.0.0" }),
+ );
+ const [electronIssue] = findDependencyInstallIssues(root, {});
+ assert.match(electronIssue, /Electron/);
+ assert.match(electronIssue, /--electron-binary/);
+ assert.deepEqual(
+ findDependencyInstallIssues(root, { ELECTRON_OVERRIDE_DIST_PATH: "/stub" }),
+ [],
+ );
+ assert.deepEqual(findDependencyInstallIssues(root, {}, { needsElectron: false }), []);
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("only selections that include Desktop need the Electron binary", () => {
+ const workspaces = manifest.workspaces;
+ assert.equal(selectionNeedsElectron(workspaces), true);
+ assert.equal(selectionNeedsElectron(workspaces, { workspaces: ["apps/desktop"] }), true);
+ assert.equal(selectionNeedsElectron(workspaces, { workspaces: ["desktop", "packages/auth-client"] }), true);
+ assert.equal(selectionNeedsElectron(workspaces, { workspaces: ["packages/auth-client"] }), false);
+ assert.equal(selectionNeedsElectron(workspaces, { excludeWorkspaces: ["desktop"] }), false);
+ assert.equal(selectionNeedsElectron([{ name: "sample", cwd: "packages/sample" }]), false);
+});
diff --git a/scripts/desktop-dev-verdict.mjs b/scripts/desktop-dev-verdict.mjs
index 570f2269f5..529f1d9c45 100644
--- a/scripts/desktop-dev-verdict.mjs
+++ b/scripts/desktop-dev-verdict.mjs
@@ -17,6 +17,7 @@ const VERDICT_FIELDS = Object.freeze([
'pid',
'region',
'message',
+ 'log',
'next',
]);
@@ -158,7 +159,9 @@ export function printDesktopDevVerdict(verdict, writer = console.log) {
}
function isolatedNextIfNeeded(context, code) {
- return shouldSuggestIsolatedNext({ isolated: context.isolated, code })
+ // 默认 dev 沙箱跨 checkout 共用:被另一个 worktree 的实例占着时,换成本 worktree
+ // 自己的沙箱就能并行启动,不必停掉别人的实例。
+ return code === 'USERDATA_IN_USE' || shouldSuggestIsolatedNext({ isolated: context.isolated, code })
? { next: isolatedRestartNextCommand(context) }
: {};
}
@@ -216,6 +219,7 @@ export function buildDesktopDevVerdictFromFailure(error, context = {}) {
mode: context.isolated ? 'isolated' : 'shared',
...(context.sandbox ? { sandbox: context.sandbox } : {}),
...(context.rootDir ? { root: context.rootDir } : {}),
+ ...(context.log ? { log: context.log } : {}),
...isolatedNextIfNeeded(context, code),
};
}
diff --git a/scripts/ensure-deps.mjs b/scripts/ensure-deps.mjs
index c078daa0c6..41bfca1499 100644
--- a/scripts/ensure-deps.mjs
+++ b/scripts/ensure-deps.mjs
@@ -8,6 +8,9 @@
* 3. Electron binary 完整性 — 确认 electron postinstall 已完整解出 dist binary
* 4. native ABI 隔离 — root 保持 Node ABI,Electron cache 单独准备 native binding
*
+ * `--electron-binary` 只跑第 3 道,由根 postinstall 调用,让任何 `pnpm install` 结束时
+ * Electron 都是完整的。
+ *
* 关于 hoisted 模式:项目 .npmrc 指定 node-linker=hoisted,绝大多数依赖被平铺到根
* node_modules,但原生二进制包(electron、protobufjs 等)必须留
* 在子包 node_modules 下。如果这些子包目录只剩 postinstall 产物(例如
@@ -430,6 +433,26 @@ function ensureElectronBinaryComplete(root = ROOT) {
}
}
+// CI 用 stub dist 代替真实 Electron;显式跳过下载时也不应在安装阶段补下载。
+export function electronBinaryCheckSkipReason(env = process.env) {
+ if (env.ELECTRON_OVERRIDE_DIST_PATH) return 'ELECTRON_OVERRIDE_DIST_PATH';
+ if (env.ELECTRON_SKIP_BINARY_DOWNLOAD) return 'ELECTRON_SKIP_BINARY_DOWNLOAD';
+ return null;
+}
+
+// 由根 postinstall 调用。pnpm 的 side-effects cache 一旦记下「electron 构建完成但没有产物」
+// (例如某次安装设置了 ELECTRON_SKIP_BINARY_DOWNLOAD),之后同机每个新 worktree 都会跳过
+// Electron 自己的 postinstall,留下缺 dist 的安装。这里在每次 install 末尾按 install.js
+// 语义复核一次,缺失就补装,不依赖 store 缓存是否干净。
+function ensureElectronBinaryAfterInstall() {
+ const skipReason = electronBinaryCheckSkipReason();
+ if (skipReason) {
+ log(`已设置 ${skipReason},跳过 Electron binary 检查`);
+ return;
+ }
+ ensureElectronBinaryComplete();
+}
+
// 检测 frozen-lockfile 是否生效(根 .npmrc 显式配置,或环境变量覆盖)。
// 仅用于在 install 失败时判断要不要给出 frozen 专属的修复指引。
function isFrozenLockfileEnabled() {
@@ -736,6 +759,10 @@ function main() {
ensureWorkspaceOnlyDependencies();
return;
}
+ if (process.argv.slice(2).includes('--electron-binary')) {
+ ensureElectronBinaryAfterInstall();
+ return;
+ }
cleanStaleSubpkgDirs();
diff --git a/scripts/restart-desktop-remote.mjs b/scripts/restart-desktop-remote.mjs
index a8043f6aeb..8fe4ef0022 100644
--- a/scripts/restart-desktop-remote.mjs
+++ b/scripts/restart-desktop-remote.mjs
@@ -166,16 +166,31 @@ export function commandUsesUserDataDir(command, userDataDir) {
return false;
}
+/**
+ * 进程是否属于 ownRootDir 这份 checkout。Cindy 托管的 `.cindy-worktrees/<name>`
+ * 嵌在主 checkout 目录里,只看路径前缀会把托管 worktree 的 dev 当成主 checkout
+ * 自己的进程(主仓 restart 误杀并行实例、userData 冲突门漏检)。归属以命中的
+ * 最深 checkout 为准:同时命中嵌套在 ownRootDir 下的其他 worktree 时不算自己的。
+ */
+export function commandBelongsToCheckout(command, ownRootDir, checkoutPaths = []) {
+ if (!commandContainsPath(command, ownRootDir)) return false;
+ const own = stripTrailingSlashes(normalize(ownRootDir));
+ return !checkoutPaths.some((candidate) => {
+ const normalized = stripTrailingSlashes(normalize(candidate));
+ return normalized.startsWith(`${own}/`) && commandContainsPath(command, candidate);
+ });
+}
+
/**
* 重启的 kill 作用域:只收当前 checkout(ownRootDir)自己的 dev 进程。其他
* worktree / 命名沙箱一律保留 ——「重启」的语义是重启这份 checkout 的实例,
* 不是清场(2026-07-30 约束:PI 沙箱启动器曾全灭掉并行的 tgbot-review 沙箱)。
*/
-export function partitionDesktopDevProcesses(processes, ownRootDir) {
+export function partitionDesktopDevProcesses(processes, ownRootDir, checkoutPaths = []) {
const targets = [];
const preserved = [];
for (const proc of processes) {
- (commandContainsPath(proc.command, ownRootDir) ? targets : preserved).push(proc);
+ (commandBelongsToCheckout(proc.command, ownRootDir, checkoutPaths) ? targets : preserved).push(proc);
}
return { targets, preserved };
}
@@ -486,6 +501,49 @@ export function prepareDarwinTerminalLaunch(command, dir = os.tmpdir()) {
};
}
+// 足够覆盖启动全过程(实测一次冷启动约 0.6MB);main/agent 日志另有按天轮转的文件。
+export const DEV_TERMINAL_LOG_MAX_BYTES = 8 * 1024 * 1024;
+
+export function desktopDevTerminalLogPath(root = rootDir) {
+ return path.join(root, 'apps', 'desktop', 'logs', 'dev-terminal.log');
+}
+
+// Agent 没有 TTY 时 dev 跑在新开的 Terminal 标签页里,进程退出后标签页随之关闭,
+// 失败原因就看不到了。script(1) 继续给子进程一个 pty(electron-forge 依赖 TTY),
+// 输出经命名管道只把前 maxBytes 写进日志、其余丢弃:dev 会把 trace 级日志镜像到
+// 终端,长期运行的实例不能让这份文件无限增长。每次启动覆盖,退出码与子进程一致。
+// 返回一个 `{ ...; }` 命令组,可以整体接在 `cd … &&` 后面;envPrefix 只作用于 script。
+export function darwinTerminalLoggedCommand(
+ command,
+ logPath,
+ { envPrefix = '', maxBytes = DEV_TERMINAL_LOG_MAX_BYTES } = {},
+) {
+ const log = shellSingleQuote(logPath);
+ const fifo = shellSingleQuote(`${logPath}.fifo`);
+ return [
+ `{ rm -f ${fifo}; mkfifo ${fifo} && { { head -c ${maxBytes} > ${log}; cat > /dev/null; } < ${fifo} & }; `,
+ `${envPrefix}/usr/bin/script -q -F ${fifo} ${command}; `,
+ `cindyDevExit=$?; rm -f ${fifo}; (exit $cindyDevExit); }`,
+ ].join('');
+}
+
+export function readDesktopDevLogTail(logPath, maxLines = 40) {
+ let text;
+ try {
+ text = fs.readFileSync(logPath, 'utf8');
+ } catch {
+ return [];
+ }
+ const lines = text
+ // ANSI 转义、script(1) 写入的 ^D/退格等控制字符都去掉,只保留可读文本。
+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
+ .replace(/\x1b\][^\x07]*\x07/g, '')
+ .split(/\r?\n/)
+ .map((line) => line.split('\r').at(-1).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, '').trimEnd())
+ .filter((line) => line.trim() !== '');
+ return lines.slice(-maxLines);
+}
+
function osascriptCloseDarwinTerminalTtyArgs(ttyPath) {
return closeDarwinTerminalTtyScript
.flatMap((line) => ['-e', line])
@@ -742,14 +800,15 @@ export function shouldRefuseHostedRestart(ancestor, {
preserveRunning,
ownRootDir,
isolated = false,
+ checkoutPaths = [],
}) {
if (!ancestor || preserveRunning) return false;
- if (commandContainsPath(ancestor.command, ownRootDir)) return true;
+ if (commandBelongsToCheckout(ancestor.command, ownRootDir, checkoutPaths)) return true;
return isolated !== true;
}
-export function hostedRestartRefusal(ancestor, { ownRootDir }) {
- return commandContainsPath(ancestor.command, ownRootDir)
+export function hostedRestartRefusal(ancestor, { ownRootDir, checkoutPaths = [] }) {
+ return commandBelongsToCheckout(ancestor.command, ownRootDir, checkoutPaths)
? {
code: 'HOSTED_RESTART_REFUSED',
message: "Refusing to restart from within this checkout's desktop dev process tree.",
@@ -982,7 +1041,11 @@ function launchInSystemTerminal(mode) {
}
if (process.platform === 'darwin') {
- const command = `${darwinEnvPrefix()}${darwinStaleDevEnvUnset()}cd ${shellSingleQuote(rootDir)} && ${devEnvPrefix()}${packageManagerCommand(mode)}; exitCode=$?; exit $exitCode`;
+ const logPath = desktopDevTerminalLogPath();
+ fs.mkdirSync(path.dirname(logPath), { recursive: true });
+ fs.rmSync(logPath, { force: true });
+ fs.rmSync(`${logPath}.fifo`, { force: true });
+ const command = `${darwinEnvPrefix()}${darwinStaleDevEnvUnset()}cd ${shellSingleQuote(rootDir)} && ${darwinTerminalLoggedCommand(packageManagerCommand(mode), logPath, { envPrefix: devEnvPrefix() })}; exitCode=$?; exit $exitCode`;
const { scriptPath, args } = prepareDarwinTerminalLaunch(command);
// osascript 在 do script 之前失败(自动化权限被拒、脚本错误)时临时脚本不会被 source,
// 首行自删不会发生;按失败退出尽力删除,避免留下含开发环境变量的文件。
@@ -1007,19 +1070,20 @@ function launchInSystemTerminal(mode) {
throw new Error('Failed to open Terminal.app');
}
console.log(`==> Opened desktop ${mode} dev in a new Terminal window.`);
- return;
+ console.log(`==> Dev terminal output is also written to ${logPath}`);
+ return logPath;
}
console.warn('==> Non-interactive terminal detected, but no system terminal launcher is configured for this platform.');
console.warn('==> Falling back to current process; this may fail if electron-forge requires a TTY.');
+ return null;
}
function startDesktopDev(mode) {
console.log(`==> Starting desktop ${mode} dev...`);
if (!hasInteractiveTty() && (process.platform === 'win32' || process.platform === 'darwin')) {
- launchInSystemTerminal(mode);
- return;
+ return launchInSystemTerminal(mode) ?? null;
}
const child = spawn(process.execPath, [path.join(rootDir, 'scripts', 'desktop-dev-runner.mjs'), mode], {
@@ -1035,6 +1099,7 @@ function startDesktopDev(mode) {
if (signal) process.kill(process.pid, signal);
process.exit(code ?? 0);
});
+ return null;
}
function createStartupStatusPath() {
@@ -1313,13 +1378,16 @@ async function main() {
}
if (startupConfig) ensureDesktopEnv();
+ const checkoutPaths = repositoryWorktreePaths();
+ const belongsToThisCheckout = (proc) => commandBelongsToCheckout(proc.command, rootDir, checkoutPaths);
const devAncestor = findDevAncestor();
if (shouldRefuseHostedRestart(devAncestor, {
preserveRunning,
ownRootDir: rootDir,
isolated: hasIsolationIntent(argv, process.env),
+ checkoutPaths,
})) {
- const refusal = hostedRestartRefusal(devAncestor, { ownRootDir: rootDir });
+ const refusal = hostedRestartRefusal(devAncestor, { ownRootDir: rootDir, checkoutPaths });
exitWithFailure(
refusal.code,
refusal.message,
@@ -1383,7 +1451,7 @@ async function main() {
}
if (!preserveRunning) {
const conflicts = listDesktopDevProcesses().filter(
- (proc) => !commandContainsPath(proc.command, rootDir)
+ (proc) => !belongsToThisCheckout(proc)
&& commandUsesUserDataDir(proc.command, targetUserDataDir),
);
if (conflicts.length > 0) {
@@ -1414,7 +1482,7 @@ async function main() {
const allTargets = listDesktopDevProcesses();
// kill 作用域 = 当前 checkout。其他 worktree / 命名沙箱的实例一律保留。
- const ownScope = partitionDesktopDevProcesses(allTargets, rootDir);
+ const ownScope = partitionDesktopDevProcesses(allTargets, rootDir, checkoutPaths);
const targets = replaceRunningRoot
? allTargets.filter((proc) => commandContainsPath(proc.command, replaceRunningRoot))
: ownScope.targets;
@@ -1484,7 +1552,7 @@ async function main() {
// 等待/强杀同样限定在本 checkout —— 不带过滤器会把其他 checkout 仍在跑的
// 实例当成"顽固进程"逐个 SIGKILL 掉。
- const matchesOwnRoot = (proc) => commandContainsPath(proc.command, rootDir);
+ const matchesOwnRoot = belongsToThisCheckout;
const remainingAfterTerm = await waitForDesktopDevProcessesToExit(gracefulTimeoutMs, matchesOwnRoot);
if (remainingAfterTerm.length > 0) {
console.log(`==> Force stopping ${remainingAfterTerm.length} stubborn Cindy desktop dev process(es)...`);
@@ -1525,7 +1593,17 @@ async function main() {
isolationName: process.env.XDT_ISOLATED_NAME || '',
});
}
- startDesktopDev(mode);
+ const terminalLogPath = startDesktopDev(mode);
+ // 所有非 ready 的结论(启动失败、超时、ready 后进程退出导致的 WHOAMI_MISMATCH)
+ // 都先打印终端日志末尾,并在 verdict 里带上 log=。
+ const printFailedVerdict = (verdict) => {
+ const logTail = terminalLogPath ? readDesktopDevLogTail(terminalLogPath) : [];
+ if (logTail.length > 0) {
+ console.error(`==> Last ${logTail.length} lines of ${terminalLogPath}:`);
+ for (const line of logTail) console.error(` ${line}`);
+ }
+ printDesktopDevVerdict(terminalLogPath ? { ...verdict, log: terminalLogPath } : verdict);
+ };
if (startupStatusPath) {
try {
await waitForDesktopStartup(startupStatusPath);
@@ -1534,10 +1612,13 @@ async function main() {
userDataDir: process.env.XDT_USER_DATA_DIR,
});
const verdict = buildDesktopDevVerdictFromWhoami(report, verdictContext);
+ if (verdict.state !== 'ready') {
+ printFailedVerdict(verdict);
+ process.exit(1);
+ }
printDesktopDevVerdict(verdict);
- if (verdict.state !== 'ready') process.exit(1);
} catch (error) {
- printDesktopDevVerdict(buildDesktopDevVerdictFromFailure(error, verdictContext));
+ printFailedVerdict(buildDesktopDevVerdictFromFailure(error, verdictContext));
console.error(error instanceof Error ? error.message : error);
process.exit(1);
}
diff --git a/scripts/test-workspaces.mjs b/scripts/test-workspaces.mjs
index fdfddd202c..4918ddd862 100644
--- a/scripts/test-workspaces.mjs
+++ b/scripts/test-workspaces.mjs
@@ -4,6 +4,10 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
+import {
+ electronBinaryCheckSkipReason,
+ findElectronBinaryIssue,
+} from "./ensure-deps.mjs";
import { resolvePnpmInvocation } from "./shared/pnpm-invocation.mjs";
import {
acquireTestGateLock,
@@ -1026,6 +1030,44 @@ function intersectRelatedRuns(runs, requested, manifestWorkspaces) {
});
}
+// 只有选中 Desktop 时才需要 Electron;只跑其他 workspace 不应被桌面依赖拦住。
+export function selectionNeedsElectron(
+ manifestWorkspaces,
+ { workspaces = [], excludeWorkspaces = [] } = {},
+) {
+ const desktop = manifestWorkspaces.filter(
+ (workspace) => normalizeRelPath(workspace.cwd) === "apps/desktop",
+ );
+ return (
+ filterRunsByWorkspace(
+ desktop.map((workspace) => ({ workspace })),
+ { workspaces, excludeWorkspaces },
+ ).length > 0
+ );
+}
+
+// 新 worktree 没装依赖、或 Electron 没解出 dist 时,vitest 会让几十个文件各自报错,
+// 极易被当成被测代码或「环境问题」放过。开跑前只读检查一次,直接给出处置命令。
+export function findDependencyInstallIssues(
+ root = ROOT,
+ env = process.env,
+ { needsElectron = true } = {},
+) {
+ if (!fs.existsSync(path.join(root, "node_modules", ".modules.yaml"))) {
+ return ["依赖尚未安装:请先在当前 checkout 运行 pnpm install"];
+ }
+ if (!needsElectron || electronBinaryCheckSkipReason(env)) return [];
+ if (!fs.existsSync(path.join(root, "node_modules", "electron", "package.json"))) {
+ return ["依赖安装不完整(缺少 node_modules/electron):请在当前 checkout 运行 pnpm install"];
+ }
+ const electronIssue = findElectronBinaryIssue(root);
+ if (!electronIssue) return [];
+ return [
+ `Electron 安装不完整(${electronIssue.reason}: ${path.relative(root, electronIssue.missingPath)}):` +
+ "请运行 pnpm install,或 node scripts/ensure-deps.mjs --electron-binary 单独补装",
+ ];
+}
+
async function main() {
const options = parseCliOptions(process.argv.slice(2));
const {
@@ -1071,6 +1113,20 @@ async function main() {
related &&
(relatedPlan?.mode === "full" || relatedPlan?.runTestRunner);
if (related && !willRunWorkspaces && !willRunTestRunner) return;
+ if (willRunWorkspaces) {
+ const manifest = (await import("./test-workspaces.config.mjs")).default;
+ const installIssues = findDependencyInstallIssues(ROOT, process.env, {
+ needsElectron: selectionNeedsElectron(manifest.workspaces, {
+ workspaces,
+ excludeWorkspaces,
+ }),
+ });
+ if (installIssues.length > 0) {
+ for (const issue of installIssues) console.error(`DEPENDENCY_SETUP_INCOMPLETE ${issue}`);
+ process.exitCode = 1;
+ return;
+ }
+ }
const lock = shouldUseTestGateLock({ all, tier, lock: useLock, noLock })
? await acquireTestGateLock({