Skip to content

armgit / cindy

Public Imported from GitHub
0

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

refactor(plugins): 收缩提审状态并移除匿名设置

liugaowei70f4901dab72
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.md
index e5c9eba826..f655f5337c 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
@@ -67,7 +67,7 @@ Desktop 信任来源已经完成的版本选择,不再按 `minCindyVersion`
首次上架可省略,插件用途写在 `description`。插件曾上架后再提审时,须完整覆盖相对上一已上架版本的变化,不只写最近一次修改。
上方只是写法示例,须按真实实现改写;骨架不自动生成说明,也不能从版本号猜变化。
缺字段的包仍能本地打包、安装;仅曾上架插件的后续提审要求非空说明,通过本地打包不表示可以提审。
-发布预检与提审流程见 §7.3,署名与匿名设置见 §7.4。
+发布预检与提审流程见 §7.3,平台署名规则见 §7.4。
### 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.md
index 30163d6b0e..0de8e5fda2 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
@@ -89,7 +89,7 @@
安装与运行批准不证明作者身份,也不授予公开发布权。首次发布只接受 Host 可核实的本地包或 Forge 开发安装,属于等待人工审核的发布申请,不是作者认证。
官方 public 插件必须通过 GitHub 仓库提交修改,不允许经客户端(含 Agent 工具)提审,以保证仓库源码完整、便于后续维护。普通第三方公共插件仍沿既有授权流程。
从公共市场下载的第三方插件,只有当前账号已有精确提交授权且 Host 核实原安装来源时才能提交更新;Git/本地自定义市场、私域或来源无法确认的安装不能转作首发。
-可读取发布历史不等于可提交更新。旧发布回执、同名、包内 author 或相同包摘要均不能替代当前授权;恢复原操作也重新核对账号、安装、批准与来源。
+可读取发布历史不等于可提交更新。旧发布回执、同名、包内 author 或相同包摘要均不能替代当前授权;提交时仍核对账号、安装、批准与来源。
已有明确公开发布委托时,先读取摘要并确认包内说明适用,再调用
`ghost_contribution_submit({ prepared_id })`。Full Access 直接执行,Auto 走现有审阅,Ask 走既有权限卡,
不要求额外的最后人工点击。Host 在提交前再次检查已安装内容,变更后必须刷新摘要,不能悄悄替换包。
@@ -104,9 +104,9 @@
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_contribution_status({ local_id })` 查询到本次动作结束。
+202 / processing 仅表示提交仍在处理,不等于待审核;结束后用 `ghost_my_plugins` 查看审核结果。
+没有上传记录列表或 resume 参数。不要自行重复提交;网络结果尚未确认时,Host 在下一次正常提交中先核对同一服务端请求,避免重复提审。
只有服务端回执、实际审核及市场可用事实才能说明已提审、已通过或已上架。
`ghost_my_plugins` 的 plugin_id 读详情,submission_id 读精确留存包内容,cursor 为分页。
@@ -118,16 +118,15 @@ plugin_id、release_id、sha256 和 revision;取消保留版本与记录,当
不让审核人修包、不依赖先上线分享页。
已有 public 插件权限由服务端精确 ACL 决定,包内署名、本地安装与同名均不证明权利;私域不经此入口转公域。
-## 7.4 个人署名与匿名设置
+## 7.4 平台署名
-个人社区插件默认匿名;匿名是整款插件的服务端设置,与当前查看的版本无关。
-只有固定原作者可随时在“我的插件”的管理页名称右侧修改;安装或提交资格都不能代替原作者匿名修改权。
-当前 Agent 工具可查询发布详情,不提供修改匿名的能力;不要通过写文件或调用未声明接口代改。
+个人投稿暂不返回平台展示署名;服务端仍完整保存作者绑定、提审昵称快照和审计记录。
+客户端保留原有署名展示逻辑,以服务端返回值为准,不从包内信息或当前账号昵称补齐。
+客户端界面与 Agent 工具均不提供匿名设置,不要通过写文件或调用未声明接口修改匿名状态。
不要在 `ghost.json` 中添加 `anonymous` 字段;包内 `author` 也不能指定平台的可信发布署名。
-关闭匿名后显示相应版本提审时保存的原作者账号昵称。修改账号昵称不会自动改变旧版;
-原作者下次提审时保存新昵称。当前个人发布按单作者流程使用,不提供多人协作入口。
-匿名隐藏平台展示的署名和作者搜索资料,不会清除作者写进源码、README 或包内的个人信息。
+昵称按相应版本提审时的账号信息保存,改名不改写旧快照。当前个人发布按单作者流程使用,不提供多人协作入口。
+隐藏平台展示署名不会清除作者写进源码、README 或包内的个人信息。
历史内容和更新说明按对应版本的提审快照展示,不用当前本地包补写历史。
-可信官方来源固定署名 Cindy,不显示个人匿名开关;组织插件沿用原有发布与署名规则。
-缺少作者关系或当前服务端不提供设置时,不推断为可编辑原作者,也不把本地安装当作作者资格。
+可信官方来源固定署名 Cindy;组织插件沿用原有发布与署名规则。
+不把本地安装或提交资格当作作者身份。
diff --git a/apps/desktop/src/main/mcp-integrations/ghost.ts b/apps/desktop/src/main/mcp-integrations/ghost.ts
index 0c547dd4ec..3b58edd543 100644
--- a/apps/desktop/src/main/mcp-integrations/ghost.ts
+++ b/apps/desktop/src/main/mcp-integrations/ghost.ts
@@ -1789,13 +1789,13 @@ export function getCindyGhostsMcpDeps(
} : {}),
async communityContribution(input) {
try {
- const authority = await contributionAuthority(['prepare', 'submit', 'resume', 'cancel', 'cancel-review'].includes(input.action));
+ const authority = await contributionAuthority(['prepare', 'submit', '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') {
+ } else if (input.action === 'submit' || 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 ?? '')) {
@@ -1803,7 +1803,7 @@ export function getCindyGhostsMcpDeps(
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;
+ 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 : undefined;
if (!prepared) throwIpcError('PRECONDITION_FAILED', 'Contribution preparation is unavailable');
const context = authority.context;
const live = hostDeps.getLiveSessionGrantState!(context.sessionId!, context.sessionInstanceId!);
@@ -1840,13 +1840,12 @@ export function getCindyGhostsMcpDeps(
}
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.assertAccepted) : await community.resumeContribution(input.id, authority.assertAccepted);
+ result = input.action === 'cancel-review' ? await community.cancelPluginReview(input.pluginId, input.release, authority.assert) : await community.submitContribution(input.id, authority.assertAccepted);
} 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) {
diff --git a/apps/desktop/src/main/plugin-contributions/__tests__/host.test.ts b/apps/desktop/src/main/plugin-contributions/__tests__/host.test.ts
index c3375f485d..7959cf7d83 100644
--- a/apps/desktop/src/main/plugin-contributions/__tests__/host.test.ts
+++ b/apps/desktop/src/main/plugin-contributions/__tests__/host.test.ts
@@ -11,7 +11,7 @@ import type {
ContributionOperation,
SubmissionView,
} from '../../../shared/pluginContributionContract';
-import type { PreparedEntry } from '../prepared';
+import { releasePreparedContribution, type PreparedEntry } from '../prepared';
import { installedGhostStoragePart } from '../../../shared/pluginIdentity';
import { PluginMarketLedger } from '../../plugin-market/ledger';
@@ -71,7 +71,13 @@ vi.mock('../prepared', () => ({
assertContributionOwner: (owner: string) => {
if (owner !== harness.owner) throw new Error('[OWNER_CHANGED] changed');
},
- assertPreparedInstallation: vi.fn(),
+ assertPreparedInstallation: (entry: PreparedEntry) => {
+ const { source } = harness.readInstallation(entry.summary.instanceId, {
+ directory: entry.installationDir, approvalToken: entry.approvalToken,
+ });
+ if (JSON.stringify(source) !== entry.publishingSourceKey)
+ throw createIpcError('PRECONDITION_FAILED', 'Publishing source changed');
+ },
assertPreparedContent: harness.verifyContent,
readContributionInstallation: harness.readInstallation,
prepareInstalledContribution: harness.snapshot,
@@ -80,11 +86,12 @@ vi.mock('../prepared', () => ({
}));
vi.mock('../api', () => ({
ContributionApi: class {
+ constructor(private readonly guard?: () => Promise<void>) {}
readonly owner = harness.owner;
preflight = harness.preflight;
- prepare = harness.prepare;
+ prepare = async (...args: unknown[]) => { await this.guard?.(); return harness.prepare(...args); };
operation = harness.operation;
- commit = harness.commit;
+ commit = async (...args: unknown[]) => { await this.guard?.(); return harness.commit(...args); };
list = harness.list;
detail = harness.detail;
releases = harness.releases;
@@ -248,7 +255,7 @@ afterEach(async () => {
await fsp.rm(harness.root, { recursive: true, force: true });
});
-describe('community contribution recovery', () => {
+describe('community submission', () => {
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' } });
@@ -265,24 +272,9 @@ describe('community contribution recovery', () => {
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.entry!.publishingSourceKey = JSON.stringify(harness.ghosts[0].publishingSource);
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' } });
@@ -290,60 +282,6 @@ describe('community contribution recovery', () => {
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 } } });
@@ -358,7 +296,7 @@ describe('community contribution recovery', () => {
harness.prepare.mockResolvedValueOnce(response);
await host.prepareContribution('hello', 'manual');
await host.submitContribution('prepared-1');
- await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('complete'));
+ await vi.waitFor(() => expect(host.contributionTransferStatus('prepared-1').stage).toBe('complete'));
expect(harness.put).toHaveBeenCalledExactlyOnceWith(expect.anything(), expect.objectContaining({ putUrl: response.upload.putUrl }));
});
@@ -378,7 +316,7 @@ describe('community contribution recovery', () => {
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' }));
+ await vi.waitFor(() => expect(host.contributionTransferStatus('prepared-1')).toMatchObject({ stage: 'complete', errorCode: 'PRECONDITION_FAILED' }));
expect(harness.put).not.toHaveBeenCalled();
expect(harness.commit).not.toHaveBeenCalled();
});
@@ -391,158 +329,179 @@ describe('community contribution recovery', () => {
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' }));
+ await vi.waitFor(() => expect(host.contributionTransferStatus('prepared-1')).toMatchObject({ stage: 'complete', 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];
+ const result = host.contributionTransferStatus('prepared-1');
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');
+ await vi.waitFor(() => expect(host.contributionTransferStatus('prepared-1').stage).toBe('complete'));
+ expect(host.contributionTransferStatus('prepared-1').stage).toBe('complete');
});
- it('refuses out-of-bounds cleanup paths loaded from a recovery journal', async () => {
- harness.prepare.mockRejectedValueOnce(new Error('offline'));
+ // Unit regressions through prepare/submit/status: removing upload recovery must
+ // preserve owner/ACL guards and prevent a lost commit from submitting twice.
+ function pendingRows(): unknown[] {
+ const dir = path.join(harness.root, 'plugin-contributions');
+ const file = fs.existsSync(dir) && fs.readdirSync(dir).find(name => name.startsWith('pending-'));
+ return file ? JSON.parse(fs.readFileSync(path.join(dir, file), 'utf8')) : [];
+ }
+ async function prepareAgain(id = 'prepared-2') {
+ harness.entry = { ...harness.entry!, owner: harness.owner, pinned: false,
+ summary: { ...harness.entry!.summary, preparedId: id },
+ idempotencyKey: '00000000-0000-4000-8000-000000000003' };
+ return host.prepareContribution('hello', 'manual');
+ }
+ async function finished(id = 'prepared-1') {
+ await vi.waitFor(() => expect(host.contributionTransferStatus(id).stage).toBe('complete'));
+ return host.contributionTransferStatus(id);
+ }
+ it('releases a failed pre-commit snapshot without creating persistent upload history', async () => {
+ harness.prepare.mockRejectedValueOnce(new Error('prepare response lost'));
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');
+ expect((await finished()).errorCode).toBe('INTERNAL');
+ expect(pendingRows()).toEqual([]);
+ expect(harness.put).not.toHaveBeenCalled();
+ expect(harness.commit).not.toHaveBeenCalled();
+ expect(releasePreparedContribution).toHaveBeenCalledWith('prepared-1');
});
-});
-
-
-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'));
+ it('resolves a lost commit through the normal submit action without re-uploading or saving terminal history', async () => {
+ harness.commit.mockRejectedValueOnce(new Error('commit response lost'));
+ await host.prepareContribution('hello', 'manual');
+ await host.submitContribution('prepared-1');
+ await finished();
+ expect(pendingRows()).toEqual([expect.objectContaining({ operationId: 'operation-1', contentSha256: sha })]);
+ expect(JSON.stringify(pendingRows())).not.toContain('plugin.cindy');
+ expect(JSON.stringify(pendingRows())).not.toContain('receipt');
+ await prepareAgain();
+ await host.submitContribution('prepared-2');
+ const result = await finished('prepared-2');
+ expect(result.operation?.receipt?.uploadedPackage.sha256).toBe(sha);
+ expect(result.operation?.receipt?.releaseRevision.sha256).toBe(revision.sha256);
+ expect(harness.prepare).toHaveBeenCalledTimes(1);
+ expect(harness.put).toHaveBeenCalledTimes(1);
+ expect(harness.commit).toHaveBeenCalledTimes(1);
+ expect(pendingRows()).toEqual([]);
+ });
+ it.each(['validating', 'publishing'] as const)('confirms the same %s commit without a separate resume capability', async status => {
+ harness.commit.mockRejectedValueOnce(new Error('commit response lost'));
+ await host.prepareContribution('hello', 'manual');
+ await host.submitContribution('prepared-1');
+ await finished();
+ const calls: string[] = [];
+ harness.operation.mockImplementationOnce(async () => { calls.push('get'); return operation(status); });
+ harness.commit.mockImplementationOnce(async () => { calls.push('commit'); });
+ await prepareAgain();
+ await host.submitContribution('prepared-2');
+ expect((await finished('prepared-2')).operation?.status).toBe('succeeded');
+ expect(calls).toEqual(['get', 'commit']);
+ expect(harness.prepare).toHaveBeenCalledTimes(1);
+ expect(harness.put).toHaveBeenCalledTimes(1);
+ expect(harness.commit).toHaveBeenCalledTimes(2);
+ });
+ it.each(['revoked', 'official'] as const)('refuses another write when the pending target becomes %s', async condition => {
+ harness.preflight.mockResolvedValue({ ...(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 finished();
+ await prepareAgain();
+ harness.operation.mockResolvedValueOnce(operation('publishing'));
+ harness.detail.mockResolvedValue({ ...ownDetail(), plugin: { ...ownPlugin(),
+ publisherKind: condition === 'official' ? 'official' : 'personal',
+ actions: { canSubmit: condition !== 'revoked', canViewMarket: true } } });
+ await host.submitContribution('prepared-2');
+ expect((await finished('prepared-2')).errorCode).toBe(condition === 'official' ? 'OFFICIAL_PLUGIN_GITHUB_REQUIRED' : 'PERMISSION_DENIED');
+ expect(harness.operation).toHaveBeenCalledWith('operation-1');
+ expect(harness.commit).toHaveBeenCalledTimes(1);
+ expect(harness.put).toHaveBeenCalledTimes(1);
+ });
+ it('does not start another version while an earlier commit remains unconfirmed', 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'));
+ await finished();
+ await prepareAgain();
+ harness.entry!.contentSha256 = 'c'.repeat(64);
+ harness.operation.mockResolvedValueOnce(operation('publishing'));
+ await host.submitContribution('prepared-2');
+ expect((await finished('prepared-2')).errorCode).toBe('INTERNAL');
+ expect(harness.commit).toHaveBeenCalledTimes(1);
+ expect(harness.prepare).toHaveBeenCalledTimes(1);
+ expect(pendingRows()).toHaveLength(1);
+ });
+ it('keeps duplicate clicks on the same active submission instead of starting another upload', async () => {
+ const gate = deferred<ReturnType<typeof uploadResponse>>();
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));
+ await host.submitContribution('prepared-1');
+ await prepareAgain();
+ const duplicate = await host.submitContribution('prepared-2');
+ expect(duplicate.localId).toBe('prepared-1');
gate.resolve(uploadResponse());
- await vi.waitFor(() => expect(host.listContributionTransfers()[0].stage).toBe('complete'));
+ await finished();
+ expect(harness.prepare).toHaveBeenCalledTimes(1);
expect(harness.put).toHaveBeenCalledTimes(1);
expect(harness.commit).toHaveBeenCalledTimes(1);
});
+ 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', 'installation changed'); });
+ 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');
+ expect((await finished()).errorCode).toBe('MUTATION_CANCELLED');
+ expect(callbackReturned && uploadAborted).toBe(true);
+ expect(harness.commit).not.toHaveBeenCalled();
+ });
+ it('rechecks the accepted AI permission before commit after an asynchronous upload', async () => {
+ const caller = vi.fn(async () => undefined);
+ harness.put.mockImplementationOnce(async () => {
+ caller.mockRejectedValue(createIpcError('PERMISSION_DENIED', 'task permissions changed'));
+ });
+ await host.prepareContribution('hello', 'ai');
+ await host.submitContribution('prepared-1', caller);
+ expect((await finished()).errorCode).toBe('PERMISSION_DENIED');
+ expect(harness.put).toHaveBeenCalledTimes(1);
+ expect(harness.commit).not.toHaveBeenCalled();
+ });
+ it('does not let an old account generation overwrite a newly confirmed result', async () => {
+ const gate = deferred<void>();
+ harness.commit.mockReturnValueOnce(gate.promise);
+ await host.prepareContribution('hello', 'manual');
+ await host.submitContribution('prepared-1');
+ await vi.waitFor(() => expect(harness.commit).toHaveBeenCalledTimes(1));
+ harness.owner = `A:${testGeneration}:2`;
+ await prepareAgain();
+ await host.submitContribution('prepared-2');
+ await finished('prepared-2');
+ expect(pendingRows()).toEqual([]);
+ gate.reject(new Error('late failure from the old owner'));
+ await vi.waitFor(() => expect(releasePreparedContribution).toHaveBeenCalledWith('prepared-1'));
+ expect(pendingRows()).toEqual([]);
+ expect(host.contributionTransferStatus('prepared-2').operation?.status).toBe('succeeded');
+ });
+});
+
+describe('submission preview ownership', () => {
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'));
@@ -558,7 +517,7 @@ describe('admission summary and transfer ownership', () => {
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'));
+ await vi.waitFor(() => expect(host.contributionTransferStatus('prepared-1').stage).toBe('complete'));
});
it('keeps a first submission without release notes eligible when the server allows it', async () => {
delete harness.entry!.summary.releaseNotes;
@@ -660,7 +619,7 @@ describe('author installation projection', () => {
} });
expect(harness.snapshot).not.toHaveBeenCalled();
expect(harness.prepare).not.toHaveBeenCalled();
- expect(host.listContributionTransfers()).toEqual([]);
+ expect(harness.commit).not.toHaveBeenCalled();
});
it('does not match another ID or organization namespace, even with the same display name', async () => {
const original = harness.ghosts[0];
@@ -678,8 +637,8 @@ describe('author installation projection', () => {
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');
+ await vi.waitFor(() => expect(host.contributionTransferStatus('prepared-1').stage).toBe('complete'));
+ expect(host.contributionTransferStatus('prepared-1').operation?.status).toBe('succeeded');
expect((await localView()).localInstallation).toMatchObject({ state: 'installed', origin: 'local' });
expect(harness.ghosts).toHaveLength(1);
});
diff --git a/apps/desktop/src/main/plugin-contributions/__tests__/registerIpc.test.ts b/apps/desktop/src/main/plugin-contributions/__tests__/registerIpc.test.ts
index db509c28f8..695ef0289c 100644
--- a/apps/desktop/src/main/plugin-contributions/__tests__/registerIpc.test.ts
+++ b/apps/desktop/src/main/plugin-contributions/__tests__/registerIpc.test.ts
@@ -29,11 +29,9 @@ vi.mock('../host', () => ({
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,
diff --git a/apps/desktop/src/main/plugin-contributions/host.ts b/apps/desktop/src/main/plugin-contributions/host.ts
index b8916f28fe..294322e481 100644
--- a/apps/desktop/src/main/plugin-contributions/host.ts
+++ b/apps/desktop/src/main/plugin-contributions/host.ts
@@ -2,6 +2,7 @@ import crypto from 'node:crypto';
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
import { app } from 'electron';
import { z } from 'zod';
import * as wire from '../../shared/pluginContributionContract.js';
@@ -23,7 +24,6 @@ import {
type InstalledGhost,
} from '../../shared/ghost.js';
import {
- findInstalledGhostByInstanceId,
installedGhostStoragePart,
} from '../../shared/pluginIdentity.js';
import { ownerScopedUserDataPath } from '../appSessionState.js';
@@ -38,126 +38,89 @@ import { isIpcError, isIpcErrorCode } from '../../shared/ipc-errors.js';
import { throwIpcError } from '../utils/ipcValidate.js';
import { ContributionApi } from './api.js';
import {
+ type PreparedEntry,
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(),
+// Only a commit that may have reached the server needs to survive this process.
+// Preparing a ticket and uploading bytes do not create a review submission.
+const pendingCommitSchema = z.object({
+ operationId: z.string(),
request: wire.contributionRequest,
- directory: z.string(),
- approvalToken: z.string(),
- contentSha256: z.string().optional(),
+ instanceId: z.string(),
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(),
+ approvalToken: z.string(),
+ contentSha256: z.string(),
});
-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 }>();
+type PendingCommit = z.infer<typeof pendingCommitSchema>;
+interface Submission {
+ entry: PreparedEntry;
+ request: wire.ContributionRequest;
+ prepared: PreparedEntry['summary'];
+ stage: ContributionTransferView['stage'];
+ operation: wire.ContributionOperation | null;
+ errorCode: string | null;
+ controller: AbortController;
+}
+const submissions = new Map<string, Submission>();
let hooked = false;
-function journal(owner = contributionOwnerKey()): Journal {
+function pendingCommitFile(owner: string): string {
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[] = [];
+ const account = crypto.createHash('sha256').update(contributionAccountKey()).digest('hex');
+ return ownerScopedUserDataPath('plugin-contributions', `pending-${account}.v1.json`);
+}
+function pendingCommits(owner: string): PendingCommit[] {
try {
- records = z
- .array(recordSchema)
- .parse(JSON.parse(fs.readFileSync(file, 'utf8')))
- .filter((entry) => entry.accountKey === accountKey)
- .map((entry) => ({ ...entry, owner }));
+ return z.array(pendingCommitSchema).parse(JSON.parse(fs.readFileSync(pendingCommitFile(owner), 'utf8')));
} 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');
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
+ throwIpcError('PRECONDITION_FAILED', 'Unable to read the unconfirmed submission');
}
- return value;
}
-
-function persist(book: Journal): void {
- assertContributionOwner(book.owner);
+function writePendingCommits(owner: string, values: PendingCommit[]): void {
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);
+ const file = pendingCommitFile(owner);
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ const temporary = `${file}.${crypto.randomUUID()}.tmp`;
+ fs.writeFileSync(temporary, JSON.stringify(values), { mode: 0o600 });
+ fs.renameSync(temporary, file);
+}
+function clearPendingCommit(owner: string, operationId: string): void {
+ const values = pendingCommits(owner);
+ if (values.some(item => item.operationId === operationId))
+ writePendingCommits(owner, values.filter(item => item.operationId !== operationId));
+}
+function view(value: Submission): ContributionTransferView {
+ return { localId: value.entry.summary.preparedId, prepared: value.prepared,
+ stage: value.stage, operation: value.operation, errorCode: value.errorCode };
+}
+function currentSubmission(id: string): Submission {
+ const value = submissions.get(id);
+ if (!value) throwIpcError('NOT_FOUND', 'Current submission not found');
+ assertContributionOwner(value.entry.owner);
+ return value;
}
-function view(record: RecordEntry): ContributionTransferView {
- return {
- localId: record.localId,
- prepared: record.prepared,
- stage: record.stage,
- operation: record.operation,
- errorCode: record.errorCode,
- };
+function terminal(operation: wire.ContributionOperation): boolean {
+ return ['succeeded', 'failed', 'expired'].includes(operation.status);
}
-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 verifyOperation(operation: wire.ContributionOperation, request: wire.ContributionRequest, operationId?: string): void {
+ const receipt = operation.receipt;
+ if ((operationId && operation.operationId !== operationId) || (receipt && (
+ receipt.uploadedPackage.sha256 !== request.sha256 || receipt.uploadedPackage.sizeBytes !== request.sizeBytes ||
+ receipt.ghostId !== request.target.ghostId || receipt.version !== request.target.version ||
+ (request.target.pluginId !== null && receipt.pluginId !== request.target.pluginId)
+ ))) throwIpcError('PRECONDITION_FAILED', 'Submission receipt does not match the package');
}
+
+
function safeCode(error: unknown): string {
if (isIpcError(error)) return error.code;
if (
@@ -175,11 +138,7 @@ export function mapContributionError(error: unknown): never {
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;
+ throwIpcError('PRECONDITION_FAILED', 'Use the active Cindy instance for publishing');
}
function assertClientPublishingTarget(plugin: Pick<wire.MyPluginSummary, 'publisherKind'>): void {
@@ -235,7 +194,7 @@ export async function prepareContribution(
source,
target: preflight.target,
};
- preparedTargets.set(prepared.preparedId, { owner: api.owner, request });
+ entry.request = request;
return prepared;
} catch (error) {
await releasePreparedContribution(prepared.preparedId);
@@ -245,9 +204,8 @@ export async function prepareContribution(
export async function discardContribution(preparedId: string): Promise<void> {
const entry = getPreparedContribution(preparedId);
- // Once submitted, the durable transfer owns these bytes until its terminal cleanup.
+ // A running submission owns its bytes until the current action finishes.
if (entry.pinned) return;
- preparedTargets.delete(preparedId);
await releasePreparedContribution(preparedId);
}
@@ -260,339 +218,169 @@ export async function submitContribution(
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',
- );
+ throwIpcError(blocker?.code && isIpcErrorCode(blocker.code) ? blocker.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);
+ const request = entry.request;
+ if (!request)
+ throwIpcError('PRECONDITION_FAILED', 'Prepare this submission before submitting');
+ const active = [...submissions.values()].find(item => item.entry.owner === entry.owner &&
+ item.request.target.ghostId === request.target.ghostId && item.stage !== 'complete');
+ if (active) {
+ if (active.entry.contentSha256 !== entry.contentSha256 || active.request.target.version !== entry.summary.version ||
+ active.entry.installationDir !== entry.installationDir || active.entry.approvalToken !== entry.approvalToken ||
+ active.entry.publishingSourceKey !== entry.publishingSourceKey)
+ throwIpcError('PRECONDITION_FAILED', 'A submission for this plugin is already running');
+ if (active.entry !== entry) await discardContribution(preparedId);
+ return view(active);
}
- 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);
+ const value: Submission = { entry, prepared: entry.summary, request,
+ stage: 'prepared', operation: null, errorCode: null, controller: new AbortController() };
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';
+ submissions.set(preparedId, value);
+ if (!hooked) {
+ hooked = true;
+ onAuthStateChange(() => {
+ for (const item of submissions.values()) {
+ try { assertContributionOwner(item.entry.owner); }
+ catch { item.controller.abort(); }
}
- })
- .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;
+ onQuit('plugin-contributions', () => {
+ for (const item of submissions.values()) item.controller.abort();
+ }, 'sync');
}
- return absolute;
+ void submit(value, assertCaller).catch(error => {
+ value.errorCode = value.controller.signal.aborted ? 'MUTATION_CANCELLED' : safeCode(error);
+ }).finally(() => {
+ value.stage = 'complete';
+ void releasePreparedContribution(preparedId);
+ // A short-lived result lets the current UI/tool finish reading its progress.
+ // Published versions and history are read from the server, never this map.
+ const timer = setTimeout(() => {
+ if (submissions.get(preparedId) === value) submissions.delete(preparedId);
+ }, 30 * 60_000);
+ timer.unref();
+ });
+ return view(value);
}
-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?.();
+async function submit(value: Submission, assertCaller?: () => Promise<void>): Promise<void> {
+ const { entry, controller } = value;
+ const api = new ContributionApi();
+ const assertCurrent = () => {
+ assertContributionOwner(entry.owner);
+ if (controller.signal.aborted) throwIpcError('MUTATION_CANCELLED', 'Submission stopped');
assertWritableInstance();
- assert();
- if (!authorizedSource || JSON.stringify(assertInstallation().source) !== authorizedSource)
- throwIpcError('PRECONDITION_FAILED', 'Publishing source changed');
- });
+ assertPreparedInstallation(entry);
+ };
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);
+ assertCurrent();
+ if (value.request.target.pluginId) {
+ const target = await api.detail(value.request.target.pluginId);
assertClientPublishingTarget(target.plugin);
- if (!target.plugin.actions.canSubmit || target.plugin.pluginId !== record.request.target.pluginId)
+ if (!target.plugin.actions.canSubmit || target.plugin.pluginId !== value.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);
+ assertCurrent();
};
- if (record.phase === 'prepared') {
- await assertWrite();
- const response = await writer.prepare(record.request, record.key);
- assert();
+ const writer = new ContributionApi(assertWrite);
+ const accept = (operation: wire.ContributionOperation, operationId?: string) => {
+ assertContributionOwner(entry.owner);
+ verifyOperation(operation, value.request, operationId);
+ value.operation = operation;
+ value.errorCode = operation.failure?.code ?? null;
+ if (terminal(operation)) clearPendingCommit(entry.owner, operation.operationId);
+ };
+ assertCurrent();
+ const previous = pendingCommits(entry.owner).find(item => item.request.target.ghostId === value.request.target.ghostId);
+ if (previous) {
+ const operation = await api.operation(previous.operationId);
+ assertCurrent();
+ verifyOperation(operation, previous.request, previous.operationId);
+ const samePackage = previous.instanceId === entry.summary.instanceId &&
+ previous.installationDir === entry.installationDir && previous.approvalToken === entry.approvalToken &&
+ previous.contentSha256 === entry.contentSha256 &&
+ (previous.request.target.pluginId === value.request.target.pluginId ||
+ previous.request.target.pluginId === null && operation.receipt?.pluginId === value.request.target.pluginId) &&
+ previous.request.target.version === entry.summary.version;
+ if (terminal(operation)) {
+ clearPendingCommit(entry.owner, previous.operationId);
+ if (operation.status === 'succeeded' && samePackage) {
+ value.request = previous.request;
+ value.prepared = { ...entry.summary, sha256: previous.request.sha256, sizeBytes: previous.request.sizeBytes };
+ accept(operation, previous.operationId);
+ return;
+ }
+ } else {
+ if (!samePackage) throwIpcError('INTERNAL', 'Previous submission result is not confirmed');
+ value.request = previous.request;
+ value.prepared = { ...entry.summary, sha256: previous.request.sha256, sizeBytes: previous.request.sizeBytes };
+ accept(operation, previous.operationId);
+ }
+ }
+ if (!value.operation) {
+ const response = await writer.prepare(value.request, entry.idempotencyKey);
+ assertCurrent();
const { upload, ...operation } = response;
- await accept(book, record, wire.contributionOperation.parse(operation));
- if (isTerminal(record)) return;
+ accept(wire.contributionOperation.parse(operation));
+ if (terminal(operation)) 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.
+ throwIpcError('PRECONDITION_FAILED', 'Upload ticket expired');
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),
- )
- )
+ const endpoint = new URL(getClientEndpoint('pluginApiBaseUrl'));
+ const localUpload = app.isPackaged === false && endpoint.protocol === 'http:' &&
+ ['127.0.0.1', 'localhost', '[::1]'].includes(endpoint.hostname) && !endpoint.username && !endpoint.password &&
+ url.protocol === 'http:' && 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,
- );
+ const handle = await fsp.open(entry.filePath, 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');
+ if (!stat.isFile() || stat.size !== value.request.sizeBytes ||
+ crypto.createHash('sha256').update(await handle.readFile()).digest('hex') !== value.request.sha256)
+ throwIpcError('PRECONDITION_FAILED', 'Prepared package 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(); }
- },
+ value.stage = 'uploading';
+ await putLocalFile(handle, { putUrl: upload.putUrl, headers: upload.headers, sizeBytes: stat.size,
+ signal: controller.signal,
+ onBytes: () => { try { assertCurrent(); } 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.
+ assertCurrent();
+ const operationId = value.operation!.operationId;
+ // No local package history is needed: after PUT, any ambiguous commit can be
+ // reconciled using this server operation alone. Never re-upload on that path.
+ const values = pendingCommits(entry.owner).filter(item => item.operationId !== operationId);
+ values.push({ operationId, request: value.request, instanceId: entry.summary.instanceId,
+ installationDir: entry.installationDir, approvalToken: entry.approvalToken, contentSha256: entry.contentSha256 });
+ writePendingCommits(entry.owner, values);
+ value.stage = 'processing';
+ await writer.commit(operationId);
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 },
- );
- });
+ assertCurrent();
+ accept(await api.operation(operationId), operationId);
+ if (terminal(value.operation!)) return;
+ await delay(Math.min(1000 * (attempt + 1), 5000), undefined, { signal: controller.signal });
}
- record.stage = 'paused';
- persist(book);
+ throwIpcError('INTERNAL', 'Submission result is not confirmed');
}
-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 contributionTransferStatus(id: string): ContributionTransferView {
+ return view(currentSubmission(id));
}
export function cancelContribution(id: string): void {
- const { record } = locate(id);
- if (running(record)) pending.get(id)?.controller.abort();
+ currentSubmission(id).controller.abort();
}
function releaseView(
diff --git a/apps/desktop/src/main/plugin-contributions/prepared.ts b/apps/desktop/src/main/plugin-contributions/prepared.ts
index 90353ebd4c..2c2595acff 100644
--- a/apps/desktop/src/main/plugin-contributions/prepared.ts
+++ b/apps/desktop/src/main/plugin-contributions/prepared.ts
@@ -2,6 +2,7 @@ import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
+import type { ContributionRequest } from '../../shared/pluginContributionContract.js';
import type {
PreparedPluginContribution,
ContributionInstallationBinding,
@@ -45,6 +46,7 @@ export function assertContributionOwner(owner: string): void {
}
export interface PreparedEntry {
+ request?: ContributionRequest;
owner: string;
approvalToken: string;
contentSha256: string;
@@ -54,7 +56,7 @@ export interface PreparedEntry {
directory: string;
filePath: string;
summary: PreparedPluginContribution;
- /** One operation key for every UI/AI retry of this immutable package. */
+ /** An idempotency key for this fixed package submission. */
idempotencyKey: string;
expiresAt: number;
}
diff --git a/apps/desktop/src/main/plugin-contributions/registerIpc.ts b/apps/desktop/src/main/plugin-contributions/registerIpc.ts
index f43036ef4c..ffe1463846 100644
--- a/apps/desktop/src/main/plugin-contributions/registerIpc.ts
+++ b/apps/desktop/src/main/plugin-contributions/registerIpc.ts
@@ -40,7 +40,6 @@ export function registerPluginContributionsIpc(): void {
({ 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(
@@ -62,7 +61,6 @@ export function registerPluginContributionsIpc(): void {
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));
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 5ab4fe8ac9..420b38de5a 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1607,13 +1607,11 @@ contextBridge.exposeInMainWorld('electronAPI', {
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 } : {}) }),
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
index cbb41c8f90..39321d4078 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx
@@ -1,13 +1,13 @@
+import { useContributionPreview } from './lib/useContributionPreview';
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 type { MyPluginView } from '../../../shared/pluginContributions';
import { featureRetirementById } from '../../../shared/featureRetirements';
import { RetiredFeatureDetail } from './RetiredFeatureDetail';
import { Button } from '@/components/ui/button';
@@ -477,7 +477,6 @@ function LocalGhostPluginPage({
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'));
@@ -1706,42 +1705,6 @@ function LocalGhostPluginPage({
: 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);
@@ -1788,30 +1751,16 @@ function LocalGhostPluginPage({
});
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), {
+ const canPreparePublication = personalContributor && selectedGhost?.publishingSource?.kind === 'local' &&
+ !contributionUnavailableKey && !showMyPlugins && localContributionResult &&
+ !localContributionResult.error && !localContributionResult.plugin;
+ const currentPublicationDraft = useContributionPreview(localContributionKey,
+ canPreparePublication && selectedGhost ? installedGhostStoragePart(selectedGhost) : undefined,
+ selectedGhost?.manifest.version,
+ instanceId => window.electronAPI.pluginContributions.prepare(instanceId, 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]);
+ } : undefined),
+ preparedId => window.electronAPI.pluginContributions.discard(preparedId));
useEffect(() => {
if (showMyPlugins) { setSelectedId(null); setMarketDetail(null); }
}, [showMyPlugins]);
@@ -1868,7 +1817,7 @@ function LocalGhostPluginPage({
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') {
+ while (result.stage !== 'complete') {
if (!contributionMounted.current || contributionOwnerRef.current !== owner) return false;
await new Promise(resolve => window.setTimeout(resolve, 1000));
if (!contributionMounted.current || contributionOwnerRef.current !== owner) return false;
@@ -1985,9 +1934,8 @@ function LocalGhostPluginPage({
) : null;
if (showMyPlugins) return <MyPluginsPage
- key={`${contributionOwner}:${authorRevision}`}
+ key={contributionOwner}
cache={contributionCache.current}
- onAuthorSettingsUpdated={acceptAuthorSettings}
reader={window.electronAPI.pluginContributions}
localPlugins={publishableInstalledItems}
installedPluginCount={allInstalledItems.length}
diff --git a/apps/desktop/src/renderer/features/plugin/MyPluginsPage.tsx b/apps/desktop/src/renderer/features/plugin/MyPluginsPage.tsx
index d8ce633ad3..a87935f1d2 100644
--- a/apps/desktop/src/renderer/features/plugin/MyPluginsPage.tsx
+++ b/apps/desktop/src/renderer/features/plugin/MyPluginsPage.tsx
@@ -14,12 +14,12 @@ 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 { contributionErrorKey, useContributionPreview } from './lib/useContributionPreview';
+export { contributionErrorKey } from './lib/useContributionPreview';
import type {
PluginContributionsApi,
ContributionReleaseView,
@@ -57,17 +57,6 @@ export interface PluginSubmitOptions {
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,
@@ -77,7 +66,6 @@ export function MyPluginsPage({
onPrepare,
onViewLocal,
cache,
- onAuthorSettingsUpdated,
renderVersionFacts,
onInstallPublished,
onReadPublished,
@@ -86,7 +74,6 @@ export function MyPluginsPage({
installedRevision,
}: {
reader: PluginContributionsApi;
- onAuthorSettingsUpdated?: (detail: MyPluginDetailView, appliesToCurrentControl: boolean) => void;
localPlugins: readonly GhostPluginListItem[];
installedPluginCount: number;
cache: MyPluginsPageCache;
@@ -113,15 +100,8 @@ export function MyPluginsPage({
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 [updateDraft, setUpdateDraft] = useState<{
- token: object; prepared?: PreparedPluginContribution; error?: string;
- } | null>(null);
const [updateRefresh, setUpdateRefresh] = useState(0);
- const preparePicker = useRef(onPrepare ?? reader.prepare);
- preparePicker.current = onPrepare ?? reader.prepare;
+ const preparePreview = onPrepare ?? reader.prepare;
const [accountSwitcherOpen, setAccountSwitcherOpen] = useState(false);
const accountTrigger = useRef<HTMLButtonElement>(null);
const { confirm } = useConfirmDialog();
@@ -204,7 +184,9 @@ export function MyPluginsPage({
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 currentPickerDraft = useContributionPreview(pickerKey,
+ pickerOpen && pickerVersion !== undefined ? pickerSelection ?? undefined : undefined,
+ pickerVersion, preparePreview, reader.discard);
const pickerBlocker = currentPickerDraft?.prepared?.preflight?.blockers[0];
const pickerUnavailable = (local: GhostPluginListItem) => {
const plugin = pickerRead?.plugins.find(item => item.localInstanceId === local.id);
@@ -244,35 +226,6 @@ export function MyPluginsPage({
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(() => {
@@ -475,36 +428,6 @@ export function MyPluginsPage({
}, [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(() => {
@@ -895,15 +818,6 @@ export function MyPluginsPage({
);
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 && (
@@ -921,35 +835,9 @@ export function MyPluginsPage({
installedLocal?.instanceId, installedLocal?.version, canPrepareUpdate, updateRefresh]);
const updateContext = useRef({ key: updateKey, token: {} });
if (updateContext.current.key !== updateKey) updateContext.current = { key: updateKey, token: {} };
- const currentUpdateDraft = updateDraft?.token === updateContext.current.token ? updateDraft : null;
+ const currentUpdateDraft = useContributionPreview(updateKey,
+ canPrepareUpdate ? updateInstanceId : undefined, updateVersion, preparePreview, reader.discard);
const updateBlocker = currentUpdateDraft?.prepared?.preflight?.blockers[0];
- useEffect(() => {
- if (!canPrepareUpdate || !updateInstanceId || !updateVersion) return;
- let disposed = false;
- let held: string | undefined;
- const token = updateContext.current.token;
- const instanceId = updateInstanceId, version = updateVersion;
- void Promise.resolve().then(() => preparePicker.current(instanceId)).then(prepared => {
- held = prepared.preparedId;
- if (disposed || updateContext.current.token !== token) {
- void reader.discard(prepared.preparedId).catch(() => undefined);
- return;
- }
- if (prepared.instanceId !== instanceId || prepared.version !== version) {
- void reader.discard(prepared.preparedId).catch(() => undefined);
- held = undefined;
- setUpdateDraft({ token, error: `${copy}.errors.CONTRIBUTION_PACKAGE_CHANGED` });
- } else setUpdateDraft({ token, prepared });
- }).catch(error => {
- if (!disposed && updateContext.current.token === token)
- setUpdateDraft({ token, error: contributionErrorKey(error) });
- });
- return () => {
- disposed = true;
- if (held) void reader.discard(held).catch(() => undefined);
- };
- // The key captures the exact installation and permission generation, not the response object.
- }, [updateKey, canPrepareUpdate, updateInstanceId, updateVersion, reader]);
const published = publishedContent?.key === publishedKey ? publishedContent : null;
const listedDetail = plugin?.market.state === 'available' ? published?.value : null;
const currentNotes = currentSubmission?.content?.manifestView.releaseNotes;
@@ -1265,7 +1153,6 @@ export function MyPluginsPage({
? (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) ? (
diff --git a/apps/desktop/src/renderer/features/plugin/PluginAnonymityControl.tsx b/apps/desktop/src/renderer/features/plugin/PluginAnonymityControl.tsx
deleted file mode 100644
index ad831dcb05..0000000000
--- a/apps/desktop/src/renderer/features/plugin/PluginAnonymityControl.tsx
+++ /dev/null
@@ -1,99 +0,0 @@
-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/__tests__/GhostPluginPage.navigation.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginPage.navigation.test.tsx
index eaefb84107..c346ceadaf 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
@@ -829,7 +829,7 @@ describe('plugin use details and independent author management', () => {
};
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() };
+ prepare: vi.fn(), submit: vi.fn(), setAnonymity: vi.fn() };
}
function localAuthorInstallation(version: string): InstalledGhost {
@@ -846,7 +846,7 @@ describe('plugin use details and independent author management', () => {
['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],
+ ['unconfirmed', null],
['processing', null],
['succeeded', null],
] as const)('keeps a %s submission in the original detail without an upload-management page', async (stage, message) => {
@@ -863,8 +863,8 @@ describe('plugin use details and independent author management', () => {
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,
+ localId: prepared.preparedId, prepared, stage: stage === 'processing' ? 'processing' : 'complete',
+ errorCode: stage === 'unconfirmed' ? '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,
@@ -885,7 +885,7 @@ describe('plugin use details and independent author management', () => {
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' }); });
+ await act(async () => { finish({ ...transfer, stage: 'complete', errorCode: 'INTERNAL' }); });
}
if (stage === 'succeeded') {
await screen.findByRole('heading', { name: 'Published snapshot name' });
@@ -901,7 +901,6 @@ describe('plugin use details and independent author management', () => {
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.
@@ -982,31 +981,6 @@ describe('plugin use details and independent author management', () => {
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';
@@ -1049,7 +1023,7 @@ describe('plugin use details and independent author management', () => {
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);
+ expect(screen.queryByRole('switch', { name: `${prefix}.anonymous` })).toBeNull();
} else {
await screen.findByRole('heading', { level: 1, name: entry === 'market' ? detail.name : 'Actual installed name' });
expect(screen.queryByLabelText(`${prefix}.versionFacts`)).toBeNull();
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.tsx
index 8cc1089615..a817a10219 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/MyPluginsPage.cancelReview.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/MyPluginsPage.cancelReview.test.tsx
@@ -21,11 +21,9 @@ vi.mock('../../../../main/plugin-contributions/host', () => ({
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(),
@@ -62,8 +60,7 @@ function view() {
});
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 () => [],
+ prepare: vi.fn(), submit: vi.fn(), cancel: vi.fn(), discard: vi.fn(), status: vi.fn(),
list: async () => ({ plugins: [plugin()], nextCursor: null, queriedAt: at }),
setAnonymity: vi.fn(),
detail: async () => ({ plugin: plugin(), history: [], nextCursor: null, queriedAt: at }),
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/MyPluginsPage.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/MyPluginsPage.test.tsx
index 6758c412b7..c633813f96 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/MyPluginsPage.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/MyPluginsPage.test.tsx
@@ -9,7 +9,6 @@ import type {
MyPluginDetailView,
ContributionReleaseView,
PluginContributionsApi,
- ContributionTransferView,
} from '../../../../shared/pluginContributions';
import type { PluginMarketDetail } from '../../../../shared/pluginMarket';
import type { GhostPluginListItem } from '../lib/ghostPluginViewModel';
@@ -96,20 +95,18 @@ function packagePreview(instanceId: string, version = '1.0.0'): PreparedPluginCo
queriedAt: at, policyVersion: 2, target: { pluginId: null, ghostId: 'demo', version, expectedRelease: null },
pendingRelease: null, blockers: [], actions: { canSubmit: true } } };
}
-function reader(transfers: ContributionTransferView[] = []): PluginContributionsApi {
+function reader(): PluginContributionsApi {
return {
reviewUpdates: vi.fn().mockResolvedValue([]),
markReviewRead: vi.fn(),
prepare: vi.fn(async (instanceId: string) => packagePreview(instanceId, '1.2.0')),
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 }),
@@ -218,14 +215,13 @@ describe('My Plugins facts', () => {
expect(await screen.findByRole('button', { name: /My Plugin/ })).toBeTruthy();
});
- it('preserves a confirmed original author anonymity setting after publishing grant revocation', async () => {
+ it('keeps management readable without a submission action 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.getByText('New version changes')).toBeTruthy();
expect(screen.queryByRole('button', { name: `${prefix}.submitVersion 1.2.0` })).toBeNull();
expect(api.setAnonymity).not.toHaveBeenCalled();
});
@@ -263,27 +259,17 @@ describe('My Plugins facts', () => {
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('shows server submissions without querying or reconstructing an upload history', async () => {
+ const api = reader();
+ view(api, false);
+ fireEvent.click(await screen.findByRole('button', { name: /My Plugin/ }));
+ await waitForManagement();
+ expect(screen.getByText('Full reason, line one Full reason, line two')).toBeTruthy();
+ expect(screen.queryByText(`${prefix}.resume`)).toBeNull();
+ expect(screen.queryByText(`${prefix}.retryPublish`)).toBeNull();
+ expect(api.status).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();
@@ -817,60 +803,7 @@ describe('My Plugins facts', () => {
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]);
+ const api = reader();
vi.mocked(api.list).mockResolvedValue({
plugins: [
{
@@ -1038,85 +971,6 @@ describe('review result indicators in My Plugins', () => {
});
-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
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/PluginAnonymityControl.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/PluginAnonymityControl.test.tsx
deleted file mode 100644
index 388d5baccd..0000000000
--- a/apps/desktop/src/renderer/features/plugin/__tests__/PluginAnonymityControl.test.tsx
+++ /dev/null
@@ -1,118 +0,0 @@
-/** @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/useContributionPreview.ts b/apps/desktop/src/renderer/features/plugin/lib/useContributionPreview.ts
new file mode 100644
index 0000000000..0cea2d50c5
--- /dev/null
+++ b/apps/desktop/src/renderer/features/plugin/lib/useContributionPreview.ts
@@ -0,0 +1,58 @@
+import { useEffect, useRef, useState } from 'react';
+import { extractIpcError } from '@/utils/ipcError';
+import type { PluginContributionsApi, PreparedPluginContribution } from '../../../../shared/pluginContributions';
+
+const copy = 'settings.ghosts.contribution';
+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`;
+ return code ? `${copy}.errors.${code}` : navigator.onLine ? `${copy}.loadFailed` : `${copy}.offline`;
+}
+
+/** All three existing publishing surfaces own a preview in the same way. */
+export function useContributionPreview(
+ key: string,
+ instanceId: string | undefined,
+ version: string | undefined,
+ prepare: PluginContributionsApi['prepare'],
+ discard: PluginContributionsApi['discard'],
+) {
+ const input = JSON.stringify([key, instanceId, version]);
+ const current = useRef({ input, token: {} });
+ if (current.current.input !== input) current.current = { input, token: {} };
+ const token = current.current.token;
+ const callbacks = useRef({ prepare, discard });
+ callbacks.current = { prepare, discard };
+ const [snapshot, setSnapshot] = useState<{
+ token: object; prepared?: PreparedPluginContribution; error?: string;
+ } | null>(null);
+ useEffect(() => {
+ if (!instanceId) return;
+ let disposed = false;
+ let held: string | undefined;
+ const { prepare, discard } = callbacks.current;
+ void Promise.resolve().then(() => disposed ? null : prepare(instanceId)).then(prepared => {
+ if (!prepared) return;
+ if (disposed || current.current.token !== token) {
+ void discard(prepared.preparedId).catch(() => undefined);
+ } else if (prepared.instanceId !== instanceId || (version !== undefined && prepared.version !== version)) {
+ void discard(prepared.preparedId).catch(() => undefined);
+ setSnapshot({ token, error: `${copy}.errors.CONTRIBUTION_PACKAGE_CHANGED` });
+ } else {
+ held = prepared.preparedId;
+ setSnapshot({ token, prepared });
+ }
+ }).catch(error => {
+ if (!disposed && current.current.token === token) setSnapshot({ token, error: contributionErrorKey(error) });
+ });
+ return () => {
+ disposed = true;
+ if (held) void discard(held).catch(() => undefined);
+ };
+ }, [token, instanceId, version]);
+ return snapshot?.token === token ? snapshot : null;
+}
diff --git a/apps/desktop/src/renderer/hooks/useLocale.ts b/apps/desktop/src/renderer/hooks/useLocale.ts
index c928059285..a94518c280 100644
--- a/apps/desktop/src/renderer/hooks/useLocale.ts
+++ b/apps/desktop/src/renderer/hooks/useLocale.ts
@@ -80,7 +80,8 @@ export function LocaleProvider({ children }: { children: ReactNode }) {
applyLocale(eff);
}, []);
- // 首次 mount 时确保 i18next、<html lang> 和原生菜单与当前语言偏好一致。
+ // 首次 mount 时确保 i18next + <html lang> 与 state 一致 (state 来自 localStorage,
+ // 而 i18n.init 默认用的是 DEFAULT_LOCALE,两者可能不同)。
// 仅 mount 一次:locale 后续变化都走 setLocale 路径。
useEffect(() => {
applyLocale(effectiveLocale);
diff --git a/apps/desktop/src/shared/pluginContributions.ts b/apps/desktop/src/shared/pluginContributions.ts
index cbd2c9c929..9d387113a3 100644
--- a/apps/desktop/src/shared/pluginContributions.ts
+++ b/apps/desktop/src/shared/pluginContributions.ts
@@ -95,7 +95,7 @@ export interface MyPluginReleasePageView {
export interface ContributionTransferView {
localId: string;
prepared: PreparedPluginContribution;
- stage: 'prepared' | 'uploading' | 'processing' | 'paused' | 'complete';
+ stage: 'prepared' | 'uploading' | 'processing' | 'complete';
operation: ContributionOperation | null;
errorCode: string | null;
}
@@ -119,8 +119,6 @@ export interface PluginContributionsApi {
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(
diff --git a/docs/plugin-community-contribution-contract.md b/docs/plugin-community-contribution-contract.md
index 80875fe22b..e3b01cecdc 100644
--- a/docs/plugin-community-contribution-contract.md
+++ b/docs/plugin-community-contribution-contract.md
@@ -28,11 +28,10 @@ AI 不接触 Bearer、PUT URL 或原包路径。
- 官方来源继续通过 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 在线或个人会话。原始下载包保持不变;匿名控制服务端分发的展示署名,不清除开发者自行写入代码、文档或包内容的个人信息。
+- 改名不会自动同步旧版本;原作者下次提审保存新的昵称。其他维护者提审沿用已保存的原作者署名,不能改成维护者本人名字。绑定、昵称快照与审计信息继续完整记录。
+- 当前仅在生成响应时短路个人署名:公开列表、搜索、详情、本人管理详情及历史内容的展示署名统一返回 null,展示 manifest 不含作者;不受已保存的 anonymous 偏好影响,也不通过个人昵称搜索命中。读取投影不改写数据库中的作者绑定、版本昵称或回执内容。
+- `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 和账本一致,只更新署名投影。
diff --git a/docs/plugin-community-contribution.md b/docs/plugin-community-contribution.md
index 954b7cb002..d500e3e213 100644
--- a/docs/plugin-community-contribution.md
+++ b/docs/plugin-community-contribution.md
@@ -3,15 +3,15 @@
客户端实现与权限边界说明。
两仓各自维护等价的 [HTTP / DTO 契约](plugin-community-contribution-contract.md)。
-插件列表以当前最新主线为基线,原卡片、来源文案、署名布局、统计、推荐分类、筛选与排序保持一致,仅新增“我的插件”按钮。来源继续使用主线的“公开 / 团队共享 / 本地 / 自定义”,不新增“本地开发 / 本地导入”等分类,不用来源推断作者身份或发布状态。匿名署名继续尊重服务端的空值,不回退包内个人信息。
+插件列表以当前最新主线为基线,原卡片、来源文案、署名布局、统计、推荐分类、筛选与排序保持一致,仅新增“我的插件”按钮。来源继续使用主线的“公开 / 团队共享 / 本地 / 自定义”,不新增“本地开发 / 本地导入”等分类,不用来源推断作者身份或发布状态。个人投稿的展示署名暂由服务端统一返回为空,作者绑定和提审昵称仍完整记录;客户端保留原有展示,不回退包内个人信息。
作者在独立源码目录开发、安装并使用插件后,可在本地插件使用详情选择“提交审核”;后续版本在“我的插件”的独立管理页选择“提交 {{version}} 审核”,提交完成后留在本页刷新版本和审核状态。
本地使用详情准备当前包的只读发布摘要,在“版本与更新”中查看;按钮显示“提交 {{version}} 审核”时,点击就是公开发布意图:Host 固定并再核对当前安装内容,
不弹保存或选文件框,没有资料表单、独立介绍、翻译或第二个确认步骤。只有提交结果已确认后才进入该插件管理详情;提交失败留在原处显示实际原因,用户已离开时不抢回页面。作者继续开发时仍回到源码目录,不直接编辑 Host 的安装目录。
本地使用详情顶部操作区排列提审按钮、使用动作与启用开关;发布说明、适用的限制原因、
-当前准备阶段和提审限制在版本与更新中查看。普通列表始终进入使用详情,不自动跳入作者管理;发布结果、版本历史和匿名设置集中在“我的插件”独立页面。保留原三列详情头部:
+当前准备阶段和提审限制在版本与更新中查看。普通列表始终进入使用详情,不自动跳入作者管理;发布结果和版本历史集中在“我的插件”独立页面。保留原三列详情头部:
宽窗图标与标题在左、操作在右,发布按钮紧随使用动作;详情内容区不足 680px 时整组转到标题下方换行。
-右侧按钮较多时允许组内换行,并为标题至少保留 160px;管理页的长名称与匿名控件在同一个标题组中自然换行。
+右侧按钮较多时允许组内换行,并为标题至少保留 160px;管理页的长名称自然换行,不提供匿名发布开关。
未能查询时显示错误,不以本地版本推断线上结果。
“我的插件”是插件页常驻入口,页头(含空列表)提供“发布插件”。该按钮只打开当前账号的已安装插件选择,
@@ -26,7 +26,7 @@
自动代替原目标。列表支持服务端搜索、筛选与分页,每行以插件为主体,分别列出本地版本、当前上架版本和最近提审;
列表只展示服务端已收到的插件提交,不把未完成上传当作插件记录。上传与提交过程留在原提交按钮中,失败原因也在该次提交时显示。
管理详情默认显示本地、已上架、待审核三份当前事实,以及本地动作、已上架内容和当前提审。
-本地版本可提交时先只读准备该安装的名称、版本、用途、更新说明和预检,显示在本地版本区域;同一个提交按钮只提交这份已展示的固定包,不借用上一提审的说明,也不增加确认弹窗。受管预览与后台操作持有的包分开计算名额;普通对话结束不取消已经获准的后台提交,账号、任务实例、权限与安装变化仍会阻止后续写入。
+本地版本可提交时先只读准备该安装的名称、版本、用途、更新说明和预检,显示在本地版本区域;同一个提交按钮只提交这份已展示的固定包,不借用上一提审的说明,也不增加确认弹窗。三处现有摘要共用相同的准备与释放逻辑;普通对话结束不取消已经获准的本次提交,账号、任务实例、权限与安装变化仍会阻止后续写入。
已上架介绍与更新说明只读取匹配当前市场 releaseId/version 的真实公开版本,不借最新待审内容补齐。
发布记录默认收起,内部版本选择仅切换历史快照;版本号与状态分开显示,共用应用 Select,
单个历史版本不显示无用下拉框。完整退回原因保留,历史选择不改变本地版本、当前提审或提交目标。
@@ -38,7 +38,7 @@
首次上架不要求更新说明,插件用途写在 `description`。插件曾上架后再提审时,作者在 `ghost.json.releaseNotes` 写相对上一已上架版本的完整更新说明;从未上架的退回或取消不视为更新,下架不免除更新说明要求。
缺字段的包仍可安装,只有曾上架插件的更新缺说明时才阻止提审。摘要展示实际版本、已有说明与不可复用提示。
-每次准备各自持有临时包;StrictMode 清理不影响另一份摘要,提交后由原操作持有固定字节直到终态。
+每次准备持有临时包;页面清理不影响已发起的提交,本次动作结束后释放包,不保存上传历史。
本地安装内容或批准变化后必须刷新摘要;AI 也读取同一摘要并按当前权限档提交。
成功提审后该插件的版本号永久占用;退回、取消、通过、下架均不能再次使用。
@@ -51,20 +51,13 @@
只读预检与取消审核的接口见两仓共享契约。
个人投稿复用原待审、审核和上架流程,没有额外启用开关,不要求发布基准或审核阅读令牌。
-## 当前包与上传恢复
-
-- `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 开发实例不能写入
- 发布恢复文件,应在持有当前数据的主实例操作。
+## 当前包与提交
+
+- 包快照沿 `exportGhostPackage.ts` 和既有 inspect 校验,固定实际安装字节;系统导出保持原行为。临时包只属于当前预览或本次提交,不建立持久包历史。
+- `api.ts` 沿 Main 个人 Access Token 与可信 issuer 核验,服务端验签并判定 public 权限;不借用企业或 Platform 身份。
+- Main 统一执行准备上传票据、上传和提交;页面及 Agent 只跟随本次进度。prepare 与 PUT 不会创建待审版本,失败后释放临时包,不保存可恢复上传任务。
+- 发送 commit 前仅记录尚未确认请求的服务端 operationId、目标/包摘要及安装绑定;响应丢失时,下一次正常提交先查询原请求,必要时提交同一 operation,不重复上传。确定终态后清除该记录,不保留完整回执、本地 phase/stage 或终态历史。
+- 未确认记录按账号隔离,不保存 Bearer、PUT 票据或临时包路径,不读取持久文件里的路径执行清理。共用 userData 的 passive 实例不能写入;页面、登录和应用重启不自动提交。普通对话结束后当前已授权提交可继续,账号、任务权限或安装变化仍阻止后续写入。
202 只是处理中。只有服务器成功操作附带完整回执,才解释 `submitted_for_review`、`metadata_updated`
或 `unchanged`;上传包 SHA 与实际 Release SHA 分开。审核状态属于对应修订,市场可用以 `available`
@@ -83,7 +76,7 @@
本地版本、已上架版本、当前提审是独立事实。提审、审核通过和页面读取都不改变安装来源,
不自动安装或替换包。同一账号仍按现有 namespace + id 去重,不支持同身份的本地版与公开版并装;
-名称相同而 ID 不同的插件不合并。发布权限与匿名修改权限继续由服务端分别判定,不能从本地安装推断。
+名称相同而 ID 不同的插件不合并。发布权限与平台署名继续由服务端判定,不能从本地安装推断。
已安装旧版本无法取得可信的提审昵称时隐藏署名,不用当前市场新版昵称补齐;本地、组织和旧安装仍按原包内署名规则展示。桌面与远程详情共用公开来源的署名回退限制。
## 基础数据
@@ -106,14 +99,14 @@ Host 账号。普通用户自己的 Worker 和自动任务不被泛化封禁。I
额外主体字段和不可信 Renderer;未增加 device-link allowlist 或远程控制能力。
故障只影响当前个人发布动作:停止、断网或服务端失败不会改变已装插件、运行时或既有市场版本。
-重启后不自动重新上传,也不展示内部恢复记录;用户仍通过普通提交入口操作。未知结果保留原键及原请求,
+重启后不自动重新上传,也不展示上传记录;用户仍通过普通提交入口操作。未知 commit 结果保留服务端请求标识,
不由 UI 推断成功或擅自更换包。服务端不支持接口时明确失败,不回退到企业或 Platform 身份。
## 验证与维护
-提交前对 Host 固定包与恢复、可信 IPC、账号隔离、普通详情入口、管理页版本与匿名设置、审核结果未读执行相关回归;检查共享协议和开发工具包的类型及行为。
+提交前对 Host 固定包与重复提交防护、可信 IPC、账号隔离、普通详情入口、管理页版本、审核结果未读执行相关回归;检查共享协议和开发工具包的类型及行为。
界面使用仓库 `pnpm ui:check` 验证真实组件的明暗主题与窗口尺寸,并在 PR 附截图。隔离场景不代替真实提审、审核、安装或权限验收。
-`ghost.json.releaseNotes` 和提审/匿名规则同时维护在内置 `cindy-plugin-creator` 手册及 `cindy-tools` 工具说明中。官方插件仓的文档、示例与校验不在本次客户端改动范围内。
+`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.md
index 8f0bcd6d6f..9941771143 100644
--- a/docs/product-rules/agent-user-parity.md
+++ b/docs/product-rules/agent-user-parity.md
@@ -59,7 +59,7 @@
| 伙伴 | 工作台一眼(等你 / 在做) | 有 | 无 |
| 伙伴 | 跟进任务:读取与继续(自动跟进所有任务的伙伴) | 有 | 有(2026-10-17) |
| 伙伴 | 查看与更换主力电脑 | 有 | 有(2026-10-17) |
-| 社区插件贡献 | 当前安装快照准备、公开提交/原操作恢复、本人列表/详情/留存内容 | 有(2026-10-15) | 无 |
+| 社区插件贡献 | 当前安装快照准备、提交审核/当前进度、本人列表/详情/留存内容 | 有(2026-10-15) | 无 |
Worker 工具省略 working_dir 时保持继承 Lead 任务记录目录,不跟随之后 cd 进入的 worktree。
面板默认识别实际目录属于 UI 行为;Agent 通过显式 working_dir 共用已有 worktree,
@@ -116,7 +116,7 @@ Session 委托写操作,以及 `cindy_orca` 的协作写操作,共用 Host
Bearer、PUT 票据或受管文件路径。公开写入遵循当前任务 Full Access / Auto / Ask,不加最后人工点击。
共享任务访客及既有 helper surface 判为 restricted 的插件托管任务(包括其 Worker)不得读取个人
个人插件发布资料或执行发布。普通用户自己的 Worker、自动任务沿相同账号边界与任务权限;人工审核不由 Agent 执行。
-客户端协议和恢复边界见 [社区贡献实现说明](../plugin-community-contribution.md)。
+客户端提交边界见 [社区贡献实现说明](../plugin-community-contribution.md)。
2026-10-16:个人发布 prepare 返回包内 releaseNotes 和远端只读预检;submit 前重新校验所见快照内容。
`ghost_cancel_plugin_review` 使用本人版本的精确 revision,区分停止上传与取消审核,沿现有 Full Access/Auto/Ask 授权。
diff --git a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
index 82ed64a2ef..a7bbfb40bd 100644
--- a/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
+++ b/packages/cindy-tools/src/__tests__/ghostMcp.test.ts
@@ -2210,9 +2210,7 @@ describe('personal community author MCP transport', () => {
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' }],
@@ -2224,9 +2222,7 @@ describe('personal community author MCP transport', () => {
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' },
@@ -2243,6 +2239,8 @@ describe('personal community author MCP transport', () => {
try {
for (const [name, args] of [
['ghost_contribution_prepare', { ghost_id: 'hello', file: '/private/package.cindy' }],
+ ['ghost_contribution_submit', { prepared_id: 'original-operation', resume: true }],
+ ['ghost_contribution_status', {}],
['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' }],
diff --git a/packages/cindy-tools/src/ghost/mcpServer.ts b/packages/cindy-tools/src/ghost/mcpServer.ts
index c42255f7e2..dd171d6a46 100644
--- a/packages/cindy-tools/src/ghost/mcpServer.ts
+++ b/packages/cindy-tools/src/ghost/mcpServer.ts
@@ -128,7 +128,7 @@ const D_GHOST_FORGE_GUIDE = [
"创建、修改、调试、打包或发布 Cindy 插件时使用该 Skill;本工具保留按章读取同一份资料的兼容入口。",
'不传参数返回目录,传 section(章号如 "4.7" 或标题关键词如 "network")返回单章正文。',
"本工具只读文档,不安装或发布插件。",
- "发布前另读 §2 的 releaseNotes、§7.3 个人发布和 §7.4 署名与匿名。",
+ "发布前另读 §2 的 releaseNotes、§7.3 个人发布和 §7.4 平台署名。",
].join("\n");
const D_GHOST_FORGE_SCAFFOLD = [
@@ -1506,22 +1506,22 @@ export function createCindyGhostsMcpServer(
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 }));
+ description: '把 ghost_contribution_prepare 刚准备的确切插件提交审核。用户已明确委托公开发布时沿当前任务的 Full Access / Auto / Ask 权限执行,不额外要求用户重新授权或最后手动点击;只有安装委托不等于发布委托。不接受文件路径、独立文案、账号或票据。返回本次提交的进度标识,接 ghost_contribution_status 查询到结束;202/处理中不等于已提交审核。不要自行重复发起提交;Host 内部核对尚未确认的同包请求。权限拒绝时说明原因并停止,不改权限模式重试。官方 public 插件须通过 GitHub 仓库提交修改,以保证源码完整、便于维护;客户端与 Agent 工具均不得提审。',
+ inputSchema: z.object({ prepared_id: contributionId }).strict() },
+ async ({ prepared_id }) => contribute({ action: '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' }));
+ description: '查询本次提交的进度。只跟随当前提交,结束后通过 ghost_my_plugins 查看审核结果,不轮询人工审核。成功回执 outcome、修订审核状态与市场可用事实分别解释,上传 SHA 不一定是实际 Release SHA。',
+ inputSchema: z.object({ local_id: contributionId }).strict() },
+ async ({ local_id }) => contribute({ action: 'status', id: local_id }));
server.registerTool('ghost_contribution_stop', {
- description: '停止当前上传并保留原操作。停止不代表撤回已提交内容,也不改变审核结果;后续查询原操作再恢复。',
+ description: '停止本次上传。停止不代表取消已提交的审核,也不改变审核结果;已提交内容通过 ghost_my_plugins 查看。',
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 与组织规则不变。',
+ description: '读取当前个人账号的我的插件列表或精确详情。搜索/筛选/分页由服务端执行;详情分当前市场、最近提交、已留存内容和独立处理历史,退回原因完整返回。只查询本人,不审核、不代修、不发通知。修改作者源码后重新安装并使用,再从当前实例准备发布更新,不直接修改 Host 管理的安装目录。历史内容和 releaseNotes 取对应版本提审快照。个人投稿的展示署名暂由服务端返回为空,作者绑定和提审昵称仍完整记录。不从 ghost.json.author 或当前账号昵称补齐。客户端界面与本工具不提供匿名设置;官方 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);
diff --git a/packages/cindy-tools/src/types.ts b/packages/cindy-tools/src/types.ts
index 1f0dc9fe10..45c9aed861 100644
--- a/packages/cindy-tools/src/types.ts
+++ b/packages/cindy-tools/src/types.ts
@@ -494,12 +494,11 @@ export interface CindyGhostsMcpDeps {
/** 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: 'submit' | '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;
diff --git a/scripts/__tests__/restart-desktop-remote.test.mjs b/scripts/__tests__/restart-desktop-remote.test.mjs
index 5806b66e10..5237d6e502 100644
--- a/scripts/__tests__/restart-desktop-remote.test.mjs
+++ b/scripts/__tests__/restart-desktop-remote.test.mjs
@@ -35,7 +35,6 @@ import {
productionUserDataDir,
readDesktopStartupStatus,
parseWorktreePaths,
- osascriptCloseDarwinTerminalTtyArgs,
osascriptLaunchDarwinTerminalArgs,
writeDarwinTerminalLaunchScript,
darwinTerminalSourceCommand,
@@ -90,30 +89,6 @@ 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.mjs
index b8438cce69..8fe4ef0022 100644
--- a/scripts/restart-desktop-remote.mjs
+++ b/scripts/restart-desktop-remote.mjs
@@ -54,9 +54,7 @@ function desktopEnvSpec() {
}
const closeDarwinTerminalTtyScript = Object.freeze([
'on closeMatchingTerminalTab(targetTty)',
- // 查询运行状态不会启动应用;直接 tell 会在清理 iTerm 的 TTY 时误开 Terminal。
- 'if application id "com.apple.Terminal" is not running then return',
- 'tell application id "com.apple.Terminal"',
+ 'tell application "Terminal"',
'repeat with terminalWindow in windows',
'repeat with terminalTab in tabs of terminalWindow',
'if (tty of terminalTab) is targetTty then',
@@ -546,7 +544,7 @@ export function readDesktopDevLogTail(logPath, maxLines = 40) {
return lines.slice(-maxLines);
}
-export function osascriptCloseDarwinTerminalTtyArgs(ttyPath) {
+function osascriptCloseDarwinTerminalTtyArgs(ttyPath) {
return closeDarwinTerminalTtyScript
.flatMap((line) => ['-e', line])
.concat(ttyPath);