Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(library): 作品库支持在文件夹中显示与系统另存为 (#3626)
Praiseac1435b88b4b
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.tsindex 2a348f786d..cdba7e2cfe 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts@@ -1503,6 +1503,20 @@ describe('FORGE_GUIDE', () => {expect(FORGE_GUIDE).toContain('仅企业组织成员可用,个人账号不可用');});+ it('documents library reveal/saveAs without leaking the user-chosen absolute path', () => {+ expect(FORGE_GUIDE).toContain("op: 'reveal'");+ expect(FORGE_GUIDE).toContain("op: 'saveAs'");+ expect(FORGE_GUIDE).toContain('path 永远是库内相对键,不是用户另存到的绝对路径');+ expect(FORGE_GUIDE).toContain('reveal 打开系统文件夹、saveAs 弹系统对话框');+ expect(FORGE_GUIDE).toContain('跨平台标题带已核验插件名');+ expect(FORGE_GUIDE).toContain('已有对话框在场');+ expect(FORGE_GUIDE).toContain('对话框期间账号切换');+ expect(FORGE_GUIDE).toContain('拷贝完成替换前、reveal 打开文件夹前再核一次会话');+ expect(FORGE_GUIDE).toContain('先拷到目标旁临时文件再替换');+ expect(FORGE_GUIDE).toContain('`BUSY`');+ expect(FORGE_GUIDE).toContain('`RATE_LIMITED`');+ });+it('documents explicit Forge install without changing pack into an install action', () => {expect(FORGE_GUIDE).toContain("ghost_forge_install({ dir: '<绝对路径>' })");expect(FORGE_GUIDE).toContain('不要因为 scaffold 或 pack 成功就自动调用本工具');diff --git a/apps/desktop/src/main/cindy-brain/__tests__/librarySaveAsDialogParent.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/librarySaveAsDialogParent.test.tsnew file mode 100644index 0000000000..1023bf1de5--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/librarySaveAsDialogParent.test.ts@@ -0,0 +1,30 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++import { describe, expect, it } from 'vitest';++describe('library saveAs dialog parent wiring', () => {+ const mainSource = readFileSync(+ resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),+ 'utf8',+ ).replace(/\r\n/g, '\n');++ const start = mainSource.indexOf('export function getGhostLibrarySlot(');+ const end = mainSource.indexOf('\n}\n\n/**\n * 迁移执行体', start);+ const body = mainSource.slice(start, end);++ it('parents saveAs to a visible main-shell window, not getAllWindows()[0]', () => {+ expect(start).toBeGreaterThan(-1);+ expect(end).toBeGreaterThan(start);+ expect(body).toContain('const candidates = mainShellWindows().filter(');+ expect(body).toContain('window.isVisible() && !window.isMinimized()');+ expect(body).toContain('candidates.includes(focused)');+ expect(body).toContain("throw new Error('没有可挂靠的宿主窗口')");+ expect(body).not.toContain('BrowserWindow.getAllWindows()[0]');+ // Windows 对话框不展示 message,插件名必须进跨平台 title。+ expect(body).toContain("t('settings.ghosts.saveAs.dialogTitle')");+ expect(body).toMatch(+ /t\('settings\.ghosts\.saveAs\.dialogTitle'\)[\s\S]{0,80}replaceAll\(\s*'{{name}}'/,+ );+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.tsindex 2e94e4ba78..1de27566f7 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts@@ -3,7 +3,7 @@* read/rename/delete)、db 子集(经进程内 core)、binding 漂移 → unavailable、* owner scope 切换后旧会话作废且写入落新根。注入 deps + tmpdir,零 Electron。*/-import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';@@ -45,12 +45,16 @@ describe('GhostLibrarySlot', () => {let scopeKey: string | null = 'local:owner-a:1';let ghost: InstalledGhost;let slot: GhostLibrarySlot;+ let showItemInFolder: ReturnType<typeof vi.fn>;+ let showSaveDialog: ReturnType<typeof vi.fn>;+ let clock: number;beforeEach(async () => {tmp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-library-slot-'));defaultRootBase = path.join(tmp, 'owners', 'a', 'libraries');bindingFile = path.join(tmp, 'owners', 'a', 'libraries-binding.json');candidate = path.join(tmp, 'picked');+ clock = 0;await fs.promises.mkdir(candidate, { recursive: true });ghost = makeGhost(true);const deps: GhostLibrarySlotDeps = {@@ -72,7 +76,12 @@ describe('GhostLibrarySlot', () => {getDiskFreeBytes: async () => 1024 ** 4,workerScriptPath: () => path.join(tmp, 'unused-worker.js'),betterSqliteModulePath: () => 'better-sqlite3',+ showItemInFolder: (...args: unknown[]) => showItemInFolder(...args),+ showSaveDialog: (...args: unknown[]) => showSaveDialog(...args),+ now: () => clock,};+ showItemInFolder = vi.fn();+ showSaveDialog = vi.fn(async () => ({ canceled: true }));slot = new GhostLibrarySlot(deps);});@@ -209,4 +218,226 @@ describe('GhostLibrarySlot', () => {if (!r.ok || r.op !== 'read') throw new Error(JSON.stringify(r));expect(r.content).toBe('owner-b');});++ it('reveal: 在文件夹中显示库内已有文件',+ async () => {+ await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ await slot.handleLibraryRequest(GHOST_ID, { op: 'write', path: 'exports/a.psd', content: 'psd' });+ const r = await slot.handleLibraryRequest(GHOST_ID, { op: 'reveal', path: 'exports/a.psd' });+ expect(r.ok).toBe(true);+ if (!r.ok || r.op !== 'reveal') throw new Error(JSON.stringify(r));+ expect(showItemInFolder).toHaveBeenCalledTimes(1);+ const abs = String(showItemInFolder.mock.calls[0]?.[0] ?? '');+ expect(abs.endsWith(`${path.sep}exports${path.sep}a.psd`)).toBe(true);+ },+ );++ it('reveal: 库内没有该文件 → NOT_FOUND,不调用 Finder',+ async () => {+ await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ const r = await slot.handleLibraryRequest(GHOST_ID, { op: 'reveal', path: 'exports/missing.psd' });+ expect(r.ok).toBe(false);+ if (!r.ok) expect(r.errorCode).toBe('NOT_FOUND');+ expect(showItemInFolder).not.toHaveBeenCalled();+ },+ );++ it('reveal: 同插件两次请求间隔不足 = RATE_LIMITED(按尝试记账)', async () => {+ await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ await slot.handleLibraryRequest(GHOST_ID, { op: 'write', path: 'exports/a.psd', content: 'psd' });+ const first = await slot.handleLibraryRequest(GHOST_ID, { op: 'reveal', path: 'exports/a.psd' });+ expect(first.ok).toBe(true);+ clock += 1_000;+ const second = await slot.handleLibraryRequest(GHOST_ID, { op: 'reveal', path: 'exports/a.psd' });+ expect(second).toMatchObject({ ok: false, errorCode: 'RATE_LIMITED' });+ expect(showItemInFolder).toHaveBeenCalledTimes(1);+ });++ it('reveal: 解析期间账号切换则不打开文件夹', async () => {+ await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ await slot.handleLibraryRequest(GHOST_ID, { op: 'write', path: 'exports/a.psd', content: 'psd' });+ const orig = LibraryVault.prototype.resolveExistingFile;+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ let started!: () => void;+ const opened = new Promise<void>((resolve) => {+ started = resolve;+ });+ const spy = vi.spyOn(LibraryVault.prototype, 'resolveExistingFile').mockImplementation(async function (+ this: LibraryVault,+ relPath: string,+ ) {+ started();+ await gate;+ return orig.call(this, relPath);+ });+ try {+ const pending = slot.handleLibraryRequest(GHOST_ID, { op: 'reveal', path: 'exports/a.psd' });+ await opened;+ scopeKey = 'local:owner-b:1';+ await slot.disposeAll();+ release();+ const r = await pending;+ expect(r).toMatchObject({ ok: false, errorCode: 'LIBRARY_UNAVAILABLE' });+ expect(showItemInFolder).not.toHaveBeenCalled();+ } finally {+ spy.mockRestore();+ }+ });++ it('saveAs: 用户取消不复制;确认则拷到所选路径,成功只回库内相对键',+ async () => {+ await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ await slot.handleLibraryRequest(GHOST_ID, { op: 'write', path: 'exports/a.psd', content: 'psd-bytes' });+ showSaveDialog.mockResolvedValueOnce({ canceled: true });+ const cancelled = await slot.handleLibraryRequest(GHOST_ID, {+ op: 'saveAs', path: 'exports/a.psd', name: 'layers.psd',+ });+ expect(cancelled).toEqual({ ok: true, op: 'saveAs', cancelled: true });+ expect(showSaveDialog).toHaveBeenCalledWith({+ defaultPath: 'layers.psd',+ ghostName: '测试意识',+ });++ clock += 4_000;+ const dest = path.join(tmp, 'Desktop', 'out.psd');+ await fs.promises.mkdir(path.dirname(dest), { recursive: true });+ showSaveDialog.mockResolvedValueOnce({ canceled: false, filePath: dest });+ const saved = await slot.handleLibraryRequest(GHOST_ID, {+ op: 'saveAs', path: 'exports/a.psd', name: 'layers.psd',+ });+ expect(saved.ok).toBe(true);+ if (!saved.ok || saved.op !== 'saveAs' || saved.cancelled) throw new Error(JSON.stringify(saved));+ expect(saved.path).toBe('exports/a.psd');+ expect(saved.bytes).toBeGreaterThan(0);+ expect(JSON.stringify(saved)).not.toContain(dest);+ expect(fs.readFileSync(dest, 'utf8')).toBe('psd-bytes');+ },+ );++ it('saveAs: 覆盖已有目标时先写临时文件;拷贝失败则原文件原样', async () => {+ await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ await slot.handleLibraryRequest(GHOST_ID, { op: 'write', path: 'exports/a.psd', content: 'new-psd' });+ const dest = path.join(tmp, 'Desktop', 'existing.psd');+ await fs.promises.mkdir(path.dirname(dest), { recursive: true });+ await fs.promises.writeFile(dest, 'keep-me');++ clock += 4_000;+ showSaveDialog.mockResolvedValueOnce({ canceled: false, filePath: dest });+ const copy = vi.spyOn(fs.promises, 'copyFile').mockRejectedValueOnce(new Error('ENOSPC'));+ try {+ const r = await slot.handleLibraryRequest(GHOST_ID, { op: 'saveAs', path: 'exports/a.psd' });+ expect(r).toMatchObject({ ok: false, errorCode: 'INTERNAL' });+ expect(fs.readFileSync(dest, 'utf8')).toBe('keep-me');+ } finally {+ copy.mockRestore();+ }++ clock += 4_000;+ showSaveDialog.mockResolvedValueOnce({ canceled: false, filePath: dest });+ const saved = await slot.handleLibraryRequest(GHOST_ID, { op: 'saveAs', path: 'exports/a.psd' });+ expect(saved.ok).toBe(true);+ expect(fs.readFileSync(dest, 'utf8')).toBe('new-psd');+ });++ it('saveAs: 同插件两次请求间隔不足 = RATE_LIMITED(按尝试记账)', async () => {+ await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ await slot.handleLibraryRequest(GHOST_ID, { op: 'write', path: 'exports/a.psd', content: 'psd' });+ showSaveDialog.mockResolvedValue({ canceled: true });+ expect((await slot.handleLibraryRequest(GHOST_ID, { op: 'saveAs', path: 'exports/a.psd' })).ok).toBe(true);+ clock += 1_000;+ const second = await slot.handleLibraryRequest(GHOST_ID, { op: 'saveAs', path: 'exports/a.psd' });+ expect(second).toMatchObject({ ok: false, errorCode: 'RATE_LIMITED' });+ expect(showSaveDialog).toHaveBeenCalledTimes(1);+ });++ it('saveAs: 已有另存为窗口在场 = BUSY,不排队', async () => {+ await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ await slot.handleLibraryRequest(GHOST_ID, { op: 'write', path: 'exports/a.psd', content: 'psd' });+ let release: (value: { canceled: boolean; filePath?: string }) => void = () => {};+ const gate = new Promise<{ canceled: boolean; filePath?: string }>((resolve) => {+ release = resolve;+ });+ let dialogOpened!: () => void;+ const opened = new Promise<void>((resolve) => {+ dialogOpened = resolve;+ });+ showSaveDialog.mockImplementationOnce(() => {+ dialogOpened();+ return gate;+ });+ const first = slot.handleLibraryRequest(GHOST_ID, { op: 'saveAs', path: 'exports/a.psd' });+ await opened;+ clock += 4_000;+ const second = await slot.handleLibraryRequest(GHOST_ID, { op: 'saveAs', path: 'exports/a.psd' });+ expect(second).toMatchObject({ ok: false, errorCode: 'BUSY' });+ release({ canceled: true });+ expect(await first).toEqual({ ok: true, op: 'saveAs', cancelled: true });+ });++ it('saveAs: 拷贝期间账号切换则不替换已有目标', async () => {+ await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ await slot.handleLibraryRequest(GHOST_ID, { op: 'write', path: 'exports/a.psd', content: 'new-psd' });+ const dest = path.join(tmp, 'Desktop', 'existing.psd');+ await fs.promises.mkdir(path.dirname(dest), { recursive: true });+ await fs.promises.writeFile(dest, 'keep-me');+ clock += 4_000;+ showSaveDialog.mockResolvedValueOnce({ canceled: false, filePath: dest });++ const origCopy = fs.promises.copyFile.bind(fs.promises);+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ let started!: () => void;+ const opened = new Promise<void>((resolve) => {+ started = resolve;+ });+ const spy = vi.spyOn(fs.promises, 'copyFile').mockImplementation(async (src, dst, mode) => {+ started();+ await gate;+ return origCopy(src, dst, mode);+ });+ try {+ const pending = slot.handleLibraryRequest(GHOST_ID, { op: 'saveAs', path: 'exports/a.psd' });+ await opened;+ scopeKey = 'local:owner-b:1';+ await slot.disposeAll();+ release();+ const r = await pending;+ expect(r).toMatchObject({ ok: false, errorCode: 'LIBRARY_UNAVAILABLE' });+ expect(fs.readFileSync(dest, 'utf8')).toBe('keep-me');+ } finally {+ spy.mockRestore();+ }+ });++ it('saveAs: 对话框期间账号切换则拒绝拷贝,不把源文件拷出', async () => {+ await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });+ await slot.handleLibraryRequest(GHOST_ID, { op: 'write', path: 'exports/a.psd', content: 'secret-psd' });+ const dest = path.join(tmp, 'Desktop', 'leaked.psd');+ await fs.promises.mkdir(path.dirname(dest), { recursive: true });+ let release: (value: { canceled: boolean; filePath?: string }) => void = () => {};+ const gate = new Promise<{ canceled: boolean; filePath?: string }>((resolve) => {+ release = resolve;+ });+ let dialogOpened!: () => void;+ const opened = new Promise<void>((resolve) => {+ dialogOpened = resolve;+ });+ showSaveDialog.mockImplementationOnce(() => {+ dialogOpened();+ return gate;+ });+ const pending = slot.handleLibraryRequest(GHOST_ID, { op: 'saveAs', path: 'exports/a.psd' });+ await opened;+ scopeKey = 'local:owner-b:1';+ await slot.disposeAll();+ release({ canceled: false, filePath: dest });+ const r = await pending;+ expect(r).toMatchObject({ ok: false, errorCode: 'LIBRARY_UNAVAILABLE' });+ expect(fs.existsSync(dest)).toBe(false);+ });});diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.tsindex f199bbfd37..5cb7114f73 100644--- a/apps/desktop/src/main/cindy-brain/forge.ts+++ b/apps/desktop/src/main/cindy-brain/forge.ts@@ -3469,6 +3469,13 @@ for (const chunk of chunks) {const done = await cindy.library({ op: 'writeCommit', streamId: b.streamId });// done = { ok:true, path, bytes, sha256 }; 中断/放弃用 writeAbort+// 在文件夹中显示 / 系统另存为(不回用户所选绝对路径)+await cindy.library({ op: 'reveal', path: 'exports/a.psd' });+const saved = await cindy.library({ op: 'saveAs', path: 'exports/a.psd', name: 'layers.psd' });+// saved = { ok:true, cancelled:true }+// 或 { ok:true, cancelled:false, path:'exports/a.psd', bytes }+// path 永远是库内相对键,不是用户另存到的绝对路径+// SQLite:参数化语句 + 首词白名单(SELECT/WITH/INSERT/REPLACE/UPDATE/DELETE/// CREATE/DROP/ALTER/REINDEX/ANALYZE);ATTACH/PRAGMA/VACUUM/事务语句一律拒,// 事务由宿主管理(db.batch 整批原子),迁移按 user_version 幂等续跑@@ -3491,7 +3498,15 @@ await cindy.library({ op: 'db.check', dbPath: 'library.sqlite' }); // quick_ch\`LIBRARY_UNAVAILABLE\`(含 reason:binding-moved/disk-missing/corrupt)、\`LIBRARY_READONLY\`、\`DISK_FULL\`、\`PATH_INVALID\`、\`NOT_FOUND\`、\`ALREADY_EXISTS\`、\`TOO_LARGE\`、\`STREAM_INVALID\`、\`DB_STATEMENT_REJECTED\`、- \`DB_ROW_LIMIT\`(结果集超 2000 行,自己加 LIMIT)、\`DB_MIGRATION_CONFLICT\`;+ \`DB_ROW_LIMIT\`(结果集超 2000 行,自己加 LIMIT)、\`DB_MIGRATION_CONFLICT\`、+ \`BUSY\`、\`RATE_LIMITED\`;+- **reveal / saveAs**:只收库内相对路径。成功不回用户另存目标的绝对路径;+ 取消是 \`{ cancelled:true }\`。reveal 打开系统文件夹、saveAs 弹系统对话框+ (跨平台标题带已核验插件名;macOS 另有正文),同插件 3 秒内连发 \`RATE_LIMITED\`;+ saveAs 已有对话框在场 \`BUSY\`(不排队)。+ 对话框期间账号切换则拒绝拷贝(\`LIBRARY_UNAVAILABLE\`);+ 拷贝完成替换前、reveal 打开文件夹前再核一次会话;+ 确认后先拷到目标旁临时文件再替换,失败不破坏已有文件;- **不可用 ≠ 空**:\`state:'unavailable'\` 时**不要**当空库重建、不要触发清理、不要把素材判成已删——如实向用户展示状态,等位置恢复;- **无跨库事务**:多个 .sqlite 之间没有 ATTACH;跨库一致性用幂等 + 墓碑diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 583ccf8510..d701d7a0f2 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -5142,6 +5142,41 @@ export function getGhostLibrarySlot(): GhostLibrarySlot {workerScriptPath: defaultLibraryDbWorkerPath,betterSqliteModulePath: () => resolveBetterSqliteModuleEntry() ?? 'better-sqlite3',log,+ showItemInFolder: (absPath) => {+ shell.showItemInFolder(absPath);+ },+ showSaveDialog: async (opts) => {+ // 另存为由插件自主发起,必须挂可见主壳窗。不能 `getAllWindows()[0]`:+ // 语音 overlay 是 hidden + focusable:false 的 prewarm 窗,经常排在 [0]+ // (bootstrap-electron.ts / authManager.ts 已踩过);macOS sheet 挂上去+ // 用户看不见,saveAsDialogInFlight 却一直占着。无主壳窗 = 失败关闭。+ const candidates = mainShellWindows().filter(+ (window) => window.isVisible() && !window.isMinimized(),+ );+ const focused = BrowserWindow.getFocusedWindow();+ const win =+ focused && !focused.isDestroyed() && candidates.includes(focused)+ ? focused+ : candidates[0];+ if (!win) throw new Error('没有可挂靠的宿主窗口');+ // main 侧 t() 只插值 {{appName}},插件名在调用点替换(与 pick 槽同做法)。+ // Electron SaveDialogOptions.message 仅 macOS;Windows 只看 title,+ // 已核验插件名必须进跨平台标题,否则用户看不到是谁在另存为。+ const title = t('settings.ghosts.saveAs.dialogTitle').replaceAll(+ '{{name}}',+ opts.ghostName,+ );+ const message = t('settings.ghosts.saveAs.dialogMessage').replaceAll(+ '{{name}}',+ opts.ghostName,+ );+ const picked = await dialog.showSaveDialog(win, {+ title,+ message,+ defaultPath: opts.defaultPath,+ });+ return { canceled: picked.canceled, filePath: picked.filePath };+ },});// 面板只读投影(cindy-ghost://<id>/library/<relPath>)的解析器:与电子脑// read 同源校验(binding 根 + vault 路径纪律),失败折叠 404。diff --git a/apps/desktop/src/main/cindy-brain/librarySlot.ts b/apps/desktop/src/main/cindy-brain/librarySlot.tsindex 4547a94934..77130c6e7c 100644--- a/apps/desktop/src/main/cindy-brain/librarySlot.ts+++ b/apps/desktop/src/main/cindy-brain/librarySlot.ts@@ -17,11 +17,13 @@* 全部经 deps,单测拿 tmpdir + 进程内 core 直测,零 Electron。*/+import { randomBytes } from 'node:crypto';import * as fs from 'node:fs';import * as path from 'node:path';import {GHOST_LIBRARY_OPS,+ GHOST_PICK_MIN_INTERVAL_MS,type GhostPipeLibraryResult,type InstalledGhost,} from '../../shared/ghost.js';@@ -60,6 +62,12 @@ export interface GhostLibrarySlotDeps {info: (msg: string, meta?: Record<string, unknown>) => void;warn: (msg: string, meta?: Record<string, unknown>) => void;};+ /** 在 Finder/Explorer 显示库内已有文件(生产接 shell.showItemInFolder)。 */+ showItemInFolder?(absPath: string): void;+ /** 系统另存为(生产接 dialog.showSaveDialog;标题/正文由主机拼装并带已核验插件名)。 */+ showSaveDialog?(opts: { defaultPath: string; ghostName: string }): Promise<{ canceled: boolean; filePath?: string }>;+ /** 可注入时钟(单测限速);默认 Date.now。 */+ now?(): number;}const fail = (errorCode: string, message: string): GhostPipeLibraryResult => ({ ok: false, errorCode, message });@@ -68,6 +76,12 @@ export class GhostLibrarySlot {private readonly sessions = new Map<string, GhostLibrarySession>();/** 迁移进行中的插件:全部写操作只读化(切换与 grace 前不再有写入落旧根)。 */private readonly relocating = new Set<string>();+ /** 插件 id → 上次 reveal 尝试时刻(按尝试记账;对齐 pick/confirm 骚扰钳制)。 */+ private readonly lastRevealAttemptAt = new Map<string, number>();+ /** 插件 id → 上次 saveAs 尝试时刻(按尝试记账;对齐 pick/confirm 骚扰钳制)。 */+ private readonly lastSaveAsAttemptAt = new Map<string, number>();+ /** 全局另存为对话框在场标记(系统弹窗一次一个,不排队)。 */+ private saveAsDialogInFlight = false;constructor(private readonly deps: GhostLibrarySlotDeps) {}@@ -214,6 +228,29 @@ export class GhostLibrarySlot {}}+ /**+ * 慢 IO / 系统对话框之后再核一次:停用、切账号、disposeAll 都会让这次+ * 请求作废。reveal 的 resolveExistingFile 与 saveAs 的 copyFile 都不走+ * vault.invalidated,不能把切换前解析的路径继续交给 Finder 或 rename。+ */+ private rejectIfSessionStale(+ ghostId: string,+ session: GhostLibrarySession,+ cancelledMessage: string,+ ): GhostPipeLibraryResult | null {+ if (!this.checkEligibility(ghostId)) {+ return fail('NOT_DECLARED', '插件未装入、已停用或未声明 "library" 能力');+ }+ if (this.deps.captureOwnerScope() !== session.ownerScopeKey) {+ return fail('LIBRARY_UNAVAILABLE', cancelledMessage);+ }+ const live = this.sessions.get(ghostId);+ if (!live || live !== session) {+ return fail('LIBRARY_UNAVAILABLE', cancelledMessage);+ }+ return null;+ }+/** dbPath 相对键 → 库内绝对路径;经 vault 收敛校验(库内 symlink 指根外拒)。 */private async resolveDbPath(session: GhostLibrarySession, dbPath: unknown): Promise<{ abs: string } | GhostPipeLibraryResult> {const reason = validateLibraryRelPath(dbPath);@@ -338,6 +375,117 @@ export class GhostLibrarySlot {if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };return { ok: true, op: 'rename', from: r.from, to: r.to };}+ case 'reveal': {+ if (typeof req.path !== 'string' || !req.path) {+ return fail('PATH_INVALID', 'reveal 需要库内相对路径');+ }+ const abs = await vault.resolveExistingFile(req.path);+ if (!abs) return fail('NOT_FOUND', `库内没有这个文件:${req.path}`);+ if (!this.deps.showItemInFolder) return fail('UNSUPPORTED', '当前宿主不能在文件夹中显示');++ // 骚扰钳制:限速按尝试记账(spam 顺延窗口),PATH_INVALID/NOT_FOUND/UNSUPPORTED 不记账。+ const now = this.deps.now?.() ?? Date.now();+ const last = this.lastRevealAttemptAt.get(ghostId);+ this.lastRevealAttemptAt.set(ghostId, now);+ if (last !== undefined && now - last < GHOST_PICK_MIN_INTERVAL_MS) {+ return fail('RATE_LIMITED', '在文件夹中显示请求太频繁,稍后再试');+ }+ const stale = this.rejectIfSessionStale(+ ghostId,+ session,+ '账号已切换,在文件夹中显示已取消',+ );+ if (stale) return stale;+ this.deps.showItemInFolder(abs);+ return { ok: true, op: 'reveal', path: req.path };+ }+ case 'saveAs': {+ if (typeof req.path !== 'string' || !req.path) {+ return fail('PATH_INVALID', 'saveAs 需要库内相对路径');+ }+ const relPath = req.path;+ const abs = await vault.resolveExistingFile(relPath);+ if (!abs) return fail('NOT_FOUND', `库内没有这个文件:${relPath}`);+ if (!this.deps.showSaveDialog) return fail('UNSUPPORTED', '当前宿主不能弹出另存为');+ const ghost = this.deps.getGhost(ghostId);+ if (!ghost) return fail('NOT_DECLARED', '插件未装入、已停用或未声明 "library" 能力');++ // 骚扰钳制:限速按尝试记账(spam 顺延窗口),再看全局在场标记。+ const now = this.deps.now?.() ?? Date.now();+ const last = this.lastSaveAsAttemptAt.get(ghostId);+ this.lastSaveAsAttemptAt.set(ghostId, now);+ if (last !== undefined && now - last < GHOST_PICK_MIN_INTERVAL_MS) {+ return fail('RATE_LIMITED', '另存为请求太频繁,稍后再试');+ }+ if (this.saveAsDialogInFlight) {+ return fail('BUSY', '已有一个选择窗口在等用户操作');+ }++ const rawName = typeof req.name === 'string' ? req.name.trim() : '';+ const base = path.basename(rawName || path.basename(abs) || 'export.bin');+ this.saveAsDialogInFlight = true;+ let picked: { canceled: boolean; filePath?: string };+ try {+ picked = await this.deps.showSaveDialog({+ defaultPath: base,+ ghostName: ghost.manifest.name,+ });+ } catch (error) {+ this.deps.log?.warn('ghost library saveAs dialog failed', {+ ghostId,+ err: error instanceof Error ? error.message : String(error),+ });+ return fail('INTERNAL', '另存为窗口无法打开');+ } finally {+ this.saveAsDialogInFlight = false;+ }+ if (picked.canceled || !picked.filePath) {+ return { ok: true, op: 'saveAs', cancelled: true };+ }++ // 对话框可能挂很久:期间账号切换会 disposeAll 作废旧 vault,但源文件+ // 仍在磁盘。不得用切换前解析的 abs 拷贝,也不得把用户所选绝对路径回沙箱。+ const afterDialog = this.rejectIfSessionStale(+ ghostId,+ session,+ '账号已切换,另存为已取消',+ );+ if (afterDialog) return afterDialog;+ const live = this.sessions.get(ghostId);+ if (!live) return fail('LIBRARY_UNAVAILABLE', '账号已切换,另存为已取消');+ const freshAbs = await live.vault.resolveExistingFile(relPath);+ if (!freshAbs) return fail('NOT_FOUND', `库内没有这个文件:${relPath}`);+ const dest = picked.filePath;+ // 先拷到目标旁临时文件,成功后再 rename 替换。copyFile 直接写 dest+ // 会在磁盘满/中断时截断用户已有文件;同目录 rename 在 POSIX 原子,+ // Windows 经 libuv MoveFileEx REPLACE_EXISTING。失败清 tmp、不碰原文件+ // (不走先删目标再 rename:那条 Windows 退化会在第二步失败时毁掉原文件)。+ const tmpDest = path.join(+ path.dirname(dest),+ `.cindy-saveas-${process.pid}-${randomBytes(6).toString('hex')}.tmp`,+ );+ try {+ await fs.promises.copyFile(freshAbs, tmpDest);+ // copy 可能很慢:期间 disposeAll 不会取消这份 Node 拷贝,替换前再核一次。+ const afterCopy = this.rejectIfSessionStale(+ ghostId,+ session,+ '账号已切换,另存为已取消',+ );+ if (afterCopy) return afterCopy;+ await fs.promises.rename(tmpDest, dest);+ } catch (error) {+ this.deps.log?.warn('ghost library saveAs copy failed', {+ ghostId,+ err: error instanceof Error ? error.message : String(error),+ });+ return fail('INTERNAL', '另存为写入失败');+ } finally {+ await fs.promises.unlink(tmpDest).catch(() => {});+ }+ const st = await fs.promises.stat(dest);+ return { ok: true, op: 'saveAs', cancelled: false, path: relPath, bytes: st.size };+ }case 'db.open': {const resolved = await this.resolveDbPath(session, req.dbPath);if (!('abs' in resolved)) return resolved;diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 087196fdae..77cf33e259 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -4693,7 +4693,7 @@"fsWrite": "Can write files (create / modify)","fsWriteDetail": "Its own private data folder is always writable. Writes into the current session's working directory follow the session's permission mode (auto-approve modes write directly; per-action modes ask you first). Any other folder always requires your confirmation. Files are always written by the host — the plugin itself never touches your file system.","libraryPersist": "Can use a durable library (large files and databases)",- "libraryPersistDetail": "It gets a Cindy-managed storage area for your work (canvases, images, databases) with no normal plugin data quota. All file and database operations are executed by the host; the plugin only uses relative paths inside its own library and cannot touch your other files. Uninstalling the plugin does not delete this data; deletion requires separate confirmation in Cindy settings.",+ "libraryPersistDetail": "It gets a Cindy-managed storage area for your work (canvases, images, databases) with no normal plugin data quota. All file and database operations are executed by the host; the plugin only uses relative paths inside its own library and cannot touch your other files. It can also ask Cindy to show a library file in Finder or Explorer, or open the system Save As dialog so you choose where a copy goes; cancelling Save As copies nothing. Uninstalling the plugin does not delete this data; deletion requires separate confirmation in Cindy settings.","networkHost": "Accesses the network domain {{host}}","networkSecret": "Needs a credential from you: \"{{name}}\"","networkSecretGhostInputDetail": "Collected by this plugin's own settings UI — the plugin page sees the value at entry time. It is then handed to the host in one step for encrypted storage; once stored, the plugin can never read it back, and the host injects it only for the domains it declares.",@@ -4913,6 +4913,10 @@"dialogTitle": "Choose a folder","dialogMessage": "Plugin “{{name}}” is asking you to choose a folder"},+ "saveAs": {+ "dialogTitle": "Plugin “{{name}}” — Save As",+ "dialogMessage": "Plugin “{{name}}” is asking you to save a copy"+ },"confirm": {"dialogTitle": "Plugin “{{name}}” needs your confirmation"},diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 157d426611..ce74e82390 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -4686,7 +4686,7 @@"fsWrite": "ファイルを書き込めます(作成/変更)","fsWriteDetail": "専用データフォルダにはいつでも書き込めます。現在のセッションの作業ディレクトリへの書き込みはセッションの権限モードに従います(自動承認モードでは直接書き込み、逐次確認モードでは事前に承認を求めます)。それ以外のフォルダへの書き込みは毎回確認が必要です。ファイルは常にホストが代理で書き込み、プラグイン自体があなたのファイルシステムに直接アクセスすることはありません。","libraryPersist": "永続ライブラリを使用可能(大量のファイルとデータベース)",- "libraryPersistDetail": "Cindy が管理する独立した保存領域を取得し、作品データ(キャンバス、画像、データベースなど)を保存します。通常のプラグインデータ割り当ての制限を受けません。ファイルとデータベースの操作はすべてホストが代行実行し、プラグインはライブラリ内の相対パスのみを使用して、他のファイルに触れることはできません。プラグインをアンインストールしてもこのデータは削除されず、削除には Cindy 設定での個別確認が必要です。",+ "libraryPersistDetail": "Cindy が管理する独立した保存領域を取得し、作品データ(キャンバス、画像、データベースなど)を保存します。通常のプラグインデータ割り当ての制限を受けません。ファイルとデータベースの操作はすべてホストが代行実行し、プラグインはライブラリ内の相対パスのみを使用して、他のファイルに触れることはできません。ライブラリ内のファイルをシステムのフォルダで表示したり、システムの名前を付けて保存ダイアログを開いてコピー先を選ばせることもできます。キャンセルすれば何もコピーされません。プラグインをアンインストールしてもこのデータは削除されず、削除には Cindy 設定での個別確認が必要です。","networkHost": "ネットワークドメイン {{host}} にアクセス","networkSecret": "認証情報「{{name}}」の入力が必要","networkSecretGhostInputDetail": "この資格情報はプラグイン自身の設定画面で入力を受け付けるため、入力時にはプラグインのページを経由します。その後ホストへ一度だけ渡されて暗号化保存され、保存後はプラグインから読み出せません。注入は宣言されたドメインへのリクエスト時のみホストが行います。",@@ -4906,6 +4906,10 @@"dialogTitle": "フォルダを選択","dialogMessage": "プラグイン「{{name}}」がフォルダの選択を求めています"},+ "saveAs": {+ "dialogTitle": "プラグイン「{{name}}」名前を付けて保存",+ "dialogMessage": "プラグイン「{{name}}」がコピーの保存先選択を求めています"+ },"confirm": {"dialogTitle": "プラグイン「{{name}}」が確認を求めています"},diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 91c263ed32..84e5ecccf1 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -4686,7 +4686,7 @@"fsWrite": "파일을 쓸 수 있음(생성/수정)","fsWriteDetail": "전용 데이터 폴더에는 언제든지 쓸 수 있습니다. 현재 세션의 작업 디렉터리 쓰기는 세션의 권한 모드를 따릅니다(자동 승인 모드에서는 바로 쓰고, 개별 확인 모드에서는 먼저 승인을 요청합니다). 그 외 폴더에 쓰려면 매번 확인이 필요합니다. 파일은 항상 호스트가 대신 기록하며 플러그인 자체는 파일 시스템에 직접 접근할 수 없습니다.","libraryPersist": "영구 라이브러리 사용 가능(대용량 파일 및 데이터베이스)",- "libraryPersistDetail": "Cindy가 관리하는 독립 저장 공간을 받아 작업 데이터(캔버스, 이미지, 데이터베이스 등)를 저장하며, 일반 플러그인 데이터 할당량 제한을 받지 않습니다. 파일과 데이터베이스 작업은 모두 호스트가 대신 실행하고 플러그인은 라이브러리 내 상대 경로만 사용하여 다른 파일에는 접근할 수 없습니다. 플러그인을 제거해도 이 데이터는 삭제되지 않으며, 삭제는 Cindy 설정에서 별도 확인이 필요합니다.",+ "libraryPersistDetail": "Cindy가 관리하는 독립 저장 공간을 받아 작업 데이터(캔버스, 이미지, 데이터베이스 등)를 저장하며, 일반 플러그인 데이터 할당량 제한을 받지 않습니다. 파일과 데이터베이스 작업은 모두 호스트가 대신 실행하고 플러그인은 라이브러리 내 상대 경로만 사용하여 다른 파일에는 접근할 수 없습니다. 라이브러리 파일을 시스템 폴더에서 보여 주거나 시스템 다른 이름으로 저장 대화상자를 열어 복사 위치를 고르게 할 수도 있으며, 취소하면 아무 파일도 복사되지 않습니다. 플러그인을 제거해도 이 데이터는 삭제되지 않으며, 삭제는 Cindy 설정에서 별도 확인이 필요합니다.","networkHost": "네트워크 도메인 {{host}}에 접근","networkSecret": "자격 증명 \"{{name}}\" 입력 필요","networkSecretGhostInputDetail": "이 자격 증명은 플러그인 자체 설정 화면에서 입력받으므로 입력 시점에 플러그인 페이지를 거칩니다. 이후 호스트에 한 번만 전달되어 암호화 저장되며, 저장 후에는 플러그인이 다시 읽을 수 없습니다. 주입은 선언된 도메인 요청 시에만 호스트가 수행합니다.",@@ -4906,6 +4906,10 @@"dialogTitle": "폴더 선택","dialogMessage": "플러그인 \"{{name}}\"이(가) 폴더 선택을 요청합니다"},+ "saveAs": {+ "dialogTitle": "플러그인 \"{{name}}\" 다른 이름으로 저장",+ "dialogMessage": "플러그인 \"{{name}}\"이(가) 복사본 저장을 요청합니다"+ },"confirm": {"dialogTitle": "플러그인 \"{{name}}\"이(가) 확인을 요청합니다"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 69524e8aed..cdfe392d58 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -4678,7 +4678,7 @@"fsWrite": "可写入文件(创建/修改)","fsWriteDetail": "它自己的专属数据目录随时可写;当前任务的工作目录跟随任务的权限模式(免批模式直接写,逐条确认模式先征求你同意);其它目录每次都需要你确认。文件始终由主机代写,插件本身无法直接访问你的文件系统。","libraryPersist": "可使用持久作品库(大量文件与数据库)",- "libraryPersistDetail": "它会获得一个由 Cindy 管理的独立存储区,用来保存你的作品数据(如画布、图片、数据库),不受普通插件数据配额限制。文件与数据库操作全部由主机代执行,插件只能使用库内相对路径,无法触碰你的其它文件。卸载插件不会删除这些数据;删除必须在 Cindy 设置中单独确认。",+ "libraryPersistDetail": "它会获得一个由 Cindy 管理的独立存储区,用来保存你的作品数据(如画布、图片、数据库),不受普通插件数据配额限制。文件与数据库操作全部由主机代执行,插件只能使用库内相对路径,无法触碰你的其它文件。它还可以让 Cindy 在系统文件夹中显示库内文件,或弹出系统另存为窗口由你选择拷贝位置;取消则不会拷出任何文件。卸载插件不会删除这些数据;删除必须在 Cindy 设置中单独确认。","networkHost": "访问网络域名 {{host}}","networkSecret": "需要你提供凭证「{{name}}」","networkSecretGhostInputDetail": "凭证由这个插件自己的设置界面收集,录入时会经过插件页面;随后一次性交给主机加密保管,存入后插件无法读回,主机只在请求它声明的域名时注入。",@@ -4898,6 +4898,10 @@"dialogTitle": "选择文件夹","dialogMessage": "插件「{{name}}」请求你选择一个文件夹"},+ "saveAs": {+ "dialogTitle": "插件「{{name}}」另存为",+ "dialogMessage": "插件「{{name}}」请求你另存一份拷贝"+ },"confirm": {"dialogTitle": "插件「{{name}}」请你确认"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex a372e21e88..40e2658bf5 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -4678,7 +4678,7 @@"fsWrite": "可寫入檔案(建立/修改)","fsWriteDetail": "它自己的專屬資料目錄隨時可寫;當前任務的工作目錄跟隨任務的權限模式(免批模式直接寫,逐條確認模式先徵求你同意);其它目錄每次都需要你確認。檔案始終由主機代寫,插件本身無法直接訪問你的檔案系統。","libraryPersist": "可使用持久作品庫(大量檔案與資料庫)",- "libraryPersistDetail": "它會取得一個由 Cindy 管理的獨立儲存區,用來保存你的作品資料(如畫布、圖片、資料庫),不受一般插件資料配額限制。檔案與資料庫操作全部由主機代執行,插件只能使用庫內相對路徑,無法觸碰你的其它檔案。解除安裝插件不會刪除這些資料;刪除必須在 Cindy 設定中單獨確認。",+ "libraryPersistDetail": "它會取得一個由 Cindy 管理的獨立儲存區,用來保存你的作品資料(如畫布、圖片、資料庫),不受一般插件資料配額限制。檔案與資料庫操作全部由主機代執行,插件只能使用庫內相對路徑,無法觸碰你的其它檔案。它還可以讓 Cindy 在系統資料夾中顯示庫內檔案,或彈出系統另存為視窗由你選擇拷貝位置;取消則不會拷出任何檔案。解除安裝插件不會刪除這些資料;刪除必須在 Cindy 設定中單獨確認。","networkHost": "訪問網路域名 {{host}}","networkSecret": "需要你提供憑證「{{name}}」","networkSecretGhostInputDetail": "憑證由這個插件自己的設定介面收集,錄入時會經過插件頁面;隨後一次性交給主機加密保管,存入後插件無法讀回,主機只在請求它宣告的域名時注入。",@@ -4898,6 +4898,10 @@"dialogTitle": "選擇資料夾","dialogMessage": "插件「{{name}}」請求你選擇一個資料夾"},+ "saveAs": {+ "dialogTitle": "插件「{{name}}」另存為",+ "dialogMessage": "插件「{{name}}」請求你另存一份拷貝"+ },"confirm": {"dialogTitle": "插件「{{name}}」請你確認"},diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex f6faffc63a..1b09a8abd9 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -2085,7 +2085,7 @@ export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItitems.push({ key: 'fs', kind: 'fs', labelKey: 'fsWrite', detailKey: 'fsWriteDetail' });}// library 能力:持久作品库(用户数据语义,不是临时缓存)。详情页必须讲清- // 三件事:卸载不删、删除走独立确认、数据库只收参数化语句。+ // 卸载不删、删除走独立确认,以及会打开系统文件夹/另存为对话框。if (manifest.library === true) {items.push({key: 'library',@@ -8246,6 +8246,8 @@ export const GHOST_LIBRARY_OPS = ['db.backup','db.check','db.userVersion',+ 'reveal',+ 'saveAs',] as const;export type GhostLibraryOp = (typeof GHOST_LIBRARY_OPS)[number];@@ -8285,6 +8287,8 @@ export interface GhostPipeLibraryRequest {/** read 分段。 */offset?: number;length?: number;+ /** saveAs: 另存为建议文件名(仅 basename)。 */+ name?: string;}/**@@ -8342,6 +8346,10 @@ export type GhostPipeLibraryResult =| { ok: true; op: 'db.backup'; backedUp: boolean }| { ok: true; op: 'db.check'; healthy: boolean; detail: string }| { ok: true; op: 'db.userVersion'; version: number | null }+ | { ok: true; op: 'reveal'; path: string }+ | { ok: true; op: 'saveAs'; cancelled: true }+ /** saveAs 成功:path 是库内相对键(与请求相同),不是用户另存到的绝对路径。 */+ | { ok: true; op: 'saveAs'; cancelled: false; path: string; bytes: number }| { ok: false; errorCode: string; message: string };/** Library 概览(ghosts:library-overview IPC 载荷;设置页插件详情消费)。 */diff --git a/docs/dev-rules/plugin-library-storage.md b/docs/dev-rules/plugin-library-storage.mdindex bd5aca2cf1..63094eac5f 100644--- a/docs/dev-rules/plugin-library-storage.md+++ b/docs/dev-rules/plugin-library-storage.md@@ -79,7 +79,7 @@ backups)对插件不可达——路径语法段首不许点,协议层天然## Review 清单-1. 路径/SQL 是否仍只经白名单与相对键?有没有新的绝对路径出口?+1. 路径/SQL 是否仍只经白名单与相对键?有没有新的绝对路径出口?(saveAs 成功 path 必须是库内相对键,不得把用户另存目标送进沙箱)2. 失败路径是否保持「不可用 ≠ 空」「任一步失败原位原样」?3. 生命周期挂点(uninstall/setEnabled/owner 边界)是否补了对应的 dispose?4. i18n 五语与中文标点门禁、FORGE_GUIDE §4.10.1 是否同步?