Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 支持 Git/本地自定义插件市场源 (#1176)
xxxcc045d152b505a
diff --git a/.github/pull-request-assets/custom-plugin-marketplace.png b/.github/pull-request-assets/custom-plugin-marketplace.pngnew file mode 100644index 0000000000..8f26472256Binary files /dev/null and b/.github/pull-request-assets/custom-plugin-marketplace.png differdiff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex a6f0b472b5..b32e78c380 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -24,7 +24,10 @@ import {verifyGhostZipSignatures,type GhostTrustRegistry,} from './ghostSignature.js';-import { isPathInsideDir } from './dirDeposit.js';+import {+ readBoundedFileFollowLinks,+ readBoundedFileNoFollowSync,+} from '../utils/readBoundedFile.js';import { checkSkillMdConsistency } from './skillSlot.js';/** 普通沙箱插件维持小包上限;随包 Node/CLI 允许更大的预打包产物。 */@@ -114,7 +117,11 @@ export class GhostManager {const manifestPath = path.join(dir, GHOST_MANIFEST_FILE);let raw: unknown;try {- raw = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));+ // 已安装目录也可能被外部进程/同步盘改动,且 list() 每次市场快照都会+ // 执行:单句柄限量闸(拒链接),不让无界字节进 main。+ const bytes = readBoundedFileNoFollowSync(manifestPath, MAX_GHOST_MANIFEST_BYTES);+ if (bytes === null) throw new Error('manifest is not a bounded regular file');+ raw = JSON.parse(bytes.toString('utf-8'));} catch (err) {this.options.log?.warn('ghost dir skipped: unreadable manifest', {dir,@@ -164,16 +171,15 @@ export class GhostManager {for (const candidatePath of candidates) {try {const absPath = path.join(dir, ...candidatePath.split('/'));- const stat = fs.lstatSync(absPath);- if (!stat.isFile() || stat.size > GHOST_LOCALE_MAX_BYTES) {- throw new Error(`locale 文件缺失或超过 ${GHOST_LOCALE_MAX_BYTES} 字节`);- }- const realDir = fs.realpathSync.native(dir);- const realLocalePath = fs.realpathSync.native(absPath);- if (!isPathInsideDir(realDir, realLocalePath)) {- throw new Error('locale 文件经软链解析后位于插件目录之外');+ // lstat 判完再按路径 readFileSync 是三次独立打开,期间可被换成超大+ // 文件或根外链接。单句柄限量闸 + containWithin 一次完成全部校验。+ const bytes = readBoundedFileNoFollowSync(absPath, GHOST_LOCALE_MAX_BYTES, {+ containWithin: fs.realpathSync(dir),+ });+ if (bytes === null) {+ throw new Error(`locale 文件缺失、超过 ${GHOST_LOCALE_MAX_BYTES} 字节或位于插件目录之外`);}- const raw = JSON.parse(fs.readFileSync(realLocalePath, 'utf8'));+ const raw = JSON.parse(bytes.toString('utf8'));const validated = validateGhostManifestLocaleResource(raw, manifest);if (!validated.ok) throw new Error(validated.reason);return resolveGhostManifestLocale(runtimeManifest, validated.resource);@@ -227,12 +233,17 @@ export class GhostManager {if (manifest.icon === undefined) return null;const iconPath = path.join(dir, ...manifest.icon.split('/'));try {- const stat = fs.statSync(iconPath);- if (!stat.isFile() || stat.size > MAX_GHOST_ICON_BYTES) {+ // statSync 后再 readFileSync 是两次独立打开:并发方可在其间把 icon 换成+ // 指向宿主任意文件的链接,字节会被包成 dataURL 经 IPC 送进 Renderer。+ // 单句柄限量闸拒链接、限大小;containWithin 堵中间目录链接。+ const bytes = readBoundedFileNoFollowSync(iconPath, MAX_GHOST_ICON_BYTES, {+ containWithin: fs.realpathSync(dir),+ });+ if (bytes === null) {this.options.log?.warn('ghost icon skipped: missing or oversize', { dir, icon: manifest.icon });return null;}- return buildIconDataUrl(manifest.icon, fs.readFileSync(iconPath));+ return buildIconDataUrl(manifest.icon, bytes);} catch {this.options.log?.warn('ghost icon skipped: unreadable', { dir, icon: manifest.icon });return null;@@ -242,7 +253,9 @@ export class GhostManager {/** 读取主机安装时写下的签名验证快照;坏文件只降级未显示,不信作者自报。 */private readInstalledTrust(dir: string): GhostTrustInfo | null {try {- const raw = JSON.parse(fs.readFileSync(path.join(dir, TRUST_METADATA_FILE), 'utf8')) as GhostTrustInfo;+ const bytes = readBoundedFileNoFollowSync(path.join(dir, TRUST_METADATA_FILE), 64 * 1024);+ if (bytes === null) return null;+ const raw = JSON.parse(bytes.toString('utf8')) as GhostTrustInfo;if (!raw ||typeof raw !== 'object' ||@@ -297,19 +310,21 @@ export class GhostManager {}| { rejection: InstallRejection }> {- // 1) 读源文件(带体积上限)+ // 1) 读源文件(带体积上限)。stat 后再 readFile 是两次独立打开,期间文件+ // 可被换成超大文件绕过上限——单句柄限量读。允许跟随链接:用户拖入的+ // .cindy 本身可以是链接,防篡改由 expectedPackageSha256 对账负责。let buf: Buffer;try {- const stat = await fs.promises.stat(lizFilePath);- if (!stat.isFile()) {- return { rejection: { code: 'source-not-found', reason: '路径不是文件' } };- }- if (stat.size > MAX_NODE_CINDY_FILE_BYTES) {+ const bytes = await readBoundedFileFollowLinks(lizFilePath, MAX_NODE_CINDY_FILE_BYTES);+ if (bytes === null) {return {- rejection: { code: 'file-invalid', reason: `文件过大:${stat.size} 字节(上限 ${MAX_NODE_CINDY_FILE_BYTES})` },+ rejection: {+ code: 'file-invalid',+ reason: `不是普通文件或超过体积上限(${MAX_NODE_CINDY_FILE_BYTES} 字节)`,+ },};}- buf = await fs.promises.readFile(lizFilePath);+ buf = bytes;} catch (err) {if ((err as NodeJS.ErrnoException).code === 'ENOENT') {return { rejection: { code: 'source-not-found', reason: '文件不存在' } };diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex d3e5b71b54..7c6f46eeb0 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -562,6 +562,28 @@ describe('GhostManager · author / icon(身份卡展示字段)', () => {await expectRejection(await manager.install(cindy), 'file-invalid');});+ it.runIf(process.platform !== 'win32')(+ '已装目录 icon 被换成指向目录外的符号链接 → list 降级为无图标,不外泄目标字节',+ async () => {+ const cindy = await makeCindy('icon3.cindy', iconManifest(), { 'assets/icon.png': 'PNGDATA' });+ await manager.install(cindy);+ // 装完后把 icon 换成指向插件目录外一个私密文件的符号链接:statSync 会+ // 跟随链接对目标判 isFile/大小 → 通过,再 readFileSync 目标字节 → 经+ // iconDataUrl 送进 Renderer。限量闸拒链接,list 只降级为无图标。+ const secret = path.join(workDir, 'ssh-key');+ await fs.promises.writeFile(secret, 'PRIVATE-KEY-BYTES');+ const iconAbs = path.join(rootDir, 'hello', 'assets', 'icon.png');+ await fs.promises.rm(iconAbs);+ await fs.promises.symlink(secret, iconAbs);+ const listed = manager.list();+ expect(listed).toHaveLength(1);+ expect(listed[0].iconDataUrl).toBeUndefined();+ expect(JSON.stringify(listed[0])).not.toContain(+ Buffer.from('PRIVATE-KEY-BYTES').toString('base64'),+ );+ },+ );+it('已装意识的 icon 文件事后丢失 → list 降级为无图标,不影响意识本体', async () => {const cindy = await makeCindy('icon2.cindy', iconManifest(), { 'assets/icon.png': 'PNGDATA' });await manager.install(cindy);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex cd3dff6ebd..e97be68404 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -6,12 +6,20 @@*/import fs from 'node:fs';+import JSZip from 'jszip';import os from 'node:os';import path from 'node:path';+import { fileURLToPath } from 'node:url';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { FORGE_GUIDE, packGhostDir, scaffoldGhostDir, type ForgeScaffoldTemplate } from '../forge';+import {+ FORGE_GUIDE,+ packGhostDir,+ packGhostDirToFile,+ scaffoldGhostDir,+ type ForgeScaffoldTemplate,+} from '../forge';import { GhostManager } from '../GhostManager';let workDir: string;@@ -67,6 +75,154 @@ describe('packGhostDir', () => {await fs.promises.rm(r.cindyPath, { force: true });});+ it('打包进 zip 的 ghost.json 是校验时的快照,并发改写不生效(防 TOCTOU)', async () => {+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),+ 'main.js': '// brain',+ });+ // 模拟"校验通过后、写入 zip 前"目录被并发改写:保 id/version,偷加权限声明。+ // 若打包时重读磁盘,包里的 manifest 会与返回值(安装侧审阅比对的依据)分叉。+ const tampered = JSON.stringify({ ...GOOD_MANIFEST, slots: ['tool', 'network'], network: { allow: ['x.test'] } });+ const realRead = fs.promises.readFile;+ let ghostReads = 0;+ const spy = vi+ .spyOn(fs.promises, 'readFile')+ .mockImplementation(((target: unknown, ...rest: unknown[]) => {+ if (String(target).endsWith('ghost.json')) {+ ghostReads += 1;+ if (ghostReads > 1) return Promise.resolve(Buffer.from(tampered));+ }+ return (realRead as (...args: unknown[]) => unknown)(target, ...rest);+ }) as typeof fs.promises.readFile);+ try {+ const r = await packGhostDir(dir);+ expect(r.ok, JSON.stringify(r)).toBe(true);+ if (!r.ok) return;+ const zip = await JSZip.loadAsync(await realRead(r.cindyPath));+ const packedManifest = JSON.parse(await zip.file('ghost.json')!.async('string'));+ // 包里的 manifest 必须与返回值一致(校验时的快照),不能是改写后的版本。+ expect(packedManifest.slots).toEqual(GOOD_MANIFEST.slots);+ expect(packedManifest).not.toHaveProperty('network');+ await fs.promises.rm(r.cindyPath, { force: true });+ } finally {+ spy.mockRestore();+ }+ });++ it('ghost.json 为符号链接或超限 → MANIFEST_INVALID(与市场发现/安装同一把闸)', async () => {+ // 符号链接:目标是合法清单也不放行——"符号链接一律不穿透"覆盖身份卡本身,+ // 否则打包输入目录里一根链接就能把目录外的文件读进打包管道。+ const outside = path.join(workDir, 'outside-ghost.json');+ await fs.promises.writeFile(outside, JSON.stringify(GOOD_MANIFEST));+ const linked = path.join(workDir, 'src-linked');+ await fs.promises.mkdir(linked, { recursive: true });+ await fs.promises.symlink(outside, path.join(linked, 'ghost.json'));+ await fs.promises.writeFile(path.join(linked, 'main.js'), '// brain');+ expect(await packGhostDir(linked)).toMatchObject({+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ });++ // 超限:JSON 本身合法(合法清单 + 尾随空白撑体积),必须在读取层按大小拒,+ // 不能等到 JSON.parse/validate——那时数 GB 的文件已经进内存了。+ const big = path.join(workDir, 'src-big');+ await fs.promises.mkdir(big, { recursive: true });+ await fs.promises.writeFile(+ path.join(big, 'ghost.json'),+ JSON.stringify(GOOD_MANIFEST) + ' '.repeat(600 * 1024),+ );+ await fs.promises.writeFile(path.join(big, 'main.js'), '// brain');+ const r = await packGhostDir(big);+ expect(r).toMatchObject({ ok: false, errorCode: 'MANIFEST_INVALID' });+ if (!r.ok) expect(r.message).toContain('不是普通文件或超过');+ });++ it('zip 阶段逐文件走剩余预算限量闸:walk 之后被撑大的文件结构化拒绝', async () => {+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),+ 'main.js': '// brain',+ });+ // 33MiB 零填充:超总预算(32MiB),但压缩后极小——旧实现无界 readFile 后+ // 整包压缩体积检查照样通过,超大字节已经进过内存。+ await fs.promises.writeFile(path.join(dir, 'blob.bin'), Buffer.alloc(33 * 1024 * 1024));+ // 模拟"walk 预算预估时文件还小,zip 读取时已被并发撑大":walk 的 stat 看+ // 到 10 字节。句柄侧 handle.stat 不受此 spy 影响,读到真实大小。+ const realStat = fs.promises.stat;+ const spy = vi.spyOn(fs.promises, 'stat').mockImplementation((async (+ target: Parameters<typeof fs.promises.stat>[0],+ ...rest: unknown[]+ ) => {+ const st = await (realStat as (...a: unknown[]) => Promise<fs.Stats>)(target, ...rest);+ if (String(target).endsWith('blob.bin')) {+ return Object.assign(Object.create(Object.getPrototypeOf(st)), st, { size: 10 });+ }+ return st;+ }) as typeof fs.promises.stat);+ try {+ const r = await packGhostDir(dir);+ expect(r).toMatchObject({ ok: false, errorCode: 'TOO_LARGE' });+ if (!r.ok) expect(r.message).toContain('打包期间被并发改动或超出剩余体积预算');+ } finally {+ spy.mockRestore();+ }+ });++ it('打包器不自我参照:realpath 与调用方给定的规范根不一致 → 拒绝', async () => {+ // 只靠"自己 realpath 一次、再拿它当 containWithin 锚点"是自我参照:目录在+ // 调用方校验之后、这里解析之前被换成指向外部的链接时,锚点就是那个外部目录,+ // 包含性判定全部通过,外部 payload 会被打包。锚点必须由上游给。+ const outside = await makeSrcDir({+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),+ 'main.js': '// outside payload',+ 'secret.txt': 'EXFILTRATED',+ });+ const staged = path.join(workDir, 'staged');+ await fs.promises.mkdir(staged, { recursive: true });+ const pluginDir = path.join(staged, 'alpha');+ await fs.promises.mkdir(pluginDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(pluginDir, 'ghost.json'),+ JSON.stringify(GOOD_MANIFEST),+ );+ await fs.promises.writeFile(path.join(pluginDir, 'main.js'), '// brain');+ // 调用方(安装管道)校验时拿到的规范根。+ const expectedRealDir = await fs.promises.realpath(pluginDir);+ // 校验之后被换成指向外部目录的链接(外部目录留着同样的 ghost.json)。+ await fs.promises.rm(pluginDir, { recursive: true, force: true });+ await fs.promises.symlink(await fs.promises.realpath(outside), pluginDir);++ const dest = path.join(workDir, 'out.cindy');+ const r = await packGhostDirToFile(pluginDir, dest, expectedRealDir);+ expect(r).toMatchObject({ ok: false, errorCode: 'MANIFEST_INVALID' });+ if (!r.ok) expect(r.message).toContain('打包前被替换');+ // 外部 payload 一个字节都没进包(产物根本没生成)。+ expect(fs.existsSync(dest)).toBe(false);+ });++ it('规范根一致时正常打包(锚点校验不误伤)', async () => {+ const dir = await makeSrcDir({+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),+ 'main.js': '// brain',+ });+ const dest = path.join(workDir, 'ok.cindy');+ const realDir = await fs.promises.realpath(dir);+ const r = await packGhostDirToFile(realDir, dest, realDir);+ expect(r.ok, JSON.stringify(r)).toBe(true);+ expect(fs.existsSync(dest)).toBe(true);+ });++ it('结构守卫:forge.ts 与 ghostLocaleFiles.ts 不允许出现按路径的 readFile', async () => {+ // 打包管道触及的都是用户可写目录,所有读取必须走 readBoundedFileNoFollow+ // 系列;任何一处退回按路径 readFile 都会重开"检查与读取两次打开"的窗口。+ const here = path.dirname(fileURLToPath(import.meta.url));+ for (const rel of ['../forge.ts', '../ghostLocaleFiles.ts']) {+ const source = await fs.promises.readFile(path.join(here, rel), 'utf8');+ expect(source, rel).not.toMatch(/fs\.promises\.readFile\(/);+ expect(source, rel).not.toMatch(/readFileSync\(/);+ expect(source, rel).toMatch(/readBoundedFileNoFollow/);+ }+ });+it('打包跳过开发残留:.git / node_modules / 隐藏文件 / 旧 .cindy 不进包', async () => {const dir = await makeSrcDir({'ghost.json': JSON.stringify(GOOD_MANIFEST),diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallLock.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallLock.test.tsnew file mode 100644index 0000000000..f907c4dee5--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstallLock.test.ts@@ -0,0 +1,111 @@+/**+ * withGhostInstallLock — 按 ghostId 的互斥。同 id 串行、异 id 并行。+ */+import { describe, expect, it } from 'vitest';++import { withGhostInstallLock } from '../ghostInstallLock';++/** 手动可控的 deferred,便于精确编排交错。 */+function deferred(): { promise: Promise<void>; resolve: () => void } {+ let resolve!: () => void;+ const promise = new Promise<void>((r) => {+ resolve = r;+ });+ return { promise, resolve };+}++describe('withGhostInstallLock', () => {+ it('同一 ghostId 串行:第二笔在第一笔释放前不得进入临界区', async () => {+ const order: string[] = [];+ const first = deferred();+ const a = withGhostInstallLock('ghost-x', async () => {+ order.push('a:start');+ await first.promise;+ order.push('a:end');+ });+ // 让 a 先取得锁并进入 fn。+ await Promise.resolve();+ const b = withGhostInstallLock('ghost-x', async () => {+ order.push('b:start');+ });+ // a 尚未释放:b 绝不能开始。+ await Promise.resolve();+ expect(order).toEqual(['a:start']);+ first.resolve();+ await Promise.all([a, b]);+ expect(order).toEqual(['a:start', 'a:end', 'b:start']);+ });++ it('前一笔抛错不卡死后一笔(链在成败后都继续)', async () => {+ const order: string[] = [];+ const failing = withGhostInstallLock('ghost-y', async () => {+ order.push('boom');+ throw new Error('boom');+ });+ const next = withGhostInstallLock('ghost-y', async () => {+ order.push('after');+ });+ await expect(failing).rejects.toThrow('boom');+ await next;+ expect(order).toEqual(['boom', 'after']);+ });++ it('可重入:同一上下文嵌套取同一 id 不自锁', async () => {+ // 锁同时加在三个卡点与各调用方的复核段上,外层已持有时内层必须是 no-op,+ // 否则市场路径(外层持锁)进入 installOrUpdateMarketGhostPackage(卡点也取锁)+ // 就会等自己释放 → 永久挂起。+ const order: string[] = [];+ await withGhostInstallLock('ghost-z', async () => {+ order.push('outer');+ await withGhostInstallLock('ghost-z', async () => {+ order.push('inner');+ // 再套一层也一样(卡点可能层层嵌套:service → install.ts → market 出口)。+ await withGhostInstallLock('ghost-z', async () => {+ order.push('innermost');+ });+ });+ });+ expect(order).toEqual(['outer', 'inner', 'innermost']);+ });++ it('可重入不放宽互斥:嵌套期间外部的同 id 请求仍被挡住', async () => {+ const order: string[] = [];+ const gate = deferred();+ const holder = withGhostInstallLock('ghost-w', async () => {+ await withGhostInstallLock('ghost-w', async () => {+ order.push('nested:enter');+ await gate.promise;+ order.push('nested:exit');+ });+ });+ await Promise.resolve();+ await Promise.resolve();+ // 另一个**独立上下文**的同 id 请求不是重入,必须排队。+ const outsider = withGhostInstallLock('ghost-w', async () => {+ order.push('outsider');+ });+ await Promise.resolve();+ expect(order).toEqual(['nested:enter']);+ gate.resolve();+ await Promise.all([holder, outsider]);+ expect(order).toEqual(['nested:enter', 'nested:exit', 'outsider']);+ });++ it('不同 ghostId 并行:互不阻塞', async () => {+ const order: string[] = [];+ const xGate = deferred();+ const x = withGhostInstallLock('ghost-x', async () => {+ order.push('x:start');+ await xGate.promise;+ });+ await Promise.resolve();+ // y 与 x 不同 id:即使 x 仍持锁,y 也应立即进入。+ const y = withGhostInstallLock('ghost-y', async () => {+ order.push('y:start');+ });+ await y;+ expect(order).toContain('y:start');+ xGate.resolve();+ await x;+ });+});diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex 494de3b43a..857f47d30d 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -24,6 +24,10 @@ import {validateGhostManifest,type GhostManifest,} from '../../shared/ghost.js';+import {+ GHOST_MANIFEST_MAX_BYTES,+ readBoundedFileNoFollow,+} from '../utils/readBoundedFile.js';import { validateGhostLocaleResourcesInDirectory } from './ghostLocaleFiles.js';import { checkSkillMdConsistency } from './skillSlot.js';@@ -38,7 +42,7 @@ const MAX_NODE_CINDY_BYTES = 128 * 1024 * 1024;/** 打包时跳过的目录/文件(源码目录里的开发残留,不属于意识本体)。 */function shouldSkip(name: string): boolean {if (name.startsWith('.')) return true; // .git / .DS_Store / .disabled 等- if (name === 'node_modules') return true;+ if (name.toLowerCase() === 'node_modules') return true;if (name.toLowerCase().endsWith('.cindy')) return true; // 上次打包产物,防套娃return false;}@@ -537,11 +541,27 @@ export async function scaffoldGhostDir(}/**- * 校验 + 打包一个意识源码目录。产物写到源码目录自身(<id>-<version>.cindy,- * 同名覆盖——同 id 同版本重打包语义上就是同一个包),用户在自己的意识目录里- * 就能拿到成品;出错返回结构化分类,agent 按 message 修源码即可,不抛异常。+ * 打包核心:校验 + 收集 + 生成 zip buffer,不写盘。packGhostDir(产物进源码目录)+ * 与 packGhostDirToFile(产物去调用方指定路径,自定义市场安装管道用)共用,+ * 保证两条路径的校验与打包规则永远一致。*/-export async function packGhostDir(dir: string): Promise<ForgePackResult> {+async function buildGhostPackage(+ dir: string,+ /**+ * 调用方**已经校验过**的规范根(realpath 产物)。传入时,这里会核对自己解析出的+ * realpath 仍等于它,不等即拒。+ *+ * 为什么必须由调用方给:光靠"我自己 realpath 一次、再拿它当 containWithin 的锚点"+ * 是**自我参照**——插件目录或其父目录在调用方校验之后、这里解析之前被换成指向+ * 目录外的符号链接时,解析结果就是那个外部目录,以它为锚点的一切包含性判定自然+ * 全部通过,外部 payload 会被打包进去(外部目录只要留着同样的 ghost.json,清单+ * 对账也发现不了)。锚点必须来自上游的既有结论,不能在下游重新发明。+ */+ expectedRealDir?: string,+): Promise<+ | { ok: true; buf: Buffer; manifest: GhostManifest }+ | Exclude<ForgePackResult, { ok: true }>+> {try {let stat: fs.Stats;try {@@ -552,13 +572,42 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {if (!stat.isDirectory()) {return { ok: false, errorCode: 'DIR_NOT_FOUND', message: `不是目录:${dir}` };}+ // 后续所有读取都以 realpath 根做 containWithin 复核:O_NOFOLLOW 只管最后+ // 一个路径分量,校验后中间目录被换成根外链接的窗口靠它堵。+ const realDir = await fs.promises.realpath(dir);+ if (expectedRealDir !== undefined && realDir !== expectedRealDir) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: '插件目录在打包前被替换(实际规范路径与调用方校验过的不一致)',+ };+ }// 1) 清单先行:与装入侧同一套校验,错在打包期就报清楚。+ // 读到的**原始字节**要留作不可变快照:后面生成 zip 时逐文件重新读盘,若+ // ghost.json 在"这里校验"与"写入 zip"之间被并发改写(保 id/version、加权限+ // 声明),返回的 manifest 与包里那份就会分叉——安装侧拿返回值做审阅比对,+ // 装进去的却是改过的包。快照写入让"校验的 = 返回的 = 包里的"三者恒等。+ // 与市场发现/安装层同一把闸(单句柄限量读,拒符号链接):打包输入目录是+ // 用户可写的活目录,按路径无界 readFile 会跟随链接读到目录外、或被超大+ // 文件耗尽内存。快照字节也必须出自这把闸,不能再按路径重读。let manifestRaw: unknown;+ let manifestBytes: Buffer;try {- manifestRaw = JSON.parse(- await fs.promises.readFile(path.join(dir, GHOST_MANIFEST_FILE), 'utf-8'),+ const bytes = await readBoundedFileNoFollow(+ path.join(realDir, GHOST_MANIFEST_FILE),+ GHOST_MANIFEST_MAX_BYTES,+ { containWithin: realDir },);+ if (bytes === null) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `${GHOST_MANIFEST_FILE} 不是普通文件或超过 ${GHOST_MANIFEST_MAX_BYTES} 字节上限`,+ };+ }+ manifestBytes = bytes;+ manifestRaw = JSON.parse(manifestBytes.toString('utf-8'));} catch (err) {return {ok: false,@@ -592,7 +641,9 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {for (const item of manifest.skill?.items ?? []) mustExist.push(`${item.dir}/SKILL.md`);for (const rel of mustExist) {try {- const st = await fs.promises.stat(path.join(dir, rel));+ // lstat 与收集侧(walk 的 Dirent)同一语义:声明的入口若是符号链接,+ // stat 会判"在场"而 walk 不收集它,装出的包缺入口、运行期才 404。+ const st = await fs.promises.lstat(path.join(dir, rel));if (!st.isFile()) throw new Error('not a file');} catch {return { ok: false, errorCode: 'ENTRY_MISSING', message: `清单声明的文件不存在:${rel}` };@@ -605,7 +656,18 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {const skillMdPath = path.join(dir, ...item.dir.split('/'), 'SKILL.md');let content: string;try {- content = await fs.promises.readFile(skillMdPath, 'utf-8');+ // 同一把单句柄限量闸:超限在读之前拒,符号链接不放行。+ const bytes = await readBoundedFileNoFollow(skillMdPath, GHOST_SKILL_MD_MAX_BYTES, {+ containWithin: realDir,+ });+ if (bytes === null) {+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `${item.dir}/SKILL.md 不是普通文件或超过 ${GHOST_SKILL_MD_MAX_BYTES} 字节上限`,+ };+ }+ content = bytes.toString('utf-8');} catch (err) {return {ok: false,@@ -613,13 +675,6 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {message: `读取 ${item.dir}/SKILL.md 失败:${err instanceof Error ? err.message : String(err)}`,};}- if (Buffer.byteLength(content, 'utf8') > GHOST_SKILL_MD_MAX_BYTES) {- return {- ok: false,- errorCode: 'MANIFEST_INVALID',- message: `${item.dir}/SKILL.md 过大(上限 ${GHOST_SKILL_MD_MAX_BYTES} 字节)`,- };- }const consistencyError = checkSkillMdConsistency(content, item);if (consistencyError) {return {@@ -636,7 +691,7 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {const maxFiles = manifest.node ? MAX_NODE_FILES : MAX_BASIC_FILES;const maxTotalBytes = manifest.node ? MAX_NODE_TOTAL_BYTES : MAX_BASIC_TOTAL_BYTES;const seenPackPaths = new Set<string>();- const walk = async (cur: string, relBase: string): Promise<ForgePackResult | null> => {+ const walk = async (cur: string, relBase: string): Promise<Exclude<ForgePackResult, { ok: true }> | null> => {const entries = await fs.promises.readdir(cur, { withFileTypes: true });for (const e of entries) {if (shouldSkip(e.name)) continue;@@ -654,6 +709,15 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {if (e.isDirectory()) {const bad = await walk(abs, rel);if (bad) return bad;+ } else if (e.isSymbolicLink()) {+ // 符号链接一律不穿透。此前是静默跳过——OneDrive 未水合占位文件、+ // 仓库里提交的链接都会被悄悄丢出包外,校验说"在场"、包里却没有,+ // 运行期才 404。改为结构化拒绝,错误可见。+ return {+ ok: false,+ errorCode: 'MANIFEST_INVALID',+ message: `源码目录含符号链接条目,不允许打包:${rel}`,+ };} else if (e.isFile()) {files.push({ rel, abs });totalBytes += (await fs.promises.stat(abs)).size;@@ -674,12 +738,39 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {const tooLarge = await walk(dir, '');if (tooLarge) return tooLarge;- // 5) 打包到源码目录自身(2026-07 Lizi 定案:产物跟源码住一起,拿取直观)。- // 文件收集在写盘之前完成 + shouldSkip 跳过 *.cindy,自身产物不会进包;- // 同名覆盖:同 id 同版本重打包语义上就是同一个包。+ // 5) 生成 zip buffer。文件收集在此之前完成 + shouldSkip 跳过 *.cindy,+ // 产物自身不会进包;写盘位置由调用方决定(packGhostDir 进源码目录,+ // packGhostDirToFile 进调用方指定路径)。const zip = new JSZip();+ // 身份卡用第 1 步的不可变快照,其余文件走同一把单句柄限量闸现读:walk 里+ // 的 stat 只是预算预估,文件可在 walk 与此处之间被换成超大文件或符号链接+ // (网络共享/并发写)。真正的边界在读取时按**剩余总预算**强制执行,任何+ // 文件被并发改动(换链接/删除/膨胀)都结构化拒绝,不把无界字节交给 JSZip。+ let packedBytes = 0;for (const f of files) {- zip.file(f.rel, await fs.promises.readFile(f.abs));+ let content: Buffer;+ if (f.rel === GHOST_MANIFEST_FILE) {+ content = manifestBytes;+ } else {+ let bytes: Buffer | null;+ try {+ bytes = await readBoundedFileNoFollow(f.abs, maxTotalBytes - packedBytes, {+ containWithin: realDir,+ });+ } catch {+ bytes = null;+ }+ if (bytes === null) {+ return {+ ok: false,+ errorCode: 'TOO_LARGE',+ message: `文件在打包期间被并发改动或超出剩余体积预算:${f.rel}`,+ };+ }+ content = bytes;+ }+ packedBytes += content.byteLength;+ zip.file(f.rel, content);}const buf = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });const maxCindyBytes = manifest.node ? MAX_NODE_CINDY_BYTES : MAX_BASIC_CINDY_BYTES;@@ -690,9 +781,7 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {message: `压缩包体积超上限(${maxCindyBytes} 字节)`,};}- const cindyPath = path.join(dir, `${manifest.id}-${manifest.version}.cindy`);- await fs.promises.writeFile(cindyPath, buf);- return { ok: true, cindyPath, manifest };+ return { ok: true, buf, manifest };} catch (err) {return {ok: false,@@ -702,6 +791,57 @@ export async function packGhostDir(dir: string): Promise<ForgePackResult> {}}+/**+ * 校验 + 打包一个意识源码目录。产物写到源码目录自身(<id>-<version>.cindy,+ * 同名覆盖——同 id 同版本重打包语义上就是同一个包),用户在自己的意识目录里+ * 就能拿到成品;出错返回结构化分类,agent 按 message 修源码即可,不抛异常。+ */+export async function packGhostDir(dir: string): Promise<ForgePackResult> {+ const built = await buildGhostPackage(dir);+ if (!built.ok) return built;+ // 产物跟源码住一起(2026-07 Lizi 定案:拿取直观);文件收集在写盘之前完成+ // + shouldSkip 跳过 *.cindy,自身产物不会进包;同名覆盖。+ const cindyPath = path.join(dir, `${built.manifest.id}-${built.manifest.version}.cindy`);+ try {+ await fs.promises.writeFile(cindyPath, built.buf);+ } catch (err) {+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: `写入打包产物失败:${err instanceof Error ? err.message : String(err)}`,+ };+ }+ return { ok: true, cindyPath, manifest: built.manifest };+}++/**+ * 打包到调用方指定的绝对路径。自定义市场安装管道用:市场克隆缓存是只读事实,+ * 产物落到临时目录,装完即删。校验与打包规则与 packGhostDir 完全一致。+ *+ * `expectedRealDir` **必填**:这条路径的输入来自用户可写的市场目录,打包器不能+ * 自己 realpath 一次就当锚点(自我参照,见 buildGhostPackage 的说明)。做成必填+ * 而不是可选,是为了让新调用方无法跳过——签名逼着它交出上游已经校验过的规范根。+ */+export async function packGhostDirToFile(+ dir: string,+ destPath: string,+ expectedRealDir: string,+): Promise<ForgePackResult> {+ const built = await buildGhostPackage(dir, expectedRealDir);+ if (!built.ok) return built;+ try {+ // 0o600:临时包可能落在共享 /tmp,不给同机其它用户读权限。+ await fs.promises.writeFile(destPath, built.buf, { flag: 'wx', mode: 0o600 });+ } catch (err) {+ return {+ ok: false,+ errorCode: 'INTERNAL',+ message: `写入打包产物失败:${err instanceof Error ? err.message : String(err)}`,+ };+ }+ return { ok: true, cindyPath: destPath, manifest: built.manifest };+}+/*** 《意识编写手册》——ghost_forge_guide 的返回体。随主机版本演进,改了机制* 就同步改这里;agent 每次做意识前现拿现读,永不过期。diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallLock.ts b/apps/desktop/src/main/cindy-brain/ghostInstallLock.tsnew file mode 100644index 0000000000..360b9ba8f5--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/ghostInstallLock.ts@@ -0,0 +1,66 @@+/**+ * 按 ghostId 的**可重入**互斥锁:同一插件的装入 / 更新 / 卸载全程串行。+ *+ * 为什么需要:`GhostMutationCoordinator` 是账户 drain barrier(可并发持有,只保证+ * 切号前排空),**不提供互斥**。同一 ghostId 的市场装入、本地 .cindy 装入 / 更新、+ * 卸载若能交错,"检查目标是否已装 → 落位 → 写溯源"之间的窗口就会被另一条路径插入:+ * 把"更新"降级成"首装带电"、静默覆盖刚装入的同 id 包、或让账本认领一个其实不属于+ * 自己的包(权限差异确认还因审阅时目标不存在而没跑过)。+ *+ * 为什么**可重入**:这块的教训是"给眼前这条路加个 guard"永远漏下一条。锁因此同时+ * 加在三个卡点(`installAndDock`、`installOrUpdateMarketGhostPackage`、+ * `uninstallGhostAndCleanup`)与各调用方的复核段上——外层已持有时内层必须是 no-op,+ * 否则自锁死锁。这样新增装入路径即使忘了取锁,也会在卡点被兜住。+ *+ * 锁序不变量(违反即死锁):+ * `withMutation(pluginId)` → `SOURCE_MUTATION_KEY` → **ghostId** → `ledgerMutation`+ * 持本锁时不得反向去取来源锁或 pluginId 锁。卸载路径只用 pluginId → ghostId →+ * ledger(不取来源锁),与上面的偏序相容。+ *+ * 仅 main 进程内有效(Electron 单实例)。+ */+import { AsyncLocalStorage } from 'node:async_hooks';++/** 当前异步上下文已持有的 ghostId 集合(重入判定依据)。 */+const heldIds = new AsyncLocalStorage<ReadonlySet<string>>();++/** 每个 ghostId 的等待链尾。 */+const locks = new Map<string, Promise<void>>();++/** 当前异步上下文是否已持有该 ghostId 的锁(供卡点断言用)。 */+export function isGhostInstallLockHeld(ghostId: string): boolean {+ return heldIds.getStore()?.has(ghostId) ?? false;+}++export async function withGhostInstallLock<T>(+ ghostId: string,+ fn: () => Promise<T>,+): Promise<T> {+ const current = heldIds.getStore();+ // 重入:本上下文已持有 → 直接执行。必须在排队之前判定,否则等自己释放 = 自锁。+ if (current?.has(ghostId)) return fn();++ const prev = locks.get(ghostId) ?? Promise.resolve();+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ const mine = prev.then(() => gate);+ locks.set(ghostId, mine);+ // 轮到自己:等前一笔结束(无论成败)。+ await prev.catch(() => undefined);+ const nextHeld = new Set(current ?? []);+ nextHeld.add(ghostId);+ try {+ return await heldIds.run(nextHeld, fn);+ } finally {+ release();+ // 链尾清理,避免 Map 无界增长(仅当自己仍是最后一笔时删)。+ if (locks.get(ghostId) === mine) locks.delete(ghostId);+ }+}++/** 仅测试用:清空等待链,避免用例间互相影响。 */+export function resetGhostInstallLocksForTest(): void {+ locks.clear();+}diff --git a/apps/desktop/src/main/cindy-brain/ghostLocaleFiles.ts b/apps/desktop/src/main/cindy-brain/ghostLocaleFiles.tsindex 736210c6b6..83beb107e6 100644--- a/apps/desktop/src/main/cindy-brain/ghostLocaleFiles.ts+++ b/apps/desktop/src/main/cindy-brain/ghostLocaleFiles.ts@@ -6,6 +6,7 @@ import {validateGhostManifestLocaleResource,type GhostManifest,} from '../../shared/ghost.js';+import { readBoundedFileNoFollowSync } from '../utils/readBoundedFile.js';export type GhostLocaleDirectoryValidation = { ok: true } | { ok: false; reason: string };@@ -46,17 +47,31 @@ export function validateGhostLocaleResourcesInDirectory(manifest: GhostManifest,): GhostLocaleDirectoryValidation {if (!manifest.locales) return { ok: true };+ let realRoot: string;+ try {+ realRoot = fs.realpathSync(rootDir);+ } catch (error) {+ return {+ ok: false,+ reason: `locale 根目录不可用:${error instanceof Error ? error.message : String(error)}`,+ };+ }for (const [locale, relativePath] of Object.entries(manifest.locales)) {try {const absolutePath = resolveExactFile(rootDir, relativePath);- const stat = fs.statSync(absolutePath);- if (stat.size > GHOST_LOCALE_MAX_BYTES) {+ // 单句柄限量闸(同步变体):statSync 后再 readFileSync 是两次独立打开,+ // 并发方可在其间把文件换成超大文件或符号链接绕过大小闸;containWithin+ // 复核堵中间目录被换成根外链接的窗口。+ const bytes = readBoundedFileNoFollowSync(absolutePath, GHOST_LOCALE_MAX_BYTES, {+ containWithin: realRoot,+ });+ if (bytes === null) {return {ok: false,- reason: `locales.${locale} 超过 ${GHOST_LOCALE_MAX_BYTES} 字节上限(${relativePath})`,+ reason: `locales.${locale} 不是普通文件或超过 ${GHOST_LOCALE_MAX_BYTES} 字节上限(${relativePath})`,};}- const raw = JSON.parse(fs.readFileSync(absolutePath, 'utf8')) as unknown;+ const raw = JSON.parse(bytes.toString('utf8')) as unknown;const localized = validateGhostManifestLocaleResource(raw, manifest);if (!localized.ok) {return {diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex a6af95afb4..8b8ba51e6a 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -39,6 +39,7 @@ import { getLayoutStore } from '../layout/index.js';import { GhostManager, type InstallRejection, type UninstallRejection } from './GhostManager.js';import { exportGhostPackage } from './exportGhostPackage.js';import { GhostMutationCoordinator } from './ghostMutationCoordinator.js';+import { withGhostInstallLock } from './ghostInstallLock.js';import {clearBuiltinTombstone,listEligibleBuiltinCommands,@@ -2830,6 +2831,14 @@ function rejectReservedGhostId(id: string): void {throwIpcError('GHOST_ID_RESERVED', `id "${id}" 使用了官方保留前缀(cindy- / filo- / xd-),用户通道不可装入`);}+/**+ * 自定义市场(Git / 本地源)装入前的保留前缀闸。与服务端市场不同,自定义源+ * 的包字节未经 plugin-server 绑定,不享受官方前缀豁免,语义同本地 .cindy 装入。+ */+export function rejectReservedGhostIdForCustomMarket(id: string): void {+ rejectReservedGhostId(id);+}+/*** tokenBroker 第一方门控·装入闸:oauth 详单声明了 tokenBroker 的意识,XDT* server 的授权 broker(带用户登录 JWT 的服务端资产)只对官方前缀 id 开放,@@ -2884,17 +2893,38 @@ function throwUninstallError(rejection: UninstallRejection): never {export async function installAndDock(manager: GhostManager,lizFilePath: string,- opts?: { enable?: boolean; expectedPackageSha256?: string },+ /**+ * `ghostId` 必填:它同时是**按 id 互斥锁的键**。装入前已由调用方经 inspect+ * 验明(市场路径核对 expected、本地路径核对 sha256 钉住的 probe),所以此处+ * 可信。做成必填而不是可选,是为了让新增装入路径无法"忘记取锁"——签名逼着+ * 它交出 id,锁在这里自动获取(外层已持有时按可重入 no-op)。+ */+ opts: { ghostId: string; enable?: boolean; expectedPackageSha256?: string },+): Promise<InstalledGhost> {+ return withGhostInstallLock(opts.ghostId, () => installAndDockLocked(manager, lizFilePath, opts));+}++async function installAndDockLocked(+ manager: GhostManager,+ lizFilePath: string,+ opts: { ghostId: string; enable?: boolean; expectedPackageSha256?: string },): Promise<InstalledGhost> {// 默认沉睡(2026-07-09 Lizi 定案):装入 ≠ 授权运行,用户在确认框显式勾选// "立即开启"才带电;沉睡态面板不渲染、总机不列、沙箱不拉起。const result = await manager.install(lizFilePath, {- initiallyEnabled: opts?.enable ?? false,- ...(opts?.expectedPackageSha256+ initiallyEnabled: opts.enable ?? false,+ ...(opts.expectedPackageSha256? { expectedPackageSha256: opts.expectedPackageSha256 }: {}),});if ('rejection' in result) throwInstallError(result.rejection);+ // 纵深防御:调用方给错 id 意味着刚才那把锁上在了错误的键上(等于没上锁)。+ // 宁可装完即报错让上层看见,也不要留下"以为串行、其实没有"的假象。+ if (result.ghost.manifest.id !== opts.ghostId) {+ throw new Error(+ `装入包的 ghostId(${result.ghost.manifest.id})与加锁使用的 id(${opts.ghostId})不一致`,+ );+ }// 用户手动重装同 id 的内置意识 = 重新跟随包内版本(清墓碑,播种恢复对账)。clearBuiltinTombstone(brainRootDir(), result.ghost.manifest.id, log);// 声明了面板的意识装入后立即停进布局树(树上已有 = 重装,原位复活不动树)。@@ -2925,6 +2955,21 @@ export async function installOrUpdateMarketGhostPackage(ghostId: string;version: string;},+): Promise<InstalledGhost> {+ // 卡点:按 ghostId 上锁,覆盖 inspect → 落位整段。服务端与自定义两条市场路径+ // 都经此出口,调用方漏取锁也被兜住;调用方已持有时按可重入 no-op(它们会把+ // 复核与账本写入一起纳入同一把锁,范围比这里更大)。+ return withGhostInstallLock(expected.ghostId, () =>+ installOrUpdateMarketGhostPackageLocked(cindyFilePath, expected),+ );+}++async function installOrUpdateMarketGhostPackageLocked(+ cindyFilePath: string,+ expected: {+ ghostId: string;+ version: string;+ },): Promise<InstalledGhost> {const mutationOwner = captureGhostMutationOwner();let releaseMutation: (() => void) | null = null;@@ -2957,7 +3002,15 @@ export async function installOrUpdateMarketGhostPackage(// 校验下载),且确认框如实展示权限清单,确认安装即授权运行;本地 .cindy// 文件装入的初始启用态仍由确认框勾选决定(勾选默认开启,main 侧// installAndDock 缺省不启用,授权判断始终来自 UI 显式值)。- return installAndDock(manager, cindyFilePath, { enable: true });+ // expectedPackageSha256 把"检查过的字节"与"落位的字节"钉死为同一份:+ // inspect 与 install 各自重读磁盘,临时 .cindy 在两读之间被替换时,+ // 所有前置校验(保留前缀/审阅比对/签名/解压上限)都会作用在旧字节上。+ // 本地 .cindy 装入通道已强制此对账,市场通道同一口径。+ return installAndDock(manager, cindyFilePath, {+ ghostId: expected.ghostId,+ enable: true,+ expectedPackageSha256: inspected.packageSha256,+ });}const runtime = getGhostRuntime();@@ -2967,7 +3020,10 @@ export async function installOrUpdateMarketGhostPackage(getGhostErrandSlot().clearGhost(expected.ghostId);let result: Awaited<ReturnType<typeof manager.update>>;try {- result = await manager.update(cindyFilePath);+ // 与首装分支同一口径:钉住 inspect 时校验过的包字节(见上)。+ result = await manager.update(cindyFilePath, {+ expectedPackageSha256: inspected.packageSha256,+ });} catch (error) {spawnIfResident(installed);throw error;@@ -3019,6 +3075,15 @@ export function setGhostUninstallLedgerPreparer(export async function uninstallGhostAndCleanup(id: string,options?: { skipMarketLedger?: boolean },+): Promise<void> {+ // 按 ghostId 与装入/更新互斥:卸载与同 id 的市场/本地装入不得交错,否则+ // 市场装入的"目标是否已装"判定会被本卸载在其落位前抽走(反之亦然)。+ return withGhostInstallLock(id, () => uninstallGhostAndCleanupLocked(id, options));+}++async function uninstallGhostAndCleanupLocked(+ id: string,+ options?: { skipMarketLedger?: boolean },): Promise<void> {const releaseMutation = beginGhostMutation();try {@@ -3998,26 +4063,29 @@ export function registerGhostIpc(): void {const installOpts = opts as| { enable?: unknown; expectedPackageSha256?: unknown }| undefined;+ const expectedPackageSha256 = installOpts?.expectedPackageSha256;if (- typeof installOpts?.expectedPackageSha256 !== 'string' ||- !/^[a-f0-9]{64}$/.test(installOpts.expectedPackageSha256)+ typeof expectedPackageSha256 !== 'string' ||+ !/^[a-f0-9]{64}$/.test(expectedPackageSha256)) {throwIpcError('INVALID_PARAMS', 'expectedPackageSha256 must come from ghosts:inspect');}const probe = await manager.inspect(lizFilePath);if ('rejection' in probe) throwInstallError(probe.rejection);- if (probe.packageSha256 !== installOpts.expectedPackageSha256) {+ if (probe.packageSha256 !== expectedPackageSha256) {throwIpcError('GHOST_FILE_INVALID', '插件文件在确认后发生了变化,请重新选择并确认');}rejectReservedGhostId(probe.manifest.id);rejectUnauthorizedTokenBroker(probe.manifest);// Node 高风险提示在 renderer 装入确认卡的权限清单里如实展示;// 2026-07-24 Lizi 定案:不再追加 Main 原生二次确认弹窗。- const enable = installOpts.enable === true;+ const enable = installOpts?.enable === true;+ // 锁由 installAndDock 按 ghostId 自动获取(卡点);这里传 id 即可。return {ghost: await installAndDock(manager, lizFilePath, {+ ghostId: probe.manifest.id,enable,- expectedPackageSha256: installOpts.expectedPackageSha256,+ expectedPackageSha256,}),};});@@ -4045,34 +4113,38 @@ export function registerGhostIpc(): void {}rejectReservedGhostId(inspected.manifest.id);rejectUnauthorizedTokenBroker(inspected.manifest);- const previousGhost = manager.list().find((g) => g.manifest.id === inspected.manifest.id);- runtime.stop(inspected.manifest.id);- getGhostNodeRuntimeBroker().stop(inspected.manifest.id);- getGhostAgentSlot().clearGhost(inspected.manifest.id);- getGhostErrandSlot().clearGhost(inspected.manifest.id);- let result: Awaited<ReturnType<typeof manager.update>>;- try {- result = await manager.update(lizFilePath, { expectedPackageSha256 });- } catch (err) {- // 更新失败:恢复旧版本的常驻 Node 工作进程(如果是 resident 且已启用)- if (previousGhost) spawnIfResident(previousGhost);- throw err;- }- if ('rejection' in result) {- if (previousGhost) spawnIfResident(previousGhost);- throwInstallError(result.rejection);- }- runtime.resetFuse(inspected.manifest.id); // 换了代码,给新版本干净的熔断记账- const store = getLayoutStore();- const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);- if (docked) {- const applied = store.setLayout(docked);- if ('rejection' in applied) {- log.warn('ghost panel dock rejected', { id: result.ghost.manifest.id, reason: applied.rejection });+ // 与市场装入/本地装入/卸载共用按 ghostId 的互斥:换目录期间同 id 的其它+ // 装入/卸载不得插入(否则并发装入会与本次 rename 竞争、留下不一致态)。+ return withGhostInstallLock(inspected.manifest.id, async () => {+ const previousGhost = manager.list().find((g) => g.manifest.id === inspected.manifest.id);+ runtime.stop(inspected.manifest.id);+ getGhostNodeRuntimeBroker().stop(inspected.manifest.id);+ getGhostAgentSlot().clearGhost(inspected.manifest.id);+ getGhostErrandSlot().clearGhost(inspected.manifest.id);+ let result: Awaited<ReturnType<typeof manager.update>>;+ try {+ result = await manager.update(lizFilePath, { expectedPackageSha256 });+ } catch (err) {+ // 更新失败:恢复旧版本的常驻 Node 工作进程(如果是 resident 且已启用)+ if (previousGhost) spawnIfResident(previousGhost);+ throw err;}- }- spawnIfResident(result.ghost); // 常驻意识:换完代码立即用新版本点火- return { ghost: result.ghost };+ if ('rejection' in result) {+ if (previousGhost) spawnIfResident(previousGhost);+ throwInstallError(result.rejection);+ }+ runtime.resetFuse(inspected.manifest.id); // 换了代码,给新版本干净的熔断记账+ const store = getLayoutStore();+ const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);+ if (docked) {+ const applied = store.setLayout(docked);+ if ('rejection' in applied) {+ log.warn('ghost panel dock rejected', { id: result.ghost.manifest.id, reason: applied.rejection });+ }+ }+ spawnIfResident(result.ghost); // 常驻意识:换完代码立即用新版本点火+ return { ghost: result.ghost };+ });});// 设置页「装入意识…」第一步:系统文件选择框(按 .cindy 过滤),只选不装。diff --git a/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts b/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.tsnew file mode 100644index 0000000000..9913fad503--- /dev/null+++ b/apps/desktop/src/main/plugin-market/__tests__/install-manifest-read.test.ts@@ -0,0 +1,201 @@+/**+ * installCustomMarketPlugin — 安装前置的身份卡读取必须走限量句柄闸。+ * 详情展示后、确认安装前,本地市场目录仍是用户可写的活目录;按路径无界+ * readFile 会被换成超大文件或符号链接绕过发现层的闸。+ */+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('electron', () => ({+ app: { getPath: vi.fn(() => os.tmpdir()) },+}));++const brain = vi.hoisted(() => ({+ installOrUpdateMarketGhostPackage: vi.fn(async () => ({}) as never),+ rejectReservedGhostIdForCustomMarket: vi.fn(),+ packGhostDirToFile: vi.fn(async () => ({ ok: true as const, manifest: {} })),+}));+vi.mock('../../cindy-brain/index.js', () => ({+ installOrUpdateMarketGhostPackage: brain.installOrUpdateMarketGhostPackage,+ rejectReservedGhostIdForCustomMarket: brain.rejectReservedGhostIdForCustomMarket,+}));+vi.mock('../../cindy-brain/forge.js', () => ({+ packGhostDirToFile: brain.packGhostDirToFile,+}));+const logger = vi.hoisted(() => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }));+vi.mock('../../logger.js', () => ({ createLogger: () => logger }));++import type { GhostManifest } from '../../../shared/ghost.js';+import { installCustomMarketPlugin } from '../install';++const GOOD_MANIFEST = {+ schemaVersion: 2,+ id: 'demo',+ name: '演示插件',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['tool'],+ tools: [{ name: 'do_thing', description: '做点事' }],+};++let workDir: string;++beforeEach(async () => {+ workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-market-install-'));+ brain.packGhostDirToFile.mockClear();+ logger.warn.mockClear();+});++afterEach(async () => {+ await fs.promises.rm(workDir, { recursive: true, force: true });+});++describe('installCustomMarketPlugin · 身份卡读取闸', () => {+ it.runIf(process.platform !== 'win32')(+ 'ghost.json 为符号链接 → GHOST_FILE_INVALID,不进入打包',+ async () => {+ // 目标是合法清单也不放行:发现层拒链接,安装层跟随链接就等于绕闸。+ const outside = path.join(workDir, 'outside-ghost.json');+ await fs.promises.writeFile(outside, JSON.stringify(GOOD_MANIFEST));+ const pluginDir = path.join(workDir, 'plugin');+ await fs.promises.mkdir(pluginDir, { recursive: true });+ await fs.promises.symlink(outside, path.join(pluginDir, 'ghost.json'));++ await expect(+ installCustomMarketPlugin({+ pluginDir,+ expected: GOOD_MANIFEST as unknown as GhostManifest,+ }),+ ).rejects.toMatchObject({ code: 'GHOST_FILE_INVALID' });+ expect(brain.packGhostDirToFile).not.toHaveBeenCalled();+ },+ );++ it('ghost.json 超过 512 KiB → GHOST_FILE_INVALID,不进入打包', async () => {+ // JSON 本身合法(合法清单 + 尾随空白撑体积):必须在读取层按大小拒,+ // 不能等 parse/validate——那时超大文件已经整个进内存了。+ const pluginDir = path.join(workDir, 'plugin-big');+ await fs.promises.mkdir(pluginDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(pluginDir, 'ghost.json'),+ JSON.stringify(GOOD_MANIFEST) + ' '.repeat(600 * 1024),+ );++ await expect(+ installCustomMarketPlugin({+ pluginDir,+ expected: GOOD_MANIFEST as unknown as GhostManifest,+ }),+ ).rejects.toMatchObject({ code: 'GHOST_FILE_INVALID' });+ expect(brain.packGhostDirToFile).not.toHaveBeenCalled();+ });++ it('把已校验的规范根同时作为打包输入与打包器锚点传下去', async () => {+ // 契约用例:锚点必须是**本层校验过的那个规范根**,不能是任何别的字符串+ // (第三个参数是必填的,TS 只能保证"传了",保证不了"传对";传成 tempPath+ // 之类会让打包器的锚点校验永远失败或永远通过,这里咬住)。+ // "被换成外部链接"本身由两处防线拦:本层的等值校验 + 打包器内的锚点校验+ // (各有独立用例)。+ const pluginDir = path.join(workDir, 'plugin-ok');+ await fs.promises.mkdir(pluginDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(pluginDir, 'ghost.json'),+ JSON.stringify(GOOD_MANIFEST),+ );+ const canonical = await fs.promises.realpath(pluginDir);+ brain.packGhostDirToFile.mockResolvedValue({+ ok: true as const,+ manifest: GOOD_MANIFEST,+ });++ await installCustomMarketPlugin({+ pluginDir: canonical,+ expected: GOOD_MANIFEST as unknown as GhostManifest,+ });++ expect(brain.packGhostDirToFile).toHaveBeenCalledWith(+ canonical,+ expect.stringContaining('.cindy'),+ canonical, // ← 锚点必须是上游校验过的规范根+ );+ });++ it.runIf(process.platform !== 'win32')(+ '发现后插件目录被换成指向市场外的符号链接 → 拒绝,不进入打包',+ async () => {+ // 发现层交回的是已 realpath、已校验在根内的规范路径。之后把该目录换成指向+ // 市场外(留着同样的 ghost.json)的符号链接:重解析落到别处,清单摘要复核+ // 发现不了。install 必须发现 realpath 已改变并拒绝,payload 不被打包。+ const outside = path.join(workDir, 'outside');+ await fs.promises.mkdir(outside, { recursive: true });+ await fs.promises.writeFile(+ path.join(outside, 'ghost.json'),+ JSON.stringify(GOOD_MANIFEST),+ );+ const realParent = path.join(workDir, 'market');+ await fs.promises.mkdir(realParent, { recursive: true });+ const realPluginDir = path.join(realParent, 'alpha');+ await fs.promises.mkdir(realPluginDir, { recursive: true });+ await fs.promises.writeFile(+ path.join(realPluginDir, 'ghost.json'),+ JSON.stringify(GOOD_MANIFEST),+ );+ // 发现时的规范路径(realpath 幂等)。+ const discovered = await fs.promises.realpath(realPluginDir);+ // 攻击:把 alpha 换成指向 outside 的符号链接。+ await fs.promises.rm(realPluginDir, { recursive: true, force: true });+ await fs.promises.symlink(outside, realPluginDir);++ await expect(+ installCustomMarketPlugin({+ pluginDir: discovered, // 传发现时的规范路径+ expected: GOOD_MANIFEST as unknown as GhostManifest,+ }),+ ).rejects.toMatchObject({+ code: 'GHOST_FILE_INVALID',+ // 专用原因不得被下面那个通用 catch 的 "manifest missing or unreadable"+ // 覆盖:事后排查要能区分"有人中途替换了目录"与"文件确实损坏"。+ message: expect.stringContaining('changed after discovery'),+ });+ expect(brain.packGhostDirToFile).not.toHaveBeenCalled();+ },+ );++ it('清单确实损坏 → 通用文案给 Renderer,原始原因留 main 日志', async () => {+ // Renderer 只该拿到不泄露宿主细节的通用文案,但 main 日志必须留下原因,+ // 否则"损坏"与"被替换"两种情况在日志里完全一样,排查无从下手。+ const pluginDir = path.join(workDir, 'plugin-broken');+ await fs.promises.mkdir(pluginDir, { recursive: true });+ await fs.promises.writeFile(path.join(pluginDir, 'ghost.json'), '{not json');++ await expect(+ installCustomMarketPlugin({+ pluginDir: await fs.promises.realpath(pluginDir),+ expected: GOOD_MANIFEST as unknown as GhostManifest,+ }),+ ).rejects.toMatchObject({+ code: 'GHOST_FILE_INVALID',+ message: expect.stringContaining('missing or unreadable'),+ });+ expect(logger.warn).toHaveBeenCalledWith(+ 'custom market plugin manifest unreadable',+ expect.objectContaining({ detail: expect.stringMatching(/JSON|token|Unexpected/i) }),+ );+ });++ it('结构守卫:install.ts 不允许出现按路径的 readFile', async () => {+ // 发现/安装/打包三条链路都必须走 readBoundedFileNoFollow;任何一处退回+ // fs.promises.readFile(path) 都会重开"检查与读取两次打开"的替换窗口。+ const source = await fs.promises.readFile(+ path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'install.ts'),+ 'utf8',+ );+ expect(source).not.toMatch(/readFile\(/);+ expect(source).toContain('readBoundedFileNoFollow');+ });+});diff --git a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.tsindex fe730e2652..1c2a7f8476 100644--- a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts@@ -25,7 +25,17 @@ describe('Plugin Market IPC error boundary', () => {expect(body).toContain('if (isIpcError(error)) throw error;');expect(body).toContain("throwIpcError('INTERNAL', 'Plugin market operation failed');");- expect(registerSource.match(/return invokePluginMarket\(/g)?.length).toBe(4);+ expect(registerSource.match(/return invokePluginMarket\(/g)?.length).toBe(10);+ });++ it('refuses renderer-supplied local paths and only grants them via the picker', () => {+ // 本地目录授权边界:Renderer 直传绝对路径不构成授权,必须由 Main 原生+ // 目录选择器签发(用户的选择即授权)。此断言防止有人退回"直传即添加"。+ expect(registerSource).toContain("parsed.source.type === 'local'");+ expect(registerSource).toContain('Local folders must be added via the directory picker');+ expect(registerSource).toContain("ipcMain.handle('plugin-market:pick-local-source'");+ expect(serviceSource).toContain('addLocalSourceFromPicker');+ expect(serviceSource).toContain("properties: ['openDirectory']");});it('does not throw user-visible plain errors from the market service', () => {diff --git a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.tsindex ae9cc65e05..ac2562407d 100644--- a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts@@ -113,4 +113,166 @@ describe('PluginMarketLedger', () => {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('recovers installations from .bak instead of reading a missing file as empty', () => {+ const h = harness();+ h.ledger.upsertInstallation(record({ ghostId: 'cindy-kept' }));+ // 模拟 Windows 备份交换与回滚都失败:主文件缺失,.bak 是唯一有效快照。+ fs.renameSync(h.filePath, `${h.filePath}.bak`);++ // 读取入口必须恢复 .bak;否则这里读成空账本,下面的写入会把唯一快照覆盖掉,+ // 已安装插件的溯源记录永久丢失。+ expect(h.ledger.read().installations['cindy-kept']).toMatchObject({+ ghostId: 'cindy-kept',+ installed: true,+ });++ h.ledger.upsertInstallation(record({ ghostId: 'cindy-added' }));+ const after = h.ledger.read().installations;+ expect(Object.keys(after).sort()).toEqual(['cindy-added', 'cindy-kept']);+ });++ it('keeps custom-market provenance out of the main ledger file', () => {+ const h = harness();+ const customPath = path.join(path.dirname(h.filePath), 'custom-ledger.v1.json');+ h.ledger.upsertInstallation(record({ ghostId: 'cindy-server', source: 'market' }));+ h.ledger.upsertInstallation(+ record({+ ghostId: 'cindy-custom',+ pluginId: 'custom:team-lib/cindy-custom',+ source: 'git-market',+ sourceKey: 'git:https://x.test/r.git#:',+ }),+ );++ // 主账本文件不得出现旧版本不认识的 source:旧版 validRecord 是封闭枚举,+ // 会把它们过滤并重写落盘,自定义安装的溯源随降级永久丢失。+ const main = JSON.parse(fs.readFileSync(h.filePath, 'utf8'));+ expect(Object.keys(main.installations)).toEqual(['cindy-server']);+ const custom = JSON.parse(fs.readFileSync(customPath, 'utf8'));+ expect(Object.keys(custom.installations)).toEqual(['cindy-custom']);+ // 合并读仍是完整视图。+ expect(Object.keys(h.ledger.read().installations).sort()).toEqual([+ 'cindy-custom',+ 'cindy-server',+ ]);+ });++ it('survives an old-version rewrite that drops unknown sources from the main ledger', () => {+ const h = harness();+ h.ledger.upsertInstallation(record({ ghostId: 'cindy-server', source: 'market' }));+ h.ledger.upsertInstallation(+ record({+ ghostId: 'cindy-custom',+ pluginId: 'custom:team-lib/cindy-custom',+ source: 'local-market',+ sourceKey: 'local:/tmp/team-lib',+ }),+ );++ // 模拟降级后的旧版本写入:旧版 read() 只保留 market/legacy-adopted,+ // 任意一次写入都会把过滤后的主账本整份重写。+ const main = JSON.parse(fs.readFileSync(h.filePath, 'utf8'));+ main.installations = Object.fromEntries(+ Object.entries(main.installations).filter(([, value]) =>+ ['market', 'legacy-adopted'].includes((value as { source: string }).source),+ ),+ );+ fs.writeFileSync(h.filePath, JSON.stringify(main));++ // 再升级:自定义溯源在独立文件里,原样还在,不会被投影成本地冲突项。+ expect(h.ledger.read().installations['cindy-custom']).toMatchObject({+ source: 'local-market',+ sourceKey: 'local:/tmp/team-lib',+ installed: true,+ });+ });++ it('does not let a stale custom record shadow a newer server record for the same ghostId', () => {+ const h = harness();+ const customPath = path.join(path.dirname(h.filePath), 'custom-ledger.v1.json');+ // 降级窗口:新版装过自定义 X(记录在 custom 账本)→ 降级后旧版卸载它并从+ // 服务端装了同 ghostId(只写主账本)→ 升级回来。custom 账本里的陈旧记录若+ // 无条件覆盖,服务端安装会被错误归属给自定义来源,并允许该来源提供更新。+ fs.mkdirSync(path.dirname(h.filePath), { recursive: true });+ fs.writeFileSync(+ customPath,+ JSON.stringify({+ schemaVersion: 1,+ installations: {+ 'cindy-x': record({+ ghostId: 'cindy-x',+ pluginId: 'custom:team-lib/cindy-x',+ source: 'git-market',+ sourceKey: '["git","https://x.test/r.git",null,[]]',+ updatedAt: '2026-07-01T00:00:00.000Z',+ }),+ },+ }),+ );+ fs.writeFileSync(+ h.filePath,+ JSON.stringify({+ schemaVersion: 1,+ installations: {+ 'cindy-x': record({+ ghostId: 'cindy-x',+ source: 'market',+ updatedAt: '2026-08-01T00:00:00.000Z',+ }),+ },+ defaultInstallOptOuts: {},+ }),+ );++ expect(h.ledger.read().installations['cindy-x']).toMatchObject({ source: 'market' });++ // 反向仍成立:custom 记录更新(正常使用中主账本残留陈旧 server 记录)时 custom 胜。+ fs.writeFileSync(+ h.filePath,+ JSON.stringify({+ schemaVersion: 1,+ installations: {+ 'cindy-x': record({+ ghostId: 'cindy-x',+ source: 'market',+ installed: false,+ updatedAt: '2026-06-01T00:00:00.000Z',+ }),+ },+ defaultInstallOptOuts: {},+ }),+ );+ expect(h.ledger.read().installations['cindy-x']).toMatchObject({ source: 'git-market' });+ });++ it('migrates stray custom records out of the main ledger on the next write', () => {+ const h = harness();+ const customPath = path.join(path.dirname(h.filePath), 'custom-ledger.v1.json');+ // 早期开发版把自定义记录直接写进了主账本。+ fs.mkdirSync(path.dirname(h.filePath), { recursive: true });+ fs.writeFileSync(+ h.filePath,+ JSON.stringify({+ schemaVersion: 1,+ installations: {+ 'cindy-custom': record({+ ghostId: 'cindy-custom',+ pluginId: 'custom:team-lib/cindy-custom',+ source: 'git-market',+ }),+ },+ defaultInstallOptOuts: {},+ }),+ );++ // 读取兼容合并;任意一次写入即按 source 归位。+ expect(h.ledger.read().installations['cindy-custom']).toBeDefined();+ h.ledger.upsertInstallation(record({ ghostId: 'cindy-server', source: 'market' }));++ const main = JSON.parse(fs.readFileSync(h.filePath, 'utf8'));+ expect(Object.keys(main.installations)).toEqual(['cindy-server']);+ const custom = JSON.parse(fs.readFileSync(customPath, 'utf8'));+ expect(Object.keys(custom.installations)).toEqual(['cindy-custom']);+ });});diff --git a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.tsnew file mode 100644index 0000000000..be36d5471f--- /dev/null+++ b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts@@ -0,0 +1,1133 @@+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;+ }>,+ /** 测试可注入:每次 list() 调用返回不同快照(模拟打包窗口内运行时变动)。 */+ listSequence: null as null | (() => 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,+ },+}));++const pickerDialog = vi.hoisted(() => ({+ showOpenDialog: vi.fn(async () => ({ canceled: true, filePaths: [] as string[] })),+}));+vi.mock('electron', () => ({+ app: { getPath: vi.fn(() => os.tmpdir()) },+ dialog: pickerDialog,+}));+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.listSequence ? runtime.listSequence() : runtime.ghosts),+ }),+ isGhostAvailableForActiveSession: vi.fn(() => runtime.accountGhostAvailable),+ installOrUpdateMarketGhostPackage: runtime.install,+ rejectReservedGhostIdForCustomMarket: vi.fn(),+ isBuiltinGhostRemovedByUser: (id: string) => runtime.builtinRemoved.has(id),+ uninstallGhostAndCleanup: runtime.uninstall,+}));+vi.mock('../download.js', () => ({+ downloadVerifiedPlugin: vi.fn(async () => undefined),+}));++import type { VisiblePluginSummary } from '@cindy/plugin-protocol';++import type { MarketSourceConfig } from '../../../shared/pluginMarket';+import { customMarketPluginId, customMarketReleaseId, marketSourceKey } from '../../../shared/pluginMarket';+import { PluginMarketLedger, ghostManifestDigest } from '../ledger';+import { PluginMarketService } from '../service';+import { MarketSourceStore } from '../sources/store';+import type { PluginMarketApi } from '../api';++const roots: string[] = [];+const PLUGIN_ID = `c${'a'.repeat(24)}`;++afterEach(() => {+ runtime.ghosts = [];+ runtime.listSequence = null;+ 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 ghostManifest(id: string, version = '1.0.0') {+ return {+ schemaVersion: 2 as const,+ id,+ name: `Plugin ${id}`,+ description: 'Custom market plugin',+ author: 'Community',+ version,+ kind: 'chip' as const,+ entry: 'main.js',+ slots: ['notify'],+ };+}++function serverSummary(overrides: Partial<VisiblePluginSummary> = {}): VisiblePluginSummary {+ return {+ id: PLUGIN_ID,+ ghostId: 'server-plugin',+ name: 'Server Plugin',+ description: 'Server 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,+ };+}++/** 服务端详情夹具:summary + 该 release 的完整 manifest。 */+function serverDetail() {+ const summary = serverSummary();+ return {+ ...summary,+ currentRelease: {+ ...summary.currentRelease,+ manifest: ghostManifest(summary.ghostId),+ },+ };+}++/** 在临时目录造一个本地市场夹具(marketplace.json + 插件目录)。 */+function writeLocalMarket(+ root: string,+ marketName: string,+ plugins: Array<{ rel: string; id: string; version?: string }>,+): string {+ const dir = path.join(root, marketName);+ for (const plugin of plugins) {+ const pluginDir = path.join(dir, ...plugin.rel.split('/'));+ fs.mkdirSync(pluginDir, { recursive: true });+ fs.writeFileSync(+ path.join(pluginDir, 'ghost.json'),+ JSON.stringify(ghostManifest(plugin.id, plugin.version ?? '1.0.0')),+ );+ fs.writeFileSync(path.join(pluginDir, 'main.js'), '// entry');+ }+ fs.mkdirSync(path.join(dir, '.agents', 'plugins'), { recursive: true });+ fs.writeFileSync(+ path.join(dir, '.agents', 'plugins', 'marketplace.json'),+ JSON.stringify({+ name: marketName,+ plugins: plugins.map((plugin) => ({ name: plugin.id, source: plugin.rel })),+ }),+ );+ return dir;+}++function harness(items: VisiblePluginSummary[], marketDirs: Array<{ name: string; dir: string }>) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-plugin-custom-'));+ roots.push(root);+ const ledger = new PluginMarketLedger(path.join(root, 'ledger.json'));+ const sourceStore = new MarketSourceStore(path.join(root, 'sources.v1.json'));+ for (const market of marketDirs) {+ sourceStore.add({+ name: market.name,+ addedAt: '2026-07-30T00:00:00.000Z',+ lastSyncedAt: '2026-07-30T01:00:00.000Z',+ lastRevision: null,+ source: { type: 'local', path: market.dir },+ });+ }+ const api = {+ listAll: vi.fn(async () => items),+ detail: vi.fn(),+ download: vi.fn(),+ };+ return {+ api,+ ledger,+ sourceStore,+ service: new PluginMarketService(+ api as unknown as PluginMarketApi,+ ledger,+ sourceStore,+ ),+ };+}++describe('PluginMarketService 自定义市场聚合', () => {+ it('appends custom market items after server items with source identity', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);++ const snapshot = await h.service.snapshot();+ expect(snapshot.unavailableReason).toBeNull();+ expect(snapshot.customSourceNames).toEqual(['team-lib']);+ expect(snapshot.items).toHaveLength(2);+ const [server, custom] = snapshot.items;+ expect(server?.sourceType).toBe('server');+ expect(server?.sourceMarketName).toBeNull();+ expect(custom).toMatchObject({+ pluginId: customMarketPluginId('team-lib', 'alpha'),+ ghostId: 'alpha',+ releaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),+ installState: 'not-installed',+ sourceType: 'local-market',+ sourceMarketName: 'team-lib',+ });+ });++ it('strips bidi/control chars from custom plugin name/description/author in snapshot', async () => {+ // ghost.json 来自不受信市场仓库,双向控制符会在卡片上伪造署名/说明。+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = path.join(root, 'team-lib');+ const pluginDir = path.join(dir, 'plugins', 'alpha');+ fs.mkdirSync(pluginDir, { recursive: true });+ fs.writeFileSync(+ path.join(pluginDir, 'ghost.json'),+ JSON.stringify({+ ...ghostManifest('alpha'),+ name: 'AlphaEVIL',+ description: 'line1trick',+ author: 'mex',+ }),+ );+ fs.writeFileSync(path.join(pluginDir, 'main.js'), '// entry');+ fs.mkdirSync(path.join(dir, '.agents', 'plugins'), { recursive: true });+ fs.writeFileSync(+ path.join(dir, '.agents', 'plugins', 'marketplace.json'),+ JSON.stringify({ name: 'team-lib', plugins: [{ name: 'alpha', source: 'plugins/alpha' }] }),+ );+ const h = harness([], [{ name: 'team-lib', dir }]);++ const snapshot = await h.service.snapshot();+ const custom = snapshot.items.find((item) => item.ghostId === 'alpha');+ expect(custom?.name).toBe('AlphaEVIL');+ expect(custom?.description).toBe('line1trick');+ expect(custom?.author).toBe('mex');+ for (const field of [custom?.name, custom?.description, custom?.author]) {+ expect(field).not.toMatch(/[--]/);+ }+ });++ it('keeps custom items available when the server market is not configured', async () => {+ runtime.pluginApiBaseUrl = null;+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);++ const snapshot = await h.service.snapshot();+ expect(snapshot.unavailableReason).toBeNull();+ expect(snapshot.items).toHaveLength(1);+ expect(snapshot.items[0]?.sourceType).toBe('local-market');+ });++ it('keeps the not-configured reason when neither source has anything', async () => {+ runtime.pluginApiBaseUrl = null;+ const h = harness([], []);+ const snapshot = await h.service.snapshot();+ expect(snapshot).toEqual({+ items: [],+ unavailableReason: 'not-configured',+ customSourceNames: [],+ });+ });++ it('marks cross-source ghostId duplicates as conflict on both sides', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'server-plugin' }]);+ const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);++ const snapshot = await h.service.snapshot();+ expect(snapshot.items.find((item) => item.sourceType === 'server')?.installState).toBe(+ 'conflict',+ );+ expect(snapshot.items.find((item) => item.sourceType === 'local-market')?.installState).toBe(+ 'conflict',+ );+ });++ it('reports update-available when the marketplace version moved past the install', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [+ { rel: 'plugins/alpha', id: 'alpha', version: '2.0.0' },+ ]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ // 已装插件目录里放**原始** ghost.json;运行时 manifest 用"本地化后"的变体+ // (name 被翻译)——摘要比对必须 locale 无关,切语言不得把自装插件判成 conflict。+ const installedDir = path.join(root, 'installed-alpha');+ fs.mkdirSync(installedDir, { recursive: true });+ fs.writeFileSync(+ path.join(installedDir, 'ghost.json'),+ JSON.stringify(ghostManifest('alpha', '1.0.0')),+ );+ runtime.ghosts = [+ {+ manifest: { ...ghostManifest('alpha', '1.0.0'), name: 'アルファ(localized)' },+ dir: installedDir,+ enabled: true,+ },+ ];+ h.ledger.upsertInstallation({+ pluginId: customMarketPluginId('team-lib', 'alpha'),+ ghostId: 'alpha',+ releaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),+ version: '1.0.0',+ sha256: 'custom-unverified',+ scope: 'public',+ organizationId: null,+ source: 'local-market',+ installed: true,+ updatedAt: '2026-07-30T02:00:00.000Z',+ // 所有权 = pluginId + 来源指纹 + 安装时 manifest 摘要,三者齐全才认领。+ sourceKey: marketSourceKey({ type: 'local', path: dir }),+ manifestDigest: ghostManifestDigest(ghostManifest('alpha', '1.0.0')),+ });++ const snapshot = await h.service.snapshot();+ expect(snapshot.items[0]).toMatchObject({+ installState: 'update-available',+ version: '2.0.0',+ enabled: true,+ });+ });+});++describe('PluginMarketService 自定义市场 snapshot 账户作用域', () => {+ it('rejects the snapshot when the account switches during custom discovery', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);++ // 以 user-1 捕获 owner、按 user-1 完成自定义发现;在随后的服务端目录+ // await 间隙把会话漂移到 user-2,此后 requireSameMarketOwner 必须检测到并拒绝,+ // 而不是把 user-1 的自定义插件聚合进 user-2 的快照。+ h.api.listAll.mockImplementation(async () => {+ runtime.session = { mode: 'cloud', dataOwnerId: 'user-2', generation: 2 };+ return [];+ });+ await expect(h.service.snapshot()).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ });+ runtime.session = { mode: 'cloud', dataOwnerId: 'user-1', generation: 1 };+ });++ it('returns empty custom items instead of reading the previous account store when session is switching', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);++ // 切换中:不得按调用时 owner 现查 store/目录,直接降级为空并标记原因。+ runtime.boundaryPending = true;+ const snap = await h.service.snapshot();+ expect(snap.items).toEqual([]);+ expect(snap.customSourceNames).toEqual([]);+ expect(snap.unavailableReason).toBe('session-switching');+ runtime.boundaryPending = false;+ });+});++describe('PluginMarketService 自定义市场 detail/install', () => {+ it('returns the validated manifest for custom plugin detail', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);++ const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));+ expect(detail.manifest.id).toBe('alpha');+ expect(detail.sourceType).toBe('local-market');+ await expect(h.service.detail(customMarketPluginId('team-lib', 'missing'))).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ await expect(h.service.detail(customMarketPluginId('no-such-market', 'alpha'))).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ });++ it('installs a custom market plugin and records local-market provenance', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ runtime.install.mockResolvedValue({+ manifest: ghostManifest('alpha'),+ dir: '/ghosts/alpha',+ enabled: true,+ });++ const pluginId = customMarketPluginId('team-lib', 'alpha');+ // 以 detail 下发的归一化 manifest 作为“用户审阅内容”,与安装侧重读结果逐字比对。+ const reviewed = await h.service.detail(pluginId);+ const result = await h.service.install(pluginId, {+ expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),+ expectedManifest: reviewed.manifest,+ });+ expect(result.ghost.manifest.id).toBe('alpha');+ expect(runtime.install).toHaveBeenCalledTimes(1);+ // 打包产物是临时文件,装完即删+ expect(runtime.install.mock.calls[0]?.[0]).toMatch(/cindy-custom-market-alpha-.*\.cindy$/);+ expect(fs.existsSync(runtime.install.mock.calls[0]?.[0] as string)).toBe(false);++ const record = h.ledger.installationForGhost('alpha');+ expect(record).toMatchObject({+ pluginId,+ source: 'local-market',+ installed: true,+ version: '1.0.0',+ });+ });++ it('rejects install when the reviewed release no longer matches', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));++ await expect(+ h.service.install(customMarketPluginId('team-lib', 'alpha'), {+ expectedReleaseId: 'custom:stale',+ expectedManifest: reviewed.manifest,+ }),+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(runtime.install).not.toHaveBeenCalled();+ });++ it('rejects install when the manifest changed after permission review', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);++ const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));+ // 用户审阅之后,本地 ghost.json 保持 id/version 不变但新增权限声明。+ const ghostFile = path.join(dir, 'plugins', 'alpha', 'ghost.json');+ const tampered = { ...ghostManifest('alpha'), description: 'tampered after review' };+ fs.writeFileSync(ghostFile, JSON.stringify(tampered));++ await expect(+ h.service.install(customMarketPluginId('team-lib', 'alpha'), {+ expectedReleaseId: detail.releaseId,+ expectedManifest: detail.manifest,+ }),+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(runtime.install).not.toHaveBeenCalled();+ });++ it('rejects install when the account switches during packaging', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ const detail = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));++ // 打包(异步)完成后、装出前,会话已漂移到 user-2:beforeCommit 必须拒绝,+ // 不得把 user-1 审阅的插件装进 user-2 的运行时。+ h.api.listAll.mockImplementation(async () => {+ runtime.session = { mode: 'cloud', dataOwnerId: 'user-2', generation: 2 };+ return [];+ });+ // 打包前的 discover/校验按 user-1 完成;在 install 入口后切换会话。+ const installPromise = h.service.install(customMarketPluginId('team-lib', 'alpha'), {+ expectedReleaseId: detail.releaseId,+ expectedManifest: detail.manifest,+ });+ runtime.session = { mode: 'cloud', dataOwnerId: 'user-2', generation: 2 };+ await expect(installPromise).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(runtime.install).not.toHaveBeenCalled();+ runtime.session = { mode: 'cloud', dataOwnerId: 'user-1', generation: 1 };+ });++ it('rejects install when the plugin is uninstalled during packaging (runtime 复核)', async () => {+ // F1:审阅时 alpha 已装(existing 存在),打包窗口内本地页把它卸载。+ // beforeCommit 的 runtime 复核必须发现 existing→缺失并拒,避免"更新"被+ // 静默降级成"首装 + 带电启用"。用 listSequence 让最后一次 list()(即+ // beforeCommit 内的复核)看到空,前面的 list() 都看到已装。+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ const pluginId = customMarketPluginId('team-lib', 'alpha');+ const reviewed = await h.service.detail(pluginId);+ const installedGhost = [+ { manifest: ghostManifest('alpha'), dir: path.join(dir, 'plugins', 'alpha'), enabled: true },+ ];+ // detail 之后开始计数:审阅路径的 list() 都看到已装,beforeCommit(最后一次)+ // 看到空——alpha 在打包窗口内被卸载。+ // 该路径共两次 list():#1 审阅算 existing(看到已装),#2 beforeCommit+ // 的 runtime 复核(看到空=打包窗口内被卸载)。+ const calls = { n: 0 };+ runtime.listSequence = () => {+ calls.n += 1;+ return calls.n >= 2 ? [] : installedGhost;+ };+ await expect(+ h.service.install(pluginId, {+ expectedReleaseId: reviewed.releaseId,+ expectedManifest: reviewed.manifest,+ }),+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(runtime.install).not.toHaveBeenCalled();+ });++ it('rejects listSources when the account switches during discovery', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);++ // listSources 异步发现 A 的目录;返回前会话漂移到 user-2 时必须拒绝,+ // 不得把 A 的私有 URL/本地路径摘要发给当前 Renderer。+ const listPromise = h.service.listSources();+ runtime.session = { mode: 'cloud', dataOwnerId: 'user-2', generation: 2 };+ await expect(listPromise).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ runtime.session = { mode: 'cloud', dataOwnerId: 'user-1', generation: 1 };+ });++ it('rejects the snapshot when listAll fails after an account switch', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);++ // listAll 因切号失败:catch 分支不能把按 user-1 发现的自定义项返回当前会话。+ h.api.listAll.mockImplementation(async () => {+ runtime.session = { mode: 'cloud', dataOwnerId: 'user-2', generation: 2 };+ throw new Error('session changed');+ });+ await expect(h.service.snapshot()).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ runtime.session = { mode: 'cloud', dataOwnerId: 'user-1', generation: 1 };+ });++ it('rejects refreshSource when the account switches during refresh', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);++ // 本地源刷新完成、返回 summary 前会话漂移:runForOwner 必须拒绝,+ // 不把含本地绝对路径的摘要发给当前 Renderer。+ const refreshPromise = h.service.refreshSource('team-lib');+ runtime.session = { mode: 'cloud', dataOwnerId: 'user-2', generation: 2 };+ await expect(refreshPromise).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ runtime.session = { mode: 'cloud', dataOwnerId: 'user-1', generation: 1 };+ });++ it('rejects custom detail when the account switches during discovery', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);++ // discoverSource 之后、返回 manifest 前会话漂移:必须拒绝,不把 A 的+ // 名称/作者/权限声明发给当前 Renderer。+ const detailPromise = h.service.detail(customMarketPluginId('team-lib', 'alpha'));+ runtime.session = { mode: 'cloud', dataOwnerId: 'user-2', generation: 2 };+ await expect(detailPromise).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ runtime.session = { mode: 'cloud', dataOwnerId: 'user-1', generation: 1 };+ });++ it('rejects install when another source already owns the ghostId', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ runtime.ghosts = [+ { manifest: ghostManifest('alpha'), dir: '/ghosts/alpha', enabled: true },+ ];+ // 服务端市场装过同 id 插件+ h.ledger.upsertInstallation({+ pluginId: PLUGIN_ID,+ ghostId: 'alpha',+ releaseId: 'release-1',+ version: '1.0.0',+ sha256: 'a'.repeat(64),+ scope: 'public',+ organizationId: null,+ source: 'market',+ installed: true,+ updatedAt: '2026-07-30T02:00:00.000Z',+ });++ const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));+ await expect(+ h.service.install(customMarketPluginId('team-lib', 'alpha'), {+ expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),+ expectedManifest: reviewed.manifest,+ }),+ ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });+ expect(runtime.install).not.toHaveBeenCalled();+ });++ it('rejects install when another custom source declares the same ghostId', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const rival = writeLocalMarket(root, 'rival-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [+ { name: 'team-lib', dir },+ { name: 'rival-lib', dir: rival },+ ]);++ // 两个来源声明同一 ghostId、本地尚无安装:列表把双方都标成 conflict 并禁用,+ // 安装入口必须用同一口径重算并拒绝,不能因为"本地还没装"就放行。+ const snapshot = await h.service.snapshot();+ expect(snapshot.items.map((item) => item.installState)).toEqual(['conflict', 'conflict']);++ const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));+ await expect(+ h.service.install(customMarketPluginId('team-lib', 'alpha'), {+ expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),+ expectedManifest: reviewed.manifest,+ }),+ ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });+ expect(runtime.install).not.toHaveBeenCalled();+ });++ it('rejects install when the server catalog declares the same ghostId', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'server-plugin' }]);+ const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);++ const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'server-plugin'));+ await expect(+ h.service.install(customMarketPluginId('team-lib', 'server-plugin'), {+ expectedReleaseId: customMarketReleaseId('team-lib', 'server-plugin', '1.0.0'),+ expectedManifest: reviewed.manifest,+ }),+ ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });+ expect(runtime.install).not.toHaveBeenCalled();+ });++ it('rejects installing a server plugin that a custom source also declares', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'server-plugin' }]);+ const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);+ const item = serverSummary();+ h.api.detail.mockResolvedValue(serverDetail());++ // 列表把两边都标成 conflict 并禁用;服务端安装入口只查服务端目录内部重名,+ // 必须用同一口径重算,否则普通 UI 流程或直接 IPC 都能装进来并抢占 ghostId。+ const snapshot = await h.service.snapshot();+ expect(+ snapshot.items.find((entry) => entry.sourceType === 'server')?.installState,+ ).toBe('conflict');++ await expect(+ h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),+ ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });+ expect(h.api.download).not.toHaveBeenCalled();+ });++ it('keeps the conflict state on the server detail view', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'server-plugin' }]);+ const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);+ h.api.detail.mockResolvedValue(serverDetail());++ // 详情传空重复集合会把 conflict 项恢复成可安装,给出绕过冲突闸的入口。+ const detail = await h.service.detail(serverSummary().id);+ expect(detail.installState).toBe('conflict');+ });++ it('skips defaultInstall when a custom source declares the same ghostId', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'server-plugin' }]);+ const h = harness([serverSummary({ defaultInstall: true })], [{ name: 'team-lib', dir }]);+ h.api.detail.mockResolvedValue(serverDetail());++ // 默认安装会真的下载并启用插件。若只按服务端目录判重,与自定义来源同 ghostId+ // 的默认项会被静默抢占所有权,而列表随后又把它标成 conflict —— 既定事实已经+ // 发生。冲突集合必须先于默认安装算出来。+ const snapshot = await h.service.snapshot();+ expect(h.api.download).not.toHaveBeenCalled();+ expect(runtime.install).not.toHaveBeenCalled();+ expect(+ snapshot.items.find((entry) => entry.sourceType === 'server')?.installState,+ ).toBe('conflict');+ });++ it('rechecks cross-source ownership right before committing the install', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const rivalDir = writeLocalMarket(root, 'rival-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ runtime.install.mockResolvedValue({+ manifest: ghostManifest('alpha'),+ dir: '/ghosts/alpha',+ enabled: true,+ });+ const pluginId = customMarketPluginId('team-lib', 'alpha');+ const reviewed = await h.service.detail(pluginId);++ // 竞争来源必须在**入口检查之后**才出现,否则被入口那次判定拦住,根本触不到+ // 提交点复核。打包是异步的、可以持续很久,期间另一窗口经独立的 market-sources+ // 互斥键添加了声明同一 ghostId 的来源 —— 用"第一次读取来源表之后才加进去"+ // 精确模拟这个时序。+ const rival: MarketSourceConfig = {+ name: 'rival-lib',+ addedAt: '2026-08-01T00:00:00.000Z',+ lastSyncedAt: '2026-08-01T00:00:00.000Z',+ lastRevision: null,+ source: { type: 'local', path: rivalDir },+ };+ const realList = MarketSourceStore.prototype.list;+ let reads = 0;+ const listSpy = vi+ .spyOn(MarketSourceStore.prototype, 'list')+ .mockImplementation(function (this: MarketSourceStore) {+ const configs = realList.call(this);+ reads += 1;+ return reads <= 1 ? configs : [...configs, rival];+ });++ try {+ await expect(+ h.service.install(pluginId, {+ expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),+ expectedManifest: reviewed.manifest,+ }),+ ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });+ // 关键:不能只是报错,而是必须在**改动 Ghost 运行时之前**就拒绝。+ expect(runtime.install).not.toHaveBeenCalled();+ expect(reads).toBeGreaterThan(1);+ } finally {+ listSpy.mockRestore();+ }+ });++ it('holds the source lock across the install commit so sources cannot interleave', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const rivalDir = writeLocalMarket(root, 'rival-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ const pluginId = customMarketPluginId('team-lib', 'alpha');+ const reviewed = await h.service.detail(pluginId);++ // 落位期间(installOrUpdateMarketGhostPackage 还在 await 包检查)另一窗口尝试+ // 添加声明同一 ghostId 的来源。提交段持有来源锁,这次 addSource 必须排在落位+ // 之后 —— 否则复核结论在真正落位前就过期了。+ let addSourceStarted = false;+ let installFinished = false;+ runtime.install.mockImplementation(async () => {+ await new Promise((resolve) => setTimeout(resolve, 60));+ installFinished = true;+ return { manifest: ghostManifest('alpha'), dir: '/ghosts/alpha', enabled: true };+ });++ const installing = h.service.install(pluginId, {+ expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),+ expectedManifest: reviewed.manifest,+ });+ // 等安装真正进入落位段再发起来源添加。+ await new Promise((resolve) => setTimeout(resolve, 20));+ const adding = h.service+ .addSource({ source: rivalDir })+ .then(() => {+ addSourceStarted = true;+ })+ .catch(() => {+ addSourceStarted = true;+ });++ await installing;+ // 落位完成时,来源添加还没被放行(它在锁后面排队)。+ expect(installFinished).toBe(true);+ expect(addSourceStarted).toBe(false);+ await adding;+ });++ it('denies a re-added same-name source with a different origin from owning the install', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ // 来源 B 与当初安装用的来源 A 市场名相同(marketplace.json 自报、可复用),+ // 但指向完全不同的目录。pluginId 因此完全相同,所有权必须由来源指纹裁决。+ const dirB = writeLocalMarket(root, 'team-lib', [+ { rel: 'plugins/alpha', id: 'alpha', version: '2.0.0' },+ ]);+ const h = harness([], [{ name: 'team-lib', dir: dirB }]);+ runtime.ghosts = [+ { manifest: ghostManifest('alpha', '1.0.0'), dir: '/ghosts/alpha', enabled: true },+ ];+ h.ledger.upsertInstallation({+ pluginId: customMarketPluginId('team-lib', 'alpha'),+ ghostId: 'alpha',+ releaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),+ version: '1.0.0',+ sha256: 'custom-unverified',+ scope: 'public',+ organizationId: null,+ source: 'local-market',+ installed: true,+ updatedAt: '2026-07-30T02:00:00.000Z',+ // 当初的安装来自另一个目录(来源 A)。+ sourceKey: marketSourceKey({ type: 'local', path: path.join(root, 'origin-a') }),+ });++ // 列表:同 pluginId 但指纹不符 → 不是所有者,如实标 conflict 而不是把+ // "无关仓库的 2.0.0"呈现成本插件的可用更新。+ const snapshot = await h.service.snapshot();+ expect(snapshot.items[0]?.installState).toBe('conflict');++ // 安装:同样被拒,恶意/无关仓库不能借同名市场"更新"别人装出来的插件。+ const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));+ await expect(+ h.service.install(customMarketPluginId('team-lib', 'alpha'), {+ expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '2.0.0'),+ expectedManifest: reviewed.manifest,+ }),+ ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });+ expect(runtime.install).not.toHaveBeenCalled();+ });++ it('rejects the install when the source vanishes before the commit point', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ const pluginId = customMarketPluginId('team-lib', 'alpha');+ const reviewed = await h.service.detail(pluginId);++ // 打包期间另一窗口移除了该来源(移除先拿 SOURCE_MUTATION_KEY 删配置,租约只+ // 保住目录字节)。用"入口发现之后 store.get 开始返回 null"精确模拟这个时序:+ // 提交点必须确认来源仍在,否则会装出一个没有对应来源的包并写孤儿账本记录。+ const realGet = MarketSourceStore.prototype.get;+ let gets = 0;+ const spy = vi+ .spyOn(MarketSourceStore.prototype, 'get')+ .mockImplementation(function (this: MarketSourceStore, name: string) {+ gets += 1;+ if (gets > 1) return null;+ return realGet.call(this, name);+ });+ try {+ await expect(+ h.service.install(pluginId, {+ expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),+ expectedManifest: reviewed.manifest,+ }),+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(runtime.install).not.toHaveBeenCalled();+ expect(gets).toBeGreaterThan(1);+ } finally {+ spy.mockRestore();+ }+ });++ it('does not let a stale custom record claim a locally replaced package', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [+ { rel: 'plugins/alpha', id: 'alpha', version: '2.0.0' },+ ]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ // 降级窗口:旧版卸载了本来源装的 A,又从本地 .cindy 装了同 ghostId 的 B。+ // 旧版不认识 custom 账本,记录原样留存(installed:true、指纹全对),唯一能+ // 分辨的是"运行时的 manifest 已不是安装时那份"。+ const replacedManifest = {+ ...ghostManifest('alpha', '1.0.0'),+ description: 'locally installed replacement',+ slots: ['notify', 'network'],+ };+ runtime.ghosts = [{ manifest: replacedManifest, dir: '/ghosts/alpha', enabled: true }];+ h.ledger.upsertInstallation({+ pluginId: customMarketPluginId('team-lib', 'alpha'),+ ghostId: 'alpha',+ releaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),+ version: '1.0.0',+ sha256: 'custom-unverified',+ scope: 'public',+ organizationId: null,+ source: 'local-market',+ installed: true,+ updatedAt: '2026-07-30T02:00:00.000Z',+ sourceKey: marketSourceKey({ type: 'local', path: dir }),+ // 摘要是**安装时那份 A** 的,不是替换后的 B 的。+ manifestDigest: ghostManifestDigest(ghostManifest('alpha', '1.0.0')),+ });++ // 列表:B 不归本来源所有,如实标 conflict,而不是把来源的 2.0.0 呈现成+ // "B 的可用更新"。+ const snapshot = await h.service.snapshot();+ expect(snapshot.items[0]?.installState).toBe('conflict');++ // 安装:同样被拒,来源的更新不能覆盖用户降级期间自己装的包。+ const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));+ await expect(+ h.service.install(customMarketPluginId('team-lib', 'alpha'), {+ expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '2.0.0'),+ expectedManifest: reviewed.manifest,+ }),+ ).rejects.toMatchObject({ code: 'ALREADY_EXISTS' });+ expect(runtime.install).not.toHaveBeenCalled();+ });++ it('masks failure details with a generation error when the account switches mid-operation', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ // 让操作在"开始之后"失败:来源目录消失 → refreshSource 在 operation 内抛+ // MARKET_SOURCE_INVALID。切号发生在 operation 已启动、错误尚未抛出之间——+ // 用 store.get 作时序钩子(refreshSource 第一步就是读配置)。+ const realGet = MarketSourceStore.prototype.get;+ const spy = vi+ .spyOn(MarketSourceStore.prototype, 'get')+ .mockImplementation(function (this: MarketSourceStore, name: string) {+ const config = realGet.call(this, name);+ fs.rmSync(dir, { recursive: true, force: true });+ runtime.session = { ...runtime.session, generation: runtime.session.generation + 1 };+ return config;+ });+ try {+ // 失败出口若不校验代际,git/discover 类错误的 detail(刻意保留仓库地址等+ // 上一账号私有信息)会被交给切号后的 Renderer。必须统一换成代际错误。+ await expect(h.service.refreshSource('team-lib')).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ });+ } finally {+ spy.mockRestore();+ }+ });++ it('skips default installs while any custom source is unreadable', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'other-plugin' }]);+ const h = harness([serverSummary({ defaultInstall: true })], [{ name: 'team-lib', dir }]);+ h.api.detail.mockResolvedValue(serverDetail());+ // 来源暂时不可读:合并冲突集合缺了它声明的 ghostId,此刻自动安装会在它恢复+ // 前抢占所有权——目录不完整时必须整体跳过默认安装。+ fs.rmSync(dir, { recursive: true, force: true });++ await h.service.snapshot();+ expect(h.api.download).not.toHaveBeenCalled();+ expect(runtime.install).not.toHaveBeenCalled();+ });++ it('skips default installs while a single plugin entry is temporarily unreadable', async () => {+ // 粒度到条目:来源本身可读、清单也在,只是**某个插件的 ghost.json** 因文件锁/+ // 权限/网络盘抖动暂时读不到。此前这类失败与"内容非法"共用静默跳过分支,目录+ // 仍被判 complete,同 ghostId 的默认安装会在这个窗口里抢占所有权,恢复后该+ // 插件永久 conflict。现在读取事实不明必须让目录判为不完整。+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ // 插件 id **刻意不与服务端 ghostId 相同**:否则"同 ghostId 重复"规则本身就会+ // 拦下默认安装,用例即使没有完整性闸也照样通过(咬不住)。+ const dir = writeLocalMarket(root, 'team-lib', [+ { rel: 'plugins/srv', id: 'unrelated-plugin' },+ ]);+ const h = harness([serverSummary({ defaultInstall: true })], [{ name: 'team-lib', dir }]);+ h.api.detail.mockResolvedValue(serverDetail());+ // EACCES 是可重试类错误(事实不明);注意不能用 ENOENT —— 那是"清单指向不存在+ // 的目录"这种永久错误,按内容非法跳过才对(否则这类市场永久阻塞默认安装)。+ // 路径必须按 realpath 拼:发现层用的是 realpath(macOS 上 /var → /private/var),+ // 用 mkdtemp 原样路径做匹配会让 mock 永不命中。+ const target = path.join(fs.realpathSync(dir), 'plugins', 'srv', 'ghost.json');+ const realOpen = fs.promises.open;+ const spy = vi.spyOn(fs.promises, 'open').mockImplementation((async (+ ...args: Parameters<typeof fs.promises.open>+ ) => {+ if (String(args[0]) === target) {+ throw Object.assign(new Error('EACCES'), { code: 'EACCES' });+ }+ return realOpen(...args);+ }) as typeof fs.promises.open);+ try {+ await h.service.snapshot();+ expect(h.api.download).not.toHaveBeenCalled();+ expect(runtime.install).not.toHaveBeenCalled();+ } finally {+ spy.mockRestore();+ }+ });++ it('still treats a missing plugin directory as invalid content (不阻塞默认安装)', async () => {+ // 对照组:marketplace.json 列了一个已被删掉的插件目录(ENOENT)是常见的**永久**+ // 错误。若把它也当"读取事实不明",这类市场会永久阻塞默认安装 —— 必须按内容+ // 非法跳过,默认安装照常进行。+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/gone', id: 'stale-entry' }]);+ fs.rmSync(path.join(dir, 'plugins', 'gone'), { recursive: true, force: true });+ const h = harness([serverSummary({ defaultInstall: true })], [{ name: 'team-lib', dir }]);+ h.api.detail.mockResolvedValue(serverDetail());++ await h.service.snapshot();+ // 与"不可读"组对称的信号:目录判为完整 → 默认安装照常进入下载阶段。+ expect(h.api.download).toHaveBeenCalled();+ });++ it('fails closed on manual installs while any custom source is unreadable', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/x', id: 'other-plugin' }]);+ const h = harness([serverSummary()], [{ name: 'team-lib', dir }]);+ h.api.detail.mockResolvedValue(serverDetail());+ fs.rmSync(dir, { recursive: true, force: true });++ const item = serverSummary();+ await expect(+ h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),+ ).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(h.api.download).not.toHaveBeenCalled();+ });++ it('adopts a matching install after a lost ledger write instead of dead-ending in conflict', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ // 场景:包已落位,但溯源账本因文件锁/磁盘错没写成——账本里没有记录。+ // 运行时内容与来源候选**完全一致**(同一份原始 ghost.json)。+ const installedDir = path.join(root, 'installed-alpha');+ fs.mkdirSync(installedDir, { recursive: true });+ fs.writeFileSync(path.join(installedDir, 'ghost.json'), JSON.stringify(ghostManifest('alpha')));+ runtime.ghosts = [{ manifest: ghostManifest('alpha'), dir: installedDir, enabled: true }];++ // 列表:不能标 conflict(UI 会禁用安装,用户连修复入口都没有);投影成可安装。+ const snapshot = await h.service.snapshot();+ expect(snapshot.items[0]?.installState).toBe('not-installed');++ // 安装 = 收养:完整重装 + 补写溯源,自愈完成。+ runtime.install.mockResolvedValue({+ manifest: ghostManifest('alpha'),+ dir: installedDir,+ enabled: true,+ });+ const reviewed = await h.service.detail(customMarketPluginId('team-lib', 'alpha'));+ await h.service.install(customMarketPluginId('team-lib', 'alpha'), {+ expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),+ expectedManifest: reviewed.manifest,+ });+ expect(h.ledger.installationForGhost('alpha')).toMatchObject({+ installed: true,+ source: 'local-market',+ });+ });++ it('adds a local source only through the native directory picker', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], []);++ // 用户取消:什么都不添加。+ pickerDialog.showOpenDialog.mockResolvedValueOnce({ canceled: true, filePaths: [] });+ await expect(h.service.addLocalSourceFromPicker(dir)).resolves.toEqual({ canceled: true });+ expect(h.sourceStore.list()).toEqual([]);++ // 用户在原生框选中目录:授权即选择结果,defaultPath 只是初始定位提示。+ pickerDialog.showOpenDialog.mockResolvedValueOnce({ canceled: false, filePaths: [dir] });+ const added = await h.service.addLocalSourceFromPicker('/somewhere/else');+ expect(added).toMatchObject({ canceled: false, summary: { name: 'team-lib' } });+ expect(h.sourceStore.list().map((config) => config.name)).toEqual(['team-lib']);+ });++ it('rejects the picker result when the account switched while it was open', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], []);+ // 原生选择器可以开着很久:打开期间切号,选完落盘会写进新账户的 store。+ pickerDialog.showOpenDialog.mockImplementationOnce(async () => {+ runtime.session = { ...runtime.session, generation: runtime.session.generation + 1 };+ return { canceled: false, filePaths: [dir] };+ });+ await expect(h.service.addLocalSourceFromPicker()).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ });+ expect(h.sourceStore.list()).toEqual([]);+ });++ it('uninstalls a custom market plugin through the shared uninstall path', async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-fixture-'));+ roots.push(root);+ const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);+ const h = harness([], [{ name: 'team-lib', dir }]);+ const pluginId = customMarketPluginId('team-lib', 'alpha');+ h.ledger.upsertInstallation({+ pluginId,+ ghostId: 'alpha',+ releaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),+ version: '1.0.0',+ sha256: 'custom-unverified',+ scope: 'public',+ organizationId: null,+ source: 'local-market',+ installed: true,+ updatedAt: '2026-07-30T02:00:00.000Z',+ });++ await expect(h.service.uninstall(pluginId)).resolves.toEqual({ ok: true });+ expect(runtime.uninstall).toHaveBeenCalledWith('alpha', { skipMarketLedger: true });+ expect(h.ledger.installationForGhost('alpha')?.installed).toBe(false);+ });++ it('结构守卫:service.ts 不允许出现按路径的 readFile/readFileSync', async () => {+ // 已安装目录同样可能被外部进程/同步盘改动,且摘要读取在每次市场快照都会+ // 执行;所有此类读取必须走 readBoundedFileNoFollow 系列(单句柄限量闸)。+ const source = await fs.promises.readFile(+ path.join(path.dirname(new URL(import.meta.url).pathname), '..', 'service.ts'),+ 'utf8',+ );+ expect(source).not.toMatch(/fs\.promises\.readFile\(/);+ expect(source).not.toMatch(/readFileSync\(/);+ expect(source).toMatch(/readBoundedFileNoFollowSync/);+ });+});diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 3f0c5256ed..2badcd2cfd 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -57,6 +57,7 @@ vi.mock('../download.js', () => ({import type { VisiblePluginDetail, VisiblePluginSummary } from '@cindy/plugin-protocol';+import { withGhostInstallLock } from '../../cindy-brain/ghostInstallLock';import { PluginMarketLedger } from '../ledger';import { PluginMarketService } from '../service';import type { PluginMarketApi } from '../api';@@ -64,6 +65,15 @@ import type { PluginMarketApi } from '../api';const roots: string[] = [];const PLUGIN_ID = `c${'a'.repeat(24)}`;+/** 手动可控 deferred,用于精确编排"安装在飞行中"的交错。 */+function deferred(): { promise: Promise<void>; resolve: () => void } {+ let resolve!: () => void;+ const promise = new Promise<void>((r) => {+ resolve = r;+ });+ return { promise, resolve };+}+afterEach(() => {runtime.ghosts = [];runtime.install.mockReset();@@ -269,6 +279,7 @@ describe('PluginMarketService migration and defaultInstall', () => {await expect(h.service.snapshot()).resolves.toEqual({items: [],unavailableReason: 'authentication-required',+ customSourceNames: [],});expect(h.api.listAll).not.toHaveBeenCalled();});@@ -285,6 +296,7 @@ describe('PluginMarketService migration and defaultInstall', () => {await expect(h.service.snapshot()).resolves.toEqual({items: [],unavailableReason: 'not-configured',+ customSourceNames: [],});expect(h.api.listAll).not.toHaveBeenCalled();});@@ -296,6 +308,7 @@ describe('PluginMarketService migration and defaultInstall', () => {await expect(h.service.snapshot()).resolves.toEqual({items: [],unavailableReason: 'session-switching',+ customSourceNames: [],});expect(h.api.listAll).not.toHaveBeenCalled();});@@ -466,6 +479,43 @@ describe('PluginMarketService migration and defaultInstall', () => {});});+ it('服务端安装持 ghostId 锁,覆盖落位到溯源写入整段', async () => {+ // 少了这把锁,本地 .cindy 装入能在包检查窗口里落入同 id 的包,随后被本次安装+ // 当作更新目标覆盖;账本写入若在锁外,本地装入还能插在"落位"与"写溯源"之间,+ // 让账本认领一个已被替换的包(服务端记录不带 manifestDigest,投影判不出来)。+ // 这里用真实的 withGhostInstallLock(service 直接 import,未被 mock)观察:+ // 安装在飞行中时,外部同 id 请求必须进不来;账本已写入后才放行。+ const item = summary();+ const h = harness([item]);+ const installGate = deferred();+ runtime.install.mockImplementation(async () => {+ await installGate.promise;+ return { manifest: manifest(), dir: '/userData/cindy-brain/cindy-test', enabled: true };+ });++ const order: string[] = [];+ const installing = h.service.install(item.id, {+ expectedReleaseId: item.currentRelease.id,+ });+ // 等安装推进到持锁并阻塞在 runtime.install 上。+ await vi.waitFor(() => expect(runtime.install).toHaveBeenCalled());+ const outsider = withGhostInstallLock(item.ghostId, async () => {+ // 进入临界区的那一刻,账本必须已经写完(写入在锁内)。+ order.push(+ h.ledger.installationForGhost(item.ghostId)?.installed === true+ ? 'outsider:ledger-written'+ : 'outsider:ledger-missing',+ );+ });+ await Promise.resolve();+ // 安装仍持锁(阻塞在落位上):外部同 id 请求不得进入。+ expect(order).toEqual([]);+ installGate.resolve();+ await Promise.all([installing, outsider]);+ // 进入时看到的是"账本已写",而不是"包已落位但溯源还没写"的中间态。+ expect(order).toEqual(['outsider:ledger-written']);+ });+it('rejects a non-public plugin returned to account-free local mode', async () => {runtime.session = {mode: 'local',@@ -496,6 +546,7 @@ describe('PluginMarketService migration and defaultInstall', () => {await expect(h.service.snapshot()).resolves.toEqual({items: [],unavailableReason: null,+ customSourceNames: [],});expect(h.api.listAll).toHaveBeenCalledOnce();});diff --git a/apps/desktop/src/main/plugin-market/__tests__/sources-cache-lease.test.ts b/apps/desktop/src/main/plugin-market/__tests__/sources-cache-lease.test.tsnew file mode 100644index 0000000000..b74f92e827--- /dev/null+++ b/apps/desktop/src/main/plugin-market/__tests__/sources-cache-lease.test.ts@@ -0,0 +1,217 @@+/**+ * 市场缓存删除的**结构门禁**。+ *+ * 这块反复出过七八轮同一类事故:每轮都是"又发现一个删除点没查租约"——交换旧+ * 目录、清理历史版本、清理暂存目录、移除来源、失败回滚,各自直接 `fs.rm`。行为+ * 用例只能覆盖已知的那几条路径;真正防止下一轮的是这里的两条约束:+ *+ * 1. `sources/index.ts` 不得出现任何直接的文件系统删除——所有删除必须经+ * `cacheLease.removeCachePath` 这个唯一入口。新增删除点会在这里失败。+ * 2. 守卫的判据是"路径重叠"(任一方向),因此整槽删、版本目录删、以及 git 的+ * `<dest>.staging-*` 兄弟目录都落在同一条规则里,不需要各自记得判断。+ */+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ isCachePathLeased,+ releaseCachePath,+ removeCachePath,+ resetCacheLeasesForTest,+ retainCachePath,+ settleCachePathRemovals,+ withCachePath,+} from '../sources/cacheLease';++const roots: string[] = [];++afterEach(() => {+ resetCacheLeasesForTest();+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });+});++function makeTree(): { root: string; slot: string; version: string; staging: string } {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-cache-lease-'));+ roots.push(root);+ const slot = path.join(root, 'slot');+ const version = path.join(slot, 'versions', 'v1');+ const staging = path.join(slot, 'incoming', 'job1');+ fs.mkdirSync(version, { recursive: true });+ fs.mkdirSync(`${staging}.staging-abc`, { recursive: true });+ fs.writeFileSync(path.join(version, 'file.txt'), 'content');+ return { root, slot, version, staging };+}++async function waitFor(predicate: () => boolean, attempts = 100): Promise<void> {+ for (let i = 0; i < attempts; i += 1) {+ if (predicate()) return;+ await new Promise((resolve) => setTimeout(resolve, 5));+ }+}++/** 给"推迟的删除"留出执行窗口,用于断言它**没有**发生。 */+async function settle(): Promise<void> {+ await new Promise((resolve) => setTimeout(resolve, 20));+}++describe('cacheLease 删除守卫', () => {+ it('deletes immediately when nothing is leased', async () => {+ const tree = makeTree();+ expect(await removeCachePath(tree.version)).toBe(true);+ expect(fs.existsSync(tree.version)).toBe(false);+ });++ it('defers deleting a leased path until the last lease is released', async () => {+ const tree = makeTree();+ retainCachePath(tree.version);+ expect(await removeCachePath(tree.version)).toBe(false);+ expect(fs.existsSync(tree.version)).toBe(true);++ releaseCachePath(tree.version);+ await waitFor(() => !fs.existsSync(tree.version));+ expect(fs.existsSync(tree.version)).toBe(false);+ });++ it('protects an ancestor delete while a descendant is leased (removeSource)', async () => {+ const tree = makeTree();+ await withCachePath(tree.version, async () => {+ // 整槽递归删:租约在目标之下,同样必须被挡住。+ expect(await removeCachePath(tree.slot)).toBe(false);+ expect(fs.readFileSync(path.join(tree.version, 'file.txt'), 'utf8')).toBe('content');+ });+ await waitFor(() => !fs.existsSync(tree.slot));+ expect(fs.existsSync(tree.slot)).toBe(false);+ });++ it('protects the git staging sibling of a leased staging dir', async () => {+ const tree = makeTree();+ const sibling = `${tree.staging}.staging-abc`;+ await withCachePath(tree.staging, async () => {+ // `<dest>.staging-<uuid>` 是兄弟目录而不是子目录,按路径分段比较盖不住它,+ // 守卫用字符串前缀判据才拦得下。+ expect(await removeCachePath(sibling)).toBe(false);+ expect(fs.existsSync(sibling)).toBe(true);+ });+ await waitFor(() => !fs.existsSync(sibling));+ expect(fs.existsSync(sibling)).toBe(false);+ });++ it('honours skipIf at execution time, not at scheduling time', async () => {+ const tree = makeTree();+ let stillCurrent = true;+ retainCachePath(tree.version);+ await removeCachePath(tree.version, { skipIf: () => stillCurrent });+ releaseCachePath(tree.version);+ // 推迟执行时条件仍然成立 → 放弃删除。+ await settle();+ expect(fs.existsSync(tree.version)).toBe(true);++ // 条件不再成立后重新排一次,这次真的删。+ stillCurrent = false;+ await removeCachePath(tree.version, { skipIf: () => stillCurrent });+ expect(fs.existsSync(tree.version)).toBe(false);+ });++ it('lets callers await an already-started removal before reusing the path', async () => {+ const tree = makeTree();+ // 让 rm 变慢,模拟"删除已经启动、还没跑完"这个窗口。skipIf 只挡得住尚未开始的+ // 删除;已经在跑的那笔必须能被复用方等到,否则它会落在刚重建出来的内容上。+ const realRm = fs.promises.rm;+ const spy = vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {+ await new Promise((resolve) => setTimeout(resolve, 40));+ return realRm(target as never, options as never);+ });+ try {+ retainCachePath(tree.version);+ await removeCachePath(tree.slot);+ releaseCachePath(tree.version); // 触发推迟删除:此刻它开始跑但没结束++ await settleCachePathRemovals(tree.slot);+ // 等到之后重建:内容不能再被那笔在途删除带走。+ fs.mkdirSync(tree.version, { recursive: true });+ fs.writeFileSync(path.join(tree.version, 'file.txt'), 'rebuilt');+ // 等待必须**长于**上面模拟的 rm 耗时(40ms),否则在途删除还没落地就断言完了,+ // 用例会在缺少 settleCachePathRemovals 时照样通过(没有牙齿)。+ await new Promise((resolve) => setTimeout(resolve, 150));+ expect(fs.readFileSync(path.join(tree.version, 'file.txt'), 'utf8')).toBe('rebuilt');+ } finally {+ spy.mockRestore();+ }+ });++ it('blocks a still-queued removal from starting while the path is leased for reuse', async () => {+ const tree = makeTree();+ // 场景:移除来源时旧安装仍持有版本租约 → 整槽删除进 deferred(尚未启动)。+ retainCachePath(tree.version);+ let configured = false;+ await removeCachePath(tree.slot, { skipIf: () => configured });++ // 复用方对整个槽持租约后再重建:此时 deferred 里那笔删除**启动不了**——+ // 只等 inFlight 是不够的,它当时还没开始跑。+ retainCachePath(tree.slot);+ releaseCachePath(tree.version); // 旧租约释放,但槽租约仍在+ fs.mkdirSync(tree.version, { recursive: true });+ fs.writeFileSync(path.join(tree.version, 'file.txt'), 'rebuilt');+ await settle();+ expect(fs.readFileSync(path.join(tree.version, 'file.txt'), 'utf8')).toBe('rebuilt');++ // 配置在释放槽租约之前写入 → 释放时 skipIf 直接否决那笔删除。+ configured = true;+ releaseCachePath(tree.slot);+ await settle();+ expect(fs.readFileSync(path.join(tree.version, 'file.txt'), 'utf8')).toBe('rebuilt');+ });++ it('counts nested leases so an inner release does not unblock deletion', async () => {+ const tree = makeTree();+ retainCachePath(tree.version);+ retainCachePath(tree.version);+ await removeCachePath(tree.version);++ releaseCachePath(tree.version);+ expect(isCachePathLeased(tree.version)).toBe(true);+ await settle();+ expect(fs.existsSync(tree.version)).toBe(true);++ releaseCachePath(tree.version);+ await waitFor(() => !fs.existsSync(tree.version));+ expect(fs.existsSync(tree.version)).toBe(false);+ });+});++describe('缓存删除收口(结构门禁)', () => {+ const sourcesDir = path.join(+ path.dirname(fileURLToPath(import.meta.url)),+ '..',+ 'sources',+ );+ // 容忍链式换行(fs.promises\n.rm(…)):否则漏数 cacheLease/git 的真实删除点。+ const countRawDeletions = (file: string): number =>+ [+ ...fs+ .readFileSync(path.join(sourcesDir, file), 'utf8')+ .matchAll(/fs\s*\.\s*(?:promises\s*\.\s*)?rm(?:Sync|dir)?\s*\(/g),+ ].length;++ // 门禁扩到整个 sources/,而不只 index.ts:任一 lease 管理的文件新增直接删除点+ // 就是又一个绕过租约守卫的口子——这正是此前每一轮返工的形态。+ it.each(['index.ts', 'store.ts', 'discover.ts', 'parse.ts', 'preflight.ts'])(+ 'sources/%s never deletes filesystem paths directly',+ (file) => {+ expect(countRawDeletions(file)).toBe(0);+ },+ );++ it('git.ts only deletes its own private clone staging, nothing else', () => {+ // git.ts 的唯一直接删除是它自己 clone 出的 `<dest>.staging-<uuid>` 私有目录+ // (UUID 私有、同函数内建同函数内删、从不被租约持有),是经过审阅的例外。+ // 断言"只删 stagingPath":出现任何删别的路径的调用都要重新确认边界。+ const git = fs.readFileSync(path.join(sourcesDir, 'git.ts'), 'utf8');+ const deletions = [...git.matchAll(/\.\s*rm(?:Sync|dir)?\s*\(\s*([A-Za-z]+)/g)].map((m) => m[1]);+ expect(deletions).toEqual(['stagingPath']);+ });+});diff --git a/apps/desktop/src/main/plugin-market/__tests__/sources-discover.test.ts b/apps/desktop/src/main/plugin-market/__tests__/sources-discover.test.tsnew file mode 100644index 0000000000..b6d93b5c74--- /dev/null+++ b/apps/desktop/src/main/plugin-market/__tests__/sources-discover.test.ts@@ -0,0 +1,372 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it, vi } from 'vitest';++import { discoverMarketplace } from '../sources/discover';++const roots: string[] = [];++afterEach(() => {+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });+});++function makeRoot(): string {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-discover-'));+ roots.push(root);+ return root;+}++function ghostJson(id: string, version = '1.0.0') {+ return JSON.stringify({+ schemaVersion: 2,+ id,+ name: `Plugin ${id}`,+ version,+ entry: 'main.js',+ slots: ['notify'],+ });+}++function writePlugin(root: string, rel: string, id: string, version = '1.0.0') {+ const dir = path.join(root, ...rel.split('/'));+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, 'ghost.json'), ghostJson(id, version));+ fs.writeFileSync(path.join(dir, 'main.js'), '// entry');+}++function writeManifest(root: string, manifest: unknown, rel = '.agents/plugins/marketplace.json') {+ const file = path.join(root, ...rel.split('/'));+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, typeof manifest === 'string' ? manifest : JSON.stringify(manifest));+}++describe('discoverMarketplace', () => {+ it('discovers plugins from the primary manifest location', async () => {+ const root = makeRoot();+ writePlugin(root, 'plugins/alpha', 'alpha');+ writePlugin(root, 'plugins/beta', 'beta', '2.0.0');+ writeManifest(root, {+ name: 'team-market',+ interface: { displayName: 'Team Market' },+ plugins: [{ name: 'alpha', source: './plugins/alpha' }, { name: 'beta', source: 'plugins/beta' }],+ });++ const result = await discoverMarketplace(root);+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.marketplace.name).toBe('team-market');+ expect(result.marketplace.displayName).toBe('Team Market');+ expect(result.marketplace.plugins.map((plugin) => plugin.ghostId)).toEqual([+ 'alpha',+ 'beta',+ ]);+ expect(result.marketplace.plugins[1]?.version).toBe('2.0.0');+ expect(result.marketplace.skippedCount).toBe(0);+ });++ it.each([+ '.claude-plugin/marketplace.json',+ '.cursor-plugin/marketplace.json',+ '.agents/plugins/api_marketplace.json',+ ])('falls back to the alternate manifest location %s', async (rel) => {+ const root = makeRoot();+ writePlugin(root, 'p', 'solo');+ writeManifest(root, { name: 'alt', plugins: [{ name: 'solo', source: 'p' }] }, rel);+ const result = await discoverMarketplace(root);+ expect(result.ok).toBe(true);+ if (result.ok) expect(result.marketplace.name).toBe('alt');+ });++ it('prefers the primary manifest when several locations exist', async () => {+ const root = makeRoot();+ writePlugin(root, 'p', 'solo');+ writeManifest(root, { name: 'primary', plugins: [] });+ writeManifest(root, { name: 'secondary', plugins: [] }, '.claude-plugin/marketplace.json');+ const result = await discoverMarketplace(root);+ expect(result.ok && result.marketplace.name).toBe('primary');+ });++ it('supports the object form of local sources', async () => {+ const root = makeRoot();+ writePlugin(root, 'p', 'solo');+ writeManifest(root, {+ name: 'obj',+ plugins: [{ name: 'solo', source: { source: 'local', path: 'p' } }],+ });+ const result = await discoverMarketplace(root);+ expect(result.ok && result.marketplace.plugins).toHaveLength(1);+ });++ it('reports a missing manifest distinctly from a malformed one', async () => {+ const empty = makeRoot();+ expect(await discoverMarketplace(empty)).toEqual({ ok: false, code: 'MARKET_MANIFEST_MISSING' });++ const malformed = makeRoot();+ writeManifest(malformed, '{ not json');+ const result = await discoverMarketplace(malformed);+ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.code).toBe('MARKET_SOURCE_INVALID');+ });++ it('skips unsupported remote plugin sources and invalid entries', async () => {+ const root = makeRoot();+ writePlugin(root, 'ok', 'good-one');+ writeManifest(root, {+ name: 'mixed',+ plugins: [+ { name: 'good', source: 'ok' },+ { name: 'remote', source: { source: 'url', url: 'https://x.test/r.git' } },+ { name: 'npm', source: { source: 'npm', package: '@x/y' } },+ { name: 'escapes', source: '../outside' },+ { name: 'absolute', source: '/etc/passwd' },+ { name: 'missing-ghost', source: 'nowhere' },+ 'not-an-object',+ ],+ });+ const result = await discoverMarketplace(root);+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.marketplace.plugins.map((plugin) => plugin.ghostId)).toEqual(['good-one']);+ expect(result.marketplace.skippedCount).toBe(6);+ });++ it('skips plugins whose directory symlinks escape the market root', async () => {+ const root = makeRoot();+ const outside = makeRoot();+ writePlugin(outside, 'escaped', 'escaped');+ writePlugin(root, 'plugins/good', 'good-one');+ fs.symlinkSync(outside, path.join(root, 'plugins', 'linked-out'), 'dir');+ writeManifest(root, {+ name: 'linked',+ plugins: [+ { name: 'good', source: 'plugins/good' },+ { name: 'escaped', source: 'plugins/linked-out/escaped' },+ ],+ });+ const result = await discoverMarketplace(root);+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.marketplace.plugins.map((plugin) => plugin.ghostId)).toEqual(['good-one']);+ expect(result.marketplace.skippedCount).toBe(1);+ });++ it('skips duplicate ghostIds keeping the first occurrence', async () => {+ const root = makeRoot();+ writePlugin(root, 'a', 'dup-id', '1.0.0');+ writePlugin(root, 'b', 'dup-id', '9.9.9');+ writeManifest(root, {+ name: 'dup',+ plugins: [{ name: 'a', source: 'a' }, { name: 'b', source: 'b' }],+ });+ const result = await discoverMarketplace(root);+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.marketplace.plugins).toHaveLength(1);+ expect(result.marketplace.plugins[0]?.version).toBe('1.0.0');+ });++ it('redacts host paths from the detail when the manifest cannot be resolved', async () => {+ const root = makeRoot();+ writeManifest(root, { name: 'lib', plugins: [] });+ // realpath 的 ENOENT/EACCES message 自带完整宿主路径;detail 会经 IPC 原样+ // 转发 Renderer,必须脱敏。用 mock 确定性地触发 catch 分支。+ const spy = vi.spyOn(fs.promises, 'realpath').mockRejectedValue(+ Object.assign(+ new Error("ENOENT: no such file or directory, realpath '/Users/alice/.config/secret'"),+ { code: 'ENOENT' },+ ),+ );+ try {+ const result = await discoverMarketplace(root);+ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(result.detail ?? '').not.toContain('alice');+ expect(result.detail ?? '').not.toContain('/Users/');+ // 仍保留可引导的原因文本。+ expect(result.detail ?? '').toContain('ENOENT');+ } finally {+ spy.mockRestore();+ }+ });++ it('rejects an oversized marketplace manifest instead of parsing it', async () => {+ const root = makeRoot();+ const file = path.join(root, '.agents', 'plugins', 'marketplace.json');+ fs.mkdirSync(path.dirname(file), { recursive: true });+ // 市场仓库是不受信内容:超大清单必须在 readFile 之前按大小拒绝,不能靠解析。+ fs.writeFileSync(file, `{"name":"big","plugins":[],"pad":"${'x'.repeat(1024 * 1024)}"}`);++ const result = await discoverMarketplace(root);+ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(result.detail).toContain('regular file within');+ });++ it('skips a plugin whose ghost.json is oversized without reading it', async () => {+ const root = makeRoot();+ writePlugin(root, 'plugins/good', 'good-one');+ const bigDir = path.join(root, 'plugins', 'big');+ fs.mkdirSync(bigDir, { recursive: true });+ fs.writeFileSync(+ path.join(bigDir, 'ghost.json'),+ `{"schemaVersion":2,"id":"big","pad":"${'x'.repeat(600 * 1024)}"}`,+ );+ writeManifest(root, {+ name: 'sized',+ plugins: [+ { name: 'good', source: 'plugins/good' },+ { name: 'big', source: 'plugins/big' },+ ],+ });++ // 关键断言是"没有去读":超大身份卡若被 readFile 进内存,拒绝就晚了(OOM 防护+ // 的意义就在读之前)。仅断言"被跳过"没有牙齿——解析/校验失败同样会跳过。+ const realReadFile = fs.promises.readFile;+ const readTargets: string[] = [];+ const spy = vi+ .spyOn(fs.promises, 'readFile')+ .mockImplementation(((target: unknown, ...rest: unknown[]) => {+ readTargets.push(String(target));+ return (realReadFile as (...args: unknown[]) => unknown)(target, ...rest);+ }) as typeof fs.promises.readFile);+ try {+ const result = await discoverMarketplace(root);+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.marketplace.plugins.map((plugin) => plugin.ghostId)).toEqual(['good-one']);+ expect(result.marketplace.skippedCount).toBe(1);+ expect(readTargets.some((target) => target.includes(path.join('big', 'ghost.json')))).toBe(+ false,+ );+ } finally {+ spy.mockRestore();+ }+ });++ it('rejects a manifest that lists an absurd number of plugin entries', async () => {+ const root = makeRoot();+ // 每个条目都触发 realpath + 读身份卡:十万条目能把快照/列表/刷新拖死。+ writeManifest(root, {+ name: 'flood',+ plugins: Array.from({ length: 513 }, (_, index) => ({+ name: `p${index}`,+ source: `plugins/p${index}`,+ })),+ });+ const result = await discoverMarketplace(root);+ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(result.detail).toContain('more than');+ });++ it('rejects marketplace names that are oversized or carry control characters', async () => {+ for (const name of ['x'.repeat(129), 'evilname', 'line\nbreak']) {+ const root = makeRoot();+ writeManifest(root, { name, plugins: [] });+ const result = await discoverMarketplace(root);+ expect(result.ok).toBe(false);+ }+ // 合法边界值仍然接受。+ const root = makeRoot();+ writeManifest(root, { name: 'x'.repeat(128), plugins: [] });+ expect((await discoverMarketplace(root)).ok).toBe(true);+ });++ it('drops an invalid displayName instead of failing the market', async () => {+ const root = makeRoot();+ writeManifest(root, {+ name: 'lib',+ interface: { displayName: 'baddisplay' },+ plugins: [],+ });+ const result = await discoverMarketplace(root);+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.marketplace.displayName).toBeNull();+ });++ it('skips a plugin whose ghost.json is a symlink, even to a valid manifest outside', async () => {+ const root = makeRoot();+ const outside = makeRoot();+ // 市场外放一份**内容完全合法**的身份卡:只断言"被跳过"才有区分度——+ // 若 lstat 闸退回 stat,这份外部身份卡会被解析并投影给 Renderer。+ // (/dev/zero 一类特殊文件是同一漏洞的 DoS 形态:stat.size 为 0 绕过大小闸+ // 后 readFile 无限读;lstat 拒掉 symlink 本身,两种形态一起堵死。)+ const target = path.join(outside, 'stolen-ghost.json');+ fs.writeFileSync(target, ghostJson('stolen'));+ writePlugin(root, 'plugins/good', 'good-one');+ const evilDir = path.join(root, 'plugins', 'evil');+ fs.mkdirSync(evilDir, { recursive: true });+ fs.writeFileSync(path.join(evilDir, 'main.js'), '// entry');+ fs.symlinkSync(target, path.join(evilDir, 'ghost.json'));+ writeManifest(root, {+ name: 'linked-card',+ plugins: [+ { name: 'good', source: 'plugins/good' },+ { name: 'evil', source: 'plugins/evil' },+ ],+ });++ const result = await discoverMarketplace(root);+ expect(result.ok).toBe(true);+ if (!result.ok) return;+ expect(result.marketplace.plugins.map((plugin) => plugin.ghostId)).toEqual(['good-one']);+ expect(result.marketplace.skippedCount).toBe(1);+ });++ it('validates and reads ghost.json through one file handle, never by pathname', async () => {+ const root = makeRoot();+ writePlugin(root, 'plugins/good', 'good-one');+ writeManifest(root, { name: 'lib', plugins: [{ name: 'good', source: 'plugins/good' }] });++ // 校验与读取必须共用同一句柄:路径式 lstat/readFile 是两次独立打开,并发方+ // 可以在两次之间把身份卡换成超大文件或设备链接。此断言防止退回两段式实现。+ const pathReads: string[] = [];+ const realRead = fs.promises.readFile;+ const readSpy = vi+ .spyOn(fs.promises, 'readFile')+ .mockImplementation(((target: unknown, ...rest: unknown[]) => {+ pathReads.push(String(target));+ return (realRead as (...args: unknown[]) => unknown)(target, ...rest);+ }) as typeof fs.promises.readFile);+ const lstatSpy = vi.spyOn(fs.promises, 'lstat');+ try {+ const result = await discoverMarketplace(root);+ expect(result.ok).toBe(true);+ expect(pathReads.some((target) => target.endsWith('ghost.json'))).toBe(false);+ expect(+ lstatSpy.mock.calls.some((call) => String(call[0]).endsWith('ghost.json')),+ ).toBe(false);+ } finally {+ readSpy.mockRestore();+ lstatSpy.mockRestore();+ }+ });++ it('rejects a manifest whose real path escapes the market root', async () => {+ const root = makeRoot();+ const outside = makeRoot();+ // 恶意市场把清单做成指向根目录外的 symlink,借宿主之手读任意路径。+ const secret = path.join(outside, 'secret.json');+ fs.writeFileSync(secret, JSON.stringify({ name: 'stolen', plugins: [] }));+ fs.mkdirSync(path.join(root, '.agents', 'plugins'), { recursive: true });+ fs.symlinkSync(secret, path.join(root, '.agents', 'plugins', 'marketplace.json'));++ const result = await discoverMarketplace(root);+ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(result.code).toBe('MARKET_SOURCE_INVALID');+ });++ it('rejects manifests without a name or with a non-array plugins field', async () => {+ const root = makeRoot();+ writeManifest(root, { plugins: [] });+ expect((await discoverMarketplace(root)).ok).toBe(false);++ const root2 = makeRoot();+ writeManifest(root2, { name: 'x', plugins: {} });+ expect((await discoverMarketplace(root2)).ok).toBe(false);+ });+});diff --git a/apps/desktop/src/main/plugin-market/__tests__/sources-git.test.ts b/apps/desktop/src/main/plugin-market/__tests__/sources-git.test.tsnew file mode 100644index 0000000000..1389c558c2--- /dev/null+++ b/apps/desktop/src/main/plugin-market/__tests__/sources-git.test.ts@@ -0,0 +1,262 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ classifyGitFailure,+ cloneMarketplace,+ fetchMarketplace,+ gitVersion,+ isGitVersionSupported,+ type GitExecutor,+} from '../sources/git';+import { checkGitPreflight } from '../sources/preflight';++const roots: string[] = [];++afterEach(() => {+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });+});++function destPath(): string {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-git-'));+ roots.push(root);+ return path.join(root, 'clone');+}++/** 记录调用并按需造出克隆目录的假执行器。 */+function fakeExecutor(+ handler?: (args: readonly string[], cwd?: string) => { stdout?: string; stderr?: string },+): { executor: GitExecutor; calls: Array<{ args: readonly string[]; cwd?: string }> } {+ const calls: Array<{ args: readonly string[]; cwd?: string }> = [];+ const executor: GitExecutor = async (args, options) => {+ calls.push({ args, ...(options.cwd ? { cwd: options.cwd } : {}) });+ if (args[0] === 'clone') {+ fs.mkdirSync(String(args[args.length - 1]), { recursive: true });+ }+ const result = handler?.(args, options.cwd) ?? {};+ return { stdout: result.stdout ?? '', stderr: result.stderr ?? '' };+ };+ return { executor, calls };+}++describe('cloneMarketplace', () => {+ it('clones plainly without ref or sparse paths', async () => {+ const { executor, calls } = fakeExecutor((_args) => ({ stdout: 'abc123\n' }));+ const dest = destPath();+ const revision = await cloneMarketplace(+ { url: 'https://x.test/r.git', sparsePaths: [] },+ dest,+ executor,+ );+ expect(calls[0]?.args.slice(0, 1)).toEqual(['clone']);+ expect(calls[0]?.args).not.toContain('--filter=blob:none');+ expect(calls[0]?.args).not.toContain('--branch');+ expect(revision).toBe('abc123');+ expect(fs.existsSync(dest)).toBe(true);+ });++ it('checks out the requested ref after a plain clone', async () => {+ const { executor, calls } = fakeExecutor(() => ({ stdout: 'abc123\n' }));+ await cloneMarketplace(+ { url: 'https://x.test/r.git', ref: 'v1.2', sparsePaths: [] },+ destPath(),+ executor,+ );+ expect(calls[0]?.args).toEqual(expect.arrayContaining(['clone']));+ expect(calls[0]?.args).not.toContain('--branch');+ // --detach 消歧:防 ref 与仓库内同名文件把 checkout 变成路径检出。+ expect(calls[1]?.args).toEqual(['checkout', '--detach', 'v1.2']);+ });++ it('uses blobless clone + sparse-checkout when sparse paths are given', async () => {+ const { executor, calls } = fakeExecutor(() => ({ stdout: 'abc123\n' }));+ await cloneMarketplace(+ { url: 'https://x.test/r.git', ref: 'main', sparsePaths: ['plugins/a', 'plugins/b'] },+ destPath(),+ executor,+ );+ expect(calls[0]?.args).toContain('--filter=blob:none');+ expect(calls[0]?.args).toContain('--no-checkout');+ expect(calls[1]?.args).toEqual(['sparse-checkout', 'set', '--', 'plugins/a', 'plugins/b']);+ expect(calls[2]?.args).toEqual(['checkout', '--detach', 'main']);+ });++ it('checks out the default branch for sparse clones without an explicit ref', async () => {+ const { executor, calls } = fakeExecutor((args) =>+ args[0] === 'symbolic-ref' ? { stdout: 'origin/trunk\n' } : { stdout: 'abc123\n' },+ );+ await cloneMarketplace(+ { url: 'https://x.test/r.git', sparsePaths: ['plugins/a'] },+ destPath(),+ executor,+ );+ // 必须 checkout 真实分支:`checkout HEAD` 会留下 detached HEAD,后续刷新的+ // `git pull --ff-only` 稳定失败,每次刷新都退化成整仓重克隆。+ expect(calls.map((call) => call.args[0])).toContain('symbolic-ref');+ expect(calls.some((call) => call.args[0] === 'checkout' && call.args[1] === 'trunk')).toBe(true);+ expect(calls.some((call) => call.args[0] === 'checkout' && call.args[1] === 'HEAD')).toBe(false);+ });++ it('falls back to HEAD when the default branch cannot be resolved', async () => {+ const { executor, calls } = fakeExecutor((args) => {+ if (args[0] === 'symbolic-ref') throw new Error('no origin/HEAD');+ return { stdout: 'abc123\n' };+ });+ await cloneMarketplace(+ { url: 'https://x.test/r.git', sparsePaths: ['plugins/a'] },+ destPath(),+ executor,+ );+ expect(calls.some((call) => call.args[0] === 'checkout' && call.args[1] === 'HEAD')).toBe(true);+ });++ it('cleans the staging directory and classifies auth failures', async () => {+ const { executor } = fakeExecutor(() => {+ throw Object.assign(new Error('fatal: Authentication failed'), {+ stderr: 'fatal: Authentication failed',+ });+ });+ const dest = destPath();+ await expect(+ cloneMarketplace({ url: 'https://x.test/r.git', sparsePaths: [] }, dest, executor),+ ).rejects.toMatchObject({ code: 'MARKET_CLONE_AUTH_FAILED' });+ expect(fs.readdirSync(path.dirname(dest)).filter((n) => n.includes('staging'))).toEqual([]);+ });+});++describe('fetchMarketplace', () => {+ it('pulls fast-forward when no ref is pinned', async () => {+ const { executor, calls } = fakeExecutor(() => ({ stdout: 'def456\n' }));+ const dir = destPath();+ fs.mkdirSync(dir, { recursive: true });+ const revision = await fetchMarketplace(dir, undefined, executor);+ expect(calls.map((call) => call.args[0])).toEqual(['pull', 'rev-parse']);+ expect(calls[0]?.args).toContain('--ff-only');+ expect(revision).toBe('def456');+ });++ it('resets to FETCH_HEAD when a ref is pinned', async () => {+ const { executor, calls } = fakeExecutor(() => ({ stdout: 'def456\n' }));+ const dir = destPath();+ fs.mkdirSync(dir, { recursive: true });+ await fetchMarketplace(dir, 'v1.2', executor);+ expect(calls.map((call) => call.args[0])).toEqual(['fetch', 'reset', 'rev-parse']);+ expect(calls[1]?.args).toEqual(['reset', '--hard', 'FETCH_HEAD']);+ });+});++describe('git environment', () => {+ it('parses git versions and enforces the sparse-checkout floor', async () => {+ const { executor } = fakeExecutor(() => ({ stdout: 'git version 2.43.0\n' }));+ expect(await gitVersion(executor)).toEqual({ major: 2, minor: 43 });+ expect(isGitVersionSupported({ major: 2, minor: 25 })).toBe(true);+ expect(isGitVersionSupported({ major: 2, minor: 24 })).toBe(false);+ expect(isGitVersionSupported({ major: 3, minor: 0 })).toBe(true);+ });++ it('preflight fails closed when git cannot execute', async () => {+ const executor: GitExecutor = async () => {+ throw new Error('spawn git ENOENT');+ };+ expect(await checkGitPreflight(executor)).toEqual({ ok: false, version: null });+ });++ it('preflight reports versions below the floor', async () => {+ const { executor } = fakeExecutor(() => ({ stdout: 'git version 2.20.1\n' }));+ expect(await checkGitPreflight(executor)).toEqual({ ok: false, version: '2.20' });+ });+});++describe('classifyGitFailure', () => {+ it.each([+ 'fatal: Authentication failed',+ 'fatal: could not read Username for https://github.com: terminal prompts disabled',+ 'ERROR: Repository not found.',+ '[email protected]: Permission denied (publickey).',+ // SSH 无权限的标准英文输出(LC_ALL=C 保证不被本地化文案绕过)+ 'fatal: Could not read from remote repository.\nPlease make sure you have the correct access rights',+ // 组织强制 SAML SSO、SSH key 未授权该组织+ "ERROR: The 'acme' organization has enabled or enforced SAML SSO.",+ ])('classifies %s as an auth failure', (message) => {+ expect(classifyGitFailure(new Error(message)).code).toBe('MARKET_CLONE_AUTH_FAILED');+ });++ it.each([+ 'fatal: Remote branch main not found in upstream origin',+ "fatal: couldn't find remote ref v9.9",+ ])('classifies %s as a missing ref', (message) => {+ expect(classifyGitFailure(new Error(message)).code).toBe('MARKET_REF_NOT_FOUND');+ });++ it('classifies other failures as generic clone failures', () => {+ expect(classifyGitFailure(new Error('Could not resolve host')).code).toBe(+ 'MARKET_CLONE_FAILED',+ );+ });++ it('redacts host paths and embedded credentials from the renderer-facing detail', () => {+ // OpenSSH / credential helper / 杀毒钩子都会往 stderr 写宿主绝对路径;+ // 用户名与宿主目录结构不该经 IPC 到达 Renderer(完整原文只留 main 日志)。+ const stderr = [+ 'Warning: Identity file /Users/alice/.ssh/id_market not accessible.',+ 'error: cannot run C:\\Users\\alice\\AppData\\git-credential.exe',+ 'hint: see ~/.gitconfig for details',+ 'fatal: could not read Username for https://bob:[email protected]',+ // 两段的短路径同样带用户名与目录结构,不能因为"段数不够"漏掉。+ 'error: chdir /home/alice failed',+ 'warning: cannot write /tmp/agent-sock',+ ].join('\n');+ const detail = classifyGitFailure(Object.assign(new Error('boom'), { stderr })).message;++ expect(detail).not.toContain('alice');+ expect(detail).not.toContain('/Users/');+ expect(detail).not.toContain('C:\\Users');+ expect(detail).not.toContain('~/.gitconfig');+ expect(detail).not.toContain('s3cr3t');+ expect(detail).not.toContain('/home/');+ expect(detail).not.toContain('/tmp/');+ // 仍要保留可引导的原因文本。+ expect(detail).toContain('Identity file');+ expect(detail).toContain('could not read Username');+ });++ it('keeps the repository URL readable while redacting host paths', () => {+ const stderr = 'fatal: repository https://github.com/org/repo.git not found (/home/bob/.gitconfig)';+ const detail = classifyGitFailure(Object.assign(new Error('boom'), { stderr })).message;+ // 仓库地址是用户自己输入的,要留着给他定位问题;宿主路径必须抹掉。+ expect(detail).toContain('https://github.com/org/repo.git');+ expect(detail).not.toContain('/home/bob');+ });++ it('keeps the marketplace placeholder for known internal cache paths', () => {+ const stderr = 'fatal: destination path /tmp/cache/slot/incoming/job already exists';+ const detail = classifyGitFailure(+ Object.assign(new Error('boom'), { stderr }),+ ['/tmp/cache/slot/incoming/job'],+ ).message;+ expect(detail).toContain('<marketplace>');+ });++ it('masks single-segment userinfo token in URLs (insteadOf 重写场景)', () => {+ // ~/.gitconfig 的 url.https://<token>@github.com/.insteadOf 会让 git 把+ // 带 token 的 URL 回显到 stderr;user:pass 规则盖不住无冒号的单段 token。+ const stderr = "fatal: unable to access 'https://[email protected]/o/r.git/'";+ const detail = classifyGitFailure(Object.assign(new Error('boom'), { stderr })).message;+ expect(detail).not.toContain('ghp_SUPERSECRET');+ expect(detail).toContain('***@');+ // host 与路径保留给用户定位。+ expect(detail).toContain('github.com/o/r.git');+ });++ it('strips control/bidi chars remote can echo into stderr', () => {+ // 自建 git 服务可在 remote: 文案里塞 U+202E 做错误区文案欺骗。+ const stderr = 'remote: denied hctlibgtnetnoc\nfatal: unable to access repo';+ const detail = classifyGitFailure(Object.assign(new Error('boom'), { stderr })).message;+ expect(detail).not.toMatch(/[--]/);+ // 换行保留(可读性)。+ expect(detail).toContain('\n');+ });+});diff --git a/apps/desktop/src/main/plugin-market/__tests__/sources-manager.test.ts b/apps/desktop/src/main/plugin-market/__tests__/sources-manager.test.tsnew file mode 100644index 0000000000..efacfa4fc6--- /dev/null+++ b/apps/desktop/src/main/plugin-market/__tests__/sources-manager.test.ts@@ -0,0 +1,818 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it, vi } from 'vitest';++import { MarketSourceManager, marketCloneSlug } from '../sources/index';+import type { GitExecutor } from '../sources/git';+import { releaseCachePath, retainCachePath } from '../sources/cacheLease';+import { MarketSourceStore } from '../sources/store';++const roots: string[] = [];++afterEach(() => {+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });+});++/** 等待推迟清理这类"引用释放后异步执行"的副作用落地。 */+async function waitFor(predicate: () => boolean, attempts = 100): Promise<void> {+ for (let i = 0; i < attempts; i += 1) {+ if (predicate()) return;+ await new Promise((resolve) => setTimeout(resolve, 5));+ }+}++function makeRoot(): string {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-manager-'));+ roots.push(root);+ return root;+}++function writeMarketplace(dir: string, name: string, plugins: Array<{ rel: string; id: string }>) {+ for (const plugin of plugins) {+ const pluginDir = path.join(dir, ...plugin.rel.split('/'));+ fs.mkdirSync(pluginDir, { recursive: true });+ fs.writeFileSync(+ path.join(pluginDir, 'ghost.json'),+ JSON.stringify({ schemaVersion: 2, id: plugin.id, name: `Plugin ${plugin.id}`, version: '1.0.0', entry: 'main.js', slots: ['notify'] }),+ );+ fs.writeFileSync(path.join(pluginDir, 'main.js'), '// entry');+ }+ const manifestDir = path.join(dir, '.agents', 'plugins');+ fs.mkdirSync(manifestDir, { recursive: true });+ fs.writeFileSync(+ path.join(manifestDir, 'marketplace.json'),+ JSON.stringify({+ name,+ plugins: plugins.map((plugin) => ({ name: plugin.id, source: plugin.rel })),+ }),+ );+}++function makeManager(root: string, gitExecutor?: GitExecutor) {+ return new MarketSourceManager({+ store: new MarketSourceStore(path.join(root, 'sources.v1.json')),+ cloneRoot: path.join(root, 'sources'),+ homeDir: root,+ ...(gitExecutor ? { gitExecutor } : {}),+ });+}++/** Git 假执行器:版本探测通过,clone 时向目标目录写入一个市场夹具。 */+function fakeGit(marketName: string, plugins: Array<{ rel: string; id: string }>) {+ const calls: string[][] = [];+ const executor: GitExecutor = async (args) => {+ calls.push([...args]);+ if (args[0] === '--version') return { stdout: 'git version 2.43.0\n', stderr: '' };+ if (args[0] === 'clone') {+ const dest = String(args[args.length - 1]);+ writeMarketplace(dest, marketName, plugins);+ return { stdout: '', stderr: '' };+ }+ if (args[0] === 'rev-parse') return { stdout: 'abc123\n', stderr: '' };+ return { stdout: '', stderr: '' };+ };+ return { executor, calls };+}++describe('MarketSourceManager local sources', () => {+ it('adds a local marketplace and lists it with the plugin count', async () => {+ const root = makeRoot();+ const market = path.join(root, 'my-market');+ writeMarketplace(market, 'local-lib', [{ rel: 'plugins/a', id: 'alpha' }]);+ const manager = makeManager(root);++ const added = await manager.addSource({ source: market });+ expect(added).toMatchObject({+ name: 'local-lib',+ pluginCount: 1,+ status: 'ok',+ });+ expect(added.source).toEqual({ type: 'local', path: market });++ const list = await manager.listSources();+ expect(list).toHaveLength(1);+ expect(list[0]?.name).toBe('local-lib');+ });++ it('rejects a local source that is not a directory', async () => {+ const manager = makeManager(makeRoot());+ await expect(+ manager.addSource({ source: path.join(makeRoot(), 'missing') }),+ ).rejects.toMatchObject({ code: 'MARKET_SOURCE_INVALID' });+ });++ it('rejects duplicate sources and duplicate marketplace names', async () => {+ const root = makeRoot();+ const market = path.join(root, 'my-market');+ writeMarketplace(market, 'local-lib', []);+ const manager = makeManager(root);++ await manager.addSource({ source: market });+ await expect(manager.addSource({ source: market })).rejects.toMatchObject({+ code: 'ALREADY_EXISTS',+ });++ const other = path.join(root, 'other-market');+ writeMarketplace(other, 'local-lib', []);+ await expect(manager.addSource({ source: other })).rejects.toMatchObject({+ code: 'ALREADY_EXISTS',+ });+ });++ it('removes sources and keeps local directories untouched', async () => {+ const root = makeRoot();+ const market = path.join(root, 'my-market');+ writeMarketplace(market, 'local-lib', []);+ const manager = makeManager(root);++ await manager.addSource({ source: market });+ await expect(manager.removeSource('local-lib')).resolves.toEqual({ ok: true });+ expect(await manager.listSources()).toEqual([]);+ expect(fs.existsSync(path.join(market, '.agents', 'plugins', 'marketplace.json'))).toBe(true);+ await expect(manager.removeSource('local-lib')).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });++ it('marks sources with vanished roots as errors in the list view', async () => {+ const root = makeRoot();+ const market = path.join(root, 'my-market');+ writeMarketplace(market, 'local-lib', [{ rel: 'p', id: 'alpha' }]);+ const manager = makeManager(root);+ await manager.addSource({ source: market });++ fs.rmSync(market, { recursive: true, force: true });+ const list = await manager.listSources();+ expect(list[0]?.status).toBe('error');+ expect(list[0]?.errorCode).toBe('MARKET_SOURCE_INVALID');+ });++ it('refreshes local sources by rescanning the manifest', async () => {+ const root = makeRoot();+ const market = path.join(root, 'my-market');+ writeMarketplace(market, 'local-lib', []);+ const manager = makeManager(root);+ await manager.addSource({ source: market });++ writeMarketplace(market, 'local-lib', [{ rel: 'p', id: 'alpha' }]);+ const refreshed = await manager.refreshSource('local-lib');+ expect(refreshed.pluginCount).toBe(1);+ expect(refreshed.lastSyncedAt).not.toBeNull();+ });+});++describe('MarketSourceManager git sources', () => {+ it('clones into the derived cache directory on add', async () => {+ const root = makeRoot();+ const { executor } = fakeGit('hub', [{ rel: 'plugins/a', id: 'alpha' }]);+ const manager = makeManager(root, executor);++ const added = await manager.addSource({ source: 'openai/plugins' });+ expect(added).toMatchObject({ name: 'hub', pluginCount: 1, lastRevision: 'abc123' });++ const slot = path.join(+ root,+ 'sources',+ marketCloneSlug('hub', {+ type: 'git',+ url: 'https://github.com/openai/plugins.git',+ sparsePaths: [],+ }),+ );+ const pointer = fs.readFileSync(path.join(slot, 'current'), 'utf8').trim();+ expect(fs.existsSync(path.join(slot, 'versions', pointer, '.agents', 'plugins', 'marketplace.json'))).toBe(true);+ // 临时 incoming 目录不残留+ expect(+ fs.readdirSync(path.join(root, 'sources')).filter((name) => name.startsWith('.incoming')),+ ).toEqual([]);+ });++ it('blocks git sources when git is unavailable', async () => {+ const root = makeRoot();+ const executor: GitExecutor = async () => {+ throw new Error('spawn git ENOENT');+ };+ const manager = makeManager(root, executor);+ await expect(manager.addSource({ source: 'openai/plugins' })).rejects.toMatchObject({+ code: 'MARKET_GIT_UNAVAILABLE',+ });+ expect(await manager.listSources()).toEqual([]);+ });++ it('rolls back the clone when the marketplace name conflicts', async () => {+ const root = makeRoot();+ const local = path.join(root, 'local-market');+ writeMarketplace(local, 'hub', []);+ const { executor } = fakeGit('hub', []);+ const manager = makeManager(root, executor);++ await manager.addSource({ source: local });+ await expect(manager.addSource({ source: 'openai/plugins' })).rejects.toMatchObject({+ code: 'ALREADY_EXISTS',+ });+ expect(fs.readdirSync(path.join(root, 'sources'))).toEqual([]);+ });++ it('removes the clone cache when the source is removed', async () => {+ const root = makeRoot();+ const { executor } = fakeGit('hub', []);+ const manager = makeManager(root, executor);+ await manager.addSource({ source: 'openai/plugins' });++ const cloneDir = path.join(+ root,+ 'sources',+ marketCloneSlug('hub', {+ type: 'git',+ url: 'https://github.com/openai/plugins.git',+ sparsePaths: [],+ }),+ );+ expect(fs.existsSync(cloneDir)).toBe(true);+ await manager.removeSource('hub');+ expect(fs.existsSync(cloneDir)).toBe(false);+ });++ it('re-clones when fast-forward refresh fails', async () => {+ const root = makeRoot();+ let failFetch = false;+ const executor: GitExecutor = async (args) => {+ if (args[0] === '--version') return { stdout: 'git version 2.43.0\n', stderr: '' };+ if (args[0] === 'clone') {+ writeMarketplace(String(args[args.length - 1]), 'hub', [{ rel: 'p', id: 'alpha' }]);+ return { stdout: '', stderr: '' };+ }+ if (args[0] === 'pull' || args[0] === 'fetch') {+ if (failFetch) throw Object.assign(new Error('rejected'), { stderr: 'non-fast-forward' });+ return { stdout: '', stderr: '' };+ }+ if (args[0] === 'rev-parse') return { stdout: 'def456\n', stderr: '' };+ return { stdout: '', stderr: '' };+ };+ const manager = makeManager(root, executor);+ await manager.addSource({ source: 'openai/plugins' });++ failFetch = true;+ const refreshed = await manager.refreshSource('hub');+ expect(refreshed.lastRevision).toBe('def456');+ expect(refreshed.pluginCount).toBe(1);+ });++ it('keeps the previous cache when the fast-forwarded marketplace content is invalid', async () => {+ const root = makeRoot();+ const executor: GitExecutor = async (args, opts) => {+ if (args[0] === '--version') return { stdout: 'git version 2.43.0\n', stderr: '' };+ if (args[0] === 'clone') {+ writeMarketplace(String(args[args.length - 1]), 'hub', [{ rel: 'p', id: 'alpha' }]);+ return { stdout: '', stderr: '' };+ }+ if (args[0] === 'pull') {+ // 快进成功,但新内容删除了 marketplace.json(在 staging 工作目录里破坏)。+ const cwd = String(opts?.cwd ?? '');+ fs.rmSync(`${cwd}/.agents/plugins/marketplace.json`, { force: true });+ return { stdout: '', stderr: '' };+ }+ if (args[0] === 'rev-parse') return { stdout: 'def456\n', stderr: '' };+ return { stdout: '', stderr: '' };+ };+ const manager = makeManager(root, executor);+ await manager.addSource({ source: 'openai/plugins' });++ await expect(manager.refreshSource('hub')).rejects.toMatchObject({+ code: 'MARKET_MANIFEST_MISSING',+ });+ // 旧缓存未被损坏的快进污染:列表仍返回插件计数。+ const listed = await manager.listSources();+ expect(listed[0]?.pluginCount).toBe(1);+ expect(listed[0]?.status).toBe('ok');+ });++ it('keeps the previous cache when the re-cloned marketplace is invalid', async () => {+ const root = makeRoot();+ let failFetch = false;+ const executor: GitExecutor = async (args) => {+ if (args[0] === '--version') return { stdout: 'git version 2.43.0\n', stderr: '' };+ if (args[0] === 'clone') {+ const dest = String(args[args.length - 1]);+ if (failFetch) {+ // 重克隆拿到的远端已损坏:没有 marketplace.json。+ fs.mkdirSync(dest, { recursive: true });+ } else {+ writeMarketplace(dest, 'hub', [{ rel: 'p', id: 'alpha' }]);+ }+ return { stdout: '', stderr: '' };+ }+ if (args[0] === 'pull' || args[0] === 'fetch') {+ if (failFetch) throw Object.assign(new Error('rejected'), { stderr: 'non-fast-forward' });+ return { stdout: '', stderr: '' };+ }+ if (args[0] === 'rev-parse') return { stdout: 'def456\n', stderr: '' };+ return { stdout: '', stderr: '' };+ };+ const manager = makeManager(root, executor);+ await manager.addSource({ source: 'openai/plugins' });++ failFetch = true;+ await expect(manager.refreshSource('hub')).rejects.toMatchObject({+ code: 'MARKET_MANIFEST_MISSING',+ });+ // 旧缓存仍然可用:列表照常返回插件计数。+ const listed = await manager.listSources();+ expect(listed[0]?.pluginCount).toBe(1);+ });++ it('migrates a legacy single-dir cache into the versioned layout on read', async () => {+ const root = makeRoot();+ const slug = marketCloneSlug('hub', {+ type: 'git',+ url: 'https://github.com/openai/plugins.git',+ sparsePaths: [],+ });+ // 旧布局:槽目录直接是缓存(含 .agents)。+ const slot = path.join(root, 'sources', slug);+ writeMarketplace(slot, 'hub', [{ rel: 'p', id: 'alpha' }]);+ const store = new MarketSourceStore(path.join(root, 'sources.v1.json'));+ store.add({+ name: 'hub',+ addedAt: '2026-07-30T00:00:00.000Z',+ lastSyncedAt: '2026-07-30T01:00:00.000Z',+ lastRevision: 'abc123',+ source: { type: 'git', url: 'https://github.com/openai/plugins.git', sparsePaths: [] },+ });+ const manager = new MarketSourceManager({+ store,+ cloneRoot: path.join(root, 'sources'),+ homeDir: root,+ });++ const listed = await manager.listSources();+ expect(listed[0]?.status).toBe('ok');+ expect(listed[0]?.pluginCount).toBe(1);+ const pointer = fs.readFileSync(path.join(slot, 'current'), 'utf8').trim();+ expect(fs.existsSync(path.join(slot, 'versions', pointer, '.agents', 'plugins', 'marketplace.json'))).toBe(true);+ });++ it('keeps serving the current version while a refresh validates a new one', async () => {+ const root = makeRoot();+ let failFetch = false;+ const executor: GitExecutor = async (args) => {+ if (args[0] === '--version') return { stdout: 'git version 2.43.0\n', stderr: '' };+ if (args[0] === 'clone') {+ writeMarketplace(String(args[args.length - 1]), 'hub', [{ rel: 'p', id: 'alpha' }]);+ return { stdout: '', stderr: '' };+ }+ if (args[0] === 'pull' || args[0] === 'fetch') {+ if (failFetch) throw Object.assign(new Error('rejected'), { stderr: 'non-fast-forward' });+ return { stdout: '', stderr: '' };+ }+ if (args[0] === 'rev-parse') return { stdout: 'def456\n', stderr: '' };+ return { stdout: '', stderr: '' };+ };+ const manager = makeManager(root, executor);+ await manager.addSource({ source: 'openai/plugins' });++ const slot = path.join(+ root,+ 'sources',+ marketCloneSlug('hub', {+ type: 'git',+ url: 'https://github.com/openai/plugins.git',+ sparsePaths: [],+ }),+ );+ const before = fs.readFileSync(path.join(slot, 'current'), 'utf8').trim();++ // 刷新成功后指针切到新版本,旧版本目录被清理,来源持续可读。+ failFetch = true;+ const refreshed = await manager.refreshSource('hub');+ expect(refreshed.pluginCount).toBe(1);+ const after = fs.readFileSync(path.join(slot, 'current'), 'utf8').trim();+ expect(after).not.toBe(before);+ expect(fs.existsSync(path.join(slot, 'versions', before))).toBe(false);+ expect(fs.existsSync(path.join(slot, 'versions', after, '.agents', 'plugins', 'marketplace.json'))).toBe(true);+ });++ it('prunes stale versions after the pointer switches, keeping only current', async () => {+ const root = makeRoot();+ let failFetch = false;+ const executor: GitExecutor = async (args) => {+ if (args[0] === '--version') return { stdout: 'git version 2.43.0\n', stderr: '' };+ if (args[0] === 'clone') {+ writeMarketplace(String(args[args.length - 1]), 'hub', [{ rel: 'p', id: 'alpha' }]);+ return { stdout: '', stderr: '' };+ }+ if (args[0] === 'pull' || args[0] === 'fetch') {+ if (failFetch) throw Object.assign(new Error('rejected'), { stderr: 'non-fast-forward' });+ return { stdout: '', stderr: '' };+ }+ if (args[0] === 'rev-parse') return { stdout: 'def456\n', stderr: '' };+ return { stdout: '', stderr: '' };+ };+ const manager = makeManager(root, executor);+ await manager.addSource({ source: 'openai/plugins' });++ const slot = path.join(+ root,+ 'sources',+ marketCloneSlug('hub', {+ type: 'git',+ url: 'https://github.com/openai/plugins.git',+ sparsePaths: [],+ }),+ );+ const before = fs.readFileSync(path.join(slot, 'current'), 'utf8').trim();++ // 连续两次刷新:无人读取时每次切完指针就清掉非 current 版本。+ failFetch = true;+ await manager.refreshSource('hub');+ const second = fs.readFileSync(path.join(slot, 'current'), 'utf8').trim();+ expect(second).not.toBe(before);+ await manager.refreshSource('hub');+ const third = fs.readFileSync(path.join(slot, 'current'), 'utf8').trim();+ // 历史版本(v1)已被延迟清理,current(v3)完整可读。+ expect(fs.existsSync(path.join(slot, 'versions', before))).toBe(false);+ expect(fs.existsSync(path.join(slot, 'versions', third, '.agents', 'plugins', 'marketplace.json'))).toBe(true);+ });++ it('keeps a version alive while a reader holds it, then prunes it on release', async () => {+ const root = makeRoot();+ let failFetch = false;+ const executor: GitExecutor = async (args) => {+ if (args[0] === '--version') return { stdout: 'git version 2.43.0\n', stderr: '' };+ if (args[0] === 'clone') {+ writeMarketplace(String(args[args.length - 1]), 'hub', [{ rel: 'p', id: 'alpha' }]);+ return { stdout: '', stderr: '' };+ }+ if (args[0] === 'pull' || args[0] === 'fetch') {+ if (failFetch) throw Object.assign(new Error('rejected'), { stderr: 'non-fast-forward' });+ return { stdout: '', stderr: '' };+ }+ if (args[0] === 'rev-parse') return { stdout: 'def456\n', stderr: '' };+ return { stdout: '', stderr: '' };+ };+ const manager = makeManager(root, executor);+ await manager.addSource({ source: 'openai/plugins' });++ const slot = path.join(+ root,+ 'sources',+ marketCloneSlug('hub', {+ type: 'git',+ url: 'https://github.com/openai/plugins.git',+ sparsePaths: [],+ }),+ );+ const held = fs.readFileSync(path.join(slot, 'current'), 'utf8').trim();+ const heldDir = path.join(slot, 'versions', held);++ // 读取方持有租约期间发生刷新:指针切走,但被持有的版本目录不得被清理,+ // 逐文件读取(安装打包的实质动作)必须全程可用。+ //+ // 刷新刻意走**另一个 manager 实例**:生产里 PluginMarketService 每次操作都+ // 新建一个 manager,租约注册表若是实例字段,安装持有的租约对刷新不可见。+ const refresher = makeManager(root, executor);+ failFetch = true;+ await manager.withDiscoveredSource('hub', async (discovered) => {+ expect(discovered.result.ok).toBe(true);+ const pluginDir = discovered.result.ok+ ? discovered.result.marketplace.plugins[0]!.dir+ : '';+ // discover 返回 realpath(macOS 下 /var → /private/var),按 realpath 比对。+ expect(pluginDir.startsWith(fs.realpathSync(heldDir))).toBe(true);++ await refresher.refreshSource('hub');+ const switched = fs.readFileSync(path.join(slot, 'current'), 'utf8').trim();+ expect(switched).not.toBe(held);+ // 指针已切走,旧版本仍在,且包内容仍可逐文件读取。+ expect(fs.existsSync(heldDir)).toBe(true);+ expect(fs.readFileSync(path.join(pluginDir, 'main.js'), 'utf8')).toContain('entry');+ });++ // 最后一个引用释放后,被推迟的清理执行完毕。+ await waitFor(() => !fs.existsSync(heldDir));+ expect(fs.existsSync(heldDir)).toBe(false);+ });++ it('keeps the activated version when persisting sync metadata fails', async () => {+ const root = makeRoot();+ const { executor } = fakeGit('hub', [{ rel: 'p', id: 'alpha' }]);+ const store = new MarketSourceStore(path.join(root, 'sources.v1.json'));+ const manager = new MarketSourceManager({+ store,+ cloneRoot: path.join(root, 'sources'),+ homeDir: root,+ gitExecutor: executor,+ });+ await manager.addSource({ source: 'openai/plugins' });++ const slot = path.join(+ root,+ 'sources',+ marketCloneSlug('hub', {+ type: 'git',+ url: 'https://github.com/openai/plugins.git',+ sparsePaths: [],+ }),+ );+ // 指针已切到新版本后元数据写入失败(磁盘满/只读/文件锁):必须如实报错,+ // 但绝不能删掉已生效的版本目录——否则指针指向不存在的目录,来源整体消失。+ store.update = () => {+ throw new Error('disk full');+ };+ await expect(manager.refreshSource('hub')).rejects.toThrow('disk full');++ const current = fs.readFileSync(path.join(slot, 'current'), 'utf8').trim();+ expect(+ fs.existsSync(path.join(slot, 'versions', current, '.agents', 'plugins', 'marketplace.json')),+ ).toBe(true);+ // 来源仍然可发现(不会因为缓存被回收而变成 market root missing)。+ const discovered = await manager.discoverSource('hub');+ expect(discovered.result.ok).toBe(true);+ });++ it('defers removeSource cleanup while a reader still holds a cached version', async () => {+ const root = makeRoot();+ const { executor } = fakeGit('hub', [{ rel: 'p', id: 'alpha' }]);+ const manager = makeManager(root, executor);+ await manager.addSource({ source: 'openai/plugins' });++ const slot = path.join(+ root,+ 'sources',+ marketCloneSlug('hub', {+ type: 'git',+ url: 'https://github.com/openai/plugins.git',+ sparsePaths: [],+ }),+ );++ // 移除来源会整槽递归删除。并发的详情发现/安装打包可能正持有槽内某个版本+ // 目录,直接删会让它们读到一半 ENOENT —— 租约守卫必须按"重叠"判定挡住整槽删。+ // 移除刻意走另一个 manager 实例(与生产一致:每次操作新建 manager)。+ const remover = makeManager(root, executor);+ await manager.withDiscoveredSource('hub', async (discovered) => {+ expect(discovered.result.ok).toBe(true);+ const pluginDir = discovered.result.ok+ ? discovered.result.marketplace.plugins[0]!.dir+ : '';++ await remover.removeSource('hub');+ // 配置已移除(来源对用户即刻消失),但被持有的缓存内容仍可逐文件读取。+ expect(remover.getConfig('hub')).toBeNull();+ expect(fs.readFileSync(path.join(pluginDir, 'main.js'), 'utf8')).toContain('entry');+ });++ // 租约释放后,被推迟的整槽删除执行完毕。+ await waitFor(() => !fs.existsSync(slot));+ expect(fs.existsSync(slot)).toBe(false);+ });++ it('keeps a re-added source when a deferred slot removal finally runs', async () => {+ const root = makeRoot();+ const { executor } = fakeGit('hub', [{ rel: 'p', id: 'alpha' }]);+ const store = new MarketSourceStore(path.join(root, 'sources.v1.json'));+ const deps = {+ store,+ cloneRoot: path.join(root, 'sources'),+ homeDir: root,+ gitExecutor: executor,+ };+ const manager = new MarketSourceManager(deps);+ await manager.addSource({ source: 'openai/plugins' });+ const config = manager.getConfig('hub')!;++ const slot = path.join(+ root,+ 'sources',+ marketCloneSlug('hub', {+ type: 'git',+ url: 'https://github.com/openai/plugins.git',+ sparsePaths: [],+ }),+ );++ // 读取方持有租约时移除来源 → 整槽删除被推迟;用户随即重新添加同名同源,+ // 复用同一个槽。旧租约释放后那笔延迟删除若不再核对"槽是否仍被配置占用",+ // 就会把刚添加成功的缓存连 current 指针一起删掉(配置有效但市场内容不见了)。+ //+ // 这里刻意直接写回配置而不是走 addSource:addSource 自己也会排一笔带守卫的+ // 整槽删除,而推迟队列按路径为键、后写覆盖,那会掩盖 removeSource 这一侧+ // 是否带了守卫。+ const remover = new MarketSourceManager(deps);+ await manager.withDiscoveredSource('hub', async () => {+ await remover.removeSource('hub');+ store.add(config);+ });++ // 给延迟删除留出执行窗口,然后断言它放弃了删除。+ await new Promise((resolve) => setTimeout(resolve, 30));+ const current = fs.readFileSync(path.join(slot, 'current'), 'utf8').trim();+ expect(+ fs.existsSync(path.join(slot, 'versions', current, '.agents', 'plugins', 'marketplace.json')),+ ).toBe(true);+ const rediscovered = await remover.discoverSource('hub');+ expect(rediscovered.result.ok).toBe(true);+ });++ it('survives a queued slot removal that unblocks while the slot is being reused', async () => {+ const root = makeRoot();+ const { executor } = fakeGit('hub', [{ rel: 'p', id: 'alpha' }]);+ const store = new MarketSourceStore(path.join(root, 'sources.v1.json'));+ const deps = {+ store,+ cloneRoot: path.join(root, 'sources'),+ homeDir: root,+ gitExecutor: executor,+ };+ const manager = new MarketSourceManager(deps);+ await manager.addSource({ source: 'openai/plugins' });++ const slot = path.join(+ root,+ 'sources',+ marketCloneSlug('hub', {+ type: 'git',+ url: 'https://github.com/openai/plugins.git',+ sparsePaths: [],+ }),+ );+ const held = fs.readFileSync(path.join(slot, 'current'), 'utf8').trim();+ const heldDir = path.join(slot, 'versions', held);++ // 安装打包仍持有旧版本 → 移除来源时整槽删除只能进 deferred(尚未启动)。+ retainCachePath(heldDir);+ await new MarketSourceManager(deps).removeSource('hub');++ // 精确命中危险窗口:旧租约在"等完在途删除之后、写回配置之前"释放。此刻+ // slotIsConfigured() 还是 false,那笔 deferred 删除会启动并与落位并发。+ // 只有整个复用段持有槽租约才挡得住它。+ const realRename = fs.promises.rename;+ const renameSpy = vi+ .spyOn(fs.promises, 'rename')+ .mockImplementation(async (from, to) => {+ if (String(to).includes(`${path.sep}versions${path.sep}`)) {+ releaseCachePath(heldDir);+ await new Promise((resolve) => setTimeout(resolve, 40));+ }+ return realRename(from as never, to as never);+ });+ try {+ await new MarketSourceManager(deps).addSource({ source: 'openai/plugins' });+ } finally {+ renameSpy.mockRestore();+ }++ await new Promise((resolve) => setTimeout(resolve, 60));+ const current = fs.readFileSync(path.join(slot, 'current'), 'utf8').trim();+ expect(+ fs.existsSync(path.join(slot, 'versions', current, '.agents', 'plugins', 'marketplace.json')),+ ).toBe(true);+ });++ it('does not run a deferred deletion against a version referenced only by current.bak', async () => {+ const root = makeRoot();+ let failFetch = false;+ const executor: GitExecutor = async (args) => {+ if (args[0] === '--version') return { stdout: 'git version 2.43.0\n', stderr: '' };+ if (args[0] === 'clone') {+ writeMarketplace(String(args[args.length - 1]), 'hub', [{ rel: 'p', id: 'alpha' }]);+ return { stdout: '', stderr: '' };+ }+ if (args[0] === 'pull' || args[0] === 'fetch') {+ if (failFetch) throw Object.assign(new Error('rejected'), { stderr: 'non-fast-forward' });+ return { stdout: '', stderr: '' };+ }+ if (args[0] === 'rev-parse') return { stdout: 'def456\n', stderr: '' };+ return { stdout: '', stderr: '' };+ };+ const manager = makeManager(root, executor);+ await manager.addSource({ source: 'openai/plugins' });++ const slot = path.join(+ root,+ 'sources',+ marketCloneSlug('hub', {+ type: 'git',+ url: 'https://github.com/openai/plugins.git',+ sparsePaths: [],+ }),+ );+ const v1 = fs.readFileSync(path.join(slot, 'current'), 'utf8').trim();+ const v1Dir = path.join(slot, 'versions', v1);++ // 读者持有 v1 → 刷新切到 v2,v1 的删除进推迟队列(skipIf = 是否为 current)。+ retainCachePath(v1Dir);+ failFetch = true;+ await manager.refreshSource('hub');++ // 并发刷新把指针切回 v1 后,Windows 备份交换失败:主文件缺失,唯一有效指针+ // 留在 current.bak。skipIf 执行时若裸读主文件,会把"v1 是 current"误判成+ // "不是",让推迟的删除把当前生效版本删掉。+ fs.writeFileSync(path.join(slot, 'current.bak'), v1);+ fs.rmSync(path.join(slot, 'current'));++ releaseCachePath(v1Dir);+ await new Promise((resolve) => setTimeout(resolve, 40));+ expect(fs.existsSync(path.join(v1Dir, '.agents', 'plugins', 'marketplace.json'))).toBe(true);+ });++ it('resolves the current version from current.bak when the pointer is missing', async () => {+ const root = makeRoot();+ const { executor } = fakeGit('hub', [{ rel: 'p', id: 'alpha' }]);+ const manager = makeManager(root, executor);+ await manager.addSource({ source: 'openai/plugins' });++ const slot = path.join(+ root,+ 'sources',+ marketCloneSlug('hub', {+ type: 'git',+ url: 'https://github.com/openai/plugins.git',+ sparsePaths: [],+ }),+ );+ // 备份交换连续失败时,唯一有效的指针留在 current.bak。只看主文件会把仍有完整+ // 版本的缓存判成缺失,整个来源报 market root missing。+ fs.renameSync(path.join(slot, 'current'), path.join(slot, 'current.bak'));++ const discovered = await manager.discoverSource('hub');+ expect(discovered.result.ok).toBe(true);+ // 读取入口顺带把指针恢复回主文件。+ expect(fs.existsSync(path.join(slot, 'current'))).toBe(true);+ });++ it('prunes dead incoming staging directories left by a killed refresh', async () => {+ const root = makeRoot();+ const { executor } = fakeGit('hub', [{ rel: 'p', id: 'alpha' }]);+ const manager = makeManager(root, executor);+ await manager.addSource({ source: 'openai/plugins' });++ const slot = path.join(+ root,+ 'sources',+ marketCloneSlug('hub', {+ type: 'git',+ url: 'https://github.com/openai/plugins.git',+ sparsePaths: [],+ }),+ );+ // 进程在刷新途中被杀会留下 incoming/ 残骸;下次刷新必须清掉,不能无界增长。+ const dead = path.join(slot, 'incoming', 'dead-uuid');+ fs.mkdirSync(dead, { recursive: true });+ fs.writeFileSync(path.join(dead, 'partial'), 'x');++ await manager.refreshSource('hub');+ await waitFor(() => !fs.existsSync(dead));+ expect(fs.existsSync(dead)).toBe(false);+ });++ it('does not let concurrent refreshes prune each other staging directories', async () => {+ const root = makeRoot();+ // 两次刷新交错:第一次进入 clone 后挂住,让第二次完整跑完(切指针 + 清理),+ // 再放行第一次。第二次的清理不得删掉第一次正在写入的暂存目录。+ let gateClone: (() => void) | null = null;+ let holdNextClone = false;+ let stagingMarker = '';+ const executor: GitExecutor = async (args) => {+ if (args[0] === '--version') return { stdout: 'git version 2.43.0\n', stderr: '' };+ if (args[0] === 'clone') {+ const dest = String(args[args.length - 1]);+ if (holdNextClone) {+ holdNextClone = false;+ // 真实 clone 会边下边写:先让暂存目录带着内容落盘,再挂住。+ fs.mkdirSync(dest, { recursive: true });+ stagingMarker = path.join(dest, 'partial-clone.txt');+ fs.writeFileSync(stagingMarker, 'in-flight');+ await new Promise<void>((resolve) => {+ gateClone = resolve;+ });+ }+ writeMarketplace(dest, 'hub', [{ rel: 'p', id: 'alpha' }]);+ return { stdout: '', stderr: '' };+ }+ // fetch 一律失败,迫使两次刷新都走重克隆路径。+ if (args[0] === 'pull' || args[0] === 'fetch') {+ throw Object.assign(new Error('rejected'), { stderr: 'non-fast-forward' });+ }+ if (args[0] === 'rev-parse') return { stdout: 'def456\n', stderr: '' };+ return { stdout: '', stderr: '' };+ };+ const manager = makeManager(root, executor);+ await manager.addSource({ source: 'openai/plugins' });++ holdNextClone = true;+ const slowRefresh = manager.refreshSource('hub');+ await waitFor(() => gateClone !== null);+ // 第二次刷新走另一个 manager 实例(与生产一致:每次操作新建 manager),+ // 完整跑完:切指针并清理非 current 版本。+ await makeManager(root, executor).refreshSource('hub');+ // 关键断言:清理不得碰到第一次正在写入的暂存目录(它还不是 current)。+ expect(fs.existsSync(stagingMarker)).toBe(true);++ gateClone!();+ // 被挂住的那次仍能完成。+ const summary = await slowRefresh;+ expect(summary.pluginCount).toBe(1);+ expect(summary.status).toBe('ok');+ });+});diff --git a/apps/desktop/src/main/plugin-market/__tests__/sources-parse.test.ts b/apps/desktop/src/main/plugin-market/__tests__/sources-parse.test.tsnew file mode 100644index 0000000000..c4681697c6--- /dev/null+++ b/apps/desktop/src/main/plugin-market/__tests__/sources-parse.test.ts@@ -0,0 +1,173 @@+import { describe, expect, it } from 'vitest';++import { parseMarketSource, resolveLocalSourcePath } from '../sources/parse';++const HOME = '/home/tester';++function parse(input: { source: string; ref?: string; sparsePaths?: string[] }) {+ return parseMarketSource(input, HOME);+}++describe('parseMarketSource', () => {+ it('parses GitHub shorthand into an https git source', () => {+ const result = parse({ source: 'openai/plugins' });+ expect(result).toEqual({+ ok: true,+ source: {+ type: 'git',+ url: 'https://github.com/openai/plugins.git',+ sparsePaths: [],+ },+ });+ });++ it('keeps ref and sparse paths on git sources', () => {+ const result = parse({+ source: 'openai/plugins',+ ref: 'v1.2',+ sparsePaths: ['plugins/codex', ' plugins/extra ', ''],+ });+ expect(result).toEqual({+ ok: true,+ source: {+ type: 'git',+ url: 'https://github.com/openai/plugins.git',+ ref: 'v1.2',+ sparsePaths: ['plugins/codex', 'plugins/extra'],+ },+ });+ });++ it.each([+ 'https://github.com/org/repo.git',+ 'ssh://[email protected]/org/repo.git',+ '[email protected]:org/repo.git',+ ])('accepts full git URL %s', (source) => {+ const result = parse({ source });+ expect(result).toEqual({+ ok: true,+ source: { type: 'git', url: source, sparsePaths: [] },+ });+ });++ it.each([+ 'https://user:[email protected]/org/repo.git',+ 'https://[email protected]/org/repo.git',+ 'ssh://user:[email protected]/org/repo.git',+ 'https://[email protected]:443/org/repo.git',+ 'https://example.com/org/repo.git?access_token=SECRET',+ 'https://example.com/org/repo.git?sig=abc&token=def',+ // fragment 与 query 一样能塞令牌/签名,并随 source 持久化、在 UI 摘要里露出。+ 'https://example.com/org/repo.git#token=SECRET',+ 'ssh://example.com/org/repo.git?token=SECRET',+ 'ssh://example.com/org/repo.git#sig=abc',+ // scp 形态不是合法 URL,new URL 解析不了,得单独拦。+ '[email protected]:org/repo.git?token=SECRET',+ '[email protected]:org/repo.git#sig=abc',+ ])('rejects git URL with embedded credentials %s', (source) => {+ expect(parse({ source })).toEqual({ ok: false, code: 'CREDENTIALS_NOT_ALLOWED' });+ });++ it('resolves ~ against the injected home directory', () => {+ const result = parse({ source: '~/team/plugins' });+ expect(result).toEqual({+ ok: true,+ source: { type: 'local', path: `${HOME}/team/plugins` },+ });+ });++ it.each(['/abs/path', './rel/path', '../up/path'])(+ 'treats %s as a local path',+ (source) => {+ const result = parse({ source });+ expect(result.ok).toBe(true);+ if (result.ok) expect(result.source.type).toBe('local');+ },+ );++ it('rejects ref and sparse paths for local sources', () => {+ expect(parse({ source: '~/x', ref: 'main' })).toEqual({+ ok: false,+ code: 'REF_NOT_ALLOWED_FOR_LOCAL',+ });+ expect(parse({ source: '~/x', sparsePaths: ['a'] })).toEqual({+ ok: false,+ code: 'SPARSE_NOT_ALLOWED_FOR_LOCAL',+ });+ });++ it('rejects empty and unrecognizable sources', () => {+ expect(parse({ source: ' ' })).toEqual({ ok: false, code: 'EMPTY_SOURCE' });+ expect(parse({ source: 'git://example.com/org/repo.git' })).toEqual({+ ok: false,+ code: 'INVALID_SOURCE_FORMAT',+ });+ expect(parse({ source: 'just-a-word' })).toEqual({+ ok: false,+ code: 'INVALID_SOURCE_FORMAT',+ });+ expect(parse({ source: 'a/b/c' })).toEqual({+ ok: false,+ code: 'INVALID_SOURCE_FORMAT',+ });+ });++ it('rejects option-injection shaped refs', () => {+ expect(parse({ source: 'openai/plugins', ref: '--upload-pack=evil' })).toEqual({+ ok: false,+ code: 'INVALID_REF',+ });+ });++ it('rejects sparse paths that look like git options', () => {+ for (const opt of ['--stdin', '--no-cone', '--cone', '-x']) {+ expect(parse({ source: 'openai/plugins', sparsePaths: [opt] })).toEqual({+ ok: false,+ code: 'INVALID_SPARSE_PATH',+ });+ }+ });++ it('rejects sparse paths escaping the repository', () => {+ expect(parse({ source: 'openai/plugins', sparsePaths: ['../outside'] })).toEqual({+ ok: false,+ code: 'INVALID_SPARSE_PATH',+ });+ expect(parse({ source: 'openai/plugins', sparsePaths: ['/abs'] })).toEqual({+ ok: false,+ code: 'INVALID_SPARSE_PATH',+ });+ });++ it('resolves local paths without touching the filesystem', () => {+ expect(resolveLocalSourcePath('~/a/b', HOME)).toBe(`${HOME}/a/b`);+ });++ it('rejects backslash in git URL authority (WHATWG/git 分歧,凭证闸失明)', () => {+ // new URL 把 \ 归一成 /,userinfo 看不见;git 实际连 evil.com。+ expect(parse({ source: 'https://github.com\\@evil.com/x/y.git' })).toEqual({+ ok: false,+ code: 'INVALID_SOURCE_FORMAT',+ });+ // 单段 token 形态:同样必须在 \ 处拒,不能落进 git 源。+ expect(parse({ source: 'https://ghp_secret\\@github.com/o/r.git' })).toEqual({+ ok: false,+ code: 'INVALID_SOURCE_FORMAT',+ });+ });++ it('rejects control/bidi chars in source and sparse paths', () => {+ expect(parse({ source: 'https://github.com/o/r.git' })).toEqual({+ ok: false,+ code: 'INVALID_SOURCE_FORMAT',+ });+ expect(+ parse({ source: 'https://github.com/o/r.git', sparsePaths: ['plugins/a'] }),+ ).toEqual({ ok: false, code: 'INVALID_SPARSE_PATH' });+ });++ it('unparseable https URL fails closed as possibly carrying credentials', () => {+ // new URL 抛错的串按"可能带凭证"拒,而不是 fail-open 放行。+ expect(parse({ source: 'https://[not-a-host/o/r.git' }).ok).toBe(false);+ });+});diff --git a/apps/desktop/src/main/plugin-market/__tests__/sources-store.test.ts b/apps/desktop/src/main/plugin-market/__tests__/sources-store.test.tsnew file mode 100644index 0000000000..b912b3a7ed--- /dev/null+++ b/apps/desktop/src/main/plugin-market/__tests__/sources-store.test.ts@@ -0,0 +1,200 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import type { MarketSourceConfig } from '../../../shared/pluginMarket';+import { marketSourceKey } from '../../../shared/pluginMarket';+import { MarketSourceStore, sourcesEqual } from '../sources/store';++const roots: string[] = [];++afterEach(() => {+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });+});++function makeStore() {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-store-'));+ roots.push(root);+ return new MarketSourceStore(path.join(root, 'sources.v1.json'));+}++function config(overrides: Partial<MarketSourceConfig> = {}): MarketSourceConfig {+ return {+ name: 'openai/plugins',+ addedAt: '2026-07-31T00:00:00.000Z',+ lastSyncedAt: null,+ lastRevision: null,+ source: { type: 'git', url: 'https://github.com/openai/plugins.git', sparsePaths: [] },+ ...overrides,+ };+}++describe('MarketSourceStore', () => {+ it('returns an empty list when the file does not exist', () => {+ expect(makeStore().list()).toEqual([]);+ });++ it('persists configs across instances (atomic write + read back)', () => {+ const store = makeStore();+ store.add(config());+ store.add(config({ name: 'local-lib', source: { type: 'local', path: '/x' } }));++ const reread = new MarketSourceStore(+ (store as unknown as { filePathSource: string }).filePathSource,+ );+ expect(reread.list().map((source) => source.name)).toEqual([+ 'openai/plugins',+ 'local-lib',+ ]);+ });++ it('add replaces a same-name config instead of duplicating it', () => {+ const store = makeStore();+ store.add(config());+ store.add(config({ lastSyncedAt: '2026-07-31T01:00:00.000Z' }));+ expect(store.list()).toHaveLength(1);+ expect(store.get('openai/plugins')?.lastSyncedAt).toBe('2026-07-31T01:00:00.000Z');+ });++ it('updates sync metadata without touching identity fields', () => {+ const store = makeStore();+ store.add(config());+ store.update('openai/plugins', {+ lastSyncedAt: '2026-07-31T02:00:00.000Z',+ lastRevision: 'abc123',+ });+ const updated = store.get('openai/plugins');+ expect(updated?.lastRevision).toBe('abc123');+ expect(updated?.source).toEqual(config().source);+ expect(store.update('missing', { lastRevision: 'x' })).toBeUndefined();+ });++ it('removes configs and reports what was removed', () => {+ const store = makeStore();+ store.add(config());+ expect(store.remove('openai/plugins')?.name).toBe('openai/plugins');+ expect(store.remove('openai/plugins')).toBeNull();+ expect(store.list()).toEqual([]);+ });++ it('drops malformed entries instead of failing the whole file', () => {+ const store = makeStore();+ store.add(config());+ const file = (store as unknown as { filePathSource: string }).filePathSource;+ fs.writeFileSync(+ file,+ JSON.stringify({+ schemaVersion: 1,+ sources: [config(), { name: '' }, { name: 'bad', source: { type: 'other' } }],+ }),+ );+ expect(store.list().map((source) => source.name)).toEqual(['openai/plugins']);+ });++ it('detects equivalent sources by type + location + ref + sparse paths', () => {+ const store = makeStore();+ store.add(config({ source: { type: 'git', url: 'https://x.test/r.git', ref: 'v1', sparsePaths: ['a'] } }));+ expect(+ store.hasEquivalent({ type: 'git', url: 'https://x.test/r.git', ref: 'v1', sparsePaths: ['a'] }),+ ).toBe(true);+ expect(+ store.hasEquivalent({ type: 'git', url: 'https://x.test/r.git', sparsePaths: ['a'] }),+ ).toBe(false);+ expect(store.hasEquivalent({ type: 'local', path: 'https://x.test/r.git' })).toBe(false);+ });++ it('recovers sources from .bak instead of reading a missing file as empty', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-store-'));+ roots.push(root);+ const filePath = path.join(root, 'sources.v1.json');+ const store = new MarketSourceStore(filePath);+ store.add(config());+ // 模拟 Windows 备份交换与回滚都失败:主文件缺失,.bak 是唯一有效快照。+ fs.renameSync(filePath, `${filePath}.bak`);++ // 读取入口必须恢复 .bak;否则读成空来源表,后续写入会覆盖唯一快照,+ // 用户添加过的自定义市场来源全部丢失。+ expect(store.list().map((item) => item.name)).toEqual(['openai/plugins']);+ store.add(config({ name: 'other/hub' }));+ expect(store.list().map((item) => item.name).sort()).toEqual(['openai/plugins', 'other/hub']);+ });++ it('marketSourceKey never collides across distinct sources', () => {+ // 拼接式指纹(join/定界符)存在可构造碰撞,而这个 key 承担账本所有权判定:+ // 碰撞 = 两个不同来源被判成同一个,同名异源防线随之失效。+ const keys = [+ marketSourceKey({ type: 'git', url: 'u', sparsePaths: ['a,b', 'c'] }),+ marketSourceKey({ type: 'git', url: 'u', sparsePaths: ['a', 'b,c'] }),+ marketSourceKey({ type: 'git', url: 'u', ref: 'x', sparsePaths: ['p'] }),+ marketSourceKey({ type: 'git', url: 'u', ref: 'x:p', sparsePaths: [] }),+ marketSourceKey({ type: 'git', url: 'u#x', sparsePaths: ['p'] }),+ marketSourceKey({ type: 'local', path: 'u' }),+ ];+ expect(new Set(keys).size).toBe(keys.length);+ });++ it('sourcesEqual treats undefined and empty ref as identical', () => {+ expect(+ sourcesEqual(+ { type: 'git', url: 'u', sparsePaths: [] },+ { type: 'git', url: 'u', ref: undefined, sparsePaths: [] },+ ),+ ).toBe(true);+ });++ it('sourcesEqual 不被 sparsePaths 的分隔符碰撞骗过', () => {+ // 旧写法 `sparsePaths.join('\n')` 会把这两个**不同**的来源判成同一个:+ // ['a\nb'] 与 ['a','b'] 的 join 结果字面相同。身份判据必须让数组边界+ // 不可伪造(与 marketSourceKey 同一实现)。+ expect(+ sourcesEqual(+ { type: 'git', url: 'u', sparsePaths: ['a\nb'] },+ { type: 'git', url: 'u', sparsePaths: ['a', 'b'] },+ ),+ ).toBe(false);+ // 同样不能被顺序变化骗过(顺序不同 = 不同的稀疏检出集合声明)。+ expect(+ sourcesEqual(+ { type: 'git', url: 'u', sparsePaths: ['a', 'b'] },+ { type: 'git', url: 'u', sparsePaths: ['b', 'a'] },+ ),+ ).toBe(false);+ // 真正相同的仍判相同。+ expect(+ sourcesEqual(+ { type: 'git', url: 'u', sparsePaths: ['a', 'b'] },+ { type: 'git', url: 'u', sparsePaths: ['a', 'b'] },+ ),+ ).toBe(true);+ });++ it('sourcesEqual 与 marketSourceKey 是同一判据(不允许两套逻辑漂移)', () => {+ const samples: Array<[Parameters<typeof sourcesEqual>[0], Parameters<typeof sourcesEqual>[1]]> = [+ [+ { type: 'local', path: '/a' },+ { type: 'local', path: '/a' },+ ],+ [+ { type: 'local', path: '/a' },+ { type: 'local', path: '/b' },+ ],+ [+ { type: 'git', url: 'u', ref: 'v1', sparsePaths: ['x'] },+ { type: 'git', url: 'u', ref: 'v1', sparsePaths: ['x'] },+ ],+ [+ { type: 'git', url: 'u', ref: 'v1', sparsePaths: ['x'] },+ { type: 'git', url: 'u', ref: 'v2', sparsePaths: ['x'] },+ ],+ [+ { type: 'local', path: '/a' },+ { type: 'git', url: 'u', sparsePaths: [] },+ ],+ ];+ for (const [a, b] of samples) {+ expect(sourcesEqual(a, b)).toBe(marketSourceKey(a) === marketSourceKey(b));+ }+ });+});diff --git a/apps/desktop/src/main/plugin-market/install.ts b/apps/desktop/src/main/plugin-market/install.tsnew file mode 100644index 0000000000..dbcf11f877--- /dev/null+++ b/apps/desktop/src/main/plugin-market/install.ts@@ -0,0 +1,178 @@+/**+ * 自定义市场插件的安装管道。+ *+ * 复用服务端市场的装入出口(installOrUpdateMarketGhostPackage):打包 →+ * inspect 校验 → 原子换目录 → 布局停靠,全部走同一条已验证路径。差异只在+ * 包来源与信任闸:+ * - 包字节来自用户添加的 Git/本地源,未经 plugin-server 校验,因此保留前缀+ * 闸(cindy- 等官方 id)与服务端市场相反——按本地 .cindy 装入语义拒绝。+ * - 打包产物落系统临时目录(唯一文件名),装完即删,不污染市场克隆缓存。+ */+import fs from 'node:fs';+import path from 'node:path';+import crypto from 'node:crypto';++import { app } from 'electron';++import {+ validateGhostManifest,+ type GhostManifest,+ type InstalledGhost,+} from '../../shared/ghost.js';+import {+ installOrUpdateMarketGhostPackage,+ rejectReservedGhostIdForCustomMarket,+} from '../cindy-brain/index.js';+import { packGhostDirToFile } from '../cindy-brain/forge.js';+import { createLogger } from '../logger.js';+import { isIpcError } from '../../shared/ipc-errors.js';+import { redactAbsolutePaths } from './sources/git.js';+import { throwIpcError } from '../utils/ipcValidate.js';+import {+ GHOST_MANIFEST_MAX_BYTES,+ readBoundedFileNoFollow,+} from '../utils/readBoundedFile.js';++/**+ * 把插件目录装成运行中的 Ghost。+ *+ * expected 是 Renderer 确认框实际审阅过的完整 manifest;这里重读 ghost.json+ * 逐字比对,确认到打包之间目录被改动时拒绝滑入(与服务端市场的+ * expectedReleaseId 同一防线,但自定义市场必须核对权限与能力声明本身)。+ */+const log = createLogger('plugin-market-install');++/** 进 IPC 的打包/校验详情统一脱敏(宿主路径、控制符)并截断,原文留 main 日志。 */+function sanitizeInstallDetail(message: string): string {+ return (+ redactAbsolutePaths(message)+ // eslint-disable-next-line no-control-regex+ .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '')+ .slice(0, 256)+ );+}++export async function installCustomMarketPlugin(input: {+ pluginDir: string;+ expected: GhostManifest;+ /**+ * 打包完成后、实际改动 Ghost 运行时之前调用的校验钩(可异步)。+ * 自定义市场按调用方捕获的账户审阅 manifest;打包是异步的,装出前必须+ * 重新确认会话未漂移,避免把 A 审阅的插件装进当前账户 B 的运行时。+ * 跨来源 ghostId 所有权也在这里复核——打包耗时,期间另一窗口可能添加了+ * 声明同一 ghostId 的来源。+ */+ beforeCommit?: () => void | Promise<void>;+ /**+ * 提交段(复核 + 落位)的互斥包装,与来源增删共享同一把锁。+ *+ * 只在 `beforeCommit` 里复核不够:它返回后 `installOrUpdateMarketGhostPackage`+ * 还要先 await 包检查才开始真正改动运行时,那段时间另一窗口仍能添加声明同一+ * ghostId 的来源,复核结论在落位前就过期了。把"复核 + 落位"整段放进锁里,+ * 来源变更插不进来。+ */+ withCommitLock?: <T>(fn: () => Promise<T>) => Promise<T>;+ /**+ * 落位成功后、仍在 `withCommitLock` 内执行的溯源写入钩。+ *+ * 账本写入必须与落位同锁:放在锁外时,另一条路径(本地 .cindy 装入/更新)可以+ * 插在"包已落位"与"写下溯源"之间换掉同 id 的包,账本随后认领一个其实已被替换+ * 的包。抛错则整个安装按失败上报(包已落位,由调用方决定补偿)。+ */+ afterCommit?: () => Promise<void>;+}): Promise<InstalledGhost> {+ // input.pluginDir 是发现层已 realpath、且已校验落在市场根内的规范路径。+ // 发现之后、打包之前,若插件目录或其某个父目录被换成指向市场外的符号链接,+ // 重新 realpath 会解析到别处——只要外部目录留着同样的 ghost.json,清单摘要+ // 复核发现不了(它只比对清单本身),市场外的 payload 就会被打包安装。+ // 这里要求重解析结果**仍等于发现时的规范路径**:任一路径段被换成链接都会+ // 让 realpath 改变,直接拒绝(比只锚新解析目录更严——那等于跟着链接走)。+ // 刻意放在下面那个 try 之外:它的 catch 会把一切压成"清单读不出来"的通用+ // 文案,这条的原因需要如实区分。+ let realPluginDir: string;+ try {+ realPluginDir = await fs.promises.realpath(input.pluginDir);+ } catch {+ throwIpcError('GHOST_FILE_INVALID', 'The Plugin directory is unreadable');+ }+ if (realPluginDir !== input.pluginDir) {+ throwIpcError('GHOST_FILE_INVALID', 'The Plugin directory changed after discovery');+ }+ let raw: unknown;+ try {+ // 与发现层同一把闸(单句柄限量读,拒符号链接):本地市场目录仍是用户可写的+ // 活目录,按路径无界 readFile 会被换成超大文件或 /dev/zero 链接卡死 main。+ // containWithin 再堵 ghost.json 这一层自身被换成根外链接的窗口。+ const bytes = await readBoundedFileNoFollow(+ path.join(realPluginDir, 'ghost.json'),+ GHOST_MANIFEST_MAX_BYTES,+ { containWithin: realPluginDir },+ );+ if (bytes === null) throw new Error('not a bounded regular file');+ raw = JSON.parse(bytes.toString('utf8'));+ } catch (error) {+ // 已经带 code 的 IPC 错误如实上抛,不被下面的通用文案覆盖。+ if (isIpcError(error)) throw error;+ // Renderer 只拿到通用文案(不泄露宿主细节),但 main 日志必须留下原始原因:+ // 少了这一行,"清单确实损坏"与"有人中途替换了插件目录"在事后排查时无从区分。+ log.warn('custom market plugin manifest unreadable', {+ detail: sanitizeInstallDetail(error instanceof Error ? error.message : String(error)),+ });+ throwIpcError('GHOST_FILE_INVALID', 'The Plugin manifest is missing or unreadable');+ }+ // 前置快速失败:清单非法或官方保留 id 直接拒,避免无谓打包。+ // reason 会插值 ghost.json 里的未知字段值(不受长度约束的不可信内容),+ // packed.message 会带 fs 错误自附的宿主绝对路径——进 IPC 前一律脱敏+截断,+ // 完整原文只留 main 日志。+ const validated = validateGhostManifest(raw);+ if (!validated.ok) {+ throwIpcError('GHOST_FILE_INVALID', sanitizeInstallDetail(validated.reason));+ }+ rejectReservedGhostIdForCustomMarket(validated.manifest.id);++ const tempPath = path.join(+ app.getPath('temp'),+ `cindy-custom-market-${validated.manifest.id}-${crypto.randomUUID()}.cindy`,+ );+ try {+ // 传**已校验的规范根**(既作为打包输入,也作为打包器的锚点):打包器会核对+ // 自己解析出的 realpath 仍等于它。少了这个传递,上面那次等值校验只能证明+ // "检查那一刻是干净的"——打包器随后自己重解析,目录在这中间被换成指向市场外+ // 的链接时,它以自己解析出的结果为锚点,外部 payload 会被打包进去。+ const packed = await packGhostDirToFile(realPluginDir, tempPath, realPluginDir);+ if (!packed.ok) {+ throwIpcError(+ packed.errorCode === 'TOO_LARGE' || packed.errorCode === 'MANIFEST_INVALID'+ ? 'GHOST_FILE_INVALID'+ : packed.errorCode === 'DIR_NOT_FOUND'+ ? 'NOT_FOUND'+ : 'INTERNAL',+ sanitizeInstallDetail(packed.message),+ );+ }+ // 唯一防篡改防线:比对实际打进包的 manifest,而非打包前磁盘上的 ghost.json。+ // 堵住"前置比对通过后、打包读取文件前"目录被改(保持 id/version 却新增+ // 权限声明)的窗口——装的就是 packed.manifest,必须以它为准。+ if (JSON.stringify(packed.manifest) !== JSON.stringify(input.expected)) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'Plugin changed after permission review',+ );+ }+ // 装出前最后防线:打包期间账号可能已切换、也可能有别的来源声明了同一 ghostId。+ // 复核与落位必须在同一把锁内完成,否则复核结论会在落位前过期。+ const commit = async (): Promise<InstalledGhost> => {+ await input.beforeCommit?.();+ const installed = await installOrUpdateMarketGhostPackage(tempPath, {+ ghostId: validated.manifest.id,+ version: validated.manifest.version,+ });+ // 溯源写入与落位同锁(见 afterCommit 注释)。+ await input.afterCommit?.();+ return installed;+ };+ return await (input.withCommitLock ? input.withCommitLock(commit) : commit());+ } finally {+ await fs.promises.rm(tempPath, { force: true }).catch(() => undefined);+ }+}diff --git a/apps/desktop/src/main/plugin-market/ledger.ts b/apps/desktop/src/main/plugin-market/ledger.tsindex 3735932247..c5d0f61f8a 100644--- a/apps/desktop/src/main/plugin-market/ledger.ts+++ b/apps/desktop/src/main/plugin-market/ledger.ts@@ -1,11 +1,20 @@-import fs from 'node:fs';-import path from 'node:path';import crypto from 'node:crypto';+import path from 'node:path';import type { PluginScope } from '@cindy/plugin-protocol';+import {+ atomicWriteFileSync,+ readAtomicFileSync,+} from '../utils/atomicWriteFile.js';const LEDGER_SCHEMA_VERSION = 1;+/** 自定义市场溯源的独立账本文件名(与 ledger.v1.json 同目录)。 */+const CUSTOM_LEDGER_FILE = 'custom-ledger.v1.json';++/** 服务端市场安装的溯源来源(旧版本也认识的封闭集合)。 */+const SERVER_SOURCES = new Set(['market', 'legacy-adopted']);+export interface PluginMarketInstallationRecord {pluginId: string;ghostId: string;@@ -14,9 +23,40 @@ export interface PluginMarketInstallationRecord {sha256: string;scope: PluginScope;organizationId: string | null;- source: 'market' | 'legacy-adopted';+ source: 'market' | 'legacy-adopted' | 'git-market' | 'local-market';installed: boolean;updatedAt: string;+ /**+ * 自定义来源的规范化指纹(marketSourceKey)。市场名可复用——移除来源后添加+ * 同名异源的市场会得到相同 pluginId,所有权校验必须同时对上这个指纹。+ * 仅自定义安装记录携带;服务端记录没有此字段。+ */+ sourceKey?: string;+ /**+ * 安装落位那一刻的 manifest 规范化摘要(ghostManifestDigest)。账本记录只是+ * "我装过"的声明,运行时的包在降级窗口可以被旧版换成任何东西(旧版不认识+ * custom 账本,卸载/本地重装都不会更新它)——认领运行时安装必须同时对上这个+ * 摘要,只凭 ghostId 存在就恢复所有权会把别人的包错误归属给本来源并放行其+ * 更新覆盖。仅自定义安装记录携带。+ */+ manifestDigest?: string;+}++/** 递归按键排序的规范化 JSON(摘要必须与对象键序无关,两侧独立算也一致)。 */+function canonicalJson(value: unknown): string {+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;+ if (value && typeof value === 'object') {+ const entries = Object.entries(value as Record<string, unknown>)+ .filter(([, item]) => item !== undefined)+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));+ return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(',')}}`;+ }+ return JSON.stringify(value) ?? 'null';+}++/** manifest 的稳定摘要:语义相同的 manifest 无论键序/来源如何,摘要一致。 */+export function ghostManifestDigest(manifest: unknown): string {+ return crypto.createHash('sha256').update(canonicalJson(manifest)).digest('hex');}interface PluginMarketLedgerData {@@ -33,6 +73,24 @@ function emptyLedger(): PluginMarketLedgerData {};}+function isCustomRecord(record: PluginMarketInstallationRecord): boolean {+ return record.source === 'git-market' || record.source === 'local-market';+}++/**+ * 同一 ghostId 在两个账本文件里都有记录时的消解规则(只在降级窗口出现):+ * 仍在安装中的记录优先于已卸载的;同为安装中(或同为已卸载)按 updatedAt 新者+ * 胜(ISO 字符串可直接比较);完全平手保第一个参数(调用方传主账本记录——冲突+ * 本身即意味着旧版本操作过主账本,它是最后被真实写入过的一侧)。+ */+function preferRecord(+ main: PluginMarketInstallationRecord,+ custom: PluginMarketInstallationRecord,+): PluginMarketInstallationRecord {+ if (main.installed !== custom.installed) return main.installed ? main : custom;+ return custom.updatedAt > main.updatedAt ? custom : main;+}+function validRecord(value: unknown): value is PluginMarketInstallationRecord {if (!value || typeof value !== 'object' || Array.isArray(value)) return false;const record = value as Record<string, unknown>;@@ -46,15 +104,61 @@ function validRecord(value: unknown): value is PluginMarketInstallationRecord {record.scope === 'organization' ||record.scope === 'personal') &&(record.organizationId === null || typeof record.organizationId === 'string') &&- (record.source === 'market' || record.source === 'legacy-adopted') &&+ (record.source === 'market' ||+ record.source === 'legacy-adopted' ||+ record.source === 'git-market' ||+ record.source === 'local-market') &&typeof record.installed === 'boolean' &&- typeof record.updatedAt === 'string'+ typeof record.updatedAt === 'string' &&+ (record.sourceKey === undefined || typeof record.sourceKey === 'string') &&+ (record.manifestDigest === undefined || typeof record.manifestDigest === 'string'));}+/** 读取并解析一个账本 JSON 文件的 installations 段;文件不存在返回空。 */+function readInstallationsFile(+ filePath: string,+): { installations: Record<string, PluginMarketInstallationRecord>; raw: Record<string, unknown> | null } {+ // 读失败与解析失败分开处理:文件不存在(ENOENT)才是空;文件在但读不到(文件锁/+ // 权限/瞬时 I/O)或备份救不回来时由 readAtomicFileSync **上抛**——降级成空会让+ // 紧接着的写入把真实记录覆盖掉。只有"内容确实不是合法 JSON"才按空重建。+ const text = readAtomicFileSync(filePath);+ if (text === null) return { installations: {}, raw: null };+ let parsed: unknown;+ try {+ parsed = JSON.parse(text);+ } catch {+ return { installations: {}, raw: null };+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ return { installations: {}, raw: null };+ }+ const value = parsed as Record<string, unknown>;+ if (value.schemaVersion !== LEDGER_SCHEMA_VERSION) return { installations: {}, raw: null };+ 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;+ }+ }+ return { installations, raw: value };+}+/*** Plugin 市场来源账本。包目录仍是 runtime 安装事实;本账本只记录 server* Plugin ID、Release 溯源和 defaultInstall 退订,不复制 manifest/凭证。+ *+ * **存储分两个文件(存量兼容红线)**:+ * - `ledger.v1.json`:服务端安装(market / legacy-adopted)与 defaultInstall 退订。+ * schema 与旧版本完全一致——旧版 `validRecord()` 是封闭枚举,任何它不认识的+ * source 都会在下一次写入时被过滤并重写落盘。+ * - `custom-ledger.v1.json`:自定义市场安装(git-market / local-market)。旧版本+ * 不认识也不会触碰这个文件,用户降级再升级,自定义安装的溯源原样还在。+ * 若把自定义记录混进主账本,降级后旧版的任意一次写入都会把它们永久丢掉,该插件+ * 再升级后会被投影成"占用 ghostId 的本地冲突项"、无法从原市场更新。+ *+ * 早期开发版把自定义记录写进了主账本:读取时兼容合并,任意一次写入即按 source+ * 归位迁移(写路径本来就整份重写两个文件)。*/export class PluginMarketLedger {constructor(private readonly filePathSource: string | (() => string)) {}@@ -75,25 +179,36 @@ export class PluginMarketLedger {: this.filePathSource;}+ /** 自定义溯源账本与主账本同目录(同一 owner 作用域)。 */+ private customFilePath(): string {+ return path.join(path.dirname(this.filePath()), CUSTOM_LEDGER_FILE);+ }+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 main = readInstallationsFile(this.filePath());+ const custom = readInstallationsFile(this.customFilePath());+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;- }+ for (const [ghostId, record] of Object.entries(main.installations)) {+ // 主账本里的自定义记录是早期开发版写入的存量,一并纳入(下次写入时归位)。+ installations[ghostId] = record;+ }+ for (const [ghostId, record] of Object.entries(custom.installations)) {+ if (!isCustomRecord(record)) continue; // 自定义账本只承载自定义溯源+ // 两个文件出现同一 ghostId 只发生在降级窗口:旧版本只写主账本(比如降级后+ // 卸载了自定义安装、又从服务端装了同 ghostId),custom 账本里留着它不认识、+ // 也不会清理的陈旧记录。无条件让 custom 覆盖会把服务端安装错误归属给自定义+ // 来源,并允许该来源提供更新 —— 必须按"实际安装状态 + 时间"消解,平手保+ // 主账本(冲突本身即意味着旧版操作过主账本)。胜出后由任意一次写入按 source+ // 归位,败方记录随整份重写被清掉。+ const existing = installations[ghostId];+ installations[ghostId] = existing ? preferRecord(existing, record) : record;}+const defaultInstallOptOuts: Record<string, string[]> = {};- if (value.defaultInstallOptOuts && typeof value.defaultInstallOptOuts === 'object') {- for (const [userId, pluginIds] of Object.entries(value.defaultInstallOptOuts)) {+ const rawOptOuts = main.raw?.defaultInstallOptOuts;+ if (rawOptOuts && typeof rawOptOuts === 'object') {+ for (const [userId, pluginIds] of Object.entries(rawOptOuts)) {if (!Array.isArray(pluginIds)) continue;defaultInstallOptOuts[userId] = [...new Set(pluginIds.filter((id): id is string => typeof id === 'string')),@@ -135,31 +250,33 @@ export class PluginMarketLedger {}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 });+ // 按 source 分仓落盘:主账本只出现旧版本认识的 source,自定义溯源全部进+ // 独立文件。混写过的存量(早期开发版)由此在任意一次写入时自动归位。+ const server: Record<string, PluginMarketInstallationRecord> = {};+ const custom: Record<string, PluginMarketInstallationRecord> = {};+ for (const [ghostId, record] of Object.entries(data.installations)) {+ if (isCustomRecord(record)) custom[ghostId] = record;+ else if (SERVER_SOURCES.has(record.source)) server[ghostId] = record;}+ atomicWriteFileSync(+ this.filePath(),+ `${JSON.stringify(+ {+ schemaVersion: LEDGER_SCHEMA_VERSION,+ installations: server,+ defaultInstallOptOuts: data.defaultInstallOptOuts,+ },+ null,+ 2,+ )}\n`,+ );+ atomicWriteFileSync(+ this.customFilePath(),+ `${JSON.stringify(+ { schemaVersion: LEDGER_SCHEMA_VERSION, installations: custom },+ null,+ 2,+ )}\n`,+ );}}diff --git a/apps/desktop/src/main/plugin-market/registerIpc.ts b/apps/desktop/src/main/plugin-market/registerIpc.tsindex 1ae767143c..c24d32ae44 100644--- a/apps/desktop/src/main/plugin-market/registerIpc.ts+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts@@ -1,10 +1,14 @@+import os from 'node:os';+import { ipcMain } from 'electron';import { isIpcError } from '../../shared/ipc-errors.js';+import type { GhostManifest } from '../../shared/ghost.js';import { setGhostUninstallLedgerPreparer } from '../cindy-brain/index.js';import { createLogger } from '../logger.js';import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';-import { requireString, throwIpcError } from '../utils/ipcValidate.js';+import { requireObject, requireString, throwIpcError } from '../utils/ipcValidate.js';+import { parseMarketSource } from './sources/parse.js';import { PluginMarketService } from './service.js';const log = createLogger('plugin-market-ipc');@@ -58,14 +62,20 @@ export function registerPluginMarketIpc(): void {typeof options === 'object' && options !== null? (options as {expectedReleaseId?: unknown;+ expectedManifest?: unknown;allowPermissionExpansion?: unknown;}): null;const expectedReleaseId = requireString(obj?.expectedReleaseId, 'expectedReleaseId');+ const expectedManifest =+ obj?.expectedManifest === undefined || obj?.expectedManifest === null+ ? undefined+ : requireObject(obj.expectedManifest);const allowPermissionExpansion = obj?.allowPermissionExpansion === true;return invokePluginMarket(() =>service().install(requireString(pluginId, 'pluginId'), {expectedReleaseId,+ ...(expectedManifest ? { expectedManifest: expectedManifest as unknown as GhostManifest } : {}),allowPermissionExpansion,}),);@@ -77,4 +87,80 @@ export function registerPluginMarketIpc(): void {service().uninstall(requireString(pluginId, 'pluginId')),);});++ /* ------------------------- 自定义市场源管理 ------------------------- */++ ipcMain.handle('plugin-market:list-sources', (event) => {+ assertTrustedAppRendererEvent(event);+ return invokePluginMarket(() => service().listSources());+ });+ ipcMain.handle('plugin-market:add-source', (event, payload: unknown) => {+ assertTrustedAppRendererEvent(event);+ const obj = requireObject(payload);+ const source = requireString(obj.source, 'source');+ if (source.length > 512) throwIpcError('INVALID_PARAMS', 'source is too long');+ const ref =+ obj.ref === undefined || obj.ref === null+ ? undefined+ : requireString(obj.ref, 'ref');+ if (ref !== undefined && ref.length > 128) {+ throwIpcError('INVALID_PARAMS', 'ref is too long');+ }+ let sparsePaths: string[] | undefined;+ if (obj.sparsePaths !== undefined && obj.sparsePaths !== null) {+ if (!Array.isArray(obj.sparsePaths) || obj.sparsePaths.length > 32) {+ throwIpcError('INVALID_PARAMS', 'sparsePaths must be an array of at most 32 entries');+ }+ sparsePaths = obj.sparsePaths.map((entry) => {+ const value = requireString(entry, 'sparsePaths entry');+ if (value.length > 256) throwIpcError('INVALID_PARAMS', 'sparsePaths entry is too long');+ return value;+ });+ }+ // 本地目录不接受 Renderer 直传的绝对路径:XSS 控制下的 Renderer 自报路径+ // 不构成用户授权(frame 校验只证明来源窗口,不证明用户选择了这个目录)。+ // 本地来源一律走 pick-local-source(Main 原生目录选择器,选择即授权)。+ const parsed = parseMarketSource(+ { source, ...(ref !== undefined ? { ref } : {}), ...(sparsePaths !== undefined ? { sparsePaths } : {}) },+ os.homedir(),+ );+ if (parsed.ok && parsed.source.type === 'local') {+ throwIpcError('INVALID_PARAMS', 'Local folders must be added via the directory picker');+ }+ return invokePluginMarket(() =>+ service().addSource({+ source,+ ...(ref !== undefined ? { ref } : {}),+ ...(sparsePaths !== undefined ? { sparsePaths } : {}),+ }),+ );+ });+ ipcMain.handle('plugin-market:pick-local-source', (event, defaultPath: unknown) => {+ assertTrustedAppRendererEvent(event);+ const hint =+ defaultPath === undefined || defaultPath === null+ ? undefined+ : requireString(defaultPath, 'defaultPath');+ if (hint !== undefined && hint.length > 512) {+ throwIpcError('INVALID_PARAMS', 'defaultPath is too long');+ }+ // 授权来自用户在 Main 原生选择器里的选择;hint 只影响初始定位。+ return invokePluginMarket(() => service().addLocalSourceFromPicker(hint));+ });+ ipcMain.handle('plugin-market:remove-source', (event, name: unknown) => {+ assertTrustedAppRendererEvent(event);+ return invokePluginMarket(() =>+ service().removeSource(requireString(name, 'name')),+ );+ });+ ipcMain.handle('plugin-market:refresh-source', (event, name: unknown) => {+ assertTrustedAppRendererEvent(event);+ return invokePluginMarket(() =>+ service().refreshSource(requireString(name, 'name')),+ );+ });+ ipcMain.handle('plugin-market:git-preflight', (event) => {+ assertTrustedAppRendererEvent(event);+ return invokePluginMarket(() => service().gitPreflight());+ });}diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex 4e29b13345..e5b9e8d060 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -7,19 +7,28 @@ import {type VisiblePluginDetail,type VisiblePluginSummary,} from '@cindy/plugin-protocol';-import { app, type WebContents } from 'electron';+import { app, dialog, type WebContents } from 'electron';import {diffGhostPermissionItems,isOfficialGhostId,validateGhostManifest,+ type GhostManifest,type InstalledGhost,} from '../../shared/ghost.js';import type {+ MarketSourceConfig,+ MarketSourceSummary,PluginMarketDetail,PluginMarketItem,PluginMarketSnapshot,} from '../../shared/pluginMarket.js';+import {+ customMarketPluginId,+ customMarketReleaseId,+ marketSourceKey,+ parseCustomMarketPluginId,+} from '../../shared/pluginMarket.js';import { getCurrentUserId } from '../authManager.js';import {getGhostManager,@@ -37,16 +46,43 @@ import {import { getClientEndpoint } from '../clientEndpointsService.js';import { createLogger } from '../logger.js';import { throwIpcError } from '../utils/ipcValidate.js';+import {+ GHOST_MANIFEST_MAX_BYTES,+ readBoundedFileNoFollowSync,+} from '../utils/readBoundedFile.js';+import { withGhostInstallLock } from '../cindy-brain/ghostInstallLock.js';import { PluginMarketApi } from './api.js';import { downloadVerifiedPlugin } from './download.js';+import { installCustomMarketPlugin } from './install.js';import {PluginMarketLedger,+ ghostManifestDigest,type PluginMarketInstallationRecord,} from './ledger.js';+import type { DiscoveredMarketPlugin } from './sources/discover.js';+import { checkGitPreflight, type GitPreflightResult } from './sources/preflight.js';+import { MarketSourceManager } from './sources/index.js';+import { MarketSourceStore } from './sources/store.js';const log = createLogger('plugin-market');const NO_DUPLICATE_GHOST_IDS: ReadonlySet<string> = new Set();+/**+ * 来源增删改的互斥键。**安装的提交段(所有权复核 + 包落位)也要拿这把锁**:+ * 否则复核通过后、真正改动 Ghost 运行时之前,另一窗口能添加声明同一 ghostId 的+ * 来源,让已冲突的插件照样装上。+ *+ * **锁次序(不变量,违反即死锁)**:允许 `withMutation(pluginId)` 内再取本键+ * (安装路径就是这么做的),**禁止**持本键时再取任何 pluginId 键。来源操作+ * (add/remove/refresh)只拿本键,永不反向,因此锁图无环。+ *+ * **已知权衡**:refreshSource 全程持本键,大仓库 clone 期间(可达分钟级)安装的+ * 提交段与其它来源操作会排队。这是有意选择——只读路径(快照/列表/详情)不受+ * 影响,而把刷新的网络段移出锁会重新打开"提交点复核过期"的窗口;吞吐不构成+ * 放宽正确性的理由。+ */+const SOURCE_MUTATION_KEY = 'market-sources';+function captureMarketOwner(): ActiveAppSession {const session = getActiveAppSession();if (@@ -143,12 +179,68 @@ function ghostIdCounts(return counts;}+/** 自定义市场发现到的单个插件条目(快照投影的原料)。 */+interface CustomMarketEntry {+ config: MarketSourceConfig;+ plugin: DiscoveredMarketPlugin;+}++/** 服务端目录 + 自定义市场合并后的重复 ghostId 集合。 */+function combinedDuplicateGhostIds(+ plugins: readonly VisiblePluginSummary[],+ customEntries: readonly CustomMarketEntry[],+): ReadonlySet<string> {+ const counts = ghostIdCounts(plugins);+ for (const entry of customEntries) {+ counts.set(entry.plugin.ghostId, (counts.get(entry.plugin.ghostId) ?? 0) + 1);+ }+ return new Set(+ [...counts.entries()].filter(([, count]) => count > 1).map(([ghostId]) => ghostId),+ );+}++/**+ * 已安装插件的 locale 无关 manifest 摘要。运行时 `InstalledGhost.manifest` 是+ * **按当前界面语言本地化后的**(GhostManager.readInstalledLocalizedManifest),+ * 拿它算摘要会让"切换应用语言"被误判成"包被替换"。所以摘要一律来自安装目录的+ * 原始 ghost.json,并过同一 validateGhostManifest 再规范化——与写入侧(发现层的+ * plugin.manifest,同为校验器输出)同口径。读不出/校验不过返回 null,视为不匹配+ * (fail 向 conflict,安全方向)。+ */+/**+ * 展示投影用:剥掉控制字符(保留换行/制表)与双向文本控制符。只作用于送往+ * Renderer 的市场条目字段,不改动 manifest 本体(校验/摘要仍以原文为准)。+ */+function stripDirectionalControls(text: string): string {+ // eslint-disable-next-line no-control-regex+ return text.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '');+}++function installedGhostRawManifestDigest(dir: string): string | null {+ try {+ // 安装目录也可能被外部进程/同步盘改动,且本函数每次市场快照都会执行:+ // 与市场目录同一把单句柄限量闸,拒链接、超限即拒,不让无界字节进快照路径。+ const bytes = readBoundedFileNoFollowSync(+ path.join(dir, 'ghost.json'),+ GHOST_MANIFEST_MAX_BYTES,+ );+ if (bytes === null) return null;+ const raw = JSON.parse(bytes.toString('utf8')) as unknown;+ const validated = validateGhostManifest(raw);+ return validated.ok ? ghostManifestDigest(validated.manifest) : null;+ } catch {+ return null;+ }+}+/** 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>>;+ /** 每个已装插件的 locale 无关 manifest 摘要(一次快照只读一遍盘)。 */+ rawDigestByGhostId: ReadonlyMap<string, string | null>;}/**@@ -164,21 +256,44 @@ export class PluginMarketService {private readonly ledger = new PluginMarketLedger(() =>ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'),),+ private readonly sourceStore = new MarketSourceStore(() =>+ ownerScopedUserDataPath('plugin-market', 'sources.v1.json'),+ ),) {}async snapshot(): Promise<PluginMarketSnapshot> {- if (!getClientEndpoint('pluginApiBaseUrl')) {- return { items: [], unavailableReason: 'not-configured' };- }+ // 自定义市场项完全来自本地数据,不依赖服务端与登录态;服务端不可用时+ // 仍然返回,unavailableReason 只表达服务端部分的不可用。+ //+ // 自定义发现与服务端目录/账本必须在同一 owner 作用域内:先捕获 owner,+ // store/cloneRoot 绑定到它,跨 await 后用 generation 校验会话未切换,+ // 避免账号 A 的插件数据在切换窗口期被返回给账号 B 的 Renderer。let owner: ActiveAppSession;try {owner = captureMarketOwner();} catch {+ // 无稳定会话(未登录/切换中):无法可靠确定自定义数据该按哪个账号+ // 现查,返回空自定义项并标记原因,避免在切换窗口期把上一账号的+ // 插件数据返回给当前 Renderer。return {items: [],unavailableReason: isAppSessionBoundaryPending()? 'session-switching'- : 'authentication-required',+ : getClientEndpoint('pluginApiBaseUrl')+ ? 'authentication-required'+ : 'not-configured',+ customSourceNames: [],+ };+ }+ const { entries: customEntries, complete: customComplete } =+ await this.discoverCustomEntriesSafe(owner);+ const customSourceNames = this.customSourceNamesSafe(owner);+ requireSameMarketOwner(owner);+ if (!getClientEndpoint('pluginApiBaseUrl')) {+ return {+ items: this.projectCustomItems(customEntries),+ unavailableReason: customEntries.length > 0 ? null : 'not-configured',+ customSourceNames,};}let plugins: VisiblePluginSummary[];@@ -188,44 +303,79 @@ export class PluginMarketService {log.warn('market list unavailable', {error: error instanceof Error ? error.message : String(error),});+ // 本函数捕获 owner 后的每个 return 出口都必须先过 generation 校验:+ // listAll 失败(常因切号)时,不能把按旧账号发现的自定义项返回给当前会话。+ requireSameMarketOwner(owner);return {- items: [],+ items: this.projectCustomItems(customEntries),unavailableReason: error instanceof Error ? error.message : String(error),+ customSourceNames,};}requireSameMarketOwner(owner);const ledger = this.ledgerForOwner(owner);+ // ghostId 冲突判定跨服务端与自定义市场合并计算(全局唯一、先装先得)。+ // 必须**先于** applyDefaultInstalls 算出来:默认安装会真的下载并启用插件,+ // 若只按服务端目录判重,与自定义来源同 ghostId 的默认项会被静默抢占所有权,+ // 而列表随后又把它标成 conflict —— 既定事实已经发生。+ const duplicateGhostIds = combinedDuplicateGhostIds(plugins, customEntries);await this.adoptLegacyInstallations(plugins, ledger, owner);await this.reconcileRemovedInstallations(ledger, owner);- await this.applyDefaultInstalls(plugins, owner, ledger);+ // 自定义目录不完整(某来源暂时不可读)时跳过全部默认安装:此刻的合并冲突+ // 集合缺了坏来源声明的 ghostId,自动安装会在它恢复前抢占所有权。+ if (customComplete) {+ await this.applyDefaultInstalls(plugins, owner, ledger, duplicateGhostIds);+ } else {+ log.warn('skipping default installs: custom marketplace catalog is incomplete');+ }+ requireSameMarketOwner(owner);+ const local = this.localInstallSnapshot(ledger);+ const serverItems = plugins.map((plugin) =>+ this.toItem(plugin, duplicateGhostIds, local),+ );+ const items = [...serverItems, ...this.projectCustomItems(customEntries, duplicateGhostIds, local)];+ // 聚合完成、返回 Renderer 前最后校验:账号在任一 await 间隙漂移则拒绝,+ // 不把按旧账号解析的自定义项/账本状态发给当前会话。requireSameMarketOwner(owner);- return { items: this.toItems(plugins, ledger), unavailableReason: null };+ return {+ items,+ unavailableReason: null,+ customSourceNames,+ };}async detail(pluginId: string): Promise<PluginMarketDetail> {+ // 自定义市场插件走本地发现,不要求服务端可用,也不受 CUID 形状约束。+ const customRef = parseCustomMarketPluginId(pluginId);+ if (customRef) return this.customDetail(customRef);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,- };+ return this.runForOwner(async (owner) => {+ 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');+ }+ // 详情必须与列表同口径:传空重复集合会把列表标为 conflict 并禁用的项+ // 在详情页恢复成可安装,给出一条绕过冲突闸的入口。+ const { duplicates } = await this.crossSourceDuplicateGhostIds(owner);+ requireSameMarketOwner(owner);+ return {+ ...this.toItem(+ plugin,+ duplicates,+ this.localInstallSnapshot(this.ledgerForOwner(owner)),+ ),+ manifest: compatible.manifest,+ };+ });}async install(@@ -234,9 +384,18 @@ export class PluginMarketService {/** Renderer 确认框实际展示过的 release。Main 重拉详情后必须仍一致,* 否则用户审阅 A、实际安装/启用 B(review P1)。 */expectedReleaseId: string;+ /** 自定义市场插件:Renderer 确认框实际审阅过的完整 manifest。 */+ expectedManifest?: GhostManifest;allowPermissionExpansion?: boolean;},): Promise<{ ghost: InstalledGhost }> {+ const customRef = parseCustomMarketPluginId(pluginId);+ if (customRef) {+ if (!options.expectedManifest) {+ throwIpcError('INVALID_PARAMS', 'The reviewed Plugin manifest is required');+ }+ return this.customInstall(customRef, options as typeof options & { expectedManifest: GhostManifest });+ }if (!isValidPluginResourceId(pluginId)) {throwIpcError('INVALID_PARAMS', 'Invalid Plugin ID');}@@ -267,12 +426,30 @@ export class PluginMarketService {const existing = getGhostManager().list().some((ghost) => ghost.manifest.id === plugin.ghostId);+ // 上面只查了服务端目录内部重名。列表的 conflict 判定是"服务端 + 全部自定义+ // 来源"合并计数,这里必须用同一口径重算,否则被标为 conflict 并禁用的服务端+ // 项仍能经普通 UI 流程或直接 IPC 装进来并抢占 ghostId。+ const record = ledger.installationForGhost(plugin.ghostId);+ const ownsInstall = Boolean(+ existing && record?.installed && record.pluginId === plugin.id,+ );+ const assertOwnership = () =>+ this.assertSourceOwnsGhostId({+ owner,+ ghostId: plugin.ghostId,+ ownsInstall,+ // 复用已拉到的目录,复核不再多打一次网络请求。+ knownServerPlugins: catalog,+ });+ await assertOwnership();return {ghost: await this.installDetail(plugin,{expectedInstalled: existing,allowPermissionExpansion: options.allowPermissionExpansion === true,+ // 下载可能持续数分钟,提交副作用前按当前事实再算一次。+ recheckOwnership: assertOwnership,},owner,ledger,@@ -282,7 +459,11 @@ export class PluginMarketService {}async uninstall(pluginId: string): Promise<{ ok: true }> {- if (!isValidPluginResourceId(pluginId)) {+ // 自定义市场插件的卸载走同一账本路径,仅跳过服务端 CUID 形状校验。+ if (+ !parseCustomMarketPluginId(pluginId) &&+ !isValidPluginResourceId(pluginId)+ ) {throwIpcError('INVALID_PARAMS', 'Invalid Plugin ID');}const owner = captureMarketOwner();@@ -340,12 +521,530 @@ export class PluginMarketService {};}+ /* ---------------------------------------------------------------------- */+ /* 自定义市场源(Git / 本地文件夹) */+ /* ---------------------------------------------------------------------- */++ async listSources(): Promise<MarketSourceSummary[]> {+ return this.runForOwner((owner) => this.sourceManagerForOwner(owner).listSources());+ }++ async addSource(input: {+ source: string;+ ref?: string;+ sparsePaths?: string[];+ }): Promise<MarketSourceSummary> {+ // 源管理操作全局串行:添加期间发现的市场名必须唯一,并行添加会互相覆盖。+ return this.runForOwner((owner) =>+ this.withMutation(SOURCE_MUTATION_KEY, async () => {+ requireSameMarketOwner(owner);+ return this.sourceManagerForOwner(owner).addSource(input);+ }),+ );+ }++ /**+ * 经 Main 侧原生目录选择器添加本地市场来源。+ *+ * 本地目录的授权必须来自**用户在原生对话框里的选择**,而不是 Renderer 传来的+ * 绝对路径——Renderer 被 XSS 控制时,任何"它自己报的路径"都不构成用户授权+ * (electron-security 规则:不把 Renderer 路径当授权)。`defaultPath` 只是原生+ * 框的初始定位提示,不参与授权判定;用户在框里选中哪个目录,授权就是哪个。+ */+ async addLocalSourceFromPicker(+ defaultPath?: string,+ ): Promise<{ canceled: true } | { canceled: false; summary: MarketSourceSummary }> {+ // owner 在**打开选择器之前**捕获:原生框可以开着很久,期间切号的话,+ // 选完再捕获会把账户 A 发起的选择持久化进账户 B 的 store。返回后先校验+ // 同一代际,漂移即拒,再让 addSource 在同一 owner 下落盘。+ const owner = captureMarketOwner();+ const picked = await dialog.showOpenDialog({+ properties: ['openDirectory'],+ ...(defaultPath ? { defaultPath } : {}),+ });+ const dir = picked.filePaths[0];+ if (picked.canceled || !dir) return { canceled: true };+ requireSameMarketOwner(owner);+ return { canceled: false, summary: await this.addSource({ source: dir }) };+ }++ async removeSource(name: string): Promise<{ ok: true }> {+ return this.runForOwner((owner) =>+ this.withMutation(SOURCE_MUTATION_KEY, async () => {+ requireSameMarketOwner(owner);+ return this.sourceManagerForOwner(owner).removeSource(name);+ }),+ );+ }++ async refreshSource(name: string): Promise<MarketSourceSummary> {+ return this.runForOwner((owner) =>+ this.withMutation(SOURCE_MUTATION_KEY, async () => {+ requireSameMarketOwner(owner);+ return this.sourceManagerForOwner(owner).refreshSource(name);+ }),+ );+ }++ async gitPreflight(): Promise<GitPreflightResult> {+ return checkGitPreflight();+ }++ /** 自定义市场插件详情:本地发现现查,不要求服务端市场可用。 */+ private async customDetail(ref: {+ marketName: string;+ ghostId: string;+ }): Promise<PluginMarketDetail> {+ return this.runForOwner(async (owner) => {+ const manager = this.sourceManagerForOwner(owner);+ const discovered = await manager.discoverSource(ref.marketName);+ if (!discovered.result.ok) {+ throwIpcError(discovered.result.code, discovered.result.detail ?? discovered.result.code);+ }+ const plugin = discovered.result.marketplace.plugins.find(+ (candidate) => candidate.ghostId === ref.ghostId,+ );+ if (!plugin) {+ throwIpcError('NOT_FOUND', 'The Plugin is no longer listed by this marketplace');+ }+ // 与服务端详情同理:详情必须沿用列表的 conflict 口径,不能传空重复集合。+ const { duplicates } = await this.crossSourceDuplicateGhostIds(owner);+ requireSameMarketOwner(owner);+ return {+ ...this.customToItem(+ { config: discovered.config, plugin },+ duplicates,+ this.localInstallSnapshot(this.ledgerForOwner(owner)),+ ),+ manifest: plugin.manifest,+ };+ });+ }++ /**+ * 按 snapshot 的同一口径重算跨来源重复 ghostId(服务端目录 + 全部自定义来源)。+ * 详情与安装都用它,保证"列表标成 conflict 并禁用"的判定不会在别处被放宽。+ *+ * 服务端目录可选:未配置或拉取失败时降级为仅自定义来源,并把 `serverKnown`+ * 置为 false 供调用方判断。自定义安装本就不要求服务端可用;未安装的服务端插件+ * 不构成本地运行期抢占,已安装的那种情况由安装侧的 `existing` 检查拦住。+ */+ private async crossSourceDuplicateGhostIds(+ owner: ActiveAppSession,+ knownServerPlugins?: readonly VisiblePluginSummary[],+ ): Promise<{ duplicates: ReadonlySet<string>; serverKnown: boolean; customComplete: boolean }> {+ const { entries: customEntries, complete: customComplete } =+ await this.discoverCustomEntriesSafe(owner);+ let serverPlugins: readonly VisiblePluginSummary[] = knownServerPlugins ?? [];+ let serverKnown = knownServerPlugins !== undefined;+ if (!serverKnown && getClientEndpoint('pluginApiBaseUrl')) {+ try {+ serverPlugins = visiblePluginsForOwner(owner, await this.api.listAll());+ serverKnown = true;+ } catch (error) {+ log.warn('market catalog unavailable while recomputing cross-source duplicates', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ requireSameMarketOwner(owner);+ return {+ duplicates: combinedDuplicateGhostIds(serverPlugins, customEntries),+ serverKnown,+ customComplete,+ };+ }++ /**+ * 安装入口重算 ghostId 所有权:列表把跨来源重名标成 `conflict` 并禁用,但那份+ * 判定是快照期算的。安装 IPC 可以被不可信 Renderer 直接调用,也可能在详情打开+ * 后由另一个窗口添加了声明同一 ghostId 的来源 —— 所以真正产生副作用之前必须+ * 用同一口径重新确认。服务端与自定义两条安装路径共用这道闸。+ */+ private async assertSourceOwnsGhostId(input: {+ owner: ActiveAppSession;+ ghostId: string;+ ownsInstall: boolean;+ knownServerPlugins?: readonly VisiblePluginSummary[];+ }): Promise<void> {+ // 已经拥有当前安装记录的来源保留所有权(先装先得,与列表判定一致)。+ if (input.ownsInstall) return;+ const { duplicates, customComplete } = await this.crossSourceDuplicateGhostIds(+ input.owner,+ input.knownServerPlugins,+ );+ // 任一来源暂时不可读时,冲突集合是不完整的——此刻放行安装会在坏来源恢复前+ // 抢占它声明的 ghostId(先装先得被绕过)。fail closed:提示先修复或移除。+ if (!customComplete) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'A marketplace source is unavailable; refresh or remove it before installing',+ );+ }+ if (duplicates.has(input.ghostId)) {+ throwIpcError('ALREADY_EXISTS', 'Another marketplace already provides this Plugin ID');+ }+ }++ /**+ * 自定义市场插件安装/更新。与服务端 installDetail 同一组防线:+ * release 一致性(重发现后比对 expectedReleaseId)、冲突先装先得、+ * 权限扩张显式确认;打包与装入复用 installOrUpdateMarketGhostPackage。+ *+ * 全程在 `withDiscoveredSource` 租约内执行:`plugin.dir` 指向 Git 源的缓存版本+ * 目录,打包要逐文件读它。租约必须一直持到打包结束,否则并发刷新的清理能在+ * 打包途中删掉该目录(安装随机失败或产物残缺)。+ */+ private async customInstall(+ ref: { marketName: string; ghostId: string },+ options: { expectedReleaseId: string; expectedManifest: GhostManifest; allowPermissionExpansion?: boolean },+ ): Promise<{ ghost: InstalledGhost }> {+ const owner = captureMarketOwner();+ const ledger = this.ledgerForOwner(owner);+ const manager = this.sourceManagerForOwner(owner);+ // 互斥键与 uninstall 一致使用规范化 pluginId,保证同插件的安装/更新/卸载串行。+ return this.withMutation(customMarketPluginId(ref.marketName, ref.ghostId), async () => {+ requireSameMarketOwner(owner);+ return manager.withDiscoveredSource(ref.marketName, async (discovered) => {+ if (!discovered.result.ok) {+ throwIpcError(discovered.result.code, discovered.result.detail ?? discovered.result.code);+ }+ const plugin = discovered.result.marketplace.plugins.find(+ (candidate) => candidate.ghostId === ref.ghostId,+ );+ if (!plugin) {+ throwIpcError('NOT_FOUND', 'The Plugin is no longer listed by this marketplace');+ }+ const pluginId = customMarketPluginId(ref.marketName, plugin.ghostId);+ const releaseId = customMarketReleaseId(ref.marketName, plugin.ghostId, plugin.version);+ if (releaseId !== options.expectedReleaseId) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'Plugin release changed after permission review',+ );+ }+ const existing = getGhostManager()+ .list()+ .find((ghost) => ghost.manifest.id === plugin.ghostId);+ const currentRecord = ledger.installationForGhost(plugin.ghostId);+ // 所有权 = pluginId、来源指纹、安装时 manifest 摘要**同时**对上。市场名+ // 可复用(同名异源重加得到相同 pluginId);运行时的包在降级窗口可被旧版+ // 换成本地安装的任何东西(旧版不认识 custom 账本,不会更新它)——只凭+ // 记录存在就认领,会把别人的包错误归属给本来源并放行其更新覆盖。+ const sourceKey = marketSourceKey(discovered.config.source);+ // 审阅时刻的已装内容摘要:所有权/收养判定与提交段复核共用同一份快照。+ const reviewInstalledDigest = existing+ ? installedGhostRawManifestDigest(existing.dir)+ : null;+ const ownsInstall = Boolean(+ existing &&+ currentRecord?.installed &&+ currentRecord.pluginId === pluginId &&+ currentRecord.sourceKey === sourceKey &&+ currentRecord.manifestDigest != null &&+ currentRecord.manifestDigest === reviewInstalledDigest,+ );+ // 收养:运行时已装内容的声明与本来源候选**完全一致**(原始 manifest 摘要+ // 相等)时,允许在没有有效账本记录的情况下重装并补写溯源。这是"包已落位+ // 但账本写失败"(文件锁/磁盘错)后的唯一自愈入口——否则该插件永久 conflict、+ // 更新永被拒。安全性:收养走完整重装,落位字节来自本来源的包,且用户刚在+ // 确认框审阅过同一份 manifest;声明有任何差异都收养不了。+ const adoptable = Boolean(+ existing &&+ !ownsInstall &&+ reviewInstalledDigest === ghostManifestDigest(plugin.manifest),+ );+ if (existing && !ownsInstall && !adoptable) {+ throwIpcError('ALREADY_EXISTS', 'A local Plugin already uses this Plugin ID');+ }+ await this.assertSourceOwnsGhostId({ owner, ghostId: plugin.ghostId, ownsInstall });+ if (+ existing &&+ // 与服务端安装同口径:对比已装 manifest 与候选包,只有新增权限才要求+ // 显式确认(upstream 已回退批准 receipt 基线,这里跟随主干口径)。+ diffGhostPermissionItems(existing.manifest, plugin.manifest).added.length > 0 &&+ options.allowPermissionExpansion !== true+ ) {+ throwIpcError('PRECONDITION_FAILED', 'Plugin permissions changed and require review');+ }+ requireSameMarketOwner(owner);+ const ghost = await installCustomMarketPlugin({+ pluginDir: plugin.dir,+ expected: options.expectedManifest,+ // 打包耗时,期间另一窗口可以经独立的 market-sources 互斥键添加声明同一+ // ghostId 的来源(来源变更与插件安装不共享互斥边界)。所以在真正改动+ // Ghost 运行时之前把所有权再算一遍,而不是只依赖打包前那一次。+ beforeCommit: async () => {+ requireSameMarketOwner(owner);+ // 所选来源必须**仍然存在且仍是同一个来源**:移除来源会先拿+ // SOURCE_MUTATION_KEY 删掉配置,租约只保住了目录字节;没有这道核对,+ // 安装会把一个已经没有对应来源的包装进运行时并写下孤儿账本记录。+ // 同名异源的重加也在这里被指纹拦下。+ const live = manager.getConfig(ref.marketName);+ if (!live || marketSourceKey(live.source) !== sourceKey) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'The marketplace source changed during the install',+ );+ }+ await this.assertSourceOwnsGhostId({ owner, ghostId: plugin.ghostId, ownsInstall });+ // runtime 所有权也要复核,不只来源所有权:打包窗口(秒到分钟级)内,+ // 本地插件页可以卸载同 id 插件(那条路径不持本服务的互斥锁)——不查+ // 会把"更新"降级成"首装+带电启用";反向地,窗口内新装入的同 id+ // 本地 .cindy 会被更新分支静默覆盖,还绕过了审阅时跳过的权限 diff。+ // 判据与审阅时刻同一份:在场状态一致 + 已装内容摘要未变。+ const current = getGhostManager()+ .list()+ .find((ghost) => ghost.manifest.id === plugin.ghostId);+ if (Boolean(current) !== Boolean(existing)) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ current+ ? 'A local Plugin appeared with this Plugin ID during the install'+ : 'Plugin was uninstalled while the install was packaging',+ );+ }+ if (current && installedGhostRawManifestDigest(current.dir) !== reviewInstalledDigest) {+ throwIpcError('PRECONDITION_FAILED', 'Installed Plugin changed during the install');+ }+ },+ // 复核与落位的双重互斥:+ // - SOURCE_MUTATION_KEY:beforeCommit 返回后包检查还要跑一段,期间不能+ // 让来源被增删,否则复核结论在落位前过期。+ // - withGhostInstallLock(ghostId):与本地 .cindy 装入/更新/卸载共用同一+ // 按 id 互斥,beforeCommit 的 runtime 复核到 installOrUpdate 落位之间,+ // 同 id 的本地装入/卸载插不进来(否则复核仍会在落位前过期)。+ withCommitLock: (fn) =>+ this.withMutation(SOURCE_MUTATION_KEY, () =>+ withGhostInstallLock(plugin.ghostId, fn),+ ),+ // 溯源写入仍在上面那把 ghost 锁内(afterCommit 由 commit 段调用):+ // 放到锁外时,本地装入能插在"包已落位"与"写下溯源"之间换掉同 id 的包。+ // 锁序:pluginId → SOURCE_MUTATION_KEY → ghostId → ledgerMutation。+ afterCommit: async () => {+ await this.withCapturedLedgerMutation(ledger, () => {+ ledger.upsertInstallation({+ pluginId,+ ghostId: plugin.ghostId,+ releaseId,+ version: plugin.version,+ // 自定义源没有服务端内容哈希;占位值如实表达"未经内容校验"。+ sha256: 'custom-unverified',+ scope: 'public',+ organizationId: null,+ source: discovered.config.source.type === 'git' ? 'git-market' : 'local-market',+ installed: true,+ updatedAt: new Date().toISOString(),+ // 来源指纹与 pluginId 一起构成所有权:同名异源的重加对不上它。+ sourceKey,+ // 落位那一刻的 manifest 摘要:降级期间运行时被换成别的包后,认领+ // 对不上摘要即失效。摘要来自发现层的原始 manifest(校验器输出),+ // **不是**安装返回的 ghost.manifest——后者按当前界面语言本地化过,+ // 切语言会被误判成包被替换。+ manifestDigest: ghostManifestDigest(plugin.manifest),+ });+ });+ },+ });+ return { ghost };+ });+ });+ }++ /** 已配置来源名(按添加顺序);存储读取失败时降级为空数组。 */+ private customSourceNamesSafe(owner?: ActiveAppSession): string[] {+ try {+ // 与 sourceManagerForOwner/ledgerForOwner 同一约定:先确认会话没漂移,+ // 再按 owner 解析路径——否则切号窗口里会读到新账号的 sources.v1.json。+ if (owner) requireSameMarketOwner(owner);+ const store = owner+ ? this.sourceStore.bind(ownerScopedUserDataPath('plugin-market', 'sources.v1.json'))+ : this.sourceStore;+ return store.list().map((source) => source.name);+ } catch {+ return [];+ }+ }++ /** 快照聚合用:发现全部自定义市场条目。任何失败都降级为空,不拖垮快照。 */+ private async discoverCustomEntriesSafe(+ owner?: ActiveAppSession,+ ): Promise<{ entries: CustomMarketEntry[]; complete: boolean }> {+ try {+ const manager = owner+ ? this.sourceManagerForOwner(owner)+ : new MarketSourceManager({+ store: this.sourceStore,+ cloneRoot: ownerScopedUserDataPath('plugin-market', 'sources'),+ });+ const discovered = await manager.discoverAll();+ const entries: CustomMarketEntry[] = [];+ // "目录不完整"与"来源确实为空"必须分开:任一来源发现失败时,合并冲突集合+ // 缺了它声明的 ghostId,自动安装/所有权提交会在它暂时不可读的窗口里抢占+ // 先装先得。展示照旧容错(单源失败不拖垮列表),但 complete=false 要让+ // 写路径 fail closed。+ let complete = true;+ for (const { config, result } of discovered) {+ if (!result.ok) {+ complete = false;+ log.warn('custom marketplace discovery failed', {+ market: config.name,+ code: result.code,+ });+ continue;+ }+ // 粒度到条目的同一口径:某个插件的 ghost.json 暂时读不到(文件锁/网络盘+ // 抖动/权限)时,这个市场声明了哪些 ghostId 就给不出完整答案——展示照旧+ // 容错,但写路径必须 fail closed,否则同 ghostId 的默认安装会在这个窗口+ // 里抢占所有权,恢复后该插件永久 conflict。内容非法(skippedCount)不算。+ if (result.marketplace.unreadableCount > 0) {+ complete = false;+ log.warn('custom marketplace has unreadable plugin entries', {+ market: config.name,+ unreadableCount: result.marketplace.unreadableCount,+ });+ }+ for (const plugin of result.marketplace.plugins) {+ entries.push({ config, plugin });+ }+ }+ return { entries, complete };+ } catch (error) {+ log.warn('custom marketplace enumeration failed', {+ error: error instanceof Error ? error.message : String(error),+ });+ return { entries: [], complete: false };+ }+ }++ private projectCustomItems(+ entries: readonly CustomMarketEntry[],+ duplicateGhostIds?: ReadonlySet<string>,+ local?: LocalInstallSnapshot,+ ): PluginMarketItem[] {+ const duplicates =+ duplicateGhostIds ?? combinedDuplicateGhostIds([], entries);+ const snapshot = local ?? this.localInstallSnapshot();+ return entries.map((entry) => this.customToItem(entry, duplicates, snapshot));+ }++ /** 自定义市场项的状态机与服务端 toItem 完全一致(冲突 / 首装 / 更新 / 已装)。 */+ private customToItem(+ entry: CustomMarketEntry,+ duplicateGhostIds: ReadonlySet<string>,+ local: LocalInstallSnapshot,+ ): PluginMarketItem {+ const { config, plugin } = entry;+ const pluginId = customMarketPluginId(config.name, plugin.ghostId);+ const releaseId = customMarketReleaseId(config.name, plugin.ghostId, plugin.version);+ const ghost = local.ghostsById.get(plugin.ghostId);+ const record = local.installations[plugin.ghostId];+ // 所有权 = pluginId + 来源指纹 + 安装时 manifest 摘要都对上,与 customInstall+ // 同口径:同名异源的重加、降级期间被本地替换的包,都不是所有者,列表如实标+ // conflict 而不是 update-available。+ const ownsInstall = Boolean(+ ghost &&+ record?.installed &&+ record.pluginId === pluginId &&+ record.sourceKey === marketSourceKey(config.source) &&+ record.manifestDigest != null &&+ record.manifestDigest === local.rawDigestByGhostId.get(plugin.ghostId),+ );+ // 收养口径与 customInstall 一致:运行时内容声明与候选完全一致时不标 conflict,+ // 投影成可安装——这是账本写失败后的自愈入口(conflict 在 UI 被禁用,没有它+ // 用户连重试的按钮都没有)。+ const adoptable = Boolean(+ ghost &&+ !ownsInstall &&+ local.rawDigestByGhostId.get(plugin.ghostId) === ghostManifestDigest(plugin.manifest),+ );+ // 已拥有当前安装记录的来源保留所有权(installed / update-available);+ // duplicate 只把未拥有安装的竞争来源标为冲突,避免“先装先得”被降格。+ const conflict = Boolean(+ (duplicateGhostIds.has(plugin.ghostId) && !ownsInstall) ||+ (ghost && !ownsInstall && !adoptable),+ );+ const installState: PluginMarketItem['installState'] = conflict+ ? 'conflict'+ : !ownsInstall+ ? 'not-installed'+ : record?.releaseId === releaseId+ ? 'installed'+ : 'update-available';+ return {+ pluginId,+ ghostId: plugin.ghostId,+ // ghost.json 来自不受信市场仓库:双向控制符可把市场卡片上的署名/说明+ // 显示成另一副样子(视觉欺骗),控制字符可撑破布局。展示投影一律剥掉+ // (保留换行);市场名闸在 discover,这里补齐插件侧同一口径。+ name: stripDirectionalControls(plugin.manifest.name),+ description: plugin.manifest.description != null+ ? stripDirectionalControls(plugin.manifest.description)+ : null,+ author: plugin.manifest.author != null+ ? stripDirectionalControls(plugin.manifest.author)+ : null,+ // scope 是服务端授权概念,自定义市场项无服务端身份;展示层按 sourceType 分流。+ scope: 'public',+ organizationId: null,+ defaultInstall: false,+ releaseId,+ version: plugin.version,+ publishedAt: config.lastSyncedAt ?? config.addedAt,+ icon: null,+ installState,+ enabled: ownsInstall ? (ghost?.enabled ?? null) : null,+ sourceType: config.source.type === 'git' ? 'git-market' : 'local-market',+ sourceMarketName: config.name,+ };+ }++ /**+ * owner 绑定执行 + 返回前漂移校验。所有把市场数据返回 Renderer 或改动+ * 运行时的 owner-bound 导出方法统一走此闸:账号在 await 间隙切换则拒绝,+ * 不把上一账号的 URL/路径/manifest/summary 发给当前 Renderer,也不让+ * 写操作落在错误账户。新增 owner-bound 方法只允许经此入口,从结构上+ * 杜绝逐路径漏加 generation 校验。+ */+ private async runForOwner<T>(+ operation: (owner: ActiveAppSession) => Promise<T>,+ ): Promise<T> {+ const owner = captureMarketOwner();+ let result: T;+ try {+ result = await operation(owner);+ } catch (error) {+ // 异常出口同样要校验代际:git 类错误的 detail 刻意保留了仓库 URL 等+ // 上一账号的私有信息,操作期间切了号就不能把它交给当前 Renderer——+ // 统一替换成账号漂移错误,原始失败对当前会话本来就没有意义。+ requireSameMarketOwner(owner);+ throw error;+ }+ requireSameMarketOwner(owner);+ return result;+ }++ private sourceManagerForOwner(owner: ActiveAppSession): MarketSourceManager {+ requireSameMarketOwner(owner);+ return new MarketSourceManager({+ store: this.sourceStore.bind(+ ownerScopedUserDataPath('plugin-market', 'sources.v1.json'),+ ),+ cloneRoot: ownerScopedUserDataPath('plugin-market', 'sources'),+ });+ }+private async installDetail(plugin: VisiblePluginDetail,options: {allowPermissionExpansion?: boolean;/** 确认操作时的安装意图;下载窗口期目标被另一窗口卸载时拒绝滑入首装。 */expectedInstalled: boolean;+ /**+ * 提交副作用前的所有权复核。下载可能持续数分钟,期间另一窗口可经独立的+ * market-sources 互斥键添加声明同一 ghostId 的来源,入口处那次判定已过期。+ */+ recheckOwnership?: () => Promise<void>;} = { expectedInstalled: false },owner = captureMarketOwner(),ledger = this.ledgerForOwner(owner),@@ -406,18 +1105,36 @@ export class PluginMarketService {);}}- // 市场首装一律装完即开(2026-07-26 定案,见 installOrUpdateMarketGhostPackage);- // 已装过则走原位更新,唤醒/沉睡状态延续当前值。- const ghost = await installOrUpdateMarketGhostPackage(tempPath, {- ghostId: plugin.ghostId,- version: plugin.currentRelease.version,- });- // 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'));- });+ // 复核 + 落位 + 溯源写入在同一对锁内完成:+ // - SOURCE_MUTATION_KEY:`installOrUpdateMarketGhostPackage` 会先 await 包+ // 检查才开始改动运行时,复核若在锁外做,结论会在这段等待里过期。+ // - withGhostInstallLock(ghostId):与本地 .cindy 装入/更新/卸载共用同一按 id+ // 互斥。少了它,本地装入能在包检查窗口里落入同 id 的包,随后被本次安装当作+ // 更新目标覆盖,而权限差异确认因审阅时目标不存在而没跑过。账本写入也必须在+ // 锁内:否则本地装入可以插在"落位"与"写溯源"之间,让账本认领一个其实已被+ // 替换掉的包(服务端记录不带 manifestDigest,投影时判不出来)。+ // 锁序:pluginId → SOURCE_MUTATION_KEY → ghostId → ledgerMutation,不可反向。+ const ghost = await this.withMutation(SOURCE_MUTATION_KEY, () =>+ withGhostInstallLock(plugin.ghostId, async () => {+ // 改动 Ghost 运行时之前的最后一道:跨来源 ghostId 所有权按当前事实重算。+ await options.recheckOwnership?.();+ requireSameMarketOwner(owner);+ // 市场首装一律装完即开(2026-07-26 定案,见 installOrUpdateMarketGhostPackage);+ // 已装过则走原位更新,唤醒/沉睡状态延续当前值。+ const installed = await installOrUpdateMarketGhostPackage(tempPath, {+ ghostId: plugin.ghostId,+ version: plugin.currentRelease.version,+ });+ // 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 installed;+ }),+ );return ghost;} finally {await fs.promises.rm(tempPath, { force: true }).catch(() => undefined);@@ -430,20 +1147,6 @@ export class PluginMarketService {}}- 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,@@ -454,8 +1157,11 @@ export class PluginMarketService {const ownsInstall = Boolean(ghost && record?.installed && record.pluginId === plugin.id,);+ // 与自定义侧 customToItem 对齐:已拥有当前安装记录的来源保留所有权+ // (installed / update-available),duplicate 只标未拥有安装的竞争来源,+ // 避免先安装者被重复 ghostId 降格、失去更新入口。const conflict = Boolean(- duplicateGhostIds.has(plugin.ghostId) ||+ (duplicateGhostIds.has(plugin.ghostId) && !ownsInstall) ||(ghost && (!record?.installed || record.pluginId !== plugin.id)),);const installState: PluginMarketItem['installState'] = conflict@@ -480,6 +1186,8 @@ export class PluginMarketService {icon: plugin.currentRelease.icon,installState,enabled: ownsInstall ? (ghost?.enabled ?? null) : null,+ sourceType: 'server',+ sourceMarketName: null,};}@@ -517,16 +1225,19 @@ export class PluginMarketService {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);- });- }+ if (!record.installed) continue;+ await this.withLedgerMutation(owner, () => {+ // 在场判定必须与写入同处一把锁内且即时重取:manager.update 的两次+ // rename 之间 ghosts/<id> 短暂不存在,锁外的一次性快照会把这类瞬态+ // 误判成"已卸载",把 pluginId 永久写进 defaultInstallOptOuts,该+ // 默认安装插件从此不再自动装回。+ const stillInstalled = getGhostManager()+ .list()+ .some((ghost) => ghost.manifest.id === record.ghostId);+ if (!stillInstalled) ledger.markRemoved(record.ghostId, installSubject);+ });}}@@ -534,6 +1245,8 @@ export class PluginMarketService {plugins: readonly VisiblePluginSummary[],owner: ActiveAppSession,ledger: PluginMarketLedger,+ /** 服务端 + 全部自定义来源合并算出的重复 ghostId;命中的默认项一律跳过。 */+ duplicateGhostIds: ReadonlySet<string>,): Promise<void> {const installSubject = defaultInstallSubject(owner);const counts = ghostIdCounts(plugins);@@ -546,9 +1259,12 @@ export class PluginMarketService {const local = this.localInstallSnapshot(ledger, ledgerData.installations);for (const summary of plugins) {if (!summary.defaultInstall || !uniqueGhostIds.has(summary.ghostId)) continue;+ // 跨来源重名:自动安装会替用户做出"服务端胜出"的抢占决定,必须交回用户手动+ // 处置(列表把两边都标成 conflict)。+ if (duplicateGhostIds.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;+ const state = this.toItem(summary, duplicateGhostIds, local).installState;if (state !== 'not-installed') continue;try {await this.withMutation(summary.id, async () => {@@ -557,7 +1273,18 @@ export class PluginMarketService {// 装完即开语义已收敛进市场安装入口本身,这里无需再显式声明。await this.installDetail(detail,- { expectedInstalled: false },+ {+ expectedInstalled: false,+ // 默认安装同样有下载窗口:提交前按当前事实重算跨来源所有权,+ // 复用已有的服务端目录,不额外打网络请求。+ recheckOwnership: () =>+ this.assertSourceOwnsGhostId({+ owner,+ ghostId: summary.ghostId,+ ownsInstall: false,+ knownServerPlugins: plugins,+ }),+ },owner,ledger,);@@ -576,11 +1303,13 @@ export class PluginMarketService {ledger = this.ledger,installations = ledger.read().installations,): LocalInstallSnapshot {+ const ghosts = getGhostManager().list();return {- ghostsById: new Map(- getGhostManager().list().map((ghost) => [ghost.manifest.id, ghost]),- ),+ ghostsById: new Map(ghosts.map((ghost) => [ghost.manifest.id, ghost])),installations,+ rawDigestByGhostId: new Map(+ ghosts.map((ghost) => [ghost.manifest.id, installedGhostRawManifestDigest(ghost.dir)]),+ ),};}diff --git a/apps/desktop/src/main/plugin-market/sources/cacheLease.ts b/apps/desktop/src/main/plugin-market/sources/cacheLease.tsnew file mode 100644index 0000000000..639e8556e9--- /dev/null+++ b/apps/desktop/src/main/plugin-market/sources/cacheLease.ts@@ -0,0 +1,174 @@+/**+ * 市场缓存目录的租约与**唯一删除入口**。+ *+ * 为什么单独成模块:这块此前反复出问题,每一轮都是"又发现一个删除点没查租约"+ * ——交换旧目录、清理历史版本、清理暂存目录、移除来源、失败回滚,各自直接+ * `fs.rm`。只要删除动作散落在多个调用点,租约就是"可选的",总会有下一个漏掉的+ * 点。把删除收口到这里,并让 `sources/index.ts` 不再直接调用 `fs.rm`,+ * "删掉正在被读的路径"才从结构上不可能发生,而不是靠每个调用点自觉。+ *+ * 判据只有一条(`overlaps`):目标路径与任何持有中的租约**在任一方向上重叠**时+ * 不删,推迟到最后一个相关租约释放。三种历史事故都落在这一条里:+ * - 清理删掉正在被读的版本目录 → 租约 === 目标+ * - 移除来源整槽递归删,而槽内某版本在读 → 租约在目标之下+ * - 清理删掉 git 的 `<dest>.staging-*` → 目标在租约"之下"(字符串前缀)+ *+ * 前缀按**字符串**比较而不是路径分段:git clone 的暂存目录是目标的兄弟+ * (`<dest>.staging-<uuid>`),分段比较盖不住它。代价是极端情况下会把名字恰好以+ * 某个租约全文开头的无关目录判成"在用"——后果仅是该目录晚一点被清理(纯磁盘),+ * 永远不会导致误删。+ *+ * 字符串比较是**大小写敏感**的,而 Windows/macOS 文件系统通常不敏感。这里安全的+ * 前提是:所有缓存路径都由同一套代码派生(ownerScopedUserDataPath + marketCloneSlug,+ * slug 全小写),同一目录永远以同一写法出现。新调用方不得传入手工拼写或改过大小写+ * 的路径。+ *+ * 仅在 main 进程内有效(同一 userData 只有一个 main 进程,Electron 单实例)。+ * 按绝对路径为键,因此 owner 隔离由路径自带(`ownerScopedUserDataPath` 已把+ * owner 编进 cloneRoot),也不受"每次操作都新建 MarketSourceManager"影响。+ */+import fs from 'node:fs';++/** 持有中的租约:绝对路径 → 引用数。 */+const leases = new Map<string, number>();++/** 因租约冲突被推迟的删除:绝对路径 → 执行前的最后一道否决条件。 */+const deferred = new Map<string, DeferredRemoval>();++/**+ * 已经启动、尚未结束的删除:绝对路径 → 该删除的 Promise。+ * `skipIf` 只能挡住"还没开始"的删除;已经在跑的那笔必须能被复用方等到,否则它会+ * 落在刚重建出来的内容上(见 `settleCachePathRemovals`)。+ */+const inFlight = new Map<string, Promise<void>>();++interface DeferredRemoval {+ /** 返回 true 表示放弃删除(例如该版本目录已重新成为 current)。 */+ skipIf?: () => boolean;+ onError?: (error: unknown) => void;+}++/** 两条路径在任一方向上重叠(含相等、互为前缀)。 */+function overlaps(a: string, b: string): boolean {+ return a === b || a.startsWith(b) || b.startsWith(a);+}++/** 是否有持有中的租约与该路径重叠。 */+export function isCachePathLeased(target: string): boolean {+ for (const held of leases.keys()) {+ if (overlaps(held, target)) return true;+ }+ return false;+}++/**+ * 登记一个租约。必须覆盖到该路径的**最后一次使用**为止(例如自定义源安装要+ * 一直持到 `.cindy` 打包完成),否则并发的清理仍能在使用途中把目录抽走。+ */+export function retainCachePath(target: string): void {+ leases.set(target, (leases.get(target) ?? 0) + 1);+}++/** 释放租约;不再有重叠租约时执行被推迟的删除。 */+export function releaseCachePath(target: string): void {+ const remaining = (leases.get(target) ?? 0) - 1;+ if (remaining > 0) {+ leases.set(target, remaining);+ return;+ }+ leases.delete(target);+ drainDeferred();+}++/** 在持有租约的作用域内执行 fn。 */+export async function withCachePath<T>(+ target: string,+ fn: () => Promise<T>,+): Promise<T> {+ retainCachePath(target);+ try {+ return await fn();+ } finally {+ releaseCachePath(target);+ }+}++/**+ * 删除一个缓存路径。**这是本模块外唯一允许的缓存删除方式。**+ *+ * 与任何持有中的租约重叠时不删,而是推迟到最后一个相关租约释放;`skipIf` 在真正+ * 执行前再核对一次(推迟期间事实可能已经变了,例如该版本又成了 current)。+ * 返回是否已就地删除。删除失败只影响磁盘占用,不影响正确性。+ */+export async function removeCachePath(+ target: string,+ options: DeferredRemoval = {},+): Promise<boolean> {+ if (isCachePathLeased(target)) {+ deferred.set(target, options);+ return false;+ }+ deferred.delete(target);+ if (options.skipIf?.()) return false;+ await runRemoval(target, options);+ return true;+}++/**+ * 真正执行删除,并把它登记进 `inFlight`。+ *+ * 登记是必需的:`skipIf` 只在**启动前**核对一次,一旦 rm 开始跑,调用方就再也无法+ * 取消或等待它。旧槽删除正在途中、而重新添加同名同源的来源刚好把新版本落进同一个+ * 槽,那笔在途删除就会把新内容删掉(配置有效但来源持续报缓存缺失)。要复用某个路径+ * 的调用方必须先 `settleCachePathRemovals` 等它结束。+ */+async function runRemoval(target: string, options: DeferredRemoval): Promise<void> {+ const task = fs.promises+ // maxRetries/retryDelay:Windows 上 AV/索引器/云同步持句柄会让 rm 抛+ // EBUSY/EPERM/ENOTEMPTY,libuv 原生重试即可,不必自建循环。+ .rm(target, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 })+ .catch((error: unknown) => {+ options.onError?.(error);+ });+ inFlight.set(target, task);+ try {+ await task;+ } finally {+ if (inFlight.get(target) === task) inFlight.delete(target);+ }+}++/**+ * 等待与该路径重叠的在途删除全部结束。**复用一个刚被删除过的路径前必须调用**+ * (例如移除来源后重新添加同名同源会复用同一个缓存槽)。+ *+ * 循环是因为等待期间可能又有租约释放、触发新的推迟删除;上限只是防御性兜底,+ * 正常情况下一两轮就空了。+ */+export async function settleCachePathRemovals(target: string): Promise<void> {+ for (let round = 0; round < 8; round += 1) {+ const pending = [...inFlight]+ .filter(([path]) => overlaps(path, target))+ .map(([, task]) => task);+ if (pending.length === 0) return;+ await Promise.allSettled(pending);+ }+}++/** 执行所有已不再被租约挡住的推迟删除。 */+function drainDeferred(): void {+ for (const [target, options] of [...deferred]) {+ if (isCachePathLeased(target)) continue;+ deferred.delete(target);+ if (options.skipIf?.()) continue;+ // 释放路径是同步的,这里不能 await;但删除会登记进 inFlight,复用方能等到它。+ void runRemoval(target, options);+ }+}++/** 仅测试用:清空租约与推迟队列,避免用例间互相影响。 */+export function resetCacheLeasesForTest(): void {+ leases.clear();+ deferred.clear();+ inFlight.clear();+}diff --git a/apps/desktop/src/main/plugin-market/sources/discover.ts b/apps/desktop/src/main/plugin-market/sources/discover.tsnew file mode 100644index 0000000000..6d80c85dd4--- /dev/null+++ b/apps/desktop/src/main/plugin-market/sources/discover.ts@@ -0,0 +1,364 @@+/**+ * 自定义市场发现:在市场根目录查找 Codex 兼容的 marketplace.json 并解析插件列表。+ *+ * 兼容 Codex 的清单位置与基础 schema(name + plugins[],source 为相对路径或+ * {source:"local",path}),但插件本体必须是 Cindy 插件(目录内含合法 ghost.json)。+ * 清单里的描述性字段不作为事实来源——展示与安装一律以 ghost.json 为准。+ *+ * 容错策略与 Codex 一致:单个插件条目非法只跳过并记日志,不让整个市场不可用。+ */+import fs from 'node:fs';+import path from 'node:path';++import { validateGhostManifest, type GhostManifest } from '../../../shared/ghost.js';+import {+ GHOST_MANIFEST_MAX_BYTES,+ readBoundedFileFollowLinks,+ readBoundedFileNoFollow,+} from '../../utils/readBoundedFile.js';+import { redactAbsolutePaths } from './git.js';++/** 与 Codex 相同的清单位置,按优先级查找。 */+export const MARKETPLACE_MANIFEST_PATHS = [+ '.agents/plugins/marketplace.json',+ '.agents/plugins/api_marketplace.json',+ '.claude-plugin/marketplace.json',+ '.cursor-plugin/marketplace.json',+] as const;++/**+ * 清单与身份卡的读取上限。市场仓库是不受信内容,git clone 不限制单文件大小,+ * 不设上限时一份数 GB 的 marketplace.json / ghost.json 会在 readFile + JSON.parse+ * 里把 main 进程内存打爆。合法清单远小于此(Codex 生态同量级)。+ */+const MARKETPLACE_MANIFEST_MAX_BYTES = 1024 * 1024;++/**+ * 插件条目数上限。每个条目都会触发 realpath + 读身份卡,不设上限时一份十万条目的+ * 清单能把快照/列表/刷新拖住很久。合法市场远小于此。+ */+const MARKETPLACE_MAX_PLUGIN_ENTRIES = 512;++/** 市场名上限:进 store 持久化、进 pluginId、进 UI,不能不设边界。 */+const MARKET_NAME_MAX_CHARS = 128;++/** 控制字符与双向文本控制符不允许出现在市场名里,防 UI 欺骗与日志注入。 */+// eslint-disable-next-line no-control-regex+const FORBIDDEN_NAME_CHARS = /[\u0000-\u001f\u007f\u200e\u200f\u202a-\u202e\u2066-\u2069]/;++/**+ * 以单一文件句柄完成"拒符号链接 → 校验普通文件与大小 → 限量读取 → JSON 解析"。+ * 实体见 readBoundedFileNoFollow(发现/安装/打包三条链路共用同一实现,含+ * Windows 无 O_NOFOLLOW 时的 lstat+dev/ino 回退闸)。非普通文件/超限返回 null;+ * 打开失败(含 O_NOFOLLOW 对 symlink 的拒绝)抛出,由调用方决定语义。+ */+async function readBoundedJsonFile(+ filePath: string,+ maxBytes: number,+ realRoot: string,+): Promise<unknown | null> {+ // containWithin 复核堵"realpath 校验后、open 前中间目录被换成根外链接"的+ // 窗口:O_NOFOLLOW 只管最后一个路径分量。+ const bytes = await readBoundedFileNoFollow(filePath, maxBytes, {+ containWithin: realRoot,+ });+ if (bytes === null) return null;+ return JSON.parse(bytes.toString('utf8')) as unknown;+}++/** 清单侧变体:路径已是 realpath 产物且经根包含校验,允许跟随链接,其余同上。 */+async function readBoundedManifest(+ filePath: string,+ realRoot: string,+): Promise<unknown | null> {+ const bytes = await readBoundedFileFollowLinks(filePath, MARKETPLACE_MANIFEST_MAX_BYTES, {+ containWithin: realRoot,+ });+ if (bytes === null) return null;+ return JSON.parse(bytes.toString('utf8')) as unknown;+}++/** 错误 message 可能携带完整宿主路径(ENOENT/EACCES 自带),进 IPC detail 前脱敏。 */+function sanitizedDetail(error: unknown): string {+ return redactAbsolutePaths(error instanceof Error ? error.message : String(error)).slice(0, 256);+}++export type DiscoverError =+ | 'MARKET_MANIFEST_MISSING'+ | 'MARKET_SOURCE_INVALID';++export interface DiscoveredMarketPlugin {+ ghostId: string;+ version: string;+ /** 插件目录的绝对路径(已校验不越出市场根目录)。 */+ dir: string;+ manifest: GhostManifest;+}++export interface DiscoveredMarketplace {+ name: string;+ displayName: string | null;+ plugins: DiscoveredMarketPlugin[];+ /**+ * 因**内容非法**被跳过的条目数(非法 source / 目录不存在 / 越出根 / 清单不合格 /+ * 超限)。这类是永久事实,跳过即结论,不影响目录完整性。+ */+ skippedCount: number;+ /**+ * 因**读取事实不明**未能判定的条目数(文件锁、权限、网络盘抖动、瞬时 I/O)。+ *+ * 与 skippedCount 必须分开:>0 表示"这个市场声明了哪些 ghostId"当前给不出完整+ * 答案。展示可以照旧容错,但**新的所有权提交必须 fail closed**——否则同 ghostId+ * 的服务端默认安装/手动安装会在它暂时不可读的窗口里抢占先装先得,恢复后该插件+ * 永久 conflict。与来源级失败(result.ok === false)同一口径,只是粒度到条目。+ */+ unreadableCount: number;+}++export type DiscoverResult =+ | { ok: true; marketplace: DiscoveredMarketplace }+ | { ok: false; code: DiscoverError; detail?: string };++interface RawMarketplaceManifest {+ name?: unknown;+ interface?: unknown;+ plugins?: unknown;+}++/** 解析插件条目的 source 字段为市场内相对路径;不支持的形态返回 null。 */+function pluginEntryRelativePath(source: unknown): string | null {+ if (typeof source === 'string') return source;+ if (source && typeof source === 'object' && !Array.isArray(source)) {+ const record = source as Record<string, unknown>;+ if (record.source === 'local' && typeof record.path === 'string') return record.path;+ // url / git-subdir / npm 形态的远程插件源 Phase 1 不支持。+ return null;+ }+ return null;+}++/**+ * 单个插件条目的解析结论。+ * - `ok`:可用。+ * - `invalid`:**永久**非法(路径形态、目录不存在、越出根、清单不合格、超限、+ * ghost.json 是符号链接)。跳过即结论。+ * - `unreadable`:**事实不明**(文件锁、权限、网络盘抖动、瞬时 I/O)。不能与+ * invalid 混同——它会让"本市场声明了哪些 ghostId"给不出完整答案。+ */+type PluginDirResolution =+ | { kind: 'ok'; plugin: DiscoveredMarketPlugin }+ | { kind: 'invalid' }+ | { kind: 'unreadable' };++/**+ * 可重试的文件系统错误码 = 事实不明。+ *+ * 刻意**不含 ENOENT / ELOOP / ENOTDIR**:清单指向一个不存在的目录是常见的永久+ * 错误(市场删了插件却没更新 marketplace.json),把它当"暂时读不到"会让这类市场+ * 永久处于"目录不完整",默认安装被永久阻塞;ELOOP 是 O_NOFOLLOW 拒符号链接的+ * 结果,属攻击/非法内容,同样是永久结论。+ */+const TRANSIENT_FS_CODES = new Set([+ 'EACCES',+ 'EPERM',+ 'EBUSY',+ 'EIO',+ 'EAGAIN',+ 'ETIMEDOUT',+ 'EMFILE',+ 'ENFILE',+ 'ENOMEM',+ 'ESTALE',+]);++function classifyFsFailure(error: unknown): 'invalid' | 'unreadable' {+ const code = (error as NodeJS.ErrnoException | null)?.code;+ return code && TRANSIENT_FS_CODES.has(code) ? 'unreadable' : 'invalid';+}++async function resolvePluginDir(+ marketRoot: string,+ relPath: string,+): Promise<PluginDirResolution> {+ const trimmed = relPath.trim();+ if (!trimmed || path.isAbsolute(trimmed) || /^[A-Za-z]:/.test(trimmed)) {+ return { kind: 'invalid' };+ }+ const dir = path.resolve(marketRoot, trimmed);+ const rootWithSep = marketRoot.endsWith(path.sep) ? marketRoot : `${marketRoot}${path.sep}`;+ if (dir !== marketRoot && !dir.startsWith(rootWithSep)) return { kind: 'invalid' };++ let realRoot: string;+ let realDir: string;+ try {+ // 字符串前缀只能挡住 "../" 形式的路径穿越;市场内 symlink 仍会指向外部。+ // 边界判定必须以真实路径为准,市场克隆缓存也不应允许 symlink 越出根目录。+ [realRoot, realDir] = await Promise.all([+ fs.promises.realpath(marketRoot),+ fs.promises.realpath(dir),+ ]);+ } catch (error) {+ return { kind: classifyFsFailure(error) };+ }+ const realRootWithSep = realRoot.endsWith(path.sep) ? realRoot : `${realRoot}${path.sep}`;+ if (realDir !== realRoot && !realDir.startsWith(realRootWithSep)) return { kind: 'invalid' };++ let raw: unknown;+ try {+ // 身份卡的校验与读取必须落在**同一个文件句柄**上:先 lstat 再按路径 readFile+ // 是两次独立打开,并发方可以在两次之间把 ghost.json 换成超大文件或指向+ // /dev/zero 的链接,绕过类型与大小闸。O_NOFOLLOW 让 open 对 symlink 直接+ // 失败(与打包侧"符号链接一律不穿透"同口径;Windows 无此 flag 时走+ // lstat+dev/ino 回退闸,同样拒链接);随后 stat 与限量读取都作用于已打开的+ // inode,路径再被替换也影响不到它。+ raw = await readBoundedJsonFile(+ path.join(realDir, 'ghost.json'),+ GHOST_MANIFEST_MAX_BYTES,+ realRoot,+ );+ // null = 非普通文件 / 超限 / 根内复核不过:都是内容判据,属永久非法。+ if (raw === null) return { kind: 'invalid' };+ } catch (error) {+ // JSON 解析失败是内容非法;fs 错误按可重试性分类。+ if (error instanceof SyntaxError) return { kind: 'invalid' };+ return { kind: classifyFsFailure(error) };+ }+ const validated = validateGhostManifest(raw);+ if (!validated.ok) return { kind: 'invalid' };+ return {+ kind: 'ok',+ plugin: {+ ghostId: validated.manifest.id,+ version: validated.manifest.version,+ dir: realDir,+ manifest: validated.manifest,+ },+ };+}++/**+ * 在市场根目录发现插件。marketRoot 必须已存在(调用方负责克隆/路径校验)。+ */+export async function discoverMarketplace(marketRoot: string): Promise<DiscoverResult> {+ let manifestPath: string | null = null;+ for (const relPath of MARKETPLACE_MANIFEST_PATHS) {+ const candidate = path.join(marketRoot, ...relPath.split('/'));+ if (fs.existsSync(candidate)) {+ manifestPath = candidate;+ break;+ }+ }+ if (!manifestPath) return { ok: false, code: 'MARKET_MANIFEST_MISSING' };++ // 清单读取也必须按真实路径做包含性判定(与 resolvePluginDir 同一套):候选路径是+ // 我们自己拼的,挡不住仓库内的 symlink —— 恶意市场可以把+ // `.agents/plugins/marketplace.json` 做成指向市场根目录外的链接,从而让宿主去读+ // 任意路径。realpath 落在根目录外一律拒。+ let realManifestPath: string;+ let realMarketRoot: string;+ try {+ const [realRoot, realManifest] = await Promise.all([+ fs.promises.realpath(marketRoot),+ fs.promises.realpath(manifestPath),+ ]);+ const realRootWithSep = realRoot.endsWith(path.sep) ? realRoot : `${realRoot}${path.sep}`;+ if (!realManifest.startsWith(realRootWithSep)) {+ return {+ ok: false,+ code: 'MARKET_SOURCE_INVALID',+ detail: 'marketplace manifest escapes the marketplace root',+ };+ }+ realManifestPath = realManifest;+ realMarketRoot = realRoot;+ } catch (error) {+ // realpath 的 ENOENT/EACCES message 自带完整宿主路径,进 IPC detail 前必须脱敏。+ return { ok: false, code: 'MARKET_SOURCE_INVALID', detail: sanitizedDetail(error) };+ }++ let raw: RawMarketplaceManifest;+ try {+ // 校验与读取共用同一句柄(见 readBoundedJsonFile):数 GB 的清单在读之前按+ // 大小拒掉,且两次之间不存在被替换的窗口。realpath 已解析链接并做过根包含+ // 校验,这里不再加 O_NOFOLLOW(根内链接指向根内文件是允许的)。+ const parsed = await readBoundedManifest(realManifestPath, realMarketRoot);+ if (parsed === null) {+ return {+ ok: false,+ code: 'MARKET_SOURCE_INVALID',+ detail: `marketplace manifest must be a regular file within ${MARKETPLACE_MANIFEST_MAX_BYTES} bytes`,+ };+ }+ raw = parsed as RawMarketplaceManifest;+ } catch (error) {+ return { ok: false, code: 'MARKET_SOURCE_INVALID', detail: sanitizedDetail(error) };+ }+ if (!raw || typeof raw.name !== 'string' || raw.name.trim().length === 0) {+ return { ok: false, code: 'MARKET_SOURCE_INVALID', detail: 'marketplace.json missing name' };+ }+ const name = raw.name.trim();+ // 市场名会进 store 持久化、进 pluginId、进 UI 与路径 slug,必须有边界:超长+ // 会让配置与账本无界膨胀,控制字符/双向控制符可伪装 UI 文案与污染日志。+ if (name.length > MARKET_NAME_MAX_CHARS || FORBIDDEN_NAME_CHARS.test(name)) {+ return { ok: false, code: 'MARKET_SOURCE_INVALID', detail: 'marketplace name is invalid' };+ }+ if (!Array.isArray(raw.plugins)) {+ return { ok: false, code: 'MARKET_SOURCE_INVALID', detail: 'marketplace.json plugins must be an array' };+ }+ if (raw.plugins.length > MARKETPLACE_MAX_PLUGIN_ENTRIES) {+ return {+ ok: false,+ code: 'MARKET_SOURCE_INVALID',+ detail: `marketplace lists more than ${MARKETPLACE_MAX_PLUGIN_ENTRIES} plugins`,+ };+ }++ const rawDisplayName =+ raw.interface &&+ typeof raw.interface === 'object' &&+ !Array.isArray(raw.interface) &&+ typeof (raw.interface as Record<string, unknown>).displayName === 'string'+ ? ((raw.interface as Record<string, unknown>).displayName as string).trim()+ : null;+ // displayName 是描述性字段:非法就丢弃,不因它拒掉整个市场。+ const displayName =+ rawDisplayName &&+ rawDisplayName.length <= MARKET_NAME_MAX_CHARS &&+ !FORBIDDEN_NAME_CHARS.test(rawDisplayName)+ ? rawDisplayName+ : null;++ const plugins: DiscoveredMarketPlugin[] = [];+ const seenGhostIds = new Set<string>();+ let skippedCount = 0;+ let unreadableCount = 0;+ for (const entry of raw.plugins) {+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {+ skippedCount += 1;+ continue;+ }+ const relPath = pluginEntryRelativePath((entry as Record<string, unknown>).source);+ if (!relPath) {+ skippedCount += 1;+ continue;+ }+ const resolved = await resolvePluginDir(marketRoot, relPath);+ if (resolved.kind === 'unreadable') {+ // 事实不明:不能与"内容非法"共用静默跳过分支,否则调用方会把目录当完整,+ // 允许同 ghostId 的默认安装/手动安装在这个窗口里抢占所有权。+ unreadableCount += 1;+ continue;+ }+ if (resolved.kind === 'invalid' || seenGhostIds.has(resolved.plugin.ghostId)) {+ skippedCount += 1;+ continue;+ }+ seenGhostIds.add(resolved.plugin.ghostId);+ plugins.push(resolved.plugin);+ }++ return {+ ok: true,+ marketplace: { name, displayName, plugins, skippedCount, unreadableCount },+ };+}diff --git a/apps/desktop/src/main/plugin-market/sources/git.ts b/apps/desktop/src/main/plugin-market/sources/git.tsnew file mode 100644index 0000000000..84d16d9808--- /dev/null+++ b/apps/desktop/src/main/plugin-market/sources/git.ts@@ -0,0 +1,327 @@+/**+ * 自定义市场的 Git 操作。+ *+ * 与 Codex 同一策略:私有仓库认证完全交给用户系统级 Git 配置+ * (credential helper / SSH agent / gh auth),客户端不做任何特殊处理。+ * 唯一的强约束是 GIT_TERMINAL_PROMPT=0 —— Electron 主进程没有 TTY,+ * 缺少凭证的克隆必须立即失败并分类引导,绝不能挂在隐形的密码提示上。+ */+import { execFile } from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';+import crypto from 'node:crypto';++import type { IpcErrorCode } from '../../../shared/ipc-errors.js';++/** 克隆/拉取超时:大仓库给足窗口,但绝不无限挂起。 */+const GIT_OPERATION_TIMEOUT_MS = 5 * 60 * 1000;++/** rename 遇 Windows 瞬时锁(AV/索引器/云同步持句柄)短退避重试;其余立即上抛。 */+async function renameWithRetry(from: string, to: string): Promise<void> {+ const transient = new Set(['EBUSY', 'EACCES', 'EPERM', 'ENOTEMPTY']);+ for (let attempt = 0; ; attempt += 1) {+ try {+ await fs.promises.rename(from, to);+ return;+ } catch (error) {+ const code = (error as NodeJS.ErrnoException)?.code;+ if (attempt >= 3 || !code || !transient.has(code)) throw error;+ await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));+ }+ }+}+/** sparse-checkout 需要 Git >= 2.25。 */+export const MIN_GIT_VERSION = { major: 2, minor: 25 } as const;++/** 带 IPC 错误码的市场 Git 失败;service 层原样转成 throwIpcError。 */+export class MarketGitError extends Error {+ constructor(+ readonly code: Extract<+ IpcErrorCode,+ | 'MARKET_GIT_UNAVAILABLE'+ | 'MARKET_CLONE_AUTH_FAILED'+ | 'MARKET_CLONE_FAILED'+ | 'MARKET_REF_NOT_FOUND'+ >,+ message: string,+ ) {+ super(message);+ this.name = 'MarketGitError';+ }+}++export interface GitExecResult {+ stdout: string;+ stderr: string;+}++/** 可注入的 git 执行器:单测用 fake,生产走 execFile。 */+export type GitExecutor = (+ args: readonly string[],+ options: { cwd?: string; timeoutMs: number },+) => Promise<GitExecResult>;++const defaultExecutor: GitExecutor = (args, options) =>+ new Promise((resolve, reject) => {+ execFile(+ 'git',+ // 缓存路径(owners/<hex>/plugin-market/sources/<slug>/incoming/…)在+ // Windows 上极易越过 MAX_PATH 260,不带 longpaths 时 clone/checkout 报+ // "Filename too long"。统一在执行器注入,非 Windows 平台 git 会忽略。+ ['-c', 'core.longpaths=true', ...args],+ {+ cwd: options.cwd,+ timeout: options.timeoutMs,+ maxBuffer: 16 * 1024 * 1024,+ // Windows 上不闪控制台窗口(一次 addSource 要跑 5-6 条 git 命令)。+ windowsHide: true,+ env: {+ ...process.env,+ GIT_TERMINAL_PROMPT: '0',+ // Windows 上凭据管理器可能尝试弹 UI;与 TERMINAL_PROMPT 一起双保险。+ GCM_INTERACTIVE: 'never',+ // askpass helper(VSCode 注入的 GIT_ASKPASS、桌面环境的 SSH_ASKPASS)+ // 会弹 GUI 输入框,Electron main 没人去点,只能挂满 5 分钟超时。+ // 置空让 git 直接失败并落到 stderr 分类。+ GIT_ASKPASS: '',+ SSH_ASKPASS: '',+ // 强制英文报错:classifyGitFailure 按英文文案分类,本地化 git+ // 输出(如中文 "无法读取远程仓库")会让分类失效、误导引导文案。+ LC_ALL: 'C',+ },+ },+ (error, stdout, stderr) => {+ if (error) {+ reject(Object.assign(error, { stderr }));+ return;+ }+ resolve({ stdout, stderr });+ },+ );+ });++function errorText(error: unknown): string {+ if (error && typeof error === 'object') {+ const stderr = 'stderr' in error ? String((error as { stderr?: unknown }).stderr ?? '') : '';+ const message = error instanceof Error ? error.message : String(error);+ return `${message}\n${stderr}`;+ }+ return String(error);+}++/**+ * 抹掉任意绝对路径。git 自己的输出之外,OpenSSH、credential helper、杀毒钩子都会+ * 往 stderr 写宿主路径(`/Users/<name>/.ssh/id_rsa`、`C:\Users\<name>\...`、+ * `~/.gitconfig`),只替换已知的缓存路径盖不住这些 —— 用户名与宿主目录结构不该+ * 经 IPC 到达 Renderer。诊断用的完整原文仍在 main 日志里。+ *+ * 导出给 discover 等其它会把错误详情转发 Renderer 的模块共用:任何进 IPC 错误+ * detail 的系统错误 message(realpath/readFile 的 ENOENT/EACCES 自带完整路径)+ * 都必须先过这一遍。+ */+export function redactAbsolutePaths(text: string): string {+ // 先把 URL 摘出来占位:仓库地址是用户自己输入的、要留着给他定位问题,不能被+ // 下面的路径规则把 `https://host/org/repo.git` 的路径段一起抹掉。+ const urls: string[] = [];+ const masked = text.replace(/\b(?:https?|ssh|git):\/\/[^\s"'<>|]+/gi, (match) => {+ urls.push(match);+ return `\u0000URL${urls.length - 1}\u0000`;+ });+ return (+ masked+ // Windows:C:\Users\name\... / \\server\share\...+ .replace(/[A-Za-z]:\\[^\s"'<>|]*/g, '<path>')+ .replace(/\\\\[^\s"'<>|]+/g, '<path>')+ // POSIX:`/home/alice`、`/tmp/foo` 这类两段路径同样带用户名与目录结构,+ // 必须一起覆盖(此前要求两个带斜杠的段,实际只盖到三段及以上)。+ .replace(/\/(?:[^\s"'<>|/]+\/)+[^\s"'<>|/]*/g, '<path>')+ // ~ 开头的家目录相对路径+ .replace(/~\/[^\s"'<>|]*/g, '<path>')+ // 还原 URL 时抹掉整个 userinfo:`https://ghp_TOKEN@host/...` 这类单段+ // 凭证没有冒号,user:pass 规则盖不住;host 与路径保留给用户定位问题。+ .replace(/\u0000URL(\d+)\u0000/g, (_, index: string) => {+ const url = urls[Number(index)];+ if (url === undefined) return '<path>';+ return url.replace(/^((?:https?|ssh|git):\/\/)[^/@\s]+@/i, '$1***@');+ })+ );+}++/**+ * 把原始 git 输出整理成可以回传 Renderer 的详情:只保留 stderr(execFile 的+ * message 前缀含完整命令行与内部 staging 路径)、抹掉 URL 内嵌凭证与任意绝对+ * 路径。完整原文仍留在 main 日志(调用方记录)。+ */+function sanitizeGitDetail(error: unknown, internalPaths: readonly string[]): string {+ const raw =+ error && typeof error === 'object' && 'stderr' in error && (error as { stderr?: unknown }).stderr+ ? String((error as { stderr?: unknown }).stderr)+ : errorText(error);+ let text = raw;+ // 已知的内部缓存路径换成有意义的占位符(比统一的 <path> 更可读)。+ for (const internalPath of internalPaths) {+ text = text.split(internalPath).join('<marketplace>');+ }+ // URL 内嵌凭证不进 Renderer:user:pass 与单段 token(https://ghp_x@host,+ // 常见于 ~/.gitconfig 的 insteadOf 重写)都要盖住。+ text = text.replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/g, '$1***@');+ text = text.replace(/((?:https?|ssh):\/\/)[^\s/@]+@/gi, '$1***@');+ // 兜住其余任意绝对路径(SSH identity file、credential helper、杀毒钩子等)。+ text = redactAbsolutePaths(text);+ // git stderr 会回显远端提供的文案(remote: …),自建服务可塞双向控制符做+ // 错误区文案欺骗;与市场名同一口径剥掉(保留换行/制表便于阅读)。+ // eslint-disable-next-line no-control-regex+ text = text.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, '');+ return text.trim().slice(0, 512);+}++/** 把 git 失败分类成可引导的 IPC 错误码;message 是经消毒、可展示给用户的详情。 */+export function classifyGitFailure(+ error: unknown,+ internalPaths: readonly string[] = [],+): MarketGitError {+ const text = errorText(error);+ const detail = sanitizeGitDetail(error, internalPaths);+ if (/Remote branch \S+ not found|Couldn't find remote ref|couldn't find remote ref/i.test(text)) {+ return new MarketGitError('MARKET_REF_NOT_FOUND', detail);+ }+ if (/Authentication failed|could not read Username|Repository not found|Permission denied \(publickey\)|Host key verification failed|Could not read from remote repository|SAML SSO/i.test(text)) {+ return new MarketGitError('MARKET_CLONE_AUTH_FAILED', detail);+ }+ return new MarketGitError('MARKET_CLONE_FAILED', detail);+}++export async function gitVersion(+ executor: GitExecutor = defaultExecutor,+): Promise<{ major: number; minor: number } | null> {+ try {+ const { stdout } = await executor(['--version'], { timeoutMs: 10_000 });+ const match = /git version (\d+)\.(\d+)/.exec(stdout);+ if (!match) return null;+ return { major: Number(match[1]), minor: Number(match[2]) };+ } catch {+ return null;+ }+}++export function isGitVersionSupported(version: { major: number; minor: number }): boolean {+ if (version.major !== MIN_GIT_VERSION.major) return version.major > MIN_GIT_VERSION.major;+ return version.minor >= MIN_GIT_VERSION.minor;+}++/**+ * 远端默认分支名(`origin/HEAD` → `main`/`master`/…)。`--no-checkout` 克隆后+ * 拿它来 checkout 一个**真实分支**,保留上游跟踪关系,后续 `pull --ff-only`+ * 才能快进。解析失败返回 null,由调用方决定退路。+ */+async function defaultBranchName(+ cwd: string,+ executor: GitExecutor,+): Promise<string | null> {+ try {+ const { stdout } = await executor(['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], {+ cwd,+ timeoutMs: 10_000,+ });+ // 形如 `origin/main`,取 remote 前缀之后的分支名。+ const value = stdout.trim();+ const slash = value.indexOf('/');+ const branch = slash >= 0 ? value.slice(slash + 1) : value;+ return branch.length > 0 ? branch : null;+ } catch {+ return null;+ }+}++/**+ * 克隆市场仓库到 destPath(staging + rename 原子替换;Windows 不允许 rename+ * 覆盖非空目录,因此调用方需保证 destPath 不存在或先移除)。+ */+export async function cloneMarketplace(+ input: { url: string; ref?: string; sparsePaths: readonly string[] },+ destPath: string,+ executor: GitExecutor = defaultExecutor,+): Promise<string> {+ const stagingPath = `${destPath}.staging-${crypto.randomUUID()}`;+ const timeoutMs = GIT_OPERATION_TIMEOUT_MS;+ try {+ if (input.sparsePaths.length === 0) {+ await executor(['clone', input.url, stagingPath], { timeoutMs });+ if (input.ref) {+ // --branch 只支持 branch/tag;显式 checkout 同时覆盖可达的 commit SHA。+ // 必须带 --detach 消歧:`git checkout <ref>` 在 ref 不存在但仓库根恰有+ // 同名文件时会退化成**路径检出**并成功返回,HEAD 仍停在默认分支——用户+ // pin 住的引用被静默换成默认分支内容。--detach 强制按 commit-ish 解析,+ // 解析不了就如实失败。+ await executor(['checkout', '--detach', input.ref], { cwd: stagingPath, timeoutMs });+ }+ } else {+ await executor(+ ['clone', '--filter=blob:none', '--no-checkout', input.url, stagingPath],+ { timeoutMs },+ );+ // -- 终止选项解析:即使上游漏放了以 - 开头的值,也只被当作路径。+ await executor(['sparse-checkout', 'set', '--', ...input.sparsePaths], {+ cwd: stagingPath,+ timeoutMs,+ });+ // 无显式 ref 时必须 checkout 默认**分支**而不是 `HEAD`:后者留下 detached+ // HEAD,刷新走的 `git pull --ff-only` 会稳定失败并回落到整仓重克隆,+ // 等于每次刷新都重新 clone。取不到默认分支名时才退回 HEAD。+ // 显式 ref 同样带 --detach 消歧(见上:防同名文件把 checkout 变成路径检出)。+ if (input.ref) {+ await executor(['checkout', '--detach', input.ref], { cwd: stagingPath, timeoutMs });+ } else {+ const target = (await defaultBranchName(stagingPath, executor)) ?? 'HEAD';+ await executor(['checkout', target], { cwd: stagingPath, timeoutMs });+ }+ }+ await fs.promises.mkdir(path.dirname(destPath), { recursive: true });+ // Windows 上 AV/索引器/云同步会短暂占用刚 clone 出的文件,rename 抛+ // EBUSY/EACCES/EPERM;瞬时锁短退避重试。目标是全新 UUID 路径,不存在覆盖。+ await renameWithRetry(stagingPath, destPath);+ return await currentRevision(destPath, executor);+ } catch (error) {+ await fs.promises.rm(stagingPath, { recursive: true, force: true }).catch(() => undefined);+ throw classifyGitFailure(error, [stagingPath, destPath]);+ }+}++/**+ * 刷新已克隆市场:fetch + 快进到上游。返回新 HEAD SHA。+ * 用户在克隆目录里的本地改动不属于支持场景——市场目录是客户端管理的缓存,+ * 快进失败按刷新失败处理,由调用方决定重克隆。+ */+export async function fetchMarketplace(+ marketPath: string,+ ref: string | undefined,+ executor: GitExecutor = defaultExecutor,+ /** 默认在 marketPath 原地快进;传入 cwd 时在该工作目录执行(刷新 staging 用)。 */+ cwd?: string,+): Promise<string> {+ const workDir = cwd ?? marketPath;+ const timeoutMs = GIT_OPERATION_TIMEOUT_MS;+ try {+ if (ref) {+ // 显式引用:对齐远端该 ref(branch/tag/commit 统一用 FETCH_HEAD 落位)。+ await executor(['fetch', 'origin', ref], { cwd: workDir, timeoutMs });+ await executor(['reset', '--hard', 'FETCH_HEAD'], { cwd: workDir, timeoutMs });+ } else {+ await executor(['pull', '--ff-only'], { cwd: workDir, timeoutMs });+ }+ return await currentRevision(workDir, executor);+ } catch (error) {+ throw classifyGitFailure(error, [workDir]);+ }+}++export async function currentRevision(+ marketPath: string,+ executor: GitExecutor = defaultExecutor,+): Promise<string> {+ const { stdout } = await executor(['rev-parse', 'HEAD'], {+ cwd: marketPath,+ timeoutMs: 10_000,+ });+ return stdout.trim();+}diff --git a/apps/desktop/src/main/plugin-market/sources/index.ts b/apps/desktop/src/main/plugin-market/sources/index.tsnew file mode 100644index 0000000000..0b43480878--- /dev/null+++ b/apps/desktop/src/main/plugin-market/sources/index.ts@@ -0,0 +1,806 @@+/**+ * 自定义市场源管理器:添加 / 移除 / 刷新 / 发现的统一入口。+ *+ * 实例按 owner 构造(store 与 cloneRoot 已由调用方绑定到操作开始时的+ * dataOwner),与 PluginMarketService 的 ledger 同一套 owner 捕获语义。+ *+ * Git 缓存布局(版本目录 + 当前指针 + 读取引用计数):+ * - 每次刷新克隆/快进到 sources/<slug>/incoming/<uuid>/ 并完成完整发现验证,+ * 通过后才 rename 进 sources/<slug>/versions/<new>/,再用可回滚原子写把+ * sources/<slug>/current 指针文件改成新版本名。读取方永远经 current 指针+ * 解析到完整版本目录。+ * - 在途工作一律在 versions/ 之外:git clone 会在目标同级建 `<dest>.staging-*`,+ * 目标若在 versions/ 内,并发刷新切完指针后的清理会把别人正在写的 staging+ * 目录当历史版本删掉。versions/ 只承载完整版本目录,清理碰不到在途工作。+ * - 没有任何"固定路径被 rename"的瞬态:要么指针指向旧版(刷新中途失败,+ * 旧版完好),要么指向新版(全成功)。原子性由指针文件原子写保证,不需要+ * 备份交换/哨兵/自愈。+ * - **本文件不直接删除任何缓存路径**:所有删除都经 `removeCacheDir` →+ * `cacheLease.removeCachePath` 这一个入口,与持有中的租约重叠就自动推迟。+ * 这块此前反复出事,每轮都是"又发现一个删除点没查租约"(交换旧目录、清理历史+ * 版本、清理暂存目录、移除来源、失败回滚各自直接 rm)。收口到唯一入口后,+ * "删掉正在被读的路径"才从结构上不可能发生,而不是靠每个调用点自觉。判据与+ * 推迟机制见 `cacheLease.ts`。+ * - 租约登记的关键是**与指针解析同步完成**:resolveCurrentVersionSync 全同步,+ * acquireCurrentVersion 在同一个同步块里解析并登记,中间不 await,因此不存在+ * "解析到登记"的窗口——任何 fs 回调都插不进来。文件系统标记(.reading 之类)+ * 做不到这点(解析与落标记之间必有 await,且标记会被 fs.cp 复制进新版本)。+ * - 旧布局(单个 sources/<slug>/ 直接是缓存)在首次读取时自动迁移进版本目录。+ * - 前提:同一 userData 只有一个 main 进程管理这些缓存槽(Electron 单实例)。+ *+ * 不变量:+ * - Git 克隆目录是客户端管理的缓存,路径只由 (name, source) 派生,用户不应+ * 手动编辑。+ * - 市场名来自 marketplace.json,全局唯一;同名不同源拒绝添加。+ * - 移除来源只删配置与克隆缓存,已安装插件的包目录与 ledger 记录保留。+ */+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import crypto from 'node:crypto';++import {+ marketSourceKey,+ type MarketSource,+ type MarketSourceConfig,+ type MarketSourceSummary,+} from '../../../shared/pluginMarket.js';+import { createLogger } from '../../logger.js';+import { throwIpcError } from '../../utils/ipcValidate.js';+import { atomicWriteFileSync, readAtomicFileSync } from '../../utils/atomicWriteFile.js';+import {+ releaseCachePath,+ removeCachePath,+ retainCachePath,+ settleCachePathRemovals,+} from './cacheLease.js';+import { discoverMarketplace, type DiscoveredMarketplace, type DiscoverError } from './discover.js';+import {+ MarketGitError,+ cloneMarketplace,+ fetchMarketplace,+ type GitExecutor,+} from './git.js';+import { checkGitPreflight as checkGitPreflightImpl } from './preflight.js';+import { parseMarketSource } from './parse.js';+import { MarketSourceStore } from './store.js';++export interface MarketSourceManagerDeps {+ store: MarketSourceStore;+ /** Git 克隆缓存根目录(owner 作用域)。 */+ cloneRoot: string;+ gitExecutor?: GitExecutor;+ homeDir?: string;+ now?: () => string;+}++export interface DiscoveredSource {+ config: MarketSourceConfig;+ result:+ | { ok: true; marketplace: DiscoveredMarketplace }+ | { ok: false; code: DiscoverError; detail?: string };+}++/** 克隆目录名:可读的市场名片段 + 来源指纹,避免同名不同源互相覆盖。 */+export function marketCloneSlug(name: string, source: MarketSource): string {+ // 指纹定义与账本所有权校验共用 marketSourceKey,两处永不漂移。+ const hash = crypto+ .createHash('sha256')+ .update(marketSourceKey(source))+ .digest('hex')+ .slice(0, 10);+ const base =+ name+ .toLowerCase()+ .replace(/[^a-z0-9._-]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 40) || 'market';+ return `${base}-${hash}`;+}++/**+ * Windows 上 AV / 索引器 / 云同步会短暂占用刚 clone / cp 出来的目录里的文件,+ * 使 rename 抛 EBUSY / EACCES / EPERM。这些是瞬时锁,短退避重试即可解除;目标+ * 都是全新 UUID 路径(不存在覆盖问题),重试纯粹是等锁释放。其余错误立即上抛。+ */+async function renameWithRetry(from: string, to: string): Promise<void> {+ const transient = new Set(['EBUSY', 'EACCES', 'EPERM', 'ENOTEMPTY']);+ for (let attempt = 0; ; attempt += 1) {+ try {+ await fs.promises.rename(from, to);+ return;+ } catch (error) {+ const code = (error as NodeJS.ErrnoException)?.code;+ if (attempt >= 3 || !code || !transient.has(code)) throw error;+ await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));+ }+ }+}++/** 版本目录名比较:大小写不敏感。我们生成的版本名恒为小写 UUID,但备份还原 /+ * 跨 FS 迁移可能引入大小写漂移;不敏感比较确保绝不把 current 的大小写变体+ * 误判成历史版本删掉(方向永远偏向"不删")。 */+function sameVersionName(a: string, b: string): boolean {+ return a.toLowerCase() === b.toLowerCase();+}++export class MarketSourceManager {+ private readonly log = createLogger('plugin-market-sources');++ constructor(private readonly deps: MarketSourceManagerDeps) {}++ private now(): string {+ return this.deps.now?.() ?? new Date().toISOString();+ }++ /** 来源的缓存槽根目录(内含 versions/ 与 current 指针)。 */+ private cacheSlot(config: Pick<MarketSourceConfig, 'name' | 'source'>): string {+ return path.join(this.deps.cloneRoot, marketCloneSlug(config.name, config.source));+ }++ private versionsDir(slot: string): string {+ return path.join(slot, 'versions');+ }++ private currentPointer(slot: string): string {+ return path.join(slot, 'current');+ }++ /**+ * 一次刷新的暂存目录,刻意放在 versions/ 之外:git clone 会在目标同级建+ * `<dest>.staging-<uuid>`,若目标位于 versions/ 内,并发刷新的清理会把这些+ * 在途目录当历史版本删掉。versions/ 只承载完整版本目录。+ */+ private incomingDir(slot: string): string {+ return path.join(slot, 'incoming', crypto.randomUUID());+ }++ /**+ * 解析 Git 源当前生效的缓存版本目录。读取 current 指针得到版本名,+ * 校验其在 versions/ 内(防指针被改成穿越路径);旧布局(槽目录直接是+ * 缓存,含 marketplace.json)首次读取时迁移进 versions/ 并写指针。+ * 无法解析(指针缺失/失效且非旧布局)返回 null。+ *+ * **必须保持全同步**:调用方要在同一个同步块里解析 + 登记引用(见+ * acquireCurrentVersion),中间出现 await 就会重新引入"解析到登记"的窗口。+ */+ private resolveCurrentVersionSync(+ config: Pick<MarketSourceConfig, 'name' | 'source'>,+ ): string | null {+ const slot = this.cacheSlot(config);+ const pointer = this.currentPointer(slot);+ // 已有指针:按指针解析。指针也是原子写维护的文件,备份交换连续失败时唯一有效+ // 的那份会留在 `current.bak` —— 只看主文件会把仍有完整版本的缓存判成缺失,+ // 整个来源报 market root missing。所以经 readAtomicFileSync 读,让它先恢复。+ if (fs.existsSync(pointer) || fs.existsSync(`${pointer}.bak`)) {+ try {+ const version = (readAtomicFileSync(pointer) ?? '').trim();+ // 版本名必须是 versions/ 下的直接子目录名,拒绝绝对路径与穿越。+ if (version && !version.includes('/') && !version.includes('\\') && version !== '..' && version !== '.') {+ const dir = path.join(this.versionsDir(slot), version);+ if (fs.existsSync(dir)) return dir;+ }+ this.log.warn('marketplace cache pointer invalid', { name: config.name, version });+ return null;+ } catch (error) {+ // 指针读不出来(含备份也恢复不了)按"无可用缓存"处理即可 —— 与 ledger /+ // 来源配置不同,缓存是可重建的:返回 null 会让下次刷新整目录重克隆,+ // 不存在"用空数据覆盖用户资产"的风险。+ this.log.error('failed to read marketplace cache pointer', {+ name: config.name,+ error: error instanceof Error ? error.message : String(error),+ });+ return null;+ }+ }+ // 旧布局迁移:槽目录直接是缓存(含 .agents 或 marketplace.json)。+ if (this.looksLikeLegacyCache(slot)) {+ const version = `legacy-${crypto.randomUUID()}`;+ const dir = path.join(this.versionsDir(slot), version);+ try {+ // 目标版本目录必须先存在,逐项搬入才不会因父目录缺失报 ENOENT。+ fs.mkdirSync(dir, { recursive: true });+ // 把槽目录里除 versions/current/incoming 外的内容整体搬进版本目录。+ const keep = new Set(['versions', 'current', 'incoming']);+ for (const entry of fs.readdirSync(slot)) {+ if (keep.has(entry)) continue;+ // 符号链接条目不搬(与打包/读取侧同口径:一律不跟随)。留在旧槽根即可,+ // 读取只经 versions/ 目录,永不跟随它;删除留给缓存删除唯一入口,本文件+ // 不做任何直接的文件系统删除(结构门禁)。+ const src = path.join(slot, entry);+ if (fs.lstatSync(src).isSymbolicLink()) continue;+ fs.renameSync(src, path.join(dir, entry));+ }+ atomicWriteFileSync(pointer, version);+ this.log.warn('migrated legacy marketplace cache layout', { name: config.name });+ return dir;+ } catch (error) {+ this.log.error('failed to migrate legacy marketplace cache', {+ name: config.name,+ error: error instanceof Error ? error.message : String(error),+ });+ return null;+ }+ }+ return null;+ }++ /**+ * 解析当前版本目录并登记一个读取引用。**解析与登记之间没有 await**:+ * JS 单线程 run-to-completion 保证这段同步块执行期间不会有任何 fs 回调+ * (包括并发刷新的清理)插入,因此不存在"解析到旧目录、登记前被删"的窗口。+ */+ private acquireCurrentVersion(+ config: Pick<MarketSourceConfig, 'name' | 'source'>,+ ): string | null {+ const dir = this.resolveCurrentVersionSync(config);+ if (!dir) return null;+ retainCachePath(dir);+ return dir;+ }++ /**+ * 该缓存槽当前是否仍被某个已配置来源占用(整槽删除在执行前的再核对)。+ *+ * 整槽删除可能因租约被推迟。推迟期间用户完全可以移除后**立刻重新添加同名同源**+ * 的来源——槽路径只由 (name, source) 派生,于是同一个槽被复用、写入并激活了新+ * 版本。此时若不核对就执行那笔延迟删除,会把刚添加成功的缓存连 current 指针一起+ * 递归删掉,配置有效但市场内容不见了(报 MARKET_SOURCE_INVALID / market root+ * missing)。按"槽是否仍被配置占用"判定,同时覆盖两种情形:重新添加同源(同槽,+ * 放弃删除)与重新添加异源(异槽,旧槽照常回收)。+ */+ private slotIsConfigured(slot: string): boolean {+ try {+ return this.deps.store.list().some((config) => this.cacheSlot(config) === slot);+ } catch {+ // 读不到配置时按"仍被占用"处理:宁可漏回收磁盘,也不误删有效缓存。+ return true;+ }+ }++ /** 目录是否为其所属槽当前生效的版本(推迟清理执行前的再核对)。 */+ private isCurrentVersionDir(dir: string): boolean {+ // 版本目录布局固定为 <slot>/versions/<version>。+ const slot = path.dirname(path.dirname(dir));+ try {+ // 经 readAtomicFileSync:主文件缺失但 current.bak 是唯一有效指针时,+ // 裸读会把当前版本误判成"非 current",让延迟删除把它删掉。+ const text = readAtomicFileSync(this.currentPointer(slot));+ if (text === null) return false;+ return sameVersionName(text.trim(), path.basename(dir));+ } catch {+ // 指针读不出来(文件锁/备份救不回来):事实不明,宁可不删。+ return true;+ }+ }++ /**+ * 在持有版本目录读取引用的作用域内执行 fn。租约必须覆盖到目录的**最后一次+ * 使用**为止(例如自定义源安装要一直持到 .cindy 打包完成),否则并发刷新的+ * 清理仍能在使用途中把目录抽走。+ */+ private async withCurrentVersion<T>(+ config: Pick<MarketSourceConfig, 'name' | 'source'>,+ fn: (dir: string | null) => Promise<T>,+ ): Promise<T> {+ const dir = this.acquireCurrentVersion(config);+ if (!dir) return fn(null);+ try {+ return await fn(dir);+ } finally {+ releaseCachePath(dir);+ }+ }++ /**+ * 删除一个缓存目录。所有缓存删除都必须走这里(它再走 `removeCachePath` 这个+ * 唯一入口):有租约重叠就自动推迟,调用点不需要、也不允许自己判断。+ */+ private async removeCacheDir(+ dir: string,+ options: { skipIf?: () => boolean } = {},+ ): Promise<void> {+ await removeCachePath(dir, {+ ...options,+ onError: (error: unknown) => {+ this.log.warn('failed to remove marketplace cache directory', {+ target: path.basename(dir),+ error: error instanceof Error ? error.message : String(error),+ });+ },+ });+ }++ /** 旧布局判定:槽目录本身含市场内容(.agents 目录)。 */+ private looksLikeLegacyCache(slot: string): boolean {+ if (!fs.existsSync(slot)) return false;+ try {+ // lstat 拒符号链接:槽被换成指向别处的链接时,迁移会把外部目录的条目+ // rename 进版本目录(数据破坏 + 把外部内容当市场内容读)。槽必须是真目录。+ return fs.lstatSync(slot).isDirectory() && fs.existsSync(path.join(slot, '.agents'));+ } catch {+ return false;+ }+ }++ /**+ * 刷新后让新版本生效:只做一件事——原子写 current 指针指向新版本目录。+ * 指针切换是唯一的生效动作:切换前解析到旧版→旧版还在(清理受引用保护),+ * 切换后解析到新版→新版已完成完整发现验证。+ */+ private async activateVersion(slot: string, newVersion: string): Promise<void> {+ atomicWriteFileSync(this.currentPointer(slot), newVersion);+ }++ /**+ * 清理历史版本:删除 versions/ 里非 current 的目录。是否真的能删由+ * `removeCacheDir` 的租约守卫决定 —— 刚被切下来的那一代往往正被并发的发现/+ * 详情/安装打包使用,守卫会把删除推迟到最后一个租约释放。+ */+ private async pruneStaleVersions(slot: string): Promise<void> {+ // 指针经 readAtomicFileSync 读取(含 .bak 恢复):Windows 备份交换失败后+ // 主文件缺失但 current.bak 仍是唯一有效指针,裸读会把"有 current"误判成+ // "无 current",清理逻辑与实际生效版本脱节。读不出指针(null / 抛错)一律+ // 不清理——事实不明时宁可多留磁盘,不冒删错的险。+ let current: string;+ try {+ const text = readAtomicFileSync(this.currentPointer(slot));+ if (text === null) return;+ current = text.trim();+ } catch {+ return;+ }+ let entries: string[];+ try {+ entries = await fs.promises.readdir(this.versionsDir(slot));+ } catch {+ return;+ }+ for (const entry of entries) {+ if (sameVersionName(entry, current)) continue;+ // 仅删除 versions/ 内的直接子目录,防穿越。+ if (entry.includes('/') || entry.includes('\\') || entry === '..' || entry === '.') continue;+ const dir = path.join(this.versionsDir(slot), entry);+ // 推迟期间该版本可能又成了 current(并发刷新把它激活了),执行前再核对。+ await this.removeCacheDir(dir, { skipIf: () => this.isCurrentVersionDir(dir) });+ }+ await this.pruneStaleIncoming(slot);+ }++ /**+ * 清理 incoming/ 里已死的暂存目录(进程在刷新途中被杀会留下残骸)。+ * 在途的暂存目录由租约守卫按前缀放过 —— git clone 的+ * `<incoming>.staging-<uuid>` 是兄弟目录,正好落在守卫的字符串前缀判据里。+ */+ private async pruneStaleIncoming(slot: string): Promise<void> {+ const root = path.join(slot, 'incoming');+ let entries: string[];+ try {+ entries = await fs.promises.readdir(root);+ } catch {+ return;+ }+ for (const entry of entries) {+ if (entry.includes('/') || entry.includes('\\') || entry === '..' || entry === '.') continue;+ await this.removeCacheDir(path.join(root, entry));+ }+ }++ /**+ * 清理 cloneRoot 顶层的 `.incoming-*` / `.staging-*` 残骸(add 途中进程被杀+ * 遗留)。它们在任何 slot 之外,pruneStaleIncoming/Versions 都扫不到。仍被+ * 租约持有的(正在进行的 add)由 removeCachePath 守卫按前缀跳过。+ */+ private async pruneStaleCloneStaging(): Promise<void> {+ let entries: string[];+ try {+ entries = await fs.promises.readdir(this.deps.cloneRoot);+ } catch {+ return;+ }+ for (const entry of entries) {+ if (!entry.startsWith('.incoming-') && !entry.startsWith('.staging-')) continue;+ await this.removeCacheDir(path.join(this.deps.cloneRoot, entry));+ }+ }++ async addSource(input: {+ source: string;+ ref?: string;+ sparsePaths?: string[];+ }): Promise<MarketSourceSummary> {+ const parsed = parseMarketSource(input, this.deps.homeDir ?? os.homedir());+ if (!parsed.ok) {+ throwIpcError('MARKET_SOURCE_INVALID', parsed.code);+ }+ const source = parsed.source;++ if (this.deps.store.hasEquivalent(source)) {+ throwIpcError('ALREADY_EXISTS', 'This marketplace source has already been added');+ }++ if (source.type === 'local') {+ let stat: fs.Stats;+ try {+ stat = fs.statSync(source.path);+ } catch {+ throwIpcError('MARKET_SOURCE_INVALID', 'LOCAL_SOURCE_NOT_DIRECTORY');+ }+ if (!stat!.isDirectory()) {+ throwIpcError('MARKET_SOURCE_INVALID', 'LOCAL_SOURCE_NOT_DIRECTORY');+ }+ return this.commitDiscoveredSource(source, source.path, null);+ }++ // Git 源:前置检测 → 克隆到独立目录 → 发现验证 → 激活为新版本。+ const preflight = await checkGitPreflightImpl(this.deps.gitExecutor);+ if (!preflight.ok) {+ throwIpcError('MARKET_GIT_UNAVAILABLE', preflight.version ?? 'git not found');+ }+ // 进程在上次 add 途中被杀会在 cloneRoot 顶层留下 `.incoming-*`(及其+ // `.staging-*` 兄弟),这两者不在任何 slot 内,pruneStale* 扫不到,会永久+ // 占盘。新建前先扫掉未被租约持有的残骸(被持有的由守卫跳过)。+ await this.pruneStaleCloneStaging();+ const incoming = path.join(this.deps.cloneRoot, `.incoming-${crypto.randomUUID()}`);+ let revision: string;+ try {+ revision = await cloneMarketplace(+ { url: source.url, ...(source.ref ? { ref: source.ref } : {}), sparsePaths: source.sparsePaths },+ incoming,+ this.deps.gitExecutor,+ );+ } catch (error) {+ if (error instanceof MarketGitError) {+ // 原始 git 输出(含命令行与内部路径)只进 main 日志;Renderer 拿到的是+ // 消毒后的 detail。IpcError 不经 invokePluginMarket 的兜底日志,这里必须留痕。+ this.log.warn('marketplace clone failed', { code: error.code, detail: error.message });+ throwIpcError(error.code, error.message);+ }+ throw error;+ }+ try {+ return await this.commitDiscoveredSource(source, incoming, revision);+ } catch (error) {+ await this.removeCacheDir(incoming);+ throw error;+ }+ }++ /**+ * 发现 + 校验 + 落盘。Git 源的 discoveredRoot 先落在独立目录,持久化成功后+ * 整体搬入版本目录并激活(写 current 指针);名称冲突等失败由调用方清理。+ */+ private async commitDiscoveredSource(+ source: MarketSource,+ discoveredRoot: string,+ revision: string | null,+ ): Promise<MarketSourceSummary> {+ const discovered = await discoverMarketplace(discoveredRoot);+ if (!discovered.ok) {+ throwIpcError(discovered.code, discovered.detail ?? discovered.code);+ }+ const name = discovered.marketplace.name;+ if (this.deps.store.get(name)) {+ throwIpcError('ALREADY_EXISTS', `A marketplace named "${name}" has already been added`);+ }+ const config: MarketSourceConfig = {+ name,+ addedAt: this.now(),+ lastSyncedAt: this.now(),+ lastRevision: revision,+ source,+ };+ if (source.type === 'git') {+ const slot = this.cacheSlot(config);+ const version = crypto.randomUUID();+ const dir = path.join(this.versionsDir(slot), version);+ // 复用缓存槽的全过程(清残骸 → 落位 → 切指针 → 写配置)都对**整个槽**持租约。+ //+ // 这是必需的,而且比"先清理 + 等在途删除"更强:那两步只能处理"已经启动"的+ // 删除,而移除来源留下的那笔可能仍躺在 deferred 里,会在 settle 返回后、+ // store.add 之前因旧租约释放而启动 —— 那时 slotIsConfigured() 还是 false,+ // 于是它与紧随的 mkdir/rename 并发,把刚重建的槽删掉。持槽租约则让守卫+ // 无法启动这笔删除,等本段结束释放时配置已写入,skipIf 直接否决它。+ retainCachePath(slot);+ try {+ // 清掉同 slug 的历史残骸(带"槽已被配置占用则放弃"的再核对);此刻本方法+ // 自己持有槽租约,所以它必然被推迟,由本段末尾释放后统一判定。+ await this.removeCacheDir(slot, { skipIf: () => this.slotIsConfigured(slot) });+ // 已经启动的删除仍要等它跑完——租约挡不住早于它启动的那笔。+ await settleCachePathRemovals(slot);+ await fs.promises.mkdir(this.versionsDir(slot), { recursive: true });+ await renameWithRetry(discoveredRoot, dir);+ atomicWriteFileSync(this.currentPointer(slot), version);+ // 配置必须在**释放槽租约之前**写入:这样任何被推迟的整槽删除在释放时+ // 立刻看到"槽已被配置占用"并放弃,不存在中间空档。+ this.deps.store.add(config);+ } finally {+ releaseCachePath(slot);+ }+ return this.toSummary(config, discovered.marketplace);+ }+ this.deps.store.add(config);+ return this.toSummary(config, discovered.marketplace);+ }++ async removeSource(name: string): Promise<{ ok: true }> {+ const removed = this.deps.store.remove(name);+ if (!removed) {+ throwIpcError('NOT_FOUND', 'The marketplace source is not added');+ }+ if (removed.source.type === 'git') {+ // 整槽递归删同样要过租约守卫:并发的详情发现/快照/安装打包可能正持有槽内+ // 某个版本目录,直接删会让它们读到一半 ENOENT(安装失败或来源误报无效)。+ // 守卫按重叠判定(租约在目标之下也算),把删除推迟到最后一个租约释放;+ // 配置已从 store 移除,来源对用户即刻消失,残留缓存只是延后回收。+ //+ // 推迟期间用户可能移除后立刻重新添加同名同源 —— 那会复用同一个槽,所以执行+ // 前必须再核对一次"槽是否仍被配置占用",否则会把刚重新添加的缓存删掉。+ const slot = this.cacheSlot(removed);+ await this.removeCacheDir(slot, { skipIf: () => this.slotIsConfigured(slot) });+ }+ return { ok: true };+ }++ async refreshSource(name: string): Promise<MarketSourceSummary> {+ const config = this.deps.store.get(name);+ if (!config) {+ throwIpcError('NOT_FOUND', 'The marketplace source is not added');+ }++ if (config.source.type === 'local') {+ if (!fs.existsSync(config.source.path)) {+ throwIpcError('MARKET_SOURCE_INVALID', 'LOCAL_SOURCE_NOT_DIRECTORY');+ }+ const discovered = await discoverMarketplace(config.source.path);+ if (!discovered.ok) {+ throwIpcError(discovered.code, discovered.detail ?? discovered.code);+ }+ const syncedAt = this.now();+ this.deps.store.update(name, { lastSyncedAt: syncedAt });+ return this.toSummary({ ...config, lastSyncedAt: syncedAt }, discovered.marketplace);+ }++ const preflight = await checkGitPreflightImpl(this.deps.gitExecutor);+ if (!preflight.ok) {+ throwIpcError('MARKET_GIT_UNAVAILABLE', preflight.version ?? 'git not found');+ }+ const slot = this.cacheSlot(config);+ const gitSource = config.source;+ const newVersion = crypto.randomUUID();+ const newDir = path.join(this.versionsDir(slot), newVersion);+ // 暂存目录必须落在 versions/ **之外**:cloneMarketplace 会在目标同级建+ // `<dest>.staging-<uuid>`,目标若在 versions/ 内,并发刷新切完指针后的清理+ // 会把别人正在写入的 staging 目录当历史版本删掉。versions/ 只放完整版本,+ // 清理就永远碰不到在途工作。+ //+ // 两个候选暂存目录:快进用一个,回落重克隆用**另一个全新的**。不复用同一个+ // "先清理再重用"——清理要过租约守卫、可能被推迟,复用会让 clone 写进脏目录。+ // 两个都登记租约,守卫据此按前缀放过 git 的 `<dest>.staging-<uuid>` 兄弟目录。+ const staging = [this.incomingDir(slot), this.incomingDir(slot)] as const;+ const [fastForwardDir, cloneDir] = staging;+ for (const dir of staging) retainCachePath(dir);+ try {+ // 刷新同样往这个槽里写:先等与它重叠的在途删除结束,免得新版本被一笔"移除+ // 来源"遗留的在途整槽删除带走。+ await settleCachePathRemovals(slot);+ await fs.promises.mkdir(path.dirname(fastForwardDir), { recursive: true });+ await fs.promises.mkdir(this.versionsDir(slot), { recursive: true });+ // 快进要整目录复制当前版本并在其上 fetch:登记读取引用,否则并发刷新的+ // 清理能在复制途中删掉源目录。引用在快进段结束后立刻释放(见 finally)。+ const current = this.acquireCurrentVersion(config);+ // 两条路径(快进成功 / 重克隆)都会赋值或抛出,此处仅满足 TS 的确定性赋值分析。+ let revision = '';+ let stagedDir = fastForwardDir;+ let discovered: Extract<+ Awaited<ReturnType<typeof discoverMarketplace>>,+ { ok: true }+ >;+ try {+ let fastForwarded = false;+ if (current) {+ // 快进路径:复制当前版本到暂存目录,在暂存目录内快进。+ try {+ await fs.promises.cp(current, fastForwardDir, { recursive: true });+ revision = await fetchMarketplace(+ current,+ gitSource.ref,+ this.deps.gitExecutor,+ fastForwardDir,+ );+ fastForwarded = true;+ } catch {+ fastForwarded = false;+ }+ }+ if (!fastForwarded) {+ // 无当前版本或快进失败(历史改写/缓存损坏):整目录重克隆到另一个暂存目录。+ stagedDir = cloneDir;+ try {+ revision = await cloneMarketplace(+ {+ url: gitSource.url,+ ...(gitSource.ref ? { ref: gitSource.ref } : {}),+ sparsePaths: gitSource.sparsePaths,+ },+ cloneDir,+ this.deps.gitExecutor,+ );+ } catch (error) {+ if (error instanceof MarketGitError) throwIpcError(error.code, error.message);+ throw error;+ }+ }+ // 在暂存目录完成完整发现验证,通过后才落位并激活;失败时当前版本不动,+ // 暂存目录由本方法末尾的统一回收清掉。+ const staged = await discoverMarketplace(stagedDir);+ if (!staged.ok) {+ throwIpcError(staged.code, staged.detail ?? staged.code);+ }+ discovered = staged;+ } finally {+ // 快进段已结束(成功或回落重克隆),本次刷新不再使用旧版本目录。+ if (current) releaseCachePath(current);+ }+ // 落位前先登记引用:rename 进 versions/ 到切指针之间,新版本还不是 current,+ // 并发刷新的清理会把它当历史版本删掉。+ retainCachePath(newDir);+ try {+ try {+ await renameWithRetry(stagedDir, newDir);+ await this.activateVersion(slot, newVersion);+ } catch (error) {+ // 半落位目录交给守卫:它会在执行前再核对一次指针,指针一旦已经指向+ // newDir 就放弃删除——那时它是唯一有效缓存,删掉会留下"指针指向不存在+ // 目录"的槽,整个来源从列表消失。+ await this.removeCacheDir(newDir, { skipIf: () => this.isCurrentVersionDir(newDir) });+ throw error;+ }+ // —— 到这里指针已生效:newDir 是当前唯一有效缓存,后续任何失败都不得删它 ——+ // 指针已切到新版本:清理非 current 版本,仍被读取的推迟到引用释放后再删。+ await this.pruneStaleVersions(slot);+ const syncedAt = this.now();+ try {+ this.deps.store.update(name, { lastSyncedAt: syncedAt, lastRevision: revision });+ } catch (error) {+ // 元数据写入失败(磁盘满/只读/文件锁)不影响缓存有效性:如实上报失败,+ // 但绝不回收已生效的版本目录——下次刷新会重写元数据。+ this.log.error('failed to persist marketplace sync metadata', {+ name,+ error: error instanceof Error ? error.message : String(error),+ });+ throw error;+ }+ return this.toSummary(+ { ...config, lastSyncedAt: syncedAt, lastRevision: revision },+ discovered.marketplace,+ );+ } finally {+ releaseCachePath(newDir);+ }+ } finally {+ // 暂存目录统一在这里回收:成功的那个已被 rename 走、没用到的从未创建+ // (force rm 都是 no-op),失败的在这里清掉。先释放租约再删,守卫才会就地执行。+ for (const dir of staging) releaseCachePath(dir);+ for (const dir of staging) await this.removeCacheDir(dir);+ }+ }++ getConfig(name: string): MarketSourceConfig | null {+ return this.deps.store.get(name);+ }++ /**+ * 发现单个来源(详情 / 安装入口现查事实用)。+ *+ * 发现结果里的 `plugin.dir` 指向缓存版本目录:调用方**在 fn 返回后就不得再+ * 使用这些路径**。要跨到后续读盘(例如安装打包)的调用方必须把那段工作放进+ * fn 内,租约才覆盖到最后一次使用;否则并发刷新的清理可以在中途删掉目录。+ */+ async withDiscoveredSource<T>(+ name: string,+ fn: (discovered: DiscoveredSource) => Promise<T>,+ ): Promise<T> {+ const config = this.deps.store.get(name);+ if (!config) {+ throwIpcError('NOT_FOUND', 'The marketplace source is not added');+ }+ return this.withMarketRoot(config!, async (root) => {+ if (!root || !fs.existsSync(root)) {+ return fn({+ config: config!,+ result: { ok: false, code: 'MARKET_SOURCE_INVALID', detail: 'market root missing' },+ });+ }+ const discovered = await discoverMarketplace(root);+ return fn({+ config: config!,+ result: discovered.ok+ ? { ok: true, marketplace: discovered.marketplace }+ : {+ ok: false,+ code: discovered.code,+ ...(discovered.detail ? { detail: discovered.detail } : {}),+ },+ });+ });+ }++ /**+ * 发现单个来源并返回结果。只读取发现出的元数据时用这个;结果里的+ * `plugin.dir` 在返回后已不受租约保护,需要继续读盘请改用+ * `withDiscoveredSource`。+ */+ async discoverSource(name: string): Promise<DiscoveredSource> {+ return this.withDiscoveredSource(name, async (discovered) => discovered);+ }++ /** 管理视图用:全部来源 + 实时发现状态。单个源失败不影响其它源。 */+ async listSources(): Promise<MarketSourceSummary[]> {+ const discovered = await this.discoverAll();+ return discovered.map((entry) =>+ entry.result.ok+ ? this.toSummary(entry.config, entry.result.marketplace)+ : {+ ...entry.config,+ pluginCount: 0,+ status: 'error' as const,+ errorCode: entry.result.code,+ },+ );+ }++ /** 快照聚合用:全部来源的发现结果(含失败)。 */+ async discoverAll(): Promise<DiscoveredSource[]> {+ const configs = this.deps.store.list();+ const results: DiscoveredSource[] = [];+ for (const config of configs) {+ await this.withMarketRoot(config, async (root) => {+ if (!root || !fs.existsSync(root)) {+ results.push({+ config,+ result: { ok: false, code: 'MARKET_SOURCE_INVALID', detail: 'market root missing' },+ });+ return;+ }+ const discovered = await discoverMarketplace(root);+ results.push({+ config,+ result: discovered.ok+ ? { ok: true, marketplace: discovered.marketplace }+ : {+ ok: false,+ code: discovered.code,+ ...(discovered.detail ? { detail: discovered.detail } : {}),+ },+ });+ });+ }+ return results;+ }++ /**+ * 在持有读取引用的作用域内提供来源的市场根目录:Git 源是当前缓存版本目录+ * (受引用保护,fn 执行期间不会被清理删掉),本地源是用户目录(用户自管,+ * 客户端不清理,无需引用)。+ */+ private async withMarketRoot<T>(+ config: MarketSourceConfig,+ fn: (root: string | null) => Promise<T>,+ ): Promise<T> {+ if (config.source.type === 'local') return fn(config.source.path);+ return this.withCurrentVersion(config, fn);+ }++ private toSummary(+ config: MarketSourceConfig,+ marketplace: DiscoveredMarketplace,+ ): MarketSourceSummary {+ return {+ ...config,+ pluginCount: marketplace.plugins.length,+ status: 'ok',+ errorCode: null,+ };+ }+}diff --git a/apps/desktop/src/main/plugin-market/sources/parse.ts b/apps/desktop/src/main/plugin-market/sources/parse.tsnew file mode 100644index 0000000000..7468037176--- /dev/null+++ b/apps/desktop/src/main/plugin-market/sources/parse.ts@@ -0,0 +1,157 @@+/**+ * 自定义插件市场来源解析。+ *+ * 把用户输入(GitHub shorthand / Git URL / 本地路径)归一成 MarketSource。+ * 纯函数、无副作用:本地路径只做形状判断,存在性检查由 SourceManager 在+ * 添加时执行(parse 阶段不碰文件系统,便于单测与 Renderer 即时校验复用)。+ */+import path from 'node:path';++import type { MarketSource } from '../../../shared/pluginMarket.js';++export type MarketSourceParseError =+ | 'EMPTY_SOURCE'+ | 'REF_NOT_ALLOWED_FOR_LOCAL'+ | 'SPARSE_NOT_ALLOWED_FOR_LOCAL'+ | 'INVALID_SOURCE_FORMAT'+ | 'INVALID_REF'+ | 'INVALID_SPARSE_PATH'+ | 'CREDENTIALS_NOT_ALLOWED';++export type MarketSourceParseResult =+ | { ok: true; source: MarketSource }+ | { ok: false; code: MarketSourceParseError };++/** Git 引用(branch / tag / commit)允许的字符集;拒绝选项注入(- 开头)与路径穿越。 */+const REF_PATTERN = /^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/;+/**+ * 控制字符与双向文本控制符:URL / sparsePaths 里出现即拒。U+202E 等可让来源+ * 在 UI 单行里显示成另一个域名(视觉欺骗),控制字符则可注入日志与终端。+ * 与 discover 的市场名闸(FORBIDDEN_NAME_CHARS)同一口径。+ */+// eslint-disable-next-line no-control-regex+const FORBIDDEN_SOURCE_CHARS = /[\u0000-\u001f\u007f\u200e\u200f\u202a-\u202e\u2066-\u2069]/;+/** GitHub shorthand:owner/repo,各段为常见 GitHub 命名字符。 */+const GITHUB_SHORTHAND_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]{1,100}$/;+// 仅允许经认证的传输:https(服务端证书)、ssh/git@(SSH agent)。+// 明文 git:// 无服务端认证与传输加密,链路可被中间人篡改插件代码,拒绝。+const GIT_URL_PATTERN = /^(https:\/\/|ssh:\/\/|git@)[^\s]+$/i;++function looksLikeLocalPath(input: string): boolean {+ if (input.startsWith('~')) return true;+ if (path.isAbsolute(input)) return true;+ // Windows 盘符路径(C:\... / C:/...)。+ if (/^[A-Za-z]:[\\/]/.test(input)) return true;+ // 显式相对路径(./plugins、../shared)按本地路径对待。+ if (input.startsWith('./') || input.startsWith('../') || input.startsWith('.\\') || input.startsWith('..\\')) {+ return true;+ }+ return false;+}++function hasEmbeddedCredentials(input: string): boolean {+ // https:// 明文 URL 的凭证会随 source 持久化并回传 Renderer,必须拒绝。+ // ssh:// 的 username 是认证主体(git@ 是标准形式),由 SSH agent 持有私钥,不算内嵌凭证。+ if (/^https?:\/\//i.test(input)) {+ try {+ const parsed = new URL(input);+ if (parsed.username.length > 0 || parsed.password.length > 0) return true;+ // 查询参数同样可携带签名/令牌(?access_token=SECRET),市场仓库 URL+ // 不需要 query,一律拒绝,引导走 credential helper / SSH,而非白名单剥离。+ if (parsed.search.length > 0 || parsed.hash.length > 0) return true;+ } catch {+ // 解析不了的串无从判定 userinfo,按"可能带凭证"拒绝(fail closed)。+ return true;+ }+ }+ // ssh:// 的 username 是认证主体,但 password 位是明文凭证;query / fragment+ // 同样能塞令牌或签名并随 source 持久化、在 UI 摘要里露出,一并拒绝。+ if (/^ssh:\/\//i.test(input)) {+ try {+ const parsed = new URL(input);+ return parsed.password.length > 0 || parsed.search.length > 0 || parsed.hash.length > 0;+ } catch {+ return true;+ }+ }+ // scp 形态(git@host:owner/repo.git)不是合法 URL,new URL 解析不了。它同样不该+ // 带 query / fragment —— `git@host:repo.git?token=...` 会被 GIT_URL_PATTERN 接受,+ // 然后把令牌一路持久化下去。+ if (/^[^\s/@]+@[^\s:/]+:/.test(input)) {+ return input.includes('?') || input.includes('#');+ }+ return false;+}++/** 展开 ~ 并归一化;不解析符号链接(归属判断由安装管道负责)。 */+export function resolveLocalSourcePath(input: string, homeDir: string): string {+ const expanded = input.startsWith('~')+ ? path.join(homeDir, input.slice(1).replace(/^[/\\]/, ''))+ : input;+ return path.resolve(expanded);+}++function validSparsePaths(paths: readonly string[]): boolean {+ return paths.every((entry) => {+ const trimmed = entry.trim();+ if (!trimmed || trimmed.length > 256) return false;+ if (FORBIDDEN_SOURCE_CHARS.test(trimmed)) return false;+ if (trimmed.startsWith('/') || trimmed.startsWith('\\')) return false;+ if (/^[A-Za-z]:/.test(trimmed)) return false;+ // 拒绝 Git 选项注入(--stdin 会让 sparse-checkout 读 stdin 直至超时)。+ if (trimmed.startsWith('-')) return false;+ // 拒绝路径穿越;sparse-checkout 只允许仓库内相对目录。+ return !trimmed.split(/[/\\]/).includes('..');+ });+}++/**+ * 解析用户输入的市场来源。`homeDir` 由调用方注入(Main 取 os.homedir(),+ * 测试注入固定值),保持本模块不直接读进程环境。+ */+export function parseMarketSource(+ input: { source: string; ref?: string; sparsePaths?: string[] },+ homeDir: string,+): MarketSourceParseResult {+ const trimmed = input.source.trim();+ const ref = input.ref?.trim() || undefined;+ const sparsePaths = (input.sparsePaths ?? [])+ .map((entry) => entry.trim())+ .filter((entry) => entry.length > 0);++ if (!trimmed) return { ok: false, code: 'EMPTY_SOURCE' };+ if (FORBIDDEN_SOURCE_CHARS.test(trimmed)) return { ok: false, code: 'INVALID_SOURCE_FORMAT' };+ if (ref && !REF_PATTERN.test(ref)) return { ok: false, code: 'INVALID_REF' };+ if (!validSparsePaths(sparsePaths)) return { ok: false, code: 'INVALID_SPARSE_PATH' };++ if (looksLikeLocalPath(trimmed)) {+ if (ref) return { ok: false, code: 'REF_NOT_ALLOWED_FOR_LOCAL' };+ if (sparsePaths.length > 0) return { ok: false, code: 'SPARSE_NOT_ALLOWED_FOR_LOCAL' };+ return { ok: true, source: { type: 'local', path: resolveLocalSourcePath(trimmed, homeDir) } };+ }++ if (GIT_URL_PATTERN.test(trimmed)) {+ // WHATWG URL 把 `\` 当 `/` 归一,git 却按原样解析 authority:+ // `https://TOKEN\@host/...` 在 new URL 里看不到 userinfo(凭证闸失明),+ // git 实际连的 host 也与校验层认定的不一致(供应链/视觉欺骗)。一律拒。+ if (trimmed.includes('\\')) return { ok: false, code: 'INVALID_SOURCE_FORMAT' };+ if (hasEmbeddedCredentials(trimmed)) {+ return { ok: false, code: 'CREDENTIALS_NOT_ALLOWED' };+ }+ return { ok: true, source: { type: 'git', url: trimmed, ...(ref ? { ref } : {}), sparsePaths } };+ }++ if (GITHUB_SHORTHAND_PATTERN.test(trimmed)) {+ return {+ ok: true,+ source: {+ type: 'git',+ url: `https://github.com/${trimmed}.git`,+ ...(ref ? { ref } : {}),+ sparsePaths,+ },+ };+ }++ return { ok: false, code: 'INVALID_SOURCE_FORMAT' };+}diff --git a/apps/desktop/src/main/plugin-market/sources/preflight.ts b/apps/desktop/src/main/plugin-market/sources/preflight.tsnew file mode 100644index 0000000000..fe387777b4--- /dev/null+++ b/apps/desktop/src/main/plugin-market/sources/preflight.ts@@ -0,0 +1,28 @@+/**+ * Git 环境前置检测。+ *+ * 打开添加市场对话框时调用一次:Git 缺失或版本过低时禁用 Git 来源的添加+ * (本地来源不受影响)。结果不缓存——用户可能在会话中途装好 Git。+ */+import {+ gitVersion,+ isGitVersionSupported,+ type GitExecutor,+} from './git.js';++export interface GitPreflightResult {+ ok: boolean;+ /** 检测到的版本文本(如 "2.43.0");未安装/执行失败为 null。 */+ version: string | null;+}++export async function checkGitPreflight(+ executor?: GitExecutor,+): Promise<GitPreflightResult> {+ const version = await gitVersion(executor);+ if (!version) return { ok: false, version: null };+ return {+ ok: isGitVersionSupported(version),+ version: `${version.major}.${version.minor}`,+ };+}diff --git a/apps/desktop/src/main/plugin-market/sources/store.ts b/apps/desktop/src/main/plugin-market/sources/store.tsnew file mode 100644index 0000000000..72105a5d94--- /dev/null+++ b/apps/desktop/src/main/plugin-market/sources/store.ts@@ -0,0 +1,149 @@+/**+ * 自定义市场来源配置的持久化(sources.v1.json)。+ *+ * 与 PluginMarketLedger 同一套约定:schemaVersion 闸、逐条校验、原子写+ * (临时文件 + rename,Windows 下先删目标重试)、0o600。只存来源配置,+ * 不复制发现到的插件数据——快照时重新发现,磁盘上的克隆目录才是事实。+ */+import type { MarketSource, MarketSourceConfig } from '../../../shared/pluginMarket.js';+import { marketSourceKey } from '../../../shared/pluginMarket.js';+import { atomicWriteFileSync, readAtomicFileSync } from '../../utils/atomicWriteFile.js';++const SOURCES_SCHEMA_VERSION = 1;++interface MarketSourcesData {+ schemaVersion: typeof SOURCES_SCHEMA_VERSION;+ sources: MarketSourceConfig[];+}++function emptySources(): MarketSourcesData {+ return { schemaVersion: SOURCES_SCHEMA_VERSION, sources: [] };+}++function validSource(value: unknown): value is MarketSource {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;+ const source = value as Record<string, unknown>;+ if (source.type === 'local') {+ return typeof source.path === 'string' && source.path.length > 0;+ }+ if (source.type === 'git') {+ return (+ typeof source.url === 'string' &&+ source.url.length > 0 &&+ (source.ref === undefined || typeof source.ref === 'string') &&+ Array.isArray(source.sparsePaths) &&+ (source.sparsePaths as unknown[]).every((entry) => typeof entry === 'string')+ );+ }+ return false;+}++function validConfig(value: unknown): value is MarketSourceConfig {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;+ const config = value as Record<string, unknown>;+ return (+ typeof config.name === 'string' &&+ config.name.length > 0 &&+ typeof config.addedAt === 'string' &&+ (config.lastSyncedAt === null || typeof config.lastSyncedAt === 'string') &&+ (config.lastRevision === null || typeof config.lastRevision === 'string') &&+ validSource(config.source)+ );+}++export class MarketSourceStore {+ constructor(private readonly filePathSource: string | (() => string)) {}++ /**+ * Binds a dynamic owner-scoped store to the path captured at operation start.+ * Mirrors PluginMarketLedger.bind so owner switches never cross-write state.+ */+ bind(filePath: string): MarketSourceStore {+ return typeof this.filePathSource === 'function'+ ? new MarketSourceStore(filePath)+ : this;+ }++ private filePath(): string {+ return typeof this.filePathSource === 'function'+ ? this.filePathSource()+ : this.filePathSource;+ }++ list(): MarketSourceConfig[] {+ return this.read().sources;+ }++ get(name: string): MarketSourceConfig | null {+ return this.read().sources.find((source) => source.name === name) ?? null;+ }++ /** 追加新来源;调用方负责先完成名称与重复来源校验。 */+ add(config: MarketSourceConfig): void {+ const data = this.read();+ data.sources = [...data.sources.filter((source) => source.name !== config.name), config];+ this.write(data);+ }++ update(name: string, patch: Partial<Pick<MarketSourceConfig, 'lastSyncedAt' | 'lastRevision'>>): void {+ const data = this.read();+ const index = data.sources.findIndex((source) => source.name === name);+ if (index < 0) return;+ data.sources[index] = { ...data.sources[index]!, ...patch };+ this.write(data);+ }++ remove(name: string): MarketSourceConfig | null {+ const data = this.read();+ const existing = data.sources.find((source) => source.name === name) ?? null;+ if (!existing) return null;+ data.sources = data.sources.filter((source) => source.name !== name);+ this.write(data);+ return existing;+ }++ /** 重复添加判定:来源类型 + 定位 + 引用 + 稀疏路径全部一致视为同一来源。 */+ hasEquivalent(source: MarketSource): boolean {+ return this.read().sources.some((config) => sourcesEqual(config.source, source));+ }++ private read(): MarketSourcesData {+ // 读取入口恢复 .bak:主文件缺失时若直接读成空来源表,调用方随后的写入会用这份+ // 空数据永久覆盖唯一有效快照(全部自定义来源配置丢失)。+ //+ // 读失败与解析失败分开处理:文件不存在(ENOENT)才是空来源表;文件在但读不到+ // (文件锁/权限/瞬时 I/O)或备份救不回来时一律**上抛**。只有"内容确实不是合法+ // JSON"才按空来源表重建。+ const text = readAtomicFileSync(this.filePath());+ if (text === null) return emptySources();+ let raw: unknown;+ try {+ raw = JSON.parse(text);+ } catch {+ return emptySources();+ }+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return emptySources();+ const value = raw as Record<string, unknown>;+ if (value.schemaVersion !== SOURCES_SCHEMA_VERSION) return emptySources();+ if (!Array.isArray(value.sources)) return emptySources();+ return { schemaVersion: SOURCES_SCHEMA_VERSION, sources: value.sources.filter(validConfig) };+ }++ private write(data: MarketSourcesData): void {+ atomicWriteFileSync(this.filePath(), `${JSON.stringify(data, null, 2)}\n`);+ }+}++/**+ * 两个来源是否同一个。判据直接复用 `marketSourceKey` —— 它就是本仓库对"来源身份"+ * 的唯一定义(账本所有权校验、缓存 slug 都用它),这里再写一套等价逻辑只会漂移。+ *+ * 尤其不能用 `sparsePaths.join('\n')` 比较列表:分隔符碰撞(`['a\nb']` 与+ * `['a','b']` join 结果相同)会让两个不同的来源被判成同一个。`marketSourceKey`+ * 用 JSON 序列化,数组边界不可伪造(它自己也有碰撞对抗测试)。当前 parse 层的+ * FORBIDDEN_SOURCE_CHARS 已经拒掉换行、这条路走不通,但身份判据不该依赖"上游恰好+ * 拦住了某个字符"这种远距离前提。+ */+export function sourcesEqual(a: MarketSource, b: MarketSource): boolean {+ return marketSourceKey(a) === marketSourceKey(b);+}diff --git a/apps/desktop/src/main/utils/__tests__/atomicWriteFile.test.ts b/apps/desktop/src/main/utils/__tests__/atomicWriteFile.test.tsnew file mode 100644index 0000000000..05606b7dbd--- /dev/null+++ b/apps/desktop/src/main/utils/__tests__/atomicWriteFile.test.ts@@ -0,0 +1,175 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ AtomicBackupUnrecoverableError,+ atomicWriteFileSync,+ readAtomicFileSync,+} from '../atomicWriteFile';++const roots: string[] = [];++afterEach(() => {+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });+});++function makeFile(contents = 'old'): string {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-atomic-write-'));+ roots.push(root);+ const file = path.join(root, 'state.json');+ fs.writeFileSync(file, contents);+ return file;+}++describe('atomicWriteFileSync', () => {+ it('writes new contents replacing the existing file', () => {+ const file = makeFile();+ atomicWriteFileSync(file, 'new');+ expect(fs.readFileSync(file, 'utf8')).toBe('new');+ const dir = path.dirname(file);+ expect(fs.readdirSync(dir).filter((n) => n !== 'state.json')).toEqual([]);+ });++ it('creates the parent directory when missing', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-atomic-write-'));+ roots.push(root);+ const file = path.join(root, 'nested', 'deep', 'state.json');+ atomicWriteFileSync(file, 'created');+ expect(fs.readFileSync(file, 'utf8')).toBe('created');+ });++ it('restores a missing main file from .bak before writing', () => {+ const file = makeFile();+ // 模拟上次 temp 落位与恢复都失败:主文件缺失,.bak 是唯一快照。+ fs.renameSync(file, `${file}.bak`);+ expect(fs.existsSync(file)).toBe(false);+ atomicWriteFileSync(file, 'next');+ // 先把 .bak 恢复回主文件再写入新内容,唯一快照不被覆盖丢失。+ expect(fs.readFileSync(file, 'utf8')).toBe('next');+ expect(fs.existsSync(`${file}.bak`)).toBe(false);+ });++ it('clears a stale .bak from a previous failed write before writing', () => {+ const file = makeFile();+ fs.writeFileSync(`${file}.bak`, 'stale-backup');+ atomicWriteFileSync(file, 'fresh');+ expect(fs.readFileSync(file, 'utf8')).toBe('fresh');+ expect(fs.existsSync(`${file}.bak`)).toBe(false);+ });++ it('retries a transient EBUSY rename (Windows AV/索引器持句柄)而非硬失败', () => {+ const file = makeFile('old');+ const realRename = fs.renameSync;+ let flaky = 2; // 前两次抛 EBUSY,第三次放行+ const spy = vi.spyOn(fs, 'renameSync').mockImplementation(((from: string, to: string) => {+ if (String(from).endsWith('.tmp') && flaky > 0) {+ flaky -= 1;+ throw Object.assign(new Error('EBUSY'), { code: 'EBUSY' });+ }+ return realRename(from as never, to as never);+ }) as typeof fs.renameSync);+ try {+ atomicWriteFileSync(file, 'new');+ expect(fs.readFileSync(file, 'utf8')).toBe('new');+ } finally {+ spy.mockRestore();+ }+ });++ it('已成功落位后清理 .bak 失败不把成功报成失败', () => {+ // Windows 上 AV 占用刚生成的 .bak 会让 rm 抛 EPERM/EBUSY;这发生在 rename+ // 成功**之后**,不能反过来让整个写入抛错。这里用 EEXIST 触发备份交换分支,+ // 再让 .bak 的 rm 抛错,断言写入仍成功。+ const file = makeFile('old');+ const realRename = fs.renameSync;+ let firstTmpRename = true;+ const renameSpy = vi.spyOn(fs, 'renameSync').mockImplementation(((from: string, to: string) => {+ if (String(from).endsWith('.tmp') && String(to) === file && firstTmpRename) {+ firstTmpRename = false;+ throw Object.assign(new Error('EEXIST'), { code: 'EEXIST' }); // 逼入备份交换+ }+ return realRename(from as never, to as never);+ }) as typeof fs.renameSync);+ const realRm = fs.rmSync;+ const rmSpy = vi.spyOn(fs, 'rmSync').mockImplementation(((target: string, opts?: fs.RmOptions) => {+ if (String(target) === `${file}.bak`) {+ throw Object.assign(new Error('EPERM'), { code: 'EPERM' });+ }+ return realRm(target as never, opts as never);+ }) as typeof fs.rmSync);+ try {+ expect(() => atomicWriteFileSync(file, 'new')).not.toThrow();+ expect(fs.readFileSync(file, 'utf8')).toBe('new');+ } finally {+ renameSpy.mockRestore();+ rmSpy.mockRestore();+ }+ });+});++describe('readAtomicFileSync', () => {+ it('returns the main file contents when present', () => {+ const file = makeFile('kept');+ expect(readAtomicFileSync(file)).toBe('kept');+ });++ it('returns null when neither the main file nor .bak exists', () => {+ const file = makeFile();+ fs.rmSync(file);+ expect(readAtomicFileSync(file)).toBeNull();+ });++ it('rethrows non-ENOENT read failures instead of reporting empty', () => {+ const file = makeFile('real-content');+ // 文件明明在,只是被 Windows 文件锁/权限/瞬时 I/O 挡住。返回 null 会让调用方+ // 解释成空状态,那次写入随即用空状态派生的快照覆盖真实内容。+ const spy = vi.spyOn(fs, 'readFileSync').mockImplementation(() => {+ throw Object.assign(new Error('EBUSY'), { code: 'EBUSY' });+ });+ try {+ expect(() => readAtomicFileSync(file)).toThrow(/EBUSY/);+ } finally {+ spy.mockRestore();+ }+ // 真的不存在时仍按"空"处理。+ fs.rmSync(file);+ expect(readAtomicFileSync(file)).toBeNull();+ });++ it('throws instead of reporting empty when the .bak cannot be restored', () => {+ const file = makeFile('only-snapshot');+ fs.renameSync(file, `${file}.bak`);+ // 模拟 Windows 文件锁/杀毒占用:恢复用的 rename 失败。+ const renameSync = fs.renameSync;+ const spy = vi.spyOn(fs, 'renameSync').mockImplementation(((from: string, to: string) => {+ if (String(from) === `${file}.bak`) {+ throw Object.assign(new Error('EBUSY'), { code: 'EBUSY' });+ }+ return renameSync(from as never, to as never);+ }) as typeof fs.renameSync);+ try {+ // 关键:不能降级成 null。降级 = 调用方读成空数据 → 写入 → 主文件出现 →+ // 下一次写入把 .bak 当陈旧残留删掉,唯一有效快照永久丢失。+ expect(() => readAtomicFileSync(file)).toThrow(AtomicBackupUnrecoverableError);+ // 写入侧同样必须拒绝,不能用派生自空数据的内容覆盖唯一快照。+ expect(() => atomicWriteFileSync(file, '{}')).toThrow(AtomicBackupUnrecoverableError);+ expect(fs.readFileSync(`${file}.bak`, 'utf8')).toBe('only-snapshot');+ expect(fs.existsSync(file)).toBe(false);+ } finally {+ spy.mockRestore();+ }+ });++ it('restores and reads .bak when the main file is missing', () => {+ const file = makeFile('only-snapshot');+ // 主文件缺失、.bak 是唯一快照:读取入口必须先恢复再读。只在写入侧恢复时,+ // 调用方会先把这里读成空数据,再拿空数据发起写入把唯一快照覆盖掉。+ fs.renameSync(file, `${file}.bak`);+ expect(readAtomicFileSync(file)).toBe('only-snapshot');+ expect(fs.readFileSync(file, 'utf8')).toBe('only-snapshot');+ expect(fs.existsSync(`${file}.bak`)).toBe(false);+ });+});diff --git a/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts b/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.tsnew file mode 100644index 0000000000..de51382c40--- /dev/null+++ b/apps/desktop/src/main/utils/__tests__/readBoundedFile.test.ts@@ -0,0 +1,204 @@+/**+ * readBoundedFileNoFollow — 不可信目录单文件的安全读取。+ * 重点:符号链接一律拒(POSIX 走 O_NOFOLLOW,无该 flag 的平台走+ * lstat+dev/ino 回退闸),超限/非普通文件返回 null。+ */+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ GHOST_MANIFEST_MAX_BYTES,+ readBoundedFileNoFollow,+ readBoundedFileNoFollowSync,+} from '../readBoundedFile';++let workDir: string;++beforeEach(async () => {+ workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-bounded-read-'));+});++afterEach(async () => {+ await fs.promises.rm(workDir, { recursive: true, force: true });+});++describe('readBoundedFileNoFollow', () => {+ it('普通文件按实际字节返回,超限返回 null', async () => {+ const small = path.join(workDir, 'small.json');+ await fs.promises.writeFile(small, '{"ok":true}');+ expect((await readBoundedFileNoFollow(small, 1024))?.toString('utf8')).toBe('{"ok":true}');++ const big = path.join(workDir, 'big.json');+ await fs.promises.writeFile(big, 'x'.repeat(GHOST_MANIFEST_MAX_BYTES + 1));+ expect(await readBoundedFileNoFollow(big, GHOST_MANIFEST_MAX_BYTES)).toBeNull();+ });++ it.runIf(process.platform !== 'win32')('POSIX:符号链接在 open 处被 O_NOFOLLOW 拒绝', async () => {+ const target = path.join(workDir, 'target.json');+ await fs.promises.writeFile(target, '{"ok":true}');+ const link = path.join(workDir, 'link.json');+ await fs.promises.symlink(target, link);+ await expect(readBoundedFileNoFollow(link, 1024)).rejects.toThrow();+ });++ it.runIf(process.platform !== 'win32')(+ '无 O_NOFOLLOW 的平台:lstat 回退闸同样拒符号链接,目标合法也不放行',+ async () => {+ const target = path.join(workDir, 'target.json');+ await fs.promises.writeFile(target, '{"ok":true}');+ const link = path.join(workDir, 'link.json');+ await fs.promises.symlink(target, link);+ // 注入 null 模拟 Windows:open 会跟随链接,回退闸必须把它拦下来。+ expect(await readBoundedFileNoFollow(link, 1024, { noFollowFlag: null })).toBeNull();+ },+ );++ it('无 O_NOFOLLOW 的平台:普通文件不被回退闸误伤', async () => {+ const file = path.join(workDir, 'plain.json');+ await fs.promises.writeFile(file, '{"ok":1}');+ expect((await readBoundedFileNoFollow(file, 1024, { noFollowFlag: null }))?.toString('utf8')).toBe('{"ok":1}');+ });++ it.runIf(process.platform !== 'win32')(+ 'containWithin:中间目录被换成根外链接时拒绝(最终分量是普通文件,O_NOFOLLOW 拦不住)',+ async () => {+ const realWork = await fs.promises.realpath(workDir);+ const root = path.join(realWork, 'root');+ const outsideSub = path.join(realWork, 'outside', 'sub');+ await fs.promises.mkdir(root, { recursive: true });+ await fs.promises.mkdir(outsideSub, { recursive: true });+ await fs.promises.writeFile(path.join(outsideSub, 'ghost.json'), '{"ok":1}');+ await fs.promises.symlink(outsideSub, path.join(root, 'linkdir'));++ expect(+ await readBoundedFileNoFollow(path.join(root, 'linkdir', 'ghost.json'), 1024, {+ containWithin: root,+ }),+ ).toBeNull();+ expect(+ readBoundedFileNoFollowSync(path.join(root, 'linkdir', 'ghost.json'), 1024, {+ containWithin: root,+ }),+ ).toBeNull();++ // 根内正常文件不被复核误伤(含 root 自带链接祖先的情形:两侧都走 realpath)。+ await fs.promises.writeFile(path.join(root, 'plain.json'), '{"ok":2}');+ expect(+ (+ await readBoundedFileNoFollow(path.join(root, 'plain.json'), 1024, {+ containWithin: root,+ })+ )?.toString('utf8'),+ ).toBe('{"ok":2}');+ expect(+ readBoundedFileNoFollowSync(path.join(root, 'plain.json'), 1024, {+ containWithin: root,+ })?.toString('utf8'),+ ).toBe('{"ok":2}');+ },+ );++ it('网络盘短读:单次 read 未填满时循环读满已校验长度', async () => {+ const file = path.join(workDir, 'short.json');+ const payload = `{"key":"${'a'.repeat(64)}"}`;+ await fs.promises.writeFile(file, payload);+ // 模拟 FUSE/网络盘:每次 read 最多返回 7 字节。单次读会把合法文件截断。+ const realOpen = fs.promises.open;+ const spy = vi.spyOn(fs.promises, 'open').mockImplementation((async (+ ...args: Parameters<typeof fs.promises.open>+ ) => {+ const handle = await realOpen(...args);+ const realRead = handle.read.bind(handle);+ return new Proxy(handle, {+ get(target, key) {+ if (key === 'read') {+ return (buffer: Buffer, offset: number, length: number, position: number) =>+ realRead(buffer, offset, Math.min(length, 7), position);+ }+ const value = Reflect.get(target, key);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ }) as typeof fs.promises.open);+ try {+ const bytes = await readBoundedFileNoFollow(file, 1024);+ expect(bytes?.toString('utf8')).toBe(payload);+ } finally {+ spy.mockRestore();+ }+ });++ it.runIf(process.platform !== 'win32')(+ '回退闸:dev/ino 为 0(网络盘/无标识 FS)时拒绝,不退化成只看 isSymbolicLink',+ async () => {+ const file = path.join(workDir, 'zero-ino.json');+ await fs.promises.writeFile(file, '{"ok":1}');+ // 模拟 SMB/FUSE:句柄 stat 与 lstat 都拿不到可信 dev/ino(填 0)。没有 reject-0+ // 守卫时 0n===0n 恒真,回退闸退化成"证明句柄=路径目录项"永真,只剩+ // isSymbolicLink 一条。此时应拒绝(无法证明),而不是照读。走 noFollowFlag:null。+ const zero = (st: fs.BigIntStats): fs.BigIntStats =>+ new Proxy(st, {+ get(target, key) {+ if (key === 'dev' || key === 'ino') return 0n;+ const value = Reflect.get(target, key);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ const realOpen = fs.promises.open;+ const openSpy = vi.spyOn(fs.promises, 'open').mockImplementation((async (+ ...args: Parameters<typeof fs.promises.open>+ ) => {+ const handle = await realOpen(...args);+ const realStat = handle.stat.bind(handle);+ return new Proxy(handle, {+ get(target, key) {+ if (key === 'stat') {+ return async (opts?: fs.StatOptions) =>+ zero((await realStat(opts as never)) as unknown as fs.BigIntStats);+ }+ const value = Reflect.get(target, key);+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ }) as typeof fs.promises.open);+ const realLstat = fs.promises.lstat;+ const lstatSpy = vi+ .spyOn(fs.promises, 'lstat')+ .mockImplementation((async (p: fs.PathLike, opts?: fs.StatOptions) => {+ const st = (await (realLstat as (...a: unknown[]) => Promise<fs.BigIntStats>)(p, opts)) as fs.BigIntStats;+ return zero(st);+ }) as typeof fs.promises.lstat);+ try {+ expect(await readBoundedFileNoFollow(file, 1024, { noFollowFlag: null })).toBeNull();+ } finally {+ openSpy.mockRestore();+ lstatSpy.mockRestore();+ }+ },+ );+});++describe('readBoundedFileNoFollowSync', () => {+ it('限量与回退闸语义和异步变体一致', async () => {+ const file = path.join(workDir, 'plain.json');+ await fs.promises.writeFile(file, '{"ok":1}');+ expect(readBoundedFileNoFollowSync(file, 1024)?.toString('utf8')).toBe('{"ok":1}');+ expect(readBoundedFileNoFollowSync(file, 1024, { noFollowFlag: null })?.toString('utf8')).toBe('{"ok":1}');++ const big = path.join(workDir, 'big.json');+ await fs.promises.writeFile(big, 'x'.repeat(2048));+ expect(readBoundedFileNoFollowSync(big, 1024)).toBeNull();+ });++ it.runIf(process.platform !== 'win32')('符号链接:O_NOFOLLOW 拒于 open,回退闸拒于 lstat', async () => {+ const target = path.join(workDir, 'target.json');+ await fs.promises.writeFile(target, '{"ok":true}');+ const link = path.join(workDir, 'link.json');+ await fs.promises.symlink(target, link);+ expect(() => readBoundedFileNoFollowSync(link, 1024)).toThrow();+ expect(readBoundedFileNoFollowSync(link, 1024, { noFollowFlag: null })).toBeNull();+ });+});diff --git a/apps/desktop/src/main/utils/atomicWriteFile.ts b/apps/desktop/src/main/utils/atomicWriteFile.tsnew file mode 100644index 0000000000..d2b62dc8c9--- /dev/null+++ b/apps/desktop/src/main/utils/atomicWriteFile.ts@@ -0,0 +1,168 @@+import fs from 'node:fs';+import path from 'node:path';+import crypto from 'node:crypto';++/**+ * Windows 上 AV / 索引器 / 云同步会短暂占用刚落地的文件,rename 抛+ * EBUSY / EACCES,而不是 POSIX 直觉里的 EPERM / EEXIST。这些是瞬时锁,短退避+ * 重试即可解除;EPERM / EEXIST 属"无法覆盖已存在目标"的语义分歧,不在此列+ * (由调用方的备份交换兜底)。+ */+const TRANSIENT_RENAME_CODES = new Set(['EBUSY', 'EACCES', 'ENOTEMPTY']);++/** 同步小退避。状态文件都很小、重试上限低,阻塞时间可忽略。 */+function sleepSync(ms: number): void {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++/** rename 遇瞬时锁短退避重试;EPERM/EEXIST 与其余错误立即上抛。 */+function renameSyncWithRetry(from: string, to: string): void {+ for (let attempt = 0; ; attempt += 1) {+ try {+ fs.renameSync(from, to);+ return;+ } catch (error) {+ const code = (error as NodeJS.ErrnoException)?.code;+ if (attempt >= 3 || !code || !TRANSIENT_RENAME_CODES.has(code)) throw error;+ sleepSync(20 * (attempt + 1));+ }+ }+}++/**+ * 尽力删除,绝不外抛。清理残留文件失败(AV 占用)不能掩盖一次**已经成功**的+ * 写入,也不能中断一次尚可继续的写入;残留由下次写入清掉。maxRetries 交给+ * libuv 处理 Windows 的 EBUSY/EPERM/ENOTEMPTY。+ */+function rmSyncQuiet(target: string): void {+ try {+ fs.rmSync(target, { force: true, maxRetries: 3, retryDelay: 20 });+ } catch {+ // 忽略:best-effort 清理。+ }+}++/**+ * 主文件缺失但 `.bak` 仍在、且无法恢复回来。+ *+ * 这种状态下磁盘上唯一的有效快照是那个 `.bak`,任何"按空数据继续"的行为都会把它+ * 永久丢掉(读成空 → 用空数据写入 → 主文件出现 → 下次写入把 .bak 当陈旧残留删掉)。+ * 因此读写两侧都必须 fail loud,把决定权交给上层而不是静默降级。+ */+export class AtomicBackupUnrecoverableError extends Error {+ readonly code = 'ATOMIC_BACKUP_UNRECOVERABLE' as const;++ constructor(readonly filePath: string, cause?: unknown) {+ super(`Cannot restore ${filePath} from its .bak backup`);+ this.name = 'AtomicBackupUnrecoverableError';+ if (cause !== undefined) this.cause = cause;+ }+}++/** 是否为"备份无法恢复"错误(调用方据此避免降级成空数据)。 */+export function isAtomicBackupUnrecoverable(error: unknown): boolean {+ return error instanceof AtomicBackupUnrecoverableError;+}++/**+ * 主文件缺失且 `.bak` 在场时把备份恢复回主文件。+ *+ * 这是 Windows 备份交换失败后唯一的有效快照。恢复动作必须同时出现在读与写两侧:+ * 只放在写侧时,调用方会先把缺失的主文件读成空数据,再拿这份空数据发起写入 ——+ * 写入前恢复的备份随即被空快照覆盖,数据仍然永久丢失。+ *+ * 返回值必须区分"发现备份"与"恢复成功":恢复失败(Windows 文件锁/杀毒占用)时+ * 按 `restored` 处理会让读取方读成空、写入方拿空数据覆盖,唯一快照照样丢 ——+ * 所以这里抛 `AtomicBackupUnrecoverableError`,由两侧一致地拒绝继续。+ */+function restoreBackupIfMainMissing(filePath: string): 'restored' | 'not-needed' {+ const backupPath = `${filePath}.bak`;+ if (fs.existsSync(filePath) || !fs.existsSync(backupPath)) return 'not-needed';+ try {+ renameSyncWithRetry(backupPath, filePath);+ } catch (error) {+ throw new AtomicBackupUnrecoverableError(filePath, error);+ }+ return 'restored';+}++/**+ * 读取由 `atomicWriteFileSync` 维护的文件:主文件缺失时先从 `.bak` 恢复再读。+ * 文件确实不存在(`ENOENT`)返回 null,由调用方决定空值语义。+ *+ * **只有 ENOENT 才算"不存在"**,其余读取错误一律上抛:文件明明在,只是被+ * Windows 文件锁、权限或瞬时 I/O 挡住时若返回 null,调用方会解释成空状态,+ * 随后那次写入就用空状态派生的快照覆盖原文件,其余来源/安装记录永久丢失。+ *+ * `.bak` 在场但恢复不了时抛 `AtomicBackupUnrecoverableError` —— **不要**把它+ * 降级成 null:那等于把"有一份救得回来的数据"说成"没有数据",后续写入会清掉它。+ */+export function readAtomicFileSync(filePath: string): string | null {+ restoreBackupIfMainMissing(filePath);+ try {+ return fs.readFileSync(filePath, 'utf8');+ } catch (error) {+ if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') return null;+ throw error;+ }+}++/**+ * 可回滚的原子文件替换(main 进程本地 JSON 状态文件共用)。+ *+ * 常规路径是 temp 写入 + rename 原子替换。Windows 上 rename 无法覆盖已存在+ * 目标(EPERM/EEXIST),需要兜底;兜底若直接删目标再 rename,第二次 rename+ * 再失败(文件锁/杀毒/瞬时 I/O)会把旧文件与唯一临时副本都删掉,导致配置+ * 全丢。这里兜底改为备份交换:先把旧文件改名 .bak、再让 temp 落位、成功后+ * 删 .bak;任一步失败都从 .bak 恢复,.bak 残留由下次写入时清理。+ *+ * `.bak` 在场但恢复不了时**直接抛错、不写入**(`AtomicBackupUnrecoverableError`):+ * 那时它是磁盘上唯一有效的快照,继续写入会让它先被忽略、再在下一次写入时当陈旧+ * 残留删掉。宁可这次写失败让上层看见,也不能把唯一副本换成派生自空数据的内容。+ */+export function atomicWriteFileSync(filePath: string, contents: string): void {+ fs.mkdirSync(path.dirname(filePath), { recursive: true });+ const tempPath = `${filePath}.${crypto.randomUUID()}.tmp`;+ const backupPath = `${filePath}.bak`;+ // 上次 temp 落位与恢复都失败时,主文件缺失、.bak 是唯一有效快照:+ // 先把它恢复回主文件,再写入,避免把缺失主文件读成空后覆盖唯一快照。+ // 主文件存在时,.bak 才是陈旧残留,直接清理。恢复不了则抛错,不写入。+ if (restoreBackupIfMainMissing(filePath) === 'not-needed') {+ rmSyncQuiet(backupPath);+ }+ try {+ fs.writeFileSync(tempPath, contents, { mode: 0o600, flag: 'wx' });+ try {+ // 主路径:rename 覆盖已存在目标(Windows/POSIX 均原子替换),瞬时锁重试。+ renameSyncWithRetry(tempPath, filePath);+ return;+ } catch (error) {+ const code =+ error && typeof error === 'object' && 'code' in error+ ? (error as NodeJS.ErrnoException).code+ : undefined;+ // 只有"无法覆盖已存在目标"(EPERM/EEXIST)才走备份交换;EBUSY/EACCES 已在+ // renameSyncWithRetry 里重试过,到这里仍失败就是真失败,直接上抛。+ if (code !== 'EPERM' && code !== 'EEXIST') {+ throw error;+ }+ // 兜底:备份交换而非直接删目标(两步 rename 都带瞬时锁重试)。+ renameSyncWithRetry(filePath, backupPath);+ try {+ renameSyncWithRetry(tempPath, filePath);+ } catch (swapError) {+ // temp 落位失败:从备份恢复旧文件,避免配置全丢。+ try {+ renameSyncWithRetry(backupPath, filePath);+ } catch {+ // 恢复也失败:.bak 仍在磁盘上,下次写入或启动时可人工/自愈找回。+ }+ throw swapError;+ }+ // 写入已成功;清 .bak 失败(AV 占用)不能反过来把成功报成失败。+ rmSyncQuiet(backupPath);+ }+ } finally {+ rmSyncQuiet(tempPath);+ }+}diff --git a/apps/desktop/src/main/utils/readBoundedFile.ts b/apps/desktop/src/main/utils/readBoundedFile.tsnew file mode 100644index 0000000000..1a844e9301--- /dev/null+++ b/apps/desktop/src/main/utils/readBoundedFile.ts@@ -0,0 +1,212 @@+/**+ * 不可信目录里单个文件的安全读取:以**同一个文件句柄**完成+ * "拒符号链接 → 校验普通文件与大小 → (可选)根内复核 → 限量读取"。+ *+ * 动机(自定义插件市场):ghost.json 等文件位于用户可写的市场目录,"先检查、+ * 再按路径读"是两次独立打开,并发方能在两次之间把它换成超大文件或指向+ * /dev/zero 的符号链接。这里检查与读取都作用于已打开的 inode,路径再被替换+ * 也影响不到。发现、安装、打包(含 zip 逐文件、SKILL.md、locale 校验)所有+ * 触及不可信目录的读取都必须共用本工具,任何一处按路径裸读都会重开缺口。+ *+ * containWithin 堵的是**中间目录**被换成符号链接的窗口:O_NOFOLLOW 只管最后+ * 一个路径分量,realpath 校验后、open 之前,路径上的某个父目录可被换成指向+ * 根外的链接。open 之后复核"路径此刻仍解析到已打开的 inode(stat dev/ino 与+ * 句柄一致)且 realpath 落在根内"——两个条件同时成立时,句柄对应的就是根内+ * 文件;换链接(realpath 出根)与换回去(inode 不再一致)都会被拒。+ */+import fs from 'node:fs';+import path from 'node:path';++/**+ * 身份卡(ghost.json)体量上限。合法身份卡远小于此;超限视为非法内容,+ * 发现层跳过、安装/打包层结构化拒绝。+ */+export const GHOST_MANIFEST_MAX_BYTES = 512 * 1024;++export interface ReadBoundedFileOptions {+ /** 仅供测试注入:传 null 模拟无 O_NOFOLLOW 的平台。 */+ noFollowFlag?: number | null;+ /**+ * 已 realpath 的根目录。传入时在 open 之后复核:路径此刻 stat 的 dev/ino+ * 与句柄一致,且 realpath(filePath) 落在该根内;任一不成立返回 null。+ */+ containWithin?: string;+}++/** realpath 产物是否落在同为 realpath 产物的根内(含根本身)。 */+function isWithinRoot(realFilePath: string, realRoot: string): boolean {+ if (realFilePath === realRoot) return true;+ const rootWithSep = realRoot.endsWith(path.sep) ? realRoot : `${realRoot}${path.sep}`;+ return realFilePath.startsWith(rootWithSep);+}++/**+ * 路径上的目录项与已打开句柄是否同一 inode。**必须用 BigInt**:+ * NTFS 的 FileId 高位在长期使用的卷上会超过 2^53,number 截断可能让两个不同+ * 文件比相等(误放行)。dev/ino 任一为 0 表示文件系统没提供可信标识(SMB /+ * 网络重定向器 / 部分 FUSE 常见)——此时无法证明"路径仍解析到这个 inode",+ * 一律按不可信拒绝,不让回退闸退化成只剩 isSymbolicLink 一条。+ */+function sameInode(a: fs.BigIntStats, b: fs.BigIntStats): boolean {+ if (a.dev === 0n || a.ino === 0n || b.dev === 0n || b.ino === 0n) return false;+ return a.dev === b.dev && a.ino === b.ino;+}++/**+ * 在已打开句柄上循环读满已校验的长度。网络盘/FUSE 上单次 read() 不保证填满+ * 请求区间,单次读会把合法文件截断成解析失败。EOF 早于已校验长度(并发截断)+ * 时按实际读到的字节返回,交由上层解析/校验自然拒绝。+ */+async function readToLength(+ handle: fs.promises.FileHandle,+ size: number,+): Promise<Buffer> {+ const buffer = Buffer.alloc(size);+ let offset = 0;+ while (offset < size) {+ const { bytesRead } = await handle.read(buffer, offset, size - offset, offset);+ if (bytesRead === 0) break;+ offset += bytesRead;+ }+ return buffer.subarray(0, offset);+}++/** open 之后的根内复核(异步侧),失败一律按不可信拒绝。 */+async function verifyStillWithinRoot(+ handleStat: fs.BigIntStats,+ filePath: string,+ realRoot: string,+): Promise<boolean> {+ try {+ const [pathStat, realFilePath] = await Promise.all([+ fs.promises.stat(filePath, { bigint: true }),+ fs.promises.realpath(filePath),+ ]);+ if (!sameInode(pathStat, handleStat)) return false;+ return isWithinRoot(realFilePath, realRoot);+ } catch {+ return false;+ }+}++/**+ * 读取一个"必须是普通文件"的文件,拒绝符号链接,限量读取。+ *+ * - 非普通文件 / 超过 maxBytes / 符号链接或根内复核不过 → 返回 null;+ * - open 失败(含 O_NOFOLLOW 平台对 symlink 的 ELOOP 拒绝、ENOENT)→ 抛出,+ * 由调用方决定语义。+ *+ * Windows 没有 O_NOFOLLOW(open 会跟随链接),回退为:open 之后 lstat 路径,+ * 链接一律拒;再比对 lstat 与句柄 stat 的 dev/ino,确认路径上的目录项就是已+ * 打开的 inode,堵"open 之后换文件"的窗口。语义与 POSIX 侧一致:该文件不允许+ * 是符号链接,无论目标指向哪里。+ */+export async function readBoundedFileNoFollow(+ filePath: string,+ maxBytes: number,+ options?: ReadBoundedFileOptions,+): Promise<Buffer | null> {+ const noFollow =+ options?.noFollowFlag !== undefined+ ? options.noFollowFlag+ : (fs.constants.O_NOFOLLOW ?? null);+ const handle = await fs.promises.open(+ filePath,+ fs.constants.O_RDONLY | (noFollow ?? 0),+ );+ try {+ const stat = await handle.stat({ bigint: true });+ if (!stat.isFile() || Number(stat.size) > maxBytes) return null;+ if (noFollow === null) {+ let linkStat: fs.BigIntStats;+ try {+ linkStat = await fs.promises.lstat(filePath, { bigint: true });+ } catch {+ // 路径条目已消失,无从证明句柄对应目录项 → 按不可信拒绝。+ return null;+ }+ if (linkStat.isSymbolicLink()) return null;+ if (!sameInode(linkStat, stat)) return null;+ }+ if (options?.containWithin !== undefined) {+ if (!(await verifyStillWithinRoot(stat, filePath, options.containWithin))) return null;+ }+ return await readToLength(handle, Number(stat.size));+ } finally {+ await handle.close();+ }+}++/**+ * 跟随符号链接的变体:仅供"路径已经是 realpath 产物、链接目标已被根包含校验+ * 管住"的调用方使用(市场清单 marketplace.json)。类型与大小闸、根内复核、+ * 读满循环与主变体一致。+ */+export async function readBoundedFileFollowLinks(+ filePath: string,+ maxBytes: number,+ options?: Pick<ReadBoundedFileOptions, 'containWithin'>,+): Promise<Buffer | null> {+ const handle = await fs.promises.open(filePath, fs.constants.O_RDONLY);+ try {+ const stat = await handle.stat({ bigint: true });+ if (!stat.isFile() || Number(stat.size) > maxBytes) return null;+ if (options?.containWithin !== undefined) {+ if (!(await verifyStillWithinRoot(stat, filePath, options.containWithin))) return null;+ }+ return await readToLength(handle, Number(stat.size));+ } finally {+ await handle.close();+ }+}++/**+ * 同步变体,语义与 readBoundedFileNoFollow 完全一致(拒链接、限量、根内复核、+ * 读满)。供无法转异步的同步校验链路(目录 locale 校验、已装插件摘要)使用。+ */+export function readBoundedFileNoFollowSync(+ filePath: string,+ maxBytes: number,+ options?: ReadBoundedFileOptions,+): Buffer | null {+ const noFollow =+ options?.noFollowFlag !== undefined+ ? options.noFollowFlag+ : (fs.constants.O_NOFOLLOW ?? null);+ const fd = fs.openSync(filePath, fs.constants.O_RDONLY | (noFollow ?? 0));+ try {+ const stat = fs.fstatSync(fd, { bigint: true });+ if (!stat.isFile() || Number(stat.size) > maxBytes) return null;+ if (noFollow === null) {+ let linkStat: fs.BigIntStats;+ try {+ linkStat = fs.lstatSync(filePath, { bigint: true });+ } catch {+ return null;+ }+ if (linkStat.isSymbolicLink()) return null;+ if (!sameInode(linkStat, stat)) return null;+ }+ if (options?.containWithin !== undefined) {+ try {+ const pathStat = fs.statSync(filePath, { bigint: true });+ const realFilePath = fs.realpathSync(filePath);+ if (!sameInode(pathStat, stat)) return null;+ if (!isWithinRoot(realFilePath, options.containWithin)) return null;+ } catch {+ return null;+ }+ }+ const size = Number(stat.size);+ const buffer = Buffer.alloc(size);+ let offset = 0;+ while (offset < size) {+ const bytesRead = fs.readSync(fd, buffer, offset, size - offset, offset);+ if (bytesRead === 0) break;+ offset += bytesRead;+ }+ return buffer.subarray(0, offset);+ } finally {+ fs.closeSync(fd);+ }+}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex e07c4a760f..523bad7345 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1011,11 +1011,37 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('plugin-market:detail', pluginId),install: (pluginId: string,- options: { expectedReleaseId: string; allowPermissionExpansion?: boolean },+ options: {+ expectedReleaseId: string;+ expectedManifest?: import('../shared/ghost').GhostManifest;+ 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),+ listSources: (): Promise<import('../shared/pluginMarket').MarketSourceSummary[]> =>+ ipcRenderer.invoke('plugin-market:list-sources'),+ pickLocalSource: (+ defaultPath?: string,+ ): Promise<+ | { canceled: true }+ | { canceled: false; summary: import('../shared/pluginMarket').MarketSourceSummary }+ > => ipcRenderer.invoke('plugin-market:pick-local-source', defaultPath),+ addSource: (input: {+ source: string;+ ref?: string;+ sparsePaths?: string[];+ }): Promise<import('../shared/pluginMarket').MarketSourceSummary> =>+ ipcRenderer.invoke('plugin-market:add-source', input),+ removeSource: (name: string): Promise<{ ok: true }> =>+ ipcRenderer.invoke('plugin-market:remove-source', name),+ refreshSource: (+ name: string,+ ): Promise<import('../shared/pluginMarket').MarketSourceSummary> =>+ ipcRenderer.invoke('plugin-market:refresh-source', name),+ gitPreflight: (): Promise<{ ok: boolean; version: string | null }> =>+ ipcRenderer.invoke('plugin-market:git-preflight'),},voiceInput: {prewarm: (payload?: { sourceLanguage?: string; refinementEnabled?: boolean }): Promise<{ ok: true }> =>diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.tsindex 76570075a6..27b7ca3f9f 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostPluginViewModel.test.ts@@ -71,6 +71,8 @@ function marketItem(overrides: Partial<PluginMarketItem> = {}): PluginMarketItemreleaseId: 'release-1',version: '1.5.10',publishedAt: '2026-07-27T00:00:00.000Z',+ sourceType: 'server',+ sourceMarketName: null,icon: {mimeType: 'image/png',sha256: 'a'.repeat(64),diff --git a/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx b/apps/desktop/src/renderer/components/ui/confirm-dialog.tsxindex 6822b1ab73..ba0a7ab482 100644--- a/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx+++ b/apps/desktop/src/renderer/components/ui/confirm-dialog.tsx@@ -49,6 +49,8 @@ export interface ConfirmDialogProps {autoFocusConfirm?: boolean;/** Disable the primary action until caller-owned validation has passed. */confirmDisabled?: boolean;+ /** 嵌套在其它 Dialog 内时提升层级;普通确认继续使用默认层级。 */+ zIndex?: number;/** Destructive actions use the semantic destructive theme tokens. */confirmVariant?: 'default' | 'destructive';/**@@ -85,6 +87,7 @@ export function ConfirmDialog({onConfirm,onCancel,onTertiary,+ zIndex = 10000,}: ConfirmDialogProps) {const { t } = useTranslation();const resolvedConfirmText = confirmText ?? t('commonUi.confirmDialog.confirm');@@ -123,7 +126,7 @@ export function ConfirmDialog({'data-[state=open]:animate-confirm-overlay-in','data-[state=closed]:animate-confirm-overlay-out',)}- style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}+ style={{ WebkitAppRegion: 'no-drag', zIndex } as React.CSSProperties}/><AlertDialog.ContentclassName={cn(@@ -134,7 +137,7 @@ export function ConfirmDialog({'data-[state=open]:animate-confirm-content-in','data-[state=closed]:animate-confirm-content-out',)}- style={{ WebkitAppRegion: 'no-drag', maxWidth: maxWidth ?? 400 } as React.CSSProperties}+ style={{ WebkitAppRegion: 'no-drag', maxWidth: maxWidth ?? 400, zIndex } as React.CSSProperties}{...(!description ? { 'aria-describedby': undefined } : {})}onEscapeKeyDown={(e) => {if (loading) e.preventDefault();diff --git a/apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx b/apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsxnew file mode 100644index 0000000000..2ec4cb1038--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx@@ -0,0 +1,350 @@+/**+ * 添加插件市场对话框:添加表单(来源 / Git 引用 / 稀疏路径)+ 已添加市场的+ * 管理入口(新开 MarketplaceSourcesDialog,避免本对话框被列表撑长)。+ *+ * 视觉规格遵循 DESIGN.md §4 Dialog & Modal:overlay 用 --overlay-modal token,+ * 容器 12px radius + --confirm-bg + --confirm-shadow,表单对话框放宽到 460px;+ * 单行输入 pill、多行输入 8px 内层 radius,按钮全部 pill。+ */+import { useCallback, useEffect, useState } from 'react';+import * as Dialog from '@radix-ui/react-dialog';+import { ChevronRight } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { Spinner } from '@/components/ui/spinner';+import { cn } from '@/lib/utils';+import { useAuth } from '@/contexts/AuthContext';+import { extractIpcError } from '@/utils/ipcError';+import type { MarketSourceSummary } from '../../../shared/pluginMarket';++import { marketplaceSourceErrorKey } from './lib/pluginMarketErrorKey';+import { MarketplaceGuideDialog } from './MarketplaceGuideDialog';+import { MarketplaceSourcesDialog } from './MarketplaceSourcesDialog';++export interface AddMarketplaceDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ /** 来源增删 / 刷新成功后通知父级重拉市场快照。 */+ onSourcesChanged: () => void;+}++/** 与 main 侧 parse.ts 同形状的前置判断:仅用于决定 Git 不可用时要不要禁用添加。 */+function looksLikeLocalPath(input: string): boolean {+ const trimmed = input.trim();+ return (+ trimmed.startsWith('~') ||+ trimmed.startsWith('/') ||+ trimmed.startsWith('\\') ||+ /^[A-Za-z]:[\\/]/.test(trimmed) ||+ trimmed.startsWith('./') ||+ trimmed.startsWith('../') ||+ trimmed.startsWith('.\\') ||+ trimmed.startsWith('..\\')+ );+}++export function AddMarketplaceDialog({+ open,+ onOpenChange,+ onSourcesChanged,+}: AddMarketplaceDialogProps) {+ const { t } = useTranslation();+ // 账号/模式作为来源列表的作用域键:切号必须清掉上一账号的来源摘要。+ const { mode, dataOwnerId } = useAuth();+ const [sources, setSources] = useState<MarketSourceSummary[] | null>(null);+ const [gitReady, setGitReady] = useState<boolean | null>(null);+ const [sourceInput, setSourceInput] = useState('');+ const [refInput, setRefInput] = useState('');+ const [sparseInput, setSparseInput] = useState('');+ const [adding, setAdding] = useState(false);+ const [guideOpen, setGuideOpen] = useState(false);+ const [sourcesOpen, setSourcesOpen] = useState(false);+ // 添加/刷新失败的内联错误:本地化引导 + git 原始详情(与 Codex 同级信息量)。+ const [operationError, setOperationError] = useState<{+ key: string;+ detail: string | null;+ } | null>(null);++ // 只有 git 克隆类错误码的 detail 是消毒后的 stderr 摘录,值得原文展示;+ // 其它错误码的 message 是内部英文文案,展示反而会和本地化引导重复。+ const GIT_DETAIL_CODES = new Set([+ 'MARKET_CLONE_AUTH_FAILED',+ 'MARKET_CLONE_FAILED',+ 'MARKET_REF_NOT_FOUND',+ ]);+ const toOperationError = (error: unknown) => {+ const ipc = extractIpcError(error);+ return {+ key: marketplaceSourceErrorKey(error),+ detail: ipc && GIT_DETAIL_CODES.has(ipc.code) ? ipc.message : null,+ };+ };++ const loadSources = useCallback(async () => {+ try {+ const list = await window.electronAPI.pluginMarket.listSources();+ setSources(list);+ } catch {+ // 会话切换中等场景下读取失败:保持上一次列表,下次打开再试。+ setSources((current) => current ?? []);+ }+ }, []);++ // 来源摘要里有私有仓库 URL 与本地绝对路径,属于上一账号的数据。Main 的返回前+ // generation 校验只能拒掉新请求,撤不回 Renderer 已经缓存并正在展示的列表——+ // 所以账号/模式一变就立刻清空本地状态并关掉来源管理子对话框,再按新账号重载。+ useEffect(() => {+ setSources(null);+ setSourcesOpen(false);+ setOperationError(null);+ if (!open) return;+ void loadSources();+ }, [mode, dataOwnerId, open, loadSources]);++ useEffect(() => {+ if (!open) return;+ setSourceInput('');+ setRefInput('');+ setSparseInput('');+ void window.electronAPI.pluginMarket+ .gitPreflight()+ .then((result) => setGitReady(result.ok))+ .catch(() => setGitReady(null));+ }, [open]);++ const sourceIsLocal = looksLikeLocalPath(sourceInput);+ const addDisabled =+ adding ||+ sourceInput.trim().length === 0 ||+ (gitReady === false && !sourceIsLocal);++ const handleAdd = useCallback(async () => {+ if (addDisabled) return;+ setAdding(true);+ setOperationError(null);+ try {+ // 本地目录的授权必须来自 Main 原生目录选择器(选择即授权):Renderer 直传+ // 绝对路径在 IPC 层会被拒——XSS 控制下的自报路径不构成用户授权。输入的+ // 路径只作为原生框的初始定位提示;用户取消则静默结束。+ if (sourceIsLocal) {+ const picked = await window.electronAPI.pluginMarket.pickLocalSource(sourceInput.trim());+ if (picked.canceled) return;+ } else {+ const sparsePaths = sparseInput+ .split('\n')+ .map((entry) => entry.trim())+ .filter((entry) => entry.length > 0);+ const ref = refInput.trim();+ await window.electronAPI.pluginMarket.addSource({+ source: sourceInput.trim(),+ ...(ref ? { ref } : {}),+ ...(sparsePaths.length > 0 ? { sparsePaths } : {}),+ });+ }+ setSourceInput('');+ setRefInput('');+ setSparseInput('');+ await loadSources();+ onSourcesChanged();+ } catch (error) {+ setOperationError(toOperationError(error));+ } finally {+ setAdding(false);+ }+ }, [+ addDisabled,+ loadSources,+ onSourcesChanged,+ refInput,+ sourceInput,+ sourceIsLocal,+ sparseInput,+ t,+ ]);++ return (+ <Dialog.Root open={open} onOpenChange={(next) => !adding && onOpenChange(next)}>+ <Dialog.Portal>+ <Dialog.Overlay+ className={cn(+ 'fixed inset-0 z-[10000] bg-[var(--overlay-modal)]',+ 'data-[state=open]:animate-confirm-overlay-in',+ 'data-[state=closed]:animate-confirm-overlay-out',+ )}+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}+ />+ <Dialog.Content+ className={cn(+ 'fixed left-1/2 top-1/2 z-[10000] -translate-x-1/2 -translate-y-1/2',+ 'flex max-h-[85vh] w-full select-none flex-col rounded-xl p-4',+ 'bg-[var(--confirm-bg)] shadow-[var(--confirm-shadow)]',+ 'data-[state=open]:animate-confirm-content-in',+ 'data-[state=closed]:animate-confirm-content-out',+ )}+ style={+ {+ WebkitAppRegion: 'no-drag',+ maxWidth: 'min(460px, 100vw - 32px)',+ } as React.CSSProperties+ }+ >+ <Dialog.Title className="shrink-0 text-lg font-medium text-[var(--confirm-title)]">+ {t('settings.ghosts.market.sources.dialogTitle')}+ </Dialog.Title>+ <Dialog.Description className="mt-2 shrink-0 text-12 text-[var(--confirm-desc)]">+ {t('settings.ghosts.market.sources.dialogDescription')}{' '}+ <button+ type="button"+ onClick={() => setGuideOpen(true)}+ className="cursor-pointer bg-transparent p-0 text-12 text-[var(--settings-source-link)] transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ >+ {t('settings.ghosts.market.sources.learnMore')}+ </button>+ </Dialog.Description>++ {/* 负 margin + 内边距补偿:滚动容器不裁掉输入框向外渲染的 focus ring。 */}+ <div className="-mx-1 mt-3 min-h-0 flex-1 overflow-y-auto overscroll-contain px-1">+ {gitReady === false ? (+ <p className="mb-3 rounded-xl border border-[var(--border-default)] bg-[var(--surface-chip)] px-4 py-3 text-12 text-[var(--text-secondary)]">+ {t('settings.ghosts.market.sources.gitUnavailable')}+ </p>+ ) : null}++ <div className="flex flex-col gap-3">+ <label className="flex flex-col gap-1.5">+ <span className="text-12 text-[var(--text-secondary)]">+ {t('settings.ghosts.market.sources.sourceLabel')}+ </span>+ <input+ value={sourceInput}+ onChange={(event) => setSourceInput(event.target.value)}+ placeholder={t('settings.ghosts.market.sources.sourcePlaceholder')}+ spellCheck={false}+ className={cn(+ 'h-10 rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4',+ 'text-13 text-[var(--text-primary)] placeholder:text-[var(--text-placeholder)]',+ 'outline-none transition-colors focus:border-[var(--focus-ring)] focus:ring-1 focus:ring-[var(--focus-ring-soft)]',+ )}+ />+ </label>+ <label className="flex flex-col gap-1.5">+ <span className="text-12 text-[var(--text-secondary)]">+ {t('settings.ghosts.market.sources.refLabel')}+ </span>+ <input+ value={refInput}+ onChange={(event) => setRefInput(event.target.value)}+ placeholder={t('settings.ghosts.market.sources.refPlaceholder')}+ spellCheck={false}+ disabled={sourceIsLocal}+ className={cn(+ 'h-10 rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4',+ 'text-13 text-[var(--text-primary)] placeholder:text-[var(--text-placeholder)]',+ 'outline-none transition-colors focus:border-[var(--focus-ring)] focus:ring-1 focus:ring-[var(--focus-ring-soft)]',+ 'disabled:cursor-not-allowed disabled:opacity-50',+ )}+ />+ </label>+ <label className="flex flex-col gap-1.5">+ <span className="text-12 text-[var(--text-secondary)]">+ {t('settings.ghosts.market.sources.sparseLabel')}+ </span>+ <textarea+ value={sparseInput}+ onChange={(event) => setSparseInput(event.target.value)}+ placeholder={t('settings.ghosts.market.sources.sparsePlaceholder')}+ spellCheck={false}+ rows={2}+ disabled={sourceIsLocal}+ className={cn(+ 'resize-none rounded-lg border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-2.5',+ 'text-13 text-[var(--text-primary)] placeholder:text-[var(--text-placeholder)]',+ 'outline-none transition-colors focus:border-[var(--focus-ring)] focus:ring-1 focus:ring-[var(--focus-ring-soft)]',+ 'disabled:cursor-not-allowed disabled:opacity-50',+ )}+ />+ </label>+ </div>++ {operationError ? (+ <div+ role="alert"+ className="mt-3 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3"+ >+ <p className="text-12 leading-5 text-[hsl(var(--destructive))]">+ {t(operationError.key)}+ </p>+ {operationError.detail ? (+ <pre className="mt-2 max-h-32 overflow-y-auto whitespace-pre-wrap break-all font-mono text-11 leading-4 text-[var(--text-tertiary)]">+ {operationError.detail}+ </pre>+ ) : null}+ </div>+ ) : null}++ {sources && sources.length > 0 ? (+ <button+ type="button"+ onClick={() => setSourcesOpen(true)}+ className={cn(+ 'mt-5 flex w-full items-center justify-between gap-3 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3',+ 'transition-colors hover:bg-[var(--surface-hover-soft)]',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',+ )}+ >+ <span className="text-13 font-medium text-[var(--text-primary)]">+ {t('settings.ghosts.market.sources.listTitle')}+ </span>+ <span className="flex shrink-0 items-center gap-1.5 text-12 tabular-nums text-[var(--text-tertiary)]">+ {sources.length}+ <ChevronRight size={13} aria-hidden="true" />+ </span>+ </button>+ ) : null}+ </div>++ <div className="mt-6 flex shrink-0 justify-end gap-2.5">+ <button+ type="button"+ disabled={adding}+ onClick={() => onOpenChange(false)}+ className={cn(+ 'inline-flex min-w-[96px] items-center justify-center rounded-full border px-6 py-2.5 text-13 font-medium',+ 'border-[var(--confirm-btn-secondary-border)] bg-transparent text-[var(--confirm-btn-secondary-text)]',+ 'transition-colors hover:bg-[var(--confirm-btn-secondary-hover)]',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--confirm-btn-secondary-border)]',+ 'active:scale-[0.98] disabled:opacity-50',+ )}+ >+ {t('settings.ghosts.market.sources.close')}+ </button>+ <button+ type="button"+ disabled={addDisabled}+ onClick={() => void handleAdd()}+ className={cn(+ 'inline-flex min-w-[96px] items-center justify-center rounded-full px-6 py-2.5 text-13 font-medium',+ 'bg-[var(--confirm-btn-primary-bg)] text-[var(--confirm-btn-primary-text)]',+ 'transition-colors hover:bg-[var(--confirm-btn-primary-hover)]',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--confirm-btn-primary-bg)]',+ 'active:scale-[0.98] disabled:cursor-not-allowed disabled:opacity-50 disabled:active:scale-100',+ )}+ >+ {adding ? <Spinner size={14} /> : t('settings.ghosts.market.sources.add')}+ </button>+ </div>+ </Dialog.Content>+ </Dialog.Portal>+ <MarketplaceGuideDialog open={guideOpen} onOpenChange={setGuideOpen} />+ <MarketplaceSourcesDialog+ open={sourcesOpen}+ onOpenChange={setSourcesOpen}+ sources={sources ?? []}+ onChanged={() => {+ void loadSources();+ onSourcesChanged();+ }}+ />+ </Dialog.Root>+ );+}diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsxindex 547bff9511..4eaf0f2642 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx@@ -8,7 +8,7 @@import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';import { useNavigate, useSearchParams } from 'react-router-dom';-import { ChevronDown, ChevronRight, ChevronUp, Plus, Sparkles, Upload } from 'lucide-react';+import { ChevronDown, ChevronRight, ChevronUp, Plus, Sparkles, Store, Upload } from 'lucide-react';import { useTranslation } from 'react-i18next';import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';@@ -75,8 +75,10 @@ import {orderPluginCatalogItems,pluginPresentationOrigin,pluginUpdateForInstalledVersion,+ type PluginCatalogPresentationItem,type PluginPresentationOrigin,} from './lib/pluginMarketPresentation';+import { AddMarketplaceDialog } from './AddMarketplaceDialog';import { pluginMarketErrorKey } from './lib/pluginMarketErrorKey';import { usePluginIconRefresh } from './lib/usePluginIconRefresh';import { usePluginMarketForegroundRefresh } from './lib/usePluginMarketForegroundRefresh';@@ -98,6 +100,7 @@ const PRESENTATION_FILTERS: readonly PluginPresentationFilter[] = ['public','organization','local',+ 'custom',];/**@@ -181,6 +184,7 @@ export function GhostPluginPage() {: {items: [],unavailableReason: error instanceof Error ? error.message : String(error),+ customSourceNames: [],},);// Background icon renewal keeps the current snapshot visible, but must still report@@ -290,6 +294,11 @@ export function GhostPluginPage() {setSearchParams(next, { replace: true });}, [searchParams, setSearchParams]);const marketItems = marketSnapshot?.items ?? [];+ const customSourceNames = useMemo(+ () => marketSnapshot?.customSourceNames ?? [],+ [marketSnapshot?.customSourceNames],+ );+ const [addMarketplaceOpen, setAddMarketplaceOpen] = useState(false);const marketByGhostId = useMemo(() => {const map = new Map<string, PluginMarketItem>();for (const item of marketItems) {@@ -349,13 +358,20 @@ export function GhostPluginPage() {}, [marketItems, query, showEnterprise]);const originFilters = useMemo(() =>- showEnterprise- ? PRESENTATION_FILTERS- : PRESENTATION_FILTERS.filter((filter) => filter !== 'organization'),- [showEnterprise],+ PRESENTATION_FILTERS.filter((filter) => {+ if (filter === 'organization') return showEnterprise;+ // 未添加任何自定义市场时不显示"自定义"tab(与组织 tab 的隐藏模式一致)。+ if (filter === 'custom') return customSourceNames.length > 0;+ return true;+ }),+ [customSourceNames.length, showEnterprise],);const effectiveOriginFilter =- !showEnterprise && originFilter === 'organization' ? 'all' : originFilter;+ !showEnterprise && originFilter === 'organization'+ ? 'all'+ : originFilter === 'custom' && customSourceNames.length === 0+ ? 'all'+ : originFilter;const items = useMemo(() =>effectiveOriginFilter === 'all'@@ -376,11 +392,38 @@ export function GhostPluginPage() {() => orderPluginCatalogItems(marketItems, items, availableMarketItems),[availableMarketItems, items, marketItems],);+ // "自定义" tab 内按来源市场分组(≥2 个源时展示小标题);组顺序沿用市场添加顺序。+ const customGroups = useMemo(() => {+ if (effectiveOriginFilter !== 'custom') return null;+ const groups = new Map<string, typeof catalogItems>();+ for (const catalogItem of catalogItems) {+ const marketName =+ catalogItem.kind === 'market'+ ? catalogItem.item.sourceMarketName+ : (marketByGhostId.get(catalogItem.item.id)?.sourceMarketName ?? null);+ const key = marketName ?? '';+ const list = groups.get(key);+ if (list) {+ list.push(catalogItem);+ } else {+ groups.set(key, [catalogItem]);+ }+ }+ return [...groups.entries()].sort((a, b) => {+ const aIndex = customSourceNames.indexOf(a[0]);+ const bIndex = customSourceNames.indexOf(b[0]);+ return (+ (aIndex === -1 ? Number.MAX_SAFE_INTEGER : aIndex) -+ (bIndex === -1 ? Number.MAX_SAFE_INTEGER : bIndex)+ );+ });+ }, [catalogItems, customSourceNames, effectiveOriginFilter, marketByGhostId]);const originCounts = useMemo(() => {const counts: Record<PluginPresentationOrigin, number> = {public: 0,organization: 0,local: 0,+ custom: 0,};for (const item of searchedInstalledItems) counts[item.origin] += 1;for (const item of searchedAvailableMarketItems) {@@ -480,6 +523,7 @@ export function GhostPluginPage() {if (!approved || !isMarketBusyLeaseActive(marketBusyLease)) return;const result = await window.electronAPI.pluginMarket.install(marketItem.pluginId, {expectedReleaseId: next.releaseId,+ ...(next.sourceType !== 'server' ? { expectedManifest: next.manifest } : {}),allowPermissionExpansion: diff.added.length > 0,});if (!isMarketBusyLeaseActive(marketBusyLease)) return;@@ -783,7 +827,10 @@ export function GhostPluginPage() {}),description: isUpdate? t('settings.ghosts.market.updateConfirmDescription')- : t('settings.ghosts.market.installConfirmDescription'),+ : // 自定义市场未经服务端完整性校验,确认文案必须如实区分。+ marketDetail.sourceType !== 'server'+ ? t('settings.ghosts.market.customInstallConfirmDescription')+ : t('settings.ghosts.market.installConfirmDescription'),// 限高与滚动交给共享 ConfirmDialog(max-h-[85vh] + 内部滚动区 + 打开时// 闪一下滚动条),这里不再自套一层 min(56vh,520px) —— 两层限高会让// "到底了没有"取决于内外层谁先触底(2026-07-27 收口)。@@ -804,6 +851,9 @@ export function GhostPluginPage() {if (!confirmed || !isMarketBusyLeaseActive(marketBusyLease)) return;const result = await window.electronAPI.pluginMarket.install(marketDetail.pluginId, {expectedReleaseId: marketDetail.releaseId,+ ...(marketDetail.sourceType !== 'server'+ ? { expectedManifest: marketDetail.manifest }+ : {}),...(isUpdate && diff!.added.length > 0? { allowPermissionExpansion: true }: {}),@@ -895,6 +945,45 @@ export function GhostPluginPage() {);}+ const renderCatalogItem = (+ catalogItem: PluginCatalogPresentationItem<PresentedGhostPluginItem>,+ ) =>+ catalogItem.kind === 'installed' ? (+ <GhostPluginCard+ key={`installed:${catalogItem.item.id}`}+ item={catalogItem.item}+ sourceLabel={t(`settings.ghosts.page.origin.${catalogItem.item.origin}`)}+ onSelect={() => setSelectedId(catalogItem.item.id)}+ onAction={() =>+ void handleUseGhost(catalogItem.item.id, catalogItem.item.name)+ }+ updateVersion={catalogItem.item.marketUpdate?.version}+ updateBusy={catalogItem.item.marketUpdate !== null && marketBusyId !== null}+ onUpdate={+ catalogItem.item.marketUpdate+ ? () => void handleMarketUpdate(catalogItem.item.id)+ : undefined+ }+ effectiveEnabled={effectiveEnabled(+ catalogItem.item.id,+ catalogItem.item.enabled,+ )}+ toggleDisabled={scopeDir !== null && !catalogItem.item.enabled}+ onToggle={(enabled) =>+ void handleToggle(catalogItem.item.id, enabled, catalogItem.item.name)+ }+ onIconLoadError={handleMarketIconLoadError}+ />+ ) : (+ <MarketPluginCard+ key={`market:${catalogItem.item.pluginId}`}+ item={catalogItem.item}+ busy={marketBusyId !== null}+ onSelect={() => void handleSelectMarket(catalogItem.item.pluginId)}+ onIconLoadError={handleMarketIconLoadError}+ />+ );+return (<PluginManagementLayoutactiveTab="plugins"@@ -906,6 +995,7 @@ export function GhostPluginPage() {<GhostPluginActionsonInstall={() => void handleInstall()}onCreateWithCindy={handleCreateWithCindy}+ onAddMarketplace={() => setAddMarketplaceOpen(true)}/>}>@@ -1036,45 +1126,34 @@ export function GhostPluginPage() {) : null}{catalogItems.length > 0 ? (- <div className={cn('plugin-motion-stagger', PLUGIN_MANAGEMENT_CARD_GRID_CLASS)}>- {catalogItems.map((catalogItem) =>- catalogItem.kind === 'installed' ? (- <GhostPluginCard- key={`installed:${catalogItem.item.id}`}- item={catalogItem.item}- sourceLabel={t(`settings.ghosts.page.origin.${catalogItem.item.origin}`)}- onSelect={() => setSelectedId(catalogItem.item.id)}- onAction={() =>- void handleUseGhost(catalogItem.item.id, catalogItem.item.name)- }- updateVersion={catalogItem.item.marketUpdate?.version}- updateBusy={catalogItem.item.marketUpdate !== null && marketBusyId !== null}- onUpdate={- catalogItem.item.marketUpdate- ? () => void handleMarketUpdate(catalogItem.item.id)- : undefined- }- effectiveEnabled={effectiveEnabled(- catalogItem.item.id,- catalogItem.item.enabled,- )}- toggleDisabled={scopeDir !== null && !catalogItem.item.enabled}- onToggle={(enabled) =>- void handleToggle(catalogItem.item.id, enabled, catalogItem.item.name)- }- onIconLoadError={handleMarketIconLoadError}- />- ) : (- <MarketPluginCard- key={`market:${catalogItem.item.pluginId}`}- item={catalogItem.item}- busy={marketBusyId !== null}- onSelect={() => void handleSelectMarket(catalogItem.item.pluginId)}- onIconLoadError={handleMarketIconLoadError}- />- ),- )}- </div>+ customGroups && customGroups.length > 1 ? (+ <div className="flex flex-col gap-6">+ {customGroups.map(([marketName, groupItems]) => (+ <section key={marketName || 'unknown-source'}>+ <header className="mb-3 flex items-baseline gap-2">+ <h3 className="text-14 font-medium text-[var(--text-primary)]">+ {marketName || t('settings.ghosts.page.origin.custom')}+ </h3>+ <span className="text-12 tabular-nums text-[var(--text-tertiary)]">+ {groupItems.length}+ </span>+ </header>+ <div+ className={cn(+ 'plugin-motion-stagger',+ PLUGIN_MANAGEMENT_CARD_GRID_CLASS,+ )}+ >+ {groupItems.map(renderCatalogItem)}+ </div>+ </section>+ ))}+ </div>+ ) : (+ <div className={cn('plugin-motion-stagger', PLUGIN_MANAGEMENT_CARD_GRID_CLASS)}>+ {catalogItems.map(renderCatalogItem)}+ </div>+ )) : !legacyRecoveryStatus ? (<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)]">@@ -1092,6 +1171,11 @@ export function GhostPluginPage() {</section></PluginManagementPage></main>+ <AddMarketplaceDialog+ open={addMarketplaceOpen}+ onOpenChange={setAddMarketplaceOpen}+ onSourcesChanged={() => void refreshMarket()}+ /></PluginManagementLayout>);}@@ -1239,9 +1323,11 @@ export function MarketPluginCard({function GhostPluginActions({onInstall,onCreateWithCindy,+ onAddMarketplace,}: {onInstall: () => void;onCreateWithCindy: () => void;+ onAddMarketplace: () => void;}) {const { t } = useTranslation();@@ -1302,6 +1388,19 @@ function GhostPluginActions({/>{t('settings.ghosts.install')}</DropdownMenuItem>+ <DropdownMenuSeparator className="mx-2 my-1 h-px bg-[var(--border-default)]" />+ <DropdownMenuItem+ onSelect={onAddMarketplace}+ className="h-10 gap-3 rounded-lg px-3 text-13 focus:bg-[var(--surface-hover-soft)] focus:text-[var(--text-primary)]"+ >+ <Store+ size={16}+ strokeWidth={1.7}+ className="text-[var(--text-secondary)]"+ aria-hidden="true"+ />+ {t('settings.ghosts.market.sources.addMarketplace')}+ </DropdownMenuItem></DropdownMenuContent></DropdownMenu>);diff --git a/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsxindex 0d656ea3cf..c826946fc6 100644--- a/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx@@ -27,6 +27,8 @@ export function MarketPluginDetailView({const { scrolled, onScroll } = usePluginDetailScrolled();const permissions = ghostPermissionItems(detail.manifest);const presentationOrigin = pluginPresentationOrigin(detail);+ // 自定义市场(Git/本地源)的包字节未经服务端校验,安全说明必须如实区分。+ const isCustomSource = detail.sourceType !== 'server';const actionKey =detail.installState === 'update-available'? 'settings.ghosts.market.update'@@ -109,7 +111,11 @@ export function MarketPluginDetailView({aria-hidden="true"/><p className="text-13 leading-5 text-[var(--text-secondary)]">- {t('settings.ghosts.market.securityDescription')}+ {t(+ isCustomSource+ ? 'settings.ghosts.market.customSecurityDescription'+ : 'settings.ghosts.market.securityDescription',+ )}</p></div></section>diff --git a/apps/desktop/src/renderer/features/plugin/MarketplaceGuideDialog.tsx b/apps/desktop/src/renderer/features/plugin/MarketplaceGuideDialog.tsxnew file mode 100644index 0000000000..878b036ebf--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/MarketplaceGuideDialog.tsx@@ -0,0 +1,196 @@+/**+ * 自定义插件市场指南对话框:从「添加插件市场」里的「了解更多」进入。+ *+ * 内容覆盖用户搭建/添加一个市场所需的全部事实:目录结构与清单位置、+ * marketplace.json 格式、来源与稀疏路径用法、私有仓库认证(系统 Git 配置)、+ * 安装规则。文案全部走 i18n;代码块内容(结构树 / JSON 示例)不翻译。+ */+import type { CSSProperties, ReactNode } from 'react';+import * as Dialog from '@radix-ui/react-dialog';+import { Copy, X } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { toast } from '@/lib/toast';+import { cn } from '@/lib/utils';++/**+ * 目录结构示例。路径本身不翻译,箭头后的解释性标签必须跟随界面语言 —— 否则+ * 英/日/韩界面下展示与复制出来的内容里会夹着中文标签。路径列宽固定,标签长度+ * 变化不影响箭头对齐。+ */+function structureExample(label: (key: string) => string): string {+ return `my-marketplace/+├── .agents/plugins/marketplace.json ← ${label('structureLabelManifest')}+└── plugins/+ └── my-plugin/+ ├── ghost.json ← ${label('structureLabelGhostCard')}+ └── main.js ← ${label('structureLabelEntry')}`;+}++const MANIFEST_PATHS_EXAMPLE = `.agents/plugins/marketplace.json+.agents/plugins/api_marketplace.json+.claude-plugin/marketplace.json+.cursor-plugin/marketplace.json`;++const MANIFEST_EXAMPLE = `{+ "name": "my-marketplace",+ "plugins": [+ { "name": "my-plugin", "source": "plugins/my-plugin" }+ ]+}`;++export interface MarketplaceGuideDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+}++function GuideSection({+ title,+ children,+}: {+ title: string;+ children: ReactNode;+}) {+ return (+ <section className="mt-5 first:mt-0">+ <h3 className="text-13 font-medium text-[var(--text-primary)]">{title}</h3>+ <div className="mt-2 text-12 leading-5 text-[var(--text-secondary)]">{children}</div>+ </section>+ );+}++function GuideCode({ children }: { children: string }) {+ return (+ <pre className="mt-2 overflow-x-auto rounded-xl bg-[var(--surface-chip)] px-3.5 py-3 font-mono text-11 leading-4 text-[var(--text-secondary)]">+ {children}+ </pre>+ );+}++export function MarketplaceGuideDialog({ open, onOpenChange }: MarketplaceGuideDialogProps) {+ const { t } = useTranslation();+ const guideKey = (key: string) => t(`settings.ghosts.market.sources.guide.${key}`);+ // 展示与复制共用同一份已本地化的结构树,两处内容必须一致。+ const structure = structureExample(guideKey);++ /** 把整份指南按纯文本组装进剪贴板,结构树与 JSON 示例原样带上。 */+ const copyGuide = async () => {+ const text = [+ guideKey('title'),+ '',+ guideKey('intro'),+ '',+ `## ${guideKey('structureTitle')}`,+ guideKey('structureBody'),+ '',+ structure,+ '',+ guideKey('structureNote'),+ '',+ MANIFEST_PATHS_EXAMPLE,+ '',+ `## ${guideKey('manifestTitle')}`,+ guideKey('manifestBody'),+ '',+ MANIFEST_EXAMPLE,+ '',+ `## ${guideKey('sourceTitle')}`,+ guideKey('sourceBody'),+ '',+ `## ${guideKey('authTitle')}`,+ guideKey('authBody'),+ '',+ `## ${guideKey('rulesTitle')}`,+ guideKey('rulesBody'),+ ].join('\n');+ try {+ await navigator.clipboard.writeText(text);+ toast.success(t('settings.ghosts.market.sources.guide.copied'));+ } catch {+ toast.error(t('settings.ghosts.market.sources.guide.copyFailed'));+ }+ };+ return (+ <Dialog.Root open={open} onOpenChange={onOpenChange}>+ <Dialog.Portal>+ <Dialog.Overlay+ className={cn(+ 'fixed inset-0 z-[10001] bg-[var(--overlay-modal)]',+ 'data-[state=open]:animate-confirm-overlay-in',+ 'data-[state=closed]:animate-confirm-overlay-out',+ )}+ style={{ WebkitAppRegion: 'no-drag' } as CSSProperties}+ />+ <Dialog.Content+ className={cn(+ 'fixed left-1/2 top-1/2 z-[10001] -translate-x-1/2 -translate-y-1/2',+ 'flex max-h-[85vh] w-full select-none flex-col rounded-xl p-4',+ 'bg-[var(--confirm-bg)] shadow-[var(--confirm-shadow)]',+ 'data-[state=open]:animate-confirm-content-in',+ 'data-[state=closed]:animate-confirm-content-out',+ )}+ style={+ {+ WebkitAppRegion: 'no-drag',+ maxWidth: 'min(560px, 100vw - 32px)',+ } as CSSProperties+ }+ >+ <div className="flex shrink-0 items-start justify-between gap-3">+ <Dialog.Title className="text-lg font-medium text-[var(--confirm-title)]">+ {t('settings.ghosts.market.sources.guide.title')}+ </Dialog.Title>+ <div className="flex shrink-0 items-center gap-1">+ <button+ type="button"+ onClick={() => void copyGuide()}+ aria-label={t('settings.ghosts.market.sources.guide.copy')}+ className="inline-flex size-7 items-center justify-center rounded-full text-[var(--text-tertiary)] transition-colors 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)]"+ >+ <Copy size={14} aria-hidden="true" />+ </button>+ <Dialog.Close asChild>+ <button+ type="button"+ aria-label={t('settings.ghosts.market.sources.close')}+ className="inline-flex size-7 items-center justify-center rounded-full text-[var(--text-tertiary)] transition-colors hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ >+ <X size={15} aria-hidden="true" />+ </button>+ </Dialog.Close>+ </div>+ </div>+ <Dialog.Description className="mt-2 shrink-0 text-13 text-[var(--confirm-desc)]">+ {t('settings.ghosts.market.sources.guide.intro')}+ </Dialog.Description>++ <div className="mt-4 min-h-0 flex-1 overflow-y-auto overscroll-contain pr-1">+ <GuideSection title={t('settings.ghosts.market.sources.guide.structureTitle')}>+ <p>{t('settings.ghosts.market.sources.guide.structureBody')}</p>+ <GuideCode>{structure}</GuideCode>+ <p className="mt-2">{t('settings.ghosts.market.sources.guide.structureNote')}</p>+ <GuideCode>{MANIFEST_PATHS_EXAMPLE}</GuideCode>+ </GuideSection>++ <GuideSection title={t('settings.ghosts.market.sources.guide.manifestTitle')}>+ <p>{t('settings.ghosts.market.sources.guide.manifestBody')}</p>+ <GuideCode>{MANIFEST_EXAMPLE}</GuideCode>+ </GuideSection>++ <GuideSection title={t('settings.ghosts.market.sources.guide.sourceTitle')}>+ <p>{t('settings.ghosts.market.sources.guide.sourceBody')}</p>+ </GuideSection>++ <GuideSection title={t('settings.ghosts.market.sources.guide.authTitle')}>+ <p>{t('settings.ghosts.market.sources.guide.authBody')}</p>+ </GuideSection>++ <GuideSection title={t('settings.ghosts.market.sources.guide.rulesTitle')}>+ <p>{t('settings.ghosts.market.sources.guide.rulesBody')}</p>+ </GuideSection>+ </div>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>+ );+}diff --git a/apps/desktop/src/renderer/features/plugin/MarketplaceSourcesDialog.tsx b/apps/desktop/src/renderer/features/plugin/MarketplaceSourcesDialog.tsxnew file mode 100644index 0000000000..a41011af81--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/MarketplaceSourcesDialog.tsx@@ -0,0 +1,276 @@+/**+ * 已添加市场管理对话框:从「添加插件市场」里的入口按钮进入。+ *+ * 承载源列表(市场名 / 来源摘要 / 插件计数 / 上次同步时间)与单个源的+ * 刷新、移除操作。刷新与移除失败时在列表上方内联展示本地化引导 ++ * (git 类错误的)消毒后原始输出。+ */+import { useCallback, useEffect, useState, type CSSProperties } from 'react';+import * as Dialog from '@radix-ui/react-dialog';+import { RefreshCw, Trash2, X } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { ConfirmDialog } from '@/components/ui/confirm-dialog';+import { Spinner } from '@/components/ui/spinner';+import { cn } from '@/lib/utils';+import { extractIpcError } from '@/utils/ipcError';+import type { MarketSourceSummary } from '../../../shared/pluginMarket';++import { marketplaceSourceErrorKey } from './lib/pluginMarketErrorKey';++export interface MarketplaceSourcesDialogProps {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ sources: MarketSourceSummary[];+ /** 刷新/移除成功后通知父级重拉源列表与市场快照。 */+ onChanged: () => void;+}++function sourceSummary(source: MarketSourceSummary['source']): string {+ if (source.type === 'local') return source.path;+ return source.url.replace(/\.git$/, '').replace(/^https:\/\//, '');+}++// 只有 git 克隆类错误码的 detail 是消毒后的 stderr 摘录,值得原文展示;+// 其它错误码的 message 是内部英文文案,展示反而会和本地化引导重复。+const GIT_DETAIL_CODES = new Set([+ 'MARKET_CLONE_AUTH_FAILED',+ 'MARKET_CLONE_FAILED',+ 'MARKET_REF_NOT_FOUND',+]);++export function MarketplaceSourcesDialog({+ open,+ onOpenChange,+ sources,+ onChanged,+}: MarketplaceSourcesDialogProps) {+ const { t, i18n } = useTranslation();+ const [busySource, setBusySource] = useState<string | null>(null);+ const [pendingRemove, setPendingRemove] = useState<MarketSourceSummary | null>(null);+ const [operationError, setOperationError] = useState<{+ key: string;+ detail: string | null;+ } | null>(null);++ const toOperationError = (error: unknown) => {+ const ipc = extractIpcError(error);+ return {+ key: marketplaceSourceErrorKey(error),+ detail: ipc && GIT_DETAIL_CODES.has(ipc.code) ? ipc.message : null,+ };+ };++ // 移除确认框由 `pendingRemove` 独立驱动:父对话框被关掉(含切号时父级清空状态并+ // 关闭)时它不会自动消失,用户随后确认会对**当前账号**执行 removeSource ——+ // 若新账号恰有同名来源,就会在还显示旧账号来源名的确认框里误删新账号的配置。+ // 所以父级一关就立刻清空待移除项,并让确认框的打开状态受父级 open 约束。+ useEffect(() => {+ if (open) return;+ setPendingRemove(null);+ setBusySource(null);+ setOperationError(null);+ }, [open]);++ const handleRefresh = useCallback(+ async (name: string) => {+ setBusySource(name);+ setOperationError(null);+ try {+ await window.electronAPI.pluginMarket.refreshSource(name);+ onChanged();+ } catch (error) {+ setOperationError(toOperationError(error));+ } finally {+ setBusySource(null);+ }+ },+ [onChanged],+ );++ const executeRemove = useCallback(+ async (source: MarketSourceSummary) => {+ setBusySource(source.name);+ setOperationError(null);+ try {+ await window.electronAPI.pluginMarket.removeSource(source.name);+ onChanged();+ } catch (error) {+ setOperationError(toOperationError(error));+ } finally {+ setBusySource(null);+ }+ },+ [onChanged],+ );++ const handleRemove = useCallback((source: MarketSourceSummary) => {+ setPendingRemove(source);+ }, []);++ const formatSyncedAt = (iso: string | null): string => {+ if (!iso) return t('settings.ghosts.market.sources.neverSynced');+ const date = new Date(iso);+ if (Number.isNaN(date.getTime())) return iso;+ return new Intl.DateTimeFormat(i18n.resolvedLanguage ?? i18n.language, {+ dateStyle: 'medium',+ timeStyle: 'short',+ }).format(date);+ };++ return (+ <Dialog.Root open={open} onOpenChange={onOpenChange}>+ <Dialog.Portal>+ <Dialog.Overlay+ className={cn(+ 'fixed inset-0 z-[10001] bg-[var(--overlay-modal)]',+ 'data-[state=open]:animate-confirm-overlay-in',+ 'data-[state=closed]:animate-confirm-overlay-out',+ )}+ style={{ WebkitAppRegion: 'no-drag' } as CSSProperties}+ />+ <Dialog.Content+ className={cn(+ 'fixed left-1/2 top-1/2 z-[10001] -translate-x-1/2 -translate-y-1/2',+ 'flex max-h-[85vh] w-full select-none flex-col rounded-xl p-4',+ 'bg-[var(--confirm-bg)] shadow-[var(--confirm-shadow)]',+ 'data-[state=open]:animate-confirm-content-in',+ 'data-[state=closed]:animate-confirm-content-out',+ )}+ style={+ {+ WebkitAppRegion: 'no-drag',+ maxWidth: 'min(460px, 100vw - 32px)',+ } as CSSProperties+ }+ >+ <div className="flex shrink-0 items-start justify-between gap-3">+ <Dialog.Title className="text-lg font-medium text-[var(--confirm-title)]">+ {t('settings.ghosts.market.sources.listTitle')}+ </Dialog.Title>+ <Dialog.Close asChild>+ <button+ type="button"+ aria-label={t('settings.ghosts.market.sources.close')}+ className="inline-flex size-7 shrink-0 items-center justify-center rounded-full text-[var(--text-tertiary)] transition-colors hover:bg-[var(--surface-hover-soft)] hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"+ >+ <X size={15} aria-hidden="true" />+ </button>+ </Dialog.Close>+ </div>++ <div className="mt-3 min-h-0 flex-1 overflow-y-auto overscroll-contain">+ {operationError ? (+ <div+ role="alert"+ className="mb-3 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3"+ >+ <p className="text-12 leading-5 text-[hsl(var(--destructive))]">+ {t(operationError.key)}+ </p>+ {operationError.detail ? (+ <pre className="mt-2 max-h-32 overflow-y-auto whitespace-pre-wrap break-all font-mono text-11 leading-4 text-[var(--text-tertiary)]">+ {operationError.detail}+ </pre>+ ) : null}+ </div>+ ) : null}++ <div className="flex flex-col gap-2">+ {sources.map((source) => (+ <div+ key={source.name}+ className="rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] px-4 py-3"+ >+ <div className="flex items-center justify-between gap-3">+ <span className="min-w-0 truncate text-13 font-medium text-[var(--text-primary)]">+ {source.name}+ </span>+ <span className="shrink-0 text-12 tabular-nums text-[var(--text-tertiary)]">+ {source.status === 'ok'+ ? t('settings.ghosts.market.sources.pluginCount', {+ count: source.pluginCount,+ })+ : t('settings.ghosts.market.sources.sourceError')}+ </span>+ </div>+ <div className="mt-1 flex min-w-0 items-center gap-1.5 text-11 text-[var(--text-tertiary)]">+ <span className="shrink-0">+ {source.source.type === 'local'+ ? t('settings.ghosts.market.sources.localBadge')+ : (source.source.ref ??+ t('settings.ghosts.market.sources.defaultRef'))}+ </span>+ <span aria-hidden="true">·</span>+ <span className="min-w-0 truncate">{sourceSummary(source.source)}</span>+ <span aria-hidden="true">·</span>+ <span className="shrink-0">{formatSyncedAt(source.lastSyncedAt)}</span>+ </div>+ <div className="mt-2.5 flex items-center justify-end gap-2">+ <button+ type="button"+ disabled={busySource !== null}+ onClick={() => void handleRefresh(source.name)}+ className={cn(+ 'inline-flex h-8 items-center gap-1.5 rounded-full border border-[var(--border-default)] px-3 text-12 font-medium text-[var(--text-primary)]',+ 'transition-colors hover:bg-[var(--surface-hover-soft)]',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',+ 'disabled:cursor-not-allowed disabled:opacity-40',+ )}+ >+ {busySource === source.name ? (+ <Spinner size={12} />+ ) : (+ <RefreshCw size={12} aria-hidden="true" />+ )}+ {t('settings.ghosts.market.sources.refresh')}+ </button>+ <button+ type="button"+ disabled={busySource !== null}+ onClick={() => void handleRemove(source)}+ className={cn(+ 'inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-12 font-medium',+ 'bg-[color-mix(in_srgb,hsl(var(--destructive))_15%,transparent)] text-[hsl(var(--destructive))]',+ 'transition-colors hover:bg-[color-mix(in_srgb,hsl(var(--destructive))_25%,transparent)]',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[hsl(var(--destructive))]',+ 'disabled:cursor-not-allowed disabled:opacity-40',+ )}+ >+ <Trash2 size={12} aria-hidden="true" />+ {t('settings.ghosts.market.sources.remove')}+ </button>+ </div>+ </div>+ ))}+ </div>+ </div>+ </Dialog.Content>+ </Dialog.Portal>+ {/* 父级关闭即视为确认框关闭:切号时父级会先关掉,不能让它独立存活。 */}+ <ConfirmDialog+ open={open && pendingRemove !== null}+ onOpenChange={(nextOpen) => {+ if (!nextOpen) setPendingRemove(null);+ }}+ zIndex={10002}+ title={+ pendingRemove+ ? t('settings.ghosts.market.sources.removeConfirmTitle', {+ name: pendingRemove.name,+ })+ : ''+ }+ description={t('settings.ghosts.market.sources.removeConfirmDescription')}+ confirmText={t('settings.ghosts.market.sources.remove')}+ confirmVariant="destructive"+ onConfirm={() => {+ if (!pendingRemove) return;+ const source = pendingRemove;+ setPendingRemove(null);+ void executeRemove(source);+ }}+ />+ </Dialog.Root>+ );+}diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/AddMarketplaceDialog.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/AddMarketplaceDialog.test.tsxnew file mode 100644index 0000000000..be8432f672--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/__tests__/AddMarketplaceDialog.test.tsx@@ -0,0 +1,136 @@+/**+ * 添加市场对话框:切到本地来源后不得再提交 Git 专属字段。+ * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md+ * @vitest-environment jsdom+ */++import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+ // AuthContext 链路会引入 i18n 初始化,mock 必须补齐这些导出。+ initReactI18next: { type: '3rdParty', init: vi.fn() },+ I18nextProvider: ({ children }: { children: React.ReactNode }) => children,+}));+vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));++const auth = { mode: 'cloud' as string, dataOwnerId: 'user-1' as string | null };+vi.mock('@/contexts/AuthContext', () => ({+ useAuth: () => auth,+}));++import { AddMarketplaceDialog } from '../AddMarketplaceDialog';++const addSource = vi.fn(async () => ({}) as never);+const pickLocalSource = vi.fn(async () => ({ canceled: false, summary: {} }) as never);++beforeEach(() => {+ addSource.mockClear();+ vi.stubGlobal('window', window);+ pickLocalSource.mockClear();+ (window as unknown as { electronAPI: unknown }).electronAPI = {+ pluginMarket: {+ addSource,+ pickLocalSource,+ listSources: vi.fn(async () => []),+ removeSource: vi.fn(async () => ({ ok: true })),+ refreshSource: vi.fn(),+ gitPreflight: vi.fn(async () => ({ ok: true, version: '2.43.0' })),+ },+ };+});++/** 按 placeholder key 定位输入框(i18n 被 mock 成回显 key)。 */+function input(key: string): HTMLElement {+ return screen.getByPlaceholderText(key);+}++describe('AddMarketplaceDialog', () => {+ it('drops ref and sparse paths once the source turns out to be a local path', async () => {+ render(<AddMarketplaceDialog open onOpenChange={() => {}} onSourcesChanged={() => {}} />);++ // 先按 Git 源填 ref 与稀疏路径。+ fireEvent.change(input('settings.ghosts.market.sources.sourcePlaceholder'), {+ target: { value: 'openai/plugins' },+ });+ fireEvent.change(input('settings.ghosts.market.sources.refPlaceholder'), {+ target: { value: 'release' },+ });+ fireEvent.change(input('settings.ghosts.market.sources.sparsePlaceholder'), {+ target: { value: 'plugins/a\nplugins/b' },+ });++ // 再把来源改成本地目录:两个输入框变为禁用,用户无法自己清空它们。+ fireEvent.change(input('settings.ghosts.market.sources.sourcePlaceholder'), {+ target: { value: '~/team/plugins' },+ });+ expect(+ (input('settings.ghosts.market.sources.refPlaceholder') as HTMLInputElement).disabled,+ ).toBe(true);++ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.market.sources.add' }));+ // 本地目录必须走 Main 原生选择器(选择即授权),输入的路径只是初始定位提示;+ // Renderer 直传本地路径的 addSource 会在 IPC 层被拒。+ await waitFor(() => expect(pickLocalSource).toHaveBeenCalledWith('~/team/plugins'));+ expect(addSource).not.toHaveBeenCalled();+ });++ it('drops the loaded source summaries when the account switches', async () => {+ const listSources = vi+ .fn(async () => [+ {+ name: 'team-lib',+ addedAt: '2026-07-30T00:00:00.000Z',+ lastSyncedAt: null,+ lastRevision: null,+ source: { type: 'git' as const, url: 'https://git.acme.test/private/repo.git', sparsePaths: [] },+ pluginCount: 1,+ status: 'ok' as const,+ errorCode: null,+ },+ ])+ .mockName('listSources');+ (window as unknown as { electronAPI: { pluginMarket: Record<string, unknown> } }).electronAPI+ .pluginMarket.listSources = listSources;++ const view = render(+ <AddMarketplaceDialog open onOpenChange={() => {}} onSourcesChanged={() => {}} />,+ );+ await waitFor(() => expect(listSources).toHaveBeenCalledTimes(1));++ // 切号:来源摘要里有私有仓库 URL 与本地绝对路径,属于上一账号的数据。+ // Main 的 generation 校验只能拒掉新请求,撤不回 Renderer 已缓存的列表,+ // 所以必须由 Renderer 自己按账号作用域清空并重载。+ auth.mode = 'local';+ auth.dataOwnerId = 'local';+ view.rerender(+ <AddMarketplaceDialog open onOpenChange={() => {}} onSourcesChanged={() => {}} />,+ );+ await waitFor(() => expect(listSources).toHaveBeenCalledTimes(2));++ auth.mode = 'cloud';+ auth.dataOwnerId = 'user-1';+ });++ it('still forwards ref and sparse paths for git sources', async () => {+ render(<AddMarketplaceDialog open onOpenChange={() => {}} onSourcesChanged={() => {}} />);+ fireEvent.change(input('settings.ghosts.market.sources.sourcePlaceholder'), {+ target: { value: 'openai/plugins' },+ });+ fireEvent.change(input('settings.ghosts.market.sources.refPlaceholder'), {+ target: { value: 'release' },+ });+ fireEvent.change(input('settings.ghosts.market.sources.sparsePlaceholder'), {+ target: { value: 'plugins/a' },+ });++ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.market.sources.add' }));+ await waitFor(() => expect(addSource).toHaveBeenCalled());+ expect(addSource).toHaveBeenCalledWith({+ source: 'openai/plugins',+ ref: 'release',+ sparsePaths: ['plugins/a'],+ });+ });+});diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsxindex a5528cb774..e4bac6e86a 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx@@ -54,6 +54,8 @@ const marketPlugin: PluginMarketItem = {icon: null,installState: 'not-installed',enabled: null,+ sourceType: 'server',+ sourceMarketName: null,};function InstalledQueueHarness({ items }: { items: readonly GhostPluginListItem[] }) {diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/MarketplaceGuideDialog.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/MarketplaceGuideDialog.test.tsxnew file mode 100644index 0000000000..234867fd2c--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/__tests__/MarketplaceGuideDialog.test.tsx@@ -0,0 +1,65 @@+/**+ * 自定义市场指南对话框:结构树里的解释性标签必须跟随界面语言,且展示与复制内容一致。+ * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md+ * @vitest-environment jsdom+ */++import { render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++// 用真实的 en 资源渲染:硬编码中文标签会直接暴露在断言里。+const enGuide: Record<string, string> = {+ structureLabelManifest: 'manifest',+ structureLabelGhostCard: 'Plugin card',+ structureLabelEntry: 'Plugin entry',+};++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) => {+ const suffix = key.replace('settings.ghosts.market.sources.guide.', '');+ return enGuide[suffix] ?? suffix;+ },+ }),+}));++const copied: string[] = [];+vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));++import { MarketplaceGuideDialog } from '../MarketplaceGuideDialog';++describe('MarketplaceGuideDialog', () => {+ it('localizes the structure annotations instead of hardcoding Chinese', () => {+ render(<MarketplaceGuideDialog open onOpenChange={() => {}} />);+ const tree = screen.getByText(/my-marketplace\//);+ const text = tree.textContent ?? '';++ // 路径本身不翻译。+ expect(text).toContain('.agents/plugins/marketplace.json');+ expect(text).toContain('ghost.json');+ // 箭头后的标签必须来自 locale 资源。+ expect(text).toContain('manifest');+ expect(text).toContain('Plugin card');+ expect(text).toContain('Plugin entry');+ // 英文界面下不得残留中文标签。+ expect(text).not.toMatch(/[一-鿿]/);+ });++ it('copies the same localized tree that is displayed', async () => {+ const writeText = vi.fn(async (value: string) => {+ copied.push(value);+ });+ vi.stubGlobal('navigator', { clipboard: { writeText } });++ render(<MarketplaceGuideDialog open onOpenChange={() => {}} />);+ const displayed = screen.getByText(/my-marketplace\//).textContent ?? '';+ screen.getByRole('button', { name: 'copy' }).click();+ await vi.waitFor(() => expect(writeText).toHaveBeenCalled());++ const payload = copied.at(-1) ?? '';+ // 复制出来的内容与界面上看到的是同一份(不能一处本地化、一处仍是中文)。+ expect(payload).toContain(displayed.trim());+ expect(payload).not.toMatch(/[一-鿿]/);+ vi.unstubAllGlobals();+ });+});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.tsindex 5461987c1a..9482c62fb4 100644--- a/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/pluginMarketPresentation.test.ts@@ -26,20 +26,33 @@ function marketItem(icon: null,installState,enabled: installState === 'not-installed' ? null : true,+ sourceType: 'server',+ sourceMarketName: null,};}describe('pluginPresentationOrigin', () => {it('maps public plugins independently of their default-install policy', () => {- expect(pluginPresentationOrigin({ scope: 'public' })).toBe('public');+ expect(pluginPresentationOrigin({ scope: 'public', sourceType: 'server' })).toBe('public');});it('maps organization plugins to their organization source', () => {- expect(pluginPresentationOrigin({ scope: 'organization' })).toBe('organization');+ expect(+ pluginPresentationOrigin({ scope: 'organization', sourceType: 'server' }),+ ).toBe('organization');});it('keeps personal plugins out of the client-facing market taxonomy', () => {- expect(pluginPresentationOrigin({ scope: 'personal' })).toBe('local');+ expect(pluginPresentationOrigin({ scope: 'personal', sourceType: 'server' })).toBe('local');+ });++ it('maps custom market sources to the custom origin regardless of scope', () => {+ expect(pluginPresentationOrigin({ scope: 'public', sourceType: 'git-market' })).toBe(+ 'custom',+ );+ expect(pluginPresentationOrigin({ scope: 'public', sourceType: 'local-market' })).toBe(+ 'custom',+ );});it.each([null, undefined])('keeps unmatched installed plugins local', (item) => {diff --git a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketErrorKey.ts b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketErrorKey.tsindex fe116f727d..8f93c891ee 100644--- a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketErrorKey.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketErrorKey.ts@@ -21,3 +21,31 @@ export function pluginMarketErrorKey(error: unknown): string {return 'settings.ghosts.market.errors.generic';}}++/** 自定义市场源管理(添加 / 刷新 / 移除)的 IPC 错误码 → 本地化文案 key。 */+export function marketplaceSourceErrorKey(error: unknown): string {+ switch (extractIpcError(error)?.code) {+ case 'MARKET_SOURCE_INVALID':+ // addSource 把 parse 的子码放进 detail 透传;内嵌凭证有独立引导文案。+ if (extractIpcError(error)?.message === 'CREDENTIALS_NOT_ALLOWED') {+ return 'settings.ghosts.market.sources.errors.credentialsNotAllowed';+ }+ return 'settings.ghosts.market.sources.errors.invalidSource';+ case 'MARKET_GIT_UNAVAILABLE':+ return 'settings.ghosts.market.sources.errors.gitUnavailable';+ case 'MARKET_CLONE_AUTH_FAILED':+ return 'settings.ghosts.market.sources.errors.cloneAuthFailed';+ case 'MARKET_CLONE_FAILED':+ return 'settings.ghosts.market.sources.errors.cloneFailed';+ case 'MARKET_REF_NOT_FOUND':+ return 'settings.ghosts.market.sources.errors.refNotFound';+ case 'MARKET_MANIFEST_MISSING':+ return 'settings.ghosts.market.sources.errors.manifestMissing';+ case 'ALREADY_EXISTS':+ return 'settings.ghosts.market.sources.errors.duplicate';+ case 'NOT_FOUND':+ return 'settings.ghosts.market.sources.errors.notFound';+ default:+ return pluginMarketErrorKey(error);+ }+}diff --git a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.tsindex 09964e33ad..8870165f4e 100644--- a/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/pluginMarketPresentation.ts@@ -10,14 +10,17 @@ import type { PluginMarketItem } from '../../../../shared/pluginMarket';export type PluginPresentationOrigin =| 'public'| 'organization'- | 'local';+ | 'local'+ | 'custom';export type PluginCatalogPresentationItem<TInstalled> ={ kind: 'installed'; item: TInstalled } | { kind: 'market'; item: PluginMarketItem };export function pluginPresentationOrigin(- item: Pick<PluginMarketItem, 'scope'> | null | undefined,+ item: Pick<PluginMarketItem, 'scope' | 'sourceType'> | null | undefined,): PluginPresentationOrigin {+ // 自定义市场(Git / 本地源)归 'custom',与服务端 scope 正交。+ if (item && item.sourceType !== 'server') return 'custom';if (item?.scope === 'public' || item?.scope === 'organization') {return item.scope;}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 2e00492f01..5662968fc0 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3017,7 +3017,8 @@"origin": {"public": "Public","organization": "Team shared",- "local": "Local"+ "local": "Local",+ "custom": "Custom"},"emptyFiltered": "No matching plugins","useAction": "Use",@@ -3030,7 +3031,8 @@"public": "Public","organization": "Organization","personal": "Personal",- "local": "Local"+ "local": "Local",+ "custom": "Custom"},"install": "Install","details": "Details",@@ -3056,10 +3058,69 @@},"securityTitle": "Install and permissions","securityDescription": "Cindy verifies package size and SHA-256 in the main process, validates the plugin manifest, then installs atomically. First-time installs are enabled automatically and can be disabled anytime on the Plugins page; updates keep the current enabled state.",+ "customSecurityDescription": "This plugin comes from a custom marketplace you added and has not been verified by the Cindy server. Its manifest is validated in the main process before install. First-time installs are enabled automatically and can be disabled anytime on the Plugins page.","noPermissions": "This plugin declares no additional capabilities.","installConfirmTitle": "Install “{{name}}”?","installConfirmDescription": "The package will be verified for integrity and manifest compatibility. The plugin is enabled automatically after install; you can disable it or adjust its setup anytime.",- "updateConfirmDescription": "The package will be verified for integrity and manifest compatibility, then replace the installed version. Its current enabled state stays unchanged."+ "customInstallConfirmDescription": "This plugin comes from a custom marketplace and has not been verified for integrity by the server; its manifest will be validated before install. The plugin is enabled automatically after install; you can disable it or adjust its setup anytime.",+ "updateConfirmDescription": "The package will be verified for integrity and manifest compatibility, then replace the installed version. Its current enabled state stays unchanged.",+ "sources": {+ "addMarketplace": "Add Plugin Marketplace…",+ "dialogTitle": "Add Plugin Marketplace",+ "dialogDescription": "Add a plugin marketplace from a GitHub repository, Git URL, or local folder.",+ "learnMore": "Learn more",+ "sourceLabel": "Source",+ "sourcePlaceholder": "openai/plugins or [email protected]:org/repo.git",+ "refLabel": "Git Ref",+ "refPlaceholder": "Main branch",+ "sparseLabel": "Sparse Paths",+ "sparsePlaceholder": "One path per line, e.g. plugins/codex",+ "gitUnavailable": "Git is not installed or is older than 2.25. Git sources are unavailable; local folder sources still work.",+ "listTitle": "Added Marketplaces",+ "pluginCount": "{{count}} plugins",+ "sourceError": "Unavailable",+ "localBadge": "Local",+ "defaultRef": "Default branch",+ "neverSynced": "Never synced",+ "refresh": "Refresh",+ "remove": "Remove",+ "removeConfirmTitle": "Remove marketplace \"{{name}}\"?",+ "removeConfirmDescription": "Plugins from this marketplace will no longer be listed. Installed plugins are kept.",+ "close": "Close",+ "add": "Add Marketplace",+ "errors": {+ "invalidSource": "Invalid source. Use a GitHub owner/repo, a Git URL, or a local folder path.",+ "gitUnavailable": "Git is not installed or is older than 2.25, so Git sources cannot be added.",+ "cloneAuthFailed": "Cannot access this repository. For private repositories, configure Git authentication on this machine first (credential helper or SSH key).",+ "credentialsNotAllowed": "The source URL cannot contain a username or password. Use system Git authentication instead (credential helper or SSH key).",+ "cloneFailed": "Failed to clone the repository. Check your network or proxy settings and try again.",+ "refNotFound": "The specified Git ref was not found. Check the branch or tag name.",+ "manifestMissing": "No supported marketplace.json manifest was found in this source.",+ "duplicate": "This marketplace has already been added.",+ "notFound": "This marketplace does not exist or has been removed."+ },+ "guide": {+ "title": "Custom Plugin Marketplace Guide",+ "intro": "A plugin marketplace is a Git repository or local folder with a manifest file, used to distribute a set of Cindy plugins.",+ "structureTitle": "Directory Structure",+ "structureBody": "A marketplace needs one manifest file plus one directory per plugin. Every plugin directory must contain a valid ghost.json (the plugin identity card).",+ "structureLabelManifest": "manifest",+ "structureLabelGhostCard": "Plugin card",+ "structureLabelEntry": "Plugin entry",+ "structureNote": "The manifest can live in one of these locations:",+ "manifestTitle": "Manifest Format",+ "manifestBody": "name is the unique identity of the marketplace (you manage it by this name after adding). Each source in the plugins array points to a plugin directory inside the repository as a relative path; the object form {\"source\": \"local\", \"path\": \"…\"} is also supported.",+ "sourceTitle": "Source Formats",+ "sourceBody": "Accepted sources: GitHub shorthand owner/repo, full Git URLs (https / ssh / git@), and local folder paths (~ supported). Git ref accepts a branch, tag, or commit; leave empty for the default branch. Sparse paths (one per line) check out only the listed subdirectories — useful for large repositories.",+ "authTitle": "Private Repositories",+ "authBody": "Authentication relies entirely on your system Git configuration — Cindy never stores Git credentials. SSH: a working key must be configured on this machine; if the organization enforces SAML SSO, authorize the key for that organization via Configure SSO in your GitHub SSH key settings. HTTPS: use a Personal Access Token stored by the system credential helper.",+ "rulesTitle": "Install Rules",+ "rulesBody": "Plugin ids are globally unique, first come first served — conflicts with installed plugins are called out explicitly. Plugins using officially reserved prefixes like cindy- cannot be installed from custom marketplaces. Before install, every permission the plugin declares is shown for review; confirming completes the install and enables the plugin.",+ "copy": "Copy guide",+ "copied": "Guide copied to clipboard.",+ "copyFailed": "Copy failed. Please try again."+ }+ }},"install": "Install Plugin…","empty": "No plugins installed yet",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex ca540d8116..e81221c9a7 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3016,7 +3016,8 @@"origin": {"public": "公開","organization": "チーム共有",- "local": "ローカル"+ "local": "ローカル",+ "custom": "カスタム"},"emptyFiltered": "一致するプラグインがありません","useAction": "使用",@@ -3029,7 +3030,8 @@"public": "公開","organization": "組織","personal": "個人",- "local": "ローカル"+ "local": "ローカル",+ "custom": "カスタム"},"install": "インストール","details": "詳細",@@ -3055,10 +3057,69 @@},"securityTitle": "インストールと権限","securityDescription": "メインプロセスでサイズと SHA-256、プラグインマニフェストを検証してからアトミックにインストールします。初回インストール後は自動的に有効になり、プラグインページからいつでも無効化できます。更新では現在の有効/無効の状態が維持されます。",+ "customSecurityDescription": "このプラグインは追加したカスタムマーケット由来で、Cindy サーバーによる整合性検証は行われていません。インストール前にメインプロセスでマニフェストを検証します。初回インストール後は自動で有効になり、プラグインページでいつでも無効化できます。","noPermissions": "このプラグインは追加機能を宣言していません。","installConfirmTitle": "「{{name}}」をインストールしますか?","installConfirmDescription": "パッケージの整合性とマニフェスト互換性を確認してからインストールします。インストール完了後は自動的に有効になり、いつでも無効化や設定の変更ができます。",- "updateConfirmDescription": "パッケージの整合性とマニフェスト互換性を確認してから、既存のバージョンを置き換えます。現在の有効/無効の状態は変わりません。"+ "customInstallConfirmDescription": "カスタムマーケット由来のプラグインのため、サーバーによる整合性検証は行われません。インストール前にマニフェストを検証します。インストール後は自動で有効になり、プラグインページでいつでも無効化・設定変更ができます。",+ "updateConfirmDescription": "パッケージの整合性とマニフェスト互換性を確認してから、既存のバージョンを置き換えます。現在の有効/無効の状態は変わりません。",+ "sources": {+ "addMarketplace": "プラグインマーケットを追加…",+ "dialogTitle": "プラグインマーケットを追加",+ "dialogDescription": "GitHub リポジトリ、Git URL、またはローカルフォルダーからプラグインマーケットを追加します。",+ "learnMore": "詳しく見る",+ "sourceLabel": "ソース",+ "sourcePlaceholder": "openai/plugins または [email protected]:org/repo.git",+ "refLabel": "Git 参照",+ "refPlaceholder": "メインブランチ",+ "sparseLabel": "スパースパス",+ "sparsePlaceholder": "1 行に 1 パス(例: plugins/codex)",+ "gitUnavailable": "Git がインストールされていないか、バージョンが 2.25 未満です。Git ソースは利用できません。ローカルフォルダーのソースは引き続き利用できます。",+ "listTitle": "追加済みのマーケット",+ "pluginCount": "{{count}} 個のプラグイン",+ "sourceError": "読み込み失敗",+ "localBadge": "ローカル",+ "defaultRef": "デフォルトブランチ",+ "neverSynced": "未同期",+ "refresh": "更新",+ "remove": "削除",+ "removeConfirmTitle": "マーケット「{{name}}」を削除しますか?",+ "removeConfirmDescription": "削除すると、このマーケットのプラグインは表示されなくなります。インストール済みのプラグインは保持されます。",+ "close": "閉じる",+ "add": "マーケットを追加",+ "errors": {+ "invalidSource": "ソースの形式が無効です。GitHub の owner/repo、Git URL、またはローカルフォルダーのパスを指定してください。",+ "gitUnavailable": "Git がインストールされていないか、バージョンが 2.25 未満のため、Git ソースを追加できません。",+ "cloneAuthFailed": "このリポジトリにアクセスできません。プライベートリポジトリの場合は、先にシステムで Git 認証(credential helper または SSH key)を設定してください。",+ "credentialsNotAllowed": "ソースの URL にユーザー名やパスワードを含めることはできません。システムの Git 認証(credential helper または SSH key)を使用してください。",+ "cloneFailed": "リポジトリのクローンに失敗しました。ネットワークまたはプロキシ設定を確認してから再試行してください。",+ "refNotFound": "指定された Git 参照が見つかりません。ブランチ名またはタグ名を確認してください。",+ "manifestMissing": "このソースに対応する marketplace.json マニフェストが見つかりません。",+ "duplicate": "このマーケットはすでに追加されています。",+ "notFound": "このマーケットは存在しないか、すでに削除されています。"+ },+ "guide": {+ "title": "カスタムプラグインマーケットガイド",+ "intro": "プラグインマーケットとは、マニフェストファイルを持つ Git リポジトリまたはローカルフォルダーで、Cindy プラグインのセットを配布するためのものです。",+ "structureTitle": "ディレクトリ構造",+ "structureBody": "マーケットには 1 つのマニフェストファイルと、プラグインごとのディレクトリが必要です。各プラグインディレクトリには有効な ghost.json(プラグインの身分証)が必要です。",+ "structureLabelManifest": "マニフェスト",+ "structureLabelGhostCard": "プラグインカード",+ "structureLabelEntry": "プラグインのエントリー",+ "structureNote": "マニフェストは次のいずれかに配置できます:",+ "manifestTitle": "マニフェスト形式",+ "manifestBody": "name はマーケットの一意の識別子です(追加後はこの名前で管理します)。plugins 配列の source はリポジトリ内のプラグインディレクトリを相対パスで指します。{\"source\": \"local\", \"path\": \"…\"} のオブジェクト形式も利用できます。",+ "sourceTitle": "ソース形式",+ "sourceBody": "GitHub 省略形 owner/repo、完全な Git URL(https / ssh / git@)、ローカルフォルダーパス(~ 可)を指定できます。Git 参照にはブランチ、タグ、commit を指定でき、空ならデフォルトブランチです。スパースパスは 1 行に 1 つ指定し、リポジトリの一部のサブディレクトリだけをチェックアウトします(大きなリポジトリ向け)。",+ "authTitle": "プライベートリポジトリ",+ "authBody": "認証はすべてシステムの Git 設定に依存し、Cindy は Git の認証情報を一切保存しません。SSH の場合: 利用可能な key がマシンに設定されている必要があります。組織が SAML SSO を強制している場合は、GitHub の SSH key 設定で Configure SSO からその組織に key を承認してください。HTTPS の場合: Personal Access Token を使用し、システムの credential helper に保存します。",+ "rulesTitle": "インストールルール",+ "rulesBody": "プラグイン id はグローバルに一意で先着順です。インストール済みプラグインとの競合は明示されます。cindy- などの公式予約プレフィックスを使うプラグインはカスタムマーケットからインストールできません。インストール前にプラグインが宣言する権限をすべて表示し、確認するとインストールが完了して自動的に有効になります。",+ "copy": "ガイドをコピー",+ "copied": "ガイドをクリップボードにコピーしました。",+ "copyFailed": "コピーに失敗しました。もう一度お試しください。"+ }+ }},"install": "プラグインをインストール…","empty": "まだプラグインがインストールされていません",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex b4c96c2ea5..f389a0a6c9 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3016,7 +3016,8 @@"origin": {"public": "공개","organization": "팀 공유",- "local": "로컬"+ "local": "로컬",+ "custom": "사용자 지정"},"emptyFiltered": "일치하는 플러그인이 없습니다","useAction": "사용",@@ -3029,7 +3030,8 @@"public": "공개","organization": "조직","personal": "개인",- "local": "로컬"+ "local": "로컬",+ "custom": "사용자 지정"},"install": "설치","details": "상세",@@ -3055,10 +3057,69 @@},"securityTitle": "설치 및 권한","securityDescription": "메인 프로세스에서 크기와 SHA-256 및 플러그인 매니페스트를 검증한 뒤 원자적으로 설치합니다. 최초 설치 후 자동으로 활성화되며 플러그인 페이지에서 언제든지 비활성화할 수 있습니다. 업데이트 시 현재 활성화 상태가 유지됩니다.",+ "customSecurityDescription": "이 플러그인은 추가한 사용자 지정 마켓에서 제공되며 Cindy 서버의 무결성 검증을 거치지 않았습니다. 설치 전에 메인 프로세스에서 매니페스트를 검증합니다. 처음 설치하면 자동으로 활성화되며 플러그인 페이지에서 언제든 비활성화할 수 있습니다.","noPermissions": "이 플러그인은 추가 기능을 선언하지 않았습니다.","installConfirmTitle": "‘{{name}}’을(를) 설치할까요?","installConfirmDescription": "패키지 무결성과 매니페스트 호환성을 확인한 뒤 설치합니다. 설치가 완료되면 자동으로 활성화되며, 언제든지 비활성화하거나 설정을 변경할 수 있습니다.",- "updateConfirmDescription": "패키지 무결성과 매니페스트 호환성을 확인한 뒤 기존 버전을 교체합니다. 현재 활성화 상태는 그대로 유지됩니다."+ "customInstallConfirmDescription": "사용자 지정 마켓의 플러그인으로 서버 무결성 검증을 거치지 않았으며, 설치 전에 매니페스트를 검증합니다. 설치 후 플러그인이 자동으로 활성화되며 언제든 비활성화하거나 설정을 변경할 수 있습니다.",+ "updateConfirmDescription": "패키지 무결성과 매니페스트 호환성을 확인한 뒤 기존 버전을 교체합니다. 현재 활성화 상태는 그대로 유지됩니다.",+ "sources": {+ "addMarketplace": "플러그인 마켓 추가…",+ "dialogTitle": "플러그인 마켓 추가",+ "dialogDescription": "GitHub 리포지토리, Git URL 또는 로컬 폴더에서 플러그인 마켓을 추가합니다.",+ "learnMore": "자세히 알아보기",+ "sourceLabel": "소스",+ "sourcePlaceholder": "openai/plugins 또는 [email protected]:org/repo.git",+ "refLabel": "Git 참조",+ "refPlaceholder": "기본 브랜치",+ "sparseLabel": "스파스 경로",+ "sparsePlaceholder": "한 줄에 하나의 경로(예: plugins/codex)",+ "gitUnavailable": "Git이 설치되어 있지 않거나 버전이 2.25 미만입니다. Git 소스는 사용할 수 없으며 로컬 폴더 소스는 계속 사용할 수 있습니다.",+ "listTitle": "추가된 마켓",+ "pluginCount": "플러그인 {{count}}개",+ "sourceError": "읽기 실패",+ "localBadge": "로컬",+ "defaultRef": "기본 브랜치",+ "neverSynced": "동기화되지 않음",+ "refresh": "새로고침",+ "remove": "제거",+ "removeConfirmTitle": "마켓 \"{{name}}\"을(를) 제거할까요?",+ "removeConfirmDescription": "제거하면 이 마켓의 플러그인이 더 이상 표시되지 않습니다. 설치된 플러그인은 유지됩니다.",+ "close": "닫기",+ "add": "마켓 추가",+ "errors": {+ "invalidSource": "소스 형식이 올바르지 않습니다. GitHub owner/repo, Git URL 또는 로컬 폴더 경로를 사용하세요.",+ "gitUnavailable": "Git이 설치되어 있지 않거나 버전이 2.25 미만이므로 Git 소스를 추가할 수 없습니다.",+ "cloneAuthFailed": "이 리포지토리에 접근할 수 없습니다. 비공개 리포지토리의 경우 먼저 시스템에 Git 인증(credential helper 또는 SSH key)을 구성하세요.",+ "credentialsNotAllowed": "소스 URL에 사용자 이름이나 비밀번호를 포함할 수 없습니다. 시스템 Git 인증(credential helper 또는 SSH key)을 사용하세요.",+ "cloneFailed": "리포지토리를 클론하지 못했습니다. 네트워크 또는 프록시 설정을 확인한 후 다시 시도하세요.",+ "refNotFound": "지정한 Git 참조를 찾을 수 없습니다. 브랜치 또는 태그 이름을 확인하세요.",+ "manifestMissing": "이 소스에서 지원되는 marketplace.json 매니페스트를 찾을 수 없습니다.",+ "duplicate": "이 마켓은 이미 추가되어 있습니다.",+ "notFound": "이 마켓이 존재하지 않거나 이미 제거되었습니다."+ },+ "guide": {+ "title": "사용자 지정 플러그인 마켓 가이드",+ "intro": "플러그인 마켓은 매니페스트 파일을 포함하는 Git 리포지토리 또는 로컬 폴더로, Cindy 플러그인 세트를 배포하는 데 사용됩니다.",+ "structureTitle": "디렉터리 구조",+ "structureBody": "마켓에는 매니페스트 파일 하나와 플러그인별 디렉터리가 필요합니다. 각 플러그인 디렉터리에는 유효한 ghost.json(플러그인 신원 카드)이 있어야 합니다.",+ "structureLabelManifest": "매니페스트",+ "structureLabelGhostCard": "플러그인 카드",+ "structureLabelEntry": "플러그인 진입점",+ "structureNote": "매니페스트는 다음 위치 중 하나에 둘 수 있습니다:",+ "manifestTitle": "매니페스트 형식",+ "manifestBody": "name은 마켓의 고유 식별자입니다(추가 후 이 이름으로 관리합니다). plugins 배열의 source는 리포지토리 내 플러그인 디렉터리를 상대 경로로 가리킵니다. {\"source\": \"local\", \"path\": \"…\"} 객체 형식도 지원합니다.",+ "sourceTitle": "소스 형식",+ "sourceBody": "GitHub 약칭 owner/repo, 전체 Git URL(https / ssh / git@), 로컬 폴더 경로(~ 지원)를 사용할 수 있습니다. Git 참조에는 브랜치, 태그 또는 commit을 입력하고, 비우면 기본 브랜치를 사용합니다. 스파스 경로는 한 줄에 하나씩 입력하며 리포지토리의 지정된 하위 디렉터리만 체크아웃합니다(대형 리포지토리에 유용).",+ "authTitle": "비공개 리포지토리",+ "authBody": "인증은 전적으로 시스템 Git 구성에 의존하며 Cindy는 Git 자격 증명을 저장하지 않습니다. SSH: 이 머신에 사용 가능한 key가 구성되어 있어야 합니다. 조직이 SAML SSO를 강제하는 경우 GitHub SSH key 설정에서 Configure SSO로 해당 조직에 key를 승인해야 합니다. HTTPS: Personal Access Token을 사용하고 시스템 credential helper에 저장합니다.",+ "rulesTitle": "설치 규칙",+ "rulesBody": "플러그인 id는 전역적으로 고유하며 선착순입니다. 설치된 플러그인과의 충돌은 명확히 표시됩니다. cindy- 같은 공식 예약 접두사를 사용하는 플러그인은 사용자 지정 마켓에서 설치할 수 없습니다. 설치 전에 플러그인이 선언한 권한을 모두 보여주며, 확인하면 설치가 완료되고 자동으로 활성화됩니다.",+ "copy": "가이드 복사",+ "copied": "가이드를 클립보드에 복사했습니다.",+ "copyFailed": "복사에 실패했습니다. 다시 시도하세요."+ }+ }},"install": "플러그인 설치…","empty": "아직 설치된 플러그인이 없습니다",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 2c48ba3f3c..6e05d1e37e 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3016,7 +3016,8 @@"origin": {"public": "公开","organization": "团队共享",- "local": "本地"+ "local": "本地",+ "custom": "自定义"},"emptyFiltered": "没有找到匹配的插件","useAction": "使用",@@ -3029,7 +3030,8 @@"public": "公开","organization": "组织","personal": "个人",- "local": "本地"+ "local": "本地",+ "custom": "自定义"},"install": "安装","details": "详情",@@ -3055,10 +3057,69 @@},"securityTitle": "安装与权限","securityDescription": "安装包会在主进程中校验大小与 SHA-256,再经 Cindy 插件清单校验后原子安装。首次安装完成后即自动开启,可随时在插件页停用;更新会保留当前生效状态。",+ "customSecurityDescription": "该插件来自你添加的自定义市场,未经 Cindy 服务端完整性校验。安装前会在主进程校验插件清单;首次安装完成后即自动开启,可随时在插件页停用。","noPermissions": "此插件未声明额外能力。","installConfirmTitle": "安装「{{name}}」?","installConfirmDescription": "安装包将经过完整性与清单校验。安装完成后插件将自动开启,你可以随时在插件页停用或调整配置。",- "updateConfirmDescription": "安装包将经过完整性与清单校验,并替换现有版本。当前生效状态保持不变。"+ "customInstallConfirmDescription": "插件来自自定义市场,未经服务端完整性校验,安装前将校验插件清单。安装完成后插件将自动开启,你可以随时在插件页停用或调整配置。",+ "updateConfirmDescription": "安装包将经过完整性与清单校验,并替换现有版本。当前生效状态保持不变。",+ "sources": {+ "addMarketplace": "添加插件市场…",+ "dialogTitle": "添加插件市场",+ "dialogDescription": "从 GitHub 仓库、Git URL 或本地文件夹添加插件市场。",+ "learnMore": "了解更多",+ "sourceLabel": "来源",+ "sourcePlaceholder": "owner/repo 或 [email protected]:org/repo.git",+ "refLabel": "Git 引用",+ "refPlaceholder": "主分支",+ "sparseLabel": "稀疏路径",+ "sparsePlaceholder": "每行一个路径,如 team/tools",+ "gitUnavailable": "未检测到 Git 或版本低于 2.25。Git 来源不可用,本地文件夹来源不受影响。",+ "listTitle": "已添加的市场",+ "pluginCount": "{{count}} 个插件",+ "sourceError": "读取失败",+ "localBadge": "本地",+ "defaultRef": "默认分支",+ "neverSynced": "尚未同步",+ "refresh": "刷新",+ "remove": "移除",+ "removeConfirmTitle": "移除市场「{{name}}」?",+ "removeConfirmDescription": "移除后,来自该市场的插件将不再显示;已安装的插件保留。",+ "close": "关闭",+ "add": "添加市场",+ "errors": {+ "invalidSource": "来源格式无效。支持 GitHub owner/repo、Git URL 或本地文件夹路径。",+ "gitUnavailable": "未检测到 Git 或版本低于 2.25,无法添加 Git 来源。",+ "cloneAuthFailed": "无法访问该仓库。私有仓库需要先在系统中配置 Git 认证(credential helper 或 SSH key)。",+ "credentialsNotAllowed": "来源 URL 不能内嵌用户名或密码。请改用系统 Git 认证(credential helper 或 SSH key)。",+ "cloneFailed": "克隆仓库失败,请检查网络连接后重试。",+ "refNotFound": "找不到指定的 Git 引用,请检查分支或标签名是否正确。",+ "manifestMissing": "该来源中找不到受支持的 marketplace.json 清单。",+ "duplicate": "该市场已添加。",+ "notFound": "该市场不存在或已被移除。"+ },+ "guide": {+ "title": "自定义插件市场指南",+ "intro": "插件市场是一个带有清单文件的 Git 仓库或本地文件夹,用来分发一组 Cindy 插件。",+ "structureTitle": "目录结构",+ "structureBody": "市场仓库需要一份清单文件,以及若干插件目录。每个插件目录必须包含合法的 ghost.json(插件身份卡)。",+ "structureLabelManifest": "清单",+ "structureLabelGhostCard": "插件身份卡",+ "structureLabelEntry": "插件入口",+ "structureNote": "清单可以放在以下位置之一:",+ "manifestTitle": "清单格式",+ "manifestBody": "name 是市场的唯一标识(添加后按它管理)。清单的插件数组里,每个条目的 source 指向仓库内的插件目录,使用相对路径;也支持 {\"source\": \"local\", \"path\": \"…\"} 的对象写法。",+ "sourceTitle": "来源格式",+ "sourceBody": "支持 GitHub 简写 owner/repo、完整 Git URL(https / ssh / git@)和本地文件夹路径(含 ~)。Git 引用可填分支、标签或 commit,不填则用默认分支。稀疏路径每行一个,只检出仓库的指定子目录,适合大型仓库。",+ "authTitle": "私有仓库",+ "authBody": "认证完全依赖系统的 Git 配置,Cindy 不保存任何 Git 凭证。SSH 方式:本机已配置可用的 key;若组织开启了 SAML SSO,还需在 GitHub 的 SSH key 设置里为该组织点 Configure SSO 授权。HTTPS 方式:使用 Personal Access Token,并由系统 credential helper 保存。",+ "rulesTitle": "安装规则",+ "rulesBody": "插件 id 全局唯一、先装先得——与已安装插件冲突时会明确提示。使用 cindy- 等官方保留前缀的插件不能从自定义市场安装。安装前会逐项展示插件声明的权限,确认后即完成安装并自动开启。",+ "copy": "复制指南",+ "copied": "指南已复制到剪贴板。",+ "copyFailed": "复制失败,请重试。"+ }+ }},"install": "安装插件…","empty": "还没有安装任何插件",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 2905b76fa4..c6fd8ae06c 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1357,9 +1357,30 @@ interface ElectronAPI {) => Promise<import('../shared/pluginMarket').PluginMarketDetail>;install: (pluginId: string,- options: { expectedReleaseId: string; allowPermissionExpansion?: boolean },+ options: {+ expectedReleaseId: string;+ expectedManifest?: import('../shared/ghost').GhostManifest;+ allowPermissionExpansion?: boolean;+ },) => Promise<{ ghost: import('../shared/ghost').InstalledGhost }>;uninstall: (pluginId: string) => Promise<{ ok: true }>;+ listSources: () => Promise<import('../shared/pluginMarket').MarketSourceSummary[]>;+ pickLocalSource: (+ defaultPath?: string,+ ) => Promise<+ | { canceled: true }+ | { canceled: false; summary: import('../shared/pluginMarket').MarketSourceSummary }+ >;+ addSource: (input: {+ source: string;+ ref?: string;+ sparsePaths?: string[];+ }) => Promise<import('../shared/pluginMarket').MarketSourceSummary>;+ removeSource: (name: string) => Promise<{ ok: true }>;+ refreshSource: (+ name: string,+ ) => Promise<import('../shared/pluginMarket').MarketSourceSummary>;+ gitPreflight: () => Promise<{ ok: boolean; version: string | null }>;};voiceInput: {prewarm: (payload?: { sourceLanguage?: string; refinementEnabled?: boolean }) => Promise<{ ok: true }>;diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.tsindex cb393cccfb..8518b3d052 100644--- a/apps/desktop/src/shared/ipc-errors.ts+++ b/apps/desktop/src/shared/ipc-errors.ts@@ -113,6 +113,13 @@ export type IpcErrorCode =| 'GHOST_FILE_INVALID' // 不是合法 zip / 缺 ghost.json / 清单不合格 / 超限| 'GHOST_COMMAND_CONFLICT' // 显式指令与已装意识撞名(装入拒绝)| 'GHOST_ID_RESERVED' // id 属官方保留前缀(cindy-),用户通道拒装(防抢注蹭凭证别名)+ // 自定义插件市场源(Git / 本地文件夹)+ | 'MARKET_SOURCE_INVALID' // 来源格式非法 / 本地路径不是目录 / 参数组合不允许+ | 'MARKET_GIT_UNAVAILABLE' // 未安装 Git 或版本 < 2.25(稀疏检出下限)+ | 'MARKET_CLONE_AUTH_FAILED' // 克隆被拒绝:私有仓库未配置认证+ | 'MARKET_CLONE_FAILED' // 克隆/拉取失败:网络、代理或远端其它错误+ | 'MARKET_REF_NOT_FOUND' // 指定的 Git 引用(分支/tag/commit)在远端不存在+ | 'MARKET_MANIFEST_MISSING' // 来源内找不到受支持的 marketplace.json// 网关凭据自动下发(model-access)| 'MODEL_ACCESS_FAILED' // 拉取/轮换失败(网络或服务端错误),可重试| 'MODEL_ACCESS_DISABLED' // 服务端灰度未启用(503)——走手填兜底@@ -233,6 +240,12 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>(['GHOST_FILE_INVALID','GHOST_COMMAND_CONFLICT','GHOST_ID_RESERVED',+ 'MARKET_SOURCE_INVALID',+ 'MARKET_GIT_UNAVAILABLE',+ 'MARKET_CLONE_AUTH_FAILED',+ 'MARKET_CLONE_FAILED',+ 'MARKET_REF_NOT_FOUND',+ 'MARKET_MANIFEST_MISSING','MODEL_ACCESS_FAILED','MODEL_ACCESS_DISABLED','MODEL_ACCESS_UNSUPPORTED',diff --git a/apps/desktop/src/shared/pluginMarket.ts b/apps/desktop/src/shared/pluginMarket.tsindex db401fd3b6..bcbc5fca79 100644--- a/apps/desktop/src/shared/pluginMarket.ts+++ b/apps/desktop/src/shared/pluginMarket.ts@@ -8,6 +8,9 @@ export type PluginMarketInstallState =| 'update-available'| 'conflict';+/** 市场项来源:服务端市场,或用户添加的 Git / 本地自定义市场。 */+export type PluginMarketItemSource = 'server' | 'git-market' | 'local-market';+/** Renderer-safe Plugin 市场列表项;所有字段都来自协议或本地安装事实。 */export interface PluginMarketItem {pluginId: string;@@ -24,14 +27,103 @@ export interface PluginMarketItem {icon: PluginIconMetadata | null;installState: PluginMarketInstallState;enabled: boolean | null;+ /** 来源类型;服务端市场项为 'server'。 */+ sourceType: PluginMarketItemSource;+ /** 来源市场名(自定义市场项必填;服务端项为 null)。 */+ sourceMarketName: string | null;}/** 市场快照。服务不可用时 renderer 保留本地插件并只展示非阻断提示。 */export interface PluginMarketSnapshot {items: PluginMarketItem[];unavailableReason: string | null;+ /** 已添加的自定义市场名(按添加顺序);驱动"自定义"筛选 tab 的可见性。 */+ customSourceNames: string[];}/** 详情额外携带经 Desktop 当前 runtime validator 验证过的完整清单。 */export interface PluginMarketDetail extends PluginMarketItem {manifest: GhostManifest;}++/* ------------------------------------------------------------------------ */+/* 自定义市场源(Git / 本地文件夹) */+/* ------------------------------------------------------------------------ */++/** 用户添加的市场来源。Git 源支持可选引用与稀疏检出;本地源指向文件夹。 */+export type MarketSource =+ | { type: 'git'; url: string; ref?: string; sparsePaths: string[] }+ | { type: 'local'; path: string };++/** 持久化的市场来源配置(sources.v1.json)。 */+export interface MarketSourceConfig {+ /** 市场名,来自 marketplace.json 的 name;全局唯一,作为管理主键。 */+ name: string;+ addedAt: string;+ lastSyncedAt: string | null;+ /** 最近一次同步到的 Git commit SHA;本地源为 null。 */+ lastRevision: string | null;+ source: MarketSource;+}++/** Renderer 管理视图使用的来源摘要。 */+export interface MarketSourceSummary extends MarketSourceConfig {+ /** 最近一次发现到的插件数;发现失败时为 0 并携带 status。 */+ pluginCount: number;+ status: 'ok' | 'error';+ /** status === 'error' 时的 IPC 错误码(Renderer 按码本地化)。 */+ errorCode: string | null;+}++/**+ * 来源的规范化指纹。市场名是 marketplace.json 自报的、**可复用**——移除来源 A 后+ * 添加一个同名的来源 B,`customMarketPluginId` 完全相同;账本所有权若只锚在+ * pluginId 上,无关甚至恶意仓库就能借同名市场"更新"A 装出来的插件。所以自定义+ * 安装的账本记录同时记下这个指纹,所有权校验必须两者都对上。+ * 与 sources/store 的 sourcesEqual、sources/index 的 marketCloneSlug 同一套+ * 判定维度(type + 定位 + ref + 稀疏路径)。+ *+ * 序列化必须**无歧义**:用分隔符拼接(`join(',')`、`#ref:sparse`)会产生可构造的+ * 碰撞——`sparsePaths:['a,b','c']` 与 `['a','b,c']`、`ref:'x' + ['p']` 与+ * `ref:'x:p' + []` 都会得到同一 key,两个不同来源被判成同一个,所有权校验随之+ * 失效。JSON 数组序列化对每个元素定界,不存在拼接歧义。+ */+export function marketSourceKey(source: MarketSource): string {+ return source.type === 'local'+ ? JSON.stringify(['local', source.path])+ : JSON.stringify(['git', source.url, source.ref ?? null, source.sparsePaths]);+}++/**+ * 自定义市场插件的合成 pluginId。与服务端 CUID(^c[a-z0-9]{24}$)互不相交,+ * Main 在 detail/install/uninstall 入口据此分流,Renderer 无需感知差异。+ */+export const CUSTOM_MARKET_PLUGIN_ID_PREFIX = 'custom:';++export function customMarketPluginId(marketName: string, ghostId: string): string {+ return `${CUSTOM_MARKET_PLUGIN_ID_PREFIX}${encodeURIComponent(marketName)}/${encodeURIComponent(ghostId)}`;+}++export function parseCustomMarketPluginId(+ pluginId: string,+): { marketName: string; ghostId: string } | null {+ if (!pluginId.startsWith(CUSTOM_MARKET_PLUGIN_ID_PREFIX)) return null;+ const rest = pluginId.slice(CUSTOM_MARKET_PLUGIN_ID_PREFIX.length);+ const slash = rest.indexOf('/');+ if (slash <= 0 || slash === rest.length - 1) return null;+ try {+ return {+ marketName: decodeURIComponent(rest.slice(0, slash)),+ ghostId: decodeURIComponent(rest.slice(slash + 1)),+ };+ } catch {+ return null;+ }+}++/**+ * 自定义市场插件的合成 releaseId。版本变化即产生新 releaseId,+ * 从而复用服务端市场既有的 update-available / expectedReleaseId 机制。+ */+export function customMarketReleaseId(marketName: string, ghostId: string, version: string): string {+ return `custom:${encodeURIComponent(marketName)}:${encodeURIComponent(ghostId)}:${encodeURIComponent(version)}`;+}diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex 5c208396d8..a38d4dfc53 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -1258,4 +1258,4 @@"note": "一次提问到一次回答结束。**内部概念,不作为界面术语**:面向用户一律说「消息」,只在确实要强调一次完整往返时说「一轮」(如「上一轮」)。不要引入「轮次」作为界面用词。"}]-}+}\ No newline at end of file