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(linux): support managed user installs and updates on Arch/Omarchy (#3922)

Dash891a66c7bb7f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1503c4044e..2265b8c2eb 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -157,6 +157,9 @@ jobs:
GITHUB_TOKEN: ${{ github.token }}
run: pnpm install:ripgrep
+ - name: Install Linux user-installer test tools
+ run: sudo apt-get update && sudo apt-get install --yes libarchive-tools binutils desktop-file-utils xdg-utils
+
- name: Run client and package unit test shard
# package script 会传递 npm_execpath,让子进程复用当前 pnpm 入口。
run: pnpm run test:workspaces --tier unit
diff --git a/README.md b/README.md
index f7bf135bcf..8af0739d87 100644
--- a/README.md
+++ b/README.md
@@ -41,6 +41,9 @@ API keys, or use local models.
See [cindy.app](https://cindy.app) for service details,
[pricing](https://cindy.app/#pricing), and [downloads](https://cindy.app/download/).
+Linux users: see the [Ubuntu, Arch Linux and Omarchy installation guide](docs/linux.md)
+for installation, updates, keyring setup and migration from a manual install.
+
## Yours to shape
Open source means more than visible — it means changeable:
diff --git a/apps/desktop/forge-linux.ts b/apps/desktop/forge-linux.ts
new file mode 100644
index 0000000000..9e04e00d1b
--- /dev/null
+++ b/apps/desktop/forge-linux.ts
@@ -0,0 +1,15 @@
+import fs from 'node:fs';
+import path from 'node:path';
+
+/** Release identity outside ASAR for the unprivileged Linux installer. */
+export function stageLinuxBuildInfo(
+ buildPath: string, platform: string, arch: string, version: string, region: string,
+): void {
+ if (platform !== 'linux') return;
+ if (!['x64', 'arm64'].includes(arch) || !['global', 'cn', 'dev'].includes(region)
+ || !/^[0-9]+\.[0-9]+\.[0-9]+([+-][A-Za-z0-9.-]+)?$/.test(version)) {
+ throw new Error('Invalid Linux build identity');
+ }
+ fs.writeFileSync(path.join(buildPath, 'resources', 'linux-build-info'),
+ `cindy-linux-v1\n${version}\n${arch}\n${region}\n${region === 'dev' ? 'CindyDev' : 'Cindy'}\n`);
+}
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index a45a65102b..e84571ad01 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -11,6 +11,7 @@ import { AutoUnpackNativesPlugin } from '@electron-forge/plugin-auto-unpack-nati
import { FusesPlugin } from '@electron-forge/plugin-fuses';
import { VitePlugin } from '@electron-forge/plugin-vite';
import type { ForgeArch, ForgeConfig, ForgePlatform } from '@electron-forge/shared-types';
+import { stageLinuxBuildInfo } from './forge-linux';
import {
BRAND_IDENTITY,
allDeepLinkSchemes,
@@ -844,6 +845,7 @@ function extraResourcesForTarget(targetPlatform: string): string[] {
if (targetPlatform === 'darwin') {
base.push('resources/cli');
}
+ if (targetPlatform === 'linux') base.push('resources/linux');
return base;
}
@@ -1707,6 +1709,8 @@ const config: ForgeConfig = {
postPackage: async (_forgeConfig, opts) => {
try {
for (const buildPath of opts.outputPaths) {
+ stageLinuxBuildInfo(buildPath, opts.platform, opts.arch,
+ process.env.APP_VERSION || DESKTOP_PACKAGE_VERSION, CINDY_REGION);
const noticeName = stagePackagedThirdPartyNotices(buildPath, opts.platform);
console.log(`[forge:postPackage] staged ${noticeName} + restricted component disclosure`);
signPackagedExes(buildPath);
diff --git a/apps/desktop/resources/linux/install-user.sh b/apps/desktop/resources/linux/install-user.sh
new file mode 100755
index 0000000000..afcdeadb67
--- /dev/null
+++ b/apps/desktop/resources/linux/install-user.sh
@@ -0,0 +1,217 @@
+#!/usr/bin/env bash
+# User-owned Cindy installation. Also embedded in the in-app updater: no Debian
+# maintainer scripts, privilege escalation, or ASAR rewriting.
+set -euo pipefail
+umask 077
+
+fail() { printf 'Cindy: %s\n' "$*" >&2; exit 1; }
+[[ $(uname -s) == Linux ]] || fail 'This installer requires Linux.'
+[[ $EUID -ne 0 ]] || fail 'Run as your desktop user, not root or sudo.'
+for tool in bsdtar sha256sum stat dd mktemp realpath flock find readlink mv ln; do
+ command -v "$tool" >/dev/null || fail "Missing dependency: $tool (see docs/linux.md)."
+done
+mode=${1:-}
+case "$mode" in
+ --install)
+ [[ $# -ge 3 && $# -le 4 ]] || fail 'Usage: install-user.sh --install PACKAGE.deb SHA256 [PREFIX]'
+ archive=$2 digest=${3,,} prefix=${4:-"$HOME/.local/opt/cindy"}
+ size=$(stat -c %s -- "$archive")
+ expected_version='' expected_region=''
+ ;;
+ --apply)
+ [[ $# -eq 8 ]] || fail 'Invalid update transaction arguments.'
+ archive=$2 digest=${3,,} size=$4 prefix=$5 expected_version=$6 expected_region=$7 expected_current=$8
+ ;;
+ *) fail 'Usage: install-user.sh --install PACKAGE.deb SHA256 [PREFIX]' ;;
+esac
+[[ $digest =~ ^[a-f0-9]{64}$ ]] || fail 'A SHA-256 from the trusted release is required.'
+[[ $size =~ ^[1-9][0-9]{0,10}$ ]] || fail 'Invalid package size.'
+[[ -f $archive && ! -L $archive ]] || fail 'Package must be a regular file, not a symlink.'
+archive=$(realpath -e -- "$archive")
+[[ $prefix == /* && $prefix != *$'\n'* && $prefix != *$'\r'* ]] || fail 'PREFIX must be an absolute path without line breaks.'
+prefix=$(realpath -m -- "$prefix")
+user_home=$(realpath -e -- "$HOME")
+[[ $prefix == "$user_home/"* && $prefix != "$user_home" ]] || fail 'PREFIX must be inside your home directory.'
+marker="$prefix/.cindy-user-install"
+if [[ -e $prefix ]]; then
+ [[ -d $prefix && -f $marker && ! -L $marker ]] || fail 'Existing PREFIX is not a managed Cindy install; choose an empty new path.'
+else
+ [[ $mode == --install ]] || fail 'Managed installation disappeared.'
+ mkdir -p -- "$prefix"
+ printf 'cindy-user-install-v1:pending\n' > "$marker"
+fi
+[[ -O $prefix && -O $marker ]] || fail 'Installation is not owned by this user.'
+exec 9> "$prefix/.install.lock"
+flock -n 9 || fail 'Another installation is in progress.'
+mkdir -p -- "$prefix/releases"
+[[ ! -L $prefix/releases && -O $prefix/releases ]] || fail 'Invalid releases directory.'
+stage=$(mktemp -d "$prefix/releases/.stage.XXXXXXXX")
+new_release=''
+cleanup() {
+ # Only remove this transaction's unactivated directory. In particular a
+ # signal just after activation must never delete the now-current release.
+ if (( ${activation_in_progress:-0} )); then
+ rollback_activation || true
+ fi
+ if [[ -n $new_release && $(readlink -- "$prefix/current" 2>/dev/null || true) != "$new_release" ]]; then
+ rm -rf -- "$prefix/$new_release"
+ fi
+ if [[ -n ${stage:-} && -d $stage ]]; then rm -rf -- "$stage"; fi
+}
+trap cleanup EXIT
+
+write_launcher() {
+ [[ $mode == --install ]] || return 0
+ # Stage the launcher beside the other transaction files so an interrupted
+ # write cannot leave a truncated executable behind. Replacing it is safe:
+ # the managed prefix owns this stable entry point.
+ local quoted=${prefix//\'/\'\\\'\'}
+ printf '#!/bin/sh\nexec '\''%s/current/Cindy'\'' "$@"\n' "$quoted" > "$stage/launch"
+ chmod 755 "$stage/launch"
+ mv -Tf -- "$stage/launch" "$prefix/launch"
+}
+
+# Copy once, bounded and O_NOFOLLOW. Hash and extract the same private snapshot.
+cap=$((size / 1048576 + 2))
+dd if="$archive" of="$stage/package.deb" iflag=nofollow,nonblock bs=1048576 count="$cap" status=none
+[[ $(stat -c %s -- "$stage/package.deb") == "$size" ]] || fail 'Package size mismatch.'
+actual=$(sha256sum -- "$stage/package.deb")
+[[ ${actual:0:64} == "$digest" ]] || fail 'Package SHA-256 mismatch.'
+bsdtar -tf "$stage/package.deb" > "$stage/members"
+data_member=''
+while IFS= read -r member; do
+ case "$member" in
+ data.tar|data.tar.gz|data.tar.xz|data.tar.zst)
+ [[ -z $data_member ]] || fail 'Duplicate package payload.'
+ data_member=$member ;;
+ esac
+done < "$stage/members"
+[[ -n $data_member ]] || fail 'Missing package payload.'
+bsdtar -xOf "$stage/package.deb" "$data_member" > "$stage/data.tar"
+mkdir "$stage/payload"
+# libarchive's secure defaults reject traversal and symlink escapes. Never use
+# -P / --absolute-paths or preserve archive ownership / setuid permissions.
+bsdtar -xf "$stage/data.tar" -C "$stage/payload" --no-same-owner --no-same-permissions ./usr/lib/cindy
+payload="$stage/payload/usr/lib/cindy"
+[[ -d $payload && ! -L $payload ]] || fail 'Missing Cindy payload.'
+info="$payload/resources/linux-build-info"
+[[ -f $info && ! -L $info ]] || fail 'This package predates user-install support; use a newer release.'
+mapfile -t fields < "$info"
+[[ ${#fields[@]} -eq 5 && ${fields[0]} == cindy-linux-v1 ]] || fail 'Invalid build identity.'
+version=${fields[1]} arch=${fields[2]} region=${fields[3]} executable=${fields[4]}
+[[ $version =~ ^[0-9]+\.[0-9]+\.[0-9]+([+-][A-Za-z0-9.-]+)?$ ]] || fail 'Invalid build version.'
+[[ $region == global || $region == cn ]] || fail 'Only release builds can be installed.'
+[[ $executable == Cindy ]] || fail 'Unexpected executable identity.'
+case "$(uname -m):$arch" in x86_64:x64|aarch64:arm64) ;; *) fail 'Package architecture does not match this machine.' ;; esac
+[[ -z $expected_version || $version == "$expected_version" ]] || fail 'Downloaded version does not match the update manifest.'
+[[ -z $expected_region || $region == "$expected_region" ]] || fail 'Downloaded build belongs to a different region.'
+identity=$(< "$marker")
+[[ $identity == cindy-user-install-v1:pending || $identity == "cindy-user-install-v1:$region" ]] || fail 'Do not mix release regions in one installation.'
+[[ -x $payload/$executable && ! -L $payload/$executable && -f $payload/resources/app.asar ]] || fail 'Incomplete application.'
+while IFS= read -r -d '' entry; do
+ if [[ -L $entry ]]; then
+ target=$(realpath -m -- "$entry")
+ [[ $target == "$payload/"* ]] || fail 'Package symlink escapes the application.'
+ elif [[ ! -f $entry && ! -d $entry ]]; then
+ fail 'Package contains a special file.'
+ fi
+done < <(find "$payload" -print0)
+
+current=''
+if [[ -e $prefix/current || -L $prefix/current ]]; then
+ [[ -L $prefix/current ]] || fail 'current is not a managed symlink.'
+ current=$(readlink -- "$prefix/current")
+ [[ $current =~ ^releases/[A-Za-z0-9.+-]+$ && -d $prefix/$current ]] || fail 'Invalid current release.'
+fi
+if [[ $mode == --apply ]]; then
+ [[ $identity == "cindy-user-install-v1:$region" && -n $current ]] || fail 'Update requires an installed release.'
+ [[ $current == "$expected_current" ]] || fail 'Installation changed while the update was pending.'
+fi
+release="releases/$version-$digest"
+if [[ $current == "$release" || ( $current == "$release-"* && ${current#"$release-"} =~ ^[A-Za-z0-9]{8}$ ) ]]; then
+ write_launcher
+ exit 0
+fi
+if [[ -e $prefix/$release || -L $prefix/$release ]]; then
+ # A hard interruption can leave a release before current is switched. It
+ # might also be a retained release still used by a running process: never
+ # overwrite, remove, or trust it. Install the freshly verified payload using
+ # this transaction's existing unique stage suffix instead.
+ release="$release-${stage##*.stage.}"
+ [[ ! -e $prefix/$release && ! -L $prefix/$release ]] || fail 'Release destination is occupied; retry installation.'
+fi
+# Never install setuid/setgid helpers from a system package into user storage.
+find "$payload" -type f -exec chmod u-s,g-s -- {} +
+new_release=$release
+mv -T -- "$payload" "$prefix/$release"
+printf 'cindy-user-install-v1:%s\n' "$region" > "$stage/marker"
+mv -T -- "$stage/marker" "$marker"
+ln -s -- "$release" "$stage/current"
+had_previous=0
+previous_target=''
+if [[ -e $prefix/previous || -L $prefix/previous ]]; then
+ [[ -L $prefix/previous ]] || fail 'previous is not a managed symlink.'
+ had_previous=1
+ previous_target=$(readlink -- "$prefix/previous")
+fi
+if [[ -n $current ]]; then
+ ln -s -- "$current" "$stage/previous"
+ ln -s -- "$current" "$stage/restore-current"
+ if (( had_previous )); then
+ ln -s -- "$previous_target" "$stage/restore-previous"
+ fi
+fi
+
+current_activated=0
+previous_activated=0
+rollback_activation() {
+ local rollback_failed=0
+ if (( previous_activated )); then
+ if (( had_previous )); then
+ if ! mv -Tf -- "$stage/restore-previous" "$prefix/previous"; then
+ [[ $(readlink -- "$prefix/previous" 2>/dev/null || true) == "$previous_target" ]] || rollback_failed=1
+ fi
+ else
+ rm -f -- "$prefix/previous" || rollback_failed=1
+ fi
+ fi
+ if (( current_activated )); then
+ if [[ -n $current ]]; then
+ if ! mv -Tf -- "$stage/restore-current" "$prefix/current"; then
+ [[ $(readlink -- "$prefix/current" 2>/dev/null || true) == "$current" ]] || rollback_failed=1
+ fi
+ else
+ rm -f -- "$prefix/current" || rollback_failed=1
+ fi
+ fi
+ return "$rollback_failed"
+}
+activation_in_progress=1
+
+# Commit the pointers in a recoverable order. A failed current rename leaves
+# the old previous pointer untouched; a later previous failure rolls current
+# back to its staged old target before the transaction exits.
+current_activated=1
+if mv -Tf -- "$stage/current" "$prefix/current"; then
+ :
+else
+ status=$?
+ if rollback_activation; then activation_in_progress=0; fi
+ exit "$status"
+fi
+if [[ -n $current ]]; then
+ previous_activated=1
+ if mv -Tf -- "$stage/previous" "$prefix/previous"; then
+ :
+ else
+ status=$?
+ if rollback_activation; then activation_in_progress=0; fi
+ exit "$status"
+ fi
+fi
+activation_in_progress=0
+if [[ $mode == --install ]]; then
+ write_launcher
+ printf 'Installed Cindy %s. Start with: %s/launch\n' "$version" "$prefix"
+ printf 'To add a menu entry and login links, run: bash %q %q\n' "$prefix/current/resources/linux/register-desktop.sh" "$prefix"
+fi
diff --git a/apps/desktop/resources/linux/register-desktop.sh b/apps/desktop/resources/linux/register-desktop.sh
new file mode 100755
index 0000000000..1f3123ae5f
--- /dev/null
+++ b/apps/desktop/resources/linux/register-desktop.sh
@@ -0,0 +1,50 @@
+#!/usr/bin/env bash
+# Explicit opt-in desktop integration, separate from the update transaction.
+set -euo pipefail
+umask 077
+fail() { printf 'Cindy: %s\n' "$*" >&2; exit 1; }
+[[ $(uname -s) == Linux && $EUID -ne 0 && $# -eq 1 ]] || fail 'Run as your desktop user: register-desktop.sh PREFIX'
+for tool in realpath sha256sum desktop-file-validate update-desktop-database xdg-mime flock; do
+ command -v "$tool" >/dev/null || fail "Missing dependency: $tool"
+done
+prefix=$(realpath -e -- "$1")
+user_home=$(realpath -e -- "$HOME")
+[[ $prefix == "$user_home/"* && $prefix != *[$'\n\r\t=%']* ]] || fail 'PREFIX must be inside HOME with no control characters, = or %.'
+marker="$prefix/.cindy-user-install"
+[[ -d $prefix && -O $prefix && -f $marker && ! -L $marker && -O $marker && -x $prefix/launch ]] || fail 'Not a managed installation.'
+case "$(< "$marker")" in
+ cindy-user-install-v1:global|cindy-user-install-v1:cn) ;;
+ *) fail 'Not a release installation.' ;;
+esac
+exec 9> "$prefix/.install.lock"
+flock -n 9 || fail 'Another installation is in progress.'
+data_dir=$(realpath -m -- "${XDG_DATA_HOME:-$HOME/.local/share}")
+[[ $data_dir == "$user_home/"* && $data_dir != *[$'\n\r\t']* ]] || fail 'XDG_DATA_HOME must be inside HOME.'
+apps_dir="$data_dir/applications"
+mkdir -p -- "$apps_dir"
+id=$(printf '%s' "$prefix" | sha256sum)
+app_id="com.xd.cindy.user.h${id:0:16}"
+id="$app_id.desktop"
+dest="$apps_dir/$id"
+[[ ! -e $dest && ! -L $dest || -f $dest && ! -L $dest && -O $dest ]] || fail 'Desktop entry is not user-owned.'
+temp=$(mktemp --suffix=.desktop "$apps_dir/.cindy-desktop.XXXXXXXX")
+trap 'rm -f -- "$temp"' EXIT
+# Desktop Entry escaping has two layers, unlike shell quoting. Keep %U
+# outside the quoted executable. Reject literal % in PREFIX above.
+exec_path=$prefix/launch
+exec_path=${exec_path//\\/\\\\\\\\}
+exec_path=${exec_path//\"/\\\\\"}
+exec_path=${exec_path//\$/\\\\$}
+exec_path=${exec_path//\`/\\\\\`}
+icon=$prefix/current/resources/icon.png
+icon=${icon//\\/\\\\}
+printf '%s\n' '[Desktop Entry]' 'Type=Application' 'Name=Cindy (User)' \
+ "Exec=\"$exec_path\" %U" "Icon=$icon" 'Terminal=false' \
+ 'Categories=Development;' "StartupWMClass=$app_id" \
+ 'MimeType=x-scheme-handler/cindy;x-scheme-handler/xdt-maker;' > "$temp"
+desktop-file-validate "$temp"
+mv -T -- "$temp" "$dest"
+update-desktop-database "$apps_dir"
+xdg-mime default "$id" x-scheme-handler/cindy x-scheme-handler/xdt-maker
+printf 'Menu entry and login links registered: %s\n' "$dest"
+printf 'CLI: use %s/launch (add a cindy symlink to your PATH if desired).\n' "$prefix"
diff --git a/apps/desktop/scripts/package-desktop.mjs b/apps/desktop/scripts/package-desktop.mjs
index bdbc14dd53..2371e3163e 100644
--- a/apps/desktop/scripts/package-desktop.mjs
+++ b/apps/desktop/scripts/package-desktop.mjs
@@ -537,7 +537,8 @@ async function finishLinux({ artifactDir, baseName, arch }) {
// 包一致:归集时写死 amd64 会让 arm64 产物顶着 amd64 的名字发出去。
const installerPath = path.join(artifactDir, `${baseName}-${debianArch(arch)}.deb`);
fs.copyFileSync(debPath, installerPath);
- // Linux 没有 hotfix zip;应用内更新下载这份 installer .deb,再用 pkexec 覆盖安装。
+ // One verified payload: Debian uses pkexec; managed user installs on Arch /
+ // Omarchy extract it without elevation and atomically switch releases.
return { files: [fileEntry('installer', installerPath)], signing: { mode: 'none' } };
}
diff --git a/apps/desktop/src/main/__tests__/linuxInstallation.test.ts b/apps/desktop/src/main/__tests__/linuxInstallation.test.ts
new file mode 100644
index 0000000000..6ec0471fd1
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/linuxInstallation.test.ts
@@ -0,0 +1,242 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { execFileSync, spawnSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { findLinuxUserInstallation, isDebianManagedInstallation, missingLinuxUserInstallTools, linuxUserDesktopName } from '../linuxInstallation';
+import { stageLinuxBuildInfo } from '../../../forge-linux';
+import { buildLinuxUpdateScript } from '../updateScriptLinux';
+import { allDeepLinkSchemes } from '@cindy/maker-shared/brand-identity';
+
+describe('Linux install routing', () => {
+ it('requires exact Debian package ownership, not the existence of dpkg', () => {
+ expect(isDebianManagedInstallation('/usr/lib/cindy/Cindy', () => 'cindy: /usr/lib/cindy/Cindy\n')).toBe(true);
+ expect(isDebianManagedInstallation('/usr/lib/cindy/Cindy', () => 'cindy:amd64: /usr/lib/cindy/Cindy\n')).toBe(true);
+ expect(isDebianManagedInstallation('/home/test/Cindy', () => 'cindy: /usr/lib/cindy/Cindy\n')).toBe(false);
+ expect(isDebianManagedInstallation('/usr/lib/cindy/Cindy', () => 'unrelated: /usr/lib/cindy/Cindy\n')).toBe(false);
+ expect(isDebianManagedInstallation('/usr/lib/cindy/Cindy', () => { throw new Error('no dpkg'); })).toBe(false);
+ });
+ it('reports missing portable dependencies', () => {
+ expect(missingLinuxUserInstallTools(() => true)).toEqual([]);
+ expect(missingLinuxUserInstallTools((name) => name !== 'bsdtar')).toEqual(['bsdtar']);
+ });
+});
+
+// One shared, isolated filesystem fixture. No real app, credentials, network,
+// package-manager database or desktop settings are accessed.
+describe.skipIf(process.platform !== 'linux')('user installer transaction smoke (Linux/libarchive)', () => {
+ let root: string;
+ let prefix: string;
+ const installer = path.resolve(__dirname, '../../../resources/linux/install-user.sh');
+ const packages = new Map<string, { file: string; digest: string; size: number }>();
+ beforeAll(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-install-test-'));
+ prefix = path.join(root, 'home', "Cindy's space $literal");
+ fs.mkdirSync(path.join(root, 'home'));
+ for (const version of ['1.0.0', '1.0.1', '1.0.2', '1.0.3', '1.0.4', '1.0.5']) {
+ const pkg = path.join(root, version);
+ const appDir = path.join(pkg, 'usr', 'lib', 'cindy');
+ fs.mkdirSync(path.join(appDir, 'resources'), { recursive: true });
+ fs.writeFileSync(path.join(appDir, 'Cindy'), '#!/bin/sh\nprintf "%s\\n" "fixture"\n', { mode: 0o755 });
+ if (version === '1.0.4' || version === '1.0.5') {
+ fs.writeFileSync(path.join(appDir, 'Cindy'), [
+ '#!/bin/sh', 'printf "%s\\n" "$$" "$@" > "$CINDY_TEST_LAUNCH_LOG"', 'exec sleep 10', '',
+ ].join('\n'), { mode: 0o755 });
+ }
+ fs.writeFileSync(path.join(appDir, 'resources', 'app.asar'), 'fake archive');
+ stageLinuxBuildInfo(appDir, 'linux', process.arch, version, 'global');
+ if (version === '1.0.3') fs.symlinkSync('/etc/passwd', path.join(appDir, 'escape'));
+ execFileSync('bsdtar', ['-czf', 'data.tar.gz', './usr'], { cwd: pkg });
+ fs.writeFileSync(path.join(pkg, 'debian-binary'), '2.0\n');
+ const file = path.join(pkg, 'package.deb');
+ execFileSync('ar', ['rc', file, 'debian-binary', 'data.tar.gz'], { cwd: pkg });
+ const bytes = fs.readFileSync(file);
+ packages.set(version, { file, digest: createHash('sha256').update(bytes).digest('hex'), size: bytes.length });
+ }
+ });
+ afterAll(() => fs.rmSync(root, { recursive: true, force: true }));
+ function run(version: string, apply = false, overrides: { prefix?: string; digest?: string; version?: string; region?: string; env?: NodeJS.ProcessEnv } = {}) {
+ const pkg = packages.get(version)!;
+ const targetPrefix = overrides.prefix ?? prefix;
+ const args = apply
+ ? ['--apply', pkg.file, overrides.digest ?? pkg.digest, String(pkg.size), targetPrefix,
+ overrides.version ?? version, overrides.region ?? 'global', fs.readlinkSync(path.join(targetPrefix, 'current'))]
+ : ['--install', pkg.file, overrides.digest ?? pkg.digest, targetPrefix];
+ return spawnSync('bash', [installer, ...args], {
+ env: { ...process.env, HOME: path.join(root, 'home'), ...overrides.env }, encoding: 'utf8', timeout: 15_000,
+ });
+ }
+ it('installs, rejects corrupt/wrong builds, applies two updates, and retains previous releases', () => {
+ const first = run('1.0.0');
+ expect(first.stderr).toBe('');
+ expect(first.status).toBe(0);
+ const before = fs.readlinkSync(path.join(prefix, 'current'));
+ expect(execFileSync(path.join(prefix, 'launch'), { encoding: 'utf8' })).toBe('fixture\n');
+ fs.rmSync(path.join(prefix, 'launch'));
+ expect(run('1.0.0').status).toBe(0);
+ expect(execFileSync(path.join(prefix, 'launch'), { encoding: 'utf8' })).toBe('fixture\n');
+ const find = () => findLinuxUserInstallation(path.join(prefix, 'current', 'Cindy'), path.join(root, 'home'), process.getuid!());
+ expect(find()).toEqual({ prefix, current: before, region: 'global' });
+ expect(run('1.0.1', true, { digest: '0'.repeat(64) }).status).not.toBe(0);
+ expect(run('1.0.1', true, { version: '9.9.9' }).status).not.toBe(0);
+ expect(run('1.0.1', true, { region: 'cn' }).status).not.toBe(0);
+ expect(run('1.0.3', true).status).not.toBe(0);
+ expect(fs.readlinkSync(path.join(prefix, 'current'))).toBe(before);
+ expect(run('1.0.1', true).status).toBe(0);
+ const installed = fs.readlinkSync(path.join(prefix, 'current'));
+ const previousBeforeFailure = fs.readlinkSync(path.join(prefix, 'previous'));
+ const faultBin = path.join(root, 'fault-bin');
+ fs.mkdirSync(faultBin);
+ fs.writeFileSync(path.join(faultBin, 'mv'), [
+ '#!/bin/bash', 'if [[ "${@: -1}" == "$CINDY_TEST_FAIL_DEST" ]]; then',
+ ' /usr/bin/mv "$@"', ' exit 73', 'fi',
+ 'exec /usr/bin/mv "$@"', '',
+ ].join('\n'), { mode: 0o755 });
+ expect(run('1.0.2', true, { env: {
+ PATH: faultBin + path.delimiter + process.env.PATH, CINDY_TEST_FAIL_DEST: path.join(prefix, 'current'),
+ } }).status).toBe(73);
+ expect(fs.readlinkSync(path.join(prefix, 'current'))).toBe(installed);
+ expect(fs.readlinkSync(path.join(prefix, 'previous'))).toBe(previousBeforeFailure);
+ expect(fs.existsSync(path.join(prefix, 'releases', '1.0.2-' + packages.get('1.0.2')!.digest))).toBe(false);
+ expect(run('1.0.2', true, { env: {
+ PATH: faultBin + path.delimiter + process.env.PATH, CINDY_TEST_FAIL_DEST: path.join(prefix, 'previous'),
+ } }).status).toBe(73);
+ expect(fs.readlinkSync(path.join(prefix, 'current'))).toBe(installed);
+ expect(fs.readlinkSync(path.join(prefix, 'previous'))).toBe(previousBeforeFailure);
+ expect(fs.existsSync(path.join(prefix, 'releases', '1.0.2-' + packages.get('1.0.2')!.digest))).toBe(false);
+ // Retrying after a failure immediately before the atomic rename works.
+ expect(run('1.0.2', true).status).toBe(0);
+ expect(fs.readlinkSync(path.join(prefix, 'previous'))).toBe(installed);
+ expect(fs.existsSync(path.join(prefix, before, 'Cindy'))).toBe(true);
+ expect(fs.readdirSync(path.join(prefix, 'releases')).some((name) => name.startsWith('.stage.'))).toBe(false);
+ expect(find()?.current).toContain('1.0.2');
+ expect(findLinuxUserInstallation(path.join(prefix, before, 'Cindy'), path.join(root, 'home'), process.getuid!())).toBeNull();
+ expect(findLinuxUserInstallation(path.join(prefix, 'current', 'Cindy'), prefix, process.getuid!())).toBeNull();
+ });
+ it.each([false, true])('retries hard-interrupted installs without modifying retained releases (apply=%s)', (apply) => {
+ const prefix = path.join(root, 'home', `interrupted-${apply}`);
+ if (apply) expect(run('1.0.0', false, { prefix }).status).toBe(0);
+ const before = apply ? fs.readlinkSync(path.join(prefix, 'current')) : null;
+ const release = 'releases/1.0.1-' + packages.get('1.0.1')!.digest;
+ const faultBin = path.join(root, `kill-bin-${apply}`);
+ fs.mkdirSync(faultBin);
+ fs.writeFileSync(path.join(faultBin, 'mv'), [
+ '#!/bin/bash', '/usr/bin/mv "$@" || exit "$?"',
+ // Kill only the installer parent, after its release or marker rename.
+ 'if [[ "${@: -1}" == "$CINDY_TEST_KILL_DEST" ]]; then kill -KILL "$PPID"; fi', '',
+ ].join('\n'), { mode: 0o755 });
+ const orphans: string[] = [];
+ for (const destination of [path.join(prefix, release), path.join(prefix, '.cindy-user-install')]) {
+ const interrupted = run('1.0.1', apply, { prefix, env: {
+ PATH: faultBin + path.delimiter + process.env.PATH, CINDY_TEST_KILL_DEST: destination,
+ } });
+ expect(interrupted.signal).toBe('SIGKILL');
+ expect(apply ? fs.readlinkSync(path.join(prefix, 'current')) : fs.existsSync(path.join(prefix, 'current'))).toBe(before ?? false);
+ const releases = fs.readdirSync(path.join(prefix, 'releases')).filter((name) => name.startsWith('1.0.1-'));
+ expect(releases).toHaveLength(orphans.length + 1);
+ for (const name of releases) {
+ if (!orphans.includes(name)) {
+ orphans.push(name);
+ fs.writeFileSync(path.join(prefix, 'releases', name, 'sentinel'), 'retained');
+ }
+ }
+ }
+ expect(run('1.0.1', apply, { prefix, digest: '0'.repeat(64) }).status).not.toBe(0);
+ expect(run('1.0.1', apply, { prefix }).status).toBe(0);
+ const current = fs.readlinkSync(path.join(prefix, 'current'));
+ expect(current.startsWith(release + '-')).toBe(true);
+ expect(current.slice(release.length + 1)).toMatch(/^[A-Za-z0-9]{8}$/);
+ expect(fs.existsSync(path.join(prefix, current, 'sentinel'))).toBe(false);
+ for (const name of orphans) expect(fs.readFileSync(path.join(prefix, 'releases', name, 'sentinel'), 'utf8')).toBe('retained');
+ if (apply) expect(fs.readlinkSync(path.join(prefix, 'previous'))).toBe(before);
+ // A successful suffixed install is still idempotent and repairs its launcher.
+ fs.rmSync(path.join(prefix, 'launch'), { force: true });
+ expect(run('1.0.1', false, { prefix }).status).toBe(0);
+ expect(fs.readlinkSync(path.join(prefix, 'current'))).toBe(current);
+ expect(execFileSync(path.join(prefix, 'launch'), { encoding: 'utf8' })).toBe('fixture\n');
+ expect(findLinuxUserInstallation(path.join(prefix, 'current', 'Cindy'), path.join(root, 'home'), process.getuid!())?.current).toBe(current);
+ });
+ it('reinstalls a retained version without reusing or deleting its directory', () => {
+ const prefix = path.join(root, 'home', 'retained');
+ expect(run('1.0.0', false, { prefix }).status).toBe(0);
+ const original = fs.readlinkSync(path.join(prefix, 'current'));
+ fs.writeFileSync(path.join(prefix, original, 'sentinel'), 'retained');
+ expect(run('1.0.1', true, { prefix }).status).toBe(0);
+ const before = fs.readlinkSync(path.join(prefix, 'current'));
+ expect(run('1.0.0', false, { prefix }).status).toBe(0);
+ expect(fs.readlinkSync(path.join(prefix, 'current'))).not.toBe(original);
+ expect(fs.readlinkSync(path.join(prefix, 'previous'))).toBe(before);
+ expect(fs.readFileSync(path.join(prefix, original, 'sentinel'), 'utf8')).toBe('retained');
+ expect(fs.existsSync(path.join(prefix, 'current', 'sentinel'))).toBe(false);
+ const dangling = path.join(prefix, 'releases', '1.0.2-' + packages.get('1.0.2')!.digest);
+ fs.symlinkSync('missing-release', dangling);
+ expect(run('1.0.2', true, { prefix }).status).toBe(0);
+ expect(fs.readlinkSync(dangling)).toBe('missing-release');
+ expect(fs.existsSync(path.join(prefix, 'current', 'Cindy'))).toBe(true);
+ });
+ it('registers a valid stable desktop entry with no real desktop changes', () => {
+ const bin = path.join(root, 'fake-bin');
+ fs.mkdirSync(bin);
+ const mimeLog = path.join(root, 'mime-args');
+ fs.writeFileSync(path.join(bin, 'xdg-mime'), '#!/bin/sh\nprintf "%s\\n" "$@" > "$CINDY_TEST_MIME_LOG"\n', { mode: 0o755 });
+ const data = path.join(root, 'home', 'data');
+ const result = spawnSync('bash', [
+ path.resolve(__dirname, '../../../resources/linux/register-desktop.sh'), prefix,
+ ], {
+ env: { ...process.env, HOME: path.join(root, 'home'), XDG_DATA_HOME: data,
+ XDG_CONFIG_HOME: path.join(root, 'home', 'config'), PATH: bin + path.delimiter + process.env.PATH,
+ CINDY_TEST_MIME_LOG: mimeLog },
+ encoding: 'utf8', timeout: 15_000,
+ });
+ expect(result.stderr).toBe('');
+ expect(result.status).toBe(0);
+ const entries = fs.readdirSync(path.join(data, 'applications')).filter((name) => name.endsWith('.desktop'));
+ expect(entries).toHaveLength(1);
+ expect(entries[0]).toBe(linuxUserDesktopName(prefix));
+ const desktop = fs.readFileSync(path.join(data, 'applications', entries[0]), 'utf8');
+ expect(desktop).toContain('/launch" %U');
+ expect(desktop).not.toContain('/releases/');
+ expect(desktop).toContain('StartupWMClass=' + entries[0].replace(/\.desktop$/, ''));
+ expect(desktop).toContain('space \\\\$literal');
+ expect(fs.readFileSync(mimeLog, 'utf8').trim().split('\n')).toEqual([
+ 'default', entries[0], ...allDeepLinkSchemes().map((scheme) => 'x-scheme-handler/' + scheme),
+ ]);
+ });
+ it('runs the detached updater and relaunches with the same backend on success and failure', () => {
+ const launchLog = path.join(root, 'launch-args');
+ const logPath = path.join(root, 'update.log');
+ const lockFilePath = path.join(root, 'update.lock');
+ for (const [version, valid] of [['1.0.4', true], ['1.0.5', false]] as const) {
+ const pkg = packages.get(version)!;
+ const before = fs.readlinkSync(path.join(prefix, 'current'));
+ const script = buildLinuxUpdateScript({
+ pid: 2147483647, // Outside Linux's pid_max: no real process may be killed.
+ debPath: pkg.file, sha256: valid ? pkg.digest : 'f'.repeat(64), sizeBytes: pkg.size,
+ exePath: path.join(prefix, before, 'Cindy'), lockFilePath, logPath,
+ userInstallation: { prefix, current: before, region: 'global', version },
+ relaunchArgs: ['--password-store=gnome-libsecret'],
+ timings: { lockHeartbeatSeconds: 1, verifyTimeoutSeconds: 3, verifyRetryAtSeconds: 2 },
+ });
+ fs.rmSync(launchLog, { force: true });
+ const result = spawnSync('setsid', ['bash', '-c', script], {
+ env: { ...process.env, HOME: path.join(root, 'home'), CINDY_TEST_LAUNCH_LOG: launchLog },
+ encoding: 'utf8', timeout: 15_000,
+ });
+ // The failed-install path launches asynchronously just before exiting.
+ const wait = spawnSync('bash', ['-c', 'for i in {1..50}; do [[ -s "$1" ]] && exit 0; sleep 0.02; done; exit 1', 'wait', launchLog],
+ { timeout: 3000 });
+ expect(wait.status).toBe(0);
+ const [pid, ...args] = fs.readFileSync(launchLog, 'utf8').trim().split('\n');
+ try {
+ expect(result.stderr).toBe('');
+ expect(result.status).toBe(valid ? 0 : 1);
+ expect(args).toEqual(['--password-store=gnome-libsecret']);
+ expect(fs.readlinkSync(path.join(prefix, 'current'))).toBe(valid ? 'releases/' + version + '-' + pkg.digest : before);
+ expect(fs.existsSync(lockFilePath)).toBe(false);
+ } finally {
+ process.kill(Number(pid), 'SIGTERM'); // Only the fake app this test launched.
+ }
+ }
+ }, 30_000);
+});
diff --git a/apps/desktop/src/main/__tests__/linuxInstallationPreflight.test.ts b/apps/desktop/src/main/__tests__/linuxInstallationPreflight.test.ts
new file mode 100644
index 0000000000..bbb7e6eae6
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/linuxInstallationPreflight.test.ts
@@ -0,0 +1,102 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs';
+import path from 'node:path';
+import { findLinuxUserInstallation, linuxUserDesktopName, recognizeLinuxUserInstallation } from '../linuxInstallation';
+
+// In-memory filesystem answers keep ownership/ACL cases deterministic on all
+// hosts, including root and Windows where chmod cannot model Linux access.
+describe('Linux user installation preflight', () => {
+ const home = path.resolve('fixture-home');
+ const prefix = path.join(home, 'cindy');
+ const current = 'releases/1.0.0-digest';
+ const exe = path.join(prefix, current, 'Cindy');
+ const uid = 1000;
+ const entries = new Map<string, fs.Stats>();
+ const denied = new Set<string>();
+ const stat = (type: 'file' | 'directory' | 'link', owner = uid) => ({
+ uid: owner,
+ isFile: () => type === 'file',
+ isDirectory: () => type === 'directory',
+ isSymbolicLink: () => type === 'link',
+ }) as fs.Stats;
+ const find = () => findLinuxUserInstallation(exe, home, uid);
+ const recognize = () => recognizeLinuxUserInstallation(exe, home, uid);
+ const desktopName = () => {
+ const installation = recognize();
+ return installation && linuxUserDesktopName(installation.prefix);
+ };
+
+ beforeEach(() => {
+ entries.clear();
+ denied.clear();
+ entries.set(prefix, stat('directory'));
+ entries.set(path.join(prefix, '.cindy-user-install'), stat('file'));
+ entries.set(path.join(prefix, 'releases'), stat('directory'));
+ entries.set(path.join(prefix, '.install.lock'), stat('file'));
+ const lookup = (input: fs.PathLike) => {
+ const entry = entries.get(String(input));
+ if (!entry) throw Object.assign(new Error('missing'), { code: 'ENOENT' });
+ return entry;
+ };
+ vi.spyOn(fs, 'realpathSync').mockImplementation((input) => String(input));
+ vi.spyOn(fs, 'statSync').mockImplementation(lookup as typeof fs.statSync);
+ vi.spyOn(fs, 'lstatSync').mockImplementation(lookup as typeof fs.lstatSync);
+ vi.spyOn(fs, 'readlinkSync').mockReturnValue(current);
+ vi.spyOn(fs, 'readFileSync').mockReturnValue('cindy-user-install-v1:global');
+ vi.spyOn(fs, 'accessSync').mockImplementation((input) => {
+ if (denied.has(String(input))) throw Object.assign(new Error('denied'), { code: 'EACCES' });
+ });
+ });
+ afterEach(() => vi.restoreAllMocks());
+
+ it('checks staging and lock access, allowing an absent lock or previous link', () => {
+ expect(find()).toEqual({ prefix, current, region: 'global' });
+ expect(fs.accessSync).toHaveBeenCalledWith(prefix, fs.constants.W_OK | fs.constants.X_OK);
+ expect(fs.accessSync).toHaveBeenCalledWith(path.join(prefix, 'releases'), fs.constants.W_OK | fs.constants.X_OK);
+ expect(fs.accessSync).toHaveBeenCalledWith(path.join(prefix, '.install.lock'), fs.constants.W_OK);
+ entries.delete(path.join(prefix, '.install.lock'));
+ entries.set(path.join(prefix, 'previous'), stat('link'));
+ expect(find()).not.toBeNull();
+ });
+
+ it.each(['', 'releases', '.install.lock'])('rejects denied access to %s until repaired', (name) => {
+ const identity = desktopName();
+ expect(identity).not.toBeNull();
+ const target = path.join(prefix, name);
+ denied.add(target);
+ expect(find()).toBeNull();
+ expect(desktopName()).toBe(identity);
+ denied.delete(target);
+ expect(find()).not.toBeNull();
+ expect(desktopName()).toBe(identity);
+ });
+
+ it.each(['releases', '.install.lock'])('rejects foreign ownership and symlinks at %s', (name) => {
+ const target = path.join(prefix, name);
+ entries.set(target, stat(name === 'releases' ? 'directory' : 'file', uid + 1));
+ expect(find()).toBeNull();
+ expect(recognize()).not.toBeNull();
+ entries.set(target, stat('link'));
+ expect(find()).toBeNull();
+ expect(recognize()).not.toBeNull();
+ });
+
+ it('rejects a non-link previous destination before activation', () => {
+ entries.set(path.join(prefix, 'previous'), stat('directory'));
+ expect(find()).toBeNull();
+ expect(recognize()).not.toBeNull();
+ });
+
+ it('recognizes identity without probing update write access', () => {
+ expect(recognize()).toEqual({ prefix, current, region: 'global' });
+ expect(fs.accessSync).not.toHaveBeenCalled();
+ });
+
+ it.each(['marker contents', 'marker owner', 'current target'])('rejects invalid %s for both identity and update', (invalid) => {
+ if (invalid === 'marker contents') vi.mocked(fs.readFileSync).mockReturnValue('not-cindy');
+ if (invalid === 'marker owner') entries.set(path.join(prefix, '.cindy-user-install'), stat('file', uid + 1));
+ if (invalid === 'current target') vi.mocked(fs.readlinkSync).mockReturnValue('releases/another-release');
+ expect(recognize()).toBeNull();
+ expect(find()).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/linuxPasswordStore.test.ts b/apps/desktop/src/main/__tests__/linuxPasswordStore.test.ts
index 009a3ef2a2..be2ecb369d 100644
--- a/apps/desktop/src/main/__tests__/linuxPasswordStore.test.ts
+++ b/apps/desktop/src/main/__tests__/linuxPasswordStore.test.ts
@@ -1,5 +1,14 @@
import { describe, expect, it, vi } from 'vitest';
-import { configureLinuxPasswordStore } from '../linuxPasswordStore.js';
+import { configureLinuxPasswordStore, linuxPasswordStoreRelaunchArgs } from '../linuxPasswordStore.js';
+
+describe('Linux secure storage startup policy', () => {
+ it('preserves the backend on relaunch without forwarding arbitrary arguments', () => {
+ expect(linuxPasswordStoreRelaunchArgs('gnome-libsecret')).toEqual(['--password-store=gnome-libsecret']);
+ expect(linuxPasswordStoreRelaunchArgs('kwallet6')).toEqual(['--password-store=kwallet6']);
+ expect(linuxPasswordStoreRelaunchArgs('')).toEqual([]);
+ expect(linuxPasswordStoreRelaunchArgs('gnome-libsecret --no-sandbox')).toEqual([]);
+ });
+});
function configure(
env: NodeJS.ProcessEnv,
@@ -49,6 +58,7 @@ describe('Hyprland password store startup selection', () => {
{ XDG_CURRENT_DESKTOP: 'GNOME', DESKTOP_SESSION: 'hyprland' },
{ XDG_CURRENT_DESKTOP: 'KDE', XDG_SESSION_DESKTOP: 'Hyprland' },
{ XDG_CURRENT_DESKTOP: 'sway' },
+ { XDG_CURRENT_DESKTOP: 'niri' },
{ XDG_CURRENT_DESKTOP: 'not-hyprland' },
{ XDG_SESSION_TYPE: 'wayland' },
])('leaves other or unknown desktops to Electron: %j', (env) => {
diff --git a/apps/desktop/src/main/__tests__/updateScriptLinux.test.ts b/apps/desktop/src/main/__tests__/updateScriptLinux.test.ts
index 67cb54ab81..f355d8a7ec 100644
--- a/apps/desktop/src/main/__tests__/updateScriptLinux.test.ts
+++ b/apps/desktop/src/main/__tests__/updateScriptLinux.test.ts
@@ -38,6 +38,20 @@ describe('shellSingleQuote', () => {
describe('buildLinuxUpdateScript structure', () => {
const script = buildLinuxUpdateScript(makeParams());
+ it('uses the embedded transaction and stable launcher for a managed user install', () => {
+ const portable = buildLinuxUpdateScript(makeParams({
+ userInstallation: { prefix: '/home/user/Cindy', current: 'releases/1.0.0-aaa', region: 'global', version: '1.0.1' },
+ relaunchArgs: ['--password-store=gnome-libsecret'],
+ }));
+ expect(portable).not.toContain('PKEXEC=');
+ expect(portable).not.toContain('apt-get install');
+ expect(portable).toContain('cindy-user-install --apply');
+ expect(portable).toContain("nohup '/home/user/Cindy/current/Cindy' '--password-store=gnome-libsecret'");
+ expect(portable).toContain('flock -n 9');
+ expect(portable).toContain('INSTALL_EXIT=$?');
+ if (process.platform !== 'win32') execFileSync('bash', ['-n'], { input: portable });
+ });
+
it('installs the staged .deb through one pkexec bash shell', () => {
expect(script).toContain('PKEXEC=/usr/bin/pkexec');
expect(script).toContain('ELEVATED=\'set -eu');
diff --git a/apps/desktop/src/main/__tests__/updateService.test.ts b/apps/desktop/src/main/__tests__/updateService.test.ts
index d7ede71f8b..37e2b6cda3 100644
--- a/apps/desktop/src/main/__tests__/updateService.test.ts
+++ b/apps/desktop/src/main/__tests__/updateService.test.ts
@@ -38,6 +38,12 @@ const spawnProcess = vi.fn(() => ({
unref: vi.fn(),
on: vi.fn(),
}));
+const findLinuxUserInstallation = vi.fn(() => null);
+const isDebianManagedInstallation = vi.fn(() => false);
+const missingLinuxUserInstallTools = vi.fn(() => [] as string[]);
+vi.mock('../linuxInstallation', () => ({
+ findLinuxUserInstallation, isDebianManagedInstallation, missingLinuxUserInstallTools,
+}));
const checkWindowsUpdaterPrerequisites = vi.fn<
() => { satisfied: boolean; missingFiles: string[] }
>(() => ({
@@ -249,6 +255,12 @@ beforeEach(() => {
readAutoUpdateSettings.mockReset();
readAutoUpdateSettings.mockReturnValue({ autoRelaunchOnIdle: true });
spawnProcess.mockClear();
+ findLinuxUserInstallation.mockReset();
+ findLinuxUserInstallation.mockReturnValue(null);
+ isDebianManagedInstallation.mockReset();
+ isDebianManagedInstallation.mockReturnValue(false);
+ missingLinuxUserInstallTools.mockReset();
+ missingLinuxUserInstallTools.mockReturnValue([]);
checkWindowsUpdaterPrerequisites.mockReset();
checkWindowsUpdaterPrerequisites.mockReturnValue({
satisfied: true,
@@ -449,6 +461,33 @@ function linuxInstallerManifest(version = '0.0.65') {
}
describe('checkForUpdate Linux installer flow', () => {
+ it('does not quit or increment attempts for an unmanaged Linux installation', async () => {
+ download.mockImplementation(async ({ targetPath }: { targetPath: string }) => {
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
+ fs.writeFileSync(targetPath, 'deb');
+ return { path: targetPath, size: 123 };
+ });
+ const service = await freshUpdateService('linux', 'x64');
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
+ service.initUpdateService();
+ try {
+ await expect(service.checkForUpdate(linuxInstallerManifest())).resolves.toBe('ready');
+ ipcListeners.get('update-relaunch')?.({}, 'dark');
+ await vi.waitFor(() => expect(ipcHandlers.get('update-get-status')?.()).toMatchObject({
+ status: 'ready', errorCode: 'linux_installation_unsupported',
+ }));
+ const info = JSON.parse(fs.readFileSync(path.join(TEST_USER_DATA, 'updates', 'patch-info.json'), 'utf8'));
+ expect(info.applyAttempts).toBeUndefined();
+ expect(fs.existsSync(path.join(TEST_USER_DATA, 'updates', info.fileName))).toBe(true);
+ expect(spawnProcess).not.toHaveBeenCalled();
+ expect(exitSpy).not.toHaveBeenCalled();
+ expect(service.isUpdateRelaunchImminent()).toBe(false);
+ } finally {
+ service.stopUpdateService();
+ exitSpy.mockRestore();
+ }
+ });
+
it('downloads the Linux installer .deb instead of a hotfix zip', async () => {
readAutoUpdateSettings.mockReturnValue({ autoRelaunchOnIdle: false });
download.mockImplementation(async ({ targetPath }: { targetPath: string }) => {
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts
index 05ca864805..e3d2884293 100644
--- a/apps/desktop/src/main/index.ts
+++ b/apps/desktop/src/main/index.ts
@@ -4,6 +4,7 @@ import { ensureMacPackageManagerPath } from './agentToolPath.js';
import { app } from 'electron';
import { execFileSync } from 'node:child_process';
import path from 'node:path';
+import os from 'node:os';
import { setDefaultAutoSelectFamilyAttemptTimeout } from 'node:net';
import { exit, stderr } from 'node:process';
import { BRAND_IDENTITY } from '@cindy/maker-shared/brand-identity';
@@ -14,6 +15,12 @@ import { createLogger, initLogger } from './logger.js';
import { beginDesktopDevInstance, type DesktopDevMode } from './devStartupStatus.js';
import { ensureSystemBinPathForMachineId } from './deviceId.js';
import { configureLinuxPasswordStore } from './linuxPasswordStore.js';
+import { recognizeLinuxUserInstallation, linuxUserDesktopName } from './linuxInstallation.js';
+
+if (process.platform === 'linux' && app.isPackaged) {
+ const installation = recognizeLinuxUserInstallation(app.getPath('exe'), os.homedir(), process.getuid?.() ?? -1);
+ if (installation) app.setDesktopName(linuxUserDesktopName(installation.prefix));
+}
// Backend selection must precede ready and the dynamic bootstrap/auth imports.
// This default never overrides --password-store; no plaintext fallback is added.
diff --git a/apps/desktop/src/main/linuxInstallation.ts b/apps/desktop/src/main/linuxInstallation.ts
new file mode 100644
index 0000000000..7b9c440aa0
--- /dev/null
+++ b/apps/desktop/src/main/linuxInstallation.ts
@@ -0,0 +1,107 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+
+/** Same identity as register-desktop.sh, stable across releases and valid for
+ * portals requiring reverse-DNS application IDs. This does not rename the app
+ * or its keyring identity.
+ */
+export function linuxUserDesktopName(prefix: string): string {
+ return `com.xd.cindy.user.h${createHash('sha256').update(prefix).digest('hex').slice(0, 16)}.desktop`;
+}
+
+/** Only our marked, user-owned release layout is eligible for unprivileged
+ * self-update. A writable arbitrary directory is not an installation contract.
+ */
+export interface LinuxUserInstallation {
+ prefix: string;
+ current: string;
+ region: 'global' | 'cn';
+}
+
+/** Recognize the stable desktop identity without requiring update access. */
+export function recognizeLinuxUserInstallation(
+ exePath: string, home: string, uid: number,
+): LinuxUserInstallation | null {
+ try {
+ const exe = fs.realpathSync(exePath);
+ const release = path.dirname(exe);
+ const prefix = path.dirname(path.dirname(release));
+ const relative = path.relative(fs.realpathSync(home), prefix);
+ if (!relative || relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)) return null;
+ if (path.basename(exe) !== 'Cindy' || path.basename(path.dirname(release)) !== 'releases') return null;
+ const markerPath = path.join(prefix, '.cindy-user-install');
+ const marker = fs.lstatSync(markerPath);
+ if (!marker.isFile() || marker.uid !== uid || fs.statSync(prefix).uid !== uid) return null;
+ const identity = fs.readFileSync(markerPath, 'utf8').trim();
+ const region = identity === 'cindy-user-install-v1:global' ? 'global'
+ : identity === 'cindy-user-install-v1:cn' ? 'cn' : null;
+ if (!region) return null;
+ const current = fs.readlinkSync(path.join(prefix, 'current'));
+ if (!/^releases\/[A-Za-z0-9.+-]+$/.test(current)) return null;
+ if (fs.realpathSync(path.join(prefix, current)) !== release) return null;
+ return { prefix, current, region };
+ } catch { return null; }
+}
+
+/** Strict preflight for self-update, checked again before stopping work. */
+export function findLinuxUserInstallation(
+ exePath: string, home: string, uid: number,
+): LinuxUserInstallation | null {
+ const installation = recognizeLinuxUserInstallation(exePath, home, uid);
+ if (!installation) return null;
+ const { prefix } = installation;
+ try {
+ // Check the paths the installer actually writes before stopping active
+ // work. A writable prefix alone says nothing about staging or flock.
+ const releasesPath = path.join(prefix, 'releases');
+ const releases = fs.lstatSync(releasesPath);
+ if (!releases.isDirectory() || releases.uid !== uid) return null;
+ fs.accessSync(prefix, fs.constants.W_OK | fs.constants.X_OK);
+ fs.accessSync(releasesPath, fs.constants.W_OK | fs.constants.X_OK);
+ for (const name of ['.install.lock', 'previous']) {
+ const entryPath = path.join(prefix, name);
+ let entry: fs.Stats;
+ try { entry = fs.lstatSync(entryPath); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;
+ throw error;
+ }
+ if (name === '.install.lock') {
+ if (!entry.isFile() || entry.uid !== uid) return null;
+ fs.accessSync(entryPath, fs.constants.W_OK);
+ } else if (!entry.isSymbolicLink()) return null;
+ }
+ return installation;
+ } catch { return null; }
+}
+
+/** Query ownership, not just tool existence: dpkg installed on Arch must not
+ * cause us to install a second Cindy while relaunching a pacman-owned binary.
+ */
+export function isDebianManagedInstallation(
+ exePath: string,
+ query: (exe: string) => string = (exe) => execFileSync('/usr/bin/dpkg-query', ['-S', exe], {
+ encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'],
+ }),
+): boolean {
+ try {
+ return query(exePath).split('\n').some((line) => /^cindy(?::[a-z0-9]+)?: /.test(line)
+ && line.slice(line.indexOf(': ') + 2) === exePath);
+ } catch { return false; }
+}
+
+export function missingLinuxUserInstallTools(
+ probe: (name: string) => boolean = (name) => {
+ try {
+ execFileSync('/bin/bash', ['-c', 'command -v -- "$1" >/dev/null', 'cindy-probe', name], {
+ timeout: 2000, stdio: 'ignore',
+ });
+ return true;
+ } catch { return false; }
+ },
+): string[] {
+ return ['bsdtar', 'sha256sum', 'stat', 'dd', 'mktemp', 'realpath', 'flock', 'find', 'readlink', 'mv', 'ln', 'setsid', 'pgrep']
+ .filter((name) => !probe(name));
+}
diff --git a/apps/desktop/src/main/linuxPasswordStore.ts b/apps/desktop/src/main/linuxPasswordStore.ts
index be8ba7e6fb..1dd3fb7f2c 100644
--- a/apps/desktop/src/main/linuxPasswordStore.ts
+++ b/apps/desktop/src/main/linuxPasswordStore.ts
@@ -1,3 +1,9 @@
+/** Preserve only the storage selector, not URLs or transient task arguments. */
+export function linuxPasswordStoreRelaunchArgs(value: string): string[] {
+ return ['gnome-libsecret', 'kwallet', 'kwallet5', 'kwallet6', 'basic'].includes(value)
+ ? [`--password-store=${value}`] : [];
+}
+
/** Configure before Electron's ready event, without probing or opening the keyring. */
export function configureLinuxPasswordStore({
platform,
diff --git a/apps/desktop/src/main/updateScriptLinux.ts b/apps/desktop/src/main/updateScriptLinux.ts
index 52e64f4115..9f8dfa3174 100644
--- a/apps/desktop/src/main/updateScriptLinux.ts
+++ b/apps/desktop/src/main/updateScriptLinux.ts
@@ -1,9 +1,12 @@
+import userInstallerSource from '../../resources/linux/install-user.sh?raw';
+import type { LinuxUserInstallation } from './linuxInstallation';
+
/**
* updateScriptLinux — pure builder for the Linux .deb update-apply bash script.
*
* Linux has no cindy-updater binary. After the Electron process exits, this
- * script asks polkit (pkexec) to install the staged .deb over the existing
- * package, then relaunches the same executable path.
+ * script either applies a managed user install without elevation, or asks
+ * polkit to replace a Debian-owned package, then relaunches the stable entry.
*
* Extracted so the generated script can be regression-tested without Electron.
*/
@@ -44,6 +47,9 @@ export interface LinuxUpdateScriptParams {
lockFilePath: string;
/** cindy-update.log path. */
logPath: string;
+ /** Only a validated, marked user install may bypass the package manager. */
+ userInstallation?: LinuxUserInstallation & { version: string };
+ relaunchArgs?: string[];
timings?: Partial<LinuxUpdateScriptTimings>;
}
@@ -86,6 +92,9 @@ export function buildLinuxUpdateScript(params: LinuxUpdateScriptParams): string
const qExe = shellSingleQuote(exePath);
const qLock = shellSingleQuote(lockFilePath);
const qSha = shellSingleQuote(sha256);
+ const userInstallation = params.userInstallation;
+ const launchPath = userInstallation ? `${userInstallation.prefix}/current/Cindy` : exePath;
+ const launch = [launchPath, ...(params.relaunchArgs ?? [])].map(shellSingleQuote).join(' ');
return [
'#!/bin/bash',
@@ -131,7 +140,7 @@ export function buildLinuxUpdateScript(params: LinuxUpdateScriptParams): string
` wait "$LOCK_HEARTBEAT_PID" 2>/dev/null`,
' rm -f "$INSTALL_PID_FILE"',
` rm -f ${qLock}`,
- ` setsid nohup ${qExe} >/dev/null 2>&1 &`,
+ ` setsid nohup ${launch} >/dev/null 2>&1 &`,
' LAUNCHED_PID=$!',
'}',
'(',
@@ -174,7 +183,7 @@ export function buildLinuxUpdateScript(params: LinuxUpdateScriptParams): string
'trap cleanup EXIT',
'',
`echo "[$(date)] Update script started, waiting for PID ${pid}" >> ${qLog}`,
- `echo "[$(date)] deb=${qDeb} exe=${qExe}" >> ${qLog}`,
+ `printf '[%s] deb=%s exe=%s\\n' "$(date)" ${qDeb} ${qExe} >> ${qLog}`,
'',
'WAITED=0',
`while kill -0 ${pid} 2>/dev/null; do`,
@@ -192,6 +201,12 @@ export function buildLinuxUpdateScript(params: LinuxUpdateScriptParams): string
`echo "[$(date)] Process ${pid} exited, waiting for filesystem to settle" >> ${qLog}`,
'sleep 2',
'',
+ ...(userInstallation ? [
+ // Source is embedded in the packaged application, never loaded
+ // from a mutable external helper or a pinned system Node installation.
+ `INSTALLER=${shellSingleQuote(userInstallerSource)}`,
+ `bash -c "$INSTALLER" cindy-user-install --apply ${qDeb} ${qSha} ${sizeBytes} ${shellSingleQuote(userInstallation.prefix)} ${shellSingleQuote(userInstallation.version)} ${shellSingleQuote(userInstallation.region)} ${shellSingleQuote(userInstallation.current)} >> ${qLog} 2>&1 &`,
+ ] : [
'PKEXEC=/usr/bin/pkexec',
'if [ ! -x "$PKEXEC" ]; then',
' PKEXEC=$(command -v pkexec 2>/dev/null || true)',
@@ -247,6 +262,7 @@ export function buildLinuxUpdateScript(params: LinuxUpdateScriptParams): string
'',
`echo "[$(date)] invoking elevated installer via pkexec" >> ${qLog}`,
`"$PKEXEC" /bin/bash -c "$ELEVATED" bash ${qSha} ${qDeb} ${sizeBytes} >> ${qLog} 2>&1 &`,
+ ]),
'INSTALL_PID=$!',
`echo "$INSTALL_PID" > "$INSTALL_PID_FILE"`,
'wait "$INSTALL_PID"',
@@ -260,7 +276,7 @@ export function buildLinuxUpdateScript(params: LinuxUpdateScriptParams): string
' exit 1',
'fi',
'',
- `echo "[$(date)] Starting app: ${qExe}" >> ${qLog}`,
+ `printf '[%s] Starting app: %s\\n' "$(date)" ${shellSingleQuote(launchPath)} >> ${qLog}`,
// 先杀心跳、放锁,再 setsid 拉起:新进程不在本进程组里,不会
// 被 scan_group_others 误判成安装链,也不会卡在自己的锁上。
'relaunch_app',
@@ -279,7 +295,7 @@ export function buildLinuxUpdateScript(params: LinuxUpdateScriptParams): string
' fi',
` if [ "$i" -eq ${t.verifyRetryAtSeconds} ]; then`,
` echo "[$(date)] still not up after ${t.verifyRetryAtSeconds}s — retrying relaunch" >> ${qLog}`,
- ` setsid nohup ${qExe} >/dev/null 2>&1 &`,
+ ` setsid nohup ${launch} >/dev/null 2>&1 &`,
' LAUNCHED_PID=$!',
' fi',
' sleep 1',
diff --git a/apps/desktop/src/main/updateService.ts b/apps/desktop/src/main/updateService.ts
index bfaf42e15f..a38f0051b9 100644
--- a/apps/desktop/src/main/updateService.ts
+++ b/apps/desktop/src/main/updateService.ts
@@ -66,6 +66,9 @@ import { throwIpcError } from './utils/ipcValidate';
import { noteExpectedExit } from './startup-diagnostics';
import { buildMacOSUpdateScript } from './updateScriptMacOS';
import { buildLinuxUpdateScript, normalizeLinuxDebSha256 } from './updateScriptLinux';
+import { findLinuxUserInstallation, isDebianManagedInstallation, missingLinuxUserInstallTools, type LinuxUserInstallation } from './linuxInstallation';
+import { linuxPasswordStoreRelaunchArgs } from './linuxPasswordStore';
+import { CURRENT_CINDY_REGION } from '../shared/brandRegion';
import { disposeAndroidAdb } from './mcp-integrations/android';
import { abortIOSSimulatorOperationsForExit } from './mcp-integrations/ios-simulator-exit';
import { getGhostNodeRuntimeBroker } from './cindy-brain/index';
@@ -1720,7 +1723,7 @@ function readStagedLinuxDebSha256(debPath: string): string | null {
return linuxStagedDebSha256;
}
-function executeUpdateLinux(debPath: string): void {
+function executeUpdateLinux(debPath: string, installation: LinuxUserInstallation | null): void {
const exePath = app.getPath('exe');
const lockFilePath = getUpdateLockPath();
const logDir = path.join(app.getPath('userData'), 'logs');
@@ -1762,8 +1765,19 @@ function executeUpdateLinux(debPath: string): void {
let script: string;
try {
+ // Do not change installation strategy after the preflight (there is an
+ // await while reclaiming runners). A changed layout must fail closed.
+ const now = findLinuxUserInstallation(exePath, os.homedir(), process.getuid?.() ?? -1);
+ if (installation
+ ? !now || now.prefix !== installation.prefix || now.current !== installation.current
+ || now.region !== installation.region || !readyVersion
+ : now !== null || !isDebianManagedInstallation(exePath)) {
+ throw new Error('Linux installation changed after preflight');
+ }
script = buildLinuxUpdateScript({
pid, debPath, sha256, sizeBytes, exePath, lockFilePath, logPath,
+ userInstallation: installation ? { ...installation, version: readyVersion! } : undefined,
+ relaunchArgs: linuxPasswordStoreRelaunchArgs(app.commandLine?.getSwitchValue('password-store') ?? ''),
});
} catch (err) {
log.error('failed to build Linux update script:', err);
@@ -1918,6 +1932,25 @@ async function executeRelaunchUnguarded(theme: 'light' | 'dark', checkForBinaryU
// keeps both Cindy and the already-downloaded patch intact.
if (!ensureWindowsUpdaterPrerequisites()) return;
+ // Do not stop active work or quit into a Debian-only installer on Arch.
+ // This also protects pacman/AUR-owned and manually unpacked applications.
+ let linuxInstallation: LinuxUserInstallation | null = null;
+ if (process.platform === 'linux') {
+ const exePath = app.getPath('exe');
+ const installation = findLinuxUserInstallation(exePath, os.homedir(), process.getuid?.() ?? -1);
+ linuxInstallation = installation;
+ const supported = installation
+ ? installation.region === CURRENT_CINDY_REGION && missingLinuxUserInstallTools().length === 0
+ : isDebianManagedInstallation(exePath);
+ if (!supported) {
+ log.error('Linux installation cannot self-update; use the installation guide or its package manager');
+ isRelaunching = false;
+ autoRelaunchInProgress = false;
+ setStatus('ready', { version: readyVersion ?? undefined, errorCode: 'linux_installation_unsupported' });
+ return;
+ }
+ }
+
// Gate *before* the updater is spawned, not inside forceQuit: once the
// updater script is running it polls our pid and SIGKILLs us after 120s
// (`updateScriptMacOS.ts`), so a late decision not to exit does not keep this
@@ -1957,7 +1990,7 @@ async function executeRelaunchUnguarded(theme: 'light' | 'dark', checkForBinaryU
break;
case 'linux':
incrementApplyAttempts();
- executeUpdateLinux(readyFilePath);
+ executeUpdateLinux(readyFilePath, linuxInstallation);
break;
default:
log.error(`Unsupported platform: ${process.platform}`);
diff --git a/apps/desktop/src/main/vendor.d.ts b/apps/desktop/src/main/vendor.d.ts
index 59a9063f26..4eeffd531d 100644
--- a/apps/desktop/src/main/vendor.d.ts
+++ b/apps/desktop/src/main/vendor.d.ts
@@ -14,6 +14,11 @@ declare module '*.md?raw' {
export default content;
}
+declare module '*.sh?raw' {
+ const content: string;
+ export default content;
+}
+
declare module '*.cjs?raw' {
const content: string;
export default content;
diff --git a/apps/desktop/src/renderer/__tests__/updateBannerRelaunchEntry.test.tsx b/apps/desktop/src/renderer/__tests__/updateBannerRelaunchEntry.test.tsx
index 3db7c650d3..e656693418 100644
--- a/apps/desktop/src/renderer/__tests__/updateBannerRelaunchEntry.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/updateBannerRelaunchEntry.test.tsx
@@ -53,7 +53,7 @@ vi.mock('@/hooks/useUpdateStatus', () => ({
vi.mock('@/hooks/useUpdateBannerDismiss', () => ({
useUpdateBannerDismiss: () => ({
dismissed: dismissState.dismissed,
- reason: null,
+ reason: dismissState.dismissed ? 'user' : null,
dismiss: () => { dismissState.dismissed = true; },
restore: () => { dismissState.dismissed = false; },
deferBecauseBusy: vi.fn(),
@@ -105,6 +105,67 @@ beforeEach(() => {
afterEach(cleanup);
describe('UpdateBanner relaunch entry', () => {
+ it.each([false, true].flatMap(busy => [false, true].flatMap(hidden =>
+ [false, true].map(collapsed => ({ busy, hidden, collapsed })),
+ )))('keeps repeated Linux failures actionable ($busy/$hidden/$collapsed)', async ({ busy, hidden, collapsed }) => {
+ updateStatus.current.errorCode = 'linux_installation_unsupported';
+ dismissState.dismissed = hidden;
+ anyActivityBlockingRelaunch.mockResolvedValue(busy);
+ const { rerender } = render(<UpdateBanner isCollapsed={collapsed} />);
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
+ fireEvent.click(await screen.findByRole('button', { name: 'update.linuxInstallation.retry' }));
+ if (busy) {
+ fireEvent.click(await screen.findByRole('button', { name: 'update.banner.confirmAria' }));
+ }
+ await waitFor(() => expect(relaunchToUpdate).toHaveBeenCalledTimes(attempt));
+ // Identical main-process result: no boolean error transition to rescue UI.
+ rerender(<UpdateBanner isCollapsed={collapsed} />);
+ await screen.findByText('update.linuxInstallation.title');
+ expect(screen.queryByRole('button', { name: 'update.banner.confirmAria' })).toBeNull();
+ }
+ updateStatus.current = { status: 'idle', errorCode: null };
+ rerender(<UpdateBanner isCollapsed={collapsed} />);
+ expect(screen.queryByText('update.linuxInstallation.title')).toBeNull();
+ });
+
+ it.each([false, true])('cancelling a Linux recheck ignores its late busy=%s result', async (busy) => {
+ updateStatus.current.errorCode = 'linux_installation_unsupported';
+ const settle = deferredProbe();
+ render(<UpdateBanner isCollapsed={false} />);
+ fireEvent.click(await screen.findByRole('button', { name: 'update.linuxInstallation.retry' }));
+ fireEvent.click(screen.getByRole('button', { name: 'update.linuxInstallation.later' }));
+ settle(busy);
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(relaunchToUpdate).not.toHaveBeenCalled();
+ expect(screen.queryByRole('button', { name: 'update.banner.confirmAria' })).toBeNull();
+ });
+
+ it('checks active work again when retrying a Linux update after repairing dependencies', async () => {
+ updateStatus.current.errorCode = 'linux_installation_unsupported';
+ anyActivityBlockingRelaunch.mockResolvedValue(true);
+ render(<UpdateBanner isCollapsed={false} />);
+ fireEvent.click(await screen.findByRole('button', { name: 'update.linuxInstallation.retry' }));
+ await waitFor(() => expect(anyActivityBlockingRelaunch).toHaveBeenCalledTimes(1));
+ expect(relaunchToUpdate).not.toHaveBeenCalled();
+ });
+
+ it.each(['light', 'dark'])('offers the Linux guide without restarting in %s mode', async (theme) => {
+ document.documentElement.classList.toggle('dark', theme === 'dark');
+ updateStatus.current.errorCode = 'linux_installation_unsupported';
+ render(<UpdateBanner isCollapsed={false} />);
+ await screen.findByText('update.linuxInstallation.title');
+ fireEvent.click(screen.getByRole('button', { name: 'update.linuxInstallation.later' }));
+ await waitFor(() => expect(screen.queryByText('update.linuxInstallation.title')).toBeNull());
+ fireEvent.click(screen.getByRole('button', { name: 'update.banner.ariaExpanded' }));
+ await screen.findByText('update.linuxInstallation.title');
+ fireEvent.click(screen.getByRole('button', { name: 'update.linuxInstallation.guide' }));
+ expect(openExternal).toHaveBeenCalledWith('https://github.com/makecindy/cindy/blob/main/docs/linux.md');
+ expect(anyActivityBlockingRelaunch).not.toHaveBeenCalled();
+ expect(relaunchToUpdate).not.toHaveBeenCalled();
+ document.documentElement.classList.remove('dark');
+ });
+
it('prompts for the VC++ Runtime, keeps the banner, and rechecks on demand', async () => {
updateStatus.current = {
status: 'ready',
diff --git a/apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx b/apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx
index 097e8328e5..2f76170b9f 100644
--- a/apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx
+++ b/apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx
@@ -108,6 +108,7 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP
const restoreFocusRef = useRef(false);
const [showTranslocatedDialog, setShowTranslocatedDialog] = useState(false);
const [showWindowsRuntimeDialog, setShowWindowsRuntimeDialog] = useState(false);
+ const [showLinuxInstallationDialog, setShowLinuxInstallationDialog] = useState(false);
const { t } = useTranslation();
const [showSpawnFailedDialog, setShowSpawnFailedDialog] = useState(false);
@@ -120,8 +121,14 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP
const isSpawnFailed = status === 'error' && errorCode === 'updater_spawn_failed';
const isWindowsRuntimeMissing =
status === 'ready' && errorCode === 'windows_vc_runtime_missing';
+ const isLinuxInstallationUnsupported =
+ status === 'ready' && errorCode === 'linux_installation_unsupported';
const isPreparing = status === 'superseding';
+ useEffect(() => {
+ if (isLinuxInstallationUnsupported) setShowLinuxInstallationDialog(true);
+ }, [isLinuxInstallationUnsupported]);
+
useEffect(() => {
if (isWindowsRuntimeMissing) setShowWindowsRuntimeDialog(true);
}, [isWindowsRuntimeMissing]);
@@ -137,11 +144,11 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP
// 一旦不再是 ready(如被 superseding 顶掉 / 出错),复位确认态,避免残留一个
// 指向旧补丁的「仍要重启」;同时作废在飞的探针 —— 它的结论建立在「当前补丁可装」之上。
useEffect(() => {
- if (status !== 'ready' || isWindowsRuntimeMissing) {
+ if (status !== 'ready' || isWindowsRuntimeMissing || isLinuxInstallationUnsupported) {
relaunchEpochRef.current += 1;
setConfirming(false);
}
- }, [status, isWindowsRuntimeMissing]);
+ }, [status, isWindowsRuntimeMissing, isLinuxInstallationUnsupported]);
// 卸载时同样作废在飞的探针。卸载后 setConfirming 只是一次无效更新,但 handleRelaunch
// 会真的把 app 重启掉 —— 这条 cleanup 不是防 React 警告,是防意外重启。
@@ -212,6 +219,12 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP
|| (dismissed && (status === 'ready' || isPreparing));
const handleRelaunch = () => {
+ // Main may emit exactly the same prerequisite error again. Keep the
+ // prompt visible without relying on a false -> true error transition.
+ if (isLinuxInstallationUnsupported) {
+ setConfirming(false);
+ setShowLinuxInstallationDialog(true);
+ }
const theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light';
window.electronAPI.relaunchToUpdate(theme);
};
@@ -236,10 +249,18 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP
// 卸载、已就绪补丁可能被 superseding 顶掉。少了它们,「点了稍后却重启」「装回旧补丁」
// 「confirming 残留到下次唤回」三种都会真实发生。
const handleRelaunchClick = async (): Promise<void> => {
+ if (isLinuxInstallationUnsupported) {
+ setShowLinuxInstallationDialog(true);
+ return;
+ }
if (isWindowsRuntimeMissing) {
setShowWindowsRuntimeDialog(true);
return;
}
+ await probeBeforeRelaunch();
+ };
+
+ const probeBeforeRelaunch = async (): Promise<void> => {
if (relaunchProbeRef.current) return;
relaunchProbeRef.current = true;
const epoch = relaunchEpochRef.current;
@@ -257,8 +278,10 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP
// status 变化的作废由上面那个 effect 打点,但 effect 会晚一拍;这里直接读最新值,
// 关掉「已 setState 未跑 effect」的那段窗口。两道判定针对同一不变量的不同触发路径。
if (statusRef.current !== 'ready') return;
- if (hasInFlight) setConfirming(true);
- else handleRelaunch();
+ if (hasInFlight) {
+ setShowLinuxInstallationDialog(false);
+ setConfirming(true);
+ } else handleRelaunch();
};
const handleMoveToApplications = () => {
@@ -281,11 +304,16 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP
void window.electronAPI.openExternal(WINDOWS_VC_RUNTIME_DOWNLOAD_URL);
};
- const handleWindowsRuntimeRetry = () => {
+ const handlePrerequisiteRetry = () => {
const theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light';
window.electronAPI.relaunchToUpdate(theme);
};
+ const handleLinuxDialogOpenChange = (open: boolean) => {
+ if (!open) relaunchEpochRef.current += 1;
+ setShowLinuxInstallationDialog(open);
+ };
+
// 文字链要显示的版本 —— undefined 即不显示。ready 态之外(superseding / error)没有
// 可信版本号,confirming 态则刻意让位给两步确认。hasNotes 已经蕴含「ready + 该版本
// 公告可渲染」,这里再显式列出条件,读代码时不必回溯 effect。
@@ -301,8 +329,28 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP
// nothing because the patch has already been cleared).
const isErrorOnly = isTranslocated || isSpawnFailed;
- const withWindowsRuntimeDialog = (content: ReactNode) => (
+ const withPrerequisiteDialogs = (content: ReactNode) => (
<>
+ {isLinuxInstallationUnsupported && (
+ <ConfirmDialog
+ open={showLinuxInstallationDialog}
+ onOpenChange={handleLinuxDialogOpenChange}
+ title={t('update.linuxInstallation.title')}
+ description={t('update.linuxInstallation.description')}
+ confirmText={t('update.linuxInstallation.guide')}
+ tertiaryText={t('update.linuxInstallation.retry')}
+ cancelText={t('update.linuxInstallation.later')}
+ autoFocusConfirm
+ onConfirm={() => {
+ handleLinuxDialogOpenChange(false);
+ void window.electronAPI.openExternal('https://github.com/makecindy/cindy/blob/main/docs/linux.md');
+ }}
+ onCancel={() => handleLinuxDialogOpenChange(false)}
+ onTertiary={() => {
+ void probeBeforeRelaunch();
+ }}
+ />
+ )}
{isWindowsRuntimeMissing && (
<ConfirmDialog
open={showWindowsRuntimeDialog}
@@ -314,7 +362,7 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP
cancelText={t('update.windowsRuntimeMissing.later')}
autoFocusConfirm
onConfirm={handleWindowsRuntimeDownload}
- onTertiary={handleWindowsRuntimeRetry}
+ onTertiary={handlePrerequisiteRetry}
onCancel={() => setShowWindowsRuntimeDialog(false)}
/>
)}
@@ -362,10 +410,11 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP
// The prerequisite dialog must not be suppressed by the normal busy/dismiss
// rules. After the user chooses "later", the usual banner visibility rules
- // resume and clicking the update entry opens this dialog again.
- if (!isCollapsed && hideExpandedBanner) return withWindowsRuntimeDialog(null);
- if (isCollapsed && dismissed && reason === 'user' && (status === 'ready' || isPreparing)) {
- return withWindowsRuntimeDialog(null);
+ // resume and clicking the update entry opens this dialog again. Explicit
+ // retry confirmation also remains visible when the banner was busy-deferred.
+ if (!isCollapsed && hideExpandedBanner && !confirming) return withPrerequisiteDialogs(null);
+ if (isCollapsed && dismissed && reason === 'user' && !confirming && (status === 'ready' || isPreparing)) {
+ return withPrerequisiteDialogs(null);
}
// ── Collapsed state: icon only ──
@@ -373,7 +422,7 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP
// 确认态(仅在有任务在跑时出现):上方 ✓(仍要重启,占据原 Flame 图标位置,鼠标零位移),
// 下方 ✕(取消)。收起态没有文案位置,「会打断进行中的任务」只能落在 ✓ 的 tooltip 上。
if (confirming && !isPreparing) {
- return withWindowsRuntimeDialog(
+ return withPrerequisiteDialogs(
<div className="flex flex-col items-center gap-0.5 border-t border-sidebar-border py-1.5">
<Tip text={t('update.banner.confirmTooltip')} side="right">
<button
@@ -406,7 +455,7 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP
);
}
- return withWindowsRuntimeDialog(
+ return withPrerequisiteDialogs(
<div className="flex flex-col items-center border-t border-sidebar-border">
<Tip
text={isPreparing
@@ -442,7 +491,7 @@ export function UpdateBanner({ isCollapsed, onOpenVersionNotice }: UpdateBannerP
}
// ── Expanded state: full banner ──
- return withWindowsRuntimeDialog(
+ return withPrerequisiteDialogs(
<div className="flex select-none flex-col border-t border-sidebar-border">
<div className="relative flex flex-col items-center gap-[10px] px-4 py-3">
{/* X dismiss —— 右上角。error 态 body 本就隐藏,superseding 允许 dismiss。
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 5be9f504b2..1cf0663fc4 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -881,10 +881,10 @@
},
"linuxUpdates": {
"title": "Linux install and updates",
- "description": "Linux currently ships as a .deb for Ubuntu 22.04 / 24.04. When a newer build is available, the app downloads it and asks for your system password to install.",
- "item1": "First install with sudo apt install ./cindy-<version>-<arch>.deb (amd64 on x64, arm64 on arm64).",
- "item2": "In-app updates download the .deb. After you choose Update, a system prompt installs it over the current package.",
- "item3": "Linux x64 supports the Beta channel; arm64 does not yet. Neither architecture supports idle auto-install because installation requires system authorization."
+ "description": "Ubuntu uses system .deb packages. Arch Linux and Omarchy use the managed user installer with the same verified .deb payload, without a Debian package manager.",
+ "item1": "Ubuntu: use sudo apt install ./cindy-<version>-<arch>.deb. Arch/Omarchy: follow the user-install guide in docs/linux.md.",
+ "item2": "After choosing Update, system .deb installs request authorization; managed user installs switch versions without a system password. Other package-managed installs use their package manager.",
+ "item3": "Linux x64 supports the Beta channel; arm64 does not yet. Linux updates are applied only when you choose to restart, never automatically while idle."
},
"qnaTitle": "Ask directly",
"qnaDescription": "If the overview does not cover your question, ask what you want to do and I will point you to the right path.",
@@ -945,7 +945,7 @@
"openLogsDirError": "Failed to open logs directory",
"autoUpdateLabel": "Install updates while idle",
"autoUpdateDescription": "After an update finishes downloading, restart the app to install it when this computer has been idle for 10 minutes and no tasks are running.",
- "linuxUpdateDescription": "When a newer build is available, Cindy downloads the .deb in the app. Installing it asks for your system password, so updates are not applied while idle.",
+ "linuxUpdateDescription": "Updates require a restart you choose. System .deb installs request your system password; managed user installs do not. Other installations use their package manager.",
"autoUpdateEnabledToast": "Idle update installation enabled",
"autoUpdateDisabledToast": "Idle update installation disabled",
"autoUpdateSaveFailed": "Failed to save auto-update settings",
@@ -6322,7 +6322,7 @@
"ready": "New version ready — click the sidebar to apply",
"manifestFailed": "Update check failed, please check your network",
"downloadFailed": "New version download failed, try again later",
- "manualDownload": "Download the update in the app. Installing it requires your system password."
+ "manualDownload": "Download in the app, then choose when to restart. Only system .deb installs require a system password."
},
"closeConfirm": {
"title": "Confirm exit?",
@@ -7219,6 +7219,13 @@
"move": "Move Now (Recommended)",
"download": "Download manually"
},
+ "linuxInstallation": {
+ "title": "This installation cannot update itself",
+ "description": "Use your package manager, or follow the Linux user-install guide. A managed install may need missing tools or write access restored. Cindy and the downloaded update have been kept.",
+ "guide": "Open Linux guide",
+ "retry": "Check again",
+ "later": "Later"
+ },
"windowsRuntimeMissing": {
"title": "Microsoft Visual C++ Runtime Required",
"description": "This PC is missing the Microsoft Visual C++ Runtime required by the updater. The downloaded update will be kept. Install Microsoft's official x64 Runtime, then check again.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 2e06f44e00..98020266d0 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -881,10 +881,10 @@
},
"linuxUpdates": {
"title": "Linux のインストールと更新",
- "description": "Linux は現在 Ubuntu 22.04 / 24.04 向けの .deb として提供されます。新しいビルドがある場合、アプリがダウンロードし、インストール時にシステムパスワードを求めます。",
- "item1": "初回は sudo apt install ./cindy-<バージョン>-<アーキテクチャ>.deb でインストールします(x64 は amd64、arm64 は arm64)。",
- "item2": "アプリ内更新は .deb をダウンロードします。更新を選ぶと、システム権限の確認後に上書きインストールします。",
- "item3": "Linux x64 では Beta チャネルを利用できますが、arm64 は現時点で利用できません。インストールにはシステム認証が必要なため、どちらもアイドル時の自動インストールには対応していません。"
+ "description": "Ubuntu はシステムの .deb パッケージを使用します。Arch Linux と Omarchy は、同じ検証済み .deb の内容をユーザーディレクトリにインストールします。Debian のパッケージマネージャーは不要です。",
+ "item1": "Ubuntu:sudo apt install ./cindy-<version>-<arch>.deb を実行します。Arch/Omarchy:docs/linux.md のユーザーインストール手順に従ってください。",
+ "item2": "更新時、システムの .deb インストールは認証を要求します。ユーザーインストールはシステムパスワードなしでバージョンを切り替えます。それ以外は対応するパッケージマネージャーで更新してください。",
+ "item3": "Linux x64 は Beta チャネルに対応し、arm64 は未対応です。更新は再起動を選択したときのみ適用され、アイドル時には自動適用されません。"
},
"qnaTitle": "そのまま質問する",
"qnaDescription": "overview に載っていない内容でも、やりたいことを聞けば次に開く場所や進め方を案内します。",
@@ -945,7 +945,7 @@
"openLogsDirError": "ログディレクトリを開けませんでした",
"autoUpdateLabel": "アイドル時に更新をインストール",
"autoUpdateDescription": "更新のダウンロード完了後、このコンピューターが 10 分間操作されず、実行中のタスクがない場合に、アプリを自動的に再起動してインストールします。",
- "linuxUpdateDescription": "新しいビルドがある場合、アプリ内で .deb をダウンロードします。インストールにはシステムパスワードが必要なため、アイドル時の自動インストールは行いません。",
+ "linuxUpdateDescription": "更新は再起動を選択したときに適用されます。システムの .deb インストールにはシステムパスワードが必要ですが、ユーザーインストールには不要です。それ以外はパッケージマネージャーで更新してください。",
"autoUpdateEnabledToast": "アイドル時の更新インストールを有効にしました",
"autoUpdateDisabledToast": "アイドル時の更新インストールを無効にしました",
"autoUpdateSaveFailed": "自動更新設定を保存できませんでした",
@@ -6320,7 +6320,7 @@
"ready": "新バージョン準備完了 — サイドバーをクリックして更新を完了",
"manifestFailed": "更新確認に失敗しました。ネットワークを確認してください",
"downloadFailed": "新バージョンのダウンロードに失敗しました。後でもう一度お試しください",
- "manualDownload": "アプリ内で更新をダウンロードしてください。インストールにはシステムパスワードが必要です。"
+ "manualDownload": "アプリ内でダウンロード後、再起動するタイミングを選んでください。システムの .deb インストールのみパスワードが必要です。"
},
"closeConfirm": {
"title": "終了しますか?",
@@ -7217,6 +7217,13 @@
"move": "今すぐ移動(推奨)",
"download": "手動でダウンロード"
},
+ "linuxInstallation": {
+ "title": "このインストールは自動更新できません",
+ "description": "パッケージマネージャーを使うか、Linux ユーザーインストールガイドを確認してください。管理対象のインストールでは、必要なツールや書き込み権限の復元が必要な場合があります。Cindy とダウンロード済みの更新は保持されています。",
+ "guide": "Linux ガイドを開く",
+ "retry": "再確認",
+ "later": "後で"
+ },
"windowsRuntimeMissing": {
"title": "Microsoft Visual C++ ランタイムが必要です",
"description": "この PC にはアップデーターに必要な Microsoft Visual C++ ランタイムがありません。ダウンロード済みの更新は保持されます。Microsoft 公式の x64 ランタイムをインストールしてから、もう一度確認してください。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 650c86656b..2b348c9b0b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -881,10 +881,10 @@
},
"linuxUpdates": {
"title": "Linux 설치와 업데이트",
- "description": "Linux는 현재 Ubuntu 22.04 / 24.04용 .deb로 제공됩니다. 새 빌드가 있으면 앱이 다운로드하고, 설치할 때 시스템 비밀번호를 묻습니다.",
- "item1": "처음 설치할 때는 sudo apt install ./cindy-<버전>-<아키텍처>.deb 를 사용하세요(x64는 amd64, arm64는 arm64).",
- "item2": "앱 안 업데이트는 .deb를 다운로드합니다. 업데이트를 선택하면 시스템 권한 확인 후 덮어써 설치합니다.",
- "item3": "Linux x64에서는 Beta 채널을 사용할 수 있지만 arm64는 아직 지원하지 않습니다. 설치에는 시스템 권한 승인이 필요하므로 두 아키텍처 모두 유휴 상태 자동 설치를 지원하지 않습니다."
+ "description": "Ubuntu는 시스템 .deb 패키지를 사용합니다. Arch Linux와 Omarchy는 같은 검증된 .deb 콘텐츠를 관리되는 사용자 디렉터리에 설치합니다. Debian 패키지 관리자는 필요하지 않습니다.",
+ "item1": "Ubuntu: sudo apt install ./cindy-<version>-<arch>.deb를 실행하세요. Arch/Omarchy: docs/linux.md의 사용자 설치 안내를 따르세요.",
+ "item2": "업데이트 시 시스템 .deb 설치는 인증을 요청하고, 사용자 설치는 시스템 비밀번호 없이 버전을 전환합니다. 다른 패키지 관리자로 설치한 경우 해당 관리자로 업데이트하세요.",
+ "item3": "Linux x64는 Beta 채널을 지원하며 arm64는 아직 지원하지 않습니다. Linux 업데이트는 재시작을 선택할 때만 적용되며 유휴 상태에서 자동으로 설치되지 않습니다."
},
"qnaTitle": "바로 질문하기",
"qnaDescription": "overview 에 없는 내용이라도 하고 싶은 일을 물어보면 다음에 열어야 할 곳이나 진행 방법을 안내합니다.",
@@ -945,7 +945,7 @@
"openLogsDirError": "로그 디렉터리를 열지 못했습니다",
"autoUpdateLabel": "유휴 상태일 때 업데이트 설치",
"autoUpdateDescription": "업데이트 다운로드가 완료된 뒤, 이 컴퓨터가 10분 동안 조작되지 않았고 실행 중인 작업이 없으면 앱을 자동으로 다시 시작해 설치합니다.",
- "linuxUpdateDescription": "새 빌드가 있으면 앱에서 .deb를 다운로드합니다. 설치할 때 시스템 비밀번호가 필요하므로 유휴 상태에서는 자동 설치하지 않습니다.",
+ "linuxUpdateDescription": "재시작을 선택하면 업데이트가 적용됩니다. 시스템 .deb 설치에는 시스템 비밀번호가 필요하지만 사용자 설치에는 필요하지 않습니다. 다른 설치 방식은 패키지 관리자를 사용하세요.",
"autoUpdateEnabledToast": "유휴 상태 자동 업데이트 설치가 켜졌습니다",
"autoUpdateDisabledToast": "유휴 상태 자동 업데이트 설치가 꺼졌습니다",
"autoUpdateSaveFailed": "자동 업데이트 설정을 저장하지 못했습니다",
@@ -6320,7 +6320,7 @@
"ready": "새 버전 준비 완료 — 사이드바를 클릭해 업데이트 완료",
"manifestFailed": "업데이트 확인 실패, 네트워크를 확인하세요",
"downloadFailed": "새 버전 다운로드 실패, 나중에 다시 시도하세요",
- "manualDownload": "앱에서 업데이트를 다운로드하세요. 설치하려면 시스템 비밀번호가 필요합니다."
+ "manualDownload": "앱에서 다운로드한 뒤 재시작할 때를 선택하세요. 시스템 .deb 설치에만 시스템 비밀번호가 필요합니다."
},
"closeConfirm": {
"title": "정말 나가시겠습니까?",
@@ -7217,6 +7217,13 @@
"move": "지금 이동 (권장)",
"download": "수동으로 다운로드"
},
+ "linuxInstallation": {
+ "title": "이 설치는 자체 업데이트할 수 없습니다",
+ "description": "패키지 관리자를 사용하거나 Linux 사용자 설치 안내를 확인하세요. 관리되는 설치에는 누락된 도구를 설치하거나 쓰기 권한을 복원해야 할 수 있습니다. Cindy와 다운로드한 업데이트는 유지됩니다.",
+ "guide": "Linux 안내 열기",
+ "retry": "다시 확인",
+ "later": "나중에"
+ },
"windowsRuntimeMissing": {
"title": "Microsoft Visual C++ 런타임 필요",
"description": "이 PC에는 업데이터에 필요한 Microsoft Visual C++ 런타임이 없습니다. 다운로드한 업데이트는 유지됩니다. Microsoft 공식 x64 런타임을 설치한 후 다시 확인해 주세요.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index e88d6a746e..acb9ca7cd5 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -881,10 +881,10 @@
},
"linuxUpdates": {
"title": "Linux 安装与更新",
- "description": "Linux 目前提供 Ubuntu 22.04 / 24.04 的 .deb 包。有新版本时,应用会下载安装包,安装时需要系统密码。",
- "item1": "首次安装用 sudo apt install ./cindy-<版本>-<架构>.deb(x64 为 amd64,arm64 为 arm64)。",
- "item2": "应用内更新会下载 .deb,点更新后通过系统权限提示覆盖安装。",
- "item3": "Linux x64 支持 Beta 渠道,arm64 暂不支持。两种架构都不支持空闲时自动安装,因为安装需要系统授权。"
+ "description": "Ubuntu 使用系统 .deb 安装包。Arch Linux 和 Omarchy 使用受管理的用户目录安装器,复用同一份经过校验的 .deb 内容,无需 Debian 包管理器。",
+ "item1": "Ubuntu:使用 sudo apt install ./cindy-<version>-<arch>.deb。Arch/Omarchy:请按 docs/linux.md 中的用户目录安装指南操作。",
+ "item2": "点击更新后,系统 .deb 安装需要授权;用户目录安装无需系统密码即可切换版本。其他包管理器安装的版本请通过对应包管理器更新。",
+ "item3": "Linux x64 支持 Beta 渠道,arm64 暂不支持。Linux 仅在你选择重启时应用更新,不会在空闲时自动安装。"
},
"qnaTitle": "直接提问",
"qnaDescription": "如果 overview 里没有覆盖到你的问题,可以直接问我该怎么做。",
@@ -945,7 +945,7 @@
"openLogsDirError": "打开日志目录失败",
"autoUpdateLabel": "空闲时自动安装更新",
"autoUpdateDescription": "更新下载完成后,当这台电脑 10 分钟无操作且没有任务运行时,自动重启应用完成安装。",
- "linuxUpdateDescription": "有新版本时会在应用内下载 .deb。点更新后需要输入系统密码完成安装,因此不会在空闲时自动安装。",
+ "linuxUpdateDescription": "更新在你选择重启时生效。系统 .deb 安装需要系统密码,用户目录安装不需要。其他安装方式请通过对应包管理器更新。",
"autoUpdateEnabledToast": "已开启空闲时自动安装更新",
"autoUpdateDisabledToast": "已关闭空闲时自动安装更新",
"autoUpdateSaveFailed": "保存自动更新设置失败",
@@ -6320,7 +6320,7 @@
"ready": "新版本已就绪,点击侧边栏完成更新",
"manifestFailed": "检查更新失败,请检查网络",
"downloadFailed": "新版本下载失败,稍后再试",
- "manualDownload": "请在应用内下载更新,安装时需要系统密码。"
+ "manualDownload": "在应用内下载,再选择重启时间。只有系统 .deb 安装需要系统密码。"
},
"closeConfirm": {
"title": "确认要离开吗?",
@@ -7217,6 +7217,13 @@
"move": "立即移动(推荐)",
"download": "手动下载新版本"
},
+ "linuxInstallation": {
+ "title": "当前安装无法自行更新",
+ "description": "请使用对应的包管理器,或参考 Linux 用户目录安装指南。受管理的安装可能需要补齐工具或恢复写入权限。Cindy 和已下载的更新均已保留。",
+ "guide": "打开 Linux 指南",
+ "retry": "重新检查",
+ "later": "稍后"
+ },
"windowsRuntimeMissing": {
"title": "需要安装 Microsoft Visual C++ 运行库",
"description": "这台电脑缺少更新程序所需的 Microsoft Visual C++ 运行库。已下载的更新包会保留;请安装微软官方 x64 运行库后重新检查。",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index d05815b390..7c543ecfe1 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -881,10 +881,10 @@
},
"linuxUpdates": {
"title": "Linux 安裝與更新",
- "description": "Linux 目前提供 Ubuntu 22.04 / 24.04 的 .deb 套件。有新版本時,應用程式會下載安裝包,安裝時需要系統密碼。",
- "item1": "首次安裝用 sudo apt install ./cindy-<版本>-<架構>.deb(x64 為 amd64,arm64 為 arm64)。",
- "item2": "應用程式內更新會下載 .deb,點更新後透過系統權限提示覆蓋安裝。",
- "item3": "Linux x64 支援 Beta 渠道,arm64 暫不支援。兩種架構都不支援閒置時自動安裝,因為安裝需要系統授權。"
+ "description": "Ubuntu 使用系統 .deb 安裝套件。Arch Linux 和 Omarchy 使用受管理的使用者目錄安裝程式,採用同一份經過驗證的 .deb 內容,無需 Debian 套件管理器。",
+ "item1": "Ubuntu:使用 sudo apt install ./cindy-<version>-<arch>.deb。Arch/Omarchy:請依照 docs/linux.md 中的使用者目錄安裝指南操作。",
+ "item2": "點擊更新後,系統 .deb 安裝需要授權;使用者目錄安裝無需系統密碼即可切換版本。其他套件管理器安裝的版本請透過對應套件管理器更新。",
+ "item3": "Linux x64 支援 Beta 渠道,arm64 暫不支援。Linux 僅在你選擇重新啟動時套用更新,不會在閒置時自動安裝。"
},
"qnaTitle": "直接提問",
"qnaDescription": "如果 overview 裡沒有覆蓋到你的問題,可以直接問我該怎麼做。",
@@ -945,7 +945,7 @@
"openLogsDirError": "開啟日誌目錄失敗",
"autoUpdateLabel": "空閒時自動安裝更新",
"autoUpdateDescription": "更新下載完成後,當這臺電腦 10 分鐘無操作且沒有任務執行時,自動重啟應用完成安裝。",
- "linuxUpdateDescription": "有新版本時會在應用程式內下載 .deb。點更新後需要輸入系統密碼完成安裝,因此不會在空閒時自動安裝。",
+ "linuxUpdateDescription": "更新在你選擇重新啟動時生效。系統 .deb 安裝需要系統密碼,使用者目錄安裝不需要。其他安裝方式請透過對應套件管理器更新。",
"autoUpdateEnabledToast": "已開啟空閒時自動安裝更新",
"autoUpdateDisabledToast": "已關閉空閒時自動安裝更新",
"autoUpdateSaveFailed": "儲存自動更新設定失敗",
@@ -6320,7 +6320,7 @@
"ready": "新版本已就緒,點選側邊欄完成更新",
"manifestFailed": "檢查更新失敗,請檢查網路",
"downloadFailed": "新版本下載失敗,稍後再試",
- "manualDownload": "請在應用程式內下載更新,安裝時需要系統密碼。"
+ "manualDownload": "在應用程式內下載,再選擇重新啟動時間。只有系統 .deb 安裝需要系統密碼。"
},
"closeConfirm": {
"title": "確認要離開嗎?",
@@ -7217,6 +7217,13 @@
"move": "立即移動(推薦)",
"download": "手動下載新版本"
},
+ "linuxInstallation": {
+ "title": "目前的安裝無法自行更新",
+ "description": "請使用對應的套件管理器,或參考 Linux 使用者目錄安裝指南。受管理的安裝可能需要補齊工具或恢復寫入權限。Cindy 和已下載的更新均已保留。",
+ "guide": "開啟 Linux 指南",
+ "retry": "重新檢查",
+ "later": "稍後"
+ },
"windowsRuntimeMissing": {
"title": "需要安裝 Microsoft Visual C++ 執行階段",
"description": "這台電腦缺少更新程式所需的 Microsoft Visual C++ 執行階段。已下載的更新套件會保留;請安裝 Microsoft 官方 x64 執行階段後重新檢查。",
diff --git a/docs/linux.md b/docs/linux.md
new file mode 100644
index 0000000000..401f0a7722
--- /dev/null
+++ b/docs/linux.md
@@ -0,0 +1,164 @@
+# Linux installation and updates
+
+## Supported installation routes
+
+| Environment | Installation | How updates are applied |
+| --- | --- | --- |
+| Ubuntu 22.04 / 24.04 | Official system `.deb` via apt | In-app download, explicit restart, polkit authorization |
+| Arch Linux / Omarchy (Hyprland), x86_64 | Managed user installation below | In-app download, explicit restart, atomic user-owned version switch |
+| Other glibc Linux desktops | Same user installer, with compatible runtime dependencies | Same transaction; not a claim that every distribution is tested |
+| pacman/AUR or another third-party package | That package manager | Use that package manager, not the in-app installer |
+
+The user installer supports x64 and arm64 payload identities, but requires a
+matching published artifact. Arm64 does not currently support the Beta channel;
+this change's host checks use x64 Omarchy; release acceptance is listed below.
+Alpine/musl, root desktop sessions,
+and unpacking old releases by hand are not supported user-install routes.
+This does not add Linux equivalents of features that require macOS or Windows.
+
+The downloaded artifact remains the official `.deb`. On Arch it is a verified
+container for the application, **not a Debian package installed into the
+system**. No apt/dpkg, maintainer scripts, root privileges, ASAR patches, or
+system Electron are used. Old releases without `resources/linux-build-info`
+cannot bootstrap this layout: start with a release containing this support.
+
+## Arch / Omarchy prerequisites
+
+Keep the distribution fully updated (Arch does not support partial upgrades).
+Install the runtime libraries and integration tools if absent:
+
+```sh
+sudo pacman -Syu --needed libarchive coreutils util-linux findutils procps-ng \
+ gtk3 nss alsa-lib libxss libxtst libnotify libdrm mesa \
+ gnome-keyring libsecret desktop-file-utils xdg-utils
+```
+
+Cindy bundles its own Electron; installing Arch's `electron` package is not
+required. Run from a normal logged-in desktop session with a working session
+D-Bus and an unlocked Secret Service keyring. Installing `gnome-keyring` does
+not itself unlock it: use your desktop's supported login/PAM integration.
+Do not start a second keyring daemon or replace its existing keys.
+The distribution must allow Electron's user-namespace sandbox; the installer
+does not create a root-owned setuid helper or disable sandboxing.
+
+For Wayland screen sharing and file dialogs, keep your compositor's portal
+backend and PipeWire installed and working. Omarchy normally configures these;
+this installer deliberately does not rewrite Hyprland, PAM or portal settings.
+See the [Electron safeStorage documentation](https://www.electronjs.org/docs/latest/api/safe-storage)
+for the backend model. KDE and GNOME retain Electron's existing selection;
+Hyprland selects `gnome-libsecret` before app readiness; other desktops retain
+Electron's selection. Desktop identity uses the first non-empty value from
+`XDG_CURRENT_DESKTOP`, `XDG_SESSION_DESKTOP`, and `DESKTOP_SESSION`.
+An explicit `--password-store` always wins and survives an in-app update restart.
+
+## Install
+
+1. Download the matching official Linux package from
+ [Cindy downloads](https://cindy.app/download/). Obtain its **trusted SHA-256**
+ from the release's metadata/update manifest; computing a new digest from an
+ untrusted download is not verification.
+2. Get [install-user.sh](../apps/desktop/resources/linux/install-user.sh) from the
+ source revision associated with that release. Review it, then run it as your
+ desktop user, **not with sudo**:
+
+```sh
+bash ./install-user.sh --install ./cindy-VERSION-amd64.deb TRUSTED_SHA256
+bash "$HOME/.local/opt/cindy/current/resources/linux/register-desktop.sh" "$HOME/.local/opt/cindy"
+"$HOME/.local/opt/cindy/launch"
+```
+
+Replace the package name and digest. An optional fourth argument to
+`--install` chooses another absolute prefix inside your home. The installer
+refuses to overwrite an unmarked existing directory. Desktop integration needs
+a prefix without control characters, `=` or `%` (Desktop Entry restrictions).
+It creates a prefix-specific menu entry and **explicitly makes this installation
+the handler for Cindy login/share links**; other application files are untouched.
+Both release regions share these schemes, so the last registered handler wins.
+Concurrent use of two release regions is not supported.
+The packaged app sets the same stable reverse-DNS desktop identity before
+startup, including when reopened by the updater. Portal permissions may need
+to be granted again when migrating from an older manual desktop entry.
+
+The command-line entry is `PREFIX/launch`. If desired, create a `cindy` symlink
+to that entry in a directory already on PATH, but do not replace an existing
+command belonging to a different installation.
+
+## Updates, existing installations, and recovery
+
+Choose Update in Cindy, then restart when convenient. Linux never installs
+while idle. Managed user installs need no system password. System `.deb`
+installs still request authorization. Unknown/package-manager-owned layouts
+are rejected **before Cindy quits or stops active work** with a guide prompt.
+The downloaded package remains available.
+
+Each update verifies the manifest size and SHA-256 again using a private
+snapshot, checks the package's version/architecture/region, then prepares a new
+release directory. A single rename switches `current`; `previous` and all old
+release directories are retained. A handled failure before activation leaves
+the current executable intact and removes that transaction's new directory.
+SIGKILL or power loss can leave an unactivated release behind; retry verifies
+the package again and installs into a fresh directory without overwriting or
+deleting the retained release. Repeating an already active package repairs the
+stable launcher without switching releases. The two pointer renames are not a
+power-loss-atomic pair: interruption after switching `current` can leave
+`previous` pointing to an older retained release rather than its immediate predecessor.
+Application data, credentials, plugins and keyring entries are never copied,
+cleared, re-encrypted or moved by the installer.
+
+For a previously hand-extracted or locally patched installation:
+
+1. Quit Cindy fully and back up its existing data using your normal backup
+ procedure. Do not delete the old installation, profile, keyring or launchers.
+2. Install a compatible official release into a **new** prefix, for example
+ `$HOME/.local/opt/cindy-managed`.
+3. Explicitly register the new desktop entry before signing in, so the browser
+ callback returns to the new installation instead of starting the old one.
+ Run the new stable launcher with the same existing password-store selector
+ if you previously specified one. The application's existing region-specific
+ userData mapping is unchanged (`CindyGlobal` / `Cindy`).
+4. Verify login and reopening. Only after verification remove obsolete
+ launchers/manual patches yourself.
+ Do not run both versions against the same profile simultaneously.
+
+This cannot recover already revoked tokens or decrypt a profile with a missing
+keyring. If an old install used a different backend (including `basic`), do not
+delete its keys: restoring that backend or signing in once may be necessary.
+There is no automatic insecure/plaintext fallback. A locked keyring must be
+unlocked, not bypassed with sandbox-disabling flags or permissive chmod.
+
+For failures, inspect the application's `logs/cindy-update.log`, the current
+release's `resources/linux-build-info`, and `readlink PREFIX/current`.
+`ldd PREFIX/current/Cindy` can identify missing runtime libraries in a trusted
+official package. Do not post tokens or complete private profiles in issues.
+
+Binary rollback is not a database rollback: old releases are retained for
+recovery, but running an older app after migrations may be unsafe. Prefer a
+fixed forward release, or restore a matching data backup with maintainer help.
+Do not automatically launch `previous` after a successfully activated app has
+already opened its database.
+
+To uninstall, quit Cindy and remove only the chosen managed prefix and its
+prefix-specific `com.xd.cindy.user.h*.desktop` entry (the registration command prints
+the exact filename). Remove any CLI symlink you added and re-register another
+installation if required. User data and the keyring live outside the prefix
+and are retained. Old release directories are not automatically pruned; review
+their disk usage and retain a suitable backup before cleaning them.
+
+## Maintenance and validation
+
+- Forge writes build identity outside ASAR and bundles both Linux scripts.
+ The in-app update helper embeds the same installer source at build time;
+ it does not execute a mutable script from the installation directory.
+- Keep `install-user.sh`, the marker schema, `linuxInstallation.ts`, and
+ `forge-linux.ts` compatible across releases. Do not change server manifest
+ fields or the existing system-package route to add a distribution.
+- Native smoke tests create small synthetic DEBs in a temporary HOME. They
+ cover two updates, bad digest/version/region, escaping symlinks, failure at
+ activation, retry, stable desktop registration, and exact package ownership.
+ They run on Linux with libarchive/binutils/desktop-file-utils/xdg-utils; all
+ other platform-selection and UI tests also run on Windows.
+- Before broad rollout, test two **real release** upgrades on both a fresh and
+ migrated Omarchy profile, cold-start login retention, locked-keyring recovery,
+ deep links, notifications, file dialogs and Wayland screen sharing. Repeat
+ Debian system updates and native GNOME/KDE login checks. Synthetic packages
+ are not a substitute for these release acceptance checks.
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
index aae0277139..b967fbbe2b 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
@@ -2711,7 +2711,10 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
scriptedResponses.length = 0;
scriptedResponses.push(
- anthropicToolUseBody('bash', { command: 'cat <*' }),
+ // Bash 4+ inherits dotglob, so <* matches both fixture files and is
+ // an ambiguous redirect. Keep that operation, then read a uniquely
+ // matched ordinary file to prove Full Access reached the shell.
+ anthropicToolUseBody('bash', { command: 'cat <*; cat <ordinary.*' }),
anthropicStreamBody('bash Full Access dotglob turn finished'),
);
const fullAccessReqBefore = seenRequests.length;
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts
index 696db9c34b..ad395c949d 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-rpc-resource-discovery.integration.test.ts
@@ -105,11 +105,11 @@ function canonicalPath(value: string): string {
function expectedExplicitProjectSkillScope(fixture: Fixture): 'project' | 'temporary' {
if (process.platform === 'win32') return 'project';
- // Pi v0.83.0 reports `project` on macOS when the lexical git root is already
- // canonical. The default /var -> /private/var temp-dir alias instead yields
- // `temporary`, so keep the fixture deterministic under either TMPDIR form.
+ // The pinned Pi reports `project` on Linux and macOS when the lexical git
+ // root is canonical. macOS's /var -> /private/var temp-dir alias instead
+ // yields `temporary`; do not assume that alias also exists on Linux.
if (
- process.platform === 'darwin'
+ (process.platform === 'darwin' || process.platform === 'linux')
&& path.resolve(fixture.repoRoot) === canonicalPath(fixture.repoRoot)
) {
return 'project';
@@ -181,7 +181,7 @@ function normalizeSkills(commands: PiCommand[], fixture: Fixture): NormalizedSki
.sort((a, b) => a.name.localeCompare(b.name));
}
-describe.skipIf(!existsSync(PI_BINARY))('Pi v0.83.0 RPC resource discovery facts', () => {
+describe.skipIf(!existsSync(PI_BINARY))('Pinned Pi RPC resource discovery facts', () => {
it('applies session-local Skill exclusions without removing native package resources', async () => {
const fixture = await createFixture('pi-rpc-skill-exclusions-');
const hiddenGlobal = path.join(fixture.configHome, 'skills', 'global-skill', 'SKILL.md');