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): 按 owner 隔离 main-view 和 settings WebView (#3414)

fmfsaisai1f7f76ff42b4
diff --git a/apps/desktop/src/main/__tests__/lifecycle.test.ts b/apps/desktop/src/main/__tests__/lifecycle.test.ts
index f2db745e72..e209236f4f 100644
--- a/apps/desktop/src/main/__tests__/lifecycle.test.ts
+++ b/apps/desktop/src/main/__tests__/lifecycle.test.ts
@@ -50,6 +50,12 @@ vi.mock('../ghost-panel-window/registry.js', () => ({
ghostPanelWebContentsIds.has(webContentsId),
}));
+// lifecycle 只消费这个查询函数;owner-scoped Electron session 会让 adapter
+// 依赖 owner 持久化与进程锁,不应把整条运行时链带进退出编排单测。
+vi.mock('../cindy-brain/runtime/electronSandboxAdapter', () => ({
+ isGhostSandboxWebContentsId: () => false,
+}));
+
const mocks = vi.hoisted(() => ({
logger: {
info: vi.fn(),
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index 2a83b971c4..06b7682f8e 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -90,6 +90,7 @@ describe('session runtime control wiring', () => {
'setAppSessionCommitBoundaryHook(() => {',
'// ── Custom protocol registration',
);
+ expect(body).toContain('ghostPanelWindowsController.closeForOwnerChange();');
expect(body).toContain('clearAllSessionProviders();');
expect(body).toContain('clearAllSessionRuntimeAxes();');
expect(body.indexOf('clearAllSessionProviders();')).toBeLessThan(
diff --git a/apps/desktop/src/main/__tests__/webview-security.test.ts b/apps/desktop/src/main/__tests__/webview-security.test.ts
index 23de91145e..d28ded90cc 100644
--- a/apps/desktop/src/main/__tests__/webview-security.test.ts
+++ b/apps/desktop/src/main/__tests__/webview-security.test.ts
@@ -49,6 +49,7 @@ import {
applyGhostWebviewHardening,
applyLoginCaptchaWebviewHardening,
applyWebviewHardening,
+ authorizeGhostWebviewAttach,
hardenLoginCaptchaSession,
installGhostGuestNavigationHandlers,
installBrowserGuestHandlers,
@@ -292,7 +293,7 @@ describe('applyGhostWebviewHardening(意识面板 webview)', () => {
};
const params: Record<string, string> = {
src: 'cindy-ghost://art/panel.html',
- partition: 'cindy-ghost-art',
+ partition: 'cindy-ghost-owner:cloud:0123456789abcdefabcd:art',
disablewebsecurity: 'true',
webpreferences: 'nodeIntegration=1',
allowpopups: 'true',
@@ -311,11 +312,59 @@ describe('applyGhostWebviewHardening(意识面板 webview)', () => {
expect(webPreferences.plugins).toBe(false);
expect('preload' in webPreferences).toBe(false);
// 与浏览器路径的两点差异:分区保留、popup 掐死
- expect(params.partition).toBe('cindy-ghost-art');
+ expect(params.partition).toBe('cindy-ghost-owner:cloud:0123456789abcdefabcd:art');
expect('allowpopups' in params).toBe(false);
expect('disablewebsecurity' in params).toBe(false);
expect('webpreferences' in params).toBe(false);
});
+
+ it('把 Renderer claim 覆盖为 Main 核准的 owner partition', () => {
+ // Electron 在 will-attach-webview 前会把 renderer claim 复制到这里,真实
+ // guest 创建时使用的是 webPreferences.partition,而不是后续的 params。
+ const webPreferences: Record<string, unknown> = {
+ nodeIntegration: true,
+ partition: 'cindy-ghost-same-ghost',
+ };
+ const params: Record<string, string> = {
+ src: 'cindy-ghost://same-ghost/panel.html',
+ partition: 'cindy-ghost-same-ghost',
+ allowpopups: 'true',
+ };
+ const resolver = vi.fn(() => ({
+ ghost: { manifest: { id: 'same-ghost' } },
+ partition: 'cindy-ghost-owner:cloud:opaque-owner-a:same-ghost',
+ owner: { mode: 'cloud', dataOwnerId: 'owner-a' },
+ })) as never;
+
+ expect(authorizeGhostWebviewAttach(webPreferences, params, resolver)).toEqual({
+ id: 'same-ghost',
+ owner: { mode: 'cloud', dataOwnerId: 'owner-a' },
+ });
+ expect(resolver).toHaveBeenCalledWith(
+ 'cindy-ghost-same-ghost',
+ 'cindy-ghost://same-ghost/panel.html',
+ );
+ expect(params.partition).toBe('cindy-ghost-owner:cloud:opaque-owner-a:same-ghost');
+ expect(webPreferences.partition).toBe(
+ 'cindy-ghost-owner:cloud:opaque-owner-a:same-ghost',
+ );
+ expect(webPreferences.nodeIntegration).toBe(false);
+ expect('allowpopups' in params).toBe(false);
+ });
+
+ it('Main 解析或协议注册异常时不核准 attach', () => {
+ const params: Record<string, string> = {
+ src: 'cindy-ghost://same-ghost/panel.html',
+ partition: 'cindy-ghost-same-ghost',
+ };
+
+ expect(
+ authorizeGhostWebviewAttach({}, params, (() => {
+ throw new Error('protocol registration failed');
+ }) as never),
+ ).toBeNull();
+ expect(params.partition).toBe('cindy-ghost-same-ghost');
+ });
});
describe('applyLoginCaptchaWebviewHardening(登录 captcha webview)', () => {
@@ -490,13 +539,28 @@ describe('installGhostGuestNavigationHandlers(Ghost settingsHtml / panel 共用
openHandler = handler;
});
const host = { id: 10 } as unknown as WebContents;
+ let ownerActive = true;
+ const gesture = vi.fn();
const preview = vi.fn();
const external = vi.fn();
- installGhostGuestNavigationHandlers(host, guest as unknown as WebContents, 'xd-sites', {
+ installGhostGuestNavigationHandlers(
+ host,
+ guest as unknown as WebContents,
+ 'xd-sites',
+ () => ownerActive,
+ { gesture, preview, external },
+ );
+ return {
+ guest,
+ host,
+ gesture,
preview,
external,
- });
- return { guest, host, preview, external, getOpenHandler: () => openHandler };
+ setOwnerActive: (active: boolean) => {
+ ownerActive = active;
+ },
+ getOpenHandler: () => openHandler,
+ };
}
it('普通 HTTPS <a> 的 will-navigate 被拦下并带真实 host/guest 交给外链处理', () => {
@@ -511,6 +575,7 @@ describe('installGhostGuestNavigationHandlers(Ghost settingsHtml / panel 共用
'https://workers.xd.team/workspace/published',
harness.host,
harness.guest,
+ expect.any(Function),
);
expect(harness.preview).not.toHaveBeenCalled();
});
@@ -546,6 +611,24 @@ describe('installGhostGuestNavigationHandlers(Ghost settingsHtml / panel 共用
expect(harness.getOpenHandler()?.()).toEqual({ action: 'deny' });
expect(harness.external).not.toHaveBeenCalled();
});
+
+ it('owner 切换后旧 guest 的手势和导航全部被 Main 拒绝', () => {
+ const harness = makeHarness();
+ harness.setOwnerActive(false);
+ const externalEvent = { preventDefault: vi.fn() };
+ const sameOriginEvent = { preventDefault: vi.fn() };
+
+ harness.guest.emit('before-mouse-event', {}, { type: 'mouseDown' });
+ harness.guest.emit('before-input-event', {}, { type: 'keyDown' });
+ harness.guest.emit('will-navigate', externalEvent, 'https://workers.xd.team/owner-a-data');
+ harness.guest.emit('will-navigate', sameOriginEvent, 'cindy-ghost://xd-sites/panel.html');
+
+ expect(harness.gesture).not.toHaveBeenCalled();
+ expect(externalEvent.preventDefault).toHaveBeenCalledOnce();
+ expect(sameOriginEvent.preventDefault).toHaveBeenCalledOnce();
+ expect(harness.preview).not.toHaveBeenCalled();
+ expect(harness.external).not.toHaveBeenCalled();
+ });
});
describe('installDeferredPopupRouter', () => {
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 1a4fe9a897..00d7db5f5e 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -2324,6 +2324,7 @@ registerGhostIpc();
registerPluginMarketIpc();
registerPluginPublisherIpc();
setAppSessionCommitBoundaryHook(() => {
+ ghostPanelWindowsController.closeForOwnerChange();
clearAllSessionProviders();
clearAllSessionRuntimeAxes();
clearAllSessionRuntimeControlStates();
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostExternalLinkNavigation.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostExternalLinkNavigation.test.ts
index 2a3e27e9e5..e6f19c60b8 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostExternalLinkNavigation.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostExternalLinkNavigation.test.ts
@@ -57,6 +57,7 @@ function makeHarness(options: {
const openExternal = vi.fn<(url: string) => Promise<void>>(async () => undefined);
const debug = vi.fn();
const warn = vi.fn();
+ let ownerActive = true;
const translate = vi.fn((key: string) => {
const labels: Record<string, string> = {
'ghostPanel.externalLinkConfirm.title': '是否要 Cindy 打开外部网站',
@@ -78,6 +79,9 @@ function makeHarness(options: {
destroyOwner: () => {
ownerDestroyed = true;
},
+ setOwnerActive: (active: boolean) => {
+ ownerActive = active;
+ },
deps: {
gate,
resolveOwner,
@@ -85,6 +89,7 @@ function makeHarness(options: {
openExternal,
translate,
logger: { debug, warn },
+ isOwnerActive: () => ownerActive,
},
};
}
@@ -180,6 +185,7 @@ describe('runGhostExternalLinkNavigation', () => {
openExternal,
translate: (key: string) => key,
logger: { debug: vi.fn(), warn: vi.fn() },
+ isOwnerActive: () => true,
};
for (const { surface, contents, owner } of entries) {
@@ -287,6 +293,36 @@ describe('runGhostExternalLinkNavigation', () => {
expect(harness.showMessageBox).toHaveBeenCalledTimes(2);
});
+ it('owner 在确认期间切换后,即使旧确认返回打开也不执行', async () => {
+ const contents = makeContents();
+ const harness = makeHarness({});
+ let finishDialog!: (value: { response: number }) => void;
+ harness.showMessageBox.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finishDialog = resolve;
+ }),
+ );
+
+ const pending = runGhostExternalLinkNavigation(
+ {
+ ghostId: 'xd-sites',
+ url: 'https://example.com/owner-a-data',
+ hostContents: contents.host,
+ guestContents: contents.guest,
+ },
+ harness.deps,
+ );
+ await vi.waitFor(() => expect(harness.showMessageBox).toHaveBeenCalledOnce());
+
+ harness.setOwnerActive(false);
+ finishDialog({ response: 0 });
+ await pending;
+
+ expect(harness.openExternal).not.toHaveBeenCalled();
+ expect(harness.warn).not.toHaveBeenCalled();
+ });
+
it('guest 已脱离原宿主时不弹窗也不打开', async () => {
const contents = makeContents();
contents.detachGuest();
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostPreviewNavigation.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostPreviewNavigation.test.ts
new file mode 100644
index 0000000000..75b49cb073
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostPreviewNavigation.test.ts
@@ -0,0 +1,79 @@
+import type { WebContents } from 'electron';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { GhostPreviewOutcome } from '../previewGate';
+import { runGhostPreviewNavigation } from '../ghostPreviewNavigation';
+
+describe('runGhostPreviewNavigation', () => {
+ it('owner 仍有效且预览成功时向当前 renderer 推送一次', async () => {
+ const outcome: GhostPreviewOutcome = {
+ ok: true,
+ src: 'cindy-media://blob/current-owner.png',
+ kind: 'image',
+ };
+ const request = vi.fn().mockResolvedValue(outcome);
+ const send = vi.fn();
+ const hostContents = { isDestroyed: () => false } as unknown as WebContents;
+ const guestContents = {
+ isDestroyed: () => false,
+ isFocused: () => true,
+ } as unknown as WebContents;
+
+ await runGhostPreviewNavigation(
+ {
+ ghostId: 'same-ghost',
+ url: `cindy-ghost://same-ghost/preview/${'a'.repeat(64)}.png`,
+ hostContents,
+ guestContents,
+ },
+ {
+ request,
+ isOwnerActive: () => true,
+ send,
+ logger: { debug: vi.fn(), warn: vi.fn() },
+ },
+ );
+
+ expect(send).toHaveBeenCalledOnce();
+ expect(send).toHaveBeenCalledWith(outcome);
+ });
+
+ it('owner 在账本查询期间切换后不向新 owner 的 renderer 推送旧预览', async () => {
+ let ownerActive = true;
+ let finishRequest!: (outcome: GhostPreviewOutcome) => void;
+ const request = vi.fn(
+ () =>
+ new Promise<GhostPreviewOutcome>((resolve) => {
+ finishRequest = resolve;
+ }),
+ );
+ const send = vi.fn();
+ const hostContents = { isDestroyed: () => false } as unknown as WebContents;
+ const guestContents = {
+ isDestroyed: () => false,
+ isFocused: () => true,
+ } as unknown as WebContents;
+
+ const pending = runGhostPreviewNavigation(
+ {
+ ghostId: 'same-ghost',
+ url: `cindy-ghost://same-ghost/preview/${'a'.repeat(64)}.png`,
+ hostContents,
+ guestContents,
+ },
+ {
+ request,
+ isOwnerActive: () => ownerActive,
+ send,
+ logger: { debug: vi.fn(), warn: vi.fn() },
+ },
+ );
+ await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());
+
+ ownerActive = false;
+ finishRequest({ ok: true, src: 'cindy-media://blob/owner-a.png', kind: 'image' });
+ await pending;
+
+ expect(send).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostWebviewPartition.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostWebviewPartition.test.ts
new file mode 100644
index 0000000000..4734c04695
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostWebviewPartition.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('../../appSessionState', () => ({
+ dataOwnerStorageKey: (ownerId: string) => `opaque-${ownerId}`,
+}));
+
+import { ghostPartition } from '../../../shared/ghost';
+import {
+ ownerScopedGhostPartition,
+ resolveGhostWebviewPartitionClaim,
+} from '../ghostWebviewPartition';
+
+describe('ghost WebView Main partition', () => {
+ const ownerA = { mode: 'cloud' as const, dataOwnerId: 'owner-a' };
+ const ownerB = { mode: 'cloud' as const, dataOwnerId: 'owner-b' };
+
+ it('同 owner + ghost 稳定,不同 owner + 同 ghost 使用不同 session', () => {
+ const partitionA = ownerScopedGhostPartition('same-ghost', ownerA);
+ const partitionB = ownerScopedGhostPartition('same-ghost', ownerB);
+
+ expect(partitionA).toBe('cindy-ghost-owner:cloud:opaque-owner-a:same-ghost');
+ expect(ownerScopedGhostPartition('same-ghost', ownerA)).toBe(partitionA);
+ expect(partitionB).not.toBe(partitionA);
+ });
+
+ it('把 Renderer claim 解析为 Main 当前 owner 的权威 partition', () => {
+ const claim = ghostPartition('same-ghost');
+
+ expect(resolveGhostWebviewPartitionClaim(claim, ownerA)).toEqual({
+ ghostId: 'same-ghost',
+ partition: 'cindy-ghost-owner:cloud:opaque-owner-a:same-ghost',
+ });
+ expect(resolveGhostWebviewPartitionClaim(claim, ownerB)?.partition).toBe(
+ 'cindy-ghost-owner:cloud:opaque-owner-b:same-ghost',
+ );
+ });
+
+ it('无 owner、非法 claim 和伪造的真实 partition 都 fail closed', () => {
+ expect(
+ resolveGhostWebviewPartitionClaim(ghostPartition('same-ghost'), {
+ mode: 'signed-out',
+ dataOwnerId: null,
+ }),
+ ).toBeNull();
+ expect(resolveGhostWebviewPartitionClaim('cindy-ghost-BAD_ID', ownerA)).toBeNull();
+ expect(
+ resolveGhostWebviewPartitionClaim(
+ 'cindy-ghost-owner:cloud:opaque-owner-b:same-ghost',
+ ownerA,
+ ),
+ ).toBeNull();
+ expect(resolveGhostWebviewPartitionClaim(undefined, ownerA)).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/ghostExternalLinkNavigation.ts b/apps/desktop/src/main/cindy-brain/ghostExternalLinkNavigation.ts
index 68682c1564..6e8f676727 100644
--- a/apps/desktop/src/main/cindy-brain/ghostExternalLinkNavigation.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostExternalLinkNavigation.ts
@@ -14,6 +14,8 @@ export interface GhostExternalLinkNavigationDeps {
openExternal(url: string): Promise<void>;
translate(key: string): string;
logger: GhostExternalLinkNavigationLogger;
+ /** Captured attach owner is still the committed active owner. */
+ isOwnerActive(): boolean;
}
export interface GhostExternalLinkNavigationParams {
@@ -39,6 +41,7 @@ async function openExternalBestEffort(
url: string,
deps: GhostExternalLinkNavigationDeps,
): Promise<void> {
+ if (!deps.isOwnerActive()) return;
try {
await deps.openExternal(url);
} catch (error) {
@@ -61,6 +64,7 @@ export async function runGhostExternalLinkNavigation(
params: GhostExternalLinkNavigationParams,
deps: GhostExternalLinkNavigationDeps,
): Promise<void> {
+ if (!deps.isOwnerActive()) return;
const outcome = deps.gate.request({
ghostId: params.ghostId,
url: params.url,
@@ -82,6 +86,7 @@ export async function runGhostExternalLinkNavigation(
const confirmedUrl = outcome.url;
let shouldOpen = false;
try {
+ if (!deps.isOwnerActive()) return;
if (!guestStillBelongsToHost(params.guestContents, params.hostContents)) return;
const owner = deps.resolveOwner(params.hostContents);
if (!owner || owner.isDestroyed()) return;
@@ -102,6 +107,7 @@ export async function runGhostExternalLinkNavigation(
noLink: true,
}));
} catch (error) {
+ if (!deps.isOwnerActive()) return;
deps.logger.warn('ghost external link confirmation failed', {
ghostId: params.ghostId,
error: errorMessage(error),
@@ -109,6 +115,7 @@ export async function runGhostExternalLinkNavigation(
return;
}
if (response !== 0) return;
+ if (!deps.isOwnerActive()) return;
if (!guestStillBelongsToHost(params.guestContents, params.hostContents)) return;
if (owner.isDestroyed()) return;
if (!deps.gate.isGhostAvailable(params.ghostId)) return;
diff --git a/apps/desktop/src/main/cindy-brain/ghostPreviewNavigation.ts b/apps/desktop/src/main/cindy-brain/ghostPreviewNavigation.ts
new file mode 100644
index 0000000000..fde29ef6f4
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostPreviewNavigation.ts
@@ -0,0 +1,60 @@
+import type { WebContents } from 'electron';
+
+import type { GhostPreviewGate, GhostPreviewOutcome } from './previewGate.js';
+
+export interface GhostPreviewNavigationLogger {
+ debug(message: string, meta: Record<string, unknown>): void;
+ warn(message: string, meta: Record<string, unknown>): void;
+}
+
+export interface GhostPreviewNavigationParams {
+ ghostId: string;
+ url: string;
+ hostContents: WebContents;
+ guestContents: WebContents;
+}
+
+export interface GhostPreviewNavigationDeps {
+ request: GhostPreviewGate['request'];
+ isOwnerActive(): boolean;
+ send(outcome: Extract<GhostPreviewOutcome, { ok: true }>): void;
+ logger: GhostPreviewNavigationLogger;
+}
+
+/**
+ * Owner-aware preview continuation. The ledger lookup may finish after an
+ * account commit, so the captured owner is checked both before and after it.
+ */
+export async function runGhostPreviewNavigation(
+ params: GhostPreviewNavigationParams,
+ deps: GhostPreviewNavigationDeps,
+): Promise<void> {
+ if (!deps.isOwnerActive()) return;
+ try {
+ const outcome = await deps.request({
+ ghostId: params.ghostId,
+ url: params.url,
+ isPanelFocused: () =>
+ deps.isOwnerActive() &&
+ !params.guestContents.isDestroyed() &&
+ params.guestContents.isFocused(),
+ });
+ if (!deps.isOwnerActive()) return;
+ if (!outcome.ok) {
+ deps.logger.debug('ghost preview rejected', {
+ ghostId: params.ghostId,
+ reason: outcome.reason,
+ });
+ return;
+ }
+ if (params.hostContents.isDestroyed()) return;
+ if (!deps.isOwnerActive()) return;
+ deps.send(outcome);
+ } catch (error) {
+ if (!deps.isOwnerActive()) return;
+ deps.logger.warn('ghost preview failed', {
+ ghostId: params.ghostId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostWebviewPartition.ts b/apps/desktop/src/main/cindy-brain/ghostWebviewPartition.ts
new file mode 100644
index 0000000000..030466cc98
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostWebviewPartition.ts
@@ -0,0 +1,33 @@
+import { GHOST_PARTITION_PREFIX, isValidGhostId, parseGhostPartition } from '../../shared/ghost.js';
+import { dataOwnerStorageKey, type ActiveAppSession } from '../appSessionState.js';
+
+const GHOST_OWNER_PARTITION_PREFIX = `${GHOST_PARTITION_PREFIX}owner:`;
+
+export interface ResolvedGhostWebviewPartition {
+ ghostId: string;
+ partition: string;
+}
+
+/** Main 持有的真实 owner → 不透明、稳定的插件 Electron session 分区。 */
+export function ownerScopedGhostPartition(
+ ghostId: string,
+ owner: Pick<ActiveAppSession, 'mode' | 'dataOwnerId'>,
+): string | null {
+ if (!isValidGhostId(ghostId) || owner.mode === 'signed-out' || !owner.dataOwnerId) return null;
+ return `${GHOST_OWNER_PARTITION_PREFIX}${owner.mode}:${dataOwnerStorageKey(owner.dataOwnerId)}:${ghostId}`;
+}
+
+/**
+ * Main 侧 WebView attach 的 owner 决策原语。
+ * Renderer 的 ghost-only partition 只是 attach claim;实际 partition 由 Main
+ * 根据当前已提交 owner 生成,Renderer 无法挑选另一个 owner 的 session。
+ */
+export function resolveGhostWebviewPartitionClaim(
+ partitionClaim: unknown,
+ activeOwner: Pick<ActiveAppSession, 'mode' | 'dataOwnerId'>,
+): ResolvedGhostWebviewPartition | null {
+ const ghostId = parseGhostPartition(partitionClaim);
+ if (!ghostId) return null;
+ const partition = ownerScopedGhostPartition(ghostId, activeOwner);
+ return partition ? { ghostId, partition } : null;
+}
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index bf80895b7f..52533e0fb9 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -67,6 +67,7 @@ import {
isAppSessionBoundaryPending,
ownerScopedUserDataPath,
type ActiveAppSession,
+ type AppSessionMode,
} from '../appSessionState.js';
import { getLayoutStore } from '../layout/index.js';
import {
@@ -205,7 +206,7 @@ import {
readLegacyEncryptedValue,
type LegacyMigrationRead,
} from './legacyMigrationRead.js';
-import { GHOST_SCHEME, ghostExternalLinkUrls, parseGhostPartition } from '../../shared/ghost.js';
+import { GHOST_SCHEME, ghostExternalLinkUrls } from '../../shared/ghost.js';
import { GhostPipeDispatcher } from './pipeDispatcher.js';
import { GhostCardService, parseCardHeightReport } from './cardService.js';
import { GhostCardActionDispatcher } from './cardActionDispatch.js';
@@ -334,6 +335,8 @@ import {
} from './subscriptionGateway.js';
import { GhostExternalLinkGate, GhostPreviewGate, resolveGhostPanelMedia } from './previewGate.js';
import { runGhostExternalLinkNavigation } from './ghostExternalLinkNavigation.js';
+import { runGhostPreviewNavigation } from './ghostPreviewNavigation.js';
+import { resolveGhostWebviewPartitionClaim } from './ghostWebviewPartition.js';
import {
ghostSecretSaved,
readGhostSecret,
@@ -7681,31 +7684,23 @@ export function handleGhostPreviewNavigation(
url: string,
hostContents: WebContents,
guestContents: WebContents,
+ isOwnerActive: () => boolean,
): void {
- void getGhostPreviewGate()
- .request({
- ghostId,
- url,
- isPanelFocused: () => !guestContents.isDestroyed() && guestContents.isFocused(),
- })
- .then((outcome) => {
- if (!outcome.ok) {
- log.debug('ghost preview rejected', { ghostId, reason: outcome.reason });
- return;
- }
- if (hostContents.isDestroyed()) return;
- sendGhostContentsPush(hostContents, GHOST_PREVIEW_MEDIA_CHANNEL, {
- ghostId,
- src: outcome.src,
- kind: outcome.kind,
- });
- })
- .catch((err) => {
- log.warn('ghost preview failed', {
- ghostId,
- error: err instanceof Error ? err.message : String(err),
- });
- });
+ void runGhostPreviewNavigation(
+ { ghostId, url, hostContents, guestContents },
+ {
+ request: (request) => getGhostPreviewGate().request(request),
+ isOwnerActive,
+ send: (outcome) => {
+ sendGhostContentsPush(hostContents, GHOST_PREVIEW_MEDIA_CHANNEL, {
+ ghostId,
+ src: outcome.src,
+ kind: outcome.kind,
+ });
+ },
+ logger: log,
+ },
+ );
}
let externalLinkGateSingleton: GhostExternalLinkGate | null = null;
@@ -7733,6 +7728,7 @@ export function handleGhostExternalLinkNavigation(
url: string,
hostContents: WebContents,
guestContents: WebContents,
+ isOwnerActive: () => boolean,
): void {
void runGhostExternalLinkNavigation(
{ ghostId, url, hostContents, guestContents },
@@ -7743,6 +7739,7 @@ export function handleGhostExternalLinkNavigation(
openExternal: (targetUrl) => shell.openExternal(targetUrl),
translate: t,
logger: log,
+ isOwnerActive,
},
);
}
@@ -7756,10 +7753,19 @@ export function handleGhostExternalLinkNavigation(
* 把协议 handler 挂好(必须先于 webview 首次加载)。任何一条不满足返回
* null(闸口拒附加)。
*/
-export function resolveGhostWebviewAttach(partition: unknown, src: unknown): InstalledGhost | null {
- const id = parseGhostPartition(partition);
- if (!id || typeof src !== 'string') return null;
- const ghost = findAvailableGhost(id);
+export function resolveGhostWebviewAttach(
+ partitionClaim: unknown,
+ src: unknown,
+): {
+ ghost: InstalledGhost;
+ partition: string;
+ owner: { mode: AppSessionMode; dataOwnerId: string };
+} | null {
+ if (typeof src !== 'string') return null;
+ const owner = getActiveAppSession();
+ const resolvedPartition = resolveGhostWebviewPartitionClaim(partitionClaim, owner);
+ if (!resolvedPartition) return null;
+ const ghost = findAvailableGhost(resolvedPartition.ghostId);
if (!ghost || !ghost.enabled) return null;
const allowedPaths = ghostWebviewEntryPaths(ghost.manifest);
if (allowedPaths.length === 0) return null;
@@ -7769,10 +7775,14 @@ export function resolveGhostWebviewAttach(partition: unknown, src: unknown): Ins
} catch {
return null;
}
- if (url.protocol !== `${GHOST_SCHEME}:` || url.host !== id) return null;
+ if (url.protocol !== `${GHOST_SCHEME}:` || url.host !== resolvedPartition.ghostId) return null;
if (!allowedPaths.includes(url.pathname)) return null;
- ensureGhostProtocolRegistered(ghost);
- return ghost;
+ ensureGhostProtocolRegistered(ghost, owner);
+ return {
+ ghost,
+ partition: resolvedPartition.partition,
+ owner: { mode: owner.mode, dataOwnerId: owner.dataOwnerId! },
+ };
}
/** 播种进行中提示广播(renderer 显示/收起非阻塞胶囊;与退出 overlay 同款视觉)。 */
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts
new file mode 100644
index 0000000000..20d1ecb6bb
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/electronSandboxAdapter.ownerPartition.test.ts
@@ -0,0 +1,320 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const harness = vi.hoisted(() => {
+ let nextWebContentsId = 1;
+ type RegisteredSession = {
+ permissionRequest: ReturnType<typeof vi.fn>;
+ permissionCheck: ReturnType<typeof vi.fn>;
+ on: ReturnType<typeof vi.fn>;
+ beforeRequest: ReturnType<typeof vi.fn>;
+ protocolHandle: ReturnType<typeof vi.fn>;
+ protocolHandler?: (request: Request) => Promise<Response>;
+ downloadHandler?: (event: { preventDefault(): void }) => void;
+ };
+ const sessions = new Map<string, RegisteredSession>();
+ return {
+ activeOwner: {
+ mode: 'cloud' as 'signed-out' | 'local' | 'cloud',
+ dataOwnerId: 'owner-a' as string | null,
+ generation: 1,
+ },
+ sessions,
+ fromPartition: vi.fn((partition: string) => {
+ const existing = sessions.get(partition);
+ if (existing) return existing;
+ const created: RegisteredSession = {
+ permissionRequest: vi.fn(),
+ permissionCheck: vi.fn(),
+ on: vi.fn((event: string, handler: (event: { preventDefault(): void }) => void) => {
+ if (event === 'will-download') created.downloadHandler = handler;
+ }),
+ beforeRequest: vi.fn(),
+ protocolHandle: vi.fn(
+ (_scheme: string, handler: (request: Request) => Promise<Response>) => {
+ created.protocolHandler = handler;
+ },
+ ),
+ };
+ sessions.set(partition, created);
+ return {
+ setPermissionRequestHandler: created.permissionRequest,
+ setPermissionCheckHandler: created.permissionCheck,
+ on: created.on,
+ webRequest: { onBeforeRequest: created.beforeRequest },
+ protocol: { handle: created.protocolHandle },
+ };
+ }),
+ browserWindowOptions: [] as Array<Record<string, unknown>>,
+ BrowserWindow: vi.fn(function BrowserWindow(options: Record<string, unknown>) {
+ harness.browserWindowOptions.push(options);
+ return {
+ webContents: {
+ id: nextWebContentsId++,
+ on: vi.fn(),
+ isDestroyed: vi.fn(() => false),
+ forcefullyCrashRenderer: vi.fn(),
+ },
+ loadURL: vi.fn().mockResolvedValue(undefined),
+ isDestroyed: vi.fn(() => false),
+ destroy: vi.fn(),
+ };
+ }),
+ };
+});
+
+const kvEndpoint = vi.hoisted(() => ({
+ handleGhostKvRequest: vi.fn(),
+ readBoundedBodyText: vi.fn(),
+}));
+
+vi.mock('electron', () => ({
+ BrowserWindow: harness.BrowserWindow,
+ session: { fromPartition: harness.fromPartition },
+ webContents: { fromId: vi.fn(() => null) },
+}));
+
+vi.mock('node:fs', () => ({ createReadStream: vi.fn() }));
+vi.mock('node:fs/promises', () => ({
+ default: {
+ readFile: vi.fn(),
+ stat: vi.fn().mockResolvedValue({ isFile: () => true, size: 0 }),
+ },
+}));
+vi.mock('../../../appSessionState', () => ({
+ dataOwnerStorageKey: (ownerId: string) =>
+ ownerId.startsWith('collision-') ? 'opaque-collision' : `opaque-${ownerId}`,
+ getActiveAppSession: () => ({ ...harness.activeOwner }),
+}));
+vi.mock('../../../logger', () => ({
+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
+}));
+vi.mock('../../../cindy-media/blobStore', () => ({
+ readBlob: vi.fn(),
+ resolveHashRef: vi.fn(),
+}));
+vi.mock('../../../cindy-media/ledger', () => ({
+ ghostCanRead: vi.fn(),
+ listGhostGallery: vi.fn().mockResolvedValue([]),
+}));
+vi.mock('../ghostKvEndpoint', () => kvEndpoint);
+
+import type {
+ GhostAppContextResult,
+ GhostMediaModelsResult,
+ InstalledGhost,
+} from '../../../../shared/ghost';
+import {
+ electronSandboxAdapter,
+ ensureGhostProtocolRegistered,
+ setGhostAppContextProvider,
+ setGhostKvStore,
+ setGhostMediaModelsProvider,
+} from '../electronSandboxAdapter';
+
+function ghost(id: string): InstalledGhost {
+ return {
+ dir: `/plugins/${id}`,
+ enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ manifest: {
+ schemaVersion: 2,
+ id,
+ name: id,
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['panel'],
+ panel: { html: 'panel.html' },
+ },
+ };
+}
+
+beforeEach(() => {
+ harness.activeOwner = { mode: 'cloud', dataOwnerId: 'owner-a', generation: 1 };
+ harness.sessions.clear();
+ harness.fromPartition.mockClear();
+ harness.BrowserWindow.mockClear();
+ harness.browserWindowOptions.length = 0;
+ kvEndpoint.handleGhostKvRequest.mockReset();
+ kvEndpoint.readBoundedBodyText.mockReset();
+});
+
+describe('electronSandboxAdapter owner partition', () => {
+ it('同 ghostId 的不同 owner 使用不同的非持久 session,并显式拒绝权限和下载', () => {
+ const installed = ghost('same-ghost');
+ ensureGhostProtocolRegistered(installed, {
+ mode: 'cloud',
+ dataOwnerId: 'owner-a',
+ generation: 1,
+ });
+ ensureGhostProtocolRegistered(installed, {
+ mode: 'cloud',
+ dataOwnerId: 'owner-b',
+ generation: 2,
+ });
+
+ const sessionA = harness.sessions.get(
+ 'cindy-ghost-owner:cloud:opaque-owner-a:same-ghost',
+ );
+ const sessionB = harness.sessions.get(
+ 'cindy-ghost-owner:cloud:opaque-owner-b:same-ghost',
+ );
+ for (const registered of [sessionA, sessionB]) {
+ expect(registered).toBeDefined();
+ const permissionCallback = vi.fn();
+ registered?.permissionRequest.mock.calls[0]?.[0](null, 'camera', permissionCallback);
+ expect(permissionCallback).toHaveBeenCalledWith(false);
+ expect(registered?.permissionCheck.mock.calls[0]?.[0]()).toBe(false);
+ const downloadEvent = { preventDefault: vi.fn() };
+ registered?.downloadHandler?.(downloadEvent);
+ expect(downloadEvent.preventDefault).toHaveBeenCalledOnce();
+ }
+ });
+
+ it('同 owner 只增加 generation 时复用原 partition', () => {
+ const installed = ghost('generation-stable');
+ ensureGhostProtocolRegistered(installed, {
+ mode: 'cloud',
+ dataOwnerId: 'owner-a',
+ generation: 1,
+ });
+ ensureGhostProtocolRegistered(installed, {
+ mode: 'cloud',
+ dataOwnerId: 'owner-a',
+ generation: 2,
+ });
+
+ expect(harness.fromPartition).toHaveBeenCalledOnce();
+ expect([...harness.sessions.keys()]).toEqual([
+ 'cindy-ghost-owner:cloud:opaque-owner-a:generation-stable',
+ ]);
+ });
+
+ it('owner 切换后旧 Session 的新请求在路由和业务读取前返回 403', async () => {
+ const store = { read: vi.fn(() => ({})), write: vi.fn() };
+ setGhostKvStore(store);
+ ensureGhostProtocolRegistered(ghost('stale-request'), {
+ mode: 'cloud',
+ dataOwnerId: 'owner-a',
+ generation: 1,
+ });
+ const sessionA = harness.sessions.get(
+ 'cindy-ghost-owner:cloud:opaque-owner-a:stale-request',
+ );
+ const routeRead = vi.fn(() => 'cindy-ghost://stale-request/kv');
+ const request = {
+ get url() {
+ return routeRead();
+ },
+ method: 'POST',
+ headers: new Headers(),
+ } as unknown as Request;
+
+ harness.activeOwner = { mode: 'cloud', dataOwnerId: 'owner-b', generation: 2 };
+ const response = await sessionA?.protocolHandler?.(request);
+
+ expect(response?.status).toBe(403);
+ expect(response?.headers.get('cache-control')).toBe('no-store');
+ expect(routeRead).not.toHaveBeenCalled();
+ expect(kvEndpoint.handleGhostKvRequest).not.toHaveBeenCalled();
+ expect(kvEndpoint.readBoundedBodyText).not.toHaveBeenCalled();
+ expect(store.read).not.toHaveBeenCalled();
+ expect(store.write).not.toHaveBeenCalled();
+ });
+
+ it('同 owner generation 变化后旧 Session 仍可走静态与能力路由', async () => {
+ const appContext: GhostAppContextResult = {
+ ok: true,
+ context: { region: 'global', locale: 'en' },
+ };
+ const appContextProvider = vi.fn(() => appContext);
+ setGhostAppContextProvider(appContextProvider);
+ ensureGhostProtocolRegistered(ghost('active-request'), {
+ mode: 'cloud',
+ dataOwnerId: 'owner-a',
+ generation: 1,
+ });
+ harness.activeOwner.generation = 99;
+ const registered = harness.sessions.get(
+ 'cindy-ghost-owner:cloud:opaque-owner-a:active-request',
+ );
+
+ const bootResponse = await registered?.protocolHandler?.(
+ new Request('cindy-ghost://active-request/'),
+ );
+ const contextResponse = await registered?.protocolHandler?.(
+ new Request('cindy-ghost://active-request/app-context'),
+ );
+
+ expect(bootResponse?.status).toBe(200);
+ expect(contextResponse?.status).toBe(200);
+ expect(appContextProvider).toHaveBeenCalledOnce();
+ });
+
+ it('请求已进入 handler 后切换 owner 不取消或重新检查在途 provider', async () => {
+ let finishProvider!: (result: GhostMediaModelsResult) => void;
+ const provider = vi.fn(
+ () =>
+ new Promise<GhostMediaModelsResult>((resolve) => {
+ finishProvider = resolve;
+ }),
+ );
+ setGhostMediaModelsProvider(provider);
+ ensureGhostProtocolRegistered(ghost('inflight-request'), {
+ mode: 'cloud',
+ dataOwnerId: 'owner-a',
+ generation: 1,
+ });
+ const registered = harness.sessions.get(
+ 'cindy-ghost-owner:cloud:opaque-owner-a:inflight-request',
+ );
+ const pending = registered?.protocolHandler?.(
+ new Request('cindy-ghost://inflight-request/media-models?type=image'),
+ );
+ await vi.waitFor(() => expect(provider).toHaveBeenCalledOnce());
+
+ harness.activeOwner = { mode: 'cloud', dataOwnerId: 'owner-b', generation: 2 };
+ const outcome: GhostMediaModelsResult = {
+ ok: true,
+ type: 'image',
+ models: [],
+ defaultModelId: null,
+ defaultProviderId: null,
+ };
+ finishProvider(outcome);
+
+ const response = await pending;
+ expect(response?.status).toBe(200);
+ await expect(response?.json()).resolves.toEqual(outcome);
+ });
+
+ it('相同 partition 不能被不同 owner snapshot 重新认领', () => {
+ const installed = ghost('owner-collision');
+ ensureGhostProtocolRegistered(installed, {
+ mode: 'cloud',
+ dataOwnerId: 'collision-a',
+ generation: 1,
+ });
+
+ expect(() =>
+ ensureGhostProtocolRegistered(installed, {
+ mode: 'cloud',
+ dataOwnerId: 'collision-b',
+ generation: 2,
+ }),
+ ).toThrow('ghost protocol partition already belongs to a different data owner');
+ });
+
+ it('逻辑沙箱也使用当前 owner 的同一非持久 partition', () => {
+ harness.activeOwner = { mode: 'local', dataOwnerId: 'local-owner', generation: 4 };
+ const handle = electronSandboxAdapter.create(ghost('panel-owner'));
+
+ expect(harness.browserWindowOptions[0]?.webPreferences).toMatchObject({
+ partition: 'cindy-ghost-owner:local:opaque-local-owner:panel-owner',
+ });
+ expect(
+ (harness.browserWindowOptions[0]?.webPreferences as { partition: string }).partition,
+ ).not.toMatch(/^persist:/);
+ handle.destroy();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts
index 47a56032ae..2f056f1940 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts
@@ -8,12 +8,13 @@ import { fileURLToPath } from 'node:url';
import { createLogger } from '../../logger.js';
import {
GHOST_SCHEME,
- ghostPartition,
type GhostAppContextResult,
type GhostMediaModelsResult,
type GhostMediaModelType,
type InstalledGhost,
} from '../../../shared/ghost.js';
+import { getActiveAppSession, type ActiveAppSession } from '../../appSessionState.js';
+import { ownerScopedGhostPartition } from '../ghostWebviewPartition.js';
import { GHOST_BOOT_PATH, ghostBootHtml, ghostFileMime, resolveGhostFilePath } from './ghostFiles.js';
import { handleGhostKvRequest, readBoundedBodyText } from './ghostKvEndpoint.js';
import { resolveHashRef as resolveBlobHashRef } from '../../cindy-media/blobStore.js';
@@ -224,14 +225,36 @@ export function setGhostConnectionsHandler(handler: GhostConnectionsProtocolHand
/** 该分区是否已挂过协议 handler(session 分区随 app 生命周期,挂一次即可)。 */
const partitionRegistered = new Set<string>();
const partitionGhost = new Map<string, { dir: string; entry: string }>();
+type GhostProtocolOwnerIdentity = Pick<ActiveAppSession, 'mode' | 'dataOwnerId'>;
+const partitionOwner = new Map<string, GhostProtocolOwnerIdentity>();
+
+function ghostProtocolOwnerSnapshot(owner: ActiveAppSession): GhostProtocolOwnerIdentity {
+ return { mode: owner.mode, dataOwnerId: owner.dataOwnerId };
+}
+
+function isSameGhostProtocolOwner(
+ left: GhostProtocolOwnerIdentity,
+ right: GhostProtocolOwnerIdentity,
+): boolean {
+ return left.mode === right.mode && left.dataOwnerId === right.dataOwnerId;
+}
+
+function isGhostProtocolOwnerActive(owner: GhostProtocolOwnerIdentity): boolean {
+ return isSameGhostProtocolOwner(owner, getActiveAppSession());
+}
/**
* 确保某意识分区上的 cindy-ghost:// 协议 handler 就位(幂等)。
* 两个调用方:离屏沙箱窗口(create)与面板 webview 附加闸(webview-security
* 放行前调用——handler 必须先于 webview 首次加载挂好)。
*/
-export function ensureGhostProtocolRegistered(ghost: InstalledGhost): void {
- registerGhostProtocol(ghostPartition(ghost.manifest.id), ghost);
+export function ensureGhostProtocolRegistered(
+ ghost: InstalledGhost,
+ owner: ActiveAppSession = getActiveAppSession(),
+): void {
+ const partition = ownerScopedGhostPartition(ghost.manifest.id, owner);
+ if (!partition) throw new Error('ghost protocol requires an active data owner');
+ registerGhostProtocol(partition, ghost, ghostProtocolOwnerSnapshot(owner));
}
/**
@@ -242,7 +265,15 @@ export function ensureGhostProtocolRegistered(ghost: InstalledGhost): void {
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 {
+function registerGhostProtocol(
+ partition: string,
+ ghost: InstalledGhost,
+ owner: GhostProtocolOwnerIdentity,
+): void {
+ const registeredOwner = partitionOwner.get(partition);
+ if (registeredOwner && !isSameGhostProtocolOwner(registeredOwner, owner)) {
+ throw new Error('ghost protocol partition already belongs to a different data owner');
+ }
partitionGhost.set(partition, {
dir: ghost.dir,
entry: ghost.manifest.entry,
@@ -253,6 +284,11 @@ function registerGhostProtocol(partition: string, ghost: InstalledGhost): void {
// 实际无 handler,面板与电子脑一起哑火(review P0 的中毒模式)。
const ses = session.fromPartition(partition);
const ghostId = ghost.manifest.id;
+ // 每个 owner 都会得到新的内存 session;权限与下载必须显式拒绝,不能
+ // 因为分区是新建的就依赖 Electron 默认行为。
+ ses.setPermissionRequestHandler((_webContents, _permission, callback) => callback(false));
+ ses.setPermissionCheckHandler(() => false);
+ ses.on('will-download', (event) => event.preventDefault());
// 分区级断网(docs/dev-rules/plugin-security-and-authoring.md 的"网络永远不直连"):本分区发出的一切
// 请求,只放行自己协议同 id 下的资源;http(s) / ws / 其它协议一律掐断。
// 进程沙箱不管网络,这里才是"零网络"承诺的真正闸门;外部数据未来走
@@ -263,6 +299,15 @@ function registerGhostProtocol(partition: string, ghost: InstalledGhost): void {
});
ses.protocol.handle(SCHEME, async (request) => {
try {
+ // owner B 提交后,owner A 的旧 guest 仍可能短暂存活并新发请求。
+ // 在 URL 路由、body 读取和任何 provider 调用前拒绝旧 Session;已经
+ // 进入 handler 的请求不在这里取消或排空。
+ if (!isGhostProtocolOwnerActive(owner)) {
+ return new Response(null, {
+ status: 403,
+ headers: { 'Cache-Control': 'no-store' },
+ });
+ }
const url = new URL(request.url);
// 分区专属通道只认自己的 id,其它 host 一律 403(结构隔离的最后一道断言)。
if (url.host !== ghostId) return new Response(null, { status: 403 });
@@ -453,6 +498,7 @@ function registerGhostProtocol(partition: string, ghost: InstalledGhost): void {
return new Response(null, { status: 500 });
}
});
+ partitionOwner.set(partition, owner);
partitionRegistered.add(partition); // 全部挂载成功,才算注册完成
}
@@ -615,8 +661,10 @@ class ElectronSandboxHandle implements SandboxHandle {
private destroyed = false;
constructor(private readonly ghost: InstalledGhost) {
- const partition = ghostPartition(ghost.manifest.id);
- registerGhostProtocol(partition, ghost);
+ const activeOwner = getActiveAppSession();
+ const partition = ownerScopedGhostPartition(ghost.manifest.id, activeOwner);
+ if (!partition) throw new Error('ghost sandbox requires an active data owner');
+ registerGhostProtocol(partition, ghost, ghostProtocolOwnerSnapshot(activeOwner));
this.win = new BrowserWindow({
show: false,
// 逻辑页是恒隐藏的离屏工作台;可见面板由独立 webview 嵌入布局。
diff --git a/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts b/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts
index 7d7de9f92d..88108b5946 100644
--- a/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts
+++ b/apps/desktop/src/main/ghost-panel-window/__tests__/controller.test.ts
@@ -426,6 +426,55 @@ describe('closed event', () => {
});
});
+describe('owner change', () => {
+ it('destroys visible, hidden, pending, and prewarmed windows and returns entries to docked', () => {
+ const h = makeHarness(new Set(['visible', 'hidden', 'pending', 'prewarmed']));
+ h.controller.open('visible');
+ markReady(h.controller, h.created[0].win);
+ h.controller.open('hidden');
+ markReady(h.controller, h.created[1].win);
+ h.controller.close('hidden');
+ h.controller.open('pending');
+ h.controller.prewarm('prewarmed');
+
+ h.controller.closeForOwnerChange();
+
+ expect(h.created.map(({ win }) => win.isDestroyed())).toEqual([true, true, true, true]);
+ expect(h.created.every(({ win }) => win.destroy.mock.calls.length === 1)).toBe(true);
+ expect(h.created.every(({ win }) => win.close.mock.calls.length === 0)).toBe(true);
+ expect(h.entries()).toEqual({
+ visible: { detached: false, lastOpen: false },
+ hidden: { detached: false, lastOpen: false },
+ pending: { detached: false, lastOpen: false },
+ });
+ expect(h.controller.getState()).toEqual({
+ visible: { detached: false, lastOpen: false, open: false },
+ hidden: { detached: false, lastOpen: false, open: false },
+ pending: { detached: false, lastOpen: false, open: false },
+ });
+ expect(h.broadcasts.at(-1)).toEqual(h.controller.getState());
+ });
+
+ it('keeps the panel docked through reconcile and only creates a new slot on explicit detach', () => {
+ const h = makeHarness(new Set(['a']));
+ h.controller.setDetached('a', true);
+ const ownerAWindow = h.created[0].win;
+
+ h.controller.closeForOwnerChange();
+ h.controller.reconcile([ghost('a')]);
+
+ expect(ownerAWindow.isDestroyed()).toBe(true);
+ expect(h.created).toHaveLength(1);
+ expect(h.entries().a).toEqual({ detached: false, lastOpen: false });
+
+ const state = h.controller.setDetached('a', true);
+ expect(h.created).toHaveLength(2);
+ expect(h.created[1].win.isDestroyed()).toBe(false);
+ expect(h.entries().a).toEqual({ detached: true, lastOpen: true });
+ expect(state.a).toEqual({ detached: true, lastOpen: true, open: true });
+ });
+});
+
describe('open guard (non-detachable)', () => {
it('non-detachable plugin: prunes entry, no window', () => {
const h = makeHarness(new Set());
diff --git a/apps/desktop/src/main/ghost-panel-window/controller.ts b/apps/desktop/src/main/ghost-panel-window/controller.ts
index 3460675ace..f3f1c6cac6 100644
--- a/apps/desktop/src/main/ghost-panel-window/controller.ts
+++ b/apps/desktop/src/main/ghost-panel-window/controller.ts
@@ -281,6 +281,19 @@ export class GhostPanelWindowsController {
// ── 生命周期 ────────────────────────────────────────────────────────
+ /**
+ * data owner 真变化时同步销毁旧 owner 的所有独立窗口。
+ * 把既有面板收口回 docked/closed,避免新 owner 失去正常 UI 入口。
+ */
+ closeForOwnerChange(): void {
+ const { windows } = this.deps.settings.read();
+ this.destroyAllWindows();
+ for (const ghostId of Object.keys(windows)) {
+ this.deps.settings.patchEntry(ghostId, { detached: false, lastOpen: false });
+ }
+ this.broadcast();
+ }
+
/** 主窗口销毁时回收所有隐藏窗口;controller 仍可随下一扇主窗重新预热。 */
destroyAllWindows(): void {
for (const [id, slot] of this.slots) {
diff --git a/apps/desktop/src/main/webview-security.ts b/apps/desktop/src/main/webview-security.ts
index 1d4c141651..88ba90e9c7 100644
--- a/apps/desktop/src/main/webview-security.ts
+++ b/apps/desktop/src/main/webview-security.ts
@@ -33,6 +33,7 @@ import {
LOGIN_CAPTCHA_PARTITION,
} from '../shared/webviewPartition';
import { GHOST_PARTITION_PREFIX } from '../shared/ghost';
+import { getActiveAppSession, type AppSessionMode } from './appSessionState.js';
import {
matchesElectronInput,
type AppShortcutCombo,
@@ -166,6 +167,34 @@ export function applyGhostWebviewHardening(
delete webPreferences.preload;
}
+type GhostWebviewAttachResolver = typeof resolveGhostWebviewAttach;
+
+/**
+ * 把 Renderer 的 ghost-only claim 换成 Main 已核准的 owner partition,并同步
+ * 应用插件 WebView 安全锁。返回 null 时调用方必须拒绝 attach。
+ */
+export function authorizeGhostWebviewAttach(
+ webPreferences: Record<string, unknown>,
+ params: Record<string, string>,
+ resolver: GhostWebviewAttachResolver = resolveGhostWebviewAttach,
+): { id: string; owner: { mode: AppSessionMode; dataOwnerId: string } } | null {
+ let resolved: ReturnType<GhostWebviewAttachResolver> = null;
+ try {
+ resolved = resolver(params.partition, params.src);
+ } catch {
+ // session/protocol 注册失败也必须 fail closed。
+ }
+ if (!resolved) return null;
+
+ // Electron 在触发 will-attach-webview 前已经把 params.partition 复制进
+ // webPreferences.partition,之后创建 guest 时读取的是后者。两边都必须由
+ // Main 的核准结果覆盖,否则只改 attribute dict 不会改变真实 session。
+ params.partition = resolved.partition;
+ webPreferences.partition = resolved.partition;
+ applyGhostWebviewHardening(webPreferences, params);
+ return { id: resolved.ghost.manifest.id, owner: resolved.owner };
+}
+
/**
* 登录页人机验证(Turnstile 托管挑战页)webview 的加固:与意识面板同一套锁死集——
* 零弹窗、零 preload、保留调用方已验证的专属内存分区。挑战页是我们自己的
@@ -776,10 +805,21 @@ export function installBrowserGuestHandlers(
}
interface GhostGuestNavigationHandlers {
+ gesture?: typeof noteGhostUserGesture;
preview: typeof handleGhostPreviewNavigation;
external: typeof handleGhostExternalLinkNavigation;
}
+interface GhostGuestOwnerIdentity {
+ mode: AppSessionMode;
+ dataOwnerId: string;
+}
+
+function isGhostGuestOwnerActive(owner: GhostGuestOwnerIdentity): boolean {
+ const activeOwner = getActiveAppSession();
+ return activeOwner.mode === owner.mode && activeOwner.dataOwnerId === owner.dataOwnerId;
+}
+
/**
* settingsHtml 与 panel 共用的 Ghost guest 导航接线。策略仍集中在
* previewGate / cindy-brain;这里仅保证普通 will-navigate 被主机接管,
@@ -789,13 +829,17 @@ export function installGhostGuestNavigationHandlers(
hostContents: WebContents,
guestContents: WebContents,
ghostId: string,
+ isOwnerActive: () => boolean,
handlers: GhostGuestNavigationHandlers = {
preview: handleGhostPreviewNavigation,
external: handleGhostExternalLinkNavigation,
},
): void {
guestContents.setWindowOpenHandler(() => ({ action: 'deny' }));
- const noteGesture = () => noteGhostUserGesture(ghostId);
+ const noteGesture = () => {
+ if (!isOwnerActive()) return;
+ (handlers.gesture ?? noteGhostUserGesture)(ghostId);
+ };
guestContents.on('before-mouse-event', (_event, mouse) => {
if (mouse.type === 'mouseDown') noteGesture();
});
@@ -803,13 +847,19 @@ export function installGhostGuestNavigationHandlers(
if (input.type === 'keyDown') noteGesture();
});
guestContents.on('will-navigate', (event, url) => {
+ // owner commit 后、Renderer 卸载旧 guest 前仍可能收到导航事件。旧页
+ // 不能借新 owner 的同名插件声明或授权代开外链。
+ if (!isOwnerActive()) {
+ event.preventDefault();
+ return;
+ }
const nav = classifyGhostPanelNavigation(url, ghostId);
if (nav === 'allow') return;
event.preventDefault();
if (nav === 'preview') {
- handlers.preview(ghostId, url, hostContents, guestContents);
+ handlers.preview(ghostId, url, hostContents, guestContents, isOwnerActive);
} else if (nav === 'external') {
- handlers.external(ghostId, url, hostContents, guestContents);
+ handlers.external(ghostId, url, hostContents, guestContents, isOwnerActive);
}
});
}
@@ -819,7 +869,7 @@ export function installWebviewHardener(): void {
// will-attach → did-attach 对同一个 guest 同步成对触发;用闭包变量把
// will 阶段的意识/captcha 判定带给 did 阶段(这两类 guest 走独立接线,
// 不装浏览器的 popup 路由与快捷键转发)。
- let pendingGhostAttach: { id: string } | null = null;
+ let pendingGhostAttach: ReturnType<typeof authorizeGhostWebviewAttach> = null;
let pendingCaptchaAttach = false;
contents.on('will-attach-webview', (e, webPreferences, params) => {
pendingCaptchaAttach = false;
@@ -827,14 +877,16 @@ export function installWebviewHardener(): void {
// 分区/地址/已装清单三对齐才放行并保留专属分区;验证失败直接拒附加
// (绝不回落到浏览器分区,那会让 cindy-ghost:// 内容跑进错误 session)。
if (typeof params.partition === 'string' && params.partition.startsWith(GHOST_PARTITION_PREFIX)) {
- const ghost = resolveGhostWebviewAttach(params.partition, params.src);
- if (!ghost) {
+ const authorized = authorizeGhostWebviewAttach(
+ webPreferences as unknown as Record<string, unknown>,
+ params,
+ );
+ if (!authorized) {
e.preventDefault();
pendingGhostAttach = null;
return;
}
- applyGhostWebviewHardening(webPreferences as unknown as Record<string, unknown>, params);
- pendingGhostAttach = { id: ghost.manifest.id };
+ pendingGhostAttach = authorized;
return;
}
pendingGhostAttach = null;
@@ -879,7 +931,8 @@ export function installWebviewHardener(): void {
return;
}
if (pendingGhostAttach) {
- const ghostId = pendingGhostAttach.id;
+ const authorized = pendingGhostAttach;
+ const ghostId = authorized.id;
pendingGhostAttach = null;
// 崩溃豁免登记(lifecycle 的全局 render-process-gone 守卫据此放行,
// 面板错误接管态负责用户侧收尾)。
@@ -888,7 +941,12 @@ export function installWebviewHardener(): void {
// 两个声明式例外(都是拦下导航、主机代办,面板侧依旧零桥):
// - /preview/ 预览链接 → 主窗口弹 lightbox(cindy-brain/previewGate.ts);
// - https 外链 → 外链闸(声明/授信直开,其余二次确认)转系统浏览器。
- installGhostGuestNavigationHandlers(contents, guestContents, ghostId);
+ installGhostGuestNavigationHandlers(
+ contents,
+ guestContents,
+ ghostId,
+ () => isGhostGuestOwnerActive(authorized.owner),
+ );
return;
}
installBrowserGuestHandlers(contents, guestContents);
diff --git a/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx b/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
index e1bd5877e9..f66801c636 100644
--- a/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
@@ -3,6 +3,7 @@ import { useTranslation } from 'react-i18next';
import { CircleAlert, LayoutGrid, MoonStar } from 'lucide-react';
import type { WebviewTag } from 'electron';
+import { useAuth } from '@/contexts/AuthContext';
import { cn } from '@/lib/utils';
import { GHOST_SCHEME, ghostPartition, type InstalledGhost } from '../../shared/ghost';
import {
@@ -159,14 +160,17 @@ function CrashedHint({
function SettingsWebviewBody({
ghost,
appearance,
+ dataOwnerId,
}: {
ghost: InstalledGhost;
appearance: 'settings' | 'plugin';
+ dataOwnerId: string | null;
}): ReactNode {
const [crashed, setCrashed] = useState(false);
const [generation, setGeneration] = useState(0);
const hostRef = useRef<HTMLDivElement | null>(null);
const { manifest } = ghost;
+ const partitionClaim = ghostPartition(manifest.id);
const settingsHtml = manifest.settingsHtml;
const fixedHeight = manifest.settingsHeight;
const buildSettingsThemeCss =
@@ -174,7 +178,7 @@ function SettingsWebviewBody({
// 首帧贴的快照(仅 mount 时决定一次;版本/主题/DPR 现场比对,宽度等布局后
// 由下方 layout effect 补验)。失配 = null,走透明占位 + 淡入的老路径。
const [snapshot, setSnapshot] = useState<GhostSettingsSnapshot | null>(() => {
- const snap = loadGhostSettingsSnapshot(manifest.id);
+ const snap = loadGhostSettingsSnapshot(dataOwnerId, manifest.id);
if (!snap) return null;
const ctx = {
version: manifest.version,
@@ -187,9 +191,9 @@ function SettingsWebviewBody({
// 版本——换版后界面可能全变,旧高度不可信;主题/DPR 不影响布局高,不卡)
// → 占位高。前两级命中时首帧即终态,零跳变。固定高度声明时本状态不参与。
const [autoHeight, setAutoHeight] = useState(() => {
- const cached = lastMeasuredHeights.get(manifest.id);
+ const cached = lastMeasuredHeights.get(`${dataOwnerId ?? ''}:${manifest.id}`);
if (cached !== undefined) return cached;
- const snap = loadGhostSettingsSnapshot(manifest.id);
+ const snap = loadGhostSettingsSnapshot(dataOwnerId, manifest.id);
return snap && snap.version === manifest.version ? snap.height : AUTO_HEIGHT_PLACEHOLDER;
});
@@ -211,7 +215,7 @@ function SettingsWebviewBody({
const host = hostRef.current;
if (!host) return;
const webview = document.createElement('webview') as WebviewTag;
- webview.setAttribute('partition', ghostPartition(manifest.id));
+ webview.setAttribute('partition', partitionClaim);
webview.setAttribute('src', `${GHOST_SCHEME}://${manifest.id}/${settingsHtml}`);
// 先透明占位:guest 装载与主题注入完成前不露面(一次性淡入,非常驻动画)。
// 有快照时快照图盖在上层,这段透明期用户看到的就是"成品画面"。
@@ -262,7 +266,7 @@ function SettingsWebviewBody({
if (disposed) return;
const rect = host.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) return;
- saveGhostSettingsSnapshot(manifest.id, {
+ saveGhostSettingsSnapshot(dataOwnerId, manifest.id, {
dataUrl: image.toDataURL(),
width: rect.width,
height: rect.height,
@@ -314,7 +318,7 @@ function SettingsWebviewBody({
.then((h: unknown) => {
if (disposed || typeof h !== 'number' || !Number.isFinite(h)) return;
const clamped = Math.max(AUTO_HEIGHT_MIN, Math.min(AUTO_HEIGHT_MAX, Math.ceil(h)));
- lastMeasuredHeights.set(manifest.id, clamped);
+ lastMeasuredHeights.set(`${dataOwnerId ?? ''}:${manifest.id}`, clamped);
setAutoHeight((cur) => (cur === clamped ? cur : clamped));
})
.catch(() => {})
@@ -404,6 +408,8 @@ function SettingsWebviewBody({
manifest.resolvedLocale,
settingsHtml,
fixedHeight,
+ dataOwnerId,
+ partitionClaim,
]);
if (crashed) {
@@ -455,6 +461,8 @@ export function GhostSettingsWebview({
appearance?: 'settings' | 'plugin';
}): ReactNode {
const { t } = useTranslation();
+ const { mode, dataOwnerId } = useAuth();
+ const ownerKey = `${mode}:${dataOwnerId ?? ''}`;
const { manifest } = ghost;
if (!manifest.settingsHtml) return null;
return (
@@ -478,7 +486,12 @@ export function GhostSettingsWebview({
</p>
</div>
{ghost.enabled ? (
- <SettingsWebviewBody ghost={ghost} appearance={appearance} />
+ <SettingsWebviewBody
+ key={ownerKey}
+ ghost={ghost}
+ appearance={appearance}
+ dataOwnerId={dataOwnerId}
+ />
) : (
<AsleepHint appearance={appearance} />
)}
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx
index 511ce5b900..808f9012ed 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx
@@ -5,7 +5,12 @@
*/
import { render, waitFor } from '@testing-library/react';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const authState = vi.hoisted(() => ({
+ mode: 'cloud' as 'signed-out' | 'local' | 'cloud',
+ dataOwnerId: 'owner-a' as string | null,
+}));
import type { InstalledGhost } from '../../../shared/ghost';
import { GhostSettingsWebview } from '../GhostSettingsWebview';
@@ -14,12 +19,27 @@ vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
+vi.mock('@/contexts/AuthContext', () => ({
+ useAuth: () => authState,
+}));
+
+beforeEach(() => {
+ authState.mode = 'cloud';
+ authState.dataOwnerId = 'owner-a';
+});
+
afterEach(() => {
vi.restoreAllMocks();
});
-function renderSettings(settingsHeight?: number) {
- const executeJavaScript = vi.fn().mockResolvedValue(undefined);
+function renderSettings(settingsHeight?: number, measuredHeight?: number) {
+ const executeJavaScript = vi.fn().mockImplementation((script: unknown) =>
+ Promise.resolve(
+ measuredHeight !== undefined && String(script).includes('var bottom=r.bottom')
+ ? measuredHeight
+ : undefined,
+ ),
+ );
const originalCreateElement = document.createElement.bind(document);
vi.spyOn(document, 'createElement').mockImplementation(((
@@ -42,7 +62,7 @@ function renderSettings(settingsHeight?: number) {
enabled: true,
dir: '/tmp/example',
manifest: {
- id: 'example.settings-layout',
+ id: 'example-settings-layout',
name: 'Example',
version: '1.0.0',
settingsHtml: 'settings.html',
@@ -58,7 +78,7 @@ function renderSettings(settingsHeight?: number) {
const host = view.container.querySelector<HTMLElement>('[data-ghost-webview]');
if (!host) throw new Error('Expected settings webview host');
- return { executeJavaScript, host };
+ return { executeJavaScript, ghost, host, view, webview };
}
describe('GhostSettingsWebview layout ownership', () => {
@@ -90,4 +110,27 @@ describe('GhostSettingsWebview layout ownership', () => {
expect(responsiveScript).toContain('max-width:100%!important');
expect(host.classList.contains('overflow-hidden')).toBe(true);
});
+
+ it('recreates settings WebView when owner changes for the same ghostId', () => {
+ const { ghost, view, webview: ownerAWebview } = renderSettings();
+
+ authState.dataOwnerId = 'owner-b';
+ view.rerender(<GhostSettingsWebview ghost={ghost} />);
+
+ const ownerBWebview = view.container.querySelector('webview');
+ expect(ownerBWebview).not.toBeNull();
+ expect(ownerBWebview).not.toBe(ownerAWebview);
+ });
+
+ it('does not reuse owner A measured height for owner B first frame', async () => {
+ const { ghost, host: ownerAHost, view } = renderSettings(undefined, 432);
+ await waitFor(() => expect(ownerAHost.style.height).toBe('432px'));
+
+ authState.dataOwnerId = 'owner-b';
+ view.rerender(<GhostSettingsWebview ghost={ghost} />);
+
+ const ownerBHost = view.container.querySelector<HTMLElement>('[data-ghost-webview]');
+ expect(ownerBHost).not.toBeNull();
+ expect(ownerBHost?.style.height).toBe('160px');
+ });
});
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostSettingsSnapshot.test.ts b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostSettingsSnapshot.test.ts
index 8fc79af06b..a492f286d5 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/ghostSettingsSnapshot.test.ts
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/ghostSettingsSnapshot.test.ts
@@ -39,33 +39,50 @@ beforeEach(() => {
describe('存取往返', () => {
it('save 后 load 返回同一内容,且写进了 localStorage', () => {
const snap = makeSnapshot();
- saveGhostSettingsSnapshot('g1', snap);
+ saveGhostSettingsSnapshot('owner-a', 'g1', snap);
__resetGhostSettingsSnapshotCacheForTest();
- expect(loadGhostSettingsSnapshot('g1')).toEqual(snap);
- expect(localStorage.getItem('ghostSettings.snapshot.g1')).toBeTruthy();
+ expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toEqual(snap);
+ expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:g1')).toBeTruthy();
});
it('不同意识 id 互不串台', () => {
- saveGhostSettingsSnapshot('g1', makeSnapshot({ version: '1.0.0' }));
- saveGhostSettingsSnapshot('g2', makeSnapshot({ version: '2.0.0' }));
- expect(loadGhostSettingsSnapshot('g1')?.version).toBe('1.0.0');
- expect(loadGhostSettingsSnapshot('g2')?.version).toBe('2.0.0');
+ saveGhostSettingsSnapshot('owner-a', 'g1', makeSnapshot({ version: '1.0.0' }));
+ saveGhostSettingsSnapshot('owner-a', 'g2', makeSnapshot({ version: '2.0.0' }));
+ expect(loadGhostSettingsSnapshot('owner-a', 'g1')?.version).toBe('1.0.0');
+ expect(loadGhostSettingsSnapshot('owner-a', 'g2')?.version).toBe('2.0.0');
+ });
+
+ it('不同 owner 的同 ghostId 互不读取,旧的无 owner 快照不自动认领', () => {
+ const ownerASnapshot = makeSnapshot({ version: 'owner-a-version' });
+ saveGhostSettingsSnapshot('owner-a', 'shared-ghost', ownerASnapshot);
+ localStorage.setItem(
+ 'ghostSettings.snapshot.shared-ghost',
+ JSON.stringify(makeSnapshot({ version: 'legacy-unowned' })),
+ );
+
+ expect(loadGhostSettingsSnapshot('owner-a', 'shared-ghost')).toEqual(ownerASnapshot);
+ expect(loadGhostSettingsSnapshot('owner-b', 'shared-ghost')).toBeNull();
+
+ const ownerBSnapshot = makeSnapshot({ version: 'owner-b-version' });
+ saveGhostSettingsSnapshot('owner-b', 'shared-ghost', ownerBSnapshot);
+ expect(loadGhostSettingsSnapshot('owner-b', 'shared-ghost')).toEqual(ownerBSnapshot);
+ expect(loadGhostSettingsSnapshot('owner-a', 'shared-ghost')).toEqual(ownerASnapshot);
});
it('没有存量时返回 null', () => {
- expect(loadGhostSettingsSnapshot('nope')).toBeNull();
+ expect(loadGhostSettingsSnapshot('owner-a', 'nope')).toBeNull();
});
});
describe('容错', () => {
it('localStorage 里是坏 JSON 时按没有处理', () => {
- localStorage.setItem('ghostSettings.snapshot.g1', '{oops');
- expect(loadGhostSettingsSnapshot('g1')).toBeNull();
+ localStorage.setItem('ghostSettings.snapshot.v2.owner-a:g1', '{oops');
+ expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toBeNull();
});
it('形不对(缺字段 / 类型错 / 非图片 dataUrl)按没有处理', () => {
localStorage.setItem(
- 'ghostSettings.snapshot.g1',
+ 'ghostSettings.snapshot.v2.owner-a:g1',
JSON.stringify({
dataUrl: 'javascript:alert(1)',
width: 1,
@@ -76,25 +93,25 @@ describe('容错', () => {
capturedAt: Date.now(),
}),
);
- expect(loadGhostSettingsSnapshot('g1')).toBeNull();
+ expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toBeNull();
__resetGhostSettingsSnapshotCacheForTest();
localStorage.setItem(
- 'ghostSettings.snapshot.g1',
+ 'ghostSettings.snapshot.v2.owner-a:g1',
JSON.stringify({ ...makeSnapshot(), width: 'wide' }),
);
- expect(loadGhostSettingsSnapshot('g1')).toBeNull();
+ expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toBeNull();
__resetGhostSettingsSnapshotCacheForTest();
// 老格式(缺 capturedAt)同样作废。
const legacy: Partial<GhostSettingsSnapshot> = { ...makeSnapshot() };
delete legacy.capturedAt;
- localStorage.setItem('ghostSettings.snapshot.g1', JSON.stringify(legacy));
- expect(loadGhostSettingsSnapshot('g1')).toBeNull();
+ localStorage.setItem('ghostSettings.snapshot.v2.owner-a:g1', JSON.stringify(legacy));
+ expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toBeNull();
__resetGhostSettingsSnapshotCacheForTest();
const preLayoutRevision: Partial<GhostSettingsSnapshot> = { ...makeSnapshot() };
delete preLayoutRevision.layoutRevision;
- localStorage.setItem('ghostSettings.snapshot.g1', JSON.stringify(preLayoutRevision));
- expect(loadGhostSettingsSnapshot('g1')).toBeNull();
+ localStorage.setItem('ghostSettings.snapshot.v2.owner-a:g1', JSON.stringify(preLayoutRevision));
+ expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toBeNull();
});
it('localStorage 写失败(配额满)时静默降级为仅内存缓存', () => {
@@ -103,9 +120,9 @@ describe('容错', () => {
});
try {
const snap = makeSnapshot();
- expect(() => saveGhostSettingsSnapshot('g1', snap)).not.toThrow();
+ expect(() => saveGhostSettingsSnapshot('owner-a', 'g1', snap)).not.toThrow();
// 本会话内存缓存仍可读。
- expect(loadGhostSettingsSnapshot('g1')).toEqual(snap);
+ expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toEqual(snap);
} finally {
spy.mockRestore();
}
@@ -114,47 +131,57 @@ describe('容错', () => {
describe('存储预算', () => {
it('单条超大位图只存内存不落 localStorage,并清掉同 id 旧持久快照', () => {
- saveGhostSettingsSnapshot('g1', makeSnapshot());
- expect(localStorage.getItem('ghostSettings.snapshot.g1')).toBeTruthy();
+ saveGhostSettingsSnapshot('owner-a', 'g1', makeSnapshot());
+ expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:g1')).toBeTruthy();
const snap = makeSnapshot({ dataUrl: `data:image/png;base64,${'a'.repeat(500_000)}` });
- saveGhostSettingsSnapshot('g1', snap);
- expect(localStorage.getItem('ghostSettings.snapshot.g1')).toBeNull();
- expect(loadGhostSettingsSnapshot('g1')).toEqual(snap);
+ saveGhostSettingsSnapshot('owner-a', 'g1', snap);
+ expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:g1')).toBeNull();
+ expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toEqual(snap);
});
it('总量超预算时按拍摄时间淘汰最旧的其它快照', () => {
const big = (tag: string) => `data:image/png;base64,${tag.repeat(390_000)}`;
// 5 条 ~390k 快照(总预算 2M):写第 6 条时应从最旧开始腾位。
for (let i = 0; i < 5; i++) {
- saveGhostSettingsSnapshot(`g${i}`, makeSnapshot({ dataUrl: big('a'), capturedAt: 1000 + i }));
+ saveGhostSettingsSnapshot('owner-a', `g${i}`, makeSnapshot({ dataUrl: big('a'), capturedAt: 1000 + i }));
}
- saveGhostSettingsSnapshot('gNew', makeSnapshot({ dataUrl: big('b'), capturedAt: 9999 }));
+ saveGhostSettingsSnapshot('owner-a', 'gNew', makeSnapshot({ dataUrl: big('b'), capturedAt: 9999 }));
// 最新的必须在;最旧的 g0(至少)被淘汰;总量回到预算内。
- expect(localStorage.getItem('ghostSettings.snapshot.gNew')).toBeTruthy();
- expect(localStorage.getItem('ghostSettings.snapshot.g0')).toBeNull();
+ expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:gNew')).toBeTruthy();
+ expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:g0')).toBeNull();
let total = 0;
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i)!;
- if (key.startsWith('ghostSettings.snapshot.')) total += localStorage.getItem(key)!.length;
+ if (key.startsWith('ghostSettings.snapshot.v2.owner-a:')) total += localStorage.getItem(key)!.length;
}
expect(total).toBeLessThanOrEqual(2_000_000);
});
it('TTL 过期的快照按没有处理并顺手清盘', () => {
const stale = makeSnapshot({ capturedAt: Date.now() - 15 * 24 * 60 * 60 * 1000 });
- localStorage.setItem('ghostSettings.snapshot.g1', JSON.stringify(stale));
- expect(loadGhostSettingsSnapshot('g1')).toBeNull();
- expect(localStorage.getItem('ghostSettings.snapshot.g1')).toBeNull();
+ localStorage.setItem('ghostSettings.snapshot.v2.owner-a:g1', JSON.stringify(stale));
+ expect(loadGhostSettingsSnapshot('owner-a', 'g1')).toBeNull();
+ expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:g1')).toBeNull();
});
it('prune 按已装清单清孤儿(含内存缓存),在装的不动', () => {
- saveGhostSettingsSnapshot('keep', makeSnapshot());
- saveGhostSettingsSnapshot('orphan', makeSnapshot());
- pruneGhostSettingsSnapshots(['keep', 'not-yet-snapshotted']);
- expect(localStorage.getItem('ghostSettings.snapshot.keep')).toBeTruthy();
- expect(localStorage.getItem('ghostSettings.snapshot.orphan')).toBeNull();
- expect(loadGhostSettingsSnapshot('orphan')).toBeNull();
- expect(loadGhostSettingsSnapshot('keep')).toBeTruthy();
+ saveGhostSettingsSnapshot('owner-a', 'keep', makeSnapshot());
+ saveGhostSettingsSnapshot('owner-a', 'orphan', makeSnapshot());
+ pruneGhostSettingsSnapshots('owner-a', ['keep', 'not-yet-snapshotted']);
+ expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:keep')).toBeTruthy();
+ expect(localStorage.getItem('ghostSettings.snapshot.v2.owner-a:orphan')).toBeNull();
+ expect(loadGhostSettingsSnapshot('owner-a', 'orphan')).toBeNull();
+ expect(loadGhostSettingsSnapshot('owner-a', 'keep')).toBeTruthy();
+ });
+
+ it('prune 只清当前 owner,不触碰其他 owner 的同名快照', () => {
+ saveGhostSettingsSnapshot('owner-a', 'orphan', makeSnapshot({ version: 'a' }));
+ saveGhostSettingsSnapshot('owner-b', 'orphan', makeSnapshot({ version: 'b' }));
+
+ pruneGhostSettingsSnapshots('owner-a', []);
+
+ expect(loadGhostSettingsSnapshot('owner-a', 'orphan')).toBeNull();
+ expect(loadGhostSettingsSnapshot('owner-b', 'orphan')?.version).toBe('b');
});
});
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
index c89e975f2e..dac4709f74 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/ghostPanels.tsx
@@ -19,6 +19,7 @@ import { GhostChipPanelBody, GhostPanelError } from './ghostPanelBody';
import { ghostInstallErrorKey } from './installErrorKey';
import { pruneGhostSettingsSnapshots } from './ghostSettingsSnapshot';
import { useGhostRuntimeState } from './runtimeStates';
+import { getDataOwnerGeneration } from '../contexts/dataOwnerGeneration';
/**
* 意识面板接入布局引擎。
@@ -173,7 +174,10 @@ export function syncGhostPanelRegistrations(ghosts: InstalledGhost[]): void {
// 顺手清设置区快照缓存的孤儿(卸载的意识不该在 localStorage 留位图);
// 本函数是"已装清单"的唯一同步点(启动 + ghosts:changed),挂这里最省。
// 注意用全量清单(含沉睡)——沉睡只是不注册面板,快照仍然有效。
- pruneGhostSettingsSnapshots(ghosts.map((g) => g.manifest.id));
+ pruneGhostSettingsSnapshots(
+ getDataOwnerGeneration().dataOwnerId,
+ ghosts.map((g) => g.manifest.id),
+ );
// 气泡状态对齐(与快照 prune 不同:停用/失格的要强制还原,不只清卸载)——
// 气泡是"面板不可见 + 唯一恢复入口",失格后必须回停靠,不留死角。
reconcileGhostPanelBubbles(ghosts);
diff --git a/apps/desktop/src/renderer/cindy-brain/ghostSettingsSnapshot.ts b/apps/desktop/src/renderer/cindy-brain/ghostSettingsSnapshot.ts
index 25133e454c..915edf1a91 100644
--- a/apps/desktop/src/renderer/cindy-brain/ghostSettingsSnapshot.ts
+++ b/apps/desktop/src/renderer/cindy-brain/ghostSettingsSnapshot.ts
@@ -42,7 +42,8 @@ export interface GhostSettingsSnapshotContext {
dpr: number;
}
-const STORAGE_PREFIX = 'ghostSettings.snapshot.';
+// v1 只有 ghostId,无法证明快照属于哪个 owner;保留但永不读取/迁移。
+const STORAGE_PREFIX = 'ghostSettings.snapshot.v2.';
/** 宿主设置 guest 的布局契约版本;布局注入改变时递增以主动淘汰旧快照。 */
export const GHOST_SETTINGS_LAYOUT_REVISION = 3;
@@ -86,27 +87,50 @@ function isValidSnapshot(value: unknown): value is GhostSettingsSnapshot {
);
}
+function snapshotKey(dataOwnerId: string, ghostId: string): string {
+ return `${encodeURIComponent(dataOwnerId)}:${ghostId}`;
+}
+
+function parseSnapshotKey(key: string): { dataOwnerId: string; ghostId: string } | null {
+ const separator = key.lastIndexOf(':');
+ if (separator <= 0 || separator === key.length - 1) return null;
+ try {
+ const dataOwnerId = decodeURIComponent(key.slice(0, separator));
+ const ghostId = key.slice(separator + 1);
+ if (!dataOwnerId || !ghostId) return null;
+ return { dataOwnerId, ghostId };
+ } catch {
+ return null;
+ }
+}
+
/** 静默删一条持久化快照(localStorage 不可用时忽略)。 */
-function removePersisted(ghostId: string): void {
+function removePersisted(dataOwnerId: string, ghostId: string): void {
+ const key = snapshotKey(dataOwnerId, ghostId);
try {
- localStorage.removeItem(STORAGE_PREFIX + ghostId);
+ localStorage.removeItem(STORAGE_PREFIX + key);
} catch {
// ignore
}
}
/** 读取某意识的存量快照(内存 → localStorage;损坏/缺失/过期返回 null)。 */
-export function loadGhostSettingsSnapshot(ghostId: string): GhostSettingsSnapshot | null {
- const cached = memoryCache.get(ghostId);
+export function loadGhostSettingsSnapshot(
+ dataOwnerId: string | null,
+ ghostId: string,
+): GhostSettingsSnapshot | null {
+ if (!dataOwnerId) return null;
+ const key = snapshotKey(dataOwnerId, ghostId);
+ const cached = memoryCache.get(key);
if (cached !== undefined) return cached;
let snapshot: GhostSettingsSnapshot | null = null;
try {
- const raw = localStorage.getItem(STORAGE_PREFIX + ghostId);
+ const raw = localStorage.getItem(STORAGE_PREFIX + key);
if (raw) {
const parsed: unknown = JSON.parse(raw);
if (isValidSnapshot(parsed)) {
if (Date.now() - parsed.capturedAt > SNAPSHOT_TTL_MS) {
- removePersisted(ghostId);
+ removePersisted(dataOwnerId, ghostId);
} else {
snapshot = parsed;
}
@@ -115,12 +139,14 @@ export function loadGhostSettingsSnapshot(ghostId: string): GhostSettingsSnapsho
} catch {
// localStorage 不可用或 JSON 损坏:视同没有快照,走老的淡入路径。
}
- memoryCache.set(ghostId, snapshot);
+ memoryCache.set(key, snapshot);
return snapshot;
}
-/** 遍历所有持久化快照键,回调收到意识 id 与原始串(解析失败的键直接跳过)。 */
-function forEachPersisted(fn: (ghostId: string, raw: string) => void): void {
+/** 遍历所有新版持久快照键;旧的无 owner 快照不会进入回调。 */
+function forEachPersisted(
+ fn: (identity: { key: string; dataOwnerId: string; ghostId: string }, raw: string) => void,
+): void {
try {
const keys: string[] = [];
for (let i = 0; i < localStorage.length; i++) {
@@ -129,7 +155,9 @@ function forEachPersisted(fn: (ghostId: string, raw: string) => void): void {
}
for (const key of keys) {
const raw = localStorage.getItem(key);
- if (raw !== null) fn(key.slice(STORAGE_PREFIX.length), raw);
+ const scopedKey = key.slice(STORAGE_PREFIX.length);
+ const identity = parseSnapshotKey(scopedKey);
+ if (raw !== null && identity) fn({ key: scopedKey, ...identity }, raw);
}
} catch {
// localStorage 不可用:静默(持久化本就是 best-effort)。
@@ -140,19 +168,25 @@ function forEachPersisted(fn: (ghostId: string, raw: string) => void): void {
* 存快照(内存必存;持久化 best-effort):单条超限只留内存;写入前按
* capturedAt 淘汰最旧的其它快照直到总量回到预算内;写失败静默降级仅内存。
*/
-export function saveGhostSettingsSnapshot(ghostId: string, snapshot: GhostSettingsSnapshot): void {
- memoryCache.set(ghostId, snapshot);
+export function saveGhostSettingsSnapshot(
+ dataOwnerId: string | null,
+ ghostId: string,
+ snapshot: GhostSettingsSnapshot,
+): void {
+ if (!dataOwnerId) return;
+ const key = snapshotKey(dataOwnerId, ghostId);
+ memoryCache.set(key, snapshot);
if (snapshot.dataUrl.length > MAX_PERSIST_CHARS) {
// 单条超限只留内存;同 id 更早的持久快照顺手清掉——它已确认过时,
// 重启后贴一张旧画面不如诚实走淡入。
- removePersisted(ghostId);
+ removePersisted(dataOwnerId, ghostId);
return;
}
const serialized = JSON.stringify(snapshot);
// 总量预算:收集其它快照的体积与拍摄时间,超预算从最旧开始腾位。
const others: Array<{ id: string; size: number; capturedAt: number }> = [];
- forEachPersisted((id, raw) => {
- if (id === ghostId) return;
+ forEachPersisted((identity, raw) => {
+ if (identity.key === key) return;
let capturedAt = 0;
try {
const parsed: unknown = JSON.parse(raw);
@@ -160,20 +194,21 @@ export function saveGhostSettingsSnapshot(ghostId: string, snapshot: GhostSettin
} catch {
// 坏数据当最旧(capturedAt 0),优先被淘汰。
}
- others.push({ id, size: raw.length, capturedAt });
+ others.push({ id: identity.key, size: raw.length, capturedAt });
});
let total = serialized.length + others.reduce((sum, o) => sum + o.size, 0);
if (total > TOTAL_PERSIST_BUDGET_CHARS) {
others.sort((a, b) => a.capturedAt - b.capturedAt);
for (const victim of others) {
if (total <= TOTAL_PERSIST_BUDGET_CHARS) break;
- removePersisted(victim.id);
+ const identity = parseSnapshotKey(victim.id);
+ if (identity) removePersisted(identity.dataOwnerId, identity.ghostId);
memoryCache.delete(victim.id);
total -= victim.size;
}
}
try {
- localStorage.setItem(STORAGE_PREFIX + ghostId, serialized);
+ localStorage.setItem(STORAGE_PREFIX + key, serialized);
} catch {
// 配额满等写失败:内存缓存仍生效(本会话内复用),不影响功能。
}
@@ -183,18 +218,28 @@ export function saveGhostSettingsSnapshot(ghostId: string, snapshot: GhostSettin
* 按"当前已装意识清单"清理孤儿快照(卸载后的快照没有存在理由)。
* 由意识清单同步点(启动 + ghosts:changed)顺手调用,幂等。
*/
-export function pruneGhostSettingsSnapshots(installedGhostIds: Iterable<string>): void {
+export function pruneGhostSettingsSnapshots(
+ dataOwnerId: string | null,
+ installedGhostIds: Iterable<string>,
+): void {
+ if (!dataOwnerId) return;
const keep = new Set(installedGhostIds);
const orphanIds: string[] = [];
- forEachPersisted((id) => {
- if (!keep.has(id)) orphanIds.push(id);
+ forEachPersisted((identity) => {
+ if (identity.dataOwnerId === dataOwnerId && !keep.has(identity.ghostId)) {
+ orphanIds.push(identity.ghostId);
+ }
});
for (const id of orphanIds) {
- removePersisted(id);
- memoryCache.delete(id);
+ removePersisted(dataOwnerId, id);
+ const key = snapshotKey(dataOwnerId, id);
+ memoryCache.delete(key);
}
- for (const id of [...memoryCache.keys()]) {
- if (!keep.has(id)) memoryCache.delete(id);
+ for (const key of [...memoryCache.keys()]) {
+ const identity = parseSnapshotKey(key);
+ if (identity?.dataOwnerId === dataOwnerId && !keep.has(identity.ghostId)) {
+ memoryCache.delete(key);
+ }
}
}
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 3f90df1d01..814d881041 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -56,16 +56,17 @@ export const GHOST_SCHEME = 'cindy-ghost';
/**
* 意识沙箱的 session 分区前缀。无 `persist:` 前缀 = 纯内存分区,熄灯即蒸发。
- * 面板 webview 与离屏沙箱窗口共用同一分区规则(同一意识 = 同一间房)。
+ * Renderer 只用它声明待附加的意识 id;Main 验明当前 owner 后会覆盖成真正的
+ * owner-scoped partition,不能把这里的 claim 当成最终 Electron session 边界。
*/
export const GHOST_PARTITION_PREFIX = 'cindy-ghost-';
-/** 某段意识的 session 分区名。 */
+/** Renderer 的意识 WebView attach claim;Main 放行前会覆盖成 owner 分区。 */
export function ghostPartition(id: string): string {
return `${GHOST_PARTITION_PREFIX}${id}`;
}
-/** 从分区名解析意识 id;不是意识分区(或 id 非法)返回 null。 */
+/** 从 Renderer claim 解析意识 id;不是合法 claim 返回 null。 */
export function parseGhostPartition(partition: unknown): string | null {
if (typeof partition !== 'string' || !partition.startsWith(GHOST_PARTITION_PREFIX)) return null;
const id = partition.slice(GHOST_PARTITION_PREFIX.length);