Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 在目标电脑执行插件与技能管理
nana1b29438a4c7f
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex de3f6244a2..0788638d8a 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -443,6 +443,7 @@ import { cindyGhostSchemePrivilege } from './cindy-brain/runtime/electronSandboximport { fetchReleaseNotes, fetchReleaseNotesIndex } from './releaseNotesService';import { resolveWorkspacePathCached, resolveWorkspacePathBatchCached } from './pathResolver';import { registerLocalDbIpc } from './localDb/ipc/registerAll';+import { listRecentWorkdirs } from './localDb/ipc/recentWorkdirs';import { getActiveCatalog } from './maker-host/active-catalog';import { resolveSessionContextWindow } from '../shared/sessionContextWindow';import { resumeDeletedPiSubagentCleanup } from './localDb/ipc/sessions';@@ -637,7 +638,7 @@ import { reconcileSavepointRefsForDeletedSessions } from './git-snapshot/savepoiimport { registerGitContextIpc, disposeGitContext } from './git-context';import { registerGitReviewDeviceOp, registerGitReviewIpc } from './git-review';import { registerProjectOrderIpc } from './projectOrderStore';-import { registerSidebarSettingsIpc } from './sidebarSettingsStore';+import { registerSidebarSettingsIpc, loadSidebarSettingsSnapshot, setLocalMainViewHidden } from './sidebarSettingsStore';import { registerModelVisibilityOwnerClaimIpc } from './maker-host/model-visibility-owner-claim.js';import { registerRemotePrecreatedWorktreeLedgerIpc } from './remotePrecreatedWorktreeLedger';import { registerTerminalHandlers } from './maker-ipc/terminal-handlers';@@ -1113,6 +1114,7 @@ import {refreshGhostLocalization,refreshPluginUsageBindings,registerGhostIpc,+ setRemotePluginManagementServices,runStableOwnerPostCommitTask,setGhostNodeRuntimeStartAttemptContextReader,setGhostsChangedObserver,@@ -1126,6 +1128,7 @@ import { registerRelaunchBusyActivityIpc } from './relaunchBusyActivityIpc.js';import { getGhostSetupChangeBus } from './cindy-brain/ghostSetupChangeBus.js';import { getGhostSetupInteractionBridge } from './cindy-brain/ghostSetupInteractionBridge.js';import { registerPluginMarketIpc, syncDefaultMarketPlugins } from './plugin-market/registerIpc.js';+import { getPluginMarketService } from './plugin-market/service.js';import { StableOwnerPostCommitStep } from './stableOwnerPostCommit.js';import { registerPluginPublisherIpc } from './plugin-publisher/registerIpc.js';import { findCindyFileInArgv } from './cindy-brain/argv.js';@@ -2463,6 +2466,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 });+ },+ },+});registerGhostIpc();registerPluginMarketIpc();registerPluginPublisherIpc();@@ -6891,6 +6909,7 @@ const registerIpcHandlers = () => {);registerSkillhubIpc({+ remoteIsRelayOnline: () => getDeviceLinkStatus() === 'online',getMaker: getMakerCore,getManagedSkillRoots: () => getGhostManager().managedRootDirs(),getBuiltInSkills: () => builtInSkillDescriptors(diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex adb394927c..638a259b8c 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -2802,8 +2802,12 @@ export class GhostManager {id: string,enabled: boolean,expectedInstalledApproval?: string,+ assertCurrent?: () => void,): Promise<{ ok: true } | { rejection: UninstallRejection }> {- return this.runExclusiveMutation(() => this.setEnabledUnlocked(id, enabled, expectedInstalledApproval));+ return this.runExclusiveMutation(() => {+ assertCurrent?.();+ return this.setEnabledUnlocked(id, enabled, expectedInstalledApproval);+ });}private async setEnabledUnlocked(diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.tsindex 1ffe05dcfd..fdfef1a70c 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostInstanceBoundaries.test.ts@@ -68,12 +68,12 @@ describe('production plugin instance boundaries', () => {expect(fixture.stop).not.toHaveBeenCalled();const currentApproval = ghostInstallApprovalToken(fixture.organization.approval);await fixture.setGhostEnabledForUser('helper', false, currentApproval);- expect(fixture.setEnabled).toHaveBeenCalledExactlyOnceWith('helper', false, currentApproval);+ expect(fixture.setEnabled).toHaveBeenCalledExactlyOnceWith('helper', false, currentApproval, undefined);});it('does not disable a logical twin after the original physical target disappears', async () => {const fixture = harness();await fixture.setGhostEnabledForUser('helper', false);- expect(fixture.setEnabled).toHaveBeenCalledWith('helper', false, ghostInstallApprovalToken(fixture.organization.approval));+ expect(fixture.setEnabled).toHaveBeenCalledWith('helper', false, ghostInstallApprovalToken(fixture.organization.approval), undefined);fixture.setEnabled.mockClear();fixture.stop.mockClear();fixture.ghosts.splice(0, 1);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.tsindex e1e44117c8..217a75a75a 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostIpcMutationLease.test.ts@@ -67,7 +67,7 @@ describe('ghost 写路径 IPC 的 owner 租约(源码契约)', () => {expect(lease).toBeLessThan(fn.indexOf('await '));expect(fn).toContain('const relId = installedGhostPhysicalRelId(target)');expect(fn).toContain('const storagePart = installedGhostStoragePart(target)');- expect(fn).toContain('await manager.setEnabled(relId, enabled, expectedInstalledApproval ?? approvalToken)');+ expect(fn).toContain('await manager.setEnabled(relId, enabled, expectedInstalledApproval ?? approvalToken, assertCurrent)');expect(fn).toMatch(/finally\s*\{\s*releaseMutation\(\)/);});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.tsindex 40835166a3..793178fb95 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostUserDataRelocation.test.ts@@ -217,12 +217,12 @@ it('completes source replacement and another plugin uninstall without reversingconst code = ts.transpileModule(`return (async () => { ${source.slice(start, end)} })();`, {compilerOptions: { target: ts.ScriptTarget.ES2022 },}).outputText;- const remove = new Function('activeOwnerScopeKey', 'pluginTaskUninstaller', 'storagePart', 'manager', 'relId', 'throwUninstallError', 'currentPluginUsageService', 'log', code);+ const remove = new Function('activeOwnerScopeKey', 'pluginTaskUninstaller', 'storagePart', 'manager', 'relId', 'throwUninstallError', 'currentPluginUsageService', 'log', 'options', code);const detach = vi.fn(async () => {});const log = { warn: vi.fn() };const removing = remove(() => scope.dir, (id: string, callback: () => Promise<void>) => service.withUninstall(id, callback),'_root__other', manager, '_ns/_root/other', (failure: { reason: string }) => { throw new Error(failure.reason); },- () => ({ detach }), log);+ () => ({ detach }), log, {});await new Promise<void>(resolve => setImmediate(resolve));finish();const [updated] = await Promise.all([updating, removing]);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/mobilePageRelay.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageRelay.test.tsindex ccfcb5f7c9..3e5ba3a613 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/mobilePageRelay.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/mobilePageRelay.test.ts@@ -39,8 +39,24 @@ describe('mobile page relay', () => {expect(run({ op: 'poll', pageId: 'a', after: 0 })).toHaveLength(1);expect(run({ op: 'poll', pageId: 'a', after: 0 })).toHaveLength(1);expect(run({ op: 'poll', pageId: 'a', after: 1 })).toHaveLength(0);+ run({ op: 'connect', pageId: 'a', channels: ['practice', 'next'] });+ expect(channels).toHaveLength(3);+ channels[0].onmessage?.({ data: { removed: true } });+ channels[2].onmessage?.({ data: { current: true } });+ run({ op: 'connect', pageId: 'a', channels: ['next'] });+ expect(channels[0].closed).toBe(true);+ expect(channels[1].closed).toBe(false);+ expect(channels[2].closed).toBe(false);+ expect(run({ op: 'poll', pageId: 'a', after: 1 })).toEqual([+ { sequence: 3, channel: 'next', data: { current: true } },+ ]);+ expect(() =>+ run({ op: 'post', pageId: 'a', channel: 'practice', data: {} }),+ ).toThrow('PLUGIN_CHANNEL_UNAVAILABLE');+ expect(run({ op: 'poll', pageId: 'a', after: 3 })).toHaveLength(0);run({ op: 'disconnect', pageId: 'a' });expect(channels[0].closed).toBe(true);expect(channels[1].closed).toBe(false);+ expect(channels[2].closed).toBe(true);});});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginManagement.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginManagement.test.tsnew file mode 100644index 0000000000..7aab1918bb--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginManagement.test.ts@@ -0,0 +1,571 @@+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' };+ 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(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.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'); });+ 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' },+ ]);+ 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; }));+ 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('rejects the superseded task-card configuration action', async () => {+ const f = fixture();+ 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 --git a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginPreferences.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginPreferences.test.tsnew file mode 100644index 0000000000..7c5a36c049--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginPreferences.test.ts@@ -0,0 +1,144 @@+import { describe, expect, it, vi } from 'vitest';+import type { PluginTaskPreferences } from '@cindy/device-link';+import { RemotePluginPreferences } from '../remotePluginPreferences';+import type { InstalledGhost } from '../../../shared/ghost';++function fixture() {+ const ghost = {+ manifest: {+ id: 'sample',+ cindy: { text: ['oneshot'] },+ agent: { tasks: true },+ mainView: { html: 'main.html' },+ },+ enabled: true,+ approval: { state: 'approved', revision: 'install-a' },+ } as unknown as InstalledGhost;+ let visible = true;+ let tasks: PluginTaskPreferences = {+ revision: 'task-a',+ config: {},+ permissionModes: ['ask'],+ defaultPermissionMode: 'ask',+ };+ const deps = {+ auxiliaryModelLabel: () => 'Target auxiliary model',+ tasks: {+ read: vi.fn(() => tasks),+ update: vi.fn<+ (+ id: string,+ installation: string,+ input: Record<string, unknown>,+ check: () => void,+ ) => Promise<PluginTaskPreferences>+ >(async (...[, , input, check]) => {+ check();+ tasks = {+ ...tasks,+ revision: 'task-b',+ config: input.model as PluginTaskPreferences['config'],+ };+ return tasks;+ }),+ },+ sidebar: {+ read: vi.fn(() => visible),+ write: vi.fn(async (...[, value, check]: [string, boolean, () => void]) => {+ check();+ visible = value;+ }),+ },+ };+ return {+ service: new RemotePluginPreferences(deps),+ ghost,+ deps,+ changeSidebar: () => {+ visible = false;+ },+ };+}+describe('target-owned plugin preferences', () => {+ it('uses the single target model and sidebar controls without projecting private routes', () => {+ const f = fixture(),+ value = f.service.read('physical-instance', f.ghost);+ expect(value.tasks?.revision).toBe('task-a');+ expect(value.auxiliaryModelLabel).toBe('Target auxiliary model');+ expect(value.sidebarVisible).toBe(true);+ expect(f.deps.tasks.read).toHaveBeenCalledWith('physical-instance', expect.any(String));+ expect(JSON.stringify(value)).not.toMatch(/workingDir|routing|overrides/);+ });+ it('shows one model for quick-answer-only plugins and no obsolete media capability controls', () => {+ const f = fixture();+ f.ghost.manifest.agent = undefined;+ expect(f.service.read('sample', f.ghost).tasks).toBeDefined();+ f.ghost.manifest.cindy = { image: ['generate'] };+ expect(f.service.read('sample', f.ghost).tasks).toBeUndefined();+ });+ it('rejects stale revisions before writing', async () => {+ const f = fixture(),+ value = f.service.read('sample', f.ghost);+ f.changeSidebar();+ await expect(+ f.service.update(+ 'sample',+ f.ghost,+ { expectedRevision: value.revision, kind: 'tasks', patch: { model: null } },+ () => {},+ ),+ ).rejects.toThrow('PLUGIN_SETTINGS_CHANGED');+ expect(f.deps.tasks.update).not.toHaveBeenCalled();+ });+ it('patches the target model and returns the committed snapshot', async () => {+ const f = fixture(),+ value = f.service.read('sample', f.ghost);+ const model = {+ agentKind: 'codex',+ providerId: 'target-provider',+ model: 'target-model',+ fastMode: false,+ };+ const result = await f.service.update(+ 'sample',+ f.ghost,+ { expectedRevision: value.revision, kind: 'tasks', patch: { model } },+ () => {},+ );+ expect(result.tasks?.config).toEqual(model);+ expect(result.revision).not.toBe(value.revision);+ expect(f.deps.tasks.update).toHaveBeenCalledWith(+ 'sample',+ expect.any(String),+ { model, expectedRevision: 'task-a' },+ expect.any(Function),+ );+ expect(f.deps.sidebar.write).not.toHaveBeenCalled();+ });+ it('does not expose or mutate controls absent from the installed declaration', async () => {+ const f = fixture();+ f.ghost.manifest = {+ ...f.ghost.manifest,+ cindy: undefined,+ agent: undefined,+ mainView: undefined,+ };+ const value = f.service.read('sample', f.ghost);+ expect(value.tasks).toBeUndefined();+ expect(value.sidebarVisible).toBeUndefined();+ for (const input of [+ { kind: 'sidebar', visible: true },+ { kind: 'tasks', patch: { model: null } },+ { kind: 'cindy', capability: 'image.generate', model: 'target-model' },+ ]) {+ await expect(+ f.service.update(+ 'sample',+ f.ghost,+ { expectedRevision: value.revision, ...input },+ () => {},+ ),+ ).rejects.toThrow('PLUGIN_SETTINGS_INVALID');+ }+ });+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginProjects.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginProjects.test.tsnew file mode 100644index 0000000000..eefa89c6fc--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginProjects.test.ts@@ -0,0 +1,35 @@+import path from 'node:path';+import { beforeEach, expect, it, vi } from 'vitest';+import { projectPluginWorkdir, resolvePluginWorkdir } from '../remotePluginProjects';++const { stat } = vi.hoisted(() => ({ stat: vi.fn() }));+vi.mock('node:fs/promises', () => ({ stat }));+vi.mock('../../maker-host/logger-adapter.js', () => ({+ desktopMakerLogger: { child: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }) },+}));+vi.mock('../../appSessionState.js', () => ({ ownerScopedUserDataPath: () => 'unused' }));++beforeEach(() => stat.mockReset());++it('keeps the selected Host path as display metadata and issues the same identity for normalized spellings', () => {+ const workdir = path.resolve('target', 'Cindy');+ const project = projectPluginWorkdir(workdir);+ expect(project).toMatchObject({ name: 'Cindy', path: workdir, workdir });+ expect(project.id).toMatch(/^[a-f0-9]{64}$/);+ expect(projectPluginWorkdir(workdir + path.sep).id).toBe(project.id);+});++it('resolves only an existing absolute directory on the Host before issuing a project id', async () => {+ const workdir = path.resolve('target', 'Cindy');+ stat.mockResolvedValue({ isDirectory: () => true });+ expect(await resolvePluginWorkdir(workdir)).toEqual(projectPluginWorkdir(workdir));+ expect(stat).toHaveBeenCalledWith(workdir);+ stat.mockResolvedValueOnce({ isDirectory: () => false });+ await expect(resolvePluginWorkdir(workdir)).rejects.toThrow('INVALID_PROJECT_DIRECTORY');+ stat.mockRejectedValueOnce(new Error('ENOENT'));+ await expect(resolvePluginWorkdir(workdir)).rejects.toThrow('ENOENT');+ stat.mockClear();+ await expect(resolvePluginWorkdir('controller-relative')).rejects.toThrow('INVALID_PROJECT_DIRECTORY');+ await expect(resolvePluginWorkdir(workdir + '\0')).rejects.toThrow('INVALID_PROJECT_DIRECTORY');+ expect(stat).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.tsnew file mode 100644index 0000000000..e23bf646e9--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginSettings.test.ts@@ -0,0 +1,427 @@+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.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 --git a/apps/desktop/src/main/cindy-brain/__tests__/remoteSettingsBroadcast.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/remoteSettingsBroadcast.test.tsnew file mode 100644index 0000000000..ecd186dec5--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/remoteSettingsBroadcast.test.ts@@ -0,0 +1,77 @@+import { readFile } from 'node:fs/promises';+import { runInNewContext } from 'node:vm';+import { transformWithEsbuild } from 'vite';+import { describe, expect, it, vi } from 'vitest';++describe('original settings BroadcastChannel transport', () => {+ it('runs the built script without Main helpers and preserves subscribe, reply and close', async () => {+ const source = await readFile(+ new URL('../remoteSettingsBroadcast.ts', import.meta.url),+ 'utf8',+ );+ const built = await transformWithEsbuild(source, 'remoteSettingsBroadcast.ts', {+ target: 'es2020',+ format: 'cjs',+ tsconfigRaw: { compilerOptions: { useDefineForClassFields: true } },+ });+ const module = { exports: {} as { remoteSettingsBroadcastScript(endpoint: string): string } };+ runInNewContext(built.code, { module, exports: module.exports });+ const window = {} as { BroadcastChannel: typeof BroadcastChannel };+ const commands: Array<Record<string, unknown>> = [];+ const timers: Array<() => void> = [];+ const events: Array<{ channel: string; sequence: number; data: unknown }> = [];+ let failPoll = false;+ runInNewContext(module.exports.remoteSettingsBroadcastScript('/fixture-bridge'), {+ window,+ EventTarget,+ MessageEvent,+ DOMException,+ structuredClone,+ setTimeout: (callback: () => void) => timers.push(callback),+ fetch: async (_path: string, init: { body: string }) => {+ const command = JSON.parse(init.body);+ commands.push(command);+ return {+ ok: !(failPoll && command.kind === 'poll'),+ json: async () => (command.kind === 'poll' ? { events: events.splice(0) } : {}),+ };+ },+ });+ const channel = new window.BroadcastChannel('settings');+ const onmessage = vi.fn(),+ listener = vi.fn();+ channel.onmessage = onmessage;+ channel.addEventListener('message', listener);+ channel.postMessage({ op: 'status' });+ await vi.waitFor(() =>+ expect(commands).toContainEqual({+ kind: 'post',+ channel: 'settings',+ data: { op: 'status' },+ }),+ );+ expect(commands[0]).toEqual({ kind: 'subscribe', channels: ['settings'] });+ events.push({ channel: 'settings', sequence: 1, data: { saved: true } });+ timers.shift()!();+ await vi.waitFor(() => expect(onmessage).toHaveBeenCalledTimes(1));+ expect(onmessage.mock.calls[0][0].data).toEqual({ saved: true });+ expect(listener).toHaveBeenCalledTimes(1);+ const onmessageerror = vi.fn(),+ errorListener = vi.fn();+ channel.onmessageerror = onmessageerror;+ channel.addEventListener('messageerror', errorListener);+ failPoll = true;+ timers.shift()!();+ await vi.waitFor(() => expect(errorListener).toHaveBeenCalledTimes(1));+ expect(onmessageerror).toHaveBeenCalledTimes(1);+ const sameName = new window.BroadcastChannel('settings');+ channel.close();+ await Promise.resolve();+ expect(commands).not.toContainEqual({ kind: 'unsubscribe', channel: 'settings' });+ sameName.close();+ await vi.waitFor(() =>+ expect(commands).toContainEqual({ kind: 'unsubscribe', channel: 'settings' }),+ );+ expect(() => channel.postMessage({ late: true })).toThrow('Channel closed');+ });+});diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 6f3aef29d1..a12f98893f 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -1,14 +1,44 @@+import { RemotePluginPreferences } from './remotePluginPreferences.js';+import { readDeviceLinkSettings } from '../device-link/settings-store.js';+import { isSharedTaskPeer, isProviderSharePeer } from '@cindy/device-link';+import { RemotePluginManagement, type RemotePluginManagementDeps } from './remotePluginManagement.js';+import { projectPluginWorkdir, resolvePluginWorkdir } from './remotePluginProjects.js';+import { takePeerAttachment } from '../device-link/peerAttachmentStore.js';+import { parsePeerAttachmentRef } from '@cindy/device-link';import { capturePluginOauthPeer } from '../plugin-oauth/runtime.js';import { readMobilePreview } from './mobilePreview.js';import { MobileTaskSettings } from './mobileTaskSettings.js';import { MobilePluginPages } from './mobilePageService.js';import { listMobilePageFiles, readMobilePageChunk } from './mobilePageAssets.js';-import { invokeGhostMobileRelay, fetchGhostMobilePage } from './runtime/electronSandboxAdapter.js';+import { invokeGhostMobileRelay, fetchGhostMobilePage, fetchGhostSettings } from './runtime/electronSandboxAdapter.js';import { remoteResourceRegistry } from '../device-link/remoteResourceRegistry.js';import { REMOTE_RESOURCE_CHANGED_CHANNEL, PLUGIN_COLLECTION, type PluginPagePoll } from '@cindy/device-link';import { tapWindowBroadcast, getSafeDataOwnerPushStamp, captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from '../device-link/broadcast-tap.js';let mobilePluginPages: MobilePluginPages | null = null;+let remotePluginManagement: RemotePluginManagement | null = null;+export const remotePluginSettings = {+ bind: (action: import('@cindy/device-link').PluginOauthAction) => mobilePluginPages?.settingsBinding(action) ?? null,+ bindAuthorization: (action: import('@cindy/device-link').PluginOauthAction) => mobilePluginPages?.settingsAuthorizationBinding(action) ?? null,+ runAuthorization: (action: import('@cindy/device-link').PluginOauthAction) => mobilePluginPages?.runSettingsAuthorization(action) ?? false,+ request: (peer: string, request: import('@cindy/device-link').PluginSettingsRequest) =>+ mobilePluginPages?.settingsRequest(peer, request) ?? Promise.reject(new Error('PLUGIN_PAGE_UNAVAILABLE')),+};+interface RemotePluginManagementServices {+ isRelayOnline(): boolean;+ market: RemotePluginManagementDeps['market'];+ listProjects(): Promise<Array<{ path: string; exists: boolean }>>;+ sidebar: { read(id: string): boolean; write(id: string, visible: boolean, assertCurrent: () => void): Promise<void> };+}+let remotePluginManagementServices: RemotePluginManagementServices | null = null;+/** Bootstrap owns cross-host service wiring, keeping the plugin module import graph acyclic. */+export function setRemotePluginManagementServices(services: RemotePluginManagementServices): void {+ remotePluginManagementServices = services;+}+function requireRemotePluginManagementServices(): RemotePluginManagementServices {+ if (!remotePluginManagementServices) throwIpcError('PRECONDITION_FAILED', 'Remote plugin management unavailable');+ return remotePluginManagementServices!;+}/** Dedicated Host permission presentation. The existing capability/write gates still own the decision and persistence. */export async function showMobilePluginTaskPermission(pluginId: string, pageId: string, presentation: {title: string; message: string; detail: string; allow: string; cancel: string;@@ -24,6 +54,7 @@ export async function showMobilePluginTaskPermission(pluginId: string, pageId: sfunction notifyMobilePluginsChanged(): void {mobilePluginPages?.invalidate();+ remotePluginManagement?.invalidate();tapWindowBroadcast(REMOTE_RESOURCE_CHANGED_CHANNEL, { collectionId: PLUGIN_COLLECTION }, getSafeDataOwnerPushStamp());}@@ -95,7 +126,7 @@ function requestPluginTaskApproval(id: string, isCurrent: () => boolean, confirm}));}-import { isValidPluginNamespace, supportsCindyVersion } from '@cindy/plugin-protocol';+import { isValidPluginNamespace, supportsCindyVersion, PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES } from '@cindy/plugin-protocol';import { buildGhostRecommendationSnapshot } from './ghostRecommendationSnapshot.js';import {readGhostRecommendationEntries,@@ -7049,12 +7080,12 @@ async function updateLocalGhostPackageLocked(installOrigin: installOrigin ?? 'manual',...(sourceChanged ? { sourceStateArchiveId: ghostSourceStateArchiveId(previousGhost) } : {}),...deliveryNamespaceFields(previousGhost),- beforePackageCommit: () =>- getGhostOauthAccountManager().prepareAccountsForChangedClients(- previousGhost.manifest,- inspected.canonicalManifest,- instanceId,- ),+ beforePackageCommit: () => {+ if (isCurrent?.() === false) throwIpcError('PRECONDITION_FAILED', 'Plugin operation is no longer current');+ return getGhostOauthAccountManager().prepareAccountsForChangedClients(+ previousGhost.manifest, inspected.canonicalManifest, instanceId,+ );+ },onPackagePlaced: () => {packagePlaced = true;},@@ -7585,7 +7616,7 @@ export function setGhostUninstallLedgerPreparer(preparer: GhostUninstallLedgerPr*/export async function uninstallGhostAndCleanup(id: string,- options?: { skipMarketLedger?: boolean },+ options?: { skipMarketLedger?: boolean; assertCurrent?: () => void },): Promise<void> {// Install lock is the catalog ghostId so public and org instances of the// same name stay serial. OAuth/vault lock is the storage part, never a@@ -7595,6 +7626,7 @@ export async function uninstallGhostAndCleanup(throwIpcError('INVALID_PARAMS', 'id must be a valid Ghost id');}return withGhostInstallLock(identity.ghostId, () => {+ options?.assertCurrent?.();const ghost = findGhostForInstanceId(id);if (!ghost) throwIpcError('NOT_FOUND', '目标插件实例已不存在');return withActiveOwnerGhostOauthMutationLock(installedGhostStoragePart(ghost), () =>@@ -7605,10 +7637,11 @@ export async function uninstallGhostAndCleanup(async function uninstallGhostAndCleanupLocked(id: string,- options?: { skipMarketLedger?: boolean },+ options?: { skipMarketLedger?: boolean; assertCurrent?: () => void },): Promise<void> {const releaseMutation = beginGhostMutation();try {+ options?.assertCurrent?.();requireGhostAvailableForActiveSession(id);const ghost = findGhostForInstanceId(id);if (!ghost) throwIpcError('NOT_FOUND', '目标插件实例已不存在');@@ -7635,6 +7668,7 @@ async function uninstallGhostAndCleanupLocked(const uninstallTasks = pluginTaskUninstaller;if (!uninstallTasks) throw new Error('Plugin task storage is not ready for uninstall');await manager.runExclusiveMutation(mutation => uninstallTasks(storagePart, async () => {+ options?.assertCurrent?.();const result = await mutation.uninstall(relId, { notify: false });if ('rejection' in result) throwUninstallError(result.rejection);}));@@ -7782,7 +7816,8 @@ function readLegacyEncryptedSecret(file: string): LegacyMigrationRead<string> {}-async function setGhostEnabledForUser(id: string, enabled: boolean, expectedInstalledApproval?: string) {+async function setGhostEnabledForUser(id: string, enabled: boolean, expectedInstalledApproval?: string, assertCurrent?: () => void) {+ assertCurrent?.();const target = findGhostForPhysicalStoragePart(id);if (!target) throwIpcError('NOT_FOUND', '目标插件实例已不存在');const approvalToken = ghostInstallApprovalToken(target.approval);@@ -7811,7 +7846,7 @@ async function setGhostEnabledForUser(id: string, enabled: boolean, expectedInst// 不得继续后台读写(数据本体不动,重新启用后重开)。await getGhostLibrarySlot().disposeGhost(storagePart);}- const result = await manager.setEnabled(relId, enabled, expectedInstalledApproval ?? approvalToken);+ const result = await manager.setEnabled(relId, enabled, expectedInstalledApproval ?? approvalToken, assertCurrent);if ('rejection' in result) throwUninstallError(result.rejection);if (enabled) {runtime.resetFuse(storagePart); // 重新唤醒 = 清熔断记账,可再拉起@@ -7846,6 +7881,44 @@ async function setGhostEnabledForUser(id: string, enabled: boolean, expectedInst}}+/** Materialize only an authenticated peer inbox ticket, then reuse ordinary file install/update. */+async function installRemoteGhostFile(peer: string, attachment: string, target: string | undefined,+ expectedApproval: string | undefined, prompt: GhostInstallConsentPrompt, assertCurrent: () => void): Promise<void> {+ const ref = parsePeerAttachmentRef(attachment);+ if (!ref || ref.size > PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES) throwIpcError('INVALID_PARAMS', 'Invalid plugin attachment');+ const owner = captureGhostMutationOwner();+ assertCurrent();+ const dir = await fs.promises.mkdtemp(path.join(app.getPath('temp'), 'cindy-remote-plugin-'));+ const file = path.join(dir, 'package.cindy');+ try {+ await takePeerAttachment(peer, ref, file);+ assertCurrent();+ const manager = getGhostManager();+ const inspected = await manager.inspect(file);+ if ('rejection' in inspected) throwInstallError(inspected.rejection);+ rejectReservedGhostId(inspected.manifest.id);+ rejectBrokerWithoutDeclaredRedirectPort(inspected.manifest);+ const existing = target ? findInstalledGhostForLocalUpdate(manager.list(), inspected.manifest.id, target, expectedApproval!) :+ findInstalledGhostForDeliveryTarget(manager.list(), { ghostId: inspected.manifest.id, namespace: null });+ if (target && !existing) throwIpcError('PRECONDITION_FAILED', 'Plugin installation changed');+ if (existing && typeof existing.namespace === 'string') throwIpcError('PRECONDITION_FAILED', 'Use the organization marketplace to update this plugin');+ const updateSource = existing ? readLocalGhostUpdateSource(manager, existing, inspected) : undefined;+ rejectUnauthorizedTokenBroker(inspected.canonicalManifest, updateSource?.authorizationOverrides);+ const token = existing ? ghostInstallApprovalToken(existing.approval) : undefined;+ const consent = await obtainGhostInstallConsent({ mode: 'prompt', prompt, initiator: 'user', origin: 'local-file' },+ existing, inspected.manifest, inspected.packageSha256);+ assertCurrent();+ const release = beginGhostMutation(owner);+ try {+ const current = () => { assertCurrent(); return true; };+ if (existing) await withGhostInstallLock(inspected.manifest.id, () => updateLocalGhostPackageLocked(+ manager, file, inspected, inspected.packageSha256, token!, installedGhostStoragePart(existing), consent, undefined, current));+ else await installAndDock(manager, file, { ghostId: inspected.manifest.id, namespace: null, enable: true,+ expectedPackageSha256: inspected.packageSha256, consent: { decision: consent, manifest: inspected.manifest }, beforePackagePlacement: assertCurrent });+ } finally { release(); }+ } finally { await fs.promises.rm(dir, { recursive: true, force: true }); }+}+export function registerGhostIpc(): void {registerGhostCardRemoteProvider((id) => {const ghost = findGhostForRemotePluginIdentity(availableGhosts(), id);@@ -7862,7 +7935,61 @@ export function registerGhostIpc(): void {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);+ },+ },+ 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 }>();@@ -7889,11 +8016,20 @@ export function registerGhostIpc(): void {},revision: ghost => JSON.stringify([ghost.manifest.version, ghostInstallApprovalToken(ghost.approval)]),captureOwner: () => { const scope = captureDataOwnerBroadcastScope(); return () => isDataOwnerBroadcastScopeCurrent(scope); },- // This existing peer fence is invalidated on disconnect, revoke, owner switch and relay teardown.- captureController: id => { const assertCurrent = capturePluginOauthPeer(id); return () => { try { assertCurrent(); return true; } catch { return false; } }; },+ captureController: id => {+ const assertCurrent = capturePluginOauthPeer(id);+ return () => { try {+ assertCurrent();+ const settings = readDeviceLinkSettings();+ return !isSharedTaskPeer(id) && !isProviderSharePeer(id) &&+ remotePluginManagementServices?.isRelayOnline() === true && settings.remoteControlEnabled &&+ !settings.revokedControllers.includes(id);+ } catch { return false; } };+ },unread: id => visibleGhostUnread().find(entry => entry.ghostId === id) ?? null,clearUnread: extinguishGhostUnread,setEnabled: async (id, enabled) => { await setGhostEnabledForUser(id, enabled); },+ settingsFetch: fetchGhostSettings,bundle: listMobilePageFiles,asset: readMobilePageChunk,connect: async (ghost, pageId, channels) => {@@ -7915,11 +8051,7 @@ export function registerGhostIpc(): void {if (!(await fs.promises.stat(real)).isDirectory()) throw new Error('INVALID_DIRECTORY');return real;},- 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() ?? []; },- }),+ taskSettings,});remoteResourceRegistry.register(mobilePluginPages.provider());// 启动即对账一次 skill 槽链接:上次会话崩溃/异常退出留下的悬空链接、@@ -8113,7 +8245,7 @@ export function registerGhostIpc(): void {// 关键闸:**新增地址必须过 main 侧受信确认弹窗**——意识设置页是意识自绘// 的不可信界面,动态白名单扩张必须由主机模态拿到用户点头(规则 9:用代码// 保证,不靠意识自觉)。- setGhostConnectionsHandler(async ({ ghostId, method, pathname, readBodyText, isCurrent }) => {+ setGhostConnectionsHandler(async ({ ghostId, method, pathname, readBodyText, isCurrent, confirmConnection }) => {const ghost = findGhostForInstanceId(ghostId);if (!ghost) return { status: 404 };const connectionDecls = ghost.manifest.network?.connections ?? [];@@ -8135,6 +8267,7 @@ export function registerGhostIpc(): void {// 受信确认:main 侧系统模态(对照 bootstrap 的 moveToApplications 弹窗// 用法),默认落在「取消」上防误触;意识名从在装清单现查。confirmAddHost: async (declLabel, host) => {+ if (confirmConnection) return confirmConnection(declLabel, host);const ghostName = (findGhostForInstanceId(ghostId))?.manifest.name ?? ghostId;// main 迷你 i18n 只内置 {{appName}} 插值,其余变量按其约定在调用点// 自行 replace(对照 bootstrap 菜单的用法)。@@ -8962,18 +9095,7 @@ export function registerGhostIpc(): void {}const target = findGhostForInstanceId(ghostId);const storedId = target ? installedGhostStoragePart(target) : ghostId;- const wasDisabled = isGhostDisabledForWorkdir(storedId, workdir);- const next = setGhostDisabledForWorkdir(workdir, storedId, disabled);- // A setup card may already be waiting for this plugin in the affected- // project. Wake all waiters for the plugin; each one revalidates its own- // captured workdir and only the matching scope is rejected.- if (wasDisabled !== disabled) {- getGhostSetupChangeBus().emit(storedId, { source: 'workdir_policy' });- }- // 生效面变了(新会话花名册 / $ 菜单),借 ghosts:changed 通知所有窗口- // 重拉——载荷仍是完整已装清单,消费方按需再 sendSync 取目录级清单。- broadcastGhostsChanged(manager.list());- return { disabled: next };+ return { disabled: setGhostWorkdirDisabledAndNotify(workdir, storedId, disabled) };},);@@ -9829,6 +9951,15 @@ export function resolveGhostWebviewAttach(};}+/** Local and remote project controls share persistence, setup wake-up and list invalidation. */+function setGhostWorkdirDisabledAndNotify(workdir: string, storedId: string, disabled: boolean): string[] {+ const wasDisabled = isGhostDisabledForWorkdir(storedId, workdir);+ const next = setGhostDisabledForWorkdir(workdir, storedId, disabled);+ if (wasDisabled !== disabled) getGhostSetupChangeBus().emit(storedId, { source: 'workdir_policy' });+ broadcastGhostsChanged(getGhostManager().list());+ return next;+}+/** 播种进行中提示广播(renderer 显示/收起非阻塞胶囊;与退出 overlay 同款视觉)。 */function broadcastGhostProvisioning(active: boolean): void {broadcastGhostWindowPush('ghosts:provisioning', { active });diff --git a/apps/desktop/src/main/cindy-brain/mobilePageService.ts b/apps/desktop/src/main/cindy-brain/mobilePageService.tsindex e71c356706..d97ff4f4b9 100644--- a/apps/desktop/src/main/cindy-brain/mobilePageService.ts+++ b/apps/desktop/src/main/cindy-brain/mobilePageService.ts@@ -10,10 +10,15 @@ import {type PluginPageSurface,type PluginPageAsset,type PluginPageFile,+ PLUGIN_SETTINGS_ACTION,+ type PluginSettingsRequest,+ type PluginOauthAction,type RemoteCollectionItem,type PluginConfigurationSummary,} from '@cindy/device-link';-import { ghostContentKeys, ghostPermissionItems, ghostTrustLabelKey, type GhostSetupAssessment, type InstalledGhost } from '../../shared/ghost.js';+import { ghostContentKeys, ghostInstallApprovalToken, ghostPermissionItems, ghostTrustLabelKey, type GhostSetupAssessment, type InstalledGhost } from '../../shared/ghost.js';+import { getRemoteOauthContext, notifyOauthCardClosed } from '../plugin-oauth/context.js';+import type { OauthCardBinding } from '../plugin-oauth/transactions.js';import { installedGhostStoragePart } from '../../shared/pluginIdentity.js';import { resolvePreferredSystemLocale } from '../../shared/locale.js';import { t } from '../i18n.js';@@ -26,6 +31,9 @@ import {} from '../device-link/remoteResourceRegistry.js';interface Page {+ desktopSettings?: true;+ channels?: string[];+ authorizations?: Map<string, { path: string; body?: string; running: boolean; result?: import('@cindy/device-link').PluginPageFetchResult }>;id: string;controller: string;plugin: string;@@ -59,6 +67,7 @@ interface Page {previews?: Map<string, MobilePluginPreview>;}interface Dependencies {+ management?: import('./remotePluginManagement.js').RemotePluginManagement;list(): InstalledGhost[];listOrder?(): ReadonlyMap<string, NonNullable<RemoteCollectionItem['pluginOrder']>>;setupAssessment?(id: string): GhostSetupAssessment;@@ -85,6 +94,7 @@ interface Dependencies {revision?: string,): Promise<import('@cindy/device-link').PluginPageFetchResult>;fetchPreview?: MobilePreviewReader;+ settingsFetch?(ghost: InstalledGhost, path: string, method: string, body: string | undefined, current: () => boolean, confirmConnection?: (label: string, host: string) => Promise<boolean>): Promise<import('@cindy/device-link').PluginPageFetchResult>;resolveMedia?(ghostId: string,url: string,@@ -146,6 +156,7 @@ export class MobilePluginPages {}private close(page: Page) {this.pages.delete(page.id);+ for (const id of page.authorizations?.keys() ?? []) notifyOauthCardClosed(id);this.cancelDirectory(page);page.previews?.clear();for (const pending of page.confirms.values()) {@@ -164,6 +175,248 @@ export class MobilePluginPages {}}}+ settingsBinding(action: PluginOauthAction): OauthCardBinding | null {+ if (action.actionId !== PLUGIN_SETTINGS_ACTION || action.expectedRevision !== 0) return null;+ const page = this.pages.get(action.requestId);+ if (!page?.desktopSettings) return null;+ return {+ ghostId: page.plugin,+ controllerDeviceId: page.controller,+ settingsPage: true,+ current: () => {+ try {+ this.page(page.id, page.controller);+ return true;+ } catch {+ return false;+ }+ },+ };+ }+ settingsAuthorizationBinding(action: PluginOauthAction): OauthCardBinding | null {+ if (action.actionId !== 'settings-oauth' || action.expectedRevision !== 0) return null;+ const page = [...this.pages.values()].find(+ (p) => p.desktopSettings && p.authorizations?.has(action.requestId),+ );+ if (!page) return null;+ return {+ ghostId: page.plugin,+ controllerDeviceId: page.controller,+ current: () => {+ try {+ this.page(page.id, page.controller);+ return page.authorizations!.has(action.requestId);+ } catch {+ return false;+ }+ },+ };+ }+ runSettingsAuthorization(action: PluginOauthAction): boolean {+ const binding = this.settingsAuthorizationBinding(action),+ remote = getRemoteOauthContext();+ if (!binding?.current() || !remote || remote.peer !== binding.controllerDeviceId) return false;+ const page = [...this.pages.values()].find((p) => p.authorizations?.has(action.requestId))!;+ const authorization = page.authorizations!.get(action.requestId)!;+ if (authorization.running) return false;+ authorization.running = true;+ const ghost = this.check(page);+ void (async () => {+ try {+ // The original endpoint owns OAuth validation, exchange and persistence.+ const result = await this.deps.settingsFetch!(+ ghost,+ authorization.path,+ 'POST',+ authorization.body,+ binding.current,+ );+ if (!binding.current()) throw new Error('PLUGIN_PAGE_CLOSED');+ authorization.result = result;+ remote.finish(+ result.status === 200 &&+ JSON.parse(Buffer.from(result.base64, 'base64').toString()).ok === true,+ );+ } catch {+ if (binding.current())+ authorization.result = {+ status: 200,+ mime: 'application/json',+ base64: Buffer.from(JSON.stringify({ ok: false, error: 'CANCELLED' })).toString(+ 'base64',+ ),+ };+ remote.finish(false);+ } finally {+ authorization.body = undefined;+ }+ })();+ return true;+ }+ async settingsRequest(controller: string, request: PluginSettingsRequest): Promise<unknown> {+ const page = this.page(request.id, controller);+ if (!page.desktopSettings) return fail();+ const ghost = this.check(page),+ command = request.command;+ const current = () => {+ try {+ return this.page(page.id, controller) === page;+ } catch {+ return false;+ }+ };+ const done = <T>(value: T): T => {+ if (!current()) return fail();+ return value;+ };+ switch (command.kind) {+ case 'close':+ this.close(page);+ return {};+ case 'asset': {+ const file = page.files.find((f) => f.path === command.path);+ if (!file || command.offset > file.size) return fail();+ return done(await this.deps.asset(ghost, file, command.offset));+ }+ case 'subscribe': {+ const channels = [...new Set([...(page.channels ?? []), ...command.channels])];+ if (channels.length > 16) return fail();+ await this.deps.connect(ghost, page.id, channels);+ page.channels = channels;+ return done({});+ }+ case 'post':+ if (!page.channels?.includes(command.channel)) return fail();+ await this.deps.post(ghost, page.id, command.channel, command.data);+ return done({});+ case 'unsubscribe': {+ const channels = (page.channels ?? []).filter((name) => name !== command.channel);+ await this.deps.connect(ghost, page.id, channels);+ page.channels = channels;+ return done({});+ }+ case 'poll':+ return done({+ events: page.channels?.length ? await this.deps.poll(ghost, page.id, command.after) : [],+ confirms: [...page.confirms.values()].map((p) => p.value),+ notifications: page.notices.splice(0),+ directories: page.directory ? [page.directory.value] : [],+ });+ case 'confirm': {+ const pending = page.confirms.get(command.requestId);+ if (!pending || pending.value.expiresAt <= this.now()) return fail();+ clearTimeout(pending.timer);+ page.confirms.delete(command.requestId);+ pending.answer(command.accepted);+ return {};+ }+ case 'answer-directory':+ await this.answerDirectory(page, command);+ return done({});+ case 'authorization-result': {+ const authorization = page.authorizations?.get(command.requestId);+ if (!authorization?.result) return fail();+ const result = authorization.result;+ page.authorizations!.delete(command.requestId);+ return result;+ }+ case 'authorize': {+ const match = /^\/oauth\/([a-zA-Z0-9_-]+)\/connect$/.exec(command.path);+ if (+ !match ||+ !ghost.manifest.network?.secrets?.some((s) => s.key === match[1] && s.source === 'oauth')+ )+ return fail();+ page.authorizations ??= new Map();+ if (page.authorizations.size >= 4) return fail();+ const id = randomUUID();+ page.authorizations.set(id, { path: command.path, body: command.body, running: false });+ return { requestId: id, actionId: 'settings-oauth', expectedRevision: 0 };+ }+ case 'fetch': {+ if (!command.path.startsWith('/') || command.path.startsWith('//')) return fail();+ const url = new URL(command.path, 'https://plugin.invalid');+ if (+ url.origin !== 'https://plugin.invalid' ||+ url.hash ||+ !/^\/(?:kv|app-context|agent-models|media-models|secrets(?:\/[^/]+)?|oauth(?:\/[^/]+\/(?:client|default|insufficient-scopes|accounts\/[^/]+))?|connections(?:\/[^/]+(?:\/[^/]+)?)?|wake)$/.test(+ url.pathname,+ )+ )+ return fail();+ return done(+ await this.deps.settingsFetch!(+ ghost,+ url.pathname + url.search,+ command.method,+ command.body,+ current,+ (label, host) =>+ this.confirm(page.id, {+ ghostId: page.plugin,+ ghostName: ghost.manifest.name,+ iconDataUrl: ghost.iconDataUrl,+ body:+ t('settings.ghosts.connections.confirmMessage')+ .replaceAll('{{name}}', ghost.manifest.name)+ .replaceAll('{{host}}', host) ++ '\n\n' ++ t('settings.ghosts.connections.confirmDetail').replaceAll('{{label}}', label),+ confirmText: t('settings.ghosts.connections.confirmAllow'),+ cancelText: t('settings.ghosts.connections.confirmCancel'),+ danger: false,+ }),+ ),+ );+ }+ }+ }+ private async answerDirectory(+ page: Page,+ input: { requestId?: unknown; path?: unknown },+ ): Promise<void> {+ if (+ !page.active ||+ typeof input.requestId !== 'string' ||+ !(+ input.path === null ||+ (typeof input.path === 'string' && input.path.length > 0 && input.path.length <= 4096)+ )+ )+ return fail();+ const receipt = createHash('sha256').update(JSON.stringify(input.path)).digest('hex');+ const previous = page.directoryAnswers?.get(input.requestId);+ if (previous) {+ if (previous !== receipt) return fail();+ return;+ }+ const pending = page.directory;+ if (+ !pending ||+ pending.value.id !== input.requestId ||+ pending.answering ||+ pending.value.expiresAt <= this.now()+ )+ return fail();+ pending.answering = true;+ try {+ const path =+ input.path === null ? null : await this.deps.validateDirectory!(input.path as string);+ this.check(page);+ if (!page.active || page.directory !== pending || pending.value.expiresAt <= this.now())+ return fail();+ clearTimeout(pending.timer);+ page.directory = undefined;+ page.directoryAnswers ??= new Map();+ page.directoryAnswers.set(input.requestId, receipt);+ if (page.directoryAnswers.size > 32)+ page.directoryAnswers.delete(page.directoryAnswers.keys().next().value!);+ pending.answer(path);+ return;+ } finally {+ pending.answering = false;+ }+ }private cancelDirectory(page: Page) {if (!page.directory) return;clearTimeout(page.directory.timer);@@ -304,7 +557,10 @@ export class MobilePluginPages {});});}- private item(ghost: InstalledGhost, order?: RemoteCollectionItem['pluginOrder']): RemoteCollectionItem {+ private item(+ ghost: InstalledGhost,+ order?: RemoteCollectionItem['pluginOrder'],+ ): RemoteCollectionItem {const m = ghost.manifest;const id = installedGhostStoragePart(ghost);const mobile = parsePluginMobileDeclaration(m.mobile);@@ -358,11 +614,18 @@ export class MobilePluginPages {resourceKind: 'plugin',title: { fallback: 'Plugins', translations: { 'zh-CN': '插件' } },icon: { name: 'puzzle', fallbackText: 'P' },+ ...(this.deps.management+ ? { actions: [{ id: 'management:snapshot', label: 'Manage plugins' }] }+ : {}),},list: async (_ctx, request) => {this.sweep();let order: ReturnType<NonNullable<Dependencies['listOrder']>> | undefined;- try { order = this.deps.listOrder?.(); } catch { /* Optional ordering cannot block the list. */ }+ try {+ order = this.deps.listOrder?.();+ } catch {+ /* Optional ordering cannot block the list. */+ }const q = request.query?.toLocaleLowerCase();const items = this.deps.list()@@ -384,24 +647,77 @@ export class MobilePluginPages {const locale = resolvePreferredSystemLocale([request.client.locale ?? 'en']);// Read-only declaration facts and copy shared with PC; no saved values leave Host.const permissionText = (key: string, args?: Record<string, string>) =>- t(`settings.ghosts.perm.${key}`, locale).replace(/\{\{(\w+)\}\}/g, (match, name: string) => args?.[name] ?? match);+ t(`settings.ghosts.perm.${key}`, locale).replace(+ /\{\{(\w+)\}\}/g,+ (match, name: string) => args?.[name] ?? match,+ );const permissions = ghostPermissionItems(ghost.manifest)- .filter(permission => permission.kind !== 'tool')- .map(permission => ({+ .filter((permission) => permission.kind !== 'tool')+ .map((permission) => ({title: permissionText(permission.labelKey, permission.labelArgs),description: [- permission.detailKey ? permissionText(permission.detailKey, permission.detailArgs) : '',+ permission.detailKey+ ? permissionText(permission.detailKey, permission.detailArgs)+ : '',permission.detail ?? '',- ].filter(Boolean).join('\n\n'),+ ]+ .filter(Boolean)+ .join('\n\n'),}));const detailFacts = [- {key: 'version', title: t('settings.ghosts.detail.infoVersion', locale), value: 'v' + ghost.manifest.version},- ...(ghost.manifest.author ? [{key: 'author', title: t('settings.ghosts.detail.infoAuthor', locale), value: ghost.manifest.author}] : []),- {key: 'trust', title: t('settings.ghosts.detail.infoTrust', locale), value: t('settings.ghosts.trust.' + ghostTrustLabelKey(ghost.trust), locale).replaceAll('{{publisher}}', ghost.trust?.publisherName ?? t('settings.ghosts.trust.unknownPublisher', locale))},- {key: 'identifier', title: t('settings.ghosts.detail.infoId', locale), value: ghost.manifest.id},- {key: 'contents', title: t('settings.ghosts.detail.infoContents', locale), value: ghostContentKeys(ghost.manifest).map(key => t('settings.ghosts.contents.' + key, locale)).join(' · ')},- {key: 'panel', title: t('settings.ghosts.detail.infoPanel', locale), value: t(ghost.manifest.panel ? 'settings.ghosts.contents.panel' : 'settings.ghosts.detail.panelNone', locale)},- ...(ghost.dir ? [{key: 'location', title: t('settings.ghosts.detail.infoLocation', locale), value: ghost.dir}] : []),+ {+ key: 'version',+ title: t('settings.ghosts.detail.infoVersion', locale),+ value: 'v' + ghost.manifest.version,+ },+ ...(ghost.manifest.author+ ? [+ {+ key: 'author',+ title: t('settings.ghosts.detail.infoAuthor', locale),+ value: ghost.manifest.author,+ },+ ]+ : []),+ {+ key: 'trust',+ title: t('settings.ghosts.detail.infoTrust', locale),+ value: t('settings.ghosts.trust.' + ghostTrustLabelKey(ghost.trust), locale).replaceAll(+ '{{publisher}}',+ ghost.trust?.publisherName ?? t('settings.ghosts.trust.unknownPublisher', locale),+ ),+ },+ {+ key: 'identifier',+ title: t('settings.ghosts.detail.infoId', locale),+ value: ghost.manifest.id,+ },+ {+ key: 'contents',+ title: t('settings.ghosts.detail.infoContents', locale),+ value: ghostContentKeys(ghost.manifest)+ .map((key) => t('settings.ghosts.contents.' + key, locale))+ .join(' · '),+ },+ {+ key: 'panel',+ title: t('settings.ghosts.detail.infoPanel', locale),+ value: t(+ ghost.manifest.panel+ ? 'settings.ghosts.contents.panel'+ : 'settings.ghosts.detail.panelNone',+ locale,+ ),+ },+ ...(ghost.dir+ ? [+ {+ key: 'location',+ title: t('settings.ghosts.detail.infoLocation', locale),+ value: ghost.dir,+ },+ ]+ : []),];let assessment: GhostSetupAssessment | undefined;try {@@ -411,7 +727,9 @@ export class MobilePluginPages {}let configuration = mobilePluginConfiguration(ghost.manifest, undefined, assessment);try {- configuration = this.deps.configuration?.(installedGhostStoragePart(ghost), assessment) ?? configuration;+ configuration =+ this.deps.configuration?.(installedGhostStoragePart(ghost), assessment) ??+ configuration;} catch {// A failed configuration read retains declarations with unknown status.}@@ -451,6 +769,14 @@ export class MobilePluginPages {},invoke: async (context, request) => {this.sweep();+ if (request.actionId.startsWith('management:')) {+ if (!this.deps.management)+ throw new RemoteResourceRegistryError(+ 'UNSUPPORTED_CAPABILITY',+ 'Update Cindy on the target computer',+ );+ return this.deps.management.invoke(context.controllerDeviceId, request);+ }const input = record(request.input);const id = request.resourceRef?.id;if (!id) return fail();@@ -509,6 +835,49 @@ export class MobilePluginPages {for (const page of this.pages.values()) if (page.plugin === id) this.close(page);return { effects: [{ kind: 'refresh-collection', collectionId: PLUGIN_COLLECTION }] };}+ if (request.actionId === 'settings:open') {+ const ghost = this.ghost(id);+ if (+ !this.deps.settingsFetch ||+ !ghost.enabled ||+ !ghost.manifest.settingsHtml ||+ input.expectedInstalledApproval !== ghostInstallApprovalToken(ghost.approval) ||+ this.pages.size >= 32+ )+ return fail();+ const page: Page = {+ id: randomUUID(),+ plugin: id,+ controller: context.controllerDeviceId,+ revision: this.deps.revision(ghost),+ currentOwner: this.deps.captureOwner(),+ currentController: this.deps.captureController(context.controllerDeviceId),+ surface: 'settings',+ desktopSettings: true,+ active: true,+ touchedAt: this.now(),+ files: [],+ confirms: new Map(),+ notices: [],+ answered: new Map(),+ };+ this.check(page);+ page.files = await this.deps.bundle(ghost, ghost.manifest.settingsHtml);+ this.check(page);+ if (this.pages.size >= 32) return fail();+ this.pages.set(page.id, page);+ return {+ effects: [],+ result: {+ pageId: page.id,+ pluginId: id,+ manifestId: ghost.manifest.id,+ name: ghost.manifest.name,+ entry: ghost.manifest.settingsHtml,+ files: page.files,+ },+ };+ }if (request.actionId.startsWith('open:')) {const surface = request.actionId.slice(5);if (!isPluginPageSurface(surface)) return fail();@@ -564,6 +933,8 @@ export class MobilePluginPages {return { effects: [], result };}const page = this.page(input.pageId, context.controllerDeviceId);+ // Desktop configuration values only cross the authenticated encrypted bridge.+ if (page.desktopSettings) return fail();if (page.plugin !== id) return fail();const ghost = this.check(page);switch (request.actionId) {@@ -696,57 +1067,9 @@ export class MobilePluginPages {page.previews?.delete(input.intentId);return { effects: [] };}- case 'answer-directory': {- if (- !page.active ||- typeof input.requestId !== 'string' ||- !(- input.path === null ||- (typeof input.path === 'string' &&- input.path.length > 0 &&- input.path.length <= 4096)- )- )- return fail();- const receipt = createHash('sha256').update(JSON.stringify(input.path)).digest('hex');- const previous = page.directoryAnswers?.get(input.requestId);- if (previous) {- if (previous !== receipt) return fail();- return { effects: [] };- }- const pending = page.directory;- if (- !pending ||- pending.value.id !== input.requestId ||- pending.answering ||- pending.value.expiresAt <= this.now()- )- return fail();- pending.answering = true;- try {- const path =- input.path === null- ? null- : await this.deps.validateDirectory!(input.path as string);- this.check(page);- if (- !page.active ||- page.directory !== pending ||- pending.value.expiresAt <= this.now()- )- return fail();- clearTimeout(pending.timer);- page.directory = undefined;- page.directoryAnswers ??= new Map();- page.directoryAnswers.set(input.requestId, receipt);- if (page.directoryAnswers.size > 32)- page.directoryAnswers.delete(page.directoryAnswers.keys().next().value!);- pending.answer(path);- return { effects: [] };- } finally {- pending.answering = false;- }- }+ case 'answer-directory':+ await this.answerDirectory(page, input);+ return { effects: [] };case 'answer': {const pending =typeof input.confirmId === 'string' ? page.confirms.get(input.confirmId) : null;diff --git a/apps/desktop/src/main/cindy-brain/remotePluginManagement.ts b/apps/desktop/src/main/cindy-brain/remotePluginManagement.tsnew file mode 100644index 0000000000..4d6a5b6726--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/remotePluginManagement.ts@@ -0,0 +1,479 @@+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,+ ): 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,+ );+ 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 --git a/apps/desktop/src/main/cindy-brain/remotePluginPreferences.ts b/apps/desktop/src/main/cindy-brain/remotePluginPreferences.tsnew file mode 100644index 0000000000..e236f77d02--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/remotePluginPreferences.ts@@ -0,0 +1,84 @@+import { createHash } from 'node:crypto';+import type { InstalledGhost } from '../../shared/ghost.js';+import { ghostInstallApprovalToken } from '../../shared/ghost.js';+import {+ pluginHasModelPreferences,+ type RemotePluginPreferenceSnapshot,+} from '../../shared/pluginPreferences.js';+import type { MobileTaskSettings } from './mobileTaskSettings.js';++interface Dependencies {+ auxiliaryModelLabel(): string | null;+ tasks: Pick<MobileTaskSettings, 'read' | 'update'>;+ sidebar: {+ read(id: string): boolean;+ write(id: string, visible: boolean, assertCurrent: () => void): Promise<void>;+ };+}++/** Reuses the target Host's preference stores and compares revisions before a write. */+export class RemotePluginPreferences {+ constructor(private readonly deps: Dependencies) {}++ read(id: string, ghost: InstalledGhost): RemotePluginPreferenceSnapshot {+ const data: Omit<RemotePluginPreferenceSnapshot, 'revision'> = {};+ const installation = ghostInstallApprovalToken(ghost.approval);+ if (pluginHasModelPreferences(ghost.manifest)) {+ data.tasks = this.deps.tasks.read(id, installation);+ data.auxiliaryModelLabel = this.deps.auxiliaryModelLabel();+ }+ if (ghost.manifest.mainView?.html) data.sidebarVisible = this.deps.sidebar.read(id);+ return {+ ...data,+ revision: createHash('sha256')+ .update(JSON.stringify([installation, data]))+ .digest('hex'),+ };+ }++ async update(+ id: string,+ ghost: InstalledGhost,+ input: Record<string, unknown>,+ assertCurrent: () => void,+ ): Promise<RemotePluginPreferenceSnapshot> {+ const check = () => {+ assertCurrent();+ if (input.expectedRevision !== this.read(id, ghost).revision)+ throw new Error('PLUGIN_SETTINGS_CHANGED');+ };+ check();+ switch (input.kind) {+ case 'tasks': {+ const tasks = this.read(id, ghost).tasks;+ if (+ !tasks ||+ !input.patch ||+ typeof input.patch !== 'object' ||+ Array.isArray(input.patch) ||+ Object.keys(input.patch).some((key) => !['model', 'permissionMode'].includes(key))+ )+ throw new Error('PLUGIN_SETTINGS_INVALID');+ await this.deps.tasks.update(+ id,+ ghostInstallApprovalToken(ghost.approval),+ {+ ...input.patch,+ expectedRevision: tasks.revision,+ },+ check,+ );+ break;+ }+ case 'sidebar':+ if (!ghost.manifest.mainView?.html || typeof input.visible !== 'boolean')+ throw new Error('PLUGIN_SETTINGS_INVALID');+ await this.deps.sidebar.write(id, input.visible, check);+ break;+ default:+ throw new Error('PLUGIN_SETTINGS_INVALID');+ }+ assertCurrent();+ return this.read(id, ghost);+ }+}diff --git a/apps/desktop/src/main/cindy-brain/remotePluginProjects.ts b/apps/desktop/src/main/cindy-brain/remotePluginProjects.tsnew file mode 100644index 0000000000..0aba58dfe8--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/remotePluginProjects.ts@@ -0,0 +1,23 @@+import { createHash } from 'node:crypto';+import { stat } from 'node:fs/promises';+import path from 'node:path';+import { normalizeWorkdirKey } from './ghostWorkdirPrefs.js';+import type { PluginManagementProject } from '../../shared/pluginManagement.js';++export type RemotePluginProject = PluginManagementProject & { workdir: string };++export function projectPluginWorkdir(workdir: string): RemotePluginProject {+ return {+ id: createHash('sha256').update(normalizeWorkdirKey(workdir)).digest('hex'),+ name: path.basename(workdir) || workdir,+ path: workdir,+ workdir,+ };+}++/** Only the selected Host resolves browser output; subsequent writes use its issued ID. */+export async function resolvePluginWorkdir(workdir: string): Promise<RemotePluginProject> {+ if (!path.isAbsolute(workdir) || workdir.includes('\0') || !(await stat(workdir)).isDirectory())+ throw new Error('INVALID_PROJECT_DIRECTORY');+ return projectPluginWorkdir(workdir);+}diff --git a/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.ts b/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.tsnew file mode 100644index 0000000000..05e1a0cc2c--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/remotePluginSettingsController.ts@@ -0,0 +1,504 @@+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;+ 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();+ };+ 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) {+ renew ??= connect().finally(() => {+ renew = undefined;+ });+ await renew;+ }+ assertCurrent();+ 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 --git a/apps/desktop/src/main/cindy-brain/remoteSettingsBroadcast.ts b/apps/desktop/src/main/cindy-brain/remoteSettingsBroadcast.tsnew file mode 100644index 0000000000..04a4f26d3c--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/remoteSettingsBroadcast.ts@@ -0,0 +1,83 @@+/** Installed settings scripts keep using BroadcastChannel; only its transport changes. */+function bridge(endpoint: string) {+ const call = async (command: unknown) => {+ const response = await fetch(endpoint, { method: 'POST', body: JSON.stringify(command) });+ if (!response.ok) throw new Error('PLUGIN_PAGE_UNAVAILABLE');+ return response.json();+ };+ const channels = new Map<string, Set<RemoteChannel>>();+ let ready = Promise.resolve(),+ after = 0,+ polling = false;+ async function poll() {+ if (polling) return;+ polling = true;+ try {+ await ready;+ const result = await call({ kind: 'poll', after });+ for (const event of result.events) {+ for (const channel of channels.get(event.channel) ?? []) channel.deliver(event.data);+ after = Math.max(after, event.sequence);+ }+ } catch {+ for (const group of channels.values()) for (const channel of group) channel.deliverError();+ } finally {+ polling = false;+ if (channels.size) setTimeout(() => void poll(), 800);+ }+ }+ class RemoteChannel extends EventTarget {+ // This function is serialized into the guest; avoid emitted class-field helpers.+ declare readonly name: string;+ declare onmessage: ((event: MessageEvent) => void) | null;+ declare onmessageerror: ((event: MessageEvent) => void) | null;+ declare private closed: boolean;+ constructor(name: string) {+ super();+ this.name = String(name);+ this.onmessage = null;+ this.onmessageerror = null;+ this.closed = false;+ const members = channels.get(this.name) ?? new Set();+ members.add(this);+ channels.set(this.name, members);+ ready = ready.then(() => call({ kind: 'subscribe', channels: [this.name] }));+ void poll();+ }+ postMessage(data: unknown) {+ if (this.closed) throw new DOMException('Channel closed', 'InvalidStateError');+ const copy = structuredClone(data);+ void ready+ .then(() => call({ kind: 'post', channel: this.name, data: copy }))+ .catch(() => this.deliverError());+ }+ close() {+ if (this.closed) return;+ this.closed = true;+ const members = channels.get(this.name);+ members?.delete(this);+ if (!members?.size) {+ channels.delete(this.name);+ ready = ready.then(() => call({ kind: 'unsubscribe', channel: this.name }));+ void ready.catch(() => {});+ }+ }+ deliver(data: unknown) {+ if (this.closed) return;+ const event = new MessageEvent('message', { data });+ this.onmessage?.(event);+ this.dispatchEvent(event);+ }+ deliverError() {+ if (this.closed) return;+ const event = new MessageEvent('messageerror');+ this.onmessageerror?.(event);+ this.dispatchEvent(event);+ }+ }+ Object.defineProperty(window, 'BroadcastChannel', { value: RemoteChannel });+}++export function remoteSettingsBroadcastScript(endpoint: string): string {+ return '(' + bridge.toString() + ')(' + JSON.stringify(endpoint) + ');';+}diff --git a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.tsindex e4acfb861a..612acc1a4e 100644--- a/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts+++ b/apps/desktop/src/main/cindy-brain/runtime/electronSandboxAdapter.ts@@ -194,6 +194,34 @@ export async function fetchGhostMobilePage(ghost: InstalledGhost, pathname: stri};}+/** Same configuration executors as local settings, with the remote lease checked at persistence. */+export async function fetchGhostSettings(ghost: InstalledGhost, pathname: string, method: string, body: string | undefined, current: () => boolean, confirmConnection?: (label: string, host: string) => Promise<boolean>) {+ const partition = ownerScopedGhostPartitionForInstalledGhost(ghost, getActiveAppSession());+ if (!partition || !current()) throw new Error('PLUGIN_PAGE_UNAVAILABLE');+ ensureGhostProtocolRegistered(ghost);+ const target = captureGhostProtocolTargetGuard(partition);+ const isCurrent = () => current() && target();+ const id = installedGhostStoragePart(ghost), path = new URL(pathname, 'https://plugin.invalid').pathname;+ if (!isCurrent()) throw new Error('PLUGIN_PAGE_UNAVAILABLE');+ const args = { ghostId: id, pathname: path, method, readBodyText: async () => body ?? '', isCurrent, confirmConnection };+ const handler = path === '/secrets' || path.startsWith('/secrets/') ? ghostSecretsHandler+ : path === '/oauth' || path.startsWith('/oauth/') ? ghostOauthHandler+ : path === '/connections' || path.startsWith('/connections/') ? ghostConnectionsHandler : null;+ let result: { status: number; body?: string };+ if (handler) result = await handler(args);+ else if (path === '/kv' && ghostKvStore) result = await handleGhostKvRequest({+ method, readBodyText: args.readBodyText, store: ghostKvStore, ghostId: id, isCurrent,+ });+ else {+ if (method !== 'GET') return { status: 405, mime: 'application/json', base64: '' };+ const response = await fetchGhostMobilePage(ghost, pathname, method);+ if (!isCurrent()) throw new Error('PLUGIN_PAGE_UNAVAILABLE');+ return response;+ }+ if (!isCurrent()) throw new Error('PLUGIN_PAGE_UNAVAILABLE');+ return { status: result.status, mime: 'application/json', base64: Buffer.from(result.body ?? '').toString('base64') };+}+// 管子桥 preload 的产物路径(与 main bundle 同目录,forge VitePlugin 出的// .vite/build/ghostPreload.js;__dirname 在 dev/prod 都指向 .vite/build)。const GHOST_PRELOAD_PATH = path.join(@@ -312,6 +340,7 @@ type GhostConnectionsProtocolHandler = (args: {pathname: string;readBodyText: () => Promise<string>;isCurrent: () => boolean;+ confirmConnection?: (label: string, host: string) => Promise<boolean>;}) => Promise<{ status: number; body?: string }>;let ghostConnectionsHandler: GhostConnectionsProtocolHandler | null = null;@@ -373,7 +402,7 @@ export function revokeLegacyGhostProtocolPartition(ghostId: string): void {* data:/blob:。* 与分区级断网(onBeforeRequest)构成双保险。*/-const GHOST_HTML_CSP =+export const GHOST_HTML_CSP ="default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; media-src 'self' data: blob:";function createGhostProtocolTargetGuard(diff --git a/apps/desktop/src/main/cindy-brain/runtime/mobilePageRelay.ts b/apps/desktop/src/main/cindy-brain/runtime/mobilePageRelay.tsindex 90e21d4bee..3194e105e4 100644--- a/apps/desktop/src/main/cindy-brain/runtime/mobilePageRelay.ts+++ b/apps/desktop/src/main/cindy-brain/runtime/mobilePageRelay.ts@@ -19,10 +19,18 @@ function relay(operation: MobileRelayOperation) {const pages: Map<string, Page> = (root.__cindyMobilePages ??= new Map<string, Page>());let page: Page | undefined = pages.get(operation.pageId);if (operation.op === 'connect') {- if (page) return;- page = { channels: new Map(), events: [], sequence: 0, bytes: 0, overflow: false };+ page ??= { channels: new Map(), events: [], sequence: 0, bytes: 0, overflow: false };const target = page;+ for (const [name, channel] of target.channels) {+ if (!operation.channels.includes(name)) {+ channel.close();+ target.channels.delete(name);+ }+ }+ target.events = target.events.filter((event) => operation.channels.includes(event.channel));+ target.bytes = new TextEncoder().encode(JSON.stringify(target.events)).length;for (const name of operation.channels) {+ if (target.channels.has(name)) continue;const channel = new BroadcastChannel(name);channel.onmessage = (event) => {let data: unknown, bytes: number;diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.tsindex 1752f29400..3146c84c8f 100644--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts@@ -202,6 +202,14 @@ beforeEach(() => {registerDeviceLinkIpc();});+it('rejects Renderer-supplied remote Skill approval before forwarding any request', async () => {+ await expect(call(DEVICE_LINK_INVOKE.INVOKE, {+ deviceId: 'private-peer', channel: 'maker:remote-resources:invoke',+ args: [{ collectionId: 'skills', actionId: 'management:answer', input: { accepted: true } }],+ })).rejects.toThrow('PERMISSION_DENIED');+ expect(remoteInvoke).not.toHaveBeenCalled();+});+it.each([1_000, 30_000])('flushes completed calls on quit after %i ms without duplicate summaries', async (elapsed) => {vi.useFakeTimers();try {diff --git a/apps/desktop/src/main/device-link/__tests__/remoteSkillConfirmation.test.ts b/apps/desktop/src/main/device-link/__tests__/remoteSkillConfirmation.test.tsnew file mode 100644index 0000000000..e0ddc47aa1--- /dev/null+++ b/apps/desktop/src/main/device-link/__tests__/remoteSkillConfirmation.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it, vi } from 'vitest';+import { confirmRemoteSkillMutation, isRemoteSkillApproval } from '../remoteSkillConfirmation';+import { REMOTE_RESOURCE_INVOKE_CHANNEL } from '@cindy/device-link';++const receipt = {+ operationId: 'op',+ phase: 'confirmation',+ confirmation: { kind: 'uninstall', name: 'fixture', requestId: 'request' },+};+describe('remote Skill native confirmation', () => {+ it('reads Host facts and sends the exact request after a native decision', async () => {+ const invoke = vi.fn(async (action) =>+ action === 'operation' ? receipt : { operationId: 'op', phase: 'running' },+ );+ const prompt = vi.fn(async () => true),+ current = vi.fn();+ await confirmRemoteSkillMutation({ invoke, prompt, current }, 'op');+ expect(prompt).toHaveBeenCalledWith(receipt.confirmation);+ expect(invoke).toHaveBeenLastCalledWith('answer', {+ operationId: 'op',+ requestId: 'request',+ accepted: true,+ });+ });+ it('never approves after navigation, account switch or target revocation during the dialog', async () => {+ let valid = true;+ const invoke = vi.fn(async () => receipt);+ await expect(+ confirmRemoteSkillMutation(+ {+ invoke,+ current: () => {+ if (!valid) throw Error('stale');+ },+ prompt: async () => {+ valid = false;+ return true;+ },+ },+ 'op',+ ),+ ).rejects.toThrow('stale');+ expect(invoke).toHaveBeenCalledOnce();+ });+ it('blocks direct generic Renderer approval while preserving ordinary remote reads and plugin actions', () => {+ expect(+ isRemoteSkillApproval(REMOTE_RESOURCE_INVOKE_CHANNEL, [+ { collectionId: 'skills', actionId: 'management:answer' },+ ]),+ ).toBe(true);+ expect(+ isRemoteSkillApproval(REMOTE_RESOURCE_INVOKE_CHANNEL, [+ { collectionId: 'skills', actionId: 'management:snapshot' },+ ]),+ ).toBe(false);+ expect(+ isRemoteSkillApproval(REMOTE_RESOURCE_INVOKE_CHANNEL, [+ { collectionId: 'plugins', actionId: 'management:answer' },+ ]),+ ).toBe(false);+ });+ it('rejects malformed Host confirmation before opening the native dialog', async () => {+ const prompt = vi.fn();+ await expect(+ confirmRemoteSkillMutation(+ {+ invoke: async () => ({+ ...receipt,+ confirmation: { ...receipt.confirmation, kind: 'arbitrary' },+ }),+ current: () => {},+ prompt,+ },+ 'op',+ ),+ ).rejects.toThrow('INVALID_RESPONSE');+ expect(prompt).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.tsindex 2a18d25efe..02feebb56f 100644--- a/apps/desktop/src/main/device-link/ipc.ts+++ b/apps/desktop/src/main/device-link/ipc.ts@@ -5,8 +5,21 @@* ipcMain.handle 只做 adapter),__tests__ 用内存 harness 直接调 handler body。*/+import { promises as pluginFileFs } from 'node:fs';+import { PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES } from '@cindy/plugin-protocol';+import { capturePluginOauthPeer } from '../plugin-oauth/runtime.js';+import { openRemotePluginSettings, closeRemotePluginSettings, answerRemotePluginSettingsDirectory } from '../cindy-brain/remotePluginSettingsController.js';+import { REMOTE_PLUGIN_SETTINGS_OPEN, REMOTE_PLUGIN_SETTINGS_CLOSE, REMOTE_PLUGIN_SETTINGS_DIRECTORY_ANSWER } from '../../shared/remotePluginSettings.js';+import {+ REMOTE_RESOURCE_MANIFEST_CHANNEL,+ REMOTE_RESOURCE_INVOKE_CHANNEL,+ REMOTE_RESOURCE_PROTOCOL_VERSION,+ isProviderSharePeer,+} from '@cindy/device-link';+import { confirmRemoteSkillMutation, isRemoteSkillApproval } from './remoteSkillConfirmation';+import { t } from '../i18n';import { createHash, randomBytes } from 'node:crypto';-import { ipcMain, shell, clipboard } from 'electron';+import { ipcMain, shell, clipboard, dialog, BrowserWindow } from 'electron';import { MCP_APPS_INVOKE } from '../../shared/mcpApps.js';import { currentOauthIdentityScope, trustOauthPeer } from '../plugin-oauth/desktopIdentity.js';import { RemotePluginOauthUnsupportedError, resolveOauthPeerIdentity } from '../plugin-oauth/identityResolver.js';@@ -1434,6 +1447,104 @@ export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()):try { return await deviceCodes.handle(scope, raw); }catch { throwIpcError('PRECONDITION_FAILED', 'Authorization code unavailable; retry from the current card'); }});+ const skillConfirmations = new Set<number>();+ ipcMain.handle('device-link:confirm-skill-mutation', async (event, raw: unknown) => {+ assertTrustedAppRendererEvent(event);+ requireDeviceLinkCapability();+ const request = (raw ?? {}) as { deviceId?: unknown; operationId?: unknown };+ const deviceId = requireString(request.deviceId, 'deviceId');+ const operationId = requireString(request.operationId, 'operationId');+ if (+ deviceId.length > 256 || operationId.length > 64 || parseSharedTaskPeer(deviceId) ||+ isProviderSharePeer(deviceId) || deviceId === getDeviceId()+ ) throwIpcError('INVALID_PARAMS', 'Expected a same-account computer');+ const owner = activeOwnerScopeKey();+ const peerCurrent = capturePluginOauthPeer(deviceId);+ const parent = BrowserWindow.fromWebContents(event.sender);+ if (!parent || parent.isDestroyed() || skillConfirmations.has(event.sender.id)) {+ throwIpcError('PRECONDITION_FAILED', 'Skill confirmation unavailable');+ }+ let navigated = false;+ const invalidate = () => { navigated = true; };+ event.sender.on('did-start-navigation', invalidate);+ const current = () => {+ peerCurrent();+ assertTrustedAppRendererEvent(event);+ assertControlTargetEnabled(deps, deviceId);+ if (+ navigated || parent.isDestroyed() || event.sender.isDestroyed() ||+ isAppSessionBoundaryPending() || owner !== activeOwnerScopeKey()+ ) throwIpcError('PRECONDITION_FAILED', 'Skill confirmation expired');+ };+ skillConfirmations.add(event.sender.id);+ try {+ return await confirmRemoteSkillMutation({+ current,+ invoke: async (action, input) => {+ const response = await deps.invoke(deviceId, REMOTE_RESOURCE_INVOKE_CHANNEL, [{+ collectionId: 'skills', actionId: `management:${action}`,+ client: { protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION, primitives: [] }, input,+ }]);+ if (!response.ok) throwIpcError('PRECONDITION_FAILED', 'Skill confirmation unavailable');+ return (response.result as { result?: unknown })?.result;+ },+ prompt: async facts => {+ const device = deps.readLastKnownDeviceNames()[deviceId] ?? deviceId;+ const message = t(`skillhub.remote.confirm.${facts.kind}`)+ .replace('{{name}}', () => facts.name)+ .replace('{{device}}', () => device)+ .replace('{{version}}', () => facts.version ?? '');+ const detail = facts.kind === 'uninstall'+ ? t(facts.linkOnly ? 'skillhub.management.unlinkDescription' : 'skillhub.management.trashDescription')+ : t('skillhub.remote.confirm.installDescription');+ const { response } = await dialog.showMessageBox(parent, {+ type: 'warning', title: message, message, detail,+ buttons: [t('commonUi.confirmDialog.confirm'), t('commonUi.confirmDialog.cancel')],+ defaultId: 1, cancelId: 1, noLink: true,+ });+ return response === 0;+ },+ }, operationId);+ } finally {+ skillConfirmations.delete(event.sender.id);+ event.sender.removeListener('did-start-navigation', invalidate);+ }+ });+ // The native picker grants only this file; no renderer-supplied filesystem path.+ ipcMain.handle('device-link:pick-plugin-package', async (event, raw: unknown) => {+ assertTrustedAppRendererEvent(event);+ requireDeviceLinkCapability();+ const deviceId = requireString(raw, 'deviceId');+ if (parseSharedTaskPeer(deviceId) || isProviderSharePeer(deviceId) || deviceId === getDeviceId()) throwIpcError('INVALID_PARAMS', 'Expected a same-account target computer');+ const owner = activeOwnerScopeKey(), peerCurrent = capturePluginOauthPeer(deviceId);+ const assertCurrent = () => {+ peerCurrent(); assertTrustedAppRendererEvent(event);+ if (event.sender.isDestroyed() || isAppSessionBoundaryPending() || owner !== activeOwnerScopeKey())+ throwIpcError('PRECONDITION_FAILED', 'Plugin upload is no longer current');+ assertControlTargetEnabled(deps, deviceId);+ };+ assertCurrent();+ await deps.openLink(deviceId);+ assertCurrent();+ const caps = await deps.invoke(deviceId, REMOTE_RESOURCE_MANIFEST_CHANNEL, [{ client: { protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION, primitives: [] } }]);+ assertCurrent();+ const manifest = caps.ok ? caps.result as { collections?: Array<{ id: string; actions?: Array<{ id: string }> }> } : null;+ if (!manifest?.collections?.some(c => c.id === 'plugins' && c.actions?.some(a => a.id === 'management:snapshot')))+ throwIpcError('UNSUPPORTED_CAPABILITY', 'Update Cindy on the target computer');+ const win = BrowserWindow.fromWebContents(event.sender);+ const options = { filters: [{ name: t('settings.ghosts.detail.exportFileType'), extensions: ['cindy'] }], properties: ['openFile' as const] };+ const picked = win ? await dialog.showOpenDialog(win, options) : await dialog.showOpenDialog(options);+ assertCurrent();+ if (picked.canceled || picked.filePaths.length !== 1) return null;+ const file = picked.filePaths[0];+ const stat = await pluginFileFs.lstat(file);+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES) throwIpcError('GHOST_FILE_INVALID', 'Invalid plugin file');+ assertCurrent();+ const attachment = await tryUploadPeerAttachment(deviceId, file, 'application/octet-stream', deps.invoke);+ assertCurrent();+ if (!attachment) throwIpcError('UNSUPPORTED_CAPABILITY', 'Secure plugin file transfer is unavailable');+ return { attachment };+ });const localOauthDeps = (event: import('electron').IpcMainInvokeEvent): LocalOauthDeps => ({owner: () => !isAppSessionBoundaryPending() && getActiveAppSession().mode === 'cloud' ? activeOwnerScopeKey() : null,assertTarget: deviceId => {@@ -1461,6 +1572,23 @@ export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()):throwIpcError('UNSUPPORTED_CAPABILITY', 'Update Cindy on the remote device to use remote plugin authorization');throwIpcError('PRECONDITION_FAILED', 'Remote authorization unavailable; retry from the current card');};+ ipcMain.handle(REMOTE_PLUGIN_SETTINGS_OPEN, async (event, raw: unknown) => {+ assertTrustedAppRendererEvent(event);+ try {+ return await openRemotePluginSettings(event.sender, localOauthDeps(event), raw);+ } catch {+ throwIpcError('PRECONDITION_FAILED', 'Remote plugin settings unavailable');+ }+ });+ ipcMain.handle(REMOTE_PLUGIN_SETTINGS_CLOSE, (event, id: unknown) => {+ assertTrustedAppRendererEvent(event);+ closeRemotePluginSettings(event.sender, id);+ });+ ipcMain.handle(REMOTE_PLUGIN_SETTINGS_DIRECTORY_ANSWER, async (event, raw: unknown) => {+ assertTrustedAppRendererEvent(event);+ try { await answerRemotePluginSettingsDirectory(event.sender, raw); }+ catch { throwIpcError('PRECONDITION_FAILED', 'Remote plugin directory request unavailable'); }+ });const authorizationHandler = (mode: 'oauth' | 'secret' | 'connection' | 'input') => async (event: import('electron').IpcMainInvokeEvent, raw: unknown) => {assertTrustedAppRendererEvent(event);requireDeviceLinkCapability();@@ -1540,6 +1668,7 @@ export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()):ipcMain.handle(DEVICE_LINK_INVOKE.INVOKE, (e, payload: unknown) => {requireDeviceLinkCapability();const p = (payload ?? {}) as { deviceId?: unknown; channel?: unknown; args?: 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 --git a/apps/desktop/src/main/device-link/remoteSkillConfirmation.ts b/apps/desktop/src/main/device-link/remoteSkillConfirmation.tsnew file mode 100644index 0000000000..8b22c653ef--- /dev/null+++ b/apps/desktop/src/main/device-link/remoteSkillConfirmation.ts@@ -0,0 +1,37 @@+import { REMOTE_RESOURCE_INVOKE_CHANNEL } from '@cindy/device-link';+import { parseRemoteSkillReceipt, type RemoteSkillReceipt } from '../../shared/remoteSkills';++/** Ordinary Renderer remote invokes cannot authorize a native Skill mutation. */+export function isRemoteSkillApproval(channel: unknown, args: unknown): boolean {+ if (channel !== REMOTE_RESOURCE_INVOKE_CHANNEL || !Array.isArray(args)) return false;+ return args.some(+ (request) =>+ request &&+ typeof request === 'object' &&+ request.collectionId === 'skills' &&+ request.actionId === 'management:answer',+ );+}+export async function confirmRemoteSkillMutation(+ deps: {+ invoke(action: string, input: Record<string, unknown>): Promise<unknown>;+ current(): void;+ prompt(facts: NonNullable<RemoteSkillReceipt['confirmation']>): Promise<boolean>;+ },+ operationId: string,+): Promise<RemoteSkillReceipt> {+ deps.current();+ const receipt = parseRemoteSkillReceipt(+ await deps.invoke('operation', { operationId }),+ operationId,+ );+ deps.current();+ if (receipt.phase !== 'confirmation') return receipt;+ const facts = receipt.confirmation!;+ const accepted = await deps.prompt(facts);+ deps.current();+ return parseRemoteSkillReceipt(+ await deps.invoke('answer', { operationId, requestId: facts.requestId, accepted }),+ operationId,+ );+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 11963fb6ba..64a25111ce 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -254,6 +254,7 @@ import {getGhostManager,getGhostPipeDispatcher,getGhostSetupAssessment,+ remotePluginSettings,isGhostAvailableForActiveSession,} from '../cindy-brain/index.js';import {@@ -3150,6 +3151,7 @@ initGhostSetupCoordinator({});initializePluginOauthCards({+ settings: remotePluginSettings,bindConnection: bindGhostSetupConnectionAction,identity: currentOauthIdentityScope,loadKey: loadOauthSigningKey,diff --git a/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.ts b/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.tsindex 3a7fe9375b..e14160b33d 100644--- a/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.ts+++ b/apps/desktop/src/main/plugin-oauth/__tests__/authentication.test.ts@@ -6,16 +6,21 @@ import {OauthHostIdentity,} from '../authentication.js';import { OauthBox } from '../box.js';-import { parsePluginOauthHelloReply, type PluginOauthAction, type PluginOauthPeerIdentity } from '@cindy/device-link';+import {+ parsePluginOauthHelloReply,+ type PluginOauthAction,+ type PluginOauthPeerIdentity,+} from '@cindy/device-link';const action: PluginOauthAction = {requestId: 'card-1',actionId: 'oauth_connect:account',expectedRevision: 1,};-function fixture(ghostId = 'test-plugin') {+function fixture(ghostId = 'test-plugin', controllerDeviceId?: string, settingsPage = false) {let now = Date.now(),- owner: string | null = 'membership:g1';+ owner: string | null = 'membership:g1',+ current = true;const identity = {key: new OauthHostIdentity(),deviceId: 'cloud-device',@@ -31,7 +36,7 @@ function fixture(ghostId = 'test-plugin') {identity: () => identity,owner: () => owner,available: () => true,- bind: async () => ({ ghostId, current: () => true }),+ bind: async () => ({ ghostId, controllerDeviceId, ...(settingsPage ? { settingsPage: true as const } : {}), current: () => current }),request,now: () => now,});@@ -66,25 +71,30 @@ function fixture(ghostId = 'test-plugin') {owner: (v: string | null) => {owner = v;},+ invalidateBinding: () => {+ current = false;+ },};}describe('signed OAuth transport with explicit peer trust', () => {it.each(['test-plugin', '_root__test-plugin', '_ns__' + 'a'.repeat(128) + '__test-plugin'])(- 'authenticates %s before side effects and encrypts subsequent bodies', async (ghostId) => {- const context = fixture(ghostId),- call = await authenticateOauthController(context.options);- expect(context.request).not.toHaveBeenCalled();- await expect(call({ op: 'capabilities' })).resolves.toMatchObject({- marker: 'synthetic-private-result',- });- expect(JSON.stringify(context.invoke.mock.calls)).not.toContain('capabilities');- const frame = context.invoke.mock.calls[1][0];- expect(JSON.stringify(await context.host.request('desktop', frame))).not.toContain(- 'synthetic-private-result',- );- expect(context.request).toHaveBeenCalledTimes(1); // identical retry returns the cached ciphertext, without replaying work- });+ 'authenticates %s before side effects and encrypts subsequent bodies',+ async (ghostId) => {+ const context = fixture(ghostId),+ call = await authenticateOauthController(context.options);+ expect(context.request).not.toHaveBeenCalled();+ await expect(call({ op: 'capabilities' })).resolves.toMatchObject({+ marker: 'synthetic-private-result',+ });+ expect(JSON.stringify(context.invoke.mock.calls)).not.toContain('capabilities');+ const frame = context.invoke.mock.calls[1][0];+ expect(JSON.stringify(await context.host.request('desktop', frame))).not.toContain(+ 'synthetic-private-result',+ );+ expect(context.request).toHaveBeenCalledTimes(1); // identical retry returns the cached ciphertext, without replaying work+ },+ );it('rejects the former raw v1 transport', async () => {const f = fixture();await expect(@@ -93,16 +103,62 @@ describe('signed OAuth transport with explicit peer trust', () => {await expect(f.host.request('desktop', { op: 'capabilities' })).rejects.toThrow();expect(f.request).not.toHaveBeenCalled();});+ it('rejects a settings command inside an authenticated ordinary OAuth exchange', async () => {+ const f = fixture(),+ call = await authenticateOauthController(f.options);+ await expect(+ call({ op: 'settings', id: action.requestId, command: { kind: 'close' } }),+ ).rejects.toThrow();+ expect(f.request).not.toHaveBeenCalled();+ });+ it('binds an authenticated settings exchange to its page and its live lease', async () => {+ const f = fixture('test-plugin', 'desktop', true);+ const settingsAction = { requestId: 'page-1', actionId: 'settings-page', expectedRevision: 0 };+ const call = await authenticateOauthController({ ...f.options, action: settingsAction });+ await expect(call({ op: 'capabilities' })).rejects.toThrow();+ await expect(+ call({ op: 'settings', id: 'other-page', command: { kind: 'close' } }),+ ).rejects.toThrow();+ expect(f.request).not.toHaveBeenCalled();+ await expect(+ call({ op: 'settings', id: settingsAction.requestId, command: { kind: 'poll', after: 0 } }),+ ).resolves.toBeDefined();+ expect(f.request).toHaveBeenCalledTimes(1);+ f.invalidateBinding();+ await expect(+ call({+ op: 'settings',+ id: settingsAction.requestId,+ command: { kind: 'fetch', path: '/kv', method: 'PUT', body: '{}' },+ }),+ ).rejects.toThrow();+ expect(f.request).toHaveBeenCalledTimes(1);+ });it('rejects reuse of an authenticated nonce with a different ciphertext before dispatch', async () => {- const f = fixture(), key = new OauthBox();- const reply = parsePluginOauthHelloReply(await f.host.request('desktop', {- op: 'hello', version: 3, nonce: randomBytes(32).toString('base64url'),- publicKey: key.publicKey, action,- }));- const payload = { nonce: randomBytes(32).toString('base64url'), request: { op: 'capabilities' } };+ const f = fixture(),+ key = new OauthBox();+ const reply = parsePluginOauthHelloReply(+ await f.host.request('desktop', {+ op: 'hello',+ version: 3,+ nonce: randomBytes(32).toString('base64url'),+ publicKey: key.publicKey,+ action,+ }),+ );+ const payload = {+ nonce: randomBytes(32).toString('base64url'),+ request: { op: 'capabilities' },+ };const frame = () => ({- op: 'exchange', id: reply.id,- box: key.seal(reply.publicKey, `authenticated-plugin-oauth-v3:${reply.id}`, 'callback', payload),+ op: 'exchange',+ id: reply.id,+ box: key.seal(+ reply.publicKey,+ `authenticated-plugin-oauth-v3:${reply.id}`,+ 'callback',+ payload,+ ),});const first = frame();const result = await f.host.request('desktop', first);@@ -112,12 +168,15 @@ describe('signed OAuth transport with explicit peer trust', () => {});it('rejects a mutated authenticated envelope without invoking the transaction', async () => {- const f = fixture(), call = await authenticateOauthController(f.options);+ const f = fixture(),+ call = await authenticateOauthController(f.options);await call({ op: 'capabilities' });const frame = f.invoke.mock.calls[1][0] as { op: string; id: string; box: string };const ciphertext = Buffer.from(frame.box, 'base64url');ciphertext[16] ^= 1;- await expect(f.host.request('desktop', { ...frame, box: ciphertext.toString('base64url') })).rejects.toThrow();+ await expect(+ f.host.request('desktop', { ...frame, box: ciphertext.toString('base64url') }),+ ).rejects.toThrow();expect(f.request).toHaveBeenCalledTimes(1);});it('rejects relay substitution of the client ephemeral key, before provider or browser work', async () => {@@ -194,6 +253,12 @@ describe('signed OAuth transport with explicit peer trust', () => {await expect(f.host.request('desktop', frame)).rejects.toThrow();expect(f.request).toHaveBeenCalledTimes(1);});+ it('rejects a page configuration opened by another controller before producing an offer', async () => {+ const f = fixture('test-plugin', 'desktop-other');+ await expect(authenticateOauthController(f.options)).rejects.toThrow();+ expect(f.request).not.toHaveBeenCalled();+ });+it('prevents a connection from starting another card', async () => {const f = fixture(),call = await authenticateOauthController(f.options);diff --git a/apps/desktop/src/main/plugin-oauth/authentication.ts b/apps/desktop/src/main/plugin-oauth/authentication.tsindex c64da20966..1303411c3e 100644--- a/apps/desktop/src/main/plugin-oauth/authentication.ts+++ b/apps/desktop/src/main/plugin-oauth/authentication.ts@@ -167,6 +167,7 @@ export class AuthenticatedOauthHost {const currentIdentity = await this.deps.identity();if (!binding?.current() ||+ (binding.controllerDeviceId !== undefined && binding.controllerDeviceId !== peer) ||this.deps.owner() !== owner ||!this.deps.available(peer) ||generation !== this.generation ||@@ -229,7 +230,15 @@ export class AuthenticatedOauthHost {return prior.promise;}if (c.messages.size >= 1024) throw fail();- if (request.op === 'start') {+ if (c.binding.settingsPage) {+ if (+ request.op !== 'settings' ||+ request.id !== c.hello.action.requestId ||+ !c.binding.current()+ )+ throw fail();+ } else if (request.op === 'settings') throw fail();+ else if (request.op === 'start') {if (c.started || !sameAction(request, c.hello.action) || !c.binding.current()) throw fail();c.started = true;} else if (request.op !== 'capabilities' && (!c.innerId || request.id !== c.innerId))@@ -247,6 +256,7 @@ export class AuthenticatedOauthHost {}if (request.op === 'cancel' ||+ (request.op === 'settings' && request.command.kind === 'close') ||['succeeded', 'failed', 'cancelled', 'expired'].includes(String((result as { phase?: unknown })?.phase),)diff --git a/apps/desktop/src/main/plugin-oauth/cards.ts b/apps/desktop/src/main/plugin-oauth/cards.tsindex b13b34698f..6ecec0bddc 100644--- a/apps/desktop/src/main/plugin-oauth/cards.ts+++ b/apps/desktop/src/main/plugin-oauth/cards.ts@@ -33,6 +33,15 @@ export function initializePluginOauthCards(deps: {actionId: string;onCommitted(): void;}): ((value: PluginConnectionInput) => boolean) | null;+ settings?: {+ bind(action: PluginOauthAction): OauthCardBinding | null;+ bindAuthorization(action: PluginOauthAction): OauthCardBinding | null;+ runAuthorization(action: PluginOauthAction): boolean;+ request(+ peer: string,+ request: import('@cindy/device-link').PluginSettingsRequest,+ ): Promise<unknown>;+ };}): void {const findCardAction = (action: PluginOauthAction) => {const found = deps.bridge@@ -82,7 +91,9 @@ export function initializePluginOauthCards(deps: {if (!step || !remote?.submitInput) return false;const presentation = inputHandoffPresentation(step.snapshot);// A screenshot step travels only inside this sealed offer, to the device that asked for it.- const picture = presentation.picture ? step.service.picture(action.requestId, action.expectedRevision) : null;+ const picture = presentation.picture+ ? step.service.picture(action.requestId, action.expectedRevision)+ : null;if (presentation.picture && !picture) return false;void (async () => {let submission: InputHandoffSubmission | undefined;@@ -94,8 +105,13 @@ export function initializePluginOauthCards(deps: {...(picture ? { picture } : {}),});remote.assertCurrent();- if (submission.expectedRevision !== action.expectedRevision) throw new Error('INPUT_HANDOFF_STALE');- const accepted = await step.service.submit(action.requestId, submission, remote.peer ? { deviceId: remote.peer } : undefined);+ if (submission.expectedRevision !== action.expectedRevision)+ throw new Error('INPUT_HANDOFF_STALE');+ const accepted = await step.service.submit(+ action.requestId,+ submission,+ remote.peer ? { deviceId: remote.peer } : undefined,+ );remote.finish(accepted);} catch {remote.finish(false);@@ -110,11 +126,14 @@ export function initializePluginOauthCards(deps: {owner: deps.owner,available: deps.available,bind: async (action) =>+ deps.settings?.bind(action) ??+ deps.settings?.bindAuthorization(action) ??findCardAction(action)?.binding ??findHandoffStep(action)?.binding ??(await deps.bots()?.bindRemoteOauth(action)) ??null,run: async (action) => {+ if (deps.settings?.bindAuthorization(action)) return deps.settings.runAuthorization(action);if (findHandoffStep(action)) return runHandoffStep(action);const card = findCardAction(action);if (card) {@@ -193,6 +212,9 @@ export function initializePluginOauthCards(deps: {}return (await deps.bots()?.resolveRemoteOauth(action)) ?? false;},+ settingsRequest: (peer, request) =>+ deps.settings?.request(peer, request) ??+ Promise.reject(new Error('PLUGIN_PAGE_UNAVAILABLE')),},deps.identity,deps.loadKey,diff --git a/apps/desktop/src/main/plugin-oauth/runtime.ts b/apps/desktop/src/main/plugin-oauth/runtime.tsindex 6ee313efc9..1ee4b9844f 100644--- a/apps/desktop/src/main/plugin-oauth/runtime.ts+++ b/apps/desktop/src/main/plugin-oauth/runtime.ts@@ -80,7 +80,12 @@ export function initializePluginOauthHost(authenticated = new AuthenticatedOauthHost({...deps,identity: currentIdentity,- request: (peer, raw) => transactions.request(peer, raw),+ request: (peer, raw) => {+ const request = raw as import('@cindy/device-link').PluginOauthRequest;+ return request.op === 'settings' && deps.settingsRequest+ ? deps.settingsRequest(peer, request)+ : transactions.request(peer, raw);+ },});unsubscribe = onOauthCardClosed((id) => host?.cancelRequest(id));}diff --git a/apps/desktop/src/main/plugin-oauth/transactions.ts b/apps/desktop/src/main/plugin-oauth/transactions.tsindex 6518e86f74..f8c8df28c8 100644--- a/apps/desktop/src/main/plugin-oauth/transactions.ts+++ b/apps/desktop/src/main/plugin-oauth/transactions.ts@@ -26,6 +26,9 @@ import { withRemoteOauthContext, type RemoteOauthContext } from './context.js';export interface OauthCardBinding {ghostId: string;+ settingsPage?: true;+ /** Page actions belong to the controller that opened that page. */+ controllerDeviceId?: string;/** Must become false on card cancellation, session close/rewind or replacement. */current(): boolean;}@@ -34,6 +37,10 @@ export interface OauthTransactionDeps {available(peer: string): boolean;bind(action: PluginOauthAction): Promise<OauthCardBinding | null>;run(action: PluginOauthAction): Promise<boolean> | boolean;+ settingsRequest?(+ peer: string,+ request: import('@cindy/device-link').PluginSettingsRequest,+ ): Promise<unknown>;now?: () => number;}type TransactionReply =@@ -43,13 +50,15 @@ type TransactionReply =| PluginConnectionValue| InputHandoffValueReply;type ReplyMode = 'loopback' | 'device' | 'secret' | 'connection' | 'input';-const parseOrNull = <T>(parse: (raw: unknown) => T) => (raw: unknown): T | null => {- try {- return parse(raw);- } catch {- return null;- }-};+const parseOrNull =+ <T>(parse: (raw: unknown) => T) =>+ (raw: unknown): T | null => {+ try {+ return parse(raw);+ } catch {+ return null;+ }+ };interface OfferExchange<T> {offer: { state: string };mode: ReplyMode;@@ -96,7 +105,8 @@ export class OauthTransactions {t.owner === this.deps.owner() &&this.deps.available(t.peer) &&this.now() < t.expiresAt &&- t.binding.current()+ t.binding.current() &&+ (!t.binding.controllerDeviceId || t.binding.controllerDeviceId === t.peer));}private assertCurrent(t: Transaction) {@@ -249,6 +259,7 @@ export class OauthTransactions {async request(peer: string, raw: unknown): Promise<unknown> {const request = parsePluginOauthRequest(raw);if (!request || !this.deps.owner() || !this.deps.available(peer)) throw failure();+ if (request.op === 'settings') throw failure();for (const t of this.entries.values()) {if (!terminal(t.phase) && !this.current(t)) this.finish(t, 'cancelled');if (this.now() >= t.expiresAt) this.entries.delete(t.id);@@ -284,6 +295,7 @@ export class OauthTransactions {if (!binding ||!binding.current() ||+ (binding.controllerDeviceId !== undefined && binding.controllerDeviceId !== peer) ||owner !== this.deps.owner() ||!this.deps.available(peer) ||epoch !== this.epoch ||@@ -339,12 +351,12 @@ export class OauthTransactions {t.mode === 'input'? parseOrNull(parseInputHandoffValueReply)(rawCallback): t.mode === 'connection'- ? parsePluginConnectionValue(rawCallback)- : t.mode === 'secret'- ? parsePluginSecretValue(rawCallback)- : t.mode === 'device'- ? parsePluginDeviceOpened(rawCallback)- : parsePluginOauthCallback(rawCallback);+ ? parsePluginConnectionValue(rawCallback)+ : t.mode === 'secret'+ ? parsePluginSecretValue(rawCallback)+ : t.mode === 'device'+ ? parsePluginDeviceOpened(rawCallback)+ : parsePluginOauthCallback(rawCallback);if (!callback || callback.state !== t.state) throw failure();if ('kind' in callback &&diff --git a/apps/desktop/src/main/sidebarSettingsStore.ts b/apps/desktop/src/main/sidebarSettingsStore.tsindex 96cd3b0511..08cfcb1214 100644--- a/apps/desktop/src/main/sidebarSettingsStore.ts+++ b/apps/desktop/src/main/sidebarSettingsStore.ts@@ -566,7 +566,8 @@ async function setProjectHidden(rawRequest: unknown): Promise<boolean> {}/** Persist one plugin main-view visibility override in Main's owner-scoped store. */-async function setMainViewHidden(rawRequest: unknown): Promise<string[]> {+async function setMainViewHidden(rawRequest: unknown, assertCurrent?: () => void): Promise<string[]> {+ assertCurrent?.();const request = requireWriteRequest(rawRequest);const ghostId = requireGhostId(request.ghostId);if (typeof request.hidden !== 'boolean') {@@ -586,6 +587,7 @@ async function setMainViewHidden(rawRequest: unknown): Promise<string[]> {try {nextSettings = await enqueueWrite(scopeKey, () =>store.updateAtomic((current) => {+ assertCurrent?.();requireSidebarStoreAccess({ rejectSnapshotChange: true });const currentIds = current.value.hiddenMainViewGhostIds;const alreadyHidden = currentIds.includes(ghostId);@@ -616,6 +618,11 @@ async function setMainViewHidden(rawRequest: unknown): Promise<string[]> {return Array.from(nextSettings.hiddenMainViewGhostIds);}+export async function setLocalMainViewHidden(ghostId: string, hidden: boolean, assertCurrent: () => void): Promise<void> {+ const { dataOwnerId, ownerGeneration } = loadSidebarSettingsSnapshot();+ await setMainViewHidden({ dataOwnerId, ownerGeneration, ghostId, hidden }, assertCurrent);+}+type SidebarPathState = 'missing' | 'regular-file' | 'blocked';function sidebarPathState(file: string): SidebarPathState {diff --git a/apps/desktop/src/main/skillhub/__tests__/installService.test.ts b/apps/desktop/src/main/skillhub/__tests__/installService.test.tsindex 24978c8e2d..863dfb2254 100644--- a/apps/desktop/src/main/skillhub/__tests__/installService.test.ts+++ b/apps/desktop/src/main/skillhub/__tests__/installService.test.ts@@ -188,6 +188,32 @@ describe('skillhub/installService', () => {expect(isCindySkillEnabled(source)).toBe(true);});+ it('keeps files intact when a remote approval expires after the uninstall leases are acquired', async () => {+ const { source, target } = await localFixture('remote-remove');+ const { uninstall } = await import('../installService');+ const { shell } = await import('electron');+ const beforeCommit = vi.fn(() => false);+ expect((await uninstall(source, target, () => true, beforeCommit)).success).toBe(false);+ expect(beforeCommit).toHaveBeenCalledOnce();+ expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe('fixture content');+ expect(shell.trashItem).not.toHaveBeenCalled();+ });++ it('checks the remote instance after extraction and preserves the old version when confirmation is stale', async () => {+ const { source } = await localFixture('remote-update');+ await setupInstallDownload('remote-update', await makeZip({ 'SKILL.md': 'new content' }));+ const { getCurrentDataOwnerId } = await import('../../authManager');+ vi.mocked(getCurrentDataOwnerId).mockReturnValue('owner');+ const { install } = await import('../installService');+ const { registryService } = await import('../registry');+ const beforeCommit = vi.fn(async () => false);+ const result = await install({ name: 'remote-update', installPath: source, version: '2.0.0', force: true }, () => {}, { current: () => true, beforeCommit });+ expect(result).toMatchObject({ success: false, errorCode: 'CANCELLED' });+ expect(beforeCommit).toHaveBeenCalledOnce();+ expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe('fixture content');+ expect(registryService.addInstall).not.toHaveBeenCalled();+ });+it('serializes an in-flight scanner repair before uninstall snapshots and removes its completed link', async () => {const { source, target } = await localFixture('scanner-race');const { registryService } = await import('../registry');diff --git a/apps/desktop/src/main/skillhub/__tests__/remoteCatalog.test.ts b/apps/desktop/src/main/skillhub/__tests__/remoteCatalog.test.tsnew file mode 100644index 0000000000..5a3096ef56--- /dev/null+++ b/apps/desktop/src/main/skillhub/__tests__/remoteCatalog.test.ts@@ -0,0 +1,97 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { readRemoteSkillCatalog } from '../remoteCatalog';+import type { SkillhubMarketService } from '../marketService';++const service = {+ listMarket: vi.fn(),+ listCategories: vi.fn(),+ info: vi.fn(),+ getPublishedFiles: vi.fn(),+ readPublishedFile: vi.fn(),+ getScanStatus: vi.fn(),+};+const read = (input: Record<string, unknown>) =>+ readRemoteSkillCatalog(service as unknown as SkillhubMarketService, input);+beforeEach(() => vi.resetAllMocks());++describe('selected computer uses its full Skill Hub service', () => {+ it('preserves complete metadata and pagination, forwarding public/team filters', async () => {+ const response = {+ success: true,+ items: [+ { name: 'example', authorName: 'Author', downloads: 321, tags: [{ slug: 'research' }] },+ ],+ nextCursor: '3',+ };+ service.listMarket.mockResolvedValue(response);+ await expect(+ read({+ method: 'list',+ scope: 'team',+ q: 'research',+ category: 'knowledge',+ sort: 'downloads',+ cursor: '2',+ limit: 1000,+ }),+ ).resolves.toBe(response);+ expect(service.listMarket).toHaveBeenCalledWith({+ scope: 'team',+ q: 'research',+ category: 'knowledge',+ sort: 'downloads',+ cursor: '2',+ limit: 24,+ mine: false,+ available: false,+ });+ await read({ method: 'list', scope: 'market', mine: true });+ expect(service.listMarket).toHaveBeenLastCalledWith(+ expect.objectContaining({ scope: 'market', mine: true }),+ );+ });+ it('reads categories, full details, the published file tree and content from the same scope', async () => {+ await read({ method: 'categories', scope: 'team' });+ expect(service.listCategories).toHaveBeenCalledWith('team', false);+ await read({ method: 'info', scope: 'market', name: 'example' });+ expect(service.info).toHaveBeenCalledWith('example', 'market');+ await read({ method: 'files', scope: 'team', name: 'example', version: '1.2.3' });+ expect(service.getPublishedFiles).toHaveBeenCalledWith({+ name: 'example',+ version: '1.2.3',+ catalogScope: 'team',+ });+ await read({+ method: 'file',+ scope: 'team',+ name: 'example',+ version: '1.2.3',+ path: 'references/guide.md',+ });+ expect(service.readPublishedFile).toHaveBeenCalledWith({+ name: 'example',+ version: '1.2.3',+ catalogScope: 'team',+ path: 'references/guide.md',+ });+ await read({ method: 'scan-status', scope: 'market', name: 'example', version: '1.2.3' });+ expect(service.getScanStatus).toHaveBeenCalledWith({+ slug: 'example',+ version: '1.2.3',+ catalogScope: 'market',+ });+ });+ it.each([+ { method: 'delete', scope: 'market', name: 'example' },+ { method: 'list', scope: 'private' },+ { method: 'list', scope: 'market', cursor: '../2' },+ { method: 'list', scope: 'market', sort: 'arbitrary' },+ { method: 'info', scope: 'market', name: '../example' },+ ...['../SKILL.md', '/etc/passwd', 'references/../SKILL.md', 'C:\\private', './SKILL.md'].map(+ (path) => ({ method: 'file', scope: 'market', name: 'example', path }),+ ),+ ])('rejects unsupported operations and caller paths: %j', async (input) => {+ await expect(read(input)).rejects.toMatchObject({ code: 'INVALID_PARAMS' });+ expect(Object.values(service).every((method) => method.mock.calls.length === 0)).toBe(true);+ });+});diff --git a/apps/desktop/src/main/skillhub/__tests__/remoteManagement.test.ts b/apps/desktop/src/main/skillhub/__tests__/remoteManagement.test.tsnew file mode 100644index 0000000000..03be552ce3--- /dev/null+++ b/apps/desktop/src/main/skillhub/__tests__/remoteManagement.test.ts@@ -0,0 +1,315 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { RemoteSkillsManagement, type RemoteSkillRecord } from '../remoteManagement';+import type { RemoteActionInvokeRequest } from '@cindy/device-link';+import type { RemoteSkillReceipt } from '../../../shared/remoteSkills';++const entry = (id = 'global-instance', revision = 'r1'): RemoteSkillRecord<string> => ({+ target: id,+ view: {+ id,+ revision,+ name: 'same-name',+ description: 'fixture',+ kind: 'skill',+ scope: 'global',+ engines: ['Codex'],+ enabled: true,+ managedByPlugin: false,+ builtIn: false,+ canUninstall: true,+ version: '1.0.0',+ market: { name: 'same-name', catalogScope: 'market' },+ },+});+let records: ReturnType<typeof entry>[], live: boolean, visible: boolean;+const mutate = vi.fn(),+ scan = vi.fn(async () => records);+let management: RemoteSkillsManagement<string>;+const catalog = vi.fn(),+ readFile = vi.fn(),+ projects = vi.fn(),+ market = vi.fn();+beforeEach(() => {+ vi.clearAllMocks();+ records = [entry(), entry('project-instance')];+ live = visible = true;+ management = new RemoteSkillsManagement({+ capture: () => ({ current: () => live, visible: () => visible }),+ scan,+ market: market.mockResolvedValue({ items: [], nextCursor: null }),+ catalog,+ readFile,+ projects: projects.mockResolvedValue([+ { id: 'target-project', revision: 'p1', name: 'Project B' },+ ]),+ latest: async (name, catalogScope) => ({+ name,+ catalogScope,+ displayName: name,+ description: '',+ version: '2.0.0',+ }),+ detail: async () => '# fixture',+ mutate,+ });+});+const invoke = async (+ action: string,+ input: Record<string, unknown> = {},+ id?: string,+ peer = 'control-a',+) =>+ (+ await management.provider().invoke!({ controllerDeviceId: peer }, {+ collectionId: 'skills',+ client: { protocolVersion: 1, primitives: [] },+ actionId: `management:${action}`,+ input,+ ...(id ? { resourceRef: { collectionId: 'skills', kind: 'skill', id } } : {}),+ } satisfies RemoteActionInvokeRequest)+ ).result as RemoteSkillReceipt;++describe('remote Skills reuse the Host instances and mutation services', () => {+ it('advertises the complete catalog and keeps installed scans independent of market availability', async () => {+ expect(management.provider().collection.actions).toEqual(+ expect.arrayContaining([{ id: 'management:catalog', label: 'Browse skill catalog' }]),+ );+ await expect(invoke('snapshot', { installedOnly: true })).resolves.toMatchObject({+ projects: [{ id: 'target-project', revision: 'p1' }],+ items: expect.any(Array),+ });+ expect(market).not.toHaveBeenCalled();+ await invoke('snapshot');+ expect(market).toHaveBeenCalledOnce();+ });+ it('fences catalog responses when the owning account/peer changes during a read', async () => {+ catalog.mockImplementation(async () => {+ live = false;+ return { success: true, items: [] };+ });+ await expect(invoke('catalog', { method: 'list', scope: 'team' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ expect(catalog).toHaveBeenCalledWith({ method: 'list', scope: 'team' });+ catalog.mockClear();+ await expect(invoke('catalog')).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(catalog).not.toHaveBeenCalled();+ });+ it('binds file browsing to the selected physical revision and rejects traversal before reading', async () => {+ readFile.mockResolvedValue({ success: true, content: '# Guide' });+ await expect(+ invoke(+ 'read-file',+ { path: 'references/guide.md', expectedRevision: 'r1' },+ 'project-instance',+ ),+ ).resolves.toMatchObject({ content: '# Guide' });+ expect(readFile).toHaveBeenCalledWith(records[1], 'references/guide.md', false);+ readFile.mockClear();+ for (const path of ['../guide.md', '/private/file', 'folder/../guide.md', 'C:\\private']) {+ await expect(+ invoke('read-file', { path, expectedRevision: 'r1' }, 'project-instance'),+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });+ }+ await expect(+ invoke('children', { path: '', expectedRevision: 'old' }, 'project-instance'),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(readFile).not.toHaveBeenCalled();+ });+ it('installs only into the Host project selected before confirmation, and rechecks its identity', async () => {+ const receipt = await invoke('begin', {+ operationId: 'project-install',+ kind: 'install',+ name: 'same-name',+ catalogScope: 'team',+ version: '2.0.0',+ projectId: 'target-project',+ projectRevision: 'p1',+ });+ await invoke('answer', {+ operationId: receipt.operationId,+ requestId: receipt.confirmation!.requestId,+ accepted: true,+ });+ await vi.waitFor(() => expect(mutate).toHaveBeenCalledOnce());+ expect(mutate.mock.calls[0][4]).toEqual({+ id: 'target-project',+ revision: 'p1',+ name: 'Project B',+ });+ mutate.mockClear();+ const pending = await invoke('begin', {+ operationId: 'changed-project',+ kind: 'install',+ name: 'same-name',+ catalogScope: 'team',+ version: '2.0.0',+ projectId: 'target-project',+ projectRevision: 'p1',+ });+ projects.mockResolvedValue([{ id: 'target-project', revision: 'p2', name: 'Project B' }]);+ await invoke('answer', {+ operationId: pending.operationId,+ requestId: pending.confirmation!.requestId,+ accepted: true,+ });+ await vi.waitFor(async () =>+ expect((await invoke('operation', { operationId: pending.operationId })).phase).toBe(+ 'failed',+ ),+ );+ expect(mutate).not.toHaveBeenCalled();+ await expect(+ invoke('begin', {+ operationId: 'unknown-project',+ kind: 'install',+ name: 'same-name',+ catalogScope: 'team',+ version: '2.0.0',+ projectId: '/controller/project',+ projectRevision: 'p2',+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });+ it('lists same-name instances independently and reads only the named revision', async () => {+ const snapshot = (await invoke('snapshot')) as unknown as { items: Array<{ id: string }> };+ expect(snapshot.items.map((i) => i.id)).toEqual(['global-instance', 'project-instance']);+ await expect(+ invoke('detail', { expectedRevision: 'old' }, 'global-instance'),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ await expect(+ invoke('detail', { expectedRevision: 'r1' }, 'project-instance'),+ ).resolves.toMatchObject({ markdown: '# fixture', id: 'project-instance' });+ });+ it('changes only the selected physical target and preserves a queryable success receipt', async () => {+ await invoke(+ 'begin',+ { operationId: 'toggle', kind: 'disable', expectedRevision: 'r1' },+ 'project-instance',+ );+ await vi.waitFor(() => expect(mutate).toHaveBeenCalledOnce());+ expect(mutate.mock.calls[0][1].target).toBe('project-instance');+ expect((await invoke('operation', { operationId: 'toggle' })).phase).toBe('succeeded');+ });+ it('waits outside the installer for confirmation and binds it to the requesting controller', async () => {+ const receipt = await invoke(+ 'begin',+ { operationId: 'remove', kind: 'uninstall', expectedRevision: 'r1' },+ 'global-instance',+ );+ expect(receipt.phase).toBe('confirmation');+ expect(mutate).not.toHaveBeenCalled();+ await expect(+ invoke(+ 'answer',+ { operationId: 'remove', requestId: receipt.confirmation!.requestId, accepted: true },+ undefined,+ 'control-b',+ ),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ await invoke('answer', {+ operationId: 'remove',+ requestId: receipt.confirmation!.requestId,+ accepted: true,+ });+ await vi.waitFor(() => expect(mutate).toHaveBeenCalledOnce());+ });+ it('rejects a replaced instance after confirmation and never calls uninstall', async () => {+ const receipt = await invoke(+ 'begin',+ { operationId: 'replace', kind: 'uninstall', expectedRevision: 'r1' },+ 'global-instance',+ );+ records = [entry('global-instance', 'r2')];+ await invoke('answer', {+ operationId: 'replace',+ requestId: receipt.confirmation!.requestId,+ accepted: true,+ });+ await vi.waitFor(async () =>+ expect((await invoke('operation', { operationId: 'replace' })).phase).toBe('failed'),+ );+ expect(mutate).not.toHaveBeenCalled();+ });+ it('queries committed results after disconnect but refuses approval from the stale peer epoch', async () => {+ const receipt = await invoke(+ 'begin',+ { operationId: 'offline', kind: 'uninstall', expectedRevision: 'r1' },+ 'global-instance',+ );+ live = false;+ await expect(+ invoke('answer', {+ operationId: 'offline',+ requestId: receipt.confirmation!.requestId,+ accepted: true,+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect((await invoke('operation', { operationId: 'offline' })).phase).toBe('confirmation');+ visible = false;+ await expect(invoke('operation', { operationId: 'offline' })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ });+ it('does not replay a completed uninstall when the instance has gone', async () => {+ const input = { operationId: 'dedupe', kind: 'uninstall', expectedRevision: 'r1' };+ const receipt = await invoke('begin', input, 'global-instance');+ await invoke('answer', {+ operationId: 'dedupe',+ requestId: receipt.confirmation!.requestId,+ accepted: true,+ });+ await vi.waitFor(() => expect(mutate).toHaveBeenCalledOnce());+ records = [];+ expect((await invoke('begin', input, 'global-instance')).phase).toBe('succeeded');+ expect(mutate).toHaveBeenCalledOnce();+ });+ it('cancels confirmation without changing the original skill', async () => {+ const receipt = await invoke(+ 'begin',+ { operationId: 'cancel', kind: 'update', expectedRevision: 'r1', version: '2.0.0' },+ 'global-instance',+ );+ await invoke('answer', {+ operationId: 'cancel',+ requestId: receipt.confirmation!.requestId,+ accepted: false,+ });+ expect((await invoke('operation', { operationId: 'cancel' })).phase).toBe('cancelled');+ expect(mutate).not.toHaveBeenCalled();+ });+ it('allocates one receipt for overlapping requests with the same operation id', async () => {+ const input = { operationId: 'overlap', kind: 'uninstall', expectedRevision: 'r1' };+ const [first, second] = await Promise.all([+ invoke('begin', input, 'global-instance'),+ invoke('begin', input, 'global-instance'),+ ]);+ expect(first.confirmation!.requestId).toBe(second.confirmation!.requestId);+ await invoke('answer', {+ operationId: 'overlap',+ requestId: first.confirmation!.requestId,+ accepted: true,+ });+ await vi.waitFor(() => expect(mutate).toHaveBeenCalledOnce());+ });+ it('refuses independent mutation of plugin-managed Skills and unknown release versions', async () => {+ records[0].view.managedByPlugin = true;+ await expect(+ invoke(+ 'begin',+ { operationId: 'plugin', kind: 'disable', expectedRevision: 'r1' },+ 'global-instance',+ ),+ ).rejects.toMatchObject({ code: 'INVALID_PARAMS' });+ await expect(+ invoke('begin', {+ operationId: 'install',+ kind: 'install',+ name: 'new-skill',+ catalogScope: 'team',+ version: 'old',+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mutate).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts b/apps/desktop/src/main/skillhub/__tests__/scanner.test.tsindex 04e495d2ff..9adc856e3e 100644--- a/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts+++ b/apps/desktop/src/main/skillhub/__tests__/scanner.test.ts@@ -116,6 +116,7 @@ describe('scanAllSkills', () => {expect(result.skills).toHaveLength(2);expect(result.skills.find((skill) => skill.builtIn)).toMatchObject({name: 'cindy-skill-creator',+ scope: 'global',description: 'Cindy copy',builtIn: true,canUninstall: false,@@ -124,6 +125,7 @@ describe('scanAllSkills', () => {});expect(result.skills.find((skill) => !skill.builtIn)).toMatchObject({description: 'User copy',+ scope: 'global',canUninstall: true,});});diff --git a/apps/desktop/src/main/skillhub/installService.ts b/apps/desktop/src/main/skillhub/installService.tsindex 5ab8e71a1f..3bf19ab80c 100644--- a/apps/desktop/src/main/skillhub/installService.ts+++ b/apps/desktop/src/main/skillhub/installService.ts@@ -515,7 +515,7 @@ function safeJoin(dest: string, relPath: string): string | null {// ── 主入口:install ─────────────────────────────────────────────────────────-export async function install(p: InstallParams, onProgress: ProgressCb): Promise<InstallResult> {+export async function install(p: InstallParams, onProgress: ProgressCb, remoteGuard?: { current(): boolean; beforeCommit(): Promise<boolean> }): Promise<InstallResult> {const userId = getCurrentUserId();if (!userId) {onProgress({ phase: 'failed', name: p.name, errorCode: 'AUTH_REQUIRED', message: '未登录' });@@ -560,6 +560,7 @@ export async function install(p: InstallParams, onProgress: ProgressCb): Promiseconst checkAbort = (): boolean => {if (signal.aborted ||+ (remoteGuard !== undefined && !remoteGuard.current()) ||!getAppCapabilities().canUseSkillHubCloud ||getCurrentDataOwnerId() !== installOwnerId) {@@ -719,6 +720,12 @@ export async function install(p: InstallParams, onProgress: ProgressCb): Promisereturn { success: false, errorCode: 'CANCELLED', message: '已取消' };}+ // A remote approval is tied to the scanned physical instance/content. Recheck+ // after download/extraction while the original mutation leases are held.+ if (remoteGuard && !(await remoteGuard.beforeCommit())) {+ await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});+ return { success: false, errorCode: 'CANCELLED', message: '已取消' };+ }// 6) final switch: staging → final。只有此时才移动/删除旧目录。// 物理 Skill 自身可能还是一层用户链接;替换后再 realpath 已看不到旧 registry key。const preSwitchPhysicalRealDir = !pathTextEquals(@@ -990,6 +997,7 @@ export async function uninstall(absolutePath: string,target?: LocalSkillTarget,canMutate: () => boolean = () => true,+ beforeCommit?: () => boolean | Promise<boolean>,): Promise<UninstallResult> {// 防御:resolve 后验证路径是精确的 skill 根目录(只允许一层 slug,防 traversal)let resolved: string;@@ -1062,6 +1070,9 @@ export async function uninstall(};}+ if (beforeCommit && !(await beforeCommit())) {+ return { success: false, errorCode: 'INTERNAL', message: 'Skill source changed; refresh and retry' };+ }const cloudUserId = getCurrentUserId();return await uninstallLocked(absolutePath,diff --git a/apps/desktop/src/main/skillhub/registerIpc.ts b/apps/desktop/src/main/skillhub/registerIpc.tsindex cdd41898f9..dc26ad77af 100644--- a/apps/desktop/src/main/skillhub/registerIpc.ts+++ b/apps/desktop/src/main/skillhub/registerIpc.ts@@ -1,4 +1,8 @@import { inspectSkillListGrants } from './customizationScanHost';+import { createRemoteSkillsHost } from './remoteManagementHost';+import { remoteResourceRegistry } from '../device-link/remoteResourceRegistry';+import { REMOTE_RESOURCE_CHANGED_CHANNEL } from '@cindy/device-link';+import { tapWindowBroadcast, getSafeDataOwnerPushStamp } from '../device-link/broadcast-tap';import fs from 'node:fs';import { t } from '../i18n.js';import { throwIpcError } from '../utils/ipcValidate';@@ -105,6 +109,7 @@ function assertReviewOwnerCurrent(ownerScope: string): void {}export interface RegisterSkillhubIpcOptions {+ remoteIsRelayOnline?: () => boolean;getMaker: () => Maker;getManagedSkillRoots: () => readonly string[];getBuiltInSkills?: () => readonly BuiltInSkillDescriptor[];@@ -171,6 +176,7 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {return JSON.stringify([fs.realpathSync.native(source), st.dev, st.ino]);};const broadcastLocalChange = () => {+ if (options.remoteIsRelayOnline && !isAppSessionBoundaryPending()) tapWindowBroadcast(REMOTE_RESOURCE_CHANGED_CHANNEL, { collectionId: 'skills' }, getSafeDataOwnerPushStamp());for (const win of BrowserWindow.getAllWindows()) {if (!win.isDestroyed()) {try { win.webContents.send('skillhub:local-state-changed'); } catch { /* Window closed. */ }@@ -378,6 +384,9 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {const publishService = options.publishService ?? new SkillPublishService({onProgress: broadcastPublishProgress,});+ if (options.remoteIsRelayOnline) {+ remoteResourceRegistry.register(createRemoteSkillsHost(options, marketService, broadcastLocalChange, refreshCodexProjectSkillCache).provider());+ }configureSkillhubAgentServices({market: marketService,publisher: publishService,diff --git a/apps/desktop/src/main/skillhub/remoteCatalog.ts b/apps/desktop/src/main/skillhub/remoteCatalog.tsnew file mode 100644index 0000000000..f86b408124--- /dev/null+++ b/apps/desktop/src/main/skillhub/remoteCatalog.ts@@ -0,0 +1,62 @@+import type { SkillhubMarketService, ListMarketParams } from './marketService';+import { RemoteResourceRegistryError } from '../device-link/remoteResourceRegistry';++const invalid = (): never => {+ throw new RemoteResourceRegistryError('INVALID_PARAMS', 'Invalid skill catalog request');+};+function text(value: unknown, max: number, optional = false): string | undefined {+ if (value === undefined && optional) return undefined;+ return typeof value === 'string' && value.length > 0 && value.length <= max ? value : invalid();+}++/** Fixed read operations reuse the same Hub service as the local Skill pages. */+export async function readRemoteSkillCatalog(+ service: SkillhubMarketService,+ input: Record<string, unknown>,+) {+ const scope = input.scope;+ if (scope !== 'market' && scope !== 'team' && !(input.method === 'list' && scope === 'all'))+ invalid();+ if (input.method === 'list') {+ const sort = input.sort;+ if (+ sort !== undefined &&+ !['trending', 'downloads', 'updated_at', 'created_at'].includes(String(sort))+ )+ invalid();+ if (input.mine !== undefined && typeof input.mine !== 'boolean') invalid();+ const cursor = text(input.cursor, 32, true);+ if (cursor !== undefined && !/^[1-9]\d{0,8}$/.test(cursor)) invalid();+ return service.listMarket({+ scope: scope as ListMarketParams['scope'],+ sort: sort as ListMarketParams['sort'],+ q: text(input.q, 256, true),+ category: text(input.category, 128, true),+ cursor,+ limit: 24,+ mine: input.mine === true,+ available: false,+ });+ }+ if (input.method === 'categories')+ return service.listCategories(scope as 'market' | 'team', false);+ const name = text(input.name, 128)!;+ if (!/^[a-z0-9][a-z0-9-]{0,127}$/.test(name)) invalid();+ const catalogScope = scope as 'market' | 'team';+ if (input.method === 'info') return service.info(name, catalogScope);+ const version = text(input.version, 128, true);+ if (input.method === 'files') return service.getPublishedFiles({ name, version, catalogScope });+ if (input.method === 'file') {+ const filePath = text(input.path, 1024)!;+ if (+ filePath.includes('\\') ||+ filePath.startsWith('/') ||+ filePath.split('/').some((part) => part === '..' || part === '.')+ )+ invalid();+ return service.readPublishedFile({ name, version, path: filePath, catalogScope });+ }+ if (input.method === 'scan-status')+ return service.getScanStatus({ slug: name, version, catalogScope });+ invalid();+}diff --git a/apps/desktop/src/main/skillhub/remoteManagement.ts b/apps/desktop/src/main/skillhub/remoteManagement.tsnew file mode 100644index 0000000000..4bb3331301--- /dev/null+++ b/apps/desktop/src/main/skillhub/remoteManagement.ts@@ -0,0 +1,349 @@+import { randomUUID, createHash } from 'node:crypto';+import type { RemoteActionInvokeRequest } from '@cindy/device-link';+import type { RemoteResourceProvider } from '../device-link/remoteResourceRegistry';+import { RemoteResourceRegistryError } from '../device-link/remoteResourceRegistry';+import type {+ RemoteSkillItem,+ RemoteSkillMarketItem,+ RemoteSkillMutation,+ RemoteSkillReceipt,+ RemoteSkillProject,+} from '../../shared/remoteSkills';++export interface RemoteSkillRecord<T> {+ view: RemoteSkillItem;+ target: T;+ linkOnly?: boolean;+}+export interface RemoteSkillsDeps<T> {+ capture(peer: string): { current(): boolean; visible(): boolean };+ scan(): Promise<RemoteSkillRecord<T>[]>;+ market(+ query: string,+ cursor?: string,+ ): Promise<{ items: RemoteSkillMarketItem[]; nextCursor: string | null }>;+ latest(name: string, catalogScope: 'market' | 'team'): Promise<RemoteSkillMarketItem | null>;+ detail(record: RemoteSkillRecord<T>): Promise<string>;+ catalog?(input: Record<string, unknown>): Promise<unknown>;+ projects?(): Promise<RemoteSkillProject[]>;+ readFile?(+ record: RemoteSkillRecord<T>,+ relativePath: string,+ children: boolean,+ ): Promise<unknown>;+ mutate(+ kind: RemoteSkillMutation,+ record: RemoteSkillRecord<T> | undefined,+ market: RemoteSkillMarketItem | undefined,+ current: () => boolean,+ project?: RemoteSkillProject,+ ): Promise<void>;+}+type Operation = {+ peer: string;+ fingerprint: string;+ receipt: RemoteSkillReceipt;+ current(): boolean;+ visible(): boolean;+ run(): Promise<void>;+ timer: ReturnType<typeof setTimeout>;+};+function fail(+ code: 'INVALID_PARAMS' | 'NOT_FOUND' | 'UNSUPPORTED_CAPABILITY' = 'INVALID_PARAMS',+): never {+ throw new RemoteResourceRegistryError(code, 'Skill management request is unavailable');+}+const str = (v: unknown, max = 256): string =>+ typeof v === 'string' && v.length > 0 && v.length <= max ? v : fail();++/** Host-owned identities and per-controller receipts; no local renderer path authority. */+export class RemoteSkillsManagement<T> {+ private operations = new Map<string, Operation>();+ constructor(private readonly deps: RemoteSkillsDeps<T>) {}+ private access(peer: string) {+ const access = this.deps.capture(peer);+ if (!access.current()) fail('NOT_FOUND');+ return access;+ }+ private operation(peer: string, id: unknown) {+ const operation = this.operations.get(str(id));+ if (!operation || operation.peer !== peer || !operation.visible()) fail('NOT_FOUND');+ return operation;+ }+ private async invoke(peer: string, request: RemoteActionInvokeRequest): Promise<unknown> {+ const input = request.input ?? {};+ if (request.actionId === 'management:operation')+ return this.operation(peer, input.operationId).receipt;+ if (request.actionId === 'management:cancel' || request.actionId === 'management:answer') {+ const operation = this.operation(peer, input.operationId);+ if (request.actionId === 'management:cancel') {+ if (operation.receipt.phase === 'confirmation')+ operation.receipt = { operationId: operation.receipt.operationId, phase: 'cancelled' };+ } else if (operation.receipt.phase === 'confirmation') {+ if (+ !operation.current() ||+ input.requestId !== operation.receipt.confirmation?.requestId ||+ typeof input.accepted !== 'boolean'+ )+ fail('NOT_FOUND');+ if (input.accepted) {+ operation.receipt = { operationId: operation.receipt.operationId, phase: 'running' };+ void operation.run();+ } else+ operation.receipt = { operationId: operation.receipt.operationId, phase: 'cancelled' };+ }+ return operation.receipt;+ }+ const access = this.access(peer);+ if (request.actionId === 'management:catalog') {+ if (!this.deps.catalog) fail('UNSUPPORTED_CAPABILITY');+ const result = await this.deps.catalog(input);+ if (!access.current()) fail('NOT_FOUND');+ return result;+ }+ if (request.actionId === 'management:snapshot') {+ const records = await this.deps.scan();+ const projects = await this.deps.projects?.();+ let market: { items: RemoteSkillMarketItem[]; nextCursor: string | null } = {+ items: [],+ nextCursor: null,+ },+ marketUnavailable = false;+ try {+ // New controllers use the paginated catalog API independently of scans.+ if (input.installedOnly !== true) {+ market = await this.deps.market(+ typeof input.query === 'string' ? input.query.slice(0, 256) : '',+ typeof input.cursor === 'string' ? input.cursor.slice(0, 32) : undefined,+ );+ }+ } catch {+ marketUnavailable = true;+ }+ if (!access.current()) fail('NOT_FOUND');+ return {+ version: 1,+ items: records.map((r) => r.view),+ market: market.items,+ nextCursor: market.nextCursor,+ marketUnavailable,+ ...(projects ? { projects } : {}),+ };+ }+ if (+ ![+ 'management:detail',+ 'management:begin',+ 'management:children',+ 'management:read-file',+ ].includes(request.actionId)+ )+ fail('UNSUPPORTED_CAPABILITY');+ const operationId = request.actionId === 'management:begin' ? str(input.operationId, 64) : '';+ const fingerprint = JSON.stringify([+ request.resourceRef?.id,+ input.expectedRevision,+ input.kind,+ input.name,+ input.catalogScope,+ input.version,+ input.projectId,+ input.projectRevision,+ ]);+ if (operationId && this.operations.has(operationId)) {+ const operation = this.operation(peer, operationId);+ if (operation.fingerprint !== fingerprint) fail();+ return operation.receipt;+ }+ let record: RemoteSkillRecord<T> | undefined;+ if (request.resourceRef) {+ record = (await this.deps.scan()).find((r) => r.view.id === request.resourceRef?.id);+ if (!record || record.view.revision !== input.expectedRevision) fail('NOT_FOUND');+ }+ if (!access.current()) fail('NOT_FOUND');+ if (request.actionId === 'management:children' || request.actionId === 'management:read-file') {+ if (!record || !this.deps.readFile) fail('UNSUPPORTED_CAPABILITY');+ const relativePath = input.path === '' ? '' : str(input.path, 1024);+ if (+ relativePath.startsWith('/') ||+ relativePath.includes('\\') ||+ relativePath.split('/').some((part) => part === '..' || part === '.')+ )+ fail();+ const result = await this.deps.readFile(+ record,+ relativePath,+ request.actionId === 'management:children',+ );+ if (!access.current()) fail('NOT_FOUND');+ return result;+ }+ if (request.actionId === 'management:detail') {+ if (!record) fail();+ const markdown = await this.deps.detail(record);+ let latest: RemoteSkillMarketItem | null = null;+ if (record.view.market && !record.view.builtIn && !record.view.managedByPlugin) {+ try {+ latest = await this.deps.latest(+ record.view.market.name,+ record.view.market.catalogScope ?? 'market',+ );+ } catch {+ /* Keep installed content readable when the market is unavailable. */+ }+ }+ if (!access.current()) fail('NOT_FOUND');+ return { id: record.view.id, revision: record.view.revision, markdown, latest };+ }+ const kind = str(input.kind) as RemoteSkillMutation;+ if (!['enable', 'disable', 'install', 'update', 'uninstall'].includes(kind)) fail();+ if (kind !== 'install' && !record) fail();+ let project: RemoteSkillProject | undefined;+ if (input.projectId !== undefined) {+ if (kind !== 'install' || !this.deps.projects) fail();+ project = (await this.deps.projects()).find(+ (entry) => entry.id === input.projectId && entry.revision === input.projectRevision,+ );+ if (!project || !access.current()) fail('NOT_FOUND');+ }+ if (+ record?.view.managedByPlugin ||+ (kind === 'uninstall' && !record?.view.canUninstall) ||+ (kind === 'update' && (record?.view.builtIn || !record?.view.market))+ )+ fail();+ let market: RemoteSkillMarketItem | undefined;+ if (kind === 'install' || kind === 'update') {+ if (kind === 'install' && record) fail();+ const name = kind === 'update' ? record!.view.market!.name : str(input.name, 128);+ const scope =+ kind === 'update' ? (record!.view.market!.catalogScope ?? 'market') : input.catalogScope;+ if (scope !== 'market' && scope !== 'team') fail();+ market = (await this.deps.latest(name, scope)) ?? undefined;+ if (!market || market.version !== input.version || !access.current()) fail('NOT_FOUND');+ }+ // Two identical begin calls may finish their async reads together. Recheck+ // the receipt at the final allocation point before starting any mutation.+ if (this.operations.has(operationId)) {+ const existing = this.operation(peer, operationId);+ if (existing.fingerprint !== fingerprint) fail();+ return existing.receipt;+ }+ for (const [id, op] of this.operations)+ if (!op.visible()) {+ clearTimeout(op.timer);+ this.operations.delete(id);+ }+ if (+ this.operations.size >= 128 ||+ [...this.operations.values()].filter(+ (op) => op.peer === peer && ['running', 'confirmation'].includes(op.receipt.phase),+ ).length >= 8+ )+ fail();+ const confirmation = ['install', 'update', 'uninstall'].includes(kind);+ const receipt: RemoteSkillReceipt = {+ operationId,+ phase: confirmation ? 'confirmation' : 'running',+ ...(confirmation+ ? {+ confirmation: {+ requestId: randomUUID(),+ kind,+ name: record?.view.name ?? market!.displayName,+ version: market?.version,+ linkOnly: record?.linkOnly,+ },+ }+ : {}),+ };+ const operation: Operation = {+ peer,+ fingerprint,+ receipt,+ ...access,+ timer: setTimeout(() => {+ this.operations.delete(operationId);+ }, 15 * 60_000),+ run: async () => {+ try {+ if (!access.current()) fail('NOT_FOUND');+ if (+ record &&+ !(await this.deps.scan()).some(+ (next) =>+ next.view.id === record!.view.id && next.view.revision === record!.view.revision,+ )+ )+ fail('NOT_FOUND');+ if (!access.current()) fail('NOT_FOUND');+ if (+ project &&+ !(await this.deps.projects!()).some(+ (next) => next.id === project.id && next.revision === project.revision,+ )+ )+ fail('NOT_FOUND');+ await this.deps.mutate(kind, record, market, access.current, project);+ operation.receipt = { operationId, phase: 'succeeded' };+ } catch {+ operation.receipt = { operationId, phase: 'failed' };+ }+ },+ };+ operation.timer.unref?.();+ this.operations.set(operationId, operation);+ if (!confirmation) void operation.run();+ return receipt;+ }+ provider(): RemoteResourceProvider {+ return {+ collection: {+ id: 'skills',+ resourceKind: 'skill',+ title: { fallback: 'Skills' },+ actions: [+ { id: 'management:snapshot', label: 'Manage skills' },+ ...(this.deps.catalog+ ? [{ id: 'management:catalog', label: 'Browse skill catalog' }]+ : []),+ ],+ },+ list: async ({ controllerDeviceId }) => {+ const access = this.access(controllerDeviceId);+ const records = await this.deps.scan();+ if (!access.current()) fail('NOT_FOUND');+ return {+ collectionId: 'skills',+ revision: createHash('sha256')+ .update(records.map((record) => record.view.revision).join(':'))+ .digest('hex'),+ items: records.map(({ view }) => ({+ ref: { collectionId: 'skills', kind: 'skill', id: view.id },+ revision: view.revision,+ display: { title: view.name, subtitle: view.description },+ links: [],+ })),+ };+ },+ get: async ({ controllerDeviceId }, request) => {+ const access = this.access(controllerDeviceId);+ const record = (await this.deps.scan()).find((record) => record.view.id === request.ref.id);+ if (!record) fail('NOT_FOUND');+ const markdown = await this.deps.detail(record);+ if (!access.current()) fail('NOT_FOUND');+ return {+ ref: request.ref,+ revision: record.view.revision,+ display: { title: record.view.name, subtitle: record.view.description },+ links: [],+ blocks: [{ id: 'content', primitive: 'markdown', fallbackMarkdown: markdown }],+ };+ },+ invoke: async ({ controllerDeviceId }, request) => ({+ effects: [],+ result: await this.invoke(controllerDeviceId, request),+ }),+ };+ }+}diff --git a/apps/desktop/src/main/skillhub/remoteManagementHost.ts b/apps/desktop/src/main/skillhub/remoteManagementHost.tsnew file mode 100644index 0000000000..605dba7c85--- /dev/null+++ b/apps/desktop/src/main/skillhub/remoteManagementHost.ts@@ -0,0 +1,331 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash } from 'node:crypto';+import { isSharedTaskPeer, isProviderSharePeer } from '@cindy/device-link';+import {+ captureDataOwnerBroadcastScope,+ isDataOwnerBroadcastScopeCurrent,+} from '../device-link/broadcast-tap';+import { readDeviceLinkSettings } from '../device-link/settings-store';+import { capturePluginOauthPeer } from '../plugin-oauth/runtime';+import { RemoteSkillsManagement, type RemoteSkillRecord } from './remoteManagement';+import {+ scanAllSkills,+ readSkillContent,+ readSkillSiblingFile,+ listSkillFolderChildren,+ type Skill,+} from './scanner';+import {+ setCindySkillEnabled,+ isCindySkillEnabled,+ snapshotSkillActivation,+} from './activationPreferences';+import {+ inspectLocalSkillTarget,+ isLocalSkillTargetCurrent,+ isPluginManagedSkillPath,+} from './localSkillTarget';+import { tryAcquireSkillInstallLock } from './installLock';+import * as installService from './installService';+import type { SkillhubMarketService } from './marketService';+import type { RegisterSkillhubIpcOptions } from './registerIpc';+import type { RemoteSkillMarketItem, RemoteSkillProject } from '../../shared/remoteSkills';+import { readRemoteSkillCatalog } from './remoteCatalog';++const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');+function physicalRevision(skill: Skill): string {+ const files = [+ skill.absolutePath,+ skill.mdPath,+ ...(skill.discoveryPaths ?? [skill.discoveredPath]),+ ];+ return digest([+ files.map((file) => {+ const stat = fs.statSync(file);+ const link = fs.lstatSync(file);+ return [+ fs.realpathSync.native(file),+ stat.dev,+ stat.ino,+ stat.mtimeMs,+ stat.ctimeMs,+ stat.size,+ link.dev,+ link.ino,+ ];+ }),+ isCindySkillEnabled(skill.absolutePath),+ snapshotSkillActivation(skill.absolutePath),+ ]);+}+interface Target {+ skill: Skill;+ physical: string;+ uninstall: ReturnType<typeof inspectLocalSkillTarget>;+}++/** Adapt existing SkillHub services, preserving their locks, backups and trash semantics. */+export function createRemoteSkillsHost(+ options: RegisterSkillhubIpcOptions,+ marketService: SkillhubMarketService,+ changed: () => void,+ refresh: (workingDir?: string) => Promise<void>,+) {+ const projectTargets = async () =>+ (await options.getAllowedProjectRoots()).flatMap((root) => {+ try {+ const stat = fs.statSync(root);+ if (!stat.isDirectory()) return [];+ const real = fs.realpathSync.native(root);+ const identity =+ process.platform === 'win32' ? path.resolve(root).toLowerCase() : path.resolve(root);+ return [+ {+ root,+ view: {+ id: digest(identity),+ revision: digest([real, stat.dev, stat.ino]),+ name: path.basename(root),+ },+ },+ ];+ } catch {+ return [];+ }+ });+ const resolveProject = async (project: RemoteSkillProject) => {+ const match = (await projectTargets()).find(+ ({ view }) => view.id === project.id && view.revision === project.revision,+ );+ if (!match) throw new Error('Skill project changed');+ return match.root;+ };+ const scan = async (): Promise<RemoteSkillRecord<Target>[]> => {+ const targets = await projectTargets();+ const projects = targets.map(({ root, view }) => ({+ projectRoot: root,+ hash: view.id,+ }));+ const result = await scanAllSkills(+ { projects },+ options.getMaker(),+ options.getManagedSkillRoots(),+ options.getBuiltInSkills?.() ?? [],+ );+ if (!result.skills.length && result.sources.some((source) => source.status.state === 'error'))+ throw new Error('Skill discovery unavailable');+ return result.skills.flatMap((skill) => {+ try {+ const physical = physicalRevision(skill);+ const uninstall = inspectLocalSkillTarget(+ skill.absolutePath,+ skill.discoveryPaths ?? [skill.discoveredPath],+ options.getManagedSkillRoots(),+ );+ const managedByPlugin =+ skill.managedByPlugin === true ||+ isPluginManagedSkillPath(skill.absolutePath, options.getManagedSkillRoots());+ return [+ {+ target: { skill, physical, uninstall },+ linkOnly: uninstall?.linkOnly,+ view: {+ id: digest([skill.id, skill.absolutePath, skill.scope, skill.projectRoot]),+ revision: digest([physical, uninstall, skill.registryEntry]),+ name: skill.name,+ description: skill.description ?? '',+ kind: skill.kind,+ scope: skill.scope,+ project: skill.projectRoot ? path.basename(skill.projectRoot) : undefined,+ projectId: targets.find(({ root }) => root === skill.projectRoot)?.view.id,+ entryFile: path.basename(skill.mdPath),+ engines: skill.linkedEngines.map((engine) => engine.label),+ enabled: skill.cindyEnabled !== false,+ managedByPlugin,+ builtIn: skill.builtIn === true,+ canUninstall: !skill.builtIn && !managedByPlugin && uninstall !== null,+ version: skill.registryEntry?.version,+ market: skill.registryEntry+ ? {+ name: skill.registrySkillName ?? skill.name,+ catalogScope: skill.registryEntry.catalogScope,+ origin: skill.registryEntry.origin,+ authorId: skill.registryEntry.authorId,+ }+ : undefined,+ },+ },+ ];+ } catch {+ return [];+ }+ });+ };+ const projectMarket = (item: {+ name: string;+ displayName: string;+ description: string;+ latestVersion: string;+ catalogScope?: 'market' | 'team';+ }): RemoteSkillMarketItem => ({+ name: item.name,+ displayName: item.displayName,+ description: item.description,+ version: item.latestVersion,+ catalogScope: item.catalogScope ?? 'market',+ });+ return new RemoteSkillsManagement<Target>({+ capture: (peer) => {+ const scope = captureDataOwnerBroadcastScope(),+ checkPeer = capturePluginOauthPeer(peer);+ const visible = () => {+ const settings = readDeviceLinkSettings();+ return (+ !isSharedTaskPeer(peer) &&+ !isProviderSharePeer(peer) &&+ settings.remoteControlEnabled &&+ !settings.revokedControllers.includes(peer) &&+ isDataOwnerBroadcastScopeCurrent(scope)+ );+ };+ return {+ visible,+ current: () => {+ try {+ checkPeer();+ return options.remoteIsRelayOnline?.() === true && visible();+ } catch {+ return false;+ }+ },+ };+ },+ scan,+ projects: async () => (await projectTargets()).map(({ view }) => view),+ catalog: (input) => readRemoteSkillCatalog(marketService, input),+ readFile: async (record, relativePath, children) => {+ const skill = record.target.skill;+ const root = skill.kind === 'skill' ? skill.absolutePath : path.dirname(skill.mdPath);+ const candidate = path.resolve(root, relativePath);+ const relative = path.relative(+ fs.realpathSync.native(root),+ fs.realpathSync.native(candidate),+ );+ if (+ relative === '..' ||+ relative.startsWith(`..${path.sep}`) ||+ path.isAbsolute(relative) ||+ (skill.kind !== 'skill' && (children || candidate !== skill.mdPath))+ )+ throw new Error('Skill file unavailable');+ if (!children && fs.statSync(candidate).size > 1024 * 1024)+ throw new Error('Skill file too large');+ if (physicalRevision(skill) !== record.target.physical) throw new Error('Skill changed');+ const attestedRoot = skill.builtIn ? root : undefined;+ const result = children+ ? await listSkillFolderChildren({ dirPath: candidate, attestedRoot })+ : candidate.toLowerCase().endsWith('.md')+ ? await readSkillContent({ mdPath: candidate, attestedRoot })+ : await readSkillSiblingFile({ filePath: candidate, attestedRoot });+ if (!result.success || physicalRevision(skill) !== record.target.physical)+ throw new Error('Skill file unavailable');+ return result;+ },+ market: async (query, cursor) => {+ const result = await marketService.listMarket({ q: query, cursor, limit: 24, scope: 'all' });+ return { items: result.items.map(projectMarket), nextCursor: result.nextCursor };+ },+ latest: async (name, scope) => {+ const result = await marketService.info(name, scope);+ return 'info' in result && result.info ? projectMarket(result.info) : null;+ },+ detail: async (record) => {+ const result = await readSkillContent({+ mdPath: record.target.skill.mdPath,+ ...(record.view.builtIn ? { attestedRoot: record.target.skill.absolutePath } : {}),+ });+ if (!result.success || !('content' in result)) throw new Error('Skill detail unavailable');+ if (physicalRevision(record.target.skill) !== record.target.physical)+ throw new Error('Skill changed');+ return String(result.content).slice(0, 1024 * 1024);+ },+ mutate: async (kind, record, market, current, project) => {+ const projectRoot = project ? await resolveProject(project) : undefined;+ const allowed = async () =>+ (!project || (await resolveProject(project)) === projectRoot) &&+ (!record?.target.skill.projectRoot ||+ (await options.getAllowedProjectRoots()).some((root) => {+ const normalize = (value: string) =>+ process.platform === 'win32'+ ? path.resolve(value).toLowerCase()+ : path.resolve(value);+ return normalize(root) === normalize(record.target.skill.projectRoot!);+ }));+ const valid = () => {+ try {+ return (+ current() &&+ (!record ||+ (physicalRevision(record.target.skill) === record.target.physical &&+ !isPluginManagedSkillPath(+ record.target.skill.absolutePath,+ options.getManagedSkillRoots(),+ )))+ );+ } catch {+ return false;+ }+ };+ if (!valid() || !(await allowed()) || !valid()) throw new Error('Skill target changed');+ let workingDir: string | undefined;+ if (kind === 'enable' || kind === 'disable') {+ const release = tryAcquireSkillInstallLock(record!.target.skill.name, 'market-uninstall');+ if (!release) throw new Error('Skill busy');+ try {+ await setCindySkillEnabled(+ record!.target.skill.absolutePath,+ kind === 'enable',+ valid,+ record!.target.skill.discoveryPaths ?? [record!.target.skill.discoveredPath],+ );+ } finally {+ release();+ }+ } else if (kind === 'uninstall') {+ const target = record!.target.uninstall;+ if (!target || !isLocalSkillTargetCurrent(target)) throw new Error('Skill target changed');+ const result = await installService.uninstall(+ record!.target.skill.absolutePath,+ target,+ () =>+ current() &&+ !isPluginManagedSkillPath(target.sourcePath, options.getManagedSkillRoots()),+ async () => valid() && (await allowed()) && valid(),+ );+ if (!result.success) throw new Error('Skill uninstall failed');+ workingDir = result.projectWorkingDir;+ } else {+ const result = await installService.install(+ {+ name: market!.name,+ version: market!.version,+ catalogScope: market!.catalogScope,+ ...(projectRoot+ ? { installPath: path.join(projectRoot, '.agents', 'skills', market!.name) }+ : {}),+ ...(kind === 'update'+ ? { force: true, installPath: record!.target.skill.absolutePath }+ : {}),+ },+ () => {},+ { current, beforeCommit: async () => valid() && (await allowed()) && valid() },+ );+ if (!result.success) throw new Error('Skill install failed');+ workingDir = result.projectWorkingDir;+ }+ changed();+ await refresh(workingDir);+ },+ });+}diff --git a/apps/desktop/src/main/skillhub/skillListProjection.ts b/apps/desktop/src/main/skillhub/skillListProjection.tsindex 8ed21e5d04..fd40b822ac 100644--- a/apps/desktop/src/main/skillhub/skillListProjection.ts+++ b/apps/desktop/src/main/skillhub/skillListProjection.ts@@ -37,7 +37,7 @@ function normalizeScope(engine: string, rawScope: string): SkillScope {if (engine === 'codex' || engine === 'pi') {return rawScope === 'repo' ? 'project' : 'global';}- return rawScope as SkillScope;+ return rawScope === 'project' ? 'project' : 'global';}function realPathOrNormalized(value: string): string {diff --git a/apps/desktop/src/main/webview-security.ts b/apps/desktop/src/main/webview-security.tsindex fdd57be5db..9b3107c2ee 100644--- a/apps/desktop/src/main/webview-security.ts+++ b/apps/desktop/src/main/webview-security.ts@@ -50,6 +50,8 @@ import {import { classifyGhostPanelNavigation } from './cindy-brain/previewGate.js';import { ghostMediaHandoverDragScript, ghostMediaHandoverTargetTracker } from './cindy-brain/ghostMediaHandoverTargetTracker.js';import { registerGhostWebContents } from './cindy-brain/runtime/electronSandboxAdapter.js';+import { REMOTE_PLUGIN_SETTINGS_PARTITION } from '../shared/remotePluginSettings.js';+import { resolveRemoteSettingsAttach } from './cindy-brain/remotePluginSettingsController.js';import {attributeRsbNativePopupSurface,createRsbNativePopupSurface,@@ -942,8 +944,23 @@ export function installWebviewHardener(): void {// 不装浏览器的 popup 路由与快捷键转发)。let pendingGhostAttach: ReturnType<typeof authorizeGhostWebviewAttach> = null;let pendingCaptchaAttach = false;+ let pendingRemoteSettings: ReturnType<typeof resolveRemoteSettingsAttach> = null;contents.on('will-attach-webview', (e, webPreferences, params) => {pendingCaptchaAttach = false;+ pendingRemoteSettings = null;+ pendingGhostAttach = null;+ if (typeof params.partition === 'string' && params.partition.startsWith(REMOTE_PLUGIN_SETTINGS_PARTITION)) {+ const view = resolveRemoteSettingsAttach(contents, params.partition, params.src);+ if (!view) { e.preventDefault(); return; }+ params.partition = view.partition;+ webPreferences.partition = view.partition;+ applyGhostWebviewHardening(webPreferences as unknown as Record<string, unknown>, params);+ webPreferences.experimentalFeatures = false;+ webPreferences.navigateOnDragDrop = false;+ delete webPreferences.enableBlinkFeatures;+ pendingRemoteSettings = view;+ return;+ }// 意识面板分支:声明了意识分区的 webview 必须验明正身——// 分区/地址/已装清单三对齐才放行并保留专属分区;验证失败直接拒附加// (绝不回落到浏览器分区,那会让 cindy-ghost:// 内容跑进错误 session)。@@ -993,6 +1010,12 @@ export function installWebviewHardener(): void {);});contents.on('did-attach-webview', (_e, guestContents) => {+ if (pendingRemoteSettings) {+ const view = pendingRemoteSettings;+ pendingRemoteSettings = null;+ try { view.current(); view.attach(guestContents); } catch { guestContents.close(); }+ return;+ }if (pendingCaptchaAttach) {pendingCaptchaAttach = false;// 挑战页零弹窗;顶层导航只允许停留在托管挑战页白名单内(Turnstile 的diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 654854b413..3f6660b144 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -719,6 +719,7 @@ const fanOutGhostAssistantPending = createIpcFanOut('ghosts:assistant-message-peconst fanOutGhostHookFused = createIpcFanOut('ghosts:hook-fused');// 意识系统提示(notify 槽:宿主 Toast 渲染,带意识身份头)。const fanOutGhostNotify = createIpcFanOut('ghosts:notify');+const fanOutRemoteSettingsDirectory = createIpcFanOut('device-link:plugin-settings:directory');// 意识未读角标(badge 槽:插件入口与插件卡上的绿点,持久状态非一次性 toast)。const fanOutGhostBadge = createIpcFanOut('ghosts:badge');// 未读全量快照(换账号后整表替换;逐条 badge 只表达增量)。@@ -1245,6 +1246,12 @@ contextBridge.exposeInMainWorld('electronAPI', {// 意识仓库 (shared/ghost.ts)。listSync 走 sendSync:意识面板要与内置// 面板同帧注册进布局引擎(规则 7 无跳变);目录扫描极小,同步读不卡启动。ghosts: {+ openRemoteSettings: (target: import('../shared/remotePluginSettings').RemotePluginSettingsTarget): Promise<import('../shared/remotePluginSettings').RemotePluginSettingsView> =>+ ipcRenderer.invoke('device-link:plugin-settings:open', target),+ closeRemoteSettings: (id: string): Promise<void> => ipcRenderer.invoke('device-link:plugin-settings:close', id),+ onRemoteSettingsDirectory: fanOutRemoteSettingsDirectory,+ answerRemoteSettingsDirectory: (answer: import('../shared/remotePluginSettings').RemotePluginSettingsDirectoryAnswer): Promise<void> =>+ ipcRenderer.invoke('device-link:plugin-settings:answer-directory', answer),recommendationsSync:(): import('../shared/homePluginRecommendations').HomePluginRecommendationsSnapshot =>ipcRenderer.sendSync('ghosts:recommendations'),@@ -4599,6 +4606,8 @@ contextBridge.exposeInMainWorld('electronAPI', {onChanged: fanOutProviderGroupChanged,},deviceLink: {+ confirmSkillMutation: (deviceId: string, operationId: string): Promise<import('../shared/remoteSkills').RemoteSkillReceipt> => ipcRenderer.invoke('device-link:confirm-skill-mutation', { deviceId, operationId }),+ pickPluginPackage: (deviceId: string): Promise<{ attachment: string } | null> => ipcRenderer.invoke('device-link:pick-plugin-package', deviceId),taskMigration: (deviceId: string | null, request: import('@cindy/device-link').TaskMigrationRequest): Promise<import('@cindy/device-link').TaskMigrationView> =>ipcRenderer.invoke(TASK_MIGRATION_LOCAL_CHANNEL, deviceId, request),getState: (): Promise<{diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex eac622fb8b..c938b4742c 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1275,6 +1275,10 @@ interface ElectronAPI {/** 意识仓库 —— 数据模型与校验见 shared/ghost.ts,main 端见 main/cindy-brain/。 */ghosts: {+ openRemoteSettings: (target: import('../shared/remotePluginSettings').RemotePluginSettingsTarget) => Promise<import('../shared/remotePluginSettings').RemotePluginSettingsView>;+ closeRemoteSettings: (id: string) => Promise<void>;+ onRemoteSettingsDirectory: (callback: (value: import('../shared/remotePluginSettings').RemotePluginSettingsDirectory) => void) => () => void;+ answerRemoteSettingsDirectory: (answer: import('../shared/remotePluginSettings').RemotePluginSettingsDirectoryAnswer) => Promise<void>;recommendationsSync: () => import('../shared/homePluginRecommendations').HomePluginRecommendationsSnapshot;/** 首帧同步拉取已装清单(规则 7:意识面板与内置面板同帧注册,无跳变)。 */listSync: () => { ghosts: import('../shared/ghost').InstalledGhost[] };@@ -3980,6 +3984,8 @@ interface ElectronAPI {onChanged(cb: (event: { providerId: string }) => void): () => void;};deviceLink: {+ confirmSkillMutation: (deviceId: string, operationId: string) => Promise<import('../shared/remoteSkills').RemoteSkillReceipt>;+ pickPluginPackage: (deviceId: string) => Promise<{ attachment: string } | null>;taskMigration: (deviceId: string | null, request: import('@cindy/device-link').TaskMigrationRequest) => Promise<import('@cindy/device-link').TaskMigrationView>;getState: () => Promise<{remoteControlEnabled: boolean;diff --git a/apps/desktop/src/shared/pluginManagement.ts b/apps/desktop/src/shared/pluginManagement.tsnew file mode 100644index 0000000000..ea8f0dd948--- /dev/null+++ b/apps/desktop/src/shared/pluginManagement.ts@@ -0,0 +1,35 @@+import type { InstalledGhost } from './ghost';+import type { GhostInstallConsentRequest } from './ghostInstallConsent';+import type { PluginMarketSnapshot } from './pluginMarket';++export interface PluginManagementProject {+ /** Host-owned identity, never a controller filesystem path. */+ id: string;+ name: string;+ /** Read-only target path for the existing scope picker; never a mutation credential. */+ path?: string;+}+export interface PluginManagementProjectState {+ projectId: string;+ revision: string;+ /** Physical plugin instance keys disabled in this project. Global enable remains authoritative. */+ disabled: string[];+}+/** Additive plugins resource capability. Contains declarations, never saved credentials. */+export interface PluginManagementSnapshot {+ version: 1;+ ghosts: InstalledGhost[];+ market: PluginMarketSnapshot;+ /** Absent on older Hosts. Empty means project management is supported with no recent projects. */+ projects?: PluginManagementProject[];+ /** The Host can resolve a directory chosen through the existing remote folder browser. */+ projectBrowse?: true;+ hostPreferences?: true;+ settingsPage?: true;+}+export interface PluginManagementReceipt {+ operationId: string;+ phase: 'running' | 'confirmation' | 'succeeded' | 'cancelled' | 'failed';+ consent?: GhostInstallConsentRequest;+ errorCode?: string;+}diff --git a/apps/desktop/src/shared/pluginPreferences.ts b/apps/desktop/src/shared/pluginPreferences.tsnew file mode 100644index 0000000000..022134c5b6--- /dev/null+++ b/apps/desktop/src/shared/pluginPreferences.ts@@ -0,0 +1,19 @@+import type { PluginTaskPreferences } from '@cindy/device-link';+import type { GhostManifest } from './ghost';++/** Non-secret Host controls; the plugin's own fields remain in its settings page. */+export interface RemotePluginPreferenceSnapshot {+ revision: string;+ tasks?: PluginTaskPreferences;+ auxiliaryModelLabel?: string | null;+ sidebarVisible?: boolean;+}++export function pluginHasModelPreferences(manifest: GhostManifest): boolean {+ return Boolean(+ manifest.workspace ||+ manifest.agent?.tasks ||+ manifest.agent?.errand ||+ manifest.cindy?.text?.includes('oneshot'),+ );+}diff --git a/apps/desktop/src/shared/remotePluginSettings.ts b/apps/desktop/src/shared/remotePluginSettings.tsnew file mode 100644index 0000000000..66af9a9655--- /dev/null+++ b/apps/desktop/src/shared/remotePluginSettings.ts@@ -0,0 +1,26 @@+export const REMOTE_PLUGIN_SETTINGS_PARTITION = 'remote-plugin-settings:';+export const REMOTE_PLUGIN_SETTINGS_OPEN = 'device-link:plugin-settings:open';+export const REMOTE_PLUGIN_SETTINGS_CLOSE = 'device-link:plugin-settings:close';+export const REMOTE_PLUGIN_SETTINGS_DIRECTORY = 'device-link:plugin-settings:directory';+export const REMOTE_PLUGIN_SETTINGS_DIRECTORY_ANSWER =+ 'device-link:plugin-settings:answer-directory';++export interface RemotePluginSettingsTarget {+ deviceId: string;+ instanceId: string;+ expectedInstalledApproval: string;+}+export interface RemotePluginSettingsView {+ id: string;+ partition: string;+ src: string;+}+export interface RemotePluginSettingsDirectory {+ viewId: string;+ request: import('@cindy/device-link').PluginDirectoryRequest;+}+export interface RemotePluginSettingsDirectoryAnswer {+ viewId: string;+ requestId: string;+ path: string | null;+}diff --git a/apps/desktop/src/shared/remoteSkills.ts b/apps/desktop/src/shared/remoteSkills.tsnew file mode 100644index 0000000000..ccc889d856--- /dev/null+++ b/apps/desktop/src/shared/remoteSkills.ts@@ -0,0 +1,95 @@+import type { SkillhubCatalogScope } from './skillhubCatalog';++/** Paths, registry internals and credentials never cross this projection. */+export interface RemoteSkillItem {+ id: string;+ revision: string;+ name: string;+ description: string;+ kind: 'skill' | 'command' | 'agent';+ scope: 'global' | 'project';+ project?: string;+ projectId?: string;+ /** Basename only; the Host retains the absolute entry path. */+ entryFile?: string;+ engines: string[];+ enabled: boolean;+ managedByPlugin: boolean;+ builtIn: boolean;+ canUninstall: boolean;+ version?: string;+ market?: {+ name: string;+ catalogScope?: SkillhubCatalogScope;+ origin?: 'installed' | 'published' | 'learned' | 'imported';+ authorId?: string;+ };+}+export interface RemoteSkillMarketItem {+ name: string;+ displayName: string;+ description: string;+ version: string;+ catalogScope: SkillhubCatalogScope;+}+export function isRemoteSkillMarketItem(value: unknown): value is RemoteSkillMarketItem {+ const item = value as RemoteSkillMarketItem | null;+ return (+ !!item &&+ typeof item.name === 'string' &&+ item.name.length <= 128 &&+ typeof item.displayName === 'string' &&+ item.displayName.length <= 256 &&+ typeof item.description === 'string' &&+ typeof item.version === 'string' &&+ item.version.length <= 128 &&+ ['market', 'team'].includes(item.catalogScope)+ );+}+export interface RemoteSkillsSnapshot {+ version: 1;+ items: RemoteSkillItem[];+ market: RemoteSkillMarketItem[];+ nextCursor: string | null;+ marketUnavailable: boolean;+ /** Absent on older Hosts. IDs authorize a choice, never a caller-supplied path. */+ projects?: RemoteSkillProject[];+}+export interface RemoteSkillProject {+ id: string;+ revision: string;+ name: string;+}+export type RemoteSkillMutation = 'enable' | 'disable' | 'install' | 'update' | 'uninstall';+export interface RemoteSkillReceipt {+ operationId: string;+ phase: 'confirmation' | 'running' | 'succeeded' | 'cancelled' | 'failed';+ confirmation?: {+ requestId: string;+ kind: RemoteSkillMutation;+ name: string;+ version?: string;+ linkOnly?: boolean;+ };+}++export function parseRemoteSkillReceipt(value: unknown, operationId: string): RemoteSkillReceipt {+ const receipt = value as RemoteSkillReceipt | null;+ const confirmation = receipt?.confirmation;+ if (+ !receipt ||+ receipt.operationId !== operationId ||+ !['confirmation', 'running', 'succeeded', 'cancelled', 'failed'].includes(receipt.phase) ||+ (receipt.phase === 'confirmation' &&+ (!confirmation ||+ typeof confirmation.requestId !== 'string' ||+ confirmation.requestId.length > 64 ||+ typeof confirmation.name !== 'string' ||+ confirmation.name.length > 256 ||+ !['install', 'update', 'uninstall'].includes(confirmation.kind) ||+ (confirmation.version !== undefined &&+ (typeof confirmation.version !== 'string' || confirmation.version.length > 128))))+ )+ throw new Error('INVALID_RESPONSE');+ return receipt;+}