Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 账号迁移后恢复遗留插件 (#398)
DavidShenXD5fc1834a91d9
diff --git a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.tsindex b9362d4cc6..77822c90b5 100644--- a/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts+++ b/apps/desktop/src/main/__tests__/ownerNamespaceMigration.test.ts@@ -6,7 +6,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { dataOwnerStorageKey } from '../appSessionState.js';import {claimLegacyOwnerNamespace,+ getLegacyGhostRecoveryStatus,hasLegacyOwnerNamespaceClaim,+ listLegacyGhostTombstoneRoots,+ recoverLegacyGhostPlugins,__testing,} from '../ownerNamespaceMigration.js';@@ -38,6 +41,10 @@ afterEach(async () => {await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));});+beforeEach(() => {+ __testing.resetLegacyGhostRecoveryState();+});+describe('claimLegacyOwnerNamespace', () => {it.each(['local', 'signed-out'] as const)('%s never resolves or scans userData', async (mode) => {const userDataDir = vi.fn(() => {@@ -217,7 +224,11 @@ describe('claimLegacyOwnerNamespace', () => {const result = await claimLegacyOwnerNamespace({ mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },- realFsDeps(root, { isPidAlive: (pid) => pid === 4242 }),+ realFsDeps(+ root,+ { isPidAlive: (pid) => pid === 4242 },+ { readlink: () => Promise.resolve('myhost-4242') },+ ),);expect(result).toEqual({@@ -236,7 +247,8 @@ describe('claimLegacyOwnerNamespace', () => {const result = await claimLegacyOwnerNamespace({ mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },- realFsDeps(root), // isPidAlive 恒 false = 崩溃残留+ realFsDeps(root, {}, { readlink: () => Promise.resolve('myhost-4242') }),+ // isPidAlive 恒 false = 崩溃残留);expect(result).toMatchObject({ status: 'migrated' });@@ -436,6 +448,934 @@ describe('claimLegacyOwnerNamespace', () => {});});+describe('legacy Ghost plugin recovery', () => {+ it('does not follow a linked legacy repository root', async () => {+ const root = await tempRoot();+ const externalRoot = await tempRoot();+ await writeGhostDirAtPath(+ path.join(externalRoot, 'external-plugin'),+ 'external-plugin',+ );+ await fs.symlink(+ externalRoot,+ path.join(root, 'brain'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ realFsDeps(root),+ ),+ ).resolves.toEqual({ status: 'skipped', moved: 0, conflicts: 0 });+ await expect(+ fs.readFile(path.join(externalRoot, 'external-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"id":"external-plugin"');+ await expect(+ fs.access(+ path.join(+ root,+ 'owners',+ dataOwnerStorageKey('cloud-a'),+ 'cindy-brain',+ 'external-plugin',+ ),+ ),+ ).rejects.toThrow();+ });++ it('does not move linked legacy plugin directories', async () => {+ const root = await tempRoot();+ const externalRoot = await tempRoot();+ const linkedPlugin = path.join(externalRoot, 'linked-plugin');+ await writeGhostDirAtPath(linkedPlugin, 'linked-plugin');+ await fs.mkdir(path.join(root, 'brain'), { recursive: true });+ await fs.symlink(+ linkedPlugin,+ path.join(root, 'brain', 'linked-plugin'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ realFsDeps(root),+ ),+ ).resolves.toEqual({ status: 'skipped', moved: 0, conflicts: 0 });+ await expect(+ fs.readFile(path.join(linkedPlugin, 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"id":"linked-plugin"');+ await expect(+ fs.access(+ path.join(+ root,+ 'owners',+ dataOwnerStorageKey('cloud-a'),+ 'cindy-brain',+ 'linked-plugin',+ ),+ ),+ ).rejects.toThrow();+ });++ it('does not follow a linked owner-scoped recovery destination', async () => {+ const root = await tempRoot();+ const externalRoot = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ await writeGhostDir(root, 'brain', 'legacy-plugin');+ const ownerRoot = path.join(root, 'owners', ownerKey);+ await fs.mkdir(ownerRoot, { recursive: true });+ await fs.symlink(+ externalRoot,+ path.join(ownerRoot, 'cindy-brain'),+ process.platform === 'win32' ? 'junction' : 'dir',+ );++ expect(+ getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ root,+ ),+ ).toEqual({+ state: 'partial',+ legacyPluginCount: 1,+ canRetry: false,+ });+ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ ),+ ).resolves.toMatchObject({ status: 'partial', moved: 0, conflicts: 1 });+ await expect(+ fs.readFile(path.join(root, 'brain', 'legacy-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"id":"legacy-plugin"');+ await expect(fs.access(path.join(externalRoot, 'legacy-plugin'))).rejects.toThrow();+ });++ it('does not restore plugins whose command conflicts with an installed plugin', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ await writeGhostDirAtPath(+ path.join(root, 'brain', 'legacy-plugin'),+ 'legacy-plugin',+ 'Draw',+ );+ const targetRoot = path.join(root, 'owners', ownerKey, 'cindy-brain');+ await writeGhostDirAtPath(+ path.join(targetRoot, 'current-plugin'),+ 'current-plugin',+ 'draw',+ );++ expect(+ getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ root,+ ),+ ).toEqual({+ state: 'partial',+ legacyPluginCount: 1,+ canRetry: false,+ });+ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ ),+ ).resolves.toMatchObject({ status: 'partial', moved: 0, conflicts: 1 });+ await expect(+ fs.readFile(path.join(root, 'brain', 'legacy-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"command":"Draw"');+ await expect(fs.access(path.join(targetRoot, 'legacy-plugin'))).rejects.toThrow();+ await expect(fs.access(path.join(root, __testing.CLAIM_MARKER))).rejects.toThrow();+ });++ it('does not restore plugins whose command is reserved for a builtin seed', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ await writeGhostDirAtPath(+ path.join(root, 'brain', 'custom-plugin'),+ 'custom-plugin',+ 'Draw',+ );++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ { reservedCommands: new Set(['draw']) },+ ),+ ).resolves.toMatchObject({ status: 'partial', moved: 0, conflicts: 1 });+ await expect(+ fs.readFile(path.join(root, 'brain', 'custom-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"command":"Draw"');+ });++ it('derives retryability from bundled command reservations', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ await writeGhostDirAtPath(+ path.join(root, 'brain', 'custom-plugin'),+ 'custom-plugin',+ 'Draw',+ );++ expect(+ getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ root,+ false,+ { reservedCommands: new Set(['draw']) },+ ),+ ).toEqual({+ state: 'partial',+ legacyPluginCount: 1,+ canRetry: false,+ });+ });++ it('ignores tombstones from a foreign shared root during recovery planning', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const foreignOwnerKey = dataOwnerStorageKey('cloud-b');+ const scopedRoot = path.join(root, 'owners', dataOwnerStorageKey(ownerId), 'brain');+ await writeGhostDir(root, 'brain', 'shared-plugin');+ await writeGhostDirAtPath(path.join(scopedRoot, 'scoped-plugin'), 'scoped-plugin', 'Draw');+ await fs.writeFile(+ path.join(root, __testing.CLAIM_MARKER),+ JSON.stringify({ version: 1, ownerKey: foreignOwnerKey, complete: true }),+ );+ await fs.writeFile(+ path.join(root, 'brain', '.builtin-provisioning.json'),+ JSON.stringify({ removed: ['draw'] }),+ );++ expect(listLegacyGhostTombstoneRoots(ownerId, root)).toEqual([scopedRoot]);+ });++ it('does not restore reserved plugin IDs when packaged recovery protection is enabled', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ await writeGhostDir(root, 'brain', 'cindy-untrusted');++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ { rejectReservedIds: true },+ ),+ ).resolves.toMatchObject({ status: 'partial', moved: 0, conflicts: 1 });+ await expect(+ fs.readFile(path.join(root, 'brain', 'cindy-untrusted', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"id":"cindy-untrusted"');+ });++ it('moves builtin provisioning state with plugins before reconciliation', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ await writeGhostDir(root, 'brain', 'seeded-plugin');+ const state = {+ removed: ['removed-builtin'],+ seeded: ['seeded-plugin'],+ };+ await fs.writeFile(+ path.join(root, 'brain', '.builtin-provisioning.json'),+ JSON.stringify(state),+ );++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ ),+ ).resolves.toMatchObject({+ status: 'migrated',+ moved: 1,+ conflicts: 0,+ provisioningStateMoved: true,+ });+ await expect(+ fs.readFile(+ path.join(+ root,+ 'owners',+ ownerKey,+ 'cindy-brain',+ '.builtin-provisioning.json',+ ),+ 'utf-8',+ ),+ ).resolves.toBe(JSON.stringify(state));+ await expect(+ fs.access(path.join(root, 'brain', '.builtin-provisioning.json')),+ ).rejects.toThrow();+ });++ it('does not move plugins when builtin provisioning state would conflict', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ await writeGhostDir(root, 'brain', 'seeded-plugin');+ await fs.writeFile(+ path.join(root, 'brain', '.builtin-provisioning.json'),+ JSON.stringify({ removed: ['legacy'], seeded: [] }),+ );+ const targetRoot = path.join(root, 'owners', ownerKey, 'cindy-brain');+ await fs.mkdir(targetRoot, { recursive: true });+ await fs.writeFile(+ path.join(targetRoot, '.builtin-provisioning.json'),+ JSON.stringify({ removed: ['current'], seeded: [] }),+ );++ expect(+ getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ root,+ ),+ ).toEqual({+ state: 'partial',+ legacyPluginCount: 1,+ canRetry: false,+ });+ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ ),+ ).resolves.toMatchObject({ status: 'partial', moved: 0, conflicts: 1 });+ await expect(+ fs.readFile(path.join(root, 'brain', 'seeded-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"id":"seeded-plugin"');+ await expect(+ fs.readFile(path.join(targetRoot, '.builtin-provisioning.json'), 'utf-8'),+ ).resolves.toContain('current');+ });++ it('does not reserve commands from roots blocked by provisioning preflight', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ const blockedRoot = path.join(root, 'cindy-brain');+ const safeRoot = path.join(root, 'brain');+ const targetRoot = path.join(root, 'owners', ownerKey, 'cindy-brain');+ await writeGhostDirAtPath(+ path.join(blockedRoot, 'blocked-plugin'),+ 'blocked-plugin',+ 'Draw',+ );+ await writeGhostDirAtPath(path.join(safeRoot, 'safe-plugin'), 'safe-plugin', 'draw');+ await fs.mkdir(targetRoot, { recursive: true });+ await fs.writeFile(+ path.join(blockedRoot, '.builtin-provisioning.json'),+ JSON.stringify({ removed: [], seeded: ['blocked-plugin'] }),+ );+ await fs.writeFile(+ path.join(targetRoot, '.builtin-provisioning.json'),+ JSON.stringify({ removed: [], seeded: [] }),+ );++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ ),+ ).resolves.toMatchObject({ status: 'partial', moved: 1, conflicts: 1 });+ await expect(+ fs.readFile(path.join(targetRoot, 'safe-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"id":"safe-plugin"');+ await expect(+ fs.readFile(path.join(blockedRoot, 'blocked-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"id":"blocked-plugin"');+ });++ it('aborts before moving builtin provisioning state when the owner changes', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ await writeGhostDir(root, 'brain', 'seeded-plugin');+ await fs.writeFile(+ path.join(root, 'brain', '.builtin-provisioning.json'),+ JSON.stringify({ removed: [], seeded: ['seeded-plugin'] }),+ );+ let checks = 0;++ const result = await recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ { shouldAbort: () => ++checks >= 4 },+ );++ expect(result).toMatchObject({ status: 'partial', moved: 0 });+ await expect(+ fs.readFile(path.join(root, 'brain', '.builtin-provisioning.json'), 'utf-8'),+ ).resolves.toContain('seeded-plugin');+ await expect(+ fs.access(+ path.join(root, 'owners', ownerKey, 'cindy-brain', '.builtin-provisioning.json'),+ ),+ ).rejects.toThrow();+ });++ it('rolls back builtin provisioning state when the owner changes during rename', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ await writeGhostDir(root, 'brain', 'seeded-plugin');+ const sourceState = path.join(root, 'brain', '.builtin-provisioning.json');+ const targetState = path.join(+ root,+ 'owners',+ ownerKey,+ 'cindy-brain',+ '.builtin-provisioning.json',+ );+ await fs.writeFile(+ sourceState,+ JSON.stringify({ removed: [], seeded: ['seeded-plugin'] }),+ );+ let boundaryPending = false;+ const deps = realFsDeps(+ root,+ {},+ {+ rename: async (source: string, target: string) => {+ await fs.rename(source, target);+ if (source === sourceState && target === targetState) boundaryPending = true;+ },+ },+ );++ const result = await recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ deps,+ { shouldAbort: () => boundaryPending },+ );++ expect(result).toMatchObject({ status: 'partial', moved: 0 });+ await expect(fs.readFile(sourceState, 'utf-8')).resolves.toContain('seeded-plugin');+ await expect(fs.access(targetState)).rejects.toThrow();+ await expect(+ fs.readFile(path.join(root, 'brain', 'seeded-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('seeded-plugin');+ });++ it('keeps moved provisioning state when a peer appears before rollback', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ await writeGhostDir(root, 'brain', 'seeded-plugin');+ await writeDevInstanceRecord(root, 4242);+ const sourceState = path.join(root, 'brain', '.builtin-provisioning.json');+ const targetState = path.join(+ root,+ 'owners',+ ownerKey,+ 'cindy-brain',+ '.builtin-provisioning.json',+ );+ await fs.writeFile(+ sourceState,+ JSON.stringify({ removed: [], seeded: ['seeded-plugin'] }),+ );+ let boundaryPending = false;+ let peerStarted = false;+ const deps = realFsDeps(+ root,+ { isPidAlive: (pid) => peerStarted && pid === 4242 },+ {+ rename: async (source: string, target: string) => {+ await fs.rename(source, target);+ if (source === sourceState && target === targetState) {+ boundaryPending = true;+ peerStarted = true;+ }+ },+ },+ );++ const result = await recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ deps,+ { shouldAbort: () => boundaryPending },+ );++ expect(result).toMatchObject({+ status: 'partial',+ moved: 0,+ provisioningStateMoved: true,+ });+ await expect(fs.access(sourceState)).rejects.toThrow();+ await expect(fs.readFile(targetState, 'utf-8')).resolves.toContain('seeded-plugin');+ });++ it('reports a provisioning-state move even when the plugin rename fails', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ await writeGhostDir(root, 'brain', 'seeded-plugin');+ await fs.writeFile(+ path.join(root, 'brain', '.builtin-provisioning.json'),+ JSON.stringify({ removed: [], seeded: ['seeded-plugin'] }),+ );+ const deps = realFsDeps(+ root,+ {},+ {+ rename: (source: string, target: string) =>+ path.basename(source) === '.builtin-provisioning.json'+ ? fs.rename(source, target)+ : Promise.reject(Object.assign(new Error('rename denied'), { code: 'EACCES' })),+ },+ );++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ deps,+ ),+ ).resolves.toMatchObject({+ status: 'partial',+ moved: 0,+ conflicts: 0,+ provisioningStateMoved: true,+ });+ await expect(+ fs.readFile(+ path.join(root, 'owners', ownerKey, 'cindy-brain', '.builtin-provisioning.json'),+ 'utf-8',+ ),+ ).resolves.toContain('seeded-plugin');+ await expect(+ fs.readFile(path.join(root, 'brain', 'seeded-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('seeded-plugin');+ });++ it('moves only valid legacy plugins and leaves other owner data in place', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ await writeGhostDir(root, 'cindy-brain', 'valid-plugin');+ await fs.mkdir(path.join(root, 'cindy-brain', 'invalid-plugin'), { recursive: true });+ await fs.writeFile(path.join(root, 'cindy-brain', 'invalid-plugin', 'ghost.json'), '{ nope');+ await fs.mkdir(path.join(root, 'dialogues'), { recursive: true });+ await fs.writeFile(path.join(root, 'dialogues', 'session.json'), 'legacy-dialogue');++ const result = await recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ );++ const targetRoot = path.join(root, 'owners', dataOwnerStorageKey(ownerId));+ expect(result).toMatchObject({ status: 'migrated', moved: 1, conflicts: 0 });+ await expect(+ fs.readFile(path.join(targetRoot, 'cindy-brain', 'valid-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"id":"valid-plugin"');+ await expect(+ fs.readFile(path.join(root, 'cindy-brain', 'invalid-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toBe('{ nope');+ await expect(fs.readFile(path.join(root, 'dialogues', 'session.json'), 'utf-8')).resolves.toBe(+ 'legacy-dialogue',+ );+ });++ it('removes a newly created empty target when every plugin rename fails', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ await writeGhostDirAtPath(+ path.join(root, 'owners', ownerKey, 'brain', 'legacy-plugin'),+ 'legacy-plugin',+ );+ const deps = realFsDeps(+ root,+ {},+ {+ rename: () =>+ Promise.reject(Object.assign(new Error('rename denied'), { code: 'EACCES' })),+ },+ );++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ deps,+ ),+ ).resolves.toMatchObject({ status: 'partial', moved: 0 });+ await expect(+ fs.access(path.join(root, 'owners', ownerKey, 'cindy-brain')),+ ).rejects.toThrow();+ await expect(+ fs.readFile(+ path.join(root, 'owners', ownerKey, 'brain', 'legacy-plugin', 'ghost.json'),+ 'utf-8',+ ),+ ).resolves.toContain('"id":"legacy-plugin"');+ });++ it('does not overwrite an existing scoped plugin', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ await writeGhostDir(root, 'cindy-brain', 'valid-plugin');+ const target = path.join(root, 'owners', dataOwnerStorageKey(ownerId), 'cindy-brain', 'valid-plugin');+ await fs.mkdir(target, { recursive: true });+ await fs.writeFile(path.join(target, 'ghost.json'), 'scoped');++ const result = await recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ );+ const status = getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ root,+ );++ expect(result).toMatchObject({ status: 'partial', moved: 0, conflicts: 1 });+ expect(status).toEqual({+ state: 'partial',+ legacyPluginCount: 1,+ canRetry: false,+ });+ await expect(fs.readFile(path.join(target, 'ghost.json'), 'utf-8')).resolves.toBe('scoped');+ await expect(+ fs.readFile(path.join(root, 'cindy-brain', 'valid-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"id":"valid-plugin"');+ await expect(fs.access(path.join(root, __testing.CLAIM_MARKER))).rejects.toThrow();+ });++ it('does not claim legacy owner data when no valid plugin can be recovered', async () => {+ const root = await tempRoot();+ await fs.mkdir(path.join(root, 'cindy-brain', 'invalid-plugin'), { recursive: true });+ await fs.writeFile(path.join(root, 'cindy-brain', 'invalid-plugin', 'ghost.json'), '{ nope');+ await fs.mkdir(path.join(root, 'dialogues'), { recursive: true });+ await fs.writeFile(path.join(root, 'dialogues', 'session.json'), 'legacy-dialogue');++ const result = await recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ realFsDeps(root),+ );++ expect(result).toEqual({ status: 'skipped', moved: 0, conflicts: 0 });+ await expect(fs.access(path.join(root, __testing.CLAIM_MARKER))).rejects.toThrow();+ await expect(fs.readFile(path.join(root, 'dialogues', 'session.json'), 'utf-8')).resolves.toBe(+ 'legacy-dialogue',+ );+ });++ it('consolidates plugins left in the current owner scoped brain directory', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ const legacyPluginDir = path.join(+ root,+ 'owners',+ ownerKey,+ 'brain',+ 'scoped-legacy-plugin',+ );+ await writeGhostDirAtPath(legacyPluginDir, 'scoped-legacy-plugin');+ await fs.writeFile(+ path.join(root, __testing.CLAIM_MARKER),+ JSON.stringify({ version: 1, ownerKey, complete: true }),+ );++ expect(+ getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ root,+ ),+ ).toEqual({+ state: 'partial',+ legacyPluginCount: 1,+ canRetry: true,+ });++ const result = await recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ );++ expect(result).toMatchObject({ status: 'migrated', moved: 1, conflicts: 0 });+ await expect(+ fs.readFile(+ path.join(root, 'owners', ownerKey, 'cindy-brain', 'scoped-legacy-plugin', 'ghost.json'),+ 'utf-8',+ ),+ ).resolves.toContain('"id":"scoped-legacy-plugin"');+ await expect(+ fs.access(path.join(root, 'owners', ownerKey, 'brain', 'scoped-legacy-plugin')),+ ).rejects.toThrow();+ });++ it('recovers current-owner scoped plugins without changing another owner global claim', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-b';+ const ownerKey = dataOwnerStorageKey(ownerId);+ const otherOwnerKey = dataOwnerStorageKey('cloud-a');+ await writeGhostDirAtPath(+ path.join(root, 'owners', ownerKey, 'brain', 'scoped-legacy-plugin'),+ 'scoped-legacy-plugin',+ );+ await fs.writeFile(+ path.join(root, __testing.CLAIM_MARKER),+ JSON.stringify({ version: 1, ownerKey: otherOwnerKey, complete: true }),+ );++ expect(+ getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ root,+ ),+ ).toEqual({+ state: 'partial',+ legacyPluginCount: 1,+ canRetry: true,+ });++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ ),+ ).resolves.toMatchObject({ status: 'migrated', moved: 1, conflicts: 0 });+ await expect(+ fs.readFile(+ path.join(root, 'owners', ownerKey, 'cindy-brain', 'scoped-legacy-plugin', 'ghost.json'),+ 'utf-8',+ ),+ ).resolves.toContain('"id":"scoped-legacy-plugin"');+ await expect(+ fs.readFile(path.join(root, __testing.CLAIM_MARKER), 'utf-8'),+ ).resolves.toContain(otherOwnerKey);+ });++ it('fails closed when the global claim marker is unreadable', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ await writeGhostDir(root, 'cindy-brain', 'valid-plugin');+ await fs.writeFile(path.join(root, __testing.CLAIM_MARKER), '{ invalid');++ expect(+ getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ root,+ ),+ ).toEqual({+ state: 'partial',+ legacyPluginCount: 1,+ canRetry: false,+ });++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ realFsDeps(root),+ ),+ ).resolves.toEqual({ status: 'partial', moved: 0, conflicts: 1 });+ await expect(+ fs.readFile(path.join(root, 'cindy-brain', 'valid-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"id":"valid-plugin"');+ });++ it('preserves successful moves when empty legacy root cleanup fails', async () => {+ const root = await tempRoot();+ const ownerId = 'cloud-a';+ const ownerKey = dataOwnerStorageKey(ownerId);+ await writeGhostDir(root, 'cindy-brain', 'valid-plugin');+ const deps = realFsDeps(+ root,+ {},+ {+ rmdir: (dir: string) =>+ path.basename(dir) === 'cindy-brain'+ ? Promise.reject(Object.assign(new Error('cleanup denied'), { code: 'EACCES' }))+ : fs.rmdir(dir),+ },+ );++ await expect(+ recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: ownerId, user: { id: ownerId } },+ deps,+ ),+ ).resolves.toMatchObject({ status: 'migrated', moved: 1, conflicts: 0 });+ await expect(+ fs.readFile(+ path.join(root, 'owners', ownerKey, 'cindy-brain', 'valid-plugin', 'ghost.json'),+ 'utf-8',+ ),+ ).resolves.toContain('"id":"valid-plugin"');+ });++ it('defers without writing a marker while another live instance shares userData', async () => {+ const root = await tempRoot();+ await writeGhostDir(root, 'cindy-brain', 'valid-plugin');+ await writeDevInstanceRecord(root, 4242);++ expect(+ getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ root,+ false,+ {},+ (pid) => pid === 4242,+ ),+ ).toEqual({+ state: 'deferred',+ legacyPluginCount: 1,+ canRetry: false,+ });++ const result = await recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ realFsDeps(root, { isPidAlive: (pid) => pid === 4242 }),+ );++ expect(result).toEqual({+ status: 'deferred',+ moved: 0,+ conflicts: 0,+ deferredReason: 'concurrent-live-instances',+ });+ await expect(fs.access(path.join(root, __testing.CLAIM_MARKER))).rejects.toThrow();+ await expect(+ fs.readFile(path.join(root, 'cindy-brain', 'valid-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"id":"valid-plugin"');+ });++ it('interrupts plugin recovery when an instance registers before the next plugin move', async () => {+ const root = await tempRoot();+ await writeGhostDir(root, 'cindy-brain', 'first-plugin');+ await writeGhostDir(root, 'brain', 'second-plugin');+ let scans = 0;+ const racedDeps = realFsDeps(+ root,+ { isPidAlive: (pid) => pid === 9999 },+ {+ readdir: (dir: string) => {+ if (path.basename(dir) === '.dev-instances') {+ scans += 1;+ return Promise.resolve(scans <= 2 ? [] : ['9999.json']);+ }+ return fs.readdir(dir);+ },+ readFile: (file: string) =>+ path.basename(file) === '9999.json'+ ? Promise.resolve(JSON.stringify({ pid: 9999, userDataDir: root }))+ : fs.readFile(file, 'utf-8'),+ },+ );++ const result = await recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ racedDeps,+ );++ const targetRoot = path.join(root, 'owners', dataOwnerStorageKey('cloud-a'), 'cindy-brain');+ expect(result).toMatchObject({+ status: 'partial',+ moved: 1,+ conflicts: 0,+ deferredReason: 'concurrent-live-instances',+ });+ await expect(+ fs.readFile(path.join(targetRoot, 'first-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"id":"first-plugin"');+ await expect(+ fs.readFile(path.join(root, 'brain', 'second-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"id":"second-plugin"');+ await expect(fs.access(path.join(root, 'cindy-brain'))).resolves.toBeUndefined();+ expect(hasLegacyOwnerNamespaceClaim('cloud-a', root)).toBe(false);+ });++ it('reports claimed-by-other-owner and never moves plugins across accounts', async () => {+ const root = await tempRoot();+ await writeGhostDir(root, 'cindy-brain', 'valid-plugin');+ await fs.writeFile(+ path.join(root, __testing.CLAIM_MARKER),+ JSON.stringify({ version: 1, ownerKey: dataOwnerStorageKey('cloud-a'), complete: true }),+ );++ const result = await recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: 'cloud-b', user: { id: 'cloud-b' } },+ realFsDeps(root),+ );+ const status = getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: 'cloud-b', user: { id: 'cloud-b' } },+ root,+ );++ expect(result).toEqual({ status: 'claimed-by-other-owner', moved: 0, conflicts: 0 });+ expect(status).toEqual({+ state: 'claimed-by-other-owner',+ legacyPluginCount: 1,+ canRetry: false,+ });+ await expect(+ fs.access(path.join(root, 'owners', dataOwnerStorageKey('cloud-b'), 'cindy-brain')),+ ).rejects.toThrow();+ });++ it('reports retryable partial status when legacy plugins appear after a completed owner claim', async () => {+ const root = await tempRoot();+ await writeGhostDir(root, 'cindy-brain', 'valid-plugin');+ await fs.writeFile(+ path.join(root, __testing.CLAIM_MARKER),+ JSON.stringify({ version: 1, ownerKey: dataOwnerStorageKey('cloud-a'), complete: true }),+ );++ expect(+ getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ root,+ ),+ ).toEqual({+ state: 'partial',+ legacyPluginCount: 1,+ canRetry: true,+ });+ });++ it('disables manual recovery retry in passive shared-userData mode', async () => {+ const root = await tempRoot();+ await writeGhostDir(root, 'cindy-brain', 'valid-plugin');+ process.env.XDT_PASSIVE_SHARED_USER_DATA = '1';+ try {+ expect(+ getLegacyGhostRecoveryStatus(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ root,+ ),+ ).toEqual({+ state: 'deferred',+ legacyPluginCount: 1,+ canRetry: false,+ });+ } finally {+ delete process.env.XDT_PASSIVE_SHARED_USER_DATA;+ }+ });++ it('aborts before the first write when the owner generation guard changes', async () => {+ const root = await tempRoot();+ await writeGhostDir(root, 'cindy-brain', 'valid-plugin');++ const result = await recoverLegacyGhostPlugins(+ { mode: 'cloud', dataOwnerId: 'cloud-a', user: { id: 'cloud-a' } },+ realFsDeps(root),+ { shouldAbort: () => true },+ );++ expect(result).toEqual({ status: 'deferred', moved: 0, conflicts: 0 });+ await expect(fs.access(path.join(root, __testing.CLAIM_MARKER))).rejects.toThrow();+ await expect(+ fs.readFile(path.join(root, 'cindy-brain', 'valid-plugin', 'ghost.json'), 'utf-8'),+ ).resolves.toContain('"id":"valid-plugin"');+ });+});+describe('hasLegacyOwnerNamespaceClaim', () => {beforeEach(() => {// 防外部 shell 的 ambient env 污染断言(该函数直接读 env)。@@ -509,6 +1449,27 @@ describe('isSameUserDataDir', () => {});});+describe('pathExistsNoFollowSync', () => {+ it('treats any lstat-visible entry as occupied, including links', () => {+ const lstat = vi.fn(() => ({}) as never);+ expect(__testing.pathExistsNoFollowSync('destination', lstat)).toBe(true);+ expect(lstat).toHaveBeenCalledWith('destination');+ });++ it('returns missing only for ENOENT and fails closed for other lstat errors', () => {+ expect(+ __testing.pathExistsNoFollowSync('missing', () => {+ throw Object.assign(new Error('missing'), { code: 'ENOENT' });+ }),+ ).toBe(false);+ expect(+ __testing.pathExistsNoFollowSync('unreadable', () => {+ throw Object.assign(new Error('denied'), { code: 'EACCES' });+ }),+ ).toBe(true);+ });+});+function realFsDeps(root: string,guardOverrides: Partial<GuardDeps> = {},@@ -555,3 +1516,32 @@ async function writeDevInstanceRecord('utf-8',);}++async function writeGhostDir(root: string, rootName: 'cindy-brain' | 'brain', id: string): Promise<void> {+ const dir = path.join(root, rootName, id);+ await writeGhostDirAtPath(dir, id);+}++async function writeGhostDirAtPath(+ dir: string,+ id: string,+ command?: string,+): Promise<void> {+ await fs.mkdir(dir, { recursive: true });+ await fs.writeFile(+ path.join(dir, 'ghost.json'),+ JSON.stringify({+ schemaVersion: 2,+ id,+ name: `Plugin ${id}`,+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['tool'],+ tools: [{ name: 'do_thing', description: 'Do something' }],+ ...(command === undefined ? {} : { command }),+ }),+ 'utf-8',+ );+ await fs.writeFile(path.join(dir, 'main.js'), 'export default {};', 'utf-8');+}diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.tsindex 55a148a5cd..720428eba7 100644--- a/apps/desktop/src/main/authManager.ts+++ b/apps/desktop/src/main/authManager.ts@@ -80,18 +80,23 @@ import {getActiveAppSession,type AppSessionMode,} from './appSessionState.js';-import { claimLegacyOwnerNamespace } from './ownerNamespaceMigration.js';+import {+ claimLegacyOwnerNamespace,+ recordLegacyGhostMigrationResult,+} from './ownerNamespaceMigration.js';const log = createLogger('authManager');async function claimLegacyNamespaceForVerifiedUser(userId: string): Promise<void> {try {- await claimLegacyOwnerNamespace({+ const result = await claimLegacyOwnerNamespace({mode: 'cloud',dataOwnerId: userId,user: { id: userId },});+ recordLegacyGhostMigrationResult(userId, result);} catch (error) {+ recordLegacyGhostMigrationResult(userId, { status: 'partial', moved: 0, conflicts: 0 });log.warn('legacy owner namespace claim failed; continuing with scoped storage', {userId,error: error instanceof Error ? error.message : String(error),diff --git a/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryIpc.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryIpc.test.tsnew file mode 100644index 0000000000..7b0b9abbd7--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/legacyGhostRecoveryIpc.test.ts@@ -0,0 +1,103 @@+import { describe, expect, it, vi } from 'vitest';++import { createLegacyGhostRecoveryIpcHandlers } from '../legacyGhostRecoveryIpc.js';++describe('legacy Ghost recovery IPC boundary', () => {+ it('authenticates the sender and returns only the coarse status projection', () => {+ const event = { sender: 'trusted' };+ const assertTrusted = vi.fn();+ const getStatus = vi.fn(() => ({+ state: 'deferred' as const,+ legacyPluginCount: 2,+ canRetry: true,+ }));+ const handlers = createLegacyGhostRecoveryIpcHandlers({+ assertTrusted,+ invalid: (message) => {+ throw new Error(message);+ },+ failure: (error) => {+ throw error;+ },+ getStatus,+ retry: vi.fn(),+ });++ expect(handlers.status(event)).toEqual({+ state: 'deferred',+ legacyPluginCount: 2,+ canRetry: true,+ });+ expect(assertTrusted).toHaveBeenCalledWith(event);+ expect(getStatus).toHaveBeenCalledTimes(1);+ });++ it('rejects unexpected renderer payload before reading or moving data', async () => {+ const getStatus = vi.fn();+ const retry = vi.fn();+ const handlers = createLegacyGhostRecoveryIpcHandlers({+ assertTrusted: vi.fn(),+ invalid: (message) => {+ throw new Error(message);+ },+ failure: (error) => {+ throw error;+ },+ getStatus,+ retry,+ });++ expect(() => handlers.status({}, 'owner-id')).toThrow(/does not accept renderer payload/);+ await expect(handlers.retry({}, { path: 'legacy' })).rejects.toThrow(+ /does not accept renderer payload/,+ );+ expect(getStatus).not.toHaveBeenCalled();+ expect(retry).not.toHaveBeenCalled();+ });++ it('does not execute a request rejected by the sender guard', async () => {+ const getStatus = vi.fn();+ const retry = vi.fn();+ const handlers = createLegacyGhostRecoveryIpcHandlers({+ assertTrusted: () => {+ throw new Error('untrusted sender');+ },+ invalid: (message) => {+ throw new Error(message);+ },+ failure: (error) => {+ throw error;+ },+ getStatus,+ retry,+ });++ expect(() => handlers.status({})).toThrow(/untrusted sender/);+ await expect(handlers.retry({})).rejects.toThrow(/untrusted sender/);+ expect(getStatus).not.toHaveBeenCalled();+ expect(retry).not.toHaveBeenCalled();+ });++ it('normalizes retry failures before they cross the IPC boundary', async () => {+ const rawError = new Error('rename C:\\Users\\secret\\legacy C:\\Users\\secret\\owner');+ const failure = vi.fn((error: unknown) => {+ expect(error).toBe(rawError);+ throw new Error('Legacy Plugin recovery failed.');+ });+ const handlers = createLegacyGhostRecoveryIpcHandlers({+ assertTrusted: vi.fn(),+ invalid: (message) => {+ throw new Error(message);+ },+ failure,+ getStatus: vi.fn(),+ retry: vi.fn(async () => {+ throw rawError;+ }),+ });++ await expect(handlers.retry({})).rejects.toThrow('Legacy Plugin recovery failed.');+ await expect(handlers.retry({})).rejects.not.toThrow('secret');+ expect(failure).toHaveBeenCalledTimes(2);+ });+});diff --git a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.tsindex 951abbe40f..2e5eed45e5 100644--- a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts+++ b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts@@ -133,6 +133,32 @@ export function listBuiltinSeedIds(seedRootDirs: string[]): string[] {return [...ids].sort();}+/** 列出当前身份本轮会播种的 command(已墓碑的 id 由调用方排除)。 */+export function listEligibleBuiltinCommands(+ seedRootDirs: string[],+ identity: ProvisionIdentity | null,+ excludedIds: ReadonlySet<string> = new Set(),+ log?: BuiltinProvisionerLogger,+): string[] {+ const commands = new Set<string>();+ const seen = new Set<string>();+ for (const root of seedRootDirs) {+ const ids = listSeedIdsInRoot(root);+ if (ids.length === 0) continue;+ const config = readProvisioningConfig(root, log);+ if (config === null) continue;+ for (const id of ids) {+ if (seen.has(id)) continue;+ seen.add(id);+ if (excludedIds.has(id) || !matchesAudience(config.get(id)?.audience, identity)) continue;+ const manifest = readSeedManifest(path.join(root, id), id, log);+ const command = manifest?.command?.toLowerCase();+ if (command) commands.add(command);+ }+ }+ return [...commands].sort();+}+/** 列出单个种子根下的意识 id(= 子目录名;点开头跳过)。种子根缺失返回空。 */function listSeedIdsInRoot(seedRootDir: string): string[] {let entries: fs.Dirent[];diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex e065ea4f8a..8c86157839 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -37,6 +37,7 @@ import { GhostManager, type InstallRejection, type UninstallRejection } from './import { GhostMutationCoordinator } from './ghostMutationCoordinator.js';import {clearBuiltinTombstone,+ listEligibleBuiltinCommands,listBuiltinSeedIds,listEnterpriseSeedIds,listRestorableBuiltinGhosts,@@ -197,7 +198,19 @@ import { getDbClient } from '../localDb/client/current.js';import * as localDbSchema from '../localDb/schema.js';import { eq } from 'drizzle-orm';import { requireAppCapability } from '../appCapabilities.js';-import { hasLegacyOwnerNamespaceClaim } from '../ownerNamespaceMigration.js';+import {+ getLegacyGhostRecoveryStatus,+ hasLegacyOwnerNamespaceClaim,+ listLegacyGhostPluginSources,+ listLegacyGhostTombstoneRoots,+ recoverLegacyGhostPlugins,+} from '../ownerNamespaceMigration.js';+import {+ LEGACY_GHOST_RECOVERY_RETRY_CHANNEL,+ LEGACY_GHOST_RECOVERY_STATUS_CHANNEL,+ createLegacyGhostRecoveryIpcHandlers,+} from './legacyGhostRecoveryIpc.js';+import type { LegacyGhostRecoveryStatus } from '../../shared/legacyGhostRecovery.js';/*** 意识仓库的进程级单例 + IPC 注册。@@ -278,6 +291,219 @@ function beginGhostMutation(expectedOwner?: ActiveAppSession): () => void {return ghostMutationCoordinator.acquire();}+function isSameAppSession(a: ActiveAppSession, b: ActiveAppSession): boolean {+ return a.mode === b.mode && a.dataOwnerId === b.dataOwnerId && a.generation === b.generation;+}++function currentLegacyGhostMigrationSession(): {+ mode: ActiveAppSession['mode'];+ dataOwnerId: string | null;+ user: { id: string } | null;+} {+ const session = getActiveAppSession();+ return {+ mode: session.mode,+ dataOwnerId: session.dataOwnerId,+ user: session.mode === 'cloud' && session.dataOwnerId ? { id: session.dataOwnerId } : null,+ };+}++function getLegacyGhostRecoveryStatusForActiveSession(): LegacyGhostRecoveryStatus {+ const ownerId = getActiveAppSession().dataOwnerId;+ const excludedBuiltinIds =+ ownerId === null+ ? new Set<string>()+ : new Set(+ listLegacyGhostTombstoneRoots(ownerId, app.getPath('userData')).flatMap((root) =>+ readBuiltinTombstones(root),+ ),+ );+ const reservedBuiltinCommands = new Set(+ listEligibleBuiltinCommands(+ builtinSeedRootDirs(),+ currentProvisionIdentity(),+ excludedBuiltinIds,+ log,+ ),+ );+ return getLegacyGhostRecoveryStatus(+ currentLegacyGhostMigrationSession(),+ undefined,+ isAppSessionBoundaryPending(),+ { reservedCommands: reservedBuiltinCommands },+ );+}++async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostRecoveryStatus> {+ const expectedOwner = captureGhostMutationOwner();+ if (expectedOwner.mode !== 'cloud' || !expectedOwner.dataOwnerId) {+ return getLegacyGhostRecoveryStatusForActiveSession();+ }+ const initialStatus = getLegacyGhostRecoveryStatusForActiveSession();+ if (!initialStatus.canRetry) return initialStatus;++ const releaseMutation = beginGhostMutation(expectedOwner);+ try {+ const shouldAbort = (): boolean =>+ isAppSessionBoundaryPending() || !isSameAppSession(expectedOwner, getActiveAppSession());+ if (shouldAbort()) return getLegacyGhostRecoveryStatusForActiveSession();+ const authorizedStatus = getLegacyGhostRecoveryStatusForActiveSession();+ if (!authorizedStatus.canRetry) return authorizedStatus;++ const existingGhosts = getGhostManager().list();+ const existingGhostById = new Map(+ existingGhosts.map((ghost) => [ghost.manifest.id, ghost]),+ );+ const existingGhostDirs = new Map(+ existingGhosts.map((ghost) => [ghost.manifest.id, ghost.dir]),+ );+ type StoppedActiveGhost = {+ ghost: InstalledGhost;+ browserRuntimeRunning: boolean;+ nodeRuntimeRunning: boolean;+ };+ const stoppedActiveGhosts = new Map<string, StoppedActiveGhost>();+ const legacySources = listLegacyGhostPluginSources(+ expectedOwner.dataOwnerId,+ app.getPath('userData'),+ );+ const excludedBuiltinIds = new Set(+ listLegacyGhostTombstoneRoots(+ expectedOwner.dataOwnerId,+ app.getPath('userData'),+ ).flatMap((root) => readBuiltinTombstones(root)),+ );+ const reservedBuiltinCommands = new Set(+ listEligibleBuiltinCommands(+ builtinSeedRootDirs(),+ currentProvisionIdentity(),+ excludedBuiltinIds,+ log,+ ),+ );+ for (const source of legacySources) {+ const activeDir = existingGhostDirs.get(source.id);+ if (activeDir !== undefined && path.resolve(activeDir) !== path.resolve(source.dir)) continue;+ const browserRuntimeRunning = getGhostRuntime().stateOf(source.id) === 'running';+ const nodeRuntimeRunning = getGhostNodeRuntimeBroker().stateOf(source.id) === 'running';+ getGhostRuntime().stop(source.id);+ getGhostNodeRuntimeBroker().stop(source.id);+ const activeGhost = existingGhostById.get(source.id);+ if (activeGhost) {+ stoppedActiveGhosts.set(source.id, {+ ghost: activeGhost,+ browserRuntimeRunning,+ nodeRuntimeRunning,+ });+ }+ }+ const restoreGhostRuntimes = (+ ghost: InstalledGhost,+ stopped: StoppedActiveGhost,+ ): void => {+ spawnIfResident(ghost);+ if (+ stopped.browserRuntimeRunning &&+ ghost.manifest.launch !== 'resident' &&+ isGhostAvailableForActiveSession(ghost.manifest.id) &&+ ghost.enabled+ ) {+ void getGhostRuntime()+ .spawn(ghost)+ .catch((error) =>+ log.warn('recovery on-demand ghost spawn error', {+ id: ghost.manifest.id,+ error: error instanceof Error ? error.message : String(error),+ }),+ );+ }+ if (+ stopped.nodeRuntimeRunning &&+ ghost.manifest.node?.lifecycle !== 'resident' &&+ isGhostAvailableForActiveSession(ghost.manifest.id) &&+ ghost.enabled+ ) {+ void getGhostNodeRuntimeBroker()+ .startForRecovery(ghost)+ .catch((error) =>+ log.warn('recovery on-demand ghost node spawn error', {+ id: ghost.manifest.id,+ error: error instanceof Error ? error.message : String(error),+ }),+ );+ }+ };+ const restartStoppedActiveGhosts = (): void => {+ for (const stopped of stoppedActiveGhosts.values()) {+ restoreGhostRuntimes(stopped.ghost, stopped);+ }+ };+ let result;+ try {+ result = await recoverLegacyGhostPlugins(+ {+ mode: 'cloud',+ dataOwnerId: expectedOwner.dataOwnerId,+ user: { id: expectedOwner.dataOwnerId },+ },+ undefined,+ {+ shouldAbort,+ reservedCommands: reservedBuiltinCommands,+ rejectReservedIds: app.isPackaged,+ },+ );+ } catch (error) {+ if (!shouldAbort()) restartStoppedActiveGhosts();+ throw error;+ }+ if (shouldAbort()) return getLegacyGhostRecoveryStatusForActiveSession();+ if (result.moved === 0 && !result.provisioningStateMoved) {+ restartStoppedActiveGhosts();+ return getLegacyGhostRecoveryStatusForActiveSession();+ }+ if (result.moved > 0 || result.provisioningStateMoved) {+ brainRootCache = null;+ const restoredBeforeReconcile = getGhostManager().list();+ const movedGhostIds = new Set<string>();+ for (const ghost of restoredBeforeReconcile) {+ const previousDir = existingGhostDirs.get(ghost.manifest.id);+ if (+ previousDir !== undefined &&+ path.resolve(previousDir) !== path.resolve(ghost.dir)+ ) {+ movedGhostIds.add(ghost.manifest.id);+ getGhostRuntime().stop(ghost.manifest.id);+ getGhostNodeRuntimeBroker().stop(ghost.manifest.id);+ }+ }+ const builtinReconcileSucceeded =+ result.deferredReason !== 'concurrent-live-instances' &&+ await scheduleBuiltinReconcile('legacy-recovery');+ if (shouldAbort()) return getLegacyGhostRecoveryStatusForActiveSession();+ const ghosts = getGhostManager().list();+ for (const ghost of ghosts) {+ const previousDir = existingGhostDirs.get(ghost.manifest.id);+ const relocatedExistingGhost =+ movedGhostIds.has(ghost.manifest.id) ||+ (previousDir !== undefined &&+ path.resolve(previousDir) !== path.resolve(ghost.dir));+ if (relocatedExistingGhost) ensureGhostProtocolRegistered(ghost);+ const stopped = stoppedActiveGhosts.get(ghost.manifest.id);+ if (relocatedExistingGhost && stopped) {+ restoreGhostRuntimes(ghost, stopped);+ } else if (builtinReconcileSucceeded && previousDir === undefined) {+ spawnIfResident(ghost);+ }+ }+ broadcastGhostsChanged(ghosts);+ }+ return getLegacyGhostRecoveryStatusForActiveSession();+ } finally {+ releaseMutation();+ }+}+/** Wait until all owner-bound Ghost filesystem mutations have finished. */export function waitForGhostMutations(): Promise<void> {return ghostMutationCoordinator.waitForIdle();@@ -365,15 +591,27 @@ function currentProvisionIdentity(): ProvisionIdentity | null {*/let builtinReconcileChain: Promise<void> = Promise.resolve();-function scheduleBuiltinReconcile(reason: string): void {- builtinReconcileChain = builtinReconcileChain- .then(() => reconcileBuiltinGhosts(reason))+function scheduleBuiltinReconcile(reason: string): Promise<boolean> {+ const scheduled = builtinReconcileChain.catch((err) => {- log.warn('builtin ghost reconcile error', {- reason,+ log.warn('builtin ghost activation error; reconcile chain resumed', {error: err instanceof Error ? err.message : String(err),});+ })+ .then(async () => {+ try {+ await reconcileBuiltinGhosts(reason);+ return true;+ } catch (err) {+ log.warn('builtin ghost reconcile error', {+ reason,+ error: err instanceof Error ? err.message : String(err),+ });+ return false;+ }});+ builtinReconcileChain = scheduled.then(() => undefined);+ return scheduled;}/**@@ -2347,6 +2585,15 @@ export function registerGhostIpc(): void {// 启动即对账一次 skill 槽链接:上次会话崩溃/异常退出留下的悬空链接、// 换账号后的期望态变化,都在这里自愈(后续变更由 ghosts:changed 广播驱动)。scheduleGhostSkillReconcile();+ const legacyRecoveryIpc = createLegacyGhostRecoveryIpcHandlers({+ assertTrusted: assertTrustedAppRendererEvent,+ invalid: (message) => throwIpcError('INVALID_PARAMS', message),+ failure: () => throwIpcError('INTERNAL', 'Legacy Plugin recovery failed.'),+ getStatus: getLegacyGhostRecoveryStatusForActiveSession,+ retry: retryLegacyGhostRecoveryForActiveSession,+ });+ ipcMain.handle(LEGACY_GHOST_RECOVERY_STATUS_CHANNEL, legacyRecoveryIpc.status);+ ipcMain.handle(LEGACY_GHOST_RECOVERY_RETRY_CHANNEL, legacyRecoveryIpc.retry);setGhostSandboxDevToolsDisabled(app.isPackaged);setGhostAppContextProvider(currentGhostAppContext);// 面板唤醒电子脑(cindy-ghost://<id>/wake 供片分支):面板零桥,唤醒经它@@ -2741,7 +2988,7 @@ export function registerGhostIpc(): void {};void app.whenReady().then(() => {- scheduleBuiltinReconcile('startup');+ void scheduleBuiltinReconcile('startup');builtinReconcileChain = builtinReconcileChain.then(activateGhostsAndMigrateLegacyAccounts,);@@ -2750,7 +2997,7 @@ export function registerGhostIpc(): void {// Even when provisioning itself is a no-op, the renderer and agent// roster must immediately reflect the new session capability set.broadcastGhostsChanged(manager.list());- scheduleBuiltinReconcile('auth-change');+ void scheduleBuiltinReconcile('auth-change');builtinReconcileChain = builtinReconcileChain.then(activateGhostsAndMigrateLegacyAccounts,);@@ -3274,7 +3521,7 @@ export function registerGhostIpc(): void {throwIpcError('NOT_FOUND', `意识 ${id} 不是内置种子`);}clearBuiltinTombstone(brainRootDir(), id, log);- scheduleBuiltinReconcile('restore');+ void scheduleBuiltinReconcile('restore');await builtinReconcileChain; // 等本轮装完再返回,renderer 拿到结果时列表已就位return { ok: true };});diff --git a/apps/desktop/src/main/cindy-brain/legacyGhostRecoveryIpc.ts b/apps/desktop/src/main/cindy-brain/legacyGhostRecoveryIpc.tsnew file mode 100644index 0000000000..d1ab4d41a0--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/legacyGhostRecoveryIpc.ts@@ -0,0 +1,41 @@+import type { LegacyGhostRecoveryStatus } from '../../shared/legacyGhostRecovery.js';++export const LEGACY_GHOST_RECOVERY_STATUS_CHANNEL = 'ghosts:legacy-recovery-status';+export const LEGACY_GHOST_RECOVERY_RETRY_CHANNEL = 'ghosts:retry-legacy-recovery';++interface LegacyGhostRecoveryIpcDeps<Event> {+ assertTrusted(event: Event): void;+ invalid(message: string): never;+ failure(error: unknown): never;+ getStatus(): LegacyGhostRecoveryStatus;+ retry(): Promise<LegacyGhostRecoveryStatus>;+}++/**+ * Small injectable IPC boundary: both channels accept zero renderer payload+ * and authenticate the sender before reading or moving any local data.+ */+export function createLegacyGhostRecoveryIpcHandlers<Event>(+ deps: LegacyGhostRecoveryIpcDeps<Event>,+) {+ const assertRequest = (event: Event, args: unknown[]): void => {+ deps.assertTrusted(event);+ if (args.length !== 0) {+ deps.invalid('legacy Plugin recovery IPC does not accept renderer payload');+ }+ };+ return {+ status: (event: Event, ...args: unknown[]): LegacyGhostRecoveryStatus => {+ assertRequest(event, args);+ return deps.getStatus();+ },+ retry: async (event: Event, ...args: unknown[]): Promise<LegacyGhostRecoveryStatus> => {+ assertRequest(event, args);+ try {+ return await deps.retry();+ } catch (error) {+ return deps.failure(error);+ }+ },+ };+}diff --git a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.tsindex 139c11ae3f..caf3f5bf6a 100644--- a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts+++ b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts@@ -401,6 +401,14 @@ export class GhostNodeRuntimeBroker {if (ghost.manifest.node.protocol === 'mcp-stdio') await this.ensureMcpInitialized(entry);}+ /** Recovery-only restart for a runtime that was already running on demand. */+ async startForRecovery(ghost: InstalledGhost): Promise<void> {+ this.stoppedGhosts.delete(ghost.manifest.id);+ if (!ghost.enabled || !ghost.manifest.node) return;+ const entry = await this.ensureWorker(ghost, ghost.manifest.node.entry);+ if (ghost.manifest.node.protocol === 'mcp-stdio') await this.ensureMcpInitialized(entry);+ }+/** main.js 的 node-request 入口。 */async handleRequest(ghostId: string, payload: unknown): Promise<GhostPipeNodeResult> {const ghost = this.deps.getGhost(ghostId);diff --git a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.tsindex 27b815957b..32b3591770 100644--- a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts+++ b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts@@ -205,6 +205,7 @@ export function setGhostConnectionsHandler(handler: GhostConnectionsProtocolHand/** 该分区是否已挂过协议 handler(session 分区随 app 生命周期,挂一次即可)。 */const partitionRegistered = new Set<string>();+const partitionGhost = new Map<string, { dir: string; entry: string }>();/*** 确保某意识分区上的 cindy-ghost:// 协议 handler 就位(幂等)。@@ -224,14 +225,16 @@ const GHOST_HTML_CSP ="default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' data: blob:";function registerGhostProtocol(partition: string, ghost: InstalledGhost): void {+ partitionGhost.set(partition, {+ dir: ghost.dir,+ entry: ghost.manifest.entry,+ });if (partitionRegistered.has(partition)) return;// 注意:登记发生在全部挂载成功之后(函数末尾)——session.fromPartition 在// app ready 前会 throw,若先登记后挂载,失败分区会被永久标记"已注册"而// 实际无 handler,面板与电子脑一起哑火(review P0 的中毒模式)。const ses = session.fromPartition(partition);const ghostId = ghost.manifest.id;- const installDir = ghost.dir;- const entry = ghost.manifest.entry;// 分区级断网(docs/dev-rules/plugin-security-and-authoring.md 的"网络永远不直连"):本分区发出的一切// 请求,只放行自己协议同 id 下的资源;http(s) / ws / 其它协议一律掐断。// 进程沙箱不管网络,这里才是"零网络"承诺的真正闸门;外部数据未来走@@ -369,6 +372,7 @@ function registerGhostProtocol(partition: string, ghost: InstalledGhost): void {});}if (url.pathname === GHOST_BOOT_PATH || url.pathname === '/') {+ const entry = partitionGhost.get(partition)?.entry;if (!entry) return new Response(null, { status: 404 });return new Response(ghostBootHtml(entry), {status: 200,@@ -379,6 +383,8 @@ function registerGhostProtocol(partition: string, ghost: InstalledGhost): void {},});}+ const installDir = partitionGhost.get(partition)?.dir;+ if (!installDir) return new Response(null, { status: 404 });const filePath = resolveGhostFilePath(installDir, url.pathname);if (!filePath) return new Response(null, { status: 403 });const data = await fs.readFile(filePath);diff --git a/apps/desktop/src/main/ownerNamespaceMigration.ts b/apps/desktop/src/main/ownerNamespaceMigration.tsindex b82f8ea774..482c283990 100644--- a/apps/desktop/src/main/ownerNamespaceMigration.ts+++ b/apps/desktop/src/main/ownerNamespaceMigration.ts@@ -5,8 +5,18 @@ import path from 'node:path';import { dataOwnerStorageKey, type AppSessionMode } from './appSessionState.js';import { createLogger } from './logger.js';+import {+ GHOST_MANIFEST_FILE,+ isOfficialGhostId,+ validateGhostManifest,+} from '../shared/ghost.js';+import {+ NO_LEGACY_GHOST_RECOVERY,+ type LegacyGhostRecoveryStatus,+} from '../shared/legacyGhostRecovery.js';const CLAIM_MARKER = '.owner-namespace-claim-v1.json';+const BUILTIN_PROVISIONING_STATE_FILE = '.builtin-provisioning.json';const LEGACY_PATHS = ['ghost-kv','ghost-fs',@@ -70,10 +80,15 @@ export interface OwnerNamespaceMigrationResult {status: 'skipped' | 'deferred' | 'claimed-by-other-owner' | 'migrated' | 'partial';moved: number;conflicts: number;+ provisioningStateMoved?: boolean;deferredReason?: OwnerNamespaceClaimDeferredReason;}const log = createLogger('ownerNamespaceMigration');+const legacyGhostMigrationResults = new Map<+ string,+ OwnerNamespaceMigrationResult['status']+>();const productionDeps: MigrationDeps = {userDataDir: () => app.getPath('userData'),@@ -242,6 +257,752 @@ export function hasLegacyOwnerNamespaceClaim(return !hasConcurrentLiveInstanceSync(userDataDir, isPidAlive);}+function readMarkerSync(+ userDataDir: string,+): { marker: ClaimMarker | null; invalid: boolean } {+ try {+ const parsed = JSON.parse(+ fsSync.readFileSync(path.join(userDataDir, CLAIM_MARKER), 'utf-8'),+ ) as Partial<ClaimMarker>;+ if (+ parsed.version === 1 &&+ typeof parsed.ownerKey === 'string' &&+ typeof parsed.complete === 'boolean'+ ) {+ return { marker: parsed as ClaimMarker, invalid: false };+ }+ return { marker: null, invalid: true };+ } catch (error) {+ return isMissing(error)+ ? { marker: null, invalid: false }+ : { marker: null, invalid: true };+ }+}++interface LegacyGhostDir {+ root: string;+ id: string;+ dir: string;+ command: string | null;+}++function readValidLegacyGhostDir(+ dir: string,+ expectedId: string,+): Pick<LegacyGhostDir, 'command'> | null {+ let raw: unknown;+ try {+ raw = JSON.parse(fsSync.readFileSync(path.join(dir, GHOST_MANIFEST_FILE), 'utf-8'));+ } catch {+ return null;+ }+ const parsed = validateGhostManifest(raw);+ if (!parsed.ok || parsed.manifest.id !== expectedId) return null;+ return { command: parsed.manifest.command ?? null };+}++function pathExistsNoFollowSync(+ file: string,+ lstat: (path: string) => fsSync.Stats = fsSync.lstatSync,+): boolean {+ try {+ lstat(file);+ return true;+ } catch (error) {+ return !isMissing(error);+ }+}++function hasBlockingProvisioningStateSync(legacyRoot: string, targetRoot: string): boolean {+ const sourceState = path.join(legacyRoot, BUILTIN_PROVISIONING_STATE_FILE);+ let sourceStateStats: fsSync.Stats;+ try {+ sourceStateStats = fsSync.lstatSync(sourceState);+ } catch (error) {+ return !isMissing(error);+ }+ if (!sourceStateStats.isFile() || sourceStateStats.isSymbolicLink()) return true;+ return pathExistsNoFollowSync(path.join(targetRoot, BUILTIN_PROVISIONING_STATE_FILE));+}++function sharedLegacyGhostRootDirs(userDataDir: string): string[] {+ return [path.join(userDataDir, 'cindy-brain'), path.join(userDataDir, 'brain')];+}++function ownerScopedLegacyGhostRootDir(userDataDir: string, ownerKey: string): string {+ return path.join(userDataDir, 'owners', ownerKey, 'brain');+}++function listLegacyGhostDirsInRoots(+ roots: string[],+): LegacyGhostDir[] {+ const result: LegacyGhostDir[] = [];+ for (const root of roots) {+ try {+ const stats = fsSync.lstatSync(root);+ if (!stats.isDirectory() || stats.isSymbolicLink()) continue;+ } catch {+ continue;+ }+ let entries: fsSync.Dirent[];+ try {+ entries = fsSync.readdirSync(root, { withFileTypes: true });+ } catch {+ continue;+ }+ for (const entry of entries) {+ if (entry.name.startsWith('.')) continue;+ const dir = path.join(root, entry.name);+ let dirStats: fsSync.Stats;+ try {+ dirStats = fsSync.lstatSync(dir);+ } catch {+ continue;+ }+ if (!dirStats.isDirectory() || dirStats.isSymbolicLink()) continue;+ const valid = readValidLegacyGhostDir(dir, entry.name);+ if (valid) result.push({ root, id: entry.name, dir, command: valid.command });+ }+ }+ return result;+}++function listSharedLegacyGhostDirs(+ userDataDir: string,+): LegacyGhostDir[] {+ return listLegacyGhostDirsInRoots(sharedLegacyGhostRootDirs(userDataDir));+}++function listOwnerScopedLegacyGhostDirs(+ userDataDir: string,+ ownerKey: string,+): LegacyGhostDir[] {+ return listLegacyGhostDirsInRoots([+ ownerScopedLegacyGhostRootDir(userDataDir, ownerKey),+ ]);+}++function listLegacyGhostDirs(+ userDataDir: string,+ ownerKey?: string,+): LegacyGhostDir[] {+ const shared = listSharedLegacyGhostDirs(userDataDir);+ return ownerKey+ ? [...shared, ...listOwnerScopedLegacyGhostDirs(userDataDir, ownerKey)]+ : shared;+}++export function countLegacyGhostPlugins(+ userDataDir = app.getPath('userData'),+ ownerKey?: string,+): number {+ return listLegacyGhostDirs(userDataDir, ownerKey).length;+}++export function listLegacyGhostPluginSources(+ ownerId: string,+ userDataDir = app.getPath('userData'),+): Array<{ id: string; dir: string }> {+ const ownerKey = dataOwnerStorageKey(ownerId);+ return listLegacyGhostDirs(userDataDir, ownerKey).map(({ id, dir }) => ({ id, dir }));+}++/**+ * Return only legacy roots whose provisioning state and owner claim can move+ * into the active owner namespace. Tombstones from a foreign or blocked root+ * must not suppress built-ins that will be reconciled for the active owner.+ */+export function listLegacyGhostTombstoneRoots(+ ownerId: string,+ userDataDir = app.getPath('userData'),+): string[] {+ const ownerKey = dataOwnerStorageKey(ownerId);+ const targetRoot = path.join(userDataDir, 'owners', ownerKey, 'cindy-brain');+ const sharedLegacyGhosts = listSharedLegacyGhostDirs(userDataDir);+ const scopedLegacyGhosts = listOwnerScopedLegacyGhostDirs(userDataDir, ownerKey);+ const markerRead = readMarkerSync(userDataDir);+ const sharedRecoveryBlocked =+ sharedLegacyGhosts.length > 0 &&+ (markerRead.invalid ||+ (markerRead.marker !== null && markerRead.marker.ownerKey !== ownerKey));+ const eligible = sharedRecoveryBlocked+ ? scopedLegacyGhosts+ : [...sharedLegacyGhosts, ...scopedLegacyGhosts];+ const blockedRoots = new Set(+ eligible+ .map((legacy) => legacy.root)+ .filter((legacyRoot) => hasBlockingProvisioningStateSync(legacyRoot, targetRoot)),+ );+ return [...new Set(eligible.map((legacy) => legacy.root))].filter(+ (legacyRoot) => !blockedRoots.has(legacyRoot),+ );+}++function hasSafeRecoveryTargetChainSync(userDataDir: string, targetRoot: string): boolean {+ const relative = path.relative(userDataDir, targetRoot);+ if (+ relative.length === 0 ||+ path.isAbsolute(relative) ||+ relative === '..' ||+ relative.startsWith(`..${path.sep}`)+ ) {+ return false;+ }+ let current = userDataDir;+ for (const part of relative.split(path.sep)) {+ current = path.join(current, part);+ try {+ const stats = fsSync.lstatSync(current);+ if (!stats.isDirectory() || stats.isSymbolicLink()) return false;+ } catch (error) {+ if (isMissing(error)) continue;+ return false;+ }+ }+ return true;+}++export function recordLegacyGhostMigrationResult(+ ownerId: string,+ result: OwnerNamespaceMigrationResult,+ userDataDir = app.getPath('userData'),+): void {+ const ownerKey = dataOwnerStorageKey(ownerId);+ let status = result.status;+ if (+ status === 'migrated' &&+ result.conflicts > 0 &&+ countLegacyGhostPlugins(userDataDir, ownerKey) > 0+ ) {+ status = 'partial';+ }+ legacyGhostMigrationResults.set(ownerKey, status);+}++export function getLegacyGhostRecoveryStatus(+ session: MigrationSessionState,+ userDataDir?: string,+ boundaryPending = false,+ options: { reservedCommands?: ReadonlySet<string> } = {},+ isPidAlive: (pid: number) => boolean = isPidAliveDefault,+): LegacyGhostRecoveryStatus {+ if (boundaryPending || session.mode !== 'cloud' || !session.dataOwnerId || !session.user) {+ return NO_LEGACY_GHOST_RECOVERY;+ }+ if (session.user.id !== session.dataOwnerId) return NO_LEGACY_GHOST_RECOVERY;++ const root = userDataDir ?? app.getPath('userData');+ const ownerKey = dataOwnerStorageKey(session.dataOwnerId);+ const sharedLegacyGhosts = listSharedLegacyGhostDirs(root);+ const scopedLegacyGhosts = listOwnerScopedLegacyGhostDirs(root, ownerKey);+ const legacyGhosts = [...sharedLegacyGhosts, ...scopedLegacyGhosts];+ const legacyPluginCount = legacyGhosts.length;+ if (legacyPluginCount === 0) return NO_LEGACY_GHOST_RECOVERY;+ if (process.env.XDT_PASSIVE_SHARED_USER_DATA === '1') {+ return { state: 'deferred', legacyPluginCount, canRetry: false };+ }++ const markerRead = readMarkerSync(root);+ const sharedRecoveryBlocked =+ sharedLegacyGhosts.length > 0 &&+ (markerRead.invalid ||+ (markerRead.marker !== null && markerRead.marker.ownerKey !== ownerKey));+ if (sharedRecoveryBlocked && scopedLegacyGhosts.length === 0) {+ if (markerRead.marker && markerRead.marker.ownerKey !== ownerKey) {+ return { state: 'claimed-by-other-owner', legacyPluginCount, canRetry: false };+ }+ return { state: 'partial', legacyPluginCount, canRetry: false };+ }+ if (hasConcurrentLiveInstanceSync(root, isPidAlive)) {+ return { state: 'deferred', legacyPluginCount, canRetry: false };+ }++ const eligibleLegacyGhosts = sharedRecoveryBlocked ? scopedLegacyGhosts : legacyGhosts;+ const targetRoot = path.join(root, 'owners', ownerKey, 'cindy-brain');+ if (!hasSafeRecoveryTargetChainSync(root, targetRoot)) {+ return { state: 'partial', legacyPluginCount, canRetry: false };+ }+ const occupiedCommands = new Set(+ listLegacyGhostDirsInRoots([targetRoot])+ .map((legacy) => legacy.command?.toLowerCase() ?? null)+ .filter((command): command is string => command !== null),+ );+ for (const command of options.reservedCommands ?? []) {+ occupiedCommands.add(command.toLowerCase());+ }+ const blockedRoots = new Set(+ eligibleLegacyGhosts+ .map((legacy) => legacy.root)+ .filter((legacyRoot) => hasBlockingProvisioningStateSync(legacyRoot, targetRoot)),+ );+ const canRetry = eligibleLegacyGhosts.some((legacy) => {+ if (blockedRoots.has(legacy.root)) return false;+ if (pathExistsNoFollowSync(path.join(targetRoot, legacy.id))) return false;+ const command = legacy.command?.toLowerCase() ?? null;+ return command === null || !occupiedCommands.has(command);+ });+ if (!canRetry) {+ if (+ sharedRecoveryBlocked &&+ markerRead.marker &&+ markerRead.marker.ownerKey !== ownerKey &&+ scopedLegacyGhosts.length === 0+ ) {+ return { state: 'claimed-by-other-owner', legacyPluginCount, canRetry: false };+ }+ return { state: 'partial', legacyPluginCount, canRetry: false };+ }++ const marker = markerRead.marker;+ const last = legacyGhostMigrationResults.get(ownerKey);+ if (last === 'deferred') return { state: 'deferred', legacyPluginCount, canRetry: true };+ if (last === 'partial') return { state: 'partial', legacyPluginCount, canRetry: true };+ if (marker && !marker.complete) return { state: 'partial', legacyPluginCount, canRetry: true };+ return { state: 'partial', legacyPluginCount, canRetry: true };+}++export async function recoverLegacyGhostPlugins(+ state: MigrationSessionState,+ deps: MigrationDeps = productionDeps,+ options: {+ shouldAbort?: () => boolean;+ reservedCommands?: ReadonlySet<string>;+ rejectReservedIds?: boolean;+ } = {},+): Promise<OwnerNamespaceMigrationResult> {+ const ownerId = verifiedCloudOwner(state);+ if (!ownerId) return { status: 'skipped', moved: 0, conflicts: 0 };+ if (options.shouldAbort?.()) return { status: 'deferred', moved: 0, conflicts: 0 };++ const userDataDir = deps.userDataDir();+ const ownerKey = dataOwnerStorageKey(ownerId);+ const markerPath = path.join(userDataDir, CLAIM_MARKER);+ const sharedLegacyGhosts = listSharedLegacyGhostDirs(userDataDir);+ const scopedLegacyGhosts = listOwnerScopedLegacyGhostDirs(userDataDir, ownerKey);+ let marker: ClaimMarker | null = null;+ let eligibleSharedGhosts = sharedLegacyGhosts;+ let sharedRecoveryBlocked = false;+ if (sharedLegacyGhosts.length > 0) {+ try {+ marker = await readMarker(deps, markerPath);+ if (marker && marker.ownerKey !== ownerKey) {+ eligibleSharedGhosts = [];+ sharedRecoveryBlocked = true;+ }+ } catch (error) {+ eligibleSharedGhosts = [];+ sharedRecoveryBlocked = true;+ log.warn('legacy ghost recovery blocked: claim marker unreadable', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ if (+ sharedRecoveryBlocked &&+ scopedLegacyGhosts.length === 0 &&+ marker &&+ marker.ownerKey !== ownerKey+ ) {+ const result: OwnerNamespaceMigrationResult = {+ status: 'claimed-by-other-owner',+ moved: 0,+ conflicts: 0,+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+ }++ const targetRoot = path.join(userDataDir, 'owners', ownerKey, 'cindy-brain');+ let movableLegacyGhosts: ReturnType<typeof listLegacyGhostDirs> = [];+ let conflicts = sharedRecoveryBlocked ? sharedLegacyGhosts.length : 0;+ for (const legacy of [...eligibleSharedGhosts, ...scopedLegacyGhosts]) {+ if (options.rejectReservedIds && isOfficialGhostId(legacy.id)) {+ conflicts += 1;+ continue;+ }+ if ((await pathType(deps, path.join(targetRoot, legacy.id))) === 'missing') {+ movableLegacyGhosts.push(legacy);+ } else {+ conflicts += 1;+ }+ }+ if (movableLegacyGhosts.length === 0) {+ const result: OwnerNamespaceMigrationResult = {+ status: conflicts > 0 ? 'partial' : 'skipped',+ moved: 0,+ conflicts,+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+ }++ if (deps.passiveSharedUserData()) {+ const result: OwnerNamespaceMigrationResult = {+ status: 'deferred',+ moved: 0,+ conflicts: 0,+ deferredReason: 'passive-shared-user-data',+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+ }+ try {+ const pids = await findConcurrentLiveInstancePids(deps, userDataDir);+ if (pids.length > 0) {+ const result: OwnerNamespaceMigrationResult = {+ status: 'deferred',+ moved: 0,+ conflicts: 0,+ deferredReason: 'concurrent-live-instances',+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+ }+ } catch (error) {+ log.warn('legacy ghost recovery deferred: instance registry unreadable', {+ error: error instanceof Error ? error.message : String(error),+ });+ const result: OwnerNamespaceMigrationResult = {+ status: 'deferred',+ moved: 0,+ conflicts: 0,+ deferredReason: 'concurrent-live-instances',+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+ }++ if (options.shouldAbort?.()) return { status: 'deferred', moved: 0, conflicts: 0 };+ await deps.mkdir(userDataDir);+ const sharedDirs = new Set(sharedLegacyGhosts.map((legacy) => legacy.dir));++ let moved = 0;+ let provisioningStateMoved = false;+ let failed = false;+ let concurrentRecoveryInterrupted = false;+ if (!hasSafeRecoveryTargetChainSync(userDataDir, targetRoot)) {+ const result: OwnerNamespaceMigrationResult = {+ status: 'partial',+ moved: 0,+ conflicts: conflicts + movableLegacyGhosts.length,+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+ }+ const preflightBlockedRoots = new Set(+ movableLegacyGhosts+ .map((legacy) => legacy.root)+ .filter((legacyRoot) => hasBlockingProvisioningStateSync(legacyRoot, targetRoot)),+ );+ if (preflightBlockedRoots.size > 0) {+ const blockedCount = movableLegacyGhosts.filter((legacy) =>+ preflightBlockedRoots.has(legacy.root)+ ).length;+ conflicts += blockedCount;+ failed = true;+ movableLegacyGhosts = movableLegacyGhosts.filter(+ (legacy) => !preflightBlockedRoots.has(legacy.root),+ );+ }+ if (movableLegacyGhosts.length === 0) {+ const result: OwnerNamespaceMigrationResult = {+ status: conflicts > 0 ? 'partial' : 'skipped',+ moved: 0,+ conflicts,+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+ }+ const occupiedCommands = new Set(+ listLegacyGhostDirsInRoots([targetRoot])+ .map((legacy) => legacy.command?.toLowerCase() ?? null)+ .filter((command): command is string => command !== null),+ );+ for (const command of options.reservedCommands ?? []) {+ occupiedCommands.add(command.toLowerCase());+ }+ const commandSafeLegacyGhosts: typeof movableLegacyGhosts = [];+ for (const legacy of movableLegacyGhosts) {+ const command = legacy.command?.toLowerCase() ?? null;+ if (command !== null && occupiedCommands.has(command)) {+ conflicts += 1;+ continue;+ }+ if (command !== null) occupiedCommands.add(command);+ commandSafeLegacyGhosts.push(legacy);+ }+ movableLegacyGhosts = commandSafeLegacyGhosts;+ if (movableLegacyGhosts.length === 0) {+ const result: OwnerNamespaceMigrationResult = {+ status: conflicts > 0 ? 'partial' : 'skipped',+ moved: 0,+ conflicts,+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+ }+ if (options.shouldAbort?.()) return { status: 'deferred', moved: 0, conflicts: 0 };+ const needsSharedClaim = movableLegacyGhosts.some((legacy) => sharedDirs.has(legacy.dir));+ if (needsSharedClaim && !marker) {+ marker = { version: 1, ownerKey, complete: false };+ try {+ await deps.writeFileExclusive(markerPath, JSON.stringify(marker));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;+ marker = await readMarker(deps, markerPath);+ if (!marker) throw new Error('owner namespace claim marker disappeared');+ if (marker.ownerKey !== ownerKey) {+ const scopedMovableGhosts = movableLegacyGhosts.filter(+ (legacy) => !sharedDirs.has(legacy.dir),+ );+ if (scopedMovableGhosts.length === 0) {+ const result: OwnerNamespaceMigrationResult = {+ status: 'claimed-by-other-owner',+ moved: 0,+ conflicts: 0,+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+ }+ conflicts += movableLegacyGhosts.length - scopedMovableGhosts.length;+ movableLegacyGhosts = scopedMovableGhosts;+ }+ }+ }+ const targetRootWasMissing = (await pathType(deps, targetRoot)) === 'missing';+ await deps.mkdir(targetRoot);+ if (!hasSafeRecoveryTargetChainSync(userDataDir, targetRoot)) {+ const result: OwnerNamespaceMigrationResult = {+ status: 'partial',+ moved: 0,+ conflicts: conflicts + movableLegacyGhosts.length,+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+ }+ const blockedRoots = new Set<string>();+ for (const legacyRoot of new Set(movableLegacyGhosts.map((legacy) => legacy.root))) {+ const sourceState = path.join(legacyRoot, BUILTIN_PROVISIONING_STATE_FILE);+ let sourceStateStats: fsSync.Stats;+ try {+ sourceStateStats = fsSync.lstatSync(sourceState);+ } catch (error) {+ if (isMissing(error)) continue;+ blockedRoots.add(legacyRoot);+ failed = true;+ log.warn('legacy ghost recovery blocked: provisioning state unreadable', {+ error: error instanceof Error ? error.message : String(error),+ });+ continue;+ }+ if (!sourceStateStats.isFile() || sourceStateStats.isSymbolicLink()) {+ blockedRoots.add(legacyRoot);+ failed = true;+ log.warn('legacy ghost recovery blocked: provisioning state is not a regular file');+ continue;+ }+ const targetState = path.join(targetRoot, BUILTIN_PROVISIONING_STATE_FILE);+ if (pathExistsNoFollowSync(targetState)) {+ blockedRoots.add(legacyRoot);+ failed = true;+ log.warn('legacy ghost recovery blocked: provisioning state target already exists');+ continue;+ }+ let racedPids: number[];+ try {+ racedPids = await findConcurrentLiveInstancePids(deps, userDataDir);+ } catch (error) {+ blockedRoots.add(legacyRoot);+ failed = true;+ concurrentRecoveryInterrupted = true;+ log.warn('legacy ghost recovery blocked: instance registry unreadable before state move', {+ error: error instanceof Error ? error.message : String(error),+ });+ continue;+ }+ if (racedPids.length > 0) {+ blockedRoots.add(legacyRoot);+ failed = true;+ concurrentRecoveryInterrupted = true;+ log.info('legacy ghost recovery blocked: instance started before state move', {+ racedPids,+ });+ continue;+ }+ if (options.shouldAbort?.()) {+ blockedRoots.add(legacyRoot);+ failed = true;+ continue;+ }+ try {+ await deps.rename(sourceState, targetState);+ if (options.shouldAbort?.()) {+ let rollbackAllowed = false;+ try {+ const rollbackPeers = await findConcurrentLiveInstancePids(deps, userDataDir);+ rollbackAllowed = rollbackPeers.length === 0;+ if (!rollbackAllowed) {+ concurrentRecoveryInterrupted = true;+ log.info('legacy ghost recovery skipped provisioning rollback: instance started', {+ racedPids: rollbackPeers,+ });+ }+ } catch (error) {+ concurrentRecoveryInterrupted = true;+ log.warn('legacy ghost recovery skipped provisioning rollback: registry unreadable', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ if (rollbackAllowed) {+ try {+ await deps.rename(targetState, sourceState);+ } catch (rollbackError) {+ provisioningStateMoved = true;+ log.warn('legacy ghost recovery could not roll back provisioning state', {+ error:+ rollbackError instanceof Error ? rollbackError.message : String(rollbackError),+ });+ }+ } else {+ provisioningStateMoved = true;+ }+ blockedRoots.add(legacyRoot);+ failed = true;+ continue;+ }+ provisioningStateMoved = true;+ } catch (error) {+ blockedRoots.add(legacyRoot);+ failed = true;+ log.warn('legacy ghost recovery failed to move provisioning state', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ if (blockedRoots.size > 0) {+ const blockedCount = movableLegacyGhosts.filter((legacy) =>+ blockedRoots.has(legacy.root)+ ).length;+ conflicts += blockedCount;+ movableLegacyGhosts = movableLegacyGhosts.filter(+ (legacy) => !blockedRoots.has(legacy.root),+ );+ }+ for (const legacy of movableLegacyGhosts) {+ if (options.shouldAbort?.()) {+ failed = true;+ break;+ }+ const target = path.join(targetRoot, legacy.id);+ if ((await pathType(deps, target)) !== 'missing') {+ conflicts += 1;+ continue;+ }+ let racedPids: number[];+ try {+ racedPids = await findConcurrentLiveInstancePids(deps, userDataDir);+ } catch (error) {+ failed = true;+ concurrentRecoveryInterrupted = true;+ log.warn('legacy ghost recovery interrupted: registry unreadable mid-recovery', {+ id: legacy.id,+ error: error instanceof Error ? error.message : String(error),+ });+ break;+ }+ if (racedPids.length > 0) {+ failed = true;+ concurrentRecoveryInterrupted = true;+ log.info('legacy ghost recovery interrupted: instance started mid-recovery', {+ id: legacy.id,+ racedPids,+ });+ break;+ }+ try {+ await deps.rename(legacy.dir, target);+ moved += 1;+ } catch (error) {+ failed = true;+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') {+ conflicts += 1;+ continue;+ }+ log.warn('legacy ghost recovery failed to move plugin', {+ id: legacy.id,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ for (const legacyRoot of new Set(movableLegacyGhosts.map((legacy) => legacy.root))) {+ if (options.shouldAbort?.()) {+ failed = true;+ break;+ }+ let cleanupPids: number[];+ try {+ cleanupPids = await findConcurrentLiveInstancePids(deps, userDataDir);+ } catch (error) {+ failed = true;+ concurrentRecoveryInterrupted = true;+ log.warn('legacy ghost recovery kept old root: registry unreadable before cleanup', {+ error: error instanceof Error ? error.message : String(error),+ });+ break;+ }+ if (cleanupPids.length > 0) {+ failed = true;+ concurrentRecoveryInterrupted = true;+ log.info('legacy ghost recovery kept old root: instance started before cleanup', {+ racedPids: cleanupPids,+ });+ break;+ }+ try {+ await deps.rmdir(legacyRoot);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOTEMPTY' && !isMissing(error)) {+ log.warn('legacy ghost recovery could not remove an empty root', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ }+ if (targetRootWasMissing && moved === 0 && !provisioningStateMoved) {+ let canRemoveTargetRoot = false;+ try {+ canRemoveTargetRoot =+ (await findConcurrentLiveInstancePids(deps, userDataDir)).length === 0;+ } catch (error) {+ log.warn('legacy ghost recovery kept empty target: instance registry unreadable', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ if (canRemoveTargetRoot && hasSafeRecoveryTargetChainSync(userDataDir, targetRoot)) {+ try {+ await deps.rmdir(targetRoot);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOTEMPTY' && !isMissing(error)) {+ log.warn('legacy ghost recovery could not remove empty target root', {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }+ }+ }+ const result: OwnerNamespaceMigrationResult = {+ status: failed || conflicts > 0 ? 'partial' : 'migrated',+ moved,+ conflicts,+ ...(provisioningStateMoved ? { provisioningStateMoved: true } : {}),+ ...(concurrentRecoveryInterrupted+ ? { deferredReason: 'concurrent-live-instances' as const }+ : {}),+ };+ recordLegacyGhostMigrationResult(ownerId, result, userDataDir);+ return result;+}+async function pathType(deps: MigrationDeps,file: string,@@ -618,4 +1379,10 @@ export async function claimLegacyOwnerNamespace(return { status: failed ? 'partial' : 'migrated', moved, conflicts };}-export const __testing = { CLAIM_MARKER, LEGACY_PATHS, isSameUserDataDir };+export const __testing = {+ CLAIM_MARKER,+ LEGACY_PATHS,+ isSameUserDataDir,+ pathExistsNoFollowSync,+ resetLegacyGhostRecoveryState: () => legacyGhostMigrationResults.clear(),+};diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 4b1870ed04..d7b19bb02f 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -900,6 +900,10 @@ contextBridge.exposeInMainWorld('electronAPI', {runtimeStates: (): Promise<{ states: Record<string, string> }> =>ipcRenderer.invoke('ghosts:runtime-states'),reload: (id: string): Promise<{ state: string }> => ipcRenderer.invoke('ghosts:reload', id),+ legacyRecoveryStatus: (): Promise<import('../shared/legacyGhostRecovery').LegacyGhostRecoveryStatus> =>+ ipcRenderer.invoke('ghosts:legacy-recovery-status'),+ retryLegacyRecovery: (): Promise<import('../shared/legacyGhostRecovery').LegacyGhostRecoveryStatus> =>+ ipcRenderer.invoke('ghosts:retry-legacy-recovery'),// dev-only 运行时控制(packaged 版 main 侧不注册该 channel)。devRuntime: (action: 'status' | 'spawn' | 'stop' | 'crash', id?: string): Promise<unknown> =>ipcRenderer.invoke('ghosts:dev-runtime', action, id),diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsxindex 1c988a86ba..20189e9f80 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx@@ -49,6 +49,7 @@ import type {PluginMarketItem,PluginMarketSnapshot,} from '../../../shared/pluginMarket';+import type { LegacyGhostRecoveryStatus } from '../../../shared/legacyGhostRecovery';import {toGhostPluginDetail,toGhostPluginListItem,@@ -106,6 +107,14 @@ export function GhostPluginPage() {const { user, mode, dataOwnerId } = useAuth();const showEnterprise = user?.membershipKind === 'org';const ghosts = useInstalledGhosts();+ const installedGhostIdsKey = ghosts+ .map((ghost) => ghost.manifest.id)+ .sort()+ .join('\0');+ const installedGhostLocationsKey = ghosts+ .map((ghost) => `${ghost.manifest.id}\0${ghost.dir}`)+ .sort()+ .join('\0');const [selectedId, setSelectedId] = useState<string | null>(null);const [query, setQuery] = useState('');const [installedExpanded, setInstalledExpanded] = useState(false);@@ -135,6 +144,12 @@ export function GhostPluginPage() {);const marketRefreshRequestRef = useRef(0);const marketDetailRequestRef = useRef(0);+ const installedGhostIdsKeyRef = useRef(installedGhostIdsKey);+ const legacyRecoveryStatusRequestRef = useRef(0);+ const legacyRecoveryRetryRequestRef = useRef(0);+ const [legacyRecoveryStatus, setLegacyRecoveryStatus] =+ useState<LegacyGhostRecoveryStatus | null>(null);+ const [legacyRecoveryRetrying, setLegacyRecoveryRetrying] = useState(false);const refreshMarket = useCallback(async (preserveOnError = false) => {const requestId = ++marketRefreshRequestRef.current;try {@@ -170,6 +185,13 @@ export function GhostPluginPage() {marketDetailRequestRef.current += 1;void refreshMarket();}, [refreshMarket, mode, dataOwnerId]);+ useEffect(() => {+ if (installedGhostIdsKeyRef.current === installedGhostIdsKey) return;+ installedGhostIdsKeyRef.current = installedGhostIdsKey;+ // refreshMarket(true) reports an unavailable market by rejecting after preserving+ // the current snapshot; the state update already happened in refreshMarket.+ void refreshMarket(true).catch(() => undefined);+ }, [installedGhostIdsKey, refreshMarket]);const activeSessionWorkingDir = useSyncExternalStore(subscribeToLastWorkingDir,getLastWorkingDir,@@ -221,6 +243,29 @@ export function GhostPluginPage() {}),[],);+ useEffect(() => {+ legacyRecoveryStatusRequestRef.current += 1;+ legacyRecoveryRetryRequestRef.current += 1;+ setLegacyRecoveryRetrying(false);+ }, [dataOwnerId, mode]);+ useEffect(() => {+ const requestId = ++legacyRecoveryStatusRequestRef.current;+ if (mode !== 'cloud' || !dataOwnerId) {+ setLegacyRecoveryStatus(null);+ return;+ }+ void window.electronAPI.ghosts+ .legacyRecoveryStatus()+ .then((status) => {+ if (requestId !== legacyRecoveryStatusRequestRef.current) return;+ setLegacyRecoveryStatus(status.state === 'none' ? null : status);+ })+ .catch(() => {+ if (requestId === legacyRecoveryStatusRequestRef.current) {+ setLegacyRecoveryStatus(null);+ }+ });+ }, [dataOwnerId, installedGhostLocationsKey, mode]);// /plugins?ghost=<id> 深链:直接打开该插件详情(配置就绪弹窗等入口复用;// 读后即清参数,避免从详情返回列表后又被同一参数拉回详情)。useEffect(() => {@@ -458,6 +503,30 @@ export function GhostPluginPage() {await confirmAndInstallGhost(picked.filePath, { t, confirm, confirmWithCheckbox });}, [confirm, confirmWithCheckbox, t]);+ const handleRetryLegacyRecovery = useCallback(async () => {+ legacyRecoveryStatusRequestRef.current += 1;+ const requestId = ++legacyRecoveryRetryRequestRef.current;+ setLegacyRecoveryRetrying(true);+ try {+ const status = await window.electronAPI.ghosts.retryLegacyRecovery();+ if (requestId === legacyRecoveryRetryRequestRef.current) {+ setLegacyRecoveryStatus(status.state === 'none' ? null : status);+ }+ } catch {+ const status = await window.electronAPI.ghosts.legacyRecoveryStatus().catch(() => null);+ if (requestId === legacyRecoveryRetryRequestRef.current) {+ setLegacyRecoveryStatus(status && status.state !== 'none' ? status : null);+ }+ } finally {+ if (requestId === legacyRecoveryRetryRequestRef.current) {+ await refreshMarket().catch(() => undefined);+ if (requestId === legacyRecoveryRetryRequestRef.current) {+ setLegacyRecoveryRetrying(false);+ }+ }+ }+ }, [refreshMarket]);+const handleCreateWithCindy = useCallback(() => {saveComposerDraft(NEW_MAKER_DRAFT_KEY, {text: plainTextToTiptapDoc(t('settings.ghosts.page.createPrompt')),@@ -840,6 +909,14 @@ export function GhostPluginPage() {</p>) : null}+ {legacyRecoveryStatus ? (+ <LegacyGhostRecoveryNotice+ status={legacyRecoveryStatus}+ retrying={legacyRecoveryRetrying}+ onRetry={() => void handleRetryLegacyRecovery()}+ />+ ) : null}+{items.length > 0 || availableMarketItems.length > 0 ? (<div className={cn('plugin-motion-stagger', PLUGIN_MANAGEMENT_CARD_GRID_CLASS)}>{items.map((item) => (@@ -869,7 +946,7 @@ export function GhostPluginPage() {/>))}</div>- ) : (+ ) : !legacyRecoveryStatus ? (<div className="rounded-xl border-[0.5px] border-[var(--border-default)] px-5 py-10 text-center"><p className="text-13 text-[var(--text-secondary)]">{installedItems.length === 0 && marketItems.length === 0@@ -882,7 +959,7 @@ export function GhostPluginPage() {</p>) : null}</div>- )}+ ) : null}</section></PluginManagementPage></main>@@ -890,6 +967,53 @@ export function GhostPluginPage() {);}+export function LegacyGhostRecoveryNotice({+ status,+ retrying,+ onRetry,+}: {+ status: LegacyGhostRecoveryStatus;+ retrying: boolean;+ onRetry: () => void;+}) {+ const { t } = useTranslation();+ if (status.state === 'none') return null;+ const messageKey =+ status.state === 'claimed-by-other-owner'+ ? 'settings.ghosts.legacyRecovery.claimedByOtherOwner'+ : status.state === 'partial' || status.canRetry+ ? status.canRetry+ ? 'settings.ghosts.legacyRecovery.partial'+ : 'settings.ghosts.legacyRecovery.partialBlocked'+ : 'settings.ghosts.legacyRecovery.deferred';+ return (+ <div className="rounded-xl border-[0.5px] border-[var(--border-default)] bg-[var(--surface-elevated)] px-5 py-6 text-left">+ <p className="text-14 font-medium text-[var(--text-primary)]">+ {t('settings.ghosts.legacyRecovery.title')}+ </p>+ <p className="mt-2 text-13 leading-5 text-[var(--text-secondary)]">+ {t(messageKey, { count: status.legacyPluginCount })}+ </p>+ {status.canRetry ? (+ <button+ type="button"+ onClick={onRetry}+ disabled={retrying}+ className={cn(+ 'mt-4 inline-flex h-9 items-center rounded-full border border-[var(--border-default)] px-4 text-12 font-medium text-[var(--text-primary)]',+ 'transition-[background-color,border-color,opacity,transform] duration-150 hover:bg-[var(--surface-hover-soft)] active:scale-[0.98]',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:cursor-wait disabled:opacity-55 disabled:active:scale-100',+ )}+ >+ {retrying+ ? t('settings.ghosts.legacyRecovery.retrying')+ : t('settings.ghosts.legacyRecovery.retry')}+ </button>+ ) : null}+ </div>+ );+}+export function MarketPluginCard({item,busy,diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsxindex a87bef8bcd..fe81dbe8da 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx@@ -25,6 +25,7 @@ import {InstalledGhostQueue,InstalledGhostShortcut,MarketPluginCard,+ LegacyGhostRecoveryNotice,} from '../GhostPluginPage';import type { GhostPluginListItem } from '../lib/ghostPluginViewModel';import type { PluginMarketItem } from '../../../../shared/pluginMarket';@@ -256,3 +257,60 @@ describe('GhostPluginCard', () => {expect(screen.getByText('Cindy').className).toContain('truncate');});});++describe('LegacyGhostRecoveryNotice', () => {+ it('shows a retry action for deferred recovery', () => {+ const onRetry = vi.fn();+ render(+ <LegacyGhostRecoveryNotice+ status={{ state: 'deferred', legacyPluginCount: 2, canRetry: true }}+ retrying={false}+ onRetry={onRetry}+ />,+ );++ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.legacyRecovery.retry' }));+ expect(onRetry).toHaveBeenCalledTimes(1);+ expect(screen.getByText('settings.ghosts.legacyRecovery.partial')).toBeTruthy();+ });++ it('renders nothing for the none state', () => {+ const { container } = render(+ <LegacyGhostRecoveryNotice+ status={{ state: 'none', legacyPluginCount: 0, canRetry: false }}+ retrying={false}+ onRetry={vi.fn()}+ />,+ );++ expect(container.firstChild).toBeNull();+ });++ it('does not offer retry for data claimed by another owner', () => {+ render(+ <LegacyGhostRecoveryNotice+ status={{ state: 'claimed-by-other-owner', legacyPluginCount: 1, canRetry: false }}+ retrying={false}+ onRetry={vi.fn()}+ />,+ );++ expect(screen.getByText('settings.ghosts.legacyRecovery.claimedByOtherOwner')).toBeTruthy();+ expect(screen.queryByRole('button')).toBeNull();+ });++ it('does not offer retry when every legacy plugin has a destination conflict', () => {+ render(+ <LegacyGhostRecoveryNotice+ status={{ state: 'partial', legacyPluginCount: 2, canRetry: false }}+ retrying={false}+ onRetry={vi.fn()}+ />,+ );++ expect(+ screen.getByText('settings.ghosts.legacyRecovery.partialBlocked'),+ ).toBeTruthy();+ expect(screen.queryByRole('button')).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 55e6120130..ce4f26c22f 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -2305,6 +2305,23 @@"install": "Install Plugin…","empty": "No plugins installed yet","emptyHint": "Install from the market, or import a .cindy file from the menu above",+ "legacyRecovery": {+ "title": "Plugins from an older version are waiting to be restored",+ "deferred": "Found {{count}} older plugin directory. Cindy deferred restoration to avoid moving data while another instance may still be using it.",+ "deferred_one": "Found {{count}} older plugin directory. Cindy deferred restoration to avoid moving data while another instance may still be using it.",+ "deferred_other": "Found {{count}} older plugin directories. Cindy deferred restoration to avoid moving data while another instance may still be using it.",+ "partial": "Found {{count}} older plugin directory. Some data was not restored automatically, so you can retry now.",+ "partial_one": "Found {{count}} older plugin directory. Some data was not restored automatically, so you can retry now.",+ "partial_other": "Found {{count}} older plugin directories. Some data was not restored automatically, so you can retry now.",+ "partialBlocked": "Found {{count}} older plugin directory, but Cindy could not safely restore it automatically. The data was kept unchanged.",+ "partialBlocked_one": "Found {{count}} older plugin directory, but Cindy could not safely restore it automatically. The data was kept unchanged.",+ "partialBlocked_other": "Found {{count}} older plugin directories, but Cindy could not safely restore them automatically. The data was kept unchanged.",+ "claimedByOtherOwner": "Found {{count}} older plugin directory, but it belongs to the first account that claimed this device data. Switch back to that account to restore it.",+ "claimedByOtherOwner_one": "Found {{count}} older plugin directory, but it belongs to the first account that claimed this device data. Switch back to that account to restore it.",+ "claimedByOtherOwner_other": "Found {{count}} older plugin directories, but it belongs to the first account that claimed this device data. Switch back to that account to restore it.",+ "retry": "Retry restoring",+ "retrying": "Restoring…"+ },"disabledTag": "Disabled","projectDisabledTag": "Off in this project","projectSwitchLockedTip": "This plugin is disabled globally; enable it in the Global view first",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 08a7d1386c..5e8d80ce8c 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -2304,6 +2304,23 @@"install": "プラグインをインストール…","empty": "まだプラグインがインストールされていません","emptyHint": "マーケットからインストールするか、上のメニューから .cindy ファイルを読み込めます",+ "legacyRecovery": {+ "title": "旧バージョンのプラグインを復元できます",+ "deferred": "{{count}} 個の旧プラグインディレクトリを検出しました。他のインスタンスが使用中の可能性があるため、復元を保留しました。",+ "deferred_one": "{{count}} 個の旧プラグインディレクトリを検出しました。他のインスタンスが使用中の可能性があるため、復元を保留しました。",+ "deferred_other": "{{count}} 個の旧プラグインディレクトリを検出しました。他のインスタンスが使用中の可能性があるため、復元を保留しました。",+ "partial": "{{count}} 個の旧プラグインディレクトリを検出しました。一部を自動復元できなかったため、再試行できます。",+ "partial_one": "{{count}} 個の旧プラグインディレクトリを検出しました。一部を自動復元できなかったため、再試行できます。",+ "partial_other": "{{count}} 個の旧プラグインディレクトリを検出しました。一部を自動復元できなかったため、再試行できます。",+ "partialBlocked": "{{count}} 個の旧プラグインディレクトリを検出しましたが、Cindy は安全に自動復元できませんでした。データは変更せず保持されています。",+ "partialBlocked_one": "{{count}} 個の旧プラグインディレクトリを検出しましたが、Cindy は安全に自動復元できませんでした。データは変更せず保持されています。",+ "partialBlocked_other": "{{count}} 個の旧プラグインディレクトリを検出しましたが、Cindy は安全に自動復元できませんでした。データは変更せず保持されています。",+ "claimedByOtherOwner": "{{count}} 個の旧プラグインディレクトリを検出しましたが、このデータは最初に取得したアカウントに属します。元のアカウントに戻って復元してください。",+ "claimedByOtherOwner_one": "{{count}} 個の旧プラグインディレクトリを検出しましたが、このデータは最初に取得したアカウントに属します。元のアカウントに戻って復元してください。",+ "claimedByOtherOwner_other": "{{count}} 個の旧プラグインディレクトリを検出しましたが、このデータは最初に取得したアカウントに属します。元のアカウントに戻って復元してください。",+ "retry": "復元を再試行",+ "retrying": "復元中…"+ },"disabledTag": "無効","projectDisabledTag": "このプロジェクトでは無効","projectSwitchLockedTip": "このプラグインはグローバルで無効です。先に「グローバル」ビューで有効にしてください",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 92c243a1d3..0329271da9 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -2304,6 +2304,23 @@"install": "플러그인 설치…","empty": "아직 설치된 플러그인이 없습니다","emptyHint": "마켓에서 설치하거나 위 메뉴에서 .cindy 파일을 가져올 수 있습니다",+ "legacyRecovery": {+ "title": "이전 버전 플러그인을 복원할 수 있습니다",+ "deferred": "이전 플러그인 디렉터리 {{count}}개를 찾았습니다. 다른 인스턴스가 사용 중일 수 있어 복원을 보류했습니다.",+ "deferred_one": "이전 플러그인 디렉터리 {{count}}개를 찾았습니다. 다른 인스턴스가 사용 중일 수 있어 복원을 보류했습니다.",+ "deferred_other": "이전 플러그인 디렉터리 {{count}}개를 찾았습니다. 다른 인스턴스가 사용 중일 수 있어 복원을 보류했습니다.",+ "partial": "이전 플러그인 디렉터리 {{count}}개를 찾았습니다. 일부를 자동 복원하지 못했으므로 다시 시도할 수 있습니다.",+ "partial_one": "이전 플러그인 디렉터리 {{count}}개를 찾았습니다. 일부를 자동 복원하지 못했으므로 다시 시도할 수 있습니다.",+ "partial_other": "이전 플러그인 디렉터리 {{count}}개를 찾았습니다. 일부를 자동 복원하지 못했으므로 다시 시도할 수 있습니다.",+ "partialBlocked": "이전 플러그인 디렉터리 {{count}}개를 찾았지만 Cindy가 안전하게 자동 복원할 수 없었습니다. 관련 데이터는 변경하지 않고 그대로 유지했습니다.",+ "partialBlocked_one": "이전 플러그인 디렉터리 {{count}}개를 찾았지만 Cindy가 안전하게 자동 복원할 수 없었습니다. 관련 데이터는 변경하지 않고 그대로 유지했습니다.",+ "partialBlocked_other": "이전 플러그인 디렉터리 {{count}}개를 찾았지만 Cindy가 안전하게 자동 복원할 수 없었습니다. 관련 데이터는 변경하지 않고 그대로 유지했습니다.",+ "claimedByOtherOwner": "이전 플러그인 디렉터리 {{count}}개를 찾았지만, 이 데이터는 처음 소유권을 가져간 계정에 속합니다. 원래 계정으로 전환해 복원하세요.",+ "claimedByOtherOwner_one": "이전 플러그인 디렉터리 {{count}}개를 찾았지만, 이 데이터는 처음 소유권을 가져간 계정에 속합니다. 원래 계정으로 전환해 복원하세요.",+ "claimedByOtherOwner_other": "이전 플러그인 디렉터리 {{count}}개를 찾았지만, 이 데이터는 처음 소유권을 가져간 계정에 속합니다. 원래 계정으로 전환해 복원하세요.",+ "retry": "복원 다시 시도",+ "retrying": "복원 중…"+ },"disabledTag": "비활성","projectDisabledTag": "이 프로젝트에서 꺼짐","projectSwitchLockedTip": "이 플러그인은 전역에서 비활성 상태입니다. 먼저 '전역' 보기에서 활성화해 주세요",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex a8b6640dc5..ac14f13088 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -2304,6 +2304,23 @@"install": "安装插件…","empty": "还没有安装任何插件","emptyHint": "可从插件市场安装,或点击右上角导入 .cindy 文件",+ "legacyRecovery": {+ "title": "旧版本插件正在等待恢复",+ "deferred": "检测到 {{count}} 个旧插件目录。为避免其它实例仍在使用这些数据,Cindy 暂缓了自动恢复。",+ "deferred_one": "检测到 {{count}} 个旧插件目录。为避免其它实例仍在使用这些数据,Cindy 暂缓了自动恢复。",+ "deferred_other": "检测到 {{count}} 个旧插件目录。为避免其它实例仍在使用这些数据,Cindy 暂缓了自动恢复。",+ "partial": "检测到 {{count}} 个旧插件目录。部分数据未能自动恢复,可以现在重试。",+ "partial_one": "检测到 {{count}} 个旧插件目录。部分数据未能自动恢复,可以现在重试。",+ "partial_other": "检测到 {{count}} 个旧插件目录。部分数据未能自动恢复,可以现在重试。",+ "partialBlocked": "检测到 {{count}} 个旧插件目录,但 Cindy 无法安全地自动恢复。相关数据已原样保留。",+ "partialBlocked_one": "检测到 {{count}} 个旧插件目录,但 Cindy 无法安全地自动恢复。相关数据已原样保留。",+ "partialBlocked_other": "检测到 {{count}} 个旧插件目录,但 Cindy 无法安全地自动恢复。相关数据已原样保留。",+ "claimedByOtherOwner": "检测到 {{count}} 个旧插件目录,但这批数据已归属于最先认领它的账号。请切回原身份恢复。",+ "claimedByOtherOwner_one": "检测到 {{count}} 个旧插件目录,但这批数据已归属于最先认领它的账号。请切回原身份恢复。",+ "claimedByOtherOwner_other": "检测到 {{count}} 个旧插件目录,但这批数据已归属于最先认领它的账号。请切回原身份恢复。",+ "retry": "重试恢复",+ "retrying": "正在恢复…"+ },"disabledTag": "未生效","projectDisabledTag": "本项目未生效","projectSwitchLockedTip": "该插件已在全局停用;请先切回「全局」视图开启",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 36d3d181c7..4daf89c1aa 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1216,6 +1216,8 @@ interface ElectronAPI {runtimeStates: () => Promise<{ states: Record<string, string> }>;/** 面板错误态「重载意识」:清熔断记账 + 重新拉起沙箱。 */reload: (id: string) => Promise<{ state: string }>;+ legacyRecoveryStatus: () => Promise<import('../shared/legacyGhostRecovery').LegacyGhostRecoveryStatus>;+ retryLegacyRecovery: () => Promise<import('../shared/legacyGhostRecovery').LegacyGhostRecoveryStatus>;/** dev-only 运行时控制(packaged 版 main 侧不注册,调用会 reject)。 */devRuntime: (action: 'status' | 'spawn' | 'stop' | 'crash',diff --git a/apps/desktop/src/shared/legacyGhostRecovery.ts b/apps/desktop/src/shared/legacyGhostRecovery.tsnew file mode 100644index 0000000000..885f9c6678--- /dev/null+++ b/apps/desktop/src/shared/legacyGhostRecovery.ts@@ -0,0 +1,19 @@+/**+ * Renderer-safe projection of the legacy Plugin namespace recovery state.+ *+ * Main intentionally exposes only a coarse status and a count. Owner ids,+ * filesystem paths, manifests, settings, and credentials never cross IPC.+ */+export type LegacyGhostRecoveryState = 'none' | 'deferred' | 'partial' | 'claimed-by-other-owner';++export interface LegacyGhostRecoveryStatus {+ state: LegacyGhostRecoveryState;+ legacyPluginCount: number;+ canRetry: boolean;+}++export const NO_LEGACY_GHOST_RECOVERY: LegacyGhostRecoveryStatus = {+ state: 'none',+ legacyPluginCount: 0,+ canRetry: false,+};