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): 装入链路消费 forge 打包凭证并记录装入来源

fmfsaisaif172fd59c9c4
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 0ed220d03e..ff253a4eee 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -2885,6 +2885,7 @@ export class GhostManager {
initiallyEnabled?: boolean;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
+ installOrigin?: string;
},
) {
return this.runExclusiveMutation(() => this.installUnlocked(lizFilePath, opts));
@@ -2896,6 +2897,7 @@ export class GhostManager {
initiallyEnabled?: boolean;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
+ installOrigin?: string;
},
): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {
// 装入初始启用态由 UI 层决定(装入确认框勾选,默认沉睡);缺省 true
@@ -3003,6 +3005,7 @@ export class GhostManager {
packageSha256,
revision: receiptRevision,
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
+ ...(opts?.installOrigin !== undefined ? { installOrigin: opts.installOrigin } : {}),
});
await this.receiptStore.write(receipt, { skillSourceDir: finalDir });
let tombstoneClearPending = false;
@@ -3100,6 +3103,7 @@ export class GhostManager {
expectedInstalledApproval: string;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
+ installOrigin?: string;
beforePackageCommit?: () => GhostPackageCommitPreparation | void;
/** 目录换位完成后、任何通知或运行时收尾前触发。 */
onPackagePlaced?: () => void;
@@ -3114,6 +3118,7 @@ export class GhostManager {
expectedInstalledApproval: string;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
+ installOrigin?: string;
/** 新目录已换位、旧目录仍可回滚时执行;抛错会恢复旧版本。 */
beforePackageCommit?: () => GhostPackageCommitPreparation | void;
/** 目录换位完成后、任何通知或运行时收尾前触发。 */
@@ -3337,6 +3342,7 @@ export class GhostManager {
packageSha256,
revision: receiptRevision,
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
+ ...(opts.installOrigin !== undefined ? { installOrigin: opts.installOrigin } : {}),
});
await this.receiptStore.write(receipt, { skillSourceDir: finalDir });
} catch (err) {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forgePackConsume.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forgePackConsume.test.ts
new file mode 100644
index 0000000000..3398f5fef3
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forgePackConsume.test.ts
@@ -0,0 +1,356 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import type { ActiveAppSession } from '../../appSessionState.js';
+import {
+ abandonForgePackInstall,
+ consumeForgePackAtInspect,
+ consumeForgePackAtInstall,
+} from '../forgePackConsume.js';
+import {
+ createForgePackStagingController,
+ sha256Hex,
+} from '../forgePackStaging.js';
+
+const OWNER: ActiveAppSession = {
+ mode: 'cloud',
+ dataOwnerId: 'user-a',
+ generation: 1,
+};
+
+const OTHER: ActiveAppSession = {
+ mode: 'cloud',
+ dataOwnerId: 'user-b',
+ generation: 2,
+};
+
+let tempDir: string | null = null;
+
+afterEach(() => {
+ if (tempDir) {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+ tempDir = null;
+ }
+});
+
+function makeController() {
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-forge-consume-'));
+ let n = 0;
+ return createForgePackStagingController({
+ getTempDir: () => tempDir!,
+ randomId: () => `id-${n++}`,
+ scheduleTimeout: () => ({ cancel() {} }),
+ });
+}
+
+describe('consumeForgePackAtInspect / consumeForgePackAtInstall', () => {
+ it('accepts matching hash and manifest id, then refuses a second inspect', () => {
+ const controller = makeController();
+ const buf = Buffer.from('pkg-bytes');
+ const staged = controller.stage({
+ buf,
+ manifestId: 'demo',
+ owner: OWNER,
+ operationKind: 'install',
+ });
+ const first = consumeForgePackAtInspect(controller, {
+ filePath: staged.stagingPath,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ });
+ expect(first.kind).toBe('accepted');
+ const second = consumeForgePackAtInspect(controller, {
+ filePath: staged.stagingPath,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ });
+ expect(second).toEqual({ kind: 'rejected', reason: 'ticket-replay' });
+ });
+
+ it('invalidates the ticket when inspect hash or manifest id mismatches', () => {
+ const controller = makeController();
+ const buf = Buffer.from('pkg-bytes');
+ const staged = controller.stage({
+ buf,
+ manifestId: 'demo',
+ owner: OWNER,
+ operationKind: 'install',
+ });
+ const rejected = consumeForgePackAtInspect(controller, {
+ filePath: staged.stagingPath,
+ packageSha256: 'b'.repeat(64),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ });
+ expect(rejected).toEqual({ kind: 'rejected', reason: 'ticket-binding-mismatch' });
+ expect(fs.existsSync(staged.stagingPath)).toBe(false);
+ expect(
+ consumeForgePackAtInspect(controller, {
+ filePath: staged.stagingPath,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ }),
+ ).toEqual({ kind: 'not-forge' });
+ });
+
+ it('refuses inspect while the session boundary is pending without consuming the ticket', () => {
+ const controller = makeController();
+ const buf = Buffer.from('pkg-bytes');
+ const staged = controller.stage({
+ buf,
+ manifestId: 'demo',
+ owner: OWNER,
+ operationKind: 'install',
+ });
+ expect(
+ consumeForgePackAtInspect(controller, {
+ filePath: staged.stagingPath,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: true,
+ }),
+ ).toEqual({ kind: 'rejected', reason: 'session-boundary-pending' });
+ expect(fs.existsSync(staged.stagingPath)).toBe(true);
+ expect(
+ consumeForgePackAtInspect(controller, {
+ filePath: staged.stagingPath,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ }).kind,
+ ).toBe('accepted');
+ });
+
+ it('refuses install while the session boundary is pending without consuming the continuation', () => {
+ const controller = makeController();
+ const buf = Buffer.from('pkg-bytes');
+ const staged = controller.stage({
+ buf,
+ manifestId: 'demo',
+ owner: OWNER,
+ operationKind: 'install',
+ });
+ const inspected = consumeForgePackAtInspect(controller, {
+ filePath: staged.stagingPath,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ });
+ expect(inspected.kind).toBe('accepted');
+ if (inspected.kind !== 'accepted') return;
+ expect(
+ consumeForgePackAtInstall(controller, {
+ packTicket: inspected.packTicket,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: true,
+ }),
+ ).toEqual({ kind: 'rejected', reason: 'session-boundary-pending' });
+ expect(
+ consumeForgePackAtInstall(controller, {
+ packTicket: inspected.packTicket,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ }).kind,
+ ).toBe('agent-forge');
+ });
+
+ it('lets install proceed as update even when the pack ticket said install', () => {
+ const controller = makeController();
+ const buf = Buffer.from('pkg-bytes');
+ const staged = controller.stage({
+ buf,
+ manifestId: 'demo',
+ owner: OWNER,
+ operationKind: 'install',
+ });
+ const inspected = consumeForgePackAtInspect(controller, {
+ filePath: staged.stagingPath,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ });
+ expect(inspected.kind).toBe('accepted');
+ if (inspected.kind !== 'accepted') return;
+ const installed = consumeForgePackAtInstall(controller, {
+ packTicket: inspected.packTicket,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ });
+ expect(installed.kind).toBe('agent-forge');
+ if (installed.kind !== 'agent-forge') return;
+ expect(installed.ticket.operationKind).toBe('install');
+ expect(installed.ticket.manifestId).toBe('demo');
+ });
+
+ it('treats a missing pack ticket as manual and refuses replay of a consumed continuation', () => {
+ const controller = makeController();
+ expect(
+ consumeForgePackAtInstall(controller, {
+ packTicket: undefined,
+ packageSha256: 'a'.repeat(64),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ }),
+ ).toEqual({ kind: 'manual' });
+
+ const buf = Buffer.from('pkg-bytes');
+ const staged = controller.stage({
+ buf,
+ manifestId: 'demo',
+ owner: OWNER,
+ operationKind: 'update',
+ });
+ const inspected = consumeForgePackAtInspect(controller, {
+ filePath: staged.stagingPath,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ });
+ expect(inspected.kind).toBe('accepted');
+ if (inspected.kind !== 'accepted') return;
+ expect(
+ consumeForgePackAtInstall(controller, {
+ packTicket: inspected.packTicket,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ }).kind,
+ ).toBe('agent-forge');
+ expect(
+ consumeForgePackAtInstall(controller, {
+ packTicket: inspected.packTicket,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ }),
+ ).toEqual({ kind: 'rejected', reason: 'ticket-replay' });
+ });
+
+ it('refuses inspect continuation when the process freezes past the pack hard deadline', () => {
+ const t1 = 1_700_000_000_000;
+ const ttlMs = 10 * 60 * 1000;
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-forge-consume-'));
+ let afterStage = false;
+ let inspectNowCalls = 0;
+ let n = 0;
+ const controller = createForgePackStagingController({
+ getTempDir: () => tempDir!,
+ ttlMs,
+ randomId: () => `id-${n++}`,
+ scheduleTimeout: () => ({ cancel() {} }),
+ now: () => {
+ if (!afterStage) return t1;
+ inspectNowCalls += 1;
+ // First now() is the pack expiry check (still live). Later now() is
+ // issueInstallContinuation after a 30-minute freeze.
+ return inspectNowCalls === 1 ? t1 + ttlMs - 1_000 : t1 + ttlMs - 1_000 + 30 * 60 * 1000;
+ },
+ });
+ const buf = Buffer.from('pkg-bytes');
+ const staged = controller.stage({
+ buf,
+ manifestId: 'demo',
+ owner: OWNER,
+ operationKind: 'install',
+ });
+ afterStage = true;
+ expect(
+ consumeForgePackAtInspect(controller, {
+ filePath: staged.stagingPath,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ }),
+ ).toEqual({ kind: 'rejected', reason: 'ticket-expired' });
+ expect(fs.existsSync(staged.stagingPath)).toBe(false);
+ expect(inspectNowCalls).toBeGreaterThanOrEqual(2);
+ });
+
+ it('cleans staging on cancel, success, and reject', () => {
+ const controller = makeController();
+ const buf = Buffer.from('pkg-bytes');
+ const cancelStaged = controller.stage({
+ buf,
+ manifestId: 'demo',
+ owner: OWNER,
+ operationKind: 'install',
+ });
+ const cancelInspect = consumeForgePackAtInspect(controller, {
+ filePath: cancelStaged.stagingPath,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ });
+ expect(cancelInspect.kind).toBe('accepted');
+ if (cancelInspect.kind !== 'accepted') return;
+ abandonForgePackInstall(controller, cancelInspect.packTicket);
+ expect(fs.existsSync(cancelStaged.stagingPath)).toBe(false);
+
+ const successStaged = controller.stage({
+ buf,
+ manifestId: 'demo',
+ owner: OWNER,
+ operationKind: 'install',
+ });
+ const successInspect = consumeForgePackAtInspect(controller, {
+ filePath: successStaged.stagingPath,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ });
+ expect(successInspect.kind).toBe('accepted');
+ if (successInspect.kind !== 'accepted') return;
+ const successInstall = consumeForgePackAtInstall(controller, {
+ packTicket: successInspect.packTicket,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'demo',
+ currentOwner: OWNER,
+ boundaryPending: false,
+ });
+ expect(successInstall.kind).toBe('agent-forge');
+ if (successInstall.kind !== 'agent-forge') return;
+ controller.releaseStaging(successInstall.ticket.stagingPath);
+ expect(fs.existsSync(successStaged.stagingPath)).toBe(false);
+
+ const rejectStaged = controller.stage({
+ buf,
+ manifestId: 'demo',
+ owner: OWNER,
+ operationKind: 'install',
+ });
+ consumeForgePackAtInspect(controller, {
+ filePath: rejectStaged.stagingPath,
+ packageSha256: sha256Hex(buf),
+ manifestId: 'other',
+ currentOwner: OTHER,
+ boundaryPending: false,
+ });
+ expect(fs.existsSync(rejectStaged.stagingPath)).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forgePackStaging.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forgePackStaging.test.ts
index 31b1c31a2c..fb1cc8077c 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forgePackStaging.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forgePackStaging.test.ts
@@ -1,15 +1,20 @@
+import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import type { ActiveAppSession } from '../../appSessionState.js';
import {
+ bindForgePackStagingTempDir,
completeForgePackStaging,
configureForgePackStagingForTests,
createForgePackStagingController,
+ getForgePackStagingController,
resetForgePackStagingForTests,
sha256Hex,
+ sweepStaleForgePackStagingDirs,
+ FORGE_PACK_STAGING_SWEEP_MAX_AGE_MS,
} from '../forgePackStaging.js';
const OWNER_A: ActiveAppSession = {
@@ -112,13 +117,14 @@ describe('createForgePackStagingController', () => {
expect(staging.ticket).not.toMatch(/^\d+$/);
expect(staging.ticket).not.toMatch(/T\d{2}:\d{2}/);
expect(staging.taskDir).toContain(ids[0]);
- expect(issued.peek(staging.ticket)).toEqual({
+ expect(issued.peek(staging.ticket)).toMatchObject({
owner: OWNER_A,
operationKind: 'update',
stagingPath: staging.stagingPath,
packageSha256: sha256Hex(Buffer.from('pkg')),
manifestId: 'acme-tool',
});
+ expect(issued.peek(staging.ticket)?.packExpiresAt).toEqual(expect.any(Number));
});
it('lets peek read the five bound fields from the issuing controller', () => {
@@ -134,13 +140,14 @@ describe('createForgePackStagingController', () => {
owner: OWNER_A,
operationKind: 'update',
});
- expect(issued.peek(staged.ticket)).toEqual({
+ expect(issued.peek(staged.ticket)).toMatchObject({
owner: OWNER_A,
operationKind: 'update',
stagingPath: staged.stagingPath,
packageSha256: sha256Hex(Buffer.from('pkg')),
manifestId: 'acme-tool',
});
+ expect(issued.peek(staged.ticket)?.packExpiresAt).toEqual(expect.any(Number));
});
it('creates an unpredictable 0700 task dir and a 0600 staging file', () => {
@@ -257,6 +264,222 @@ describe('createForgePackStagingController', () => {
fs.writeFileSync(authorCindyPath, Buffer.from('author-copy-C'));
expect(fs.readFileSync(completed.installPath)).toEqual(memoryBytes);
});
+
+ it('sweeps leftover cindy-forge UUID task dirs on restart without following links', () => {
+ const dir = makeTempDir();
+ const leftover = path.join(dir, 'cindy-forge-aaaaaaaa-bbbb-4ccc-9ddd-eeeeeeeeeeee');
+ const keepName = path.join(dir, 'cindy-forge-not-a-uuid');
+ const other = path.join(dir, 'unrelated');
+ fs.mkdirSync(leftover);
+ fs.writeFileSync(path.join(leftover, 'package.cindy'), 'stale');
+ const nowMs = 1_700_000_000_000;
+ const staleMs = nowMs - FORGE_PACK_STAGING_SWEEP_MAX_AGE_MS - 5_000;
+ const lease = path.join(leftover, '.cindy-forge-lease');
+ fs.writeFileSync(lease, `${staleMs}\n`);
+ fs.utimesSync(leftover, staleMs / 1000, staleMs / 1000);
+ fs.utimesSync(lease, staleMs / 1000, staleMs / 1000);
+ fs.mkdirSync(keepName);
+ fs.writeFileSync(path.join(keepName, 'keep.txt'), 'keep');
+ fs.mkdirSync(other);
+ const outside = path.join(dir, 'outside-target');
+ fs.mkdirSync(outside);
+ fs.writeFileSync(path.join(outside, 'sentinel.txt'), 'safe');
+ const linkName = path.join(dir, 'cindy-forge-ffffffff-bbbb-4ccc-9ddd-eeeeeeeeeeee');
+ try {
+ fs.symlinkSync(outside, linkName);
+ } catch {
+ // Platforms that cannot symlink still cover the UUID directory sweep.
+ }
+
+ sweepStaleForgePackStagingDirs(dir, { now: nowMs });
+
+ expect(fs.existsSync(leftover)).toBe(false);
+ expect(fs.existsSync(keepName)).toBe(true);
+ expect(fs.existsSync(other)).toBe(true);
+ expect(fs.readFileSync(path.join(outside, 'sentinel.txt'), 'utf8')).toBe('safe');
+ if (fs.existsSync(linkName)) {
+ expect(fs.lstatSync(linkName).isSymbolicLink()).toBe(true);
+ }
+ });
+
+ it('does not sweep another instance live staging directory that is still within TTL', () => {
+ const dir = makeTempDir();
+ const liveA = controller({
+ getTempDir: () => dir,
+ randomId: (() => {
+ let n = 0;
+ return () =>
+ [
+ 'aaaaaaaa-bbbb-4ccc-9ddd-eeeeeeeeeeee',
+ 'aaaaaaaa-bbbb-4ccc-9ddd-ffffffffffff',
+ ][n++] ?? `extra-${n}`;
+ })(),
+ }).stage({
+ buf: Buffer.from('live-a'),
+ manifestId: 'demo',
+ owner: OWNER_A,
+ operationKind: 'install',
+ });
+ expect(fs.existsSync(liveA.stagingPath)).toBe(true);
+ sweepStaleForgePackStagingDirs(dir);
+ expect(fs.existsSync(liveA.stagingPath)).toBe(true);
+ });
+
+ it('production getController sweep keeps a fresh dir and deletes a >21min leftover', () => {
+ const dir = makeTempDir();
+ const liveA = controller({
+ getTempDir: () => dir,
+ randomId: (() => {
+ let n = 0;
+ return () =>
+ [
+ 'aaaaaaaa-bbbb-4ccc-9ddd-eeeeeeeeeeee',
+ 'aaaaaaaa-bbbb-4ccc-9ddd-ffffffffffff',
+ ][n++] ?? `extra-${n}`;
+ })(),
+ }).stage({
+ buf: Buffer.from('live-a'),
+ manifestId: 'demo',
+ owner: OWNER_A,
+ operationKind: 'install',
+ });
+ const leftover = path.join(dir, 'cindy-forge-cccccccc-bbbb-4ccc-9ddd-eeeeeeeeeeee');
+ fs.mkdirSync(leftover);
+ fs.writeFileSync(path.join(leftover, 'package.cindy'), 'stale');
+ const nowMs = Date.now();
+ const staleMs = nowMs - FORGE_PACK_STAGING_SWEEP_MAX_AGE_MS - 5_000;
+ const lease = path.join(leftover, '.cindy-forge-lease');
+ fs.writeFileSync(lease, '\n');
+ fs.utimesSync(leftover, staleMs / 1000, staleMs / 1000);
+ fs.utimesSync(lease, staleMs / 1000, staleMs / 1000);
+
+ resetForgePackStagingForTests();
+ bindForgePackStagingTempDir(() => dir);
+ getForgePackStagingController();
+
+ expect(fs.existsSync(liveA.stagingPath)).toBe(true);
+ expect(fs.existsSync(leftover)).toBe(false);
+ });
+
+ it('does not renew ticket expiry if the process freezes after pinning expiresAt', () => {
+ const dir = makeTempDir();
+ const t1 = 1_700_000_000_000;
+ const t2 = t1 + 30 * 60 * 1000;
+ let sawLeaseAfterPin = false;
+ const issued = controller({
+ getTempDir: () => dir,
+ // T1 before the one-shot lease exists, T2 after — a freeze between the
+ // pin and tickets.set (or a now() read after the marker) must not mint
+ // a ticket that outlives the marker.
+ now: () => {
+ const taskDir = fs.readdirSync(dir).find((name) => name.startsWith('cindy-forge-'));
+ if (taskDir && fs.existsSync(path.join(dir, taskDir, '.cindy-forge-lease'))) {
+ sawLeaseAfterPin = true;
+ return t2;
+ }
+ return t1;
+ },
+ ttlMs: 10 * 60 * 1000,
+ randomId: (() => {
+ let n = 0;
+ return () => ['task-freeze', 'ticket-freeze'][n++] ?? `extra-${n}`;
+ })(),
+ });
+ const staged = issued.stage({
+ buf: Buffer.from('frozen-mid-stage'),
+ manifestId: 'demo',
+ owner: OWNER_A,
+ operationKind: 'install',
+ });
+ expect(issued.peek(staged.ticket)).toBeNull();
+ expect(sawLeaseAfterPin).toBe(true);
+ });
+
+ it('does not mint a continuation that outlives the pack hard deadline after a freeze', () => {
+ const t1 = 1_700_000_000_000;
+ let clock = t1;
+ const ttlMs = 10 * 60 * 1000;
+ const issued = controller({
+ now: () => clock,
+ ttlMs,
+ randomId: (() => {
+ let n = 0;
+ return () =>
+ ['task-cont-freeze', 'ticket-cont-freeze', 'cont-freeze'][n++] ?? `extra-${n}`;
+ })(),
+ });
+ const staged = issued.stage({
+ buf: Buffer.from('continuation-freeze'),
+ manifestId: 'demo',
+ owner: OWNER_A,
+ operationKind: 'install',
+ });
+ clock = t1 + ttlMs - 1_000;
+ const ticket = issued.consumeMatchingStagingPath(staged.stagingPath);
+ expect(ticket).not.toBeNull();
+ expect(ticket?.packExpiresAt).toBe(t1 + ttlMs);
+ clock = t1 + ttlMs - 1_000 + 30 * 60 * 1000;
+ expect(issued.issueInstallContinuation(ticket!)).toBeNull();
+ expect(fs.existsSync(staged.stagingPath)).toBe(false);
+ });
+
+ it('does not delete staging if the continuation timeout fires before the ticket is registered', () => {
+ const issued = controller({
+ scheduleTimeout: (_ms, callback) => {
+ callback();
+ return { cancel() {} };
+ },
+ randomId: (() => {
+ let n = 0;
+ return () =>
+ ['task-sync-timeout', 'ticket-sync-timeout', 'cont-sync-timeout'][n++] ?? `extra-${n}`;
+ })(),
+ });
+ const staged = issued.stage({
+ buf: Buffer.from('sync-timeout'),
+ manifestId: 'demo',
+ owner: OWNER_A,
+ operationKind: 'install',
+ });
+ const ticket = issued.consumeMatchingStagingPath(staged.stagingPath);
+ expect(ticket).not.toBeNull();
+ const continuation = issued.issueInstallContinuation(ticket!);
+ expect(continuation).toBe('cont-sync-timeout');
+ expect(fs.existsSync(staged.stagingPath)).toBe(true);
+ expect(issued.consumeInstallContinuation(continuation!)).toEqual(ticket);
+ });
+
+ it('writes the one-shot lease marker after hashing, not when the package file is created', () => {
+ const dir = makeTempDir();
+ const originalCreateHash = crypto.createHash;
+ let leaseExistedDuringHash = false;
+ const spy = vi.spyOn(crypto, 'createHash').mockImplementation((algorithm, options) => {
+ const hash = originalCreateHash.call(crypto, algorithm, options);
+ const update = hash.update.bind(hash);
+ hash.update = ((data: crypto.BinaryLike) => {
+ const taskDir = fs.readdirSync(dir).find((name) => name.startsWith('cindy-forge-'));
+ if (taskDir) {
+ leaseExistedDuringHash = fs.existsSync(path.join(dir, taskDir, '.cindy-forge-lease'));
+ }
+ return update(data);
+ }) as typeof hash.update;
+ return hash;
+ });
+ try {
+ const staged = controller({ getTempDir: () => dir }).stage({
+ buf: Buffer.from('hashed-after-write'),
+ manifestId: 'demo',
+ owner: OWNER_A,
+ operationKind: 'install',
+ });
+ expect(leaseExistedDuringHash).toBe(false);
+ const lease = path.join(path.dirname(staged.stagingPath), '.cindy-forge-lease');
+ expect(fs.lstatSync(lease).isFile()).toBe(true);
+ expect(fs.lstatSync(lease).isSymbolicLink()).toBe(false);
+ } finally {
+ spy.mockRestore();
+ }
+ });
});
function cryptoRandom(): string {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts
index e5855a743f..c79714b498 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallReceipt.test.ts
@@ -4,10 +4,11 @@ import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { validateGhostManifest } from '../../../shared/ghost';
+import { validateGhostManifest, type GhostManifest } from '../../../shared/ghost';
import {
createGhostInstallReceipt,
+ effectiveInstallOrigin,
type GhostInstallReceipt,
GhostInstallReceiptStore,
} from '../ghostInstallReceipt';
@@ -298,3 +299,184 @@ describe('GhostInstallReceiptStore cleanup', () => {
expect(fs.existsSync(path.join(parent, 'stale'))).toBe(true);
});
});
+
+describe('GhostInstallReceipt installOrigin', () => {
+ function input(installOrigin?: string) {
+ const manifest: GhostManifest = {
+ schemaVersion: 2,
+ id: 'hello',
+ name: 'Hello',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['tool'],
+ tools: [{ name: 'do_thing', description: 'Do something' }],
+ };
+ return {
+ manifest,
+ localeResources: {},
+ enabled: true,
+ trust: {
+ level: 'unverified' as const,
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: false,
+ },
+ skillContentSha256: {},
+ ...(installOrigin !== undefined ? { installOrigin } : {}),
+ };
+ }
+
+ it('treats a v2 receipt without installOrigin as approved manual', () => {
+ const receipt = createGhostInstallReceipt(input());
+ expect(receipt.schemaVersion).toBe(2);
+ expect(receipt.installOrigin).toBeUndefined();
+ expect(effectiveInstallOrigin(receipt)).toBe('manual');
+ expect(JSON.stringify(receipt)).not.toContain('installOrigin');
+ });
+
+ it('keeps an unknown bounded origin and does not use it for authorization', () => {
+ const receipt = createGhostInstallReceipt(input('future-origin'));
+ expect(receipt.installOrigin).toBe('future-origin');
+ expect(effectiveInstallOrigin(receipt)).toBe('manual');
+ const rewritten = createGhostInstallReceipt({
+ ...input(),
+ enabled: false,
+ installOrigin: receipt.installOrigin,
+ });
+ expect(rewritten.installOrigin).toBe('future-origin');
+ expect(rewritten.enabled).toBe(false);
+ expect(effectiveInstallOrigin(rewritten)).toBe('manual');
+ });
+
+ it('writes this-operation origin instead of inheriting the previous receipt', () => {
+ expect(createGhostInstallReceipt(input('manual')).installOrigin).toBe('manual');
+ expect(createGhostInstallReceipt(input('agent-forge')).installOrigin).toBe('agent-forge');
+ expect(createGhostInstallReceipt(input()).installOrigin).toBeUndefined();
+ expect(effectiveInstallOrigin(createGhostInstallReceipt(input()))).toBe('manual');
+ });
+
+ it('reads a v2 disk receipt without installOrigin as approved manual', async () => {
+ const workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-receipt-origin-'));
+ try {
+ const rawState = path.join(workDir, 'state');
+ await fs.promises.mkdir(rawState);
+ const stateRoot = await fs.promises.realpath(rawState);
+ const store = new GhostInstallReceiptStore(() => stateRoot, async ({ parentDir, targetName, operation }) => {
+ if (operation === 'remove') {
+ await fs.promises.rm(path.join(parentDir, targetName), { recursive: true, force: true });
+ }
+ });
+ const legacyV2 = {
+ schemaVersion: 2,
+ id: 'hello',
+ revision: '00000000-0000-4000-8000-000000000001',
+ manifest: {
+ schemaVersion: 2,
+ id: 'hello',
+ name: 'Hello',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['tool'],
+ tools: [{ name: 'do_thing', description: 'Do something' }],
+ },
+ localeResources: {},
+ enabled: true,
+ trust: {
+ level: 'unverified',
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: false,
+ },
+ skillContentSha256: {},
+ };
+ expect(JSON.stringify(legacyV2)).not.toContain('installOrigin');
+ await fs.promises.writeFile(
+ path.join(stateRoot, 'hello.json'),
+ `${JSON.stringify(legacyV2, null, 2)}\n`,
+ 'utf8',
+ );
+ const read = store.read('hello');
+ expect(read.state).toBe('approved');
+ if (read.state !== 'approved') return;
+ expect(read.receipt.schemaVersion).toBe(2);
+ expect(read.receipt.installOrigin).toBeUndefined();
+ expect(effectiveInstallOrigin(read.receipt)).toBe('manual');
+
+ await store.write(createGhostInstallReceipt(input('agent-forge')));
+ const written = store.read('hello');
+ expect(written.state).toBe('approved');
+ if (written.state !== 'approved') return;
+ expect(written.receipt.installOrigin).toBe('agent-forge');
+ } finally {
+ await fs.promises.rm(workDir, { recursive: true, force: true });
+ }
+ });
+
+ it('rejects writer values the parser would not read back', () => {
+ expect(() => createGhostInstallReceipt(input(''))).toThrow('installOrigin');
+ expect(() => createGhostInstallReceipt(input('x'.repeat(65)))).toThrow('installOrigin');
+ expect(() => createGhostInstallReceipt(input('Bad_Origin'))).toThrow('installOrigin');
+ expect(createGhostInstallReceipt(input('future-origin')).installOrigin).toBe('future-origin');
+ });
+
+ it('reads unknown-but-bounded origins as approved manual and malformed origins as invalid', async () => {
+ const workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-receipt-origin-parse-'));
+ try {
+ const rawState = path.join(workDir, 'state');
+ await fs.promises.mkdir(rawState);
+ const stateRoot = await fs.promises.realpath(rawState);
+ const store = new GhostInstallReceiptStore(() => stateRoot, async ({ parentDir, targetName, operation }) => {
+ if (operation === 'remove') {
+ await fs.promises.rm(path.join(parentDir, targetName), { recursive: true, force: true });
+ }
+ });
+ const base = {
+ schemaVersion: 2,
+ id: 'hello',
+ revision: '00000000-0000-4000-8000-000000000001',
+ manifest: {
+ schemaVersion: 2,
+ id: 'hello',
+ name: 'Hello',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['tool'],
+ tools: [{ name: 'do_thing', description: 'Do something' }],
+ },
+ localeResources: {},
+ enabled: true,
+ trust: {
+ level: 'unverified',
+ publisherSigned: false,
+ publisherVerified: false,
+ reviewed: false,
+ },
+ skillContentSha256: {},
+ };
+ await fs.promises.writeFile(
+ path.join(stateRoot, 'hello.json'),
+ `${JSON.stringify({ ...base, installOrigin: 'future-origin' }, null, 2)}\n`,
+ 'utf8',
+ );
+ const unknown = store.read('hello');
+ expect(unknown.state).toBe('approved');
+ if (unknown.state !== 'approved') return;
+ expect(unknown.receipt.installOrigin).toBe('future-origin');
+ expect(effectiveInstallOrigin(unknown.receipt)).toBe('manual');
+
+ for (const installOrigin of [{ kind: 'agent-forge' }, '', 'x'.repeat(65), 'Bad Origin']) {
+ await fs.promises.writeFile(
+ path.join(stateRoot, 'hello.json'),
+ `${JSON.stringify({ ...base, installOrigin }, null, 2)}\n`,
+ 'utf8',
+ );
+ expect(store.read('hello').state, String(installOrigin)).toBe('invalid');
+ }
+ } finally {
+ await fs.promises.rm(workDir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
index 79d7acd7f3..c6b6c9dc4d 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
@@ -189,6 +189,10 @@ describe('market Ghost session boundary', () => {
// stopAndWait (rollback if provenance check fails).
expect(restoreIndex).toBeGreaterThan(waitIndex);
expect(body).toContain('finally {\n releaseMutation();');
+ const leaseReleaseIndex = body.indexOf('finally {\n releaseMutation();');
+ const stagingReleaseIndex = body.indexOf('releaseForgePackStaging(');
+ expect(leaseReleaseIndex).toBeGreaterThan(-1);
+ expect(stagingReleaseIndex).toBeGreaterThan(leaseReleaseIndex);
expect(body).toContain("throwIpcError('INTERNAL', 'Unable to verify the installed Plugin source');");
expect(body).toContain("throwIpcError('INTERNAL', 'Unable to detach the installed Plugin source');");
});
diff --git a/apps/desktop/src/main/cindy-brain/forgePackConsume.ts b/apps/desktop/src/main/cindy-brain/forgePackConsume.ts
new file mode 100644
index 0000000000..0904a53c9e
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/forgePackConsume.ts
@@ -0,0 +1,103 @@
+/**
+ * Consume a forge-pack integrity ticket at inspect / install.
+ *
+ * Pack tickets are one-shot: the first inspect attempt consumes them.
+ * A matching hash + manifest.id issues an install continuation; mismatch
+ * deletes staging immediately. Renderer only ever sees the continuation
+ * token — never origin. No ticket ⇒ receipt origin is `manual`.
+ *
+ * `operationKind` on the pack ticket is a hint, not a reject condition.
+ * Real install-vs-update classification happens after the install lock.
+ */
+import type { ActiveAppSession } from '../appSessionState.js';
+import type { ForgePackIntegrityTicket, ForgePackStagingController } from './forgePackStaging.js';
+
+export type ForgePackInspectConsume =
+ | { kind: 'not-forge' }
+ | { kind: 'accepted'; packTicket: string }
+ | { kind: 'rejected'; reason: string };
+
+export type ForgePackInstallConsume =
+ | { kind: 'manual' }
+ | { kind: 'agent-forge'; ticket: ForgePackIntegrityTicket }
+ | { kind: 'rejected'; reason: string };
+
+function sameOwner(a: ActiveAppSession, b: ActiveAppSession): boolean {
+ return a.mode === b.mode && a.dataOwnerId === b.dataOwnerId && a.generation === b.generation;
+}
+
+export function consumeForgePackAtInspect(
+ controller: ForgePackStagingController,
+ input: {
+ filePath: string;
+ packageSha256: string;
+ manifestId: string;
+ currentOwner: ActiveAppSession;
+ boundaryPending: boolean;
+ },
+): ForgePackInspectConsume {
+ if (input.boundaryPending) {
+ // Short account-switch window: do not consume the pack ticket. The user
+ // can retry inspect on the same staging file after the owner is stable.
+ const existing = controller.peekMatchingStagingPath(input.filePath);
+ if (!existing && !controller.wasStagingPathConsumed(input.filePath)) {
+ return { kind: 'not-forge' };
+ }
+ return { kind: 'rejected', reason: 'session-boundary-pending' };
+ }
+ if (controller.wasStagingPathConsumed(input.filePath)) {
+ return { kind: 'rejected', reason: 'ticket-replay' };
+ }
+ const ticket = controller.consumeMatchingStagingPath(input.filePath);
+ if (!ticket) return { kind: 'not-forge' };
+ if (!sameOwner(ticket.owner, input.currentOwner)) {
+ controller.releaseStaging(ticket.stagingPath);
+ return { kind: 'rejected', reason: 'owner-mismatch' };
+ }
+ if (ticket.packageSha256 !== input.packageSha256 || ticket.manifestId !== input.manifestId) {
+ controller.releaseStaging(ticket.stagingPath);
+ return { kind: 'rejected', reason: 'ticket-binding-mismatch' };
+ }
+ const packTicket = controller.issueInstallContinuation(ticket);
+ if (!packTicket) {
+ return { kind: 'rejected', reason: 'ticket-expired' };
+ }
+ return { kind: 'accepted', packTicket };
+}
+
+export function consumeForgePackAtInstall(
+ controller: ForgePackStagingController,
+ input: {
+ packTicket: string | undefined;
+ packageSha256: string;
+ manifestId: string;
+ currentOwner: ActiveAppSession;
+ boundaryPending: boolean;
+ },
+): ForgePackInstallConsume {
+ if (!input.packTicket) return { kind: 'manual' };
+ if (input.boundaryPending) {
+ // Caller should only reach here without a stable mutation lease. Do not
+ // consume the continuation — the same owner can retry after the window.
+ return { kind: 'rejected', reason: 'session-boundary-pending' };
+ }
+ const ticket = controller.consumeInstallContinuation(input.packTicket);
+ if (!ticket) return { kind: 'rejected', reason: 'ticket-replay' };
+ if (!sameOwner(ticket.owner, input.currentOwner)) {
+ controller.releaseStaging(ticket.stagingPath);
+ return { kind: 'rejected', reason: 'owner-mismatch' };
+ }
+ if (ticket.packageSha256 !== input.packageSha256 || ticket.manifestId !== input.manifestId) {
+ controller.releaseStaging(ticket.stagingPath);
+ return { kind: 'rejected', reason: 'ticket-binding-mismatch' };
+ }
+ return { kind: 'agent-forge', ticket };
+}
+
+export function abandonForgePackInstall(
+ controller: ForgePackStagingController,
+ packTicket: string,
+): void {
+ const ticket = controller.consumeInstallContinuation(packTicket);
+ if (ticket) controller.releaseStaging(ticket.stagingPath);
+}
diff --git a/apps/desktop/src/main/cindy-brain/forgePackStaging.ts b/apps/desktop/src/main/cindy-brain/forgePackStaging.ts
index 3e0da57472..464b096d06 100644
--- a/apps/desktop/src/main/cindy-brain/forgePackStaging.ts
+++ b/apps/desktop/src/main/cindy-brain/forgePackStaging.ts
@@ -15,6 +15,15 @@ import path from 'node:path';
import type { ActiveAppSession } from '../appSessionState.js';
export const FORGE_PACK_TICKET_TTL_MS = 10 * 60 * 1000;
+/** Extra grace so a long confirm wait plus clock skew is not swept as stale. */
+export const FORGE_PACK_STAGING_SWEEP_GRACE_MS = 60 * 1000;
+/**
+ * Cross-instance sweep threshold: pack TTL + continuation TTL + grace.
+ * Another Cindy process sharing OS temp must not delete a live confirm wait.
+ */
+export const FORGE_PACK_STAGING_SWEEP_MAX_AGE_MS =
+ FORGE_PACK_TICKET_TTL_MS + FORGE_PACK_TICKET_TTL_MS + FORGE_PACK_STAGING_SWEEP_GRACE_MS;
+const FORGE_PACK_LEASE_MARKER = '.cindy-forge-lease';
export type ForgePackOperationKind = 'install' | 'update';
@@ -34,6 +43,12 @@ export interface ForgePackIntegrityTicket {
stagingPath: string;
packageSha256: string;
manifestId: string;
+ /**
+ * Wall-clock pack expiry pinned before the lease marker. Continuation must
+ * inherit `packExpiresAt + ttl` as a hard cap and must not re-base from
+ * issue-time `now()`.
+ */
+ packExpiresAt: number;
}
export interface StageBuiltGhostPackageInput {
@@ -52,9 +67,25 @@ export interface StageBuiltGhostPackageResult {
export interface ForgePackStagingController {
stage(input: StageBuiltGhostPackageInput): StageBuiltGhostPackageResult;
- /** Look up without consuming. Consumption is ⑥a-2. */
peek(token: string): ForgePackIntegrityTicket | null;
+ /**
+ * Atomically take the ticket out of the map. Staging files stay until
+ * `invalidate` / `releaseStaging` — inspect consumes so the pack ticket
+ * cannot be replayed, but install still needs the bytes.
+ */
+ consume(token: string): ForgePackIntegrityTicket | null;
+ consumeMatchingStagingPath(stagingPath: string): ForgePackIntegrityTicket | null;
+ peekMatchingStagingPath(stagingPath: string): ForgePackIntegrityTicket | null;
+ wasStagingPathConsumed(stagingPath: string): boolean;
+ /**
+ * After inspect consumes the pack ticket, issue a one-shot install continuation.
+ * Returns null (and deletes staging) when `now()` is already past the inherited
+ * hard deadline — never mint a ticket younger than the lease marker.
+ */
+ issueInstallContinuation(ticket: ForgePackIntegrityTicket): string | null;
+ consumeInstallContinuation(token: string): ForgePackIntegrityTicket | null;
invalidate(token: string): boolean;
+ releaseStaging(stagingPath: string): void;
invalidateMismatchedOwners(current: ActiveAppSession): void;
invalidateAll(): void;
}
@@ -131,6 +162,98 @@ function rmTaskDir(taskDir: string): void {
fs.rmSync(taskDir, { recursive: true, force: true });
}
+function tryRmTaskDir(taskDir: string): void {
+ try {
+ rmTaskDir(taskDir);
+ } catch {
+ // Best-effort maintenance: a locked leftover must not fail controller init.
+ }
+}
+
+const FORGE_TASK_DIR_RE =
+ /^cindy-forge-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
+
+function leaseMarkerPath(taskDir: string): string {
+ return path.join(taskDir, FORGE_PACK_LEASE_MARKER);
+}
+
+/**
+ * One-shot lease file: exclusive create, never rewritten. mtime is the sweep
+ * clock. Must be written after the package bytes and hash are done, and after
+ * `expiresAt` is pinned, immediately before the ticket is registered.
+ */
+function writeExclusiveLeaseMarker(taskDir: string): void {
+ writeExclusiveNoFollow(leaseMarkerPath(taskDir), Buffer.from('\n'), taskDir);
+}
+
+function forgePackLeaseAgeMs(taskDir: string, nowMs: number): number | null {
+ const marker = leaseMarkerPath(taskDir);
+ try {
+ const stat = fs.lstatSync(marker);
+ if (stat.isSymbolicLink() || !stat.isFile()) return null;
+ return Math.max(0, nowMs - Number(stat.mtimeMs));
+ } catch {
+ // No marker means there is no consumable ticket yet. Sweeping such a dir
+ // can at worst fail an in-flight pack (including one frozen long enough
+ // that directory mtime exceeds the threshold); it cannot revive or
+ // invalidate an already-issued ticket.
+ try {
+ const dirStat = fs.lstatSync(taskDir);
+ if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) return null;
+ return Math.max(0, nowMs - Number(dirStat.mtimeMs));
+ } catch {
+ return null;
+ }
+ }
+}
+
+/**
+ * Restart / crash recovery: drop leftover Host staging dirs under tempRoot.
+ * Only enumerates direct children that match `cindy-forge-<v4 UUID>`. Symlinks
+ * and non-directories are skipped; real parent must still be tempRoot.
+ * Only dirs older than pack TTL + continuation TTL + grace are removed, so a
+ * sibling Cindy process waiting on confirm is not deleted.
+ */
+export function sweepStaleForgePackStagingDirs(
+ tempRoot: string,
+ options?: { now?: number; maxAgeMs?: number },
+): void {
+ const nowMs = options?.now ?? Date.now();
+ const maxAgeMs = options?.maxAgeMs ?? FORGE_PACK_STAGING_SWEEP_MAX_AGE_MS;
+ let realTempRoot: string;
+ try {
+ realTempRoot = fs.realpathSync.native(tempRoot);
+ } catch {
+ return;
+ }
+ let entries: string[];
+ try {
+ entries = fs.readdirSync(realTempRoot);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
+ throw error;
+ }
+ for (const name of entries) {
+ if (!FORGE_TASK_DIR_RE.test(name)) continue;
+ const taskDir = path.join(realTempRoot, name);
+ let stat: fs.Stats;
+ try {
+ stat = fs.lstatSync(taskDir);
+ } catch {
+ continue;
+ }
+ if (stat.isSymbolicLink() || !stat.isDirectory()) continue;
+ try {
+ assertManagedDirectory(taskDir, realTempRoot);
+ } catch {
+ continue;
+ }
+ const ageMs = forgePackLeaseAgeMs(taskDir, nowMs);
+ if (ageMs === null || ageMs < maxAgeMs) continue;
+ tryRmTaskDir(taskDir);
+ }
+}
+
export function createForgePackStagingController(
options: CreateForgePackStagingControllerOptions,
): ForgePackStagingController {
@@ -150,13 +273,22 @@ export function createForgePackStagingController(
timeout: { cancel(): void };
};
const tickets = new Map<string, Entry>();
+ const installContinuations = new Map<string, Entry>();
+ const consumedStagingPaths = new Set<string>();
+
+ const forgetConsumedPath = (stagingPath: string): void => {
+ consumedStagingPaths.delete(path.resolve(stagingPath));
+ };
const drop = (token: string, removeFiles: boolean): boolean => {
const entry = tickets.get(token);
if (!entry) return false;
tickets.delete(token);
entry.timeout.cancel();
- if (removeFiles) rmTaskDir(path.dirname(entry.ticket.stagingPath));
+ if (removeFiles) {
+ forgetConsumedPath(entry.ticket.stagingPath);
+ rmTaskDir(path.dirname(entry.ticket.stagingPath));
+ }
return true;
};
@@ -180,6 +312,12 @@ export function createForgePackStagingController(
}
const token = randomId();
const packageSha256 = sha256Hex(input.buf);
+ const timeout = scheduleTimeout(ttlMs, () => {
+ drop(token, true);
+ });
+ // Pin expiry before the lease mtime exists. A freeze between the marker
+ // write and Map insert must not mint a ticket younger than the marker.
+ const expiresAt = now() + ttlMs;
const ticket: ForgePackIntegrityTicket = {
owner: {
mode: input.owner.mode,
@@ -190,11 +328,16 @@ export function createForgePackStagingController(
stagingPath,
packageSha256,
manifestId: input.manifestId,
+ packExpiresAt: expiresAt,
};
- const timeout = scheduleTimeout(ttlMs, () => {
- drop(token, true);
- });
- tickets.set(token, { ticket, expiresAt: now() + ttlMs, timeout });
+ try {
+ writeExclusiveLeaseMarker(taskDir);
+ } catch (error) {
+ timeout.cancel();
+ rmTaskDir(taskDir);
+ throw error;
+ }
+ tickets.set(token, { ticket, expiresAt, timeout });
return { ticket: token, stagingPath, taskDir, packageSha256 };
},
@@ -208,18 +351,128 @@ export function createForgePackStagingController(
return entry.ticket;
},
+ consume(token) {
+ const entry = tickets.get(token);
+ if (!entry) return null;
+ tickets.delete(token);
+ entry.timeout.cancel();
+ if (entry.expiresAt <= now()) {
+ rmTaskDir(path.dirname(entry.ticket.stagingPath));
+ return null;
+ }
+ return entry.ticket;
+ },
+
+ consumeMatchingStagingPath(stagingPath) {
+ const target = path.resolve(stagingPath);
+ for (const [token, entry] of tickets) {
+ if (path.resolve(entry.ticket.stagingPath) === target) {
+ tickets.delete(token);
+ entry.timeout.cancel();
+ consumedStagingPaths.add(target);
+ if (entry.expiresAt <= now()) {
+ consumedStagingPaths.delete(target);
+ rmTaskDir(path.dirname(entry.ticket.stagingPath));
+ return null;
+ }
+ return entry.ticket;
+ }
+ }
+ return null;
+ },
+
+ peekMatchingStagingPath(stagingPath) {
+ const target = path.resolve(stagingPath);
+ for (const [token, entry] of tickets) {
+ if (path.resolve(entry.ticket.stagingPath) !== target) continue;
+ if (entry.expiresAt <= now()) {
+ drop(token, true);
+ return null;
+ }
+ return entry.ticket;
+ }
+ return null;
+ },
+
+ wasStagingPathConsumed(stagingPath) {
+ return consumedStagingPaths.has(path.resolve(stagingPath));
+ },
+
+ issueInstallContinuation(ticket) {
+ const issueNow = now();
+ const hardDeadline = ticket.packExpiresAt + ttlMs;
+ if (issueNow >= hardDeadline) {
+ forgetConsumedPath(ticket.stagingPath);
+ rmTaskDir(path.dirname(ticket.stagingPath));
+ return null;
+ }
+ const expiresAt = Math.min(issueNow + ttlMs, hardDeadline);
+ const token = randomId();
+ const timeout = scheduleTimeout(Math.max(0, expiresAt - issueNow), () => {
+ const entry = installContinuations.get(token);
+ if (!entry) return;
+ installContinuations.delete(token);
+ entry.timeout.cancel();
+ forgetConsumedPath(ticket.stagingPath);
+ rmTaskDir(path.dirname(ticket.stagingPath));
+ });
+ installContinuations.set(token, { ticket, expiresAt, timeout });
+ return token;
+ },
+
+ consumeInstallContinuation(token) {
+ const entry = installContinuations.get(token);
+ if (!entry) return null;
+ installContinuations.delete(token);
+ entry.timeout.cancel();
+ if (entry.expiresAt <= now()) {
+ forgetConsumedPath(entry.ticket.stagingPath);
+ rmTaskDir(path.dirname(entry.ticket.stagingPath));
+ return null;
+ }
+ return entry.ticket;
+ },
+
invalidate(token) {
+ const continuation = installContinuations.get(token);
+ if (continuation) {
+ installContinuations.delete(token);
+ continuation.timeout.cancel();
+ forgetConsumedPath(continuation.ticket.stagingPath);
+ rmTaskDir(path.dirname(continuation.ticket.stagingPath));
+ return true;
+ }
return drop(token, true);
},
+ releaseStaging(stagingPath) {
+ forgetConsumedPath(stagingPath);
+ rmTaskDir(path.dirname(stagingPath));
+ },
+
invalidateMismatchedOwners(current) {
for (const [token, entry] of [...tickets]) {
if (!isSameOwner(entry.ticket.owner, current)) drop(token, true);
}
+ for (const [token, entry] of [...installContinuations]) {
+ if (!isSameOwner(entry.ticket.owner, current)) {
+ installContinuations.delete(token);
+ entry.timeout.cancel();
+ forgetConsumedPath(entry.ticket.stagingPath);
+ rmTaskDir(path.dirname(entry.ticket.stagingPath));
+ }
+ }
},
invalidateAll() {
for (const token of [...tickets.keys()]) drop(token, true);
+ for (const [token, entry] of [...installContinuations]) {
+ installContinuations.delete(token);
+ entry.timeout.cancel();
+ forgetConsumedPath(entry.ticket.stagingPath);
+ rmTaskDir(path.dirname(entry.ticket.stagingPath));
+ }
+ consumedStagingPaths.clear();
},
};
}
@@ -247,13 +500,24 @@ export function bindForgePackStagingTempDir(getTempDir: () => string): void {
getProductionTempDir = getTempDir;
}
+export function getForgePackStagingController(): ForgePackStagingController {
+ return getController();
+}
+
+export function getForgePackStagingControllerIfConfigured(): ForgePackStagingController | null {
+ if (!productionController && !getProductionTempDir) return null;
+ return getController();
+}
+
function getController(): ForgePackStagingController {
if (!productionController) {
if (!getProductionTempDir) {
throw new Error('Forge pack staging temp dir is not configured');
}
+ const getTempDir = getProductionTempDir;
+ sweepStaleForgePackStagingDirs(getTempDir());
productionController = createForgePackStagingController({
- getTempDir: getProductionTempDir,
+ getTempDir,
});
}
return productionController;
@@ -300,10 +564,36 @@ export function peekForgePackTicket(token: string): ForgePackIntegrityTicket | n
return getController().peek(token);
}
+export function consumeForgePackTicket(token: string): ForgePackIntegrityTicket | null {
+ return getController().consume(token);
+}
+
+export function consumeForgePackTicketForStagingPath(
+ stagingPath: string,
+): ForgePackIntegrityTicket | null {
+ return getController().consumeMatchingStagingPath(stagingPath);
+}
+
+export function issueForgePackInstallContinuation(
+ ticket: ForgePackIntegrityTicket,
+): string | null {
+ return getController().issueInstallContinuation(ticket);
+}
+
+export function consumeForgePackInstallContinuation(
+ token: string,
+): ForgePackIntegrityTicket | null {
+ return getController().consumeInstallContinuation(token);
+}
+
export function invalidateForgePackTicket(token: string): boolean {
return productionController?.invalidate(token) ?? false;
}
+export function releaseForgePackStaging(stagingPath: string): void {
+ productionController?.releaseStaging(stagingPath);
+}
+
export function invalidateForgePackTicketsForOwner(current: ActiveAppSession): void {
productionController?.invalidateMismatchedOwners(current);
}
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
index 2dcefd9dc6..64c1c253bd 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
@@ -64,6 +64,12 @@ export interface GhostInstallReceipt {
* 随包种子是内容目录哈希。**运行时不校验它**,不要据此认为安装内容持续完整。
*/
packageSha256?: string;
+ /**
+ * 本次装入/更新操作的来源。可选;缺失按 `manual` 读。
+ * 不要改成必填、不要升 schemaVersion、不要批量重写旧 receipt。
+ * 未知值只在授权判断时降级为 manual,不写回磁盘。
+ */
+ installOrigin?: string;
/**
* 按 skill item 目录钉住的批准字节指纹(`item.dir` → sha256)。声明了 skill 槽
* 时逐项必填,没声明时是空对象。
@@ -1020,7 +1026,11 @@ export function createGhostInstallReceipt(input: {
packageSha256?: string;
revision?: string;
iconDataUrl?: string;
+ installOrigin?: string;
}): GhostInstallReceipt {
+ if (input.installOrigin !== undefined && !isPersistableInstallOrigin(input.installOrigin)) {
+ throw new Error('receipt installOrigin 不合法');
+ }
return {
schemaVersion: RECEIPT_SCHEMA_VERSION,
id: input.manifest.id,
@@ -1032,9 +1042,28 @@ export function createGhostInstallReceipt(input: {
skillContentSha256: input.skillContentSha256,
...(input.packageSha256 ? { packageSha256: input.packageSha256 } : {}),
...(input.iconDataUrl ? { iconDataUrl: input.iconDataUrl } : {}),
+ ...(input.installOrigin !== undefined ? { installOrigin: input.installOrigin } : {}),
};
}
+const MAX_INSTALL_ORIGIN_CHARS = 64;
+const INSTALL_ORIGIN_PATTERN = /^[a-z0-9-]+$/;
+
+function isPersistableInstallOrigin(value: string): boolean {
+ return (
+ value.length > 0 &&
+ value.length <= MAX_INSTALL_ORIGIN_CHARS &&
+ INSTALL_ORIGIN_PATTERN.test(value)
+ );
+}
+
+/** Authorization-time view: missing or unknown → manual. Never write this back. */
+export function effectiveInstallOrigin(
+ receipt: Pick<GhostInstallReceipt, 'installOrigin'>,
+): 'manual' | 'agent-forge' {
+ return receipt.installOrigin === 'agent-forge' ? 'agent-forge' : 'manual';
+}
+
/**
* 逐 skill item 目录算规范化内容指纹(排序后的相对路径 + 字节)。
*
@@ -1164,6 +1193,16 @@ function validateReceipt(
if (!validated.ok) return { ok: false, reason: `receipt locale 不合法:${localePath}` };
localeResources[localePath] = validated.resource;
}
+ let installOrigin: string | undefined;
+ if (value.installOrigin !== undefined) {
+ if (typeof value.installOrigin !== 'string') {
+ return { ok: false, reason: 'receipt installOrigin 不合法' };
+ }
+ if (!isPersistableInstallOrigin(value.installOrigin)) {
+ return { ok: false, reason: 'receipt installOrigin 不合法' };
+ }
+ installOrigin = value.installOrigin;
+ }
return {
ok: true,
receipt: {
@@ -1177,6 +1216,7 @@ function validateReceipt(
skillContentSha256,
...(typeof value.packageSha256 === 'string' ? { packageSha256: value.packageSha256 } : {}),
...(typeof value.iconDataUrl === 'string' ? { iconDataUrl: value.iconDataUrl } : {}),
+ ...(installOrigin !== undefined ? { installOrigin } : {}),
},
};
}
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 566143ad14..60120d45a9 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -82,8 +82,15 @@ import { GhostMutationCoordinator } from './ghostMutationCoordinator.js';
import { createOneShotTicketStore } from './oneShotTickets.js';
import {
bindForgePackStagingTempDir,
+ getForgePackStagingControllerIfConfigured,
invalidateForgePackTicketsForOwner,
+ releaseForgePackStaging,
} from './forgePackStaging.js';
+import {
+ abandonForgePackInstall,
+ consumeForgePackAtInspect,
+ consumeForgePackAtInstall,
+} from './forgePackConsume.js';
import { withGhostInstallLock } from './ghostInstallLock.js';
import {
GhostPackagePermissionReviewRequiredError,
@@ -5283,6 +5290,7 @@ export async function installAndDock(
enable?: boolean;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
+ installOrigin?: string;
},
): Promise<InstalledGhost> {
return withGhostInstallLock(opts.ghostId, () => installAndDockLocked(manager, lizFilePath, opts));
@@ -5296,6 +5304,7 @@ async function installAndDockLocked(
enable?: boolean;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
+ installOrigin?: string;
},
): Promise<InstalledGhost> {
// 默认沉睡(2026-07-09 Lizi 定案):装入 ≠ 授权运行,用户在确认框显式勾选
@@ -5306,6 +5315,7 @@ async function installAndDockLocked(
? { expectedPackageSha256: opts.expectedPackageSha256 }
: {}),
...(opts.trustOverride ? { trustOverride: opts.trustOverride } : {}),
+ ...(opts.installOrigin !== undefined ? { installOrigin: opts.installOrigin } : {}),
});
if ('rejection' in result) throwInstallError(result.rejection);
// 纵深防御:调用方给错 id 意味着刚才那把锁上在了错误的键上(等于没上锁)。
@@ -6868,8 +6878,13 @@ export function registerGhostIpc(): void {
if (typeof lizFilePath !== 'string' || lizFilePath.trim().length === 0) {
throwIpcError('INVALID_PARAMS', 'lizFilePath must be a non-empty string');
}
- const installOpts = opts as { enable?: unknown; expectedPackageSha256?: unknown } | undefined;
+ const installOpts = opts as {
+ enable?: unknown;
+ expectedPackageSha256?: unknown;
+ packTicket?: unknown;
+ } | undefined;
const expectedPackageSha256 = installOpts?.expectedPackageSha256;
+ const packTicket = typeof installOpts?.packTicket === 'string' ? installOpts.packTicket : undefined;
if (
typeof expectedPackageSha256 !== 'string' ||
!/^[a-f0-9]{64}$/.test(expectedPackageSha256)
@@ -6890,16 +6905,45 @@ export function registerGhostIpc(): void {
// owner 租约在锁外整段持有(防中途 owner 切换把落位写进新 owner);按 ghostId 的
// 互斥锁由 installAndDock 自动获取(卡点),这里传 id 即可。二者语义不同,叠加保留。
const releaseMutation = beginGhostMutation(mutationOwner);
+ let forgeInstall: ReturnType<typeof consumeForgePackAtInstall> = { kind: 'manual' };
try {
+ const forgeController = getForgePackStagingControllerIfConfigured();
+ if (packTicket && !forgeController) {
+ throwIpcError('GHOST_FILE_INVALID', '插件打包凭证已失效,请重新打包并确认');
+ }
+ forgeInstall = forgeController
+ ? consumeForgePackAtInstall(forgeController, {
+ packTicket,
+ packageSha256: probe.packageSha256,
+ manifestId: probe.manifest.id,
+ currentOwner: mutationOwner,
+ boundaryPending: isAppSessionBoundaryPending(),
+ })
+ : ({ kind: 'manual' } as const);
+ if (forgeInstall.kind === 'rejected') {
+ if (forgeInstall.reason === 'session-boundary-pending') {
+ throwIpcError('PRECONDITION_FAILED', '账号切换中,请稍后再试');
+ }
+ throwIpcError('GHOST_FILE_INVALID', '插件打包凭证已失效,请重新打包并确认');
+ }
+ const installOrigin = forgeInstall.kind === 'agent-forge' ? 'agent-forge' : 'manual';
return {
ghost: await installAndDock(manager, lizFilePath, {
ghostId: probe.manifest.id,
enable,
expectedPackageSha256,
+ installOrigin,
}),
};
} finally {
releaseMutation();
+ if (forgeInstall.kind === 'agent-forge') {
+ try {
+ releaseForgePackStaging(forgeInstall.ticket.stagingPath);
+ } catch {
+ // Staging cleanup must not leak the owner mutation lease.
+ }
+ }
}
});
@@ -6917,10 +6961,12 @@ export function registerGhostIpc(): void {
| {
expectedPackageSha256?: unknown;
expectedInstalledApproval?: unknown;
+ packTicket?: unknown;
}
| undefined;
const expectedPackageSha256 = updateOptions?.expectedPackageSha256;
const expectedInstalledApproval = updateOptions?.expectedInstalledApproval;
+ const packTicket = typeof updateOptions?.packTicket === 'string' ? updateOptions.packTicket : undefined;
if (
typeof expectedPackageSha256 !== 'string' ||
!/^[a-f0-9]{64}$/.test(expectedPackageSha256)
@@ -6949,7 +6995,28 @@ export function registerGhostIpc(): void {
// 与市场/本地装入/卸载共用的按 ghostId 互斥叠加(二者语义不同,决策 A 都保留)。
// 锁序不变量(违反即死锁):owner lease → per-id lock。
const releaseMutation = beginGhostMutation(mutationOwner);
+ let forgeUpdate: ReturnType<typeof consumeForgePackAtInstall> = { kind: 'manual' };
try {
+ const forgeUpdateController = getForgePackStagingControllerIfConfigured();
+ if (packTicket && !forgeUpdateController) {
+ throwIpcError('GHOST_FILE_INVALID', '插件打包凭证已失效,请重新打包并确认');
+ }
+ forgeUpdate = forgeUpdateController
+ ? consumeForgePackAtInstall(forgeUpdateController, {
+ packTicket,
+ packageSha256: inspected.packageSha256,
+ manifestId: inspected.manifest.id,
+ currentOwner: mutationOwner,
+ boundaryPending: isAppSessionBoundaryPending(),
+ })
+ : ({ kind: 'manual' } as const);
+ if (forgeUpdate.kind === 'rejected') {
+ if (forgeUpdate.reason === 'session-boundary-pending') {
+ throwIpcError('PRECONDITION_FAILED', '账号切换中,请稍后再试');
+ }
+ throwIpcError('GHOST_FILE_INVALID', '插件打包凭证已失效,请重新打包并确认');
+ }
+ const updateOrigin = forgeUpdate.kind === 'agent-forge' ? 'agent-forge' : 'manual';
return await withGhostInstallLock(inspected.manifest.id, async () => {
const previousGhost = manager.list().find((g) => g.manifest.id === inspected.manifest.id);
runtime.stop(inspected.manifest.id);
@@ -7030,6 +7097,7 @@ export function registerGhostIpc(): void {
manager.update(lizFilePath, {
expectedPackageSha256,
expectedInstalledApproval,
+ installOrigin: updateOrigin,
...(previousGhost
? {
beforePackageCommit: () =>
@@ -7091,6 +7159,13 @@ export function registerGhostIpc(): void {
});
} finally {
releaseMutation();
+ if (forgeUpdate.kind === 'agent-forge') {
+ try {
+ releaseForgePackStaging(forgeUpdate.ticket.stagingPath);
+ } catch {
+ // Staging cleanup must not leak the owner mutation lease.
+ }
+ }
}
});
@@ -7256,14 +7331,43 @@ export function registerGhostIpc(): void {
// 官方前缀在 inspect 就拒(确认弹窗都不该弹出来),install/update 双保险再拦。
rejectReservedGhostId(result.manifest.id);
rejectUnauthorizedTokenBroker(result.manifest);
+ let packTicket: string | undefined;
+ const inspectController = getForgePackStagingControllerIfConfigured();
+ const forgeInspect = inspectController
+ ? consumeForgePackAtInspect(inspectController, {
+ filePath: lizFilePath,
+ packageSha256: result.packageSha256,
+ manifestId: result.manifest.id,
+ currentOwner: getActiveAppSession(),
+ boundaryPending: isAppSessionBoundaryPending(),
+ })
+ : ({ kind: 'not-forge' } as const);
+ if (forgeInspect.kind === 'rejected') {
+ if (forgeInspect.reason === 'session-boundary-pending') {
+ throwIpcError('PRECONDITION_FAILED', '账号切换中,请稍后再试');
+ }
+ throwIpcError('GHOST_FILE_INVALID', '插件打包凭证已失效,请重新打包并确认');
+ }
+ if (forgeInspect.kind === 'accepted') packTicket = forgeInspect.packTicket;
return {
manifest: result.manifest,
trust: result.trust,
packageSha256: result.packageSha256,
...(result.iconDataUrl !== undefined ? { iconDataUrl: result.iconDataUrl } : {}),
+ ...(packTicket ? { packTicket } : {}),
};
});
+ ipcMain.handle('ghosts:abandon-pack-ticket', async (event, packTicket: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof packTicket !== 'string' || packTicket.length === 0) {
+ throwIpcError('INVALID_PARAMS', 'packTicket must be a non-empty string');
+ }
+ const controller = getForgePackStagingControllerIfConfigured();
+ if (controller) abandonForgePackInstall(controller, packTicket);
+ return { ok: true };
+ });
+
ipcMain.handle('ghosts:uninstall', async (event, id: unknown) => {
// 卸载会停运行时、撤 receipt 批准、清凭证/KV/ghost-fs 并删安装目录 —— 与
// install/update/set-enabled/export 同级的高权限写路径,来源判定必须由 Main
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index a05381dd12..b1216da582 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1115,13 +1115,14 @@ contextBridge.exposeInMainWorld('electronAPI', {
setupStatus: (id: string): Promise<unknown> => ipcRenderer.invoke('ghosts:setup-status', id),
install: (
lizFilePath: string,
- opts: { enable?: boolean; expectedPackageSha256: string },
+ opts: { enable?: boolean; expectedPackageSha256: string; packTicket?: string },
): Promise<{ ghost: unknown }> => ipcRenderer.invoke('ghosts:install', lizFilePath, opts),
update: (
lizFilePath: string,
opts: {
expectedPackageSha256: string;
expectedInstalledApproval: string;
+ packTicket?: string;
},
): Promise<{ ghost: unknown }> => ipcRenderer.invoke('ghosts:update', lizFilePath, opts),
cindyPrefsSync: (
@@ -1187,7 +1188,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
trust: unknown;
packageSha256: string;
iconDataUrl?: string;
+ packTicket?: string;
}> => ipcRenderer.invoke('ghosts:inspect', lizFilePath),
+ abandonPackTicket: (packTicket: string): Promise<{ ok: true }> =>
+ ipcRenderer.invoke('ghosts:abandon-pack-ticket', packTicket),
/** 本地包第三条恢复路径:从已装目录读确认卡事实(零副作用)。 */
reapproveInspect: (
id: string,
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
index 21f6d5aa4a..7419e31df0 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/installFlow.test.tsx
@@ -47,6 +47,7 @@ function setupWindow(
listSync: vi.fn(() => ({ ghosts: installedGhosts })),
install,
update,
+ abandonPackTicket: vi.fn(async () => ({ ok: true })),
},
};
Object.defineProperty(globalThis, 'window', {
diff --git a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
index 2bcb19c9ae..bcf1229051 100644
--- a/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/installFlow.tsx
@@ -137,6 +137,7 @@ async function confirmAndRunUpdate(
installed: InstalledGhost,
deps: InstallFlowDeps,
origin?: GhostInstallOrigin,
+ packTicket?: string,
): Promise<void> {
const { t, confirm } = deps;
// 权限 diff:只把新增/移除的权限亮给用户,不变项折叠计数。
@@ -167,11 +168,15 @@ async function confirmAndRunUpdate(
cancelText: t('settings.ghosts.updateConfirm.cancel'),
requireTypedConfirmation: typedIdConfirmation(t, manifest.id, escalate),
});
- if (!ok) return;
+ if (!ok) {
+ if (packTicket) await window.electronAPI.ghosts.abandonPackTicket(packTicket);
+ return;
+ }
try {
const { ghost } = await window.electronAPI.ghosts.update(lizFilePath, {
expectedPackageSha256: packageSha256,
expectedInstalledApproval: ghostInstallApprovalToken(installed.approval),
+ ...(packTicket ? { packTicket } : {}),
});
toast.success(
t('settings.ghosts.toast.updated', {
@@ -199,11 +204,13 @@ export async function confirmAndInstallGhost(
let manifest: GhostManifest;
let trust: GhostTrustInfo;
let packageSha256: string;
+ let packTicket: string | undefined;
try {
const inspected = await window.electronAPI.ghosts.inspect(lizFilePath);
manifest = inspected.manifest;
trust = inspected.trust;
packageSha256 = inspected.packageSha256;
+ packTicket = inspected.packTicket;
} catch (err) {
toast.error(t(ghostInstallErrorKey(extractIpcError(err)?.code)));
return;
@@ -213,7 +220,16 @@ export async function confirmAndInstallGhost(
// "已经注入",直接给换版确认)。origin 透传:Agent 发起的更新也要能加重。
const installed = findInstalled(manifest.id);
if (installed) {
- await confirmAndRunUpdate(lizFilePath, manifest, trust, packageSha256, installed, deps, origin);
+ await confirmAndRunUpdate(
+ lizFilePath,
+ manifest,
+ trust,
+ packageSha256,
+ installed,
+ deps,
+ origin,
+ packTicket,
+ );
return;
}
@@ -268,7 +284,10 @@ export async function confirmAndInstallGhost(
cancelText: t('settings.ghosts.installConfirm.cancel'),
requireTypedConfirmation: typedIdConfirmation(t, manifest.id, requireTypedId),
});
- if (!ok) return;
+ if (!ok) {
+ if (packTicket) await window.electronAPI.ghosts.abandonPackTicket(packTicket);
+ return;
+ }
// 2.5) 用户在确认框里选了自定义位置 → **装入前**先落 binding(keyed by
// ghostId,与安装顺序无关):否则「立即开启」的常驻插件会在 install 返回
@@ -289,6 +308,7 @@ export async function confirmAndInstallGhost(
const { ghost } = await window.electronAPI.ghosts.install(lizFilePath, {
enable: true,
expectedPackageSha256: packageSha256,
+ ...(packTicket ? { packTicket } : {}),
});
toast.success(t('settings.ghosts.toast.installed', { name: ghost.manifest.name }));
if (willOpenPanel) {
@@ -401,16 +421,19 @@ export async function pickAndUpdateGhost(expectedId: string, deps: InstallFlowDe
let manifest: GhostManifest;
let trust: GhostTrustInfo;
let packageSha256: string;
+ let packTicket: string | undefined;
try {
const inspected = await window.electronAPI.ghosts.inspect(picked.filePath);
manifest = inspected.manifest;
trust = inspected.trust;
packageSha256 = inspected.packageSha256;
+ packTicket = inspected.packTicket;
} catch (err) {
toast.error(t(ghostInstallErrorKey(extractIpcError(err)?.code)));
return;
}
if (manifest.id !== expectedId) {
+ if (packTicket) await window.electronAPI.ghosts.abandonPackTicket(packTicket);
toast.error(
t('settings.ghosts.errors.updateIdMismatch', { id: manifest.id, expected: expectedId }),
);
@@ -418,11 +441,21 @@ export async function pickAndUpdateGhost(expectedId: string, deps: InstallFlowDe
}
const installed = findInstalled(expectedId);
if (!installed) {
+ if (packTicket) await window.electronAPI.ghosts.abandonPackTicket(packTicket);
// 详情页开着的意识刚被别处抽离——极端竞态,按通用错误提示。
toast.error(t('settings.ghosts.errors.generic'));
return;
}
- await confirmAndRunUpdate(picked.filePath, manifest, trust, packageSha256, installed, deps);
+ await confirmAndRunUpdate(
+ picked.filePath,
+ manifest,
+ trust,
+ packageSha256,
+ installed,
+ deps,
+ undefined,
+ packTicket,
+ );
}
/**
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index f85c79aa43..f85e774eeb 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1239,7 +1239,7 @@ interface ElectronAPI {
install: (
lizFilePath: string,
/** enable:装入后立即开启(确认框勾选决定;缺省沉睡)。 */
- opts: { enable?: boolean; expectedPackageSha256: string },
+ opts: { enable?: boolean; expectedPackageSha256: string; packTicket?: string },
) => Promise<{ ghost: import('../shared/ghost').InstalledGhost }>;
/** 原位更新(同 id 换版):唤醒状态与面板位置延续,沙箱熄灯待重拉。 */
update: (
@@ -1247,6 +1247,7 @@ interface ElectronAPI {
opts: {
expectedPackageSha256: string;
expectedInstalledApproval: string;
+ packTicket?: string;
},
) => Promise<{ ghost: import('../shared/ghost').InstalledGhost }>;
/**
@@ -1313,7 +1314,11 @@ interface ElectronAPI {
/** 本次检查的整包指纹;安装/更新时回传,防止确认后文件被替换。 */
packageSha256: string;
iconDataUrl?: string;
+ /** Host 一次性打包凭证。有则回传给 install/update;无则按手动装入。 */
+ packTicket?: string;
}>;
+ /** 用户取消确认框时丢掉 inspect 签发的一次性打包凭证并清理 staging。 */
+ abandonPackTicket: (packTicket: string) => Promise<{ ok: true }>;
/** 本地包第三条恢复路径第一步:从已装目录读确认卡事实,零副作用。 */
reapproveInspect: (
id: string,