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。

fix(desktop): bound plugin publishing resources

fmfsaisai52298f594a7d
diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
index 23d44e8e27..9a550ebacf 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts
@@ -402,6 +402,34 @@ describe('PluginMarketService migration and defaultInstall', () => {
expect(store.lookup('org-acme')).toEqual({ kind: 'known', pluginPrefix: 'acme' });
});
+ it('still returns the market snapshot when the organization prefix cache write fails', async () => {
+ const item = summary();
+ const h = harness([item]);
+ h.api.listAll.mockResolvedValue({
+ plugins: [item],
+ removals: [],
+ currentOrganization: { organizationId: 'org-acme', pluginPrefix: 'acme' },
+ });
+ const realRenameSync = fs.renameSync;
+ const renameSync = vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => {
+ if (String(to).endsWith(path.join('plugin-market', 'organization.v1.json'))) {
+ throw Object.assign(new Error('simulated cache rename failure'), { code: 'EPERM' });
+ }
+ return realRenameSync(from, to);
+ });
+
+ try {
+ // Excludes allowing a reconstructable cache write failure to reject the whole catalog.
+ await expect(h.service.snapshot()).resolves.toMatchObject({
+ items: [{ pluginId: item.id }],
+ unavailableReason: null,
+ });
+ expect(renameSync).toHaveBeenCalled();
+ } finally {
+ renameSync.mockRestore();
+ }
+ });
+
it('passes the optional release icon metadata to renderer-safe market items', async () => {
const icon = {
mimeType: 'image/png',
diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.ts
index 1ac22a187a..e3df0b4191 100644
--- a/apps/desktop/src/main/plugin-market/service.ts
+++ b/apps/desktop/src/main/plugin-market/service.ts
@@ -2703,9 +2703,17 @@ export class PluginMarketService {
currentOrganization: PluginCurrentOrganization | null | undefined,
): void {
if (!currentOrganization) return;
- createOrganizationPrefixStore(
- ownerScopedUserDataPath('plugin-market', 'organization.v1.json'),
- ).remember(currentOrganization.organizationId, currentOrganization.pluginPrefix);
+ try {
+ createOrganizationPrefixStore(
+ ownerScopedUserDataPath('plugin-market', 'organization.v1.json'),
+ ).remember(currentOrganization.organizationId, currentOrganization.pluginPrefix);
+ } catch (error) {
+ // This is a reconstructable cache. A failed write must not hide the market;
+ // a later lookup still fails closed as unavailable/absent.
+ log.warn('organization prefix cache write failed', {
+ errorType: error instanceof Error ? error.name : typeof error,
+ });
+ }
}
private withLedgerMutation<T>(
diff --git a/apps/desktop/src/main/plugin-publisher/__tests__/confirmBridge.test.ts b/apps/desktop/src/main/plugin-publisher/__tests__/confirmBridge.test.ts
index 491f4df1be..b1c03c851a 100644
--- a/apps/desktop/src/main/plugin-publisher/__tests__/confirmBridge.test.ts
+++ b/apps/desktop/src/main/plugin-publisher/__tests__/confirmBridge.test.ts
@@ -44,4 +44,26 @@ describe('PluginPublisherConfirmBridge', () => {
bridge.cancelAll();
await expect(pending).resolves.toBe(false);
});
+
+ it('drops a pending confirm when its transfer is aborted', async () => {
+ const bridge = new PluginPublisherConfirmBridge();
+ const controller = new AbortController();
+ let requestId = '';
+ const pending = bridge.request(
+ 0,
+ facts,
+ ownerStamp,
+ (request) => {
+ requestId = request.requestId;
+ return true;
+ },
+ controller.signal,
+ );
+
+ controller.abort();
+
+ await expect(pending).resolves.toBe(false);
+ // Excludes leaving an unreachable entry behind after the quota is released.
+ expect(bridge.resolve(1, requestId, true)).toBe(false);
+ });
});
diff --git a/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts b/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts
index 13a420509f..8db0602db7 100644
--- a/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts
+++ b/apps/desktop/src/main/plugin-publisher/__tests__/orchestrator.test.ts
@@ -37,6 +37,20 @@ async function fileSha256(filePath: string): Promise<string> {
.digest('hex');
}
+function deferredBoolean(): {
+ promise: Promise<boolean>;
+ resolve: (value: boolean) => void;
+ reject: (error: unknown) => void;
+} {
+ let resolve!: (value: boolean) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<boolean>((done, fail) => {
+ resolve = done;
+ reject = fail;
+ });
+ return { promise, resolve, reject };
+}
+
function waitFor(
snapshots: PluginPublisherProgress[],
predicate: (progress: PluginPublisherProgress) => boolean,
@@ -61,11 +75,121 @@ const prepared = {
'Content-Type': 'application/octet-stream',
'x-oss-forbid-overwrite': 'true',
},
- expiresAt: '2026-08-19T08:15:00.000Z',
+ expiresAt: '2099-08-19T08:15:00.000Z',
status: 'awaiting_upload' as const,
};
describe('PluginPublisherOrchestrator', () => {
+ it('caps pending confirmations per owner before opening another package', async () => {
+ const filePath = await packagePath();
+ const snapshots: PluginPublisherProgress[] = [];
+ const confirmations: Array<ReturnType<typeof deferredBoolean>> = [];
+ const openFile = vi.fn(async (candidate: string, flags: string | number) =>
+ fs.open(candidate, flags),
+ );
+ const orch = createPluginPublisherOrchestrator({
+ api: { prepare: vi.fn(), commit: vi.fn(), status: vi.fn() } as unknown as PluginPublisherApi,
+ inspectPackage: async () => ({ ghostId: 'demo', name: 'Demo', version: '1.0.0' }),
+ confirm: () => {
+ const confirmation = deferredBoolean();
+ confirmations.push(confirmation);
+ return confirmation.promise;
+ },
+ identity: () => ({ membershipId: 'm1', orgSlug: 'acme', orgName: 'Acme' }),
+ openFile: openFile as typeof fs.open,
+ onProgress: (progress) => snapshots.push({ ...progress }),
+ });
+
+ orch.start(filePath);
+ orch.start(filePath);
+ await vi.waitFor(() => expect(confirmations).toHaveLength(2));
+ const rejected = orch.start(filePath);
+ const failed = await waitFor(
+ snapshots,
+ (progress) => progress.transferId === rejected.transferId && progress.stage === 'failed',
+ );
+
+ // Excludes both an unbounded confirmation map and a quota placed after open().
+ expect(failed.errorCode).toBe('SERVER_BUSY');
+ expect(openFile).toHaveBeenCalledTimes(2);
+ expect(confirmations).toHaveLength(2);
+
+ orch.abortAll();
+ });
+
+ it('keeps the pending-confirmation quota isolated by active-session owner', async () => {
+ const filePath = await packagePath();
+ const confirmations: Array<ReturnType<typeof deferredBoolean>> = [];
+ let owner = { mode: 'cloud' as const, dataOwnerId: 'member-a', generation: 1 };
+ const orch = createPluginPublisherOrchestrator({
+ api: { prepare: vi.fn(), commit: vi.fn(), status: vi.fn() } as unknown as PluginPublisherApi,
+ inspectPackage: async () => ({ ghostId: 'demo', name: 'Demo', version: '1.0.0' }),
+ confirm: () => {
+ const confirmation = deferredBoolean();
+ confirmations.push(confirmation);
+ return confirmation.promise;
+ },
+ identity: () => ({ membershipId: 'm1', orgSlug: 'acme', orgName: 'Acme' }),
+ owner: () => owner,
+ });
+
+ orch.start(filePath);
+ orch.start(filePath);
+ await vi.waitFor(() => expect(confirmations).toHaveLength(2));
+ owner = { ...owner, dataOwnerId: 'member-b' };
+ const otherOwner = orch.start(filePath);
+
+ // Excludes a global cap that lets one owner exhaust another owner's allowance.
+ await vi.waitFor(() => expect(confirmations).toHaveLength(3));
+ expect(orch.snapshot(otherOwner.transferId)?.stage).toBe('confirming');
+ orch.abortAll();
+ });
+
+ it.each(['accepted', 'rejected', 'aborted', 'failed'] as const)(
+ 'releases pending-confirmation capacity after a confirmation is %s',
+ async (outcome) => {
+ const filePath = await packagePath();
+ const confirmations: Array<ReturnType<typeof deferredBoolean>> = [];
+ const orch = createPluginPublisherOrchestrator({
+ api: {
+ prepare: vi.fn(async () => {
+ throw new Error('stop after confirmation');
+ }),
+ commit: vi.fn(),
+ status: vi.fn(),
+ } as unknown as PluginPublisherApi,
+ inspectPackage: async () => ({ ghostId: 'demo', name: 'Demo', version: '1.0.0' }),
+ confirm: () => {
+ const confirmation = deferredBoolean();
+ confirmations.push(confirmation);
+ return confirmation.promise;
+ },
+ identity: () => ({ membershipId: 'm1', orgSlug: 'acme', orgName: 'Acme' }),
+ });
+
+ const first = orch.start(filePath);
+ orch.start(filePath);
+ await vi.waitFor(() => expect(confirmations).toHaveLength(2));
+ if (outcome === 'accepted') confirmations[0].resolve(true);
+ else if (outcome === 'rejected') confirmations[0].resolve(false);
+ else if (outcome === 'aborted') {
+ expect(orch.cancel(first.transferId)).toEqual({ cancelled: true });
+ } else confirmations[0].reject(new Error('confirmation failed'));
+ await vi.waitFor(() =>
+ expect(orch.snapshot(first.transferId)?.stage).toMatch(/^(failed|cancelled)$/),
+ );
+
+ const next = orch.start(filePath);
+ // Excludes a leaked counter on the accept, reject, and abort exits respectively.
+ await vi.waitFor(() => expect(confirmations).toHaveLength(3));
+ expect(orch.snapshot(next.transferId)?.stage).toBe('confirming');
+
+ confirmations[1].resolve(false);
+ confirmations[2].resolve(false);
+ await vi.waitFor(() => expect(orch.snapshot(next.transferId)?.stage).toBe('failed'));
+ },
+ );
+
it('hides status and cancel from a different active-session owner', async () => {
const filePath = await packagePath();
const owner = { mode: 'cloud' as const, dataOwnerId: 'member-1', generation: 7 };
@@ -280,8 +404,52 @@ describe('PluginPublisherOrchestrator', () => {
expect(commit3).toHaveBeenCalledTimes(1);
});
+ it('recomputes the remaining absolute PUT budget before a retry', async () => {
+ const filePath = await packagePath();
+ const snapshots: PluginPublisherProgress[] = [];
+ let now = Date.parse('2026-08-19T07:15:00.000Z');
+ const expiresAt = new Date(now + PLUGIN_PUBLISHER_COMMIT_MARGIN_MS + 5_000).toISOString();
+ const budgets: number[] = [];
+ const orch = createPluginPublisherOrchestrator({
+ api: {
+ prepare: async () => ({ ...prepared, expiresAt }),
+ commit: async () => ({ uploadId: 'upload-1', status: 'validating' }),
+ status: async () => ({
+ uploadId: 'upload-1',
+ status: 'succeeded',
+ pluginId: `c${'a'.repeat(24)}`,
+ releaseId: 'rel-1',
+ ghostId: 'demo',
+ version: '1.0.0',
+ reviewStatus: 'pending',
+ failure: null,
+ }),
+ } as unknown as PluginPublisherApi,
+ inspectPackage: async () => ({ ghostId: 'demo', name: 'Demo', version: '1.0.0' }),
+ confirm: async () => true,
+ identity: () => ({ membershipId: 'm1', orgSlug: 'acme', orgName: 'Acme' }),
+ now: () => now,
+ putFile: async (_handle, options) => {
+ if (options.maxTotalMs === undefined) throw new Error('missing PUT budget');
+ budgets.push(options.maxTotalMs);
+ if (budgets.length === 1) {
+ now += 3_000;
+ throw new PluginPublisherPutError('timeout', 'retry_same_url');
+ }
+ return { bytesSent: 24 };
+ },
+ sleep: async () => undefined,
+ onProgress: (progress) => snapshots.push({ ...progress }),
+ });
+
+ orch.start(filePath);
+ await waitFor(snapshots, (progress) => progress.stage === 'succeeded');
+ // Excludes restarting the original five-second relative timeout on retry.
+ expect(budgets).toEqual([5_000, 2_000]);
+ });
+
it('derives the PUT deadline from expiresAt minus a commit margin', () => {
- const now = Date.parse('2026-08-19T07:15:00.000Z');
+ const now = Date.parse('2099-08-19T07:15:00.000Z');
const budget = remainingPutBudgetMs(prepared.expiresAt, now);
const sessionLeft = Date.parse(prepared.expiresAt) - now;
expect(budget).toBe(sessionLeft - PLUGIN_PUBLISHER_COMMIT_MARGIN_MS);
diff --git a/apps/desktop/src/main/plugin-publisher/confirmBridge.ts b/apps/desktop/src/main/plugin-publisher/confirmBridge.ts
index 6da8a69332..80043f8213 100644
--- a/apps/desktop/src/main/plugin-publisher/confirmBridge.ts
+++ b/apps/desktop/src/main/plugin-publisher/confirmBridge.ts
@@ -17,6 +17,8 @@ export interface PluginPublisherConfirmRequest {
interface PendingConfirm {
requesterId: number;
resolve: (confirmed: boolean) => void;
+ signal?: AbortSignal;
+ onAbort?: () => void;
}
export class PluginPublisherConfirmBridge {
@@ -27,10 +29,14 @@ export class PluginPublisherConfirmBridge {
facts: PluginPublisherConfirmFacts,
ownerStamp: DataOwnerPushStamp,
send: (request: PluginPublisherConfirmRequest) => boolean,
+ signal?: AbortSignal,
): Promise<boolean> {
+ if (signal?.aborted) return Promise.resolve(false);
const requestId = randomUUID();
return new Promise<boolean>((resolve) => {
- this.pending.set(requestId, { requesterId, resolve });
+ const onAbort = (): void => this.settle(requestId, false);
+ this.pending.set(requestId, { requesterId, resolve, signal, onAbort });
+ signal?.addEventListener('abort', onAbort, { once: true });
let delivered = false;
try {
delivered = send({ requestId, ownerStamp, facts });
@@ -65,6 +71,9 @@ export class PluginPublisherConfirmBridge {
const pending = this.pending.get(requestId);
if (!pending) return;
this.pending.delete(requestId);
+ if (pending.signal && pending.onAbort) {
+ pending.signal.removeEventListener('abort', pending.onAbort);
+ }
pending.resolve(confirmed);
}
}
diff --git a/apps/desktop/src/main/plugin-publisher/host.ts b/apps/desktop/src/main/plugin-publisher/host.ts
index fe5615f41b..a7baad2c99 100644
--- a/apps/desktop/src/main/plugin-publisher/host.ts
+++ b/apps/desktop/src/main/plugin-publisher/host.ts
@@ -113,11 +113,17 @@ export function getPluginPublisherOrchestrator(): PluginPublisherOrchestrator {
version: inspected.canonicalManifest.version,
};
},
- confirm(facts) {
+ confirm(facts, signal) {
const ownerStamp = getActiveDataOwnerPushStamp();
- return confirmBridge.request(0, facts, ownerStamp, (request) => {
- return sendToTrustedAppWindows(PLUGIN_PUBLISHER_CONFIRM_CHANNEL, request) > 0;
- });
+ return confirmBridge.request(
+ 0,
+ facts,
+ ownerStamp,
+ (request) => {
+ return sendToTrustedAppWindows(PLUGIN_PUBLISHER_CONFIRM_CHANNEL, request) > 0;
+ },
+ signal,
+ );
},
onProgress(progress: PluginPublisherProgress) {
sendToTrustedAppWindows(PLUGIN_PUBLISHER_PROGRESS_CHANNEL, progress);
@@ -166,17 +172,23 @@ export function startPluginPublish(
log.info('plugin publish started');
return getPluginPublisherOrchestrator().start(filePath, {
...(sourceBinding ? { sourceBinding } : {}),
- confirm: (facts) => {
+ confirm: (facts, signal) => {
const ownerStamp = getActiveDataOwnerPushStamp();
const requesterId = requester && !requester.isDestroyed() ? requester.id : 0;
if (requester && !requester.isDestroyed()) trackPublisherConfirmRequester(requester);
- return confirmBridge.request(requesterId, facts, ownerStamp, (request) => {
- if (requester && !requester.isDestroyed()) {
- requester.send(PLUGIN_PUBLISHER_CONFIRM_CHANNEL, request);
- return true;
- }
- return sendToTrustedAppWindows(PLUGIN_PUBLISHER_CONFIRM_CHANNEL, request) > 0;
- });
+ return confirmBridge.request(
+ requesterId,
+ facts,
+ ownerStamp,
+ (request) => {
+ if (requester && !requester.isDestroyed()) {
+ requester.send(PLUGIN_PUBLISHER_CONFIRM_CHANNEL, request);
+ return true;
+ }
+ return sendToTrustedAppWindows(PLUGIN_PUBLISHER_CONFIRM_CHANNEL, request) > 0;
+ },
+ signal,
+ );
},
});
}
diff --git a/apps/desktop/src/main/plugin-publisher/orchestrator.ts b/apps/desktop/src/main/plugin-publisher/orchestrator.ts
index 3f5aee6bf5..7da6c113c5 100644
--- a/apps/desktop/src/main/plugin-publisher/orchestrator.ts
+++ b/apps/desktop/src/main/plugin-publisher/orchestrator.ts
@@ -26,10 +26,11 @@ import { hashLocalFile, PluginPublisherHashCancelledError } from './hashFile.js'
import { PluginPublisherPutError, putLocalFile } from './putObject.js';
import {
PLUGIN_PUBLISHER_MAX_CONCURRENT,
+ PLUGIN_PUBLISHER_MIN_PUT_BUDGET_MS,
PLUGIN_PUBLISHER_POLL_INTERVAL_MS,
PLUGIN_PUBLISHER_POLL_MAX_TRANSIENT_RETRIES,
PLUGIN_PUBLISHER_POLL_TRANSIENT_BACKOFF_MS,
- remainingPutBudgetMs,
+ putDeadlineAtMs,
type PluginPublisherProgress,
type PluginPublisherStage,
type PluginPublisherStartResult,
@@ -44,20 +45,24 @@ export interface PluginPublisherOrchestratorDeps {
name: string;
version: string;
}>;
- confirm(facts: {
- orgSlug: string;
- orgName: string | null;
- ghostId: string;
- name: string;
- version: string;
- sizeBytes: number;
- }): Promise<boolean>;
+ confirm(
+ facts: {
+ orgSlug: string;
+ orgName: string | null;
+ ghostId: string;
+ name: string;
+ version: string;
+ sizeBytes: number;
+ },
+ signal: AbortSignal,
+ ): Promise<boolean>;
identity(): { membershipId: string; orgSlug: string; orgName: string | null } | null;
owner?: () => ActiveAppSession;
now?: () => number;
sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
onProgress?: (progress: PluginPublisherProgress) => void;
putFile?: typeof putLocalFile;
+ openFile?: typeof fsPromises.open;
inspectGate?: { acquire(signal: AbortSignal): Promise<void>; release(): void };
}
@@ -102,6 +107,33 @@ function isPathSafeForPublish(filePath: string): boolean {
return path.extname(filePath).toLowerCase() === '.cindy';
}
+class PluginPublisherPutDeadlineExpiredError extends Error {}
+
+async function waitForConfirmationOrAbort(
+ confirmation: Promise<boolean>,
+ signal: AbortSignal,
+): Promise<boolean> {
+ if (signal.aborted) return false;
+ return new Promise<boolean>((resolve, reject) => {
+ const onAbort = (): void => {
+ cleanup();
+ resolve(false);
+ };
+ const cleanup = (): void => signal.removeEventListener('abort', onAbort);
+ signal.addEventListener('abort', onAbort, { once: true });
+ confirmation.then(
+ (confirmed) => {
+ cleanup();
+ resolve(confirmed);
+ },
+ (error: unknown) => {
+ cleanup();
+ reject(error);
+ },
+ );
+ });
+}
+
class SerialGate {
private active = false;
private readonly waiters: Array<() => void> = [];
@@ -142,12 +174,15 @@ export class PluginPublisherOrchestrator {
private readonly sleep: (ms: number, signal: AbortSignal) => Promise<void>;
private readonly inspectGate: { acquire(signal: AbortSignal): Promise<void>; release(): void };
private readonly owner: () => ActiveAppSession;
+ private readonly openFile: typeof fsPromises.open;
+ private readonly pendingConfirmations: Array<{ owner: ActiveAppSession; count: number }> = [];
constructor(private readonly deps: PluginPublisherOrchestratorDeps) {
this.now = deps.now ?? Date.now;
this.sleep = deps.sleep ?? defaultSleep;
this.inspectGate = deps.inspectGate ?? new SerialGate();
this.owner = deps.owner ?? getActiveAppSession;
+ this.openFile = deps.openFile ?? fsPromises.open;
}
start(
@@ -264,6 +299,31 @@ export class PluginPublisherOrchestrator {
next?.();
}
+ private tryAcquirePendingConfirmation(owner: ActiveAppSession): boolean {
+ const entry = this.pendingConfirmations.find((candidate) =>
+ sameActiveAppSessionOwner(candidate.owner, owner),
+ );
+ if (entry) {
+ // Align the pending-confirmation cap with the upload concurrency cap: more
+ // than two simultaneous confirmations is not a normal publishing flow.
+ if (entry.count >= PLUGIN_PUBLISHER_MAX_CONCURRENT) return false;
+ entry.count += 1;
+ return true;
+ }
+ this.pendingConfirmations.push({ owner, count: 1 });
+ return true;
+ }
+
+ private releasePendingConfirmation(owner: ActiveAppSession): void {
+ const index = this.pendingConfirmations.findIndex((candidate) =>
+ sameActiveAppSessionOwner(candidate.owner, owner),
+ );
+ if (index < 0) return;
+ const entry = this.pendingConfirmations[index];
+ if (entry.count <= 1) this.pendingConfirmations.splice(index, 1);
+ else entry.count -= 1;
+ }
+
private async run(
record: TransferRecord,
confirm: PluginPublisherOrchestratorDeps['confirm'],
@@ -271,6 +331,7 @@ export class PluginPublisherOrchestrator {
): Promise<void> {
const signal = record.controller.signal;
let handle: fsPromises.FileHandle | null = null;
+ let pendingConfirmationHeld = false;
try {
if (!isPathSafeForPublish(record.filePath)) {
this.fail(record, 'INVALID_PARAMS', '只能发布 .cindy 插件包');
@@ -293,7 +354,14 @@ export class PluginPublisherOrchestrator {
this.fail(record, 'PUBLISH_PACKAGE_ID_MISMATCH', '打包票据与待发布插件 id 不一致');
return;
}
- handle = await fsPromises.open(record.filePath, fs.constants.O_RDONLY);
+ // Inspect is serialized and short-lived. Reserve the durable open-fd / confirmation
+ // resource only after inspect succeeds, but before opening the package.
+ if (!this.tryAcquirePendingConfirmation(record.owner)) {
+ this.fail(record, 'SERVER_BUSY', '待确认的发布任务过多,请先处理已有确认');
+ return;
+ }
+ pendingConfirmationHeld = true;
+ handle = await this.openFile(record.filePath, fs.constants.O_RDONLY);
const stat = await handle.stat();
if (!stat.isFile()) {
this.fail(record, 'INVALID_PARAMS', '只能发布普通文件');
@@ -312,14 +380,22 @@ export class PluginPublisherOrchestrator {
orgSlug: identity.orgSlug,
totalBytes: stat.size,
});
- const confirmed = await confirm({
- orgSlug: identity.orgSlug,
- orgName: identity.orgName,
- ghostId: inspected.ghostId,
- name: inspected.name,
- version: inspected.version,
- sizeBytes: stat.size,
- });
+ const confirmed = await waitForConfirmationOrAbort(
+ confirm(
+ {
+ orgSlug: identity.orgSlug,
+ orgName: identity.orgName,
+ ghostId: inspected.ghostId,
+ name: inspected.name,
+ version: inspected.version,
+ sizeBytes: stat.size,
+ },
+ signal,
+ ),
+ signal,
+ );
+ this.releasePendingConfirmation(record.owner);
+ pendingConfirmationHeld = false;
if (!confirmed || signal.aborted) {
this.update(record, {
stage: signal.aborted ? 'cancelled' : 'failed',
@@ -367,19 +443,37 @@ export class PluginPublisherOrchestrator {
const putFile = this.deps.putFile ?? putLocalFile;
const openHandle = handle;
- const putDeadlineMs = remainingPutBudgetMs(prepared.expiresAt, this.now());
- const putOnce = () =>
- putFile(openHandle, {
+ const putDeadline = putDeadlineAtMs(prepared.expiresAt, this.now());
+ const putOnce = () => {
+ const remainingBudgetMs = putDeadline - this.now();
+ if (remainingBudgetMs < PLUGIN_PUBLISHER_MIN_PUT_BUDGET_MS) {
+ throw new PluginPublisherPutDeadlineExpiredError();
+ }
+ return putFile(openHandle, {
putUrl: prepared.putUrl,
headers: prepared.headers,
sizeBytes: digest.sizeBytes,
signal,
- maxTotalMs: putDeadlineMs,
+ maxTotalMs: remainingBudgetMs,
onBytes: (bytesSent) => {
this.update(record, { stage: 'uploading', bytesSent, totalBytes: digest.sizeBytes });
},
});
- const putOutcome = await this.putWithRecovery(putOnce);
+ };
+ let putOutcome: Awaited<ReturnType<PluginPublisherOrchestrator['putWithRecovery']>>;
+ try {
+ putOutcome = await this.putWithRecovery(putOnce);
+ } catch (error) {
+ if (error instanceof PluginPublisherPutDeadlineExpiredError) {
+ this.update(record, {
+ stage: 'expired',
+ status: 'expired',
+ message: '上传会话已过期',
+ });
+ return;
+ }
+ throw error;
+ }
if (putOutcome === 'cancelled_incomplete' || putOutcome === 'cancelled_uncertain') {
this.update(record, {
stage: 'cancelled',
@@ -420,6 +514,7 @@ export class PluginPublisherOrchestrator {
}
this.fail(record, 'INTERNAL', '发布失败');
} finally {
+ if (pendingConfirmationHeld) this.releasePendingConfirmation(record.owner);
await handle?.close().catch(() => undefined);
try {
await sourceBinding?.onTerminal?.();
diff --git a/apps/desktop/src/main/plugin-publisher/types.ts b/apps/desktop/src/main/plugin-publisher/types.ts
index deabe1692c..d14d7976b2 100644
--- a/apps/desktop/src/main/plugin-publisher/types.ts
+++ b/apps/desktop/src/main/plugin-publisher/types.ts
@@ -55,13 +55,18 @@ export const PLUGIN_PUBLISHER_MAX_CONCURRENT = 2;
export const PLUGIN_PUBLISHER_UPLOAD_TTL_MS = 60 * 60_000;
/** Leave this much of the session TTL for commit after PUT. */
export const PLUGIN_PUBLISHER_COMMIT_MARGIN_MS = 90_000;
+/** Do not start a PUT that cannot receive at least one second of network time. */
+export const PLUGIN_PUBLISHER_MIN_PUT_BUDGET_MS = 1_000;
export const PLUGIN_PUBLISHER_POLL_MAX_TRANSIENT_RETRIES = 8;
export const PLUGIN_PUBLISHER_POLL_TRANSIENT_BACKOFF_MS = 2_000;
-export function remainingPutBudgetMs(expiresAt: string, now: number): number {
+export function putDeadlineAtMs(expiresAt: string, now: number): number {
const expiresAtMs = Date.parse(expiresAt);
- const remaining = Number.isFinite(expiresAtMs)
- ? expiresAtMs - now - PLUGIN_PUBLISHER_COMMIT_MARGIN_MS
- : PLUGIN_PUBLISHER_UPLOAD_TTL_MS - PLUGIN_PUBLISHER_COMMIT_MARGIN_MS;
- return Math.max(1_000, remaining);
+ return Number.isFinite(expiresAtMs)
+ ? expiresAtMs - PLUGIN_PUBLISHER_COMMIT_MARGIN_MS
+ : now + PLUGIN_PUBLISHER_UPLOAD_TTL_MS - PLUGIN_PUBLISHER_COMMIT_MARGIN_MS;
+}
+
+export function remainingPutBudgetMs(expiresAt: string, now: number): number {
+ return Math.max(PLUGIN_PUBLISHER_MIN_PUT_BUDGET_MS, putDeadlineAtMs(expiresAt, now) - now);
}