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): 减少插件市场点击安装时的卡顿 (#6552)

DavidShenXD131dfb5b5a72
diff --git a/apps/desktop/src/main/bot-import/__tests__/nativePackage.test.ts b/apps/desktop/src/main/bot-import/__tests__/nativePackage.test.ts
index ad393d85f2..c1532587d1 100644
--- a/apps/desktop/src/main/bot-import/__tests__/nativePackage.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/nativePackage.test.ts
@@ -84,8 +84,13 @@ it('rejects unbound extra files, even in a skill subtree', async () => {
});
it('refuses symlinks rather than following package paths outside the trusted directory', async () => {
const dir = await fixture();
- const file = path.join(dir, 'engineer-bot', version, 'knowledge/method.md');
- await fs.unlink(file); await fs.symlink(path.join(root, 'engineer-bot', version, 'knowledge/method.md'), file);
+ // Unit: exercise the same lstat rejection with an unprivileged Windows junction,
+ // as in files.test.ts, rather than failing to create the fixture before validation.
+ const relative = process.platform === 'win32' ? 'knowledge' : path.join('knowledge', 'method.md');
+ const link = path.join(dir, 'engineer-bot', version, relative);
+ await fs.rm(link, { recursive: true });
+ await fs.symlink(path.join(root, 'engineer-bot', version, relative), link,
+ process.platform === 'win32' ? 'junction' : 'file');
await expect(readNativeBotPackage(dir, 'engineer-bot')).rejects.toThrow('INVALID_PACKAGE');
});
it('rejects capability icons outside the shared whitelist', async () => {
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index db0c3da2a7..42d34cc3d4 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -239,6 +239,28 @@ export interface ApprovedGhostInstallEvidence {
legacyMigrated: boolean;
}
+interface ParsedGhostPackage {
+ manifest: GhostManifest;
+ approvedManifest: GhostManifest;
+ canonicalManifest: GhostManifest;
+ localeResources: Record<string, GhostManifestLocaleResource>;
+ unsupportedLegacySlots: string[];
+ trust: GhostTrustInfo;
+ packageSha256: string;
+ rawManifestSha256: string;
+ releasedLegacyDigestFormat: unknown;
+ iconDataUrl?: string;
+ allEntries: JSZip.JSZipObject[];
+ prefix: string;
+}
+
+function cloneParsedGhostPackage(parsed: ParsedGhostPackage): ParsedGhostPackage {
+ const { allEntries, ...metadata } = parsed;
+ // ZIP objects stay private to the manager. Callers must never mutate the
+ // validated metadata retained for another inspect/install of these bytes.
+ return { ...structuredClone(metadata), allEntries };
+}
+
export interface GhostManagerOptions {
/** 意识仓库根目录(生产:userData/cindy-brain;测试:os.tmpdir 下临时目录)。 */
getRootDir: () => string;
@@ -639,6 +661,14 @@ export class GhostManager {
private readonly retirements = new FeatureRetirementStore(() => this.receiptStore.rootDir());
private ownerContextKey: string;
private mutationTail: Promise<void> = Promise.resolve();
+ /** One small archive, for the inspect → consent → install path only. */
+ private parsedPackageCache: {
+ packageSha256: string;
+ locale: string | undefined;
+ trustRegistry: string;
+ expiresAt: number;
+ parsed: ParsedGhostPackage;
+ } | null = null;
private activeMutationContext: {
ownerContextKey: string;
contentRoot: string;
@@ -883,6 +913,7 @@ export class GhostManager {
}
private planInstancePlacement(
+ registry: PluginInstanceRegistry,
ghostId: string,
namespace: string | null,
source?: PluginInstanceSource,
@@ -891,7 +922,6 @@ export class GhostManager {
):
| { kind: 'blocked'; reason: string }
| { kind: 'ok'; instanceKey: string; relId: string } {
- const registry = this.syncInstanceRegistry();
const relId = pluginNewInstallRelId(createPluginLogicalIdentity(namespace, ghostId));
const instanceKey = pluginInstallStoragePart(relId);
if (!this.instanceRegistryService.isBlocked()) {
@@ -2580,6 +2610,10 @@ export class GhostManager {
/** Synchronous first-frame projection; share disk reads only within this call. */
list(): InstalledGhost[] {
+ return this.scanInstalled().ghosts;
+ }
+
+ private scanInstalled(): { ghosts: InstalledGhost[]; registry: PluginInstanceRegistry } {
this.ensureCurrentOwnerContextSync();
const entries = this.listContentEntries();
const receipts = new Map<string, GhostInstallReceiptReadResult>();
@@ -2593,13 +2627,13 @@ export class GhostManager {
};
// Registry facts and the list projection consume the same validated bytes.
// No cache survives this synchronous scan; isolation checks still run below.
- this.instanceRegistryService.sync({
+ const registry = this.instanceRegistryService.sync({
listContentEntries: () => entries,
receiptFact: (relId) => this.receiptFact(relId, readReceipt(relId)),
});
const result = this.projectListedEntries(entries, readReceipt);
result.sort((a, b) => a.manifest.id.localeCompare(b.manifest.id));
- return result;
+ return { ghosts: result, registry };
}
/**
@@ -3109,25 +3143,7 @@ export class GhostManager {
}
/** 装入的前半程(读文件 / 解包 / 校验清单),inspect 与 install 共用。 */
- private async parse(lizFilePath: string): Promise<
- | {
- manifest: GhostManifest;
- // 同一份包内清单的两个名字:approvedManifest 供 receipt 写入(我们),
- // canonicalManifest 供 inspect/可恢复复核比对(main)。parse 里都置为 v.manifest。
- approvedManifest: GhostManifest;
- canonicalManifest: GhostManifest;
- localeResources: Record<string, GhostManifestLocaleResource>;
- unsupportedLegacySlots: string[];
- trust: GhostTrustInfo;
- packageSha256: string;
- rawManifestSha256: string;
- releasedLegacyDigestFormat: unknown;
- iconDataUrl?: string;
- allEntries: JSZip.JSZipObject[];
- prefix: string;
- }
- | { rejection: InstallRejection }
- > {
+ private async parse(lizFilePath: string): Promise<ParsedGhostPackage | { rejection: InstallRejection }> {
// 1) 读源文件(带体积上限)。stat 后再 readFile 是两次独立打开,期间文件
// 可被换成超大文件绕过上限——单句柄限量读。允许跟随链接:用户拖入的
// .cindy 本身可以是链接,防篡改由 expectedPackageSha256 对账负责。
@@ -3151,6 +3167,22 @@ export class GhostManager {
};
}
+ // Always reread the complete, stable source before reuse: a pathname or mtime
+ // is not evidence that the package approved before consent is still present.
+ const packageSha256 = crypto.createHash('sha256').update(buf).digest('hex');
+ const locale = this.options.getLocale?.();
+ const trustRegistry = structuredClone(this.options.trustRegistry ?? {});
+ const trustRegistryKey = JSON.stringify(trustRegistry);
+ const cached = this.parsedPackageCache;
+ if (
+ cached && cached.expiresAt > Date.now() &&
+ cached.packageSha256 === packageSha256 && cached.locale === locale &&
+ cached.trustRegistry === trustRegistryKey
+ ) {
+ return cloneParsedGhostPackage(cached.parsed);
+ }
+ this.parsedPackageCache = null;
+
// 2) 解析 zip + 找 ghost.json(容忍"压缩时多包了一层文件夹"的常见做法)
let zip: JSZip;
try {
@@ -3292,7 +3324,7 @@ export class GhostManager {
},
};
}
- let localizedManifest = withGhostResolvedLocale(v.manifest, this.options.getLocale?.());
+ let localizedManifest = withGhostResolvedLocale(v.manifest, locale);
const localeResources: Record<string, GhostManifestLocaleResource> = {};
if (v.manifest.locales !== undefined) {
const resources = new Map<string, GhostManifestLocaleResource>();
@@ -3338,7 +3370,7 @@ export class GhostManager {
resources.set(localePath, validated.resource);
localeResources[localePath] = validated.resource;
}
- const localePath = ghostLocalePathFor(v.manifest, this.options.getLocale?.());
+ const localePath = ghostLocalePathFor(v.manifest, locale);
const resource = localePath ? resources.get(localePath) : undefined;
if (resource) localizedManifest = resolveGhostManifestLocale(localizedManifest, resource);
}
@@ -3364,7 +3396,7 @@ export class GhostManager {
zip,
prefix,
v.manifest,
- this.options.trustRegistry,
+ trustRegistry,
);
if (!signature.ok) {
return { rejection: { code: 'file-invalid', reason: `签名验证失败:${signature.reason}` } };
@@ -3509,14 +3541,14 @@ export class GhostManager {
}
}
- return {
+ const parsed: ParsedGhostPackage = {
manifest: localizedManifest,
approvedManifest: v.manifest,
canonicalManifest: v.manifest,
localeResources,
unsupportedLegacySlots: v.unsupportedLegacySlots,
trust: signature.trust,
- packageSha256: crypto.createHash('sha256').update(buf).digest('hex'),
+ packageSha256,
rawManifestSha256: crypto.createHash('sha256').update(manifestBytes).digest('hex'),
releasedLegacyDigestFormat: ghostManifestToLegacyV2DigestFormat(
v.manifest,
@@ -3526,6 +3558,17 @@ export class GhostManager {
allEntries,
prefix,
};
+ // Large bundled CLI archives must not become a long-lived memory cache.
+ if (buf.byteLength <= MAX_BASIC_CINDY_FILE_BYTES) {
+ this.parsedPackageCache = {
+ packageSha256,
+ locale,
+ trustRegistry: trustRegistryKey,
+ expiresAt: Date.now() + 60_000,
+ parsed,
+ };
+ }
+ return cloneParsedGhostPackage(parsed);
}
async install(
@@ -3606,7 +3649,9 @@ export class GhostManager {
const identity = createPluginLogicalIdentity(opts?.namespace ?? null, manifest.id);
const registrySource = opts?.registrySource ??
(opts?.installOrigin === 'agent-forge' ? 'agent-forge' : 'manual');
+ const preflight = this.scanInstalled();
const placement = this.planInstancePlacement(
+ preflight.registry,
manifest.id, identity.namespace, registrySource, opts?.pluginId, opts?.reclaimLegacyBareInstance === true,
);
if (placement.kind === 'blocked') {
@@ -3617,7 +3662,7 @@ export class GhostManager {
if (this.hasPendingMutationJournal(relId)) {
return { rejection: { code: 'io', reason: '意识正在恢复,请稍后重试' } };
}
- if (findInstalledGhostByIdentity(this.list(), identity)) {
+ if (findInstalledGhostByIdentity(preflight.ghosts, identity)) {
return { rejection: { code: 'already-installed', reason: `意识 ${manifest.id} 已装入` } };
}
const physicalRel = this.resolvePhysicalRelId(relId) ?? relId;
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 5c7ccb51f2..3463417443 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -5258,6 +5258,33 @@ describe('GhostManager · setEnabled(启用/停用)', () => {
});
describe('GhostManager · inspect(只验不装)', () => {
+ // Unit: first-install inspects twice before install parses the same archive.
+ // Reuse must still isolate returned manifests and reread source bytes; existing
+ // replacement tests did not cover repeated decompression of unchanged input.
+ it('reuses verified package parsing without trusting mutated inspection results or changed bytes', async () => {
+ const cindy = await makeCindy('reused.cindy', goodManifest());
+ const parseZip = vi.spyOn(JSZip, 'loadAsync');
+ try {
+ const inspected = await manager.inspect(cindy);
+ if ('rejection' in inspected) throw new Error(inspected.rejection.reason);
+ inspected.manifest.name = 'Changed by inspection caller';
+ inspected.canonicalManifest.name = 'Changed canonical manifest';
+
+ expect(await manager.inspect(cindy)).toMatchObject({
+ manifest: { name: 'Hello 意识' }, canonicalManifest: { name: 'Hello 意识' },
+ });
+ expect(await manager.install(cindy, { expectedPackageSha256: inspected.packageSha256 }))
+ .toMatchObject({ ghost: { manifest: { name: 'Hello 意识' }, enabled: true } });
+ expect(parseZip).toHaveBeenCalledTimes(1);
+
+ await makeCindy('reused.cindy', { ...goodManifest(), name: 'Replaced package' });
+ expect(await manager.inspect(cindy)).toMatchObject({ manifest: { name: 'Replaced package' } });
+ expect(parseZip).toHaveBeenCalledTimes(2);
+ } finally {
+ parseZip.mockRestore();
+ }
+ });
+
it('opens a top-level .cindy source in non-blocking mode', async () => {
const cindy = await makeCindy('nonblocking.cindy', goodManifest());
const realOpen = fs.promises.open;
@@ -5410,6 +5437,10 @@ describe('GhostManager · inspect(只验不装)', () => {
tools: [{ name: 'do_thing', description: '做点事' }],
},
});
+ hostLocale = 'en';
+ expect(await manager.inspect(cindy)).toMatchObject({
+ manifest: { name: 'English name' }, canonicalManifest: { name: 'Base name' },
+ });
});
it('确认后源文件被替换时,整包指纹不一致会拒绝安装', async () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostSignature.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostSignature.test.ts
index d0b5dda9fd..ac61475d8d 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostSignature.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostSignature.test.ts
@@ -16,6 +16,7 @@ import {
signGhostPackage,
verifyGhostZipSignatures,
type GhostSignatureDocument,
+ type GhostTrustRegistry,
} from '../ghostSignature';
const MANIFEST: GhostManifest = {
@@ -126,6 +127,36 @@ describe('ghostSignature · 发布者签名', () => {
});
});
+ // Unit: unchanged package bytes must not retain revoked publisher trust through
+ // inspect's parse cache. Existing signature tests only verified fresh ZIPs.
+ it('refreshes inspection trust when the publisher registry changes', async () => {
+ const { privateKey } = crypto.generateKeyPairSync('ed25519');
+ const signed = await signGhostPackage(await unsignedPackage(), {
+ publisherName: 'Publisher',
+ privateKey,
+ });
+ const doc = await readSignature(signed);
+ const file = path.join(workDir, 'registry-change.cindy');
+ await fs.promises.writeFile(file, signed);
+ const trustRegistry: GhostTrustRegistry = {
+ publishers: {
+ [doc.publisher.keyId]: { name: 'Trusted publisher', publicKey: doc.publisher.publicKey },
+ },
+ };
+ const manager = new GhostManager({
+ getRootDir: () => path.join(workDir, 'ghosts'),
+ trustRegistry,
+ });
+
+ expect(await manager.inspect(file)).toMatchObject({
+ trust: { level: 'verified-publisher', publisherVerified: true },
+ });
+ delete trustRegistry.publishers![doc.publisher.keyId];
+ expect(await manager.inspect(file)).toMatchObject({
+ trust: { level: 'unverified', publisherVerified: false },
+ });
+ });
+
it('签名后任一文件被改,GhostManager inspect 直接拒绝,不能降级成无签名', async () => {
const { privateKey } = crypto.generateKeyPairSync('ed25519');
const signed = await signGhostPackage(await unsignedPackage(), {
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
index 32a7659a96..56e7237c0f 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -698,6 +698,28 @@ describe('same-release legacy organization source recovery', () => {
});
describe('PluginMarketService migration and defaultInstall', () => {
+ // Unit: market install used four full synchronous scans before download.
+ // Existing download-race cases protect the later fresh approval checks;
+ // this first-install case protects the uninterrupted preflight work budget.
+ it('uses one installed scan before downloading a market install', async () => {
+ const item = summary();
+ const h = harness([item]);
+ const download = h.api.download.getMockImplementation()!;
+ let scansBeforeDownload = 0;
+ h.api.download.mockImplementation(async (...args) => {
+ scansBeforeDownload = runtime.listScans;
+ return download(...args);
+ });
+ runtime.install.mockResolvedValue({
+ manifest: manifest(), dir: path.join(os.tmpdir(), 'market-install'), enabled: true,
+ });
+
+ await h.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT);
+
+ expect(scansBeforeDownload).toBe(1);
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({ installed: true });
+ });
+
it.each([
{ namespace: undefined, evidence: 'matching' },
{ namespace: 'acme', evidence: 'matching' },
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index f0acc568ed..a9982cd4b5 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -1532,8 +1532,9 @@ export class PluginMarketService {
if (plugin.currentRelease.id !== options.expectedReleaseId) {
throwIpcError('PRECONDITION_FAILED', 'Plugin release changed after selection');
}
- const target = organizationDeliveryTarget(plugin, this.localInstallSnapshot(ledger), owner);
- const existing = installedGhostMatchingMarketPlugin(target);
+ const local = this.localInstallSnapshot(ledger, undefined, plugin.ghostId);
+ const target = organizationDeliveryTarget(plugin, local, owner);
+ const existing = snapshotGhost(local, target);
return this.installDetail(
plugin,
{
@@ -1557,6 +1558,7 @@ export class PluginMarketService {
},
owner,
ledger,
+ local,
);
}
@@ -2265,10 +2267,13 @@ export class PluginMarketService {
},
owner = captureMarketOwner(),
ledger = this.ledgerForOwner(owner),
+ // Only reuse the caller's uninterrupted preflight. After download/consent,
+ // the live target and locked commit continue to read fresh installation facts.
+ preflight?: LocalInstallSnapshot,
): Promise<PluginMarketInstallResult> {
requireSameMarketOwner(owner);
const serverPlugin = plugin;
- const local = this.localInstallSnapshot(ledger);
+ const local = preflight ?? this.localInstallSnapshot(ledger, undefined, plugin.ghostId);
const legacyTarget = legacyOrganizationDeliveryTarget(plugin, local);
plugin = organizationDeliveryTarget(plugin, local, owner);
const namespaceFromLogin = !hasDeliveryNamespace(legacyTarget) && hasDeliveryNamespace(plugin);
@@ -2298,7 +2303,7 @@ export class PluginMarketService {
if (brokerPortError) {
throwIpcError(brokerPortError.code, brokerPortError.reason);
}
- const existing = installedGhostMatchingMarketPlugin(plugin);
+ const existing = snapshotGhost(local, plugin);
const currentRecord = ledger.installationForPlugin(plugin);
const sourceReplacementMode = options.sourceReplacementMode ?? 'preserve-existing-source';
if (
@@ -2312,7 +2317,7 @@ export class PluginMarketService {
if (
existing &&
sourceReplacementMode === 'preserve-existing-source' &&
- !serverRecordMatchesInstalledGhost(plugin.id, existing, currentRecord)
+ !serverRecordMatchesInstalledGhost(plugin.id, existing, currentRecord, snapshotManifestIdentity(local, existing))
) {
throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');
}
@@ -3546,6 +3551,7 @@ export class PluginMarketService {
private localInstallSnapshot(
ledger = this.ledger,
installations = ledger.read().installations,
+ ghostId?: string,
): LocalInstallSnapshot {
const ghosts = getGhostManager().list();
const records = Object.values(installations).filter((record) => record.installed);
@@ -3555,7 +3561,7 @@ export class PluginMarketService {
installations,
installedRecordsByGhostId: indexByGhostId(records, (record) => record.ghostId),
manifestIdentityByStoragePart: new Map(
- ghosts.map((ghost) => [
+ ghosts.filter((ghost) => ghostId === undefined || ghost.manifest.id === ghostId).map((ghost) => [
installedGhostStoragePart(ghost),
readInstalledMarketManifestIdentity(ghost.dir),
]),
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index ebaf6a11a0..269414952d 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -41,7 +41,7 @@ import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { toast } from '@/lib/toast';
import { extractIpcError } from '@/utils/ipcError';
import { useAuth } from '@/contexts/AuthContext';
-import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';
+import { readInstalledGhostsSnapshot, useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';
import {
cancelPendingPluginSuggestion,
getPendingPluginSuggestion,
@@ -399,6 +399,13 @@ export function shouldOpenInstalledDetailAfterMarketSuccess(isUpdate: boolean):
return !isUpdate;
}
+function installedGhostMarketKeyFor(ghosts: readonly InstalledGhost[]): string {
+ return ghosts
+ .map((ghost) => `${ghost.manifest.id}\0${ghost.manifest.version}`)
+ .sort()
+ .join('\0');
+}
+
/** 读「忽略本轮更新」的持久值(键按数据归属分桶,见 ignoredRoundStorageKey)。 */
function readIgnoredRound(storageKey: string): string {
try {
@@ -508,11 +515,7 @@ function LocalGhostPluginPage({
const ghosts = useInstalledGhosts();
useMainViewVisibilityRevision();
const installedGhostMarketKey = useMemo(
- () =>
- ghosts
- .map((ghost) => `${ghost.manifest.id}\0${ghost.manifest.version}`)
- .sort()
- .join('\0'),
+ () => installedGhostMarketKeyFor(ghosts),
[ghosts],
);
const installedGhostLocationsKey = ghosts
@@ -575,6 +578,7 @@ function LocalGhostPluginPage({
useState<LegacyGhostRecoveryStatus | null>(null);
const [legacyRecoveryRetrying, setLegacyRecoveryRetrying] = useState(false);
const refreshMarket = useCallback(async (preserveOnError = false) => {
+ installedGhostMarketKeyRef.current = installedGhostMarketKeyFor(readInstalledGhostsSnapshot());
const requestId = ++marketRefreshRequestRef.current;
try {
const snapshot = await window.electronAPI.pluginMarket.snapshot();
@@ -621,11 +625,16 @@ function LocalGhostPluginPage({
});
}, [refreshMarket]);
useEffect(() => {
- if (installedGhostMarketKeyRef.current === installedGhostMarketKey) return;
- installedGhostMarketKeyRef.current = installedGhostMarketKey;
+ if (
+ installedGhostMarketKeyRef.current === installedGhostMarketKey ||
+ marketBusyLockRef.current !== null
+ ) {
+ return;
+ }
// 已装集合或版本变化(装/卸/后台更新)时刷新市场;排序是反应式的。
+ // 安装广播早于市场账本提交;等待事务收尾,由成功刷新消费,失败/取消后补刷。
void refreshMarket(true).catch(() => undefined);
- }, [installedGhostMarketKey, refreshMarket]);
+ }, [installedGhostMarketKey, marketBusyId, refreshMarket]);
const activeSessionWorkingDir = useSyncExternalStore(
subscribeToLastWorkingDir,
getLastWorkingDir,
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
index 7368927a5b..c17e0bff92 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
@@ -265,28 +265,51 @@ describe('plugin page return navigation', () => {
description: 'Refreshed market details after installation',
};
window.electronAPI.ghosts.listSync = () => ({ ghosts: [installed] });
+ const changed = new Set<Parameters<typeof window.electronAPI.ghosts.onChanged>[0]>();
+ window.electronAPI.ghosts.onChanged = (listener) => {
+ changed.add(listener);
+ return () => { changed.delete(listener); };
+ };
+ const snapshot = vi.fn(window.electronAPI.pluginMarket.snapshot);
+ window.electronAPI.pluginMarket.snapshot = snapshot;
let installationComplete = false;
loadDetail.mockImplementation(async () =>
installationComplete ? refreshedDetail : marketDetail,
);
+ let finishInstall!: () => void;
+ const committed = new Promise<void>((resolve) => { finishInstall = resolve; });
const install = vi.fn(async () => {
+ const ghost = { ...installed, manifest: { ...installed.manifest, version: detail.version } };
+ changed.forEach((listener) => listener({ ghosts: [ghost] }));
+ await committed;
installationComplete = true;
return {
- ghost: { ...installed, manifest: { ...installed.manifest, version: detail.version } },
+ ghost,
};
});
Object.assign(window.electronAPI.pluginMarket, { install });
render(page(`/plugins?market=${detail.pluginId}`));
await screen.findByRole('heading', { level: 1, name: detail.name });
const marketPage = screen.getByRole('main');
-
- fireEvent.click(screen.getByRole('button', {
- name: installState === 'conflict'
- ? 'settings.ghosts.market.replace'
- : 'settings.ghosts.market.update',
- }));
+ const snapshotsBeforeInstall = snapshot.mock.calls.length;
+
+ try {
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', {
+ name: installState === 'conflict'
+ ? 'settings.ghosts.market.replace'
+ : 'settings.ghosts.market.update',
+ }));
+ });
+ // The roster arrives before market provenance commits. Reading it here
+ // caused an extra full scan and could expose a transient source conflict.
+ expect(snapshot).toHaveBeenCalledTimes(snapshotsBeforeInstall);
+ } finally {
+ await act(async () => { finishInstall(); });
+ }
await screen.findByText(refreshedDetail.description!);
+ expect(snapshot).toHaveBeenCalledTimes(snapshotsBeforeInstall + 1);
expect(install).toHaveBeenCalledWith(detail.pluginId, expect.objectContaining({
expectedReleaseId: detail.releaseId,
expectedManifest: detail.manifest,
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index d12c88f962..dd68eb0dd6 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -309,6 +309,10 @@ Library 请求同时绑定迁移代次和安装批准,根解析、排队及开
网络失败与安装包异常;服务端负责包体大小发布准入,客户端保留防御校验而不另设体积提示。
实现与回归见 `apps/desktop/src/main/plugin-market/download.ts` 及同目录的
`__tests__/download.test.ts`。
+- 同一安装流程的同步预检可以复用一次已装清单扫描;跨下载、用户确认或异步等待后,
+ 目标安装、批准状态与锁内提交仍须重新核对,不能缓存批准结果。`inspect` 与安装可在
+ 60 秒内复用一份不超过 8 MiB 的包解析结果,但每次必须稳定重读完整源文件并核对
+ SHA-256、宿主语言与信任表;返回的清单与缓存隔离,不能只凭路径或修改时间复用。
- Host receipt 是安装事务和运行完整性的状态记录,不是一次交互式“能力授权”。合法的安装/更新
事务(已按上文求得确认)写入 receipt,钉住 canonical manifest、trust、启停态与随机 `revision`;
`ghostInstallApprovalToken()` 只是 Renderer 与 Main 之间防止并发漂移的前置条件,不是权限凭证。