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(plugins): 修复 0.1.105 作品库读写变慢与重装后作品库变空 (#5967)

fattycatc950b504649f
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index eac71b102e..adb394927c 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -289,6 +289,11 @@ export interface GhostManagerOptions {
namespace: string | null;
packageSha256: string | null;
}) => { pluginId: string } | null;
+ /**
+ * Market evidence that a bare-id library left by an organization install
+ * removed before the registry existed belongs to this organization plugin.
+ */
+ canReclaimLegacyBareInstance?: (input: { ghostId: string; namespace: string; pluginId: string }) => boolean;
canResumePendingResidentOffline?: (ghostId: string) => boolean;
onResumePendingResidentOffline?: (ghost: InstalledGhost) => void;
preparePendingResidentForMigration?: (ghostId: string) => Promise<boolean>;
@@ -596,6 +601,21 @@ export function ghostManifestHostUnsupportedReason(raw: unknown): string | null
* - **卸载防御**:id 先过格式校验(shared/ghost 同一份规则),再确认
* 目标是 rootDir 的直接子目录,杜绝借 id 删任意路径。
*/
+/**
+ * The bare key is free when no record holds it. A user-confirmed reattach may
+ * also replace an inactive record that never belonged to an organization.
+ */
+function canTakeBareKey(
+ registry: PluginInstanceRegistry,
+ ghostId: string,
+ allowInactiveRootHolder: boolean,
+): boolean {
+ const holders = Object.values(registry.instances).filter((record) =>
+ record.instanceKey === ghostId || record.contentRelId === ghostId);
+ if (holders.length === 0) return true;
+ return allowInactiveRootHolder && holders.every((record) => !record.active && record.namespace === null);
+}
+
export class GhostManager {
private readonly receiptStore: GhostInstallReceiptStore;
private readonly retirements = new FeatureRetirementStore(() => this.receiptStore.rootDir());
@@ -797,6 +817,7 @@ export class GhostManager {
namespace: string | null,
source?: PluginInstanceSource,
pluginId?: string | null,
+ userConfirmedBareReclaim = false,
):
| { kind: 'blocked'; reason: string }
| { kind: 'ok'; instanceKey: string; relId: string } {
@@ -810,10 +831,59 @@ export class GhostManager {
}
const reusable = findReusableInstance(registry, { ghostId, namespace, source, pluginId });
if (reusable) return { kind: 'ok', instanceKey: reusable.instanceKey, relId: reusable.contentRelId };
+ // The same organization plugin takes the bare key back, so its leftover
+ // library opens again: by market evidence, or because the user said so.
+ if (namespace !== null && source === 'market' && pluginId &&
+ canTakeBareKey(registry, ghostId, userConfirmedBareReclaim) &&
+ (userConfirmedBareReclaim ||
+ this.options.canReclaimLegacyBareInstance?.({ ghostId, namespace, pluginId }) === true)) {
+ return { kind: 'ok', instanceKey: ghostId, relId: ghostId };
+ }
}
return { kind: 'ok', instanceKey, relId };
}
+ /**
+ * Whether the library left under the bare id may move to an installed
+ * instance in this namespace. `in-use` means an install still runs under the
+ * bare id (for example the local copy), so its library is not left behind.
+ * A record of another organization never gives the bare id away. The caller
+ * asks the user.
+ */
+ bareLibraryOffer(ghostId: string, namespace: string | null): 'available' | 'in-use' | 'unavailable' {
+ this.ensureCurrentOwnerContextSync();
+ const registry = this.syncInstanceRegistry();
+ if (this.instanceRegistryService.isBlocked()) return 'unavailable';
+ const holders = Object.values(registry.instances).filter((record) =>
+ record.instanceKey === ghostId || record.contentRelId === ghostId);
+ if (holders.some((record) => !record.active && record.namespace !== null && record.namespace !== namespace)) {
+ return 'unavailable';
+ }
+ if (holders.some((record) => record.active)) return 'in-use';
+ try {
+ return fs.lstatSync(this.contentPath(ghostId), { throwIfNoEntry: false }) === undefined ? 'available' : 'in-use';
+ } catch {
+ return 'unavailable';
+ }
+ }
+
+ /**
+ * Whether an organization market install could take the bare key if the
+ * user confirms. No evidence is checked here; the caller asks the user.
+ */
+ canOfferBareReclaim(ghostId: string, namespace: string, pluginId: string): boolean {
+ this.ensureCurrentOwnerContextSync();
+ const registry = this.syncInstanceRegistry();
+ if (this.instanceRegistryService.isBlocked()) return false;
+ if (findReusableInstance(registry, { ghostId, namespace, source: 'market', pluginId })) return false;
+ if (!canTakeBareKey(registry, ghostId, true)) return false;
+ try {
+ return fs.lstatSync(this.contentPath(ghostId), { throwIfNoEntry: false }) === undefined;
+ } catch {
+ return false;
+ }
+ }
+
/**
* Pending is only the upgrade census. A missing ledger means this process
* has not recorded the census yet, so bare directories present now are it.
@@ -2439,7 +2509,33 @@ export class GhostManager {
list(): InstalledGhost[] {
this.ensureCurrentOwnerContextSync();
this.syncInstanceRegistry();
- const listedDirs = this.listContentEntries();
+ const result = this.projectListedEntries(this.listContentEntries());
+ result.sort((a, b) => a.manifest.id.localeCompare(b.manifest.id));
+ return result;
+ }
+
+ /**
+ * One active instance by its registry key, projected exactly as list() does
+ * but without rescanning every install. Undefined means the cached registry
+ * cannot answer, so the caller must fall back to list().
+ */
+ findInstalledInstance(instanceKey: string): InstalledGhost | undefined {
+ this.ensureCurrentOwnerContextSync();
+ if (this.instanceRegistryService.isBlocked()) return undefined;
+ const record = this.instanceRegistryService.current()?.instances[instanceKey];
+ if (!record?.active || !isValidPluginInstallRelId(record.contentRelId)) return undefined;
+ let dir: string;
+ try {
+ dir = this.contentPath(record.contentRelId);
+ if (classifyGhostDirEntrySync(dir) !== 'directory') return undefined;
+ } catch {
+ return undefined;
+ }
+ const [ghost] = this.projectListedEntries([{ relId: record.contentRelId, dir }]);
+ return ghost && installedGhostStoragePart(ghost) === instanceKey ? ghost : undefined;
+ }
+
+ private projectListedEntries(listedDirs: Array<{ relId: string; dir: string }>): InstalledGhost[] {
const result: InstalledGhost[] = [];
for (const listed of listedDirs) {
const { relId, dir } = listed;
@@ -2568,7 +2664,6 @@ export class GhostManager {
...(identity.namespace === null && this.options.isTrustedBundledId?.(identity.ghostId) ? { builtin: true } : {}),
});
}
- result.sort((a, b) => a.manifest.id.localeCompare(b.manifest.id));
return result;
}
@@ -3350,6 +3445,8 @@ export class GhostManager {
registrySource?: PluginInstanceSource;
pluginId?: string | null;
namespace?: string | null;
+ /** The user agreed to reattach the library left under the bare id. */
+ reclaimLegacyBareInstance?: boolean;
/** Synchronous live-authority check immediately before publishing the staged package. */
beforePackagePlacement?: () => void;
},
@@ -3369,6 +3466,8 @@ export class GhostManager {
registrySource?: PluginInstanceSource;
pluginId?: string | null;
namespace?: string | null;
+ /** The user agreed to reattach the library left under the bare id. */
+ reclaimLegacyBareInstance?: boolean;
beforePackagePlacement?: () => void;
},
): Promise<{ ghost: InstalledGhost } | { rejection: InstallRejection }> {
@@ -3410,7 +3509,7 @@ export class GhostManager {
const registrySource = opts?.registrySource ??
(opts?.installOrigin === 'agent-forge' ? 'agent-forge' : 'manual');
const placement = this.planInstancePlacement(
- manifest.id, identity.namespace, registrySource, opts?.pluginId,
+ manifest.id, identity.namespace, registrySource, opts?.pluginId, opts?.reclaimLegacyBareInstance === true,
);
if (placement.kind === 'blocked') {
return { rejection: { code: 'already-installed', reason: placement.reason } };
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts
index 02beb6fcba..1ffe05dcfd 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts
@@ -34,7 +34,8 @@ function harness() {
blobUrl: (hash, ext) => 'cindy-media://blobs/' + hash + ext });
const api = load({ availableGhosts: () => ghosts, findInstalledGhostByInstanceId, resolveInstalledGhost,
installedGhostPhysicalKeys,
- requireGhostAvailableForActiveSession: vi.fn(), getGhostManager: () => ({ setEnabled }),
+ requireGhostAvailableForActiveSession: vi.fn(), getGhostManager: () => ({ setEnabled,
+ findInstalledInstance: (key: string) => ghosts.find((ghost) => installedGhostStoragePart(ghost) === key) }),
beginGhostMutation: () => vi.fn(), captureGhostMutationOwner: vi.fn(),
getGhostNodeRuntimeBroker: () => ({ stop }), getGhostSubscriptionGateway: () => ({ dropGhost: vi.fn() }),
getGhostErrandSlot: () => ({ clearGhost: vi.fn() }),
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostProductionCallbacksFixture.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostProductionCallbacksFixture.ts
index 7936233d8c..711831abef 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostProductionCallbacksFixture.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostProductionCallbacksFixture.ts
@@ -12,8 +12,26 @@ const productionIdentityDeps = {
installedGhostStoragePart,
isPluginInstanceKey,
resolvePluginInstanceQuery,
+ libraryRestartRequiredReason: (): string | null => null,
};
+/**
+ * findGhostForInstanceId reads an exact instance key straight from the
+ * manager. Tests that inject availableGhosts get the same answer from it.
+ */
+function instanceLookupDeps(deps: Record<string, unknown>): Record<string, unknown> {
+ const availableGhosts = deps.availableGhosts as (() => Array<Parameters<typeof installedGhostStoragePart>[0]>) | undefined;
+ if (!availableGhosts) return {};
+ return {
+ isAppSessionBoundaryPending: () => false,
+ isGhostAvailableForActiveSession: () => true,
+ getGhostManager: () => ({
+ findInstalledInstance: (key: string) =>
+ availableGhosts().find((ghost) => installedGhostStoragePart(ghost) === key),
+ }),
+ };
+}
+
const source = fs.readFileSync(new URL('../index.ts', import.meta.url), 'utf8');
const ast = ts.createSourceFile('index.ts', source, ts.ScriptTarget.Latest, true);
@@ -61,7 +79,7 @@ export function createGhostProductionCallbacks<Result>(options: {
{ compilerOptions: { target: ts.ScriptTarget.ES2022 } },
).outputText;
return (deps) => {
- const merged = { ...productionIdentityDeps, ...deps };
+ const merged = { ...productionIdentityDeps, ...instanceLookupDeps(deps), ...deps };
return new Function(
'deps', 'const {' + Object.keys(merged).join(',') + '} = deps;' + compiled +
';return {' + names.join(',') + '};',
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostProtocolTargetLookup.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostProtocolTargetLookup.test.ts
new file mode 100644
index 0000000000..96be6d0287
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostProtocolTargetLookup.test.ts
@@ -0,0 +1,187 @@
+/**
+ * cindy-ghost:// 请求的目标复核(#5983):每个面板资源请求前后各复核一次目标,
+ * /wake 也要查一次。用生产里接到协议 handler 的回调 + 真实 GhostManager,
+ * 装多个插件,断言稳定注册后的目标请求只读目标实例,不因其他插件做全量扫描;
+ * 同时守住实例隔离和失效语义。
+ */
+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 { ghostPartition, ghostWebviewEntryPaths, type InstalledGhost } from '../../../shared/ghost.js';
+import { installedGhostMutationTargetToken } from '../../../shared/pluginIdentity.js';
+import { GhostManager, type GhostManagerOptions } from '../GhostManager.js';
+import { runGhostSnapshotWorkerRequest } from '../ghostSnapshotWorkerProcess.js';
+import { ownerScopedGhostPartitionForInstalledGhost, resolveGhostWebviewPartitionClaim } from '../ghostWebviewPartition.js';
+import { writeTestCindyPackage } from './cindyPackageFixture.js';
+import { createGhostProductionCallbacks } from './ghostProductionCallbacksFixture.js';
+
+type TargetStore = {
+ captureTarget(ghostId: string): string | null;
+ isTargetCurrent(ghostId: string, expectedTarget: string | null): boolean;
+};
+type WakeHandler = (ghostId: string) => Promise<{ state: string }>;
+type AttachResolver = (partitionClaim: unknown, src: unknown) => { ghost: InstalledGhost } | null;
+
+const TARGET = '_ns__acme__canvas';
+const OTHER_PLUGINS = 12;
+
+const mutateSnapshot: NonNullable<GhostManagerOptions['mutateSnapshot']> = async ({ parentDir, ...request }) => {
+ await runGhostSnapshotWorkerRequest(request, parentDir);
+};
+
+let workDir: string;
+let manager: GhostManager;
+let owner: string;
+
+async function packageFor(id: string, withPanel = false): Promise<string> {
+ return writeTestCindyPackage(path.join(workDir, `${id}-${Date.now()}-${Math.random()}.cindy`), {
+ schemaVersion: 2,
+ id,
+ name: id,
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: withPanel ? ['tool', 'panel'] : ['tool'],
+ tools: [{ name: 'do_thing', description: 'do' }],
+ ...(withPanel ? { panel: { html: 'panel.html' } } : {}),
+ }, { 'main.js': '// ok\n', ...(withPanel ? { 'panel.html': '<!doctype html>' } : {}) });
+}
+
+async function installTarget(): Promise<void> {
+ await expect(manager.install(await packageFor('canvas', true), {
+ namespace: 'acme', registrySource: 'market', pluginId: 'plugin-canvas',
+ })).resolves.toMatchObject({ ghost: { instanceKey: TARGET } });
+}
+
+const session = { mode: 'cloud' as const, dataOwnerId: 'owner-a', generation: 1 };
+
+function productionCallbacks(
+ spawn = vi.fn(async () => ({ ok: true, state: 'running' })),
+ libraryRestartRequiredReason: (id: string) => string | null = () => null,
+) {
+ const callbacks = createGhostProductionCallbacks<{
+ store: TargetStore;
+ wake: WakeHandler;
+ resolveGhostWebviewAttach: AttachResolver;
+ }>({
+ functions: ['availableGhosts', 'findGhostForInstanceId', 'ghostInstallMutationTargetFor', 'resolveGhostWebviewAttach'],
+ callbacks: { store: ['setGhostKvStore'], wake: ['setGhostWakeHandler'] },
+ })({
+ getGhostManager: () => manager,
+ isAppSessionBoundaryPending: () => false,
+ isGhostAvailableForActiveSession: () => true,
+ activeOwnerScopeKey: () => owner,
+ installedGhostMutationTargetToken,
+ runtime: { stateOf: () => 'off', spawn },
+ getActiveAppSession: () => session,
+ resolveGhostWebviewPartitionClaim,
+ ownerScopedGhostPartitionForInstalledGhost,
+ ghostWebviewEntryPaths,
+ GHOST_SCHEME: 'cindy-ghost',
+ ensureGhostProtocolRegistered: vi.fn(),
+ libraryRestartRequiredReason,
+ });
+ return { ...callbacks, spawn };
+}
+
+beforeEach(async () => {
+ workDir = fs.realpathSync.native(await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-protocol-target-')));
+ manager = new GhostManager({ getRootDir: () => path.join(workDir, 'ghosts'), mutateSnapshot });
+ owner = 'owner-a';
+ for (let index = 0; index < OTHER_PLUGINS; index += 1) {
+ const id = `other-${index}`;
+ await manager.install(await packageFor(id), index % 2 === 0
+ ? {}
+ : { namespace: 'acme', registrySource: 'market', pluginId: `plugin-${id}` });
+ }
+ await manager.install(await packageFor('canvas'));
+ await installTarget();
+ manager.list();
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await fs.promises.rm(workDir, { recursive: true, force: true });
+});
+
+describe('cindy-ghost:// target lookup', () => {
+ it('rechecks a registered panel target without rescanning the other installed plugins', async () => {
+ const { store, wake, spawn } = productionCallbacks();
+ const expected = store.captureTarget(TARGET);
+ expect(expected).not.toBeNull();
+ const list = vi.spyOn(manager, 'list');
+ const readdir = vi.spyOn(fs, 'readdirSync');
+ // A panel open loads dozens of static files; each request checks its
+ // target before it runs and again before it answers.
+ for (let request = 0; request < 40; request += 1) {
+ expect(store.isTargetCurrent(TARGET, expected)).toBe(true);
+ expect(store.isTargetCurrent(TARGET, expected)).toBe(true);
+ }
+ expect(store.captureTarget(TARGET)).toBe(expected);
+ await expect(wake(TARGET)).resolves.toEqual({ state: 'running' });
+ expect(spawn).toHaveBeenCalledWith(expect.objectContaining({ instanceKey: TARGET }));
+ expect(list).not.toHaveBeenCalled();
+ expect(readdir).not.toHaveBeenCalled();
+ });
+
+ it('rechecks a panel on every click and key press without rescanning the other installed plugins', () => {
+ const { resolveGhostWebviewAttach } = productionCallbacks();
+ const claim = ghostPartition(TARGET);
+ expect(resolveGhostWebviewAttach(claim, 'cindy-ghost://canvas/panel.html')?.ghost.instanceKey).toBe(TARGET);
+ const list = vi.spyOn(manager, 'list');
+ for (let gesture = 0; gesture < 40; gesture += 1) {
+ expect(resolveGhostWebviewAttach(claim, 'cindy-ghost://canvas/panel.html')).not.toBeNull();
+ }
+ expect(resolveGhostWebviewAttach(claim, 'cindy-ghost://canvas/other.html')).toBeNull();
+ expect(list).not.toHaveBeenCalled();
+ });
+
+ it('does not attach a panel the host holds stopped until restart', () => {
+ const { resolveGhostWebviewAttach } = productionCallbacks(undefined, (id) => (id === TARGET ? 'restart' : null));
+ expect(resolveGhostWebviewAttach(ghostPartition(TARGET), 'cindy-ghost://canvas/panel.html')).toBeNull();
+ });
+
+ it('keeps the root and organization instances of the same plugin apart', () => {
+ const { store } = productionCallbacks();
+ const rootKey = manager.list().find((ghost) => ghost.manifest.id === 'canvas' && ghost.instanceKey !== TARGET)?.instanceKey;
+ expect(rootKey).toBeDefined();
+ const organization = store.captureTarget(TARGET);
+ const root = store.captureTarget(rootKey!);
+ expect(root).not.toBeNull();
+ expect(root).not.toBe(organization);
+ expect(store.isTargetCurrent(rootKey!, organization)).toBe(false);
+ expect(store.isTargetCurrent(TARGET, root)).toBe(false);
+ // The bare plugin id names two installs, so it opens neither.
+ expect(store.captureTarget('canvas')).toBeNull();
+ });
+
+ it('rejects an old target after uninstall, reinstall or an account switch, and accepts the current one', async () => {
+ const { store, wake } = productionCallbacks();
+ const before = store.captureTarget(TARGET);
+ owner = 'owner-b';
+ expect(store.isTargetCurrent(TARGET, before)).toBe(false);
+ owner = 'owner-a';
+ expect(store.isTargetCurrent(TARGET, before)).toBe(true);
+
+ await expect(manager.uninstall('_ns/acme/canvas', { notify: false })).resolves.toEqual({ ok: true });
+ expect(store.captureTarget(TARGET)).toBeNull();
+ expect(store.isTargetCurrent(TARGET, before)).toBe(false);
+ await expect(wake(TARGET)).resolves.toEqual({ state: 'off' });
+
+ await installTarget();
+ const after = store.captureTarget(TARGET);
+ expect(after).not.toBeNull();
+ expect(after).not.toBe(before);
+ expect(store.isTargetCurrent(TARGET, before)).toBe(false);
+ expect(store.isTargetCurrent(TARGET, after)).toBe(true);
+ });
+
+ it('still resolves a bare plugin id through the full list', () => {
+ const { store } = productionCallbacks();
+ const list = vi.spyOn(manager, 'list');
+ expect(store.captureTarget('other-0')).not.toBeNull();
+ expect(list).toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/libraryBinding.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/libraryBinding.test.ts
index 2e5b0b7ca0..2a914d84fa 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/libraryBinding.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/libraryBinding.test.ts
@@ -368,6 +368,17 @@ describe('LibraryBindingStore', () => {
expect(await relocateLibraryMetaOwner(path.join(defaultRootBase, 'missing'), 'hello', '_ns__acme__hello')).toBe(false);
});
+ it('clears the uninstall marker when asked, including on a repeat after the owner already moved', async () => {
+ const root = path.join(defaultRootBase, 'hello');
+ const file = path.join(root, '.cindy-library', 'meta.json');
+ await fs.promises.mkdir(path.dirname(file), { recursive: true });
+ await fs.promises.writeFile(file, JSON.stringify({ version: 1, ghostId: '_ns__acme__hello', createdAt: 1, orphaned: { at: 2, name: 'old' } }));
+ const options = { clearOrphaned: true };
+ expect(await relocateLibraryMetaOwner(root, 'hello', '_ns__acme__hello', () => {}, options)).toBe(true);
+ expect(JSON.parse(await fs.promises.readFile(file, 'utf8'))).toEqual({ version: 1, ghostId: '_ns__acme__hello', createdAt: 1 });
+ expect(await relocateLibraryMetaOwner(root, 'hello', '_ns__acme__hello', () => {}, options)).toBe(false);
+ });
+
it('无 binding → 默认根;绑定后解析到 <candidate>/<ghostId>', async () => {
const store = new LibraryBindingStore(deps);
const before = await store.resolveLibraryRoot(GHOST_ID);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/libraryLegacyReattach.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/libraryLegacyReattach.test.ts
new file mode 100644
index 0000000000..60bfc7927b
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/libraryLegacyReattach.test.ts
@@ -0,0 +1,441 @@
+import { createHash } from 'node:crypto';
+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 { relocateLibraryMetaOwner } from '../libraryBinding.js';
+import { LibraryStagingStore, relocateLibraryStagingOwner } from '../libraryStaging.js';
+import {
+ finishLegacyLibraryReattach,
+ LibrarySwapNeedsRestartError,
+ readLegacyLibraryReattachJournal,
+ relocateOrAdoptLibraryMeta,
+ startLegacyLibraryReattach,
+ withPluginHeldForLibrarySwap,
+ type LegacyLibraryReattachDeps,
+ type PluginHoldForLibrarySwapDeps,
+} from '../libraryLegacyReattach.js';
+
+const FROM = 'xd-mivo-canvas';
+const TO = '_ns__xd__xd-mivo-canvas';
+
+let root: string;
+
+beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-library-reattach-'));
+});
+
+afterEach(() => {
+ fs.rmSync(root, { recursive: true, force: true });
+});
+
+function plantLibrary(dir: string, ghostId: string, marker: string): void {
+ fs.mkdirSync(path.join(dir, '.cindy-library'), { recursive: true });
+ fs.writeFileSync(
+ path.join(dir, '.cindy-library', 'meta.json'),
+ JSON.stringify({ version: 1, ghostId, createdAt: 1, orphaned: { at: 1, name: 'Mivo Canvas' } }),
+ );
+ fs.writeFileSync(path.join(dir, 'marker.txt'), marker);
+}
+
+function readMeta(dir: string): { ghostId: string } {
+ return JSON.parse(fs.readFileSync(path.join(dir, '.cindy-library', 'meta.json'), 'utf8')) as { ghostId: string };
+}
+
+function deps(overrides: Partial<LegacyLibraryReattachDeps> = {}): LegacyLibraryReattachDeps {
+ return {
+ journalFile: () => path.join(root, 'library-reattach.json'),
+ defaultRoot: (id) => path.join(root, 'libraries', id),
+ stagingRoot: (id) => path.join(root, 'library-staging', id),
+ trashRoot: () => path.join(root, 'libraries-trash'),
+ relocateCustomBinding: async () => {},
+ assertCustomBindingRelocatable: async () => {},
+ customRoot: async () => null,
+ relocateMeta: async (dir, fromId, toId) => {
+ await relocateLibraryMetaOwner(dir, fromId, toId);
+ },
+ relocateStaging: async (dir, fromId, toId) => {
+ await relocateLibraryMetaOwner(dir, fromId, toId);
+ },
+ assertCurrent: () => {},
+ ...overrides,
+ };
+}
+
+function plantDefaultPair(): void {
+ plantLibrary(path.join(root, 'libraries', FROM), FROM, 'old');
+ plantLibrary(path.join(root, 'libraries', TO), TO, 'new');
+ plantLibrary(path.join(root, 'library-staging', FROM), FROM, 'old-staging');
+ plantLibrary(path.join(root, 'library-staging', TO), TO, 'new-staging');
+}
+
+function expectReattached(): void {
+ const library = path.join(root, 'libraries', TO);
+ expect(fs.readFileSync(path.join(library, 'marker.txt'), 'utf8')).toBe('old');
+ expect(readMeta(library).ghostId).toBe(TO);
+ expect(fs.existsSync(path.join(root, 'libraries', FROM))).toBe(false);
+ const staging = path.join(root, 'library-staging', TO);
+ expect(fs.readFileSync(path.join(staging, 'marker.txt'), 'utf8')).toBe('old-staging');
+ expect(readMeta(staging).ghostId).toBe(TO);
+ const trash = path.join(root, 'libraries-trash', `${TO}-7-replaced`);
+ expect(fs.readFileSync(path.join(trash, 'marker.txt'), 'utf8')).toBe('new');
+ expect(fs.readFileSync(path.join(`${trash}-staging`, 'marker.txt'), 'utf8')).toBe('new-staging');
+ expect(fs.existsSync(path.join(root, 'library-reattach.json'))).toBe(false);
+}
+
+describe('legacy library reattach', () => {
+ it('moves the current library to the trash and puts the old one in its place', async () => {
+ plantDefaultPair();
+ await startLegacyLibraryReattach({ fromId: FROM, toId: TO, oldLocation: 'default', now: 7 }, deps());
+ expectReattached();
+ });
+
+ it('reattaches when the current instance never created a library', async () => {
+ plantLibrary(path.join(root, 'libraries', FROM), FROM, 'old');
+ await startLegacyLibraryReattach({ fromId: FROM, toId: TO, oldLocation: 'default', now: 7 }, deps());
+ expect(readMeta(path.join(root, 'libraries', TO)).ghostId).toBe(TO);
+ expect(fs.existsSync(path.join(root, 'libraries-trash'))).toBe(false);
+ });
+
+ it.each(Array.from({ length: 10 }, (_, index) => index + 1))(
+ 'finishes from the journal after stopping at check %i',
+ async (stopAt) => {
+ plantDefaultPair();
+ let checks = 0;
+ const interrupted = deps({
+ assertCurrent: () => {
+ checks += 1;
+ if (checks === stopAt) throw new Error('stopped');
+ },
+ });
+ await expect(startLegacyLibraryReattach(
+ { fromId: FROM, toId: TO, oldLocation: 'default', now: 7 },
+ interrupted,
+ )).rejects.toThrow('stopped');
+ const journal = await readLegacyLibraryReattachJournal(path.join(root, 'library-reattach.json'));
+ if (journal) await finishLegacyLibraryReattach(journal, deps());
+ if (stopAt <= 3) {
+ // Stopped before the journal was written: nothing moved.
+ expect(journal).toBeNull();
+ expect(fs.readFileSync(path.join(root, 'libraries', TO, 'marker.txt'), 'utf8')).toBe('new');
+ return;
+ }
+ expectReattached();
+ },
+ );
+
+ it('does not trash a different library that took the current place', async () => {
+ plantDefaultPair();
+ await expect(startLegacyLibraryReattach(
+ { fromId: FROM, toId: TO, oldLocation: 'default', now: 7 },
+ deps({ assertCurrent: (() => {
+ let checks = 0;
+ return () => {
+ checks += 1;
+ if (checks === 4) throw new Error('stopped');
+ };
+ })() }),
+ )).rejects.toThrow('stopped');
+ const current = path.join(root, 'libraries', TO);
+ // Keep the original inode alive so the replacement cannot reuse it.
+ fs.renameSync(current, path.join(root, 'moved-away'));
+ plantLibrary(current, TO, 'replacement');
+ const journal = await readLegacyLibraryReattachJournal(path.join(root, 'library-reattach.json'));
+ await expect(finishLegacyLibraryReattach(journal!, deps())).rejects.toThrow('destination already exists');
+ expect(fs.readFileSync(path.join(current, 'marker.txt'), 'utf8')).toBe('replacement');
+ expect(fs.readFileSync(path.join(root, 'libraries', FROM, 'marker.txt'), 'utf8')).toBe('old');
+ });
+
+ it('refuses to start another reattach while one is unfinished', async () => {
+ fs.writeFileSync(path.join(root, 'library-reattach.json'), JSON.stringify({
+ version: 1, fromId: FROM, toId: TO, oldLocation: 'default', newLibrary: null, newStaging: null, trashName: 'x',
+ }));
+ await expect(startLegacyLibraryReattach(
+ { fromId: FROM, toId: TO, oldLocation: 'default', now: 7 },
+ deps(),
+ )).rejects.toThrow('unfinished');
+ });
+
+ it('lets the binding store move a library at a custom location', async () => {
+ const custom = path.join(root, 'custom');
+ plantLibrary(path.join(custom, FROM), FROM, 'old');
+ const relocateCustomBinding = vi.fn(async (fromId: string, toId: string) => {
+ fs.renameSync(path.join(custom, fromId), path.join(custom, toId));
+ });
+ await startLegacyLibraryReattach({ fromId: FROM, toId: TO, oldLocation: 'custom', now: 7 }, deps({
+ relocateCustomBinding,
+ customRoot: async (id) => path.join(custom, id),
+ }));
+ expect(relocateCustomBinding).toHaveBeenCalledWith(FROM, TO);
+ expect(readMeta(path.join(custom, TO)).ghostId).toBe(TO);
+ });
+
+ it('flushes every moved directory and identity before removing the journal', async () => {
+ plantDefaultPair();
+ const order: string[] = [];
+ const journal = path.join(root, 'library-reattach.json');
+ await startLegacyLibraryReattach({ fromId: FROM, toId: TO, oldLocation: 'default', now: 7 }, deps({
+ syncDirectory: async (dir) => {
+ order.push((fs.existsSync(journal) ? 'before:' : 'after:') + path.relative(root, dir));
+ },
+ }));
+ expect(order).toEqual([
+ 'before:libraries-trash',
+ 'before:libraries',
+ 'before:library-staging',
+ `before:${path.join('libraries', TO, '.cindy-library')}`,
+ `before:${path.join('library-staging', TO, '.cindy-library')}`,
+ 'after:',
+ ]);
+ expectReattached();
+ });
+
+ it('keeps the journal when the account switches while the moves are flushed', async () => {
+ plantDefaultPair();
+ const ownJournal = path.join(root, 'library-reattach.json');
+ const otherJournal = path.join(root, 'other-account', 'library-reattach.json');
+ fs.mkdirSync(path.dirname(otherJournal), { recursive: true });
+ fs.writeFileSync(otherJournal, 'other account');
+ let switched = false;
+ await expect(startLegacyLibraryReattach({ fromId: FROM, toId: TO, oldLocation: 'default', now: 7 }, deps({
+ journalFile: () => (switched ? otherJournal : ownJournal),
+ assertCurrent: () => {
+ if (switched) throw new Error('owner changed');
+ },
+ syncDirectory: async () => {
+ switched = true;
+ },
+ }))).rejects.toThrow('owner changed');
+ expect(fs.existsSync(ownJournal)).toBe(true);
+ expect(fs.readFileSync(otherJournal, 'utf8')).toBe('other account');
+ });
+
+ it('stops before moving anything when the custom destination is already taken', async () => {
+ plantDefaultPair();
+ const custom = path.join(root, 'custom');
+ plantLibrary(path.join(custom, FROM), FROM, 'old');
+ fs.mkdirSync(path.join(custom, TO));
+ const relocateCustomBinding = vi.fn(async () => {});
+ await expect(startLegacyLibraryReattach({ fromId: FROM, toId: TO, oldLocation: 'custom', now: 7 }, deps({
+ relocateCustomBinding,
+ assertCustomBindingRelocatable: async (_fromId, toId) => {
+ if (fs.existsSync(path.join(custom, toId))) throw new Error('library custom root destination already exists');
+ },
+ customRoot: async (id) => path.join(custom, id),
+ }))).rejects.toThrow('destination already exists');
+ expect(relocateCustomBinding).not.toHaveBeenCalled();
+ expect(fs.existsSync(path.join(root, 'library-reattach.json'))).toBe(false);
+ expect(fs.readFileSync(path.join(root, 'libraries', TO, 'marker.txt'), 'utf8')).toBe('new');
+ });
+
+ it('stops before moving anything when the old custom library is unavailable', async () => {
+ plantDefaultPair();
+ const relocateCustomBinding = vi.fn(async () => {});
+ await expect(startLegacyLibraryReattach({ fromId: FROM, toId: TO, oldLocation: 'custom', now: 7 }, deps({
+ relocateCustomBinding,
+ customRoot: async (id) => path.join(root, 'unmounted', id),
+ }))).rejects.toThrow();
+ expect(relocateCustomBinding).not.toHaveBeenCalled();
+ expect(fs.existsSync(path.join(root, 'library-reattach.json'))).toBe(false);
+ expect(fs.readFileSync(path.join(root, 'libraries', TO, 'marker.txt'), 'utf8')).toBe('new');
+ });
+
+ it('treats an existing trash target as done, even if directory identity cannot tell the libraries apart', async () => {
+ plantDefaultPair();
+ await startLegacyLibraryReattach({ fromId: FROM, toId: TO, oldLocation: 'default', now: 7 }, deps());
+ // A volume without inode numbers reports the same identity for every
+ // directory; make the recorded identity match the reattached library.
+ const stat = fs.lstatSync(path.join(root, 'libraries', TO));
+ const stagingStat = fs.lstatSync(path.join(root, 'library-staging', TO));
+ await finishLegacyLibraryReattach({
+ version: 1, fromId: FROM, toId: TO, oldLocation: 'default',
+ newLibrary: { dev: stat.dev, ino: stat.ino },
+ newStaging: { dev: stagingStat.dev, ino: stagingStat.ino },
+ trashName: `${TO}-7-replaced`,
+ }, deps());
+ expectReattached();
+ });
+
+ it.each([
+ ['a path in fromId', { fromId: '../outside' }],
+ ['a path in toId', { toId: '../../outside' }],
+ ['a parent trash name', { trashName: '..' }],
+ ])('rejects a journal with %s', async (_label, change) => {
+ fs.writeFileSync(path.join(root, 'library-reattach.json'), JSON.stringify({
+ version: 1, fromId: FROM, toId: TO, oldLocation: 'default', newLibrary: null, newStaging: null, trashName: 'x',
+ ...change,
+ }));
+ await expect(readLegacyLibraryReattachJournal(path.join(root, 'library-reattach.json'))).rejects.toThrow('invalid');
+ });
+});
+
+describe('staging tasks during a reattach', () => {
+ const OWNER_SCOPE = 'local:owner-a:1';
+
+ function stagingStore(dir: string, ghostId: string): LibraryStagingStore {
+ return new LibraryStagingStore({
+ rootDir: dir, ghostId, ownerScopeKey: OWNER_SCOPE,
+ captureOwnerScope: () => OWNER_SCOPE, getDiskFreeBytes: async () => 1024 ** 4,
+ });
+ }
+
+ async function beginUpload(store: LibraryStagingStore, taskId: string, body: string): Promise<string> {
+ const bytes = Buffer.from(body);
+ const begin = await store.begin({
+ ghostId: FROM, taskId, sourceRevision: 'rev-1', totalBytes: bytes.byteLength,
+ sha256: createHash('sha256').update(bytes).digest('hex'), mime: 'image/png',
+ recovery: { sceneId: 's1', nodeId: 'n1' },
+ });
+ if (!begin.ok) throw new Error(JSON.stringify(begin));
+ const chunk = await store.chunk({
+ ghostId: FROM, stagingId: begin.stagingId, seq: 1, content: bytes.toString('base64'), encoding: 'base64',
+ });
+ if (!chunk.ok) throw new Error(JSON.stringify(chunk));
+ return begin.stagingId;
+ }
+
+ function taskOwners(dir: string): string[] {
+ const tasks = path.join(dir, 'tasks');
+ return fs.readdirSync(tasks).flatMap((id) => ['manifest.json', 'intent.json']
+ .map((name) => path.join(tasks, id, name))
+ .filter((file) => fs.existsSync(file))
+ .map((file) => (JSON.parse(fs.readFileSync(file, 'utf8')) as { ghostId: string }).ghostId));
+ }
+
+ it('finishes rewriting upload tasks after stopping with only some of them moved', async () => {
+ plantLibrary(path.join(root, 'libraries', FROM), FROM, 'old');
+ const oldStaging = path.join(root, 'library-staging', FROM);
+ const store = stagingStore(oldStaging, FROM);
+ const durable = await beginUpload(store, 'durable', 'pixel-bytes');
+ expect((await store.commit({ ghostId: FROM, stagingId: durable })).ok).toBe(true);
+ await beginUpload(store, 'unfinished-1', 'pending-1');
+ await beginUpload(store, 'unfinished-2', 'pending-2');
+ await store.dispose();
+
+ const newStaging = path.join(root, 'library-staging', TO);
+ let stopped = false;
+ const relocateStaging = async (dir: string, fromId: string, toId: string): Promise<void> => {
+ await relocateLibraryStagingOwner(dir, fromId, toId, OWNER_SCOPE, () => {
+ const owners = taskOwners(newStaging);
+ if (!stopped && owners.includes(TO) && owners.includes(FROM)) {
+ stopped = true;
+ throw new Error('stopped');
+ }
+ });
+ };
+ await expect(startLegacyLibraryReattach(
+ { fromId: FROM, toId: TO, oldLocation: 'default', now: 7 },
+ deps({ relocateStaging }),
+ )).rejects.toThrow('stopped');
+ expect(new Set(taskOwners(newStaging))).toEqual(new Set([FROM, TO]));
+
+ const journal = await readLegacyLibraryReattachJournal(path.join(root, 'library-reattach.json'));
+ await finishLegacyLibraryReattach(journal!, deps({ relocateStaging }));
+ expect(new Set(taskOwners(newStaging))).toEqual(new Set([TO]));
+ const restored = stagingStore(newStaging, TO);
+ expect(await restored.list({ ghostId: TO })).toMatchObject({
+ ok: true, items: [expect.objectContaining({ stagingId: durable })],
+ });
+ expect(await restored.read({ ghostId: TO, stagingId: durable })).toMatchObject({
+ ok: true, content: Buffer.from('pixel-bytes').toString('base64'),
+ });
+ await restored.dispose();
+ });
+});
+
+describe('library without host identity', () => {
+ it('gets the new owner written in, and a rerun keeps it', async () => {
+ const library = path.join(root, 'libraries', FROM);
+ fs.mkdirSync(path.join(library, 'store'), { recursive: true });
+ fs.writeFileSync(path.join(library, 'store', 'canvas.json'), '{}');
+ const relocate = vi.fn(async (dir: string, fromId: string, toId: string) => {
+ await relocateLibraryMetaOwner(dir, fromId, toId);
+ });
+ await relocateOrAdoptLibraryMeta(library, FROM, TO, relocate, 9);
+ expect(readMeta(library)).toMatchObject({ ghostId: TO, createdAt: 9 });
+ expect(relocate).not.toHaveBeenCalled();
+ await relocateOrAdoptLibraryMeta(library, FROM, TO, relocate, 10);
+ expect(relocate).toHaveBeenCalledTimes(1);
+ expect(readMeta(library)).toMatchObject({ ghostId: TO, createdAt: 9 });
+ });
+
+ it('writes the identity on a rerun that stopped after the identity folder was made', async () => {
+ const library = path.join(root, 'libraries', FROM);
+ fs.mkdirSync(path.join(library, '.cindy-library'), { recursive: true });
+ fs.writeFileSync(path.join(library, '.cindy-library', 'meta.json.leftover.tmp'), '{');
+ const relocate = vi.fn(async () => {});
+ await relocateOrAdoptLibraryMeta(library, FROM, TO, relocate, 9);
+ expect(relocate).not.toHaveBeenCalled();
+ expect(readMeta(library)).toMatchObject({ ghostId: TO, createdAt: 9 });
+ });
+
+ it('relocates an existing identity instead of overwriting it', async () => {
+ const library = path.join(root, 'libraries', FROM);
+ plantLibrary(library, FROM, 'old');
+ const relocate = vi.fn(async (dir: string, fromId: string, toId: string) => {
+ await relocateLibraryMetaOwner(dir, fromId, toId);
+ });
+ await relocateOrAdoptLibraryMeta(library, FROM, TO, relocate);
+ expect(relocate).toHaveBeenCalledWith(library, FROM, TO);
+ expect(readMeta(library)).toMatchObject({ ghostId: TO, createdAt: 1 });
+ });
+});
+
+describe('plugin hold during a library swap', () => {
+ function recorder(overrides: Partial<PluginHoldForLibrarySwapDeps> = {}) {
+ const calls: string[] = [];
+ const deps: PluginHoldForLibrarySwapDeps = {
+ stopRuntime: async () => { calls.push('stop'); return { browser: true, node: false }; },
+ notifyPanels: (phase) => { calls.push('panels:' + phase); },
+ closePages: async () => { calls.push('close-pages'); },
+ holdLibraries: (on) => { calls.push(on ? 'hold' : 'release'); },
+ disposeLibraries: async () => { calls.push('dispose'); },
+ clearPartitionStorage: async () => { calls.push('clear'); },
+ restartRuntime: (running) => { calls.push('restart:' + running.browser + ':' + running.node); },
+ warn: () => { calls.push('warn'); },
+ ...overrides,
+ };
+ return { calls, deps };
+ }
+
+ it('closes old pages before the swap and again before clearing, then restores the plugin', async () => {
+ const { calls, deps } = recorder();
+ await withPluginHeldForLibrarySwap(deps, async () => { calls.push('swap'); });
+ expect(calls).toEqual([
+ 'stop', 'panels:start', 'hold', 'close-pages', 'dispose', 'swap',
+ 'close-pages', 'clear', 'release', 'restart:true:false', 'panels:done',
+ ]);
+ });
+
+ it('still clears and restores when the swap stops midway', async () => {
+ const { calls, deps } = recorder();
+ await expect(withPluginHeldForLibrarySwap(deps, async () => { throw new Error('stopped'); }))
+ .rejects.toThrow('stopped');
+ expect(calls.slice(-5)).toEqual(['close-pages', 'clear', 'release', 'restart:true:false', 'panels:done']);
+ });
+
+ it('retries a failed clear once and then restores the plugin', async () => {
+ let attempts = 0;
+ const { calls, deps } = recorder({
+ clearPartitionStorage: async () => {
+ attempts += 1;
+ if (attempts === 1) throw new Error('busy');
+ calls.push('clear');
+ },
+ });
+ await withPluginHeldForLibrarySwap(deps, async () => {});
+ expect(calls.slice(-6)).toEqual(['warn', 'close-pages', 'clear', 'release', 'restart:true:false', 'panels:done']);
+ });
+
+ it.each([
+ ['the swap finished', async () => {}],
+ ['the swap stopped midway', async () => { throw new Error('stopped'); }],
+ ])('keeps the plugin stopped and the library held when the clear keeps failing after %s', async (_label, swap) => {
+ const { calls, deps } = recorder({ clearPartitionStorage: async () => { throw new Error('busy'); } });
+ await expect(withPluginHeldForLibrarySwap(deps, swap)).rejects.toBeInstanceOf(LibrarySwapNeedsRestartError);
+ expect(calls).not.toContain('release');
+ expect(calls.some((call) => call.startsWith('restart'))).toBe(false);
+ expect(calls).not.toContain('panels:done');
+ });
+});
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 66e220b4c0..a7ae8f79eb 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/librarySlot.test.ts
@@ -77,6 +77,7 @@ describe('GhostLibrarySlot', () => {
let createVault: ReturnType<typeof vi.fn>;
let createSqlService: ReturnType<typeof vi.fn>;
let getGhost: GhostLibrarySlotDeps['getGhost'];
+ let slotDeps: GhostLibrarySlotDeps;
let clock: number;
beforeEach(async () => {
@@ -128,6 +129,7 @@ describe('GhostLibrarySlot', () => {
showSaveDialog = vi.fn(async () => ({ canceled: true }));
writeClipboardPng = vi.fn(async () => {});
syncAgentReadonlyExtraDir = vi.fn(async () => {});
+ slotDeps = deps;
slot = new GhostLibrarySlot(deps);
});
@@ -151,6 +153,33 @@ describe('GhostLibrarySlot', () => {
return { resume, started };
}
+ it('settles host preparation before a request resolves the library root', async () => {
+ let release!: () => void;
+ const prepared = new Promise<void>((resolve) => { release = resolve; });
+ await slot.disposeAll();
+ const prepareRequest = vi.fn(() => prepared);
+ slot = new GhostLibrarySlot({ ...slotDeps, prepareRequest });
+ const pending = slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
+ expect(prepareRequest).toHaveBeenCalledWith(GHOST_ID);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(resolveLibraryRoot).not.toHaveBeenCalled();
+ release();
+ await expect(pending).resolves.toMatchObject({ ok: true });
+ expect(resolveLibraryRoot).toHaveBeenCalled();
+ });
+
+ it('does not run host preparation for capability queries, invalid ops or undeclared plugins', async () => {
+ const prepareRequest = vi.fn(() => Promise.resolve());
+ await slot.disposeAll();
+ slot = new GhostLibrarySlot({ ...slotDeps, prepareRequest });
+ await expect(slot.handleLibraryRequest(GHOST_ID, { op: 'capabilities' })).resolves.toMatchObject({ ok: true });
+ await expect(slot.handleLibraryRequest(GHOST_ID, { op: 'nope' })).resolves.toMatchObject({ ok: false });
+ ghosts.set(GHOST_ID, makeGhost(false));
+ await expect(slot.handleLibraryRequest(GHOST_ID, { op: 'open' })).resolves.toMatchObject({ errorCode: 'NOT_DECLARED' });
+ await expect(slot.resolvePanelFilePath(GHOST_ID, 'a.txt')).resolves.toBeNull();
+ expect(prepareRequest).not.toHaveBeenCalled();
+ });
+
it('资格审:未声明 library 能力/停用 → NOT_DECLARED', async () => {
ghosts.set(GHOST_ID, makeGhost(false));
const r = await slot.handleLibraryRequest(GHOST_ID, { op: 'open' });
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
index f4daa40e5f..63caa98e85 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
@@ -155,7 +155,14 @@ describe('market Ghost session boundary', () => {
expect(resolverBody.match(/availableGhosts\(\)/g)).toHaveLength(1);
expect(resolverBody).toContain('resolvePluginInstanceQuery(availableGhosts(), id, namespace)');
expect(resolverBody).not.toContain('findInstalledGhostByInstanceId');
- expect(resolverBody).not.toContain('if (namespace === undefined)');
+ // The exact-key fast path fails closed at an account boundary and keeps the
+ // active-session availability filter that availableGhosts() applies.
+ const fastPathStart = resolverBody.indexOf('if (namespace === undefined) {');
+ expect(fastPathStart).toBeGreaterThanOrEqual(0);
+ const fastPath = resolverBody.slice(fastPathStart, resolverBody.indexOf('\n }', fastPathStart));
+ expect(fastPath).toContain('if (isAppSessionBoundaryPending()) return null;');
+ expect(fastPath.indexOf('isAppSessionBoundaryPending()')).toBeLessThan(fastPath.indexOf('findInstalledInstance(id)'));
+ expect(fastPath).toContain('isGhostAvailableForActiveSession(ghost.manifest.id) ? ghost : null');
expect(source.match(/getGhost: findAvailableGhost/g)?.length ?? 0).toBe(0);
expect(source.match(/getGhost: findGhostForInstanceId/g)?.length ?? 0).toBeGreaterThanOrEqual(12);
expect(resolverBody).toContain(
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts
index aa747a85d1..ca4e1426a3 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts
@@ -161,6 +161,23 @@ function rpcRequest(method = 'echo', params: unknown = { value: 1 }) {
}
describe('nodeRuntimeBroker owner boundary races', () => {
+ it('does not spawn a worker for an instance the host holds stopped until restart', async () => {
+ const ghost = fakeGhost();
+ const spawnProcess = vi.fn(() => new FakeNodeProcess() as unknown as NodeWorkerProcess);
+ const broker = new GhostNodeRuntimeBroker({
+ getGhost: () => ghost,
+ spawnProcess,
+ startBlockedReason: (id) => (id === 'node-ghost' ? 'restart Cindy' : null),
+ });
+ try {
+ await expect(broker.handleRequest('node-ghost', rpcRequest('blocked'))).resolves.toMatchObject({ ok: false });
+ await expect(broker.startForRecovery(ghost)).rejects.toThrow('restart Cindy');
+ expect(spawnProcess).not.toHaveBeenCalled();
+ } finally {
+ broker.destroyAll();
+ }
+ });
+
it('owner boundary change during startup kills the worker and fails closed', async () => {
let generation = 1;
const invalidated = vi.fn();
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.manager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.manager.test.ts
index f7ab774a19..5ca8e294b2 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.manager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.manager.test.ts
@@ -1116,6 +1116,35 @@ describe('GhostManager namespace migration census', () => {
});
+describe('single instance lookup', () => {
+ it('projects one instance exactly as list() does without rescanning', async () => {
+ await expect(manager.install(await makeCindy('hello'), {
+ namespace: 'acme', registrySource: 'market', pluginId: 'plugin-a',
+ })).resolves.toMatchObject({ ghost: { instanceKey: '_ns__acme__hello' } });
+ await expect(manager.install(await makeCindy('other'))).resolves.toMatchObject({ ghost: {} });
+ const listed = manager.list().find((ghost) => ghost.instanceKey === '_ns__acme__hello');
+ const readdir = vi.spyOn(fs, 'readdirSync');
+ try {
+ expect(manager.findInstalledInstance('_ns__acme__hello')).toEqual(listed);
+ expect(readdir).not.toHaveBeenCalled();
+ } finally {
+ readdir.mockRestore();
+ }
+ await expect(manager.setEnabled('_ns/acme/hello', false)).resolves.toEqual({ ok: true });
+ expect(manager.findInstalledInstance('_ns__acme__hello')).toMatchObject({ enabled: false });
+ });
+
+ it('leaves removed and unregistered installs to the full scan', async () => {
+ await expect(manager.install(await makeCindy('hello'), {
+ namespace: 'acme', registrySource: 'market', pluginId: 'plugin-a',
+ })).resolves.toMatchObject({ ghost: {} });
+ await expect(manager.uninstall('_ns/acme/hello', { notify: false })).resolves.toEqual({ ok: true });
+ expect(manager.findInstalledInstance('_ns__acme__hello')).toBeUndefined();
+ await plantLegacyInstall('legacy');
+ expect(manager.findInstalledInstance('legacy')).toBeUndefined();
+ });
+});
+
describe('plugin instance registry boundaries', () => {
it('uses the directory key for a new install and removes that key on uninstall', async () => {
const installed = await manager.install(await makeCindy('hello'));
@@ -1198,6 +1227,75 @@ describe('plugin instance registry boundaries', () => {
expect(fs.existsSync(path.join(rootDir, '_ns', '_root', 'hello'))).toBe(true);
});
+ it('takes back the bare key for a removed pre-registry organization install', async () => {
+ const canReclaimLegacyBareInstance = vi.fn(() => true);
+ const reclaiming = createManager({ mutateSnapshot, canReclaimLegacyBareInstance });
+ await expect(reclaiming.install(await makeCindy('hello'), {
+ namespace: 'acme', registrySource: 'market', pluginId: 'plugin-a',
+ })).resolves.toMatchObject({ ghost: { instanceKey: 'hello', namespace: 'acme' } });
+ expect(canReclaimLegacyBareInstance).toHaveBeenCalledWith({
+ ghostId: 'hello', namespace: 'acme', pluginId: 'plugin-a',
+ });
+ expect(fs.existsSync(path.join(rootDir, 'hello'))).toBe(true);
+ const registry = JSON.parse(fs.readFileSync(
+ pluginInstanceRegistryPath(path.join(workDir, 'ghosts-install-state')), 'utf8',
+ )) as { instances: Record<string, { namespace: string | null; namespaceState: string; contentRelId: string }> };
+ expect(registry.instances['hello']).toMatchObject({
+ namespace: 'acme', namespaceState: 'confirmed', contentRelId: 'hello',
+ });
+ });
+
+ it('keeps the bare key for the instance that still owns it', async () => {
+ const reclaiming = createManager({ mutateSnapshot, canReclaimLegacyBareInstance: () => true });
+ await plantLegacyInstall('hello');
+ reclaiming.list();
+ await expect(reclaiming.commitPendingNamespace('hello', null, 'explicit-root')).resolves.toEqual({ ok: true });
+ await expect(reclaiming.uninstall('hello', { notify: false })).resolves.toEqual({ ok: true });
+ await expect(reclaiming.install(await makeCindy('hello'), {
+ namespace: 'acme', registrySource: 'market', pluginId: 'plugin-a',
+ })).resolves.toMatchObject({ ghost: { instanceKey: '_ns__acme__hello' } });
+ });
+
+ it('takes the bare key from a removed local install once the user confirms', async () => {
+ await plantLegacyInstall('hello');
+ manager.list();
+ await expect(manager.commitPendingNamespace('hello', null, 'manual-after-sync')).resolves.toEqual({ ok: true });
+ expect(manager.canOfferBareReclaim('hello', 'acme', 'plugin-a')).toBe(false);
+ await expect(manager.uninstall('hello', { notify: false })).resolves.toEqual({ ok: true });
+ expect(manager.canOfferBareReclaim('hello', 'acme', 'plugin-a')).toBe(true);
+ await expect(manager.install(await makeCindy('hello'), {
+ namespace: 'acme', registrySource: 'market', pluginId: 'plugin-a', reclaimLegacyBareInstance: true,
+ })).resolves.toMatchObject({ ghost: { instanceKey: 'hello', namespace: 'acme' } });
+ const registry = JSON.parse(fs.readFileSync(
+ pluginInstanceRegistryPath(path.join(workDir, 'ghosts-install-state')), 'utf8',
+ )) as { instances: Record<string, { namespace: string | null; namespaceState: string; active: boolean }> };
+ expect(registry.instances['hello']).toMatchObject({ namespace: 'acme', namespaceState: 'confirmed', active: true });
+ });
+
+ it('never offers another organization its bare key', async () => {
+ await plantLegacyInstall('hello');
+ manager.list();
+ await expect(manager.commitPendingNamespace('hello', 'other', 'market-organization')).resolves.toEqual({ ok: true });
+ await expect(manager.uninstall('hello', { notify: false })).resolves.toEqual({ ok: true });
+ expect(manager.canOfferBareReclaim('hello', 'acme', 'plugin-a')).toBe(false);
+ await expect(manager.install(await makeCindy('hello'), {
+ namespace: 'acme', registrySource: 'market', pluginId: 'plugin-a', reclaimLegacyBareInstance: true,
+ })).resolves.toMatchObject({ ghost: { instanceKey: '_ns__acme__hello' } });
+ });
+
+ it('offers a bare-id library only while nothing installed or foreign owns the bare id', async () => {
+ expect(manager.bareLibraryOffer('hello', 'acme')).toBe('available');
+ await plantLegacyInstall('hello');
+ manager.list();
+ expect(manager.bareLibraryOffer('hello', 'acme')).toBe('in-use');
+ await expect(manager.commitPendingNamespace('hello', 'acme', 'market-organization')).resolves.toEqual({ ok: true });
+ expect(manager.bareLibraryOffer('hello', 'acme')).toBe('in-use');
+ await expect(manager.uninstall('hello', { notify: false })).resolves.toEqual({ ok: true });
+ expect(manager.bareLibraryOffer('hello', 'acme')).toBe('available');
+ expect(manager.bareLibraryOffer('hello', 'other')).toBe('unavailable');
+ expect(manager.bareLibraryOffer('hello', null)).toBe('unavailable');
+ });
+
it('records the market plugin id instead of treating the install as manual', async () => {
await expect(manager.install(await makeCindy('hello'), {
namespace: 'acme', registrySource: 'market', pluginId: 'plugin-a',
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.test.ts
index 81ac0c2057..6dec7fd627 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigration.test.ts
@@ -1,7 +1,11 @@
import { describe, expect, it, vi } from 'vitest';
import { buildUnconfirmedConfirmationEvidence } from '../pluginInstanceConfirmation.js';
-import { reconcilePendingNamespaceMigrations, stampInstanceCensus } from '../pluginNamespaceMigration.js';
+import {
+ canReclaimLegacyBareInstance,
+ reconcilePendingNamespaceMigrations,
+ stampInstanceCensus,
+} from '../pluginNamespaceMigration.js';
import { emptyPluginInstanceRegistry, type PluginInstanceRecord } from '../pluginInstanceRegistry.js';
const NOW = '2026-10-08T00:00:00.000Z';
@@ -136,3 +140,43 @@ describe('reconcilePendingNamespaceMigrations', () => {
expect(settled).toHaveBeenCalledWith('hello', true);
});
});
+
+describe('canReclaimLegacyBareInstance', () => {
+ const org = { organizationId: 'org-acme', orgSlug: 'acme' };
+ const removed = {
+ pluginId: 'plugin-a',
+ scope: 'organization' as const,
+ source: 'market' as const,
+ organizationId: 'org-acme',
+ installed: false,
+ };
+ const reclaim = (
+ records: Parameters<typeof canReclaimLegacyBareInstance>[0]['records'],
+ currentOrganization: Parameters<typeof canReclaimLegacyBareInstance>[0]['currentOrganization'] = org,
+ namespace = 'acme',
+ ) => canReclaimLegacyBareInstance({ pluginId: 'plugin-a', namespace, records, currentOrganization });
+
+ it('lets the same organization plugin take back its removed pre-namespace install', () => {
+ expect(reclaim([removed])).toBe(true);
+ expect(reclaim([{ ...removed, source: 'legacy-adopted' }])).toBe(true);
+ });
+
+ it.each([
+ ['another plugin id', [{ ...removed, pluginId: 'plugin-b' }]],
+ ['a record that is still installed', [{ ...removed, installed: true }]],
+ ['a record written after namespaces', [{ ...removed, namespace: 'acme' }]],
+ ['a root record', [{ ...removed, namespace: null }]],
+ ['a public install', [{ ...removed, scope: 'public' as const, organizationId: null }]],
+ ['a custom market install', [{ ...removed, source: 'git-market' as const }]],
+ ['another organization', [{ ...removed, organizationId: 'org-other' }]],
+ ['two records for the same plugin', [removed, { ...removed }]],
+ ])('refuses %s', (_label, records) => {
+ expect(reclaim(records)).toBe(false);
+ });
+
+ it('refuses when the current organization does not own the requested namespace', () => {
+ expect(reclaim([removed], null)).toBe(false);
+ expect(reclaim([removed], { organizationId: 'org-acme', orgSlug: null })).toBe(false);
+ expect(reclaim([removed], org, 'other')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigrationHost.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigrationHost.test.ts
index 169dec53c9..9011fadfb1 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigrationHost.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginNamespaceMigrationHost.test.ts
@@ -130,3 +130,33 @@ describe('pending resident migration host', () => {
await vi.waitFor(() => expect(reconcile).toHaveBeenCalledWith(true));
});
});
+
+describe('legacy bare instance reclaim', () => {
+ const removed = {
+ pluginId: 'plugin-a', ghostId: 'hello', releaseId: 'release-a', version: '1.0.0', sha256: 'a'.repeat(64),
+ scope: 'organization' as const, organizationId: 'org-acme', source: 'market' as const,
+ installed: false, updatedAt: '2026-10-01T00:00:00.000Z',
+ };
+ const signedIn = {
+ isAuthenticated: true,
+ user: { membershipKind: 'org', orgId: 'org-acme', orgSlug: 'acme' },
+ };
+
+ it('reads the ledger and the signed-in organization', () => {
+ const lookup = vi.fn(() => ({ kind: 'found', records: [removed] }));
+ const host = createNamespaceMigrationHost(deps({
+ getPluginMarketLedger: () => ({ lookupInstallationsForNamespaceMigration: lookup }),
+ getAuthState: () => signedIn,
+ }));
+ expect(host.canReclaimLegacyBareInstance({ ghostId: 'hello', namespace: 'acme', pluginId: 'plugin-a' })).toBe(true);
+ expect(lookup).toHaveBeenCalledWith('hello');
+ });
+
+ it('refuses an unreadable ledger', () => {
+ const host = createNamespaceMigrationHost(deps({
+ getPluginMarketLedger: () => ({ lookupInstallationsForNamespaceMigration: () => ({ kind: 'invalid' }) }),
+ getAuthState: () => signedIn,
+ }));
+ expect(host.canReclaimLegacyBareInstance({ ghostId: 'hello', namespace: 'acme', pluginId: 'plugin-a' })).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 747b3fdc84..75a66859a1 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -64,7 +64,10 @@ import {
ipcMain,
nativeImage,
safeStorage,
+ session as electronSession,
shell,
+ webContents as electronWebContents,
+ type Session,
type WebContents,
} from 'electron';
import { createHash, randomUUID } from 'node:crypto';
@@ -435,6 +438,15 @@ import { LibraryVault, statfsFreeBytes, DEFAULT_LIBRARY_LIMITS } from './library
import { LibraryStagingStore, relocateLibraryStagingOwner } from './libraryStaging.js';
import { LibrarySqlService, defaultLibraryDbWorkerPath } from './librarySqlService.js';
import { trashGhostLibrary } from './libraryTrash.js';
+import {
+ finishLegacyLibraryReattach,
+ LibrarySwapNeedsRestartError,
+ readLegacyLibraryReattachJournal,
+ relocateOrAdoptLibraryMeta,
+ startLegacyLibraryReattach,
+ withPluginHeldForLibrarySwap,
+ type LegacyLibraryReattachDeps,
+} from './libraryLegacyReattach.js';
import { migrateGhostLibrary } from './libraryMigrate.js';
import { setGhostLibraryFileResolver } from './runtime/electronSandboxAdapter.js';
import {
@@ -1118,6 +1130,14 @@ function findAvailableGhost(id: string, namespace?: string | null): InstalledGho
}
export function findGhostForInstanceId(id: string, namespace?: string | null): InstalledGhost | null {
+ // Plugin requests recheck their target many times per call. An exact
+ // instance key reads only that instance so each check does not rescan every
+ // install; anything else still resolves against the full list.
+ if (namespace === undefined) {
+ if (isAppSessionBoundaryPending()) return null;
+ const ghost = getGhostManager().findInstalledInstance(id);
+ if (ghost) return isGhostAvailableForActiveSession(ghost.manifest.id) ? ghost : null;
+ }
const resolved = resolvePluginInstanceQuery(availableGhosts(), id, namespace);
return resolved.status === 'unique' ? resolved.ghost : null;
}
@@ -1856,6 +1876,8 @@ export function getGhostManager(): GhostManager {
},
readUnconfirmedConfirmationEvidence: (record) =>
getNamespaceMigrationHost().readUnconfirmedConfirmationEvidence(record),
+ canReclaimLegacyBareInstance: (input) =>
+ getNamespaceMigrationHost().canReclaimLegacyBareInstance(input),
isNamespaceMigrationBusy: (ghostId) => getNamespaceMigrationHost().isNamespaceMigrationBusy(ghostId),
marketIdentityForInstance: (instance) => {
try {
@@ -1964,6 +1986,9 @@ export function getGhostRuntime(): GhostRuntime {
runtimeSingleton = new GhostRuntime({
adapter: electronSandboxAdapter,
log,
+ startBlockedReason: (id) => libraryRestartRequiredReason(
+ isValidPluginInstallRelId(id) ? pluginInstallStoragePart(id) : id,
+ ),
// 熔断不再自动转沉睡(Lizi 2026-07-09 定案):面板原地显示错误状态,
// 关闭(沉睡)/ 重载都由用户在面板上决定,主机只记日志。
onFused: (id) => log.warn('ghost fused after repeated crashes', { id }),
@@ -2151,6 +2176,7 @@ export function getGhostNodeRuntimeBroker(): GhostNodeRuntimeBroker {
if (!nodeRuntimeBrokerSingleton) {
nodeRuntimeBrokerSingleton = new GhostNodeRuntimeBroker({
getGhost: findGhostForInstanceId,
+ startBlockedReason: libraryRestartRequiredReason,
getCallSignal: (ghostId, callId) =>
getGhostPipeDispatcher().getPendingCallSignal(ghostId, callId),
getCallSessionId: (ghostId, callId) =>
@@ -5924,6 +5950,7 @@ export function getGhostLibrarySlot(): GhostLibrarySlot {
});
librarySlotSingleton = new GhostLibrarySlot({
getGhost: findGhostForInstanceId,
+ prepareRequest: finishPendingLegacyLibraryReattach,
bindingStore,
getDefaultRoot: (ghostId) => ownerScopedUserDataPath('libraries', ghostId),
getStagingRoot: (ghostId) => ownerScopedUserDataPath('library-staging', ghostId),
@@ -6137,8 +6164,13 @@ export async function getGhostLibraryOverview(ghostId: string): Promise<GhostLib
softLimitBytes: DEFAULT_LIBRARY_LIMITS.softLimitBytes,
softLimitExceeded: false,
orphaned: false,
+ legacyLibrary: null,
+ legacyLibraryInUse: false,
};
}
+ await finishPendingLegacyLibraryReattach()?.catch((error: unknown) => {
+ log.warn('library reattach recovery failed', { error: error instanceof Error ? error.message : String(error) });
+ });
const store = getGhostLibraryBindingStore();
const binding = await store.getBinding(storagePart);
const resolution = await store.resolveLibraryRoot(storagePart);
@@ -6200,9 +6232,338 @@ export async function getGhostLibraryOverview(ghostId: string): Promise<GhostLib
softLimitBytes: DEFAULT_LIBRARY_LIMITS.softLimitBytes,
softLimitExceeded: usedBytes > DEFAULT_LIBRARY_LIMITS.softLimitBytes,
orphaned,
+ ...(supported && ghost
+ ? await findLegacyLibraryUsage(ghost)
+ : { legacyLibrary: null, legacyLibraryInUse: false }),
};
}
+interface LegacyLibraryCandidate {
+ kind: 'candidate';
+ fromId: string;
+ toId: string;
+ oldLocation: 'default' | 'custom';
+ /** uninstalled = 宿主卸载时留下的库;unknown = 没有宿主身份文件、来源无法证明。 */
+ provenance: 'uninstalled' | 'unknown';
+ usedBytes: number;
+ fileCount: number;
+}
+
+/** 一个目录树的文件数与字节数;只用于展示,数到上限即停。 */
+async function countLibraryFiles(root: string, limit = 20000): Promise<{ usedBytes: number; fileCount: number }> {
+ let usedBytes = 0;
+ let fileCount = 0;
+ const stack = [root];
+ while (stack.length > 0 && fileCount < limit) {
+ const dir = stack.pop()!;
+ let entries: fs.Dirent[];
+ try {
+ entries = await fs.promises.readdir(dir, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const entry of entries) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) stack.push(full);
+ else if (entry.isFile()) {
+ fileCount += 1;
+ usedBytes += (await fs.promises.stat(full).catch(() => null))?.size ?? 0;
+ }
+ }
+ }
+ return { usedBytes, fileCount };
+}
+
+/**
+ * An installed instance under a namespaced key may have an older library left
+ * under the bare id by an earlier install. A library the host marked as left
+ * by an uninstall counts; so does a directory without any host identity
+ * (copied in by hand or by a migration script), whose source is unknown. A
+ * library with an identity of another owner never counts. The current
+ * instance must still use the default location. GhostManager decides whether
+ * the bare id is free; `in-use` means another install still runs on it.
+ */
+async function findLegacyLibraryCandidate(
+ ghost: InstalledGhost,
+): Promise<LegacyLibraryCandidate | { kind: 'in-use' } | null> {
+ const fromId = ghost.manifest.id;
+ const toId = installedGhostStoragePart(ghost);
+ if (fromId === toId || ghost.manifest.library !== true || !isValidGhostId(fromId)) return null;
+ const offer = getGhostManager().bareLibraryOffer(fromId, ghost.namespace ?? null);
+ if (offer === 'unavailable') return null;
+ const store = getGhostLibraryBindingStore();
+ if (await store.getBinding(toId) !== null) return null;
+ let oldLocation: 'default' | 'custom' = 'default';
+ let root = ownerScopedUserDataPath('libraries', fromId);
+ if (await store.getBinding(fromId) !== null) {
+ const resolution = await store.resolveLibraryRoot(fromId);
+ if (resolution.kind !== 'custom' || resolution.root === null) return null;
+ oldLocation = 'custom';
+ root = resolution.root;
+ }
+ const rootStat = await fs.promises.lstat(root).catch(() => null);
+ if (!rootStat?.isDirectory() || rootStat.isSymbolicLink()) return null;
+ if (offer === 'in-use') return { kind: 'in-use' };
+ const hostDir = path.join(root, '.cindy-library');
+ if (!(await fs.promises.lstat(hostDir).catch(() => null))) {
+ const usage = await countLibraryFiles(root);
+ if (usage.fileCount === 0) return null;
+ return { kind: 'candidate', fromId, toId, oldLocation, provenance: 'unknown', ...usage };
+ }
+ let meta: { ghostId?: unknown };
+ try {
+ meta = JSON.parse(await fs.promises.readFile(path.join(hostDir, 'meta.json'), 'utf8')) as typeof meta;
+ } catch {
+ return null;
+ }
+ // Nothing runs under the bare id (offer is available), so a library still
+ // owned by it was left behind. The uninstall marker is not required: for a
+ // custom location it lands under the default root instead.
+ if (meta.ghostId !== fromId) return null;
+ let usedBytes = 0;
+ let fileCount = 0;
+ try {
+ const usage = JSON.parse(
+ await fs.promises.readFile(path.join(hostDir, 'usage.json'), 'utf8'),
+ ) as { files?: number; bytes?: number };
+ usedBytes = Number(usage.bytes ?? 0);
+ fileCount = Number(usage.files ?? 0);
+ } catch {
+ /* 账本缺失按 0 计 */
+ }
+ return { kind: 'candidate', fromId, toId, oldLocation, provenance: 'uninstalled', usedBytes, fileCount };
+}
+
+async function findLegacyLibraryUsage(
+ ghost: InstalledGhost,
+): Promise<Pick<GhostLibraryOverview, 'legacyLibrary' | 'legacyLibraryInUse'>> {
+ try {
+ const found = await findLegacyLibraryCandidate(ghost);
+ if (found?.kind === 'in-use') return { legacyLibrary: null, legacyLibraryInUse: true };
+ return {
+ legacyLibrary: found
+ ? { usedBytes: found.usedBytes, fileCount: found.fileCount, provenance: found.provenance }
+ : null,
+ legacyLibraryInUse: false,
+ };
+ } catch (error) {
+ log.warn('legacy library lookup failed', { error: error instanceof Error ? error.message : String(error) });
+ return { legacyLibrary: null, legacyLibraryInUse: false };
+ }
+}
+
+function legacyLibraryReattachDeps(assertCurrent: () => void): LegacyLibraryReattachDeps {
+ const ownerKey = activeOwnerScopeKey();
+ const store = getGhostLibraryBindingStore();
+ return {
+ journalFile: () => ownerScopedUserDataPath('library-reattach.json'),
+ defaultRoot: (id) => ownerScopedUserDataPath('libraries', id),
+ stagingRoot: (id) => ownerScopedUserDataPath('library-staging', id),
+ trashRoot: () => ownerScopedUserDataPath('libraries-trash'),
+ relocateCustomBinding: (fromId, toId) => store.relocateBinding(fromId, toId),
+ assertCustomBindingRelocatable: (fromId, toId) => store.assertCanRelocateBinding(fromId, toId),
+ customRoot: async (id) => {
+ const binding = await store.getBinding(id, { strict: true });
+ return binding ? path.join(binding.root, id) : null;
+ },
+ relocateMeta: async (root, fromId, toId) => {
+ assertCurrent();
+ // 接回的目标实例已装好,顺手清掉卸载时留的 orphaned,设置页不用等插件首次打开才自愈。
+ await relocateOrAdoptLibraryMeta(root, fromId, toId, async (dir, from, to) => {
+ await relocateLibraryMetaOwner(dir, from, to, assertCurrent, { clearOrphaned: true });
+ });
+ },
+ relocateStaging: (root, fromId, toId) =>
+ relocateLibraryStagingOwner(root, fromId, toId, ownerKey, assertCurrent),
+ assertCurrent,
+ };
+}
+
+/**
+ * Holds the plugin out of the way while both library directories move: the
+ * runtime and panels share an in-memory partition whose cache would otherwise
+ * be written back over the swapped library.
+ */
+/**
+ * Instances whose partition cache could not be cleared after a library swap.
+ * They stay stopped until Cindy restarts, which empties the in-memory
+ * partition; panel attach and both runtimes check this before starting.
+ */
+const libraryRestartRequired = new Set<string>();
+
+function libraryRestartRequiredKey(id: string): string {
+ return `${activeOwnerScopeKey()}\0${id}`;
+}
+
+function libraryRestartRequiredReason(id: string): string | null {
+ return libraryRestartRequired.has(libraryRestartRequiredKey(id))
+ ? t('settings.ghosts.library.legacyReattachNeedsRestart')
+ : null;
+}
+
+/** Close every page still open in a plugin partition and wait until each is gone. */
+async function closePartitionPages(partitionSession: Session, timeoutMs = 5_000): Promise<void> {
+ const pages = electronWebContents.getAllWebContents()
+ .filter((page) => !page.isDestroyed() && page.session === partitionSession);
+ await Promise.all(pages.map((page) => new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('plugin page did not close')), timeoutMs);
+ page.once('destroyed', () => {
+ clearTimeout(timer);
+ resolve();
+ });
+ page.close();
+ })));
+}
+
+async function withLibrariesHeld<T>(fromId: string, toId: string, run: () => Promise<T>): Promise<T> {
+ const slot = getGhostLibrarySlot();
+ const ids = [fromId, toId];
+ const ghostBefore = findGhostForInstanceId(toId);
+ const partition = ghostBefore
+ ? ownerScopedGhostPartitionForInstalledGhost(ghostBefore, getActiveAppSession())
+ : null;
+ return withPluginHeldForLibrarySwap({
+ stopRuntime: async () => {
+ const running = {
+ browser: getGhostRuntime().stateOf(toId) === 'running',
+ node: getGhostNodeRuntimeBroker().stateOf(toId) === 'running',
+ };
+ getGhostRuntime().stop(toId);
+ await getGhostNodeRuntimeBroker().stopAndWait(toId);
+ return running;
+ },
+ notifyPanels: (phase) => broadcastGhostWindowPush('ghosts:library-replaced', { id: toId, phase }),
+ closePages: async () => {
+ if (partition) await closePartitionPages(electronSession.fromPartition(partition));
+ },
+ holdLibraries: (on) => {
+ for (const id of ids) slot.setRelocating(id, on);
+ },
+ disposeLibraries: async () => {
+ for (const id of ids) await slot.disposeGhost(id);
+ },
+ clearPartitionStorage: async () => {
+ if (partition) await electronSession.fromPartition(partition).clearStorageData();
+ },
+ restartRuntime: (running) => {
+ const ghost = findGhostForInstanceId(toId);
+ if (!ghost?.enabled || !isGhostAvailableForActiveSession(ghost.manifest.id)) return;
+ spawnIfResident(ghost);
+ const warn = (error: unknown) => log.warn('plugin restart after library reattach failed', {
+ id: toId, error: error instanceof Error ? error.message : String(error),
+ });
+ if (running.browser && !isResidentBrowserGhost(ghost.manifest)) {
+ void getGhostRuntime().spawn(ghost).catch(warn);
+ }
+ if (running.node && ghost.manifest.node?.lifecycle !== 'resident') {
+ void getGhostNodeRuntimeBroker().startForRecovery(ghost).catch(warn);
+ }
+ },
+ warn: (message, error) => log.warn(message, {
+ id: toId, error: error instanceof Error ? error.message : String(error),
+ }),
+ }, run).catch((error: unknown) => {
+ if (error instanceof LibrarySwapNeedsRestartError) libraryRestartRequired.add(libraryRestartRequiredKey(toId));
+ throw error;
+ });
+}
+
+let pendingLegacyLibraryReattach: Promise<void> | null = null;
+/** Owner whose journal is known to be absent; library requests then skip the file read. */
+let legacyLibraryReattachClearOwner: string | null = null;
+/** The two libraries named by the unfinished journal, once it has been read. */
+let legacyLibraryReattachIds: { owner: string; ids: readonly string[] } | null = null;
+
+/**
+ * A reattach that stopped midway leaves its journal. Finish it before a
+ * library request runs, so neither end is opened half moved. When recovery
+ * fails, only the two libraries it names stay closed; with a ghostId, other
+ * plugins' requests go on.
+ */
+function finishPendingLegacyLibraryReattach(ghostId?: string): Promise<void> | undefined {
+ if (ghostId !== undefined && isOutsideFailedLegacyLibraryReattach(ghostId)) return undefined;
+ const running = runPendingLegacyLibraryReattach();
+ if (!running || ghostId === undefined) return running;
+ return running.catch((error: unknown) => {
+ if (!isOutsideFailedLegacyLibraryReattach(ghostId)) throw error;
+ });
+}
+
+/** A recovery that failed is retried only by the two libraries it names. */
+function isOutsideFailedLegacyLibraryReattach(ghostId: string): boolean {
+ const known = legacyLibraryReattachIds;
+ if (known === null || known.owner !== activeOwnerScopeKey()) return false;
+ return !known.ids.includes(ghostId) && !known.ids.includes(libraryStorageKeyFor(ghostId) ?? ghostId);
+}
+
+function runPendingLegacyLibraryReattach(): Promise<void> | undefined {
+ if (isAppSessionBoundaryPending()) return undefined;
+ if (legacyLibraryReattachClearOwner === activeOwnerScopeKey()) return undefined;
+ pendingLegacyLibraryReattach ??= (async () => {
+ try {
+ const ownerKey = activeOwnerScopeKey();
+ const assertCurrent = (): void => {
+ if (activeOwnerScopeKey() !== ownerKey || isAppSessionBoundaryPending()) {
+ throw new Error('Library reattach owner changed');
+ }
+ };
+ const deps = legacyLibraryReattachDeps(assertCurrent);
+ legacyLibraryReattachIds = null;
+ const journal = await readLegacyLibraryReattachJournal(deps.journalFile());
+ if (journal) {
+ legacyLibraryReattachIds = { owner: ownerKey, ids: [journal.fromId, journal.toId] };
+ await getGhostManager().runExclusiveMutation(() =>
+ withLibrariesHeld(journal.fromId, journal.toId, () => finishLegacyLibraryReattach(journal, deps)));
+ await refreshMivoLibraryExtraDirGrant().catch(() => undefined);
+ }
+ legacyLibraryReattachClearOwner = ownerKey;
+ legacyLibraryReattachIds = null;
+ } finally {
+ pendingLegacyLibraryReattach = null;
+ }
+ })();
+ return pendingLegacyLibraryReattach;
+}
+
+/**
+ * Settings-page reattach, run after the Main confirmation. The current
+ * library goes to the library trash; the old one takes its place.
+ */
+export async function reattachLegacyLibraryForActiveOwner(
+ ghostId: string,
+ expectedTarget: string | null,
+): Promise<{ ok: boolean; message?: string }> {
+ await finishPendingLegacyLibraryReattach();
+ return getGhostManager().runExclusiveMutation(async () => {
+ const assertCurrent = (): void => {
+ if (expectedTarget === null || ghostLibraryDeleteTargetFor(ghostId) !== expectedTarget) {
+ throw new Error('Library 对应的 Plugin 或账号已变化,请重新操作');
+ }
+ };
+ assertCurrent();
+ const ghost = findGhostForInstanceId(ghostId);
+ const found = ghost ? await findLegacyLibraryCandidate(ghost) : null;
+ if (found?.kind !== 'candidate') return { ok: false, message: '没有可以接回的作品数据' };
+ const candidate = found;
+ assertCurrent();
+ // A failure midway leaves the journal; the next library request finishes it.
+ legacyLibraryReattachClearOwner = null;
+ await withLibrariesHeld(candidate.fromId, candidate.toId, () =>
+ startLegacyLibraryReattach(
+ { fromId: candidate.fromId, toId: candidate.toId, oldLocation: candidate.oldLocation, now: Date.now() },
+ legacyLibraryReattachDeps(assertCurrent),
+ ));
+ legacyLibraryReattachClearOwner = activeOwnerScopeKey();
+ await refreshMivoLibraryExtraDirGrant().catch((error) => {
+ log.warn('library extraDirs reattach sync failed', {
+ ghostId: candidate.toId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ return { ok: true };
+ });
+}
+
function ghostLibraryDeleteTargetFor(ghostId: string): string | null {
if (isAppSessionBoundaryPending()) return null;
const approvedTarget = ghostInstallMutationTargetFor(ghostId);
@@ -6433,6 +6794,8 @@ export async function installAndDock(
trustOverride?: GhostHostTrustOverride;
registrySource?: 'market' | 'manual' | 'agent-forge' | 'legacy' | 'builtin';
pluginId?: string | null;
+ /** The user agreed to reattach the library left under the bare id. */
+ reclaimLegacyBareInstance?: boolean;
beforePackagePlacement?: () => void;
},
): Promise<InstalledGhost> {
@@ -6452,6 +6815,8 @@ async function installAndDockLocked(
installOrigin?: 'agent-forge';
registrySource?: 'market' | 'manual' | 'agent-forge' | 'legacy' | 'builtin';
pluginId?: string | null;
+ /** The user agreed to reattach the library left under the bare id. */
+ reclaimLegacyBareInstance?: boolean;
beforePackagePlacement?: () => void;
},
): Promise<InstalledGhost> {
@@ -6477,6 +6842,7 @@ async function installAndDockLocked(
...(opts.installOrigin ? { installOrigin: opts.installOrigin } : {}),
...(opts.registrySource ? { registrySource: opts.registrySource } : {}),
...(opts.pluginId ? { pluginId: opts.pluginId } : {}),
+ ...(opts.reclaimLegacyBareInstance ? { reclaimLegacyBareInstance: true } : {}),
namespace: opts.namespace,
...(opts.beforePackagePlacement ? { beforePackagePlacement: opts.beforePackagePlacement } : {}),
});
@@ -6862,6 +7228,44 @@ export interface MarketGhostPackageCommitEvidence {
canonicalManifest: GhostManifest;
}
+/**
+ * An organization market install may find a library left under the bare id by
+ * an earlier install whose source cannot be proven, such as a local package.
+ * Ask before reattaching it. Market evidence reattaches without asking.
+ */
+export async function confirmLegacyLibraryReattach(plugin: {
+ ghostId: string;
+ namespace: string | null;
+ pluginId: string;
+ name: string;
+}): Promise<boolean> {
+ const { ghostId, namespace, pluginId } = plugin;
+ if (namespace === null || !isValidGhostId(ghostId)) return false;
+ if (!getGhostManager().canOfferBareReclaim(ghostId, namespace, pluginId)) return false;
+ if (getNamespaceMigrationHost().canReclaimLegacyBareInstance({ ghostId, namespace, pluginId })) return false;
+ const leftover = fs.existsSync(ownerScopedUserDataPath('libraries', ghostId)) ||
+ (await getGhostLibraryBindingStore().getBinding(ghostId)) !== null;
+ if (!leftover) return false;
+ const options = {
+ type: 'question' as const,
+ title: t('settings.ghosts.library.reattachTitle'),
+ message: t('settings.ghosts.library.reattachTitle'),
+ detail: `${plugin.name}\n\n${t('settings.ghosts.library.reattachDescription')}`,
+ buttons: [
+ t('settings.ghosts.library.reattachConfirm'),
+ t('settings.ghosts.library.reattachSkip'),
+ ],
+ defaultId: 0,
+ cancelId: 1,
+ noLink: true,
+ };
+ const parent = mainShellWindows().find((window) => window.isVisible() && !window.isMinimized());
+ const decision = parent
+ ? await dialog.showMessageBox(parent, options)
+ : await dialog.showMessageBox(options);
+ return decision.response === 0;
+}
+
export async function installOrUpdateMarketGhostPackage(
cindyFilePath: string,
expected: {
@@ -6880,6 +7284,8 @@ export async function installOrUpdateMarketGhostPackage(
pendingMarketRecord?: GhostFirstPartyPendingMarketRecord;
/** Server-market resource id. Recorded on the instance so another market does not reuse it. */
pluginId?: string;
+ /** The user agreed to reattach the library left under the bare id. */
+ reclaimLegacyBareInstance?: boolean;
/** 自定义 Git/本地市场在打包前读取的 Manifest,用于防止打包窗口内能力扩张。 */
manifestCap?: GhostManifest;
beforeCommitInLock?: () => void;
@@ -6919,6 +7325,8 @@ async function installOrUpdateMarketGhostPackageLocked(
pendingMarketRecord?: GhostFirstPartyPendingMarketRecord;
/** Server-market resource id. Recorded on the instance so another market does not reuse it. */
pluginId?: string;
+ /** The user agreed to reattach the library left under the bare id. */
+ reclaimLegacyBareInstance?: boolean;
manifestCap?: GhostManifest;
beforeCommitInLock?: () => void;
/** 新包已经原子换位;后续异常不能再按落位失败回滚来源路由。 */
@@ -7039,6 +7447,7 @@ async function installOrUpdateMarketGhostPackageLocked(
enable: true,
registrySource: 'market',
...(expected.pluginId ? { pluginId: expected.pluginId } : {}),
+ ...(expected.reclaimLegacyBareInstance ? { reclaimLegacyBareInstance: true } : {}),
expectedPackageSha256: inspected.packageSha256,
consent: { decision: expected.consent, manifest: inspected.manifest },
beforePackagePlacement: expected.beforeCommitInLock,
@@ -9251,6 +9660,52 @@ export function registerGhostIpc(): void {
releaseMutation();
}
});
+ ipcMain.handle('ghosts:library-reattach-legacy', async (event, id: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof id !== 'string' || !isGhostInstanceId(id)) throwIpcError('INVALID_PARAMS', '非法插件 id');
+ const expectedOwner = captureGhostMutationOwner();
+ const expectedTarget = ghostLibraryDeleteTargetFor(id);
+ // 换掉当前作品数据是破坏性操作,唯一有效的确认在 Main(与删除同口径)。
+ const parent = BrowserWindow.fromWebContents(event.sender);
+ const ghost = findGhostForInstanceId(id);
+ const ghostName = ghost?.manifest.name ?? id;
+ const found = ghost ? await findLegacyLibraryCandidate(ghost).catch(() => null) : null;
+ const unknownSource = found?.kind === 'candidate' && found.provenance === 'unknown'
+ ? `\n\n${t('settings.ghosts.library.legacyReattachUnknownSource')}`
+ : '';
+ const options = {
+ type: 'question' as const,
+ title: t('settings.ghosts.library.legacyReattachConfirmTitle'),
+ message: t('settings.ghosts.library.legacyReattachConfirmTitle'),
+ detail: `${ghostName}\n\n${t('settings.ghosts.library.legacyReattachConfirmDescription')}${unknownSource}`,
+ buttons: [
+ t('settings.ghosts.library.legacyReattachConfirmText'),
+ t('settings.ghosts.library.cancel'),
+ ],
+ defaultId: 1,
+ cancelId: 1,
+ noLink: true,
+ };
+ const decision = parent
+ ? await dialog.showMessageBox(parent, options)
+ : await dialog.showMessageBox(options);
+ if (decision.response !== 0) return { ok: false as const, cancelled: true as const };
+ const releaseMutation = beginGhostMutation(expectedOwner);
+ try {
+ const res = await reattachLegacyLibraryForActiveOwner(id, expectedTarget);
+ return res.ok
+ ? { ok: true as const }
+ : { ok: false as const, cancelled: false as const, message: res.message };
+ } catch (error) {
+ // The raw error can name absolute paths; it stays in the Main log.
+ log.warn('legacy library reattach failed', { id, error: error instanceof Error ? error.message : String(error) });
+ return error instanceof LibrarySwapNeedsRestartError
+ ? { ok: false as const, cancelled: false as const, message: t('settings.ghosts.library.legacyReattachNeedsRestart') }
+ : { ok: false as const, cancelled: false as const };
+ } finally {
+ releaseMutation();
+ }
+ });
// 面板错误态的「重载意识」:清熔断记账 + 重新拉起沙箱。
ipcMain.handle('ghosts:reload', async (event, id: unknown) => {
@@ -9451,10 +9906,11 @@ export function resolveGhostWebviewAttach(
const resolvedPartition = resolveGhostWebviewPartitionClaim(partitionClaim, owner);
if (!resolvedPartition) return null;
if (!isPluginInstanceKey(resolvedPartition.ghostId)) return null;
- const ghost = availableGhosts().find(
- (candidate) => installedGhostStoragePart(candidate) === resolvedPartition.ghostId,
- );
+ // Panels recheck this on every click and key press; an exact instance key
+ // reads only that instance.
+ const ghost = findGhostForInstanceId(resolvedPartition.ghostId);
if (!ghost || !ghost.enabled) return null;
+ if (libraryRestartRequiredReason(resolvedPartition.ghostId) !== null) return null;
if (resolvedPartition.ghostId !== installedGhostStoragePart(ghost)) return null;
const partition = ownerScopedGhostPartitionForInstalledGhost(ghost, owner);
if (!partition) return null;
diff --git a/apps/desktop/src/main/cindy-brain/libraryBinding.ts b/apps/desktop/src/main/cindy-brain/libraryBinding.ts
index 6cea5d7ee1..5a61238691 100644
--- a/apps/desktop/src/main/cindy-brain/libraryBinding.ts
+++ b/apps/desktop/src/main/cindy-brain/libraryBinding.ts
@@ -25,7 +25,7 @@ import { isDeepStrictEqual } from 'node:util';
import { isArchiveInstanceKey, isPluginInstanceKey } from '../../shared/pluginIdentity.js';
-function isLibraryOwnerId(value: unknown): value is string {
+export function isLibraryOwnerId(value: unknown): value is string {
return isPluginInstanceKey(value) || isArchiveInstanceKey(value);
}
@@ -76,7 +76,7 @@ async function directoryIdentity(root: string): Promise<{ dev: number; ino: numb
}
}
-async function syncDirectory(root: string): Promise<void> {
+export async function syncDirectory(root: string): Promise<void> {
if (process.platform === 'win32') return;
const directory = await fs.promises.open(root, 'r');
try {
@@ -132,6 +132,7 @@ export async function assertLibraryMetaOwner(root: string, ownerId: string): Pro
export async function relocateLibraryMetaOwner(
root: string, fromId: string, toId: string, assertCurrent: () => void = () => {},
+ options: { clearOrphaned?: boolean } = {},
): Promise<boolean> {
if (!isLibraryOwnerId(fromId) || !isLibraryOwnerId(toId)) {
throw new Error('library meta relocate ids are invalid');
@@ -140,14 +141,24 @@ export async function relocateLibraryMetaOwner(
assertCurrent();
if (!meta) return false;
const owner = meta.ghostId;
- if (owner === toId) return false;
- if (owner !== fromId) throw new Error('library meta belongs to a different plugin');
+ const clearOrphaned = options.clearOrphaned === true && meta.orphaned !== undefined;
+ if (owner === toId && !clearOrphaned) return false;
+ if (owner !== fromId && owner !== toId) throw new Error('library meta belongs to a different plugin');
+ const next: Record<string, unknown> = { ...meta, ghostId: toId };
+ if (clearOrphaned) delete next.orphaned;
const file = path.join(root, '.cindy-library', 'meta.json');
const temporary = file + '.' + randomUUID() + '.tmp';
try {
- await fs.promises.writeFile(temporary, JSON.stringify({ ...meta, ghostId: toId }), { flag: 'wx', mode: 0o600 });
+ const handle = await fs.promises.open(temporary, 'wx', 0o600);
+ try {
+ await handle.writeFile(JSON.stringify(next), 'utf8');
+ await handle.sync();
+ } finally {
+ await handle.close();
+ }
assertCurrent();
await fs.promises.rename(temporary, file);
+ await syncDirectory(path.dirname(file));
} finally {
await fs.promises.rm(temporary, { force: true });
}
diff --git a/apps/desktop/src/main/cindy-brain/libraryLegacyReattach.ts b/apps/desktop/src/main/cindy-brain/libraryLegacyReattach.ts
new file mode 100644
index 0000000000..5422650372
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/libraryLegacyReattach.ts
@@ -0,0 +1,350 @@
+/**
+ * libraryLegacyReattach.ts — 把裸 id 下遗留的旧作品库换回当前实例。
+ * ---------------------------------------------------------------------------
+ * namespace 实例键上线后,旧安装卸载再从企业市场重装,会得到新实例键和一个
+ * 新的空库,旧库留在裸 id 下没人认领。用户在设置页确认后,这里只换作品库,
+ * 插件安装、设置与私有数据都不动:
+ *
+ * 1. 当前实例的新库(及暂存区)移入作品库回收站(保留 30 天);
+ * 2. 旧库改名到当前实例键(自定义位置由 binding store 搬,它自带日志);
+ * 3. 改旧库与暂存区里记录的身份。
+ *
+ * 换库期间插件进程停掉、面板卸下,并清掉插件分区的缓存,换完再恢复
+ * (withPluginHeldForLibrarySwap)。
+ *
+ * 动手前先写日志,每一步都可以重跑:中途崩溃后,下次打开作品库前按日志做完。
+ * 纯 Node + 依赖注入,单测拿 tmpdir 直测。
+ */
+import { randomUUID } from 'node:crypto';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import { isDeepStrictEqual } from 'node:util';
+import { isLibraryOwnerId, syncDirectory } from './libraryBinding.js';
+
+interface DirectoryIdentity {
+ dev: number;
+ ino: number;
+}
+
+export interface LegacyLibraryReattachJournal {
+ version: 1;
+ /** 旧库所在的裸 id。 */
+ fromId: string;
+ /** 当前实例键。 */
+ toId: string;
+ oldLocation: 'default' | 'custom';
+ /** 动手前当前实例新库的目录身份;只有身份仍一致的目录才会被移入回收站。 */
+ newLibrary: DirectoryIdentity | null;
+ newStaging: DirectoryIdentity | null;
+ trashName: string;
+}
+
+export interface LegacyLibraryReattachDeps {
+ journalFile(): string;
+ defaultRoot(id: string): string;
+ stagingRoot(id: string): string;
+ trashRoot(): string;
+ /** 自定义位置:把 binding 与目录一起从 fromId 搬到 toId(重跑时无记录即返回)。 */
+ relocateCustomBinding(fromId: string, toId: string): Promise<void>;
+ /** 自定义位置:搬之前确认 toId 没有 binding、自定义父目录下也没有同名目录。 */
+ assertCustomBindingRelocatable(fromId: string, toId: string): Promise<void>;
+ /** 自定义位置下 toId 的库根;没有 binding 时返回 null。 */
+ customRoot(id: string): Promise<string | null>;
+ relocateMeta(root: string, fromId: string, toId: string): Promise<void>;
+ relocateStaging(root: string, fromId: string, toId: string): Promise<void>;
+ assertCurrent(): void;
+ /** 把目录项刷到磁盘;目录不存在时跳过。测试可注入以检查顺序。 */
+ syncDirectory?(dir: string): Promise<void>;
+}
+
+async function syncDirectoryIfPresent(dir: string): Promise<void> {
+ try {
+ await syncDirectory(dir);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+}
+
+async function directoryIdentity(dir: string): Promise<DirectoryIdentity | null> {
+ try {
+ const stat = await fs.promises.lstat(dir);
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`not a real directory: ${dir}`);
+ return { dev: stat.dev, ino: stat.ino };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw error;
+ }
+}
+
+function isIdentity(value: unknown): value is DirectoryIdentity {
+ if (!value || typeof value !== 'object') return false;
+ const identity = value as Partial<DirectoryIdentity>;
+ return typeof identity.dev === 'number' && typeof identity.ino === 'number';
+}
+
+function isJournal(value: unknown): value is LegacyLibraryReattachJournal {
+ if (!value || typeof value !== 'object') return false;
+ const journal = value as Partial<LegacyLibraryReattachJournal>;
+ return journal.version === 1 &&
+ isLibraryOwnerId(journal.fromId) && isLibraryOwnerId(journal.toId) &&
+ journal.fromId !== journal.toId &&
+ (journal.oldLocation === 'default' || journal.oldLocation === 'custom') &&
+ (journal.newLibrary === null || isIdentity(journal.newLibrary)) &&
+ (journal.newStaging === null || isIdentity(journal.newStaging)) &&
+ typeof journal.trashName === 'string' && /^[A-Za-z0-9_.-]+$/.test(journal.trashName) &&
+ journal.trashName !== '.' && journal.trashName !== '..';
+}
+
+export async function readLegacyLibraryReattachJournal(
+ file: string,
+): Promise<LegacyLibraryReattachJournal | null> {
+ let raw: string;
+ try {
+ raw = await fs.promises.readFile(file, 'utf8');
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
+ throw error;
+ }
+ const parsed: unknown = JSON.parse(raw);
+ if (!isJournal(parsed)) throw new Error('library reattach journal is invalid');
+ return parsed;
+}
+
+async function writeJournal(file: string, journal: LegacyLibraryReattachJournal): Promise<void> {
+ await fs.promises.mkdir(path.dirname(file), { recursive: true });
+ const temporary = `${file}.${randomUUID()}.tmp`;
+ const handle = await fs.promises.open(temporary, 'wx', 0o600);
+ try {
+ await handle.writeFile(JSON.stringify(journal), 'utf8');
+ await handle.sync();
+ } finally {
+ await handle.close();
+ }
+ await fs.promises.rename(temporary, file);
+ // The journal entry must be on disk before any library moves.
+ await syncDirectory(path.dirname(file));
+}
+
+async function assertCustomLibraryRelocatable(root: string | null): Promise<void> {
+ if (root === null) throw new Error('old custom library root is unavailable');
+ // The binding store moves a custom library by the identity of the library
+ // and its parent. A volume without inode numbers cannot be moved, so stop
+ // before anything changes.
+ for (const dir of [path.dirname(root), root]) {
+ const stat = await fs.promises.lstat(dir);
+ if (!stat.isDirectory() || stat.isSymbolicLink() || stat.ino === 0) {
+ throw new Error('old custom library cannot be moved on this volume');
+ }
+ }
+}
+
+/** 记下要换的两边,然后执行。日志已存在时拒绝开始新的一次。 */
+export async function startLegacyLibraryReattach(
+ input: { fromId: string; toId: string; oldLocation: 'default' | 'custom'; now: number },
+ deps: LegacyLibraryReattachDeps,
+): Promise<void> {
+ if (await readLegacyLibraryReattachJournal(deps.journalFile())) {
+ throw new Error('another library reattach is unfinished');
+ }
+ deps.assertCurrent();
+ if (input.oldLocation === 'custom') {
+ await assertCustomLibraryRelocatable(await deps.customRoot(input.fromId));
+ await deps.assertCustomBindingRelocatable(input.fromId, input.toId);
+ }
+ deps.assertCurrent();
+ const journal: LegacyLibraryReattachJournal = {
+ version: 1,
+ fromId: input.fromId,
+ toId: input.toId,
+ oldLocation: input.oldLocation,
+ newLibrary: await directoryIdentity(deps.defaultRoot(input.toId)),
+ newStaging: await directoryIdentity(deps.stagingRoot(input.toId)),
+ trashName: `${input.toId}-${input.now}-replaced`,
+ };
+ deps.assertCurrent();
+ await writeJournal(deps.journalFile(), journal);
+ await finishLegacyLibraryReattach(journal, deps);
+}
+
+/**
+ * 只把仍是那个新库的目录移入回收站;已移走或换成别的目录都不动。回收站里已有
+ * 目标就算这步做完——不提供 inode 的卷上(ino 为 0)目录身份分不出新旧库。
+ */
+async function trashIfSame(dir: string, identity: DirectoryIdentity | null, target: string): Promise<void> {
+ if (identity === null) return;
+ if (await directoryIdentity(target) !== null) return;
+ if (!isDeepStrictEqual(await directoryIdentity(dir), identity)) return;
+ await fs.promises.mkdir(path.dirname(target), { recursive: true });
+ await fs.promises.rename(dir, target);
+}
+
+async function moveIfFree(fromDir: string, toDir: string): Promise<void> {
+ if (await directoryIdentity(fromDir) === null) return;
+ if (await directoryIdentity(toDir) !== null) {
+ throw new Error(`library reattach destination already exists: ${toDir}`);
+ }
+ await fs.promises.rename(fromDir, toDir);
+}
+
+/** 按日志做完剩下的步骤;每一步重跑都安全。 */
+export async function finishLegacyLibraryReattach(
+ journal: LegacyLibraryReattachJournal,
+ deps: LegacyLibraryReattachDeps,
+): Promise<void> {
+ const { fromId, toId } = journal;
+ // Paths are owner scoped. Pin this account's journal so a switch midway
+ // cannot make the final removal hit another account's journal.
+ const journalFile = deps.journalFile();
+ const trash = path.join(deps.trashRoot(), journal.trashName);
+ deps.assertCurrent();
+ await trashIfSame(deps.defaultRoot(toId), journal.newLibrary, trash);
+ deps.assertCurrent();
+ await trashIfSame(deps.stagingRoot(toId), journal.newStaging, `${trash}-staging`);
+ deps.assertCurrent();
+ if (journal.oldLocation === 'custom') {
+ await deps.relocateCustomBinding(fromId, toId);
+ } else {
+ await moveIfFree(deps.defaultRoot(fromId), deps.defaultRoot(toId));
+ }
+ deps.assertCurrent();
+ await moveIfFree(deps.stagingRoot(fromId), deps.stagingRoot(toId));
+ deps.assertCurrent();
+ const root = journal.oldLocation === 'custom' ? await deps.customRoot(toId) : deps.defaultRoot(toId);
+ if (root === null) throw new Error('reattached custom library root is unavailable');
+ await deps.relocateMeta(root, fromId, toId);
+ deps.assertCurrent();
+ await deps.relocateStaging(deps.stagingRoot(toId), fromId, toId);
+ deps.assertCurrent();
+ // Every rename and identity rewrite above must be on disk before the journal
+ // goes; otherwise a crash could leave the moves half applied with nothing to
+ // finish them from.
+ const sync = deps.syncDirectory ?? syncDirectoryIfPresent;
+ for (const dir of new Set([
+ deps.trashRoot(),
+ path.dirname(deps.defaultRoot(toId)),
+ path.dirname(deps.stagingRoot(toId)),
+ path.join(root, '.cindy-library'),
+ path.join(deps.stagingRoot(toId), '.cindy-library'),
+ ])) {
+ await sync(dir);
+ }
+ deps.assertCurrent();
+ await fs.promises.rm(journalFile, { force: true });
+ await sync(path.dirname(journalFile));
+}
+
+/**
+ * A library copied in without host identity (no `.cindy-library/meta.json`)
+ * gets the new owner written in; one that has an identity is relocated as
+ * usual. Safe to run again: a stop after the folder was made but before the
+ * identity landed still finds no meta.json, and a written identity already
+ * names the new owner.
+ */
+export async function relocateOrAdoptLibraryMeta(
+ root: string,
+ fromId: string,
+ toId: string,
+ relocate: (root: string, fromId: string, toId: string) => Promise<void>,
+ now = Date.now(),
+): Promise<void> {
+ const hostDir = path.join(root, '.cindy-library');
+ const metaFile = path.join(hostDir, 'meta.json');
+ const hasMeta = await fs.promises.lstat(metaFile).then(() => true, (error: NodeJS.ErrnoException) => {
+ if (error.code === 'ENOENT') return false;
+ throw error;
+ });
+ if (await directoryIdentity(root) === null || hasMeta) {
+ await relocate(root, fromId, toId);
+ return;
+ }
+ await fs.promises.mkdir(hostDir, { recursive: true });
+ const temporary = `${metaFile}.${randomUUID()}.tmp`;
+ const handle = await fs.promises.open(temporary, 'wx', 0o600);
+ try {
+ await handle.writeFile(JSON.stringify({ version: 1, ghostId: toId, createdAt: now }), 'utf8');
+ await handle.sync();
+ } finally {
+ await handle.close();
+ }
+ await fs.promises.rename(temporary, metaFile);
+ await syncDirectory(hostDir);
+}
+
+export interface PluginHoldForLibrarySwapDeps {
+ /** 停掉插件运行进程,返回停之前在跑的运行时,供换完后按原样恢复。 */
+ stopRuntime(): Promise<{ browser: boolean; node: boolean }>;
+ /** 通知各窗口里这个插件的面板:start = 先卸下,done = 从磁盘重新挂上。 */
+ notifyPanels(phase: 'start' | 'done'): void;
+ /**
+ * 关掉这个实例分区里仍开着的页面,等它们真正销毁。面板与后台页之间走同源
+ * BroadcastChannel,Main 不在中间,只能把旧页关掉,不能只靠 notifyPanels。
+ */
+ closePages(): Promise<void>;
+ holdLibraries(on: boolean): void;
+ disposeLibraries(): Promise<void>;
+ /**
+ * 清掉这个实例的 Electron 分区存储。分区只在内存里,面板和后台进程都用它;
+ * 不清的话,插件会拿换库前的缓存覆盖刚换上来的库。
+ */
+ clearPartitionStorage(): Promise<void>;
+ restartRuntime(running: { browser: boolean; node: boolean }): void;
+ warn(message: string, error: unknown): void;
+}
+
+/** 换库后旧缓存清不掉:插件保持停止、作品库保持拦截,重启 Cindy 后分区自然清空。 */
+export class LibrarySwapNeedsRestartError extends Error {
+ constructor(cause: unknown) {
+ super('plugin cache could not be cleared after the library swap', { cause });
+ }
+}
+
+/** 关掉旧页、清掉分区;失败再试一次。返回是否清干净。 */
+async function clearStalePluginState(deps: PluginHoldForLibrarySwapDeps): Promise<unknown> {
+ let failure: unknown = null;
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ try {
+ await deps.closePages();
+ await deps.clearPartitionStorage();
+ return null;
+ } catch (error) {
+ failure = error;
+ deps.warn('plugin partition storage clear failed after library swap', error);
+ }
+ }
+ return failure ?? new Error('plugin cache clear failed');
+}
+
+/**
+ * 换库期间插件不能运行、面板不能挂着:进程与面板都可能把旧库的状态写回来。
+ * 顺序:停进程、卸面板并关掉旧页 → 换库 → 再关一次旧页、清分区(此时没人在用)
+ * → 放行作品库 → 重启进程、挂回面板。清不掉就停在拦截状态,报需要重启。
+ */
+export async function withPluginHeldForLibrarySwap<T>(
+ deps: PluginHoldForLibrarySwapDeps,
+ run: () => Promise<T>,
+): Promise<T> {
+ const running = await deps.stopRuntime();
+ deps.notifyPanels('start');
+ deps.holdLibraries(true);
+ let result: T;
+ try {
+ await deps.closePages();
+ await deps.disposeLibraries();
+ result = await run();
+ } catch (error) {
+ const failure = await clearStalePluginState(deps);
+ if (failure !== null) throw new LibrarySwapNeedsRestartError(failure);
+ release(deps, running);
+ throw error;
+ }
+ const failure = await clearStalePluginState(deps);
+ if (failure !== null) throw new LibrarySwapNeedsRestartError(failure);
+ release(deps, running);
+ return result;
+}
+
+function release(deps: PluginHoldForLibrarySwapDeps, running: { browser: boolean; node: boolean }): void {
+ deps.holdLibraries(false);
+ deps.restartRuntime(running);
+ deps.notifyPanels('done');
+}
diff --git a/apps/desktop/src/main/cindy-brain/librarySlot.ts b/apps/desktop/src/main/cindy-brain/librarySlot.ts
index 898ce4a58d..35480a12a6 100644
--- a/apps/desktop/src/main/cindy-brain/librarySlot.ts
+++ b/apps/desktop/src/main/cindy-brain/librarySlot.ts
@@ -192,6 +192,8 @@ class GhostLibraryRequestCancelled extends Error {}
export interface GhostLibrarySlotDeps {
getGhost(id: string): InstalledGhost | null;
+ /** Host work that must settle before this plugin's library request opens a root; undefined when none is due. */
+ prepareRequest?(ghostId: string): Promise<void> | undefined;
/** 自定义位置 binding 存储(owner-scoped;生产注入)。 */
bindingStore: LibraryBindingStore;
/** 系统默认库根(生产 = ownerScopedUserDataPath('libraries', ghostId))。 */
@@ -294,8 +296,7 @@ export class GhostLibrarySlot {
this.relocationGenerations.set(ghostId, (this.relocationGenerations.get(ghostId) ?? 0) + 1);
}
- private ghostRequestTarget(ghostId: string): string | null {
- const ghost = this.deps.getGhost(ghostId);
+ private ghostRequestTarget(ghostId: string, ghost = this.deps.getGhost(ghostId)): string | null {
return ghost ? JSON.stringify([
ghost.manifest.id, ghost.dir, ghost.namespace ?? null, ghost.enabled !== false,
ghostInstallApprovalToken(ghost.approval),
@@ -312,8 +313,13 @@ export class GhostLibrarySlot {
return !this.relocating.has(ghostId)
&& target.relocationGeneration === this.relocationGenerations.get(ghostId)
&& target.ownerScopeKey === this.deps.captureOwnerScope()
- && this.checkEligibility(ghostId)
- && target.ghostTarget === this.ghostRequestTarget(ghostId);
+ && this.isCurrentGhostTarget(ghostId, target.ghostTarget);
+ }
+
+ /** One lookup serves both checks: eligibility and the captured target must see the same ghost. */
+ private isCurrentGhostTarget(ghostId: string, ghostTarget: string | null): boolean {
+ const ghost = this.deps.getGhost(ghostId);
+ return this.checkEligibility(ghostId, ghost) && ghostTarget === this.ghostRequestTarget(ghostId, ghost);
}
private assertRequestCurrent(ghostId: string, target: GhostLibraryRequestTarget, session?: GhostLibrarySession): void {
@@ -435,6 +441,15 @@ export class GhostLibrarySlot {
},
};
}
+ // Host work such as an unfinished reattach settles only for a request that
+ // will really open the library.
+ const preparing = this.deps.prepareRequest?.(ghostId);
+ if (preparing) {
+ await preparing;
+ if (!this.checkEligibility(ghostId)) {
+ return fail('NOT_DECLARED', '插件未装入、已停用或未声明 "library" 能力', 'PERMISSION_DENIED');
+ }
+ }
if (isGhostLibraryStagingOp(op)) {
if (op === 'staging.release') {
if (this.relocating.has(ghostId)) {
@@ -541,8 +556,7 @@ export class GhostLibrarySlot {
* 与 read 同源校验——面板与电子脑看到同一个库。
*/
/** 资格审:装入 + 启用 + 声明 library 能力(dispatch 与面板投影共用)。 */
- private checkEligibility(ghostId: string): boolean {
- const ghost = this.deps.getGhost(ghostId);
+ private checkEligibility(ghostId: string, ghost = this.deps.getGhost(ghostId)): boolean {
if (!ghost) return false;
if (ghost.enabled === false) return false;
if (ghost.approval && ghost.approval.state !== 'approved') return false;
@@ -556,6 +570,9 @@ export class GhostLibrarySlot {
*/
async resolvePanelFilePath(ghostId: string, relPath: string): Promise<string | null> {
try {
+ if (!this.checkEligibility(ghostId)) return null;
+ const preparing = this.deps.prepareRequest?.(ghostId);
+ if (preparing) await preparing;
if (!this.checkEligibility(ghostId)) return null;
const session = await this.getOrCreateSession(ghostId, this.deps.captureOwnerScope());
if (session.drift !== null) return null;
diff --git a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts
index e8ffb91841..3408cf6515 100644
--- a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts
+++ b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts
@@ -148,6 +148,8 @@ export interface NodeRuntimeStartAttemptContext {
export interface GhostNodeRuntimeBrokerDeps {
getGhost(id: string): InstalledGhost | null;
+ /** 宿主要求这个实例暂不启动时返回原因(如换库后缓存没清掉、需要重启应用)。 */
+ startBlockedReason?(id: string): string | null;
openSecretInput?: (input: import('./nodeSecretSetup.js').NodeSecretSetupInput) => Promise<boolean>;
/** Main's exact live tool-call lookup; a plugin cannot select another call's owner. */
getCallSignal?: (ghostId: string, callId: string) => AbortSignal | null;
@@ -1727,6 +1729,8 @@ export class GhostNodeRuntimeBroker {
if (this.destroyed || this.stoppedGhosts.has(GhostNodeRuntimeBroker.instanceId(ghost))) {
throw new WorkerStartError('Node 工作进程启动已取消', false, true);
}
+ const blocked = this.deps.startBlockedReason?.(GhostNodeRuntimeBroker.instanceId(ghost)) ?? null;
+ if (blocked !== null) throw new WorkerStartError(blocked, false);
this.sendStatus(ghost, 'starting', undefined, entryRel);
let current = ghost;
let lastError = new Error('Node 工作进程启动失败');
diff --git a/apps/desktop/src/main/cindy-brain/pluginNamespaceMigration.ts b/apps/desktop/src/main/cindy-brain/pluginNamespaceMigration.ts
index 808d281cd2..da9a2138a7 100644
--- a/apps/desktop/src/main/cindy-brain/pluginNamespaceMigration.ts
+++ b/apps/desktop/src/main/cindy-brain/pluginNamespaceMigration.ts
@@ -158,7 +158,7 @@ export function classifyNamespaceMigration(
function matchingOrganizationNamespace(
organizationId: string | null,
- currentOrganization: ClassifyNamespaceMigrationInput['currentOrganization'],
+ currentOrganization: { organizationId: string; orgSlug: string | null } | null,
): string | null {
if (!organizationId || !currentOrganization) return null;
if (currentOrganization.organizationId !== organizationId) return null;
@@ -166,6 +166,34 @@ function matchingOrganizationNamespace(
return namespace && isValidPluginNamespace(namespace) ? namespace : null;
}
+/**
+ * An organization install removed before this client first ran leaves its
+ * library under the bare id and no registry record. The market ledger still
+ * holds the pre-namespace record, so only that same organization plugin may
+ * take the bare key back.
+ */
+export function canReclaimLegacyBareInstance(input: {
+ pluginId: string;
+ namespace: string;
+ records: readonly {
+ pluginId: string;
+ scope: 'public' | 'personal' | 'organization';
+ source: 'market' | 'legacy-adopted' | 'git-market' | 'local-market';
+ organizationId: string | null;
+ namespace?: string | null;
+ installed: boolean;
+ }[];
+ currentOrganization: { organizationId: string; orgSlug: string | null } | null;
+}): boolean {
+ const matches = input.records.filter((record) => record.pluginId === input.pluginId);
+ if (matches.length !== 1) return false;
+ const record = matches[0]!;
+ return !record.installed && !hasDeliveryNamespace(record) &&
+ record.scope === 'organization' &&
+ (record.source === 'market' || record.source === 'legacy-adopted') &&
+ matchingOrganizationNamespace(record.organizationId, input.currentOrganization) === input.namespace;
+}
+
export type NamespaceCommitPlan =
| { kind: 'skip'; reason: 'not-pending' | 'busy' }
| { kind: 'write-registry-only'; namespace: string | null; basis: 'receipt-recovered' }
diff --git a/apps/desktop/src/main/cindy-brain/pluginNamespaceMigrationHost.ts b/apps/desktop/src/main/cindy-brain/pluginNamespaceMigrationHost.ts
index 1d5bf271bf..0d10b33206 100644
--- a/apps/desktop/src/main/cindy-brain/pluginNamespaceMigrationHost.ts
+++ b/apps/desktop/src/main/cindy-brain/pluginNamespaceMigrationHost.ts
@@ -10,6 +10,7 @@ import { installedGhostPhysicalRelId, installedGhostStoragePart } from '../../sh
import type { GhostManifest, InstalledGhost } from '../../shared/ghost.js';
import { isResidentBrowserGhost } from './residentGhost.js';
import {
+ canReclaimLegacyBareInstance,
classifyNamespaceMigration,
readNamespaceMigrationInstallOrigin,
readNamespaceMigrationMarketRecord,
@@ -93,6 +94,7 @@ export interface NamespaceMigrationHost {
isNamespaceMigrationBusy(ghostId: string): boolean;
preparePendingResidentForMigration(ghostId: string): Promise<boolean>;
readUnconfirmedConfirmationEvidence(record: PluginInstanceRecord): InstanceConfirmationEvidence;
+ canReclaimLegacyBareInstance(input: { ghostId: string; namespace: string; pluginId: string }): boolean;
rememberOfflineResident(ghostId: string): void;
forgetOfflineResident(ghostId: string): void;
clearPendingResidentMigrationRetry(ghostId: string): void;
@@ -120,6 +122,14 @@ export function createNamespaceMigrationHost(deps: NamespaceMigrationHostDeps):
return ownedResidentIds;
}
+ function currentOrganizationFacts(): { organizationId: string; orgSlug: string | null } | null {
+ const state = deps.getAuthState();
+ const user = state.isAuthenticated ? state.user : null;
+ return user?.membershipKind === 'org' && user.orgId
+ ? { organizationId: user.orgId, orgSlug: user.orgSlug ?? null }
+ : null;
+ }
+
function namespaceMigrationMarketRecordsForGhost(ghostId: string): PluginMarketInstallationRecord[] {
const lookup = deps.getPluginMarketLedger().lookupInstallationsForNamespaceMigration(ghostId);
if (lookup.kind === 'invalid') throw new Error('Plugin namespace migration market evidence is invalid');
@@ -284,11 +294,7 @@ export function createNamespaceMigrationHost(deps: NamespaceMigrationHostDeps):
});
},
readUnconfirmedConfirmationEvidence(record: PluginInstanceRecord): InstanceConfirmationEvidence {
- const state = deps.getAuthState();
- const user = state.isAuthenticated ? state.user : null;
- const currentOrganization = user?.membershipKind === 'org' && user.orgId
- ? { organizationId: user.orgId, orgSlug: user.orgSlug ?? null }
- : null;
+ const currentOrganization = currentOrganizationFacts();
let packageSha256: string | null = null;
let forgeSelfTest = false;
try {
@@ -311,5 +317,19 @@ export function createNamespaceMigrationHost(deps: NamespaceMigrationHostDeps):
rows, record, currentOrganization, packageSha256, forgeSelfTest,
});
},
+ canReclaimLegacyBareInstance({ ghostId, namespace, pluginId }): boolean {
+ try {
+ const lookup = deps.getPluginMarketLedger().lookupInstallationsForNamespaceMigration(ghostId);
+ if (lookup.kind !== 'found') return false;
+ return canReclaimLegacyBareInstance({
+ pluginId,
+ namespace,
+ records: lookup.records ?? [],
+ currentOrganization: currentOrganizationFacts(),
+ });
+ } catch {
+ return false;
+ }
+ },
};
}
diff --git a/apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts b/apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts
index ad6f0f771b..889ce61ce9 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts
@@ -46,6 +46,8 @@ interface GhostRuntimeOptions {
onStateChanged?: (id: string, state: GhostRuntimeState) => void;
/** 时钟注入(测试用假时钟)。 */
now?: () => number;
+ /** 宿主要求这个实例暂不启动时返回原因(如换库后缓存没清掉、需要重启应用)。 */
+ startBlockedReason?: (id: string) => string | null;
log?: {
info: (msg: string, meta?: Record<string, unknown>) => void;
warn: (msg: string, meta?: Record<string, unknown>) => void;
@@ -89,6 +91,8 @@ export class GhostRuntime {
if (entry.state === 'starting' || entry.state === 'running') return { ok: true, state: entry.state };
if (entry.state === 'fused') return { ok: false, reason: '已熔断(反复崩溃),重新唤醒后可再试' };
if (entry.state === 'stopping') return { ok: false, reason: '正在熄灯,稍后再试' };
+ const blocked = this.options.startBlockedReason?.(id) ?? null;
+ if (blocked !== null) return { ok: false, reason: blocked };
this.setState(id, entry, 'starting');
// 沙箱创建本身也可能同步 throw(如 app 未 ready、窗口创建失败):同样按
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/GhostRuntime.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/GhostRuntime.test.ts
index 378f790137..f5fb2c8f88 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/GhostRuntime.test.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/GhostRuntime.test.ts
@@ -55,6 +55,20 @@ function setup(opts?: { now?: () => number; loadFails?: boolean }) {
}
describe('GhostRuntime · 状态机', () => {
+ it('does not start an instance the host holds stopped until restart', async () => {
+ const handles: FakeHandle[] = [];
+ let blocked: string | null = 'restart Cindy';
+ const runtime = new GhostRuntime({
+ adapter: { create: () => { const handle = new FakeHandle(); handles.push(handle); return handle; } },
+ startBlockedReason: (id) => (id === 'demo' ? blocked : null),
+ });
+ await expect(runtime.spawn(chipGhost())).resolves.toEqual({ ok: false, reason: 'restart Cindy' });
+ expect(handles).toHaveLength(0);
+ expect(runtime.stateOf('demo')).toBe('off');
+ blocked = null;
+ await expect(runtime.spawn(chipGhost())).resolves.toMatchObject({ ok: true });
+ });
+
it('spawn → running;stop → off,沙箱被销毁', async () => {
const { runtime, handles } = setup();
const ghost = chipGhost();
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.ts
index f5a5e5a2f6..b469355db7 100644
--- 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.ts
@@ -36,6 +36,7 @@ const brain = vi.hoisted(() => ({
),
}));
vi.mock('../../cindy-brain/index.js', () => ({
+ confirmLegacyLibraryReattach: async () => false,
getGhostManager: () => ({ inspect: brain.inspect }),
installOrUpdateMarketGhostPackage: async (
filePath: string,
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.ts
index 45c7e42416..6ce3d317cd 100644
--- 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.ts
@@ -74,6 +74,7 @@ vi.mock('../../logger.js', () => ({
createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
vi.mock('../../cindy-brain/index.js', () => ({
+ confirmLegacyLibraryReattach: async () => false,
getGhostManager: () => ({
list: () =>
(runtime.listSequence ? runtime.listSequence() : runtime.ghosts).map((ghost) => ({
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
index f29d4809f2..300a4ce0db 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -15,6 +15,7 @@ import {
type InstalledGhost,
} from '../../../shared/ghost.js';
const runtime = vi.hoisted(() => ({
+ confirmLegacyLibraryReattach: vi.fn(async (_plugin: unknown) => false),
ghosts: [] as Array<{
manifest: Record<string, unknown>;
dir: string;
@@ -103,6 +104,7 @@ vi.mock('../../logger.js', () => ({
createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
vi.mock('../../cindy-brain/index.js', () => ({
+ confirmLegacyLibraryReattach: (plugin: unknown) => runtime.confirmLegacyLibraryReattach(plugin),
getGhostManager: () => ({
resumePendingResidentsOffline: runtime.resumeOfflineResidents,
reconcilePendingRootNamespaces: runtime.reconcilePendingRootNamespaces,
@@ -249,6 +251,8 @@ function deferred(): { promise: Promise<void>; resolve: () => void } {
afterEach(() => {
runtime.ghosts = [];
+ runtime.confirmLegacyLibraryReattach.mockReset();
+ runtime.confirmLegacyLibraryReattach.mockImplementation(async () => false);
runtime.install.mockReset();
runtime.inspect.mockReset();
runtime.inspectedManifest = null;
@@ -2153,6 +2157,32 @@ describe('PluginMarketService migration and defaultInstall', () => {
.not.toHaveProperty('approvedPackageSha256');
});
+ it.each([true, false])('asks once before a first organization install and passes the answer (%s)', async (answer) => {
+ runtime.confirmLegacyLibraryReattach.mockImplementation(async () => answer);
+ const item = summary({ scope: 'organization', organizationId: 'org-1', ghostId: 'acme-tool', namespace: 'acme' });
+ runtime.install.mockResolvedValue({
+ manifest: manifest(item.ghostId),
+ dir: '/userData/cindy-brain/' + item.ghostId,
+ enabled: true,
+ });
+ const target = harness([item]);
+ await target.service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT);
+ expect(runtime.confirmLegacyLibraryReattach).toHaveBeenCalledTimes(1);
+ expect(runtime.confirmLegacyLibraryReattach).toHaveBeenCalledWith({
+ ghostId: 'acme-tool', namespace: 'acme', pluginId: item.id, name: item.name,
+ });
+ const options = runtime.install.mock.calls[0]?.[1] as Record<string, unknown>;
+ if (answer) expect(options).toMatchObject({ reclaimLegacyBareInstance: true });
+ else expect(options).not.toHaveProperty('reclaimLegacyBareInstance');
+ });
+
+ it('does not ask about leftover libraries for a public install', async () => {
+ const item = summary();
+ runtime.install.mockResolvedValue({ manifest: manifest(), dir: '/userData/cindy-brain/cindy-test', enabled: true });
+ await harness([item]).service.install(item.id, reviewedInstallOptions(item), TEST_INSTALL_CONTEXT);
+ expect(runtime.confirmLegacyLibraryReattach).not.toHaveBeenCalled();
+ });
+
it('manual market install accepts the normalized setup manifest returned by detail', async () => {
const item = summary();
const rawManifest = setupSecretManifest();
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index 358c60921b..16d5fdaa53 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -48,6 +48,7 @@ import {
} from '../../shared/pluginMarket.js';
import { getAuthState, getCurrentUserId } from '../authManager.js';
import {
+ confirmLegacyLibraryReattach,
getGhostManager,
hasPendingGhostCalls,
hasRunningGhostCindyWork,
@@ -2317,12 +2318,27 @@ export class PluginMarketService {
inspected.packageSha256,
);
requireSameMarketOwner(owner);
+ // Asked only beside a first-install prompt the user just answered;
+ // background and default installs never stop for it.
+ const reclaimLegacyBareInstance = consent.mode === 'confirmed' && !options.expectedInstalled &&
+ plugin.scope === 'organization' && typeof plugin.namespace === 'string' &&
+ await confirmLegacyLibraryReattach({
+ ghostId: plugin.ghostId,
+ namespace: plugin.namespace,
+ pluginId: plugin.id,
+ name: plugin.name,
+ }).catch((error: unknown) => {
+ log.warn('legacy library reattach prompt unavailable', { ghostId: plugin.ghostId, error: String(error) });
+ return false;
+ });
+ requireSameMarketOwner(owner);
const commit = () =>
this.commitDownloadedPackage(
tempPath,
plugin,
{
consent,
+ ...(reclaimLegacyBareInstance ? { reclaimLegacyBareInstance: true } : {}),
expectedInstalled: options.expectedInstalled,
...(options.expectedInstalledApproval !== undefined
? { expectedInstalledApproval: options.expectedInstalledApproval }
@@ -2356,6 +2372,8 @@ export class PluginMarketService {
plugin: VisiblePluginSummary | VisiblePluginDetail,
options: {
consent: GhostInstallConsentDecision;
+ /** The user agreed to reattach the library left under the bare id. */
+ reclaimLegacyBareInstance?: boolean;
expectedInstalledApproval?: string;
sourceReplacementMode: ServerSourceReplacementMode;
beforeCommitInLock?: () => void;
@@ -2437,6 +2455,7 @@ export class PluginMarketService {
pluginId: plugin.id,
version: plugin.currentRelease.version,
consent: options.consent,
+ ...(options.reclaimLegacyBareInstance && !installedNow ? { reclaimLegacyBareInstance: true } : {}),
...(sourceChanged ? { sourceChanged: true } : {}),
...deliveryNamespaceFields(plugin),
...(plugin.ghostId === 'cindy-github' && plugin.scope === 'public' &&
diff --git a/apps/desktop/src/preload/ghostPanelWindowPreload.ts b/apps/desktop/src/preload/ghostPanelWindowPreload.ts
index c2463f8aaa..5deaac5c95 100644
--- a/apps/desktop/src/preload/ghostPanelWindowPreload.ts
+++ b/apps/desktop/src/preload/ghostPanelWindowPreload.ts
@@ -8,7 +8,7 @@
* - 插件面板窗口状态(detach / attach)
* - 双阶段就绪握手 + visibility 刷新
* - 插件管理(list / reload / setEnabled / resolvePanelMedia / runtimeStates +
- * 事件订阅 onChanged / onRuntimeChanged / onPreviewMedia)
+ * 事件订阅 onChanged / onRuntimeChanged / onLibraryReplaced / onPreviewMedia)
* - 面板产物右键菜单媒体动作(copyMediaToClipboard / showItemInFolder)
* - 面板拖拽引渡落会话附件(cacheMediaForSession)
*
@@ -75,6 +75,7 @@ function fanOut(channel: string): (cb: (payload: unknown) => void) => Unsub {
const fanOutGhostsChanged = fanOut('ghosts:changed');
const fanOutGhostRuntimeChanged = fanOut('ghosts:runtime-changed');
+const fanOutGhostLibraryReplaced = fanOut('ghosts:library-replaced');
const fanOutGhostPreviewMedia = fanOut('ghosts:preview-media');
function onCurrentGhostBadge(
@@ -267,6 +268,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
onChanged: fanOutGhostsChanged,
/** 插件运行时状态变化(crashed / fused / off 等)。 */
onRuntimeChanged: fanOutGhostRuntimeChanged,
+ onLibraryReplaced: fanOutGhostLibraryReplaced,
/** 面板点图/视频预览(宿主弹 lightbox)。 */
onPreviewMedia: fanOutGhostPreviewMedia,
/** 未读角标快照(ghostUnreadStore 首帧)。 */
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 7cf8826cc6..cdb1a2a3c4 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -691,6 +691,8 @@ const fanOutGhostRecentUsageChanged = createIpcFanOut('ghosts:recent-usage-chang
const fanOutGhostInstallRequested = createIpcFanOut('ghosts:install-requested');
// 意识运行时状态广播(crashed/fused → 面板原地错误接管态)。
const fanOutGhostRuntimeChanged = createIpcFanOut('ghosts:runtime-changed');
+// 设置页接回旧作品库后,对应插件面板从磁盘重新加载。
+const fanOutGhostLibraryReplaced = createIpcFanOut('ghosts:library-replaced');
// 意识面板「点图看大图」推送(main 拦下 /preview/ 导航并过闸后推 cindy-media 地址)。
const fanOutGhostPreviewMedia = createIpcFanOut('ghosts:preview-media');
// 意识聊天卡片更新推送(卡槽③:card-update 过闸后带 html 全量推,renderer 免回查)。
@@ -1436,6 +1438,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
onRecentUsageChanged: fanOutGhostRecentUsageChanged,
onInstallRequested: fanOutGhostInstallRequested,
onRuntimeChanged: fanOutGhostRuntimeChanged,
+ onLibraryReplaced: fanOutGhostLibraryReplaced,
onPreviewMedia: fanOutGhostPreviewMedia,
onCardUpdated: fanOutGhostCardUpdated,
onSessionActivity: fanOutGhostSessionActivity,
@@ -1539,6 +1542,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('ghosts:library-unbind', id),
libraryDelete: (id: string): Promise<{ ok: boolean; cancelled?: boolean; message?: string }> =>
ipcRenderer.invoke('ghosts:library-delete', id),
+ /** 接回裸 id 下以前留下的作品数据;确认框由 Main 弹出。 */
+ libraryReattachLegacy: (id: string): Promise<{ ok: boolean; cancelled?: boolean; message?: string }> =>
+ ipcRenderer.invoke('ghosts:library-reattach-legacy', id),
legacyRecoveryStatus: (): Promise<
import('../shared/legacyGhostRecovery').LegacyGhostRecoveryStatus
> => ipcRenderer.invoke('ghosts:legacy-recovery-status'),
diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.ts
index 04b5408650..fdc43286c1 100644
--- a/apps/desktop/src/preload/sidebarWindowPreload.ts
+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts
@@ -307,6 +307,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
onChanged: (cb: (payload: unknown) => void): (() => void) => onPayload('ghosts:changed', cb),
onRuntimeChanged: (cb: (payload: unknown) => void): (() => void) =>
onPayload('ghosts:runtime-changed', cb),
+ onLibraryReplaced: (cb: (payload: unknown) => void): (() => void) =>
+ onPayload('ghosts:library-replaced', cb),
onPreviewMedia: (cb: (payload: unknown) => void): (() => void) =>
onPayload('ghosts:preview-media', cb),
unreadSync: (): { entries: unknown[] } => {
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostWebviewBody.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostWebviewBody.test.tsx
index 0e6be4fbc4..410e8b6881 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostWebviewBody.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostWebviewBody.test.tsx
@@ -1,6 +1,6 @@
/** @vitest-environment jsdom */
-import { fireEvent, render, waitFor } from '@testing-library/react';
+import { act, fireEvent, render, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
vi.mock('../ghostPanelTheme', () => ({
@@ -30,6 +30,28 @@ const manifest: GhostManifest = {
describe('GhostWebviewBody', () => {
afterEach(() => vi.unstubAllGlobals());
+ it('drops the panel during its library swap and reloads it afterwards', () => {
+ let notify: ((payload: { id: string; phase: 'start' | 'done' }) => void) | undefined;
+ vi.stubGlobal('electronAPI', { ghosts: { onLibraryReplaced: (callback: typeof notify) => {
+ notify = callback;
+ return () => { notify = undefined; };
+ } } });
+ const ghost = { manifest, dir: '/plugins/workspace', approval: { state: 'approved' as const, revision: 'receipt-a' } };
+ const { container, unmount } = render(<GhostWebviewBody ghost={ghost} html="panel.html" />);
+ const original = container.querySelector('webview');
+ act(() => notify?.({ id: 'another', phase: 'start' }));
+ expect(container.querySelector('webview')).toBe(original);
+ act(() => notify?.({ id: 'workspace', phase: 'start' }));
+ expect(container.querySelector('webview')).toBeNull();
+ expect(original?.isConnected).toBe(false);
+ act(() => notify?.({ id: 'workspace', phase: 'done' }));
+ const reloaded = container.querySelector('webview');
+ expect(reloaded).not.toBeNull();
+ expect(reloaded).not.toBe(original);
+ unmount();
+ expect(notify).toBeUndefined();
+ });
+
it.each(['panel.html', 'main-view.html'])('recreates %s on a same-version receipt replacement', (html) => {
const ghost = { manifest, dir: '/plugins/workspace', approval: { state: 'approved' as const, revision: 'receipt-a' } };
const { container, rerender } = render(<GhostWebviewBody ghost={ghost} html={html} />);
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
index 625b8de0cd..108c345b5b 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanelBody.tsx
@@ -206,6 +206,20 @@ export function GhostWebviewBody({
const partitionClaim = installedGhostWebviewPartitionClaim(ghost);
const [generation, setGeneration] = useState(0);
const [mediaMenu, setMediaMenu] = useState<GhostPanelMediaMenuState | null>(null);
+
+ // The host is swapping this instance's library on disk. Drop the webview
+ // until the swap and the partition clear finish, then load from disk again,
+ // so the old page cannot write its state over the swapped library.
+ const [librarySwapping, setLibrarySwapping] = useState(false);
+ useEffect(() => window.electronAPI?.ghosts?.onLibraryReplaced?.((payload) => {
+ if (payload?.id !== instanceId) return;
+ if (payload.phase === 'start') {
+ setLibrarySwapping(true);
+ return;
+ }
+ setLibrarySwapping(false);
+ setGeneration((value) => value + 1);
+ }), [instanceId]);
const hostRef = useRef<HTMLDivElement | null>(null);
const setHostNode = useCallback(
(el: HTMLDivElement | null) => {
@@ -216,7 +230,7 @@ export function GhostWebviewBody({
);
useEffect(() => {
- if (crashed || !html) return;
+ if (crashed || !html || librarySwapping) return;
const host = hostRef.current;
if (!host) return;
const webview = document.createElement('webview') as WebviewTag;
@@ -293,7 +307,7 @@ export function GhostWebviewBody({
};
// version 入依赖:原位更新换版后 webview 重挂载,面板立刻跑新代码
// (供片协议直读安装目录,不重挂会一直渲染旧版缓存的页面)。
- }, [crashed, generation, instanceId, approvalToken, partitionClaim, manifest.id, manifest.version, manifest.resolvedLocale, html]);
+ }, [crashed, generation, librarySwapping, instanceId, approvalToken, partitionClaim, manifest.id, manifest.version, manifest.resolvedLocale, html]);
if (crashed) {
return (
diff --git a/apps/desktop/src/renderer/features/plugin/GhostLibrarySection.tsx b/apps/desktop/src/renderer/features/plugin/GhostLibrarySection.tsx
index ec049b5683..b4b2d0484a 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostLibrarySection.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostLibrarySection.tsx
@@ -48,7 +48,7 @@ function GhostLibrarySectionInner({ ghostId }: { ghostId: string }) {
const { t } = useTranslation();
const { confirm } = useConfirmDialog();
const [overview, setOverview] = useState<GhostLibraryOverview | null>(null);
- const [busy, setBusy] = useState<'relocate' | 'delete' | null>(null);
+ const [busy, setBusy] = useState<'relocate' | 'delete' | 'reattach' | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const refresh = useCallback(async () => {
@@ -153,6 +153,23 @@ function GhostLibrarySectionInner({ ghostId }: { ghostId: string }) {
}
};
+ const handleReattachLegacy = async () => {
+ if (busy) return;
+ // 确认框由 Main 弹出(换掉当前作品数据,唯一有效确认在 Main)。
+ setBusy('reattach');
+ try {
+ const res = await window.electronAPI.ghosts.libraryReattachLegacy(ghostId);
+ if (res.ok) toast.success(t('settings.ghosts.library.legacyReattachDone'));
+ else if (!res.cancelled) {
+ const failed = t('settings.ghosts.library.legacyReattachFailed');
+ toast.error(res.message ? `${failed}:${res.message}` : failed);
+ }
+ } finally {
+ setBusy(null);
+ void refresh();
+ }
+ };
+
return (
<section className={SECTION_CLASS} aria-labelledby="ghost-library-title">
<div className="flex items-center justify-between">
@@ -190,6 +207,32 @@ function GhostLibrarySectionInner({ ghostId }: { ghostId: string }) {
{overview.orphaned ? (
<p className="mb-3 text-13 text-[var(--text-secondary)]">{t('settings.ghosts.library.orphanedBanner')}</p>
) : null}
+ {overview.legacyLibraryInUse ? (
+ <p className="mb-3 text-13 text-[var(--text-secondary)]">{t('settings.ghosts.library.legacyInUseBanner')}</p>
+ ) : null}
+ {overview.legacyLibrary ? (
+ <div className="mb-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
+ <p className="min-w-0 flex-1 text-13 text-[var(--text-secondary)]">
+ {t(
+ overview.legacyLibrary.provenance === 'unknown'
+ ? 'settings.ghosts.library.legacyFoundUnknownBanner'
+ : 'settings.ghosts.library.legacyFoundBanner',
+ {
+ size: formatBytes(overview.legacyLibrary.usedBytes),
+ count: overview.legacyLibrary.fileCount,
+ },
+ )}
+ </p>
+ <button
+ type="button"
+ className={ACTION_BUTTON_CLASS}
+ disabled={busy !== null}
+ onClick={() => void handleReattachLegacy()}
+ >
+ {busy === 'reattach' ? t('settings.ghosts.library.legacyReattachBusy') : t('settings.ghosts.library.legacyReattach')}
+ </button>
+ </div>
+ ) : null}
<div className="space-y-2">
<div className={ROW_CLASS}>
<span className="text-[var(--text-secondary)]">{t('settings.ghosts.library.locationLabel')}</span>
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 0a701ece80..307a1af5dd 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -6603,7 +6603,23 @@
"installLocationPickedPrefix": "Selected:",
"installLocationChange": "Change…",
"bindAfterInstallFailed": "Failed to set the custom storage location; fell back to the default",
- "cancel": "Cancel"
+ "cancel": "Cancel",
+ "reattachTitle": "Reattach this plugin's earlier work data?",
+ "reattachDescription": "This computer still has work data from an earlier install of this plugin, possibly a locally imported version that was later uninstalled. Reattach it to keep your earlier canvases and images in this install. If you skip, this install starts empty and the earlier data stays on this computer.",
+ "reattachConfirm": "Reattach",
+ "reattachSkip": "Don't reattach",
+ "legacyFoundBanner": "This computer still has earlier work data from this plugin ({{size}} · {{count}} files) that the current install does not use.",
+ "legacyReattach": "Reattach earlier work data",
+ "legacyReattachBusy": "Reattaching…",
+ "legacyReattachConfirmTitle": "Reattach earlier work data?",
+ "legacyReattachConfirmDescription": "The plugin will use the earlier work data instead. Its current work data is moved to the trash and kept for 30 days, then permanently removed.",
+ "legacyReattachConfirmText": "Reattach",
+ "legacyReattachDone": "Earlier work data reattached",
+ "legacyReattachFailed": "Reattach failed",
+ "legacyReattachNeedsRestart": "This plugin's cache could not be cleared. Restart Cindy before using the plugin again.",
+ "legacyInUseBanner": "Another install on this computer (such as a local copy) is still using this plugin's earlier work data. Uninstall that install to reattach the data here.",
+ "legacyFoundUnknownBanner": "This computer has work data that may have been left by this plugin ({{size}} · {{count}} files). It has no source record, and the current install does not use it.",
+ "legacyReattachUnknownSource": "This work data has no source record. It may have been copied in by hand or by a script. Make sure it belongs to this plugin."
},
"updateConfirm": {
"title": "Update plugin \"{{name}}\"?",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 4defb76fe4..53a8e08701 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -6578,7 +6578,23 @@
"installLocationPickedPrefix": "選択済み:",
"installLocationChange": "変更…",
"bindAfterInstallFailed": "カスタム保存場所の設定に失敗したため、既定の場所に戻しました",
- "cancel": "キャンセル"
+ "cancel": "キャンセル",
+ "reattachTitle": "このプラグインの以前の作品データを引き継ぎますか?",
+ "reattachDescription": "このコンピューターには、このプラグインを以前インストールしたときの作品データが残っています。以前ローカルから読み込み、その後アンインストールしたバージョンのものかもしれません。引き継ぐと、以前のキャンバスや画像を今回インストールしたプラグインで引き続き使えます。引き継がない場合は空の状態から始まり、以前のデータはこのコンピューターに残ります。",
+ "reattachConfirm": "引き継ぐ",
+ "reattachSkip": "引き継がない",
+ "legacyFoundBanner": "このコンピューターには、このプラグインが以前残した作品データ({{size}} · {{count}} ファイル)があり、現在のインストールでは使われていません。",
+ "legacyReattach": "以前の作品データを引き継ぐ",
+ "legacyReattachBusy": "引き継ぎ中…",
+ "legacyReattachConfirmTitle": "以前の作品データを引き継ぎますか?",
+ "legacyReattachConfirmDescription": "プラグインは以前の作品データを使うようになります。現在の作品データはごみ箱に移動され 30 日間保持された後、完全に消去されます。",
+ "legacyReattachConfirmText": "引き継ぐ",
+ "legacyReattachDone": "以前の作品データを引き継ぎました",
+ "legacyReattachFailed": "引き継ぎに失敗しました",
+ "legacyReattachNeedsRestart": "このプラグインのキャッシュを消去できませんでした。Cindy を再起動してからプラグインを使ってください。",
+ "legacyInUseBanner": "このコンピューター上の別のインストール(ローカル版など)が、このプラグインの以前の作品データをまだ使っています。そのインストールをアンインストールすると、ここで引き継げます。",
+ "legacyFoundUnknownBanner": "このコンピューターには、このプラグインが以前残した可能性のある作品データ({{size}} · {{count}} ファイル)があります。出所の記録がなく、現在のインストールでは使われていません。",
+ "legacyReattachUnknownSource": "この作品データには出所の記録がありません。手動またはスクリプトでコピーされた可能性があります。このプラグインのものか確認してください。"
},
"updateConfirm": {
"title": "プラグイン「{{name}}」を更新しますか?",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index dffa9692e3..f3e7444cd9 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -6578,7 +6578,23 @@
"installLocationPickedPrefix": "선택됨:",
"installLocationChange": "변경…",
"bindAfterInstallFailed": "사용자 지정 저장 위치 설정에 실패하여 기본 위치로 되돌렸습니다",
- "cancel": "취소"
+ "cancel": "취소",
+ "reattachTitle": "이 플러그인의 이전 작업 데이터를 다시 연결할까요?",
+ "reattachDescription": "이 컴퓨터에 이 플러그인을 이전에 설치했을 때의 작업 데이터가 남아 있습니다. 이전에 로컬에서 가져온 후 제거한 버전의 데이터일 수 있습니다. 다시 연결하면 이전 캔버스와 이미지를 이번에 설치한 플러그인에서 계속 사용할 수 있습니다. 연결하지 않으면 빈 상태로 시작하며, 이전 데이터는 이 컴퓨터에 그대로 남습니다.",
+ "reattachConfirm": "다시 연결",
+ "reattachSkip": "연결 안 함",
+ "legacyFoundBanner": "이 컴퓨터에 이 플러그인이 이전에 남긴 작업 데이터({{size}} · 파일 {{count}}개)가 있지만, 현재 설치에서는 사용하지 않고 있습니다.",
+ "legacyReattach": "이전 작업 데이터 다시 연결",
+ "legacyReattachBusy": "다시 연결하는 중…",
+ "legacyReattachConfirmTitle": "이전 작업 데이터를 다시 연결할까요?",
+ "legacyReattachConfirmDescription": "플러그인이 이전 작업 데이터를 사용하게 됩니다. 현재 작업 데이터는 휴지통으로 옮겨져 30일간 보관된 후 완전히 삭제됩니다.",
+ "legacyReattachConfirmText": "다시 연결",
+ "legacyReattachDone": "이전 작업 데이터를 다시 연결했습니다",
+ "legacyReattachFailed": "다시 연결하지 못했습니다",
+ "legacyReattachNeedsRestart": "이 플러그인의 캐시를 지우지 못했습니다. Cindy를 다시 시작한 뒤 플러그인을 사용하세요.",
+ "legacyInUseBanner": "이 컴퓨터의 다른 설치(예: 로컬 버전)가 이 플러그인의 이전 작업 데이터를 아직 사용하고 있습니다. 그 설치를 제거하면 여기에서 다시 연결할 수 있습니다.",
+ "legacyFoundUnknownBanner": "이 컴퓨터에 이 플러그인이 이전에 남긴 것으로 보이는 작업 데이터({{size}} · 파일 {{count}}개)가 있습니다. 출처 기록이 없으며 현재 설치에서는 사용하지 않고 있습니다.",
+ "legacyReattachUnknownSource": "이 작업 데이터에는 출처 기록이 없습니다. 수동이나 스크립트로 복사되었을 수 있습니다. 이 플러그인의 데이터가 맞는지 확인하세요."
},
"updateConfirm": {
"title": "플러그인 \"{{name}}\"을(를) 업데이트할까요?",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 33aef31025..c7b0272b10 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -6578,7 +6578,23 @@
"installLocationPickedPrefix": "已选择:",
"installLocationChange": "更改…",
"bindAfterInstallFailed": "自定义存储位置设置失败,已回退默认位置",
- "cancel": "取消"
+ "cancel": "取消",
+ "reattachTitle": "接回这个插件以前的作品数据?",
+ "reattachDescription": "本机还保留着这个插件以前安装时的作品数据,可能来自之前从本地导入、后来卸载的版本。接回后,以前的画布和图片会继续出现在这次安装的插件里;不接回则从空白开始,以前的数据仍保留在本机。",
+ "reattachConfirm": "接回",
+ "reattachSkip": "不接回",
+ "legacyFoundBanner": "这台电脑上还有这个插件以前留下的作品数据({{size}} · {{count}} 个文件),当前安装没有使用它。",
+ "legacyReattach": "接回以前的作品数据",
+ "legacyReattachBusy": "正在接回…",
+ "legacyReattachConfirmTitle": "接回以前的作品数据?",
+ "legacyReattachConfirmDescription": "插件会改用以前留下的作品数据。当前的作品数据会移入回收站,保留 30 天,期满后彻底清除。",
+ "legacyReattachConfirmText": "接回",
+ "legacyReattachDone": "已接回以前的作品数据",
+ "legacyReattachFailed": "接回失败",
+ "legacyReattachNeedsRestart": "没能清掉这个插件的缓存。请重启 Cindy 后再使用这个插件。",
+ "legacyInUseBanner": "这台电脑上另一个安装(例如本地版)还在使用这个插件以前的作品数据。卸载那个安装后,可以在这里接回。",
+ "legacyFoundUnknownBanner": "这台电脑上有一份可能是这个插件以前留下的作品数据({{size}} · {{count}} 个文件),没有来源记录,当前安装没有使用它。",
+ "legacyReattachUnknownSource": "这份作品数据没有来源记录,可能是手动复制或用脚本搬过来的。请确认它属于这个插件。"
},
"updateConfirm": {
"title": "更新插件「{{name}}」?",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index daf6ba3c90..ac36d4f413 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -6578,7 +6578,23 @@
"installLocationPickedPrefix": "已選擇:",
"installLocationChange": "更改…",
"bindAfterInstallFailed": "自訂儲存位置設定失敗,已回退預設位置",
- "cancel": "取消"
+ "cancel": "取消",
+ "reattachTitle": "接回這個插件以前的作品資料?",
+ "reattachDescription": "這台電腦還保留著這個插件以前安裝時的作品資料,可能來自之前從本機匯入、後來解除安裝的版本。接回後,以前的畫布和圖片會繼續出現在這次安裝的插件裡;不接回則從空白開始,以前的資料仍保留在這台電腦上。",
+ "reattachConfirm": "接回",
+ "reattachSkip": "不接回",
+ "legacyFoundBanner": "這台電腦上還有這個插件以前留下的作品資料({{size}} · {{count}} 個檔案),目前的安裝沒有使用它。",
+ "legacyReattach": "接回以前的作品資料",
+ "legacyReattachBusy": "正在接回…",
+ "legacyReattachConfirmTitle": "接回以前的作品資料?",
+ "legacyReattachConfirmDescription": "插件會改用以前留下的作品資料。目前的作品資料會移入回收站,保留 30 天,期滿後徹底清除。",
+ "legacyReattachConfirmText": "接回",
+ "legacyReattachDone": "已接回以前的作品資料",
+ "legacyReattachFailed": "接回失敗",
+ "legacyReattachNeedsRestart": "沒能清掉這個插件的快取。請重新啟動 Cindy 後再使用這個插件。",
+ "legacyInUseBanner": "這台電腦上另一個安裝(例如本機版)還在使用這個插件以前的作品資料。解除安裝那個版本後,可以在這裡接回。",
+ "legacyFoundUnknownBanner": "這台電腦上有一份可能是這個插件以前留下的作品資料({{size}} · {{count}} 個檔案),沒有來源記錄,目前的安裝沒有使用它。",
+ "legacyReattachUnknownSource": "這份作品資料沒有來源記錄,可能是手動複製或用腳本搬過來的。請確認它屬於這個插件。"
},
"updateConfirm": {
"title": "更新插件「{{name}}」?",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 6631fc9702..4873c00e01 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1444,6 +1444,8 @@ interface ElectronAPI {
) => () => void;
/** 双击 .cindy 转交信号:收到后调 takePendingInstall 取路径走一键装入流程。 */
onInstallRequested: (callback: () => void) => () => void;
+ /** 设置页接回旧作品库:start 时对应插件面板先卸下,done 时从磁盘重新挂上。 */
+ onLibraryReplaced: (callback: (payload: { id: string; phase: 'start' | 'done' }) => void) => () => void;
/** 运行时状态广播:crashed / fused 时面板原地显示错误接管态。 */
onRuntimeChanged: (
callback: (payload: { states: Record<string, string> }) => void,
@@ -1665,6 +1667,7 @@ interface ElectronAPI {
libraryRevertDefault: (id: string) => Promise<{ ok: boolean; message?: string }>;
libraryUnbind: (id: string) => Promise<{ ok: boolean; message?: string }>;
libraryDelete: (id: string) => Promise<{ ok: boolean; cancelled?: boolean; message?: string }>;
+ libraryReattachLegacy: (id: string) => Promise<{ ok: boolean; cancelled?: boolean; message?: string }>;
legacyRecoveryStatus: () => Promise<
import('../shared/legacyGhostRecovery').LegacyGhostRecoveryStatus
>;
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index cbd62fc8f1..477e3fe67b 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -8534,6 +8534,18 @@ export interface GhostLibraryOverview {
softLimitExceeded: boolean;
/** 卸载后未删除的标记(重装自动清除;设置页以横幅提示)。 */
orphaned: boolean;
+ /**
+ * 裸 id 下还留着这个插件以前的作品库,可以换回当前实例(设置页提供「接回」)。
+ * 没有可接回的旧库时为 null。
+ */
+ legacyLibrary: {
+ usedBytes: number;
+ fileCount: number;
+ /** uninstalled = 卸载时留下;unknown = 没有宿主身份记录,来源无法证明。 */
+ provenance: 'uninstalled' | 'unknown';
+ } | null;
+ /** 裸 id 下的旧作品库还被本机另一个安装(例如本地版)使用着,卸载它后才能接回。 */
+ legacyLibraryInUse: boolean;
}
/** 上行:主机代理 fetch 请求。 */
diff --git a/docs/dev-rules/plugin-library-storage.md b/docs/dev-rules/plugin-library-storage.md
index 923690d1f9..b25dcbaf08 100644
--- a/docs/dev-rules/plugin-library-storage.md
+++ b/docs/dev-rules/plugin-library-storage.md
@@ -36,9 +36,13 @@ owners/<ownerKey>/
├── libraries/<ghostId>/ # 系统管理默认根
├── libraries-binding.json # 自定义位置持久 binding(原子写)
├── libraries-trash/<ghostId>-<ts>/ # 删除通道的 30 天回收站
+├── library-reattach.json # 设置页「接回以前的作品数据」未完成时的日志
└── library-staging/<ghostId>/ # H1 上传 staging(不可随 Library 根迁移)
```
+这里的 `<ghostId>` 是实例键(`installedGhostStoragePart`):升级前的旧安装是裸 id,
+namespace 之后的新安装是 `_ns__<org>__<id>` / `_root__<id>`。
+
自定义根 = `<用户所选父目录>/<ghostId>`(binding 记录 realpath 快照 + 文件
identity + generation)。库内宿主命名空间 `.cindy-library/`(meta/usage/tmp/
backups)对插件不可达——路径语法段首不许点,协议层天然隔离。
@@ -62,6 +66,25 @@ backups)对插件不可达——路径语法段首不许点,协议层天然
事实不因重装消失)。删除 = 设置页独立破坏性确认 + `trashGhostLibrary`
(rename 进回收站,漂移时 NOT_FOUND 不误删)。内置插件退役清理
(`cleanupRetiredGhostData`)**不得**触及 Library。
+ **重装接回**:企业市场首次安装若找不到可复用的实例记录,市场账本又证明裸 id 下的
+ 旧库属于同一插件编号、同一组织(升级前已卸载、未打 namespace 标记),安装直接收回
+ 裸 id 键,旧库与 binding 原样接上;证明不了但裸 id 下有旧库时,由 Main 在安装确认
+ 之后询问用户(后台 / 默认安装不询问,按新键)。已经拿到新键空库的实例,可在设置页
+ 「接回以前的作品数据」:当前库与 staging 进回收站,旧库改名到当前实例键,meta 改身份
+ 并清掉 orphaned;没有 `.cindy-library` 的旧目录按「来源不明」提示,接回时补写 meta。
+ 动手前写 `library-reattach.json`(写完刷盘所在目录),每步可重跑,下次作品库请求或打开
+ 设置页时续完;续完失败只拦日志里的两个库,其他插件照常读写。所有改名与 meta 改写
+ 刷盘后才删日志。自定义位置的旧库在写日志前先确认能按目录身份搬(不提供 inode 的卷
+ 直接拒绝)、目标没有 binding 且自定义父目录下没有同名目录;
+ 换库前停插件运行时并卸下面板;面板与后台页走同源 BroadcastChannel,Main 不在中间,
+ 所以 Main 还会关掉该实例分区里仍开着的页面并等它们销毁。换完再关一次旧页、清掉
+ 该实例的 Electron 分区存储(内存分区,面板与后台共用,不清会把旧库的缓存写进新库),
+ 再重启运行时、让面板从磁盘重新挂上。清分区重试后仍失败,插件保持停止、作品库保持
+ 拦截,提示用户重启 Cindy;Main 记下该实例,面板挂载、插件运行时与 Node 运行时启动
+ (含 /wake、重载、常驻拉起)都拒绝,直到应用重启。未完成的接回只在真正打开作品库的请求里续完(能力查询与
+ 资格不符的请求不触发);报给界面的失败只用通用文案,原始错误留在 Main 日志。
+ 属于其他组织或仍在启用的记录不让出裸 id;裸 id 被启用中的安装(如本地版)占用时,
+ 设置页只提示占用、不给接回;接回只动作品库与 staging,不碰密钥、账号、KV 与私有目录。
3. **owner 隔离**:会话绑定 `activeOwnerScopeKey` 每请求比对;切换在途由
`interruptGhostCallsForAccountBoundary` 的 `disposeAll` 收口(在途写入随串行
链归属原 owner)。根解析每次经 binding store 现解。