Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 建插件第一方资格的事实供给层(已接线取事实,判据仍未接线)
fmfsaisaie823dd22e6bc
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.tsnew file mode 100644index 0000000000..037ece6033--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyFacts.test.ts@@ -0,0 +1,232 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { afterEach, describe, expect, it } from 'vitest';++import type { PluginMarketInstallationRecord } from '../../plugin-market/ledger.js';+import { createOrganizationPrefixStore } from '../../plugin-market/organizationPrefixStore.js';+import {+ loadGhostFirstPartyFactsLoader,+ type GhostFirstPartyFactsIdentity,+ type LoadGhostFirstPartyFactsLoaderOptions,+} from '../ghostFirstPartyFacts.js';+import { resolveGhostFirstPartyPrivilege } from '../ghostFirstPartyPrivilege.js';++const PERSONAL: GhostFirstPartyFactsIdentity = {+ membershipKind: 'personal',+ orgId: null,+};++const ORG_A: GhostFirstPartyFactsIdentity = {+ membershipKind: 'org',+ orgId: 'org-a',+};++const ORG_B: GhostFirstPartyFactsIdentity = {+ membershipKind: 'org',+ orgId: 'org-b',+};++const MARKET_ROW: PluginMarketInstallationRecord = {+ pluginId: 'plugin-1',+ ghostId: 'acme-tool',+ releaseId: 'release-1',+ version: '1.0.0',+ sha256: 'a'.repeat(64),+ scope: 'organization',+ organizationId: 'org-a',+ source: 'market',+ installed: true,+ updatedAt: '2026-08-21T00:00:00.000Z',+};++let tempDir: string | null = null;++afterEach(() => {+ if (tempDir) {+ fs.rmSync(tempDir, { recursive: true, force: true });+ tempDir = null;+ }+});++function loader(overrides: Partial<LoadGhostFirstPartyFactsLoaderOptions> = {}) {+ return loadGhostFirstPartyFactsLoader({+ readInstalledBuiltin: () => false,+ readMarketInstallation: () => null,+ lookupOrganizationPrefix: () => ({ kind: 'absent' }),+ ...overrides,+ });+}++describe('loadGhostFirstPartyFactsLoader', () => {+ it('gives builtin official plugins broker on a personal identity with no prefix cache', () => {+ const factsLoader = loader({+ readInstalledBuiltin: (ghostId) => ghostId === 'xd-feishu' || ghostId === 'xd-atlassian',+ lookupOrganizationPrefix: () => {+ throw new Error('prefix cache must not be required for builtin official plugins');+ },+ });++ for (const ghostId of ['xd-feishu', 'xd-atlassian']) {+ const loaded = factsLoader.load(ghostId, 'runtime', PERSONAL);+ expect(loaded.kind, ghostId).toBe('ready');+ if (loaded.kind !== 'ready') continue;+ expect(loaded.facts).toEqual({+ ghostId,+ builtin: true,+ marketRecord: null,+ currentOrganization: null,+ });+ expect(resolveGhostFirstPartyPrivilege(loaded.facts)).toEqual({+ brokerEligible: true,+ hostPrimitiveEligible: true,+ basis: 'builtin-official',+ });+ }+ });++ it('re-evaluates the current organization prefix after an org switch and keeps the previous key', () => {+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-first-party-facts-'));+ const store = createOrganizationPrefixStore(path.join(tempDir, 'organization.v1.json'));+ store.remember('org-a', 'aaa');+ store.remember('org-b', 'bbb');+ const factsLoader = loader({+ lookupOrganizationPrefix: (orgId) => store.lookup(orgId),+ });++ const orgA = factsLoader.load('aaa-tool', 'runtime', ORG_A);+ expect(orgA).toMatchObject({+ kind: 'ready',+ facts: {+ currentOrganization: { organizationId: 'org-a', pluginPrefix: 'aaa' },+ },+ });++ const orgB = factsLoader.load('bbb-tool', 'runtime', ORG_B);+ expect(orgB).toMatchObject({+ kind: 'ready',+ facts: {+ currentOrganization: { organizationId: 'org-b', pluginPrefix: 'bbb' },+ },+ });++ const orgAAgain = factsLoader.load('aaa-tool', 'runtime', ORG_A);+ expect(orgAAgain).toMatchObject({+ kind: 'ready',+ facts: {+ currentOrganization: { organizationId: 'org-a', pluginPrefix: 'aaa' },+ },+ });+ expect(store.lookup('org-a')).toEqual({ kind: 'known', pluginPrefix: 'aaa' });+ expect(store.lookup('org-b')).toEqual({ kind: 'known', pluginPrefix: 'bbb' });+ });++ it('does not synthesize pluginPrefix null when the cache is absent or unavailable', () => {+ const absent = loader({+ lookupOrganizationPrefix: () => ({ kind: 'absent' }),+ }).load('acme-tool', 'runtime', ORG_A);+ expect(absent).toEqual({+ kind: 'unavailable',+ reason: 'organization-prefix-absent',+ purpose: 'runtime',+ action: 'load-without-privilege',+ });++ const unavailable = loader({+ lookupOrganizationPrefix: () => ({ kind: 'unavailable' }),+ }).load('acme-tool', 'install', ORG_A);+ expect(unavailable).toEqual({+ kind: 'unavailable',+ reason: 'organization-prefix-unavailable',+ purpose: 'install',+ action: 'refuse-install',+ });+ });++ it('treats personal identity currentOrganization null as a determined fact', () => {+ const loaded = loader({+ lookupOrganizationPrefix: () => {+ throw new Error('personal identity must not look up an organization prefix');+ },+ }).load('local-tool', 'runtime', PERSONAL);++ expect(loaded).toEqual({+ kind: 'ready',+ facts: {+ ghostId: 'local-tool',+ builtin: false,+ marketRecord: null,+ currentOrganization: null,+ },+ });+ });++ it('keeps refuse-install vs load-without-privilege as the two fail-closed intensities', () => {+ const factsLoader = loader({+ lookupOrganizationPrefix: () => ({ kind: 'absent' }),+ });+ expect(factsLoader.load('acme-tool', 'install', ORG_A)).toMatchObject({+ kind: 'unavailable',+ action: 'refuse-install',+ });+ expect(factsLoader.load('acme-tool', 'runtime', ORG_A)).toMatchObject({+ kind: 'unavailable',+ action: 'load-without-privilege',+ });+ });++ it('treats a ledger read failure as unavailable, not marketRecord null', () => {+ const loaded = loader({+ readMarketInstallation: () => {+ throw new Error('EACCES');+ },+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),+ }).load('acme-tool', 'install', ORG_A);++ expect(loaded).toEqual({+ kind: 'unavailable',+ reason: 'market-installation-read-failed',+ purpose: 'install',+ action: 'refuse-install',+ });+ });++ it('copies a confirmed ledger miss as marketRecord null when facts are otherwise ready', () => {+ const loaded = loader({+ readMarketInstallation: () => null,+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: 'acme' }),+ }).load('acme-tool', 'runtime', ORG_A);++ expect(loaded).toEqual({+ kind: 'ready',+ facts: {+ ghostId: 'acme-tool',+ builtin: false,+ marketRecord: null,+ currentOrganization: { organizationId: 'org-a', pluginPrefix: 'acme' },+ },+ });+ });++ it('copies a known null pluginPrefix instead of treating it as absent', () => {+ const loaded = loader({+ readMarketInstallation: () => MARKET_ROW,+ lookupOrganizationPrefix: () => ({ kind: 'known', pluginPrefix: null }),+ }).load('acme-tool', 'runtime', ORG_A);++ expect(loaded).toEqual({+ kind: 'ready',+ facts: {+ ghostId: 'acme-tool',+ builtin: false,+ marketRecord: {+ scope: 'organization',+ organizationId: 'org-a',+ source: 'market',+ installed: true,+ },+ currentOrganization: { organizationId: 'org-a', pluginPrefix: null },+ },+ });+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.tsindex 5ba7ee26c0..f4e6edd438 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostFirstPartyPrivilege.test.ts@@ -66,6 +66,43 @@ describe('resolveGhostFirstPartyPrivilege', () => {}});+ // 事实供给层(`ghostFirstPartyFacts.ts` 的 `builtinOnlyFacts`)在「身份是组织、但前缀+ // 缓存取不到」时会给随包插件填 `currentOrganization: null`——那不是真事实,只是输入+ // 类型没有「是组织但前缀未知」的表示。它安全的唯一依据就是这条不变量:+ // **优先级 1 在返回前不读 `currentOrganization` 与 `marketRecord`。**+ // 这条测试就是那个填充值的护栏:哪天有人让优先级 1 开始读这两个字段,这里会红,+ // 提醒他去修供给层,而不是让一个假事实静默生效。+ it('priority 1 is independent of ledger and organization facts', () => {+ const expected = {+ brokerEligible: true,+ hostPrimitiveEligible: true,+ basis: 'builtin-official',+ };+ const ledgerShapes = [+ null,+ market({ scope: 'personal' }),+ market({ scope: 'organization', organizationId: 'org-other' }),+ market({ scope: 'public', source: 'legacy-adopted' }),+ market({ scope: 'public', installed: false }),+ ];+ const orgShapes = [+ null,+ CURRENT_ORG,+ { organizationId: 'org-acme', pluginPrefix: null },+ { organizationId: 'org-other', pluginPrefix: 'other' },+ ];+ for (const marketRecord of ledgerShapes) {+ for (const currentOrganization of orgShapes) {+ expect(+ resolveGhostFirstPartyPrivilege(+ facts({ ghostId: 'xd-feishu', builtin: true, marketRecord, currentOrganization }),+ ),+ JSON.stringify({ marketRecord, currentOrganization }),+ ).toEqual(expected);+ }+ }+ });+it('denies bundled plugins that miss the static official table, including x-manager reclaimPort', () => {for (const ghostId of BUNDLED_NON_OFFICIAL_IDS) {expect(diff --git a/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts b/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.tsnew file mode 100644index 0000000000..5c9a6ae01b--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/ghostFirstPartyFacts.ts@@ -0,0 +1,181 @@+/**+ * Assembles `GhostFirstPartyFacts` for `resolveGhostFirstPartyPrivilege`.+ *+ * This loader only collects facts. It does not grant or refuse privileges, and+ * existing `isBrokerEligibleGhostId` / `isFirstPartyHostPrivilegeGhostId` call+ * sites stay unwired.+ *+ * Do not return a bare `GhostFirstPartyFacts` object: callers must be able to+ * tell "facts are complete" from "a required fact could not be obtained".+ * `marketRecord: null` means the ledger confirmed there is no row — never+ * "the ledger could not be read".+ *+ * `currentOrganization.pluginPrefix: null` is a positive server statement+ * ("this org has no registered prefix"). Cache `absent` / `unavailable` must+ * not be folded into that shape.+ *+ * Builtin official plugins (priority 1 of the pure function) do not need the+ * organization prefix. Their conclusion stays available on a personal identity+ * and when the prefix cache has never been filled.+ */+import type { PluginMarketInstallationRecord } from '../plugin-market/ledger.js';+import type { OrganizationPrefixLookup } from '../plugin-market/organizationPrefixStore.js';+import type {+ GhostFirstPartyFacts,+ GhostFirstPartyMarketRecord,+} from './ghostFirstPartyPrivilege.js';++export type GhostFirstPartyFactsPurpose = 'install' | 'runtime';++export type GhostFirstPartyFactsUnavailableAction =+ | 'refuse-install'+ | 'load-without-privilege';++export type GhostFirstPartyFactsUnavailableReason =+ | 'installed-list-read-failed'+ | 'market-installation-read-failed'+ | 'organization-prefix-absent'+ | 'organization-prefix-unavailable';++export interface GhostFirstPartyFactsIdentity {+ membershipKind: 'personal' | 'org';+ orgId: string | null;+}++export type GhostFirstPartyFactsLoad =+ | { kind: 'ready'; facts: GhostFirstPartyFacts }+ | {+ kind: 'unavailable';+ reason: GhostFirstPartyFactsUnavailableReason;+ purpose: GhostFirstPartyFactsPurpose;+ action: GhostFirstPartyFactsUnavailableAction;+ };++export interface GhostFirstPartyFactsLoader {+ load(+ ghostId: string,+ purpose: GhostFirstPartyFactsPurpose,+ identity: GhostFirstPartyFactsIdentity,+ ): GhostFirstPartyFactsLoad;+}++export interface LoadGhostFirstPartyFactsLoaderOptions {+ readInstalledBuiltin(ghostId: string): boolean;+ readMarketInstallation(ghostId: string): PluginMarketInstallationRecord | null;+ lookupOrganizationPrefix(orgId: string): OrganizationPrefixLookup;+}++function actionFor(purpose: GhostFirstPartyFactsPurpose): GhostFirstPartyFactsUnavailableAction {+ return purpose === 'install' ? 'refuse-install' : 'load-without-privilege';+}++function toMarketRecord(+ record: PluginMarketInstallationRecord,+): GhostFirstPartyMarketRecord {+ return {+ scope: record.scope,+ organizationId: record.organizationId,+ source: record.source,+ installed: record.installed,+ };+}++export function loadGhostFirstPartyFactsLoader(+ options: LoadGhostFirstPartyFactsLoaderOptions,+): GhostFirstPartyFactsLoader {+ return {+ load(ghostId, purpose, identity) {+ const unavailable = (+ reason: GhostFirstPartyFactsUnavailableReason,+ ): GhostFirstPartyFactsLoad => ({+ kind: 'unavailable',+ reason,+ purpose,+ action: actionFor(purpose),+ });++ let builtin: boolean;+ try {+ builtin = options.readInstalledBuiltin(ghostId);+ } catch {+ return unavailable('installed-list-read-failed');+ }++ let marketRecord: GhostFirstPartyMarketRecord | null = null;+ try {+ const installation = options.readMarketInstallation(ghostId);+ marketRecord = installation ? toMarketRecord(installation) : null;+ } catch {+ // Builtin official plugins do not consult the ledger. A corrupt ledger+ // must not take away xd-feishu / xd-atlassian broker eligibility.+ if (!builtin) return unavailable('market-installation-read-failed');+ marketRecord = null;+ }++ if (identity.membershipKind !== 'org' || !identity.orgId) {+ return {+ kind: 'ready',+ facts: {+ ghostId,+ builtin,+ marketRecord,+ currentOrganization: null,+ },+ };+ }++ /**+ * 随包插件的结论不依赖组织事实,所以前缀取不到时它照旧可求值。+ *+ * ⚠️ 这里填的 `currentOrganization: null` **不是一个真事实**:当前身份确实是+ * 组织身份,只是前缀这个事实拿不到,而输入类型没有「是组织但前缀未知」这种+ * 表示(`{organizationId, pluginPrefix: null}` 的含义是「该组织确实没登记+ * 前缀」,那是服务端才能给出的正面声明,用在这里会是更严重的失真)。+ *+ * 之所以安全,靠的是一条不变量:**纯函数的优先级 1(`facts.builtin`)在返回前+ * 不读 `currentOrganization` 与 `marketRecord`。** 这条不变量已由+ * `__tests__/ghostFirstPartyPrivilege.test.ts` 里+ * 「priority 1 is independent of ledger and organization facts」钉住——+ * 哪天有人让优先级 1 开始读这两个字段,那条测试会红,+ * 提醒他这里的填充值会变成静默误报。+ */+ const builtinOnlyFacts = (): GhostFirstPartyFactsLoad => ({+ kind: 'ready',+ facts: { ghostId, builtin, marketRecord, currentOrganization: null },+ });++ let lookup: OrganizationPrefixLookup;+ try {+ lookup = options.lookupOrganizationPrefix(identity.orgId);+ } catch {+ if (builtin) return builtinOnlyFacts();+ return unavailable('organization-prefix-unavailable');+ }++ if (lookup.kind === 'known') {+ return {+ kind: 'ready',+ facts: {+ ghostId,+ builtin,+ marketRecord,+ currentOrganization: {+ organizationId: identity.orgId,+ pluginPrefix: lookup.pluginPrefix,+ },+ },+ };+ }++ // Prefix is required for non-builtin evaluation. Builtin still concludes+ // from `facts.builtin` and must not wait on a market-list cache fill.+ if (builtin) return builtinOnlyFacts();++ return unavailable(+ lookup.kind === 'absent'+ ? 'organization-prefix-absent'+ : 'organization-prefix-unavailable',+ );+ },+ };+}diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 408be208d7..60257137d2 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -280,6 +280,12 @@ import {loadConnectionAudienceResolver,type ConnectionAudienceResolver,} from './connectionAudienceResolver.js';+import {+ loadGhostFirstPartyFactsLoader,+ type GhostFirstPartyFactsLoader,+ type GhostFirstPartyFactsLoad,+ type GhostFirstPartyFactsPurpose,+} from './ghostFirstPartyFacts.js';import { ConnectionTokenProvider, type IssuedConnectionToken } from './connectionTokenProvider.js';import { GhostFsSlot } from './fsSlot.js';import { GhostLibrarySlot } from './librarySlot.js';@@ -300,6 +306,7 @@ import {PluginMarketLedger,type PluginMarketInstallationRecord,} from '../plugin-market/ledger.js';+import { createOrganizationPrefixStore } from '../plugin-market/organizationPrefixStore.js';import {GhostSubscriptionGateway,GhostActivityTracker,@@ -2519,6 +2526,7 @@ let notifySlotSingleton: GhostNotifySlot | null = null;let connectionAudienceResolverSingleton: ConnectionAudienceResolver | null = null;let connectionTokenProviderSingleton: ConnectionTokenProvider | null = null;let pluginMarketLedgerSingleton: PluginMarketLedger | null = null;+let ghostFirstPartyFactsLoaderSingleton: GhostFirstPartyFactsLoader | null = null;function getPluginMarketLedger(): PluginMarketLedger {if (!pluginMarketLedgerSingleton) {@@ -2567,6 +2575,45 @@ function resolveConnectionAudienceForGhost(ghostId: string): ConnectionAudienceR});}+function getGhostFirstPartyFactsLoader(): GhostFirstPartyFactsLoader {+ if (!ghostFirstPartyFactsLoaderSingleton) {+ ghostFirstPartyFactsLoaderSingleton = loadGhostFirstPartyFactsLoader({+ readInstalledBuiltin: (ghostId) =>+ getGhostManager().list().find((candidate) => candidate.manifest.id === ghostId)?.builtin ===+ true,+ readMarketInstallation: (ghostId) => getPluginMarketLedger().installationForGhost(ghostId),+ lookupOrganizationPrefix: (orgId) =>+ createOrganizationPrefixStore(+ ownerScopedUserDataPath('plugin-market', 'organization.v1.json'),+ ).lookup(orgId),+ });+ }+ return ghostFirstPartyFactsLoaderSingleton;+}++/**+ * 每次调用都重新求值,不做任何缓存或作废——身份变更靠重新求值生效,+ * 不要在这里造平行的失效状态机(AGENTS.md 硬规则)。+ *+ * **为什么不需要额外检查 `isAppSessionBoundaryPending()`**:切身份的窗口期里+ * `getAuthState()` 与 owner 分域路径可能短暂不同步,但前缀缓存是「owner 分域的文件+ * × 文件内按 orgId 分键」的双键结构,任一侧不同步的结果都是查不到那个键+ * (`absent`)而不是查到别人的前缀——方向是 fail-closed。同账号内切组织时文件同一份、+ * 键各自独立,落后一拍只会拿到旧组织的前缀,随后被判据要求「台账 organizationId 与+ * 当前组织一致」挡掉。所以这里刻意不加闸,别补。+ */+export function loadGhostFirstPartyFactsForGhost(+ ghostId: string,+ purpose: GhostFirstPartyFactsPurpose,+): GhostFirstPartyFactsLoad {+ const state = getAuthState();+ const user = state.isAuthenticated ? state.user : null;+ return getGhostFirstPartyFactsLoader().load(ghostId, purpose, {+ membershipKind: user?.membershipKind ?? 'personal',+ orgId: user?.orgId ?? null,+ });+}+/** Main-memory-only Connection token issuer/cache. */export function getConnectionTokenProvider(): ConnectionTokenProvider {if (!connectionTokenProviderSingleton) {diff --git a/apps/desktop/src/main/plugin-market/__tests__/api.test.ts b/apps/desktop/src/main/plugin-market/__tests__/api.test.tsindex 07310109f5..ddbf540f9e 100644--- a/apps/desktop/src/main/plugin-market/__tests__/api.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/api.test.ts@@ -161,4 +161,59 @@ describe('PluginMarketApi', () => {await expect(api.listAll()).rejects.toThrow('游标未前进');});++ it('surfaces currentOrganization from the completed list response', async () => {+ const fetcher = pagedFetcher(+ {+ plugins: [summary(PLUGIN_A, 'alpha')],+ nextCursor: PLUGIN_A,+ currentOrganization: { organizationId: 'org-acme', pluginPrefix: 'acme' },+ },+ {+ plugins: [summary(PLUGIN_B, 'beta')],+ nextCursor: null,+ currentOrganization: { organizationId: 'org-acme', pluginPrefix: 'acme' },+ },+ );++ await expect(new PluginMarketApi(fetcher).listAll()).resolves.toMatchObject({+ plugins: [{ id: PLUGIN_A }, { id: PLUGIN_B }],+ currentOrganization: { organizationId: 'org-acme', pluginPrefix: 'acme' },+ });+ });++ // 服务端是否每页都重复下发 currentOrganization 没有写进契约。若它只在首页带,+ // 逐页覆盖会让后续页的 null 抹掉身份事实,多页目录的组织就永远缓存不到前缀。+ // 上面那条用例两页都带了值,所以在"每页重复"的假设下必过、抓不到这个问题。+ it('keeps the first non-null currentOrganization across later pages that omit it', async () => {+ const fetcher = pagedFetcher(+ {+ plugins: [summary(PLUGIN_A, 'alpha')],+ nextCursor: PLUGIN_A,+ currentOrganization: { organizationId: 'org-acme', pluginPrefix: 'acme' },+ },+ {+ plugins: [summary(PLUGIN_B, 'beta')],+ nextCursor: null,+ currentOrganization: null,+ },+ );++ await expect(new PluginMarketApi(fetcher).listAll()).resolves.toMatchObject({+ plugins: [{ id: PLUGIN_A }, { id: PLUGIN_B }],+ currentOrganization: { organizationId: 'org-acme', pluginPrefix: 'acme' },+ });+ });++ it('keeps a null currentOrganization as a personal-identity fact', async () => {+ const fetcher = pagedFetcher({+ plugins: [summary(PLUGIN_A, 'alpha')],+ nextCursor: null,+ currentOrganization: null,+ });++ await expect(new PluginMarketApi(fetcher).listAll()).resolves.toMatchObject({+ currentOrganization: null,+ });+ });});diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex af28813734..bcfce87670 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -103,6 +103,7 @@ import {} from '../ledger';import { PluginMarketService } from '../service';import type { PluginMarketApi } from '../api';+import { createOrganizationPrefixStore } from '../organizationPrefixStore';const roots: string[] = [];const PLUGIN_ID = `c${'a'.repeat(24)}`;@@ -252,7 +253,13 @@ function harness(items: VisiblePluginSummary[], removals: PluginRemovalNotice[]roots.push(root);const ledger = new PluginMarketLedger(path.join(root, 'ledger.json'));const api = {- listAll: vi.fn(async () => ({ plugins: items, removals })),+ listAll: vi.fn(+ async (): Promise<Awaited<ReturnType<PluginMarketApi['listAll']>>> => ({+ plugins: items,+ removals,+ currentOrganization: null,+ }),+ ),detail: vi.fn(async (pluginId: string): Promise<VisiblePluginDetail> => {const item = items.find((candidate) => candidate.id === pluginId);if (!item) throw new Error('not found');@@ -347,6 +354,29 @@ describe('PluginMarketService migration and defaultInstall', () => {expect(runtime.install).not.toHaveBeenCalled();});+ it('remembers the listed organization prefix after a successful snapshot', async () => {+ const item = summary();+ const h = harness([item]);+ const prefixRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-org-prefix-service-'));+ roots.push(prefixRoot);+ const { ownerScopedUserDataPath } = await import('../../appSessionState.js');+ vi.mocked(ownerScopedUserDataPath).mockImplementation((...parts: string[]) =>+ path.join(prefixRoot, ...parts),+ );+ h.api.listAll.mockResolvedValue({+ plugins: [item],+ removals: [],+ currentOrganization: { organizationId: 'org-acme', pluginPrefix: 'acme' },+ });++ await h.service.snapshot();++ const store = createOrganizationPrefixStore(+ path.join(prefixRoot, 'plugin-market', 'organization.v1.json'),+ );+ expect(store.lookup('org-acme')).toEqual({ kind: 'known', pluginPrefix: 'acme' });+ });+it('passes the optional release icon metadata to renderer-safe market items', async () => {const icon = {mimeType: 'image/png',diff --git a/apps/desktop/src/main/plugin-market/api.ts b/apps/desktop/src/main/plugin-market/api.tsindex 969ee4926b..ef2c98f991 100644--- a/apps/desktop/src/main/plugin-market/api.ts+++ b/apps/desktop/src/main/plugin-market/api.ts@@ -49,9 +49,10 @@ export class PluginMarketApi {async listAll(query?: string,- ): Promise<Pick<ListPluginsResponse, 'plugins' | 'removals'>> {+ ): Promise<Pick<ListPluginsResponse, 'plugins' | 'removals' | 'currentOrganization'>> {const plugins: ListPluginsResponse['plugins'] = [];const removalsByPluginId = new Map<string, PluginRemovalNotice>();+ let currentOrganization: ListPluginsResponse['currentOrganization'] = null;let cursor: string | null = null;const seen = new Set<string>();for (let page = 0; page < 100; page += 1) {@@ -74,6 +75,11 @@ export class PluginMarketApi {removalsByPluginId.set(removal.pluginId, removal);}}+ // 取**第一个非 null** 的值,不要每页覆盖。服务端是否每页都重复下发+ // `currentOrganization` 并没有写进契约(PLAN §6 没有这一条),若它只在首页带,+ // 逐页覆盖会让第二页的 null 把身份事实抹掉——多页目录的组织就永远缓存不到前缀。+ // 两种服务端行为下这个写法都对,且结果确定。+ currentOrganization ??= response.currentOrganization;if (!response.nextCursor) {// 在架优先(契约:通告与**任一页** plugins 有交集即作废)的作用域是// 未经 owner 过滤的完整目录,必须留在聚合层;挪到 service 的 owner@@ -85,7 +91,7 @@ export class PluginMarketApi {});return false;});- return { plugins, removals };+ return { plugins, removals, currentOrganization };}if (response.nextCursor === cursor) throw new Error('Plugin 市场分页游标未前进');cursor = response.nextCursor;diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex 975d5c131c..09e752a8d5 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -5,6 +5,7 @@ import crypto from 'node:crypto';import {isValidPluginResourceId,supportsCindyVersion,+ type PluginCurrentOrganization,type PluginRemovalNotice,type VisiblePluginDetail,type VisiblePluginSummary,@@ -80,6 +81,7 @@ import { readInstalledGhostManifest } from '../installedGhostManifest.js';import { withGhostInstallLock } from '../cindy-brain/ghostInstallLock.js';import { GhostPackagePermissionReviewRequiredError } from '../cindy-brain/packagePermissionReview.js';import { PluginMarketApi } from './api.js';+import { createOrganizationPrefixStore } from './organizationPrefixStore.js';import { downloadVerifiedPlugin } from './download.js';import { installCustomMarketPlugin } from './install.js';import {@@ -599,12 +601,14 @@ export class PluginMarketService {}let plugins: VisiblePluginSummary[];let removals: PluginRemovalNotice[];+ let currentOrganization: PluginCurrentOrganization | null | undefined;let customDiscovery: CustomMarketDiscovery;try {// 官方目录与自定义发现并行;单个本地/网络盘来源卡顿不会串行拖住官方请求。const [catalog, discovered] = await Promise.all([this.api.listAll(), customDiscoveryPromise]);plugins = visiblePluginsForOwner(owner, catalog.plugins);removals = catalog.removals;+ currentOrganization = catalog.currentOrganization;customDiscovery = discovered;} catch (error) {log.warn('market list unavailable', {@@ -623,6 +627,7 @@ export class PluginMarketService {}requireSameMarketOwner(owner);+ this.rememberCurrentOrganization(currentOrganization);const ledger = this.ledgerForOwner(owner);await this.adoptLegacyInstallations(plugins, ledger, owner);await this.recoverDisconnectedMarketInstallations(plugins, ledger, owner);@@ -790,8 +795,10 @@ export class PluginMarketService {// 本地(免账号)模式只对 public 插件暴露详情;目录 summary 也是 detail 身份// 绑定的依据,服务端返回的 id/ghostId/scope 与请求不一致时必须拒,防止把// A 的详情内容(含权限清单)呈现给请求 B 的 Renderer。- const catalog = visiblePluginsForOwner(owner, (await this.api.listAll()).plugins);+ const listed = await this.api.listAll();requireSameMarketOwner(owner);+ this.rememberCurrentOrganization(listed.currentOrganization);+ const catalog = visiblePluginsForOwner(owner, listed.plugins);const summary = catalog.find((candidate) => candidate.id === pluginId);if (!summary) {throwIpcError('NOT_FOUND', 'Plugin is unavailable to the active account');@@ -986,8 +993,10 @@ export class PluginMarketService {// 可见性的条目在调用 detail 之前就要拒掉,不能把组织私有插件的详情拉下来。// 目录 summary 也是 detail 身份绑定的依据:detail 自报的 id/ghostId/scope/// 发布必须与用户确认时看到的那份 summary 一致,否则 A 的确认会被导向 B 的内容。- const catalog = visiblePluginsForOwner(owner, (await this.api.listAll()).plugins);+ const listed = await this.api.listAll();requireSameMarketOwner(owner);+ this.rememberCurrentOrganization(listed.currentOrganization);+ const catalog = visiblePluginsForOwner(owner, listed.plugins);const selected = catalog.find((candidate) => candidate.id === pluginId);if (!selected) {throwIpcError('NOT_FOUND', 'Plugin is unavailable to the active account');@@ -2663,6 +2672,22 @@ export class PluginMarketService {return this.ledger.bind(ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'));}+ /**+ * Persist the org plugin prefix from a successful market list.+ * Call only after `requireSameMarketOwner`, so the owner-scoped path matches+ * the identity that received this list. Personal / unsigned lists send+ * `currentOrganization: null` and are a no-op — they must not synthesize+ * `pluginPrefix: null` for an org that was never listed.+ */+ private rememberCurrentOrganization(+ currentOrganization: PluginCurrentOrganization | null | undefined,+ ): void {+ if (!currentOrganization) return;+ createOrganizationPrefixStore(+ ownerScopedUserDataPath('plugin-market', 'organization.v1.json'),+ ).remember(currentOrganization.organizationId, currentOrganization.pluginPrefix);+ }+private withLedgerMutation<T>(owner: ActiveAppSession,operation: () => T | Promise<T>,