🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(cli): reuse a pending publish key only for the same request (#22315)
YuTengjing3deeec68887e
diff --git a/apps/cli/src/commands/artifact.test.ts b/apps/cli/src/commands/artifact.test.tsindex d91475c375f..c5fb7abb3ee 100644--- a/apps/cli/src/commands/artifact.test.ts+++ b/apps/cli/src/commands/artifact.test.ts@@ -5,7 +5,8 @@ import path from 'node:path';import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { registerArtifactCommand } from './artifact';+import { log } from '../utils/logger';+import { fingerprintCreate, registerArtifactCommand } from './artifact';const { mockTrpcClient } = vi.hoisted(() => ({mockTrpcClient: {@@ -235,6 +236,86 @@ describe('artifact publish', () => {expect(call.idempotencyKey).toBe('key-from-a-lost-response');});+ // T-6166: the commit failed after the site went live; the next publish+ // changed the title with --new and was rejected as a reused key.+ describe('after a commit whose outcome is unknown', () => {+ let errorSpy: ReturnType<typeof vi.spyOn>;+ const commit = () => mockTrpcClient.market.deployments.commitWorkspaceHtmlUpload.mutate;+ const preparedKey = (index: number) =>+ mockTrpcClient.market.deployments.prepareWorkspaceHtmlUpload.mutate.mock.calls[index][0]+ .idempotencyKey;++ beforeEach(async () => {+ errorSpy = vi.spyOn(log, 'error').mockImplementation(() => {});+ commit().mockRejectedValueOnce(+ Object.assign(+ new Error(+ 'The hosting service did not confirm this publish, so the site may already be live',+ ),+ { data: { code: 'INTERNAL_SERVER_ERROR' } },+ ),+ );+ await publish('--title', 'First');+ });++ afterEach(() => {+ errorSpy.mockRestore();+ });++ it('says the site may be live and that retrying is safe', () => {+ expect(exitSpy).toHaveBeenCalledWith(1);+ const output = errorSpy.mock.calls.flat().join('\n');+ expect(output).toContain('may already be live');+ expect(output).toContain('Run the same command again');+ expect(readManifest().artifacts['index.html'].pendingCreateKey).toBe(preparedKey(0));+ });++ it('reuses the key when the same command is retried', async () => {+ await publish('--title', 'First');++ expect(preparedKey(1)).toBe(preparedKey(0));+ expect(readManifest().artifacts['index.html']).toEqual({ deploymentId: 'dep-1' });+ });++ it('uses a fresh key for --new with a changed title', async () => {+ await publish('--new', '--title', 'Second');++ expect(preparedKey(1)).toEqual(expect.any(String));+ expect(preparedKey(1)).not.toBe(preparedKey(0));+ expect(readManifest().artifacts['index.html']).toEqual({ deploymentId: 'dep-1' });+ });+ });++ it('reports a definite rejection without suggesting a retry', async () => {+ const errorSpy = vi.spyOn(log, 'error').mockImplementation(() => {});+ mockTrpcClient.market.deployments.commitWorkspaceHtmlUpload.mutate.mockRejectedValueOnce(+ Object.assign(new Error('Upload expired'), { data: { code: 'BAD_REQUEST' } }),+ );++ await publish();++ expect(exitSpy).toHaveBeenCalledWith(1);+ const output = errorSpy.mock.calls.flat().join('\n');+ expect(output).toContain('Upload expired');+ expect(output).not.toContain('Run the same command again');+ errorSpy.mockRestore();+ });++ it('discards a pre-fingerprint key that market rejects as a different publish', async () => {+ const errorSpy = vi.spyOn(log, 'error').mockImplementation(() => {});+ writeManifest({ 'index.html': { pendingCreateKey: 'legacy-key', pendingType: 'html' } });+ mockTrpcClient.market.deployments.commitWorkspaceHtmlUpload.mutate.mockRejectedValueOnce(+ new Error('Idempotency key was already used for a different publish'),+ );++ await publish('--new', '--title', 'Changed');++ expect(exitSpy).toHaveBeenCalledWith(1);+ expect(errorSpy.mock.calls.flat().join('\n')).toContain('Run the command again');+ expect(readManifest().artifacts['index.html']).toEqual({});+ errorSpy.mockRestore();+ });+it('records the pending key before sending, so a crash mid-publish is recoverable', async () => {mockTrpcClient.market.deployments.prepareWorkspaceHtmlUpload.mutate.mockRejectedValueOnce(new Error('network died'),@@ -324,3 +405,29 @@ describe('artifact publish', () => {});});});++describe('fingerprintCreate', () => {+ const entry = (path: string, body: string) => ({+ body: Buffer.from(body),+ contentType: 'text/plain',+ path,+ });++ it('does not depend on the order assets finished reading', () => {+ const a = entry('/a.png', 'a');+ const b = entry('/b.png', 'b');+ const index = entry('/index.html', '<html></html>');++ expect(fingerprintCreate([index, b, a], '', 'Site')).toBe(+ fingerprintCreate([index, a, b], '', 'Site'),+ );+ });++ it('changes when the title changes', () => {+ const index = entry('/index.html', '<html></html>');++ expect(fingerprintCreate([index], '', 'First')).not.toBe(+ fingerprintCreate([index], '', 'Second'),+ );+ });+});diff --git a/apps/cli/src/commands/artifact.ts b/apps/cli/src/commands/artifact.tsindex b74ec889c55..f5d659660fe 100644--- a/apps/cli/src/commands/artifact.ts+++ b/apps/cli/src/commands/artifact.ts@@ -1,3 +1,4 @@+import { createHash } from 'node:crypto';import path from 'node:path';import {@@ -7,6 +8,7 @@ import {packWorkspaceHtmlDocument,} from '@lobechat/html-artifact';import { artifactShareUrl } from '@lobechat/utils/artifactShare';+import { toRecord } from '@lobechat/utils/object';import type { Command } from 'commander';import pc from 'picocolors';@@ -78,6 +80,35 @@ interface UploadEntry {path: string;}+/**+ * Mirrors what market compares before replaying an idempotent create: the+ * served files, the requested slug and the title. Entries are hashed in path+ * order because asset reads complete concurrently, so the gathered order can+ * differ between two runs of the same command.+ */+export const fingerprintCreate = (entries: UploadEntry[], requestedSlug: string, title: string) => {+ const hash = createHash('sha256').update(JSON.stringify([requestedSlug, title]));+ const sorted = [...entries].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));+ for (const entry of sorted) {+ hash.update(`\n${entry.path}\n${createHash('sha256').update(entry.body).digest('hex')}`);+ }+ return hash.digest('hex');+};++/**+ * A commit that failed without a definite answer: a server error (the+ * hosting service may have published before failing) or no response at all.+ * Rejections such as quota, size or an expired upload carry other codes.+ */+const isUnknownCommitOutcome = (error: unknown) => {+ const code = toRecord(toRecord(error)?.data)?.code;+ return code === undefined || code === 'INTERNAL_SERVER_ERROR';+};++/** Market's answer when a reused key carries a different request. */+const isIdempotencyConflict = (error: unknown) =>+ error instanceof Error && error.message.includes('Idempotency key was already used');+const fail = (message: string) => {log.error(message);process.exit(1);@@ -274,19 +305,35 @@ export function registerArtifactCommand(program: Command) {? { deploymentId: boundDeploymentId, kind: 'deployment' }: { kind: 'create' };+ const requestedSlug = options.slug || title;+ const fingerprint = fingerprintCreate(entries, requestedSlug, title);+// Reuse a key left behind by a create whose response never arrived, so- // the retry resolves to the deployment the server already made.+ // the retry resolves to the deployment the server already made. Only the+ // same request may reuse it: market rejects a key replayed with other+ // content or title. A key recorded without a fingerprint predates this+ // check and is still reused; a conflict below then discards it.+ const reusesPendingKey =+ !!binding.pendingCreateKey &&+ (!binding.pendingCreateFingerprint || binding.pendingCreateFingerprint === fingerprint);const idempotencyKey =target.kind === 'create'- ? (binding.pendingCreateKey ?? createIdempotencyKey())+ ? reusesPendingKey+ ? binding.pendingCreateKey+ : createIdempotencyKey(): undefined;// Recorded before the request, not after: a create that succeeds and// then loses its response must still be recoverable on the next run.const persistsBinding = target.kind === 'create' && !options.deployment;- if (persistsBinding && idempotencyKey !== binding.pendingCreateKey) {+ if (+ persistsBinding &&+ (idempotencyKey !== binding.pendingCreateKey ||+ fingerprint !== binding.pendingCreateFingerprint)+ ) {writeBinding(manifest, {...binding,+ pendingCreateFingerprint: fingerprint,pendingCreateKey: idempotencyKey,pendingType: 'html',});@@ -302,7 +349,7 @@ export function registerArtifactCommand(program: Command) {sizeBytes: item.body.byteLength,})),idempotencyKey,- requestedSlug: options.slug || title,+ requestedSlug,target,title,});@@ -328,9 +375,39 @@ export function registerArtifactCommand(program: Command) {}}- const result = await deployments.commitWorkspaceHtmlUpload.mutate({- uploadId: prepared.data.uploadId,- });+ let result: { data: DeploymentRecord };+ try {+ result = await deployments.commitWorkspaceHtmlUpload.mutate({+ uploadId: prepared.data.uploadId,+ });+ } catch (error) {+ if (persistsBinding && isIdempotencyConflict(error)) {+ // The earlier unconfirmed create went live with other content; its+ // key can never publish this request, so drop it for the next run.+ const {+ pendingCreateFingerprint: _fingerprint,+ pendingCreateKey: _key,+ pendingType: _type,+ ...rest+ } = readBinding(manifest);+ writeBinding(manifest, rest);+ fail(+ 'An earlier unconfirmed publish of this file already went live with different content, so this version was not published. Run the command again to publish it.',+ );+ return;+ }+ if (!isUnknownCommitOutcome(error)) {+ fail(formatError(error));+ return;+ }+ // The outcome is unknown, not failed: the site may be live. Retrying+ // reuses the recorded key (create) or the same target (update), so it+ // returns that site instead of publishing a second one.+ fail(+ `${formatError(error).replace(/\.$/, '')}. Run the same command again to finish publishing; it will not create a second site.`,+ );+ return;+ }if (persistsBinding && result.data.id) {writeBinding(manifest, { deploymentId: result.data.id });diff --git a/apps/cli/src/utils/artifactManifest.ts b/apps/cli/src/utils/artifactManifest.tsindex e0e72b47983..bcd8ff1f42f 100644--- a/apps/cli/src/utils/artifactManifest.ts+++ b/apps/cli/src/utils/artifactManifest.ts@@ -16,10 +16,19 @@ export interface ArtifactBinding {deploymentId?: string;expectedVersion: number;fingerprint: string;- previous: Omit<ArtifactBinding, 'pendingCanvas' | 'pendingCreateKey' | 'pendingType'>;+ previous: Omit<+ ArtifactBinding,+ 'pendingCanvas' | 'pendingCreateFingerprint' | 'pendingCreateKey' | 'pendingType'+ >;rejectedPublication?: { requestedSlug?: string };saved?: { canvasId: string; version: number; workId: string };};+ /**+ * What the pending HTML create sent (title, slug and file bytes). Market+ * replays a key only for the identical request, so a changed publish must+ * not reuse the key or it is rejected as a different publish.+ */+ pendingCreateFingerprint?: string;/*** Set before a create is sent and cleared once its deployment is recorded, so* a retry after a lost response reuses the key and the server returns the@@ -68,6 +77,7 @@ const bindingSchema = z.optional(),}).optional(),+ pendingCreateFingerprint: z.string().min(1).optional(),pendingCreateKey: z.string().min(1).optional(),pendingType: z.enum(['canvas', 'html']).optional(),})