Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): consume enterprise plugin removal notices (#1651)
fmfsaisai77d63645264f
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 9d6ed82bfb..2ce259c111 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -1952,7 +1952,7 @@ export const GHOST_UNREAD_SNAPSHOT_CHANNEL = 'ghosts:unread-snapshot';* 出站推送与入站 IPC 是同一道授权边界,不能只守一边(codex review)。* 判据复用 `isTrustedAppRendererWindow`,与 `ghosts:unread` 同步读那道闸同源。*/-function sendToTrustedAppWindows(channel: string, payload: unknown): void {+export function sendToTrustedAppWindows(channel: string, payload: unknown): void {sendGhostTrustedWindowPush(channel, payload);}diff --git a/apps/desktop/src/main/plugin-market/__tests__/api.test.ts b/apps/desktop/src/main/plugin-market/__tests__/api.test.tsindex a48a9cbb61..4786e1a7fa 100644--- a/apps/desktop/src/main/plugin-market/__tests__/api.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/api.test.ts@@ -2,6 +2,14 @@ import { describe, expect, it, vi } from 'vitest';import { PluginMarketApi } from '../api';+const logger = vi.hoisted(() => ({+ warn: vi.fn(),+}));++vi.mock('../../logger.js', () => ({+ createLogger: () => ({ info: vi.fn(), warn: logger.warn, error: vi.fn() }),+}));+const PLUGIN_A = `c${'a'.repeat(24)}`;const PLUGIN_B = `c${'b'.repeat(24)}`;@@ -25,26 +33,91 @@ function summary(id: string, ghostId: string) {};}+function removal(pluginId: string, ghostId: string) {+ return {+ pluginId,+ ghostId,+ scope: 'organization',+ organizationId: 'org-1',+ action: 'purge',+ removedAt: '2026-08-03T08:00:00.000Z',+ };+}++/** 依序吐出各页响应(自动补 schemaVersion: 2)的 fetcher mock。 */+function pagedFetcher(...pages: Array<Record<string, unknown>>) {+ const fetcher = vi.fn();+ for (const page of pages) {+ fetcher.mockResolvedValueOnce({ schemaVersion: 2, ...page });+ }+ return fetcher;+}+describe('PluginMarketApi', () => {it('paginates with opaque cursors and deduplicates repeated ids', async () => {- const fetcher = vi- .fn()- .mockResolvedValueOnce({- schemaVersion: 2,- plugins: [summary(PLUGIN_A, 'alpha')],- nextCursor: PLUGIN_A,- })- .mockResolvedValueOnce({- schemaVersion: 2,+ const fetcher = pagedFetcher(+ { plugins: [summary(PLUGIN_A, 'alpha')], nextCursor: PLUGIN_A },+ {plugins: [summary(PLUGIN_A, 'alpha'), summary(PLUGIN_B, 'beta')],nextCursor: null,- });+ },+ );const api = new PluginMarketApi(fetcher);- await expect(api.listAll()).resolves.toHaveLength(2);+ await expect(api.listAll()).resolves.toMatchObject({+ plugins: [{ id: PLUGIN_A }, { id: PLUGIN_B }],+ removals: [],+ });expect(fetcher.mock.calls[1]?.[0]).toContain(`cursor=${PLUGIN_A}`);});+ it('deduplicates removals by pluginId across pages keeping the first-seen notice', async () => {+ const fetcher = pagedFetcher(+ {+ plugins: [],+ removals: [removal(PLUGIN_A, 'alpha')],+ nextCursor: PLUGIN_A,+ },+ {+ plugins: [],+ removals: [+ // 同 pluginId 但内容不同的后到通告必须被丢弃(保首见)。+ { ...removal(PLUGIN_A, 'alpha'), removedAt: '2026-08-04T00:00:00.000Z' },+ removal(PLUGIN_B, 'beta'),+ ],+ nextCursor: null,+ },+ );++ await expect(new PluginMarketApi(fetcher).listAll()).resolves.toMatchObject({+ plugins: [],+ removals: [+ { pluginId: PLUGIN_A, removedAt: '2026-08-03T08:00:00.000Z' },+ { pluginId: PLUGIN_B },+ ],+ });+ });++ it('keeps active plugins over conflicting removals across pages', async () => {+ const fetcher = pagedFetcher(+ {+ plugins: [],+ removals: [removal(PLUGIN_A, 'alpha'), removal(PLUGIN_B, 'beta')],+ nextCursor: PLUGIN_A,+ },+ { plugins: [summary(PLUGIN_A, 'alpha')], removals: [], nextCursor: null },+ );++ await expect(new PluginMarketApi(fetcher).listAll()).resolves.toMatchObject({+ plugins: [{ id: PLUGIN_A }],+ removals: [{ pluginId: PLUGIN_B }],+ });+ expect(logger.warn).toHaveBeenCalledWith(+ 'market removal ignored because plugin is active',+ { pluginId: PLUGIN_A },+ );+ });+it('fails closed when the server still returns schema v1', async () => {const api = new PluginMarketApi(vi.fn().mockResolvedValue({diff --git a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.tsindex d1464c6e99..7db9e405fb 100644--- a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts@@ -29,7 +29,25 @@ describe('Plugin Market IPC error boundary', () => {expect(body).toContain('if (isIpcError(error)) throw error;');expect(body).toContain("throwIpcError('INTERNAL', 'Plugin market operation failed');");- expect(registerSource.match(/return invokePluginMarket\(/g)?.length).toBe(10);+ expect(registerSource.match(/return invokePluginMarket\(/g)?.length).toBe(11);+ });++ it('guards removal notice consumption and signals trusted app windows only', () => {+ const consumeStart = registerSource.indexOf(+ "ipcMain.handle('plugin-market:consume-removal-notice'",+ );+ const consumeEnd = registerSource.indexOf("ipcMain.handle('plugin-market:detail'", consumeStart);+ const consumeBody = registerSource.slice(consumeStart, consumeEnd);+ expect(consumeBody).toContain('assertTrustedAppRendererEvent(event);');+ expect(consumeBody).toContain('service().consumeRemovalNotice()');++ const signalStart = registerSource.indexOf('function signalRemovalNoticeAvailable()');+ const signalEnd = registerSource.indexOf('\n}\n', signalStart);+ const signalBody = registerSource.slice(signalStart, signalEnd);+ // 出站广播必须走共享的可信窗口收口(isDestroyed + isTrustedAppRendererWindow+ // 判据都在 helper 里),不允许退回手写 getAllWindows 循环。+ expect(signalBody).toContain('sendToTrustedAppWindows(REMOVAL_NOTICE_AVAILABLE_CHANNEL');+ expect(signalBody).not.toContain('getAllWindows');});it('refuses renderer-supplied local paths and only grants them via the picker', () => {@@ -54,9 +72,15 @@ describe('Plugin Market IPC error boundary', () => {);const syncEnd = registerSource.indexOf('\n}\n\n/**\n * Preserve stable IPC errors', syncStart);const syncBody = registerSource.slice(syncStart, syncEnd);- expect(syncBody).toContain('await service().snapshot();');+ expect(syncBody).toContain('await snapshotAndSignalRemovalNotice();');expect(syncBody).toContain("log.warn('default plugin startup sync failed'");+ const snapshotStart = registerSource.indexOf('async function snapshotAndSignalRemovalNotice()');+ const snapshotEnd = registerSource.indexOf('\n}\n\n/**', snapshotStart);+ const snapshotBody = registerSource.slice(snapshotStart, snapshotEnd);+ expect(snapshotBody).toContain('finally {');+ expect(snapshotBody).toContain('signalRemovalNoticeAvailable();');+const ownerSyncStart = bootstrapSource.indexOf('function syncDefaultPluginsForActiveOwner(): void',);diff --git a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.tsindex ac2562407d..952c77f92c 100644--- a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts@@ -82,6 +82,28 @@ describe('PluginMarketLedger', () => {});});+ it('filters a schema-v1 installation record with required fields missing', () => {+ const { filePath, ledger } = harness();+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(+ filePath,+ JSON.stringify({+ schemaVersion: 1,+ installations: {+ 'cindy-test': {+ pluginId: `c${'a'.repeat(24)}`,+ ghostId: 'cindy-test',+ source: 'market',+ installed: true,+ },+ },+ defaultInstallOptOuts: {},+ }),+ );++ expect(ledger.installationForGhost('cindy-test')).toBeNull();+ });+it('resolves the owner-scoped path for every operation', () => {const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-plugin-ledger-owner-'));roots.push(root);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.tsindex d896916d71..4973ac4d56 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@@ -180,7 +180,7 @@ function harness(items: VisiblePluginSummary[], marketDirs: Array<{ name: string});}const api = {- listAll: vi.fn(async () => items),+ listAll: vi.fn(async () => ({ plugins: items, removals: [] })),detail: vi.fn(),download: vi.fn(),};@@ -352,7 +352,7 @@ describe('PluginMarketService 自定义市场 snapshot 账户作用域', () => {// 而不是把 user-1 的自定义插件聚合进 user-2 的快照。h.api.listAll.mockImplementation(async () => {runtime.session = { mode: 'cloud', dataOwnerId: 'user-2', generation: 2 };- return [];+ return { plugins: [], removals: [] };});await expect(h.service.snapshot()).rejects.toMatchObject({code: 'PRECONDITION_FAILED',@@ -475,7 +475,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {// 不得把 user-1 审阅的插件装进 user-2 的运行时。h.api.listAll.mockImplementation(async () => {runtime.session = { mode: 'cloud', dataOwnerId: 'user-2', generation: 2 };- return [];+ return { plugins: [], removals: [] };});// 打包前的 discover/校验按 user-1 完成;在 install 入口后切换会话。const installPromise = h.service.install(customMarketPluginId('team-lib', 'alpha'), {diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 355c23aa34..1aa3191e28 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -57,11 +57,19 @@ vi.mock('../download.js', () => ({downloadVerifiedPlugin: vi.fn(async () => undefined),}));-import type { VisiblePluginDetail, VisiblePluginSummary } from '@cindy/plugin-protocol';+import type {+ PluginRemovalNotice,+ VisiblePluginDetail,+ VisiblePluginSummary,+} from '@cindy/plugin-protocol';import { withGhostInstallLock } from '../../cindy-brain/ghostInstallLock';import { GhostPackagePermissionReviewRequiredError } from '../../cindy-brain/packagePermissionReview';-import { PluginMarketLedger, ghostManifestDigest } from '../ledger';+import {+ PluginMarketLedger,+ ghostManifestDigest,+ type PluginMarketInstallationRecord,+} from '../ledger';import { PluginMarketService } from '../service';import type { PluginMarketApi } from '../api';@@ -145,12 +153,29 @@ function detail(item = summary(), slots: ['notify'] | ['notify', 'fs'] = ['notif};}-function harness(items: VisiblePluginSummary[]) {+function removal(+ overrides: Partial<PluginRemovalNotice> = {},+): PluginRemovalNotice {+ return {+ pluginId: PLUGIN_ID,+ ghostId: 'cindy-test',+ scope: 'organization',+ organizationId: 'org-1',+ action: 'purge',+ removedAt: '2026-08-03T08:00:00.000Z',+ ...overrides,+ };+}++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'));const api = {- listAll: vi.fn(async () => items),+ listAll: vi.fn(async () => ({ plugins: items, removals })),detail: vi.fn(async (pluginId: string) => {const item = items.find((candidate) => candidate.id === pluginId);if (!item) throw new Error('not found');@@ -170,6 +195,33 @@ function harness(items: VisiblePluginSummary[]) {};}+/** 清理通告测试的组织安装记录(统一账本 factory 的 organization 视图)。 */+function removalRecord(+ overrides: Partial<PluginMarketInstallationRecord> = {},+): PluginMarketInstallationRecord {+ return recordForTest(+ summary({ scope: 'organization', organizationId: 'org-1' }),+ overrides,+ );+}++/** 清理通告测试的运行时 Ghost 目录项。 */+function ghostEntry(id: string, name?: string) {+ return {+ manifest: name === undefined ? manifest(id) : { ...manifest(id), name },+ dir: `/userData/cindy-brain/${id}`,+ enabled: true,+ };+}++/** uninstall mock 真的把 Ghost 从运行时目录拿走;failFor 指定的那条抛错。 */+function mockUninstallDropsGhost(failFor?: string): void {+ runtime.uninstall.mockImplementation(async (ghostId: string) => {+ if (ghostId === failFor) throw new Error('cleanup failed');+ runtime.ghosts = runtime.ghosts.filter((ghost) => ghost.manifest.id !== ghostId);+ });+}+describe('PluginMarketService migration and defaultInstall', () => {it('projects same-release display metadata without reinstalling the package', async () => {runtime.ghosts = [@@ -890,6 +942,251 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(h.service.prepareLocalUninstallTracking('cindy-test')).toBeNull();});+ it.each(['market', 'legacy-adopted'] as const)(+ 'purges an installed organization plugin owned by the %s source without opting out',+ async (source) => {+ const notice = removal();+ const h = harness([], [notice]);+ runtime.ghosts = [ghostEntry(notice.ghostId)];+ mockUninstallDropsGhost();+ h.ledger.upsertInstallation(removalRecord({ source }));++ await expect(h.service.snapshot()).resolves.toMatchObject({+ unavailableReason: null,+ });++ expect(runtime.uninstall).toHaveBeenCalledWith(notice.ghostId, {+ skipMarketLedger: true,+ });+ expect(h.ledger.installationForGhost(notice.ghostId)?.installed).toBe(false);+ expect(h.ledger.isDefaultInstallSuppressed('user-1', notice.pluginId)).toBe(false);+ expect(h.service.consumeRemovalNotice()).toEqual({+ count: 1,+ name: 'Test Plugin',+ });+ },+ );++ it('purges when the ledger provenance digest matches the installed package', async () => {+ const notice = removal();+ const h = harness([], [notice]);+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-installed-'));+ roots.push(installDir);+ 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()) }),+ );++ await expect(h.service.snapshot()).resolves.toMatchObject({+ unavailableReason: null,+ });++ expect(runtime.uninstall).toHaveBeenCalledWith(notice.ghostId, {+ skipMarketLedger: true,+ });+ expect(h.ledger.installationForGhost(notice.ghostId)?.installed).toBe(false);+ expect(h.service.consumeRemovalNotice()).toEqual({+ count: 1,+ name: 'Test Plugin',+ });+ });++ it.each([+ ['missing ledger record', null],+ ['different pluginId', removalRecord({ pluginId: `c${'b'.repeat(24)}` })],+ [+ 'git marketplace source',+ removalRecord({ source: 'git-market', sourceKey: '["git","repo"]' }),+ ],+ [+ 'local marketplace source',+ removalRecord({ source: 'local-market', sourceKey: '["local","dir"]' }),+ ],+ ['already removed record', removalRecord({ installed: false })],+ ['public scope record', removalRecord({ scope: 'public', organizationId: null })],+ // 记录带溯源摘要但运行时包对不上(此处 ghost.json 不可读=摘要 null):占位的+ // 已不是市场装的那份包,按 fail-closed 口径不删。+ ['stale manifest digest', removalRecord({ manifestDigest: 'f'.repeat(64) })],+ ] as const)(+ 'skips a server removal with %s without touching the ledger',+ async (_label, record) => {+ const notice = removal();+ const h = harness([], [notice]);+ runtime.ghosts = [ghostEntry(notice.ghostId)];+ if (record) h.ledger.upsertInstallation(record);+ const before = h.ledger.read();++ await expect(h.service.snapshot()).resolves.toMatchObject({+ unavailableReason: null,+ });++ expect(runtime.uninstall).not.toHaveBeenCalled();+ expect(h.ledger.read()).toEqual(before);+ expect(h.service.consumeRemovalNotice()).toBeNull();+ },+ );++ it('skips a removal whose action is not purge without touching the ledger', async () => {+ // 协议层已滤掉未知 action;这里锁的是 service 兜底(验收点 6):万一有+ // 非 purge 通告穿透,零卸载、零账本写入、零通知。+ const notice = removal({+ action: 'quarantine' as unknown as PluginRemovalNotice['action'],+ });+ const h = harness([], [notice]);+ runtime.ghosts = [ghostEntry(notice.ghostId)];+ h.ledger.upsertInstallation(removalRecord());+ const before = h.ledger.read();++ await expect(h.service.snapshot()).resolves.toMatchObject({+ unavailableReason: null,+ });++ expect(runtime.uninstall).not.toHaveBeenCalled();+ expect(h.ledger.read()).toEqual(before);+ expect(h.service.consumeRemovalNotice()).toBeNull();+ });++ it('keeps an existing default-install opt-out when a repeated purge is skipped', async () => {+ const notice = removal();+ const h = harness([], [notice]);+ h.ledger.upsertInstallation(removalRecord());+ h.ledger.markRemoved(notice.ghostId, 'user-1');++ await h.service.snapshot();++ expect(runtime.uninstall).not.toHaveBeenCalled();+ expect(h.ledger.isDefaultInstallSuppressed('user-1', notice.pluginId)).toBe(true);+ expect(h.service.consumeRemovalNotice()).toBeNull();+ });++ it('keeps a pre-existing opt-out intact after a successful purge', async () => {+ // 退订只读的另一半(不清):早先手动卸载写过退订、之后又重新安装的用户,+ // purge 成功后退订必须原样保留,穿越重新上架周期继续生效。+ const notice = removal();+ const h = harness([], [notice]);+ runtime.ghosts = [ghostEntry(notice.ghostId)];+ mockUninstallDropsGhost();+ h.ledger.upsertInstallation(removalRecord());+ h.ledger.markRemoved(notice.ghostId, 'user-1');+ h.ledger.upsertInstallation(removalRecord());++ await h.service.snapshot();++ expect(runtime.uninstall).toHaveBeenCalledTimes(1);+ expect(h.ledger.installationForGhost(notice.ghostId)?.installed).toBe(false);+ expect(h.ledger.isDefaultInstallSuppressed('user-1', notice.pluginId)).toBe(true);+ expect(h.service.consumeRemovalNotice()).toEqual({ count: 1, name: 'Test Plugin' });+ });++ it('applies a repeated removal only once across snapshots', async () => {+ const notice = removal();+ const h = harness([], [notice]);+ runtime.ghosts = [ghostEntry(notice.ghostId)];+ mockUninstallDropsGhost();+ h.ledger.upsertInstallation(removalRecord());++ await h.service.snapshot();+ expect(h.service.consumeRemovalNotice()).toEqual({ count: 1, name: 'Test Plugin' });+ await h.service.snapshot();++ expect(runtime.uninstall).toHaveBeenCalledTimes(1);+ expect(h.service.consumeRemovalNotice()).toBeNull();+ });++ 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 h = harness([], notices);+ runtime.ghosts = [+ ghostEntry('cindy-test'),+ ghostEntry('cindy-second', 'Second Plugin'),+ ];+ mockUninstallDropsGhost();+ h.ledger.upsertInstallation(removalRecord());+ h.ledger.upsertInstallation(+ removalRecord({ pluginId: secondPluginId, ghostId: 'cindy-second' }),+ );++ await h.service.snapshot();++ expect(runtime.uninstall).toHaveBeenCalledTimes(2);+ expect(h.service.consumeRemovalNotice()).toEqual({ count: 2, name: null });+ });++ it('keeps a pending removal notice isolated to the owner that was cleaned', async () => {+ const notice = removal();+ const h = harness([], [notice]);+ runtime.ghosts = [ghostEntry(notice.ghostId)];+ mockUninstallDropsGhost();+ h.ledger.upsertInstallation(removalRecord());++ await h.service.snapshot();+ runtime.session = {+ mode: 'cloud',+ dataOwnerId: 'user-2',+ generation: 2,+ };+ expect(h.service.consumeRemovalNotice()).toBeNull();+ runtime.session = {+ mode: 'cloud',+ dataOwnerId: 'user-1',+ generation: 3,+ };+ expect(h.service.consumeRemovalNotice()).toEqual({+ count: 1,+ name: 'Test Plugin',+ });+ // 一次即清:同 owner 紧接着再取必须为空,不会重复弹窗。+ expect(h.service.consumeRemovalNotice()).toBeNull();+ });++ it('still counts a successful removal when the safe display name becomes empty', async () => {+ const notice = removal();+ const h = harness([], [notice]);+ runtime.ghosts = [ghostEntry(notice.ghostId, '\u202e')];+ mockUninstallDropsGhost();+ h.ledger.upsertInstallation(removalRecord());++ await h.service.snapshot();++ expect(h.service.consumeRemovalNotice()).toEqual({ count: 1, name: null });+ });++ 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 h = harness([], notices);+ runtime.ghosts = [+ ghostEntry('cindy-test'),+ ghostEntry('cindy-second', 'Second Plugin'),+ ];+ mockUninstallDropsGhost('cindy-test');+ h.ledger.upsertInstallation(removalRecord());+ h.ledger.upsertInstallation(+ removalRecord({ pluginId: secondPluginId, ghostId: 'cindy-second' }),+ );++ await expect(h.service.snapshot()).resolves.toMatchObject({+ unavailableReason: null,+ });++ expect(runtime.uninstall).toHaveBeenCalledTimes(2);+ expect(h.ledger.installationForGhost('cindy-test')?.installed).toBe(true);+ expect(h.ledger.installationForGhost('cindy-second')?.installed).toBe(false);+ expect(h.service.consumeRemovalNotice()).toEqual({+ count: 1,+ name: 'Second Plugin',+ });+ });+it('does not restore a bundled default after the user removed it', async () => {const item = summary({ defaultInstall: true });runtime.builtinRemoved.add(item.ghostId);@@ -1145,7 +1442,7 @@ describe('PluginMarketService migration and defaultInstall', () => {dataOwnerId: 'user-2',generation: 2,};- return [item];+ return { plugins: [item], removals: [] };});await expect(h.service.install(item.id, { expectedReleaseId: item.currentRelease.id })).rejects.toThrow('[PRECONDITION_FAILED]');@@ -1210,7 +1507,10 @@ describe('PluginMarketService migration and defaultInstall', () => {});});-function recordForTest(item: VisiblePluginSummary) {+function recordForTest(+ item: VisiblePluginSummary,+ overrides: Partial<PluginMarketInstallationRecord> = {},+): PluginMarketInstallationRecord {return {pluginId: item.id,ghostId: item.ghostId,@@ -1219,8 +1519,9 @@ function recordForTest(item: VisiblePluginSummary) {sha256: item.currentRelease.sha256,scope: item.scope,organizationId: item.organizationId,- source: 'market' as const,+ source: 'market',installed: true,updatedAt: '2026-07-23T00:00:00.000Z',+ ...overrides,};}diff --git a/apps/desktop/src/main/plugin-market/api.ts b/apps/desktop/src/main/plugin-market/api.tsindex 2db87eee4b..0006e93824 100644--- a/apps/desktop/src/main/plugin-market/api.ts+++ b/apps/desktop/src/main/plugin-market/api.ts@@ -4,12 +4,16 @@ import {parsePluginDownloadResponse,type GetPluginResponse,type ListPluginsResponse,+ type PluginRemovalNotice,type PluginDownloadResponse,} from '@cindy/plugin-protocol';import { getClientEndpoint } from '../clientEndpointsService.js';+import { createLogger } from '../logger.js';import { serverApiFetch, type ApiFetchOptions } from '../serverApiClient.js';+const log = createLogger('plugin-market-api');+type Fetcher = <T>(apiPath: string,options: Omit<ApiFetchOptions, 'baseUrl'>,@@ -25,8 +29,11 @@ const defaultFetcher: Fetcher = (apiPath, options) =>export class PluginMarketApi {constructor(private readonly fetcher: Fetcher = defaultFetcher) {}- async listAll(query?: string): Promise<ListPluginsResponse['plugins']> {+ async listAll(+ query?: string,+ ): Promise<Pick<ListPluginsResponse, 'plugins' | 'removals'>> {const plugins: ListPluginsResponse['plugins'] = [];+ const removalsByPluginId = new Map<string, PluginRemovalNotice>();let cursor: string | null = null;const seen = new Set<string>();for (let page = 0; page < 100; page += 1) {@@ -43,7 +50,24 @@ export class PluginMarketApi {seen.add(plugin.id);plugins.push(plugin);}- if (!response.nextCursor) return plugins;+ for (const removal of response.removals) {+ if (!removalsByPluginId.has(removal.pluginId)) {+ removalsByPluginId.set(removal.pluginId, removal);+ }+ }+ if (!response.nextCursor) {+ // 在架优先(契约:通告与**任一页** plugins 有交集即作废)的作用域是+ // 未经 owner 过滤的完整目录,必须留在聚合层;挪到 service 的 owner+ // 视角之后,owner 不可见但在架的插件会被错误放行清理。+ const removals = [...removalsByPluginId.values()].filter((removal) => {+ if (!seen.has(removal.pluginId)) return true;+ log.warn('market removal ignored because plugin is active', {+ pluginId: removal.pluginId,+ });+ return false;+ });+ return { plugins, removals };+ }if (response.nextCursor === cursor) throw new Error('Plugin 市场分页游标未前进');cursor = response.nextCursor;}diff --git a/apps/desktop/src/main/plugin-market/registerIpc.ts b/apps/desktop/src/main/plugin-market/registerIpc.tsindex f46edc7c36..8462cad98f 100644--- a/apps/desktop/src/main/plugin-market/registerIpc.ts+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts@@ -4,7 +4,10 @@ import { ipcMain } from 'electron';import { isIpcError } from '../../shared/ipc-errors.js';import type { GhostManifest } from '../../shared/ghost.js';-import { setGhostUninstallLedgerPreparer } from '../cindy-brain/index.js';+import {+ sendToTrustedAppWindows,+ setGhostUninstallLedgerPreparer,+} from '../cindy-brain/index.js';import { createLogger } from '../logger.js';import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';import { requireObject, requireString, throwIpcError } from '../utils/ipcValidate.js';@@ -14,12 +17,28 @@ import { PluginMarketService } from './service.js';const log = createLogger('plugin-market-ipc');let registered = false;let serviceSingleton: PluginMarketService | null = null;+const REMOVAL_NOTICE_AVAILABLE_CHANNEL = 'plugin-market:removal-notice-available';function service(): PluginMarketService {serviceSingleton ??= new PluginMarketService();return serviceSingleton;}+function signalRemovalNoticeAvailable(): void {+ if (!service().hasPendingRemovalNotice()) return;+ sendToTrustedAppWindows(REMOVAL_NOTICE_AVAILABLE_CHANNEL, undefined);+}++async function snapshotAndSignalRemovalNotice() {+ try {+ return await service().snapshot();+ } finally {+ // 清理已成功但后续默认安装等步骤失败时,pending 仍必须通知 Renderer;+ // snapshot 的原始异常继续向上抛,不把通知信号伪装成整轮成功。+ signalRemovalNoticeAvailable();+ }+}+/*** Reuse the market snapshot reconciliation outside the Plugins page so* default-install plugins are provisioned as soon as an app owner is ready.@@ -27,7 +46,7 @@ function service(): PluginMarketService {*/export async function syncDefaultMarketPlugins(): Promise<void> {try {- await service().snapshot();+ await snapshotAndSignalRemovalNotice();} catch (error) {log.warn('default plugin startup sync failed', {error: error instanceof Error ? error.message : String(error),@@ -61,7 +80,11 @@ export function registerPluginMarketIpc(): void {);ipcMain.handle('plugin-market:snapshot', (event) => {assertTrustedAppRendererEvent(event);- return invokePluginMarket(() => service().snapshot());+ return invokePluginMarket(() => snapshotAndSignalRemovalNotice());+ });+ ipcMain.handle('plugin-market:consume-removal-notice', (event) => {+ assertTrustedAppRendererEvent(event);+ return invokePluginMarket(async () => service().consumeRemovalNotice());});ipcMain.handle('plugin-market:detail', (event, pluginId: unknown) => {assertTrustedAppRendererEvent(event);diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex a88bb60644..8411396351 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -4,6 +4,7 @@ import crypto from 'node:crypto';import {isValidPluginResourceId,+ type PluginRemovalNotice,type VisiblePluginDetail,type VisiblePluginSummary,} from '@cindy/plugin-protocol';@@ -25,6 +26,7 @@ import type {PluginMarketInstallResult,PluginMarketItem,PluginMarketSnapshot,+ PluginRemovalUserNotice,} from '../../shared/pluginMarket.js';import {customMarketPluginId,@@ -281,6 +283,14 @@ interface LocalInstallSnapshot {rawDigestByGhostId: ReadonlyMap<string, string | null>;}+/**+ * 清理通告 pending 汇总的 owner 隔离键。**故意不含 generation**:同一 owner+ * 重新登录(换代)后,未消费的通知仍应展示,不随会话代际作废。+ */+function removalNoticeKey(owner: ActiveAppSession): string {+ return `${owner.mode}:${owner.dataOwnerId}`;+}+/*** Plugin 市场的 main 端协调器。远程不可用时不碰本地目录;安装写路径必须依次* 通过 protocol parser、下载大小/SHA 校验、Ghost runtime validator 和原子换目录。@@ -288,6 +298,7 @@ interface LocalInstallSnapshot {export class PluginMarketService {private readonly mutations = new Map<string, Promise<unknown>>();private ledgerMutation: Promise<void> = Promise.resolve();+ private readonly pendingRemovalNotices = new Map<string, PluginRemovalUserNotice>();constructor(private readonly api = new PluginMarketApi(),@@ -335,8 +346,11 @@ export class PluginMarketService {};}let plugins: VisiblePluginSummary[];+ let removals: PluginRemovalNotice[];try {- plugins = visiblePluginsForOwner(owner, await this.api.listAll());+ const catalog = await this.api.listAll();+ plugins = visiblePluginsForOwner(owner, catalog.plugins);+ removals = catalog.removals;} catch (error) {log.warn('market list unavailable', {error: error instanceof Error ? error.message : String(error),@@ -361,6 +375,7 @@ export class PluginMarketService {await this.adoptLegacyInstallations(plugins, ledger, owner);await this.migrateMarketManifestDigests(plugins, ledger, owner);await this.reconcileRemovedInstallations(ledger, owner);+ await this.applyServerRemovals(removals, owner, ledger);// 自定义目录不完整(某来源暂时不可读)时跳过全部默认安装:此刻的合并冲突// 集合缺了坏来源声明的 ghostId,自动安装会在它恢复前抢占所有权。if (customComplete) {@@ -384,6 +399,23 @@ export class PluginMarketService {};}+ /** 按当前 owner 消费一次清理汇总,避免组织插件名跨账号泄露。 */+ consumeRemovalNotice(): PluginRemovalUserNotice | null {+ const key = removalNoticeKey(captureMarketOwner());+ const notice = this.pendingRemovalNotices.get(key) ?? null;+ if (notice) this.pendingRemovalNotices.delete(key);+ return notice;+ }++ hasPendingRemovalNotice(): boolean {+ if (this.pendingRemovalNotices.size === 0) return false;+ try {+ return this.pendingRemovalNotices.has(removalNoticeKey(captureMarketOwner()));+ } catch {+ return false;+ }+ }+async detail(pluginId: string): Promise<PluginMarketDetail> {// 自定义市场插件走本地发现,不要求服务端可用,也不受 CUID 形状约束。const customRef = parseCustomMarketPluginId(pluginId);@@ -436,7 +468,7 @@ export class PluginMarketService {const ledger = this.ledgerForOwner(owner);return this.withMutation(pluginId, async () => {requireSameMarketOwner(owner);- const catalog = visiblePluginsForOwner(owner, await this.api.listAll());+ const catalog = visiblePluginsForOwner(owner, (await this.api.listAll()).plugins);requireSameMarketOwner(owner);const selected = catalog.find((plugin) => plugin.id === pluginId);if (!selected) {@@ -683,7 +715,7 @@ export class PluginMarketService {let serverKnown = knownServerPlugins !== undefined;if (!serverKnown && getClientEndpoint('pluginApiBaseUrl')) {try {- serverPlugins = visiblePluginsForOwner(owner, await this.api.listAll());+ serverPlugins = visiblePluginsForOwner(owner, (await this.api.listAll()).plugins);serverKnown = true;} catch (error) {log.warn('market catalog unavailable while recomputing cross-source duplicates', {@@ -1425,6 +1457,109 @@ export class PluginMarketService {}}+ private async applyServerRemovals(+ removals: readonly PluginRemovalNotice[],+ owner: ActiveAppSession,+ ledger: PluginMarketLedger,+ ): Promise<void> {+ if (removals.length === 0) return;+ const skip = (removal: PluginRemovalNotice, reason: string): undefined => {+ log.info('server plugin removal skipped', {+ pluginId: removal.pluginId,+ ghostId: removal.ghostId,+ reason,+ });+ return undefined;+ };+ // 五道闸的账本侧判定。锁外先用一次性快照预筛(绝大多数通告在这里就被+ // 挡下,不必为它们各自重读账本/进互斥段);幸存候选进锁后**必须**用+ // installationForGhost 即时复检——快照在等锁期间可能过时,权威判定只认锁内。+ const ledgerGateReason = (+ record: PluginMarketInstallationRecord | null | undefined,+ removal: PluginRemovalNotice,+ ): string | null => {+ if (!record) return 'ledger-record-missing';+ if (record.pluginId !== removal.pluginId) return 'plugin-id-mismatch';+ if (record.source !== 'market' && record.source !== 'legacy-adopted') {+ return 'non-server-source';+ }+ if (!record.installed) return 'already-not-installed';+ if (record.scope !== 'organization') return 'non-organization-scope';+ return null;+ };+ const snapshot = ledger.read().installations;+ // runtime 在场判定与取名共用一次目录扫描(list 会读每个包的 manifest 与+ // 图标),首个幸存候选时才建;清理会改目录,但每条清理都在自己的互斥段里+ // 由账本复检把关,这张表只回答"清理前它在不在场、叫什么"。+ let ghostsById: Map<string, InstalledGhost> | null = null;+ const removedNames: Array<string | null> = [];+ for (const removal of removals) {+ if (removal.action !== 'purge') {+ skip(removal, 'unsupported-action');+ continue;+ }+ const prefilterReason = ledgerGateReason(snapshot[removal.ghostId], removal);+ if (prefilterReason) {+ skip(removal, prefilterReason);+ continue;+ }+ try {+ const removed = await this.withMutation(removal.pluginId, async () => {+ requireSameMarketOwner(owner);+ const record = ledger.installationForGhost(removal.ghostId);+ const reason = ledgerGateReason(record, removal);+ if (reason) return skip(removal, reason);++ ghostsById ??= new Map(+ getGhostManager().list().map((ghost) => [ghost.manifest.id, ghost]),+ );+ const installed = ghostsById.get(removal.ghostId);+ if (!installed) return skip(removal, 'runtime-not-installed');+ // 溯源摘要闸:账本记录只证明"市场装过这个 ghostId",不证明现在占位的+ // 还是那份包——本地 .cindy 可原位替换,替换不写市场账本。摘要对不上+ // (含 ghost.json 读不出)即视为非服务端安装,不删,与更新路径/连接授权+ // 的 fail-closed 判据同口径。缺摘要的存量记录放行:被下架的插件已不在+ // 目录里,digest 迁移永远补不上,fail-closed 会让老安装的合法清理永久失效。+ if (+ record?.manifestDigest != null &&+ installedGhostRawManifestDigest(installed.dir) !== record.manifestDigest+ ) {+ return skip(removal, 'manifest-digest-mismatch');+ }++ await uninstallGhostAndCleanup(removal.ghostId, { skipMarketLedger: true });+ await this.withCapturedLedgerMutation(ledger, () => {+ // userId=null 即不写退订(拍板:purge 对 defaultInstallOptOuts 只读,+ // 不写也不清;重新上架后按用户既有退订状态决定是否自动装回)。+ ledger.markRemoved(removal.ghostId, null);+ });+ log.info('server plugin removal applied', {+ pluginId: removal.pluginId,+ ghostId: removal.ghostId,+ });+ return {+ name: stripDirectionalControls(installed.manifest.name) || null,+ };+ });+ if (removed) removedNames.push(removed.name);+ } catch (error) {+ log.error('server plugin removal failed', {+ pluginId: removal.pluginId,+ ghostId: removal.ghostId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ if (removedNames.length === 0) return;+ const key = removalNoticeKey(owner);+ const count =+ (this.pendingRemovalNotices.get(key)?.count ?? 0) + removedNames.length;+ this.pendingRemovalNotices.set(key, {+ count,+ name: count === 1 ? (removedNames[0] ?? null) : null,+ });+ }+private async applyDefaultInstalls(plugins: readonly VisiblePluginSummary[],owner: ActiveAppSession,diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex e3e99d0164..d75bbf4d59 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -367,6 +367,9 @@ const fanOutApplicationMenuCommand = createIpcFanOut('app-menu:command');// 首登轻量数据迁移(mToc)弹窗阶段推送(confirm / running / done / failed)const fanOutLegacyMigrationState = createIpcFanOut('legacy-migration:state');const fanOutCorruptionRestored = createIpcFanOut('local-db:corruption-restored');+const fanOutPluginRemovalNoticeAvailable = createIpcFanOut(+ 'plugin-market:removal-notice-available',+);// #37: release 端检测到 schema drift 时一次性 toast 提示开发者切回 dev 自动修复const fanOutSchemaDriftWarning = createIpcFanOut('local-db:schema-drift-warning');const fanOutProjectAliasesChanged = createIpcFanOut('local-db:project-aliases:changed');@@ -1144,6 +1147,10 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('plugin-market:install', pluginId, options),uninstall: (pluginId: string): Promise<{ ok: true }> =>ipcRenderer.invoke('plugin-market:uninstall', pluginId),+ consumeRemovalNotice: (): Promise<+ import('../shared/pluginMarket').PluginRemovalUserNotice | null+ > => ipcRenderer.invoke('plugin-market:consume-removal-notice'),+ onRemovalNoticeAvailable: fanOutPluginRemovalNoticeAvailable,listSources: (): Promise<import('../shared/pluginMarket').MarketSourceSummary[]> =>ipcRenderer.invoke('plugin-market:list-sources'),pickLocalSource: (diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsxindex f95a9e5aa3..8292e64ff0 100644--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx@@ -71,6 +71,7 @@ import { useCorruptionRestoredToast } from '@/hooks/useCorruptionRestoredToast';// #37 schema-drift release-side toastimport { useSchemaDriftWarningToast } from '@/hooks/useSchemaDriftWarningToast';import { useVoiceInputShortcutRecoveryToast } from '@/hooks/useVoiceInputShortcutRecoveryToast';+import { usePluginRemovalNoticeToast } from '@/hooks/usePluginRemovalNoticeToast';import { requestProjectFocus } from '@/state/pendingProjectFocus';import { patchDraft } from '@/state/newMakerDraft';import { cn } from '@/lib/utils';@@ -469,6 +470,8 @@ export function MainLayout() {useSchemaDriftWarningToast();// 语音快捷键在设置页之外自动恢复失败 —— 那时设置页的 toast 不在,只能由常挂载的这里提示。useVoiceInputShortcutRecoveryToast();+ // 冷启动市场对账可能早于 Renderer 挂载;Main pending + 常驻 consume 保证清理不静默。+ usePluginRemovalNoticeToast();// device-link 跨设备远程控制:同账号在线 + 开了被控的设备,其项目自动并入侧边栏useDeviceLinkRemoteProjects();diff --git a/apps/desktop/src/renderer/hooks/__tests__/usePluginRemovalNoticeToast.test.tsx b/apps/desktop/src/renderer/hooks/__tests__/usePluginRemovalNoticeToast.test.tsxnew file mode 100644index 0000000000..78f99a186b--- /dev/null+++ b/apps/desktop/src/renderer/hooks/__tests__/usePluginRemovalNoticeToast.test.tsx@@ -0,0 +1,107 @@+// @vitest-environment jsdom++import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ state: {+ listener: undefined as (() => void) | undefined,+ secondary: false,+ },+ consume: vi.fn(),+ subscribe: vi.fn(),+ unsubscribe: vi.fn(),+ toastInfo: vi.fn(),+ translate: vi.fn((key: string) => key),+ warn: vi.fn(),+}));++vi.mock('@/i18n', () => ({+ i18n: { t: mocks.translate },+}));++vi.mock('@/lib/secondaryWindow', () => ({+ isSecondaryWindow: () => mocks.state.secondary,+}));++vi.mock('@/lib/toast', () => ({+ toast: { info: mocks.toastInfo },+}));++vi.mock('@/lib/logger', () => ({+ createLogger: () => ({ warn: mocks.warn }),+}));++import { usePluginRemovalNoticeToast } from '../usePluginRemovalNoticeToast';++describe('usePluginRemovalNoticeToast', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.state.listener = undefined;+ mocks.state.secondary = false;+ mocks.consume.mockResolvedValue(null);+ mocks.subscribe.mockImplementation((listener: () => void) => {+ mocks.state.listener = listener;+ return mocks.unsubscribe;+ });+ (+ window as unknown as {+ electronAPI: {+ pluginMarket: {+ consumeRemovalNotice: typeof mocks.consume;+ onRemovalNoticeAvailable: typeof mocks.subscribe;+ };+ };+ }+ ).electronAPI = {+ pluginMarket: {+ consumeRemovalNotice: mocks.consume,+ onRemovalNoticeAvailable: mocks.subscribe,+ },+ };+ });++ afterEach(() => cleanup());++ it('subscribes before consuming and shows a cold-start single-plugin notice', async () => {+ mocks.consume.mockResolvedValueOnce({ count: 1, name: 'Team Plugin' });++ const view = renderHook(() => usePluginRemovalNoticeToast());++ await waitFor(() => expect(mocks.toastInfo).toHaveBeenCalledTimes(1));+ expect(mocks.subscribe.mock.invocationCallOrder[0]).toBeLessThan(+ mocks.consume.mock.invocationCallOrder[0]!,+ );+ expect(mocks.translate).toHaveBeenCalledWith('settings.ghosts.market.removalNotice.single', {+ name: 'Team Plugin',+ });+ expect(mocks.toastInfo).toHaveBeenCalledWith('settings.ghosts.market.removalNotice.single', {+ duration: 8000,+ });++ view.unmount();+ expect(mocks.unsubscribe).toHaveBeenCalledOnce();+ });++ it('consumes a later signal and shows one combined multi-plugin notice', async () => {+ renderHook(() => usePluginRemovalNoticeToast());+ await waitFor(() => expect(mocks.consume).toHaveBeenCalledTimes(1));+ mocks.consume.mockResolvedValueOnce({ count: 3, name: null });++ act(() => mocks.state.listener?.());++ await waitFor(() => expect(mocks.toastInfo).toHaveBeenCalledTimes(1));+ expect(mocks.translate).toHaveBeenCalledWith('settings.ghosts.market.removalNotice.multiple', {+ count: 3,+ });+ });++ it('does not let a secondary window consume the main-window notice', () => {+ mocks.state.secondary = true;++ renderHook(() => usePluginRemovalNoticeToast());++ expect(mocks.subscribe).not.toHaveBeenCalled();+ expect(mocks.consume).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/hooks/usePluginRemovalNoticeToast.ts b/apps/desktop/src/renderer/hooks/usePluginRemovalNoticeToast.tsnew file mode 100644index 0000000000..ed272bc5bc--- /dev/null+++ b/apps/desktop/src/renderer/hooks/usePluginRemovalNoticeToast.ts@@ -0,0 +1,54 @@+/**+ * 组织插件被服务端清理后的一次性汇总提示。+ *+ * 清理可能发生在主界面挂载前(冷启动对账),所以不能只依赖 push:Main 保留+ * owner 隔离的 pending 汇总,Renderer 先订阅再主动 consume;后续 push 也走同一+ * consume 入口。Main 侧 consume 是同步的原子取走(get+delete),并发信号里+ * 后到的一次只会拿到 null,不会重复弹窗。文案在展示瞬间用 i18n 直调翻译,+ * 不依赖组件重渲染,effect 因此无依赖、只随挂载建立一次订阅。+ */++import { useEffect } from 'react';++import { i18n } from '@/i18n';+import { createLogger } from '@/lib/logger';+import { isSecondaryWindow } from '@/lib/secondaryWindow';+import { toast } from '@/lib/toast';++const log = createLogger('usePluginRemovalNoticeToast');++export function usePluginRemovalNoticeToast(): void {+ useEffect(() => {+ // 副窗口不消费全局一次性通知,避免抢在主窗口前取走。+ if (isSecondaryWindow()) return undefined;++ let cancelled = false;+ const showIfPending = async (): Promise<void> => {+ try {+ const notice = await window.electronAPI.pluginMarket.consumeRemovalNotice();+ if (cancelled || !notice) return;+ const message =+ notice.count === 1 && notice.name+ ? i18n.t('settings.ghosts.market.removalNotice.single', {+ name: notice.name,+ })+ : i18n.t('settings.ghosts.market.removalNotice.multiple', {+ count: notice.count,+ });+ toast.info(message, { duration: 8000 });+ } catch (error) {+ log.warn('failed to consume plugin removal notice:', error);+ }+ };++ // 先订阅再主动取,封住「初次 consume 与 listener 建立之间」的新通知窗口。+ const unsubscribe = window.electronAPI.pluginMarket.onRemovalNoticeAvailable(() => {+ void showIfPending();+ });+ void showIfPending();+ return () => {+ cancelled = true;+ unsubscribe();+ };+ }, []);+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 6fa8d98f81..ecd9ea6735 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3214,6 +3214,11 @@"unavailable": "The plugin market is temporarily unavailable. Installed plugins remain available.","authenticationRequired": "Sign in to Cindy to view the plugin market.","notConfigured": "The plugin market is not configured for this environment. Installed plugins remain available.",+ "removalNotice": {+ "single": "The organization removed the plugin “{{name}}”. Its local copy and data on this device have been cleaned up.",+ "multiple_one": "The organization removed {{count}} plugin. Its local copy and data on this device have been cleaned up.",+ "multiple_other": "The organization removed {{count}} plugins. Their local copies and data on this device have been cleaned up."+ },"errors": {"generic": "The plugin market operation failed. Please try again.","invalidRequest": "The plugin request is invalid.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex d431bd2223..8911ee09c4 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3213,6 +3213,11 @@"unavailable": "プラグインマーケットを一時的に利用できません。インストール済みプラグインは引き続き利用できます。","authenticationRequired": "プラグインマーケットを表示するには Cindy にログインしてください。","notConfigured": "この環境ではプラグインマーケットが設定されていません。インストール済みプラグインは引き続き利用できます。",+ "removalNotice": {+ "single": "プラグイン「{{name}}」は組織によって削除され、このデバイス上のローカルコピーとデータはクリーンアップされました。",+ "multiple_one": "{{count}} 件のプラグインが組織によって削除され、このデバイス上のローカルコピーとデータはクリーンアップされました。",+ "multiple_other": "{{count}} 件のプラグインが組織によって削除され、このデバイス上のローカルコピーとデータはクリーンアップされました。"+ },"errors": {"generic": "プラグインマーケットの操作に失敗しました。もう一度お試しください。","invalidRequest": "プラグインのリクエストが無効です。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex bc384bf492..2f32c79b27 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3213,6 +3213,11 @@"unavailable": "플러그인 마켓을 일시적으로 사용할 수 없습니다. 설치된 플러그인은 계속 사용할 수 있습니다.","authenticationRequired": "플러그인 마켓을 보려면 Cindy에 로그인하세요.","notConfigured": "이 환경에는 플러그인 마켓이 구성되지 않았습니다. 설치된 플러그인은 계속 사용할 수 있습니다.",+ "removalNotice": {+ "single": "플러그인 “{{name}}”: 조직에서 제거했으며 이 기기의 로컬 사본과 데이터도 정리했습니다.",+ "multiple_one": "{{count}}개의 플러그인이 조직에서 제거되었습니다. 이 기기의 로컬 사본과 데이터가 정리되었습니다.",+ "multiple_other": "{{count}}개의 플러그인이 조직에서 제거되었습니다. 이 기기의 로컬 사본과 데이터가 정리되었습니다."+ },"errors": {"generic": "플러그인 마켓 작업에 실패했습니다. 다시 시도해 주세요.","invalidRequest": "플러그인 요청이 올바르지 않습니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 215da8e88e..88e5145cca 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3213,6 +3213,11 @@"unavailable": "插件市场暂时不可用;已安装插件仍可正常管理和使用。","authenticationRequired": "登录 Cindy 后才能查看插件市场。","notConfigured": "当前环境未配置插件市场;已安装插件仍可正常管理和使用。",+ "removalNotice": {+ "single": "插件“{{name}}”已被组织移除,本机副本与数据已清理",+ "multiple_one": "{{count}} 个插件已被组织移除,本机副本与数据已清理",+ "multiple_other": "{{count}} 个插件已被组织移除,本机副本与数据已清理"+ },"errors": {"generic": "插件市场操作失败,请重试。","invalidRequest": "插件请求无效。",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 7f9fff298b..56f88a7626 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1465,6 +1465,10 @@ interface ElectronAPI {options: import('../shared/pluginMarket').PluginMarketInstallOptions,) => Promise<import('../shared/pluginMarket').PluginMarketInstallResult>;uninstall: (pluginId: string) => Promise<{ ok: true }>;+ consumeRemovalNotice: () => Promise<+ import('../shared/pluginMarket').PluginRemovalUserNotice | null+ >;+ onRemovalNoticeAvailable: (callback: () => void) => () => void;listSources: () => Promise<import('../shared/pluginMarket').MarketSourceSummary[]>;pickLocalSource: (defaultPath?: string,diff --git a/apps/desktop/src/shared/pluginMarket.ts b/apps/desktop/src/shared/pluginMarket.tsindex 2b946bac98..44f44e480f 100644--- a/apps/desktop/src/shared/pluginMarket.ts+++ b/apps/desktop/src/shared/pluginMarket.ts@@ -40,6 +40,13 @@ export interface PluginMarketSnapshot {customSourceNames: string[];}+/** 服务端清理的一次性汇总提示:按 owner 缓存,consume 前跨多轮对账累加,consume 后即清。 */+export interface PluginRemovalUserNotice {+ count: number;+ /** 累计单条且插件名经安全过滤后非空时为插件名;其余情况为 null,只展示数量。 */+ name: string | null;+}+/** 详情额外携带经 Desktop 当前 runtime validator 验证过的完整清单。 */export interface PluginMarketDetail extends PluginMarketItem {manifest: GhostManifest;