Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): integrate plugin marketplace (#256)
xxxcc0339f94f74f6
diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 9e03c8e0e8..89b6cd58d4 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -44,6 +44,7 @@"license": "Apache-2.0","dependencies": {"@cindy/auth-client": "workspace:*",+ "@cindy/plugin-protocol": "workspace:*","@cindy/slack-hook-protocol": "workspace:*","@codemirror/commands": "^6.10.3","@codemirror/lang-cpp": "^6.0.3",diff --git a/apps/desktop/src/main/__tests__/authAccountDeletionLifecycle.test.ts b/apps/desktop/src/main/__tests__/authAccountDeletionLifecycle.test.tsindex a665140d03..45613aa60f 100644--- a/apps/desktop/src/main/__tests__/authAccountDeletionLifecycle.test.ts+++ b/apps/desktop/src/main/__tests__/authAccountDeletionLifecycle.test.ts@@ -78,10 +78,10 @@ describe('desktop auth account-deletion lifecycle', () => {expect(body).toContain('if (sessionInvalidationPromise) return sessionInvalidationPromise;');expect(body).toContain('await authSessionTeardown(reason);');expect(body).toContain('closeLocalDb();');- expect(body).toContain('clearAuth({ notify: false });');+ expect(body).toContain('clearAuth({ notify: false, deferSessionCommit: true });');expect(body).toContain('notifyAuthListeners();');expect(body).toContain('notifySessionExpired(');- expect(body.indexOf('clearAuth({ notify: false });')).toBeLessThan(+ expect(body.indexOf('clearAuth({ notify: false, deferSessionCommit: true });')).toBeLessThan(body.indexOf('notifySessionExpired('),);});diff --git a/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts b/apps/desktop/src/main/__tests__/clientEndpointsService.test.tsindex 01a37c4bd3..fb3e473e9f 100644--- a/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts+++ b/apps/desktop/src/main/__tests__/clientEndpointsService.test.ts@@ -54,6 +54,7 @@ const FULL_MANIFEST = JSON.stringify({voiceApiBaseUrl: 'https://voice.remote.example.com',githubApiBaseUrl: 'https://github-api.remote.example.com',skillhubApiBaseUrl: 'https://skillhub.remote.example.com',+ pluginApiBaseUrl: 'https://plugin.remote.example.com',cdnBaseUrl: 'https://cdn.remote.example.com/app',mobileUpdateBaseUrl: 'https://mobile-update.remote.example.com',});diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex 12c02a6f25..55a148a5cd 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -944,6 +944,13 @@ function clearAuth(* removeSafe 会把别人的新 token 删掉,把对方也踢成半死。*/preservePersistedRefreshToken?: boolean;+ /**+ * Clear auth fields immediately, but defer publishing the signed-out+ * owner until the enclosing teardown completes. Owner-bound consumers are+ * blocked while the boundary is pending so they cannot enter a temporary+ * namespace during teardown.+ */+ deferSessionCommit?: boolean;} = {},): void {const notify = opts.notify ?? true;@@ -973,7 +980,9 @@ function clearAuth(// 串号边界改由 login / 冷启动时 providerSecretStore.reconcileOwner 处理:owner 变了才清。// clearAuth 必须保持同步(大量调用方依赖立即 notify),但 promise rejection 仍要吞掉并记日志。clearPerAccountIntegrationsInBackground();- commitActiveAppSession(opts.nextMode ?? 'signed-out');+ if (!opts.deferSessionCommit) {+ commitActiveAppSession(opts.nextMode ?? 'signed-out');+ }if (notify) {notifyRenderer();notifyAuthListeners();@@ -994,7 +1003,11 @@ async function expireRuntimeAuth(): Promise<void> {const releaseBoundary = beginAppSessionBoundary();notifyRendererAuthBoundaryPending();- clearAuth({ notify: false, preservePersistedRefreshToken: opts.preservePersistedRefreshToken });+ clearAuth({+ notify: false,+ preservePersistedRefreshToken: opts.preservePersistedRefreshToken,+ deferSessionCommit: true,+ });try {if (accountSwitchTeardown) {await accountSwitchTeardown({ previousUserId, nextUserId: 'signed-out' });@@ -1012,6 +1025,7 @@ async function expireRuntimeAuth(} catch (err) {log.error('closeLocalDb on runtime auth expiry failed', err);} finally {+ commitActiveAppSession('signed-out');releaseBoundary();notifyRenderer();notifyAuthListeners();@@ -1032,6 +1046,7 @@ export function invalidateSession(reason: string): Promise<void> {// published and credentials can be cleared synchronously first. API calls// that detect the rejection may themselves run inside a scheduler/service// being torn down; they must be able to unwind without a stop-await cycle.+ const releaseBoundary = beginAppSessionBoundary();const run = Promise.resolve().then(async () => {try {if (authSessionTeardown) {@@ -1048,13 +1063,16 @@ export function invalidateSession(reason: string): Promise<void> {closeLocalDb();} catch (error) {log.error(`closeLocalDb on ${reason} failed (non-fatal)`, error);+ } finally {+ commitActiveAppSession('signed-out');+ releaseBoundary();}});sessionInvalidationPromise = run;// Keep the current renderer surface in place until its session-expired// dialog is acknowledged. Main-process consumers still need the immediate// logged-out transition so no account-scoped work can restart meanwhile.- clearAuth({ notify: false });+ clearAuth({ notify: false, deferSessionCommit: true });notifyAuthListeners();// invalidateSession 的 reason 是调用方语境串而非服务端失效码,这里只把// 「账号不可用」显式归类,其余统一走通用过期文案。diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex b6e30625ae..2d9cd27055 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -532,7 +532,12 @@ import {} from './app-shortcuts/index.js';import { installNewMakerWindowShortcut } from './app-shortcuts/new-maker-window-shortcut.js';import { registerLayoutIpc } from './layout/index.js';-import { registerGhostIpc, suspendAllGhosts } from './cindy-brain/index.js';+import {+ registerGhostIpc,+ suspendAllGhosts,+ waitForGhostMutations,+} from './cindy-brain/index.js';+import { registerPluginMarketIpc } from './plugin-market/registerIpc.js';import { findCindyFileInArgv } from './cindy-brain/argv.js';import { handleIncomingCindyFile } from './cindy-brain/openFileInstall.js';import { registerCindyFileAssociation } from './cindy-brain/fileAssociation.js';@@ -795,6 +800,7 @@ async function teardownAuthAccountBoundary(reason: string): Promise<void> {// Every Ghost sandbox can retain live OAuth, subscription, or in-memory// state. Stop them before changing owners; resident Ghosts are recreated by// the auth-change activation pass after the new boundary is committed.+ await waitForGhostMutations();suspendAllGhosts();// Personal IM channels have the same DB boundary. Relogin restarts them via// app:ready-for-bot after the new DbClient is ready.@@ -1014,6 +1020,7 @@ registerLayoutIpc();// renderer 首帧 sendSync 拉已装意识清单(意识面板与内置面板同帧注册,规则 7// 无跳变)、install/uninstall 写路径、changed 广播。见 main/cindy-brain/。registerGhostIpc();+registerPluginMarketIpc();// ── Custom protocol registration (image-local-cache M2) ──────────────────// MUST run before app.whenReady(), and MUST be a SINGLE call:diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostMutationCoordinator.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostMutationCoordinator.test.tsnew file mode 100644index 0000000000..bfcbe056b4--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostMutationCoordinator.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';++import { GhostMutationCoordinator } from '../ghostMutationCoordinator';++describe('GhostMutationCoordinator', () => {+ it('waits for every active mutation before becoming idle', async () => {+ const coordinator = new GhostMutationCoordinator();+ const releaseA = coordinator.acquire();+ const releaseB = coordinator.acquire();+ let drained = false;+ const waiting = coordinator.waitForIdle().then(() => {+ drained = true;+ });++ await Promise.resolve();+ expect(drained).toBe(false);+ releaseA();+ await Promise.resolve();+ expect(drained).toBe(false);+ releaseB();+ await waiting;+ expect(drained).toBe(true);+ });++ it('makes release idempotent and allows a later mutation', async () => {+ const coordinator = new GhostMutationCoordinator();+ const release = coordinator.acquire();+ release();+ release();+ await coordinator.waitForIdle();++ const releaseLater = coordinator.acquire();+ const waiting = coordinator.waitForIdle();+ releaseLater();+ await waiting;+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.tsnew file mode 100644index 0000000000..6bd7f1f77c--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts@@ -0,0 +1,62 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++import { describe, expect, it } from 'vitest';++/**+ * Regression guards for the market Node-authorization/session-switch race.+ * cindy-brain/index.ts depends on Electron process state and is not safe to+ * import in the Node test environment, so this follows the repository's+ * established source-contract test pattern for main-process auth boundaries.+ */+describe('market Ghost session boundary', () => {+ const source = readFileSync(+ resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');++ it('requires the pre-approval session generation when acquiring the mutation lease', () => {+ const captureStart = source.indexOf(+ 'function captureGhostMutationOwner(): ActiveAppSession {',+ );+ const captureEnd = source.indexOf('\n}\n', captureStart);+ const captureBody = source.slice(captureStart, captureEnd);+ expect(captureBody).toContain('isAppSessionBoundaryPending()');+ expect(captureBody).toContain('return getActiveAppSession();');++ const leaseStart = source.indexOf(+ 'function beginGhostMutation(expectedOwner?: ActiveAppSession): () => void {',+ );+ const leaseEnd = source.indexOf('\n}\n', leaseStart);+ const leaseBody = source.slice(leaseStart, leaseEnd);+ expect(leaseBody).toContain('isAppSessionBoundaryPending()');+ expect(leaseBody).toContain('currentOwner.mode !== expectedOwner.mode');+ expect(leaseBody).toContain('currentOwner.dataOwnerId !== expectedOwner.dataOwnerId');+ expect(leaseBody).toContain('currentOwner.generation !== expectedOwner.generation');+ });++ it('captures before async inspection but leases only after Node authorization', () => {+ const installStart = source.indexOf(+ 'export async function installOrUpdateMarketGhostPackage(',+ );+ const installEnd = source.indexOf(+ '\n}\n\ntype GhostUninstallLedgerCompletion',+ installStart,+ );+ const body = source.slice(installStart, installEnd);++ const captureIndex = body.indexOf(+ 'const mutationOwner = captureGhostMutationOwner();',+ );+ const inspectIndex = body.indexOf('await manager.inspect(cindyFilePath)');+ const authorizationIndex = body.indexOf('await requestNodeInstallAuthorization(');+ const leaseIndex = body.indexOf(+ 'releaseMutation = beginGhostMutation(mutationOwner);',+ );++ expect(captureIndex).toBeGreaterThan(-1);+ expect(captureIndex).toBeLessThan(inspectIndex);+ expect(authorizationIndex).toBeLessThan(leaseIndex);+ expect(body).toContain('releaseMutation?.();');+ });+});diff --git a/apps/desktop/src/main/cindy-brain/ghostMutationCoordinator.ts b/apps/desktop/src/main/cindy-brain/ghostMutationCoordinator.tsnew file mode 100644index 0000000000..04917b9e7f--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/ghostMutationCoordinator.ts@@ -0,0 +1,38 @@+/**+ * Coordinates account-bound Ghost filesystem mutations with session teardown.+ *+ * A mutation lease keeps the active owner stable until all package and host+ * data cleanup has completed. Session teardown waits for the leases before it+ * clears the Ghost root cache and commits a new owner.+ */+export class GhostMutationCoordinator {+ private active = 0;+ private drainPromise: Promise<void> | null = null;+ private resolveDrain: (() => void) | null = null;++ acquire(): () => void {+ if (this.active === 0) {+ this.drainPromise = new Promise<void>((resolve) => {+ this.resolveDrain = resolve;+ });+ }+ this.active += 1;+ let released = false;+ return () => {+ if (released) return;+ released = true;+ this.active -= 1;+ if (this.active === 0) {+ this.resolveDrain?.();+ this.resolveDrain = null;+ this.drainPromise = null;+ }+ };+ }++ async waitForIdle(): Promise<void> {+ while (this.active > 0) {+ await this.drainPromise;+ }+ }+}diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 676fb21f37..b4da660b82 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -22,8 +22,15 @@ import {type InstalledGhost,} from '../../shared/ghost.js';import { getAppCapabilities } from '../appCapabilities.js';+import {+ getActiveAppSession,+ isAppSessionBoundaryPending,+ ownerScopedUserDataPath,+ type ActiveAppSession,+} from '../appSessionState.js';import { getLayoutStore } from '../layout/index.js';import { GhostManager, type InstallRejection, type UninstallRejection } from './GhostManager.js';+import { GhostMutationCoordinator } from './ghostMutationCoordinator.js';import {clearBuiltinTombstone,listBuiltinSeedIds,@@ -162,7 +169,6 @@ import { recordGhostCallMedia } from './ghostMediaLedger.js';import { getDbClient } from '../localDb/client/current.js';import * as localDbSchema from '../localDb/schema.js';import { eq } from 'drizzle-orm';-import { getActiveAppSession, ownerScopedUserDataPath } from '../appSessionState.js';import { requireAppCapability } from '../appCapabilities.js';import { hasLegacyOwnerNamespaceClaim } from '../ownerNamespaceMigration.js';@@ -194,6 +200,46 @@ function currentGhostAppContext() {}let managerSingleton: GhostManager | null = null;+const ghostMutationCoordinator = new GhostMutationCoordinator();++/**+ * Capture the stable owner before a mutation performs any asynchronous+ * preparation that cannot safely hold a lease (for example, user approval).+ */+function captureGhostMutationOwner(): ActiveAppSession {+ if (isAppSessionBoundaryPending()) {+ throw new Error('账号切换中,已取消本次 Plugin 操作');+ }+ return getActiveAppSession();+}++/**+ * Acquire a lease for a market/local Ghost filesystem mutation. When an owner+ * was captured before asynchronous preparation, generation equality prevents+ * a completed account switch from turning a stale approval into a mutation for+ * the new owner. New leases also fail closed while a boundary is still active.+ */+function beginGhostMutation(expectedOwner?: ActiveAppSession): () => void {+ if (isAppSessionBoundaryPending()) {+ throw new Error('账号切换中,已取消本次 Plugin 操作');+ }+ if (expectedOwner) {+ const currentOwner = getActiveAppSession();+ if (+ currentOwner.mode !== expectedOwner.mode ||+ currentOwner.dataOwnerId !== expectedOwner.dataOwnerId ||+ currentOwner.generation !== expectedOwner.generation+ ) {+ throw new Error('账号已切换,已取消本次 Plugin 操作');+ }+ }+ return ghostMutationCoordinator.acquire();+}++/** Wait until all owner-bound Ghost filesystem mutations have finished. */+export function waitForGhostMutations(): Promise<void> {+ return ghostMutationCoordinator.waitForIdle();+}/** Account-managed built-ins are unavailable outside a verified cloud session. */export function isGhostAvailableForActiveSession(id: string): boolean {@@ -1769,6 +1815,199 @@ export async function installAndDock(return result.ghost;}+/**+ * Plugin 市场专用装入入口。市场包已由 plugin-server 绑定到稳定 Plugin ID,+ * 因而允许官方保留前缀;本地文件入口仍继续走 rejectReservedGhostId。+ * tokenBroker 门控、原子换目录、布局停靠与运行时重启保持和本地安装一致。+ */+export async function installOrUpdateMarketGhostPackage(+ cindyFilePath: string,+ expected: {+ ghostId: string;+ version: string;+ initiallyEnabled?: boolean;+ nodeAuthorizationWebContents?: WebContents;+ },+): Promise<InstalledGhost> {+ const mutationOwner = captureGhostMutationOwner();+ let releaseMutation: (() => void) | null = null;+ try {+ const manager = getGhostManager();+ const inspected = await manager.inspect(cindyFilePath);+ if ('rejection' in inspected) throwInstallError(inspected.rejection);+ if (+ inspected.manifest.id !== expected.ghostId ||+ inspected.manifest.version !== expected.version+ ) {+ throwIpcError(+ 'GHOST_FILE_INVALID',+ '下载包清单与市场 Release 不一致',+ );+ }+ requireGhostAvailableForActiveSession(expected.ghostId);+ rejectUnauthorizedTokenBroker(inspected.manifest);++ const installed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);+ if (inspected.manifest.node) {+ const sender = expected.nodeAuthorizationWebContents;+ if (+ !sender ||+ !(await requestNodeInstallAuthorization(+ sender,+ inspected.manifest,+ installed ? 'update' : 'install',+ ))+ ) {+ throwIpcError(+ 'PERMISSION_DENIED',+ sender+ ? '用户取消了 Node Plugin 安装授权'+ : 'Node Plugin 需要用户显式授权,不能自动安装',+ );+ }+ }+ // Hold the owner-stability lease only for the actual Ghost filesystem+ // mutation. Node authorization is an unbounded user interaction; keeping+ // the lease across it would block account teardown indefinitely if the+ // dialog is left unanswered.+ releaseMutation = beginGhostMutation(mutationOwner);+ if (!installed) {+ // defaultInstall 首次装入即启用;手动市场安装仍保持沉睡,等待用户主动开启。+ return installAndDock(manager, cindyFilePath, {+ enable: expected.initiallyEnabled === true,+ });+ }++ const runtime = getGhostRuntime();+ runtime.stop(expected.ghostId);+ getGhostNodeRuntimeBroker().stop(expected.ghostId);+ getGhostAgentSlot().clearGhost(expected.ghostId);+ let result: Awaited<ReturnType<typeof manager.update>>;+ try {+ result = await manager.update(cindyFilePath);+ } catch (error) {+ spawnIfResident(installed);+ throw error;+ }+ if ('rejection' in result) {+ spawnIfResident(installed);+ throwInstallError(result.rejection);+ }+ runtime.resetFuse(expected.ghostId);+ const store = getLayoutStore();+ const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);+ if (docked) {+ const applied = store.setLayout(docked);+ if ('rejection' in applied) {+ log.warn('market ghost panel dock rejected', {+ id: result.ghost.manifest.id,+ reason: applied.rejection,+ });+ }+ }+ spawnIfResident(result.ghost);+ return result.ghost;+ } finally {+ releaseMutation?.();+ }+}++type GhostUninstallLedgerCompletion = () => Promise<void>;+type GhostUninstallLedgerPreparer = (+ ghostId: string,+) => GhostUninstallLedgerCompletion | null;++let prepareGhostUninstallLedgerCompletion: GhostUninstallLedgerPreparer | null = null;++/**+ * 由 Plugin Market 在 IPC 注册期注入账本桥接,保持 cindy-brain 不反向依赖+ * 市场服务。preparer 在卸载开始前捕获 owner,返回的 completion 只在卸载成功后执行。+ */+export function setGhostUninstallLedgerPreparer(+ preparer: GhostUninstallLedgerPreparer,+): void {+ prepareGhostUninstallLedgerCompletion = preparer;+}++/**+ * 卸载一张意识并清理其宿主侧凭证、KV、私有文件与最近使用记录。+ * Plugin 市场和本地插件页共用;本地入口还会在成功后同步市场账本。+ */+export async function uninstallGhostAndCleanup(+ id: string,+ options?: { skipMarketLedger?: boolean },+): Promise<void> {+ const releaseMutation = beginGhostMutation();+ try {+ requireGhostAvailableForActiveSession(id);+ const completeLedger =+ options?.skipMarketLedger === true+ ? null+ : (prepareGhostUninstallLedgerCompletion?.(id) ?? null);+ const manager = getGhostManager();+ const runtime = getGhostRuntime();+ runtime.stop(id);+ getGhostNodeRuntimeBroker().stop(id);+ getGhostAgentSlot().clearGhost(id);+ getGhostSubscriptionGateway().dropGhost(id);+ const result = await manager.uninstall(id, { notify: false });+ if ('rejection' in result) throwUninstallError(result.rejection);+ removeGhostSecrets(id);+ removeGhostKvBestEffort(+ createGhostKvStore({+ getRootDir: () => ownerScopedUserDataPath('ghost-kv'),+ log,+ }),+ id,+ log,+ );+ if (isValidGhostId(id)) {+ try {+ await fs.promises.rm(ownerScopedUserDataPath('ghost-fs', id), {+ recursive: true,+ force: true,+ });+ } catch (err) {+ log.warn('ghost-fs 私有目录回收失败', {+ id,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+ if (listBuiltinSeedIds(builtinSeedRootDirs()).includes(id)) {+ recordBuiltinTombstone(brainRootDir(), id, log);+ }+ let recentIds: string[] | null = null;+ try {+ recentIds = forgetGhostRecentUsage(id);+ } catch (error) {+ log.warn('ghost recent usage 清理失败', {+ id,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ broadcastGhostsChanged(manager.list());+ if (recentIds) broadcastGhostRecentUsageChanged(recentIds);+ try {+ await completeLedger?.();+ } catch (error) {+ // The package is already gone; a session switch must not report uninstall+ // as failed. The next market snapshot reconciles the ledger conservatively.+ log.warn('market ledger uninstall reconciliation deferred', {+ id,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ } finally {+ releaseMutation();+ }+}++/** 市场默认安装必须尊重用户对内置插件的显式卸载选择。 */+export function isBuiltinGhostRemovedByUser(id: string): boolean {+ return readBuiltinTombstones(brainRootDir()).includes(id);+}+/*** launch: 'resident' 的意识在"唤醒且在场"时保持电子脑常驻——本函数是所有* "该在场了"时机的统一入口(应用启动扫描 / 装入即开 / 唤醒 / 更新换代后)。@@ -2639,48 +2878,7 @@ export function registerGhostIpc(): void {if (typeof id !== 'string' || id.trim().length === 0) {throwIpcError('INVALID_PARAMS', 'id must be a non-empty string');}- requireGhostAvailableForActiveSession(id);- runtime.stop(id); // 抽离先熄灯,再删目录- getGhostNodeRuntimeBroker().stop(id); // Node 同步停掉,不留安装目录使用者- getGhostAgentSlot().clearGhost(id); // 会话关联随抽离清零,防止重装后权限残留- getGhostSubscriptionGateway().dropGhost(id); // 订阅态随抽离清零- // GhostManager 先只删目录;内置 tombstone 与 host 清理完成后再- // 只广播一次一致快照,避免详情页中途掉回列表且无恢复入口。- const result = await manager.uninstall(id, { notify: false });- if ('rejection' in result) throwUninstallError(result.rejection);- // network 槽凭证随抽离清空(按前缀扫,含旧版本声明过的孤儿键;幂等)。- removeGhostSecrets(id);- // 自定义参数 KV 同点位清除(卸下即清、沉睡保留;幂等)。- removeGhostKvBestEffort(ghostKv, id, log);- // fs 槽私有数据目录随抽离整体回收(卸下即清、沉睡保留;best-effort,- // 失败只 warn——目录被占用不该卡死卸载流程)。id 先过形状闸,防拼路径。- if (isValidGhostId(id)) {- try {- await fs.promises.rm(ownerScopedUserDataPath('ghost-fs', id), {- recursive: true,- force: true,- });- } catch (err) {- log.warn('ghost-fs 私有目录回收失败', { id, error: err instanceof Error ? err.message : String(err) });- }- }- // 内置意识被用户主动卸载 → 记墓碑,启动播种永远跳过(不然重启就弹回来)。- if (listBuiltinSeedIds(builtinSeedRootDirs()).includes(id)) {- recordBuiltinTombstone(brainRootDir(), id, log);- }- let recentIds: string[] | null = null;- try {- recentIds = forgetGhostRecentUsage(id);- } catch (error) {- // 插件目录已删,MRU 是非关键附属数据;清理失败只记录,- // 不能让 renderer 把已完成的卸载误报为失败。- log.warn('ghost recent usage 清理失败', {- id,- error: error instanceof Error ? error.message : String(error),- });- }- broadcastGhostsChanged(manager.list());- if (recentIds) broadcastGhostRecentUsageChanged(recentIds);+ await uninstallGhostAndCleanup(id);return { ok: true };});diff --git a/apps/desktop/src/main/plugin-market/__tests__/api.test.ts b/apps/desktop/src/main/plugin-market/__tests__/api.test.tsnew file mode 100644index 0000000000..a48a9cbb61--- /dev/null+++ b/apps/desktop/src/main/plugin-market/__tests__/api.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it, vi } from 'vitest';++import { PluginMarketApi } from '../api';++const PLUGIN_A = `c${'a'.repeat(24)}`;+const PLUGIN_B = `c${'b'.repeat(24)}`;++function summary(id: string, ghostId: string) {+ return {+ id,+ ghostId,+ name: ghostId,+ description: null,+ author: null,+ scope: 'public',+ organizationId: null,+ defaultInstall: false,+ currentRelease: {+ id: `release-${ghostId}`,+ version: '1.0.0',+ sha256: 'a'.repeat(64),+ sizeBytes: 42,+ publishedAt: '2026-07-23T00:00:00.000Z',+ },+ };+}++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,+ plugins: [summary(PLUGIN_A, 'alpha'), summary(PLUGIN_B, 'beta')],+ nextCursor: null,+ });+ const api = new PluginMarketApi(fetcher);++ await expect(api.listAll()).resolves.toHaveLength(2);+ expect(fetcher.mock.calls[1]?.[0]).toContain(`cursor=${PLUGIN_A}`);+ });++ it('fails closed when the server still returns schema v1', async () => {+ const api = new PluginMarketApi(+ vi.fn().mockResolvedValue({+ schemaVersion: 1,+ plugins: [],+ nextCursor: null,+ }),+ );++ await expect(api.listAll()).rejects.toThrow('schemaVersion');+ });++ it('rejects a cursor that does not advance', async () => {+ const fetcher = vi.fn().mockResolvedValue({+ schemaVersion: 2,+ plugins: [],+ nextCursor: PLUGIN_A,+ });+ const api = new PluginMarketApi(fetcher);++ await expect(api.listAll()).rejects.toThrow('游标未前进');+ });+});diff --git a/apps/desktop/src/main/plugin-market/__tests__/download.test.ts b/apps/desktop/src/main/plugin-market/__tests__/download.test.tsnew file mode 100644index 0000000000..5b7e9d4582--- /dev/null+++ b/apps/desktop/src/main/plugin-market/__tests__/download.test.ts@@ -0,0 +1,100 @@+import crypto from 'node:crypto';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it, vi } from 'vitest';++const fetchMock = vi.hoisted(() => vi.fn());+vi.mock('electron', () => ({ net: { fetch: fetchMock } }));++import { downloadVerifiedPlugin } from '../download';++const files: string[] = [];++afterEach(() => {+ fetchMock.mockReset();+ for (const file of files.splice(0)) fs.rmSync(file, { force: true });+});+function target(): string {+ const file = path.join(+ os.tmpdir(),+ `cindy-plugin-download-${process.pid}-${Date.now()}-${Math.random()}.cindy`,+ );+ files.push(file);+ return file;+}++function expected(bytes: Buffer) {+ return {+ sizeBytes: bytes.byteLength,+ sha256: crypto.createHash('sha256').update(bytes).digest('hex'),+ };+}++describe('downloadVerifiedPlugin', () => {+ it('writes only bytes matching the release size and SHA-256', async () => {+ const bytes = Buffer.from('verified plugin bytes');+ fetchMock.mockResolvedValue(+ new Response(bytes, {+ status: 200,+ headers: { 'content-length': String(bytes.byteLength) },+ }),+ );+ const file = target();++ await downloadVerifiedPlugin('https://downloads.example.test/a', expected(bytes), file);++ expect(fs.readFileSync(file)).toEqual(bytes);+ expect(fetchMock).toHaveBeenCalledWith(+ 'https://downloads.example.test/a',+ expect.objectContaining({ redirect: 'error', cache: 'no-store' }),+ );+ });++ it('rejects a SHA mismatch without writing the target', async () => {+ const bytes = Buffer.from('tampered');+ fetchMock.mockResolvedValue(new Response(bytes, { status: 200 }));+ const file = target();++ await expect(+ downloadVerifiedPlugin('https://downloads.example.test/a', {+ ...expected(bytes),+ sha256: '0'.repeat(64),+ }, file),+ ).rejects.toThrow('SHA-256');+ expect(fs.existsSync(file)).toBe(false);+ });++ it('stops when the stream exceeds the declared release size', async () => {+ const bytes = Buffer.from('larger-than-declared');+ fetchMock.mockResolvedValue(new Response(bytes, { status: 200 }));++ await expect(+ downloadVerifiedPlugin(+ 'https://downloads.example.test/a',+ { sizeBytes: 3, sha256: '0'.repeat(64) },+ target(),+ ),+ ).rejects.toThrow('超过');+ });++ it('cancels the response body when Content-Length mismatches the release', async () => {+ const bytes = Buffer.from('mismatched length');+ const response = new Response(bytes, {+ status: 200,+ headers: { 'content-length': String(bytes.byteLength + 1) },+ });+ const cancel = vi.spyOn(response.body!, 'cancel');+ fetchMock.mockResolvedValue(response);++ await expect(+ downloadVerifiedPlugin(+ 'https://downloads.example.test/a',+ expected(bytes),+ target(),+ ),+ ).rejects.toThrow('Content-Length');+ expect(cancel).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.tsnew file mode 100644index 0000000000..fe730e2652--- /dev/null+++ b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts@@ -0,0 +1,36 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++import { describe, expect, it } from 'vitest';++/**+ * The IPC registration module imports Electron and the full Ghost host graph,+ * so guard its error-boundary contract using the established main-process+ * source-test pattern.+ */+describe('Plugin Market IPC error boundary', () => {+ const registerSource = readFileSync(+ resolve(process.cwd(), 'src/main/plugin-market/registerIpc.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');+ const serviceSource = readFileSync(+ resolve(process.cwd(), 'src/main/plugin-market/service.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');++ it('preserves structured errors and normalizes unexpected failures', () => {+ const start = registerSource.indexOf('async function invokePluginMarket');+ const end = registerSource.indexOf('\n}\n\n/** 注册 renderer', start);+ const body = registerSource.slice(start, end);++ 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(4);+ });++ it('does not throw user-visible plain errors from the market service', () => {+ expect(serviceSource).not.toContain('throw new Error(');+ expect(serviceSource).toContain("throwIpcError('PRECONDITION_FAILED'");+ expect(serviceSource).toContain("throwIpcError('PERMISSION_DENIED'");+ });+});diff --git a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.tsnew file mode 100644index 0000000000..ae9cc65e05--- /dev/null+++ b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts@@ -0,0 +1,116 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import {+ PluginMarketLedger,+ type PluginMarketInstallationRecord,+} from '../ledger';++const roots: string[] = [];++afterEach(() => {+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });+});++function harness() {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-plugin-ledger-'));+ roots.push(root);+ const filePath = path.join(root, 'plugin-market', 'ledger.v1.json');+ return { filePath, ledger: new PluginMarketLedger(filePath) };+}++function record(+ overrides: Partial<PluginMarketInstallationRecord> = {},+): PluginMarketInstallationRecord {+ return {+ pluginId: `c${'a'.repeat(24)}`,+ ghostId: 'cindy-test',+ releaseId: 'release-1',+ version: '1.0.0',+ sha256: 'b'.repeat(64),+ scope: 'public',+ organizationId: null,+ source: 'market',+ installed: true,+ updatedAt: '2026-07-23T00:00:00.000Z',+ ...overrides,+ };+}++describe('PluginMarketLedger', () => {+ it('writes provenance atomically and reads it back', () => {+ const { filePath, ledger } = harness();+ ledger.upsertInstallation(record());++ expect(ledger.installationForGhost('cindy-test')).toMatchObject({+ pluginId: `c${'a'.repeat(24)}`,+ installed: true,+ source: 'market',+ });+ expect(fs.existsSync(filePath)).toBe(true);+ expect(+ fs.readdirSync(path.dirname(filePath)).filter((name) => name.endsWith('.tmp')),+ ).toEqual([]);+ });++ it('records defaultInstall opt-out per authenticated user on removal', () => {+ const { ledger } = harness();+ ledger.upsertInstallation(record());+ ledger.markRemoved('cindy-test', 'user-a');++ expect(ledger.installationForGhost('cindy-test')?.installed).toBe(false);+ expect(+ ledger.isDefaultInstallSuppressed('user-a', `c${'a'.repeat(24)}`),+ ).toBe(true);+ expect(+ ledger.isDefaultInstallSuppressed('user-b', `c${'a'.repeat(24)}`),+ ).toBe(false);+ });++ it('fails closed to an empty ledger for malformed or future data', () => {+ const { filePath, ledger } = harness();+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ fs.writeFileSync(filePath, '{"schemaVersion":99,"installations":{"x":{}}}');++ expect(ledger.read()).toEqual({+ schemaVersion: 1,+ installations: {},+ defaultInstallOptOuts: {},+ });+ });++ it('resolves the owner-scoped path for every operation', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-plugin-ledger-owner-'));+ roots.push(root);+ let owner = 'owner-a';+ const ledger = new PluginMarketLedger(() =>+ path.join(root, owner, 'ledger.v1.json'),+ );++ ledger.upsertInstallation(record());+ owner = 'owner-b';++ expect(ledger.installationForGhost('cindy-test')).toBeNull();+ expect(fs.existsSync(path.join(root, 'owner-a', 'ledger.v1.json'))).toBe(true);+ expect(fs.existsSync(path.join(root, 'owner-b', 'ledger.v1.json'))).toBe(false);+ });++ it('keeps a bound owner path stable after the active owner changes', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-plugin-ledger-bound-'));+ roots.push(root);+ let owner = 'owner-a';+ const ledger = new PluginMarketLedger(() =>+ path.join(root, owner, 'ledger.v1.json'),+ );+ const bound = ledger.bind(path.join(root, owner, 'ledger.v1.json'));++ owner = 'owner-b';+ bound.upsertInstallation(record());++ expect(fs.existsSync(path.join(root, 'owner-a', 'ledger.v1.json'))).toBe(true);+ expect(fs.existsSync(path.join(root, 'owner-b', 'ledger.v1.json'))).toBe(false);+ });+});diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsnew file mode 100644index 0000000000..9892cf7122--- /dev/null+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -0,0 +1,754 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it, vi } from 'vitest';++const runtime = vi.hoisted(() => ({+ ghosts: [] as Array<{+ manifest: Record<string, unknown>;+ dir: string;+ enabled: boolean;+ }>,+ install: vi.fn(),+ uninstall: vi.fn(),+ builtinRemoved: new Set<string>(),+ accountGhostAvailable: true,+ boundaryPending: false,+ pluginApiBaseUrl: 'https://plugin.test.invalid' as string | null,+ session: {+ mode: 'cloud' as 'signed-out' | 'local' | 'cloud',+ dataOwnerId: 'user-1' as string | null,+ generation: 1,+ },+}));++vi.mock('electron', () => ({+ app: { getPath: vi.fn(() => os.tmpdir()) },+}));+vi.mock('../../authManager.js', () => ({+ getCurrentUserId: vi.fn(() =>+ runtime.session.mode === 'cloud' ? runtime.session.dataOwnerId : null,+ ),+}));+vi.mock('../../appSessionState.js', () => ({+ getActiveAppSession: vi.fn(() => ({ ...runtime.session })),+ isAppSessionBoundaryPending: vi.fn(() => runtime.boundaryPending),+ ownerScopedUserDataPath: vi.fn((...parts: string[]) =>+ path.join(os.tmpdir(), 'owners', runtime.session.dataOwnerId ?? 'local', ...parts),+ ),+}));+vi.mock('../../clientEndpointsService.js', () => ({+ getClientEndpoint: vi.fn(() => runtime.pluginApiBaseUrl),+}));+vi.mock('../../logger.js', () => ({+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),+}));+vi.mock('../../cindy-brain/index.js', () => ({+ getGhostManager: () => ({ list: () => runtime.ghosts }),+ isGhostAvailableForActiveSession: vi.fn(() => runtime.accountGhostAvailable),+ installOrUpdateMarketGhostPackage: runtime.install,+ isBuiltinGhostRemovedByUser: (id: string) => runtime.builtinRemoved.has(id),+ uninstallGhostAndCleanup: runtime.uninstall,+}));+vi.mock('../download.js', () => ({+ downloadVerifiedPlugin: vi.fn(async () => undefined),+}));++import type { VisiblePluginDetail, VisiblePluginSummary } from '@cindy/plugin-protocol';++import { PluginMarketLedger } from '../ledger';+import { PluginMarketService } from '../service';+import type { PluginMarketApi } from '../api';++const roots: string[] = [];+const PLUGIN_ID = `c${'a'.repeat(24)}`;++afterEach(() => {+ runtime.ghosts = [];+ runtime.install.mockReset();+ runtime.uninstall.mockReset();+ runtime.builtinRemoved.clear();+ runtime.accountGhostAvailable = true;+ runtime.boundaryPending = false;+ runtime.pluginApiBaseUrl = 'https://plugin.test.invalid';+ runtime.session = {+ mode: 'cloud',+ dataOwnerId: 'user-1',+ generation: 1,+ };+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });+});++function manifest(+ id = 'cindy-test',+ version = '1.0.0',+ slots: ['notify'] | ['notify', 'fs'] = ['notify'],+) {+ return {+ schemaVersion: 2 as const,+ id,+ name: 'Test Plugin',+ description: 'Test description',+ author: 'Cindy',+ version,+ kind: 'chip' as const,+ entry: 'main.js',+ slots,+ };+}++function summary(+ overrides: Partial<VisiblePluginSummary> = {},+): VisiblePluginSummary {+ return {+ id: PLUGIN_ID,+ ghostId: 'cindy-test',+ name: 'Test Plugin',+ description: 'Test description',+ author: 'Cindy',+ scope: 'public',+ organizationId: null,+ defaultInstall: false,+ currentRelease: {+ id: 'release-1',+ version: '1.0.0',+ sha256: 'a'.repeat(64),+ sizeBytes: 42,+ publishedAt: '2026-07-23T00:00:00.000Z',+ icon: null,+ },+ ...overrides,+ };+}++function detail(item = summary(), slots: ['notify'] | ['notify', 'fs'] = ['notify']): VisiblePluginDetail {+ return {+ ...item,+ currentRelease: {+ ...item.currentRelease,+ manifest: manifest(item.ghostId, item.currentRelease.version, slots),+ },+ };+}++function harness(items: VisiblePluginSummary[]) {+ 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),+ detail: vi.fn(async (pluginId: string) => {+ const item = items.find((candidate) => candidate.id === pluginId);+ if (!item) throw new Error('not found');+ return detail(item);+ }),+ download: vi.fn(async () => ({+ url: 'https://downloads.test.invalid/plugin.cindy',+ expiresAt: '2099-01-01T00:00:00.000Z',+ sha256: 'a'.repeat(64),+ sizeBytes: 42,+ })),+ };+ return {+ api,+ ledger,+ service: new PluginMarketService(api as unknown as PluginMarketApi, ledger),+ };+}++describe('PluginMarketService migration and defaultInstall', () => {+ it('passes the optional release icon metadata to renderer-safe market items', async () => {+ const icon = {+ mimeType: 'image/png',+ sha256: 'b'.repeat(64),+ sizeBytes: 128,+ url: 'https://oss.example.invalid/icons/test.png',+ expiresAt: '2026-07-23T00:05:00.000Z',+ };+ const h = harness([summary({+ currentRelease: {+ ...summary().currentRelease,+ icon,+ },+ })]);++ await expect(h.service.snapshot()).resolves.toMatchObject({+ items: [{ icon }],+ unavailableReason: null,+ });+ });++ 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 h = harness(items);+ const read = vi.spyOn(h.ledger, 'read');++ await h.service.snapshot();++ expect(read.mock.calls.length).toBeLessThan(10);+ });++ it('shows only public market plugins in account-free local mode', async () => {+ runtime.session = {+ mode: 'local',+ dataOwnerId: 'local-v1',+ generation: 2,+ };+ const publicPlugin = summary();+ const organizationPlugin = summary({+ id: `c${'b'.repeat(24)}`,+ ghostId: 'cindy-team-only',+ scope: 'organization',+ organizationId: 'org-1',+ });+ const h = harness([publicPlugin, organizationPlugin]);++ await expect(h.service.snapshot()).resolves.toMatchObject({+ items: [{ pluginId: publicPlugin.id, scope: 'public' }],+ unavailableReason: null,+ });+ expect(h.api.listAll).toHaveBeenCalledTimes(1);+ });++ it('keeps signed-out sessions out of the market until an owner is selected', async () => {+ runtime.session = {+ mode: 'signed-out',+ dataOwnerId: null,+ generation: 2,+ };+ const h = harness([summary()]);++ await expect(h.service.snapshot()).resolves.toEqual({+ items: [],+ unavailableReason: 'authentication-required',+ });+ expect(h.api.listAll).not.toHaveBeenCalled();+ });++ it('reports missing market configuration before requiring authentication', async () => {+ runtime.pluginApiBaseUrl = null;+ runtime.session = {+ mode: 'signed-out',+ dataOwnerId: null,+ generation: 2,+ };+ const h = harness([summary()]);++ await expect(h.service.snapshot()).resolves.toEqual({+ items: [],+ unavailableReason: 'not-configured',+ });+ expect(h.api.listAll).not.toHaveBeenCalled();+ });++ it('uses a switching reason while the account boundary is pending', async () => {+ runtime.boundaryPending = true;+ const h = harness([summary()]);++ await expect(h.service.snapshot()).resolves.toEqual({+ items: [],+ unavailableReason: 'session-switching',+ });+ expect(h.api.listAll).not.toHaveBeenCalled();+ });++ it('adopts one exact official legacy install without downloading or changing enable state', async () => {+ runtime.ghosts = [+ {+ manifest: manifest(),+ dir: '/userData/cindy-brain/cindy-test',+ enabled: true,+ },+ ];+ const h = harness([summary()]);++ const snapshot = await h.service.snapshot();++ expect(snapshot.items[0]).toMatchObject({+ installState: 'update-available',+ enabled: true,+ });+ expect(h.ledger.installationForGhost('cindy-test')).toMatchObject({+ source: 'legacy-adopted',+ pluginId: PLUGIN_ID,+ releaseId: 'legacy-unresolved:1.0.0',+ sha256: 'legacy-unverified',+ });+ expect(runtime.install).not.toHaveBeenCalled();+ });++ it('adopts an older official legacy install as update-available without rendering a duplicate', async () => {+ runtime.ghosts = [+ {+ manifest: manifest('cindy-test', '0.9.0'),+ dir: '/userData/cindy-brain/cindy-test',+ enabled: false,+ },+ ];+ const h = harness([summary()]);++ const snapshot = await h.service.snapshot();++ expect(snapshot.items).toHaveLength(1);+ expect(snapshot.items[0]).toMatchObject({+ ghostId: 'cindy-test',+ installState: 'update-available',+ enabled: false,+ });+ expect(h.ledger.installationForGhost('cindy-test')).toMatchObject({+ source: 'legacy-adopted',+ pluginId: PLUGIN_ID,+ releaseId: 'legacy-unresolved:0.9.0',+ version: '0.9.0',+ sha256: 'legacy-unverified',+ });+ expect(runtime.install).not.toHaveBeenCalled();+ });++ it('installs and enables a unique defaultInstall package and records its release', async () => {+ const item = summary({ defaultInstall: true });+ runtime.install.mockImplementation(async () => {+ const ghost = {+ manifest: manifest(),+ dir: '/userData/cindy-brain/cindy-test',+ enabled: true,+ };+ runtime.ghosts = [ghost];+ return ghost;+ });+ const h = harness([item]);++ const snapshot = await h.service.snapshot();++ expect(runtime.install).toHaveBeenCalledWith(+ expect.stringMatching(/\.cindy$/),+ {+ ghostId: 'cindy-test',+ version: '1.0.0',+ initiallyEnabled: true,+ },+ );+ expect(snapshot.items[0]).toMatchObject({+ installState: 'installed',+ enabled: true,+ });+ expect(h.ledger.installationForGhost('cindy-test')).toMatchObject({+ source: 'market',+ releaseId: 'release-1',+ });+ });++ it('keeps a manual market install disabled by default', async () => {+ const item = summary();+ runtime.install.mockResolvedValue({+ manifest: manifest(),+ dir: '/userData/cindy-brain/cindy-test',+ enabled: false,+ });+ const h = harness([item]);++ await h.service.install(item.id);++ expect(runtime.install).toHaveBeenCalledWith(+ expect.stringMatching(/\.cindy$/),+ {+ ghostId: 'cindy-test',+ version: '1.0.0',+ initiallyEnabled: false,+ },+ );+ });++ it('installs and enables a public defaultInstall package in local mode', async () => {+ runtime.session = {+ mode: 'local',+ dataOwnerId: 'local-v1',+ generation: 2,+ };+ const item = summary({ defaultInstall: true });+ runtime.install.mockImplementation(async () => {+ const ghost = {+ manifest: manifest(),+ dir: '/userData/cindy-brain/cindy-test',+ enabled: true,+ };+ runtime.ghosts = [ghost];+ return ghost;+ });+ const h = harness([item]);++ const snapshot = await h.service.snapshot();++ expect(runtime.install).toHaveBeenCalledWith(+ expect.stringMatching(/\.cindy$/),+ {+ ghostId: item.ghostId,+ version: item.currentRelease.version,+ initiallyEnabled: true,+ },+ );+ expect(snapshot.items[0]).toMatchObject({+ installState: 'installed',+ enabled: true,+ });+ });++ it('installs a public market plugin in account-free local mode', async () => {+ runtime.session = {+ mode: 'local',+ dataOwnerId: 'local-v1',+ generation: 2,+ };+ const item = summary();+ runtime.install.mockResolvedValue({+ manifest: manifest(),+ dir: '/userData/cindy-brain/cindy-test',+ enabled: false,+ });+ const h = harness([item]);++ await expect(h.service.install(item.id)).resolves.toMatchObject({+ ghost: { manifest: { id: 'cindy-test' }, enabled: false },+ });+ expect(h.api.download).toHaveBeenCalledWith(item.id, item.currentRelease.id);+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({+ pluginId: item.id,+ installed: true,+ });+ });++ it('rejects a non-public plugin returned to account-free local mode', async () => {+ runtime.session = {+ mode: 'local',+ dataOwnerId: 'local-v1',+ generation: 2,+ };+ const item = summary({+ scope: 'organization',+ organizationId: 'org-1',+ });+ const h = harness([item]);++ await expect(h.service.install(item.id)).rejects.toThrow('[NOT_FOUND]');+ expect(h.api.detail).not.toHaveBeenCalled();+ expect(runtime.install).not.toHaveBeenCalled();+ });++ it('hides account-managed public plugins from account-free local mode', async () => {+ runtime.session = {+ mode: 'local',+ dataOwnerId: 'local-v1',+ generation: 2,+ };+ const item = summary({ ghostId: 'cindy-github' });+ runtime.accountGhostAvailable = false;+ const h = harness([item]);++ await expect(h.service.snapshot()).resolves.toEqual({+ items: [],+ unavailableReason: null,+ });+ expect(h.api.listAll).toHaveBeenCalledOnce();+ });++ it('does not re-enable an installed defaultInstall package disabled by the user', async () => {+ const item = summary({ defaultInstall: true });+ runtime.ghosts = [+ {+ manifest: manifest(),+ dir: '/userData/cindy-brain/cindy-test',+ enabled: false,+ },+ ];+ const h = harness([item]);+ h.ledger.upsertInstallation(recordForTest(item));++ const snapshot = await h.service.snapshot();++ expect(runtime.install).not.toHaveBeenCalled();+ expect(snapshot.items[0]).toMatchObject({+ installState: 'installed',+ enabled: false,+ });+ });++ it('treats a missing previously-managed directory as an opt-out and does not reinstall', async () => {+ const item = summary({ defaultInstall: true });+ const h = harness([item]);+ h.ledger.upsertInstallation({+ pluginId: item.id,+ ghostId: item.ghostId,+ releaseId: item.currentRelease.id,+ version: item.currentRelease.version,+ sha256: item.currentRelease.sha256,+ scope: item.scope,+ organizationId: item.organizationId,+ source: 'market',+ installed: true,+ updatedAt: '2026-07-23T00:00:00.000Z',+ });++ const snapshot = await h.service.snapshot();++ expect(runtime.install).not.toHaveBeenCalled();+ expect(snapshot.items[0]?.installState).toBe('not-installed');+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(true);+ });++ it('records an opt-out only after a tracked local uninstall succeeds', async () => {+ const item = summary({ defaultInstall: true });+ const h = harness([item]);+ h.ledger.upsertInstallation(recordForTest(item));++ const complete = h.service.prepareLocalUninstallTracking(item.ghostId);++ expect(complete).not.toBeNull();+ expect(h.ledger.installationForGhost(item.ghostId)?.installed).toBe(true);+ await complete?.();+ expect(h.ledger.installationForGhost(item.ghostId)?.installed).toBe(false);+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(true);+ });++ it('records local-mode defaultInstall opt-out under the local owner', async () => {+ runtime.session = {+ mode: 'local',+ dataOwnerId: 'local-v1',+ generation: 2,+ };+ const item = summary({ defaultInstall: true });+ const h = harness([item]);+ h.ledger.upsertInstallation(recordForTest(item));++ const complete = h.service.prepareLocalUninstallTracking(item.ghostId);++ expect(complete).not.toBeNull();+ await complete?.();+ expect(h.ledger.installationForGhost(item.ghostId)?.installed).toBe(false);+ expect(h.ledger.isDefaultInstallSuppressed('local-v1', item.id)).toBe(true);+ });++ it('records a local uninstall opt-out for the captured owner after an account switch', async () => {+ const item = summary({ defaultInstall: true });+ const h = harness([item]);+ h.ledger.upsertInstallation(recordForTest(item));+ const complete = h.service.prepareLocalUninstallTracking(item.ghostId);++ runtime.session = {+ mode: 'cloud',+ dataOwnerId: 'user-2',+ generation: 2,+ };++ await expect(complete?.()).resolves.toBeUndefined();+ expect(h.ledger.installationForGhost(item.ghostId)?.installed).toBe(false);+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(true);+ expect(h.ledger.isDefaultInstallSuppressed('user-2', item.id)).toBe(false);+ });++ it('does not attach local uninstall tracking without a stable owner', () => {+ runtime.session = {+ mode: 'signed-out',+ dataOwnerId: null,+ generation: 2,+ };+ const h = harness([summary()]);++ expect(h.service.prepareLocalUninstallTracking('cindy-test')).toBeNull();+ });++ it('does not restore a bundled default after the user removed it', async () => {+ const item = summary({ defaultInstall: true });+ runtime.builtinRemoved.add(item.ghostId);+ const h = harness([item]);++ const snapshot = await h.service.snapshot();++ expect(snapshot.items[0]?.installState).toBe('not-installed');+ expect(runtime.install).not.toHaveBeenCalled();+ });++ it('does not auto-adopt or overwrite an untracked non-official id collision', async () => {+ const item = summary({+ ghostId: 'third-party',+ defaultInstall: true,+ });+ runtime.ghosts = [+ {+ manifest: manifest('third-party'),+ dir: '/userData/cindy-brain/third-party',+ enabled: true,+ },+ ];+ const h = harness([item]);++ const snapshot = await h.service.snapshot();++ expect(snapshot.items[0]?.installState).toBe('conflict');+ expect(runtime.install).not.toHaveBeenCalled();+ expect(h.ledger.installationForGhost('third-party')).toBeNull();+ });++ it('treats a removed market record plus an existing directory as an id conflict', async () => {+ const item = summary();+ runtime.ghosts = [+ {+ 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)).rejects.toThrow('[ALREADY_EXISTS]');+ expect(runtime.install).not.toHaveBeenCalled();+ });++ it('requires an explicit reviewed flag before an update can add permissions', async () => {+ const item = summary({+ currentRelease: {+ ...summary().currentRelease,+ id: 'release-2',+ version: '2.0.0',+ },+ });+ runtime.ghosts = [+ {+ manifest: manifest(),+ dir: '/userData/cindy-brain/cindy-test',+ enabled: true,+ },+ ];+ runtime.install.mockResolvedValue({+ manifest: manifest('cindy-test', '2.0.0', ['notify', 'fs']),+ dir: '/userData/cindy-brain/cindy-test',+ enabled: true,+ });+ const h = harness([item]);+ h.ledger.upsertInstallation({+ ...recordForTest(item),+ releaseId: 'release-1',+ version: '1.0.0',+ });+ h.api.detail.mockResolvedValue(detail(item, ['notify', 'fs']));++ await expect(h.service.install(item.id)).rejects.toThrow('[PRECONDITION_FAILED]');+ expect(runtime.install).not.toHaveBeenCalled();++ await expect(+ h.service.install(item.id, { allowPermissionExpansion: true }),+ ).resolves.toMatchObject({+ ghost: { manifest: { version: '2.0.0' } },+ });+ expect(runtime.install).toHaveBeenCalledTimes(1);+ });++ it('rejects a download credential with an invalid expiry timestamp', async () => {+ const item = summary();+ const h = harness([item]);+ h.api.download.mockResolvedValue({+ url: 'https://downloads.test.invalid/plugin.cindy',+ expiresAt: 'not-a-timestamp',+ sha256: item.currentRelease.sha256,+ sizeBytes: item.currentRelease.sizeBytes,+ });++ await expect(h.service.install(item.id)).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 () => {+ runtime.session = {+ mode: 'cloud',+ dataOwnerId: 'user-2',+ generation: 2,+ };+ return [item];+ });++ await expect(h.service.install(item.id)).rejects.toThrow('[PRECONDITION_FAILED]');+ expect(runtime.install).not.toHaveBeenCalled();+ expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();+ });++ it('records provenance for the captured owner when the owner changes after install', async () => {+ const item = summary();+ const installedGhost = {+ manifest: manifest(),+ dir: '/userData/cindy-brain/cindy-test',+ enabled: false,+ };+ const h = harness([item]);+ runtime.install.mockImplementationOnce(async () => {+ runtime.session = {+ mode: 'cloud',+ dataOwnerId: 'user-2',+ generation: 2,+ };+ runtime.ghosts = [installedGhost];+ return installedGhost;+ });++ await expect(h.service.install(item.id)).resolves.toEqual({+ ghost: installedGhost,+ });+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({+ pluginId: item.id,+ releaseId: item.currentRelease.id,+ installed: true,+ });+ });++ it('reports a successful market uninstall when the owner changes during cleanup', async () => {+ const item = summary({ defaultInstall: true });+ const h = harness([item]);+ h.ledger.upsertInstallation(recordForTest(item));+ runtime.ghosts = [+ {+ manifest: manifest(),+ dir: '/userData/cindy-brain/cindy-test',+ enabled: true,+ },+ ];+ runtime.uninstall.mockImplementationOnce(async () => {+ runtime.session = {+ mode: 'cloud',+ dataOwnerId: 'user-2',+ generation: 2,+ };+ runtime.ghosts = [];+ });++ await expect(h.service.uninstall(item.id)).resolves.toEqual({ ok: true });+ expect(runtime.uninstall).toHaveBeenCalledWith(item.ghostId, {+ skipMarketLedger: true,+ });+ expect(h.ledger.installationForGhost(item.ghostId)?.installed).toBe(false);+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(true);+ });+});++function recordForTest(item: VisiblePluginSummary) {+ return {+ pluginId: item.id,+ ghostId: item.ghostId,+ releaseId: item.currentRelease.id,+ version: item.currentRelease.version,+ sha256: item.currentRelease.sha256,+ scope: item.scope,+ organizationId: item.organizationId,+ source: 'market' as const,+ installed: true,+ updatedAt: '2026-07-23T00:00:00.000Z',+ };+}diff --git a/apps/desktop/src/main/plugin-market/api.ts b/apps/desktop/src/main/plugin-market/api.tsnew file mode 100644index 0000000000..10b9d3ab77--- /dev/null+++ b/apps/desktop/src/main/plugin-market/api.ts@@ -0,0 +1,72 @@+import {+ parseGetPluginResponse,+ parseListPluginsResponse,+ parsePluginDownloadResponse,+ type GetPluginResponse,+ type ListPluginsResponse,+ type PluginDownloadResponse,+} from '@cindy/plugin-protocol';++import { getClientEndpoint } from '../clientEndpointsService.js';+import { serverApiFetch, type ApiFetchOptions } from '../serverApiClient.js';++type Fetcher = <T>(+ apiPath: string,+ options: Omit<ApiFetchOptions, 'baseUrl'>,+) => Promise<T>;++const defaultFetcher: Fetcher = (apiPath, options) =>+ serverApiFetch(apiPath, {+ ...options,+ baseUrl: getClientEndpoint('pluginApiBaseUrl'),+ });++/** plugin-server 普通客户端 API;每个响应都经过共享 v2 parser fail-closed。 */+export class PluginMarketApi {+ constructor(private readonly fetcher: Fetcher = defaultFetcher) {}++ async listAll(query?: string): Promise<ListPluginsResponse['plugins']> {+ const plugins: ListPluginsResponse['plugins'] = [];+ let cursor: string | null = null;+ const seen = new Set<string>();+ for (let page = 0; page < 100; page += 1) {+ const search = new URLSearchParams({ scope: 'all', limit: '100' });+ if (query?.trim()) search.set('query', query.trim());+ if (cursor) search.set('cursor', cursor);+ const response = parseListPluginsResponse(+ await this.fetcher<unknown>(`/api/plugins?${search.toString()}`, {+ cache: 'no-store',+ }),+ );+ for (const plugin of response.plugins) {+ if (seen.has(plugin.id)) continue;+ seen.add(plugin.id);+ plugins.push(plugin);+ }+ if (!response.nextCursor) return plugins;+ if (response.nextCursor === cursor) throw new Error('Plugin 市场分页游标未前进');+ cursor = response.nextCursor;+ }+ throw new Error('Plugin 市场分页超过安全上限');+ }++ async detail(pluginId: string): Promise<GetPluginResponse['plugin']> {+ return parseGetPluginResponse(+ await this.fetcher<unknown>(`/api/plugins/${encodeURIComponent(pluginId)}`, {+ cache: 'no-store',+ }),+ ).plugin;+ }++ async download(+ pluginId: string,+ releaseId: string,+ ): Promise<PluginDownloadResponse> {+ return parsePluginDownloadResponse(+ await this.fetcher<unknown>(+ `/api/plugins/${encodeURIComponent(pluginId)}/releases/${encodeURIComponent(releaseId)}/download`,+ { cache: 'no-store' },+ ),+ );+ }+}diff --git a/apps/desktop/src/main/plugin-market/download.ts b/apps/desktop/src/main/plugin-market/download.tsnew file mode 100644index 0000000000..eb4e1814c3--- /dev/null+++ b/apps/desktop/src/main/plugin-market/download.ts@@ -0,0 +1,48 @@+import crypto from 'node:crypto';+import fs from 'node:fs';++import { net } from 'electron';++const MAX_PLUGIN_BYTES = 8 * 1024 * 1024;++/** 下载并校验 `.cindy` 原始字节,写入调用方提供的临时路径。 */+export async function downloadVerifiedPlugin(+ url: string,+ expected: { sizeBytes: number; sha256: string },+ targetPath: string,+): Promise<void> {+ if (expected.sizeBytes <= 0 || expected.sizeBytes > MAX_PLUGIN_BYTES) {+ throw new Error(`Plugin 包大小超限: ${expected.sizeBytes}`);+ }+ const response = await net.fetch(url, {+ method: 'GET',+ cache: 'no-store',+ redirect: 'error',+ });+ if (!response.ok) throw new Error(`Plugin 下载失败 (${response.status})`);+ if (!response.body) throw new Error('Plugin 下载响应体为空');+ const contentLength = response.headers.get('content-length');+ if (contentLength !== null && Number(contentLength) !== expected.sizeBytes) {+ await response.body.cancel().catch(() => undefined);+ throw new Error('Plugin 下载 Content-Length 与 Release 不一致');+ }++ const reader = response.body.getReader();+ const chunks: Buffer[] = [];+ let size = 0;+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ size += value.byteLength;+ if (size > expected.sizeBytes || size > MAX_PLUGIN_BYTES) {+ await reader.cancel();+ throw new Error('Plugin 下载字节数超过 Release 声明');+ }+ chunks.push(Buffer.from(value));+ }+ if (size !== expected.sizeBytes) throw new Error('Plugin 下载字节数与 Release 不一致');+ const bytes = Buffer.concat(chunks, size);+ const sha256 = crypto.createHash('sha256').update(bytes).digest('hex');+ if (sha256 !== expected.sha256) throw new Error('Plugin 下载 SHA-256 校验失败');+ await fs.promises.writeFile(targetPath, bytes, { mode: 0o600, flag: 'wx' });+}diff --git a/apps/desktop/src/main/plugin-market/ledger.ts b/apps/desktop/src/main/plugin-market/ledger.tsnew file mode 100644index 0000000000..3735932247--- /dev/null+++ b/apps/desktop/src/main/plugin-market/ledger.ts@@ -0,0 +1,165 @@+import fs from 'node:fs';+import path from 'node:path';+import crypto from 'node:crypto';++import type { PluginScope } from '@cindy/plugin-protocol';++const LEDGER_SCHEMA_VERSION = 1;++export interface PluginMarketInstallationRecord {+ pluginId: string;+ ghostId: string;+ releaseId: string;+ version: string;+ sha256: string;+ scope: PluginScope;+ organizationId: string | null;+ source: 'market' | 'legacy-adopted';+ installed: boolean;+ updatedAt: string;+}++interface PluginMarketLedgerData {+ schemaVersion: typeof LEDGER_SCHEMA_VERSION;+ installations: Record<string, PluginMarketInstallationRecord>;+ defaultInstallOptOuts: Record<string, string[]>;+}++function emptyLedger(): PluginMarketLedgerData {+ return {+ schemaVersion: LEDGER_SCHEMA_VERSION,+ installations: {},+ defaultInstallOptOuts: {},+ };+}++function validRecord(value: unknown): value is PluginMarketInstallationRecord {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;+ const record = value as Record<string, unknown>;+ return (+ typeof record.pluginId === 'string' &&+ typeof record.ghostId === 'string' &&+ typeof record.releaseId === 'string' &&+ typeof record.version === 'string' &&+ typeof record.sha256 === 'string' &&+ (record.scope === 'public' ||+ record.scope === 'organization' ||+ record.scope === 'personal') &&+ (record.organizationId === null || typeof record.organizationId === 'string') &&+ (record.source === 'market' || record.source === 'legacy-adopted') &&+ typeof record.installed === 'boolean' &&+ typeof record.updatedAt === 'string'+ );+}++/**+ * Plugin 市场来源账本。包目录仍是 runtime 安装事实;本账本只记录 server+ * Plugin ID、Release 溯源和 defaultInstall 退订,不复制 manifest/凭证。+ */+export class PluginMarketLedger {+ constructor(private readonly filePathSource: string | (() => string)) {}++ /**+ * Binds a dynamic owner-scoped ledger to the path captured at operation start.+ * Static test/isolated ledgers keep their instance so callers can inspect them.+ */+ bind(filePath: string): PluginMarketLedger {+ return typeof this.filePathSource === 'function'+ ? new PluginMarketLedger(filePath)+ : this;+ }++ private filePath(): string {+ return typeof this.filePathSource === 'function'+ ? this.filePathSource()+ : this.filePathSource;+ }++ read(): PluginMarketLedgerData {+ let raw: unknown;+ try {+ raw = JSON.parse(fs.readFileSync(this.filePath(), 'utf8'));+ } catch {+ return emptyLedger();+ }+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return emptyLedger();+ const value = raw as Record<string, unknown>;+ if (value.schemaVersion !== LEDGER_SCHEMA_VERSION) return emptyLedger();+ const installations: Record<string, PluginMarketInstallationRecord> = {};+ if (value.installations && typeof value.installations === 'object') {+ for (const [ghostId, record] of Object.entries(value.installations)) {+ if (validRecord(record) && record.ghostId === ghostId) installations[ghostId] = record;+ }+ }+ const defaultInstallOptOuts: Record<string, string[]> = {};+ if (value.defaultInstallOptOuts && typeof value.defaultInstallOptOuts === 'object') {+ for (const [userId, pluginIds] of Object.entries(value.defaultInstallOptOuts)) {+ if (!Array.isArray(pluginIds)) continue;+ defaultInstallOptOuts[userId] = [+ ...new Set(pluginIds.filter((id): id is string => typeof id === 'string')),+ ];+ }+ }+ return { schemaVersion: LEDGER_SCHEMA_VERSION, installations, defaultInstallOptOuts };+ }++ installationForGhost(ghostId: string): PluginMarketInstallationRecord | null {+ return this.read().installations[ghostId] ?? null;+ }++ upsertInstallation(record: PluginMarketInstallationRecord): void {+ const data = this.read();+ data.installations[record.ghostId] = record;+ this.write(data);+ }++ markRemoved(ghostId: string, userId: string | null): void {+ const data = this.read();+ const record = data.installations[ghostId];+ if (!record) return;+ data.installations[ghostId] = {+ ...record,+ installed: false,+ updatedAt: new Date().toISOString(),+ };+ if (userId) {+ data.defaultInstallOptOuts[userId] = [+ ...new Set([...(data.defaultInstallOptOuts[userId] ?? []), record.pluginId]),+ ];+ }+ this.write(data);+ }++ isDefaultInstallSuppressed(userId: string, pluginId: string): boolean {+ return this.read().defaultInstallOptOuts[userId]?.includes(pluginId) ?? false;+ }++ private write(data: PluginMarketLedgerData): void {+ const filePath = this.filePath();+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ const tempPath = `${filePath}.${crypto.randomUUID()}.tmp`;+ try {+ fs.writeFileSync(tempPath, `${JSON.stringify(data, null, 2)}\n`, {+ mode: 0o600,+ flag: 'wx',+ });+ try {+ fs.renameSync(tempPath, filePath);+ } catch (error) {+ // Windows refuses to replace an existing file with renameSync. The+ // destination is only the previous ledger snapshot, so remove it and+ // retry while retaining the freshly flushed temp file.+ const code = error && typeof error === 'object' && 'code' in error+ ? (error as NodeJS.ErrnoException).code+ : undefined;+ if (process.platform !== 'win32' || (code !== 'EPERM' && code !== 'EEXIST')) {+ throw error;+ }+ fs.rmSync(filePath, { force: true });+ fs.renameSync(tempPath, filePath);+ }+ } finally {+ fs.rmSync(tempPath, { force: true });+ }+ }+}diff --git a/apps/desktop/src/main/plugin-market/registerIpc.ts b/apps/desktop/src/main/plugin-market/registerIpc.tsnew file mode 100644index 0000000000..0edd218939--- /dev/null+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts@@ -0,0 +1,75 @@+import { ipcMain } from 'electron';++import { isIpcError } from '../../shared/ipc-errors.js';+import { setGhostUninstallLedgerPreparer } from '../cindy-brain/index.js';+import { createLogger } from '../logger.js';+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';+import { requireString, throwIpcError } from '../utils/ipcValidate.js';+import { PluginMarketService } from './service.js';++const log = createLogger('plugin-market-ipc');+let registered = false;+let serviceSingleton: PluginMarketService | null = null;++function service(): PluginMarketService {+ serviceSingleton ??= new PluginMarketService();+ return serviceSingleton;+}++/**+ * Preserve stable IPC errors and hide internal/network messages from the+ * renderer. Detailed failures stay in main logs; the renderer localizes by+ * code and uses a generic fallback for INTERNAL.+ */+async function invokePluginMarket<T>(operation: () => Promise<T>): Promise<T> {+ try {+ return await operation();+ } catch (error) {+ if (isIpcError(error)) throw error;+ log.warn('plugin market IPC failed', {+ error: error instanceof Error ? error.message : String(error),+ });+ throwIpcError('INTERNAL', 'Plugin market operation failed');+ }+}++/** 注册 renderer 可用的只读市场与显式安装/卸载写路径。 */+export function registerPluginMarketIpc(): void {+ if (registered) return;+ registered = true;+ setGhostUninstallLedgerPreparer((ghostId) =>+ service().prepareLocalUninstallTracking(ghostId),+ );+ ipcMain.handle('plugin-market:snapshot', (event) => {+ assertTrustedAppRendererEvent(event);+ return invokePluginMarket(() => service().snapshot());+ });+ ipcMain.handle('plugin-market:detail', (event, pluginId: unknown) => {+ assertTrustedAppRendererEvent(event);+ return invokePluginMarket(() =>+ service().detail(requireString(pluginId, 'pluginId')),+ );+ });+ ipcMain.handle(+ 'plugin-market:install',+ (event, pluginId: unknown, options: unknown) => {+ assertTrustedAppRendererEvent(event);+ const allowPermissionExpansion =+ typeof options === 'object' &&+ options !== null &&+ (options as { allowPermissionExpansion?: unknown }).allowPermissionExpansion === true;+ return invokePluginMarket(() =>+ service().install(requireString(pluginId, 'pluginId'), {+ allowPermissionExpansion,+ nodeAuthorizationWebContents: event.sender,+ }),+ );+ },+ );+ ipcMain.handle('plugin-market:uninstall', (event, pluginId: unknown) => {+ assertTrustedAppRendererEvent(event);+ return invokePluginMarket(() =>+ service().uninstall(requireString(pluginId, 'pluginId')),+ );+ });+}diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsnew file mode 100644index 0000000000..ecf1658cb4--- /dev/null+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -0,0 +1,619 @@+import fs from 'node:fs';+import path from 'node:path';+import crypto from 'node:crypto';++import {+ isValidPluginResourceId,+ type VisiblePluginDetail,+ type VisiblePluginSummary,+} from '@cindy/plugin-protocol';+import { app, type WebContents } from 'electron';++import {+ diffGhostPermissionItems,+ isOfficialGhostId,+ validateGhostManifest,+ type InstalledGhost,+} from '../../shared/ghost.js';+import type {+ PluginMarketDetail,+ PluginMarketItem,+ PluginMarketSnapshot,+} from '../../shared/pluginMarket.js';+import { getCurrentUserId } from '../authManager.js';+import {+ getGhostManager,+ installOrUpdateMarketGhostPackage,+ isGhostAvailableForActiveSession,+ isBuiltinGhostRemovedByUser,+ uninstallGhostAndCleanup,+} from '../cindy-brain/index.js';+import {+ getActiveAppSession,+ isAppSessionBoundaryPending,+ ownerScopedUserDataPath,+ type ActiveAppSession,+} from '../appSessionState.js';+import { getClientEndpoint } from '../clientEndpointsService.js';+import { createLogger } from '../logger.js';+import { throwIpcError } from '../utils/ipcValidate.js';+import { PluginMarketApi } from './api.js';+import { downloadVerifiedPlugin } from './download.js';+import {+ PluginMarketLedger,+ type PluginMarketInstallationRecord,+} from './ledger.js';++const log = createLogger('plugin-market');+const NO_DUPLICATE_GHOST_IDS: ReadonlySet<string> = new Set();++function captureMarketOwner(): ActiveAppSession {+ const session = getActiveAppSession();+ if (+ (session.mode !== 'cloud' && session.mode !== 'local') ||+ !session.dataOwnerId ||+ isAppSessionBoundaryPending()+ ) {+ throwIpcError('PRECONDITION_FAILED', 'Plugin market requires a stable app session');+ }+ return session;+}++function requireSameMarketOwner(expected: ActiveAppSession): void {+ const current = getActiveAppSession();+ if (+ isAppSessionBoundaryPending() ||+ current.mode !== expected.mode ||+ current.dataOwnerId !== expected.dataOwnerId ||+ current.generation !== expected.generation+ ) {+ throwIpcError('PRECONDITION_FAILED', 'The active account changed during the Plugin operation');+ }+}++function visiblePluginsForOwner(+ owner: ActiveAppSession,+ plugins: readonly VisiblePluginSummary[],+): VisiblePluginSummary[] {+ return owner.mode === 'local'+ ? plugins.filter(+ (plugin) =>+ plugin.scope === 'public' && isGhostAvailableForActiveSession(plugin.ghostId),+ )+ : [...plugins];+}++function defaultInstallSubject(owner: ActiveAppSession): string {+ const subject = getCurrentUserId() ?? owner.dataOwnerId;+ if (!subject) {+ throwIpcError('PRECONDITION_FAILED', 'Plugin market data owner is unavailable');+ }+ return subject;+}++function recordFrom(+ plugin: VisiblePluginSummary | VisiblePluginDetail,+ source: PluginMarketInstallationRecord['source'],+): PluginMarketInstallationRecord {+ return {+ pluginId: plugin.id,+ ghostId: plugin.ghostId,+ releaseId: plugin.currentRelease.id,+ version: plugin.currentRelease.version,+ sha256: plugin.currentRelease.sha256,+ scope: plugin.scope,+ organizationId: plugin.organizationId,+ source,+ installed: true,+ updatedAt: new Date().toISOString(),+ };+}++/**+ * Claims a trusted legacy install without pretending its bytes came from the+ * current market release. A synthetic release id keeps the local version+ * visible as update-available until the user explicitly installs the market+ * release; the normal update path then replaces this with verified provenance.+ */+function legacyRecordFrom(+ plugin: VisiblePluginSummary,+ ghost: InstalledGhost,+): PluginMarketInstallationRecord {+ return {+ pluginId: plugin.id,+ ghostId: plugin.ghostId,+ releaseId: `legacy-unresolved:${ghost.manifest.version}`,+ version: ghost.manifest.version,+ sha256: 'legacy-unverified',+ scope: plugin.scope,+ organizationId: plugin.organizationId,+ source: 'legacy-adopted',+ installed: true,+ updatedAt: new Date().toISOString(),+ };+}++function ghostIdCounts(+ plugins: readonly VisiblePluginSummary[],+): Map<string, number> {+ const counts = new Map<string, number>();+ for (const plugin of plugins) {+ counts.set(plugin.ghostId, (counts.get(plugin.ghostId) ?? 0) + 1);+ }+ return counts;+}++/** Stable local facts reused while projecting one market catalog response. */+interface LocalInstallSnapshot {+ /** Installed Ghost runtime facts indexed once for one market operation. */+ ghostsById: ReadonlyMap<string, InstalledGhost>;+ /** Parsed provenance records from one ledger read. */+ installations: Readonly<Record<string, PluginMarketInstallationRecord>>;+}++/**+ * Plugin 市场的 main 端协调器。远程不可用时不碰本地目录;安装写路径必须依次+ * 通过 protocol parser、下载大小/SHA 校验、Ghost runtime validator 和原子换目录。+ */+export class PluginMarketService {+ private readonly mutations = new Map<string, Promise<unknown>>();+ private ledgerMutation: Promise<void> = Promise.resolve();++ constructor(+ private readonly api = new PluginMarketApi(),+ private readonly ledger = new PluginMarketLedger(() =>+ ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'),+ ),+ ) {}++ async snapshot(): Promise<PluginMarketSnapshot> {+ if (!getClientEndpoint('pluginApiBaseUrl')) {+ return { items: [], unavailableReason: 'not-configured' };+ }+ let owner: ActiveAppSession;+ try {+ owner = captureMarketOwner();+ } catch {+ return {+ items: [],+ unavailableReason: isAppSessionBoundaryPending()+ ? 'session-switching'+ : 'authentication-required',+ };+ }+ let plugins: VisiblePluginSummary[];+ try {+ plugins = visiblePluginsForOwner(owner, await this.api.listAll());+ } catch (error) {+ log.warn('market list unavailable', {+ error: error instanceof Error ? error.message : String(error),+ });+ return {+ items: [],+ unavailableReason: error instanceof Error ? error.message : String(error),+ };+ }++ requireSameMarketOwner(owner);+ const ledger = this.ledgerForOwner(owner);+ await this.adoptLegacyInstallations(plugins, ledger, owner);+ await this.reconcileRemovedInstallations(ledger, owner);+ await this.applyDefaultInstalls(plugins, owner, ledger);+ requireSameMarketOwner(owner);+ return { items: this.toItems(plugins, ledger), unavailableReason: null };+ }++ async detail(pluginId: string): Promise<PluginMarketDetail> {+ if (!isValidPluginResourceId(pluginId)) {+ throwIpcError('INVALID_PARAMS', 'Invalid Plugin ID');+ }+ this.requireConfigured();+ const owner = captureMarketOwner();+ const plugin = await this.api.detail(pluginId);+ requireSameMarketOwner(owner);+ if (owner.mode === 'local' && plugin.scope !== 'public') {+ throwIpcError('PERMISSION_DENIED', 'Local mode can only access public Plugins');+ }+ const compatible = validateGhostManifest(plugin.currentRelease.manifest);+ if (!compatible.ok) {+ throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');+ }+ return {+ ...this.toItem(+ plugin,+ NO_DUPLICATE_GHOST_IDS,+ this.localInstallSnapshot(this.ledgerForOwner(owner)),+ ),+ manifest: compatible.manifest,+ };+ }++ async install(+ pluginId: string,+ options?: {+ allowPermissionExpansion?: boolean;+ nodeAuthorizationWebContents?: WebContents;+ },+ ): Promise<{ ghost: InstalledGhost }> {+ if (!isValidPluginResourceId(pluginId)) {+ throwIpcError('INVALID_PARAMS', 'Invalid Plugin ID');+ }+ this.requireConfigured();+ const owner = captureMarketOwner();+ const ledger = this.ledgerForOwner(owner);+ return this.withMutation(pluginId, async () => {+ requireSameMarketOwner(owner);+ const catalog = visiblePluginsForOwner(owner, await this.api.listAll());+ 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);+ return {+ ghost: await this.installDetail(+ plugin,+ {+ allowPermissionExpansion:+ options?.allowPermissionExpansion === true,+ ...(options?.nodeAuthorizationWebContents+ ? { nodeAuthorizationWebContents: options.nodeAuthorizationWebContents }+ : {}),+ },+ owner,+ ledger,+ ),+ };+ });+ }++ async uninstall(pluginId: string): Promise<{ ok: true }> {+ if (!isValidPluginResourceId(pluginId)) {+ throwIpcError('INVALID_PARAMS', 'Invalid Plugin ID');+ }+ const owner = captureMarketOwner();+ const ledger = this.ledgerForOwner(owner);+ return this.withMutation(pluginId, async () => {+ requireSameMarketOwner(owner);+ const data = ledger.read();+ const record = Object.values(data.installations).find(+ (candidate) => candidate.pluginId === pluginId && candidate.installed,+ );+ if (!record) {+ throwIpcError('NOT_FOUND', 'The market Plugin is not installed');+ }+ const installSubject = defaultInstallSubject(owner);+ requireSameMarketOwner(owner);+ await uninstallGhostAndCleanup(record.ghostId, { skipMarketLedger: true });+ // The package removal is already complete at this point. The session may+ // have changed while the runtime was stopping, so ledger reconciliation+ // must not turn a successful uninstall into an IPC failure. The ledger+ // instance is bound to the original owner's path, and the write is+ // serialized separately from the active-session check.+ try {+ await this.withCapturedLedgerMutation(ledger, () => {+ ledger.markRemoved(record.ghostId, installSubject);+ });+ } catch (error) {+ log.warn('market uninstall ledger reconciliation deferred', {+ ghostId: record.ghostId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ return { ok: true };+ });+ }++ /**+ * Captures the active owner and ledger before a local-page uninstall starts.+ * The returned completion records opt-out only after the package was removed.+ */+ prepareLocalUninstallTracking(ghostId: string): (() => Promise<void>) | null {+ let owner: ActiveAppSession;+ try {+ owner = captureMarketOwner();+ } catch {+ return null;+ }+ const ledger = this.ledgerForOwner(owner);+ const record = ledger.installationForGhost(ghostId);+ if (!record?.installed) return null;+ const installSubject = defaultInstallSubject(owner);+ return async () => {+ await this.withCapturedLedgerMutation(ledger, () => {+ ledger.markRemoved(ghostId, installSubject);+ });+ };+ }++ private async installDetail(+ plugin: VisiblePluginDetail,+ options: {+ allowPermissionExpansion?: boolean;+ initiallyEnabled?: boolean;+ nodeAuthorizationWebContents?: WebContents;+ } = {},+ owner = captureMarketOwner(),+ ledger = this.ledgerForOwner(owner),+ ): Promise<InstalledGhost> {+ requireSameMarketOwner(owner);+ if (owner.mode === 'local' && plugin.scope !== 'public') {+ throwIpcError('PERMISSION_DENIED', 'Local mode can only access public Plugins');+ }+ const existing = getGhostManager()+ .list()+ .find((ghost) => ghost.manifest.id === plugin.ghostId);+ const currentRecord = ledger.installationForGhost(plugin.ghostId);+ if (existing && (!currentRecord?.installed || currentRecord.pluginId !== plugin.id)) {+ throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');+ }++ const compatible = validateGhostManifest(plugin.currentRelease.manifest);+ if (!compatible.ok) {+ throwIpcError('GHOST_FILE_INVALID', 'This Plugin manifest is not supported');+ }+ if (+ existing &&+ diffGhostPermissionItems(existing.manifest, compatible.manifest).added.length > 0 &&+ options.allowPermissionExpansion !== true+ ) {+ throwIpcError('PRECONDITION_FAILED', 'Plugin permissions changed and require review');+ }+ const download = await this.api.download(plugin.id, plugin.currentRelease.id);+ requireSameMarketOwner(owner);+ if (+ download.sha256 !== plugin.currentRelease.sha256 ||+ download.sizeBytes !== plugin.currentRelease.sizeBytes+ ) {+ throwIpcError('PRECONDITION_FAILED', 'Plugin release metadata changed');+ }+ const expiresAt = Date.parse(download.expiresAt);+ if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) {+ throwIpcError('PRECONDITION_FAILED', 'Plugin download authorization expired');+ }++ const tempPath = path.join(+ app.getPath('temp'),+ `cindy-plugin-${plugin.id}-${crypto.randomUUID()}.cindy`,+ );+ try {+ await downloadVerifiedPlugin(download.url, download, tempPath);+ requireSameMarketOwner(owner);+ const ghost = await installOrUpdateMarketGhostPackage(tempPath, {+ ghostId: plugin.ghostId,+ version: plugin.currentRelease.version,+ initiallyEnabled: options.initiallyEnabled === true,+ ...(options.nodeAuthorizationWebContents+ ? { nodeAuthorizationWebContents: options.nodeAuthorizationWebContents }+ : {}),+ });+ // Once the package directory is committed, finish provenance against the+ // owner captured at operation start even if the active session changes.+ // The bound ledger prevents this write from leaking into the new owner.+ await this.withCapturedLedgerMutation(ledger, () => {+ ledger.upsertInstallation(recordFrom(plugin, 'market'));+ });+ return ghost;+ } finally {+ await fs.promises.rm(tempPath, { force: true }).catch(() => undefined);+ }+ }++ private requireConfigured(): void {+ if (!getClientEndpoint('pluginApiBaseUrl')) {+ throwIpcError('UNSUPPORTED_CAPABILITY', 'Plugin market is not configured');+ }+ }++ private toItems(+ plugins: readonly VisiblePluginSummary[],+ ledger = this.ledger,+ ): PluginMarketItem[] {+ const counts = ghostIdCounts(plugins);+ const duplicateGhostIds = new Set(+ plugins+ .filter((plugin) => (counts.get(plugin.ghostId) ?? 0) > 1)+ .map((plugin) => plugin.ghostId),+ );+ const local = this.localInstallSnapshot(ledger);+ return plugins.map((plugin) => this.toItem(plugin, duplicateGhostIds, local));+ }++ private toItem(+ plugin: VisiblePluginSummary | VisiblePluginDetail,+ duplicateGhostIds: ReadonlySet<string> = NO_DUPLICATE_GHOST_IDS,+ local = this.localInstallSnapshot(),+ ): PluginMarketItem {+ const ghost = local.ghostsById.get(plugin.ghostId);+ const record = local.installations[plugin.ghostId];+ const ownsInstall = Boolean(+ ghost && record?.installed && record.pluginId === plugin.id,+ );+ const conflict = Boolean(+ duplicateGhostIds.has(plugin.ghostId) ||+ (ghost && (!record?.installed || record.pluginId !== plugin.id)),+ );+ const installState: PluginMarketItem['installState'] = conflict+ ? 'conflict'+ : !ownsInstall+ ? 'not-installed'+ : record?.releaseId === plugin.currentRelease.id+ ? 'installed'+ : 'update-available';+ return {+ pluginId: plugin.id,+ ghostId: plugin.ghostId,+ name: plugin.name,+ description: plugin.description,+ author: plugin.author,+ scope: plugin.scope,+ organizationId: plugin.organizationId,+ defaultInstall: plugin.defaultInstall,+ releaseId: plugin.currentRelease.id,+ version: plugin.currentRelease.version,+ publishedAt: plugin.currentRelease.publishedAt,+ icon: plugin.currentRelease.icon,+ installState,+ enabled: ownsInstall ? (ghost?.enabled ?? null) : null,+ };+ }++ private async adoptLegacyInstallations(+ plugins: readonly VisiblePluginSummary[],+ ledger: PluginMarketLedger,+ owner: ActiveAppSession,+ ): Promise<void> {+ const counts = ghostIdCounts(plugins);+ const installations = ledger.read().installations;+ for (const ghost of getGhostManager().list()) {+ if (installations[ghost.manifest.id]) continue;+ if (!isOfficialGhostId(ghost.manifest.id)) continue;+ const matches = plugins.filter(+ (plugin) =>+ counts.get(plugin.ghostId) === 1 &&+ plugin.scope !== 'personal' &&+ plugin.ghostId === ghost.manifest.id,+ );+ if (matches.length !== 1) continue;+ const record = legacyRecordFrom(matches[0], ghost);+ await this.withLedgerMutation(owner, () => {+ ledger.upsertInstallation(record);+ });+ installations[record.ghostId] = record;+ log.info('legacy plugin adopted into market ledger', {+ ghostId: ghost.manifest.id,+ pluginId: matches[0].id,+ exactCurrentRelease: record.releaseId === matches[0].currentRelease.id,+ });+ }+ }++ private async reconcileRemovedInstallations(+ ledger: PluginMarketLedger,+ owner: ActiveAppSession,+ ): Promise<void> {+ const installedIds = new Set(+ getGhostManager().list().map((ghost) => ghost.manifest.id),+ );+ const installSubject = defaultInstallSubject(owner);+ for (const record of Object.values(ledger.read().installations)) {+ if (record.installed && !installedIds.has(record.ghostId)) {+ await this.withLedgerMutation(owner, () => {+ ledger.markRemoved(record.ghostId, installSubject);+ });+ }+ }+ }++ private async applyDefaultInstalls(+ plugins: readonly VisiblePluginSummary[],+ owner: ActiveAppSession,+ ledger: PluginMarketLedger,+ ): Promise<void> {+ const installSubject = defaultInstallSubject(owner);+ const counts = ghostIdCounts(plugins);+ const uniqueGhostIds = new Set(+ plugins+ .filter((plugin) => counts.get(plugin.ghostId) === 1)+ .map((plugin) => plugin.ghostId),+ );+ const ledgerData = ledger.read();+ const local = this.localInstallSnapshot(ledger, ledgerData.installations);+ for (const summary of plugins) {+ if (!summary.defaultInstall || !uniqueGhostIds.has(summary.ghostId)) continue;+ if (ledgerData.defaultInstallOptOuts[installSubject]?.includes(summary.id)) continue;+ if (isBuiltinGhostRemovedByUser(summary.ghostId)) continue;+ const state = this.toItem(summary, NO_DUPLICATE_GHOST_IDS, local).installState;+ if (state !== 'not-installed') continue;+ try {+ await this.withMutation(summary.id, async () => {+ requireSameMarketOwner(owner);+ const detail = await this.api.detail(summary.id);+ await this.installDetail(+ detail,+ { initiallyEnabled: true },+ owner,+ ledger,+ );+ });+ } catch (error) {+ // 单个默认插件失败不拖垮整个市场;下次同步可重试。+ log.warn('default plugin install failed', {+ pluginId: summary.id,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ }++ private localInstallSnapshot(+ ledger = this.ledger,+ installations = ledger.read().installations,+ ): LocalInstallSnapshot {+ return {+ ghostsById: new Map(+ getGhostManager().list().map((ghost) => [ghost.manifest.id, ghost]),+ ),+ installations,+ };+ }++ private ledgerForOwner(owner: ActiveAppSession): PluginMarketLedger {+ requireSameMarketOwner(owner);+ return this.ledger.bind(+ ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'),+ );+ }++ private withLedgerMutation<T>(+ owner: ActiveAppSession,+ operation: () => T | Promise<T>,+ ): Promise<T> {+ const current = this.ledgerMutation.then(() => {+ requireSameMarketOwner(owner);+ return operation();+ });+ this.ledgerMutation = current.then(+ () => undefined,+ () => undefined,+ );+ return current;+ }++ /**+ * Serializes a ledger mutation against other operations without resolving+ * the ledger path from the current session. Callers that use this directly+ * must pass a ledger already bound to the operation's original owner.+ */+ private withCapturedLedgerMutation<T>(+ _ledger: PluginMarketLedger,+ operation: () => T | Promise<T>,+ ): Promise<T> {+ const current = this.ledgerMutation.then(() => {+ return operation();+ });+ this.ledgerMutation = current.then(+ () => undefined,+ () => undefined,+ );+ return current;+ }++ 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);+ this.mutations.set(pluginId, current);+ const cleanup = () => {+ if (this.mutations.get(pluginId) === current) this.mutations.delete(pluginId);+ };+ void current.then(cleanup, cleanup);+ return current;+ }+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 6f34a4f4d7..96e25e69a0 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -855,6 +855,21 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('ghosts:dev-runtime', action, id),},+ pluginMarket: {+ snapshot: (): Promise<import('../shared/pluginMarket').PluginMarketSnapshot> =>+ ipcRenderer.invoke('plugin-market:snapshot'),+ detail: (+ pluginId: string,+ ): Promise<import('../shared/pluginMarket').PluginMarketDetail> =>+ ipcRenderer.invoke('plugin-market:detail', pluginId),+ install: (+ pluginId: string,+ options?: { allowPermissionExpansion?: boolean },+ ): Promise<{ ghost: import('../shared/ghost').InstalledGhost }> =>+ ipcRenderer.invoke('plugin-market:install', pluginId, options),+ uninstall: (pluginId: string): Promise<{ ok: true }> =>+ ipcRenderer.invoke('plugin-market:uninstall', pluginId),+ },voiceInput: {prewarm: (payload?: { sourceLanguage?: string; refinementEnabled?: boolean }): Promise<{ ok: true }> =>ipcRenderer.invoke('voice-input:prewarm', payload),diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex 4becae8909..8210921707 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -65,6 +65,7 @@ interface GhostPluginDetailViewProps {onToggle: (enabled: boolean) => void;onUse: () => void;onUpdate: () => void;+ updateLabel?: string;onUninstall: () => void;toggleDisabled: boolean;}@@ -119,6 +120,7 @@ export function GhostPluginDetailView({onToggle,onUse,onUpdate,+ updateLabel,onUninstall,toggleDisabled,}: GhostPluginDetailViewProps) {@@ -246,7 +248,7 @@ export function GhostPluginDetailView({onSelect={onUpdate}className="h-10 rounded-lg px-3 text-13 focus:bg-[var(--surface-hover-soft)]">- {t('settings.ghosts.detail.updateFromFile')}+ {updateLabel ?? t('settings.ghosts.detail.updateFromFile')}</DropdownMenuItem><DropdownMenuSeparator className="mx-2 my-1 h-px bg-[var(--border-default)]" /><DropdownMenuItemdiff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginIcon.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginIcon.tsxindex 27ae5c4cd1..cebbba2ea7 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginIcon.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginIcon.tsx@@ -14,6 +14,7 @@ import {Workflow,type LucideIcon,} from 'lucide-react';+import { useEffect, useState } from 'react';import { cn } from '@/lib/utils';import { ghostFallbackIconKind, type GhostFallbackIconKind } from './lib/ghostPluginViewModel';@@ -67,7 +68,12 @@ export function GhostPluginIcon({iconName: string;size?: GhostPluginIconSize;}) {- const svg = iconDataUrl ? isSvgIconSrc(iconDataUrl) : false;+ const [failedSrc, setFailedSrc] = useState<string | null>(null);+ useEffect(() => {+ setFailedSrc(null);+ }, [iconDataUrl]);+ const resolvedIconDataUrl = iconDataUrl && failedSrc !== iconDataUrl ? iconDataUrl : undefined;+ const svg = resolvedIconDataUrl ? isSvgIconSrc(resolvedIconDataUrl) : false;const fallbackKind = ghostFallbackIconKind(iconName, iconId);const FallbackIcon = FALLBACK_ICONS[fallbackKind];@@ -75,17 +81,19 @@ export function GhostPluginIcon({<spanclassName={cn('inline-flex shrink-0 items-center justify-center overflow-hidden border-[0.5px] border-[var(--border-default)]',- iconDataUrl+ resolvedIconDataUrl? 'bg-[var(--plugin-icon-surface)] shadow-[var(--plugin-icon-shadow)]': 'bg-[var(--surface-elevated)] text-[var(--text-secondary)] shadow-none',CONTAINER_CLASSES[size],)}>- {iconDataUrl ? (+ {resolvedIconDataUrl ? (<img- src={iconDataUrl}+ src={resolvedIconDataUrl}alt=""draggable={false}+ referrerPolicy="no-referrer"+ onError={() => setFailedSrc(resolvedIconDataUrl)}className={cn(svg ? SVG_ICON_CLASSES[size] : 'size-full object-cover',iconId === 'cindy-github' && 'plugin-icon--github',diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsxindex 0aab644fe5..4410486bc2 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx@@ -8,9 +8,10 @@import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';import { useNavigate, useSearchParams } from 'react-router-dom';-import { ChevronDown, Plus, Sparkles, Upload } from 'lucide-react';+import { ChevronDown, ChevronRight, Plus, Sparkles, Upload } from 'lucide-react';import { useTranslation } from 'react-i18next';+import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { Tip } from '@/components/ui/tooltip';import {@@ -22,6 +23,7 @@ import {} from '@/components/ui/dropdown-menu';import { toast } from '@/lib/toast';import { extractIpcError } from '@/utils/ipcError';+import { useAuth } from '@/contexts/AuthContext';import { useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';import { NEW_MAKER_DRAFT_KEY } from '@/features/cc-agent/newMakerDraftKeys';import {@@ -32,11 +34,21 @@ import {import { patchDraft } from '@/state/newMakerDraft';import { ghostInstallErrorKey } from '@/cindy-brain/installErrorKey';import { confirmAndInstallGhost, pickAndUpdateGhost } from '@/cindy-brain/installFlow';+import { GhostPermissionDiffView } from '@/cindy-brain/GhostPermissionList';import { cn } from '@/lib/utils';import { Switch } from '@/components/ui/switch';import { getLastWorkingDir, subscribeToLastWorkingDir } from '@/state/lastWorkingDir';import { findSplitChildByPanelKind } from '../../../shared/layoutTree';-import { ghostPanelKind, type GhostSetupStatus } from '../../../shared/ghost';+import {+ diffGhostPermissionItems,+ ghostPanelKind,+ type GhostSetupStatus,+} from '../../../shared/ghost';+import type {+ PluginMarketDetail,+ PluginMarketItem,+ PluginMarketSnapshot,+} from '../../../shared/pluginMarket';import {toGhostPluginDetail,toGhostPluginListItem,@@ -48,10 +60,25 @@ import { formatSetupGateDescription } from './lib/ghostSetupGateModel';import { PluginManagementLayout, PluginManagementPage } from './PluginManagementLayout';import { GhostPluginDetailView } from './GhostPluginDetailView';import { GhostPluginIcon } from './GhostPluginIcon';+import { MarketPluginDetailView } from './MarketPluginDetailView';import { PluginScopePicker, usePluginRecentWorkdirs } from './PluginScopePicker';+import {+ pluginPresentationOrigin,+ type PluginPresentationOrigin,+} from './lib/pluginMarketPresentation';+import { pluginMarketErrorKey } from './lib/pluginMarketErrorKey';import './plugin-motion.css';const MAX_VISIBLE_INSTALLED_GHOSTS = 5;+type PluginPresentationFilter = 'all' | PluginPresentationOrigin;+type PresentedGhostPluginItem = GhostPluginListItem & { origin: PluginPresentationOrigin };++const PRESENTATION_FILTERS: readonly PluginPresentationFilter[] = [+ 'all',+ 'public',+ 'organization',+ 'local',+];/*** Ghost-backed Plugin page.@@ -65,10 +92,39 @@ export function GhostPluginPage() {const navigate = useNavigate();const [searchParams, setSearchParams] = useSearchParams();const { confirm, confirmWithCheckbox } = useConfirmDialog();+ const { user, mode, dataOwnerId } = useAuth();+ const showEnterprise = user?.membershipKind === 'org';const ghosts = useInstalledGhosts();const [selectedId, setSelectedId] = useState<string | null>(null);const [query, setQuery] = useState('');const [installedExpanded, setInstalledExpanded] = useState(false);+ const [marketSnapshot, setMarketSnapshot] = useState<PluginMarketSnapshot | null>(null);+ const [originFilter, setOriginFilter] = useState<PluginPresentationFilter>('all');+ const [marketDetail, setMarketDetail] = useState<PluginMarketDetail | null>(null);+ const [marketBusyId, setMarketBusyId] = useState<string | null>(null);+ const marketRefreshRequestRef = useRef(0);+ const marketDetailRequestRef = useRef(0);+ const refreshMarket = useCallback(async () => {+ const requestId = ++marketRefreshRequestRef.current;+ try {+ const snapshot = await window.electronAPI.pluginMarket.snapshot();+ if (requestId === marketRefreshRequestRef.current) setMarketSnapshot(snapshot);+ } catch (error) {+ if (requestId === marketRefreshRequestRef.current) {+ setMarketSnapshot({+ items: [],+ unavailableReason: error instanceof Error ? error.message : String(error),+ });+ }+ }+ }, []);+ useEffect(() => {+ setMarketSnapshot(null);+ setMarketDetail(null);+ setMarketBusyId(null);+ marketDetailRequestRef.current += 1;+ void refreshMarket();+ }, [refreshMarket, mode, dataOwnerId]);const activeSessionWorkingDir = useSyncExternalStore(subscribeToLastWorkingDir,getLastWorkingDir,@@ -130,7 +186,15 @@ export function GhostPluginPage() {next.delete('ghost');setSearchParams(next, { replace: true });}, [searchParams, setSearchParams]);- const installedItems = useMemo(+ const marketItems = marketSnapshot?.items ?? [];+ const marketByGhostId = useMemo(() => {+ const map = new Map<string, PluginMarketItem>();+ for (const item of marketItems) {+ if (item.installState !== 'conflict') map.set(item.ghostId, item);+ }+ return map;+ }, [marketItems]);+ const allInstalledItems = useMemo<PresentedGhostPluginItem[]>(() =>ghosts// cindy-mivo was renamed to xd-mivo. Older user data can still@@ -140,21 +204,88 @@ export function GhostPluginPage() {ghost.manifest.id !== 'cindy-mivo' ||!ghosts.some((candidate) => candidate.manifest.id === 'xd-mivo'),)- .map((ghost) => toGhostPluginListItem(ghost)),- [ghosts],+ .map((ghost) => ({+ ...toGhostPluginListItem(ghost),+ origin: pluginPresentationOrigin(marketByGhostId.get(ghost.manifest.id)),+ })),+ [ghosts, marketByGhostId],+ );+ const installedItems = useMemo(+ () =>+ showEnterprise+ ? allInstalledItems+ : allInstalledItems.filter((item) => item.origin !== 'organization'),+ [allInstalledItems, showEnterprise],);const installedShortcutItems = useMemo(() => sortGhostPluginItemsByRecentUse(installedItems, recentGhostIds),[installedItems, recentGhostIds],);- const items = useMemo(+ const searchedInstalledItems = useMemo(() => filterGhostPluginItems(installedItems, query),[installedItems, query],);+ const searchedAvailableMarketItems = useMemo(() => {+ const normalizedQuery = query.trim().toLocaleLowerCase();+ return marketItems.filter((item) => {+ if (item.installState === 'installed' || item.installState === 'update-available') {+ return false;+ }+ if (!showEnterprise && pluginPresentationOrigin(item) === 'organization') return false;+ return `${item.name} ${item.description ?? ''} ${item.ghostId} ${item.author ?? ''}`+ .toLocaleLowerCase()+ .includes(normalizedQuery);+ });+ }, [marketItems, query, showEnterprise]);+ const originFilters = useMemo(+ () =>+ showEnterprise+ ? PRESENTATION_FILTERS+ : PRESENTATION_FILTERS.filter((filter) => filter !== 'organization'),+ [showEnterprise],+ );+ const effectiveOriginFilter =+ !showEnterprise && originFilter === 'organization' ? 'all' : originFilter;+ const items = useMemo(+ () =>+ effectiveOriginFilter === 'all'+ ? searchedInstalledItems+ : searchedInstalledItems.filter((item) => item.origin === effectiveOriginFilter),+ [effectiveOriginFilter, searchedInstalledItems],+ );+ const availableMarketItems = useMemo(+ () =>+ effectiveOriginFilter === 'all'+ ? searchedAvailableMarketItems+ : searchedAvailableMarketItems.filter(+ (item) => pluginPresentationOrigin(item) === effectiveOriginFilter,+ ),+ [effectiveOriginFilter, searchedAvailableMarketItems],+ );+ const originCounts = useMemo(() => {+ const counts: Record<PluginPresentationOrigin, number> = {+ public: 0,+ organization: 0,+ local: 0,+ };+ for (const item of searchedInstalledItems) counts[item.origin] += 1;+ for (const item of searchedAvailableMarketItems) {+ counts[pluginPresentationOrigin(item)] += 1;+ }+ return counts;+ }, [searchedAvailableMarketItems, searchedInstalledItems]);+ const searchedItemCount = searchedInstalledItems.length + searchedAvailableMarketItems.length;const selectedGhost = selectedId? (ghosts.find((ghost) => ghost.manifest.id === selectedId) ?? null): null;const selectedDetail = selectedGhost ? toGhostPluginDetail(selectedGhost) : null;+ const selectedMarketInstall = selectedDetail+ ? (marketByGhostId.get(selectedDetail.id) ?? null)+ : null;+ const selectedMarketUpdate =+ selectedMarketInstall?.installState === 'update-available'+ ? selectedMarketInstall+ : null;const panelStatus = useMemo(() => {if (!selectedDetail || selectedDetail.panelMinWidth === null) return null;@@ -201,8 +332,56 @@ export function GhostPluginPage() {const handleUpdate = useCallback(async () => {if (!selectedDetail) return;+ if (selectedMarketUpdate) {+ setMarketBusyId(selectedMarketUpdate.pluginId);+ try {+ const next = await window.electronAPI.pluginMarket.detail(+ selectedMarketUpdate.pluginId,+ );+ const diff = diffGhostPermissionItems(+ selectedGhost?.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: selectedGhost?.manifest.version ?? selectedDetail.version,+ to: next.version,+ }),+ content: <GhostPermissionDiffView diff={diff} />,+ maxWidth: 520,+ confirmText: t('settings.ghosts.updateConfirm.confirm'),+ cancelText: t('settings.ghosts.updateConfirm.cancel'),+ });+ if (!approved) return;+ const result = await window.electronAPI.pluginMarket.install(+ selectedMarketUpdate.pluginId,+ { allowPermissionExpansion: diff.added.length > 0 },+ );+ toast.success(+ t('settings.ghosts.toast.updated', {+ name: result.ghost.manifest.name,+ version: result.ghost.manifest.version,+ }),+ );+ await refreshMarket();+ } catch (error) {+ toast.error(t(pluginMarketErrorKey(error)));+ } finally {+ setMarketBusyId(null);+ }+ return;+ }await pickAndUpdateGhost(selectedDetail.id, { t, confirm, confirmWithCheckbox });- }, [confirm, confirmWithCheckbox, selectedDetail, t]);+ }, [+ confirm,+ confirmWithCheckbox,+ refreshMarket,+ selectedDetail,+ selectedGhost,+ selectedMarketUpdate,+ t,+ ]);const handleInstall = useCallback(async () => {const picked = await window.electronAPI.ghosts.pickFile().catch(() => null);@@ -297,12 +476,83 @@ export function GhostPluginPage() {});if (!ok) return;try {- await window.electronAPI.ghosts.uninstall(selectedDetail.id);+ if (selectedMarketInstall) {+ await window.electronAPI.pluginMarket.uninstall(selectedMarketInstall.pluginId);+ await refreshMarket();+ } else {+ await window.electronAPI.ghosts.uninstall(selectedDetail.id);+ }toast.success(t('settings.ghosts.toast.uninstalled', { name: selectedDetail.name }));} catch (error) {- toast.error(t(ghostInstallErrorKey(extractIpcError(error)?.code)));+ toast.error(+ selectedMarketInstall+ ? t(pluginMarketErrorKey(error))+ : t(ghostInstallErrorKey(extractIpcError(error)?.code)),+ );+ }+ }, [confirm, refreshMarket, selectedDetail, selectedMarketInstall, t]);++ const handleSelectMarket = useCallback(+ async (pluginId: string) => {+ const requestId = ++marketDetailRequestRef.current;+ setMarketBusyId(pluginId);+ try {+ const detail = await window.electronAPI.pluginMarket.detail(pluginId);+ if (requestId === marketDetailRequestRef.current) setMarketDetail(detail);+ } catch (error) {+ if (requestId === marketDetailRequestRef.current) {+ toast.error(t(pluginMarketErrorKey(error)));+ }+ } finally {+ if (requestId === marketDetailRequestRef.current) setMarketBusyId(null);+ }+ },+ [t],+ );++ const handleInstallFromMarket = useCallback(async () => {+ if (!marketDetail) return;+ const confirmed = await confirm({+ title: t('settings.ghosts.market.installConfirmTitle', {+ name: marketDetail.name,+ }),+ description: t('settings.ghosts.market.installConfirmDescription'),+ confirmText: t('settings.ghosts.market.install'),+ cancelText: t('settings.ghosts.installConfirm.cancel'),+ autoFocusConfirm: true,+ });+ if (!confirmed) return;+ setMarketBusyId(marketDetail.pluginId);+ try {+ const result = await window.electronAPI.pluginMarket.install(marketDetail.pluginId);+ toast.success(+ t('settings.ghosts.toast.installedAsleep', {+ name: result.ghost.manifest.name,+ }),+ );+ setMarketDetail(null);+ setSelectedId(result.ghost.manifest.id);+ await refreshMarket();+ } catch (error) {+ toast.error(t(pluginMarketErrorKey(error)));+ } finally {+ setMarketBusyId(null);}- }, [confirm, selectedDetail, t]);+ }, [confirm, marketDetail, refreshMarket, t]);++ if (marketDetail) {+ return (+ <MarketPluginDetailView+ detail={marketDetail}+ busy={marketBusyId === marketDetail.pluginId}+ onBack={() => {+ marketDetailRequestRef.current += 1;+ setMarketDetail(null);+ }}+ onInstall={() => void handleInstallFromMarket()}+ />+ );+ }if (selectedDetail) {return (@@ -319,6 +569,11 @@ export function GhostPluginPage() {onToggle={(enabled) => void handleToggle(selectedDetail.id, enabled)}onUse={handleUse}onUpdate={() => void handleUpdate()}+ updateLabel={+ selectedMarketUpdate+ ? t('settings.ghosts.market.update')+ : undefined+ }onUninstall={() => void handleUninstall()}toggleDisabled={scopeDir !== null && selectedGhost !== null && !selectedGhost.enabled}/>@@ -446,21 +701,69 @@ export function GhostPluginPage() {) : null}<section className="plugin-motion-page-section mt-6 min-w-0">- <div className="mb-5 flex items-baseline gap-2">- <h2 className="text-20 font-medium text-[var(--text-primary)]">- {t('settings.ghosts.page.allTitle')}- </h2>- <span className="text-13 tabular-nums text-[var(--text-tertiary)]">- {items.length}- </span>+ <div className="mb-5 flex flex-col gap-4 md:flex-row md:items-center md:justify-between">+ <div className="flex items-baseline gap-2">+ <h2 className="text-20 font-medium text-[var(--text-primary)]">+ {t('settings.ghosts.page.allTitle')}+ </h2>+ <span className="text-13 tabular-nums text-[var(--text-tertiary)]">+ {items.length + availableMarketItems.length}+ </span>+ </div>+ <div+ className="flex max-w-full items-center gap-1 overflow-x-auto"+ role="group"+ aria-label={t('settings.ghosts.page.filtersAria')}+ style={WINDOW_NO_DRAG_STYLE}+ >+ {originFilters.map((filter) => {+ const selected = effectiveOriginFilter === filter;+ const count = filter === 'all' ? searchedItemCount : originCounts[filter];+ return (+ <button+ key={filter}+ type="button"+ aria-pressed={selected}+ onClick={() => setOriginFilter(filter)}+ className={cn(+ 'shrink-0 select-none rounded-full px-3.5 py-2 text-12 transition-colors duration-150',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',+ selected+ ? 'bg-[var(--surface-chip)] text-[var(--text-primary)]'+ : 'text-[var(--text-secondary)] hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)]',+ )}+ >+ {filter === 'all'+ ? t('settings.ghosts.page.filterAll')+ : t(`settings.ghosts.page.origin.${filter}`)}+ <span className="ml-1.5 tabular-nums text-[var(--text-tertiary)]">+ {count}+ </span>+ </button>+ );+ })}+ </div></div>- {items.length > 0 ? (+ {marketSnapshot?.unavailableReason ? (+ <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(+ marketSnapshot.unavailableReason === 'authentication-required'+ ? 'settings.ghosts.market.authenticationRequired'+ : marketSnapshot.unavailableReason === 'not-configured'+ ? 'settings.ghosts.market.notConfigured'+ : 'settings.ghosts.market.unavailable',+ )}+ </p>+ ) : null}++ {items.length > 0 || availableMarketItems.length > 0 ? (<div className="plugin-motion-stagger grid grid-cols-1 gap-3 sm:grid-cols-2">{items.map((item) => (<GhostPluginCardkey={item.id}item={item}+ sourceLabel={t(`settings.ghosts.page.origin.${item.origin}`)}onSelect={() => setSelectedId(item.id)}onAction={() => void handleUseGhost(item.id)}effectiveEnabled={effectiveEnabled(item.id, item.enabled)}@@ -468,15 +771,23 @@ export function GhostPluginPage() {onToggle={(enabled) => void handleToggle(item.id, enabled)}/>))}+ {availableMarketItems.map((item) => (+ <MarketPluginCard+ key={item.pluginId}+ item={item}+ busy={marketBusyId === item.pluginId}+ onSelect={() => void handleSelectMarket(item.pluginId)}+ />+ ))}</div>) : (<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)]">- {installedItems.length === 0+ {installedItems.length === 0 && marketItems.length === 0? t('settings.ghosts.empty'): t('settings.ghosts.page.emptyFiltered')}</p>- {installedItems.length === 0 ? (+ {installedItems.length === 0 && marketItems.length === 0 ? (<p className="mt-1.5 text-12 text-[var(--text-tertiary)]">{t('settings.ghosts.emptyHint')}</p>@@ -490,6 +801,84 @@ export function GhostPluginPage() {);}+function MarketPluginCard({+ item,+ busy,+ onSelect,+}: {+ item: PluginMarketItem;+ busy: boolean;+ onSelect: () => void;+}) {+ const { t } = useTranslation();+ return (+ <article+ className={cn(+ 'group flex min-h-[108px] w-full select-none items-start gap-4 rounded-xl border-[0.5px] border-[var(--border-default)] bg-[var(--surface-elevated)] p-4 text-left',+ 'transition-[background-color,border-color,transform] duration-150 ease-out',+ 'hover:-translate-y-px hover:border-[var(--text-tertiary)] hover:bg-[var(--surface-hover-soft)]',+ 'active:translate-y-0 active:scale-[0.992] motion-reduce:transform-none motion-reduce:transition-none',+ )}+ >+ <button+ type="button"+ onClick={onSelect}+ disabled={busy || item.installState === 'conflict'}+ className="flex min-w-0 flex-1 items-start gap-4 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-wait"+ aria-label={item.name}+ >+ <GhostPluginIcon+ iconDataUrl={item.icon?.url}+ iconId={item.ghostId}+ iconName={item.name}+ />+ <span className="flex min-w-0 flex-1 flex-col self-stretch pt-0.5">+ <span className="flex min-w-0 items-center gap-2">+ <span className="truncate text-15 font-medium text-[var(--text-primary)]">+ {item.name}+ </span>+ </span>+ <span className="mt-1 flex min-w-0 items-center gap-1.5 text-11 text-[var(--text-tertiary)]">+ <span>+ {t(`settings.ghosts.page.origin.${pluginPresentationOrigin(item)}`)}+ </span>+ <span aria-hidden="true">·</span>+ <span>v{item.version}</span>+ <span aria-hidden="true">·</span>+ <span className="truncate font-mono">{item.ghostId}</span>+ {item.author ? (+ <>+ <span aria-hidden="true">·</span>+ <span className="truncate">{item.author}</span>+ </>+ ) : null}+ </span>+ <span className="mt-1.5 line-clamp-2 text-13 leading-5 text-[var(--text-secondary)]">+ {item.description || item.ghostId}+ </span>+ </span>+ </button>+ <button+ type="button"+ onClick={onSelect}+ disabled={busy || item.installState === 'conflict'}+ className={cn(+ 'inline-flex h-8 shrink-0 items-center gap-1.5 self-center rounded-lg border border-[var(--border-default)] px-3 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',+ )}+ >+ <ChevronRight size={13} aria-hidden="true" />+ {t(+ item.installState === 'conflict'+ ? 'settings.ghosts.market.conflict'+ : 'settings.ghosts.market.details',+ )}+ </button>+ </article>+ );+}+/** Plugin-specific creation and import actions rendered after the shared search. */function GhostPluginActions({onInstall,@@ -563,6 +952,7 @@ function GhostPluginActions({/** Compact installed Plugin card. */export function GhostPluginCard({item,+ sourceLabel,onSelect,onAction,onToggle,@@ -570,6 +960,7 @@ export function GhostPluginCard({toggleDisabled = false,}: {item: GhostPluginListItem;+ sourceLabel?: string;onSelect: () => void;onAction: () => void;onToggle?: (enabled: boolean) => void;@@ -599,6 +990,17 @@ export function GhostPluginCard({<span className="truncate text-15 font-medium text-[var(--text-primary)]">{item.name}</span>+ <span className="mt-1 flex min-w-0 items-center gap-1.5 text-11 text-[var(--text-tertiary)]">+ {sourceLabel ? (+ <>+ <span>{sourceLabel}</span>+ <span aria-hidden="true">·</span>+ </>+ ) : null}+ <span>v{item.version}</span>+ <span aria-hidden="true">·</span>+ <span className="truncate font-mono">{item.id}</span>+ </span><span className="mt-1.5 line-clamp-2 text-13 leading-5 text-[var(--text-secondary)]">{item.description || item.id}</span>diff --git a/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsxnew file mode 100644index 0000000000..2f102428f7--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx@@ -0,0 +1,147 @@+import { ArrowLeft, Download, ShieldCheck } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';+import { cn } from '@/lib/utils';+import { ghostPermissionItems } from '../../../shared/ghost';+import type { PluginMarketDetail } from '../../../shared/pluginMarket';+import { GhostPluginIcon } from './GhostPluginIcon';+import { pluginPresentationOrigin } from './lib/pluginMarketPresentation';++interface MarketPluginDetailViewProps {+ detail: PluginMarketDetail;+ busy: boolean;+ onBack: () => void;+ onInstall: () => void;+}+/** 尚未安装的市场 Plugin 详情;只展示协议事实,不创建 renderer 侧安装逻辑。 */+export function MarketPluginDetailView({+ detail,+ busy,+ onBack,+ onInstall,+}: MarketPluginDetailViewProps) {+ const { t } = useTranslation();+ const permissions = ghostPermissionItems(detail.manifest);+ const presentationOrigin = pluginPresentationOrigin(detail);+ const actionKey =+ detail.installState === 'update-available'+ ? 'settings.ghosts.market.update'+ : detail.installState === 'installed'+ ? 'settings.ghosts.market.installed'+ : detail.installState === 'conflict'+ ? 'settings.ghosts.market.conflict'+ : 'settings.ghosts.market.install';+ const actionDisabled =+ busy || detail.installState === 'installed' || detail.installState === 'conflict';++ return (+ <main className="plugin-motion-root h-full min-h-0 w-full overflow-y-auto bg-[var(--surface)] [scrollbar-gutter:stable_both-edges]">+ <article className="plugin-detail-frame mx-auto w-full max-w-[824px] px-8 pb-16 pt-5 max-[760px]:px-6">+ <button+ type="button"+ onClick={onBack}+ className="-ml-3 mb-7 inline-flex h-9 items-center gap-2 rounded-full px-3 text-13 text-[var(--text-secondary)] transition-colors duration-150 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)]"+ style={WINDOW_NO_DRAG_STYLE}+ >+ <ArrowLeft size={16} aria-hidden="true" />+ {t('settings.ghosts.detail.backToList')}+ </button>++ <header>+ <div className="grid grid-cols-[64px_minmax(0,1fr)_auto] items-center gap-5">+ <GhostPluginIcon+ iconDataUrl={detail.icon?.url}+ iconId={detail.ghostId}+ iconName={detail.name}+ size="detail"+ />+ <div className="min-w-0">+ <h1 className="truncate text-28 font-medium leading-[34px] text-[var(--text-primary)]">+ {detail.name}+ </h1>+ <div className="mt-1.5 flex flex-wrap items-center gap-2 text-12 text-[var(--text-tertiary)]">+ <span>{t(`settings.ghosts.market.scope.${presentationOrigin}`)}</span>+ <span aria-hidden="true">·</span>+ <span>v{detail.version}</span>+ {detail.author ? (+ <>+ <span aria-hidden="true">·</span>+ <span>{detail.author}</span>+ </>+ ) : null}+ </div>+ </div>+ <button+ type="button"+ onClick={onInstall}+ disabled={actionDisabled}+ className={cn(+ 'inline-flex h-10 min-w-[104px] items-center justify-center gap-2 rounded-full px-5 text-13 font-medium',+ 'bg-[var(--accent-cta-bg)] text-[var(--accent-pure-cta-fg)]',+ 'transition-[background-color,transform,opacity] 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)]',+ 'disabled:cursor-not-allowed disabled:opacity-40 disabled:active:scale-100',+ )}+ >+ <Download size={15} aria-hidden="true" />+ {t(actionKey)}+ </button>+ </div>+ <p className="mt-5 text-14 leading-[22px] text-[var(--text-secondary)]">+ {detail.description || detail.ghostId}+ </p>+ </header>++ <section className="mt-10" aria-labelledby="market-security-title">+ <h2+ id="market-security-title"+ className="text-18 font-medium leading-[26px] text-[var(--text-primary)]"+ >+ {t('settings.ghosts.market.securityTitle')}+ </h2>+ <div className="mt-5 flex max-w-[760px] items-start gap-3 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-5 py-4">+ <ShieldCheck+ size={18}+ className="mt-0.5 shrink-0 text-[var(--text-secondary)]"+ aria-hidden="true"+ />+ <p className="text-13 leading-5 text-[var(--text-secondary)]">+ {t('settings.ghosts.market.securityDescription')}+ </p>+ </div>+ </section>++ <section className="mt-10" aria-labelledby="market-permissions-title">+ <div className="flex items-baseline gap-2">+ <h2+ id="market-permissions-title"+ className="text-18 font-medium leading-[26px] text-[var(--text-primary)]"+ >+ {t('settings.ghosts.perm.grantsTitle')}+ </h2>+ <span className="text-12 text-[var(--text-tertiary)]">+ {t('settings.ghosts.perm.itemCount', { count: permissions.length })}+ </span>+ </div>+ <div className="mt-5 max-w-[760px] divide-y divide-[var(--border-default)] rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-5">+ {permissions.length > 0 ? (+ permissions.map((permission, index) => (+ <div+ key={`${permission.kind}-${permission.labelKey}-${index}`}+ className="py-3.5 text-13 leading-5 text-[var(--text-secondary)]"+ >+ {t(`settings.ghosts.perm.${permission.labelKey}`, permission.labelArgs)}+ </div>+ ))+ ) : (+ <div className="py-4 text-13 text-[var(--text-tertiary)]">+ {t('settings.ghosts.market.noPermissions')}+ </div>+ )}+ </div>+ </section>+ </article>+ </main>+ );+}diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsxindex 2a5385d2d5..11bb0c1a53 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx@@ -11,6 +11,9 @@ import type { ReactNode } from 'react';vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),}));+vi.mock('@/contexts/AuthContext', () => ({+ useAuth: () => ({ user: null, mode: 'signed-out', dataOwnerId: null }),+}));vi.mock('@/components/ui/tooltip', () => ({Tip: ({ text, children }: { text: string; children: ReactNode }) => (<span data-tooltip={text}>{children}</span>diff --git a/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketErrorKey.test.ts b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketErrorKey.test.tsnew file mode 100644index 0000000000..8fa234750a--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketErrorKey.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest';++import { pluginMarketErrorKey } from '../pluginMarketErrorKey';++function serializedIpcError(code: string): Error {+ return new Error(`Error invoking remote method: Error: [${code}] internal detail`);+}++describe('pluginMarketErrorKey', () => {+ it.each([+ ['INVALID_PARAMS', 'invalidRequest'],+ ['NOT_FOUND', 'notFound'],+ ['ALREADY_EXISTS', 'conflict'],+ ['PRECONDITION_FAILED', 'stateChanged'],+ ['PERMISSION_DENIED', 'accessDenied'],+ ['UNSUPPORTED_CAPABILITY', 'notConfigured'],+ ['GHOST_FILE_INVALID', 'invalidPackage'],+ ])('maps %s to localized market copy', (code, suffix) => {+ expect(pluginMarketErrorKey(serializedIpcError(code))).toBe(+ `settings.ghosts.market.errors.${suffix}`,+ );+ });++ it('never exposes a plain main-process error message', () => {+ expect(pluginMarketErrorKey(new Error('不应显示给 renderer 的内部错误'))).toBe(+ 'settings.ghosts.market.errors.generic',+ );+ });+});diff --git a/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.tsnew file mode 100644index 0000000000..661c1a97fd--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from 'vitest';+import { pluginPresentationOrigin } from '../pluginMarketPresentation';++describe('pluginPresentationOrigin', () => {+ it('maps public plugins independently of their default-install policy', () => {+ expect(pluginPresentationOrigin({ scope: 'public' })).toBe('public');+ });++ it('maps organization plugins to their organization source', () => {+ expect(pluginPresentationOrigin({ scope: 'organization' })).toBe('organization');+ });++ it('keeps personal plugins out of the client-facing market taxonomy', () => {+ expect(pluginPresentationOrigin({ scope: 'personal' })).toBe('local');+ });++ it.each([null, undefined])('keeps unmatched installed plugins local', (item) => {+ expect(pluginPresentationOrigin(item)).toBe('local');+ });+});diff --git a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketErrorKey.ts b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketErrorKey.tsnew file mode 100644index 0000000000..fe116f727d--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketErrorKey.ts@@ -0,0 +1,23 @@+import { extractIpcError } from '@/utils/ipcError';++/** Stable Plugin Market IPC error codes → localized renderer copy keys. */+export function pluginMarketErrorKey(error: unknown): string {+ switch (extractIpcError(error)?.code) {+ case 'INVALID_PARAMS':+ return 'settings.ghosts.market.errors.invalidRequest';+ case 'NOT_FOUND':+ return 'settings.ghosts.market.errors.notFound';+ case 'ALREADY_EXISTS':+ return 'settings.ghosts.market.errors.conflict';+ case 'PRECONDITION_FAILED':+ return 'settings.ghosts.market.errors.stateChanged';+ case 'PERMISSION_DENIED':+ return 'settings.ghosts.market.errors.accessDenied';+ case 'UNSUPPORTED_CAPABILITY':+ return 'settings.ghosts.market.errors.notConfigured';+ case 'GHOST_FILE_INVALID':+ return 'settings.ghosts.market.errors.invalidPackage';+ default:+ return 'settings.ghosts.market.errors.generic';+ }+}diff --git a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.tsnew file mode 100644index 0000000000..bac80d4407--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts@@ -0,0 +1,24 @@+/**+ * Maps server authorization scope into the client-facing source taxonomy.+ *+ * Scope is the source of truth for visibility and publishing authority. Whether a+ * public Plugin is installed by default is an installation policy, not a source.+ * An installed Ghost without a matching market record remains local.+ */+import type { PluginMarketItem } from '../../../../shared/pluginMarket';++export type PluginPresentationOrigin =+ | 'public'+ | 'organization'+ | 'local';++export function pluginPresentationOrigin(+ item: Pick<PluginMarketItem, 'scope'> | null | undefined,+): PluginPresentationOrigin {+ if (item?.scope === 'public' || item?.scope === 'organization') {+ return item.scope;+ }+ // Personal market publishing is intentionally not exposed by the client.+ // Keep the renderer taxonomy closed even if an older/newer server returns it.+ return 'local';+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 25477f2f30..478aa226cd 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -2212,13 +2212,53 @@"installedExpand": "Show {{count}} more installed plugins","installedCollapse": "Hide additional installed plugins","allTitle": "All plugins",+ "filterAll": "All",+ "filtersAria": "Filter plugins by source",+ "origin": {+ "public": "Public",+ "organization": "Team shared",+ "local": "Local"+ },"emptyFiltered": "No matching plugins","useAction": "Use","useAria": "Use {{name}}"},+ "market": {+ "scopeAria": "Filter plugin sources",+ "scope": {+ "all": "All",+ "public": "Public",+ "organization": "Organization",+ "personal": "Personal",+ "local": "Local"+ },+ "install": "Install",+ "details": "Details",+ "update": "Update from market",+ "installed": "Installed",+ "conflict": "Plugin ID conflict",+ "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.",+ "errors": {+ "generic": "The plugin market operation failed. Please try again.",+ "invalidRequest": "The plugin request is invalid.",+ "notFound": "This plugin is no longer available. Refresh the market and try again.",+ "conflict": "Another installed or market plugin uses the same plugin ID.",+ "stateChanged": "The account, plugin, or release changed during this operation. Review the latest state and try again.",+ "accessDenied": "This plugin operation is not permitted or was cancelled.",+ "notConfigured": "The plugin market is not available in this environment.",+ "invalidPackage": "This plugin package is invalid or is not supported by this version of Cindy."+ },+ "securityTitle": "Install and permissions",+ "securityDescription": "Cindy verifies package size and SHA-256 in the main process, validates the plugin manifest, then installs atomically. New installs stay disabled until you review permissions and enable them.",+ "noPermissions": "This plugin declares no additional capabilities.",+ "installConfirmTitle": "Install “{{name}}”?",+ "installConfirmDescription": "The package will be verified for integrity and manifest compatibility, then installed disabled. Review its setup and enable it when ready."+ },"install": "Install Plugin…","empty": "No plugins installed yet",- "emptyHint": "Click \"Install Plugin…\" above and pick a .cindy file",+ "emptyHint": "Install from the market, or import a .cindy file from the menu above","disabledTag": "Disabled","projectDisabledTag": "Off in this project","projectSwitchLockedTip": "This plugin is disabled globally; enable it in the Global view first",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex fdb20944b1..486a55a107 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -2211,13 +2211,53 @@"installedExpand": "インストール済みプラグインをさらに {{count}} 件表示","installedCollapse": "追加のインストール済みプラグインを隠す","allTitle": "すべてのプラグイン",+ "filterAll": "すべて",+ "filtersAria": "提供元でプラグインを絞り込む",+ "origin": {+ "public": "公開",+ "organization": "チーム共有",+ "local": "ローカル"+ },"emptyFiltered": "一致するプラグインがありません","useAction": "使用","useAria": "{{name}} を使用"},+ "market": {+ "scopeAria": "プラグインの提供元を絞り込む",+ "scope": {+ "all": "すべて",+ "public": "公開",+ "organization": "組織",+ "personal": "個人",+ "local": "ローカル"+ },+ "install": "インストール",+ "details": "詳細",+ "update": "マーケットから更新",+ "installed": "インストール済み",+ "conflict": "プラグイン ID の競合",+ "unavailable": "プラグインマーケットを一時的に利用できません。インストール済みプラグインは引き続き利用できます。",+ "authenticationRequired": "プラグインマーケットを表示するには Cindy にログインしてください。",+ "notConfigured": "この環境ではプラグインマーケットが設定されていません。インストール済みプラグインは引き続き利用できます。",+ "errors": {+ "generic": "プラグインマーケットの操作に失敗しました。もう一度お試しください。",+ "invalidRequest": "プラグインのリクエストが無効です。",+ "notFound": "このプラグインは利用できなくなりました。マーケットを更新して、もう一度お試しください。",+ "conflict": "インストール済みまたはマーケットの別のプラグインが同じプラグイン ID を使用しています。",+ "stateChanged": "操作中にアカウント、プラグイン、またはリリースが変更されました。最新の状態を確認して、もう一度お試しください。",+ "accessDenied": "このプラグイン操作は許可されていないか、キャンセルされました。",+ "notConfigured": "この環境ではプラグインマーケットを利用できません。",+ "invalidPackage": "このプラグインパッケージは無効か、現在の Cindy バージョンではサポートされていません。"+ },+ "securityTitle": "インストールと権限",+ "securityDescription": "メインプロセスでサイズと SHA-256、プラグインマニフェストを検証してからアトミックにインストールします。権限を確認して有効にするまで、新規プラグインは無効のままです。",+ "noPermissions": "このプラグインは追加機能を宣言していません。",+ "installConfirmTitle": "「{{name}}」をインストールしますか?",+ "installConfirmDescription": "パッケージの整合性とマニフェスト互換性を確認し、無効の状態でインストールします。設定を確認してから有効にできます。"+ },"install": "プラグインをインストール…","empty": "まだプラグインがインストールされていません",- "emptyHint": "右上の「プラグインをインストール…」から .cindy ファイルを選択してください",+ "emptyHint": "マーケットからインストールするか、上のメニューから .cindy ファイルを読み込めます","disabledTag": "無効","projectDisabledTag": "このプロジェクトでは無効","projectSwitchLockedTip": "このプラグインはグローバルで無効です。先に「グローバル」ビューで有効にしてください",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex dd6e8a107e..f390e8bff3 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -2211,13 +2211,53 @@"installedExpand": "설치된 플러그인 {{count}}개 더 보기","installedCollapse": "추가 설치 플러그인 숨기기","allTitle": "모든 플러그인",+ "filterAll": "전체",+ "filtersAria": "출처별 플러그인 필터",+ "origin": {+ "public": "공개",+ "organization": "팀 공유",+ "local": "로컬"+ },"emptyFiltered": "일치하는 플러그인이 없습니다","useAction": "사용","useAria": "{{name}} 사용"},+ "market": {+ "scopeAria": "플러그인 출처 필터",+ "scope": {+ "all": "전체",+ "public": "공개",+ "organization": "조직",+ "personal": "개인",+ "local": "로컬"+ },+ "install": "설치",+ "details": "상세",+ "update": "마켓에서 업데이트",+ "installed": "설치됨",+ "conflict": "플러그인 ID 충돌",+ "unavailable": "플러그인 마켓을 일시적으로 사용할 수 없습니다. 설치된 플러그인은 계속 사용할 수 있습니다.",+ "authenticationRequired": "플러그인 마켓을 보려면 Cindy에 로그인하세요.",+ "notConfigured": "이 환경에는 플러그인 마켓이 구성되지 않았습니다. 설치된 플러그인은 계속 사용할 수 있습니다.",+ "errors": {+ "generic": "플러그인 마켓 작업에 실패했습니다. 다시 시도해 주세요.",+ "invalidRequest": "플러그인 요청이 올바르지 않습니다.",+ "notFound": "이 플러그인은 더 이상 사용할 수 없습니다. 마켓을 새로 고친 후 다시 시도해 주세요.",+ "conflict": "설치된 플러그인 또는 마켓 플러그인이 동일한 플러그인 ID를 사용하고 있습니다.",+ "stateChanged": "작업 중 계정, 플러그인 또는 릴리스가 변경되었습니다. 최신 상태를 확인한 후 다시 시도해 주세요.",+ "accessDenied": "이 플러그인 작업은 허용되지 않았거나 취소되었습니다.",+ "notConfigured": "이 환경에서는 플러그인 마켓을 사용할 수 없습니다.",+ "invalidPackage": "이 플러그인 패키지가 올바르지 않거나 현재 Cindy 버전에서 지원되지 않습니다."+ },+ "securityTitle": "설치 및 권한",+ "securityDescription": "메인 프로세스에서 크기와 SHA-256 및 플러그인 매니페스트를 검증한 뒤 원자적으로 설치합니다. 권한을 확인하고 활성화할 때까지 새 플러그인은 비활성 상태로 유지됩니다.",+ "noPermissions": "이 플러그인은 추가 기능을 선언하지 않았습니다.",+ "installConfirmTitle": "‘{{name}}’을(를) 설치할까요?",+ "installConfirmDescription": "패키지 무결성과 매니페스트 호환성을 확인한 뒤 비활성 상태로 설치합니다. 설정을 검토한 후 직접 활성화할 수 있습니다."+ },"install": "플러그인 설치…","empty": "아직 설치된 플러그인이 없습니다",- "emptyHint": "오른쪽 위 \"플러그인 설치…\"에서 .cindy 파일을 선택하세요",+ "emptyHint": "마켓에서 설치하거나 위 메뉴에서 .cindy 파일을 가져올 수 있습니다","disabledTag": "비활성","projectDisabledTag": "이 프로젝트에서 꺼짐","projectSwitchLockedTip": "이 플러그인은 전역에서 비활성 상태입니다. 먼저 '전역' 보기에서 활성화해 주세요",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 21777084cf..2f94da556f 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -2211,13 +2211,53 @@"installedExpand": "展开另外 {{count}} 个已安装插件","installedCollapse": "收起其他已安装插件","allTitle": "全部插件",+ "filterAll": "全部",+ "filtersAria": "按来源筛选插件",+ "origin": {+ "public": "公开",+ "organization": "团队共享",+ "local": "本地"+ },"emptyFiltered": "没有找到匹配的插件","useAction": "使用","useAria": "使用 {{name}}"},+ "market": {+ "scopeAria": "筛选插件来源",+ "scope": {+ "all": "全部",+ "public": "公开",+ "organization": "组织",+ "personal": "个人",+ "local": "本地"+ },+ "install": "安装",+ "details": "详情",+ "update": "从市场更新",+ "installed": "已安装",+ "conflict": "插件标识冲突",+ "unavailable": "插件市场暂时不可用;已安装插件仍可正常管理和使用。",+ "authenticationRequired": "登录 Cindy 后才能查看插件市场。",+ "notConfigured": "当前环境未配置插件市场;已安装插件仍可正常管理和使用。",+ "errors": {+ "generic": "插件市场操作失败,请重试。",+ "invalidRequest": "插件请求无效。",+ "notFound": "该插件已不可用,请刷新市场后重试。",+ "conflict": "已有本地或市场插件使用相同的插件标识。",+ "stateChanged": "操作期间账号、插件或版本已发生变化,请确认最新状态后重试。",+ "accessDenied": "当前插件操作不被允许,或操作已取消。",+ "notConfigured": "当前环境未提供插件市场。",+ "invalidPackage": "该插件包无效,或当前 Cindy 版本不支持它。"+ },+ "securityTitle": "安装与权限",+ "securityDescription": "安装包会在主进程中校验大小与 SHA-256,再经 Cindy 插件清单校验后原子安装。安装后默认不生效,由你确认权限后再开启。",+ "noPermissions": "此插件未声明额外能力。",+ "installConfirmTitle": "安装「{{name}}」?",+ "installConfirmDescription": "安装包将经过完整性与清单校验,并以未生效状态安装。你可以在安装后查看配置并手动开启。"+ },"install": "安装插件…","empty": "还没有安装任何插件",- "emptyHint": "点击右上角「安装插件…」选择一个 .cindy 文件",+ "emptyHint": "可从插件市场安装,或点击右上角导入 .cindy 文件","disabledTag": "未生效","projectDisabledTag": "本项目未生效","projectSwitchLockedTip": "该插件已在全局停用;请先切回「全局」视图开启",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 017c61803c..2380ae6438 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1209,6 +1209,18 @@ interface ElectronAPI {) => Promise<{ states?: Record<string, string>; state?: string }>;};+ /** Plugin Protocol v2 市场;网络、下载与安装全部在 main 进程完成。 */+ pluginMarket: {+ snapshot: () => Promise<import('../shared/pluginMarket').PluginMarketSnapshot>;+ detail: (+ pluginId: string,+ ) => Promise<import('../shared/pluginMarket').PluginMarketDetail>;+ install: (+ pluginId: string,+ options?: { allowPermissionExpansion?: boolean },+ ) => Promise<{ ghost: import('../shared/ghost').InstalledGhost }>;+ uninstall: (pluginId: string) => Promise<{ ok: true }>;+ };voiceInput: {prewarm: (payload?: { sourceLanguage?: string; refinementEnabled?: boolean }) => Promise<{ ok: true }>;getBenchmarkFixtureAudio: () => Promise<{ ok: true; path: string; wav: ArrayBuffer } | { ok: false }>;diff --git a/apps/desktop/src/shared/pluginMarket.ts b/apps/desktop/src/shared/pluginMarket.tsnew file mode 100644index 0000000000..db401fd3b6--- /dev/null+++ b/apps/desktop/src/shared/pluginMarket.ts@@ -0,0 +1,37 @@+import type { GhostManifest } from './ghost';+import type { PluginIconMetadata } from '@cindy/plugin-protocol';++export type PluginMarketScope = 'public' | 'organization' | 'personal';+export type PluginMarketInstallState =+ | 'not-installed'+ | 'installed'+ | 'update-available'+ | 'conflict';++/** Renderer-safe Plugin 市场列表项;所有字段都来自协议或本地安装事实。 */+export interface PluginMarketItem {+ pluginId: string;+ ghostId: string;+ name: string;+ description: string | null;+ author: string | null;+ scope: PluginMarketScope;+ organizationId: string | null;+ defaultInstall: boolean;+ releaseId: string;+ version: string;+ publishedAt: string;+ icon: PluginIconMetadata | null;+ installState: PluginMarketInstallState;+ enabled: boolean | null;+}+/** 市场快照。服务不可用时 renderer 保留本地插件并只展示非阻断提示。 */+export interface PluginMarketSnapshot {+ items: PluginMarketItem[];+ unavailableReason: string | null;+}++/** 详情额外携带经 Desktop 当前 runtime validator 验证过的完整清单。 */+export interface PluginMarketDetail extends PluginMarketItem {+ manifest: GhostManifest;+}diff --git a/apps/desktop/src/test/vitest/clientEndpointsFixture.ts b/apps/desktop/src/test/vitest/clientEndpointsFixture.tsindex f830f2038c..2d9d553737 100644--- a/apps/desktop/src/test/vitest/clientEndpointsFixture.ts+++ b/apps/desktop/src/test/vitest/clientEndpointsFixture.ts@@ -34,6 +34,7 @@ export const TEST_CLIENT_ENDPOINTS: ClientEndpointMap = {voiceApiBaseUrl: 'https://voice.test.invalid',githubApiBaseUrl: 'https://github-api.test.invalid',skillhubApiBaseUrl: 'https://skillhub.test.invalid',+ pluginApiBaseUrl: 'https://plugin.test.invalid',cdnBaseUrl: TEST_CDN_BASE_URL,mobileUpdateBaseUrl: 'https://mobile-update.test.invalid',};diff --git a/cindy-protocol b/cindy-protocolindex 446873069a..f9eff5a239 160000--- a/cindy-protocol+++ b/cindy-protocol@@ -1 +1 @@-Subproject commit 446873069add56c51d54a6b8aaa886a6c02093ae+Subproject commit f9eff5a239578afdf3d585a7acaf50ecc8698866diff --git a/config/endpoint.dev.json.example b/config/endpoint.dev.json.exampleindex 626a106dc8..826452f47e 100644--- a/config/endpoint.dev.json.example+++ b/config/endpoint.dev.json.example@@ -13,6 +13,7 @@"voiceApiBaseUrl": "http://localhost:3342","githubApiBaseUrl": "http://localhost:3336","skillhubApiBaseUrl": "http://localhost:3341",+ "pluginApiBaseUrl": "http://localhost:3343","cdnBaseUrl": "http://localhost:3345/cindy","mobileUpdateBaseUrl": "http://localhost:3346","review": "0.1.0"diff --git a/config/endpoint.global.json b/config/endpoint.global.jsonindex 586af37873..414fec0de9 100644--- a/config/endpoint.global.json+++ b/config/endpoint.global.json@@ -12,6 +12,7 @@"voiceApiBaseUrl": "https://voice.cindy.app","githubApiBaseUrl": "https://github.cindy.app","skillhubApiBaseUrl": "https://xd-skillhub.cindy.app",+ "pluginApiBaseUrl": "https://plugin.cindy.app","cdnBaseUrl": "https://hotfix.cindy.app/cindy","mobileUpdateBaseUrl": "https://mobile-update.cindy.app","review": "0.1.0"diff --git a/config/endpoint.json b/config/endpoint.jsonindex 4c7c9ad65c..aef0f4b2c6 100644--- a/config/endpoint.json+++ b/config/endpoint.json@@ -12,6 +12,7 @@"voiceApiBaseUrl": "https://voice.cindy.com.cn","githubApiBaseUrl": "https://github.cindy.com.cn","skillhubApiBaseUrl": "https://xd-skillhub.cindy.com.cn",+ "pluginApiBaseUrl": "https://plugin.cindy.com.cn","cdnBaseUrl": "https://hotfix.cindy.com.cn/cindy","mobileUpdateBaseUrl": "https://mobile-update.cindy.com.cn","review": "0.1.0"diff --git a/packages/maker-shared/src/__tests__/clientEndpoints.test.ts b/packages/maker-shared/src/__tests__/clientEndpoints.test.tsindex c73b6fa24c..7674b76203 100644--- a/packages/maker-shared/src/__tests__/clientEndpoints.test.ts+++ b/packages/maker-shared/src/__tests__/clientEndpoints.test.ts@@ -21,6 +21,7 @@ const VALID_MANIFEST = {voiceApiBaseUrl: 'https://voice.example.com',githubApiBaseUrl: 'https://github-api.example.com',skillhubApiBaseUrl: 'https://skillhub.example.com',+ pluginApiBaseUrl: 'https://plugin.example.com',cdnBaseUrl: 'https://cdn.example.com/app',mobileUpdateBaseUrl: 'https://mobile-update.example.com',};diff --git a/packages/maker-shared/src/clientEndpoints.ts b/packages/maker-shared/src/clientEndpoints.tsindex 21159fb975..30ef4c4f81 100644--- a/packages/maker-shared/src/clientEndpoints.ts+++ b/packages/maker-shared/src/clientEndpoints.ts@@ -90,6 +90,8 @@ export const CLIENT_ENDPOINT_KEYS = ['githubApiBaseUrl',// skillhub-server(SkillHub 技能市场/发布 → XD hub 的 S2S 代理)的 API 基址。'skillhubApiBaseUrl',+ // plugin-server(Plugin/Skill 市场、组织管理与发布)的 API 基址。+ 'pluginApiBaseUrl',// 更新/hotfix 链的 CDN base(manifest-*.json / hotfix 包 / agent 二进制)。'cdnBaseUrl',// 自建线手机整包发现的 mobile-update-server 基址(`${base}/latest`)。仅@@ -142,6 +144,7 @@ const FIELD_PROTOCOLS: Record<ClientEndpointKey, readonly string[]> = {voiceApiBaseUrl: ['https:'],githubApiBaseUrl: ['https:'],skillhubApiBaseUrl: ['https:'],+ pluginApiBaseUrl: ['https:'],cdnBaseUrl: ['https:'],mobileUpdateBaseUrl: ['https:'],};diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 0346561e4c..abe3cd06ed 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -99,6 +99,9 @@ importers:'@cindy/orca-workflow':specifier: workspace:*version: link:../../packages/orca-workflow+ '@cindy/plugin-protocol':+ specifier: workspace:*+ version: link:../../cindy-protocol/packages/plugin-protocol'@cindy/remote-file-service':specifier: workspace:*version: link:../../packages/remote-file-service@@ -716,7 +719,6 @@ importers:vitest:specifier: ^3.2.4version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected])([email protected])([email protected])([email protected])-cindy-protocol/packages/slack-hook-protocol:devDependencies:'@types/node':diff --git a/scripts/__tests__/endpoint-local-file.test.mjs b/scripts/__tests__/endpoint-local-file.test.mjsindex 58b8d81489..59d6953236 100644--- a/scripts/__tests__/endpoint-local-file.test.mjs+++ b/scripts/__tests__/endpoint-local-file.test.mjs@@ -32,13 +32,16 @@ const CN_MANIFEST = JSON.stringify({telegramHookWsUrl: '',slackHookWsUrl: 'wss://hook.example.invalid',websiteUrl: 'https://website.example.invalid',+ modelAccessApiBaseUrl: 'https://model-access.example.invalid',+ voiceApiBaseUrl: 'https://voice.example.invalid',githubApiBaseUrl: 'https://github-api.example.invalid',skillhubApiBaseUrl: 'https://skillhub.example.invalid',+ pluginApiBaseUrl: 'https://plugin.example.invalid',cdnBaseUrl: 'https://cdn.example.invalid/app',mobileUpdateBaseUrl: 'https://mobile-update.example.invalid',});-test('localhost 七件套覆写,其余字段照抄 cn 正本,返回绝对路径', () => {+test('localhost 八件套覆写,其余字段照抄 cn 正本,返回绝对路径', () => {const repoRoot = makeRepoRoot(CN_MANIFEST);const target = generateEndpointLocalFile({ repoRoot });assert.equal(target, path.join(repoRoot, 'config', 'endpoint.local.json'));@@ -46,8 +49,11 @@ test('localhost 七件套覆写,其余字段照抄 cn 正本,返回绝对路径'assert.equal(local.authApiBaseUrl, 'http://localhost:3344');assert.equal(local.deviceLinkApiBaseUrl, 'http://localhost:3335');assert.equal(local.ossApiBaseUrl, 'http://localhost:3340');+ assert.equal(local.modelAccessApiBaseUrl, 'http://localhost:3339');+ assert.equal(local.voiceApiBaseUrl, 'http://localhost:3342');assert.equal(local.githubApiBaseUrl, 'http://localhost:3336');assert.equal(local.skillhubApiBaseUrl, 'http://localhost:3341');+ assert.equal(local.pluginApiBaseUrl, 'http://localhost:3343');// 其余字段与正本一致(oauth broker 等本地不起的服务沿用远程值)assert.equal(local.oauthBrokerApiBaseUrl, 'https://oauth.example.invalid');assert.equal(local.cdnBaseUrl, 'https://cdn.example.invalid/app');@@ -82,8 +88,11 @@ test('生成物能过客户端 parser 的 allowHttp 校验(与仓内正本同一'heartbeatUrl','slackHookWsUrl','websiteUrl',+ 'modelAccessApiBaseUrl',+ 'voiceApiBaseUrl','githubApiBaseUrl','skillhubApiBaseUrl',+ 'pluginApiBaseUrl','cdnBaseUrl','mobileUpdateBaseUrl',];diff --git a/scripts/shared/endpoint-local-file.mjs b/scripts/shared/endpoint-local-file.mjsindex 189f01df4a..804076e61e 100644--- a/scripts/shared/endpoint-local-file.mjs+++ b/scripts/shared/endpoint-local-file.mjs@@ -3,8 +3,8 @@** 背景:dev 默认读仓内 cn 正本 config/endpoint.json(远程生产/测试值);* 「连本地 server」的 local 模式改由本文件生成的 endpoint.local.json 承载——- * auth / device-link / oss / model-access / github / skillhub 指向 localhost- * 六件套(oss / model-access / github / skillhub 必须跟 auth 同侧:都用+ * auth / device-link / oss / model-access / voice / github / skillhub / plugin 指向 localhost+ * 八件套(oss / model-access / voice / github / skillhub / plugin 必须跟 auth 同侧:都用* AUTH_ISSUER 验签,本地 auth 签发的 token 过不了生产侧验签),* 其余字段(oauth broker / heartbeat / slack hook / website / 网关 / 更新链* CDN)照抄 cn 正本(本地不起这些服务,沿用远程值,消费方各自的@@ -25,6 +25,7 @@ const LOCAL_MODEL_ACCESS_BASE_URL = 'http://localhost:3339';const LOCAL_VOICE_BASE_URL = 'http://localhost:3342';const LOCAL_GITHUB_BASE_URL = 'http://localhost:3336';const LOCAL_SKILLHUB_BASE_URL = 'http://localhost:3341';+const LOCAL_PLUGIN_BASE_URL = 'http://localhost:3343';/*** 从 cn 正本生成 endpoint.local.json,返回生成文件的绝对路径。@@ -38,7 +39,7 @@ export function generateEndpointLocalFile({ repoRoot }) {const local = {_note:'由 scripts/shared/endpoint-local-file.mjs 生成(restart:desktop:local / dev:desktop),' +- '每次启动整文件重写,手改会丢;localhost 六件套之外的字段照抄 config/endpoint.json。',+ '每次启动整文件重写,手改会丢;localhost 八件套之外的字段照抄 config/endpoint.json。',...source,authApiBaseUrl: LOCAL_AUTH_BASE_URL,deviceLinkApiBaseUrl: LOCAL_DEVICE_LINK_BASE_URL,@@ -47,6 +48,7 @@ export function generateEndpointLocalFile({ repoRoot }) {voiceApiBaseUrl: LOCAL_VOICE_BASE_URL,githubApiBaseUrl: LOCAL_GITHUB_BASE_URL,skillhubApiBaseUrl: LOCAL_SKILLHUB_BASE_URL,+ pluginApiBaseUrl: LOCAL_PLUGIN_BASE_URL,};fs.writeFileSync(targetPath, `${JSON.stringify(local, null, 2)}\n`);return targetPath;