Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): honor Desktop reclaim release credentials
xuzini-xzn6aca3823bf14
diff --git a/apps/desktop/src/main/maker-host/__tests__/pi-native-compat-overrides-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/pi-native-compat-overrides-store.test.tsindex 231d85232f..8202526723 100644--- a/apps/desktop/src/main/maker-host/__tests__/pi-native-compat-overrides-store.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/pi-native-compat-overrides-store.test.ts@@ -110,7 +110,7 @@ let pendingTimers = 0;let calls = 0, pause = ${Boolean(options.pause)}, failWrite = ${Boolean(options.failWrite)};let releaseFailure = ${JSON.stringify(options.failRelease ?? '')};const api = runInNewContext(${JSON.stringify(PI_CACHE_RECOVERY_SOURCE + '\ninstallCindyCacheRecovery(pi)')}, {- ...fs, path, process: { pid: process.pid, uptime: () => process.uptime(), kill: (...a) => process.kill(...a),+ ...fs, path, process: { pid: process.pid, platform: process.platform, uptime: () => process.uptime(), kill: (...a) => process.kill(...a),env: { PI_CODING_AGENT_DIR: '/fixture', CINDY_PI_CACHE_COMPAT_FILE: file } },createHash, randomUUID, Buffer, clearTimeout, Date,setTimeout: (fn, ms) => {@@ -121,7 +121,7 @@ const api = runInNewContext(${JSON.stringify(PI_CACHE_RECOVERY_SOURCE + '\ninsta}, ms);}, homedir: () => '/fixture',pi: { on: (event, fn) => handlers.set(event, fn) },- statSync: name => name === ruleFile ? { size: rule.length } : fs.statSync(name),+ statSync: (name, ...args) => name === ruleFile ? { size: rule.length } : fs.statSync(name, ...args),readFileSync: (name, ...a) => name === ruleFile ? rule : fs.readFileSync(name, ...a),writeFileSync: (name, ...a) => {if (failWrite && typeof name === 'string' && name.endsWith('.tmp')) throw new Error('fixture write failure');@@ -190,13 +190,13 @@ process.send({ event: 'ready', key });const send = (command: string) => child.stdin!.write(command + '\n');return {child, release, send,- async event(name: string) {+ async event(name: string, occurrence = 1) {await vi.waitFor(() => {expect(child.exitCode, stderr).toBeNull();expect(messages.find(message => message.event === 'error'), stderr).toBeUndefined();- expect(messages.some(message => message.event === name), stderr).toBe(true);+ expect(messages.filter(message => message.event === name).length, stderr).toBeGreaterThanOrEqual(occurrence);}, { timeout: 2000 });- return messages.find(message => message.event === name);+ return messages.filter(message => message.event === name)[occurrence - 1];},async stop() {fs.writeFileSync(release, 'release');@@ -253,6 +253,63 @@ describe('native and Desktop cache writers share one lock', () => {} finally { await native.stop(); }});+ it.each(['valid', 'wrong nonce', 'active gate', 'wrong filename', 'invalid nonce', 'malformed', 'oversized', 'directory'])('validates %s after Desktop publishes a release credential for an undeletable held gate', async credential => {+ const gateDir = file + '.lock.reclaim.d';+ const rm = fsp.rm.bind(fsp);+ let gate: string | undefined;+ const spy = vi.spyOn(fsp, 'rm').mockImplementation((target, options) => {+ if (typeof target === 'string' && path.dirname(target) === gateDir && target.endsWith('.json') && fs.existsSync(target)) {+ gate ??= target;+ if (target === gate) return Promise.reject(Object.assign(new Error('fixture gate busy'), { code: 'EBUSY' }));+ }+ return rm(target, options);+ });+ const native = cacheProcess('desktop-released');+ try {+ await withCrossProcessLock(file + '.lock', { label: 'fixture' }, async status => {+ expect(status.held).toBe(true);+ });+ expect(gate).toBeDefined();+ const held = JSON.parse(fs.readFileSync(gate!, 'utf8'));+ expect(held).toMatchObject({ state: 'held', pid: process.pid });+ expect(JSON.parse(fs.readFileSync(gate! + '.released', 'utf8'))).toEqual({ gateFile: path.basename(gate!), nonce: held.nonce });+ const marker = gate! + '.released';+ if (credential === 'wrong nonce') fs.writeFileSync(marker, JSON.stringify({ gateFile: path.basename(gate!), nonce: '00000000-0000-4000-8000-000000000000' }));+ if (credential === 'active gate') fs.rmSync(marker);+ if (credential === 'wrong filename') fs.writeFileSync(marker, JSON.stringify({ gateFile: 'gate-other.json', nonce: held.nonce }));+ if (credential === 'invalid nonce') {+ fs.writeFileSync(gate!, JSON.stringify({ ...held, nonce: 'invalid' }));+ fs.writeFileSync(marker, JSON.stringify({ gateFile: path.basename(gate!), nonce: 'invalid' }));+ }+ if (credential === 'malformed') fs.writeFileSync(marker, '{bad-json');+ if (credential === 'oversized') fs.writeFileSync(marker, JSON.stringify({ gateFile: path.basename(gate!), nonce: held.nonce, padding: 'x'.repeat(4096) }));+ if (credential === 'directory') { fs.rmSync(marker); fs.mkdirSync(marker); }+ // The Desktop process remains alive, and its own production release+ // function, rather than this fixture, minted the original credential.+ await native.event('ready'); native.send('start');+ const first = await native.event('success');+ expect(first.events).toEqual(['done']); expect(first.calls).toBe(2);+ if (credential === 'valid') {+ await vi.waitFor(() => expect(read('child', 'desktop-released', 'c'.repeat(64))).toEqual(fix));+ } else {+ await native.event('persistence-idle');+ expect(fs.existsSync(file)).toBe(false);+ }+ native.send('next');+ const next = await native.event('next');+ expect(next.events).toEqual(['done']); expect(next.calls).toBe(3);+ expect(next.sent).toEqual([{ model: 'desktop-released' }]);+ if (credential !== 'valid') {+ await native.event('persistence-idle', 2);+ expect(fs.existsSync(file)).toBe(false);+ }+ expect(fs.existsSync(gate!)).toBe(true);+ } finally {+ spy.mockRestore(); await native.stop();+ fs.rmSync(gateDir, { recursive: true, force: true });+ }+ });+it.each(['once', 'held'] as const)('lets Desktop persist while Pi stays alive after %s release failure', async failRelease => {const native = cacheProcess('release', { failRelease });try {diff --git a/packages/maker-core/src/agents/pi/cache-recovery-source.ts b/packages/maker-core/src/agents/pi/cache-recovery-source.tsindex 67686fc002..352015cb83 100644--- a/packages/maker-core/src/agents/pi/cache-recovery-source.ts+++ b/packages/maker-core/src/agents/pi/cache-recovery-source.ts@@ -85,6 +85,45 @@ function installCindyCacheRecovery(pi) {return left && right && ['dev', 'ino', 'size', 'mtimeMs'].every(key => left.info[key] === right.info[key])&& left.text === right.text;}+ function gateReleased(name, nonce) {+ // Desktop's existing .released credential is bound to both the unique+ // gate filename and its UUID nonce. Read only a bounded, stable regular+ // file through one handle, with the same no-follow/root checks as Desktop.+ let fd;+ try {+ const marker = name + '.released';+ const normalize = value => process.platform === 'win32' ? value.replace(/^([A-Z]):/, (_, drive) => drive.toLowerCase() + ':') : value;+ const directory = normalize(realpathSync(path.dirname(name)));+ fd = openSync(marker, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));+ const before = fstatSync(fd, { bigint: true });+ if (!before.isFile() || before.size > 4096n) return false;+ const matchesPath = () => {+ const link = lstatSync(marker, { bigint: true });+ const current = statSync(marker, { bigint: true });+ return !link.isSymbolicLink() && current.dev !== 0n && current.ino !== 0n+ && current.dev === before.dev && current.ino === before.ino+ && link.dev === before.dev && link.ino === before.ino+ && normalize(path.dirname(realpathSync(marker))) === directory;+ };+ if (!matchesPath()) return false;+ const bytes = Buffer.alloc(Number(before.size));+ let offset = 0;+ while (offset < bytes.length) {+ const count = readSync(fd, bytes, offset, bytes.length - offset, offset);+ if (!count) return false;+ offset += count;+ }+ const after = fstatSync(fd, { bigint: true });+ if (!after.isFile() || !['dev', 'ino', 'mode', 'size', 'mtimeNs', 'ctimeNs'].every(key => before[key] === after[key])+ || !matchesPath()) return false;+ const value = JSON.parse(bytes.toString('utf8'));+ return value && typeof value === 'object' && !Array.isArray(value)+ && value.gateFile === path.basename(name) && typeof value.nonce === 'string'+ && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value.nonce)+ && (nonce === undefined || value.nonce === nonce);+ } catch { return false; }+ finally { if (fd !== undefined) { try { closeSync(fd); } catch {} } }+ }function gateBusy(lock, ownGate) {// Legacy gates are still observed by released Desktop versions.try {@@ -101,7 +140,7 @@ function installCindyCacheRecovery(pi) {const snapshot = lockSnapshot(name);if (!snapshot) return true;const record = snapshot.record;- if (record?.state === 'released') continue;+ if (record?.state === 'released' || gateReleased(name, record?.nonce ?? undefined)) continue;if (stale(snapshot)) {const pid = Number(/^gate-(\d+)-/.exec(entry)?.[1]);if (record?.pid || dead(pid)) continue;diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.tsindex 9efc4903fa..f743b93e03 100644--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts@@ -82,7 +82,7 @@ export const CINDY_BRIDGE_EXTENSION_SOURCE = String.raw`/*** cindy-bridge (generated by Cindy — do not edit; overwritten on session start)*/import {- closeSync, globSync, lstatSync, openSync, opendirSync, readFileSync, realpathSync,+ closeSync, constants, fstatSync, globSync, lstatSync, openSync, opendirSync, readFileSync, readSync, realpathSync,renameSync, rmSync, statSync, writeFileSync, mkdirSync, readdirSync, rmdirSync, linkSync,} from 'node:fs';import { createHash, randomUUID } from 'node:crypto';