Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(plugins): 支持本地插件提审与我的插件管理
liugaowei60110fa67313
diff --git a/apps/desktop/resources/system-skills/cindy-plugin-creator/SKILL.md b/apps/desktop/resources/system-skills/cindy-plugin-creator/SKILL.mdindex 589f51f8d5..89a35888bb 100644--- a/apps/desktop/resources/system-skills/cindy-plugin-creator/SKILL.md+++ b/apps/desktop/resources/system-skills/cindy-plugin-creator/SKILL.md@@ -15,7 +15,7 @@ Build a Cindy plugin from the user's request, or update an existing plugin. This2. Before writing code, read the [sandbox boundaries](references/plugin-sandbox.md) and [packaging workflow](references/plugin-packaging.md). Read the capability references below as needed; do not load the whole manual at once.3. For a new plugin, prefer ghost_forge_scaffold with the appropriate plain, agent-action, node-json-rpc or node-mcp template, then edit the generated files. For an existing plugin, preserve its identity, data and compatible behavior. Use schemaVersion: 3 for new manifests and declare the first stable Cindy version actually required.4. Implement and validate the requested behavior, including Light and Dark modes for any UI. Separate current Agent tool-call operations from autonomous plugin capabilities, as described in the manifest and Agent-call references. Use [tool discovery](references/plugin-tool-discovery.md) and [manuals](references/plugin-manual.md) for authoring the plugin's own discovery and workflow documentation.-5. Call ghost_forge_pack to validate and produce the .cindy artifact. Report what was tested and what remains unverified. Packaging does not install or publish: use ghost_forge_install only when installation is requested, and follow [publishing](references/plugin-publishing.md) when publication is requested.+5. Call ghost_forge_pack to validate and produce the .cindy artifact. Report what was tested and what remains unverified. Packaging does not install or publish: use ghost_forge_install only when installation is requested, and follow [personal publication and anonymity (§7.3–7.4)](references/plugin-packaging.md) for community publication, or [publishing signatures and review (§8)](references/plugin-publishing.md) as applicable. Read the releaseNotes contract in [manifest (§2)](references/plugin-manifest.md) before submitting a version.Cindy supplies the Forge tools. If they are unavailable in the current environment, explain the missing capability and continue any local source work that is possible; do not claim to have packaged, installed or published. The legacy ghost_forge_guide tool serves these same references by section number or title when needed. It is a compatibility entry point, not a second source of documentation.diff --git a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-manifest.md b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-manifest.mdindex 0f015a97af..e5c9eba826 100644--- a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-manifest.md+++ b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-manifest.md@@ -15,6 +15,7 @@"ko": "locales/ko.json"},"version": "1.0.0",+ "releaseNotes": "新增图片编辑工具。", // 可选;首次上架可省略,更新时写相对上一已上架版本的完整变化"minCindyVersion": "1.2.3", // 示例;v3 必填:本插件实际依赖的首个 Cindy 正式版本(SemVer)"entry": "main.js", // 电子脑入口(kind 字段已无需填写:插件只有芯片一种形态,缺省即 chip;写了也只认 "chip")"launch": "on-demand", // 可选:电子脑启动模式。on-demand(缺省)=被需要才拉起;resident=唤醒即常驻(详情页会如实标注"常驻运行",绝大多数插件不需要,仅订阅型/需秒响应的场景用)@@ -59,6 +60,15 @@ Desktop 信任来源已经完成的版本选择,不再按 `minCindyVersion`用户主动导入的本地包、以及用户添加的自定义市场也遵循同一安装策略。这个字段仍必须准确填写:它供发布服务选择兼容 release,也记录插件真实依赖的首个 Host 版本。+### releaseNotes:随版本保存的更新说明++在 `ghost.json` 顶层填写纯文本字符串 `releaseNotes`,不是数组、对象或独立文件。+现有 v2 与 v3 清单都支持;新插件仍用 v3,不必仅为此字段升级旧包 schema。+首次上架可省略,插件用途写在 `description`。插件曾上架后再提审时,须完整覆盖相对上一已上架版本的变化,不只写最近一次修改。+上方只是写法示例,须按真实实现改写;骨架不自动生成说明,也不能从版本号猜变化。+缺字段的包仍能本地打包、安装;仅曾上架插件的后续提审要求非空说明,通过本地打包不表示可以提审。+发布预检与提审流程见 §7.3,署名与匿名设置见 §7.4。+### whenToUse:只写发现线索,不写使用规则在作者契约里,`whenToUse` 是专门给模型做插件发现与判断的唯一字段;diff --git a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-packaging.md b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-packaging.mdindex c3ae15777d..30163d6b0e 100644--- a/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-packaging.md+++ b/apps/desktop/resources/system-skills/cindy-plugin-creator/references/plugin-packaging.md@@ -75,3 +75,59 @@后台继续;用 `ghost_forge_publish_status` 查询传输与审核状态。发布确认屏仍由用户明确确认。成员发布仅企业组织成员可用,个人账号不可用;票据过期、换账号或重复使用后须重新以 publish intent 打包,不能改传文件路径绕过。++## 7.3 个人插件发布到社区++普通个人作者发布到社区使用独立入口:先在作者源码目录开发、安装并实际使用插件,再调用+`ghost_contribution_prepare({ ghost_id, namespace: null })`。Host 固定当前精确安装的包并返回+只读发布摘要:实际版本、包内更新说明以及提审阻塞原因;此时没有创建上传或占用版本。+首次上架不要求更新说明,插件用途写在 `description`。插件曾上架后再提审时,须在 `ghost.json` 顶层写入 `releaseNotes` 纯文本字符串(v2、v3 均支持),完整描述相对上一已上架版本的全部变化。+例如文本工具的更新说明可写“相较已上架的 1.0.0:新增 UTF-8 字节数统计,修复末尾空行计数”。+示例须核对源码与实际变化,不自动套用。该字段随包携带,不在发布时另填资料。+缺字段的包仍能打包和安装;只有曾上架插件的更新缺少非空说明时,预检才返回 `RELEASE_NOTES_REQUIRED`。从未上架的退回或取消不视为更新,下架不免除更新说明要求。++安装与运行批准不证明作者身份,也不授予公开发布权。首次发布只接受 Host 可核实的本地包或 Forge 开发安装,属于等待人工审核的发布申请,不是作者认证。+官方 public 插件必须通过 GitHub 仓库提交修改,不允许经客户端(含 Agent 工具)提审,以保证仓库源码完整、便于后续维护。普通第三方公共插件仍沿既有授权流程。+从公共市场下载的第三方插件,只有当前账号已有精确提交授权且 Host 核实原安装来源时才能提交更新;Git/本地自定义市场、私域或来源无法确认的安装不能转作首发。+可读取发布历史不等于可提交更新。旧发布回执、同名、包内 author 或相同包摘要均不能替代当前授权;恢复原操作也重新核对账号、安装、批准与来源。+已有明确公开发布委托时,先读取摘要并确认包内说明适用,再调用+`ghost_contribution_submit({ prepared_id })`。Full Access 直接执行,Auto 走现有审阅,Ask 走既有权限卡,+不要求额外的最后人工点击。Host 在提交前再次检查已安装内容,变更后必须刷新摘要,不能悄悄替换包。+用户已明确委托发布时,不再另问一次是否发布。预检有 blockers 时先说明具体原因;需要改包则回到+现有作者源码,用原 Forge 工具修改、安装更新后重新预检,不直接改 Host 管理的安装目录。+权限拒绝按原任务权限处理,返回原因并停止,不切换权限或借其它入口重试。+当前个人账号普通任务可用;共享访客及插件托管任务不能借用房主账号。++一次成功提审永久占用该插件的版本号,退回、取消或下架都不能复用;修改后需要换版本号、重新安装再提交。+每个插件同时只能有一个待审版本。`ghost_my_plugins` 读取本人插件及精确版本结果;停止上传用+`ghost_contribution_stop`,不等于取消审核。取消待审用 `ghost_cancel_plugin_review`,传本人详情返回的+plugin_id、release_id、sha256 和 revision;取消保留版本与记录,当前上架版不变。审核已结束时返回实际终局。+不设计多作者代取消。++提交立即返回原操作句柄;202 / processing 仅为处理中,不等于待审核。网络结果未知先查+`ghost_contribution_status({ local_id })`,再以 `ghost_contribution_submit({ prepared_id: local_id, resume: true })`+恢复同操作、同包、同键,不能盲目新建操作。旧服务回执仍可能包含 metadata_updated / unchanged;它们不是新版提审许可。+只有服务端回执、实际审核及市场可用事实才能说明已提审、已通过或已上架。++`ghost_my_plugins` 的 plugin_id 读详情,submission_id 读精确留存包内容,cursor 为分页。+时间取真实提审/通过/取消事件,未知为未知;当前市场和所选版本分开读取。旧版上架而新版被退回时+完整保留旧市场版本与退回原因。作者在“我的插件”的独立管理页查看使用中、已上架和待审核版本;普通插件详情仍用于使用和配置,+只有本地来源插件提供“提交审核”快速入口,管理页的后续提交入口为“提交新版本审核”,不支持提交时不展示管理页提交按钮。+插件列表沿用主线原有来源展示,不用来源标签表示作者身份或审核、上架状态;发布情况在“我的插件”中查看。+选择发布历史只改变所查看的快照,不切换使用版本。审核结果在应用内提示未读,不新增外部通知、+不让审核人修包、不依赖先上线分享页。+已有 public 插件权限由服务端精确 ACL 决定,包内署名、本地安装与同名均不证明权利;私域不经此入口转公域。++## 7.4 个人署名与匿名设置++个人社区插件默认匿名;匿名是整款插件的服务端设置,与当前查看的版本无关。+只有固定原作者可随时在“我的插件”的管理页名称右侧修改;安装或提交资格都不能代替原作者匿名修改权。+当前 Agent 工具可查询发布详情,不提供修改匿名的能力;不要通过写文件或调用未声明接口代改。+不要在 `ghost.json` 中添加 `anonymous` 字段;包内 `author` 也不能指定平台的可信发布署名。++关闭匿名后显示相应版本提审时保存的原作者账号昵称。修改账号昵称不会自动改变旧版;+原作者下次提审时保存新昵称。当前个人发布按单作者流程使用,不提供多人协作入口。+匿名隐藏平台展示的署名和作者搜索资料,不会清除作者写进源码、README 或包内的个人信息。+历史内容和更新说明按对应版本的提审快照展示,不用当前本地包补写历史。+可信官方来源固定署名 Cindy,不显示个人匿名开关;组织插件沿用原有发布与署名规则。+缺少作者关系或当前服务端不提供设置时,不推断为可编辑原作者,也不把本地安装当作作者资格。diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 988ac4f3ee..f26ab92fdf 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -1132,6 +1132,7 @@ import { getGhostSetupInteractionBridge } from './cindy-brain/ghostSetupInteractimport { registerPluginMarketIpc, syncDefaultMarketPlugins } from './plugin-market/registerIpc.js';import { getPluginMarketService } from './plugin-market/service.js';import { StableOwnerPostCommitStep } from './stableOwnerPostCommit.js';+import { registerPluginContributionsIpc } from './plugin-contributions/registerIpc.js';import { registerPluginPublisherIpc } from './plugin-publisher/registerIpc.js';import { findCindyFileInArgv } from './cindy-brain/argv.js';import { handleIncomingCindyFile } from './cindy-brain/openFileInstall.js';@@ -2507,6 +2508,7 @@ setRemotePluginManagementServices({registerGhostIpc();registerPluginMarketIpc();registerPluginPublisherIpc();+registerPluginContributionsIpc();setAppSessionCommitBoundaryHook(() => {// 进行中的 Claude Code 登录属于旧 owner:结束 CLI 子进程,不让它在新 owner 下完成。cancelClaudeCliLogin();diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex 9a1f835480..776640d244 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -262,6 +262,9 @@ function cloneParsedGhostPackage(parsed: ParsedGhostPackage): ParsedGhostPackage}export interface GhostManagerOptions {+ /** Read-only source projections. Does not affect running, installation, or publishing ACL. */+ sourcesForInstance?: (record: PluginInstanceRecord, receipt: PluginInstanceReceiptFact | null | undefined) =>+ Pick<InstalledGhost, 'publishingSource'>;/** 意识仓库根目录(生产:userData/cindy-brain;测试:os.tmpdir 下临时目录)。 */getRootDir: () => string;/** Host 批准状态根;必须位于插件安装根之外。 */@@ -837,21 +840,23 @@ export class GhostManager {return createPluginInstanceRegistryStore(pluginInstanceRegistryPath(this.stateRootDir()));}- private listContentEntries(): Array<{ relId: string; dir: string }> {+ private listContentEntries(strict = false): Array<{ relId: string; dir: string }> {const root = this.contentRootDir();let entries: fs.Dirent[];try {entries = fs.readdirSync(root, { withFileTypes: true });- } catch {+ } catch (error) {+ if (strict && (error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;return [];}- const listed = this.listManagedInstallDirs(root);+ const listed = this.listManagedInstallDirs(root, strict);for (const entry of entries) {if (entry.name.startsWith('.') || entry.name === PLUGIN_NS_INSTALL_ROOT) continue;const dir = path.join(root, entry.name);try {if (classifyGhostDirEntrySync(dir) !== 'directory') continue;- } catch {+ } catch (error) {+ if (strict && (error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;continue;}if (!isValidGhostId(entry.name)) {@@ -889,9 +894,46 @@ export class GhostManager {return this.instanceRegistryService.recordForAddress(id);}+ /** Author management must not turn an unreadable installation scan into "not installed". */+ assertContributionReadAvailable(ghostId?: string): void {+ this.ensureCurrentOwnerContextSync();+ const registry = this.instanceRegistryStore().read();+ if (registry.kind !== 'ok' && registry.kind !== 'missing') {+ throw new Error('plugin instance registry is ' + registry.kind);+ }+ if (registry.kind === 'ok' && Object.values(registry.registry.instances).some((record) =>+ record.active && (!ghostId || record.ghostId === ghostId) &&+ this.hasPendingMutationJournal(record.contentRelId))) {+ throw new Error('plugin installation is changing');+ }+ for (const { relId, dir } of this.listContentEntries(true)) {+ const identity = parsePluginInstallRelId(relId);+ if (!identity || (ghostId && identity.ghostId !== ghostId)) continue;+ if (this.hasPendingMutationJournal(relId)) throw new Error('plugin installation is changing');+ const approval = this.readApproval(relId);+ if (approval.state === 'invalid') throw new Error('plugin approval evidence is unavailable');+ if (approval.state === 'approved') continue;+ // list() may skip an unreadable legacy manifest. Do not interpret that+ // omitted entry as proof that the user's corresponding plugin is absent.+ try {+ const manifestPath = resolveGhostContentPathSync(dir, GHOST_MANIFEST_FILE, {+ expect: 'file', label: 'installed manifest',+ });+ const bytes = readBoundedFileNoFollowSync(manifestPath, MAX_GHOST_MANIFEST_BYTES);+ const parsed = bytes && parseInstalledGhostManifest(JSON.parse(bytes.toString('utf8')));+ if (!parsed || !parsed.ok || parsed.manifest.id !== identity.ghostId) {+ throw new Error('invalid manifest');+ }+ } catch {+ throw new Error('plugin manifest evidence is unavailable');+ }+ }+ }+private instanceProjection(relId: string, ghostId: string): {instanceKey?: string;+ publishingSource?: InstalledGhost['publishingSource'];namespace?: string | null;namespaceState?: PluginInstanceRecord['namespaceState'];} {@@ -901,6 +943,7 @@ export class GhostManager {if (!record || record.ghostId !== ghostId) return {};return {instanceKey: record.instanceKey,+ ...this.options.sourcesForInstance?.(record, this.receiptFact(relId)),namespaceState: record.namespaceState,...(record.namespaceState === 'confirmed' || record.namespaceState === 'unconfirmed'? { namespace: record.namespace } : {}),@@ -1164,7 +1207,7 @@ export class GhostManager {}, ghostId, namespace, basis, expectedReceipt);}- private listManagedInstallDirs(root: string): Array<{ relId: string; dir: string }> {+ private listManagedInstallDirs(root: string, strict = false): Array<{ relId: string; dir: string }> {const listed: Array<{ relId: string; dir: string }> = [];const managedRoot = path.join(root, PLUGIN_NS_INSTALL_ROOT);let parents: string[];@@ -1173,7 +1216,8 @@ export class GhostManager {parents = fs.readdirSync(managedRoot).filter((namespace) => namespace === PLUGIN_ROOT_INSTALL_DIR || isValidPluginNamespace(namespace)).map((namespace) => PLUGIN_NS_INSTALL_ROOT + '/' + namespace);- } catch {+ } catch (error) {+ if (strict && (error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;return listed;}for (const parent of parents) {@@ -1182,7 +1226,8 @@ export class GhostManager {try {if (classifyGhostDirEntrySync(parentDir) !== 'directory') continue;entries = fs.readdirSync(parentDir);- } catch {+ } catch (error) {+ if (strict && (error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;continue;}for (const entry of entries) {@@ -1191,7 +1236,8 @@ export class GhostManager {const dir = path.join(parentDir, entry);try {if (classifyGhostDirEntrySync(dir) === 'directory') listed.push({ relId, dir });- } catch {+ } catch (error) {+ if (strict && (error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;continue;}}diff --git a/apps/desktop/src/main/cindy-brain/__tests__/exportGhostPackage.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/exportGhostPackage.test.tsindex 66a04961a2..b497442eff 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/exportGhostPackage.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/exportGhostPackage.test.ts@@ -7,7 +7,7 @@ import JSZip from 'jszip';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { InstalledGhost } from '../../../shared/ghost';-import { exportGhostPackage, sanitizeExportFileNamePart } from '../exportGhostPackage';+import { exportGhostPackage, snapshotInstalledGhostPackage, sanitizeExportFileNamePart } from '../exportGhostPackage';import { MAX_BASIC_ZIP_ENTRIES } from '../GhostManager';import { signGhostPackage } from '../ghostSignature';@@ -136,6 +136,27 @@ function makeDeps(overrides: Partial<Parameters<typeof exportGhostPackage>[1]> =};}+describe('snapshotInstalledGhostPackage', () => {+ 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');+ await fs.promises.mkdir(otherDir);+ await fs.promises.writeFile(path.join(otherDir, 'ghost.json'), JSON.stringify(root.manifest));+ await fs.promises.writeFile(path.join(otherDir, 'main.js'), 'OTHER_OWNER');+ const deps = makeDeps({ listInstalled: () => [{ ...root, namespace: 'another-org', dir: otherDir }, root] });+ const result = await snapshotInstalledGhostPackage('hello', deps);+ expect(result.status).toBe('prepared');+ if (result.status !== 'prepared') throw new Error('Expected a package snapshot');+ await fs.promises.writeFile(path.join(ghostDir, 'main.js'), 'CHANGED_AFTER_PREPARING');+ const zip = await JSZip.loadAsync(result.bytes);+ expect(await zip.file('main.js')!.async('string')).toBe('console.log("hi")');+ expect(result.ghost.dir).toBe(ghostDir);+ expect(deps.showSaveDialog).not.toHaveBeenCalled();+ expect(Object.keys(zip.files)).not.toContain('.cindy-trust.json');+ expect(Object.keys(zip.files)).not.toContain('.disabled');+ });+});+describe('exportGhostPackage', () => {it.skipIf(process.platform === 'win32')('round-trips installed Unix execute bits while stripping special bits',diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pluginPublishingSource.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pluginPublishingSource.test.tsnew file mode 100644index 0000000000..3d8280403b--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/pluginPublishingSource.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest';+import type { PluginInstanceRecord, PluginInstanceReceiptFact } from '../pluginInstanceRegistry';+import type { PluginMarketInstallationRecord } from '../../plugin-market/ledger';+import { projectPluginPublishingSource } from '../pluginPublishingSource';++const record: PluginInstanceRecord = { instanceKey: '_root__example', contentRelId: '_ns/_root/example',+ ghostId: 'example', namespace: null, namespaceState: 'confirmed', source: 'manual', pluginId: null,+ receiptRevision: 'revision', packageSha256: 'a'.repeat(64), active: true };+const receipt: PluginInstanceReceiptFact = { ghostId: 'example', hasNamespace: true, namespace: null,+ revision: 'revision', packageSha256: 'a'.repeat(64) };+const market: PluginMarketInstallationRecord = { pluginId: 'public-id', ghostId: 'example', namespace: null,+ releaseId: 'release', version: '1.0.0', sha256: 'a'.repeat(64), scope: 'public', organizationId: null,+ source: 'market', installed: true, updatedAt: '2026-10-20T00:00:00.000Z' };+describe('publishing provenance does not grant authorship', () => {+ it('permits a verified local package path but refuses unreadable evidence and legacy guesses', () => {+ expect(projectPluginPublishingSource(record, receipt, { kind: 'absent' })).toEqual({ kind: 'local', source: 'manual' });+ expect(projectPluginPublishingSource(record, undefined, { kind: 'absent' }).kind).toBe('unavailable');+ expect(projectPluginPublishingSource(record, receipt, { kind: 'invalid' }).kind).toBe('unavailable');+ expect(projectPluginPublishingSource({ ...record, source: 'legacy' }, receipt, { kind: 'absent' }).kind).toBe('unavailable');+ expect(projectPluginPublishingSource(record, { ...receipt, revision: 'replacement' }, { kind: 'absent' }).kind).toBe('unavailable');+ });+ it.each(['git-market', 'local-market'] as const)('does not turn %s installation into first publication', source => {+ expect(projectPluginPublishingSource(record, receipt, { kind: 'found', record: { ...market, source } }).kind).toBe('unavailable');+ });+ it('requires the exact public market identity and approved bytes, independently of publishing ACL', () => {+ const installed = { ...record, source: 'market' as const, pluginId: market.pluginId };+ expect(projectPluginPublishingSource(installed, receipt, { kind: 'found', record: market })).toEqual({ kind: 'public-market', pluginId: market.pluginId });+ expect(projectPluginPublishingSource({ ...installed, pluginId: 'other' }, receipt, { kind: 'found', record: market }).kind).toBe('unavailable');+ expect(projectPluginPublishingSource(installed, receipt, { kind: 'absent' }).kind).toBe('unavailable');+ expect(projectPluginPublishingSource(installed, receipt, { kind: 'found', record: { ...market, scope: 'personal' } }).kind).toBe('unavailable');+ });+});diff --git a/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts b/apps/desktop/src/main/cindy-brain/exportGhostPackage.tsindex 6ec48fde97..97cbabe429 100644--- a/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts+++ b/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts@@ -2,7 +2,8 @@* exportGhostPackage* ---------------------------------------------------------------------------* 插件详情页「导出 .cindy」的打包业务体:把已装插件的安装目录重新打成- * .cindy zip 包,供 main IPC handler 经系统保存对话框落盘。+ * .cindy zip 包。snapshotInstalledGhostPackage 供社区投稿直接固定当前包,+ * exportGhostPackage 保持经系统保存对话框导出的原行为。** 设计(第一性原理:导出包必须可原样通过装入校验):*@@ -526,10 +527,13 @@ async function snapshotPackage(return null;}-export async function exportGhostPackage(+export async function snapshotInstalledGhostPackage(id: unknown,- deps: ExportGhostPackageDeps,-): Promise<ExportGhostPackageResult> {+ deps: Pick<ExportGhostPackageDeps, 'listInstalled'>,+): Promise<+ | { status: 'prepared'; bytes: Buffer; ghost: InstalledGhost; contentSha256: string }+ | Exclude<ExportGhostPackageResult, { status: 'saved' } | { status: 'canceled' }>+> {if (typeof id !== 'string' || !isGhostInstanceId(id)) {return { status: 'invalid_id' };}@@ -580,6 +584,23 @@ export async function exportGhostPackage(}if (buf.byteLength > maxArchive) return { status: 'error', code: 'too_large' };+ const contentEntries = snapshot.entries.map(file => [+ file.rel, file.unixPermissions, crypto.createHash('sha256').update(file.data).digest('hex'),+ ]).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 };+}++export async function exportGhostPackage(+ id: unknown,+ deps: ExportGhostPackageDeps,+): Promise<ExportGhostPackageResult> {+ const prepared = await snapshotInstalledGhostPackage(id, deps);+ if (prepared.status !== 'prepared') return prepared;+ const { bytes: buf, ghost } = prepared;+const baseName = sanitizeExportFileNamePart(ghost.manifest.name) || ghost.manifest.id;// 版本同样来自作者清单,可能与名字一样含路径分隔符/控制字符,// 必须走同一道清洗再拼进默认文件名。组合后按 UTF-8 字节数截断——diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 35a2490d43..fb7dfccf26 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -8,6 +8,7 @@ import { projectPluginWorkdir, resolvePluginWorkdir } from './remotePluginProjecimport { takePeerAttachment } from '../device-link/peerAttachmentStore.js';import { parsePeerAttachmentRef } from '@cindy/device-link';import { capturePluginOauthPeer } from '../plugin-oauth/runtime.js';+import { projectPluginPublishingSource } from './pluginPublishingSource.js';import { readMobilePreview } from './mobilePreview.js';import { createMailReader, mailReaderRemoteProvider } from './mailReader.js';import { assertRemoteBotInvocationAllowed } from '../device-link/remoteBotSessionBoundary.js';@@ -1905,6 +1906,17 @@ export function getGhostManager(): GhostManager {return null;}},+ sourcesForInstance: (record, receipt) => {+ let lookup: ReturnType<ReturnType<typeof getPluginMarketLedger>['lookupInstallationForAuthorization']>;+ try {+ lookup = getPluginMarketLedger().lookupInstallationForAuthorization({ ghostId: record.ghostId, namespace: record.namespace });+ } catch {+ lookup = { kind: 'invalid' };+ }+ return {+ publishingSource: projectPluginPublishingSource(record, receipt, lookup),+ };+ },canResumePendingResidentOffline: (ghostId) => getNamespaceMigrationHost().canResumePendingResidentOffline(ghostId),onResumePendingResidentOffline: (ghost) => {if (!isGhostAvailableForActiveSession(ghost.manifest.id)) return;@@ -8557,6 +8569,12 @@ export function registerGhostIpc(): void {// The migration body has its own committed-owner gate, so signed-out runs// the common activation phase without touching legacy account data.const activationOutcome = activateGhostsAndMigrateLegacyAccounts();+ if (+ activeOwnerScopeKey() !== scope.scopeKey ||+ getActiveAppSession().dataOwnerId !== scope.dataOwnerId+ ) {+ return 'deferred';+ }return outcome === 'failed'? 'failed': outcome === 'retry-pending' || activationOutcome === 'retry-pending'diff --git a/apps/desktop/src/main/cindy-brain/pluginPublishingSource.ts b/apps/desktop/src/main/cindy-brain/pluginPublishingSource.tsnew file mode 100644index 0000000000..982f306e62--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/pluginPublishingSource.ts@@ -0,0 +1,25 @@+import type { InstalledGhost } from '../../shared/ghost.js';+import type { PluginMarketAuthorizationLookup } from '../plugin-market/ledger.js';+import type { PluginInstanceRecord, PluginInstanceReceiptFact } from './pluginInstanceRegistry.js';++/** Rebuilt from existing Host facts; never grants authorship or changes installation state. */+export function projectPluginPublishingSource(+ record: PluginInstanceRecord,+ receipt: PluginInstanceReceiptFact | null | undefined,+ lookup: PluginMarketAuthorizationLookup,+): NonNullable<InstalledGhost['publishingSource']> {+ const unavailable = { kind: 'unavailable' } as const;+ if (!record.active || record.namespaceState !== 'confirmed' || record.namespace !== null ||+ !receipt || !receipt.hasNamespace || receipt.namespace !== null || receipt.ghostId !== record.ghostId ||+ receipt.revision !== record.receiptRevision || receipt.packageSha256 !== record.packageSha256 ||+ lookup.kind === 'invalid') return unavailable;+ const market = lookup.kind === 'found' ? lookup.record : null;+ if (market && (market.scope !== 'public' || market.organizationId !== null)) return unavailable;+ if (market?.installed && market.source !== 'market' && market.source !== 'legacy-adopted') return unavailable;+ if (record.source === 'manual' || record.source === 'agent-forge')+ return { kind: 'local', source: record.source };+ if (record.source === 'market' && market?.installed && market.namespace === null &&+ market.pluginId === record.pluginId && market.sha256 === receipt.packageSha256)+ return { kind: 'public-market', pluginId: market.pluginId };+ return unavailable;+}diff --git a/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts b/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.tsindex 8342c3c1ec..7c1c7da997 100644--- a/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/sharedTaskDispatch.test.ts@@ -102,7 +102,7 @@ describe('sharedTask dispatch scope', () => {args: ['permission-1', { kind: 'permission', behavior: 'allow', permissionUpdates: [permissionSuggestion] }],})).not.toThrow();});- it.each(['cindy.app.update', 'cindy.app.auto_update'])('keeps the owner-only %s card away from guests', (toolName) => {+ it.each(['cindy.app.update', 'cindy.app.auto_update', 'ghost_contribution_submit', 'ghost_cancel_plugin_review'])('keeps the owner-only %s card away from guests', (toolName) => {setSharedTaskInteractionReader(() => ({ sessionId: 'task', kind: 'permission', toolName }));for (const behavior of ['allow', 'deny']) {const args = ['app-update-1', { kind: 'permission', behavior }];diff --git a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts b/apps/desktop/src/main/device-link/sharedTaskDispatch.tsindex 18eaab5afb..c7fb2d9549 100644--- a/apps/desktop/src/main/device-link/sharedTaskDispatch.ts+++ b/apps/desktop/src/main/device-link/sharedTaskDispatch.ts@@ -170,7 +170,7 @@ function assertSharedTaskInteractionResolve(if (args.length !== 2 || typeof args[0] !== 'string' || !args[0]) deny();const interaction = phase === 'invoke' ? readInteractionSession?.(args[0]) : undefined;if (phase === 'invoke' && (!interaction || interaction.sessionId !== sessionId)) deny();- if (interaction?.toolName && OWNER_ONLY_HOST_CONFIRMATION_TOOL_NAMES.has(interaction.toolName)) deny();+ if (interaction?.toolName && (OWNER_ONLY_HOST_CONFIRMATION_TOOL_NAMES.has(interaction.toolName) || ['ghost_contribution_submit', 'ghost_cancel_plugin_review'].includes(interaction.toolName))) deny();const decision = record(args[1]);if (!decision || typeof decision.kind !== 'string' || !interactionDecisionKinds.has(decision.kind)) deny();// Guests approve the host-displayed input, never substitute executable input.diff --git a/apps/desktop/src/main/maker-host/built-in-skills.ts b/apps/desktop/src/main/maker-host/built-in-skills.tsindex 04af10afc5..91ca66daf8 100644--- a/apps/desktop/src/main/maker-host/built-in-skills.ts+++ b/apps/desktop/src/main/maker-host/built-in-skills.ts@@ -25,7 +25,7 @@ const VERSIONS_DIRECTORY = '.versions';const ACTIVE_BUNDLE_LINK = '.active';const BUILT_IN_SKILL_MUTATION_WAIT_MS = 5_000;/** Increment whenever shipped built-in Skill bytes change between releases. */-export const BUILT_IN_SKILLS_BUNDLE_VERSION = 16;+export const BUILT_IN_SKILLS_BUNDLE_VERSION = 17;const PLUGIN_CREATOR_FIRST_BUNDLE_VERSION = 13;export interface BuiltInSkillDescriptor {diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex b4125dbfcb..d605c7649b 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -1,4 +1,5 @@import { readGeneratedImageEpoch } from '../cindy-media/generatedImageStorage';+import { resolveHelperSurface } from '../mcp-integrations/helperSurface.js';import { readAgentCapabilityCatalog, RUNTIME_MCP_NAMES_KEY, type AgentCapabilityQuery } from './agentCapabilityCatalog.js';import { listCindyManagedSkills, prepareCindyCodexSkills } from './managed-skills.js';import { scanLocalCustomizations } from '../skillhub/customizationScanHost';@@ -117,6 +118,8 @@ import type { MakerSessionCreateOpts } from '../maker-ipc/sessionRequest.js';import {dispatchInterAgentMessage,isActiveInputOwnerAuthored,+ isActiveInputAccountScoped,+ getSessionInputProvenance,isSessionInTurn,wireSessionToIpc,} from '../maker-ipc/register.js';@@ -1100,6 +1103,14 @@ export function getMaker(): Maker {if (!session || session.instanceId !== sessionInstanceId) return null;const snapshot = resolveGhostFsSessionSnapshot((id) => _maker?.getSession(id), sessionId, sessionInstanceId);return {+ contributionAccountAllowed: async () => {+ if (!isActiveInputAccountScoped(sessionId) || isAppSessionBoundaryPending()) return false;+ const db = getCurrentDbClientSnapshot();+ if (!db) return false;+ const surface = await resolveHelperSurface(db.client, sessionId, getSessionInputProvenance);+ return surface !== 'restricted' && db === getCurrentDbClientSnapshot()+ && !isAppSessionBoundaryPending() && isActiveInputAccountScoped(sessionId);+ },permissionMode: session.stablePermissionModeState?.mode ?? null,remoteHostId: session.remoteHostId,isCurrent: () => !!snapshot && !snapshot.planModeEnabled && snapshot.permissionMode !== 'plan'diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.tsindex 8830e369aa..8d37401d7e 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts@@ -2239,6 +2239,22 @@ describe('AgentInputCoordinator send transaction', () => {expect(h.coordinator.isActiveInputOwnerAuthored(sid)).toBe(false);});+ it.each([+ ['the owner', {}, true],+ ['an ordinary scheduled task', { origin: { kind: 'scheduler' as const, scheduleId: 's', scheduleName: 'n' } }, true],+ ['an ordinary Worker', { origin: { kind: 'orca' as const, senderLabel: 'Lead' } }, true],+ ['a shared-task guest', { sharedTaskAuthor: { sharedTaskId: 't', sessionId: 'account-input', memberId: 'm', accountId: 'guest', displayName: 'G' } }, false],+ ])('keeps account tools scoped to %s throughout the active turn', async (_label, patch, expected) => {+ const h = createHarness(), sid = 'account-input';+ h.sendToAgent.mockImplementationOnce(async () => { h.setRunning(true); return sendSuccess(); });+ expect(h.coordinator.isActiveInputAccountScoped(sid)).toBe(false);+ h.coordinator.enqueue(sid, { ...makeItem('input', 'Check my plugins'), ...patch } as AgentInputQueuedMessage);+ await flush();+ expect(h.coordinator.isActiveInputAccountScoped(sid)).toBe(expected);+ h.setRunning(false); h.coordinator.onTurnEvent(sid, 'done');+ expect(h.coordinator.isActiveInputAccountScoped(sid)).toBe(false);+ });+it('judges owner authority by the latest accepted steer, in both directions', async () => {const h = createHarness(), sid = 'owner-authority-steer';h.sendToAgent.mockImplementationOnce(async () => { h.setRunning(true); return sendSuccess(); });diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.tsindex e89373a69d..8cbc916951 100644--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts@@ -1312,6 +1312,12 @@ export class AgentInputCoordinator {retrySourceClientId: item.retrySourceClientId ?? item.supersedesUserClientId };}+ /** Account-scoped tools may not borrow the Host identity from a shared guest input. */+ isActiveInputAccountScoped(sessionId: string): boolean {+ const item = this.states.get(sessionId)?.activeTurn?.item;+ return !!item && !item.sharedTaskAuthor;+ }+/*** Owner-only Host actions (app update) require the active input itself to be text* this account's user typed on Desktop or a same-account remote device. Automation,diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 05cb88240d..d76a0cd155 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -4467,6 +4467,11 @@ export function getTaskActionInputState(sessionId: string) {};}+/** Runtime-only account boundary for personal author tools; never grants external-write permission. */+export function isActiveInputAccountScoped(sessionId: string): boolean {+ return agentInputCoordinatorHolder?.isActiveInputAccountScoped(sessionId) ?? false;+}+/** Owner-authored active input (see AgentInputCoordinator.isActiveInputOwnerAuthored). */export function isActiveInputOwnerAuthored(sessionId: string): boolean {return agentInputCoordinatorHolder?.isActiveInputOwnerAuthored(sessionId) ?? false;diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.tsindex 7f3e16077a..ee45b5005a 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ghostWorkdirGate.test.ts@@ -25,6 +25,7 @@ import type {import { t } from '../../i18n';import { Session } from '@cindy/maker-core';import { resolveGhostFsSessionSnapshot } from '../../maker-ipc/ghostFsSessionSnapshot';+import { createIpcError } from '../../../shared/ipc-errors';import type { CindyGhostsHostDeps } from '../ghost';import type { GhostInstallConsentPrompt } from '../../cindy-brain/ghostInstallConsent';import type { InstalledGhost, GhostSetupAssessment } from '../../../shared/ghost';@@ -258,6 +259,19 @@ vi.mock('../ghostAttachmentResolve.js', () => ({resolveGhostAttachmentUrl: resolveGhostAttachmentUrlMock,}));+const communityReadMock = vi.fn();+const communitySubmitMock = vi.fn();+const communityPreparedMock = vi.fn();+vi.mock('../../plugin-contributions/host.js', () => ({+ listMyPlugins: (...args: unknown[]) => communityReadMock(...args),+ submitContribution: (...args: unknown[]) => communitySubmitMock(...args),+ mapContributionError: (error: unknown) => { throw error; },+}));+vi.mock('../../plugin-contributions/prepared.js', () => ({+ contributionOwnerKey: () => 'test-owner', assertContributionOwner: vi.fn(),+ getPreparedContribution: (...args: unknown[]) => communityPreparedMock(...args),+}));+const { authorizeDesktopSessionPath, getCindyGhostsMcpDeps, getGhostRosterPrompt } = await import('../ghost');const { createCindyGhostsMcpServer, handleGhostList, handleGhostInfo, handleGhostCall, handleGhostManual } = await import('cindy-tools');const { setGhostDisabledForWorkdir, listDisabledGhostIdsForWorkdir, isGhostDisabledForWorkdir } =@@ -3378,3 +3392,118 @@ describe('market install live authority', () => {expect(market.detail).not.toHaveBeenCalled();});});+++describe('personal contribution account surface', () => {+ beforeEach(() => {+ communityReadMock.mockReset();+ communitySubmitMock.mockReset();+ communityPreparedMock.mockReset();+ communityPreparedMock.mockReturnValue({ summary: {+ preparedId: 'prepared-1', ghostId: 'hello', name: 'Hello', description: 'Current installed plugin',+ version: '1.0.0', sha256: 'a'.repeat(64), releaseNotes: 'Complete release changes.\nIncludes all fixes.',+ } });+ communitySubmitMock.mockReturnValue({ localId: 'prepared-1', phase: 'preparing' });+ });++ it('blocks an account read when the live helper surface is restricted', async () => {+ communityReadMock.mockReset();+ liveGrantStateMock.mockReturnValue({ permissionMode: 'bypassPermissions', remoteHostId: null,+ isCurrent: () => true, contributionAccountAllowed: async () => false });+ const result = await makeDeps().communityContribution!({ action: 'list' });+ expect(result).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });+ expect(communityReadMock).not.toHaveBeenCalled();+ });++ it('discards personal results if the helper surface becomes restricted during the read', async () => {+ let allowed = true;+ communityReadMock.mockImplementationOnce(async () => { allowed = false; return { privateReason: 'private author record' }; });+ liveGrantStateMock.mockReturnValue({ permissionMode: 'bypassPermissions', remoteHostId: null,+ isCurrent: () => true, contributionAccountAllowed: async () => allowed });+ const result = await makeDeps().communityContribution!({ action: 'list' });+ expect(result).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });+ expect(JSON.stringify(result)).not.toContain('private author record');+ });++ it('allows an ordinary current account task to read its own records', async () => {+ communityReadMock.mockResolvedValueOnce({ plugins: [] });+ liveGrantStateMock.mockReturnValue({ permissionMode: 'bypassPermissions', remoteHostId: null,+ isCurrent: () => true, contributionAccountAllowed: async () => true });+ await expect(makeDeps().communityContribution!({ action: 'list' })).resolves.toEqual({ ok: true, result: { plugins: [] } });+ });++ it('returns a known publishing precondition so the author can fix the original package', async () => {+ const error = createIpcError('PRECONDITION_FAILED', 'This version is already submitted; install a new version before publishing.');+ communityPreparedMock.mockImplementationOnce(() => { throw error; });+ liveGrantStateMock.mockReturnValue({ permissionMode: 'bypassPermissions', remoteHostId: null,+ isCurrent: () => true, contributionAccountAllowed: async () => true });+ await expect(makeDeps().communityContribution!({ action: 'submit', id: 'prepared-1' }))+ .resolves.toEqual({ ok: false, errorCode: 'PRECONDITION_FAILED', message: error.message });+ expect(communitySubmitMock).not.toHaveBeenCalled();+ });++ it.each([new Error('private-transport-token'), createIpcError('INTERNAL', 'private-transport-token')])('does not expose unexpected publishing failures (%#)', async (error) => {+ communityPreparedMock.mockImplementationOnce(() => { throw error; });+ liveGrantStateMock.mockReturnValue({ permissionMode: 'bypassPermissions', remoteHostId: null,+ isCurrent: () => true, contributionAccountAllowed: async () => true });+ const result = await makeDeps().communityContribution!({ action: 'submit', id: 'prepared-1' });+ expect(result).toMatchObject({ ok: false, errorCode: 'INTERNAL' });+ expect(JSON.stringify(result)).not.toContain('private-transport-token');+ expect(communitySubmitMock).not.toHaveBeenCalled();+ });++ it('submits the fixed preparation in Full Access without an extra confirmation', async () => {+ const permission = vi.fn();+ liveGrantStateMock.mockReturnValue({ permissionMode: 'bypassPermissions', remoteHostId: null,+ isCurrent: () => true, contributionAccountAllowed: async () => true });+ const deps = makeDeps('pi', 'author', 'author-instance', {}, undefined, permission);+ await expect(deps.communityContribution!({ action: 'submit', id: 'prepared-1' })).resolves.toMatchObject({ ok: true });+ expect(communityPreparedMock).toHaveBeenCalledWith('prepared-1');+ expect(communitySubmitMock).toHaveBeenCalledExactlyOnceWith('prepared-1', expect.any(Function));+ expect(permission).not.toHaveBeenCalled();+ });++ it.each(['allow', 'block'] as const)('honors Auto %s for the exact public bytes', async (verdict) => {+ const permission = vi.fn();+ const reviewAction = vi.fn<(action: { description: string }) => Promise<{ verdict: typeof verdict; reason: string }>>()+ .mockResolvedValue({ verdict, reason: 'Public publishing is outside the approved scope.' });+ liveGrantStateMock.mockReturnValue({ permissionMode: 'auto', remoteHostId: null, reviewAction,+ isCurrent: () => true, contributionAccountAllowed: async () => true });+ const result = await makeDeps('codex', 'author', 'author-instance', {}, undefined, permission)+ .communityContribution!({ action: 'submit', id: 'prepared-1' });+ expect(JSON.parse(reviewAction.mock.calls[0]![0].description)).toMatchObject({+ toolName: 'ghost_contribution_submit', input: {+ prepared_id: 'prepared-1', ghost_id: 'hello', version: '1.0.0', sha256: 'a'.repeat(64), public: true,+ },+ });+ expect(result).toMatchObject(verdict === 'allow' ? { ok: true } : {+ ok: false,+ errorCode: 'PERMISSION_DENIED',+ message: 'Public publishing is outside the approved scope.',+ });+ expect(communitySubmitMock).toHaveBeenCalledTimes(verdict === 'allow' ? 1 : 0);+ expect(permission).not.toHaveBeenCalled();+ });++ it.each([false, true])('rechecks the account surface after Ask confirmation (restricted=%s)', async (restrict) => {+ let allowed = true;+ const permission = vi.fn(async () => {+ allowed = !restrict;+ return { kind: 'permission' as const, behavior: 'allow' as const };+ });+ liveGrantStateMock.mockReturnValue({ permissionMode: 'ask', remoteHostId: null,+ isCurrent: () => true, contributionAccountAllowed: async () => allowed });+ const result = await makeDeps('pi', 'author', 'author-instance', {}, undefined, permission)+ .communityContribution!({ action: 'submit', id: 'prepared-1' });+ expect(permission).toHaveBeenCalledWith('author', 'author-instance', expect.objectContaining({+ toolName: 'ghost_contribution_submit', metadata: { hostOwnedConfirmation: 'plugin_contribution' },+ input: { prepared_id: 'prepared-1', ghost_id: 'hello', version: '1.0.0', sha256: 'a'.repeat(64) },+ description: expect.stringContaining('Complete release changes.\nIncludes all fixes.'),+ }), expect.any(AbortSignal));+ expect(permission).toHaveBeenCalledWith('author', 'author-instance', expect.objectContaining({+ description: expect.stringContaining('Once a submission is accepted for review, its version number cannot be reused'),+ }), expect.any(AbortSignal));+ expect(result).toMatchObject(restrict ? { ok: false, errorCode: 'PERMISSION_DENIED' } : { ok: true });+ expect(communitySubmitMock).toHaveBeenCalledTimes(restrict ? 0 : 1);+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/helperSurface.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/helperSurface.test.tsindex 0f0c414e78..96ef97503d 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/helperSurface.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/helperSurface.test.ts@@ -1,5 +1,6 @@-import { describe, expect, it } from 'vitest';-import { classifyHelperSurface } from '../helperSurface.js';+import { describe, expect, it, vi } from 'vitest';+import type { DbClient } from '../../localDb/client/DbClient.js';+import { classifyHelperSurface, resolveHelperSurface } from '../helperSurface.js';describe('classifyHelperSurface', () => {it.each([@@ -34,3 +35,21 @@ describe('classifyHelperSurface', () => {expect(classifyHelperSurface(undefined, false)).toBe('default');});});+++describe('personal author tools reuse the helper surface', () => {+ const ordinary = { source: 'user', botId: null, botRole: null, status: 'active', remoteHostId: null, pluginOwned: 0, retainedPlugin: 0, isWorker: 0 };+ function db(row: typeof ordinary) {+ return { queryOne: vi.fn().mockResolvedValue(row) } as unknown as Pick<DbClient, 'queryOne' | 'drizzle'>;+ }+ it.each([0, 1])('restricts plugin-owned tasks and their Workers (worker=%s)', async (isWorker) => {+ await expect(resolveHelperSurface(db({ ...ordinary, pluginOwned: 1, retainedPlugin: 1, isWorker }), 'session', () => ({ executing: true, input: { clientId: 'plugin-task:request', originKind: 'plugin' } }))).resolves.toBe('restricted');+ });+ it('keeps revoked-but-still-executing plugin input restricted', async () => {+ await expect(resolveHelperSurface(db({ ...ordinary, retainedPlugin: 1, isWorker: 1 }), 'worker', () => ({ executing: true, input: { clientId: 'plugin-task:request', originKind: 'orca' } }))).resolves.toBe('restricted');+ });+ it('does not exclude ordinary user Workers or automation', async () => {+ await expect(resolveHelperSurface(db({ ...ordinary, isWorker: 1 }), 'worker', () => ({ executing: true, input: { clientId: 'orca-input', originKind: 'orca' } }))).resolves.toBe('default');+ await expect(resolveHelperSurface(db(ordinary), 'scheduled', () => ({ executing: true, input: { clientId: 'automation-input', autoResume: true } }))).resolves.toBe('default');+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.tsindex 5f7d5459f0..b945d663ef 100644--- a/apps/desktop/src/main/mcp-integrations/ghost.ts+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts@@ -1,3 +1,5 @@+import * as community from '../plugin-contributions/host.js';+import { contributionOwnerKey, assertContributionOwner, getPreparedContribution } from '../plugin-contributions/prepared.js';import { createPluginMarketAgentTools } from '../plugin-market/agentTools.js';import type { GhostInstallConsentPrompt } from '../cindy-brain/ghostInstallConsent.js';import {@@ -460,6 +462,8 @@ async function packForgeSource(* ──────────────────────────────────────────────────────────────────────── */export interface GhostGrantLiveSessionState {+ /** Rechecks accepted account input and the existing plugin-managed helper surface. */+ contributionAccountAllowed?: () => Promise<boolean>;permissionMode: PermissionMode | null;remoteHostId: string | null;/** Includes the captured permission/Plan generations and forbids active or unknown Plan. */@@ -1763,11 +1767,100 @@ export function getCindyGhostsMcpDeps(return { assertCurrent, release: () => undefined, consentPrompt: installConsentPrompt() };},});+ const contributionAuthority = async (write: boolean) => {+ const context = resolveSessionContext();+ const owner = contributionOwnerKey();+ const live = context?.sessionId && context.sessionInstanceId+ ? hostDeps.getLiveSessionGrantState?.(context.sessionId, context.sessionInstanceId) : null;+ const assert = async () => {+ assertContributionOwner(owner);+ if (!live || await live.contributionAccountAllowed?.() !== true || (write && (live.isCurrent?.() !== true || !live.permissionMode || workdirWriteVerdict(live.permissionMode, false) === 'deny'))) {+ throwIpcError('PERMISSION_DENIED', 'Community contributions require a current account task; shared-task guests cannot borrow the Host account');+ }+ assertContributionOwner(owner);+ };+ await assert();+ return { context: context!, assert };+ };return {...(marketTools ? {searchMarket: (query: string) => marketTools.search(query),installMarket: (request: { pluginId: string; releaseId: string }, signal?: AbortSignal) => marketTools.install(request, signal),} : {}),+ async communityContribution(input) {+ try {+ const authority = await contributionAuthority(['prepare', 'submit', 'resume', 'cancel', 'cancel-review'].includes(input.action));+ let result: unknown;+ if (input.action === 'prepare') {+ const resolved = resolveInstalledGhost(getGhostManager().list(), input.ghostId, input.namespace);+ if (resolved.status !== 'unique') return { ok: false, errorCode: resolved.status === 'ambiguous' ? 'GHOST_AMBIGUOUS' : 'GHOST_NOT_FOUND' };+ result = await community.prepareContribution(installedGhostStoragePart(resolved.ghost), 'ai');+ } else if (input.action === 'submit' || input.action === 'resume' || input.action === 'cancel-review') {+ const cancelTarget = input.action === 'cancel-review' ? await community.myPluginReviewTarget(input.pluginId, input.release.releaseId) : null;+ if (input.action === 'cancel-review' && (!cancelTarget || cancelTarget.release.sha256 !== input.release.sha256 || cancelTarget.release.revision !== input.release.revision)) throwIpcError('CONTRIBUTION_REVISION_STALE', 'Refresh this version before cancelling its review');+ if (input.action === 'cancel-review' && cancelTarget && ['approved', 'rejected', 'cancelled'].includes(cancelTarget.release.reviewStatus ?? '')) {+ await authority.assert();+ return { ok: true, result: cancelTarget.release };+ }+ const toolName = input.action === 'cancel-review' ? 'ghost_cancel_plugin_review' : 'ghost_contribution_submit';+ const prepared = input.action === 'cancel-review' && cancelTarget ? { preparedId: cancelTarget.release.releaseId, ghostId: input.pluginId, version: cancelTarget.release.version, sha256: cancelTarget.release.sha256, name: cancelTarget.name, description: t('settings.ghosts.contribution.cancelReviewDescription').replaceAll('{{version}}', cancelTarget.release.version) } : input.action === 'submit' ? getPreparedContribution(input.id).summary : input.action === 'resume' ? (await community.listContributionTransfers()).find((item) => item.localId === input.id)?.prepared : undefined;+ if (!prepared) throwIpcError('PRECONDITION_FAILED', 'Contribution preparation is unavailable');+ const context = authority.context;+ const live = hostDeps.getLiveSessionGrantState!(context.sessionId!, context.sessionInstanceId!);+ let allowed = live?.permissionMode === 'bypassPermissions';+ if (!allowed && live?.permissionMode === 'auto' && live.reviewAction) {+ const decision = await live.reviewAction(toolAutoReviewAction(toolName, {+ prepared_id: prepared.preparedId, ghost_id: prepared.ghostId, version: prepared.version, sha256: prepared.sha256, public: true,+ }));+ await authority.assert();+ if (decision.verdict === 'block') return {+ ok: false,+ errorCode: 'PERMISSION_DENIED',+ message: decision.reason ?? 'Automatic review denied this action; no publishing or cancellation request was sent.',+ };+ allowed = decision.verdict === 'allow';+ }+ if (!allowed) {+ if (!hostDeps.requestHostPermission) throwIpcError('PRECONDITION_FAILED', 'Contribution confirmation is unavailable');+ const decision = await hostDeps.requestHostPermission(context.sessionId!, context.sessionInstanceId!, {+ kind: 'permission', requestId: randomUUID(), toolName,+ input: { prepared_id: prepared.preparedId, ghost_id: prepared.ghostId, version: prepared.version, sha256: prepared.sha256 },+ title: t(input.action === 'cancel-review' ? 'settings.ghosts.contribution.cancelReview' : 'settings.ghosts.contribution.confirmSubmit'),+ description: [+ input.action === 'cancel-review' ? '' : t('settings.ghosts.contribution.confirmPublic'),+ `${prepared.name} · ${prepared.version}`,+ prepared.description,+ ...('releaseNotes' in prepared && typeof prepared.releaseNotes === 'string' && prepared.releaseNotes.trim()+ ? [t('settings.ghosts.contribution.releaseNotes'), prepared.releaseNotes] : []),+ input.action === 'cancel-review' ? '' : t('settings.ghosts.contribution.versionConsumedHint'),+ ].filter(Boolean).join('\n'),+ metadata: { hostOwnedConfirmation: 'plugin_contribution' },+ }, AbortSignal.timeout(10 * 60_000));+ allowed = decision?.kind === 'permission' && decision.behavior === 'allow';+ }+ await authority.assert();+ if (!allowed) return { ok: false, errorCode: 'MUTATION_CANCELLED' };+ result = input.action === 'cancel-review' ? await community.cancelPluginReview(input.pluginId, input.release, authority.assert) : input.action === 'submit' ? await community.submitContribution(input.id, authority.assert) : await community.resumeContribution(input.id, authority.assert);+ } else if (input.action === 'status') result = await community.contributionTransferStatus(input.id);+ else if (input.action === 'cancel') result = community.cancelContribution(input.id);+ else if (input.action === 'list') result = await community.listMyPlugins({ query: input.query ?? '', filter: input.filter ?? 'all', cursor: input.cursor });+ else if (input.action === 'submission') result = await community.myPluginSubmission(input.pluginId, input.submissionId);+ else if (input.action === 'detail') result = await community.myPluginDetail(input.pluginId, input.cursor);+ else result = community.listContributionTransfers();+ await authority.assert();+ return { ok: true, result };+ } catch (error) {+ try { community.mapContributionError(error); } catch (safe) {+ return {+ ok: false,+ errorCode: isIpcError(safe) ? safe.code : 'INTERNAL',+ message: isIpcError(safe) && safe.code !== 'INTERNAL'+ ? safe.message+ : 'Community contribution action could not complete; query the original operation before retrying.',+ };+ }+ }+ },connectAccount: async (target, signal) => {const context = resolveSessionContext();const sessionId = ghostSetupInteractionSessionId(context);diff --git a/apps/desktop/src/main/plugin-contributions/__tests__/api.test.ts b/apps/desktop/src/main/plugin-contributions/__tests__/api.test.tsnew file mode 100644index 0000000000..9de04c26cf--- /dev/null+++ b/apps/desktop/src/main/plugin-contributions/__tests__/api.test.ts@@ -0,0 +1,141 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { ServerApiError } from '../../serverApiClient';++const harness = vi.hoisted(() => ({+ owner: 'A:1',+ token: '',+ fetch: vi.fn(),+ discover: vi.fn(),+ refresh: vi.fn(),+}));+vi.mock('electron', () => ({+ app: { getVersion: () => '1.0.0' },+ net: { fetch: harness.discover },+}));+vi.mock('../../authManager', () => ({+ getAccessToken: () => harness.token,+ getActiveAuthRealm: () => 'cn',+ getAuthState: () => ({ user: { id: 'member-A' } }),+ refresh: harness.refresh,+}));+vi.mock('../../clientEndpointsService', () => ({+ getClientEndpoint: () => 'https://plugin.test',+ getClientEndpointForRealm: () => 'https://auth.test',+}));+vi.mock('../../serverApiClient', () => ({+ serverApiFetch: harness.fetch,+ ServerApiError: class extends Error {+ constructor(+ readonly code: string,+ readonly statusCode: number,+ message: string,+ ) {+ super(message);+ }+ },+}));+vi.mock('../prepared', () => ({+ contributionOwnerKey: () => harness.owner,+ assertContributionOwner: (owner: string) => {+ if (owner !== harness.owner) throw new Error('[OWNER_CHANGED] changed');+ },+}));++const issuer = 'https://trusted-issuer.test';+const subject = { authority: issuer, membershipId: 'member-A' };+const page = () => ({+ subject,+ queriedAt: '2026-10-15T00:00:00.000Z',+ plugins: [],+ nextCursor: null,+});+const listInput = { query: '', filter: 'all' };+import { ContributionApi as Api } from '../api';+let testClock = 0;+beforeEach(() => {+ vi.restoreAllMocks();+ vi.resetAllMocks();+ vi.spyOn(Date, 'now').mockReturnValue(Date.UTC(2026, 9, 21) + ++testClock * 360_000);+ harness.owner = 'A:1';+ harness.token = `unused.${Buffer.from(JSON.stringify({ iss: issuer, sub: 'member-A', ctx: 'personal' })).toString('base64url')}.unused`;+ harness.discover.mockResolvedValue({ ok: true, json: async () => ({ issuer }) });+ harness.fetch.mockResolvedValue(page());+});+afterEach(() => vi.restoreAllMocks());++describe('personal contribution authority', () => {+ it('rechecks a write guard after awaited discovery, before dispatching the original commit', async () => {+ let allowed = true;+ harness.discover.mockImplementationOnce(async () => {+ allowed = false;+ return { ok: true, json: async () => ({ issuer }) };+ });+ const api = new Api(async () => { if (!allowed) throw new Error('[PRECONDITION_FAILED] installation or task changed'); });+ await expect(api.commit('original-operation')).rejects.toThrow('PRECONDITION_FAILED');+ expect(harness.fetch).not.toHaveBeenCalled();+ });+ it('reads version pages without losing the existing prepare version filter or subject fence', async () => {+ const result = { subject, queriedAt: page().queriedAt, releases: [], nextCursor: 'more' };+ harness.fetch.mockResolvedValue(result);+ const api = new Api();+ await expect(api.releases('plugin/one', undefined, 'page+2')).resolves.toEqual(result);+ const path = harness.fetch.mock.calls[0][0] as string;+ expect(path).toContain('/plugins/plugin%2Fone/releases?');+ expect(new URL(path, 'https://plugin.test').searchParams.get('cursor')).toBe('page+2');+ expect(new URL(path, 'https://plugin.test').searchParams.get('limit')).toBe('50');+ await api.releases('plugin/one', '1.0.0');+ expect(harness.fetch.mock.calls[1][0]).toContain('version=1.0.0');+ harness.fetch.mockResolvedValueOnce({+ ...result,+ subject: { ...subject, membershipId: 'other' },+ });+ await expect(api.releases('plugin/one')).rejects.toThrow(+ 'Contribution response subject mismatch',+ );+ });+ it('uses the trusted issuer rather than equating the cn realm with authority', async () => {+ await expect(new Api().list(listInput)).resolves.toEqual(page());+ expect(harness.discover.mock.calls[0][0]).toBe(+ 'https://auth.test/.well-known/openid-configuration',+ );+ expect(harness.fetch.mock.calls[0][1]).toMatchObject({+ token: harness.token,+ skipAutoRefresh: true,+ skipSessionInvalidation: true,+ });+ harness.fetch.mockResolvedValueOnce({ ...page(), subject: { ...subject, authority: 'cn' } });+ await expect(new Api().list(listInput)).rejects.toThrow();+ });+ it('rejects a validly shaped response for another member', async () => {+ harness.fetch.mockResolvedValueOnce({+ ...page(),+ subject: { ...subject, membershipId: 'member-B' },+ });+ await expect(new Api().list(listInput)).rejects.toThrow(+ 'Contribution response subject mismatch',+ );+ });+ it('rejects a late response after A to B to A, without refreshing a new account', async () => {+ harness.fetch.mockImplementationOnce(async () => {+ harness.owner = 'A:3';+ return page();+ });+ await expect(new Api().list(listInput)).rejects.toThrow('OWNER_CHANGED');+ expect(harness.refresh).not.toHaveBeenCalled();+ });+ it('rechecks the captured owner after refresh and does not send a retry under another identity', async () => {+ harness.fetch.mockRejectedValueOnce(new ServerApiError('TOKEN_EXPIRED', 401, 'expired'));+ harness.refresh.mockImplementationOnce(async () => {+ harness.owner = 'B:2';+ });+ await expect(new Api().list(listInput)).rejects.toThrow('OWNER_CHANGED');+ expect(harness.fetch).toHaveBeenCalledTimes(1);+ });+});+++it('stops before HTTP when the requesting AI session loses its write permission', async () => {+ const api = new Api(async () => { throw new Error('[PERMISSION_DENIED] session changed'); });+ await expect(api.cancelReview('plugin', { releaseId: 'release', sha256: 'a'.repeat(64), displayUpdatedAt: '2026-10-16T00:00:00.000Z' })).rejects.toThrow('PERMISSION_DENIED');+ expect(harness.fetch).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/main/plugin-contributions/__tests__/host.test.ts b/apps/desktop/src/main/plugin-contributions/__tests__/host.test.tsnew file mode 100644index 0000000000..c3375f485d--- /dev/null+++ b/apps/desktop/src/main/plugin-contributions/__tests__/host.test.ts@@ -0,0 +1,719 @@+import crypto from 'node:crypto';+import fs from 'node:fs';+import fsp from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { InstalledGhost } from '../../../shared/ghost';+import { ghostInstallApprovalToken } from '../../../shared/ghost';+import { createIpcError } from '../../../shared/ipc-errors';+import type {+ ContributionOperation,+ SubmissionView,+} from '../../../shared/pluginContributionContract';+import type { PreparedEntry } from '../prepared';+import { installedGhostStoragePart } from '../../../shared/pluginIdentity';+import { PluginMarketLedger } from '../../plugin-market/ledger';++const harness = vi.hoisted(() => ({+ owner: 'A:1',+ root: '',+ entry: null as PreparedEntry | null,+ ghosts: [] as InstalledGhost[],+ passive: false,+ packaged: false,+ evidence: vi.fn(),+ readAvailable: vi.fn(),+ pluginEndpoint: 'https://plugin.test',+ preflight: vi.fn(),+ verifyContent: vi.fn(),+ readInstallation: vi.fn(),+ snapshot: vi.fn(),+ prepare: vi.fn(),+ operation: vi.fn(),+ commit: vi.fn(),+ list: vi.fn(),+ detail: vi.fn(),+ releases: vi.fn(),+ history: vi.fn(),+ put: vi.fn(),+}));+vi.mock('electron', () => ({ app: { getPath: () => harness.root, get isPackaged() { return harness.packaged; } } }));+vi.mock('../../clientEndpointsService', () => ({ getClientEndpoint: () => harness.pluginEndpoint }));+vi.mock('../../appSessionState', () => ({+ ownerScopedUserDataPath: (...parts: string[]) => path.join(harness.root, ...parts),+}));+vi.mock('../../authManager', () => ({+ onAuthStateChange: vi.fn(),+ isPassiveSharedUserDataInstance: () => harness.passive,+}));+vi.mock('../../serverApiClient', () => ({+ ServerApiError: class extends Error {+ statusCode = 500;+ code = 'INTERNAL';+ },+}));+vi.mock('../../lifecycle', () => ({ onQuit: vi.fn() }));+vi.mock('../../logger', () => ({ createLogger: () => ({ warn: vi.fn() }) }));+vi.mock('../../cindy-brain/index', () => ({+ getGhostManager: () => ({+ list: () => harness.ghosts,+ approvedInstallEvidence: harness.evidence,+ assertContributionReadAvailable: harness.readAvailable,+ }),+}));+vi.mock('../../plugin-publisher/putObject', () => ({+ putLocalFile: (...args: unknown[]) => harness.put(...args),+}));+vi.mock('../prepared', () => ({+ contributionOwnerKey: () => harness.owner,+ contributionAccountKey: () => harness.owner.split(':')[0],+ assertContributionOwner: (owner: string) => {+ if (owner !== harness.owner) throw new Error('[OWNER_CHANGED] changed');+ },+ assertPreparedInstallation: vi.fn(),+ assertPreparedContent: harness.verifyContent,+ readContributionInstallation: harness.readInstallation,+ prepareInstalledContribution: harness.snapshot,+ getPreparedContribution: () => harness.entry!,+ releasePreparedContribution: vi.fn(async () => undefined),+}));+vi.mock('../api', () => ({+ ContributionApi: class {+ readonly owner = harness.owner;+ preflight = harness.preflight;+ prepare = harness.prepare;+ operation = harness.operation;+ commit = harness.commit;+ list = harness.list;+ detail = harness.detail;+ releases = harness.releases;+ history = harness.history;+ },+}));++const at = '2026-10-15T00:00:00.000Z';+const subject = { authority: 'https://issuer.test', membershipId: 'member-A' };+const bytes = Buffer.from('the exact package uploaded before a lost response');+const sha = crypto.createHash('sha256').update(bytes).digest('hex');+const revision = { releaseId: 'release-1', sha256: 'b'.repeat(64), displayUpdatedAt: at };+function submission(): SubmissionView {+ return {+ submissionId: 'submission-1',+ releaseId: 'release-1',+ version: '1.0.0',+ submittedAt: at,+ publishSource: 'community_upload',+ source: 'manual',+ revision,+ revisionState: 'current',+ reviewStatus: 'pending',+ decidedAt: null,+ reason: null,+ };+}+function operation(status: ContributionOperation['status']): ContributionOperation {+ return {+ subject,+ operationId: 'operation-1',+ status,+ createdAt: at,+ updatedAt: at,+ expiresAt: '2099-10-15T00:00:00.000Z',+ failure: null,+ receipt:+ status === 'succeeded'+ ? {+ operationId: 'operation-1',+ submissionId: 'submission-1',+ pluginId: 'canonical-plugin',+ releaseId: 'release-1',+ ghostId: 'hello',+ version: '1.0.0',+ source: 'manual',+ submittedAt: at,+ uploadedPackage: { sha256: sha, sizeBytes: bytes.length },+ releaseRevision: revision,+ outcome: 'metadata_updated',+ }+ : null,+ submission: status === 'succeeded' ? submission() : null,+ };+}+function uploadResponse() {+ return {+ ...operation('awaiting_upload'),+ upload: {+ putUrl: 'https://storage.test/upload',+ headers: {},+ expiresAt: '2099-10-15T00:00:00.000Z',+ },+ };+}+function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<T>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ return { promise, resolve, reject };+}+function ownPlugin() {+ return { pluginId: 'canonical-plugin', ghostId: 'hello', namespace: null, name: 'Hello', icon: null,+ updatedAt: at, market: { available: false, unavailableReason: 'not_listed', currentRelease: null },+ latestSubmission: null, actions: { canSubmit: true, canViewMarket: false } };+}+function ownDetail() {+ return { plugin: ownPlugin(), latestSubmissionContent: null, queriedAt: at,+ history: { events: [], nextCursor: null } };+}+import * as host from '../host';+let testGeneration = 0;+beforeEach(async () => {+ vi.resetAllMocks();+ testGeneration++;+ harness.owner = `A:${testGeneration}:1`;+ harness.passive = false;+ harness.packaged = false;+ harness.pluginEndpoint = 'https://plugin.test';+ harness.evidence.mockReturnValue(null);+ harness.root = await fsp.mkdtemp(path.join(os.tmpdir(), 'cindy-contribution-test-'));+ const directory = await fsp.mkdtemp(path.join(harness.root, 'cindy-contribution-'));+ await fsp.writeFile(path.join(directory, 'plugin.cindy'), bytes);+ const ghost: InstalledGhost = {+ manifest: {+ schemaVersion: 2,+ id: 'hello',+ name: 'Hello',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ },+ dir: path.join(harness.root, 'installed'),+ enabled: true,+ namespace: null,+ publishingSource: { kind: 'local', source: 'manual' },+ namespaceState: 'confirmed',+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },+ };+ harness.ghosts = [ghost];+ harness.readInstallation.mockImplementation((instanceId: string, expected?: { directory: string; approvalToken: string }) => {+ const installed = harness.ghosts.find(item => installedGhostStoragePart(item) === instanceId);+ if (!installed) throw createIpcError('NOT_FOUND', 'Installed plugin not found');+ if (expected && (installed.dir !== expected.directory ||+ ghostInstallApprovalToken(installed.approval) !== expected.approvalToken))+ throw createIpcError('PRECONDITION_FAILED', 'Installed plugin changed');+ return { ghost: installed, source: installed.publishingSource };+ });+ harness.entry = {+ owner: harness.owner,+ directory,+ filePath: path.join(directory, 'plugin.cindy'),+ approvalToken: ghostInstallApprovalToken(ghost.approval),+ installationDir: ghost.dir,+ publishingSourceKey: JSON.stringify(ghost.publishingSource),+ pinned: false,+ contentSha256: sha,+ idempotencyKey: '00000000-0000-4000-8000-000000000002',+ expiresAt: Date.now() + 60_000,+ summary: {+ preparedId: 'prepared-1',+ instanceId: 'hello',+ pluginId: null,+ ghostId: 'hello',+ name: 'Hello',+ description: '',+ releaseNotes: 'Initial local test functionality',+ version: '1.0.0',+ sha256: sha,+ sizeBytes: bytes.length,+ expiresAt: '2099-10-15T00:00:00.000Z',+ },+ };+ harness.snapshot.mockImplementation(async () => harness.entry!.summary);+ harness.detail.mockResolvedValue(ownDetail());+ harness.preflight.mockResolvedValue({ subject, queriedAt: at, policyVersion: 2, target: { pluginId: null, ghostId: 'hello', version: '1.0.0', expectedRelease: null }, pendingRelease: null, blockers: [], actions: { canSubmit: true } });+ harness.list.mockResolvedValue({ plugins: [], nextCursor: null });+ harness.prepare.mockResolvedValue(uploadResponse());+ harness.commit.mockResolvedValue({ subject, operationId: 'operation-1', status: 'validating' });+ harness.operation.mockResolvedValue(operation('succeeded'));+ harness.put.mockImplementation(async (handle: fsp.FileHandle) => {+ const result = Buffer.alloc(bytes.length);+ await handle.read(result, 0, result.length, 0);+ expect(result).toEqual(bytes);+ });+});+afterEach(async () => {+ await fsp.rm(harness.root, { recursive: true, force: true });+});++describe('community contribution recovery', () => {+ it('rejects an official market target despite a current submission grant, before reading bytes', async () => {+ harness.ghosts[0].publishingSource = { kind: 'public-market', pluginId: 'canonical-plugin' };+ harness.detail.mockResolvedValue({ ...ownDetail(), plugin: { ...ownPlugin(), publisherKind: 'official' } });+ await expect(host.prepareContribution('hello', 'manual')).rejects.toThrow('OFFICIAL_PLUGIN_GITHUB_REQUIRED');+ expect(harness.snapshot).not.toHaveBeenCalled();+ expect(harness.preflight).not.toHaveBeenCalled();+ expect(harness.prepare).not.toHaveBeenCalled();+ });+ it('rejects a local copy resolved to an official target by preflight', async () => {+ harness.preflight.mockResolvedValueOnce({ ...(await harness.preflight()), target: {+ pluginId: 'canonical-plugin', ghostId: 'hello', version: '1.0.0', expectedRelease: null } });+ harness.detail.mockResolvedValue({ ...ownDetail(), plugin: { ...ownPlugin(), publisherKind: 'official' } });+ await expect(host.prepareContribution('hello', 'ai')).rejects.toThrow('OFFICIAL_PLUGIN_GITHUB_REQUIRED');+ expect(harness.prepare).not.toHaveBeenCalled();+ expect(harness.put).not.toHaveBeenCalled();+ });+ it('refuses further writes when an existing target is now official, while still reading its result', async () => {+ harness.preflight.mockResolvedValueOnce({ ...(await harness.preflight()), target: {+ pluginId: 'canonical-plugin', ghostId: 'hello', version: '1.0.0', expectedRelease: null } });+ harness.commit.mockRejectedValueOnce(new Error('commit response lost'));+ await host.prepareContribution('hello', 'manual');+ await host.submitContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('paused'));+ harness.operation.mockResolvedValueOnce(operation('publishing'));+ harness.detail.mockResolvedValue({ ...ownDetail(), plugin: { ...ownPlugin(), publisherKind: 'official' } });+ host.resumeContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].errorCode).toBe('OFFICIAL_PLUGIN_GITHUB_REQUIRED'));+ expect(harness.operation).toHaveBeenCalledWith('operation-1');+ expect(harness.prepare).toHaveBeenCalledTimes(1);+ expect(harness.put).toHaveBeenCalledTimes(1);+ expect(harness.commit).toHaveBeenCalledTimes(1);+ });+ it('keeps third-party public targets with a current grant available for preparation', async () => {+ harness.ghosts[0].publishingSource = { kind: 'public-market', pluginId: 'canonical-plugin' };+ harness.preflight.mockResolvedValueOnce({ ...(await harness.preflight()), target: {+ pluginId: 'canonical-plugin', ghostId: 'hello', version: '1.0.0', expectedRelease: null } });+ harness.detail.mockResolvedValue({ ...ownDetail(), plugin: { ...ownPlugin(), publisherKind: 'personal' } });+ expect(await host.prepareContribution('hello', 'manual')).toMatchObject({ preflight: { actions: { canSubmit: true } } });+ expect(harness.snapshot).toHaveBeenCalled();+ expect(harness.prepare).not.toHaveBeenCalled();+ });+ it('queries the old operation but refuses a new commit after publishing ACL is revoked', async () => {+ harness.preflight.mockResolvedValueOnce({ ...(await harness.preflight()), target: {+ pluginId: 'canonical-plugin', ghostId: 'hello', version: '1.0.0', expectedRelease: null } });+ harness.commit.mockRejectedValueOnce(new Error('commit response lost'));+ await host.prepareContribution('hello', 'manual');+ await host.submitContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('paused'));+ harness.operation.mockResolvedValueOnce(operation('publishing'));+ harness.detail.mockResolvedValue({ plugin: { pluginId: 'canonical-plugin', actions: { canSubmit: false } } });+ host.resumeContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].errorCode).toBe('PERMISSION_DENIED'));+ expect(harness.commit).toHaveBeenCalledTimes(1);+ expect(harness.prepare).toHaveBeenCalledTimes(1);+ expect(harness.put).toHaveBeenCalledTimes(1);+ });+ // Regression: a mid-stream source change previously threw through Transform.+ // Tier: unit; exercise public submit and its real callback contract, without+ // duplicating uploader internals or sending any network request.+ it('aborts a changed installation from the byte callback without throwing or committing', async () => {+ let callbackReturned = false;+ let uploadAborted = false;+ harness.put.mockImplementation(async (_handle, options) => {+ harness.readInstallation.mockImplementation(() => {+ throw createIpcError('PRECONDITION_FAILED', 'source replaced during upload');+ });+ options.onBytes(1);+ callbackReturned = true;+ uploadAborted = options.signal.aborted;+ throw createIpcError('MUTATION_CANCELLED', 'upload aborted');+ });+ await host.prepareContribution('hello', 'manual');+ await host.submitContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('paused'));+ expect(callbackReturned).toBe(true);+ expect(uploadAborted).toBe(true);+ expect(harness.commit).not.toHaveBeenCalled();+ });+ it('rechecks the AI caller and installation before resuming past the upload phase', async () => {+ harness.commit.mockRejectedValueOnce(new Error('commit response lost'));+ await host.prepareContribution('hello', 'ai');+ await host.submitContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('paused'));+ harness.operation.mockResolvedValueOnce(operation('validating'));+ const caller = vi.fn(async () => { throw createIpcError('PERMISSION_DENIED', 'restricted task'); });+ host.resumeContribution('prepared-1', caller);+ await vi.waitFor(() => expect(caller).toHaveBeenCalledOnce());+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('paused'));+ expect(harness.commit).toHaveBeenCalledTimes(1);+ harness.readInstallation.mockImplementation(() => { throw createIpcError('PRECONDITION_FAILED', 'source replaced'); });+ harness.operation.mockResolvedValueOnce(operation('validating'));+ host.resumeContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].errorCode).toBe('PRECONDITION_FAILED'));+ expect(harness.commit).toHaveBeenCalledTimes(1);+ });+ it('does not read downloaded package bytes when detail visibility lacks publishing ACL', async () => {+ harness.ghosts[0].publishingSource = { kind: 'public-market', pluginId: 'canonical-plugin' };+ harness.detail.mockResolvedValue({ plugin: { pluginId: 'canonical-plugin', actions: { canSubmit: false } } });+ await expect(host.prepareContribution('hello', 'ai')).rejects.toThrow('Publishing permission required');+ expect(harness.snapshot).not.toHaveBeenCalled();+ expect(harness.prepare).not.toHaveBeenCalled();+ });+ it.each(['127.0.0.1', 'localhost', '[::1]'])('allows the configured %s dev-local adapter on its exact origin', async (hostname) => {+ harness.pluginEndpoint = `http://${hostname}:43340`;+ const response = uploadResponse();+ response.upload.putUrl = `${harness.pluginEndpoint}/dev-local/member-upload?key=test&storageId=memory`;+ harness.prepare.mockResolvedValueOnce(response);+ await host.prepareContribution('hello', 'manual');+ await host.submitContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('complete'));+ expect(harness.put).toHaveBeenCalledExactlyOnceWith(expect.anything(), expect.objectContaining({ putUrl: response.upload.putUrl }));+ });++ it.each([+ { label: 'remote HTTP endpoint', endpoint: 'http://plugin.example.test:43340', url: 'http://plugin.example.test:43340/dev-local/member-upload' },+ { label: 'HTTPS configuration', endpoint: 'https://plugin.test', url: 'http://127.0.0.1:43340/dev-local/member-upload' },+ { label: 'another local port', endpoint: 'http://127.0.0.1:43340', url: 'http://127.0.0.1:43341/dev-local/member-upload' },+ { label: 'another local path', endpoint: 'http://127.0.0.1:43340', url: 'http://127.0.0.1:43340/other-upload' },+ { label: 'userinfo', endpoint: 'http://127.0.0.1:43340', url: 'http://user:[email protected]:43340/dev-local/member-upload' },+ { label: 'packaged application', endpoint: 'http://127.0.0.1:43340', url: 'http://127.0.0.1:43340/dev-local/member-upload', packaged: true },+ { label: 'a loopback-looking DNS name', endpoint: 'http://127.evil.test:43340', url: 'http://127.evil.test:43340/dev-local/member-upload' },+ ])('refuses $label before sending any package bytes', async ({ endpoint, url, packaged }) => {+ harness.pluginEndpoint = endpoint;+ harness.packaged = packaged ?? false;+ const response = uploadResponse();+ response.upload.putUrl = url;+ harness.prepare.mockResolvedValueOnce(response);+ await host.prepareContribution('hello', 'manual');+ await host.submitContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0]).toMatchObject({ stage: 'paused', errorCode: 'PRECONDITION_FAILED' }));+ expect(harness.put).not.toHaveBeenCalled();+ expect(harness.commit).not.toHaveBeenCalled();+ });++ it.each(['Authorization', 'Proxy-Authorization', 'Cookie'])('refuses the sensitive %s header even on the exact dev-local origin', async (header) => {+ harness.pluginEndpoint = 'http://127.0.0.1:43340';+ const response = uploadResponse();+ response.upload.putUrl = `${harness.pluginEndpoint}/dev-local/member-upload`;+ response.upload.headers = { [header]: 'not-a-real-credential' };+ harness.prepare.mockResolvedValueOnce(response);+ await host.prepareContribution('hello', 'manual');+ await host.submitContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0]).toMatchObject({ stage: 'paused', errorCode: 'PRECONDITION_FAILED' }));+ expect(harness.put).not.toHaveBeenCalled();+ });++ it('replays the same prepare body and key after a lost response, uploading the pinned bytes', async () => {+ harness.prepare.mockRejectedValueOnce(new Error('response lost after server acceptance'));+ const prepared = await host.prepareContribution('hello', 'manual');+ await host.submitContribution(prepared.preparedId);+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('paused'));+ const first = structuredClone(harness.prepare.mock.calls[0]);+ host.resumeContribution(prepared.preparedId);+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('complete'));+ expect(harness.prepare.mock.calls[1]).toEqual(first);+ expect(harness.put).toHaveBeenCalledTimes(1);+ const result = host.listContributionTransfers()[0];+ // A metadata update keeps the existing Release package; upload SHA is separate.+ expect(result.operation?.receipt?.releaseRevision.sha256).toBe('b'.repeat(64));+ expect(result.operation?.receipt?.uploadedPackage.sha256).toBe(sha);+ });++ it('queries an unknown commit result before retrying and never starts a second upload', async () => {+ harness.commit.mockRejectedValueOnce(new Error('commit response lost'));+ await host.prepareContribution('hello', 'manual');+ await host.submitContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('paused'));+ host.resumeContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('complete'));+ expect(harness.operation).toHaveBeenCalledWith('operation-1');+ expect(harness.commit).toHaveBeenCalledTimes(1);+ expect(harness.prepare).toHaveBeenCalledTimes(1);+ expect(harness.put).toHaveBeenCalledTimes(1);+ });++ it.each(['validating', 'publishing'] as const)(+ 'reclaims a released %s operation by replaying commit after the initial GET',+ async (status) => {+ harness.commit.mockRejectedValueOnce(+ new Error('server lease released after a temporary failure'),+ );+ await host.prepareContribution('hello', 'manual');+ await host.submitContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('paused'));+ const calls: string[] = [];+ harness.operation.mockImplementationOnce(async () => {+ calls.push('get');+ return operation(status);+ });+ harness.commit.mockImplementationOnce(async (id) => {+ calls.push(`commit:${id}`);+ return { subject, operationId: id, status };+ });+ host.resumeContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('complete'));+ expect(calls).toEqual(['get', 'commit:operation-1']);+ expect(harness.commit).toHaveBeenCalledTimes(2);+ expect(harness.prepare).toHaveBeenCalledTimes(1);+ expect(harness.put).toHaveBeenCalledTimes(1);+ },+ );++ it('does not write an old generation catch over the restored account journal', async () => {+ const old = deferred<ReturnType<typeof uploadResponse>>();+ harness.prepare.mockImplementationOnce(() => old.promise);+ await host.prepareContribution('hello', 'manual');+ await host.submitContribution('prepared-1');+ await vi.waitFor(() => expect(harness.prepare).toHaveBeenCalledTimes(1));+ harness.owner = `B:${testGeneration}:2`;+ expect(host.listContributionTransfers()).toEqual([]);+ harness.owner = `A:${testGeneration}:3`;+ expect(host.listContributionTransfers()[0].stage).toBe('paused');+ host.resumeContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('complete'));+ const file = path.join(+ harness.root,+ 'plugin-contributions',+ `${crypto.createHash('sha256').update('A').digest('hex').slice(0, 20)}.v1.json`,+ );+ const completed = fs.readFileSync(file, 'utf8');+ old.reject(new Error('late timeout from A:1'));+ await old.promise.catch(() => undefined);+ await Promise.resolve();+ await Promise.resolve();+ expect(fs.readFileSync(file, 'utf8')).toBe(completed);+ expect(host.listContributionTransfers()[0].stage).toBe('complete');+ });++ it('keeps 202 as processing without inventing a pending submission', async () => {+ const query = deferred<ContributionOperation>();+ harness.operation.mockImplementationOnce(() => query.promise);+ await host.prepareContribution('hello', 'manual');+ await host.submitContribution('prepared-1');+ await vi.waitFor(() => expect(harness.operation).toHaveBeenCalledTimes(1));+ const result = host.listContributionTransfers()[0];+ expect(result.stage).toBe('processing');+ expect(result.operation?.receipt).toBeNull();+ expect(result.operation?.submission).toBeNull();+ expect(harness.ghosts[0].publishingSource).toEqual({ kind: 'local', source: 'manual' });+ query.resolve(operation('succeeded'));+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('complete'));+ expect(host.listContributionTransfers()[0].stage).toBe('complete');+ });++ it('refuses out-of-bounds cleanup paths loaded from a recovery journal', async () => {+ harness.prepare.mockRejectedValueOnce(new Error('offline'));+ await host.prepareContribution('hello', 'manual');+ await host.submitContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('paused'));+ const file = path.join(+ harness.root,+ 'plugin-contributions',+ `${crypto.createHash('sha256').update('A').digest('hex').slice(0, 20)}.v1.json`,+ );+ const outside = path.join(harness.root, 'keep-user-data');+ await fsp.mkdir(outside);+ await fsp.writeFile(path.join(outside, 'keep.txt'), 'keep');+ const records = JSON.parse(fs.readFileSync(file, 'utf8'));+ records[0].directory = outside;+ records[0].operationId = 'operation-1';+ fs.writeFileSync(file, JSON.stringify(records));+ harness.owner = `A:${testGeneration}:2`; // Reload from disk under a fresh owner generation.+ await expect(host.contributionTransferStatus('prepared-1')).rejects.toThrow(+ 'Invalid contribution snapshot location',+ );+ expect(fs.readFileSync(path.join(outside, 'keep.txt'), 'utf8')).toBe('keep');+ expect(host.listContributionTransfers()[0].stage).toBe('paused');+ });+});+++describe('admission summary and transfer ownership', () => {+ it('reuses the unfinished submission from a new preview of the same package content', async () => {+ const gate = deferred<ReturnType<typeof uploadResponse>>();+ harness.prepare.mockRejectedValueOnce(new Error('network interrupted'));+ await host.prepareContribution('hello', 'manual');+ await host.submitContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('paused'));+ harness.prepare.mockReturnValueOnce(gate.promise);+ harness.entry = { ...harness.entry!, pinned: false,+ summary: { ...harness.entry!.summary, preparedId: 'prepared-2', sha256: 'c'.repeat(64) },+ idempotencyKey: '00000000-0000-4000-8000-000000000003' };+ await host.prepareContribution('hello', 'manual');+ const result = await host.submitContribution('prepared-2');+ expect(result.localId).toBe('prepared-1');+ expect(result.stage).toBe('prepared');+ expect(result.errorCode).toBeNull();+ expect(host.listContributionTransfers()).toHaveLength(1);+ await vi.waitFor(() => expect(harness.prepare).toHaveBeenCalledTimes(2));+ gate.resolve(uploadResponse());+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('complete'));+ expect(harness.put).toHaveBeenCalledTimes(1);+ expect(harness.commit).toHaveBeenCalledTimes(1);+ });+ it('never starts an operation when the displayed package has changed', async () => {+ await host.prepareContribution('hello', 'manual');+ harness.verifyContent.mockRejectedValueOnce(new Error('[CONTRIBUTION_PACKAGE_CHANGED] changed'));+ await expect(host.submitContribution('prepared-1')).rejects.toThrow('CONTRIBUTION_PACKAGE_CHANGED');+ expect(harness.prepare).not.toHaveBeenCalled();+ expect(harness.put).not.toHaveBeenCalled();+ });+ it('keeps admitted transfer bytes when a detail cleanup discards its preview', async () => {+ const gate = deferred<ReturnType<typeof uploadResponse>>();+ harness.prepare.mockReturnValueOnce(gate.promise);+ await host.prepareContribution('hello', 'manual');+ await host.submitContribution('prepared-1');+ await host.discardContribution('prepared-1');+ expect(await fsp.readFile(harness.entry!.filePath)).toEqual(bytes);+ gate.resolve(uploadResponse());+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('complete'));+ });+ it('keeps a first submission without release notes eligible when the server allows it', async () => {+ delete harness.entry!.summary.releaseNotes;+ const prepared = await host.prepareContribution('hello', 'manual');+ expect(harness.preflight).toHaveBeenCalledWith({ pluginId: null, ghostId: 'hello', version: '1.0.0', hasReleaseNotes: false });+ expect(prepared.preflight?.actions.canSubmit).toBe(true);+ expect(prepared.preflight?.blockers).toEqual([]);+ expect(harness.prepare).not.toHaveBeenCalled();+ });+ it('blocks an unavailable preflight without remote mutation', async () => {+ harness.preflight.mockResolvedValueOnce({ subject, queriedAt: at, policyVersion: 2, target: { pluginId: null, ghostId: 'hello', version: '1.0.0', expectedRelease: null }, pendingRelease: { releaseId: 'pending', version: '0.9.0' }, blockers: [{ code: 'PLUGIN_PENDING_RELEASE_EXISTS', message: 'Review already pending' }], actions: { canSubmit: false } });+ await host.prepareContribution('hello', 'manual');+ await expect(host.submitContribution('prepared-1')).rejects.toThrow('PLUGIN_PENDING_RELEASE_EXISTS');+ expect(harness.prepare).not.toHaveBeenCalled();+ });+});++describe('review result reading state', () => {+ function approved() { return { ...submission(), reviewStatus: 'approved' as const, decidedAt: at }; }+ function plugin(latestSubmission: SubmissionView = approved()) {+ return { pluginId: 'plugin-1', updatedAt: at, latestSubmission };+ }+ it('keeps an older proven approval discoverable beneath a newer pending version and caches its history', async () => {+ harness.list.mockResolvedValue({ plugins: [plugin({ ...submission(), reviewStatus: 'pending', decidedAt: null })], nextCursor: null });+ harness.detail.mockResolvedValue({ history: { events: [], nextCursor: 'older' } });+ harness.history.mockResolvedValue({ events: [{ type: 'approved', at, revision, version: '1.0.0' }], nextCursor: null });+ const service = await import('../reviewUpdates');+ const result = await service.reviewUpdates();+ expect(result).toEqual([expect.objectContaining({ pluginId: 'plugin-1', status: 'approved', unread: true, decidedAt: at })]);+ expect(harness.history).toHaveBeenCalledWith('plugin-1', 'older');+ await service.reviewUpdates();+ expect(harness.detail).toHaveBeenCalledTimes(1);+ });+ it('persists the exact decision per account across a new login generation and never acknowledges a later decision', async () => {+ harness.list.mockResolvedValue({ plugins: [plugin()], nextCursor: null });+ let service = await import('../reviewUpdates');+ const [first] = await service.reviewUpdates();+ service.markReviewRead('plugin-1', first.key);+ expect((await service.reviewUpdates())[0].unread).toBe(false);+ // reset-modules: Simulate process restart to prove markers survive an empty in-memory review cache.+ vi.resetModules();+ harness.owner = `A:${testGeneration}:2`;+ service = await import('../reviewUpdates');+ expect((await service.reviewUpdates())[0].unread).toBe(false);+ harness.list.mockResolvedValue({ plugins: [plugin({ ...approved(), decidedAt: '2026-10-16T00:00:00.000Z' })], nextCursor: null });+ expect((await service.reviewUpdates())[0].unread).toBe(true);+ expect(() => service.markReviewRead('plugin-1', first.key)).toThrow('PRECONDITION_FAILED');+ harness.owner = `B:${testGeneration}:1`;+ expect((await service.reviewUpdates())[0].unread).toBe(true);+ harness.passive = true;+ expect(() => service.markReviewRead('plugin-1', first.key)).toThrow('PRECONDITION_FAILED');+ });+ it('reads every plugin page, ignores unproven legacy decisions, and rejects late responses from a previous account', async () => {+ harness.list.mockResolvedValueOnce({ plugins: [], nextCursor: 'page-2' })+ .mockResolvedValueOnce({ plugins: [plugin({ ...approved(), decidedAt: null })], nextCursor: null });+ harness.detail.mockResolvedValue({ history: { events: [{ type: 'approved', at, revision: null, version: '1.0.0' }], nextCursor: null } });+ const service = await import('../reviewUpdates');+ expect(await service.reviewUpdates()).toEqual([]);+ expect(harness.list).toHaveBeenLastCalledWith({ query: '', filter: 'all', cursor: 'page-2' });+ let finish!: (value: unknown) => void;+ harness.list.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ const late = service.reviewUpdates();+ harness.owner = `B:${testGeneration}:1`;+ finish({ plugins: [plugin()], nextCursor: null });+ await expect(late).rejects.toThrow('OWNER_CHANGED');+ harness.list.mockRejectedValueOnce(new Error('offline'));+ await expect(service.reviewUpdates()).rejects.toThrow('offline');+ });+});+++// 测试价值:列表/详情直接读取现有身份与来源,不增加发布关联或安装写入。+// 依据:namespace + id 是已安装插件身份;提审/上架不能改变安装来源。+// 缺口:原用例依赖已撤除的关联记录,无法覆盖无回执和正常本地迭代。+// 最小输入:本人 API 的一个目标和一个同 ID 安装;tier: unit。+describe('author installation projection', () => {+ async function localView() {+ harness.list.mockResolvedValue({ plugins: [ownPlugin()], nextCursor: null, queriedAt: at });+ return (await host.listMyPlugins({ query: '', filter: 'all' })).plugins[0];+ }+ it('keeps official plugin facts readable while projecting client submission as unavailable', async () => {+ harness.list.mockResolvedValue({ plugins: [{ ...ownPlugin(), publisherKind: 'official' }], nextCursor: null, queriedAt: at });+ const result = (await host.listMyPlugins({ query: '', filter: 'all' })).plugins[0];+ expect(result).toMatchObject({ publisherKind: 'official', actions: { submitUpdate: false },+ localInstallation: { state: 'installed', version: '1.0.0', origin: 'local' } });+ expect(harness.prepare).not.toHaveBeenCalled();+ expect(harness.snapshot).not.toHaveBeenCalled();+ });+ it('shows the installed local version without a submission or a separate association', async () => {+ expect(await localView()).toMatchObject({ localInstallation: {+ state: 'installed', instanceId: 'hello', origin: 'local', version: '1.0.0', enabled: true,+ }, localInstanceId: 'hello' });+ expect((await host.myPluginDetail('canonical-plugin')).plugin.localVersion).toBe('1.0.0');+ harness.ghosts[0] = { ...harness.ghosts[0], enabled: false,+ manifest: { ...harness.ghosts[0].manifest, name: 'Renamed plugin', version: '1.2.0' },+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000099' } };+ expect(await localView()).toMatchObject({ localInstallation: {+ state: 'installed', version: '1.2.0', enabled: false, origin: 'local',+ } });+ expect(harness.snapshot).not.toHaveBeenCalled();+ expect(harness.prepare).not.toHaveBeenCalled();+ expect(host.listContributionTransfers()).toEqual([]);+ });+ it('does not match another ID or organization namespace, even with the same display name', async () => {+ const original = harness.ghosts[0];+ harness.ghosts = [{ ...original, manifest: { ...original.manifest, id: 'different' } }];+ expect((await localView()).localInstallation).toEqual({ state: 'missing' });+ harness.ghosts = [{ ...original, namespace: 'org' }];+ expect((await localView()).localInstallation).toEqual({ state: 'missing' });+ });+ it('reports unavailable instead of missing when the installation cannot be read', async () => {+ harness.ghosts = [];+ harness.readAvailable.mockImplementation(() => { throw new Error('unreadable registry'); });+ expect(await localView()).toMatchObject({ localInstallation: { state: 'unavailable' }, localInstanceId: null });+ expect(harness.readAvailable).toHaveBeenCalledWith('hello');+ });+ it('does not change the local source after a submission succeeds', async () => {+ await host.prepareContribution('hello', 'manual');+ await host.submitContribution('prepared-1');+ await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('complete'));+ expect(host.listContributionTransfers()[0].operation?.status).toBe('succeeded');+ expect((await localView()).localInstallation).toMatchObject({ state: 'installed', origin: 'local' });+ expect(harness.ghosts).toHaveLength(1);+ });+ it('never substitutes a private, custom, or unverified installation for this public target', async () => {+ harness.ghosts[0].publishingSource = { kind: 'unavailable' };+ expect(await localView()).toMatchObject({ localInstallation: { state: 'unavailable' }, localInstanceId: null });+ });+ it('matches public installations using their existing source ledger and approved package', async () => {+ harness.ghosts[0].publishingSource = { kind: 'public-market', pluginId: 'canonical-plugin' };+ const ledger = new PluginMarketLedger(path.join(harness.root, 'plugin-market', 'ledger.v1.json'));+ const record = { pluginId: 'canonical-plugin', ghostId: 'hello', namespace: null,+ releaseId: 'release-1', version: '1.0.0', sha256: sha, scope: 'public' as const, organizationId: null,+ source: 'market' as const, installed: true, updatedAt: at };+ ledger.upsertInstallation(record);+ harness.evidence.mockReturnValue({ packageSha256: sha });+ expect(await localView()).toMatchObject({ localInstallation: {+ state: 'installed', instanceId: 'hello', version: '1.0.0', origin: 'public',+ } });+ harness.ghosts[0].publishingSource = { kind: 'public-market', pluginId: 'different-plugin' };+ expect((await localView()).localInstallation).toEqual({ state: 'unavailable' });+ harness.ghosts[0].publishingSource = { kind: 'public-market', pluginId: 'canonical-plugin' };+ ledger.upsertInstallation({ ...record, pluginId: 'different-plugin' });+ expect((await localView()).localInstanceId).toBeNull();+ expect(harness.snapshot).not.toHaveBeenCalled();+ });+ it('resolves a local update through server preflight and checks the returned publishing permission', async () => {+ harness.preflight.mockResolvedValue({ ...(await harness.preflight()), target: {+ pluginId: 'canonical-plugin', ghostId: 'hello', version: '1.0.0', expectedRelease: null } });+ await host.prepareContribution('hello', 'manual');+ expect(harness.preflight).toHaveBeenCalledWith({ pluginId: null, ghostId: 'hello', version: '1.0.0', hasReleaseNotes: true });+ expect(harness.detail).toHaveBeenCalledWith('canonical-plugin');+ harness.detail.mockResolvedValue({ ...ownDetail(), plugin: {+ ...ownPlugin(), actions: { canSubmit: false, canViewMarket: false },+ } });+ await expect(host.prepareContribution('hello', 'manual')).rejects.toThrow('PERMISSION_DENIED');+ });+});diff --git a/apps/desktop/src/main/plugin-contributions/__tests__/prepared.test.ts b/apps/desktop/src/main/plugin-contributions/__tests__/prepared.test.tsnew file mode 100644index 0000000000..1cef6e3a18--- /dev/null+++ b/apps/desktop/src/main/plugin-contributions/__tests__/prepared.test.ts@@ -0,0 +1,165 @@+import crypto from 'node:crypto';+import fsp from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { InstalledGhost } from '../../../shared/ghost';+import { ghostInstallApprovalToken } from '../../../shared/ghost';++const harness = vi.hoisted(() => ({+ root: '',+ generation: 1,+ ghosts: [] as InstalledGhost[],+ ledger: null as { scope: string; organizationId: string | null; source?: string; installed?: boolean } | null,+ snapshot: vi.fn(),+ inspect: vi.fn(),+}));+vi.mock('electron', () => ({ app: { getPath: () => harness.root } }));+vi.mock('../../appSessionState', () => ({+ activeOwnerScopeKey: () => `owner:${harness.generation}`,+ getActiveAppSession: () => ({ mode: 'cloud', dataOwnerId: 'owner' }),+ isAppSessionBoundaryPending: () => false,+ ownerScopedUserDataPath: (...parts: string[]) => path.join(harness.root, ...parts),+}));+vi.mock('../../authManager', () => ({+ getAuthState: () => ({+ isAuthenticated: true,+ user: { id: 'member', membershipKind: 'personal' },+ }),+ getActiveAuthRealm: () => 'global',+}));+vi.mock('../../cindy-brain/index', () => ({+ getGhostManager: () => ({ list: () => harness.ghosts, inspect: harness.inspect }),+}));+vi.mock('../../cindy-brain/exportGhostPackage', () => ({+ snapshotInstalledGhostPackage: harness.snapshot,+}));+vi.mock('../../plugin-market/ledger', () => ({+ PluginMarketLedger: class {+ installationForAuthorization() {+ return harness.ledger;+ }+ },+}));+const bytes = Buffer.from('fixed-package-bytes');+import * as prepared from '../prepared';+let testGeneration = 0;+beforeEach(async () => {+ vi.resetAllMocks();+ harness.generation = ++testGeneration * 1000;+ harness.ledger = null;+ harness.root = await fsp.mkdtemp(path.join(os.tmpdir(), 'cindy-contribution-prepare-test-'));+ harness.ghosts = [+ {+ manifest: {+ schemaVersion: 2,+ id: 'hello',+ name: 'Hello',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ },+ namespace: null,+ publishingSource: { kind: 'local', source: 'manual' },+ namespaceState: 'confirmed',+ enabled: true,+ dir: path.join(harness.root, 'current'),+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },+ },+ ];+ harness.snapshot.mockResolvedValue({ status: 'prepared', bytes, contentSha256: 'fixed-content' });+ harness.inspect.mockResolvedValue({+ canonicalManifest: harness.ghosts[0].manifest,+ packageSha256: crypto.createHash('sha256').update(bytes).digest('hex'),+ });+});+afterEach(async () => {+ await fsp.rm(harness.root, { recursive: true, force: true });+});+describe('current installation contribution preparation', () => {+ it.each(['manual', 'ai'] as const)('rejects trusted official public plugins before packaging (%s)', async source => {+ harness.ghosts[0].publishingSource = { kind: 'public-market', pluginId: 'official-plugin' };+ harness.ghosts[0].trust = { level: 'cindy-official', publisherSigned: true, publisherVerified: true, reviewed: true };+ harness.ledger = { scope: 'public', organizationId: null, source: 'market', installed: true };+ await expect(prepared.prepareInstalledContribution('hello', source)).rejects.toThrow('OFFICIAL_PLUGIN_GITHUB_REQUIRED');+ expect(harness.snapshot).not.toHaveBeenCalled();+ expect(harness.inspect).not.toHaveBeenCalled();+ });+ it('does not infer official identity from a package author or display name', async () => {+ harness.ghosts[0].manifest.name = 'Cindy community tool';+ harness.ghosts[0].manifest.author = 'Cindy';+ expect(await prepared.prepareInstalledContribution('hello')).toMatchObject({ ghostId: 'hello' });+ expect(harness.snapshot).toHaveBeenCalled();+ });+ it.each(['git-market', 'local-market'])('rejects %s before reading package bytes', async source => {+ harness.ledger = { scope: 'public', organizationId: null, source, installed: true };+ await expect(prepared.prepareInstalledContribution('hello')).rejects.toThrow('Custom market installation');+ expect(harness.snapshot).not.toHaveBeenCalled();+ });+ it('refuses an unknown source rather than falling back to first publication', async () => {+ delete harness.ghosts[0].publishingSource;+ await expect(prepared.prepareInstalledContribution('hello')).rejects.toThrow('source could not be verified');+ expect(harness.snapshot).not.toHaveBeenCalled();+ });+ it('rejects a same-ID installation that differs from the clicked instance evidence before reading bytes', async () => {+ await expect(+ prepared.prepareInstalledContribution('hello', 'manual', {+ directory: path.join(harness.root, 'previous-account'),+ approvalToken: ghostInstallApprovalToken(harness.ghosts[0].approval),+ }),+ ).rejects.toThrow('Original installed plugin no longer matches');+ expect(harness.snapshot).not.toHaveBeenCalled();+ expect(harness.inspect).not.toHaveBeenCalled();+ });+ it('refuses private ledger resources before creating a public snapshot', async () => {+ harness.ledger = { scope: 'personal', organizationId: null };+ await expect(prepared.prepareInstalledContribution('hello')).rejects.toThrow(+ 'Private plugin resources',+ );+ expect(harness.snapshot).not.toHaveBeenCalled();+ });+ it('discards preparation if the account generation changes during inspect', async () => {+ harness.inspect.mockImplementationOnce(async () => {+ harness.generation++;+ return {+ canonicalManifest: harness.ghosts[0].manifest,+ packageSha256: crypto.createHash('sha256').update(bytes).digest('hex'),+ };+ });+ await expect(prepared.prepareInstalledContribution('hello')).rejects.toThrow('OWNER_CHANGED');+ expect(await fsp.readdir(harness.root)).toEqual([]);+ });+ it('pins the inspected bytes and refuses later approval changes before submission', async () => {+ const result = await prepared.prepareInstalledContribution('hello');+ const entry = prepared.getPreparedContribution(result.preparedId);+ expect(await fsp.readFile(entry.filePath)).toEqual(bytes);+ expect(result.sha256).toBe(crypto.createHash('sha256').update(bytes).digest('hex'));+ harness.ghosts[0] = {+ ...harness.ghosts[0],+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000002' },+ };+ expect(() => prepared.assertPreparedInstallation(entry)).toThrow('Installed plugin changed');+ await prepared.releasePreparedContribution(result.preparedId);+ });+});+++describe('publishing summary package binding', () => {+ it('keeps notes from the package and detects changed installed bytes before submission', async () => {+ harness.ghosts[0].manifest.releaseNotes = 'All changes since the last released version';+ const summary = await prepared.prepareInstalledContribution('hello');+ expect(summary.releaseNotes).toBe(harness.ghosts[0].manifest.releaseNotes);+ const entry = prepared.getPreparedContribution(summary.preparedId);+ await expect(prepared.assertPreparedContent(entry)).resolves.toBeUndefined();+ harness.snapshot.mockResolvedValueOnce({ status: 'prepared', bytes, contentSha256: 'changed-content' });+ await expect(prepared.assertPreparedContent(entry)).rejects.toThrow('CONTRIBUTION_PACKAGE_CHANGED');+ });+});+++it('gives concurrent preview callers independent ownership', async () => {+ const [first, second] = await Promise.all([prepared.prepareInstalledContribution('hello'), prepared.prepareInstalledContribution('hello')]);+ expect(first.preparedId).not.toBe(second.preparedId);+ await prepared.releasePreparedContribution(first.preparedId);+ expect(prepared.getPreparedContribution(second.preparedId).summary).toEqual(second);+});diff --git a/apps/desktop/src/main/plugin-contributions/__tests__/registerIpc.test.ts b/apps/desktop/src/main/plugin-contributions/__tests__/registerIpc.test.tsnew file mode 100644index 0000000000..db509c28f8--- /dev/null+++ b/apps/desktop/src/main/plugin-contributions/__tests__/registerIpc.test.ts@@ -0,0 +1,148 @@+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++const harness = vi.hoisted(() => ({+ reviews: vi.fn(),+ markRead: vi.fn(),+ handlers: new Map<string, (event: unknown, raw?: unknown) => Promise<unknown>>(),+ trusted: vi.fn(),+ prepare: vi.fn(),+ cancelReview: vi.fn(),+ setAnonymity: vi.fn(),+ detail: vi.fn(),+ releases: vi.fn(),+ failure: vi.fn(),+}));+vi.mock('electron', () => ({+ ipcMain: {+ handle: (name: string, handler: (event: unknown, raw?: unknown) => Promise<unknown>) =>+ harness.handlers.set(name, handler),+ },+}));+vi.mock('../../security/trustedAppRenderer', () => ({+ assertTrustedAppRendererEvent: harness.trusted,+}));+vi.mock('../reviewUpdates', () => ({ reviewUpdates: harness.reviews, markReviewRead: harness.markRead }));+vi.mock('../host', () => ({+ prepareContribution: harness.prepare,+ cancelPluginReview: harness.cancelReview,+ setPluginAnonymity: harness.setAnonymity,+ myPluginDetail: harness.detail,+ mapContributionError: harness.failure,+ submitContribution: vi.fn(),+ resumeContribution: vi.fn(),+ contributionTransferStatus: vi.fn(),+ cancelContribution: vi.fn(),+ discardContribution: vi.fn(),+ listContributionTransfers: vi.fn(),+ listMyPlugins: vi.fn(),+ myPluginSubmission: vi.fn(),+ myPluginReleases: harness.releases,+}));+beforeAll(async () => {+ (await import('../registerIpc')).registerPluginContributionsIpc();+});+beforeEach(() => {+ vi.resetAllMocks();+});+describe('personal contribution IPC', () => {+ it('reads versions through the trusted renderer with bounded pagination and no authority override', async () => {+ const handler = harness.handlers.get('plugin-contributions:releases')!;+ const result = { releases: [], nextCursor: null, queriedAt: '2026-10-16T00:00:00.000Z' };+ harness.releases.mockResolvedValue(result);+ await expect(handler({}, { pluginId: 'plugin', cursor: 'page-2' })).resolves.toEqual(result);+ expect(harness.releases).toHaveBeenCalledWith('plugin', 'page-2');+ for (const invalid of [+ { pluginId: 'plugin', membershipId: 'other' },+ { pluginId: 'plugin', cursor: 'x'.repeat(4097) },+ { pluginId: '' },+ ])+ await expect(handler({}, invalid)).rejects.toThrow('INVALID_PARAMS');+ harness.trusted.mockImplementationOnce(() => {+ throw new Error('[PERMISSION_DENIED] untrusted');+ });+ await expect(handler({}, { pluginId: 'plugin' })).rejects.toThrow('PERMISSION_DENIED');+ expect(harness.releases).toHaveBeenCalledTimes(1);+ });+ it('passes only the exact instance identifier and a Host-owned manual source', async () => {+ harness.prepare.mockResolvedValue({ preparedId: 'prepared' });+ await expect(+ harness.handlers.get('plugin-contributions:prepare')!(+ {},+ { instanceId: 'physical-instance' },+ ),+ ).resolves.toEqual({ preparedId: 'prepared' });+ expect(harness.prepare).toHaveBeenCalledWith('physical-instance', 'manual', undefined);+ await expect(+ harness.handlers.get('plugin-contributions:prepare')!(+ {},+ { instanceId: 'physical-instance', path: '/private/package.cindy' },+ ),+ ).rejects.toThrow('INVALID_PARAMS');+ expect(harness.prepare).toHaveBeenCalledTimes(1);+ });+ it('rejects an untrusted renderer before accessing personal author data', async () => {+ harness.trusted.mockImplementationOnce(() => {+ throw new Error('[PERMISSION_DENIED] untrusted');+ });+ await expect(+ harness.handlers.get('plugin-contributions:detail')!({}, { pluginId: 'plugin' }),+ ).rejects.toThrow('PERMISSION_DENIED');+ expect(harness.detail).not.toHaveBeenCalled();+ });+ it('rejects extra authority fields and forwards failures to the redaction boundary', async () => {+ const handler = harness.handlers.get('plugin-contributions:detail')!;+ await expect(+ handler({}, { pluginId: 'plugin', membershipId: 'another-member' }),+ ).rejects.toThrow('INVALID_PARAMS');+ expect(harness.detail).not.toHaveBeenCalled();+ const failure = new Error('private transport detail');+ harness.detail.mockRejectedValueOnce(failure);+ harness.failure.mockImplementationOnce(() => {+ throw new Error('[INTERNAL] Community contribution request failed');+ });+ await expect(handler({}, { pluginId: 'plugin' })).rejects.toThrow(+ '[INTERNAL] Community contribution request failed',+ );+ expect(harness.failure).toHaveBeenCalledWith(failure);+ });+});+++it('cancels only the exact displayed release and rejects extra caller identity', async () => {+ const input = { pluginId: 'plugin', release: { releaseId: 'release', sha256: 'a'.repeat(64), revision: '2026-10-16T00:00:00.000Z' } };+ harness.cancelReview.mockResolvedValue({ reviewStatus: 'cancelled' });+ const cancel = harness.handlers.get('plugin-contributions:cancel-review')!;+ await expect(cancel({}, input)).resolves.toMatchObject({ reviewStatus: 'cancelled' });+ expect(harness.cancelReview).toHaveBeenCalledWith(input.pluginId, input.release);+ await expect(cancel({}, { ...input, membershipId: 'other' })).rejects.toThrow('INVALID_PARAMS');+ await expect(cancel({}, { ...input, release: { ...input.release, revision: 'bad' } })).rejects.toThrow('INVALID_PARAMS');+ expect(harness.cancelReview).toHaveBeenCalledTimes(1);+});++it('validates review-read receipts and rejects remote subject overrides before reading or acknowledging', async () => {+ const list = harness.handlers.get('plugin-contributions:review-updates')!;+ harness.reviews.mockResolvedValue([]);+ await expect(list({}, undefined)).resolves.toEqual([]);+ await expect(list({}, { membershipId: 'other' })).rejects.toThrow('INVALID_PARAMS');+ const mark = harness.handlers.get('plugin-contributions:mark-review-read')!;+ await mark({}, { pluginId: 'plugin', key: 'exact-decision' });+ expect(harness.markRead).toHaveBeenCalledExactlyOnceWith('plugin', 'exact-decision');+ await expect(mark({}, { pluginId: 'plugin', key: 'exact', authority: 'other' })).rejects.toThrow('INVALID_PARAMS');+ await expect(mark({}, { pluginId: 'plugin', key: 'x'.repeat(1025) })).rejects.toThrow('INVALID_PARAMS');+ harness.trusted.mockImplementationOnce(() => { throw new Error('PERMISSION_DENIED'); });+ await expect(mark({}, { pluginId: 'plugin', key: 'exact' })).rejects.toThrow('PERMISSION_DENIED');+ expect(harness.markRead).toHaveBeenCalledTimes(1);+});+++it('validates anonymity preferences without accepting a caller-supplied author identity', async () => {+ const handler = harness.handlers.get('plugin-contributions:set-anonymity')!;+ await handler({}, { pluginId: 'plugin', anonymous: false });+ expect(harness.setAnonymity).toHaveBeenCalledExactlyOnceWith('plugin', false);+ for (const input of [{ pluginId: 'plugin', anonymous: 'false' }, { pluginId: 'plugin', anonymous: false, membershipId: 'other' }])+ await expect(handler({}, input)).rejects.toThrow('INVALID_PARAMS');+ expect(harness.setAnonymity).toHaveBeenCalledTimes(1);+ harness.trusted.mockImplementationOnce(() => { throw new Error('PERMISSION_DENIED'); });+ await expect(handler({}, { pluginId: 'plugin', anonymous: true })).rejects.toThrow('PERMISSION_DENIED');+ expect(harness.setAnonymity).toHaveBeenCalledTimes(1);+});diff --git a/apps/desktop/src/main/plugin-contributions/api.ts b/apps/desktop/src/main/plugin-contributions/api.tsnew file mode 100644index 0000000000..72649c7fbc--- /dev/null+++ b/apps/desktop/src/main/plugin-contributions/api.ts@@ -0,0 +1,195 @@+import { app, net } from 'electron';+import type { z } from 'zod';+import * as wire from '../../shared/pluginContributionContract.js';+import { getAccessToken, getActiveAuthRealm, getAuthState, refresh } from '../authManager.js';+import { getClientEndpoint, getClientEndpointForRealm } from '../clientEndpointsService.js';+import { ServerApiError, serverApiFetch } from '../serverApiClient.js';+import { throwIpcError } from '../utils/ipcValidate.js';+import { assertContributionOwner, contributionOwnerKey } from './prepared.js';++const issuerCache = new Map<string, { issuer: string; until: number }>();++/** Discover issuer only from the Host's trusted auth endpoint, never from an unverified token URL. */+async function trustedIssuer(endpoint: string): Promise<string> {+ const cached = issuerCache.get(endpoint);+ if (cached && cached.until > Date.now()) return cached.issuer;+ const response = await net.fetch(+ `${endpoint.replace(/\/+$/, '')}/.well-known/openid-configuration`,+ {+ signal: AbortSignal.timeout(15_000),+ redirect: 'error',+ },+ );+ if (!response.ok)+ throwIpcError('PRECONDITION_FAILED', 'Unable to resolve trusted contribution issuer');+ const value: unknown = await response.json();+ const issuer = value && typeof value === 'object' && 'issuer' in value ? value.issuer : null;+ if (typeof issuer !== 'string' || !/^https?:\/\//.test(issuer))+ throwIpcError('PRECONDITION_FAILED', 'Invalid trusted issuer configuration');+ issuerCache.set(endpoint, { issuer, until: Date.now() + 300_000 });+ return issuer;+}++export class ContributionApi {+ constructor(private readonly assertCaller?: () => Promise<void>) {}+ readonly owner = contributionOwnerKey();+ private readonly endpoint = getClientEndpoint('pluginApiBaseUrl');+ private readonly authEndpoint = getClientEndpointForRealm(getActiveAuthRealm(), 'authApiBaseUrl');+ private subject: wire.ContributionSubject | null = null;++ private async token(): Promise<string> {+ assertContributionOwner(this.owner);+ const token = getAccessToken();+ if (!token) throwIpcError('ACCOUNT_REAUTH_REQUIRED', 'Personal login required');+ const issuer = await trustedIssuer(this.authEndpoint);+ assertContributionOwner(this.owner);+ // Claims here only bind the response to the Host session. Plugin Server+ // authenticates the signature; decoded claims never grant submission rights.+ let claims: { iss?: string; sub?: string; ctx?: string };+ try {+ claims = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf8'));+ } catch {+ throwIpcError('ACCOUNT_REAUTH_REQUIRED', 'Invalid personal session');+ }+ if (+ claims.iss !== issuer ||+ typeof claims.sub !== 'string' ||+ claims.sub !== getAuthState().user?.id ||+ claims.ctx !== 'personal'+ ) {+ throwIpcError('ACCOUNT_REAUTH_REQUIRED', 'Personal session issuer mismatch');+ }+ this.subject = { authority: issuer, membershipId: claims.sub };+ return token;+ }++ async request<S extends z.ZodTypeAny>(+ route: string,+ schema: S,+ method = 'GET',+ body?: unknown,+ headers?: Record<string, string>,+ ): Promise<z.infer<S>> {+ const run = async () => {+ const token = await this.token();+ assertContributionOwner(this.owner);+ await this.assertCaller?.();+ assertContributionOwner(this.owner);+ const value = await serverApiFetch<unknown>(`/api/plugin-contributions${route}`, {+ baseUrl: this.endpoint,+ token,+ method,+ body,+ headers: { ...headers, 'x-cindy-version': app.getVersion() },+ cache: 'no-store',+ timeoutMs: 20_000,+ skipAutoRefresh: true,+ skipSessionInvalidation: true,+ redactErrorDetails: true,+ logLabel: '/api/plugin-contributions',+ allowedRedactedErrorCodes: [+ ...wire.CONTRIBUTION_ERROR_CODES,+ 'UNAUTHORIZED',+ 'INVALID_TOKEN',+ 'TOKEN_EXPIRED',+ ],+ });+ assertContributionOwner(this.owner);+ const parsed = schema.safeParse(value);+ if (!parsed.success) throwIpcError('PRECONDITION_FAILED', 'Invalid contribution response');+ const result = parsed.data;+ const subject = wire.contributionSubject.safeParse((result as { subject?: unknown }).subject);+ if (+ !subject.success ||+ subject.data.authority !== this.subject?.authority ||+ subject.data.membershipId !== this.subject?.membershipId+ ) {+ throwIpcError('OWNER_CHANGED', 'Contribution response subject mismatch');+ }+ return result;+ };+ try {+ return await run();+ } catch (error) {+ assertContributionOwner(this.owner);+ if (+ error instanceof ServerApiError &&+ error.statusCode === 401 &&+ ['UNAUTHORIZED', 'INVALID_TOKEN', 'TOKEN_EXPIRED'].includes(error.code)+ ) {+ await refresh();+ assertContributionOwner(this.owner);+ return run();+ }+ throw error;+ }+ }++ preflight(input: { pluginId: string | null; ghostId: string; version: string; hasReleaseNotes: boolean }) {+ return this.request(+ `/preflight?${new URLSearchParams({ ghostId: input.ghostId, version: input.version, hasReleaseNotes: String(input.hasReleaseNotes), ...(input.pluginId ? { pluginId: input.pluginId } : {}) })}`,+ wire.contributionPreflight,+ );+ }+ cancelReview(pluginId: string, expectedRelease: z.infer<typeof wire.releaseRevision>) {+ return this.request(+ `/plugins/${encodeURIComponent(pluginId)}/releases/${encodeURIComponent(expectedRelease.releaseId)}/cancel-review`,+ wire.cancelledReview,+ 'POST',+ { expectedRelease },+ );+ }+ prepare(body: wire.ContributionRequest, key: string) {+ return this.request(+ '/prepare',+ wire.preparedResponse,+ 'POST',+ wire.contributionRequest.parse(body),+ { 'Idempotency-Key': key },+ );+ }+ commit(id: string) {+ return this.request(+ `/operations/${encodeURIComponent(id)}/commit`,+ wire.commitResponse,+ 'POST',+ {},+ );+ }+ operation(id: string) {+ return this.request(`/operations/${encodeURIComponent(id)}`, wire.contributionOperation);+ }+ list(input: { query: string; filter: string; cursor?: string }) {+ const params = new URLSearchParams({+ query: input.query.trim(),+ filter: input.filter,+ limit: '20',+ });+ if (input.cursor) params.set('cursor', input.cursor);+ return this.request(`/plugins?${params}`, wire.myPluginList);+ }+ detail(id: string) {+ return this.request(`/plugins/${encodeURIComponent(id)}`, wire.myPluginDetail);+ }+ setAnonymity(id: string, anonymous: boolean) {+ return this.request(`/plugins/${encodeURIComponent(id)}/author-settings`, wire.myPluginDetail, 'PATCH', { anonymous });+ }+ history(id: string, cursor: string) {+ return this.request(+ `/plugins/${encodeURIComponent(id)}/history?${new URLSearchParams({ cursor, limit: '20' })}`,+ wire.myPluginHistory,+ );+ }+ releases(id: string, version?: string, cursor?: string) {+ return this.request(+ `/plugins/${encodeURIComponent(id)}/releases?${new URLSearchParams({ ...(version ? { version } : {}), ...(cursor ? { cursor } : {}), limit: '50' })}`,+ wire.myPluginReleases,+ );+ }+ submission(pluginId: string, submissionId: string) {+ return this.request(+ `/plugins/${encodeURIComponent(pluginId)}/submissions/${encodeURIComponent(submissionId)}`,+ wire.mySubmissionDetail,+ );+ }+}diff --git a/apps/desktop/src/main/plugin-contributions/host.ts b/apps/desktop/src/main/plugin-contributions/host.tsnew file mode 100644index 0000000000..b8916f28fe--- /dev/null+++ b/apps/desktop/src/main/plugin-contributions/host.ts@@ -0,0 +1,790 @@+import crypto from 'node:crypto';+import fs from 'node:fs';+import fsp from 'node:fs/promises';+import path from 'node:path';+import { app } from 'electron';+import { z } from 'zod';+import * as wire from '../../shared/pluginContributionContract.js';+import type {+ ContributionInstallationBinding,+ ContributionReleaseView,+ ContributionTransferView,+ MyPluginDetailView,+ MyPluginFilter,+ MyPluginLocalInstallation,+ MyPluginPageView,+ MyPluginReleasePageView,+ MyPluginView,+} from '../../shared/pluginContributions.js';+import {+ ghostInstallApprovalToken,+ ghostPermissionItems,+ validateGhostManifest,+ type InstalledGhost,+} from '../../shared/ghost.js';+import {+ findInstalledGhostByInstanceId,+ installedGhostStoragePart,+} from '../../shared/pluginIdentity.js';+import { ownerScopedUserDataPath } from '../appSessionState.js';+import { isPassiveSharedUserDataInstance, onAuthStateChange } from '../authManager.js';+import { getGhostManager } from '../cindy-brain/index.js';+import { getClientEndpoint } from '../clientEndpointsService.js';+import { onQuit } from '../lifecycle.js';+import { putLocalFile } from '../plugin-publisher/putObject.js';+import { PluginMarketLedger } from '../plugin-market/ledger.js';+import { ServerApiError } from '../serverApiClient.js';+import { isIpcError, isIpcErrorCode } from '../../shared/ipc-errors.js';+import { throwIpcError } from '../utils/ipcValidate.js';+import { ContributionApi } from './api.js';+import {+ assertContributionOwner,+ assertPreparedInstallation,+ assertPreparedContent,+ contributionAccountKey,+ contributionOwnerKey,+ getPreparedContribution,+ prepareInstalledContribution,+ releasePreparedContribution,+ readContributionInstallation,+} from './prepared.js';++const preparedSchema = z.object({+ preparedId: z.string(),+ instanceId: z.string(),+ pluginId: z.string().nullable(),+ ghostId: z.string(),+ name: z.string(),+ description: z.string(),+ releaseNotes: z.string().optional(),+ preflight: wire.contributionPreflight.optional(),+ version: z.string(),+ sha256: z.string(),+ sizeBytes: z.number(),+ expiresAt: z.string(),+});+const recordSchema = z.object({+ localId: z.string(),+ owner: z.string(),+ accountKey: z.string(),+ prepared: preparedSchema,+ key: z.string(),+ request: wire.contributionRequest,+ directory: z.string(),+ approvalToken: z.string(),+ contentSha256: z.string().optional(),+ installationDir: z.string(),+ phase: z.enum(['prepared', 'uploaded', 'committing', 'processing', 'terminal']),+ stage: z.enum(['prepared', 'uploading', 'processing', 'paused', 'complete']),+ operationId: z.string().nullable(),+ operation: wire.contributionOperation.nullable(),+ errorCode: z.string().nullable(),+});+type RecordEntry = z.infer<typeof recordSchema>;+interface Journal {+ owner: string;+ file: string;+ records: RecordEntry[];+}+const journals = new Map<string, Journal>();+const pending = new Map<+ string,+ { owner: string; controller: AbortController; task: Promise<void> }+>();+const preparedTargets = new Map<string, { owner: string; request: wire.ContributionRequest }>();+let hooked = false;++function journal(owner = contributionOwnerKey()): Journal {+ assertContributionOwner(owner);+ const existing = journals.get(owner);+ if (existing) return existing;+ const accountKey = contributionAccountKey();+ const file = ownerScopedUserDataPath(+ 'plugin-contributions',+ `${crypto.createHash('sha256').update(accountKey).digest('hex').slice(0, 20)}.v1.json`,+ );+ let records: RecordEntry[] = [];+ try {+ records = z+ .array(recordSchema)+ .parse(JSON.parse(fs.readFileSync(file, 'utf8')))+ .filter((entry) => entry.accountKey === accountKey)+ .map((entry) => ({ ...entry, owner }));+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT')+ throwIpcError('PRECONDITION_FAILED', 'Contribution recovery journal cannot be read');+ }+ const value = { owner, file, records };+ journals.set(owner, value);+ if (!hooked) {+ hooked = true;+ const abort = () => {+ for (const run of pending.values()) run.controller.abort();+ };+ onAuthStateChange(() => {+ for (const run of pending.values()) {+ try {+ assertContributionOwner(run.owner);+ } catch {+ run.controller.abort();+ }+ }+ });+ onQuit('plugin-contributions', abort, 'sync');+ }+ return value;+}++function persist(book: Journal): void {+ assertContributionOwner(book.owner);+ assertWritableInstance();+ fs.mkdirSync(path.dirname(book.file), { recursive: true });+ const temporary = `${book.file}.${crypto.randomUUID()}.tmp`;+ fs.writeFileSync(temporary, JSON.stringify(book.records), { mode: 0o600 });+ fs.renameSync(temporary, book.file);+}+function view(record: RecordEntry): ContributionTransferView {+ return {+ localId: record.localId,+ prepared: record.prepared,+ stage: record.stage,+ operation: record.operation,+ errorCode: record.errorCode,+ };+}+function locate(id: string): { book: Journal; record: RecordEntry } {+ const book = journal();+ const record = book.records.find((entry) => entry.localId === id);+ if (!record) throwIpcError('NOT_FOUND', 'Contribution operation not found for this account');+ return { book, record };+}+function safeCode(error: unknown): string {+ if (isIpcError(error)) return error.code;+ if (+ error instanceof ServerApiError &&+ (wire.CONTRIBUTION_ERROR_CODES as readonly string[]).includes(error.code)+ )+ return error.code;+ return 'INTERNAL';+}+export function mapContributionError(error: unknown): never {+ if (isIpcError(error)) throw error;+ const code = safeCode(error);+ throwIpcError(isIpcErrorCode(code) ? code : 'INTERNAL', 'Community contribution request failed');+}++function assertWritableInstance(): void {+ if (isPassiveSharedUserDataInstance())+ throwIpcError('PRECONDITION_FAILED', 'Use the active Cindy instance for contribution recovery');+}++function running(record: RecordEntry): boolean {+ return pending.get(record.localId)?.owner === record.owner;+}++function assertClientPublishingTarget(plugin: Pick<wire.MyPluginSummary, 'publisherKind'>): void {+ if (plugin.publisherKind === 'official')+ throwIpcError('OFFICIAL_PLUGIN_GITHUB_REQUIRED', 'Submit official public plugins through GitHub to keep repository source complete and maintainable');+}++/** Resolve an existing public target only through a server-authorized identity, never package authorship. */+export async function prepareContribution(+ instanceId: string,+ source: 'manual' | 'ai',+ expected?: ContributionInstallationBinding,+) {+ assertWritableInstance();+ const api = new ContributionApi();+ const initial = readContributionInstallation(instanceId, expected);+ const binding = { directory: initial.ghost.dir, approvalToken: ghostInstallApprovalToken(initial.ghost.approval) };+ const targetId = initial.source.kind === 'public-market' ? initial.source.pluginId : null;+ // A downloaded package needs current publishing ACL BEFORE reading its bytes.+ if (targetId) {+ const target = await api.detail(targetId);+ assertClientPublishingTarget(target.plugin);+ if (!target.plugin.actions.canSubmit || target.plugin.pluginId !== targetId ||+ target.plugin.ghostId !== initial.ghost.manifest.id || target.plugin.namespace !== initial.ghost.namespace)+ throwIpcError('PERMISSION_DENIED', 'Publishing permission required');+ assertContributionOwner(api.owner);+ const current = readContributionInstallation(instanceId, binding);+ if (JSON.stringify(current.source) !== JSON.stringify(initial.source))+ throwIpcError('PRECONDITION_FAILED', 'Publishing source changed');+ }+ // Also bind callers without a Renderer-supplied binding across asynchronous pruning.+ const prepared = await prepareInstalledContribution(instanceId, source, binding);+ const entry = getPreparedContribution(prepared.preparedId);+ try {+ const preflight = await api.preflight({+ pluginId: targetId ?? prepared.pluginId,+ ghostId: prepared.ghostId,+ version: prepared.version,+ hasReleaseNotes: Boolean(prepared.releaseNotes?.trim()),+ });+ assertPreparedInstallation(entry);+ if (preflight.target.pluginId) {+ const target = await api.detail(preflight.target.pluginId);+ assertClientPublishingTarget(target.plugin);+ if (!target.plugin.actions.canSubmit) throwIpcError('PERMISSION_DENIED', 'Publishing permission required');+ assertPreparedInstallation(entry);+ }+ prepared.pluginId = preflight.target.pluginId;+ prepared.preflight = preflight;+ const request: wire.ContributionRequest = {+ sizeBytes: prepared.sizeBytes,+ sha256: prepared.sha256,+ source,+ target: preflight.target,+ };+ preparedTargets.set(prepared.preparedId, { owner: api.owner, request });+ return prepared;+ } catch (error) {+ await releasePreparedContribution(prepared.preparedId);+ throw error;+ }+}++export async function discardContribution(preparedId: string): Promise<void> {+ const entry = getPreparedContribution(preparedId);+ // Once submitted, the durable transfer owns these bytes until its terminal cleanup.+ if (entry.pinned) return;+ preparedTargets.delete(preparedId);+ await releasePreparedContribution(preparedId);+}++export async function submitContribution(+ preparedId: string,+ assertCaller?: () => Promise<void>,+): Promise<ContributionTransferView> {+ assertWritableInstance();+ const entry = getPreparedContribution(preparedId);+ assertPreparedInstallation(entry);+ if (!entry.summary.preflight?.actions.canSubmit) {+ const blocker = entry.summary.preflight?.blockers[0];+ const code = blocker?.code;+ throwIpcError(+ code && isIpcErrorCode(code) ? code : 'PRECONDITION_FAILED',+ blocker?.message ?? 'Refresh the publishing summary before submitting',+ );+ }+ await assertPreparedContent(entry);+ await assertCaller?.();+ assertPreparedInstallation(entry);+ const target = preparedTargets.get(preparedId);+ if (!target || target.owner !== entry.owner)+ throwIpcError('PRECONDITION_FAILED', 'Prepare this contribution again explicitly');+ const book = journal(entry.owner);+ const existing = book.records.find((item) => item.localId === preparedId || (+ item.phase !== 'terminal' &&+ item.prepared.instanceId === entry.summary.instanceId &&+ item.installationDir === entry.installationDir && item.approvalToken === entry.approvalToken &&+ JSON.stringify(item.request.target) === JSON.stringify(target.request.target) &&+ item.request.source === target.request.source &&+ (item.request.sha256 === target.request.sha256 ||+ (Boolean(entry.contentSha256) && item.contentSha256 === entry.contentSha256))+ ));+ if (existing) {+ // A normal submit of the same package reuses its pending request internally.+ // ZIP timestamps may differ, so compare the verified content fingerprint too.+ if (existing.localId !== preparedId) await discardContribution(preparedId);+ assertContributionOwner(entry.owner);+ start(book, existing, assertCaller);+ return view(existing);+ }+ if (book.records.filter((item) => item.phase !== 'terminal').length >= 16)+ throwIpcError('PRECONDITION_FAILED', 'Too many unfinished contributions');+ const record: RecordEntry = {+ localId: preparedId,+ owner: entry.owner,+ accountKey: contributionAccountKey(),+ prepared: entry.summary,+ key: entry.idempotencyKey,+ request: target.request,+ directory: entry.directory,+ approvalToken: entry.approvalToken,+ contentSha256: entry.contentSha256,+ installationDir: entry.installationDir,+ phase: 'prepared',+ stage: 'prepared',+ operationId: null,+ operation: null,+ errorCode: null,+ };+ // Persist the key and immutable request BEFORE the first remote write.+ book.records.push(record);+ persist(book);+ entry.pinned = true;+ start(book, record, assertCaller);+ return view(record);+}++function start(book: Journal, record: RecordEntry, assertCaller?: () => Promise<void>): void {+ assertContributionOwner(record.owner);+ assertWritableInstance();+ if (running(record) || record.phase === 'terminal') return;+ pending.get(record.localId)?.controller.abort();+ record.stage = record.phase === 'prepared' ? 'prepared' : 'processing';+ record.errorCode = null;+ persist(book);+ const controller = new AbortController();+ const task = run(book, record, controller, assertCaller)+ .catch((error) => {+ try {+ assertContributionOwner(record.owner);+ } catch {+ return;+ }+ record.stage = 'paused';+ record.errorCode = safeCode(error);+ // A disk error remains visible in memory; never let a detached task reject.+ try {+ persist(book);+ } catch {+ record.errorCode = 'INTERNAL';+ }+ })+ .finally(() => {+ if (pending.get(record.localId)?.task === task) pending.delete(record.localId);+ });+ pending.set(record.localId, { owner: record.owner, controller, task });+}++function isTerminal(record: RecordEntry): boolean {+ return record.phase === 'terminal';+}++async function accept(book: Journal, record: RecordEntry, operation: wire.ContributionOperation): Promise<void> {+ assertContributionOwner(record.owner);+ if (record.operationId && operation.operationId !== record.operationId)+ throwIpcError('PRECONDITION_FAILED', 'Operation identity changed');+ if (+ operation.receipt &&+ (operation.receipt.uploadedPackage.sha256 !== record.request.sha256 ||+ operation.receipt.uploadedPackage.sizeBytes !== record.request.sizeBytes ||+ operation.receipt.ghostId !== record.request.target.ghostId ||+ operation.receipt.version !== record.request.target.version ||+ (record.request.target.pluginId !== null &&+ operation.receipt.pluginId !== record.request.target.pluginId))+ ) {+ throwIpcError('PRECONDITION_FAILED', 'Contribution receipt does not match uploaded snapshot');+ }+ record.operationId = operation.operationId;+ record.operation = operation;+ if (['succeeded', 'failed', 'expired'].includes(operation.status)) {+ const cleanupDirectory = record.directory ? managedSnapshotDirectory(record.directory) : null;+ record.phase = 'terminal';+ record.stage = 'complete';+ record.errorCode = operation.failure?.code ?? null;+ void releasePreparedContribution(record.localId);+ if (cleanupDirectory)+ void fsp.rm(cleanupDirectory, { recursive: true, force: true }).catch(() => undefined);+ record.directory = '';+ preparedTargets.delete(record.localId);+ } else if (operation.status !== 'awaiting_upload') {+ record.phase = 'processing';+ record.stage = 'processing';+ }+ persist(book);+}++function managedSnapshotDirectory(directory: string): string {+ const absolute = path.resolve(directory);+ const temp = path.resolve(app.getPath('temp'));+ if (path.dirname(absolute) !== temp || !path.basename(absolute).startsWith('cindy-contribution-'))+ throwIpcError('PRECONDITION_FAILED', 'Invalid contribution snapshot location');+ try {+ if (+ !fs.lstatSync(absolute).isDirectory() ||+ fs.lstatSync(absolute).isSymbolicLink() ||+ path.dirname(fs.realpathSync(absolute)) !== fs.realpathSync(temp)+ )+ throwIpcError('PRECONDITION_FAILED', 'Invalid contribution snapshot directory');+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ }+ return absolute;+}++async function run(book: Journal, record: RecordEntry, controller: AbortController, assertCaller?: () => Promise<void>): Promise<void> {+ const signal = controller.signal;+ const api = new ContributionApi(assertCaller);+ if (api.owner !== record.owner) throwIpcError('OWNER_CHANGED', 'Contribution account changed');+ const assert = () => {+ assertContributionOwner(record.owner);+ if (signal.aborted)+ throwIpcError('MUTATION_CANCELLED', 'Upload stopped; existing operation retained');+ };+ assert();+ record.errorCode = null;+ // Unknown commit outcomes are always queried before any further action.+ if (record.operationId) await accept(book, record, await api.operation(record.operationId));+ if (isTerminal(record)) return;+ const assertInstallation = () => readContributionInstallation(record.prepared.instanceId, {+ directory: record.installationDir, approvalToken: record.approvalToken,+ });+ let authorizedSource: string | null = null;+ // The API invokes this after token/discovery/refresh awaits, immediately before+ // dispatch. A stale package or a newly restricted AI task cannot pass that gap.+ const writer = new ContributionApi(async () => {+ await assertCaller?.();+ assertWritableInstance();+ assert();+ if (!authorizedSource || JSON.stringify(assertInstallation().source) !== authorizedSource)+ throwIpcError('PRECONDITION_FAILED', 'Publishing source changed');+ });+ const assertWrite = async () => {+ assert();+ const { source } = assertInstallation();+ // Reading a detail/old receipt is not a current publishing grant. Check the+ // exact target again, including recovery that already passed the PUT stage.+ const id = source.kind === 'public-market' ? source.pluginId : record.request.target.pluginId;+ if (id) {+ const target = await api.detail(id);+ assertClientPublishingTarget(target.plugin);+ if (!target.plugin.actions.canSubmit || target.plugin.pluginId !== record.request.target.pluginId)+ throwIpcError('PERMISSION_DENIED', 'Publishing permission or target changed');+ }+ await assertCaller?.();+ assert();+ if (JSON.stringify(assertInstallation().source) !== JSON.stringify(source))+ throwIpcError('PRECONDITION_FAILED', 'Publishing source changed');+ authorizedSource = JSON.stringify(source);+ };+ if (record.phase === 'prepared') {+ await assertWrite();+ const response = await writer.prepare(record.request, record.key);+ assert();+ const { upload, ...operation } = response;+ await accept(book, record, wire.contributionOperation.parse(operation));+ if (isTerminal(record)) return;+ if (response.status === 'awaiting_upload') {+ if (!upload || new Date(upload.expiresAt).getTime() <= Date.now())+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'Original upload ticket expired; query the original operation',+ );+ // URLs remain Main-only. Redirects and credential-bearing headers are refused.+ const url = new URL(upload.putUrl);+ let localUpload = false;+ if (app.isPackaged === false && url.protocol === 'http:') {+ const endpoint = new URL(getClientEndpoint('pluginApiBaseUrl'));+ // The existing dev-local storage adapter is the only HTTP exception:+ // an explicitly configured loopback server, the same origin and path.+ localUpload =+ endpoint.protocol === 'http:' &&+ ['127.0.0.1', 'localhost', '[::1]'].includes(endpoint.hostname) &&+ !endpoint.username &&+ !endpoint.password &&+ url.origin === endpoint.origin &&+ url.pathname === '/dev-local/member-upload' &&+ !url.hash;+ }+ if (+ (url.protocol !== 'https:' && !localUpload) ||+ url.username ||+ url.password ||+ Object.keys(upload.headers).some((key) =>+ /^(authorization|proxy-authorization|cookie)$/i.test(key),+ )+ )+ throwIpcError('PRECONDITION_FAILED', 'Unsafe upload ticket');+ const directory = managedSnapshotDirectory(record.directory);+ const current = findInstalledGhostByInstanceId(+ getGhostManager().list(),+ record.prepared.instanceId,+ );+ if (+ !current ||+ current.dir !== record.installationDir ||+ current.namespace !== null ||+ current.namespaceState !== 'confirmed' ||+ ghostInstallApprovalToken(current.approval) !== record.approvalToken+ )+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'Installed plugin changed; existing operation retained',+ );+ const handle = await fsp.open(+ path.join(directory, 'plugin.cindy'),+ fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW,+ );+ try {+ const stat = await handle.stat();+ if (!stat.isFile() || stat.size !== record.request.sizeBytes)+ throwIpcError('PRECONDITION_FAILED', 'Original package snapshot unavailable');+ const bytes = await handle.readFile();+ if (crypto.createHash('sha256').update(bytes).digest('hex') !== record.request.sha256)+ throwIpcError('PRECONDITION_FAILED', 'Original package snapshot changed');+ await assertWrite();+ record.stage = 'uploading';+ persist(book);+ await putLocalFile(handle, {+ putUrl: upload.putUrl,+ headers: upload.headers,+ sizeBytes: stat.size,+ signal,+ onBytes: () => {+ // A stream callback must abort the request rather than throw out of+ // Transform._transform and take down the Main process.+ try { assert(); assertInstallation(); } catch { controller.abort(); }+ },+ });+ assert();+ record.phase = 'uploaded';+ persist(book);+ } finally {+ await handle.close();+ }+ }+ }+ await assertWrite();+ if (!record.operationId) throwIpcError('PRECONDITION_FAILED', 'Original operation not known');+ // An explicit resume first queries above, then replays commit on the SAME+ // operation. GET alone cannot reclaim a released validation/publishing lease.+ record.phase = 'committing';+ record.stage = 'processing';+ persist(book);+ await writer.commit(record.operationId);+ assert();+ record.phase = 'processing';+ persist(book);+ // Only the active upload action is followed. Human review is NEVER polled.+ for (let attempt = 0; attempt < 8; attempt++) {+ assert();+ await accept(book, record, await api.operation(record.operationId));+ if (isTerminal(record)) return;+ await new Promise<void>((resolve) => {+ const timer = setTimeout(resolve, Math.min(1000 * (attempt + 1), 5000));+ signal.addEventListener(+ 'abort',+ () => {+ clearTimeout(timer);+ resolve();+ },+ { once: true },+ );+ });+ }+ record.stage = 'paused';+ persist(book);+}++export function resumeContribution(id: string, assertCaller?: () => Promise<void>) {+ const { book, record } = locate(id);+ start(book, record, assertCaller);+ return view(record);+}+export function listContributionTransfers() {+ return journal().records.map((record) => ({+ ...view(record),+ stage: record.phase !== 'terminal' && !running(record) ? ('paused' as const) : record.stage,+ }));+}+export async function contributionTransferStatus(id: string) {+ const { book, record } = locate(id);+ if (record.operationId && !running(record)) {+ assertWritableInstance();+ await accept(book, record, await new ContributionApi().operation(record.operationId));+ }+ return {+ ...view(record),+ stage: record.phase !== 'terminal' && !running(record) ? ('paused' as const) : record.stage,+ };+}+export function cancelContribution(id: string): void {+ const { record } = locate(id);+ if (running(record)) pending.get(id)?.controller.abort();+}++function releaseView(+ value: wire.SubmissionView,+ content: wire.SubmissionContent | null,+): ContributionReleaseView {+ const parsed = content ? validateGhostManifest(content.manifest) : null;+ return {+ submissionId: value.submissionId,+ releaseId: value.releaseId,+ version: value.version,+ sha256: value.revision.sha256,+ revision: value.revision.displayUpdatedAt,+ revisionState: value.revisionState,+ reviewStatus: value.reviewStatus,+ submittedAt: value.submittedAt,+ approvedAt: value.approvedAt,+ cancelledAt: value.cancelledAt,+ canCancelReview: value.actions?.canCancelReview ?? false,+ reviewedAt: value.decidedAt,+ reason: value.reason,+ source: value.source ?? value.publishSource,+ content: content+ ? {+ name: content.manifest.name,+ description: content.manifest.description ?? '',+ iconUrl: content.icon?.url ?? null,+ permissions: parsed?.ok ? ghostPermissionItems(parsed.manifest) : [],+ // Preserve the complete server projection, including capabilities unknown to+ // this client, without inventing current content for historical submissions.+ manifestView: content.manifestView,+ }+ : null,+ };+}+function localPluginInstallation(value: wire.MyPluginSummary): MyPluginLocalInstallation {+ try {+ const manager = getGhostManager();+ manager.assertContributionReadAvailable(value.ghostId);+ const related = manager.list().filter(ghost => ghost.manifest.id === value.ghostId &&+ (ghost.namespace === value.namespace || ghost.namespaceState !== 'confirmed'));+ if (related.length === 0) return { state: 'missing' };+ const matches = related.filter(ghost => {+ if (ghost.namespaceState !== 'confirmed' || ghost.namespace !== value.namespace ||+ ghost.approval.state !== 'approved' || !ghost.publishingSource ||+ ghost.publishingSource.kind === 'unavailable') return false;+ if (ghost.publishingSource.kind === 'local') return true;+ return publicInstallationMatches(value, ghost);+ });+ if (matches.length === 1) {+ const ghost = matches[0];+ return { state: 'installed', instanceId: installedGhostStoragePart(ghost),+ version: ghost.manifest.version, enabled: ghost.enabled,+ origin: ghost.publishingSource?.kind === 'public-market' ? 'public' : 'local' };+ }+ return { state: 'unavailable' };+ } catch {+ return { state: 'unavailable' };+ }+}++function publicInstallationMatches(value: wire.MyPluginSummary, ghost: InstalledGhost): boolean {+ const ledger = new PluginMarketLedger(ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'));+ const lookup = ledger.lookupInstallationForAuthorization({ ghostId: ghost.manifest.id, namespace: ghost.namespace });+ if (lookup.kind !== 'found') return false;+ const record = lookup.record;+ const evidence = getGhostManager().approvedInstallEvidence(installedGhostStoragePart(ghost));+ return Boolean(record.scope === 'public' && record.organizationId === null &&+ (record.source === 'market' || record.source === 'legacy-adopted') &&+ ghost.publishingSource?.kind === 'public-market' && ghost.publishingSource.pluginId === value.pluginId &&+ record.installed && record.pluginId === value.pluginId &&+ record.version === ghost.manifest.version && evidence?.packageSha256 === record.sha256);+}++function pluginView(+ value: wire.MyPluginSummary,+ content: wire.SubmissionContent | null = null,+): MyPluginView {+ const local = localPluginInstallation(value);+ return {+ pluginId: value.pluginId,+ name: value.name,+ displayAuthor: value.displayAuthor ?? null,+ authorSettings: value.authorSettings ?? null,+ publisherKind: value.publisherKind ?? null,+ iconUrl: value.icon?.url ?? null,+ updatedAt: value.updatedAt,+ market: {+ state: value.market.available+ ? 'available'+ : (value.market.unavailableReason ?? 'release_unavailable'),+ version: value.market.currentRelease?.version ?? null,+ releaseId: value.market.currentRelease?.releaseId ?? null,+ reason: null,+ },+ latestSubmission: value.latestSubmission ? releaseView(value.latestSubmission, content) : null,+ actions: { submitUpdate: value.publisherKind !== 'official' && value.actions.canSubmit, viewMarket: value.actions.canViewMarket },+ localInstallation: local,+ localInstanceId: local.state === 'installed' ? local.instanceId : null,+ localVersion: local.state === 'installed' ? local.version : null,+ };+}++export async function listMyPlugins(input: {+ query: string;+ filter: MyPluginFilter;+ cursor?: string;+}): Promise<MyPluginPageView> {+ const result = await new ContributionApi().list({+ ...input,+ filter:+ ({ needs_action: 'action_required', published: 'listed' } as Record<string, string>)[+ input.filter+ ] ?? input.filter,+ });+ return {+ queriedAt: result.queriedAt,+ plugins: result.plugins.map((item) => pluginView(item)),+ nextCursor: result.nextCursor,+ };+}+export async function myPluginDetail(+ pluginId: string,+ cursor?: string,+): Promise<MyPluginDetailView> {+ const api = new ContributionApi();+ const result = await api.detail(pluginId);+ // A later history page has its own read timestamp; never replace the detail+ // market/latest snapshot with fields reconstructed from that event stream.+ const history = cursor ? await api.history(pluginId, cursor) : null;+ return {+ plugin: pluginView(result.plugin, result.latestSubmissionContent),+ queriedAt: result.queriedAt,+ history: history?.events ?? result.history.events,+ nextCursor: history?.nextCursor ?? (history ? null : result.history.nextCursor),+ };+}++export async function setPluginAnonymity(pluginId: string, anonymous: boolean): Promise<MyPluginDetailView> {+ assertWritableInstance();+ const result = await new ContributionApi().setAnonymity(pluginId, anonymous);+ return { plugin: pluginView(result.plugin, result.latestSubmissionContent), queriedAt: result.queriedAt,+ history: result.history.events, nextCursor: result.history.nextCursor };+}++export async function myPluginSubmission(+ pluginId: string,+ submissionId: string,+): Promise<ContributionReleaseView> {+ const result = await new ContributionApi().submission(pluginId, submissionId);+ return {+ ...releaseView(result.submission, result.content),+ uploadedSha256: result.receipt.uploadedPackage.sha256,+ uploadedSizeBytes: result.receipt.uploadedPackage.sizeBytes,+ };+}++export async function myPluginReleases(+ pluginId: string,+ cursor?: string,+): Promise<MyPluginReleasePageView> {+ const result = await new ContributionApi().releases(pluginId, undefined, cursor);+ return {+ releases: result.releases.map((release) => releaseView(release, null)),+ queriedAt: result.queriedAt,+ nextCursor: result.nextCursor,+ };+}++export async function cancelPluginReview(+ pluginId: string,+ release: { releaseId: string; sha256: string; revision: string },+ assertCaller?: () => Promise<void>,+): Promise<ContributionReleaseView> {+ assertWritableInstance();+ const result = await new ContributionApi(assertCaller).cancelReview(pluginId, {+ releaseId: release.releaseId,+ sha256: release.sha256,+ displayUpdatedAt: release.revision,+ });+ return releaseView(result.submission, null);+}++export async function myPluginReviewTarget(pluginId: string, releaseId: string) {+ const api = new ContributionApi();+ const detail = await api.detail(pluginId);+ let cursor: string | undefined;+ do {+ const page = await api.releases(pluginId, undefined, cursor);+ const release = page.releases.find((entry) => entry.releaseId === releaseId);+ if (release) return { name: detail.plugin.name, release: releaseView(release, null) };+ cursor = page.nextCursor ?? undefined;+ } while (cursor);+ throwIpcError('NOT_FOUND', 'Plugin version not found');+}diff --git a/apps/desktop/src/main/plugin-contributions/prepared.ts b/apps/desktop/src/main/plugin-contributions/prepared.tsnew file mode 100644index 0000000000..66191e4608--- /dev/null+++ b/apps/desktop/src/main/plugin-contributions/prepared.ts@@ -0,0 +1,242 @@+import crypto from 'node:crypto';+import fs from 'node:fs/promises';+import path from 'node:path';++import type {+ PreparedPluginContribution,+ ContributionInstallationBinding,+} from '../../shared/pluginContributions.js';+import { ghostInstallApprovalToken, isUserInstallReservedGhostId } from '../../shared/ghost.js';+import { findInstalledGhostByInstanceId } from '../../shared/pluginIdentity.js';+import { app } from 'electron';+import {+ activeOwnerScopeKey,+ getActiveAppSession,+ isAppSessionBoundaryPending,+ ownerScopedUserDataPath,+} from '../appSessionState.js';+import { getAuthState, getActiveAuthRealm } from '../authManager.js';+import { getGhostManager } from '../cindy-brain/index.js';+import { snapshotInstalledGhostPackage } from '../cindy-brain/exportGhostPackage.js';+import { PluginMarketLedger } from '../plugin-market/ledger.js';+import { throwIpcError } from '../utils/ipcValidate.js';++export function contributionAccountKey(): string {+ const state = getAuthState();+ const session = getActiveAppSession();+ return JSON.stringify([session.mode, session.dataOwnerId, getActiveAuthRealm(), state.user?.id]);+}++export function contributionOwnerKey(): string {+ const state = getAuthState();+ if (+ isAppSessionBoundaryPending() ||+ !state.isAuthenticated ||+ state.user?.membershipKind !== 'personal'+ ) {+ throwIpcError('PERMISSION_DENIED', 'Personal account required for community contributions');+ }+ return JSON.stringify([activeOwnerScopeKey(), getActiveAuthRealm(), state.user.id]);+}++export function assertContributionOwner(owner: string): void {+ if (contributionOwnerKey() !== owner)+ throwIpcError('OWNER_CHANGED', 'Contribution account changed');+}++export interface PreparedEntry {+ owner: string;+ approvalToken: string;+ contentSha256: string;+ installationDir: string;+ publishingSourceKey: string;+ pinned: boolean;+ directory: string;+ filePath: string;+ summary: PreparedPluginContribution;+ /** One operation key for every UI/AI retry of this immutable package. */+ idempotencyKey: string;+ expiresAt: number;+}++const entries = new Map<string, PreparedEntry>();+const TTL_MS = 30 * 60_000;++/** Source and approval are independent gates. Neither proves code authorship. */+export function readContributionInstallation(instanceId: string, expected?: ContributionInstallationBinding) {+ const ghost = findInstalledGhostByInstanceId(getGhostManager().list(), instanceId);+ if (!ghost) throwIpcError('NOT_FOUND', 'Installed plugin not found');+ if (expected && (ghost.dir !== expected.directory || ghostInstallApprovalToken(ghost.approval) !== expected.approvalToken))+ throwIpcError('PRECONDITION_FAILED', 'Original installed plugin no longer matches this account');+ if (ghost.namespace === null && ghost.publishingSource?.kind === 'public-market' && ghost.trust?.level === 'cindy-official')+ throwIpcError('OFFICIAL_PLUGIN_GITHUB_REQUIRED', 'Submit official public plugins through GitHub to keep repository source complete and maintainable');+ if (ghost.approval.state !== 'approved' || ghost.namespaceState !== 'confirmed' || ghost.namespace !== null ||+ ghost.builtin || isUserInstallReservedGhostId(ghost.manifest.id))+ throwIpcError('PERMISSION_DENIED', 'Only an approved, non-reserved root installation can be published');+ const record = new PluginMarketLedger(ownerScopedUserDataPath('plugin-market', 'ledger.v1.json'))+ .installationForAuthorization({ ghostId: ghost.manifest.id, namespace: null });+ if (record && (record.scope !== 'public' || record.organizationId !== null))+ throwIpcError('PERMISSION_DENIED', 'Private plugin resources cannot be converted to public');+ if (record?.installed && record.source !== 'market' && record.source !== 'legacy-adopted')+ throwIpcError('PERMISSION_DENIED', 'Custom market installation does not grant publishing permission');+ const source = ghost.publishingSource;+ if (!source || source.kind === 'unavailable')+ throwIpcError('PERMISSION_DENIED', 'Publishing source could not be verified');+ return { ghost, source };+}++async function prune(): Promise<void> {+ const owner = contributionOwnerKey();+ for (const [id, entry] of entries) {+ if (entry.pinned || (entry.owner === owner && entry.expiresAt > Date.now())) continue;+ entries.delete(id);+ await fs.rm(entry.directory, { recursive: true, force: true }).catch(() => undefined);+ }+}++/** Never accepts a source path. Main resolves the exact approved installation. */+export async function prepareInstalledContribution(+ instanceId: string,+ _source: 'manual' | 'ai' = 'manual',+ expected?: ContributionInstallationBinding,+): Promise<PreparedPluginContribution> {+ // Host records the source on its request; the byte snapshot is source independent.+ void _source;+ const owner = contributionOwnerKey();+ // Every caller owns its own preview. A disposed StrictMode render must not+ // discard another caller's identical package or idempotency key.+ return prepare(owner, instanceId, expected);+}++async function prepare(+ owner: string,+ instanceId: string,+ expected?: ContributionInstallationBinding,+): Promise<PreparedPluginContribution> {+ await prune();+ assertContributionOwner(owner);+ if ([...entries.values()].filter((entry) => entry.owner === owner).length >= 8)+ throwIpcError('PRECONDITION_FAILED', 'Too many prepared contributions');+ const manager = getGhostManager();+ const { ghost, source } = readContributionInstallation(instanceId, expected);+ const approval = ghostInstallApprovalToken(ghost.approval);+ const snapshot = await snapshotInstalledGhostPackage(instanceId, {+ listInstalled: () => [ghost],+ });+ assertContributionOwner(owner);+ if (snapshot.status !== 'prepared')+ throwIpcError('PRECONDITION_FAILED', 'Plugin package could not be prepared');+ const directory = await fs.mkdtemp(path.join(app.getPath('temp'), 'cindy-contribution-'));+ const filePath = path.join(directory, 'plugin.cindy');+ try {+ await fs.writeFile(filePath, snapshot.bytes, { flag: 'wx', mode: 0o600 });+ const inspected = await manager.inspect(filePath);+ assertContributionOwner(owner);+ if ('rejection' in inspected)+ throwIpcError('PRECONDITION_FAILED', 'Plugin package validation failed');+ const current = readContributionInstallation(instanceId).ghost;+ if (+ !current ||+ current.dir !== ghost.dir ||+ ghostInstallApprovalToken(current.approval) !== approval ||+ current.namespaceState !== 'confirmed' ||+ current.namespace !== null ||+ JSON.stringify(current.publishingSource) !== JSON.stringify(source) ||+ inspected.canonicalManifest.id !== ghost.manifest.id ||+ inspected.canonicalManifest.version !== ghost.manifest.version+ ) {+ throwIpcError('PRECONDITION_FAILED', 'Installed plugin changed while preparing');+ }+ const sha256 = crypto.createHash('sha256').update(snapshot.bytes).digest('hex');+ if (sha256 !== inspected.packageSha256)+ throwIpcError('PRECONDITION_FAILED', 'Package checksum changed');+ const preparedId = crypto.randomUUID();+ const expiresAt = Date.now() + TTL_MS;+ const manifest = inspected.canonicalManifest;+ const summary: PreparedPluginContribution = {+ preparedId,+ instanceId,+ pluginId: source.kind === 'public-market' ? source.pluginId : null,+ ghostId: manifest.id,+ name: manifest.name,+ description: manifest.description ?? '',+ version: manifest.version,+ releaseNotes: manifest.releaseNotes,+ sha256,+ sizeBytes: snapshot.bytes.byteLength,+ expiresAt: new Date(expiresAt).toISOString(),+ };+ entries.set(preparedId, {+ owner,+ approvalToken: approval,+ contentSha256: snapshot.contentSha256,+ installationDir: ghost.dir,+ publishingSourceKey: JSON.stringify(source),+ pinned: false,+ directory,+ filePath,+ summary,+ idempotencyKey: crypto.randomUUID(),+ expiresAt,+ });+ const timer = setTimeout(() => {+ const entry = entries.get(preparedId);+ if (!entry || entry.pinned) return;+ entries.delete(preparedId);+ void fs.rm(entry.directory, { recursive: true, force: true }).catch(() => undefined);+ }, TTL_MS);+ timer.unref();+ return summary;+ } catch (error) {+ await fs.rm(directory, { recursive: true, force: true }).catch(() => undefined);+ throw error;+ }+}++export function getPreparedContribution(preparedId: string): PreparedEntry {+ const entry = entries.get(preparedId);+ if (!entry || entry.expiresAt <= Date.now())+ throwIpcError('PRECONDITION_FAILED', 'Prepared contribution expired');+ assertContributionOwner(entry.owner);+ return entry;+}++export function assertPreparedInstallation(entry: PreparedEntry): void {+ assertContributionOwner(entry.owner);+ const current = readContributionInstallation(entry.summary.instanceId).ghost;+ if (+ !current ||+ current.dir !== entry.installationDir ||+ current.namespace !== null ||+ current.namespaceState !== 'confirmed' ||+ ghostInstallApprovalToken(current.approval) !== entry.approvalToken ||+ JSON.stringify(current.publishingSource) !== entry.publishingSourceKey+ ) {+ throwIpcError('PRECONDITION_FAILED', 'Installed plugin changed; prepare again explicitly');+ }+}++export async function assertPreparedContent(entry: PreparedEntry): Promise<void> {+ assertPreparedInstallation(entry);+ const snapshot = await snapshotInstalledGhostPackage(entry.summary.instanceId, {+ listInstalled: () => getGhostManager().list(),+ });+ assertPreparedInstallation(entry);+ if (+ snapshot.status !== 'prepared' ||+ !entry.contentSha256 ||+ snapshot.contentSha256 !== entry.contentSha256+ ) {+ throwIpcError(+ 'CONTRIBUTION_PACKAGE_CHANGED',+ 'Installed plugin changed after the publishing summary was shown; refresh before submitting',+ );+ }+}++export async function releasePreparedContribution(preparedId: string): Promise<void> {+ const entry = entries.get(preparedId);+ if (!entry) return;+ entries.delete(preparedId);+ await fs.rm(entry.directory, { recursive: true, force: true }).catch(() => undefined);+}diff --git a/apps/desktop/src/main/plugin-contributions/registerIpc.ts b/apps/desktop/src/main/plugin-contributions/registerIpc.tsnew file mode 100644index 0000000000..f43036ef4c--- /dev/null+++ b/apps/desktop/src/main/plugin-contributions/registerIpc.ts@@ -0,0 +1,95 @@+import { ipcMain } from 'electron';+import { z } from 'zod';+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';+import { throwIpcError } from '../utils/ipcValidate.js';+import * as host from './host.js';+import { reviewUpdates, markReviewRead } from './reviewUpdates.js';++let registered = false;+const id = z.string().min(1).max(256);+export function registerPluginContributionsIpc(): void {+ if (registered) return;+ registered = true;+ const handle = <S extends z.ZodTypeAny>(+ name: string,+ schema: S,+ action: (input: z.infer<S>) => unknown,+ ) => {+ ipcMain.handle(`plugin-contributions:${name}`, async (event, raw: unknown) => {+ assertTrustedAppRendererEvent(event);+ const parsed = schema.safeParse(raw);+ if (!parsed.success) throwIpcError('INVALID_PARAMS', 'Invalid contribution request');+ try {+ return await action(parsed.data);+ } catch (error) {+ host.mapContributionError(error);+ }+ });+ };+ handle(+ 'prepare',+ z+ .object({+ instanceId: id,+ expected: z+ .object({ directory: z.string().min(1).max(4096), approvalToken: id })+ .strict()+ .optional(),+ })+ .strict(),+ ({ instanceId, expected }) => host.prepareContribution(instanceId, 'manual', expected),+ );+ handle('submit', id, host.submitContribution);+ handle('resume', id, host.resumeContribution);+ handle('status', id, host.contributionTransferStatus);+ handle('cancel', id, host.cancelContribution);+ handle(+ 'cancel-review',+ z+ .object({+ pluginId: id,+ release: z+ .object({+ releaseId: id,+ sha256: z.string().regex(/^[a-f0-9]{64}$/),+ revision: z.string().datetime(),+ })+ .strict(),+ })+ .strict(),+ ({ pluginId, release }) => host.cancelPluginReview(pluginId, release),+ );+ handle('set-anonymity', z.object({ pluginId: id, anonymous: z.boolean() }).strict(),+ ({ pluginId, anonymous }) => host.setPluginAnonymity(pluginId, anonymous));+ handle('discard', id, host.discardContribution);+ handle('transfers', z.undefined(), host.listContributionTransfers);+ handle('review-updates', z.undefined(), reviewUpdates);+ handle('mark-review-read', z.object({ pluginId: id, key: z.string().min(1).max(1024) }).strict(),+ ({ pluginId, key }) => markReviewRead(pluginId, key));+ handle(+ 'list',+ z+ .object({+ query: z.string().max(200),+ filter: z.enum(['all', 'pending', 'needs_action', 'published']),+ cursor: z.string().max(4096).optional(),+ })+ .strict(),+ host.listMyPlugins,+ );+ handle(+ 'submission',+ z.object({ pluginId: id, submissionId: id }).strict(),+ ({ pluginId, submissionId }) => host.myPluginSubmission(pluginId, submissionId),+ );+ handle(+ 'releases',+ z.object({ pluginId: id, cursor: z.string().max(4096).optional() }).strict(),+ ({ pluginId, cursor }) => host.myPluginReleases(pluginId, cursor),+ );+ handle(+ 'detail',+ z.object({ pluginId: id, cursor: z.string().max(4096).optional() }).strict(),+ ({ pluginId, cursor }) => host.myPluginDetail(pluginId, cursor),+ );+}diff --git a/apps/desktop/src/main/plugin-contributions/reviewUpdates.ts b/apps/desktop/src/main/plugin-contributions/reviewUpdates.tsnew file mode 100644index 0000000000..51cc373736--- /dev/null+++ b/apps/desktop/src/main/plugin-contributions/reviewUpdates.ts@@ -0,0 +1,102 @@+import crypto from 'node:crypto';+import fs from 'node:fs';+import path from 'node:path';+import { z } from 'zod';+import type { AuthorHistoryEvent, MyPluginSummary, SubmissionView } from '../../shared/pluginContributionContract.js';+import type { PluginReviewUpdate } from '../../shared/pluginContributions.js';+import { ownerScopedUserDataPath } from '../appSessionState.js';+import { isPassiveSharedUserDataInstance } from '../authManager.js';+import { throwIpcError } from '../utils/ipcValidate.js';+import { ContributionApi } from './api.js';+import { assertContributionOwner, contributionAccountKey } from './prepared.js';++type Decision = Omit<PluginReviewUpdate, 'unread'>;+let cache: { owner: string; entries: Map<string, { fingerprint: string; decision: Decision | null }> } | null = null;+let inFlight: { owner: string; task: Promise<PluginReviewUpdate[]> } | null = null;+const readSchema = z.object({ version: z.literal(1), read: z.record(z.string(), z.string()) });++function readFile(): string {+ const account = crypto.createHash('sha256').update(contributionAccountKey()).digest('hex');+ return ownerScopedUserDataPath('plugin-contributions', `review-read-${account}.v1.json`);+}+function readMarkers(file: string): Record<string, string> {+ try { return readSchema.parse(JSON.parse(fs.readFileSync(file, 'utf8'))).read; }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT' || error instanceof SyntaxError || error instanceof z.ZodError) return {};+ throw error;+ }+}+function decision(pluginId: string, value: SubmissionView | AuthorHistoryEvent): Decision | null {+ const status = 'reviewStatus' in value ? value.reviewStatus : value.type;+ const at = 'decidedAt' in value ? value.decidedAt : value.at;+ const revision = value.revision;+ if ((status !== 'approved' && status !== 'rejected') || !at || !revision || !value.version) return null;+ const key = JSON.stringify([revision.releaseId, revision.sha256, revision.displayUpdatedAt, status, at]);+ return { pluginId, key, releaseId: revision.releaseId, version: value.version, sha256: revision.sha256,+ revision: revision.displayUpdatedAt, status, decidedAt: at };+}+async function latestDecision(api: ContributionApi, plugin: MyPluginSummary): Promise<Decision | null> {+ const current = plugin.latestSubmission && decision(plugin.pluginId, plugin.latestSubmission);+ if (current) return current;+ // A newer pending/cancelled version must not hide an older unread decision.+ const detail = await api.detail(plugin.pluginId);+ let history = detail.history;+ for (;;) {+ for (const event of history.events) {+ const result = decision(plugin.pluginId, event);+ if (result) return result;+ }+ if (!history.nextCursor) return null;+ history = await api.history(plugin.pluginId, history.nextCursor);+ }+}+async function refresh(api: ContributionApi): Promise<PluginReviewUpdate[]> {+ const owner = api.owner;+ if (cache?.owner !== owner) cache = { owner, entries: new Map() };+ const held = cache;+ const visible = new Set<string>();+ let cursor: string | undefined;+ do {+ const page = await api.list({ query: '', filter: 'all', ...(cursor ? { cursor } : {}) });+ assertContributionOwner(owner);+ for (const plugin of page.plugins) {+ visible.add(plugin.pluginId);+ const fingerprint = JSON.stringify([plugin.updatedAt, plugin.latestSubmission]);+ if (held.entries.get(plugin.pluginId)?.fingerprint !== fingerprint) {+ const result = await latestDecision(api, plugin);+ assertContributionOwner(owner);+ held.entries.set(plugin.pluginId, { fingerprint, decision: result });+ }+ }+ cursor = page.nextCursor ?? undefined;+ } while (cursor);+ assertContributionOwner(owner);+ for (const pluginId of held.entries.keys()) if (!visible.has(pluginId)) held.entries.delete(pluginId);+ const markers = readMarkers(readFile());+ assertContributionOwner(owner);+ return [...held.entries.values()].flatMap(({ decision: value }) => value+ ? [{ ...value, unread: markers[value.pluginId] !== value.key }] : []);+}++export async function reviewUpdates(): Promise<PluginReviewUpdate[]> {+ const api = new ContributionApi();+ if (inFlight?.owner === api.owner) return inFlight.task;+ const task = refresh(api);+ inFlight = { owner: api.owner, task };+ try { return await task; }+ finally { if (inFlight?.task === task) inFlight = null; }+}+export function markReviewRead(pluginId: string, key: string): void {+ const api = new ContributionApi();+ assertContributionOwner(api.owner);+ if (isPassiveSharedUserDataInstance()) throwIpcError('PRECONDITION_FAILED', 'Use the active Cindy instance');+ if (cache?.owner !== api.owner || cache.entries.get(pluginId)?.decision?.key !== key)+ throwIpcError('PRECONDITION_FAILED', 'Refresh the review result before marking it read');+ const file = readFile();+ const read = readMarkers(file);+ read[pluginId] = key;+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const temporary = `${file}.${crypto.randomUUID()}.tmp`;+ fs.writeFileSync(temporary, JSON.stringify({ version: 1, read }), { mode: 0o600 });+ fs.renameSync(temporary, file);+}diff --git a/apps/desktop/src/main/plugin-market/__tests__/download.test.ts b/apps/desktop/src/main/plugin-market/__tests__/download.test.tsindex 12c7886fc2..c2bf884a34 100644--- a/apps/desktop/src/main/plugin-market/__tests__/download.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/download.test.ts@@ -3,15 +3,19 @@ import fs from 'node:fs';import os from 'node:os';import path from 'node:path';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES } from '@cindy/plugin-protocol';const fetchMock = vi.hoisted(() => vi.fn());+const host = vi.hoisted(() => ({ packaged: false, endpoint: 'http://127.0.0.1:43340' }));+vi.mock('electron', () => ({ app: { get isPackaged() { return host.packaged; } } }));+vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => host.endpoint }));vi.mock('../../downloader/http', () => ({ requestResponse: fetchMock }));import { downloadVerifiedPlugin } from '../download';const files: string[] = [];+beforeEach(() => { host.packaged = false; host.endpoint = 'http://127.0.0.1:43340'; });afterEach(() => {fetchMock.mockReset();@@ -32,6 +36,26 @@ function expected(bytes: Buffer) {}describe('downloadVerifiedPlugin', () => {+ it('downloads the exact local development object and still verifies its bytes', async () => {+ const bytes = Buffer.from('local fixture');+ fetchMock.mockResolvedValue(new Response(bytes));+ const file = target();+ await downloadVerifiedPlugin('http://127.0.0.1:43340/dev-local/object?key=fixture', expected(bytes), file);+ expect(fs.readFileSync(file).equals(bytes)).toBe(true);+ });+ it.each(['packaged', 'remote', 'other-port', 'other-path'] as const)('rejects %s HTTP before making a request', async boundary => {+ host.packaged = boundary === 'packaged';+ const url = boundary === 'remote' ? 'http://remote.example/dev-local/object' : boundary === 'other-port'+ ? 'http://127.0.0.1:43341/dev-local/object' : boundary === 'other-path' ? 'http://127.0.0.1:43340/private' : 'http://127.0.0.1:43340/dev-local/object';+ await expect(downloadVerifiedPlugin(url, expected(Buffer.from('fixture')), target())).rejects.toMatchObject({ code: 'GHOST_DOWNLOAD_FAILED' });+ expect(fetchMock).not.toHaveBeenCalled();+ });+ it('never follows a redirect from an allowed local object', async () => {+ fetchMock.mockResolvedValue(new Response(null, { status: 302, headers: { location: 'http://127.0.0.1:43341/dev-local/object' } }));+ await expect(downloadVerifiedPlugin('http://127.0.0.1:43340/dev-local/object', expected(Buffer.from('fixture')), target())).rejects.toMatchObject({ code: 'GHOST_DOWNLOAD_FAILED' });+ expect(fetchMock).toHaveBeenCalledOnce();+ });+it('accepts a package above the former 8 MiB market limit', async () => {const bytes = Buffer.alloc(9 * 1024 * 1024, 7);fetchMock.mockResolvedValue(new Response(bytes));diff --git a/apps/desktop/src/main/plugin-market/__tests__/objectUrlPolicy.test.ts b/apps/desktop/src/main/plugin-market/__tests__/objectUrlPolicy.test.tsnew file mode 100644index 0000000000..6eb8f8408f--- /dev/null+++ b/apps/desktop/src/main/plugin-market/__tests__/objectUrlPolicy.test.ts@@ -0,0 +1,27 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+const host = vi.hoisted(() => ({ packaged: false, endpoint: 'http://127.0.0.1:43340' }));+vi.mock('electron', () => ({ app: { get isPackaged() { return host.packaged; } } }));+vi.mock('../../clientEndpointsService.js', () => ({ getClientEndpoint: () => host.endpoint }));+import { pluginObjectUrlAllowed, pluginObjectUrlOptions } from '../objectUrlPolicy';++beforeEach(() => { host.packaged = false; host.endpoint = 'http://127.0.0.1:43340'; });+describe('Host delivery object policy', () => {+ it('enables HTTP only for an unpackaged Host explicitly configured with the same loopback origin', () => {+ expect(pluginObjectUrlAllowed('http://127.0.0.1:43340/dev-local/object?key=fixture', pluginObjectUrlOptions())).toBe(true);+ expect(pluginObjectUrlAllowed('http://127.0.0.1:43341/dev-local/object', pluginObjectUrlOptions())).toBe(false);+ expect(pluginObjectUrlAllowed('http://remote.example/dev-local/object', pluginObjectUrlOptions())).toBe(false);+ });+ it('keeps a packaged Host HTTPS-only even with loopback configuration', () => {+ host.packaged = true;+ expect(pluginObjectUrlOptions()).toBeUndefined();+ expect(pluginObjectUrlAllowed('http://127.0.0.1:43340/dev-local/object', pluginObjectUrlOptions())).toBe(false);+ expect(pluginObjectUrlAllowed('https://downloads.example/package', pluginObjectUrlOptions())).toBe(true);+ });+ it.each(['https://plugins.example', 'http://plugins.example', 'invalid', 'http://[email protected]:43340'])(+ 'does not grant local HTTP from a different endpoint configuration: %s', endpoint => {+ host.endpoint = endpoint;+ expect(pluginObjectUrlOptions()).toBeUndefined();+ expect(pluginObjectUrlAllowed('http://127.0.0.1:43340/dev-local/object', pluginObjectUrlOptions())).toBe(false);+ },+ );+});diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 56e7237c0f..48cb8e472c 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -589,6 +589,34 @@ function sameReleaseRecoveryHarness(return { ...h, item, evidence, dir };}+describe('workflow display author projection', () => {+ it.each(['verified', 'missing', 'mismatch'] as const)('binds older-version attribution only to verified installed package evidence (%s)', async state => {+ const h = sameReleaseRecoveryHarness('market', 'legacy');+ h.evidence.packageSha256 = h.item.currentRelease.sha256;+ h.item.scope = 'public'; h.item.organizationId = null; h.item.namespace = null;+ runtime.ghosts[0] = { ...runtime.ghosts[0], namespace: null,+ approval: { state: 'approved', revision: 'public-fixture' } };+ h.ledger.upsertInstallation(recordForTest(h.item, {+ namespace: null, manifestDigest: ghostManifestDigest(h.evidence.approvedManifest),+ }));+ if (state === 'missing') runtime.approvedInstallEvidence.mockReturnValue(null);+ if (state === 'mismatch') h.evidence.packageSha256 = 'c'.repeat(64);+ h.item.displayAuthor = 'Current name';+ h.item.currentRelease = { ...h.item.currentRelease, id: 'release-2', version: '2.0.0', sha256: 'b'.repeat(64) };+ const item = (await h.service.snapshot({ discoveryOnly: true })).items[0];+ expect(item.installState).toBe('update-available');+ expect(item.installedAuthor).toBe(state === 'verified' ? 'Current name' : undefined);+ });+ it.each([+ { displayAuthor: '名'.repeat(100), expected: '名'.repeat(100) },+ { displayAuthor: null, expected: null },+ { displayAuthor: undefined, expected: 'Cindy' },+ ])('uses the workflow name and preserves old-server compatibility (%j)', async ({ displayAuthor, expected }) => {+ const h = harness([summary({ displayAuthor })]);+ expect((await h.service.snapshot({ discoveryOnly: true })).items[0].author).toBe(expected);+ });+});+describe('same-release legacy organization source recovery', () => {it.each([{ source: 'legacy-adopted', layout: 'legacy', hasPackage: false },diff --git a/apps/desktop/src/main/plugin-market/api.ts b/apps/desktop/src/main/plugin-market/api.tsindex 68c2c287d9..489687dd3f 100644--- a/apps/desktop/src/main/plugin-market/api.ts+++ b/apps/desktop/src/main/plugin-market/api.ts@@ -17,6 +17,7 @@ import {import { getClientEndpoint } from '../clientEndpointsService.js';import { createLogger } from '../logger.js';import { serverApiFetch, type ApiFetchOptions } from '../serverApiClient.js';+import { pluginObjectUrlOptions } from './objectUrlPolicy.js';const log = createLogger('plugin-market-api');const PLUGIN_MARKET_API_TIMEOUT_MS = 15_000;@@ -113,6 +114,7 @@ export class PluginMarketApi {`/api/plugins?${search.toString()}`,this.requestOptions(),),+ pluginObjectUrlOptions(),);for (const plugin of response.plugins) {if (seen.has(plugin.id)) continue;@@ -182,6 +184,7 @@ export class PluginMarketApi {`/api/plugins/${encodeURIComponent(pluginId)}`,this.requestOptions(),),+ pluginObjectUrlOptions(),).plugin;}@@ -194,6 +197,7 @@ export class PluginMarketApi {`/api/plugins/${encodeURIComponent(pluginId)}/releases/${encodeURIComponent(releaseId)}/download`,this.requestOptions(),),+ pluginObjectUrlOptions(),);}diff --git a/apps/desktop/src/main/plugin-market/download.ts b/apps/desktop/src/main/plugin-market/download.tsindex d32c7afa09..e741badbcc 100644--- a/apps/desktop/src/main/plugin-market/download.ts+++ b/apps/desktop/src/main/plugin-market/download.ts@@ -1,6 +1,7 @@import { PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES } from '@cindy/plugin-protocol';import { download, DownloadError } from '../downloader/index.js';import { createIpcError } from '../../shared/ipc-errors.js';+import { pluginObjectUrlAllowed, pluginObjectUrlOptions } from './objectUrlPolicy.js';/** Plugin policy only; transport, timeouts, byte limits and hashing are shared. */export async function downloadVerifiedPlugin(@@ -17,8 +18,10 @@ export async function downloadVerifiedPlugin(throw createIpcError('GHOST_FILE_INVALID', 'Plugin Release size or SHA-256 is invalid');}try {+ const urlOptions = pluginObjectUrlOptions();await download({url,+ isUrlAllowed: (candidate) => pluginObjectUrlAllowed(candidate, urlOptions),targetPath,sha256: expected.sha256,expectedSize: expected.sizeBytes,diff --git a/apps/desktop/src/main/plugin-market/objectUrlPolicy.ts b/apps/desktop/src/main/plugin-market/objectUrlPolicy.tsnew file mode 100644index 0000000000..91d138460f--- /dev/null+++ b/apps/desktop/src/main/plugin-market/objectUrlPolicy.ts@@ -0,0 +1,19 @@+import { app } from 'electron';+import { parsePluginObjectUrl, type PluginObjectUrlOptions } from '@cindy/plugin-protocol';+import { getClientEndpoint } from '../clientEndpointsService.js';++/** An explicit local Plugin endpoint is the sole HTTP delivery exception in an unpackaged Host. */+export function pluginObjectUrlOptions(): PluginObjectUrlOptions | undefined {+ if (app.isPackaged !== false) return undefined;+ try {+ const endpoint = new URL(getClientEndpoint('pluginApiBaseUrl'));+ if (endpoint.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(endpoint.hostname) &&+ !endpoint.username && !endpoint.password && !endpoint.hash)+ return { developmentObjectOrigin: endpoint.origin };+ } catch { /* Missing or invalid endpoint never enables HTTP. */ }+ return undefined;+}++export function pluginObjectUrlAllowed(url: string, options: PluginObjectUrlOptions | undefined): boolean {+ try { parsePluginObjectUrl(url, 'download.url', options); return true; } catch { return false; }+}diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex a9982cd4b5..ed413339d5 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -2640,7 +2640,11 @@ export class PluginMarketService {plugin: VisiblePluginSummary,local = this.localInstallSnapshot(),): PluginMarketItem {- const { target, ghost, matchesUpdateRoute, installState } = this.serverMarketBinding(plugin, local);+ const { target, ghost, record, matchesUpdateRoute, installState } = this.serverMarketBinding(plugin, local);+ const evidence = plugin.scope === 'public' && matchesUpdateRoute && ghost?.approval.state === 'approved'+ ? getGhostManager().approvedInstallEvidence(installedGhostPhysicalRelId(ghost))+ : null;+ const author = plugin.displayAuthor === undefined ? plugin.author : plugin.displayAuthor;return {...(plugin.usageStatistics ? { usageStatistics: plugin.usageStatistics } : {}),...(plugin.downloadStatistics ? { downloadStatistics: plugin.downloadStatistics } : {}),@@ -2649,7 +2653,11 @@ export class PluginMarketService {...deliveryNamespaceFields(target),name: plugin.name,description: plugin.description,- author: plugin.author,+ author,+ ...(plugin.scope === 'public' && plugin.publisherKind !== undefined ? { publisherKind: plugin.publisherKind } : {}),+ ...(evidence?.packageSha256 && evidence.packageSha256 === record?.sha256+ ? { installedAuthor: author }+ : {}),scope: plugin.scope,organizationId: plugin.organizationId,defaultInstall: plugin.defaultInstall,diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex df811c2a28..a7c64df456 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1601,6 +1601,23 @@ contextBridge.exposeInMainWorld('electronAPI', {gitPreflight: (): Promise<{ ok: boolean; version: string | null }> =>ipcRenderer.invoke('plugin-market:git-preflight'),},+ pluginContributions: {+ reviewUpdates: () => ipcRenderer.invoke('plugin-contributions:review-updates'),+ markReviewRead: (pluginId: string, key: string) => ipcRenderer.invoke('plugin-contributions:mark-review-read', { pluginId, key }),+ prepare: (instanceId: string, expected?: import('../shared/pluginContributions').ContributionInstallationBinding) => ipcRenderer.invoke('plugin-contributions:prepare', { instanceId, expected }),+ submit: (preparedId: string) => ipcRenderer.invoke('plugin-contributions:submit', preparedId),+ resume: (localId: string) => ipcRenderer.invoke('plugin-contributions:resume', localId),+ status: (localId: string) => ipcRenderer.invoke('plugin-contributions:status', localId),+ cancel: (localId: string) => ipcRenderer.invoke('plugin-contributions:cancel', localId),+ cancelReview: (pluginId: string, release: { releaseId: string; sha256: string; revision: string }) => ipcRenderer.invoke('plugin-contributions:cancel-review', { pluginId, release }),+ setAnonymity: (pluginId: string, anonymous: boolean) => ipcRenderer.invoke('plugin-contributions:set-anonymity', { pluginId, anonymous }),+ discard: (preparedId: string) => ipcRenderer.invoke('plugin-contributions:discard', preparedId),+ transfers: () => ipcRenderer.invoke('plugin-contributions:transfers'),+ list: (input: { query: string; filter: import('../shared/pluginContributions').MyPluginFilter; cursor?: string }) => ipcRenderer.invoke('plugin-contributions:list', input),+ submission: (pluginId: string, submissionId: string) => ipcRenderer.invoke('plugin-contributions:submission', { pluginId, submissionId }),+ releases: (pluginId: string, cursor?: string) => ipcRenderer.invoke('plugin-contributions:releases', { pluginId, ...(cursor ? { cursor } : {}) }),+ detail: (pluginId: string, cursor?: string) => ipcRenderer.invoke('plugin-contributions:detail', { pluginId, ...(cursor ? { cursor } : {}) }),+ } satisfies import('../shared/pluginContributions').PluginContributionsApi,pluginPublisher: {start: (filePath: string): Promise<{ transferId: string; uploadId: string | null }> =>ipcRenderer.invoke('plugin-publisher:start', filePath),diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsxindex 3c1feeaa70..4f4c960364 100644--- a/apps/desktop/src/renderer/App.tsx+++ b/apps/desktop/src/renderer/App.tsx@@ -13,6 +13,7 @@ import { WallpaperSettingsProvider } from '@/hooks/useWallpaperSettings';import { FontSettingsProvider } from '@/hooks/useFontSettings';import { LocaleProvider } from '@/hooks/useLocale';import { AuthProvider, useAuth } from '@/contexts/AuthContext';+import { PluginReviewUpdatesProvider } from '@/contexts/PluginReviewUpdatesContext';import { AppShellCoverProvider, useAppShellCover } from '@/contexts/AppShellCoverContext';import { LoginHandoffProvider } from '@/contexts/LoginHandoffContext';import { EnvCheckProvider, EnvCheckGuard } from '@/contexts/EnvCheckContext';@@ -437,6 +438,7 @@ export function App() {<ConfirmDialogProvider><EnvCheckProvider><AuthProvider>+ <PluginReviewUpdatesProvider><AppShellCoverProvider><WorktreeProvider><PrRefsProvider>@@ -475,6 +477,7 @@ export function App() {</PrRefsProvider></WorktreeProvider></AppShellCoverProvider>+ </PluginReviewUpdatesProvider></AuthProvider></EnvCheckProvider></ConfirmDialogProvider>diff --git a/apps/desktop/src/renderer/components/auth/GuestRoute.tsx b/apps/desktop/src/renderer/components/auth/GuestRoute.tsxindex 409755745e..8cc38ee6d0 100644--- a/apps/desktop/src/renderer/components/auth/GuestRoute.tsx+++ b/apps/desktop/src/renderer/components/auth/GuestRoute.tsx@@ -1,11 +1,14 @@-import { Navigate, Outlet } from 'react-router-dom';+import { Navigate, Outlet, useLocation } from 'react-router-dom';import { useAuth } from '@/contexts/AuthContext';export function GuestRoute() {+ const location = useLocation();+ const returnTo = (location.state as { returnTo?: unknown } | null)?.returnTo;+ const destination = typeof returnTo === 'string' && returnTo.startsWith('/') && !returnTo.startsWith('//') && !returnTo.startsWith('/login') ? returnTo : '/';const { mode, isInitializing } = useAuth();if (isInitializing) return null;- if (mode === 'cloud' || mode === 'local') return <Navigate to="/" replace />;+ if (mode === 'cloud' || mode === 'local') return <Navigate to={destination} replace />;return <Outlet />;}diff --git a/apps/desktop/src/renderer/components/auth/__tests__/GuestRoute.test.tsx b/apps/desktop/src/renderer/components/auth/__tests__/GuestRoute.test.tsxindex d1c74b2db4..9bcdec5161 100644--- a/apps/desktop/src/renderer/components/auth/__tests__/GuestRoute.test.tsx+++ b/apps/desktop/src/renderer/components/auth/__tests__/GuestRoute.test.tsx@@ -17,11 +17,12 @@ vi.mock('@/contexts/AuthContext', () => ({import { GuestRoute } from '../GuestRoute';-function renderAt(path: string) {+function renderAt(path: string, state?: { returnTo: string }) {return render(- <MemoryRouter initialEntries={[path]}>+ <MemoryRouter initialEntries={[{ pathname: path, state }]}><Routes><Route path="/" element={<div data-testid="app-shell" />} />+ <Route path="/plugins" element={<div data-testid="plugins-page" />} /><Route path="/login" element={<GuestRoute />}><Route index element={<div data-testid="login-page" />} /></Route>@@ -64,4 +65,20 @@ describe('GuestRoute', () => {expect(screen.getByTestId('app-shell')).toBeTruthy();expect(screen.queryByTestId('login-page')).toBeNull();});++ it('restores the internal plugin destination after signing in', () => {+ authState.current = { mode: 'cloud', isInitializing: false };+ renderAt('/login', { returnTo: '/plugins?contribution=hello' });+ expect(screen.getByTestId('plugins-page')).toBeTruthy();+ expect(screen.queryByTestId('login-page')).toBeNull();+ });++ it.each(['https://example.com', '//example.com', '/login', '/login?returnTo=/plugins'])(+ 'rejects an external destination or login loop: %s', (returnTo) => {+ authState.current = { mode: 'cloud', isInitializing: false };+ renderAt('/login', { returnTo });+ expect(screen.getByTestId('app-shell')).toBeTruthy();+ expect(screen.queryByTestId('login-page')).toBeNull();+ },+ );});diff --git a/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx b/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsxindex 25045728ff..516af4d1d3 100644--- a/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx+++ b/apps/desktop/src/renderer/components/sidebar/SidebarTopNav.tsx@@ -37,6 +37,7 @@ import { useTranslation } from 'react-i18next';import { cn } from '@/lib/utils';import { NavigationCountBadge } from '@/components/sidebar/NavigationCountBadge';import { useAuth } from '@/contexts/AuthContext';+import { usePluginReviewUpdates } from '@/contexts/PluginReviewUpdatesContext';import { AttentionDot, type DotTone } from '@/components/sidebar/AttentionDot';import { useAnyGhostUnread } from '@/cindy-brain/ghostUnreadStore';import { useGhostMainViews, type GhostMainViewItem } from '@/cindy-brain/ghostMainViews';@@ -126,6 +127,7 @@ function useSidebarNavigationActions(// 呼吸留给单条卡片;见 AttentionDot 头部的形态规范)。const hasRetirementUnread = useInstalledGhosts().some((ghost) => ghost.retirement?.unread);const hasGhostUnread = useAnyGhostUnread() || hasRetirementUnread;+ const reviewUnread = usePluginReviewUpdates().updates.filter(item => item.unread);return {automations: {label: t('ccAgent.layout.automations'),@@ -139,8 +141,8 @@ function useSidebarNavigationActions(icon: SIDEBAR_NAVIGATION_ITEM_ICONS.plugins,onSelect: () => navigateToView('plugins'),active: activeKey === 'plugins',- showDot: hasGhostUnread,- dotTone: hasRetirementUnread ? 'awaiting' : 'done',+ showDot: hasGhostUnread || reviewUnread.length > 0,+ dotTone: reviewUnread.some(item => item.status === 'rejected') ? 'error' : hasRetirementUnread ? 'awaiting' : 'done',},search: {label: t('sidebar.navigation.items.search'),diff --git a/apps/desktop/src/renderer/contexts/PluginReviewUpdatesContext.tsx b/apps/desktop/src/renderer/contexts/PluginReviewUpdatesContext.tsxnew file mode 100644index 0000000000..35343c9be7--- /dev/null+++ b/apps/desktop/src/renderer/contexts/PluginReviewUpdatesContext.tsx@@ -0,0 +1,81 @@+import { createContext, useCallback, useContext, useEffect, useRef, useState, type ReactNode } from 'react';+import type { PluginReviewUpdate } from '../../shared/pluginContributions';+import { useAuth } from './AuthContext';++const empty: PluginReviewUpdate[] = [];+const PluginReviewUpdatesContext = createContext<{+ updates: PluginReviewUpdate[];+ refresh: () => Promise<void>;+ markRead: (pluginId: string, key: string) => Promise<void>;+}>({+ updates: empty,+ refresh: async () => {},+ markRead: async () => {},+});+export const usePluginReviewUpdates = () => useContext(PluginReviewUpdatesContext);++/** One foreground reader for the app; reading a list never acknowledges a result. */+export function PluginReviewUpdatesProvider({ children }: { children: ReactNode }) {+ const { dataOwnerId, dataOwnerGeneration, user, mode } = useAuth();+ const owner = JSON.stringify([dataOwnerId, dataOwnerGeneration, user?.id, mode]);+ const personal = mode === 'cloud' && user?.membershipKind === 'personal';+ const current = useRef(owner);+ current.current = owner;+ const [snapshot, setSnapshot] = useState({ owner, updates: empty });+ const lifecycle = useRef(0);+ const pending = useRef<{ owner: string; task: Promise<void> } | null>(null);+ const marking = useRef(new Set<string>());+ const acknowledged = useRef({ owner, keys: new Set<string>() });+ const refresh = useCallback(async () => {+ if (!personal || document.visibilityState !== 'visible') return;+ if (pending.current?.owner === owner) return pending.current.task;+ const generation = lifecycle.current;+ const task = (async () => {+ try {+ const updates = await window.electronAPI.pluginContributions.reviewUpdates();+ if (current.current !== owner || lifecycle.current !== generation) return;+ setSnapshot({ owner, updates: updates.map(item => acknowledged.current.owner === owner && acknowledged.current.keys.has(item.key)+ ? { ...item, unread: false } : item) });+ } catch { /* Preserve an existing unread result during an offline interval. */ }+ })();+ pending.current = { owner, task };+ try { await task; }+ finally { if (pending.current?.task === task) pending.current = null; }+ }, [owner, personal]);+ const markRead = useCallback(async (pluginId: string, key: string) => {+ const request = JSON.stringify([owner, pluginId, key]);+ if (!personal || marking.current.has(request)) return;+ marking.current.add(request);+ const generation = lifecycle.current;+ try {+ await window.electronAPI.pluginContributions.markReviewRead(pluginId, key);+ if (current.current !== owner || lifecycle.current !== generation) return;+ if (acknowledged.current.owner !== owner) acknowledged.current = { owner, keys: new Set() };+ acknowledged.current.keys.add(key);+ setSnapshot(previous => previous.owner !== owner ? previous : {+ owner, updates: previous.updates.map(item => item.pluginId === pluginId && item.key === key ? { ...item, unread: false } : item),+ });+ } catch { /* A failed read receipt must leave the dot visible. */ }+ finally { marking.current.delete(request); }+ }, [owner, personal]);+ useEffect(() => {+ lifecycle.current++;+ pending.current = null;+ void refresh();+ const sync = () => { void refresh(); };+ const timer = window.setInterval(sync, 60_000);+ window.addEventListener('focus', sync);+ window.addEventListener('online', sync);+ document.addEventListener('visibilitychange', sync);+ return () => {+ lifecycle.current++;+ window.clearInterval(timer);+ window.removeEventListener('focus', sync);+ window.removeEventListener('online', sync);+ document.removeEventListener('visibilitychange', sync);+ };+ }, [refresh]);+ return <PluginReviewUpdatesContext.Provider value={{ updates: personal && snapshot.owner === owner ? snapshot.updates : empty, refresh, markRead }}>+ {children}+ </PluginReviewUpdatesContext.Provider>;+}diff --git a/apps/desktop/src/renderer/contexts/__tests__/PluginReviewUpdatesContext.test.tsx b/apps/desktop/src/renderer/contexts/__tests__/PluginReviewUpdatesContext.test.tsxnew file mode 100644index 0000000000..235535ad29--- /dev/null+++ b/apps/desktop/src/renderer/contexts/__tests__/PluginReviewUpdatesContext.test.tsx@@ -0,0 +1,78 @@+/** @vitest-environment jsdom */+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { PluginReviewUpdate } from '../../../shared/pluginContributions';+import { PluginReviewUpdatesProvider, usePluginReviewUpdates } from '../PluginReviewUpdatesContext';++const harness = vi.hoisted(() => ({ owner: 'A', generation: 1, read: vi.fn(), mark: vi.fn() }));+vi.mock('../AuthContext', () => ({ useAuth: () => ({+ dataOwnerId: harness.owner, dataOwnerGeneration: harness.generation,+ user: { id: harness.owner, membershipKind: 'personal' }, mode: 'cloud',+}) }));+const update: PluginReviewUpdate = { pluginId: 'plugin', key: 'approval', releaseId: 'release',+ version: '1.0.0', sha256: 'a'.repeat(64), revision: 'revision', status: 'approved', decidedAt: 'time', unread: true };+function Probe() {+ const { updates, refresh, markRead } = usePluginReviewUpdates();+ return <><output>{updates.filter(item => item.unread).map(item => item.key).join(',')}</output>+ <button onClick={() => void refresh()}>refresh</button>+ <button onClick={() => void markRead('plugin', 'approval')}>read result</button></>;+}+const app = () => <PluginReviewUpdatesProvider><Probe /></PluginReviewUpdatesProvider>;+beforeEach(() => {+ harness.owner = 'A'; harness.generation = 1;+ harness.read.mockReset().mockResolvedValue([update]); harness.mark.mockReset().mockResolvedValue(undefined);+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { pluginContributions: { reviewUpdates: harness.read, markReviewRead: harness.mark } } });+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');+});+afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.useRealTimers(); });+describe('in-app review result indicators', () => {+ it('preserves unread results offline and after failed acknowledgement, then only clears the exact result', async () => {+ render(app());+ await waitFor(() => expect(screen.getByRole('status').textContent).toBe('approval'));+ expect(harness.mark).not.toHaveBeenCalled();+ harness.read.mockRejectedValueOnce(new Error('offline'));+ fireEvent.click(screen.getByText('refresh'));+ await act(async () => {});+ expect(screen.getByRole('status').textContent).toBe('approval');+ harness.mark.mockRejectedValueOnce(new Error('disk unavailable'));+ fireEvent.click(screen.getByText('read result'));+ await act(async () => {});+ expect(screen.getByRole('status').textContent).toBe('approval');+ fireEvent.click(screen.getByText('read result'));+ await waitFor(() => expect(screen.getByRole('status').textContent).toBe(''));+ // A poll started before/after acknowledgement must not resurrect that same decision.+ fireEvent.click(screen.getByText('refresh'));+ await act(async () => {});+ expect(screen.getByRole('status').textContent).toBe('');+ harness.read.mockResolvedValueOnce([{ ...update, key: 'rejection', status: 'rejected' }]);+ fireEvent.click(screen.getByText('refresh'));+ await waitFor(() => expect(screen.getByRole('status').textContent).toBe('rejection'));+ });+ it('hides previous-account results immediately and ignores its late response', async () => {+ let finish!: (value: PluginReviewUpdate[]) => void;+ harness.read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ const view = render(app());+ harness.owner = 'B'; harness.generation++;+ harness.read.mockResolvedValueOnce([{ ...update, key: 'B-result' }]);+ view.rerender(app());+ await waitFor(() => expect(screen.getByRole('status').textContent).toBe('B-result'));+ await act(async () => { finish([update]); });+ expect(screen.getByRole('status').textContent).toBe('B-result');+ });+ it('polls while foregrounded and refreshes when returning online without acknowledging a list', async () => {+ vi.useFakeTimers();+ const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');+ render(app());+ await act(async () => {});+ expect(harness.read).toHaveBeenCalledTimes(1);+ visibility.mockReturnValue('hidden');+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });+ expect(harness.read).toHaveBeenCalledTimes(1);+ visibility.mockReturnValue('visible');+ await act(async () => { window.dispatchEvent(new Event('online')); });+ expect(harness.read).toHaveBeenCalledTimes(2);+ await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });+ expect(harness.read).toHaveBeenCalledTimes(3);+ expect(harness.mark).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex dd512d7ded..35549bbc55 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -1,3 +1,5 @@+import type { PreparedPluginContribution } from '../../../shared/pluginContributions';+import { PluginVersionUpdates } from './PluginVersionUpdates';import { Button } from '@/components/ui/button';import { GithubAccountCard } from '@/features/cc-agent/GithubAccountCard';import { shouldShowOpenPathError } from '../../../shared/openPathResult';@@ -5,7 +7,7 @@ import { shouldShowOpenPathError } from '../../../shared/openPathResult';* Plugin detail presentation for configuration, Tools, permissions, and factual metadata.** Inputs: the renderer-safe Plugin detail model plus the installed Ghost when available.- * Outputs: accessible detail interactions, Host-owned configuration rows, a single-row responsive+ * Outputs: accessible detail interactions, Host-owned configuration rows, a wrapping responsive* action hero with the shared Switch, and the sticky top bar with back and macOS window dragging.* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md*/@@ -89,6 +91,7 @@ interface GhostPluginDetailViewProps {onBack: () => void;usageOwnerKey?: string;confirmClearUsage?: () => Promise<boolean>;+ publishingSection?: ReactNode;onToggle: (enabled: boolean) => void;/** 主动作:面板型「使用」/ 指令或 Host 能力型「对话」;纯工具型不渲染主按钮。 */onUse: () => void;@@ -110,6 +113,13 @@ interface GhostPluginDetailViewProps {onUninstall: () => void;/** 导出 .cindy;当前详情非已装插件(纯市场视图)时缺省,菜单项不渲染。 */onExport?: () => void;+ onContribute?: () => void;+ contributionUpdate?: boolean;+ contributionBusy?: boolean;+ contributionSummary?: string;+ publishingPreview?: PreparedPluginContribution;+ onRefreshPublishing?: () => void;+ contributionUnavailableReason?: string;toggleDisabled: boolean;onIconLoadError?: () => void;}@@ -133,6 +143,7 @@ export function GhostPluginDetailView({panelStatus,enabledOverride,onBack,+ publishingSection,onToggle,onUse,marketItem,@@ -147,12 +158,21 @@ export function GhostPluginDetailView({updateBusy = false,onUninstall,onExport,+ onContribute,+ contributionUpdate = false,+ contributionBusy = false,+ contributionSummary,+ publishingPreview,+ onRefreshPublishing,+ contributionUnavailableReason,toggleDisabled,onIconLoadError,}: GhostPluginDetailViewProps) {const { t } = useTranslation();const { scrolled, onScroll } = usePluginDetailScrolled();const enableSwitchId = useId();+ const contributionNoticeId = useId();+ const publicationBlocked = publishingPreview?.preflight?.actions.canSubmit === false;const [githubConnectionVersion, setGithubConnectionVersion] = useState(0);const [taskApprovalPending, setTaskApprovalPending] = useState(false);// 未批准的安装不可运行;恢复入口与普通停用区分。@@ -209,7 +229,7 @@ export function GhostPluginDetailView({onIconLoadError={onIconLoadError}actions={<div- className="plugin-detail-actions flex shrink-0 flex-nowrap items-center gap-1.5"+ className="plugin-detail-actions flex min-w-0 flex-wrap items-center gap-1.5"style={WINDOW_NO_DRAG_STYLE}>{needsReapproval && !detail.builtin && onReapprove ? (@@ -266,6 +286,19 @@ export function GhostPluginDetailView({)}</Button>) : null}+ {!publicationBlocked && onContribute ? (+ <Button+ variant="secondary"+ size="lg"+ onClick={onContribute}+ loading={contributionBusy}+ disabled={Boolean(contributionUnavailableReason)}+ aria-describedby={contributionNoticeId}+ title={contributionUnavailableReason}+ >+ {publishingPreview ? t('settings.ghosts.contribution.submitVersion', { version: publishingPreview.version }) : t(`settings.ghosts.contribution.${contributionUpdate ? 'submitUpdate' : 'publish'}`)}+ </Button>+ ) : null}{/* 启用开关带明确文字(设计定稿):状态一目了然,点文字同样可切换。 */}<labelhtmlFor={enableSwitchId}@@ -499,6 +532,48 @@ export function GhostPluginDetailView({{!remote ? <GhostLibrarySection ghostId={detail.id} enabled={ghost?.manifest.library === true} /> : null}+ {publishingSection ?? ((onContribute || contributionUnavailableReason || publishingPreview || detail.releaseNotes?.trim()) ? (+ <PluginVersionUpdates key={detail.id}>+ {(onContribute || contributionUnavailableReason) ? (+ <div className="mt-3 space-y-1 text-13 leading-5 text-[var(--text-secondary)]">+ <p id={contributionNoticeId}>+ {contributionUnavailableReason ?? t('settings.ghosts.contribution.publishHint')}+ </p>+ {contributionBusy || contributionSummary ? (+ <p role="status">+ {contributionBusy ? t('settings.ghosts.contribution.preparing') : contributionSummary}+ </p>+ ) : null}+ </div>+ ) : null}++ {publishingPreview ? (+ <section className="space-y-2 text-13 leading-5 text-[var(--text-secondary)]">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h3 className="font-medium text-[var(--text-primary)]">+ {publicationBlocked ? `${t('settings.ghosts.contribution.version')} · ${publishingPreview.version}` : t('settings.ghosts.contribution.publishingVersion', { version: publishingPreview.version })}+ </h3>+ <Button size="sm" variant="secondary" tone="quiet" onClick={onRefreshPublishing}>+ {t('settings.ghosts.contribution.refreshSummary')}+ </Button>+ </div>+ {publishingPreview.releaseNotes?.trim() ? (+ <>+ <h4 className="font-medium text-[var(--text-primary)]">{t('settings.ghosts.contribution.releaseNotes')}</h4>+ <p className="max-h-48 overflow-y-auto whitespace-pre-wrap break-words">{publishingPreview.releaseNotes}</p>+ </>+ ) : null}+ {!publicationBlocked ? <p>{t('settings.ghosts.contribution.versionConsumedHint')}</p> : null}+ </section>+ ) : detail.releaseNotes?.trim() ? (+ <section className="space-y-2">+ <h3 className="text-14 font-medium text-[var(--text-primary)]">{t('settings.ghosts.contribution.releaseNotes')} · {detail.version}</h3>+ <p className="whitespace-pre-wrap break-words text-13 leading-5 text-[var(--text-secondary)]">{detail.releaseNotes}</p>+ </section>+ ) : null}+ </PluginVersionUpdates>+ ) : null)}+<DetailsSection detail={remote ? { ...detail, installDir: null } : detail} panelStatus={panelStatus} /></article></main>diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsxindex 269414952d..cbb41c8f90 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx@@ -1,5 +1,13 @@import { CatalogDeviceScope, type CatalogDeviceControl } from './useCatalogDevice';import { RemotePluginPage } from './RemotePluginPage';+import { PluginVersionFacts } from './PluginVersionFacts';+import type { PreparedPluginContribution } from '../../../shared/pluginContributions';+import { useSignInToCindy } from '@/hooks/useSignInToCindy';+import { rememberContributionIntent, consumeContributionIntent, matchesContributionIntent } from './lib/contributionIntent';+import { MyPluginsPage, contributionErrorKey, type MyPluginsPageCache, type PluginSubmitOptions } from './MyPluginsPage';+import { localPublishingUnavailableKey } from './lib/ghostPluginDetailModel';+import { usePublishingInstallations } from './lib/usePublishingInstallations';+import type { MyPluginDetailView, MyPluginView } from '../../../shared/pluginContributions';import { featureRetirementById } from '../../../shared/featureRetirements';import { RetiredFeatureDetail } from './RetiredFeatureDetail';import { Button } from '@/components/ui/button';@@ -9,6 +17,7 @@ import { Button } from '@/components/ui/button';* Inputs: installed Ghost snapshots and user actions. `embedded` mounts the same* catalog inside Settings; `onSelectCatalogTab` keeps Plugins / Skills in-panel.* Outputs: the Plugin list/detail UI, recommendation-aware return navigation, and Plugin action flows.+ * Personal submissions remain in the original detail until the server confirms the result.* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md*/@@ -23,7 +32,7 @@ import {type KeyboardEvent,type ReactNode,} from 'react';-import { useNavigate, useSearchParams } from 'react-router-dom';+import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';import {AlertTriangle,ArrowUp,@@ -41,6 +50,7 @@ import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { toast } from '@/lib/toast';import { extractIpcError } from '@/utils/ipcError';import { useAuth } from '@/contexts/AuthContext';+import { usePluginReviewUpdates } from '@/contexts/PluginReviewUpdatesContext';import { readInstalledGhostsSnapshot, useInstalledGhosts } from '@/cindy-brain/useInstalledGhosts';import {cancelPendingPluginSuggestion,@@ -440,6 +450,7 @@ function LocalGhostPluginPage({const { i18n, t } = useTranslation();const marketLocale = resolveSystemLocale(i18n.resolvedLanguage ?? i18n.language);const navigate = useNavigate();+ const location = useLocation();const [searchParams, setSearchParams] = useSearchParams();const { confirm } = useConfirmDialog();@@ -452,6 +463,23 @@ function LocalGhostPluginPage({[t],);const { user, mode, dataOwnerId, dataOwnerGeneration } = useAuth();+ const reviewUnread = usePluginReviewUpdates().updates.filter(item => item.unread);+ const signInForContribution = useSignInToCindy('/plugins?myPlugins=1');+ const contributionOwner = JSON.stringify([dataOwnerId, dataOwnerGeneration, user?.id, mode]);+ const contributionOwnerRef = useRef(contributionOwner);+ contributionOwnerRef.current = contributionOwner;+ const contributionMounted = useRef(true);+ useEffect(() => {+ contributionMounted.current = true;+ return () => { contributionMounted.current = false; };+ }, []);+ const contributionCache = useRef<MyPluginsPageCache>({});+ const [contributionBusy, setContributionBusy] = useState(false);+ const [submissionRevision, setSubmissionRevision] = useState(0);+ const contributing = useRef<string | null>(null);+ const [publicationDraft, setPublicationDraft] = useState<{ key: string; prepared?: PreparedPluginContribution; error?: string } | null>(null);+ const [publicationRefresh, setPublicationRefresh] = useState(0);+ const [localContribution, setLocalContribution] = useState<{ key: string; plugin: MyPluginView | null; versionUsed: boolean; error: string | null } | null>(null);const [recommendationNonce] = useState(() => searchParams.get('recommendation'));const pendingRecommendation = useSyncExternalStore(subscribePendingPluginSuggestion,@@ -512,7 +540,11 @@ function LocalGhostPluginPage({</div>) : null;const showEnterprise = user?.membershipKind === 'org';+ const personalContributor = mode === 'cloud' && user?.membershipKind === 'personal';const ghosts = useInstalledGhosts();+ const publishingInstallations = usePublishingInstallations(contributionOwner, personalContributor, ghosts);+ const canSubmitMarketInstallation = (ghost: InstalledGhost) => publishingInstallations.some(plugin =>+ plugin.localInstanceId === installedGhostStoragePart(ghost) && plugin.actions.submitUpdate);useMainViewVisibilityRevision();const installedGhostMarketKey = useMemo(() => installedGhostMarketKeyFor(ghosts),@@ -538,8 +570,12 @@ function LocalGhostPluginPage({}, [ignoredRoundKey]);const [originFilter, setOriginFilter] = useState<PluginPresentationFilter>('all');const [marketDetail, setMarketDetail] = useState<PluginMarketDetail | null>(null);+ const contributionViewKey = JSON.stringify([location.key, selectedId, marketDetail?.pluginId]);+ const contributionView = useRef({ key: contributionViewKey, token: {} });+ if (contributionView.current.key !== contributionViewKey)+ contributionView.current = { key: contributionViewKey, token: {} };// 列表与详情是互斥分支;列表节点会卸载,返回时需显式恢复进入前的滚动位置。- const pluginCatalogVisible = marketDetail === null && selectedId === null;+ const pluginCatalogVisible = marketDetail === null && selectedId === null && !searchParams.has('myPlugins');const {listRef: pluginCatalogListRef,onListScroll: onPluginCatalogScroll,@@ -580,9 +616,10 @@ function LocalGhostPluginPage({const refreshMarket = useCallback(async (preserveOnError = false) => {installedGhostMarketKeyRef.current = installedGhostMarketKeyFor(readInstalledGhostsSnapshot());const requestId = ++marketRefreshRequestRef.current;+ const owner = contributionOwnerRef.current;try {const snapshot = await window.electronAPI.pluginMarket.snapshot();- if (requestId !== marketRefreshRequestRef.current) return;+ if (requestId !== marketRefreshRequestRef.current || contributionOwnerRef.current !== owner) return;// Main intentionally represents market outages as data so the initial page can render a// non-blocking empty state. During icon renewal, convert that fulfilled unavailable result// back into a failure: the catch path preserves the visible snapshot and the hook retries.@@ -592,7 +629,7 @@ function LocalGhostPluginPage({setMarketSnapshot(snapshot);lastMarketRefreshAtRef.current = Date.now();} catch (error) {- if (requestId !== marketRefreshRequestRef.current) return;+ if (requestId !== marketRefreshRequestRef.current || contributionOwnerRef.current !== owner) return;setMarketSnapshot((current) =>preserveOnError && current? current@@ -616,7 +653,7 @@ function LocalGhostPluginPage({setMarketBusyId(null);marketDetailRequestRef.current += 1;void refreshMarket();- }, [clearPluginCatalogScrollRestore, refreshMarket, mode, dataOwnerId]);+ }, [clearPluginCatalogScrollRestore, refreshMarket, mode, dataOwnerId, dataOwnerGeneration]);const refreshMarketOnForeground = useCallback(() => refreshMarket(true), [refreshMarket]);usePluginMarketForegroundRefresh(refreshMarketOnForeground, lastMarketRefreshAtRef);useEffect(() => {@@ -761,7 +798,15 @@ function LocalGhostPluginPage({...toGhostPluginListItem(ghost, presentation),origin: pluginPresentationOrigin(marketItem),marketItem,- author: presentation?.author ?? ghost.manifest.author ?? null,+ // 服务端的空署名代表匿名;公域来源缺少可信投影时也不回退包内作者。+ author: presentation+ ? presentation.author+ : ghost.publishingSource?.kind === 'public-market' ||+ (marketItem?.sourceType === 'server' && marketItem.scope === 'public')+ ? null+ : ghost.manifest.author ?? null,+ // 同版本展示刷新由 main 标成 installed;legacy-unresolved 仍保留+ // update-available,以便用户用市场包替换未验证的本地字节。marketUpdate: ghost.retirement ? null : pluginUpdateForInstalledVersion(marketItem),};}),@@ -774,6 +819,13 @@ function LocalGhostPluginPage({: allInstalledItems.filter((item) => item.origin !== 'organization'),[allInstalledItems, showEnterprise],);+ const publishableInstalledItems = useMemo(() => {+ const eligible = new Set(ghosts.filter((ghost) =>+ ghost.publishingSource?.kind === 'local' &&+ !localPublishingUnavailableKey(ghost, marketItemForInstalledGhost(marketItems, ghost), canSubmitMarketInstallation(ghost)),+ ).map(installedGhostStoragePart));+ return allInstalledItems.filter((item) => eligible.has(item.id));+ }, [ghosts, marketItems, allInstalledItems, publishingInstallations]);const searchedInstalledItems = useMemo(() => filterGhostPluginItems(installedItems, query),[installedItems, query],@@ -1635,6 +1687,237 @@ function LocalGhostPluginPage({await handleInstallMarketItem(target.marketId);};+ const showMyPlugins = searchParams.has('myPlugins');+ useEffect(() => {+ if (!searchParams.has('contributionChild') && !searchParams.has('contributionTransfer')) return;+ const next = new URLSearchParams(searchParams); next.delete('contributionChild'); next.delete('contributionTransfer');+ setSearchParams(next, { replace: true });+ }, [searchParams, setSearchParams]);+ const localContributionKey = JSON.stringify([contributionOwner, selectedDetail?.id, selectedGhost?.dir, selectedGhost?.manifest.version, ghostInstallApprovalToken(selectedGhost?.approval), selectedGhost?.publishingSource, publicationRefresh]);+ const localContributionResult = localContribution?.key === localContributionKey ? localContribution : null;+ const contributionUnavailableKey = localPublishingUnavailableKey(selectedGhost, selectedMarketInstall,+ Boolean(selectedGhost && canSubmitMarketInstallation(selectedGhost)));+ // Ordinary downloads have use/configuration details only. Unknown provenance+ // also cannot become a first publication merely because no market card exists.+ const showLocalPublishing = selectedGhost?.publishingSource?.kind === 'local';+ const localPublishBlocker = localContributionResult?.plugin+ ? !localContributionResult.plugin.actions.submitUpdate ? 'PERMISSION_DENIED'+ : localContributionResult.plugin.latestSubmission?.reviewStatus === 'pending' && localContributionResult.plugin.latestSubmission.revisionState === 'current' ? 'PLUGIN_PENDING_RELEASE_EXISTS'+ : localContributionResult.versionUsed ? 'VERSION_ALREADY_SUBMITTED'+ : null+ : null;+ const [authorRevision, setAuthorRevision] = useState(0);+ const acceptAuthorSettings = (result: MyPluginDetailView, appliesToCurrentControl: boolean) => {+ if (!contributionMounted.current || contributionOwnerRef.current !== contributionOwner) return;+ // Refetch instead of applying an old completion to a remounted same-plugin+ // detail (A → B → A). The server remains the only anonymity source of truth.+ // The active control applies its confirmed result in place. Only a completion+ // from an abandoned control requires rebuilding the current author view.+ if (!appliesToCurrentControl) setAuthorRevision(value => value + 1);+ // MyPlugins remounts on return. Its old author/content snapshots must be rebuilt.+ contributionCache.current.page = null;+ contributionCache.current.detail = null;+ const affectedIds = new Set([result.plugin.pluginId]);+ // Do not cancel navigation already loading a different plugin.+ if (!marketBusyLockRef.current || affectedIds.has(marketBusyLockRef.current.pluginId))+ marketDetailRequestRef.current++;+ const hideOldAuthor = (detail: PluginMarketDetail) => ({+ ...detail, author: null, installedAuthor: null, manifest: { ...detail.manifest, author: undefined },+ });+ setMarketSnapshot(current => current ? { ...current, items: current.items.map(item =>+ affectedIds.has(item.pluginId) ? { ...item, author: null, installedAuthor: null } : item) } : current);+ setMarketDetail(current => current && affectedIds.has(current.pluginId) ? hideOldAuthor(current) : current);+ const owner = contributionOwner;+ const request = marketDetailRequestRef.current;+ void refreshMarket(true).catch(() => {+ if (contributionMounted.current && contributionOwnerRef.current === owner) toast.error(t('settings.ghosts.contribution.loadFailed'));+ });+ if (!result.plugin.actions.viewMarket) return;+ // Each version's public nickname is projected by Main/server, never guessed from+ // the current account or copied from a different release's author snapshot.+ void window.electronAPI.pluginMarket.detail(result.plugin.pluginId).then(detail => {+ if (!contributionMounted.current || contributionOwnerRef.current !== owner || marketDetailRequestRef.current !== request) return;+ setMarketDetail(current => current && affectedIds.has(current.pluginId) ? detail : current);+ }).catch(() => {+ if (contributionMounted.current && contributionOwnerRef.current === owner && marketDetailRequestRef.current === request) toast.error(t('settings.ghosts.contribution.loadFailed'));+ });+ };+ useEffect(() => {+ let disposed = false;+ setLocalContribution(null);+ if (!personalContributor || !selectedGhost || !selectedGhost.publishingSource || selectedGhost.publishingSource.kind !== 'local' || selectedGhost.namespace !== null || selectedGhost.namespaceState !== 'confirmed' || selectedGhost.approval.state !== 'approved' || showMyPlugins) return;+ const owner = contributionOwner;+ const instanceId = installedGhostStoragePart(selectedGhost);+ const read = async () => {+ let cursor: string | undefined;+ const listCursors = new Set<string>();+ do {+ const page = await window.electronAPI.pluginContributions.list({ query: selectedGhost.manifest.id, filter: 'all', cursor });+ if (disposed || contributionOwnerRef.current !== owner) return;+ const plugin = page.plugins.find((item) => item.localInstanceId === instanceId);+ if (plugin) {+ // Cancelled/rejected versions stay occupied, including versions older+ // than latestSubmission. Do not enable an update until this read ends.+ const version = selectedGhost.manifest.version;+ let versionUsed = plugin.market.version === version || plugin.latestSubmission?.version === version;+ const pending = plugin.latestSubmission?.reviewStatus === 'pending' && plugin.latestSubmission.revisionState === 'current';+ if (plugin.actions.submitUpdate && !pending && !versionUsed) {+ let releaseCursor: string | undefined;+ const releaseCursors = new Set<string>();+ do {+ const releases = await window.electronAPI.pluginContributions.releases(plugin.pluginId, releaseCursor);+ if (disposed || contributionOwnerRef.current !== owner) return;+ versionUsed = releases.releases.some(release => release.version === version);+ if (versionUsed) break;+ releaseCursor = releases.nextCursor ?? undefined;+ if (releaseCursor && releaseCursors.has(releaseCursor)) throw new Error('Repeated release cursor');+ if (releaseCursor) releaseCursors.add(releaseCursor);+ } while (releaseCursor);+ }+ setLocalContribution({ key: localContributionKey, plugin, versionUsed, error: null });+ return;+ }+ cursor = page.nextCursor ?? undefined;+ if (cursor && listCursors.has(cursor)) throw new Error('Repeated contribution cursor');+ if (cursor) listCursors.add(cursor);+ } while (cursor);+ setLocalContribution({ key: localContributionKey, plugin: null, versionUsed: false, error: null });+ };+ void read().catch((error) => {+ if (!disposed && contributionOwnerRef.current === owner) setLocalContribution({ key: localContributionKey, plugin: null, versionUsed: false, error: contributionErrorKey(error) });+ });+ return () => { disposed = true; };+ }, [personalContributor, localContributionKey, showMyPlugins]);+ const currentPublicationDraft = publicationDraft?.key === localContributionKey ? publicationDraft : null;+ useEffect(() => {+ let disposed = false;+ let held: string | undefined;+ setPublicationDraft(null);+ if (!personalContributor || !selectedGhost || selectedGhost.publishingSource?.kind !== 'local' || contributionUnavailableKey || showMyPlugins || !localContributionResult || localContributionResult.error || localContributionResult.plugin) return;+ const owner = contributionOwner;+ void window.electronAPI.pluginContributions.prepare(installedGhostStoragePart(selectedGhost), {+ directory: selectedGhost.dir, approvalToken: ghostInstallApprovalToken(selectedGhost.approval),+ }).then(prepared => {+ held = prepared.preparedId;+ if (disposed || contributionOwnerRef.current !== owner) {+ void window.electronAPI.pluginContributions.discard(prepared.preparedId).catch(() => undefined);+ return;+ }+ setPublicationDraft({ key: localContributionKey, prepared });+ }).catch(error => {+ if (!disposed && contributionOwnerRef.current === owner) setPublicationDraft({ key: localContributionKey, error: contributionErrorKey(error) });+ });+ return () => {+ disposed = true;+ if (held) void window.electronAPI.pluginContributions.discard(held).catch(() => undefined);+ };+ }, [personalContributor, localContributionKey, showMyPlugins, contributionUnavailableKey, publicationRefresh, localContributionResult]);+ useEffect(() => {+ if (showMyPlugins) { setSelectedId(null); setMarketDetail(null); }+ }, [showMyPlugins]);+ useEffect(() => { contributing.current = null; setContributionBusy(false); }, [contributionOwner]);++ const openMyPlugins = (pluginId?: string) => {+ if (pluginCatalogVisible) capturePluginCatalogScroll();+ setSelectedId(null); setMarketDetail(null);+ const next = new URLSearchParams(searchParams);+ next.set('myPlugins', '1'); next.delete('contributionChild'); next.delete('contributionTransfer');+ if (pluginId) next.set('contribution', pluginId); else next.delete('contribution');+ setSearchParams(next);+ };+ const preparePublication = (instanceId: string) => {+ const ghost = findInstalledGhostByInstanceId(ghosts, instanceId);+ if (!ghost || ghost.publishingSource?.kind !== 'local' ||+ localPublishingUnavailableKey(ghost, marketItemForInstalledGhost(marketItems, ghost)))+ throw new Error('Current local publishing source is unavailable');+ return window.electronAPI.pluginContributions.prepare(instanceId, {+ directory: ghost.dir, approvalToken: ghostInstallApprovalToken(ghost.approval),+ });+ };+ const contribute = async (instanceId: string, options?: PluginSubmitOptions): Promise<boolean> => {+ if (contributing.current) return false;+ if (!personalContributor) {+ const ghost = findInstalledGhostByInstanceId(ghosts, instanceId);+ if (!ghost || localPublishingUnavailableKey(ghost) || ghost.publishingSource?.kind !== 'local') return false;+ const nonce = rememberContributionIntent(ghost);+ const next = new URLSearchParams(searchParams); next.set('myPlugins', '1'); next.set('contributionIntent', nonce);+ setSearchParams(next);+ if (mode !== 'cloud') {+ await signInForContribution();+ navigate('/login', { replace: true, state: { returnTo: `/plugins?${next}` } });+ }+ return false;+ }+ const owner = contributionOwner;+ const submittedFrom = contributionView.current.token;+ const stillHere = () => contributionMounted.current && contributionOwnerRef.current === owner &&+ contributionView.current.token === submittedFrom && (options?.isCurrent?.() ?? true);+ contributing.current = owner;+ setContributionBusy(true);+ let preparedId: string | undefined;+ try {+ const clicked = findInstalledGhostByInstanceId(ghosts, instanceId);+ if (!clicked) throw new Error('Original installed plugin is unavailable');+ if (clicked.publishingSource?.kind !== 'local' || localPublishingUnavailableKey(clicked, marketItemForInstalledGhost(marketItems, clicked)))+ throw new Error('Current publishing source or permission is unavailable');+ const prepared = options?.prepared ?? (currentPublicationDraft?.prepared?.instanceId === instanceId ? currentPublicationDraft.prepared : undefined) ?? await preparePublication(instanceId);+ if (prepared.instanceId !== instanceId) throw new Error('Original installed plugin changed');+ preparedId = prepared.preparedId;+ if (contributionOwnerRef.current !== owner) return false;+ let result = await window.electronAPI.pluginContributions.submit(prepared.preparedId);+ preparedId = undefined;+ // Keep upload bookkeeping inside this submit action. Only a confirmed+ // server submission belongs in My Plugins; HTTP 202 is still submitting.+ while (result.stage !== 'complete' && result.stage !== 'paused') {+ if (!contributionMounted.current || contributionOwnerRef.current !== owner) return false;+ await new Promise(resolve => window.setTimeout(resolve, 1000));+ if (!contributionMounted.current || contributionOwnerRef.current !== owner) return false;+ result = await window.electronAPI.pluginContributions.status(result.localId);+ }+ if (!contributionMounted.current || contributionOwnerRef.current !== owner) return false;+ if (result.operation?.status !== 'succeeded' || !result.operation.receipt) {+ const message = result.operation?.failure?.message;+ toast.error(message && ![+ '投稿处理暂不可用,请查看原操作后重试',+ '发布处理暂不可用,请查看原操作后重试',+ ].includes(message) ? message : t(`settings.ghosts.contribution.errors.${result.errorCode ?? 'INTERNAL'}`, {+ defaultValue: t('settings.ghosts.contribution.submitFailed'),+ }));+ if (result.stage === 'complete' && stillHere()) setPublicationRefresh(value => value + 1);+ return false;+ }+ contributionCache.current.page = null; contributionCache.current.detail = null;+ setSubmissionRevision(value => value + 1);+ if (stillHere() && (!showMyPlugins || searchParams.get('contribution') !== result.operation.receipt.pluginId))+ openMyPlugins(result.operation.receipt.pluginId);+ return true;+ } catch (error) {+ if (contributionOwnerRef.current === owner) { toast.error(t(contributionErrorKey(error), { defaultValue: t('settings.ghosts.contribution.loadFailed') })); setPublicationRefresh(value => value + 1); }+ return false;+ } finally {+ if (preparedId && contributionOwnerRef.current === owner) void window.electronAPI.pluginContributions.discard(preparedId).catch(() => undefined);+ if (contributionOwnerRef.current === owner && contributing.current === owner) { contributing.current = null; setContributionBusy(false); }+ }+ };++ useEffect(() => {+ const nonce = searchParams.get('contributionIntent');+ if (!nonce || !personalContributor) return;+ const target = consumeContributionIntent(nonce);+ const next = new URLSearchParams(searchParams); next.delete('contributionIntent');+ setSearchParams(next, { replace: true });+ if (!target) return;+ const matches = ghosts.filter((ghost) => matchesContributionIntent(target, ghost));+ if (matches.length === 1) {+ // Login returns to the exact local detail so the actual package summary is read first.+ next.delete('myPlugins'); next.delete('contribution'); next.delete('contributionChild');+ setSelectedId(installedGhostStoragePart(matches[0]));+ setMarketDetail(null);+ setSearchParams(next, { replace: true });+ }+ else toast.error(t('settings.ghosts.contribution.installForAccount'));+ }, [searchParams, personalContributor, contributionOwner, ghosts]);+// 面板收束:aside 只挂在插件页语境里(列表/详情/市场详情共用),// 路由离开本页组件整体卸载 → webview 一并回收,绝不残留到别的界面。const panelAside = openPanelGhost ? (@@ -1647,52 +1930,8 @@ function LocalGhostPluginPage({/>) : null;- if (marketDetail) {- return (- <div className="flex h-full min-h-0 w-full">- <div className="flex min-w-0 flex-1 flex-col">- {recommendationNotice}- <div className="min-h-0 flex-1">- <MarketPluginDetailView- detail={marketDetail}- busy={marketBusyId === marketDetail.pluginId}- onBack={handleMarketBack}- onInstall={- canOfferMarketInstall(mode, marketDetail.ghostId)- ? () => void handleInstallFromMarket()- : undefined- }- onIconLoadError={handleMarketIconLoadError}- />- </div>- </div>- {panelAside}- </div>- );- }- if (selectedGhost?.retirement) {- const target = featureRetirementById(selectedGhost.retirement.id)?.replacement;- return (- <RetiredFeatureDetail- ghost={selectedGhost}- replacement={findInstalledRetirementReplacement(ghosts, marketItems, target)}- busy={marketBusyId !== null}- onBack={() => setSelectedId(null)}- onReplace={() => void handleReplaceRetiredFeature()}- onDismiss={() => {- void window.electronAPI.ghosts- .acknowledgeRetirement(installedGhostStoragePart(selectedGhost))- .then(() => setSelectedId(null))- .catch(() => toast.error(t('settings.ghosts.retirement.saveFailed')));- }}- onUninstall={() => void handleUninstall()}- />- );- }-- if (selectedDetail) {- return (+ const renderInstalledDetail = () => selectedDetail ? (<div className="flex h-full min-h-0 w-full"><div className="flex min-w-0 flex-1 flex-col">{recommendationNotice}@@ -1730,6 +1969,12 @@ function LocalGhostPluginPage({? () => void handleExport(): undefined}+ onContribute={!showLocalPublishing || contributionUnavailableKey || localPublishBlocker ? undefined : () => void contribute(selectedDetail.id)}+ contributionUnavailableReason={contributionUnavailableKey === 'officialGithubRequired' || (contributionUnavailableKey === 'reservedId' && selectedGhost?.publishingSource?.kind === 'public-market') ? t(`settings.ghosts.contribution.unavailable.${contributionUnavailableKey}`) : !showLocalPublishing ? undefined : contributionUnavailableKey ? t(`settings.ghosts.contribution.unavailable.${contributionUnavailableKey}`) : localContributionResult?.error ? t(localContributionResult.error) : localPublishBlocker ? t(`settings.ghosts.contribution.errors.${localPublishBlocker}`) : currentPublicationDraft?.error ? t(currentPublicationDraft.error, { defaultValue: t('settings.ghosts.contribution.loadFailed') }) : currentPublicationDraft?.prepared?.preflight?.blockers[0] ? currentPublicationDraft.prepared.preflight.blockers[0].message : personalContributor && !localContributionResult?.plugin && !currentPublicationDraft?.prepared ? t('settings.ghosts.contribution.preparing') : undefined}+ publishingPreview={currentPublicationDraft?.prepared}+ onRefreshPublishing={() => setPublicationRefresh(value => value + 1)}+ contributionUpdate={Boolean(localContributionResult?.plugin || (selectedGhost?.manifest.id && marketItems.some((item) => marketItemMatchesInstalledGhost(item, selectedGhost))))}+ contributionBusy={contributionBusy}toggleDisabled={scopeDir !== null && selectedGhost !== null && !selectedGhost.enabled}onIconLoadError={handleMarketIconLoadError}/>@@ -1737,9 +1982,84 @@ function LocalGhostPluginPage({</div>{panelAside}</div>+ ) : null;++ if (showMyPlugins) return <MyPluginsPage+ key={`${contributionOwner}:${authorRevision}`}+ cache={contributionCache.current}+ onAuthorSettingsUpdated={acceptAuthorSettings}+ reader={window.electronAPI.pluginContributions}+ localPlugins={publishableInstalledItems}+ installedPluginCount={allInstalledItems.length}+ onPrepare={preparePublication}+ installedRevision={JSON.stringify([installedGhostMarketKey, installedGhostLocationsKey,+ ghosts.map(ghost => [installedGhostStoragePart(ghost), ghostInstallApprovalToken(ghost.approval), ghost.publishingSource])])}+ renderVersionFacts={(plugin) => <PluginVersionFacts plugin={plugin} />}+ onReadPublished={window.electronAPI.pluginMarket.detail}+ submitBusy={contributionBusy}+ submissionRevision={submissionRevision}+ onSubmitUpdate={contribute}+ onInstallPublished={async (pluginId) => {+ const owner = contributionOwner;+ const detail = await window.electronAPI.pluginMarket.detail(pluginId);+ if (contributionOwnerRef.current !== owner) return;+ if (detail.scope !== 'public' || detail.sourceType !== 'server') return;+ await runMarketInstallFlow(detail);+ }}+ onViewLocal={() => {+ const next = new URLSearchParams(searchParams); next.delete('myPlugins'); next.delete('contribution'); next.delete('contributionChild'); next.delete('contributionTransfer');+ requestPluginCatalogScrollRestore();+ setSelectedId(null); setMarketDetail(null); setSearchParams(next, { replace: true });+ }}+ />;+++ if (marketDetail) {+ return (+ <div className="flex h-full min-h-0 w-full">+ <div className="flex min-w-0 flex-1 flex-col">+ {recommendationNotice}+ <div className="min-h-0 flex-1">+ <MarketPluginDetailView+ detail={marketDetail}+ busy={marketBusyId === marketDetail.pluginId}+ onBack={handleMarketBack}+ onInstall={+ canOfferMarketInstall(mode, marketDetail.ghostId)+ ? () => void handleInstallFromMarket()+ : undefined+ }+ onIconLoadError={handleMarketIconLoadError}+ />+ </div>+ </div>+ {panelAside}+ </div>);}+ if (selectedGhost?.retirement) {+ const target = featureRetirementById(selectedGhost.retirement.id)?.replacement;+ return (+ <RetiredFeatureDetail+ ghost={selectedGhost}+ replacement={findInstalledRetirementReplacement(ghosts, marketItems, target)}+ busy={marketBusyId !== null}+ onBack={() => setSelectedId(null)}+ onReplace={() => void handleReplaceRetiredFeature()}+ onDismiss={() => {+ void window.electronAPI.ghosts+ .acknowledgeRetirement(installedGhostStoragePart(selectedGhost))+ .then(() => setSelectedId(null))+ .catch(() => toast.error(t('settings.ghosts.retirement.saveFailed')));+ }}+ onUninstall={() => void handleUninstall()}+ />+ );+ }++ if (selectedDetail) return renderInstalledDetail();+return (<PluginManagementLayoutactiveTab="plugins"@@ -1750,11 +2070,21 @@ function LocalGhostPluginPage({embedded={embedded}onSelectTab={onSelectCatalogTab}headerActions={- <GhostPluginActions- onInstall={() => void handleInstall()}- onCreateWithCindy={handleCreateWithCindy}- onAddMarketplace={() => setAddMarketplaceOpen(true)}- />+ <>+ <Button variant="secondary" size="sm" onClick={() => openMyPlugins()}>+ {t('settings.ghosts.contribution.myPlugins')}+ {reviewUnread.length > 0 ? (+ <span role="img" className="inline-flex" aria-label={t('settings.ghosts.contribution.unreadReview')}>+ <AttentionDot tone={reviewUnread.some(item => item.status === 'rejected') ? 'error' : 'done'} />+ </span>+ ) : null}+ </Button>+ <GhostPluginActions+ onInstall={() => void handleInstall()}+ onCreateWithCindy={handleCreateWithCindy}+ onAddMarketplace={() => setAddMarketplaceOpen(true)}+ />+ </>}><div className="flex min-h-0 flex-1">diff --git a/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsxindex e417fe75d2..92b6d1f5bf 100644--- a/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx@@ -1,4 +1,6 @@import { Button } from '@/components/ui/button';+import { PluginVersionUpdates } from './PluginVersionUpdates';+import { ToolsSection } from './GhostPluginDetailView';import { useId } from 'react';import { Download, ShieldCheck } from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -106,14 +108,17 @@ export function MarketPluginDetailView({</Button>) : null}</div>- <p- id={replacementDescription ? replacementDescriptionId : undefined}- className="mt-5 text-14 leading-[1.571] text-[var(--text-secondary)]"- >- {replacementDescription ?? (detail.description || detail.ghostId)}+ <p className="mt-5 text-14 leading-[1.571] text-[var(--text-secondary)]">+ {detail.description || detail.ghostId}</p>+ {replacementDescription ? (+ <p id={replacementDescriptionId} className="mt-3 text-13 leading-5 text-[var(--text-secondary)]">+ {replacementDescription}+ </p>+ ) : null}</header>+ {detail.manifest.tools?.length ? <ToolsSection tools={detail.manifest.tools} /> : null}<section className="mt-10" aria-labelledby="market-security-title"><h2id="market-security-title"@@ -166,6 +171,18 @@ export function MarketPluginDetailView({)}</div></section>+ {detail.manifest.releaseNotes?.trim() ? (+ <PluginVersionUpdates key={detail.pluginId}>+ <section className="space-y-3" aria-label={t('settings.ghosts.contribution.releaseNotes')}>+ <h2 className="text-18 font-medium leading-[1.444] text-[var(--text-primary)]">+ {t('settings.ghosts.contribution.releaseNotes')} · {detail.version}+ </h2>+ <p className="whitespace-pre-wrap break-words text-14 leading-6 text-[var(--text-secondary)]">+ {detail.manifest.releaseNotes}+ </p>+ </section>+ </PluginVersionUpdates>+ ) : null}</article></main>);diff --git a/apps/desktop/src/renderer/features/plugin/MyPluginsPage.tsx b/apps/desktop/src/renderer/features/plugin/MyPluginsPage.tsxnew file mode 100644index 0000000000..a9a1d86493--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/MyPluginsPage.tsx@@ -0,0 +1,1530 @@+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';+import { PluginPublisherBadge } from './PluginPublisherBadge';+import { PluginSharedUsage } from './PluginSharedUsage';+import * as Dialog from '@radix-ui/react-dialog';+import { Check, ChevronRight, Plus, RotateCw } from 'lucide-react';+import { Select } from '@/components/ui/select';+import { Tip } from '@/components/ui/tooltip';+import type { GhostPluginListItem } from './lib/ghostPluginViewModel';+import type { PluginMarketDetail } from '../../../shared/pluginMarket';+import { AccountSwitcherDialog } from '@/components/sidebar/AccountSwitcherDialog';+import { useSignInToCindy } from '@/hooks/useSignInToCindy';+import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } from 'react';+import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';+import { useTranslation } from 'react-i18next';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { PluginAnonymityControl } from './PluginAnonymityControl';+import { PluginVersionFacts } from './PluginVersionFacts';+import { useAuth } from '@/contexts/AuthContext';+import { usePluginReviewUpdates } from '@/contexts/PluginReviewUpdatesContext';+import { AttentionDot } from '@/components/sidebar/AttentionDot';+import { extractIpcError } from '@/utils/ipcError';+import type {+ PluginContributionsApi,+ ContributionReleaseView,+ MyPluginDetailView,+ MyPluginFilter,+ MyPluginPageView,+ MyPluginReleasePageView,+ MyPluginView,+ PreparedPluginContribution,+} from '../../../shared/pluginContributions';+import { PluginDetailTopBar, usePluginDetailScrolled } from './PluginDetailTopBar';+import { PLUGIN_MANAGEMENT_FRAME_CLASS, PluginManagementPage } from './PluginManagementLayout';+import { GhostPluginIcon } from './GhostPluginIcon';+import { usePluginMarketForegroundRefresh } from './lib/usePluginMarketForegroundRefresh';++const copy = 'settings.ghosts.contribution';+const releaseKey = (release: ContributionReleaseView) =>+ JSON.stringify([release.releaseId, release.revision, release.sha256, release.submissionId]);++export interface MyPluginsPageCache {+ ownerKey?: string;+ query?: string;+ filter?: MyPluginFilter;+ page?: MyPluginPageView | null;+ detail?: MyPluginDetailView | null;+ /** In-memory binding of this cached detail to the last Main association read. */+ installationRevision?: string;+ scroll?: number;+ selectedRelease?: { pluginId: string; key: string };+}++export interface PluginSubmitOptions {+ prepared?: PreparedPluginContribution;+ /** Closing/reopening the picker must not let an old completion navigate. */+ isCurrent?: () => boolean;+}++export function contributionErrorKey(error: unknown): string {+ const code = extractIpcError(error)?.code;+ if (code === 'OFFICIAL_PLUGIN_GITHUB_REQUIRED') return `${copy}.unavailable.officialGithubRequired`;+ if (!navigator.onLine && (!code || code === 'INTERNAL')) return `${copy}.offline`;+ if (code === 'PERMISSION_DENIED') return `${copy}.permissionDenied`;+ if (code === 'NOT_FOUND') return `${copy}.notFound`;+ if (code === 'OWNER_CHANGED') return `${copy}.accountChanged`;+ if (code) return `${copy}.errors.${code}`;+ return navigator.onLine ? `${copy}.loadFailed` : `${copy}.offline`;+}++/** Kept independent of transport DTOs; the Host supplies an owner-fenced read projection. */+export function MyPluginsPage({+ reader,+ localPlugins,+ installedPluginCount,+ onSubmitUpdate,+ onPrepare,+ onViewLocal,+ cache,+ onAuthorSettingsUpdated,+ renderVersionFacts,+ onInstallPublished,+ onReadPublished,+ submitBusy = false,+ submissionRevision = 0,+ installedRevision,+}: {+ reader: PluginContributionsApi;+ onAuthorSettingsUpdated?: (detail: MyPluginDetailView, appliesToCurrentControl: boolean) => void;+ localPlugins: readonly GhostPluginListItem[];+ installedPluginCount: number;+ cache: MyPluginsPageCache;+ onSubmitUpdate: (instanceId: string, options?: PluginSubmitOptions) => Promise<boolean>;+ onPrepare?: (instanceId: string) => Promise<PreparedPluginContribution>;+ renderVersionFacts?: (plugin: MyPluginView) => ReactNode;+ onInstallPublished?: (pluginId: string) => Promise<void>;+ onReadPublished?: (pluginId: string) => Promise<PluginMarketDetail>;+ submitBusy?: boolean;+ submissionRevision?: number;+ installedRevision?: string;+ onViewLocal: () => void;+}) {+ const { t, i18n } = useTranslation();+ const { dataOwnerId, dataOwnerGeneration, user, mode } = useAuth();+ const ownerKey = JSON.stringify([dataOwnerId, dataOwnerGeneration, user?.id, mode]);+ const navigate = useNavigate();+ const location = useLocation();+ const signIn = useSignInToCindy(`${location.pathname}${location.search}`);+ const [pickerOwner, setPickerOwner] = useState<string | null>(null);+ const pickerStatusId = useId();+ const [pickerSelection, setPickerSelection] = useState<string | null>(null);+ const [pickerRefresh, setPickerRefresh] = useState(0);+ const [pickerPlugins, setPickerPlugins] = useState<{+ key: string; plugins: MyPluginView[]; failure?: string;+ } | null>(null);+ const [pickerDraft, setPickerDraft] = useState<{+ key: string; prepared?: PreparedPluginContribution; error?: string;+ } | null>(null);+ const preparePicker = useRef(onPrepare ?? reader.prepare);+ preparePicker.current = onPrepare ?? reader.prepare;+ const [accountSwitcherOpen, setAccountSwitcherOpen] = useState(false);+ const accountTrigger = useRef<HTMLButtonElement>(null);+ const { confirm } = useConfirmDialog();+ const reviewUpdates = usePluginReviewUpdates();+ const [cancelBusy, setCancelBusy] = useState(false);+ const [installBusy, setInstallBusy] = useState(false);+ const [publishedContent, setPublishedContent] = useState<{+ key: string; value: PluginMarketDetail | null; loading: boolean;+ } | null>(null);+ const publishedRequest = useRef(0);+ const [historyOpenKey, setHistoryOpenKey] = useState<string | null>(null);+ const [cancelResult, setCancelResult] = useState<{+ owner: string;+ pluginId: string;+ releaseId: string;+ cancelled: boolean;+ } | null>(null);+ const cancelling = useRef<symbol | null>(null);+ const saved = cache.ownerKey === ownerKey ? cache : {};+ const [installationRead, setInstallationRead] = useState<{ owner: string; pluginId: string; revision?: string } | null>(() =>+ saved.detail && saved.installationRevision !== undefined+ ? { owner: ownerKey, pluginId: saved.detail.plugin.pluginId, revision: saved.installationRevision } : null);+ const [loadedOwner, setLoadedOwner] = useState(ownerKey);+ const ownerMatches = loadedOwner === ownerKey;+ const [storedSnapshots, setSnapshots] = useState<Record<string, ContributionReleaseView>>({});+ const [storedSnapshotLoading, setSnapshotLoading] = useState<string | null>(null);+ const [params, setParams] = useSearchParams();+ const selectedId = params.get('contribution');+ const [selectedRelease, setSelectedRelease] = useState(saved.selectedRelease);+ const [versionPage, setVersionPage] = useState<+ (MyPluginReleasePageView & { pluginId: string }) | null+ >(null);+ const [versionsLoading, setVersionsLoading] = useState(false);+ const [versionFailure, setVersionFailure] = useState<string | null>(null);+ const versionRequest = useRef(0);+ const snapshotRequest = useRef(0);+ const selectedPlugin = useRef(selectedId);+ selectedPlugin.current = selectedId;+ const [storedQuery, setQuery] = useState(saved.query ?? '');+ const [storedFilter, setFilter] = useState<MyPluginFilter>(saved.filter ?? 'all');+ const [storedPage, setPage] = useState<MyPluginPageView | null>(saved.page ?? null);+ const [listInstallationRead, setListInstallationRead] = useState<string | null>(null);+ const [storedDetail, setDetail] = useState<MyPluginDetailView | null>(saved.detail ?? null);+ const [storedFailure, setFailure] = useState<string | null>(null);+ const [storedLoading, setLoading] = useState(false);+ // Cached history remains readable; write controls require a successful current+ // detail read in this mount/owner/install generation, never a cached grant.+ const [writeRead, setWriteRead] = useState<string | null>(null);+ const [localRead, setLocalRead] = useState<string | null>(null);+ const writeKey = JSON.stringify([ownerKey, selectedId, installedRevision]);+ const currentWriteKey = useRef(writeKey);+ currentWriteKey.current = writeKey;+ const historyOpen = historyOpenKey === JSON.stringify([ownerKey, selectedId]);+ const writeReady = writeRead === writeKey && navigator.onLine;+ const snapshots = ownerMatches ? storedSnapshots : {};+ const snapshotLoading = ownerMatches ? storedSnapshotLoading : null;+ const query = ownerMatches ? storedQuery : '';+ const filter = ownerMatches ? storedFilter : 'all';+ const page = ownerMatches ? storedPage : null;+ const detail = ownerMatches ? storedDetail : null;+ const failure = ownerMatches ? storedFailure : null;+ const loading = ownerMatches && storedLoading;+ const request = useRef(0);+ const mounted = useRef(true);+ const currentOwner = useRef(ownerKey);+ currentOwner.current = ownerKey;+ const lastRefresh = useRef(0);+ const listScroll = useRef(saved.scroll ?? 0);+ const pageKey = useRef(JSON.stringify([query, filter]));+ const scrollFrame = useRef<HTMLElement>(null);+ const { scrolled, onScroll } = usePluginDetailScrolled();+ const personal = mode === 'cloud' && user?.membershipKind === 'personal';+ const pickerOpen = personal && ownerMatches && pickerOwner === ownerKey && !selectedId;+ const pickerReadKey = JSON.stringify([ownerKey, installedRevision, submissionRevision]);+ const pickerRead = pickerPlugins?.key === pickerReadKey ? pickerPlugins : null;+ const pickerReady = Boolean(pickerRead && !pickerRead.failure);+ const pickerItem = localPlugins.find(item => item.id === pickerSelection);+ const pickerVersion = pickerItem?.version;+ const pickerKey = JSON.stringify([ownerKey, location.key, pickerOpen, pickerSelection,+ pickerVersion, installedRevision, pickerRefresh]);+ const pickerContext = useRef({ key: pickerKey, token: {} });+ if (pickerContext.current.key !== pickerKey) pickerContext.current = { key: pickerKey, token: {} };+ const currentPickerDraft = pickerDraft?.key === pickerKey ? pickerDraft : null;+ const pickerBlocker = currentPickerDraft?.prepared?.preflight?.blockers[0];+ const pickerUnavailable = (local: GhostPluginListItem) => {+ const plugin = pickerRead?.plugins.find(item => item.localInstanceId === local.id);+ if (!plugin) return null;+ if (plugin.publisherKind === 'official') return `${copy}.unavailable.officialGithubRequired`;+ if (!plugin.actions.submitUpdate) return `${copy}.permissionDenied`;+ if (plugin.latestSubmission?.reviewStatus === 'pending' && plugin.latestSubmission.revisionState === 'current')+ return `${copy}.errors.PLUGIN_PENDING_RELEASE_EXISTS`;+ if (plugin.market.version === local.version || plugin.latestSubmission?.version === local.version)+ return `${copy}.errors.VERSION_ALREADY_SUBMITTED`;+ return null;+ };+ const selectedPickerUnavailable = pickerItem ? pickerUnavailable(pickerItem) : null;++ useEffect(() => {+ let disposed = false;+ setPickerPlugins(null);+ if (!pickerOpen || !localPlugins.length) return;+ // Read version facts once for this dialog, independently of the list's search+ // and pagination. Do not prepare packages just to render the choices.+ void (async () => {+ const plugins: MyPluginView[] = [];+ const cursors = new Set<string>();+ let cursor: string | undefined;+ do {+ const page = await reader.list({ query: '', filter: 'all', cursor });+ if (disposed) return;+ plugins.push(...page.plugins);+ cursor = page.nextCursor ?? undefined;+ if (cursor && cursors.has(cursor)) throw new Error('Repeated contribution cursor');+ if (cursor) cursors.add(cursor);+ } while (cursor);+ setPickerPlugins({ key: pickerReadKey, plugins });+ })().catch(error => {+ if (!disposed) setPickerPlugins({ key: pickerReadKey, plugins: [], failure: contributionErrorKey(error) });+ });+ return () => { disposed = true; };+ }, [pickerOpen, pickerReadKey, reader, localPlugins.length]);++ useEffect(() => {+ let disposed = false;+ let held: string | undefined;+ setPickerDraft(null);+ if (!pickerOpen || !pickerSelection || pickerVersion === undefined) return;+ const token = pickerContext.current.token;+ void Promise.resolve().then(() => preparePicker.current(pickerSelection)).then(prepared => {+ held = prepared.preparedId;+ if (disposed || pickerContext.current.token !== token) {+ void reader.discard(prepared.preparedId).catch(() => undefined);+ return;+ }+ if (prepared.instanceId !== pickerSelection || prepared.version !== pickerVersion) {+ void reader.discard(prepared.preparedId).catch(() => undefined);+ held = undefined;+ setPickerDraft({ key: pickerKey, error: `${copy}.errors.CONTRIBUTION_PACKAGE_CHANGED` });+ return;+ }+ setPickerDraft({ key: pickerKey, prepared });+ }).catch(error => {+ if (!disposed && pickerContext.current.token === token)+ setPickerDraft({ key: pickerKey, error: contributionErrorKey(error) });+ });+ return () => {+ disposed = true;+ if (held) void reader.discard(held).catch(() => undefined);+ };+ }, [pickerKey, pickerOpen, pickerSelection, pickerVersion, reader]);++ useEffect(() => { setPickerOwner(null); }, [selectedId]);++ useEffect(() => {+ mounted.current = true;+ return () => {+ mounted.current = false;+ request.current++;+ versionRequest.current++;+ snapshotRequest.current++;+ publishedRequest.current++;+ };+ }, []);+ useEffect(() => {+ if (!ownerMatches || (cache.ownerKey !== ownerKey && cache.ownerKey !== undefined)) {+ request.current++;+ setPage(null);+ setDetail(null);+ setInstallationRead(null);+ setFailure(null);+ setPickerOwner(null);+ setPublishedContent(null);+ setHistoryOpenKey(null);+ setSnapshots({});+ setVersionPage(null);+ setSelectedRelease(undefined);+ setVersionsLoading(false);+ setVersionFailure(null);+ cancelling.current = null;+ setCancelBusy(false);+ setCancelResult(null);+ versionRequest.current++;+ snapshotRequest.current++;+ setSnapshotLoading(null);+ setLoading(false);+ setQuery('');+ setFilter('all');+ listScroll.current = 0;+ Object.assign(cache, {+ query: '',+ filter: 'all',+ page: null,+ detail: null,+ installationRevision: undefined,+ scroll: 0,+ selectedRelease: undefined,+ });+ }+ cache.ownerKey = ownerKey;+ setLoadedOwner(ownerKey);+ }, [ownerKey, ownerMatches, cache]);+ useEffect(() => {+ if (ownerMatches && cache.ownerKey === ownerKey)+ Object.assign(cache, {+ query,+ filter,+ page,+ detail,+ installationRevision: installationRead?.owner === ownerKey && installationRead.pluginId === detail?.plugin.pluginId+ ? installationRead.revision : undefined,+ scroll: listScroll.current,+ selectedRelease,+ });+ }, [cache, ownerKey, ownerMatches, query, filter, page, detail, selectedRelease, installationRead]);++ const refresh = useCallback(+ async (cursor?: string) => {+ if (!personal || !ownerMatches) return;+ const id = ++request.current;+ const owner = ownerKey;+ setLoading(true);+ setWriteRead(null);+ try {+ if (selectedId) {+ const result = await reader.detail(selectedId, cursor);+ if (!mounted.current || request.current !== id || currentOwner.current !== owner) return;+ setInstallationRead({ owner, pluginId: selectedId, revision: installedRevision });+ setWriteRead(JSON.stringify([owner, selectedId, installedRevision]));+ setLocalRead(JSON.stringify([owner, selectedId, installedRevision]));+ setDetail((previous) =>+ cursor && previous?.plugin.pluginId === selectedId+ ? {+ ...result,+ history: [...previous.history, ...result.history].filter(+ (item, index, all) =>+ all.findIndex((entry) => entry.eventId === item.eventId) === index,+ ),+ }+ : result,+ );+ } else {+ const result = await reader.list({ query, filter, ...(cursor ? { cursor } : {}) });+ if (!mounted.current || request.current !== id || currentOwner.current !== owner) return;+ setListInstallationRead(JSON.stringify([owner, installedRevision]));+ setPage((previous) =>+ cursor && previous+ ? {+ ...result,+ plugins: [...previous.plugins, ...result.plugins].filter(+ (item, index, all) =>+ all.findIndex((entry) => entry.pluginId === item.pluginId) === index,+ ),+ }+ : result,+ );+ }+ lastRefresh.current = Date.now();+ void reviewUpdates.refresh();+ setFailure(null);+ } catch (error) {+ if (mounted.current && request.current === id && currentOwner.current === owner) {+ setLocalRead(null);+ setListInstallationRead(null);+ setFailure(contributionErrorKey(error));+ }+ } finally {+ if (mounted.current && request.current === id && currentOwner.current === owner)+ setLoading(false);+ }+ },+ [reader, selectedId, query, filter, ownerKey, personal, ownerMatches, reviewUpdates.refresh, installedRevision],+ );++ useEffect(() => {+ // Invalidate old requests immediately when the search changes; do not show a+ // previous query as if it were the result of the new server-side filter.+ request.current++;+ const nextKey = JSON.stringify([query, filter]);+ if (pageKey.current !== nextKey) {+ setPage(null);+ listScroll.current = 0;+ pageKey.current = nextKey;+ }+ if (!selectedId) {+ /* Retain this account's list while returning from a detail. */+ } else setDetail((current) => (current?.plugin.pluginId === selectedId ? current : null));+ const timer = window.setTimeout(() => void refresh(), query ? 200 : 0);+ return () => {+ window.clearTimeout(timer);+ request.current++;+ };+ }, [refresh, selectedId, query, filter, submissionRevision]);+ const loadVersions = useCallback(+ async (cursor?: string) => {+ if (!selectedId || !personal || !ownerMatches) return;+ const sequence = ++versionRequest.current,+ owner = ownerKey,+ pluginId = selectedId;+ setVersionsLoading(true);+ try {+ const result = await reader.releases(pluginId, cursor);+ if (+ !mounted.current ||+ currentOwner.current !== owner ||+ selectedPlugin.current !== pluginId ||+ versionRequest.current !== sequence+ )+ return;+ setVersionPage((previous) => ({+ ...result,+ pluginId,+ releases: (cursor && previous?.pluginId === pluginId+ ? [...previous.releases, ...result.releases]+ : result.releases+ ).filter(+ (release, index, all) =>+ all.findIndex((candidate) => releaseKey(candidate) === releaseKey(release)) === index,+ ),+ }));+ setVersionFailure(null);+ } catch (error) {+ if (+ mounted.current &&+ currentOwner.current === owner &&+ selectedPlugin.current === pluginId &&+ versionRequest.current === sequence+ )+ setVersionFailure(contributionErrorKey(error));+ } finally {+ if (+ mounted.current &&+ currentOwner.current === owner &&+ versionRequest.current === sequence+ )+ setVersionsLoading(false);+ }+ },+ [selectedId, personal, ownerMatches, ownerKey, reader],+ );+ useEffect(() => {+ setVersionFailure(null);+ setSnapshotLoading(null);+ void loadVersions();+ return () => {+ versionRequest.current++;+ snapshotRequest.current++;+ };+ }, [loadVersions, submissionRevision]);+ const refreshAll = useCallback(async () => {+ await Promise.all([refresh(), loadVersions()]);+ }, [refresh, loadVersions]);+ const refreshAllRef = useRef(refreshAll);+ refreshAllRef.current = refreshAll;+ const acceptAuthorSettings = (result: MyPluginDetailView) => {+ request.current++;+ versionRequest.current++;+ snapshotRequest.current++;+ setLoading(false);+ setSnapshotLoading(null);+ // Keep the selected version and its content mounted during attribution refresh.+ // Hide cached author fields immediately when enabling anonymity; never invent+ // a historical nickname when disabling it. The selected snapshot is reread below.+ const projectAuthor = (release: ContributionReleaseView): ContributionReleaseView => {+ if (result.plugin.latestSubmission && releaseKey(release) === releaseKey(result.plugin.latestSubmission))+ return result.plugin.latestSubmission;+ return result.plugin.authorSettings?.anonymous && release.content+ ? { ...release, content: { ...release.content,+ manifestView: { ...release.content.manifestView, author: null } } }+ : release;+ };+ setSnapshots(previous => snapshotId && previous[snapshotId]+ ? { [snapshotId]: projectAuthor(previous[snapshotId]) } : {});+ setVersionPage(previous => previous ? { ...previous, releases: previous.releases.map(projectAuthor) } : previous);+ setDetail(result);+ setWriteRead(writeKey);+ setPage(previous => previous ? { ...previous, plugins: previous.plugins.map(item =>+ item.pluginId === result.plugin.pluginId ? result.plugin : item) } : previous);+ setFailure(null);+ // Anonymity does not change version summaries or pagination. Keep them rather+ // than replacing a selected older page with the first page of releases.+ if (!versionPage) void loadVersions();+ if (snapshotId && snapshotId !== result.plugin.latestSubmission?.submissionId) void loadSnapshot(snapshotId);+ };+ const reviewSignature = reviewUpdates.updates.map(item => item.key).sort().join('|');+ const lastReviewRefresh = useRef('');+ useEffect(() => {+ const signature = `${ownerKey}:${reviewSignature}`;+ if (!reviewSignature || lastReviewRefresh.current === signature) return;+ lastReviewRefresh.current = signature;+ void refreshAll();+ }, [ownerKey, reviewSignature, refreshAll]);+ useEffect(() => { setInstallBusy(false); }, [ownerKey, selectedId]);+ useEffect(() => { setHistoryOpenKey(null); }, [ownerKey, selectedId]);+ usePluginMarketForegroundRefresh(refreshAll, lastRefresh);+ useEffect(() => {+ const online = () => {+ if (document.visibilityState === 'visible') void refreshAll();+ };+ window.addEventListener('online', online);+ const offline = () => setWriteRead(null);+ window.addEventListener('offline', offline);+ return () => { window.removeEventListener('online', online); window.removeEventListener('offline', offline); };+ }, [refreshAll]);+ useLayoutEffect(() => {+ if (!selectedId && scrollFrame.current)+ scrollFrame.current.scrollTop = listScroll.current;+ }, [selectedId, page]);++ const loadSnapshot = useCallback(+ async (submissionId: string) => {+ if (!selectedId) return;+ const owner = ownerKey,+ pluginId = selectedId,+ sequence = ++snapshotRequest.current;+ setSnapshotLoading(submissionId);+ try {+ const result = await reader.submission(selectedId, submissionId);+ if (+ mounted.current &&+ currentOwner.current === owner &&+ selectedPlugin.current === pluginId &&+ snapshotRequest.current === sequence+ )+ setSnapshots((previous) => ({ ...previous, [submissionId]: result }));+ } catch (error) {+ if (+ mounted.current &&+ currentOwner.current === owner &&+ selectedPlugin.current === pluginId &&+ snapshotRequest.current === sequence+ )+ setFailure(contributionErrorKey(error));+ } finally {+ if (+ mounted.current &&+ currentOwner.current === owner &&+ snapshotRequest.current === sequence+ )+ setSnapshotLoading(null);+ }+ },+ [selectedId, ownerKey, reader],+ );++ const back = () => {+ if (selectedId) {+ const next = new URLSearchParams(params);+ next.delete('contribution');+ next.delete('contributionTransfer');+ setParams(next, { replace: true });+ } else onViewLocal();+ };+ const openDetail = (pluginId: string) => {+ if (scrollFrame.current) listScroll.current = scrollFrame.current.scrollTop;+ cache.scroll = listScroll.current;+ const next = new URLSearchParams(params);+ next.set('contribution', pluginId);+ next.delete('contributionTransfer');+ setParams(next);+ };+ const timestamp = selectedId ? detail?.queriedAt : page?.queriedAt;+ const formatDate = (value: string | null) =>+ value+ ? new Date(value).toLocaleString(i18n.resolvedLanguage ?? i18n.language)+ : t(`${copy}.timeUnavailable`);+ const status = (release: ContributionReleaseView, plugin?: MyPluginView) =>+ t(+ `${copy}.review.${+ release.reviewStatus === 'approved' &&+ plugin?.market.state === 'available' &&+ plugin.market.releaseId === release.releaseId+ ? 'published'+ : (release.reviewStatus ?? release.revisionState)+ }`,+ );++ const releaseContent = (release: ContributionReleaseView) => (+ <>+ {release.content ? (+ <div className="space-y-3 text-14 leading-6 text-[var(--text-primary)]">+ <div className="flex items-center gap-3">+ <GhostPluginIcon+ iconDataUrl={release.content.iconUrl ?? undefined}+ iconId={release.releaseId}+ iconName={release.content.name}+ />+ <p className="font-medium">{release.content.name}</p>+ </div>+ <p className="whitespace-pre-wrap break-words">{release.content.description}</p>+ {release.content.permissions.length > 0 ? (+ <ul className="list-inside list-disc">+ {release.content.permissions.map((permission) => (+ <li key={permission.key}>+ {t(`settings.ghosts.perm.${permission.labelKey}`, permission.labelArgs)}+ {permission.detailKey ? (+ <p className="text-13 text-[var(--text-secondary)]">+ {t(`settings.ghosts.perm.${permission.detailKey}`, permission.detailArgs)}+ </p>+ ) : null}+ {permission.detail ? (+ <p className="whitespace-pre-wrap text-13 text-[var(--text-secondary)]">+ {permission.detail}+ </p>+ ) : null}+ </li>+ ))}+ </ul>+ ) : null}+ </div>+ ) : (+ <p className="text-13 text-[var(--text-secondary)]">{t(`${copy}.snapshotUnavailable`)}</p>+ )}+ <p className="mt-3 text-12 text-[var(--text-secondary)]">+ {formatDate(release.submittedAt)}+ {release.source+ ? ` · ${t(`${copy}.source.${release.source}`, { defaultValue: t(`${copy}.source.unknown`) })}`+ : ''}+ </p>+ <details className="mt-3 text-12 text-[var(--text-secondary)]">+ <summary className="cursor-pointer select-none">{t(`${copy}.technicalDetails`)}</summary>+ <dl className="mt-2 space-y-1 break-all">+ <dt>{t(`${copy}.releaseSha`)}</dt>+ <dd>{release.sha256}</dd>+ {release.uploadedSha256 ? (+ <>+ <dt>{t(`${copy}.uploadedSha`)}</dt>+ <dd>{release.uploadedSha256}</dd>+ </>+ ) : null}+ <dt>{t(`${copy}.releaseId`)}</dt>+ <dd>{release.releaseId}</dd>+ <dt>{t(`${copy}.revision`)}</dt>+ <dd>{release.revision}</dd>+ </dl>+ {release.content ? (+ <pre className="mt-3 whitespace-pre-wrap break-words">+ {JSON.stringify(release.content.manifestView, null, 2)}+ </pre>+ ) : null}+ </details>+ </>+ );++ const currentDetail = detail?.plugin.pluginId === selectedId ? detail : null;+ const plugin = currentDetail?.plugin;+ // A cached author detail must not select a replacement installation before Main+ // has rechecked its exact source and approval in this installation generation.+ const installationIsCurrent = installedRevision === undefined ||+ (installationRead?.owner === ownerKey && installationRead.pluginId === selectedId &&+ installationRead.revision === installedRevision);+ const localInstallation = installationIsCurrent && localRead === writeKey && navigator.onLine+ ? plugin?.localInstallation : undefined;+ const installedLocal = localInstallation?.state === 'installed' ? localInstallation : null;+ const publishedKey = JSON.stringify([writeKey, plugin?.market.releaseId, plugin?.market.version]);+ useEffect(() => {+ const sequence = ++publishedRequest.current;+ if (!plugin || plugin.market.state !== 'available' || !plugin.market.releaseId || !onReadPublished) {+ setPublishedContent(null);+ return;+ }+ const key = publishedKey, expected = plugin.market, pluginId = plugin.pluginId, requestKey = writeKey;+ setPublishedContent(previous => ({ key, value: previous?.key === key ? previous.value : null, loading: true }));+ void onReadPublished(pluginId).then(value => {+ if (!mounted.current || publishedRequest.current !== sequence || currentWriteKey.current !== requestKey) return;+ const exact = value.pluginId === pluginId && value.releaseId === expected.releaseId &&+ value.version === expected.version && value.sourceType === 'server' && value.scope === 'public';+ setPublishedContent({ key, value: exact ? value : null, loading: false });+ }).catch(() => {+ if (mounted.current && publishedRequest.current === sequence && currentWriteKey.current === requestKey)+ setPublishedContent({ key, value: null, loading: false });+ });+ return () => { publishedRequest.current++; };+ }, [publishedKey, onReadPublished, plugin, currentDetail?.queriedAt, writeKey]);+ const candidates =+ ownerMatches && versionPage?.pluginId === selectedId ? versionPage.releases : [];+ const latest = plugin?.latestSubmission ? [plugin.latestSubmission] : [];+ const unreadReview = reviewUpdates.updates.find(item => item.pluginId === selectedId && item.unread);+ const unreadRelease = unreadReview && [...latest, ...candidates].find(item =>+ item.releaseId === unreadReview.releaseId && item.sha256 === unreadReview.sha256 && item.revision === unreadReview.revision);+ const detailIsNewer =+ !versionPage || Date.parse(currentDetail?.queriedAt ?? '') >= Date.parse(versionPage.queriedAt);+ const releases = (detailIsNewer ? [...latest, ...candidates] : [...candidates, ...latest]).filter(+ (release, index, all) =>+ all.findIndex((entry) => releaseKey(entry) === releaseKey(release)) === index,+ );+ const selectedSummary =+ (selectedRelease?.pluginId === selectedId+ ? releases.find((release) => releaseKey(release) === selectedRelease.key)+ : null) ??+ unreadRelease ??+ releases.find(+ (release) =>+ plugin?.latestSubmission && releaseKey(release) === releaseKey(plugin.latestSubmission),+ ) ??+ releases[0];+ const snapshot = selectedSummary?.submissionId ? snapshots[selectedSummary.submissionId] : null;+ const shownRelease =+ selectedSummary && snapshot && releaseKey(snapshot) === releaseKey(selectedSummary)+ ? { ...selectedSummary, content: snapshot.content }+ : selectedSummary &&+ plugin?.latestSubmission &&+ releaseKey(plugin.latestSubmission) === releaseKey(selectedSummary)+ ? { ...selectedSummary, content: plugin.latestSubmission.content }+ : selectedSummary;+ const selectedKey = selectedSummary ? releaseKey(selectedSummary) : null;+ const snapshotId = selectedSummary?.submissionId;+ const hasContent = Boolean(shownRelease?.content);+ const visibleRelease = historyOpen ? shownRelease : plugin?.latestSubmission;+ const visibleReview = unreadReview && visibleRelease && currentDetail &&+ visibleRelease.releaseId === unreadReview.releaseId && visibleRelease.sha256 === unreadReview.sha256 &&+ visibleRelease.revision === unreadReview.revision && visibleRelease.reviewStatus === unreadReview.status &&+ visibleRelease.reviewedAt === unreadReview.decidedAt ? unreadReview : null;+ const visibleReviewKey = visibleReview?.key;+ const visibleReviewPlugin = visibleReview?.pluginId;+ const visibleReleaseKey = visibleRelease ? releaseKey(visibleRelease) : null;+ useEffect(() => {+ if (!visibleReviewKey || !visibleReviewPlugin || !visibleReleaseKey || document.visibilityState !== 'visible') return;+ // Keep the exact result selected after acknowledging it; do not jump to a newer pending version.+ setSelectedRelease(previous => previous?.pluginId === visibleReviewPlugin && previous.key === visibleReleaseKey+ ? previous : { pluginId: visibleReviewPlugin, key: visibleReleaseKey });+ void reviewUpdates.markRead(visibleReviewPlugin, visibleReviewKey);+ }, [visibleReviewKey, visibleReviewPlugin, visibleReleaseKey, reviewUpdates.markRead]);+ const openUnreadResult = async () => {+ if (!unreadReview) return;+ const target = unreadReview, owner = ownerKey, sequence = ++versionRequest.current;+ setVersionsLoading(true);+ try {+ const collected: ContributionReleaseView[] = [];+ let cursor: string | undefined;+ for (;;) {+ const result = await reader.releases(target.pluginId, cursor);+ if (!mounted.current || currentOwner.current !== owner || selectedPlugin.current !== target.pluginId ||+ versionRequest.current !== sequence) return;+ collected.push(...result.releases);+ const match = collected.find(item => item.releaseId === target.releaseId && item.sha256 === target.sha256 &&+ item.revision === target.revision);+ if (match || !result.nextCursor) {+ setVersionPage({ ...result, pluginId: target.pluginId, releases: collected });+ if (match) {+ setSelectedRelease({ pluginId: target.pluginId, key: releaseKey(match) });+ setHistoryOpenKey(JSON.stringify([owner, target.pluginId]));+ setVersionFailure(null);+ } else setVersionFailure(`${copy}.loadFailed`);+ return;+ }+ cursor = result.nextCursor;+ }+ } catch (error) {+ if (mounted.current && currentOwner.current === owner && versionRequest.current === sequence)+ setVersionFailure(contributionErrorKey(error));+ } finally {+ if (mounted.current && currentOwner.current === owner && versionRequest.current === sequence)+ setVersionsLoading(false);+ }+ };+ const latestSnapshot = plugin?.latestSubmission?.submissionId ? snapshots[plugin.latestSubmission.submissionId] : null;+ const currentSubmission = plugin?.latestSubmission && latestSnapshot && releaseKey(latestSnapshot) === releaseKey(plugin.latestSubmission)+ ? { ...plugin.latestSubmission, content: latestSnapshot.content } : plugin?.latestSubmission;+ const visibleSnapshotId = historyOpen ? snapshotId : currentSubmission?.submissionId;+ const visibleHasContent = historyOpen ? hasContent : Boolean(currentSubmission?.content);+ useEffect(() => {+ snapshotRequest.current++;+ setSnapshotLoading(null);+ if (visibleSnapshotId && !visibleHasContent) void loadSnapshot(visibleSnapshotId);+ }, [selectedKey, visibleSnapshotId, visibleHasContent, loadSnapshot, historyOpen]);+ const isDetail = Boolean(selectedId);+ const listEmpty = page?.plugins.length === 0;+ const rowAction = (+ <span className="my-plugins-chevron inline-flex items-center justify-end gap-1 text-13 text-[var(--text-secondary)]">+ {t(`${copy}.versionManagement`)}+ <ChevronRight size={16} className="shrink-0" aria-hidden="true" />+ </span>+ );+ const cancelReview = async (plugin: MyPluginView, release: ContributionReleaseView) => {+ if (cancelling.current || !writeReady || !plugin.actions.submitUpdate || !release.canCancelReview || !navigator.onLine) return;+ const owner = ownerKey;+ const cancellation = Symbol('cancel-review');+ cancelling.current = cancellation;+ setCancelBusy(true);+ try {+ const accepted = await confirm({+ title: t(`${copy}.cancelReviewTitle`, { name: plugin.name, version: release.version }),+ description: t(`${copy}.cancelReviewDescription`, { version: release.version }),+ confirmText: t(`${copy}.cancelReview`),+ cancelText: t(`${copy}.keepReview`),+ });+ if (+ !accepted ||+ !mounted.current ||+ currentOwner.current !== owner ||+ selectedPlugin.current !== plugin.pluginId+ )+ return;+ const result = await reader.cancelReview(plugin.pluginId, {+ releaseId: release.releaseId,+ sha256: release.sha256,+ revision: release.revision,+ });+ if (!mounted.current || currentOwner.current !== owner) return;+ setCancelResult({+ owner,+ pluginId: plugin.pluginId,+ releaseId: result.releaseId,+ cancelled: result.reviewStatus === 'cancelled',+ });+ // Keep the selected version; the subsequent read supplies its actual final decision.+ setVersionPage((previous) =>+ previous?.pluginId === plugin.pluginId+ ? {+ ...previous,+ releases: previous.releases.map((entry) =>+ entry.releaseId === result.releaseId+ ? { ...result, content: entry.content }+ : entry,+ ),+ }+ : previous,+ );+ await refreshAllRef.current();+ } catch (error) {+ if (mounted.current && currentOwner.current === owner)+ setFailure(contributionErrorKey(error));+ } finally {+ if (cancelling.current === cancellation) {+ cancelling.current = null;+ if (mounted.current && currentOwner.current === owner) setCancelBusy(false);+ }+ }+ };+ const chooseRelease = (key: string) => {+ if (!selectedId) return;+ const release = releases.find((entry) => releaseKey(entry) === key);+ if (!release) return;+ setSelectedRelease({ pluginId: selectedId, key });+ };+ const reviewTimes = (release: ContributionReleaseView) => (+ <dl className="flex flex-wrap gap-x-6 gap-y-2 text-12 leading-5 text-[var(--text-tertiary)]">+ <div className="flex flex-wrap gap-x-2">+ <dt>{t(`${copy}.submittedAt`)}</dt>+ <dd>{formatDate(release.submittedAt)}</dd>+ </div>+ {release.reviewStatus === 'approved' ? (+ <div className="flex flex-wrap gap-x-2">+ <dt>{t(`${copy}.approvedAt`)}</dt>+ <dd>{release.approvedAt ? formatDate(release.approvedAt) : t(`${copy}.timeUnavailable`)}</dd>+ </div>+ ) : null}+ {release.cancelledAt ? (+ <div className="flex flex-wrap gap-x-2">+ <dt>{t(`${copy}.cancelledAt`)}</dt>+ <dd>{formatDate(release.cancelledAt)}</dd>+ </div>+ ) : null}+ </dl>+ );+ const refreshButton = (+ <Tip text={t(`${copy}.${isDetail ? 'refreshDetail' : 'refreshList'}`)}>+ <Button+ variant="secondary"+ tone="quiet"+ size="sm"+ className="size-7 p-0"+ aria-label={t(`${copy}.${isDetail ? 'refreshDetail' : 'refreshList'}`)}+ loading={loading || versionsLoading}+ disabled={!personal}+ onClick={() => void refreshAll()}+ >+ <RotateCw size={16} />+ </Button>+ </Tip>+ );+ const notes = shownRelease?.content?.manifestView.releaseNotes;++ const anonymity = personal && isDetail && plugin && plugin.publisherKind !== 'official' ? (+ <PluginAnonymityControl key={JSON.stringify([ownerKey, plugin.pluginId])}+ ownerKey={ownerKey} pluginId={plugin.pluginId} settings={plugin.authorSettings}+ reader={reader} unavailable={!plugin.authorSettings} disabled={!writeReady}+ onBeforeChange={() => {+ request.current++; versionRequest.current++; snapshotRequest.current++;+ setLoading(false); setVersionsLoading(false); setSnapshotLoading(null);+ }} onCommitted={onAuthorSettingsUpdated} onUpdated={acceptAuthorSettings} />+ ) : null;+ const factsPlugin = plugin ? { ...plugin, localInstallation: localInstallation ?? { state: 'unavailable' as const } } : null;+ const versions = factsPlugin ? renderVersionFacts?.(factsPlugin) ?? <PluginVersionFacts plugin={factsPlugin} /> : null;+ const knownPublishBlocker = installedLocal && (+ plugin?.latestSubmission?.reviewStatus === 'pending' && plugin.latestSubmission.revisionState === 'current'+ ? 'PLUGIN_PENDING_RELEASE_EXISTS'+ : releases.some(release => release.version === installedLocal.version) ? 'VERSION_ALREADY_SUBMITTED' : null+ );+ const localCanSubmit = installedLocal && localPlugins.some(item => item.id === installedLocal.instanceId);+ const updateUnavailable = plugin?.publisherKind === 'official' ? t(`${copy}.unavailable.officialGithubRequired`)+ : knownPublishBlocker ? t(`${copy}.errors.${knownPublishBlocker}`) : undefined;+ const published = publishedContent?.key === publishedKey ? publishedContent : null;+ const listedDetail = plugin?.market.state === 'available' ? published?.value : null;+ const currentNotes = currentSubmission?.content?.manifestView.releaseNotes;+ const publishingContent = currentDetail && plugin ? (+ <div className="space-y-6 pb-8">+ <section aria-label={t(`${copy}.localVersion`)} className="space-y-3">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="space-y-1">+ <h2 className="text-16 font-medium leading-6 text-[var(--text-primary)]">{t(`${copy}.localVersion`)}</h2>+ <p className="text-14 leading-6 text-[var(--text-secondary)]">+ {installedLocal ? `${installedLocal.version} · ${t(`settings.ghosts.page.origin.${installedLocal.origin}`)} · ${t(`${copy}.${installedLocal.enabled ? 'localEnabled' : 'localDisabled'}`)}`+ : t(`${copy}.localState.${localInstallation?.state ?? 'unavailable'}`)}+ </p>+ </div>+ <div className="flex flex-wrap items-center gap-2">+ {installedLocal && localCanSubmit && plugin.actions.submitUpdate && writeReady && !updateUnavailable ? (+ <Button variant="cta" size="sm" loading={submitBusy} disabled={submitBusy}+ onClick={() => void onSubmitUpdate(installedLocal.instanceId)}>{t(`${copy}.submitVersion`, { version: installedLocal.version })}</Button>+ ) : null}+ {localInstallation?.state === 'missing' && plugin.market.state === 'available' && onInstallPublished && writeReady ? (+ <Button variant="secondary" size="sm" loading={installBusy} disabled={installBusy}+ onClick={() => {+ const key = writeKey, owner = ownerKey, pluginId = plugin.pluginId;+ setInstallBusy(true);+ void onInstallPublished(plugin.pluginId).then(() => {+ if (mounted.current && currentOwner.current === owner && selectedPlugin.current === pluginId) void refreshAllRef.current();+ }).catch(error => {+ if (mounted.current && currentWriteKey.current === key) setFailure(contributionErrorKey(error));+ }).finally(() => {+ if (mounted.current && currentOwner.current === owner && selectedPlugin.current === pluginId) setInstallBusy(false);+ });+ }}>{t(`${copy}.installPublished`)}</Button>+ ) : null}+ </div>+ </div>+ {updateUnavailable && (installedLocal || plugin.publisherKind === 'official') ? <p role="status" className="text-12 leading-5 text-[var(--text-tertiary)]">{updateUnavailable}</p> : null}+ </section>+ <section aria-label={t(`${copy}.listedVersion`)} className="space-y-3 border-t border-[var(--border-default)] pt-5">+ <h2 className="text-16 font-medium leading-6 text-[var(--text-primary)]">+ {t(`${copy}.listedVersion`)}{plugin.market.state === 'available' ? ` · ${plugin.market.version}` : ''}+ </h2>+ {plugin.market.state !== 'available' ? <p className="text-14 leading-6 text-[var(--text-secondary)]">{t(`${copy}.market.${plugin.market.state}`)}</p>+ : published?.value ? <>+ <p className="select-text whitespace-pre-wrap break-words text-14 leading-6 text-[var(--text-primary)]">{published.value.description || published.value.manifest.description}</p>+ <h3 className="text-13 font-medium leading-5 text-[var(--text-secondary)]">{t(`${copy}.releaseNotes`)}</h3>+ <p className="select-text whitespace-pre-wrap break-words text-14 leading-6 text-[var(--text-primary)]">{published.value.manifest.releaseNotes?.trim() || t(`${copy}.notesMissing`)}</p>+ </> : <p role="status" className="text-14 leading-6 text-[var(--text-secondary)]">{t(`${copy}.${published?.loading ? 'loading' : 'publishedContentUnavailable'}`)}</p>}+ {plugin.market.reason ? <p className="select-text whitespace-pre-wrap break-words text-14 leading-6 text-[var(--text-secondary)]">{plugin.market.reason}</p> : null}+ </section>+ <section aria-label={t(`${copy}.currentSubmission`)} className="space-y-3 border-t border-[var(--border-default)] pt-5">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <h2 className="text-16 font-medium leading-6 text-[var(--text-primary)]">{t(`${copy}.currentSubmission`)}</h2>+ {currentSubmission?.canCancelReview && plugin.actions.submitUpdate && writeReady ? (+ <Button variant="secondary" size="sm" loading={cancelBusy} disabled={cancelBusy}+ onClick={() => void cancelReview(plugin, currentSubmission)}>{t(`${copy}.cancelReview`)}</Button>+ ) : null}+ </div>+ {currentSubmission ? <>+ <p className="flex flex-wrap gap-x-2 text-14 leading-6 text-[var(--text-primary)]"><span>{currentSubmission.version}</span><span aria-hidden="true">·</span><span>{status(currentSubmission, plugin)}</span></p>+ {reviewTimes(currentSubmission)}+ {cancelResult?.owner === ownerKey && cancelResult.pluginId === plugin.pluginId && cancelResult.releaseId === currentSubmission.releaseId ? (+ <p role="status" className="text-13 leading-5 text-[var(--text-secondary)]">{t(`${copy}.${cancelResult.cancelled ? 'cancelReviewCompleted' : 'cancelReviewAlreadyFinal'}`)}</p>+ ) : null}+ {currentSubmission.reason ? <p className="select-text whitespace-pre-wrap break-words text-14 leading-6 text-[var(--text-primary)]">{currentSubmission.reason}</p> : null}+ <h3 className="text-13 font-medium leading-5 text-[var(--text-secondary)]">{t(`${copy}.releaseNotes`)}</h3>+ <p className="select-text whitespace-pre-wrap break-words text-14 leading-6 text-[var(--text-primary)]">+ {typeof currentNotes === 'string' && currentNotes.trim() ? currentNotes : t(`${copy}.${currentSubmission.content ? 'notesMissing' : 'snapshotUnavailable'}`)}+ </p>+ <details className="group/current">+ <summary className="flex cursor-pointer list-none items-center gap-2 text-13 font-medium leading-5 text-[var(--text-secondary)] [&::-webkit-details-marker]:hidden">+ <ChevronRight size={14} aria-hidden="true" className="shrink-0 group-open/current:rotate-90" />{t(`${copy}.submittedContent`)}+ </summary>+ <div className="pt-3">{releaseContent(currentSubmission)}</div>+ </details>+ </> : <p className="text-14 leading-6 text-[var(--text-secondary)]">{t(`${copy}.noSubmission`)}</p>}+ </section>+ {unreadReview && !visibleReview ? (+ <Button variant="secondary" size="sm" loading={versionsLoading}+ disabled={versionsLoading || !navigator.onLine} onClick={() => void openUnreadResult()}>+ <AttentionDot tone={unreadReview.status === 'rejected' ? 'error' : 'done'} />+ {t(`${copy}.viewReviewResult`, { version: unreadReview.version })}+ </Button>+ ) : null}+ {versionFailure ? (+ <p role="alert" className="text-13 text-[var(--text-secondary)]">+ {t(versionFailure, { defaultValue: t(`${copy}.loadFailed`) })}+ </p>+ ) : null}+ <details key={JSON.stringify([ownerKey, selectedId])} open={historyOpen}+ onToggle={event => setHistoryOpenKey(event.currentTarget.open ? JSON.stringify([ownerKey, selectedId]) : null)}+ className="group/history border-t border-[var(--border-default)] pt-4">+ <summary className="flex cursor-pointer list-none items-center gap-2 text-13 font-medium leading-5 text-[var(--text-secondary)] [&::-webkit-details-marker]:hidden">+ <ChevronRight size={14} aria-hidden="true" className="shrink-0 group-open/history:rotate-90" />+ {t(`${copy}.history`)}+ </summary>+ {historyOpen ? <div className="space-y-4 pt-4">+ {shownRelease ? (+ <section className="space-y-4" aria-label={t(`${copy}.versionContent`)}>+ <div className="flex min-w-0 flex-wrap items-center justify-between gap-x-4 gap-y-3">+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <span className="text-14 text-[var(--text-primary)]">+ {t(`${copy}.version`)}+ </span>+ {releases.length > 1 ? (+ <Select+ label={t(`${copy}.chooseVersion`)}+ value={releaseKey(shownRelease)}+ options={releases.map((release) => ({+ value: releaseKey(release),+ label: release.version,+ title: release.version,+ endAdornment: (+ <span className="text-12 text-[var(--text-tertiary)]">+ {status(release, plugin)}+ </span>+ ),+ }))}+ onValueChange={chooseRelease}+ truncateOptions+ className="h-8 w-28 min-w-0 gap-3 font-normal"+ contentClassName="min-w-[240px] max-w-[calc(100vw-16px)]"+ aria-describedby="my-plugin-version-status"+ />+ ) : (+ <span className="min-w-0 break-words text-14 text-[var(--text-primary)]">+ {shownRelease.version}+ </span>+ )}+ <span+ id="my-plugin-version-status"+ className="rounded-full bg-[var(--surface-chip)] px-2 py-0.5 text-12 text-[var(--text-primary)]"+ >+ {status(shownRelease, plugin)}+ </span>+ </div>+ </div>+ {reviewTimes(shownRelease)}+ {shownRelease.reason ? (+ <section className="space-y-2">+ <h3 className="text-13 font-medium text-[var(--text-primary)]">+ {t(`${copy}.reason`)}+ </h3>+ <p className="select-text whitespace-pre-wrap break-words text-14 leading-6 text-[var(--text-primary)]">+ {shownRelease.reason}+ </p>+ </section>+ ) : null}+ {snapshotLoading === shownRelease.submissionId && snapshotLoading && !shownRelease.content ? (+ <p role="status" className="text-13 text-[var(--text-tertiary)]">+ {t(`${copy}.loading`)}+ </p>+ ) : (+ <>+ <section className="space-y-3 pt-2">+ <div className="space-y-1">+ <h3 className="text-14 font-medium leading-5 text-[var(--text-primary)]">+ {t(`${copy}.releaseNotes`)}+ </h3>+ </div>+ <p className="select-text whitespace-pre-wrap break-words text-14 leading-6 text-[var(--text-primary)]">+ {typeof notes === 'string' && notes.trim()+ ? notes+ : t(+ `${copy}.${shownRelease.content ? 'notesMissing' : 'snapshotUnavailable'}`,+ )}+ </p>+ </section>+ <details className="group/version border-t border-[var(--border-default)] pt-4">+ <summary className="flex cursor-pointer list-none items-center gap-2 text-13 font-medium leading-5 text-[var(--text-secondary)] [&::-webkit-details-marker]:hidden">+ <ChevronRight size={14} aria-hidden="true" className="shrink-0 group-open/version:rotate-90" />+ {t(`${copy}.versionContent`)}+ </summary>+ <div className="pt-4">{releaseContent(shownRelease)}</div>+ </details>+ </>+ )}+ </section>+ ) : (+ <p className="text-14 text-[var(--text-tertiary)]">+ {t(`${copy}.noSubmission`)}+ </p>+ )}+ {versionPage?.pluginId === selectedId && versionPage.nextCursor ? (+ <Button+ variant="secondary"+ size="sm"+ compact+ loading={versionsLoading}+ onClick={() => void loadVersions(versionPage.nextCursor!)}+ >+ {t(`${copy}.loadMoreVersions`)}+ </Button>+ ) : null}+ {currentDetail.history.map((event) => (+ <article+ key={event.eventId}+ className="space-y-2 border-b border-[var(--border-default)] pb-4"+ >+ <p className="break-words text-14 text-[var(--text-primary)]">+ {event.version ? `${event.version} · ` : ''}+ {t(`${copy}.event.${event.type}`)}+ </p>+ <p className="text-12 text-[var(--text-tertiary)]">+ {formatDate(event.at)}+ </p>+ {event.reason ? (+ <p className="select-text whitespace-pre-wrap break-words text-14 leading-6 text-[var(--text-primary)]">+ {event.reason}+ </p>+ ) : null}+ {event.submissionId ? (+ <div>+ <Button+ variant="secondary"+ size="sm"+ compact+ loading={snapshotLoading === event.submissionId}+ onClick={() => void loadSnapshot(event.submissionId!)}+ >+ {t(`${copy}.submittedContent`)}+ </Button>+ {snapshots[event.submissionId] ? (+ <div className="mt-3">+ {releaseContent(snapshots[event.submissionId])}+ </div>+ ) : null}+ </div>+ ) : null}+ {event.revision ? (+ <details className="text-12 text-[var(--text-tertiary)]">+ <summary className="cursor-pointer select-none">+ {t(`${copy}.technicalDetails`)}+ </summary>+ <p className="mt-2 break-all">+ {event.revision.releaseId}+ <br />+ {event.revision.sha256}+ <br />+ {event.revision.displayUpdatedAt}+ </p>+ </details>+ ) : null}+ </article>+ ))}+ {currentDetail.nextCursor ? (+ <Button+ variant="secondary"+ loading={loading}+ onClick={() => void refresh(currentDetail.nextCursor!)}+ >+ {t(`${copy}.loadMoreHistory`)}+ </Button>+ ) : null}+ </div> : null}+ </details>+ </div>+ ) : null;+ const publishing = <section aria-label={t(`${copy}.versionManagement`)}>+ {currentSubmission?.content?.description ? <p className="mb-6 select-text whitespace-pre-wrap break-words text-14 leading-6 text-[var(--text-secondary)]">{currentSubmission.content.description}</p> : null}+ {versions ? <div className="mb-6">{versions}</div> : null}+ {publishingContent}+ </section>;++ return (+ <div className="flex h-full min-h-0 flex-col">+ <main+ ref={scrollFrame}+ className="app-wallpaper-surface min-h-0 flex-1 overflow-y-auto bg-[var(--surface)]"+ onScroll={(event) => {+ onScroll(event);+ if (!isDetail) listScroll.current = event.currentTarget.scrollTop;+ cache.scroll = listScroll.current;+ }}+ >+ <PluginDetailTopBar+ label={isDetail ? t(`${copy}.myPlugins`) : t('settings.ghosts.title')}+ onBack={back}+ scrolled={scrolled}+ frameClassName={PLUGIN_MANAGEMENT_FRAME_CLASS}+ />+ <PluginManagementPage className={isDetail ? 'pt-6' : undefined}>+ <header className={`flex min-w-0 flex-wrap justify-between gap-4 ${isDetail ? 'mb-6 items-start' : 'mb-5 items-center'}`}>+ <div className={`flex min-w-0 flex-1 gap-4 ${isDetail ? 'items-start' : 'items-center'}`}>+ {isDetail && plugin ? (+ <GhostPluginIcon+ iconDataUrl={plugin?.iconUrl ?? undefined}+ iconId={plugin.pluginId}+ iconName={plugin.name}+ size="detail"+ />+ ) : null}+ <div className="min-w-0">+ <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2">+ <h1 className={`min-w-0 break-words font-medium text-[var(--text-primary)] [overflow-wrap:anywhere] ${isDetail ? 'text-20 leading-7' : 'text-24 leading-8'}`}>+ {isDetail+ ? (plugin?.name ?? t(`${copy}.myPlugins`))+ : t(`${copy}.myPlugins`)}+ </h1>+ {anonymity}+ </div>+ {isDetail && plugin?.publisherKind === 'official' ? <div className="mt-1"><PluginPublisherBadge kind={plugin.publisherKind} /></div> : null}+ {isDetail && (plugin?.displayAuthor || listedDetail) ? (+ <div className="plugin-detail-metadata mt-2 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-13 leading-5 text-[var(--text-tertiary)]">+ {plugin?.displayAuthor ? <span className="min-w-0 break-words">{plugin.displayAuthor}</span> : null}+ {listedDetail ? <>+ {plugin?.displayAuthor ? <span aria-hidden="true">·</span> : null}+ <span>v{listedDetail.version}</span>+ <PluginSharedUsage detail={listedDetail} />+ </> : null}+ </div>+ ) : null}+ {!isDetail ? (+ <p className="mt-1 text-14 leading-6 text-[var(--text-tertiary)]">+ {t(`${copy}.intro`)}+ </p>+ ) : null}+ </div>+ </div>+ {!isDetail ? (+ <Button+ variant="cta"+ disabled={!personal || !ownerMatches}+ onClick={() => { setPickerPlugins(null); setPickerSelection(null); setPickerOwner(ownerKey); }}+ >+ <Plus size={16} />+ {t(`${copy}.publishPlugin`)}+ </Button>+ ) : (+ refreshButton+ )}+ </header>+ {!personal ? (+ <div className="space-y-4">+ <p role="status" className="text-14 leading-6 text-[var(--text-secondary)]">+ {t(`${copy}.personalRequired`)}+ </p>+ <Button+ ref={accountTrigger}+ variant="secondary"+ onClick={() => (mode === 'cloud' ? setAccountSwitcherOpen(true) : void signIn())}+ >+ {t(mode === 'cloud' ? 'sidebar.accountSwitcher.title' : 'login.signIn')}+ </Button>+ <AccountSwitcherDialog+ open={accountSwitcherOpen}+ onOpenChange={setAccountSwitcherOpen}+ triggerRef={accountTrigger}+ onAddAccount={() =>+ navigate('/add-account', {+ state: { returnTo: `${location.pathname}${location.search}` },+ })+ }+ />+ </div>+ ) : (+ <>+ {failure ? (+ <p+ role="alert"+ className="mb-4 whitespace-pre-wrap text-14 leading-6 text-[var(--text-secondary)]"+ >+ {t(failure, { defaultValue: t(`${copy}.loadFailed`) })}+ {timestamp ? ` · ${t(`${copy}.cachedResult`)}` : ''}+ </p>+ ) : null}+ {!isDetail ? (+ <>+ {!listEmpty || query || filter !== 'all' ? (+ <div className="mb-5 flex flex-wrap items-center gap-3">+ <Input+ size="sm"+ value={query}+ onChange={setQuery}+ placeholder={t(`${copy}.search`)}+ aria-label={t(`${copy}.search`)}+ className="min-w-0 max-w-xs"+ />+ <div className="flex flex-wrap gap-1" aria-label={t(`${copy}.filterLabel`)}>+ {(['all', 'pending', 'needs_action', 'published'] as const).map((value) => (+ <Button+ key={value}+ variant={filter === value ? 'primary' : 'secondary'}+ tone={filter === value ? 'default' : 'quiet'}+ size="sm"+ compact+ aria-pressed={filter === value}+ onClick={() => setFilter(value)}+ >+ {t(`${copy}.filter.${value}`)}+ </Button>+ ))}+ </div>+ <span className="ml-auto">{refreshButton}</span>+ </div>+ ) : null}+ {loading && !page ? (+ <p role="status" className="text-14 text-[var(--text-secondary)]">+ {t(`${copy}.loading`)}+ </p>+ ) : null}+ {listEmpty ? (+ <div className="flex min-h-72 flex-col items-center justify-center gap-4 py-8 text-center text-14 leading-6 text-[var(--text-tertiary)]">+ <p>{t(`${copy}.${query || filter !== 'all' ? 'noMatches' : 'empty'}`)}</p>+ {!query && filter === 'all' ? (+ <Button variant="secondary" onClick={onViewLocal}>+ {t(`${copy}.viewLocal`)}+ </Button>+ ) : null}+ </div>+ ) : null}+ {page?.plugins.length ? (+ <div className="my-plugins-table">+ <div+ className="my-plugins-columns border-b border-[var(--border-default)] pb-3 text-12 text-[var(--text-tertiary)]"+ aria-hidden="true"+ >+ <span>{t(`${copy}.pluginColumn`)}</span>+ <span>{t(`${copy}.localVersion`)}</span>+ <span>{t(`${copy}.currentMarket`)}</span>+ <span>{t(`${copy}.latestState`)}</span>+ <span />+ </div>+ {page?.plugins.map((entry) => {+ const local = listInstallationRead === JSON.stringify([ownerKey, installedRevision]) && navigator.onLine+ ? entry.localInstallation : undefined;+ const review = reviewUpdates.updates.find(item => item.pluginId === entry.pluginId && item.unread);+ return (+ <button+ type="button"+ key={entry.pluginId}+ className="my-plugins-row w-full border-b border-[var(--border-default)] py-5 text-left hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)]"+ onClick={() => openDetail(entry.pluginId)}+ >+ <span className="my-plugins-identity flex min-w-0 items-center gap-3">+ <GhostPluginIcon+ iconDataUrl={entry.iconUrl ?? undefined}+ iconId={entry.pluginId}+ iconName={entry.name}+ />+ <span className="min-w-0">+ <span className="block break-words text-16 font-medium leading-6 text-[var(--text-primary)]">{entry.name}</span>+ <PluginPublisherBadge kind={entry.publisherKind} />+ {entry.displayAuthor ? <span className="block break-words text-13 leading-5 text-[var(--text-tertiary)]">{entry.displayAuthor}</span> : null}+ </span>+ {review ? <span role="img" className="inline-flex" aria-label={t(`${copy}.unreadReview`)}><AttentionDot tone={review.status === 'rejected' ? 'error' : 'done'} /></span> : null}+ </span>+ <span className="my-plugins-local min-w-0 break-words text-13 leading-5 text-[var(--text-primary)]">+ <span className="my-plugins-mobile-label">{t(`${copy}.localVersion`)} ·{' '}</span>+ {local?.state === 'installed' ? local.version : t(`${copy}.localState.${local?.state ?? 'unavailable'}`)}+ </span>+ <span className="my-plugins-market min-w-0 break-words text-13 leading-5 text-[var(--text-tertiary)]">+ <span className="my-plugins-mobile-label">+ {t(`${copy}.currentMarket`)} ·{' '}+ </span>+ {entry.market.state === 'available'+ ? entry.market.version+ : t(`${copy}.market.${entry.market.state}`)}+ </span>+ <span className="my-plugins-latest min-w-0 break-words text-13 leading-5 text-[var(--text-primary)]">+ <span className="my-plugins-mobile-label">+ {t(`${copy}.latestState`)} ·{' '}+ </span>+ {entry.latestSubmission+ ? `${entry.latestSubmission.version} · ${status(entry.latestSubmission, entry)}`+ : t(`${copy}.noSubmission`)}+ </span>+ {rowAction}+ </button>+ );+ })}+ </div>+ ) : null}+ {page?.nextCursor ? (+ <Button+ variant="secondary"+ loading={loading}+ onClick={() => void refresh(page.nextCursor!)}+ >+ {t(`${copy}.loadMore`)}+ </Button>+ ) : null}+ </>+ ) : currentDetail && plugin ? (+ <>+ {publishing}+ </>+ ) : loading ? (+ <p role="status" className="text-14 text-[var(--text-tertiary)]">+ {t(`${copy}.loading`)}+ </p>+ ) : null}+ <footer+ className="mt-6 flex items-center justify-between gap-3 pb-4 text-12 text-[var(--text-tertiary)]"+ aria-live="polite"+ >+ <span>+ {timestamp+ ? t(`${copy}.lastRefreshed`, { time: formatDate(timestamp) })+ : loading+ ? t(`${copy}.loading`)+ : ''}+ </span>+ {!isDetail && listEmpty && !query && filter === 'all' ? refreshButton : null}+ </footer>+ </>+ )}+ </PluginManagementPage>+ </main>+ <Dialog.Root+ open={pickerOpen}+ onOpenChange={(open) => {+ if (!open) setPickerOwner(null);+ }}+ >+ <Dialog.Portal>+ <Dialog.Overlay className="modal-scrim fixed inset-0 z-[10000]" />+ <Dialog.Content onInteractOutside={event => event.preventDefault()} className="modal-panel fixed left-1/2 top-1/2 z-[10000] flex max-h-[85vh] w-[calc(100vw-32px)] max-w-[460px] -translate-x-1/2 -translate-y-1/2 flex-col p-4">+ <Dialog.Title className="text-18 font-medium text-[var(--text-primary)]">+ {t(`${copy}.publishPlugin`)}+ </Dialog.Title>+ <Dialog.Description className="mt-2 text-13 leading-5 text-[var(--text-secondary)]">+ {t(`${copy}.chooseLocal`)}+ </Dialog.Description>+ <div className="my-4 min-h-0 overflow-y-auto p-1">+ {pickerOwner === ownerKey && ownerMatches+ ? localPlugins.map((local) => {+ const unavailable = pickerUnavailable(local);+ return (+ <button+ type="button"+ key={local.id}+ className={`flex w-full min-w-0 items-center gap-3 rounded-lg border px-2 py-3 text-left enabled:hover:bg-[var(--surface-hover)] disabled:cursor-default focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)] ${submitBusy || !pickerReady ? 'opacity-60' : ''} ${pickerSelection === local.id ? 'border-[var(--border-default)] bg-[var(--surface-hover)]' : 'border-transparent'}`}+ aria-label={`${local.name} · ${local.version} · ${local.id}`}+ aria-describedby={unavailable ? `${pickerStatusId}-${local.id}` : undefined}+ aria-pressed={pickerSelection === local.id}+ disabled={submitBusy || !pickerReady || Boolean(unavailable)}+ onClick={() => setPickerSelection(local.id)}+ >+ <GhostPluginIcon+ iconDataUrl={local.iconDataUrl}+ iconId={local.id}+ iconName={local.name}+ />+ <span className="min-w-0 flex-1 [overflow-wrap:anywhere]">+ <span className={`block text-14 font-medium leading-5 ${unavailable ? 'text-[var(--text-secondary)]' : 'text-[var(--text-primary)]'}`}>+ {local.name}+ </span>+ <span className="mt-1 block text-12 leading-4 text-[var(--text-tertiary)]">+ {local.version}+ </span>+ <span className="mt-1 block text-12 leading-4 text-[var(--text-tertiary)]">+ {local.id}+ </span>+ {unavailable ? <span id={`${pickerStatusId}-${local.id}`} className="mt-1 block text-13 leading-5 text-[var(--text-secondary)]">+ {t(unavailable)}+ </span> : null}+ </span>+ {pickerSelection === local.id ? <Check size={16} aria-hidden="true" className="shrink-0 text-[var(--text-primary)]" /> : null}+ </button>+ );+ })+ : null}+ {localPlugins.length === 0 ? (+ <p className="text-14 leading-6 text-[var(--text-secondary)]">+ {t(+ `${copy}.${installedPluginCount === 0 ? 'noLocalPlugins' : 'noPublishablePlugins'}`,+ )}+ </p>+ ) : null}+ </div>+ {pickerSelection && pickerItem ? (+ <section aria-label={t(`${copy}.publishingVersion`, { version: pickerItem.version })}+ className="mb-4 max-h-52 space-y-2 overflow-y-auto border-t border-[var(--border-default)] pt-3 text-13 leading-5 text-[var(--text-secondary)]">+ <p className="font-medium text-[var(--text-primary)]">{pickerItem.name} · {pickerItem.version}</p>+ {currentPickerDraft?.prepared ? <>+ <p className="whitespace-pre-wrap break-words">{currentPickerDraft.prepared.description}</p>+ {currentPickerDraft.prepared.releaseNotes?.trim() ? <>+ <h3 className="font-medium">{t(`${copy}.releaseNotes`)}</h3>+ <p className="whitespace-pre-wrap break-words">{currentPickerDraft.prepared.releaseNotes}</p>+ </> : null}+ <p>{t(`${copy}.confirmPublic`)}</p>+ </> : !currentPickerDraft?.error ? <p role="status">{t(`${copy}.preparing`)}</p> : null}+ </section>+ ) : null}+ {localPlugins.length > 0 && !pickerRead ? <p role="status" className="mb-3 shrink-0 text-13 leading-5 text-[var(--text-secondary)]">{t(`${copy}.loading`)}</p> : null}+ {pickerRead?.failure || currentPickerDraft?.error ? (+ <p role="alert" className="mb-3 shrink-0 text-13 leading-5 text-[var(--text-secondary)]">+ {t((pickerRead?.failure ?? currentPickerDraft?.error)!, { defaultValue: t(`${copy}.loadFailed`) })}+ </p>+ ) : pickerBlocker || selectedPickerUnavailable ? (+ <p role="status" className="mb-3 shrink-0 text-13 leading-5 text-[var(--text-primary)]">+ {selectedPickerUnavailable ? t(selectedPickerUnavailable) : pickerBlocker?.message}+ </p>+ ) : null}+ <div className="flex shrink-0 flex-wrap justify-end gap-2">+ <Dialog.Close asChild>+ <Button variant="secondary">{t('settings.ghosts.detail.closeDialog')}</Button>+ </Dialog.Close>+ {pickerReady && !selectedPickerUnavailable && pickerItem && currentPickerDraft?.prepared?.preflight?.actions.canSubmit ? (+ <Button variant="cta" loading={submitBusy} disabled={submitBusy || !navigator.onLine}+ onClick={() => {+ const prepared = currentPickerDraft.prepared!;+ const token = pickerContext.current.token;+ const isCurrent = () => mounted.current && pickerContext.current.token === token;+ void onSubmitUpdate(pickerItem.id, { prepared, isCurrent }).then(submitted => {+ if (!isCurrent()) return;+ if (submitted) setPickerOwner(null);+ else setPickerRefresh(value => value + 1);+ });+ }}>{t(`${copy}.submitVersion`, { version: currentPickerDraft.prepared.version })}</Button>+ ) : null}+ </div>+ </Dialog.Content>+ </Dialog.Portal>+ </Dialog.Root>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/features/plugin/PluginAnonymityControl.tsx b/apps/desktop/src/renderer/features/plugin/PluginAnonymityControl.tsxnew file mode 100644index 0000000000..ad831dcb05--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/PluginAnonymityControl.tsx@@ -0,0 +1,99 @@+import { useEffect, useId, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Switch } from '@/components/ui/switch';+import { extractIpcError } from '@/utils/ipcError';+import type { MyPluginDetailView, MyPluginView, PluginContributionsApi } from '../../../shared/pluginContributions';++const copy = 'settings.ghosts.contribution';++/** Plugin-level author preference. Only a server-confirmed author can write it. */+export function PluginAnonymityControl({+ ownerKey, pluginId, settings, reader, loading = false, unavailable = false,+ onBeforeChange, onCommitted, onUpdated, disabled = false,+}: {+ ownerKey: string;+ pluginId: string;+ settings: MyPluginView['authorSettings'];+ reader: Pick<PluginContributionsApi, 'setAnonymity'>;+ loading?: boolean;+ unavailable?: boolean;+ disabled?: boolean;+ onBeforeChange?: () => void;+ /** Owner-fenced cache invalidation also runs if navigation unmounted this control. */+ onCommitted?: (detail: MyPluginDetailView, appliesToCurrentControl: boolean) => void;+ onUpdated?: (detail: MyPluginDetailView) => void;+}) {+ const { t } = useTranslation();+ const id = useId();+ const scope = JSON.stringify([ownerKey, pluginId]);+ const currentScope = useRef(scope);+ currentScope.current = scope;+ const mounted = useRef(true);+ const pending = useRef<symbol | null>(null);+ const [busyScope, setBusyScope] = useState<string | null>(null);+ const [failure, setFailure] = useState<{ scope: string; key: string } | null>(null);+ const [online, setOnline] = useState(navigator.onLine);+ useEffect(() => {+ mounted.current = true;+ const update = () => setOnline(navigator.onLine);+ window.addEventListener('online', update);+ window.addEventListener('offline', update);+ return () => {+ mounted.current = false;+ window.removeEventListener('online', update);+ window.removeEventListener('offline', update);+ };+ }, []);+ useEffect(() => {+ pending.current = null;+ setBusyScope(null);+ setFailure(null);+ }, [scope]);+ const change = async (anonymous: boolean) => {+ if (disabled || !settings?.canEdit || !navigator.onLine || pending.current) return;+ const operation = Symbol();+ pending.current = operation;+ setBusyScope(scope);+ setFailure(null);+ onBeforeChange?.();+ try {+ const result = await reader.setAnonymity(pluginId, anonymous);+ onCommitted?.(result, mounted.current && currentScope.current === scope && pending.current === operation);+ if (!mounted.current || currentScope.current !== scope || pending.current !== operation) return;+ onUpdated?.(result);+ } catch (error) {+ if (!mounted.current || currentScope.current !== scope || pending.current !== operation) return;+ const code = extractIpcError(error)?.code;+ setFailure({ scope, key: !navigator.onLine ? `${copy}.offline`+ : code === 'PERMISSION_DENIED' ? `${copy}.anonymousAuthorOnly`+ : code === 'OWNER_CHANGED' ? `${copy}.accountChanged` : `${copy}.anonymousUpdateFailed` });+ } finally {+ if (mounted.current && currentScope.current === scope && pending.current === operation) {+ pending.current = null;+ setBusyScope(null);+ }+ }+ };+ if (!settings && !loading && !unavailable) return null;+ const busy = busyScope === scope;+ return (+ <span className="inline-flex max-w-full flex-wrap items-center gap-x-2 gap-y-1 text-12 font-normal leading-5 text-[var(--text-tertiary)]">+ <label htmlFor={settings ? id : undefined} title={t(`${copy}.anonymousHint`)}>+ {t(`${copy}.anonymous`)}+ </label>+ {settings ? (+ <Switch id={id} checked={settings.anonymous} disabled={disabled || !settings.canEdit || busy || !online}+ aria-label={t(`${copy}.anonymous`)} aria-busy={busy} aria-describedby={`${id}-hint${!settings.canEdit ? ` ${id}-readonly` : ''}`}+ onCheckedChange={value => void change(value)} />+ ) : (+ <span role="status">{t(`${copy}.${loading ? 'loading' : 'anonymousUnavailable'}`)}</span>+ )}+ <span id={`${id}-hint`} className="sr-only">+ {t(`${copy}.anonymousHint`)}+ </span>+ {settings && !settings.canEdit ? <span id={`${id}-readonly`}>{t(`${copy}.anonymousAuthorOnly`)}</span> : null}+ {settings && !online ? <span role="status">{t(`${copy}.offline`)}</span> : null}+ {failure?.scope === scope ? <span role="alert" className="basis-full text-[var(--text-secondary)]">{t(failure.key)}</span> : null}+ </span>+ );+}diff --git a/apps/desktop/src/renderer/features/plugin/PluginDetailTopBar.tsx b/apps/desktop/src/renderer/features/plugin/PluginDetailTopBar.tsxindex 940585f5fe..83be4d90eb 100644--- a/apps/desktop/src/renderer/features/plugin/PluginDetailTopBar.tsx+++ b/apps/desktop/src/renderer/features/plugin/PluginDetailTopBar.tsx@@ -1,7 +1,7 @@/*** Shared sticky top bar for both Plugin detail surfaces (installed + market).*- * Inputs: the back affordance's label and handler, plus the owning scroll frame's scrolled flag.+ * Inputs: the back affordance, scroll state, and optional owning page's horizontal frame.* Outputs: the back button and, on macOS, the page's own window-drag region.* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md*/@@ -19,6 +19,8 @@ interface PluginDetailTopBarProps {onBack: () => void;/** 滚动帧是否已离开顶部;顶栏据此从透明切到实底 + hairline。 */scrolled: boolean;+ /** 管理页传入与正文共用的宽度和留白;详情页保留默认阅读宽度。 */+ frameClassName?: string;}/**@@ -65,7 +67,12 @@ export function usePluginDetailScrolled(): {* cindy-dark.ts:131,两端同值),两条线同时出现即为一片 --surface 上相隔 64px 的* 两条同色平行线;那两端由 ContentHeader 的下边框充当顶部分隔,本行只留实底。*/-export function PluginDetailTopBar({ label, onBack, scrolled }: PluginDetailTopBarProps) {+export function PluginDetailTopBar({+ label,+ onBack,+ scrolled,+ frameClassName,+}: PluginDetailTopBarProps) {const { isMac } = useMacFullscreen();// Both installed and market detail surfaces share this escape hatch. Let@@ -111,7 +118,12 @@ export function PluginDetailTopBar({ label, onBack, scrolled }: PluginDetailTopB)}style={isMac ? WINDOW_DRAG_STYLE : undefined}>- <div className="mx-auto flex h-16 w-full max-w-[824px] items-center px-8 max-[760px]:px-6">+ <div+ className={cn(+ 'flex h-16 items-center',+ frameClassName ?? 'mx-auto w-full max-w-[824px] px-8 max-[760px]:px-6',+ )}+ ><buttontype="button"onClick={onBack}diff --git a/apps/desktop/src/renderer/features/plugin/PluginPublisherBadge.tsx b/apps/desktop/src/renderer/features/plugin/PluginPublisherBadge.tsxnew file mode 100644index 0000000000..a396aab640--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/PluginPublisherBadge.tsx@@ -0,0 +1,15 @@+import { BadgeCheck } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import type { PluginMarketItem } from '../../../shared/pluginMarket';++/** A display of verified public provenance; it never grants runtime privileges. */+export function PluginPublisherBadge({ kind }: { kind?: PluginMarketItem['publisherKind'] }) {+ const { t } = useTranslation();+ if (kind !== 'official') return null;+ return (+ <span className="inline-flex h-5 shrink-0 items-center gap-1 rounded-full bg-[var(--surface-chip)] px-2 text-11 font-medium leading-none text-[var(--text-primary)]">+ <BadgeCheck size={12} strokeWidth={2} aria-hidden="true" />+ {t('settings.ghosts.market.publisherKind.official')}+ </span>+ );+}diff --git a/apps/desktop/src/renderer/features/plugin/PluginVersionFacts.tsx b/apps/desktop/src/renderer/features/plugin/PluginVersionFacts.tsxnew file mode 100644index 0000000000..36e3441082--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/PluginVersionFacts.tsx@@ -0,0 +1,26 @@+import { useTranslation } from 'react-i18next';+import type { MyPluginView } from '../../../shared/pluginContributions';++/** Current facts stay independent of the historical release selection. */+export function PluginVersionFacts({ plugin }: {+ plugin: MyPluginView;+}) {+ const { t } = useTranslation();+ const copy = 'settings.ghosts.contribution';+ const pending = plugin.latestSubmission?.reviewStatus === 'pending' &&+ plugin.latestSubmission.revisionState === 'current' ? plugin.latestSubmission.version : null;+ const facts = [+ ['localVersion', plugin.localInstallation?.state === 'installed'+ ? plugin.localInstallation.version+ : t(`${copy}.localState.${plugin.localInstallation?.state ?? 'unavailable'}`)],+ ['listedVersion', plugin.market.state === 'available' && plugin.market.version+ ? plugin.market.version : t(`${copy}.market.${plugin.market.state}`)],+ ['pendingVersion', pending ?? t(`${copy}.noPendingVersion`)],+ ];+ return <dl aria-label={t(`${copy}.versionFacts`)} className="grid grid-cols-3 gap-x-6 gap-y-3 border-y border-[var(--border-default)] py-3 max-[600px]:grid-cols-1">+ {facts.map(([label, value]) => <div key={label} className="flex min-w-0 flex-wrap items-baseline gap-x-3 gap-y-1">+ <dt className="text-12 leading-5 text-[var(--text-tertiary)]">{t(`${copy}.${label}`)}</dt>+ <dd className="break-words text-14 font-medium leading-5 text-[var(--text-primary)]">{value}</dd>+ </div>)}+ </dl>;+}diff --git a/apps/desktop/src/renderer/features/plugin/PluginVersionUpdates.tsx b/apps/desktop/src/renderer/features/plugin/PluginVersionUpdates.tsxnew file mode 100644index 0000000000..d6e9cf9739--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/PluginVersionUpdates.tsx@@ -0,0 +1,29 @@+import type { ReactNode } from 'react';+import { ChevronDown } from 'lucide-react';+import { useTranslation } from 'react-i18next';++/** Updates stay secondary to the plugin's purpose and use controls. No persisted open state. */+export function PluginVersionUpdates({ children, attention, open, onOpenChange }: {+ children: ReactNode;+ attention?: ReactNode;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+}) {+ const { t } = useTranslation();+ return (+ <details+ open={open}+ className="group mt-8 border-y border-[var(--border-default)] py-4"+ onToggle={(event) => {+ if (event.target === event.currentTarget) onOpenChange?.(event.currentTarget.open);+ }}+ >+ <summary className="flex min-h-8 cursor-pointer select-none list-none items-center gap-2 rounded-md text-16 font-medium text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] [&::-webkit-details-marker]:hidden">+ <span>{t('settings.ghosts.contribution.versionUpdates')}</span>+ {attention}+ <ChevronDown size={16} aria-hidden="true" className="ml-auto shrink-0 text-[var(--text-tertiary)] transition-transform group-open:rotate-180" />+ </summary>+ <div className="pt-5">{children}</div>+ </details>+ );+}diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsxindex c5536faa31..728af0afbd 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx@@ -9,6 +9,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { ReactNode } from 'react';import path from 'node:path';import type { InstalledGhost } from '../../../../shared/ghost';+import type { PreparedPluginContribution } from '../../../../shared/pluginContributions';const toastMocks = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));@@ -248,6 +249,92 @@ describe('Ghost plugin detail sections', () => {fireEvent.click(screen.getByRole('button', { name: 'Permissions: Read service' }));expect(within(await screen.findByRole('dialog')).getByText('Only the declared service')).toBeTruthy();});+ it('shows the plugin purpose and capabilities before the collapsed local update notes', () => {+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });+ render(<GhostPluginDetailView ghost={null} detail={{ ...detail, releaseNotes: 'Only version changes', tools: [{ name: 'example', description: 'Example tool' }] }} panelStatus={null}+ onBack={vi.fn()} onToggle={vi.fn()} onUse={vi.fn()} onUpdate={vi.fn()} onUpdateFromFile={vi.fn()}+ onUninstall={vi.fn()} toggleDisabled={false} />);+ const summary = screen.getByText('settings.ghosts.contribution.versionUpdates');+ const updates = summary.closest('details')!;+ expect(updates.open).toBe(false);+ expect(screen.getByText(detail.description).compareDocumentPosition(updates) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(screen.getByRole('heading', { name: 'Tools' }).compareDocumentPosition(updates) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ fireEvent.click(summary);+ expect(updates.open).toBe(true);+ expect(screen.getByText('Only version changes')).toBeTruthy();+ });+++ it.each(['pending', 'approved', 'rejected', 'cancelled'] as const)(+ 'keeps the %s version result without advertising a submission that cannot be repeated', (status) => {+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });+ const publish = vi.fn();+ const refresh = vi.fn();+ const preview: PreparedPluginContribution = {+ preparedId: 'preview', instanceId: 'instance', pluginId: 'plugin', ghostId: 'example',+ name: detail.name, description: detail.description, version: '1.0.0', sha256: 'a'.repeat(64),+ sizeBytes: 100, releaseNotes: 'Complete package release notes', expiresAt: '2026-10-16T00:00:00.000Z',+ preflight: {+ subject: { authority: 'https://auth.example', membershipId: 'member' },+ queriedAt: '2026-10-16T00:00:00.000Z', policyVersion: 2,+ target: { pluginId: 'plugin', ghostId: 'example', version: '1.0.0', expectedRelease: null },+ pendingRelease: status === 'pending' ? { releaseId: 'release', version: '1.0.0' } : null,+ blockers: [{ code: 'VERSION_ALREADY_SUBMITTED', message: 'Change the version before publishing again' }],+ actions: { canSubmit: false },+ },+ };+ const view = (prepared: PreparedPluginContribution) => <GhostPluginDetailView+ ghost={null} detail={detail} panelStatus={null} onBack={vi.fn()} onToggle={vi.fn()} onUse={vi.fn()}+ onUpdate={vi.fn()} onUpdateFromFile={vi.fn()} onUninstall={vi.fn()} toggleDisabled={false}+ onContribute={publish} onRefreshPublishing={refresh}+ publishingPreview={prepared} contributionSummary={`1.0.0 · ${status}`}+ contributionUnavailableReason={prepared.preflight?.actions.canSubmit ? undefined : 'Change the version before publishing again'} />;+ const { rerender } = render(view(preview));+ const updates = screen.getByText('settings.ghosts.contribution.versionUpdates').closest('details')!;+ expect(updates.open).toBe(false);+ expect(screen.getByRole('heading', { name: 'settings.ghosts.contribution.version · 1.0.0' }).closest('details')).toBe(updates);+ fireEvent.click(screen.getByText('settings.ghosts.contribution.versionUpdates'));+ expect(screen.queryByRole('button', { name: 'settings.ghosts.contribution.submitVersion' })).toBeNull();+ expect(screen.getByRole('status').textContent).toBe(`1.0.0 · ${status}`);+ expect(screen.getByText('Change the version before publishing again')).toBeTruthy();+ expect(screen.getByRole('heading', { name: 'settings.ghosts.contribution.version · 1.0.0' })).toBeTruthy();+ expect(screen.queryByText('settings.ghosts.contribution.versionConsumedHint')).toBeNull();+ expect(screen.getByText('Complete package release notes')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.contribution.refreshSummary' }));+ expect(refresh).toHaveBeenCalledOnce();+ expect(publish).not.toHaveBeenCalled();+ // A previous cancelled/rejected/approved result does not hide a new eligible version.+ rerender(view({ ...preview, version: '1.1.0', preflight: { ...preview.preflight!, target: { ...preview.preflight!.target, version: '1.1.0' }, pendingRelease: null, blockers: [], actions: { canSubmit: true } } }));+ const submit = screen.getByRole('button', { name: 'settings.ghosts.contribution.submitVersion' });+ expect(submit).toHaveProperty('disabled', false);+ expect(screen.getByRole('heading', { name: 'settings.ghosts.contribution.publishingVersion' })).toBeTruthy();+ fireEvent.click(submit);+ expect(publish).toHaveBeenCalledOnce();+ },+ );++ it('keeps the local quick submission in the use header and release information secondary', () => {+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });+ const publish = vi.fn();+ render(<GhostPluginDetailView ghost={null} detail={detail} panelStatus={null}+ onBack={vi.fn()} onToggle={vi.fn()} onUse={vi.fn()} onUpdate={vi.fn()}+ onUpdateFromFile={vi.fn()} onUninstall={vi.fn()} toggleDisabled={false}+ onContribute={publish} contributionSummary="2.0.0 · Pending Review" />);+ const summary = screen.getByText('settings.ghosts.contribution.versionUpdates');+ const updates = summary.closest('details')!;+ expect(updates.open).toBe(false);+ expect(screen.getByRole('button', { name: 'settings.ghosts.contribution.publish' }).closest('header')).toBeTruthy();+ expect(within(updates).getByRole('status').textContent).toBe('2.0.0 · Pending Review');+ const chat = screen.getByRole('button', { name: 'settings.ghosts.detail.chatAction' });+ expect(within(chat.closest('.plugin-detail-actions') as HTMLElement).getByRole('switch')).toBeTruthy();+ expect(screen.getByText('Example plugin').compareDocumentPosition(updates) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ fireEvent.click(summary);+ const action = screen.getByRole('button', { name: 'settings.ghosts.contribution.publish' });+ expect(within(updates).getByRole('status').textContent).toBe('2.0.0 · Pending Review');+ fireEvent.click(action);+ expect(publish).toHaveBeenCalledOnce();+ });+it('does not advertise host login for a locally imported unverified GitHub plugin', () => {vi.stubGlobal('ResizeObserver',@@ -613,7 +700,7 @@ describe('Ghost plugin detail sections', () => {expect(topBarFrame?.className).toContain('max-w-[824px]');expect(backButton?.className).toContain('-ml-3');expect(detailHero?.className).toContain('grid-cols-[64px_minmax(0,1fr)_auto]');- expect(detailActions?.className).toContain('flex-nowrap');+ expect(detailActions?.className).toContain('flex-wrap');});it('routes a projected detail icon failure to market recovery', () => {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.tsxindex c17e0bff92..eaefb84107 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@@ -1,11 +1,12 @@/** @vitest-environment jsdom */-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import { MemoryRouter, useNavigate } from 'react-router-dom';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import path from 'node:path';import type { PluginMarketDetail } from '../../../../shared/pluginMarket';+import type { ContributionTransferView, MyPluginDetailView, MyPluginReleasePageView } from '../../../../shared/pluginContributions';import type { InstalledGhost } from '../../../../shared/ghost';import { __resetInstalledGhostsStoreForTest } from '@/cindy-brain/useInstalledGhosts';import {@@ -95,6 +96,8 @@ const listAgentSkills = vi.fn();beforeEach(() => {vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });+ auth.mode = 'local';+ auth.user.membershipKind = 'personal';translation.i18n.language = 'en';translation.i18n.resolvedLanguage = 'en';cancelPendingPluginSuggestion();@@ -116,6 +119,7 @@ beforeEach(() => {},ghosts: {listSync: () => ({ ghosts: [] }),+ legacyRecoveryStatus: vi.fn().mockResolvedValue({ state: 'none' }),recentUsageSync: () => ({ ids: [] }),onChanged: () => () => {},onRecentUsageChanged: () => () => {},@@ -324,6 +328,157 @@ describe('plugin page return navigation', () => {},);+ it.each([+ { state: 'installed', author: 'Published nickname', installedAuthor: undefined, expected: 'Published nickname' },+ { state: 'installed', author: null, installedAuthor: undefined, expected: null },+ { state: 'update-available', author: 'New release nickname', installedAuthor: 'Installed release nickname', expected: 'Installed release nickname' },+ { state: 'update-available', author: 'New release nickname', installedAuthor: null, expected: null },+ ] as const)('preserves installed attribution and anonymity ($state, $expected)', async ({ state, author, installedAuthor, expected }) => {+ const installed: InstalledGhost = {+ manifest: { ...detail.manifest, author: 'Package author must not leak' },+ dir: '/tmp/brain/' + detail.ghostId,+ namespace: null, namespaceState: 'confirmed', enabled: true,+ publishingSource: { kind: 'public-market', pluginId: detail.pluginId },+ approval: { state: 'approved', revision: 'revision' },+ };+ window.electronAPI.ghosts.listSync = () => ({ ghosts: [installed] });+ window.electronAPI.pluginMarket.snapshot = async () => ({+ items: [{ ...detail, namespace: null, installState: state, author, installedAuthor,+ version: state === 'update-available' ? '1.1.0' : detail.version }],+ unavailableReason: null, customSourceNames: [], unavailableCustomSourceNames: [],+ });+ render(page('/plugins'));+ const card = screen.getByRole('button', { name: detail.name });+ await within(card).findByText('settings.ghosts.page.origin.public');+ if (expected) expect(within(card).getByText(expected)).toBeTruthy();+ if (author !== expected && author) expect(within(card).queryByText(author)).toBeNull();+ expect(within(card).queryByText('Package author must not leak')).toBeNull();+ });++ it.each(['local', 'public-market'] as const)('keeps the original local author fallback without exposing an unconfirmed public author (%s)', async (kind) => {+ const installed: InstalledGhost = {+ manifest: { ...detail.manifest, author: 'Local package author' },+ dir: '/tmp/brain/' + detail.ghostId,+ namespace: null, namespaceState: 'confirmed', enabled: true,+ publishingSource: kind === 'local'+ ? { kind: 'local', source: 'manual' }+ : { kind: 'public-market', pluginId: detail.pluginId },+ approval: { state: 'approved', revision: 'revision' },+ };+ window.electronAPI.ghosts.listSync = () => ({ ghosts: [installed] });+ window.electronAPI.pluginMarket.snapshot = async () => ({+ items: [], unavailableReason: 'OFFLINE', customSourceNames: [], unavailableCustomSourceNames: [],+ });+ render(page('/plugins'));+ const card = screen.getByRole('button', { name: detail.name });+ await within(card).findByText('settings.ghosts.page.origin.local');+ expect(Boolean(within(card).queryByText('Local package author'))).toBe(kind === 'local');+ });++ it.each([+ { id: 'cindy-art', namespace: null, namespaceState: 'confirmed', publishingSource: { kind: 'local', source: 'manual' }, approval: 'approved', reason: 'reservedId' },+ { id: 'personal-plugin', namespace: 'org', namespaceState: 'confirmed', publishingSource: { kind: 'local', source: 'manual' }, approval: 'approved', reason: 'privatePlugin' },+ { id: 'personal-plugin', namespace: null, namespaceState: 'pending', approval: 'approved', reason: 'identityPending' },+ { id: 'personal-plugin', namespace: null, namespaceState: 'confirmed', publishingSource: { kind: 'local', source: 'manual' }, approval: 'invalid', reason: 'approvalRequired' },+ ])('explains why $id cannot be published ($reason)', async ({ id, namespace, namespaceState, approval, reason }) => {+ const installed = {+ manifest: { ...detail.manifest, id, name: 'Installed Plugin' },+ dir: '/tmp/brain/' + id, namespace, namespaceState, publishingSource: { kind: 'local', source: 'manual' },+ enabled: true, approval: { state: approval, revision: 'revision' },+ } as InstalledGhost;+ window.electronAPI.ghosts.listSync = () => ({ ghosts: [installed] });+ window.electronAPI.pluginMarket.snapshot = async () => ({ items: [], unavailableReason: null, customSourceNames: [], unavailableCustomSourceNames: [] });+ render(page('/plugins'));+ fireEvent.click(await screen.findByText('Installed Plugin'));+ fireEvent.click(screen.getByText('settings.ghosts.contribution.versionUpdates'));+ expect(screen.queryByRole('button', { name: 'settings.ghosts.contribution.publish' })).toBeNull();+ expect(screen.getByText('settings.ghosts.contribution.unavailable.' + reason)).toBeTruthy();+ });++ it('offers only locally publishable exact installations and opens a read-only package summary without uploading or publishing', async () => {+ auth.mode = 'cloud';+ const installed = {+ manifest: { ...detail.manifest, id: 'local-author-plugin', name: 'Local Author Plugin' },+ dir: '/tmp/brain/local-author-plugin', namespace: null, namespaceState: 'confirmed', publishingSource: { kind: 'local', source: 'manual' },+ enabled: true, approval: { state: 'approved', revision: 'revision' },+ } as InstalledGhost;+ const unavailable = [+ { ...installed, manifest: { ...installed.manifest, id: 'cindy-art', name: 'Reserved Plugin' } },+ { ...installed, manifest: { ...installed.manifest, id: 'organization-plugin', name: 'Organization Plugin' }, namespace: 'org' },+ { ...installed, manifest: { ...installed.manifest, id: 'unapproved-plugin', name: 'Unapproved Plugin' }, approval: { state: 'legacy-unapproved' } },+ { ...installed, manifest: { ...installed.manifest, id: 'pending-plugin', name: 'Pending Identity Plugin' }, namespaceState: 'pending' },+ ] as InstalledGhost[];+ const ghosts = [...unavailable.map((ghost) => ({ ...ghost, dir: path.join(path.dirname(installed.dir), ghost.manifest.id) })), installed];+ window.electronAPI.ghosts.listSync = () => ({ ghosts });+ const api = { list: vi.fn().mockResolvedValue({ plugins: [], nextCursor: null, queriedAt: '2026-10-15T00:00:00Z' }), transfers: vi.fn().mockResolvedValue([]), prepare: vi.fn().mockResolvedValue({ preparedId: 'preview', instanceId: 'local-author-plugin', version: '1.0.0', releaseNotes: 'Initial release', preflight: { blockers: [], actions: { canSubmit: true } } }), discard: vi.fn().mockResolvedValue(undefined), submit: vi.fn() };+ Object.assign(window.electronAPI, { pluginContributions: api });+ render(page('/plugins?myPlugins=1'));+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.contribution.publishPlugin' }));+ const picker = screen.getByRole('dialog');+ expect(within(picker).getAllByRole('button')).toHaveLength(2); // One installation and Close; select before submitting.+ for (const ghost of unavailable) expect(within(picker).queryByText(ghost.manifest.name)).toBeNull();+ const option = within(picker).getByRole('button', { name: 'Local Author Plugin · 1.0.0 · local-author-plugin' });+ await waitFor(() => expect(option).toHaveProperty('disabled', false));+ fireEvent.click(option);+ expect(await within(picker).findByRole('button', { name: 'settings.ghosts.contribution.submitVersion' })).toHaveProperty('disabled', false);+ // Radix correctly removes the page behind an open modal from the accessibility tree.+ expect(screen.getByText('settings.ghosts.contribution.myPlugins', { selector: 'h1' })).toBeTruthy();+ expect(api.prepare).toHaveBeenCalledWith('local-author-plugin', expect.objectContaining({ directory: installed.dir }));+ expect(api.submit).not.toHaveBeenCalled();+ fireEvent.click(within(picker).getByRole('button', { name: 'settings.ghosts.detail.closeDialog' }));+ expect(screen.getByRole('heading', { level: 1, name: 'settings.ghosts.contribution.myPlugins' })).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.title' }));+ expect(await screen.findByRole('button', { name: 'settings.ghosts.contribution.myPlugins' })).toBeTruthy();+ expect(screen.queryByRole('heading', { name: 'Local Author Plugin' })).toBeNull();+ });++ it.each(['VERSION_ALREADY_SUBMITTED', 'PLUGIN_PENDING_RELEASE_EXISTS', 'RELEASE_NOTES_REQUIRED'])(+ 'hides the unavailable submit action after reading the real preflight projection (%s)', async code => {+ auth.mode = 'cloud';+ const installed: InstalledGhost = {+ manifest: { ...detail.manifest, id: 'local-author-plugin', name: 'Local Author Plugin' },+ dir: path.resolve('brain', 'local-author-plugin'), namespace: null, namespaceState: 'confirmed', publishingSource: { kind: 'local', source: 'manual' },+ enabled: true, approval: { state: 'approved', revision: 'revision' },+ };+ window.electronAPI.ghosts.listSync = () => ({ ghosts: [installed] });+ const api = {+ list: vi.fn().mockResolvedValue({ plugins: [], nextCursor: null, queriedAt: '2026-10-15T00:00:00Z' }),+ prepare: vi.fn().mockResolvedValue({ preparedId: 'preview', instanceId: 'local-author-plugin', version: '1.0.0', releaseNotes: 'Initial release', preflight: { blockers: [{ code, message: 'Publication blocked' }], actions: { canSubmit: false } } }),+ discard: vi.fn().mockResolvedValue(undefined), submit: vi.fn(),+ };+ Object.assign(window.electronAPI, { pluginContributions: api });+ render(page('/plugins'));+ fireEvent.click(await screen.findByText('Local Author Plugin'));+ await screen.findAllByText('Publication blocked');+ expect(screen.queryByRole('button', { name: 'settings.ghosts.contribution.submitVersion' })).toBeNull();+ fireEvent.click(screen.getByText('settings.ghosts.contribution.versionUpdates'));+ expect(screen.getByRole('button', { name: 'settings.ghosts.contribution.refreshSummary' })).toBeTruthy();+ expect(api.submit).not.toHaveBeenCalled();+ },+ );++ it('shows no publishable installations instead of no installations when only a reserved plugin is installed', async () => {+ auth.mode = 'cloud';+ const installed: InstalledGhost = {+ manifest: { ...detail.manifest, id: 'cindy-art', name: 'Art' },+ dir: path.resolve('brain', 'cindy-art'),+ namespace: null, namespaceState: 'confirmed', publishingSource: { kind: 'local', source: 'manual' }, enabled: true,+ approval: { state: 'approved', revision: 'revision' },+ };+ window.electronAPI.ghosts.listSync = () => ({ ghosts: [installed] });+ const api = { list: vi.fn().mockResolvedValue({ plugins: [], nextCursor: null, queriedAt: '2026-10-15T00:00:00Z' }), transfers: vi.fn().mockResolvedValue([]), prepare: vi.fn().mockResolvedValue({ preparedId: 'preview', instanceId: 'local-author-plugin', version: '1.0.0', releaseNotes: 'Initial release', preflight: { blockers: [], actions: { canSubmit: true } } }), discard: vi.fn().mockResolvedValue(undefined), submit: vi.fn() };+ Object.assign(window.electronAPI, { pluginContributions: api });+ render(page('/plugins?myPlugins=1'));+ await screen.findByText('settings.ghosts.contribution.empty');+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.contribution.publishPlugin' }));+ const picker = screen.getByRole('dialog');+ expect(within(picker).getByText('settings.ghosts.contribution.noPublishablePlugins')).toBeTruthy();+ expect(within(picker).queryByText('settings.ghosts.contribution.noLocalPlugins')).toBeNull();+ expect(within(picker).queryByText('Art')).toBeNull();+ expect(api.prepare).not.toHaveBeenCalled();+ expect(api.submit).not.toHaveBeenCalled();+ });+it.each(['xd-ordinary', 'filo-ordinary'])('updates an ordinary root %s from a local file and offers export in packaged builds',async (ghostId) => {@@ -654,3 +809,317 @@ describe('organization catalog access notice', () => {expect(screen.queryByText('settings.ghosts.market.errors.organizationUnavailable')).toBeNull();});});+++describe('plugin use details and independent author management', () => {+ const prefix = 'settings.ghosts.contribution';+ function authorApi(localInstanceId: string | null = '_root__navigation-plugin') {+ const own: MyPluginDetailView = {+ plugin: { pluginId: detail.pluginId, name: 'Published snapshot name', iconUrl: null,+ updatedAt: '2026-10-19T00:00:00Z', market: { state: 'available', version: '1.0.0', releaseId: detail.releaseId, reason: null },+ localInstanceId, localVersion: localInstanceId ? '1.2.0' : null,+ localInstallation: localInstanceId ? { state: 'installed', instanceId: localInstanceId, version: '1.2.0', origin: 'local', enabled: true } : { state: 'missing' },+ actions: { submitUpdate: true, viewMarket: true }, authorSettings: { anonymous: true, canEdit: false },+ latestSubmission: { releaseId: 'pending-release', version: '1.2.0', sha256: 'a'.repeat(64), revision: 'revision',+ revisionState: 'current', submissionId: 'pending-submission', reviewStatus: 'pending',+ submittedAt: '2026-10-19T00:00:00Z', reviewedAt: null, reason: null, source: 'manual', canCancelReview: true,+ content: { name: 'Submitted snapshot name', description: 'Submitted snapshot description', iconUrl: null,+ permissions: [], manifestView: { releaseNotes: 'Changes since the published 1.0.0' } } } },+ history: [], nextCursor: null, queriedAt: '2026-10-19T00:00:00Z',+ };+ return { list: vi.fn().mockResolvedValue({ plugins: [own.plugin], nextCursor: null, queriedAt: own.queriedAt }),+ detail: vi.fn().mockResolvedValue(own), releases: vi.fn<() => Promise<MyPluginReleasePageView>>().mockResolvedValue({ releases: [], nextCursor: null, queriedAt: own.queriedAt }),+ transfers: vi.fn().mockResolvedValue([]), prepare: vi.fn(), submit: vi.fn(), setAnonymity: vi.fn() };+ }++ function localAuthorInstallation(version: string): InstalledGhost {+ return {+ manifest: { ...detail.manifest, name: 'Local Author Plugin', version, releaseNotes: 'Complete changes' },+ dir: path.resolve('brain', '_ns', '_root', detail.ghostId), instanceKey: '_root__navigation-plugin',+ namespace: null, namespaceState: 'confirmed', publishingSource: { kind: 'local', source: 'manual' },+ enabled: true, approval: { state: 'approved', revision: 'revision' },+ };+ }++ it.each([+ ['failed', 'Missing entry file: main.js\nPackage validation stopped.'],+ ['failed', 'Expected SHA256 aabb, received ccdd.'],+ ['failed', 'Package is 120 MB; maximum size is 100 MB.'],+ ['failed', 'Release storage could not retain the validated package.'],+ ['paused', null],+ ['processing', null],+ ['succeeded', null],+ ] as const)('keeps a %s submission in the original detail without an upload-management page', async (stage, message) => {+ auth.mode = 'cloud';+ const installed = localAuthorInstallation('1.3.0');+ window.electronAPI.ghosts.listSync = () => ({ ghosts: [installed] });+ const api = authorApi();+ const own = await api.detail();+ own.plugin.latestSubmission = null;+ const prepared: ContributionTransferView['prepared'] = { preparedId: 'submit-package', instanceId: installed.instanceKey!, pluginId: detail.pluginId,+ ghostId: detail.ghostId, name: 'Local Author Plugin', description: '', version: '1.3.0', releaseNotes: 'Complete changes',+ sha256: 'a'.repeat(64), sizeBytes: 100, expiresAt: '2099-01-01T00:00:00Z',+ preflight: { subject: { authority: 'https://issuer.test', membershipId: 'member-A' }, queriedAt: '2026-10-21T00:00:00Z', policyVersion: 2,+ target: { pluginId: detail.pluginId, ghostId: detail.ghostId, version: '1.3.0', expectedRelease: null }, pendingRelease: null, blockers: [], actions: { canSubmit: true } } };+ api.prepare.mockResolvedValue(prepared);+ const transfer: ContributionTransferView = {+ localId: prepared.preparedId, prepared, stage: stage === 'failed' || stage === 'succeeded' ? 'complete' : stage,+ errorCode: stage === 'paused' ? 'INTERNAL' : null,+ operation: { subject: { authority: 'https://issuer.test', membershipId: 'member-A' }, operationId: 'operation',+ status: stage === 'failed' ? 'failed' : stage === 'succeeded' ? 'succeeded' : 'validating', createdAt: '2026-10-21T00:00:00Z', updatedAt: '2026-10-21T00:00:00Z',+ expiresAt: '2099-01-01T00:00:00Z', receipt: stage === 'succeeded' ? { operationId: 'operation', submissionId: 'new-submission', pluginId: detail.pluginId, releaseId: 'new-release', ghostId: detail.ghostId, version: '1.3.0', source: 'manual', submittedAt: '2026-10-21T00:00:00Z', uploadedPackage: { sha256: prepared.sha256, sizeBytes: prepared.sizeBytes }, releaseRevision: { releaseId: 'new-release', sha256: prepared.sha256, displayUpdatedAt: '2026-10-21T00:00:00Z' }, outcome: 'submitted_for_review' } : null, submission: null,+ failure: message ? { code: 'PLUGIN_PACKAGE_INVALID', message } : null },+ };+ api.submit.mockResolvedValue(transfer);+ let finish!: (value: ContributionTransferView) => void;+ const status = vi.fn(() => new Promise<ContributionTransferView>(resolve => { finish = resolve; }));+ const error = vi.spyOn(toast, 'error').mockReturnValue('submit-error');+ Object.assign(window.electronAPI, { pluginContributions: { ...api, status, discard: vi.fn() } });+ render(page(`/plugins?ghost=${installed.instanceKey}`));+ await screen.findByRole('heading', { name: 'Local Author Plugin' });+ fireEvent.click(screen.getByText(`${prefix}.versionUpdates`));+ const submit = await screen.findByRole('button', { name: `${prefix}.submitUpdate` });+ fireEvent.click(submit);+ fireEvent.click(submit);+ await waitFor(() => expect(api.submit).toHaveBeenCalledExactlyOnceWith(prepared.preparedId));+ if (stage === 'processing') {+ expect(submit).toHaveProperty('disabled', true);+ await waitFor(() => expect(status).toHaveBeenCalledWith(transfer.localId), { timeout: 2500 });+ await act(async () => { finish({ ...transfer, stage: 'paused', errorCode: 'INTERNAL' }); });+ }+ if (stage === 'succeeded') {+ await screen.findByRole('heading', { name: 'Published snapshot name' });+ expect(error).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: `${prefix}.myPlugins` }));+ await screen.findByRole('heading', { level: 1, name: `${prefix}.myPlugins` });+ fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.title' }));+ await screen.findByRole('heading', { level: 1, name: 'settings.ghosts.title' });+ } else {+ await waitFor(() => expect(error).toHaveBeenCalledWith(message ?? `${prefix}.errors.INTERNAL`));+ expect(screen.getByRole('heading', { name: 'Local Author Plugin' })).toBeTruthy();+ }+ expect(screen.queryByText(`${prefix}.resume`)).toBeNull();+ expect(screen.queryByText(`${prefix}.retryPublish`)).toBeNull();+ expect(screen.queryByRole('region', { name: `${prefix}.publicationProgress` })).toBeNull();+ expect(api.transfers).not.toHaveBeenCalled();+ });++ // Unit: a cancelled 1.0.0 still offered submission and only failed after clicking.+ // Exercise the real installed-detail entry; preflight-only coverage missed updates.+ it.each(['cancelled', 'rejected', 'approved', 'pending'] as const)(+ 'hides the installed-version submit action after a %s submission', async reviewStatus => {+ auth.mode = 'cloud';+ const installed = localAuthorInstallation('1.2.0');+ window.electronAPI.ghosts.listSync = () => ({ ghosts: [installed] });+ const api = authorApi();+ const own = await api.detail();+ own.plugin.latestSubmission!.reviewStatus = reviewStatus;+ Object.assign(window.electronAPI, { pluginContributions: api });+ render(page(`/plugins?ghost=${installed.instanceKey}`));+ await screen.findByRole('heading', { name: 'Local Author Plugin' });+ fireEvent.click(screen.getByText(`${prefix}.versionUpdates`));+ await screen.findByText(`${prefix}.errors.${reviewStatus === 'pending' ? 'PLUGIN_PENDING_RELEASE_EXISTS' : 'VERSION_ALREADY_SUBMITTED'}`);+ expect(screen.queryByRole('button', { name: `${prefix}.submitUpdate` })).toBeNull();+ expect(api.prepare).not.toHaveBeenCalled();+ expect(api.submit).not.toHaveBeenCalled();+ },+ );++ it('checks older release pages before enabling submission of an installed version', async () => {+ auth.mode = 'cloud';+ const installed = localAuthorInstallation('0.9.0');+ window.electronAPI.ghosts.listSync = () => ({ ghosts: [installed] });+ const api = authorApi();+ const own = await api.detail();+ const latest = own.plugin.latestSubmission!;+ latest.reviewStatus = 'approved';+ api.releases.mockResolvedValueOnce({ releases: [latest], nextCursor: 'older', queriedAt: own.queriedAt })+ .mockResolvedValueOnce({ releases: [{ ...latest, version: '0.9.0', reviewStatus: 'cancelled' }], nextCursor: null, queriedAt: own.queriedAt });+ Object.assign(window.electronAPI, { pluginContributions: api });+ render(page(`/plugins?ghost=${installed.instanceKey}`));+ await screen.findByRole('heading', { name: 'Local Author Plugin' });+ fireEvent.click(screen.getByText(`${prefix}.versionUpdates`));+ await screen.findByText(`${prefix}.errors.VERSION_ALREADY_SUBMITTED`);+ expect(api.releases).toHaveBeenCalledWith(detail.pluginId, 'older');+ expect(screen.queryByRole('button', { name: `${prefix}.submitUpdate` })).toBeNull();+ expect(api.prepare).not.toHaveBeenCalled();+ expect(api.submit).not.toHaveBeenCalled();+ });++ it('keeps submission disabled while version eligibility is loading or failed', async () => {+ auth.mode = 'cloud';+ const installed = localAuthorInstallation('2.0.0');+ window.electronAPI.ghosts.listSync = () => ({ ghosts: [installed] });+ const api = authorApi();+ (await api.detail()).plugin.latestSubmission!.reviewStatus = 'approved';+ let fail!: (error: Error) => void;+ api.releases.mockImplementation(() => new Promise((_, reject) => { fail = reject; }));+ Object.assign(window.electronAPI, { pluginContributions: api });+ render(page(`/plugins?ghost=${installed.instanceKey}`));+ await waitFor(() => expect(api.releases).toHaveBeenCalled());+ const action = screen.getByRole('button', { name: /settings\.ghosts\.contribution\.(publish|submitUpdate)$/ });+ expect(action).toHaveProperty('disabled', true);+ fireEvent.click(action);+ await act(async () => { fail(new Error('Offline')); });+ expect(screen.getByRole('button', { name: /settings\.ghosts\.contribution\.(publish|submitUpdate)$/ })).toHaveProperty('disabled', true);+ expect(api.prepare).not.toHaveBeenCalled();+ expect(api.submit).not.toHaveBeenCalled();+ });++ it('enables a new installed version only after all release pages confirm it is unused', async () => {+ auth.mode = 'cloud';+ const installed = localAuthorInstallation('2.0.0');+ window.electronAPI.ghosts.listSync = () => ({ ghosts: [installed] });+ const api = authorApi();+ const own = await api.detail();+ own.plugin.latestSubmission!.reviewStatus = 'approved';+ api.releases.mockResolvedValueOnce({ releases: [own.plugin.latestSubmission!], nextCursor: 'older', queriedAt: own.queriedAt })+ .mockResolvedValueOnce({ releases: [], nextCursor: null, queriedAt: own.queriedAt });+ Object.assign(window.electronAPI, { pluginContributions: api });+ render(page(`/plugins?ghost=${installed.instanceKey}`));+ expect(await screen.findByRole('button', { name: `${prefix}.submitUpdate` })).toHaveProperty('disabled', false);+ expect(api.releases).toHaveBeenCalledWith(detail.pluginId, 'older');+ expect(api.prepare).not.toHaveBeenCalled();+ expect(api.submit).not.toHaveBeenCalled();+ });+ it('keeps author management mounted when its active anonymity switch saves', async () => {+ auth.mode = 'cloud';+ const api = authorApi(null);+ const own = await api.detail();+ const anonymous = { ...own, plugin: { ...own.plugin, authorSettings: { anonymous: true, canEdit: true } } };+ const named = { ...anonymous, plugin: { ...anonymous.plugin, displayAuthor: 'Saved author',+ authorSettings: { anonymous: false, canEdit: true } } };+ api.detail.mockResolvedValue(anonymous);+ api.setAnonymity.mockResolvedValue(named);+ Object.assign(window.electronAPI, { pluginContributions: api });+ render(page(`/plugins?myPlugins=1&contribution=${detail.pluginId}`));+ const toggle = await screen.findByRole('switch', { name: `${prefix}.anonymous` }) as HTMLButtonElement;+ await waitFor(() => expect(toggle.disabled).toBe(false));+ const heading = screen.getByRole('heading', { level: 1, name: 'Published snapshot name' });+ const history = screen.getByText(`${prefix}.history`).closest('details')!;+ fireEvent.click(within(history).getByText(`${prefix}.history`));+ history.open = true;+ fireEvent.click(toggle);+ await screen.findByText('Saved author');+ expect(screen.getByRole('heading', { level: 1, name: 'Published snapshot name' })).toBe(heading);+ expect(screen.getByRole('switch', { name: `${prefix}.anonymous` })).toBe(toggle);+ expect(history.isConnected).toBe(true);+ expect(history.open).toBe(true);+ expect(toggle.getAttribute('aria-checked')).toBe('false');+ });+ it.each([undefined, { kind: 'unavailable' }, { kind: 'public-market', pluginId: detail.pluginId }] satisfies InstalledGhost['publishingSource'][])(+ 'does not expose publishing or prepare ordinary/unknown downloads (%j)', async publishingSource => {+ auth.mode = 'cloud';+ const installed: InstalledGhost = { manifest: { ...detail.manifest, name: 'Downloaded Plugin' },+ dir: path.resolve('brain', '_ns', '_root', detail.ghostId), instanceKey: '_root__navigation-plugin',+ namespace: null, namespaceState: 'confirmed', publishingSource, enabled: true,+ approval: { state: 'approved', revision: 'revision' } };+ window.electronAPI.ghosts.listSync = () => ({ ghosts: [installed] });+ const api = authorApi();+ const readonly = { ...(await api.detail()).plugin, actions: { submitUpdate: false, viewMarket: true } };+ api.list.mockResolvedValue({ plugins: [readonly], nextCursor: null, queriedAt: detail.publishedAt });+ api.detail.mockResolvedValue({ ...(await api.detail()), plugin: readonly });+ Object.assign(window.electronAPI, { pluginContributions: api });+ render(page(`/plugins?ghost=${installed.instanceKey}`));+ await screen.findByRole('heading', { name: 'Downloaded Plugin' });+ await act(async () => { await Promise.resolve(); });+ expect(screen.queryByRole('heading', { name: `${prefix}.publishing` })).toBeNull();+ expect(screen.queryByRole('button', { name: `${prefix}.publish` })).toBeNull();+ expect(api.prepare).not.toHaveBeenCalled();+ expect(api.submit).not.toHaveBeenCalled();+ });+ it.each(['author-list', 'installed', 'installed-market', 'market'] as const)('keeps use and version management separate when entering from %s', async entry => {+ auth.mode = 'cloud';+ const installed: InstalledGhost = { manifest: { ...detail.manifest, name: 'Actual installed name', version: '1.2.0' },+ dir: path.resolve('brain', '_ns', '_root', detail.ghostId), instanceKey: '_root__navigation-plugin', namespace: null, namespaceState: 'confirmed', publishingSource: { kind: 'local', source: 'manual' }, enabled: true,+ approval: { state: 'approved', revision: 'revision' } };+ if (entry === 'installed-market') installed.publishingSource = { kind: 'public-market', pluginId: detail.pluginId };+ window.electronAPI.ghosts.listSync = () => ({ ghosts: [installed] });+ const api = authorApi(); Object.assign(window.electronAPI, { pluginContributions: api });+ render(page(entry === 'author-list' ? '/plugins?myPlugins=1' : entry === 'market' ? `/plugins?market=${detail.pluginId}` : '/plugins'));+ if (entry === 'author-list') fireEvent.click(await screen.findByText('Published snapshot name'));+ if (entry === 'installed' || entry === 'installed-market') fireEvent.click(await screen.findByText('Actual installed name'));+ if (entry === 'author-list') {+ await screen.findByRole('heading', { level: 1, name: 'Published snapshot name' });+ const facts = screen.getByLabelText(`${prefix}.versionFacts`);+ expect(facts.closest('details')).toBeNull();+ expect(within(facts).getAllByText('1.2.0')).toHaveLength(2);+ expect(within(facts).getByText('1.0.0')).toBeTruthy();+ expect(screen.queryByRole('button', { name: /settings\.ghosts\.contribution\.submitVersion/ })).toBeNull();+ expect(screen.queryByRole('button', { name: `${prefix}.openPlugin` })).toBeNull();+ expect(screen.getByRole('button', { name: `${prefix}.cancelReview` })).toBeTruthy();+ expect(screen.queryByRole('switch', { name: 'settings.ghosts.enableAria' })).toBeNull();+ expect(screen.getAllByRole('switch', { name: `${prefix}.anonymous` })).toHaveLength(1);+ } else {+ await screen.findByRole('heading', { level: 1, name: entry === 'market' ? detail.name : 'Actual installed name' });+ expect(screen.queryByLabelText(`${prefix}.versionFacts`)).toBeNull();+ expect(screen.queryByRole('button', { name: `${prefix}.cancelReview` })).toBeNull();+ expect(screen.queryByRole('switch', { name: `${prefix}.anonymous` })).toBeNull();+ if (entry !== 'market') expect(screen.getByRole('switch', { name: 'settings.ghosts.enableAria' }).getAttribute('aria-checked')).toBe('true');+ if (entry === 'installed-market' || entry === 'market') expect(screen.queryByRole('button', { name: `${prefix}.submitUpdate` })).toBeNull();+ }+ expect(screen.getAllByRole('heading', { level: 1 })).toHaveLength(1);+ expect(api.prepare).not.toHaveBeenCalled(); expect(api.submit).not.toHaveBeenCalled();+ expect(api.setAnonymity).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: entry === 'author-list' ? `${prefix}.myPlugins` : 'settings.ghosts.detail.backToList' }));+ if (entry === 'author-list') await screen.findByRole('heading', { name: `${prefix}.myPlugins` });+ else await screen.findByRole('heading', { level: 1, name: 'settings.ghosts.title' });+ });+ it('honors an explicit installed deep link while leaving the author detail', async () => {+ auth.mode = 'cloud';+ const installed: InstalledGhost = { manifest: { ...detail.manifest, name: 'Actual installed name', version: '1.2.0' },+ dir: path.resolve('brain', '_ns', '_root', detail.ghostId), instanceKey: '_root__navigation-plugin', namespace: null, namespaceState: 'confirmed', publishingSource: { kind: 'local', source: 'manual' }, enabled: true,+ approval: { state: 'approved', revision: 'revision' } };+ window.electronAPI.ghosts.listSync = () => ({ ghosts: [installed] });+ const api = authorApi(); Object.assign(window.electronAPI, { pluginContributions: api });+ function NavigateInstalled() {+ const navigate = useNavigate();+ return <button onClick={() => navigate(`/plugins?ghost=${installed.instanceKey}`)}>Installed deep link</button>;+ }+ render(<MemoryRouter initialEntries={[`/plugins?myPlugins=1&contribution=${detail.pluginId}`]}>+ <NavigateInstalled /><GhostPluginPage />+ </MemoryRouter>);+ await screen.findByLabelText(`${prefix}.versionFacts`);+ fireEvent.click(screen.getByRole('button', { name: 'Installed deep link' }));+ await screen.findByRole('heading', { level: 1, name: 'Actual installed name' });+ expect(screen.queryByLabelText(`${prefix}.versionFacts`)).toBeNull();+ expect(api.prepare).not.toHaveBeenCalled();+ });+ it('does not guess first publication or prepare a package when author association cannot be read', async () => {+ auth.mode = 'cloud';+ const installed: InstalledGhost = { manifest: { ...detail.manifest, name: 'Unknown author association' },+ dir: path.resolve('brain', '_ns', '_root', detail.ghostId), instanceKey: '_root__navigation-plugin',+ namespace: null, namespaceState: 'confirmed', publishingSource: { kind: 'local', source: 'manual' }, enabled: true, approval: { state: 'approved', revision: 'revision' } };+ window.electronAPI.ghosts.listSync = () => ({ ghosts: [installed] });+ window.electronAPI.pluginMarket.snapshot = async () => ({ items: [], unavailableReason: null, customSourceNames: [], unavailableCustomSourceNames: [] });+ const api = authorApi(null); api.list.mockRejectedValue(new Error('Offline'));+ Object.assign(window.electronAPI, { pluginContributions: api });+ render(page(`/plugins?ghost=${installed.instanceKey}`));+ await screen.findAllByText(`${prefix}.loadFailed`);+ expect(api.prepare).not.toHaveBeenCalled();+ expect(api.submit).not.toHaveBeenCalled();+ });+ it('keeps a remote author detail usable without selecting a same-name local plugin', async () => {+ auth.mode = 'cloud';+ const api = authorApi(null); Object.assign(window.electronAPI, { pluginContributions: api });+ render(page(`/plugins?myPlugins=1&contribution=${detail.pluginId}`));+ const facts = await screen.findByLabelText(`${prefix}.versionFacts`);+ expect(within(facts).getByText(`${prefix}.localState.missing`)).toBeTruthy();+ expect(screen.getByRole('button', { name: `${prefix}.installPublished` })).toBeTruthy();+ expect(screen.queryByRole('switch', { name: 'settings.ghosts.enableAria' })).toBeNull();+ expect(screen.queryByRole('button', { name: `${prefix}.submitUpdate` })).toBeNull();+ expect(api.prepare).not.toHaveBeenCalled();+ });+ it('keeps an ordinary market viewer outside author management', async () => {+ auth.mode = 'cloud';+ const api = authorApi(null); api.detail.mockRejectedValue(new Error('PERMISSION_DENIED'));+ Object.assign(window.electronAPI, { pluginContributions: api });+ render(page(`/plugins?market=${detail.pluginId}`));+ await screen.findByRole('heading', { name: detail.name });+ expect(api.detail).not.toHaveBeenCalled();+ expect(screen.queryByLabelText(`${prefix}.versionFacts`)).toBeNull();+ expect(screen.queryByRole('heading', { name: `${prefix}.publishing` })).toBeNull();+ expect(screen.queryByText(`${prefix}.anonymous`)).toBeNull();+ expect(api.prepare).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/MarketPluginDetailView.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/MarketPluginDetailView.test.tsxindex bb15221b5c..4f01c34316 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/MarketPluginDetailView.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/MarketPluginDetailView.test.tsx@@ -5,10 +5,11 @@* @vitest-environment jsdom*/-import { render, screen } from '@testing-library/react';+import { fireEvent, render, screen } from '@testing-library/react';import { describe, expect, it, vi } from 'vitest';-vi.mock('react-i18next', () => ({+vi.mock('react-i18next', async (importOriginal) => ({+ ...await importOriginal<typeof import('react-i18next')>(),useTranslation: () => ({ t: (key: string, options?: { value?: string }) => options?.value !== undefined ? `${options.value} ${key}` : key, i18n: { language: 'en' } }),}));@@ -70,6 +71,18 @@ describe('MarketPluginDetailView', () => {expect(container.textContent).not.toContain('settings.ghosts.usage.title');});+ it('puts purpose and capabilities before version changes, which start collapsed', () => {+ renderDetail({ manifest: { ...manifest, releaseNotes: 'Changes in 1.3.11', tools: [{ name: 'calendar', description: 'Read events' }] } });+ const summary = screen.getByText('settings.ghosts.contribution.versionUpdates');+ const updates = summary.closest('details')!;+ expect(updates.open).toBe(false);+ expect(screen.getByText('Connect Google Calendar').compareDocumentPosition(updates) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(screen.getByText('calendar').compareDocumentPosition(updates) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(screen.getByRole('heading', { name: 'settings.ghosts.contribution.releaseNotes · 1.3.11' }).closest('details')).toBe(updates);+ fireEvent.click(summary);+ expect(screen.getByRole('heading', { name: 'settings.ghosts.contribution.releaseNotes · 1.3.11' })).toBeTruthy();+ });+it('shows the marketing description outside the conflict state', () => {renderDetail();const description = screen.getByText('Connect Google Calendar');@@ -91,8 +104,8 @@ describe('MarketPluginDetailView', () => {const reason = screen.getByText('settings.ghosts.market.replaceDescription');expect(reason.id).toBeTruthy();- // 冲突态下正文让位给原因,不再显示营销描述。- expect(screen.queryByText('Connect Google Calendar')).toBeNull();+ // 替换提示不能遮掉插件本身的用途。+ expect(screen.getByText('Connect Google Calendar')).toBeTruthy();const action = screen.getByRole('button', {name: /settings\.ghosts\.market\.replace$/,diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/MyPluginsPage.cancelReview.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/MyPluginsPage.cancelReview.test.tsxnew file mode 100644index 0000000000..8cc1089615--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/__tests__/MyPluginsPage.cancelReview.test.tsx@@ -0,0 +1,138 @@+/** @vitest-environment jsdom */+import { StrictMode } from 'react';+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { ConfirmDialogProvider } from '@/components/ui/confirm-dialog-provider';+import { registerPluginContributionsIpc } from '../../../../main/plugin-contributions/registerIpc';+import type { ContributionReleaseView, PluginContributionsApi } from '../../../../shared/pluginContributions';+import { MyPluginsPage } from '../MyPluginsPage';++const host = vi.hoisted(() => ({+ handlers: new Map<string, (event: unknown, raw: unknown) => Promise<unknown>>(),+ cancelReview: vi.fn(),+}));+vi.mock('electron', () => ({+ ipcMain: { handle: (name: string, handler: (event: unknown, raw: unknown) => Promise<unknown>) => host.handlers.set(name, handler) },+}));+vi.mock('../../../../main/security/trustedAppRenderer', () => ({ assertTrustedAppRendererEvent: vi.fn() }));+vi.mock('../../../../main/plugin-contributions/host', () => ({+ cancelPluginReview: host.cancelReview,+ setPluginAnonymity: vi.fn(),+ prepareContribution: vi.fn(),+ submitContribution: vi.fn(),+ resumeContribution: vi.fn(),+ contributionTransferStatus: vi.fn(),+ cancelContribution: vi.fn(),+ discardContribution: vi.fn(),+ listContributionTransfers: vi.fn(),+ listMyPlugins: vi.fn(),+ myPluginSubmission: vi.fn(),+ myPluginReleases: vi.fn(),+ myPluginDetail: vi.fn(),+ mapContributionError: (error: unknown) => { throw error; },+}));+vi.mock('../../../../main/plugin-contributions/reviewUpdates', () => ({ reviewUpdates: vi.fn(), markReviewRead: vi.fn() }));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en', resolvedLanguage: 'en' } }),+}));+vi.mock('@/contexts/AuthContext', () => ({+ useAuth: () => ({ dataOwnerId: 'owner', dataOwnerGeneration: 1, user: { id: 'member', membershipKind: 'personal' }, mode: 'cloud' }),+}));+vi.mock('@/components/sidebar/AccountSwitcherDialog', () => ({ AccountSwitcherDialog: () => null }));+vi.mock('@/hooks/useSignInToCindy', () => ({ useSignInToCindy: () => vi.fn() }));+vi.mock('@/hooks/useMacFullscreen', () => ({ useMacFullscreen: () => ({ isMac: false }) }));++const prefix = 'settings.ghosts.contribution';+const at = '2026-10-16T00:00:00.000Z';+const pending: ContributionReleaseView = {+ releaseId: 'release', version: '1.1.0', sha256: 'a'.repeat(64), revision: at,+ reviewStatus: 'pending', revisionState: 'current', submissionId: 'submission',+ submittedAt: at, reviewedAt: null, approvedAt: null, cancelledAt: null,+ canCancelReview: true, reason: null, source: 'manual',+ content: { name: 'My Plugin', description: 'Description', iconUrl: null, permissions: [], manifestView: { releaseNotes: 'Complete version changes' } },+};++function view() {+ let current = pending;+ const plugin = () => ({+ pluginId: 'plugin', name: 'My Plugin', iconUrl: null, updatedAt: at,+ market: { state: 'not_listed' as const, version: null, releaseId: null, reason: null },+ latestSubmission: current, actions: { submitUpdate: true, viewMarket: false }, localInstanceId: null,+ });+ const api: PluginContributionsApi = {+ reviewUpdates: async () => [], markReviewRead: vi.fn(),+ prepare: vi.fn(), submit: vi.fn(), resume: vi.fn(), cancel: vi.fn(), discard: vi.fn(), status: vi.fn(),+ transfers: async () => [],+ list: async () => ({ plugins: [plugin()], nextCursor: null, queriedAt: at }),+ setAnonymity: vi.fn(),+ detail: async () => ({ plugin: plugin(), history: [], nextCursor: null, queriedAt: at }),+ releases: async () => ({ releases: [current], nextCursor: null, queriedAt: at }),+ submission: async () => current,+ // Match preload's real envelope, then exercise the actual strict Main IPC handler.+ cancelReview: vi.fn(async (pluginId, release) => {+ const result = await host.handlers.get('plugin-contributions:cancel-review')!({}, { pluginId, release });+ current = result as ContributionReleaseView;+ return current;+ }),+ };+ render(+ <StrictMode>+ <MemoryRouter initialEntries={['/plugins?myPlugins=1&contribution=plugin']}>+ <ConfirmDialogProvider>+ <MyPluginsPage reader={api} localPlugins={[]} installedPluginCount={0} cache={{}}+ onSubmitUpdate={vi.fn()} onViewLocal={vi.fn()} />+ </ConfirmDialogProvider>+ </MemoryRouter>+ </StrictMode>,+ );+ return api;+}++beforeAll(() => registerPluginContributionsIpc());+beforeEach(() => { host.cancelReview.mockReset(); });+afterEach(cleanup);++describe('review cancellation through the real confirmation and IPC validation', () => {+ it('keeps the review when the user dismisses the confirmation and enables the opener again', async () => {+ const api = view();+ await screen.findByRole('region', { name: `${prefix}.versionManagement` });+ fireEvent.click(await screen.findByRole('button', { name: `${prefix}.cancelReview` }));+ const dialog = await screen.findByRole('alertdialog');+ expect(host.cancelReview).not.toHaveBeenCalled();+ const keep = within(dialog).getByRole('button', { name: `${prefix}.keepReview` });+ await waitFor(() => expect(document.activeElement).toBe(keep));+ fireEvent.click(keep);+ await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull());+ expect(api.cancelReview).not.toHaveBeenCalled();+ expect((screen.getByRole('button', { name: `${prefix}.cancelReview` }) as HTMLButtonElement).disabled).toBe(false);+ });++ it.each(['cancelled', 'approved'] as const)('sends only the frozen revision and displays the actual %s result after confirmation', async status => {+ host.cancelReview.mockResolvedValue({ ...pending, reviewStatus: status, canCancelReview: false, cancelledAt: status === 'cancelled' ? at : null, approvedAt: status === 'approved' ? at : null });+ const api = view();+ await screen.findByRole('region', { name: `${prefix}.versionManagement` });+ fireEvent.click(await screen.findByRole('button', { name: `${prefix}.cancelReview` }));+ const dialog = await screen.findByRole('alertdialog');+ expect(api.cancelReview).not.toHaveBeenCalled();+ fireEvent.click(within(dialog).getByRole('button', { name: `${prefix}.cancelReview` }));+ await waitFor(() => expect(host.cancelReview).toHaveBeenCalledExactlyOnceWith('plugin', {+ releaseId: pending.releaseId, sha256: pending.sha256, revision: pending.revision,+ }));+ expect(await screen.findByText(`${prefix}.${status === 'cancelled' ? 'cancelReviewCompleted' : 'cancelReviewAlreadyFinal'}`)).toBeTruthy();+ await waitFor(() => expect(screen.queryByRole('button', { name: `${prefix}.cancelReview` })).toBeNull());+ });++ it('shows a rejected cancellation and allows the user to try again without losing the pending version', async () => {+ host.cancelReview.mockRejectedValue(new Error('[PERMISSION_DENIED] Permission changed'));+ view();+ fireEvent.click(await screen.findByRole('button', { name: `${prefix}.cancelReview` }));+ const dialog = await screen.findByRole('alertdialog');+ fireEvent.click(within(dialog).getByRole('button', { name: `${prefix}.cancelReview` }));+ const alert = await screen.findByRole('alert');+ expect(alert.textContent).toContain(`${prefix}.permissionDenied`);+ expect(host.cancelReview).toHaveBeenCalledTimes(1);+ expect((screen.getByRole('button', { name: `${prefix}.cancelReview` }) as HTMLButtonElement).disabled).toBe(false);+ expect(screen.getByText('Complete version changes')).toBeTruthy();+ });+});diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/MyPluginsPage.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/MyPluginsPage.test.tsxnew file mode 100644index 0000000000..436380a11f--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/__tests__/MyPluginsPage.test.tsx@@ -0,0 +1,1191 @@+/** @vitest-environment jsdom */+import { StrictMode } from 'react';+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type {+ PluginReviewUpdate,+ PreparedPluginContribution,+ MyPluginDetailView,+ ContributionReleaseView,+ PluginContributionsApi,+ ContributionTransferView,+} from '../../../../shared/pluginContributions';+import type { PluginMarketDetail } from '../../../../shared/pluginMarket';+import type { GhostPluginListItem } from '../lib/ghostPluginViewModel';+import { MyPluginsPage, type MyPluginsPageCache, type PluginSubmitOptions } from '../MyPluginsPage';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, args?: Record<string, unknown>) =>+ args?.version ? `${key} ${args.version}` : args?.value !== undefined ? `${key} ${args.value}` : key,+ i18n: { language: 'en', resolvedLanguage: 'en' },+ }),+}));+const confirmation = vi.hoisted(() => ({ confirm: vi.fn(async () => true) }));+vi.mock('@/components/ui/confirm-dialog-provider', () => ({ useConfirmDialog: () => confirmation }));+const auth = vi.hoisted(() => ({ owner: 'A', generation: 1 }));+vi.mock('@/contexts/AuthContext', () => ({+ useAuth: () => ({+ dataOwnerId: `owner-${auth.owner}`,+ dataOwnerGeneration: auth.generation,+ user: { id: `member-${auth.owner}`, membershipKind: 'personal' },+ mode: 'cloud',+ }),+}));+vi.mock('@/components/sidebar/AccountSwitcherDialog', () => ({+ AccountSwitcherDialog: () => null,+}));+vi.mock('@/hooks/useSignInToCindy', () => ({ useSignInToCindy: () => vi.fn() }));+vi.mock('@/hooks/useMacFullscreen', () => ({ useMacFullscreen: () => ({ isMac: false }) }));++const reviews = vi.hoisted(() => ({ updates: [] as PluginReviewUpdate[], refresh: vi.fn(), markRead: vi.fn() }));+vi.mock('@/contexts/PluginReviewUpdatesContext', () => ({ usePluginReviewUpdates: () => reviews }));+const prefix = 'settings.ghosts.contribution';+const at = '2026-10-15T00:00:00.000Z';+const detail: MyPluginDetailView = {+ plugin: {+ pluginId: 'plugin-1',+ name: 'My Plugin',+ iconUrl: null,+ updatedAt: at,+ market: { state: 'available', version: '1.0.0', releaseId: 'old-release', reason: null },+ latestSubmission: {+ releaseId: 'new-release',+ version: '2.0.0',+ sha256: 'a'.repeat(64),+ revision: at,+ revisionState: 'current',+ submissionId: 'submission-1',+ reviewStatus: 'rejected',+ submittedAt: at,+ reviewedAt: at,+ reason: 'Full reason, line one\nFull reason, line two',+ source: 'manual',+ content: {+ name: 'My Plugin',+ description: 'Plugin description',+ iconUrl: null,+ permissions: [],+ manifestView: { releaseNotes: 'New version changes' },+ },+ },+ actions: { submitUpdate: true, viewMarket: true },+ localInstanceId: 'exact-instance',+ localVersion: '1.2.0',+ localInstallation: { state: 'installed', instanceId: 'exact-instance', version: '1.2.0', origin: 'local', enabled: true },+ },+ history: ['submitted', 'approved', 'disabled'].map((type, index) => ({+ eventId: `event-${index}`,+ type: type as 'submitted' | 'approved' | 'disabled',+ at,+ releaseId: 'old-release',+ version: '1.0.0',+ submissionId: null,+ reason: null,+ revision: { releaseId: 'old-release', sha256: 'b'.repeat(64), displayUpdatedAt: at },+ })),+ nextCursor: null,+ queriedAt: at,+};+function packagePreview(instanceId: string, version = '1.0.0'): PreparedPluginContribution {+ return { preparedId: 'chosen-snapshot', instanceId, pluginId: null, ghostId: 'demo',+ name: 'Local Plugin', description: 'Actual selected package', version,+ sha256: 'a'.repeat(64), sizeBytes: 100, expiresAt: '2099-01-01T00:00:00Z',+ preflight: { subject: { authority: 'https://issuer.test', membershipId: 'member-A' },+ queriedAt: at, policyVersion: 2, target: { pluginId: null, ghostId: 'demo', version, expectedRelease: null },+ pendingRelease: null, blockers: [], actions: { canSubmit: true } } };+}+function reader(transfers: ContributionTransferView[] = []): PluginContributionsApi {+ return {+ reviewUpdates: vi.fn().mockResolvedValue([]),+ markReviewRead: vi.fn(),+ prepare: vi.fn(),+ submit: vi.fn(),+ resume: vi.fn(),+ cancel: vi.fn(),+ cancelReview: vi.fn(),+ discard: vi.fn().mockResolvedValue(undefined),+ status: vi.fn(),+ submission: vi.fn(),+ releases: vi.fn().mockResolvedValue({ releases: [], nextCursor: null, queriedAt: at }),+ transfers: vi.fn().mockResolvedValue(transfers),+ setAnonymity: vi.fn(),+ detail: vi.fn().mockResolvedValue(detail),+ list: vi.fn().mockResolvedValue({ plugins: [detail.plugin], nextCursor: null, queriedAt: at }),+ };+}+function view(+ api: PluginContributionsApi,+ selected = true,+ cache: MyPluginsPageCache = {},+ localPlugins: GhostPluginListItem[] = [{ id: 'exact-instance', name: 'Local Plugin', version: '1.2.0' } as GhostPluginListItem],+ onSubmitUpdate = vi.fn().mockResolvedValue(false),+ installedPluginCount = localPlugins.length,+) {+ return render(+ <StrictMode>+ <MemoryRouter+ initialEntries={[`/plugins?myPlugins=1${selected ? '&contribution=plugin-1' : ''}`]}+ >+ <MyPluginsPage+ localPlugins={localPlugins}+ installedPluginCount={installedPluginCount}+ reader={api}+ cache={cache}+ onSubmitUpdate={onSubmitUpdate}+ onViewLocal={vi.fn()}+ />+ </MemoryRouter>+ </StrictMode>,+ );+}+async function openHistory() {+ const disclosure = (await screen.findByText(`${prefix}.history`)).closest('details')!;+ if (!disclosure.open) fireEvent.click(within(disclosure).getByText(`${prefix}.history`));+ await waitFor(() => expect(disclosure.open).toBe(true));+}+async function waitForManagement() {+ await screen.findByRole('region', { name: `${prefix}.versionManagement` });+}+async function selectPublishingPlugin(label: string) {+ const option = within(screen.getByRole('dialog')).getByRole('button', { name: label });+ await waitFor(() => expect(option).toHaveProperty('disabled', false));+ fireEvent.click(option);+}+beforeEach(() => {+ // Radix scrolls keyboard-focused options; jsdom has no layout implementation.+ Element.prototype.scrollIntoView = vi.fn();+ reviews.updates = []; reviews.refresh.mockReset(); reviews.markRead.mockReset();+ auth.owner = 'A';+ auth.generation = 1;+});+afterEach(cleanup);++describe('My Plugins facts', () => {+ it('opens an independent management page with immediately visible versions and publishing controls', async () => {+ const api = reader();+ view(api);+ await waitForManagement();+ expect(screen.getByLabelText(`${prefix}.versionFacts`).closest('details')).toBeNull();+ expect(screen.getByRole('button', { name: `${prefix}.submitVersion 1.2.0` })).toBeTruthy();+ expect(screen.getByText('New version changes')).toBeTruthy();+ expect(screen.queryByText(`${prefix}.versionUpdates`)).toBeNull();+ expect(screen.queryByRole('switch', { name: 'settings.ghosts.enableAria' })).toBeNull();+ expect(api.prepare).not.toHaveBeenCalled();+ });++ it('shows the running version in the developer list and opens management without preparing a package', async () => {+ const api = reader();+ view(api, false);+ const row = await screen.findByRole('button', { name: /My Plugin/ });+ expect(within(row).getByText('1.2.0')).toBeTruthy();+ expect(within(row).getByText(`${prefix}.versionManagement`)).toBeTruthy();+ fireEvent.click(row);+ await waitForManagement();+ expect(within(screen.getByLabelText(`${prefix}.versionFacts`)).getByText('1.2.0')).toBeTruthy();+ expect(screen.getByRole('button', { name: `${prefix}.submitVersion 1.2.0` })).toBeTruthy();+ expect(api.prepare).not.toHaveBeenCalled();+ expect(api.submit).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: `${prefix}.myPlugins` }));+ expect(await screen.findByRole('button', { name: /My Plugin/ })).toBeTruthy();+ });++ it('preserves a confirmed original author anonymity setting after publishing grant revocation', async () => {+ const api = reader();+ vi.mocked(api.detail).mockResolvedValue({ ...detail, plugin: { ...detail.plugin,+ actions: { submitUpdate: false, viewMarket: true }, authorSettings: { anonymous: true, canEdit: true } } });+ view(api);+ await waitForManagement();+ const control = await screen.findByRole('switch', { name: `${prefix}.anonymous` });+ await waitFor(() => expect(control).toHaveProperty('disabled', false));+ expect(screen.queryByRole('button', { name: `${prefix}.submitVersion 1.2.0` })).toBeNull();+ expect(api.setAnonymity).not.toHaveBeenCalled();+ });+ it('hides submission while a version is pending without hiding its management details', async () => {+ const api = reader();+ vi.mocked(api.detail).mockResolvedValue({ ...detail, plugin: { ...detail.plugin,+ latestSubmission: { ...detail.plugin.latestSubmission!, reviewStatus: 'pending' } } });+ view(api);+ await waitForManagement();+ expect(screen.queryByRole('button', { name: `${prefix}.submitVersion 1.2.0` })).toBeNull();+ expect(screen.getByText('New version changes')).toBeTruthy();+ expect(api.prepare).not.toHaveBeenCalled();+ });++ it('hides submission when the installed version number has already been submitted', async () => {+ const api = reader();+ vi.mocked(api.detail).mockResolvedValue({ ...detail, plugin: { ...detail.plugin, localVersion: '2.0.0', localInstallation: { state: 'installed', instanceId: 'exact-instance', version: '2.0.0', origin: 'local', enabled: true } } });+ view(api);+ await waitForManagement();+ expect(screen.queryByRole('button', { name: `${prefix}.submitVersion 1.2.0` })).toBeNull();+ expect(screen.getByText('New version changes')).toBeTruthy();+ expect(api.prepare).not.toHaveBeenCalled();+ });++ it('keeps cached history readable but hides submission after the current permission read fails', async () => {+ const api = reader();+ view(api);+ await waitForManagement();+ const update = await screen.findByRole('button', { name: `${prefix}.submitVersion 1.2.0` });+ await waitFor(() => expect(update).toHaveProperty('disabled', false));+ vi.mocked(api.detail).mockRejectedValueOnce(new Error('[PERMISSION_DENIED] revoked'));+ fireEvent.click(screen.getByRole('button', { name: `${prefix}.refreshDetail` }));+ await waitFor(() => expect(screen.queryByRole('button', { name: `${prefix}.submitVersion 1.2.0` })).toBeNull());+ expect(screen.getByText('New version changes')).toBeTruthy();+ expect(api.submit).not.toHaveBeenCalled();+ expect(api.setAnonymity).not.toHaveBeenCalled();+ });+ it.each(['failed', 'expired', 'validating', 'awaiting_upload'] as const)(+ 'shows server submissions rather than an internal %s upload record', async operationStatus => {+ const transfer: ContributionTransferView = {+ localId: 'attempt', stage: operationStatus === 'failed' || operationStatus === 'expired' ? 'complete' : 'paused', errorCode: null,+ prepared: { preparedId: 'attempt', instanceId: 'exact-instance', pluginId: null, ghostId: 'hello', name: 'Unsubmitted upload', description: '', version: '1.0.0', sha256: 'a'.repeat(64), sizeBytes: 100, expiresAt: at },+ operation: { subject: { authority: 'https://issuer.test', membershipId: 'member-A' }, operationId: 'operation', status: operationStatus, createdAt: at, updatedAt: at, expiresAt: at, receipt: null, submission: null, failure: null },+ };+ const api = reader([transfer]);+ view(api, false);+ fireEvent.click(await screen.findByRole('button', { name: /My Plugin/ }));+ await waitForManagement();+ expect(screen.queryByText('Unsubmitted upload')).toBeNull();+ expect(screen.queryByText(`${prefix}.resume`)).toBeNull();+ expect(screen.queryByText(`${prefix}.retryPublish`)).toBeNull();+ expect(screen.getByText('Full reason, line one Full reason, line two')).toBeTruthy();+ expect(api.transfers).not.toHaveBeenCalled();+ expect(api.status).not.toHaveBeenCalled();+ expect(api.resume).not.toHaveBeenCalled();+ expect(api.submit).not.toHaveBeenCalled();+ },+ );++ it('keeps the exact publishing selection and package preview in the dialog until submission', async () => {+ const api = reader();+ vi.mocked(api.list).mockResolvedValue({ plugins: [], nextCursor: null, queriedAt: at });+ const submit = vi.fn().mockResolvedValue(false);+ const prepared = packagePreview('exact-instance-b');+ vi.mocked(api.prepare).mockResolvedValue(prepared);+ vi.mocked(api.discard).mockResolvedValue(undefined);+ const installations = ['exact-instance-a', 'exact-instance-b'].map(+ (id) =>+ ({+ id,+ name: 'Same Name',+ version: '1.0.0',+ }) as GhostPluginListItem,+ );+ view(api, false, {}, installations, submit);+ await screen.findByText(`${prefix}.empty`);+ expect(screen.queryByRole('textbox', { name: `${prefix}.search` })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: `${prefix}.publishPlugin` }));+ const picker = screen.getByRole('dialog');+ expect(submit).not.toHaveBeenCalled();+ expect(api.prepare).not.toHaveBeenCalled();+ expect(api.submit).not.toHaveBeenCalled();+ await selectPublishingPlugin('Same Name · 1.0.0 · exact-instance-b');+ await within(picker).findByText('Actual selected package');+ expect(api.prepare).toHaveBeenCalledWith('exact-instance-b');+ expect(api.submit).not.toHaveBeenCalled();+ expect(screen.getByRole('dialog')).toBe(picker);+ fireEvent.click(within(picker).getByRole('button', { name: `${prefix}.submitVersion 1.0.0` }));+ await waitFor(() => expect(submit).toHaveBeenCalledWith('exact-instance-b', expect.objectContaining({ prepared, isCurrent: expect.any(Function) })));+ expect(screen.getByRole('dialog')).toBe(picker);+ });++ it('explains official GitHub publishing in management and the picker despite a submission grant', async () => {+ const api = reader();+ const official = { ...detail.plugin, publisherKind: 'official' as const };+ vi.mocked(api.detail).mockResolvedValue({ ...detail, plugin: official });+ vi.mocked(api.list).mockResolvedValue({ plugins: [official], nextCursor: null, queriedAt: at });+ view(api);+ await waitForManagement();+ expect(screen.getByText(`${prefix}.unavailable.officialGithubRequired`)).toBeTruthy();+ expect(screen.queryByRole('button', { name: `${prefix}.submitVersion 1.2.0` })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: `${prefix}.myPlugins` }));+ fireEvent.click(screen.getByRole('button', { name: `${prefix}.publishPlugin` }));+ const picker = screen.getByRole('dialog');+ const option = within(picker).getByRole('button', { name: 'Local Plugin · 1.2.0 · exact-instance' });+ expect(await within(option).findByText(`${prefix}.unavailable.officialGithubRequired`)).toBeTruthy();+ expect(option).toHaveProperty('disabled', true);+ fireEvent.click(option);+ expect(api.prepare).not.toHaveBeenCalled();+ expect(api.submit).not.toHaveBeenCalled();+ });++ it('explains GitHub publishing for an official plugin that is not installed on this computer', async () => {+ const api = reader();+ vi.mocked(api.detail).mockResolvedValue({ ...detail, plugin: { ...detail.plugin,+ publisherKind: 'official', localInstanceId: null, localVersion: null, localInstallation: { state: 'missing' } } });+ view(api);+ await waitForManagement();+ expect(screen.getByText(`${prefix}.unavailable.officialGithubRequired`)).toBeTruthy();+ expect(screen.queryByRole('button', { name: `${prefix}.submitVersion 1.2.0` })).toBeNull();+ expect(api.prepare).not.toHaveBeenCalled();+ });++ it.each(['cancelled', 'pending', 'denied'] as const)(+ 'explains an unavailable %s version before it can be selected', async state => {+ const api = reader();+ const plugin = { ...detail.plugin,+ market: { state: 'not_listed' as const, version: null, releaseId: null, reason: null },+ actions: { submitUpdate: state !== 'denied', viewMarket: false },+ latestSubmission: { ...detail.plugin.latestSubmission!,+ version: state === 'pending' ? '1.1.0' : '1.0.0',+ reviewStatus: state === 'cancelled' ? 'cancelled' as const : 'pending' as const } };+ vi.mocked(api.list).mockResolvedValue({ plugins: [plugin], nextCursor: null, queriedAt: at });+ const local = { id: 'exact-instance', name: 'Local Plugin', version: '1.0.0' } as GhostPluginListItem;+ view(api, false, {}, [local]);+ fireEvent.click(screen.getByRole('button', { name: `${prefix}.publishPlugin` }));+ const picker = screen.getByRole('dialog');+ const option = within(picker).getByRole('button', { name: 'Local Plugin · 1.0.0 · exact-instance' });+ const reason = state === 'denied' ? `${prefix}.permissionDenied`+ : `${prefix}.errors.${state === 'pending' ? 'PLUGIN_PENDING_RELEASE_EXISTS' : 'VERSION_ALREADY_SUBMITTED'}`;+ expect(await within(option).findByText(reason)).toBeTruthy();+ expect(option).toHaveProperty('disabled', true);+ fireEvent.click(option);+ expect(api.prepare).not.toHaveBeenCalled();+ expect(api.submit).not.toHaveBeenCalled();+ expect(within(picker).queryByRole('button', { name: `${prefix}.submitVersion 1.0.0` })).toBeNull();+ },+ );++ it('keeps an older-version preflight blocker outside the scrollable package summary', async () => {+ const api = reader();+ const local = { id: 'exact-instance', name: 'Local Plugin', version: '0.9.0' } as GhostPluginListItem;+ const prepared = packagePreview(local.id, local.version);+ prepared.preflight!.actions.canSubmit = false;+ prepared.preflight!.blockers = [{ code: 'VERSION_ALREADY_SUBMITTED', message: 'This earlier version was already submitted' }];+ vi.mocked(api.prepare).mockResolvedValue(prepared);+ view(api, false, {}, [local]);+ fireEvent.click(screen.getByRole('button', { name: `${prefix}.publishPlugin` }));+ await selectPublishingPlugin('Local Plugin · 0.9.0 · exact-instance');+ const picker = screen.getByRole('dialog');+ const reason = await within(picker).findByText('This earlier version was already submitted');+ const summary = within(picker).getByRole('region', { name: `${prefix}.publishingVersion 0.9.0` });+ expect(summary.contains(reason)).toBe(false);+ expect(reason.getAttribute('role')).toBe('status');+ expect(within(picker).queryByRole('button', { name: `${prefix}.submitVersion 0.9.0` })).toBeNull();+ expect(api.submit).not.toHaveBeenCalled();+ });++ it('keeps choices unavailable when reading all submission pages fails', async () => {+ const api = reader();+ vi.mocked(api.list).mockImplementation(async options => {+ if (options?.cursor) throw new Error('Next page unavailable');+ return { plugins: [], nextCursor: 'unread-page', queriedAt: at };+ });+ const local = { id: 'exact-instance', name: 'Local Plugin', version: '1.0.0' } as GhostPluginListItem;+ view(api, false, {}, [local]);+ fireEvent.click(screen.getByRole('button', { name: `${prefix}.publishPlugin` }));+ const picker = screen.getByRole('dialog');+ expect(await within(picker).findByRole('alert')).toHaveProperty('textContent', `${prefix}.loadFailed`);+ const option = within(picker).getByRole('button', { name: 'Local Plugin · 1.0.0 · exact-instance' });+ expect(option).toHaveProperty('disabled', true);+ fireEvent.click(option);+ expect(api.prepare).not.toHaveBeenCalled();+ expect(api.submit).not.toHaveBeenCalled();+ });++ // Unit: the old picker navigated on selection. These cases exercise the real+ // dialog lifecycle; ordinary page-entry tests did not cover close/reopen ABA.+ it('discards a snapshot that arrives after closing and reopening the same selection', async () => {+ const api = reader();+ vi.mocked(api.list).mockResolvedValue({ plugins: [], nextCursor: null, queriedAt: at });+ const local = { id: 'exact-instance', name: 'Local Plugin', version: '1.0.0' } as GhostPluginListItem;+ let finish!: (value: Awaited<ReturnType<PluginContributionsApi['prepare']>>) => void;+ const old = new Promise<Awaited<ReturnType<PluginContributionsApi['prepare']>>>(resolve => { finish = resolve; });+ const current = { ...packagePreview(local.id), preparedId: 'current-package', description: 'Current package preview' };+ vi.mocked(api.prepare).mockReturnValueOnce(old).mockResolvedValue(current);+ view(api, false, {}, [local]);+ const choose = async () => {+ fireEvent.click(screen.getByRole('button', { name: `${prefix}.publishPlugin` }));+ await selectPublishingPlugin('Local Plugin · 1.0.0 · exact-instance');+ };+ await choose();+ await waitFor(() => expect(api.prepare).toHaveBeenCalledTimes(1));+ fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'settings.ghosts.detail.closeDialog' }));+ await choose();+ await screen.findByText('Current package preview');+ await act(async () => { finish({ ...current, preparedId: 'abandoned-package', description: 'Abandoned package preview' }); });+ expect(screen.queryByText('Abandoned package preview')).toBeNull();+ expect(screen.getByRole('dialog')).toBeTruthy();+ expect(api.discard).toHaveBeenCalledWith('abandoned-package');+ expect(api.submit).not.toHaveBeenCalled();+ });++ it('keeps a reopened dialog when an earlier submission finishes', async () => {+ const api = reader();+ vi.mocked(api.list).mockResolvedValue({ plugins: [], nextCursor: null, queriedAt: at });+ const local = { id: 'exact-instance', name: 'Local Plugin', version: '1.0.0' } as GhostPluginListItem;+ const prepared = packagePreview(local.id);+ vi.mocked(api.prepare).mockResolvedValue(prepared);+ let finish!: (submitted: boolean) => void;+ const submit = vi.fn<(id: string, options?: PluginSubmitOptions) => Promise<boolean>>().mockImplementation(() => new Promise<boolean>(resolve => { finish = resolve; }));+ view(api, false, {}, [local], submit);+ const choose = async () => {+ fireEvent.click(screen.getByRole('button', { name: `${prefix}.publishPlugin` }));+ await selectPublishingPlugin('Local Plugin · 1.0.0 · exact-instance');+ return within(screen.getByRole('dialog')).findByRole('button', { name: `${prefix}.submitVersion 1.0.0` });+ };+ fireEvent.click(await choose());+ await waitFor(() => expect(submit).toHaveBeenCalledTimes(1));+ fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'settings.ghosts.detail.closeDialog' }));+ await choose();+ await act(async () => { finish(true); });+ expect(screen.getByRole('dialog')).toBeTruthy();+ expect(submit.mock.calls[0][1]?.isCurrent?.()).toBe(false);+ });++ it.each([+ { installed: 0, expected: 'noLocalPlugins', absent: 'noPublishablePlugins' },+ { installed: 3, expected: 'noPublishablePlugins', absent: 'noLocalPlugins' },+ ])(+ 'distinguishes an empty publishing selection with $installed installed plugins',+ async ({ installed, expected, absent }) => {+ const api = reader();+ const open = vi.fn();+ view(api, false, {}, [], open, installed);+ fireEvent.click(screen.getByRole('button', { name: `${prefix}.publishPlugin` }));+ const picker = screen.getByRole('dialog');+ expect(within(picker).getByText(`${prefix}.${expected}`)).toBeTruthy();+ expect(within(picker).queryByText(`${prefix}.${absent}`)).toBeNull();+ expect(within(picker).getAllByRole('button')).toHaveLength(1); // Close only.+ expect(open).not.toHaveBeenCalled();+ expect(api.prepare).not.toHaveBeenCalled();+ expect(api.submit).not.toHaveBeenCalled();+ },+ );++ it('closes the local selection on an owner change without opening an old installation', async () => {+ const api = reader();+ const cache: MyPluginsPageCache = {};+ const open = vi.fn();+ const localPlugins = [+ { id: 'private-A', name: 'Owner A', version: '1' } as GhostPluginListItem,+ ];+ const element = () => (+ <MemoryRouter initialEntries={['/plugins?myPlugins=1']}>+ <MyPluginsPage+ reader={api}+ cache={cache}+ localPlugins={localPlugins}+ installedPluginCount={localPlugins.length}+ onSubmitUpdate={vi.fn()}+ onViewLocal={vi.fn()}+ />+ </MemoryRouter>+ );+ const rendered = render(element());+ fireEvent.click(screen.getByRole('button', { name: `${prefix}.publishPlugin` }));+ expect(screen.getByRole('dialog')).toBeTruthy();+ auth.owner = 'B';+ auth.generation++;+ rendered.rerender(element());+ expect(screen.queryByRole('dialog')).toBeNull();+ auth.owner = 'A';+ auth.generation++;+ rendered.rerender(element());+ expect(screen.queryByRole('dialog')).toBeNull();+ expect(open).not.toHaveBeenCalled();+ });++ it('keeps an available old market version separate from the latest rejected version', async () => {+ const api = reader();+ view(api);+ await waitForManagement();+ const facts = await screen.findByLabelText(`${prefix}.versionFacts`);+ expect(within(facts).getByText('1.0.0')).toBeTruthy();+ expect(within(facts).getByText('1.2.0')).toBeTruthy();+ expect(within(facts).getByText(`${prefix}.noPendingVersion`)).toBeTruthy();+ expect(screen.getByText('2.0.0')).toBeTruthy();+ expect(screen.getByText(`${prefix}.review.rejected`)).toBeTruthy();+ expect(screen.getByText('Full reason, line one Full reason, line two')).toBeTruthy();+ expect(screen.queryByRole('button', { name: `${prefix}.viewMarket` })).toBeNull();+ expect(screen.queryByRole('button', { name: `${prefix}.openLocal` })).toBeNull();+ expect(screen.getByRole('button', { name: `${prefix}.submitVersion 1.2.0` })).toBeTruthy();+ const history = screen.getByText(`${prefix}.history`).closest('details')!;+ expect(history.open).toBe(false);+ await openHistory();+ // Effect replay must still accept the result; all three events share a revision.+ expect(screen.getByText(`1.0.0 · ${prefix}.event.submitted`)).toBeTruthy();+ expect(screen.getByText(`1.0.0 · ${prefix}.event.approved`)).toBeTruthy();+ expect(screen.getByText(`1.0.0 · ${prefix}.event.disabled`)).toBeTruthy();+ });++ it('rechecks Main association before enabling submission after installation replacement', async () => {+ const api = reader();+ const element = (revision: string) => <MemoryRouter initialEntries={['/plugins?myPlugins=1&contribution=plugin-1']}>+ <MyPluginsPage reader={api} localPlugins={[{ id: 'exact-instance', name: 'Local Plugin', version: '1.2.0' } as GhostPluginListItem]} installedPluginCount={1} cache={{}} onSubmitUpdate={vi.fn()} onViewLocal={vi.fn()}+ installedRevision={revision} />+ </MemoryRouter>;+ const rendered = render(element('original-approved-package'));+ await waitFor(() => expect(screen.getByRole('button', { name: `${prefix}.submitVersion 1.2.0` })).toHaveProperty('disabled', false));+ let finish!: (value: MyPluginDetailView) => void;+ vi.mocked(api.detail).mockReturnValue(new Promise(resolve => { finish = resolve; }));+ const reads = vi.mocked(api.detail).mock.calls.length;+ rendered.rerender(element('replacement-package'));+ expect(screen.queryByRole('button', { name: `${prefix}.submitVersion 1.2.0` })?.hasAttribute('disabled') ?? true).toBe(true);+ await waitFor(() => expect(vi.mocked(api.detail).mock.calls.length).toBeGreaterThan(reads));+ await act(async () => { finish({ ...detail, plugin: { ...detail.plugin, localInstanceId: null, localVersion: null, localInstallation: { state: 'missing' } } }); });+ expect(screen.queryByRole('button', { name: `${prefix}.submitVersion 1.2.0` })?.hasAttribute('disabled') ?? true).toBe(true);+ expect(within(screen.getByLabelText(`${prefix}.versionFacts`)).getByText(`${prefix}.localState.missing`)).toBeTruthy();+ expect(api.prepare).not.toHaveBeenCalled();+ });++ it.each(['unchanged', 'replacement', 'other-owner'] as const)(+ 'does not enable submission from offline cached management data (%s)', async scenario => {+ const api = reader(); vi.mocked(api.detail).mockRejectedValue(new Error('Offline'));+ const cache: MyPluginsPageCache = { ownerKey: JSON.stringify(['owner-A', 1, 'member-A', 'cloud']),+ detail, installationRevision: 'approved-installation' };+ if (scenario === 'other-owner') { auth.owner = 'B'; auth.generation++; }+ render(<MemoryRouter initialEntries={['/plugins?myPlugins=1&contribution=plugin-1']}>+ <MyPluginsPage reader={api} localPlugins={[]} installedPluginCount={0} cache={cache}+ onSubmitUpdate={vi.fn()} onViewLocal={vi.fn()} installedRevision={scenario === 'replacement' ? 'replaced' : 'approved-installation'}+ />+ </MemoryRouter>);+ await waitFor(() => expect(api.detail).toHaveBeenCalled());+ expect(screen.queryByRole('button', { name: `${prefix}.submitVersion 1.2.0` })?.hasAttribute('disabled') ?? true).toBe(true);+ expect(Boolean(screen.queryByRole('heading', { name: 'My Plugin' }))).toBe(scenario !== 'other-owner');+ expect(api.prepare).not.toHaveBeenCalled();+ },+ );++ it('refreshes the current installation generation after an awaited normal install completes', async () => {+ const api = reader();+ vi.mocked(api.detail).mockResolvedValue({ ...detail, plugin: { ...detail.plugin, localInstanceId: null, localVersion: null, localInstallation: { state: 'missing' } } });+ let finish!: () => void;+ const install = vi.fn(() => new Promise<void>(resolve => { finish = resolve; }));+ const element = (revision: string) => <MemoryRouter initialEntries={['/plugins?myPlugins=1&contribution=plugin-1']}>+ <MyPluginsPage reader={api} localPlugins={[]} installedPluginCount={0} cache={{}}+ onSubmitUpdate={vi.fn()} onViewLocal={vi.fn()} installedRevision={revision}+ onInstallPublished={install} />+ </MemoryRouter>;+ const rendered = render(element('not-installed'));+ await waitForManagement();+ fireEvent.click(await screen.findByRole('button', { name: `${prefix}.installPublished` }));+ vi.mocked(api.detail).mockResolvedValue(detail);+ rendered.rerender(element('new-approved-installation'));+ await waitFor(() => expect(within(screen.getByLabelText(`${prefix}.versionFacts`)).getByText('1.2.0')).toBeTruthy());+ const reads = vi.mocked(api.detail).mock.calls.length;+ await act(async () => { finish(); });+ await waitFor(() => expect(vi.mocked(api.detail).mock.calls.length).toBeGreaterThan(reads));+ expect(within(screen.getByLabelText(`${prefix}.versionFacts`)).getByText('1.2.0')).toBeTruthy();+ expect(install).toHaveBeenCalledExactlyOnceWith('plugin-1');+ expect(api.prepare).not.toHaveBeenCalled();+ });++ it('refreshes a confirmed submission in place without replacing the management page', async () => {+ const api = reader();+ const cache: MyPluginsPageCache = {};+ const tree = (revision: number) => (+ <MemoryRouter initialEntries={['/plugins?myPlugins=1&contribution=plugin-1']}>+ <MyPluginsPage reader={api} localPlugins={[]} installedPluginCount={1} cache={cache}+ onSubmitUpdate={vi.fn()} onViewLocal={vi.fn()} submissionRevision={revision} />+ </MemoryRouter>+ );+ const rendered = render(tree(0));+ await waitForManagement();+ const heading = screen.getByRole('heading', { name: 'My Plugin' });+ const reads = vi.mocked(api.detail).mock.calls.length;+ const pending = { ...detail.plugin.latestSubmission!, releaseId: 'confirmed-submission',+ version: '2.1.0', reviewStatus: 'pending' as const, reviewedAt: null, reason: null };+ vi.mocked(api.detail).mockResolvedValue({ ...detail, plugin: { ...detail.plugin, latestSubmission: pending } });+ vi.mocked(api.releases).mockResolvedValue({ releases: [pending], nextCursor: null, queriedAt: at });+ rendered.rerender(tree(1));+ await waitFor(() => expect(vi.mocked(api.detail).mock.calls.length).toBeGreaterThan(reads));+ await waitFor(() => expect(within(screen.getByLabelText(`${prefix}.versionFacts`)).getByText('2.1.0')).toBeTruthy());+ expect(screen.getByRole('heading', { name: 'My Plugin' })).toBe(heading);+ const facts = screen.getByLabelText(`${prefix}.versionFacts`);+ expect(within(facts).getByText('1.0.0')).toBeTruthy();+ expect(within(facts).getByText('1.2.0')).toBeTruthy();+ expect(api.prepare).not.toHaveBeenCalled();+ expect(api.submit).not.toHaveBeenCalled();+ });++ it('retains this account snapshot after a failed foreground read and labels it as cached', async () => {+ const api = reader();+ view(api);+ await waitForManagement();+ await screen.findByLabelText(`${prefix}.versionFacts`);+ vi.mocked(api.detail).mockRejectedValueOnce(new Error('offline'));+ await act(async () => {+ screen.getByRole('button', { name: `${prefix}.refreshDetail` }).click();+ });+ await waitFor(() =>+ expect(screen.getByRole('alert').textContent).toContain(`${prefix}.cachedResult`),+ );+ expect(within(screen.getByLabelText(`${prefix}.versionFacts`)).getByText('1.0.0')).toBeTruthy();+ });+ it('selects an exact historical version with its own notes, decision and timestamps', async () => {+ const api = reader();+ const historic: ContributionReleaseView = {+ ...detail.plugin.latestSubmission!,+ releaseId: 'old-release',+ version: '1.0.0',+ submissionId: 'old-submission',+ sha256: 'b'.repeat(64),+ reviewStatus: 'approved',+ approvedAt: '2026-10-11T09:00:00.000Z',+ submittedAt: '2026-10-10T08:00:00.000Z',+ reviewedAt: '2026-10-11T09:00:00.000Z',+ reason: null,+ content: null,+ };+ vi.mocked(api.releases).mockResolvedValue({+ releases: [detail.plugin.latestSubmission!, historic],+ nextCursor: null,+ queriedAt: at,+ });+ vi.mocked(api.submission).mockResolvedValue({+ ...historic,+ content: {+ name: 'Old plugin content',+ description: 'Old description',+ permissions: [],+ iconUrl: null,+ manifestView: { releaseNotes: 'First released functionality' },+ },+ });+ view(api);+ await waitForManagement();+ await openHistory();+ const selector = await screen.findByRole('combobox', { name: `${prefix}.chooseVersion` });+ expect(selector.textContent).toBe('2.0.0');+ fireEvent.keyDown(selector, { key: 'ArrowDown' });+ fireEvent.click(await screen.findByRole('option', { name: /1.0.0/ }));+ expect(await screen.findByText('First released functionality')).toBeTruthy();+ expect(screen.getAllByText('Plugin description').some(element => !element.closest('details'))).toBe(true); // Historical selection never replaces the overview.+ expect(api.submission).toHaveBeenCalledWith('plugin-1', 'old-submission');+ expect(screen.getByText(`${prefix}.review.published`)).toBeTruthy();+ const version = screen.getByRole('region', { name: `${prefix}.versionContent` });+ expect(+ within(version).getByText(new Date(historic.submittedAt!).toLocaleString('en')),+ ).toBeTruthy();+ expect(+ within(version).getByText(new Date(historic.approvedAt!).toLocaleString('en')),+ ).toBeTruthy();+ expect(within(version).queryByText('New version changes')).toBeNull();+ expect(screen.getByText(`${prefix}.history`).closest('details')!.open).toBe(true);+ });++ it('refreshes the selected decision without letting cached package content restore an old result', async () => {+ const api = reader();+ const pending = {+ ...detail.plugin.latestSubmission!,+ content: null,+ reviewStatus: 'pending' as const,+ reviewedAt: null,+ reason: null,+ };+ vi.mocked(api.detail).mockResolvedValue({+ ...detail,+ plugin: { ...detail.plugin, latestSubmission: pending },+ });+ vi.mocked(api.releases).mockResolvedValue({+ releases: [pending],+ nextCursor: null,+ queriedAt: at,+ });+ vi.mocked(api.submission).mockResolvedValue({+ ...pending,+ content: detail.plugin.latestSubmission!.content,+ });+ view(api);+ await waitForManagement();+ await screen.findByText('New version changes');+ const approved = {+ ...pending,+ reviewStatus: 'approved' as const,+ approvedAt: at,+ reviewedAt: '2026-10-16T09:00:00.000Z',+ };+ const newAt = '2026-10-16T10:00:00.000Z';+ vi.mocked(api.detail).mockResolvedValue({+ ...detail,+ queriedAt: newAt,+ plugin: { ...detail.plugin, latestSubmission: approved },+ });+ vi.mocked(api.releases).mockResolvedValue({+ releases: [approved],+ nextCursor: null,+ queriedAt: newAt,+ });+ fireEvent.click(screen.getByRole('button', { name: `${prefix}.refreshDetail` }));+ expect(await screen.findByText(`${prefix}.review.approved`)).toBeTruthy();+ expect(screen.queryByText(`${prefix}.review.pending`)).toBeNull();+ expect(screen.getByText('New version changes')).toBeTruthy();+ expect(api.releases).toHaveBeenLastCalledWith('plugin-1', undefined);+ });++ it('paginates versions and keeps duplicate revisions out of the selector', async () => {+ const api = reader();+ vi.mocked(api.releases).mockResolvedValue({+ releases: [detail.plugin.latestSubmission!],+ nextCursor: 'older',+ queriedAt: at,+ });+ view(api);+ await waitForManagement();+ await openHistory();+ const more = await screen.findByRole('button', { name: `${prefix}.loadMoreVersions` });+ vi.mocked(api.releases).mockResolvedValue({+ releases: [+ detail.plugin.latestSubmission!,+ {+ ...detail.plugin.latestSubmission!,+ releaseId: 'old-release',+ version: '1.0.0',+ submissionId: 'older',+ },+ ],+ nextCursor: null,+ queriedAt: at,+ });+ fireEvent.click(more);+ await openHistory();+ const selector = await screen.findByRole('combobox', { name: `${prefix}.chooseVersion` });+ expect(api.releases).toHaveBeenCalledWith('plugin-1', 'older');+ fireEvent.keyDown(selector, { key: 'ArrowDown' });+ expect(await screen.findAllByRole('option')).toHaveLength(2);+ });++ it('drops a late version page after the owner generation changes', async () => {+ const api = reader();+ let finish!: (value: Awaited<ReturnType<PluginContributionsApi['releases']>>) => void;+ vi.mocked(api.releases).mockReturnValue(+ new Promise((resolve) => {+ finish = resolve;+ }),+ );+ const cache: MyPluginsPageCache = {};+ const tree = () => (+ <MemoryRouter initialEntries={['/plugins?myPlugins=1&contribution=plugin-1']}>+ <MyPluginsPage+ reader={api}+ cache={cache}+ localPlugins={[]}+ installedPluginCount={0}+ onSubmitUpdate={vi.fn()}+ onViewLocal={vi.fn()}+ />+ </MemoryRouter>+ );+ const mounted = render(tree());+ await screen.findByText('New version changes');+ auth.owner = 'B';+ auth.generation++;+ vi.mocked(api.releases).mockResolvedValue({ releases: [], nextCursor: null, queriedAt: at });+ mounted.rerender(tree());+ await waitFor(() => expect(api.releases).toHaveBeenCalledTimes(2));+ await act(async () =>+ finish({+ releases: [{ ...detail.plugin.latestSubmission!, version: 'SECRET-OLD-OWNER' }],+ nextCursor: null,+ queriedAt: at,+ }),+ );+ expect(screen.queryByText('SECRET-OLD-OWNER')).toBeNull();+ expect(screen.queryByRole('combobox')).toBeNull();+ });+ it.each(['approved', 'rejected'] as const)(+ 'shows the actual %s decision instead of a historical submitted outcome',+ async (reviewStatus) => {+ const revision = { releaseId: 'new-release', sha256: 'a'.repeat(64), displayUpdatedAt: at };+ const transfer: ContributionTransferView = {+ localId: 'finished',+ stage: 'complete',+ errorCode: null,+ prepared: {+ preparedId: 'finished',+ instanceId: 'exact-instance',+ pluginId: 'plugin-1',+ ghostId: 'hello',+ name: 'Finished upload',+ description: '',+ version: '2.0.0',+ sha256: revision.sha256,+ sizeBytes: 100,+ expiresAt: at,+ },+ operation: {+ subject: { authority: 'https://issuer.test', membershipId: 'member-A' },+ operationId: 'operation-1',+ status: 'succeeded',+ createdAt: at,+ updatedAt: at,+ expiresAt: at,+ failure: null,+ receipt: {+ submissionId: 'submission-1',+ operationId: 'operation-1',+ pluginId: 'plugin-1',+ releaseId: revision.releaseId,+ ghostId: 'hello',+ version: '2.0.0',+ source: 'manual',+ submittedAt: at,+ uploadedPackage: { sha256: revision.sha256, sizeBytes: 100 },+ releaseRevision: revision,+ outcome: 'submitted_for_review',+ },+ submission: {+ submissionId: 'submission-1',+ releaseId: revision.releaseId,+ version: '2.0.0',+ submittedAt: at,+ publishSource: 'community_upload',+ source: 'manual',+ revision,+ revisionState: 'current',+ reviewStatus,+ decidedAt: at,+ reason: null,+ },+ },+ };+ const api = reader([transfer]);+ vi.mocked(api.list).mockResolvedValue({+ plugins: [+ {+ ...detail.plugin,+ latestSubmission: { ...detail.plugin.latestSubmission!, reviewStatus },+ },+ ],+ nextCursor: null,+ queriedAt: at,+ });+ view(api, false);+ expect(await screen.findByText(`2.0.0 · ${prefix}.review.${reviewStatus}`)).toBeTruthy();+ expect(screen.queryByText('Finished upload')).toBeNull();+ expect(screen.queryByText(`${prefix}.outcome.submitted_for_review`)).toBeNull();+ expect(screen.queryByText(`${prefix}.review.published`)).toBeNull();+ },+ );+ it.each(['loaded', 'pending'] as const)(+ 'clears %s submission snapshots and their loading state across owners',+ async (state) => {+ const api = reader();+ const ownDetail = structuredClone(detail);+ ownDetail.history = [{ ...ownDetail.history[0], submissionId: 'same-submission-id' }];+ vi.mocked(api.detail).mockResolvedValue(ownDetail);+ const snapshot = (name: string) => ({+ ...ownDetail.plugin.latestSubmission!,+ content: { name, description: '', iconUrl: null, permissions: [], manifestView: {} },+ });+ let finishOld!: (value: ReturnType<typeof snapshot>) => void;+ const old = new Promise<ReturnType<typeof snapshot>>((resolve) => {+ finishOld = resolve;+ });+ vi.mocked(api.submission).mockReturnValueOnce(old);+ const cache: MyPluginsPageCache = {};+ const tree = () => (+ <MemoryRouter initialEntries={['/plugins?myPlugins=1&contribution=plugin-1']}>+ <MyPluginsPage+ localPlugins={[]}+ installedPluginCount={0}+ reader={api}+ cache={cache}+ onSubmitUpdate={vi.fn()}++ onViewLocal={vi.fn()}+ />+ </MemoryRouter>+ );+ const rendered = render(tree());+ await waitForManagement();+ fireEvent.click(await screen.findByText(`${prefix}.history`));+ const contentButton = await screen.findByRole('button', {+ name: `${prefix}.submittedContent`,+ });+ await act(async () => {+ contentButton.click();+ });+ if (state === 'loaded') {+ await act(async () => {+ finishOld(snapshot('OldOwnerSnapshot'));+ });+ await screen.findByText('OldOwnerSnapshot');+ }+ auth.owner = 'B';+ auth.generation++;+ vi.mocked(api.detail).mockResolvedValue({+ ...ownDetail,+ plugin: {+ ...ownDetail.plugin,+ name: 'Current Owner Plugin',+ latestSubmission: {+ ...ownDetail.plugin.latestSubmission!,+ reason: 'Current owner reason',+ },+ },+ });+ vi.mocked(api.submission).mockResolvedValueOnce(snapshot('CurrentOwnerSnapshot'));+ rendered.rerender(tree());+ await screen.findByText('Current Owner Plugin');+ await waitForManagement();+ const currentHistory = screen.getByText(`${prefix}.history`).closest('details')!;+ if (!currentHistory.open) fireEvent.click(within(currentHistory).getByText(`${prefix}.history`));+ expect(screen.queryByText('OldOwnerSnapshot')).toBeNull();+ expect(JSON.stringify(cache)).not.toContain('Full reason, line one');+ const newContentButton = await screen.findByRole('button', {+ name: `${prefix}.submittedContent`,+ }) as HTMLButtonElement;+ expect(newContentButton.disabled).toBe(false);+ await act(async () => {+ newContentButton.click();+ });+ await screen.findByText('CurrentOwnerSnapshot');+ expect(api.submission).toHaveBeenCalledTimes(2);+ if (state === 'pending') {+ await act(async () => {+ finishOld(snapshot('OldOwnerSnapshot'));+ });+ expect(screen.queryByText('OldOwnerSnapshot')).toBeNull();+ }+ },+ );+});+++describe('cancelling a version review', () => {+ it.each(['cancelled', 'approved'] as const)('shows the actual %s outcome and sends the displayed revision only', async status => {+ const api = reader();+ const pending = { ...detail.plugin.latestSubmission!, reviewStatus: 'pending' as const, canCancelReview: true, };+ vi.mocked(api.detail).mockResolvedValue({ ...detail, plugin: { ...detail.plugin, latestSubmission: pending } });+ vi.mocked(api.releases).mockResolvedValue({ releases: [pending], nextCursor: null, queriedAt: at });+ vi.mocked(api.submission).mockResolvedValue(pending);+ vi.mocked(api.cancelReview).mockResolvedValue({ ...pending, reviewStatus: status, canCancelReview: false, cancelledAt: status === 'cancelled' ? at : null, approvedAt: status === 'approved' ? at : null });+ view(api);+ await waitForManagement();+ fireEvent.click(await screen.findByRole('button', { name: `${prefix}.cancelReview` }));+ await waitFor(() => expect(api.cancelReview).toHaveBeenCalledExactlyOnceWith('plugin-1', { releaseId: pending.releaseId, sha256: pending.sha256, revision: pending.revision }));+ expect(await screen.findByText(`${prefix}.${status === 'cancelled' ? 'cancelReviewCompleted' : 'cancelReviewAlreadyFinal'}`)).toBeTruthy();+ expect(confirmation.confirm).toHaveBeenCalledWith(expect.objectContaining({ description: `${prefix}.cancelReviewDescription ${pending.version}` }));+ });+});++describe('review result indicators in My Plugins', () => {+ const result = (): PluginReviewUpdate => ({ pluginId: 'plugin-1', key: 'exact-review', releaseId: 'new-release',+ version: '2.0.0', sha256: 'a'.repeat(64), revision: at, status: 'rejected', decidedAt: at, unread: true });+ it('shows an unread dot on the plugin row without acknowledging the list', async () => {+ reviews.updates = [result()];+ view(reader(), false);+ expect(await screen.findByRole('img', { name: `${prefix}.unreadReview` })).toBeTruthy();+ expect(reviews.markRead).not.toHaveBeenCalled();+ });+ it('acknowledges only the exact decision displayed in the version result', async () => {+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');+ reviews.updates = [result()];+ view(reader());+ await waitForManagement();+ expect(screen.getByLabelText(`${prefix}.versionFacts`).closest('details')).toBeNull();+ await waitFor(() => expect(reviews.markRead).toHaveBeenCalledWith('plugin-1', 'exact-review'));+ const count = reviews.markRead.mock.calls.length;+ await act(async () => {});+ expect(reviews.markRead.mock.calls.length).toBe(count);+ vi.restoreAllMocks();+ });+ it('does not clear an older unread decision when viewing a newer pending version; opens its exact paginated version', async () => {+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible');+ reviews.updates = [{ ...result(), releaseId: 'older', sha256: 'b'.repeat(64), version: '1.0.0', status: 'approved' }];+ const api = reader();+ const pending = { ...detail.plugin.latestSubmission!, reviewStatus: 'pending' as const, reviewedAt: null };+ const older = { ...detail.plugin.latestSubmission!, releaseId: 'older', sha256: 'b'.repeat(64), version: '1.0.0',+ reviewStatus: 'approved' as const, reason: null, submissionId: 'older-submission' };+ vi.mocked(api.detail).mockResolvedValue({ ...detail, plugin: { ...detail.plugin, latestSubmission: pending } });+ vi.mocked(api.releases).mockImplementation(async (_id, cursor) => cursor+ ? { releases: [older], nextCursor: null, queriedAt: at }+ : { releases: [pending], nextCursor: 'older-page', queriedAt: at });+ view(api);+ await waitForManagement();+ const link = await screen.findByRole('button', { name: `${prefix}.viewReviewResult 1.0.0` });+ expect(reviews.markRead).not.toHaveBeenCalled();+ await waitFor(() => expect((link as HTMLButtonElement).disabled).toBe(false));+ fireEvent.click(link);+ await waitFor(() => expect(reviews.markRead).toHaveBeenCalledWith('plugin-1', 'exact-review'));+ expect(api.releases).toHaveBeenCalledWith('plugin-1', 'older-page');+ const facts = screen.getByLabelText(`${prefix}.versionFacts`);+ expect(within(facts).getByText('1.2.0')).toBeTruthy();+ expect(within(facts).getByText('2.0.0')).toBeTruthy(); // Still the real pending version after opening old approval.+ expect(within(facts).getByText('1.0.0')).toBeTruthy();+ vi.restoreAllMocks();+ });+});+++describe('plugin-level anonymous attribution', () => {+ it('keeps original-author anonymity editable after the submission grant is revoked', async () => {+ const api = reader();+ vi.mocked(api.detail).mockResolvedValue({ ...detail, plugin: { ...detail.plugin,+ actions: { ...detail.plugin.actions, submitUpdate: false },+ authorSettings: { anonymous: true, canEdit: true } } });+ view(api);+ await waitForManagement();+ const toggle = await screen.findByRole('switch', { name: `${prefix}.anonymous` }) as HTMLButtonElement;+ await waitFor(() => expect(toggle.disabled).toBe(false));+ expect(screen.queryByRole('button', { name: `${prefix}.submitVersion 1.2.0` })).toBeNull();+ expect(api.setAnonymity).not.toHaveBeenCalled();+ });+ it('reflects the default anonymous setting and applies the server result after an author change', async () => {+ const api = reader();+ const anonymousDetail = { ...detail, plugin: { ...detail.plugin, displayAuthor: null,+ authorSettings: { anonymous: true, canEdit: true } } };+ const namedDetail = { ...anonymousDetail, plugin: { ...anonymousDetail.plugin, displayAuthor: 'Saved submission name',+ authorSettings: { anonymous: false, canEdit: true } } };+ vi.mocked(api.detail).mockResolvedValue(anonymousDetail);+ vi.mocked(api.setAnonymity).mockResolvedValue(namedDetail);+ view(api);+ await waitForManagement();+ const toggle = await screen.findByRole('switch', { name: `${prefix}.anonymous` });+ expect(toggle.getAttribute('data-state')).toBe('checked');+ expect(screen.getByRole('heading', { name: 'My Plugin', level: 1 }).parentElement?.contains(toggle)).toBe(true);+ fireEvent.click(toggle);+ await waitFor(() => expect(api.setAnonymity).toHaveBeenCalledExactlyOnceWith('plugin-1', false));+ await screen.findByText('Saved submission name');+ expect(screen.getByRole('switch', { name: `${prefix}.anonymous` }).getAttribute('data-state')).toBe('unchecked');+ });+ it('preserves historical content and disclosure while refreshing anonymity', async () => {+ const api = reader();+ const named = { ...detail, plugin: { ...detail.plugin, displayAuthor: 'Saved author',+ authorSettings: { anonymous: false, canEdit: true } } };+ const hidden = { ...named, plugin: { ...named.plugin, displayAuthor: null,+ authorSettings: { anonymous: true, canEdit: true } } };+ const historic: ContributionReleaseView = { ...detail.plugin.latestSubmission!,+ releaseId: 'old-release', submissionId: 'old-submission', version: '1.0.0',+ content: { ...detail.plugin.latestSubmission!.content!, manifestView: { author: 'Historical author', releaseNotes: 'Historical notes' } } };+ vi.mocked(api.detail).mockResolvedValue(named);+ vi.mocked(api.releases).mockResolvedValue({ releases: [historic], nextCursor: null, queriedAt: at });+ vi.mocked(api.setAnonymity).mockResolvedValue(hidden);+ view(api);+ await waitForManagement();+ await openHistory();+ const selector = await screen.findByRole('combobox', { name: `${prefix}.chooseVersion` });+ fireEvent.keyDown(selector, { key: 'ArrowDown' });+ fireEvent.click(await screen.findByRole('option', { name: /1.0.0/ }));+ const notes = await screen.findByText('Historical notes');+ const content = screen.getByText(`${prefix}.versionContent`, { selector: 'summary' }).closest('details')!;+ content.open = true;+ // Keep the refresh pending: already displayed content must not become a spinner.+ vi.mocked(api.releases).mockImplementation(() => new Promise(() => {}));+ vi.mocked(api.submission).mockImplementation(() => new Promise(() => {}));+ fireEvent.click(screen.getByRole('switch', { name: `${prefix}.anonymous` }));+ await waitFor(() => expect(screen.getByRole('switch', { name: `${prefix}.anonymous` }).getAttribute('aria-checked')).toBe('true'));+ expect(screen.getByText('Historical notes')).toBe(notes);+ expect(selector.textContent).toBe('1.0.0');+ expect(content.isConnected).toBe(true);+ expect(content.open).toBe(true);+ expect(content.textContent).not.toContain('Historical author');+ });+ it('shows the author preference read-only to a submit-only maintainer', async () => {+ const api = reader();+ vi.mocked(api.detail).mockResolvedValue({ ...detail, plugin: { ...detail.plugin,+ authorSettings: { anonymous: true, canEdit: false } } });+ view(api);+ await waitForManagement();+ await screen.findByText('My Plugin', { selector: 'h1' });+ const toggle = screen.getByRole('switch', { name: `${prefix}.anonymous` }) as HTMLButtonElement;+ expect(toggle.disabled).toBe(true);+ expect(toggle.getAttribute('aria-checked')).toBe('true');+ fireEvent.click(toggle);+ expect(api.setAnonymity).not.toHaveBeenCalled();+ expect(screen.getByText(`${prefix}.anonymousAuthorOnly`)).toBeTruthy();+ });+});++// Value: Main's installation projection distinguishes missing from unreadable,+// while published content must match the actual market release. Minimal inputs+// are an absent projection or mismatched release. Shared counters use the existing+// cumulative totals and hide missing metrics and unlisted plugins. Tier: unit; real component entry.+describe('installation state and published content', () => {+ const publicDetail = (releaseId = 'old-release'): PluginMarketDetail => ({+ pluginId: 'plugin-1', ghostId: 'plugin', name: 'Public name', description: 'Published purpose',+ author: null, scope: 'public', organizationId: null, defaultInstall: false,+ releaseId, version: '1.0.0', publishedAt: at, icon: null, installState: 'not-installed',+ enabled: null, sourceType: 'server', sourceMarketName: null,+ downloadStatistics: { requestCount: '2000', last7DaysRequestCount: '35' },+ usageStatistics: { usageCount: '9000', usageCountLast7Days: '27', asOf: at },+ manifest: { schemaVersion: 2, id: 'plugin', name: 'Public name', version: '1.0.0', kind: 'chip',+ entry: 'main.js', description: 'Published purpose', releaseNotes: 'Published changes' },+ });+ it.each(['missing', 'unavailable', undefined] as const)(+ 'offers only the action justified by the %s local state', async state => {+ const api = reader(), install = vi.fn();+ vi.mocked(api.detail).mockResolvedValue({ ...detail, plugin: { ...detail.plugin,+ localInstanceId: null, localVersion: null, localInstallation: state ? { state } : undefined } });+ render(<MemoryRouter initialEntries={['/plugins?myPlugins=1&contribution=plugin-1']}>+ <MyPluginsPage reader={api} localPlugins={[]} installedPluginCount={0} cache={{}} onSubmitUpdate={vi.fn()} onViewLocal={vi.fn()} onInstallPublished={install} />+ </MemoryRouter>);+ await waitForManagement();+ await waitFor(() => expect(within(screen.getByLabelText(`${prefix}.versionFacts`)).getByText(`${prefix}.localState.${state ?? 'unavailable'}`)).toBeTruthy());+ expect(Boolean(screen.queryByRole('button', { name: `${prefix}.installPublished` }))).toBe(state === 'missing');+ expect(screen.queryByRole('button', { name: `${prefix}.submitVersion 1.2.0` })).toBeNull();+ expect(api.prepare).not.toHaveBeenCalled();+ expect(install).not.toHaveBeenCalled();+ },+ );+ it.each(['exact', 'different-release', 'failed'] as const)(+ 'keeps the published version fact while handling %s published content', async result => {+ const api = reader();+ const readPublished = result === 'failed' ? vi.fn().mockRejectedValue(new Error('Unavailable'))+ : vi.fn().mockResolvedValue(publicDetail(result === 'exact' ? 'old-release' : 'newer-release'));+ render(<MemoryRouter initialEntries={['/plugins?myPlugins=1&contribution=plugin-1']}>+ <MyPluginsPage reader={api} localPlugins={[]} installedPluginCount={0} cache={{}} onSubmitUpdate={vi.fn()} onViewLocal={vi.fn()} onReadPublished={readPublished} />+ </MemoryRouter>);+ await waitForManagement();+ const published = screen.getByRole('region', { name: `${prefix}.listedVersion` });+ if (result === 'exact') {+ expect(await within(published).findByText('Published purpose')).toBeTruthy();+ expect(within(published).getByText('Published changes')).toBeTruthy();+ expect(screen.getByRole('group', { name: 'settings.ghosts.usage.downloadsValue 2,000' })).toBeTruthy();+ expect(screen.getByRole('group', { name: 'settings.ghosts.usage.usesValue 9,000' })).toBeTruthy();+ } else {+ expect(await within(published).findByText(`${prefix}.publishedContentUnavailable`)).toBeTruthy();+ expect(within(published).queryByText('Published changes')).toBeNull();+ expect(screen.queryByRole('group', { name: /^settings\.ghosts\.usage\./ })).toBeNull();+ }+ expect(within(published).queryByText('New version changes')).toBeNull();+ expect(within(screen.getByLabelText(`${prefix}.versionFacts`)).getByText('1.0.0')).toBeTruthy();+ expect(within(screen.getByRole('region', { name: `${prefix}.currentSubmission` })).getByText('New version changes')).toBeTruthy();+ },+ );+ it.each(['missing', 'zero'] as const)('keeps the existing display for %s shared counters', async state => {+ const api = reader(), value = publicDetail();+ value.downloadStatistics = state === 'zero' ? { requestCount: '0' } : undefined;+ value.usageStatistics = state === 'zero' ? { usageCount: '0', asOf: at } : undefined;+ render(<MemoryRouter initialEntries={['/plugins?myPlugins=1&contribution=plugin-1']}>+ <MyPluginsPage reader={api} localPlugins={[]} installedPluginCount={0} cache={{}} onSubmitUpdate={vi.fn()} onViewLocal={vi.fn()} onReadPublished={vi.fn().mockResolvedValue(value)} />+ </MemoryRouter>);+ await screen.findByText('Published purpose');+ if (state === 'zero') {+ expect(screen.getByRole('group', { name: 'settings.ghosts.usage.downloadsValue 0' })).toBeTruthy();+ expect(screen.getByRole('group', { name: 'settings.ghosts.usage.usesValue 0' })).toBeTruthy();+ } else {+ expect(screen.queryByRole('group', { name: /^settings\.ghosts\.usage\./ })).toBeNull();+ }+ });+ it('does not read or display shared counters before the plugin is listed', async () => {+ const api = reader(), readPublished = vi.fn().mockResolvedValue(publicDetail());+ vi.mocked(api.detail).mockResolvedValue({ ...detail, plugin: { ...detail.plugin,+ market: { state: 'not_listed', version: null, releaseId: null, reason: null } } });+ render(<MemoryRouter initialEntries={['/plugins?myPlugins=1&contribution=plugin-1']}>+ <MyPluginsPage reader={api} localPlugins={[]} installedPluginCount={0} cache={{}} onSubmitUpdate={vi.fn()} onViewLocal={vi.fn()} onReadPublished={readPublished} />+ </MemoryRouter>);+ await waitForManagement();+ expect(readPublished).not.toHaveBeenCalled();+ expect(screen.queryByRole('group', { name: /^settings\.ghosts\.usage\./ })).toBeNull();+ });+ it('keeps the same published content mounted during a refresh of that exact release', async () => {+ const api = reader(), readPublished = vi.fn().mockResolvedValue(publicDetail());+ render(<MemoryRouter initialEntries={['/plugins?myPlugins=1&contribution=plugin-1']}>+ <MyPluginsPage reader={api} localPlugins={[]} installedPluginCount={0} cache={{}} onSubmitUpdate={vi.fn()} onViewLocal={vi.fn()} onReadPublished={readPublished} />+ </MemoryRouter>);+ const notes = await screen.findByText('Published changes');+ const calls = readPublished.mock.calls.length;+ readPublished.mockImplementation(() => new Promise(() => {}));+ vi.mocked(api.detail).mockResolvedValue({ ...detail, queriedAt: '2026-10-16T00:00:00Z' });+ fireEvent.click(screen.getByRole('button', { name: `${prefix}.refreshDetail` }));+ await waitFor(() => expect(readPublished.mock.calls.length).toBeGreaterThan(calls));+ expect(screen.getByText('Published changes')).toBe(notes);+ expect(notes.isConnected).toBe(true);+ expect(within(screen.getByRole('region', { name: `${prefix}.listedVersion` })).queryByText(`${prefix}.loading`)).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/PluginAnonymityControl.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/PluginAnonymityControl.test.tsxnew file mode 100644index 0000000000..388d5baccd--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/__tests__/PluginAnonymityControl.test.tsx@@ -0,0 +1,118 @@+/** @vitest-environment jsdom */+import { StrictMode } from 'react';+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { MyPluginDetailView } from '../../../../shared/pluginContributions';+import { PluginAnonymityControl } from '../PluginAnonymityControl';++vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+afterEach(cleanup);+const copy = 'settings.ghosts.contribution';+function response(anonymous: boolean): MyPluginDetailView {+ return {+ plugin: { pluginId: 'plugin', name: 'Plugin', authorSettings: { anonymous, canEdit: true },+ iconUrl: null, updatedAt: '2026-10-19T00:00:00Z',+ market: { state: 'not_listed', version: null, releaseId: null, reason: null },+ latestSubmission: null, actions: { submitUpdate: false, viewMarket: false }, localInstanceId: null },+ history: [], nextCursor: null, queriedAt: '2026-10-19T00:00:00Z',+ };+}+function deferred() {+ let resolve!: (result: MyPluginDetailView) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<MyPluginDetailView>((yes, no) => { resolve = yes; reject = no; });+ return { promise, resolve, reject };+}+function setup() {+ const pending = deferred();+ const reader = { setAnonymity: vi.fn(() => pending.promise) };+ const onUpdated = vi.fn(), onCommitted = vi.fn();+ const props = { ownerKey: 'owner:1', pluginId: 'plugin', settings: { anonymous: true, canEdit: true },+ reader, onUpdated, onCommitted };+ return { pending, props, reader, onUpdated, onCommitted };+}++describe('plugin-level anonymity control', () => {+ it('does not infer editing rights from a plugin being visible', () => {+ const { props, reader } = setup();+ render(<PluginAnonymityControl {...props} settings={{ anonymous: false, canEdit: false }} />);+ const control = screen.getByRole('switch') as HTMLButtonElement;+ expect(control.disabled).toBe(true);+ expect(control.getAttribute('aria-checked')).toBe('false');+ fireEvent.click(control);+ expect(reader.setAnonymity).not.toHaveBeenCalled();+ expect(screen.getByText(`${copy}.anonymousAuthorOnly`)).toBeTruthy();+ });++ it('keeps the confirmed value until the server replies, including StrictMode replay', async () => {+ const { props, reader, pending, onUpdated, onCommitted } = setup();+ render(<StrictMode><PluginAnonymityControl {...props} /></StrictMode>);+ const control = screen.getByRole('switch') as HTMLButtonElement;+ fireEvent.click(control);+ fireEvent.click(control);+ expect(reader.setAnonymity).toHaveBeenCalledExactlyOnceWith('plugin', false);+ expect(control.disabled).toBe(true);+ expect(control.getAttribute('aria-checked')).toBe('true');+ const result = response(false);+ await act(async () => pending.resolve(result));+ expect(onUpdated).toHaveBeenCalledExactlyOnceWith(result);+ expect(onCommitted).toHaveBeenCalledExactlyOnceWith(result, true);+ expect(control.disabled).toBe(false);+ });++ it('invalidates parent caches after a committed write even if navigation removed the control', async () => {+ const { props, pending, onUpdated, onCommitted } = setup();+ const view = render(<PluginAnonymityControl {...props} />);+ fireEvent.click(screen.getByRole('switch'));+ view.unmount();+ const result = response(false);+ await act(async () => pending.resolve(result));+ expect(onCommitted).toHaveBeenCalledExactlyOnceWith(result, false);+ expect(onUpdated).not.toHaveBeenCalled();+ });++ it('does not apply a late write to a different owner or plugin', async () => {+ const { props, pending, onUpdated } = setup();+ const view = render(<PluginAnonymityControl {...props} />);+ fireEvent.click(screen.getByRole('switch'));+ view.rerender(<PluginAnonymityControl {...props} ownerKey="owner:2" pluginId="another-plugin" />);+ await act(async () => pending.resolve(response(false)));+ expect(onUpdated).not.toHaveBeenCalled();+ expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('true');+ });++ it('discards the old completion after an owner leaves and returns with a new generation', async () => {+ const { props, pending, onUpdated, onCommitted } = setup();+ const view = render(<PluginAnonymityControl {...props} />);+ fireEvent.click(screen.getByRole('switch'));+ view.rerender(<PluginAnonymityControl {...props} ownerKey="other-owner:1" />);+ view.rerender(<PluginAnonymityControl {...props} ownerKey="owner:2" />);+ await act(async () => pending.resolve(response(false)));+ expect(onUpdated).not.toHaveBeenCalled();+ // The parent rechecks its owner generation before invalidating any cache.+ expect(onCommitted).toHaveBeenCalledOnce();+ expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('true');+ });++ it('preserves the confirmed state and exposes failure rather than pretending the write succeeded', async () => {+ const { props, pending, onUpdated, onCommitted } = setup();+ render(<PluginAnonymityControl {...props} />);+ fireEvent.click(screen.getByRole('switch'));+ await act(async () => pending.reject(new Error('network unavailable')));+ expect(screen.getByRole('alert').textContent).toBe(`${copy}.anonymousUpdateFailed`);+ expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('true');+ expect(onUpdated).not.toHaveBeenCalled();+ expect(onCommitted).not.toHaveBeenCalled();+ });++ it('does not fabricate an enabled default for missing authorship or loading settings', () => {+ const { props, reader } = setup();+ const view = render(<PluginAnonymityControl {...props} settings={null} unavailable />);+ expect(screen.queryByRole('switch')).toBeNull();+ expect(screen.getByRole('status').textContent).toBe(`${copy}.anonymousUnavailable`);+ view.rerender(<PluginAnonymityControl {...props} settings={undefined} loading />);+ expect(screen.queryByRole('switch')).toBeNull();+ expect(screen.getByRole('status').textContent).toBe(`${copy}.loading`);+ expect(reader.setAnonymity).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/features/plugin/lib/__tests__/contributionIntent.test.ts b/apps/desktop/src/renderer/features/plugin/lib/__tests__/contributionIntent.test.tsnew file mode 100644index 0000000000..b82bd36bae--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/contributionIntent.test.ts@@ -0,0 +1,45 @@+/** @vitest-environment jsdom */+import { describe, expect, it } from 'vitest';+import type { InstalledGhost } from '../../../../../shared/ghost';+import {+ consumeContributionIntent,+ matchesContributionIntent,+ rememberContributionIntent,+} from '../contributionIntent';++const ghost: InstalledGhost = {+ manifest: {+ schemaVersion: 2,+ id: 'hello',+ name: 'Hello',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ },+ dir: '/test-only/owner-A/hello',+ namespace: null,+ publishingSource: { kind: 'local', source: 'manual' },+ namespaceState: 'confirmed',+ enabled: true,+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },+};+describe('public contribution login intent', () => {+ it('does not substitute another account installation or a new approval for the same logical ID', () => {+ const nonce = rememberContributionIntent(ghost);+ const target = consumeContributionIntent(nonce)!;+ expect(matchesContributionIntent(target, ghost)).toBe(true);+ expect(matchesContributionIntent(target, { ...ghost, dir: '/test-only/owner-B/hello' })).toBe(+ false,+ );+ expect(+ matchesContributionIntent(target, {+ ...ghost,+ approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000002' },+ }),+ ).toBe(false);+ expect(matchesContributionIntent(target, { ...ghost, namespace: 'org' })).toBe(false);+ expect(matchesContributionIntent(target, { ...ghost, publishingSource: { kind: 'public-market', pluginId: 'other' } })).toBe(false);+ expect(matchesContributionIntent(target, { ...ghost, publishingSource: undefined })).toBe(false);+ expect(consumeContributionIntent(nonce)).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/features/plugin/lib/__tests__/ghostPluginDetailModel.test.ts b/apps/desktop/src/renderer/features/plugin/lib/__tests__/ghostPluginDetailModel.test.tsnew file mode 100644index 0000000000..cd600f1a34--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/ghostPluginDetailModel.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest';+import path from 'node:path';+import os from 'node:os';+import type { InstalledGhost } from '../../../../../shared/ghost';+import type { PluginMarketItem } from '../../../../../shared/pluginMarket';+import { localPublishingUnavailableKey } from '../ghostPluginDetailModel';++const installed: InstalledGhost = {+ manifest: { schemaVersion: 2, id: 'author-plugin', name: 'Author Plugin', version: '1.0.0', kind: 'chip', entry: 'main.js' },+ dir: path.join(os.tmpdir(), 'author-plugin'),+ namespace: null,+ publishingSource: { kind: 'local', source: 'manual' },+ namespaceState: 'confirmed',+ enabled: true,+ approval: { state: 'approved', revision: 'approved-content' },+};++describe('local publishing availability shared by details and selection', () => {+ it('explains the GitHub requirement for verified official public plugins even with submission permission', () => {+ const market = { scope: 'public' as const, organizationId: null, sourceType: 'server' as const, publisherKind: 'official' as const };+ expect(localPublishingUnavailableKey(installed, market, true)).toBe('officialGithubRequired');+ const trusted: InstalledGhost = { ...installed, publishingSource: { kind: 'public-market', pluginId: 'official-id' },+ trust: { level: 'cindy-official', publisherSigned: true, publisherVerified: true, reviewed: true } };+ expect(localPublishingUnavailableKey(trusted, null, true)).toBe('officialGithubRequired');+ expect(localPublishingUnavailableKey(installed, { ...market, sourceType: 'local-market' }, true)).toBeNull();+ expect(localPublishingUnavailableKey({ ...installed, manifest: { ...installed.manifest, author: 'Cindy' } }, { ...market, publisherKind: 'personal' }, true)).toBeNull();+ });+ it('separates approved use from current exact publishing permission', () => {+ expect(localPublishingUnavailableKey({ ...installed, publishingSource: undefined })).toBe('sourceUnverified');+ const downloaded: InstalledGhost = { ...installed, publishingSource: { kind: 'public-market', pluginId: 'public-id' } };+ expect(localPublishingUnavailableKey(downloaded)).toBe('publishingPermissionRequired');+ expect(localPublishingUnavailableKey(downloaded, null, true)).toBeNull();+ expect(localPublishingUnavailableKey({ ...downloaded, publishingSource: { kind: 'unavailable' } }, null, true)).toBe('sourceUnverified');+ });+ it.each([+ { ghost: null, reason: 'installationUnavailable' },+ { ghost: { ...installed, manifest: { ...installed.manifest, id: 'cindy-art' } }, reason: 'reservedId' },+ { ghost: { ...installed, builtin: true }, reason: 'reservedId' },+ { ghost: { ...installed, namespace: 'org' }, reason: 'privatePlugin' },+ { ghost: { ...installed, namespace: undefined }, reason: 'privatePlugin' },+ { ghost: { ...installed, namespaceState: undefined }, reason: 'identityPending' },+ { ghost: { ...installed, namespaceState: 'pending' as const }, reason: 'identityPending' },+ { ghost: { ...installed, namespaceState: 'unconfirmed' as const }, reason: 'identityPending' },+ { ghost: { ...installed, approval: { state: 'legacy-unapproved' as const } }, reason: 'approvalRequired' },+ { ghost: { ...installed, approval: { state: 'invalid' as const } }, reason: 'approvalRequired' },+ ])('excludes a locally unavailable installation ($reason)', ({ ghost, reason }) => {+ expect(localPublishingUnavailableKey(ghost)).toBe(reason);+ });++ it.each([+ { scope: 'personal', organizationId: null },+ { scope: 'organization', organizationId: 'org' },+ { scope: 'public', organizationId: 'org' },+ ] satisfies Pick<PluginMarketItem, 'scope' | 'organizationId'>[])(+ 'excludes a private market association even for an approved root ($scope)', (market) => {+ expect(localPublishingUnavailableKey(installed, market)).toBe('privatePlugin');+ },+ );++ it('keeps ordinary approved roots available without inferring author rights or requiring enabled state', () => {+ expect(localPublishingUnavailableKey(installed)).toBeNull();+ expect(localPublishingUnavailableKey({ ...installed, enabled: false }, { scope: 'public', organizationId: null })).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/features/plugin/lib/__tests__/ghostPluginViewModel.author.test.ts b/apps/desktop/src/renderer/features/plugin/lib/__tests__/ghostPluginViewModel.author.test.tsnew file mode 100644index 0000000000..d70cbe1c8e--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/lib/__tests__/ghostPluginViewModel.author.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from 'vitest';+import path from 'node:path';+import os from 'node:os';+import type { InstalledGhost } from '../../../../../shared/ghost';+import { marketPresentationForInstalledGhost, toGhostPluginDetail } from '../ghostPluginViewModel';+import type { PluginMarketItem } from '../../../../../shared/pluginMarket';++const installed: InstalledGhost = {+ manifest: { schemaVersion: 3, id: 'example', name: 'Example', version: '1.0.0', kind: 'chip', entry: 'main.js', author: 'Package claim' },+ dir: path.join(os.tmpdir(), 'example'), namespace: null, namespaceState: 'confirmed', enabled: true,+ approval: { state: 'approved', revision: 'approved-content' },+};++describe('workflow-owned author presentation', () => {+ it('uses the verified public classification without inferring official status from a name', () => {+ const market = { ghostId: installed.manifest.id, namespace: null, scope: 'public',+ installState: 'installed', sourceType: 'server', version: '1.0.0', name: 'Example',+ description: '', author: 'Cindy', publisherKind: 'personal', icon: null } as PluginMarketItem;+ expect(toGhostPluginDetail(installed, marketPresentationForInstalledGhost(installed, market)).publisherKind).toBe('personal');+ expect(marketPresentationForInstalledGhost(installed, { ...market, sourceType: 'git-market' })?.publisherKind).toBeUndefined();+ expect(toGhostPluginDetail({ ...installed, namespace: 'example-org' }).publisherKind).toBeUndefined();+ });+ it('retains organization package attribution without a current market presentation', () => {+ const organization = { ...installed, namespace: 'example-org' };+ expect(toGhostPluginDetail(organization).author).toBe('Package claim');+ expect(toGhostPluginDetail({ ...organization, manifest: { ...installed.manifest, author: undefined } }).author).toBeNull();+ });+ it('does not display a local package author when verified market attribution is absent', () => {+ expect(toGhostPluginDetail(installed).author).toBeNull();+ });+ it('uses the market attribution and does not fall back when it is explicitly missing', () => {+ const presentation = { name: 'Example', description: '', iconDataUrl: undefined, author: 'Verified account' };+ expect(toGhostPluginDetail(installed, presentation).author).toBe('Verified account');+ expect(toGhostPluginDetail(installed, { ...presentation, author: null }).author).toBeNull();+ expect(installed.manifest.author).toBe('Package claim');+ });+ it('uses Main-verified attribution for an older version while retaining its local content', () => {+ const newer = { ghostId: installed.manifest.id, namespace: null, installState: 'update-available',+ sourceType: 'server', version: '2.0.0', name: 'New version name', description: 'New version description',+ author: 'Current name', installedAuthor: 'Current name', icon: null } as PluginMarketItem;+ expect(marketPresentationForInstalledGhost(installed, newer)).toMatchObject({+ name: installed.manifest.name, description: '', author: 'Current name',+ });+ const unverified = { ...newer, installedAuthor: undefined };+ expect(marketPresentationForInstalledGhost(installed, unverified)).toBeNull();+ expect(marketPresentationForInstalledGhost(installed, { ...newer, installState: 'conflict' })).toBeNull();+ expect(marketPresentationForInstalledGhost(installed, { ...newer, sourceType: 'git-market' })).toBeNull();+ expect(marketPresentationForInstalledGhost(installed, { ...newer, ghostId: 'other-plugin' })).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/features/plugin/lib/contributionIntent.ts b/apps/desktop/src/renderer/features/plugin/lib/contributionIntent.tsnew file mode 100644index 0000000000..85a07b6cd1--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/lib/contributionIntent.ts@@ -0,0 +1,48 @@+import { ghostInstallApprovalToken, type InstalledGhost } from '../../../../shared/ghost';+import { installedGhostStoragePart } from '../../../../shared/pluginIdentity';++/** Navigation intent only: no package, credential or grant crosses an owner boundary. */+interface ExactTarget {+ instanceId: string;+ directory: string;+ approvalToken: string;+ ghostId: string;+ version: string;+ sourceKey: string;+}+let pending: { nonce: string; target: ExactTarget; at: number } | null = null;+export function rememberContributionIntent(ghost: InstalledGhost): string {+ pending = {+ nonce: crypto.randomUUID(),+ at: Date.now(),+ target: {+ instanceId: installedGhostStoragePart(ghost),+ directory: ghost.dir,+ approvalToken: ghostInstallApprovalToken(ghost.approval),+ ghostId: ghost.manifest.id,+ version: ghost.manifest.version,+ sourceKey: JSON.stringify(ghost.publishingSource),+ },+ };+ return pending.nonce;+}+export function consumeContributionIntent(nonce: string): ExactTarget | null {+ if (!pending || pending.nonce !== nonce) return null;+ const value = pending;+ pending = null;+ return Date.now() - value.at <= 15 * 60_000 ? value.target : null;+}+export function matchesContributionIntent(target: ExactTarget, ghost: InstalledGhost): boolean {+ return (+ installedGhostStoragePart(ghost) === target.instanceId &&+ ghost.dir === target.directory &&+ ghostInstallApprovalToken(ghost.approval) === target.approvalToken &&+ ghost.approval.state === 'approved' &&+ ghost.manifest.id === target.ghostId &&+ ghost.manifest.version === target.version &&+ ghost.namespace === null &&+ ghost.namespaceState === 'confirmed'+ && ghost.publishingSource?.kind === 'local'+ && JSON.stringify(ghost.publishingSource) === target.sourceKey+ );+}diff --git a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginDetailModel.ts b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginDetailModel.tsindex 6885da7950..426a72a4d5 100644--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginDetailModel.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginDetailModel.ts@@ -1,9 +1,31 @@/**- * Pure description helpers for the Plugin detail page.+ * Pure description and local publishing helpers shared by Plugin details and selection.** Permission presentation intentionally consumes the shared Ghost permission items directly.* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md*/+import { isUserInstallReservedGhostId, type InstalledGhost } from '../../../../shared/ghost';+import type { PluginMarketItem } from '../../../../shared/pluginMarket';++/** Host provenance is not authorship. Market updates additionally need current exact submit ACL. */+export function localPublishingUnavailableKey(+ ghost: InstalledGhost | null | undefined,+ market?: (Pick<PluginMarketItem, 'scope' | 'organizationId'> & Partial<Pick<PluginMarketItem, 'sourceType' | 'publisherKind'>>) | null,+ canSubmitMarket = false,+) {+ if (!ghost) return 'installationUnavailable';+ if (ghost.namespace === null && (+ (ghost.publishingSource?.kind === 'public-market' && ghost.trust?.level === 'cindy-official') ||+ (market?.scope === 'public' && market.sourceType === 'server' && market.publisherKind === 'official')+ )) return 'officialGithubRequired';+ if (isUserInstallReservedGhostId(ghost.manifest.id) || ghost.builtin) return 'reservedId';+ if (ghost.namespaceState !== 'confirmed') return 'identityPending';+ if (ghost.namespace !== null || (market && (market.scope !== 'public' || market.organizationId !== null))) return 'privatePlugin';+ if (ghost.approval.state !== 'approved') return 'approvalRequired';+ if (!ghost.publishingSource || ghost.publishingSource.kind === 'unavailable') return 'sourceUnverified';+ if (ghost.publishingSource.kind === 'public-market' && !canSubmitMarket) return 'publishingPermissionRequired';+ return null;+}/** Returns the complete normalized description without model-generated copy. */export function ghostPluginSummary(description: string, fallback: string): string {diff --git a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.tsindex e266843eb8..397b04e6e3 100644--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts@@ -26,6 +26,7 @@ export interface GhostPluginListItem {ghostId: string;name: string;description: string;+ publisherKind?: PluginMarketItem['publisherKind'];version: string;enabled: boolean;canUse: boolean;@@ -67,6 +68,7 @@ export function ghostPrimaryAction(return 'manage';}export interface GhostPluginDetail extends GhostPluginListItem {+ releaseNotes?: string;trust: GhostTrustInfo;author: string | null;contents: readonly string[];@@ -95,13 +97,14 @@ export interface GhostPluginMarketPresentation {name: string;description: string;author: string | null;+ publisherKind?: PluginMarketItem['publisherKind'];iconDataUrl: string | undefined;}/*** Returns a market presentation only when the installed package is the exact- * market-owned version. A local install, a conflicting ghostId, an unavailable- * market item, or a pending version update must keep using its local manifest.+ * market-owned version. A verified older installation keeps its local content+ * and uses only the saved public attribution and privacy projection from Main.*/export function marketPresentationForInstalledGhost(ghost: Pick<InstalledGhost, 'manifest' | 'iconDataUrl'>,@@ -114,16 +117,27 @@ export function marketPresentationForInstalledGhost(| 'name'| 'description'| 'author'+ | 'installedAuthor'| 'icon'| 'sourceType'> &- Pick<PluginMarketItem, 'namespace'>)+ Pick<PluginMarketItem, 'namespace'> &+ Partial<Pick<PluginMarketItem, 'scope' | 'publisherKind'>>)| null| undefined,): GhostPluginMarketPresentation | null {if (!marketItem ||- !marketItemMatchesInstalledGhost(marketItem, ghost) ||+ !marketItemMatchesInstalledGhost(marketItem, ghost)+ ) return null;+ const publisherKind = marketItem.sourceType === 'server' && marketItem.scope === 'public'+ ? marketItem.publisherKind : undefined;+ if (marketItem.sourceType === 'server' && marketItem.installState === 'update-available'+ && marketItem.installedAuthor !== undefined) {+ return { name: ghost.manifest.name, description: ghost.manifest.description ?? '',+ iconDataUrl: ghost.iconDataUrl, author: marketItem.installedAuthor, publisherKind };+ }+ if (marketItem.installState !== 'installed' ||marketItem.version !== ghost.manifest.version) {@@ -133,6 +147,7 @@ export function marketPresentationForInstalledGhost(name: marketItem.name,description: marketItem.description ?? '',author: marketItem.author,+ publisherKind,iconDataUrl:marketItem.sourceType === 'git-market' && !marketItem.icon? ghost.iconDataUrl@@ -255,8 +270,8 @@ export function installedVisibleCount<T extends Pick<GhostPluginListItem, 'id' |/*** 将安装清单转换成列表卡片需要的最小字段。*- * 这里刻意不加入安装量、使用量、认证徽章等旧原型字段;这些字段在 Ghost- * runtime 中没有事实来源,页面不应继续展示伪数据。+ * 安装量、使用量等没有事实来源的旧原型字段不加入;发布身份仅消费+ * Host 核实后的 public 市场投影,不能从包内声明或昵称推断。*/export function toGhostPluginListItem(ghost: InstalledGhost,@@ -273,6 +288,7 @@ export function toGhostPluginListItem(ghostId: manifest.id,name: display.name,description: display.description,+ publisherKind: presentation?.publisherKind,version: manifest.version,enabled: ghost.enabled,canUse: Boolean(manifest.command),@@ -308,7 +324,9 @@ export function toGhostPluginDetail(return {...listItem,trust: listItem.trust!,- author: presentation ? presentation.author : (manifest.author ?? null),+ releaseNotes: manifest.releaseNotes,+ author: presentation ? presentation.author+ : typeof ghost.namespace === 'string' ? manifest.author ?? null : null,contents: ghostContentKeys(manifest),permissions: ghostPermissionItems(manifest),tools: manifest.tools ?? [],diff --git a/apps/desktop/src/renderer/features/plugin/lib/usePublishingInstallations.ts b/apps/desktop/src/renderer/features/plugin/lib/usePublishingInstallations.tsnew file mode 100644index 0000000000..77eaf0d806--- /dev/null+++ b/apps/desktop/src/renderer/features/plugin/lib/usePublishingInstallations.ts@@ -0,0 +1,50 @@+import { useEffect, useState } from 'react';+import type { InstalledGhost } from '../../../../shared/ghost';+import type { MyPluginView } from '../../../../shared/pluginContributions';+import { installedGhostStoragePart } from '../../../../shared/pluginIdentity';++/** Rebuildable exact install/ACL projection. Never derives ownership from package metadata. */+export function usePublishingInstallations(owner: string, personal: boolean, ghosts: InstalledGhost[]) {+ const installationKey = JSON.stringify(ghosts.map(ghost => [installedGhostStoragePart(ghost), ghost.dir,+ ghost.approval, ghost.publishingSource]));+ const key = JSON.stringify([owner, personal, installationKey]);+ const [result, setResult] = useState<{ key: string; plugins: MyPluginView[] } | null>(null);+ useEffect(() => {+ let disposed = false;+ let generation = 0;+ const refresh = async () => {+ const request = ++generation;+ setResult(null);+ if (!personal || !navigator.onLine || !ghosts.some(ghost => ghost.publishingSource?.kind === 'public-market')) return;+ try {+ const plugins: MyPluginView[] = [];+ let cursor: string | undefined;+ do {+ const page = await window.electronAPI.pluginContributions.list({ query: '', filter: 'all', cursor });+ if (disposed || request !== generation) return;+ plugins.push(...page.plugins);+ cursor = page.nextCursor ?? undefined;+ } while (cursor);+ setResult({ key, plugins });+ } catch {+ // Unknown current permission cannot preserve an old write candidate.+ }+ };+ const foreground = () => { if (document.visibilityState === 'visible') void refresh(); };+ const offline = () => { generation++; setResult(null); };+ void refresh();+ window.addEventListener('focus', foreground);+ window.addEventListener('online', foreground);+ window.addEventListener('offline', offline);+ document.addEventListener('visibilitychange', foreground);+ return () => {+ disposed = true;+ window.removeEventListener('focus', foreground);+ window.removeEventListener('online', foreground);+ window.removeEventListener('offline', offline);+ document.removeEventListener('visibilitychange', foreground);+ };+ // The serialized key binds every source, approval, directory and owner generation.+ }, [key]);+ return result?.key === key ? result.plugins : [];+}diff --git a/apps/desktop/src/renderer/features/plugin/plugin-motion.css b/apps/desktop/src/renderer/features/plugin/plugin-motion.cssindex ac06176322..84f90a55e6 100644--- a/apps/desktop/src/renderer/features/plugin/plugin-motion.css+++ b/apps/desktop/src/renderer/features/plugin/plugin-motion.css@@ -128,6 +128,28 @@}}+@container plugin-detail (min-width: 680px) {+ .plugin-detail-frame .plugin-detail-hero {+ grid-template-columns: 64px minmax(160px, 1fr) auto;+ }++ .plugin-detail-frame .plugin-detail-actions {+ /* Keep a readable title even when update/result actions wrap on the right. */+ max-width: calc(100cqi - 64px - 160px - 2.5rem);+ justify-content: flex-end;+ }+}++@container plugin-detail (width < 680px) {+ .plugin-detail-frame .plugin-detail-hero {+ grid-template-columns: 64px minmax(0, 1fr);+ }++ .plugin-detail-frame .plugin-detail-actions {+ grid-column: 1 / -1;+ }+}+@container plugin-management-content (max-width: 720px) {.plugin-installed-card-grid {grid-template-columns: minmax(0, 1fr);@@ -194,6 +216,51 @@}}+.my-plugins-columns,+.my-plugins-row {+ display: grid;+ grid-template-columns: minmax(0, 1fr) 6rem 6rem 9rem 5rem;+ align-items: center;+ gap: 1.25rem;+}++.my-plugins-mobile-label {+ display: none;+}++@container plugin-management-content (max-width: 600px) {+ .my-plugins-columns {+ display: none;+ }++ .my-plugins-row {+ grid-template-columns: minmax(0, 1fr) 5rem;+ gap: 0.5rem;+ }++ .my-plugins-identity {+ grid-column: 1;+ grid-row: 1;+ }++ .my-plugins-chevron {+ grid-column: 2;+ grid-row: 1;+ }++ .my-plugins-local,+ .my-plugins-market,+ .my-plugins-latest {+ grid-column: 1 / -1;+ margin-inline-start: 3.75rem;+ }++ .my-plugins-mobile-label {+ display: inline;+ color: var(--text-tertiary);+ }+}+@media (prefers-reduced-motion: reduce) {.plugin-motion-root .plugin-installed-overflow {animation: none !important;diff --git a/apps/desktop/src/renderer/hooks/useLocale.ts b/apps/desktop/src/renderer/hooks/useLocale.tsindex a94518c280..c928059285 100644--- a/apps/desktop/src/renderer/hooks/useLocale.ts+++ b/apps/desktop/src/renderer/hooks/useLocale.ts@@ -80,8 +80,7 @@ export function LocaleProvider({ children }: { children: ReactNode }) {applyLocale(eff);}, []);- // 首次 mount 时确保 i18next + <html lang> 与 state 一致 (state 来自 localStorage,- // 而 i18n.init 默认用的是 DEFAULT_LOCALE,两者可能不同)。+ // 首次 mount 时确保 i18next、<html lang> 和原生菜单与当前语言偏好一致。// 仅 mount 一次:locale 后续变化都走 setLocale 路径。useEffect(() => {applyLocale(effectiveLocale);diff --git a/apps/desktop/src/renderer/hooks/useSignInToCindy.ts b/apps/desktop/src/renderer/hooks/useSignInToCindy.tsindex 8dda440713..8f77776884 100644--- a/apps/desktop/src/renderer/hooks/useSignInToCindy.ts+++ b/apps/desktop/src/renderer/hooks/useSignInToCindy.ts@@ -16,7 +16,7 @@ import { useNavigate } from 'react-router-dom';import { useAuth } from '@/contexts/AuthContext';-export function useSignInToCindy(): () => Promise<void> {+export function useSignInToCindy(returnTo?: string): () => Promise<void> {const { mode, exitLocalMode } = useAuth();const navigate = useNavigate();@@ -29,6 +29,6 @@ export function useSignInToCindy(): () => Promise<void> {// transition is pending. Do not leave the sign-in action as a no-op.}}- navigate('/login');- }, [mode, exitLocalMode, navigate]);+ navigate('/login', returnTo ? { state: { returnTo } } : undefined);+ }, [mode, exitLocalMode, navigate, returnTo]);}diff --git a/apps/desktop/src/renderer/i18n/index.ts b/apps/desktop/src/renderer/i18n/index.tsindex 1a0ee927a0..6e69008d61 100644--- a/apps/desktop/src/renderer/i18n/index.ts+++ b/apps/desktop/src/renderer/i18n/index.ts@@ -5,7 +5,7 @@* - 资源同步 import (零网络/零 IO),i18n.init 同步完成 → React 首屏不闪。* - 默认 namespace 为 'common';体积较小、边界清晰的功能文案可独立拆分。* - fallbackLng:缺 key 时不显示 key 本身,直接回退英文。- * - 不接 LanguageDetector backend,用户偏好全部在 useLocale 里走 localStorage。+ * - 不接 LanguageDetector backend,初始化与 useLocale 共用现有语言偏好。* 'system' 的实际语言由 main 侧读取 OS 首选语言后传入 renderer。*/@@ -25,6 +25,7 @@ import koCommon from './locales/ko/common.json';import koAiRename from './locales/ko/aiRename.json';import { GHOST_OFFICIAL_ID_PREFIX } from '../../shared/ghost';import { DEFAULT_LOCALE } from '../../shared/locale';+import { getEffectiveLocale } from '../lib/localePreference';export {DEFAULT_LOCALE,@@ -93,7 +94,8 @@ const resources = {// 不 await 也安全:所有 t() 调用之前 init 已经完成 (本文件 import 即 init)。void i18n.use(initReactI18next).init({resources,- lng: DEFAULT_LOCALE,+ // 翻译资源热更新会重新执行本模块,不能把用户已选语言重置为默认英文。+ lng: getEffectiveLocale(),// 缺 key 回退英文。fallbackLng: { default: [DEFAULT_LOCALE] },defaultNS: 'common',diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 063054e4af..7a881fa205 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -6404,6 +6404,9 @@"installAria": "Install {{name}}"},"market": {+ "publisherKind": {+ "official": "Official"+ },"scopeAria": "Filter plugin sources","scope": {"all": "All",@@ -7136,6 +7139,204 @@"downloadsValue": "{{value}} downloads","usesValue": "{{value}} uses","usesExplanation": "Cumulative shared tool calls across all releases in the authorized audience. Your calls below count only this account on this computer."+ },+ "contribution": {+ "unreadReview": "New review result",+ "viewReviewResult": "View review result for {{version}}",+ "anonymous": "Publish anonymously",+ "anonymousHint": "Hide public attribution for the entire plugin. When disabled, each version shows the original author’s name saved when it was submitted.",+ "anonymousAuthorOnly": "Only the original author can change this",+ "anonymousUnavailable": "Author settings unavailable",+ "anonymousUpdateFailed": "Could not confirm the anonymity setting was saved. Refresh before trying again.",+ "myPlugins": "My Plugins",+ "publish": "Submit for Review",+ "submitUpdate": "Submit New Version for Review",+ "publishHint": "Publish only plugins you have permission to publish. Human approval is required for community listing.",+ "preparing": "Preparing the installed plugin…",+ "confirmSubmit": "Submit for Review",+ "confirmPublic": "The current plugin package, including its code and declared permissions, will be submitted for human review. Public community distribution requires approval.",+ "packageSize": "Package size: {{size}} bytes",+ "refreshList": "Refresh List",+ "refreshDetail": "Refresh Details",+ "personalRequired": "Switch to your personal account to view your plugins.",+ "permissionDenied": "This account cannot publish this plugin.",+ "notFound": "This plugin is unavailable to the current account.",+ "accountChanged": "The account changed. Refresh using the current account.",+ "loadFailed": "Plugin information could not be loaded.",+ "offline": "You are offline. Reconnect and refresh to see the latest result.",+ "cachedResult": "Showing the last result for this account",+ "lastRefreshed": "Last refreshed: {{time}}",+ "search": "Search your plugins",+ "filterLabel": "Filter your plugins",+ "filter": {+ "all": "All",+ "pending": "Pending Review",+ "needs_action": "Needs Attention",+ "published": "Published"+ },+ "loading": "Loading…",+ "empty": "No plugins submitted yet. Choose Publish Plugin to start with a plugin you developed and use.",+ "noMatches": "No plugins match this search or filter.",+ "viewLocal": "View Installed Plugins",+ "currentMarket": "Currently Published Version",+ "inUseVersion": "In Use",+ "localVersion": "Local version",+ "localEnabled": "Enabled",+ "localDisabled": "Disabled",+ "submitVersion": "Submit {{version}} for review",+ "installPublished": "Install published version",+ "publishedContentUnavailable": "The current published version’s description and release notes are temporarily unavailable.",+ "currentSubmission": "Current submission",+ "localState": {+ "missing": "Not installed on this computer",+ "unavailable": "Local version temporarily unavailable"+ },+ "listedVersion": "Published",+ "pendingVersion": "Pending Review",+ "notInstalled": "Not Installed",+ "versionUnknown": "Version Unknown",+ "noPendingVersion": "No Pending Review",+ "versionFacts": "Version Status",+ "publishing": "Publishing",+ "latestSubmission": "Latest Submission",+ "noSubmission": "No submissions yet",+ "marketVersion": "Published · {{version}}",+ "market": {+ "not_listed": "Not Listed",+ "disabled": "Unlisted",+ "archived": "Archived",+ "release_unavailable": "Version Unavailable"+ },+ "review": {+ "pending": "Pending Review",+ "approved": "Approved",+ "rejected": "Returned",+ "published": "Published",+ "superseded": "Replaced by a Later Submission",+ "legacy_unverified": "Historical revision unavailable",+ "current": "Result Unconfirmed",+ "cancelled": "Cancelled"+ },+ "reason": "Reason",+ "submittedContent": "Submitted Content",+ "snapshotUnavailable": "The original content was not retained or can no longer be verified.",+ "history": "Publishing History",+ "loadMore": "Load More",+ "loadMoreHistory": "Load More History",+ "releaseId": "Release ID",+ "revision": "Revision",+ "technicalDetails": "Technical Details",+ "outcome": {+ "submitted_for_review": "Submitted for Review",+ "metadata_updated": "Display Information Updated",+ "unchanged": "Existing Result Returned"+ },+ "event": {+ "submitted": "Submitted",+ "metadata_updated": "Display Information Updated",+ "approved": "Approved",+ "rejected": "Returned",+ "enabled": "Published",+ "disabled": "Unlisted",+ "current_changed": "Community Version Changed",+ "revoked": "Version Revoked",+ "cancelled": "Cancelled"+ },+ "source": {+ "manual": "Manual Publishing",+ "ai": "AI-Assisted Publishing",+ "github_oidc": "Repository Publishing",+ "console_upload": "Console Upload",+ "member_upload": "Organization Publishing",+ "server_template": "Template Publishing",+ "community_upload": "Community Publishing",+ "unknown": "Existing Publishing Channel"+ },+ "errors": {+ "CONTRIBUTION_NOT_AUTHORIZED": "You do not have permission to publish this public plugin. Contact its maintainer; installation does not grant publishing rights.",+ "CONTRIBUTION_REVISION_STALE": "The target version changed. Refresh and review it, then prepare again explicitly.",+ "RELEASE_VERSION_CONFLICT": "This version cannot replace its existing runtime content. Update the plugin version before submitting.",+ "PLUGIN_GHOST_ID_CONFLICT": "This public plugin ID already exists. It cannot be claimed by uploading a package.",+ "CONTRIBUTION_OPERATION_NOT_FOUND": "This account cannot view this submission.",+ "PRECONDITION_FAILED": "This plugin cannot currently be submitted for review.",+ "PERSONAL_CONTEXT_REQUIRED": "Switch to your personal account to view your plugins.",+ "ACCOUNT_REAUTH_REQUIRED": "Your personal account session is no longer valid. Sign in again before retrying.",+ "PERMISSION_DENIED": "This account cannot publish this plugin.",+ "OWNER_CHANGED": "The account changed. Refresh using the current account.",+ "PLUGIN_NOT_FOUND": "This plugin is unavailable to the current account.",+ "CONTRIBUTION_SUBMISSION_NOT_FOUND": "This plugin is unavailable to the current account.",+ "NOT_FOUND": "This plugin is unavailable to the current account.",+ "INTERNAL": "The submission result could not be confirmed.",+ "MUTATION_CANCELLED": "The submission result could not be confirmed.",+ "CONTRIBUTION_IDEMPOTENCY_CONFLICT": "The submission result could not be confirmed.",+ "PLUGIN_ARCHIVED": "Archived",+ "RELEASE_REVOKED": "Version Revoked",+ "INVALID_PARAMS": "The submission result could not be confirmed.",+ "PAYLOAD_TOO_LARGE": "The submission result could not be confirmed.",+ "RATE_LIMITED": "The submission result could not be confirmed.",+ "JWKS_UNAVAILABLE": "The submission result could not be confirmed.",+ "STORAGE_UNAVAILABLE": "The submission result could not be confirmed.",+ "PLUGIN_REPLICAS_NOT_READY": "The submission result could not be confirmed.",+ "UPLOAD_OBJECT_MISSING": "The submission result could not be confirmed.",+ "UPLOAD_SIZE_MISMATCH": "The submission result could not be confirmed.",+ "UPLOAD_SHA256_MISMATCH": "The submission result could not be confirmed.",+ "PLUGIN_PACKAGE_INVALID": "The submission result could not be confirmed.",+ "CONTRIBUTION_TARGET_MISMATCH": "The submission result could not be confirmed.",+ "PUBLISH_STORAGE_UNAVAILABLE": "The submission result could not be confirmed.",+ "PUBLISH_INTERNAL_ERROR": "The submission result could not be confirmed.",+ "RELEASE_NOTES_REQUIRED": "Not submitted for review: Complete ghost.json.releaseNotes in the plugin source, install the updated plugin, then submit it for review.",+ "VERSION_ALREADY_SUBMITTED": "This version was already submitted. Change the version number and install the updated plugin before submitting for review again.",+ "PLUGIN_PENDING_RELEASE_EXISTS": "Another version is under review. View or cancel that review first.",+ "CONTRIBUTION_PACKAGE_CHANGED": "The installed plugin changed after the summary was shown. Refresh and check it again."+ },+ "installForAccount": "The originally selected plugin installation could not be found. Select the plugin again in the current account and check it before submitting for review.",+ "releaseSha": "Release package SHA-256",+ "uploadedSha": "Uploaded package SHA-256",+ "publishPlugin": "Publish Plugin",+ "chooseLocal": "Choose a local plugin you developed, check its version, and submit it for review.",+ "noLocalPlugins": "No installed plugins yet. Install and use a plugin you developed first.",+ "noPublishablePlugins": "No installed plugins are available to publish. Install and use a plugin you developed, then check its installation identity and permission approval in the details.",+ "unavailable": {+ "officialGithubRequired": "Official public plugins cannot be submitted for review from the client. Submit changes through the GitHub repository to keep its source complete and support future maintenance.",+ "reservedId": "Plugins using Cindy's reserved identifiers cannot be submitted from the client. Submit official public plugin changes through GitHub to keep repository source complete and maintainable.",+ "privatePlugin": "Organization and private plugins cannot be converted to public community plugins.",+ "identityPending": "The plugin installation identity is not confirmed yet. Publishing is unavailable.",+ "approvalRequired": "The plugin permissions have not been approved. Complete the permission check in these details first.",+ "installationUnavailable": "This plugin installation is unavailable. Reopen the original plugin details.",+ "sourceUnverified": "This plugin’s installation source could not be verified. Open a local plugin you developed.",+ "publishingPermissionRequired": "This account does not have permission to submit this plugin."+ },+ "intro": "Manage plugin releases, updates and reviews",+ "pluginColumn": "Plugin",+ "latestState": "Latest status",+ "version": "Version",+ "chooseVersion": "View version",+ "submittedAt": "Submitted",+ "approvedAt": "Approved",+ "notApproved": "Not approved yet",+ "timeUnavailable": "Not recorded",+ "releaseNotes": "Release notes",+ "versionUpdates": "Versions & Updates",+ "versionManagement": "Manage Versions",+ "notesMissing": "No release notes were provided for this version",+ "versionContent": "Version content",+ "loadMoreVersions": "Load more versions",+ "notSubmitted": "Not submitted for review",+ "submitVersion": "Submit {{version}} for review",+ "publishingVersion": "Version for Review · {{version}}",+ "refreshSummary": "Refresh publishing summary",+ "versionConsumedHint": "Once a submission is accepted for review, its version number cannot be reused, even after cancellation or rejection.",+ "cancelReview": "Cancel this review",+ "cancelReviewTitle": "Cancel review of {{name}} {{version}}?",+ "cancelReviewDescription": "The currently listed version stays available. Version {{version}} has been submitted and cannot be submitted again. Use a new version number.",+ "keepReview": "Keep review",+ "cancelledAt": "Cancelled at",+ "cancelled": "Cancelled",+ "cancelReviewCompleted": "Review cancelled. The currently listed version is unchanged.",+ "cancelReviewAlreadyFinal": "Review already finished, so it was not cancelled. The actual result is shown below.",+ "viewPendingVersion": "View version under review",+ "submitFailed": "Submission failed",+ "viewDetails": "View details"}},"mcp": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 22a2c86b29..ef95937ea0 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -6373,6 +6373,9 @@"installAria": "{{name}} をインストール"},"market": {+ "publisherKind": {+ "official": "公式"+ },"scopeAria": "プラグインの提供元を絞り込む","scope": {"all": "すべて",@@ -7105,6 +7108,204 @@"downloadsValue": "{{value}} ダウンロード","usesValue": "{{value}} 利用","usesExplanation": "許可された共有範囲の全バージョンにおける累計ツール呼び出し数です。下の個人の呼び出しは、この端末の現在のアカウントのみを集計します。"+ },+ "contribution": {+ "unreadReview": "新しい審査結果があります",+ "viewReviewResult": "{{version}} の審査結果を見る",+ "anonymous": "匿名で公開",+ "anonymousHint": "プラグイン全体の公開作者名を非表示にします。オフにすると、各バージョンの審査提出時に保存された元の作者名が表示されます。",+ "anonymousAuthorOnly": "変更できるのは元の作者のみです",+ "anonymousUnavailable": "作者設定を取得できません",+ "anonymousUpdateFailed": "匿名設定が保存されたか確認できません。更新してから再試行してください。",+ "myPlugins": "マイプラグイン",+ "publish": "審査に提出",+ "submitUpdate": "新しいバージョンを審査に提出",+ "publishHint": "公開する権限のあるプラグインのみ対象です。審査の承認後にコミュニティで公開されます。",+ "preparing": "インストール済みのプラグインを準備中…",+ "confirmSubmit": "審査に提出",+ "confirmPublic": "現在のプラグインパッケージ(コードと宣言した権限を含む)を人による審査に提出します。コミュニティでの公開配布には審査の承認が必要です。",+ "packageSize": "パッケージサイズ:{{size}} バイト",+ "refreshList": "一覧を更新",+ "refreshDetail": "詳細を更新",+ "personalRequired": "個人アカウントに切り替えてマイプラグインを表示してください。",+ "permissionDenied": "このアカウントではこのプラグインを公開できません。",+ "notFound": "現在のアカウントではこのプラグインを表示できません。",+ "accountChanged": "アカウントが変わりました。現在のアカウントで更新してください。",+ "loadFailed": "プラグイン情報を読み込めません。",+ "offline": "オフラインです。接続後に更新して最新の結果を確認してください。",+ "cachedResult": "このアカウントの前回の結果を表示中",+ "lastRefreshed": "最終更新:{{time}}",+ "search": "マイプラグインを検索",+ "filterLabel": "マイプラグインを絞り込む",+ "filter": {+ "all": "すべて",+ "pending": "審査待ち",+ "needs_action": "対応が必要",+ "published": "公開中"+ },+ "loading": "読み込み中…",+ "empty": "提出したプラグインはまだありません。「プラグインを公開」から、自分で開発して使用しているプラグインを選んでください。",+ "noMatches": "検索条件に一致するプラグインはありません。",+ "viewLocal": "インストール済みプラグインを見る",+ "currentMarket": "現在公開中のバージョン",+ "inUseVersion": "使用中",+ "localVersion": "ローカル版",+ "localEnabled": "有効",+ "localDisabled": "無効",+ "submitVersion": "{{version}} を審査に提出",+ "installPublished": "公開版をインストール",+ "publishedContentUnavailable": "現在の公開版の説明と更新内容を読み込めません。",+ "currentSubmission": "現在の提出",+ "localState": {+ "missing": "このコンピューターには未インストール",+ "unavailable": "ローカル版を読み込めません"+ },+ "listedVersion": "公開中",+ "pendingVersion": "審査待ち",+ "notInstalled": "未インストール",+ "versionUnknown": "バージョン不明",+ "noPendingVersion": "審査待ちなし",+ "versionFacts": "バージョンの状況",+ "publishing": "公開管理",+ "latestSubmission": "最新の提出",+ "noSubmission": "まだ提出されていません",+ "marketVersion": "公開中 · {{version}}",+ "market": {+ "not_listed": "未公開",+ "disabled": "公開停止中",+ "archived": "アーカイブ済み",+ "release_unavailable": "バージョンを利用できません"+ },+ "review": {+ "pending": "審査待ち",+ "approved": "承認済み",+ "rejected": "差し戻し",+ "published": "公開中",+ "superseded": "後の提出に置き換え済み",+ "legacy_unverified": "過去の改訂を確認できません",+ "current": "結果未確認",+ "cancelled": "取り消し済み"+ },+ "reason": "理由",+ "submittedContent": "送信した内容",+ "snapshotUnavailable": "送信した内容が保存されていないか、確認できません。",+ "history": "公開履歴",+ "loadMore": "さらに表示",+ "loadMoreHistory": "履歴をさらに表示",+ "releaseId": "リリース ID",+ "revision": "改訂トークン",+ "technicalDetails": "技術情報",+ "outcome": {+ "submitted_for_review": "審査に提出済み",+ "metadata_updated": "表示情報を更新済み",+ "unchanged": "変更なし(既存の結果)"+ },+ "event": {+ "submitted": "提出済み",+ "metadata_updated": "表示情報を更新済み",+ "approved": "承認済み",+ "rejected": "差し戻し",+ "enabled": "公開を開始",+ "disabled": "公開を停止",+ "current_changed": "公開バージョンを変更",+ "revoked": "バージョンを取り消し",+ "cancelled": "取り消し済み"+ },+ "source": {+ "manual": "手動で公開",+ "ai": "AI で公開",+ "github_oidc": "リポジトリから公開",+ "console_upload": "コンソールから送信",+ "member_upload": "組織から公開",+ "server_template": "テンプレートから公開",+ "community_upload": "コミュニティで公開",+ "unknown": "既存の公開経路"+ },+ "errors": {+ "CONTRIBUTION_NOT_AUTHORIZED": "この公開プラグインを審査に提出する権限がありません。管理者に連絡してください。インストールしても公開する権限は付与されません。",+ "CONTRIBUTION_REVISION_STALE": "対象のバージョンが変わりました。更新して確認後に再準備してください。",+ "RELEASE_VERSION_CONFLICT": "このバージョンの実行内容は上書きできません。バージョンを更新してください。",+ "PLUGIN_GHOST_ID_CONFLICT": "この公開プラグイン ID は使用済みです。アップロードで所有権は取得できません。",+ "CONTRIBUTION_OPERATION_NOT_FOUND": "このアカウントでは、この提出を確認できません。",+ "PRECONDITION_FAILED": "現在、このプラグインは審査に提出できません。",+ "PERSONAL_CONTEXT_REQUIRED": "個人アカウントに切り替えてマイプラグインを表示してください。",+ "ACCOUNT_REAUTH_REQUIRED": "個人アカウントのログイン状態が無効です。再度ログインしてからお試しください。",+ "PERMISSION_DENIED": "このアカウントではこのプラグインを公開できません。",+ "OWNER_CHANGED": "アカウントが変わりました。現在のアカウントで更新してください。",+ "PLUGIN_NOT_FOUND": "現在のアカウントではこのプラグインを表示できません。",+ "CONTRIBUTION_SUBMISSION_NOT_FOUND": "現在のアカウントではこのプラグインを表示できません。",+ "NOT_FOUND": "現在のアカウントではこのプラグインを表示できません。",+ "INTERNAL": "提出結果を確認できません。",+ "MUTATION_CANCELLED": "提出結果を確認できません。",+ "CONTRIBUTION_IDEMPOTENCY_CONFLICT": "提出結果を確認できません。",+ "PLUGIN_ARCHIVED": "アーカイブ済み",+ "RELEASE_REVOKED": "バージョンを取り消し",+ "INVALID_PARAMS": "提出結果を確認できません。",+ "PAYLOAD_TOO_LARGE": "提出結果を確認できません。",+ "RATE_LIMITED": "提出結果を確認できません。",+ "JWKS_UNAVAILABLE": "提出結果を確認できません。",+ "STORAGE_UNAVAILABLE": "提出結果を確認できません。",+ "PLUGIN_REPLICAS_NOT_READY": "提出結果を確認できません。",+ "UPLOAD_OBJECT_MISSING": "提出結果を確認できません。",+ "UPLOAD_SIZE_MISMATCH": "提出結果を確認できません。",+ "UPLOAD_SHA256_MISMATCH": "提出結果を確認できません。",+ "PLUGIN_PACKAGE_INVALID": "提出結果を確認できません。",+ "CONTRIBUTION_TARGET_MISMATCH": "提出結果を確認できません。",+ "PUBLISH_STORAGE_UNAVAILABLE": "提出結果を確認できません。",+ "PUBLISH_INTERNAL_ERROR": "提出結果を確認できません。",+ "RELEASE_NOTES_REQUIRED": "審査未提出:プラグインのソースにある ghost.json.releaseNotes に更新内容を記載し、更新したプラグインをインストールしてから審査に提出してください。",+ "VERSION_ALREADY_SUBMITTED": "このバージョンは提出済みです。バージョン番号を変更して更新をインストールしてから、審査に再提出してください。",+ "PLUGIN_PENDING_RELEASE_EXISTS": "別のバージョンが審査中です。その審査を確認するか取り消してください。",+ "CONTRIBUTION_PACKAGE_CHANGED": "概要の表示後にインストール済みプラグインが変わりました。再読み込みして確認してください。"+ },+ "installForAccount": "選択した元のプラグインのインストールが見つかりません。現在のアカウントで選び直し、確認してから審査に提出してください。",+ "releaseSha": "リリースパッケージの SHA-256",+ "uploadedSha": "アップロードしたパッケージの SHA-256",+ "publishPlugin": "プラグインを公開",+ "chooseLocal": "自分で開発したローカルプラグインを選び、バージョンを確認して審査に提出してください。",+ "noLocalPlugins": "インストール済みのプラグインはありません。自分で開発したプラグインをインストールして使用してください。",+ "noPublishablePlugins": "公開できるインストール済みプラグインはありません。自分で開発したプラグインをインストールして使用し、詳細画面でインストール元の識別情報と権限の承認状態を確認してください。",+ "unavailable": {+ "officialGithubRequired": "公式公開プラグインはクライアントから審査に提出できません。リポジトリのソースコードを完全に保ち、継続して保守できるよう、変更は GitHub リポジトリから提出してください。",+ "reservedId": "Cindy の予約済み識別子を使うプラグインはクライアントから審査に提出できません。公式公開プラグインの変更は、ソースコードを完全に保ち、継続して保守できるよう GitHub リポジトリから提出してください。",+ "privatePlugin": "組織内または非公開のプラグインをコミュニティの公開プラグインに変更することはできません。",+ "identityPending": "プラグインのインストール元の識別情報が未確認のため、まだ公開できません。",+ "approvalRequired": "このプラグインの権限はまだ承認されていません。この詳細画面で先に確認を完了してください。",+ "installationUnavailable": "このプラグインのインストールを利用できません。元のプラグインの詳細を開き直してください。",+ "sourceUnverified": "このプラグインのインストール元を確認できません。ご自身が開発したローカルのプラグインを開いてください。",+ "publishingPermissionRequired": "このアカウントには、このプラグインを審査に提出する権限がありません。"+ },+ "intro": "プラグインの公開・更新・審査状況を管理",+ "pluginColumn": "プラグイン",+ "latestState": "最新の状況",+ "version": "バージョン",+ "chooseVersion": "バージョンを表示",+ "submittedAt": "審査提出日時",+ "approvedAt": "承認日時",+ "notApproved": "未承認",+ "timeUnavailable": "記録なし",+ "releaseNotes": "更新内容",+ "versionUpdates": "バージョンと更新",+ "versionManagement": "バージョン管理",+ "notesMissing": "このバージョンの更新内容は記載されていません",+ "versionContent": "バージョンの内容",+ "loadMoreVersions": "さらにバージョンを読み込む",+ "notSubmitted": "審査未提出",+ "submitVersion": "{{version}} を審査に提出",+ "publishingVersion": "審査に提出するバージョン · {{version}}",+ "refreshSummary": "公開内容を再読み込み",+ "versionConsumedHint": "審査への提出が受理されると、そのバージョン番号は再利用できません。取消・差し戻し後も新しい番号が必要です。",+ "cancelReview": "この審査を取り消す",+ "cancelReviewTitle": "{{name}} {{version}} の審査を取り消しますか?",+ "cancelReviewDescription": "公開中のバージョンには影響しません。{{version}} は提出済みのため、次回は新しいバージョン番号が必要です。",+ "keepReview": "審査を続ける",+ "cancelledAt": "取消日時",+ "cancelled": "取り消し済み",+ "cancelReviewCompleted": "審査を取り消しました。公開中のバージョンに影響はありません。",+ "cancelReviewAlreadyFinal": "審査は完了しているため取り消されませんでした。実際の結果を下に表示します。",+ "viewPendingVersion": "審査中のバージョンを表示",+ "submitFailed": "提出に失敗",+ "viewDetails": "詳細を見る"}},"mcp": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 69619e9d97..1d9643b2ef 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -6373,6 +6373,9 @@"installAria": "{{name}} 설치"},"market": {+ "publisherKind": {+ "official": "공식"+ },"scopeAria": "플러그인 출처 필터","scope": {"all": "전체",@@ -7105,6 +7108,204 @@"downloadsValue": "{{value}} 다운로드","usesValue": "{{value}} 사용","usesExplanation": "허용된 공유 범위의 모든 버전에서 누적된 도구 호출 수입니다. 아래 내 호출은 이 컴퓨터의 현재 계정만 집계합니다."+ },+ "contribution": {+ "unreadReview": "새 심사 결과가 있습니다",+ "viewReviewResult": "{{version}} 심사 결과 보기",+ "anonymous": "익명으로 게시",+ "anonymousHint": "플러그인 전체의 공개 작성자 이름을 숨깁니다. 끄면 각 버전의 심사 제출 시 저장된 원작자 이름이 표시됩니다.",+ "anonymousAuthorOnly": "원작자만 변경할 수 있습니다",+ "anonymousUnavailable": "작성자 설정을 불러올 수 없습니다",+ "anonymousUpdateFailed": "익명 설정이 저장되었는지 확인할 수 없습니다. 새로고침 후 다시 시도하세요.",+ "myPlugins": "내 플러그인",+ "publish": "심사 요청",+ "submitUpdate": "새 버전 심사 요청",+ "publishHint": "게시 권한이 있는 플러그인만 게시하세요. 담당자의 검토와 승인 후 커뮤니티에 게시됩니다.",+ "preparing": "설치된 플러그인을 준비하는 중…",+ "confirmSubmit": "심사 요청",+ "confirmPublic": "현재 플러그인 패키지의 코드와 선언된 권한을 담당자 심사에 제출합니다. 커뮤니티 공개 배포에는 심사 승인이 필요합니다.",+ "packageSize": "패키지 크기: {{size}}바이트",+ "refreshList": "목록 새로고침",+ "refreshDetail": "상세 새로고침",+ "personalRequired": "개인 계정으로 전환해 내 플러그인을 확인하세요.",+ "permissionDenied": "이 계정으로는 이 플러그인을 게시할 수 없습니다.",+ "notFound": "현재 계정으로 이 플러그인을 볼 수 없습니다.",+ "accountChanged": "계정이 변경되었습니다. 현재 계정으로 새로고침하세요.",+ "loadFailed": "플러그인 정보를 불러올 수 없습니다.",+ "offline": "오프라인 상태입니다. 연결 후 새로고침해 최신 결과를 확인하세요.",+ "cachedResult": "이 계정의 마지막 조회 결과 표시 중",+ "lastRefreshed": "마지막 새로고침: {{time}}",+ "search": "내 플러그인 검색",+ "filterLabel": "내 플러그인 필터",+ "filter": {+ "all": "전체",+ "pending": "심사 대기",+ "needs_action": "조치 필요",+ "published": "게시됨"+ },+ "loading": "불러오는 중…",+ "empty": "아직 제출한 플러그인이 없습니다. 플러그인 게시를 눌러 직접 개발하고 사용하는 플러그인을 선택하세요.",+ "noMatches": "검색 또는 필터 조건과 일치하는 플러그인이 없습니다.",+ "viewLocal": "설치된 플러그인 보기",+ "currentMarket": "현재 게시된 버전",+ "inUseVersion": "사용 중",+ "localVersion": "로컬 버전",+ "localEnabled": "사용 중",+ "localDisabled": "사용 안 함",+ "submitVersion": "{{version}} 검토 요청",+ "installPublished": "공개된 버전 설치",+ "publishedContentUnavailable": "현재 공개된 버전의 설명과 업데이트 내용을 불러올 수 없습니다.",+ "currentSubmission": "현재 제출",+ "localState": {+ "missing": "이 컴퓨터에 설치되지 않음",+ "unavailable": "로컬 버전을 불러올 수 없음"+ },+ "listedVersion": "게시됨",+ "pendingVersion": "심사 대기",+ "notInstalled": "설치되지 않음",+ "versionUnknown": "버전 알 수 없음",+ "noPendingVersion": "심사 대기 버전 없음",+ "versionFacts": "버전 상태",+ "publishing": "게시 관리",+ "latestSubmission": "최근 제출",+ "noSubmission": "아직 제출 내역 없음",+ "marketVersion": "게시됨 · {{version}}",+ "market": {+ "not_listed": "게시 전",+ "disabled": "게시 중단",+ "archived": "보관됨",+ "release_unavailable": "버전 사용 불가"+ },+ "review": {+ "pending": "심사 대기",+ "approved": "승인됨",+ "rejected": "반려됨",+ "published": "게시됨",+ "superseded": "이후 제출로 대체됨",+ "legacy_unverified": "과거 수정본 확인 불가",+ "current": "처리 결과 미확인",+ "cancelled": "취소됨"+ },+ "reason": "처리 사유",+ "submittedContent": "제출된 내용",+ "snapshotUnavailable": "원래 제출 내용이 보존되지 않았거나 확인할 수 없습니다.",+ "history": "게시 이력",+ "loadMore": "더 보기",+ "loadMoreHistory": "이력 더 보기",+ "releaseId": "릴리스 ID",+ "revision": "수정 토큰",+ "technicalDetails": "상세 정보",+ "outcome": {+ "submitted_for_review": "심사 제출됨",+ "metadata_updated": "표시 정보 업데이트됨",+ "unchanged": "변경 없음, 기존 결과 반환"+ },+ "event": {+ "submitted": "제출됨",+ "metadata_updated": "표시 정보 업데이트됨",+ "approved": "승인됨",+ "rejected": "반려됨",+ "enabled": "게시 시작",+ "disabled": "게시 중단",+ "current_changed": "게시 버전 변경",+ "revoked": "버전 철회됨",+ "cancelled": "취소됨"+ },+ "source": {+ "manual": "직접 게시",+ "ai": "AI 지원 게시",+ "github_oidc": "저장소 게시",+ "console_upload": "콘솔 업로드",+ "member_upload": "조직 게시",+ "server_template": "템플릿 게시",+ "community_upload": "커뮤니티 게시",+ "unknown": "기존 게시 경로"+ },+ "errors": {+ "CONTRIBUTION_NOT_AUTHORIZED": "이 공개 플러그인을 심사에 제출할 권한이 없습니다. 관리자에게 문의하세요. 설치만으로 게시 권한이 부여되지는 않습니다.",+ "CONTRIBUTION_REVISION_STALE": "대상 버전이 변경되었습니다. 새로고침해 확인한 후 다시 준비하세요.",+ "RELEASE_VERSION_CONFLICT": "이 버전의 기존 실행 내용을 덮어쓸 수 없습니다. 버전을 올린 후 제출하세요.",+ "PLUGIN_GHOST_ID_CONFLICT": "이 공개 플러그인 ID는 이미 존재합니다. 업로드로 소유권을 얻을 수 없습니다.",+ "CONTRIBUTION_OPERATION_NOT_FOUND": "현재 계정으로 이 제출 내역을 볼 수 없습니다.",+ "PRECONDITION_FAILED": "현재 이 플러그인을 검토에 제출할 수 없습니다.",+ "PERSONAL_CONTEXT_REQUIRED": "개인 계정으로 전환해 내 플러그인을 확인하세요.",+ "ACCOUNT_REAUTH_REQUIRED": "개인 계정 로그인 세션이 유효하지 않습니다. 다시 로그인한 후 시도하세요.",+ "PERMISSION_DENIED": "이 계정으로는 이 플러그인을 게시할 수 없습니다.",+ "OWNER_CHANGED": "계정이 변경되었습니다. 현재 계정으로 새로고침하세요.",+ "PLUGIN_NOT_FOUND": "현재 계정으로 이 플러그인을 볼 수 없습니다.",+ "CONTRIBUTION_SUBMISSION_NOT_FOUND": "현재 계정으로 이 플러그인을 볼 수 없습니다.",+ "NOT_FOUND": "현재 계정으로 이 플러그인을 볼 수 없습니다.",+ "INTERNAL": "제출 결과를 확인할 수 없습니다.",+ "MUTATION_CANCELLED": "제출 결과를 확인할 수 없습니다.",+ "CONTRIBUTION_IDEMPOTENCY_CONFLICT": "제출 결과를 확인할 수 없습니다.",+ "PLUGIN_ARCHIVED": "보관됨",+ "RELEASE_REVOKED": "버전 철회됨",+ "INVALID_PARAMS": "제출 결과를 확인할 수 없습니다.",+ "PAYLOAD_TOO_LARGE": "제출 결과를 확인할 수 없습니다.",+ "RATE_LIMITED": "제출 결과를 확인할 수 없습니다.",+ "JWKS_UNAVAILABLE": "제출 결과를 확인할 수 없습니다.",+ "STORAGE_UNAVAILABLE": "제출 결과를 확인할 수 없습니다.",+ "PLUGIN_REPLICAS_NOT_READY": "제출 결과를 확인할 수 없습니다.",+ "UPLOAD_OBJECT_MISSING": "제출 결과를 확인할 수 없습니다.",+ "UPLOAD_SIZE_MISMATCH": "제출 결과를 확인할 수 없습니다.",+ "UPLOAD_SHA256_MISMATCH": "제출 결과를 확인할 수 없습니다.",+ "PLUGIN_PACKAGE_INVALID": "제출 결과를 확인할 수 없습니다.",+ "CONTRIBUTION_TARGET_MISMATCH": "제출 결과를 확인할 수 없습니다.",+ "PUBLISH_STORAGE_UNAVAILABLE": "제출 결과를 확인할 수 없습니다.",+ "PUBLISH_INTERNAL_ERROR": "제출 결과를 확인할 수 없습니다.",+ "RELEASE_NOTES_REQUIRED": "아직 심사에 제출되지 않았습니다. 플러그인 소스의 ghost.json.releaseNotes에 업데이트 내용을 작성하고, 업데이트한 플러그인을 설치한 후 심사를 요청하세요.",+ "VERSION_ALREADY_SUBMITTED": "이미 심사를 요청한 버전입니다. 버전 번호를 변경하고 업데이트를 설치한 후 다시 심사를 요청하세요.",+ "PLUGIN_PENDING_RELEASE_EXISTS": "다른 버전이 심사 중입니다. 먼저 해당 심사를 확인하거나 취소하세요.",+ "CONTRIBUTION_PACKAGE_CHANGED": "요약을 표시한 뒤 설치된 플러그인이 변경되었습니다. 새로 고침하고 다시 확인하세요."+ },+ "installForAccount": "처음 선택한 플러그인 설치를 찾을 수 없습니다. 현재 계정에서 플러그인을 다시 선택하고 확인한 후 심사를 요청하세요.",+ "releaseSha": "릴리스 패키지 SHA-256",+ "uploadedSha": "업로드한 패키지 SHA-256",+ "publishPlugin": "플러그인 게시",+ "chooseLocal": "직접 개발한 로컬 플러그인을 선택하고 버전을 확인한 후 심사를 요청하세요.",+ "noLocalPlugins": "설치된 플러그인이 없습니다. 직접 개발한 플러그인을 먼저 설치하고 사용하세요.",+ "noPublishablePlugins": "게시할 수 있는 설치된 플러그인이 없습니다. 직접 개발한 플러그인을 설치하고 사용한 다음 상세 화면에서 설치 ID와 권한 승인 상태를 확인하세요.",+ "unavailable": {+ "officialGithubRequired": "공식 공개 플러그인은 클라이언트에서 심사를 요청할 수 없습니다. 저장소 소스 코드의 완전성을 유지하고 향후 유지보수를 위해 GitHub 저장소를 통해 변경 사항을 제출하세요.",+ "reservedId": "Cindy 예약 식별자를 사용하는 플러그인은 클라이언트에서 심사를 요청할 수 없습니다. 공식 공개 플러그인의 변경 사항은 소스 코드의 완전성과 향후 유지보수를 위해 GitHub 저장소를 통해 제출하세요.",+ "privatePlugin": "조직 또는 비공개 플러그인을 커뮤니티 공개 플러그인으로 전환할 수 없습니다.",+ "identityPending": "플러그인 설치 ID가 아직 확인되지 않아 게시할 수 없습니다.",+ "approvalRequired": "플러그인 권한이 아직 승인되지 않았습니다. 이 상세 화면에서 먼저 권한 확인을 완료하세요.",+ "installationUnavailable": "이 플러그인 설치를 사용할 수 없습니다. 원래 플러그인 상세를 다시 여세요.",+ "sourceUnverified": "이 플러그인의 설치 출처를 확인할 수 없습니다. 직접 개발한 로컬 플러그인을 여세요.",+ "publishingPermissionRequired": "이 계정에는 이 플러그인을 심사에 제출할 권한이 없습니다."+ },+ "intro": "플러그인의 게시, 업데이트 및 심사 상태 관리",+ "pluginColumn": "플러그인",+ "latestState": "최근 상태",+ "version": "버전",+ "chooseVersion": "버전 보기",+ "submittedAt": "심사 제출 시간",+ "approvedAt": "승인 시간",+ "notApproved": "아직 승인되지 않음",+ "timeUnavailable": "기록 없음",+ "releaseNotes": "업데이트 내용",+ "versionUpdates": "버전 및 업데이트",+ "versionManagement": "버전 관리",+ "notesMissing": "이 버전에는 업데이트 내용이 제공되지 않았습니다",+ "versionContent": "버전 내용",+ "loadMoreVersions": "버전 더 불러오기",+ "notSubmitted": "심사에 제출되지 않음",+ "submitVersion": "{{version}} 심사 요청",+ "publishingVersion": "심사 요청 버전 · {{version}}",+ "refreshSummary": "게시 요약 새로 고침",+ "versionConsumedHint": "심사 제출이 접수되면 해당 버전 번호는 다시 사용할 수 없습니다. 취소 또는 반려 후에도 새 버전 번호가 필요합니다.",+ "cancelReview": "이번 심사 취소",+ "cancelReviewTitle": "{{name}} {{version}} 심사를 취소할까요?",+ "cancelReviewDescription": "현재 게시된 버전에는 영향이 없습니다. {{version}}은 이미 심사를 요청했으므로 다음 요청에는 새 버전 번호가 필요합니다.",+ "keepReview": "심사 유지",+ "cancelledAt": "취소 시간",+ "cancelled": "취소됨",+ "cancelReviewCompleted": "심사가 취소되었습니다. 현재 게시된 버전에는 영향이 없습니다.",+ "cancelReviewAlreadyFinal": "심사가 이미 완료되어 취소되지 않았습니다. 아래에 실제 결과가 표시됩니다.",+ "viewPendingVersion": "심사 중인 버전 보기",+ "submitFailed": "제출 실패",+ "viewDetails": "상세 보기"}},"mcp": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 1e258e8402..7d2d9ca6a7 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -6373,6 +6373,9 @@"installAria": "安装 {{name}}"},"market": {+ "publisherKind": {+ "official": "官方"+ },"scopeAria": "筛选插件来源","scope": {"all": "全部",@@ -7105,6 +7108,204 @@"downloadsValue": "{{value}} 下载","usesValue": "{{value}} 使用","usesExplanation": "当前共享范围内各版本累计的工具调用次数。下方个人调用仅统计本机当前账户,口径不同。"+ },+ "contribution": {+ "unreadReview": "有新的审核结果",+ "viewReviewResult": "查看 {{version}} 审核结果",+ "anonymous": "匿名发布",+ "anonymousHint": "对整款插件隐藏公开署名,可随时修改。关闭后显示各版本提审时保存的原作者昵称。",+ "anonymousAuthorOnly": "仅原作者可修改",+ "anonymousUnavailable": "作者设置暂不可用",+ "anonymousUpdateFailed": "无法确认匿名设置是否已保存,请刷新后重试。",+ "myPlugins": "我的插件",+ "publish": "提交审核",+ "submitUpdate": "提交新版本审核",+ "publishHint": "仅限有权发布的插件,审核通过后在社区上架。",+ "preparing": "正在准备当前安装的插件…",+ "confirmSubmit": "提交审核",+ "confirmPublic": "当前插件包及其中的代码、声明的权限将提交人工审核,审核通过后可在社区公开分发。",+ "packageSize": "包大小:{{size}} 字节",+ "refreshList": "刷新列表",+ "refreshDetail": "刷新详情",+ "personalRequired": "请切换到个人账号查看我的插件。",+ "permissionDenied": "当前账号无权发布此插件。",+ "notFound": "当前账号无法查看此插件。",+ "accountChanged": "账号已切换,请用当前账号刷新。",+ "loadFailed": "暂时无法读取插件信息。",+ "offline": "当前离线,请联网后刷新查看最新结果。",+ "cachedResult": "当前显示此账号上次查询的结果",+ "lastRefreshed": "上次刷新:{{time}}",+ "search": "搜索我的插件",+ "filterLabel": "筛选我的插件",+ "filter": {+ "all": "全部",+ "pending": "待审核",+ "needs_action": "需要处理",+ "published": "已上架"+ },+ "loading": "正在加载…",+ "empty": "还没有提交过插件。点击“发布插件”,选择自己开发并使用的插件。",+ "noMatches": "没有符合搜索或筛选条件的插件。",+ "viewLocal": "查看已安装插件",+ "currentMarket": "当前上架版本",+ "inUseVersion": "使用中",+ "localVersion": "本地版本",+ "localEnabled": "已启用",+ "localDisabled": "已停用",+ "submitVersion": "提交 {{version}} 审核",+ "installPublished": "安装已上架版本",+ "publishedContentUnavailable": "暂时无法读取当前上架版本的介绍和更新说明。",+ "currentSubmission": "当前提审",+ "localState": {+ "missing": "本机未安装",+ "unavailable": "暂时无法读取本地版本"+ },+ "listedVersion": "已上架",+ "pendingVersion": "待审核",+ "notInstalled": "未安装",+ "versionUnknown": "版本未知",+ "noPendingVersion": "无待审核版本",+ "versionFacts": "版本状态",+ "publishing": "发布管理",+ "latestSubmission": "最近提交",+ "noSubmission": "尚无提交",+ "marketVersion": "已上架 · {{version}}",+ "market": {+ "not_listed": "尚未上架",+ "disabled": "已下架",+ "archived": "已归档",+ "release_unavailable": "版本暂不可用"+ },+ "review": {+ "pending": "待审核",+ "approved": "审核通过",+ "rejected": "已退回",+ "published": "已上架",+ "superseded": "已被后续提交替代",+ "legacy_unverified": "历史修订无法核实",+ "current": "处理结果尚未确认",+ "cancelled": "已取消"+ },+ "reason": "处理原因",+ "submittedContent": "已提交内容",+ "snapshotUnavailable": "原提交内容未留存或已无法核实。",+ "history": "发布记录",+ "loadMore": "加载更多",+ "loadMoreHistory": "加载更多历史",+ "releaseId": "版本记录 ID",+ "revision": "修订令牌",+ "technicalDetails": "技术详情",+ "outcome": {+ "submitted_for_review": "已提交审核",+ "metadata_updated": "展示信息已更新",+ "unchanged": "内容未变,已返回已有结果"+ },+ "event": {+ "submitted": "已提交",+ "metadata_updated": "展示信息已更新",+ "approved": "审核通过",+ "rejected": "已退回",+ "enabled": "已上架",+ "disabled": "已下架",+ "current_changed": "市场版本已切换",+ "revoked": "版本已撤销",+ "cancelled": "已取消"+ },+ "source": {+ "manual": "手动发布",+ "ai": "AI 协助发布",+ "github_oidc": "仓库发布",+ "console_upload": "控制台上传",+ "member_upload": "企业发布",+ "server_template": "模板发布",+ "community_upload": "社区发布",+ "unknown": "既有发布渠道"+ },+ "errors": {+ "CONTRIBUTION_NOT_AUTHORIZED": "没有此公开插件的提交权限,请联系维护者。安装插件不授予发布权。",+ "CONTRIBUTION_REVISION_STALE": "目标版本已变化,请刷新并核对内容后重新准备。",+ "RELEASE_VERSION_CONFLICT": "此版本不能覆盖已有运行内容,请修改插件版本后再提交。",+ "PLUGIN_GHOST_ID_CONFLICT": "此公开插件 ID 已存在,不能通过上传插件包认领。",+ "CONTRIBUTION_OPERATION_NOT_FOUND": "当前账号无法查看这次提交。",+ "PRECONDITION_FAILED": "当前插件无法提交审核。",+ "PERSONAL_CONTEXT_REQUIRED": "请切换到个人账号查看我的插件。",+ "ACCOUNT_REAUTH_REQUIRED": "个人账号登录状态已失效,请重新登录后重试。",+ "PERMISSION_DENIED": "当前账号无权发布此插件。",+ "OWNER_CHANGED": "账号已切换,请用当前账号刷新。",+ "PLUGIN_NOT_FOUND": "当前账号无法查看此插件。",+ "CONTRIBUTION_SUBMISSION_NOT_FOUND": "当前账号无法查看此插件。",+ "NOT_FOUND": "当前账号无法查看此插件。",+ "INTERNAL": "暂时无法确认提交结果。",+ "MUTATION_CANCELLED": "暂时无法确认提交结果。",+ "CONTRIBUTION_IDEMPOTENCY_CONFLICT": "暂时无法确认提交结果。",+ "PLUGIN_ARCHIVED": "已归档",+ "RELEASE_REVOKED": "版本已撤销",+ "INVALID_PARAMS": "暂时无法确认提交结果。",+ "PAYLOAD_TOO_LARGE": "暂时无法确认提交结果。",+ "RATE_LIMITED": "暂时无法确认提交结果。",+ "JWKS_UNAVAILABLE": "暂时无法确认提交结果。",+ "STORAGE_UNAVAILABLE": "暂时无法确认提交结果。",+ "PLUGIN_REPLICAS_NOT_READY": "暂时无法确认提交结果。",+ "UPLOAD_OBJECT_MISSING": "暂时无法确认提交结果。",+ "UPLOAD_SIZE_MISMATCH": "暂时无法确认提交结果。",+ "UPLOAD_SHA256_MISMATCH": "暂时无法确认提交结果。",+ "PLUGIN_PACKAGE_INVALID": "暂时无法确认提交结果。",+ "CONTRIBUTION_TARGET_MISMATCH": "暂时无法确认提交结果。",+ "PUBLISH_STORAGE_UNAVAILABLE": "暂时无法确认提交结果。",+ "PUBLISH_INTERNAL_ERROR": "暂时无法确认提交结果。",+ "RELEASE_NOTES_REQUIRED": "尚未提审:请在插件源码的 ghost.json.releaseNotes 中补全更新说明,安装更新后重新提交审核。",+ "VERSION_ALREADY_SUBMITTED": "该版本已经提审,请更改版本号并安装更新后重新提交审核。",+ "PLUGIN_PENDING_RELEASE_EXISTS": "此插件已有版本正在审核,请先查看或取消该次提审。",+ "CONTRIBUTION_PACKAGE_CHANGED": "本地插件在摘要显示后发生变化,请刷新摘要后重新核对。"+ },+ "installForAccount": "无法找到原来选择的插件安装。请在当前账号下重新选择插件,核对后再提交审核。",+ "releaseSha": "实际版本包 SHA-256",+ "uploadedSha": "本次上传包 SHA-256",+ "publishPlugin": "发布插件",+ "chooseLocal": "选择自己开发的本地插件,核对版本后提交审核。",+ "noLocalPlugins": "还没有已安装插件。请先安装并使用自己开发的插件。",+ "noPublishablePlugins": "没有可发布的已安装插件。请先安装并使用自己开发的插件,并在详情确认安装身份和权限批准状态。",+ "unavailable": {+ "officialGithubRequired": "官方公开插件不支持在客户端提审。请通过 GitHub 仓库提交修改,以保证仓库源码完整,便于后续维护。",+ "reservedId": "此插件使用 Cindy 保留标识,不能在客户端提审。官方公开插件请通过 GitHub 仓库提交修改,以保证源码完整,便于后续维护。",+ "privatePlugin": "此插件来自组织或私域,不能转为社区公开发布。",+ "identityPending": "插件安装身份尚未确认,暂时无法发布。",+ "approvalRequired": "此插件尚未完成权限批准,请先在此详情完成确认。",+ "installationUnavailable": "当前插件安装不可用,请重新打开原插件详情。",+ "sourceUnverified": "无法确认此插件的安装来源。请打开自己开发的本地插件。",+ "publishingPermissionRequired": "当前账号没有此插件的提交权限。"+ },+ "intro": "管理插件的发布、更新与审核状态",+ "pluginColumn": "插件",+ "latestState": "最新情况",+ "version": "版本",+ "chooseVersion": "查看版本",+ "submittedAt": "提审时间",+ "approvedAt": "通过时间",+ "notApproved": "尚未通过",+ "timeUnavailable": "未记录",+ "releaseNotes": "更新说明",+ "versionUpdates": "版本与更新",+ "versionManagement": "版本管理",+ "notesMissing": "此版本未提供更新说明",+ "versionContent": "版本内容",+ "loadMoreVersions": "加载更多版本",+ "notSubmitted": "尚未提审",+ "submitVersion": "提交 {{version}} 审核",+ "publishingVersion": "本次提审 · {{version}}",+ "refreshSummary": "刷新发布摘要",+ "versionConsumedHint": "提审成功受理后,此版本号不能再次使用;取消或退回后也需要更改版本号。",+ "cancelReview": "取消本次提审",+ "cancelReviewTitle": "取消 {{name}} {{version}} 的提审?",+ "cancelReviewDescription": "取消不影响当前上架版本。{{version}} 已经提审,之后必须使用新版本号再提交。",+ "keepReview": "继续审核",+ "cancelledAt": "取消时间",+ "cancelled": "已取消",+ "cancelReviewCompleted": "已取消本次提审。当前上架版本不受影响。",+ "cancelReviewAlreadyFinal": "审核已经完成,本次未取消。下方显示实际审核结果。",+ "viewPendingVersion": "查看正在审核的版本",+ "submitFailed": "提交失败",+ "viewDetails": "查看详情"}},"mcp": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 2aa665cc2d..ff4598be3b 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -6373,6 +6373,9 @@"installAria": "安裝 {{name}}"},"market": {+ "publisherKind": {+ "official": "官方"+ },"scopeAria": "篩選插件來源","scope": {"all": "全部",@@ -7105,6 +7108,204 @@"downloadsValue": "{{value}} 下載","usesValue": "{{value}} 使用","usesExplanation": "目前共享範圍內各版本累計的工具呼叫次數。下方個人呼叫僅統計本機目前帳戶,口徑不同。"+ },+ "contribution": {+ "unreadReview": "有新的審核結果",+ "viewReviewResult": "查看 {{version}} 審核結果",+ "anonymous": "匿名發布",+ "anonymousHint": "隱藏整款插件的公開署名,可隨時修改。關閉後顯示各版本送審時儲存的原作者暱稱。",+ "anonymousAuthorOnly": "僅原作者可修改",+ "anonymousUnavailable": "作者設定暫不可用",+ "anonymousUpdateFailed": "無法確認匿名設定是否已儲存,請重新整理後再試。",+ "myPlugins": "我的插件",+ "publish": "提交審核",+ "submitUpdate": "提交新版本審核",+ "publishHint": "僅限有權發佈的插件,審核通過後在社群上架。",+ "preparing": "正在準備目前安裝的插件…",+ "confirmSubmit": "提交審核",+ "confirmPublic": "目前插件套件及其中的程式碼、宣告的權限將提交人工審核,審核通過後可在社群公開分發。",+ "packageSize": "套件大小:{{size}} 位元組",+ "refreshList": "重新整理列表",+ "refreshDetail": "重新整理詳情",+ "personalRequired": "請切換至個人帳號查看我的插件。",+ "permissionDenied": "目前帳號無權發佈此插件。",+ "notFound": "目前帳號無法查看此插件。",+ "accountChanged": "帳號已切換,請使用目前帳號重新整理。",+ "loadFailed": "暫時無法讀取插件資訊。",+ "offline": "目前離線,請連線後重新整理以查看最新結果。",+ "cachedResult": "目前顯示此帳號上次查詢的結果",+ "lastRefreshed": "上次重新整理:{{time}}",+ "search": "搜尋我的插件",+ "filterLabel": "篩選我的插件",+ "filter": {+ "all": "全部",+ "pending": "待審核",+ "needs_action": "需要處理",+ "published": "已上架"+ },+ "loading": "正在載入…",+ "empty": "還沒有提交過插件。點擊「發佈插件」,選擇自己開發並使用的插件。",+ "noMatches": "沒有符合搜尋或篩選條件的插件。",+ "viewLocal": "查看已安裝插件",+ "currentMarket": "目前上架版本",+ "inUseVersion": "使用中",+ "localVersion": "本機版本",+ "localEnabled": "已啟用",+ "localDisabled": "已停用",+ "submitVersion": "提交 {{version}} 審核",+ "installPublished": "安裝已上架版本",+ "publishedContentUnavailable": "暫時無法讀取目前上架版本的介紹和更新說明。",+ "currentSubmission": "目前提交",+ "localState": {+ "missing": "本機未安裝",+ "unavailable": "暫時無法讀取本機版本"+ },+ "listedVersion": "已上架",+ "pendingVersion": "待審核",+ "notInstalled": "未安裝",+ "versionUnknown": "版本未知",+ "noPendingVersion": "無待審核版本",+ "versionFacts": "版本狀態",+ "publishing": "發佈管理",+ "latestSubmission": "最近提交",+ "noSubmission": "尚無提交",+ "marketVersion": "已上架 · {{version}}",+ "market": {+ "not_listed": "尚未上架",+ "disabled": "已下架",+ "archived": "已封存",+ "release_unavailable": "版本暫時無法使用"+ },+ "review": {+ "pending": "待審核",+ "approved": "審核通過",+ "rejected": "已退回",+ "published": "已上架",+ "superseded": "已由後續提交取代",+ "legacy_unverified": "歷史修訂無法核實",+ "current": "處理結果尚未確認",+ "cancelled": "已取消"+ },+ "reason": "處理原因",+ "submittedContent": "已提交內容",+ "snapshotUnavailable": "原提交內容未留存或已無法核實。",+ "history": "發佈紀錄",+ "loadMore": "載入更多",+ "loadMoreHistory": "載入更多歷史",+ "releaseId": "版本紀錄 ID",+ "revision": "修訂權杖",+ "technicalDetails": "技術詳情",+ "outcome": {+ "submitted_for_review": "已提交審核",+ "metadata_updated": "展示資訊已更新",+ "unchanged": "內容未變,已傳回既有結果"+ },+ "event": {+ "submitted": "已提交",+ "metadata_updated": "展示資訊已更新",+ "approved": "審核通過",+ "rejected": "已退回",+ "enabled": "已上架",+ "disabled": "已下架",+ "current_changed": "市場版本已切換",+ "revoked": "版本已撤銷",+ "cancelled": "已取消"+ },+ "source": {+ "manual": "手動發佈",+ "ai": "AI 協助發佈",+ "github_oidc": "儲存庫發佈",+ "console_upload": "控制台上傳",+ "member_upload": "企業發佈",+ "server_template": "範本發佈",+ "community_upload": "社群發佈",+ "unknown": "既有發佈管道"+ },+ "errors": {+ "CONTRIBUTION_NOT_AUTHORIZED": "沒有此公開插件的提交權限,請聯絡維護者。安裝插件不授予發佈權。",+ "CONTRIBUTION_REVISION_STALE": "目標版本已變更,請重新整理並核對內容後重新準備。",+ "RELEASE_VERSION_CONFLICT": "此版本不能覆寫既有執行內容,請修改插件版本後再提交。",+ "PLUGIN_GHOST_ID_CONFLICT": "此公開插件 ID 已存在,無法透過上傳套件認領。",+ "CONTRIBUTION_OPERATION_NOT_FOUND": "目前帳號無法查看這次提交。",+ "PRECONDITION_FAILED": "目前插件無法提交審核。",+ "PERSONAL_CONTEXT_REQUIRED": "請切換至個人帳號查看我的插件。",+ "ACCOUNT_REAUTH_REQUIRED": "個人帳號登入狀態已失效,請重新登入後再試。",+ "PERMISSION_DENIED": "目前帳號無權發佈此插件。",+ "OWNER_CHANGED": "帳號已切換,請使用目前帳號重新整理。",+ "PLUGIN_NOT_FOUND": "目前帳號無法查看此插件。",+ "CONTRIBUTION_SUBMISSION_NOT_FOUND": "目前帳號無法查看此插件。",+ "NOT_FOUND": "目前帳號無法查看此插件。",+ "INTERNAL": "暫時無法確認提交結果。",+ "MUTATION_CANCELLED": "暫時無法確認提交結果。",+ "CONTRIBUTION_IDEMPOTENCY_CONFLICT": "暫時無法確認提交結果。",+ "PLUGIN_ARCHIVED": "已封存",+ "RELEASE_REVOKED": "版本已撤銷",+ "INVALID_PARAMS": "暫時無法確認提交結果。",+ "PAYLOAD_TOO_LARGE": "暫時無法確認提交結果。",+ "RATE_LIMITED": "暫時無法確認提交結果。",+ "JWKS_UNAVAILABLE": "暫時無法確認提交結果。",+ "STORAGE_UNAVAILABLE": "暫時無法確認提交結果。",+ "PLUGIN_REPLICAS_NOT_READY": "暫時無法確認提交結果。",+ "UPLOAD_OBJECT_MISSING": "暫時無法確認提交結果。",+ "UPLOAD_SIZE_MISMATCH": "暫時無法確認提交結果。",+ "UPLOAD_SHA256_MISMATCH": "暫時無法確認提交結果。",+ "PLUGIN_PACKAGE_INVALID": "暫時無法確認提交結果。",+ "CONTRIBUTION_TARGET_MISMATCH": "暫時無法確認提交結果。",+ "PUBLISH_STORAGE_UNAVAILABLE": "暫時無法確認提交結果。",+ "PUBLISH_INTERNAL_ERROR": "暫時無法確認提交結果。",+ "RELEASE_NOTES_REQUIRED": "尚未送審:請在插件原始碼的 ghost.json.releaseNotes 中補齊更新說明,安裝更新後重新提交審核。",+ "VERSION_ALREADY_SUBMITTED": "此版本已經送審,請更改版本號並安裝更新後重新提交審核。",+ "PLUGIN_PENDING_RELEASE_EXISTS": "此插件已有版本正在審核,請先查看或取消該次審核。",+ "CONTRIBUTION_PACKAGE_CHANGED": "本機插件在摘要顯示後發生變更,請重新整理摘要後核對。"+ },+ "installForAccount": "找不到原先選取的插件安裝。請在目前帳號下重新選取插件,確認後再提交審核。",+ "releaseSha": "實際版本套件 SHA-256",+ "uploadedSha": "本次上傳套件 SHA-256",+ "publishPlugin": "發佈插件",+ "chooseLocal": "選擇自己開發的本機插件,核對版本後提交審核。",+ "noLocalPlugins": "還沒有已安裝插件。請先安裝並使用自己開發的插件。",+ "noPublishablePlugins": "沒有可發佈的已安裝插件。請先安裝並使用自己開發的插件,並在詳情確認安裝身分和權限核准狀態。",+ "unavailable": {+ "officialGithubRequired": "官方公開插件不支援在用戶端提交審核。請透過 GitHub 儲存庫提交修改,以確保儲存庫原始碼完整,便於後續維護。",+ "reservedId": "此插件使用 Cindy 保留識別碼,不能在用戶端提交審核。官方公開插件請透過 GitHub 儲存庫提交修改,以確保原始碼完整,便於後續維護。",+ "privatePlugin": "此插件來自組織或私域,不能轉為社群公開發佈。",+ "identityPending": "插件安裝身分尚未確認,暫時無法發佈。",+ "approvalRequired": "此插件尚未完成權限核准,請先在此詳情完成確認。",+ "installationUnavailable": "目前的插件安裝無法使用,請重新開啟原插件詳情。",+ "sourceUnverified": "無法確認此插件的安裝來源。請開啟自己開發的本機插件。",+ "publishingPermissionRequired": "目前帳號沒有此插件的提交權限。"+ },+ "intro": "管理插件的發布、更新與審核狀態",+ "pluginColumn": "插件",+ "latestState": "最新狀態",+ "version": "版本",+ "chooseVersion": "查看版本",+ "submittedAt": "送審時間",+ "approvedAt": "通過時間",+ "notApproved": "尚未通過",+ "timeUnavailable": "未記錄",+ "releaseNotes": "更新說明",+ "versionUpdates": "版本與更新",+ "versionManagement": "版本管理",+ "notesMissing": "此版本未提供更新說明",+ "versionContent": "版本內容",+ "loadMoreVersions": "載入更多版本",+ "notSubmitted": "尚未送審",+ "submitVersion": "提交 {{version}} 審核",+ "publishingVersion": "本次送審 · {{version}}",+ "refreshSummary": "重新整理發布摘要",+ "versionConsumedHint": "送審成功受理後,此版本號無法再次使用;取消或退回後也需要更改版本號。",+ "cancelReview": "取消本次審核",+ "cancelReviewTitle": "取消 {{name}} {{version}} 的審核?",+ "cancelReviewDescription": "取消不影響目前上架版本。{{version}} 已經提交審核,之後必須使用新版本號再提交。",+ "keepReview": "繼續審核",+ "cancelledAt": "取消時間",+ "cancelled": "已取消",+ "cancelReviewCompleted": "已取消本次審核。目前上架版本不受影響。",+ "cancelReviewAlreadyFinal": "審核已經完成,本次未取消。下方顯示實際審核結果。",+ "viewPendingVersion": "查看正在審核的版本",+ "submitFailed": "提交失敗",+ "viewDetails": "查看詳情"}},"mcp": {diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 9aef9f4fd1..f93140472f 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1683,6 +1683,7 @@ interface ElectronAPI {refreshSource: (name: string) => Promise<import('../shared/pluginMarket').MarketSourceSummary>;gitPreflight: () => Promise<{ ok: boolean; version: string | null }>;};+ pluginContributions: import('../shared/pluginContributions').PluginContributionsApi;pluginPublisher: {start: (filePath: string) => Promise<{ transferId: string; uploadId: string | null }>;status: (transferId: string) => Promise<{ progress: unknown }>;diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex dc093ae33e..8edf8fc7ca 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -1432,6 +1432,8 @@ export interface GhostManifest {name: string;/** 版本字符串(不强制 semver,仅展示用)。 */version: string;+ /** 包内本版本完整更新说明;旧包可省略。 */+ releaseNotes?: string;/** 安装此 Release 所需的最低 Cindy 客户端 SemVer;缺省表示不限制。 */minCindyVersion?: string;/** 作者展示名(仅展示用)。 */@@ -1642,6 +1644,11 @@ export function isGhostInstallApprovalToken(value: unknown): value is string {/** 已装入主机的插件(批准清单 + 安装位置 + 启用态)。 */export interface InstalledGhost {+ /** Read-only Host provenance, not authorship or publication permission. Missing is unknown. */+ publishingSource?:+ | { kind: 'local'; source: 'manual' | 'agent-forge' }+ | { kind: 'public-market'; pluginId: string }+ | { kind: 'unavailable' };/** Host retirement projection; never supplied by plugin authors. */retirement?: import('./featureRetirements').InstalledFeatureRetirement;/** Host receipt fact, not a manifest declaration. Missing means tasks need confirmation. */@@ -2991,6 +2998,7 @@ const GHOST_MANIFEST_KNOWN_TOP_LEVEL_FIELDS = new Set(['id','name','version',+ 'releaseNotes','minCindyVersion','author','locales',@@ -3862,6 +3870,9 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: boo) {return { ok: false, reason: 'version 必须是 1–32 字符的非空字符串' };}+ if (raw.releaseNotes !== undefined && typeof raw.releaseNotes !== 'string') {+ return { ok: false, reason: 'releaseNotes 必须是纯文本字符串' };+ }if (raw.minCindyVersion !== undefined && !isValidCindyVersion(raw.minCindyVersion)) {return { ok: false, reason: 'minCindyVersion 必须是合法的 SemVer 字符串' };}@@ -6058,6 +6069,7 @@ function validateGhostManifestInput(value: unknown, preserveHistoricalTasks: booid: raw.id,name: raw.name,version: raw.version,+ ...(raw.releaseNotes !== undefined ? { releaseNotes: raw.releaseNotes as string } : {}),...(raw.minCindyVersion !== undefined? { minCindyVersion: raw.minCindyVersion as string }: {}),diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.tsindex b16cea656c..790cf8f77f 100644--- a/apps/desktop/src/shared/ipc-errors.ts+++ b/apps/desktop/src/shared/ipc-errors.ts@@ -1,3 +1,4 @@+import { CONTRIBUTION_ERROR_CODES } from './pluginContributionContract';import type { BrowserOpenForLoginErrorCode } from './browserBackend';/** main / preload / renderer 共用的 IPC 错误类型。 */@@ -70,6 +71,7 @@ export const COMPANION_IMPORT_ERROR_CODES = [] as const;export type IpcErrorCode =+ | (typeof CONTRIBUTION_ERROR_CODES)[number]| (typeof COMPANION_IMPORT_ERROR_CODES)[number]// 通用错误| 'INVALID_PARAMS'@@ -77,6 +79,7 @@ export type IpcErrorCode =| 'INTERNAL'| 'ALREADY_EXISTS'| 'PRECONDITION_FAILED'+ | 'OFFICIAL_PLUGIN_GITHUB_REQUIRED' // 客户端提审限制,不扩展服务端 wire 错误| 'PROVIDER_GROUP_CHANGED' // 编辑期间组设置已变化,拒绝覆盖,需重新读取| 'HTML_PREVIEW_TOO_LARGE'| 'HTML_PREVIEW_UNSUPPORTED'@@ -332,12 +335,14 @@ export interface IpcError {const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>([...COMPANION_IMPORT_ERROR_CODES,+ ...CONTRIBUTION_ERROR_CODES,'INVALID_PARAMS','NOT_FOUND','INTERNAL','ALREADY_EXISTS','IDENTITY_CONFLICT','PRECONDITION_FAILED',+ 'OFFICIAL_PLUGIN_GITHUB_REQUIRED','PROVIDER_GROUP_CHANGED','HTML_PREVIEW_TOO_LARGE','HTML_PREVIEW_UNSUPPORTED',diff --git a/apps/desktop/src/shared/pluginContributionContract.ts b/apps/desktop/src/shared/pluginContributionContract.tsnew file mode 100644index 0000000000..1d1d23f9fe--- /dev/null+++ b/apps/desktop/src/shared/pluginContributionContract.ts@@ -0,0 +1,254 @@+/** Personal contribution wire contract. Keep equivalent to docs/plugin-community-contribution-contract.md. */+import { z } from 'zod';++const id = z.string().min(1).max(256);+const date = z.string().datetime();+const sha = z.string().regex(/^[a-f0-9]{64}$/);+export const contributionSubject = z.object({ authority: z.string().url(), membershipId: id });+export const releaseRevision = z.object({ releaseId: id, sha256: sha, displayUpdatedAt: date });+export const contributionRequest = z+ .object({+ sizeBytes: z.number().int().positive().max(134217728),+ sha256: sha,+ source: z.enum(['manual', 'ai']),+ target: z+ .object({+ pluginId: id.nullable(),+ ghostId: id,+ version: z.string().min(1).max(32),+ expectedRelease: releaseRevision.nullable(),+ })+ .strict(),+ })+ .strict();+const review = z.enum(['pending', 'approved', 'rejected', 'cancelled']);+const icon = z+ .object({+ mimeType: z.string(),+ sha256: sha,+ sizeBytes: z.number(),+ url: z.string().url(),+ expiresAt: date,+ })+ .nullable();+export const submissionView = z.object({+ submissionId: id.nullable(),+ releaseId: id,+ version: z.string(),+ submittedAt: date.nullable(),+ approvedAt: date.nullable().optional(),+ cancelledAt: date.nullable().optional(),+ actions: z.object({ canCancelReview: z.boolean() }).optional(),+ publishSource: z.enum([+ 'community_upload',+ 'github_oidc',+ 'console_upload',+ 'member_upload',+ 'server_template',+ ]),+ source: z.enum(['manual', 'ai']).nullable(),+ revision: releaseRevision,+ revisionState: z.enum(['current', 'superseded', 'legacy_unverified']),+ reviewStatus: review.nullable(),+ decidedAt: date.nullable(),+ reason: z.string().nullable(),+});+export const contributionReceipt = z.object({+ submissionId: id,+ operationId: id,+ pluginId: id,+ releaseId: id,+ ghostId: id,+ version: z.string(),+ source: z.enum(['manual', 'ai']),+ submittedAt: date,+ uploadedPackage: z.object({ sha256: sha, sizeBytes: z.number().int().positive() }),+ releaseRevision,+ outcome: z.enum(['submitted_for_review', 'metadata_updated', 'unchanged']),+});+export const operationStatus = z.enum([+ 'awaiting_upload',+ 'validating',+ 'publishing',+ 'succeeded',+ 'failed',+ 'expired',+]);+export const contributionOperation = z+ .object({+ subject: contributionSubject,+ operationId: id,+ status: operationStatus,+ createdAt: date,+ updatedAt: date,+ expiresAt: date,+ receipt: contributionReceipt.nullable(),+ submission: submissionView.nullable(),+ failure: z.object({ code: z.string(), message: z.string() }).nullable(),+ })+ .superRefine((value, ctx) => {+ if (+ (value.status === 'succeeded' && (!value.receipt || !value.submission)) ||+ (value.status === 'failed' && !value.failure) ||+ (value.status !== 'failed' && value.failure !== null) ||+ (value.receipt && value.receipt.operationId !== value.operationId)+ ) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Inconsistent contribution operation' });+ }+ });+export const preparedResponse = z.object({+ subject: contributionSubject,+ operationId: id,+ status: operationStatus,+ createdAt: date,+ updatedAt: date,+ expiresAt: date,+ receipt: contributionReceipt.nullable(),+ submission: submissionView.nullable(),+ failure: z.object({ code: z.string(), message: z.string() }).nullable(),+ upload: z+ .object({+ putUrl: z.string().url(),+ headers: z.record(z.string(), z.string()),+ expiresAt: date,+ })+ .nullable(),+});+export const commitResponse = z.object({+ subject: contributionSubject,+ operationId: id,+ status: operationStatus,+});+const content = z.object({+ manifest: z+ .object({ id, name: z.string(), description: z.string().optional(), version: z.string() })+ .passthrough(),+ manifestView: z.record(z.string(), z.unknown()),+ icon,+});+export const myPluginSummary = z.object({+ pluginId: id,+ ghostId: id,+ scope: z.literal('public'),+ namespace: z.string().nullable(),+ name: z.string(),+ displayAuthor: z.string().max(100).nullable().optional(),+ authorSettings: z.object({ anonymous: z.boolean(), canEdit: z.boolean() }).nullable().optional(),+ publisherKind: z.enum(['official', 'personal']).nullable().optional(),+ description: z.string().nullable(),+ icon,+ market: z.object({+ pluginStatus: z.enum(['active', 'disabled', 'archived']),+ currentRelease: z+ .object({+ releaseId: id,+ version: z.string(),+ sha256: sha,+ reviewStatus: review,+ revokedAt: date.nullable(),+ })+ .nullable(),+ available: z.boolean(),+ unavailableReason: z+ .enum(['not_listed', 'disabled', 'archived', 'release_unavailable'])+ .nullable(),+ }),+ latestSubmission: submissionView.nullable(),+ updatedAt: date,+ actions: z.object({ canSubmit: z.boolean(), canViewMarket: z.boolean() }),+});+export const authorHistoryEvent = z.object({+ eventId: id,+ type: z.enum([+ 'submitted',+ 'metadata_updated',+ 'approved',+ 'rejected',+ 'cancelled',+ 'enabled',+ 'disabled',+ 'current_changed',+ 'revoked',+ ]),+ at: date,+ releaseId: id.nullable(),+ version: z.string().nullable(),+ submissionId: id.nullable(),+ revision: releaseRevision.nullable(),+ reason: z.string().nullable(),+});+const envelope = z.object({ subject: contributionSubject, queriedAt: date });+export const contributionPreflight = envelope.extend({+ policyVersion: z.literal(2),+ target: z.object({+ pluginId: id.nullable(),+ ghostId: id,+ version: z.string(),+ expectedRelease: releaseRevision.nullable(),+ }),+ pendingRelease: z.object({ releaseId: id, version: z.string() }).nullable(),+ blockers: z.array(z.object({ code: z.string(), message: z.string() })),+ actions: z.object({ canSubmit: z.boolean() }),+});+export const cancelledReview = envelope.extend({ pluginId: id, submission: submissionView });+export type ContributionPreflight = z.infer<typeof contributionPreflight>;+export const myPluginList = envelope.extend({+ plugins: z.array(myPluginSummary),+ nextCursor: z.string().nullable(),+});+export const myPluginDetail = envelope.extend({+ plugin: myPluginSummary,+ latestSubmissionContent: content.nullable(),+ history: z.object({ events: z.array(authorHistoryEvent), nextCursor: z.string().nullable() }),+});+export const myPluginHistory = envelope.extend({+ events: z.array(authorHistoryEvent),+ nextCursor: z.string().nullable(),+});+export const myPluginReleases = envelope.extend({+ releases: z.array(submissionView),+ nextCursor: z.string().nullable(),+});+export const mySubmissionDetail = envelope.extend({+ receipt: contributionReceipt,+ submission: submissionView,+ content: content.nullable(),+});+export type ContributionSubject = z.infer<typeof contributionSubject>;+export type ContributionRequest = z.infer<typeof contributionRequest>;+export type ContributionOperation = z.infer<typeof contributionOperation>;+export type SubmissionView = z.infer<typeof submissionView>;+export type SubmissionContent = z.infer<typeof content>;+export type AuthorHistoryEvent = z.infer<typeof authorHistoryEvent>;+export type MyPluginSummary = z.infer<typeof myPluginSummary>;++export const CONTRIBUTION_ERROR_CODES = [+ 'RELEASE_NOTES_REQUIRED',+ 'VERSION_ALREADY_SUBMITTED',+ 'PLUGIN_PENDING_RELEASE_EXISTS',+ 'CONTRIBUTION_PACKAGE_CHANGED',++ 'PERSONAL_CONTEXT_REQUIRED',+ 'CONTRIBUTION_NOT_AUTHORIZED',+ 'CONTRIBUTION_OPERATION_NOT_FOUND',+ 'PLUGIN_NOT_FOUND',+ 'CONTRIBUTION_SUBMISSION_NOT_FOUND',+ 'CONTRIBUTION_IDEMPOTENCY_CONFLICT',+ 'CONTRIBUTION_REVISION_STALE',+ 'PLUGIN_GHOST_ID_CONFLICT',+ 'RELEASE_VERSION_CONFLICT',+ 'PLUGIN_ARCHIVED',+ 'RELEASE_REVOKED',+ 'PAYLOAD_TOO_LARGE',+ 'RATE_LIMITED',+ 'JWKS_UNAVAILABLE',+ 'STORAGE_UNAVAILABLE',+ 'PLUGIN_REPLICAS_NOT_READY',+ 'UPLOAD_OBJECT_MISSING',+ 'UPLOAD_SIZE_MISMATCH',+ 'UPLOAD_SHA256_MISMATCH',+ 'PLUGIN_PACKAGE_INVALID',+ 'CONTRIBUTION_TARGET_MISMATCH',+ 'PUBLISH_STORAGE_UNAVAILABLE',+ 'PUBLISH_INTERNAL_ERROR',+] as const;diff --git a/apps/desktop/src/shared/pluginContributions.ts b/apps/desktop/src/shared/pluginContributions.tsnew file mode 100644index 0000000000..cbd2c9c929--- /dev/null+++ b/apps/desktop/src/shared/pluginContributions.ts@@ -0,0 +1,140 @@+import type { GhostPermissionItem } from './ghost';+import type { AuthorHistoryEvent, ContributionOperation } from './pluginContributionContract';+/** Personal contribution operations share the exact installed-package snapshot across UI and AI. */+/** Compared against Main's installation; never used to resolve a filesystem path. */+export interface ContributionInstallationBinding {+ directory: string;+ approvalToken: string;+}+export interface PreparedPluginContribution {+ preparedId: string;+ instanceId: string;+ pluginId: string | null;+ ghostId: string;+ name: string;+ description: string;+ version: string;+ sha256: string;+ sizeBytes: number;+ releaseNotes?: string;+ preflight?: import('./pluginContributionContract').ContributionPreflight;+ expiresAt: string;+}++/** UI projection only. Review and market facts always come from one server read. */+export type MyPluginFilter = 'all' | 'pending' | 'needs_action' | 'published';+export interface ContributionReleaseView {+ releaseId: string;+ version: string;+ sha256: string;+ revision: string;+ uploadedSha256?: string;+ uploadedSizeBytes?: number;+ reviewStatus: 'pending' | 'approved' | 'rejected' | 'cancelled' | null;+ revisionState: 'current' | 'superseded' | 'legacy_unverified';+ submissionId: string | null;+ submittedAt: string | null;+ approvedAt?: string | null;+ cancelledAt?: string | null;+ canCancelReview?: boolean;+ reviewedAt: string | null;+ reason: string | null;+ source: string | null;+ /** Absent historical bytes must never be filled from today's Release metadata. */+ content: {+ name: string;+ description: string;+ iconUrl: string | null;+ permissions: GhostPermissionItem[];+ manifestView: Record<string, unknown>;+ } | null;+}+export type MyPluginLocalInstallation =+ | { state: 'installed'; instanceId: string; version: string; origin: 'local' | 'public'; enabled: boolean }+ | { state: 'missing' | 'unavailable' };+export interface MyPluginView {+ pluginId: string;+ name: string;+ displayAuthor?: string | null;+ authorSettings?: { anonymous: boolean; canEdit: boolean } | null;+ publisherKind?: 'official' | 'personal' | null;+ iconUrl: string | null;+ updatedAt: string;+ market: {+ state: 'available' | 'not_listed' | 'disabled' | 'archived' | 'release_unavailable';+ version: string | null;+ releaseId: string | null;+ reason: string | null;+ };+ latestSubmission: ContributionReleaseView | null;+ actions: { submitUpdate: boolean; viewMarket: boolean };+ /** Main-owned installation match by namespace and plugin ID. */+ localInstanceId: string | null;+ localVersion?: string | null;+ /** Missing on older readers; absence must not be interpreted as not installed. */+ localInstallation?: MyPluginLocalInstallation;+}+export interface MyPluginPageView {+ plugins: MyPluginView[];+ nextCursor: string | null;+ queriedAt: string;+}+export interface MyPluginDetailView {+ plugin: MyPluginView;+ history: AuthorHistoryEvent[];+ nextCursor: string | null;+ queriedAt: string;+}++export interface MyPluginReleasePageView {+ releases: ContributionReleaseView[];+ nextCursor: string | null;+ queriedAt: string;+}++export interface ContributionTransferView {+ localId: string;+ prepared: PreparedPluginContribution;+ stage: 'prepared' | 'uploading' | 'processing' | 'paused' | 'complete';+ operation: ContributionOperation | null;+ errorCode: string | null;+}+/** A server-recorded decision; unread is only this account's local reading state. */+export interface PluginReviewUpdate {+ pluginId: string;+ key: string;+ releaseId: string;+ version: string;+ sha256: string;+ revision: string;+ status: 'approved' | 'rejected';+ decidedAt: string;+ unread: boolean;+}+export interface PluginContributionsApi {+ reviewUpdates(): Promise<PluginReviewUpdate[]>;+ markReviewRead(pluginId: string, key: string): Promise<void>;+ prepare(+ instanceId: string,+ expected?: ContributionInstallationBinding,+ ): Promise<PreparedPluginContribution>;+ submit(preparedId: string): Promise<ContributionTransferView>;+ resume(localId: string): Promise<ContributionTransferView>;+ transfers(): Promise<ContributionTransferView[]>;+ status(localId: string): Promise<ContributionTransferView>;+ cancel(localId: string): Promise<void>;+ cancelReview(+ pluginId: string,+ release: { releaseId: string; sha256: string; revision: string },+ ): Promise<ContributionReleaseView>;+ discard(preparedId: string): Promise<void>;+ list(input: {+ query: string;+ filter: MyPluginFilter;+ cursor?: string;+ }): Promise<MyPluginPageView>;+ submission(pluginId: string, submissionId: string): Promise<ContributionReleaseView>;+ releases(pluginId: string, cursor?: string): Promise<MyPluginReleasePageView>;+ detail(pluginId: string, cursor?: string): Promise<MyPluginDetailView>;+ setAnonymity(pluginId: string, anonymous: boolean): Promise<MyPluginDetailView>;+}diff --git a/apps/desktop/src/shared/pluginMarket.ts b/apps/desktop/src/shared/pluginMarket.tsindex 08dfa7f963..f9c498d9ab 100644--- a/apps/desktop/src/shared/pluginMarket.ts+++ b/apps/desktop/src/shared/pluginMarket.ts@@ -22,6 +22,10 @@ export interface PluginMarketItem {name: string;description: string | null;author: string | null;+ /** Display identity from verified public publishing; never grants runtime trust. */+ publisherKind?: 'official' | 'personal' | null;+ /** Main verified a public installation's market origin; attribution spans versions. */+ installedAuthor?: string | null;scope: PluginMarketScope;organizationId: string | null;defaultInstall: boolean;diff --git a/docs/dev-rules/desktop-development.md b/docs/dev-rules/desktop-development.mdindex 5b47500b89..10d0516b31 100644--- a/docs/dev-rules/desktop-development.md+++ b/docs/dev-rules/desktop-development.md@@ -51,6 +51,10 @@ Agent 没有 TTY 时,dev 会在新开的 Terminal(macOS)/cmd(Windows只保留前 8MB,足够覆盖启动过程;之后的运行日志看按天轮转的 `main-*.log`),窗口关掉后仍可查;启动失败时命令会直接打印日志末尾,verdict 带 `log=` 指向该文件。排查启动失败先读这份日志,不要靠反复重启猜原因。+停止旧实例后的 macOS Terminal 标签页清理,只访问已经运行的 Terminal,并按旧实例的精确+TTY 匹配标签页;Terminal 未运行时直接跳过,不能因清理 iTerm 等终端的 TTY 而将它启动。+实现与回归见 `scripts/restart-desktop-remote.mjs` 和 `scripts/__tests__/restart-desktop-remote.test.mjs`。+Desktop 连接的是你自己的 Cindy 云端账号(remote)。这与登录页中免 Cindy 账号的「跳过登录」(应用内显示为「未登录」,无需账号即可使用本机 agent;代码内部标识仍为`local` mode)不是同一个概念。Agent 不得自行改用diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.mdindex 8191871d4b..f000d19ab0 100644--- a/docs/dev-rules/plugin-security-and-authoring.md+++ b/docs/dev-rules/plugin-security-and-authoring.md@@ -851,3 +851,18 @@ visible 复用当前账号模型选择器的用户开关与目录默认值;隐不向插件提供设备私钥、账号 token 或其他插件数据,不为通道增加远程 Renderer IPC。接口和失败语义见 `FORGE_GUIDE` §4.10.2,协议与兼容边界见[协议兼容](protocol-compatibility.md#插件资料设备同步)。++## 社区插件贡献入口++个人作者可从来源可核实且已批准的本地 root 插件详情提交审核;已有公开插件的后续版本通过“我的插件”管理页提交,并核对当前提交授权。安装或运行批准本身不授予发布权。Host 复用导出快照原语和现有包自检,+不弹保存/选文件框,不接受任意路径或独立资料。准备绑定原物理实例、安装目录、批准版本与账号;+登录意图也须核对这些证据,不按同 ID 替换为另一个账号安装。私域 ledger 关联不可转 public;+合法 public Broker 声明仍由服务端既有 public 规则与精确 ACL 判断,不靠声明直接拒绝。++个人工具与旧企业 Forge 发布是独立能力入口。任务权限只决定是否可以执行公开写入,不决定+public 身份归属;共享访客及插件托管/errand 任务与其 Worker 沿既有 restricted helper surface,+不能借用 Host 个人发布能力。普通个人用户任务和正常 Worker 不因此被封禁。++详见 [客户端实现与验证边界](../plugin-community-contribution.md) 和+[HTTP 契约](../plugin-community-contribution-contract.md)。此改动涉及打包原语和授权边界,仍须人工 review+及本规则第 5 节的插件基座白名单确认后方可合并;本地代码检查不替代该门禁。diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex dad74e2f68..edb1e39dc9 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -2915,3 +2915,33 @@ namespace + id 下同一插件的有界 JSON 请求;`deviceSync: true` 是独旧端没有该确认或未收到释放回执时保留原过期清理,不把旧端的普通验证成功当作释放成功。断线、撤销、账号切换或重启后无法复核时不投递,不自动重放;已送达历史保留。未知投递结果仍要求先读取目标核实。没有新 relay channel、服务端变更、数据库 migration 或 Mobile 原生指纹变化。++## 普通个人的社区插件贡献++已安装清单可选追加只读 `publishingSource`,由 Host 既有实例记录、批准回执与安装台账重建。+它仅用于个人提审入口的来源准入,不改变列表的来源展示、安装来源、自动更新或发布权限。+缺失或无法核实来源时不开放提审;本地安装和公开安装都不会因提审或过审自动转换来源,不新增持久化关联记录。++新增独立 `/api/plugin-contributions` 和精确 `plugin-contributions:*` IPC,不改企业发布、+旧公开市场 DTO 或 device-link allowlist。两仓分别维护等价+[HTTP / DTO 契约](../plugin-community-contribution-contract.md)。客户端使用当前个人 Access Token,+以可信 auth discovery 的 issuer 与 token sub 核对所有作者响应主体;`cn/global` 只用于选择 Host 配置,+不能当作 issuer。服务器仍做验签和 public 提交 ACL,包内作者声明不授予提交权。++prepare / PUT / commit 复用同一固定包和持久幂等键;202 仅表示处理。结果不明先查原操作;+不换包、不换键自动新建发布操作。receipt 的 uploadedPackage SHA 与实际 releaseRevision SHA 分开,+`outcome`、修订审核与市场 `available` 分开。处理历史以独立 eventId 分页,旧修订不套用当前修订结果。+Host 持久操作按账号隔离、异步结果按 owner generation 拦截;审核结果通过用户打开、刷新、前台恢复及前台定时读取同步。+本地 `review-updates` / `mark-review-read` IPC 仅供可信桌面 Renderer,不加入 device-link 白名单。+提示点复用现有作者列表和精确修订的审核记录,Main 只额外保存按账号隔离的本机已读标记;+不新增服务端通知/已读 API,不改变审核事实,不因列表查询或 AI 查询而清除提示。+旧服务器未实现接口时如实显示读取/发布失败,不试探企业或 Platform 身份,也不伪造空列表或成功。+存量插件安装、批准记录、启用状态、包格式和市场来源枚举均保持原契约;本能力需要两端更新。++## 社区版本提审 v2(2026-10-16)++manifest 可选字符串 `releaseNotes`;旧包缺字段仍可安装。首次上架可不填写,曾上架插件的后续提审须提供完整非空更新说明。+个人只读 preflight 查询版本、待审与提交权限;SubmissionView 追加真实时间及允许取消动作。+审核状态增加 cancelled;Main/preload 新增精确 cancelReview,AI 对应 ghost_cancel_plugin_review。+旧 journal 字段可选只为读取/原操作恢复,不允许新客户端静默绕过新版预检。+个人投稿复用原审核请求及上架流程,不增加启用开关、审核令牌或历史比较包门槛。取消仅针对本人仍有提交授权的精确待审修订,已通过或驳回时按真实状态返回。diff --git a/docs/plugin-community-contribution-contract.md b/docs/plugin-community-contribution-contract.mdnew file mode 100644index 0000000000..80875fe22b--- /dev/null+++ b/docs/plugin-community-contribution-contract.md@@ -0,0 +1,170 @@+# 个人社区插件发布 HTTP / DTO 契约++2026-10-16,v2。两仓逐字共享,产品流程见共享方案 `plugin_community_contribution.md`。+实现不等于生产部署;本地验证与上线前提分别见两服务文档。++## 1. 身份与包++普通接口前缀 `/api/plugin-contributions`,沿 Host 当前配置的 Plugin Server。+使用普通 Auth Access Token,经 `requireAuth` 验签,必须 `ctx=personal`。+主体为可信 issuer authority + membershipId;请求体、包内 author、版本或本地安装均不是授权证据。+不接受企业 JWT、GitHub OIDC 或 Platform token,不增加 scope,也不回退鉴权。+所有本人响应回显 `subject:{authority,membershipId}`;Host 在返回前核对 owner 和主体。+AI 不接触 Bearer、PUT URL 或原包路径。++运行批准和安装来源只代表本机使用事实,不证明作者身份,也不授予发布权。Host 核对可信安装来源;普通市场安装不能自动作为本人开发的新插件首发。已有 public 插件始终要求当前个人主体的精确提交授权。新标识受理是等待人工审核的发布申请,首发事务建立的初始提交权和固定作者关系不表示平台已认证代码作者;服务端不接受客户端自报来源或作者字段代替这些校验。++`ghost.json.releaseNotes` 是可选字符串,缺此字段仍可安装。首次上架不要求更新说明,+插件用途写在 `description`;从未上架的插件在退回或取消后再提审也不要求更新说明。+曾上架后再提审须填写非空说明,完整覆盖相对上一已上架版本的变化;下架不免除此要求。+服务端依据现有 `listedAt` 记录判断,并在提交事务中复核。+不增加作者表单、版本基准字段、翻译资料或独立上传文件选择。+服务器验证字段和精确包,人工判断说明完整性,校验不执行插件代码。++### 发布署名与匿名设置(2026-10-19)++本节仅适用于 `scope=public` 的官方插件和个人社区插件。两类同属 public,`publisherKind:official|personal|null` 由固定的 `PluginAuthorship.kind` 派生;个人昵称为 Cindy 也不会成为官方。组织插件沿用原发布、署名、搜索和交付规则。++- 官方来源继续通过 GitHub Actions OIDC、精确官方仓库名与不变 repository_id 校验,固定署名 Cindy,不能通过个人匿名设置隐藏或变更官方身份。+- 个人首发在同一事务绑定已验证的 authority + membershipId;作者归属不随后续提交授权变更。预检或仅上传不占用归属。+- 原作者提审时,Plugin 使用该请求的用户 Token 调用原 Auth `GET /api/me`,核对返回的个人 Membership 与提交身份一致,将昵称保存至已有 `PluginRelease.displayAuthor` 和该次回执的 `manifestView.author`。只读本人资料,Token 不持久化,不新增 Auth 作者 API、公开作者映射或机器凭证。+- 改名不会自动同步旧版本;原作者下次提审保存新的昵称。其他维护者提审沿用已保存的原作者署名,不能改成维护者本人名字。历史版本按各自提审快照展示,不用当前版本的名字覆盖。+- 作者搜索匹配当前客户端最终交付版本的提审昵称,并应用当前插件匿名设置;兼容回退到旧版本时,不借用新版昵称命中。本人的列表和详情标题区按本次可见版本内容展示名称、说明和署名;同一作者改名后提审新版时,不能由已上架旧版昵称覆盖新版内容的署名。+- 个人插件的 `PluginAuthorship.anonymous` 默认 true,由固定原作者随时修改;与昵称快照分别控制。匿名时公开列表、详情、旧协议 author 和嵌套展示 manifest 不返回名字,作者搜索也不能通过隐藏昵称命中。关闭匿名后显示相应版本保存的昵称。切换不消耗版本、无需重审、不改变包 SHA、当前上架版或审核修订。+- `PATCH /api/plugin-contributions/plugins/:pluginId/author-settings` 只接受 `{anonymous:boolean}`,使用原个人鉴权、写限流与固定作者归属校验;提交 ACL 不授予此权限;原作者被撤销提交权后仍可修改匿名设置,但不会因此恢复发布权。返回最新的作者详情。详情中的可选 `authorSettings:{anonymous,canEdit}|null` 只服务于原作者设置界面,不接受客户端指定作者、Auth 来源或昵称。+- 市场读取仅访问 Plugin 自有数据库,不依赖 Auth 在线或个人会话。原始下载包保持不变;匿名控制服务端分发的展示署名,不清除开发者自行写入代码、文档或包内容的个人信息。++昵称最多100字符。可选 `displayAuthor:string|null` 的显式 null 不回退包内作者;旧协议 `author` 与嵌套展示 manifest.author 在64字符以内保持相同,长昵称分别 null / 缺失,不截断。Host 的 installedAuthor 继续要求来源、已批准 SHA 和账本一致,只更新署名投影。++保留已应用的 `20261019010000_plugin_authorship`,通过增量 `20261019020000_plugin_author_privacy` 将不再使用的 publicAuthorId 替换为一个默认匿名布尔值;官方已有关系设为非匿名。昵称使用已有列,不新增姓名表;移除本轮未交付的 Auth 公开作者草稿。用户确认无历史个人社区插件,本轮无个人作者回填;本地已应用的旧迁移不改校验和,不清库。部署前仍需完成迁移与鉴权边界的人工 review,未自动部署。++## 2. 预检与提审++`GET /preflight?ghostId=&version=&pluginId=&hasReleaseNotes=true|false`:pluginId 可省略;hasReleaseNotes 只说明当前包是否含非空更新说明,未提供视为 false。仅只读,不建 operation、授权、票据或版本。+仅当插件曾上架且当前包缺说明时返回 `RELEASE_NOTES_REQUIRED`;客户端声明不代替提交时对实际包的校验。+返回如下字段(UTC ISO 毫秒时间;SHA 为64位小写十六进制):++```ts+type Subject = { authority: string; membershipId: string };+type Revision = { releaseId: string; sha256: string; displayUpdatedAt: string };+type Preflight = {+ subject: Subject; queriedAt: string; policyVersion: 2;+ target: { pluginId: string | null; ghostId: string; version: string; expectedRelease: Revision | null };+ pendingRelease: { releaseId: string; version: string } | null;+ blockers: Array<{ code: string; message: string }>;+ actions: { canSubmit: boolean };+};+```++现有目标只通过本人精确 ACL / 已核实 legacy alias 解析。新身份遇到同名冲突不会自动认领。+预检验证远端已用版本、实际待审和当前提交权限;Host 另核对本地说明及快照。+符合来源条件且具有发布资格的本地详情展示实际版本与完整说明,明确“成功提审后版本不可复用”;普通市场安装者不进入发布准备流程。+直接点击版本提审即公开提交,无第二份资料表单或预览确认;UI / AI 共用 Host。+提交前再次核对当前安装内容、批准及 owner,变化时停止并要求刷新。++`POST /prepare`,`Idempotency-Key` 为 UUID。严格请求:++```ts+type Prepare = {+ sizeBytes: number; sha256: string; source: 'manual' | 'ai';+ target: { pluginId: string | null; ghostId: string; version: string; expectedRelease: Revision | null };+};+```++同键绑定完整规范化请求,不能换包或目标。201 新操作、200 原键恢复。+返回 operation 及 `upload:{putUrl,headers,expiresAt}|null`,原包 PUT 后:++- `POST /operations/:id/commit {}` → 202 `{subject,operationId,status}`。+- `GET /operations/:id` → 原操作和不可变回执、即时审核投影。+- `status` 为 awaiting_upload / validating / publishing / succeeded / failed / expired。+- succeeded 才有 receipt;202 不表示已提审,PUT 成功也不表示受理。+- receipt 含 operationId/submissionId/pluginId/releaseId/ghostId/version/source/submittedAt,+ uploadedPackage{sha256,sizeBytes}、releaseRevision 和 outcome。+- v2 成功新提审 outcome=submitted_for_review;旧回执 metadata_updated / unchanged 仍可读,+ 不允许借旧 outcome 绕过新版本规则。++暂态 Auth/JWKS、存储、事务或未知网络结果释放当前租约并保留原操作,5秒退避后显式恢复同 commit。+Host 在远程写入前落盘键和原请求,不保存 token/票据;切号停止旧任务,旧 generation 不能回写。+未知结果先 GET 原操作,非终态重放同 commit,不重新 prepare / PUT / 新键。+停止上传只中止本机任务,不取消审核或删除服务端事实。++## 3. 个人提审的版本规则++同一 canonical pluginId + version 只能成功提审一次,取消/退回/通过/撤权/下架均不释放版本。+prepare、上传、坏包、明确未提交审核不消费版本;未知结果先查询原操作。+个人入口对每插件同时至多允许一个实际 pending 审核版本。GitHub/OIDC、组织成员人工审核和组织免审保持原有规则。++写入复用既有 namespace 和 Release→Plugin 锁序,新 Release 只锁 Plugin。+锁后重查版本、待审、当前提交权限及租约;同一事务写包事实、精确修订的 `review.submit` 审计、回执及 operation 成功。+个人入口不覆盖既有 Release;历史比较包和发布事件不作为提交或审核前置条件。++## 4. 本人插件、版本与取消++| 入口 | 返回/语义 |+|---|---|+| GET /plugins?query=&filter=&limit=&cursor= | subject/queriedAt/plugins/nextCursor;filter=all/pending/action_required/listed;服务端筛选分页 |+| GET /plugins/:id | plugin、latestSubmissionContent、分页 history;市场与最近版本分开 |+| GET /plugins/:id/releases?version=&limit=&cursor= | 每 Release 当前修订一项,不能用操作回执数量充当版本 |+| GET /plugins/:id/history?limit=&cursor= | 独立 eventId、类型、精确 revision 或 null、完整原因与游标 |+| GET /plugins/:id/submissions/:submissionId | receipt、匹配修订的 submission、原提交 content 或明确 null |++SubmissionView 包含 revision/revisionState、reviewStatus(pending/approved/rejected/cancelled 或未知 null)、+submittedAt、approvedAt、cancelledAt、decidedAt、reason 和 actions.canCancelReview。+真实时间取匹配修订的事件;旧资料无法核实时为 null,不能拿包创建/上传时间或当前状态补造。+content 留存规范化 manifest/manifestView/icon;不是原始 manifest 字节。旧内容未知不借当前包补齐。+市场状态独立为 pluginStatus/currentRelease/available/unavailableReason,approved 不等于已上架。++`POST /plugins/:pluginId/releases/:releaseId/cancel-review`:++```json+{"expectedRelease":{"releaseId":"exact-release","sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","displayUpdatedAt":"2026-10-16T10:42:00.000Z"}}+```++仅本次个人提审原发起人且仍有精确 ACL 可取消;不设计多作者代取消。+事务中 Release→Plugin 加锁、核对 receipt/修订/授权并用当前 bearer 再验签。+pending→cancelled 与 `plugin.review.cancel` 原子写入;重复不产生新事件或取消时间。+已通过或退回时返回真实终局,不伪称取消成功。响应 `{subject,queriedAt,pluginId,submission}`。+取消不撤销当前上架包,不释放版本,不伪装为 rejected/revoked。+客户端使用现有确认框说明版本不可复用,无原因表单;所选待审版本才有取消按钮。++“我的插件”每插件一行,主体是名称、当前市场与最新情况,不展示提交次数。+进入插件后版本选择统领状态、提审/通过时间、说明、原因与操作,历史和技术资料默认收起。+当前市场与所选版本相同则合并展示;查看旧版本可定位待审版本。+上传问题附在所属插件,完整消息可读;不叫“本机发布记录”,不在列表上方铺流水。+前台、进入页面、手动刷新或网络恢复时读取,无后台审核轮询或通知。+撤权后只保留本人回执及匹配历史,不泄露他人的后续待审内容。++## 5. Platform 审核与来源++管理读取 additive `release.contribution` 只标记真实匹配个人回执;内部 publishSource 仍为 console_upload,+本人 API 派生 community_upload;无回执不推断来源,也不扩老来源 enum。+旧邮箱路径不得用于个人版本,个人发布不新增任何通知。+个人版本在原后台详情补充来源、提交身份和包内更新说明,不增加提交者管理或独立审核页面。+Web / CLI 沿用原 approve/reject 请求及 `expectedReleaseUpdatedAt` 修订检查,复用原待审队列、审核、上架与驳回流程。+不增加审核阅读令牌、发布基准或历史比较包门槛;个人接口没有额外启用开关。++## 6. 错误与恢复++| code | 含义与合法下一步 |+|---|---|+| RELEASE_NOTES_REQUIRED | 曾上架插件的更新缺说明,尚未提交审核、未占号;修改包内 releaseNotes 并重新安装 |+| VERSION_ALREADY_SUBMITTED | 已用版本;查看结果,修改需换号 |+| PLUGIN_PENDING_RELEASE_EXISTS | 已有实际待审;先查看或取消该版本 |+| CONTRIBUTION_PACKAGE_CHANGED | 摘要后本地内容变化,未开始上传;刷新摘要 |+| CONTRIBUTION_REVISION_STALE / PLUGIN_REVIEW_STALE | 目标或待审修订变化,刷新并重新核对 |++主体/ACL/重复键/坏包/体积/过期等沿既有精确错误,不把具体原因统一覆盖成“失败”。+没有终态证据时只显示处理中/结果待核对,不声称版本未占用。++## 7. 迁移与本地验证++`20261016010000_plugin_review_cancellation` 只扩 review enum cancelled 和审计索引;+个人三表与旧审计修订触发器仍由前一 migration 提供。++个人投稿接口部署后即可使用,沿普通个人登录及当前插件权限校验,不增加启用开关或开通资格。+不清理或迁移旧 GitHub/组织待审队列;旧渠道继续原流程。+历史 migration 的开关注释已不适用,保留已应用迁移的校验和。+新增 cancelled 的 reader 兼容须在合并部署前核实,不得让不支持该值的旧 reader 与新写入混跑;写入后回滚须保留兼容 reader。++两仓相关选测、真实隔离数据库与本地接口证据在交付时写入对应服务/客户端说明。+源码、mock 测试、本地新库演练均不等于存量生产滚动演练或部署许可。diff --git a/docs/plugin-community-contribution.md b/docs/plugin-community-contribution.mdnew file mode 100644index 0000000000..0fd604dd2f--- /dev/null+++ b/docs/plugin-community-contribution.md@@ -0,0 +1,117 @@+# 个人社区插件发布客户端++客户端实现与权限边界说明。+两仓各自维护等价的 [HTTP / DTO 契约](plugin-community-contribution-contract.md)。++插件列表以当前最新主线为基线,原卡片、来源文案、署名布局、统计、推荐分类、筛选与排序保持一致,仅新增“我的插件”按钮。来源继续使用主线的“公开 / 团队共享 / 本地 / 自定义”,不新增“本地开发 / 本地导入”等分类,不用来源推断作者身份或发布状态。匿名署名继续尊重服务端的空值,不回退包内个人信息。++作者在独立源码目录开发、安装并使用插件后,可在本地插件使用详情选择“提交审核”;后续版本在“我的插件”的独立管理页选择“提交 {{version}} 审核”,提交完成后留在本页刷新版本和审核状态。+本地使用详情准备当前包的只读发布摘要,在“版本与更新”中查看;按钮显示“提交 {{version}} 审核”时,点击就是公开发布意图:Host 固定并再核对当前安装内容,+不弹保存或选文件框,没有资料表单、独立介绍、翻译或第二个确认步骤。只有提交结果已确认后才进入该插件管理详情;提交失败留在原处显示实际原因,用户已离开时不抢回页面。作者继续开发时仍回到源码目录,不直接编辑 Host 的安装目录。+本地使用详情顶部操作区排列提审按钮、使用动作与启用开关;发布说明、适用的限制原因、+当前准备阶段和提审限制在版本与更新中查看。普通列表始终进入使用详情,不自动跳入作者管理;发布结果、版本历史和匿名设置集中在“我的插件”独立页面。保留原三列详情头部:+宽窗图标与标题在左、操作在右,发布按钮紧随使用动作;详情内容区不足 680px 时整组转到标题下方换行。+右侧按钮较多时允许组内换行,并为标题至少保留 160px;管理页的长名称与匿名控件在同一个标题组中自然换行。+未能查询时显示错误,不以本地版本推断线上结果。++“我的插件”是插件页常驻入口,页头(含空列表)提供“发布插件”。该按钮只打开当前账号的已安装插件选择,+选择框与原详情复用同一份本地条件判断,只列出可信本地精确实例;保留标识、组织/私域、+安装身份未确认或权限未批准的实例不进入选择框。没有可选项时区分未安装与没有可发布实例,+引导安装、使用自己的插件并核对详情。选择后留在当前弹窗,展示所选精确本地安装的实际名称、版本、用途、更新说明与只读预检结果,不创建上传或占用版本;点击“提交 {{version}} 审核”才开始上传。关闭弹窗保留管理列表位置,不提交。+选择框打开后独立完整读取本人插件版本事实,不受管理列表搜索和分页影响。已知当前版本已提审、插件有待审版本或无提交权时,在选项内直接说明并禁止选择;未知或读取失败时不冒充可提交。选中后的实际包预检仍是最终提交条件;限制或错误固定显示在底部按钮上方,不藏在用途、更新说明的滚动区域中。首次发布沿“我的插件 → 发布插件 → 选择本地版本 → 提交审核”,新版沿已有管理详情提交,审核结果仍在同一管理详情查看,不把 Agent 的调用步骤作为用户页面。+不能发布的实例仍在详情固定位置显示实际原因(保留标识、组织/私域、身份或权限批准未就绪),+安装不表示作者权,最终仍由 Main、服务端核验私域台账与 public ACL。+未登录或组织身份复用现有登录、切个人账号入口;登录意图只在内存保存,+恢复时必须匹配原物理实例键、安装目录和批准记录,再按当前账号重新准备。另一个账号的同 ID 安装不会+自动代替原目标。列表支持服务端搜索、筛选与分页,每行以插件为主体,分别列出本地版本、当前上架版本和最近提审;+列表只展示服务端已收到的插件提交,不把未完成上传当作插件记录。上传与提交过程留在原提交按钮中,失败原因也在该次提交时显示。+管理详情默认显示本地、已上架、待审核三份当前事实,以及本地动作、已上架内容和当前提审。+已上架介绍与更新说明只读取匹配当前市场 releaseId/version 的真实公开版本,不借最新待审内容补齐。+发布记录默认收起,内部版本选择仅切换历史快照;版本号与状态分开显示,共用应用 Select,+单个历史版本不显示无用下拉框。完整退回原因保留,历史选择不改变本地版本、当前提审或提交目标。+顶部返回按固定父页面跳转:管理详情返回“我的插件”列表,再返回原插件列表,同账号保留查询、筛选和列表位置。管理读取本机安装不改变普通详情的选择;管理页不再提供实际跳往普通详情的“打开插件”按钮。普通插件详情仍沿原列表返回逻辑。++官方 public 插件不允许经客户端提审(包括 Agent 工具),即使当前账号有提交授权也不例外。请通过 GitHub 仓库提交修改,以保证仓库源码完整、便于后续维护。官方身份只取 Host 可信官方来源或服务端 publisherKind,不根据名字、包内 author 或自定义市场声明认定;界面隐藏提交入口并显示原因,Main 在准备和实际写入前复核。普通第三方 public 插件沿既有授权流程。++## 版本更新与取消审核++首次上架不要求更新说明,插件用途写在 `description`。插件曾上架后再提审时,作者在 `ghost.json.releaseNotes` 写相对上一已上架版本的完整更新说明;从未上架的退回或取消不视为更新,下架不免除更新说明要求。+缺字段的包仍可安装,只有曾上架插件的更新缺说明时才阻止提审。摘要展示实际版本、已有说明与不可复用提示。+每次准备各自持有临时包;StrictMode 清理不影响另一份摘要,提交后由原操作持有固定字节直到终态。+本地安装内容或批准变化后必须刷新摘要;AI 也读取同一摘要并按当前权限档提交。++成功提审后该插件的版本号永久占用;退回、取消、通过、下架均不能再次使用。+每插件至多一个真实待审版本。预检或上传失败未提交成功不占号。用户流程只有提交本地插件、后台审核、通过或驳回;上传中只显示提交进度,失败就显示原因,不提供独立恢复、重试或上传记录页面。相同内容的未完成请求由普通提交入口内部复用,不要求用户选择或理解操作记录。+“我的插件”按插件和版本展示真实提审时间、通过时间;历史未知时间明确未记录。+待审版本可通过原确认框“取消本次提审”,不填写原因;取消保留版本与记录,不改变当前市场。+取消与审批竞争时返回实际终局,不把已通过伪装成取消成功。+“我的插件”管理详情独立显示本地版本、已上架、待审核三个事实;本地版本指这台电脑实际安装的版本,来源沿原规则,可为“本地”或“公开”,并准确显示启停情况。管理页不支持提交时隐藏提交入口,包括待审、版本号已占用、权限或安装状态未就绪及离线;处理中保留 loading 防重复提交。不能从列表直接盲提交。++只读预检与取消审核的接口见两仓共享契约。+个人投稿复用原待审、审核和上架流程,没有额外启用开关,不要求发布基准或审核阅读令牌。++## 当前包与上传恢复++- `exportGhostPackage.ts` 的快照原语复用原目录闭包、签名文件和内容一致性规则;系统导出保持原行为。+ `plugin-contributions/prepared.ts` 只接受实例标识,核对 root、批准记录、owner 及私域 ledger 隔离,+ 经既有 inspect 自检后把确切字节固定到受管临时目录。+- `plugin-contributions/api.ts` 使用 Main 中的个人 Access Token。可信 auth endpoint 的 discovery+ 返回 issuer;所有作者响应须匹配该 issuer 和当前 membership sub,服务器仍负责验签及 public ACL。+ 历史 alias 经本人详情解析后以 canonical pluginId 作为后续目标和回执比较基准。+- `plugin-contributions/host.ts` 在第一次远程写入前持久化固定请求、操作键和快照引用;PUT 只发原包字节。+ prepare 丢响应重放同请求、同键;commit 丢响应先查原操作;用户再次点击普通提交时,对相同安装与内容复用未完成请求,内部幂等重放同一 operation commit,不另建发布操作。页面读取不触发写入,+ 换账号会停止旧任务;旧 owner generation 不能覆盖当前账号文件或新任务。+- journal 不保存 Bearer 或 PUT 票据。恢复记录按稳定账号隔离,临时包路径不返回 Renderer / AI;+ 从 journal 读取的目录须通过受管目录校验才可递归清理。共用正式 userData 的 passive 开发实例不能写入+ 发布恢复文件,应在持有当前数据的主实例操作。++202 只是处理中。只有服务器成功操作附带完整回执,才解释 `submitted_for_review`、`metadata_updated`+或 `unchanged`;上传包 SHA 与实际 Release SHA 分开。审核状态属于对应修订,市场可用以 `available`+为准。旧版上架而新版被退回时,两者同时保留;历史按独立 eventId 展示,不能把同修订事件压成一条。++上传动作只做有限的操作处理查询。人工审核结果在个人账号的应用前台按 60 秒间隔及打开、手动刷新、回到前台或网络恢复时读取;应用内保留审核结果未读标记,不发送外部消息,后台不可见时不查询。+离线保留当前账号上次查询快照及时间并标明失败;查询失败不冒充+空列表。换账号清空视图缓存,不显示旧账号原因或内容。++## 本机安装与已上架版本++“我的插件”按服务端本人 API 返回的插件展示一条管理记录。Main 以现有 `namespace + ghost.json.id`+读取这台电脑实际安装的版本;公开安装继续核对原市场台账的 pluginId、来源和批准包证据。+本地安装不要求先有提审回执,也不新增手动关联操作或持久化关联记录。+同一插件正常本地更新后直接展示新的安装版本;未安装和读取失败分别显示,不混为一谈。++本地版本、已上架版本、当前提审是独立事实。提审、审核通过和页面读取都不改变安装来源,+不自动安装或替换包。同一账号仍按现有 namespace + id 去重,不支持同身份的本地版与公开版并装;+名称相同而 ID 不同的插件不合并。发布权限与匿名修改权限继续由服务端分别判定,不能从本地安装推断。++## 基础数据++“我的插件”详情在标题下方的元信息行直接复用现有 `PluginSharedUsage` 组件,和插件列表、普通详情使用相同的累计统计及悬停/聚焦交互。+复用已上架版本详情中的 `downloadStatistics.requestCount` 与 `usageStatistics.usageCount`,按插件的所有版本聚合,不限定近七天。+下载量沿既有下载地址请求口径,不等于安装完成次数;调用量沿服务端已上报的共享调用口径,不读取本机个人调用记录。+未上架不显示统计;详情读取失败或服务端缺少指标时沿现有组件逻辑隐藏对应计数,只有服务端明确返回零才显示 0。统计不随历史版本选择切换,不增加请求、IPC、服务端接口或统计组件分支。++## AI 与特权边界++`ghost_contribution_prepare`、`ghost_contribution_submit`、`ghost_contribution_status`、+`ghost_contribution_stop`、`ghost_cancel_plugin_review`、`ghost_my_plugins` 是普通个人作者的独立能力入口;旧企业 Forge 发布保持原行为。+读取工具支持列表、精确详情、历史游标和指定 submission 留存内容。提交沿当前任务 Full Access / Auto / Ask,+不再增加最后人工点击;安装许可不证明公开发布权。AI 不获得 Bearer、PUT URL、受管文件路径或审核权限。++所有新能力在调用前及返回前复核 owner 和既有 helper surface;公开写入还在确认后、最终启动前复核。+共享任务访客和 `resolveHelperSurface` 判为 restricted 的插件托管任务、errand 及其 Worker 不得借用+Host 账号。普通用户自己的 Worker 和自动任务不被泛化封禁。IPC 仅暴露精确方法和参数,拒绝任意路径、+额外主体字段和不可信 Renderer;未增加 device-link allowlist 或远程控制能力。++故障只影响当前个人发布动作:停止、断网或服务端失败不会改变已装插件、运行时或既有市场版本。+重启后不自动重新上传,也不展示内部恢复记录;用户仍通过普通提交入口操作。未知结果保留原键及原请求,+不由 UI 推断成功或擅自更换包。服务端不支持接口时明确失败,不回退到企业或 Platform 身份。++## 验证与维护++提交前对 Host 固定包与恢复、可信 IPC、账号隔离、普通详情入口、管理页版本与匿名设置、审核结果未读执行相关回归;检查共享协议和开发工具包的类型及行为。+界面使用仓库 `pnpm ui:check` 验证真实组件的明暗主题与窗口尺寸,并在 PR 附截图。隔离场景不代替真实提审、审核、安装或权限验收。++`ghost.json.releaseNotes` 和提审/匿名规则同时维护在内置 `cindy-plugin-creator` 手册及 `cindy-tools` 工具说明中。官方插件仓的文档、示例与校验不在本次客户端改动范围内。++存量插件影响:不改变 registry 格式、批准记录、运行指纹、安装布局或启停状态;缺少 `releaseNotes` 的旧包继续可打包、安装和运行。插件基座改动仍须按仓库白名单确认门完成人工 review 后合并。diff --git a/docs/product-rules/agent-user-parity.md b/docs/product-rules/agent-user-parity.mdindex 597446e088..8f0bcd6d6f 100644--- a/docs/product-rules/agent-user-parity.md+++ b/docs/product-rules/agent-user-parity.md@@ -59,6 +59,7 @@| 伙伴 | 工作台一眼(等你 / 在做) | 有 | 无 || 伙伴 | 跟进任务:读取与继续(自动跟进所有任务的伙伴) | 有 | 有(2026-10-17) || 伙伴 | 查看与更换主力电脑 | 有 | 有(2026-10-17) |+| 社区插件贡献 | 当前安装快照准备、公开提交/原操作恢复、本人列表/详情/留存内容 | 有(2026-10-15) | 无 |Worker 工具省略 working_dir 时保持继承 Lead 任务记录目录,不跟随之后 cd 进入的 worktree。面板默认识别实际目录属于 UI 行为;Agent 通过显式 working_dir 共用已有 worktree,@@ -106,3 +107,17 @@ Session 委托写操作,以及 `cindy_orca` 的协作写操作,共用 Host自动轮次没有有效委托只准备建议;已有委托的执行权不依赖自动观察规则的开关。普通 Orca Lead 的当前 team 回报只延续原 team 范围,不能据此控制其它任务。跨电脑任务互发要求双方支持行动回执,旧端明确提示不支持;未增加观察数据权限。实机多端验收仍待完成。++## 社区插件贡献++普通个人作者的独立入口为 `ghost_contribution_prepare`、`ghost_contribution_submit`、+`ghost_contribution_status`、`ghost_contribution_stop`、`ghost_my_plugins`、`ghost_cancel_plugin_review`,由 `cindy-tools`+直接提供工具说明。手动和 AI 复用 Host 的精确安装快照、操作键、回执及个人读取接口;AI 不拿到+Bearer、PUT 票据或受管文件路径。公开写入遵循当前任务 Full Access / Auto / Ask,不加最后人工点击。+共享任务访客及既有 helper surface 判为 restricted 的插件托管任务(包括其 Worker)不得读取个人+个人插件发布资料或执行发布。普通用户自己的 Worker、自动任务沿相同账号边界与任务权限;人工审核不由 Agent 执行。+客户端协议和恢复边界见 [社区贡献实现说明](../plugin-community-contribution.md)。++2026-10-16:个人发布 prepare 返回包内 releaseNotes 和远端只读预检;submit 前重新校验所见快照内容。+`ghost_cancel_plugin_review` 使用本人版本的精确 revision,区分停止上传与取消审核,沿现有 Full Access/Auto/Ask 授权。+旧版本包仍可安装,成功提审后的同版本不再支持改包重提。diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.mdindex 135d3a0dba..89f56a848f 100644--- a/i18n/GLOSSARY.md+++ b/i18n/GLOSSARY.md@@ -435,6 +435,10 @@ issue #882:模型管理/新对话选择器的分类标签,对应 Gateway mod模型目录维护的权威协议;独立于各 Harness 的实际接入配置。设置面板用于简短对比原生支持与兼容模式。+### My Plugins++个人账号发布插件、查看发布情况与发布记录的页面,区别于本机已安装插件和旧企业我的发布。+### Not signed in跳过登录后应用内的账号状态名(侧边栏账号胶囊、设置页资料卡、语音服务提示,以及 main 侧不走 locale 的 model-visible 文案——已知 mcp-integrations/ghost.ts 的 GHOST_NOT_FOUND tool result,它会被模型读到并可能回显进对话,#907 review 补上)。**约束范围不限于 locale JSON**:guard 只扫 locale 文件,这类硬编码文案要人工找(见 engineering-conventions §5.1「Slack / IM 侧的文案不在任何 locale 文件里」同类问题)。2026-07-29 产品口径:面向用户只说「未登录」,不再叫「本地模式」——后者听起来像另一种服务端连接方式,实际只是没有登录 Cindy 账号。「本地」仅用于描述数据落在本机(如资料卡副文案「数据仅保存在本机」),不作为状态名。代码内部标识(AuthState mode='local'、authEnterLocal IPC、data owner)不受本条约束,仍用 local。en 侧统一走 not signed in 一种说法(含 settings.userProfile.local 的 exit / exitFailed 两条当前无引用的文案:the not-signed-in state),不与 unauthenticated 混用——PR #907 review 指出过同一状态两种英文说法会让日后启用这些文案时 UI 自相矛盾。status 仍为 proposed:Not signed in 作为状态名尚未与设计侧正式过一遍。@@ -475,6 +479,10 @@ WebAuthn 可发现凭证的用户可见名称,采用 Apple、Google 与 Micros右侧栏插件面板页签的图钉:钉住 = 面板在所有对话中保留。动词对:Pin=钉住 / Unpin=取消钉住。2026-07-31 随图钉功能提出,待裁决。+### Publish anonymously++个人插件的公开署名开关,默认开启,原作者可随时修改;不改变固定账号归属,关闭后展示提审时保存的昵称。+### Main viewPlugin 声明的应用级完整页面能力;区别于会话内 Panel。V1 由 Cindy 侧边栏入口打开,manifest/代码标识固定为 main-view。diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex b1b5ed7096..94c32be385 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -11,6 +11,8 @@{"id": "mcp-app", "status": "proposed", "en": "MCP App", "translations": {"zh-CN": "MCP App", "zh-TW": "MCP App", "ja": "MCP App", "ko": "MCP App"}, "note": "标准 MCP Apps 协议提供的交互应用;卡片标题与消息来源沿用协议名称,各语言保留 MCP App,待术语评审后固化。"},{"id": "dissolve-group", "status": "proposed", "en": "Dissolve group", "translations": {"zh-CN": "解散群聊", "zh-TW": "解散群聊", "ja": "グループを解散", "ko": "그룹 해산"}, "checkCase": false, "note": "Irreversible group termination, distinct from archive, leave and personal list removal."},{"id": "bot-market", "status": "proposed", "en": "Discover Teammates", "translations": {"zh-CN": "发现伙伴", "zh-TW": "發現夥伴", "ja": "仲間を探す", "ko": "동료 찾기"}, "checkCase": false, "note": "预制伙伴目录与邀请入口,仅 Desktop。入口菜单项与弹窗标题同用 bots.market.heading,不再另设英文品牌名 Bot Market;英文句中小写 teammates(Discover teammates 作动作时),作功能名保持 Discover Teammates。"},+ {"id": "plugin-anonymous-publishing", "status": "proposed", "en": "Publish anonymously", "translations": {"zh-CN": "匿名发布", "zh-TW": "匿名發布", "ja": "匿名で公開", "ko": "익명으로 게시"}, "note": "个人插件的公开署名开关,默认开启,原作者可随时修改;不改变固定账号归属,关闭后展示提审时保存的昵称。"},+ {"id": "my-plugins", "status": "proposed", "en": "My Plugins", "translations": {"zh-CN": "我的插件", "zh-TW": "我的插件", "ja": "マイプラグイン", "ko": "내 플러그인"}, "note": "个人账号发布插件、查看发布情况与发布记录的页面,区别于本机已安装插件和旧企业我的发布。"},{"id": "input-handoff", "status": "proposed", "en": "Input Handoff", "translations": {"zh-CN": "代输入", "zh-TW": "代輸入", "ja": "代理入力", "ko": "대리 입력"}, "checkCase": false, "note": "Agent 遇到需要主人填写的界面(选择、文本、密码、验证码、授权)时,由宿主读出当前一步,主人在本机或远程设备上填写,值只交给宿主、不进模型与记录。不是远程控制。"},{"id": "wallpaper-blur", "status": "proposed", "en": "Wallpaper Blur", "translations": {"zh-CN": "壁纸模糊", "zh-TW": "桌布模糊", "ja": "壁紙のぼかし", "ko": "배경화면 흐림"}, "note": "仅使应用壁纸柔化,不模糊文字或控件;0 为关闭,按用户选择应用于静态图片和视频。"},{"id": "group-owner", "status": "proposed", "en": "Group Owner", "translations": {"zh-CN": "群主", "zh-TW": "群主", "ja": "グループオーナー", "ko": "그룹 소유자"}, "checkCase": false, "note": "Chat Server 的群角色,可由人或伙伴担任;不要与伙伴主人或分工负责人混同。群设置成员行英文可简写 Owner。"},diff --git a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts b/packages/cindy-tools/src/__tests__/ghostMcp.test.tsindex 89c48d13c4..82ed64a2ef 100644--- a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts+++ b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts@@ -1250,6 +1250,11 @@ describe("cindy_ghosts · server 构建", () => {};expect(Object.keys(server._registeredTools).sort()).toEqual(["ghost_call",+ "ghost_cancel_plugin_review",+ "ghost_contribution_prepare",+ "ghost_contribution_status",+ "ghost_contribution_stop",+ "ghost_contribution_submit","ghost_forge_guide","ghost_forge_install","ghost_forge_pack",@@ -1259,6 +1264,7 @@ describe("cindy_ghosts · server 构建", () => {"ghost_info","ghost_list","ghost_manual",+ "ghost_my_plugins","media",]);const infoDescription = server._registeredTools.ghost_info?.description ?? "";@@ -2183,3 +2189,93 @@ describe("portable legacy plugin media", () => {}});});++describe('personal community author MCP transport', () => {+ async function connected(deps: CindyGhostsMcpDeps) {+ const { Client } = await import('@modelcontextprotocol/sdk/client/index.js');+ const { InMemoryTransport } = await import('@modelcontextprotocol/sdk/inMemory.js');+ const server = createCindyGhostsMcpServer(deps);+ const client = new Client({ name: 'personal-author-test', version: '1' });+ const [ct, st] = InMemoryTransport.createLinkedPair();+ await server.connect(st);+ await client.connect(ct);+ return { client, close: async () => { await client.close(); await server.close(); } };+ }++ it('routes preparation, the same operation, and exact personal reads to the independent Host capability', async () => {+ const communityContribution = vi.fn<NonNullable<CindyGhostsMcpDeps['communityContribution']>>(async () => ({ ok: true, result: {} }));+ const forgePublish = vi.fn();+ const transport = await connected(fakeDeps({ communityContribution, forgePublish }));+ try {+ for (const [name, args] of [+ ['ghost_contribution_prepare', { ghost_id: 'hello', namespace: null }],+ ['ghost_contribution_submit', { prepared_id: 'original-operation' }],+ ['ghost_contribution_submit', { prepared_id: 'original-operation', resume: true }],+ ['ghost_contribution_status', { local_id: 'original-operation' }],+ ['ghost_contribution_status', {}],+ ['ghost_contribution_stop', { local_id: 'original-operation' }],+ ['ghost_cancel_plugin_review', { plugin_id: 'plugin-1', release_id: 'release-1', sha256: 'a'.repeat(64), revision: '2026-10-16T00:00:00.000Z' }],+ ['ghost_my_plugins', { query: 'hello', filter: 'needs_action', cursor: 'list-cursor' }],+ ['ghost_my_plugins', { plugin_id: 'plugin-1', cursor: 'history-cursor' }],+ ['ghost_my_plugins', { plugin_id: 'plugin-1', submission_id: 'submission-1' }],+ ] as const) {+ expect((await transport.client.callTool({ name, arguments: args })).isError).not.toBe(true);+ }+ expect(communityContribution.mock.calls.map(([input]) => input)).toEqual([+ { action: 'prepare', ghostId: 'hello', namespace: null },+ { action: 'submit', id: 'original-operation' },+ { action: 'resume', id: 'original-operation' },+ { action: 'status', id: 'original-operation' },+ { action: 'transfers' },+ { action: 'cancel', id: 'original-operation' },+ { action: 'cancel-review', pluginId: 'plugin-1', release: { releaseId: 'release-1', sha256: 'a'.repeat(64), revision: '2026-10-16T00:00:00.000Z' } },+ { action: 'list', query: 'hello', filter: 'needs_action', cursor: 'list-cursor' },+ { action: 'detail', pluginId: 'plugin-1', cursor: 'history-cursor' },+ { action: 'submission', pluginId: 'plugin-1', submissionId: 'submission-1' },+ ]);+ expect(forgePublish).not.toHaveBeenCalled();+ } finally { await transport.close(); }+ });++ it('rejects arbitrary paths, replacement identities and incomplete exact submission reads before Host', async () => {+ const communityContribution = vi.fn();+ const transport = await connected(fakeDeps({ communityContribution }));+ try {+ for (const [name, args] of [+ ['ghost_contribution_prepare', { ghost_id: 'hello', file: '/private/package.cindy' }],+ ['ghost_contribution_submit', { prepared_id: 'original-operation', authority: 'other-issuer' }],+ ['ghost_contribution_status', { local_id: 'original-operation', token: 'not-a-host-token' }],+ ['ghost_contribution_stop', { local_id: 'original-operation', membershipId: 'other' }],+ ['ghost_cancel_plugin_review', { plugin_id: 'plugin-1', release_id: 'r', sha256: 'bad', revision: 'not-a-date' }],+ ['ghost_cancel_plugin_review', { plugin_id: 'plugin-1', release_id: 'r', sha256: 'a'.repeat(64), revision: '2026-10-16T00:00:00.000Z', token: 'override' }],+ ['ghost_my_plugins', { plugin_id: 'plugin-1', scope: 'organization' }],+ ['ghost_my_plugins', { submission_id: 'submission-without-plugin' }],+ ] as const) {+ expect((await transport.client.callTool({ name, arguments: args })).isError).toBe(true);+ }+ expect(communityContribution).not.toHaveBeenCalled();+ } finally { await transport.close(); }+ });++ it('reports unavailable capabilities and sanitized Host failures as MCP errors without enterprise fallback', async () => {+ const absent = await connected(fakeDeps());+ try {+ const result = await absent.client.callTool({ name: 'ghost_my_plugins', arguments: {} });+ expect(result.isError).toBe(true);+ expect(JSON.stringify(result)).toContain('UNSUPPORTED_CAPABILITY');+ } finally { await absent.close(); }+ const communityContribution = vi.fn()+ .mockResolvedValueOnce({ ok: false, errorCode: 'CONTRIBUTION_NOT_AUTHORIZED', message: 'This account cannot publish this plugin.' })+ .mockRejectedValueOnce(new Error('private-transport-token'));+ const transport = await connected(fakeDeps({ communityContribution }));+ try {+ const denied = await transport.client.callTool({ name: 'ghost_contribution_submit', arguments: { prepared_id: 'original-operation' } });+ expect(denied.isError).toBe(true);+ expect(JSON.stringify(denied)).toContain('CONTRIBUTION_NOT_AUTHORIZED');+ expect(JSON.stringify(denied)).toContain('This account cannot publish this plugin.');+ const failed = await transport.client.callTool({ name: 'ghost_my_plugins', arguments: {} });+ expect(failed.isError).toBe(true);+ expect(JSON.stringify(failed)).not.toContain('private-transport-token');+ } finally { await transport.close(); }+ });+});diff --git a/packages/cindy-tools/src/ghost/mcpServer.ts b/packages/cindy-tools/src/ghost/mcpServer.tsindex 0fb5e99a1c..c42255f7e2 100644--- a/packages/cindy-tools/src/ghost/mcpServer.ts+++ b/packages/cindy-tools/src/ghost/mcpServer.ts@@ -128,6 +128,7 @@ const D_GHOST_FORGE_GUIDE = ["创建、修改、调试、打包或发布 Cindy 插件时使用该 Skill;本工具保留按章读取同一份资料的兼容入口。",'不传参数返回目录,传 section(章号如 "4.7" 或标题关键词如 "network")返回单章正文。',"本工具只读文档,不安装或发布插件。",+ "发布前另读 §2 的 releaseNotes、§7.3 个人发布和 §7.4 署名与匿名。",].join("\n");const D_GHOST_FORGE_SCAFFOLD = [@@ -135,6 +136,7 @@ const D_GHOST_FORGE_SCAFFOLD = ["template 可选:plain(普通沙箱工具)、agent-action(卡片点击后让 Agent 继续/分叉/新建)、","node-json-rpc(普通随包 Node 服务)、node-mcp(随包 stdio MCP)。Node 模板只写零依赖示例","源码,不会执行 npm install / npx / postinstall。生成后按需求修改,再调用 ghost_forge_pack。",+ "骨架不自动填写 ghost.json.releaseNotes;首次上架可省略,后续更新须补写相对上一已上架版本完整变化的纯文本说明,见 ghost_forge_guide 的第 2、7.3 章。","会话工作目录内直接生成;工作目录外(例如相邻 worktree)走当前会话权限:","本地 Full Access 自动放行,Auto 交审阅,Ask 向用户确认。不要因为目录在工作目录外就改换目录或空转重试。",].join("\n");@@ -143,6 +145,7 @@ const D_GHOST_FORGE_PACK = ["把一个插件源码目录校验并打包成 .cindy。只生成产物,不安装或更新插件。","缺省只打包并返回产物路径;intent=publish 时额外返回一次性 publishToken。","intent=publish 仅企业组织成员可用;个人账号仍可使用缺省的纯打包模式。",+ "releaseNotes 若填写须为 ghost.json 顶层纯文本;缺字段仍可打包、安装;首次上架可省略,曾上架插件的后续提审必须非空。打包成功不代表通过发布预检,个人发布从已安装实例走 ghost_contribution_prepare,见手册 §7.3。","dir 传源码目录的绝对路径(目录里须有 ghost.json;打包自动跳过 .git / node_modules /","隐藏文件 / *.cindy)。会话工作目录内直接打包;工作目录外走当前会话权限","(本地 Full Access 自动放行,Auto 交审阅,Ask 向用户确认),不要因此改换目录或空转重试。",@@ -160,6 +163,7 @@ const D_GHOST_FORGE_INSTALL = ["dir 传插件源码目录绝对路径(工作目录外走与 pack 相同的会话权限)。成功返回本次真实执行的是 installed 还是 updated;","仅当用户明确选择 AI 生成图标时,可像 ghost_forge_pack 一样传 icon_source。","失败返回打包校验或 Host 安装事务的结构化错误。ghost_forge_pack 始终只打包,不受本工具影响。",+ "用户明确要求把自己开发并使用的插件发布到社区时,安装后调用 ghost_contribution_prepare,再用 ghost_contribution_submit 提审;本工具自身不发布。",].join("\n");const D_GHOST_FORGE_PUBLISH = [@@ -1488,5 +1492,41 @@ export function createCindyGhostsMcpServer(async (input) => handleForgePublishStatus(deps, input),);+ const contribute = async (input: Parameters<NonNullable<CindyGhostsMcpDeps['communityContribution']>>[0]) => {+ try {+ const result = deps.communityContribution ? await deps.communityContribution(input) : { ok: false, errorCode: 'UNSUPPORTED_CAPABILITY' };+ return textResult(result, !!result && typeof result === 'object' && 'ok' in result && result.ok === false);+ } catch {+ return textResult({ ok: false, errorCode: 'INTERNAL' }, true);+ }+ };+ const contributionId = z.string().min(1).max(256);+ server.registerTool('ghost_contribution_prepare', {+ description: '为用户自己开发、已安装并使用的确切插件固定临时快照并进行发布预检。此工具只读取原插件,不修改 ghost.json、插件源码或用户文件,不上传、不提审,也不自动补写更新说明。返回 preparedId、包摘要、包内 ghost.json.releaseNotes 和 blockers。首次上架不要求更新说明,插件用途写在 description;曾上架后再提审须用顶层纯文本 releaseNotes 完整覆盖相对上一已上架版本的变化(v2/v3 均支持)。仅更新缺失时按已有 Forge 开发流程修改作者源码,再用 ghost_forge_install 安装更新后重新预检,不改 Host 管理的安装目录。成功受理后的版本号永久占用,预检或未受理的上传失败不占号;同一插件只能有一个待审版本。用户已明确委托公开发布且 blockers 为空时,直接接 ghost_contribution_submit,不要求用户重新授权或手动完成最后一步。首次发布只接受 Host 可核实的本地包或 Forge 开发安装,属于人工审核申请,不代表作者认证。市场下载与可读历史不授予提交权;公共市场更新须有当前服务端精确提交授权和 Host 来源关联,Git/本地自定义市场、私域或来源不明不能转作首发。不能认领同名插件。官方 public 插件不允许经客户端或本工具提审;须通过 GitHub 仓库提交修改,保证仓库源码完整并便于后续维护。',+ inputSchema: z.object({ ghost_id: contributionId, namespace: ghostNamespaceInput }).strict() },+ async ({ ghost_id, namespace }) => contribute({ action: 'prepare', ghostId: ghost_id, namespace }));+ server.registerTool('ghost_contribution_submit', {+ description: '把 ghost_contribution_prepare 刚准备的确切插件公开提交或恢复同一操作。用户已明确委托公开发布时沿当前任务的 Full Access / Auto / Ask 权限执行,不额外要求用户重新授权或最后手动点击;只有安装委托不等于发布委托。不接受文件路径、独立文案、账号或票据。立即返回原操作句柄,接 ghost_contribution_status 查询到终态;202/处理中不等于已提交审核。结果未知先查原操作,再按原句柄 resume,不能换键另建发布操作。权限拒绝时说明原因并停止,不改权限模式重试。官方 public 插件须通过 GitHub 仓库提交修改,以保证源码完整、便于维护;客户端与 Agent 工具均不得提审。',+ inputSchema: z.object({ prepared_id: contributionId, resume: z.boolean().optional() }).strict() },+ async ({ prepared_id, resume }) => contribute({ action: resume ? 'resume' : 'submit', id: prepared_id }));+ server.registerTool('ghost_contribution_status', {+ description: '查询当前个人账号的原发布操作或本机恢复列表。只在当前上传动作处理中有限查询;操作终结后停止轮询人工审核。成功回执 outcome、修订审核状态与市场可用事实分别解释,上传 SHA 不一定是实际 Release SHA。',+ inputSchema: z.object({ local_id: contributionId.optional() }).strict() },+ async ({ local_id }) => contribute(local_id ? { action: 'status', id: local_id } : { action: 'transfers' }));+ server.registerTool('ghost_contribution_stop', {+ description: '停止当前上传并保留原操作。停止不代表撤回已提交内容,也不改变审核结果;后续查询原操作再恢复。',+ inputSchema: z.object({ local_id: contributionId }).strict() }, async ({ local_id }) => contribute({ action: 'cancel', id: local_id }));+ server.registerTool('ghost_cancel_plugin_review', {+ description: '取消本人仍有发布授权的精确待审版本。先从 ghost_my_plugins 读取当前版本、SHA 和 revision;取消不影响当前上架包,且该版本号以后不能再次提审。与停止上传不同;同一次取消可安全重试,批准/驳回已先完成时返回真实审核结果。依任务 Ask/Auto/Full Access 权限执行。',+ inputSchema: z.object({ plugin_id: contributionId, release_id: contributionId, sha256: z.string().regex(/^[a-f0-9]{64}$/), revision: z.string().datetime() }).strict() },+ async ({ plugin_id, release_id, sha256, revision }) => contribute({ action: 'cancel-review', pluginId: plugin_id, release: { releaseId: release_id, sha256, revision } }));+ server.registerTool('ghost_my_plugins', {+ description: '读取当前个人账号的我的插件列表或精确详情。搜索/筛选/分页由服务端执行;详情分当前市场、最近提交、已留存内容和独立处理历史,退回原因完整返回。只查询本人,不审核、不代修、不发通知。修改作者源码后重新安装并使用,再从当前实例准备发布更新,不直接修改 Host 管理的安装目录。历史内容和 releaseNotes 取对应版本提审快照。个人插件默认匿名,关闭后显示该版提审时保存的原作者昵称;账号改名不自动改变旧版。匿名由固定原作者在“我的插件”管理页名称右侧的 UI 设置,不能靠 ghost.json.author/anonymous 或本工具修改;官方 Cindy 与组织规则不变。',+ inputSchema: z.object({ plugin_id: contributionId.optional(), submission_id: contributionId.optional(), query: z.string().max(200).optional(), filter: z.enum(['all', 'pending', 'needs_action', 'published']).optional(), cursor: z.string().max(4096).optional() }).strict() },+ async ({ plugin_id, submission_id, ...input }) => {+ if (submission_id && !plugin_id) return textResult({ ok: false, errorCode: 'INVALID_ARGUMENT' }, true);+ return contribute(plugin_id ? submission_id ? { action: 'submission', pluginId: plugin_id, submissionId: submission_id } : { action: 'detail', pluginId: plugin_id, cursor: input.cursor } : { action: 'list', ...input });+ });+return server;}diff --git a/packages/cindy-tools/src/types.ts b/packages/cindy-tools/src/types.tsindex 176d4c7a4c..1f0dc9fe10 100644--- a/packages/cindy-tools/src/types.ts+++ b/packages/cindy-tools/src/types.ts@@ -491,6 +491,16 @@ export interface CindyGhostsMcpDeps {forgePublish(request: { token: string }): Promise<CindyForgePublishResult>;/** 查询一次后台发布传输的当前状态。 */forgePublishStatus(request: { transferId: string }): Promise<CindyForgePublishStatusResult>;+ /** Ordinary personal community author capability, separate from organization Forge publishing. */+ communityContribution?(request:+ | { action: 'prepare'; ghostId: string; namespace?: string | null }+ | { action: 'submit' | 'resume' | 'status' | 'cancel'; id: string }+ | { action: 'list'; query?: string; filter?: 'all' | 'pending' | 'needs_action' | 'published'; cursor?: string }+ | { action: 'detail'; pluginId: string; cursor?: string }+ | { action: 'submission'; pluginId: string; submissionId: string }+ | { action: 'cancel-review'; pluginId: string; release: { releaseId: string; sha256: string; revision: string } }+ | { action: 'transfers' }+ ): Promise<unknown>;logger?: {info: (msg: string, meta?: Record<string, unknown>) => void;warn: (msg: string, meta?: Record<string, unknown>) => void;diff --git a/packages/plugin-protocol/src/__tests__/delivery.author.test.ts b/packages/plugin-protocol/src/__tests__/delivery.author.test.tsnew file mode 100644index 0000000000..5ef842fa3d--- /dev/null+++ b/packages/plugin-protocol/src/__tests__/delivery.author.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';+import { PLUGIN_API_SCHEMA_VERSION, parseGetPluginResponse, parseListPluginsResponse, PluginProtocolError } from '../delivery.js';++function plugin(displayAuthor?: string | null) {+ return {+ id: `c${'p'.repeat(24)}`, ghostId: 'example', name: 'Example', description: null,+ author: null, ...(displayAuthor === undefined ? {} : { displayAuthor }),+ scope: 'public', organizationId: null, defaultInstall: false,+ currentRelease: { id: 'release', version: '1.0.0', sha256: 'a'.repeat(64), sizeBytes: 42,+ publishedAt: '2026-10-19T00:00:00.000Z', icon: null,+ manifest: { schemaVersion: 3, minCindyVersion: '1.0.0', id: 'example', name: 'Example', version: '1.0.0', kind: 'chip', entry: 'main.js' } },+ };+}++describe('workflow display author transport', () => {+ it('preserves public publisher identity independently from the displayed nickname', () => {+ for (const publisherKind of ['official', 'personal'] as const) {+ const value = { ...plugin('Cindy'), publisherKind };+ const response = parseGetPluginResponse({ schemaVersion: PLUGIN_API_SCHEMA_VERSION, plugin: value });+ expect(response.plugin.scope).toBe('public');+ expect(response.plugin.publisherKind).toBe(publisherKind);+ const list = parseListPluginsResponse({ schemaVersion: PLUGIN_API_SCHEMA_VERSION, plugins: [value], nextCursor: null });+ expect(list.plugins[0].publisherKind).toBe(publisherKind);+ }+ expect(() => parseGetPluginResponse({ schemaVersion: PLUGIN_API_SCHEMA_VERSION, plugin: { ...plugin(), publisherKind: 'forged' } })).toThrow(PluginProtocolError);+ });+ it('preserves the complete nickname without changing the legacy manifest author', () => {+ const value = plugin('名'.repeat(100));+ const response = parseGetPluginResponse({ schemaVersion: PLUGIN_API_SCHEMA_VERSION, plugin: value });+ expect(response.plugin.displayAuthor).toBe('名'.repeat(100));+ expect(response.plugin.author).toBeNull();+ expect(response.plugin.currentRelease.manifest.author).toBeUndefined();+ const list = parseListPluginsResponse({ schemaVersion: PLUGIN_API_SCHEMA_VERSION, plugins: [value], nextCursor: null });+ expect(list.plugins[0].displayAuthor).toBe('名'.repeat(100));+ });+ it('keeps old-server responses valid and preserves explicit missing attribution', () => {+ const old = parseGetPluginResponse({ schemaVersion: PLUGIN_API_SCHEMA_VERSION, plugin: plugin() });+ expect(old.plugin).not.toHaveProperty('displayAuthor');+ const missing = parseGetPluginResponse({ schemaVersion: PLUGIN_API_SCHEMA_VERSION, plugin: plugin(null) });+ expect(missing.plugin.displayAuthor).toBeNull();+ });+ it('still checks legacy manifest consistency instead of weakening that contract', () => {+ expect(() => parseGetPluginResponse({ schemaVersion: PLUGIN_API_SCHEMA_VERSION, plugin: { ...plugin('Verified account'), author: 'Package claim' } })).toThrow('author 与 currentRelease.manifest.author 不一致');+ });+ it('rejects a malformed extended display name', () => {+ expect(() => parseGetPluginResponse({ schemaVersion: PLUGIN_API_SCHEMA_VERSION, plugin: plugin('x'.repeat(101)) })).toThrow(PluginProtocolError);+ });+});diff --git a/packages/plugin-protocol/src/__tests__/delivery.localObject.test.ts b/packages/plugin-protocol/src/__tests__/delivery.localObject.test.tsnew file mode 100644index 0000000000..0c8cf88b5d--- /dev/null+++ b/packages/plugin-protocol/src/__tests__/delivery.localObject.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from 'vitest';+import { parseGetPluginResponse, parseListPluginsResponse, parsePluginDownloadResponse, PluginProtocolError } from '../delivery.js';++const options = { developmentObjectOrigin: 'http://127.0.0.1:43340' };+const url = `${options.developmentObjectOrigin}/dev-local/object?storageId=fixture&key=package`;+const download = { url, expiresAt: '2026-10-20T00:05:00.000Z', sha256: 'a'.repeat(64), sizeBytes: 42 };+const manifest = { schemaVersion: 2, id: 'example', name: 'Example', version: '1.0.0', kind: 'chip', entry: 'main.js', slots: [] };+const plugin = { id: `c${'a'.repeat(24)}`, ghostId: 'example', name: 'Example', description: null, author: null,+ scope: 'public', organizationId: null, defaultInstall: false,+ currentRelease: { id: 'release', version: '1.0.0', sha256: download.sha256, sizeBytes: 42, publishedAt: download.expiresAt,+ icon: { ...download, mimeType: 'image/png' }, manifest } };++describe('explicit local development delivery objects', () => {+ it('keeps HTTPS as the default for download, catalog icons and detail icons', () => {+ expect(() => parsePluginDownloadResponse(download)).toThrow(PluginProtocolError);+ expect(() => parseListPluginsResponse({ schemaVersion: 2, plugins: [plugin], nextCursor: null })).toThrow(PluginProtocolError);+ expect(() => parseGetPluginResponse({ schemaVersion: 2, plugin })).toThrow(PluginProtocolError);+ });+ it('parses the complete envelopes with an explicit exact loopback object policy', () => {+ expect(parsePluginDownloadResponse(download, options).url).toBe(url);+ expect(parseListPluginsResponse({ schemaVersion: 2, plugins: [plugin], nextCursor: null }, options).plugins[0].currentRelease.icon?.url).toBe(url);+ expect(parseGetPluginResponse({ schemaVersion: 2, plugin }, options).plugin.currentRelease.icon?.url).toBe(url);+ expect(() => parsePluginDownloadResponse({ ...download, sha256: 'bad' }, options)).toThrow(PluginProtocolError);+ });+ it.each([+ 'http://127.0.0.1:43341/dev-local/object',+ 'http://localhost:43340/dev-local/object',+ 'http://remote.example/dev-local/object',+ 'http://127.0.0.1:43340/dev-local/member-upload',+ 'http://127.0.0.1:43340/dev-local/object/other',+ 'http://user:[email protected]:43340/dev-local/object',+ 'http://127.0.0.1:43340/dev-local/object#fragment',+ ])('rejects an object outside the exact development boundary: %s', invalid => {+ expect(() => parsePluginDownloadResponse({ ...download, url: invalid }, options)).toThrow(PluginProtocolError);+ });+ it.each(['http://remote.example', 'http://[email protected]:43340', 'https://127.0.0.1:43340', 'http://127.0.0.1:43340/other'])(+ 'does not turn an invalid development policy into HTTP permission: %s', origin => {+ expect(() => parsePluginDownloadResponse(download, { developmentObjectOrigin: origin })).toThrow(PluginProtocolError);+ },+ );+});diff --git a/packages/plugin-protocol/src/__tests__/manifest.test.ts b/packages/plugin-protocol/src/__tests__/manifest.test.tsindex c3404e45bd..7d59e07cf6 100644--- a/packages/plugin-protocol/src/__tests__/manifest.test.ts+++ b/packages/plugin-protocol/src/__tests__/manifest.test.ts@@ -1938,3 +1938,21 @@ it('validates independent target access without dropping the tasks dependency',const disabled = validateGhostManifest({ ...base, agent: { tasks: true, targets: false } });expect(disabled.ok && disabled.manifest.agent).toEqual({ tasks: true });});++describe('package release notes', () => {+ const base = { schemaVersion: 3, minCindyVersion: '0.1.0', id: 'notes-test', name: 'Notes test', version: '1.0.0', entry: 'main.js' };+ it('keeps old packages without notes installable', () => {+ const result = validateGhostManifest(base);+ expect(result.ok).toBe(true);+ if (result.ok) expect(result.manifest).not.toHaveProperty('releaseNotes');+ });+ it('retains the complete package text without turning it into manifest summary', () => {+ const releaseNotes = 'First change\nSecond change\n' + 'More changes '.repeat(500);+ const result = validateGhostManifest({ ...base, releaseNotes });+ expect(result.ok).toBe(true);+ if (result.ok) expect(result.manifest.releaseNotes).toBe(releaseNotes);+ });+ it('rejects a non-text package releaseNotes', () => {+ expect(validateGhostManifest({ ...base, releaseNotes: { version: '1' } }).ok).toBe(false);+ });+});diff --git a/packages/plugin-protocol/src/__tests__/memberUpload.test.ts b/packages/plugin-protocol/src/__tests__/memberUpload.test.tsindex af5313f155..dd22a59e8d 100644--- a/packages/plugin-protocol/src/__tests__/memberUpload.test.ts+++ b/packages/plugin-protocol/src/__tests__/memberUpload.test.ts@@ -52,7 +52,7 @@ describe('member upload contract', () => {'failed','expired',]);- expect(PLUGIN_MEMBER_RELEASE_REVIEW_STATUSES).toEqual(['pending', 'approved', 'rejected']);+ expect(PLUGIN_MEMBER_RELEASE_REVIEW_STATUSES).toEqual(['pending', 'approved', 'rejected', 'cancelled']);expect(new Set(PLUGIN_MEMBER_UPLOAD_FAILURE_CODES).size).toBe(PLUGIN_MEMBER_UPLOAD_FAILURE_CODES.length,);diff --git a/packages/plugin-protocol/src/delivery.ts b/packages/plugin-protocol/src/delivery.tsindex 90111f6b1c..82d409d29a 100644--- a/packages/plugin-protocol/src/delivery.ts+++ b/packages/plugin-protocol/src/delivery.ts@@ -1,3 +1,4 @@+import { parsePluginObjectUrl, type PluginObjectUrlOptions } from './deliveryObjectUrl.js';import {ghostManifestUsesOidcToken,isValidGhostId,@@ -6,7 +7,6 @@ import {} from './manifest.js';import {PluginProtocolError,- httpsUrl,isoDate,nextCursor,object,@@ -23,6 +23,7 @@ export {isValidPluginNamespace,} from './internal/namespace.js';export { PluginProtocolError } from './internal/parse.js';+export { parsePluginObjectUrl, type PluginObjectUrlOptions } from './deliveryObjectUrl.js';export { isValidPluginResourceId } from './internal/pluginResourceId.js';/** Plugin 客户端 HTTP list/detail envelope 版本;与 ghost.json 版本独立演进。 */@@ -148,6 +149,10 @@ export interface VisiblePluginSummary {description: string | null;/** 客户端兼容 Release manifest 的作者;未声明时为 `null`。 */author: string | null;+ /** Full workflow-owned nickname; omitted by older servers. */+ displayAuthor?: string | null;+ /** Derived from the verified public authorship binding; not a new database column. */+ publisherKind?: 'official' | 'personal' | null;/** Plugin 的来源范围。 */scope: PluginScope;/** Organization 必须是非空组织 ID;Public 和 Personal 恒为 `null`。 */@@ -173,6 +178,10 @@ export interface VisiblePluginDetail {description: string | null;/** 客户端兼容 Release manifest 的作者;未声明时为 `null`。 */author: string | null;+ /** Full workflow-owned nickname; omitted by older servers. */+ displayAuthor?: string | null;+ /** Derived from the verified public authorship binding; not a new database column. */+ publisherKind?: 'official' | 'personal' | null;/** Plugin 的来源范围。 */scope: PluginScope;/** Organization 必须是非空组织 ID;Public 和 Personal 恒为 `null`。 */@@ -268,7 +277,7 @@ export interface PluginDownloadResponse {sizeBytes: number;}-function parseIconMetadata(value: unknown, path: string): PluginIconMetadata | null {+function parseIconMetadata(value: unknown, path: string, options?: PluginObjectUrlOptions): PluginIconMetadata | null {// 老的 v2 服务端尚未提供 icon 字段时,客户端继续使用本地兜底图标。if (value === null || value === undefined) return null;const raw = object(value, path);@@ -287,12 +296,12 @@ function parseIconMetadata(value: unknown, path: string): PluginIconMetadata | nmimeType,sha256: sha256(raw.sha256, `${path}.sha256`),sizeBytes: raw.sizeBytes,- url: httpsUrl(raw.url, `${path}.url`),+ url: parsePluginObjectUrl(raw.url, `${path}.url`, options),expiresAt: isoDate(raw.expiresAt, `${path}.expiresAt`),};}-function parseReleaseSummary(value: unknown, path: string): PluginReleaseSummary {+function parseReleaseSummary(value: unknown, path: string, options?: PluginObjectUrlOptions): PluginReleaseSummary {const raw = object(value, path);const version = string(raw.version, `${path}.version`, 32);if (@@ -308,13 +317,13 @@ function parseReleaseSummary(value: unknown, path: string): PluginReleaseSummarysha256: sha256(raw.sha256, `${path}.sha256`),sizeBytes: raw.sizeBytes,publishedAt: isoDate(raw.publishedAt, `${path}.publishedAt`),- icon: parseIconMetadata(raw.icon, `${path}.icon`),+ icon: parseIconMetadata(raw.icon, `${path}.icon`, options),};}-function parseReleaseDetail(value: unknown, ghostId: string, path: string): PluginReleaseDetail {+function parseReleaseDetail(value: unknown, ghostId: string, path: string, options?: PluginObjectUrlOptions): PluginReleaseDetail {const raw = object(value, path);- const summary = parseReleaseSummary(raw, path);+ const summary = parseReleaseSummary(raw, path, options);const validatedManifest = validateGhostManifest(raw.manifest);if (!validatedManifest.ok) {throw new PluginProtocolError(`${path}.manifest 不合法: ${validatedManifest.reason}`);@@ -376,6 +385,10 @@ function parseVisiblePluginBase(name: string;description: string | null;author: string | null;+ /** Full workflow-owned nickname; omitted by older servers. */+ displayAuthor?: string | null;+ /** Derived from the verified public authorship binding; not a new database column. */+ publisherKind?: 'official' | 'personal' | null;scope: PluginScope;namespace?: string | null;organizationId: string | null;@@ -385,6 +398,10 @@ function parseVisiblePluginBase(if (!isValidPluginResourceId(raw.id)) throw new PluginProtocolError(`${path}.id 不合法`);if (!isValidGhostId(raw.ghostId)) throw new PluginProtocolError(`${path}.ghostId 不合法`);const scope = parseScope(raw.scope, path);+ if (raw.publisherKind !== undefined && raw.publisherKind !== null+ && (scope !== 'public' || (raw.publisherKind !== 'official' && raw.publisherKind !== 'personal'))) {+ throw new PluginProtocolError(`${path}.publisherKind 不合法`);+ }const organizationId = parseScopedOrganizationId(scope, raw.organizationId, path);const identity = parseScopedNamespace(raw, scope, path);if (typeof raw.defaultInstall !== 'boolean') {@@ -398,6 +415,8 @@ function parseVisiblePluginBase(description:raw.description === null ? null : string(raw.description, `${path}.description`, 300),author: raw.author === null ? null : string(raw.author, `${path}.author`),+ ...(raw.displayAuthor === undefined ? {} : { displayAuthor: raw.displayAuthor === null ? null : string(raw.displayAuthor, `${path}.displayAuthor`, 100) }),+ ...(raw.publisherKind === undefined ? {} : { publisherKind: raw.publisherKind as 'official' | 'personal' | null }),scope,...identity,organizationId,@@ -405,7 +424,7 @@ function parseVisiblePluginBase(};}-function parseVisiblePluginSummary(value: unknown, index: number): VisiblePluginSummary {+function parseVisiblePluginSummary(value: unknown, index: number, options?: PluginObjectUrlOptions): VisiblePluginSummary {const path = `plugins[${index}]`;const { raw, ...base } = parseVisiblePluginBase(value, path);const downloadStatistics = parsePluginDownloadStatistics(raw.downloadStatistics);@@ -413,17 +432,18 @@ function parseVisiblePluginSummary(value: unknown, index: number): VisiblePlugin...base,...(parsePluginUsageStatistics(raw.usageStatistics) ? { usageStatistics: parsePluginUsageStatistics(raw.usageStatistics) } : {}),...(downloadStatistics ? { downloadStatistics } : {}),- currentRelease: parseReleaseSummary(raw.currentRelease, `${path}.currentRelease`),+ currentRelease: parseReleaseSummary(raw.currentRelease, `${path}.currentRelease`, options),};}-function parseVisiblePluginDetail(value: unknown, path: string): VisiblePluginDetail {+function parseVisiblePluginDetail(value: unknown, path: string, options?: PluginObjectUrlOptions): VisiblePluginDetail {const { raw, ...parsed } = parseVisiblePluginBase(value, path);const downloadStatistics = parsePluginDownloadStatistics(raw.downloadStatistics);const currentRelease = parseReleaseDetail(raw.currentRelease,parsed.ghostId,`${path}.currentRelease`,+ options,);if (ghostManifestUsesOidcToken(currentRelease.manifest) && parsed.scope !== 'organization') {throw new PluginProtocolError(@@ -530,13 +550,13 @@ function parseCurrentOrganization(value: unknown): PluginCurrentOrganization | n* `null`;对象存在但缺少 `pluginPrefix` 键时抛错。`organizationAccessError`* 缺失时不保留;出现时必须同时有组织身份,且不能夹带企业条目或清理通告。*/-export function parseListPluginsResponse(value: unknown): ListPluginsResponse {+export function parseListPluginsResponse(value: unknown, options?: PluginObjectUrlOptions): ListPluginsResponse {const raw = object(value, 'response');if (raw.schemaVersion !== PLUGIN_API_SCHEMA_VERSION) {throw new PluginProtocolError(`response.schemaVersion 必须为 ${PLUGIN_API_SCHEMA_VERSION}`);}if (!Array.isArray(raw.plugins)) throw new PluginProtocolError('response.plugins 必须是数组');- const plugins = raw.plugins.map(parseVisiblePluginSummary);+ const plugins = raw.plugins.map((plugin, index) => parseVisiblePluginSummary(plugin, index, options));const removals = parseRemovals(raw.removals);const currentOrganization = parseCurrentOrganization(raw.currentOrganization);const organizationAccessError = parseOrganizationAccessError(raw.organizationAccessError);@@ -599,24 +619,24 @@ export function assertPluginListOrganizationNamespace(* 除通用字段校验外,还要求 manifest 的 id、version 和展示字段与外层数据一致。* 校验失败时抛出 `PluginProtocolError`。*/-export function parseGetPluginResponse(value: unknown): GetPluginResponse {+export function parseGetPluginResponse(value: unknown, options?: PluginObjectUrlOptions): GetPluginResponse {const raw = object(value, 'response');if (raw.schemaVersion !== PLUGIN_API_SCHEMA_VERSION) {throw new PluginProtocolError(`response.schemaVersion 必须为 ${PLUGIN_API_SCHEMA_VERSION}`);}return {schemaVersion: PLUGIN_API_SCHEMA_VERSION,- plugin: parseVisiblePluginDetail(raw.plugin, 'response.plugin'),+ plugin: parseVisiblePluginDetail(raw.plugin, 'response.plugin', options),};}/*** 解析并规范化当前 Release 的短期下载凭证。*- * 只接受 HTTPS URL、UTC 时间、合法 SHA-256 和正整数文件大小;校验失败时抛出+ * 默认只接受 HTTPS URL;Host 可显式启用受限本地开发对象地址。UTC 时间、SHA-256 和大小仍严格校验;失败时抛出* `PluginProtocolError`。*/-export function parsePluginDownloadResponse(value: unknown): PluginDownloadResponse {+export function parsePluginDownloadResponse(value: unknown, options?: PluginObjectUrlOptions): PluginDownloadResponse {const raw = object(value, 'response');if (typeof raw.sizeBytes !== 'number' ||@@ -646,7 +666,7 @@ export function parsePluginDownloadResponse(value: unknown): PluginDownloadRespo...identity,}: {}),- url: httpsUrl(raw.url, 'response.url'),+ url: parsePluginObjectUrl(raw.url, 'response.url', options),expiresAt: isoDate(raw.expiresAt, 'response.expiresAt'),sha256: sha256(raw.sha256, 'response.sha256'),sizeBytes: raw.sizeBytes,diff --git a/packages/plugin-protocol/src/deliveryObjectUrl.ts b/packages/plugin-protocol/src/deliveryObjectUrl.tsnew file mode 100644index 0000000000..4f3f464f80--- /dev/null+++ b/packages/plugin-protocol/src/deliveryObjectUrl.ts@@ -0,0 +1,28 @@+import { httpsUrl, PluginProtocolError, string } from './internal/parse.js';++/** Host-only opt-in. Packaged clients must never supply this development origin. */+export interface PluginObjectUrlOptions {+ developmentObjectOrigin?: string;+}++/** Delivery objects default to HTTPS; only the exact local storage adapter may use HTTP. */+export function parsePluginObjectUrl(+ value: unknown,+ path: string,+ options?: PluginObjectUrlOptions,+): string {+ const text = string(value, path, 8_192);+ let url: URL;+ try { url = new URL(text); } catch { throw new PluginProtocolError(`${path} 必须是 HTTPS URL`); }+ if (url.username || url.password) throw new PluginProtocolError(`${path} 不允许 URL 用户信息`);+ if (url.protocol === 'https:') return httpsUrl(text, path);+ if (options?.developmentObjectOrigin) {+ let origin: URL | undefined;+ try { origin = new URL(options.developmentObjectOrigin); } catch { /* Reject invalid policy. */ }+ if (origin && origin.origin === options.developmentObjectOrigin &&+ origin.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(origin.hostname) &&+ !origin.username && !origin.password && url.protocol === 'http:' &&+ url.origin === origin.origin && url.pathname === '/dev-local/object' && !url.hash) return text;+ }+ throw new PluginProtocolError(`${path} 必须是 HTTPS URL`);+}diff --git a/packages/plugin-protocol/src/manifest.ts b/packages/plugin-protocol/src/manifest.tsindex 454fb15ea0..9f14a764f6 100644--- a/packages/plugin-protocol/src/manifest.ts+++ b/packages/plugin-protocol/src/manifest.ts@@ -884,6 +884,8 @@ export interface GhostManifest {name: string;/** 版本字符串(不强制 semver,仅展示用)。 */version: string;+ /** 本版本相对上一实际发布包的完整更新说明;旧包可省略。纯文本。 */+ releaseNotes?: string;/*** 安装此 Release 所需的最低 Cindy 客户端版本。缺省表示不限制客户端版本;* 声明时必须是合法 SemVer,客户端与 Plugin Server 使用同一比较语义。@@ -1179,6 +1181,7 @@ const GHOST_MANIFEST_KNOWN_TOP_LEVEL_FIELDS = new Set(['id','name','version',+ 'releaseNotes','minCindyVersion','author','locales',@@ -1393,6 +1396,9 @@ export function validateGhostManifest(value: unknown): ManifestValidation {) {return { ok: false, reason: 'version 必须是 1–32 字符的非空字符串' };}+ if (raw.releaseNotes !== undefined && typeof raw.releaseNotes !== 'string') {+ return { ok: false, reason: 'releaseNotes 必须是纯文本字符串' };+ }if (raw.minCindyVersion !== undefined &&(typeof raw.minCindyVersion !== 'string' || !isValidCindyVersion(raw.minCindyVersion))@@ -3798,6 +3804,7 @@ export function validateGhostManifest(value: unknown): ManifestValidation {id: raw.id,name: raw.name,version: raw.version,+ ...(raw.releaseNotes !== undefined ? { releaseNotes: raw.releaseNotes as string } : {}),...(raw.minCindyVersion !== undefined? { minCindyVersion: raw.minCindyVersion as string }: {}),diff --git a/packages/plugin-protocol/src/memberUpload.ts b/packages/plugin-protocol/src/memberUpload.tsindex ecae837123..65cdc050f5 100644--- a/packages/plugin-protocol/src/memberUpload.ts+++ b/packages/plugin-protocol/src/memberUpload.ts@@ -42,7 +42,7 @@ export const PLUGIN_MEMBER_UPLOAD_STATUSES = [export type PluginMemberUploadStatus = (typeof PLUGIN_MEMBER_UPLOAD_STATUSES)[number];/** Release review state after a member upload has produced a Release. */-export const PLUGIN_MEMBER_RELEASE_REVIEW_STATUSES = ['pending', 'approved', 'rejected'] as const;+export const PLUGIN_MEMBER_RELEASE_REVIEW_STATUSES = ['pending', 'approved', 'rejected', 'cancelled'] as const;export type PluginMemberReleaseReviewStatus =(typeof PLUGIN_MEMBER_RELEASE_REVIEW_STATUSES)[number];diff --git a/scripts/__tests__/restart-desktop-remote.test.mjs b/scripts/__tests__/restart-desktop-remote.test.mjsindex 5237d6e502..5806b66e10 100644--- a/scripts/__tests__/restart-desktop-remote.test.mjs+++ b/scripts/__tests__/restart-desktop-remote.test.mjs@@ -35,6 +35,7 @@ import {productionUserDataDir,readDesktopStartupStatus,parseWorktreePaths,+ osascriptCloseDarwinTerminalTtyArgs,osascriptLaunchDarwinTerminalArgs,writeDarwinTerminalLaunchScript,darwinTerminalSourceCommand,@@ -89,6 +90,30 @@ function appleScriptLines(args) {// macOS / Windows 上都与生产实际所见一致——硬编码 POSIX 字面量只在 *nix 成立。const stepScript = (root, name) => path.join(root, "scripts", name);+test("macOS Terminal cleanup returns before contacting an app that is not running", () => {+ const lines = appleScriptLines(osascriptCloseDarwinTerminalTtyArgs("/dev/ttys002"));+ assert.equal(lines[0], "on closeMatchingTerminalTab(targetTty)");+ assert.equal(lines[1], 'if application id "com.apple.Terminal" is not running then return');+ assert.equal(lines[2], 'tell application id "com.apple.Terminal"');+ assert.ok(!lines.includes("activate"), "cleanup must not activate Terminal");+});++test("macOS Terminal cleanup only exits the matching tab and passes the tty as data", () => {+ const tty = '/dev/ttys002" & do shell script "echo unexpected';+ const args = osascriptCloseDarwinTerminalTtyArgs(tty);+ const lines = appleScriptLines(args);+ const matchIndex = lines.indexOf("if (tty of terminalTab) is targetTty then");+ const exitIndex = lines.indexOf('if busy of terminalTab is false then do script "exit" in terminalTab');++ assert.notEqual(matchIndex, -1);+ assert.ok(exitIndex > matchIndex, "exit must target an existing tab with the exact tty");+ assert.deepEqual(lines.filter((line) => line.includes("do script")), [+ 'if busy of terminalTab is false then do script "exit" in terminalTab',+ ]);+ assert.equal(args.at(-1), tty);+ assert.ok(lines.every((line) => !line.includes(tty)), "tty must not be interpolated into AppleScript");+});+test("macOS Terminal launch runs command before activating Terminal", () => {const lines = appleScriptLines(osascriptLaunchDarwinTerminalArgs("echo test"));const doScriptIndex = lines.indexOf("set targetTab to do script devCommand");diff --git a/scripts/restart-desktop-remote.mjs b/scripts/restart-desktop-remote.mjsindex 8fe4ef0022..b8438cce69 100644--- a/scripts/restart-desktop-remote.mjs+++ b/scripts/restart-desktop-remote.mjs@@ -54,7 +54,9 @@ function desktopEnvSpec() {}const closeDarwinTerminalTtyScript = Object.freeze(['on closeMatchingTerminalTab(targetTty)',- 'tell application "Terminal"',+ // 查询运行状态不会启动应用;直接 tell 会在清理 iTerm 的 TTY 时误开 Terminal。+ 'if application id "com.apple.Terminal" is not running then return',+ 'tell application id "com.apple.Terminal"','repeat with terminalWindow in windows','repeat with terminalTab in tabs of terminalWindow','if (tty of terminalTab) is targetTty then',@@ -544,7 +546,7 @@ export function readDesktopDevLogTail(logPath, maxLines = 40) {return lines.slice(-maxLines);}-function osascriptCloseDarwinTerminalTtyArgs(ttyPath) {+export function osascriptCloseDarwinTerminalTtyArgs(ttyPath) {return closeDarwinTerminalTtyScript.flatMap((line) => ['-e', line]).concat(ttyPath);