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(plugins): 按实例隔离个人统计与来源回填

nana2ead041f8023
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 2c444a3e54..607b1acb2f 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -2005,7 +2005,7 @@ export function getGhostPipeDispatcher(): GhostPipeDispatcher {
const service = currentPluginUsageService();
if (!service) return null;
if (ghost.approval.state !== 'approved') return null;
- const handle = service.captureBound(ghost.manifest.id, ghost.approval.revision);
+ const handle = service.captureBound(installedGhostStoragePart(ghost), ghost.approval.revision);
if (!handle) {
void bindPluginUsage(ghost);
return null;
@@ -3013,7 +3013,7 @@ function pluginMarketAuthorizationTargetFor(ghostId: string): { ghostId: string;
function readPluginUsageIdentity(ghost: InstalledGhost) {
try {
const result = readInstalledGhostManifestSnapshot(ghost.dir, GHOST_INSTALL_MANIFEST_MAX_BYTES);
- return pluginUsageIdentity(ghost, getPluginMarketLedger().installationForGhost(ghost.manifest.id),
+ return pluginUsageIdentity(ghost, getPluginMarketLedger().installationForPlugin({ ghostId: ghost.manifest.id, ...deliveryNamespaceFields(ghost) }),
result.ok ? installedMarketManifestIdentity(result.snapshot) : null,
pluginUsageServerRoot());
} catch { return null; }
@@ -3032,7 +3032,7 @@ async function bindPluginUsage(ghost: InstalledGhost, previousRevision?: string)
await withGhostInstallLock(ghost.manifest.id, async () => {
if (activeOwnerScopeKey() !== scope || isAppSessionBoundaryPending()) return;
// A fallback bind can wait behind update/uninstall. Read the final committed identity.
- const installed = getGhostManager().list().find(g => g.manifest.id === ghost.manifest.id);
+ const installed = findInstalledGhostByInstanceId(getGhostManager().list(), installedGhostStoragePart(ghost));
const identity = installed && readPluginUsageIdentity(installed);
if (identity) await service.bind(identity, previousRevision);
});
@@ -9187,9 +9187,10 @@ export function registerGhostIpc(): void {
});
registerPluginUsageIpc({
ipcMain, assertTrusted: assertTrustedAppRendererEvent, service: currentPluginUsageService,
+ lockId: id => findGhostForInstanceId(id)?.manifest.id ?? id,
identity: id => {
requireGhostAvailableForActiveSession(id);
- const ghost = getGhostManager().list().find(g => g.manifest.id === id);
+ const ghost = findGhostForInstanceId(id);
return ghost ? readPluginUsageIdentity(ghost) : null;
},
warn: () => log.warn('plugin usage IPC unavailable'),
diff --git a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts
index f020259eb7..155086d03a 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts
@@ -842,3 +842,23 @@ describe('backfill missing namespace from the server catalog', () => {
expect(ledger.installationForPlugin({ ghostId: 'xd-feishu', namespace: 'xd' })?.namespace).toBe('xd');
});
});
+
+it('backfills a verified reporting root only in the exact same-name namespace row', () => {
+ const { ledger } = sameNameNamespaceHarness();
+ const root = ledger.installationForPlugin({ ghostId: 'helper', namespace: null })!;
+ const org = ledger.installationForPlugin({ ghostId: 'helper', namespace: 'acme' })!;
+ expect(ledger.backfillServerRoot(org, 'https://org-origin')).toBe(true);
+ expect(ledger.installationForPlugin({ ghostId: 'helper', namespace: 'acme' })).toMatchObject({ serverRoot: 'https://org-origin' });
+ expect(ledger.installationForPlugin({ ghostId: 'helper', namespace: null })).toEqual(root);
+ expect(ledger.backfillServerRoot(org, 'https://other')).toBe(false);
+});
+
+it('keeps a pending local uninstall valid after reporting-root backfill without accepting an origin replacement', () => {
+ const { ledger } = harness();
+ const captured = record({ namespace: null });
+ ledger.upsertInstallation(captured);
+ expect(ledger.backfillServerRoot(captured, 'https://original')).toBe(true);
+ expect(ledger.markRemovedRecordIfUnchanged({ ...captured, serverRoot: 'https://other' }, 'user-1')).toBe(false);
+ expect(ledger.markRemovedRecordIfUnchanged(captured, 'user-1')).toBe(true);
+ expect(ledger.installationForPlugin(captured)).toMatchObject({ installed: false, serverRoot: 'https://original' });
+});
diff --git a/apps/desktop/src/main/plugin-market/ledger.ts b/apps/desktop/src/main/plugin-market/ledger.ts
index f64617ec19..91731e20bf 100644
--- a/apps/desktop/src/main/plugin-market/ledger.ts
+++ b/apps/desktop/src/main/plugin-market/ledger.ts
@@ -476,7 +476,12 @@ export class PluginMarketLedger {
markRemovedRecordIfUnchanged(record: PluginMarketInstallationRecord, userId: string | null): boolean {
const current = this.installationForPlugin(record);
- if (!current || canonicalJson(current) !== canonicalJson(record)) return false;
+ if (!current) return false;
+ // A verified reporting-root backfill does not replace the captured installation.
+ // Every other provenance field (and an already pinned root) still participates in CAS.
+ const expected = record.serverRoot === undefined && current.serverRoot
+ ? { ...record, serverRoot: current.serverRoot } : record;
+ if (canonicalJson(current) !== canonicalJson(expected)) return false;
this.markRemovedRecord(current, userId);
return true;
}
@@ -546,9 +551,9 @@ export class PluginMarketLedger {
backfillServerRoot(expected: PluginMarketInstallationRecord, serverRoot: string): boolean {
const data = this.read();
- const current = data.installations[expected.ghostId];
+ const current = data.installations[pluginLedgerRecordKey(expected)];
if (!current || current.serverRoot || canonicalJson(current) !== canonicalJson(expected)) return false;
- data.installations[current.ghostId] = { ...current, serverRoot };
+ data.installations[pluginLedgerRecordKey(current)] = { ...current, serverRoot };
this.write(data);
return true;
}
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index 01d1175026..693e808ea8 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -1107,7 +1107,7 @@ export class PluginMarketService {
requireSameMarketOwner(owner);
const installations = ledger.read().installations;
for (const plugin of plugins) {
- const record = installations[plugin.ghostId];
+ const record = installations[pluginLedgerRecordKey(plugin)];
if (record?.installed && !record.serverRoot && record.source !== 'git-market'
&& record.source !== 'local-market' && record.pluginId === plugin.id
&& record.scope === plugin.scope && record.organizationId === plugin.organizationId
diff --git a/apps/desktop/src/main/plugin-usage/__tests__/identity.test.ts b/apps/desktop/src/main/plugin-usage/__tests__/identity.test.ts
index f17b77ad59..af780ff0a3 100644
--- a/apps/desktop/src/main/plugin-usage/__tests__/identity.test.ts
+++ b/apps/desktop/src/main/plugin-usage/__tests__/identity.test.ts
@@ -81,3 +81,18 @@ it('keeps a verified installed origin when the current endpoint changes or becom
pluginUsageIdentity(ghost, record, snapshot, 'https://original')?.verifiedServerRoot,
).toBeUndefined();
});
+
+it('keeps same-name namespace instances separate and never borrows a sibling catalog provenance', () => {
+ const orgGhost = { ...ghost, namespace: 'acme', instanceKey: '_ns__acme__some-plugin' };
+ const rootGhost = { ...ghost, namespace: null, instanceKey: 'some-plugin' };
+ const orgRecord = { ...record, namespace: 'acme', scope: 'organization', organizationId: 'org-1' } as PluginMarketInstallationRecord;
+ expect(pluginUsageIdentity(orgGhost, orgRecord, snapshot, 'https://server')).toMatchObject({
+ ghostId: '_ns__acme__some-plugin', sourceKind: 'server', pluginId: 'plugin1',
+ });
+ expect(pluginUsageIdentity(rootGhost, orgRecord, snapshot, 'https://server')).toMatchObject({
+ ghostId: 'some-plugin', sourceKind: 'manual', pluginId: null, stableKey: null,
+ });
+ expect(pluginUsageIdentity(orgGhost, null, snapshot, 'https://server')?.ghostId).not.toBe(
+ pluginUsageIdentity(rootGhost, null, snapshot, 'https://server')?.ghostId,
+ );
+});
diff --git a/apps/desktop/src/main/plugin-usage/__tests__/ipc.test.ts b/apps/desktop/src/main/plugin-usage/__tests__/ipc.test.ts
index 66d8f20822..038f542d4a 100644
--- a/apps/desktop/src/main/plugin-usage/__tests__/ipc.test.ts
+++ b/apps/desktop/src/main/plugin-usage/__tests__/ipc.test.ts
@@ -4,7 +4,7 @@ import type { PluginUsageService } from '../service';
import type { IpcMain, IpcMainInvokeEvent } from 'electron';
import { withGhostInstallLock } from '../../cindy-brain/ghostInstallLock';
import type { PluginUsageIdentity } from '../../../shared/pluginUsage';
-function harness(trusted = true) {
+function harness(trusted = true, lockId?: (id: string) => string) {
const handlers = new Map<string, Parameters<IpcMain['handle']>[1]>();
const service = {
summary: vi.fn(async () => null),
@@ -23,6 +23,7 @@ function harness(trusted = true) {
},
service: () => current.service,
identity,
+ lockId,
warn,
});
return { handlers, service, warn, identity, current };
@@ -115,3 +116,22 @@ it('hides database failures and preserves deliberate visibility and argument err
code: 'NOT_FOUND',
});
});
+
+it('accepts an instance key while waiting on the existing logical package lock', async () => {
+ const { handlers, identity } = harness(true, () => 'same-name');
+ let release!: () => void;
+ let entered!: () => void;
+ const ready = new Promise<void>((resolve) => { entered = resolve; });
+ const updating = withGhostInstallLock('same-name', async () => {
+ entered();
+ await new Promise<void>((resolve) => { release = resolve; });
+ });
+ await ready;
+ const summary = handlers.get('ghosts:usage-summary')!({} as IpcMainInvokeEvent, '_ns__acme__same-name');
+ await Promise.resolve();
+ expect(identity).not.toHaveBeenCalled();
+ release();
+ await updating;
+ await expect(summary).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ expect(identity).toHaveBeenCalledWith('_ns__acme__same-name');
+});
diff --git a/apps/desktop/src/main/plugin-usage/__tests__/service.test.ts b/apps/desktop/src/main/plugin-usage/__tests__/service.test.ts
index 678c674fe5..3b5168a82d 100644
--- a/apps/desktop/src/main/plugin-usage/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-usage/__tests__/service.test.ts
@@ -594,3 +594,20 @@ it('runs usage transactions in the bundled file worker, not only its inline fall
rmSync(dir, { recursive: true, force: true });
}
}, 60_000);
+
+it('counts and clears tool calls separately for same-name namespace instances', async () => {
+ const root = { ...identity, ghostId: 'same-name' };
+ const org = { ...identity, ghostId: '_ns__acme__same-name' };
+ await service.bind(root);
+ await service.bind(org);
+ const rootHandle = service.capture(root)!;
+ const orgHandle = service.capture(org)!;
+ expect(rootHandle.subjectId).not.toBe(orgHandle.subjectId);
+ service.accept(rootHandle, 'root-call', 'tool', null, now - 1);
+ service.accept(orgHandle, 'org-call', 'tool', null, now - 1);
+ expect(await service.summary(rootHandle.subjectId)).toMatchObject({ totalCalls: 1 });
+ expect(await service.summary(orgHandle.subjectId)).toMatchObject({ totalCalls: 1 });
+ await service.clear(rootHandle.subjectId);
+ expect(await service.summary(rootHandle.subjectId)).toMatchObject({ totalCalls: 0 });
+ expect(await service.summary(orgHandle.subjectId)).toMatchObject({ totalCalls: 1 });
+});
diff --git a/apps/desktop/src/main/plugin-usage/identity.ts b/apps/desktop/src/main/plugin-usage/identity.ts
index 52c7e302ed..8eac0bcfe7 100644
--- a/apps/desktop/src/main/plugin-usage/identity.ts
+++ b/apps/desktop/src/main/plugin-usage/identity.ts
@@ -1,3 +1,7 @@
+import {
+ installedGhostStoragePart,
+ knownDeliveryNamespacesDiffer,
+} from '../../shared/pluginIdentity.js';
import type { InstalledGhost } from '../../shared/ghost.js';
import type { PluginUsageIdentity } from '../../shared/pluginUsage.js';
import type { PluginMarketInstallationRecord } from '../plugin-market/ledger.js';
@@ -15,7 +19,7 @@ export function pluginUsageIdentity(
): PluginUsageIdentity | null {
if (ghost.approval.state !== 'approved') return null;
const base: PluginUsageIdentity = {
- ghostId: ghost.manifest.id,
+ ghostId: installedGhostStoragePart(ghost),
displayName: ghost.manifest.name,
revision: ghost.approval.revision,
sourceKind: 'manual',
@@ -29,7 +33,8 @@ export function pluginUsageIdentity(
};
if (
!record?.installed ||
- record.ghostId !== base.ghostId ||
+ record.ghostId !== ghost.manifest.id ||
+ knownDeliveryNamespacesDiffer(ghost, record) ||
!installedIdentity ||
!verifyInstalledMarketManifest(record, installedIdentity)
)
diff --git a/apps/desktop/src/main/plugin-usage/ipc.ts b/apps/desktop/src/main/plugin-usage/ipc.ts
index 7e48429b13..7114c6bead 100644
--- a/apps/desktop/src/main/plugin-usage/ipc.ts
+++ b/apps/desktop/src/main/plugin-usage/ipc.ts
@@ -1,5 +1,5 @@
import type { IpcMain, IpcMainInvokeEvent } from 'electron';
-import { isValidGhostId } from '../../shared/ghost.js';
+import { isGhostInstanceId } from '../../shared/pluginIdentity.js';
import { isIpcError } from '../../shared/ipc-errors.js';
import type { PluginUsageIdentity } from '../../shared/pluginUsage.js';
import { throwIpcError } from '../utils/ipcValidate.js';
@@ -12,6 +12,8 @@ export function registerPluginUsageIpc(deps: {
service(): PluginUsageService | null;
/** Checks current-owner plugin visibility and derives verified install identity. */
identity(ghostId: string): PluginUsageIdentity | null;
+ /** The existing package lock is keyed by logical id, including instance-key queries. */
+ lockId?(instanceId: string): string;
warn(): void;
}): void {
const historyId = (value: unknown): string => {
@@ -39,10 +41,10 @@ export function registerPluginUsageIpc(deps: {
};
deps.ipcMain.handle('ghosts:usage-summary', (event, id: unknown) =>
invoke(event, async () => {
- if (typeof id !== 'string' || !isValidGhostId(id))
+ if (typeof id !== 'string' || !isGhostInstanceId(id))
throwIpcError('INVALID_PARAMS', 'Invalid plugin id');
const current = service();
- return withGhostInstallLock(id, async () => {
+ return withGhostInstallLock(deps.lockId?.(id) ?? id, async () => {
if (service() !== current)
throwIpcError('PRECONDITION_FAILED', 'Plugin usage owner changed');
const identity = deps.identity(id);
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index 629961689e..d8117bfad7 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@ -425,7 +425,13 @@ export function GhostPluginDetailView({
) : null}
</header>
- {ghost ? <PluginUsageCard key={`${usageOwnerKey ?? "local"}:${ghost.manifest.id}`} ghostId={ghost.manifest.id} confirmClear={confirmClearUsage} /> : null}
+ {ghost ? (
+ <PluginUsageCard
+ key={`${usageOwnerKey ?? 'local'}:${detail.id}`}
+ ghostId={detail.id}
+ confirmClear={confirmClearUsage}
+ />
+ ) : null}
{hasConfiguration ? (
<section