Open source CapCut alternative.
TypeScript
fix(site): wait for a ChatGPT card that is booting
David Le362bbf3a1964
diff --git a/site/src/clients/chatgpt/server/oauthTokens.ts b/site/src/clients/chatgpt/server/oauthTokens.tsindex b9ab80cc..bef13fee 100644--- a/site/src/clients/chatgpt/server/oauthTokens.ts+++ b/site/src/clients/chatgpt/server/oauthTokens.ts@@ -323,6 +323,21 @@ export async function redeemEditorCode(return { userId: grant.userId, grantId: grant.id };}+/** How long a card that just redeemed its link takes to boot the editor and+ * claim its first batch. */+const EDITOR_BOOT_MS = 20_000;++/** When the card this connection framed last is done booting; 0 when none is+ * booting. An edit queued before then waits for that card. */+export async function editorBootDeadline(grantId: string, db = prisma): Promise<number> {+ const latest = await db.chatgptToken.findFirst({+ where: { grantId, kind: "embed", consumedAt: { gte: new Date(Date.now() - EDITOR_BOOT_MS) } },+ orderBy: { consumedAt: "desc" },+ select: { consumedAt: true },+ });+ return latest?.consumedAt ? latest.consumedAt.getTime() + EDITOR_BOOT_MS : 0;+}+/** The editor session a code produced, kept so revoking the connection ends it. */export async function recordEditorSession(grantId: string,diff --git a/site/src/clients/chatgpt/server/projects.ts b/site/src/clients/chatgpt/server/projects.tsindex 0543512b..71ed61d9 100644--- a/site/src/clients/chatgpt/server/projects.ts+++ b/site/src/clients/chatgpt/server/projects.ts@@ -19,7 +19,7 @@ import { usageBytes } from "@/cut/server/cloud/usage";import { wakeRenderWorker } from "@/cut/server/cloud/wake";import type { ImportUrlResult } from "@/cut/worker/importUrlJob";import type { Download, Editor, Playback, ProjectView } from "@/clients/chatgpt/contracts";-import { createEditorCode } from "@/clients/chatgpt/server/oauthTokens";+import { createEditorCode, editorBootDeadline } from "@/clients/chatgpt/server/oauthTokens";import type { ChatgptConfig } from "@/clients/chatgpt/server/config";import { READ_COMMANDS, unknownCommandNames } from "@/clients/chatgpt/server/catalog";@@ -109,6 +109,13 @@ export function projectTools(return { ...emptyProjectView(), view: "project", project: await getOwnedProject(projectId) };}+ /** How long a batch waits for the card: the claim window, or longer while+ * a card this connection just framed boots its editor. */+ const claimWait = {+ editorClaimMs: config.editorClaimMs,+ editorBootDeadline: () => editorBootDeadline(identity.grantId, db),+ };+function requireEdit() {if (!canEdit) throw new ProjectToolError("Reconnect Donkey Cut with editing permission.");}@@ -323,7 +330,7 @@ export function projectTools(if (!record.files?.length || !row.projectId) return { state: "adopted", assets: [] };const queued = await adoptionBatch(row, record);if (queued instanceof Response) return { state: "failed", error: await refusalText(queued) };- const batch = await waitForJob(identity.userId, queued.id, config.commandWaitMs, { editorClaimMs: config.editorClaimMs });+ const batch = await waitForJob(identity.userId, queued.id, config.commandWaitMs, claimWait);if (!batch) return { state: "failed", error: "The import could not be added to the project." };if (batch.state === "queued" || batch.state === "running") return { state: "pending" };if (batch.state === "dismissed") return { state: "failed", error: NO_CARD_OPEN };@@ -365,7 +372,7 @@ export function projectTools(throw new ProjectToolError(`Unknown command${unknown.length > 1 ? "s" : ""}: ${unknown.join(", ")}.`);const queued = await queueCommands(identity.userId, projectId, { commands, ...opts });if (queued instanceof Response) return refusal(queued);- const row = await waitForJob(identity.userId, queued.id, config.commandWaitMs, { editorClaimMs: config.editorClaimMs });+ const row = await waitForJob(identity.userId, queued.id, config.commandWaitMs, claimWait);if (!row) throw new ProjectToolError("The job disappeared. Try again.");return jobView(row);}diff --git a/site/src/cut/server/cloud/commands.test.ts b/site/src/cut/server/cloud/commands.test.tsindex 538a4ceb..256135cd 100644--- a/site/src/cut/server/cloud/commands.test.ts+++ b/site/src/cut/server/cloud/commands.test.ts@@ -92,6 +92,27 @@ test("a batch no card claims in time is dismissed with the answer the tool givesexpect(await claimEditorBatch("u", "p")).toBeNull();});+test("a batch waits past the claim window for a card that is still booting its editor", async () => {+ const queued = await queueCommands("u", "p", { commands: [{ name: "set_aspect", input: { aspect: "1:1" } }] });+ const id = (queued as { id: string }).id;+ rows[0].createdAt = new Date(Date.now() - 5000);++ // The card framed a moment ago; its editor claims and settles the batch+ // while the tool waits.+ setTimeout(async () => {+ await claimEditorBatch("u", "p");+ await settleEditorBatch("u", id, { ok: true, results: [], changed: true, docVersion: "cloud:5" });+ }, 100);+ const row = await waitForJob("u", id, 3000, { editorClaimMs: 1000, editorBootDeadline: async () => Date.now() + 10_000 });+ expect(row?.state).toBe("done");++ // Once the boot allowance is spent, an unclaimed batch is dismissed.+ await queueCommands("u", "p", { commands: [{ name: "undo", input: {} }] });+ rows[1].createdAt = new Date(Date.now() - 5000);+ const late = await waitForJob("u", rows[1].id, 50, { editorClaimMs: 1000, editorBootDeadline: async () => Date.now() - 1 });+ expect(late?.state).toBe("dismissed");+});+test("a claimed batch whose editor stops beating ends in error, and a late report changes nothing", async () => {await queueCommands("u", "p", { commands: [{ name: "set_aspect", input: {} }] });await claimEditorBatch("u", "p");diff --git a/site/src/cut/server/cloud/commands.ts b/site/src/cut/server/cloud/commands.tsindex 69823b85..111676a8 100644--- a/site/src/cut/server/cloud/commands.ts+++ b/site/src/cut/server/cloud/commands.ts@@ -86,13 +86,14 @@ async function expireBatch(row: Pick<JobRow, "id">): Promise<void> {/** Poll a job row until it settles or the budget runs out. The row comes back* either way; the caller reads its state. A command batch no card claims- * within `editorClaimMs` is dismissed; one whose editor stops beating ends- * in error. Any other kind of job is the worker's, which is woken as needed. */+ * within `editorClaimMs` is dismissed, unless `editorBootDeadline` says a+ * card is still booting its editor; one whose editor stops beating ends in+ * error. Any other kind of job is the worker's, which is woken as needed. */export async function waitForJob(userId: string,jobId: string,budgetMs: number,- opts: { editorClaimMs?: number } = {}+ opts: { editorClaimMs?: number; editorBootDeadline?: () => Promise<number> } = {}): Promise<JobRow | null> {const deadline = Date.now() + budgetMs;const claimMs = opts.editorClaimMs ?? 3000;@@ -101,7 +102,9 @@ export async function waitForJob(if (!row) return null;if (TERMINAL.has(row.state)) return row;if (row.kind === "commands") {- if (row.state === "queued" && claimWindowClosed(row, claimMs)) {+ // A card that framed a moment ago claims once its editor boots.+ const booting = row.state === "queued" && opts.editorBootDeadline && Date.now() < (await opts.editorBootDeadline());+ if (row.state === "queued" && claimWindowClosed(row, claimMs) && !booting) {await dismissBatch(row);continue;}