Skip to content

armgit / cindy

Public Imported from GitHub
0

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

feat(plugin): 支持本地插件分享与固定版本安装

liugaowei1319c3a89d66
diff --git a/apps/desktop/scripts/fixtures/local-plugin-sharing/fixture.tsx b/apps/desktop/scripts/fixtures/local-plugin-sharing/fixture.tsx
new file mode 100644
index 0000000000..b9ee06c12d
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/local-plugin-sharing/fixture.tsx
@@ -0,0 +1,72 @@
+import { mountPage, subscription } from '../../ui-page/harness';
+import { PluginShareButton } from '../../../src/renderer/features/plugin/PluginShareButton';
+import { LocalPluginShareView } from '../../../src/renderer/features/plugin/LocalPluginShareView';
+import { GhostInstallConsentHost } from '../../../src/renderer/cindy-brain/GhostInstallConsentHost';
+import type { InstalledGhost } from '../../../src/shared/ghost';
+import { useState } from 'react';
+import type { CatalogDevice } from '../../../src/renderer/features/plugin/useCatalogDevice';
+import { REMOTE_RESOURCE_MANIFEST_CHANNEL } from '@cindy/device-link';
+import { InteractivePreview, interactiveHost } from './interactive';
+
+const ghost: InstalledGhost = {
+ manifest: { schemaVersion: 3, id: 'local-share-example', name: '我的本地插件', description: '用于演示按次分享的本地插件。', version: '1.0.0', entry: 'index.js', kind: 'chip',
+ network: { hosts: ['api.example.test'] } },
+ namespace: null, namespaceState: 'confirmed', instanceKey: '_root__local-share-example',
+ dir: '/fixture/local-share-example', enabled: true, publishingSource: { kind: 'local', source: 'manual' },
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+};
+const snapshotId = 'a'.repeat(32);
+const snapshot = { schemaVersion: 1, snapshotId, ghostId: ghost.manifest.id, version: ghost.manifest.version,
+ name: ghost.manifest.name, description: ghost.manifest.description, author: null, icon: null,
+ sha256: 'a'.repeat(64), sizeBytes: 1024, createdAt: '2026-10-28T00:00:00.000Z' };
+
+const target = { deviceId: 'fixture-target', name: 'Studio Computer' };
+const candidate = { ...target, platform: 'darwin', appVersion: '0.1.200', lastSeenAt: null, online: true,
+ busy: false, isSelf: false, controlEnabled: true, remoteControlEnabled: true };
+function Preview({ receiver, scene }: { receiver: boolean; scene: string }) {
+ const [selected, setSelected] = useState<CatalogDevice | null>(scene.startsWith('remote') ? target : null);
+ const online = scene !== 'remote-offline';
+ return <main className="h-screen">
+ {receiver ? <LocalPluginShareView snapshotId={snapshotId} onBack={() => {}} onInstalled={() => {}}
+ deviceControl={{ selected, onSelect: setSelected, directory: { candidates: [{ ...candidate, online }], target: selected ? { ...candidate, online } : undefined, online: !selected || online, relayOnline: true } }} />
+ : <div className="flex items-center gap-4 p-6"><span>{ghost.manifest.name}</span><PluginShareButton ghost={ghost} /></div>}
+ <GhostInstallConsentHost />
+ </main>;
+}
+
+mountPage({
+ route: '/plugins',
+ host: ctx => ({
+ getFullscreenState: async () => false, onFullscreenChange: subscription('fullscreen'),
+ ghosts: { onInstallConsentRequest: subscription('consent'), onInstallConsentDismissed: subscription('dismissed'),
+ resolveInstallConsent: async () => ({ handled: true }) },
+ deviceLink: { invoke: async (device, channel, [request]) => {
+ if (device !== target.deviceId) throw new Error('Wrong install target');
+ if (channel === REMOTE_RESOURCE_MANIFEST_CHANNEL) return { collections: [{ id: 'plugins', actions: [{ id: 'management:snapshot' }] }] };
+ if (request.actionId === 'management:snapshot') return { effects: [], result: { version: 1, ghosts: [],
+ market: { items: [], customSourceNames: [], unavailableCustomSourceNames: [] }, ...(ctx.case === 'remote-unsupported' ? {} : { localShares: true }) } };
+ return { effects: [], result: { operationId: request.input.operationId, phase: 'confirmation', consent: {
+ requestId: 'fixture-consent', initiator: 'user', origin: 'local-file', facts: { kind: 'install', name: snapshot.name, version: snapshot.version,
+ permissions: [{ key: 'network:host:api.example.test', kind: 'network', labelKey: 'networkHost', labelArgs: { host: 'api.example.test' } }] },
+ } } };
+ } },
+ pluginMarket: {
+ releaseLocalShare: async () => {},
+ prepareLocalShare: async (_instance, _operation, _options, _binding, confirmed) => {
+ if (!confirmed) await new Promise<void>(resolve => {
+ window.addEventListener('local-share-check-complete', () => resolve(), { once: true });
+ });
+ if (ctx.case === 'changed') throw new Error('[PRECONDITION_FAILED] Package changed');
+ return !confirmed && ctx.case !== 'reused'
+ ? { confirmationRequired: true as const }
+ : { title: snapshot.name, url: `https://share.example.test/s/${snapshotId}`,
+ imageSvg: `<svg xmlns="http://www.w3.org/2000/svg" width="1080" height="1080"><text x="80" y="160" font-size="50">${snapshot.name} · v1.0.0</text></svg>` };
+ },
+ localShareDetail: ctx.case === 'login' ? () => { throw new Error('Package read before login'); } : async () => snapshot,
+ // The check supplies the original host dialog request via the harness event.
+ installLocalShare: async () => new Promise(() => {}),
+ },
+ ...(ctx.case === 'interactive' ? interactiveHost : {}),
+ }),
+ render: ctx => ctx.case === 'interactive' ? <InteractivePreview /> : <Preview receiver={ctx.case.startsWith('recipient') || ctx.case.startsWith('remote') || ctx.case === 'login'} scene={ctx.case} />,
+});
diff --git a/apps/desktop/scripts/fixtures/local-plugin-sharing/interactive.tsx b/apps/desktop/scripts/fixtures/local-plugin-sharing/interactive.tsx
new file mode 100644
index 0000000000..78f0753c43
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/local-plugin-sharing/interactive.tsx
@@ -0,0 +1,152 @@
+/** Manual UI demo only: all package, account and device data stays in this window. */
+import { useState, useSyncExternalStore } from 'react';
+import { Button } from '../../../src/renderer/components/ui/button';
+import { GhostPluginDetailView } from '../../../src/renderer/features/plugin/GhostPluginDetailView';
+import { toGhostPluginDetail } from '../../../src/renderer/features/plugin/lib/ghostPluginViewModel';
+import { LocalPluginShareView } from '../../../src/renderer/features/plugin/LocalPluginShareView';
+import { GhostInstallConsentHost } from '../../../src/renderer/cindy-brain/GhostInstallConsentHost';
+import { ToastContainer } from '../../../src/renderer/components/ui/toast/ToastContainer';
+import { toast } from '../../../src/renderer/lib/toast';
+import { createIpcError } from '../../../src/shared/ipc-errors';
+import type { InstalledGhost } from '../../../src/shared/ghost';
+import type { LocalPluginShareSnapshot } from '@cindy/plugin-protocol';
+import { REMOTE_RESOURCE_MANIFEST_CHANNEL } from '@cindy/device-link';
+import { subscription } from '../../ui-page/harness';
+import type { UiPageRuntime } from '../../ui-page/harness/types';
+
+const demoWindow = window as typeof window & { __localShareDemoSignedIn?: boolean };
+const change = () => window.dispatchEvent(new Event('local-share-demo-change'));
+const subscribe = (notify: () => void) => {
+ window.addEventListener('local-share-demo-change', notify);
+ return () => window.removeEventListener('local-share-demo-change', notify);
+};
+const plugin = (version: string, publicPlugin = false): InstalledGhost => ({
+ manifest: { schemaVersion: 3, id: publicPlugin ? 'public-share-demo' : 'local-share-demo',
+ name: publicPlugin ? '公共插件示例' : '本地笔记助手', version: publicPlugin ? '2.3.0' : version, kind: 'chip', entry: 'index.js',
+ description: '整理笔记并生成摘要。此插件仅用于分享界面演示,所有操作均为模拟数据。',
+ author: 'Demo Author', network: { hosts: ['api.example.test'] } },
+ dir: '/fixture/local-share-demo', enabled: true, namespace: null, namespaceState: 'confirmed',
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+ ...(publicPlugin ? {} : { publishingSource: { kind: 'local' as const, source: 'manual' as const } }),
+});
+const shares = new Map<string, LocalPluginShareSnapshot>();
+const operations = new Map<string, LocalPluginShareSnapshot>();
+const uploadedVersions = new Set<string>();
+let sequence = 0;
+const devices = [
+ { deviceId: 'demo-online', name: '工作电脑', online: true },
+ { deviceId: 'demo-offline', name: '离线电脑', online: false },
+ { deviceId: 'demo-old', name: '旧版电脑', online: true },
+].map(device => ({ ...device, platform: 'darwin', appVersion: '0.1.200', lastSeenAt: null,
+ busy: false, isSelf: false, controlEnabled: true, remoteControlEnabled: true }));
+const receipts = new Map<string, Record<string, unknown>>();
+const pending = new Map<string, (confirmed: boolean) => void>();
+const facts = (snapshot: LocalPluginShareSnapshot) => ({ kind: 'install', ghostId: snapshot.ghostId,
+ name: snapshot.name, version: snapshot.version,
+ permissions: [{ key: 'network:host:api.example.test', kind: 'network', labelKey: 'networkHost', labelArgs: { host: 'api.example.test' } }],
+});
+function material(snapshot: LocalPluginShareSnapshot, includeAttribution: boolean) {
+ return { title: snapshot.name, url: `https://share.example.test/s/${snapshot.snapshotId}`,
+ imageSvg: `<svg xmlns="http://www.w3.org/2000/svg" width="1080" height="1080"><rect width="1080" height="1080" fill="#f4f3ef"/><text x="72" y="128" fill="#555" font-size="28">Cindy · 分享演示</text><text x="72" y="310" fill="#222" font-size="64">${snapshot.name}</text><text x="72" y="410" fill="#555" font-size="40">v${snapshot.version}</text><text x="72" y="860" fill="#555" font-size="28">${includeAttribution ? '演示用户分享' : '插件分享'}</text></svg>`,
+ ...(includeAttribution ? { attribution: { displayName: '演示用户' } } : {}) };
+}
+const snapshotFor = (version: string, id: string): LocalPluginShareSnapshot => ({
+ schemaVersion: 1, snapshotId: id, ghostId: 'local-share-demo', name: '本地笔记助手', version,
+ description: '这是分享时固定的插件版本。切换本地版本或再次分享,不会改变此记录。', author: 'Demo Author',
+ sha256: version === '1.0.0' ? 'a'.repeat(64) : 'b'.repeat(64), sizeBytes: 4096,
+ createdAt: '2026-10-28T00:00:00.000Z', icon: null,
+});
+shares.set('a'.repeat(32), snapshotFor('1.0.0', 'a'.repeat(32)));
+
+export const interactiveHost = {
+ ghosts: {
+ listSync: () => ({ ghosts: [plugin('1.0.0')] }), onChanged: subscription('ghosts-changed'),
+ listBackgroundTasks: async () => ({ items: [] }),
+ usageSummary: async () => ({ subjectId: 'demo', recordingStartedAt: Date.now(), lastUsedAt: null,
+ callsLast7Days: 0, totalCalls: 0, until: Date.now(), deviceName: '演示电脑', recentTasks: [] }),
+ onInstallConsentRequest: subscription('consent'), onInstallConsentDismissed: subscription('dismissed'),
+ resolveInstallConsent: async (requestId: string, confirmed: boolean) => {
+ pending.get(requestId)?.(confirmed); pending.delete(requestId); return { handled: true };
+ },
+ },
+ pluginMarket: {
+ releaseLocalShare: async () => {},
+ prepareLocalShare: async (_instance: string, id: string, options: { includeAttribution: boolean }, binding: { version: string }, confirmed: boolean) => {
+ if (!confirmed && !uploadedVersions.has(binding.version)) return { confirmationRequired: true as const };
+ uploadedVersions.add(binding.version);
+ if (!operations.has(id)) {
+ const snapshot = snapshotFor(binding.version, String(++sequence).padStart(32, '0'));
+ shares.set(snapshot.snapshotId, snapshot); operations.set(id, snapshot); change();
+ }
+ return material(operations.get(id)!, options.includeAttribution);
+ },
+ prepareShare: async (_id: string, options: { includeAttribution: boolean }) =>
+ material({ ...snapshotFor('2.3.0', 'p'.repeat(32)), name: '公共插件示例' }, options.includeAttribution),
+ localShareDetail: async (id: string) => shares.get(id)!,
+ installLocalShare: async (_id: string, snapshot: LocalPluginShareSnapshot) => {
+ const requestId = `local-demo-${snapshot.snapshotId}`;
+ const confirmed = await new Promise<boolean>(resolve => {
+ pending.set(requestId, resolve);
+ (window as unknown as { __uiPage: UiPageRuntime }).__uiPage.emit!('consent', {
+ requestId, initiator: 'user', origin: 'local-file', facts: facts(snapshot),
+ });
+ });
+ if (!confirmed) throw createIpcError('MUTATION_CANCELLED', 'Demo consent declined');
+ return { ghost: plugin(snapshot.version) };
+ },
+ },
+ deviceLink: { invoke: async (device: string, channel: string, [request]: [{ actionId: string; input: Record<string, any> }]) => {
+ if (channel === REMOTE_RESOURCE_MANIFEST_CHANNEL) return { collections: [{ id: 'plugins', actions: [{ id: 'management:snapshot' }] }] };
+ if (request.actionId === 'management:snapshot') return { effects: [], result: { version: 1, ghosts: [], market: { items: [], customSourceNames: [], unavailableCustomSourceNames: [] }, localShares: device !== 'demo-old' } };
+ const id = request.input.operationId;
+ if (request.actionId === 'management:begin') receipts.set(id, { operationId: id, phase: 'confirmation', consent: {
+ requestId: `consent-${id}`, initiator: 'user', origin: 'local-file', facts: facts(request.input.expectedSnapshot),
+ } });
+ if (request.actionId === 'management:answer' || request.actionId === 'management:cancel')
+ receipts.set(id, { operationId: id, phase: request.input.confirmed ? 'succeeded' : 'cancelled' });
+ return { effects: [], result: receipts.get(id) };
+ } },
+ copyTextToClipboard: async () => { toast.info('已模拟复制动作,可在上方“打开分享记录”中查看接收页。'); },
+ copyPngToClipboard: async () => { toast.info('模拟复制图片完成。'); },
+ saveMediaAs: async () => ({ canceled: true }),
+};
+
+export function InteractivePreview() {
+ useSyncExternalStore(subscribe, () => `${sequence}:${demoWindow.__localShareDemoSignedIn !== false}`);
+ const [version, setVersion] = useState('1.0.0');
+ const [page, setPage] = useState('local');
+ const [selected, setSelected] = useState<(typeof devices)[number] | null>(null);
+ const [enabled, setEnabled] = useState(true);
+ const ghost = plugin(version, page === 'public');
+ const explain = () => toast.info('这是演示数据,不会修改真实插件。');
+ return <div className="flex h-screen flex-col bg-[var(--surface)] text-[var(--text-primary)]">
+ <aside className="shrink-0 space-y-3 border-b border-[var(--border-default)] p-4">
+ <p className="text-13 text-[var(--text-secondary)]">分享交互演示 · 模拟账号与包,不会真实上传或安装</p>
+ <div className="flex flex-wrap items-center gap-2">
+ <Button variant="secondary" onClick={() => setPage('local')}>本地插件</Button>
+ <Button variant="secondary" onClick={() => setPage('public')}>公共插件</Button>
+ <label className="text-13">本地版本 <select aria-label="本地版本" value={version} onChange={event => { setVersion(event.target.value); setPage('local'); }}>
+ <option>1.0.0</option><option>1.1.0</option>
+ </select></label>
+ <Button variant="secondary" onClick={() => { demoWindow.__localShareDemoSignedIn = demoWindow.__localShareDemoSignedIn === false; change(); }}>
+ {demoWindow.__localShareDemoSignedIn === false ? '模拟登录' : '模拟退出登录'}
+ </Button>
+ <label className="text-13">打开分享记录 <select aria-label="打开分享记录" value={shares.has(page) ? page : ''} onChange={event => setPage(event.target.value)}>
+ <option value="" disabled>选择分享</option>
+ {[...shares.values()].map((item, index) => <option key={item.snapshotId} value={item.snapshotId}>分享 {index + 1} · v{item.version}</option>)}
+ </select></label>
+ </div>
+ </aside>
+ <div className="min-h-0 flex-1">
+ {shares.has(page) ? <LocalPluginShareView key={`${page}:${selected?.deviceId ?? 'local'}`} snapshotId={page}
+ onBack={() => setPage('local')} onInstalled={() => toast.success(`模拟安装成功:${selected?.name ?? '本机'}`)}
+ deviceControl={{ selected, onSelect: next => setSelected(devices.find(item => item.deviceId === next?.deviceId) ?? null),
+ directory: { candidates: devices, target: selected ?? undefined, online: !selected || selected.online, relayOnline: true } }} />
+ : <GhostPluginDetailView key={`${page}:${version}`} ghost={ghost} detail={toGhostPluginDetail(ghost)}
+ sharePluginId={page === 'public' ? 'public-demo' : undefined} panelStatus={null} enabledOverride={enabled}
+ onToggle={setEnabled} onBack={() => setPage('local')} onUse={explain} onUpdate={explain}
+ onUpdateFromFile={explain} onUninstall={explain} toggleDisabled={false} />}
+ </div>
+ <GhostInstallConsentHost /><ToastContainer />
+ </div>;
+}
diff --git a/apps/desktop/scripts/fixtures/local-plugin-sharing/ui-page.mjs b/apps/desktop/scripts/fixtures/local-plugin-sharing/ui-page.mjs
new file mode 100644
index 0000000000..02b14aa40d
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/local-plugin-sharing/ui-page.mjs
@@ -0,0 +1,121 @@
+export default {
+ name: 'local-plugin-sharing',
+ entry: './fixture.tsx',
+ viewport: { width: 900, height: 850 },
+ real: 'PluginShareButton, ShareDialog, LocalPluginShareView and original permission dialog',
+ notCovered: 'Installed detail eligibility, real login, package transport, native clipboard and durable installation; host APIs are scene data',
+ stubs: {
+ 'src/renderer/contexts/AuthContext': `import { useSyncExternalStore } from 'react';
+ const subscribe = fn => { window.addEventListener('local-share-demo-change', fn); return () => window.removeEventListener('local-share-demo-change', fn); };
+ export function useAuth() { const signedIn = useSyncExternalStore(subscribe, () => window.__localShareDemoSignedIn ?? window.__uiPage.ctx.case !== 'login'); return { isAuthenticated: signedIn, mode: signedIn ? 'cloud' : 'local', dataOwnerId: 'fixture', dataOwnerGeneration: 1, exitLocalMode: async () => { window.__localShareDemoSignedIn = true; window.dispatchEvent(new Event('local-share-demo-change')); } }; }
+ export function useOptionalAuthUser() { return null; }`,
+ },
+ async ready(page) {
+ // The isolated HTTP fixture is not a secure context. Production runs in the
+ // trusted app renderer; fake only UUID generation at this native boundary.
+ await page.evaluate(() => {
+ if (!crypto.randomUUID) Object.defineProperty(crypto, 'randomUUID', { value: () => {
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
+ bytes[6] = (bytes[6] & 15) | 64; bytes[8] = (bytes[8] & 63) | 128;
+ const hex = [...bytes].map(value => value.toString(16).padStart(2, '0')).join('');
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
+ } });
+ });
+ },
+ cases: {
+ interactive: { about: 'Manual sharing demo with original detail pages, two versions, login states and device choices', viewport: { width: 1100, height: 850 } },
+ default: { about: 'The existing share button requires confirmation before uploading a local package' },
+ reused: { about: 'An unchanged uploaded package opens share material without another confirmation' },
+ narrow: { about: 'Local upload confirmation uses the existing dialog at narrow width', viewport: { width: 360, height: 740 } },
+ changed: { about: 'Changed content requires reopening to check and confirm the new package', viewport: { width: 360, height: 740 } },
+ recipient: { about: 'Exact shared version, explicit installation and real permission confirmation' },
+ 'recipient-narrow': { about: 'Exact shared package at narrow width', viewport: { width: 360, height: 740 } },
+ 'remote-select': { about: 'Choose another computer and confirm that computer’s permissions', viewport: { width: 900, height: 850 } },
+ 'remote-narrow': { about: 'Remote package and permission confirmation at minimum width', viewport: { width: 320, height: 740 } },
+ 'remote-offline': { about: 'Keep the offline target selected and disable installation', viewport: { width: 320, height: 740 } },
+ 'remote-unsupported': { about: 'Explain the required target update without local fallback', viewport: { width: 320, height: 740 } },
+ login: { about: 'No package read until login', viewport: { width: 360, height: 740 } },
+ },
+ async check(page, ui) {
+ if (ui.case === 'interactive') {
+ await page.getByRole('heading', { name: '本地笔记助手', exact: true }).waitFor();
+ await page.getByRole('button', { name: await ui.t('sharing.title'), exact: true }).click();
+ await page.getByRole('button', { name: await ui.t('sharing.uploadLocal') }).waitFor();
+ await ui.capture('upload-confirmation');
+ await page.getByRole('button', { name: await ui.t('sharing.uploadLocal') }).click();
+ await page.getByRole('button', { name: await ui.t('sharing.copyLink') }).waitFor();
+ await ui.capture('share-ready');
+ await page.getByRole('button', { name: await ui.t('sharing.close'), exact: true }).click();
+ await page.getByRole('combobox', { name: '打开分享记录' }).selectOption('00000000000000000000000000000001');
+ await page.getByRole('button', { name: await ui.t('sharing.localInstallButton', { version: '1.0.0' }) }).click();
+ await page.getByRole('button', { name: await ui.t('settings.ghosts.installConsent.confirmInstall'), exact: true }).click();
+ await page.getByText('模拟安装成功:本机', { exact: true }).waitFor();
+ await page.getByRole('button', { name: await ui.t('settings.ghosts.remote.device'), exact: true }).click();
+ await page.getByRole('menuitem', { name: '工作电脑', exact: true }).click();
+ await page.getByRole('button', { name: await ui.t('sharing.localInstallButton', { version: '1.0.0' }) }).click();
+ await ui.capture('remote-confirmation');
+ await page.getByRole('button', { name: await ui.t('settings.ghosts.installConsent.confirmInstall'), exact: true }).click();
+ await page.getByText('模拟安装成功:工作电脑', { exact: true }).waitFor();
+ return;
+ }
+ if (ui.case === 'login') {
+ await page.getByRole('button', { name: await ui.t('sharing.localSignIn') }).waitFor();
+ return;
+ }
+ if (ui.case.startsWith('remote')) {
+ await page.getByText('v1.0.0', { exact: true }).waitFor();
+ if (ui.case === 'remote-select') {
+ await page.getByRole('button', { name: await ui.t('settings.ghosts.remote.device') }).click();
+ await ui.capture('device-options');
+ await page.getByRole('menuitem', { name: await ui.t('settings.ghosts.remote.thisComputer') }).click();
+ await page.getByRole('button', { name: await ui.t('settings.ghosts.remote.device') }).click();
+ await page.getByRole('menuitem', { name: 'Studio Computer' }).click();
+ }
+ const button = page.getByRole('button', { name: await ui.t('sharing.localInstallButton', { version: '1.0.0' }) });
+ if (ui.case === 'remote-offline' || ui.case === 'remote-unsupported') {
+ await page.getByText(await ui.t(ui.case === 'remote-offline' ? 'settings.ghosts.remote.offlineNotice' : 'sharing.localTargetUnsupported', { device: 'Studio Computer' }), { exact: true }).waitFor();
+ if (await button.isEnabled()) throw new Error('Unavailable target enabled installation');
+ return;
+ }
+ await ui.capture('target-device');
+ await button.click();
+ await page.getByRole('alertdialog').waitFor();
+ await ui.capture('target-permissions');
+ return;
+ }
+ if (ui.case.startsWith('recipient')) {
+ await page.getByText('v1.0.0', { exact: true }).waitFor();
+ await ui.capture('fixed-version');
+ await page.getByRole('button', { name: await ui.t('sharing.localInstallButton', { version: '1.0.0' }) }).click();
+ await ui.emit('consent', {
+ requestId: 'local-share-fixture', initiator: 'user', origin: 'local-file',
+ target: { namespace: null, sourceChanged: false, otherCopies: 0 },
+ facts: { kind: 'install', ghostId: 'local-share-example', name: '我的本地插件', version: '1.0.0',
+ permissions: [{ key: 'network:host:api.example.test', kind: 'network', labelKey: 'networkHost', labelArgs: { host: 'api.example.test' } }] },
+ });
+ await page.getByRole('alertdialog').waitFor();
+ await ui.capture('permissions');
+ return;
+ }
+ await page.getByRole('button', { name: await ui.t('sharing.title') }).click();
+ await page.locator('button[aria-busy="true"]').waitFor();
+ if (await page.getByRole('dialog').count()) throw new Error('Share dialog opened before the upload decision');
+ await ui.capture('checking-before-open');
+ await page.evaluate(() => window.dispatchEvent(new Event('local-share-check-complete')));
+ if (ui.case === 'changed') {
+ await page.getByText(await ui.t('sharing.localChanged'), { exact: true }).waitFor();
+ if (await page.getByRole('button', { name: await ui.t('sharing.retry') }).count()) throw new Error('Obsolete confirmation can still be retried');
+ await ui.capture('content-changed');
+ return;
+ }
+ if (ui.case !== 'reused') {
+ await page.getByRole('button', { name: await ui.t('sharing.uploadLocal') }).waitFor();
+ await ui.capture('upload-confirmation');
+ await page.getByRole('button', { name: await ui.t('sharing.uploadLocal') }).click();
+ }
+ await page.getByRole('button', { name: await ui.t('sharing.copyLink') }).waitFor();
+ if (await page.getByRole('button', { name: await ui.t('sharing.uploadLocal') }).count()) throw new Error('Repeated upload confirmation');
+ await page.waitForFunction(() => [...document.querySelectorAll('button')].some(button => button.textContent && !button.disabled && button.querySelector('svg.lucide-copy')));
+ await ui.capture('share-material');
+ },
+};
diff --git a/apps/desktop/src/main/__tests__/deepLink.test.ts b/apps/desktop/src/main/__tests__/deepLink.test.ts
index 3ff7526052..333fe61822 100644
--- a/apps/desktop/src/main/__tests__/deepLink.test.ts
+++ b/apps/desktop/src/main/__tests__/deepLink.test.ts
@@ -733,3 +733,22 @@ describe('public plugin links are navigation only', () => {
expect(parseDeepLink('cindy://plugin/cindy-github')).toBeNull();
});
});
+
+// A local share is a fixed package, never a market ID or an automatic install.
+// Unit: the real parser and pending handoff need no server or real Electron app.
+describe('fixed local plugin share navigation', () => {
+ const snapshotId = 'a'.repeat(32);
+ it('keeps the exact snapshot through the loaded login page', () => {
+ const window = { isDestroyed: () => false, isVisible: () => true, isMinimized: () => false, show: vi.fn(), focus: vi.fn(),
+ restore: vi.fn(), moveTop: vi.fn(), setAlwaysOnTop: vi.fn(),
+ webContents: { isLoading: () => false, send: vi.fn() } } as unknown as BrowserWindow;
+ setDeepLinkMainWindow(window);
+ handleIncomingDeepLink(`cindy://plugin-share/${snapshotId}`, 'open-url');
+ expect(takePendingDeepLink()).toEqual({ type: 'local-plugin-share', snapshotId });
+ expect(takePendingDeepLink()).toBeNull();
+ setDeepLinkMainWindow(null);
+ });
+ it.each(['?install=1', '?url=https://example.test/file', '#auto', '/other', '/../other'])('rejects extra behavior %s', suffix => {
+ expect(parseDeepLink(`cindy://plugin-share/${snapshotId}${suffix}`)).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index cfc0250f07..27791a31d4 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1156,6 +1156,7 @@ import { getGhostSetupChangeBus } from './cindy-brain/ghostSetupChangeBus.js';
import { getGhostSetupInteractionBridge } from './cindy-brain/ghostSetupInteractionBridge.js';
import { registerPluginMarketIpc, syncDefaultMarketPlugins, refreshForegroundMarketPlugins } from './plugin-market/registerIpc.js';
import { getPluginMarketService } from './plugin-market/service.js';
+import { installLocalPluginShare } from './plugin-market/localSharing.js';
import { StableOwnerPostCommitStep } from './stableOwnerPostCommit.js';
import { registerPluginContributionsIpc } from './plugin-contributions/registerIpc.js';
import { registerPluginPublisherIpc } from './plugin-publisher/registerIpc.js';
@@ -2546,6 +2547,9 @@ setCodexImageAuthBinding({
configureMailAttachmentHost({ writeTempFile, materializeDirectSendOssAttachments });
setRemotePluginManagementServices({
isRelayOnline: () => getDeviceLinkStatus() === 'online',
+ installShare: async (snapshot, prompt, assertScope) => {
+ await installLocalPluginShare(snapshot.snapshotId, snapshot, prompt, assertScope);
+ },
listProjects: listRecentWorkdirs,
sidebar: {
read: id => !loadSidebarSettingsSnapshot().hiddenMainViewGhostIds.includes(id),
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/exportGhostPackage.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/exportGhostPackage.test.ts
index b497442eff..a5daa9fe50 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/exportGhostPackage.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/exportGhostPackage.test.ts
@@ -7,9 +7,9 @@ import JSZip from 'jszip';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { InstalledGhost } from '../../../shared/ghost';
-import { exportGhostPackage, snapshotInstalledGhostPackage, sanitizeExportFileNamePart } from '../exportGhostPackage';
+import { exportGhostPackage, inspectInstalledGhostPackageContent, snapshotInstalledGhostPackage, sanitizeExportFileNamePart } from '../exportGhostPackage';
import { MAX_BASIC_ZIP_ENTRIES } from '../GhostManager';
-import { signGhostPackage } from '../ghostSignature';
+import { signGhostPackage, verifyGhostZipSignatures } from '../ghostSignature';
/** 测试用发布者密钥对(每次进程一对,签名/验签都走真实 ed25519)。 */
const { privateKey: publisherKey } = crypto.generateKeyPairSync('ed25519');
@@ -137,6 +137,84 @@ function makeDeps(overrides: Partial<Parameters<typeof exportGhostPackage>[1]> =
}
describe('snapshotInstalledGhostPackage', () => {
+ // OSS reuse requires equal bytes, not only equal manifests. Existing export
+ // tests never compare two snapshots across time/entry order. Unit tier: real
+ // tiny directory, ZIP and signatures; Date is fake and no timers are awaited.
+ it.each([false, true])('reproduces unchanged package bytes across time and enumeration order (signed=%s)', async signed => {
+ await fs.promises.mkdir(path.join(ghostDir, 'templates', 'empty'), { recursive: true });
+ await fs.promises.mkdir(path.join(ghostDir, 'another-empty'));
+ if (signed) await writeStatement(['ghost.json', 'locales/en.json', 'main.js']);
+ const realOpendir = fs.promises.opendir;
+ let reverse = false;
+ const spy = vi.spyOn(fs.promises, 'opendir').mockImplementation(async (p: fs.PathLike) => {
+ const entries: fs.Dirent[] = [];
+ for await (const entry of await realOpendir(p)) entries.push(entry);
+ if (reverse) entries.reverse();
+ return { async *[Symbol.asyncIterator]() { yield* entries; } } as fs.Dir;
+ });
+ vi.useFakeTimers({ toFake: ['Date'] });
+ const compression = vi.spyOn(JSZip.prototype, 'generateAsync');
+ try {
+ vi.setSystemTime(new Date('2026-10-28T00:00:00.000Z'));
+ const content = await inspectInstalledGhostPackageContent('hello', makeDeps());
+ expect(compression).not.toHaveBeenCalled();
+ compression.mockRestore();
+ const first = await snapshotInstalledGhostPackage('hello', makeDeps());
+ reverse = true;
+ vi.setSystemTime(new Date('2026-10-29T12:34:56.000Z'));
+ const second = await snapshotInstalledGhostPackage('hello', makeDeps());
+ if (first.status !== 'prepared' || second.status !== 'prepared') throw new Error('Expected package snapshots');
+ expect(second.bytes).toEqual(first.bytes);
+ expect(content).toMatchObject({ status: 'prepared', contentSha256: first.shareContentSha256 });
+ expect(second.shareContentSha256).toBe(first.shareContentSha256);
+ const zip = await JSZip.loadAsync(second.bytes);
+ expect(zip.files['templates/empty/']?.dir).toBe(true);
+ expect(await verifyGhostZipSignatures(zip, '', makeGhost().manifest)).toMatchObject({ ok: true });
+ if (signed) expect(await zip.file('cindy-signatures.json')!.async('string'))
+ .toBe(await fs.promises.readFile(path.join(ghostDir, 'cindy-signatures.json'), 'utf8'));
+ } finally {
+ compression.mockRestore();
+ spy.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+
+ // Regression: checking whether a 255 MB local package was uploaded used to
+ // compress it first. This unit entry checks real tiny files without ZIP work;
+ // existing archive tests cannot protect preflight identity or no compression.
+ it.each(['source', 'icon', 'manifest', 'empty-directory'])('changes the uncompressed content identity for same-version %s changes', async change => {
+ await fs.promises.writeFile(path.join(ghostDir, 'icon.png'), 'first');
+ const first = await inspectInstalledGhostPackageContent('hello', makeDeps());
+ if (first.status !== 'prepared') throw new Error('Expected content snapshot');
+ await fs.promises.writeFile(path.join(ghostDir, '.cindy-trust.json'), '{"host":"changed"}');
+ expect(await inspectInstalledGhostPackageContent('hello', makeDeps())).toMatchObject({ contentSha256: first.contentSha256 });
+ if (change === 'empty-directory') await fs.promises.mkdir(path.join(ghostDir, 'empty'));
+ else if (change === 'manifest') await fs.promises.appendFile(path.join(ghostDir, 'ghost.json'), '\n');
+ else await fs.promises.writeFile(path.join(ghostDir, change === 'icon' ? 'icon.png' : 'main.js'), 'changed');
+ const second = await inspectInstalledGhostPackageContent('hello', makeDeps());
+ if (second.status !== 'prepared') throw new Error('Expected changed content snapshot');
+ expect(second.contentSha256).not.toBe(first.contentSha256);
+ });
+
+ it.skipIf(process.platform === 'win32')('changes the uncompressed identity when archive permissions change', async () => {
+ await fs.promises.chmod(path.join(ghostDir, 'main.js'), 0o644);
+ const first = await inspectInstalledGhostPackageContent('hello', makeDeps());
+ await fs.promises.chmod(path.join(ghostDir, 'main.js'), 0o755);
+ const second = await inspectInstalledGhostPackageContent('hello', makeDeps());
+ if (first.status !== 'prepared' || second.status !== 'prepared') throw new Error('Expected content snapshots');
+ expect(second.contentSha256).not.toBe(first.contentSha256);
+ });
+
+ it('changes package bytes when same-version source content changes', async () => {
+ const first = await snapshotInstalledGhostPackage('hello', makeDeps());
+ await fs.promises.writeFile(path.join(ghostDir, 'main.js'), 'console.log("ho")');
+ const second = await snapshotInstalledGhostPackage('hello', makeDeps());
+ if (first.status !== 'prepared' || second.status !== 'prepared') throw new Error('Expected package snapshots');
+ expect(second.bytes).not.toEqual(first.bytes);
+ const zip = await JSZip.loadAsync(second.bytes);
+ expect(await zip.file('main.js')!.async('string')).toBe('console.log("ho")');
+ });
+
it('pins bytes of the exact root instance without opening a picker or saving a file', async () => {
const root = { ...makeGhost(), namespace: null, namespaceState: 'confirmed' as const };
const otherDir = path.join(workDir, 'other-owner');
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalInstallIdentity.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalInstallIdentity.test.ts
index 920cd2ba42..d07ac759e2 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalInstallIdentity.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostLocalInstallIdentity.test.ts
@@ -1,10 +1,18 @@
import { describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { createHash } from 'node:crypto';
import type { InstalledGhost } from '../../../shared/ghost.js';
import type { GhostInstallConsentRequest } from '../../../shared/ghostInstallConsent.js';
import { findInstalledGhostForDeliveryTarget, installedGhostStoragePart } from '../../../shared/pluginIdentity.js';
import { assertGhostInstallConsent, confirmedTaskCapability, obtainGhostInstallConsent } from '../ghostInstallConsent.js';
import { ghostInstallApprovalToken } from '../../../shared/ghost.js';
import { createGhostProductionCallbacks } from './ghostProductionCallbacksFixture.js';
+import { GhostManager } from '../GhostManager.js';
+import { effectiveInstallOrigin } from '../ghostInstallReceipt.js';
+import { runGhostSnapshotWorkerRequest } from '../ghostSnapshotWorkerProcess.js';
+import { writeTestCindyPackage } from './cindyPackageFixture.js';
const createCallbacks = createGhostProductionCallbacks<{
install: (event: unknown, file: string, options: unknown) => Promise<{ ghost: InstalledGhost }>;
@@ -105,3 +113,83 @@ it.each(['choose', 'update', 'copy', 'cancel', 'changed'] as const)('Forge insta
expect(install).not.toHaveBeenCalled();
}
});
+
+// Test value: the shared-package entry must bind real bytes and reuse manual
+// root install/update consent. Existing file/Forge entries do not accept a fixed
+// shared version. Unit tier; production callback, no filesystem or network I/O.
+const sharedPackageCallbacks = createGhostProductionCallbacks<{
+ installLocalPluginSharePackage: (file: string, options: Record<string, unknown>) => Promise<InstalledGhost>;
+}>({ functions: ['installLocalPluginSharePackage'] });
+
+it.each(['new', 'update', 'cancel', 'different-bytes', 'owner-changed'] as const)('shared local package consent: %s', async mode => {
+ const manifest: InstalledGhost['manifest'] = { schemaVersion: 3, minCindyVersion: '99.0.0', id: 'helper', name: 'Helper', version: '1.0.0', kind: 'chip', entry: 'main.js' };
+ const root: InstalledGhost = { manifest, namespace: null, instanceKey: '_root__helper', dir: '/plugins/_root/helper', enabled: true,
+ approval: { state: 'approved', revision: '11111111-1111-4111-8111-111111111111' } };
+ const digest = 'a'.repeat(64);
+ let current = true;
+ const prompt = vi.fn<(request: Omit<GhostInstallConsentRequest, 'requestId'>) => Promise<boolean>>(async () => mode !== 'cancel');
+ const install = vi.fn<(...args: unknown[]) => Promise<InstalledGhost>>(async () => root),
+ update = vi.fn<(...args: unknown[]) => Promise<InstalledGhost>>(async () => root), release = vi.fn();
+ const entry = sharedPackageCallbacks({
+ getGhostManager: () => ({ list: () => mode === 'update' ? [root] : [],
+ inspect: async () => { if (mode === 'owner-changed') current = false;
+ return { manifest, canonicalManifest: manifest, packageSha256: mode === 'different-bytes' ? 'b'.repeat(64) : digest }; } }),
+ captureGhostMutationOwner: () => 'owner', beginGhostMutation: () => release,
+ rejectReservedGhostId() {}, rejectBrokerWithoutDeclaredRedirectPort() {}, rejectUnauthorizedTokenBroker() {},
+ throwInstallError: () => { throw new Error('invalid package'); },
+ throwIpcError: (code: string) => { throw new Error(code); },
+ findInstalledGhostForDeliveryTarget, ghostInstallApprovalToken, installedGhostStoragePart,
+ readLocalGhostUpdateSource: () => ({ sourceChanged: true, authorizationOverrides: {} }),
+ obtainGhostInstallConsent, withGhostInstallLock: async (_id: string, run: () => unknown) => run(),
+ installAndDock: install, updateLocalGhostPackageLocked: update,
+ }).installLocalPluginSharePackage;
+ const result = entry('/tmp/shared.cindy', { ghostId: 'helper', version: '1.0.0', sha256: digest, prompt,
+ assertCurrent() { if (!current) throw new Error('OWNER_CHANGED'); } });
+ if (mode === 'cancel' || mode === 'different-bytes' || mode === 'owner-changed') {
+ await expect(result).rejects.toThrow();
+ expect(install).not.toHaveBeenCalled(); expect(update).not.toHaveBeenCalled();
+ if (mode === 'owner-changed') expect(prompt).not.toHaveBeenCalled();
+ } else {
+ await expect(result).resolves.toBe(root);
+ expect(release).toHaveBeenCalledOnce();
+ if (mode === 'update') {
+ expect(install).not.toHaveBeenCalled();
+ expect(update.mock.calls[0]?.[5]).toBe('_root__helper');
+ expect(prompt.mock.calls[0]?.[0]).toMatchObject({ target: { namespace: null, sourceChanged: true } });
+ } else {
+ expect(install.mock.calls[0]?.[2]).toMatchObject({ namespace: null, enable: true, registrySource: 'manual', expectedPackageSha256: digest });
+ }
+ }
+});
+
+// Same production entry with real archive inspection, placement and receipt.
+// This distinguishes a returned UI object from an actually committed manual install.
+it('commits a shared archive with its exact digest as an approved manual installation', async () => {
+ const directory = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-share-install-')));
+ try {
+ const file = await writeTestCindyPackage(path.join(directory, 'shared.cindy'), {
+ schemaVersion: 3, minCindyVersion: '99.0.0', id: 'shared-example', name: 'Shared Example', version: '1.0.0', entry: 'main.js',
+ });
+ const sha256 = createHash('sha256').update(await fs.readFile(file)).digest('hex');
+ const manager = new GhostManager({ getRootDir: () => path.join(directory, 'plugins'),
+ mutateSnapshot: async ({ parentDir, ...request }) => runGhostSnapshotWorkerRequest(request, parentDir) });
+ const factory = createGhostProductionCallbacks<{
+ installLocalPluginSharePackage: (file: string, options: Record<string, unknown>) => Promise<InstalledGhost>;
+ }>({ functions: ['installLocalPluginSharePackage', 'installAndDock', 'installAndDockLocked'] });
+ const install = factory({ getGhostManager: () => manager, captureGhostMutationOwner: () => 'owner', beginGhostMutation: () => () => {},
+ findInstalledGhostForDeliveryTarget, obtainGhostInstallConsent, assertGhostInstallConsent, confirmedTaskCapability,
+ withGhostInstallLock: async (_id: string, run: () => unknown) => run(),
+ rejectReservedGhostId() {}, rejectBrokerWithoutDeclaredRedirectPort() {}, rejectUnauthorizedTokenBroker() {},
+ throwInstallError: (value: { reason: string }) => { throw new Error(value.reason); },
+ throwIpcError: (code: string) => { throw new Error(code); },
+ recordGhostAdded() {}, installedGhostStoragePart, spawnIfResident() {}, bindPluginUsage: async () => {}, log: { warn() {} },
+ }).installLocalPluginSharePackage;
+ const installed = await install(file, { ghostId: 'shared-example', version: '1.0.0', sha256, prompt: async () => true, assertCurrent() {} });
+ expect(installed.approval.state).toBe('approved');
+ expect(installed.enabled).toBe(true);
+ const receipt = manager.readApprovedInstallReceipt(installedGhostStoragePart(installed));
+ expect(receipt?.packageSha256).toBe(sha256);
+ expect(effectiveInstallOrigin(receipt!)).toBe('manual');
+ expect(await fs.readFile(path.join(installed.dir, 'main.js'), 'utf8')).toBe('// ok\n');
+ } finally { await fs.rm(directory, { recursive: true, force: true }); }
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginManagement.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginManagement.test.ts
index 27269fbb70..4d8035ffc9 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/remotePluginManagement.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/remotePluginManagement.test.ts
@@ -740,3 +740,61 @@ describe('remote plugin management receipt boundaries', () => {
expect((await f.invoke('operation', { operationId: 'pending' })).phase).toBe('cancelled');
});
});
+
+// Fixed share installs reuse Host receipts and consent. Unit tier: fake I/O and
+// virtual timers. Exact bytes and peer cancellation are the contract under test.
+describe('remote local share installation', () => {
+ const snapshot = { schemaVersion: 1 as const, snapshotId: 'a'.repeat(32), ghostId: 'shared', name: 'Shared',
+ version: '1.0.0', sha256: 'a'.repeat(64), sizeBytes: 123, description: null, author: null,
+ icon: null, createdAt: '2026-10-28T00:00:00.000Z' };
+ const input = { operationId: 'share-operation', kind: 'install-share', expectedSnapshot: snapshot };
+ it('advertises support only when the target installer exists', async () => {
+ const f = fixture();
+ expect(await f.invoke('snapshot', {})).not.toHaveProperty('localShares');
+ f.deps.installShare = vi.fn();
+ expect(await f.invoke('snapshot', {})).toHaveProperty('localShares', true);
+ });
+ it('installs the clicked fixed package after original consent and replays only its receipt', async () => {
+ const f = fixture();
+ const placed: string[] = [];
+ f.deps.installShare = vi.fn(async (expected, prompt, current) => {
+ if (!await prompt({ initiator: 'user', origin: 'local-file', facts: {
+ kind: 'install', name: expected.name, version: expected.version, permissions: [],
+ } })) throw { code: 'MUTATION_CANCELLED' };
+ current(); placed.push(expected.sha256);
+ });
+ await f.invoke('begin', input);
+ const receipt = await f.invoke('operation', { operationId: input.operationId });
+ expect(receipt.phase).toBe('confirmation');
+ expect(placed).toEqual([]);
+ await f.invoke('answer', { operationId: input.operationId, requestId: receipt.consent!.requestId, confirmed: true });
+ await flush();
+ expect((await f.invoke('begin', input)).phase).toBe('succeeded');
+ expect(placed).toEqual([snapshot.sha256]);
+ expect(f.deps.installShare).toHaveBeenCalledOnce();
+ await expect(f.invoke('begin', { ...input, expectedSnapshot: { ...snapshot, sha256: 'b'.repeat(64) } }))
+ .rejects.toMatchObject({ code: 'NOT_FOUND' });
+ });
+ it.each(['cancel', 'revoke', 'owner'] as const)('fences %s before the target places the package', async action => {
+ const f = fixture();
+ let resume!: () => void;
+ const placed: string[] = [];
+ f.deps.installShare = vi.fn(async (expected, _prompt, current) => {
+ await new Promise<void>(resolve => { resume = resolve; });
+ current(); placed.push(expected.sha256);
+ });
+ await f.invoke('begin', input);
+ if (action === 'cancel') await f.invoke('cancel', { operationId: input.operationId });
+ else if (action === 'revoke') f.revoke('desktop-a');
+ else f.switchOwner();
+ resume(); await flush();
+ expect(placed).toEqual([]);
+ });
+ it('rejects a URL or a malformed package binding before starting a target install', async () => {
+ const f = fixture();
+ f.deps.installShare = vi.fn();
+ await expect(f.invoke('begin', { ...input, url: 'https://other.test/package' })).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ await expect(f.invoke('begin', { ...input, expectedSnapshot: { ...snapshot, sha256: 'bad' } })).rejects.toMatchObject({ code: 'INVALID_PARAMS' });
+ expect(f.deps.installShare).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts b/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts
index 97cbabe429..c2e71fdeba 100644
--- a/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts
+++ b/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts
@@ -37,6 +37,7 @@ import fs from 'node:fs';
import path from 'node:path';
import JSZip from 'jszip';
+import { encodeLocalPluginShareContent } from '@cindy/plugin-protocol';
import { type InstalledGhost } from '../../shared/ghost.js';
import { findInstalledGhostByInstanceId, isGhostInstanceId } from '../../shared/pluginIdentity.js';
@@ -527,11 +528,11 @@ async function snapshotPackage(
return null;
}
-export async function snapshotInstalledGhostPackage(
+async function readInstalledGhostContent(
id: unknown,
deps: Pick<ExportGhostPackageDeps, 'listInstalled'>,
): Promise<
- | { status: 'prepared'; bytes: Buffer; ghost: InstalledGhost; contentSha256: string }
+ | { status: 'prepared'; ghost: InstalledGhost; snapshot: PackageSnapshot; maxEntries: number; maxArchive: number }
| Exclude<ExportGhostPackageResult, { status: 'saved' } | { status: 'canceled' }>
> {
if (typeof id !== 'string' || !isGhostInstanceId(id)) {
@@ -560,16 +561,47 @@ export async function snapshotInstalledGhostPackage(
const snapshot = await snapshotPackage(ghost.dir, limits);
if (snapshot === 'too_large') return { status: 'error', code: 'too_large' };
if (!snapshot) return { status: 'error', code: 'read_failed' };
+ return { status: 'prepared', ghost, snapshot, maxEntries: limits.maxEntries, maxArchive };
+}
+
+function contentDigest(snapshot: PackageSnapshot): string {
+ return crypto.createHash('sha256').update(encodeLocalPluginShareContent(snapshot.entries.map(file => ({
+ path: file.rel, sha256: sha256hex(file.data), unixPermissions: file.unixPermissions,
+ })), snapshot.emptyDirs)).digest('hex');
+}
+
+/** Read the same bounded, consistent package content without compressing it. */
+export async function inspectInstalledGhostPackageContent(
+ id: unknown,
+ deps: Pick<ExportGhostPackageDeps, 'listInstalled'>,
+) {
+ const content = await readInstalledGhostContent(id, deps);
+ if (content.status !== 'prepared') return content;
+ return { status: 'prepared' as const, ghost: content.ghost, contentSha256: contentDigest(content.snapshot) };
+}
+
+export async function snapshotInstalledGhostPackage(
+ id: unknown,
+ deps: Pick<ExportGhostPackageDeps, 'listInstalled'>,
+) {
+ const content = await readInstalledGhostContent(id, deps);
+ if (content.status !== 'prepared') return content;
+ const { ghost, snapshot, maxEntries, maxArchive } = content;
const zip = new JSZip();
- for (const rel of snapshot.emptyDirs) {
+ // Equal installed content must produce equal bytes for local-share OSS reuse.
+ // Use code-unit order so archive identity does not depend on host locale.
+ for (const rel of snapshot.emptyDirs.slice().sort()) {
zip.folder(rel);
}
- for (const file of snapshot.entries) {
+ for (const file of snapshot.entries.slice().sort((a, b) => a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0)) {
zip.file(file.rel, file.data, { unixPermissions: file.unixPermissions });
}
- if (Object.keys(zip.files).length > limits.maxEntries) {
- return { status: 'error', code: 'too_large' };
+ // Include automatically created parent folders; timestamps are not package content.
+ const archiveDate = new Date('1980-01-01T00:00:00.000Z');
+ zip.forEach((_rel, entry) => { entry.date = archiveDate; });
+ if (Object.keys(zip.files).length > maxEntries) {
+ return { status: 'error' as const, code: 'too_large' as const };
}
let buf: Buffer;
try {
@@ -580,17 +612,16 @@ export async function snapshotInstalledGhostPackage(
});
} catch {
// 压缩失败(zlib 等)如实落到结构化结果,不冒成未捕获的 IPC 异常。
- return { status: 'error', code: 'compress_failed' };
+ return { status: 'error' as const, code: 'compress_failed' as const };
}
- if (buf.byteLength > maxArchive) return { status: 'error', code: 'too_large' };
-
+ if (buf.byteLength > maxArchive) return { status: 'error' as const, code: 'too_large' as const };
+ // Contribution recovery persists this older digest; preserve its framing.
const contentEntries = snapshot.entries.map(file => [
- file.rel, file.unixPermissions, crypto.createHash('sha256').update(file.data).digest('hex'),
+ file.rel, file.unixPermissions, sha256hex(file.data),
]).sort((a, b) => String(a[0]).localeCompare(String(b[0])));
const contentSha256 = crypto.createHash('sha256')
- .update(JSON.stringify([snapshot.emptyDirs.slice().sort(), contentEntries]))
- .digest('hex');
- return { status: 'prepared', bytes: buf, ghost, contentSha256 };
+ .update(JSON.stringify([snapshot.emptyDirs.slice().sort(), contentEntries])).digest('hex');
+ return { status: 'prepared' as const, bytes: buf, ghost, contentSha256, shareContentSha256: contentDigest(snapshot) };
}
export async function exportGhostPackage(
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 7485b33d02..f24891180d 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -35,6 +35,7 @@ export const remotePluginSettings = {
interface RemotePluginManagementServices {
isRelayOnline(): boolean;
market: RemotePluginManagementDeps['market'];
+ installShare: NonNullable<RemotePluginManagementDeps['installShare']>;
listProjects(): Promise<Array<{ path: string; exists: boolean }>>;
sidebar: { read(id: string): boolean; write(id: string, visible: boolean, assertCurrent: () => void): Promise<void> };
}
@@ -8035,6 +8036,42 @@ async function setGhostEnabledForUser(id: string, enabled: boolean, expectedInst
}
}
+/** A fixed local share uses the same root/manual consent and durable install/update transactions. */
+export async function installLocalPluginSharePackage(file: string, options: {
+ ghostId: string; version: string; sha256: string;
+ prompt: GhostInstallConsentPrompt; assertCurrent: () => void;
+}): Promise<InstalledGhost> {
+ const owner = captureGhostMutationOwner();
+ options.assertCurrent();
+ const manager = getGhostManager();
+ const inspected = await manager.inspect(file);
+ options.assertCurrent();
+ if ('rejection' in inspected) throwInstallError(inspected.rejection);
+ if (inspected.packageSha256 !== options.sha256 || inspected.canonicalManifest.id !== options.ghostId ||
+ inspected.canonicalManifest.version !== options.version)
+ throwIpcError('GHOST_FILE_INVALID', 'The downloaded package does not match this share');
+ rejectReservedGhostId(inspected.manifest.id);
+ rejectBrokerWithoutDeclaredRedirectPort(inspected.manifest);
+ const existing = findInstalledGhostForDeliveryTarget(manager.list(), { ghostId: inspected.manifest.id, namespace: null });
+ const updateSource = existing ? readLocalGhostUpdateSource(manager, existing, inspected) : undefined;
+ rejectUnauthorizedTokenBroker(inspected.canonicalManifest, updateSource?.authorizationOverrides);
+ const approval = existing ? ghostInstallApprovalToken(existing.approval) : undefined;
+ const consent = await obtainGhostInstallConsent({ mode: 'prompt', prompt: options.prompt, initiator: 'user', origin: 'local-file',
+ force: updateSource?.sourceChanged,
+ target: ghostInstallTargetContext(manager.list(), inspected.manifest.id, null, existing, updateSource?.sourceChanged === true) },
+ existing, inspected.manifest, inspected.packageSha256);
+ options.assertCurrent();
+ const release = beginGhostMutation(owner);
+ try {
+ if (existing) return await withGhostInstallLock(inspected.manifest.id, () => updateLocalGhostPackageLocked(
+ manager, file, inspected, options.sha256, approval!, installedGhostStoragePart(existing), consent, undefined,
+ () => { options.assertCurrent(); return true; }, updateSource?.sourceChanged));
+ return await installAndDock(manager, file, { ghostId: inspected.manifest.id, namespace: null, enable: true,
+ registrySource: 'manual', expectedPackageSha256: options.sha256,
+ consent: { decision: consent, manifest: inspected.manifest }, beforePackagePlacement: options.assertCurrent });
+ } finally { release(); }
+}
+
/** 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> {
@@ -8193,6 +8230,7 @@ export function registerGhostIpc(): void {
setEnabled: async (id, enabled, approval, assertCurrent) => { await setGhostEnabledForUser(id, enabled, approval, assertCurrent); },
uninstall: async (id, _approval, assertCurrent) => { assertCurrent(); await uninstallGhostAndCleanup(id, { assertCurrent }); },
installFile: installRemoteGhostFile,
+ installShare: (snapshot, prompt, assertScope) => requireRemotePluginManagementServices().installShare(snapshot, prompt, assertScope),
});
mobilePluginPages = new MobilePluginPages({
management: remotePluginManagement,
diff --git a/apps/desktop/src/main/cindy-brain/remotePluginManagement.ts b/apps/desktop/src/main/cindy-brain/remotePluginManagement.ts
index d6a9242206..e4c9328884 100644
--- a/apps/desktop/src/main/cindy-brain/remotePluginManagement.ts
+++ b/apps/desktop/src/main/cindy-brain/remotePluginManagement.ts
@@ -1,6 +1,7 @@
import { extractIpcError } from '../../shared/ipcError.js';
import { createHash, randomUUID } from 'node:crypto';
import type { RemoteActionInvokeRequest, RemoteActionInvokeResponse } from '@cindy/device-link';
+import { parseLocalPluginShareSnapshot, type LocalPluginShareSnapshot } from '@cindy/plugin-protocol';
import {
isGhostInstallApprovalToken,
ghostInstallApprovalToken,
@@ -67,6 +68,11 @@ export interface RemotePluginManagementDeps {
assertCurrent: () => void,
): Promise<void>;
uninstall(id: string, approval: string, assertCurrent: () => void): Promise<void>;
+ installShare?(
+ snapshot: LocalPluginShareSnapshot,
+ prompt: GhostInstallConsentPrompt,
+ assertScope: () => void,
+ ): Promise<void>;
installFile?(
peer: string,
attachment: string,
@@ -196,6 +202,7 @@ export class RemotePluginManagement {
market,
...(this.deps.preferences ? { hostPreferences: true } : {}),
...(this.deps.settingsPage ? { settingsPage: true } : {}),
+ ...(this.deps.installShare ? { localShares: true } : {}),
...(scopeProjects ? { projects: scopeProjects.map(({ id, name, path }) => ({ id, name, ...(path ? { path } : {}) })) } : {}),
...(this.deps.projects?.resolve ? { projectBrowse: true } : {}),
});
@@ -304,6 +311,7 @@ export class RemotePluginManagement {
'expectedReleaseId',
'expectedInstalledApproval',
'expectedManifest',
+ 'expectedSnapshot',
'attachment',
'projectId',
'expectedProjectRevision',
@@ -313,7 +321,7 @@ export class RemotePluginManagement {
return invalid();
const id = str(input.operationId, 128);
const kind = str(input.kind, 32);
- if (!['install', 'enable', 'disable', 'uninstall', 'install-file'].includes(kind))
+ if (!['install', 'enable', 'disable', 'uninstall', 'install-file', 'install-share'].includes(kind))
return invalid();
const projectId = input.projectId === undefined ? undefined : str(input.projectId);
const projectRevision =
@@ -325,6 +333,13 @@ export class RemotePluginManagement {
)
return invalid();
const target = request.resourceRef?.id;
+ let sharedSnapshot: LocalPluginShareSnapshot | undefined;
+ if (kind === 'install-share') {
+ if (!this.deps.installShare || target || Object.keys(input).some(key =>
+ !['operationId', 'kind', 'expectedSnapshot'].includes(key))) return invalid();
+ try { sharedSnapshot = parseLocalPluginShareSnapshot(input.expectedSnapshot); }
+ catch { return invalid(); }
+ } else if (input.expectedSnapshot !== undefined) return invalid();
const fingerprint = JSON.stringify([target ?? null, input]);
const previous = this.operations.get(id);
if (previous) {
@@ -340,7 +355,7 @@ export class RemotePluginManagement {
if (target) {
ghost = this.find(target);
if (installedApproval !== ghostInstallApprovalToken(ghost.approval)) return unavailable();
- } else if (!['install', 'install-file'].includes(kind)) return invalid();
+ } else if (!['install', 'install-file', 'install-share'].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'))
@@ -396,6 +411,9 @@ export class RemotePluginManagement {
try {
assertCurrent();
switch (kind) {
+ case 'install-share':
+ await this.deps.installShare!(sharedSnapshot!, prompt, () => this.assertScope(op));
+ break;
case 'install':
await this.deps.market.install(
pluginId!,
diff --git a/apps/desktop/src/main/deepLink.ts b/apps/desktop/src/main/deepLink.ts
index b99b291379..1dc61dddca 100644
--- a/apps/desktop/src/main/deepLink.ts
+++ b/apps/desktop/src/main/deepLink.ts
@@ -41,7 +41,7 @@
* 发布前仍需用 packaged build 做最终跨平台验证。
*/
-import { isValidPluginResourceId } from '@cindy/plugin-protocol';
+import { isLocalPluginSnapshotId, isValidPluginResourceId } from '@cindy/plugin-protocol';
import { app, BrowserWindow, type IpcMainInvokeEvent } from 'electron';
import path from 'node:path';
import { parseProviderShareInvitationIntent, parseSharedTaskInvitationIntent } from '@cindy/device-link';
@@ -76,6 +76,7 @@ export type DeepLinkPayload =
/** 供应商分享链接:原样交给 Renderer 的申请弹窗,由主进程命令再解析与核对区域。 */
| { type: 'provider-share-join'; link: string }
| { type: 'plugin'; pluginId: string }
+ | { type: 'local-plugin-share'; snapshotId: string }
/**
* islandEntryId 只由主进程的灵动岛点击写入(URL 解析从不产生它),标识这一次点击,
* 供 renderer 在导航落地后申请处置被点的那张卡。
@@ -121,6 +122,10 @@ export function parseDeepLink(url: string): DeepLinkPayload | null {
const invitation = parseSharedTaskInvitationIntent(url);
if (invitation) return { type: 'shared-task-join', ...invitation };
if (parseProviderShareInvitationIntent(url)) return { type: 'provider-share-join', link: url };
+ if (/^(?:cindy|xdt-maker):\/\/plugin-share(?:[/?#]|$)/i.test(url)) {
+ const match = /^(?:cindy|xdt-maker):\/\/plugin-share\/([A-Za-z0-9_-]{32})$/.exec(url);
+ return match && isLocalPluginSnapshotId(match[1]) ? { type: 'local-plugin-share', snapshotId: match[1] } : null;
+ }
if (/^(?:cindy|xdt-maker):\/\/plugin(?:[/?#]|$)/i.test(url)) {
const match = /^(?:cindy|xdt-maker):\/\/plugin\/(c[a-z0-9]{24})$/.exec(url);
return match && isValidPluginResourceId(match[1]) ? { type: 'plugin', pluginId: match[1] } : null;
@@ -480,7 +485,7 @@ export function sendMainWindowMessage(channel: string, payload: unknown): boolea
function safeDeepLinkLog(payload: DeepLinkPayload) {
// 口令不进日志。
- return payload.type === 'chat-invite' || payload.type === 'shared-task-join' || payload.type === 'provider-share-join' ? { type: payload.type } : payload;
+ return payload.type === 'chat-invite' || payload.type === 'shared-task-join' || payload.type === 'provider-share-join' || payload.type === 'local-plugin-share' ? { type: payload.type } : payload;
}
function dispatchDeepLink(payload: DeepLinkPayload, shouldFocus = true, owner?: DataOwnerBroadcastScope): void {
@@ -502,7 +507,7 @@ function dispatchDeepLink(payload: DeepLinkPayload, shouldFocus = true, owner?:
}
// A loaded login/LocalDbGate page has no MainLayout listener yet. These intents stay
// in the existing pending slot until the authenticated consumer takes them.
- if (!windowReady || payload.type === 'provider-import' || payload.type === 'shared-task-join' || payload.type === 'provider-share-join' || payload.type === 'plugin') {
+ if (!windowReady || payload.type === 'provider-import' || payload.type === 'shared-task-join' || payload.type === 'provider-share-join' || payload.type === 'plugin' || payload.type === 'local-plugin-share') {
// 保留"用户最后意图"语义:同一次冷启动如果先后入站多条 (例如 argv 同时含
// deep link URL 和 --open-folder, 现实场景极罕见但 bootstrap 两条 scan 都
// 会触发),后到的覆盖前者。但 warn log 留下排查线索,事后能从日志识别这种
diff --git a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
index 652c2589e4..3f244e4b6b 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
@@ -39,7 +39,9 @@ describe('Plugin Market IPC error boundary', () => {
expect(body).toContain('isPluginMarketPassthroughErrorCode(error.code)');
expect(body).toContain("throwIpcError(error.code, 'Plugin market operation failed');");
expect(body).toContain("throwIpcError('INTERNAL', 'Plugin market operation failed');");
- expect(registerSource.match(/return invokePluginMarket\(/g)?.length).toBe(12);
+ // Fixed-snapshot detail and install use the same sanitized boundary as the
+ // existing twelve market operations; keep all fourteen entry points guarded.
+ expect(registerSource.match(/return invokePluginMarket\(/g)?.length).toBe(14);
});
it('validates local icon keys with the same reserved-prefix contract as the service', () => {
diff --git a/apps/desktop/src/main/plugin-market/__tests__/localSharing.test.ts b/apps/desktop/src/main/plugin-market/__tests__/localSharing.test.ts
new file mode 100644
index 0000000000..9842ebb021
--- /dev/null
+++ b/apps/desktop/src/main/plugin-market/__tests__/localSharing.test.ts
@@ -0,0 +1,356 @@
+// Test value: the local-share production coordinator must keep one immutable
+// package across upload/material retries and require the original signed-in owner.
+// Public sharing tests have no upload or owner-bound package session. Minimal
+// inputs are one local package, an ambiguous material failure and an owner switch.
+// Unit tier: native/filesystem/network boundaries are fake; no real waits or I/O.
+import { createHash } from 'node:crypto';
+import path from 'node:path';
+import os from 'node:os';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const io = vi.hoisted(() => ({
+ api: vi.fn(), put: vi.fn(), content: vi.fn(), snapshot: vi.fn(), inspect: vi.fn(), list: vi.fn(),
+ mkdir: vi.fn(), write: vi.fn(), open: vi.fn(), remove: vi.fn(),
+ auth: vi.fn(), refresh: vi.fn(), download: vi.fn(), install: vi.fn(),
+ missing: null as string | null,
+}));
+vi.mock('electron', () => ({ app: { getPath: () => os.tmpdir(), getVersion: () => '0.1.200', isPackaged: true } }));
+vi.mock('node:fs/promises', () => ({ default: { mkdtemp: io.mkdir, writeFile: io.write, open: io.open, rm: io.remove } }));
+vi.mock('../../authManager.js', () => ({ getAuthState: io.auth, getActiveAuthRealm: () => 'global', getAccessToken: () => 'owner-token', refresh: io.refresh }));
+vi.mock('../../appSessionState.js', () => ({ activeOwnerScopeKey: () => 'owner', isAppSessionBoundaryPending: () => false }));
+vi.mock('../../clientEndpointsService.js', () => ({ getBuildClientEndpoint: (name: string) => name === io.missing ? null : name === 'shareBaseUrl' ? 'https://share.example.test' : 'https://plugin.example.test' }));
+vi.mock('../../cindy-brain/index.js', () => ({ getGhostManager: () => ({ list: io.list, inspect: io.inspect }), installLocalPluginSharePackage: io.install }));
+vi.mock('../download.js', () => ({ downloadVerifiedPlugin: io.download }));
+vi.mock('../../cindy-brain/exportGhostPackage.js', () => ({ inspectInstalledGhostPackageContent: io.content, snapshotInstalledGhostPackage: io.snapshot }));
+vi.mock('../../plugin-publisher/putObject.js', () => ({ putLocalFile: io.put, PluginPublisherPutError: class extends Error {} }));
+vi.mock('../../serverApiClient.js', () => ({ serverApiFetch: io.api, ServerApiError: class extends Error {} }));
+vi.mock('../../textClipboard.js', () => ({ rememberIssuedClipboardText: vi.fn() }));
+vi.mock('../../lifecycle.js', () => ({ onQuit: vi.fn() }));
+vi.mock('../objectUrlPolicy.js', () => ({ pluginObjectUrlOptions: () => undefined }));
+
+import { prepareLocalPluginShare as prepareShare, releaseLocalPluginShare, readLocalPluginShare, installLocalPluginShare } from '../localSharing.js';
+import { ghostInstallApprovalToken } from '../../../shared/ghost.js';
+import type { ShareContent, ShareOptions } from '../../../shared/share.js';
+
+const operation = 'operation_00000001';
+const bytes = Buffer.from('frozen-local-package');
+const digest = createHash('sha256').update(bytes).digest('hex');
+const manifest = { schemaVersion: 3, id: 'local-example', name: 'Local Example', version: '1.0.0', entry: 'index.js' };
+const ghost = { manifest, dir: path.join(os.tmpdir(), 'virtual-local-plugin'), namespace: null, namespaceState: 'confirmed', approval: { state: 'approved' as const, revision: '00000000-0000-4000-8000-000000000001' }, builtin: false, publishingSource: { kind: 'local' } };
+const binding = { version: manifest.version, approvalToken: ghostInstallApprovalToken(ghost.approval) };
+const prepareLocalPluginShare = async (caller: number, instanceId: string, id: string, options: ShareOptions): Promise<ShareContent> => {
+ const result = await prepareShare(caller, instanceId, id, options, binding, true);
+ if ('confirmationRequired' in result) throw new Error('Unexpected upload confirmation');
+ return result;
+};
+let currentOwner = 1;
+let signedIn = true;
+let failMaterial = false;
+const assigned = new Map<string, string>();
+const details = (id: string) => ({ schemaVersion: 1, snapshotId: id, ghostId: manifest.id, name: manifest.name, description: null, author: null, version: manifest.version,
+ sha256: digest, contentSha256: digest, sizeBytes: bytes.length, createdAt: '2026-10-28T00:00:00.000Z', icon: null });
+
+beforeEach(() => {
+ vi.clearAllMocks(); assigned.clear(); currentOwner = 1; signedIn = true; failMaterial = false;
+ io.api.mockReset();
+ io.missing = null;
+ io.auth.mockImplementation(() => ({ ownerGeneration: currentOwner, isAuthenticated: signedIn, mode: 'cloud', user: signedIn ? { id: 'owner', membershipKind: 'personal' } : null }));
+ io.list.mockReturnValue([ghost]);
+ io.content.mockResolvedValue({ status: 'prepared', ghost, contentSha256: digest });
+ io.snapshot.mockResolvedValue({ status: 'prepared', bytes, ghost, contentSha256: digest, shareContentSha256: digest });
+ io.mkdir.mockResolvedValue(path.join(os.tmpdir(), 'virtual-local-share'));
+ io.write.mockResolvedValue(undefined); io.remove.mockResolvedValue(undefined);
+ io.open.mockResolvedValue({ close: vi.fn().mockResolvedValue(undefined) });
+ io.inspect.mockResolvedValue({ packageSha256: digest, canonicalManifest: manifest });
+ io.put.mockResolvedValue({ bytesSent: bytes.length });
+ io.download.mockResolvedValue(undefined); io.install.mockResolvedValue(ghost);
+ io.api.mockImplementation(async (url: string, options: { body: Record<string, unknown> }) => {
+ if (url === '/api/local-plugin-shares/check') return { status: 'upload_required', contentSha256: options.body.contentSha256 };
+ if (url === '/api/local-plugin-shares/uploads') {
+ const key = String(options.body.operationId);
+ if (!assigned.has(key)) assigned.set(key, String.fromCharCode(97 + assigned.size).repeat(32));
+ return { snapshotId: assigned.get(key), status: 'uploading', putUrl: 'https://object.example.test/upload',
+ headers: { 'Content-Type': 'application/octet-stream', 'x-oss-forbid-overwrite': 'true' }, expiresAt: new Date(Date.now() + 3600000).toISOString() };
+ }
+ if (url.startsWith('/api/local-plugin-shares/uploads/')) {
+ const id = url.split('/')[4]!;
+ return { snapshotId: id, status: 'ready', snapshot: details(id), expiresAt: new Date(Date.now() + 3600000).toISOString() };
+ }
+ if (url === '/api/shares') {
+ if (failMaterial) { failMaterial = false; throw new Error('Connection closed'); }
+ const id = String(options.body.reference);
+ return { schemaVersion: 1, kind: 'local-plugin', snapshot: details(id), includeAttribution: options.body.includeAttribution,
+ shareId: id, url: `https://share.example.test/s/${id}`, imageSvg: '<svg xmlns="http://www.w3.org/2000/svg"></svg>' };
+ }
+ throw new Error('Unexpected fixture route');
+ });
+});
+
+// Recipient reads/install must bind the clicked fixed snapshot. Public install
+// tests select market releases and cannot cover this independent manual source.
+describe('local share recipient', () => {
+ const snapshotId = 'z'.repeat(32);
+ const ticket = () => ({ ...details(snapshotId), url: 'https://object.example.test/fixed.cindy', expiresAt: new Date(Date.now() + 60_000).toISOString() });
+ it('requires login before reading a shared package', async () => {
+ signedIn = false;
+ await expect(readLocalPluginShare(snapshotId)).rejects.toThrow();
+ expect(io.api).not.toHaveBeenCalled();
+ });
+ it('reads only the requested snapshot and installs the exact bytes through manual consent', async () => {
+ io.api.mockResolvedValueOnce(details(snapshotId)).mockResolvedValueOnce(ticket());
+ const snapshot = await readLocalPluginShare(snapshotId);
+ expect(snapshot.version).toBe('1.0.0');
+ const prompt = vi.fn();
+ await expect(installLocalPluginShare(snapshotId, snapshot, prompt)).resolves.toBe(ghost);
+ expect(io.download.mock.calls[0]?.slice(0, 2)).toEqual(['https://object.example.test/fixed.cindy', { sha256: digest, sizeBytes: bytes.length }]);
+ expect(io.install.mock.calls[0]?.[1]).toMatchObject({ ghostId: manifest.id, version: '1.0.0', sha256: digest, prompt });
+ expect(io.remove).toHaveBeenCalled();
+ });
+ it('rejects a changed download ticket before downloading another version', async () => {
+ io.api.mockResolvedValue({ ...ticket(), version: '1.1.0' });
+ await expect(installLocalPluginShare(snapshotId, details(snapshotId), vi.fn())).rejects.toThrow();
+ expect(io.download).not.toHaveBeenCalled();
+ expect(io.install).not.toHaveBeenCalled();
+ });
+ it('does not install after the owner changes during download and cleans up failures', async () => {
+ io.api.mockResolvedValue(ticket());
+ io.download.mockImplementation(async () => { currentOwner++; });
+ await expect(installLocalPluginShare(snapshotId, details(snapshotId), vi.fn())).rejects.toThrow();
+ expect(io.install).not.toHaveBeenCalled();
+ expect(io.remove).toHaveBeenCalled();
+ });
+ it('stops before placement when the selected remote device request is cancelled during download', async () => {
+ io.api.mockResolvedValue(ticket());
+ let active = true;
+ io.download.mockImplementation(async () => { active = false; });
+ const assertScope = () => { if (!active) throw { code: 'MUTATION_CANCELLED' }; };
+ await expect(installLocalPluginShare(snapshotId, details(snapshotId), vi.fn(), assertScope))
+ .rejects.toMatchObject({ code: 'MUTATION_CANCELLED' });
+ expect(io.install).not.toHaveBeenCalled();
+ expect(io.remove).toHaveBeenCalled();
+ });
+ it('keeps the peer cancellation guard in the original installer transaction', async () => {
+ io.api.mockResolvedValue(ticket());
+ let active = true;
+ const assertScope = () => { if (!active) throw { code: 'MUTATION_CANCELLED' }; };
+ io.install.mockImplementation(async (_file, options) => {
+ active = false;
+ options.assertCurrent();
+ return ghost;
+ });
+ await expect(installLocalPluginShare(snapshotId, details(snapshotId), vi.fn(), assertScope))
+ .rejects.toMatchObject({ code: 'MUTATION_CANCELLED' });
+ });
+});
+
+afterEach(async () => {
+ await releaseLocalPluginShare(1, operation);
+ await releaseLocalPluginShare(1, 'operation_00000002');
+});
+
+describe('local plugin sharing coordinator', () => {
+ it('asks before a new upload, then reuses unchanged bytes without confirmation for a new share', async () => {
+ await expect(prepareShare(1, 'local-example', operation, { includeAttribution: false }, binding, false))
+ .resolves.toEqual({ confirmationRequired: true });
+ expect(io.put).not.toHaveBeenCalled();
+ expect(io.snapshot).not.toHaveBeenCalled();
+ expect(io.write).not.toHaveBeenCalled();
+ expect(io.api.mock.calls.some(([url]) => url === '/api/shares' || url.endsWith('/commit'))).toBe(false);
+ const first = await prepareLocalPluginShare(1, 'local-example', operation, { includeAttribution: false });
+ expect(io.put).toHaveBeenCalledOnce();
+ expect(io.snapshot).toHaveBeenCalledOnce();
+ const snapshotId = 'b'.repeat(32);
+ io.api.mockResolvedValueOnce({ status: 'ready', contentSha256: digest, snapshot: details(snapshotId) });
+ const second = await prepareShare(1, 'local-example', 'operation_00000002', { includeAttribution: false }, binding, false);
+ expect(second).not.toHaveProperty('confirmationRequired');
+ expect(second).toHaveProperty('url', `https://share.example.test/s/${snapshotId}`);
+ expect(second).not.toEqual(first);
+ expect(io.put).toHaveBeenCalledOnce();
+ expect(io.snapshot).toHaveBeenCalledOnce();
+ });
+
+ it('requires confirmation again when package bytes change without a version change', async () => {
+ await prepareLocalPluginShare(1, 'local-example', operation, { includeAttribution: false });
+ const changed = Buffer.from('changed-local-package');
+ const changedDigest = createHash('sha256').update(changed).digest('hex');
+ io.content.mockResolvedValue({ status: 'prepared', ghost, contentSha256: changedDigest });
+ io.snapshot.mockResolvedValue({ status: 'prepared', bytes: changed, ghost, contentSha256: changedDigest, shareContentSha256: changedDigest });
+ io.inspect.mockResolvedValue({ packageSha256: changedDigest, canonicalManifest: manifest });
+ await expect(prepareShare(1, 'local-example', 'operation_00000002', { includeAttribution: false }, binding, false))
+ .resolves.toEqual({ confirmationRequired: true });
+ expect(io.api.mock.calls.filter(([url]) => url === '/api/local-plugin-shares/check').at(-1)?.[1].body)
+ .toMatchObject({ contentSha256: changedDigest });
+ expect(io.api.mock.calls.filter(([url]) => url === '/api/local-plugin-shares/uploads')).toHaveLength(1);
+ expect(io.put).toHaveBeenCalledOnce();
+ });
+
+ it.each(['pluginApiBaseUrl', 'shareBaseUrl'])('rejects missing %s before reading package bytes', async endpoint => {
+ io.missing = endpoint;
+ await expect(prepareLocalPluginShare(1, 'local-example', operation, { includeAttribution: false })).rejects.toMatchObject({ code: 'SHARE_NOT_CONFIGURED' });
+ expect(io.snapshot).not.toHaveBeenCalled();
+ expect(io.content).not.toHaveBeenCalled();
+ expect(io.put).not.toHaveBeenCalled();
+ });
+ it('requires login before reading package bytes, even with attribution disabled', async () => {
+ signedIn = false;
+ await expect(prepareLocalPluginShare(1, 'local-example', operation, { includeAttribution: false })).rejects.toThrow();
+ expect(io.snapshot).not.toHaveBeenCalled();
+ expect(io.content).not.toHaveBeenCalled();
+ expect(io.api).not.toHaveBeenCalled();
+ });
+
+ it('creates independent uploads for new operations and sends login credentials without attribution', async () => {
+ const first = await prepareLocalPluginShare(1, 'local-example', operation, { includeAttribution: false });
+ const second = await prepareLocalPluginShare(1, 'local-example', 'operation_00000002', { includeAttribution: false });
+ expect(second.url).not.toBe(first.url);
+ expect(io.put).toHaveBeenCalledTimes(2);
+ for (const [, options] of io.api.mock.calls) expect(options.token).toBe('owner-token');
+ expect(io.api.mock.calls.filter(([url]) => url === '/api/shares')[0]![1].body).toMatchObject({ kind: 'local-plugin', includeAttribution: false, authRealm: 'global' });
+ });
+
+ // The server may return ready on prepare after dedup; previous fixtures only
+ // covered uploading. A new operation must still create its own share material.
+ it('creates an independent share without another PUT when prepare reuses the same package', async () => {
+ const first = await prepareLocalPluginShare(1, 'local-example', operation, { includeAttribution: false });
+ const snapshotId = 'b'.repeat(32);
+ io.api.mockResolvedValueOnce({ status: 'upload_required', contentSha256: digest })
+ .mockResolvedValueOnce({ snapshotId, status: 'ready', snapshot: details(snapshotId), expiresAt: new Date(Date.now() + 3600000).toISOString() });
+ const second = await prepareLocalPluginShare(1, 'local-example', 'operation_00000002', { includeAttribution: false });
+ expect(second.url).not.toBe(first.url);
+ expect(second.url).toContain(snapshotId);
+ expect(io.put).toHaveBeenCalledOnce();
+ expect(io.api.mock.calls.filter(([url]) => url.endsWith('/commit'))).toHaveLength(1);
+ expect(io.api.mock.calls.filter(([url]) => url === '/api/shares')).toHaveLength(2);
+ });
+
+ it('rejects a reused snapshot for bytes other than the frozen local package', async () => {
+ const snapshotId = 'b'.repeat(32);
+ io.api.mockResolvedValueOnce({ status: 'upload_required', contentSha256: digest })
+ .mockResolvedValueOnce({ snapshotId, status: 'ready', snapshot: { ...details(snapshotId), sha256: '0'.repeat(64) }, expiresAt: new Date(Date.now() + 3600000).toISOString() });
+ // The public coordinator sanitizes upload/binding failures as SHARE_READ_FAILED.
+ await expect(prepareLocalPluginShare(1, 'local-example', operation, { includeAttribution: false }))
+ .rejects.toMatchObject({ code: 'SHARE_READ_FAILED' });
+ expect(io.put).not.toHaveBeenCalled();
+ expect(io.api.mock.calls.filter(([url]) => url === '/api/shares')).toHaveLength(0);
+ });
+
+ it('reuses the exact uploaded snapshot when sharing material fails or attribution changes', async () => {
+ failMaterial = true;
+ await expect(prepareLocalPluginShare(1, 'local-example', operation, { includeAttribution: false })).rejects.toThrow();
+ io.snapshot.mockResolvedValue({ status: 'prepared', bytes: Buffer.from('later local edits'), ghost, contentSha256: 'changed' });
+ const restored = await prepareLocalPluginShare(1, 'local-example', operation, { includeAttribution: false });
+ const signed = await prepareLocalPluginShare(1, 'local-example', operation, { includeAttribution: true });
+ expect(restored.title).toBe('Local Example');
+ expect(signed.url).toBe(restored.url);
+ expect(io.snapshot).toHaveBeenCalledOnce();
+ expect(io.put).toHaveBeenCalledOnce();
+ expect(io.api.mock.calls.filter(([url]) => url === '/api/local-plugin-shares/uploads')).toHaveLength(1);
+ });
+
+ it('does not continue an old prepared operation after the active owner changes', async () => {
+ failMaterial = true;
+ await expect(prepareLocalPluginShare(1, 'local-example', operation, { includeAttribution: false })).rejects.toThrow();
+ currentOwner = 2;
+ io.api.mockClear();
+ await expect(prepareLocalPluginShare(1, 'local-example', operation, { includeAttribution: false })).rejects.toThrow();
+ expect(io.api).not.toHaveBeenCalled();
+ });
+
+ it('rejects a stale clicked installation before reading its replacement package', async () => {
+ await expect(prepareShare(1, 'local-example', operation, { includeAttribution: false }, { ...binding, version: '0.9.0' }, false)).rejects.toThrow();
+ expect(io.snapshot).not.toHaveBeenCalled();
+ expect(io.content).not.toHaveBeenCalled();
+ expect(io.api).not.toHaveBeenCalled();
+ });
+
+ // Content lookup must settle before archive work; earlier tests only mocked a
+ // ready ZIP upload. These unit inputs distinguish fast reuse, a changed package
+ // during consent, lookup failure and owner change while reading the content.
+ it('uses a verified content hit without compressing, inspecting or writing an archive', async () => {
+ const snapshotId = 'c'.repeat(32);
+ io.api.mockResolvedValueOnce({ status: 'ready', contentSha256: digest,
+ snapshot: { ...details(snapshotId), sha256: '1'.repeat(64) } });
+ const result = await prepareShare(1, 'local-example', operation, { includeAttribution: false }, binding, false);
+ expect(result).toHaveProperty('url', `https://share.example.test/s/${snapshotId}`);
+ expect(io.snapshot).not.toHaveBeenCalled();
+ expect(io.inspect).not.toHaveBeenCalled();
+ expect(io.write).not.toHaveBeenCalled();
+ expect(io.put).not.toHaveBeenCalled();
+ });
+
+ it('does not upload content that changed while the confirmation was open', async () => {
+ await prepareShare(1, 'local-example', operation, { includeAttribution: false }, binding, false);
+ const changedBytes = Buffer.from('changed');
+ io.snapshot.mockResolvedValue({ status: 'prepared', bytes: changedBytes, ghost, shareContentSha256: '0'.repeat(64) });
+ await expect(prepareShare(1, 'local-example', operation, { includeAttribution: false }, binding, true))
+ .rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ // A later attribution request still carries the old confirmation. It must
+ // not turn the invalidated operation into a new upload of changed content.
+ io.content.mockResolvedValue({ status: 'prepared', ghost, contentSha256: '0'.repeat(64) });
+ io.inspect.mockResolvedValue({ packageSha256: createHash('sha256').update(changedBytes).digest('hex'), canonicalManifest: manifest });
+ await expect(prepareShare(1, 'local-example', operation, { includeAttribution: true }, binding, true))
+ .rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ expect(io.content).toHaveBeenCalledOnce();
+ expect(io.put).not.toHaveBeenCalled();
+ expect(io.api.mock.calls.some(([url]) => url === '/api/local-plugin-shares/uploads')).toBe(false);
+ });
+
+ // Regression: version/approval changes during consent used to surface as a
+ // retryable material failure (or OWNER_CHANGED for a refreshed binding).
+ // Existing content-change coverage only changed the archive hash. These unit
+ // inputs exercise the production coordinator before any replacement upload.
+ it.each([
+ { field: 'version', refreshed: false },
+ { field: 'version', refreshed: true },
+ { field: 'approval', refreshed: false },
+ { field: 'approval', refreshed: true },
+ ])('requires reopening after $field changes with refreshed binding=$refreshed', async ({ field, refreshed }) => {
+ await expect(prepareShare(1, 'local-example', operation, { includeAttribution: false }, binding, false))
+ .resolves.toEqual({ confirmationRequired: true });
+ const changedGhost = {
+ ...ghost,
+ manifest: { ...manifest, version: field === 'version' ? '1.1.0' : manifest.version },
+ approval: { ...ghost.approval, revision: field === 'approval' ? '00000000-0000-4000-8000-000000000002' : ghost.approval.revision },
+ };
+ io.list.mockReturnValue([changedGhost]);
+ const nextBinding = { version: changedGhost.manifest.version, approvalToken: ghostInstallApprovalToken(changedGhost.approval) };
+ await expect(prepareShare(1, 'local-example', operation, { includeAttribution: false }, refreshed ? nextBinding : binding, true))
+ .rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ expect(io.snapshot).not.toHaveBeenCalled();
+ expect(io.put).not.toHaveBeenCalled();
+ expect(io.api.mock.calls.some(([url]) => url === '/api/local-plugin-shares/uploads')).toBe(false);
+ await releaseLocalPluginShare(1, operation);
+ await expect(prepareShare(1, 'local-example', 'operation_00000002', { includeAttribution: false }, nextBinding, false))
+ .resolves.toEqual({ confirmationRequired: true });
+ expect(io.content).toHaveBeenCalledTimes(2);
+ });
+
+ it('requires reopening if the installation changes while the confirmed package is inspected', async () => {
+ await prepareShare(1, 'local-example', operation, { includeAttribution: false }, binding, false);
+ io.inspect.mockImplementationOnce(async () => {
+ io.list.mockReturnValue([{ ...ghost, approval: { ...ghost.approval, revision: '00000000-0000-4000-8000-000000000002' } }]);
+ return { packageSha256: digest, canonicalManifest: manifest };
+ });
+ await expect(prepareShare(1, 'local-example', operation, { includeAttribution: false }, binding, true))
+ .rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });
+ expect(io.put).not.toHaveBeenCalled();
+ expect(io.api.mock.calls.some(([url]) => url === '/api/local-plugin-shares/uploads')).toBe(false);
+ expect(io.remove).toHaveBeenCalled();
+ });
+
+ it('keeps lookup failure retryable without compressing or uploading', async () => {
+ io.api.mockRejectedValueOnce(new Error('Lookup timed out'));
+ await expect(prepareShare(1, 'local-example', operation, { includeAttribution: false }, binding, false)).rejects.toThrow();
+ expect(io.snapshot).not.toHaveBeenCalled();
+ expect(io.put).not.toHaveBeenCalled();
+ await expect(prepareShare(1, 'local-example', operation, { includeAttribution: false }, binding, false))
+ .resolves.toEqual({ confirmationRequired: true });
+ });
+
+ it('stops before lookup when the owner changes during content reading', async () => {
+ io.content.mockImplementation(async () => { currentOwner++; return { status: 'prepared', ghost, contentSha256: digest }; });
+ await expect(prepareShare(1, 'local-example', operation, { includeAttribution: false }, binding, false)).rejects.toThrow();
+ expect(io.api).not.toHaveBeenCalled();
+ expect(io.snapshot).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/plugin-market/localSharing.ts b/apps/desktop/src/main/plugin-market/localSharing.ts
new file mode 100644
index 0000000000..f6818a9866
--- /dev/null
+++ b/apps/desktop/src/main/plugin-market/localSharing.ts
@@ -0,0 +1,319 @@
+import { createHash } from 'node:crypto';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import { app } from 'electron';
+import {
+ isLocalPluginSnapshotId, parseLocalPluginShareCheck, parseLocalPluginShareDownload, parseLocalPluginShareSnapshot, parseLocalPluginShareUpload, type LocalPluginShareSnapshot,
+} from '@cindy/plugin-protocol';
+import { ghostInstallApprovalToken, isGhostInstallApprovalToken, isUserInstallReservedGhostId } from '../../shared/ghost.js';
+import { findInstalledGhostByInstanceId } from '../../shared/pluginIdentity.js';
+import type { LocalPluginShareBinding, SharePreparation, ShareOptions } from '../../shared/share.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
+import * as auth from '../authManager.js';
+import { getGhostManager, installLocalPluginSharePackage } from '../cindy-brain/index.js';
+import type { GhostInstallConsentPrompt } from '../cindy-brain/ghostInstallConsent.js';
+import { inspectInstalledGhostPackageContent, snapshotInstalledGhostPackage } from '../cindy-brain/exportGhostPackage.js';
+import { getBuildClientEndpoint } from '../clientEndpointsService.js';
+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
+import { onQuit } from '../lifecycle.js';
+import { PluginPublisherPutError, putLocalFile } from '../plugin-publisher/putObject.js';
+import { serverApiFetch, ServerApiError } from '../serverApiClient.js';
+import { rememberIssuedClipboardText } from '../textClipboard.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+import { pluginObjectUrlOptions } from './objectUrlPolicy.js';
+import { downloadVerifiedPlugin } from './download.js';
+
+const TTL_MS = 30 * 60_000;
+class LocalShareContentChangedError extends Error {}
+function ownerKey(): string {
+ const state = auth.getAuthState();
+ if (isAppSessionBoundaryPending() || !state.isAuthenticated || !state.user)
+ throwIpcError('ACCOUNT_REAUTH_REQUIRED', 'Sign in to share a local plugin');
+ return JSON.stringify([activeOwnerScopeKey(), state.ownerGeneration, auth.getActiveAuthRealm(), state.user.id]);
+}
+function accessForOwner() {
+ const owner = ownerKey();
+ const realm = auth.getActiveAuthRealm();
+ const endpoints = { plugin: getBuildClientEndpoint('pluginApiBaseUrl'), share: getBuildClientEndpoint('shareBaseUrl') };
+ if (!endpoints.plugin) throwIpcError('SHARE_NOT_CONFIGURED', 'Local plugin sharing is not configured');
+ const assertCurrent = () => {
+ if (ownerKey() !== owner) throwIpcError('OWNER_CHANGED', 'Local share account changed');
+ };
+ return {
+ owner, realm, assertCurrent, shareBaseUrl: endpoints.share,
+ async request(service: 'plugin' | 'share', route: string, method = 'GET', body?: unknown) {
+ if (!endpoints[service]) throwIpcError('SHARE_NOT_CONFIGURED', 'Sharing is not configured');
+ const run = async () => {
+ assertCurrent();
+ const token = auth.getAccessToken();
+ if (!token) throwIpcError('ACCOUNT_REAUTH_REQUIRED', 'Sign in to access a local share');
+ const value = await serverApiFetch<unknown>(route, {
+ baseUrl: endpoints[service], token, method, body, cache: 'no-store', timeoutMs: 20_000,
+ headers: { 'x-cindy-version': app.getVersion(), 'X-Cindy-Auth-Realm': realm },
+ skipAutoRefresh: true, skipSessionInvalidation: true, redactErrorDetails: true,
+ allowedRedactedErrorCodes: ['TOKEN_EXPIRED', 'LOCAL_SHARE_UPLOAD_INCOMPLETE'],
+ logLabel: service === 'plugin' ? '/api/local-plugin-shares' : '/api/shares',
+ });
+ assertCurrent(); return value;
+ };
+ try { return await run(); }
+ catch (error) {
+ assertCurrent();
+ if (error instanceof ServerApiError && error.statusCode === 401 && error.code === 'TOKEN_EXPIRED') {
+ if (!(await auth.refresh())) throw error;
+ assertCurrent(); return run();
+ }
+ throw error;
+ }
+ },
+ };
+}
+
+function localInstallation(instanceId: string) {
+ const ghost = findInstalledGhostByInstanceId(getGhostManager().list(), instanceId);
+ if (!ghost) throwIpcError('NOT_FOUND', 'Local plugin not found');
+ if (ghost.builtin || isUserInstallReservedGhostId(ghost.manifest.id) || ghost.namespaceState !== 'confirmed' ||
+ ghost.namespace !== null || ghost.approval.state !== 'approved' || ghost.publishingSource?.kind !== 'local')
+ throwIpcError('PERMISSION_DENIED', 'Only a verified local plugin can use local sharing');
+ return ghost;
+}
+
+interface Bundle { directory: string; filePath: string; sha256: string; sizeBytes: number; ghostId: string; version: string }
+function clickedInstallation(instanceId: string, expected: LocalPluginShareBinding) {
+ const ghost = localInstallation(instanceId);
+ if (ghostInstallApprovalToken(ghost.approval) !== expected.approvalToken || ghost.manifest.version !== expected.version)
+ throw new LocalShareContentChangedError();
+ return ghost;
+}
+async function freezePackage(instanceId: string, expected: LocalPluginShareBinding, contentSha256: string, assertCurrent: () => void): Promise<Bundle> {
+ assertCurrent();
+ const ghost = clickedInstallation(instanceId, expected);
+ const approval = ghostInstallApprovalToken(ghost.approval);
+ const snapshot = await snapshotInstalledGhostPackage(instanceId, { listInstalled: () => [ghost] });
+ assertCurrent();
+ if (snapshot.status !== 'prepared') throwIpcError('PRECONDITION_FAILED', 'Local plugin could not be packaged');
+ if (snapshot.shareContentSha256 !== contentSha256) throw new LocalShareContentChangedError();
+ const directory = await fs.mkdtemp(path.join(app.getPath('temp'), 'cindy-local-share-'));
+ const filePath = path.join(directory, 'plugin.cindy');
+ try {
+ await fs.writeFile(filePath, snapshot.bytes, { flag: 'wx', mode: 0o600 });
+ const inspected = await getGhostManager().inspect(filePath);
+ assertCurrent();
+ const current = localInstallation(instanceId);
+ const sha256 = createHash('sha256').update(snapshot.bytes).digest('hex');
+ if (current.dir !== ghost.dir || ghostInstallApprovalToken(current.approval) !== approval)
+ throw new LocalShareContentChangedError();
+ if ('rejection' in inspected ||
+ inspected.packageSha256 !== sha256 || inspected.canonicalManifest.id !== ghost.manifest.id ||
+ inspected.canonicalManifest.version !== ghost.manifest.version)
+ throwIpcError('PRECONDITION_FAILED', 'Local plugin changed while packaging');
+ return { directory, filePath, sha256, sizeBytes: snapshot.bytes.length, ghostId: ghost.manifest.id, version: ghost.manifest.version };
+ } catch (error) {
+ await fs.rm(directory, { recursive: true, force: true }).catch(() => undefined);
+ throw error;
+ }
+}
+
+interface Operation {
+ caller: number; id: string; instanceId: string; access: ReturnType<typeof accessForOwner>;
+ expected: LocalPluginShareBinding;
+ invalidated?: boolean;
+ content?: { sha256: string; ghostId: string };
+ checked?: boolean; checking?: Promise<LocalPluginShareSnapshot | undefined>;
+ bundle?: Bundle; preparing?: Promise<Bundle>; uploading?: Promise<LocalPluginShareSnapshot>;
+ snapshot?: LocalPluginShareSnapshot; timer: ReturnType<typeof setTimeout>;
+}
+const operations = new Map<string, Operation>();
+const keyFor = (caller: number, id: string) => `${caller}:${id}`;
+
+async function cleanup(operation: Operation) {
+ if (operation.bundle) await fs.rm(operation.bundle.directory, { recursive: true, force: true }).catch(() => undefined);
+}
+export async function releaseLocalPluginShare(caller: number, id: string): Promise<void> {
+ const key = keyFor(caller, id);
+ const operation = operations.get(key);
+ if (!operation) return;
+ operations.delete(key); clearTimeout(operation.timer);
+ await operation.checking?.catch(() => undefined);
+ await operation.uploading?.catch(() => undefined);
+ await operation.preparing?.catch(() => undefined);
+ await cleanup(operation);
+}
+export async function releaseLocalPluginSharesForCaller(caller: number): Promise<void> {
+ await Promise.all([...operations.values()].filter(value => value.caller === caller).map(value => releaseLocalPluginShare(caller, value.id)));
+}
+
+function bindSnapshot(snapshot: LocalPluginShareSnapshot, bundle: Bundle, id?: string) {
+ if ((id && snapshot.snapshotId !== id) || snapshot.sha256 !== bundle.sha256 || snapshot.sizeBytes !== bundle.sizeBytes ||
+ snapshot.ghostId !== bundle.ghostId || snapshot.version !== bundle.version)
+ throwIpcError('PRECONDITION_FAILED', 'Local share does not match the prepared package');
+ return snapshot;
+}
+
+function bindOperationSnapshot(snapshot: LocalPluginShareSnapshot, operation: Operation, id?: string) {
+ if (snapshot.contentSha256 !== operation.content?.sha256 || snapshot.ghostId !== operation.content?.ghostId ||
+ snapshot.version !== operation.expected.version || (id && snapshot.snapshotId !== id))
+ throwIpcError('PRECONDITION_FAILED', 'Local share does not match the checked content');
+ return operation.bundle ? bindSnapshot(snapshot, operation.bundle, id) : snapshot;
+}
+
+async function checkContent(operation: Operation): Promise<LocalPluginShareSnapshot | undefined> {
+ operation.access.assertCurrent();
+ const ghost = clickedInstallation(operation.instanceId, operation.expected);
+ const content = await inspectInstalledGhostPackageContent(operation.instanceId, { listInstalled: () => [ghost] });
+ operation.access.assertCurrent();
+ if (content.status !== 'prepared' || clickedInstallation(operation.instanceId, operation.expected).dir !== ghost.dir)
+ throwIpcError('PRECONDITION_FAILED', 'Local plugin changed while checking');
+ if (operation.content && operation.content.sha256 !== content.contentSha256) throw new LocalShareContentChangedError();
+ operation.content = { sha256: content.contentSha256, ghostId: ghost.manifest.id };
+ const checked = parseLocalPluginShareCheck(await operation.access.request('plugin', '/api/local-plugin-shares/check', 'POST', {
+ operationId: operation.id, contentSha256: content.contentSha256,
+ }));
+ if (checked.contentSha256 !== content.contentSha256)
+ throwIpcError('PRECONDITION_FAILED', 'Local share content identity changed');
+ return checked.status === 'ready' ? bindOperationSnapshot(checked.snapshot, operation) : undefined;
+}
+
+async function upload(operation: Operation): Promise<LocalPluginShareSnapshot> {
+ if (!operation.preparing) operation.preparing = freezePackage(operation.instanceId, operation.expected, operation.content!.sha256, operation.access.assertCurrent)
+ .then(bundle => { operation.bundle = bundle; return bundle; });
+ const bundle = await operation.preparing;
+ const request = operation.access.request;
+ const options = pluginObjectUrlOptions();
+ const prepared = parseLocalPluginShareUpload(await request('plugin', '/api/local-plugin-shares/uploads', 'POST', {
+ operationId: operation.id, sha256: bundle.sha256, sizeBytes: bundle.sizeBytes, contentSha256: operation.content!.sha256,
+ }), options);
+ if (prepared.status === 'ready') return bindOperationSnapshot(prepared.snapshot!, operation);
+ if (prepared.status === 'uploading') {
+ if (!prepared.putUrl || !prepared.headers || new Date(prepared.expiresAt).getTime() <= Date.now())
+ throwIpcError('PRECONDITION_FAILED', 'Local share upload expired');
+ const handle = await fs.open(bundle.filePath, 'r');
+ try {
+ operation.access.assertCurrent();
+ await putLocalFile(handle, { putUrl: prepared.putUrl, headers: prepared.headers, sizeBytes: bundle.sizeBytes });
+ } catch (error) {
+ if (!(error instanceof PluginPublisherPutError) || error.disposition !== 'commit_same_upload') throw error;
+ // The PUT may have completed: commit this operation before deciding to resend.
+ } finally { await handle.close(); }
+ } else if (prepared.status !== 'validating') throwIpcError('PRECONDITION_FAILED', 'Local share upload is unavailable');
+ let progress = parseLocalPluginShareUpload(await request('plugin', `/api/local-plugin-shares/uploads/${prepared.snapshotId}/commit`, 'POST'));
+ for (let attempt = 0; progress.status === 'validating' && attempt < 30; attempt++) {
+ await delay(1000);
+ operation.access.assertCurrent();
+ progress = parseLocalPluginShareUpload(await request('plugin', `/api/local-plugin-shares/uploads/${prepared.snapshotId}`));
+ }
+ if (progress.status !== 'ready' || progress.snapshotId !== prepared.snapshotId)
+ throwIpcError('PRECONDITION_FAILED', 'Local share has not completed');
+ return bindOperationSnapshot(progress.snapshot!, operation, prepared.snapshotId);
+}
+
+/** Exact instance + per-dialog operation; never accepts filesystem paths or publish targets. */
+export async function prepareLocalPluginShare(caller: number, instanceId: string, id: string, options: ShareOptions, expected: LocalPluginShareBinding, uploadConfirmed: boolean): Promise<SharePreparation> {
+ if (!Number.isSafeInteger(caller) || caller <= 0 || typeof instanceId !== 'string' || instanceId.length > 256 ||
+ typeof id !== 'string' || !/^[A-Za-z0-9_-]{16,128}$/.test(id) || !options || typeof options !== 'object' ||
+ Array.isArray(options) || typeof options.includeAttribution !== 'boolean' || Object.keys(options).some(key => key !== 'includeAttribution') ||
+ !expected || typeof expected !== 'object' || Array.isArray(expected) || typeof expected.version !== 'string' ||
+ expected.version.length === 0 || expected.version.length > 128 || !isGhostInstallApprovalToken(expected.approvalToken) ||
+ Object.keys(expected).some(key => !['version', 'approvalToken'].includes(key)) || typeof uploadConfirmed !== 'boolean')
+ throwIpcError('INVALID_PARAMS', 'Invalid local share request');
+ const access = accessForOwner();
+ if (!access.shareBaseUrl) throwIpcError('SHARE_NOT_CONFIGURED', 'Local plugin sharing is not configured');
+ const key = keyFor(caller, id);
+ let operation = operations.get(key);
+ if (operation && (operation.access.owner !== access.owner || operation.instanceId !== instanceId))
+ throwIpcError('OWNER_CHANGED', 'Local share belongs to another owner or instance');
+ if (!operation) {
+ if ([...operations.values()].filter(value => value.caller === caller).length >= 8)
+ throwIpcError('PRECONDITION_FAILED', 'Too many local share operations');
+ const timer = setTimeout(() => { void releaseLocalPluginShare(caller, id); }, TTL_MS);
+ timer.unref();
+ operation = { caller, id, instanceId, access, expected: { ...expected }, timer };
+ operations.set(key, operation);
+ }
+ try {
+ if (operation.invalidated || operation.expected.version !== expected.version || operation.expected.approvalToken !== expected.approvalToken)
+ throw new LocalShareContentChangedError();
+ if (!operation.checked) {
+ operation.checking ??= checkContent(operation);
+ try {
+ operation.snapshot = await operation.checking;
+ operation.checked = true;
+ } catch (error) { operation.checking = undefined; throw error; }
+ }
+ if (!operation.snapshot && !uploadConfirmed) return { confirmationRequired: true };
+ if (!operation.snapshot) {
+ operation.uploading ??= upload(operation);
+ try { operation.snapshot = await operation.uploading; }
+ catch (error) { operation.uploading = undefined; if (!operation.bundle) operation.preparing = undefined; throw error; }
+ await cleanup(operation);
+ }
+ operation.access.assertCurrent();
+ const region = CURRENT_CINDY_REGION === 'global' ? 'global' : 'cn';
+ const raw = await operation.access.request('share', '/api/shares', 'POST', {
+ kind: 'local-plugin', reference: operation.snapshot.snapshotId, includeAttribution: options.includeAttribution,
+ authRealm: operation.access.realm, region, lang: region === 'cn' ? 'zh-CN' : 'en',
+ });
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('Invalid share material');
+ const row = raw as Record<string, unknown>;
+ const snapshot = parseLocalPluginShareSnapshot(row.snapshot);
+ bindOperationSnapshot(snapshot, operation, operation.snapshot.snapshotId);
+ if (row.schemaVersion !== 1 || row.kind !== 'local-plugin' || row.includeAttribution !== options.includeAttribution ||
+ typeof row.shareId !== 'string' || !/^[A-Za-z0-9_-]{32}$/.test(row.shareId) ||
+ row.url !== `${operation.access.shareBaseUrl}/s/${row.shareId}` || typeof row.imageSvg !== 'string' ||
+ !row.imageSvg.startsWith('<svg ') || row.imageSvg.length > 1024 * 1024)
+ throw new Error('Invalid local share binding');
+ operation.access.assertCurrent();
+ rememberIssuedClipboardText(row.url as string);
+ const attribution = row.attribution && typeof row.attribution === 'object' ? (row.attribution as Record<string, unknown>).displayName : null;
+ return { title: snapshot.name, url: row.url as string, imageSvg: row.imageSvg,
+ ...(options.includeAttribution && typeof attribution === 'string' && attribution.trim() && attribution.length <= 256
+ ? { attribution: { displayName: attribution.trim() } } : {}) };
+ } catch (error) {
+ operation.access.assertCurrent();
+ if (error instanceof LocalShareContentChangedError) {
+ operation.invalidated = true;
+ throwIpcError('PRECONDITION_FAILED', 'Local plugin content changed; reopen sharing to check it again');
+ }
+ throwIpcError('SHARE_READ_FAILED', 'Could not prepare this local plugin share');
+ }
+}
+
+export async function readLocalPluginShare(snapshotId: string): Promise<LocalPluginShareSnapshot> {
+ if (!isLocalPluginSnapshotId(snapshotId)) throwIpcError('INVALID_PARAMS', 'Invalid local share ID');
+ const access = accessForOwner();
+ const snapshot = parseLocalPluginShareSnapshot(await access.request('plugin', `/api/local-plugin-shares/${snapshotId}`));
+ if (snapshot.snapshotId !== snapshotId) throwIpcError('PRECONDITION_FAILED', 'Local share identity changed');
+ return snapshot;
+}
+
+/** Download only the clicked snapshot; the original manual transaction owns consent and placement. */
+export async function installLocalPluginShare(snapshotId: string, expected: unknown, prompt: GhostInstallConsentPrompt, assertScope?: () => void) {
+ if (!isLocalPluginSnapshotId(snapshotId)) throwIpcError('INVALID_PARAMS', 'Invalid local share ID');
+ const snapshot = parseLocalPluginShareSnapshot(expected);
+ if (snapshot.snapshotId !== snapshotId) throwIpcError('INVALID_PARAMS', 'Invalid local share binding');
+ const access = accessForOwner();
+ const assertCurrent = () => { access.assertCurrent(); assertScope?.(); };
+ assertCurrent();
+ const ticket = parseLocalPluginShareDownload(await access.request('plugin', `/api/local-plugin-shares/${snapshotId}/download`), pluginObjectUrlOptions());
+ assertCurrent();
+ if (ticket.snapshot.snapshotId !== snapshotId || ticket.snapshot.sha256 !== snapshot.sha256 ||
+ ticket.snapshot.sizeBytes !== snapshot.sizeBytes || ticket.snapshot.ghostId !== snapshot.ghostId ||
+ ticket.snapshot.version !== snapshot.version || new Date(ticket.expiresAt).getTime() <= Date.now())
+ throwIpcError('PRECONDITION_FAILED', 'The shared package changed');
+ const directory = await fs.mkdtemp(path.join(app.getPath('temp'), 'cindy-shared-plugin-install-'));
+ const filePath = path.join(directory, 'package.cindy');
+ try {
+ assertCurrent();
+ await downloadVerifiedPlugin(ticket.url, { sha256: snapshot.sha256, sizeBytes: snapshot.sizeBytes }, filePath);
+ assertCurrent();
+ return await installLocalPluginSharePackage(filePath, {
+ ghostId: snapshot.ghostId, version: snapshot.version, sha256: snapshot.sha256,
+ prompt, assertCurrent,
+ });
+ } finally { await fs.rm(directory, { recursive: true, force: true }); }
+}
+
+onQuit('local-plugin-share-snapshots', async () => {
+ await Promise.all([...operations.values()].map(operation => releaseLocalPluginShare(operation.caller, operation.id)));
+}, 'async');
diff --git a/apps/desktop/src/main/plugin-market/registerIpc.ts b/apps/desktop/src/main/plugin-market/registerIpc.ts
index 35d5cfe074..f7f564fb5d 100644
--- a/apps/desktop/src/main/plugin-market/registerIpc.ts
+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts
@@ -33,12 +33,14 @@ import {
} from './service.js';
import { preparePluginShare } from './sharing.js';
+import { installLocalPluginShare, readLocalPluginShare, prepareLocalPluginShare, releaseLocalPluginShare, releaseLocalPluginSharesForCaller } from './localSharing.js';
const log = createLogger('plugin-market-ipc');
let registered = false;
const REMOVAL_NOTICE_AVAILABLE_CHANNEL = 'plugin-market:removal-notice-available';
const UPDATE_CONSENT_HOLDS_CHANGED_CHANNEL = 'plugin-market:update-consent-holds-changed';
const localIconRequestGate = new LocalIconRequestGate();
+const localShareWindows = new Set<number>();
function signalRemovalNoticeAvailable(): void {
if (!service().hasPendingRemovalNotice()) return;
@@ -181,6 +183,37 @@ export function registerPluginMarketIpc(): void {
assertTrustedAppRendererEvent(event);
return preparePluginShare(pluginId, options);
});
+ ipcMain.handle('plugin-market:local-share-detail', (event, snapshotId: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ return invokePluginMarket(() => readLocalPluginShare(requireString(snapshotId, 'snapshotId')));
+ });
+ ipcMain.handle('plugin-market:install-local-share', (event, snapshotId: unknown, expected: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ return invokePluginMarket(async () => ({
+ ghost: await installLocalPluginShare(requireString(snapshotId, 'snapshotId'), expected, createWindowGhostInstallConsentPrompt(event.sender)),
+ }));
+ });
+ ipcMain.handle('plugin-market:prepare-local-share', (event, instanceId: unknown, operationId: unknown, options: unknown, expected: unknown, uploadConfirmed: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ if (typeof uploadConfirmed !== 'boolean') throwIpcError('INVALID_PARAMS', 'Invalid upload confirmation');
+ const caller = event.sender.id;
+ if (!localShareWindows.has(caller)) {
+ localShareWindows.add(caller);
+ event.sender.once('destroyed', () => {
+ localShareWindows.delete(caller);
+ void releaseLocalPluginSharesForCaller(caller);
+ });
+ }
+ return prepareLocalPluginShare(caller, requireString(instanceId, 'instanceId'), requireString(operationId, 'operationId'),
+ requireObject(options) as unknown as import('../../shared/share.js').ShareOptions,
+ requireObject(expected) as unknown as import('../../shared/share.js').LocalPluginShareBinding, uploadConfirmed);
+ });
+ ipcMain.handle('plugin-market:release-local-share', (event, operationId: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const id = requireString(operationId, 'operationId');
+ if (!/^[A-Za-z0-9_-]{16,128}$/.test(id)) throwIpcError('INVALID_PARAMS', 'Invalid local share operation');
+ return releaseLocalPluginShare(event.sender.id, id);
+ });
ipcMain.handle('plugin-market:local-icons', (event, raw: unknown) => {
assertTrustedAppRendererEvent(event);
if (!Array.isArray(raw) || raw.length > 8) {
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 58b6d367b3..22e435e4ff 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -59,7 +59,7 @@ import {
WINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL,
} from '../shared/windowBackdrop';
import { isDeepLinkProviderConnectId } from '../shared/deepLinkSchemes';
-import { isValidPluginResourceId } from '@cindy/plugin-protocol';
+import { isLocalPluginSnapshotId, isValidPluginResourceId } from '@cindy/plugin-protocol';
import {
parseProjectOrderSnapshot,
SIDEBAR_APPLY_PROJECT_ORDER_CHANNEL,
@@ -1631,6 +1631,14 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('plugin-market:detail', pluginId),
prepareShare: (pluginId: string, options?: import('../shared/share').ShareOptions): Promise<import('../shared/share').ShareContent> =>
ipcRenderer.invoke('plugin-market:prepare-share', pluginId, options),
+ prepareLocalShare: (instanceId: string, operationId: string, options: import('../shared/share').ShareOptions, expected: import('../shared/share').LocalPluginShareBinding, uploadConfirmed: boolean): Promise<import('../shared/share').SharePreparation> =>
+ ipcRenderer.invoke('plugin-market:prepare-local-share', instanceId, operationId, options, expected, uploadConfirmed),
+ releaseLocalShare: (operationId: string): Promise<void> =>
+ ipcRenderer.invoke('plugin-market:release-local-share', operationId),
+ localShareDetail: (snapshotId: string): Promise<import('@cindy/plugin-protocol').LocalPluginShareSnapshot> =>
+ ipcRenderer.invoke('plugin-market:local-share-detail', snapshotId),
+ installLocalShare: (snapshotId: string, expected: import('@cindy/plugin-protocol').LocalPluginShareSnapshot): Promise<{ ghost: import('../shared/ghost').InstalledGhost }> =>
+ ipcRenderer.invoke('plugin-market:install-local-share', snapshotId, expected),
localIcons: (
requests: import('../shared/pluginMarket').PluginMarketLocalIconRequest[],
): Promise<import('../shared/pluginMarket').PluginMarketLocalIconResult[]> =>
@@ -4045,6 +4053,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
| { type: 'share-import'; filePath: string }
| { type: 'provider-import'; importId: string }
| { type: 'plugin'; pluginId: string }
+ | { type: 'local-plugin-share'; snapshotId: string }
| { type: 'shared-task-join'; invitation: string; server: string }
| { type: 'provider-share-join'; link: string }
| { type: 'chat-invite'; token: string }
@@ -4061,6 +4070,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
filePath?: unknown;
importId?: unknown;
pluginId?: unknown;
+ snapshotId?: unknown;
invitation?: unknown;
token?: unknown;
server?: unknown;
@@ -4091,6 +4101,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
});
} else if (p.type === 'plugin' && isValidPluginResourceId(p.pluginId)) {
callback({ type: 'plugin', pluginId: p.pluginId });
+ } else if (p.type === 'local-plugin-share' && isLocalPluginSnapshotId(p.snapshotId)) {
+ callback({ type: 'local-plugin-share', snapshotId: p.snapshotId });
} else if (p.type === 'chat-message' && typeof p.groupId === 'string' && typeof p.messageId === 'string'
&& [p.groupId, p.messageId, ...(p.threadRootId === undefined ? [] : [p.threadRootId])].every(value => typeof value === 'string' && /^[0-9a-f-]{36}$/i.test(value))) {
callback({ type: 'chat-message', groupId: p.groupId, messageId: p.messageId,
@@ -4159,6 +4171,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
| { type: 'share-import'; filePath: string }
| { type: 'provider-import'; importId: string }
| { type: 'plugin'; pluginId: string }
+ | { type: 'local-plugin-share'; snapshotId: string }
| { type: 'shared-task-join'; invitation: string; server: string }
| { type: 'provider-share-join'; link: string }
| { type: 'chat-invite'; token: string }
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index e6064eb74e..7112d0081e 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -721,6 +721,7 @@ export function MainLayout() {
| { type: 'chat-invite-malformed' }
| { type: 'provider-share-join'; link: string }
| { type: 'plugin'; pluginId: string }
+ | { type: 'local-plugin-share'; snapshotId: string }
| { type: 'settings'; tab: 'voice-input' | 'providers' | 'billing' | 'remote-control'; connect?: string; intent?: 'topup' },
) => {
if (payload.type === 'chat-message') {
@@ -746,6 +747,10 @@ export function MainLayout() {
setSharedTaskInvitation({ link: buildSharedTaskInvitationLink(payload.invitation, payload.server), id: ++invitationSequence.current });
return;
}
+ if (payload.type === 'local-plugin-share') {
+ navigate(`/plugins?share=${encodeURIComponent(payload.snapshotId)}`);
+ return;
+ }
if (payload.type === 'plugin') {
navigate(`/plugins?market=${encodeURIComponent(payload.pluginId)}`);
return;
@@ -810,7 +815,7 @@ export function MainLayout() {
void pullChatInvitations();
return;
}
- if (payload.type !== 'provider-import' && payload.type !== 'shared-task-join' && payload.type !== 'provider-share-join' && payload.type !== 'plugin') {
+ if (payload.type !== 'provider-import' && payload.type !== 'shared-task-join' && payload.type !== 'provider-share-join' && payload.type !== 'plugin' && payload.type !== 'local-plugin-share') {
handleDeepLinkPayload(payload);
return;
}
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index cc1b13d39a..ca2428a754 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@ -209,6 +209,9 @@ export function GhostPluginDetailView({
? remoteFileUpdate && !isUserInstallReservedGhostId(detail.ghostId)
: import.meta.env.DEV || !isUserInstallReservedGhostId(detail.ghostId);
const hasAdditionalActions = localUpdateAvailable || onExport !== undefined;
+ const localShareAvailable = !remote && ghost?.publishingSource?.kind === 'local' &&
+ ghost.approval.state === 'approved' && ghost.namespaceState === 'confirmed' && ghost.namespace === null &&
+ !ghost.builtin && !isUserInstallReservedGhostId(ghost.manifest.id);
return (
<main
@@ -219,7 +222,7 @@ export function GhostPluginDetailView({
label={t('settings.ghosts.detail.backToList')}
onBack={onBack}
scrolled={scrolled}
- actions={sharePluginId ? <PluginShareButton pluginId={sharePluginId} /> : undefined}
+ actions={sharePluginId ? <PluginShareButton pluginId={sharePluginId} /> : localShareAvailable && ghost ? <PluginShareButton ghost={ghost} /> : undefined}
/>
<article className="plugin-detail-frame mx-auto w-full max-w-[824px] px-8 pb-16 pt-5 max-[760px]:px-6">
<PluginDetailHeader
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index 32b0aeabb8..6dfd8377f6 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -1,5 +1,6 @@
import { CatalogDeviceScope, type CatalogDeviceControl } from './useCatalogDevice';
import { RemotePluginPage } from './RemotePluginPage';
+import { LocalPluginShareView } from './LocalPluginShareView';
import { PluginVersionFacts } from './PluginVersionFacts';
import { useSignInToCindy } from '@/hooks/useSignInToCindy';
import { rememberContributionIntent, consumeContributionIntent, matchesContributionIntent } from './lib/contributionIntent';
@@ -433,7 +434,17 @@ function readIgnoredRound(storageKey: string): string {
* interaction shape, while every displayed field comes from InstalledGhost.
*/
export function GhostPluginPage(props: { embedded?: boolean; active?: boolean; onSelectCatalogTab?: (tab: 'plugins' | 'skills') => void } = {}) {
- return <CatalogDeviceScope>{(device, online, generation, deviceControl) => device
+ const [searchParams, setSearchParams] = useSearchParams();
+ const snapshotId = searchParams.get('share');
+ const closeShare = (ghost?: InstalledGhost) => {
+ const next = new URLSearchParams(searchParams); next.delete('share');
+ if (ghost) next.set('ghost', installedGhostStoragePart(ghost));
+ setSearchParams(next, { replace: true });
+ };
+ return <CatalogDeviceScope>{(device, online, generation, deviceControl) => snapshotId !== null
+ ? <LocalPluginShareView key={`${generation}:${snapshotId}:${device?.deviceId ?? 'local'}`} snapshotId={snapshotId}
+ deviceControl={deviceControl} onBack={() => closeShare()} onInstalled={closeShare} />
+ : device
? <RemotePluginPage key={`${generation}:${device.deviceId}`} device={device} online={online} deviceControl={deviceControl} {...props} />
: <LocalGhostPluginPage deviceControl={deviceControl} {...props} />}</CatalogDeviceScope>;
}
@@ -571,7 +582,7 @@ function LocalGhostPluginPage({
if (contributionView.current.key !== contributionViewKey)
contributionView.current = { key: contributionViewKey, token: {} };
// 列表与详情是互斥分支;列表节点会卸载,返回时需显式恢复进入前的滚动位置。
- const pluginCatalogVisible = marketDetail === null && selectedId === null && !searchParams.has('myPlugins');
+ const pluginCatalogVisible = marketDetail === null && selectedId === null && !searchParams.has('myPlugins') && !searchParams.has('share');
const {
listRef: pluginCatalogListRef,
onListScroll: onPluginCatalogScroll,
diff --git a/apps/desktop/src/renderer/features/plugin/LocalPluginShareView.tsx b/apps/desktop/src/renderer/features/plugin/LocalPluginShareView.tsx
new file mode 100644
index 0000000000..e5372940b3
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/LocalPluginShareView.tsx
@@ -0,0 +1,206 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { isLocalPluginSnapshotId, type LocalPluginShareSnapshot } from '@cindy/plugin-protocol';
+import { Download } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+import { Spinner } from '@/components/ui/spinner';
+import { useAuth } from '@/contexts/AuthContext';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
+import { GhostInstallConsentContent, ghostInstallConsentSourceLabel } from '@/cindy-brain/GhostInstallConsentHost';
+import { useSignInToCindy } from '@/hooks/useSignInToCindy';
+import { extractIpcError } from '@/utils/ipcError';
+import type { InstalledGhost } from '../../../shared/ghost';
+import type { PluginManagementReceipt } from '../../../shared/pluginManagement';
+import { GhostPluginIcon } from './GhostPluginIcon';
+import { PluginDetailTopBar, usePluginDetailScrolled } from './PluginDetailTopBar';
+import { pluginMarketErrorKey } from './lib/pluginMarketErrorKey';
+import { PluginDevicePicker, type CatalogDeviceControl } from './PluginDevicePicker';
+import { hasPluginManagement, invokePluginManagement, parsePluginManagementSnapshot, parsePluginManagementReceipt } from './remotePluginManagementClient';
+
+/** A shared local package is a fixed manual import, with no marketplace/update identity. */
+export function LocalPluginShareView({ snapshotId, onBack, onInstalled, deviceControl }: {
+ snapshotId: string; onBack: () => void; onInstalled: (ghost?: InstalledGhost) => void;
+ deviceControl?: CatalogDeviceControl;
+}) {
+ const { t } = useTranslation();
+ const { isAuthenticated, dataOwnerId, dataOwnerGeneration } = useAuth();
+ const signIn = useSignInToCindy(`/plugins?share=${encodeURIComponent(snapshotId)}`);
+ const { scrolled, onScroll } = usePluginDetailScrolled();
+ const [snapshot, setSnapshot] = useState<LocalPluginShareSnapshot | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [revision, setRevision] = useState(0);
+ const [busy, setBusy] = useState(false);
+ const generation = useRef(0);
+ const installing = useRef(false);
+ useEffect(() => {
+ const current = ++generation.current;
+ setSnapshot(null); setError(null);
+ if (!isLocalPluginSnapshotId(snapshotId)) setError('settings.ghosts.market.errors.invalidRequest');
+ else if (isAuthenticated) void window.electronAPI.pluginMarket.localShareDetail(snapshotId)
+ .then(value => { if (generation.current === current) setSnapshot(value); })
+ .catch(() => { if (generation.current === current) setError('sharing.localReadFailed'); });
+ return () => { generation.current++; };
+ }, [snapshotId, isAuthenticated, dataOwnerId, dataOwnerGeneration, revision]);
+ const install = async () => {
+ if (!snapshot || !isAuthenticated || installing.current) return;
+ const current = generation.current;
+ installing.current = true; setBusy(true); setError(null);
+ try {
+ const result = await window.electronAPI.pluginMarket.installLocalShare(snapshotId, snapshot);
+ if (current === generation.current) onInstalled(result.ghost);
+ } catch (cause) {
+ if (current === generation.current && extractIpcError(cause)?.code !== 'MUTATION_CANCELLED')
+ setError(pluginMarketErrorKey(cause));
+ } finally {
+ installing.current = false;
+ if (current === generation.current) setBusy(false);
+ }
+ };
+ return <main className="app-wallpaper-surface plugin-motion-root h-full min-h-0 w-full overflow-y-auto bg-[var(--surface)]" onScroll={onScroll}>
+ <PluginDetailTopBar label={t('settings.ghosts.detail.backToList')} onBack={onBack} scrolled={scrolled} />
+ <article className="plugin-detail-frame mx-auto w-full max-w-[824px] px-6 pb-16 pt-5">
+ {!isAuthenticated ? <div className="space-y-4 text-14 text-[var(--text-secondary)]">
+ <p>{t('sharing.localOpenHint')}</p>
+ <Button variant="cta" onClick={() => void signIn()}>{t('sharing.localSignIn')}</Button>
+ </div> : snapshot ? <>
+ <header className="flex flex-wrap items-center gap-4">
+ <GhostPluginIcon iconDataUrl={snapshot.icon ?? undefined} iconId={snapshot.ghostId} iconName={snapshot.name} size="detail" />
+ <div className="min-w-0 flex-1 basis-40">
+ <h1 className="break-words text-28 font-medium text-[var(--text-primary)]">{snapshot.name}</h1>
+ <p className="mt-2 flex flex-wrap gap-2 text-12 text-[var(--text-tertiary)]">
+ <span>{t('sharing.localPackage')}</span><span>·</span><span>v{snapshot.version}</span>
+ {snapshot.author ? <span>· {snapshot.author}</span> : null}
+ </p>
+ </div>
+ </header>
+ {snapshot.description ? <p className="mt-6 whitespace-pre-wrap break-words text-14 leading-relaxed text-[var(--text-secondary)]">{snapshot.description}</p> : null}
+ <p className="mt-6 text-13 leading-relaxed text-[var(--text-secondary)]">{t('sharing.localVersionNotice')}</p>
+ <section className="mt-6 space-y-3" aria-label={t('sharing.localInstallTarget')}>
+ <p className="text-13 text-[var(--text-secondary)]">{t('sharing.localInstallTarget')}</p>
+ {deviceControl ? <div className="[&>button]:max-w-full"><PluginDevicePicker {...deviceControl} disabled={busy} /></div> : null}
+ {deviceControl?.selected ? <RemoteShareInstall
+ key={`${dataOwnerId}:${dataOwnerGeneration}:${snapshotId}:${deviceControl.selected.deviceId}`}
+ snapshot={snapshot} device={deviceControl.selected} online={deviceControl.directory.online}
+ onBusy={setBusy} onError={setError} onInstalled={() => onInstalled()}
+ /> : <div><Button variant="cta" loading={busy} disabled={busy} onClick={() => void install()}>
+ <Download size={15} aria-hidden />{t(busy ? 'sharing.localInstalling' : 'sharing.localInstallButton', { version: snapshot.version })}
+ </Button></div>}
+ </section>
+ </> : !error ? <div role="status" className="flex items-center gap-2 text-13 text-[var(--text-secondary)]"><Spinner size={16} />{t('sharing.localLoading')}</div> : null}
+ {error ? <div role="alert" className="mt-5 text-13 text-[var(--text-secondary)]">
+ <p>{t(error)}</p>
+ {!snapshot ? <Button className="mt-3" variant="secondary" onClick={() => setRevision(value => value + 1)}>{t('sharing.retry')}</Button> : null}
+ </div> : null}
+ </article>
+ </main>;
+}
+
+/** Projects the original Host receipt; a reconnect only reads the same operation. */
+function RemoteShareInstall({ snapshot, device, online, onBusy, onError, onInstalled }: {
+ snapshot: LocalPluginShareSnapshot; device: { deviceId: string; name: string }; online: boolean;
+ onBusy: (busy: boolean) => void; onError: (key: string | null) => void; onInstalled: () => void;
+}) {
+ const { t } = useTranslation();
+ const { confirm } = useConfirmDialog();
+ const [supported, setSupported] = useState<boolean | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [status, setStatus] = useState<'readFailed' | 'unknown' | null>(null);
+ const scope = useRef({ owner: getDataOwnerGeneration(), alive: true, online });
+ scope.current.online = online;
+ const operation = useRef<string | null>(null);
+ const readRevision = useRef(0);
+ const dialog = useRef<AbortController | null>(null);
+ const current = useCallback(() => scope.current.alive && isDataOwnerGenerationCurrent(scope.current.owner), []);
+ const writable = useCallback(() => current() && scope.current.online, [current]);
+ const invoke = useCallback((action: string, input?: Record<string, unknown>) =>
+ invokePluginManagement(device.deviceId, action, input), [device.deviceId]);
+ useEffect(() => {
+ scope.current.alive = true;
+ return () => {
+ scope.current.alive = false; readRevision.current++; dialog.current?.abort();
+ if (operation.current && isDataOwnerGenerationCurrent(scope.current.owner))
+ void invoke('cancel', { operationId: operation.current }).catch(() => {});
+ onBusy(false);
+ };
+ }, [invoke, onBusy]);
+ const refresh = useCallback(async () => {
+ if (!writable()) return;
+ const revision = ++readRevision.current;
+ setSupported(null); setStatus(null);
+ try {
+ const supported = await hasPluginManagement(device.deviceId) &&
+ parsePluginManagementSnapshot(await invoke('snapshot')).localShares === true;
+ if (writable() && revision === readRevision.current) setSupported(supported);
+ } catch { if (writable() && revision === readRevision.current) setStatus('readFailed'); }
+ }, [device.deviceId, invoke, writable]);
+ useEffect(() => {
+ if (online) void refresh();
+ else { readRevision.current++; setSupported(null); dialog.current?.abort(); }
+ }, [online, refresh]);
+ const acceptReceipt = useCallback(async (next: PluginManagementReceipt) => {
+ if (!writable() || next.operationId !== operation.current) return;
+ setStatus(null);
+ if (['succeeded', 'cancelled', 'failed'].includes(next.phase)) {
+ operation.current = null; setBusy(false); onBusy(false);
+ if (next.phase === 'succeeded') onInstalled();
+ else if (next.phase === 'failed') onError('settings.ghosts.remote.actionFailed');
+ return;
+ }
+ if (next.phase !== 'confirmation' || !next.consent || dialog.current) return;
+ const abort = new AbortController(); dialog.current = abort;
+ try {
+ const consent = next.consent;
+ const confirmed = await confirm({
+ title: t('settings.ghosts.remote.confirmOn', { device: device.name, name: consent.facts.name }),
+ description: `${device.name} · ${consent.facts.kind === 'install'
+ ? t('settings.ghosts.installConsent.installMeta', { version: consent.facts.version, source: ghostInstallConsentSourceLabel(t, consent) })
+ : t('settings.ghosts.installConsent.updateMeta', { from: consent.facts.previousVersion, to: consent.facts.version, source: ghostInstallConsentSourceLabel(t, consent) })}`,
+ content: <GhostInstallConsentContent facts={consent.facts} />,
+ confirmText: t(consent.facts.kind === 'install' ? 'settings.ghosts.installConsent.confirmInstall' : 'settings.ghosts.installConsent.confirmUpdate'),
+ cancelText: t('settings.ghosts.installConsent.cancel'), maxWidth: 460, contentSelectable: true,
+ }, abort.signal);
+ if (writable() && !abort.signal.aborted && operation.current === next.operationId)
+ await invoke('answer', { operationId: next.operationId, requestId: consent.requestId, confirmed });
+ } catch { if (writable()) setStatus('unknown'); }
+ finally { if (dialog.current === abort) dialog.current = null; }
+ }, [confirm, device.name, invoke, onBusy, onError, onInstalled, t, writable]);
+ const poll = useCallback(async () => {
+ const id = operation.current;
+ if (!id || !writable()) return;
+ try { await acceptReceipt(parsePluginManagementReceipt(await invoke('operation', { operationId: id }), id)); }
+ catch { if (writable() && id === operation.current) setStatus('unknown'); }
+ }, [acceptReceipt, invoke, writable]);
+ useEffect(() => {
+ if (!online || !busy) return;
+ let alive = true;
+ let timer: ReturnType<typeof setTimeout>;
+ const tick = async () => {
+ await poll();
+ if (alive && operation.current) timer = setTimeout(tick, 1200);
+ };
+ timer = setTimeout(tick, 600);
+ return () => { alive = false; clearTimeout(timer); };
+ }, [online, busy, poll]);
+ const install = async () => {
+ if (!writable() || !supported || operation.current) return;
+ const id = crypto.randomUUID(); operation.current = id;
+ setBusy(true); onBusy(true); onError(null); setStatus(null);
+ try {
+ await acceptReceipt(parsePluginManagementReceipt(await invoke('begin', {
+ operationId: id, kind: 'install-share', expectedSnapshot: snapshot,
+ }), id));
+ } catch { if (writable()) setStatus('unknown'); }
+ };
+ return <div className="space-y-3">
+ <Button variant="cta" loading={busy} disabled={busy || !online || supported !== true} onClick={() => void install()}>
+ <Download size={15} aria-hidden />{t(busy ? 'sharing.localInstalling' : 'sharing.localInstallButton', { version: snapshot.version })}
+ </Button>
+ {!online ? <p className="text-13 text-[var(--text-secondary)]">{t('settings.ghosts.remote.offlineNotice', { device: device.name })}</p>
+ : supported === false ? <p className="text-13 text-[var(--text-secondary)]">{t('sharing.localTargetUnsupported', { device: device.name })}</p> : null}
+ {status ? <div role="status" className="space-y-2 text-13 text-[var(--text-secondary)]">
+ <p>{t(`settings.ghosts.remote.${status}`)}</p>
+ <Button variant="secondary" onClick={() => void (operation.current ? poll() : refresh())}>{t('sharing.retry')}</Button>
+ </div> : null}
+ </div>;
+}
diff --git a/apps/desktop/src/renderer/features/plugin/PluginDevicePicker.tsx b/apps/desktop/src/renderer/features/plugin/PluginDevicePicker.tsx
index 276e448243..2e81e0eb8b 100644
--- a/apps/desktop/src/renderer/features/plugin/PluginDevicePicker.tsx
+++ b/apps/desktop/src/renderer/features/plugin/PluginDevicePicker.tsx
@@ -74,7 +74,8 @@ export function PluginDevicePicker({
directory: { candidates, target, online, relayOnline },
projectMenu,
projectLabel,
-}: CatalogDeviceControl & { projectMenu?: ReactNode; projectLabel?: string }) {
+ disabled,
+}: CatalogDeviceControl & { projectMenu?: ReactNode; projectLabel?: string; disabled?: boolean }) {
const { t } = useTranslation();
const computerName = selected
? (target?.name ?? selected.name)
@@ -86,6 +87,7 @@ export function PluginDevicePicker({
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
+ disabled={disabled}
variant="secondary"
size="lg"
compact
diff --git a/apps/desktop/src/renderer/features/plugin/PluginShareButton.tsx b/apps/desktop/src/renderer/features/plugin/PluginShareButton.tsx
index 14e32334b6..90412317b7 100644
--- a/apps/desktop/src/renderer/features/plugin/PluginShareButton.tsx
+++ b/apps/desktop/src/renderer/features/plugin/PluginShareButton.tsx
@@ -1,43 +1,75 @@
-import { useCallback, useRef, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
import { Share2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { ChromeIconButton } from '@/components/title-bar/ChromeIconButton';
+import { Spinner } from '@/components/ui/spinner';
import { ShareDialog } from '@/features/share/ShareDialog';
import { useAuth } from '@/contexts/AuthContext';
+import { ghostInstallApprovalToken, type InstalledGhost } from '../../../shared/ghost';
+import { installedGhostStoragePart } from '../../../shared/pluginIdentity';
import type { ShareOptions } from '../../../shared/share';
-export function PluginShareButton({ pluginId }: { pluginId: string }) {
+type PluginShareButtonProps =
+ | { pluginId: string; ghost?: never }
+ | { pluginId?: never; ghost: InstalledGhost };
+
+export function PluginShareButton({ pluginId, ghost }: PluginShareButtonProps) {
const { t } = useTranslation();
const { isAuthenticated, dataOwnerGeneration, dataOwnerId } = useAuth();
- const [open, setOpen] = useState(false);
+ const instanceId = ghost ? installedGhostStoragePart(ghost) : null;
+ const version = ghost?.manifest.version;
+ const approvalToken = ghost ? ghostInstallApprovalToken(ghost.approval) : null;
+ const ownerKey = `${dataOwnerId ?? ''}:${dataOwnerGeneration}`;
+ const sourceKey = `${instanceId ?? pluginId}:${ownerKey}`;
+ const [session, setSession] = useState<{ key: string; id: string } | null>(null);
+ const [preparing, setPreparing] = useState(false);
+ const activeSession = instanceId && (!isAuthenticated || session?.key !== sourceKey) ? null : session;
+ const operationId = instanceId ? activeSession?.id ?? null : null;
const trigger = useRef<HTMLButtonElement | null>(null);
const restoringFocus = useRef(false);
+ useEffect(() => {
+ if (instanceId) setSession(null);
+ }, [instanceId, ownerKey, isAuthenticated]);
+ useEffect(() => () => {
+ if (operationId) void window.electronAPI.pluginMarket.releaseLocalShare(operationId).catch(() => undefined);
+ }, [operationId]);
const load = useCallback(
- (options: ShareOptions) => window.electronAPI.pluginMarket.prepareShare(pluginId, options),
- [pluginId],
+ (options: ShareOptions, uploadConfirmed: boolean) => pluginId !== undefined
+ ? window.electronAPI.pluginMarket.prepareShare(pluginId, options)
+ : window.electronAPI.pluginMarket.prepareLocalShare(instanceId!, operationId!, options, { version: version!, approvalToken: approvalToken! }, uploadConfirmed),
+ [pluginId, instanceId, operationId, version, approvalToken],
);
return (
<>
<ChromeIconButton
aria-label={t('sharing.title')}
- tooltip={t('sharing.title')}
+ tooltip={t(instanceId && !isAuthenticated ? 'sharing.loginRequired' : preparing ? 'sharing.localPreparing' : 'sharing.title')}
tooltipSide="bottom"
+ disabled={preparing || (!!instanceId && !isAuthenticated)}
+ aria-busy={preparing || undefined}
onFocus={(event) => {
if (restoringFocus.current) event.preventDefault();
}}
onClick={(event) => {
trigger.current = event.currentTarget;
- setOpen(true);
+ setSession({ key: sourceKey, id: instanceId ? crypto.randomUUID() : pluginId! });
}}
>
- <Share2 size={14} aria-hidden />
+ {preparing ? <Spinner size={14} /> : <Share2 size={14} aria-hidden />}
</ChromeIconButton>
- {open ? (
+ {activeSession ? (
<ShareDialog
- key={`${pluginId}:${dataOwnerId ?? ''}:${dataOwnerGeneration}`}
+ key={sourceKey}
load={load}
allowAttribution={isAuthenticated}
- onClose={() => setOpen(false)}
+ onPreparingChange={setPreparing}
+ confirmation={ghost ? {
+ message: t('sharing.localUploadNotice', { name: ghost.manifest.name, version }),
+ label: t('sharing.uploadLocal'),
+ } : undefined}
+ loadingLabel={instanceId ? t('sharing.localPreparing') : undefined}
+ recipientHint={instanceId ? t('sharing.localRecipientHint') : undefined}
+ onClose={() => setSession(null)}
restoreFocus={() => {
restoringFocus.current = true;
trigger.current?.focus();
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
index 3bf9aaad1d..74eeafda8b 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
@@ -23,7 +23,8 @@ import { leadingSlashInvocation, loadAllCommands, rewriteAgentSkillInvocationFor
import { toast } from '@/lib/toast';
import { getDraft as getWorkspaceDraft, patchDraft, resetDraftWorkspaceTargets } from '@/state/newMakerDraft';
-const { auth, translation, pickAndUpdateGhost } = vi.hoisted(() => ({
+const { auth, translation, pickAndUpdateGhost, catalog } = vi.hoisted(() => ({
+ catalog: { device: null as { deviceId: string; name: string } | null },
pickAndUpdateGhost: vi.fn(),
auth: { user: { membershipKind: 'personal' }, mode: 'local', dataOwnerId: 'navigation-owner' },
translation: {
@@ -32,6 +33,9 @@ const { auth, translation, pickAndUpdateGhost } = vi.hoisted(() => ({
},
}));
+vi.mock('../useCatalogDevice', () => ({ CatalogDeviceScope: ({ children }: { children: (...args: unknown[]) => unknown }) =>
+ children(catalog.device, false, 1, { selected: catalog.device, onSelect: vi.fn(), directory: { candidates: [], online: false, relayOnline: false } }) }));
+
vi.mock('../GhostPagePanelHost', () => ({
GhostPagePanelHost: ({ ghost }: { ghost: { manifest: { id: string } } }) => (
<aside data-testid="replacement-panel">{ghost.manifest.id}</aside>
@@ -95,6 +99,7 @@ const loadDetail = vi.fn<() => Promise<PluginMarketDetail>>();
const listAgentSkills = vi.fn();
beforeEach(() => {
+ catalog.device = null;
vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
auth.mode = 'local';
auth.user.membershipKind = 'personal';
@@ -138,6 +143,13 @@ beforeEach(() => {
});
});
+it('opens a shared package before the selected remote plugin catalogue', async () => {
+ catalog.device = { deviceId: 'remote-computer', name: 'Remote Computer' };
+ render(<MemoryRouter initialEntries={['/plugins?share=' + 's'.repeat(32)]}><GhostPluginPage /></MemoryRouter>);
+ expect(await screen.findByRole('button', { name: 'sharing.localSignIn' })).toBeTruthy();
+ expect(loadDetail).not.toHaveBeenCalled();
+});
+
afterEach(() => {
cleanup();
clearDraft(NEW_MAKER_DRAFT_KEY);
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/LocalPluginShareView.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/LocalPluginShareView.test.tsx
new file mode 100644
index 0000000000..28b00d64e8
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/LocalPluginShareView.test.tsx
@@ -0,0 +1,157 @@
+/** @vitest-environment jsdom */
+// Test value: recipient navigation must require login, wait for an install click,
+// preserve cancellation and discard stale account reads. Public detail tests use
+// market releases, not this fixed manual package. Unit tier: real view, fake IPC.
+// Minimal inputs: one snapshot, a rejected consent and a delayed old-owner read.
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { createIpcError } from '../../../../shared/ipc-errors';
+import { LocalPluginShareView } from '../LocalPluginShareView';
+import type { CatalogDeviceControl } from '../PluginDevicePicker';
+
+const io = vi.hoisted(() => ({ read: vi.fn(), install: vi.fn(), invoke: vi.fn(), confirm: vi.fn(), auth: {
+ isAuthenticated: true, mode: 'cloud', dataOwnerId: 'owner', dataOwnerGeneration: 1,
+} }));
+vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => io.auth }));
+vi.mock('@/components/ui/confirm-dialog-provider', () => ({ useConfirmDialog: () => ({ confirm: io.confirm }) }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+const snapshotId = 's'.repeat(32);
+const snapshot = { schemaVersion: 1, snapshotId, ghostId: 'shared-plugin', name: 'Shared Plugin', description: null, author: null,
+ version: '1.0.0', sha256: 'a'.repeat(64), sizeBytes: 1024, createdAt: '2026-10-28T00:00:00.000Z', icon: null };
+const ghost = { manifest: { id: 'shared-plugin' } };
+beforeEach(() => {
+ io.auth.isAuthenticated = true; io.auth.dataOwnerGeneration = 1;
+ io.read.mockReset().mockResolvedValue(snapshot); io.install.mockReset().mockResolvedValue({ ghost });
+ io.invoke.mockReset(); io.confirm.mockReset().mockResolvedValue(true);
+ vi.stubGlobal('electronAPI', { platform: 'win32', getFullscreenState: async () => false, onFullscreenChange: () => () => {},
+ deviceLink: { invoke: io.invoke },
+ pluginMarket: { localShareDetail: io.read, installLocalShare: io.install } });
+});
+afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
+const view = (onInstalled = vi.fn(), deviceControl?: CatalogDeviceControl) => <MemoryRouter><LocalPluginShareView snapshotId={snapshotId} deviceControl={deviceControl} onBack={vi.fn()} onInstalled={onInstalled} /></MemoryRouter>;
+
+it('does not read a local share before login', () => {
+ io.auth.isAuthenticated = false;
+ render(view());
+ expect(screen.getByRole('button', { name: 'sharing.localSignIn' })).toBeTruthy();
+ expect(io.read).not.toHaveBeenCalled(); expect(io.install).not.toHaveBeenCalled();
+});
+it('only installs the visible fixed version after an explicit click', async () => {
+ const installed = vi.fn(); render(view(installed));
+ expect(await screen.findByText('v1.0.0')).toBeTruthy();
+ expect(io.install).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', { name: 'sharing.localInstallButton' }));
+ await waitFor(() => expect(installed).toHaveBeenCalledWith(ghost));
+ expect(io.install).toHaveBeenCalledWith(snapshotId, snapshot);
+});
+it('keeps a declined permission confirmation as cancellation without reporting installation', async () => {
+ const installed = vi.fn(); io.install.mockRejectedValue(createIpcError('MUTATION_CANCELLED', 'Declined'));
+ render(view(installed)); await screen.findByText('v1.0.0');
+ fireEvent.click(screen.getByRole('button', { name: 'sharing.localInstallButton' }));
+ await waitFor(() => expect(screen.getByRole<HTMLButtonElement>('button', { name: 'sharing.localInstallButton' }).disabled).toBe(false));
+ expect(installed).not.toHaveBeenCalled(); expect(screen.queryByRole('alert')).toBeNull();
+});
+it('does not show an old account response after a new account read finishes', async () => {
+ let finish!: (value: typeof snapshot) => void;
+ io.read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
+ const mounted = render(view());
+ io.auth.dataOwnerGeneration++;
+ io.read.mockResolvedValue({ ...snapshot, name: 'Current Owner Package' });
+ mounted.rerender(view());
+ await screen.findByText('Current Owner Package');
+ await act(async () => { finish(snapshot); });
+ expect(screen.queryByText('Shared Plugin')).toBeNull();
+ expect(screen.getByText('Current Owner Package')).toBeTruthy();
+});
+
+const target = { deviceId: 'target-computer', name: 'Office Computer' };
+const control = (online = true): CatalogDeviceControl => ({ selected: target, onSelect: vi.fn(),
+ directory: { candidates: [], target: undefined, relayOnline: online, online } });
+function remoteHost(supported = true) {
+ io.invoke.mockImplementation(async (_device, channel, [request]) => {
+ if (String(channel).includes('manifest')) return { collections: [{ id: 'plugins', actions: [{ id: 'management:snapshot' }] }] };
+ if (request.actionId === 'management:snapshot') return { effects: [], result: { version: 1, ghosts: [],
+ market: { items: [], customSourceNames: [], unavailableCustomSourceNames: [] }, ...(supported ? { localShares: true } : {}) } };
+ const operationId = request.input.operationId;
+ if (request.actionId === 'management:begin') return { effects: [], result: { operationId, phase: 'confirmation', consent: {
+ requestId: 'consent-request', initiator: 'user', origin: 'local-file', facts: { kind: 'install', name: snapshot.name, version: snapshot.version, permissions: [] },
+ } } };
+ return { effects: [], result: { operationId, phase: 'succeeded' } };
+ });
+}
+it('installs on the chosen device with its consent receipt and never invokes local installation', async () => {
+ remoteHost(); const installed = vi.fn(); render(view(installed, control()));
+ const button = await screen.findByRole<HTMLButtonElement>('button', { name: 'sharing.localInstallButton' });
+ await waitFor(() => expect(button.disabled).toBe(false));
+ vi.useFakeTimers();
+ try {
+ await act(async () => { fireEvent.click(button); });
+ await act(async () => { await vi.advanceTimersByTimeAsync(650); });
+ expect(installed).toHaveBeenCalledWith();
+ } finally { vi.useRealTimers(); }
+ expect(io.install).not.toHaveBeenCalled();
+ expect(io.invoke.mock.calls.every(([id]) => id === target.deviceId)).toBe(true);
+ expect(io.invoke.mock.calls.find(([, , [r]]) => r.actionId === 'management:begin')?.[2][0].input)
+ .toMatchObject({ kind: 'install-share', expectedSnapshot: snapshot });
+ expect(io.confirm).toHaveBeenCalledOnce();
+});
+it.each([false, true])('keeps an offline or unsupported device selected without installing locally (%s)', async online => {
+ remoteHost(false); render(view(vi.fn(), control(online)));
+ await screen.findByText('v1.0.0');
+ if (online) await screen.findByText('sharing.localTargetUnsupported');
+ expect(screen.getByRole<HTMLButtonElement>('button', { name: 'sharing.localInstallButton' }).disabled).toBe(true);
+ expect(screen.getByText(target.name)).toBeTruthy();
+ expect(io.install).not.toHaveBeenCalled();
+});
+
+it('reads the original receipt after an ambiguous begin without sending another install', async () => {
+ remoteHost();
+ const host = io.invoke.getMockImplementation()!;
+ io.invoke.mockImplementation(async (...args) => {
+ if (args[2][0].actionId === 'management:begin') throw new Error('Connection closed after send');
+ return host(...args);
+ });
+ const installed = vi.fn(); render(view(installed, control()));
+ const button = await screen.findByRole<HTMLButtonElement>('button', { name: 'sharing.localInstallButton' });
+ await waitFor(() => expect(button.disabled).toBe(false));
+ vi.useFakeTimers();
+ try {
+ await act(async () => { fireEvent.click(button); });
+ expect(screen.getByText('settings.ghosts.remote.unknown')).toBeTruthy();
+ expect(installed).not.toHaveBeenCalled();
+ await act(async () => { await vi.advanceTimersByTimeAsync(650); });
+ expect(installed).toHaveBeenCalledOnce();
+ const requests = io.invoke.mock.calls.map(([, , [r]]) => r);
+ const begin = requests.filter(r => r.actionId === 'management:begin');
+ expect(begin).toHaveLength(1);
+ expect(requests.find(r => r.actionId === 'management:operation')?.input.operationId).toBe(begin[0].input.operationId);
+ expect(io.install).not.toHaveBeenCalled();
+ } finally { vi.useRealTimers(); }
+});
+
+it('cancels only the original target when the receiver leaves and discards its late result', async () => {
+ remoteHost();
+ const host = io.invoke.getMockImplementation()!;
+ let finish!: (value: unknown) => void;
+ let originalId = '';
+ io.invoke.mockImplementation(async (...args) => {
+ if (args[2][0].actionId === 'management:begin') {
+ originalId = args[2][0].input.operationId;
+ return new Promise(resolve => { finish = resolve; });
+ }
+ return host(...args);
+ });
+ const installed = vi.fn(); const mounted = render(view(installed, control()));
+ const button = await screen.findByRole<HTMLButtonElement>('button', { name: 'sharing.localInstallButton' });
+ await waitFor(() => expect(button.disabled).toBe(false));
+ fireEvent.click(button);
+ await waitFor(() => expect(originalId).not.toBe(''));
+ mounted.unmount();
+ expect(io.invoke.mock.calls.find(([, , [r]]) => r.actionId === 'management:cancel')).toMatchObject([
+ target.deviceId, expect.any(String), [{ input: { operationId: originalId } }],
+ ]);
+ await act(async () => { finish({ effects: [], result: { operationId: originalId, phase: 'succeeded' } }); });
+ expect(installed).not.toHaveBeenCalled();
+ expect(io.install).not.toHaveBeenCalled();
+});
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/PluginShareButton.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/PluginShareButton.test.tsx
new file mode 100644
index 0000000000..130d1ec7e4
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/PluginShareButton.test.tsx
@@ -0,0 +1,151 @@
+/** @vitest-environment jsdom */
+// The existing share button must keep public anonymous sharing while opening
+// local sharing behind explicit upload confirmation. Only auth and native IPC
+// are replaced; the real dialog verifies cancellation, identity and owner changes.
+// Regression: a delayed local preflight used to open the share page before the
+// upload decision. Existing immediate IPC replies missed this visible ordering;
+// unit tests hold that boundary pending and resolve it without real timers.
+// Upload confirmation must show only the notice and confirmation action. The
+// signed-in fixture previously exposed the result page's attribution control
+// before consent; these unit assertions cover that missing visible state.
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import type { InstalledGhost } from '../../../../shared/ghost';
+
+const auth = vi.hoisted(() => ({ isAuthenticated: true, dataOwnerId: 'owner', dataOwnerGeneration: 1 }));
+const ipc = vi.hoisted(() => ({ prepareShare: vi.fn(), prepareLocalShare: vi.fn(), releaseLocalShare: vi.fn() }));
+vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => auth }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+import { PluginShareButton } from '../PluginShareButton';
+
+const ghost: InstalledGhost = {
+ manifest: { schemaVersion: 3, id: 'local-share-test', name: 'Local plugin', version: '1.0.0', entry: 'index.js', kind: 'chip' },
+ namespace: null, namespaceState: 'confirmed', instanceKey: '_root__local-share-test',
+ dir: '/fixture/local-share-test', enabled: true, publishingSource: { kind: 'local', source: 'manual' },
+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
+};
+const material = { title: 'Plugin', url: 'https://share.example.test/s/test', imageSvg: '<svg />' };
+beforeEach(() => {
+ vi.clearAllMocks();
+ Object.assign(auth, { isAuthenticated: true, dataOwnerId: 'owner', dataOwnerGeneration: 1 });
+ ipc.prepareShare.mockResolvedValue(material);
+ ipc.prepareLocalShare.mockImplementation(async (_instance, _operation, _options, _binding, confirmed) =>
+ confirmed ? material : { confirmationRequired: true });
+ ipc.releaseLocalShare.mockResolvedValue(undefined);
+ vi.stubGlobal('electronAPI', { pluginMarket: ipc });
+});
+afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
+
+async function openShare() {
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'sharing.title' })); });
+}
+
+it('keeps public sharing anonymous and uses the existing share dialog', async () => {
+ auth.isAuthenticated = false;
+ render(<PluginShareButton pluginId="public-plugin" />);
+ await openShare();
+ expect(ipc.prepareShare).toHaveBeenCalledWith('public-plugin', { includeAttribution: false });
+ expect(ipc.prepareLocalShare).not.toHaveBeenCalled();
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'sharing.copyLink' })).toBeTruthy();
+});
+
+it('requires upload confirmation and reuses the confirmed opening for attribution', async () => {
+ let finishCheck!: (value: { confirmationRequired: true }) => void;
+ ipc.prepareLocalShare.mockImplementationOnce(() => new Promise(resolve => { finishCheck = resolve; }));
+ render(<PluginShareButton ghost={ghost} />);
+ expect(ipc.prepareLocalShare).not.toHaveBeenCalled();
+ await openShare();
+ expect(ipc.prepareLocalShare.mock.calls[0]?.[4]).toBe(false);
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(document.querySelector('button[aria-busy="true"]')).toBeTruthy();
+ await act(async () => { finishCheck({ confirmationRequired: true }); });
+ expect(screen.getByText('sharing.localUploadNotice')).toBeTruthy();
+ expect(screen.queryByRole('switch')).toBeNull();
+ expect(screen.queryByText('sharing.includeAttribution')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'sharing.copyLink' })).toBeNull();
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'sharing.uploadLocal' })); });
+ expect(ipc.prepareLocalShare).toHaveBeenCalledTimes(2);
+ const [instance, operationId, options, expected, confirmed] = ipc.prepareLocalShare.mock.calls[1];
+ expect(confirmed).toBe(true);
+ expect(instance).toBe('_root__local-share-test');
+ expect(operationId).toEqual(expect.any(String));
+ expect(options).toEqual({ includeAttribution: true });
+ expect(expected).toEqual({ version: '1.0.0', approvalToken: 'approved:00000000-0000-4000-8000-000000000001' });
+ expect(screen.getByRole('button', { name: 'sharing.copyLink' })).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'sharing.uploadLocal' })).toBeNull();
+ await act(async () => { fireEvent.click(screen.getByRole('switch')); });
+ expect(ipc.prepareLocalShare).toHaveBeenLastCalledWith(instance, operationId, { includeAttribution: false }, expected, true);
+ fireEvent.click(screen.getByRole('button', { name: 'sharing.close' }));
+ expect(ipc.releaseLocalShare).toHaveBeenCalledWith(operationId);
+ await openShare();
+ expect(ipc.prepareLocalShare.mock.calls.at(-1)?.[4]).toBe(false);
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'sharing.uploadLocal' })); });
+ expect(ipc.prepareLocalShare.mock.calls.at(-1)?.[1]).not.toBe(operationId);
+ expect(ipc.prepareShare).not.toHaveBeenCalled();
+});
+
+it('does not expose attribution or upload when the user closes before confirmation', async () => {
+ render(<PluginShareButton ghost={ghost} />);
+ await openShare();
+ expect(screen.queryByRole('switch')).toBeNull();
+ expect(ipc.prepareLocalShare.mock.calls.every(call => call[4] === false)).toBe(true);
+ fireEvent.click(screen.getByRole('button', { name: 'sharing.close' }));
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(ipc.prepareLocalShare.mock.calls.every(call => call[4] === false)).toBe(true);
+});
+
+it('skips confirmation for an unchanged uploaded package and creates a new operation each time', async () => {
+ ipc.prepareLocalShare.mockResolvedValue(material);
+ let finishCheck!: (value: typeof material) => void;
+ ipc.prepareLocalShare.mockImplementationOnce(() => new Promise(resolve => { finishCheck = resolve; }));
+ render(<PluginShareButton ghost={ghost} />);
+ await openShare();
+ expect(screen.queryByRole('dialog')).toBeNull();
+ await act(async () => { finishCheck(material); });
+ expect(screen.queryByText('sharing.localUploadNotice')).toBeNull();
+ expect(screen.getByRole('button', { name: 'sharing.copyLink' })).toBeTruthy();
+ const operationId = ipc.prepareLocalShare.mock.calls[0][1];
+ fireEvent.click(screen.getByRole('button', { name: 'sharing.close' }));
+ await openShare();
+ expect(screen.queryByRole('button', { name: 'sharing.uploadLocal' })).toBeNull();
+ expect(ipc.prepareLocalShare.mock.calls.at(-1)?.[1]).not.toBe(operationId);
+ expect(ipc.prepareLocalShare.mock.calls.every(call => call[4] === false)).toBe(true);
+});
+
+it('does not prepare a local package without login', () => {
+ auth.isAuthenticated = false;
+ const { container } = render(<PluginShareButton ghost={ghost} />);
+ const button = container.querySelector('button')!;
+ expect(button.disabled).toBe(true);
+ fireEvent.click(button);
+ expect(ipc.prepareLocalShare).not.toHaveBeenCalled();
+ expect(screen.queryByRole('dialog')).toBeNull();
+});
+
+it('closes the local share on owner change without preparing it for the new owner', async () => {
+ const view = render(<PluginShareButton ghost={ghost} />);
+ await openShare();
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'sharing.uploadLocal' })); });
+ const operationId = ipc.prepareLocalShare.mock.calls[0][1];
+ Object.assign(auth, { dataOwnerId: 'another-owner', dataOwnerGeneration: 2 });
+ view.rerender(<PluginShareButton ghost={ghost} />);
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(ipc.prepareLocalShare).toHaveBeenCalledTimes(2);
+ expect(ipc.releaseLocalShare).toHaveBeenCalledWith(operationId);
+});
+
+it('does not open a delayed local confirmation after the owner changes', async () => {
+ let finishCheck!: (value: { confirmationRequired: true }) => void;
+ ipc.prepareLocalShare.mockImplementationOnce(() => new Promise(resolve => { finishCheck = resolve; }));
+ const view = render(<PluginShareButton ghost={ghost} />);
+ await openShare();
+ const operationId = ipc.prepareLocalShare.mock.calls[0][1];
+ Object.assign(auth, { dataOwnerId: 'another-owner', dataOwnerGeneration: 2 });
+ view.rerender(<PluginShareButton ghost={ghost} />);
+ await act(async () => { finishCheck({ confirmationRequired: true }); });
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(document.querySelector('button[aria-busy="true"]')).toBeNull();
+ expect(ipc.prepareLocalShare).toHaveBeenCalledOnce();
+ expect(ipc.releaseLocalShare).toHaveBeenCalledWith(operationId);
+});
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/remotePluginManagementClient.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/remotePluginManagementClient.test.ts
index 323e1892ed..ec407fac0e 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/remotePluginManagementClient.test.ts
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/remotePluginManagementClient.test.ts
@@ -13,6 +13,11 @@ const snapshot = {
market: { items: [], customSourceNames: [], unavailableCustomSourceNames: [] },
};
describe('remote project response boundaries', () => {
+ it('requires an explicit fixed-share installation capability from the selected Host', () => {
+ expect(parsePluginManagementSnapshot(snapshot).localShares).toBeUndefined();
+ expect(parsePluginManagementSnapshot({ ...snapshot, localShares: true }).localShares).toBe(true);
+ expect(() => parsePluginManagementSnapshot({ ...snapshot, localShares: 'true' })).toThrow('INVALID_RESPONSE');
+ });
it('distinguishes old Host capability absence from a supported empty project catalogue', () => {
expect(parsePluginManagementSnapshot(snapshot).projects).toBeUndefined();
expect(parsePluginManagementSnapshot({ ...snapshot, projects: [] }).projects).toEqual([]);
diff --git a/apps/desktop/src/renderer/features/plugin/remotePluginManagementClient.ts b/apps/desktop/src/renderer/features/plugin/remotePluginManagementClient.ts
index 1720df65b7..3d443b793f 100644
--- a/apps/desktop/src/renderer/features/plugin/remotePluginManagementClient.ts
+++ b/apps/desktop/src/renderer/features/plugin/remotePluginManagementClient.ts
@@ -95,6 +95,7 @@ export function parsePluginManagementSnapshot(value: unknown): PluginManagementS
) ||
new Set(data.projects.map((project) => project.id)).size !== data.projects.length)) ||
(data.projectBrowse !== undefined && data.projectBrowse !== true) ||
+ (data.localShares !== undefined && data.localShares !== true) ||
!data.ghosts.every(
(g) =>
typeof g.instanceKey === 'string' &&
diff --git a/apps/desktop/src/renderer/features/share/ShareDialog.tsx b/apps/desktop/src/renderer/features/share/ShareDialog.tsx
index 7a38b26d73..7bb27fd9f1 100644
--- a/apps/desktop/src/renderer/features/share/ShareDialog.tsx
+++ b/apps/desktop/src/renderer/features/share/ShareDialog.tsx
@@ -12,7 +12,7 @@ import { copyPngBlobToClipboard, svgToPngBlob } from '@/lib/rasterizeToImage';
import { blobToDataUrl } from '@/lib/annotationBurnIn';
import { toast } from '@/lib/toast';
import { extractIpcError } from '@/utils/ipcError';
-import type { ShareContent, ShareOptions } from '../../../shared/share';
+import type { ShareContent, ShareOptions, SharePreparation } from '../../../shared/share';
/** Manual link + image output, independent of the business and future platform SDKs. */
export function ShareDialog({
@@ -20,17 +20,28 @@ export function ShareDialog({
onClose,
restoreFocus,
allowAttribution = false,
+ confirmation,
+ onPreparingChange,
+ loadingLabel,
+ recipientHint,
}: {
- load: (options: ShareOptions) => Promise<ShareContent>;
+ load: (options: ShareOptions, uploadConfirmed: boolean) => Promise<SharePreparation>;
onClose: () => void;
restoreFocus?: () => void;
allowAttribution?: boolean;
+ confirmation?: { message: string; label: string };
+ onPreparingChange?: (preparing: boolean) => void;
+ loadingLabel?: string;
+ recipientHint?: string;
}) {
const { t } = useTranslation();
+ const changedErrorKey = confirmation ? 'sharing.localChanged' : 'settings.ghosts.remote.changed';
const linkId = useId();
const attributionId = useId();
const contentRef = useRef<HTMLDivElement | null>(null);
const [includeAttribution, setIncludeAttribution] = useState(allowAttribution);
+ const [confirmationRequired, setConfirmationRequired] = useState(false);
+ const [uploadConfirmed, setUploadConfirmed] = useState(false);
const close = () => {
alive.current = false;
generation.current += 1;
@@ -42,19 +53,31 @@ export function ShareDialog({
const [errorKey, setErrorKey] = useState<string | null>(null);
const [revision, setRevision] = useState(0);
const [busy, setBusy] = useState<'link' | 'copy' | 'save' | null>(null);
+ const preparing = !!confirmation && loading && !confirmationRequired && !uploadConfirmed && !content && !errorKey;
const alive = useRef(false);
const busyRef = useRef(false);
const generation = useRef(0);
useEffect(() => {
+ onPreparingChange?.(preparing);
+ return () => onPreparingChange?.(false);
+ }, [onPreparingChange, preparing]);
+ useEffect(() => {
+ if (confirmationRequired && !uploadConfirmed) return;
alive.current = true;
const current = ++generation.current;
setLoading(true);
setErrorKey(null);
busyRef.current = true;
setBusy(null);
- void load({ includeAttribution: allowAttribution && includeAttribution })
+ void load({ includeAttribution: allowAttribution && includeAttribution }, uploadConfirmed)
.then(async (value) => {
if (!alive.current || generation.current !== current) return;
+ if ('confirmationRequired' in value) {
+ setConfirmationRequired(true);
+ setLoading(false);
+ busyRef.current = false;
+ return;
+ }
const imageUrl = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(value.imageSvg)}`;
const image = new Image();
image.src = imageUrl;
@@ -77,9 +100,11 @@ export function ShareDialog({
setErrorKey(
code === 'SHARE_NOT_CONFIGURED'
? 'sharing.notConfigured'
- : code === 'SHARE_UNAVAILABLE'
- ? 'sharing.unavailable'
- : 'sharing.loadFailed',
+ : code === 'PRECONDITION_FAILED'
+ ? changedErrorKey
+ : code === 'SHARE_UNAVAILABLE'
+ ? 'sharing.unavailable'
+ : 'sharing.loadFailed',
);
setLoading(false);
busyRef.current = false;
@@ -88,7 +113,7 @@ export function ShareDialog({
alive.current = false;
generation.current += 1;
};
- }, [load, revision, allowAttribution, includeAttribution]);
+ }, [load, revision, allowAttribution, includeAttribution, confirmationRequired, uploadConfirmed, changedErrorKey]);
const run = async (action: 'link' | 'copy' | 'save') => {
if (!content || loading || errorKey || busyRef.current) return;
@@ -133,7 +158,7 @@ export function ShareDialog({
};
return (
<Dialog.Root
- open
+ open={!preparing}
onOpenChange={(open) => {
if (!open) close();
}}
@@ -173,7 +198,7 @@ export function ShareDialog({
<X size={16} aria-hidden />
</Button>
</Tip>
- {allowAttribution ? (
+ {allowAttribution && !confirmationRequired ? (
<div className="mt-4 flex items-center justify-between gap-4">
<label htmlFor={attributionId} className="text-13 text-[var(--text-secondary)]">
{t('sharing.includeAttribution')}
@@ -191,7 +216,16 @@ export function ShareDialog({
/>
</div>
) : null}
- {errorKey ? (
+ {confirmationRequired && confirmation ? (
+ <div className="mt-5">
+ <p className="text-13 leading-relaxed text-[var(--text-secondary)]">{confirmation.message}</p>
+ <Button variant="cta" className="mt-4" onClick={() => {
+ setConfirmationRequired(false);
+ setUploadConfirmed(true);
+ }}>{confirmation.label}</Button>
+ </div>
+ ) : null}
+ {!confirmationRequired && errorKey ? (
<div role="alert" className="mt-5 text-13">
<p>{t(errorKey)}</p>
{errorKey === 'sharing.loadFailed' ? (
@@ -205,7 +239,7 @@ export function ShareDialog({
) : null}
</div>
) : null}
- {content || !errorKey ? (
+ {!confirmationRequired && (content || !errorKey) ? (
<>
<div
aria-busy={loading || undefined}
@@ -227,7 +261,7 @@ export function ShareDialog({
className="absolute inset-0 flex items-center justify-center gap-2 text-13"
>
<Spinner size={16} />
- {t('sharing.loading')}
+ {loadingLabel ?? t('sharing.loading')}
</div>
)}
</div>
@@ -291,7 +325,7 @@ export function ShareDialog({
</div>
</div>
<p className="mt-3 text-12 leading-relaxed text-[var(--text-tertiary)]">
- {t('sharing.recipientHint')}
+ {recipientHint ?? t('sharing.recipientHint')}
</p>
</>
) : null}
diff --git a/apps/desktop/src/renderer/features/share/__tests__/ShareDialog.test.tsx b/apps/desktop/src/renderer/features/share/__tests__/ShareDialog.test.tsx
index 997f9ef9d1..4825d68c21 100644
--- a/apps/desktop/src/renderer/features/share/__tests__/ShareDialog.test.tsx
+++ b/apps/desktop/src/renderer/features/share/__tests__/ShareDialog.test.tsx
@@ -49,6 +49,19 @@ afterEach(() => {
vi.unstubAllGlobals();
});
describe('manual sharing output', () => {
+ // A changed local package must ask for a new check/confirmation, rather than
+ // offer a retry of the obsolete confirmed package. The old output tests only
+ // covered clipboard/native-save failures after successful material loading.
+ it('explains changed content and requires reopening instead of retrying the old confirmation', async () => {
+ const changed = vi.fn().mockResolvedValueOnce({ confirmationRequired: true })
+ .mockRejectedValueOnce(new Error('[PRECONDITION_FAILED] Package changed'));
+ render(<ShareDialog load={changed} confirmation={{ message: 'Upload notice', label: 'Upload' }} onClose={vi.fn()} />);
+ const confirm = await screen.findByRole('button', { name: 'Upload' });
+ fireEvent.click(confirm);
+ await screen.findByText('sharing.localChanged');
+ expect(screen.queryByRole('button', { name: 'sharing.retry' })).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Upload' })).toBeNull();
+ });
it('does not copy a picture that finishes rendering after dismissal', async () => {
let finish!: (blob: Blob) => void;
io.png.mockImplementationOnce(
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index b0b00f41e8..0222399890 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -17885,6 +17885,22 @@
"contextReferences": "Context references:"
},
"sharing": {
+ "loginRequired": "Sign In to Share",
+ "localUploadNotice": "Upload “{{name}}” v{{version}} to Cindy so signed-in recipients can download this version. Sharing does not publish it to the marketplace.",
+ "uploadLocal": "Upload and Share Plugin",
+ "localPreparing": "Uploading plugin and preparing sharing material…",
+ "localRecipientHint": "Recipients sign in to Cindy to view and install this exact version.",
+ "localLoading": "Reading shared plugin…",
+ "localPackage": "Local Share",
+ "localInstallTarget": "Install on",
+ "localTargetUnsupported": "Update Cindy on “{{device}}” to install shared local plugins.",
+ "localInstallButton": "Install v{{version}}",
+ "localInstalling": "Installing plugin…",
+ "localVersionNotice": "This link keeps the version saved when it was shared. Review the plugin’s permissions before installation.",
+ "localSignIn": "Sign In to View",
+ "localOpenHint": "Sign in to Cindy to view and install this shared plugin.",
+ "localReadFailed": "Could not read this shared plugin",
+ "localChanged": "The plugin has changed. Close this window and share it again.",
"includeAttribution": "Include my name and avatar",
"recipientHint": "Open the link or scan the image to view the plugin. Continue in Cindy on a computer.",
"linkLabel": "Share link",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 298dcea952..e5ea0adffa 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -17825,6 +17825,22 @@
"contextReferences": "参考資料:"
},
"sharing": {
+ "loginRequired": "ログインして共有",
+ "localUploadNotice": "「{{name}}」v{{version}} を Cindy にアップロードします。受信者はログイン後にこのバージョンをダウンロードできます。マーケットには公開されません。",
+ "uploadLocal": "アップロードして共有",
+ "localPreparing": "プラグインをアップロードして共有を準備中…",
+ "localRecipientHint": "受信者は Cindy にログインして、共有されたバージョンを確認しインストールできます。",
+ "localLoading": "共有プラグインを読み込み中…",
+ "localPackage": "ローカル共有",
+ "localInstallTarget": "インストール先",
+ "localTargetUnsupported": "共有されたローカルプラグインをインストールするには、「{{device}}」の Cindy を更新してください。",
+ "localInstallButton": "v{{version}} をインストール",
+ "localInstalling": "プラグインをインストール中…",
+ "localVersionNotice": "このリンクには共有時のバージョンが保存されています。インストール前にプラグインの権限を確認できます。",
+ "localSignIn": "ログインして確認",
+ "localOpenHint": "Cindy にログインすると、共有されたプラグインの確認とインストールができます。",
+ "localReadFailed": "共有されたプラグインを読み込めませんでした",
+ "localChanged": "プラグインが変更されました。このウィンドウを閉じて、もう一度共有してください。",
"includeAttribution": "自分の名前とアイコンを付ける",
"recipientHint": "リンクを開くか画像のコードを読み取ると、プラグインを確認できます。利用はパソコン版Cindyで続けてください。",
"linkLabel": "共有リンク",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 536991f92d..5b2f49bb84 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -17825,6 +17825,22 @@
"contextReferences": "참고 자료:"
},
"sharing": {
+ "loginRequired": "로그인 후 공유",
+ "localUploadNotice": "“{{name}}” v{{version}}을 Cindy에 업로드합니다. 받는 사람은 로그인 후 이 버전을 다운로드할 수 있습니다. 플러그인 마켓에는 게시되지 않습니다.",
+ "uploadLocal": "플러그인 업로드 및 공유",
+ "localPreparing": "플러그인 업로드 및 공유 준비 중…",
+ "localRecipientHint": "받는 사람은 Cindy에 로그인하여 공유된 버전을 확인하고 설치할 수 있습니다.",
+ "localLoading": "공유 플러그인 불러오는 중…",
+ "localPackage": "로컬 공유",
+ "localInstallTarget": "설치할 기기",
+ "localTargetUnsupported": "공유된 로컬 플러그인을 설치하려면 “{{device}}”의 Cindy를 업데이트하세요。",
+ "localInstallButton": "v{{version}} 설치",
+ "localInstalling": "플러그인 설치 중…",
+ "localVersionNotice": "이 링크에는 공유 당시의 버전이 저장되어 있습니다. 설치 전에 플러그인 권한을 확인할 수 있습니다.",
+ "localSignIn": "로그인하여 보기",
+ "localOpenHint": "Cindy에 로그인하면 공유된 플러그인을 확인하고 설치할 수 있습니다.",
+ "localReadFailed": "공유된 플러그인을 불러올 수 없습니다",
+ "localChanged": "플러그인이 변경되었습니다. 이 창을 닫고 다시 공유하세요.",
"includeAttribution": "내 이름과 프로필 사진 포함",
"recipientHint": "링크를 열거나 이미지의 코드를 스캔해 플러그인을 확인하고, 컴퓨터의 Cindy에서 사용하세요.",
"linkLabel": "공유 링크",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 24bd342bc9..b5c6c25c9c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -17825,6 +17825,22 @@
"contextReferences": "参考资料:"
},
"sharing": {
+ "loginRequired": "登录后分享",
+ "localUploadNotice": "将「{{name}}」v{{version}} 上传至 Cindy,供已登录的接收者下载此版本。分享不会将插件上架到市场。",
+ "uploadLocal": "上传并分享插件",
+ "localPreparing": "正在上传插件并生成分享…",
+ "localRecipientHint": "接收者需在 Cindy 中登录,查看并安装本次分享的版本。",
+ "localLoading": "正在读取插件…",
+ "localPackage": "本地分享",
+ "localInstallTarget": "安装到哪台设备",
+ "localTargetUnsupported": "请更新「{{device}}」上的 Cindy 后,再安装分享的本地插件。",
+ "localInstallButton": "安装 v{{version}}",
+ "localInstalling": "正在安装插件…",
+ "localVersionNotice": "此链接保留分享时的版本。安装前会显示插件权限,由你确认。",
+ "localSignIn": "登录并查看",
+ "localOpenHint": "登录 Cindy 后,可查看并安装本次分享的插件。",
+ "localReadFailed": "无法读取本次分享的插件",
+ "localChanged": "插件已发生变化,请关闭此窗口后重新分享。",
"includeAttribution": "附上我的昵称和头像",
"recipientHint": "接收者可打开链接或扫描图片查看插件,在电脑端 Cindy 中使用。",
"linkLabel": "分享链接",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 4c7c0c0d1d..4781baa0b1 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -17825,6 +17825,22 @@
"contextReferences": "參考資料:"
},
"sharing": {
+ "loginRequired": "登入後分享",
+ "localUploadNotice": "將「{{name}}」v{{version}} 上傳至 Cindy,供已登入的接收者下載此版本。分享不會將插件上架到市場。",
+ "uploadLocal": "上傳並分享插件",
+ "localPreparing": "正在上傳插件並產生分享…",
+ "localRecipientHint": "接收者需在 Cindy 中登入,查看並安裝本次分享的版本。",
+ "localLoading": "正在讀取插件…",
+ "localPackage": "本機分享",
+ "localInstallTarget": "安裝到哪台裝置",
+ "localTargetUnsupported": "請更新「{{device}}」上的 Cindy 後,再安裝分享的本機插件。",
+ "localInstallButton": "安裝 v{{version}}",
+ "localInstalling": "正在安裝插件…",
+ "localVersionNotice": "此連結保留分享時的版本。安裝前會顯示插件權限,由你確認。",
+ "localSignIn": "登入並查看",
+ "localOpenHint": "登入 Cindy 後,即可查看並安裝本次分享的插件。",
+ "localReadFailed": "無法讀取本次分享的插件",
+ "localChanged": "插件已發生變更,請關閉此視窗後重新分享。",
"includeAttribution": "附上我的暱稱和頭像",
"recipientHint": "對方可開啟連結或掃描圖片查看插件,在電腦版 Cindy 中使用。",
"linkLabel": "分享連結",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index ff4f531a60..79d4012242 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1669,6 +1669,10 @@ interface ElectronAPI {
snapshot: () => Promise<import('../shared/pluginMarket').PluginMarketSnapshot>;
detail: (pluginId: string) => Promise<import('../shared/pluginMarket').PluginMarketDetail>;
prepareShare: (pluginId: string, options?: import('../shared/share').ShareOptions) => Promise<import('../shared/share').ShareContent>;
+ prepareLocalShare: (instanceId: string, operationId: string, options: import('../shared/share').ShareOptions, expected: import('../shared/share').LocalPluginShareBinding, uploadConfirmed: boolean) => Promise<import('../shared/share').SharePreparation>;
+ localShareDetail: (snapshotId: string) => Promise<import('@cindy/plugin-protocol').LocalPluginShareSnapshot>;
+ installLocalShare: (snapshotId: string, expected: import('@cindy/plugin-protocol').LocalPluginShareSnapshot) => Promise<{ ghost: import('../shared/ghost').InstalledGhost }>;
+ releaseLocalShare: (operationId: string) => Promise<void>;
localIcons: (
requests: import('../shared/pluginMarket').PluginMarketLocalIconRequest[],
) => Promise<import('../shared/pluginMarket').PluginMarketLocalIconResult[]>;
@@ -3083,6 +3087,7 @@ interface ElectronAPI {
| { type: 'chat-invite-malformed' }
| { type: 'provider-share-join'; link: string }
| { type: 'plugin'; pluginId: string }
+ | { type: 'local-plugin-share'; snapshotId: string }
| { type: 'settings'; tab: 'voice-input' | 'providers' | 'billing' | 'remote-control'; connect?: string; intent?: 'topup' },
) => void,
) => () => void;
@@ -3105,6 +3110,7 @@ interface ElectronAPI {
| { type: 'chat-invite-malformed' }
| { type: 'provider-share-join'; link: string }
| { type: 'plugin'; pluginId: string }
+ | { type: 'local-plugin-share'; snapshotId: string }
| { type: 'settings'; tab: 'voice-input' | 'providers' | 'billing' | 'remote-control'; connect?: string; intent?: 'topup' }
| null
>;
diff --git a/apps/desktop/src/shared/pluginManagement.ts b/apps/desktop/src/shared/pluginManagement.ts
index ea8f0dd948..804b78a292 100644
--- a/apps/desktop/src/shared/pluginManagement.ts
+++ b/apps/desktop/src/shared/pluginManagement.ts
@@ -26,6 +26,8 @@ export interface PluginManagementSnapshot {
projectBrowse?: true;
hostPreferences?: true;
settingsPage?: true;
+ /** The Host can install an authenticated immutable local-package share. */
+ localShares?: true;
}
export interface PluginManagementReceipt {
operationId: string;
diff --git a/apps/desktop/src/shared/share.ts b/apps/desktop/src/shared/share.ts
index f963930a5a..22ff183cf4 100644
--- a/apps/desktop/src/shared/share.ts
+++ b/apps/desktop/src/shared/share.ts
@@ -6,6 +6,15 @@ export interface ShareContent {
attribution?: { displayName: string };
}
+/** A local package is only uploaded after the caller confirms this result. */
+export type SharePreparation = ShareContent | { confirmationRequired: true };
+
export interface ShareOptions {
includeAttribution: boolean;
}
+
+/** Binds the clicked local installation without accepting a renderer filesystem path. */
+export interface LocalPluginShareBinding {
+ version: string;
+ approvalToken: string;
+}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 151886a462..b4baea9c80 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -3621,6 +3621,51 @@ Share Server 在创建时保存已验签的分享者 `membershipId` 与身份权
本版分享接收限于插件页选择本机且目录正常的情况;不承接远程电脑的分享导航或断线恢复,不自动切换所选电脑。组织目录不可用时继续遵守未下发条目不读取详情的既有限制;历史或跨区域公开编号的解析也可能被该限制拒绝,本版不新增解析入口或放宽访问边界。
+## 本地插件按次分享
+
+公共 `kind=plugin`、`cindy://plugin/<pluginId>` 及其链接复用、版本选择和安装规则保留。
+本地分享另用 `kind=local-plugin`、随机 `snapshotId` 和
+`cindy://plugin-share/<snapshotId>`;只导航,拒绝 query、fragment、包 URL 和自动安装参数,
+沿原冷启动与登录续接进入独立分享详情,优先于本机/远程目录分支。接收者使用原设备选择器选择安装电脑;离线或不支持的目标不可安装,不自动切回本机。不新增 Mobile 入口。
+
+两仓 `packages/plugin-protocol/src/localSharing.ts` 同步维护上传、固定快照与交付校验,
+不修改已有 manifest、Release 或来源枚举。每次打开本地分享面板生成新操作;用户明确开始后,
+Main 先用原一致性读取入口核对已批准的本地实例,绑定版本、批准回执、内容摘要与原登录身份;
+需要上传且取得确认后才压缩固定包。
+普通 Access Token 用于创建、查看、图片和下载;关闭署名只隐藏姓名,不转匿名。
+同一面板重试和署名切换复用原包,新的分享操作始终独立;ready 包不跟随本地文件或后来版本。
+
+逻辑分享与包存储分开:同一内容的快照打包采用稳定条目顺序与 ZIP 时间戳,保留实际文件、权限、
+空目录与签名字节。新的操作仍创建新的 snapshotId;相同包可指向同一 OSS 对象,服务端命中本人
+已验证的相同内容摘要时,check 直接返回 ready,客户端核对本次内容与身份后省略压缩、PUT/commit,
+继续创建本轮分享素材。同版本内容改变不能复用;不凭其他用户包的摘要跳过上传验证。
+本地分享先核对当前包与服务端复用结果:ready 时直接生成新链接,不再确认上传;需要传包时
+返回 `confirmationRequired`,原分享弹窗取得明确确认后才传 `uploadConfirmed: true` 执行 PUT。
+
+检查阶段仅稳定读取文件计算分享内容摘要,调用新增 `POST /api/local-plugin-shares/check`,
+不压缩 ZIP、不写上传包。命中本人已验证内容时直接返回本次新快照,免确认和上传;
+未命中才确认后打包,打包内容必须仍与确认前摘要一致。服务端从实际归档重新计算
+`contentSha256`,精确 ZIP `sha256` 继续负责传输和安装校验,版本号不能替代内容判据。
+原投稿恢复保存的 `contentSha256` 编码不变,分享使用独立版本化摘要,不改其持久状态。
+两仓增量协议同步,旧 ZIP 上传请求可省略新增摘要字段;服务端先部署检查能力,
+新客户端访问不支持检查的服务端时报告失败,不自动上传或回退成先压缩的检查。
+确认前只发送内容摘要,不发送包字节;不新增客户端长期上传记录。
+
+可信 renderer 的新增 IPC 为 `plugin-market:prepare-local-share`、`release-local-share`、
+`local-share-detail` 和 `install-local-share`;不加入 device-link allowlist,不接收文件路径、
+服务地址或用户身份。下载只取固定服务签发的该快照票据,核对大小、SHA、ghostId 和版本后,
+复用本地包的真实权限确认、root/manual 安装/更新锁及 durable receipt。换源必须沿原确认,
+不写市场更新订阅,不改写 namespace、签名或 `minCindyVersion` 策略;取消不报告安装完成。
+临时包使用独立目录,失败、释放面板、窗口关闭及退出清理;切换账号使在途结果失效。
+
+需先部署支持独立快照与增量表的 Plugin Server,再部署本地模块的 Share Server,最后发布客户端。
+旧客户端不认识新深链,不得降为公共安装;新客户端连旧服务只报告能力不可用。
+旧服务与新增表可滚动共存,回退入口不改已有本地包或公共记录;已生成的新链接需要支持本地模块的服务。
+远程插件 `management:snapshot` 增量返回可选 `localShares: true`,新控制端只在明确声明后提供固定包安装。`management:begin` 新增 `kind=install-share` 与 `expectedSnapshot`,不接受包 URL、token 或目标路径;目标宿主使用自己的登录态换取下载凭据,复核快照/摘要/大小,再进入原手动安装事务。权限确认、取消和结果查询复用原 operationId 回执;断连只查原操作,切账号后丢弃旧结果。旧端缺能力时提示更新;旧控制端忽略新能力字段。无新增远程 channel 或权限扩展。
+
+相关回归:`localSharing.test.ts`、`deepLink.test.ts`、`ghostLocalInstallIdentity.test.ts`、
+`LocalPluginShareView.test.tsx` 和 `scripts/fixtures/local-plugin-sharing/`。
+
## 伙伴关联项目
`teammates` 增加 `settings:<botId>/projects` 与其项目详情资源。使用既有 list/form/toggle 原语,
diff --git a/packages/plugin-protocol/src/index.ts b/packages/plugin-protocol/src/index.ts
index ddc24568b9..78c99568a9 100644
--- a/packages/plugin-protocol/src/index.ts
+++ b/packages/plugin-protocol/src/index.ts
@@ -6,3 +6,4 @@ export * from './memberUpload.js';
export * from './usage.js';
export * from './secretCheck.js';
export * from './publicPresentation.js';
+export * from './localSharing.js';
diff --git a/packages/plugin-protocol/src/localSharing.ts b/packages/plugin-protocol/src/localSharing.ts
new file mode 100644
index 0000000000..2c2427558b
--- /dev/null
+++ b/packages/plugin-protocol/src/localSharing.ts
@@ -0,0 +1,130 @@
+import { httpsUrl, isoDate, object, PluginProtocolError, sha256, string } from './internal/parse.js';
+import { parsePluginObjectUrl, type PluginObjectUrlOptions } from './deliveryObjectUrl.js';
+
+export const LOCAL_PLUGIN_SHARE_MAX_BYTES = 128 * 1024 * 1024;
+
+/** Identical framing on disk and in a verified archive, without ZIP compression. */
+export function encodeLocalPluginShareContent(
+ files: readonly { path: string; sha256: string; unixPermissions: number }[],
+ emptyDirectories: readonly string[],
+): string {
+ const entries = files.map(file => [file.path, file.sha256, 0o100000 | (file.unixPermissions & 0o777)] as const)
+ .sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
+ return JSON.stringify(['cindy-local-share-content-v1', emptyDirectories.slice().sort(), entries]);
+}
+
+export const isLocalPluginSnapshotId = (value: unknown): value is string =>
+ typeof value === 'string' && /^[A-Za-z0-9_-]{32}$/.test(value);
+
+export interface LocalPluginShareSnapshot {
+ schemaVersion: 1;
+ snapshotId: string;
+ ghostId: string;
+ name: string;
+ description: string | null;
+ author: string | null;
+ version: string;
+ sha256: string;
+ contentSha256?: string;
+ sizeBytes: number;
+ createdAt: string;
+ icon: string | null;
+}
+
+export interface LocalPluginShareUpload {
+ snapshotId: string;
+ status: 'uploading' | 'validating' | 'ready' | 'failed' | 'expired';
+ putUrl?: string;
+ headers?: Record<string, string>;
+ expiresAt: string;
+ snapshot?: LocalPluginShareSnapshot;
+}
+
+export type LocalPluginShareCheck =
+ | { status: 'upload_required'; contentSha256: string }
+ | { status: 'ready'; contentSha256: string; snapshot: LocalPluginShareSnapshot };
+
+export function parseCheckLocalPluginShare(value: unknown) {
+ const row = object(value, 'localShareCheck');
+ if (Object.keys(row).some(key => !['operationId', 'contentSha256'].includes(key)))
+ throw new PluginProtocolError('Unknown local share check field');
+ const operationId = string(row.operationId, 'operationId', 128);
+ if (!/^[A-Za-z0-9_-]{16,128}$/.test(operationId)) throw new PluginProtocolError('Invalid operationId');
+ return { operationId, contentSha256: sha256(row.contentSha256, 'contentSha256') };
+}
+
+export function parseLocalPluginShareCheck(value: unknown): LocalPluginShareCheck {
+ const row = object(value, 'localShareCheck');
+ const contentSha256 = sha256(row.contentSha256, 'contentSha256');
+ if (row.status === 'upload_required') return { status: 'upload_required', contentSha256 };
+ if (row.status !== 'ready') throw new PluginProtocolError('Invalid local share check status');
+ const snapshot = parseLocalPluginShareSnapshot(row.snapshot);
+ if (snapshot.contentSha256 !== contentSha256) throw new PluginProtocolError('Content identity changed');
+ return { status: 'ready', contentSha256, snapshot };
+}
+
+export function parsePrepareLocalPluginShare(value: unknown) {
+ const row = object(value, 'localShare');
+ if (Object.keys(row).some(key => !['operationId', 'sha256', 'sizeBytes', 'contentSha256'].includes(key)))
+ throw new PluginProtocolError('Unknown local share field');
+ const operationId = string(row.operationId, 'operationId', 128);
+ if (!/^[A-Za-z0-9_-]{16,128}$/.test(operationId)) throw new PluginProtocolError('Invalid operationId');
+ if (!Number.isSafeInteger(row.sizeBytes) || (row.sizeBytes as number) <= 0 || (row.sizeBytes as number) > LOCAL_PLUGIN_SHARE_MAX_BYTES)
+ throw new PluginProtocolError('Invalid local package size');
+ return { operationId, sha256: sha256(row.sha256, 'sha256'), sizeBytes: row.sizeBytes as number,
+ ...(row.contentSha256 !== undefined ? { contentSha256: sha256(row.contentSha256, 'contentSha256') } : {}) };
+}
+
+export function parseLocalPluginShareSnapshot(value: unknown): LocalPluginShareSnapshot {
+ const row = object(value, 'localShare');
+ if (row.schemaVersion !== 1 || !isLocalPluginSnapshotId(row.snapshotId)) throw new PluginProtocolError('Invalid local share snapshot');
+ if (!Number.isSafeInteger(row.sizeBytes) || (row.sizeBytes as number) <= 0 || (row.sizeBytes as number) > LOCAL_PLUGIN_SHARE_MAX_BYTES)
+ throw new PluginProtocolError('Invalid local package size');
+ const nullable = (value: unknown, name: string, max: number) => value === null || value === '' ? null : string(value, name, max);
+ const icon = row.icon === null ? null : string(row.icon, 'icon', Math.ceil(512 * 1024 / 3) * 4 + 32);
+ if (icon !== null && !/^data:image\/(png|jpeg|webp|gif);base64,[A-Za-z0-9+/]+={0,2}$/.test(icon)) throw new PluginProtocolError('Invalid snapshot icon');
+ return {
+ schemaVersion: 1, snapshotId: row.snapshotId, ghostId: string(row.ghostId, 'ghostId', 128),
+ name: string(row.name, 'name', 256), description: nullable(row.description, 'description', 10_000),
+ author: nullable(row.author, 'author', 256), version: string(row.version, 'version', 128),
+ sha256: sha256(row.sha256, 'sha256'), sizeBytes: row.sizeBytes as number,
+ ...(row.contentSha256 !== undefined ? { contentSha256: sha256(row.contentSha256, 'contentSha256') } : {}),
+ createdAt: isoDate(row.createdAt, 'createdAt'), icon,
+ };
+}
+
+export function parseLocalPluginShareUpload(value: unknown, options?: PluginObjectUrlOptions): LocalPluginShareUpload {
+ const row = object(value, 'upload');
+ if (!isLocalPluginSnapshotId(row.snapshotId) || !['uploading', 'validating', 'ready', 'failed', 'expired'].includes(String(row.status)))
+ throw new PluginProtocolError('Invalid local share upload');
+ const result: LocalPluginShareUpload = {
+ snapshotId: row.snapshotId, status: row.status as LocalPluginShareUpload['status'], expiresAt: isoDate(row.expiresAt, 'expiresAt'),
+ };
+ if (row.status === 'ready') {
+ result.snapshot = parseLocalPluginShareSnapshot(row.snapshot);
+ if (result.snapshot.snapshotId !== result.snapshotId) throw new PluginProtocolError('Snapshot identity changed');
+ }
+ if (row.putUrl !== undefined) {
+ if (row.status !== 'uploading') throw new PluginProtocolError('Unexpected upload ticket');
+ const url = new URL(string(row.putUrl, 'putUrl', 8192));
+ const development = url.protocol === 'http:' && url.origin === options?.developmentObjectOrigin &&
+ ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) && url.pathname === '/dev-local/member-upload';
+ if (url.username || url.password || url.hash || (!development && url.protocol !== 'https:')) throw new PluginProtocolError('Invalid upload URL');
+ result.putUrl = development ? row.putUrl as string : httpsUrl(row.putUrl, 'putUrl');
+ const headers = object(row.headers, 'headers');
+ const entries = Object.entries(headers);
+ if (entries.length !== 2 || entries.some(([key, value]) =>
+ !['content-type', 'x-oss-forbid-overwrite'].includes(key.toLowerCase()) || typeof value !== 'string' || /[\r\n]/.test(value)))
+ throw new PluginProtocolError('Invalid upload headers');
+ const normalized = Object.fromEntries(entries.map(([key, value]) => [key.toLowerCase(), value]));
+ if (normalized['content-type'] !== 'application/octet-stream' || normalized['x-oss-forbid-overwrite'] !== 'true')
+ throw new PluginProtocolError('Invalid immutable upload headers');
+ result.headers = headers as Record<string, string>;
+ }
+ return result;
+}
+
+export function parseLocalPluginShareDownload(value: unknown, options?: PluginObjectUrlOptions) {
+ const row = object(value, 'download');
+ return { snapshot: parseLocalPluginShareSnapshot(row), url: parsePluginObjectUrl(row.url, 'url', options), expiresAt: isoDate(row.expiresAt, 'expiresAt') };
+}