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): 收口插件市场安装与来源隔离 (#2043)

GaoWei Liu3fce01d49083
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 9c4f8c67fa..2d65d685d6 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -828,7 +828,12 @@ export class GhostManager {
*/
async update(
lizFilePath: string,
- opts?: { expectedPackageSha256?: string; trustOverride?: GhostHostTrustOverride },
+ opts?: {
+ expectedPackageSha256?: string;
+ trustOverride?: GhostHostTrustOverride;
+ /** 目录换位完成后、任何通知或运行时收尾前触发。 */
+ onPackagePlaced?: () => void;
+ },
): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {
const parsed = await this.parse(lizFilePath);
if ('rejection' in parsed) return parsed;
@@ -925,6 +930,7 @@ export class GhostManager {
trust,
...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
};
+ opts?.onPackagePlaced?.();
this.options.log?.info('ghost updated', { id: manifest.id, version: manifest.version });
this.options.onChanged?.(this.list());
return { ghost };
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 c1938dcfc2..9991aad66e 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -731,13 +731,18 @@ describe('GhostManager · update(原位换版)', () => {
{ ...goodManifest(), version: '2.0.0' },
{ 'new.txt': 'v2' },
);
- const result = await manager.update(v2);
+ const onPackagePlaced = vi.fn();
+ const result = await manager.update(v2, { onPackagePlaced });
expect('ghost' in result, JSON.stringify(result)).toBe(true);
const { ghost } = result as { ghost: InstalledGhost };
expect(ghost.manifest.version).toBe('2.0.0');
expect(ghost.dir).toBe(path.join(rootDir, 'hello'));
expect(fs.existsSync(path.join(rootDir, 'hello', 'new.txt'))).toBe(true);
expect(fs.existsSync(path.join(rootDir, 'hello', 'old.txt'))).toBe(false); // 换版不留旧文件
+ expect(onPackagePlaced).toHaveBeenCalledTimes(1);
+ expect(onPackagePlaced.mock.invocationCallOrder[0]).toBeLessThan(
+ onChanged.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY,
+ );
expect(onChanged).toHaveBeenCalledTimes(1);
// 备份/staging 临时目录不残留。
const leftovers = fs.readdirSync(rootDir).filter((n) => n.startsWith('.cindy-'));
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 37ab2baf44..b2fe650cf9 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
@@ -59,6 +59,51 @@ describe('market Ghost session boundary', () => {
expect(body).toContain('releaseMutation?.();');
});
+ it('allows explicit local replacement and detaches market routing before landing', () => {
+ const updateStart = source.indexOf(
+ "ipcMain.handle('ghosts:update'",
+ );
+ const updateEnd = source.indexOf(
+ "ipcMain.handle('ghosts:pick-file'",
+ updateStart,
+ );
+ const body = source.slice(updateStart, updateEnd);
+
+ const ledgerReadIndex = body.indexOf(
+ 'marketLedger.installationForGhost(inspected.manifest.id)',
+ );
+ const captureIndex = body.indexOf('const mutationOwner = captureGhostMutationOwner();');
+ const ledgerBindIndex = body.indexOf('const marketLedger = getPluginMarketLedger().bind(');
+ const inspectIndex = body.indexOf('await manager.inspect(lizFilePath)');
+ const leaseIndex = body.indexOf('const releaseMutation = beginGhostMutation(mutationOwner);');
+ const detachDecisionIndex = body.indexOf(
+ 'const detachMarketRecord = Boolean(marketRecord?.installed)',
+ );
+ const runtimeStopIndex = body.indexOf('runtime.stop(inspected.manifest.id)');
+ const managerUpdateIndex = body.indexOf('result = await manager.update(');
+ const detachIndex = body.indexOf(
+ 'marketLedger.markRemoved(inspected.manifest.id, marketInstallSubject)',
+ );
+
+ expect(captureIndex).toBeGreaterThan(-1);
+ expect(ledgerBindIndex).toBeGreaterThan(captureIndex);
+ expect(ledgerBindIndex).toBeLessThan(inspectIndex);
+ expect(leaseIndex).toBeGreaterThan(inspectIndex);
+ expect(ledgerReadIndex).toBeGreaterThan(leaseIndex);
+ expect(detachDecisionIndex).toBeGreaterThan(ledgerReadIndex);
+ expect(detachIndex).toBeGreaterThan(detachDecisionIndex);
+ expect(runtimeStopIndex).toBeGreaterThan(detachIndex);
+ expect(managerUpdateIndex).toBeGreaterThan(runtimeStopIndex);
+ expect(body).toContain('marketLedger.isDefaultInstallSuppressed(');
+ expect(body).toContain('marketLedger.restoreInstallation(');
+ expect(body).toContain('suppressed: marketRecordWasSuppressed');
+ expect(body).toContain('onPackagePlaced: () => {');
+ expect(body).toContain('packagePlaced = true;');
+ expect(body).toContain('if (!packagePlaced) {\n restoreMarketRecord();');
+ expect(body).toContain('releaseMutation();');
+ expect(body).not.toContain('GHOST_SOURCE_CONFLICT');
+ });
+
it('runs the final market callback before both initial install and update placement', () => {
const installStart = source.indexOf(
'async function installOrUpdateMarketGhostPackageLocked(',
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 0fac6ca5b6..c49f1e09cf 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -45,7 +45,10 @@ import {
type GhostVideoResultParams,
type InstalledGhost,
} from '../../shared/ghost.js';
-import type { PluginMarketPackageReviewFacts } from '../../shared/pluginMarket.js';
+import type {
+ PluginMarketItemSource,
+ PluginMarketPackageReviewFacts,
+} from '../../shared/pluginMarket.js';
import { getAppCapabilities } from '../appCapabilities.js';
import {
activeOwnerScopeKey,
@@ -78,7 +81,12 @@ import {
recordBuiltinTombstone,
type ProvisionIdentity,
} from './builtinGhostProvisioner.js';
-import { getAccessToken, getAuthState, onAuthStateChange } from '../authManager.js';
+import {
+ getAccessToken,
+ getAuthState,
+ getCurrentUserId,
+ onAuthStateChange,
+} from '../authManager.js';
import { serverApiFetch } from '../serverApiClient.js';
import { getClientEndpoint } from '../clientEndpointsService.js';
import { createGhostOauthBrokerClient } from './ghostOauthBroker.js';
@@ -236,7 +244,11 @@ import { getGhostGrantConfirmBridge } from './ghostGrantConfirmBridge.js';
import { getSessionFsSnapshot } from '../localDb/ipc/sessions.js';
import { getDirDepositVault, getSaveDepositVault, isPathInsideDir } from './dirDeposit.js';
import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';
-import { ghostManifestDigest, PluginMarketLedger } from '../plugin-market/ledger.js';
+import {
+ ghostManifestDigest,
+ PluginMarketLedger,
+ type PluginMarketInstallationRecord,
+} from '../plugin-market/ledger.js';
import {
GhostSubscriptionGateway,
GhostActivityTracker,
@@ -3836,16 +3848,20 @@ export async function installOrUpdateMarketGhostPackage(
ghostId: string;
version: string;
/**
- * 安装前实际展示给用户的 manifest。真实包若声明了未展示权限,会在
- * 落盘前暂停并把同一份已验证包交给上层复核。
+ * 手动首装确认真实包、同来源更新仅在真实包扩权时确认;默认安装只把
+ * 市场目录 manifest 当作 fail-closed 权限上限。目录 manifest 不记作批准。
*/
- reviewedManifest?: GhostManifest;
- /** 经来源账本摘要认证的已装清单;缺失时不得回退到可变运行时清单。 */
+ permissionPolicy?:
+ | { mode: 'manual'; sourceType: PluginMarketItemSource }
+ | { mode: 'cap'; manifest: GhostManifest; sourceType: PluginMarketItemSource };
+ /** 安装锁内从当前已落位包读取的 canonical 权限基线。 */
permissionBaselineManifest?: GhostManifest;
/** 用户确认过的真实下载包 SHA 与确认时的已装权限基线。 */
approvedPackageSha256?: string;
reviewedBaseline?: string;
beforeCommitInLock?: () => void;
+ /** 新包已经原子换位;后续异常不能再按落位失败回滚来源路由。 */
+ onPackagePlacedInLock?: () => void;
/** 仅 server-market 主机路径可传;custom/local 不传。 */
officialCindyGithub?: boolean;
},
@@ -3863,11 +3879,15 @@ async function installOrUpdateMarketGhostPackageLocked(
expected: {
ghostId: string;
version: string;
- reviewedManifest?: GhostManifest;
+ permissionPolicy?:
+ | { mode: 'manual'; sourceType: PluginMarketItemSource }
+ | { mode: 'cap'; manifest: GhostManifest; sourceType: PluginMarketItemSource };
permissionBaselineManifest?: GhostManifest;
approvedPackageSha256?: string;
reviewedBaseline?: string;
beforeCommitInLock?: () => void;
+ /** 新包已经原子换位;后续异常不能再按落位失败回滚来源路由。 */
+ onPackagePlacedInLock?: () => void;
officialCindyGithub?: boolean;
},
): Promise<InstalledGhost> {
@@ -3890,7 +3910,7 @@ async function installOrUpdateMarketGhostPackageLocked(
: undefined;
requireGhostAvailableForActiveSession(expected.ghostId);
const installed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);
- if (expected.reviewedManifest) {
+ if (expected.permissionPolicy) {
const baselineManifest = expected.permissionBaselineManifest ?? null;
const installedBaseline = baselineManifest
? ghostPermissionBaselineKey(baselineManifest)
@@ -3906,27 +3926,40 @@ async function installOrUpdateMarketGhostPackageLocked(
'Downloaded Plugin package changed after permission review',
);
}
- const unreviewed = unreviewedGhostPermissionItems(
- expected.reviewedManifest,
- baselineManifest ?? undefined,
- inspected.canonicalManifest,
- );
- if (unreviewed.length > 0) {
+ const permissionDiff = baselineManifest
+ ? diffGhostPermissionItems(baselineManifest, inspected.canonicalManifest)
+ : null;
+ const unreviewed =
+ expected.permissionPolicy.mode === 'cap'
+ ? unreviewedGhostPermissionItems(
+ expected.permissionPolicy.manifest,
+ baselineManifest ?? undefined,
+ inspected.canonicalManifest,
+ )
+ : [];
+ const needsReview =
+ expected.permissionPolicy.mode === 'manual'
+ ? permissionDiff === null || permissionDiff.added.length > 0
+ : unreviewed.length > 0;
+ if (needsReview && expected.approvedPackageSha256 === undefined) {
+ const reviewKeys =
+ expected.permissionPolicy.mode === 'manual'
+ ? (permissionDiff?.added.map((item) => item.key) ?? [])
+ : unreviewed.map((item) => item.key);
const review: PluginMarketPackageReviewFacts = {
manifest: inspected.manifest,
- permissionDiff: baselineManifest
- ? diffGhostPermissionItems(baselineManifest, inspected.canonicalManifest)
- : null,
+ permissionDiff,
+ isUpdate: installed !== undefined,
packageSha256: inspected.packageSha256,
installedBaseline,
+ sourceType: expected.permissionPolicy.sourceType,
};
- if (expected.approvedPackageSha256 === undefined) {
- log.info('market package requires permission review', {
- ghostId: expected.ghostId,
- keys: unreviewed.map((item) => item.key),
- });
- throw new GhostPackagePermissionReviewRequiredError(review);
- }
+ log.info('market package requires permission review', {
+ ghostId: expected.ghostId,
+ mode: expected.permissionPolicy.mode,
+ keys: reviewKeys,
+ });
+ throw new GhostPackagePermissionReviewRequiredError(review);
}
}
rejectUnauthorizedTokenBroker(inspected.canonicalManifest);
@@ -3963,15 +3996,29 @@ async function installOrUpdateMarketGhostPackageLocked(
getGhostAgentSlot().clearGhost(expected.ghostId);
getGhostErrandSlot().clearGhost(expected.ghostId);
let result: Awaited<ReturnType<typeof manager.update>>;
+ let packagePlaced = false;
try {
// 与首装分支同一口径:钉住 inspect 时校验过的包字节(见上)。
result = await manager.update(cindyFilePath, {
expectedPackageSha256: inspected.packageSha256,
...(trustOverride ? { trustOverride } : {}),
+ onPackagePlaced: () => {
+ packagePlaced = true;
+ expected.onPackagePlacedInLock?.();
+ },
});
} catch (error) {
- spawnIfResident(installed);
- throw error;
+ if (!packagePlaced) {
+ spawnIfResident(installed);
+ throw error;
+ }
+ const placed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);
+ if (!placed) throw error;
+ log.warn('market ghost post-placement notification failed', {
+ ghostId: expected.ghostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ result = { ghost: placed };
}
if ('rejection' in result) {
spawnIfResident(installed);
@@ -5219,6 +5266,10 @@ export function registerGhostIpc(): void {
) {
throwIpcError('INVALID_PARAMS', 'expectedPackageSha256 must come from ghosts:inspect');
}
+ const mutationOwner = captureGhostMutationOwner();
+ const marketLedger = getPluginMarketLedger().bind(
+ ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'),
+ );
const inspected = await manager.inspect(lizFilePath);
if ('rejection' in inspected) throwInstallError(inspected.rejection);
assertGhostSupportsCurrentCindy(inspected.canonicalManifest);
@@ -5230,37 +5281,122 @@ export function registerGhostIpc(): void {
// 与市场装入/本地装入/卸载共用按 ghostId 的互斥:换目录期间同 id 的其它
// 装入/卸载不得插入(否则并发装入会与本次 rename 竞争、留下不一致态)。
return withGhostInstallLock(inspected.manifest.id, async () => {
- const previousGhost = manager.list().find((g) => g.manifest.id === inspected.manifest.id);
- runtime.stop(inspected.manifest.id);
- getGhostNodeRuntimeBroker().stop(inspected.manifest.id);
- getGhostAgentSlot().clearGhost(inspected.manifest.id);
- getGhostErrandSlot().clearGhost(inspected.manifest.id);
- let result: Awaited<ReturnType<typeof manager.update>>;
+ const releaseMutation = beginGhostMutation(mutationOwner);
try {
- result = await manager.update(lizFilePath, { expectedPackageSha256 });
- } catch (err) {
- // 更新失败:恢复旧版本的常驻 Node 工作进程(如果是 resident 且已启用)
- if (previousGhost) spawnIfResident(previousGhost);
- throw err;
- }
- if ('rejection' in result) {
- if (previousGhost) spawnIfResident(previousGhost);
- throwInstallError(result.rejection);
- }
- runtime.resetFuse(inspected.manifest.id); // 换了代码,给新版本干净的熔断记账
- const store = getLayoutStore();
- const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);
- if (docked) {
- const applied = store.setLayout(docked);
- if ('rejection' in applied) {
- log.warn('ghost panel dock rejected', {
- id: result.ghost.manifest.id,
- reason: applied.rejection,
+ const previousGhost = manager.list().find((g) => g.manifest.id === inspected.manifest.id);
+ let marketRecord: PluginMarketInstallationRecord | null;
+ let marketInstallSubject: string | null = null;
+ let marketRecordWasSuppressed = false;
+ try {
+ marketRecord = marketLedger.installationForGhost(inspected.manifest.id);
+ if (
+ marketRecord?.installed &&
+ (marketRecord.source === 'market' || marketRecord.source === 'legacy-adopted')
+ ) {
+ marketInstallSubject = getCurrentUserId() ?? mutationOwner.dataOwnerId;
+ marketRecordWasSuppressed = marketInstallSubject
+ ? marketLedger.isDefaultInstallSuppressed(
+ marketInstallSubject,
+ marketRecord.pluginId,
+ )
+ : false;
+ }
+ } catch (error) {
+ log.warn('failed to verify Plugin provenance before local update', {
+ ghostId: inspected.manifest.id,
+ error: error instanceof Error ? error.message : String(error),
});
+ throwIpcError('INTERNAL', 'Unable to verify the installed Plugin source');
+ }
+ // 用户已在本地包确认流程中明确选择了这份真实包:同 id 可以原位替换,
+ // 市场来源不是永久所有权。替换前先切断旧市场更新路由;落位失败再恢复,
+ // 全程不清理 Secret、KV、偏好或其它按 ghostId 保存的用户状态。
+ const detachMarketRecord = Boolean(marketRecord?.installed);
+ const restoreMarketRecord = (): void => {
+ if (!detachMarketRecord || !marketRecord) return;
+ try {
+ marketLedger.restoreInstallation(
+ marketRecord,
+ marketInstallSubject
+ ? {
+ userId: marketInstallSubject,
+ suppressed: marketRecordWasSuppressed,
+ }
+ : undefined,
+ );
+ } catch (error) {
+ // 恢复失败时保持路由失效是安全降级:不能让旧市场自动覆盖用户
+ // 明确选择的本地包。用户仍可从任一市场显式替换同 ID 插件。
+ log.error('failed to restore Plugin market provenance after local update failure', {
+ ghostId: inspected.manifest.id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ };
+ if (detachMarketRecord) {
+ try {
+ // 先持久化切断自动更新路由,再改真实包。账本不可写时不触碰包,
+ // 避免同 manifest 的本地代码被旧市场静默覆盖。
+ marketLedger.markRemoved(inspected.manifest.id, marketInstallSubject);
+ } catch (error) {
+ restoreMarketRecord();
+ log.warn('failed to detach Plugin market provenance before local update', {
+ ghostId: inspected.manifest.id,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ throwIpcError('INTERNAL', 'Unable to detach the installed Plugin source');
+ }
+ }
+ runtime.stop(inspected.manifest.id);
+ getGhostNodeRuntimeBroker().stop(inspected.manifest.id);
+ getGhostAgentSlot().clearGhost(inspected.manifest.id);
+ getGhostErrandSlot().clearGhost(inspected.manifest.id);
+ let result: Awaited<ReturnType<typeof manager.update>>;
+ let packagePlaced = false;
+ try {
+ result = await manager.update(lizFilePath, {
+ expectedPackageSha256,
+ onPackagePlaced: () => {
+ packagePlaced = true;
+ },
+ });
+ } catch (err) {
+ if (!packagePlaced) {
+ restoreMarketRecord();
+ // 更新失败:恢复旧版本的常驻 Node 工作进程(如果是 resident 且已启用)
+ if (previousGhost) spawnIfResident(previousGhost);
+ throw err;
+ }
+ const placed = manager.list().find((ghost) => ghost.manifest.id === inspected.manifest.id);
+ if (!placed) throw err;
+ log.warn('local ghost post-placement notification failed', {
+ ghostId: inspected.manifest.id,
+ error: err instanceof Error ? err.message : String(err),
+ });
+ result = { ghost: placed };
+ }
+ if ('rejection' in result) {
+ restoreMarketRecord();
+ if (previousGhost) spawnIfResident(previousGhost);
+ throwInstallError(result.rejection);
+ }
+ runtime.resetFuse(inspected.manifest.id); // 换了代码,给新版本干净的熔断记账
+ const store = getLayoutStore();
+ const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);
+ if (docked) {
+ const applied = store.setLayout(docked);
+ if ('rejection' in applied) {
+ log.warn('ghost panel dock rejected', {
+ id: result.ghost.manifest.id,
+ reason: applied.rejection,
+ });
+ }
}
+ spawnIfResident(result.ghost); // 常驻意识:换完代码立即用新版本点火
+ return { ghost: result.ghost };
+ } finally {
+ releaseMutation();
}
- spawnIfResident(result.ghost); // 常驻意识:换完代码立即用新版本点火
- return { ghost: result.ghost };
});
});
diff --git a/apps/desktop/src/main/plugin-market/__tests__/api.test.ts b/apps/desktop/src/main/plugin-market/__tests__/api.test.ts
index 3edb4b5b7f..07310109f5 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/api.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/api.test.ts
@@ -88,6 +88,7 @@ describe('PluginMarketApi', () => {
expect(fetcher.mock.calls[1]?.[0]).toContain(`cursor=${PLUGIN_A}`);
expect(fetcher.mock.calls[0]?.[1]).toMatchObject({
headers: { 'x-cindy-version': '1.2.3' },
+ timeoutMs: 15_000,
});
});
diff --git a/apps/desktop/src/main/plugin-market/__tests__/download.test.ts b/apps/desktop/src/main/plugin-market/__tests__/download.test.ts
index 5b7e9d4582..f382bcc64f 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/download.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/download.test.ts
@@ -48,7 +48,11 @@ describe('downloadVerifiedPlugin', () => {
expect(fs.readFileSync(file)).toEqual(bytes);
expect(fetchMock).toHaveBeenCalledWith(
'https://downloads.example.test/a',
- expect.objectContaining({ redirect: 'error', cache: 'no-store' }),
+ expect.objectContaining({
+ redirect: 'error',
+ cache: 'no-store',
+ signal: expect.any(AbortSignal),
+ }),
);
});
diff --git a/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts b/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts
index 9913fad503..1ac6b70f5a 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts
@@ -15,9 +15,19 @@ vi.mock('electron', () => ({
}));
const brain = vi.hoisted(() => ({
- installOrUpdateMarketGhostPackage: vi.fn(async () => ({}) as never),
+ installOrUpdateMarketGhostPackage: vi.fn(
+ async (filePath: string, options: unknown) => {
+ if (filePath.length === 0 || options === undefined) throw new Error('invalid install call');
+ return {} as never;
+ },
+ ),
rejectReservedGhostIdForCustomMarket: vi.fn(),
- packGhostDirToFile: vi.fn(async () => ({ ok: true as const, manifest: {} })),
+ packGhostDirToFile: vi.fn(
+ async (_pluginDir: string, _tempPath: string, _expectedRoot: string) => ({
+ ok: true as const,
+ manifest: {},
+ }),
+ ),
}));
vi.mock('../../cindy-brain/index.js', () => ({
installOrUpdateMarketGhostPackage: brain.installOrUpdateMarketGhostPackage,
@@ -31,8 +41,9 @@ vi.mock('../../logger.js', () => ({ createLogger: () => logger }));
import type { GhostManifest } from '../../../shared/ghost.js';
import { installCustomMarketPlugin } from '../install';
+import { GhostPackagePermissionReviewRequiredError } from '../../cindy-brain/packagePermissionReview';
-const GOOD_MANIFEST = {
+const GOOD_MANIFEST: GhostManifest = {
schemaVersion: 2,
id: 'demo',
name: '演示插件',
@@ -42,12 +53,26 @@ const GOOD_MANIFEST = {
slots: ['tool'],
tools: [{ name: 'do_thing', description: '做点事' }],
};
+const GOOD_IDENTITY = {
+ expectedGhostId: GOOD_MANIFEST.id,
+ expectedVersion: GOOD_MANIFEST.version,
+};
let workDir: string;
beforeEach(async () => {
workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-market-install-'));
- brain.packGhostDirToFile.mockClear();
+ brain.packGhostDirToFile.mockReset();
+ brain.packGhostDirToFile.mockResolvedValue({
+ ok: true as const,
+ manifest: GOOD_MANIFEST,
+ });
+ brain.installOrUpdateMarketGhostPackage.mockReset();
+ brain.installOrUpdateMarketGhostPackage.mockResolvedValue({
+ manifest: GOOD_MANIFEST,
+ dir: path.join(workDir, 'installed'),
+ enabled: true,
+ } as never);
logger.warn.mockClear();
});
@@ -69,7 +94,8 @@ describe('installCustomMarketPlugin · 身份卡读取闸', () => {
await expect(
installCustomMarketPlugin({
pluginDir,
- expected: GOOD_MANIFEST as unknown as GhostManifest,
+ ...GOOD_IDENTITY,
+ sourceType: 'local-market',
}),
).rejects.toMatchObject({ code: 'GHOST_FILE_INVALID' });
expect(brain.packGhostDirToFile).not.toHaveBeenCalled();
@@ -89,12 +115,35 @@ describe('installCustomMarketPlugin · 身份卡读取闸', () => {
await expect(
installCustomMarketPlugin({
pluginDir,
- expected: GOOD_MANIFEST as unknown as GhostManifest,
+ ...GOOD_IDENTITY,
+ sourceType: 'local-market',
}),
).rejects.toMatchObject({ code: 'GHOST_FILE_INVALID' });
expect(brain.packGhostDirToFile).not.toHaveBeenCalled();
});
+ it('目录身份在发现后变化 → 拒绝安装另一个插件', async () => {
+ const pluginDir = path.join(workDir, 'plugin-changed-identity');
+ await fs.promises.mkdir(pluginDir, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(pluginDir, 'ghost.json'),
+ JSON.stringify({ ...GOOD_MANIFEST, id: 'other-plugin', version: '2.0.0' }),
+ );
+
+ await expect(
+ installCustomMarketPlugin({
+ pluginDir: await fs.promises.realpath(pluginDir),
+ ...GOOD_IDENTITY,
+ sourceType: 'local-market',
+ }),
+ ).rejects.toMatchObject({
+ code: 'PRECONDITION_FAILED',
+ message: expect.stringContaining('identity changed'),
+ });
+ expect(brain.packGhostDirToFile).not.toHaveBeenCalled();
+ expect(brain.installOrUpdateMarketGhostPackage).not.toHaveBeenCalled();
+ });
+
it('把已校验的规范根同时作为打包输入与打包器锚点传下去', async () => {
// 契约用例:锚点必须是**本层校验过的那个规范根**,不能是任何别的字符串
// (第三个参数是必填的,TS 只能保证"传了",保证不了"传对";传成 tempPath
@@ -115,7 +164,8 @@ describe('installCustomMarketPlugin · 身份卡读取闸', () => {
await installCustomMarketPlugin({
pluginDir: canonical,
- expected: GOOD_MANIFEST as unknown as GhostManifest,
+ ...GOOD_IDENTITY,
+ sourceType: 'local-market',
});
expect(brain.packGhostDirToFile).toHaveBeenCalledWith(
@@ -125,6 +175,141 @@ describe('installCustomMarketPlugin · 身份卡读取闸', () => {
);
});
+ it('首装确认与提交复用同一个真实临时包', async () => {
+ const pluginDir = path.join(workDir, 'plugin-review');
+ await fs.promises.mkdir(pluginDir, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(pluginDir, 'ghost.json'),
+ JSON.stringify(GOOD_MANIFEST),
+ );
+ const canonical = await fs.promises.realpath(pluginDir);
+ const review = {
+ manifest: GOOD_MANIFEST,
+ permissionDiff: null,
+ isUpdate: false,
+ packageSha256: 'a'.repeat(64),
+ installedBaseline: null,
+ sourceType: 'local-market' as const,
+ };
+ brain.packGhostDirToFile.mockImplementationOnce(async (_pluginDir, tempPath) => {
+ await fs.promises.writeFile(tempPath, 'verified-package');
+ return { ok: true as const, manifest: GOOD_MANIFEST };
+ });
+ let resolveCommit!: () => void;
+ const allowCommit = new Promise<void>((resolve) => {
+ resolveCommit = resolve;
+ });
+ let resolveCommitStarted!: () => void;
+ const commitStarted = new Promise<void>((resolve) => {
+ resolveCommitStarted = resolve;
+ });
+ let reviewedTempPath = '';
+ brain.installOrUpdateMarketGhostPackage
+ .mockRejectedValueOnce(new GhostPackagePermissionReviewRequiredError(review))
+ .mockImplementationOnce(async (tempPath: string) => {
+ reviewedTempPath = tempPath;
+ resolveCommitStarted();
+ await allowCommit;
+ expect(fs.existsSync(tempPath)).toBe(true);
+ return {
+ manifest: GOOD_MANIFEST,
+ dir: path.join(workDir, 'installed'),
+ enabled: true,
+ } as never;
+ });
+ const reviewer = vi.fn(async () => true);
+ const afterCommit = vi.fn(async () => undefined);
+
+ const installing = installCustomMarketPlugin({
+ pluginDir: canonical,
+ ...GOOD_IDENTITY,
+ sourceType: 'local-market',
+ reviewPackagePermissions: reviewer,
+ afterCommit,
+ });
+ await commitStarted;
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(fs.existsSync(reviewedTempPath)).toBe(true);
+ resolveCommit();
+ await installing;
+
+ expect(reviewer).toHaveBeenCalledWith(review);
+ expect(brain.installOrUpdateMarketGhostPackage).toHaveBeenCalledTimes(2);
+ const [reviewPath] = brain.installOrUpdateMarketGhostPackage.mock.calls[0] ?? [];
+ const [commitPath, commitOptions] =
+ brain.installOrUpdateMarketGhostPackage.mock.calls[1] ?? [];
+ expect(commitPath).toBe(reviewPath);
+ expect(commitOptions).toMatchObject({
+ ghostId: GOOD_IDENTITY.expectedGhostId,
+ version: GOOD_IDENTITY.expectedVersion,
+ approvedPackageSha256: review.packageSha256,
+ permissionPolicy: { mode: 'manual', sourceType: 'local-market' },
+ });
+ expect(afterCommit).toHaveBeenCalledWith(
+ expect.objectContaining({ manifest: GOOD_MANIFEST }),
+ GOOD_MANIFEST,
+ );
+ expect(fs.existsSync(String(commitPath))).toBe(false);
+ });
+
+ it('同来源无扩权更新直接提交,不制造额外确认状态', async () => {
+ const pluginDir = path.join(workDir, 'plugin-update');
+ await fs.promises.mkdir(pluginDir, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(pluginDir, 'ghost.json'),
+ JSON.stringify(GOOD_MANIFEST),
+ );
+ const reviewer = vi.fn(async () => true);
+
+ await installCustomMarketPlugin({
+ pluginDir: await fs.promises.realpath(pluginDir),
+ ...GOOD_IDENTITY,
+ sourceType: 'local-market',
+ permissionBaselineManifest: GOOD_MANIFEST,
+ reviewPackagePermissions: reviewer,
+ });
+
+ expect(brain.installOrUpdateMarketGhostPackage).toHaveBeenCalledTimes(1);
+ expect(reviewer).not.toHaveBeenCalled();
+ });
+
+ it('用户关闭真实包确认后立即取消并清理临时包', async () => {
+ const pluginDir = path.join(workDir, 'plugin-cancel');
+ await fs.promises.mkdir(pluginDir, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(pluginDir, 'ghost.json'),
+ JSON.stringify(GOOD_MANIFEST),
+ );
+ const review = {
+ manifest: GOOD_MANIFEST,
+ permissionDiff: null,
+ isUpdate: false,
+ packageSha256: 'b'.repeat(64),
+ installedBaseline: null,
+ sourceType: 'local-market' as const,
+ };
+ brain.installOrUpdateMarketGhostPackage.mockRejectedValueOnce(
+ new GhostPackagePermissionReviewRequiredError(review),
+ );
+ const reviewer = vi.fn(async () => false);
+ const afterCommit = vi.fn(async () => undefined);
+
+ const result = await installCustomMarketPlugin({
+ pluginDir: await fs.promises.realpath(pluginDir),
+ ...GOOD_IDENTITY,
+ sourceType: 'local-market',
+ reviewPackagePermissions: reviewer,
+ afterCommit,
+ });
+
+ expect(result).toBeNull();
+ expect(reviewer).toHaveBeenCalledWith(review);
+ expect(brain.installOrUpdateMarketGhostPackage).toHaveBeenCalledTimes(1);
+ expect(afterCommit).not.toHaveBeenCalled();
+ const [tempPath] = brain.installOrUpdateMarketGhostPackage.mock.calls[0] ?? [];
+ expect(fs.existsSync(String(tempPath))).toBe(false);
+ });
+
it.runIf(process.platform !== 'win32')(
'发现后插件目录被换成指向市场外的符号链接 → 拒绝,不进入打包',
async () => {
@@ -154,7 +339,8 @@ describe('installCustomMarketPlugin · 身份卡读取闸', () => {
await expect(
installCustomMarketPlugin({
pluginDir: discovered, // 传发现时的规范路径
- expected: GOOD_MANIFEST as unknown as GhostManifest,
+ ...GOOD_IDENTITY,
+ sourceType: 'local-market',
}),
).rejects.toMatchObject({
code: 'GHOST_FILE_INVALID',
@@ -176,7 +362,8 @@ describe('installCustomMarketPlugin · 身份卡读取闸', () => {
await expect(
installCustomMarketPlugin({
pluginDir: await fs.promises.realpath(pluginDir),
- expected: GOOD_MANIFEST as unknown as GhostManifest,
+ ...GOOD_IDENTITY,
+ sourceType: 'local-market',
}),
).rejects.toMatchObject({
code: 'GHOST_FILE_INVALID',
diff --git a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
index 6a43f8e3fd..a5a7614544 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
@@ -21,6 +21,10 @@ describe('Plugin Market IPC error boundary', () => {
resolve(process.cwd(), 'src/main/bootstrap-electron.ts'),
'utf8',
).replace(/\r\n/g, '\n');
+ const ghostPluginPageSource = readFileSync(
+ resolve(process.cwd(), 'src/renderer/features/plugin/GhostPluginPage.tsx'),
+ 'utf8',
+ ).replace(/\r\n/g, '\n');
it('preserves structured errors and normalizes unexpected failures', () => {
const start = registerSource.indexOf('async function invokePluginMarket');
@@ -90,11 +94,21 @@ describe('Plugin Market IPC error boundary', () => {
expect(syncBody).toContain('await snapshotAndSignalRemovalNotice();');
expect(syncBody).toContain("log.warn('default plugin startup sync failed'");
- const snapshotStart = registerSource.indexOf('async function snapshotAndSignalRemovalNotice()');
+ const snapshotStart = registerSource.indexOf(
+ 'async function snapshotAndSignalRemovalNotice(options?: PluginMarketSnapshotOptions)',
+ );
const snapshotEnd = registerSource.indexOf('\n}\n\n/**', snapshotStart);
const snapshotBody = registerSource.slice(snapshotStart, snapshotEnd);
expect(snapshotBody).toContain('finally {');
expect(snapshotBody).toContain('signalRemovalNoticeAvailable();');
+ expect(snapshotBody).toContain('signalUpgradeNoticeAvailable();');
+
+ expect(registerSource).toContain('deferDefaultReconciliation: true');
+ expect(registerSource).toContain('onDeferredReconciliationSettled: () => {');
+ expect(ghostPluginPageSource).toContain(
+ 'window.electronAPI.pluginMarket.onUpgradeNoticeAvailable(() => {',
+ );
+ expect(ghostPluginPageSource).toContain('void refreshMarket(true).catch(() => undefined);');
const ownerSyncStart = bootstrapSource.indexOf(
'function syncDefaultPluginsForActiveOwner(): void',
diff --git a/apps/desktop/src/main/plugin-market/__tests__/packagePermissionReviewBridge.test.ts b/apps/desktop/src/main/plugin-market/__tests__/packagePermissionReviewBridge.test.ts
index a630cd405f..e3995a0c17 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/packagePermissionReviewBridge.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/packagePermissionReviewBridge.test.ts
@@ -14,21 +14,26 @@ const facts: PluginMarketPackageReviewFacts = {
slots: ['notify'],
},
permissionDiff: null,
+ isUpdate: true,
packageSha256: 'a'.repeat(64),
installedBaseline: null,
+ sourceType: 'server',
};
+const ownerStamp = { dataOwnerId: 'owner-a', ownerGeneration: 7 };
describe('PluginMarketPackagePermissionReviewBridge', () => {
it('only accepts the answer from the requesting window and hides approval bindings', async () => {
const bridge = new PluginMarketPackagePermissionReviewBridge();
- let request: Parameters<Parameters<typeof bridge.request>[2]>[0] | undefined;
- const decision = bridge.request(7, facts, (next) => {
+ let request: Parameters<Parameters<typeof bridge.request>[3]>[0] | undefined;
+ const decision = bridge.request(7, facts, ownerStamp, (next) => {
request = next;
return true;
});
expect(request).not.toHaveProperty('packageSha256');
expect(request).not.toHaveProperty('installedBaseline');
+ // 更新语义独立于权限基线:旧安装基线不可读时 diff 可以为 null。
+ expect(request).toMatchObject({ isUpdate: true, permissionDiff: null, ownerStamp });
expect(bridge.resolve(8, request!.requestId, true)).toBe(false);
expect(bridge.resolve(7, request!.requestId, true)).toBe(true);
await expect(decision).resolves.toBe(true);
@@ -36,7 +41,7 @@ describe('PluginMarketPackagePermissionReviewBridge', () => {
it('cancels every pending decision when its requester window is destroyed', async () => {
const bridge = new PluginMarketPackagePermissionReviewBridge();
- const decision = bridge.request(7, facts, () => true);
+ const decision = bridge.request(7, facts, ownerStamp, () => true);
bridge.cancelRequester(7);
@@ -46,6 +51,6 @@ describe('PluginMarketPackagePermissionReviewBridge', () => {
it('cancels immediately when the request cannot be delivered', async () => {
const bridge = new PluginMarketPackagePermissionReviewBridge();
- await expect(bridge.request(7, facts, () => false)).resolves.toBe(false);
+ await expect(bridge.request(7, facts, ownerStamp, () => false)).resolves.toBe(false);
});
});
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
index ffd9cbc724..4e6eb43574 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
@@ -79,7 +79,12 @@ import {
pluginMarketCustomIconSourceToken,
} from '../../../shared/pluginMarket';
import { GHOST_ICON_MAX_BYTES, type GhostManifest } from '../../../shared/ghost';
-import { PluginMarketLedger, ghostManifestDigest } from '../ledger';
+import { GhostPackagePermissionReviewRequiredError } from '../../cindy-brain/packagePermissionReview';
+import {
+ PluginMarketLedger,
+ ghostManifestDigest,
+ type PluginMarketInstallationRecord,
+} from '../ledger';
import { PluginMarketService } from '../service';
import { MarketSourceManager } from '../sources';
import { MarketSourceStore } from '../sources/store';
@@ -116,6 +121,15 @@ function ghostManifest(id: string, version = '1.0.0', overrides: Record<string,
};
}
+/** runtime 安装返回的目录必须包含真实 ghost.json,和生产契约一致。 */
+function installedGhost(root: string, id: string, version = '1.0.0') {
+ const dir = path.join(root, 'installed', id);
+ fs.mkdirSync(dir, { recursive: true });
+ const manifest = ghostManifest(id, version);
+ fs.writeFileSync(path.join(dir, 'ghost.json'), JSON.stringify(manifest));
+ return { manifest, dir, enabled: true };
+}
+
function serverSummary(overrides: Partial<VisiblePluginSummary> = {}): VisiblePluginSummary {
return {
id: PLUGIN_ID,
@@ -245,6 +259,69 @@ describe('PluginMarketService 自定义市场聚合', () => {
});
});
+ it('keeps official items visible and reports only the unavailable custom source', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-missing-'));
+ roots.push(root);
+ const h = harness(
+ [serverSummary()],
+ [{ name: 'offline-market', dir: path.join(root, 'does-not-exist') }],
+ );
+
+ const snapshot = await h.service.snapshot();
+
+ expect(snapshot.items).toHaveLength(1);
+ expect(snapshot.items[0]?.sourceType).toBe('server');
+ expect(snapshot.unavailableReason).toBeNull();
+ expect(snapshot.unavailableCustomSourceNames).toEqual(['offline-market']);
+ });
+
+ it('preserves completed custom sources when a later source exceeds the snapshot timeout', async () => {
+ vi.useFakeTimers();
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-timeout-'));
+ roots.push(root);
+ const readyDir = writeLocalMarket(root, 'ready-market', [
+ { rel: 'plugins/ready', id: 'ready' },
+ ]);
+ const slowDir = writeLocalMarket(root, 'slow-market', [{ rel: 'plugins/slow', id: 'slow' }]);
+ const h = harness(
+ [],
+ [
+ { name: 'ready-market', dir: readyDir },
+ { name: 'slow-market', dir: slowDir },
+ ],
+ );
+ const original = MarketSourceManager.prototype.forEachDiscoveredSource;
+ let resolveReady!: () => void;
+ const ready = new Promise<void>((resolve) => {
+ resolveReady = resolve;
+ });
+ const discover = vi
+ .spyOn(MarketSourceManager.prototype, 'forEachDiscoveredSource')
+ .mockImplementation(async function (this: MarketSourceManager, fn) {
+ await original.call(this, async (entry) => {
+ if (entry.config.name === 'slow-market') {
+ await new Promise<void>(() => undefined);
+ return;
+ }
+ await fn(entry);
+ resolveReady();
+ });
+ });
+
+ try {
+ const snapshotPromise = h.service.snapshot();
+ await ready;
+ await vi.advanceTimersByTimeAsync(3_100);
+ const snapshot = await snapshotPromise;
+
+ expect(snapshot.items.map((item) => item.ghostId)).toEqual(['ready']);
+ expect(snapshot.unavailableCustomSourceNames).toEqual(['slow-market']);
+ } finally {
+ discover.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+
it('does not mark a custom market installation removed when discovery is temporarily empty', async () => {
const h = harness([], []);
const pluginId = customMarketPluginId('team-lib', 'alpha');
@@ -340,6 +417,7 @@ describe('PluginMarketService 自定义市场聚合', () => {
items: [],
unavailableReason: 'not-configured',
customSourceNames: [],
+ unavailableCustomSourceNames: [],
});
});
@@ -391,7 +469,7 @@ describe('PluginMarketService 自定义市场聚合', () => {
source: 'local-market',
installed: true,
updatedAt: '2026-07-30T02:00:00.000Z',
- // 所有权 = pluginId + 来源指纹 + 安装时 manifest 摘要,三者齐全才认领。
+ // 自动更新路由 = pluginId + 来源指纹 + 安装时 manifest 摘要。
sourceKey: marketSourceKey({ type: 'local', path: dir }),
manifestDigest: ghostManifestDigest(ghostManifest('alpha', '1.0.0')),
});
@@ -1021,18 +1099,13 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
const h = harness([], [{ name: 'team-lib', dir }]);
- runtime.install.mockResolvedValue({
- manifest: ghostManifest('alpha'),
- dir: '/ghosts/alpha',
- enabled: true,
- });
+ runtime.install.mockResolvedValue(installedGhost(root, 'alpha'));
const pluginId = customMarketPluginId('team-lib', 'alpha');
- // 以 detail 下发的归一化 manifest 作为“用户审阅内容”,与安装侧重读结果逐字比对。
- const reviewed = await h.service.detail(pluginId);
+ // detail 的目录 manifest 只用于预览;安装权限由 Main 随后解析真实包。
+ await h.service.detail(pluginId);
const result = await h.service.install(pluginId, {
expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
- expectedManifest: reviewed.manifest,
});
expect(result.ghost?.manifest.id).toBe('alpha');
expect(runtime.install).toHaveBeenCalledTimes(1);
@@ -1060,17 +1133,18 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
enabled: true,
});
const pluginId = customMarketPluginId('team-lib', 'cindy-github');
- const reviewed = await h.service.detail(pluginId);
+ await h.service.detail(pluginId);
await h.service.install(pluginId, {
expectedReleaseId: customMarketReleaseId('team-lib', 'cindy-github', '1.0.0'),
- expectedManifest: reviewed.manifest,
});
- expect(runtime.install.mock.calls[0]?.[1]).toEqual({
+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
ghostId: 'cindy-github',
version: '1.0.0',
+ permissionPolicy: { mode: 'manual', sourceType: 'local-market' },
});
+ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('officialCindyGithub');
});
it('rejects install when the reviewed release no longer matches', async () => {
@@ -1078,18 +1152,17 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
const h = harness([], [{ name: 'team-lib', dir }]);
- const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
+ await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
await expect(
h.service.install(customMarketPluginId('team-lib', 'alpha'), {
expectedReleaseId: 'custom:stale',
- expectedManifest: reviewed.manifest,
}),
).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
expect(runtime.install).not.toHaveBeenCalled();
});
- it('rejects install when the manifest changed after permission review', async () => {
+ it('uses the packaged manifest when the catalog preview changed before install', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
@@ -1100,14 +1173,14 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
const ghostFile = path.join(dir, 'plugins', 'alpha', 'ghost.json');
const tampered = { ...ghostManifest('alpha'), description: 'tampered after review' };
fs.writeFileSync(ghostFile, JSON.stringify(tampered));
+ runtime.install.mockResolvedValue(installedGhost(root, 'alpha'));
await expect(
h.service.install(customMarketPluginId('team-lib', 'alpha'), {
expectedReleaseId: detail.releaseId,
- expectedManifest: detail.manifest,
}),
- ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
- expect(runtime.install).not.toHaveBeenCalled();
+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });
+ expect(runtime.install).toHaveBeenCalledTimes(1);
});
it('rejects install when the account switches during packaging', async () => {
@@ -1126,7 +1199,6 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
// 打包前的 discover/校验按 user-1 完成;在 install 入口后切换会话。
const installPromise = h.service.install(customMarketPluginId('team-lib', 'alpha'), {
expectedReleaseId: detail.releaseId,
- expectedManifest: detail.manifest,
});
runtime.session = { mode: 'cloud', dataOwnerId: 'user-2', generation: 2 };
await expect(installPromise).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
@@ -1134,6 +1206,36 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
runtime.session = { mode: 'cloud', dataOwnerId: 'user-1', generation: 1 };
});
+ it('does not expose custom package review facts after the active owner changes', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
+ roots.push(root);
+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
+ const h = harness([], [{ name: 'team-lib', dir }]);
+ const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
+ runtime.install.mockImplementationOnce(async () => {
+ runtime.session = { mode: 'cloud', dataOwnerId: 'user-2', generation: 2 };
+ throw new GhostPackagePermissionReviewRequiredError({
+ manifest: ghostManifest('alpha', '1.0.0', { slots: ['notify', 'fs'] }),
+ permissionDiff: null,
+ isUpdate: false,
+ packageSha256: 'a'.repeat(64),
+ installedBaseline: null,
+ sourceType: 'local-market',
+ });
+ });
+ const confirmReview = vi.fn(async () => true);
+
+ await expect(
+ h.service.install(
+ customMarketPluginId('team-lib', 'alpha'),
+ { expectedReleaseId: detail.releaseId },
+ confirmReview,
+ ),
+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ expect(confirmReview).not.toHaveBeenCalled();
+ runtime.session = { mode: 'cloud', dataOwnerId: 'user-1', generation: 1 };
+ });
+
it('rejects install when the plugin is uninstalled during packaging (runtime 复核)', async () => {
// F1:审阅时 alpha 已装(existing 存在),打包窗口内本地页把它卸载。
// beforeCommit 的 runtime 复核必须发现 existing→缺失并拒,避免"更新"被
@@ -1148,6 +1250,20 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
const installedGhost = [
{ manifest: ghostManifest('alpha'), dir: path.join(dir, 'plugins', 'alpha'), enabled: true },
];
+ h.ledger.upsertInstallation({
+ pluginId,
+ ghostId: 'alpha',
+ releaseId: reviewed.releaseId,
+ version: '1.0.0',
+ sha256: 'custom-unverified',
+ scope: 'public',
+ organizationId: null,
+ source: 'local-market',
+ installed: true,
+ updatedAt: '2026-07-30T02:00:00.000Z',
+ sourceKey: marketSourceKey({ type: 'local', path: dir }),
+ manifestDigest: ghostManifestDigest(ghostManifest('alpha')),
+ });
// detail 之后开始计数:审阅路径的 list() 都看到已装,beforeCommit(最后一次)
// 看到空——alpha 在打包窗口内被卸载。
// 该路径共两次 list():#1 审阅算 existing(看到已装),#2 beforeCommit
@@ -1160,7 +1276,6 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
await expect(
h.service.install(pluginId, {
expectedReleaseId: reviewed.releaseId,
- expectedManifest: reviewed.manifest,
}),
).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
expect(runtime.install).not.toHaveBeenCalled();
@@ -1223,14 +1338,15 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
runtime.session = { mode: 'cloud', dataOwnerId: 'user-1', generation: 1 };
});
- it('rejects install when another source already owns the ghostId', async () => {
+ it('allows an explicit custom install to replace the same ghostId from another source', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
const h = harness([], [{ name: 'team-lib', dir }]);
- runtime.ghosts = [{ manifest: ghostManifest('alpha'), dir: '/ghosts/alpha', enabled: true }];
+ const current = installedGhost(root, 'alpha');
+ runtime.ghosts = [current];
// 服务端市场装过同 id 插件
- h.ledger.upsertInstallation({
+ const previousRecord = {
pluginId: PLUGIN_ID,
ghostId: 'alpha',
releaseId: 'release-1',
@@ -1241,16 +1357,64 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
source: 'market',
installed: true,
updatedAt: '2026-07-30T02:00:00.000Z',
- });
+ } satisfies PluginMarketInstallationRecord;
+ h.ledger.upsertInstallation(previousRecord);
- const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
+ await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
await expect(
h.service.install(customMarketPluginId('team-lib', 'alpha'), {
expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
- expectedManifest: reviewed.manifest,
}),
).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });
- expect(runtime.install).not.toHaveBeenCalled();
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ expect(h.ledger.installationForGhost('alpha')).toMatchObject({ installed: false });
+ throw new Error('placement failed');
+ });
+ await expect(
+ h.service.install(customMarketPluginId('team-lib', 'alpha'), {
+ expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
+ allowSourceReplacement: true,
+ }),
+ ).rejects.toThrow('placement failed');
+ expect(h.ledger.installationForGhost('alpha')).toEqual(previousRecord);
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', PLUGIN_ID)).toBe(false);
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ options.onPackagePlacedInLock?.();
+ throw new Error('notification failed after placement');
+ });
+ await expect(
+ h.service.install(customMarketPluginId('team-lib', 'alpha'), {
+ expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
+ allowSourceReplacement: true,
+ }),
+ ).rejects.toThrow('notification failed after placement');
+ expect(h.ledger.installationForGhost('alpha')).toMatchObject({ installed: false });
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', PLUGIN_ID)).toBe(true);
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ expect(h.ledger.installationForGhost('alpha')).toMatchObject({ installed: false });
+ return {
+ manifest: ghostManifest('alpha'),
+ dir: '/ghosts/replaced-alpha',
+ enabled: true,
+ };
+ });
+ await expect(
+ h.service.install(customMarketPluginId('team-lib', 'alpha'), {
+ expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
+ allowSourceReplacement: true,
+ }),
+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });
+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
+ permissionBaselineManifest: current.manifest,
+ });
+ expect(h.ledger.installationForGhost('alpha')).toMatchObject({
+ pluginId: customMarketPluginId('team-lib', 'alpha'),
+ source: 'local-market',
+ installed: true,
+ });
});
it('lets the user choose between uninstalled custom sources with the same ghostId', async () => {
@@ -1266,25 +1430,20 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
],
);
- runtime.install.mockResolvedValue({
- manifest: ghostManifest('alpha'),
- dir: '/ghosts/alpha',
- enabled: true,
- });
+ runtime.install.mockResolvedValue(installedGhost(root, 'alpha'));
// 市场目录只负责发现。没有真实安装时,两个条目都可选;用户选择哪个来源,
- // 安装完成后才由运行时插件和账本建立所有权。
+ // 安装完成后才由运行时插件和账本建立更新路由。
const snapshot = await h.service.snapshot();
expect(snapshot.items.map((item) => item.installState)).toEqual([
'not-installed',
'not-installed',
]);
- const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
+ await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
await expect(
h.service.install(customMarketPluginId('team-lib', 'alpha'), {
expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
- expectedManifest: reviewed.manifest,
}),
).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });
expect(runtime.install).toHaveBeenCalledTimes(1);
@@ -1295,17 +1454,12 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'server-plugin' }]);
const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);
- runtime.install.mockResolvedValue({
- manifest: ghostManifest('server-plugin'),
- dir: '/ghosts/server-plugin',
- enabled: true,
- });
+ runtime.install.mockResolvedValue(installedGhost(root, 'server-plugin'));
- const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'server-plugin'));
+ await h.service.detail(customMarketPluginId('team-lib', 'server-plugin'));
await expect(
h.service.install(customMarketPluginId('team-lib', 'server-plugin'), {
expectedReleaseId: customMarketReleaseId('team-lib', 'server-plugin', '1.0.0'),
- expectedManifest: reviewed.manifest,
}),
).resolves.toMatchObject({ ghost: { manifest: { id: 'server-plugin' } } });
expect(runtime.install).toHaveBeenCalledTimes(1);
@@ -1337,7 +1491,6 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
await expect(
h.service.install(item.id, {
expectedReleaseId: item.currentRelease.id,
- expectedManifest: ghostManifest(item.ghostId, item.currentRelease.version),
}),
).resolves.toMatchObject({ ghost: { manifest: { id: 'server-plugin' } } });
expect(h.api.download).toHaveBeenCalledTimes(1);
@@ -1380,13 +1533,9 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
const h = harness([], [{ name: 'team-lib', dir }]);
- runtime.install.mockResolvedValue({
- manifest: ghostManifest('alpha'),
- dir: '/ghosts/alpha',
- enabled: true,
- });
+ runtime.install.mockResolvedValue(installedGhost(root, 'alpha'));
const pluginId = customMarketPluginId('team-lib', 'alpha');
- const reviewed = await h.service.detail(pluginId);
+ await h.service.detail(pluginId);
const realList = MarketSourceStore.prototype.list;
let reads = 0;
@@ -1401,7 +1550,6 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
await expect(
h.service.install(pluginId, {
expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
- expectedManifest: reviewed.manifest,
}),
).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });
expect(runtime.install).toHaveBeenCalledTimes(1);
@@ -1418,7 +1566,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
const rivalDir = writeLocalMarket(root, 'rival-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
const h = harness([], [{ name: 'team-lib', dir }]);
const pluginId = customMarketPluginId('team-lib', 'alpha');
- const reviewed = await h.service.detail(pluginId);
+ await h.service.detail(pluginId);
// 落位期间(installOrUpdateMarketGhostPackage 还在 await 包检查)另一窗口尝试
// 变更来源配置。自定义安装提交段持有来源锁,这次 addSource 必须排在落位后,
@@ -1432,21 +1580,20 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
const installMayFinish = new Promise<void>((resolve) => {
releaseInstall = resolve;
});
+ const installed = installedGhost(root, 'alpha');
runtime.install.mockImplementation(async () => {
order.push('install-entered');
markInstallEntered();
await installMayFinish;
order.push('install-finished');
- return { manifest: ghostManifest('alpha'), dir: '/ghosts/alpha', enabled: true };
+ return installed;
});
const installing = h.service.install(pluginId, {
expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
- expectedManifest: reviewed.manifest,
});
// runtime.install 只会在 beforeCommit 复核之后、SOURCE_MUTATION_KEY 仍被持有时调用。
- // 用显式 barrier 等到这个时刻,不能靠固定毫秒数猜测打包是否已经完成:CI 负载下
- // 打包超过等待时间时,rival 会先拿锁,测试反而正确地收到 ALREADY_EXISTS。
+ // 用显式 barrier 等到这个时刻,不能靠固定毫秒数猜测打包是否已经完成。
await installEntered;
let addSourceSettled = false;
const adding = h.service
@@ -1471,18 +1618,22 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
expect(order).toEqual(['install-entered', 'install-finished', 'source-settled']);
});
- it('denies a re-added same-name source with a different origin from owning the install', async () => {
+ it('keeps a re-added same-name source out of automatic updates but allows explicit replacement', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
// 来源 B 与当初安装用的来源 A 市场名相同(marketplace.json 自报、可复用),
- // 但指向完全不同的目录。pluginId 因此完全相同,所有权必须由来源指纹裁决。
+ // 但指向完全不同的目录。pluginId 因此完全相同,自动更新路由必须由来源指纹区分。
const dirB = writeLocalMarket(root, 'team-lib', [
{ rel: 'plugins/alpha', id: 'alpha', version: '2.0.0' },
]);
const h = harness([], [{ name: 'team-lib', dir: dirB }]);
- runtime.ghosts = [
- { manifest: ghostManifest('alpha', '1.0.0'), dir: '/ghosts/alpha', enabled: true },
- ];
+ const current = installedGhost(root, 'alpha', '1.0.0');
+ runtime.ghosts = [current];
+ runtime.install.mockResolvedValue({
+ manifest: ghostManifest('alpha', '2.0.0'),
+ dir: '/ghosts/replaced-alpha',
+ enabled: true,
+ });
h.ledger.upsertInstallation({
pluginId: customMarketPluginId('team-lib', 'alpha'),
ghostId: 'alpha',
@@ -1503,15 +1654,22 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
const snapshot = await h.service.snapshot();
expect(snapshot.items[0]?.installState).toBe('conflict');
- // 安装:同样被拒,恶意/无关仓库不能借同名市场"更新"别人装出来的插件。
- const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
+ // 用户明确点击该条目后可以替换;成功落位后才切换后续更新路由。
+ await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
await expect(
h.service.install(customMarketPluginId('team-lib', 'alpha'), {
expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '2.0.0'),
- expectedManifest: reviewed.manifest,
+ allowSourceReplacement: true,
}),
- ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });
- expect(runtime.install).not.toHaveBeenCalled();
+ ).resolves.toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });
+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
+ permissionBaselineManifest: current.manifest,
+ });
+ expect(h.ledger.installationForGhost('alpha')).toMatchObject({
+ sourceKey: marketSourceKey({ type: 'local', path: dirB }),
+ version: '2.0.0',
+ installed: true,
+ });
});
it('rejects the install when the source vanishes before the commit point', async () => {
@@ -1520,7 +1678,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
const h = harness([], [{ name: 'team-lib', dir }]);
const pluginId = customMarketPluginId('team-lib', 'alpha');
- const reviewed = await h.service.detail(pluginId);
+ await h.service.detail(pluginId);
// 打包期间另一窗口移除了该来源(移除先拿 SOURCE_MUTATION_KEY 删配置,租约只
// 保住目录字节)。用"入口发现之后 store.get 开始返回 null"精确模拟这个时序:
@@ -1539,7 +1697,6 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
await expect(
h.service.install(pluginId, {
expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
- expectedManifest: reviewed.manifest,
}),
).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
expect(runtime.install).not.toHaveBeenCalled();
@@ -1549,7 +1706,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
}
});
- it('does not let a stale custom record claim a locally replaced package', async () => {
+ it('keeps a stale custom record out of automatic updates but allows explicit replacement', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [
@@ -1564,7 +1721,15 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
description: 'locally installed replacement',
slots: ['notify', 'network'],
};
- runtime.ghosts = [{ manifest: replacedManifest, dir: '/ghosts/alpha', enabled: true }];
+ const installedDir = path.join(root, 'installed-replacement');
+ fs.mkdirSync(installedDir, { recursive: true });
+ fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(replacedManifest));
+ runtime.ghosts = [{ manifest: replacedManifest, dir: installedDir, enabled: true }];
+ runtime.install.mockResolvedValue({
+ manifest: ghostManifest('alpha', '2.0.0'),
+ dir: '/ghosts/market-alpha',
+ enabled: true,
+ });
h.ledger.upsertInstallation({
pluginId: customMarketPluginId('team-lib', 'alpha'),
ghostId: 'alpha',
@@ -1586,15 +1751,22 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
const snapshot = await h.service.snapshot();
expect(snapshot.items[0]?.installState).toBe('conflict');
- // 安装:同样被拒,来源的更新不能覆盖用户降级期间自己装的包。
- const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
+ // 列表不把它当自动更新,但用户显式选择后可以替换。
+ await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
await expect(
h.service.install(customMarketPluginId('team-lib', 'alpha'), {
expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '2.0.0'),
- expectedManifest: reviewed.manifest,
+ allowSourceReplacement: true,
}),
- ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });
- expect(runtime.install).not.toHaveBeenCalled();
+ ).resolves.toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });
+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
+ permissionBaselineManifest: replacedManifest,
+ });
+ expect(h.ledger.installationForGhost('alpha')).toMatchObject({
+ sourceKey: marketSourceKey({ type: 'local', path: dir }),
+ version: '2.0.0',
+ installed: true,
+ });
});
it('masks failure details with a generation error when the account switches mid-operation', async () => {
@@ -1653,7 +1825,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
it('keeps official default installs available while one custom entry is unreadable', async () => {
// 粒度到条目:来源本身可读、清单也在,只是**某个插件的 ghost.json** 因文件锁/
// 权限/网络盘抖动暂时读不到。此前这类失败与"内容非法"共用静默跳过分支,目录
- // 仍被判 complete,同 ghostId 的默认安装会在这个窗口里抢占所有权,恢复后该
+ // 仍被判 complete,同 ghostId 的默认安装会在这个窗口里落位,恢复后该
// 插件永久 conflict。现在读取事实不明必须让目录判为不完整。
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
@@ -1734,20 +1906,24 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
await expect(
h.service.install(item.id, {
expectedReleaseId: item.currentRelease.id,
- expectedManifest: ghostManifest(item.ghostId, item.currentRelease.version),
+ allowSourceReplacement: true,
}),
).resolves.toMatchObject({ ghost: { manifest: { id: 'server-plugin' } } });
expect(h.api.download).toHaveBeenCalled();
});
- it('does not let official market take over an installed custom plugin when its source is unreadable', async () => {
+ it('allows explicit official replacement when the previous custom source is unreadable', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'server-plugin' }]);
const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);
- runtime.ghosts = [
- { manifest: ghostManifest('server-plugin'), dir: '/ghosts/server-plugin', enabled: true },
- ];
+ const current = installedGhost(root, 'server-plugin');
+ runtime.ghosts = [current];
+ runtime.install.mockResolvedValue({
+ manifest: ghostManifest('server-plugin'),
+ dir: '/ghosts/official-server-plugin',
+ enabled: true,
+ });
h.ledger.upsertInstallation({
pluginId: customMarketPluginId('team-lib', 'server-plugin'),
ghostId: 'server-plugin',
@@ -1765,46 +1941,63 @@ describe('PluginMarketService 自定义市场 detail/install', () => {
fs.rmSync(dir, { recursive: true, force: true });
const item = serverSummary();
+ h.api.download.mockResolvedValue({
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ });
await expect(
h.service.install(item.id, {
expectedReleaseId: item.currentRelease.id,
- expectedManifest: ghostManifest(item.ghostId, item.currentRelease.version),
+ allowSourceReplacement: true,
}),
- ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });
- expect(h.api.download).not.toHaveBeenCalled();
- expect(runtime.install).not.toHaveBeenCalled();
+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'server-plugin' } } });
+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
+ permissionBaselineManifest: current.manifest,
+ });
+ expect(h.ledger.installationForGhost('server-plugin')).toMatchObject({
+ pluginId: item.id,
+ source: 'market',
+ installed: true,
+ });
});
- it('adopts a matching install after a lost ledger write instead of dead-ending in conflict', async () => {
+ it('recovers a lost ledger write through an explicit install without automatic adoption', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
const h = harness([], [{ name: 'team-lib', dir }]);
- // 场景:包已落位,但溯源账本因文件锁/磁盘错没写成——账本里没有记录。
- // 运行时内容与来源候选**完全一致**(同一份原始 ghost.json)。
+ // 场景:包已落位,但溯源账本里没有记录。即使运行时内容与来源候选
+ // 完全一致,也不能据此自动推断后续更新来源。
const installedDir = path.join(root, 'installed-alpha');
fs.mkdirSync(installedDir, { recursive: true });
fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(ghostManifest('alpha')));
runtime.ghosts = [{ manifest: ghostManifest('alpha'), dir: installedDir, enabled: true }];
-
- // 列表:不能标 conflict(UI 会禁用安装,用户连修复入口都没有);投影成可安装。
- const snapshot = await h.service.snapshot();
- expect(snapshot.items[0]?.installState).toBe('not-installed');
-
- // 安装 = 收养:完整重装 + 补写溯源,自愈完成。
runtime.install.mockResolvedValue({
manifest: ghostManifest('alpha'),
- dir: installedDir,
+ dir: '/ghosts/recovered-alpha',
enabled: true,
});
- const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
- await h.service.install(customMarketPluginId('team-lib', 'alpha'), {
- expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
- expectedManifest: reviewed.manifest,
+
+ // 列表不根据内容相同自动推断来源;用户显式点击后可以原位恢复路由。
+ const snapshot = await h.service.snapshot();
+ expect(snapshot.items[0]?.installState).toBe('conflict');
+
+ await h.service.detail(customMarketPluginId('team-lib', 'alpha'));
+ await expect(
+ h.service.install(customMarketPluginId('team-lib', 'alpha'), {
+ expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),
+ allowSourceReplacement: true,
+ }),
+ ).resolves.toMatchObject({ ghost: { manifest: { id: 'alpha' } } });
+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
+ permissionBaselineManifest: ghostManifest('alpha'),
});
expect(h.ledger.installationForGhost('alpha')).toMatchObject({
- installed: true,
+ pluginId: customMarketPluginId('team-lib', 'alpha'),
source: 'local-market',
+ installed: true,
});
});
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 c20a2a57c4..492673adc9 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -4,10 +4,7 @@ import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import {
- diffGhostPermissionItems,
- ghostPermissionBaselineKey,
-} from '../../../shared/ghost.js';
+import { diffGhostPermissionItems, ghostPermissionBaselineKey } from '../../../shared/ghost.js';
const runtime = vi.hoisted(() => ({
ghosts: [] as Array<{
@@ -134,9 +131,7 @@ function manifest(
};
}
-function summary(
- overrides: Partial<VisiblePluginSummary> = {},
-): VisiblePluginSummary {
+function summary(overrides: Partial<VisiblePluginSummary> = {}): VisiblePluginSummary {
return {
id: PLUGIN_ID,
ghostId: 'cindy-test',
@@ -158,16 +153,17 @@ function summary(
};
}
-function reviewedInstallOptions(item: VisiblePluginSummary) {
+function reviewedInstallOptions(
+ item: VisiblePluginSummary,
+ allowSourceReplacement = false,
+) {
return {
expectedReleaseId: item.currentRelease.id,
- expectedManifest: manifest(item.ghostId, item.currentRelease.version),
+ allowSourceReplacement,
};
}
-function removal(
- overrides: Partial<PluginRemovalNotice> = {},
-): PluginRemovalNotice {
+function removal(overrides: Partial<PluginRemovalNotice> = {}): PluginRemovalNotice {
return {
pluginId: PLUGIN_ID,
ghostId: 'cindy-test',
@@ -179,10 +175,7 @@ function removal(
};
}
-function harness(
- items: VisiblePluginSummary[],
- removals: PluginRemovalNotice[] = [],
-) {
+function harness(items: VisiblePluginSummary[], removals: PluginRemovalNotice[] = []) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-plugin-service-'));
roots.push(root);
const ledger = new PluginMarketLedger(path.join(root, 'ledger.json'));
@@ -217,10 +210,7 @@ function harness(
function removalRecord(
overrides: Partial<PluginMarketInstallationRecord> = {},
): PluginMarketInstallationRecord {
- return recordForTest(
- summary({ scope: 'organization', organizationId: 'org-1' }),
- overrides,
- );
+ return recordForTest(summary({ scope: 'organization', organizationId: 'org-1' }), overrides);
}
/** 清理通告测试的运行时 Ghost 目录项。 */
@@ -293,12 +283,14 @@ describe('PluginMarketService migration and defaultInstall', () => {
url: 'https://oss.example.invalid/icons/test.png',
expiresAt: '2026-07-23T00:05:00.000Z',
};
- const h = harness([summary({
- currentRelease: {
- ...summary().currentRelease,
- icon,
- },
- })]);
+ const h = harness([
+ summary({
+ currentRelease: {
+ ...summary().currentRelease,
+ icon,
+ },
+ }),
+ ]);
await expect(h.service.snapshot()).resolves.toMatchObject({
items: [{ icon }],
@@ -307,10 +299,12 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
it('takes bounded local snapshots instead of reading the ledger per market item', async () => {
- const items = Array.from({ length: 50 }, (_, index) => summary({
- id: `c${index.toString(36).padStart(24, '0')}`,
- ghostId: `cindy-test-${index}`,
- }));
+ const items = Array.from({ length: 50 }, (_, index) =>
+ summary({
+ id: `c${index.toString(36).padStart(24, '0')}`,
+ ghostId: `cindy-test-${index}`,
+ }),
+ );
const h = harness(items);
const read = vi.spyOn(h.ledger, 'read');
@@ -353,6 +347,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
items: [],
unavailableReason: 'authentication-required',
customSourceNames: [],
+ unavailableCustomSourceNames: [],
});
expect(h.api.listAll).not.toHaveBeenCalled();
});
@@ -370,6 +365,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
items: [],
unavailableReason: 'not-configured',
customSourceNames: [],
+ unavailableCustomSourceNames: [],
});
expect(h.api.listAll).not.toHaveBeenCalled();
});
@@ -382,6 +378,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
items: [],
unavailableReason: 'session-switching',
customSourceNames: [],
+ unavailableCustomSourceNames: [],
});
expect(h.api.listAll).not.toHaveBeenCalled();
});
@@ -462,7 +459,11 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect.objectContaining({
ghostId: 'cindy-test',
version: '1.0.0',
- reviewedManifest: manifest(),
+ permissionPolicy: {
+ mode: 'cap',
+ manifest: manifest(),
+ sourceType: 'server',
+ },
beforeCommitInLock: expect.any(Function),
}),
);
@@ -477,14 +478,51 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
});
+ it('returns a Renderer snapshot before a default install download finishes', async () => {
+ const item = summary({ defaultInstall: true });
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-deferred-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(manifest()));
+ const downloadGate = deferred();
+ const reconciliationSettled = deferred();
+ const h = harness([item]);
+ h.api.download.mockImplementationOnce(async () => {
+ await downloadGate.promise;
+ return {
+ url: 'https://downloads.test.invalid/plugin.cindy',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 42,
+ };
+ });
+ runtime.install.mockImplementation(async () => {
+ const ghost = { manifest: manifest(), dir: installDir, enabled: true };
+ runtime.ghosts = [ghost];
+ return ghost;
+ });
+
+ const snapshot = await h.service.snapshot({
+ deferDefaultReconciliation: true,
+ onDeferredReconciliationSettled: reconciliationSettled.resolve,
+ });
+
+ expect(snapshot.items[0]?.installState).toBe('not-installed');
+ await vi.waitFor(() => expect(h.api.download).toHaveBeenCalledOnce());
+ downloadGate.resolve();
+ await reconciliationSettled.promise;
+ expect(runtime.install).toHaveBeenCalledOnce();
+ });
+
it('does not auto-install a default package with permissions absent from its catalog manifest', async () => {
const item = summary({ defaultInstall: true });
runtime.install.mockRejectedValueOnce(
new GhostPackagePermissionReviewRequiredError({
manifest: manifest(item.ghostId, item.currentRelease.version, ['notify', 'fs']),
permissionDiff: null,
+ isUpdate: false,
packageSha256: item.currentRelease.sha256,
installedBaseline: null,
+ sourceType: 'server',
}),
);
const h = harness([item]);
@@ -493,7 +531,13 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(runtime.install).toHaveBeenCalledWith(
expect.stringMatching(/\.cindy$/),
- expect.objectContaining({ reviewedManifest: manifest() }),
+ expect.objectContaining({
+ permissionPolicy: {
+ mode: 'cap',
+ manifest: manifest(),
+ sourceType: 'server',
+ },
+ }),
);
expect(snapshot.items[0]?.installState).toBe('not-installed');
expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
@@ -554,7 +598,6 @@ describe('PluginMarketService migration and defaultInstall', () => {
await expect(
h.service.install(item.id, {
expectedReleaseId: item.currentRelease.id,
- expectedManifest: incompatibleManifest,
}),
).rejects.toThrow('[NOT_FOUND]');
expect(h.api.download).not.toHaveBeenCalled();
@@ -574,18 +617,33 @@ describe('PluginMarketService migration and defaultInstall', () => {
const { ghost } = await h.service.install(item.id, reviewedInstallOptions(item));
- expect(runtime.install).toHaveBeenCalledWith(
- expect.stringMatching(/\.cindy$/),
- {
- ghostId: 'cindy-test',
- version: '1.0.0',
- reviewedManifest: manifest(),
- },
- );
+ expect(runtime.install).toHaveBeenCalledWith(expect.stringMatching(/\.cindy$/), {
+ ghostId: 'cindy-test',
+ version: '1.0.0',
+ permissionPolicy: { mode: 'manual', sourceType: 'server' },
+ });
+ expect(h.api.listAll).not.toHaveBeenCalled();
// 锁定装完即开的最终结果:装入入口返回的 ghost 必须是启用态。
expect(ghost?.enabled).toBe(true);
});
+ it('installs the explicitly selected official entry when another entry shares its ghostId', async () => {
+ const selected = summary();
+ const other = summary({ id: `c${'b'.repeat(24)}`, name: 'Other Listing' });
+ runtime.install.mockResolvedValue({
+ manifest: manifest(),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ });
+ const h = harness([selected, other]);
+
+ await expect(
+ h.service.install(selected.id, reviewedInstallOptions(selected)),
+ ).resolves.toMatchObject({ ghost: { manifest: { id: selected.ghostId } } });
+ expect(h.api.detail).toHaveBeenCalledWith(selected.id);
+ expect(h.api.listAll).not.toHaveBeenCalled();
+ });
+
it('server-market 只为 cindy-github 安装显式传 Host 官方身份', async () => {
const github = summary({ ghostId: 'cindy-github' });
runtime.install.mockResolvedValue({
@@ -614,7 +672,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(runtime.install.mock.calls[0]?.[1]).toEqual({
ghostId: 'cindy-test',
version: '1.0.0',
- reviewedManifest: manifest(),
+ permissionPolicy: { mode: 'manual', sourceType: 'server' },
});
});
@@ -856,7 +914,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
});
- it('passes the reviewed server manifest to the package verification boundary', async () => {
+ it('keeps the server manifest out of the manual package permission boundary', async () => {
const item = summary();
runtime.install.mockResolvedValue({
manifest: manifest(),
@@ -868,8 +926,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
await h.service.install(item.id, reviewedInstallOptions(item));
expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
- reviewedManifest: manifest(),
+ permissionPolicy: { mode: 'manual', sourceType: 'server' },
});
+ expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('permissionBaselineManifest');
});
it('pauses one install transaction for package review and reuses the download', async () => {
@@ -877,28 +936,51 @@ describe('PluginMarketService migration and defaultInstall', () => {
const review = {
manifest: manifest('cindy-test', '1.0.0', ['notify', 'fs']),
permissionDiff: null,
+ isUpdate: false,
packageSha256: 'a'.repeat(64),
installedBaseline: null,
+ sourceType: 'server' as const,
};
+ const commitStarted = deferred();
+ const allowCommit = deferred();
+ let reviewedTempPath = '';
runtime.install
- .mockRejectedValueOnce(new GhostPackagePermissionReviewRequiredError(review))
- .mockResolvedValueOnce({
- manifest: manifest(),
- dir: '/userData/cindy-brain/cindy-test',
- enabled: true,
+ .mockImplementationOnce(async (tempPath: string) => {
+ fs.writeFileSync(tempPath, 'verified-package');
+ throw new GhostPackagePermissionReviewRequiredError(review);
+ })
+ .mockImplementationOnce(async (tempPath: string) => {
+ reviewedTempPath = tempPath;
+ commitStarted.resolve();
+ await allowCommit.promise;
+ expect(fs.existsSync(tempPath)).toBe(true);
+ return {
+ manifest: manifest(),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ };
});
const h = harness([item]);
const confirmReview = vi.fn(async () => true);
- await expect(
- h.service.install(item.id, reviewedInstallOptions(item), confirmReview),
- ).resolves.toMatchObject({ ghost: { manifest: { id: item.ghostId } } });
+ const installing = h.service.install(
+ item.id,
+ reviewedInstallOptions(item),
+ confirmReview,
+ );
+ await commitStarted.promise;
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(fs.existsSync(reviewedTempPath)).toBe(true);
+ allowCommit.resolve();
+ await expect(installing).resolves.toMatchObject({
+ ghost: { manifest: { id: item.ghostId } },
+ });
expect(confirmReview).toHaveBeenCalledWith(review);
expect(h.api.download).toHaveBeenCalledTimes(1);
expect(runtime.install).toHaveBeenLastCalledWith(
expect.stringMatching(/\.cindy$/),
expect.objectContaining({
- reviewedManifest: manifest(),
+ permissionPolicy: { mode: 'manual', sourceType: 'server' },
approvedPackageSha256: review.packageSha256,
}),
);
@@ -909,8 +991,10 @@ describe('PluginMarketService migration and defaultInstall', () => {
const review = {
manifest: manifest('cindy-test', '1.0.0', ['notify', 'fs']),
permissionDiff: null,
+ isUpdate: false,
packageSha256: 'a'.repeat(64),
installedBaseline: null,
+ sourceType: 'server' as const,
};
runtime.install.mockImplementationOnce(async () => {
runtime.session = {
@@ -922,9 +1006,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
const h = harness([item]);
- await expect(
- h.service.install(item.id, reviewedInstallOptions(item)),
- ).rejects.toThrow('[PRECONDITION_FAILED]');
+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(
+ '[PRECONDITION_FAILED]',
+ );
expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
});
@@ -963,7 +1047,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
});
- it('does not let a stale official record claim a locally changed package', async () => {
+ it('keeps a stale official record out of automatic updates but allows explicit replacement', async () => {
const item = summary({
currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
});
@@ -973,21 +1057,61 @@ describe('PluginMarketService migration and defaultInstall', () => {
fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(installed));
runtime.ghosts = [{ manifest: installed, dir: installedDir, enabled: true }];
const h = harness([item]);
- h.ledger.upsertInstallation({
+ const previousRecord = {
...recordForTest(item),
releaseId: 'release-1',
version: '1.0.0',
manifestDigest: ghostManifestDigest({ ...installed, slots: ['notify'] }),
+ } satisfies PluginMarketInstallationRecord;
+ h.ledger.upsertInstallation(previousRecord);
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({ installed: false });
+ throw new Error('placement failed');
});
expect((await h.service.snapshot()).items[0]?.installState).toBe('conflict');
+ await expect(h.service.install(item.id, reviewedInstallOptions(item, true))).rejects.toThrow(
+ 'placement failed',
+ );
+ expect(h.ledger.installationForGhost(item.ghostId)).toEqual(previousRecord);
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ options.onPackagePlacedInLock?.();
+ throw new Error('notification failed after placement');
+ });
+ await expect(h.service.install(item.id, reviewedInstallOptions(item, true))).rejects.toThrow(
+ 'notification failed after placement',
+ );
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({ installed: false });
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(true);
+ runtime.install.mockImplementationOnce(async (_file, options) => {
+ options.beforeCommitInLock?.();
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({ installed: false });
+ return {
+ manifest: manifest(item.ghostId, '2.0.0', ['notify']),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ };
+ });
await expect(
- h.service.install(item.id, reviewedInstallOptions(item)),
- ).rejects.toThrow('[ALREADY_EXISTS]');
- expect(runtime.install).not.toHaveBeenCalled();
+ h.service.install(item.id, reviewedInstallOptions(item, true)),
+ ).resolves.toMatchObject({
+ ghost: { manifest: { version: '2.0.0' } },
+ });
+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
+ permissionBaselineManifest: installed,
+ });
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
+ pluginId: item.id,
+ source: 'market',
+ version: '2.0.0',
+ installed: true,
+ });
});
- it('does not trust an installed manifest as the permission baseline without a digest', async () => {
+ it('uses the actual installed manifest as the permission baseline for a legacy record', async () => {
const item = summary({
currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
});
@@ -1011,7 +1135,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
await h.service.install(item.id, reviewedInstallOptions(item));
- expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('permissionBaselineManifest');
+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
+ permissionBaselineManifest: installed,
+ });
});
it('installs and enables a public defaultInstall package in local mode', async () => {
@@ -1039,7 +1165,11 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect.objectContaining({
ghostId: item.ghostId,
version: item.currentRelease.version,
- reviewedManifest: manifest(),
+ permissionPolicy: {
+ mode: 'cap',
+ manifest: manifest(),
+ sourceType: 'server',
+ },
beforeCommitInLock: expect.any(Function),
}),
);
@@ -1085,11 +1215,20 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect.objectContaining({
ghostId: item.ghostId,
version: '2.0.0',
- reviewedManifest: upgraded,
+ permissionPolicy: {
+ mode: 'cap',
+ manifest: upgraded,
+ sourceType: 'server',
+ },
}),
);
expect(snapshot.items[0]).toMatchObject({ installState: 'installed', enabled: false });
- expect(h.service.consumeUpgradeNotice()).toEqual({ count: 1, name: 'Test Plugin', permissions: null, hasPermissionExpansion: false });
+ expect(h.service.consumeUpgradeNotice()).toEqual({
+ count: 1,
+ name: 'Test Plugin',
+ permissions: null,
+ hasPermissionExpansion: false,
+ });
});
it('integration: snapshot upgrades an organization defaultInstall release and consumes its notice', async () => {
@@ -1131,7 +1270,12 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(h.api.detail).toHaveBeenCalledWith(item.id);
expect(h.api.download).toHaveBeenCalledWith(item.id, 'release-2');
expect(runtime.install).toHaveBeenCalledTimes(1);
- expect(h.service.consumeUpgradeNotice()).toEqual({ count: 1, name: 'Test Plugin', permissions: null, hasPermissionExpansion: false });
+ expect(h.service.consumeUpgradeNotice()).toEqual({
+ count: 1,
+ name: 'Test Plugin',
+ permissions: null,
+ hasPermissionExpansion: false,
+ });
expect(h.service.consumeUpgradeNotice()).toBeNull();
});
@@ -1168,7 +1312,12 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(h.api.download).toHaveBeenCalledTimes(1);
expect(runtime.install).toHaveBeenCalledTimes(1);
- expect(h.service.consumeUpgradeNotice()).toEqual({ count: 1, name: 'Test Plugin', permissions: null, hasPermissionExpansion: false });
+ expect(h.service.consumeUpgradeNotice()).toEqual({
+ count: 1,
+ name: 'Test Plugin',
+ permissions: null,
+ hasPermissionExpansion: false,
+ });
expect(h.service.consumeUpgradeNotice()).toBeNull();
});
@@ -1236,9 +1385,14 @@ describe('PluginMarketService migration and defaultInstall', () => {
runtime.install.mockRejectedValueOnce(
new GhostPackagePermissionReviewRequiredError({
manifest: manifest(item.ghostId, '2.0.0', ['notify', 'fs']),
- permissionDiff: diffGhostPermissionItems(oldManifest, manifest(item.ghostId, '2.0.0', ['notify', 'fs'])),
+ permissionDiff: diffGhostPermissionItems(
+ oldManifest,
+ manifest(item.ghostId, '2.0.0', ['notify', 'fs']),
+ ),
+ isUpdate: true,
packageSha256: item.currentRelease.sha256,
installedBaseline: ghostPermissionBaselineKey(oldManifest),
+ sourceType: 'server',
}),
);
@@ -1271,6 +1425,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
const expanded = manifest(item.ghostId, '2.0.0', ['notify', 'fs']);
h.api.detail.mockImplementationOnce(async () => {
const changed = manifest(item.ghostId, '1.0.0', ['notify', 'workspace'] as never);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(changed));
runtime.ghosts = [{ manifest: changed, dir: installDir, enabled: true }];
return {
...item,
@@ -1279,7 +1434,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
await expect(h.service.snapshot()).resolves.toMatchObject({
- items: [{ installState: 'update-available' }],
+ items: [{ installState: 'conflict' }],
});
expect(runtime.install).not.toHaveBeenCalled();
expect(h.service.consumeUpgradeNotice()).toBeNull();
@@ -1309,9 +1464,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
...item,
currentRelease: { ...item.currentRelease, manifest: expanded },
} as never);
- const downloadMock = vi.mocked(
- (await import('../download.js')).downloadVerifiedPlugin,
- );
+ const downloadMock = vi.mocked((await import('../download.js')).downloadVerifiedPlugin);
const downloadStarted = deferred();
const downloadGate = deferred();
downloadMock.mockImplementationOnce(async () => {
@@ -1322,11 +1475,12 @@ describe('PluginMarketService migration and defaultInstall', () => {
const snapshotPromise = h.service.snapshot();
await downloadStarted.promise;
const changed = manifest(item.ghostId, '1.0.0', ['notify', 'workspace'] as never);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(changed));
runtime.ghosts = [{ manifest: changed, dir: installDir, enabled: true }];
downloadGate.resolve();
await expect(snapshotPromise).resolves.toMatchObject({
- items: [{ installState: 'update-available' }],
+ items: [{ installState: 'conflict' }],
});
expect(runtime.install).not.toHaveBeenCalled();
expect(h.service.consumeUpgradeNotice()).toBeNull();
@@ -1365,7 +1519,12 @@ describe('PluginMarketService migration and defaultInstall', () => {
runtime[signal] = false;
await h.service.snapshot();
expect(runtime.install).toHaveBeenCalledTimes(1);
- expect(h.service.consumeUpgradeNotice()).toEqual({ count: 1, name: 'Test Plugin', permissions: null, hasPermissionExpansion: false });
+ expect(h.service.consumeUpgradeNotice()).toEqual({
+ count: 1,
+ name: 'Test Plugin',
+ permissions: null,
+ hasPermissionExpansion: false,
+ });
},
);
@@ -1402,12 +1561,18 @@ describe('PluginMarketService migration and defaultInstall', () => {
it('continues upgrading other organization plugins when one upgrade fails', async () => {
const first = summary({
- scope: 'organization', organizationId: 'org-1', defaultInstall: true,
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: true,
currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
});
const second = summary({
- id: `c${'b'.repeat(24)}`, ghostId: 'cindy-second', name: 'Second Plugin',
- scope: 'organization', organizationId: 'org-1', defaultInstall: true,
+ id: `c${'b'.repeat(24)}`,
+ ghostId: 'cindy-second',
+ name: 'Second Plugin',
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: true,
currentRelease: { ...summary().currentRelease, id: 'release-2b', version: '2.0.0' },
});
const firstDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));
@@ -1422,8 +1587,18 @@ describe('PluginMarketService migration and defaultInstall', () => {
{ manifest: secondManifest, dir: secondDir, enabled: true },
];
const h = harness([first, second]);
- h.ledger.upsertInstallation({ ...recordForTest(first), releaseId: 'release-1', version: '1.0.0', manifestDigest: ghostManifestDigest(firstManifest) });
- h.ledger.upsertInstallation({ ...recordForTest(second), releaseId: 'release-1b', version: '1.0.0', manifestDigest: ghostManifestDigest(secondManifest) });
+ h.ledger.upsertInstallation({
+ ...recordForTest(first),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(firstManifest),
+ });
+ h.ledger.upsertInstallation({
+ ...recordForTest(second),
+ releaseId: 'release-1b',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(secondManifest),
+ });
runtime.install
.mockRejectedValueOnce(new Error('first failed'))
.mockImplementationOnce(async (_file, expected) => {
@@ -1433,19 +1608,33 @@ describe('PluginMarketService migration and defaultInstall', () => {
};
const dir = expected.ghostId === first.ghostId ? firstDir : secondDir;
const ghost = { manifest: upgraded, dir, enabled: true };
- runtime.ghosts = runtime.ghosts.map((candidate) => candidate.manifest.id === expected.ghostId ? ghost : candidate);
+ runtime.ghosts = runtime.ghosts.map((candidate) =>
+ candidate.manifest.id === expected.ghostId ? ghost : candidate,
+ );
return ghost;
});
await expect(h.service.snapshot()).resolves.toMatchObject({ unavailableReason: null });
expect(runtime.install).toHaveBeenCalledTimes(2);
- expect(h.service.consumeUpgradeNotice()).toEqual({ count: 1, name: 'Second Plugin', permissions: null, hasPermissionExpansion: false });
+ expect(h.service.consumeUpgradeNotice()).toEqual({
+ count: 1,
+ name: 'Second Plugin',
+ permissions: null,
+ hasPermissionExpansion: false,
+ });
});
it('does not silently update public or non-defaultInstall plugins', async () => {
- const publicItem = summary({ defaultInstall: true, currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' } });
+ const publicItem = summary({
+ defaultInstall: true,
+ currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
+ });
const nonDefault = summary({
- id: `c${'b'.repeat(24)}`, ghostId: 'cindy-second', scope: 'organization', organizationId: 'org-1', defaultInstall: false,
+ id: `c${'b'.repeat(24)}`,
+ ghostId: 'cindy-second',
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: false,
currentRelease: { ...summary().currentRelease, id: 'release-2b', version: '2.0.0' },
});
const firstDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));
@@ -1460,17 +1649,32 @@ describe('PluginMarketService migration and defaultInstall', () => {
{ manifest: secondManifest, dir: secondDir, enabled: true },
];
const h = harness([publicItem, nonDefault]);
- h.ledger.upsertInstallation({ ...recordForTest(publicItem), releaseId: 'release-1', version: '1.0.0', manifestDigest: ghostManifestDigest(firstManifest) });
- h.ledger.upsertInstallation({ ...recordForTest(nonDefault), releaseId: 'release-1b', version: '1.0.0', manifestDigest: ghostManifestDigest(secondManifest) });
+ h.ledger.upsertInstallation({
+ ...recordForTest(publicItem),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(firstManifest),
+ });
+ h.ledger.upsertInstallation({
+ ...recordForTest(nonDefault),
+ releaseId: 'release-1b',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(secondManifest),
+ });
const snapshot = await h.service.snapshot();
expect(runtime.install).not.toHaveBeenCalled();
- expect(snapshot.items.map((entry) => entry.installState)).toEqual(['update-available', 'update-available']);
+ expect(snapshot.items.map((entry) => entry.installState)).toEqual([
+ 'update-available',
+ 'update-available',
+ ]);
});
it('aggregates upgrade notices and filters directional controls from a single name', async () => {
const item = summary({
- scope: 'organization', organizationId: 'org-1', defaultInstall: true,
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: true,
currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
});
const oldManifest = manifest(item.ghostId, '1.0.0');
@@ -1479,24 +1683,43 @@ describe('PluginMarketService migration and defaultInstall', () => {
fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(oldManifest));
runtime.ghosts = [{ manifest: oldManifest, dir: installDir, enabled: true }];
const h = harness([item]);
- h.ledger.upsertInstallation({ ...recordForTest(item), releaseId: 'release-1', version: '1.0.0', manifestDigest: ghostManifestDigest(oldManifest) });
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(oldManifest),
+ });
const upgraded = { ...manifest(item.ghostId, '2.0.0'), name: '\u202eSecret Plugin' };
- h.api.detail.mockResolvedValueOnce({ ...item, currentRelease: { ...item.currentRelease, manifest: upgraded } } as never);
+ h.api.detail.mockResolvedValueOnce({
+ ...item,
+ currentRelease: { ...item.currentRelease, manifest: upgraded },
+ } as never);
runtime.install.mockResolvedValueOnce({ manifest: upgraded, dir: installDir, enabled: true });
await h.service.snapshot();
- expect(h.service.consumeUpgradeNotice()).toEqual({ count: 1, name: 'Secret Plugin', permissions: null, hasPermissionExpansion: false });
+ expect(h.service.consumeUpgradeNotice()).toEqual({
+ count: 1,
+ name: 'Secret Plugin',
+ permissions: null,
+ hasPermissionExpansion: false,
+ });
expect(h.service.consumeUpgradeNotice()).toBeNull();
});
it('aggregates multiple upgrades and flags permission expansion without listing names', async () => {
const first = summary({
- scope: 'organization', organizationId: 'org-1', defaultInstall: true,
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: true,
currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
});
const second = summary({
- id: `c${'b'.repeat(24)}`, ghostId: 'cindy-second', name: 'Second Plugin',
- scope: 'organization', organizationId: 'org-1', defaultInstall: true,
+ id: `c${'b'.repeat(24)}`,
+ ghostId: 'cindy-second',
+ name: 'Second Plugin',
+ scope: 'organization',
+ organizationId: 'org-1',
+ defaultInstall: true,
currentRelease: { ...summary().currentRelease, id: 'release-2b', version: '2.0.0' },
});
const firstDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-upgrade-'));
@@ -1511,20 +1734,43 @@ describe('PluginMarketService migration and defaultInstall', () => {
{ manifest: secondManifest, dir: secondDir, enabled: true },
];
const h = harness([first, second]);
- h.ledger.upsertInstallation({ ...recordForTest(first), releaseId: 'release-1', version: '1.0.0', manifestDigest: ghostManifestDigest(firstManifest) });
- h.ledger.upsertInstallation({ ...recordForTest(second), releaseId: 'release-1b', version: '1.0.0', manifestDigest: ghostManifestDigest(secondManifest) });
+ h.ledger.upsertInstallation({
+ ...recordForTest(first),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(firstManifest),
+ });
+ h.ledger.upsertInstallation({
+ ...recordForTest(second),
+ releaseId: 'release-1b',
+ version: '1.0.0',
+ manifestDigest: ghostManifestDigest(secondManifest),
+ });
h.api.detail.mockImplementation(async (id) => {
const plugin = id === first.id ? first : second;
- const nextManifest = id === first.id
- ? manifest(plugin.ghostId, '2.0.0', ['notify', 'fs'])
- : manifest(plugin.ghostId, '2.0.0');
- return { ...plugin, currentRelease: { ...plugin.currentRelease, manifest: nextManifest } } as never;
+ const nextManifest =
+ id === first.id
+ ? manifest(plugin.ghostId, '2.0.0', ['notify', 'fs'])
+ : manifest(plugin.ghostId, '2.0.0');
+ return {
+ ...plugin,
+ currentRelease: { ...plugin.currentRelease, manifest: nextManifest },
+ } as never;
});
runtime.install.mockImplementation(async (_file, expected) => {
const dir = expected.ghostId === first.ghostId ? firstDir : secondDir;
- const upgraded = { ...manifest(expected.ghostId, '2.0.0', expected.ghostId === first.ghostId ? ['notify', 'fs'] : ['notify']), name: expected.ghostId === second.ghostId ? 'Second Plugin' : 'Test Plugin' };
+ const upgraded = {
+ ...manifest(
+ expected.ghostId,
+ '2.0.0',
+ expected.ghostId === first.ghostId ? ['notify', 'fs'] : ['notify'],
+ ),
+ name: expected.ghostId === second.ghostId ? 'Second Plugin' : 'Test Plugin',
+ };
const ghost = { manifest: upgraded, dir, enabled: true };
- runtime.ghosts = runtime.ghosts.map((candidate) => candidate.manifest.id === expected.ghostId ? ghost : candidate);
+ runtime.ghosts = runtime.ghosts.map((candidate) =>
+ candidate.manifest.id === expected.ghostId ? ghost : candidate,
+ );
return ghost;
});
@@ -1608,7 +1854,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
});
const h = harness([item]);
- await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow('[NOT_FOUND]');
+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(
+ '[NOT_FOUND]',
+ );
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -1626,6 +1874,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
items: [],
unavailableReason: null,
customSourceNames: [],
+ unavailableCustomSourceNames: [],
});
expect(h.api.listAll).toHaveBeenCalledOnce();
});
@@ -1823,9 +2072,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(manifest()));
runtime.ghosts = [{ ...ghostEntry(notice.ghostId), dir: installDir }];
mockUninstallDropsGhost();
- h.ledger.upsertInstallation(
- removalRecord({ manifestDigest: ghostManifestDigest(manifest()) }),
- );
+ h.ledger.upsertInstallation(removalRecord({ manifestDigest: ghostManifestDigest(manifest()) }));
await expect(h.service.snapshot()).resolves.toMatchObject({
unavailableReason: null,
@@ -1945,15 +2192,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
it('purges a batch and exposes one combined user notice', async () => {
const secondPluginId = `c${'b'.repeat(24)}`;
- const notices = [
- removal(),
- removal({ pluginId: secondPluginId, ghostId: 'cindy-second' }),
- ];
+ const notices = [removal(), removal({ pluginId: secondPluginId, ghostId: 'cindy-second' })];
const h = harness([], notices);
- runtime.ghosts = [
- ghostEntry('cindy-test'),
- ghostEntry('cindy-second', 'Second Plugin'),
- ];
+ runtime.ghosts = [ghostEntry('cindy-test'), ghostEntry('cindy-second', 'Second Plugin')];
mockUninstallDropsGhost();
h.ledger.upsertInstallation(removalRecord());
h.ledger.upsertInstallation(
@@ -2007,15 +2248,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
it('continues the snapshot and later removals when one purge fails', async () => {
const secondPluginId = `c${'b'.repeat(24)}`;
- const notices = [
- removal(),
- removal({ pluginId: secondPluginId, ghostId: 'cindy-second' }),
- ];
+ const notices = [removal(), removal({ pluginId: secondPluginId, ghostId: 'cindy-second' })];
const h = harness([], notices);
- runtime.ghosts = [
- ghostEntry('cindy-test'),
- ghostEntry('cindy-second', 'Second Plugin'),
- ];
+ runtime.ghosts = [ghostEntry('cindy-test'), ghostEntry('cindy-second', 'Second Plugin')];
mockUninstallDropsGhost('cindy-test');
h.ledger.upsertInstallation(removalRecord());
h.ledger.upsertInstallation(
@@ -2067,23 +2302,42 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(h.ledger.installationForGhost('third-party')).toBeNull();
});
- it('treats a removed market record plus an existing directory as an id conflict', async () => {
+ it('allows explicit replacement when a removed market record has an existing directory', async () => {
const item = summary();
+ const installedDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-local-installed-'));
+ roots.push(installedDir);
+ fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(manifest()));
runtime.ghosts = [
{
manifest: manifest(),
- dir: '/userData/cindy-brain/cindy-test',
+ dir: installedDir,
enabled: true,
},
];
+ runtime.install.mockResolvedValue({
+ manifest: manifest(),
+ dir: '/userData/cindy-brain/cindy-test',
+ enabled: true,
+ });
const h = harness([item]);
h.ledger.upsertInstallation({
...recordForTest(item),
installed: false,
});
- await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow('[ALREADY_EXISTS]');
- expect(runtime.install).not.toHaveBeenCalled();
+ await expect(
+ h.service.install(item.id, reviewedInstallOptions(item, true)),
+ ).resolves.toMatchObject({
+ ghost: { manifest: { id: item.ghostId } },
+ });
+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
+ permissionBaselineManifest: manifest(),
+ });
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
+ pluginId: item.id,
+ source: 'market',
+ installed: true,
+ });
});
it('does not overwrite a local plugin that appears while an official package downloads', async () => {
@@ -2105,9 +2359,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
};
});
- await expect(
- h.service.install(item.id, reviewedInstallOptions(item)),
- ).rejects.toThrow('[PRECONDITION_FAILED]');
+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(
+ '[PRECONDITION_FAILED]',
+ );
expect(runtime.install).not.toHaveBeenCalled();
expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
});
@@ -2131,8 +2385,10 @@ describe('PluginMarketService migration and defaultInstall', () => {
const review = {
manifest: targetManifest,
permissionDiff: diffGhostPermissionItems(manifest(), targetManifest),
+ isUpdate: true,
packageSha256: 'a'.repeat(64),
installedBaseline: ghostPermissionBaselineKey(manifest()),
+ sourceType: 'server' as const,
};
runtime.install
.mockRejectedValueOnce(new GhostPackagePermissionReviewRequiredError(review))
@@ -2176,14 +2432,18 @@ describe('PluginMarketService migration and defaultInstall', () => {
manifest(),
manifest('cindy-test', '2.0.0', ['notify', 'fs']),
),
+ isUpdate: true,
packageSha256: 'a'.repeat(64),
installedBaseline: ghostPermissionBaselineKey(manifest()),
+ sourceType: 'server' as const,
};
- runtime.install.mockRejectedValueOnce(
- new GhostPackagePermissionReviewRequiredError(review),
- );
+ runtime.install.mockRejectedValueOnce(new GhostPackagePermissionReviewRequiredError(review));
const h = harness([item]);
- h.ledger.upsertInstallation({ ...recordForTest(item), releaseId: 'release-1', version: '1.0.0' });
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ });
await expect(
h.service.install(item.id, reviewedInstallOptions(item), async () => false),
@@ -2192,7 +2452,7 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(runtime.install).toHaveBeenCalledTimes(1);
});
- it('does not trust the current installed package without a digest after download', async () => {
+ it('re-reads the actual installed package as the permission baseline after download', async () => {
const item = summary({
currentRelease: { ...summary().currentRelease, id: 'release-2', version: '2.0.0' },
});
@@ -2209,20 +2469,22 @@ describe('PluginMarketService migration and defaultInstall', () => {
dir: '/userData/cindy-brain/cindy-test',
enabled: true,
});
- const downloadMock = vi.mocked(
- (await import('../download.js')).downloadVerifiedPlugin,
- );
+ const downloadMock = vi.mocked((await import('../download.js')).downloadVerifiedPlugin);
downloadMock.mockImplementationOnce(async () => {
- runtime.ghosts = [
- { manifest: currentInstalled, dir: installedDir, enabled: true },
- ];
+ runtime.ghosts = [{ manifest: currentInstalled, dir: installedDir, enabled: true }];
});
const h = harness([item]);
- h.ledger.upsertInstallation({ ...recordForTest(item), releaseId: 'release-1', version: '1.0.0' });
- await expect(
- h.service.install(item.id, reviewedInstallOptions(item)),
- ).resolves.toMatchObject({ ghost: { manifest: { version: '2.0.0' } } });
- expect(runtime.install.mock.calls[0]?.[1]).not.toHaveProperty('permissionBaselineManifest');
+ h.ledger.upsertInstallation({
+ ...recordForTest(item),
+ releaseId: 'release-1',
+ version: '1.0.0',
+ });
+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).resolves.toMatchObject({
+ ghost: { manifest: { version: '2.0.0' } },
+ });
+ expect(runtime.install.mock.calls[0]?.[1]).toMatchObject({
+ permissionBaselineManifest: currentInstalled,
+ });
});
it('rejects an update when the installed target disappears during download', async () => {
@@ -2251,9 +2513,9 @@ describe('PluginMarketService migration and defaultInstall', () => {
};
});
- await expect(
- h.service.install(item.id, reviewedInstallOptions(item)),
- ).rejects.toThrow('[PRECONDITION_FAILED]');
+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(
+ '[PRECONDITION_FAILED]',
+ );
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -2268,11 +2530,17 @@ describe('PluginMarketService migration and defaultInstall', () => {
},
});
const h = harness([reviewed]);
- h.api.listAll.mockResolvedValueOnce({ plugins: [replacement], removals: [] });
+ h.api.detail.mockResolvedValueOnce({
+ ...replacement,
+ currentRelease: {
+ ...replacement.currentRelease,
+ manifest: manifest(replacement.ghostId, replacement.currentRelease.version),
+ },
+ });
- await expect(
- h.service.install(reviewed.id, reviewedInstallOptions(reviewed)),
- ).rejects.toThrow('[PRECONDITION_FAILED]');
+ await expect(h.service.install(reviewed.id, reviewedInstallOptions(reviewed))).rejects.toThrow(
+ '[PRECONDITION_FAILED]',
+ );
expect(h.api.download).not.toHaveBeenCalled();
expect(runtime.install).not.toHaveBeenCalled();
});
@@ -2287,23 +2555,33 @@ describe('PluginMarketService migration and defaultInstall', () => {
sizeBytes: item.currentRelease.sizeBytes,
});
- await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow('[PRECONDITION_FAILED]');
+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(
+ '[PRECONDITION_FAILED]',
+ );
expect(runtime.install).not.toHaveBeenCalled();
});
it('cancels an install if the active data owner changes during the request', async () => {
const item = summary();
const h = harness([item]);
- h.api.listAll.mockImplementationOnce(async () => {
+ h.api.detail.mockImplementationOnce(async () => {
runtime.session = {
mode: 'cloud',
dataOwnerId: 'user-2',
generation: 2,
};
- return { plugins: [item], removals: [] };
+ return {
+ ...item,
+ currentRelease: {
+ ...item.currentRelease,
+ manifest: manifest(item.ghostId, item.currentRelease.version),
+ },
+ };
});
- await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow('[PRECONDITION_FAILED]');
+ await expect(h.service.install(item.id, reviewedInstallOptions(item))).rejects.toThrow(
+ '[PRECONDITION_FAILED]',
+ );
expect(runtime.install).not.toHaveBeenCalled();
expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
});
diff --git a/apps/desktop/src/main/plugin-market/api.ts b/apps/desktop/src/main/plugin-market/api.ts
index ed34be54c3..969ee4926b 100644
--- a/apps/desktop/src/main/plugin-market/api.ts
+++ b/apps/desktop/src/main/plugin-market/api.ts
@@ -14,6 +14,7 @@ import { createLogger } from '../logger.js';
import { serverApiFetch, type ApiFetchOptions } from '../serverApiClient.js';
const log = createLogger('plugin-market-api');
+const PLUGIN_MARKET_API_TIMEOUT_MS = 15_000;
type Fetcher = <T>(
apiPath: string,
@@ -42,6 +43,7 @@ export class PluginMarketApi {
return {
cache: 'no-store',
headers: { [CINDY_CLIENT_VERSION_HEADER]: this.getClientVersion() },
+ timeoutMs: PLUGIN_MARKET_API_TIMEOUT_MS,
};
}
diff --git a/apps/desktop/src/main/plugin-market/download.ts b/apps/desktop/src/main/plugin-market/download.ts
index eb4e1814c3..5bf0da3845 100644
--- a/apps/desktop/src/main/plugin-market/download.ts
+++ b/apps/desktop/src/main/plugin-market/download.ts
@@ -4,6 +4,7 @@ import fs from 'node:fs';
import { net } from 'electron';
const MAX_PLUGIN_BYTES = 8 * 1024 * 1024;
+const PLUGIN_DOWNLOAD_TIMEOUT_MS = 60_000;
/** 下载并校验 `.cindy` 原始字节,写入调用方提供的临时路径。 */
export async function downloadVerifiedPlugin(
@@ -18,6 +19,7 @@ export async function downloadVerifiedPlugin(
method: 'GET',
cache: 'no-store',
redirect: 'error',
+ signal: AbortSignal.timeout(PLUGIN_DOWNLOAD_TIMEOUT_MS),
});
if (!response.ok) throw new Error(`Plugin 下载失败 (${response.status})`);
if (!response.body) throw new Error('Plugin 下载响应体为空');
diff --git a/apps/desktop/src/main/plugin-market/install.ts b/apps/desktop/src/main/plugin-market/install.ts
index d450f0a9a9..261d4ee217 100644
--- a/apps/desktop/src/main/plugin-market/install.ts
+++ b/apps/desktop/src/main/plugin-market/install.ts
@@ -16,13 +16,17 @@ import { app } from 'electron';
import {
validateGhostManifest,
- type GhostManifest,
type InstalledGhost,
} from '../../shared/ghost.js';
+import type {
+ PluginMarketItemSource,
+ PluginMarketPackageReviewFacts,
+} from '../../shared/pluginMarket.js';
import {
installOrUpdateMarketGhostPackage,
rejectReservedGhostIdForCustomMarket,
} from '../cindy-brain/index.js';
+import { GhostPackagePermissionReviewRequiredError } from '../cindy-brain/packagePermissionReview.js';
import { packGhostDirToFile } from '../cindy-brain/forge.js';
import { createLogger } from '../logger.js';
import { isIpcError } from '../../shared/ipc-errors.js';
@@ -36,9 +40,8 @@ import {
/**
* 把插件目录装成运行中的 Ghost。
*
- * expected 是 Renderer 确认框实际审阅过的完整 manifest;这里重读 ghost.json
- * 逐字比对,确认到打包之间目录被改动时拒绝滑入(与服务端市场的
- * expectedReleaseId 同一防线,但自定义市场必须核对权限与能力声明本身)。
+ * Renderer 不再批准发现阶段的目录 manifest。这里先安全打包,再让 Main
+ * 从实际 `.cindy` 解析 canonical manifest;确认和落位始终绑定同一个临时包。
*/
const log = createLogger('plugin-market-install');
@@ -54,7 +57,13 @@ function sanitizeInstallDetail(message: string): string {
export async function installCustomMarketPlugin(input: {
pluginDir: string;
- expected: GhostManifest;
+ expectedGhostId: string;
+ expectedVersion: string;
+ sourceType: Extract<PluginMarketItemSource, 'git-market' | 'local-market'>;
+ permissionBaselineManifest?: PluginMarketPackageReviewFacts['manifest'];
+ reviewPackagePermissions?: (
+ facts: PluginMarketPackageReviewFacts,
+ ) => Promise<boolean>;
/**
* 打包完成后、实际改动 Ghost 运行时之前调用的校验钩(可异步)。
* 自定义市场按调用方捕获的账户审阅 manifest;打包是异步的,装出前必须
@@ -62,6 +71,10 @@ export async function installCustomMarketPlugin(input: {
* 这里同时复核当前账号、所选来源和运行时已安装插件事实。
*/
beforeCommit?: () => void | Promise<void>;
+ /** 真实包完成检查后、即将改动运行时前的同步事务钩。 */
+ beforePackagePlacement?: () => void;
+ /** 新包完成原子换位后的同步事务钩。 */
+ onPackagePlaced?: () => void;
/**
* 提交段(复核 + 落位)的互斥包装,与来源增删共享同一把锁。
*
@@ -78,8 +91,11 @@ export async function installCustomMarketPlugin(input: {
* 插在"包已落位"与"写下溯源"之间换掉同 id 的包,账本随后认领一个其实已被替换
* 的包。抛错则整个安装按失败上报(包已落位,由调用方决定补偿)。
*/
- afterCommit?: () => Promise<void>;
-}): Promise<InstalledGhost> {
+ afterCommit?: (
+ installed: InstalledGhost,
+ packagedManifest: PluginMarketPackageReviewFacts['manifest'],
+ ) => Promise<void>;
+}): Promise<InstalledGhost | null> {
// input.pluginDir 是发现层已 realpath、且已校验落在市场根内的规范路径。
// 发现之后、打包之前,若插件目录或其某个父目录被换成指向市场外的符号链接,
// 重新 realpath 会解析到别处——只要外部目录留着同样的 ghost.json,清单摘要
@@ -127,6 +143,12 @@ export async function installCustomMarketPlugin(input: {
if (!validated.ok) {
throwIpcError('GHOST_FILE_INVALID', sanitizeInstallDetail(validated.reason));
}
+ if (
+ validated.manifest.id !== input.expectedGhostId ||
+ validated.manifest.version !== input.expectedVersion
+ ) {
+ throwIpcError('PRECONDITION_FAILED', 'The Plugin identity changed after selection');
+ }
rejectReservedGhostIdForCustomMarket(validated.manifest.id);
const tempPath = path.join(
@@ -149,30 +171,57 @@ export async function installCustomMarketPlugin(input: {
sanitizeInstallDetail(packed.message),
);
}
- // 唯一防篡改防线:比对实际打进包的 manifest,而非打包前磁盘上的 ghost.json。
- // 堵住"前置比对通过后、打包读取文件前"目录被改(保持 id/version 却新增
- // 权限声明)的窗口——装的就是 packed.manifest,必须以它为准。
- if (JSON.stringify(packed.manifest) !== JSON.stringify(input.expected)) {
- throwIpcError(
- 'PRECONDITION_FAILED',
- 'Plugin changed after permission review',
- );
- }
- // 装出前最后防线:打包期间账号、所选来源或运行时插件状态都可能已变化。
- // 复核与落位必须在同一把锁内完成,否则复核结论会在落位前过期。
- const commit = async (): Promise<InstalledGhost> => {
- await input.beforeCommit?.();
- // 自定义来源已经把 Renderer 审阅的本地清单与实际打包清单逐字节绑定,
- // 不再进入官方市场“下载真实包后复核”的分支。
- const installed = await installOrUpdateMarketGhostPackage(tempPath, {
- ghostId: validated.manifest.id,
- version: validated.manifest.version,
- });
- // 溯源写入与落位同锁(见 afterCommit 注释)。
- await input.afterCommit?.();
- return installed;
+ const permissionPolicy = { mode: 'manual' as const, sourceType: input.sourceType };
+ const commit = async (
+ approval?: Pick<PluginMarketPackageReviewFacts, 'packageSha256' | 'installedBaseline'>,
+ ): Promise<InstalledGhost> => {
+ const run = async (): Promise<InstalledGhost> => {
+ await input.beforeCommit?.();
+ const installed = await installOrUpdateMarketGhostPackage(tempPath, {
+ // Main 会从真实临时包再次解析并与所选市场条目的身份核对;不能使用
+ // 打包前活目录里的值,否则目录在打包窗口变化时会把另一个插件装入。
+ ghostId: input.expectedGhostId,
+ version: input.expectedVersion,
+ permissionPolicy,
+ ...(input.permissionBaselineManifest
+ ? { permissionBaselineManifest: input.permissionBaselineManifest }
+ : {}),
+ ...(approval
+ ? {
+ approvedPackageSha256: approval.packageSha256,
+ ...(approval.installedBaseline !== null
+ ? { reviewedBaseline: approval.installedBaseline }
+ : {}),
+ }
+ : {}),
+ ...(input.beforePackagePlacement
+ ? { beforeCommitInLock: input.beforePackagePlacement }
+ : {}),
+ ...(input.onPackagePlaced
+ ? { onPackagePlacedInLock: input.onPackagePlaced }
+ : {}),
+ });
+ // 溯源写入与落位同锁(见 afterCommit 注释)。
+ await input.afterCommit?.(installed, packed.manifest);
+ return installed;
+ };
+ return input.withCommitLock ? input.withCommitLock(run) : run();
};
- return await (input.withCommitLock ? input.withCommitLock(commit) : commit());
+
+ let review: PluginMarketPackageReviewFacts;
+ try {
+ // 首装或扩权会在任何运行时写入前暂停;无扩权更新则在同一锁内直接落位。
+ return await commit();
+ } catch (error) {
+ if (!(error instanceof GhostPackagePermissionReviewRequiredError)) throw error;
+ review = error.review;
+ }
+ const approved = await input.reviewPackagePermissions?.(review);
+ if (approved !== true) return null;
+
+ // 确认返回后重新取得来源/ghost 锁,复核来源、当前安装基线与真实包 SHA。
+ // 确认期间不持锁,取消或窗口销毁可立即结束并清理临时包。
+ return await commit(review);
} finally {
await fs.promises.rm(tempPath, { force: true }).catch(() => undefined);
}
diff --git a/apps/desktop/src/main/plugin-market/ledger.ts b/apps/desktop/src/main/plugin-market/ledger.ts
index 26291c06ef..adc37be281 100644
--- a/apps/desktop/src/main/plugin-market/ledger.ts
+++ b/apps/desktop/src/main/plugin-market/ledger.ts
@@ -228,6 +228,28 @@ export class PluginMarketLedger {
this.write(data);
}
+ /** 换源落位前失败时,将旧路由和原有默认安装退订状态一起原子恢复。 */
+ restoreInstallation(
+ record: PluginMarketInstallationRecord,
+ optOut?: { userId: string; suppressed: boolean },
+ ): void {
+ const data = this.read();
+ data.installations[record.ghostId] = record;
+ if (optOut) {
+ const suppressedPluginIds = data.defaultInstallOptOuts[optOut.userId] ?? [];
+ if (optOut.suppressed) {
+ data.defaultInstallOptOuts[optOut.userId] = [
+ ...new Set([...suppressedPluginIds, record.pluginId]),
+ ];
+ } else {
+ const restored = suppressedPluginIds.filter((pluginId) => pluginId !== record.pluginId);
+ if (restored.length > 0) data.defaultInstallOptOuts[optOut.userId] = restored;
+ else delete data.defaultInstallOptOuts[optOut.userId];
+ }
+ }
+ this.write(data);
+ }
+
markRemoved(ghostId: string, userId: string | null): void {
const data = this.read();
const record = data.installations[ghostId];
diff --git a/apps/desktop/src/main/plugin-market/packagePermissionReviewBridge.ts b/apps/desktop/src/main/plugin-market/packagePermissionReviewBridge.ts
index 750d967d53..9ed54041b5 100644
--- a/apps/desktop/src/main/plugin-market/packagePermissionReviewBridge.ts
+++ b/apps/desktop/src/main/plugin-market/packagePermissionReviewBridge.ts
@@ -1,5 +1,5 @@
/**
- * 官方市场真实包权限确认的 Main ↔ Renderer 往返桥。
+ * 市场真实包权限确认的 Main ↔ Renderer 往返桥。
*
* 它只保存“当前窗口对当前弹框的回答”,不保存包路径、安装状态或批准记录。
* 安装事务本身仍停在 service.install() 的调用栈里;确认、取消或窗口销毁后,
@@ -12,6 +12,7 @@ import type {
PluginMarketPackageReviewFacts,
PluginMarketPackageReviewRequest,
} from '../../shared/pluginMarket.js';
+import type { DataOwnerPushStamp } from '../../shared/dataOwnerPush.js';
interface PendingReview {
requesterId: number;
@@ -24,6 +25,7 @@ export class PluginMarketPackagePermissionReviewBridge {
request(
requesterId: number,
facts: PluginMarketPackageReviewFacts,
+ ownerStamp: DataOwnerPushStamp,
send: (request: PluginMarketPackageReviewRequest) => boolean,
): Promise<boolean> {
const requestId = randomUUID();
@@ -33,8 +35,11 @@ export class PluginMarketPackagePermissionReviewBridge {
try {
delivered = send({
requestId,
+ ownerStamp,
manifest: facts.manifest,
permissionDiff: facts.permissionDiff,
+ isUpdate: facts.isUpdate,
+ sourceType: facts.sourceType,
});
} finally {
if (!delivered) this.settle(requestId, false);
diff --git a/apps/desktop/src/main/plugin-market/registerIpc.ts b/apps/desktop/src/main/plugin-market/registerIpc.ts
index e87be5c89d..e15203c38a 100644
--- a/apps/desktop/src/main/plugin-market/registerIpc.ts
+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts
@@ -3,8 +3,8 @@ import os from 'node:os';
import { ipcMain, type WebContents } from 'electron';
import { isIpcError } from '../../shared/ipc-errors.js';
-import type { GhostManifest } from '../../shared/ghost.js';
import { isPluginMarketCustomIconKey } from '../../shared/pluginMarket.js';
+import { getActiveDataOwnerPushStamp } from '../appSessionState.js';
import {
sendToTrustedAppWindows,
setGhostUninstallLedgerPreparer,
@@ -15,7 +15,10 @@ import { requireObject, requireString, throwIpcError } from '../utils/ipcValidat
import { parseMarketSource } from './sources/parse.js';
import { LocalIconRequestGate } from './localIconRequestGate.js';
import { PluginMarketPackagePermissionReviewBridge } from './packagePermissionReviewBridge.js';
-import { PluginMarketService } from './service.js';
+import {
+ PluginMarketService,
+ type PluginMarketSnapshotOptions,
+} from './service.js';
const log = createLogger('plugin-market-ipc');
let registered = false;
@@ -42,9 +45,9 @@ function signalUpgradeNoticeAvailable(): void {
sendToTrustedAppWindows(UPGRADE_NOTICE_AVAILABLE_CHANNEL, undefined);
}
-async function snapshotAndSignalRemovalNotice() {
+async function snapshotAndSignalRemovalNotice(options?: PluginMarketSnapshotOptions) {
try {
- return await service().snapshot();
+ return await service().snapshot(options);
} finally {
// 清理已成功但后续默认安装等步骤失败时,pending 仍必须通知 Renderer;
// snapshot 的原始异常继续向上抛,不把通知信号伪装成整轮成功。
@@ -109,7 +112,15 @@ export function registerPluginMarketIpc(): void {
);
ipcMain.handle('plugin-market:snapshot', (event) => {
assertTrustedAppRendererEvent(event);
- return invokePluginMarket(() => snapshotAndSignalRemovalNotice());
+ return invokePluginMarket(() =>
+ snapshotAndSignalRemovalNotice({
+ deferDefaultReconciliation: true,
+ onDeferredReconciliationSettled: () => {
+ signalRemovalNoticeAvailable();
+ signalUpgradeNoticeAvailable();
+ },
+ }),
+ );
});
ipcMain.handle('plugin-market:consume-removal-notice', (event) => {
assertTrustedAppRendererEvent(event);
@@ -156,30 +167,26 @@ export function registerPluginMarketIpc(): void {
typeof options === 'object' && options !== null
? (options as {
expectedReleaseId?: unknown;
- expectedManifest?: unknown;
- allowPermissionExpansion?: unknown;
- reviewedBaseline?: unknown;
+ allowSourceReplacement?: unknown;
})
: null;
const expectedReleaseId = requireString(obj?.expectedReleaseId, 'expectedReleaseId');
- const expectedManifest = requireObject(obj?.expectedManifest);
- const allowPermissionExpansion = obj?.allowPermissionExpansion === true;
- // 扩权批准的审阅基线:只收字符串,野值按缺席处理(缺席 = 保持旧行为)。
- const reviewedBaseline =
- typeof obj?.reviewedBaseline === 'string' ? obj.reviewedBaseline : undefined;
+ const allowSourceReplacement = obj?.allowSourceReplacement;
+ if (typeof allowSourceReplacement !== 'boolean') {
+ throwIpcError('INVALID_PARAMS', 'allowSourceReplacement must be a boolean');
+ }
return invokePluginMarket(() =>
service().install(
requireString(pluginId, 'pluginId'),
{
expectedReleaseId,
- expectedManifest: expectedManifest as unknown as GhostManifest,
- allowPermissionExpansion,
- ...(reviewedBaseline !== undefined ? { reviewedBaseline } : {}),
+ allowSourceReplacement,
},
(facts) =>
packagePermissionReviewBridge.request(
event.sender.id,
facts,
+ getActiveDataOwnerPushStamp(),
(request) => {
if (event.sender.isDestroyed()) return false;
event.sender.send(PACKAGE_PERMISSION_REVIEW_CHANNEL, request);
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index 8d5054dcab..2e40fb964b 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -14,7 +14,6 @@ import { app, dialog } from 'electron';
import {
diffGhostPermissionItems,
GHOST_ICON_MAX_BYTES,
- ghostPermissionBaselineKey,
ghostIconMimeType,
isSafeGhostRelativePath,
isOfficialGhostId,
@@ -93,7 +92,6 @@ const log = createLogger('plugin-market');
type PackagePermissionReviewer = (facts: PluginMarketPackageReviewFacts) => Promise<boolean>;
class SilentUpgradeBusyError extends Error {}
-class SilentUpgradeStaleBaselineError extends Error {}
class SilentDefaultInstallCancelledError extends Error {}
/**
@@ -112,30 +110,7 @@ class SilentDefaultInstallCancelledError extends Error {}
*/
const SOURCE_MUTATION_KEY = 'market-sources';
const CUSTOM_ICON_PROJECTION_TOKEN_RE = /^[a-f0-9]{16}$/;
-
-/**
- * 扩权批准的原子复核:Renderer 的 allowPermissionExpansion 只代表「用户对
- * **某一份**已装 manifest 与目标包之间的差异点过同意」。它到达这里之前有一段
- * 往返窗口,期间「从文件更新」等路径可能整体替换已装 manifest(ghosts.update()
- * 没有版本单调性检查),那份同意就不再对应现实——继续放行等于让旧批准覆盖
- * 相对新 manifest 的全部新增权限。
- *
- * 所以带审阅基线来的批准,必须在安装锁内、真正放行扩权之前,拿**当前**已装
- * manifest 重算指纹比对;不一致就拒绝这次批准,由 Renderer 回到重新审阅。
- * 基线缺席时保持既有行为(旧版本 Renderer / 首装无基线可比),不新增拒绝面。
- */
-function assertReviewedBaselineFresh(
- installed: GhostManifest,
- reviewedBaseline: string | undefined,
-): void {
- if (reviewedBaseline === undefined) return;
- if (ghostPermissionBaselineKey(installed) !== reviewedBaseline) {
- throwIpcError(
- 'PRECONDITION_FAILED',
- 'Installed Plugin permissions changed after review; re-review required',
- );
- }
-}
+const CUSTOM_MARKET_SNAPSHOT_TIMEOUT_MS = 3_000;
function captureMarketOwner(): ActiveAppSession {
const session = getActiveAppSession();
@@ -172,6 +147,19 @@ function visiblePluginsForOwner(
: [...plugins];
}
+/** 单条详情由服务端完成账号授权;本地模式仍需执行客户端能力边界。 */
+function requirePluginVisibleForOwner(
+ owner: ActiveAppSession,
+ plugin: VisiblePluginSummary | VisiblePluginDetail,
+): void {
+ if (
+ owner.mode === 'local' &&
+ (plugin.scope !== 'public' || !isGhostAvailableForActiveSession(plugin.ghostId))
+ ) {
+ throwIpcError('NOT_FOUND', 'Plugin is unavailable to the active account');
+ }
+}
+
function defaultInstallSubject(owner: ActiveAppSession): string {
const subject = getCurrentUserId() ?? owner.dataOwnerId;
if (!subject) {
@@ -265,6 +253,24 @@ interface CustomMarketEntry {
iconKey: string | null;
}
+interface CustomMarketDiscovery {
+ entries: CustomMarketEntry[];
+ unavailableSourceNames: string[];
+}
+
+interface CustomMarketDiscoveryProgress {
+ entries: CustomMarketEntry[];
+ settledSourceNames: Set<string>;
+ unavailableSourceNames: Set<string>;
+}
+
+export interface PluginMarketSnapshotOptions {
+ /** Renderer 目录请求先返回;默认安装/升级在同一 owner 上后台补做。 */
+ deferDefaultReconciliation?: boolean;
+ /** 延后对账完成(成功或失败)后通知 IPC 层刷新一次性提示。 */
+ onDeferredReconciliationSettled?: () => void;
+}
+
/**
* 已安装插件的 locale 无关 manifest 摘要。运行时 `InstalledGhost.manifest` 是
* **按当前界面语言本地化后的**(GhostManager.readInstalledLocalizedManifest),
@@ -415,8 +421,8 @@ function isDeterministicLocalIconReadFailure(error: unknown): boolean {
return code === 'ENOENT' || code === 'ENOTDIR' || code === 'EISDIR' || code === 'ELOOP';
}
-/** 官方市场是否仍拥有当前落地包;带摘要的新记录必须与磁盘事实一致。 */
-function serverMarketOwnsInstalledGhost(
+/** 官方市场记录是否仍匹配当前落地包,可作为自动更新路由。 */
+function serverRecordMatchesInstalledGhost(
pluginId: string,
ghost: InstalledGhost,
record: PluginMarketInstallationRecord | null,
@@ -443,7 +449,7 @@ function canBackfillOfficialCindyGithubTrust(
record.source === 'market' &&
record.manifestDigest !== undefined &&
!hasCindyOfficialTrustMetadata(installed.dir) &&
- serverMarketOwnsInstalledGhost(record.pluginId, installed, record)
+ serverRecordMatchesInstalledGhost(record.pluginId, installed, record)
);
}
@@ -509,7 +515,7 @@ export class PluginMarketService {
),
) {}
- async snapshot(): Promise<PluginMarketSnapshot> {
+ async snapshot(options: PluginMarketSnapshotOptions = {}): Promise<PluginMarketSnapshot> {
// 自定义市场项完全来自本地数据,不依赖服务端与登录态;服务端不可用时
// 仍然返回,unavailableReason 只表达服务端部分的不可用。
//
@@ -531,36 +537,51 @@ export class PluginMarketService {
? 'authentication-required'
: 'not-configured',
customSourceNames: [],
+ unavailableCustomSourceNames: [],
};
}
const iconProjectionGeneration = this.nextCustomIconProjectionGeneration();
- const customEntries = await this.discoverCustomEntriesSafe(owner, iconProjectionGeneration);
const customSourceNames = this.customSourceNamesSafe(owner);
- requireSameMarketOwner(owner);
+ const customDiscoveryPromise = this.discoverCustomEntriesBounded(
+ owner,
+ iconProjectionGeneration,
+ customSourceNames,
+ );
if (!getClientEndpoint('pluginApiBaseUrl')) {
+ const customDiscovery = await customDiscoveryPromise;
+ requireSameMarketOwner(owner);
return {
- items: this.projectCustomItems(customEntries),
- unavailableReason: customEntries.length > 0 ? null : 'not-configured',
+ items: this.projectCustomItems(customDiscovery.entries),
+ unavailableReason: customSourceNames.length > 0 ? null : 'not-configured',
customSourceNames,
+ unavailableCustomSourceNames: customDiscovery.unavailableSourceNames,
};
}
let plugins: VisiblePluginSummary[];
let removals: PluginRemovalNotice[];
+ let customDiscovery: CustomMarketDiscovery;
try {
- const catalog = await this.api.listAll();
+ // 官方目录与自定义发现并行;单个本地/网络盘来源卡顿不会串行拖住官方请求。
+ const [catalog, discovered] = await Promise.all([
+ this.api.listAll(),
+ customDiscoveryPromise,
+ ]);
plugins = visiblePluginsForOwner(owner, catalog.plugins);
removals = catalog.removals;
+ customDiscovery = discovered;
} catch (error) {
log.warn('market list unavailable', {
error: error instanceof Error ? error.message : String(error),
});
// 本函数捕获 owner 后的每个 return 出口都必须先过 generation 校验:
// listAll 失败(常因切号)时,不能把按旧账号发现的自定义项返回给当前会话。
+ customDiscovery = await customDiscoveryPromise;
requireSameMarketOwner(owner);
return {
- items: this.projectCustomItems(customEntries),
+ items: this.projectCustomItems(customDiscovery.entries),
unavailableReason: error instanceof Error ? error.message : String(error),
customSourceNames,
+ unavailableCustomSourceNames: customDiscovery.unavailableSourceNames,
};
}
@@ -576,22 +597,38 @@ export class PluginMarketService {
// before its ledger write. Wait for queued ledger mutations before deciding
// whether a default plugin should be installed again.
await this.ledgerMutation;
- // 自定义来源只影响自己的目录发现;暂时不可读的来源不能阻塞官方默认安装。
- // 已经落地的同 id 插件仍由 applyDefaultInstalls → installDetail 的本地事实检查保护。
- await this.applyDefaultInstalls(plugins, owner, ledger);
- await this.applyDefaultUpgrades(plugins, owner, ledger);
+ const reconcileDefaults = async () => {
+ // 自定义来源只影响自己的目录发现;暂时不可读的来源不能阻塞官方默认安装。
+ // 已经落地的同 id 插件仍由 applyDefaultInstalls → installDetail 的本地事实检查保护。
+ await this.applyDefaultInstalls(plugins, owner, ledger);
+ await this.applyDefaultUpgrades(plugins, owner, ledger);
+ };
+ if (!options.deferDefaultReconciliation) await reconcileDefaults();
requireSameMarketOwner(owner);
const local = this.localInstallSnapshot(ledger);
const serverItems = plugins.map((plugin) => this.toItem(plugin, local));
- const items = [...serverItems, ...this.projectCustomItems(customEntries, local)];
+ const items = [...serverItems, ...this.projectCustomItems(customDiscovery.entries, local)];
// 聚合完成、返回 Renderer 前最后校验:账号在任一 await 间隙漂移则拒绝,
// 不把按旧账号解析的自定义项/账本状态发给当前会话。
requireSameMarketOwner(owner);
- return {
+ const snapshot = {
items,
unavailableReason: null,
customSourceNames,
+ unavailableCustomSourceNames: customDiscovery.unavailableSourceNames,
};
+ if (options.deferDefaultReconciliation) {
+ // 目录展示不等待默认插件下载;对账仍复用原有串行锁和 owner 校验。
+ void Promise.resolve()
+ .then(reconcileDefaults)
+ .catch((error) => {
+ log.warn('deferred default plugin reconciliation failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ })
+ .finally(options.onDeferredReconciliationSettled);
+ }
+ return snapshot;
}
/** 按当前 owner 消费一次清理汇总,避免组织插件名跨账号泄露。 */
@@ -636,18 +673,9 @@ export class PluginMarketService {
}
this.requireConfigured();
return this.runForOwner(async (owner) => {
- const catalog = visiblePluginsForOwner(owner, (await this.api.listAll()).plugins);
- requireSameMarketOwner(owner);
- const summary = catalog.find((candidate) => candidate.id === pluginId);
- if (!summary) {
- throwIpcError('NOT_FOUND', 'Plugin is unavailable to the active account');
- }
const plugin = await this.api.detail(pluginId);
requireSameMarketOwner(owner);
- assertDetailMatchesSummary(summary, plugin);
- if (owner.mode === 'local' && plugin.scope !== 'public') {
- throwIpcError('PERMISSION_DENIED', 'Local mode can only access public Plugins');
- }
+ requirePluginVisibleForOwner(owner, plugin);
const compatible = validateGhostManifest(plugin.currentRelease.manifest);
if (!compatible.ok) {
throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');
@@ -820,7 +848,7 @@ export class PluginMarketService {
): Promise<PluginMarketInstallResult> {
const customRef = parseCustomMarketPluginId(pluginId);
if (customRef) {
- return this.customInstall(customRef, options);
+ return this.customInstall(customRef, options, reviewPackagePermissions);
}
if (!isValidPluginResourceId(pluginId)) {
throwIpcError('INVALID_PARAMS', 'Invalid Plugin ID');
@@ -830,29 +858,15 @@ export class PluginMarketService {
const ledger = this.ledgerForOwner(owner);
return this.withMutation(pluginId, async () => {
requireSameMarketOwner(owner);
- const catalog = visiblePluginsForOwner(owner, (await this.api.listAll()).plugins);
- requireSameMarketOwner(owner);
- const selected = catalog.find((plugin) => plugin.id === pluginId);
- if (!selected) {
- throwIpcError('NOT_FOUND', 'Plugin is unavailable to the active account');
- }
- if (catalog.filter((plugin) => plugin.ghostId === selected.ghostId).length !== 1) {
- throwIpcError('ALREADY_EXISTS', 'Multiple market Plugins use the same Plugin ID');
- }
const plugin = await this.api.detail(pluginId);
requireSameMarketOwner(owner);
- assertDetailMatchesSummary(selected, plugin);
+ requirePluginVisibleForOwner(owner, plugin);
if (plugin.currentRelease.id !== options.expectedReleaseId) {
- throwIpcError('PRECONDITION_FAILED', 'Plugin release changed after permission review');
+ throwIpcError('PRECONDITION_FAILED', 'Plugin release changed after selection');
}
const compatible = validateGhostManifest(plugin.currentRelease.manifest);
- const reviewed = validateGhostManifest(options.expectedManifest);
- if (
- !compatible.ok ||
- !reviewed.ok ||
- ghostManifestDigest(compatible.manifest) !== ghostManifestDigest(reviewed.manifest)
- ) {
- throwIpcError('PRECONDITION_FAILED', 'Plugin manifest changed after permission review');
+ if (!compatible.ok) {
+ throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');
}
if (!manifestSupportsCurrentCindy(compatible.manifest)) {
throwIpcError('NOT_FOUND', 'This Plugin is unavailable for this Cindy version');
@@ -864,12 +878,9 @@ export class PluginMarketService {
plugin,
{
expectedInstalled: Boolean(existing),
- reviewedManifest: compatible.manifest,
- allowPermissionExpansion: options.allowPermissionExpansion === true,
+ permissionPolicy: { mode: 'manual', sourceType: 'server' },
reviewPackagePermissions,
- ...(options.reviewedBaseline !== undefined
- ? { reviewedBaseline: options.reviewedBaseline }
- : {}),
+ allowSourceReplacement: options.allowSourceReplacement === true,
},
owner,
ledger,
@@ -1059,14 +1070,9 @@ export class PluginMarketService {
*/
private async customInstall(
ref: { marketName: string; ghostId: string },
- options: {
- expectedReleaseId: string;
- expectedManifest: GhostManifest;
- allowPermissionExpansion?: boolean;
- /** 扩权批准所依据的已装权限指纹;安装锁内复核,详见 install() 的说明。 */
- reviewedBaseline?: string;
- },
- ): Promise<{ ghost: InstalledGhost }> {
+ options: PluginMarketInstallOptions,
+ reviewPackagePermissions?: PackagePermissionReviewer,
+ ): Promise<PluginMarketInstallResult> {
const owner = captureMarketOwner();
const ledger = this.ledgerForOwner(owner);
const manager = this.sourceManagerForOwner(owner);
@@ -1089,57 +1095,50 @@ export class PluginMarketService {
const pluginId = customMarketPluginId(ref.marketName, plugin.ghostId);
const releaseId = customMarketReleaseId(ref.marketName, plugin.ghostId, plugin.version);
if (releaseId !== options.expectedReleaseId) {
- throwIpcError('PRECONDITION_FAILED', 'Plugin release changed after permission review');
+ throwIpcError('PRECONDITION_FAILED', 'Plugin release changed after selection');
}
const existing = getGhostManager()
.list()
.find((ghost) => ghost.manifest.id === plugin.ghostId);
- const currentRecord = ledger.installationForGhost(plugin.ghostId);
- // 所有权 = pluginId、来源指纹、安装时 manifest 摘要**同时**对上。市场名
- // 可复用(同名异源重加得到相同 pluginId);运行时的包在降级窗口可被旧版
- // 换成本地安装的任何东西(旧版不认识 custom 账本,不会更新它)——只凭
- // 记录存在就认领,会把别人的包错误归属给本来源并放行其更新覆盖。
const sourceKey = marketSourceKey(discovered.config.source);
- // 审阅时刻的已装内容摘要:所有权/收养判定与提交段复核共用同一份快照。
+ // 审阅时刻的已装内容摘要:确认等待和打包窗口内不能换掉当前包。
const reviewInstalledDigest = existing
? installedGhostRawManifestDigest(existing.dir)
: null;
- const ownsInstall = Boolean(
- existing &&
- currentRecord?.installed &&
- currentRecord.pluginId === pluginId &&
- currentRecord.sourceKey === sourceKey &&
- currentRecord.manifestDigest != null &&
- currentRecord.manifestDigest === reviewInstalledDigest,
- );
- // 收养:运行时已装内容的声明与本来源候选**完全一致**(原始 manifest 摘要
- // 相等)时,允许在没有有效账本记录的情况下重装并补写溯源。这是"包已落位
- // 但账本写失败"(文件锁/磁盘错)后的唯一自愈入口——否则该插件永久 conflict、
- // 更新永被拒。安全性:收养走完整重装,落位字节来自本来源的包,且用户刚在
- // 确认框审阅过同一份 manifest;声明有任何差异都收养不了。
- const adoptable = Boolean(
+ const currentRecord = ledger.installationForGhost(plugin.ghostId);
+ const matchesSelectedRoute = Boolean(
existing &&
- !ownsInstall &&
- reviewInstalledDigest === ghostManifestDigest(plugin.manifest),
+ currentRecord?.installed &&
+ currentRecord.pluginId === pluginId &&
+ currentRecord.sourceKey === sourceKey &&
+ currentRecord.manifestDigest != null &&
+ currentRecord.manifestDigest === reviewInstalledDigest,
);
- if (existing && !ownsInstall && !adoptable) {
+ if (existing && !matchesSelectedRoute && options.allowSourceReplacement !== true) {
throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');
}
- if (
- existing &&
- // 与服务端安装同口径:对比已装 manifest 与候选包,只有新增权限才要求
- // 显式确认(upstream 已回退批准 receipt 基线,这里跟随主干口径)。
- diffGhostPermissionItems(existing.manifest, plugin.manifest).added.length > 0
- ) {
- if (options.allowPermissionExpansion !== true) {
- throwIpcError('PRECONDITION_FAILED', 'Plugin permissions changed and require review');
- }
- assertReviewedBaselineFresh(existing.manifest, options.reviewedBaseline);
- }
+ // 来源只决定后台更新路由,不是 ghostId 的永久所有权。只有详情页明确
+ // 选择“替换”才允许原地切换来源;普通更新和“全部更新”必须保持当前路由。
+ // 权限基线始终取当前真实安装,避免换源绕过扩权确认。
+ const permissionBaselineManifest = existing
+ ? installedGhostRawManifest(existing.dir)
+ : null;
+ let replacedRoute: PluginMarketInstallationRecord | null = null;
+ let replacedRouteWasSuppressed = false;
+ let packageLanded = false;
requireSameMarketOwner(owner);
const ghost = await installCustomMarketPlugin({
pluginDir: plugin.dir,
- expected: options.expectedManifest,
+ expectedGhostId: plugin.ghostId,
+ expectedVersion: plugin.version,
+ sourceType: discovered.config.source.type === 'git' ? 'git-market' : 'local-market',
+ reviewPackagePermissions: async (facts) => {
+ requireSameMarketOwner(owner);
+ const approved = await reviewPackagePermissions?.(facts);
+ requireSameMarketOwner(owner);
+ return approved === true;
+ },
+ ...(permissionBaselineManifest ? { permissionBaselineManifest } : {}),
beforeCommit: async () => {
requireSameMarketOwner(owner);
// 所选来源必须**仍然存在且仍是同一个来源**:移除来源会先拿
@@ -1153,7 +1152,7 @@ export class PluginMarketService {
'The marketplace source changed during the install',
);
}
- // runtime 所有权也要复核:打包窗口(秒到分钟级)内,
+ // 当前已装目标也要复核:打包窗口(秒到分钟级)内,
// 本地插件页可以卸载同 id 插件(那条路径不持本服务的互斥锁)——不查
// 会把"更新"降级成"首装+带电启用";反向地,窗口内新装入的同 id
// 本地 .cindy 会被更新分支静默覆盖,还绕过了审阅时跳过的权限 diff。
@@ -1173,6 +1172,31 @@ export class PluginMarketService {
throwIpcError('PRECONDITION_FAILED', 'Installed Plugin changed during the install');
}
},
+ beforePackagePlacement: () => {
+ const record = ledger.installationForGhost(plugin.ghostId);
+ const routeStillMatches = Boolean(
+ existing &&
+ record?.installed &&
+ record.pluginId === pluginId &&
+ record.sourceKey === sourceKey &&
+ record.manifestDigest != null &&
+ record.manifestDigest === reviewInstalledDigest,
+ );
+ if (existing && !routeStillMatches && options.allowSourceReplacement !== true) {
+ throwIpcError('PRECONDITION_FAILED', 'Installed Plugin source changed');
+ }
+ if (existing && record?.installed && !routeStillMatches) {
+ replacedRouteWasSuppressed = this.detachMarketRouteForReplacement(
+ ledger,
+ record,
+ defaultInstallSubject(owner),
+ );
+ replacedRoute = record;
+ }
+ },
+ onPackagePlaced: () => {
+ packageLanded = true;
+ },
// 复核与落位的双重互斥:
// - SOURCE_MUTATION_KEY:beforeCommit 返回后包检查还要跑一段,期间不能
// 让来源被增删,否则复核结论在落位前过期。
@@ -1180,11 +1204,17 @@ export class PluginMarketService {
// 按 id 互斥,beforeCommit 的 runtime 复核到 installOrUpdate 落位之间,
// 同 id 的本地装入/卸载插不进来(否则复核仍会在落位前过期)。
withCommitLock: (fn) =>
- this.withMutation(SOURCE_MUTATION_KEY, () => withGhostInstallLock(plugin.ghostId, fn)),
+ this.withMutation(SOURCE_MUTATION_KEY, () =>
+ withGhostInstallLock(plugin.ghostId, fn),
+ ),
// 溯源写入仍在上面那把 ghost 锁内(afterCommit 由 commit 段调用):
// 放到锁外时,本地装入能插在"包已落位"与"写下溯源"之间换掉同 id 的包。
// 锁序:pluginId → SOURCE_MUTATION_KEY → ghostId → ledgerMutation。
- afterCommit: async () => {
+ afterCommit: async (_installed, packagedManifest) => {
+ // packGhostDirToFile 返回的是写入真实临时包的 canonical manifest;
+ // Main 随后复验并用包 SHA 钉死同一文件,因此无需在包已经落位后
+ // 再读一次目录。后置 I/O 失败不应把成功安装误报成失败或漏写来源。
+ const manifestDigest = ghostManifestDigest(packagedManifest);
await this.withCapturedLedgerMutation(ledger, () => {
ledger.upsertInstallation({
pluginId,
@@ -1198,18 +1228,27 @@ export class PluginMarketService {
source: discovered.config.source.type === 'git' ? 'git-market' : 'local-market',
installed: true,
updatedAt: new Date().toISOString(),
- // 来源指纹与 pluginId 一起构成所有权:同名异源的重加对不上它。
+ // 来源指纹与 pluginId 一起标识后续自动更新路由。
sourceKey,
- // 落位那一刻的 manifest 摘要:降级期间运行时被换成别的包后,认领
- // 对不上摘要即失效。摘要来自发现层的原始 manifest(校验器输出),
- // **不是**安装返回的 ghost.manifest——后者按当前界面语言本地化过,
- // 切语言会被误判成包被替换。
- manifestDigest: ghostManifestDigest(plugin.manifest),
+ // 摘要来自实际临时包的 canonical manifest,不是发现快照,也不是
+ // 安装返回的本地化 ghost.manifest;包被替换后不会被当成同源更新。
+ manifestDigest,
});
});
+ replacedRoute = null;
},
+ }).catch((error) => {
+ if (!packageLanded && replacedRoute) {
+ this.restoreMarketRouteAfterFailedReplacement(
+ ledger,
+ replacedRoute,
+ defaultInstallSubject(owner),
+ replacedRouteWasSuppressed,
+ );
+ }
+ throw error;
});
- return { ghost };
+ return ghost ? { ghost } : { cancelled: true };
});
});
}
@@ -1229,22 +1268,66 @@ export class PluginMarketService {
}
}
- /** 快照聚合用:发现全部自定义市场条目。任何失败都降级为空,不拖垮快照。 */
+ /** 快照聚合用:发现全部自定义市场条目。失败来源单独标记,不拖垮其它来源。 */
private nextCustomIconProjectionGeneration(): string {
return (this.customIconProjectionGeneration = crypto
.randomBytes(PLUGIN_MARKET_CUSTOM_ICON_PROJECTION_TOKEN_LENGTH / 2)
.toString('hex'));
}
+ private async discoverCustomEntriesBounded(
+ owner: ActiveAppSession,
+ iconProjectionGeneration: string,
+ configuredSourceNames: readonly string[],
+ ): Promise<CustomMarketDiscovery> {
+ const progress: CustomMarketDiscoveryProgress = {
+ entries: [],
+ settledSourceNames: new Set<string>(),
+ unavailableSourceNames: new Set<string>(),
+ };
+ let timeout: ReturnType<typeof setTimeout> | undefined;
+ const unavailable = new Promise<CustomMarketDiscovery>((resolve) => {
+ timeout = setTimeout(() => {
+ const unavailableSourceNames = new Set(progress.unavailableSourceNames);
+ for (const name of configuredSourceNames) {
+ if (!progress.settledSourceNames.has(name)) unavailableSourceNames.add(name);
+ }
+ log.warn('custom marketplace snapshot discovery timed out', {
+ markets: configuredSourceNames.length,
+ });
+ resolve({
+ entries: [...progress.entries],
+ unavailableSourceNames: [...unavailableSourceNames],
+ });
+ }, CUSTOM_MARKET_SNAPSHOT_TIMEOUT_MS);
+ });
+ try {
+ return await Promise.race([
+ this.discoverCustomEntriesSafe(
+ owner,
+ iconProjectionGeneration,
+ configuredSourceNames,
+ progress,
+ ),
+ unavailable,
+ ]);
+ } finally {
+ if (timeout !== undefined) clearTimeout(timeout);
+ }
+ }
+
private async discoverCustomEntriesSafe(
owner: ActiveAppSession,
iconProjectionGeneration: string,
- ): Promise<CustomMarketEntry[]> {
+ configuredSourceNames: readonly string[],
+ progress: CustomMarketDiscoveryProgress,
+ ): Promise<CustomMarketDiscovery> {
try {
const manager = this.sourceManagerForOwner(owner);
- const entries: CustomMarketEntry[] = [];
await manager.forEachDiscoveredSource(async ({ config, result }) => {
if (!result.ok) {
+ progress.unavailableSourceNames.add(config.name);
+ progress.settledSourceNames.add(config.name);
log.warn('custom marketplace discovery failed', {
market: config.name,
code: result.code,
@@ -1257,22 +1340,33 @@ export class PluginMarketService {
unreadableCount: result.marketplace.unreadableCount,
});
}
+ const sourceEntries: CustomMarketEntry[] = [];
for (const plugin of result.marketplace.plugins) {
if (!manifestSupportsCurrentCindy(plugin.manifest)) continue;
- entries.push({
+ sourceEntries.push({
config,
plugin,
iconKey: await customMarketIconKey(owner, config, plugin, iconProjectionGeneration),
});
}
+ // 只在整个来源(含 icon 投影)完成后发布,超时快照不会暴露半个市场。
+ progress.entries.push(...sourceEntries);
+ progress.settledSourceNames.add(config.name);
});
- return entries;
} catch (error) {
log.warn('custom marketplace enumeration failed', {
error: error instanceof Error ? error.message : String(error),
});
- return [];
+ // 未走完的来源统一标记不可用;已经成功发现的来源仍保留,不因另一个
+ // 来源抛出意外 I/O 错误而从列表消失。
+ for (const name of configuredSourceNames) {
+ if (!progress.settledSourceNames.has(name)) progress.unavailableSourceNames.add(name);
+ }
}
+ return {
+ entries: [...progress.entries],
+ unavailableSourceNames: [...progress.unavailableSourceNames],
+ };
}
private projectCustomItems(
@@ -1290,10 +1384,9 @@ export class PluginMarketService {
const releaseId = customMarketReleaseId(config.name, plugin.ghostId, plugin.version);
const ghost = local.ghostsById.get(plugin.ghostId);
const record = local.installations[plugin.ghostId];
- // 所有权 = pluginId + 来源指纹 + 安装时 manifest 摘要都对上,与 customInstall
- // 同口径:同名异源的重加、降级期间被本地替换的包,都不是所有者,列表如实标
- // conflict 而不是 update-available。
- const ownsInstall = Boolean(
+ // pluginId + 来源指纹 + 安装时 manifest 摘要全部对上时,
+ // 该条目才是当前自动更新路由。其它同 id 条目仍可被用户显式选择替换。
+ const matchesUpdateRoute = Boolean(
ghost &&
record?.installed &&
record.pluginId === pluginId &&
@@ -1301,20 +1394,12 @@ export class PluginMarketService {
record.manifestDigest != null &&
record.manifestDigest === local.rawDigestByGhostId.get(plugin.ghostId),
);
- // 收养口径与 customInstall 一致:运行时内容声明与候选完全一致时不标 conflict,
- // 投影成可安装——这是账本写失败后的自愈入口(conflict 在 UI 被禁用,没有它
- // 用户连重试的按钮都没有)。
- const adoptable = Boolean(
- ghost &&
- !ownsInstall &&
- local.rawDigestByGhostId.get(plugin.ghostId) === ghostManifestDigest(plugin.manifest),
- );
- // 市场目录只用于发现,不声明未安装 ghostId 的所有权。只有运行时已经存在
- // 同 id 且不属于当前来源时才冲突,避免官方或其它市场接管用户已装插件。
- const conflict = Boolean(ghost && !ownsInstall && !adoptable);
+ // conflict 是「不能作为自动更新」的内部投影,不是不可安装;
+ // Renderer 会把它呈现为用户显式的「替换」操作。
+ const conflict = Boolean(ghost && !matchesUpdateRoute);
const installState: PluginMarketItem['installState'] = conflict
? 'conflict'
- : !ownsInstall
+ : !matchesUpdateRoute
? 'not-installed'
: record?.releaseId === releaseId
? 'installed'
@@ -1343,7 +1428,7 @@ export class PluginMarketService {
icon: null,
...(iconKey !== null ? { customIconKey: iconKey } : {}),
installState,
- enabled: ownsInstall ? (ghost?.enabled ?? null) : null,
+ enabled: matchesUpdateRoute ? (ghost?.enabled ?? null) : null,
sourceType: config.source.type === 'git' ? 'git-market' : 'local-market',
sourceMarketName: config.name,
};
@@ -1383,15 +1468,19 @@ export class PluginMarketService {
private async installDetail(
plugin: VisiblePluginSummary | VisiblePluginDetail,
options: {
- /** 手动安装时已向用户展示;默认安装时作为自动授权的目录权限上限。 */
- reviewedManifest?: GhostManifest;
- allowPermissionExpansion?: boolean;
- /** 安装前权限确认所依据的已装权限指纹。 */
- reviewedBaseline?: string;
- /** 真实包比展示清单多权限时,在当前安装事务内立即询问发起窗口。 */
+ /** 手动安装确认真实包;默认安装只使用目录 manifest 作为 fail-closed 上限。 */
+ permissionPolicy?:
+ | { mode: 'manual'; sourceType: PluginMarketItem['sourceType'] }
+ | {
+ mode: 'cap';
+ manifest: GhostManifest;
+ sourceType: PluginMarketItem['sourceType'];
+ };
+ /** 真实包需要确认时,在当前安装事务内立即询问发起窗口。 */
reviewPackagePermissions?: PackagePermissionReviewer;
+ /** 用户明确点击安装时,允许所选市场包原地替换其它来源的同 id 插件。 */
+ allowSourceReplacement?: boolean;
beforeCommitInLock?: () => void;
- silentBaselineMismatch?: boolean;
/** 确认操作时的安装意图;下载窗口期目标被另一窗口卸载时拒绝滑入首装。 */
expectedInstalled: boolean;
} = { expectedInstalled: false },
@@ -1406,24 +1495,21 @@ export class PluginMarketService {
.list()
.find((ghost) => ghost.manifest.id === plugin.ghostId);
const currentRecord = ledger.installationForGhost(plugin.ghostId);
- if (existing && !serverMarketOwnsInstalledGhost(plugin.id, existing, currentRecord)) {
+ if (
+ existing &&
+ !options.allowSourceReplacement &&
+ !serverRecordMatchesInstalledGhost(plugin.id, existing, currentRecord)
+ ) {
throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');
}
- const reviewedManifest = options.reviewedManifest
- ? validateGhostManifest(options.reviewedManifest)
- : null;
- if (reviewedManifest && !reviewedManifest.ok) {
+ const permissionCap =
+ options.permissionPolicy?.mode === 'cap'
+ ? validateGhostManifest(options.permissionPolicy.manifest)
+ : null;
+ if (permissionCap && !permissionCap.ok) {
throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');
}
- this.assertServerPreviewExpansionApproved(
- existing?.manifest ?? null,
- reviewedManifest?.manifest,
- options.allowPermissionExpansion,
- options.reviewedBaseline,
- options.silentBaselineMismatch,
- );
-
const download = await this.api.download(plugin.id, plugin.currentRelease.id);
requireSameMarketOwner(owner);
if (
@@ -1450,11 +1536,19 @@ export class PluginMarketService {
plugin,
{
expectedInstalled: options.expectedInstalled,
- ...(reviewedManifest?.ok ? { reviewedManifest: reviewedManifest.manifest } : {}),
- allowPermissionExpansion: options.allowPermissionExpansion,
- reviewedBaseline: options.reviewedBaseline,
+ ...(options.permissionPolicy
+ ? {
+ permissionPolicy:
+ options.permissionPolicy.mode === 'cap' && permissionCap?.ok
+ ? {
+ ...options.permissionPolicy,
+ manifest: permissionCap.manifest,
+ }
+ : options.permissionPolicy,
+ }
+ : {}),
+ allowSourceReplacement: options.allowSourceReplacement,
beforeCommitInLock: options.beforeCommitInLock,
- silentBaselineMismatch: options.silentBaselineMismatch,
},
owner,
ledger,
@@ -1465,18 +1559,26 @@ export class PluginMarketService {
const approved = await options.reviewPackagePermissions?.(error.review);
requireSameMarketOwner(owner);
if (approved !== true) return null;
- return this.commitDownloadedPackage(
+ return await this.commitDownloadedPackage(
tempPath,
plugin,
{
expectedInstalled: options.expectedInstalled,
- ...(reviewedManifest?.ok ? { reviewedManifest: reviewedManifest.manifest } : {}),
- allowPermissionExpansion: options.allowPermissionExpansion,
- reviewedBaseline: options.reviewedBaseline,
+ ...(options.permissionPolicy
+ ? {
+ permissionPolicy:
+ options.permissionPolicy.mode === 'cap' && permissionCap?.ok
+ ? {
+ ...options.permissionPolicy,
+ manifest: permissionCap.manifest,
+ }
+ : options.permissionPolicy,
+ }
+ : {}),
approvedPackageSha256: error.review.packageSha256,
approvedPackageBaseline: error.review.installedBaseline,
+ allowSourceReplacement: options.allowSourceReplacement,
beforeCommitInLock: options.beforeCommitInLock,
- silentBaselineMismatch: options.silentBaselineMismatch,
},
owner,
ledger,
@@ -1492,13 +1594,17 @@ export class PluginMarketService {
tempPath: string,
plugin: VisiblePluginSummary | VisiblePluginDetail,
options: {
- reviewedManifest?: GhostManifest;
- allowPermissionExpansion?: boolean;
- reviewedBaseline?: string;
+ permissionPolicy?:
+ | { mode: 'manual'; sourceType: PluginMarketItem['sourceType'] }
+ | {
+ mode: 'cap';
+ manifest: GhostManifest;
+ sourceType: PluginMarketItem['sourceType'];
+ };
approvedPackageSha256?: string;
approvedPackageBaseline?: string | null;
+ allowSourceReplacement?: boolean;
beforeCommitInLock?: () => void;
- silentBaselineMismatch?: boolean;
expectedInstalled: boolean;
},
owner: ActiveAppSession,
@@ -1519,35 +1625,45 @@ export class PluginMarketService {
}
if (
installedNow &&
- !serverMarketOwnsInstalledGhost(plugin.id, installedNow, currentRecordNow)
+ !options.allowSourceReplacement &&
+ !serverRecordMatchesInstalledGhost(plugin.id, installedNow, currentRecordNow)
) {
throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');
}
requireSameMarketOwner(owner);
- this.assertServerPreviewExpansionApproved(
- installedNow?.manifest ?? null,
- options.reviewedManifest,
- options.allowPermissionExpansion,
- options.reviewedBaseline,
- options.silentBaselineMismatch,
- );
const installedRawManifest = installedNow
? installedGhostRawManifest(installedNow.dir)
: null;
- const permissionBaselineManifest =
- installedRawManifest &&
- currentRecordNow?.installed &&
- (currentRecordNow.source === 'market' || currentRecordNow.source === 'legacy-adopted') &&
- currentRecordNow.manifestDigest === ghostManifestDigest(installedRawManifest)
- ? installedRawManifest
- : null;
+ // 权限基线是当前真正运行的包,不是 ledger 中的来源摘要。更新路由已由
+ // 上面的 serverRecordMatchesInstalledGhost 单独判断;把两者捆绑会让旧记录
+ // 因缺摘要被当成首次安装,升级时无端要求重新批准全部权限。
+ const permissionBaselineManifest = installedRawManifest;
+ const replacingSource = Boolean(
+ installedNow &&
+ options.allowSourceReplacement &&
+ currentRecordNow?.installed &&
+ !serverRecordMatchesInstalledGhost(plugin.id, installedNow, currentRecordNow),
+ );
+ let routeDetached = false;
+ let replacedRouteWasSuppressed = false;
+ let packageLanded = false;
+ const detachPreviousRoute = (): void => {
+ options.beforeCommitInLock?.();
+ if (!replacingSource || !currentRecordNow) return;
+ replacedRouteWasSuppressed = this.detachMarketRouteForReplacement(
+ ledger,
+ currentRecordNow,
+ defaultInstallSubject(owner),
+ );
+ routeDetached = true;
+ };
const installed = await installOrUpdateMarketGhostPackage(tempPath, {
ghostId: plugin.ghostId,
version: plugin.currentRelease.version,
...(plugin.ghostId === 'cindy-github' ? { officialCindyGithub: true } : {}),
- ...(options.reviewedManifest
+ ...(options.permissionPolicy
? {
- reviewedManifest: options.reviewedManifest,
+ permissionPolicy: options.permissionPolicy,
...(permissionBaselineManifest ? { permissionBaselineManifest } : {}),
}
: {}),
@@ -1559,7 +1675,26 @@ export class PluginMarketService {
: {}),
}
: {}),
- ...(options.beforeCommitInLock ? { beforeCommitInLock: options.beforeCommitInLock } : {}),
+ ...(options.beforeCommitInLock || replacingSource
+ ? { beforeCommitInLock: detachPreviousRoute }
+ : {}),
+ ...(replacingSource
+ ? {
+ onPackagePlacedInLock: () => {
+ packageLanded = true;
+ },
+ }
+ : {}),
+ }).catch((error) => {
+ if (routeDetached && !packageLanded && currentRecordNow) {
+ this.restoreMarketRouteAfterFailedReplacement(
+ ledger,
+ currentRecordNow,
+ defaultInstallSubject(owner),
+ replacedRouteWasSuppressed,
+ );
+ }
+ throw error;
});
await this.withCapturedLedgerMutation(ledger, () => {
ledger.upsertInstallation(recordFrom(plugin, 'market', installed));
@@ -1568,33 +1703,6 @@ export class PluginMarketService {
});
}
- private assertServerPreviewExpansionApproved(
- installed: GhostManifest | null,
- reviewedManifest: GhostManifest | undefined,
- allowPermissionExpansion: boolean | undefined,
- reviewedBaseline: string | undefined,
- silentBaselineMismatch = false,
- ): void {
- if (
- !installed ||
- !reviewedManifest ||
- diffGhostPermissionItems(installed, reviewedManifest).added.length === 0
- ) {
- return;
- }
- if (allowPermissionExpansion !== true) {
- throwIpcError('PRECONDITION_FAILED', 'Plugin permissions changed and require review');
- }
- if (
- silentBaselineMismatch &&
- reviewedBaseline !== undefined &&
- ghostPermissionBaselineKey(installed) !== reviewedBaseline
- ) {
- throw new SilentUpgradeStaleBaselineError('Installed Plugin permissions changed');
- }
- assertReviewedBaselineFresh(installed, reviewedBaseline);
- }
-
private requireConfigured(): void {
if (!getClientEndpoint('pluginApiBaseUrl')) {
throwIpcError('UNSUPPORTED_CAPABILITY', 'Plugin market is not configured');
@@ -1607,14 +1715,14 @@ export class PluginMarketService {
): PluginMarketItem {
const ghost = local.ghostsById.get(plugin.ghostId);
const record = local.installations[plugin.ghostId];
- const ownsInstall = Boolean(
- ghost && serverMarketOwnsInstalledGhost(plugin.id, ghost, record ?? null),
+ const matchesUpdateRoute = Boolean(
+ ghost && serverRecordMatchesInstalledGhost(plugin.id, ghost, record ?? null),
);
- // 未安装的其它市场条目不拥有 ghostId;真实已安装插件才建立所有权边界。
- const conflict = Boolean(ghost && !ownsInstall);
+ // 其它同 id 条目不进入自动更新,但仍可由用户显式选择替换。
+ const conflict = Boolean(ghost && !matchesUpdateRoute);
const installState: PluginMarketItem['installState'] = conflict
? 'conflict'
- : !ownsInstall
+ : !matchesUpdateRoute
? 'not-installed'
: record?.releaseId === plugin.currentRelease.id
? 'installed'
@@ -1633,7 +1741,7 @@ export class PluginMarketService {
publishedAt: plugin.currentRelease.publishedAt,
icon: plugin.currentRelease.icon,
installState,
- enabled: ownsInstall ? (ghost?.enabled ?? null) : null,
+ enabled: matchesUpdateRoute ? (ghost?.enabled ?? null) : null,
sourceType: 'server',
sourceMarketName: null,
};
@@ -1871,8 +1979,8 @@ export class PluginMarketService {
const detail = await this.api.detail(summary.id);
requireSameMarketOwner(owner);
assertDetailMatchesSummary(summary, detail);
- const reviewedManifest = validateGhostManifest(detail.currentRelease.manifest);
- if (!reviewedManifest.ok) {
+ const permissionCap = validateGhostManifest(detail.currentRelease.manifest);
+ if (!permissionCap.ok) {
throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');
}
// 装完即开语义已收敛进市场安装入口本身,这里无需再显式声明。
@@ -1883,7 +1991,11 @@ export class PluginMarketService {
// 默认安装没有用户发起窗口:目录 manifest 是自动安装可接受的权限
// 上限;真实包若额外扩权,installDetail 会安全取消并等待用户之后
// 从详情页手动安装、在原请求窗口完成确认。
- reviewedManifest: reviewedManifest.manifest,
+ permissionPolicy: {
+ mode: 'cap',
+ manifest: permissionCap.manifest,
+ sourceType: 'server',
+ },
// 下载期间用户可能从本地插件页完成显式卸载。最终落位前在
// ghostId 锁内重读卸载意图,不能让旧 snapshot 把插件装回来。
beforeCommitInLock: () => {
@@ -1939,7 +2051,8 @@ export class PluginMarketService {
hasPendingGhostCalls(summary.ghostId) ||
hasRunningGhostErrand(summary.ghostId) ||
hasRunningGhostCindyWork(summary.ghostId)
- ) continue;
+ )
+ continue;
try {
await this.withMutation(summary.id, async () => {
requireSameMarketOwner(owner);
@@ -1958,14 +2071,12 @@ export class PluginMarketService {
return;
}
const freshInstalled = freshLocal.ghostsById.get(summary.ghostId);
- const reviewedBaseline = freshInstalled
- ? ghostPermissionBaselineKey(freshInstalled.manifest)
- : undefined;
const detail = await this.api.detail(summary.id);
requireSameMarketOwner(owner);
assertDetailMatchesSummary(summary, detail);
const reviewedManifest = validateGhostManifest(detail.currentRelease.manifest);
- if (!reviewedManifest.ok) throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');
+ if (!reviewedManifest.ok)
+ throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');
if (!manifestSupportsCurrentCindy(reviewedManifest.manifest)) {
log.warn('default plugin upgrade skipped for Cindy version', {
pluginId: summary.id,
@@ -1973,30 +2084,37 @@ export class PluginMarketService {
});
return;
}
- const installed = await this.installDetail(detail, {
- expectedInstalled: true,
- reviewedManifest: reviewedManifest.manifest,
- allowPermissionExpansion: true,
- reviewedBaseline,
- silentBaselineMismatch: true,
- beforeCommitInLock: () => {
- if (
- hasPendingGhostCalls(summary.ghostId) ||
- hasRunningGhostErrand(summary.ghostId) ||
- hasRunningGhostCindyWork(summary.ghostId)
- ) {
- throw new SilentUpgradeBusyError('Plugin is busy');
- }
+ const installed = await this.installDetail(
+ detail,
+ {
+ expectedInstalled: true,
+ permissionPolicy: {
+ mode: 'cap',
+ manifest: reviewedManifest.manifest,
+ sourceType: 'server',
+ },
+ beforeCommitInLock: () => {
+ if (
+ hasPendingGhostCalls(summary.ghostId) ||
+ hasRunningGhostErrand(summary.ghostId) ||
+ hasRunningGhostCindyWork(summary.ghostId)
+ ) {
+ throw new SilentUpgradeBusyError('Plugin is busy');
+ }
+ },
},
- }, owner, ledger);
+ owner,
+ ledger,
+ );
if (installed) {
const addedPermissions = freshInstalled
- ? diffGhostPermissionItems(freshInstalled.manifest, reviewedManifest.manifest).added
- .map(({ key, labelKey, labelArgs }) => ({
+ ? diffGhostPermissionItems(freshInstalled.manifest, installed.manifest).added.map(
+ ({ key, labelKey, labelArgs }) => ({
key,
labelKey,
...(labelArgs ? { labelArgs } : {}),
- }))
+ }),
+ )
: [];
completed.push({
name: stripDirectionalControls(installed.manifest.name) || null,
@@ -2005,7 +2123,7 @@ export class PluginMarketService {
}
});
} catch (error) {
- if (!(error instanceof SilentUpgradeBusyError || error instanceof SilentUpgradeStaleBaselineError)) {
+ if (!(error instanceof SilentUpgradeBusyError)) {
log.warn('default plugin upgrade failed', {
pluginId: summary.id,
error: error instanceof Error ? error.message : String(error),
@@ -2023,9 +2141,7 @@ export class PluginMarketService {
count,
name: count === 1 ? (completed[0]?.name ?? null) : null,
permissions:
- count === 1 && completed[0]?.permissions.length
- ? completed[0].permissions
- : null,
+ count === 1 && completed[0]?.permissions.length ? completed[0].permissions : null,
hasPermissionExpansion,
});
}
@@ -2084,6 +2200,56 @@ export class PluginMarketService {
return current;
}
+ private detachMarketRouteForReplacement(
+ ledger: PluginMarketLedger,
+ record: PluginMarketInstallationRecord,
+ installSubject: string,
+ ): boolean {
+ const tracksDefaultInstall = record.source === 'market' || record.source === 'legacy-adopted';
+ const wasSuppressed = tracksDefaultInstall
+ ? ledger.isDefaultInstallSuppressed(installSubject, record.pluginId)
+ : false;
+ try {
+ ledger.markRemoved(record.ghostId, tracksDefaultInstall ? installSubject : null);
+ } catch (error) {
+ this.restoreMarketRouteAfterFailedReplacement(
+ ledger,
+ record,
+ installSubject,
+ wasSuppressed,
+ );
+ log.warn('failed to detach Plugin market route before replacement', {
+ pluginId: record.pluginId,
+ ghostId: record.ghostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ throwIpcError('INTERNAL', 'Unable to detach the installed Plugin source');
+ }
+ return wasSuppressed;
+ }
+
+ private restoreMarketRouteAfterFailedReplacement(
+ ledger: PluginMarketLedger,
+ record: PluginMarketInstallationRecord,
+ installSubject: string,
+ wasSuppressed: boolean,
+ ): void {
+ try {
+ ledger.restoreInstallation(
+ record,
+ record.source === 'market' || record.source === 'legacy-adopted'
+ ? { userId: installSubject, suppressed: wasSuppressed }
+ : undefined,
+ );
+ } catch (error) {
+ log.error('failed to restore Plugin market route after replacement failure', {
+ pluginId: record.pluginId,
+ ghostId: record.ghostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+
private withMutation<T>(pluginId: string, operation: () => Promise<T>): Promise<T> {
const previous = this.mutations.get(pluginId) ?? Promise.resolve();
const current = previous.catch(() => undefined).then(operation);
diff --git a/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx b/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx
index 3bd1767bc7..f4321b2fd6 100644
--- a/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx
+++ b/apps/desktop/src/renderer/components/ui/confirm-dialog-provider.tsx
@@ -72,7 +72,7 @@ export interface ConfirmWithCheckboxOptions extends Omit<ConfirmOptions, 'dontSh
}
interface ConfirmDialogContextValue {
- confirm: (options: ConfirmOptions) => Promise<boolean>;
+ confirm: (options: ConfirmOptions, signal?: AbortSignal) => Promise<boolean>;
/** 三状态 confirm — 用于「保存 / 不保存 / 取消」这类需要区分 cancel 与 negative 的场景。 */
confirmThree: (options: ConfirmThreeOptions) => Promise<ConfirmThreeResult>;
/** 带业务复选框(初始勾选态由 checkboxDefaultChecked 决定,缺省不勾;取消时 checked 恒为 false)。 */
@@ -116,6 +116,7 @@ export function ConfirmDialogProvider({ children }: { children: ReactNode }) {
clearStaleSkipsOnce();
}
const queueRef = useRef<QueueItem[]>([]);
+ const currentItemRef = useRef<QueueItem | null>(null);
const [currentItem, setCurrentItem] = useState<QueueItem | null>(null);
const [open, setOpen] = useState(false);
const isShowingRef = useRef(false);
@@ -124,6 +125,7 @@ export function ConfirmDialogProvider({ children }: { children: ReactNode }) {
const processNext = useCallback(() => {
const next = queueRef.current.shift();
if (next) {
+ currentItemRef.current = next;
setCurrentItem(next);
setOpen(true);
isShowingRef.current = true;
@@ -132,24 +134,47 @@ export function ConfirmDialogProvider({ children }: { children: ReactNode }) {
}, []);
const confirm = useCallback(
- (options: ConfirmOptions): Promise<boolean> => {
+ (options: ConfirmOptions, signal?: AbortSignal): Promise<boolean> => {
+ if (signal?.aborted) return Promise.resolve(false);
// 用户曾勾过"下次不再提示" → 直接当成 confirm,不弹窗、不入队。
if (options.dontShowAgainKey && isSkipped(options.dontShowAgainKey)) {
return Promise.resolve(true);
}
return new Promise<boolean>((resolve) => {
+ let settled = false;
// 二状态调用复用同一队列:把 'confirm'→true,其它→false 透传给原 boolean 契约。
// 用户勾上"下次不再提示"且点 confirm 时,把 key 写入 localStorage。
const item: QueueItem = {
options,
resolve: (r, dontShowAgain) => {
+ if (settled) return;
+ settled = true;
+ signal?.removeEventListener('abort', abort);
if (r === 'confirm' && dontShowAgain && options.dontShowAgainKey) {
markSkipped(options.dontShowAgainKey);
}
resolve(r === 'confirm');
},
};
+ const abort = () => {
+ const queuedIndex = queueRef.current.indexOf(item);
+ if (queuedIndex >= 0) {
+ queueRef.current.splice(queuedIndex, 1);
+ item.resolve('cancel');
+ return;
+ }
+ if (currentItemRef.current === item && !resolvedRef.current) {
+ resolvedRef.current = true;
+ item.resolve('cancel');
+ setOpen(false);
+ }
+ };
queueRef.current.push(item);
+ signal?.addEventListener('abort', abort, { once: true });
+ if (signal?.aborted) {
+ abort();
+ return;
+ }
if (!isShowingRef.current) {
processNext();
}
@@ -227,6 +252,7 @@ export function ConfirmDialogProvider({ children }: { children: ReactNode }) {
if (!open && currentItem !== null) {
const timer = setTimeout(() => {
isShowingRef.current = false;
+ currentItemRef.current = null;
setCurrentItem(null);
processNext();
}, 200);
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index cd43e92ea4..6b8df45bcd 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -55,7 +55,6 @@ import {
import { resetDraftWorkspaceTargets } from '@/state/newMakerDraft';
import { ghostInstallErrorKey } from '@/cindy-brain/installErrorKey';
import { confirmAndInstallGhost, pickAndUpdateGhost } from '@/cindy-brain/installFlow';
-import { GhostPermissionList, GhostUpdateReview } from '@/cindy-brain/GhostPermissionList';
import { cn } from '@/lib/utils';
import { AttentionDot } from '@/components/sidebar/AttentionDot';
import {
@@ -67,10 +66,7 @@ import { getLastWorkingDir, subscribeToLastWorkingDir } from '@/state/lastWorkin
import { findSplitChildByPanelKind } from '../../../shared/layoutTree';
import { resolveSystemLocale } from '../../../shared/locale';
import {
- diffGhostPermissionItems,
ghostPanelKind,
- ghostPermissionBaselineKey,
- ghostPermissionItems,
isOfficialGhostId,
type GhostSetupStatus,
type InstalledGhost,
@@ -96,11 +92,9 @@ import {
} from './lib/ghostPluginViewModel';
import { ignoredRoundStorageKey, isBatchFinished, updateRoundKey } from './lib/updateAllModel';
import {
- approveUpdateExpansion,
getUpdateAllBatchState,
reconcileUpdateAllBatch,
setUpdateAllBatchHooks,
- skipUpdateExpansion,
startUpdateAllBatch,
subscribeUpdateAllBatch,
} from './lib/updateAllController';
@@ -361,6 +355,7 @@ export function GhostPluginPage() {
items: [],
unavailableReason: error instanceof Error ? error.message : String(error),
customSourceNames: [],
+ unavailableCustomSourceNames: [],
},
);
// Background icon renewal keeps the current snapshot visible, but must still report
@@ -378,6 +373,15 @@ export function GhostPluginPage() {
}, [refreshMarket, mode, dataOwnerId]);
const refreshMarketOnForeground = useCallback(() => refreshMarket(true), [refreshMarket]);
usePluginMarketForegroundRefresh(refreshMarketOnForeground, lastMarketRefreshAtRef);
+ useEffect(
+ () =>
+ window.electronAPI.pluginMarket.onUpgradeNoticeAvailable(() => {
+ // 默认插件升级在初始快照返回后异步落位;原位升级不会改变已装 ID,
+ // 复用现有完成通知刷新目录,避免继续展示旧 release 的更新入口。
+ void refreshMarket(true).catch(() => undefined);
+ }),
+ [refreshMarket],
+ );
useEffect(() => {
if (installedGhostIdsKeyRef.current === installedGhostIdsKey) return;
installedGhostIdsKeyRef.current = installedGhostIdsKey;
@@ -489,6 +493,8 @@ export function GhostPluginPage() {
const marketByGhostId = useMemo(() => {
const map = new Map<string, PluginMarketItem>();
for (const item of marketItems) {
+ // 非当前路由的同 id 条目只出现在「可替换」市场卡片,
+ // 不得投影成已装卡片的普通更新。
if (item.installState !== 'conflict') map.set(item.ghostId, item);
}
return map;
@@ -657,7 +663,7 @@ export function GhostPluginPage() {
}, [currentRoundKey, ignoredRoundKey]);
// 批次状态住在模块级控制器里(生命周期长于本页:关弹窗离开 /plugins
- // 后批次继续跑,回来仍保留待确认项的批准/跳过入口),页面只订阅快照。
+ // 后批次继续跑),页面只订阅快照。权限确认由统一安装事务负责。
const updateBatch = useSyncExternalStore(subscribeUpdateAllBatch, getUpdateAllBatchState);
const updateRows = updateBatch.rows;
const batchRunning = updateBatch.running;
@@ -668,8 +674,8 @@ export function GhostPluginPage() {
useEffect(() => {
reconcileUpdateAllBatch(marketItems);
}, [ghosts, marketItems, mode, dataOwnerId]);
- // 有未完结批次(含待确认项)时横幅必须在场:它是重开批量弹窗的唯一入口,
- // 「忽略本轮」不得顺带藏掉待确认项的批准/跳过路径。
+ // 有未完结批次时横幅必须在场:它是重开批量进度弹窗的唯一入口,
+ // 「忽略本轮」不得顺带藏掉正在执行的批次。
const hasUnfinishedBatch = updateRows !== null && !isBatchFinished(updateRows);
const bannerVisible =
hasUnfinishedBatch ||
@@ -770,15 +776,14 @@ export function GhostPluginPage() {
[t],
);
- /** 真实包的追加确认由窗口级 Host 在这一次 install IPC 事务内完成。 */
+ /** 真实包的唯一权限确认由窗口级 Host 在这一次 install IPC 事务内完成。 */
const installReviewedMarketPackage = useCallback(
async (input: {
- detail: PluginMarketDetail;
- lease: { pluginId: string };
+ pluginId: string;
options: PluginMarketInstallOptions;
}): Promise<InstalledGhost | null> => {
const result = await window.electronAPI.pluginMarket.install(
- input.detail.pluginId,
+ input.pluginId,
input.options,
);
return result.ghost ?? null;
@@ -786,45 +791,34 @@ export function GhostPluginPage() {
[],
);
- // 所有来源先展示详情清单;官方包下载后仍以真实包清单兜底发现额外权限。
+ // 目录详情只用于发现与预览;点击更新后由 Main 下载真实包并完成唯一确认。
const handleMarketUpdate = useCallback(
async (ghostId: string) => {
const marketItem = marketByGhostId.get(ghostId);
if (!marketItem || marketItem.installState !== 'update-available') return;
const installedGhost = ghosts.find((ghost) => ghost.manifest.id === ghostId) ?? null;
+ if (!installedGhost) {
+ toast.error(t('settings.ghosts.market.errors.stateChanged'));
+ await refreshMarket();
+ return;
+ }
// 列表每张卡都有直达入口,同步互斥防止并发更新互相覆盖忙碌状态。
const marketBusyLease = acquireMarketBusy(marketItem.pluginId);
if (!marketBusyLease) return;
try {
const next = await window.electronAPI.pluginMarket.detail(marketItem.pluginId);
if (!isMarketBusyLeaseActive(marketBusyLease)) return;
- const diff = diffGhostPermissionItems(
- installedGhost?.manifest ?? next.manifest,
- next.manifest,
- );
- const approved = await confirm({
- title: t('settings.ghosts.updateConfirm.title', { name: next.name }),
- description: t('settings.ghosts.updateConfirm.body', {
- from: installedGhost?.manifest.version ?? next.version,
- to: next.version,
- }),
- content: <GhostUpdateReview diff={diff} />,
- maxWidth: 520,
- confirmText: t('settings.ghosts.updateConfirm.confirm'),
- cancelText: t('settings.ghosts.updateConfirm.cancel'),
- });
- if (!approved || !isMarketBusyLeaseActive(marketBusyLease)) return;
+ if (next.installState !== 'update-available') {
+ toast.error(t('settings.ghosts.market.errors.stateChanged'));
+ await refreshMarket();
+ return;
+ }
const options: PluginMarketInstallOptions = {
expectedReleaseId: next.releaseId,
- expectedManifest: next.manifest,
- allowPermissionExpansion: diff.added.length > 0,
- ...(installedGhost
- ? { reviewedBaseline: ghostPermissionBaselineKey(installedGhost.manifest) }
- : {}),
+ allowSourceReplacement: false,
};
const ghost = await installReviewedMarketPackage({
- detail: next,
- lease: marketBusyLease,
+ pluginId: next.pluginId,
options,
});
if (!ghost) return;
@@ -846,7 +840,6 @@ export function GhostPluginPage() {
},
[
acquireMarketBusy,
- confirm,
ghosts,
isMarketBusyLeaseActive,
installReviewedMarketPackage,
@@ -878,7 +871,7 @@ export function GhostPluginPage() {
);
const handleUpdateAll = useCallback(() => {
const current = getUpdateAllBatchState();
- // 运行中或还有待确认项的批次:重开弹窗接着处理,不重建批次。
+ // 运行中或还有未完成项的批次:重开弹窗查看进度,不重建批次。
if (current.running || (current.rows !== null && !isBatchFinished(current.rows))) {
setUpdateDialogOpen(true);
return;
@@ -1133,9 +1126,11 @@ export function GhostPluginPage() {
// 旧确认回调恢复后必须先验权,不能在新会话里继续安装。
const marketBusyLease = acquireMarketBusy(marketDetail.pluginId);
if (!marketBusyLease) return;
- // 详情页按钮在 update-available 态复用本入口,后端走原位更新并保留
- // 生效状态 —— 文案必须分支,不能对更新路径承诺"装完即开"(review P1)。
- const isUpdate = marketDetail.installState === 'update-available';
+ // 市场更新与用户显式选择的同 id 替换都走原位更新,
+ // 保留生效状态和按 ghostId 存储的用户数据。
+ const isUpdate =
+ marketDetail.installState === 'update-available' ||
+ marketDetail.installState === 'conflict';
try {
let installedGhost =
ghosts.find((ghost) => ghost.manifest.id === marketDetail.ghostId) ?? null;
@@ -1150,52 +1145,13 @@ export function GhostPluginPage() {
await refreshMarket();
return;
}
- const diff = isUpdate
- ? diffGhostPermissionItems(installedGhost!.manifest, marketDetail.manifest)
- : null;
- const confirmed = await confirm({
- title: isUpdate
- ? t('settings.ghosts.updateConfirm.title', { name: marketDetail.name })
- : t('settings.ghosts.market.installConfirmTitle', {
- name: marketDetail.name,
- }),
- description: isUpdate
- ? t('settings.ghosts.market.updateConfirmDescription')
- : t(
- marketDetail.sourceType === 'server'
- ? 'settings.ghosts.market.installConfirmDescription'
- : 'settings.ghosts.market.customInstallConfirmDescription',
- ),
- content: isUpdate ? (
- <GhostUpdateReview diff={diff!} />
- ) : (
- <GhostPermissionList items={ghostPermissionItems(marketDetail.manifest)} />
- ),
- maxWidth: 520,
- confirmText: isUpdate
- ? t('settings.ghosts.updateConfirm.confirm')
- : t('settings.ghosts.market.install'),
- cancelText: isUpdate
- ? t('settings.ghosts.updateConfirm.cancel')
- : t('settings.ghosts.installConfirm.cancel'),
- autoFocusConfirm: true,
- });
- if (!confirmed || !isMarketBusyLeaseActive(marketBusyLease)) return;
+ if (!isMarketBusyLeaseActive(marketBusyLease)) return;
const options: PluginMarketInstallOptions = {
expectedReleaseId: marketDetail.releaseId,
- expectedManifest: marketDetail.manifest,
- ...(isUpdate && diff!.added.length > 0
- ? {
- allowPermissionExpansion: true,
- ...(installedGhost
- ? { reviewedBaseline: ghostPermissionBaselineKey(installedGhost.manifest) }
- : {}),
- }
- : {}),
+ allowSourceReplacement: marketDetail.installState === 'conflict',
};
const ghost = await installReviewedMarketPackage({
- detail: marketDetail,
- lease: marketBusyLease,
+ pluginId: marketDetail.pluginId,
options,
});
if (!ghost) return;
@@ -1227,7 +1183,6 @@ export function GhostPluginPage() {
},
[
acquireMarketBusy,
- confirm,
ghosts,
isMarketBusyLeaseActive,
installReviewedMarketPackage,
@@ -1524,7 +1479,8 @@ export function GhostPluginPage() {
{availableMarketItems.length > 0 ||
searchedAvailableMarketItems.length > 0 ||
- marketSnapshot?.unavailableReason ? (
+ marketSnapshot?.unavailableReason ||
+ marketSnapshot?.unavailableCustomSourceNames.length ? (
<section className="plugin-motion-page-section mt-10 min-w-0">
<div className={PLUGIN_CATALOG_TOOLBAR_CLASS}>
{/* 推荐区标题不带数字(设计定稿):数量感由卡片自身传达。 */}
@@ -1581,6 +1537,14 @@ export function GhostPluginPage() {
</p>
) : null}
+ {marketSnapshot?.unavailableCustomSourceNames.length ? (
+ <p className="mb-4 rounded-xl border border-[var(--border-default)] bg-[var(--surface-chip)] px-4 py-3 text-12 text-[var(--text-secondary)]">
+ {t('settings.ghosts.market.customSourcesUnavailable', {
+ names: marketSnapshot.unavailableCustomSourceNames.join(', '),
+ })}
+ </p>
+ ) : null}
+
{availableMarketItems.length > 0 ? (
customGroups && customGroups.length > 1 ? (
<div className="flex flex-col gap-6">
@@ -1628,7 +1592,8 @@ export function GhostPluginPage() {
))}
</div>
)
- ) : marketSnapshot?.unavailableReason ? null : (
+ ) : marketSnapshot?.unavailableReason ||
+ marketSnapshot?.unavailableCustomSourceNames.length ? null : (
<div className="rounded-xl border-[0.5px] border-[var(--border-default)] px-5 py-10 text-center">
<p className="text-13 text-[var(--text-secondary)]">
{t('settings.ghosts.page.emptyFiltered')}
@@ -1651,8 +1616,6 @@ export function GhostPluginPage() {
open={updateDialogOpen}
rows={updateRows}
iconByGhostId={new Map(ghosts.map((ghost) => [ghost.manifest.id, ghost.iconDataUrl]))}
- onApprove={(pluginId) => void approveUpdateExpansion(pluginId)}
- onSkip={skipUpdateExpansion}
onClose={() => setUpdateDialogOpen(false)}
/>
) : null}
@@ -1723,10 +1686,12 @@ export function MarketPluginCard({
}) {
const { t } = useTranslation();
const marketIcon = usePluginMarketIcon(item, { deferUntilVisible: true });
- const unavailable = busy || item.installState === 'conflict';
- const conflictDescriptionId = useId();
- const conflictDescription =
- item.installState === 'conflict' ? t('settings.ghosts.market.conflictDescription') : undefined;
+ const unavailable = busy;
+ const replacementDescriptionId = useId();
+ const replacementDescription =
+ item.installState === 'conflict'
+ ? t('settings.ghosts.market.replaceDescription')
+ : undefined;
return (
<article
className={cn(
@@ -1741,15 +1706,13 @@ export function MarketPluginCard({
onClick={onSelect}
disabled={unavailable}
aria-label={item.name}
- aria-describedby={conflictDescription ? conflictDescriptionId : undefined}
+ aria-describedby={
+ replacementDescription ? replacementDescriptionId : undefined
+ }
className={cn(
'flex min-w-0 flex-1 items-start gap-4 self-stretch text-left',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- unavailable
- ? item.installState === 'conflict'
- ? 'cursor-not-allowed'
- : 'cursor-wait'
- : 'cursor-pointer',
+ unavailable ? 'cursor-wait' : 'cursor-pointer',
)}
>
<GhostPluginIcon
@@ -1786,10 +1749,10 @@ export function MarketPluginCard({
) : null}
</span>
<span
- id={conflictDescription ? conflictDescriptionId : undefined}
+ id={replacementDescription ? replacementDescriptionId : undefined}
className="mt-1.5 line-clamp-2 text-13 leading-5 text-[var(--text-secondary)]"
>
- {conflictDescription ?? (item.description || item.ghostId)}
+ {replacementDescription ?? (item.description || item.ghostId)}
</span>
</span>
</button>
@@ -1798,13 +1761,10 @@ export function MarketPluginCard({
type="button"
onClick={onSelect}
disabled={unavailable}
- aria-label={t(
- item.installState === 'conflict'
- ? 'settings.ghosts.market.conflictAria'
- : 'settings.ghosts.market.detailsAria',
- { name: item.name },
- )}
- aria-describedby={conflictDescription ? conflictDescriptionId : undefined}
+ aria-label={t('settings.ghosts.market.detailsAria', { name: item.name })}
+ aria-describedby={
+ replacementDescription ? replacementDescriptionId : undefined
+ }
className={cn(
'group/market-details absolute inset-0 flex items-start justify-end rounded-xl text-[var(--text-tertiary)]',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-not-allowed disabled:opacity-40',
@@ -1819,14 +1779,7 @@ export function MarketPluginCard({
<ChevronRight size={16} aria-hidden="true" />
</span>
</button>
- {item.installState === 'conflict' ? (
- <span
- role="status"
- className="relative z-[1] inline-flex h-8 shrink-0 select-none items-center rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 text-11 font-medium text-[var(--text-secondary)]"
- >
- {t('settings.ghosts.market.conflict')}
- </span>
- ) : onInstall ? (
+ {onInstall ? (
<button
type="button"
onClick={(event) => {
@@ -1834,15 +1787,25 @@ export function MarketPluginCard({
onInstall();
}}
disabled={unavailable}
- aria-label={t('settings.ghosts.page.installAria', { name: item.name })}
- aria-describedby={conflictDescription ? conflictDescriptionId : undefined}
+ aria-label={
+ item.installState === 'conflict'
+ ? t('settings.ghosts.market.replaceAria', { name: item.name })
+ : t('settings.ghosts.page.installAria', { name: item.name })
+ }
+ aria-describedby={
+ replacementDescription ? replacementDescriptionId : undefined
+ }
className={cn(
'relative z-[1] inline-flex h-8 shrink-0 items-center rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3.5 text-12 font-medium text-[var(--text-primary)]',
'transition-[background-color,border-color,transform,opacity] duration-150 hover:bg-[var(--surface-hover-soft)] active:scale-[0.98]',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-not-allowed disabled:opacity-40',
)}
>
- {t('settings.ghosts.market.install')}
+ {t(
+ item.installState === 'conflict'
+ ? 'settings.ghosts.market.replace'
+ : 'settings.ghosts.market.install',
+ )}
</button>
) : null}
</div>
diff --git a/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx
index c2d212bf8f..ce2158fe00 100644
--- a/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx
@@ -38,16 +38,14 @@ export function MarketPluginDetailView({
: detail.installState === 'installed'
? 'settings.ghosts.market.installed'
: detail.installState === 'conflict'
- ? 'settings.ghosts.market.conflict'
+ ? 'settings.ghosts.market.replace'
: 'settings.ghosts.market.install';
- const actionDisabled =
- busy || detail.installState === 'installed' || detail.installState === 'conflict';
- // 冲突态的行动按钮只说「暂不可用」,原因必须在详情页也给出——列表卡片同一处理。
- // 详情可能是先以非冲突态打开、随后目录或本地安装状态变化才转冲突的。
- const conflictDescriptionId = useId();
- const conflictDescription =
+ const actionDisabled = busy || detail.installState === 'installed';
+ // 同 id 已装时仍展示明确的替换语义;用户点击后才会进入真实包事务。
+ const replacementDescriptionId = useId();
+ const replacementDescription =
detail.installState === 'conflict'
- ? t('settings.ghosts.market.conflictDescription')
+ ? t('settings.ghosts.market.replaceDescription')
: undefined;
return (
@@ -92,7 +90,9 @@ export function MarketPluginDetailView({
type="button"
onClick={onInstall}
disabled={actionDisabled}
- aria-describedby={conflictDescription ? conflictDescriptionId : undefined}
+ aria-describedby={
+ replacementDescription ? replacementDescriptionId : undefined
+ }
className={cn(
'plugin-detail-primary-action inline-flex h-10 min-w-[104px] items-center justify-center gap-2 whitespace-nowrap rounded-full px-4 text-13 font-medium',
'bg-[var(--accent-cta-bg)] text-[var(--accent-pure-cta-fg)]',
@@ -106,10 +106,10 @@ export function MarketPluginDetailView({
</button>
</div>
<p
- id={conflictDescription ? conflictDescriptionId : undefined}
+ id={replacementDescription ? replacementDescriptionId : undefined}
className="mt-5 text-14 leading-[1.571] text-[var(--text-secondary)]"
>
- {conflictDescription ?? (detail.description || detail.ghostId)}
+ {replacementDescription ?? (detail.description || detail.ghostId)}
</p>
</header>
diff --git a/apps/desktop/src/renderer/features/plugin/PluginMarketPermissionReviewHost.tsx b/apps/desktop/src/renderer/features/plugin/PluginMarketPermissionReviewHost.tsx
index ff95a900e9..5332925cd1 100644
--- a/apps/desktop/src/renderer/features/plugin/PluginMarketPermissionReviewHost.tsx
+++ b/apps/desktop/src/renderer/features/plugin/PluginMarketPermissionReviewHost.tsx
@@ -3,10 +3,11 @@ import { useTranslation } from 'react-i18next';
import { GhostPermissionList, GhostUpdateReview } from '@/cindy-brain/GhostPermissionList';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
+import { isDataOwnerPushStampCurrent } from '@/contexts/dataOwnerGeneration';
import { ghostPermissionItems } from '../../../shared/ghost';
/**
- * 官方市场安装事务的真实包权限确认入口。
+ * 市场安装事务的真实包权限确认入口。
*
* Main 下载并检查真实包后把事务暂停在调用栈内,只向发起窗口投递这一张确认卡。
* 无论确认、取消、Esc、遮罩关闭还是渲染异常,finally 都会把答案回给 Main;
@@ -21,32 +22,56 @@ export function PluginMarketPermissionReviewHost() {
if (!review || typeof review.requestId !== 'string') return;
void (async () => {
let confirmed = false;
+ let unsubscribeAuth: () => void = () => undefined;
try {
- const isUpdate = review.permissionDiff !== null;
- confirmed = await confirm({
- title: isUpdate
- ? t('settings.ghosts.updateConfirm.title', { name: review.manifest.name })
- : t('settings.ghosts.market.installConfirmTitle', {
- name: review.manifest.name,
- }),
- description: isUpdate
- ? t('settings.ghosts.market.updateConfirmDescription')
- : t('settings.ghosts.market.installConfirmDescription'),
- content: isUpdate ? (
- <GhostUpdateReview diff={review.permissionDiff!} />
- ) : (
- <GhostPermissionList items={ghostPermissionItems(review.manifest)} />
- ),
- maxWidth: 520,
- confirmText: isUpdate
- ? t('settings.ghosts.updateConfirm.confirm')
- : t('settings.ghosts.market.install'),
- cancelText: isUpdate
- ? t('settings.ghosts.updateConfirm.cancel')
- : t('settings.ghosts.installConfirm.cancel'),
- autoFocusConfirm: true,
+ // 先核对 Main 投递时的 owner stamp,再读取或渲染任何私有包事实。
+ if (!isDataOwnerPushStampCurrent(review.ownerStamp)) return;
+ const ownerStamp = review.ownerStamp;
+ const abort = new AbortController();
+ unsubscribeAuth = window.electronAPI.onAuthStateChange((state) => {
+ if (
+ state.dataOwnerId !== ownerStamp.dataOwnerId ||
+ state.ownerGeneration !== ownerStamp.ownerGeneration
+ ) {
+ abort.abort();
+ }
});
+ // 订阅前后无 await,但 AuthContext 可能已先消费同一 auth push;再核对一次
+ // 可同时覆盖回调顺序差异和未来同步 listener 实现。
+ if (!isDataOwnerPushStampCurrent(ownerStamp)) abort.abort();
+ const isUpdate = review.isUpdate;
+ confirmed = await confirm(
+ {
+ title: isUpdate
+ ? t('settings.ghosts.updateConfirm.title', { name: review.manifest.name })
+ : t('settings.ghosts.market.installConfirmTitle', {
+ name: review.manifest.name,
+ }),
+ description: isUpdate
+ ? t('settings.ghosts.market.updateConfirmDescription')
+ : t(
+ review.sourceType === 'server'
+ ? 'settings.ghosts.market.installConfirmDescription'
+ : 'settings.ghosts.market.customInstallConfirmDescription',
+ ),
+ content: review.permissionDiff ? (
+ <GhostUpdateReview diff={review.permissionDiff} />
+ ) : (
+ <GhostPermissionList items={ghostPermissionItems(review.manifest)} />
+ ),
+ maxWidth: 520,
+ confirmText: isUpdate
+ ? t('settings.ghosts.updateConfirm.confirm')
+ : t('settings.ghosts.market.install'),
+ cancelText: isUpdate
+ ? t('settings.ghosts.updateConfirm.cancel')
+ : t('settings.ghosts.installConfirm.cancel'),
+ autoFocusConfirm: true,
+ },
+ abort.signal,
+ );
} finally {
+ unsubscribeAuth();
try {
await window.electronAPI.pluginMarket.resolvePackagePermissionReview(
review.requestId,
diff --git a/apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx b/apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx
index 638d1fd441..ce27f05f19 100644
--- a/apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx
+++ b/apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx
@@ -1,20 +1,18 @@
/**
- * Batch plugin update dialog: auto rows stream through, permission
- * expansions wait for explicit per-row consent.
+ * Batch plugin update dialog: rows stream through the shared real-package
+ * install transaction and report progress here.
*
- * Inputs: live batch rows owned by the Plugin page runner plus row actions.
+ * Inputs: live batch rows owned by the Plugin page runner.
* Outputs: progress presentation only; no IPC and no batch policy here.
* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
*/
-import { useState } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
-import { Check, X } from 'lucide-react';
+import { Check } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import { Spinner } from '@/components/ui/spinner';
-import { GhostPermissionDiffView } from '@/cindy-brain/GhostPermissionList';
import { cn } from '@/lib/utils';
import { GhostPluginIcon } from './GhostPluginIcon';
import { isBatchFinished, type UpdateAllRow } from './lib/updateAllModel';
@@ -23,8 +21,6 @@ interface UpdateAllDialogProps {
open: boolean;
rows: readonly UpdateAllRow[];
iconByGhostId: ReadonlyMap<string, string | undefined>;
- onApprove: (pluginId: string) => void;
- onSkip: (pluginId: string) => void;
/** 关弹窗;批量运行器继续在页面组件里跑(「后台继续」语义)。 */
onClose: () => void;
}
@@ -73,12 +69,9 @@ export function UpdateAllDialog({
open,
rows,
iconByGhostId,
- onApprove,
- onSkip,
onClose,
}: UpdateAllDialogProps) {
const { t } = useTranslation();
- const [expandedId, setExpandedId] = useState<string | null>(null);
const finished = isBatchFinished(rows);
return (
<Dialog.Root open={open} onOpenChange={(next) => (next ? undefined : onClose())}>
@@ -91,123 +84,40 @@ export function UpdateAllDialog({
className="fixed left-1/2 top-1/2 z-[10000] flex max-h-[70vh] w-[calc(100vw-48px)] max-w-[520px] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] text-[var(--text-primary)] shadow-[var(--shadow-menu)] focus:outline-none"
style={WINDOW_NO_DRAG_STYLE}
>
- <div className="flex items-start gap-4 border-b-[0.5px] border-[var(--border-default)] px-6 py-5">
- <div className="min-w-0 flex-1">
- <Dialog.Title className="text-18 font-medium">
- {t('settings.ghosts.updateAll.title', { count: rows.length })}
- </Dialog.Title>
- <Dialog.Description className="mt-1 text-13 leading-5 text-[var(--text-tertiary)]">
- {t('settings.ghosts.updateAll.description')}
- </Dialog.Description>
- </div>
- <Dialog.Close
- aria-label={t('settings.ghosts.detail.closeDialog')}
- className="grid size-9 shrink-0 place-items-center rounded-full text-[var(--text-secondary)] hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
- >
- <X size={17} aria-hidden="true" />
- </Dialog.Close>
+ <div className="border-b-[0.5px] border-[var(--border-default)] px-6 py-5">
+ <Dialog.Title className="text-18 font-medium">
+ {t('settings.ghosts.updateAll.title', { count: rows.length })}
+ </Dialog.Title>
+ <Dialog.Description className="mt-1 text-13 leading-5 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.updateAll.description')}
+ </Dialog.Description>
</div>
<div className="overflow-y-auto px-6 py-2">
- {rows.map((row) => {
- const expanded = row.status === 'needs-confirm' && expandedId === row.pluginId;
- return (
- <div
- key={row.pluginId}
- className="border-b-[0.5px] border-[var(--border-default)] py-3.5 last:border-b-0"
- >
- <div className="flex items-center gap-3">
- <GhostPluginIcon
- iconDataUrl={iconByGhostId.get(row.ghostId)}
- iconId={row.ghostId}
- iconName={row.name}
- size="menu"
- />
- <div className="min-w-0 flex-1">
- <p className="truncate text-13 font-medium leading-5">{row.name}</p>
- <p className="text-11 text-[var(--text-tertiary)]">
- {t('settings.ghosts.updateAll.versionRange', {
- from: row.fromVersion,
- to: row.toVersion,
- })}
- {row.status === 'needs-confirm' ? (
- <>
- {' · '}
- <span className="text-[var(--text-primary)]">
- {t(
- row.staleReview
- ? 'settings.ghosts.updateAll.reviewOutdated'
- : 'settings.ghosts.updateAll.permissionChanged',
- )}
- </span>
- </>
- ) : null}
- </p>
- </div>
- <div className="flex shrink-0 items-center gap-2">
- {row.status === 'needs-confirm' && row.staleReview ? (
- // 旧差异已随外部更新失效:点这里让控制器重新取详情重算,
- // 权限没扩张就直接更新,仍有扩张则回到逐项审阅。
- <button
- type="button"
- onClick={() => onApprove(row.pluginId)}
- className={cn(
- 'inline-flex h-7 items-center rounded-full border border-[var(--border-default)] px-3 text-12 font-medium text-[var(--text-primary)]',
- 'transition-colors duration-150 hover:bg-[var(--surface-hover-soft)]',
- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- )}
- >
- {t('settings.ghosts.updateAll.rereview')}
- </button>
- ) : row.status === 'needs-confirm' ? (
- <button
- type="button"
- aria-expanded={expanded}
- onClick={() =>
- setExpandedId((current) =>
- current === row.pluginId ? null : row.pluginId,
- )
- }
- className={cn(
- 'inline-flex h-7 items-center rounded-full border border-[var(--border-default)] px-3 text-12 font-medium text-[var(--text-primary)]',
- 'transition-colors duration-150 hover:bg-[var(--surface-hover-soft)]',
- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
- )}
- >
- {t(
- expanded
- ? 'settings.ghosts.updateAll.collapseDiff'
- : 'settings.ghosts.updateAll.reviewDiff',
- )}
- </button>
- ) : (
- <RowStatus row={row} />
- )}
- </div>
- </div>
- {expanded && row.permissionDiff ? (
- <div className="ml-9 mt-3 rounded-lg border-[0.5px] border-[var(--border-default)] bg-[var(--surface)] px-4 py-3">
- <GhostPermissionDiffView diff={row.permissionDiff} />
- <div className="mt-3 flex items-center gap-2">
- <button
- type="button"
- onClick={() => onApprove(row.pluginId)}
- className="inline-flex h-8 items-center rounded-full bg-[var(--accent-cta-bg)] px-4 text-12 font-medium text-[var(--accent-pure-cta-fg)] transition-transform duration-150 hover:bg-[var(--accent-hover)] active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
- >
- {t('settings.ghosts.updateAll.approve')}
- </button>
- <button
- type="button"
- onClick={() => onSkip(row.pluginId)}
- className="inline-flex h-8 items-center rounded-full border border-[var(--border-default)] px-4 text-12 font-medium text-[var(--text-primary)] transition-colors duration-150 hover:bg-[var(--surface-hover-soft)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
- >
- {t('settings.ghosts.updateAll.skip')}
- </button>
- </div>
- </div>
- ) : null}
+ {rows.map((row) => (
+ <div
+ key={row.pluginId}
+ className="flex items-center gap-3 border-b-[0.5px] border-[var(--border-default)] py-3.5 last:border-b-0"
+ >
+ <GhostPluginIcon
+ iconDataUrl={iconByGhostId.get(row.ghostId)}
+ iconId={row.ghostId}
+ iconName={row.name}
+ size="menu"
+ />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-13 font-medium leading-5">{row.name}</p>
+ <p className="text-11 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.updateAll.versionRange', {
+ from: row.fromVersion,
+ to: row.toVersion,
+ })}
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ <RowStatus row={row} />
</div>
- );
- })}
+ </div>
+ ))}
</div>
<div className="flex items-center justify-end gap-2 border-t-[0.5px] border-[var(--border-default)] px-6 py-4">
<button
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
index a2d76cbf1f..9c49fc889a 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
@@ -13,7 +13,7 @@ vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, options?: { name?: string }) =>
(key === 'settings.ghosts.market.detailsAria' ||
- key === 'settings.ghosts.market.conflictAria') &&
+ key === 'settings.ghosts.market.replaceAria') &&
options?.name
? `${key}:${options.name}`
: key,
@@ -388,7 +388,7 @@ describe('MarketPluginCard', () => {
).toBeTruthy();
expect(
screen.getByRole('button', {
- name: 'settings.ghosts.market.conflictAria:GitHub',
+ name: 'settings.ghosts.market.detailsAria:GitHub',
}),
).toBeTruthy();
});
@@ -414,30 +414,33 @@ describe('MarketPluginCard', () => {
expect(screen.getByText('Cindy').className).toContain('truncate');
});
- it('distinguishes unavailable conflicts from busy market operations', () => {
+ it('offers explicit replacement while still blocking actions during busy operations', () => {
+ const onInstall = vi.fn();
const { rerender } = render(
<MarketPluginCard
item={{ ...marketPlugin, installState: 'conflict' }}
busy={false}
onSelect={vi.fn()}
- onInstall={vi.fn()}
+ onInstall={onInstall}
onIconLoadError={vi.fn()}
/>,
);
const cardBody = screen.getByRole('button', { name: 'Google Calendar' });
- expect((cardBody as HTMLButtonElement).disabled).toBe(true);
- expect(cardBody.className).toContain('cursor-not-allowed');
+ expect((cardBody as HTMLButtonElement).disabled).toBe(false);
+ expect(cardBody.className).toContain('cursor-pointer');
expect(cardBody.className).not.toContain('cursor-wait');
- const conflictDescription = screen.getByText('settings.ghosts.market.conflictDescription');
- expect(conflictDescription.id).toBeTruthy();
- expect(cardBody.getAttribute('aria-describedby')).toBe(conflictDescription.id);
- const conflictAction = screen.getByRole('button', {
- name: 'settings.ghosts.market.conflictAria:Google Calendar',
+ const replacementDescription = screen.getByText('settings.ghosts.market.replaceDescription');
+ expect(replacementDescription.id).toBeTruthy();
+ expect(cardBody.getAttribute('aria-describedby')).toBe(replacementDescription.id);
+ const replaceAction = screen.getByRole('button', {
+ name: 'settings.ghosts.market.replaceAria:Google Calendar',
});
- expect((conflictAction as HTMLButtonElement).disabled).toBe(true);
- expect(conflictAction.getAttribute('aria-describedby')).toBe(conflictDescription.id);
- expect(screen.getByRole('status').textContent).toBe('settings.ghosts.market.conflict');
+ expect((replaceAction as HTMLButtonElement).disabled).toBe(false);
+ expect(replaceAction.getAttribute('aria-describedby')).toBe(replacementDescription.id);
+ expect(replaceAction.textContent).toBe('settings.ghosts.market.replace');
+ fireEvent.click(replaceAction);
+ expect(onInstall).toHaveBeenCalledTimes(1);
expect(screen.queryByRole('button', { name: 'settings.ghosts.page.installAria' })).toBeNull();
expect(screen.queryByText(marketPlugin.description ?? '')).toBeNull();
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/MarketPluginDetailView.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/MarketPluginDetailView.test.tsx
index 8445a26c15..33a780b6c9 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/MarketPluginDetailView.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/MarketPluginDetailView.test.tsx
@@ -1,7 +1,6 @@
/**
- * Regression coverage for the market Plugin detail view's conflict state:
- * 行动按钮只说「暂不可用」,不可用的原因必须同时出现在正文并绑给按钮,
- * 否则详情页比改动前信息更少(改动前按钮文案本身就是「插件标识冲突」)。
+ * Regression coverage for the market Plugin detail view's explicit same-ID
+ * replacement action and its data-preservation explanation.
* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
* @vitest-environment jsdom
*/
@@ -75,18 +74,18 @@ describe('MarketPluginDetailView', () => {
expect(screen.getByText('settings.ghosts.perm.grantsTitle')).toBeTruthy();
});
- it('explains why a conflicting plugin is unavailable and binds it to the action', () => {
+ it('offers an explicit same-id replacement and binds its explanation to the action', () => {
renderDetail({ installState: 'conflict' });
- const reason = screen.getByText('settings.ghosts.market.conflictDescription');
+ const reason = screen.getByText('settings.ghosts.market.replaceDescription');
expect(reason.id).toBeTruthy();
// 冲突态下正文让位给原因,不再显示营销描述。
expect(screen.queryByText('Connect Google Calendar')).toBeNull();
const action = screen.getByRole('button', {
- name: /settings\.ghosts\.market\.conflict$/,
+ name: /settings\.ghosts\.market\.replace$/,
}) as HTMLButtonElement;
- expect(action.disabled).toBe(true);
+ expect(action.disabled).toBe(false);
expect(action.getAttribute('aria-describedby')).toBe(reason.id);
});
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/PluginMarketPermissionReviewHost.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/PluginMarketPermissionReviewHost.test.tsx
new file mode 100644
index 0000000000..a34cd2f70e
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/PluginMarketPermissionReviewHost.test.tsx
@@ -0,0 +1,137 @@
+// @vitest-environment jsdom
+
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';
+import {
+ __testing as dataOwnerGenerationTesting,
+ setDataOwnerGeneration,
+} from '@/contexts/dataOwnerGeneration';
+import type { PluginMarketPackageReviewRequest } from '../../../../shared/pluginMarket';
+import { PluginMarketPermissionReviewHost } from '../PluginMarketPermissionReviewHost';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+describe('PluginMarketPermissionReviewHost', () => {
+ let reviewListener: ((review: PluginMarketPackageReviewRequest) => void) | undefined;
+ let authListener: ((state: AuthStateChangePayload) => void) | undefined;
+ const resolveReview = vi.fn(async () => ({ handled: true }));
+
+ beforeEach(() => {
+ dataOwnerGenerationTesting.reset();
+ setDataOwnerGeneration('owner-a', 1);
+ resolveReview.mockClear();
+ (window as unknown as { electronAPI: Partial<Window['electronAPI']> }).electronAPI = {
+ onAuthStateChange: (listener) => {
+ authListener = listener;
+ return () => {
+ authListener = undefined;
+ };
+ },
+ pluginMarket: {
+ onPackagePermissionReview: (
+ listener: (review: PluginMarketPackageReviewRequest) => void,
+ ) => {
+ reviewListener = listener;
+ return () => {
+ reviewListener = undefined;
+ };
+ },
+ resolvePackagePermissionReview: resolveReview,
+ } as unknown as Window['electronAPI']['pluginMarket'],
+ };
+ });
+
+ afterEach(() => {
+ cleanup();
+ dataOwnerGenerationTesting.reset();
+ delete (window as unknown as { electronAPI?: unknown }).electronAPI;
+ reviewListener = undefined;
+ authListener = undefined;
+ });
+
+ it('closes a delivered private review and cancels it when the data owner changes', async () => {
+ render(
+ <ConfirmDialogProvider>
+ <PluginMarketPermissionReviewHost />
+ </ConfirmDialogProvider>,
+ );
+
+ act(() => {
+ reviewListener?.({
+ requestId: 'review-a',
+ ownerStamp: { dataOwnerId: 'owner-a', ownerGeneration: 1 },
+ manifest: {
+ schemaVersion: 2,
+ id: 'private-plugin',
+ name: 'Private Plugin',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['tool'],
+ },
+ permissionDiff: null,
+ isUpdate: false,
+ sourceType: 'server',
+ });
+ });
+ await screen.findByText('settings.ghosts.market.installConfirmTitle');
+
+ act(() => {
+ setDataOwnerGeneration('owner-b', 2);
+ authListener?.({
+ user: null,
+ mode: 'signed-out',
+ dataOwnerId: 'owner-b',
+ ownerGeneration: 2,
+ canEnterApp: false,
+ isAuthenticated: false,
+ isCanary: false,
+ deviceId: 'device',
+ hasAccountDeletionReceipt: false,
+ accountDeletionRestored: false,
+ });
+ });
+
+ await waitFor(() => {
+ expect(screen.queryByText('settings.ghosts.market.installConfirmTitle')).toBeNull();
+ expect(resolveReview).toHaveBeenCalledWith('review-a', false);
+ });
+ });
+
+ it('never shows a review whose Main delivery owner is already stale', async () => {
+ render(
+ <ConfirmDialogProvider>
+ <PluginMarketPermissionReviewHost />
+ </ConfirmDialogProvider>,
+ );
+ setDataOwnerGeneration('owner-b', 2);
+
+ act(() => {
+ reviewListener?.({
+ requestId: 'stale-review',
+ ownerStamp: { dataOwnerId: 'owner-a', ownerGeneration: 1 },
+ manifest: {
+ schemaVersion: 2,
+ id: 'private-plugin',
+ name: 'Private Plugin',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['tool'],
+ },
+ permissionDiff: null,
+ isUpdate: false,
+ sourceType: 'server',
+ });
+ });
+
+ await waitFor(() => {
+ expect(resolveReview).toHaveBeenCalledWith('stale-review', false);
+ });
+ expect(screen.queryByText('settings.ghosts.market.installConfirmTitle')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
index 733aa6a40e..8805662d83 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts
@@ -1,7 +1,7 @@
/**
- * Regression coverage for the module-level update-all batch controller:
- * uninstall guards, reviewed-manifest passthrough, cancellation handling,
- * baseline drift recovery, and batch state surviving page unmount.
+ * Regression coverage for the module-level update-all controller.
+ * Permission review is intentionally absent here: every row delegates to the
+ * Main-owned real-package transaction and this module owns progress only.
* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
* @vitest-environment jsdom
*/
@@ -25,14 +25,13 @@ import type { GhostManifest } from '../../../../shared/ghost';
import type { PluginMarketDetail, PluginMarketItem } from '../../../../shared/pluginMarket';
import {
__resetUpdateAllBatchForTest,
- approveUpdateExpansion,
getUpdateAllBatchState,
reconcileUpdateAllBatch,
setUpdateAllBatchHooks,
startUpdateAllBatch,
} from '../lib/updateAllController';
-function manifest(overrides: Partial<GhostManifest>): GhostManifest {
+function manifest(overrides: Partial<GhostManifest> = {}): GhostManifest {
return {
id: 'ghost-a',
name: 'Ghost A',
@@ -42,7 +41,7 @@ function manifest(overrides: Partial<GhostManifest>): GhostManifest {
} as GhostManifest;
}
-function marketItem(overrides: Partial<PluginMarketItem>): PluginMarketItem {
+function marketItem(overrides: Partial<PluginMarketItem> = {}): PluginMarketItem {
return {
pluginId: 'plugin-a',
ghostId: 'ghost-a',
@@ -64,25 +63,26 @@ function marketItem(overrides: Partial<PluginMarketItem>): PluginMarketItem {
};
}
-const detailMock = vi.fn<(pluginId: string) => Promise<PluginMarketDetail>>();
-const installMock = vi.fn(async () => ({ ghost: { manifest: manifest({}) } }) as never);
-
-function stubDetail(overrides: {
- manifest: GhostManifest;
- sourceType: PluginMarketDetail['sourceType'];
-}): void {
- detailMock.mockResolvedValue({
- ...marketItem({ sourceType: overrides.sourceType }),
- manifest: overrides.manifest,
+function detail(overrides: Partial<PluginMarketDetail> = {}): PluginMarketDetail {
+ const item = marketItem(overrides);
+ return {
+ ...item,
+ manifest: manifest({ id: item.ghostId, version: item.version }),
readme: null,
- } as unknown as PluginMarketDetail);
+ ...overrides,
+ } as PluginMarketDetail;
}
-async function waitForSettledBatch(): Promise<void> {
+const detailMock = vi.fn<(pluginId: string) => Promise<PluginMarketDetail>>();
+const installMock = vi.fn();
+
+async function waitForFinishedBatch(): Promise<void> {
await vi.waitFor(() => {
- const state = getUpdateAllBatchState();
- expect(state.running).toBe(false);
- expect(state.rows?.some((row) => row.status === 'pending')).toBe(false);
+ const current = getUpdateAllBatchState();
+ expect(current.running).toBe(false);
+ expect(
+ current.rows?.some((row) => row.status === 'pending' || row.status === 'installing'),
+ ).toBe(false);
});
}
@@ -90,921 +90,194 @@ beforeEach(() => {
__resetUpdateAllBatchForTest();
dataOwnerTesting.reset();
setDataOwnerGeneration('owner-a');
+ installedGhosts = [{ manifest: manifest({ version: '1.0.0' }) }];
detailMock.mockReset();
- // mockReset 而非 mockClear:用例可能装过"卡住不 resolve"的实现(并发编排),
- // 只清调用记录会让它泄漏到后面的用例里把 waitFor 全部拖超时。
+ detailMock.mockResolvedValue(detail());
installMock.mockReset();
- installMock.mockResolvedValue({ ghost: { manifest: manifest({}) } } as never);
+ installMock.mockResolvedValue({ ghost: { manifest: manifest() } });
vi.mocked(toast.success).mockClear();
- installedGhosts = [{ manifest: manifest({ version: '1.0.0' }) }];
(window as unknown as { electronAPI: unknown }).electronAPI = {
pluginMarket: { detail: detailMock, install: installMock },
};
});
describe('updateAllController', () => {
- it('skips rows whose plugin was uninstalled mid-batch instead of reinstalling', async () => {
- installedGhosts = [];
- stubDetail({ manifest: manifest({}), sourceType: 'server' });
+ it('serially delegates every row with only its current release precondition', async () => {
+ installedGhosts.push({ manifest: manifest({ id: 'ghost-b', version: '2.0.0' }) });
+ detailMock.mockImplementation(async (pluginId) =>
+ pluginId === 'plugin-a'
+ ? detail()
+ : detail({
+ pluginId: 'plugin-b',
+ ghostId: 'ghost-b',
+ releaseId: 'release-b2',
+ version: '2.1.0',
+ }),
+ );
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
+ startUpdateAllBatch([
+ marketItem(),
+ marketItem({
+ pluginId: 'plugin-b',
+ ghostId: 'ghost-b',
+ releaseId: 'release-b2',
+ version: '2.1.0',
+ }),
+ ]);
+ await waitForFinishedBatch();
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('skipped');
- expect(installMock).not.toHaveBeenCalled();
+ expect(installMock.mock.calls).toEqual([
+ ['plugin-a', { expectedReleaseId: 'release-2', allowSourceReplacement: false }],
+ ['plugin-b', { expectedReleaseId: 'release-b2', allowSourceReplacement: false }],
+ ]);
+ expect(getUpdateAllBatchState().rows?.map((row) => row.status)).toEqual([
+ 'done',
+ 'done',
+ ]);
});
- it('holds server preview permission expansion for approval', async () => {
- const targetManifest = manifest({ network: { hosts: ['api.example.com'] } });
- stubDetail({ manifest: targetManifest, sourceType: 'server' });
+ it('marks a Main-side permission cancellation as skipped', async () => {
+ installMock.mockResolvedValueOnce({ cancelled: true });
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
- expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({
- status: 'needs-confirm',
- releaseId: 'release-2',
- expectedManifest: targetManifest,
- });
+ startUpdateAllBatch([marketItem()]);
+ await waitForFinishedBatch();
- await approveUpdateExpansion('plugin-a');
- expect(installMock).toHaveBeenLastCalledWith(
- 'plugin-a',
- expect.objectContaining({ expectedManifest: targetManifest }),
- );
+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('skipped');
});
- it('marks a transaction cancelled in Main as skipped', async () => {
- stubDetail({ manifest: manifest({}), sourceType: 'server' });
- installMock.mockResolvedValueOnce({ cancelled: true } as never);
+ it('skips a plugin removed before its row starts', async () => {
+ installedGhosts = [];
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
+ startUpdateAllBatch([marketItem()]);
+ await waitForFinishedBatch();
expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('skipped');
+ expect(installMock).not.toHaveBeenCalled();
});
- it('passes the reviewed manifest back when approving a non-server expansion', async () => {
- const nextManifest = manifest({ network: { hosts: ['api.example.com'] } });
- stubDetail({ manifest: nextManifest, sourceType: 'git-market' });
-
- startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);
- await waitForSettledBatch();
+ it('settles a release already installed by another flow without downloading again', async () => {
+ detailMock.mockResolvedValueOnce(detail({ installState: 'installed' }));
- const held = getUpdateAllBatchState().rows?.[0];
- expect(held?.status).toBe('needs-confirm');
- expect(held?.expectedManifest).toBe(nextManifest);
+ startUpdateAllBatch([marketItem()]);
+ await waitForFinishedBatch();
- await approveUpdateExpansion('plugin-a');
- expect(installMock).toHaveBeenCalledWith('plugin-a', {
- expectedReleaseId: 'release-2',
- expectedManifest: nextManifest,
- allowPermissionExpansion: true,
- reviewedBaseline: expect.any(String),
- });
expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
- });
-
- it('passes expectedManifest when approving a server-source expansion', async () => {
- stubDetail({
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- sourceType: 'server',
- });
-
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
- await approveUpdateExpansion('plugin-a');
-
- expect(installMock).toHaveBeenLastCalledWith(
- 'plugin-a',
- expect.objectContaining({
- expectedReleaseId: 'release-2',
- expectedManifest: expect.any(Object),
- reviewedBaseline: expect.any(String),
- }),
- );
- });
-
- it('turns approval into a skip when the plugin was uninstalled while waiting', async () => {
- stubDetail({
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- sourceType: 'server',
- });
-
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
-
- installedGhosts = [];
- await approveUpdateExpansion('plugin-a');
-
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('skipped');
expect(installMock).not.toHaveBeenCalled();
});
- it('recomputes the diff when an external update replaced the permission baseline', async () => {
- stubDetail({
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- sourceType: 'server',
- });
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');
-
- // 「从文件更新」把插件装成了第三个版本,且它已自带原先要审的 network 权限:
- // 审阅过的 diff 与 allowPermissionExpansion 都不再对应现实。
- installedGhosts = [
- { manifest: manifest({ version: '1.0.5', network: { hosts: ['api.example.com'] } }) },
- ];
- reconcileUpdateAllBatch();
- const held = getUpdateAllBatchState().rows?.[0];
- expect(held).toMatchObject({ status: 'needs-confirm', staleReview: true, fromVersion: '1.0.5' });
- expect(held?.permissionDiff).toBeUndefined();
-
- await approveUpdateExpansion('plugin-a');
- // 相对当前已装 manifest 已无扩权 → 按普通更新安装,不带 allowPermissionExpansion。
- expect(installMock).toHaveBeenCalledWith('plugin-a', {
- expectedReleaseId: 'release-2',
- expectedManifest: expect.any(Object),
- });
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
- });
-
- it('keeps the row held for re-review when the recomputed diff still expands permissions', async () => {
- stubDetail({
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- sourceType: 'server',
- });
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
-
- // 外部装成第三个版本且权限面变了(多了 fs),但仍不含目标版本要新增的
- // network —— 基线失效触发重算,重算结果依旧是扩权。
- installedGhosts = [{ manifest: manifest({ version: '1.0.5', slots: ['fs'] }) }];
- reconcileUpdateAllBatch();
- await approveUpdateExpansion('plugin-a');
+ it('skips a queued update that changed to a source conflict before its turn', async () => {
+ installedGhosts.push({ manifest: manifest({ id: 'ghost-b', version: '2.0.0' }) });
+ let resolveFirstInstall: (() => void) | undefined;
+ installMock.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveFirstInstall = () => resolve({ ghost: { manifest: manifest() } });
+ }),
+ );
+ detailMock.mockImplementation(async (pluginId) =>
+ pluginId === 'plugin-a'
+ ? detail()
+ : detail({
+ pluginId: 'plugin-b',
+ ghostId: 'ghost-b',
+ installState: 'conflict',
+ }),
+ );
- const row = getUpdateAllBatchState().rows?.[0];
- expect(row).toMatchObject({ status: 'needs-confirm', staleReview: false, fromVersion: '1.0.5' });
- expect(row?.permissionDiff?.added.length).toBeGreaterThan(0);
- // 重算后仍是扩权:停在当前批次等待用户重新确认,不提前调用安装。
- expect(installMock).not.toHaveBeenCalled();
- });
+ startUpdateAllBatch([
+ marketItem(),
+ marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),
+ ]);
+ await vi.waitFor(() => expect(resolveFirstInstall).toBeDefined());
+ resolveFirstInstall?.();
+ await waitForFinishedBatch();
- it('recomputes on baseline drift even before reconcile flagged the row', async () => {
- stubDetail({
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- sourceType: 'server',
- });
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
-
- // 外部更新已落地但 reconcile 还没跑(竞态窗口):版本比较必须兜住,
- // 不得拿旧 diff 换来的 allowPermissionExpansion 安装。
- installedGhosts = [
- { manifest: manifest({ version: '1.0.5', network: { hosts: ['api.example.com'] } }) },
- ];
- await approveUpdateExpansion('plugin-a');
-
- expect(installMock).toHaveBeenCalledWith('plugin-a', {
- expectedReleaseId: 'release-2',
- expectedManifest: expect.any(Object),
- });
+ expect(installMock).toHaveBeenCalledTimes(1);
+ expect(getUpdateAllBatchState().rows?.[1]?.status).toBe('skipped');
});
- it('invalidates the review when a same-version manifest swap widened permissions', async () => {
- stubDetail({
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- sourceType: 'server',
- });
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');
+ it('keeps ordinary install failures as terminal failed rows', async () => {
+ installMock.mockRejectedValueOnce(new Error('network down'));
- // 「从文件更新」换入**同版本**但权限更宽的 manifest:版本号完全看不出来,
- // 沿用旧审阅会把 fs 这条从未审阅的权限一并放行。
- installedGhosts = [{ manifest: manifest({ version: '1.0.0', slots: ['fs'] }) }];
- reconcileUpdateAllBatch();
- const held = getUpdateAllBatchState().rows?.[0];
- expect(held).toMatchObject({ status: 'needs-confirm', staleReview: true });
- expect(held?.permissionDiff).toBeUndefined();
+ startUpdateAllBatch([marketItem()]);
+ await waitForFinishedBatch();
- await approveUpdateExpansion('plugin-a');
- // 相对新基线仍是扩权 → 回到预览权限确认,绝不沿用旧批准或提前安装。
- expect(installMock).not.toHaveBeenCalled();
expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({
- status: 'needs-confirm',
- staleReview: false,
+ status: 'failed',
+ errorText: 'settings.ghosts.market.errors.generic',
});
});
- it('keeps the review valid when only the version moved but permissions are identical', async () => {
- stubDetail({
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- sourceType: 'server',
- });
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
-
- // 权限面完全没变,只是版本号动了:审阅结论仍然成立,不该逼用户重审。
- installedGhosts = [{ manifest: manifest({ version: '1.0.4' }) }];
- reconcileUpdateAllBatch();
- const kept = getUpdateAllBatchState().rows?.[0];
- expect(kept).toMatchObject({ status: 'needs-confirm', fromVersion: '1.0.4' });
- expect(kept?.staleReview).toBeFalsy();
- expect(kept?.permissionDiff?.added.length).toBeGreaterThan(0);
-
- await approveUpdateExpansion('plugin-a');
- expect(installMock).toHaveBeenLastCalledWith(
- 'plugin-a',
- expect.objectContaining({
- expectedReleaseId: 'release-2',
- reviewedBaseline: expect.any(String),
- }),
- );
- });
-
- it('voids the batch when the data owner changes during the detail round-trip', async () => {
- let releaseDetail: (() => void) | undefined;
- detailMock.mockImplementation(
+ it('voids the whole batch when its data owner changes during detail loading', async () => {
+ let resolveDetail: ((value: PluginMarketDetail) => void) | undefined;
+ detailMock.mockImplementationOnce(
() =>
new Promise((resolve) => {
- releaseDetail = () => {
- setDataOwnerGeneration('owner-b');
- resolve({
- ...marketItem({}),
- manifest: manifest({}),
- readme: null,
- } as unknown as PluginMarketDetail);
- };
+ resolveDetail = resolve;
}),
);
- startUpdateAllBatch([marketItem({})]);
- await vi.waitFor(() => expect(releaseDetail).toBeDefined());
- releaseDetail?.();
+ startUpdateAllBatch([marketItem()]);
+ await vi.waitFor(() => expect(resolveDetail).toBeDefined());
+ setDataOwnerGeneration('owner-b');
+ resolveDetail?.(detail());
await vi.waitFor(() => expect(getUpdateAllBatchState().running).toBe(false));
- // 旧账号发起的批次在身份切换后整体作废,不得写入新账号数据。
expect(getUpdateAllBatchState().rows).toBeNull();
expect(installMock).not.toHaveBeenCalled();
});
- it('reconcile settles held rows updated externally and voids stale-owner batches', async () => {
- stubDetail({
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- sourceType: 'server',
- });
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');
-
- // 目标 release 已落账(市场快照报 installed)→ 待确认行收束为完成。
- installedGhosts = [{ manifest: manifest({ version: '1.1.0' }) }];
- reconcileUpdateAllBatch([marketItem({ installState: 'installed' })]);
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
- expect(installMock).not.toHaveBeenCalled();
-
- // 账号切换后对账直接作废整批。
- startUpdateAllBatch([]);
- setDataOwnerGeneration('owner-b');
- reconcileUpdateAllBatch();
- expect(getUpdateAllBatchState().rows).toBeNull();
- });
-
- it('does not settle as done when a same-version foreign release was installed', async () => {
- stubDetail({
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- sourceType: 'server',
- });
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
-
- // 「从文件更新」装了同版本但**不是目标 release** 的包:版本号看着到位,
- // 但 main 侧 record.releaseId 对不上,市场仍报 update-available。
- installedGhosts = [{ manifest: manifest({ version: '1.1.0' }) }];
- reconcileUpdateAllBatch([marketItem({ installState: 'update-available' })]);
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');
-
- await approveUpdateExpansion('plugin-a');
- // 目标 release 仍未落账 → 必须真正安装,不得凭版本号收成完成。
- expect(installMock).toHaveBeenLastCalledWith(
- 'plugin-a',
- expect.objectContaining({
- expectedReleaseId: 'release-2',
- reviewedBaseline: expect.any(String),
- }),
- );
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
- });
-
- it('re-reads the installed manifest after detail() instead of trusting the pre-await snapshot', async () => {
- // 审阅基线:已装带 network,目标包在此之上多出 fs → 用户审的是 fs 这一条。
- installedGhosts = [
- { manifest: manifest({ version: '1.0.0', network: { hosts: ['api.example.com'] } }) },
- ];
- stubDetail({
- manifest: manifest({ network: { hosts: ['api.example.com'] }, slots: ['fs'] }),
- sourceType: 'server',
- });
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');
-
- // detail() 往返期间「从文件更新」把已装换成**不带 network** 的包:此刻目标包
- // 相对当前已装多出 network + fs,而 network 用户从没审过。批准必须以
- // detail 之后的事实判断,拿 await 前捕获的快照会直接放行。
- detailMock.mockImplementation(async () => {
- installedGhosts = [{ manifest: manifest({ version: '1.0.0' }) }];
- return {
- ...marketItem({}),
- manifest: manifest({ network: { hosts: ['api.example.com'] }, slots: ['fs'] }),
- readme: null,
- } as unknown as PluginMarketDetail;
- });
-
- await approveUpdateExpansion('plugin-a');
- expect(installMock).not.toHaveBeenCalled();
- const row = getUpdateAllBatchState().rows?.[0];
- expect(row?.status).toBe('needs-confirm');
- // 新差异按当前事实重算,把没审过的 network 也摆出来。
- expect(row?.permissionDiff?.added.length).toBeGreaterThan(1);
- });
-
- it('returns a Main-side baseline rejection to re-review instead of a terminal failure', async () => {
- stubDetail({
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- sourceType: 'server',
- });
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
-
- // Main 在安装锁内用当前已装 manifest 复核后否决了这次批准。
- installMock.mockRejectedValueOnce(
- Object.assign(new Error('[PRECONDITION_FAILED] baseline changed'), {
- message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] baseline changed',
- }),
- );
-
- await approveUpdateExpansion('plugin-a');
- const row = getUpdateAllBatchState().rows?.[0];
- // 「事实已变,请重新审阅」而不是「更新失败」——终态失败会让用户失去入口。
- // 手里的 detail 已被 Main 否决,不能拿它出确认内容:丢弃旧差异 + 标记过期,
- // 下次批准重新取详情。
- expect(row?.status).toBe('needs-confirm');
- expect(row?.staleReview).toBe(true);
- expect(row?.permissionDiff).toBeUndefined();
- expect(row?.errorText).toBeUndefined();
- });
-
- it('holds running through the post-approval refresh so no second batch can start', async () => {
- stubDetail({
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- sourceType: 'server',
- });
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
- expect(getUpdateAllBatchState().running).toBe(false);
-
- let releaseRefresh: (() => void) | undefined;
+ it('keeps running until the post-batch market refresh finishes', async () => {
+ let resolveRefresh: (() => void) | undefined;
setUpdateAllBatchHooks({
refreshMarket: () =>
new Promise<void>((resolve) => {
- releaseRefresh = resolve;
+ resolveRefresh = resolve;
}),
});
- const approving = approveUpdateExpansion('plugin-a');
- await vi.waitFor(() => expect(releaseRefresh).toBeDefined());
- // 刷新还没回来:页面手里仍是旧的 update-available 快照,必须挡住第二批。
+ startUpdateAllBatch([marketItem()]);
+ await vi.waitFor(() => expect(resolveRefresh).toBeDefined());
expect(getUpdateAllBatchState().running).toBe(true);
- startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);
- expect(getUpdateAllBatchState().rows?.map((row) => row.pluginId)).toEqual(['plugin-a']);
-
- releaseRefresh?.();
- await approving;
- expect(getUpdateAllBatchState().running).toBe(false);
- });
- it('serialises concurrent approvals and only settles after the last one', async () => {
- const expanding = manifest({ network: { hosts: ['api.example.com'] } });
- detailMock.mockImplementation(async (pluginId) =>
- ({
- ...marketItem({ pluginId, ghostId: pluginId === 'plugin-a' ? 'ghost-a' : 'ghost-b' }),
- manifest: expanding,
- readme: null,
- }) as unknown as PluginMarketDetail,
- );
- installedGhosts = [
- { manifest: manifest({ version: '1.0.0' }) },
- { manifest: manifest({ id: 'ghost-b', version: '1.0.0' }) },
- ];
startUpdateAllBatch([
- marketItem({}),
marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),
]);
- await waitForSettledBatch();
- expect(
- getUpdateAllBatchState().rows?.every((row) => row.status === 'needs-confirm'),
- ).toBe(true);
-
- // 两次安装都卡住,用来观察是否并发。
- const installGate: Array<() => void> = [];
- let concurrentPeak = 0;
- let active = 0;
- installMock.mockImplementation(
- () =>
- new Promise((resolve) => {
- active += 1;
- concurrentPeak = Math.max(concurrentPeak, active);
- installGate.push(() => {
- active -= 1;
- resolve({ ghost: { manifest: expanding } } as never);
- });
- }),
- );
- let refreshCalls = 0;
- setUpdateAllBatchHooks({
- refreshMarket: async () => {
- refreshCalls += 1;
- },
- });
-
- // 用户连点两个「同意」。
- const first = approveUpdateExpansion('plugin-a');
- const second = approveUpdateExpansion('plugin-b');
-
- await vi.waitFor(() => expect(installGate.length).toBe(1));
- // 串行:第二个必须排队,不能与第一个同时在装。
- expect(concurrentPeak).toBe(1);
- expect(getUpdateAllBatchState().running).toBe(true);
-
- installGate[0]?.();
- await first;
- // 第一个结束时还有在途批准 → 不许提前释放闸门、不许提前报完成。
- expect(getUpdateAllBatchState().running).toBe(true);
- expect(refreshCalls).toBe(0);
-
- await vi.waitFor(() => expect(installGate.length).toBe(2));
- installGate[1]?.();
- await second;
-
- // 最后一个结束才收尾:刷新一次、释放 running、报一次完成。
- expect(concurrentPeak).toBe(1);
- expect(getUpdateAllBatchState().running).toBe(false);
- expect(refreshCalls).toBe(1);
- expect(vi.mocked(toast.success)).toHaveBeenCalledTimes(1);
- });
-
- it('skips a row whose target release was already installed by the single-item flow', async () => {
- // 用户在批次启动前用卡片的单项更新装了同一个 release;本批次拿的是那之前的
- // 市场快照,仍标 update-available。runner 取详情后必须发现已落账并跳过。
- detailMock.mockResolvedValue({
- ...marketItem({ installState: 'installed' }),
- manifest: manifest({ version: '1.1.0' }),
- readme: null,
- } as unknown as PluginMarketDetail);
-
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
-
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
- expect(installMock).not.toHaveBeenCalled();
- });
-
- it('holds a runner row for re-review instead of failing it on PRECONDITION_FAILED', async () => {
- stubDetail({ manifest: manifest({}), sourceType: 'git-market' });
- installMock.mockRejectedValueOnce(
- Object.assign(new Error('precondition'), {
- message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] release changed',
- }),
- );
-
- startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);
- await waitForSettledBatch();
-
- const row = getUpdateAllBatchState().rows?.[0];
- // 自动安装路径遇到前置条件变化 → 可恢复的待重审,不是终态失败。
- expect(row).toMatchObject({ status: 'needs-confirm', staleReview: true });
- expect(row?.errorText).toBeUndefined();
- expect(row?.permissionDiff).toBeUndefined();
- });
-
- it('lets a held runner row be re-reviewed and approved through to completion', async () => {
- stubDetail({ manifest: manifest({}), sourceType: 'git-market' });
- installMock.mockRejectedValueOnce(
- Object.assign(new Error('precondition'), {
- message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] release changed',
- }),
- );
-
- startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);
- await waitForSettledBatch();
-
- const held = getUpdateAllBatchState().rows?.[0];
- expect(held).toMatchObject({ status: 'needs-confirm', staleReview: true });
- // 关键:待重审行必须带着目标 release,否则 approve 的入口守卫会直接返回,
- // 用户点「重新审阅」毫无反应,该项在本批次里永远走不下去。
- expect(held?.releaseId).toBe('release-2');
-
- // 点「重新审阅」→ 重取详情、按当前事实重算(已无扩权)→ 装上收尾。
- await approveUpdateExpansion('plugin-a');
-
- expect(installMock).toHaveBeenLastCalledWith('plugin-a', {
- expectedReleaseId: 'release-2',
- expectedManifest: expect.anything(),
- });
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
- });
-
- it('fails instead of holding when there is no target release to re-review', async () => {
- // detail 拿得到、但 install 前置条件失败且行上没有 releaseId 的极端情形:
- // 用 detail 报 installed 之外的路径构造——这里直接验证 hold 的防御分支,
- // 保证不会产出「点不动的 needs-confirm 死行」。
- detailMock.mockResolvedValue({
- ...marketItem({ releaseId: '' }),
- manifest: manifest({}),
- readme: null,
- } as unknown as PluginMarketDetail);
- installMock.mockRejectedValueOnce(
- Object.assign(new Error('precondition'), {
- message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] gone',
- }),
- );
-
- startUpdateAllBatch([marketItem({ releaseId: '' })]);
- await waitForSettledBatch();
-
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('failed');
- });
-
- it('still fails the row on non-precondition install errors', async () => {
- stubDetail({ manifest: manifest({}), sourceType: 'server' });
- installMock.mockRejectedValueOnce(new Error('network down'));
-
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
-
- // 真失败仍然是失败:不能把所有错误都变成"再审一次"。
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('failed');
- });
-
- it('re-reviews instead of failing when a custom source swaps the manifest under the plain update path', async () => {
- // 自定义市场源:审阅基线含 network,目标包在此之上多出 fs。
- installedGhosts = [
- { manifest: manifest({ version: '1.0.0', network: { hosts: ['api.example.com'] } }) },
- ];
- stubDetail({
- manifest: manifest({ network: { hosts: ['api.example.com'] }, slots: ['fs'] }),
- sourceType: 'git-market',
- });
- startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);
- await waitForSettledBatch();
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');
-
- // 批准时外部把已装换成同样带 fs 的包 → 重算后已无扩权,走普通更新分支;
- // 但市场源又以同版本改了 manifest,Main 因 expectedManifest 不匹配拒绝。
- detailMock.mockImplementation(async () => {
- installedGhosts = [
- {
- manifest: manifest({
- version: '1.0.0',
- network: { hosts: ['api.example.com'] },
- slots: ['fs'],
- }),
- },
- ];
- return {
- ...marketItem({ sourceType: 'git-market' }),
- manifest: manifest({ network: { hosts: ['api.example.com'] }, slots: ['fs'] }),
- readme: null,
- } as unknown as PluginMarketDetail;
- });
- installMock.mockRejectedValueOnce(
- Object.assign(new Error('precondition'), {
- message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] manifest changed',
- }),
- );
-
- await approveUpdateExpansion('plugin-a');
-
- const row = getUpdateAllBatchState().rows?.[0];
- // 并发事实变化 → 回到重新审阅,不是终态失败(否则用户失去本项入口)。
- expect(row?.status).toBe('needs-confirm');
- expect(row?.errorText).toBeUndefined();
- });
-
- it('drops the stale detail when a same-release manifest swap rejects the approval', async () => {
- const reviewedManifest = manifest({ network: { hosts: ['api.example.com'] } });
- stubDetail({ manifest: reviewedManifest, sourceType: 'git-market' });
- startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);
- await waitForSettledBatch();
- expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({
- status: 'needs-confirm',
- expectedManifest: reviewedManifest,
- });
-
- // 竞态:detail() 返回的仍是审阅时那份(所以 renderer 侧判定审阅有效),
- // 但在 install 到达 Main 之前,自定义源在**同一 releaseId 下**换了 manifest,
- // Main 因 expectedManifest 对不上拒绝。此刻手里这份 detail 已经不对了。
- const swappedManifest = manifest({
- network: { hosts: ['api.example.com', 'evil.example.com'] },
- });
- installMock.mockRejectedValueOnce(
- Object.assign(new Error('precondition'), {
- message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] manifest changed',
- }),
- );
-
- await approveUpdateExpansion('plugin-a');
-
- const held = getUpdateAllBatchState().rows?.[0];
- // 旧差异与旧 manifest 必须丢弃并标记过期,否则下次批准会再提交同一份
- // 过期的 expectedManifest,循环失败。
- expect(held).toMatchObject({ status: 'needs-confirm', staleReview: true });
- expect(held?.permissionDiff).toBeUndefined();
- expect(held?.expectedManifest).toBeUndefined();
-
- // 再次批准:此时详情已能取到源上的新 manifest → 相对当前已装仍是扩权 →
- // 用**新** manifest 重新出确认内容。
- detailMock.mockResolvedValue({
- ...marketItem({ sourceType: 'git-market' }),
- manifest: swappedManifest,
- readme: null,
- } as unknown as PluginMarketDetail);
- await approveUpdateExpansion('plugin-a');
- const rereviewed = getUpdateAllBatchState().rows?.[0];
- expect(rereviewed).toMatchObject({ status: 'needs-confirm', staleReview: false });
- expect(rereviewed?.expectedManifest).toBe(swappedManifest);
-
- // 用户同意新差异 → 带新 manifest 装上,推进到完成,不再循环。
- await approveUpdateExpansion('plugin-a');
- expect(installMock).toHaveBeenLastCalledWith('plugin-a', {
- expectedReleaseId: 'release-2',
- expectedManifest: swappedManifest,
- allowPermissionExpansion: true,
- reviewedBaseline: expect.any(String),
- });
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
- });
-
- it('never treats a missing expectedManifest as a valid review for custom sources', async () => {
- const reviewed = manifest({ network: { hosts: ['api.example.com'] } });
- stubDetail({ manifest: reviewed, sourceType: 'git-market' });
- startUpdateAllBatch([marketItem({ sourceType: 'git-market' })]);
- await waitForSettledBatch();
-
- // 第一次批准被 Main 拒 → 行被清成 expectedManifest: undefined + staleReview。
- installMock.mockRejectedValueOnce(
- Object.assign(new Error('precondition'), {
- message: 'Error invoking remote method: Error: [PRECONDITION_FAILED] manifest changed',
- }),
- );
- await approveUpdateExpansion('plugin-a');
- expect(getUpdateAllBatchState().rows?.[0]?.expectedManifest).toBeUndefined();
-
- // 重新审阅 → 再批准,全程必须带上当前 expectedManifest。缺失被短路成
- // 「审阅仍有效」的话,这里会不带该字段安装,主进程直接 INVALID_PARAMS。
- await approveUpdateExpansion('plugin-a');
- await approveUpdateExpansion('plugin-a');
-
- expect(installMock).toHaveBeenLastCalledWith(
+ expect(getUpdateAllBatchState().rows?.map((row) => row.pluginId)).toEqual([
'plugin-a',
- expect.objectContaining({ expectedManifest: reviewed }),
- );
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
- });
-
- it('voids an approval whose detail returned after the account switched', async () => {
- stubDetail({
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- sourceType: 'server',
- });
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
-
- // 详情请求停在半空,期间切到账号 B(页面的作废 effect 还没跑,代际未变)。
- let releaseDetail: (() => void) | undefined;
- detailMock.mockImplementation(
- () =>
- new Promise((resolve) => {
- releaseDetail = () => {
- setDataOwnerGeneration('owner-b');
- resolve({
- ...marketItem({}),
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- readme: null,
- } as unknown as PluginMarketDetail);
- };
- }),
- );
- const approval = approveUpdateExpansion('plugin-a');
- await vi.waitFor(() => expect(releaseDetail).toBeDefined());
-
- // 账号 B 装着同 id 的插件:旧批准绝不能读它的 manifest、更不能装它。
- installedGhosts = [{ manifest: manifest({ version: '2.0.0' }) }];
- releaseDetail?.();
- await approval;
+ ]);
- expect(installMock).not.toHaveBeenCalled();
- expect(getUpdateAllBatchState().rows).toBeNull();
+ resolveRefresh?.();
+ await waitForFinishedBatch();
+ expect(toast.success).toHaveBeenCalledTimes(1);
});
- it('does not make a new generation approval wait behind the previous one', async () => {
- const expanding = manifest({ network: { hosts: ['api.example.com'] } });
- detailMock.mockImplementation(async (pluginId) =>
- ({
- ...marketItem({ pluginId, ghostId: pluginId === 'plugin-a' ? 'ghost-a' : 'ghost-b' }),
- manifest: expanding,
- readme: null,
- }) as unknown as PluginMarketDetail,
- );
- installedGhosts = [{ manifest: manifest({ version: '1.0.0' }) }];
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
-
- // 账号 A 的批准卡在安装里(永不 resolve)。
- const stuck: Array<() => void> = [];
- installMock.mockImplementation(
+ it('reconciles a pending row removed while an earlier row is installing', async () => {
+ installedGhosts.push({ manifest: manifest({ id: 'ghost-b', version: '2.0.0' }) });
+ let resolveInstall: (() => void) | undefined;
+ installMock.mockImplementationOnce(
() =>
new Promise((resolve) => {
- stuck.push(() => resolve({ ghost: { manifest: expanding } } as never));
+ resolveInstall = () => resolve({ ghost: { manifest: manifest() } });
}),
);
- const oldApproval = approveUpdateExpansion('plugin-a');
- await vi.waitFor(() => expect(stuck.length).toBe(1));
-
- // 切账号 → 新批次(新代际)。
- setDataOwnerGeneration('owner-b');
- reconcileUpdateAllBatch();
- installedGhosts = [{ manifest: manifest({ id: 'ghost-b', version: '1.0.0' }) }];
- startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);
- await waitForSettledBatch();
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');
-
- // 新代际的批准不该排在账号 A 那个仍然卡着的安装后面:它必须立刻开跑。
- const newApproval = approveUpdateExpansion('plugin-b');
- await vi.waitFor(() => expect(stuck.length).toBe(2));
-
- stuck[1]?.();
- await newApproval;
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
-
- // 收尾:放行旧代际那个安装,它轮到时因代际失效不会改写当前批次。
- stuck[0]?.();
- await oldApproval;
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
- });
-
- it('never rebinds a queued approval onto the batch that replaced it', async () => {
- const expanding = manifest({ network: { hosts: ['api.example.com'] } });
detailMock.mockImplementation(async (pluginId) =>
- ({
- ...marketItem({ pluginId, ghostId: pluginId === 'plugin-a' ? 'ghost-a' : 'ghost-b' }),
- manifest: expanding,
- readme: null,
- }) as unknown as PluginMarketDetail,
+ pluginId === 'plugin-a'
+ ? detail()
+ : detail({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),
);
- installedGhosts = [
- { manifest: manifest({ version: '1.0.0' }) },
- { manifest: manifest({ id: 'ghost-b', version: '1.0.0' }) },
- ];
+
startUpdateAllBatch([
- marketItem({}),
+ marketItem(),
marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),
]);
- await waitForSettledBatch();
-
- // 首项安装卡住,第二项的批准排在队列里等。
- const gate: Array<() => void> = [];
- installMock.mockImplementation(
- () =>
- new Promise((resolve) => {
- gate.push(() => resolve({ ghost: { manifest: expanding } } as never));
- }),
- );
- const first = approveUpdateExpansion('plugin-a');
- const queued = approveUpdateExpansion('plugin-b');
- await vi.waitFor(() => expect(gate.length).toBe(1));
-
- // 安装进行中切换账号 + 新账号启动自己的批次(同样含 plugin-b 待确认项)。
- setDataOwnerGeneration('owner-b');
- reconcileUpdateAllBatch();
- installedGhosts = [{ manifest: manifest({ id: 'ghost-b', version: '1.0.0' }) }];
- startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);
- await waitForSettledBatch();
- const newBatchRow = getUpdateAllBatchState().rows?.[0];
- expect(newBatchRow).toMatchObject({ pluginId: 'plugin-b', status: 'needs-confirm' });
-
- const installsBeforeDrain = installMock.mock.calls.length;
- // 旧队列项这时才轮到执行:它属于上一个代际/账号,必须整体作废,
- // 绝不能改绑到新批次里同 pluginId 的待确认项上并直接安装。
- gate[0]?.();
- await first;
- await queued;
-
- expect(installMock.mock.calls.length).toBe(installsBeforeDrain);
- // 新批次的待确认项原封不动,仍等用户在新账号下自己批准。
- expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({
- pluginId: 'plugin-b',
- status: 'needs-confirm',
- });
- });
-
- it('never lets a superseded runner write into the batch that replaced it', async () => {
- // 账号 A 的 detail() 停在半空。
- let releaseDetail: ((value: PluginMarketDetail) => void) | undefined;
- detailMock.mockImplementation(
- () =>
- new Promise<PluginMarketDetail>((resolve) => {
- releaseDetail = resolve;
- }),
- );
- startUpdateAllBatch([marketItem({})]);
- await vi.waitFor(() => expect(releaseDetail).toBeDefined());
-
- // 切到账号 B 并启动 B 自己的批次(旧批次已被作废 + 代际接管)。
- setDataOwnerGeneration('owner-b');
+ await vi.waitFor(() => expect(resolveInstall).toBeDefined());
+ installedGhosts = [{ manifest: manifest({ version: '1.0.0' }) }];
reconcileUpdateAllBatch();
- expect(getUpdateAllBatchState().rows).toBeNull();
- detailMock.mockResolvedValue({
- ...marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' }),
- manifest: manifest({ id: 'ghost-b' }),
- readme: null,
- } as unknown as PluginMarketDetail);
- installedGhosts = [{ manifest: manifest({ id: 'ghost-b', version: '1.0.0' }) }];
- startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);
-
- // A 的请求这时才失败返回:不得把失败写进 B、不得消费 B 的 pending 行、
- // 不得提前清掉 B 的 running。
- releaseDetail?.(undefined as unknown as PluginMarketDetail);
- await waitForSettledBatch();
-
- const rows = getUpdateAllBatchState().rows ?? [];
- expect(rows.map((row) => row.pluginId)).toEqual(['plugin-b']);
- expect(rows[0]?.status).not.toBe('failed');
- expect(installMock).toHaveBeenCalledWith('plugin-b', expect.objectContaining({}));
- });
-
- it('settles without reinstalling once the target release is actually on record', async () => {
- stubDetail({
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- sourceType: 'server',
- });
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
-
- // 目标 release 已落账:detail 报 installed,批准直接收束不重复下载。
- installedGhosts = [{ manifest: manifest({ version: '1.1.0' }) }];
- detailMock.mockResolvedValue({
- ...marketItem({ installState: 'installed' }),
- manifest: manifest({ version: '1.1.0', network: { hosts: ['api.example.com'] } }),
- readme: null,
- } as unknown as PluginMarketDetail);
-
- // 已落账的早退分支同样要走统一收尾:刷新市场快照 + 完成 toast,
- // 不留旧快照和悬空的未完成提示。
- const refreshMarket = vi.fn(async () => undefined);
- setUpdateAllBatchHooks({ refreshMarket });
-
- await approveUpdateExpansion('plugin-a');
- expect(installMock).not.toHaveBeenCalled();
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');
- expect(refreshMarket).toHaveBeenCalledTimes(1);
- expect(toast.success).toHaveBeenCalledWith('settings.ghosts.updateAll.doneToast');
- });
-
- it('holds running until the post-batch refresh settles so no second batch overlaps', async () => {
- let releaseRefresh: (() => void) | undefined;
- setUpdateAllBatchHooks({
- refreshMarket: () =>
- new Promise<void>((resolve) => {
- releaseRefresh = resolve;
- }),
- });
- stubDetail({ manifest: manifest({}), sourceType: 'server' });
-
- startUpdateAllBatch([marketItem({})]);
- await vi.waitFor(() => expect(releaseRefresh).toBeDefined());
-
- // 刷新还没回来:running 必须仍为 true,旧 runner 的收尾不能让第二批插进来。
- expect(getUpdateAllBatchState().running).toBe(true);
- startUpdateAllBatch([marketItem({ pluginId: 'plugin-b', ghostId: 'ghost-b' })]);
- expect(getUpdateAllBatchState().rows?.map((row) => row.pluginId)).toEqual(['plugin-a']);
-
- releaseRefresh?.();
- await vi.waitFor(() => expect(getUpdateAllBatchState().running).toBe(false));
- });
-
- it('keeps pending confirmations readable after the page unsubscribes (unmount)', async () => {
- stubDetail({
- manifest: manifest({ network: { hosts: ['api.example.com'] } }),
- sourceType: 'server',
- });
-
- startUpdateAllBatch([marketItem({})]);
- await waitForSettledBatch();
+ expect(getUpdateAllBatchState().rows?.[1]?.status).toBe('skipped');
- // 模块级状态与页面订阅无关:卸载(无订阅者)后快照仍保留待确认行,
- // 重新进页可以直接恢复批准/跳过入口。
- expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('needs-confirm');
+ resolveInstall?.();
+ await waitForFinishedBatch();
+ expect(installMock).toHaveBeenCalledTimes(1);
});
});
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts
index a213dea302..f32a67eae2 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllModel.test.ts
@@ -12,7 +12,6 @@ import {
buildUpdateAllRows,
ignoredRoundStorageKey,
isBatchFinished,
- isBatchSettled,
updateRoundKey,
updateRow,
} from '../lib/updateAllModel';
@@ -80,11 +79,9 @@ describe('batch transitions', () => {
expect(next[1].status).toBe('pending');
});
- it('settles when nothing auto-advances, finishes only after confirms resolve', () => {
+ it('finishes only after every serial row reaches a terminal state', () => {
let next = updateRow(rows, 'p1', { status: 'done' });
- next = updateRow(next, 'p2', { status: 'needs-confirm' });
- // needs-confirm 不再自动推进,但用户还没处理 → settled 而未 finished。
- expect(isBatchSettled(next)).toBe(true);
+ next = updateRow(next, 'p2', { status: 'installing' });
expect(isBatchFinished(next)).toBe(false);
next = updateRow(next, 'p2', { status: 'skipped' });
diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
index 7cceab1454..4bd8fb96ad 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts
@@ -1,32 +1,20 @@
/**
* Window-level controller for the "update all plugins" batch flow.
*
- * Inputs: the market update snapshot plus user approve/skip actions.
- * Outputs: a subscribable batch snapshot for the Plugin page and the
- * serial install IPC calls.
- *
- * 为什么在组件外:批次可以在用户关掉弹窗、离开 /plugins 后继续跑
- * (「后台继续」语义),待确认的扩权项也必须在回到插件页后仍然保留
- * 批准/跳过入口——状态生命周期必须长于页面组件,所以照
- * useInstalledGhosts 的先例做成模块级单例 store。真实包复核返回期间若
- * 已装权限基线漂移,保留目标 release 并退回可恢复的重新审阅状态。
+ * The controller owns only batch progress and serial execution. Permission
+ * review belongs to the Main-owned real-package transaction; no catalog
+ * manifest or parallel approval state is retained here.
* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
*/
import { i18n } from '@/i18n';
import { toast } from '@/lib/toast';
-import { extractIpcError } from '@/utils/ipcError';
import { readInstalledGhostsSnapshot } from '@/cindy-brain/useInstalledGhosts';
import {
getDataOwnerGeneration,
isDataOwnerGenerationCurrent,
type DataOwnerGeneration,
} from '@/contexts/dataOwnerGeneration';
-import {
- diffGhostPermissionItems,
- ghostPermissionBaselineKey,
- type GhostManifest,
-} from '../../../../shared/ghost';
import type { PluginMarketItem } from '../../../../shared/pluginMarket';
import { pluginMarketErrorKey } from './pluginMarketErrorKey';
import {
@@ -38,131 +26,49 @@ import {
} from './updateAllModel';
export interface UpdateAllBatchState {
- /** null = 从未启动过批次;数组引用随每次行迁移变化(快照语义)。 */
rows: UpdateAllRow[] | null;
running: boolean;
}
interface UpdateAllBatchHooks {
- /** 批次推进后的市场快照刷新;页面卸载期间缺席,重新进页会全量刷新。 */
+ /** 页面存在时刷新市场;页面卸载期间缺席,重新进入会全量刷新。 */
refreshMarket?: () => Promise<void>;
}
let state: UpdateAllBatchState = { rows: null, running: false };
let finishToastShown = false;
let hooks: UpdateAllBatchHooks = {};
-/** 批次启动时的账号世代:身份切换后旧批次整体作废,绝不跨账号安装。 */
let batchOwner: DataOwnerGeneration | null = null;
-/**
- * 批次代际。每次启动新批次或作废旧批次都自增,异步流程在启动时捕获它,
- * 之后每个写入点都先核对——**光靠账号世代不够**:同一账号内旧批次被作废、
- * 新批次接管时账号没变,旧 runner 的迟到写入照样会污染新批次(把上一批的
- * 失败写进新批次、继续消费新批次的 pending 行、提前清掉新批次的 running)。
- * 代际失效的 runner 只能停下,不得改写、不得收尾、不得触发任何副作用。
- */
let batchGeneration = 0;
-/**
- * 在途批准的串行队列,**按代际隔离**。
- *
- * 同一代际内必须排队而非并发:并发安装同一批次的多个 release 会互相踩市场
- * 刷新与已装清单快照,收尾也会被任一单项提前释放。
- *
- * 但队列不能全局共用一条链:账号/模式切换后新批次的批准会排在旧代际那个
- * 慢 install() 后面干等——代际校验只能在轮到执行时把旧项丢掉,解不掉前面的
- * 等待。各代际各排各的,新身份点批准立即开始;旧代际的项轮到时照样因代际
- * 失效而不执行安装。条目在该代际无在途时回收(见 releaseApproval)。
- */
-const approvalQueueByGeneration = new Map<number, Promise<unknown>>();
-/**
- * 在途批准计数**按代际分桶**。全局单计数不够:旧代际的在途项会把新批次的
- * 收尾计数拖住(减到 0 时代际已不匹配、跳过收尾,新批次就永远不释放 running)。
- * 每个代际只对自己的桶负责。
- */
-const inflightByGeneration = new Map<number, number>();
const listeners = new Set<() => void>();
-function retainApproval(generation: number): void {
- inflightByGeneration.set(generation, (inflightByGeneration.get(generation) ?? 0) + 1);
-}
-
-/** 归还一个在途名额;返回该代际是否已无在途(= 轮到收尾)。 */
-function releaseApproval(generation: number): boolean {
- const next = (inflightByGeneration.get(generation) ?? 1) - 1;
- if (next <= 0) {
- inflightByGeneration.delete(generation);
- // 该代际不再有批准在途,它的队列链也没人接了——一并清掉,免得
- // 长会话里每换一次账号/批次都留下一条永不回收的 promise 链。
- approvalQueueByGeneration.delete(generation);
- return true;
- }
- inflightByGeneration.set(generation, next);
- return false;
-}
-
function emit(next: UpdateAllBatchState): void {
state = next;
listeners.forEach((listener) => listener());
}
-/** 开启新代际(旧代际的异步流程随即失效),返回新代际号。 */
function beginGeneration(): number {
batchGeneration += 1;
return batchGeneration;
}
-/** 该代际是否仍是当前批次(代际未被接管 + 账号未切换)。 */
+function batchOwnerCurrent(): boolean {
+ return batchOwner !== null && isDataOwnerGenerationCurrent(batchOwner);
+}
+
function isGenerationCurrent(generation: number): boolean {
- return (
- batchGeneration === generation &&
- batchOwner !== null &&
- isDataOwnerGenerationCurrent(batchOwner)
- );
+ return generation === batchGeneration && batchOwnerCurrent();
}
function patchRow(generation: number, pluginId: string, patch: Partial<UpdateAllRow>): void {
- // 代际已失效(批次被作废或被新批次接管)时,迟到的行迁移直接丢弃。
if (!isGenerationCurrent(generation) || state.rows === null) return;
emit({ ...state, rows: updateRow(state.rows, pluginId, patch) });
}
-function batchOwnerCurrent(): boolean {
- return batchOwner !== null && isDataOwnerGenerationCurrent(batchOwner);
-}
-
-/**
- * 把一行退回「待重新审阅」——前置条件变化的统一收敛(runner 与批准共用)。
- *
- * 清掉旧的 permissionDiff 并打 staleReview:弹窗据此显示「权限差异已过期 /
- * 重新审阅」,用户点一下就走 approve 按当前事实重取详情、重算差异,
- * 无扩权直接装、仍扩权则逐项审。可恢复,不必关弹窗重启整批。
- */
-function holdRowForReReview(
- generation: number,
- pluginId: string,
- patch: Partial<UpdateAllRow> = {},
-): void {
- const releaseId = patch.releaseId ?? state.rows?.find((r) => r.pluginId === pluginId)?.releaseId;
- if (!releaseId) {
- // 没有目标 release 就没有可重审的对象:approveUpdateExpansion 的入口守卫
- // 要求 row.releaseId 存在,少了它这行会变成点「重新审阅」也没反应的死行。
- // 与其静默卡住,不如如实落失败(errorText 留空 = 弹窗显示通用失败文案)。
- patchRow(generation, pluginId, { status: 'failed' });
- return;
- }
- patchRow(generation, pluginId, {
- status: 'needs-confirm',
- staleReview: true,
- permissionDiff: undefined,
- ...patch,
- releaseId,
- });
-}
-
-/** 账号/模式切换后作废整个批次(旧代际的 runner 在下一个检查点自行退出)。 */
function voidStaleBatch(): void {
batchOwner = null;
- beginGeneration(); // 让在飞的 runner / approve 立即失效。
- finishToastShown = true; // 作废批次不再补发完成 toast。
+ beginGeneration();
+ finishToastShown = true;
emit({ rows: null, running: false });
}
@@ -177,7 +83,6 @@ export function getUpdateAllBatchState(): UpdateAllBatchState {
return state;
}
-/** 页面挂载期注册环境回调;返回的清理函数在卸载时注销。 */
export function setUpdateAllBatchHooks(next: UpdateAllBatchHooks): () => void {
hooks = next;
return () => {
@@ -185,25 +90,16 @@ export function setUpdateAllBatchHooks(next: UpdateAllBatchHooks): () => void {
};
}
-function installedManifestOf(ghostId: string): GhostManifest | null {
- return (
- readInstalledGhostsSnapshot().find((ghost) => ghost.manifest.id === ghostId)?.manifest ?? null
- );
-}
-
async function refreshMarketIfMounted(): Promise<void> {
try {
await hooks.refreshMarket?.();
} catch {
- // 快照刷新失败不影响批次结果;下次进页会重新拉取。
+ // 批次结果不依赖刷新成功;重新进入页面会再取完整快照。
}
}
function maybeFinishToast(): void {
const rows = state.rows;
- // 还有批准在途时不报完成:它们的行此刻是 installing,提前报会把"没装完"
- // 说成"已完成"。最后一个在途批准的收尾会再来一次。
- if ((inflightByGeneration.get(batchGeneration) ?? 0) > 0) return;
if (!rows || rows.length === 0 || !isBatchFinished(rows) || finishToastShown) return;
finishToastShown = true;
const summary = batchSummary(rows);
@@ -215,7 +111,6 @@ function maybeFinishToast(): void {
);
}
-/** 启动新批次(运行中调用是 no-op;是否复用未完成批次由页面判断)。 */
export function startUpdateAllBatch(marketUpdates: readonly PluginMarketItem[]): void {
if (state.running) return;
const installedVersionById = new Map(
@@ -228,89 +123,64 @@ export function startUpdateAllBatch(marketUpdates: readonly PluginMarketItem[]):
void runQueue(generation);
}
-/**
- * 批量 runner:串行走「取详情 → 权限 diff → 无扩权直接装 / 有扩权停待确认」。
- * 全程以启动时捕获的 `generation` 为准:任一 await 之后代际若已失效
- * (批次被作废或被新批次接管),立即停手——不写状态、不消费队列、不收尾。
- */
+/** 串行执行,每个 install() 自己在 Main 中下载、确认并提交同一真实包。 */
async function runQueue(generation: number): Promise<void> {
if (state.running || !isGenerationCurrent(generation)) return;
emit({ ...state, running: true });
try {
for (;;) {
- if (batchGeneration !== generation) return; // 已被新批次接管:静默让位。
+ if (generation !== batchGeneration) return;
if (!batchOwnerCurrent()) {
voidStaleBatch();
return;
}
- const next = (state.rows ?? []).find((row) => row.status === 'pending');
+ const next = state.rows?.find((row) => row.status === 'pending');
if (!next) break;
patchRow(generation, next.pluginId, { status: 'installing' });
- // detail 提到 try 外:install 抛前置条件失败时,catch 要靠它把目标 release
- // 写回待重审行——runApprovalBody 的入口守卫要求 row.releaseId 存在,
- // 缺了它用户点「重新审阅」会直接 return,该项在本批次里静默卡死。
- let detail: Awaited<ReturnType<typeof window.electronAPI.pluginMarket.detail>> | null = null;
try {
- detail = await window.electronAPI.pluginMarket.detail(next.pluginId);
- // detail 往返期间可能切换账号或换批次:install 会以当前账号执行,
- // 旧批次绝不能把上一轮的更新落到新账号/新批次上。
- if (batchGeneration !== generation) return;
+ const detail = await window.electronAPI.pluginMarket.detail(next.pluginId);
+ if (generation !== batchGeneration) return;
if (!batchOwnerCurrent()) {
voidStaleBatch();
return;
}
if (detail.installState === 'installed') {
- // 目标 release 已经落账——典型是用户在批次启动前后用卡片上的单项更新
- // 装了同一个 release,而本批次拿的是那之前的市场快照。直接收束,
- // 不重复下载安装同一份包。
patchRow(generation, next.pluginId, { status: 'done' });
continue;
}
- const installedManifest = installedManifestOf(next.ghostId);
- if (!installedManifest) {
- // 批量期间插件已被卸载:绝不拿市场 manifest 兜底继续安装
- // (那会把用户刚卸载的插件重新装回来),该行按跳过收束。
+ if (detail.installState !== 'update-available') {
patchRow(generation, next.pluginId, { status: 'skipped' });
continue;
}
- const diff = diffGhostPermissionItems(installedManifest, detail.manifest);
- if (diff.added.length > 0) {
- // 扩权不自动放行:停在待确认,由用户在弹窗里逐项同意或跳过。
- patchRow(generation, next.pluginId, {
- status: 'needs-confirm',
- releaseId: detail.releaseId,
- permissionDiff: diff,
- // 审阅基线绑定权限指纹而非版本号:同版本换 manifest 也能识别。
- reviewedBaseline: ghostPermissionBaselineKey(installedManifest),
- expectedManifest: detail.manifest,
- });
+ const installed = readInstalledGhostsSnapshot().find(
+ (ghost) => ghost.manifest.id === next.ghostId,
+ );
+ if (!installed) {
+ patchRow(generation, next.pluginId, { status: 'skipped' });
continue;
}
+ patchRow(generation, next.pluginId, {
+ fromVersion: installed.manifest.version,
+ toVersion: detail.version,
+ });
const result = await window.electronAPI.pluginMarket.install(next.pluginId, {
expectedReleaseId: detail.releaseId,
- expectedManifest: detail.manifest,
+ allowSourceReplacement: false,
});
- if (result.cancelled) {
- patchRow(generation, next.pluginId, { status: 'skipped' });
- continue;
+ if (generation !== batchGeneration) return;
+ if (!batchOwnerCurrent()) {
+ voidStaleBatch();
+ return;
}
- patchRow(generation, next.pluginId, { status: 'done' });
+ patchRow(generation, next.pluginId, {
+ status: result.cancelled ? 'skipped' : 'done',
+ });
} catch (error) {
- if (batchGeneration !== generation) return;
- // 前置条件变化(基线复核否决 / release 变了 / 自定义源换了 manifest)
- // 不是「更新失败」而是「事实已变,请重新审阅」。落成终态 failed 会让
- // 这一项彻底没有入口,用户只能关掉弹窗重启整批。改为可恢复的待重审:
- // 弹窗显示「权限差异已过期 / 重新审阅」,点一下就按当前事实重算。
- // detail 为 null 说明连详情都没取到,没有可写回的 release,此时重审也
- // 无从下手,按失败处理更诚实。
- if (extractIpcError(error)?.code === 'PRECONDITION_FAILED' && detail !== null) {
- holdRowForReReview(generation, next.pluginId, {
- releaseId: detail.releaseId,
- toVersion: detail.version,
- });
- continue;
+ if (generation !== batchGeneration) return;
+ if (!batchOwnerCurrent()) {
+ voidStaleBatch();
+ return;
}
- // 失败也只写回自己的批次:代际失效时这条错误属于已作废的批次。
patchRow(generation, next.pluginId, {
status: 'failed',
errorText: i18n.t(pluginMarketErrorKey(error)),
@@ -322,249 +192,19 @@ async function runQueue(generation: number): Promise<void> {
}
}
-/**
- * 批次收尾(所有返回路径共用):刷新市场快照 → 放开 running → 补完成 toast。
- *
- * running 必须**撑到刷新结束**才落下:刷新期间市场快照还是旧的,若此时放开
- * running,页面拿旧快照就能启动第二批,而本 runner 的收尾还会写到新批次上。
- * 代际失效时整个收尾跳过——旧 runner 不得清掉当前批次的 running、也不得
- * 触发当前批次的完成提示。
- */
async function settleBatchTail(generation: number): Promise<void> {
- if (batchGeneration !== generation) return;
+ if (generation !== batchGeneration) return;
await refreshMarketIfMounted();
- if (batchGeneration !== generation) return;
- if (state.running) emit({ ...state, running: false });
- maybeFinishToast();
-}
-
-/**
- * 用户在弹窗里同意某个扩权项后继续安装。
- *
- * 多个待确认项连点时**串行执行**:后一个排在前一个之后,不并发装。
- * running 由在途计数统一管理——第一个入队时点亮,最后一个结束时才收尾释放,
- * 中途任何单项都不许提前把闸门放开(否则页面拿旧快照可重复启动)。
- */
-export function approveUpdateExpansion(pluginId: string): Promise<void> {
- // **入队时**捕获代际与账号归属:用户点的是"此刻这个批次里的这一项"。
- // 若等排到自己时才读当前批次,账号切换 / 新批次接管后,这次旧点击就会
- // 重新绑定到新批次里同 pluginId 的待确认项上——等于未经批准放行新账号
- // 或新 release 的扩权。代际不符一律丢弃,绝不改绑。
- const generation = batchGeneration;
- const owner = batchOwner;
- retainApproval(generation);
- // 队列**按代际隔离**:全局单链下,账号切换后新批次的批准会排在旧代际那个
- // 慢 install() 后面干等——代际校验只能在轮到执行时把旧项丢掉,解不掉前面的
- // 等待。各代际各排各的,新账号点批准立即开始;旧代际的项轮到时仍会因代际
- // 失效而不执行安装。
- const previous = approvalQueueByGeneration.get(generation) ?? Promise.resolve();
- const run = previous.then(() => runApproval(pluginId, generation, owner));
- // 队列本身吞掉失败,后续批准不因前一个抛错而卡死;错误仍由 runApproval
- // 内部落到对应行的 failed 状态。
- approvalQueueByGeneration.set(generation, run.catch(() => undefined));
- return run;
-}
-
-async function runApproval(
- pluginId: string,
- generation: number,
- owner: DataOwnerGeneration | null,
-): Promise<void> {
- try {
- // 排队期间批次被作废/接管,或账号已切换 → 这次批准属于过去,直接作废。
- if (batchGeneration !== generation) return;
- if (owner === null || !isDataOwnerGenerationCurrent(owner)) {
- voidStaleBatch();
- return;
- }
- await runApprovalBody(pluginId, generation);
- } finally {
- // 只有**本代际**最后一个在途批准才收尾:刷新市场快照 → 释放 running →
- // 补完成提示。早于这一刻释放,后续排队中的批准就会在闸门已开的状态下继续装。
- // settleBatchTail 自己再校验一次代际,失效时不碰当前批次。
- if (releaseApproval(generation)) await settleBatchTail(generation);
- }
-}
-
-async function runApprovalBody(pluginId: string, generation: number): Promise<void> {
- if (!batchOwnerCurrent()) {
- voidStaleBatch();
- return;
- }
- if (batchGeneration !== generation) return;
- const row = state.rows?.find((candidate) => candidate.pluginId === pluginId);
- // 排在前面的批准可能已经把本行推进过(重复点同一项),只处理仍待确认的。
- if (!row || row.status !== 'needs-confirm' || !row.releaseId) return;
- if (installedManifestOf(row.ghostId) === null) {
- // 待确认期间插件被卸载:同意也不重装,按跳过收束。
- patchRow(generation, pluginId, { status: 'skipped' });
- return;
- }
- // 批准也是批次在推进:running 从这里一直撑到**最后一个**在途批准收尾结束,
- // 期间页面拿的是旧的 update-available 快照,不能让它启动第二批重复安装。
- patchRow(generation, pluginId, { status: 'installing' });
- if (!state.running) emit({ ...state, running: true });
- try {
- // 一律重取详情。它同时给出三件事,缺一不可:
- // 1. installState —— **目标 release 是否真的落账**的权威判据。main 侧
- // 只有 record.releaseId === 目标 release 且所有权归本插件时才报
- // 'installed'(plugin-market/service.ts),所以「从文件装了同版本
- // 但不同 release」不会被误判成完成;版本号比对做不到这点。
- // 2. 最新 releaseId / manifest —— 并发防护与非 server 源的 reviewed manifest。
- // 3. 当前 manifest —— 与已装 manifest 重算权限差异。
- const detail = await window.electronAPI.pluginMarket.detail(pluginId);
- // detail 往返期间批次可能已被作废/接管:此后一律不再写状态、不再安装。
- // 与 runQueue 同一套**双重**校验:代际管「同账号内换批次」,owner 管
- // 「账号刚切走但页面的作废 effect 还没跑」那个窗口——只看代际的话,
- // 这段时间里旧批准会读到新账号的已装 manifest 并安装新账号的同 id 插件。
- if (batchGeneration !== generation) return;
- if (!batchOwnerCurrent()) {
- voidStaleBatch();
- return;
- }
- // **detail 之后重读已装 manifest**:这段往返里「从文件更新」等路径可能整体
- // 换掉它,拿 await 之前的快照判断 = 拿过期事实做安全决策。
- const installed = installedManifestOf(row.ghostId);
- if (installed === null) {
- patchRow(generation, pluginId, { status: 'skipped' });
- return;
- }
- if (detail.installState === 'installed') {
- // 目标 release 已由别的路径装上:直接收束,不重复下载安装。
- // (return 后仍走 finally 的统一收尾——刷新市场快照 + 完成 toast。)
- patchRow(generation, pluginId, { status: 'done', fromVersion: installed.version });
- return;
- }
- /** 相对**当前**事实回到逐项审阅(不是终态失败:用户还能重新决定)。 */
- const holdForReReview = (): void => {
- patchRow(generation, pluginId, {
- status: 'needs-confirm',
- fromVersion: installed.version,
- toVersion: detail.version,
- releaseId: detail.releaseId,
- permissionDiff: diffGhostPermissionItems(installed, detail.manifest),
- staleReview: false,
- reviewedBaseline: ghostPermissionBaselineKey(installed),
- expectedManifest: detail.manifest,
- });
- };
- // 用户审阅的是「审阅当时的已装权限面 → 那一刻的目标 release」。三个前提
- // 任一变了,那份 diff 与它换来的 allowPermissionExpansion 就不再对应现实:
- // - staleReview:reconcile 已发现基线被换掉;
- // - 权限指纹变化(以刚重读的 installed 为准):ghosts.update() 允许**同版本
- // 整体替换 manifest**,同版本换入更宽的声明时版本比较完全看不出来;
- // - 目标 release 变化:市场在等待期间发了新版,审的不是这一版。
- // - 目标 manifest 变化:自定义市场源可以在**同一 releaseId 下**改 manifest,
- // 只比 releaseId 看不出来。
- // 所有来源都必须留有 expectedManifest 且与当前详情逐份一致才算有效:
- // 缺失不能短路成「有效」——那样下一次批准会不带 expectedManifest 去装,
- // 主进程对这类来源直接 INVALID_PARAMS,行落成 failed(前一轮把被拒的行
- // 清成 expectedManifest: undefined,正好会踩中)。
- const manifestStillMatches =
- row.expectedManifest !== undefined &&
- JSON.stringify(row.expectedManifest) === JSON.stringify(detail.manifest);
- const reviewStillValid =
- row.staleReview !== true &&
- ghostPermissionBaselineKey(installed) === row.reviewedBaseline &&
- detail.releaseId === row.releaseId &&
- manifestStillMatches;
- /**
- * 安装并接住「前置条件失败」。Main 的 PRECONDITION_FAILED 覆盖一组
- * **并发事实变化**:安装锁内的基线复核否决、release 变了、自定义市场源
- * 在 detail() 之后以同版本改了 manifest(expectedManifest 对不上)。
- * 这些都是「事实已变,请重新审阅」而不是「更新失败」——终态 failed 会让
- * 用户彻底失去这一项的入口,只能重启整批。所以一律回到 needs-confirm。
- * 返回 true = 真的装上了;false = 已按重审/让位处理完,调用方直接收手。
- */
- const installOrHoldForReReview = async (
- options: Parameters<typeof window.electronAPI.pluginMarket.install>[1],
- ): Promise<boolean> => {
- try {
- const result = await window.electronAPI.pluginMarket.install(pluginId, options);
- if (result.cancelled) {
- patchRow(generation, pluginId, { status: 'skipped' });
- return false;
- }
- return true;
- } catch (error) {
- if (batchGeneration !== generation) return false;
- if (extractIpcError(error)?.code === 'PRECONDITION_FAILED') {
- // 注意**不能**用 holdForReReview():那会拿手里这份 detail 重算差异并
- // 把 staleReview 置 false。可安装被拒恰恰说明这份 detail 已经不对了
- // (典型是自定义源在同 releaseId 下换了 manifest),照它生成确认内容,
- // 下次批准还会提交同一份过期的 expectedManifest,陷入循环失败。
- // 丢掉旧差异、标记过期,等下次批准重新取详情。
- holdRowForReReview(generation, pluginId, {
- releaseId: detail.releaseId,
- toVersion: detail.version,
- fromVersion: installed.version,
- expectedManifest: undefined,
- });
- return false;
- }
- throw error;
- }
- };
- if (reviewStillValid && row.expectedManifest !== undefined) {
- const didInstall = await installOrHoldForReReview({
- expectedReleaseId: row.releaseId,
- expectedManifest: row.expectedManifest,
- allowPermissionExpansion: true,
- // 审阅基线随批准回传:Main 在安装锁内用当时的已装 manifest 复核,
- // renderer 这边的检查挡不住 IPC 往返窗口内的替换。
- ...(row.reviewedBaseline !== undefined
- ? { reviewedBaseline: row.reviewedBaseline }
- : {}),
- });
- if (!didInstall) return;
- patchRow(generation, pluginId, { status: 'done' });
- } else if (diffGhostPermissionItems(installed, detail.manifest).added.length > 0) {
- // 相对新事实仍是扩权:回到逐项审阅,绝不静默放行未审过的权限。
- holdForReReview();
- return;
- } else {
- // 重算后已无扩权,按普通更新装。这条同样要接住并发变化:自定义市场源
- // 在 detail() 返回后以同版本改 manifest 时,Main 会因 expectedManifest
- // 不匹配拒绝,不能把它落成终态失败。
- const ok = await installOrHoldForReReview({
- expectedReleaseId: detail.releaseId,
- expectedManifest: detail.manifest,
- });
- if (!ok) return;
- patchRow(generation, pluginId, { status: 'done', fromVersion: installed.version });
- }
- } catch (error) {
- patchRow(generation, pluginId, {
- status: 'failed',
- errorText: i18n.t(pluginMarketErrorKey(error)),
- });
- }
- // 收尾统一由 runApproval 在**最后一个**在途批准结束时做(见那里的 finally):
- // 每项各自收尾会让前一项提前释放 running,后面排队的批准就在开着的闸门下跑。
-}
-
-/** 用户在弹窗里跳过某个扩权项。 */
-export function skipUpdateExpansion(pluginId: string): void {
+ if (generation !== batchGeneration) return;
if (!batchOwnerCurrent()) {
voidStaleBatch();
return;
}
- const row = state.rows?.find((candidate) => candidate.pluginId === pluginId);
- if (!row || row.status !== 'needs-confirm') return;
- patchRow(batchGeneration, pluginId, { status: 'skipped' });
+ if (state.running) emit({ ...state, running: false });
maybeFinishToast();
}
-/**
- * 与外部事实对账:账号切换 → 整批作废;待确认行的插件被卸载 → 跳过、
- * **目标 release 已落账**(市场快照报 'installed')→ 记为完成、
- * 权限基线被换掉(含同版本替换 manifest)→ 旧 permissionDiff 已不对应
- * 现实,清掉并标记待重审(真正的重算在 approve 时做,那里能取详情)。
- *
- * 完成判据只认市场快照的 installState,不认版本号:同版本不同 release
- * (从文件装入)在版本比对下无法区分,会把没装上目标 release 的行误收成完成。
- * 页面在已装清单、市场快照或身份变化时调用,并把当前市场快照传进来。
- */
+/** 页面外的已装/市场事实变化只用于收束尚未开始的行。 */
export function reconcileUpdateAllBatch(marketItems: readonly PluginMarketItem[] = []): void {
if (state.rows === null) return;
if (!batchOwnerCurrent()) {
@@ -574,47 +214,40 @@ export function reconcileUpdateAllBatch(marketItems: readonly PluginMarketItem[]
const installStateByPluginId = new Map(
marketItems.map((item) => [item.pluginId, item.installState]),
);
+ const installedById = new Map(
+ readInstalledGhostsSnapshot().map((ghost) => [ghost.manifest.id, ghost.manifest]),
+ );
let rows = state.rows;
let changed = false;
for (const row of state.rows) {
- if (row.status !== 'needs-confirm') continue;
- const installed = installedManifestOf(row.ghostId);
- if (installed === null) {
+ if (row.status !== 'pending') continue;
+ const installed = installedById.get(row.ghostId);
+ if (!installed) {
rows = updateRow(rows, row.pluginId, { status: 'skipped' });
changed = true;
} else if (installStateByPluginId.get(row.pluginId) === 'installed') {
- // 目标 release 已落账(main 侧 record.releaseId 对上):无需再装。
rows = updateRow(rows, row.pluginId, { status: 'done' });
changed = true;
- } else if (ghostPermissionBaselineKey(installed) !== row.reviewedBaseline) {
- // 权限基线变了(换版本,或同版本换入不同权限声明):旧审阅作废。
- rows = updateRow(rows, row.pluginId, {
- fromVersion: installed.version,
- permissionDiff: undefined,
- staleReview: true,
- });
+ } else if (
+ installStateByPluginId.has(row.pluginId) &&
+ installStateByPluginId.get(row.pluginId) !== 'update-available'
+ ) {
+ rows = updateRow(rows, row.pluginId, { status: 'skipped' });
changed = true;
} else if (installed.version !== row.fromVersion) {
- // 权限面没变、只是版本号变了:审阅结论仍然成立,同步展示用版本即可。
rows = updateRow(rows, row.pluginId, { fromVersion: installed.version });
changed = true;
}
}
- if (changed) {
- emit({ ...state, rows });
- maybeFinishToast();
- }
+ if (changed) emit({ ...state, rows });
}
-/** 仅测试用:清空模块级批次状态与回调注册。 */
+/** 仅测试用:清空模块级批次状态。 */
export function __resetUpdateAllBatchForTest(): void {
state = { rows: null, running: false };
finishToastShown = false;
hooks = {};
batchOwner = null;
- // 递增而非归零:上个用例遗留的在飞 runner 认的是旧代际,归零会让它复活。
beginGeneration();
- approvalQueueByGeneration.clear();
- inflightByGeneration.clear();
listeners.clear();
}
diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
index b3223e4737..e157604d8b 100644
--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts
@@ -7,18 +7,16 @@
* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
*/
-import type { GhostManifest, GhostPermissionDiff } from '../../../../shared/ghost';
import type { PluginMarketItem } from '../../../../shared/pluginMarket';
/**
- * 批量更新策略(设计定稿):权限无变化的自动串行完成;权限有扩张的
- * 停在 `needs-confirm`,由用户逐项同意或跳过,绝不自动放行扩权。
+ * 批量更新只维护执行进度。每个真实包的权限确认由统一安装事务完成,
+ * 本模型不再保存目录 manifest、批准基线或另一套待确认状态。
*/
export type UpdateAllRowStatus =
| 'pending'
| 'installing'
| 'done'
- | 'needs-confirm'
| 'skipped'
| 'failed';
@@ -29,26 +27,6 @@ export interface UpdateAllRow {
fromVersion: string;
toVersion: string;
status: UpdateAllRowStatus;
- /** 目标 release(needs-confirm 时由运行器填充,approve 用它做并发防护)。 */
- releaseId?: string;
- /** 扩权详情(status 为 needs-confirm 时由运行器填充)。 */
- permissionDiff?: GhostPermissionDiff;
- /**
- * 待确认期间插件被外部路径(从文件更新等)换掉了权限基线:审阅过的
- * 权限差异已不对应现实,弹窗提示"需要重新审阅",按钮点下去先重算再决定。
- */
- staleReview?: boolean;
- /**
- * 审阅所依据的**已装 manifest 权限指纹**(不是版本号)。
- * `ghosts.update()` 允许同版本整体替换 manifest,所以版本号不是可靠的
- * 审阅基线。Renderer 先检查、Main 在安装锁内复核。
- */
- reviewedBaseline?: string;
- /**
- * 审阅时取得的 manifest:主进程强制要求安装时传回同一份清单,
- * approve 必须原样带上,否则 INVALID_PARAMS。
- */
- expectedManifest?: GhostManifest;
/** status 为 failed 时的用户可读错误(已经过 i18n 映射)。 */
errorText?: string;
}
@@ -79,14 +57,9 @@ export function updateRow(
return rows.map((row) => (row.pluginId === pluginId ? { ...row, ...patch } : row));
}
-/** 批次是否已收敛:没有任何行还会自行推进(pending/installing)。 */
-export function isBatchSettled(rows: readonly UpdateAllRow[]): boolean {
- return rows.every((row) => row.status !== 'pending' && row.status !== 'installing');
-}
-
-/** 批次是否完全结束:连待确认的扩权行都已被用户处理。 */
+/** 批次是否完全结束。 */
export function isBatchFinished(rows: readonly UpdateAllRow[]): boolean {
- return isBatchSettled(rows) && rows.every((row) => row.status !== 'needs-confirm');
+ return rows.every((row) => row.status !== 'pending' && row.status !== 'installing');
}
/** 完成摘要:成功 / 跳过 / 失败计数,供收尾 toast 使用。 */
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index a80bd3a583..67deeefbd9 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3272,10 +3272,11 @@
"update": "Update from market",
"updateTo": "Update to v{{version}}",
"installed": "Installed",
- "conflict": "Unavailable",
- "conflictAria": "{{name}} has a plugin ID conflict",
- "conflictDescription": "This plugin ID is already in use, so this plugin can't be installed.",
+ "replace": "Replace",
+ "replaceAria": "Replace {{name}} with this marketplace version",
+ "replaceDescription": "A plugin with the same ID is already installed. Continuing will replace it with this marketplace version and keep its data.",
"unavailable": "The plugin market is temporarily unavailable. Installed plugins remain available.",
+ "customSourcesUnavailable": "These custom marketplaces are temporarily unavailable: {{names}}. Other marketplaces are unaffected.",
"authenticationRequired": "Sign in to Cindy to view the plugin market.",
"notConfigured": "The plugin market is not configured for this environment. Installed plugins remain available.",
"upgradeNotice": {
@@ -3697,15 +3698,8 @@
},
"updateAll": {
"title": "Update all · {{count}} plugins",
- "description": "Updates without permission changes finish automatically; permission expansions need your per-item approval.",
+ "description": "Regular updates finish automatically; verified packages that request new permissions need per-item approval.",
"versionRange": "v{{from}} → v{{to}}",
- "permissionChanged": "Permissions changed",
- "reviewOutdated": "Permission diff outdated",
- "rereview": "Review again",
- "reviewDiff": "Review & confirm",
- "collapseDiff": "Collapse",
- "approve": "Approve & update",
- "skip": "Skip",
"statusPending": "Queued",
"statusInstalling": "Updating…",
"statusDone": "Updated",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index f4eb484991..c642d2015e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3271,10 +3271,11 @@
"update": "マーケットから更新",
"updateTo": "v{{version}} に更新",
"installed": "インストール済み",
- "conflict": "利用不可",
- "conflictAria": "{{name}} にプラグイン ID の競合があります",
- "conflictDescription": "このプラグイン ID は使用中のため、インストールできません。",
+ "replace": "置き換え",
+ "replaceAria": "{{name}} をこのマーケット版で置き換える",
+ "replaceDescription": "同じ ID のプラグインがすでにインストールされています。続行するとこのマーケット版で置き換え、プラグインのデータは保持されます。",
"unavailable": "プラグインマーケットを一時的に利用できません。インストール済みプラグインは引き続き利用できます。",
+ "customSourcesUnavailable": "次のカスタムマーケットは一時的に利用できません:{{names}}。他のマーケットには影響しません。",
"authenticationRequired": "プラグインマーケットを表示するには Cindy にログインしてください。",
"notConfigured": "この環境ではプラグインマーケットが設定されていません。インストール済みプラグインは引き続き利用できます。",
"upgradeNotice": {
@@ -3696,15 +3697,8 @@
},
"updateAll": {
"title": "すべて更新 · {{count}} 件",
- "description": "権限に変更がない更新は自動で完了します。権限が拡張される更新は項目ごとに確認が必要です。",
+ "description": "通常の更新は自動で完了し、検証済みの実パッケージが新しい権限を要求する場合のみ個別に確認します。",
"versionRange": "v{{from}} → v{{to}}",
- "permissionChanged": "権限に変更あり",
- "reviewOutdated": "権限の差分が古くなりました",
- "rereview": "再確認",
- "reviewDiff": "確認する",
- "collapseDiff": "閉じる",
- "approve": "同意して更新",
- "skip": "スキップ",
"statusPending": "待機中",
"statusInstalling": "更新中…",
"statusDone": "更新済み",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index d623fdd26b..16467ce8eb 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3271,10 +3271,11 @@
"update": "마켓에서 업데이트",
"updateTo": "v{{version}}(으)로 업데이트",
"installed": "설치됨",
- "conflict": "사용할 수 없음",
- "conflictAria": "{{name}}에 플러그인 ID 충돌이 있습니다",
- "conflictDescription": "이 플러그인 ID는 이미 사용 중이어서 설치할 수 없습니다.",
+ "replace": "교체",
+ "replaceAria": "{{name}}을(를) 이 마켓 버전으로 교체",
+ "replaceDescription": "같은 ID의 플러그인이 이미 설치되어 있습니다. 계속하면 이 마켓 버전으로 교체하고 플러그인 데이터는 유지됩니다.",
"unavailable": "플러그인 마켓을 일시적으로 사용할 수 없습니다. 설치된 플러그인은 계속 사용할 수 있습니다.",
+ "customSourcesUnavailable": "다음 사용자 지정 마켓을 일시적으로 사용할 수 없습니다: {{names}}. 다른 마켓에는 영향을 주지 않습니다.",
"authenticationRequired": "플러그인 마켓을 보려면 Cindy에 로그인하세요.",
"notConfigured": "이 환경에는 플러그인 마켓이 구성되지 않았습니다. 설치된 플러그인은 계속 사용할 수 있습니다.",
"upgradeNotice": {
@@ -3696,15 +3697,8 @@
},
"updateAll": {
"title": "모두 업데이트 · {{count}}개",
- "description": "권한 변경이 없는 업데이트는 자동으로 완료됩니다. 권한이 확장되는 업데이트는 항목별 확인이 필요합니다.",
+ "description": "일반 업데이트는 자동으로 완료되며, 검증된 실제 패키지가 새 권한을 요청할 때만 개별 확인합니다.",
"versionRange": "v{{from}} → v{{to}}",
- "permissionChanged": "권한 변경됨",
- "reviewOutdated": "권한 변경 내역이 오래되었습니다",
- "rereview": "다시 검토",
- "reviewDiff": "확인",
- "collapseDiff": "접기",
- "approve": "동의 후 업데이트",
- "skip": "건너뛰기",
"statusPending": "대기 중",
"statusInstalling": "업데이트 중…",
"statusDone": "업데이트됨",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index fbe52f47b3..5fc42eb15f 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3271,10 +3271,11 @@
"update": "从市场更新",
"updateTo": "更新到 v{{version}}",
"installed": "已安装",
- "conflict": "暂不可用",
- "conflictAria": "{{name}} 存在插件标识冲突",
- "conflictDescription": "插件标识已被占用,当前无法安装",
+ "replace": "替换",
+ "replaceAria": "使用此市场版本替换 {{name}}",
+ "replaceDescription": "已安装相同标识的插件;继续安装会用此市场版本替换,并保留插件数据。",
"unavailable": "插件市场暂时不可用;已安装插件仍可正常管理和使用。",
+ "customSourcesUnavailable": "以下自定义市场暂时不可用:{{names}}。其他市场不受影响。",
"authenticationRequired": "登录 Cindy 后才能查看插件市场。",
"notConfigured": "当前环境未配置插件市场;已安装插件仍可正常管理和使用。",
"upgradeNotice": {
@@ -3696,15 +3697,8 @@
},
"updateAll": {
"title": "全部更新 · {{count}} 个插件",
- "description": "权限无变化的更新会自动完成;涉及权限变更的需要你逐项确认。",
+ "description": "普通更新会自动完成;真实包请求新增权限时需要逐项确认。",
"versionRange": "v{{from}} → v{{to}}",
- "permissionChanged": "权限有变更",
- "reviewOutdated": "权限差异已过期",
- "rereview": "重新审阅",
- "reviewDiff": "查看并确认",
- "collapseDiff": "收起",
- "approve": "同意并更新",
- "skip": "跳过此项",
"statusPending": "排队中",
"statusInstalling": "更新中…",
"statusDone": "已更新",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 7e773b04cc..3f77befb9c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -3274,10 +3274,11 @@
"update": "從市場更新",
"updateTo": "更新到 v{{version}}",
"installed": "已安裝",
- "conflict": "暫不可用",
- "conflictAria": "{{name}} 存在插件標識衝突",
- "conflictDescription": "插件標識已被佔用,當前無法安裝",
+ "replace": "替換",
+ "replaceAria": "使用此市場版本替換 {{name}}",
+ "replaceDescription": "已安裝相同標識的插件;繼續安裝會使用此市場版本替換,並保留插件資料。",
"unavailable": "插件市場暫時不可用;已安裝插件仍可正常管理和使用。",
+ "customSourcesUnavailable": "以下自訂市場暫時不可用:{{names}}。其他市場不受影響。",
"authenticationRequired": "登入 Cindy 後才能檢視插件市場。",
"notConfigured": "當前環境未配置插件市場;已安裝插件仍可正常管理和使用。",
"upgradeNotice": {
@@ -3701,13 +3702,6 @@
"title": "全部更新 · {{count}} 個插件",
"description": "權限無變化的更新會自動完成;涉及權限變更的需要你逐項確認。",
"versionRange": "v{{from}} → v{{to}}",
- "permissionChanged": "權限有變更",
- "reviewOutdated": "權限差異已過期",
- "rereview": "重新審閱",
- "reviewDiff": "檢視並確認",
- "collapseDiff": "收起",
- "approve": "同意並更新",
- "skip": "跳過此項",
"statusPending": "排隊中",
"statusInstalling": "更新中…",
"statusDone": "已更新",
diff --git a/apps/desktop/src/shared/pluginMarket.ts b/apps/desktop/src/shared/pluginMarket.ts
index 7b87fcf46f..fd0ac9373e 100644
--- a/apps/desktop/src/shared/pluginMarket.ts
+++ b/apps/desktop/src/shared/pluginMarket.ts
@@ -1,5 +1,6 @@
import type { GhostManifest, GhostPermissionDiff, InstalledGhost } from './ghost';
import type { PluginIconMetadata } from '@cindy/plugin-protocol';
+import type { DataOwnerPushStamp } from './dataOwnerPush';
export type PluginMarketScope = 'public' | 'organization' | 'personal';
export type PluginMarketInstallState =
@@ -44,6 +45,8 @@ export interface PluginMarketSnapshot {
unavailableReason: string | null;
/** 已添加的自定义市场名(按添加顺序);驱动"自定义"筛选 tab 的可见性。 */
customSourceNames: string[];
+ /** 本轮发现失败的自定义市场名;失败来源不影响其它来源和官方市场。 */
+ unavailableCustomSourceNames: string[];
}
/** 服务端清理的一次性汇总提示:按 owner 缓存,consume 前跨多轮对账累加,consume 后即清。 */
@@ -111,29 +114,33 @@ export type PluginMarketLocalIconResult =
export interface PluginMarketPackageReviewFacts {
/** 已按当前界面语言本地化,仅用于展示;安全指纹由 Main 基于原始清单计算。 */
manifest: GhostManifest;
- /** Main 基于当前已装原始清单与真实包原始清单算出的权限差异;首装为 null。 */
+ /** Main 基于当前已装原始清单与真实包原始清单算出的权限差异;无可靠基线时为 null。 */
permissionDiff: GhostPermissionDiff | null;
+ /** Main 根据安装锁内的实际落位状态判定;不从 permissionDiff 间接推断。 */
+ isUpdate: boolean;
packageSha256: string;
- /** 产生复核结果时的已装权限基线;null 表示当时尚未安装。 */
+ /** 产生复核结果时的可靠已装权限基线;null 也可能是旧安装基线不可读。 */
installedBaseline: string | null;
+ /** 只用于让确认卡如实说明包来自官方还是用户添加的市场。 */
+ sourceType: PluginMarketItemSource;
}
/** Main 在安装事务内请求当前窗口立即确认真实包权限;不暴露内部批准绑定。 */
export interface PluginMarketPackageReviewRequest {
requestId: string;
+ /** Main 投递这份私有包事实时的账号代际;Renderer 必须匹配后才可展示。 */
+ ownerStamp: DataOwnerPushStamp;
manifest: GhostManifest;
permissionDiff: GhostPermissionDiff | null;
+ isUpdate: boolean;
+ sourceType: PluginMarketItemSource;
}
export interface PluginMarketInstallOptions {
- /** 用户审阅时看到的目标 release;Main 会在下载前重新核对。 */
+ /** 用户点击时看到的目标 release;Main 会在下载前重新核对。 */
expectedReleaseId: string;
- /** 安装前展示给用户的完整清单;Main 会与当前来源事实重新核对。 */
- expectedManifest: GhostManifest;
- /** 仅用于自定义市场确认其本地真实 manifest 的扩权。 */
- allowPermissionExpansion?: boolean;
- /** 用户审阅目标权限时的已装权限基线。 */
- reviewedBaseline?: string;
+ /** 仅详情页上用户明确点击“替换”时为 true;更新和批量更新不得切换来源。 */
+ allowSourceReplacement?: boolean;
}
/** 安装成功,或用户在事务内取消真实包权限确认。 */