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(remote-management): 修复操作收尾与提交边界并同步主干

nana629ec15b8a30
diff --cc apps/desktop/src/main/bootstrap-electron.ts
index 0788638d8a,af62289111..192923c4da
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@@ -2466,21 -2470,6 +2473,21 @@@ setCodexImageAuthBinding(
getAuth: getChatgptBridgeAuth,
onAuthFailure: invalidateChatgptBridgeAuth,
});
+setRemotePluginManagementServices({
+ isRelayOnline: () => getDeviceLinkStatus() === 'online',
+ listProjects: listRecentWorkdirs,
+ sidebar: {
+ read: id => !loadSidebarSettingsSnapshot().hiddenMainViewGhostIds.includes(id),
+ write: async (id, visible, assertCurrent) => { await setLocalMainViewHidden(id, !visible, assertCurrent); },
+ },
+ market: {
+ snapshot: () => getPluginMarketService().snapshot({ discoveryOnly: true }),
+ detail: id => getPluginMarketService().detail(id),
- install: async (id, options, prompt, assertCurrent) => {
- await getPluginMarketService().install(id, options, { consent: { prompt, initiator: 'user' }, assertCurrent });
++ install: async (id, options, prompt, assertCurrent, assertScope) => {
++ await getPluginMarketService().install(id, options, { consent: { prompt, initiator: 'user' }, assertCurrent, assertScope });
+ },
+ },
+});
registerGhostIpc();
registerPluginMarketIpc();
registerPluginPublisherIpc();
diff --cc apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
index 63caa98e85,63caa98e85..b7813b92ff
--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
@@@ -96,6 -96,6 +96,7 @@@ describe('market Ghost session boundary
expect(serverCommitBody).not.toContain('requireSameMarketOwner(');
});
++
it('requires the pre-approval session generation when acquiring the mutation lease', () => {
const captureStart = source.indexOf(
'function captureGhostMutationOwner(): ActiveAppSession {',
@@@ -288,8 -288,8 +289,16 @@@
body.indexOf('const runtime = getGhostRuntime();'),
);
-- expect(initialBranch).toContain('beforePackagePlacement: expected.beforeCommitInLock,');
-- expect(body.match(/expected\.beforeCommitInLock\?\.\(\);/g)).toHaveLength(1);
++ // plugin-security-and-authoring §3: check cancellation at the actual transaction hooks.
++ const placement = initialBranch.indexOf('beforePackagePlacement: () => {');
++ expect(placement).toBeGreaterThan(-1);
++ const placementHook = initialBranch.slice(placement, initialBranch.indexOf('},', placement));
++ expect(placementHook).toContain('expected.assertCurrent?.();');
++ expect(placementHook).toContain('expected.beforeCommitInLock?.();');
++ expect(body.match(/expected\.beforeCommitInLock\?\.\(\);/g)).toHaveLength(2);
++ const commit = body.indexOf('beforePackageCommit: () => {');
++ expect(commit).toBeGreaterThan(-1);
++ expect(body.slice(commit, body.indexOf('},', commit))).toContain('expected.assertCurrent?.();');
const waitIndex = body.indexOf(
'await getGhostNodeRuntimeBroker().stopAndWait(',
diff --cc apps/desktop/src/main/cindy-brain/__tests__/remotePluginManagement.test.ts
index 7aab1918bb,0000000000..b01d6e3e6d
mode 100644,000000..100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginManagement.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginManagement.test.ts
@@@ -1,571 -1,0 +1,631 @@@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { RemotePluginManagement, type RemotePluginManagementDeps } from '../remotePluginManagement';
+import { ghostInstallApprovalToken, type InstalledGhost } from '../../../shared/ghost';
+import { installedGhostStoragePart } from '../../../shared/pluginIdentity';
+import type { PluginManagementReceipt } from '../../../shared/pluginManagement';
+
+function fixture() {
+ let owner = 'owner-a',
+ epoch = 0;
+ const revoked = new Set<string>();
+ const ghosts: InstalledGhost[] = [null, 'org-acme'].map((namespace) => ({
+ manifest: {
+ schemaVersion: 3,
+ minCindyVersion: '0.1.61',
+ id: 'weather',
+ name: 'Weather',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ },
+ dir: namespace ? '/test/_ns/org-acme/weather' : '/test/weather',
+ namespace,
+ enabled: true,
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ }));
+ const deps: RemotePluginManagementDeps = {
+ list: () => ghosts,
+ capture: (peer) => {
+ const start = owner,
+ generation = epoch;
+ return () => owner === start && generation === epoch && !revoked.has(peer);
+ },
+ captureReceipt: (peer) => {
+ const start = owner;
+ return () => owner === start && !revoked.has(peer);
+ },
+ market: {
+ snapshot: vi.fn(async () => ({
+ items: [],
+ unavailableReason: null,
+ customSourceNames: [],
+ unavailableCustomSourceNames: [],
+ })),
+ detail: vi.fn(async () => ({}) as never),
+ install: vi.fn(async () => {}),
+ },
+ setEnabled: vi.fn(async (id, enabled, _approval, current) => {
+ current();
+ ghosts.find((g) => installedGhostStoragePart(g) === id)!.enabled = enabled;
+ }),
+ uninstall: vi.fn(async (id, _approval, current) => {
+ current();
+ ghosts.splice(
+ ghosts.findIndex((g) => installedGhostStoragePart(g) === id),
+ 1,
+ );
+ }),
+ };
+ const service = new RemotePluginManagement(deps);
+ const invoke = async (
+ action: string,
+ input: Record<string, unknown>,
+ peer = 'desktop-a',
+ target?: string,
+ ) =>
+ (
+ await service.invoke(peer, {
+ collectionId: 'plugins',
+ actionId: `management:${action}`,
+ input,
+ client: { protocolVersion: 1, primitives: ['action'] },
+ ...(target ? { resourceRef: { collectionId: 'plugins', kind: 'plugin', id: target } } : {}),
+ })
+ ).result as PluginManagementReceipt;
+ const begin = (kind: string, id: string, index = 0, peer?: string) =>
+ invoke(
+ 'begin',
+ {
+ operationId: id,
+ kind,
+ expectedInstalledApproval: ghostInstallApprovalToken(ghosts[index].approval),
+ },
+ peer,
+ installedGhostStoragePart(ghosts[index]),
+ );
+ return {
+ deps,
+ service,
+ ghosts,
+ invoke,
+ begin,
+ revoke: (peer: string) => revoked.add(peer),
+ disconnect: () => epoch++,
+ switchOwner: () => {
+ owner = 'owner-b';
+ },
+ };
+}
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+});
+const flush = async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+};
+describe('remote plugin management receipt boundaries', () => {
+ it('binds preference reads and writes to the physical instance, approval and live controller', async () => {
+ const f = fixture();
+ const read = vi.fn(() => ({ revision: 'a'.repeat(64), configurationRefs: [] }));
+ const update = vi.fn(
+ async (
+ _id: string,
+ _ghost: InstalledGhost,
+ _input: Record<string, unknown>,
+ current: () => void,
+ ) => {
+ current();
+ return read();
+ },
+ );
+ f.deps.preferences = { read, update } as never;
+ const input = { expectedInstalledApproval: ghostInstallApprovalToken(f.ghosts[1].approval) };
+ const target = installedGhostStoragePart(f.ghosts[1]);
+ await f.invoke('preferences', input, 'desktop-a', target);
+ expect(read).toHaveBeenCalledWith(target, f.ghosts[1]);
+ await f.invoke(
+ 'preferences-set',
+ { ...input, expectedRevision: 'a'.repeat(64), kind: 'sidebar', visible: true },
+ 'desktop-a',
+ target,
+ );
+ expect(update.mock.calls[0][0]).toBe(target);
+ f.ghosts[1].approval = { state: 'approved', revision: '00000000-0000-4000-8000-000000000002' };
+ await expect(f.invoke('preferences-set', input, 'desktop-a', target)).rejects.toThrow();
+ f.revoke('desktop-a');
+ await expect(
+ f.invoke(
+ 'preferences',
+ { expectedInstalledApproval: ghostInstallApprovalToken(f.ghosts[0].approval) },
+ 'desktop-a',
+ installedGhostStoragePart(f.ghosts[0]),
+ ),
+ ).rejects.toThrow();
+ expect(update).toHaveBeenCalledOnce();
+ });
+ function projectsFixture() {
+ const f = fixture();
+ const projects = [
+ { id: 'project-a', name: 'Cindy', path: '/host/project-a', workdir: '/host/project-a' },
+ { id: 'project-b', name: 'Cindy', workdir: 'C:\\host\\project-b' },
+ ];
+ const disabled = new Map<string, string[]>();
+ f.deps.projects = {
+ list: vi.fn(async () => projects),
+ disabled: (workdir) => disabled.get(workdir) ?? [],
+ setDisabled: vi.fn((workdir, id, value, current) => {
+ current();
+ const next = new Set(disabled.get(workdir));
+ if (value) next.add(id);
+ else next.delete(id);
+ disabled.set(workdir, [...next]);
+ }),
+ };
+ const read = (projectId = 'project-a') =>
+ f.invoke('project-state', { projectId }) as unknown as Promise<{
+ projectId: string;
+ revision: string;
+ disabled: string[];
+ }>;
+ const toggle = async (
+ operationId: string,
+ kind: string,
+ state: Awaited<ReturnType<typeof read>>,
+ index = 0,
+ peer?: string,
+ ) =>
+ f.invoke(
+ 'begin',
+ {
+ operationId,
+ kind,
+ projectId: state.projectId,
+ expectedProjectRevision: state.revision,
+ expectedInstalledApproval: ghostInstallApprovalToken(f.ghosts[index].approval),
+ },
+ peer,
+ installedGhostStoragePart(f.ghosts[index]),
+ );
+ return { ...f, projects, disabled, read, toggle };
+ }
+ it('projects Host-issued identities and read-only display paths without exposing internal records', async () => {
+ const f = projectsFixture();
+ const value = (await f.invoke('snapshot', {})) as unknown as { projects: unknown[] };
+ expect(value.projects).toEqual([
+ { id: 'project-a', name: 'Cindy', path: '/host/project-a' },
+ { id: 'project-b', name: 'Cindy' },
+ ]);
+ expect(value.projects[0]).not.toHaveProperty('workdir');
+ const old = await fixture().invoke('snapshot', {});
+ expect(old).not.toHaveProperty('projects');
+ });
+ it('resolves a browsed target directory once as a scope, then uses only its Host id for project writes', async () => {
+ const f = projectsFixture();
- const browsed = { id: 'browsed', name: 'Other', path: '/target/other', workdir: '/target/other' };
++ const browsed = {
++ id: 'browsed',
++ name: 'Other',
++ path: '/target/other',
++ workdir: '/target/other',
++ };
+ f.deps.projects!.resolve = vi.fn(async () => browsed);
+ expect(await f.invoke('snapshot', {})).toHaveProperty('projectBrowse', true);
- expect(await f.invoke('project-select', { path: browsed.path })).toEqual({ id: 'browsed', name: 'Other', path: browsed.path });
++ expect(await f.invoke('project-select', { path: browsed.path })).toEqual({
++ id: 'browsed',
++ name: 'Other',
++ path: browsed.path,
++ });
+ expect(f.deps.projects!.resolve).toHaveBeenCalledWith(browsed.path);
+ expect(f.projects).toHaveLength(2); // Browsing must not create a task or persist a recent project.
- await expect(f.invoke('project-state', { projectId: browsed.id }, 'desktop-b')).rejects.toThrow();
++ await expect(
++ f.invoke('project-state', { projectId: browsed.id }, 'desktop-b'),
++ ).rejects.toThrow();
+ await expect(f.read(browsed.path)).rejects.toThrow();
+ await f.toggle('browsed-disable', 'disable', await f.read(browsed.id));
+ await flush();
+ expect(f.disabled.get(browsed.workdir)).toEqual(['weather']);
+ expect(f.ghosts[0].enabled).toBe(true);
+ expect(f.deps.setEnabled).not.toHaveBeenCalled();
- f.deps.projects!.resolve = vi.fn(async () => { throw new Error('directory removed'); });
++ f.deps.projects!.resolve = vi.fn(async () => {
++ throw new Error('directory removed');
++ });
+ await expect(f.read(browsed.id)).rejects.toThrow('directory removed');
+ f.switchOwner();
- expect((await f.invoke('snapshot', {})) as unknown as { projects: unknown[] }).toHaveProperty('projects', [
- { id: 'project-a', name: 'Cindy', path: '/host/project-a' },
- { id: 'project-b', name: 'Cindy' },
- ]);
++ expect((await f.invoke('snapshot', {})) as unknown as { projects: unknown[] }).toHaveProperty(
++ 'projects',
++ [
++ { id: 'project-a', name: 'Cindy', path: '/host/project-a' },
++ { id: 'project-b', name: 'Cindy' },
++ ],
++ );
+ await expect(f.read(browsed.id)).rejects.toThrow();
+ });
+ it('rejects unsupported browsing and late directory resolutions after owner or connection changes', async () => {
+ const old = projectsFixture();
+ await expect(old.invoke('project-select', { path: '/target/project' })).rejects.toThrow();
+ for (const transition of ['switchOwner', 'disconnect'] as const) {
+ const f = projectsFixture();
+ let resolve!: (value: { id: string; name: string; workdir: string }) => void;
- f.deps.projects!.resolve = vi.fn(() => new Promise<{ id: string; name: string; workdir: string }>(done => { resolve = done; }));
++ f.deps.projects!.resolve = vi.fn(
++ () =>
++ new Promise<{ id: string; name: string; workdir: string }>((done) => {
++ resolve = done;
++ }),
++ );
+ const request = f.invoke('project-select', { path: '/target/project' });
+ f[transition]();
+ resolve({ id: 'late', name: 'Late', workdir: '/target/project' });
+ await expect(request).rejects.toThrow();
+ await expect(f.read('late')).rejects.toThrow();
+ }
+ });
+ it('writes only the selected project and physical namespace, preserving global and other project switches', async () => {
+ const f = projectsFixture();
+ await f.toggle('project-disable', 'disable', await f.read(), 1);
+ await flush();
+ expect(f.ghosts.map((ghost) => ghost.enabled)).toEqual([true, true]);
+ expect((await f.read()).disabled).toEqual([installedGhostStoragePart(f.ghosts[1])]);
+ expect((await f.read('project-b')).disabled).toEqual([]);
+ expect(f.deps.setEnabled).not.toHaveBeenCalled();
+ await f.toggle('project-enable', 'enable', await f.read(), 1);
+ await flush();
+ expect((await f.read()).disabled).toEqual([]);
+ });
+ it('rejects stale project revision from another controller instead of overwriting exceptions', async () => {
+ const f = projectsFixture();
+ const state = await f.read();
+ await f.toggle('controller-a', 'disable', state, 0);
+ await f.toggle('controller-b', 'disable', state, 1, 'desktop-b');
+ await flush();
+ expect((await f.invoke('operation', { operationId: 'controller-b' }, 'desktop-b')).phase).toBe(
+ 'failed',
+ );
+ expect((await f.read()).disabled).toEqual([installedGhostStoragePart(f.ghosts[0])]);
+ expect(f.deps.projects!.setDisabled).toHaveBeenCalledTimes(1);
+ });
+ it('rejects removed projects, arbitrary paths, malformed scope and scoped installation', async () => {
+ const f = projectsFixture();
+ const state = await f.read();
+ f.projects.splice(0, 1);
+ await f.toggle('removed', 'disable', state);
+ await flush();
+ expect((await f.invoke('operation', { operationId: 'removed' })).phase).toBe('failed');
+ await expect(f.read('/controller/local-project')).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ await expect(
+ f.invoke('begin', { operationId: 'bad', kind: 'disable', projectId: 'project-b' }),
+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ await expect(
+ f.invoke('begin', {
+ operationId: 'install-scope',
+ kind: 'install',
+ projectId: 'project-b',
+ expectedProjectRevision: state.revision,
+ }),
+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ expect(f.deps.projects!.setDisabled).not.toHaveBeenCalled();
+ });
+ it('cannot enable a globally disabled plugin through project settings', async () => {
+ const f = projectsFixture();
+ const state = await f.read();
+ f.ghosts[0].enabled = false;
+ await f.toggle('global-off', 'enable', state);
+ await flush();
+ expect((await f.invoke('operation', { operationId: 'global-off' })).phase).toBe('failed');
+ expect(f.deps.projects!.setDisabled).not.toHaveBeenCalled();
+ expect(f.ghosts[0].enabled).toBe(false);
+ });
+ it.each(['disconnect', 'revoke', 'owner', 'approval'])(
+ 'invalidates pending project mutation on %s',
+ async (change) => {
+ const f = projectsFixture();
+ const state = await f.read();
+ let resolve!: (value: typeof f.projects) => void;
+ f.deps.projects!.list = vi.fn<() => Promise<typeof f.projects>>(
+ () =>
+ new Promise<typeof f.projects>((done) => {
+ resolve = done;
+ }),
+ );
+ await f.toggle('late-project', 'disable', state);
+ if (change === 'disconnect') f.disconnect();
+ if (change === 'revoke') f.revoke('desktop-a');
+ if (change === 'owner') f.switchOwner();
+ if (change === 'approval')
+ f.ghosts[0].approval = {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000002',
+ };
+ resolve(f.projects);
+ await flush();
+ expect(f.deps.projects!.setDisabled).not.toHaveBeenCalled();
+ },
+ );
+ it('uses physical identity for same-name plugins and does not alter the other namespace', async () => {
+ const f = fixture();
+ await f.begin('disable', 'one', 1);
+ await flush();
+ expect(f.ghosts.map((g) => g.enabled)).toEqual([true, false]);
+ expect((await f.invoke('operation', { operationId: 'one' })).phase).toBe('succeeded');
+ await expect(f.invoke('operation', { operationId: 'one' }, 'desktop-b')).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ });
+ it('rejects stale approval before any mutation', async () => {
+ const f = fixture();
+ await expect(
+ f.invoke(
+ 'begin',
+ {
+ operationId: 'stale',
+ kind: 'uninstall',
+ expectedInstalledApproval: 'approved:00000000-0000-4000-8000-000000000002',
+ },
+ undefined,
+ installedGhostStoragePart(f.ghosts[0]),
+ ),
+ ).rejects.toBeTruthy();
+ expect(f.deps.uninstall).not.toHaveBeenCalled();
+ });
+ it('repeated begin returns its receipt after uninstall without executing again', async () => {
+ const f = fixture();
+ const target = installedGhostStoragePart(f.ghosts[0]);
+ const input = {
+ operationId: 'delete',
+ kind: 'uninstall',
+ expectedInstalledApproval: ghostInstallApprovalToken(f.ghosts[0].approval),
+ };
+ await f.invoke('begin', input, undefined, target);
+ await flush();
+ expect((await f.invoke('begin', input, undefined, target)).phase).toBe('succeeded');
+ expect(f.deps.uninstall).toHaveBeenCalledTimes(1);
+ });
+ it('keeps a committed receipt across reconnect but invalidates it on owner change or revocation', async () => {
+ const f = fixture();
+ await f.begin('disable', 'done');
+ await flush();
+ f.disconnect();
+ expect((await f.invoke('operation', { operationId: 'done' })).phase).toBe('succeeded');
+ f.revoke('desktop-a');
+ await expect(f.invoke('operation', { operationId: 'done' })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ const g = fixture();
+ await g.begin('enable', 'old');
+ await flush();
+ g.switchOwner();
+ await expect(g.invoke('operation', { operationId: 'old' })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ });
+ it('queries unknown results instead of replaying installation', async () => {
+ const f = fixture();
+ let finish!: () => void;
+ f.deps.market.install = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ await f.invoke('begin', {
+ operationId: 'install',
+ kind: 'install',
+ pluginId: 'market-weather',
+ expectedReleaseId: 'r1',
+ });
+ expect((await f.invoke('operation', { operationId: 'install' })).phase).toBe('running');
+ f.disconnect();
+ finish();
+ await flush();
+ expect((await f.invoke('operation', { operationId: 'install' })).phase).toBe('succeeded');
+ expect(f.deps.market.install).toHaveBeenCalledTimes(1);
+ });
+ it('binds actual package confirmation to its controller and refuses replacement after confirmation', async () => {
+ const f = fixture();
+ let committed = false;
+ f.deps.market.install = vi.fn(async (_id, _options, prompt, current) => {
+ const accepted = await prompt({
+ initiator: 'user',
+ origin: 'market',
+ facts: { kind: 'install', name: 'Weather', version: '2.0.0', permissions: [] },
+ });
+ if (!accepted) throw { code: 'MUTATION_CANCELLED' };
+ current();
+ committed = true;
+ });
+ const input = {
+ operationId: 'update',
+ kind: 'install',
+ pluginId: 'weather-market',
+ expectedReleaseId: 'r2',
+ expectedInstalledApproval: ghostInstallApprovalToken(f.ghosts[0].approval),
+ };
+ await f.invoke('begin', input, undefined, installedGhostStoragePart(f.ghosts[0]));
+ const receipt = await f.invoke('operation', { operationId: 'update' });
+ expect(receipt.phase).toBe('confirmation');
+ await expect(
+ f.invoke(
+ 'answer',
+ { operationId: 'update', requestId: receipt.consent!.requestId, confirmed: true },
+ 'desktop-b',
+ ),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ f.ghosts[0].approval = { state: 'approved', revision: '00000000-0000-4000-8000-000000000002' };
+ await f.invoke('answer', {
+ operationId: 'update',
+ requestId: receipt.consent!.requestId,
+ confirmed: true,
+ });
+ await flush();
+ expect(committed).toBe(false);
+ expect((await f.invoke('operation', { operationId: 'update' })).phase).toBe('failed');
+ });
+ it('routes a transferred file to the original peer and physical instance without treating it as a host path', async () => {
+ const f = fixture();
+ f.deps.installFile = vi.fn(async (_peer, _attachment, _target, _approval, _prompt, current) => {
+ current();
+ });
+ const target = installedGhostStoragePart(f.ghosts[0]);
+ const token = ghostInstallApprovalToken(f.ghosts[0].approval);
+ await f.invoke(
+ 'begin',
+ {
+ operationId: 'file',
+ kind: 'install-file',
+ attachment: 'attachment:fixture',
+ expectedInstalledApproval: token,
+ },
+ 'desktop-a',
+ target,
+ );
+ await flush();
+ expect(f.deps.installFile).toHaveBeenCalledExactlyOnceWith(
+ 'desktop-a',
+ 'attachment:fixture',
+ target,
+ token,
+ expect.any(Function),
+ expect.any(Function),
+ );
+ expect((await f.invoke('operation', { operationId: 'file' })).phase).toBe('succeeded');
+ });
+
+ it('keeps file-update authorization valid while the installer swaps the approved package', async () => {
+ const f = fixture();
+ const token = ghostInstallApprovalToken(f.ghosts[0].approval);
+ f.deps.installFile = vi.fn(
+ async (_peer, _attachment, _target, expectedApproval, _prompt, current) => {
+ // The installer checks this token in its mutation lock, then stages the new
+ // directory before beforePackageCommit. The old receipt no longer describes it.
+ expect(expectedApproval).toBe(token);
+ current();
+ f.ghosts[0].manifest.version = '1.0.1';
+ f.ghosts[0].approval = { state: 'invalid' };
+ current();
+ f.ghosts[0].approval = {
+ state: 'approved',
+ revision: '00000000-0000-4000-8000-000000000002',
+ };
+ },
+ );
+ await f.invoke(
+ 'begin',
+ {
+ operationId: 'file-update',
+ kind: 'install-file',
+ attachment: 'attachment:fixture',
+ expectedInstalledApproval: token,
+ },
+ 'desktop-a',
+ installedGhostStoragePart(f.ghosts[0]),
+ );
+ await flush();
+ expect((await f.invoke('operation', { operationId: 'file-update' })).phase).toBe('succeeded');
+ expect(f.ghosts[0].manifest.version).toBe('1.0.1');
+ });
+
+ it.each(['disconnect', 'revoke', 'owner', 'cancel'])(
+ 'still rejects file-update commit after %s',
+ async (change) => {
+ const f = fixture();
+ let resume!: () => void;
+ let committed = false;
+ const gate = new Promise<void>((resolve) => {
+ resume = resolve;
+ });
+ f.deps.installFile = vi.fn(
+ async (_peer, _attachment, _target, _approval, _prompt, current) => {
+ await gate;
+ current();
+ committed = true;
+ },
+ );
+ await f.invoke(
+ 'begin',
+ {
+ operationId: 'file-update',
+ kind: 'install-file',
+ attachment: 'attachment:fixture',
+ expectedInstalledApproval: ghostInstallApprovalToken(f.ghosts[0].approval),
+ },
+ 'desktop-a',
+ installedGhostStoragePart(f.ghosts[0]),
+ );
+ if (change === 'disconnect') f.disconnect();
+ if (change === 'revoke') f.revoke('desktop-a');
+ if (change === 'owner') f.switchOwner();
+ if (change === 'cancel') await f.invoke('cancel', { operationId: 'file-update' });
+ resume();
+ await flush();
+ expect(committed).toBe(false);
+ },
+ );
+
++ it.each(['disconnect', 'revoke', 'owner', 'cancel', 'package-swap'])(
++ 'checks market-install scope at the late commit after %s',
++ async (change) => {
++ const f = fixture();
++ let resume!: () => void;
++ const gate = new Promise<void>((resolve) => {
++ resume = resolve;
++ });
++ let committed = false;
++ f.deps.market.install = vi.fn(async (_id, _options, _prompt, current, scope) => {
++ current();
++ await gate;
++ scope();
++ committed = true;
++ });
++ await f.invoke(
++ 'begin',
++ {
++ operationId: 'market-update',
++ kind: 'install',
++ pluginId: 'market-plugin',
++ expectedReleaseId: 'release',
++ expectedInstalledApproval: ghostInstallApprovalToken(f.ghosts[0].approval),
++ },
++ 'desktop-a',
++ installedGhostStoragePart(f.ghosts[0]),
++ );
++ if (change === 'disconnect') f.disconnect();
++ if (change === 'revoke') f.revoke('desktop-a');
++ if (change === 'owner') f.switchOwner();
++ if (change === 'cancel') await f.invoke('cancel', { operationId: 'market-update' });
++ if (change === 'package-swap') f.ghosts[0].approval = { state: 'invalid' };
++ resume();
++ await flush();
++ expect(committed).toBe(change === 'package-swap');
++ },
++ );
+ it('rejects the superseded task-card configuration action', async () => {
+ const f = fixture();
- await expect(f.begin('configure', 'configure')).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
++ await expect(f.begin('configure', 'configure')).rejects.toMatchObject({
++ code: 'INVALID_PARAMS',
++ });
+ });
+ it('revokes an offline prompt while retaining a queryable cancelled receipt', async () => {
+ const f = fixture();
+ f.deps.market.install = vi.fn(async (_id, _opts, prompt) => {
+ if (
+ !(await prompt({
+ initiator: 'user',
+ origin: 'market',
+ facts: { kind: 'install', name: 'Weather', version: '2', permissions: [] },
+ }))
+ )
+ throw { code: 'MUTATION_CANCELLED' };
+ });
+ await f.invoke('begin', {
+ operationId: 'pending',
+ kind: 'install',
+ pluginId: 'm',
+ expectedReleaseId: 'r',
+ });
+ f.disconnect();
+ f.service.invalidate();
+ await flush();
+ expect((await f.invoke('operation', { operationId: 'pending' })).phase).toBe('cancelled');
+ });
+});
diff --cc apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts
index e23bf646e9,0000000000..9eb376c8e4
mode 100644,000000..100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts
@@@ -1,427 -1,0 +1,456 @@@
+import { EventEmitter } from 'node:events';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { WebContents } from 'electron';
+import { PLUGIN_OAUTH_CHANNEL, REMOTE_RESOURCE_INVOKE_CHANNEL } from '@cindy/device-link';
+import { MobilePluginPages } from '../mobilePageService.js';
+import { AuthenticatedOauthHost, OauthHostIdentity } from '../../plugin-oauth/authentication.js';
+import { getRemoteOauthContext, withRemoteOauthContext } from '../../plugin-oauth/context.js';
+import { ghostInstallApprovalToken, type InstalledGhost } from '../../../shared/ghost.js';
+
+const mock = vi.hoisted(() => ({
+ handlers: new Map<string, (request: Request) => Promise<Response>>(),
+ sessions: new Map<string, ReturnType<typeof makeSession>>(),
+ peerCurrent: true,
+ dialog: vi.fn(async () => ({ response: 1 })),
+}));
+function makeSession(partition: string) {
+ return {
+ protocol: {
+ handle: (_scheme: string, handler: (request: Request) => Promise<Response>) =>
+ mock.handlers.set(partition, handler),
+ unhandle: () => mock.handlers.delete(partition),
+ },
+ webRequest: { onBeforeRequest: vi.fn() },
+ setPermissionRequestHandler: vi.fn(),
+ setPermissionCheckHandler: vi.fn(),
+ on: vi.fn(),
+ clearStorageData: vi.fn(async () => {}),
+ };
+}
+vi.mock('electron', () => ({
+ BrowserWindow: { fromWebContents: () => ({ isDestroyed: () => false }) },
+ session: {
+ fromPartition: (id: string) => {
+ const value = makeSession(id);
+ mock.sessions.set(id, value);
+ return value;
+ },
+ },
+ dialog: { showMessageBox: mock.dialog },
+ shell: { openExternal: vi.fn() },
+}));
+vi.mock('../runtime/electronSandboxAdapter.js', () => ({
+ GHOST_HTML_CSP: "default-src 'self'",
+ registerGhostWebContents: vi.fn(),
+}));
+vi.mock('../../plugin-oauth/runtime.js', () => ({
+ capturePluginOauthPeer: () => () => {
+ if (!mock.peerCurrent) throw new Error('CLOSED');
+ },
+}));
+vi.mock('../../device-link/broadcast-tap.js', () => ({
+ getSafeDataOwnerPushStamp: () => ({ dataOwnerId: 'owner' }),
+}));
+vi.mock('../../i18n.js', () => ({ t: (key: string) => key }));
+import {
+ openRemotePluginSettings,
+ closeRemotePluginSettings,
+ answerRemotePluginSettingsDirectory,
+ resolveRemoteSettingsAttach,
+ parseSettingsDocument,
+} from '../remotePluginSettingsController.js';
+
+const cleanup: Array<() => void> = [];
+afterEach(() => {
+ for (const close of cleanup.splice(0)) close();
+ mock.handlers.clear();
+ mock.sessions.clear();
+ mock.peerCurrent = true;
+ vi.clearAllMocks();
+});
+function fixture(namespace: string | null = null) {
+ let owner: string | null = 'owner',
+ revision = 'installed-1',
+ allowed = true;
+ const file = Buffer.from(
+ '<!doctype html><html><head></head><body><input id="original"><script src="settings.js"></script></body></html>',
+ );
+ const ghost = {
+ instanceKey: namespace ? '_ns__' + namespace + '__example' : 'example',
+ namespace,
+ enabled: true,
+ dir: '/fixture/target-only',
+ approval: { state: 'approved' },
+ manifest: {
+ id: 'example',
+ name: 'Original plugin',
+ version: '1.0.0',
+ settingsHtml: 'settings.html',
+ network: { secrets: [{ key: 'login', source: 'oauth' }] },
+ },
+ } as unknown as InstalledGhost;
+ const stored = new Map<string, string>(),
+ controllerStored = new Map<string, string>();
+ const settingsFetch = vi.fn(
+ async (
+ _ghost: InstalledGhost,
+ path: string,
+ method: string,
+ body: string | undefined,
+ current: () => boolean,
+ ) => {
+ if (!current()) throw new Error('CLOSED');
+ if (method === 'PUT') stored.set(path, body!);
+ const data =
+ path === '/oauth/login/connect'
+ ? { ok: true, account: { label: 'Existing account' } }
+ : path === '/oauth'
+ ? [{ accounts: [{ label: 'Existing account' }] }]
+ : method === 'GET'
+ ? { configured: stored.has('/secrets/key') }
+ : {};
+ return {
+ status: 200,
+ mime: 'application/json',
+ base64: Buffer.from(JSON.stringify(data)).toString('base64'),
+ };
+ },
+ );
+ const disconnect = vi.fn(async () => {}),
+ post = vi.fn(async () => {}),
+ connect = vi.fn(async () => {});
+ const validateDirectory = vi.fn<(path: string) => Promise<string>>(
+ async () => '/target/resolved',
+ );
+ const service = new MobilePluginPages({
+ list: () => [ghost],
+ revision: () => revision,
+ captureOwner: () => {
+ const captured = owner;
+ return () => owner === captured;
+ },
+ captureController: () => () => allowed,
+ unread: () => null,
+ clearUnread: vi.fn(),
+ setEnabled: vi.fn(),
+ bundle: async () => [{ path: 'settings.html', mime: 'text/html', size: file.length }],
+ asset: async (_ghost, _file, offset) => ({
+ mime: 'text/html',
+ base64: file.subarray(offset).toString('base64'),
+ }),
+ connect,
+ post,
+ poll: async () => [],
+ disconnect,
+ fetch: vi.fn(),
+ settingsFetch,
+ validateDirectory,
+ });
+ const identity = {
+ key: new OauthHostIdentity(),
+ deviceId: 'target-b',
+ realm: 'global' as const,
+ membershipId: 'membership',
+ };
+ const auth = new AuthenticatedOauthHost({
+ owner: () => owner,
+ available: () => allowed,
+ identity: () => identity,
+ bind: async (action) => service.settingsBinding(action),
+ request: (peer, raw) => service.settingsRequest(peer, raw as never),
+ });
+ const wire: unknown[] = [];
+ const deps = {
+ owner: () => owner,
+ assertTarget: () => {
+ if (!allowed) throw new Error('REVOKED');
+ },
+ localDeviceId: () => 'controller-a',
+ trustIdentity: vi.fn(async () => {}),
+ identity: async () => ({
+ ...identity,
+ ...identity.key.descriptor,
+ observedAtMs: Date.now(),
+ expiresAtMs: Date.now() + 60_000,
+ }),
+ invoke: async (_device: string, channel: string, args: unknown[]) => {
+ wire.push(args);
+ const result =
+ channel === PLUGIN_OAUTH_CHANNEL
+ ? await auth.request('controller-a', args[0])
+ : channel === REMOTE_RESOURCE_INVOKE_CHANNEL
+ ? await service.provider().invoke!(
+ { controllerDeviceId: 'controller-a' },
+ args[0] as never,
+ )
+ : undefined;
+ return { ok: true as const, result };
+ },
+ openExternal: vi.fn(async () => {}),
+ };
+ const host = Object.assign(new EventEmitter(), {
+ isDestroyed: () => false,
+ send: vi.fn(),
+ }) as unknown as WebContents;
+ const open = async () => {
+ const view = await openRemotePluginSettings(host, deps, {
+ deviceId: 'target-b',
+ instanceId: ghost.instanceKey!,
+ expectedInstalledApproval: ghostInstallApprovalToken(ghost.approval),
+ });
+ cleanup.push(() => closeRemotePluginSettings(host, view.id));
+ const fetch = (path: string, init?: RequestInit) =>
+ mock.handlers.get(view.partition)!(new Request('cindy-ghost://example' + path, init));
+ return { view, fetch };
+ };
+ return {
+ service,
+ ghost,
+ stored,
+ controllerStored,
+ settingsFetch,
+ deps,
+ host,
+ open,
+ post,
+ connect,
+ disconnect,
+ wire,
+ auth,
+ validateDirectory,
+ owner: (value: string | null) => {
+ owner = value;
+ },
+ revision: () => {
+ revision = 'replacement';
+ },
+ revoke: () => {
+ allowed = false;
+ },
+ };
+}
+
+describe('original remote plugin settings', () => {
+ it.each([null, 'org'])(
+ 'serves the original HTML in a unique, hardened session for namespace %s',
+ async (ns) => {
+ const f = fixture(ns),
+ { view, fetch } = await f.open();
+ const response = await fetch('/settings.html');
+ expect(await response.text()).toContain('<input id="original">');
+ expect(response.headers.get('Content-Security-Policy')).toBe("default-src 'self'");
+ expect(response.headers.get('Cache-Control')).toBe('no-store');
+ expect(view.partition).not.toContain('persist:');
+ expect(resolveRemoteSettingsAttach(f.host, view.partition, view.src)).toBeTruthy();
+ expect(resolveRemoteSettingsAttach({} as WebContents, view.partition, view.src)).toBeNull();
+ expect(resolveRemoteSettingsAttach(f.host, view.partition, 'https://example.com')).toBeNull();
+ const ses = mock.sessions.get(view.partition)!;
+ expect(ses.setPermissionRequestHandler).toHaveBeenCalled();
+ expect(ses.setPermissionCheckHandler).toHaveBeenCalled();
+ },
+ );
+ it('writes a new key only to B through the signed encrypted exchange, then reads B status', async () => {
+ const f = fixture(),
+ { fetch } = await f.open();
+ const value = 'synthetic-new-key-only-for-fixture';
+ expect(
+ (await fetch('/secrets/key', { method: 'PUT', body: JSON.stringify({ value }) })).status,
+ ).toBe(200);
+ expect(f.stored.get('/secrets/key')).toContain(value);
+ expect(f.controllerStored.size).toBe(0);
+ expect(JSON.stringify(f.wire)).not.toContain(value);
+ expect(await (await fetch('/secrets')).json()).toEqual({ configured: true });
+ expect(await (await fetch('/oauth')).json()).toEqual([
+ { accounts: [{ label: 'Existing account' }] },
+ ]);
+ });
++ it('renews before the authenticated message budget runs out, including concurrent reads', async () => {
++ const f = fixture(),
++ { fetch } = await f.open();
++ for (let offset = 0; offset < 1050; offset += 50) {
++ const responses = await Promise.all(Array.from({ length: 50 }, () => fetch('/secrets')));
++ expect(responses.every((response) => response.status === 200)).toBe(true);
++ }
++ expect(f.deps.trustIdentity).toHaveBeenCalledTimes(2);
++ expect(
++ (await fetch('/secrets/key', { method: 'PUT', body: '{"value":"after-renewal"}' })).status,
++ ).toBe(200);
++ expect(f.stored.get('/secrets/key')).toContain('after-renewal');
++ });
++ it('does not renew and replay a write after its response is lost', async () => {
++ const f = fixture(),
++ { fetch } = await f.open();
++ const original = f.deps.invoke;
++ f.deps.invoke = async (device, channel, args) => {
++ const response = await original(device, channel, args);
++ if (channel === PLUGIN_OAUTH_CHANNEL) throw new Error('Response lost');
++ return response;
++ };
++ expect(
++ (await fetch('/secrets/key', { method: 'PUT', body: '{"value":"submitted-once"}' })).status,
++ ).toBe(503);
++ expect(f.settingsFetch).toHaveBeenCalledTimes(1);
++ expect(f.stored.get('/secrets/key')).toContain('submitted-once');
++ expect(f.deps.trustIdentity).toHaveBeenCalledTimes(1);
++ });
+ it.each(['owner', 'revision', 'revoke', 'peer'] as const)(
+ 'rejects a late write after %s changes',
+ async (change) => {
+ const f = fixture(),
+ { fetch } = await f.open();
+ if (change === 'owner') f.owner('another-owner');
+ else if (change === 'revision') f.revision();
+ else if (change === 'revoke') f.revoke();
+ else mock.peerCurrent = false;
+ expect(
+ (await fetch('/secrets/key', { method: 'PUT', body: '{"value":"late"}' })).status,
+ ).toBe(503);
+ expect(f.stored.size).toBe(0);
+ },
+ );
+ it('rejects unbound channels, arbitrary endpoints and use of the ordinary remote page fetch', async () => {
+ const f = fixture(),
+ { view, fetch } = await f.open();
+ const body = await (await fetch('/settings.html')).text();
+ const internal = /src="([^"]+\.js)"/.exec(body)![1].slice(0, -3);
+ expect(
+ (
+ await fetch(internal, {
+ method: 'POST',
+ body: JSON.stringify({ kind: 'post', channel: 'rogue', data: 'value' }),
+ })
+ ).status,
+ ).toBe(503);
+ expect((await fetch('/arbitrary-host-api', { method: 'POST', body: '{}' })).status).toBe(503);
+ expect(f.post).not.toHaveBeenCalled();
+ const page = [...(f.service as unknown as { pages: Map<string, unknown> }).pages.keys()][0];
+ await expect(
+ f.service.provider().invoke!(
+ { controllerDeviceId: 'controller-a' },
+ {
+ client: { protocolVersion: 1, primitives: [] },
+ collectionId: 'plugins',
+ actionId: 'fetch',
+ resourceRef: { collectionId: 'plugins', kind: 'plugin', id: f.ghost.instanceKey! },
+ input: { pageId: page, path: '/secrets' },
+ },
+ ),
+ ).rejects.toThrow();
+ closeRemotePluginSettings(f.host, view.id);
+ expect(mock.handlers.has(view.partition)).toBe(false);
+ });
+ it('updates the original sandbox subscriptions and prevents posting after unsubscribe', async () => {
+ const f = fixture(),
+ { fetch } = await f.open();
+ const html = await (await fetch('/settings.html')).text();
+ const internal = /src="([^"]+\.js)"/.exec(html)![1].slice(0, -3);
+ const send = (command: unknown) =>
+ fetch(internal, { method: 'POST', body: JSON.stringify(command) });
+ expect((await send({ kind: 'subscribe', channels: ['one', 'two'] })).status).toBe(200);
+ expect(f.connect).toHaveBeenLastCalledWith(f.ghost, expect.any(String), ['one', 'two']);
+ expect((await send({ kind: 'unsubscribe', channel: 'one' })).status).toBe(200);
+ expect(f.connect).toHaveBeenLastCalledWith(f.ghost, expect.any(String), ['two']);
+ expect((await send({ kind: 'post', channel: 'one', data: { stale: true } })).status).toBe(503);
+ expect(f.post).not.toHaveBeenCalled();
+ expect((await send({ kind: 'post', channel: 'two', data: { active: true } })).status).toBe(200);
+ expect(f.post).toHaveBeenCalledTimes(1);
+ });
+ it('checks the lease inside the original endpoint after its body has been read', async () => {
+ const f = fixture(),
+ { fetch } = await f.open();
+ let resume!: () => void;
+ const reading = new Promise<void>((resolve) => {
+ resume = resolve;
+ });
+ f.settingsFetch.mockImplementationOnce(async (_ghost, path, _method, body, current) => {
+ await reading;
+ if (!current()) throw new Error('CLOSED');
+ f.stored.set(path, body!);
+ return { status: 200, mime: 'application/json', base64: '' };
+ });
+ const writing = fetch('/secrets/key', { method: 'PUT', body: '{"value":"fixture"}' });
+ await vi.waitFor(() => expect(f.settingsFetch).toHaveBeenCalledTimes(1));
+ f.revoke();
+ resume();
+ expect((await writing).status).toBe(503);
+ expect(f.stored.size).toBe(0);
+ });
+ it('returns a trusted directory selection to the target picker through the sealed page', async () => {
+ const f = fixture(),
+ { view, fetch } = await f.open();
+ const pageId = [...(f.service as unknown as { pages: Map<string, unknown> }).pages.keys()][0];
+ const selection = f.service.chooseDirectory(
+ pageId,
+ f.ghost.instanceKey!,
+ 'Choose a parent folder',
+ );
+ const html = await (await fetch('/settings.html')).text();
+ const internal = /src="([^"]+\.js)"/.exec(html)![1].slice(0, -3);
+ const response = await fetch(internal, {
+ method: 'POST',
+ body: JSON.stringify({ kind: 'poll', after: 0 }),
+ });
+ expect((await response.json()).directories).toBeUndefined();
+ const notice = vi
+ .mocked(f.host.send)
+ .mock.calls.find((call) => call[0] === 'device-link:plugin-settings:directory')![1];
+ const answer = { viewId: view.id, requestId: notice.request.id, path: '/target/folder' };
+ await expect(answerRemotePluginSettingsDirectory({} as WebContents, answer)).rejects.toThrow();
+ expect(f.validateDirectory).not.toHaveBeenCalled();
+ await answerRemotePluginSettingsDirectory(f.host, answer);
+ expect(await selection).toBe('/target/resolved');
+ expect(f.validateDirectory).toHaveBeenCalledWith('/target/folder');
+ await answerRemotePluginSettingsDirectory(f.host, answer);
+ expect(f.validateDirectory).toHaveBeenCalledTimes(1);
+ });
+ it('binds OAuth to the page and executes its original endpoint inside the existing remote authorization context', async () => {
+ const f = fixture();
+ await f.open();
+ const pageId = [...(f.service as unknown as { pages: Map<string, unknown> }).pages.keys()][0];
+ const action = (await f.service.settingsRequest('controller-a', {
+ op: 'settings',
+ id: pageId,
+ command: { kind: 'authorize', path: '/oauth/login/connect' },
+ })) as { requestId: string; actionId: string; expectedRevision: number };
+ const finish = vi.fn();
+ f.settingsFetch.mockImplementationOnce(async (_ghost, _path, _method, _body, current) => {
+ expect(current()).toBe(true);
+ expect(getRemoteOauthContext()?.peer).toBe('controller-a');
+ return {
+ status: 200,
+ mime: 'application/json',
+ base64: Buffer.from('{"ok":true}').toString('base64'),
+ };
+ });
+ withRemoteOauthContext(
+ { scope: 'fixture', peer: 'controller-a', assertCurrent() {}, authorize: vi.fn(), finish },
+ () => expect(f.service.runSettingsAuthorization(action)).toBe(true),
+ );
+ await vi.waitFor(() => expect(finish).toHaveBeenCalledWith(true));
+ const result = (await f.service.settingsRequest('controller-a', {
+ op: 'settings',
+ id: pageId,
+ command: { kind: 'authorization-result', requestId: action.requestId },
+ })) as { base64: string };
+ expect(Buffer.from(result.base64, 'base64').toString()).toBe('{"ok":true}');
+ expect(f.service.settingsAuthorizationBinding(action)).toBeNull();
+ });
+ it('rejects foreign identities and unsafe package descriptors', () => {
+ expect(() =>
+ parseSettingsDocument({ pageId: 'p', pluginId: 'elsewhere' }, 'example'),
+ ).toThrow();
+ expect(() =>
+ parseSettingsDocument(
+ {
+ pageId: 'p',
+ pluginId: 'example',
+ manifestId: 'example',
+ name: 'Plugin',
+ entry: '../outside.html',
+ files: [],
+ },
+ 'example',
+ ),
+ ).toThrow();
+ });
+});
diff --cc apps/desktop/src/main/cindy-brain/index.ts
index a12f98893f,6f3aef29d1..626540ad18
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@@ -7340,6 -7309,6 +7340,8 @@@ export async function installOrUpdateMa
/** 自定义 Git/本地市场在打包前读取的 Manifest,用于防止打包窗口内能力扩张。 */
manifestCap?: GhostManifest;
beforeCommitInLock?: () => void;
++ /** Caller owner/peer/cancellation guard, valid after the directory swap. */
++ assertCurrent?: () => void;
/** 新包已经原子换位;后续异常不能再按落位失败回滚来源路由。 */
onPackagePlacedInLock?: () => void;
/** 包与 receipt 已提交,仍持 owner mutation lease;用于原子写入来源账本。 */
@@@ -7380,6 -7349,6 +7382,7 @@@ async function installOrUpdateMarketGho
reclaimLegacyBareInstance?: boolean;
manifestCap?: GhostManifest;
beforeCommitInLock?: () => void;
++ assertCurrent?: () => void;
/** 新包已经原子换位;后续异常不能再按落位失败回滚来源路由。 */
onPackagePlacedInLock?: () => void;
/** 包与 receipt 已提交,仍持 owner mutation lease;用于原子写入来源账本。 */
@@@ -7501,7 -7470,7 +7504,10 @@@
...(expected.reclaimLegacyBareInstance ? { reclaimLegacyBareInstance: true } : {}),
expectedPackageSha256: inspected.packageSha256,
consent: { decision: expected.consent, manifest: inspected.manifest },
-- beforePackagePlacement: expected.beforeCommitInLock,
++ beforePackagePlacement: () => {
++ expected.assertCurrent?.();
++ expected.beforeCommitInLock?.();
++ },
deferUsageBinding: true,
...(trustOverride ? { trustOverride } : {}),
namespace: marketNamespace,
@@@ -7543,12 -7512,12 +7549,14 @@@
...(expected.sourceChanged ? { sourceStateArchiveId: ghostSourceStateArchiveId(installed) } : {}),
...(trustOverride ? { trustOverride } : {}),
namespace: marketNamespace,
-- beforePackageCommit: () =>
-- getGhostOauthAccountManager().prepareAccountsForChangedClients(
++ beforePackageCommit: () => {
++ expected.assertCurrent?.();
++ return getGhostOauthAccountManager().prepareAccountsForChangedClients(
installed.manifest,
inspected.canonicalManifest,
installedGhostStoragePart(installed),
-- ),
++ );
++ },
onPackagePlaced: () => {
packagePlaced = true;
expected.onPackagePlacedInLock?.();
@@@ -7935,61 -7862,7 +7943,61 @@@ export function registerGhostIpc(): voi
ipcRegistered = true;
const manager = getGhostManager();
const runtime = getGhostRuntime();
+ const taskSettings = new MobileTaskSettings({
+ read: readPluginTaskConfig, write: writePluginTaskConfig, validate: validatePluginTaskConfig,
+ providers: () => getDesktopProviderService({ allowSideEffects: false }).listProviders({ allowSideEffects: false, snapshotOnly: true }),
+ agents: async () => { const { getMakerIfReady } = await import('../maker-host/index.js'); return getMakerIfReady()?.listAvailableAgents() ?? []; },
+ });
+ remotePluginManagement = new RemotePluginManagement({
+ list: availableGhosts,
+ settingsPage: true,
+ preferences: new RemotePluginPreferences({
+ auxiliaryModelLabel: () => {
+ const ref = getEffectiveAuxiliaryModelChain().refs[0] ?? null;
+ return ref === null ? null : formatAuxiliaryModelRefLabel(ref);
+ },
+ tasks: taskSettings,
+ sidebar: {
+ read: id => requireRemotePluginManagementServices().sidebar.read(id),
+ write: (id, visible, assertCurrent) => requireRemotePluginManagementServices().sidebar.write(id, visible, assertCurrent),
+ },
+ }),
+ projects: {
+ list: async () => {
+ const entries = await requireRemotePluginManagementServices().listProjects();
+ return [...new Map(entries.map((entry) => {
+ const project = projectPluginWorkdir(entry.path);
+ return [project.id, project] as const;
+ })).values()];
+ },
+ resolve: resolvePluginWorkdir,
+ disabled: listDisabledGhostIdsForWorkdir,
+ setDisabled: (workdir, instance, disabled, assertCurrent) => {
+ assertCurrent();
+ setGhostWorkdirDisabledAndNotify(workdir, instance, disabled);
+ },
+ },
+ capture: peer => {
+ const scope = captureDataOwnerBroadcastScope(), checkPeer = capturePluginOauthPeer(peer);
+ return () => { try { checkPeer(); const settings = readDeviceLinkSettings(); return !isSharedTaskPeer(peer) && !isProviderSharePeer(peer) && remotePluginManagementServices?.isRelayOnline() === true && settings.remoteControlEnabled && !settings.revokedControllers.includes(peer) && isDataOwnerBroadcastScopeCurrent(scope); } catch { return false; } };
+ },
+ captureReceipt: peer => {
+ const scope = captureDataOwnerBroadcastScope();
+ return () => { const settings = readDeviceLinkSettings(); return !isSharedTaskPeer(peer) && !isProviderSharePeer(peer) && settings.remoteControlEnabled && !settings.revokedControllers.includes(peer) && isDataOwnerBroadcastScopeCurrent(scope); };
+ },
+ market: {
+ snapshot: () => requireRemotePluginManagementServices().market.snapshot(),
+ detail: id => requireRemotePluginManagementServices().market.detail(id),
- install: async (id, options, prompt, assertCurrent) => {
- await requireRemotePluginManagementServices().market.install(id, options, prompt, assertCurrent);
++ install: async (id, options, prompt, assertCurrent, assertScope) => {
++ await requireRemotePluginManagementServices().market.install(id, options, prompt, assertCurrent, assertScope);
+ },
+ },
+ setEnabled: async (id, enabled, approval, assertCurrent) => { await setGhostEnabledForUser(id, enabled, approval, assertCurrent); },
+ uninstall: async (id, _approval, assertCurrent) => { assertCurrent(); await uninstallGhostAndCleanup(id, { assertCurrent }); },
+ installFile: installRemoteGhostFile,
+ });
mobilePluginPages = new MobilePluginPages({
+ management: remotePluginManagement,
list: availableGhosts,
listOrder: () => {
const order = new Map<string, { addedAt?: number; recentIndex?: number }>();
diff --cc apps/desktop/src/main/cindy-brain/remotePluginManagement.ts
index 4d6a5b6726,0000000000..97da1af631
mode 100644,000000..100644
--- a/apps/desktop/src/main/cindy-brain/remotePluginManagement.ts
+++ b/apps/desktop/src/main/cindy-brain/remotePluginManagement.ts
@@@ -1,479 -1,0 +1,482 @@@
+import { extractIpcError } from '../../shared/ipcError.js';
+import { createHash, randomUUID } from 'node:crypto';
+import type { RemoteActionInvokeRequest, RemoteActionInvokeResponse } from '@cindy/device-link';
+import {
+ isGhostInstallApprovalToken,
+ ghostInstallApprovalToken,
+ type InstalledGhost,
+} from '../../shared/ghost.js';
+import { installedGhostStoragePart } from '../../shared/pluginIdentity.js';
+import type {
+ PluginMarketDetail,
+ PluginMarketInstallOptions,
+ PluginMarketSnapshot,
+} from '../../shared/pluginMarket.js';
+import type {
+ PluginManagementProject,
+ PluginManagementProjectState,
+ PluginManagementReceipt,
+} from '../../shared/pluginManagement.js';
+import type { GhostInstallConsentPrompt } from './ghostInstallConsent.js';
+import { RemoteResourceRegistryError } from '../device-link/remoteResourceRegistry.js';
+import type { RemotePluginPreferences } from './remotePluginPreferences.js';
+import type { RemotePluginProject } from './remotePluginProjects.js';
+
+interface Operation {
+ peer: string;
+ fingerprint: string;
+ receipt: PluginManagementReceipt;
+ current(): boolean;
+ visible(): boolean;
+ abort: AbortController;
+ timer: ReturnType<typeof setTimeout>;
+ answer?: (accepted: boolean) => void;
+}
+export interface RemotePluginManagementDeps {
+ list(): InstalledGhost[];
+ preferences?: RemotePluginPreferences;
+ settingsPage?: true;
+ projects?: {
+ list(): Promise<Array<PluginManagementProject & { workdir: string }>>;
+ resolve?(workdir: string): Promise<RemotePluginProject>;
+ disabled(workdir: string): string[];
+ setDisabled(
+ workdir: string,
+ instance: string,
+ disabled: boolean,
+ assertCurrent: () => void,
+ ): void;
+ };
+ capture(peer: string): () => boolean;
+ captureReceipt(peer: string): () => boolean;
+ market: {
+ snapshot(): Promise<PluginMarketSnapshot>;
+ detail(id: string): Promise<PluginMarketDetail>;
+ install(
+ id: string,
+ options: PluginMarketInstallOptions,
+ prompt: GhostInstallConsentPrompt,
+ assertCurrent: () => void,
++ assertScope: () => void,
+ ): Promise<void>;
+ };
+ setEnabled(
+ id: string,
+ enabled: boolean,
+ approval: string,
+ assertCurrent: () => void,
+ ): Promise<void>;
+ uninstall(id: string, approval: string, assertCurrent: () => void): Promise<void>;
+ installFile?(
+ peer: string,
+ attachment: string,
+ target: string | undefined,
+ approval: string | undefined,
+ prompt: GhostInstallConsentPrompt,
+ /** Owner/peer/cancellation only; the installer binds approval under its lock. */
+ assertScope: () => void,
+ ): Promise<void>;
+}
+const invalid = (): never => {
+ throw new RemoteResourceRegistryError('INVALID_PARAMS', 'Invalid plugin management request');
+};
+const unavailable = (): never => {
+ throw new RemoteResourceRegistryError(
+ 'NOT_FOUND',
+ 'Plugin management request is no longer available',
+ );
+};
+const str = (v: unknown, max = 256): string =>
+ typeof v === 'string' && v.length > 0 && v.length <= max ? v : invalid();
+const approval = (v: unknown): string =>
+ isGhostInstallApprovalToken(v) ? (v as string) : invalid();
+
+/** Project display metadata; mutations use Host-owned instance identity, never the displayed path. */
+export function projectManagedGhost(g: InstalledGhost): InstalledGhost {
+ return {
+ manifest: g.manifest,
+ dir: g.dir,
+ instanceKey: installedGhostStoragePart(g),
+ namespace: g.namespace,
+ namespaceState: g.namespaceState,
+ enabled: g.enabled,
+ approval: g.approval,
+ trust: g.trust,
+ iconDataUrl: g.iconDataUrl,
+ builtin: g.builtin,
+ retirement: g.retirement,
+ taskCapabilityApproved: g.taskCapabilityApproved,
+ oauthScopeStale: g.oauthScopeStale,
+ oauthAuthorizationExpired: g.oauthAuthorizationExpired,
+ };
+}
+
+/** Per-controller receipts reuse the installer; permission prompts wait outside its lock. */
+export class RemotePluginManagement {
+ private readonly operations = new Map<string, Operation>();
+ // A browsed directory is a transient scope, like the local picker. Do not add a task or recent project.
+ private readonly browsedProjects = new Map<string, { project: RemotePluginProject; current(): boolean }>();
+ constructor(private readonly deps: RemotePluginManagementDeps) {}
+ private find(id: string): InstalledGhost {
+ return this.deps.list().find((g) => installedGhostStoragePart(g) === id) ?? unavailable();
+ }
+ private operation(peer: string, id: string): Operation {
+ const op = this.operations.get(id);
+ if (!op || op.peer !== peer || !op.visible()) return unavailable();
+ return op;
+ }
+ private assertScope(op: Operation): void {
+ if (!op.current() || op.abort.signal.aborted) return unavailable();
+ }
+ private async project(id: string, peer: string): Promise<RemotePluginProject> {
+ const browsed = this.browsedProjects.get(peer);
+ if (browsed?.project.id === id && browsed.current() && this.deps.projects?.resolve) {
+ const resolved = await this.deps.projects.resolve(browsed.project.workdir);
+ if (!browsed.current() || resolved.id !== id) return unavailable();
+ return resolved;
+ }
+ return (
+ (await this.deps.projects?.list())?.find((project) => project.id === id) ?? unavailable()
+ );
+ }
+ private projectState(projectId: string, workdir: string): PluginManagementProjectState {
+ const disabled = [...new Set(this.deps.projects!.disabled(workdir))].sort();
+ const visible = new Set(this.deps.list().map(installedGhostStoragePart));
+ return {
+ projectId,
+ revision: createHash('sha256').update(JSON.stringify(disabled)).digest('hex'),
+ disabled: disabled.filter((id) => visible.has(id)),
+ };
+ }
+ private prune(): void {
+ for (const [peer, selection] of this.browsedProjects) {
+ if (!selection.current()) this.browsedProjects.delete(peer);
+ }
+ for (const [id, op] of this.operations) {
+ if (!op.visible()) {
+ op.abort.abort();
+ op.answer?.(false);
+ clearTimeout(op.timer);
+ this.operations.delete(id);
+ } else if (!op.current() && ['running', 'confirmation'].includes(op.receipt.phase)) {
+ // A lost connection invalidates further writes, but a reconnect must still
+ // be able to query whether the original request actually committed.
+ op.abort.abort();
+ op.answer?.(false);
+ }
+ }
+ }
+ invalidate(): void {
+ this.prune();
+ }
+ async invoke(
+ peer: string,
+ request: RemoteActionInvokeRequest,
+ ): Promise<RemoteActionInvokeResponse> {
+ this.prune();
+ const input = request.input ?? {};
+ const result = (value: unknown): RemoteActionInvokeResponse => ({ effects: [], result: value });
+ if (request.actionId === 'management:snapshot') {
+ if (Object.keys(input).length) return invalid();
+ const current = this.deps.capture(peer);
+ if (!current()) return unavailable();
+ const [market, projects] = await Promise.all([
+ this.deps.market.snapshot(),
+ this.deps.projects?.list(),
+ ]);
+ if (!current()) return unavailable();
+ const browsed = this.browsedProjects.get(peer)?.project;
+ const scopeProjects = browsed && projects
+ ? [browsed, ...projects.filter((project) => project.id !== browsed.id)]
+ : projects;
+ return result({
+ version: 1,
+ ghosts: this.deps.list().map(projectManagedGhost),
+ market,
+ ...(this.deps.preferences ? { hostPreferences: true } : {}),
+ ...(this.deps.settingsPage ? { settingsPage: true } : {}),
+ ...(scopeProjects ? { projects: scopeProjects.map(({ id, name, path }) => ({ id, name, ...(path ? { path } : {}) })) } : {}),
+ ...(this.deps.projects?.resolve ? { projectBrowse: true } : {}),
+ });
+ }
+ if (request.actionId === 'management:project-select') {
+ if (Object.keys(input).some((key) => key !== 'path')) return invalid();
+ if (!this.deps.projects?.resolve) return unavailable();
+ const current = this.deps.capture(peer);
+ if (!current()) return unavailable();
+ const project = await this.deps.projects.resolve(str(input.path, 32768));
+ if (!current()) return unavailable();
+ this.browsedProjects.set(peer, { project, current });
+ return result({ id: project.id, name: project.name, path: project.path });
+ }
+ if (
+ request.actionId === 'management:preferences' ||
+ request.actionId === 'management:preferences-set'
+ ) {
+ const settings = this.deps.preferences;
+ if (
+ !settings ||
+ !request.resourceRef?.id ||
+ Object.keys(input).some(
+ (key) =>
+ ![
+ 'expectedInstalledApproval',
+ 'expectedRevision',
+ 'kind',
+ 'patch',
+ 'visible',
+ ].includes(key),
+ )
+ )
+ return invalid();
+ const id = str(request.resourceRef.id);
+ const expected = approval(input.expectedInstalledApproval);
+ const current = this.deps.capture(peer);
+ const assertCurrent = () => {
+ const ghost = this.find(id);
+ if (!current() || !ghost.enabled || ghostInstallApprovalToken(ghost.approval) !== expected)
+ return unavailable();
+ };
+ assertCurrent();
+ const ghost = this.find(id);
+ const value =
+ request.actionId === 'management:preferences'
+ ? settings.read(id, ghost)
+ : await settings.update(id, ghost, input, assertCurrent);
+ assertCurrent();
+ return result(value);
+ }
+ if (request.actionId === 'management:project-state') {
+ if (Object.keys(input).some((key) => key !== 'projectId')) return invalid();
+ const current = this.deps.capture(peer);
+ if (!current()) return unavailable();
+ const project = await this.project(str(input.projectId), peer);
+ if (!current()) return unavailable();
+ return result(this.projectState(project.id, project.workdir));
+ }
+ if (request.actionId === 'management:market-detail') {
+ if (Object.keys(input).some((k) => k !== 'pluginId')) return invalid();
+ const current = this.deps.capture(peer);
+ if (!current()) return unavailable();
+ const detail = await this.deps.market.detail(str(input.pluginId, 1024));
+ if (!current()) return unavailable();
+ return result(detail);
+ }
+ if (request.actionId === 'management:operation') {
+ if (Object.keys(input).some((k) => k !== 'operationId')) return invalid();
+ return result(this.operation(peer, str(input.operationId)).receipt);
+ }
+ if (request.actionId === 'management:answer') {
+ if (
+ Object.keys(input).some((k) => !['operationId', 'requestId', 'confirmed'].includes(k)) ||
+ typeof input.confirmed !== 'boolean'
+ )
+ return invalid();
+ const op = this.operation(peer, str(input.operationId));
+ if (!op.answer || op.receipt.consent?.requestId !== input.requestId) return unavailable();
+ this.assertScope(op);
+ const answer = op.answer;
+ delete op.answer;
+ delete op.receipt.consent;
+ op.receipt.phase = 'running';
+ answer(input.confirmed);
+ return result(op.receipt);
+ }
+ if (request.actionId === 'management:cancel') {
+ if (Object.keys(input).some((k) => k !== 'operationId')) return invalid();
+ const op = this.operation(peer, str(input.operationId));
+ // A committed result stays committed; cancellation cannot undo an installation.
+ if (op.receipt.phase === 'running' || op.receipt.phase === 'confirmation') {
+ op.abort.abort();
+ op.answer?.(false);
+ }
+ return result(op.receipt);
+ }
+ if (request.actionId !== 'management:begin') return invalid();
+ if (
+ Object.keys(input).some(
+ (k) =>
+ ![
+ 'operationId',
+ 'kind',
+ 'pluginId',
+ 'expectedReleaseId',
+ 'expectedInstalledApproval',
+ 'expectedManifest',
+ 'attachment',
+ 'projectId',
+ 'expectedProjectRevision',
+ ].includes(k),
+ )
+ )
+ return invalid();
+ const id = str(input.operationId, 128);
+ const kind = str(input.kind, 32);
+ if (!['install', 'enable', 'disable', 'uninstall', 'install-file'].includes(kind))
+ return invalid();
+ const projectId = input.projectId === undefined ? undefined : str(input.projectId);
+ const projectRevision =
+ input.expectedProjectRevision === undefined ? undefined : str(input.expectedProjectRevision);
+ if (
+ projectId
+ ? !projectRevision || !['enable', 'disable'].includes(kind)
+ : projectRevision !== undefined
+ )
+ return invalid();
+ const target = request.resourceRef?.id;
+ const fingerprint = JSON.stringify([target ?? null, input]);
+ const previous = this.operations.get(id);
+ if (previous) {
+ if (previous.peer !== peer || previous.fingerprint !== fingerprint || !previous.visible())
+ return unavailable();
+ return result(previous.receipt);
+ }
+ const installedApproval =
+ input.expectedInstalledApproval === undefined
+ ? undefined
+ : approval(input.expectedInstalledApproval);
+ let ghost: InstalledGhost | undefined;
+ if (target) {
+ ghost = this.find(target);
+ if (installedApproval !== ghostInstallApprovalToken(ghost.approval)) return unavailable();
+ } else if (!['install', 'install-file'].includes(kind)) return invalid();
+ const pluginId = kind === 'install' ? str(input.pluginId, 1024) : undefined;
+ const releaseId = kind === 'install' ? str(input.expectedReleaseId, 1024) : undefined;
+ if (kind === 'install-file' && (!this.deps.installFile || typeof input.attachment !== 'string'))
+ return invalid();
+ if (
+ this.operations.size >= 128 ||
+ [...this.operations.values()].filter(
+ (op) => op.peer === peer && ['running', 'confirmation'].includes(op.receipt.phase),
+ ).length >= 8
+ )
+ return unavailable();
+ const current = this.deps.capture(peer);
+ if (!current()) return unavailable();
+ const op: Operation = {
+ peer,
+ fingerprint,
+ current,
+ visible: this.deps.captureReceipt(peer),
+ abort: new AbortController(),
+ receipt: { operationId: id, phase: 'running' },
+ timer: setTimeout(() => {
+ op.abort.abort();
+ op.answer?.(false);
+ this.operations.delete(id);
+ }, 15 * 60_000),
+ };
+ op.timer.unref?.();
+ this.operations.set(id, op);
+ const assertCurrent = () => {
+ this.assertScope(op);
+ if (target && ghostInstallApprovalToken(this.find(target).approval) !== installedApproval)
+ return unavailable();
+ };
+ const prompt: GhostInstallConsentPrompt = (facts) => {
+ assertCurrent();
+ const requestId = randomUUID();
+ op.receipt = { operationId: id, phase: 'confirmation', consent: { ...facts, requestId } };
+ return new Promise((resolve) => {
+ const cancel = () => {
+ delete op.answer;
+ delete op.receipt.consent;
+ resolve(false);
+ };
+ op.abort.signal.addEventListener('abort', cancel, { once: true });
+ op.answer = (accepted) => {
+ op.abort.signal.removeEventListener('abort', cancel);
+ if (!op.current() || op.abort.signal.aborted) return resolve(false);
+ resolve(accepted);
+ };
+ });
+ };
+ void (async () => {
+ try {
+ assertCurrent();
+ switch (kind) {
+ case 'install':
+ await this.deps.market.install(
+ pluginId!,
+ {
+ expectedReleaseId: releaseId!,
+ allowSourceReplacement: false,
+ ...(installedApproval ? { expectedInstalledApproval: installedApproval } : {}),
+ ...(input.expectedManifest
+ ? { expectedManifest: input.expectedManifest as PluginMarketDetail['manifest'] }
+ : {}),
+ },
+ prompt,
+ assertCurrent,
++ // The installer owns approval checks; this guard survives its directory swap.
++ () => this.assertScope(op),
+ );
+ break;
+ case 'install-file':
+ await this.deps.installFile!(
+ peer,
+ str(input.attachment, 2048),
+ target,
+ installedApproval,
+ prompt,
+ // The native update transaction checks the old approval itself. Its
+ // commit hook runs after the directory swap, when that receipt no
+ // longer describes the staged package; re-reading it would roll
+ // back our own update. Keep owner/peer/cancellation fencing active.
+ () => this.assertScope(op),
+ );
+ break;
+ case 'enable':
+ case 'disable':
+ if (projectId) {
+ const project = await this.project(projectId, peer);
+ const assertProjectCurrent = () => {
+ assertCurrent();
+ if (this.projectState(projectId, project.workdir).revision !== projectRevision)
+ return unavailable();
+ // Project exceptions can never enable a globally disabled plugin.
+ if (kind === 'enable' && !this.find(target!).enabled) return unavailable();
+ };
+ assertProjectCurrent();
+ this.deps.projects!.setDisabled(
+ project.workdir,
+ target!,
+ kind === 'disable',
+ assertProjectCurrent,
+ );
+ } else {
+ await this.deps.setEnabled(
+ target!,
+ kind === 'enable',
+ installedApproval!,
+ assertCurrent,
+ );
+ }
+ break;
+ case 'uninstall':
+ await this.deps.uninstall(target!, installedApproval!, assertCurrent);
+ break;
+ }
+ // The authoritative result wins after commit, even if the view was cancelled meanwhile.
+ op.receipt = { operationId: id, phase: 'succeeded' };
+ } catch (error) {
+ const code =
+ extractIpcError(error)?.code ??
+ (error && typeof error === 'object' && 'code' in error && typeof error.code === 'string'
+ ? error.code
+ : 'INTERNAL');
+ op.receipt = {
+ operationId: id,
+ phase:
+ op.abort.signal.aborted || code === 'MUTATION_CANCELLED' || code === 'SETUP_CANCELLED'
+ ? 'cancelled'
+ : 'failed',
+ errorCode: code,
+ };
+ } finally {
+ delete op.answer;
+ }
+ })();
+ return result(op.receipt);
+ }
+}
diff --cc apps/desktop/src/main/cindy-brain/remotePluginSettingsController.ts
index 05e1a0cc2c,0000000000..6cf87f859a
mode 100644,000000..100644
--- a/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.ts
+++ b/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.ts
@@@ -1,504 -1,0 +1,509 @@@
+import { randomUUID } from 'node:crypto';
+import {
+ BrowserWindow,
+ dialog,
+ session,
+ shell,
+ type MessageBoxOptions,
+ type WebContents,
+} from 'electron';
+import {
+ PLUGIN_OAUTH_CHANNEL,
+ PLUGIN_SETTINGS_ACTION,
+ PLUGIN_PAGE_MAX_BUNDLE_BYTES,
+ REMOTE_RESOURCE_INVOKE_CHANNEL,
+ REMOTE_RESOURCE_PROTOCOL_VERSION,
+ oauthId,
+ oauthGhostId,
+ parsePluginOauthAction,
+ parsePluginSettingsRequest,
+ type PluginPageFile,
+ type PluginPageFetchResult,
+ type PluginSettingsCommand,
+ type PluginPagePoll,
+ type PluginOauthRequest,
+} from '@cindy/device-link';
+import {
+ REMOTE_PLUGIN_SETTINGS_PARTITION,
+ REMOTE_PLUGIN_SETTINGS_DIRECTORY,
+ type RemotePluginSettingsTarget,
+ type RemotePluginSettingsView,
+} from '../../shared/remotePluginSettings.js';
+import { isSafeGhostRelativePath } from '../../shared/ghost.js';
+import { authenticateOauthController } from '../plugin-oauth/authentication.js';
+import { capturePluginOauthPeer } from '../plugin-oauth/runtime.js';
+import { handleAssistPluginOauth, type LocalOauthDeps } from '../plugin-oauth/localIpc.js';
+import { GHOST_HTML_CSP, registerGhostWebContents } from './runtime/electronSandboxAdapter.js';
+import { remoteSettingsBroadcastScript } from './remoteSettingsBroadcast.js';
+import { getSafeDataOwnerPushStamp } from '../device-link/broadcast-tap.js';
+import { t } from '../i18n.js';
+
+interface SettingsDocument {
+ pageId: string;
+ pluginId: string;
+ manifestId: string;
+ name: string;
+ entry: string;
+ files: PluginPageFile[];
+}
+const unavailable = () => new Error('PLUGIN_SETTINGS_UNAVAILABLE');
+export function parseSettingsDocument(raw: unknown, instanceId: string): SettingsDocument {
+ const doc = raw as SettingsDocument;
+ if (
+ !doc ||
+ !oauthId(doc.pageId) ||
+ doc.pluginId !== instanceId ||
+ !oauthId(doc.manifestId) ||
+ typeof doc.name !== 'string' ||
+ doc.name.length > 160 ||
+ !isSafeGhostRelativePath(doc.entry) ||
+ !Array.isArray(doc.files) ||
+ !doc.files.length ||
+ doc.files.length > 10_000
+ )
+ throw unavailable();
+ let total = 0;
+ const paths = new Set<string>();
+ for (const file of doc.files) {
+ if (
+ !file ||
+ !isSafeGhostRelativePath(file.path) ||
+ paths.has(file.path) ||
+ !Number.isSafeInteger(file.size) ||
+ file.size < 0 ||
+ typeof file.mime !== 'string' ||
+ file.mime.length > 128 ||
+ /[\r\n]/.test(file.mime)
+ )
+ throw unavailable();
+ paths.add(file.path);
+ total += file.size;
+ }
+ if (
+ total > PLUGIN_PAGE_MAX_BUNDLE_BYTES ||
+ !doc.files.some((f) => f.path === doc.entry && f.mime.startsWith('text/html'))
+ )
+ throw unavailable();
+ return {
+ pageId: doc.pageId,
+ pluginId: doc.pluginId,
+ manifestId: doc.manifestId,
+ name: doc.name,
+ entry: doc.entry,
+ files: doc.files,
+ };
+}
+
+interface View {
+ id: string;
+ host: WebContents;
+ partition: string;
+ src: string;
+ current(): void;
+ attach(guest: WebContents): void;
+ close(): void;
+ answerDirectory(requestId: string, path: string | null): Promise<void>;
+}
+const views = new Map<string, View>();
+
+export function resolveRemoteSettingsAttach(
+ host: WebContents,
+ partition: string,
+ src: string,
+): View | null {
+ const view = views.get(partition);
+ if (!view || view.host !== host || view.src !== src) return null;
+ try {
+ view.current();
+ return view;
+ } catch {
+ view.close();
+ return null;
+ }
+}
+export function closeRemotePluginSettings(host: WebContents, id: unknown): void {
+ if (typeof id !== 'string') throw unavailable();
+ for (const view of views.values())
+ if (view.id === id && view.host === host) {
+ view.close();
+ return;
+ }
+}
+export async function answerRemotePluginSettingsDirectory(
+ host: WebContents,
+ raw: unknown,
+): Promise<void> {
+ const answer =
+ raw as import('../../shared/remotePluginSettings.js').RemotePluginSettingsDirectoryAnswer;
+ if (!answer || typeof answer.viewId !== 'string') throw unavailable();
+ const command = { kind: 'answer-directory', requestId: answer.requestId, path: answer.path };
+ if (!parsePluginSettingsRequest({ op: 'settings', id: 'local', command })) throw unavailable();
+ const view = [...views.values()].find((view) => view.id === answer.viewId && view.host === host);
+ if (!view) throw unavailable();
+ view.current();
+ await view.answerDirectory(answer.requestId, answer.path);
+}
+
+/** Main owns the encrypted exchange and the isolated page session. No values enter the app Renderer. */
+export async function openRemotePluginSettings(
+ host: WebContents,
+ deps: LocalOauthDeps,
+ raw: unknown,
+): Promise<RemotePluginSettingsView> {
+ const input = raw as RemotePluginSettingsTarget;
+ if (
+ !input ||
+ !oauthId(input.deviceId) ||
+ !oauthGhostId(input.instanceId) ||
+ typeof input.expectedInstalledApproval !== 'string' ||
+ input.expectedInstalledApproval.length > 4096 ||
+ views.size >= 8
+ )
+ throw unavailable();
+ const owner = deps.owner(),
+ peerCurrent = capturePluginOauthPeer(input.deviceId);
+ let closed = false;
+ const assertCurrent = () => {
+ if (closed || !owner || deps.owner() !== owner || host.isDestroyed()) throw unavailable();
+ peerCurrent();
+ deps.assertTarget(input.deviceId);
+ };
+ assertCurrent();
+ const opened = await deps.invoke(input.deviceId, REMOTE_RESOURCE_INVOKE_CHANNEL, [
+ {
+ client: {
+ protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION,
+ primitives: ['status', 'markdown', 'action', 'form', 'list'],
+ },
+ collectionId: 'plugins',
+ actionId: 'settings:open',
+ resourceRef: { collectionId: 'plugins', kind: 'plugin', id: input.instanceId },
+ input: { expectedInstalledApproval: input.expectedInstalledApproval },
+ },
+ ]);
+ assertCurrent();
+ if (!opened.ok) throw unavailable();
+ const doc = parseSettingsDocument(
+ (opened.result as { result?: unknown })?.result,
+ input.instanceId,
+ );
+ const id = randomUUID(),
+ partition = REMOTE_PLUGIN_SETTINGS_PARTITION + id;
+ const origin = 'cindy-ghost://' + doc.manifestId;
+ const src = origin + '/' + doc.entry;
+ const internal = '/__cindy_remote_settings_' + randomUUID();
+ let exchange: ((request: PluginOauthRequest) => Promise<unknown>) | undefined;
+ let renew: Promise<void> | undefined,
- renewedAt = 0;
++ renewedAt = 0,
++ sent = 0;
+ const connect = async () => {
+ const target = await deps.identity(input.deviceId, assertCurrent);
+ if (target.deviceId !== input.deviceId) throw unavailable();
+ exchange = await authenticateOauthController({
+ target,
+ peer: deps.localDeviceId(),
+ trustIdentity: deps.trustIdentity,
+ action: { requestId: doc.pageId, actionId: PLUGIN_SETTINGS_ACTION, expectedRevision: 0 },
+ ghostId: doc.pluginId,
+ assertCurrent,
+ invoke: async (request) => {
+ peerCurrent();
+ if (deps.owner() !== owner) throw unavailable();
+ const result = await deps.invoke(input.deviceId, PLUGIN_OAUTH_CHANNEL, [request]);
+ if (!result.ok) throw unavailable();
+ return result.result;
+ },
+ });
+ renewedAt = Date.now();
++ sent = 0;
+ };
+ const send = async (command: PluginSettingsCommand) => {
+ assertCurrent();
- // Renew before expiry, never replay a submitted command after a lost response.
- if (!exchange || Date.now() - renewedAt > 240_000) {
++ // Reserve before sending; leave room under the Host's 1024-message limit.
++ // A lost response must never cause a submitted command to be replayed.
++ while (!exchange || Date.now() - renewedAt > 240_000 || sent >= 1000) {
+ renew ??= connect().finally(() => {
+ renew = undefined;
+ });
+ await renew;
++ assertCurrent();
+ }
+ assertCurrent();
++ sent++;
+ return exchange!({ op: 'settings', id: doc.pageId, command });
+ };
+ await connect();
+ assertCurrent();
+ const ses = session.fromPartition(partition);
+ let guest: WebContents | undefined;
+ const confirmations = new Set<string>();
+ const prompt = (options: MessageBoxOptions) => {
+ assertCurrent();
+ const parent = BrowserWindow.fromWebContents(host);
+ if (!parent || parent.isDestroyed()) throw unavailable();
+ return dialog.showMessageBox(parent, options);
+ };
+ const confirm = async (value: PluginPagePoll['confirms'][number]) => {
+ if (confirmations.has(value.id)) return;
+ confirmations.add(value.id);
+ if (confirmations.size > 256) confirmations.delete(confirmations.values().next().value!);
+ try {
+ assertCurrent();
+ const { response } = await prompt({
+ type: 'question',
+ message: value.body,
+ title: value.title,
+ buttons: [
+ value.confirmText ?? t('settings.ghosts.connections.confirmAllow'),
+ value.cancelText ?? t('settings.ghosts.connections.confirmCancel'),
+ ],
+ defaultId: 1,
+ cancelId: 1,
+ });
+ assertCurrent();
+ await send({ kind: 'confirm', requestId: value.id, accepted: response === 0 });
+ } catch {
+ /* A closed lease cannot approve a pending mutation. */
+ }
+ };
+ const poll = async (after: number) => {
+ const result = (await send({ kind: 'poll', after })) as PluginPagePoll;
+ for (const item of result.confirms) void confirm(item);
+ for (const request of result.directories ?? []) {
+ assertCurrent();
+ host.send(
+ REMOTE_PLUGIN_SETTINGS_DIRECTORY,
+ { viewId: id, request },
+ getSafeDataOwnerPushStamp(),
+ );
+ }
+ for (const notice of result.notifications) {
+ assertCurrent();
+ host.send(
+ 'ghosts:notify',
+ { ghostId: doc.pluginId, name: doc.name, text: notice.text, tone: 'info' },
+ getSafeDataOwnerPushStamp(),
+ );
+ }
+ return { ...result, directories: undefined };
+ };
+ const fetchSettings = async (
+ path: string,
+ method: string,
+ body?: string,
+ ): Promise<PluginPageFetchResult> => {
+ if (/^\/oauth\/[^/]+\/connect$/.test(path) && method === 'POST') {
+ const action = parsePluginOauthAction(await send({ kind: 'authorize', path, body }));
+ if (!action) throw unavailable();
+ try {
+ await handleAssistPluginOauth(deps, {
+ deviceId: input.deviceId,
+ ghostId: doc.pluginId,
+ ...action,
+ });
+ } catch {
+ /* The original endpoint supplies the result, including cancellation. */
+ }
+ assertCurrent();
+ return (await send({
+ kind: 'authorization-result',
+ requestId: action.requestId,
+ })) as PluginPageFetchResult;
+ }
+ return (await send({
+ kind: 'fetch',
+ path,
+ method,
+ ...(body === undefined ? {} : { body }),
+ })) as PluginPageFetchResult;
+ };
+ ses.setPermissionRequestHandler((_webContents, _permission, answer) => answer(false));
+ ses.setPermissionCheckHandler(() => false);
+ ses.on('will-download', (event) => event.preventDefault());
+ ses.webRequest.onBeforeRequest((details, answer) => {
+ try {
+ assertCurrent();
+ const url = new URL(details.url);
+ answer({
+ cancel: !(
+ (url.protocol === 'cindy-ghost:' && url.hostname === doc.manifestId) ||
+ ['data:', 'blob:'].includes(url.protocol) ||
+ (url.protocol === 'https:' && details.resourceType === 'image')
+ ),
+ });
+ } catch {
+ answer({ cancel: true });
+ }
+ });
+ const failure = () => new Response(null, { status: 503 });
+ ses.protocol.handle('cindy-ghost', async (request) => {
+ try {
+ assertCurrent();
+ const url = new URL(request.url);
+ if (url.hostname !== doc.manifestId) return failure();
+ let response: Response;
+ if (url.pathname === internal && request.method === 'POST') {
+ const body = await readBody(request);
+ const parsed = parsePluginSettingsRequest({
+ op: 'settings',
+ id: doc.pageId,
+ command: JSON.parse(body),
+ });
+ if (!parsed || !['subscribe', 'unsubscribe', 'post', 'poll'].includes(parsed.command.kind))
+ return failure();
+ const result =
+ parsed.command.kind === 'poll'
+ ? await poll(parsed.command.after)
+ : await send(parsed.command);
+ response = Response.json(result);
+ } else if (url.pathname === internal + '.js' && request.method === 'GET') {
+ response = new Response(remoteSettingsBroadcastScript(internal), {
+ headers: { 'Content-Type': 'text/javascript' },
+ });
+ } else {
+ const file = doc.files.find((f) => '/' + f.path === decodeURIComponent(url.pathname));
+ if (file && request.method === 'GET') {
+ const parts: Buffer[] = [];
+ for (let offset = 0; offset < file.size;) {
+ const chunk = (await send({ kind: 'asset', path: file.path, offset })) as {
+ mime: string;
+ base64: string;
+ };
+ const bytes = Buffer.from(chunk.base64, 'base64');
+ if (!bytes.length || bytes.length > 49_152 || offset + bytes.length > file.size)
+ throw unavailable();
+ parts.push(bytes);
+ offset += bytes.length;
+ }
+ let content = Buffer.concat(parts);
+ if (file.mime.startsWith('text/html')) {
+ const html = content.toString('utf8');
+ const script = '<script src="' + internal + '.js"></script>';
+ content = Buffer.from(
+ /<head\b[^>]*>/i.test(html)
+ ? html.replace(/<head\b[^>]*>/i, (m) => m + script)
+ : script + html,
+ );
+ }
+ response = new Response(content, {
+ headers: {
+ 'Content-Type': file.mime,
+ ...(file.mime.startsWith('text/html')
+ ? { 'Content-Security-Policy': GHOST_HTML_CSP }
+ : {}),
+ },
+ });
+ } else {
+ const result = await fetchSettings(
+ url.pathname + url.search,
+ request.method,
+ ['GET', 'HEAD'].includes(request.method) ? undefined : await readBody(request),
+ );
+ response = new Response(
+ result.status === 204 ? null : Buffer.from(result.base64, 'base64'),
+ {
+ status: result.status,
+ headers: { 'Content-Type': result.mime },
+ },
+ );
+ }
+ }
+ assertCurrent();
+ response.headers.set('Cache-Control', 'no-store');
+ return response;
+ } catch {
+ return failure();
+ }
+ });
+ const keepAlive = setInterval(() => {
+ void poll(0).catch(() => view.close());
+ }, 30_000);
+ keepAlive.unref();
+ const attachDeadline = setTimeout(() => view.close(), 30_000);
+ attachDeadline.unref();
+ const view: View = {
+ id,
+ partition,
+ src,
+ host,
+ current: assertCurrent,
+ answerDirectory: async (requestId, path) => {
+ await send({ kind: 'answer-directory', requestId, path });
+ },
+ close: () => {
+ if (closed) return;
+ void send({ kind: 'close' }).catch(() => {});
+ closed = true;
+ clearInterval(keepAlive);
+ clearTimeout(attachDeadline);
+ views.delete(partition);
+ host.removeListener('destroyed', view.close);
+ ses.protocol.unhandle('cindy-ghost');
+ if (guest && !guest.isDestroyed()) guest.close();
+ void ses.clearStorageData().catch(() => {});
+ },
+ attach: (attached) => {
+ if (guest) {
+ attached.close();
+ return;
+ }
+ guest = attached;
+ clearTimeout(attachDeadline);
+ registerGhostWebContents(guest.id);
+ guest.setWindowOpenHandler(() => ({ action: 'deny' }));
+ guest.on('will-navigate', (event, url) => {
+ try {
+ assertCurrent();
+ const target = new URL(url);
+ if (
+ target.protocol === 'cindy-ghost:' &&
+ target.hostname === doc.manifestId &&
+ doc.files.some((f) => '/' + f.path === target.pathname)
+ )
+ return;
+ event.preventDefault();
+ if (['https:', 'http:'].includes(target.protocol))
+ void (async () => {
+ const answer = await prompt({
+ type: 'question',
+ message: url,
+ buttons: [
+ t('settings.ghosts.connections.confirmAllow'),
+ t('settings.ghosts.connections.confirmCancel'),
+ ],
+ defaultId: 1,
+ cancelId: 1,
+ });
+ assertCurrent();
+ if (answer.response === 0) await shell.openExternal(url);
+ })().catch(() => {});
+ } catch {
+ event.preventDefault();
+ }
+ });
+ guest.once('destroyed', view.close);
+ },
+ };
+ views.set(partition, view);
+ host.once('destroyed', view.close);
+ return { id, partition, src };
+}
+
+async function readBody(request: Request): Promise<string> {
+ const reader = request.body?.getReader();
+ if (!reader) return '';
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ try {
+ for (;;) {
+ const part = await reader.read();
+ if (part.done) break;
+ size += part.value.length;
+ if (size > 65_536) throw unavailable();
+ chunks.push(part.value);
+ }
+ return Buffer.concat(chunks).toString('utf8');
+ } finally {
+ await reader.cancel();
+ }
+}
diff --cc apps/desktop/src/main/device-link/ipc.ts
index 02feebb56f,1bb4deb77e..b242b7fa97
--- a/apps/desktop/src/main/device-link/ipc.ts
+++ b/apps/desktop/src/main/device-link/ipc.ts
@@@ -1667,8 -1547,7 +1675,8 @@@ export function registerDeviceLinkIpc(d
});
ipcMain.handle(DEVICE_LINK_INVOKE.INVOKE, (e, payload: unknown) => {
requireDeviceLinkCapability();
- const p = (payload ?? {}) as { deviceId?: unknown; channel?: unknown; args?: unknown };
+ const p = (payload ?? {}) as { deviceId?: unknown; channel?: unknown; args?: unknown; scheduling?: unknown };
+ if (isRemoteSkillApproval(p.channel, p.args)) throwIpcError('PERMISSION_DENIED', 'Skill approval requires the native confirmation');
if (typeof p.deviceId === 'string' && parseProviderShareAgentDeviceId(p.deviceId)) {
assertTrustedAppRendererEvent(e);
return handleProviderShareInvoke(deps, p.deviceId, p.channel, p.args);
diff --cc apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
index 54101e63bc,54101e63bc..64be003f09
--- a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts
@@@ -2473,7 -2473,7 +2473,7 @@@ describe('Agent custom marketplace boun
expect(h.ledger.read()).toEqual(before);
});
-- it('forwards live authority to custom package placement after packaging', async () => {
++ it.each(['early', 'late'])('forwards live authority to the %s custom package commit', async (stage) => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-custom-agent-'));
roots.push(root);
const dir = writeLocalMarket(root, 'team-lib', [{ rel: 'plugins/alpha', id: 'alpha' }]);
@@@ -2482,8 -2482,8 +2482,10 @@@
let current = true;
const place = vi.fn();
runtime.install.mockImplementation(async (_file, options) => {
++ if (stage === 'late') options.beforeCommitInLock?.();
current = false;
-- options.beforeCommitInLock?.();
++ if (stage === 'early') options.beforeCommitInLock?.();
++ else options.assertCurrent?.();
place();
throw new Error('unreachable');
});
diff --cc apps/desktop/src/main/plugin-market/__tests__/service.test.ts
index 69fa5f61b9,69fa5f61b9..665dce8594
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@@ -5935,6 -5935,6 +5935,27 @@@ describe('Agent catalog discovery and i
expect(place).not.toHaveBeenCalled();
expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
});
++ it('keeps caller authority available after the early market commit check', async () => {
++ const item = summary();
++ const h = harness([item]);
++ let current = true;
++ const place = vi.fn();
++ runtime.install.mockImplementation(async (_file, options) => {
++ options.beforeCommitInLock?.();
++ await Promise.resolve();
++ current = false;
++ options.assertCurrent?.();
++ place();
++ throw new Error('unreachable');
++ });
++ await expect(h.service.install(item.id, reviewedInstallOptions(item), {
++ ...TEST_INSTALL_CONTEXT,
++ assertCurrent: vi.fn(),
++ assertScope: () => { if (!current) throw new Error('authority expired'); },
++ })).rejects.toThrow('authority expired');
++ expect(place).not.toHaveBeenCalled();
++ expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();
++ });
});
describe('PluginMarketService install consent', () => {
diff --cc apps/desktop/src/main/plugin-market/install.ts
index 607c296fde,607c296fde..c20892cec5
--- a/apps/desktop/src/main/plugin-market/install.ts
+++ b/apps/desktop/src/main/plugin-market/install.ts
@@@ -75,6 -75,6 +75,7 @@@ export interface PackedCustomMarketPlug
}
type CustomMarketCommitHooks = {
++ assertCurrent?: () => void;
sourceChanged?: boolean | (() => boolean);
expectedInstalledApproval?: string;
beforeCommit?: () => void | Promise<void>;
@@@ -248,6 -248,6 +249,7 @@@ export async function commitCustomMarke
ghostId: input.expectedGhostId,
version: input.expectedVersion,
consent: input.consent,
++ assertCurrent: input.assertCurrent,
...((typeof input.sourceChanged === 'function' ? input.sourceChanged() : input.sourceChanged)
? { sourceChanged: true } : {}),
// 发现时读到的规范化 Manifest 是这次安装允许的能力上限。打包窗口
diff --cc apps/desktop/src/main/plugin-market/service.ts
index 0a582512d0,0a582512d0..a7fbecb7af
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@@ -561,8 -561,8 +561,10 @@@ export interface PluginMarketSnapshotOp
*/
export interface PluginMarketInstallContext {
consent: { prompt: GhostInstallConsentPrompt; initiator: GhostInstallConsentInitiator };
-- /** Main-only caller authority, rechecked immediately before package placement. */
++ /** Main-only caller authority and installed approval, checked before replacement. */
assertCurrent?: () => void;
++ /** Owner/peer/cancellation only; remains valid after the package directory swap. */
++ assertScope?: () => void;
}
/**
@@@ -1455,7 -1455,7 +1457,7 @@@ export class PluginMarketService
options: PluginMarketInstallOptions,
context: PluginMarketInstallContext,
): Promise<PluginMarketInstallResult> {
-- const { assertCurrent } = context;
++ const { assertCurrent, assertScope = assertCurrent } = context;
assertCurrent?.();
const customRef = parseCustomMarketPluginId(pluginId);
if (customRef) {
@@@ -1471,6 -1471,6 +1473,7 @@@
},
captureMarketOwner(),
assertCurrent,
++ assertScope,
);
}
if (!isValidPluginResourceId(pluginId)) {
@@@ -1515,6 -1515,6 +1518,7 @@@
origin: 'market',
},
beforeCommitInLock: assertCurrent,
++ assertCurrent: assertScope,
expectedInstalled: Boolean(existing),
acquireMutation: true,
...(options.expectedInstalledApproval !== undefined
@@@ -1731,6 -1731,6 +1735,7 @@@
consent: GhostInstallConsentPolicy,
owner = captureMarketOwner(),
assertCurrent?: () => void,
++ assertScope = assertCurrent,
): Promise<PluginMarketInstallResult> {
const automatic = consent.mode === 'automatic';
if (options.expectedManifest === undefined) {
@@@ -1902,6 -1902,6 +1907,7 @@@
sourceChanged = Boolean(current && !routeStillMatches);
},
expectedInstalledApproval: options.expectedInstalledApproval,
++ assertCurrent: assertScope,
beforePackagePlacement: () => {
requireSameMarketOwner(owner);
assertCurrent?.();
@@@ -2222,6 -2222,6 +2228,7 @@@
/** 是否保留现有来源,或按明确意图切换来源。 */
sourceReplacementMode?: ServerSourceReplacementMode;
beforeCommitInLock?: () => void;
++ assertCurrent?: () => void;
/** 发起操作时的安装意图;下载窗口期目标被另一窗口卸载时拒绝滑入首装。 */
expectedInstalled: boolean;
/**
@@@ -2380,6 -2380,6 +2387,7 @@@
options.beforeCommitInLock?.();
}
: options.beforeCommitInLock,
++ assertCurrent: options.assertCurrent,
},
owner,
ledger,
@@@ -2407,6 -2407,6 +2415,7 @@@
expectedInstalledApproval?: string;
sourceReplacementMode: ServerSourceReplacementMode;
beforeCommitInLock?: () => void;
++ assertCurrent?: () => void;
expectedInstalled: boolean;
verifiedServerRoot?: string;
},
@@@ -2486,6 -2486,6 +2495,7 @@@
pluginId: plugin.id,
version: plugin.currentRelease.version,
consent: options.consent,
++ assertCurrent: options.assertCurrent,
...(options.reclaimLegacyBareInstance && !installedNow ? { reclaimLegacyBareInstance: true } : {}),
...(sourceChanged ? { sourceChanged: true } : {}),
...deliveryNamespaceFields(plugin),
diff --cc apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
index bbf6cc13b2,72cf5afebb..0340fdf069
--- a/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
@@@ -1,10 -1,9 +1,11 @@@
import { Button } from '@/components/ui/button';
+ import { ErrorNotice } from '@/components/ui/error-notice';
import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
- import { CircleAlert, LayoutGrid, MoonStar } from 'lucide-react';
+ import { LayoutGrid, MoonStar } from 'lucide-react';
import type { WebviewTag } from 'electron';
+import { AddRemoteProjectDialog } from '@/components/new-chat/AddRemoteProjectDialog';
+import type { RemotePluginSettingsDirectory } from '../../shared/remotePluginSettings';
import { useAuth } from '@/contexts/AuthContext';
import { cn } from '@/lib/utils';
diff --cc apps/desktop/src/renderer/cindy-brain/PluginTaskPrefs.tsx
index f74b37e625,5f57e06696..5524ab3e5e
--- a/apps/desktop/src/renderer/cindy-brain/PluginTaskPrefs.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/PluginTaskPrefs.tsx
@@@ -256,90 -205,72 +257,86 @@@ export function PluginTaskPrefs(
</>,
)}
- {showTaskRows ? row(
- 'permission',
- <div className="flex min-w-0 flex-1 flex-col gap-1">
- <PermissionSelector
- disabled={saving}
- permissionMode={permissionMode}
- fallbackModeLabel={permissionMode === 'plan' ? t('settings.ghosts.detail.errandPrefs.legacyPermission') : undefined}
- vendorKey={vendor}
- triggerVariant="field"
- ariaContext={t('settings.ghosts.detail.errandPrefs.permission')}
- disabledModes={{
- default: t('settings.ghosts.detail.errandPrefs.permissionDisabled'),
- bypassPermissions: t('settings.ghosts.detail.errandPrefs.permissionDisabled'),
- }}
- onPermissionModeChange={(mode) => {
- // disabledModes 已灰置非法档;这里再执一道白名单(UI 不是安全边界,
- // 存储层与协议层各有一道,三道口径一致)。
- if (!PERMISSION_ALLOWED.has(mode)) return;
- save({
- ...config,
- permissionMode: mode as 'ask' | 'acceptEdits' | 'auto',
- });
- }}
- />
- {legacyDefault && config.permissionMode === undefined ? (
- <p className="text-12 leading-4 text-[var(--text-tertiary)]">
- {t('settings.ghosts.detail.errandPrefs.legacyPermissionHint')}
- </p>
- ) : null}
- </div>,
- ) : null}
+ {showTaskRows
+ ? row(
+ 'permission',
+ <div className="flex min-w-0 flex-1 flex-col gap-1">
+ <PermissionSelector
+ disabled={saving || disabled}
+ permissionMode={permissionMode}
+ fallbackModeLabel={
+ permissionMode === 'plan'
+ ? t('settings.ghosts.detail.errandPrefs.legacyPermission')
+ : undefined
+ }
+ vendorKey={vendor}
+ triggerVariant="field"
+ ariaContext={t('settings.ghosts.detail.errandPrefs.permission')}
+ disabledModes={{
+ default: t('settings.ghosts.detail.errandPrefs.permissionDisabled'),
+ bypassPermissions: t('settings.ghosts.detail.errandPrefs.permissionDisabled'),
+ }}
+ onPermissionModeChange={(mode) => {
+ // disabledModes 已灰置非法档;这里再执一道白名单(UI 不是安全边界,
+ // 存储层与协议层各有一道,三道口径一致)。
+ if (!PERMISSION_ALLOWED.has(mode)) return;
+ save({
+ ...config,
+ permissionMode: mode as 'ask' | 'acceptEdits' | 'auto',
+ });
+ }}
+ />
+ {legacyDefault && config.permissionMode === undefined ? (
+ <p className="text-12 leading-4 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.detail.errandPrefs.legacyPermissionHint')}
+ </p>
+ ) : null}
+ </div>,
+ )
+ : null}
- {showTaskRows ? row(
- 'workdir',
- <>
- <span
- className={cn('min-w-0 flex-1 truncate text-[var(--text-tertiary)]', textCls)}
- title={config.workingDir}
- >
- {config.workingDir ?? t('settings.ghosts.detail.errandPrefs.workdirDefault')}
- </span>
- {config.workingDir ? (
- <button
- type="button"
- onClick={() => save({ ...config, workingDir: undefined })}
- aria-label={t('settings.ghosts.detail.errandPrefs.workdirClear')}
- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-[var(--text-tertiary)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-secondary)]"
- >
- <X size={13} />
- </button>
- ) : null}
- <Button
- variant="secondary"
- size="md"
- compact
- type="button"
- onClick={() => void pickWorkingDir()}
- className="shrink-0"
- >
- <FolderOpen size={13} />
- {t('settings.ghosts.detail.errandPrefs.workdirPick')}
- </Button>
- </>,
+ {showTaskRows ? (
+ remote ? (
+ <p className="text-12 leading-5 text-[var(--text-tertiary)]">
+ {t('settings.ghosts.remote.taskWorkdirBoundary')}
+ </p>
+ ) : (
+ row(
+ 'workdir',
+ <>
+ <span
+ className={cn('min-w-0 flex-1 truncate text-[var(--text-tertiary)]', textCls)}
+ title={config.workingDir}
+ >
+ {config.workingDir ?? t('settings.ghosts.detail.errandPrefs.workdirDefault')}
+ </span>
+ {config.workingDir ? (
+ <button
+ type="button"
+ onClick={() => save({ ...config, workingDir: undefined })}
+ aria-label={t('settings.ghosts.detail.errandPrefs.workdirClear')}
+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-[var(--text-tertiary)] hover:bg-[var(--surface-hover)] hover:text-[var(--text-secondary)]"
+ >
+ <X size={13} />
+ </button>
+ ) : null}
+ <Button
+ variant="secondary"
+ size="md"
+ compact
+ type="button"
+ onClick={() => void pickWorkingDir()}
+ className="shrink-0"
+ >
+ <FolderOpen size={13} />
+ {t('settings.ghosts.detail.errandPrefs.workdirPick')}
+ </Button>
+ </>,
+ )
+ )
) : null}
- {error ? (
- <p role="alert" className="text-12 leading-5 text-[var(--text-secondary)]">
- {error}
- </p>
- ) : null}
+ {error ? <ErrorNotice role="alert" message={error} /> : null}
</fieldset>
);
}
diff --cc apps/desktop/src/renderer/features/skillhub/RemoteSkillsPage.tsx
index 9c321b145b,0000000000..5f00152e40
mode 100644,000000..100644
--- a/apps/desktop/src/renderer/features/skillhub/RemoteSkillsPage.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/RemoteSkillsPage.tsx
@@@ -1,645 -1,0 +1,660 @@@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import {
+ REMOTE_RESOURCE_CHANGED_CHANNEL,
+ parseRemoteResourceChangedPayload,
+} from '@cindy/device-link';
+import {
+ getDataOwnerGeneration,
+ isDataOwnerGenerationCurrent,
+} from '@/contexts/dataOwnerGeneration';
+import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';
+import { Button } from '@/components/ui/button';
+import { Select } from '@/components/ui/select';
+import { toast } from '@/lib/toast';
++import { extractIpcError } from '@/utils/ipcError';
+import { CatalogManagementNotice } from '@/features/plugin/PluginManagementLayout';
+import type { CatalogDevice, CatalogDeviceControl } from '@/features/plugin/useCatalogDevice';
+import {
+ parseRemoteSkillReceipt,
+ type RemoteSkillItem,
+ type RemoteSkillMutation,
+ type RemoteSkillProject,
+ type RemoteSkillReceipt,
+ type RemoteSkillsSnapshot,
+} from '../../../shared/remoteSkills';
+import {
+ invokeRemoteSkills,
+ parseRemoteSkills,
+ remoteSkillsCapabilities,
+} from './remoteSkillsClient';
+import {
+ SkillhubTargetContext,
+ useSkillhubTarget,
+ type SkillhubTarget,
+ type SkillhubBrowseApi,
+} from './SkillhubTargetContext';
+import { SkillhubHomeContent } from './SkillhubHomeView';
+import { SkillhubMarketListView } from './SkillhubMarketListView';
+import { SkillhubDetailView } from './SkillhubDetailView';
+import { SkillhubMarketDetailView } from './SkillhubMarketDetailView';
+import { LocalSkillControls } from './components/LocalSkillControls';
+import { InstallTargetPicker } from './components/InstallTargetPicker';
+import { SkillDetailHeader, SkillDetailPage } from './components/SkillDetailLayout';
+import { useMarketSkillUpdate } from './hooks/useMarketSkillUpdate';
+import type { MarketSkill } from './hooks/useMarketList';
+import { marketInfoViewModel } from './lib/marketInfoViewModel';
+import { marketLocalCopies } from './lib/marketLocalCopies';
+
+type Detail = { localId?: string; market?: MarketSkill; showingMarket: boolean };
+
+/** The normal Skill pages, with a target-scoped store and fixed remote executors. */
+export function RemoteSkillsPage({
+ device,
+ online,
+ embedded,
+ active = true,
+ deviceControl,
+ onSelectCatalogTab,
+}: {
+ device: CatalogDevice;
+ online: boolean;
+ embedded?: boolean;
+ active?: boolean;
+ deviceControl?: CatalogDeviceControl;
+ onSelectCatalogTab?: (tab: 'plugins' | 'skills') => void;
+}) {
+ const { t } = useTranslation();
+ const [snapshot, setSnapshot] = useState<RemoteSkillsSnapshot | null>(null);
+ const [capabilities, setCapabilities] = useState({ management: false, catalog: false });
+ const [status, setStatus] = useState<'readFailed' | 'unknown' | null>(null);
+ const [checked, setChecked] = useState(false);
+ const [page, setPage] = useState<'home' | 'market'>('home');
+ const [visitedMarket, setVisitedMarket] = useState(false);
+ const [detail, setDetail] = useState<Detail | null>(null);
+ const [receipt, setReceipt] = useState<RemoteSkillReceipt | null>(null);
+ const owner = useRef(getDataOwnerGeneration()).current;
+ const alive = useRef(true),
+ onlineRef = useRef(online),
+ revision = useRef(0);
+ onlineRef.current = online;
+ const operation = useRef<{ id: string; resolve(result: RemoteSkillReceipt): void } | null>(null);
+ const confirming = useRef(new Set<string>());
+ const snapshotRef = useRef(snapshot);
+ snapshotRef.current = snapshot;
+ const current = useCallback(() => alive.current && isDataOwnerGenerationCurrent(owner), [owner]);
+ const writable = useCallback(() => current() && onlineRef.current, [current]);
+ const invoke = useCallback(
+ (action: string, input?: Record<string, unknown>, item?: RemoteSkillItem) =>
+ invokeRemoteSkills(device.deviceId, action, input, item),
+ [device.deviceId],
+ );
+ const rootFor = useCallback(
+ (item: RemoteSkillItem) =>
+ `remote-skill/${encodeURIComponent(device.deviceId)}/${owner.generation}/${item.id}/${item.revision}`,
+ [device.deviceId, owner],
+ );
+ const toSkill = useCallback(
+ (item: RemoteSkillItem): SkillhubSkill => {
+ const root = rootFor(item);
+ const entryFile =
+ item.entryFile && !/[\\/]/.test(item.entryFile) && !['.', '..'].includes(item.entryFile)
+ ? item.entryFile
+ : item.kind === 'skill'
+ ? 'SKILL.md'
+ : `${item.name}.md`;
+ return {
+ id: item.id,
+ urlKey: item.id,
+ sourceKey: item.id,
+ engine: 'claude-code',
+ kind: item.kind,
+ scope: item.scope,
+ name: item.name,
+ description: item.description,
+ absolutePath: root,
+ discoveredPath: root,
+ mdPath: `${root}/${entryFile}`,
+ files: [],
+ projectRoot: item.projectId ? `remote-project/${item.projectId}` : item.project,
+ projectHash: item.projectId,
+ linkedEngines: item.engines.map((label) => ({ engine: 'claude-code' as const, label })),
+ cindyEnabled: item.enabled,
+ canUninstall: item.canUninstall,
+ managedByPlugin: item.managedByPlugin,
+ builtIn: item.builtIn,
+ registrySkillName: item.market?.name,
+ registryEntry: item.market
+ ? {
+ version: item.version ?? '',
+ catalogScope: item.market.catalogScope,
+ origin: item.market.origin ?? 'installed',
+ authorId: item.market.authorId ?? '',
+ folderHash: '',
+ installedAt: 0,
+ updatedAt: 0,
+ }
+ : null,
+ };
+ },
+ [rootFor],
+ );
+ const refresh = useCallback(async () => {
+ if (!writable()) return [];
+ const read = ++revision.current;
+ try {
+ const nextCapabilities = await remoteSkillsCapabilities(device.deviceId);
+ if (!writable() || read !== revision.current) return [];
+ setCapabilities(nextCapabilities);
+ setChecked(true);
+ if (!nextCapabilities.management) return [];
+ const next = parseRemoteSkills(await invoke('snapshot', { installedOnly: true }));
+ if (!writable() || read !== revision.current) return [];
+ setSnapshot(next);
+ snapshotRef.current = next;
+ setStatus((previous) => (previous === 'readFailed' ? null : previous));
+ return next.items.map(toSkill);
+ } catch {
+ if (writable() && read === revision.current) setStatus('readFailed');
+ return [];
+ }
+ }, [device.deviceId, invoke, toSkill, writable]);
+ const accept = useCallback(
+ (next: RemoteSkillReceipt) => {
+ if (!current() || next.operationId !== operation.current?.id) return;
+ setReceipt(next);
+ if (['succeeded', 'cancelled', 'failed'].includes(next.phase)) {
+ confirming.current.delete(next.operationId);
+ const pending = operation.current;
+ operation.current = null;
+ pending?.resolve(next);
+ setStatus(null);
+ if (next.phase === 'succeeded') void refresh();
+ }
+ },
+ [current, refresh],
+ );
+ const poll = useCallback(async () => {
+ const pending = operation.current;
+ if (!pending || !writable()) return;
+ try {
+ accept(
+ parseRemoteSkillReceipt(await invoke('operation', { operationId: pending.id }), pending.id),
+ );
+ } catch {
+ if (current() && operation.current === pending) setStatus('unknown');
+ }
+ }, [accept, current, invoke, writable]);
+ useEffect(() => {
+ alive.current = true;
+ return () => {
+ alive.current = false;
+ const pending = operation.current;
+ if (pending) {
+ pending.resolve({ operationId: pending.id, phase: 'cancelled' });
+ if (isDataOwnerGenerationCurrent(owner))
+ void invoke('cancel', { operationId: pending.id }).catch(() => {});
+ }
+ };
+ }, [invoke, owner]);
+ useEffect(() => {
+ if (!online) {
+ revision.current++;
+ return;
+ }
+ if (active) {
+ void refresh();
+ void poll();
+ }
+ }, [online, active, refresh, poll]);
+ useEffect(() => {
+ if (!online || !operation.current) return;
+ const timer = setInterval(() => {
+ void poll();
+ }, 1200);
+ return () => clearInterval(timer);
+ }, [online, receipt, poll]);
+ useEffect(() => {
+ if (!online || receipt?.phase !== 'confirmation' || confirming.current.has(receipt.operationId))
+ return;
+ const id = receipt.operationId;
+ confirming.current.add(id);
+ void window.electronAPI.deviceLink
+ .confirmSkillMutation(device.deviceId, id)
+ .then((result) => {
+ if (current()) accept(parseRemoteSkillReceipt(result, id));
+ })
+ .catch(() => {
+ confirming.current.delete(id);
+ if (current() && operation.current?.id === id) setStatus('unknown');
+ });
+ }, [online, receipt, device.deviceId, current, accept]);
+ useEffect(() => {
+ const focus = () => {
+ if (active) void refresh();
+ };
+ window.addEventListener('focus', focus);
+ const off = window.electronAPI.deviceLink.onRemotePush((push, stamp) => {
+ if (
+ active &&
+ push.deviceId === device.deviceId &&
+ push.channel === REMOTE_RESOURCE_CHANGED_CHANNEL &&
+ parseRemoteResourceChangedPayload(push.payload)?.collectionId === 'skills' &&
+ isDeviceLinkRemotePushCurrent(push, stamp)
+ )
+ void refresh();
+ });
+ return () => {
+ off();
+ window.removeEventListener('focus', focus);
+ };
+ }, [active, device.deviceId, refresh]);
+
+ const mutate = useCallback(
+ async (
+ kind: RemoteSkillMutation,
+ skill?: SkillhubSkill,
+ market?: { name: string; catalogScope?: 'market' | 'team'; latestVersion: string },
+ project?: RemoteSkillProject,
+ ) => {
+ if (!writable() || !capabilities.management || operation.current)
+ throw new Error('UNAVAILABLE');
+ const item = skill
+ ? snapshotRef.current?.items.find((entry) => entry.id === skill.id)
+ : undefined;
+ if (skill && !item) throw new Error('STALE_TARGET');
+ const id = crypto.randomUUID();
+ const completion = new Promise<RemoteSkillReceipt>((resolve) => {
+ operation.current = { id, resolve };
+ });
+ setReceipt({ operationId: id, phase: 'running' });
+ void (async () => {
+ try {
+ const next = parseRemoteSkillReceipt(
+ await invoke(
+ 'begin',
+ {
+ operationId: id,
+ kind,
+ ...(market
+ ? {
+ name: market.name,
+ catalogScope: market.catalogScope ?? 'market',
+ version: market.latestVersion,
+ }
+ : {}),
+ ...(project ? { projectId: project.id, projectRevision: project.revision } : {}),
+ },
+ item,
+ ),
+ id,
+ );
+ if (!current() || operation.current?.id !== id) return;
+ accept(next);
- } catch {
++ } catch (error) {
+ if (current() && operation.current?.id === id) {
++ const code = extractIpcError(error)?.code;
++ if (
++ code &&
++ [
++ 'NOT_FOUND',
++ 'INVALID_PARAMS',
++ 'UNSUPPORTED_CAPABILITY',
++ 'PERMISSION_DENIED',
++ ].includes(code)
++ ) {
++ accept({ operationId: id, phase: 'failed' });
++ void refresh();
++ return;
++ }
+ setReceipt({ operationId: id, phase: 'running' });
+ setStatus('unknown');
+ }
+ }
+ })();
+ return completion;
+ },
- [accept, capabilities.management, current, device.deviceId, invoke, writable],
++ [accept, capabilities.management, current, invoke, refresh, writable],
+ );
+ const api = useMemo<SkillhubBrowseApi>(() => {
+ const catalog = async <T,>(method: string, input: Record<string, unknown>): Promise<T> => {
+ if (!writable()) throw new Error('UNAVAILABLE');
+ const result = await invoke('catalog', { method, ...input });
+ if (!writable()) throw new Error('STALE_TARGET');
+ if (
+ !result ||
+ typeof result !== 'object' ||
+ typeof (result as { success?: unknown }).success !== 'boolean'
+ )
+ throw new Error('INVALID_RESPONSE');
+ return result as T;
+ };
+ const read = async <T,>(virtualPath: string, children: boolean): Promise<T> => {
+ if (!writable()) throw new Error('UNAVAILABLE');
+ const item = snapshotRef.current?.items.find(
+ (entry) => virtualPath === rootFor(entry) || virtualPath.startsWith(`${rootFor(entry)}/`),
+ );
+ if (!item) throw new Error('STALE_TARGET');
+ const relative = virtualPath.slice(rootFor(item).length).replace(/^\//, '');
+ if (!capabilities.catalog && !children && virtualPath === toSkill(item).mdPath) {
+ const result = (await invoke('detail', {}, item)) as { markdown?: unknown };
+ if (!writable() || typeof result?.markdown !== 'string')
+ throw new Error('INVALID_RESPONSE');
+ return { success: true, content: result.markdown } as T;
+ }
+ const result = await invoke(children ? 'children' : 'read-file', { path: relative }, item);
+ if (!writable()) throw new Error('STALE_TARGET');
+ return result as T;
+ };
+ return {
+ listMarket: (params) => catalog('list', { ...params, scope: params?.scope ?? 'market' }),
+ listCategories: (params) => catalog('categories', { scope: params?.scope ?? 'market' }),
+ info: (name, scope) => catalog('info', { name, scope: scope ?? 'market' }),
+ getPublishedFiles: ({ catalogScope, ...params }) =>
+ catalog('files', { ...params, scope: catalogScope ?? 'market' }),
+ readPublishedFile: ({ catalogScope, ...params }) =>
+ catalog('file', { ...params, scope: catalogScope ?? 'market' }),
+ getScanStatus: ({ slug, catalogScope, ...params }) =>
+ catalog('scan-status', { ...params, name: slug, scope: catalogScope ?? 'market' }),
+ listChildren: ({ dirPath }) => read(dirPath, true),
+ readSkill: ({ mdPath }) => read(mdPath, false),
+ readSiblingFile: ({ filePath }) => read(filePath, false),
+ };
+ }, [capabilities.catalog, invoke, rootFor, toSkill, writable]);
+ const skills = useMemo(() => (snapshot?.items ?? []).map(toSkill), [snapshot, toSkill]);
+ const projects = useMemo(
+ () =>
+ (snapshot?.projects ?? []).map((project) => ({
+ projectRoot: `remote-project/${project.id}`,
+ displayName: project.name,
+ hash: project.id,
+ target: project,
+ })),
+ [snapshot],
+ );
+ const state = useMemo<SkillhubTarget['state']>(
+ () => ({
+ skills,
+ projects,
+ sources: [],
+ loading: !snapshot,
+ error: status,
+ bootstrapped: !!snapshot,
+ learnSkillEnabled: false,
+ syncResults: new Map(),
+ syncError: null,
+ availableUninstalledCount: 0,
+ }),
+ [skills, projects, snapshot, status],
+ );
+ const target = useMemo<SkillhubTarget>(() => {
+ return {
+ name: device.name,
+ ready: online && capabilities.catalog,
+ writable: online && capabilities.management && !operation.current,
+ state,
+ projects,
+ api,
+ refresh,
+ current,
+ mutate,
+ openLocal: (skill) => setDetail({ localId: skill.id, showingMarket: false }),
+ openMarket: (market) => setDetail({ market, showingMarket: true }),
+ openMarketList: () => {
+ setVisitedMarket(true);
+ setPage('market');
+ },
+ back: () => {
+ if (detail) setDetail(null);
+ else setPage('home');
+ },
+ displayPath: (value) => {
+ const item = snapshot?.items.find(
+ (entry) => value === rootFor(entry) || value.startsWith(`${rootFor(entry)}/`),
+ );
+ const project = item?.project ? ` · ${item.project}` : '';
+ return item
+ ? `${device.name}${project} · ${item.name}${value.slice(rootFor(item).length)}`
+ : device.name;
+ },
+ };
+ }, [
+ snapshot,
+ state,
+ projects,
+ device.name,
+ online,
+ capabilities,
+ api,
+ refresh,
+ current,
+ mutate,
+ detail,
+ rootFor,
+ receipt,
+ ]);
+ const notice = (
+ <CatalogManagementNotice
+ className="mb-0"
+ title={t('settings.ghosts.remote.managingTarget', { device: device.name })}
+ warning={!online || !!status}
+ action={
+ online && (status || (checked && !capabilities.catalog)) ? (
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => {
+ if (operation.current) void poll();
+ else void refresh();
+ }}
+ >
+ {t('settings.ghosts.remote.retry')}
+ </Button>
+ ) : null
+ }
+ >
+ {!online
+ ? t('settings.ghosts.remote.offlineNotice', { device: device.name })
+ : status
+ ? t(
+ status === 'readFailed'
+ ? 'skillhub.remote.readFailed'
+ : 'settings.ghosts.remote.unknown',
+ )
+ : checked && !capabilities.catalog
+ ? t('skillhub.remote.unsupported')
+ : !snapshot
+ ? t('skillhub.remote.loading')
+ : t('settings.ghosts.remote.managingDescription')}
+ </CatalogManagementNotice>
+ );
+ return (
+ <SkillhubTargetContext.Provider value={target}>
+ <div className="relative h-full min-h-0 w-full">
+ <div
+ className="absolute inset-0"
+ style={{ visibility: page === 'home' && !detail ? 'visible' : 'hidden' }}
+ aria-hidden={page !== 'home' || !!detail}
+ inert={page !== 'home' || !!detail}
+ >
+ <SkillhubHomeContent
+ deviceControl={deviceControl}
+ embedded={embedded}
+ active={active && page === 'home' && !detail}
+ onSelectCatalogTab={onSelectCatalogTab}
+ notice={notice}
+ />
+ </div>
+ {visitedMarket && (
+ <div
+ className="absolute inset-0"
+ style={{ visibility: page === 'market' && !detail ? 'visible' : 'hidden' }}
+ aria-hidden={page !== 'market' || !!detail}
+ inert={page !== 'market' || !!detail}
+ >
+ <SkillhubMarketListView active={active && page === 'market' && !detail} />
+ </div>
+ )}
+ {detail && (
+ <RemoteSkillDetail
+ key={detail.localId ?? `${detail.market?.catalogScope}:${detail.market?.name}`}
+ detail={detail}
+ onChange={setDetail}
+ />
+ )}
+ </div>
+ </SkillhubTargetContext.Provider>
+ );
+}
+
+/** Source switching and management use the same detail components as this computer. */
+function RemoteSkillDetail({
+ detail,
+ onChange,
+}: {
+ detail: Detail;
+ onChange(value: Detail): void;
+}) {
+ const target = useSkillhubTarget()!;
+ const { t } = useTranslation();
+ const explicit = target.state.skills.find((skill) => skill.id === detail.localId);
+ const [market, setMarket] = useState<MarketSkill | null>(detail.market ?? null);
+ const [pickerOpen, setPickerOpen] = useState(false);
+ const update = useMarketSkillUpdate();
+ const reference = explicit?.registryEntry
+ ? {
+ name: explicit.registrySkillName ?? explicit.name,
+ catalogScope: explicit.registryEntry.catalogScope,
+ }
+ : detail.market;
+ useEffect(() => {
+ if (!reference || !target.ready) return;
+ let cancelled = false;
+ void target.api
+ .info(reference.name, reference.catalogScope)
+ .then((result) => {
+ if (!cancelled && result.success && result.info)
+ setMarket(marketInfoViewModel(result.info, explicit ?? null, reference.catalogScope));
+ })
+ .catch(() => {
+ if (!cancelled) toast.error(t('skillhub.unifiedDetail.marketUnavailable'));
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [
+ reference?.name,
+ reference?.catalogScope,
+ target.api,
+ target.ready,
+ explicit?.registryEntry?.version,
+ t,
+ ]);
+ const copies = market
+ ? marketLocalCopies(target.state.skills, market)
+ : explicit
+ ? [explicit]
+ : [];
+ const selected = explicit ?? copies[0];
+ const navigation = (
+ <div className="flex shrink-0 flex-wrap items-center gap-2 border-b border-[var(--border-default)] px-4 py-2">
+ <div
+ className="flex items-center gap-1"
+ role="group"
+ aria-label={t('skillhub.unifiedDetail.contentSource')}
+ >
+ {selected && (
+ <Button
+ variant={detail.showingMarket ? 'secondary' : 'primary'}
+ aria-pressed={!detail.showingMarket}
+ onClick={() => onChange({ ...detail, localId: selected.id, showingMarket: false })}
+ >
+ {t('skillhub.unifiedDetail.local')}
+ </Button>
+ )}
+ {market && (
+ <Button
+ variant={detail.showingMarket ? 'primary' : 'secondary'}
+ aria-pressed={detail.showingMarket}
+ onClick={() => onChange({ ...detail, market, showingMarket: true })}
+ >
+ {t('skillhub.unifiedDetail.market')}
+ </Button>
+ )}
+ </div>
+ {copies.length > 1 && (
+ <Select
+ label={t('skillhub.sidebar.marketInstalledHeading')}
+ value={selected?.id ?? ''}
+ className="max-w-sm"
+ onValueChange={(id) => onChange({ ...detail, localId: id })}
+ options={copies.map((copy) => ({
+ value: copy.id,
+ label: `${
+ copy.scope === 'global'
+ ? t('skillhub.detail.scopeGlobal')
+ : (target.projects.find((project) => project.projectRoot === copy.projectRoot)
+ ?.displayName ?? '')
+ } · ${target.displayPath(copy.absolutePath)}`,
+ }))}
+ />
+ )}
+ {detail.showingMarket && selected && (
+ <span
+ className="min-w-0 truncate text-xs text-[var(--text-secondary)]"
+ title={target.displayPath(selected.absolutePath)}
+ >
+ {target.displayPath(selected.absolutePath)}
+ </span>
+ )}
+ </div>
+ );
+ if (!detail.showingMarket && selected)
+ return (
+ <SkillhubDetailView
+ entryOverride={selected}
+ renderNavigation={() => navigation}
+ onUninstalled={target.back}
+ />
+ );
+ if (!market)
+ return (
+ <SkillDetailPage>
+ <SkillDetailHeader
+ title={explicit?.name ?? detail.market?.name ?? ''}
+ backLabel={t('skillhub.detail.backToSkillhub')}
+ onBack={target.back}
+ />
+ {navigation}
+ </SkillDetailPage>
+ );
+ const currentMarket = marketInfoViewModel(market, selected ?? null, market.catalogScope);
+ return (
+ <>
+ <SkillhubMarketDetailView
+ skill={currentMarket}
+ onClose={target.back}
+ navigation={navigation}
+ primaryAction="clone"
+ onClone={() => setPickerOpen(true)}
+ learnSkillEnabled={false}
+ onUpdate={update.update}
+ updating={update.updatingNames.has(market.name)}
+ localActions={
+ selected ? (
+ <LocalSkillControls key={selected.id} skill={selected} disabled={!target.writable} />
+ ) : null
+ }
+ />
+ <InstallTargetPicker
+ open={pickerOpen}
+ skill={currentMarket}
+ onClose={() => setPickerOpen(false)}
+ onInstallComplete={() => {
+ setPickerOpen(false);
+ void target.refresh();
+ }}
+ />
+ </>
+ );
+}
diff --cc apps/desktop/src/renderer/features/skillhub/__tests__/RemoteSkillsPage.test.tsx
index 869b3daacf,0000000000..dc74e0236e
mode 100644,000000..100644
--- a/apps/desktop/src/renderer/features/skillhub/__tests__/RemoteSkillsPage.test.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/__tests__/RemoteSkillsPage.test.tsx
@@@ -1,453 -1,0 +1,510 @@@
+// @vitest-environment jsdom
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { MemoryRouter } from 'react-router-dom';
+import { setDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';
+
+const mocks = vi.hoisted(() => ({
+ invoke: vi.fn(),
+ confirm: vi.fn(),
+ localScan: vi.fn(),
+ localInstall: vi.fn(),
+ localRead: vi.fn(),
+ t: (key: string) => key,
+ user: { id: 'owner', membershipKind: 'org' },
+}));
+vi.mock('react-i18next', async (original) => ({
+ ...(await original<typeof import('react-i18next')>()),
+ useTranslation: () => ({ t: mocks.t, i18n: { language: 'en' } }),
+}));
+vi.mock('@/contexts/AuthContext', () => ({
+ useAuth: () => ({ user: mocks.user, dataOwnerId: 'owner', mode: 'cloud' }),
+}));
+vi.mock('@/hooks/useCCSessions', () => ({
+ useCCSessions: () => ({ sessions: [], isLoading: false }),
+}));
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({
+ useConfirmDialog: () => ({ confirm: vi.fn() }),
+}));
+vi.mock('@/components/chat/MarkdownRenderer', () => ({
+ MarkdownRenderer: ({ content }: { content: string }) => <div>{content}</div>,
+}));
+vi.mock('@/features/cc-agent/NewMakerDraftRoute', () => ({ NEW_MAKER_DRAFT_KEY: 'draft' }));
+vi.mock('@/lib/composerDraftStore', () => ({ plainTextToTiptapDoc: vi.fn(), saveDraft: vi.fn() }));
+vi.mock('@/state/newMakerDraft', () => ({ resetDraftWorkspaceTargets: vi.fn() }));
+vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } }));
+// Local detail rendering has separate coverage; keep its production controls/executor here.
+vi.mock('../SkillhubDetailView', async () => {
+ const { useEffect, useState } = await import('react');
+ const { useSkillhubTarget } = await import('../SkillhubTargetContext');
+ const { LocalSkillControls } = await import('../components/LocalSkillControls');
+ return {
+ SkillhubDetailView: ({
+ entryOverride: skill,
+ renderNavigation,
+ onUninstalled,
+ }: {
+ entryOverride: SkillhubSkill;
+ renderNavigation: () => React.ReactNode;
+ onUninstalled: () => void;
+ }) => {
+ const target = useSkillhubTarget()!;
+ const [text, setText] = useState('');
+ useEffect(() => {
+ void target.api
+ .readSkill({ mdPath: skill.mdPath })
+ .then((result) => setText(result.content ?? ''));
+ }, [target.api, skill.mdPath]);
+ return (
+ <div>
+ {renderNavigation()}
+ <p>{text}</p>
+ <LocalSkillControls skill={skill} onUninstalled={onUninstalled} />
+ </div>
+ );
+ },
+ };
+});
+import { RemoteSkillsPage } from '../RemoteSkillsPage';
+
+const market = (name = 'public-skill', scope = 'market') => ({
+ name,
+ displayName: name === 'public-skill' ? 'Public skill' : name,
+ description: name + ' description',
+ authorId: 'author',
+ authorName: 'Target author',
+ isMine: false,
+ canManage: false,
+ latestVersion: '1.0.0',
+ visibility: 'PUBLIC',
+ visibleDeptIds: [],
+ categories: ['knowledge'],
+ tags: [{ slug: 'research', name: 'Research' }],
+ githubUrl: null,
+ publishedAt: '2026-10-01T00:00:00Z',
+ downloads: 321,
+ catalogScope: scope,
+});
+const snapshot = (device: string) => ({
+ version: 1,
+ items: [
+ {
+ id: 'physical-instance',
+ revision: 'r1',
+ name: device + ' installed',
+ description: 'Target-only local skill',
+ kind: 'skill',
+ scope: 'global',
+ engines: ['Codex'],
+ enabled: true,
+ canUninstall: true,
+ managedByPlugin: false,
+ builtIn: false,
+ market: { name: 'public-skill', catalogScope: 'market' },
+ version: '1.0.0',
+ },
+ ],
+ market: [],
+ nextCursor: null,
+ marketUnavailable: false,
+ projects: [{ id: 'project-b', revision: 'p1', name: 'Target project' }],
+});
+const requests = (action: string) =>
+ mocks.invoke.mock.calls.filter((call) => call[2]?.[0]?.actionId === 'management:' + action);
+const page = (id = 'B', online = true, active = true) => (
+ <MemoryRouter initialEntries={['/skillhub/local']}>
+ <RemoteSkillsPage
+ key={id}
+ device={{ deviceId: id, name: 'Computer ' + id }}
+ online={online}
+ active={active}
+ />
+ </MemoryRouter>
+);
+beforeEach(() => {
+ vi.clearAllMocks();
+ setDataOwnerGeneration('owner');
+ window.matchMedia = vi
+ .fn()
+ .mockReturnValue({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() });
+ mocks.confirm.mockImplementation(async (_device, operationId) => ({
+ operationId,
+ phase: 'succeeded',
+ }));
+ window.electronAPI = {
+ skillhub: { scan: mocks.localScan, install: mocks.localInstall, readSkill: mocks.localRead },
+ deviceLink: {
+ invoke: mocks.invoke,
+ confirmSkillMutation: mocks.confirm,
+ onRemotePush: () => () => {},
+ },
+ } as never;
+ mocks.invoke.mockImplementation(async (device, channel, [request]) => {
+ if (channel.endsWith(':manifest'))
+ return {
+ collections: [
+ { id: 'skills', actions: [{ id: 'management:snapshot' }, { id: 'management:catalog' }] },
+ ],
+ };
+ const input = request.input;
+ let result;
+ switch (request.actionId) {
+ case 'management:snapshot':
+ result = snapshot(device);
+ break;
+ case 'management:catalog': {
+ const scope = input.scope;
+ if (input.method === 'list')
+ result = {
+ success: true,
+ items: [
+ market(
+ input.cursor ? 'next-page' : scope === 'team' ? 'Team skill' : 'public-skill',
+ scope,
+ ),
+ ],
+ nextCursor: input.cursor ? null : '2',
+ };
+ if (input.method === 'categories')
+ result = {
+ success: true,
+ categories: [{ slug: 'knowledge', name: 'Knowledge', count: 40 }],
+ };
+ if (input.method === 'info') result = { success: true, info: market(input.name, scope) };
+ if (input.method === 'files')
+ result = {
+ success: true,
+ files: [{ path: 'SKILL.md', size: 18, language: 'markdown', truncated: false }],
+ };
+ if (input.method === 'file')
+ result = {
+ success: true,
+ file: { path: 'SKILL.md', content: '# Published target content', language: 'markdown' },
+ };
+ break;
+ }
+ case 'management:read-file':
+ case 'management:detail':
+ result = {
+ success: true,
+ content: '# Target local content',
+ markdown: '# Target local content',
+ };
+ break;
+ case 'management:children':
+ result = { success: true, entries: [] };
+ break;
+ case 'management:begin':
+ result = {
+ operationId: input.operationId,
+ phase: ['enable', 'disable'].includes(input.kind) ? 'succeeded' : 'confirmation',
+ ...(['enable', 'disable'].includes(input.kind)
+ ? {}
+ : {
+ confirmation: {
+ requestId: 'confirm',
+ kind: input.kind,
+ name: input.name ?? 'Target local',
+ },
+ }),
+ };
+ break;
+ default:
+ result = { operationId: input.operationId, phase: 'running' };
+ }
+ return { result, effects: [] };
+ });
+});
+afterEach(cleanup);
+
+describe('full Skill Hub bound to the selected computer', () => {
+ it('shows original market cards/categories and target installed state together', async () => {
+ render(page());
+ await screen.findByText('Public skill');
+ expect(screen.getByText('Target author')).toBeTruthy();
+ expect(screen.getByText('321')).toBeTruthy();
+ expect(await screen.findByRole('radio', { name: 'Knowledge' })).toBeTruthy();
+ expect(screen.getByText('skillhub.home.installed')).toBeTruthy();
+ expect(screen.getByText('settings.ghosts.remote.managingDescription')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'settings.ghosts.remote.retry' })).toBeNull();
+ expect(screen.queryByText('B installed')).toBeNull();
+ fireEvent.click(screen.getByRole('radio', { name: 'skillhub.home.local' }));
+ await screen.findByText('B installed');
+ expect(screen.queryByText('Public skill')).toBeNull();
+ expect(screen.getByText('settings.ghosts.remote.managingDescription')).toBeTruthy();
+ expect(requests('snapshot')[0][2][0].input).toEqual({ installedOnly: true });
+ expect(mocks.localScan).not.toHaveBeenCalled();
+ });
+ it('paginates and sends category/search/organization filters to the selected Host', async () => {
+ render(page());
+ await screen.findByText('Public skill');
+ fireEvent.click(screen.getByText('skillhub.home.loadMore'));
+ await screen.findByText('next-page');
+ expect(
+ requests('catalog').some((call) => call[0] === 'B' && call[2][0].input.cursor === '2'),
+ ).toBe(true);
+ fireEvent.click(screen.getByRole('radio', { name: 'Knowledge' }));
+ await waitFor(() =>
+ expect(requests('catalog').some((call) => call[2][0].input.category === 'knowledge')).toBe(
+ true,
+ ),
+ );
+ fireEvent.click(
+ screen.getByRole('radio', { name: 'skillhub.home.catalogFilter.organization' }),
+ );
+ await screen.findByText('Team skill');
+ expect(screen.queryByText('Public skill')).toBeNull();
+ expect(screen.queryByText('B installed')).toBeNull();
+ fireEvent.change(screen.getByRole('textbox', { name: 'skillhub.home.search' }), {
+ target: { value: 'Team' },
+ });
+ await waitFor(() =>
+ expect(
+ requests('catalog').some(
+ (call) => call[2][0].input.q === 'Team' && call[2][0].input.scope === 'team',
+ ),
+ ).toBe(true),
+ );
+ });
+ it('keeps the complete installed list when an older Host reports a built-in user scope', async () => {
+ const original = mocks.invoke.getMockImplementation()!;
+ mocks.invoke.mockImplementation(async (device, channel, args) => {
+ const response = await original(device, channel, args);
+ if (args[0].actionId === 'management:snapshot') {
+ response.result.items.push({
+ ...snapshot(device).items[0],
+ id: 'built-in',
+ name: 'Built-in user skill',
+ scope: 'user',
+ builtIn: true,
+ canUninstall: false,
+ });
+ }
+ return response;
+ });
+ render(page());
+ await screen.findByText('Public skill');
+ fireEvent.click(screen.getByRole('radio', { name: 'skillhub.home.local' }));
+ await screen.findByText('B installed');
+ expect(screen.getByText('Built-in user skill')).toBeTruthy();
+ expect(mocks.localScan).not.toHaveBeenCalled();
+ });
+ it('associates the target author’s published copy with its visible market record', async () => {
+ const original = mocks.invoke.getMockImplementation()!;
+ mocks.invoke.mockImplementation(async (device, channel, args) => {
+ const response = await original(device, channel, args);
+ if (args[0].actionId === 'management:snapshot') {
+ response.result.items[0].market = {
+ name: 'public-skill',
+ origin: 'published',
+ authorId: 'author',
+ };
+ }
+ if (args[0].actionId === 'management:catalog' && args[0].input.method === 'list') {
+ Object.assign(response.result.items[0], { isMine: true, isCreator: true, canManage: true });
+ }
+ return response;
+ });
+ render(page());
+ await screen.findByText('Public skill');
+ await screen.findByText('skillhub.home.installed');
+ expect(mocks.localScan).not.toHaveBeenCalled();
+ });
+ it.each(['learned', 'imported'])('keeps %s target copies readable', async (origin) => {
+ const original = mocks.invoke.getMockImplementation()!;
+ mocks.invoke.mockImplementation(async (device, channel, args) => {
+ const response = await original(device, channel, args);
+ if (args[0].actionId === 'management:snapshot') {
+ response.result.items[0].market.origin = origin;
+ }
+ return response;
+ });
+ render(page());
+ await screen.findByText('Public skill');
+ fireEvent.click(screen.getByRole('radio', { name: 'skillhub.home.local' }));
+ await screen.findByText('B installed');
+ expect(mocks.localScan).not.toHaveBeenCalled();
+ });
+ it('opens full market details and published content using the target Hub', async () => {
+ render(page());
+ fireEvent.click(await screen.findByText('Public skill'));
+ await screen.findByText('# Published target content');
+ expect(
+ requests('catalog')
+ .filter((call) => ['info', 'files', 'file'].includes(call[2][0].input.method))
+ .every((call) => call[0] === 'B'),
+ ).toBe(true);
+ expect(mocks.localRead).not.toHaveBeenCalled();
+ });
+ it('uses the original picker and installs to the target project with native confirmation', async () => {
+ render(page());
+ fireEvent.click(await screen.findByText('Public skill'));
+ await screen.findByText('# Published target content');
+ fireEvent.click(screen.getByRole('button', { name: 'skillhub.marketCard.clone' }));
+ fireEvent.click(
+ within(screen.getByRole('dialog')).getByRole('button', { name: /Target project/ }),
+ );
+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledOnce());
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(requests('begin')).toHaveLength(1);
+ expect(requests('begin')[0][0]).toBe('B');
+ expect(requests('begin')[0][2][0].input).toMatchObject({
+ kind: 'install',
+ name: 'public-skill',
+ catalogScope: 'market',
+ version: '1.0.0',
+ projectId: 'project-b',
+ projectRevision: 'p1',
+ });
+ expect(JSON.stringify(requests('begin')[0])).not.toContain('installPath');
+ expect(mocks.localInstall).not.toHaveBeenCalled();
+ });
+ it('can confirm the original operation after a lost native confirmation response and reconnect', async () => {
+ const original = mocks.invoke.getMockImplementation()!;
+ mocks.invoke.mockImplementation(async (device, channel, args) => {
+ if (args[0].actionId === 'management:operation')
+ return {
+ result: {
+ operationId: args[0].input.operationId,
+ phase: 'confirmation',
+ confirmation: { requestId: 'confirm', kind: 'install', name: 'Public skill' },
+ },
+ effects: [],
+ };
+ return original(device, channel, args);
+ });
+ mocks.confirm.mockRejectedValueOnce(new Error('CONNECTION_LOST'));
+ const ui = render(page());
+ fireEvent.click(await screen.findByText('Public skill'));
+ await screen.findByText('# Published target content');
+ fireEvent.click(screen.getByRole('button', { name: 'skillhub.marketCard.clone' }));
- fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: /Target project/ }));
++ fireEvent.click(
++ within(screen.getByRole('dialog')).getByRole('button', { name: /Target project/ }),
++ );
+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledOnce());
+ ui.rerender(page('B', false));
+ ui.rerender(page());
+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(2));
+ expect(requests('begin')).toHaveLength(1);
+ expect(mocks.confirm.mock.calls[1]).toEqual(mocks.confirm.mock.calls[0]);
+ expect(mocks.localInstall).not.toHaveBeenCalled();
+ });
+ it('toggles/uninstalls the displayed physical instance without local mutation IPC', async () => {
+ render(page());
+ fireEvent.click(screen.getByRole('radio', { name: 'skillhub.home.local' }));
+ fireEvent.click(await screen.findByText('B installed'));
+ await screen.findByText('# Target local content');
+ fireEvent.click(screen.getByRole('switch'));
+ await waitFor(() => expect(requests('begin')).toHaveLength(1));
+ expect(requests('begin')[0][2][0]).toMatchObject({
+ resourceRef: { id: 'physical-instance' },
+ input: { kind: 'disable', expectedRevision: 'r1' },
+ });
+ await userEvent.click(screen.getByRole('button', { name: 'skillhub.management.moreLabel' }));
+ await userEvent.click(screen.getByRole('menuitem', { name: 'skillhub.detail.uninstall' }));
+ await waitFor(() => expect(mocks.confirm).toHaveBeenCalledWith('B', expect.any(String)));
+ expect(requests('begin')[1][2][0].input.kind).toBe('uninstall');
+ expect(requests('answer')).toHaveLength(0);
+ });
++ it.each(['NOT_FOUND', 'INVALID_PARAMS', 'UNSUPPORTED_CAPABILITY', 'PERMISSION_DENIED'])(
++ 'unlocks and refreshes after begin is explicitly rejected with %s',
++ async (code) => {
++ const original = mocks.invoke.getMockImplementation()!;
++ let rejected = false;
++ mocks.invoke.mockImplementation(async (device, channel, args) => {
++ if (args[0].actionId === 'management:begin' && !rejected) {
++ rejected = true;
++ throw new Error(`[${code}] Request rejected`);
++ }
++ return original(device, channel, args);
++ });
++ render(page());
++ fireEvent.click(screen.getByRole('radio', { name: 'skillhub.home.local' }));
++ fireEvent.click(await screen.findByText('B installed'));
++ await screen.findByText('# Target local content');
++ const reads = requests('snapshot').length;
++ fireEvent.click(screen.getByRole('switch'));
++ await waitFor(() => {
++ expect(requests('begin')).toHaveLength(1);
++ expect((screen.getByRole('switch') as HTMLButtonElement).disabled).toBe(false);
++ expect(requests('snapshot').length).toBeGreaterThan(reads);
++ });
++ fireEvent.click(screen.getByRole('switch'));
++ await waitFor(() => expect(requests('begin')).toHaveLength(2));
++ expect(requests('begin')[1][2][0].input.operationId).not.toBe(
++ requests('begin')[0][2][0].input.operationId,
++ );
++ },
++ );
++ it('queries the same receipt after a lost begin response without replaying begin', async () => {
++ const original = mocks.invoke.getMockImplementation()!;
++ mocks.invoke.mockImplementation(async (device, channel, args) => {
++ if (args[0].actionId === 'management:begin') throw new Error('[TIMEOUT] Response lost');
++ if (args[0].actionId === 'management:operation')
++ return { result: { operationId: args[0].input.operationId, phase: 'succeeded' } };
++ return original(device, channel, args);
++ });
++ const ui = render(page());
++ fireEvent.click(screen.getByRole('radio', { name: 'skillhub.home.local' }));
++ fireEvent.click(await screen.findByText('B installed'));
++ await screen.findByText('# Target local content');
++ fireEvent.click(screen.getByRole('switch'));
++ await screen.findByText('settings.ghosts.remote.unknown');
++ expect((screen.getByRole('switch') as HTMLButtonElement).disabled).toBe(true);
++ ui.rerender(page('B', false));
++ ui.rerender(page());
++ await waitFor(() =>
++ expect((screen.getByRole('switch') as HTMLButtonElement).disabled).toBe(false),
++ );
++ expect(requests('begin')).toHaveLength(1);
++ expect(requests('operation')[0][2][0].input.operationId).toBe(
++ requests('begin')[0][2][0].input.operationId,
++ );
++ });
+ it('keeps offline content visible, disables writes and does not replay', async () => {
+ const ui = render(page());
+ fireEvent.click(screen.getByRole('radio', { name: 'skillhub.home.local' }));
+ fireEvent.click(await screen.findByText('B installed'));
+ await screen.findByText('# Target local content');
+ ui.rerender(page('B', false));
+ expect((screen.getByRole('switch') as HTMLButtonElement).disabled).toBe(true);
+ expect(screen.getByText('# Target local content')).toBeTruthy();
+ expect(requests('begin')).toHaveLength(0);
+ });
+ it('discards old computer responses and does not read hidden targets', async () => {
+ const original = mocks.invoke.getMockImplementation()!;
+ let finish!: (value: unknown) => void;
+ mocks.invoke.mockImplementation((device, channel, args) =>
+ device === 'B' && args[0].actionId === 'management:snapshot'
+ ? new Promise((resolve) => {
+ finish = resolve;
+ })
+ : original(device, channel, args),
+ );
+ const ui = render(page('B', true, false));
+ expect(mocks.invoke).not.toHaveBeenCalled();
+ ui.rerender(page());
+ await waitFor(() => expect(finish).toBeTypeOf('function'));
+ ui.rerender(page('C'));
+ fireEvent.click(screen.getByRole('radio', { name: 'skillhub.home.local' }));
+ await screen.findByText('C installed');
+ await act(async () => finish({ result: snapshot('Late B'), effects: [] }));
+ expect(screen.queryByText('Late B installed')).toBeNull();
+ });
+ it('keeps older Hosts readable without falling back to this computer', async () => {
+ const original = mocks.invoke.getMockImplementation()!;
+ mocks.invoke.mockImplementation((device, channel, args) =>
+ channel.endsWith(':manifest')
+ ? { collections: [{ id: 'skills', actions: [{ id: 'management:snapshot' }] }] }
+ : original(device, channel, args),
+ );
+ render(page());
+ fireEvent.click(screen.getByRole('radio', { name: 'skillhub.home.local' }));
+ await screen.findByText('B installed');
+ expect(screen.getByText('skillhub.remote.unsupported')).toBeTruthy();
+ expect(requests('catalog')).toHaveLength(0);
+ expect(mocks.localScan).not.toHaveBeenCalled();
+ expect(mocks.localInstall).not.toHaveBeenCalled();
+ });
+});
diff --cc docs/design-rules/design-inventory.md
index 7a0e5903f6,f8205ebf31..aeef2e8e54
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@@ -33,18 -33,18 +33,18 @@@
| `desktop.overlay.find-in-page` | desktop | 页内查找条 | App → FindInPageBar | FindInPageBar | apps/desktop/src/renderer/components/find-in-page/FindInPageBar.tsx, apps/desktop/src/renderer/components/find-in-page/findInPageOwnership.ts | 4 | 0 | 4 |
| `desktop.overlay.interaction-portal` | desktop | 交互提问卡片 | components/interaction-portal(AskUser / 权限类卡片出口) | InteractionPromptCardShell, InteractionPromptHost | apps/desktop/src/renderer/components/interaction-portal/InteractionPromptCardShell.tsx, apps/desktop/src/renderer/components/interaction-portal/InteractionPromptHost.tsx, apps/desktop/src/renderer/components/interaction-portal/InteractionPromptSlot.tsx, apps/desktop/src/renderer/components/interaction-portal/index.ts, apps/desktop/src/renderer/components/interaction-portal/store.ts | 10 | 0 | 4 |
| `desktop.overlay.permission-prompt` | desktop | 权限询问 | PermissionPrompt(会话内权限卡;DS-9 迁移前置) | AskUserQuestionPrompt, PermissionPrompt, PermissionSelector | apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx | 51 | 2 | 21 |
- | `desktop.overlay.route-error` | desktop | 路由错误页 | router errorElement → RouteErrorFallback / TopLevelErrorBoundary | AppCrashScreen, RouteErrorFallback, TopLevelErrorBoundary | apps/desktop/src/renderer/components/error/AppCrashScreen.tsx, apps/desktop/src/renderer/components/error/LocalDbFatalScreen.tsx, apps/desktop/src/renderer/components/error/RouteErrorFallback.tsx, apps/desktop/src/renderer/components/error/TopLevelErrorBoundary.tsx, apps/desktop/src/renderer/components/error/localDbFatalView.ts | 8 | 0 | 4 |
+ | `desktop.overlay.route-error` | desktop | 路由错误页 | router errorElement → RouteErrorFallback / TopLevelErrorBoundary | AppCrashScreen, RouteErrorFallback, TopLevelErrorBoundary | apps/desktop/src/renderer/components/error/AppCrashScreen.tsx, apps/desktop/src/renderer/components/error/LocalDbFatalScreen.tsx, apps/desktop/src/renderer/components/error/RouteErrorFallback.tsx, apps/desktop/src/renderer/components/error/TopLevelErrorBoundary.tsx, apps/desktop/src/renderer/components/error/localDbFatalView.ts | 6 | 0 | 1 |
| `desktop.overlay.splash` | desktop | 启动遮罩 | App → SplashScreen;同源 gating 下并挂 LoginBrandStage(z-9980 品牌画布,启动期即可见、Splash(z-9999) 之下) | LoginBrandStage, SplashScreen | apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/splash/SplashScreen.tsx | 3 | 0 | 5 |
- | `desktop.overlay.toast` | desktop | Toast | App 常驻 ToastContainer(用户可见出口,不展开业务逻辑) | Toast, ToastContainer | apps/desktop/src/renderer/components/ui/toast/Toast.tsx, apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx, apps/desktop/src/renderer/components/ui/toast/index.ts | 5 | 4 | 3 |
+ | `desktop.overlay.toast` | desktop | Toast | App 常驻 ToastContainer(用户可见出口,不展开业务逻辑) | Toast, ToastContainer | apps/desktop/src/renderer/components/ui/toast/DownloadToast.tsx, apps/desktop/src/renderer/components/ui/toast/Toast.tsx, apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx, apps/desktop/src/renderer/components/ui/toast/index.ts | 7 | 4 | 3 |
| `desktop.plugins.app-main` | desktop | 插件主视图 | hash `/apps/:ghostId`(GhostMainViewFeatureLayout) | GhostMainViewFeatureLayout, GhostMainViewHost | apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx, apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx | 0 | 0 | 0 |
- | `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginActions, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginDevicePicker, PluginManagementLayout, PluginProjectMenu, RemotePluginConfiguration, RemotePluginPage, RemotePluginReadOnlyDetail, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginActions.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginDevicePicker.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/RemotePluginConfiguration.tsx, apps/desktop/src/renderer/features/plugin/RemotePluginPage.tsx, apps/desktop/src/renderer/features/plugin/RemotePluginReadOnlyDetail.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 29 | 0 | 48 |
- | `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/AvatarCropEditor.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BillingSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DialogueDirectorySection.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GeneralSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.settings-search.ts, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HarnessVersionMenuRow.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.settings-search.ts, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LlamaCppCandidates.tsx, apps/desktop/src/renderer/components/settings/LlamaCppProviderDetail.tsx, apps/desktop/src/renderer/components/settings/LocalModelDownloadUI.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/OwnRemoteProviders.tsx, apps/desktop/src/renderer/components/settings/PersonalizationDetails.settings-search.ts, apps/desktop/src/renderer/components/settings/PersonalizationSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/PiKernelVersionRow.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderImportDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/ReadOnlyProviderModels.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.settings-search.ts, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchBox.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchNavigation.ts, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SharedTasks.settings-search.ts, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.ts, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/VoiceSpeakerEnrollmentDialog.tsx, apps/desktop/src/renderer/components/settings/VoiceSpeakerFilterCard.tsx, apps/desktop/src/renderer/components/settings/WallpaperSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.settings-search.ts, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/avatarCropGeometry.ts, apps/desktop/src/renderer/components/settings/avatarCropImage.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dialogueDirectoryDisplay.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/settingsSearchCatalog.ts, apps/desktop/src/renderer/components/settings/settingsSearchTypes.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBarsTooltip.tsx, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageDeviceSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.settings-search.ts, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/useSettingsEscape.ts, apps/desktop/src/renderer/components/settings/useSettingsSectionTarget.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 139 | 100 | 550 |
- | `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, DeviceSectionHeader, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, ProjectsSection, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainEntryRedirect.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/WallpaperVideo.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/DatabaseSizeWarningBanner.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/NavigationCountBadge.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarNavigationCustomize.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/sidebar/sidebarNavigationPrefs.ts, apps/desktop/src/renderer/components/sidebar/useHoverOpenMenu.ts, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/DeviceSectionHeader.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/retired-feature/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 144 | 46 | 200 |
-| `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginManagementLayout, PluginScopePicker, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 27 | 0 | 48 |
++| `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginActions, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginDevicePicker, PluginManagementLayout, PluginProjectMenu, RemotePluginConfiguration, RemotePluginPage, RemotePluginReadOnlyDetail, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginActions.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginDevicePicker.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/RemotePluginConfiguration.tsx, apps/desktop/src/renderer/features/plugin/RemotePluginPage.tsx, apps/desktop/src/renderer/features/plugin/RemotePluginReadOnlyDetail.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 28 | 0 | 47 |
+ | `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.settings-search.ts, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/AvatarCropEditor.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BillingSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DialogueDirectorySection.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GeneralSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.settings-search.ts, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HarnessVersionMenuRow.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.settings-search.ts, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LlamaCppCandidates.tsx, apps/desktop/src/renderer/components/settings/LlamaCppProviderDetail.tsx, apps/desktop/src/renderer/components/settings/LocalModelDownloadUI.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.settings-search.ts, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/OwnRemoteProviders.tsx, apps/desktop/src/renderer/components/settings/PersonalizationDetails.settings-search.ts, apps/desktop/src/renderer/components/settings/PersonalizationSettings.settings-search.ts, apps/desktop/src/renderer/components/settings/PiKernelVersionRow.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderImportDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.settings-search.ts, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/ReadOnlyProviderModels.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.settings-search.ts, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.settings-search.ts, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchBox.tsx, apps/desktop/src/renderer/components/settings/SettingsSearchNavigation.ts, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SharedTasks.settings-search.ts, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.settings-search.ts, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.settings-search.ts, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.settings-search.ts, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/VoiceSpeakerEnrollmentDialog.tsx, apps/desktop/src/renderer/components/settings/VoiceSpeakerFilterCard.tsx, apps/desktop/src/renderer/components/settings/WallpaperSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.settings-search.ts, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.settings-search.ts, apps/desktop/src/renderer/components/settings/WorktreeRecycleCard.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/avatarCropGeometry.ts, apps/desktop/src/renderer/components/settings/avatarCropImage.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dialogueDirectoryDisplay.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/settingsRowClasses.ts, apps/desktop/src/renderer/components/settings/settingsSearchCatalog.ts, apps/desktop/src/renderer/components/settings/settingsSearchTypes.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBarsTooltip.tsx, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageDeviceSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageFilterSelect.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.settings-search.ts, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/useSettingsEscape.ts, apps/desktop/src/renderer/components/settings/useSettingsSectionTarget.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 136 | 95 | 542 |
+ | `desktop.shell.main-layout` | desktop | 主窗口壳(标题栏 / 左右栏 / 内容区) | main BrowserWindow → renderer/index.tsx → main-entry.tsx → App → MainLayout (`#/` 受保护壳) | ChromeActions, DeviceSectionHeader, FeishuConflictDialogHost, GhostMediaLightboxHost, MainLayout, ProjectsSection, RightSidebar, RightSidebarShell, SessionShareImportWizard, Sidebar, UpdateNoticeDialog, WindowControls | apps/desktop/src/renderer/cindy-brain/GhostMediaLightboxHost.tsx, apps/desktop/src/renderer/components/UpdateNoticeDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialog.tsx, apps/desktop/src/renderer/components/feishuBot/FeishuConflictDialogHost.tsx, apps/desktop/src/renderer/components/layout/AppBadgeAttentionSync.tsx, apps/desktop/src/renderer/components/layout/BrowserWebviewPool.tsx, apps/desktop/src/renderer/components/layout/ChromeActions.tsx, apps/desktop/src/renderer/components/layout/ContentHeader.tsx, apps/desktop/src/renderer/components/layout/CredentialStoreBanner.tsx, apps/desktop/src/renderer/components/layout/FadeSwitcher.tsx, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/components/layout/GlobalDropImportListener.tsx, apps/desktop/src/renderer/components/layout/MainEntryRedirect.tsx, apps/desktop/src/renderer/components/layout/MainLayout.tsx, apps/desktop/src/renderer/components/layout/RightSidebar.tsx, apps/desktop/src/renderer/components/layout/RightSidebarDetach.tsx, apps/desktop/src/renderer/components/layout/RightSidebarMaximize.tsx, apps/desktop/src/renderer/components/layout/RightSidebarToggle.tsx, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/components/layout/WallpaperVideo.tsx, apps/desktop/src/renderer/components/layout/chromeActionsGeometry.ts, apps/desktop/src/renderer/components/layout/chromeActionsLayout.ts, apps/desktop/src/renderer/components/layout/railChromeActions.ts, apps/desktop/src/renderer/components/layout/windowDrag.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/sidebar/AccountSwitcherDialog.tsx, apps/desktop/src/renderer/components/sidebar/AttentionDot.tsx, apps/desktop/src/renderer/components/sidebar/DatabaseSizeWarningBanner.tsx, apps/desktop/src/renderer/components/sidebar/GhostMainViewNavEntries.tsx, apps/desktop/src/renderer/components/sidebar/MobileDownloadDialog.tsx, apps/desktop/src/renderer/components/sidebar/NavigationCountBadge.tsx, apps/desktop/src/renderer/components/sidebar/Sidebar.tsx, apps/desktop/src/renderer/components/sidebar/SidebarIconButton.tsx, apps/desktop/src/renderer/components/sidebar/SidebarNavigationCustomize.tsx, apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx, apps/desktop/src/renderer/components/sidebar/SortableList.tsx, apps/desktop/src/renderer/components/sidebar/UpdateBanner.tsx, apps/desktop/src/renderer/components/sidebar/UserInfoSection.tsx, apps/desktop/src/renderer/components/sidebar/VendorIcon.tsx, apps/desktop/src/renderer/components/sidebar/VendorReadinessBadge.tsx, apps/desktop/src/renderer/components/sidebar/WorktreeBadge.tsx, apps/desktop/src/renderer/components/sidebar/sidebarNavigationPrefs.ts, apps/desktop/src/renderer/components/sidebar/useHoverOpenMenu.ts, apps/desktop/src/renderer/components/title-bar/ChromeIconButton.tsx, apps/desktop/src/renderer/components/title-bar/MenuButton.tsx, apps/desktop/src/renderer/components/title-bar/WindowControls.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/DeviceSectionHeader.tsx, apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useRetainedBrowserTabHosts.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/mergeSidebarWindowBack.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBotWorkbenchTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/retired-feature/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/tabAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/layout/LayoutRoot.tsx, apps/desktop/src/renderer/layout/PanelDragController.tsx, apps/desktop/src/renderer/layout/PanelDragPrototype.tsx, apps/desktop/src/renderer/layout/collapsePrefs.ts, apps/desktop/src/renderer/layout/layoutDevTools.ts, apps/desktop/src/renderer/layout/panePlacement.tsx, apps/desktop/src/renderer/layout/paneWidths.tsx, apps/desktop/src/renderer/layout/panelMaximize.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 143 | 46 | 196 |
-| `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及统一详情 `/skillhub/detail`(旧详情链接重定向) | InstallTargetPicker, PluginManagementLayout, SkillDetailLayout, SkillhubDetailRoute, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubLocalLayout, SkillhubMarketDetailView | apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubLocalLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx | 35 | 0 | 43 |
-| `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketDetailView, SkillhubMarketListView, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInstallStatus.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketListError.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/OfficialSkillBadge.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 43 | 0 | 37 |
+| `desktop.skillhub.local` | desktop | SkillHub 本地技能 | hash `/skillhub/local` 及统一详情 `/skillhub/detail`(旧详情链接重定向) | InstallTargetPicker, PluginDevicePicker, PluginManagementLayout, RemoteSkillsPage, SkillCategoryFilterBar, SkillDetailLayout, SkillhubDetailRoute, SkillhubDetailView, SkillhubFeatureLayout, SkillhubHomeView, SkillhubLocalLayout, SkillhubMarketDetailView | apps/desktop/src/renderer/features/plugin/PluginDevicePicker.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/skillhub/RemoteSkillsPage.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailRoute.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubFeatureLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubLocalLayout.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx, apps/desktop/src/renderer/features/skillhub/skillhub-home.css | 39 | 0 | 45 |
+| `desktop.skillhub.market` | desktop | SkillHub 市场 | hash `/skillhub/market`(SkillhubMarketListView) | InstallTargetPicker, MarketCard, MarketInfoEditDialog, SkillhubMarketDetailView, SkillhubMarketListView, VisibilityEditorDialog | apps/desktop/src/renderer/features/skillhub/SkillhubMarketDetailView.tsx, apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx, apps/desktop/src/renderer/features/skillhub/components/HomeMarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx, apps/desktop/src/renderer/features/skillhub/components/LocalSkillControls.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketCard.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInfoEditDialog.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketInstallStatus.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketListError.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketLocalSkills.tsx, apps/desktop/src/renderer/features/skillhub/components/MarketPreviewTree.tsx, apps/desktop/src/renderer/features/skillhub/components/OfficialSkillBadge.tsx, apps/desktop/src/renderer/features/skillhub/components/PlatformTagSelector.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillCategoryFilterBar.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillDetailLayout.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillIcon.tsx, apps/desktop/src/renderer/features/skillhub/components/SkillTagList.tsx, apps/desktop/src/renderer/features/skillhub/components/TeamScopePicker.tsx, apps/desktop/src/renderer/features/skillhub/components/VisibilityEditorDialog.tsx | 42 | 0 | 35 |
| `desktop.window.computer-permission-guide` | desktop | 电脑使用权限引导 | `?view=computer-permission-guide` → ComputerPermissionGuideWindow;backdrop 同文件 | ComputerPermissionBackdrop, ComputerPermissionGuideWindow | apps/desktop/src/main/computer-permission-guide/MacComputerPermissionGuideNativeHost.ts, apps/desktop/src/main/computer-permission-guide/placement.ts, apps/desktop/src/main/computer-permission-guide/request.ts, apps/desktop/src/main/computer-permission-guide/switch-target.ts, apps/desktop/src/main/computer-permission-guide/window.ts, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx | 7 | 2 | 9 |
| `desktop.window.ghost-panel` | desktop | 插件面板独立窗口 | `?ghostPanelWindow=<id>` → renderer/ghost-panel-window-entry.tsx;hash `/ghost-panel-window` | GhostPanelWindowLayout | apps/desktop/src/main/ghost-panel-window/controller.ts, apps/desktop/src/main/ghost-panel-window/ipc.ts, apps/desktop/src/main/ghost-panel-window/registry.ts, apps/desktop/src/main/ghost-panel-window/settings-store.ts, apps/desktop/src/main/ghost-panel-window/window.ts, apps/desktop/src/renderer/components/layout/GhostPanelWindowLayout.tsx, apps/desktop/src/renderer/ghost-panel-window-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 77 | 38 | 15 |
- | `desktop.window.remote-desktop` | desktop | 远程桌面独立窗口 | `?remoteDesktopViewer=1` → renderer/remote-desktop-viewer-entry.tsx | Button, ConfirmDialog, FormField, Popover, RemoteDesktopViewerWindow, Select, Switch, Tip | apps/desktop/src/main/remote-desktop-viewer/connection.ts, apps/desktop/src/main/remote-desktop-viewer/credentials.ts, apps/desktop/src/main/remote-desktop-viewer/preferences.ts, apps/desktop/src/main/remote-desktop-viewer/registry.ts, apps/desktop/src/main/remote-desktop-viewer/resolutionMemory.ts, apps/desktop/src/main/remote-desktop-viewer/safety.ts, apps/desktop/src/main/remote-desktop-viewer/windows.ts, apps/desktop/src/renderer/components/ui/button.tsx, apps/desktop/src/renderer/components/ui/confirm-dialog.tsx, apps/desktop/src/renderer/components/ui/form-field.tsx, apps/desktop/src/renderer/components/ui/popover.tsx, apps/desktop/src/renderer/components/ui/select.tsx, apps/desktop/src/renderer/components/ui/switch.tsx, apps/desktop/src/renderer/components/ui/tooltip.tsx, apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx, apps/desktop/src/renderer/features/remote-desktop/viewerWindow.css, apps/desktop/src/renderer/remote-desktop-viewer-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 132 | 36 | 28 |
+ | `desktop.window.remote-desktop` | desktop | 远程桌面独立窗口 | `?remoteDesktopViewer=1` → renderer/remote-desktop-viewer-entry.tsx | Button, ConfirmDialog, FormField, Popover, RemoteDesktopViewerWindow, Select, Switch, Tip | apps/desktop/src/main/remote-desktop-viewer/connection.ts, apps/desktop/src/main/remote-desktop-viewer/credentials.ts, apps/desktop/src/main/remote-desktop-viewer/preferences.ts, apps/desktop/src/main/remote-desktop-viewer/registry.ts, apps/desktop/src/main/remote-desktop-viewer/resolutionMemory.ts, apps/desktop/src/main/remote-desktop-viewer/safety.ts, apps/desktop/src/main/remote-desktop-viewer/windows.ts, apps/desktop/src/renderer/components/ui/button.tsx, apps/desktop/src/renderer/components/ui/confirm-dialog.tsx, apps/desktop/src/renderer/components/ui/form-field.tsx, apps/desktop/src/renderer/components/ui/popover.tsx, apps/desktop/src/renderer/components/ui/select-parts.tsx, apps/desktop/src/renderer/components/ui/select.css, apps/desktop/src/renderer/components/ui/select.tsx, apps/desktop/src/renderer/components/ui/switch.tsx, apps/desktop/src/renderer/components/ui/tooltip.tsx, apps/desktop/src/renderer/features/remote-desktop/RemoteDesktopViewerWindow.tsx, apps/desktop/src/renderer/features/remote-desktop/viewerWindow.css, apps/desktop/src/renderer/remote-desktop-viewer-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 132 | 36 | 29 |
| `desktop.window.resource-usage` | desktop | 资源用量窗口 | `?resourceUsageWindow=1` → renderer/resource-usage-entry.tsx(不走 router.tsx) | ResourceUsageWindowLayout, ResourceUsageWindowRoot | apps/desktop/src/main/resource-usage-window/controller.ts, apps/desktop/src/main/resource-usage-window/ipc.ts, apps/desktop/src/main/resource-usage-window/open-sender.ts, apps/desktop/src/main/resource-usage-window/registry.ts, apps/desktop/src/main/resource-usage-window/window.ts, apps/desktop/src/renderer/components/resource-usage/ResourceUsageWindowLayout.tsx, apps/desktop/src/renderer/resource-usage-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 77 | 38 | 15 |
| `desktop.window.review-artifact-confirm` | desktop | Review 成果确认窗 | main/reviewer/reviewArtifactConfirmWindow.ts 内联 HTML/CSS(不走 renderer 路由) | reviewArtifactConfirmWindow | apps/desktop/src/main/reviewer/reviewArtifactConfirmWindow.ts | 8 | 18 | 2 |
| `desktop.window.session-drag-preview` | desktop | 会话拖拽预览 | main/session-drag-preview.ts 透明预览窗 | session-drag-preview | apps/desktop/src/main/session-drag-preview.ts | 0 | 1 | 0 |