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。

feat(dev): 开发版启动输出不可忽略的 verdict (#2985)

Dash4537b5e4adf0
diff --git a/docs/dev-rules/desktop-development.md b/docs/dev-rules/desktop-development.md
index 3a6136d0b9..7268c4b00c 100644
--- a/docs/dev-rules/desktop-development.md
+++ b/docs/dev-rules/desktop-development.md
@@ -7,34 +7,52 @@
## Agent 启动入口
-Agent 启动 Desktop 只使用仓库根的安全包装命令,并显式选择目标区域:
+Agent 启动 Desktop 只使用仓库根的安全包装命令,并显式选择目标区域。用户只说
+「启动开发版 / 启动测试版 / 看当前改动」且没有指定模式时,使用当前 worktree 的
+命名隔离沙箱,不要默认共享正式登录态:
```bash
-pnpm restart:desktop:remote --region=global
-pnpm restart:desktop:remote --region=cn
+pnpm restart:desktop:remote --region=global -- --isolated=@worktree
+pnpm restart:desktop:remote --region=cn -- --isolated=@worktree
```
+`--isolated=@worktree` 按 checkout 目录名派生稳定沙箱名(去掉前导 `cindy-`,
+再加路径短哈希,例如 `cindy-local-ollama-models` → `local-ollama-models-a1b2c3`)。
+同一 worktree 下次还用这个名字,登录态会留在这份沙箱里。
+
+只有用户明确说「共享登录 / 不要重新登录 / 用现有数据 / 不要关当前实例」时才加
+`--preserve-running`。不要把「用户没提模式」理解成共享。
+
+启动命令结束时必须出现一行 `DESKTOP_DEV_VERDICT=ready` 才算成功;看到
+`DESKTOP_DEV_VERDICT=failed` 或根本没有 verdict 行,不得声称开发版已起来。
+失败时把 `code` / `message` 交给用户。若有 `next=` 且用户没有点名必须共享,
+可以执行那条 next 命令重试。不要给启动命令接会吞退出码的管道。
+
Desktop 连接的是你自己的 Cindy 云端账号(remote)。这与登录页中免 Cindy 账号的
「跳过登录」(应用内显示为「未登录」,无需账号即可使用本机 agent;代码内部标识仍为
`local` mode)不是同一个概念。Agent 不得自行改用
`pnpm dev:desktop` 或 `pnpm dev:desktop:remote` 绕过包装脚本。
启动包装会先停止**当前 checkout** 已有的 Desktop dev 进程;其他 worktree/命名沙箱的
-实例不受影响。必须尊重宿主提供的并行或保活工作流;如果脚本因为当前 Agent 运行在
-Cindy 内部而拒绝重启,或因目标 userData 被其他 checkout 占用而中止,不要换命令绕过,
-应把提示交给用户。
+实例不受影响。必须尊重宿主提供的并行或保活工作流。脚本只在宿主是**当前 checkout**
+的 desktop dev 时拒绝重启(杀掉宿主会连这次启动一起收掉)。宿主是正式版或另一个
+worktree 时可以起隔离沙箱;从另一个 checkout 的 desktop dev 里起共享实例仍会拒绝,
+避免两份进程抢同一份正式 profile。若因当前 checkout 宿主拒绝、或目标 userData 被其他
+checkout 占用而中止,不要换命令绕过,应把 verdict 交给用户。
## 可选启动参数
-两个 restart 命令都支持下列参数;**用户没提就不要主动加**(不带 = 共库 + 正常调度)。
-这些参数只对 dev 生效,不影响用户机器上的正式版。
+两个 restart 命令都支持下列参数。脚本本身不加这些旗标时仍是共库 + 正常调度(给人在
+终端里手跑)。**Agent 例外**见上一节:用户只说启动开发版时必须加
+`--isolated=@worktree`。这些参数只对 dev 生效,不影响用户机器上的正式版。
- `--region=cn|global`(默认 `global`):切换构建身份与仓内端点清单;中国大陆版
必须显式传 `--region=cn`,读取 `config/endpoint.json`。
-- `--isolated` / `--isolated=<名字>`:使用独立 userData 沙箱,数据库、登录态、会话、定时
+- `--isolated` / `--isolated=<名字>` / `--isolated=@worktree`:使用独立 userData 沙箱,数据库、登录态、会话、定时
任务与设备身份都与正式版彻底隔离(首次需重新登录);命名沙箱每个名字一条独立沙箱,
- 名字限 `A-Za-z0-9_-`、≤32 字符。用户说「独立数据库/隔离数据/沙箱启动/不要动正式版
- 数据」时用。**未合入主干的 migration 必须在 `--isolated` 沙箱里跑,不得连共享 userData**
+ 名字限 `A-Za-z0-9_-`、≤32 字符。`@worktree` 是保留名,按当前 checkout 目录派生沙箱名。
+ 用户说「独立数据库/隔离数据/沙箱启动/不要动正式版
+ 数据」时用;Agent 把「启动开发版」也落在这条路径。**未合入主干的 migration 必须在 `--isolated` 沙箱里跑,不得连共享 userData**
(见 [`database-and-migrations.md`](database-and-migrations.md))。沙箱(及任何 dev
userData 覆写)内不触发首登旧数据迁移(mToc):不探测老目录、不弹确认窗、不把正式
数据复制进沙箱。**`--isolated` 不得落在任一正式 profile 上**:显式 `XDT_USER_DATA_DIR`
diff --git a/scripts/__tests__/restart-desktop-remote.test.mjs b/scripts/__tests__/restart-desktop-remote.test.mjs
index 8c414937f9..cd62999b49 100644
--- a/scripts/__tests__/restart-desktop-remote.test.mjs
+++ b/scripts/__tests__/restart-desktop-remote.test.mjs
@@ -28,14 +28,34 @@ import {
parseWorktreePaths,
osascriptLaunchDarwinTerminalArgs,
waitForDesktopStartup,
+ shouldRefuseHostedRestart,
+ commandContainsPath,
+ inheritedUserDataBlocksNamedIsolation,
} from "../restart-desktop-remote.mjs";
import {
+ DESKTOP_DEV_VERDICT_PREFIX,
+ ISOLATED_RESTART_NEXT,
+ WORKTREE_ISOLATED_ARG,
+ buildDesktopDevVerdictFromFailure,
+ buildDesktopDevVerdictFromWhoami,
+ formatDesktopDevVerdict,
+ inferDesktopDevFailureCode,
+ isolationNameFromWorktree,
+ isolatedRestartNextCommand,
+ resolveIsolatedArg,
+ restartContextFromArgv,
+ shouldSuggestIsolatedNext,
+} from "../desktop-dev-verdict.mjs";
+import {
+ collectDesktopWhoamiReport,
identifyDesktopProcesses,
mergeDesktopInstanceRecords,
parseWorktreeEntries,
} from "../desktop-whoami.mjs";
import {
+ assertDesktopRestartStepSucceeded,
buildDesktopRestartSteps,
+ DesktopRestartStepError,
runDesktopRestart,
} from "../desktop-restart-runner.mjs";
@@ -239,6 +259,18 @@ test("env-only XDT_ISOLATED=1 derives the default sandbox, not the official prof
assert.equal(named, defaultIsolatedUserDataDir("review", "global"));
});
+test("isolated=@worktree derives the named sandbox from the checkout directory", () => {
+ const root = path.join("/repo", "cindy-local-ollama-models");
+ const name = isolationNameFromWorktree(root);
+ const target = resolveRestartTargetUserDataDir({
+ isolatedArg: "--isolated=@worktree",
+ selectedRegion: "global",
+ rootDir: root,
+ });
+ assert.match(name, /^local-ollama-models-[0-9a-f]{6}$/);
+ assert.equal(target, defaultIsolatedUserDataDir(name, "global"));
+});
+
test("invalid env isolation name falls back to the default sandbox", () => {
assert.equal(sanitizeIsolationName("../Cindy"), "");
assert.equal(sanitizeIsolationName("我的沙箱"), "");
@@ -710,3 +742,333 @@ test("devEnvPrefix passes native iOS dev switches to Electron", () => {
"CINDY_IOS_SIMULATOR_NATIVE_H264='1' CINDY_IOS_SIMULATOR_NATIVE_HID='1' ",
);
});
+
+test("formatDesktopDevVerdict prints a grepable ready block", () => {
+ const text = formatDesktopDevVerdict({
+ state: "ready",
+ mode: "isolated",
+ sandbox: "local-ollama",
+ root: "/repo/cindy-local-ollama",
+ commit: "abc123",
+ pid: 42,
+ region: "global",
+ });
+ assert.equal(
+ text,
+ [
+ `${DESKTOP_DEV_VERDICT_PREFIX}=ready`,
+ "mode=isolated",
+ "sandbox=local-ollama",
+ "root=/repo/cindy-local-ollama",
+ "commit=abc123",
+ "pid=42",
+ "region=global",
+ "",
+ ].join("\n"),
+ );
+});
+
+test("formatDesktopDevVerdict flattens failed messages and keeps next", () => {
+ const text = formatDesktopDevVerdict({
+ state: "failed",
+ code: "MIGRATION_POLICY",
+ message: "Shared Cindy userData cannot run\nmigration artifacts",
+ next: ISOLATED_RESTART_NEXT,
+ });
+ assert.match(text, new RegExp(`^${DESKTOP_DEV_VERDICT_PREFIX}=failed\\n`));
+ assert.match(text, /code=MIGRATION_POLICY/);
+ assert.match(text, /message=Shared Cindy userData cannot run migration artifacts/);
+ assert.match(text, /next=pnpm restart:desktop:remote -- --isolated=@worktree/);
+});
+
+test("isolationNameFromWorktree strips cindy-, adds a path digest, and stays within 32 chars", () => {
+ const named = isolationNameFromWorktree("/Users/dash/Code/Cindy/cindy-local-ollama-models");
+ assert.match(named, /^local-ollama-models-[0-9a-f]{6}$/);
+ assert.notEqual(
+ named,
+ isolationNameFromWorktree("/tmp/cindy-local-ollama-models"),
+ );
+ assert.match(
+ isolationNameFromWorktree("/tmp/cindy-desktop-dev-startup-verdict"),
+ /^desktop-dev-startup-verdi-[0-9a-f]{6}$/,
+ );
+ assert.match(isolationNameFromWorktree("/tmp/!!!"), /^worktree-[0-9a-f]{6}$/);
+ assert.ok(isolationNameFromWorktree(`/tmp/cindy-${"a".repeat(80)}`).length <= 32);
+});
+
+test("resolveIsolatedArg expands @worktree to a named sandbox", () => {
+ assert.match(
+ resolveIsolatedArg(WORKTREE_ISOLATED_ARG, "/repo/cindy-local-ollama-models"),
+ /^--isolated=local-ollama-models-[0-9a-f]{6}$/,
+ );
+ assert.equal(resolveIsolatedArg("--isolated=feature-a", "/repo/x"), "--isolated=feature-a");
+ assert.equal(resolveIsolatedArg("--isolated", "/repo/x"), "--isolated");
+});
+
+test("shouldRefuseHostedRestart blocks same-checkout hosts and other-checkout shared starts", () => {
+ const own = "/repo/cindy-feature";
+ const other = "/repo/cindy-other";
+ assert.equal(
+ shouldRefuseHostedRestart(
+ { pid: 10, command: `electron-forge start ${own}` },
+ { preserveRunning: false, ownRootDir: own, isolated: true },
+ ),
+ true,
+ );
+ assert.equal(
+ shouldRefuseHostedRestart(
+ { pid: 10, command: `electron-forge start ${other}` },
+ { preserveRunning: false, ownRootDir: own, isolated: true },
+ ),
+ false,
+ );
+ assert.equal(
+ shouldRefuseHostedRestart(
+ { pid: 10, command: `electron-forge start ${other}` },
+ { preserveRunning: false, ownRootDir: own, isolated: false },
+ ),
+ true,
+ );
+ assert.equal(
+ shouldRefuseHostedRestart(
+ { pid: 10, command: `electron-forge start ${own}` },
+ { preserveRunning: true, ownRootDir: own },
+ ),
+ false,
+ );
+ assert.equal(
+ shouldRefuseHostedRestart(null, { preserveRunning: false, ownRootDir: own }),
+ false,
+ );
+});
+
+test("whoami match becomes a ready verdict", () => {
+ const root = path.resolve("/repo/cindy-preview");
+ const verdict = buildDesktopDevVerdictFromWhoami({
+ match: true,
+ expected: { rootDir: root, commit: "abc123" },
+ instances: [{
+ pid: 99,
+ rootDir: root,
+ ready: true,
+ commitVerified: true,
+ commit: "abc123",
+ isolated: true,
+ region: "global",
+ }],
+ }, { isolated: true, sandbox: "preview" });
+ assert.deepEqual(verdict, {
+ state: "ready",
+ mode: "isolated",
+ sandbox: "preview",
+ root,
+ commit: "abc123",
+ pid: 99,
+ region: "global",
+ });
+});
+
+test("whoami mismatch on shared start suggests isolated retry", () => {
+ const root = path.resolve("/repo/cindy-preview");
+ const verdict = buildDesktopDevVerdictFromWhoami({
+ match: false,
+ expected: { rootDir: root, commit: "abc123" },
+ instances: [],
+ }, { isolated: false });
+ assert.equal(verdict.state, "failed");
+ assert.equal(verdict.code, "WHOAMI_MISMATCH");
+ assert.equal(verdict.next, ISOLATED_RESTART_NEXT);
+});
+
+test("shared migration policy failure keeps an isolated next command", () => {
+ const verdict = buildDesktopDevVerdictFromFailure(
+ new Error("Shared Cindy userData cannot run migration artifacts that are not canonical on origin/main."),
+ { isolated: false, rootDir: "/repo/cindy-feature" },
+ );
+ assert.equal(verdict.state, "failed");
+ assert.equal(verdict.code, "MIGRATION_POLICY");
+ assert.equal(verdict.next, ISOLATED_RESTART_NEXT);
+ assert.equal(verdict.root, "/repo/cindy-feature");
+});
+
+test("isolated failures do not suggest another isolated start", () => {
+ assert.equal(shouldSuggestIsolatedNext({ isolated: true, code: "MIGRATE_FAILED" }), false);
+ const verdict = buildDesktopDevVerdictFromFailure(
+ Object.assign(new Error("[MIGRATE_FAILED] applied identity changed"), {
+ startupStatus: { code: "MIGRATE_FAILED", message: "applied identity changed" },
+ }),
+ { isolated: true, sandbox: "feature" },
+ );
+ assert.equal(verdict.code, "MIGRATE_FAILED");
+ assert.equal(verdict.next, undefined);
+ assert.equal(verdict.mode, "isolated");
+});
+
+test("inferDesktopDevFailureCode reads tagged startup failures", () => {
+ assert.equal(inferDesktopDevFailureCode("[SINGLE_INSTANCE_OWNED] owned"), "SINGLE_INSTANCE_OWNED");
+ assert.equal(
+ inferDesktopDevFailureCode("Desktop dev did not finish window/auth/database startup within 120s."),
+ "STARTUP_TIMEOUT",
+ );
+});
+
+test("collectDesktopWhoamiReport can be built from injected process facts", () => {
+ const root = path.resolve("/repo/cindy-preview");
+ const report = collectDesktopWhoamiReport({
+ rootDir: root,
+ commit: "abc123",
+ worktrees: [{ rootDir: root, branch: "dash/preview" }],
+ processes: [],
+ scanned: [{
+ pid: 10,
+ rootDir: root,
+ branch: "dash/preview",
+ state: "ready",
+ ready: true,
+ mode: "remote",
+ passive: true,
+ isolated: null,
+ userDataDir: "/tmp/Cindy",
+ commit: null,
+ commitVerified: false,
+ source: "process-scan",
+ }],
+ records: [{
+ schemaVersion: 1,
+ pid: 10,
+ rootDir: root,
+ state: "ready",
+ mode: "remote",
+ region: "global",
+ passive: true,
+ isolated: false,
+ userDataDir: "/tmp/Cindy",
+ commit: "abc123",
+ startedAtMs: 1,
+ updatedAtMs: 2,
+ }],
+ });
+ assert.equal(report.match, true);
+ assert.equal(buildDesktopDevVerdictFromWhoami(report).state, "ready");
+});
+
+test("isolatedRestartNextCommand keeps region and local mode", () => {
+ assert.equal(isolatedRestartNextCommand(), ISOLATED_RESTART_NEXT);
+ assert.equal(
+ isolatedRestartNextCommand({ region: "cn" }),
+ "pnpm restart:desktop:remote --region=cn -- --isolated=@worktree",
+ );
+ assert.equal(
+ isolatedRestartNextCommand({ local: true }),
+ "pnpm restart:desktop:local -- --isolated=@worktree",
+ );
+ const verdict = buildDesktopDevVerdictFromFailure(
+ new Error("Shared Cindy userData cannot run migration artifacts that are not canonical on origin/main."),
+ { isolated: false, region: "cn" },
+ );
+ assert.equal(verdict.next, "pnpm restart:desktop:remote --region=cn -- --isolated=@worktree");
+});
+
+test("host identity uses the same conservative path match as kill", () => {
+ const own = "/repo/cindy-feature";
+ assert.equal(commandContainsPath(`electron-forge start ${own} --isolated=feature`, own), false);
+ assert.equal(commandContainsPath(`${own}/node_modules/electron`, own), true);
+ assert.equal(
+ shouldRefuseHostedRestart(
+ { pid: 10, command: `${own}/node_modules/electron` },
+ { preserveRunning: false, ownRootDir: own, isolated: true },
+ ),
+ true,
+ );
+ assert.equal(
+ shouldRefuseHostedRestart(
+ { pid: 10, command: `${own} extra/node_modules/electron` },
+ { preserveRunning: false, ownRootDir: own, isolated: true },
+ ),
+ false,
+ );
+});
+
+test("hosted restart sees XDT_ISOLATED as isolation intent", () => {
+ const own = "/repo/cindy-feature";
+ const other = "/repo/cindy-other/node_modules/electron";
+ assert.equal(
+ shouldRefuseHostedRestart(
+ { pid: 10, command: other },
+ { preserveRunning: false, ownRootDir: own, isolated: true },
+ ),
+ false,
+ );
+});
+
+test("restartContextFromArgv reads --region cn and XDT_ISOLATED", () => {
+ assert.equal(restartContextFromArgv(["--region", "cn"]).region, "cn");
+ assert.equal(restartContextFromArgv([], { XDT_ISOLATED: "1" }).isolated, true);
+ assert.equal(
+ buildDesktopDevVerdictFromFailure(new Error("WHOAMI_MISMATCH"), {
+ ...restartContextFromArgv(["--region", "cn"]),
+ }).next,
+ "pnpm restart:desktop:remote --region=cn -- --isolated=@worktree",
+ );
+});
+
+test("worktree sandbox hash follows the foldCase option from the volume", () => {
+ assert.equal(
+ isolationNameFromWorktree("/repo/Foo/cindy-feature", { foldCase: true }),
+ isolationNameFromWorktree("/repo/foo/cindy-feature", { foldCase: true }),
+ );
+ assert.notEqual(
+ isolationNameFromWorktree("/repo/Foo/cindy-feature", { foldCase: false }),
+ isolationNameFromWorktree("/repo/foo/cindy-feature", { foldCase: false }),
+ );
+});
+
+test("named isolated does not keep another checkout's inherited userData dir", () => {
+ const derived = defaultIsolatedUserDataDir("local-ollama-models-abc123", "global");
+ assert.equal(
+ inheritedUserDataBlocksNamedIsolation(
+ "--isolated=local-ollama-models-abc123",
+ defaultIsolatedUserDataDir("other-sandbox", "global"),
+ derived,
+ ),
+ true,
+ );
+ assert.equal(
+ inheritedUserDataBlocksNamedIsolation("--isolated=local-ollama-models-abc123", derived, derived),
+ false,
+ );
+ assert.equal(
+ inheritedUserDataBlocksNamedIsolation("--isolated", defaultIsolatedUserDataDir("other-sandbox", "global"), derived),
+ false,
+ );
+ assert.equal(
+ inheritedUserDataBlocksNamedIsolation("--isolated=local-ollama-models-abc123", "/custom/profile", derived),
+ false,
+ );
+});
+
+test("assertDesktopRestartStepSucceeded throws so runner can print a verdict", () => {
+ assert.throws(
+ () => assertDesktopRestartStepSucceeded(
+ { label: "verify desktop dependencies", args: ["ensure-deps.mjs"] },
+ { status: 1 },
+ ),
+ (error) => error instanceof DesktopRestartStepError
+ && error.alreadyHasVerdict === false
+ && error.exitCode === 1,
+ );
+ assert.throws(
+ () => assertDesktopRestartStepSucceeded(
+ { label: "start desktop and wait for readiness", args: ["restart.mjs", "--wait-ready"] },
+ { status: 2 },
+ ),
+ (error) => error instanceof DesktopRestartStepError && error.alreadyHasVerdict === true,
+ );
+ assert.throws(
+ () => assertDesktopRestartStepSucceeded(
+ { label: "stop existing desktop dev processes", args: ["restart.mjs", "--kill-only"] },
+ { status: 1 },
+ ),
+ (error) => error instanceof DesktopRestartStepError && error.alreadyHasVerdict === true,
+ );
+});
diff --git a/scripts/desktop-dev-verdict.mjs b/scripts/desktop-dev-verdict.mjs
new file mode 100644
index 0000000000..6167c494dd
--- /dev/null
+++ b/scripts/desktop-dev-verdict.mjs
@@ -0,0 +1,193 @@
+import { createHash } from 'node:crypto';
+import path from 'node:path';
+import { resolveDesktopDevRegion } from './shared/desktop-dev-region.mjs';
+
+export const DESKTOP_DEV_VERDICT_PREFIX = 'DESKTOP_DEV_VERDICT';
+export const WORKTREE_ISOLATED_ARG = '--isolated=@worktree';
+const WORKTREE_NAME_DIGEST_LEN = 6;
+
+const VERDICT_FIELDS = Object.freeze([
+ 'code',
+ 'mode',
+ 'sandbox',
+ 'root',
+ 'commit',
+ 'pid',
+ 'region',
+ 'message',
+ 'next',
+]);
+
+const SHARED_FAILURE_CODES_WITH_ISOLATED_NEXT = new Set([
+ 'MIGRATION_POLICY',
+ 'PRESERVE_RUNNING_INCOMPATIBLE',
+ 'STARTUP_TIMEOUT',
+ 'MIGRATE_FAILED',
+ 'WHOAMI_MISMATCH',
+ 'STARTUP_FAILED',
+ 'DEV_PROCESS_EXITED',
+ 'AUTH_INIT_FAILED',
+ 'HOSTED_SHARED_REFUSED',
+]);
+
+function normalizeRoot(value) {
+ return path.resolve(value).replaceAll('\\', '/').toLowerCase();
+}
+
+function worktreeHashKey(rootDir, foldCase) {
+ const resolved = path.resolve(rootDir).replaceAll('\\', '/');
+ return foldCase ? resolved.toLowerCase() : resolved;
+}
+
+function singleLine(value) {
+ return String(value).replace(/\s+/g, ' ').trim();
+}
+
+export function isolationNameFromWorktree(rootDir, { foldCase } = {}) {
+ const resolved = path.resolve(rootDir);
+ let name = path.basename(resolved);
+ name = name.replace(/^cindy-/i, '');
+ name = name.replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '');
+ if (!name) name = 'worktree';
+ const shouldFold = foldCase ?? process.platform !== 'linux';
+ const digest = createHash('sha256')
+ .update(worktreeHashKey(resolved, shouldFold))
+ .digest('hex')
+ .slice(0, WORKTREE_NAME_DIGEST_LEN);
+ const maxBase = 32 - 1 - digest.length;
+ const base = name.slice(0, maxBase).replace(/-+$/g, '') || 'wt';
+ return `${base}-${digest}`;
+}
+
+export function isolatedRestartNextCommand({ local = false, region } = {}) {
+ const script = local ? 'restart:desktop:local' : 'restart:desktop:remote';
+ const regionArg = region && region !== 'global' ? ` --region=${region}` : '';
+ return `pnpm ${script}${regionArg} -- --isolated=@worktree`;
+}
+
+export const ISOLATED_RESTART_NEXT = isolatedRestartNextCommand();
+
+export function restartContextFromArgv(argv = [], env = process.env) {
+ let region;
+ try {
+ region = resolveDesktopDevRegion(argv, env);
+ } catch {
+ region = undefined;
+ }
+ return {
+ isolated: argv.some((arg) => arg === '--isolated' || arg.startsWith('--isolated='))
+ || env.XDT_ISOLATED === '1',
+ local: argv.includes('--local'),
+ region,
+ };
+}
+
+export function resolveIsolatedArg(isolatedArg, rootDir, options) {
+ if (isolatedArg === WORKTREE_ISOLATED_ARG) {
+ return `--isolated=${isolationNameFromWorktree(rootDir, options)}`;
+ }
+ return isolatedArg;
+}
+
+export function shouldSuggestIsolatedNext({ isolated, code } = {}) {
+ return !isolated && SHARED_FAILURE_CODES_WITH_ISOLATED_NEXT.has(code);
+}
+
+export function inferDesktopDevFailureCode(message) {
+ const text = String(message ?? '');
+ const tagged = text.match(/\[([A-Z][A-Z0-9_]*)\]/);
+ if (tagged) return tagged[1];
+ if (/cannot run migration artifacts/i.test(text)) return 'MIGRATION_POLICY';
+ if (/already in use by another checkout/i.test(text)) return 'USERDATA_IN_USE';
+ if (/cannot share official userData while hosted/i.test(text)) return 'HOSTED_SHARED_REFUSED';
+ if (/Refusing to restart from within|running inside an Cindy desktop dev process tree/i.test(text)) {
+ return 'HOSTED_RESTART_REFUSED';
+ }
+ if (/--preserve-running cannot/i.test(text)) return 'PRESERVE_RUNNING_INCOMPATIBLE';
+ if (/--isolated cannot use the official/i.test(text)) return 'ISOLATED_OFFICIAL_PROFILE';
+ if (/did not finish window\/auth\/database startup/i.test(text)) return 'STARTUP_TIMEOUT';
+ if (/Invalid --isolated name/i.test(text)) return 'INVALID_ISOLATED_NAME';
+ if (/root\/commit\/ready did not match|Desktop dev process is not running/i.test(text)) {
+ return 'WHOAMI_MISMATCH';
+ }
+ if (/failed with exit/i.test(text)) return 'STARTUP_FAILED';
+ return 'STARTUP_FAILED';
+}
+
+export function formatDesktopDevVerdict(verdict) {
+ const state = verdict?.state === 'ready' ? 'ready' : 'failed';
+ const lines = [`${DESKTOP_DEV_VERDICT_PREFIX}=${state}`];
+ for (const key of VERDICT_FIELDS) {
+ const value = verdict?.[key];
+ if (value == null || value === '') continue;
+ lines.push(`${key}=${singleLine(value)}`);
+ }
+ return `${lines.join('\n')}\n`;
+}
+
+export function printDesktopDevVerdict(verdict, writer = console.log) {
+ writer(formatDesktopDevVerdict(verdict).trimEnd());
+}
+
+function isolatedNextIfNeeded(context, code) {
+ return shouldSuggestIsolatedNext({ isolated: context.isolated, code })
+ ? { next: isolatedRestartNextCommand(context) }
+ : {};
+}
+
+export function buildDesktopDevVerdictFromWhoami(report, context = {}) {
+ const expectedRoot = report?.expected?.rootDir;
+ const expectedCommit = report?.expected?.commit ?? null;
+ const instances = Array.isArray(report?.instances) ? report.instances : [];
+ const matched = instances.find((instance) =>
+ expectedRoot
+ && normalizeRoot(instance.rootDir) === normalizeRoot(expectedRoot)
+ && instance.ready === true
+ && instance.commitVerified === true
+ && instance.commit === expectedCommit);
+
+ if (report?.match && matched) {
+ return {
+ state: 'ready',
+ mode: matched.isolated === true || context.isolated ? 'isolated' : 'shared',
+ ...(context.sandbox ? { sandbox: context.sandbox } : {}),
+ root: expectedRoot,
+ commit: expectedCommit,
+ pid: matched.pid,
+ ...(matched.region ? { region: matched.region } : {}),
+ };
+ }
+
+ const code = 'WHOAMI_MISMATCH';
+ return {
+ state: 'failed',
+ code,
+ message: instances.length === 0
+ ? 'Desktop dev process is not running for this checkout.'
+ : 'Desktop dev is running but root/commit/ready did not match this checkout.',
+ mode: context.isolated ? 'isolated' : 'shared',
+ ...(context.sandbox ? { sandbox: context.sandbox } : {}),
+ root: expectedRoot,
+ commit: expectedCommit,
+ ...isolatedNextIfNeeded(context, code),
+ };
+}
+
+export function buildDesktopDevVerdictFromFailure(error, context = {}) {
+ const status = error?.startupStatus && typeof error.startupStatus === 'object'
+ ? error.startupStatus
+ : null;
+ const message = status?.message
+ || (error instanceof Error ? error.message : String(error ?? 'Desktop dev failed to start'));
+ const code = context.code
+ || (typeof status?.code === 'string' ? status.code : inferDesktopDevFailureCode(message));
+ return {
+ state: 'failed',
+ code,
+ message,
+ mode: context.isolated ? 'isolated' : 'shared',
+ ...(context.sandbox ? { sandbox: context.sandbox } : {}),
+ ...(context.rootDir ? { root: context.rootDir } : {}),
+ ...isolatedNextIfNeeded(context, code),
+ };
+}
diff --git a/scripts/desktop-restart-runner.mjs b/scripts/desktop-restart-runner.mjs
index 9a12d97f8c..107436b307 100644
--- a/scripts/desktop-restart-runner.mjs
+++ b/scripts/desktop-restart-runner.mjs
@@ -4,6 +4,11 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { assertSharedDevMigrationPolicy } from './dev-migration-policy.mjs';
+import {
+ buildDesktopDevVerdictFromFailure,
+ printDesktopDevVerdict,
+ restartContextFromArgv,
+} from './desktop-dev-verdict.mjs';
const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -51,18 +56,39 @@ export function buildDesktopRestartSteps(argv, root = rootDir) {
];
}
+export class DesktopRestartStepError extends Error {
+ constructor(message, { alreadyHasVerdict = false, exitCode = 1 } = {}) {
+ super(message);
+ this.name = 'DesktopRestartStepError';
+ this.alreadyHasVerdict = alreadyHasVerdict;
+ this.exitCode = exitCode;
+ }
+}
+
+export function assertDesktopRestartStepSucceeded(step, result) {
+ if (result?.error) throw result.error;
+ if (result?.signal) {
+ throw new DesktopRestartStepError(`${step.label} terminated by ${result.signal}`);
+ }
+ if ((result?.status ?? 0) !== 0) {
+ throw new DesktopRestartStepError(
+ `${step.label} failed with exit ${result.status ?? 1}`,
+ {
+ alreadyHasVerdict: Array.isArray(step.args)
+ && (step.args.includes('--wait-ready') || step.args.includes('--kill-only')),
+ exitCode: result.status ?? 1,
+ },
+ );
+ }
+}
+
function runStep(step) {
const result = spawnSync(step.command, step.args, {
cwd: rootDir,
env: process.env,
stdio: 'inherit',
});
- if (result.error) throw result.error;
- if (result.signal) {
- process.kill(process.pid, result.signal);
- return;
- }
- if (result.status !== 0) process.exit(result.status ?? 1);
+ assertDesktopRestartStepSucceeded(step, result);
}
export function runDesktopRestart(argv, root = rootDir, stepRunner = runStep) {
@@ -71,14 +97,21 @@ export function runDesktopRestart(argv, root = rootDir, stepRunner = runStep) {
}
function main() {
- runDesktopRestart(process.argv.slice(2));
-}
-
-if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const argv = process.argv.slice(2);
try {
- main();
+ runDesktopRestart(argv);
} catch (error) {
+ if (!error?.alreadyHasVerdict) {
+ printDesktopDevVerdict(buildDesktopDevVerdictFromFailure(error, {
+ rootDir,
+ ...restartContextFromArgv(argv),
+ }));
+ }
console.error(error instanceof Error ? error.message : String(error));
- process.exit(1);
+ process.exit(error?.exitCode ?? 1);
}
}
+
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ main();
+}
diff --git a/scripts/desktop-whoami.mjs b/scripts/desktop-whoami.mjs
index 7b15495c2a..1008dee4b9 100644
--- a/scripts/desktop-whoami.mjs
+++ b/scripts/desktop-whoami.mjs
@@ -8,6 +8,10 @@ import {
desktopUserDataDirNameForRegion,
resolveDesktopDevRegion,
} from './shared/desktop-dev-region.mjs';
+import {
+ buildDesktopDevVerdictFromWhoami,
+ printDesktopDevVerdict,
+} from './desktop-dev-verdict.mjs';
const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
@@ -53,11 +57,11 @@ export function parseWorktreeEntries(text) {
return entries;
}
-function repositoryWorktrees() {
- const result = run('git', ['worktree', 'list', '--porcelain']);
- if (result.status !== 0) return [{ rootDir, branch: null }];
+function repositoryWorktrees(cwd = rootDir) {
+ const result = run('git', ['worktree', 'list', '--porcelain'], { cwd });
+ if (result.status !== 0) return [{ rootDir: path.resolve(cwd), branch: null }];
const entries = parseWorktreeEntries(result.stdout);
- return entries.length > 0 ? entries : [{ rootDir, branch: null }];
+ return entries.length > 0 ? entries : [{ rootDir: path.resolve(cwd), branch: null }];
}
function listProcesses() {
@@ -315,36 +319,48 @@ function printText(report) {
}
}
-function main() {
- const options = parseArgs(process.argv.slice(2));
- const region = resolveDesktopDevRegion([], process.env);
- const worktrees = repositoryWorktrees();
- const processes = listProcesses();
- const preliminary = identifyDesktopProcesses(processes, worktrees);
+export function collectDesktopWhoamiReport(options = {}) {
+ const expectedRoot = path.resolve(options.rootDir ?? rootDir);
+ const env = options.env ?? process.env;
+ const region = resolveDesktopDevRegion([], env);
+ const worktrees = options.worktrees ?? repositoryWorktrees(expectedRoot);
+ const processes = options.processes ?? listProcesses();
+ const preliminary = options.scanned ?? identifyDesktopProcesses(processes, worktrees);
const userDataDirs = new Set([
- path.resolve(options.userDataDir ?? process.env.XDT_USER_DATA_DIR ?? defaultUserDataDir(region)),
+ path.resolve(options.userDataDir ?? env.XDT_USER_DATA_DIR ?? defaultUserDataDir(region)),
...preliminary.map((item) => item.userDataDir).filter(Boolean).map((item) => path.resolve(item)),
]);
- const scanned = preliminary;
- const records = readInstanceRecords(userDataDirs, worktrees);
- const allInstances = mergeDesktopInstanceRecords(scanned, records, worktrees);
- const expectedCommit = gitHead(rootDir);
+ const records = options.records ?? readInstanceRecords(userDataDirs, worktrees);
+ const allInstances = mergeDesktopInstanceRecords(preliminary, records, worktrees);
+ const expectedCommit = options.commit === undefined ? gitHead(expectedRoot) : options.commit;
const match = allInstances.some((instance) =>
- normalize(instance.rootDir) === normalize(rootDir) &&
+ normalize(instance.rootDir) === normalize(expectedRoot) &&
instance.ready &&
instance.commitVerified &&
instance.commit === expectedCommit);
- const report = {
+ return {
schemaVersion: 1,
- expected: { rootDir, commit: expectedCommit },
+ expected: { rootDir: expectedRoot, commit: expectedCommit },
match,
instances: options.all
? allInstances
- : allInstances.filter((instance) => normalize(instance.rootDir) === normalize(rootDir)),
+ : allInstances.filter((instance) => normalize(instance.rootDir) === normalize(expectedRoot)),
};
- if (options.json) console.log(JSON.stringify(report, null, 2));
- else printText(report);
- process.exitCode = match ? 0 : 1;
+}
+
+function main() {
+ const options = parseArgs(process.argv.slice(2));
+ const report = collectDesktopWhoamiReport({
+ all: options.all,
+ userDataDir: options.userDataDir,
+ });
+ const verdict = buildDesktopDevVerdictFromWhoami(report);
+ if (options.json) console.log(JSON.stringify({ ...report, verdict }, null, 2));
+ else {
+ printText(report);
+ printDesktopDevVerdict(verdict);
+ }
+ process.exitCode = verdict.state === 'ready' ? 0 : 1;
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
diff --git a/scripts/restart-desktop-remote.mjs b/scripts/restart-desktop-remote.mjs
index d1fbd9ab1a..8292842f5f 100644
--- a/scripts/restart-desktop-remote.mjs
+++ b/scripts/restart-desktop-remote.mjs
@@ -10,6 +10,14 @@ import {
desktopUserDataDirNameForRegion,
resolveDesktopDevRegion,
} from './shared/desktop-dev-region.mjs';
+import {
+ buildDesktopDevVerdictFromFailure,
+ buildDesktopDevVerdictFromWhoami,
+ printDesktopDevVerdict,
+ resolveIsolatedArg,
+ restartContextFromArgv,
+} from './desktop-dev-verdict.mjs';
+import { collectDesktopWhoamiReport } from './desktop-whoami.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const rootDir = path.resolve(__dirname, '..');
@@ -112,8 +120,9 @@ export function commandContainsPath(command, candidatePath) {
const before = normalizedCommand[index - 1];
const after = normalizedCommand[index + normalizedPath.length];
const hasStartBoundary = before === undefined || /\s|["'=]/.test(before);
- // 命令行字符串无法安全区分裸 root 参数后接参数,和带空格的 sibling 路径。
- // kill 旧进程宁可漏杀也不能误杀其它 checkout,所以这里不把空格当结束边界。
+ // 命令行无法安全区分「裸 root 后接参数」和「带空格的 sibling 路径」。
+ // 空格当结束边界会误伤 sibling;不当结束会漏认裸路径。desktop-dev 命令行里
+ // checkout 都以 /node_modules 或 /apps/desktop 出现,保守匹配足够。
const hasEndBoundary = after === undefined || after === '/' || after === '"' || after === "'";
if (hasStartBoundary && hasEndBoundary) return true;
index = normalizedCommand.indexOf(normalizedPath, index + 1);
@@ -324,10 +333,9 @@ function hasRepositoryCheckoutPath(command, checkoutPaths = repositoryWorktreePa
}
// 沿 ppid 链向上找祖先里有没有 Cindy desktop dev 进程。
-// 用途:拦住"agent 跑在 Cindy desktop dev 进程内还调 restart"这种自杀场景——
-// 一旦 taskkill /T 走到祖先 dev 进程,整棵树(包括正在跑的本脚本)都会被收掉,
-// 新 cmd 要么没机会起、要么撞上未释放的端口/文件锁,结果是看不懂的 ELIFECYCLE。
-// 检测到就直接 exit 1 + 清晰提示,让 agent 把控制权交回给开发者。
+// 用途:拦住"agent 跑在【当前 checkout】的 desktop dev 里还调 restart"这种自杀场景——
+// kill 作用域虽已限本 checkout,但祖先就是这份 checkout 时仍会把本脚本一起收掉。
+// 宿主是正式版或另一个 worktree 时不拦:杀不到那份祖先,隔离启动可以继续。
function findDevAncestor() {
const processes = process.platform === 'win32' ? listWindowsProcesses() : listPosixProcesses();
const byPid = new Map(processes.map((proc) => [proc.pid, proc]));
@@ -507,6 +515,18 @@ export function sanitizeIsolationName(raw) {
return ISOLATION_NAME_RE.test(name) ? name : '';
}
+export function looksLikeCindyManagedUserDataDir(dir) {
+ const base = path.basename(path.resolve(dir));
+ return /^(Cindy|CindyGlobal|CindyDev)(?:-dev2(?:-[A-Za-z0-9_-]+)?)?$/i.test(base);
+}
+
+/** Named `--isolated=<name>` must not inherit another Cindy profile. Custom dirs stay. */
+export function inheritedUserDataBlocksNamedIsolation(isolatedArg, envUserDataDir, derivedDir) {
+ if (!envUserDataDir || !isolatedArg || !isolatedArg.includes('=')) return false;
+ if (!looksLikeCindyManagedUserDataDir(envUserDataDir)) return false;
+ return canonicalizeUserDataDir(envUserDataDir) !== canonicalizeUserDataDir(derivedDir);
+}
+
function volumeIsCaseInsensitive(existingDir) {
let dir = existingDir;
for (;;) {
@@ -536,6 +556,15 @@ function volumeIsCaseInsensitive(existingDir) {
}
}
+function foldCaseOption(dir) {
+ try {
+ fs.statSync(dir);
+ return { foldCase: volumeIsCaseInsensitive(dir) };
+ } catch {
+ return {};
+ }
+}
+
export function canonicalizeUserDataDir(dir) {
const resolved = path.resolve(dir);
try {
@@ -574,17 +603,46 @@ export function resolveRestartTargetUserDataDir({
isolatedEnv,
isolatedName,
selectedRegion,
+ rootDir: targetRoot = rootDir,
}) {
+ const resolvedIsolatedArg = resolveIsolatedArg(isolatedArg, targetRoot, foldCaseOption(targetRoot));
const isolationName = sanitizeIsolationName(
- isolatedArg ? parseIsolationName(isolatedArg) : isolatedName,
+ resolvedIsolatedArg ? parseIsolationName(resolvedIsolatedArg) : isolatedName,
);
- const isolated = Boolean(isolatedArg) || isolatedEnv === '1';
+ const isolated = Boolean(resolvedIsolatedArg) || isolatedEnv === '1';
return envUserDataDir
|| (isolated
? defaultIsolatedUserDataDir(isolationName, selectedRegion)
: productionUserDataDir(selectedRegion));
}
+/**
+ * Refuse when restarting would suicide this checkout's host, or when a shared
+ * start is hosted by another checkout's desktop-dev (same official profile).
+ * Isolated start from another checkout is safe: kill scope is ownRootDir.
+ */
+export function shouldRefuseHostedRestart(ancestor, {
+ preserveRunning,
+ ownRootDir,
+ isolated = false,
+}) {
+ if (!ancestor || preserveRunning) return false;
+ if (commandContainsPath(ancestor.command, ownRootDir)) return true;
+ return isolated !== true;
+}
+
+export function hostedRestartRefusal(ancestor, { ownRootDir }) {
+ return commandContainsPath(ancestor.command, ownRootDir)
+ ? {
+ code: 'HOSTED_RESTART_REFUSED',
+ message: "Refusing to restart from within this checkout's desktop dev process tree.",
+ }
+ : {
+ code: 'HOSTED_SHARED_REFUSED',
+ message: 'Cannot share official userData while hosted by another checkout desktop dev.',
+ };
+}
+
export function defaultIsolatedUserDataDir(isolationName, region = 'global') {
// 目录纪元 v2(-dev2),与 devCliFlags.ts 的派生保持一字不差:#871 起隔离沙箱用
// CindyDev 钥匙串身份,旧 -dev 目录留给旧 checkout(#912 review)。
@@ -769,7 +827,9 @@ function launchInSystemTerminal(mode) {
stdio: 'inherit',
windowsHide: false,
});
- if (result.status !== 0) process.exit(result.status ?? 1);
+ if (result.status !== 0) {
+ throw new Error(`Failed to open cmd window (exit ${result.status ?? 1})`);
+ }
console.log(`==> Opened desktop ${mode} dev in a new cmd window.`);
return;
}
@@ -782,8 +842,7 @@ function launchInSystemTerminal(mode) {
});
child.unref();
if (child.pid === undefined) {
- console.error('Failed to open Terminal.app');
- process.exit(1);
+ throw new Error('Failed to open Terminal.app');
}
console.log(`==> Opened desktop ${mode} dev in a new Terminal window.`);
return;
@@ -809,6 +868,8 @@ function startDesktopDev(mode) {
});
child.on('exit', (code, signal) => {
+ // --wait-ready owns the process exit so it can print DESKTOP_DEV_VERDICT.
+ if (process.env.XDT_DESKTOP_DEV_STARTUP_STATUS_FILE) return;
if (signal) process.kill(process.pid, signal);
process.exit(code ?? 0);
});
@@ -857,6 +918,11 @@ function writeDesktopStartupStatus(statusPath, status) {
}
}
+function attachStartupFailure(error, status) {
+ error.startupStatus = status ?? null;
+ return error;
+}
+
export async function waitForDesktopStartup(statusPath, timeoutMs = startupReadyTimeoutMs) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
@@ -864,12 +930,15 @@ export async function waitForDesktopStartup(statusPath, timeoutMs = startupReady
if (status?.state === 'ready') {
console.log(`==> Desktop dev is ready (window + auth/local database, pid ${status.pid ?? 'unknown'}).`);
fs.rmSync(statusPath, { force: true });
- return;
+ return status;
}
if (status?.state === 'failed') {
fs.rmSync(statusPath, { force: true });
- throw new Error(
- `${formatDesktopStartupFailure(status)} Check the dev terminal, run \`pnpm desktop:whoami\`, and inspect apps/desktop/logs/.`,
+ throw attachStartupFailure(
+ new Error(
+ `${formatDesktopStartupFailure(status)} Check the dev terminal, run \`pnpm desktop:whoami\`, and inspect apps/desktop/logs/.`,
+ ),
+ status,
);
}
await sleep(pollIntervalMs);
@@ -877,8 +946,15 @@ export async function waitForDesktopStartup(statusPath, timeoutMs = startupReady
// Keep a tombstone so a late Electron startup signal cannot recreate a stale
// status file after this waiter has already reported timeout to its caller.
writeDesktopStartupStatus(statusPath, { state: 'abandoned', at: Date.now() });
- throw new Error(
- `Desktop dev did not finish window/auth/database startup within ${Math.round(timeoutMs / 1000)}s. Check the dev terminal and apps/desktop/logs/.`,
+ throw attachStartupFailure(
+ new Error(
+ `Desktop dev did not finish window/auth/database startup within ${Math.round(timeoutMs / 1000)}s. Check the dev terminal and apps/desktop/logs/.`,
+ ),
+ {
+ state: 'failed',
+ code: 'STARTUP_TIMEOUT',
+ message: `Desktop dev did not finish window/auth/database startup within ${Math.round(timeoutMs / 1000)}s.`,
+ },
);
}
@@ -893,7 +969,13 @@ export function applyDesktopStartupConfigForPhase(options) {
}
async function main() {
- const argv = process.argv.slice(2);
+ let argv = process.argv.slice(2);
+ const rawIsolatedArg = argv.find((arg) => arg === '--isolated' || arg.startsWith('--isolated='));
+ const isolatedArg = resolveIsolatedArg(rawIsolatedArg, rootDir, foldCaseOption(rootDir));
+ if (rawIsolatedArg && isolatedArg && isolatedArg !== rawIsolatedArg) {
+ argv = argv.map((arg) => (arg === rawIsolatedArg ? isolatedArg : arg));
+ console.log(`==> Isolated sandbox from worktree: ${parseIsolationName(isolatedArg)}`);
+ }
const killOnly = argv.includes('--kill-only');
const waitReady = argv.includes('--wait-ready');
const preserveRunning = argv.includes('--preserve-running');
@@ -905,7 +987,32 @@ async function main() {
const mode = argv.includes('--local') ? 'local' : 'remote';
const startupConfig = applyDesktopStartupConfigForPhase({ argv, mode });
const selectedRegion = startupConfig?.region ?? resolveDesktopDevRegion(argv, process.env);
- const isolatedArg = argv.find((a) => a === '--isolated' || a.startsWith('--isolated='));
+ if (isolatedArg && isolatedArg.includes('=')) {
+ const derivedDir = defaultIsolatedUserDataDir(parseIsolationName(isolatedArg), selectedRegion);
+ if (inheritedUserDataBlocksNamedIsolation(isolatedArg, process.env.XDT_USER_DATA_DIR, derivedDir)) {
+ delete process.env.XDT_USER_DATA_DIR;
+ delete process.env.XDT_USER_DATA_DIR_EPOCH;
+ delete process.env.XDT_DEVICE_ID_OVERRIDE;
+ delete process.env.XDT_ISOLATED_NAME;
+ console.log(`==> Ignoring inherited Cindy profile so --isolated=${parseIsolationName(isolatedArg)} can use its own sandbox.`);
+ }
+ }
+ const isolationName = isolatedArg ? parseIsolationName(isolatedArg) : '';
+ const verdictContext = {
+ rootDir,
+ isolated: Boolean(isolatedArg) || process.env.XDT_ISOLATED === '1',
+ sandbox: isolationName || undefined,
+ local: mode === 'local',
+ region: selectedRegion,
+ };
+ const exitWithFailure = (code, message, details = []) => {
+ for (const line of details) console.error(line);
+ printDesktopDevVerdict(buildDesktopDevVerdictFromFailure(new Error(message), {
+ ...verdictContext,
+ code,
+ }));
+ process.exit(1);
+ };
if (preserveRunning && killOnly) {
throw new Error('--preserve-running cannot be combined with the internal --kill-only stage');
}
@@ -971,15 +1078,15 @@ async function main() {
// ——服务端登录凭证按 (user, device) 一对一存,不派生的话沙箱登录会覆盖正式版
// 的续期凭证,同机互踢。
if (startupConfig && isolatedArg) {
- let isolationName = '';
- if (isolatedArg.includes('=')) {
- isolationName = isolatedArg.slice('--isolated='.length);
- // 名字白名单与主进程 devCliFlags 一致:目录跨平台安全 + deviceId 总长可控。
- if (!/^[A-Za-z0-9_-]{1,32}$/.test(isolationName)) {
- console.error(`==> Invalid --isolated name: "${isolationName}"`);
- console.error(' Allowed: letters / digits / _ / -, max 32 chars. e.g. --isolated=feature-a');
- process.exit(1);
- }
+ if (isolationName && !/^[A-Za-z0-9_-]{1,32}$/.test(isolationName)) {
+ exitWithFailure(
+ 'INVALID_ISOLATED_NAME',
+ `Invalid --isolated name: "${isolationName}"`,
+ [
+ `==> Invalid --isolated name: "${isolationName}"`,
+ ' Allowed: letters / digits / _ / -, max 32 chars. e.g. --isolated=feature-a',
+ ],
+ );
}
process.env.XDT_ISOLATED = '1';
if (isolationName) process.env.XDT_ISOLATED_NAME = isolationName;
@@ -999,8 +1106,11 @@ async function main() {
// 白名单透传,maker-host auth-adapters 消费(仅非 packaged 生效)。
if (startupConfig && argv.includes('--isolated-auth')) {
if (!isolatedArg) {
- console.error('==> --isolated-auth requires --isolated: 共享 userData 的实例不该单独隔离凭证');
- process.exit(1);
+ exitWithFailure(
+ 'INVALID_ISOLATED_NAME',
+ '--isolated-auth requires --isolated: shared userData must not isolate credentials alone',
+ ['==> --isolated-auth requires --isolated: 共享 userData 的实例不该单独隔离凭证'],
+ );
}
process.env.XDT_ISOLATED_AUTH = '1';
console.log('==> Isolated auth: this sandbox will NOT share codex OAuth credentials with ~/.codex.');
@@ -1008,16 +1118,28 @@ async function main() {
if (startupConfig) ensureDesktopEnv();
const devAncestor = findDevAncestor();
- if (devAncestor && !preserveRunning) {
- console.error('==> Detected this script is running inside an Cindy desktop dev process tree:');
- console.error(` ancestor pid ${devAncestor.pid}: ${devAncestor.command.slice(0, 180)}`);
- console.error('==> Refusing to restart from within. Killing the ancestor would terminate this');
- console.error(' script mid-flight and leave ports / file locks held by the dying process,');
- console.error(' causing the new electron-forge to fail with ELIFECYCLE.');
- console.error('==> Ask the user to restart from the terminal where they originally launched');
- console.error(` \`pnpm ${devScriptForMode(mode)}\` (Ctrl+C then re-run), or from any external shell`);
- console.error(' not spawned by the desktop dev tree.');
- process.exit(1);
+ if (shouldRefuseHostedRestart(devAncestor, {
+ preserveRunning,
+ ownRootDir: rootDir,
+ isolated: hasIsolationIntent(argv, process.env),
+ })) {
+ const refusal = hostedRestartRefusal(devAncestor, { ownRootDir: rootDir });
+ exitWithFailure(
+ refusal.code,
+ refusal.message,
+ [
+ `==> ${refusal.message}`,
+ ` ancestor pid ${devAncestor.pid}: ${devAncestor.command.slice(0, 180)}`,
+ refusal.code === 'HOSTED_RESTART_REFUSED'
+ ? '==> Ask the user to restart from the official Cindy app, another worktree, or an external terminal.'
+ : '==> Use --isolated=@worktree, or --preserve-running if you explicitly want shared login.',
+ ],
+ );
+ }
+ if (devAncestor && !preserveRunning && isolatedArg) {
+ console.log(
+ `==> Hosted by another checkout's desktop dev pid ${devAncestor.pid}; this isolated restart will not stop that host.`,
+ );
}
if (devAncestor && preserveRunning) {
if (replaceRunningRoot && commandContainsPath(devAncestor.command, replaceRunningRoot)) {
@@ -1069,13 +1191,16 @@ async function main() {
&& commandUsesUserDataDir(proc.command, targetUserDataDir),
);
if (conflicts.length > 0) {
- console.error(`==> Target userData is already in use by another checkout's dev instance: ${targetUserDataDir}`);
- for (const proc of conflicts) {
- console.error(` pid ${proc.pid}: ${proc.command.slice(0, 180)}`);
- }
- console.error('==> Refusing to stop processes outside this checkout. Pick a different sandbox');
- console.error(' name (--isolated=<name>), or stop that instance yourself and re-run.');
- process.exit(1);
+ exitWithFailure(
+ 'USERDATA_IN_USE',
+ `Target userData is already in use by another checkout's dev instance: ${targetUserDataDir}`,
+ [
+ `==> Target userData is already in use by another checkout's dev instance: ${targetUserDataDir}`,
+ ...conflicts.map((proc) => ` pid ${proc.pid}: ${proc.command.slice(0, 180)}`),
+ '==> Refusing to stop processes outside this checkout. Pick a different sandbox',
+ ' name (--isolated=<name>), or stop that instance yourself and re-run.',
+ ],
+ );
}
} else {
const compatibility = inspectSharedUserDataRegion(
@@ -1140,11 +1265,14 @@ async function main() {
matchesReplacementRoot,
);
if (remainingAfterForce.length > 0) {
- console.error(`==> Failed to stop ${remainingAfterForce.length} process(es) from ${replaceRunningRoot}; aborting restart.`);
- for (const target of remainingAfterForce) {
- console.error(` still running ${target.pid}: ${target.command.slice(0, 180)}`);
- }
- process.exit(1);
+ exitWithFailure(
+ 'STARTUP_FAILED',
+ `Failed to stop ${remainingAfterForce.length} process(es) from ${replaceRunningRoot}; aborting restart.`,
+ [
+ `==> Failed to stop ${remainingAfterForce.length} process(es) from ${replaceRunningRoot}; aborting restart.`,
+ ...remainingAfterForce.map((target) => ` still running ${target.pid}: ${target.command.slice(0, 180)}`),
+ ],
+ );
}
closeDarwinTerminalTtys(darwinTerminalTtys);
@@ -1172,11 +1300,14 @@ async function main() {
const remainingAfterForce = await waitForDesktopDevProcessesToExit(forceTimeoutMs, matchesOwnRoot);
if (remainingAfterForce.length > 0) {
- console.error(`==> Failed to stop ${remainingAfterForce.length} Cindy desktop dev process(es); aborting restart.`);
- for (const target of remainingAfterForce) {
- console.error(` still running ${target.pid}: ${target.command.slice(0, 180)}`);
- }
- process.exit(1);
+ exitWithFailure(
+ 'STARTUP_FAILED',
+ `Failed to stop ${remainingAfterForce.length} Cindy desktop dev process(es); aborting restart.`,
+ [
+ `==> Failed to stop ${remainingAfterForce.length} Cindy desktop dev process(es); aborting restart.`,
+ ...remainingAfterForce.map((target) => ` still running ${target.pid}: ${target.command.slice(0, 180)}`),
+ ],
+ );
}
closeDarwinTerminalTtys(darwinTerminalTtys);
@@ -1193,11 +1324,30 @@ async function main() {
process.env.XDT_DESKTOP_DEV_STARTUP_STATUS_FILE = startupStatusPath;
}
startDesktopDev(mode);
- if (startupStatusPath) await waitForDesktopStartup(startupStatusPath);
+ if (startupStatusPath) {
+ try {
+ await waitForDesktopStartup(startupStatusPath);
+ const report = collectDesktopWhoamiReport({
+ rootDir,
+ userDataDir: process.env.XDT_USER_DATA_DIR,
+ });
+ const verdict = buildDesktopDevVerdictFromWhoami(report, verdictContext);
+ printDesktopDevVerdict(verdict);
+ if (verdict.state !== 'ready') process.exit(1);
+ } catch (error) {
+ printDesktopDevVerdict(buildDesktopDevVerdictFromFailure(error, verdictContext));
+ console.error(error instanceof Error ? error.message : error);
+ process.exit(1);
+ }
+ }
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
main().catch((error) => {
+ printDesktopDevVerdict(buildDesktopDevVerdictFromFailure(error, {
+ rootDir,
+ ...restartContextFromArgv(process.argv.slice(2)),
+ }));
console.error(error);
process.exit(1);
});