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): close plugin recovery review gaps

Yuewei-LL342a439332f8
diff --git a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts
index 684c672812..0906b5c3cd 100644
--- a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts
+++ b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts
@@ -2293,6 +2293,62 @@ describe('legacy Ghost plugin recovery', () => {
await expect(fs.access(path.join(root, 'brain', 'queued-plugin'))).resolves.toBeUndefined();
});
+ it('does not let a reserved deferred target id block visible recovery status', async () => {
+ const root = await tempRoot();
+ const ownerId = 'cloud-a';
+ const ownerKey = dataOwnerStorageKey(ownerId);
+ const markerPath = path.join(
+ root,
+ 'owners',
+ ownerKey,
+ __testing.LEGACY_GHOST_RECOVERY_MARKER,
+ );
+ const reservedManifestPath = path.join(
+ root,
+ 'owners',
+ ownerKey,
+ 'cindy-brain',
+ 'cindy-reserved',
+ 'ghost.json',
+ );
+ await fs.mkdir(path.dirname(markerPath), { recursive: true });
+ await fs.writeFile(
+ markerPath,
+ JSON.stringify({
+ version: 1,
+ ownerKey,
+ pendingIds: ['cindy-reserved', 'recoverable-plugin'],
+ }),
+ );
+ await writeGhostDirAtPath(path.dirname(reservedManifestPath), 'cindy-reserved');
+ await writeGhostDir(root, 'brain', 'recoverable-plugin');
+
+ const boundedModule = await import('../utils/readBoundedFile.js');
+ const originalNoFollowSync = boundedModule.readBoundedFileNoFollowSync;
+ const noFollowSpy = vi
+ .spyOn(boundedModule, 'readBoundedFileNoFollowSync')
+ .mockImplementation(
+ (file: string, maxBytes?: number, options?: { containWithin?: string; nonBlocking?: boolean }) => {
+ if (path.resolve(String(file)) === path.resolve(reservedManifestPath)) {
+ throw Object.assign(new Error('reserved manifest locked'), { code: 'EACCES' });
+ }
+ return originalNoFollowSync(file, maxBytes!, options!);
+ },
+ );
+ try {
+ expect(
+ getLegacyGhostRecoveryStatus(
+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },
+ root,
+ false,
+ { rejectReservedIds: true },
+ ),
+ ).toEqual({ state: 'partial', legacyPluginCount: 1, canRetry: true });
+ } finally {
+ noFollowSpy.mockRestore();
+ }
+ });
+
it('consolidates plugins left in the current owner scoped brain directory', async () => {
const root = await tempRoot();
const ownerId = 'cloud-a';
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
index b491cff143..2a2e127475 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -3031,6 +3031,26 @@ describe('GhostManager · Host approval receipt', () => {
'---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',
});
+ it('rejects an approved snapshot root replaced by a same-bytes link', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const ghost = manager.list()[0];
+ const snapshotRoot = ghost.approvedSkillRoot!;
+ const external = path.join(workDir, 'external-approved-snapshot');
+ await fs.promises.rename(snapshotRoot, external);
+ try {
+ await fs.promises.symlink(
+ external,
+ snapshotRoot,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ await fs.promises.rename(external, snapshotRoot);
+ return;
+ }
+
+ expect(await manager.verifyApprovedSkillSnapshot(ghost)).toBe(false);
+ });
+
it('keeps manifest, enabled state, and trust independent from mutable install files', async () => {
await manager.install(await makeCindy('approved.cindy', goodManifest()));
const before = manager.list()[0];
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthOwnerReconciliation.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthOwnerReconciliation.test.ts
new file mode 100644
index 0000000000..492e30abd1
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthOwnerReconciliation.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createGhostOauthOwnerReconciliationGate } from '../ghostOauthOwnerReconciliation';
+
+describe('Ghost OAuth owner reconciliation gate', () => {
+ it('does not let an old-owner failure suppress the new owner reconciliation', async () => {
+ const gate = createGhostOauthOwnerReconciliationGate();
+ let releaseOwnerA!: () => void;
+ const ownerABlocked = new Promise<void>((resolve) => {
+ releaseOwnerA = resolve;
+ });
+ const ownerA = vi.fn(async () => {
+ await ownerABlocked;
+ throw new Error('old owner database closed');
+ });
+ const ownerB = vi.fn(async () => true);
+
+ const ownerATask = gate.run('cloud:owner-a:1', ownerA);
+ const ownerBTask = gate.run('cloud:owner-b:2', ownerB);
+ await ownerBTask;
+ releaseOwnerA();
+
+ await expect(ownerATask).rejects.toThrow('old owner database closed');
+ expect(ownerB).toHaveBeenCalledOnce();
+ await gate.run('cloud:owner-b:2', ownerB);
+ expect(ownerB).toHaveBeenCalledOnce();
+ });
+
+ it('reruns when returning to a previously reconciled owner scope', async () => {
+ const gate = createGhostOauthOwnerReconciliationGate();
+ const ownerA = vi.fn(async () => true);
+ const ownerB = vi.fn(async () => true);
+
+ await gate.run('cloud:owner-a:1', ownerA);
+ await gate.run('cloud:owner-b:2', ownerB);
+ await gate.run('cloud:owner-a:1', ownerA);
+
+ expect(ownerA).toHaveBeenCalledTimes(2);
+ expect(ownerB).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
index 2e4539b878..8f5be45020 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
@@ -849,8 +849,15 @@ export class GhostInstallReceiptStore {
receipt: GhostInstallReceipt,
snapshotDir: string,
): Promise<boolean> {
+ // The content walker pins the resolved directory identity while hashing,
+ // but an approved snapshot must also remain rooted at the Host-managed
+ // lexical path. A same-bytes symlink/junction is still an authorization
+ // escape because the projected global skill link would resolve outside
+ // the approval state root.
+ if (await classifyGhostDirEntry(snapshotDir).catch(() => null) !== 'directory') return false;
const actual = await hashApprovedSkillContent(receipt.manifest, snapshotDir).catch(() => null);
if (!actual) return false;
+ if (await classifyGhostDirEntry(snapshotDir).catch(() => null) !== 'directory') return false;
return (receipt.manifest.skill?.items ?? []).every(
(item) => actual[item.dir] === receipt.skillContentSha256[item.dir],
);
diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthOwnerReconciliation.ts b/apps/desktop/src/main/cindy-brain/ghostOauthOwnerReconciliation.ts
new file mode 100644
index 0000000000..a407b9e5ec
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostOauthOwnerReconciliation.ts
@@ -0,0 +1,39 @@
+/**
+ * Deduplicate OAuth crash reconciliation only within the same durable owner.
+ *
+ * Different owner scopes must never share an in-flight result: an old owner
+ * can fail while its database is being closed, and that stale failure must not
+ * suppress the newly committed owner's reconciliation. The completion flag is
+ * intentionally supplied by the caller so a task that became stale mid-run
+ * cannot mark its scope reconciled.
+ */
+export function createGhostOauthOwnerReconciliationGate(): {
+ run: (
+ ownerScope: string,
+ reconcile: () => Promise<boolean>,
+ ) => Promise<void>;
+} {
+ let reconciledOwnerScope: string | null = null;
+ const inFlightByOwnerScope = new Map<string, Promise<void>>();
+
+ return {
+ async run(ownerScope, reconcile): Promise<void> {
+ if (reconciledOwnerScope === ownerScope) return;
+ const existing = inFlightByOwnerScope.get(ownerScope);
+ if (existing) return existing;
+
+ let task!: Promise<void>;
+ task = (async () => {
+ if (await reconcile()) reconciledOwnerScope = ownerScope;
+ })();
+ inFlightByOwnerScope.set(ownerScope, task);
+ try {
+ await task;
+ } finally {
+ if (inFlightByOwnerScope.get(ownerScope) === task) {
+ inFlightByOwnerScope.delete(ownerScope);
+ }
+ }
+ },
+ };
+}
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index e3c86cf4a7..2cd0192d86 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -144,6 +144,7 @@ import { handleGhostOauthRequest } from './runtime/ghostOauthEndpoint.js';
import { handleGhostConnectionsRequest } from './runtime/ghostConnectionsEndpoint.js';
import { GhostOauthAccountManager, type GhostOauthDecl } from './ghostOauthAccounts.js';
import { withGhostOauthMutationLock } from './ghostOauthMutationLock.js';
+import { createGhostOauthOwnerReconciliationGate } from './ghostOauthOwnerReconciliation.js';
import { cancelActiveGhostOauthFlow } from './ghostOauthFlow.js';
import {
appendReadyGhostOauthReauthSuggest,
@@ -3610,8 +3611,7 @@ export function getGhostCindySlot(): GhostCindySlot {
* removeGhostSecrets 的前缀清扫天然连带)。
*/
let ghostOauthManagerSingleton: GhostOauthAccountManager | null = null;
-let ghostOauthReconciledOwnerScope: string | null = null;
-let ghostOauthReconcileInFlight: Promise<void> | null = null;
+const ghostOauthOwnerReconciliationGate = createGhostOauthOwnerReconciliationGate();
function ghostOauthMutationLockPath(ghostId: string): string {
return ownerScopedUserDataPath('ghost-install-state', '.oauth-locks', `${ghostId}.lock`);
@@ -3638,11 +3638,8 @@ function withActiveOwnerGhostOauthMutationLock<T>(
/** Reconcile migration markers once for every committed owner scope. */
export async function reconcileGhostOauthAccountsForActiveOwner(): Promise<void> {
const ownerScope = activeOwnerScopeKey();
- if (ghostOauthReconciledOwnerScope === ownerScope) return;
- if (ghostOauthReconcileInFlight) await ghostOauthReconcileInFlight;
- if (ghostOauthReconciledOwnerScope === ownerScope) return;
- const reconcileTask = (async () => {
- if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScope) return;
+ await ghostOauthOwnerReconciliationGate.run(ownerScope, async () => {
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScope) return false;
const oauthManager = getGhostOauthAccountManager();
for (const ghost of getGhostManager().list()) {
await withActiveOwnerGhostOauthMutationLock(ghost.manifest.id, () => {
@@ -3654,16 +3651,8 @@ export async function reconcileGhostOauthAccountsForActiveOwner(): Promise<void>
);
});
}
- if (!isAppSessionBoundaryPending() && activeOwnerScopeKey() === ownerScope) {
- ghostOauthReconciledOwnerScope = ownerScope;
- }
- })();
- ghostOauthReconcileInFlight = reconcileTask;
- try {
- await reconcileTask;
- } finally {
- if (ghostOauthReconcileInFlight === reconcileTask) ghostOauthReconcileInFlight = null;
- }
+ return !isAppSessionBoundaryPending() && activeOwnerScopeKey() === ownerScope;
+ });
}
function getGhostOauthAccountManager(): GhostOauthAccountManager {
diff --git a/apps/desktop/src/main/ownerNamespaceMigration.ts b/apps/desktop/src/main/ownerNamespaceMigration.ts
index f3ee581cf7..35bdc46495 100644
--- a/apps/desktop/src/main/ownerNamespaceMigration.ts
+++ b/apps/desktop/src/main/ownerNamespaceMigration.ts
@@ -1249,9 +1249,7 @@ export function getLegacyGhostRecoveryStatus(
scopedDiscovery.deferredRoots.length > 0 ||
targetDiscovery.deferredRoots.length > 0 ||
sourceDeferredIds.length > 0 ||
- targetDiscovery.deferredIds.some((id) =>
- recoveryMarker?.pendingIds?.includes(id),
- );
+ targetDiscovery.deferredIds.some((id) => visiblePendingIds.includes(id));
// 一个与待恢复 id 无关的 target 目录损坏(比如安装了别的插件但 ghost.json
// 偶然坏了)不应永久卡死本 owner 的整批 legacy 恢复。用已按 pendingIds
// 过滤的 targetInvalidIds 判定,而不是原始的 targetDiscovery.invalidIds。