Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugin): 对齐主干并修复分享接收链路
liugaoweibdc4a7ff08ec
diff --cc apps/desktop/scripts/fixtures/plugin-sharing/preview.mjsindex 24d89b11ee,0000000000..5d4ef73710mode 100644,000000..100644--- a/apps/desktop/scripts/fixtures/plugin-sharing/preview.mjs+++ b/apps/desktop/scripts/fixtures/plugin-sharing/preview.mjs@@@ -1,55 -1,0 +1,63 @@@+// Build a local review canvas. No Electron, credentials, business API calls or browser launch loop.+import { build } from 'esbuild';+import postcss from 'postcss';+import tailwind from 'tailwindcss';+import loadConfig from 'tailwindcss/loadConfig.js';+import { readFile, writeFile, mkdir, stat } from 'node:fs/promises';+import { createReadStream } from 'node:fs';+import { createServer } from 'node:http';+import path from 'node:path';+import os from 'node:os';+import { fileURLToPath } from 'node:url';++const here = path.dirname(fileURLToPath(import.meta.url));+const desktop = path.resolve(here, '../../..');+const renderer = path.join(desktop, 'src/renderer');+const out = path.join(os.tmpdir(), 'cindy-plugin-sharing-web-preview');+await mkdir(out, { recursive: true });+const invisible = {+ '@/contexts/AuthContext': `export const useAuth=()=>({isAuthenticated:new URLSearchParams(location.search).get('account')!=='anonymous',dataOwnerGeneration:1,dataOwnerId:'preview-owner'});`,+ '@/features/cc-agent/GithubAccountCard': 'export const GithubAccountCard=()=>null;',+ '@/cindy-brain/CindyCapabilityPrefs': 'export const CindyCapabilityPrefs=()=>null;',+ '@/cindy-brain/PluginTaskPrefs': 'export const PluginTaskPrefs=()=>null;',+ '@/cindy-brain/GhostSettingsWebview': 'export const GhostSettingsWebview=()=>null;',+ './GhostLibrarySection': 'export const GhostLibrarySection=()=>null;',+};+const result = await build({ entryPoints: [path.join(here, 'app.tsx')], outdir: out, entryNames: 'client', bundle: true, write: false, format: 'esm', platform: 'browser', jsx: 'automatic', tsconfig: path.join(desktop, 'tsconfig.json'), loader: { '.svg': 'dataurl', '.png': 'dataurl', '.jpg': 'dataurl', '.webp': 'dataurl', '.woff2': 'file', '.woff': 'file' }, define: { 'import.meta.env.PROD': 'true', 'import.meta.env.DEV': 'false' }, plugins: [{ name: 'host-only-fixtures', setup(b) { b.onResolve({ filter: /.*/ }, (a) => invisible[a.path] ? { path: a.path, namespace: 'fixture' } : undefined); b.onLoad({ filter: /.*/, namespace: 'fixture' }, (a) => ({ contents: invisible[a.path], loader: 'tsx' })); } }] });+const config = loadConfig(path.join(desktop, 'tailwind.config.ts'));+config.content = [path.join(renderer, '**/*.{ts,tsx,html}'), path.join(here, 'app.tsx')];+for (const file of result.outputFiles) {+ const bytes = file.path.endsWith('.css') ? (await postcss([tailwind(config)]).process(file.text, { from: file.path })).css : file.contents;+ await writeFile(file.path, bytes);+}+const client = '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Cindy 插件分享 · 客户端组件</title><link rel="stylesheet" href="/client.css"></head><body><div id="root"></div><script type="module" src="/client.js"></script></body></html>';+const shell = await readFile(path.join(here, 'index.html'), 'utf8');+const types = { '.js': 'text/javascript', '.css': 'text/css', '.woff2': 'font/woff2', '.woff': 'font/woff' };+createServer(async (req, res) => {+ const url = new URL(req.url, 'http://127.0.0.1:4178');+ res.setHeader('Cache-Control', 'no-store');+ if (url.pathname.startsWith('/share/')) {++ // The canvas only reads its fixture and creates shares. Choose literal++ // targets so no request path, query or redirect can select another endpoint.++ const target = !url.search && req.method === 'GET' && url.pathname === '/share/fixture.json'++ ? 'http://127.0.0.1:4179/fixture.json'++ : !url.search && req.method === 'POST' && url.pathname === '/share/api/shares'++ ? 'http://127.0.0.1:4179/api/shares'++ : null;++ if (!target) { res.writeHead(404).end(); return; }+ try {+ const chunks = []; let size = 0;+ for await (const chunk of req) { size += chunk.length; if (size > 4096) { res.writeHead(413).end(); return; } chunks.push(chunk); }+ const headers = {};+ for (const key of ['content-type', 'authorization']) if (req.headers[key]) headers[key] = req.headers[key];- const response = await fetch(`http://127.0.0.1:4179/${url.pathname.slice(7)}${url.search}`, { method: req.method, headers, ...(chunks.length ? { body: Buffer.concat(chunks) } : {}) });++ const response = await fetch(target, { method: req.method, redirect: 'error', headers, ...(chunks.length ? { body: Buffer.concat(chunks) } : {}) });+ res.writeHead(response.status, { 'Content-Type': response.headers.get('content-type') ?? 'application/octet-stream' });+ res.end(Buffer.from(await response.arrayBuffer()));+ } catch { res.writeHead(503).end('分享网页原型尚未启动'); }+ return;+ }+ if (url.pathname === '/' || url.pathname === '/client') { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.end(url.pathname === '/' ? shell : client); return; }+ const name = path.basename(url.pathname);+ try { const file = path.join(out, name); if (!(await stat(file)).isFile()) throw Error('Not a file'); res.setHeader('Content-Type', types[path.extname(name)] ?? 'application/octet-stream'); createReadStream(file).pipe(res); }+ catch { res.writeHead(404).end(); }+}).listen(4178, '127.0.0.1', () => process.stdout.write('客户端原型:http://127.0.0.1:4178\n'));diff --cc apps/desktop/src/main/__tests__/providerImportWiring.test.tsindex 6ea1cf3830,6ea1cf3830..4641b3b0fd--- a/apps/desktop/src/main/__tests__/providerImportWiring.test.ts+++ b/apps/desktop/src/main/__tests__/providerImportWiring.test.ts@@@ -20,7 -20,7 +20,7 @@@ describe('provider import wiring', () =});it('consumes the main pending slot when an import wake-up reaches MainLayout', () => {-- expect(mainLayout).toMatch(/onDeepLinkNavigate\(\(payload\) => \{[\s\S]*?if \(payload.type !== 'provider-import' && payload.type !== 'shared-task-join' && payload.type !== 'provider-share-join'\) \{\s*handleDeepLinkPayload\(payload\);\s*return;\s*\}[\s\S]*?void pullChatInvitations\(\);/);++ expect(mainLayout).toMatch(/onDeepLinkNavigate\(\(payload\) => \{[\s\S]*?if \(payload.type !== 'provider-import' && payload.type !== 'shared-task-join' && payload.type !== 'provider-share-join' && payload.type !== 'plugin'\) \{\s*handleDeepLinkPayload\(payload\);\s*return;\s*\}[\s\S]*?void pullChatInvitations\(\);/);});it('passes sanitized JS argv explicitly instead of replaying Electron native startup arguments', () => {for (const source of [bootstrap, updateService]) {diff --cc apps/desktop/src/main/deepLink.tsindex 37dca26db0,7afce996de..b99b291379--- a/apps/desktop/src/main/deepLink.ts+++ b/apps/desktop/src/main/deepLink.ts@@@ -500,9 -494,9 +500,9 @@@ function dispatchDeepLink(payload: Deepif (windowReady) win!.webContents.send('deep-link:navigate', payload);return;}-- // A loaded login/LocalDbGate page has no MainLayout listener yet. Imports stay++ // 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') {++ if (!windowReady || payload.type === 'provider-import' || payload.type === 'shared-task-join' || payload.type === 'provider-share-join' || payload.type === 'plugin') {// 保留"用户最后意图"语义:同一次冷启动如果先后入站多条 (例如 argv 同时含// deep link URL 和 --open-folder, 现实场景极罕见但 bootstrap 两条 scan 都// 会触发),后到的覆盖前者。但 warn log 留下排查线索,事后能从日志识别这种@@@ -526,7 -520,7 +526,7 @@@return;}}-- // Imports use this event only as a wake-up; MainLayout consumes the pending slot.++ // Retained intents use this event only as a wake-up; MainLayout consumes the pending slot.// Other existing navigation events retain their direct-delivery behavior.// 同时把窗口拉前台 — open-url / second-instance 本身不会唤起,用户点链接的// 意图就是要看到 app。diff --cc apps/desktop/src/main/plugin-market/__tests__/sharing.test.tsindex c73139ec34,0000000000..5ae93889b4mode 100644,000000..100644--- a/apps/desktop/src/main/plugin-market/__tests__/sharing.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/sharing.test.ts@@@ -1,248 -1,0 +1,251 @@@+// Test value: preparePluginShare exposes only validated public material and keeps+// anonymous reads separate from account-bound attribution (scope contract).+// Existing install/deep-link suites do not exercise this IPC business entry.+// Minimal failures include malformed material, an expired token and an owner+// switch during refresh; unit fakes avoid Electron, external HTTP and accounts.+import { beforeEach, describe, expect, it, vi } from 'vitest';+const mocks = vi.hoisted(() => ({+ endpoint: vi.fn(),+ fetch: vi.fn(),+ state: vi.fn(),+ realm: vi.fn(),+ token: vi.fn(),+ refresh: vi.fn(),+ region: 'global',+}));+vi.mock('../../authManager.js', () => ({+ getAuthState: mocks.state,+ getActiveAuthRealm: mocks.realm,+ getAccessToken: mocks.token,+ refresh: mocks.refresh,+}));+vi.mock('../../clientEndpointsService.js', () => ({+ getBuildClientEndpoint: mocks.endpoint,+}));+vi.mock('../../../shared/brandRegion.js', () => ({+ get CURRENT_CINDY_REGION() {+ return mocks.region;+ },+}));+vi.mock('../../serverApiClient.js', () => ({+ serverApiFetch: mocks.fetch,+ ServerApiError: class extends Error {+ constructor(public readonly code: string, public readonly statusCode: number, message: string) {+ super(message);+ }+ },+}));+vi.mock('../../utils/ipcValidate.js', () => ({+ throwIpcError: (code: string) => {+ throw new Error(code);+ },+}));+import { preparePluginShare } from '../sharing';+import { isIpcErrorCode } from '../../../shared/ipc-errors';+import { extractIpcError } from '../../../shared/ipcError';+import { ServerApiError } from '../../serverApiClient';+const pluginId = 'c123456789012345678901234';+const shareId = 's'.repeat(32);+const expiredError = new ServerApiError('TOKEN_EXPIRED', 401, 'Fixture token expired');+const response = {+ schemaVersion: 1,+ kind: 'plugin',+ shareId,+ includeAttribution: false,- url: `https://share.example.test/s/${shareId}?region=global&lang=en`,++ url: `https://share.example.test/s/${shareId}`,+ imageSvg: '<svg xmlns="http://www.w3.org/2000/svg"></svg>',+ plugin: {+ schemaVersion: 1,+ pluginId,+ name: 'Example',+ description: null,+ author: null,+ version: '1.0.0',+ publishedAt: '2026-10-15T00:00:00.000Z',+ },+};+beforeEach(() => {+ vi.clearAllMocks();+ mocks.region = 'global';+ mocks.realm.mockReturnValue('global');+ mocks.token.mockReturnValue('fixture-access-token');+ mocks.refresh.mockResolvedValue(true);+ mocks.endpoint.mockReturnValue('https://share.example.test');+ mocks.fetch.mockResolvedValue(response);+ mocks.state.mockReturnValue({+ ownerGeneration: 1,+ mode: 'cloud',+ isAuthenticated: true,+ user: { id: 'fixture-member' },+ });+});+describe('public sharing preparation', () => {+ it.each(['SHARE_NOT_CONFIGURED', 'SHARE_UNAVAILABLE', 'SHARE_READ_FAILED'])(+ 'preserves %s across Electron error serialization',+ (code) => {+ expect(isIpcErrorCode(code)).toBe(true);+ expect(+ extractIpcError(new Error(`Error invoking remote method: Error: [${code}] Failed`))?.code,+ ).toBe(code);+ },+ );+ it('creates anonymous shares without credentials or identity refresh', async () => {+ expect(await preparePluginShare(pluginId)).toEqual({+ title: 'Example',+ url: response.url,+ imageSvg: response.imageSvg,+ });+ expect(mocks.fetch).toHaveBeenCalledWith(+ '/api/shares',+ expect.objectContaining({+ method: 'POST',+ body: { kind: 'plugin', reference: pluginId, includeAttribution: false, region: 'global', lang: 'en' },+ token: null,+ skipAutoRefresh: true,+ skipSessionInvalidation: true,+ cache: 'no-store',+ }),+ );+ expect(mocks.token).not.toHaveBeenCalled();+ expect(mocks.refresh).not.toHaveBeenCalled();+ });+ it.each(['cn', 'dev'])(- 'keeps %s sharing in Chinese and binds the returned link to that context',++ 'keeps %s creation in Chinese with a clean returned link',+ async (region) => {+ mocks.region = region;- const url = `https://share.example.test/s/${shareId}?region=cn&lang=zh-CN`;++ const url = `https://share.example.test/s/${shareId}`;+ mocks.fetch.mockResolvedValue({ ...response, url });+ expect((await preparePluginShare(pluginId)).url).toBe(url);+ expect(mocks.fetch).toHaveBeenCalledWith(+ '/api/shares',- expect.objectContaining({ token: null }),++ expect.objectContaining({++ token: null,++ body: { kind: 'plugin', reference: pluginId, includeAttribution: false, region: 'cn', lang: 'zh-CN' },++ }),+ );+ },+ );- it('rejects a returned link that silently changes the language or region', async () => {++ it.each(['?region=cn', '?lang=zh-CN'])('rejects a returned link with unexpected query %s', async (query) => {+ mocks.fetch.mockResolvedValue({+ ...response,- url: response.url.replace('lang=en', 'lang=zh-CN'),++ url: `${response.url}${query}`,+ });+ await expect(preparePluginShare(pluginId)).rejects.toThrow('SHARE_READ_FAILED');+ });+ it('rejects a foreign landing origin', async () => {+ mocks.fetch.mockResolvedValue({ ...response, url: 'https://attacker.example.test' });+ await expect(preparePluginShare(pluginId)).rejects.toThrow('SHARE_READ_FAILED');+ });+ it('does not make a request before sharing is configured', async () => {+ mocks.endpoint.mockReturnValue('');+ await expect(preparePluginShare(pluginId)).rejects.toThrow('SHARE_NOT_CONFIGURED');+ expect(mocks.fetch).not.toHaveBeenCalled();+ });+ it('rejects arbitrary URLs before network access', async () => {+ await expect(preparePluginShare('https://example.test')).rejects.toThrow('INVALID_PARAMS');+ expect(mocks.fetch).not.toHaveBeenCalled();+ });+ it('requests a server-owned signed share using only the frozen current identity', async () => {+ mocks.fetch.mockResolvedValue({ ...response, includeAttribution: true, attribution: { displayName: 'Current nickname' } });+ const result = await preparePluginShare(pluginId, { includeAttribution: true });+ expect(result.attribution?.displayName).toBe('Current nickname');+ expect(mocks.fetch).toHaveBeenCalledWith('/api/shares', expect.objectContaining({+ token: 'fixture-access-token', skipAutoRefresh: true,+ body: { kind: 'plugin', reference: pluginId, includeAttribution: true, authRealm: 'global', region: 'global', lang: 'en' },+ }));+ expect(result.url).not.toContain('source=');+ });+ it('refreshes an expired signed share once and retries with the current token of the same owner', async () => {+ mocks.fetch.mockRejectedValueOnce(expiredError)+ .mockResolvedValueOnce({ ...response, includeAttribution: true });+ mocks.refresh.mockImplementationOnce(async () => {+ mocks.token.mockReturnValue('fixture-refreshed-token');+ return true;+ });+ expect((await preparePluginShare(pluginId, { includeAttribution: true })).url).toBe(response.url);+ expect(mocks.refresh).toHaveBeenCalledTimes(1);+ expect(mocks.fetch).toHaveBeenCalledTimes(2);+ expect(mocks.fetch.mock.calls[0]?.[1]).toMatchObject({+ token: 'fixture-access-token', allowedRedactedErrorCodes: ['TOKEN_EXPIRED'],+ });+ expect(mocks.fetch.mock.calls[1]?.[1]).toMatchObject({+ token: 'fixture-refreshed-token', skipAutoRefresh: true, skipSessionInvalidation: true,+ body: { includeAttribution: true, authRealm: 'global' },+ });+ });+ it('does not retry again if the refreshed signed request is rejected', async () => {+ mocks.fetch.mockRejectedValue(expiredError);+ await expect(preparePluginShare(pluginId, { includeAttribution: true })).rejects.toThrow('SHARE_READ_FAILED');+ expect(mocks.refresh).toHaveBeenCalledTimes(1);+ expect(mocks.fetch).toHaveBeenCalledTimes(2);+ });+ it.each([+ [false, 'TOKEN_EXPIRED', 401],+ [true, 'UNAUTHORIZED', 401],+ [true, 'ACCOUNT_UNAVAILABLE', 401],+ [true, 'TOKEN_EXPIRED', 503],+ ] as const)('does not refresh for attribution=%s, code=%s, status=%s', async (includeAttribution, code, status) => {+ mocks.fetch.mockRejectedValueOnce(new ServerApiError(code, status, 'Fixture request rejected'));+ await expect(preparePluginShare(pluginId, { includeAttribution })).rejects.toThrow('SHARE_READ_FAILED');+ expect(mocks.refresh).not.toHaveBeenCalled();+ expect(mocks.fetch).toHaveBeenCalledTimes(1);+ });+ it('does not refresh another account when the owner changes before the first rejection', async () => {+ mocks.fetch.mockImplementationOnce(async () => {+ mocks.state.mockReturnValue({ ownerGeneration: 2, mode: 'cloud', isAuthenticated: true, user: { id: 'other-member' } });+ throw expiredError;+ });+ await expect(preparePluginShare(pluginId, { includeAttribution: true })).rejects.toThrow('SHARE_READ_FAILED');+ expect(mocks.refresh).not.toHaveBeenCalled();+ expect(mocks.fetch).toHaveBeenCalledTimes(1);+ });+ it.each(['owner', 'realm', 'logout'] as const)('stops the retry if %s changes during refresh', async (change) => {+ mocks.fetch.mockRejectedValueOnce(expiredError);+ mocks.refresh.mockImplementationOnce(async () => {+ if (change === 'realm') mocks.realm.mockReturnValue('cn');+ else if (change === 'logout') mocks.state.mockReturnValue({ ownerGeneration: 2, mode: 'signed-out', user: null });+ else mocks.state.mockReturnValue({ ownerGeneration: 2, mode: 'cloud', isAuthenticated: true, user: { id: 'other-member' } });+ mocks.token.mockReturnValue('fixture-other-owner-token');+ return true;+ });+ await expect(preparePluginShare(pluginId, { includeAttribution: true })).rejects.toThrow('SHARE_READ_FAILED');+ expect(mocks.refresh).toHaveBeenCalledTimes(1);+ expect(mocks.fetch).toHaveBeenCalledTimes(1);+ });+ it('stops if login refresh fails', async () => {+ mocks.fetch.mockRejectedValueOnce(expiredError);+ mocks.refresh.mockResolvedValueOnce(false);+ await expect(preparePluginShare(pluginId, { includeAttribution: true })).rejects.toThrow('SHARE_READ_FAILED');+ expect(mocks.fetch).toHaveBeenCalledTimes(1);+ });+ it('does not send a signed retry without a token', async () => {+ mocks.fetch.mockRejectedValueOnce(expiredError);+ mocks.refresh.mockImplementationOnce(async () => {+ mocks.token.mockReturnValue(null);+ return true;+ });+ await expect(preparePluginShare(pluginId, { includeAttribution: true })).rejects.toThrow('SHARE_READ_FAILED');+ expect(mocks.fetch).toHaveBeenCalledTimes(1);+ });+ it('keeps the signed binding when the current profile cannot be displayed', async () => {+ mocks.fetch.mockResolvedValue({ ...response, includeAttribution: true });+ const result = await preparePluginShare(pluginId, { includeAttribution: true });+ expect(result.url).toBe(response.url);+ expect(result.attribution).toBeUndefined();+ });+ it('rejects invalid share identifiers and silently downgraded attribution', async () => {+ mocks.fetch.mockResolvedValue({ ...response, shareId: '../other', includeAttribution: true });+ await expect(preparePluginShare(pluginId, { includeAttribution: true })).rejects.toThrow('SHARE_READ_FAILED');+ mocks.fetch.mockResolvedValue(response);+ await expect(preparePluginShare(pluginId, { includeAttribution: true })).rejects.toThrow('SHARE_READ_FAILED');+ });+ it('rejects a result if the account changes while material is loading', async () => {+ mocks.fetch.mockImplementationOnce(async () => {+ mocks.state.mockReturnValue({ ownerGeneration: 2, mode: 'local', user: null });+ return response;+ });+ await expect(preparePluginShare(pluginId, { includeAttribution: true })).rejects.toThrow(+ 'SHARE_READ_FAILED',+ );+ });+});diff --cc apps/desktop/src/main/plugin-market/sharing.tsindex c653bb5ab8,0000000000..b98a343943mode 100644,000000..100644--- a/apps/desktop/src/main/plugin-market/sharing.ts+++ b/apps/desktop/src/main/plugin-market/sharing.ts@@@ -1,111 -1,0 +1,110 @@@+import { isValidPluginResourceId, parsePublicPluginPresentation } from '@cindy/plugin-protocol';+import type { ShareContent } from '../../shared/share.js';+import { getBuildClientEndpoint } from '../clientEndpointsService.js';+import * as authManager from '../authManager.js';+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';+import { serverApiFetch, ServerApiError } from '../serverApiClient.js';+import { throwIpcError } from '../utils/ipcValidate.js';+import { rememberIssuedClipboardText } from '../textClipboard.js';++/** The fixed Share Server owns the immutable resource/profile binding. */+export async function preparePluginShare(+ pluginId: unknown,+ options: unknown = undefined,+): Promise<ShareContent> {+ if (!isValidPluginResourceId(pluginId))+ throwIpcError('INVALID_PARAMS', 'Invalid public plugin reference');+ if (+ options !== undefined &&+ (!options ||+ typeof options !== 'object' ||+ Array.isArray(options) ||+ typeof (options as Record<string, unknown>).includeAttribution !== 'boolean' ||+ Object.keys(options).some((key) => key !== 'includeAttribution'))+ ) {+ throwIpcError('INVALID_PARAMS', 'Invalid share options');+ }+ // Absent options preserve the existing anonymous IPC contract for old callers.+ const includeAttribution =+ (options as { includeAttribution?: boolean } | undefined)?.includeAttribution === true;+ const session = authManager.getAuthState();+ const realm = authManager.getActiveAuthRealm();+ const isCurrent = () => {+ const current = authManager.getAuthState();+ return (+ current.ownerGeneration === session.ownerGeneration &&+ current.user?.id === session.user?.id &&+ authManager.getActiveAuthRealm() === realm &&+ current.mode === session.mode+ );+ };+ // Public sharing follows the installed edition, not a cross-realm organization session.+ const baseUrl = getBuildClientEndpoint('shareBaseUrl');+ if (!baseUrl) throwIpcError('SHARE_NOT_CONFIGURED', 'Sharing is not configured');+ const region = CURRENT_CINDY_REGION === 'global' ? 'global' : 'cn';- const query = new URLSearchParams({ region, lang: region === 'cn' ? 'zh-CN' : 'en' });+ try {+ const signed = includeAttribution && session.isAuthenticated && !!session.user;+ const request = (token: string | null) => {+ if (!isCurrent() || (signed && !token)) throw new Error('Share owner unavailable');+ return serverApiFetch<unknown>('/api/shares', {+ baseUrl,+ method: 'POST',+ body: { kind: 'plugin', reference: pluginId, includeAttribution: signed,+ region, lang: region === 'cn' ? 'zh-CN' : 'en', ...(signed ? { authRealm: realm } : {}) },+ token,+ skipAutoRefresh: true,+ skipSessionInvalidation: true,+ timeoutMs: 20000,+ cache: 'no-store',+ redactErrorDetails: true,+ allowedRedactedErrorCodes: ['TOKEN_EXPIRED'],+ logLabel: '/api/shares',+ });+ };+ let raw: unknown;+ try {+ raw = await request(signed ? authManager.getAccessToken() : null);+ } catch (error) {+ if (!signed || !isCurrent() || !(error instanceof ServerApiError) ||+ error.statusCode !== 401 || error.code !== 'TOKEN_EXPIRED') throw error;+ // Refresh only the original owner, then retry once with that owner's current token.+ if (!(await authManager.refresh()) || !isCurrent()) throw error;+ raw = await request(authManager.getAccessToken());+ }+ if (!raw || typeof raw !== 'object') throw new Error('Invalid share response');+ const row = raw as Record<string, unknown>;+ if (row.schemaVersion !== 1 || row.kind !== 'plugin')+ throw new Error('Unsupported share response');+ const plugin = parsePublicPluginPresentation(row.plugin);+ // The service can resolve legacy IDs, but cannot redirect the client to an arbitrary origin.+ if (typeof row.shareId !== 'string' || !/^[A-Za-z0-9_-]{32}$/.test(row.shareId) || row.includeAttribution !== signed)+ throw new Error('Invalid share binding');- const url = `${baseUrl}/s/${row.shareId}?${query}`;++ const url = `${baseUrl}/s/${row.shareId}`;+ if (+ row.url !== url ||+ typeof row.imageSvg !== 'string' ||+ row.imageSvg.length > 1024 * 1024 ||+ !row.imageSvg.startsWith('<svg ')+ )+ throw new Error('Invalid share material');+ let attribution: ShareContent['attribution'];+ if (signed && row.attribution && typeof row.attribution === 'object') {+ const name = (row.attribution as Record<string, unknown>).displayName;+ if (typeof name === 'string' && name.trim() && name.length <= 256)+ attribution = { displayName: name.trim() };+ }+ if (!isCurrent()) throw new Error('Share owner changed');+ rememberIssuedClipboardText(url);+ return {+ title: plugin.name,+ url,+ imageSvg: row.imageSvg,+ ...(attribution ? { attribution } : {}),+ };+ } catch (error) {+ if (error instanceof ServerApiError && error.statusCode === 404) {+ throwIpcError('SHARE_UNAVAILABLE', 'Public plugin is unavailable');+ }+ throwIpcError('SHARE_READ_FAILED', 'Could not prepare sharing material');+ }+}diff --cc apps/desktop/src/preload/__tests__/deepLinkIslandEntryBridge.test.tsindex 18acd00eee,18acd00eee..fe2f23ce41--- a/apps/desktop/src/preload/__tests__/deepLinkIslandEntryBridge.test.ts+++ b/apps/desktop/src/preload/__tests__/deepLinkIslandEntryBridge.test.ts@@@ -2,6 -2,6 +2,7 @@@ import { readFileSync } from 'node:fs'import ts from 'typescript';import { afterEach, describe, expect, it, vi } from 'vitest';import type { BrowserWindow } from 'electron';++import { isValidPluginResourceId } from '@cindy/plugin-protocol';import { handleIncomingDeepLink, openMainWindowRemoteControlSettings, openMainWindowSession, setDeepLinkMainWindow, takePendingDeepLink } from '../../main/deepLink';@@@ -21,12 -21,12 +22,13 @@@ const compiled = ts.transpileModule(`cofunction connect() {let listener: ((payload: unknown) => void) | undefined;-- const bridge = new Function('fanOutDeepLinkNavigate', 'isDeepLinkProviderConnectId', `${compiled}; return bridge;`)(++ const bridge = new Function('fanOutDeepLinkNavigate', 'isDeepLinkProviderConnectId', 'isValidPluginResourceId', `${compiled}; return bridge;`)((callback: (payload: unknown) => void) => {listener = callback;return () => { listener = undefined; };},() => false,++ isValidPluginResourceId,) as { onDeepLinkNavigate(callback: (payload: unknown) => void): () => void };const received: unknown[] = [];bridge.onDeepLinkNavigate((payload) => received.push(payload));@@@ -101,3 -101,3 +103,43 @@@ describe('Agent Island click id across]);});});++++// PR #7240: the new plugin intent was parsed by main but dropped by preload,++// and a loaded login page lost it before MainLayout mounted. The existing++// session cases cover neither branch. Unit inputs use a public resource ID,++// a loaded window, and the real one-shot main queue; no Electron is started.++describe('public plugin entry through the production bridge', () => {++ const pluginId = 'c123456789012345678901234';++ const href = `cindy://plugin/${pluginId}`;++ const expected = { type: 'plugin', pluginId };++++ it('delivers a live wake-up and retains the intent for exactly one consumer', () => {++ const { received } = connect();++ handleIncomingDeepLink(href, 'open-url');++ expect(received).toEqual([expected]);++ expect(takePendingDeepLink()).toEqual(expected);++ expect(takePendingDeepLink()).toBeNull();++ });++++ it('retains the last plugin during login and cold start until the mount pull', () => {++ connect();++ handleIncomingDeepLink('cindy://plugin/c223456789012345678901234', 'open-url');++ handleIncomingDeepLink(href, 'open-url');++ expect(takePendingDeepLink()).toEqual(expected);++ expect(takePendingDeepLink()).toBeNull();++ setDeepLinkMainWindow(null);++ handleIncomingDeepLink(href, 'argv');++ expect(takePendingDeepLink()).toEqual(expected);++ expect(takePendingDeepLink()).toBeNull();++ });++++ it('drops invalid plugin identifiers and projects only the navigation fields', () => {++ const { received, deliver } = connect();++ for (const pluginId of [undefined, null, 7, '', 'cindy-github', '../file', 'c123?install=true']) {++ deliver({ type: 'plugin', pluginId });++ }++ expect(received).toEqual([]);++ deliver({ ...expected, install: true, url: 'https://untrusted.example.test' });++ expect(received).toEqual([expected]);++ });++});diff --cc apps/desktop/src/preload/preload.tsindex 99a09afde4,1e814cf80c..caa095930b--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@@ -59,6 -59,6 +59,7 @@@ importWINDOW_BACKDROP_MATERIAL_CHANGED_CHANNEL,} from '../shared/windowBackdrop';import { isDeepLinkProviderConnectId } from '../shared/deepLinkSchemes';++import { isValidPluginResourceId } from '@cindy/plugin-protocol';import {parseProjectOrderSnapshot,SIDEBAR_APPLY_PROJECT_ORDER_CHANNEL,@@@ -4017,6 -4016,6 +4019,7 @@@ contextBridge.exposeInMainWorld('electr| { type: 'new-session'; workingDir: string }| { type: 'share-import'; filePath: string }| { type: 'provider-import'; importId: string }++ | { type: 'plugin'; pluginId: string }| { type: 'shared-task-join'; invitation: string; server: string }| { type: 'provider-share-join'; link: string }| { type: 'chat-invite'; token: string }@@@ -4032,6 -4031,6 +4035,7 @@@workingDir?: unknown;filePath?: unknown;importId?: unknown;++ pluginId?: unknown;invitation?: unknown;token?: unknown;server?: unknown;@@@ -4060,6 -4059,6 +4064,8 @@@? { islandEntryId: p.islandEntryId }: {}),});++ } else if (p.type === 'plugin' && isValidPluginResourceId(p.pluginId)) {++ callback({ type: 'plugin', pluginId: p.pluginId });} 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,@@@ -4127,6 -4126,6 +4133,7 @@@| { type: 'new-session'; workingDir: string }| { type: 'share-import'; filePath: string }| { type: 'provider-import'; importId: string }++ | { type: 'plugin'; pluginId: string }| { type: 'shared-task-join'; invitation: string; server: string }| { type: 'provider-share-join'; link: string }| { type: 'chat-invite'; token: string }diff --cc apps/desktop/src/renderer/components/layout/MainLayout.tsxindex d2b8b8fa98,492afbeead..fdf2a38724--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx@@@ -809,11 -804,11 +809,11 @@@ export function MainLayout()void pullChatInvitations();return;}-- if (payload.type !== 'provider-import' && payload.type !== 'shared-task-join' && payload.type !== 'provider-share-join') {++ if (payload.type !== 'provider-import' && payload.type !== 'shared-task-join' && payload.type !== 'provider-share-join' && payload.type !== 'plugin') {handleDeepLinkPayload(payload);return;}-- // Main retains imports through login. Both this wake-up and the mount pull++ // Main retains these intents through login. Both this wake-up and the mount pull// use the same atomic take, so either ordering navigates only once.void pullChatInvitations();});diff --cc apps/desktop/src/renderer/features/share/__tests__/ShareDialog.test.tsxindex 11887ccfab,0000000000..997f9ef9d1mode 100644,000000..100644--- a/apps/desktop/src/renderer/features/share/__tests__/ShareDialog.test.tsx+++ b/apps/desktop/src/renderer/features/share/__tests__/ShareDialog.test.tsx@@@ -1,84 -1,0 +1,92 @@@+/** @vitest-environment jsdom */+// Test value: the real ShareDialog must honor dismissal, PNG failure and native+// save cancellation. These regressions are not covered by the main IPC suite.+// Minimal inputs are a delayed PNG promise, a rejected conversion and canceled+// save; this unit tier renders jsdom and fakes only native/image boundaries.+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+const io = vi.hoisted(() => ({+ png: vi.fn(),+ copyImage: vi.fn(),+ copyText: vi.fn(),+ save: vi.fn(),+ success: vi.fn(),+ error: vi.fn(),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/lib/rasterizeToImage', () => ({+ svgToPngBlob: io.png,+ copyPngBlobToClipboard: io.copyImage,+}));+vi.mock('@/lib/annotationBurnIn', () => ({+ blobToDataUrl: async () => 'data:image/png;base64,aA==',+}));+vi.mock('@/lib/toast', () => ({ toast: { success: io.success, error: io.error } }));+import { ShareDialog } from '../ShareDialog';+const material = {+ title: 'Public plugin',+ url: 'https://share.example.test/plugins/c123456789012345678901234',+ imageSvg: '<svg />',+};+const load = async () => material;++// Buttons exist while material is loading. Wait for the real action to become++// usable so a disabled click cannot skip the PNG failure/cancellation path.++async function clickReadyAction(name: string) {++ const button = await screen.findByRole<HTMLButtonElement>('button', { name });++ await waitFor(() => expect(button.disabled).toBe(false));++ await act(async () => { fireEvent.click(button); });++}+beforeEach(() => {+ vi.clearAllMocks();+ io.copyText.mockResolvedValue(undefined);+ io.copyImage.mockResolvedValue(undefined);+ io.png.mockResolvedValue(new Blob(['png'], { type: 'image/png' }));+ io.save.mockResolvedValue({ canceled: true });+ vi.stubGlobal('electronAPI', { copyTextToClipboard: io.copyText, saveMediaAs: io.save });+});+afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});+describe('manual sharing output', () => {+ it('does not copy a picture that finishes rendering after dismissal', async () => {+ let finish!: (blob: Blob) => void;+ io.png.mockImplementationOnce(+ () =>+ new Promise<Blob>((resolve) => {+ finish = resolve;+ }),+ );+ const onClose = vi.fn();+ render(<ShareDialog load={load} onClose={onClose} />);- fireEvent.click(await screen.findByRole('button', { name: 'sharing.copyImage' }));++ await clickReadyAction('sharing.copyImage');++ expect(io.png).toHaveBeenCalledOnce();+ fireEvent.click(screen.getByRole('button', { name: 'sharing.close' }));+ await act(async () => {+ finish(new Blob(['png']));+ });+ expect(onClose).toHaveBeenCalledOnce();+ expect(io.copyImage).not.toHaveBeenCalled();+ });+ it('keeps the valid link usable after PNG generation fails', async () => {+ io.png.mockRejectedValueOnce(new Error('image unavailable'));+ render(<ShareDialog load={load} onClose={vi.fn()} />);- fireEvent.click(await screen.findByRole('button', { name: 'sharing.copyImage' }));++ await clickReadyAction('sharing.copyImage');+ await waitFor(() => expect(io.error).toHaveBeenCalledWith('sharing.copyImageFailed'));- fireEvent.click(screen.getByRole('button', { name: 'sharing.copyLink' }));++ await clickReadyAction('sharing.copyLink');+ await waitFor(() => expect(io.copyText).toHaveBeenCalledWith({ text: material.url }));+ expect(screen.getByRole('dialog')).toBeTruthy();+ });+ it('does not report a canceled native save as saved or failed', async () => {+ render(<ShareDialog load={load} onClose={vi.fn()} />);- fireEvent.click(await screen.findByRole('button', { name: 'sharing.saveImage' }));++ await clickReadyAction('sharing.saveImage');+ await waitFor(() => expect(io.save).toHaveBeenCalledOnce());+ await waitFor(() =>+ expect(+ (screen.getByRole('button', { name: 'sharing.saveImage' }) as HTMLButtonElement).disabled,+ ).toBe(false),+ );+ expect(io.success).not.toHaveBeenCalled();+ expect(io.error).not.toHaveBeenCalled();+ });+});diff --cc docs/dev-rules/protocol-compatibility.mdindex 9a3e560a97,bdf278c5f3..cb77570d86--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@@ -3489,20 -3521,6 +3521,20 @@@ namespace + id 下同一插件的有�不改变已装批准、凭证、KV、版本或原生指纹。实现与时序验证见[原配置页协议](../remote-plugin-oauth.md#手机原配置页授权的增量能力)。+## 公共插件分享(未发布首版)++`shareBaseUrl` 是端点清单的可选字段;缺失/空值关闭分享素材准备,不猜测域名。旧客户端忽略字段,既有市场和安装协议不变。公开 DTO `PublicPluginPresentation` v1 由两仓的 `packages/plugin-protocol` 同步维护,不含包或安装批准。++`plugin-market:prepare-share` 接受可选 `ShareOptions {includeAttribution:boolean}`,省略时匿名。Main 向构建区域固定 Share Server `POST /api/shares`,请求 `{kind:'plugin',reference,includeAttribution,region,lang,authRealm?}`。CN/Dev 是 cn/zh-CN,Global 是 global/en;Auth 权威区域随当前身份冻结,可以与构建区域不同。只有署名创建携带当前用户 Access Token,固定账号代次;仅遇到明确的 TOKEN_EXPIRED 时复用登录续期并重试一次,续期前后及请求前复核原身份,不降为匿名。匿名请求无凭证。Renderer 不持有 token、不指定用户或上游服务。+- Share Server 以独立 PostgreSQL 库唯一保存分享关系;返回既有素材字段及 `shareId`、`includeAttribution`。Main 校验随机分享编号、固定同源 `/s/:shareId`、同一组区域语言与署名方式。转发同一编号保留原署名;开关或重新分享选择另一条绑定,不修改既有记录。链接不含 source、内部身份、版本、包或批准;请求结果在切账号/资源后丢弃。++Share Server 以独立 PostgreSQL 库唯一保存分享关系;返回既有素材字段及 `shareId`、`includeAttribution`。Main 校验随机分享编号、固定同源且无查询参数的 `/s/:shareId` 与署名方式。区域语言仍由创建请求明确携带并存入记录。转发同一编号保留原署名;开关或重新分享选择另一条绑定,不修改既有记录。链接不含 source、内部身份、版本、包或批准;请求结果在切账号/资源后丢弃。+- 落地页、二维码和图片使用同一 `/s/:shareId?region=…&lang=…`,资源、署名、区域和默认语言以服务器记录为准;合法 `lang` 仅覆盖当前页面、JSON、SVG 的展示语言,向插件服务透传,不改写原记录或创建新编号。每次检查当前公开上架及可交付资格,显示当前公开版本;作者原文保留。当前昵称头像通过 Auth 实时读取,不可用则隐藏,不把已署名绑定降为匿名。生成时身份验证失败返回错误,可重试或另选匿名分享;资料查询不可用时隐藏署名展示,不改变原署名绑定,不复用错误身份。++落地页、二维码和图片使用同一无参 `/s/:shareId`,资源、署名、区域和默认语言以服务器记录为准;页面显式切换语言时,合法 `lang` 仅覆盖当前页面、JSON、SVG 的展示语言,向插件服务透传,不改写原记录或创建新编号。每次检查当前公开上架及可交付资格,显示当前公开版本;作者原文保留。当前昵称头像通过 Auth 实时读取,不可用则隐藏,不把已署名绑定降为匿名。生成时身份验证失败返回错误,可重试或另选匿名分享;资料查询不可用时隐藏署名展示,不改变原署名绑定,不复用错误身份。++Share Server 在创建时保存已验签的分享者 `membershipId` 与身份权威。Auth 只读现有账号资料,不增加分享字段、记录、索引或 migration;公开资料接口使用 shareId,在固定 Share Server 回查有效分享与身份绑定后读取当前资料。分享服务端已独立提供该能力,客户端沿用现有认证与固定分享入口,不引入额外 Auth 写入或凭证存储。公开资料新增可选的内嵌栅格 `icon` 字段,两仓协议同步;缺失或无效时使用默认图标,旧服务与旧客户端均兼容。++方形 SVG 为 1080×1080,Desktop PNG 为 2160×2160,接收界限 1 MiB。素材用于人工复制/保存;网页只展示与承接,不提供发送面板工具。`cindy://plugin/:pluginId` 仍只导航,拒绝 query/fragment/安装参数,沿冷启动、登录恢复、兼容包选择和原安装批准。通用市场详情入口接受服务端解析后的当前区域 ID,再与当前可见目录核对身份及发布;新旧 ID 映射仍归 Plugin Server,分享层不新增转换。已有目录 ID 的请求仍严格绑定原条目,不能借规范化跳到其他插件。不扩 device-link 或 Mobile 能力,没有“我的分享”、移除已发署名、分享统计、转发链、平台 SDK 或资料快照。+## 伙伴关联项目diff --cc packages/plugin-protocol/src/index.tsindex ddc24568b9,a8cb135319..143476e063--- a/packages/plugin-protocol/src/index.ts+++ b/packages/plugin-protocol/src/index.ts@@@ -5,4 -5,4 +5,5 @@@ export * from './delivery.js'export * from './memberUpload.js';export * from './usage.js';export * from './secretCheck.js';+export * from './publicPresentation.js';+ export * from './harness.js';