Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): 修复插件账号归属与市场来源恢复

liugaoweia335c8c7ed12
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 20ff728b52..e8c9142ecb 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -167,6 +167,15 @@ export interface GhostManagerLogger {
error?(message: string, meta?: Record<string, unknown>): void;
}
+export interface ApprovedGhostInstallEvidence {
+ /** Immutable package hash when the approval came from a modern install/update. */
+ packageSha256: string | null;
+ /** Unlocalized manifest frozen in the Host approval receipt. */
+ approvedManifest: GhostManifest;
+ /** True only when the completed one-time migration explicitly recorded this id. */
+ legacyMigrated: boolean;
+}
+
export interface GhostManagerOptions {
/** 意识仓库根目录(生产:userData/cindy-brain;测试:os.tmpdir 下临时目录)。 */
getRootDir: () => string;
@@ -1041,6 +1050,30 @@ export class GhostManager {
return this.receiptStore.rootDir();
}
+ /**
+ * Host-owned evidence for reconnecting an installation to retained source metadata.
+ * A pending package mutation or an invalid approval fails closed. Legacy provenance
+ * is accepted only from the completed one-time migration's explicit id list.
+ */
+ approvedInstallEvidence(id: string): ApprovedGhostInstallEvidence | null {
+ this.ensureCurrentOwnerContextSync();
+ if (!isValidGhostId(id) || this.hasPendingMutationJournal(id)) return null;
+ const approval = this.readApproval(id);
+ if (approval.state !== 'approved') return null;
+ const packageSha256 = approval.receipt.packageSha256;
+ const migration = this.receiptStore.readMigrationLedger();
+ return {
+ packageSha256:
+ packageSha256 && /^[a-f0-9]{64}$/.test(packageSha256) ? packageSha256 : null,
+ approvedManifest: approval.receipt.manifest,
+ legacyMigrated: Boolean(
+ migration
+ && migration.state !== 'in-progress'
+ && migration.migratedIds.includes(id)
+ ),
+ };
+ }
+
/**
* 启停投影:receipt 为主,安装目录 `.disabled` 镜像**只往停用方向覆盖**(读时合并)。
*
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
index b26b8b4d23..abb980b173 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -271,6 +271,11 @@ describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () =>
approval: { state: 'approved' },
});
expect(fs.existsSync(migrationLedgerPath())).toBe(true);
+ expect(manager.approvedInstallEvidence('hello')).toMatchObject({
+ packageSha256: null,
+ approvedManifest: { id: 'hello', version: '1.0.0' },
+ legacyMigrated: true,
+ });
});
it('带 setup.kv 的旧安装无感迁移并保留标准化就绪声明', async () => {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
index 24721dc9aa..79d7acd7f3 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
@@ -22,8 +22,8 @@ describe('market Ghost session boundary', () => {
const captureEnd = source.indexOf('\n}\n', captureStart);
const captureBody = source.slice(captureStart, captureEnd);
expect(captureBody).toContain('isAppSessionBoundaryPending()');
- expect(captureBody).toContain('const owner = getActiveAppSession();');
- expect(captureBody).toContain('isGhostSkillProjectionBoundaryStableForOwner(owner.dataOwnerId)');
+ expect(captureBody).toContain('return getActiveAppSession();');
+ expect(captureBody).not.toContain('isGhostSkillProjectionBoundaryStableForOwner');
const leaseStart = source.indexOf(
'function beginGhostMutation(expectedOwner?: ActiveAppSession): () => void {',
@@ -34,6 +34,7 @@ describe('market Ghost session boundary', () => {
expect(leaseBody).toContain('currentOwner.mode !== expectedOwner.mode');
expect(leaseBody).toContain('currentOwner.dataOwnerId !== expectedOwner.dataOwnerId');
expect(leaseBody).toContain('currentOwner.generation !== expectedOwner.generation');
+ expect(leaseBody).not.toContain('isGhostSkillProjectionBoundaryStableForOwner');
});
it('captures before async inspection but leases only after Node authorization', () => {
@@ -192,24 +193,22 @@ describe('market Ghost session boundary', () => {
expect(body).toContain("throwIpcError('INTERNAL', 'Unable to detach the installed Plugin source');");
});
- it('Ghost 媒体在途守卫注入 durable owner 组合条件,而不是退化成只看进程内边界', () => {
+ it('Ghost 媒体在途守卫只依赖当前进程的 AppSession owner 边界', () => {
const helperStart = source.indexOf('function isGhostBoundaryPending(): boolean {');
expect(helperStart).toBeGreaterThan(-1);
const helperEnd = source.indexOf('\n}\n', helperStart);
const helperBody = source.slice(helperStart, helperEnd);
- // helper 必须是组合条件:进程内 App boundary + durable projection owner 稳定性。
expect(helperBody).toContain('isAppSessionBoundaryPending()');
- expect(helperBody).toContain('isGhostSkillProjectionBoundaryStableForOwner');
+ expect(helperBody).not.toContain('isGhostSkillProjectionBoundaryStableForOwner');
// 两处 Ghost 专属消费点(xAI 通道与 GhostCindySlot)都必须走 helper。
const injections =
source.match(/isOwnerBoundaryPending: \(\) => isGhostBoundaryPending\(\)/g)?.length ?? 0;
expect(injections).toBeGreaterThanOrEqual(2);
});
- it('Ghost 媒体持久化写入守卫(resolveOwnedMedia/saveGhostMedia)也用 durable owner 组合条件', () => {
+ it('Ghost 媒体持久化写入守卫也绑定当前进程的 owner scope', () => {
// 这两处是 GhostCindySlot 的 deps,内部 assertStillValid 会在 ingestMedia 的
- // await 边界反复断言。持久化写入守卫必须和入口/生成守卫一样用 isGhostBoundaryPending,
- // 否则另一实例在落盘窗口翻转 durable owner 时,字节仍会被登记为 ghost-gallery ref。
+ // await 边界反复断言。持久化写入守卫必须同时检查本进程边界与 scope generation。
const resolveStart = source.indexOf('resolveOwnedMedia: async (ghostId, hash, ownerScopeKey)');
const saveStart = source.indexOf('saveGhostMedia: async ({ ghostId, buffer, mimeType, ownerScopeKey');
expect(resolveStart).toBeGreaterThan(-1);
@@ -219,15 +218,15 @@ describe('market Ghost session boundary', () => {
const combinedGuard = 'isGhostBoundaryPending() || activeOwnerScopeKey() !== ownerScopeKey';
expect(resolveBody).toContain(combinedGuard);
expect(saveBody).toContain(combinedGuard);
- // 持久化守卫不得退化回只看进程内边界的旧写法。
+ // generation 不能退化成只看 pending 位。
expect(source).not.toContain('isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScopeKey');
});
- it('networkSlot 的 saveGhostMedia(as:media fetch 落仓)也用 durable owner 组合条件', () => {
+ it('networkSlot 的 saveGhostMedia(as:media fetch 落仓)也绑定本地 owner scope', () => {
// networkSlot 与 cindy 槽是两个独立实现,签名不带 ownerScopeKey(在函数体开头
// 捕获)。它的落仓路径(ghost-gallery 作品归属 + recordGhostCallMedia)必须同样
- // 有 durable owner 守卫 + assertStillValid + 补偿 journal,否则 as:'media' fetch
- // 读取窗口内 durable owner 翻转时仍会落仓到错误 owner 的画廊。
+ // 有本地 owner 守卫 + assertStillValid + 补偿 journal,否则账号切换期间的
+ // as:'media' fetch 仍可能落仓到错误 owner 的画廊。
const networkStart = source.indexOf('saveGhostMedia: async ({ ghostId, buffer, mimeType, label, callId }) =>');
expect(networkStart).toBeGreaterThan(-1);
const networkBody = source.slice(networkStart, networkStart + 1800);
@@ -237,9 +236,9 @@ describe('market Ghost session boundary', () => {
expect(networkBody).toContain('refCompensationScope: captureMediaRefCompensationScope(ownerScopeKey)');
});
- it('depositMedia(ghost-deposit 寄存器落仓)也用 durable owner 组合条件', () => {
+ it('depositMedia(ghost-deposit 寄存器落仓)也绑定本地 owner scope', () => {
// 寄存器引用按 ghostId 落到 owner 作用域账本(originKind:'user' 但 refId 仍是意识),
- // 落仓窗口翻转全局 owner 时必须 fail closed,与 saveGhostMedia 同口径。
+ // 本进程账号切换时必须 fail closed,与 saveGhostMedia 同口径。
const depositStart = source.indexOf('depositMedia: async ({ ghostId, buffer, mimeType, label }) =>');
expect(depositStart).toBeGreaterThan(-1);
const depositBody = source.slice(depositStart, depositStart + 1800);
diff --git a/apps/desktop/src/main/cindy-brain/ghostOwnerScope.ts b/apps/desktop/src/main/cindy-brain/ghostOwnerScope.ts
index f4c1c03adb..8e0fcf25e0 100644
--- a/apps/desktop/src/main/cindy-brain/ghostOwnerScope.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostOwnerScope.ts
@@ -5,7 +5,7 @@ export interface GhostOwnerScope {
capture(): unknown;
/** Check the captured in-process owner and generation. */
isCurrent(scope: unknown): boolean;
- /** Check the durable projection marker for the captured owner. */
+ /** Check that the captured process-local owner boundary is still settled. */
isStable(scope: unknown): boolean;
/** Stop stale runtime work and discard owner-bound buffered work. */
onInvalidated?(ghostId: string): void;
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 2c78f13f5b..bebda583bf 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -51,10 +51,7 @@ import type {
PluginMarketPackageReviewFacts,
} from '../../shared/pluginMarket.js';
import { getAppCapabilities } from '../appCapabilities.js';
-import {
- isGhostSkillProjectionBoundaryStableForOwner,
- withGhostSkillProjectionReconcile,
-} from '../authBoundaryQuarantine.js';
+import { withGhostSkillProjectionReconcile } from '../authBoundaryQuarantine.js';
import {
activeOwnerScopeKey,
getActiveDataOwnerPushStamp,
@@ -510,11 +507,7 @@ function captureGhostMutationOwner(): ActiveAppSession {
if (isAppSessionBoundaryPending()) {
throw new Error('账号切换中,已取消本次 Plugin 操作');
}
- const owner = getActiveAppSession();
- if (!isGhostSkillProjectionBoundaryStableForOwner(owner.dataOwnerId)) {
- throw new Error('Plugin owner boundary is not durably stable');
- }
- return owner;
+ return getActiveAppSession();
}
/**
@@ -528,9 +521,6 @@ function beginGhostMutation(expectedOwner?: ActiveAppSession): () => void {
throw new Error('账号切换中,已取消本次 Plugin 操作');
}
const currentOwner = getActiveAppSession();
- if (!isGhostSkillProjectionBoundaryStableForOwner(currentOwner.dataOwnerId)) {
- throw new Error('Plugin owner boundary is not durably stable');
- }
if (expectedOwner) {
if (
currentOwner.mode !== expectedOwner.mode ||
@@ -561,9 +551,9 @@ const ghostOwnerScope: GhostOwnerScope = {
isCurrent: (scope) =>
!!scope && isSameAppSession(scope as ActiveAppSession, getActiveAppSession()),
isStable: (scope) =>
- !!scope && isGhostSkillProjectionBoundaryStableForOwner(
- (scope as ActiveAppSession).dataOwnerId,
- ),
+ !!scope
+ && !isAppSessionBoundaryPending()
+ && isSameAppSession(scope as ActiveAppSession, getActiveAppSession()),
onInvalidated: (ghostId) => {
try {
getGhostRuntime().stop(ghostId);
@@ -830,8 +820,7 @@ export function waitForGhostMutations(): Promise<void> {
/** Account-managed built-ins are unavailable outside a verified cloud session. */
export function isGhostAvailableForActiveSession(id: string): boolean {
- const activeOwner = getActiveAppSession().dataOwnerId;
- if (!isGhostSkillProjectionBoundaryStableForOwner(activeOwner)) return false;
+ if (isAppSessionBoundaryPending()) return false;
return !isCindyAccountGhostId(id) || getAppCapabilities().canUseCindyAccountServices;
}
@@ -904,14 +893,10 @@ export function listAvailableGhostsForAuthorization(): InstalledGhost[] {
function requireGhostAvailableForActiveSession(id: string): void {
if (!isGhostAvailableForActiveSession(id)) {
- const activeOwner = getActiveAppSession().dataOwnerId;
- if (
- isAppSessionBoundaryPending() ||
- !isGhostSkillProjectionBoundaryStableForOwner(activeOwner)
- ) {
+ if (isAppSessionBoundaryPending()) {
throwIpcError(
'PRECONDITION_FAILED',
- 'Ghost projection is switching owners; retry after the boundary settles.',
+ 'Plugin owner is switching; retry after the boundary settles.',
);
}
throwIpcError('PERMISSION_DENIED', 'This Plugin requires a Cindy account.');
@@ -3408,17 +3393,11 @@ function resolveImageChannelForModel(model: string, operation: 'generate' | 'edi
}
/**
- * Combined Ghost-owner boundary gate for Ghost-only paths (media generation,
- * cindy-slot work). Unlike the app-wide isAppSessionBoundaryPending(), this
- * also fails closed while the durable projection owner (shared global marker)
- * differs, so a sibling instance flipping the owner cannot let an in-flight
- * Ghost task keep calling upstream or saving media.
+ * Plugin media and storage use the same process-local AppSession owner
+ * boundary as the rest of the owner-scoped runtime.
*/
function isGhostBoundaryPending(): boolean {
- return (
- isAppSessionBoundaryPending() ||
- !isGhostSkillProjectionBoundaryStableForOwner(getActiveAppSession().dataOwnerId)
- );
+ return isAppSessionBoundaryPending();
}
export function getGhostCindySlot(): GhostCindySlot {
@@ -3716,8 +3695,8 @@ export function getGhostCindySlot(): GhostCindySlot {
// 管道;记成 'ghost' 会让 ghostCanRead 的 origin 分支把它当作该意识的
// 出生物,与"作品"混为一谈。引用方(refId)才是意识,归属由此成立。
depositMedia: async ({ ghostId, buffer, mimeType, label }) => {
- // 与 saveGhostMedia 同口径的 durable owner 守卫:寄存器引用按 ghostId
- // 落到 owner 作用域账本,落盘窗口翻转全局 owner 时必须 fail closed。
+ // 与 saveGhostMedia 同口径的应用会话守卫:寄存器引用按 ghostId
+ // 落到 owner 作用域账本,落盘窗口切换账号时必须 fail closed。
const ownerScopeKey = activeOwnerScopeKey();
const assertOwnerScopeCurrent = (): void => {
if (isGhostBoundaryPending() || activeOwnerScopeKey() !== ownerScopeKey) {
@@ -4124,9 +4103,9 @@ export function getGhostNetworkSlot(): GhostNetworkSlot {
// (规则 25)。mime 白名单同一来源(blobStore),槽内归一化后再判。
isSupportedMediaMime: (mime) => supportedMime(mime),
saveGhostMedia: async ({ ghostId, buffer, mimeType, label, callId }) => {
- // 与 cindy 槽 saveGhostMedia 同口径的 durable owner 守卫:落盘前与
- // ingestMedia 每个 await 边界都复查,防止兄弟实例在 fetch 读取窗口翻转
- // 全局 Ghost owner marker 后,字节仍被登记为 ghost-gallery 作品。
+ // 与 cindy 槽 saveGhostMedia 同口径的应用会话守卫:落盘前与
+ // ingestMedia 每个 await 边界都复查,防止当前进程在 fetch 读取窗口切换
+ // 账号后,字节仍被登记为 ghost-gallery 作品。
const ownerScopeKey = activeOwnerScopeKey();
const assertOwnerScopeCurrent = (): void => {
if (isGhostBoundaryPending() || activeOwnerScopeKey() !== ownerScopeKey) {
diff --git a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts
index 952c77f92c..a4ebf656d7 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/ledger.test.ts
@@ -70,6 +70,34 @@ describe('PluginMarketLedger', () => {
).toBe(false);
});
+ it('atomically reconnects an unchanged server record and clears its false opt-out', () => {
+ const { ledger } = harness();
+ ledger.upsertInstallation(record());
+ ledger.markRemoved('cindy-test', 'user-a');
+ const disconnected = ledger.installationForGhost('cindy-test');
+ expect(disconnected).not.toBeNull();
+ if (!disconnected) return;
+
+ expect(ledger.restoreDisconnectedInstallation(disconnected, 'user-a')).toBe(true);
+ expect(ledger.installationForGhost('cindy-test')).toMatchObject({ installed: true });
+ expect(
+ ledger.isDefaultInstallSuppressed('user-a', disconnected.pluginId),
+ ).toBe(false);
+ });
+
+ it('does not overwrite a disconnected record that changed after recovery captured it', () => {
+ const { ledger } = harness();
+ const disconnected = record({ installed: false });
+ ledger.upsertInstallation(disconnected);
+ ledger.upsertInstallation({ ...disconnected, sha256: 'c'.repeat(64) });
+
+ expect(ledger.restoreDisconnectedInstallation(disconnected, 'user-a')).toBe(false);
+ expect(ledger.installationForGhost('cindy-test')).toMatchObject({
+ installed: false,
+ sha256: 'c'.repeat(64),
+ });
+ });
+
it('fails closed to an empty ledger for malformed or future data', () => {
const { filePath, ledger } = harness();
fs.mkdirSync(path.dirname(filePath), { recursive: true });
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
index 49c1e0e277..aaf3a8452d 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -27,6 +27,11 @@ const runtime = vi.hoisted(() => ({
runningErrand: false,
cindyWork: false,
boundaryPending: false,
+ approvedInstallEvidence: vi.fn(() => null as {
+ packageSha256: string | null;
+ approvedManifest: GhostManifest;
+ legacyMigrated: boolean;
+ } | null),
pluginApiBaseUrl: 'https://plugin.test.invalid' as string | null,
session: {
mode: 'cloud' as 'signed-out' | 'local' | 'cloud',
@@ -69,6 +74,7 @@ vi.mock('../../cindy-brain/index.js', () => ({
revision: '00000000-0000-4000-8000-000000000001',
},
})),
+ approvedInstallEvidence: runtime.approvedInstallEvidence,
}),
isGhostAvailableForActiveSession: vi.fn(() => runtime.accountGhostAvailable),
installOrUpdateMarketGhostPackage: runtime.install,
@@ -100,6 +106,7 @@ import type { PluginMarketApi } from '../api';
const roots: string[] = [];
const PLUGIN_ID = `c${'a'.repeat(24)}`;
+const RELEASE_ID = `c${'b'.repeat(24)}`;
const APPROVED_INSTALL_TOKEN = 'approved:00000000-0000-4000-8000-000000000001';
/** 手动可控 deferred,用于精确编排"安装在飞行中"的交错。 */
@@ -121,6 +128,8 @@ afterEach(() => {
runtime.runningErrand = false;
runtime.cindyWork = false;
runtime.boundaryPending = false;
+ runtime.approvedInstallEvidence.mockReset();
+ runtime.approvedInstallEvidence.mockReturnValue(null);
runtime.pluginApiBaseUrl = 'https://plugin.test.invalid';
runtime.session = {
mode: 'cloud',
@@ -501,6 +510,238 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(runtime.install).not.toHaveBeenCalled();
});
+ it('silently reconnects an unchanged approved package to its historical market release', async () => {
+ const canonicalManifest = normalizedManifest(manifest());
+ const item = summary({
+ currentRelease: {
+ ...summary().currentRelease,
+ id: RELEASE_ID,
+ },
+ });
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-recovery-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(canonicalManifest));
+ runtime.ghosts = [{
+ manifest: canonicalManifest as unknown as Record<string, unknown>,
+ dir: installDir,
+ enabled: false,
+ }];
+ runtime.approvedInstallEvidence.mockReturnValue({
+ packageSha256: item.currentRelease.sha256,
+ approvedManifest: canonicalManifest,
+ legacyMigrated: false,
+ });
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ pluginId: item.id,
+ ghostId: item.ghostId,
+ releaseId: item.currentRelease.id,
+ version: item.currentRelease.version,
+ sha256: item.currentRelease.sha256,
+ scope: item.scope,
+ organizationId: item.organizationId,
+ source: 'market',
+ installed: true,
+ updatedAt: '2026-08-01T00:00:00.000Z',
+ manifestDigest: ghostManifestDigest(canonicalManifest),
+ });
+ h.ledger.markRemoved(item.ghostId, 'user-1');
+
+ const snapshot = await h.service.snapshot();
+
+ expect(snapshot.items[0]).toMatchObject({
+ installState: 'installed',
+ enabled: false,
+ });
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
+ installed: true,
+ source: 'market',
+ releaseId: RELEASE_ID,
+ });
+ expect(h.ledger.isDefaultInstallSuppressed('user-1', item.id)).toBe(false);
+ expect(h.api.download).not.toHaveBeenCalled();
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { receiptCase: 'missing', receiptSha: null },
+ { receiptCase: 'different', receiptSha: 'f'.repeat(64) },
+ ])('keeps a disconnected market route detached when its receipt hash is $receiptCase', async ({
+ receiptSha,
+ }) => {
+ const canonicalManifest = normalizedManifest(manifest());
+ const item = summary({
+ currentRelease: {
+ ...summary().currentRelease,
+ id: RELEASE_ID,
+ },
+ });
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-mismatch-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(canonicalManifest));
+ runtime.ghosts = [{
+ manifest: canonicalManifest as unknown as Record<string, unknown>,
+ dir: installDir,
+ enabled: true,
+ }];
+ runtime.approvedInstallEvidence.mockReturnValue(
+ receiptSha === null
+ ? null
+ : {
+ packageSha256: receiptSha,
+ approvedManifest: canonicalManifest,
+ // A retained migration entry must never override a present-but-different hash.
+ legacyMigrated: true,
+ },
+ );
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ pluginId: item.id,
+ ghostId: item.ghostId,
+ releaseId: item.currentRelease.id,
+ version: item.currentRelease.version,
+ sha256: item.currentRelease.sha256,
+ scope: item.scope,
+ organizationId: item.organizationId,
+ source: 'market',
+ installed: false,
+ updatedAt: '2026-08-01T00:00:00.000Z',
+ manifestDigest: ghostManifestDigest(canonicalManifest),
+ });
+
+ const snapshot = await h.service.snapshot();
+
+ expect(snapshot.items[0]?.installState).toBe('conflict');
+ expect(h.ledger.installationForGhost(item.ghostId)?.installed).toBe(false);
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it('reconnects an explicitly migrated legacy receipt whose approved manifest is unchanged', async () => {
+ const canonicalManifest = normalizedManifest(manifest());
+ const item = summary({
+ currentRelease: {
+ ...summary().currentRelease,
+ id: RELEASE_ID,
+ },
+ });
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-legacy-recovery-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(canonicalManifest));
+ runtime.ghosts = [{
+ manifest: canonicalManifest as unknown as Record<string, unknown>,
+ dir: installDir,
+ enabled: true,
+ }];
+ runtime.approvedInstallEvidence.mockReturnValue({
+ packageSha256: null,
+ approvedManifest: canonicalManifest,
+ legacyMigrated: true,
+ });
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ pluginId: item.id,
+ ghostId: item.ghostId,
+ releaseId: item.currentRelease.id,
+ version: item.currentRelease.version,
+ sha256: item.currentRelease.sha256,
+ scope: item.scope,
+ organizationId: item.organizationId,
+ source: 'market',
+ installed: false,
+ updatedAt: '2026-08-01T00:00:00.000Z',
+ // Old market records such as TapTap Maker predate manifestDigest.
+ });
+
+ const snapshot = await h.service.snapshot();
+
+ expect(snapshot.items[0]?.installState).toBe('installed');
+ expect(h.ledger.installationForGhost(item.ghostId)).toMatchObject({
+ installed: true,
+ source: 'market',
+ releaseId: RELEASE_ID,
+ });
+ expect(h.api.download).not.toHaveBeenCalled();
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it('keeps a migrated legacy route detached when its raw manifest changed after approval', async () => {
+ const canonicalManifest = normalizedManifest(manifest());
+ const item = summary({
+ currentRelease: {
+ ...summary().currentRelease,
+ id: RELEASE_ID,
+ },
+ });
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-legacy-tampered-'));
+ roots.push(installDir);
+ fs.writeFileSync(
+ path.join(installDir, 'ghost.json'),
+ JSON.stringify({ ...canonicalManifest, description: 'changed after migration' }),
+ );
+ runtime.ghosts = [{
+ manifest: canonicalManifest as unknown as Record<string, unknown>,
+ dir: installDir,
+ enabled: true,
+ }];
+ runtime.approvedInstallEvidence.mockReturnValue({
+ packageSha256: null,
+ approvedManifest: canonicalManifest,
+ legacyMigrated: true,
+ });
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ pluginId: item.id,
+ ghostId: item.ghostId,
+ releaseId: item.currentRelease.id,
+ version: item.currentRelease.version,
+ sha256: item.currentRelease.sha256,
+ scope: item.scope,
+ organizationId: item.organizationId,
+ source: 'market',
+ installed: false,
+ updatedAt: '2026-08-01T00:00:00.000Z',
+ });
+
+ const snapshot = await h.service.snapshot();
+
+ expect(snapshot.items[0]?.installState).toBe('conflict');
+ expect(h.ledger.installationForGhost(item.ghostId)?.installed).toBe(false);
+ expect(runtime.install).not.toHaveBeenCalled();
+ });
+
+ it('does not guess a Release for a synthetic legacy-adopted record', async () => {
+ const canonicalManifest = normalizedManifest(manifest());
+ const item = summary();
+ const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-legacy-unresolved-'));
+ roots.push(installDir);
+ fs.writeFileSync(path.join(installDir, 'ghost.json'), JSON.stringify(canonicalManifest));
+ runtime.ghosts = [{
+ manifest: canonicalManifest as unknown as Record<string, unknown>,
+ dir: installDir,
+ enabled: true,
+ }];
+ const h = harness([item]);
+ h.ledger.upsertInstallation({
+ pluginId: item.id,
+ ghostId: item.ghostId,
+ releaseId: `legacy-unresolved:${item.currentRelease.version}`,
+ version: item.currentRelease.version,
+ sha256: 'legacy-unverified',
+ scope: item.scope,
+ organizationId: item.organizationId,
+ source: 'legacy-adopted',
+ installed: false,
+ updatedAt: '2026-08-01T00:00:00.000Z',
+ manifestDigest: ghostManifestDigest(canonicalManifest),
+ });
+
+ await expect(h.service.snapshot()).resolves.toMatchObject({
+ items: [{ installState: 'conflict' }],
+ });
+ expect(h.api.download).not.toHaveBeenCalled();
+ expect(h.ledger.installationForGhost(item.ghostId)?.installed).toBe(false);
+ });
+
it('installs and enables a unique defaultInstall package and records its release', async () => {
const item = summary({ defaultInstall: true });
const installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-market-installed-'));
diff --git a/apps/desktop/src/main/plugin-market/ledger.ts b/apps/desktop/src/main/plugin-market/ledger.ts
index adc37be281..c54677c413 100644
--- a/apps/desktop/src/main/plugin-market/ledger.ts
+++ b/apps/desktop/src/main/plugin-market/ledger.ts
@@ -250,6 +250,40 @@ export class PluginMarketLedger {
this.write(data);
}
+ /**
+ * Reconnect an unchanged historical server record after the approved receipt
+ * proves the original package hash. The compare-and-write prevents a
+ * concurrent uninstall or source replacement from being overwritten by a
+ * stale recovery snapshot.
+ */
+ restoreDisconnectedInstallation(
+ expected: PluginMarketInstallationRecord,
+ userId: string,
+ ): boolean {
+ const data = this.read();
+ const current = data.installations[expected.ghostId];
+ if (
+ !current
+ || current.installed
+ || (current.source !== 'market' && current.source !== 'legacy-adopted')
+ || canonicalJson(current) !== canonicalJson(expected)
+ ) {
+ return false;
+ }
+ data.installations[current.ghostId] = {
+ ...current,
+ installed: true,
+ updatedAt: new Date().toISOString(),
+ };
+ const remainingOptOuts = (data.defaultInstallOptOuts[userId] ?? []).filter(
+ (pluginId) => pluginId !== current.pluginId,
+ );
+ if (remainingOptOuts.length > 0) data.defaultInstallOptOuts[userId] = remainingOptOuts;
+ else delete data.defaultInstallOptOuts[userId];
+ this.write(data);
+ return true;
+ }
+
markRemoved(ghostId: string, userId: string | null): void {
const data = this.read();
const record = data.installations[ghostId];
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index cb424a21df..f4d851b35c 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -20,6 +20,7 @@ import {
ghostIconMimeType,
isSafeGhostRelativePath,
isOfficialGhostId,
+ isValidGhostId,
validateGhostManifest,
validateNormalizedGhostManifest,
type GhostManifest,
@@ -467,6 +468,27 @@ function sameMarketInstallation(
);
}
+function sameDisconnectedMarketInstallation(
+ current: PluginMarketInstallationRecord | null,
+ expected: PluginMarketInstallationRecord,
+): current is PluginMarketInstallationRecord {
+ return Boolean(
+ current
+ && !current.installed
+ && current.pluginId === expected.pluginId
+ && current.ghostId === expected.ghostId
+ && current.releaseId === expected.releaseId
+ && current.version === expected.version
+ && current.sha256 === expected.sha256
+ && current.scope === expected.scope
+ && current.organizationId === expected.organizationId
+ && current.source === expected.source
+ && current.updatedAt === expected.updatedAt
+ && current.sourceKey === expected.sourceKey
+ && current.manifestDigest === expected.manifestDigest,
+ );
+}
+
/** Stable local facts reused while projecting one market catalog response. */
interface LocalInstallSnapshot {
/** Installed Ghost runtime facts indexed once for one market operation. */
@@ -589,6 +611,7 @@ export class PluginMarketService {
requireSameMarketOwner(owner);
const ledger = this.ledgerForOwner(owner);
await this.adoptLegacyInstallations(plugins, ledger, owner);
+ await this.recoverDisconnectedMarketInstallations(plugins, ledger, owner);
await this.backfillOfficialCindyGithubTrust(ledger, owner);
// A snapshot is passive discovery: an empty runtime list can be caused by
// startup, an owner transition, or a transient filesystem view. Only an
@@ -1997,6 +2020,139 @@ export class PluginMarketService {
}
}
+ /**
+ * Repair an existing server provenance record that an older client left
+ * disconnected while its approved package remained installed.
+ * Recovery is entirely local. Modern receipts must retain the exact Release
+ * package hash. Legacy receipts intentionally omitted that audit-only hash, so
+ * they additionally require the completed one-time migration to name this id
+ * and the raw installed manifest to equal the manifest frozen in that receipt.
+ */
+ private async recoverDisconnectedMarketInstallations(
+ plugins: readonly VisiblePluginSummary[],
+ ledger: PluginMarketLedger,
+ owner: ActiveAppSession,
+ ): Promise<void> {
+ const pluginIdCounts = new Map<string, number>();
+ const ghostCounts = ghostIdCounts(plugins);
+ for (const plugin of plugins) {
+ pluginIdCounts.set(plugin.id, (pluginIdCounts.get(plugin.id) ?? 0) + 1);
+ }
+ const summariesById = new Map(plugins.map((plugin) => [plugin.id, plugin]));
+ const records = Object.values(ledger.read().installations);
+ const installSubject = defaultInstallSubject(owner);
+
+ for (const record of records) {
+ const summary = summariesById.get(record.pluginId);
+ if (
+ record.installed
+ || (record.source !== 'market' && record.source !== 'legacy-adopted')
+ || !isValidPluginResourceId(record.pluginId)
+ || !isValidPluginResourceId(record.releaseId)
+ || !isValidGhostId(record.ghostId)
+ || !/^[a-f0-9]{64}$/.test(record.sha256)
+ || pluginIdCounts.get(record.pluginId) !== 1
+ || ghostCounts.get(record.ghostId) !== 1
+ || !summary
+ || summary.ghostId !== record.ghostId
+ || summary.scope !== record.scope
+ || summary.organizationId !== record.organizationId
+ ) {
+ continue;
+ }
+
+ const installed = getGhostManager()
+ .list()
+ .find((ghost) => ghost.manifest.id === record.ghostId);
+ if (!installed || installed.approval.state !== 'approved') continue;
+
+ try {
+ await this.withMutation(record.pluginId, async () => {
+ requireSameMarketOwner(owner);
+ await withGhostInstallLock(record.ghostId, async () => {
+ requireSameMarketOwner(owner);
+ const lockedRecord = ledger.installationForGhost(record.ghostId);
+ if (!sameDisconnectedMarketInstallation(lockedRecord, record)) return;
+ const currentInstalled = getGhostManager()
+ .list()
+ .find((ghost) => ghost.manifest.id === record.ghostId);
+ if (
+ !currentInstalled
+ || currentInstalled.approval.state !== 'approved'
+ || currentInstalled.manifest.version !== record.version
+ ) {
+ return;
+ }
+ const approvalEvidence = getGhostManager().approvedInstallEvidence(record.ghostId);
+ if (!approvalEvidence) return;
+ if (
+ approvalEvidence.packageSha256 !== null
+ && approvalEvidence.packageSha256 !== record.sha256
+ ) {
+ log.info('disconnected market recovery skipped', {
+ pluginId: record.pluginId,
+ ghostId: record.ghostId,
+ reason: 'receipt-package-sha-mismatch',
+ });
+ return;
+ }
+ const installedManifestDigest = installedGhostRawManifestDigest(currentInstalled.dir);
+ if (approvalEvidence.packageSha256 === null) {
+ if (!approvalEvidence.legacyMigrated) {
+ log.info('disconnected market recovery skipped', {
+ pluginId: record.pluginId,
+ ghostId: record.ghostId,
+ reason: 'approved-source-evidence-missing',
+ });
+ return;
+ }
+ if (
+ installedManifestDigest === null
+ || installedManifestDigest !== ghostManifestDigest(
+ approvalEvidence.approvedManifest,
+ )
+ ) {
+ log.info('disconnected market recovery skipped', {
+ pluginId: record.pluginId,
+ ghostId: record.ghostId,
+ reason: 'legacy-approved-manifest-mismatch',
+ });
+ return;
+ }
+ }
+ if (
+ record.manifestDigest !== undefined
+ && installedManifestDigest !== record.manifestDigest
+ ) {
+ log.info('disconnected market recovery skipped', {
+ pluginId: record.pluginId,
+ ghostId: record.ghostId,
+ reason: 'installed-manifest-mismatch',
+ });
+ return;
+ }
+ const restored = await this.withLedgerMutation(owner, () =>
+ ledger.restoreDisconnectedInstallation(record, installSubject));
+ if (restored) {
+ log.info('disconnected market installation recovered', {
+ pluginId: record.pluginId,
+ ghostId: record.ghostId,
+ releaseId: record.releaseId,
+ });
+ }
+ });
+ });
+ } catch (error) {
+ if (isIpcError(error) && error.code === 'PRECONDITION_FAILED') throw error;
+ log.warn('disconnected market recovery deferred', {
+ pluginId: record.pluginId,
+ ghostId: record.ghostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ }
+
/**
* 旧版 server-market 安装已经有 Host ledger + manifestDigest,但尚未写
* cindy-official receipt。不能只按 manifestDigest 抬权:攻击者可保留清单、