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(desktop): 菜单「帮助」增加「安装到命令行」,对齐 VS Code 的 code 命令 (#1258)

mlboyc603932bb6a3
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index 9097e9c388..6e7acf9269 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -760,6 +760,12 @@ function extraResourcesForTarget(targetPlatform: string): string[] {
base.unshift(`resources/${UPDATER_EXE}`);
}
+ // macOS 「帮助 → 安装到命令行」symlink 的目标脚本(<App>/Contents/Resources/cli/cindy)。
+ // 仅 darwin 有此功能,其它平台不打进包。exec 位由 git 跟踪,extraResource 拷贝时保留。
+ if (targetPlatform === 'darwin') {
+ base.push('resources/cli');
+ }
+
return base;
}
diff --git a/apps/desktop/resources/cli/cindy b/apps/desktop/resources/cli/cindy
new file mode 100755
index 0000000000..07a9b8fd5c
--- /dev/null
+++ b/apps/desktop/resources/cli/cindy
@@ -0,0 +1,56 @@
+#!/bin/sh
+# Cindy 命令行启动器 —— 随 Cindy.app 分发,由「帮助 → 安装到命令行」symlink 到 PATH。
+# 用法: <命令名> [路径] 正式版命令名为 cindy(dev 构建为 cindydev),例如 cindy .
+#
+# 手动卸载: rm 掉安装时创建的 symlink(默认 /usr/local/bin/<命令名>;命令名随
+# edition 品牌,正式版为 cindy,内部 dev 构建为 cindydev)。
+#
+# 自定位:先跟随 symlink 找到本脚本的真实路径,再按包内布局
+# <Cindy.app>/Contents/Resources/cli/cindy
+# 反推 .app 根目录。因此即使 app 被移动位置,已装好的 symlink 仍然可用,无需重装
+# (与 VS Code 的 bin/code 同一思路)。
+PROG=$(basename "$0")
+SELF="$0"
+
+# 当命令通过 PATH 调用时,$0 可能不带路径(例如 "cindy"),需要先解析为可访问的路径。
+case "$SELF" in
+ */*) ;;
+ *) SELF=$(command -v "$SELF" 2>/dev/null || printf '%s' "$SELF") ;;
+esac
+
+while [ -h "$SELF" ]; do
+ link=$(readlink "$SELF")
+ case "$link" in
+ /*) SELF="$link" ;;
+ *) SELF="$(dirname "$SELF")/$link" ;;
+ esac
+done
+BIN_DIR=$(cd "$(dirname "$SELF")" >/dev/null 2>&1 && pwd)
+APP=$(cd "$BIN_DIR/../../.." >/dev/null 2>&1 && pwd)
+
+# 无参数:仅唤起 / 聚焦 app。
+if [ "$#" -eq 0 ]; then
+ exec open -a "$APP"
+fi
+
+# 只接受单个路径:app 冷启动时目录经 open-file → handleIncomingOpenFolder 落地,
+# main 侧只有单个 pending 槽,窗口未就绪时多路径会互相覆盖、静默丢失。与其悄悄丢,
+# 不如显式拒绝,让用户分多次调用。
+if [ "$#" -gt 1 ]; then
+ echo "$PROG: 一次只能打开一个路径(收到 $# 个)。请分多次运行,例如:$PROG ." >&2
+ exit 2
+fi
+
+# 把参数解析成绝对路径(cindy . → 当前目录绝对路径),再交给 `open -a`;目录会通过
+# app 的 open-file 管线落成工作目录。`--` 结束选项解析,避免以 - 开头的路径被 open
+# 当成自身选项。
+arg="$1"
+if [ -d "$arg" ]; then
+ abs=$(cd "$arg" >/dev/null 2>&1 && pwd)
+elif [ -e "$arg" ]; then
+ dir=$(cd "$(dirname "$arg")" >/dev/null 2>&1 && pwd) && abs="$dir/$(basename "$arg")"
+else
+ abs="$arg"
+fi
+
+exec open -a "$APP" -- "$abs"
diff --git a/apps/desktop/src/main/__tests__/installCliCommand.test.ts b/apps/desktop/src/main/__tests__/installCliCommand.test.ts
new file mode 100644
index 0000000000..16ff78b083
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/installCliCommand.test.ts
@@ -0,0 +1,178 @@
+/**
+ * installCliCommand 纯函数单测:symlink 目标路径推导、install/uninstall shell 命令拼装、
+ * shell/AppleScript 转义、权限与「用户取消授权」判定,以及随包分发的启动器脚本自检。
+ * 不触发真实 symlink 或 osascript(那些路径需 packaged + 用户授权,见模块头注释,
+ * 端到端只能打包验证)。
+ */
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { brandExecutableName } from '@cindy/maker-shared/brand-identity';
+import { describe, expect, it } from 'vitest';
+
+import {
+ CLI_COMMAND_NAME,
+ CLI_LINK_PATH,
+ __testing,
+ buildInstallShellCommand,
+ buildUninstallShellCommand,
+ resolveBundledCliPath,
+} from '../installCliCommand';
+
+describe('CLI_COMMAND_NAME 跟随 edition 品牌', () => {
+ it('测试环境(未注入区域 → 默认 global)命令名为 cindy', () => {
+ expect(CLI_COMMAND_NAME).toBe('cindy');
+ expect(CLI_LINK_PATH).toBe('/usr/local/bin/cindy');
+ });
+
+ it('由区域可执行名小写化:global / cn → cindy,内部 dev → cindydev', () => {
+ // global 与 cn 展示名统一为 Cindy(2026-07-26 决策),故命令名同为 cindy。
+ expect(brandExecutableName('global').toLowerCase()).toBe('cindy');
+ expect(brandExecutableName('cn').toLowerCase()).toBe('cindy');
+ expect(brandExecutableName('dev').toLowerCase()).toBe('cindydev');
+ });
+});
+
+describe('resolveBundledCliPath', () => {
+ it('由 resourcesPath 推出包内 cli/cindy', () => {
+ expect(resolveBundledCliPath('/Applications/Cindy.app/Contents/Resources')).toBe(
+ '/Applications/Cindy.app/Contents/Resources/cli/cindy',
+ );
+ });
+
+ it('路径含空格也正确', () => {
+ expect(resolveBundledCliPath('/Users/a/My Apps/Cindy.app/Contents/Resources')).toBe(
+ '/Users/a/My Apps/Cindy.app/Contents/Resources/cli/cindy',
+ );
+ });
+});
+
+describe('buildInstallShellCommand', () => {
+ it('mkdir -p 链接目录、拒绝真实目录后 ln -sfn 目标到 source', () => {
+ const cmd = buildInstallShellCommand(
+ '/Applications/Cindy.app/Contents/Resources/cli/cindy',
+ CLI_LINK_PATH,
+ );
+ expect(cmd).toBe(
+ `mkdir -p '/usr/local/bin' && if [ -d '/usr/local/bin/cindy' ] && [ ! -L '/usr/local/bin/cindy' ]; then echo '/usr/local/bin/cindy is a directory' >&2; exit 1; fi && ln -sfn '/Applications/Cindy.app/Contents/Resources/cli/cindy' '/usr/local/bin/cindy'`,
+ );
+ });
+
+ it('用 -sfn 而非 -sf(macOS 上替换指向目录的旧 symlink,不解引用进目录)', () => {
+ const cmd = buildInstallShellCommand('/App/Cindy.app/Contents/Resources/cli/cindy', CLI_LINK_PATH);
+ expect(cmd).toContain(`ln -sfn `);
+ expect(cmd).not.toContain(`ln -sf `);
+ });
+
+ it('含单引号的路径被安全转义', () => {
+ const cmd = buildInstallShellCommand(`/Users/o'brien/Cindy.app/Contents/Resources/cli/cindy`, CLI_LINK_PATH);
+ expect(cmd).toContain(`'/Users/o'\\''brien/Cindy.app/Contents/Resources/cli/cindy'`);
+ });
+});
+
+describe('buildUninstallShellCommand', () => {
+ it('仅当目标是 symlink 时才 rm -f(不误删同路径普通文件,并发移除也幂等)', () => {
+ expect(buildUninstallShellCommand(CLI_LINK_PATH)).toBe(
+ `if [ -L '/usr/local/bin/cindy' ]; then rm -f '/usr/local/bin/cindy'; fi`,
+ );
+ });
+
+ it('含单引号的路径两处引用都被安全转义', () => {
+ const cmd = buildUninstallShellCommand(`/usr/local/bin/o'brien`);
+ expect(cmd).toBe(
+ `if [ -L '/usr/local/bin/o'\\''brien' ]; then rm -f '/usr/local/bin/o'\\''brien'; fi`,
+ );
+ });
+});
+
+describe('shellSingleQuote', () => {
+ const { shellSingleQuote } = __testing;
+
+ it('普通路径直接包单引号', () => {
+ expect(shellSingleQuote('/usr/local/bin/cindy')).toBe(`'/usr/local/bin/cindy'`);
+ });
+
+ it("内部单引号转义为 '\\''", () => {
+ expect(shellSingleQuote(`a'b`)).toBe(`'a'\\''b'`);
+ });
+});
+
+describe('escapeForAppleScriptString', () => {
+ const { escapeForAppleScriptString } = __testing;
+
+ it('转义反斜杠与双引号', () => {
+ expect(escapeForAppleScriptString('a"b\\c')).toBe('a\\"b\\\\c');
+ });
+
+ it('单引号(shell 用)不受影响', () => {
+ expect(escapeForAppleScriptString(`ln -sf '/a/b' '/c/d'`)).toBe(`ln -sf '/a/b' '/c/d'`);
+ });
+});
+
+describe('isPermissionError', () => {
+ const { isPermissionError } = __testing;
+
+ it('识别 EACCES / EPERM / EROFS', () => {
+ for (const code of ['EACCES', 'EPERM', 'EROFS']) {
+ expect(isPermissionError(Object.assign(new Error('x'), { code }))).toBe(true);
+ }
+ });
+
+ it('其它错误返回 false', () => {
+ expect(isPermissionError(Object.assign(new Error('x'), { code: 'ENOENT' }))).toBe(false);
+ expect(isPermissionError(new Error('plain'))).toBe(false);
+ expect(isPermissionError(undefined)).toBe(false);
+ });
+});
+
+describe('isUserCancelledAdmin', () => {
+ const { isUserCancelledAdmin } = __testing;
+
+ it('识别 osascript 取消授权(-128 / User canceled)', () => {
+ expect(isUserCancelledAdmin(new Error('osascript: User canceled.'))).toBe(true);
+ expect(
+ isUserCancelledAdmin(Object.assign(new Error('failed'), { stderr: 'execution error: ... (-128)' })),
+ ).toBe(true);
+ });
+
+ it('普通失败返回 false', () => {
+ expect(isUserCancelledAdmin(new Error('ln: permission denied'))).toBe(false);
+ expect(isUserCancelledAdmin(undefined)).toBe(false);
+ });
+});
+
+describe('随包分发的启动器脚本 resources/cli/cindy', () => {
+ const scriptPath = path.resolve(
+ fileURLToPath(import.meta.url),
+ '../../../../resources/cli/cindy',
+ );
+ const script = readFileSync(scriptPath, 'utf8');
+
+ it('是 sh 脚本', () => {
+ expect(script.startsWith('#!/bin/sh\n')).toBe(true);
+ });
+
+ it('跟随 symlink 自定位并反推 .app', () => {
+ expect(script).toContain('while [ -h "$SELF" ]; do');
+ expect(script).toContain('readlink "$SELF"');
+ // BIN_DIR/../../.. : cli → Resources → Contents → *.app
+ expect(script).toContain('APP=$(cd "$BIN_DIR/../../.." >/dev/null 2>&1 && pwd)');
+ });
+
+ it('无参数仅唤起 app,单参数用 open -a 打开', () => {
+ expect(script).toContain('if [ "$#" -eq 0 ]; then\n exec open -a "$APP"');
+ // -- 结束选项解析,避免以 - 开头的路径被 open 当成自身选项。
+ expect(script).toContain('exec open -a "$APP" -- "$abs"');
+ });
+
+ it('拒绝多路径调用(避免冷启动 pending 槽互相覆盖、静默丢失)', () => {
+ expect(script).toContain('if [ "$#" -gt 1 ]; then');
+ expect(script).toContain('exit 2');
+ });
+
+ it('把单个参数解析为绝对路径(支持 cindy .)', () => {
+ expect(script).toContain('abs=$(cd "$arg" >/dev/null 2>&1 && pwd)');
+ expect(script).toContain('arg="$1"');
+ });
+});
diff --git a/apps/desktop/src/main/applicationMenuLabels.ts b/apps/desktop/src/main/applicationMenuLabels.ts
index 3e8f0785f4..75a6452ff4 100644
--- a/apps/desktop/src/main/applicationMenuLabels.ts
+++ b/apps/desktop/src/main/applicationMenuLabels.ts
@@ -10,6 +10,11 @@
* vitest 直接 import 运行时对象,复用 scripts/shared/glossary-rules.mjs 的判定。
* 之所以要抽出来,是因为原先它嵌在 bootstrap-electron.ts 里,测试一 import 就会拉起
* 整个 Electron 主进程模块。
+ *
+ * `installCli*` 一组里的 `{{cmd}}` 是**命令名占位符**,由调用侧按本构建 edition 品牌
+ * 替换(global/cn → `cindy`,dev → `cindydev`,见 installCliCommand.ts 的
+ * CLI_COMMAND_NAME);`{{path}}` 替换为 symlink 安装路径。文案里的 “Cindy” 指产品/应用
+ * 本身,不随命令名变化,故保留。
*/
import type { SupportedLocale } from '../shared/locale.js';
@@ -30,6 +35,22 @@ export interface ApplicationMenuLabels {
help: string;
releaseNotes: string;
issues: string;
+ installCli: string;
+ installCliConfirmTitle: string;
+ installCliConfirmDetail: string;
+ installCliConfirmOk: string;
+ installCliCancel: string;
+ installCliSuccessTitle: string;
+ installCliSuccessDetail: string;
+ installCliErrorTitle: string;
+ installCliErrorDetail: string;
+ installCliDevOnlyTitle: string;
+ installCliDevOnlyDetail: string;
+ installCliUnsupportedTitle: string;
+ installCliUnsupportedDetail: string;
+ installCliNotInApplicationsTitle: string;
+ installCliNotInApplicationsDetail: string;
+ installCliMoveToApplications: string;
}
export const APPLICATION_MENU_LABELS: Record<ApplicationMenuLocale, ApplicationMenuLabels> = {
@@ -48,6 +69,26 @@ export const APPLICATION_MENU_LABELS: Record<ApplicationMenuLocale, ApplicationM
help: '帮助',
releaseNotes: '最新更新介绍',
issues: '问题反馈',
+ installCli: '安装到命令行',
+ installCliConfirmTitle: '把 {{cmd}} 命令安装到命令行?',
+ installCliConfirmDetail:
+ '将在 {{path}} 创建指向 Cindy 的符号链接;若该路径已存在同名文件,会被替换。之后在终端运行 {{cmd}} . 即可把当前目录作为工作目录在 Cindy 中打开。系统会请求你的管理员密码以写入该目录。',
+ installCliConfirmOk: '安装',
+ installCliCancel: '取消',
+ installCliSuccessTitle: '{{cmd}} 命令已安装',
+ installCliSuccessDetail:
+ '已安装到 {{path}}。重开一个终端窗口后运行 {{cmd}} . 即可。若提示找不到命令,请确认该目录在你的 PATH 中。',
+ installCliErrorTitle: '安装失败',
+ installCliErrorDetail: '未能安装 {{cmd}} 命令。',
+ installCliDevOnlyTitle: '仅正式版可用',
+ installCliDevOnlyDetail:
+ '开发模式下无法安装命令行工具:此时的可执行文件指向 Electron 解释器,而非 Cindy 应用。请在正式安装的 Cindy 中使用此功能。',
+ installCliUnsupportedTitle: '暂不支持当前系统',
+ installCliUnsupportedDetail: '安装到命令行目前仅支持 macOS。',
+ installCliNotInApplicationsTitle: '请先把 Cindy 移动到「应用程序」文件夹',
+ installCliNotInApplicationsDetail:
+ '当前 Cindy 运行在临时位置(不在「应用程序」文件夹里)。此时安装的命令会指向这个临时路径,应用退出或磁盘弹出后即失效。请先把 Cindy 移动到「应用程序」文件夹,再安装命令行。',
+ installCliMoveToApplications: '移动到「应用程序」',
},
en: {
about: 'About {{appName}}',
@@ -64,6 +105,26 @@ export const APPLICATION_MENU_LABELS: Record<ApplicationMenuLocale, ApplicationM
help: 'Help',
releaseNotes: "What's New",
issues: 'Issues',
+ installCli: "Install '{{cmd}}' Command in PATH",
+ installCliConfirmTitle: "Install the '{{cmd}}' command in your PATH?",
+ installCliConfirmDetail:
+ 'A symlink to Cindy will be created at {{path}}; if a file already exists there, it will be replaced. You can then run `{{cmd}} .` in a terminal to open the current directory as a working directory in Cindy. You will be asked for your administrator password to write to that location.',
+ installCliConfirmOk: 'Install',
+ installCliCancel: 'Cancel',
+ installCliSuccessTitle: "'{{cmd}}' command installed",
+ installCliSuccessDetail:
+ 'Installed at {{path}}. Open a new terminal window and run `{{cmd}} .`. If the command is not found, make sure that directory is on your PATH.',
+ installCliErrorTitle: 'Installation failed',
+ installCliErrorDetail: "Could not install the '{{cmd}}' command.",
+ installCliDevOnlyTitle: 'Packaged build only',
+ installCliDevOnlyDetail:
+ 'The command-line tool cannot be installed in development mode: the executable points at the Electron runtime rather than the Cindy app. Use this from an installed Cindy build.',
+ installCliUnsupportedTitle: 'Not supported on this system',
+ installCliUnsupportedDetail: "Installing the '{{cmd}}' command is currently supported on macOS only.",
+ installCliNotInApplicationsTitle: 'Move Cindy to the Applications folder first',
+ installCliNotInApplicationsDetail:
+ 'Cindy is running from a temporary location (not the Applications folder). A command installed now would point at that temporary path and break as soon as the app quits or the volume is ejected. Move Cindy to the Applications folder, then install the command.',
+ installCliMoveToApplications: 'Move to Applications',
},
ja: {
about: '{{appName}} について',
@@ -80,6 +141,26 @@ export const APPLICATION_MENU_LABELS: Record<ApplicationMenuLocale, ApplicationM
help: 'ヘルプ',
releaseNotes: '最新情報',
issues: 'フィードバック',
+ installCli: 'コマンドラインに {{cmd}} をインストール',
+ installCliConfirmTitle: '{{cmd}} コマンドをコマンドラインにインストールしますか?',
+ installCliConfirmDetail:
+ 'Cindy へのシンボリックリンクを {{path}} に作成します。そのパスに既存のファイルがある場合は置き換えられます。その後ターミナルで {{cmd}} . を実行すると、現在のディレクトリを作業ディレクトリとして Cindy で開けます。この場所への書き込みには管理者パスワードの入力を求められます。',
+ installCliConfirmOk: 'インストール',
+ installCliCancel: 'キャンセル',
+ installCliSuccessTitle: '{{cmd}} コマンドをインストールしました',
+ installCliSuccessDetail:
+ '{{path}} にインストールしました。新しいターミナルウインドウを開いて {{cmd}} . を実行してください。コマンドが見つからない場合は、そのディレクトリが PATH に含まれているか確認してください。',
+ installCliErrorTitle: 'インストールに失敗しました',
+ installCliErrorDetail: '{{cmd}} コマンドをインストールできませんでした。',
+ installCliDevOnlyTitle: '正式ビルドのみ対応',
+ installCliDevOnlyDetail:
+ '開発モードではコマンドラインツールをインストールできません。実行ファイルが Cindy アプリではなく Electron ランタイムを指しているためです。インストール済みの Cindy から実行してください。',
+ installCliUnsupportedTitle: 'このシステムには非対応',
+ installCliUnsupportedDetail: 'コマンドラインへのインストールは現在 macOS のみ対応しています。',
+ installCliNotInApplicationsTitle: 'まず Cindy を「アプリケーション」フォルダに移動してください',
+ installCliNotInApplicationsDetail:
+ 'Cindy は一時的な場所(「アプリケーション」フォルダの外)で実行されています。この状態でインストールしたコマンドはその一時パスを指すため、アプリの終了やボリュームの取り出しで無効になります。Cindy を「アプリケーション」フォルダに移動してから、コマンドをインストールしてください。',
+ installCliMoveToApplications: '「アプリケーション」に移動',
},
ko: {
about: '{{appName}} 정보',
@@ -96,5 +177,25 @@ export const APPLICATION_MENU_LABELS: Record<ApplicationMenuLocale, ApplicationM
help: '도움말',
releaseNotes: '최신 업데이트',
issues: '이슈',
+ installCli: '명령줄에 {{cmd}} 명령 설치',
+ installCliConfirmTitle: '{{cmd}} 명령을 명령줄에 설치할까요?',
+ installCliConfirmDetail:
+ 'Cindy를 가리키는 심볼릭 링크를 {{path}}에 만듭니다. 해당 경로에 파일이 이미 있으면 대체됩니다. 이후 터미널에서 {{cmd}} . 를 실행하면 현재 디렉터리를 작업 디렉터리로 Cindy에서 열 수 있습니다. 이 위치에 쓰려면 관리자 암호를 입력해야 합니다.',
+ installCliConfirmOk: '설치',
+ installCliCancel: '취소',
+ installCliSuccessTitle: '{{cmd}} 명령을 설치했습니다',
+ installCliSuccessDetail:
+ '{{path}}에 설치했습니다. 새 터미널 창을 열고 {{cmd}} . 를 실행하세요. 명령을 찾을 수 없으면 해당 디렉터리가 PATH에 있는지 확인하세요.',
+ installCliErrorTitle: '설치 실패',
+ installCliErrorDetail: '{{cmd}} 명령을 설치하지 못했습니다.',
+ installCliDevOnlyTitle: '정식 빌드에서만 사용 가능',
+ installCliDevOnlyDetail:
+ '개발 모드에서는 명령줄 도구를 설치할 수 없습니다. 실행 파일이 Cindy 앱이 아닌 Electron 런타임을 가리키기 때문입니다. 설치된 Cindy에서 사용하세요.',
+ installCliUnsupportedTitle: '이 시스템에서는 지원되지 않음',
+ installCliUnsupportedDetail: '명령줄 설치는 현재 macOS에서만 지원됩니다.',
+ installCliNotInApplicationsTitle: '먼저 Cindy를 응용 프로그램 폴더로 옮기세요',
+ installCliNotInApplicationsDetail:
+ 'Cindy가 임시 위치(응용 프로그램 폴더 밖)에서 실행되고 있습니다. 지금 설치하는 명령은 이 임시 경로를 가리키므로 앱을 종료하거나 볼륨을 꺼내면 작동하지 않습니다. Cindy를 응용 프로그램 폴더로 옮긴 다음 명령을 설치하세요.',
+ installCliMoveToApplications: '응용 프로그램으로 이동',
},
};
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 66730e7946..6a19f101f1 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1273,6 +1273,7 @@ protocol.registerSchemesAsPrivileged([
import started from 'electron-squirrel-startup';
import { APPLICATION_MENU_LABELS, type ApplicationMenuLocale } from './applicationMenuLabels.js';
+import { installCindyCliCommand, CLI_COMMAND_NAME } from './installCliCommand.js';
if (started) {
app.quit();
@@ -1527,6 +1528,16 @@ function installApplicationMenu(
label: labels.issues,
click: () => dispatchApplicationMenuCommand(mainWindow, 'open-issues'),
},
+ { type: 'separator' },
+ {
+ // 命令名随 edition 品牌(installCli 文案里的 {{cmd}} 占位符)。
+ label: labels.installCli.replaceAll('{{cmd}}', CLI_COMMAND_NAME),
+ // 特权动作(写 PATH 目录 / 可能弹管理员授权)整段在 main 执行,
+ // 不经 renderer,也不新增 IPC 面。见 installCliCommand.ts。
+ click: () => {
+ void installCindyCliCommand(mainWindow, locale);
+ },
+ },
],
},
];
diff --git a/apps/desktop/src/main/installCliCommand.ts b/apps/desktop/src/main/installCliCommand.ts
new file mode 100644
index 0000000000..636ff781ab
--- /dev/null
+++ b/apps/desktop/src/main/installCliCommand.ts
@@ -0,0 +1,343 @@
+/**
+ * installCliCommand — 把 `cindy` 命令装到 shell PATH(macOS)
+ * ---------------------------------------------------------------------------
+ * 类比 VS Code 的 "Install 'code' command in PATH",且**完全对齐其实现方式**:
+ * 不往 PATH 里写一份生成的脚本,而是在 `/usr/local/bin/cindy` 建一个 **symlink**,
+ * 指向随 app 分发的启动器脚本 `<Cindy.app>/Contents/Resources/cli/cindy`
+ * (forge.config.ts 的 extraResource 注入,见 resources/cli/cindy)。之后终端里
+ * `cindy .` 就能把当前工作目录作为工作目录在 Cindy 里打开。
+ *
+ * symlink 而非写脚本的好处(与 VS Code 一致):升级 app 后无需重装,symlink 始终
+ * 指向包内最新脚本;卸载只需删 symlink。启动器脚本自身会跟随 symlink 反推 .app 根,
+ * 因此 app 移动位置后仍可用。
+ *
+ * 接收侧不需要新代码:app 已声明 `public.folder` 文档类型
+ * (forge.config.ts CFBundleDocumentTypes),macOS 上 `open -a Cindy <目录>` 会通过
+ * `open-file` 事件进入 bootstrap-electron 的 handleIncomingOpenFolder,落成
+ * 「新建对话 + 预填工作目录」。
+ *
+ * 权限策略(对齐 VS Code nativeHostMainService):
+ * - 安装:**一律**通过 osascript「以管理员身份」执行
+ * `mkdir -p /usr/local/bin && ln -sf '<target>' '<source>'`。不先尝试直接写——
+ * /usr/local/bin 常属 root,直接建 symlink 多半 EACCES,直接弹一次系统授权更干净。
+ * 弹系统口令前先弹一个应用内确认框(warnEscalation),取消则不动手。
+ * - 卸载:先直接 `unlink`,只有 EACCES 才升级到 osascript `rm`;ENOENT 视为已卸载。
+ *
+ * 平台 / 构建门:
+ * - 仅 macOS(原生应用菜单本身就只在 darwin 装,见 installApplicationMenu)。
+ * - 仅 packaged:dev 模式下 process.resourcesPath 指向 Electron 自带 resources,
+ * 包内 cli/cindy 不存在且 `open -a` 找不到 Cindy.app;dev 下给出说明弹窗而不动手。
+ *
+ * 卸载:导出 uninstallCindyCliCommand 作为命令行/测试入口,不挂菜单
+ * (与 folderContextMenu.ts 的 unregisterFolderContextMenu 同一取舍)。
+ */
+
+import { app, BrowserWindow, dialog } from 'electron';
+import { execFile } from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+import { promisify } from 'node:util';
+
+import { brandExecutableName } from '@cindy/maker-shared/brand-identity';
+
+import { createLogger, maskPath } from './logger';
+import {
+ APPLICATION_MENU_LABELS,
+ type ApplicationMenuLabels,
+ type ApplicationMenuLocale,
+} from './applicationMenuLabels.js';
+import { CURRENT_CINDY_REGION } from '../shared/brandRegion.js';
+
+const execFileAsync = promisify(execFile);
+const log = createLogger('installCliCommand');
+
+/**
+ * 装进 PATH 的命令名,**跟随本构建 edition 品牌**:由区域可执行名小写化而来
+ * (global/cn 展示名统一为 Cindy → `cindy`;内部 dev 构建 → `cindydev`)。
+ * *nix 命令惯例用小写,与 forge 给 linux 包名用 `CINDY_EXE.toLowerCase()` 同一处理;
+ * 未注入区域默认 global(见 brandRegion / region-and-editions.md §2.2)。
+ */
+export const CLI_COMMAND_NAME = brandExecutableName(CURRENT_CINDY_REGION).toLowerCase();
+
+/** PATH 里的 symlink 位置(命令名随 edition 品牌)。与 VS Code 的 `code` 同目录。 */
+export const CLI_LINK_PATH = `/usr/local/bin/${CLI_COMMAND_NAME}`;
+
+/** osascript 超时。管理员授权弹窗需要用户输入,给足时间。 */
+const INSTALL_TIMEOUT_MS = 60_000;
+
+/**
+ * symlink 指向的目标:包内启动器脚本 `<Resources>/cli/cindy`。
+ * 与 forge.config.ts extraResource 的 `resources/cli` 落点一致。
+ */
+export function resolveBundledCliPath(resourcesPath: string): string {
+ return path.join(resourcesPath, 'cli', 'cindy');
+}
+
+/** POSIX shell 单引号转义:把值安全地包进 '...'。 */
+function shellSingleQuote(value: string): string {
+ return `'${value.replace(/'/g, `'\\''`)}'`;
+}
+
+/**
+ * 安装用 shell 命令:先确保 /usr/local/bin 存在,再强制建 symlink,交给 osascript
+ * 「以管理员身份」执行。
+ *
+ * macOS(BSD)ln 的坑:当链接路径已是「目录」或「指向目录的 symlink」时,`ln -sf`
+ * 会把链接建进 <目录>/<basename> 里并**成功退出**,原路径仍是那个目录、非可执行,
+ * 却会被我们当成安装成功。两道防护:
+ * - `-n`(macOS 上等价 `-h`):已存在的 symlink 本身被 `-f` 替换,不再被解引用进目录,
+ * 覆盖「坏的/指向目录的旧 symlink」这一常见的残留安装。
+ * - 真实目录(非 symlink)`-f` 无法 unlink,`ln` 仍会往里建 —— 故先显式判空并 `exit 1`,
+ * 让上层走错误弹窗,绝不误报成功。
+ */
+export function buildInstallShellCommand(target: string, source: string): string {
+ const q = shellSingleQuote;
+ const dir = path.dirname(source);
+ return (
+ `mkdir -p ${q(dir)} && ` +
+ `if [ -d ${q(source)} ] && [ ! -L ${q(source)} ]; then echo ${q(`${source} is a directory`)} >&2; exit 1; fi && ` +
+ `ln -sfn ${q(target)} ${q(source)}`
+ );
+}
+
+/**
+ * 卸载用 shell 命令(仅在直接 unlink 遇 EACCES 时才走管理员分支)。
+ * 只在目标是 symlink 时才删除:即便上层已 lstat 把关,elevated `rm` 也不越权误删
+ * 同路径上用户自己放的普通文件。非 symlink / 不存在时 `if` 直接跳过,退出码为 0。
+ * `rm -f`:`[ -L ]` 与 `rm` 之间若链接被并发移除,-f 不报错,卸载保持幂等
+ * (与非提权分支容忍 ENOENT 同一取舍);-L 把关仍在,只删 symlink 不误删普通文件。
+ */
+export function buildUninstallShellCommand(source: string): string {
+ const quoted = shellSingleQuote(source);
+ return `if [ -L ${quoted} ]; then rm -f ${quoted}; fi`;
+}
+
+function isPermissionError(err: unknown): boolean {
+ const code = (err as NodeJS.ErrnoException | undefined)?.code;
+ return code === 'EACCES' || code === 'EPERM' || code === 'EROFS';
+}
+
+/** osascript 授权弹窗被用户取消时的错误特征(errAEEventNotHandled -128 / "User canceled")。 */
+function isUserCancelledAdmin(err: unknown): boolean {
+ const e = err as { stderr?: unknown; message?: unknown } | undefined;
+ const text = `${typeof e?.stderr === 'string' ? e.stderr : ''} ${
+ typeof e?.message === 'string' ? e.message : ''
+ }`;
+ return text.includes('-128') || /User can(?:c|)elled|User canceled/i.test(text);
+}
+
+/**
+ * 在 AppleScript 双引号字符串里安全嵌入一段 shell 命令:转义反斜杠与双引号。
+ * 命令里的路径已用单引号包裹,不含裸双引号,这里主要兜底路径中的反斜杠。
+ */
+function escapeForAppleScriptString(command: string): string {
+ return command.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
+}
+
+async function runWithAdmin(shellCommand: string): Promise<void> {
+ const appleScript = `do shell script "${escapeForAppleScriptString(
+ shellCommand,
+ )}" with administrator privileges`;
+ await execFileAsync('osascript', ['-e', appleScript], {
+ timeout: INSTALL_TIMEOUT_MS,
+ });
+}
+
+/**
+ * source(PATH 里的 symlink)是否已正确指向 target(包内脚本)。
+ * 对齐 VS Code:仅当 source 是 symlink 且其真实路径等于 target 真实路径时算「已装」。
+ * 非 symlink 或指向别处,都返回 false 让安装流程用 `ln -sf` 覆盖。
+ */
+async function isAlreadyLinked(source: string, target: string): Promise<boolean> {
+ try {
+ const stat = await fs.promises.lstat(source);
+ if (!stat.isSymbolicLink()) return false;
+ const [sourceReal, targetReal] = await Promise.all([
+ fs.promises.realpath(source),
+ fs.promises.realpath(target),
+ ]);
+ return sourceReal === targetReal;
+ } catch {
+ // ENOENT / 悬空 symlink / target 不存在等 → 视为未安装,交给后续流程处理。
+ return false;
+ }
+}
+
+function labelsFor(locale: ApplicationMenuLocale): ApplicationMenuLabels {
+ return APPLICATION_MENU_LABELS[locale];
+}
+
+/** 展开标签占位符:`{{path}}` → symlink 路径,`{{cmd}}` → 品牌命令名(全部出现处)。 */
+function fmt(template: string, linkPath: string): string {
+ return template.split('{{path}}').join(linkPath).split('{{cmd}}').join(CLI_COMMAND_NAME);
+}
+
+async function showMessage(
+ window: BrowserWindow | null,
+ options: Electron.MessageBoxOptions,
+): Promise<Electron.MessageBoxReturnValue> {
+ if (window && !window.isDestroyed()) {
+ return dialog.showMessageBox(window, options);
+ }
+ return dialog.showMessageBox(options);
+}
+
+/**
+ * 「安装到命令行」菜单动作。整段在 main 进程执行(菜单 click 回调本就在 main),
+ * 不新增 IPC / preload 面。失败只弹窗 + warn,不抛;用户取消静默返回。
+ */
+export async function installCindyCliCommand(
+ window: BrowserWindow | null,
+ locale: ApplicationMenuLocale,
+): Promise<void> {
+ const labels = labelsFor(locale);
+
+ if (process.platform !== 'darwin') {
+ await showMessage(window, {
+ type: 'info',
+ message: labels.installCliUnsupportedTitle,
+ detail: labels.installCliUnsupportedDetail,
+ });
+ return;
+ }
+
+ if (!app.isPackaged) {
+ await showMessage(window, {
+ type: 'info',
+ message: labels.installCliDevOnlyTitle,
+ detail: labels.installCliDevOnlyDetail,
+ });
+ return;
+ }
+
+ // App Translocation / 直接从 DMG 运行时,process.resourcesPath 是临时只读路径。
+ // 此时建的 symlink 指向这个临时位置,app 退出或卷弹出后即失效,却会「安装成功」。
+ // 先要求把 app 移动到「应用程序」再安装(与 bootstrap-electron 的搬运提示同源)。
+ if (!app.isInApplicationsFolder()) {
+ const choice = await showMessage(window, {
+ type: 'warning',
+ buttons: [labels.installCliMoveToApplications, labels.installCliCancel],
+ defaultId: 0,
+ cancelId: 1,
+ message: labels.installCliNotInApplicationsTitle,
+ detail: labels.installCliNotInApplicationsDetail,
+ });
+ if (choice.response === 0) {
+ try {
+ // 成功会从「应用程序」重新拉起并结束当前进程;失败则不建 symlink。
+ app.moveToApplicationsFolder();
+ } catch (err) {
+ log.warn('failed to move Cindy to Applications before CLI install', err);
+ }
+ }
+ return;
+ }
+
+ const source = CLI_LINK_PATH;
+ const target = resolveBundledCliPath(process.resourcesPath);
+
+ // 包内启动器脚本缺失(打包异常)→ 明确报错,不尝试建指向空的 symlink。
+ if (!fs.existsSync(target)) {
+ log.warn('bundled cindy launcher missing; cannot install', { target: maskPath(target) });
+ await showMessage(window, {
+ type: 'error',
+ message: labels.installCliErrorTitle,
+ detail: `${fmt(labels.installCliErrorDetail, source)}\n\n${target}`,
+ });
+ return;
+ }
+
+ // 已正确安装:直接告知成功,不重复弹管理员授权。
+ if (await isAlreadyLinked(source, target)) {
+ log.info('cindy CLI command already installed', { source: maskPath(source), target: maskPath(target) });
+ await showMessage(window, {
+ type: 'info',
+ message: fmt(labels.installCliSuccessTitle, source),
+ detail: fmt(labels.installCliSuccessDetail, source),
+ });
+ return;
+ }
+
+ const confirm = await showMessage(window, {
+ type: 'question',
+ buttons: [labels.installCliConfirmOk, labels.installCliCancel],
+ defaultId: 0,
+ cancelId: 1,
+ message: fmt(labels.installCliConfirmTitle, source),
+ detail: fmt(labels.installCliConfirmDetail, source),
+ });
+ if (confirm.response !== 0) return;
+
+ try {
+ await runWithAdmin(buildInstallShellCommand(target, source));
+ log.info('cindy CLI command installed', { source: maskPath(source), target: maskPath(target) });
+ await showMessage(window, {
+ type: 'info',
+ message: fmt(labels.installCliSuccessTitle, source),
+ detail: fmt(labels.installCliSuccessDetail, source),
+ });
+ } catch (err) {
+ if (isUserCancelledAdmin(err)) {
+ log.info('cindy CLI install cancelled by user at admin prompt');
+ return;
+ }
+ log.warn('failed to install cindy CLI command', err);
+ await showMessage(window, {
+ type: 'error',
+ message: labels.installCliErrorTitle,
+ detail: `${fmt(labels.installCliErrorDetail, source)}\n\n${(err as Error)?.message ?? String(err)}`,
+ });
+ }
+}
+
+/**
+ * 卸载入口(命令行 / 测试用,不挂菜单)。先直接 unlink,EACCES 才升级到管理员 rm,
+ * ENOENT 视为已卸载。对齐 VS Code uninstallShellCommand。
+ */
+export async function uninstallCindyCliCommand(): Promise<void> {
+ if (process.platform !== 'darwin') return;
+ const source = CLI_LINK_PATH;
+
+ // 只删本功能装的 symlink。路径上若是普通文件(用户自己放的真实可执行文件)一律不动,
+ // 避免误删。lstat 不跟随链接,悬空 symlink 也照删。
+ let stat: fs.Stats;
+ try {
+ stat = await fs.promises.lstat(source);
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return;
+ log.warn('failed to stat cindy CLI command for uninstall (non-fatal)', err);
+ return;
+ }
+ if (!stat.isSymbolicLink()) {
+ log.warn('refusing to uninstall: path is not a symlink', { source: maskPath(source) });
+ return;
+ }
+
+ try {
+ await fs.promises.unlink(source);
+ log.info('cindy CLI command uninstalled', { source: maskPath(source) });
+ return;
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException)?.code;
+ if (code === 'ENOENT') return;
+ if (!isPermissionError(err)) {
+ log.warn('failed to uninstall cindy CLI command (non-fatal)', err);
+ return;
+ }
+ }
+ try {
+ // elevated 命令自身也 symlink 把关(见 buildUninstallShellCommand),双保险。
+ await runWithAdmin(buildUninstallShellCommand(source));
+ log.info('cindy CLI command uninstalled (elevated)', { source: maskPath(source) });
+ } catch (err) {
+ log.warn('failed to uninstall cindy CLI command with privileges (non-fatal)', err);
+ }
+}
+
+/** 仅给单测:导出纯函数,不依赖 Electron / 真实文件系统。 */
+export const __testing = {
+ shellSingleQuote,
+ escapeForAppleScriptString,
+ isPermissionError,
+ isUserCancelledAdmin,
+};