Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(desktop): Linux 应用内下载 .deb 并用 pkexec 安装 (#3191)

guyong-zapoc3dde8cc82b6
diff --git a/apps/desktop/scripts/ci/lib.mjs b/apps/desktop/scripts/ci/lib.mjs
index 2c64f95de0..766487ad61 100644
--- a/apps/desktop/scripts/ci/lib.mjs
+++ b/apps/desktop/scripts/ci/lib.mjs
@@ -261,11 +261,13 @@ export function createInitialManifest(version, options = {}) {
}
/**
- * Linux first release is installer/manual-download only.
- * Reuse this helper anywhere we mint a Linux manifest so `app.hotfix` and
- * `app.requireRelogin` can never leak back in through copy/paste drift.
+ * Linux in-app update downloads `app.installer` (.deb) and applies it with
+ * pkexec. Reuse this helper anywhere we mint a Linux manifest so `app.hotfix`
+ * and `app.requireRelogin` can never leak back in through copy/paste drift.
+ * Callers that have a real .deb must pass `installer`; omitting it keeps the
+ * installer-only shape without inventing a fake asset.
*/
-export function createLinuxFirstReleaseManifest(version, baseManifest) {
+export function createLinuxFirstReleaseManifest(version, baseManifest, installer) {
const releaseNotes = baseManifest?.app?.releaseNotes;
const manifest = baseManifest
? JSON.parse(JSON.stringify(baseManifest))
@@ -276,8 +278,16 @@ export function createLinuxFirstReleaseManifest(version, baseManifest) {
};
delete manifest.app.hotfix;
delete manifest.app.requireRelogin;
- delete manifest.app.installer;
delete manifest.installer;
+ if (installer?.file && installer.sha256) {
+ manifest.app.installer = {
+ file: installer.file,
+ sha256: installer.sha256,
+ size: typeof installer.size === 'number' ? installer.size : 0,
+ };
+ } else {
+ delete manifest.app.installer;
+ }
// Packaged Linux resolves Claude/Codex from a compatible system install,
// migrates the legacy local cache, or downloads the pinned official asset.
// Ripgrep remains bundled in the .deb by forge and needs no manifest entry.
diff --git a/apps/desktop/scripts/package-desktop.mjs b/apps/desktop/scripts/package-desktop.mjs
index 642577ed00..c71d111408 100644
--- a/apps/desktop/scripts/package-desktop.mjs
+++ b/apps/desktop/scripts/package-desktop.mjs
@@ -504,7 +504,7 @@ async function finishLinux({ artifactDir, baseName, arch }) {
// 包一致:归集时写死 amd64 会让 arm64 产物顶着 amd64 的名字发出去。
const installerPath = path.join(artifactDir, `${baseName}-${debianArch(arch)}.deb`);
fs.copyFileSync(debPath, installerPath);
- // Linux 首发无热更链路(见 ci/lib.mjs createLinuxFirstReleaseManifest),只出安装包。
+ // Linux 没有 hotfix zip;应用内更新下载这份 installer .deb,再用 pkexec 覆盖安装。
return { files: [fileEntry('installer', installerPath)], signing: { mode: 'none' } };
}
diff --git a/apps/desktop/src/main/__tests__/linuxManifestHelper.test.ts b/apps/desktop/src/main/__tests__/linuxManifestHelper.test.ts
new file mode 100644
index 0000000000..0467bbbd6e
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/linuxManifestHelper.test.ts
@@ -0,0 +1,69 @@
+import { createRequire } from 'node:module';
+import path from 'node:path';
+import { describe, expect, it } from 'vitest';
+
+interface LinuxManifest {
+ app: {
+ version: string;
+ installer?: { file: string; sha256: string; size: number };
+ hotfix?: unknown;
+ requireRelogin?: unknown;
+ };
+ installer?: unknown;
+ claudeCode?: unknown;
+}
+
+function loadHelper() {
+ const require = createRequire(import.meta.url);
+ const helperPath = path.resolve(__dirname, '../../../scripts/ci/lib.mjs');
+ const mod = require(helperPath) as {
+ createLinuxFirstReleaseManifest: (
+ version: string,
+ baseManifest?: unknown,
+ installer?: { file: string; sha256: string; size: number },
+ ) => LinuxManifest;
+ };
+ return mod.createLinuxFirstReleaseManifest;
+}
+
+describe('createLinuxFirstReleaseManifest', () => {
+ it('writes app.installer and never reintroduces hotfix or requireRelogin', () => {
+ const createLinuxFirstReleaseManifest = loadHelper();
+ const manifest = createLinuxFirstReleaseManifest(
+ '0.0.2',
+ {
+ app: {
+ version: '0.0.1',
+ hotfix: { file: 'hotfix/linux-x64/old.zip', sha256: 'aa', size: 1 },
+ requireRelogin: true,
+ installer: { file: 'stale.deb', sha256: 'bb', size: 2 },
+ },
+ installer: { file: 'legacy.deb', sha256: 'cc', size: 3 },
+ claudeCode: { version: '1.0.0', file: 'claude.gz', sha256: 'dd', size: 4 },
+ },
+ {
+ file: 'app/linux-x64/cindy-0.0.2-amd64.deb',
+ sha256: 'a'.repeat(64),
+ size: 166_000_000,
+ },
+ );
+
+ expect(manifest.app.version).toBe('0.0.2');
+ expect(manifest.app.installer).toEqual({
+ file: 'app/linux-x64/cindy-0.0.2-amd64.deb',
+ sha256: 'a'.repeat(64),
+ size: 166_000_000,
+ });
+ expect(manifest.app.hotfix).toBeUndefined();
+ expect(manifest.app.requireRelogin).toBeUndefined();
+ expect(manifest.installer).toBeUndefined();
+ expect(manifest.claudeCode).toBeUndefined();
+ });
+
+ it('omits installer when metadata is missing instead of inventing an asset', () => {
+ const createLinuxFirstReleaseManifest = loadHelper();
+ const manifest = createLinuxFirstReleaseManifest('0.0.2');
+ expect(manifest.app.version).toBe('0.0.2');
+ expect(manifest.app.installer).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/updateAutoRelaunchPolicy.test.ts b/apps/desktop/src/main/__tests__/updateAutoRelaunchPolicy.test.ts
index c52b2d4cc9..40d2f3db60 100644
--- a/apps/desktop/src/main/__tests__/updateAutoRelaunchPolicy.test.ts
+++ b/apps/desktop/src/main/__tests__/updateAutoRelaunchPolicy.test.ts
@@ -62,4 +62,8 @@ describe('update auto relaunch policy', () => {
it('blocks for a short cooldown after resume or unlock', () => {
expect(check({ lastResumeAtMs: BASE.nowMs - 1_000 })).toBe('recent-resume');
});
+
+ it('blocks unattended relaunch when apply needs interactive auth', () => {
+ expect(check({ requiresInteractiveAuth: true })).toBe('interactive-auth');
+ });
});
diff --git a/apps/desktop/src/main/__tests__/updateChannelStore.test.ts b/apps/desktop/src/main/__tests__/updateChannelStore.test.ts
index d55ab37187..20e5e4447c 100644
--- a/apps/desktop/src/main/__tests__/updateChannelStore.test.ts
+++ b/apps/desktop/src/main/__tests__/updateChannelStore.test.ts
@@ -94,3 +94,20 @@ describe('tryEnableUncustomizedBetaAtomic', () => {
});
});
});
+
+describe('Linux beta channel gate', () => {
+ const originalPlatform = process.platform;
+
+ afterEach(() => {
+ Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });
+ });
+
+ it('keeps Linux on the release channel even when disk says beta is on', async () => {
+ Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
+ const store = await loadStore();
+ await store.writeEnableBeta(true);
+
+ expect(store.readUpdateChannelSettings().enableBeta).toBe(true);
+ expect(store.isBetaChannelEnabled()).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/updateScriptLinux.test.ts b/apps/desktop/src/main/__tests__/updateScriptLinux.test.ts
new file mode 100644
index 0000000000..67cb54ab81
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/updateScriptLinux.test.ts
@@ -0,0 +1,191 @@
+import { describe, expect, it } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import {
+ buildLinuxUpdateScript,
+ shellSingleQuote,
+ DEFAULT_LINUX_UPDATE_SCRIPT_TIMINGS,
+ type LinuxUpdateScriptParams,
+} from '../updateScriptLinux';
+
+const STAGED_SHA = 'a'.repeat(64);
+
+const STAGED_SIZE = 166_000_000;
+
+function makeParams(overrides: Partial<LinuxUpdateScriptParams> = {}): LinuxUpdateScriptParams {
+ return {
+ pid: 12345,
+ debPath: '/tmp/cindy-0.0.2-amd64.deb',
+ sha256: STAGED_SHA,
+ sizeBytes: STAGED_SIZE,
+ exePath: '/usr/lib/cindy/Cindy',
+ lockFilePath: '/tmp/cindy-update.lock',
+ logPath: '/tmp/cindy-update.log',
+ ...overrides,
+ };
+}
+
+describe('shellSingleQuote', () => {
+ it('wraps paths in single quotes and escapes embedded quotes', () => {
+ expect(shellSingleQuote(`/tmp/cindy's.deb`)).toBe(`'/tmp/cindy'\\''s.deb'`);
+ expect(shellSingleQuote('/usr/lib/cindy/Cindy')).toBe(`'/usr/lib/cindy/Cindy'`);
+ });
+});
+
+describe('buildLinuxUpdateScript structure', () => {
+ const script = buildLinuxUpdateScript(makeParams());
+
+ it('installs the staged .deb through one pkexec bash shell', () => {
+ expect(script).toContain('PKEXEC=/usr/bin/pkexec');
+ expect(script).toContain('ELEVATED=\'set -eu');
+ expect(script).toContain('"$PKEXEC" /bin/bash -c "$ELEVATED"');
+ expect(script).toContain('apt-get install --yes --allow-downgrades');
+ expect(script).toContain('dpkg --install');
+ expect(script).toContain(`'/tmp/cindy-0.0.2-amd64.deb'`);
+ });
+
+ it('passes the manifest sha256 and deb path as argv to the elevated shell', () => {
+ expect(script).toContain(
+ `"$PKEXEC" /bin/bash -c "$ELEVATED" bash '${STAGED_SHA}' '/tmp/cindy-0.0.2-amd64.deb'`,
+ );
+ });
+
+ it('never hands the user-replaceable log path to the elevated root shell', () => {
+ // 只取 ELEVATED 提权段本体(到结束引号为止),外层用户 shell 的重定向不在此列。
+ const elevated = script.slice(script.indexOf('ELEVATED='), script.indexOf("fi'", script.indexOf('ELEVATED=')) + 3);
+ expect(elevated).not.toContain('cindy-update.log');
+ // 日志重定向由外层用户 shell 完成,提权进程只写 stdout/stderr。
+ expect(script).toContain(
+ `"$PKEXEC" /bin/bash -c "$ELEVATED" bash '${STAGED_SHA}' '/tmp/cindy-0.0.2-amd64.deb' ${STAGED_SIZE} >> '/tmp/cindy-update.log' 2>&1`,
+ );
+ });
+
+ it('copies the .deb to a root-owned 0700 temp dir and hashes before installing', () => {
+ const elevated = script.slice(script.indexOf('ELEVATED='), script.indexOf('"$PKEXEC" /bin/bash'));
+ const copyIdx = elevated.indexOf('dd if="$2" of="$TMP/update.deb"');
+ const hashIdx = elevated.indexOf('if [ "$ACTUAL" != "$1" ]');
+ const aptIdx = elevated.indexOf('apt-get install');
+ expect(copyIdx).toBeGreaterThan(-1);
+ expect(hashIdx).toBeGreaterThan(copyIdx);
+ expect(aptIdx).toBeGreaterThan(hashIdx);
+ expect(elevated).toContain('TMP=$(mktemp -d "${TMPDIR:-/tmp}/cindy-deb.XXXXXX")');
+ expect(elevated).toContain('chmod 700 "$TMP"');
+ });
+
+ it('opens the staged source atomically with nofollow and a size-bounded copy', () => {
+ const elevated = script.slice(script.indexOf('ELEVATED='), script.indexOf('"$PKEXEC" /bin/bash'));
+ expect(elevated).toContain('if [ -L "$2" ] || [ ! -f "$2" ]; then');
+ // 权威防线:dd 用 O_NOFOLLOW + O_NONBLOCK 原子打开,count 按清单大小封顶。
+ expect(elevated).toContain('dd if="$2" of="$TMP/update.deb" iflag=nofollow,nonblock');
+ expect(elevated).toContain('if [ "$WRITTEN" != "$3" ]; then');
+ expect(script).toContain(
+ `"$PKEXEC" /bin/bash -c "$ELEVATED" bash '${STAGED_SHA}' '/tmp/cindy-0.0.2-amd64.deb' ${STAGED_SIZE} >> '/tmp/cindy-update.log' 2>&1`,
+ );
+ });
+
+ it('does not run dpkg/apt outside the elevated pkexec shell', () => {
+ const outside = script.slice(script.indexOf('ELEVATED='));
+ // 除 ELEVATED 内的安装器,外层脚本里只允许 pkexec /bin/bash 一条特权调用。
+ const pkexecCalls = outside.match(/"\$PKEXEC"/g) ?? [];
+ expect(pkexecCalls).toHaveLength(1);
+ expect(outside).toContain('"$PKEXEC" /bin/bash -c "$ELEVATED"');
+ });
+
+ it('keeps the update lock alive and writes the updater pid into it', () => {
+ const lockIdx = script.indexOf(`echo updating $$ > '/tmp/cindy-update.lock'`);
+ const pkexecIdx = script.indexOf('"$PKEXEC" /bin/bash');
+ expect(lockIdx).toBeGreaterThan(-1);
+ expect(pkexecIdx).toBeGreaterThan(lockIdx);
+ // 锁内容带 $$(updater shell 自己的 PID),bootstrap 据此判定持有者是否存活。
+ const heartbeatLines = script.split('\n').filter((l) => l.includes('echo updating'));
+ expect(heartbeatLines.length).toBeGreaterThanOrEqual(2);
+ expect(script).toContain('LOCK_HEARTBEAT_PID=$!');
+ expect(script).toContain('trap cleanup EXIT');
+ expect(script).toContain("rm -f '/tmp/cindy-update.lock'");
+ // 心跳先看父 bash 存活;父死后按进程组扫描(输出落文件,pgrep 自排除,
+ // 心跳辅助进程不会误计),组里还有活成员(含孤儿 apt/dpkg 后代)就以
+ // $BASHPID 写锁继续持锁。心跳自己也被排除在扫描外,不会让 cleanup
+ // 误判成「还有别人」。
+ expect(script).toContain('if kill -0 "$LOCK_PARENT" 2>/dev/null; then');
+ expect(script).toContain('scan_group_others()');
+ expect(script).toContain('GROUPFILE=');
+ expect(script).toContain('echo updating "$BASHPID" >');
+ expect(script).toContain('[ "$GPID" = "$LOCK_HEARTBEAT_PID" ] && continue');
+ // 组文件用 mktemp 私有临时文件,不用可预测的 <lock>.group 路径;
+ // 枚举失败(mktemp 失败或 pgrep 重定向失败)必须 fail closed 成
+ // OTHERS=1,当作「安装链可能还在」,绝不能清锁让新实例在 apt 还在
+ // 替换文件时启动。
+ expect(script).toContain('GROUPFILE=$(mktemp "');
+ expect(script).toContain('|| { OTHERS=1; return 0; }');
+ expect(script).toContain('if ! pgrep -g "$LOCK_PGID" > "$GROUPFILE" 2>/dev/null; then');
+ expect(script).not.toContain('cindy-update.lock.group');
+ // 拉起走 relaunch_app:先杀心跳清锁,再 setsid 脱离本进程组,
+ // 新 Cindy 不会被误判成安装链,也不会卡在自己的锁上。
+ expect(script).toContain('relaunch_app()');
+ expect(script).toContain('setsid nohup');
+ // 锁和心跳在任何日志 append 之前就位:日志被换成 FIFO 也不影响持锁。
+ const logIdx = script.indexOf("Update script started");
+ expect(lockIdx).toBeGreaterThan(-1);
+ expect(logIdx).toBeGreaterThan(lockIdx);
+ });
+
+ it('rejects a missing or malformed sha256 instead of installing unverified bytes', () => {
+ expect(() => buildLinuxUpdateScript(makeParams({ sha256: 'abc' }))).toThrow(/sha256/);
+ });
+
+ it('escalates SIGKILL at exitKillAfterSeconds and aborts at exitAbortAfterSeconds', () => {
+ const t = DEFAULT_LINUX_UPDATE_SCRIPT_TIMINGS;
+ const killIdx = script.indexOf(`-eq ${t.exitKillAfterSeconds} `);
+ const abortIdx = script.indexOf(`-ge ${t.exitAbortAfterSeconds} `);
+ expect(killIdx).toBeGreaterThan(-1);
+ expect(abortIdx).toBeGreaterThan(killIdx);
+ const abortBlock = script.slice(abortIdx, script.indexOf('done', abortIdx));
+ expect(abortBlock).toContain('exit 1');
+ expect(script.slice(killIdx, abortIdx)).toContain('kill -9 12345');
+ });
+
+ it('relaunches the previous binary if install fails', () => {
+ expect(script).toContain('INSTALL FAILED — relaunching previous binary');
+ expect(script).toContain(`nohup '/usr/lib/cindy/Cindy' >/dev/null 2>&1 &`);
+ });
+
+ it('releases the lock before relaunch and verifies by spawned child pid', () => {
+ // 先放锁再拉起:新进程不会卡在 bootstrap 等自己的锁,2s 启动窗口后
+ // 按启动的子 PID(kill -0)验证,等锁的旧实例不会被误判。
+ const rmIdx = script.indexOf(`rm -f '/tmp/cindy-update.lock'`);
+ const nohupIdx = script.indexOf(`nohup '/usr/lib/cindy/Cindy' >/dev/null 2>&1 &`);
+ expect(rmIdx).toBeGreaterThan(-1);
+ expect(nohupIdx).toBeGreaterThan(rmIdx);
+ expect(script).toContain('LAUNCHED_PID=$!');
+ expect(script).toContain('if kill -0 "$LAUNCHED_PID" 2>/dev/null; then');
+ expect(script).toContain('sleep 2');
+ });
+
+ it('waits for the heartbeat to exit before removing the lock', () => {
+ // kill 只发信号不保证退出,bash 在 sleep 里会推迟 SIGTERM;relaunch_app 与
+ // cleanup 都必须在 rm 锁之前 wait 心跳,避免它醒来后再写一次锁。
+ const killIdx = script.indexOf(`kill "$LOCK_HEARTBEAT_PID" 2>/dev/null`);
+ expect(killIdx).toBeGreaterThan(-1);
+ const waitIdx = script.indexOf(`wait "$LOCK_HEARTBEAT_PID" 2>/dev/null`);
+ expect(waitIdx).toBeGreaterThan(killIdx);
+ // wait 必须在任何 rm 锁之前。
+ const firstLockRm = script.indexOf(`rm -f '/tmp/cindy-update.lock'`);
+ expect(firstLockRm).toBeGreaterThan(waitIdx);
+ // relaunch_app 与 cleanup 两处都应 wait(≥2 处)。
+ const waitCount = (script.match(/wait "\$LOCK_HEARTBEAT_PID" 2>\/dev\/null/g) ?? []).length;
+ expect(waitCount).toBeGreaterThanOrEqual(2);
+ });
+
+ it.runIf(process.platform !== 'win32')('renders to valid bash (bash -n)', () => {
+ const tmp = path.join(os.tmpdir(), `cindy-linux-script-syntax-${process.pid}.sh`);
+ fs.writeFileSync(tmp, script, { mode: 0o755 });
+ try {
+ execFileSync('/bin/bash', ['-n', tmp]);
+ } finally {
+ fs.rmSync(tmp, { force: true });
+ }
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/updateService.test.ts b/apps/desktop/src/main/__tests__/updateService.test.ts
index 41d0f3816e..d939e11a66 100644
--- a/apps/desktop/src/main/__tests__/updateService.test.ts
+++ b/apps/desktop/src/main/__tests__/updateService.test.ts
@@ -260,7 +260,9 @@ async function runStartupUpdate(
readAutoUpdateSettings.mockReturnValue({
autoRelaunchOnIdle: options.enabled ?? true,
});
- fetchManifest.mockResolvedValue(updateManifest());
+ fetchManifest.mockResolvedValue(
+ options.platform === 'linux' ? linuxInstallerManifest() : updateManifest(),
+ );
download.mockImplementation(async ({ targetPath }: { targetPath: string }) => {
fs.mkdirSync(path.join(TEST_USER_DATA, 'updates'), { recursive: true });
fs.writeFileSync(targetPath, 'update');
@@ -279,8 +281,41 @@ async function runStartupUpdate(
}
}
-describe('checkForUpdate Linux first-release guard', () => {
- it('returns manual_download on Linux without fetching or downloading, even with a hotfix manifest override', async () => {
+function linuxInstallerManifest(version = '0.0.65') {
+ return {
+ app: {
+ version,
+ installer: {
+ file: `app/linux-x64/cindy-${version}-amd64.deb`,
+ sha256: 'abc',
+ size: 123,
+ },
+ },
+ };
+}
+
+describe('checkForUpdate Linux installer flow', () => {
+ it('downloads the Linux installer .deb instead of a hotfix zip', async () => {
+ readAutoUpdateSettings.mockReturnValue({ autoRelaunchOnIdle: false });
+ download.mockImplementation(async ({ targetPath }: { targetPath: string }) => {
+ fs.mkdirSync(path.join(TEST_USER_DATA, 'updates'), { recursive: true });
+ fs.writeFileSync(targetPath, 'deb');
+ return { path: targetPath, size: 123 };
+ });
+ const { checkForUpdate, getUpdateStatus } = await freshUpdateService('linux');
+
+ const result = await checkForUpdate(linuxInstallerManifest('9.9.9'));
+
+ expect(result).toBe('ready');
+ expect(getUpdateStatus()).toBe('ready');
+ expect(download).toHaveBeenCalledTimes(1);
+ expect(download.mock.calls[0]?.[0]).toMatchObject({
+ url: expect.stringContaining('cindy-9.9.9-amd64.deb'),
+ sha256: 'abc',
+ });
+ });
+
+ it('ignores a Linux hotfix zip and stays idle without an installer', async () => {
const { checkForUpdate, getUpdateStatus } = await freshUpdateService('linux');
const result = await checkForUpdate({
@@ -292,29 +327,27 @@ describe('checkForUpdate Linux first-release guard', () => {
size: 123,
},
},
- claudeCode: {
- version: '1.0.0',
- file: 'claude-code/1.0.0/linux-x64/claude.gz',
- sha256: 'def',
- size: 456,
- },
});
- expect(result).toBe('manual_download');
+ expect(result).toBe('idle');
expect(getUpdateStatus()).toBe('idle');
- expect(fetchManifest).not.toHaveBeenCalled();
expect(download).not.toHaveBeenCalled();
});
- it('keeps returning manual_download on repeated Linux checks while remaining idle', async () => {
- const { checkForUpdate, getUpdateStatus } = await freshUpdateService('linux');
+ it('does not auto-apply a staged Linux .deb at startup', async () => {
+ await expect(runStartupUpdate({ platform: 'linux' })).resolves.toMatchObject({
+ hasUpdate: true,
+ action: 'none',
+ version: '0.0.65',
+ });
+ });
- expect(await checkForUpdate()).toBe('manual_download');
- expect(await checkForUpdate()).toBe('manual_download');
+ it('refuses the xd org beta default on Linux without writing to disk', async () => {
+ tryEnableUncustomizedBetaAtomic.mockReset();
+ const { enableUncustomizedBetaChannel } = await freshUpdateService('linux');
- expect(getUpdateStatus()).toBe('idle');
- expect(fetchManifest).not.toHaveBeenCalled();
- expect(download).not.toHaveBeenCalled();
+ await expect(enableUncustomizedBetaChannel()).resolves.toBe(false);
+ expect(tryEnableUncustomizedBetaAtomic).not.toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 5376454294..a897ea3fb4 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -2290,22 +2290,113 @@ if (started) {
// written → crash. Block here (synchronously) until the lock disappears.
{
const lockPath = getUpdateLockPath();
- const maxWaitMs = 30_000;
+ // Windows / mac 热更窗口很短。Linux pkexec 要用户输入密码,更新脚本会
+ // 心跳刷新这把锁并把自己的 PID 写进锁内容;只要 PID 还活着且心跳新鲜,
+ // 就不能清掉这把锁——否则旧进程会在安装中途启动,被 root 替换文件。
+ const maxWaitMs = process.platform === 'linux' ? 30 * 60 * 1000 : 30_000;
+ const staleAfterMs = process.platform === 'linux' ? 20_000 : 30_000;
const pollMs = 500;
const start = Date.now();
- while (fs.existsSync(lockPath) && Date.now() - start < maxWaitMs) {
- // Busy-wait is acceptable here: this only runs during the brief
- // robocopy window and the app has no UI yet.
- const waitUntil = Date.now() + pollMs;
- while (Date.now() < waitUntil) {
- /* spin */
+ // 启动阶段还没有 UI,必须同步等锁。Atomics.wait 会让出 CPU,
+ // 避免原来的空转在 Linux 输密码期间占满一核。
+ const lockWait = new Int32Array(new SharedArrayBuffer(4));
+ const readLockPid = (): number | null => {
+ try {
+ const raw = fs.readFileSync(lockPath, 'utf8');
+ const pid = Number(raw.trim().split(/\s+/).pop());
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
+ } catch {
+ return null;
+ }
+ };
+ const pidAlive = (pid: number): boolean => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+ };
+ // 主进程在 spawn 前预建锁(持有者 = 主进程 PID),spawn 事件后退出;
+ // 更新脚本接管后再把自己的 PID 写进去。这中间有毫秒级的交接窗口:
+ // 锁里的主进程 PID 已死但 mtime 极新,不能当死锁清掉——给 5s 交接
+ // 宽限,期间继续等脚本接管。
+ const handoffGraceMs = 5_000;
+ // 孤儿心跳兜底:如果持有者 PID 已死、心跳却持续刷新锁(更新脚本被
+ // 单独 kill、心跳子进程还活着),不能无限等。心跳每次 5s 刷新,连续
+ // 3 个心跳周期都看到「PID 死 + mtime 新」就判定为孤儿,清锁继续启动。
+ const orphanGraceMs = (staleAfterMs * 2) + 5_000;
+ let deadButFreshSinceMs: number | null = null;
+ // 记录是否在锁上等过,供等锁实例醒来后 exec 自己(见循环下方)。
+ let waitedForUpdateLock = false;
+ while (fs.existsSync(lockPath)) {
+ waitedForUpdateLock = true;
+ if (process.platform === 'linux') {
+ const holderPid = readLockPid();
+ // 带 PID 的新锁:活锁 = 心跳新鲜 且(持有者存活 或 处于交接宽限)。
+ if (holderPid !== null) {
+ const mtimeMs = (() => {
+ try {
+ return fs.statSync(lockPath).mtimeMs;
+ } catch {
+ return null;
+ }
+ })();
+ if (mtimeMs === null) break;
+ const ageMs = Date.now() - mtimeMs;
+ const fresh = ageMs <= staleAfterMs;
+ const inHandoff = ageMs <= handoffGraceMs;
+ const holderAlive = pidAlive(holderPid);
+ if (fresh && (holderAlive || inHandoff)) {
+ Atomics.wait(lockWait, 0, 0, pollMs);
+ continue;
+ }
+ // 心跳新鲜但持有者已死:超过交接宽限就开始计孤儿时长。
+ if (fresh && !holderAlive) {
+ if (deadButFreshSinceMs === null) deadButFreshSinceMs = Date.now();
+ if (Date.now() - deadButFreshSinceMs < orphanGraceMs) {
+ Atomics.wait(lockWait, 0, 0, pollMs);
+ continue;
+ }
+ break;
+ }
+ break;
+ }
+ // 老格式锁(没有 PID):退回原来的总时长上限。
+ if (Date.now() - start >= maxWaitMs) break;
+ Atomics.wait(lockWait, 0, 0, pollMs);
+ continue;
}
+ if (Date.now() - start >= maxWaitMs) break;
+ Atomics.wait(lockWait, 0, 0, pollMs);
}
- // If still locked after 30s, proceed anyway (stale lock).
+ // If still locked after the wait, proceed anyway (stale lock).
+ // 锁已不存在(更新脚本正常清掉)同样算已清——等锁实例必须走
+ // 「拉起新进程退出」路径,否则旧代码继续跑。
+ let lockCleared = !fs.existsSync(lockPath);
try {
fs.unlinkSync(lockPath);
+ lockCleared = true;
} catch {
- /* ignore */
+ lockCleared = !fs.existsSync(lockPath);
+ }
+
+ // Linux:这个实例在锁上等过(说明一次应用内更新刚刚完成)。它加载的
+ // 是安装前的旧代码,直接继续会与更新脚本刚拉起的新实例抢单实例锁,
+ // 抢赢的话旧代码会带着新资源混跑。等锁的实例醒来后拉一个新进程
+ // (加载磁盘上的新二进制)并立即退出,单实例锁两边都已是新代码。
+ // 只有锁确实删掉了才走这条路:删不掉(目录只读/权限被改)说明更新
+ // 脚本或环境仍认为更新在进行,继续按原策略放行会让自己陷入「拉起
+ // 新进程 → 新进程又见锁等待 → 再拉起」的重启循环。
+ if (process.platform === 'linux' && waitedForUpdateLock && lockCleared) {
+ try {
+ const exe = process.execPath;
+ const args = process.argv.slice(1);
+ spawn(exe, args, { stdio: 'inherit', detached: true }).unref();
+ } catch {
+ /* ignore */
+ }
+ process.exit(0);
}
}
diff --git a/apps/desktop/src/main/updateAutoRelaunchPolicy.ts b/apps/desktop/src/main/updateAutoRelaunchPolicy.ts
index a54d0c6bd9..60ae6be218 100644
--- a/apps/desktop/src/main/updateAutoRelaunchPolicy.ts
+++ b/apps/desktop/src/main/updateAutoRelaunchPolicy.ts
@@ -13,7 +13,8 @@ export type AutoRelaunchBlockReason =
| 'recent-busy'
| 'recent-resume'
| 'user-active'
- | 'screen-state-unknown';
+ | 'screen-state-unknown'
+ | 'interactive-auth';
export interface AutoRelaunchReadinessInput {
enabled: boolean;
@@ -29,6 +30,8 @@ export interface AutoRelaunchReadinessInput {
idleThresholdSeconds?: number;
busyQuietPeriodMs?: number;
resumeCooldownMs?: number;
+ /** Linux pkexec 需要用户在场输入密码,禁止无人值守 / 启动自动安装。 */
+ requiresInteractiveAuth?: boolean;
}
export function getAutoRelaunchBlockReason(
@@ -39,6 +42,7 @@ export function getAutoRelaunchBlockReason(
const resumeCooldownMs = input.resumeCooldownMs ?? AUTO_UPDATE_RESUME_COOLDOWN_MS;
if (!input.enabled) return 'disabled';
+ if (input.requiresInteractiveAuth) return 'interactive-auth';
if (input.isDev) return 'dev';
if (input.status !== 'ready') return 'not-ready';
if (input.isRelaunching) return 'relaunching';
diff --git a/apps/desktop/src/main/updateChannelStore.ts b/apps/desktop/src/main/updateChannelStore.ts
index a59a1f0c11..d2e06bffe6 100644
--- a/apps/desktop/src/main/updateChannelStore.ts
+++ b/apps/desktop/src/main/updateChannelStore.ts
@@ -148,6 +148,8 @@ export async function resetUpdateChannelSettings(): Promise<UpdateChannelSetting
/** manifestService 消费的单一读取入口:返回是否启用 beta(设备级)。 */
export function isBetaChannelEnabled(): boolean {
+ // Linux 没有 beta 清单 / 热更 zip;隐藏开关后仍读落盘值会把客户端钉在不可达渠道。
+ if (process.platform === 'linux') return false;
return readUpdateChannelSettings().enableBeta;
}
diff --git a/apps/desktop/src/main/updateScriptLinux.ts b/apps/desktop/src/main/updateScriptLinux.ts
new file mode 100644
index 0000000000..52e64f4115
--- /dev/null
+++ b/apps/desktop/src/main/updateScriptLinux.ts
@@ -0,0 +1,295 @@
+/**
+ * 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.
+ *
+ * Extracted so the generated script can be regression-tested without Electron.
+ */
+
+export interface LinuxUpdateScriptTimings {
+ /** Seconds to wait for the old PID before escalating to SIGKILL. */
+ exitKillAfterSeconds: number;
+ /** Seconds after which a PID that survived SIGKILL aborts the update. */
+ exitAbortAfterSeconds: number;
+ /** Total seconds to poll for the relaunched main process. */
+ verifyTimeoutSeconds: number;
+ /** Second at which relaunch is retried (only if the first launch failed). */
+ verifyRetryAtSeconds: number;
+ /** Seconds between lock-file heartbeats while pkexec may be waiting. */
+ lockHeartbeatSeconds: number;
+}
+
+export const DEFAULT_LINUX_UPDATE_SCRIPT_TIMINGS: LinuxUpdateScriptTimings = {
+ exitKillAfterSeconds: 120,
+ exitAbortAfterSeconds: 135,
+ verifyTimeoutSeconds: 30,
+ verifyRetryAtSeconds: 15,
+ lockHeartbeatSeconds: 5,
+};
+
+export interface LinuxUpdateScriptParams {
+ /** PID of the exiting app process the script must wait for. */
+ pid: number;
+ /** Absolute path of the downloaded .deb. */
+ debPath: string;
+ /** Manifest SHA-256 of the staged .deb, rechecked immediately before pkexec. */
+ sha256: string;
+ /** Manifest size of the staged .deb, used to bound the elevated copy. */
+ sizeBytes: number;
+ /** Absolute path of the installed main binary to relaunch. */
+ exePath: string;
+ /** Update lock file the bootstrap spins on during the swap. */
+ lockFilePath: string;
+ /** cindy-update.log path. */
+ logPath: string;
+ timings?: Partial<LinuxUpdateScriptTimings>;
+}
+
+/** POSIX single-quote so paths cannot break out of the generated script. */
+export function shellSingleQuote(value: string): string {
+ return `'${value.replace(/'/g, `'\\''`)}'`;
+}
+
+/**
+ * pgrep -f treats its pattern as an ERE — escape metacharacters so the
+ * installed binary path matches literally.
+ */
+export function escapeEre(s: string): string {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+/**
+ * 拉起验证按启动的子 PID(kill -0)而不是 pgrep:等锁的旧实例进程名
+ * 也是 Cindy,按名字会把「更新前就启动的等待者」误判成新版本。
+ */
+
+export function normalizeLinuxDebSha256(value: string): string | null {
+ const hex = value.trim().toLowerCase();
+ return /^[0-9a-f]{64}$/.test(hex) ? hex : null;
+}
+
+export function buildLinuxUpdateScript(params: LinuxUpdateScriptParams): string {
+ const { pid, debPath, exePath, lockFilePath, logPath } = params;
+ const sha256 = normalizeLinuxDebSha256(params.sha256);
+ if (!sha256) {
+ throw new Error('Linux update script requires a 64-char sha256 of the staged .deb');
+ }
+ const sizeBytes = Math.max(1, Math.floor(params.sizeBytes));
+ if (!Number.isFinite(sizeBytes)) {
+ throw new Error('Linux update script requires a finite deb size');
+ }
+ const t = { ...DEFAULT_LINUX_UPDATE_SCRIPT_TIMINGS, ...params.timings };
+ const qLog = shellSingleQuote(logPath);
+ const qDeb = shellSingleQuote(debPath);
+ const qExe = shellSingleQuote(exePath);
+ const qLock = shellSingleQuote(lockFilePath);
+ const qSha = shellSingleQuote(sha256);
+
+ return [
+ '#!/bin/bash',
+ 'set -u',
+ // 先接管更新锁、启动心跳,再碰任何外部路径——日志若被替换成
+ // FIFO 会让 append 永久阻塞,锁和心跳必须在阻塞之前就位,否则
+ // bootstrap 会在 20s 后把「持有者已死的锁」当死锁清掉。
+ `echo updating $$ > ${qLock}`,
+ 'LOCK_PARENT=$$',
+ 'LOCK_PGID=$$',
+ `INSTALL_PID_FILE=${qLock}.install`,
+ // 进程组扫描(输出落文件再逐行读,pgrep 自排除自身,心跳辅助进程不会
+ // 误计;pkexec 已死但其孤儿 apt/dpkg 后代仍在组里,会被扫到)。
+ // 组文件用 mktemp 建私有随机临时文件,不用可预测的 <lock>.group 路径——
+ // 该路径被占位成目录或父目录不可写时,`pgrep > file` 会失败;此时必须
+ // fail closed(当作「安装链可能还在」),绝不能把锁清掉让新 Cindy 在
+ // apt 还在替换文件时启动。
+ 'scan_group_others() {',
+ ` GROUPFILE=$(mktemp "\${TMPDIR:-/tmp}/cindy-group.XXXXXX") 2>/dev/null || { OTHERS=1; return 0; }`,
+ ` if ! pgrep -g "$LOCK_PGID" > "$GROUPFILE" 2>/dev/null; then`,
+ ' rm -f "$GROUPFILE"',
+ ' OTHERS=1',
+ ' return 0',
+ ' fi',
+ ' OTHERS=0',
+ ' while read -r GPID; do',
+ ' [ -z "$GPID" ] && continue',
+ ' [ "$GPID" = "$BASHPID" ] && continue',
+ ' [ "$GPID" = "$LOCK_PARENT" ] && continue',
+ ' [ -n "${LOCK_HEARTBEAT_PID:-}" ] && [ "$GPID" = "$LOCK_HEARTBEAT_PID" ] && continue',
+ ' OTHERS=1',
+ ' break',
+ ` done < "$GROUPFILE"`,
+ ' rm -f "$GROUPFILE"',
+ '}',
+ // 拉起的新进程必须脱离本进程组(setsid),否则会被 scan_group_others',
+ // 当成「仍在安装」,心跳和锁永远清不掉,新 Cindy 也会卡在等锁。',
+ // 先等心跳真正退出再清锁:kill 只是发信号,不保证进程已死;bash 在
+ // 前台等待 sleep 时会推迟处理 SIGTERM,若此刻直接 rm 锁,心跳醒来后
+ // 仍可能再写一次锁,让新拉起的 Cindy 卡在等锁。wait 收口这个窗口。
+ 'relaunch_app() {',
+ ` kill "$LOCK_HEARTBEAT_PID" 2>/dev/null`,
+ ` wait "$LOCK_HEARTBEAT_PID" 2>/dev/null`,
+ ' rm -f "$INSTALL_PID_FILE"',
+ ` rm -f ${qLock}`,
+ ` setsid nohup ${qExe} >/dev/null 2>&1 &`,
+ ' LAUNCHED_PID=$!',
+ '}',
+ '(',
+ ' while true; do',
+ ' if kill -0 "$LOCK_PARENT" 2>/dev/null; then',
+ ` echo updating "$LOCK_PARENT" > ${qLock}`,
+ ` sleep ${t.lockHeartbeatSeconds}`,
+ ' continue',
+ ' fi',
+ ' # 父 bash 死了。安装链是否还在,看本进程组里除自己和父之外',
+ ' # 还有没有活成员。',
+ ' scan_group_others',
+ ' if [ "$OTHERS" -eq 1 ]; then',
+ ' # 用 $BASHPID 写锁:子 shell 里 $$ 仍是父 shell 的 PID,',
+ ' # 写它等于宣告一个已死的持有者。',
+ ` echo updating "$BASHPID" > ${qLock}`,
+ ` sleep ${t.lockHeartbeatSeconds}`,
+ ' continue',
+ ' fi',
+ ' # 父死且组内没有别的成员:确实没有人在替换文件,清锁退出。',
+ ' rm -f "$INSTALL_PID_FILE"',
+ ` rm -f ${qLock}`,
+ ' exit 0',
+ ' done',
+ ') &',
+ 'LOCK_HEARTBEAT_PID=$!',
+ 'cleanup() {',
+ ' # 收到可捕获信号时,先扫进程组:pkexec 已死但其提权 Bash /',
+ ' # apt-get / dpkg 后代仍在覆盖安装时,锁和心跳都留下,由心跳接管。',
+ ' # 心跳自己已被排除在扫描外,不会让 cleanup 误判成「还有别人」。',
+ ' scan_group_others',
+ ' if [ "$OTHERS" -eq 1 ]; then',
+ ' return',
+ ' fi',
+ ' kill "$LOCK_HEARTBEAT_PID" 2>/dev/null',
+ ' wait "$LOCK_HEARTBEAT_PID" 2>/dev/null',
+ ' rm -f "$INSTALL_PID_FILE"',
+ ` rm -f ${qLock}`,
+ '}',
+ 'trap cleanup EXIT',
+ '',
+ `echo "[$(date)] Update script started, waiting for PID ${pid}" >> ${qLog}`,
+ `echo "[$(date)] deb=${qDeb} exe=${qExe}" >> ${qLog}`,
+ '',
+ 'WAITED=0',
+ `while kill -0 ${pid} 2>/dev/null; do`,
+ ' sleep 1',
+ ' WAITED=$((WAITED+1))',
+ ` if [ "$WAITED" -eq ${t.exitKillAfterSeconds} ]; then`,
+ ` echo "[$(date)] PID ${pid} still alive after ${t.exitKillAfterSeconds}s — exit appears hung, sending SIGKILL" >> ${qLog}`,
+ ` kill -9 ${pid} 2>/dev/null`,
+ ' fi',
+ ` if [ "$WAITED" -ge ${t.exitAbortAfterSeconds} ]; then`,
+ ` echo "[$(date)] FATAL: PID ${pid} survived SIGKILL — aborting update" >> ${qLog}`,
+ ' exit 1',
+ ' fi',
+ 'done',
+ `echo "[$(date)] Process ${pid} exited, waiting for filesystem to settle" >> ${qLog}`,
+ 'sleep 2',
+ '',
+ 'PKEXEC=/usr/bin/pkexec',
+ 'if [ ! -x "$PKEXEC" ]; then',
+ ' PKEXEC=$(command -v pkexec 2>/dev/null || true)',
+ 'fi',
+ 'if [ -z "$PKEXEC" ] || [ ! -x "$PKEXEC" ]; then',
+ ` echo "[$(date)] FATAL: pkexec not found — cannot install .deb" >> ${qLog}`,
+ ' relaunch_app',
+ ' exit 1',
+ 'fi',
+ '',
+ `if [ ! -f ${qDeb} ]; then`,
+ ` echo "[$(date)] FATAL: staged .deb missing before install" >> ${qLog}`,
+ ' relaunch_app',
+ ' exit 1',
+ 'fi',
+ // 提权边界校验:整个「复制 → 哈希 → 安装」都在同一个 root shell 里完成。
+ // .deb 先拷进 root 自有的 0700 临时目录,哈希与安装读的是同一份 root 所有
+ // 的副本,用户侧进程无法在哈希后换包;期望摘要与路径经 argv 传入。
+ // 提权 shell 只写 stdout/stderr,由外层用户 shell 重定向到日志——
+ // root 自己从不打开用户可替换的日志路径(符号链接攻击面)。
+ 'ELEVATED=\'set -eu',
+ 'TMP=$(mktemp -d "${TMPDIR:-/tmp}/cindy-deb.XXXXXX")',
+ 'chmod 700 "$TMP"',
+ 'cleanup_e() { rm -rf "$TMP"; }',
+ 'trap cleanup_e EXIT',
+ // 快速失败检查;权威防线是下面的 dd nofollow 原子打开。
+ 'if [ -L "$2" ] || [ ! -f "$2" ]; then',
+ ' echo "staged package is not a regular file" >&2',
+ ' exit 1',
+ 'fi',
+ // 原子打开:O_NOFOLLOW 拒绝符号链接(ELOOP),O_NONBLOCK 让 FIFO
+ // 立即失败而不是挂起。count 按清单大小封顶,字符设备(如 /dev/zero)
+ // 也只会读 预期大小+2MiB,随后的大小/哈希校验兜底。
+ 'CAP=$(( ($3 / 1048576) + 2 ))',
+ 'dd if="$2" of="$TMP/update.deb" iflag=nofollow,nonblock bs=1048576 count="$CAP" 2>/dev/null',
+ 'WRITTEN=$(stat -c %s "$TMP/update.deb")',
+ 'if [ "$WRITTEN" != "$3" ]; then',
+ ' echo "size mismatch: expected $3 got $WRITTEN" >&2',
+ ' exit 1',
+ 'fi',
+ `ACTUAL=$(sha256sum "$TMP/update.deb" | awk "{print \\$1}")`,
+ 'if [ "$ACTUAL" != "$1" ]; then',
+ ' echo "sha256 mismatch: expected $1 got $ACTUAL" >&2',
+ ' exit 1',
+ 'fi',
+ 'if [ -x /usr/bin/apt-get ]; then',
+ ' apt-get install --yes --allow-downgrades "$TMP/update.deb"',
+ 'elif [ -x /usr/bin/dpkg ]; then',
+ ' dpkg --install "$TMP/update.deb"',
+ 'else',
+ ' exit 127',
+ 'fi\'',
+ '',
+ `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"',
+ 'INSTALL_EXIT=$?',
+ 'rm -f "$INSTALL_PID_FILE"',
+ `echo "[$(date)] install exit code: $INSTALL_EXIT" >> ${qLog}`,
+ '',
+ 'if [ "$INSTALL_EXIT" -ne 0 ]; then',
+ ` echo "[$(date)] INSTALL FAILED — relaunching previous binary" >> ${qLog}`,
+ ' relaunch_app',
+ ' exit 1',
+ 'fi',
+ '',
+ `echo "[$(date)] Starting app: ${qExe}" >> ${qLog}`,
+ // 先杀心跳、放锁,再 setsid 拉起:新进程不在本进程组里,不会
+ // 被 scan_group_others 误判成安装链,也不会卡在自己的锁上。
+ 'relaunch_app',
+ 'OPEN_EXIT=$?',
+ `echo "[$(date)] relaunch spawn exit code: $OPEN_EXIT" >> ${qLog}`,
+ '',
+ 'VERIFIED=0',
+ 'sleep 2',
+ `for i in $(seq 1 ${t.verifyTimeoutSeconds}); do`,
+ // 按启动的子 PID 验证(kill -0),不用 pgrep 按进程名找:等锁的旧实例
+ // 进程名同样是 Cindy,会把它误判成更新后的进程;updater 自己的
+ // bash -c 也永远匹配不上这个子 PID。
+ ` if kill -0 "$LAUNCHED_PID" 2>/dev/null; then`,
+ ' VERIFIED=1',
+ ' break',
+ ' 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 &`,
+ ' LAUNCHED_PID=$!',
+ ' fi',
+ ' sleep 1',
+ 'done',
+ 'if [ "$VERIFIED" -eq 1 ]; then',
+ ` echo "[$(date)] PROCESS VERIFIED: launched pid $LAUNCHED_PID is running" >> ${qLog}`,
+ 'else',
+ ` echo "[$(date)] WARNING: relaunch not verified within ${t.verifyTimeoutSeconds}s" >> ${qLog}`,
+ 'fi',
+ '',
+ `echo "[$(date)] Update script finished" >> ${qLog}`,
+ ].join('\n') + '\n';
+}
diff --git a/apps/desktop/src/main/updateService.ts b/apps/desktop/src/main/updateService.ts
index 36c27769b6..ee385fa3be 100644
--- a/apps/desktop/src/main/updateService.ts
+++ b/apps/desktop/src/main/updateService.ts
@@ -62,6 +62,7 @@ import {
import { throwIpcError } from './utils/ipcValidate';
import { noteExpectedExit } from './startup-diagnostics';
import { buildMacOSUpdateScript } from './updateScriptMacOS';
+import { buildLinuxUpdateScript, normalizeLinuxDebSha256 } from './updateScriptLinux';
import { disposeAndroidAdb } from './mcp-integrations/android';
import { abortIOSSimulatorOperationsForExit } from './mcp-integrations/ios-simulator-exit';
import { getGhostNodeRuntimeBroker } from './cindy-brain/index';
@@ -206,7 +207,7 @@ function broadcastStatus(payload: UpdateStatusPayload): void {
function channelSettingsWire() {
return {
- enableBeta: readUpdateChannelSettings().enableBeta,
+ enableBeta: process.platform === 'linux' ? false : readUpdateChannelSettings().enableBeta,
isCustomized: isEnableBetaUserCustomized(),
};
}
@@ -293,6 +294,7 @@ async function getAutoRelaunchBlockReasonForCurrentState(): Promise<AutoRelaunch
nowMs,
lastBusyAtMs,
lastResumeAtMs,
+ requiresInteractiveAuth: process.platform === 'linux',
});
}
@@ -316,6 +318,8 @@ async function getStartupRelaunchBlockReason(): Promise<AutoRelaunchBlockReason
if (isDev()) return 'dev';
if (currentStatus !== 'ready') return 'not-ready';
if (isRelaunching || autoRelaunchInProgress) return 'relaunching';
+ // pkexec 必须用户在场输入密码,启动时不能自己装。
+ if (process.platform === 'linux') return 'interactive-auth';
return null;
}
@@ -498,6 +502,8 @@ export function isUpdateRelaunchImminent(): boolean {
if (currentStatus !== 'downloading' && currentStatus !== 'ready') return false;
// The native updater replaces the *installed* app; it never runs in dev.
if (isDev()) return false;
+ // Linux 安装要 pkexec 密码,不会在空闲/启动时自己装。
+ if (process.platform === 'linux') return false;
// Respecting the user's switch: with auto-relaunch off the patch just sits
// there until they click the banner, which is not "imminent".
return readAutoUpdateSettings().autoRelaunchOnIdle;
@@ -748,6 +754,8 @@ function discardStagedPatchFiles(): void {
readyVersion = undefined;
readyFilePath = undefined;
readyChannelEpoch = undefined;
+ linuxStagedDebSha256 = null;
+ linuxStagedDebSize = null;
removePatchInfo();
const flag = discardedVersion ? readReloginFlag() : null;
if (flag?.version === discardedVersion) {
@@ -913,6 +921,23 @@ function isMacAppTranslocated(): boolean {
return !isDev() && process.platform === 'darwin' && !app.isInApplicationsFolder();
}
+/**
+ * mac/win 热更下 hotfix zip;Linux 没有 hotfix,清单只挂 installer .deb。
+ * 非 .deb 的 Linux installer 直接丢掉,避免把任意文件交给 pkexec。
+ */
+function resolveUpdateAsset(manifest: Manifest): { file: string; sha256: string; size: number } | undefined {
+ if (process.platform === 'linux') {
+ const installer = manifest.app.installer;
+ if (!installer?.file || !installer.sha256) return undefined;
+ if (!installer.file.toLowerCase().endsWith('.deb')) {
+ log.error('Linux installer is not a .deb, refusing in-app update: %s', installer.file);
+ return undefined;
+ }
+ return installer;
+ }
+ return manifest.app.hotfix;
+}
+
// ── Core check logic ───────────────────────────────────────────────────────
export type CheckForUpdateResult =
@@ -973,12 +998,6 @@ async function doCheckForUpdate(manifestOverride?: Manifest | null): Promise<Che
return 'idle';
}
- if (process.platform === 'linux') {
- log.info('Linux first-release guard: skipping in-app update flow');
- currentStatus = 'idle';
- return 'manual_download';
- }
-
// wasReady 路径:本地已经下好了 a 版本,正在等用户点重启。这次轮询要继续做版本对比,
// 发现 b > a 时进入 superseding 状态去下 b,而不是像旧实现那样直接短路返回。
// previousReadyVersion/Path 用于失败时静默回退到 a。
@@ -1000,9 +1019,9 @@ async function doCheckForUpdate(manifestOverride?: Manifest | null): Promise<Che
return 'manifest_failed';
}
- const asset = manifest.app.hotfix;
+ const asset = resolveUpdateAsset(manifest);
if (!asset) {
- log.info('No hotfix in manifest');
+ log.info(process.platform === 'linux' ? 'No installer in Linux manifest' : 'No hotfix in manifest');
if (!wasReady) currentStatus = 'idle';
return 'idle';
}
@@ -1163,6 +1182,9 @@ async function doCheckForUpdate(manifestOverride?: Manifest | null): Promise<Che
readyVersion = latestVersion;
readyFilePath = result.path;
readyChannelEpoch = updateChannelEpoch;
+ // 信任锚:manifest 里的 installer 摘要与大小,进本进程内存,不落用户可写盘。
+ linuxStagedDebSha256 = normalizeLinuxDebSha256(asset.sha256 ?? '');
+ linuxStagedDebSize = typeof asset.size === 'number' && asset.size > 0 ? asset.size : null;
setStatus('ready', { version: latestVersion });
return 'ready';
} catch (err) {
@@ -1514,6 +1536,138 @@ async function reclaimSubagentRunnersForRelaunch(): Promise<boolean> {
* has the same shape: a patch file that disappears between the readiness check
* and the spawn.
*/
+/**
+ * Linux 安装包的信任锚:本进程从 CDN manifest 拿到的 installer 摘要。
+ * patch-info.json 与暂存 .deb 都是用户可写文件,不能当可信来源——同一用户
+ * 进程可以把两者一起换掉。只有本进程内存里的 manifest 摘要不可伪造;
+ * 冷启动拿到旧补丁却没有 manifest 时(断网回落路径)宁可不装。
+ */
+let linuxStagedDebSha256: string | null = null;
+let linuxStagedDebSize: number | null = null;
+
+function readStagedLinuxDebSha256(debPath: string): string | null {
+ if (!linuxStagedDebSha256 || linuxStagedDebSize === null) {
+ log.error('no trusted Linux installer digest/size in process state — refusing to install');
+ return null;
+ }
+ try {
+ const raw = fs.readFileSync(path.join(getUpdatesDir(), PATCH_INFO_FILE), 'utf-8');
+ const info = JSON.parse(raw) as PatchInfo;
+ if (info.fileName && path.basename(debPath) !== info.fileName) return null;
+ } catch {
+ return null;
+ }
+ return linuxStagedDebSha256;
+}
+
+function executeUpdateLinux(debPath: string): void {
+ const exePath = app.getPath('exe');
+ const lockFilePath = getUpdateLockPath();
+ const logDir = path.join(app.getPath('userData'), 'logs');
+ fs.mkdirSync(logDir, { recursive: true });
+ const logPath = path.join(logDir, 'cindy-update.log');
+ const pid = process.pid;
+
+ if (!debPath.toLowerCase().endsWith('.deb') || !fs.existsSync(debPath)) {
+ log.error('Linux update file is missing or not a .deb: %s', maskPath(debPath));
+ handleApplyFailure('linux_deb_missing');
+ return;
+ }
+
+ const sha256 = readStagedLinuxDebSha256(debPath);
+ if (!sha256) {
+ log.error('Linux staged .deb is missing a trusted sha256: %s', maskPath(debPath));
+ handleApplyFailure('linux_deb_unverified');
+ return;
+ }
+
+ log.info('Linux relaunch: exe=%s, deb=%s, pid=%d', maskPath(exePath), maskPath(debPath), pid);
+ try {
+ const exeStat = fs.statSync(exePath);
+ const debStat = fs.statSync(debPath);
+ log.info(
+ 'pre-update stat: exe size=%d mtime=%s, deb size=%d',
+ exeStat.size, exeStat.mtime.toISOString(), debStat.size,
+ );
+ } catch (err) {
+ log.error('pre-update stat failed:', err);
+ }
+
+ const sizeBytes = linuxStagedDebSize;
+ if (sizeBytes === null) {
+ log.error('Linux staged .deb is missing a trusted size: %s', maskPath(debPath));
+ handleApplyFailure('linux_deb_unverified');
+ return;
+ }
+
+ let script: string;
+ try {
+ script = buildLinuxUpdateScript({
+ pid, debPath, sha256, sizeBytes, exePath, lockFilePath, logPath,
+ });
+ } catch (err) {
+ log.error('failed to build Linux update script:', err);
+ handleApplyFailure('linux_script_build_failed');
+ return;
+ }
+
+ // 主进程在 spawn 之前先把锁建立起来(持有者 = 本进程 PID),再从 spawn
+ // 事件退出。这样「点击更新 → 脚本写入锁」之间不存在没有锁的窗口:
+ // 万一用户在 spawn 前重启 Cindy,bootstrap 至少能看到一把新鲜的心跳锁
+ // 而继续等;脚本启动后第一件事就是把锁换成自己的 PID 继续心跳。
+ // bootstrap 只按心跳新鲜度判断,因此交接窗口同样安全。
+ try {
+ fs.writeFileSync(lockFilePath, `updating ${process.pid}\n`);
+ } catch (err) {
+ log.error('failed to pre-create Linux update lock:', err);
+ handleApplyFailure('linux_lock_create_failed');
+ return;
+ }
+
+ // 脚本不落盘:内容经 argv 传给 bash -c,同一用户进程没有可替换的
+ // 目录项,也就不能借 pkexec 授权执行自己的内容。
+ const child = spawn('/bin/bash', ['-c', script, 'cindy-linux-update'], {
+ detached: true,
+ stdio: 'ignore',
+ });
+
+ // 三个终态里只有第一个赢。超时 / error 之后再收到迟到的 spawn 事件,
+ // 不能再 forceQuit()——更新已经按失败处理,退出去连旧进程都没人拉起。
+ let settled = false;
+ const clearPrecreatedLock = (): void => {
+ try { fs.unlinkSync(lockFilePath); } catch { /* ignore */ }
+ };
+ const spawnTimeout = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ log.error('Linux update script spawn timed out after 5 s');
+ // detached spawn 是进程组组长:负 PID 杀整组,心跳子 shell / pkexec
+ // 不会变成孤儿继续装。
+ if (child.pid !== undefined) {
+ try { process.kill(-child.pid, 'SIGKILL'); } catch { /* ignore */ }
+ }
+ clearPrecreatedLock();
+ handleApplyFailure('spawn_timeout');
+ }, 5_000);
+
+ child.on('spawn', () => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(spawnTimeout);
+ child.unref();
+ forceQuit();
+ });
+
+ child.on('error', (err: NodeJS.ErrnoException) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(spawnTimeout);
+ log.error('Linux update script spawn failed: %s (code=%s)', err.message, err.code);
+ clearPrecreatedLock();
+ handleApplyFailure(err.code ?? 'unknown');
+ });
+}
+
async function executeRelaunch(theme: 'light' | 'dark'): Promise<void> {
try {
await executeRelaunchUnguarded(theme);
@@ -1612,8 +1766,7 @@ async function executeRelaunchUnguarded(theme: 'light' | 'dark'): Promise<void>
executeUpdateMacOS(readyFilePath);
break;
case 'linux':
- log.error('Linux in-app update is intentionally disabled in first release');
- handleApplyFailure('linux_update_disabled');
+ executeUpdateLinux(readyFilePath);
break;
default:
log.error(`Unsupported platform: ${process.platform}`);
@@ -1629,7 +1782,11 @@ export function initUpdateService(): void {
// user stays on the latest version and never triggers another updater run.
sweepStaleUpdateTempDirs();
- ipcMain.on('update-relaunch', (_event, theme: 'light' | 'dark') => {
+ ipcMain.on('update-relaunch', (event, theme: 'light' | 'dark') => {
+ // Linux 分支会退出应用并触发 pkexec 系统授权,属于特权操作;
+ // 按仓库规则先校验 sender 是 Cindy 顶层 frame,不给未来可能拿到
+ // 该 channel 的副窗口 renderer 留强制退出/弹授权的口子。
+ assertTrustedAppRendererEvent(event);
// Defensive default: if an old preload is somehow loaded (or theme is
// missing), fall back to dark — matches the renderer's getStoredTheme()
// default and the .env'd-out look most users have.
@@ -1698,6 +1855,9 @@ export function initUpdateService(): void {
ipcMain.handle('update-channel-settings-set', async (event, payload: unknown) => {
assertTrustedAppRendererEvent(event);
+ if (process.platform === 'linux') {
+ throwIpcError('INVALID_PARAMS', 'Linux does not support the beta update channel');
+ }
if (!payload || typeof payload !== 'object') {
throwIpcError('INVALID_PARAMS', 'update channel settings payload required');
}
@@ -1831,10 +1991,16 @@ export function initUpdateService(): void {
// Network unavailable — fall back to local patch.
log.info('Manifest fetch failed, falling back to local patch');
const patchResult = checkExistingPatch();
- if (patchResult.action === 'relaunch') {
+ if (patchResult.action === 'relaunch' && process.platform !== 'linux') {
currentStatus = 'ready';
return await buildStartupReadyReply(patchResult.version);
}
+ if (patchResult.action === 'relaunch' && process.platform === 'linux') {
+ // Linux 安装的信任锚是 manifest 里的 installer 摘要;断网拿不到
+ // manifest 时旧补丁没有可信摘要,宁可重下也不装。
+ log.info('Linux: manifest unavailable — refusing to stage local patch without a trusted digest');
+ discardStagedPatchFiles();
+ }
return { hasUpdate: false, action: 'none' as const, error: 'manifest_failed' as const };
}
@@ -1852,6 +2018,22 @@ export function initUpdateService(): void {
const patchResult = checkExistingPatch();
if (patchResult.action === 'relaunch' && patchResult.version === latestVersion) {
log.info('Local patch v%s matches latest, requesting relaunch', patchResult.version);
+ if (process.platform === 'linux') {
+ // 冷启动匹配旧补丁:把这份 CDN manifest 的 installer 摘要与大小
+ // 重新锚进进程内存,让后续 apply 有可信锚可用。
+ const installer = manifest.app.installer;
+ linuxStagedDebSha256 = installer?.sha256
+ ? normalizeLinuxDebSha256(installer.sha256)
+ : null;
+ linuxStagedDebSize = typeof installer?.size === 'number' && installer.size > 0
+ ? installer.size
+ : null;
+ if (!linuxStagedDebSha256 || linuxStagedDebSize === null) {
+ log.info('Linux: manifest has no installer digest/size — discarding local patch');
+ discardStagedPatchFiles();
+ return { hasUpdate: false, action: 'none' as const };
+ }
+ }
currentStatus = 'ready';
return await buildStartupReadyReply(patchResult.version);
}
@@ -1865,6 +2047,8 @@ export function initUpdateService(): void {
readyVersion = undefined;
readyFilePath = undefined;
readyChannelEpoch = undefined;
+ linuxStagedDebSha256 = null;
+ linuxStagedDebSize = null;
}
// Step 3: download (re-using the manifest we already have). Route through
@@ -1941,6 +2125,8 @@ export function initUpdateService(): void {
export async function enableUncustomizedBetaChannel(
shouldWrite: () => boolean = () => true,
): Promise<boolean> {
+ // Linux 没有 beta 清单,组织默认打开只会把客户端钉在不可达渠道。
+ if (process.platform === 'linux') return false;
const wasBeta = readUpdateChannelSettings().enableBeta;
// 先拦住 apply 再等落盘。身份守卫拒绝或写入失败时,旧补丁还得能用。
if (!wasBeta) {
diff --git a/apps/desktop/src/renderer/components/settings/AboutSection.tsx b/apps/desktop/src/renderer/components/settings/AboutSection.tsx
index f2536779b7..d1095faf80 100644
--- a/apps/desktop/src/renderer/components/settings/AboutSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/AboutSection.tsx
@@ -313,11 +313,27 @@ function SocialPlatformIcon({ id }: { id: (typeof DESKTOP_SOCIAL_LINKS)[number][
);
}
-function AutoUpdateToggleRow() {
+export function AutoUpdateToggleRow() {
const { t } = useTranslation();
+ const isLinux = window.electronAPI?.platform === 'linux';
const { state, setAutoRelaunchOnIdle, reset } = useAutoUpdateSettings();
const [saving, setSaving] = useState(false);
+ if (isLinux) {
+ return (
+ <div className="flex flex-col gap-1.5 px-[18px] py-4">
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="text-13 text-[var(--settings-section-sublabel)]">
+ {t('settings.about.autoUpdateLabel')}
+ </span>
+ <p className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70">
+ {t('settings.about.linuxUpdateDescription')}
+ </p>
+ </div>
+ </div>
+ );
+ }
+
const handleToggle = async (next: boolean) => {
setSaving(true);
try {
diff --git a/apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx b/apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx
index 280577dff8..81ebddbccf 100644
--- a/apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx
@@ -32,7 +32,7 @@ export function ExperimentalSection() {
<div className="flex flex-col gap-3">
<LspBetaCell />
- <BetaChannelCell />
+ {window.electronAPI?.platform !== 'linux' ? <BetaChannelCell /> : null}
{EXPERIMENTAL_FEATURES.map((feature) => (
<ExperimentalFeatureRow key={feature.key} feature={feature} />
))}
diff --git a/apps/desktop/src/renderer/components/settings/HelpSection.tsx b/apps/desktop/src/renderer/components/settings/HelpSection.tsx
index 5075586fa0..54b03f14ba 100644
--- a/apps/desktop/src/renderer/components/settings/HelpSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/HelpSection.tsx
@@ -1,4 +1,4 @@
-import { GitBranch, MessageSquareText, Sparkles } from 'lucide-react';
+import { GitBranch, MessageSquareText, Sparkles, Download } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
@@ -18,6 +18,7 @@ const sectionDescClass = 'mt-1 text-12 leading-[1.6] text-[var(--settings-sectio
export function HelpSection({ onAskHelp }: HelpSectionProps) {
const { t } = useTranslation();
+ const isLinux = window.electronAPI?.platform === 'linux';
return (
<div className="flex flex-col gap-3">
@@ -74,6 +75,23 @@ export function HelpSection({ onAskHelp }: HelpSectionProps) {
</div>
</div>
+ {isLinux ? (
+ <div className={cardClass}>
+ <div className="flex items-start gap-3">
+ <Download size={16} className="mt-0.5 shrink-0 text-[var(--settings-section-title)]" />
+ <div className="min-w-0">
+ <div className={sectionTitleClass}>{t('settings.help.linuxUpdates.title')}</div>
+ <p className={sectionDescClass}>{t('settings.help.linuxUpdates.description')}</p>
+ <ul className="mt-2 space-y-1.5 text-13 leading-[1.6] text-[var(--settings-section-title)]">
+ <li>{t('settings.help.linuxUpdates.item1')}</li>
+ <li>{t('settings.help.linuxUpdates.item2')}</li>
+ <li>{t('settings.help.linuxUpdates.item3')}</li>
+ </ul>
+ </div>
+ </div>
+ </div>
+ ) : null}
+
<div className={cardClass}>
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/linuxUpdateSettings.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/linuxUpdateSettings.test.tsx
new file mode 100644
index 0000000000..34e13c59f9
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/linuxUpdateSettings.test.tsx
@@ -0,0 +1,104 @@
+// @vitest-environment jsdom
+
+import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ }),
+}));
+
+vi.mock('@/lib/toast', () => ({
+ toast: { success: vi.fn(), error: vi.fn() },
+}));
+
+vi.mock('@/hooks/useAutoUpdateSettings', () => ({
+ useAutoUpdateSettings: () => ({
+ state: {
+ autoRelaunchOnIdle: true,
+ isCustomized: false,
+ defaultAutoRelaunchOnIdle: true,
+ loading: false,
+ },
+ setAutoRelaunchOnIdle: vi.fn(),
+ reset: vi.fn(),
+ }),
+}));
+
+vi.mock('@/hooks/useExperimentalFeatures', () => ({
+ EXPERIMENTAL_FEATURES: [],
+ useExperimentalFlag: () => ({ enabled: false, setEnabled: vi.fn() }),
+}));
+
+vi.mock('../LspBetaCell', () => ({
+ LspBetaCell: () => <div>lsp-beta-cell</div>,
+}));
+
+vi.mock('../BetaChannelCell', () => ({
+ BetaChannelCell: () => <div>beta-channel-cell</div>,
+}));
+
+import { AutoUpdateToggleRow } from '../AboutSection';
+import { ExperimentalSection } from '../ExperimentalSection';
+import { HelpSection } from '../HelpSection';
+
+describe('Linux update settings', () => {
+ afterEach(() => cleanup());
+
+ beforeEach(() => {
+ (window as unknown as { electronAPI: { platform: string } }).electronAPI = {
+ platform: 'linux',
+ };
+ });
+
+ it('explains in-app .deb updates instead of showing the idle-install switch', () => {
+ render(<AutoUpdateToggleRow />);
+
+ expect(screen.getByText('settings.about.autoUpdateLabel')).toBeTruthy();
+ expect(screen.getByText('settings.about.linuxUpdateDescription')).toBeTruthy();
+ expect(screen.queryByRole('switch')).toBeNull();
+ });
+
+ it('keeps the idle-install switch on macOS', () => {
+ (window as unknown as { electronAPI: { platform: string } }).electronAPI = {
+ platform: 'darwin',
+ };
+ render(<AutoUpdateToggleRow />);
+
+ expect(screen.getByRole('switch', { name: 'settings.about.autoUpdateLabel' })).toBeTruthy();
+ expect(screen.queryByText('settings.about.linuxUpdateDescription')).toBeNull();
+ });
+
+ it('hides the beta channel card on Linux', () => {
+ render(<ExperimentalSection />);
+
+ expect(screen.getByText('lsp-beta-cell')).toBeTruthy();
+ expect(screen.queryByText('beta-channel-cell')).toBeNull();
+ });
+
+ it('keeps the beta channel card on Windows', () => {
+ (window as unknown as { electronAPI: { platform: string } }).electronAPI = {
+ platform: 'win32',
+ };
+ render(<ExperimentalSection />);
+
+ expect(screen.getByText('beta-channel-cell')).toBeTruthy();
+ });
+
+ it('shows Linux install and update help on Linux', () => {
+ render(<HelpSection onAskHelp={() => undefined} />);
+
+ expect(screen.getByText('settings.help.linuxUpdates.title')).toBeTruthy();
+ expect(screen.getByText('settings.help.linuxUpdates.item1')).toBeTruthy();
+ });
+
+ it('hides Linux install and update help on macOS', () => {
+ (window as unknown as { electronAPI: { platform: string } }).electronAPI = {
+ platform: 'darwin',
+ };
+ render(<HelpSection onAskHelp={() => undefined} />);
+
+ expect(screen.queryByText('settings.help.linuxUpdates.title')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 17fadb2a68..065847c093 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -718,6 +718,13 @@
"item2": "Break large tasks into multiple turns: understand first, edit second, verify third.",
"item3": "Create a new session for independent problems instead of mixing everything into one thread."
},
+ "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 does not offer the beta channel or idle auto-install, because installing requires your password."
+ },
"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.",
"qnaPlaceholder": "For example: how do I import a Codex session?",
@@ -776,6 +783,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.",
"autoUpdateEnabledToast": "Idle update installation enabled",
"autoUpdateDisabledToast": "Idle update installation disabled",
"autoUpdateSaveFailed": "Failed to save auto-update settings",
@@ -5436,7 +5444,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": "Linux first release uses manual downloads only. Download the latest installer from the download page."
+ "manualDownload": "Download the update in the app. Installing it requires your system password."
},
"closeConfirm": {
"title": "Confirm exit?",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 1c7d9391db..f7958a843d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -718,6 +718,13 @@
"item2": "大きな仕事は複数ターンに分けます。まず理解し、その次に編集し、最後に検証します。",
"item3": "独立した問題は一つのスレッドに混ぜず、新しいセッションを作って扱います。"
},
+ "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 では Beta チャネルとアイドル時の自動インストールは提供しません。"
+ },
"qnaTitle": "そのまま質問する",
"qnaDescription": "overview に載っていない内容でも、やりたいことを聞けば次に開く場所や進め方を案内します。",
"qnaPlaceholder": "例:Codex のセッションをインポートするには?",
@@ -776,6 +783,7 @@
"openLogsDirError": "ログディレクトリを開けませんでした",
"autoUpdateLabel": "アイドル時に更新をインストール",
"autoUpdateDescription": "更新のダウンロード完了後、このコンピューターが 10 分間操作されず、実行中のタスクがない場合に、アプリを自動的に再起動してインストールします。",
+ "linuxUpdateDescription": "新しいビルドがある場合、アプリ内で .deb をダウンロードします。インストールにはシステムパスワードが必要なため、アイドル時の自動インストールは行いません。",
"autoUpdateEnabledToast": "アイドル時の更新インストールを有効にしました",
"autoUpdateDisabledToast": "アイドル時の更新インストールを無効にしました",
"autoUpdateSaveFailed": "自動更新設定を保存できませんでした",
@@ -5434,7 +5442,7 @@
"ready": "新バージョン準備完了 — サイドバーをクリックして更新を完了",
"manifestFailed": "更新確認に失敗しました。ネットワークを確認してください",
"downloadFailed": "新バージョンのダウンロードに失敗しました。後でもう一度お試しください",
- "manualDownload": "Linux 初版は手動ダウンロードのみ対応です。ダウンロードページから最新版インストーラーを取得してください。"
+ "manualDownload": "アプリ内で更新をダウンロードしてください。インストールにはシステムパスワードが必要です。"
},
"closeConfirm": {
"title": "終了しますか?",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 3b2f0666a3..6041d52d6c 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -718,6 +718,13 @@
"item2": "큰 작업은 여러 턴으로 나누세요. 먼저 이해하고, 다음에 수정하고, 마지막에 검증하세요.",
"item3": "독립적인 문제는 한 스레드에 섞지 말고 새 세션을 만들어 처리하세요."
},
+ "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에서는 Beta 채널과 유휴 상태 자동 설치를 제공하지 않습니다."
+ },
"qnaTitle": "바로 질문하기",
"qnaDescription": "overview 에 없는 내용이라도 하고 싶은 일을 물어보면 다음에 열어야 할 곳이나 진행 방법을 안내합니다.",
"qnaPlaceholder": "예: Codex 세션을 어떻게 가져오나요?",
@@ -776,6 +783,7 @@
"openLogsDirError": "로그 디렉터리를 열지 못했습니다",
"autoUpdateLabel": "유휴 상태일 때 업데이트 설치",
"autoUpdateDescription": "업데이트 다운로드가 완료된 뒤, 이 컴퓨터가 10분 동안 조작되지 않았고 실행 중인 작업이 없으면 앱을 자동으로 다시 시작해 설치합니다.",
+ "linuxUpdateDescription": "새 빌드가 있으면 앱에서 .deb를 다운로드합니다. 설치할 때 시스템 비밀번호가 필요하므로 유휴 상태에서는 자동 설치하지 않습니다.",
"autoUpdateEnabledToast": "유휴 상태 자동 업데이트 설치가 켜졌습니다",
"autoUpdateDisabledToast": "유휴 상태 자동 업데이트 설치가 꺼졌습니다",
"autoUpdateSaveFailed": "자동 업데이트 설정을 저장하지 못했습니다",
@@ -5434,7 +5442,7 @@
"ready": "새 버전 준비 완료 — 사이드바를 클릭해 업데이트 완료",
"manifestFailed": "업데이트 확인 실패, 네트워크를 확인하세요",
"downloadFailed": "새 버전 다운로드 실패, 나중에 다시 시도하세요",
- "manualDownload": "Linux 첫 릴리스는 수동 다운로드만 지원합니다. 다운로드 페이지에서 최신 설치 프로그램을 받아 주세요."
+ "manualDownload": "앱에서 업데이트를 다운로드하세요. 설치하려면 시스템 비밀번호가 필요합니다."
},
"closeConfirm": {
"title": "정말 나가시겠습니까?",
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 19d38610b8..d8ce79624c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -718,6 +718,13 @@
"item2": "把大任务拆成多轮:先理解,再修改,再验证。",
"item3": "当你要处理独立问题时,创建新任务而不是把所有事情混在一个任务里。"
},
+ "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 暂不提供 Beta 渠道和空闲时自动安装,因为安装需要输入密码。"
+ },
"qnaTitle": "直接提问",
"qnaDescription": "如果 overview 里没有覆盖到你的问题,可以直接问我该怎么做。",
"qnaPlaceholder": "例如:如何导入 codex 任务",
@@ -776,6 +783,7 @@
"openLogsDirError": "打开日志目录失败",
"autoUpdateLabel": "空闲时自动安装更新",
"autoUpdateDescription": "更新下载完成后,当这台电脑 10 分钟无操作且没有任务运行时,自动重启应用完成安装。",
+ "linuxUpdateDescription": "有新版本时会在应用内下载 .deb。点更新后需要输入系统密码完成安装,因此不会在空闲时自动安装。",
"autoUpdateEnabledToast": "已开启空闲时自动安装更新",
"autoUpdateDisabledToast": "已关闭空闲时自动安装更新",
"autoUpdateSaveFailed": "保存自动更新设置失败",
@@ -5434,7 +5442,7 @@
"ready": "新版本已就绪,点击侧边栏完成更新",
"manifestFailed": "检查更新失败,请检查网络",
"downloadFailed": "新版本下载失败,稍后再试",
- "manualDownload": "Linux 首版仅支持手动下载安装包,请前往下载页获取最新版。"
+ "manualDownload": "请在应用内下载更新,安装时需要系统密码。"
},
"closeConfirm": {
"title": "确认要离开吗?",
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 7c87239c3f..2f64b44fdb 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -718,6 +718,13 @@
"item2": "把大任務拆成多輪:先理解,再修改,再驗證。",
"item3": "當你要處理獨立問題時,建立新任務而不是把所有事情混在一個任務裡。"
},
+ "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 暫不提供 Beta 渠道和空閒時自動安裝,因為安裝需要輸入密碼。"
+ },
"qnaTitle": "直接提問",
"qnaDescription": "如果 overview 裡沒有覆蓋到你的問題,可以直接問我該怎麼做。",
"qnaPlaceholder": "例如:如何匯入 codex 任務",
@@ -776,6 +783,7 @@
"openLogsDirError": "開啟日誌目錄失敗",
"autoUpdateLabel": "空閒時自動安裝更新",
"autoUpdateDescription": "更新下載完成後,當這臺電腦 10 分鐘無操作且沒有任務執行時,自動重啟應用完成安裝。",
+ "linuxUpdateDescription": "有新版本時會在應用程式內下載 .deb。點更新後需要輸入系統密碼完成安裝,因此不會在空閒時自動安裝。",
"autoUpdateEnabledToast": "已開啟空閒時自動安裝更新",
"autoUpdateDisabledToast": "已關閉空閒時自動安裝更新",
"autoUpdateSaveFailed": "儲存自動更新設定失敗",
@@ -5434,7 +5442,7 @@
"ready": "新版本已就緒,點選側邊欄完成更新",
"manifestFailed": "檢查更新失敗,請檢查網路",
"downloadFailed": "新版本下載失敗,稍後再試",
- "manualDownload": "Linux 首版僅支援手動下載安裝包,請前往下載頁獲取最新版。"
+ "manualDownload": "請在應用程式內下載更新,安裝時需要系統密碼。"
},
"closeConfirm": {
"title": "確認要離開嗎?",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index f85e774eeb..d4192dba0e 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3581,7 +3581,7 @@ interface ElectronAPI {
* - 'ready' → 新版本已就绪,等待重启
* - 'manifest_failed' → 拉清单失败(网络问题)
* - 'download_failed' → 找到了新版本但下载失败
- * - 'manual_download' → Linux 首版仅支持手动下载安装包
+ * - 'manual_download' → 保留给仍走手动安装的旧路径;现行 Linux 已应用内下 .deb
*/
checkForUpdate: () => Promise<{
result: