A local-first multi-agent app development platform, built on PenguinHarness
feat(desktop,docs): install the bundled penguin command automatically (#480)
Yaowei Zheng0b6430fa1213
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d09cdecd..8165de6d 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -216,6 +216,14 @@ jobs:CSC_IDENTITY_AUTO_DISCOVERY: "false"run: pnpm --dir packages/desktop exec electron-builder ${{ matrix.platform }} --dir --publish never+ # An installed desktop app installs the `penguin` command on the user's PATH — the deb+ # postinst links /usr/bin/penguin, the other forms do it from the shell at launch — and+ # every route runs <app>/bin/penguin against <app>/dist/penguin.js+ # inside this tree. Nothing else in the build fails if those stop being packed, so the+ # tree gets checked here, on all three platforms, where it already exists.+ - name: Bundled CLI runs from the packed app+ run: node packages/desktop/scripts/verify-packed-cli.mjs+- name: Upload runtime artifactuses: actions/upload-artifact@v4with:diff --git a/changelog/unreleased/2026-08-27-backward-compatibility.md b/changelog/unreleased/2026-08-27-backward-compatibility.mdnew file mode 100644index 00000000..3cd8a76c--- /dev/null+++ b/changelog/unreleased/2026-08-27-backward-compatibility.md@@ -0,0 +1,46 @@+# Backward compatibility++- **Date:** 2026-08-27+- **Type:** process+- **Scope:** `desktop`+- **PR:** [#480](https://github.com/Prism-Shadow/penguin-harness/pull/480)+- **Breaking:** yes — a "Not Now" answered to the pre-0.2.7 one-time `penguin` offer is not carried forward; the command installs itself on the next launch++[中文版](2026-08-27-backward-compatibility.zh.md)++One piece of existing state is touched by this batch: the marker the desktop app wrote when+it offered to install the `penguin` command, now that+[the app installs it automatically](2026-08-27-desktop-installs-cli.md).++## The `cli-install-offered` marker++Desktop releases 0.2.2 through 0.2.6 wrote an empty `cli-install-offered` file under+`userData` and skipped the offer whenever it existed. It was written **before** the dialog+was shown, so it records that the question was asked and not what was answered — an install,+a "Not Now" and a dialog that never got an answer all leave the same file. It therefore+cannot be read as a decline, and reading it as one would deny the command to every existing+install.++Chosen: **the marker is not migrated.** It is ignored, and removed the first time the new+state file is written. What replaces it, `cli-command.json` in the same directory, records+the outcome of the last attempt and — separately — a decision, which is set only by+dismissing the macOS administrator prompt. Only that decision stops the automatic attempt.++The removal is one `rmSync` per state write. It stays until no 0.2.2–0.2.6 install can+still upgrade into a current build; whoever prepares 0.3.0 owns deleting it, and the code+site carries the same note.++## Compatibility++Nothing has to be migrated and no action is required. Two consequences to know about:++A user who answered "Not Now" to the old offer gets the command installed on the next+launch, because that answer was never recorded. Removing it is one command — delete+`/usr/local/bin/penguin` on macOS or `~/.local/bin/penguin` on the Linux AppImage, or drop+the app's `bin` entry from the user `Path` on Windows — but the app will install it again+on the following launch, since only a dismissed macOS administrator prompt is remembered as+a decision.++A `penguin` that came from anywhere else is never touched. An `install.sh` install, a global+npm package or a hand-written script keeps its place on `PATH` and the app installs nothing;+the skipped reason is recorded in `cli-command.json`.diff --git a/changelog/unreleased/2026-08-27-backward-compatibility.zh.md b/changelog/unreleased/2026-08-27-backward-compatibility.zh.mdnew file mode 100644index 00000000..89e1f94d--- /dev/null+++ b/changelog/unreleased/2026-08-27-backward-compatibility.zh.md@@ -0,0 +1,38 @@+# 向后兼容++- **Date:** 2026-08-27+- **Type:** process+- **Scope:** `desktop`+- **PR:** [#480](https://github.com/Prism-Shadow/penguin-harness/pull/480)+- **Breaking:** yes — 对 0.2.7 之前那次一次性 `penguin` 询问回答的「Not Now」不会被沿用;命令会在下次启动时自行安装++[English](2026-08-27-backward-compatibility.md)++本批次涉及一处存量状态:桌面应用询问是否安装 `penguin` 命令时写下的标记文件——现在+[应用会自动安装该命令](2026-08-27-desktop-installs-cli.zh.md)。++## `cli-install-offered` 标记++0.2.2 至 0.2.6 的桌面版本会在 `userData` 下写一个空的 `cli-install-offered` 文件,只要它存在+就不再询问。该文件是在对话框弹出**之前**写入的,因此它记录的是「问过了」,而不是「答了什么」——+安装、点了「Not Now」、以及对话框始终没被回答,留下的文件完全相同。所以它不能被当作一次拒绝来读;+若当作拒绝,等于让所有存量安装都拿不到该命令。++选择:**不迁移该标记。**它被忽略,并在新状态文件第一次写入时删除。取而代之的是同一目录下的+`cli-command.json`,它记录最后一次尝试的结果,以及一个单独的决定字段——该字段只有在用户取消+macOS 管理员授权时才会被设置。只有这个决定会停止自动安装。++删除动作是每次写状态时的一次 `rmSync`。它保留到不再有 0.2.2–0.2.6 的安装能升级到当前构建为止;+由准备 0.3.0 的人负责删除,代码处也写有同样的说明。++## 兼容性++无需迁移,也无需任何手工操作。有两点需要知道:++对旧的询问回答过「Not Now」的用户,会在下次启动时被装上该命令,因为那个回答从未被记录下来。移除+只需一条命令——macOS 上删除 `/usr/local/bin/penguin`,Linux AppImage 上删除+`~/.local/bin/penguin`,Windows 上把应用的 `bin` 条目从用户 `Path` 中去掉——但再下一次启动时应用+会重新装上,因为只有被取消的 macOS 管理员授权才会被记为一个决定。++来自其他途径的 `penguin` 绝不会被动到。经 `install.sh` 安装的、全局 npm 包的、或手写的脚本都会+保留在 `PATH` 上,应用什么也不装;跳过的原因记录在 `cli-command.json` 中。diff --git a/changelog/unreleased/2026-08-27-desktop-installs-cli.md b/changelog/unreleased/2026-08-27-desktop-installs-cli.mdnew file mode 100644index 00000000..4a532688--- /dev/null+++ b/changelog/unreleased/2026-08-27-desktop-installs-cli.md@@ -0,0 +1,55 @@+# The desktop app installs the `penguin` command itself++- **Date:** 2026-08-27+- **Type:** feature+- **Scope:** `desktop`, `docs`+- **PR:** [#480](https://github.com/Prism-Shadow/penguin-harness/pull/480)++[中文版](2026-08-27-desktop-installs-cli.zh.md)++The desktop app now puts its bundled `penguin` command on PATH without being asked, and+re-checks it at every launch. Only the deb package did this before; macOS, Windows and the+AppImage offered it once, in a dialog on first launch, and never again. Because the app and+the CLI it carries come from the same build, installing the command from the app is also+what keeps the two in step across an update.++## What each platform does++- **macOS** — links `/usr/local/bin/penguin` to the app. The unprivileged write is tried+ first and an administrator prompt appears only where it is actually refused, which is a+ Mac with no `/usr/local/bin` yet. Dismissing that prompt is recorded and the app stops+ asking; the menu item is the way back.+- **Windows** — appends the app's `bin` directory to the user `Path` (`HKCU\Environment`),+ as before: idempotent, append-only, and no elevation.+- **Linux AppImage** — writes the `~/.local/bin/penguin` wrapper that runs the AppImage.+- **Linux deb** — unchanged; its postinst already created `/usr/bin/penguin`.++## What it will not do++- **Replace a `penguin` this app did not write.** A regular file where a link belongs, a+ symlink pointing anywhere else, anything without the marker every bundled launcher+ carries — each is left exactly as it was and the reason is recorded under `userData` in+ `cli-command.json`. `install.sh` puts its own symlink at `~/.local/bin/penguin`, which is+ the very path the AppImage form uses; the app is the side that gives way. The menu item+ **Install 'penguin' Command…** replaces it deliberately, after showing what it would+ overwrite.+- **Install from a location that will not persist.** A macOS bundle still on its mounted+ dmg, or one Gatekeeper is running translocated, would produce a link that dies with the+ mount. The app defers, and installs on the next launch from Applications.++## Repair++Running at every launch is what repairs an install rather than only creating one: a link+left dangling by a moved or updated app, or a wrapper naming an AppImage that has moved, is+rewritten to point at the running app. A `penguin` that is already correct costs one+`lstat`.++## Documentation++`quickstart-desktop` gained a `penguin` command section covering all four forms and the+two refusals, and `quickstart` stopped sending desktop users to a CLI install to get the+command. Both pages also dropped the macOS quarantine and Windows SmartScreen first-launch+instructions, which had outlived the unsigned builds they were written for — the same+correction the landing and README sweep in+[#481](https://github.com/Prism-Shadow/penguin-harness/pull/481) made, applied to the+documentation site.diff --git a/changelog/unreleased/2026-08-27-desktop-installs-cli.zh.md b/changelog/unreleased/2026-08-27-desktop-installs-cli.zh.mdnew file mode 100644index 00000000..20599d90--- /dev/null+++ b/changelog/unreleased/2026-08-27-desktop-installs-cli.zh.md@@ -0,0 +1,44 @@+# 桌面应用自行安装 `penguin` 命令++- **Date:** 2026-08-27+- **Type:** feature+- **Scope:** `desktop`, `docs`+- **PR:** [#480](https://github.com/Prism-Shadow/penguin-harness/pull/480)++[English](2026-08-27-desktop-installs-cli.md)++桌面应用现在会不经询问地把随包的 `penguin` 命令放上 PATH,并在每次启动时重新检查。此前只有+deb 包会这样做;macOS、Windows 与 AppImage 只在首次启动时用一个对话框询问一次,此后不再过问。+由于应用与它携带的 CLI 出自同一次构建,由应用来安装该命令,也就保证了两者在更新中始终同步。++## 各平台的行为++- **macOS**——把 `/usr/local/bin/penguin` 链接到应用。先尝试普通权限写入,只有在确实被拒时才+ 弹出管理员授权,也就是尚无 `/usr/local/bin` 的那种 Mac。取消该授权会被记录下来,应用不再询问;+ 菜单项是重新安装的入口。+- **Windows**——把应用的 `bin` 目录追加到用户 `Path`(`HKCU\Environment`),与此前一致:幂等、+ 只追加、无需提权。+- **Linux AppImage**——写入运行该 AppImage 的 `~/.local/bin/penguin` 包装脚本。+- **Linux deb**——不变;其 postinst 本就会创建 `/usr/bin/penguin`。++## 它不会做的事++- **替换不是本应用写入的 `penguin`。**该放链接的位置上是普通文件、符号链接指向别处、内容里没有+ 每个随包启动器都带的标记——这些都会被原样保留,原因记录在 `userData` 下的 `cli-command.json`+ 里。`install.sh` 会把自己的符号链接放在 `~/.local/bin/penguin`,正是 AppImage 形态使用的路径;+ 让路的是本应用这一侧。菜单项 **Install 'penguin' Command…** 会在展示将被覆盖的内容之后,按用户+ 意愿主动替换。+- **从不会长期存在的位置安装。**仍在挂载的 dmg 里、或被 Gatekeeper 以 translocation 方式运行的+ macOS 应用包,产生的链接会随卷的卸载而失效。此时应用会推迟安装,在下一次从「应用程序」启动时完成。++## 修复++每次启动都执行,才使它不只是创建、而是修复安装:应用被移动或更新后留下的悬空链接、或指向已移动+AppImage 的包装脚本,都会被重写为指向正在运行的这个应用。已经正确的 `penguin` 只花一次 `lstat`。++## 文档++`quickstart-desktop` 新增了 `penguin` 命令一节,覆盖四种形态与两类拒绝安装的情形;`quickstart`+不再让桌面端用户去做一次命令行安装来获得该命令。两页同时移除了 macOS 隔离标记与 Windows+SmartScreen 的首次启动说明——它们早已随未签名构建一同过时,与落地页和 README 的清理+([#481](https://github.com/Prism-Shadow/penguin-harness/pull/481))是同一处修正,只是应用到了文档站。diff --git a/changelog/unreleased/2026-08-27-packaged-cli-checks.md b/changelog/unreleased/2026-08-27-packaged-cli-checks.mdnew file mode 100644index 00000000..4db78ce1--- /dev/null+++ b/changelog/unreleased/2026-08-27-packaged-cli-checks.md@@ -0,0 +1,29 @@+# The bundled `penguin` command is checked in CI++- **Date:** 2026-08-27+- **Type:** process+- **Scope:** `desktop`, `ci`+- **PR:** [#480](https://github.com/Prism-Shadow/penguin-harness/pull/480)++[中文版](2026-08-27-packaged-cli-checks.zh.md)++The desktop app ships the CLI inside itself — `<app>/bin/penguin` and `<app>/bin/penguin.cmd`+run `<app>/dist/penguin.js` on the app's own Electron runtime, and every route that puts+`penguin` on PATH (the deb postinst, the macOS symlink, the Windows PATH entry, the AppImage+wrapper) points at one of those two launchers. Nothing verified that they were still in the+packed tree, so this batch added the checks — alongside+[making the app install that command itself](2026-08-27-desktop-installs-cli.md).++## Details++- `packages/desktop/scripts/verify-packed-cli.mjs` inspects the tree `electron-builder --dir`+ produces: every packed app directory must carry both launchers and the bundled CLI entry, the+ POSIX launcher must be executable, and at least one of them must actually run and report the+ app's version. CI's `runtime` job invokes it on Linux, macOS and Windows, on the tree it+ already builds.+- `packages/desktop/test/launcher.test.ts` gained a `packaged CLI` block pinning the couplings+ those launchers depend on and nothing else compares: `bin/**/*` staying in electron-builder's+ `files`, `asar` staying off, `productName` and `linux.executableName` matching the executable+ names the launcher scripts exec, the tsup entry name matching `CLI_ENTRY_RELPATH`, and the deb+ templates still creating `/usr/bin/penguin` (never over a non-symlink) and removing only their+ own link.diff --git a/changelog/unreleased/2026-08-27-packaged-cli-checks.zh.md b/changelog/unreleased/2026-08-27-packaged-cli-checks.zh.mdnew file mode 100644index 00000000..e27d5327--- /dev/null+++ b/changelog/unreleased/2026-08-27-packaged-cli-checks.zh.md@@ -0,0 +1,26 @@+# CI 校验随桌面应用打包的 `penguin` 命令++- **Date:** 2026-08-27+- **Type:** process+- **Scope:** `desktop`, `ci`+- **PR:** [#480](https://github.com/Prism-Shadow/penguin-harness/pull/480)++[English](2026-08-27-packaged-cli-checks.md)++桌面应用把 CLI 一并打包在自身内部——`<app>/bin/penguin` 与 `<app>/bin/penguin.cmd` 以应用自带的+Electron 运行时执行 `<app>/dist/penguin.js`,而所有把 `penguin` 放上 PATH 的途径(deb 的 postinst、+macOS 的符号链接、Windows 的 PATH 条目、AppImage 的包装脚本)指向的都是这两个启动器之一。此前没有任何+检查确认它们仍在打包产物中,本批次补上了这些检查——与+[让应用自行安装该命令](2026-08-27-desktop-installs-cli.zh.md)同批。++## 细节++- `packages/desktop/scripts/verify-packed-cli.mjs` 检查 `electron-builder --dir` 产出的目录树:+ 每个打包出的应用目录都必须带有两个启动器与打包后的 CLI 入口,POSIX 启动器必须可执行,且其中至少+ 一个要能真正运行并报出应用版本号。CI 的 `runtime` job 在 Linux、macOS 与 Windows 上对它本就构建的+ 目录树执行该脚本。+- `packages/desktop/test/launcher.test.ts` 新增 `packaged CLI` 一节,固定这些启动器所依赖、且没有+ 其他地方比对过的约束:`bin/**/*` 保留在 electron-builder 的 `files` 中、`asar` 保持关闭、+ `productName` 与 `linux.executableName` 同启动器脚本所执行的可执行文件名一致、tsup 的入口名与+ `CLI_ENTRY_RELPATH` 一致,以及 deb 模板仍会创建 `/usr/bin/penguin`(绝不覆盖非符号链接)并且只+ 移除它自己创建的链接。diff --git a/packages/desktop/scripts/verify-packed-cli.mjs b/packages/desktop/scripts/verify-packed-cli.mjsnew file mode 100644index 00000000..7b05a6b4--- /dev/null+++ b/packages/desktop/scripts/verify-packed-cli.mjs@@ -0,0 +1,128 @@+/**+ * The packed app carries a working `penguin`.+ *+ * Run after `electron-builder --dir` (CI's runtime job builds exactly that tree). An+ * installed desktop app puts the CLI on the user's PATH: the deb postinst links+ * /usr/bin/penguin at install time, and the other three forms install this same launcher+ * from the shell at launch (src/cli-install.ts). Every one of them resolves <app>/bin/penguin and+ * <app>/dist/penguin.js as plain files inside the packed tree, so `bin/` dropping out of+ * electron-builder's `files`, asar being switched on, or the bundled entry being renamed+ * would ship an app whose `penguin` command does not exist — with nothing else in the+ * build failing. The unit tests pin those couplings in the config files; this checks the+ * tree they produced.+ *+ * Every app directory found is checked for the launchers and the bundled entry. The+ * launcher is then actually run: a cross-architecture bundle that cannot execute on this+ * host is reported and skipped, but at least one has to run and report a version.+ */+import fs from "node:fs";+import path from "node:path";+import { spawnSync } from "node:child_process";+import { fileURLToPath } from "node:url";++const pkgDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+const outDir = path.join(pkgDir, "out");+const version = JSON.parse(fs.readFileSync(path.join(pkgDir, "package.json"), "utf8")).version;++/** Every `resources/app` directory under out/, in both platform layouts. */+function appDirs() {+ if (!fs.existsSync(outDir)) return [];+ const found = [];+ for (const entry of fs.readdirSync(outDir)) {+ // Windows/Linux: out/<name>/resources/app. macOS: out/<name>/<Product>.app/Contents/Resources/app.+ const flat = path.join(outDir, entry, "resources", "app");+ if (fs.existsSync(flat)) found.push(flat);+ const macRoot = path.join(outDir, entry);+ if (!fs.statSync(macRoot).isDirectory()) continue;+ for (const inner of fs.readdirSync(macRoot)) {+ if (!inner.endsWith(".app")) continue;+ const bundled = path.join(macRoot, inner, "Contents", "Resources", "app");+ if (fs.existsSync(bundled)) found.push(bundled);+ }+ }+ return found;+}++/**+ * Whether `penguin --version` named this build. The CLI prints its identity rather than a+ * bare version number: a release build prints `v<version>`, while a build from a checkout+ * prints git's description of it — `v<version>-3-g<sha>` when a tag is reachable, and+ * `v<version>-g<sha>` when none is, which is what a shallow CI checkout produces (core's+ * composeDescribe assembles both). Every form is `v<version>` alone or carrying a `-`+ * suffix; a launcher that ran some other bundle, or printed anything but a version, is not.+ */+function namesThisBuild(printed) {+ return printed === `v${version}` || printed.startsWith(`v${version}-`);+}++const problems = [];+let ran = 0;++const dirs = appDirs();+if (dirs.length === 0) {+ console.error(+ `[verify-packed-cli] no packed app found under ${outDir} — run \`electron-builder --dir\` first.`,+ );+ process.exit(1);+}++for (const app of dirs) {+ for (const rel of ["bin/penguin", "bin/penguin.cmd", "dist/penguin.js"]) {+ const file = path.join(app, ...rel.split("/"));+ if (!fs.existsSync(file)) {+ problems.push(`${app}: ${rel} is missing from the packed app.`);+ continue;+ }+ // The POSIX launcher is exec'd directly by the /usr/bin/penguin symlink a deb install+ // creates; writeFileSync's mode is masked by the umask, hence the explicit chmod in+ // scripts/build-assets.mjs that this pins.+ if (process.platform !== "win32" && rel === "bin/penguin") {+ if ((fs.statSync(file).mode & 0o111) === 0)+ problems.push(`${app}: ${rel} is not executable.`);+ }+ }++ const launcher =+ process.platform === "win32"+ ? path.join(app, "bin", "penguin.cmd")+ : path.join(app, "bin", "penguin");+ if (!fs.existsSync(launcher)) continue;+ // Node has refused to exec .cmd without a shell since the CVE-2024-27980 fix; the path+ // is this script's own, not user input.+ const result =+ process.platform === "win32"+ ? spawnSync(process.env.ComSpec ?? "cmd.exe", ["/c", launcher, "--version"], {+ encoding: "utf8",+ })+ : spawnSync(launcher, ["--version"], { encoding: "utf8" });+ const printed = (result.stdout ?? "").trim();+ if (result.status !== 0) {+ // A bundle for another architecture cannot run here; that is not a packaging fault, so+ // this alone does not fail the check — the `ran === 0` guard below does, once no bundle+ // has run. The reason is printed either way, because it is the diagnosis when it does.+ const why = result.error?.message ?? `exit ${result.status}: ${(result.stderr ?? "").trim()}`;+ console.log(`[verify-packed-cli] ${app}: launcher did not run on this host (${why}).`);+ continue;+ }+ if (!namesThisBuild(printed)) {+ problems.push(+ `${app}: penguin --version printed ${JSON.stringify(printed)}, want v${version} or v${version}-<git description>.`,+ );+ continue;+ }+ ran += 1;+ console.log(`[verify-packed-cli] ${app}: penguin --version -> ${printed}`);+}++if (ran === 0 && problems.length === 0) {+ problems.push(`none of the ${dirs.length} packed app(s) produced a runnable penguin launcher.`);+}++if (problems.length > 0) {+ console.error("[verify-packed-cli] failed:\n");+ for (const p of problems) console.error(` - ${p}`);+ console.error("");+ process.exit(1);+}++console.log(`[verify-packed-cli] ok: ${ran}/${dirs.length} packed app(s) ran their bundled CLI.`);diff --git a/packages/desktop/src/cli-install.ts b/packages/desktop/src/cli-install.tsindex 5c218ea4..79736d47 100644--- a/packages/desktop/src/cli-install.ts+++ b/packages/desktop/src/cli-install.ts@@ -1,22 +1,32 @@/**- * "Install 'penguin' Command" — PATH exposure for the bundled CLI launcher- * (<app>/bin/penguin, generated at stage time; see launcher.ts).+ * The `penguin` command an installed desktop app provides: PATH exposure for the bundled+ * CLI launcher (`<app>/bin/penguin`, generated at stage time; see launcher.ts).*- * Per platform (deb is absent on purpose — its postinst ships /usr/bin/penguin, see+ * It installs itself, at every launch, without asking — the CLI is part of what the app+ * is, and an update that left a stale command behind would point an old client at a new+ * server. Per platform (deb is absent on purpose: its postinst ships /usr/bin/penguin, see* build/linux/after-install.tpl):- * - macOS: symlink /usr/local/bin/penguin → <app>/bin/penguin; on permission errors,- * escalate ONCE via osascript "with administrator privileges".- * - Windows: append <app>\bin to the user PATH (HKCU\Environment) via reg.exe,- * idempotently (read + compare first); new terminals pick it up.- * - Linux AppImage: write an executable ~/.local/bin/penguin wrapper that runs the- * AppImage itself as Node (see launcher.ts appImageWrapperScript).+ * - macOS: symlink /usr/local/bin/penguin → <app>/bin/penguin. The unprivileged write is+ * tried first and an administrator prompt appears only where it actually fails, which on+ * a Mac without Homebrew is where /usr/local/bin has to be created.+ * - Windows: append <app>\bin to the user PATH (HKCU\Environment) via reg.exe, idempotently+ * and append-only; new terminals pick it up. No elevation is involved.+ * - Linux AppImage: write an executable ~/.local/bin/penguin wrapper that runs the AppImage+ * itself as Node (see launcher.ts appImageWrapperScript).*- * Everything is native UI (menu item + dialogs) in English: the main process stays- * outside the web app's i18n, and per the design the desktop shell talks to the page- * only through the server's HTTP API — never a private IPC channel.+ * Two rules follow from doing this silently, both enforced in cli-link.ts:+ * - A `penguin` this app did not write is never replaced. `install.sh` puts its own symlink+ * at the very path the AppImage form uses, and the user may have one from anywhere else.+ * Such a target is skipped and the reason recorded.+ * - Nothing is installed from a location that will not persist — a macOS bundle still on+ * its dmg, or one Gatekeeper is running translocated — because the link would dangle the+ * moment the mount goes away. The next launch from /Applications installs it.+ *+ * Everything is native UI (menu item + dialogs) in English: the main process stays outside+ * the web app's i18n, and per the design the desktop shell talks to the page only through+ * the server's HTTP API — never a private IPC channel.*/import { execFile } from "node:child_process";-import fs from "node:fs";import os from "node:os";import path from "node:path";import { promisify } from "node:util";@@ -29,9 +39,24 @@ import {mergeWindowsUserPath,} from "./launcher.js";import type { CliInstallKind } from "./launcher.js";+import {+ isVolatileAppLocation,+ readCliCommandState,+ syncSymlink,+ syncWrapper,+ writeCliCommandState,+} from "./cli-link.js";+import type { CliCommandState, SyncResult } from "./cli-link.js";const execFileAsync = promisify(execFile);+/** The macOS PATH directory. Fixed: it is on the default PATH of every Mac. */+const MAC_LINK_DIR = "/usr/local/bin";++function log(line: string): void {+ process.stdout.write(`[cli] ${line}\n`);+}+/** The launcher directory inside the packaged app. */function binDir(): string {return path.join(app.getAppPath(), "bin");@@ -46,70 +71,76 @@ export function currentCliInstallKind(): CliInstallKind | null {});}-function showResult(win: BrowserWindow | null, ok: boolean, detail: string): void {- const opts = {- type: ok ? ("info" as const) : ("error" as const),- title: "PenguinHarness",- message: ok- ? "The 'penguin' command is installed."- : "Could not install the 'penguin' command.",- detail,- };- void (win !== null ? dialog.showMessageBox(win, opts) : dialog.showMessageBox(opts));+interface Attempt {+ ok: boolean;+ result: NonNullable<CliCommandState["lastResult"]>;+ detail: string;+ /** The user dismissed the administrator prompt: stop attempting automatically. */+ declined?: boolean;}-/** macOS: /usr/local/bin/penguin symlink, escalating once via osascript on EACCES/EPERM. */-async function installDarwin(win: BrowserWindow | null): Promise<void> {- const target = path.join(binDir(), "penguin");- const linkDir = "/usr/local/bin";- const link = path.join(linkDir, "penguin");+/** macOS: /usr/local/bin/penguin symlink, escalating via osascript only on EACCES/EPERM. */+async function attemptDarwin(force: boolean): Promise<Attempt> {+ const appPath = app.getAppPath();+ if (isVolatileAppLocation(appPath, process.platform)) {+ return {+ ok: false,+ result: "deferred",+ detail: `The app is running from ${appPath}, which will not stay there. Move PenguinHarness to your Applications folder and open it from there; the command installs itself on that launch.`,+ };+ }+ const desired = path.join(binDir(), "penguin");+ const link = path.join(MAC_LINK_DIR, "penguin");try {- fs.mkdirSync(linkDir, { recursive: true });- fs.rmSync(link, { force: true });- fs.symlinkSync(target, link);+ const synced = syncSymlink(link, desired, force);+ if (synced.action === "current") return { ok: true, result: "current", detail: synced.detail };+ if (synced.action === "skipped") return { ok: false, result: "foreign", detail: synced.detail };} catch (err) {const code = (err as NodeJS.ErrnoException).code;if (code !== "EACCES" && code !== "EPERM") {- showResult(win, false, String(err));- return;+ return { ok: false, result: "failed", detail: String(err) };}// Privileged retry — the common path on a Mac without Homebrew, where /usr/local/bin// does not exist and creating it needs root. The command's quoting is the generator's// job (launcher.ts): the bundle path comes off disk and may hold an apostrophe.try {- await execFileAsync("osascript", ["-e", adminSymlinkAppleScript(target, link)]);+ await execFileAsync("osascript", ["-e", adminSymlinkAppleScript(desired, link)]);} catch (escalated) {- showResult(- win,- false,- `Administrator authorization failed or was cancelled.\n${String(escalated)}`,- );- return;+ return {+ ok: false,+ result: "failed",+ declined: true,+ detail: `Administrator authorization was cancelled or failed, so ${link} was not created. Use "Install 'penguin' Command…" in the application menu to try again.\n${String(escalated)}`,+ };}}- showResult(- win,- true,- `${link} now points at the app's bundled CLI. Run 'penguin' from any terminal.`,- );+ return {+ ok: true,+ result: "installed",+ detail: `${link} now points at the app's bundled CLI. Run 'penguin' from any terminal.`,+ };}-/** Windows: idempotent HKCU\Environment PATH append via reg.exe. */-async function installWindows(win: BrowserWindow | null): Promise<void> {+/** Windows: idempotent, append-only HKCU\Environment PATH entry via reg.exe. */+async function attemptWindows(): Promise<Attempt> {const dir = binDir();let current: string | null = null;try {const { stdout } = await execFileAsync("reg", ["query", "HKCU\\Environment", "/v", "Path"]);// Output line: " Path REG_EXPAND_SZ C:\foo;C:\bar"const m = /^\s*Path\s+REG(?:_EXPAND)?_SZ\s+(.*)$/im.exec(stdout);- if (m) current = m[1]!.trim();+ if (m === null) {+ // The value is there and this output does not name it. Writing the merge now would+ // put the app's directory in place of the whole user PATH, so nothing is written.+ return { ok: false, result: "failed", detail: `Could not read the user PATH:\n${stdout}` };+ }+ current = m[1]!.trim();} catch {current = null; // No user Path value yet.}const merged = mergeWindowsUserPath(current, dir);if (merged === null) {- showResult(win, true, `${dir} is already on your PATH. Run 'penguin' from any terminal.`);- return;+ return { ok: true, result: "current", detail: `${dir} is already on your PATH.` };}try {// REG_EXPAND_SZ keeps any %VAR% entries of the existing value expandable.@@ -125,96 +156,141 @@ async function installWindows(win: BrowserWindow | null): Promise<void> {"/f",]);} catch (err) {- showResult(win, false, String(err));- return;+ return { ok: false, result: "failed", detail: String(err) };}- showResult(- win,- true,- `${dir} was added to your user PATH. Open a NEW terminal (existing ones keep the old PATH) and run 'penguin'.`,- );+ // Nothing on disk is touched here: the entry is appended, so another `penguin` earlier in+ // PATH keeps winning and no other software's entry is rewritten.+ return {+ ok: true,+ result: "installed",+ detail: `${dir} was added to your user PATH. Open a NEW terminal (existing ones keep the old PATH) and run 'penguin'.`,+ };}/** Linux AppImage: executable ~/.local/bin/penguin wrapper invoking the AppImage as Node. */-function installAppImage(win: BrowserWindow | null): void {+function attemptAppImage(force: boolean): Attempt {const appImage = process.env.APPIMAGE;if (!appImage) {- showResult(win, false, "APPIMAGE is not set; this build cannot install the command.");- return;+ return {+ ok: false,+ result: "failed",+ detail: "APPIMAGE is not set; this build cannot install the command.",+ };}- const dir = path.join(os.homedir(), ".local", "bin");- const wrapper = path.join(dir, "penguin");+ const target = path.join(os.homedir(), ".local", "bin", "penguin");let script: string;try {script = appImageWrapperScript(appImage);} catch (err) {- showResult(win, false, String(err));- return;+ return { ok: false, result: "failed", detail: String(err) };}+ let synced: SyncResult;try {- fs.mkdirSync(dir, { recursive: true });- // Written to a temp file and renamed over the wrapper: a failed write leaves the previous- // command in place instead of a truncated script on PATH. chmod before the rename, since- // writeFileSync's mode is masked by the umask.- const tmp = `${wrapper}.tmp`;- fs.writeFileSync(tmp, script, { mode: 0o755, flush: true });- fs.chmodSync(tmp, 0o755);- fs.renameSync(tmp, wrapper);+ synced = syncWrapper(target, script, force);} catch (err) {- showResult(win, false, String(err));- return;+ return { ok: false, result: "failed", detail: String(err) };}- showResult(- win,- true,- `${wrapper} now runs the CLI bundled in this AppImage. Make sure ~/.local/bin is on your PATH (most distributions add it at login), then run 'penguin' from a new terminal. Re-run this menu item if you move the AppImage.`,- );+ if (synced.action === "current") return { ok: true, result: "current", detail: synced.detail };+ if (synced.action === "skipped") return { ok: false, result: "foreign", detail: synced.detail };+ return {+ ok: true,+ result: "installed",+ detail: `${target} now runs the CLI bundled in this AppImage. Make sure ~/.local/bin is on your PATH (most distributions add it at login), then run 'penguin' from a new terminal.`,+ };}-/** Runs the platform installer (menu item and first-launch offer both land here). */-export async function installCliCommand(win: BrowserWindow | null): Promise<void> {- switch (currentCliInstallKind()) {+async function attempt(kind: CliInstallKind, force: boolean): Promise<Attempt> {+ switch (kind) {case "darwin":- await installDarwin(win);- return;+ return await attemptDarwin(force);case "windows":- await installWindows(win);- return;+ return await attemptWindows();case "appimage":- installAppImage(win);- return;- case null:- showResult(win, false, "This build has no bundled CLI to install (development run).");+ return attemptAppImage(force);}}+/** The record every attempt leaves; `declined` is the only field that changes later behaviour. */+function record(outcome: Attempt): void {+ writeCliCommandState(app.getPath("userData"), {+ version: 1,+ decision: outcome.declined === true ? "declined" : undefined,+ lastResult: outcome.result,+ detail: outcome.detail,+ at: new Date().toISOString(),+ });+}+/**- * One-time first-launch offer: asks once per installation whether to install the- * command, and never again (the app menu keeps the entry point available). The- * "offered" flag persists under userData next to the shell's other state files.+ * Every launch: install the command, repair it, or record why neither happened. Cheap when+ * there is nothing to do — one lstat, or one `reg query` on Windows — and it runs again+ * next launch, which is what repairs a link left dangling by a moved or updated app.*/-export async function maybeOfferCliInstall(win: BrowserWindow | null): Promise<void> {- if (currentCliInstallKind() === null) return;- const flag = path.join(app.getPath("userData"), "cli-install-offered");+export async function ensureCliCommand(): Promise<void> {+ const kind = currentCliInstallKind();+ if (kind === null) return;try {- if (fs.existsSync(flag)) return;- fs.mkdirSync(path.dirname(flag), { recursive: true });- fs.writeFileSync(flag, `${new Date().toISOString()}\n`);- } catch {- return; // Unreadable/unwritable userData: skip rather than re-offer forever.+ // A dismissed administrator prompt is a decision and is respected; nothing else here+ // is. In particular the pre-0.2.7 `cli-install-offered` marker is not read at all —+ // it was written before its dialog was answered, so it records the question, not a+ // decline (writeCliCommandState removes it).+ if (readCliCommandState(app.getPath("userData")).decision === "declined") {+ log("skipped: the administrator prompt was declined; use the application menu to retry");+ return;+ }+ const outcome = await attempt(kind, false);+ record(outcome);+ log(`${outcome.result}: ${outcome.detail.split("\n")[0]}`);+ } catch (err) {+ // Never let this stop a launch.+ log(`failed: ${String(err)}`);}+}++function showResult(win: BrowserWindow | null, ok: boolean, detail: string): void {const opts = {- type: "question" as const,+ type: ok ? ("info" as const) : ("error" as const),title: "PenguinHarness",- message: "Install the 'penguin' command line tool?",- detail:- "Makes the CLI bundled with this app available in your terminal. You can do this later from the application menu: Install 'penguin' Command.",- buttons: ["Install", "Not Now"],- defaultId: 0,- cancelId: 1,+ message: ok+ ? "The 'penguin' command is installed."+ : "Could not install the 'penguin' command.",+ detail,};- const { response } = await (win !== null- ? dialog.showMessageBox(win, opts)- : dialog.showMessageBox(opts));- if (response === 0) await installCliCommand(win);+ void (win !== null ? dialog.showMessageBox(win, opts) : dialog.showMessageBox(opts));+}++/**+ * The menu item. Same install, but it reports every outcome and it is the one place a+ * `penguin` this app did not write can be replaced — with the user looking at what is+ * about to be overwritten. Invoking it also clears a previously declined prompt.+ */+export async function installCliCommand(win: BrowserWindow | null): Promise<void> {+ const kind = currentCliInstallKind();+ if (kind === null) {+ showResult(win, false, "This build has no bundled CLI to install (development run).");+ return;+ }+ let outcome = await attempt(kind, false);+ if (outcome.result === "foreign") {+ const opts = {+ type: "warning" as const,+ title: "PenguinHarness",+ message: "Something else already provides the 'penguin' command.",+ detail: `${outcome.detail}\n\nReplace it with this app's command? The file it replaces is not backed up.`,+ buttons: ["Replace", "Cancel"],+ defaultId: 1,+ cancelId: 1,+ };+ const { response } = await (win !== null+ ? dialog.showMessageBox(win, opts)+ : dialog.showMessageBox(opts));+ if (response !== 0) {+ record(outcome);+ showResult(win, false, `Left the existing command untouched.\n${outcome.detail}`);+ return;+ }+ outcome = await attempt(kind, true);+ }+ record(outcome);+ showResult(win, outcome.ok, outcome.detail);}diff --git a/packages/desktop/src/cli-link.ts b/packages/desktop/src/cli-link.tsnew file mode 100644index 00000000..079c3c60--- /dev/null+++ b/packages/desktop/src/cli-link.ts@@ -0,0 +1,245 @@+/**+ * The disk half of the `penguin` PATH entry: what sits at the target, whether this app put+ * it there, and how to write ours without destroying anyone else's. Pure `node:fs` and no+ * Electron import, so it unit-tests against real temporary directories rather than mocks.+ *+ * The install runs automatically at startup (see cli-install.ts), which removes the user's+ * chance to object to it — so the one rule this module exists to enforce is that a+ * `penguin` this app did not write is never touched. `install.sh` puts its own symlink at+ * exactly the path the AppImage form uses (`~/.local/bin/penguin`), and a user may have a+ * `penguin` from npm, Homebrew or their own hand anywhere on PATH. Every one of those is+ * classified `foreign` and left alone; the reason is recorded in the state file so support+ * can see why no command appeared.+ */+import fs from "node:fs";+import path from "node:path";+import { LAUNCHER_MARKER } from "./launcher.js";++/**+ * What the target holds, relative to what this app wants there.+ * - `absent` — nothing at the path; write freely.+ * - `current` — ours, and already pointing at this app: nothing to do.+ * - `ours` — ours, but stale (a dangling link, or an older/moved app): repair it.+ * - `foreign` — someone else's; never written over automatically.+ */+export type TargetKind = "absent" | "current" | "ours" | "foreign";++export interface TargetStatus {+ kind: TargetKind;+ /** One line naming what was found; recorded in the state file and shown by the menu item. */+ detail: string;+}++/**+ * Reading a file to look for the marker is bounded: the path is on PATH, so it could hold+ * anything, including a large binary from an unrelated install.+ */+const MAX_MARKER_READ_BYTES = 64 * 1024;++/**+ * The packaged layout every bundled launcher sits in — `<app>/bin/penguin`, where `<app>`+ * is `Contents/Resources/app` in a macOS bundle and `resources/app` in a Linux tree. It+ * identifies a link this app wrote even when the link dangles, which is the case the DMG+ * launch and a moved app both produce and the case where the file itself cannot be read.+ */+const BUNDLED_LAUNCHER_PATH = /(?:^|\/)[Rr]esources\/app\/bin\/penguin$/;++/** Whether `file` is a launcher this app generated (marker text shipped since 0.2.2). */+function hasLauncherMarker(file: string): boolean {+ try {+ const stat = fs.statSync(file);+ if (!stat.isFile() || stat.size > MAX_MARKER_READ_BYTES) return false;+ return fs.readFileSync(file, "utf8").includes(LAUNCHER_MARKER);+ } catch {+ return false;+ }+}++/**+ * The macOS form: a symlink at `target` that should point at `desired`+ * (`<app>/bin/penguin`). Anything that is not a symlink is foreign — this app has never+ * written a regular file here, so a regular file is someone else's `penguin`.+ */+export function inspectSymlinkTarget(target: string, desired: string): TargetStatus {+ let link: fs.Stats;+ try {+ link = fs.lstatSync(target);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {+ return { kind: "absent", detail: `${target} does not exist` };+ }+ return { kind: "foreign", detail: `${target} could not be read: ${String(err)}` };+ }+ if (!link.isSymbolicLink()) {+ return { kind: "foreign", detail: `${target} is not a symlink this app wrote` };+ }+ const value = fs.readlinkSync(target);+ if (value === desired) return { kind: "current", detail: `${target} already points at this app` };+ if (BUNDLED_LAUNCHER_PATH.test(value) || hasLauncherMarker(target)) {+ return { kind: "ours", detail: `${target} points at ${value}, a stale copy of this app` };+ }+ return { kind: "foreign", detail: `${target} points at ${value}, which this app did not write` };+}++/**+ * The AppImage form: a regular file at `target` holding the generated wrapper. A symlink+ * here is foreign — `install.sh` writes exactly that, at exactly this path.+ */+export function inspectWrapperTarget(target: string, desired: string): TargetStatus {+ let entry: fs.Stats;+ try {+ entry = fs.lstatSync(target);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {+ return { kind: "absent", detail: `${target} does not exist` };+ }+ return { kind: "foreign", detail: `${target} could not be read: ${String(err)}` };+ }+ if (entry.isSymbolicLink()) {+ const value = fs.readlinkSync(target);+ return {+ kind: "foreign",+ detail: `${target} is a symlink to ${value}, which this app did not write`,+ };+ }+ if (!entry.isFile() || !hasLauncherMarker(target)) {+ return { kind: "foreign", detail: `${target} is not a launcher this app wrote` };+ }+ const current = fs.readFileSync(target, "utf8");+ if (current === desired) {+ return { kind: "current", detail: `${target} already runs this app's CLI` };+ }+ return { kind: "ours", detail: `${target} runs a different location of this app` };+}++/** Creates `target` as a symlink to `desired`, replacing whatever is there. Throws on failure. */+export function writeSymlink(target: string, desired: string): void {+ fs.mkdirSync(path.dirname(target), { recursive: true });+ fs.rmSync(target, { force: true });+ fs.symlinkSync(desired, target);+}++/**+ * Writes the wrapper script to `target`, executable. Written to a temporary file and+ * renamed into place: a failed write leaves the previous command on PATH rather than a+ * truncated script. chmod before the rename, since writeFileSync's mode is masked by the+ * umask.+ */+export function writeWrapper(target: string, script: string): void {+ fs.mkdirSync(path.dirname(target), { recursive: true });+ const tmp = `${target}.tmp`;+ fs.writeFileSync(tmp, script, { mode: 0o755, flush: true });+ fs.chmodSync(tmp, 0o755);+ fs.renameSync(tmp, target);+}++/**+ * Whether the app is running from somewhere it will not still be next week. Installing+ * from one bakes a path into the PATH entry that dies with the mount, and nothing would+ * ever notice: `/Volumes/...` is the dmg the user has not copied to Applications yet, and+ * `AppTranslocation` is where Gatekeeper runs a quarantined bundle from — the exact state+ * the download page's `xattr -rd com.apple.quarantine` step exists to clear.+ */+export function isVolatileAppLocation(appPath: string, platform: NodeJS.Platform): boolean {+ if (platform !== "darwin") return false;+ return appPath.startsWith("/Volumes/") || appPath.includes("/AppTranslocation/");+}++/**+ * What one pass over the target did.+ * - `current` — already ours and pointing here; nothing was written.+ * - `skipped` — someone else's `penguin` is there and was left exactly as it was.+ * - `installed` — ours was written (fresh, or repairing a stale or dangling one).+ */+export interface SyncResult {+ action: "current" | "skipped" | "installed";+ /** The classification that produced the action, in one line. */+ detail: string;+}++/**+ * The whole disk-side decision, in one place so the automatic path and the menu item+ * cannot drift apart. `force` is reachable only from the menu item, where the user has+ * just been shown what would be replaced — the automatic path always passes false, which+ * is what makes "never overwrite a `penguin` this app did not write" a property of the+ * code rather than of a caller remembering to check.+ */+function sync(status: TargetStatus, force: boolean, write: () => void): SyncResult {+ if (status.kind === "current") return { action: "current", detail: status.detail };+ if (status.kind === "foreign" && !force) return { action: "skipped", detail: status.detail };+ write();+ return { action: "installed", detail: status.detail };+}++/** macOS. Propagates whatever writeSymlink throws, so the caller can escalate on EACCES/EPERM. */+export function syncSymlink(target: string, desired: string, force: boolean): SyncResult {+ return sync(inspectSymlinkTarget(target, desired), force, () => writeSymlink(target, desired));+}++/** Linux AppImage. */+export function syncWrapper(target: string, script: string, force: boolean): SyncResult {+ return sync(inspectWrapperTarget(target, script), force, () => writeWrapper(target, script));+}++// --- recorded state ---------------------------------------------------------++/**+ * What the last attempt did. Only `decision` changes behaviour; the rest is a record for+ * whoever has to explain why no `penguin` appeared.+ */+export interface CliCommandState {+ version: 1;+ /**+ * Set only by an explicit act of the user: declining the macOS administrator prompt. It+ * stops the automatic attempt for good; the menu item clears it, which is the one way+ * back. Absent means no decision has been made, which is not the same as a skip.+ */+ decision?: "declined";+ lastResult?: "installed" | "current" | "foreign" | "deferred" | "failed";+ detail?: string;+ at?: string;+}++/** Where the state lives, next to the shell's other files under userData. */+export function stateFilePath(userData: string): string {+ return path.join(userData, "cli-command.json");+}++/**+ * The pre-0.2.7 marker. It was written BEFORE the offer dialog, so it records that the+ * question was asked and not what was answered — it cannot be read as a decline, and is+ * removed rather than migrated.+ */+export function legacyOfferedFlagPath(userData: string): string {+ return path.join(userData, "cli-install-offered");+}++export function readCliCommandState(userData: string): CliCommandState {+ try {+ const parsed: unknown = JSON.parse(fs.readFileSync(stateFilePath(userData), "utf8"));+ if (typeof parsed !== "object" || parsed === null) return { version: 1 };+ const state = parsed as CliCommandState;+ // Only the field that gates behaviour is validated; an unknown value must not read as+ // a decline and strand the command.+ return {+ ...state,+ version: 1,+ decision: state.decision === "declined" ? "declined" : undefined,+ };+ } catch {+ return { version: 1 };+ }+}++export function writeCliCommandState(userData: string, state: CliCommandState): void {+ try {+ fs.mkdirSync(userData, { recursive: true });+ fs.writeFileSync(stateFilePath(userData), `${JSON.stringify(state, null, 2)}\n`);+ // TODO(compat): drop this line once no 0.2.2–0.2.6 install can still upgrade into this+ // build — it only clears a marker those versions wrote. Owner: whoever prepares 0.3.0.+ fs.rmSync(legacyOfferedFlagPath(userData), { force: true });+ } catch {+ // An unwritable userData must not stop the install itself; the next launch re-derives+ // everything it needs from the target on disk.+ }+}diff --git a/packages/desktop/src/launcher.ts b/packages/desktop/src/launcher.tsindex db3469b5..876bddef 100644--- a/packages/desktop/src/launcher.ts+++ b/packages/desktop/src/launcher.ts@@ -13,6 +13,13 @@/** CLI bundle inside the app directory, emitted by tsup alongside the shell (asar off). */export const CLI_ENTRY_RELPATH = "dist/penguin.js";+/**+ * Present in every launcher script below, and shipped unchanged in every desktop release+ * since 0.2.2 — which is what lets cli-link.ts recognise a `penguin` this app wrote,+ * including one written by an older version, and leave anyone else's alone.+ */+export const LAUNCHER_MARKER = "penguin CLI launcher (generated by";+/*** Platform executable names, fixed by electron-builder.yml: productName PenguinHarness* (macOS bundle executable and Windows .exe) and linux.executableName penguin-harness.diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.tsindex 5c458c6e..afa15196 100644--- a/packages/desktop/src/main.ts+++ b/packages/desktop/src/main.ts@@ -34,7 +34,7 @@ import { resolveRoot } from "@prismshadow/penguin-core";import { liveServerLock } from "@prismshadow/penguin-server/lock";import { appIdentity, desktopDataRoot } from "./app-identity.js";import { resolveWindowIcon } from "./app-icon.js";-import { installCliCommand, maybeOfferCliInstall, currentCliInstallKind } from "./cli-install.js";+import { installCliCommand, ensureCliCommand, currentCliInstallKind } from "./cli-install.js";import { applyLoginShellEnv } from "./login-shell-env.js";import { installAppMenu } from "./menu.js";import { startEmbeddedServer, stopEmbeddedServer } from "./server-process.js";@@ -285,9 +285,10 @@ if (!app.requestSingleInstanceLock()) {});initUpdater(() => win);await boot();- // First launch only: offer the 'penguin' command once; the menu entry remains.- // Skipped in smoke mode — a modal dialog would hang the automated run.- if (process.env.PENGUIN_DESKTOP_SMOKE !== "1") await maybeOfferCliInstall(win);+ // Install or repair the bundled 'penguin' command. Runs every launch: that is what+ // carries it across an update and repairs a link a moved app left dangling. Skipped+ // in smoke mode — the macOS administrator prompt would hang the automated run.+ if (process.env.PENGUIN_DESKTOP_SMOKE !== "1") await ensureCliCommand();})().catch((err) => fatal(`${app.name} failed to start.`, err)),);}diff --git a/packages/desktop/test/cli-link.test.ts b/packages/desktop/test/cli-link.test.tsnew file mode 100644index 00000000..c0f725bc--- /dev/null+++ b/packages/desktop/test/cli-link.test.ts@@ -0,0 +1,292 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import {+ inspectSymlinkTarget,+ inspectWrapperTarget,+ isVolatileAppLocation,+ legacyOfferedFlagPath,+ readCliCommandState,+ stateFilePath,+ syncSymlink,+ syncWrapper,+ writeCliCommandState,+} from "../src/cli-link.js";+import { appImageWrapperScript, posixLauncherScript } from "../src/launcher.js";++/**+ * A real directory tree, not a mocked fs: the whole point of these functions is what they+ * do to symlinks, modes and dangling targets, none of which a mock would reproduce.+ */+let tmp: string;++/**+ * Tests whose assertion is a POSIX fact: the target a dangling symlink stores (Windows+ * rewrites it into a backslash path that no longer names the packaged layout), and the exec+ * bit, which Windows does not carry. Both belong to forms that only run on macOS and Linux.+ */+const itPosix = it.skipIf(process.platform === "win32");++beforeEach(() => {+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-cli-link-"));+});++afterEach(() => {+ fs.rmSync(tmp, { recursive: true, force: true });+});++/** A packaged app tree with the launcher the installers point at. */+function packApp(name: string): string {+ const appDir = path.join(tmp, name, "Contents", "Resources", "app");+ fs.mkdirSync(path.join(appDir, "bin"), { recursive: true });+ const launcher = path.join(appDir, "bin", "penguin");+ fs.writeFileSync(launcher, posixLauncherScript(), { mode: 0o755 });+ return launcher;+}++describe("syncSymlink (the macOS form)", () => {+ it("installs when nothing is there", () => {+ const desired = packApp("PenguinHarness.app");+ const link = path.join(tmp, "usr-local-bin", "penguin");++ expect(syncSymlink(link, desired, false)).toEqual({+ action: "installed",+ detail: `${link} does not exist`,+ });+ expect(fs.readlinkSync(link)).toBe(desired);+ });++ it("does nothing when it already points at this app", () => {+ const desired = packApp("PenguinHarness.app");+ const link = path.join(tmp, "bin", "penguin");+ syncSymlink(link, desired, false);+ const before = fs.lstatSync(link).mtimeMs;++ expect(syncSymlink(link, desired, false).action).toBe("current");+ expect(fs.lstatSync(link).mtimeMs).toBe(before);+ });++ itPosix("repairs a link left dangling by a moved or updated app", () => {+ // What a launch from the dmg used to leave behind, and what an app moved out of a+ // previous location leaves behind: the link is ours, and its target is gone.+ const link = path.join(tmp, "bin", "penguin");+ fs.mkdirSync(path.dirname(link), { recursive: true });+ fs.symlinkSync(+ "/Volumes/PenguinHarness/PenguinHarness.app/Contents/Resources/app/bin/penguin",+ link,+ );+ expect(fs.existsSync(link)).toBe(false); // dangling+ const desired = packApp("PenguinHarness.app");++ expect(syncSymlink(link, desired, false).action).toBe("installed");+ expect(fs.readlinkSync(link)).toBe(desired);+ });++ it("repairs a link pointing at an older install of this app", () => {+ const stale = packApp("Old.app");+ const link = path.join(tmp, "bin", "penguin");+ fs.mkdirSync(path.dirname(link), { recursive: true });+ fs.symlinkSync(stale, link);+ const desired = packApp("PenguinHarness.app");++ expect(syncSymlink(link, desired, false).action).toBe("installed");+ expect(fs.readlinkSync(link)).toBe(desired);+ });++ it("never replaces a penguin this app did not write", () => {+ const desired = packApp("PenguinHarness.app");+ const link = path.join(tmp, "bin", "penguin");+ fs.mkdirSync(path.dirname(link), { recursive: true });+ // A regular file: an npm global install, a Homebrew shim, the user's own script.+ fs.writeFileSync(link, "#!/bin/sh\necho not ours\n", { mode: 0o755 });++ const result = syncSymlink(link, desired, false);+ expect(result.action).toBe("skipped");+ expect(result.detail).toContain("not a symlink this app wrote");+ expect(fs.readFileSync(link, "utf8")).toBe("#!/bin/sh\necho not ours\n");+ expect(fs.lstatSync(link).isSymbolicLink()).toBe(false);+ });++ it("never follows a foreign symlink either", () => {+ const desired = packApp("PenguinHarness.app");+ const theirs = path.join(tmp, "dot-penguin", "bin", "penguin");+ fs.mkdirSync(path.dirname(theirs), { recursive: true });+ fs.writeFileSync(theirs, "#!/bin/sh\necho tarball\n", { mode: 0o755 });+ const link = path.join(tmp, "bin", "penguin");+ fs.mkdirSync(path.dirname(link), { recursive: true });+ fs.symlinkSync(theirs, link);++ expect(syncSymlink(link, desired, false).action).toBe("skipped");+ expect(fs.readlinkSync(link)).toBe(theirs);+ });++ it("replaces a foreign command only when forced, which only the menu item does", () => {+ const desired = packApp("PenguinHarness.app");+ const link = path.join(tmp, "bin", "penguin");+ fs.mkdirSync(path.dirname(link), { recursive: true });+ fs.writeFileSync(link, "#!/bin/sh\necho not ours\n", { mode: 0o755 });++ expect(syncSymlink(link, desired, true).action).toBe("installed");+ expect(fs.readlinkSync(link)).toBe(desired);+ });+});++describe("syncWrapper (the Linux AppImage form)", () => {+ const script = appImageWrapperScript("/home/u/Apps/penguin-desktop-linux-x86_64.AppImage");++ it("installs a wrapper when nothing is there", () => {+ const target = path.join(tmp, "local-bin", "penguin");++ expect(syncWrapper(target, script, false).action).toBe("installed");+ expect(fs.readFileSync(target, "utf8")).toBe(script);+ // Written through a temporary file; it must not be left behind.+ expect(fs.existsSync(`${target}.tmp`)).toBe(false);+ });++ itPosix("installs it executable, or nothing on PATH can run it", () => {+ const target = path.join(tmp, "local-bin", "penguin");+ syncWrapper(target, script, false);++ expect(fs.statSync(target).mode & 0o111).not.toBe(0);+ });++ it("does nothing when the wrapper already runs this AppImage", () => {+ const target = path.join(tmp, "local-bin", "penguin");+ syncWrapper(target, script, false);++ expect(syncWrapper(target, script, false).action).toBe("current");+ });++ it("rewrites its own wrapper when the AppImage moved", () => {+ const target = path.join(tmp, "local-bin", "penguin");+ syncWrapper(target, appImageWrapperScript("/old/path.AppImage"), false);++ expect(syncWrapper(target, script, false).action).toBe("installed");+ expect(fs.readFileSync(target, "utf8")).toBe(script);+ });++ it("never replaces the symlink install.sh puts at this exact path", () => {+ // install.sh does `ln -sf ~/.penguin/bin/penguin ~/.local/bin/penguin`, unconditionally,+ // at the very path this form uses. Ours is the side that has to give way.+ const theirs = path.join(tmp, "dot-penguin", "bin", "penguin");+ fs.mkdirSync(path.dirname(theirs), { recursive: true });+ fs.writeFileSync(theirs, "#!/bin/sh\necho tarball\n", { mode: 0o755 });+ const target = path.join(tmp, "local-bin", "penguin");+ fs.mkdirSync(path.dirname(target), { recursive: true });+ fs.symlinkSync(theirs, target);++ const result = syncWrapper(target, script, false);+ expect(result.action).toBe("skipped");+ expect(result.detail).toContain("which this app did not write");+ expect(fs.readlinkSync(target)).toBe(theirs);+ });++ it("never replaces a foreign regular file", () => {+ const target = path.join(tmp, "local-bin", "penguin");+ fs.mkdirSync(path.dirname(target), { recursive: true });+ fs.writeFileSync(target, "#!/usr/bin/env node\n// somebody else's penguin\n", { mode: 0o755 });++ expect(syncWrapper(target, script, false).action).toBe("skipped");+ expect(fs.readFileSync(target, "utf8")).toContain("somebody else's penguin");+ });++ it("does not read a large binary sitting at the target", () => {+ const target = path.join(tmp, "local-bin", "penguin");+ fs.mkdirSync(path.dirname(target), { recursive: true });+ // The marker sits past the size cap on purpose: what makes this foreign has to be the+ // refusal to read the file, not the absence of the text.+ fs.writeFileSync(target, Buffer.concat([Buffer.alloc(128 * 1024, 7), Buffer.from(script)]));++ expect(syncWrapper(target, script, false).action).toBe("skipped");+ expect(fs.statSync(target).size).toBe(128 * 1024 + Buffer.byteLength(script));+ });+});++describe("inspect helpers", () => {+ it("recognises a launcher from an older release by its marker", () => {+ // The marker text has shipped unchanged since 0.2.2, which is what lets an install made+ // by an older version be repaired rather than treated as somebody else's command.+ const target = path.join(tmp, "penguin");+ fs.writeFileSync(target, posixLauncherScript());+ expect(inspectWrapperTarget(target, "different script").kind).toBe("ours");+ });++ it("reports an unreadable target as foreign rather than guessing", () => {+ const dir = path.join(tmp, "penguin");+ fs.mkdirSync(dir);+ expect(inspectSymlinkTarget(dir, "/x/bin/penguin").kind).toBe("foreign");+ expect(inspectWrapperTarget(dir, "script").kind).toBe("foreign");+ });+});++describe("isVolatileAppLocation", () => {+ it("refuses to install from a mounted dmg", () => {+ expect(+ isVolatileAppLocation(+ "/Volumes/PenguinHarness/PenguinHarness.app/Contents/Resources/app",+ "darwin",+ ),+ ).toBe(true);+ });++ it("refuses to install from a translocated bundle", () => {+ // Gatekeeper runs a quarantined bundle from a read-only copy under a random path; a+ // link into it dies with the session.+ expect(+ isVolatileAppLocation(+ "/private/var/folders/x/AppTranslocation/1B2C/d/PenguinHarness.app/Contents/Resources/app",+ "darwin",+ ),+ ).toBe(true);+ });++ it("installs normally from Applications", () => {+ expect(+ isVolatileAppLocation("/Applications/PenguinHarness.app/Contents/Resources/app", "darwin"),+ ).toBe(false);+ });++ it("is a macOS rule only", () => {+ expect(isVolatileAppLocation("/Volumes/whatever/app", "linux")).toBe(false);+ expect(isVolatileAppLocation("/Volumes/whatever/app", "win32")).toBe(false);+ });+});++describe("recorded state", () => {+ it("remembers a declined administrator prompt", () => {+ writeCliCommandState(tmp, { version: 1, decision: "declined", lastResult: "failed" });+ expect(readCliCommandState(tmp).decision).toBe("declined");+ });++ it("treats every other outcome as no decision, so the next launch retries", () => {+ for (const lastResult of ["foreign", "deferred", "failed"] as const) {+ writeCliCommandState(tmp, { version: 1, lastResult });+ expect(readCliCommandState(tmp).decision).toBeUndefined();+ }+ });++ it("reads a missing or corrupt file as no decision rather than a decline", () => {+ expect(readCliCommandState(tmp).decision).toBeUndefined();+ fs.writeFileSync(stateFilePath(tmp), "{ not json");+ expect(readCliCommandState(tmp).decision).toBeUndefined();+ fs.writeFileSync(stateFilePath(tmp), JSON.stringify({ decision: "whatever" }));+ expect(readCliCommandState(tmp).decision).toBeUndefined();+ });++ it("removes the pre-0.2.7 marker, which recorded the question and not the answer", () => {+ const legacy = legacyOfferedFlagPath(tmp);+ fs.writeFileSync(legacy, "2026-08-06T00:00:00.000Z\n");+ writeCliCommandState(tmp, { version: 1, lastResult: "installed" });+ expect(fs.existsSync(legacy)).toBe(false);+ });++ it("survives an unwritable state directory", () => {+ const nested = path.join(tmp, "file-in-the-way", "userData");+ fs.writeFileSync(path.join(tmp, "file-in-the-way"), "");+ expect(() =>+ writeCliCommandState(nested, { version: 1, lastResult: "installed" }),+ ).not.toThrow();+ expect(readCliCommandState(nested).decision).toBeUndefined();+ });+});diff --git a/packages/desktop/test/launcher.test.ts b/packages/desktop/test/launcher.test.tsindex ec26af53..72babed0 100644--- a/packages/desktop/test/launcher.test.ts+++ b/packages/desktop/test/launcher.test.ts@@ -1,3 +1,6 @@+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";import {adminSymlinkAppleScript,@@ -6,6 +9,7 @@ import {appleScriptString,CLI_ENTRY_RELPATH,cliInstallKind,+ LAUNCHER_MARKER,LINUX_EXECUTABLE,MAC_EXECUTABLE,mergeWindowsUserPath,@@ -113,6 +117,21 @@ describe("appImageBootstrapJs", () => {});});+describe("LAUNCHER_MARKER", () => {+ it("appears in every generated launcher", () => {+ // cli-link.ts recognises a `penguin` this app wrote by this text, and skips anything+ // that lacks it. A launcher that stopped carrying it would be classified as somebody+ // else's command and the install would silently stop repairing itself.+ for (const script of [+ posixLauncherScript(),+ windowsLauncherScript(),+ appImageWrapperScript("/home/user/Apps/penguin.AppImage"),+ ]) {+ expect(script).toContain(LAUNCHER_MARKER);+ }+ });+});+describe("shellQuote", () => {it("wraps a plain value in single quotes", () => {expect(shellQuote("/Applications/PenguinHarness.app")).toBe(@@ -224,3 +243,63 @@ describe("cliInstallKind", () => {).toBe("appimage");});});++/**+ * The couplings that make an installed desktop app carry a working `penguin`. They span+ * three files nothing else compares: the constants above, the packaging decisions in+ * electron-builder.yml, and the deb postinst templates. Each is load-bearing at run time+ * and silent at build time — a packed app with no CLI in it builds, signs and ships+ * exactly like one that has it (scripts/verify-packed-cli.mjs checks the produced tree).+ */+describe("packaged CLI", () => {+ const pkgDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");+ const read = (rel: string): string =>+ fs.readFileSync(path.join(pkgDir, ...rel.split("/")), "utf8");+ const builderConfig = read("electron-builder.yml");+ /** The deb link target, spelled identically by the install and remove templates. */+ const debTarget = "/opt/${sanitizedProductName}/resources/app/bin/penguin";++ it("ships bin/, which is the only reason <app>/bin/penguin exists in an install", () => {+ expect(builderConfig).toContain("- bin/**/*");+ });++ it("keeps asar off — inside an archive there is no bin/penguin to exec", () => {+ expect(builderConfig).toMatch(/^asar: false$/m);+ });++ it("names the runtime the launchers exec", () => {+ // posixLauncherScript and windowsLauncherScript hardcode these three names; they come+ // from productName (macOS bundle executable and the .exe) and linux.executableName.+ expect(builderConfig).toMatch(new RegExp(`^productName: ${MAC_EXECUTABLE}$`, "m"));+ expect(WIN_EXECUTABLE).toBe(`${MAC_EXECUTABLE}.exe`);+ expect(builderConfig).toMatch(new RegExp(`^ {2}executableName: ${LINUX_EXECUTABLE}$`, "m"));+ });++ it("bundles the CLI at the entry the launchers run", () => {+ const entry = CLI_ENTRY_RELPATH.replace(/^dist\//, "").replace(/\.js$/, "");+ expect(read("tsup.config.ts")).toMatch(+ new RegExp(`^\\s*"?${entry}"?: "\\.\\./cli/dist/penguin\\.js",$`, "m"),+ );+ });++ it("deb creates /usr/bin/penguin itself: it is the one form the shell does not install", () => {+ // cliInstallKind returns null for it, so nothing else would ever put the CLI on PATH.+ expect(cliInstallKind({ packaged: true, platform: "linux", appImagePath: null })).toBeNull();+ expect(builderConfig).toMatch(+ /^deb:\n(?: .*\n|#.*\n)*? {2}afterInstall: build\/linux\/after-install\.tpl$/m,+ );+ const afterInstall = read("build/linux/after-install.tpl");+ expect(afterInstall).toContain(`ln -sf '${debTarget}' '/usr/bin/penguin'`);+ // Never over a real file of that name — a CLI installed by install.sh, say.+ expect(afterInstall).toContain(`if [ ! -e '/usr/bin/penguin' ] || [ -L '/usr/bin/penguin' ]`);+ });++ it("deb removes only the link it made", () => {+ expect(builderConfig).toMatch(+ /^deb:\n(?: .*\n|#.*\n)*? {2}afterRemove: build\/linux\/after-remove\.tpl$/m,+ );+ const afterRemove = read("build/linux/after-remove.tpl");+ expect(afterRemove).toContain(`[ "\`readlink '/usr/bin/penguin'\`" = '${debTarget}' ]`);+ expect(afterRemove).toContain("rm -f '/usr/bin/penguin'");+ });+});diff --git a/packages/docs/content/quickstart-desktop.en.md b/packages/docs/content/quickstart-desktop.en.mdindex fd343107..7ebf081f 100644--- a/packages/docs/content/quickstart-desktop.en.md+++ b/packages/docs/content/quickstart-desktop.en.md@@ -3,7 +3,7 @@ title: Desktop appdescription: A double-click install that opens already signed in — the route that asks the least of a terminal.----The full Web experience as a standalone application: it embeds the server and opens already signed in — no login page, no initial password to copy, and nothing to install from a command line. The user menu leaves out **Change password** accordingly: the window signs itself in, so there is no password to type or to change. Builds are not signed yet, so macOS and Linux may each need one command the first time the system blocks the app; the box below carries it. It shares its data root with a [CLI install](/quickstart-cli), so the two can be mixed freely — if you later serve that root over the network with `penguin server`, give its admin a usable password first with `penguin server reset-admin-password` (server stopped), since the desktop app deliberately seeds one nobody can read.+The full Web experience as a standalone application: it embeds the server and opens already signed in — no login page, no initial password to copy, and nothing to install from a command line. The user menu leaves out **Change password** accordingly: the window signs itself in, so there is no password to type or to change. It also installs the `penguin` command for you, so the terminal is there when you want it. It shares its data root with a [CLI install](/quickstart-cli), so the two can be mixed freely — if you later serve that root over the network with `penguin server`, give its admin a usable password first with `penguin server reset-admin-password` (server stopped), since the desktop app deliberately seeds one nobody can read.## Download and install@@ -15,24 +15,31 @@ Get the installer for your platform from the [download page](https://penguin.ooo| Windows 10+ | installer (.exe, x64) || Linux (x64) | AppImage / deb |-> [!INFO]- The system blocked the first launch? One fix per platform, once->-> Current builds are unsigned, so the system may block the very first launch. Only your own platform needs anything:->-> **macOS says "PenguinHarness" is damaged and can't be opened** — macOS quarantines files downloaded from the internet, and the missing signature makes that flag surface as a false "damaged" alert. Drag `PenguinHarness.app` from the dmg into the **Applications** folder, open Terminal (Launchpad → Other → Terminal), paste the command below and press Enter, then type your login password (nothing shows while you type; press Enter when done). Once it finishes, double-click the app — it now opens normally:->-> ```bash-> sudo xattr -rd com.apple.quarantine /Applications/PenguinHarness.app-> ```->-> **Windows SmartScreen says "Windows protected your PC"** — the installer is not signed yet, so SmartScreen holds the first run: click **More info**, then **Run anyway** to continue installing — first run only.+The macOS builds are Developer ID signed and notarized, and the Windows installers are Authenticode signed, so neither platform needs a first-launch unblock. Linux is the one exception:++> [!INFO]- Double-clicking the Linux AppImage does nothing>-> **Double-clicking the Linux AppImage does nothing** — browsers download AppImages without the execute permission. Grant it once and the app starts normally from then on (the deb package installs through the package manager and is not affected):+> Browsers download AppImages without the execute permission. Grant it once and the app starts normally from then on (the deb package installs through the package manager and is not affected):>> ```bash> chmod +x penguin-desktop-linux-x86_64.AppImage> ```+## The `penguin` command++The app installs the `penguin` command itself, at every launch, from the CLI bundled inside it. The two always come from the same build, so updating the app updates the command with it, and no system Node.js is involved — the launcher runs the bundled CLI on the app's own runtime.++| Platform | Where the command goes |+| --- | --- |+| macOS | `/usr/local/bin/penguin`, linked to the app. Creating that directory can need an administrator password; macOS asks only when the plain write is refused, and declining leaves the command uninstalled. |+| Windows | the app's `bin` directory is appended to your user `Path`. Open a **new** terminal window afterwards — an already-running one keeps the old `Path`. |+| Linux (deb) | `/usr/bin/penguin`, created by the package's own install script. |+| Linux (AppImage) | `~/.local/bin/penguin`, a wrapper that runs the AppImage. Most distributions put that directory on `PATH` at login. |++**An existing `penguin` is never replaced.** If something else already provides the command — a [CLI install](/quickstart-cli), a global npm package, a script of your own — the app leaves it exactly as it is and installs nothing. Choose **Install 'penguin' Command…** from the application menu to replace it deliberately; that menu item is also the way back if you declined the macOS administrator prompt.++On macOS the app will not install the command while it is running from the mounted dmg, because the link would break the moment you eject it. Drag the app into **Applications** and open it from there.+## Configure a modelOpen the app, go to the **Models** page in the sidebar, click "Add model" and fill in the Provider, model id and API key, then set it as the default.@@ -50,5 +57,5 @@ Tool calls expand inline as cards you can open to inspect arguments and output;## Next steps- [Web App Guide](/web-app): every page of the interface, one by one.-- [CLI and Web App](/quickstart-cli): if you also want the `penguin` command on the same machine.+- [CLI and Web App](/quickstart-cli): a standalone install, for a server or a remote machine. On the same machine you do not need one — the app already provides `penguin` — and installing it puts a second copy on your `PATH`.- [Architecture Overview](/architecture): how the pieces fit together.diff --git a/packages/docs/content/quickstart-desktop.zh.md b/packages/docs/content/quickstart-desktop.zh.mdindex 1ebe738b..19f43664 100644--- a/packages/docs/content/quickstart-desktop.zh.md+++ b/packages/docs/content/quickstart-desktop.zh.md@@ -3,7 +3,7 @@ title: 桌面端应用description: 双击安装,打开即已登录——对终端要求最少的那条路线。----完整的 Web 体验打包成一个独立应用:内嵌服务端,双击打开即已登录——没有登录页,不用抄初始密码,也不必从命令行安装任何东西。用户菜单里相应地没有**修改密码**这一项:这个窗口自己完成登录,因此既没有要输的密码,也没有要改的密码。目前的构建尚未签名,macOS 与 Linux 在系统拦下首次启动时各需要执行一条命令,下面的方框里写了。它与[命令行安装](/quickstart-cli)共用同一个数据目录,两者可以混用——如果之后想用 `penguin server` 把这个数据目录放到网络上,请先用 `penguin server reset-admin-password`(服务端已停止时执行)给其中的 admin 设一个可用的密码,因为桌面端刻意生成的是一个谁也读不到的初始密码。+完整的 Web 体验打包成一个独立应用:内嵌服务端,双击打开即已登录——没有登录页,不用抄初始密码,也不必从命令行安装任何东西。用户菜单里相应地没有**修改密码**这一项:这个窗口自己完成登录,因此既没有要输的密码,也没有要改的密码。它还会替你装好 `penguin` 命令,需要用终端时随时可用。它与[命令行安装](/quickstart-cli)共用同一个数据目录,两者可以混用——如果之后想用 `penguin server` 把这个数据目录放到网络上,请先用 `penguin server reset-admin-password`(服务端已停止时执行)给其中的 admin 设一个可用的密码,因为桌面端刻意生成的是一个谁也读不到的初始密码。## 下载与安装@@ -15,24 +15,31 @@ description: 双击安装,打开即已登录——对终端要求最少的那| Windows 10+ | 安装程序(.exe,x64) || Linux(x64) | AppImage / deb |-> [!INFO]- 首次启动被系统拦下?按平台操作一次即可解除->-> 当前构建暂未签名,系统可能拦截第一次启动。只需处理你自己的平台:->-> **macOS 提示「PenguinHarness 已损坏,无法打开」**——macOS 会给从网络下载的文件加上隔离标记,应用未签名时会因此被误报为「已损坏」。把 `PenguinHarness.app` 从 dmg 拖入「应用程序」文件夹,打开终端(启动台 → 其他 → 终端),粘贴下面这条命令并回车,再输入开机密码(输入时屏幕不显示字符,输完回车即可);执行完成后双击即可正常打开:->-> ```bash-> sudo xattr -rd com.apple.quarantine /Applications/PenguinHarness.app-> ```->-> **Windows SmartScreen 提示「Windows 已保护你的电脑」**——安装程序暂未签名,点「更多信息」,再点「仍要运行」即可继续安装,仅首次运行需要。+macOS 安装包已由 Developer ID 签名并公证,Windows 安装程序已 Authenticode 签名,两个平台首次启动都无需额外放行;只有 Linux 是例外:++> [!INFO]- Linux 双击 AppImage 没有反应>-> **Linux 双击 AppImage 没有反应**——浏览器下载的 AppImage 默认没有执行权限,赋权一次后即可正常启动(deb 包经包管理器安装,无此问题):+> 浏览器下载的 AppImage 默认没有执行权限,赋权一次后即可正常启动(deb 包经包管理器安装,无此问题):>> ```bash> chmod +x penguin-desktop-linux-x86_64.AppImage> ```+## `penguin` 命令++应用会在每次启动时,用打包在自身内部的那份 CLI 装好 `penguin` 命令。两者始终来自同一次构建,所以应用更新时命令也随之更新;过程中不需要系统里的 Node.js——启动器用应用自带的运行时执行打包好的 CLI。++| 平台 | 命令装到哪里 |+| --- | --- |+| macOS | `/usr/local/bin/penguin`,链接到应用。创建该目录可能需要管理员密码;只有在普通写入被拒时 macOS 才会询问,取消则不安装该命令。 |+| Windows | 应用的 `bin` 目录会追加到用户 `Path`。之后请**新开一个终端窗口**——已经开着的终端仍沿用旧 `Path`。 |+| Linux(deb) | `/usr/bin/penguin`,由软件包自身的安装脚本创建。 |+| Linux(AppImage) | `~/.local/bin/penguin`,一个运行该 AppImage 的包装脚本。多数发行版会在登录时把该目录加入 `PATH`。 |++**已存在的 `penguin` 绝不会被替换。**如果该命令已由别处提供——[命令行安装](/quickstart-cli)、全局 npm 包、你自己写的脚本——应用会原样保留它,不安装自己的那份。想主动替换,请在应用菜单里选择 **Install 'penguin' Command…**;在 macOS 上取消过管理员授权后,也从这里重新安装。++在 macOS 上,只要应用还是从挂载的 dmg 里运行,就不会安装该命令——推出磁盘映像后链接就会失效。请先把应用拖入「应用程序」文件夹,再从那里打开。+## 配置模型打开应用,在左侧进入**模型**页,点「添加模型」填入 Provider、模型 id 与 API key,保存后设为默认模型。@@ -50,5 +57,5 @@ description: 双击安装,打开即已登录——对终端要求最少的那## 下一步- [Web App 指南](/web-app):按页面逐一介绍界面的全部功能。-- [命令行与 Web 应用](/quickstart-cli):想在同一台机器上再装一个 `penguin` 命令时看这里。+- [命令行与 Web 应用](/quickstart-cli):独立安装,适用于服务器或远程机器。同一台机器上不必再装——应用已经提供了 `penguin`,再装一次只会在 `PATH` 上多出一份。- [架构总览](/architecture):了解整体设计。diff --git a/packages/docs/content/quickstart.en.md b/packages/docs/content/quickstart.en.mdindex 069b4788..f49ffa1d 100644--- a/packages/docs/content/quickstart.en.md+++ b/packages/docs/content/quickstart.en.md@@ -7,11 +7,11 @@ PenguinHarness has three ways in. They run the same engine; they differ only in| Route | Best for | Terminal needed? || --- | --- | --- |-| [Desktop app](/quickstart-desktop) | Using PenguinHarness as a product, straight away | Only if the system blocks the first launch |+| [Desktop app](/quickstart-desktop) | Using PenguinHarness as a product, straight away | No — and it installs the `penguin` command for you || [CLI and Web App](/quickstart-cli) | Servers and remote machines, or wanting the `penguin` command | Once, to install || [SDK](/quickstart-sdk) | Embedding the engine in your own TypeScript program | Yes |-If you are unsure, take the [desktop app](/quickstart-desktop): it has the fewest steps, and moving to another route later costs you nothing. Builds are not signed yet, so macOS and Linux may need one command the first time — that page carries it.+If you are unsure, take the [desktop app](/quickstart-desktop): it has the fewest steps, and moving to another route later costs you nothing. The macOS and Windows installers are signed, so only a downloaded Linux AppImage needs anything before the first launch — that page carries it.## What all three sharediff --git a/packages/docs/content/quickstart.zh.md b/packages/docs/content/quickstart.zh.mdindex ccd3db73..3744dd68 100644--- a/packages/docs/content/quickstart.zh.md+++ b/packages/docs/content/quickstart.zh.md@@ -7,11 +7,11 @@ PenguinHarness 有三条入口,背后是同一个引擎,区别只在你以| 路线 | 适合 | 需要用终端吗 || --- | --- | --- |-| [桌面端应用](/quickstart-desktop) | 想直接把 PenguinHarness 当成一个应用来用 | 仅在系统拦下首次启动时 |+| [桌面端应用](/quickstart-desktop) | 想直接把 PenguinHarness 当成一个应用来用 | 不需要——而且它会替你装好 `penguin` 命令 || [命令行与 Web 应用](/quickstart-cli) | 装到服务器或远程机器,或想要 `penguin` 命令 | 安装时用一次 || [SDK](/quickstart-sdk) | 把引擎嵌进自己的 TypeScript 程序 | 需要 |-拿不准就选[桌面端应用](/quickstart-desktop):它步骤最少,而且换到另一条路线不用重来。目前的构建尚未签名,macOS 与 Linux 首次启动时可能需要执行一条命令,那一页里写了。+拿不准就选[桌面端应用](/quickstart-desktop):它步骤最少,而且换到另一条路线不用重来。macOS 与 Windows 的安装包均已签名,只有下载来的 Linux AppImage 在首次启动前需要一步操作,那一页里写了。## 三条路线共用什么