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。

fix(desktop): distinguish failed Debian update probes (#4870)

Lizie509966f80dc
diff --git a/apps/desktop/src/main/__tests__/linuxInstallation.test.ts b/apps/desktop/src/main/__tests__/linuxInstallation.test.ts
index dac68a5167..d4d134188e 100644
--- a/apps/desktop/src/main/__tests__/linuxInstallation.test.ts
+++ b/apps/desktop/src/main/__tests__/linuxInstallation.test.ts
@@ -4,7 +4,13 @@ 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 {
+ checkDebianManagedInstallation,
+ findLinuxUserInstallation,
+ isDebianManagedInstallation,
+ missingLinuxUserInstallTools,
+ linuxUserDesktopName,
+} from '../linuxInstallation';
import { stageLinuxBuildInfo } from '../../../forge-linux';
import { buildLinuxUpdateScript } from '../updateScriptLinux';
import { allDeepLinkSchemes } from '@cindy/maker-shared/brand-identity';
@@ -17,6 +23,44 @@ describe('Linux install routing', () => {
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('distinguishes a failed ownership query from confirmed non-ownership', () => {
+ expect(checkDebianManagedInstallation('/usr/lib/cindy/Cindy', () => 'unrelated: /usr/lib/cindy/Cindy\n'))
+ .toEqual({ status: 'not-managed' });
+ expect(checkDebianManagedInstallation('/usr/lib/cindy/Cindy', () => 'cindy: /usr/lib/cindy/Cindy\n'))
+ .toEqual({ status: 'managed' });
+ const timeout = Object.assign(new Error('dpkg-query timed out'), { code: 'ETIMEDOUT', signal: 'SIGTERM' });
+ expect(checkDebianManagedInstallation('/usr/lib/cindy/Cindy', () => { throw timeout; }))
+ .toEqual({ status: 'error', error: timeout });
+ const denied = Object.assign(new Error('spawnSync /usr/bin/dpkg-query EACCES'), {
+ code: 'EACCES', status: null, signal: null,
+ });
+ expect(checkDebianManagedInstallation('/usr/lib/cindy/Cindy', () => { throw denied; }))
+ .toEqual({ status: 'error', error: denied });
+ const queryFailed = Object.assign(new Error('Command failed: /usr/bin/dpkg-query -S /usr/lib/cindy/Cindy'), {
+ status: 2, signal: null,
+ });
+ expect(checkDebianManagedInstallation('/usr/lib/cindy/Cindy', () => { throw queryFailed; }))
+ .toEqual({ status: 'error', error: queryFailed });
+ });
+
+ it('maps dpkg-query exit status 1 to confirmed non-ownership', () => {
+ const noMatch = Object.assign(
+ new Error('Command failed: /usr/bin/dpkg-query -S /home/devuser/custom-builds/Cindy'),
+ { status: 1, signal: null },
+ );
+ expect(checkDebianManagedInstallation('/home/devuser/custom-builds/Cindy', () => { throw noMatch; }))
+ .toEqual({ status: 'not-managed' });
+ });
+
+ it('maps a missing dpkg-query binary to confirmed non-ownership', () => {
+ const missingBinary = Object.assign(new Error('spawnSync /usr/bin/dpkg-query ENOENT'), {
+ code: 'ENOENT', status: null, signal: null,
+ });
+ expect(checkDebianManagedInstallation('/usr/lib/cindy/Cindy', () => { throw missingBinary; }))
+ .toEqual({ status: 'not-managed' });
+ });
+
it('reports missing portable dependencies', () => {
expect(missingLinuxUserInstallTools(() => true)).toEqual([]);
expect(missingLinuxUserInstallTools((name) => name !== 'bsdtar')).toEqual(['bsdtar']);
diff --git a/apps/desktop/src/main/__tests__/updateService.test.ts b/apps/desktop/src/main/__tests__/updateService.test.ts
index 51734c8fb5..838f4d377a 100644
--- a/apps/desktop/src/main/__tests__/updateService.test.ts
+++ b/apps/desktop/src/main/__tests__/updateService.test.ts
@@ -40,10 +40,14 @@ const spawnProcess = vi.fn(() => ({
on: vi.fn(),
}));
const findLinuxUserInstallation = vi.fn(() => null);
-const isDebianManagedInstallation = vi.fn(() => false);
+const checkDebianManagedInstallation = vi.fn<() =>
+ | { status: 'managed' }
+ | { status: 'not-managed' }
+ | { status: 'error'; error: unknown }
+>(() => ({ status: 'not-managed' }));
const missingLinuxUserInstallTools = vi.fn(() => [] as string[]);
vi.mock('../linuxInstallation', () => ({
- findLinuxUserInstallation, isDebianManagedInstallation, missingLinuxUserInstallTools,
+ findLinuxUserInstallation, checkDebianManagedInstallation, missingLinuxUserInstallTools,
}));
const checkWindowsUpdaterPrerequisites = vi.fn<
() => { satisfied: boolean; missingFiles: string[] }
@@ -59,6 +63,7 @@ const logInfo = vi.fn();
const logWarn = vi.fn();
const logError = vi.fn();
const logDebug = vi.fn();
+const maskPath = vi.fn((value: string) => value);
vi.mock('electron', () => ({
app: {
@@ -176,7 +181,7 @@ vi.mock('../logger', () => ({
error: logError,
debug: logDebug,
}),
- maskPath: (value: string) => value,
+ maskPath,
}));
function setPlatform(value: NodeJS.Platform): void {
@@ -267,8 +272,8 @@ beforeEach(() => {
spawnProcess.mockClear();
findLinuxUserInstallation.mockReset();
findLinuxUserInstallation.mockReturnValue(null);
- isDebianManagedInstallation.mockReset();
- isDebianManagedInstallation.mockReturnValue(false);
+ checkDebianManagedInstallation.mockReset();
+ checkDebianManagedInstallation.mockReturnValue({ status: 'not-managed' });
missingLinuxUserInstallTools.mockReset();
missingLinuxUserInstallTools.mockReturnValue([]);
checkWindowsUpdaterPrerequisites.mockReset();
@@ -282,6 +287,7 @@ beforeEach(() => {
logWarn.mockReset();
logError.mockReset();
logDebug.mockReset();
+ maskPath.mockClear();
resetUpdateServiceFixture();
});
afterEach(() => {
@@ -566,7 +572,107 @@ function linuxInstallerManifest(version = '0.0.65') {
};
}
+function expectProbeFailureLog(
+ label: string,
+ fields: { reason: string; status: number | null; code: string | null; signal: string | null },
+ leakedPath: string,
+): void {
+ const detail = logError.mock.calls.find((call) => call[0] === label)?.[1];
+ expect(typeof detail).toBe('string');
+ const text = String(detail);
+ expect(text).not.toContain(leakedPath);
+ expect(text).not.toContain('devuser');
+ expect(text).not.toContain('Command failed');
+ expect(JSON.parse(text)).toEqual({ ...fields, path: TEST_EXE });
+ expect(maskPath).toHaveBeenCalledWith(TEST_EXE);
+}
+
describe('checkForUpdate Linux installer flow', () => {
+ it('keeps a staged update ready when the Debian ownership check fails', async () => {
+ download.mockImplementation(async ({ targetPath }: { targetPath: string }) => {
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
+ fs.writeFileSync(targetPath, 'deb');
+ return { path: targetPath, size: 123 };
+ });
+ const leakedPath = '/home/devuser/custom-builds/Cindy';
+ checkDebianManagedInstallation.mockReturnValue({
+ status: 'error',
+ error: Object.assign(new Error(`Command failed: /usr/bin/dpkg-query -S ${leakedPath}`), {
+ code: 'ETIMEDOUT', status: null, signal: 'SIGTERM',
+ }),
+ });
+ 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', version: '0.0.65', errorCode: undefined,
+ }));
+ 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(logError.mock.calls.map((call) => String(call[0]))).toContain(
+ 'Linux Debian ownership check failed: %s',
+ );
+ expectProbeFailureLog('Linux Debian ownership check failed: %s', {
+ reason: 'timeout', status: null, code: 'ETIMEDOUT', signal: 'SIGTERM',
+ }, leakedPath);
+ } finally {
+ service.stopUpdateService();
+ exitSpy.mockRestore();
+ }
+ });
+
+ it('keeps the staged update when the Debian recheck fails after preflight', async () => {
+ download.mockImplementation(async ({ targetPath }: { targetPath: string }) => {
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
+ fs.writeFileSync(targetPath, 'deb');
+ return { path: targetPath, size: 123 };
+ });
+ const leakedPath = '/home/devuser/custom-builds/Cindy';
+ checkDebianManagedInstallation
+ .mockReturnValueOnce({ status: 'managed' })
+ .mockReturnValueOnce({
+ status: 'error',
+ error: Object.assign(new Error(`Command failed: /usr/bin/dpkg-query -S ${leakedPath}`), {
+ status: 2, signal: null,
+ }),
+ });
+ const service = await freshUpdateService('linux', 'x64');
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as never);
+ service.initUpdateService();
+ try {
+ const manifest = linuxInstallerManifest();
+ manifest.app.installer.sha256 = 'ab'.repeat(32);
+ await expect(service.checkForUpdate(manifest)).resolves.toBe('ready');
+ ipcListeners.get('update-relaunch')?.({}, 'dark');
+ await vi.waitFor(() => expect(logError.mock.calls.map((call) => String(call[0]))).toContain(
+ 'Linux Debian ownership recheck failed: %s',
+ ));
+ const info = JSON.parse(fs.readFileSync(path.join(TEST_USER_DATA, 'updates', 'patch-info.json'), 'utf8'));
+ expect(checkDebianManagedInstallation).toHaveBeenCalledTimes(2);
+ expect(info.applyAttempts).toBeUndefined();
+ expect(fs.existsSync(path.join(TEST_USER_DATA, 'updates', info.fileName))).toBe(true);
+ expect(ipcHandlers.get('update-get-status')?.()).toMatchObject({
+ status: 'ready', version: '0.0.65', errorCode: undefined,
+ });
+ expect(exitSpy).not.toHaveBeenCalled();
+ expect(logError.mock.calls.map((call) => String(call[0]))).toContain(
+ 'Linux Debian ownership recheck failed: %s',
+ );
+ expectProbeFailureLog('Linux Debian ownership recheck failed: %s', {
+ reason: 'query-failed', status: 2, code: null, signal: null,
+ }, leakedPath);
+ } finally {
+ service.stopUpdateService();
+ exitSpy.mockRestore();
+ }
+ });
+
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 });
diff --git a/apps/desktop/src/main/linuxInstallation.ts b/apps/desktop/src/main/linuxInstallation.ts
index 7b9c440aa0..c6c0b06170 100644
--- a/apps/desktop/src/main/linuxInstallation.ts
+++ b/apps/desktop/src/main/linuxInstallation.ts
@@ -80,16 +80,49 @@ export function findLinuxUserInstallation(
/** 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(
+export type DebianManagedInstallationCheck =
+ | { status: 'managed' }
+ | { status: 'not-managed' }
+ | { status: 'error'; error: unknown };
+
+/** Confirmed non-ownership, not a retryable probe failure.
+ * - dpkg-query -S exits 1 when no package owns the path.
+ * - spawn ENOENT means /usr/bin/dpkg-query is absent (Arch and other
+ * non-Debian systems). That must keep the unsupported-install block.
+ * Timeouts and exit 2 (database or usage faults) stay errors.
+ */
+function isConfirmedDebianOwnershipMiss(error: unknown): boolean {
+ if (!error || typeof error !== 'object') return false;
+ const details = error as { status?: unknown; signal?: unknown; code?: unknown; killed?: unknown };
+ if (details.killed === true || details.signal != null) return false;
+ // execFileSync sets status null when the binary itself cannot be spawned.
+ if (details.code === 'ENOENT' && details.status == null) return true;
+ if (typeof details.code === 'string' && details.code.length > 0) return false;
+ return details.status === 1;
+}
+
+export function checkDebianManagedInstallation(
exePath: string,
query: (exe: string) => string = (exe) => execFileSync('/usr/bin/dpkg-query', ['-S', exe], {
encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'],
}),
-): boolean {
+): DebianManagedInstallationCheck {
try {
- return query(exePath).split('\n').some((line) => /^cindy(?::[a-z0-9]+)?: /.test(line)
+ const managed = query(exePath).split('\n').some((line) => /^cindy(?::[a-z0-9]+)?: /.test(line)
&& line.slice(line.indexOf(': ') + 2) === exePath);
- } catch { return false; }
+ return managed ? { status: 'managed' } : { status: 'not-managed' };
+ } catch (error) {
+ if (isConfirmedDebianOwnershipMiss(error)) return { status: 'not-managed' };
+ return { status: 'error', error };
+ }
+}
+
+/** Compatibility predicate for callers that only need a confirmed yes/no. */
+export function isDebianManagedInstallation(
+ exePath: string,
+ query?: (exe: string) => string,
+): boolean {
+ return checkDebianManagedInstallation(exePath, query).status === 'managed';
}
export function missingLinuxUserInstallTools(
diff --git a/apps/desktop/src/main/updateService.ts b/apps/desktop/src/main/updateService.ts
index 464e057867..f2323270b8 100644
--- a/apps/desktop/src/main/updateService.ts
+++ b/apps/desktop/src/main/updateService.ts
@@ -69,7 +69,12 @@ 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 {
+ checkDebianManagedInstallation,
+ findLinuxUserInstallation,
+ missingLinuxUserInstallTools,
+ type LinuxUserInstallation,
+} from './linuxInstallation';
import { linuxPasswordStoreRelaunchArgs } from './linuxPasswordStore';
import { CURRENT_CINDY_REGION } from '../shared/brandRegion';
import { disposeAndroidAdb } from './mcp-integrations/android';
@@ -247,6 +252,35 @@ function setStatus(status: UpdateStatus, extra?: Partial<UpdateStatusPayload>):
}
}
+function formatLinuxProbeError(error: unknown, exePath: string): string {
+ const details = error && typeof error === 'object'
+ ? error as { code?: unknown; status?: unknown; signal?: unknown }
+ : {};
+ const code = typeof details.code === 'string' && /^[A-Za-z0-9_]+$/.test(details.code)
+ ? details.code
+ : null;
+ const status = typeof details.status === 'number' && Number.isInteger(details.status)
+ ? details.status
+ : null;
+ const signal = typeof details.signal === 'string' && /^[A-Za-z0-9]+$/.test(details.signal)
+ ? details.signal
+ : null;
+ const reason = code === 'ETIMEDOUT' || (signal !== null && status === null)
+ ? 'timeout'
+ : code === 'ENOENT' || code === 'EACCES' || code === 'EPERM'
+ ? 'not-executable'
+ : 'query-failed';
+ // execFileSync's message embeds the queried path. Log only controlled
+ // fields; the path goes through maskPath on its own.
+ return JSON.stringify({
+ reason,
+ status,
+ code,
+ signal,
+ path: maskPath(exePath),
+ });
+}
+
function blockWindowsUpdaterForMissingRuntime(missingFiles: readonly string[]): false {
log.error(
'Windows updater prerequisites missing (%s); keeping patch staged',
@@ -1776,12 +1810,28 @@ function executeUpdateLinux(debPath: string, installation: LinuxUserInstallation
// 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);
+ const debianCheck = installation ? null : checkDebianManagedInstallation(exePath);
+ if (debianCheck?.status === 'error') {
+ log.error('Linux Debian ownership recheck failed: %s', formatLinuxProbeError(debianCheck.error, exePath));
+ isRelaunching = false;
+ autoRelaunchInProgress = false;
+ // A transient ownership probe failure is not evidence that the install
+ // changed. Keep the verified .deb staged so the user can retry, and do
+ // not consume an apply attempt. checkExistingPatch deletes the .deb
+ // after three recorded attempts.
+ setStatus('ready', { version: readyVersion ?? undefined });
+ return;
+ }
if (installation
? !now || now.prefix !== installation.prefix || now.current !== installation.current
|| now.region !== installation.region || !readyVersion
- : now !== null || !isDebianManagedInstallation(exePath)) {
+ : now !== null || debianCheck?.status !== 'managed') {
throw new Error('Linux installation changed after preflight');
}
+ // Count the attempt only after the recheck confirms we will launch.
+ // Incrementing earlier let three transient recheck failures burn the
+ // staged .deb on the next startup.
+ incrementApplyAttempts();
script = buildLinuxUpdateScript({
pid, debPath, sha256, sizeBytes, exePath, lockFilePath, logPath,
userInstallation: installation ? { ...installation, version: readyVersion! } : undefined,
@@ -1948,9 +1998,19 @@ async function executeRelaunchUnguarded(theme: 'light' | 'dark'): Promise<void>
const exePath = app.getPath('exe');
const installation = findLinuxUserInstallation(exePath, os.homedir(), process.getuid?.() ?? -1);
linuxInstallation = installation;
+ const debianCheck = installation ? null : checkDebianManagedInstallation(exePath);
+ if (debianCheck?.status === 'error') {
+ log.error('Linux Debian ownership check failed: %s', formatLinuxProbeError(debianCheck.error, exePath));
+ isRelaunching = false;
+ autoRelaunchInProgress = false;
+ // Keep the verified installer staged. A transient dpkg-query failure is
+ // not evidence that this executable belongs to an unsupported layout.
+ setStatus('ready', { version: readyVersion ?? undefined });
+ return;
+ }
const supported = installation
? installation.region === CURRENT_CINDY_REGION && missingLinuxUserInstallTools().length === 0
- : isDebianManagedInstallation(exePath);
+ : debianCheck?.status === 'managed';
if (!supported) {
log.error('Linux installation cannot self-update; use the installation guide or its package manager');
isRelaunching = false;
@@ -1994,13 +2054,13 @@ async function executeRelaunchUnguarded(theme: 'light' | 'dark'): Promise<void>
break;
case 'darwin':
// Increment immediately before starting the platform executor so a
- // failed updater can be bounded across restarts. Windows does this only
- // after its final app-local/System32 Runtime check inside the executor.
+ // failed updater can be bounded across restarts. Windows and Linux do
+ // this only after the last in-executor check that can still keep the
+ // staged patch for retry (Windows Runtime, Linux ownership recheck).
incrementApplyAttempts();
executeUpdateMacOS(readyFilePath);
break;
case 'linux':
- incrementApplyAttempts();
executeUpdateLinux(readyFilePath, linuxInstallation);
break;
default:
diff --git a/packages/lizi-mcps/src/__tests__/botMemoryChain.test.ts b/packages/lizi-mcps/src/__tests__/botMemoryChain.test.ts
index 92dbd0154c..cfcb761baf 100644
--- a/packages/lizi-mcps/src/__tests__/botMemoryChain.test.ts
+++ b/packages/lizi-mcps/src/__tests__/botMemoryChain.test.ts
@@ -31,7 +31,18 @@ import path from 'node:path';
import DatabaseCtor from 'better-sqlite3';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+// Real better-sqlite3 + FTS rebuild on a temp disk. Windows CI shards this
+// package next to other sqlite tests, and Defender can make that synchronous
+// work exceed Vitest's default 5s — the learned-prefix case then times out
+// and afterEach unlinks fts.db while the handle is still closing (EBUSY).
+// Same bounded Windows allowance as maker-core memory/contacts sqlite tests;
+// assertions stay unchanged.
+vi.setConfig({
+ testTimeout: process.platform === 'win32' ? 30_000 : 5_000,
+ hookTimeout: process.platform === 'win32' ? 30_000 : 10_000,
+});
import {
MakerMemoryManager,
@@ -111,7 +122,14 @@ afterEach(async () => {
// Windows cannot remove fts.db while the manager still owns an open connection.
manager.dispose();
for (const database of databases) expect(database.open).toBe(false);
- await rm(root, { recursive: true, force: true });
+ try {
+ await rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code !== 'EBUSY' && code !== 'EPERM' && code !== 'EACCES') throw error;
+ // Defender / indexer can keep fts.db briefly after close. Leave the temp
+ // directory for the OS, matching maker-core memory scope-resolver cleanup.
+ }
});
/**