Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): extraDirs 按 library opener 挂槽,握手跟实写走 (#3906)

Praisef817dab05107
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index fedfaa24ac..77bb3d0353 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -270,12 +270,13 @@ describe('session runtime control wiring', () => {
expect(syncLibrary).toContain('targets.add(focused)');
expect(syncLibrary).toContain('sessionIsRemote(sessionId)');
expect(syncLibrary).toContain('!remote && grantRoot && sessionId === focused ? grantRoot : null');
- expect(syncLibrary).toContain("throw new Error('library extraDirs sync superseded')");
+ expect(syncLibrary).toContain("return 'superseded'");
+ expect(syncLibrary).not.toContain("throw new Error('library extraDirs sync superseded')");
expect(syncLibrary).toContain("throw new Error('library extraDirs not granted to focused session')");
expect(syncLibrary).toContain('if (!remote && nextRoot && sessionId === focused) throw error');
expect(syncLibrary).toContain('libraryExtraDirSyncChain.then(run, run)');
expect(syncLibrary).toMatch(
- /await applyLibraryReadonlyExtraDir\(sessionId, nextRoot\);[\s\S]*if \(generation !== libraryExtraDirSyncGeneration\)/,
+ /await applyLibraryReadonlyExtraDir\(sessionId, nextRoot\);[\s\S]*if \(generation !== libraryExtraDirSyncGeneration\) return 'superseded'/,
);
expect(extraDirs).toContain('!isLibraryExtraDirSlot(dir)');
expect(extraDirs).not.toContain('splitExtraDirSlots(persisted)');
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/libraryExtraDirGrantContract.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/libraryExtraDirGrantContract.test.ts
new file mode 100644
index 0000000000..b9b8f3638a
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/libraryExtraDirGrantContract.test.ts
@@ -0,0 +1,37 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+describe('library extraDirs grant wiring', () => {
+ const mainSource = readFileSync(
+ resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),
+ 'utf8',
+ ).replace(/\r\n/g, '\n');
+
+ const start = mainSource.indexOf('export type LibraryExtraDirSyncResult');
+ const end = mainSource.indexOf('\nlet previewSlotSingleton:', start);
+ const body = mainSource.slice(start, end);
+
+ it('picks an enabled library-capable ghost instead of a hardcoded mivo id', () => {
+ expect(start).toBeGreaterThan(-1);
+ expect(end).toBeGreaterThan(start);
+ expect(body).toContain('function isLibraryCapableGhost(');
+ expect(body).toContain('libraryExtraDirOwnerGhostId');
+ expect(body).toContain('ghost.manifest.library === true');
+ expect(body).toContain('const ownerId = libraryExtraDirOwnerGhostId;');
+ expect(body).not.toContain('availableGhosts().find((ghost) => isLibraryCapableGhost(ghost))');
+ expect(body).not.toContain('function selectLibraryCapableGhost(');
+ expect(body).not.toContain("findAvailableGhost('xd-mivo')");
+ expect(body).not.toContain("findAvailableGhost('cindy-mivo')");
+ expect(body).not.toContain('MIVO_LIBRARY_GHOST_IDS');
+ });
+
+ it('slot sync refuses to no-op-success when the opener is not library-capable', () => {
+ expect(body).toContain('async function syncMivoLibraryExtraDirFromSlot(');
+ expect(body).toContain('if (root !== null && !isLibraryCapableGhost(findAvailableGhost(ghostId)))');
+ expect(body).toContain('if (libraryExtraDirOwnerGhostId !== null && libraryExtraDirOwnerGhostId !== ghostId)');
+ expect(body).toContain("if (result === 'granted') libraryExtraDirOwnerGhostId = ghostId;");
+ expect(body).toContain('return result;');
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
index bfa8037df4..a7de810788 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
@@ -20,12 +20,12 @@ import type { InstalledGhost } from '../../../shared/ghost.js';
const Ctor = Database as unknown as SqliteDatabaseConstructor;
const GHOST_ID = 'mivo-canvas';
-function makeGhost(library: boolean, enabled = true): InstalledGhost {
+function makeGhost(library: boolean, enabled = true, id = GHOST_ID): InstalledGhost {
return {
manifest: {
schemaVersion: 3,
minCindyVersion: '0.1.61',
- id: GHOST_ID,
+ id,
name: '测试意识',
version: '1.0.0',
kind: 'chip',
@@ -44,6 +44,7 @@ describe('GhostLibrarySlot', () => {
let bindingFile: string;
let candidate: string;
let scopeKey: string | null = 'local:owner-a:1';
+ let ghosts: Map<string, InstalledGhost>;
let ghost: InstalledGhost;
let slot: GhostLibrarySlot;
let bindingStore: LibraryBindingStore;
@@ -60,13 +61,14 @@ describe('GhostLibrarySlot', () => {
clock = 0;
await fs.promises.mkdir(candidate, { recursive: true });
ghost = makeGhost(true);
+ ghosts = new Map([[GHOST_ID, ghost]]);
bindingStore = new LibraryBindingStore({
getFile: () => bindingFile,
getManagedRoots: () => [path.join(tmp, 'managed')],
getDefaultRoot: (id) => path.join(defaultRootBase, id),
});
const deps: GhostLibrarySlotDeps = {
- getGhost: (id) => (id === GHOST_ID ? ghost : null),
+ getGhost: (id) => ghosts.get(id) ?? null,
bindingStore,
getDefaultRoot: (id) => path.join(defaultRootBase, id),
captureOwnerScope: () => scopeKey,
@@ -97,14 +99,14 @@ describe('GhostLibrarySlot', () => {
});
it('资格审:未声明 library 能力/停用 → NOT_DECLARED', async () => {
- ghost = makeGhost(false);
+ ghosts.set(GHOST_ID, makeGhost(false));
const r = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
expect(r.ok).toBe(false);
if (!r.ok) expect(r.errorCode).toBe('NOT_DECLARED');
- ghost = makeGhost(true, false);
+ ghosts.set(GHOST_ID, makeGhost(true, false));
const r2 = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
expect(r2.ok).toBe(false);
- ghost = makeGhost(true);
+ ghosts.set(GHOST_ID, makeGhost(true));
});
it('管道级全链路:open/status/write/read/rename/delete(默认根)', async () => {
@@ -512,13 +514,120 @@ describe('GhostLibrarySlot', () => {
});
it('extraDirs 同步失败则握手 authorizedReadonly=false,不假装授权', async () => {
- syncAgentReadonlyExtraDir.mockRejectedValueOnce(new Error('require app-server 0.144.6 or newer'));
+ syncAgentReadonlyExtraDir.mockRejectedValue(new Error('require app-server 0.144.6 or newer'));
const open = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
if (!open.ok || open.op !== 'open') throw new Error(JSON.stringify(open));
expect((open as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(false);
expect(JSON.stringify(open)).not.toContain(defaultRootBase);
});
+ it('extraDirs 同步 no-op/未实写则握手 authorizedReadonly=false,不假装授权', async () => {
+ syncAgentReadonlyExtraDir.mockResolvedValue('not-granted');
+ const open = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ if (!open.ok || open.op !== 'open') throw new Error(JSON.stringify(open));
+ expect((open as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(false);
+ expect(JSON.stringify(open)).not.toContain(defaultRootBase);
+ expect(syncAgentReadonlyExtraDir).toHaveBeenCalledWith(
+ GHOST_ID,
+ path.join(defaultRootBase, GHOST_ID),
+ );
+ });
+
+ it('extraDirs 后来实写成功,status 握手改为 authorizedReadonly=true', async () => {
+ syncAgentReadonlyExtraDir.mockResolvedValue('not-granted');
+ const open = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ expect((open as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(false);
+ syncAgentReadonlyExtraDir.mockResolvedValue('granted');
+ const st = await slot.handleLibraryRequest(GHOST_ID, { op: 'status' });
+ expect((st as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(true);
+ });
+
+ it('extraDirs 被更新一轮取代时,已授权握手不回退成 false', async () => {
+ const open = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ expect((open as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(true);
+ syncAgentReadonlyExtraDir.mockResolvedValueOnce('superseded');
+ const st = await slot.handleLibraryRequest(GHOST_ID, { op: 'status' });
+ expect((st as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(true);
+ });
+
+ it('A 已授权后 B 被 superseded,B 不得把 A 的根当成自己已授权', async () => {
+ const otherId = 'other-library';
+ ghosts.set(otherId, makeGhost(true, true, otherId));
+ const openA = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ expect((openA as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(true);
+ syncAgentReadonlyExtraDir.mockResolvedValue('superseded');
+ const openB = await slot.handleLibraryRequest(otherId, { op: 'open' });
+ expect((openB as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(false);
+ const stA = await slot.handleLibraryRequest(GHOST_ID, { op: 'status' });
+ expect((stA as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(true);
+ });
+
+ it('A granted 后 B granted,A 被 superseded 不得再报已授权', async () => {
+ const otherId = 'other-library';
+ ghosts.set(otherId, makeGhost(true, true, otherId));
+ const openA = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ expect((openA as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(true);
+ syncAgentReadonlyExtraDir.mockResolvedValue('granted');
+ const openB = await slot.handleLibraryRequest(otherId, { op: 'open' });
+ expect((openB as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(true);
+ syncAgentReadonlyExtraDir.mockResolvedValue('superseded');
+ const stA = await slot.handleLibraryRequest(GHOST_ID, { op: 'status' });
+ expect((stA as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(false);
+ const stB = await slot.handleLibraryRequest(otherId, { op: 'status' });
+ expect((stB as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(true);
+ });
+
+ it('B granted 后 A 漂移 open 不得撤掉 B 的槽', async () => {
+ const otherId = 'other-library';
+ ghosts.set(otherId, makeGhost(true, true, otherId));
+ syncAgentReadonlyExtraDir.mockResolvedValue('granted');
+ const openB = await slot.handleLibraryRequest(otherId, { op: 'open' });
+ expect((openB as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(true);
+ const store = new LibraryBindingStore({
+ getFile: () => bindingFile,
+ getManagedRoots: () => [path.join(tmp, 'managed')],
+ getDefaultRoot: (id) => path.join(defaultRootBase, id),
+ });
+ await store.setBinding(GHOST_ID, candidate);
+ await fs.promises.rm(candidate, { recursive: true });
+ syncAgentReadonlyExtraDir.mockClear();
+ const openA = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ expect((openA as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(false);
+ expect(syncAgentReadonlyExtraDir).not.toHaveBeenCalled();
+ const stB = await slot.handleLibraryRequest(otherId, { op: 'status' });
+ expect((stB as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(true);
+ });
+
+ it('仅 status 不挂 extraDirs;A open 后 B status 不得抢槽', async () => {
+ const first = await slot.handleLibraryRequest(GHOST_ID, { op: 'status' });
+ expect((first as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(false);
+ expect(syncAgentReadonlyExtraDir).not.toHaveBeenCalled();
+
+ const otherId = 'other-library';
+ ghosts.set(otherId, makeGhost(true, true, otherId));
+ const openA = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ expect((openA as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(true);
+ syncAgentReadonlyExtraDir.mockClear();
+ const stB = await slot.handleLibraryRequest(otherId, { op: 'status' });
+ expect((stB as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(false);
+ expect(syncAgentReadonlyExtraDir).not.toHaveBeenCalled();
+ const stA = await slot.handleLibraryRequest(GHOST_ID, { op: 'status' });
+ expect((stA as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(true);
+ });
+
+ it('B granted 后 A dispose 不得撤掉 B 的槽', async () => {
+ const otherId = 'other-library';
+ ghosts.set(otherId, makeGhost(true, true, otherId));
+ syncAgentReadonlyExtraDir.mockResolvedValue('granted');
+ const openB = await slot.handleLibraryRequest(otherId, { op: 'open' });
+ expect((openB as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(true);
+ syncAgentReadonlyExtraDir.mockClear();
+ await slot.disposeGhost(GHOST_ID);
+ expect(syncAgentReadonlyExtraDir).not.toHaveBeenCalled();
+ const stB = await slot.handleLibraryRequest(otherId, { op: 'status' });
+ expect((stB as unknown as { authorizedReadonly: boolean }).authorizedReadonly).toBe(true);
+ });
+
it('writeCommit ACK 含 64-hex sha256,形状 {ok,op,path,bytes,sha256}', async () => {
const body = 'pixel-bytes';
const sha = createHash('sha256').update(body).digest('hex');
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 8013835cfb..a6b65422e5 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -3167,12 +3167,15 @@ export function setGhostWorkspaceSessionService(service: WorkspaceSessionService
getGhostWorkspaceSlot().setSessionService(service);
}
-const MIVO_LIBRARY_GHOST_IDS = new Set(['xd-mivo', 'cindy-mivo']);
-let libraryExtraDirSync: ((root: string | null) => Promise<void>) | null = null;
+export type LibraryExtraDirSyncResult = 'granted' | 'not-granted' | 'superseded';
+type LibraryExtraDirSyncFn = (root: string | null) => Promise<LibraryExtraDirSyncResult>;
+let libraryExtraDirSync: LibraryExtraDirSyncFn | null = null;
+/** 最近一次成功把库根写入 extraDirs 的插件;焦点刷新只复用它,不抓清单第一个。 */
+let libraryExtraDirOwnerGhostId: string | null = null;
/** maker-ipc 注入:把 library 根同步进当前 Mivo 会话 extraDirs。cindy-brain 不反向依赖 register。 */
export function setGhostLibraryExtraDirSync(
- sync: ((root: string | null) => Promise<void>) | null,
+ sync: LibraryExtraDirSyncFn | null,
): void {
libraryExtraDirSync = sync;
}
@@ -3181,6 +3184,20 @@ export function getFocusedGhostSessionId(): string | null {
return ghostSessionFocusTracker.current();
}
+/** 已启用且声明 library 能力。不得用写死的 xd-mivo/cindy-mivo 白名单顶替。 */
+function isLibraryCapableGhost(ghost: InstalledGhost | null | undefined): ghost is InstalledGhost {
+ return Boolean(ghost && ghost.enabled !== false && ghost.manifest.library === true);
+}
+
+async function resolveLibraryCapableRoot(ghostId: string): Promise<string | null> {
+ if (!isLibraryCapableGhost(findAvailableGhost(ghostId))) return null;
+ const resolution = await getGhostLibraryBindingStore().resolveLibraryRoot(ghostId);
+ if (resolution.kind === 'custom' && resolution.root === null) return null;
+ return resolution.kind === 'custom' && resolution.root !== null
+ ? resolution.root
+ : ownerScopedUserDataPath('libraries', ghostId);
+}
+
async function refreshMivoLibraryExtraDirGrant(): Promise<void> {
if (!libraryExtraDirSync) return;
const focused = ghostSessionFocusTracker.current();
@@ -3188,26 +3205,42 @@ async function refreshMivoLibraryExtraDirGrant(): Promise<void> {
await libraryExtraDirSync(null);
return;
}
- const ghost = findAvailableGhost('xd-mivo') ?? findAvailableGhost('cindy-mivo');
- if (!ghost || ghost.enabled === false || ghost.manifest.library !== true) {
- await libraryExtraDirSync(null);
- return;
- }
- const ghostId = ghost.manifest.id;
- const resolution = await getGhostLibraryBindingStore().resolveLibraryRoot(ghostId);
- if (resolution.kind === 'custom' && resolution.root === null) {
+ const ownerId = libraryExtraDirOwnerGhostId;
+ const root = ownerId ? await resolveLibraryCapableRoot(ownerId) : null;
+ if (!root) {
+ libraryExtraDirOwnerGhostId = null;
await libraryExtraDirSync(null);
return;
}
- const root = resolution.kind === 'custom' && resolution.root !== null
- ? resolution.root
- : ownerScopedUserDataPath('libraries', ghostId);
await libraryExtraDirSync(root);
}
-function syncMivoLibraryExtraDirFromSlot(ghostId: string, root: string | null): Promise<void> {
- if (!MIVO_LIBRARY_GHOST_IDS.has(ghostId) || !libraryExtraDirSync) return Promise.resolve();
- return libraryExtraDirSync(root);
+/**
+ * 槽侧同步:认发起 open 的那个 ghost,不抓清单里第一个 library 插件。
+ * root 非空时必须 library 资格审过,否则不得 no-op 成功。
+ * 撤槽(root=null)只允许当前 owner;别人撤槽不得把唯一槽拆了。
+ * granted = 已把该库根写入 extraDirs;not-granted = 确定没挂上;
+ * superseded = 被更新一轮取代,不等于把已挂上的槽拆了。
+ */
+async function syncMivoLibraryExtraDirFromSlot(
+ ghostId: string,
+ root: string | null,
+): Promise<LibraryExtraDirSyncResult> {
+ if (!libraryExtraDirSync) return 'not-granted';
+ if (root !== null && !isLibraryCapableGhost(findAvailableGhost(ghostId))) {
+ return 'not-granted';
+ }
+ if (root === null) {
+ if (libraryExtraDirOwnerGhostId !== null && libraryExtraDirOwnerGhostId !== ghostId) {
+ return 'not-granted';
+ }
+ const result = await libraryExtraDirSync(null);
+ if (result !== 'superseded') libraryExtraDirOwnerGhostId = null;
+ return result === 'superseded' ? 'superseded' : 'not-granted';
+ }
+ const result = await libraryExtraDirSync(root);
+ if (result === 'granted') libraryExtraDirOwnerGhostId = ghostId;
+ return result;
}
let previewSlotSingleton: GhostPreviewSlot | null = null;
diff --git a/apps/desktop/src/main/cindy-brain/librarySlot.ts b/apps/desktop/src/main/cindy-brain/librarySlot.ts
index 794314cdfe..2d403830dc 100644
--- a/apps/desktop/src/main/cindy-brain/librarySlot.ts
+++ b/apps/desktop/src/main/cindy-brain/librarySlot.ts
@@ -73,6 +73,7 @@ export function libraryAvailableRef(input: {
/** 单插件的库会话(vault + sql 绑定到同一根与 owner scope)。 */
interface GhostLibrarySession {
+ ghostId: string;
vault: LibraryVault;
sql: LibrarySqlService;
/** 会话创建时捕获的 owner scope key;每请求比对,变了就整会话作废。 */
@@ -114,8 +115,13 @@ export interface GhostLibrarySlotDeps {
/**
* 库根 realpath 变化后同步当前 Mivo 会话 extraDirs。
* root 为 null 则撤槽。失败只记日志,不挡 library 主路径。
+ * 返回 granted = extraDirs 已挂上该库根;not-granted = 确定没挂上;
+ * superseded = 被更新一轮取代,不等于拆槽。void 仅留给旧单测 mock。
*/
- syncAgentReadonlyExtraDir?(ghostId: string, root: string | null): Promise<void>;
+ syncAgentReadonlyExtraDir?(
+ ghostId: string,
+ root: string | null,
+ ): Promise<boolean | 'granted' | 'not-granted' | 'superseded' | void>;
}
const fail = (errorCode: string, message: string): GhostPipeLibraryResult => ({ ok: false, errorCode, message });
@@ -130,8 +136,13 @@ export class GhostLibrarySlot {
private readonly lastSaveAsAttemptAt = new Map<string, number>();
/** 全局另存为对话框在场标记(系统弹窗一次一个,不排队)。 */
private saveAsDialogInFlight = false;
- /** extraDirs 注入成功才握手 authorizedReadonly,失败走 cindy-media 备胎。 */
- private extraDirGranted = false;
+ /**
+ * extraDirs 注入成功才握手 authorizedReadonly。系统槽同一时刻只有一个根,
+ * 所以只记当前 {ghostId, root};别人挂上或撤槽成功都要清掉这份记录。
+ */
+ private extraDirGrant: { ghostId: string; root: string } | null = null;
+ /** 最近一次显式 open 的插件;status 只给它复挂,别人 status 不得抢槽。 */
+ private extraDirOpenerGhostId: string | null = null;
constructor(private readonly deps: GhostLibrarySlotDeps) {}
@@ -192,8 +203,8 @@ export class GhostLibrarySlot {
const resolution = await this.deps.bindingStore.resolveLibraryRoot(ghostId);
session = this.createSession(ghostId, resolution, scopeKey);
this.sessions.set(ghostId, session);
- // 会话建立即自动 open(幂等):消除"write 前忘 open"的脚枪;显式 open
- // 操作仍有效,仅回状态。
+ // 会话建立即自动 open vault(幂等):消除"write 前忘 open"的脚枪。
+ // extraDirs 只在显式 open 时挂,status / 首次任意请求不得抢槽。
if (session.drift === null) {
await session.vault.open();
// 重装自愈:能走到这里 = 插件已装入且启用,清掉卸载时留的 orphaned
@@ -201,8 +212,7 @@ export class GhostLibrarySlot {
if (session.vault.getMeta()?.orphaned) {
await session.vault.clearOrphaned().catch(() => {});
}
- await this.syncAgentReadonlyExtraDir(ghostId, session.vault.getRootDir());
- } else {
+ } else if (this.extraDirGrant?.ghostId === ghostId) {
await this.syncAgentReadonlyExtraDir(ghostId, null);
}
}
@@ -263,6 +273,7 @@ export class GhostLibrarySlot {
const generation = record?.generation ?? 0;
const identity = record ? `g${generation}` : 'default';
return {
+ ghostId,
vault,
sql,
ownerScopeKey: scopeKey,
@@ -273,6 +284,11 @@ export class GhostLibrarySlot {
};
}
+ private isExtraDirGrantedFor(ghostId: string, root: string | null): boolean {
+ if (root === null || this.extraDirGrant === null) return false;
+ return this.extraDirGrant.ghostId === ghostId && this.extraDirGrant.root === root;
+ }
+
/** open/status 握手:已授权只读布尔 + 库代次/身份。谁问谁得,不回绝对路径。 */
private handshakeFields(
session: GhostLibrarySession,
@@ -280,22 +296,53 @@ export class GhostLibrarySlot {
): { authorizedReadonly: boolean; libraryGeneration: number; libraryIdentity: string } {
return {
authorizedReadonly:
- this.extraDirGranted && session.drift === null && (state === 'ready' || state === 'readonly'),
+ this.isExtraDirGrantedFor(session.ghostId, session.vault.getRootDir())
+ && session.drift === null
+ && (state === 'ready' || state === 'readonly'),
libraryGeneration: session.generation,
libraryIdentity: session.identity,
};
}
+ private rememberExtraDirGrant(ghostId: string, root: string): void {
+ this.extraDirGrant = { ghostId, root };
+ }
+
+ private clearExtraDirGrant(ghostId?: string): void {
+ if (ghostId === undefined || this.extraDirGrant?.ghostId === ghostId) {
+ this.extraDirGrant = null;
+ }
+ }
+
private async syncAgentReadonlyExtraDir(ghostId: string, root: string | null): Promise<void> {
if (!this.deps.syncAgentReadonlyExtraDir) {
- this.extraDirGranted = root !== null;
+ if (root === null) this.clearExtraDirGrant(ghostId);
+ else this.rememberExtraDirGrant(ghostId, root);
return;
}
try {
- await this.deps.syncAgentReadonlyExtraDir(ghostId, root);
- this.extraDirGranted = root !== null;
+ const granted = await this.deps.syncAgentReadonlyExtraDir(ghostId, root);
+ if (root === null) {
+ if (granted === 'superseded') return;
+ this.clearExtraDirGrant(ghostId);
+ return;
+ }
+ if (granted === true || granted === 'granted') {
+ this.rememberExtraDirGrant(ghostId, root);
+ return;
+ }
+ if (granted === 'superseded') {
+ this.deps.log?.warn('library extraDirs sync superseded', { ghostId });
+ return;
+ }
+ if (granted === false || granted === 'not-granted') {
+ this.clearExtraDirGrant(ghostId);
+ return;
+ }
+ // void:单测 mock 没回结果时,按 root 非空视为已实写。
+ this.rememberExtraDirGrant(ghostId, root);
} catch (error) {
- this.extraDirGranted = false;
+ this.clearExtraDirGrant(ghostId);
this.deps.log?.warn('library extraDirs sync failed', {
ghostId,
error: error instanceof Error ? error.message : String(error),
@@ -309,7 +356,10 @@ export class GhostLibrarySlot {
this.sessions.delete(ghostId);
await session.sql.dispose().catch(() => {});
await session.vault.invalidate().catch(() => {});
- await this.syncAgentReadonlyExtraDir(ghostId, null);
+ if (this.extraDirGrant?.ghostId === ghostId) {
+ await this.syncAgentReadonlyExtraDir(ghostId, null);
+ }
+ if (this.extraDirOpenerGhostId === ghostId) this.extraDirOpenerGhostId = null;
}
/** 停用/卸载/owner 切换收口:作废全部会话(commit 5 的生命周期接线点)。 */
@@ -404,6 +454,8 @@ export class GhostLibrarySlot {
case 'open': {
const r = await vault.open();
if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };
+ this.extraDirOpenerGhostId = ghostId;
+ await this.syncAgentReadonlyExtraDir(ghostId, vault.getRootDir());
const body = {
ok: true as const, op: 'open' as const, state: r.state, reason: r.reason ?? undefined,
usedBytes: r.usedBytes, fileCount: r.fileCount, location: session.locationKind,
@@ -413,6 +465,9 @@ export class GhostLibrarySlot {
case 'status': {
const r = await vault.status();
if (!r.ok) return { ok: false, errorCode: r.errorCode, message: r.message };
+ if (this.extraDirOpenerGhostId === ghostId) {
+ await this.syncAgentReadonlyExtraDir(ghostId, vault.getRootDir());
+ }
const body = {
ok: true as const, op: 'status' as const, state: r.state, reason: r.reason ?? undefined,
usedBytes: r.usedBytes, fileCount: r.fileCount,
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 56b9b0aded..da29aa7feb 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -3051,33 +3051,25 @@ let libraryExtraDirSyncGeneration = 0;
let libraryExtraDirSyncRoot: string | null = null;
let libraryExtraDirSyncChain: Promise<void> = Promise.resolve();
-async function syncLibraryReadonlyExtraDir(root: string | null): Promise<void> {
+async function syncLibraryReadonlyExtraDir(
+ root: string | null,
+): Promise<'granted' | 'not-granted' | 'superseded'> {
libraryExtraDirSyncRoot = root;
const generation = ++libraryExtraDirSyncGeneration;
- const run = async () => {
- if (generation !== libraryExtraDirSyncGeneration) {
- throw new Error('library extraDirs sync superseded');
- }
+ const run = async (): Promise<'granted' | 'not-granted' | 'superseded'> => {
+ if (generation !== libraryExtraDirSyncGeneration) return 'superseded';
const grantRoot = libraryExtraDirSyncRoot;
const focused = getFocusedGhostSessionId();
- if (generation !== libraryExtraDirSyncGeneration) {
- throw new Error('library extraDirs sync superseded');
- }
+ if (generation !== libraryExtraDirSyncGeneration) return 'superseded';
const visible = await listVisibleActiveSessionIds();
- if (generation !== libraryExtraDirSyncGeneration) {
- throw new Error('library extraDirs sync superseded');
- }
+ if (generation !== libraryExtraDirSyncGeneration) return 'superseded';
const targets = new Set(visible);
if (focused) targets.add(focused);
let granted = false;
for (const sessionId of targets) {
- if (generation !== libraryExtraDirSyncGeneration) {
- throw new Error('library extraDirs sync superseded');
- }
+ if (generation !== libraryExtraDirSyncGeneration) return 'superseded';
const remote = await sessionIsRemote(sessionId);
- if (generation !== libraryExtraDirSyncGeneration) {
- throw new Error('library extraDirs sync superseded');
- }
+ if (generation !== libraryExtraDirSyncGeneration) return 'superseded';
const nextRoot = !remote && grantRoot && sessionId === focused ? grantRoot : null;
try {
await applyLibraryReadonlyExtraDir(sessionId, nextRoot);
@@ -3089,17 +3081,16 @@ async function syncLibraryReadonlyExtraDir(root: string | null): Promise<void> {
});
if (!remote && nextRoot && sessionId === focused) throw error;
}
- if (generation !== libraryExtraDirSyncGeneration) {
- throw new Error('library extraDirs sync superseded');
- }
+ if (generation !== libraryExtraDirSyncGeneration) return 'superseded';
}
if (grantRoot && !granted) {
throw new Error('library extraDirs not granted to focused session');
}
+ return grantRoot && granted ? 'granted' : 'not-granted';
};
const queued = libraryExtraDirSyncChain.then(run, run);
libraryExtraDirSyncChain = queued.then(() => undefined, () => undefined);
- await queued;
+ return queued;
}
let agentInputCoordinatorHolder: AgentInputCoordinator | null = null;