diff --git a/.github/workflows/closura-arc-ci.yml b/.github/workflows/closura-arc-ci.yml index dcabe3208295..f5a9e0ce4161 100644 --- a/.github/workflows/closura-arc-ci.yml +++ b/.github/workflows/closura-arc-ci.yml @@ -152,7 +152,10 @@ jobs: apps/server/src/peer/RemoteDelegation.test.ts \ apps/server/src/mcp/OrchestratorMcpService.test.ts \ apps/server/src/cli/thread.test.ts \ - apps/web/src/composerDraftStore.test.ts + apps/web/src/composerDraftStore.test.ts \ + apps/web/src/components/chat/composerSend.logic.test.ts \ + apps/web/src/components/chat/chatViewSend.test.ts \ + apps/web/src/components/chat/composerImagePersistence.test.ts - name: Build native T3 server shell: bash diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 5b7bc8ad0616..3f9eb8c43997 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -67,6 +67,7 @@ import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; import * as ThreadLaunch from "./ThreadLaunchService.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as ThreadManagement from "./ThreadManagementService.ts"; +import { OrchestratorProjectionError } from "./Orchestrator.ts"; import * as ThreadTitleRegeneration from "./ThreadTitleRegenerationService.ts"; import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; import * as RemoteDelegation from "../peer/RemoteDelegation.ts"; @@ -138,6 +139,10 @@ interface HarnessOptions { readonly getLaunchSettings?: ServerSettings.ServerSettingsService["Service"]["getSettings"]; readonly providers?: ReadonlyArray; readonly git?: Partial; + /** Replaces methods of the thread service the launch uses, around the real one. */ + readonly threads?: ( + threads: ThreadManagement.ThreadManagementService["Service"], + ) => Partial; readonly isGitRepository?: CheckpointStore.CheckpointStore["Service"]["isGitRepository"]; } @@ -247,11 +252,22 @@ function makeHarness(options: HarnessOptions = {}) { folderForThread: () => Effect.succeedNone, }), ); + const wrapThreads = options.threads; + const layerLaunchThreads = + wrapThreads === undefined + ? layerThreadManagement + : Layer.effect( + ThreadManagement.ThreadManagementService, + Effect.gen(function* () { + const threads = yield* ThreadManagement.ThreadManagementService; + return { ...threads, ...wrapThreads(threads) }; + }), + ).pipe(Layer.provide(layerThreadManagement)); const layerLaunch = ThreadLaunch.layer.pipe( Layer.provide( Layer.mergeAll( layerExternalServices, - layerThreadManagement, + layerLaunchThreads, layerReceipts, layerOrchestrator, IdAllocator.layer, @@ -2000,6 +2016,45 @@ it.effect("replays a server-allocated launch", () => }), ); +// A launch can fail after its claim committed the thread, its message and its run: the caller +// gets a launch error for a launch that exists, so only the same command can settle it. +it.effect("a launch that fails after its claim committed is recovered by the same command", () => + Effect.gen(function* () { + let failedReads = 0; + const harness = makeHarness({ + threads: (threads) => ({ + getThreadProjection: (threadId) => + failedReads++ === 0 + ? Effect.fail(new OrchestratorProjectionError({ threadId })) + : threads.getThreadProjection(threadId), + }), + }); + yield* Effect.gen(function* () { + const launches = yield* ThreadLaunch.ThreadLaunchService; + const threads = yield* ThreadManagement.ThreadManagementService; + const input = launchInput({ + command: "command:launch:fails-after-claim", + thread: "thread:fails-after-claim", + message: "Run the suite", + }); + const failed = yield* launches.launch(input).pipe(Effect.flip); + assert.equal(failed._tag, "ThreadLaunchError"); + // The launch it reported as failed was accepted: its thread, message and run exist. + const accepted = yield* threads.getThreadProjection(input.threadId); + assert.equal(accepted.messages.length, 1); + assert.equal(accepted.runs.length, 1); + // The same command returns that launch; it starts nothing new. + const retried = yield* launches.launch(input); + assert.isTrue(retried.resumed); + assert.equal(retried.threadId, input.threadId); + assert.equal(retried.projection.messages.length, 1); + assert.equal(retried.projection.messages[0]?.id, accepted.messages[0]?.id); + assert.equal(retried.projection.runs.length, 1); + assert.equal(retried.projection.runs[0]?.id, accepted.runs[0]?.id); + }).pipe(Effect.provide(harness.layer)); + }), +); + it.effect("replays an accepted launch after the project disables the instance", () => { const harness = makeHarness(); return Effect.gen(function* () { diff --git a/apps/web/src/components/chat/chatViewSend.test.ts b/apps/web/src/components/chat/chatViewSend.test.ts new file mode 100644 index 000000000000..83de6940aa18 --- /dev/null +++ b/apps/web/src/components/chat/chatViewSend.test.ts @@ -0,0 +1,693 @@ +import { + CommandId, + EnvironmentId, + MessageId, + ProjectId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { createMemoryStorage } from "../../lib/storage"; + +// The server's side of uploads: the session may read, and the stored uploads still exist. +vi.mock("../../state/session", async (importOriginal) => ({ + ...(await importOriginal()), + readEnvironmentScope: () => true, +})); +vi.mock("@t3tools/client-runtime/state/attachments", async (importOriginal) => ({ + ...(await importOriginal()), + verifyPersistedAttachmentUpload: async () => ({ status: "verified" as const }), + runAttachmentUploadCycle: async () => ({ + status: "uploaded" as const, + attachmentId: "upload-file-retried", + }), +})); + +// Node has no FileReader; this one reads the real bytes, after `gate` when one is set. +let gate: Promise | null = null; +class BlobFileReader extends EventTarget { + result: string | null = null; + error: unknown = null; + async readAsDataURL(blob: Blob) { + const bytes = await blob.arrayBuffer(); + if (gate) await gate; + this.result = `data:${blob.type};base64,${Buffer.from(bytes).toString("base64")}`; + this.dispatchEvent(new Event("load")); + } +} + +const environmentId = EnvironmentId.make("environment-local"); +const otherEnvironmentId = EnvironmentId.make("environment-remote"); +const projectRef = scopeProjectRef(environmentId, ProjectId.make("project-send")); +const modelSelection = { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-sonnet-4-6", +}; + +async function openTab() { + return { + store: await import("../../composerDraftStore"), + send: await import("./chatViewSend"), + logic: await import("./composerSend.logic"), + view: await import("../ChatView.logic"), + uploads: await import("../../lib/attachmentUploadQueue"), + }; +} +type Tab = Awaited>; + +// Storage that can refuse a write, drop it without saying so, or take it and fail the read after. +const storageFaults = { throws: false, drops: false, landsUnread: false, readFails: false }; +function resetStorageFaults() { + storageFaults.throws = false; + storageFaults.drops = false; + storageFaults.landsUnread = false; + storageFaults.readFails = false; +} +function faultyStorage() { + const memory = createMemoryStorage(); + return { + getItem: (name: string) => { + if (storageFaults.readFails) { + storageFaults.readFails = false; + throw new Error("SecurityError"); + } + return memory.getItem(name); + }, + removeItem: (name: string) => memory.removeItem(name), + setItem: (name: string, value: string) => { + if (storageFaults.throws) throw new Error("QuotaExceededError"); + if (!storageFaults.drops) memory.setItem(name, value); + if (storageFaults.landsUnread) storageFaults.readFails = true; + }, + }; +} + +async function withReloadableStorage(run: () => Promise) { + vi.stubGlobal("localStorage", faultyStorage()); + vi.stubGlobal("window", new EventTarget()); + vi.stubGlobal("FileReader", BlobFileReader); + vi.useFakeTimers(); + vi.resetModules(); + try { + await run(); + } finally { + gate = null; + resetStorageFaults(); + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.resetModules(); + } +} + +/** The renderer dies: the next tab reads only what storage holds. */ +async function reload() { + vi.clearAllTimers(); + vi.resetModules(); + return openTab(); +} + +const launchRequest = (tab: Tab, branch: string | null = null) => + tab.logic.draftLaunchRequest({ + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + projectId: projectRef.projectId, + branch, + worktreePath: null, + baseBranch: null, + startFromOrigin: false, + }); + +/** A draft holding a just-attached image, whose own background saving has not run. */ +function composeDraft( + tab: Tab, + name: string, + parts: { + prompt: string; + file?: boolean; + /** The file's first upload failed: it has no upload yet, and Send retries it. */ + failedUpload?: boolean; + context?: boolean; + uploads?: boolean; + }, +) { + const store = tab.store.useComposerDraftStore.getState(); + const draftId = tab.store.DraftId.make(`draft-${name}`); + const threadId = ThreadId.make(`thread-${name}`); + store.setProjectDraftThreadId(projectRef, draftId, { threadId }); + store.setPrompt(draftId, parts.prompt); + const shot = new File([new Uint8Array([1, 2, 3, 4])], "shot.png", { type: "image/png" }); + store.addImages(draftId, [ + { + type: "image", + id: "shot-1", + name: shot.name, + mimeType: shot.type, + sizeBytes: shot.size, + previewUrl: "blob:shot-1", + file: shot, + }, + ]); + if (parts.file) { + const report = new File(["report bytes"], "report.pdf", { type: "application/pdf" }); + store.addFiles(draftId, [ + { + type: "file", + id: "file-1", + name: report.name, + mimeType: report.type, + sizeBytes: report.size, + file: report, + }, + ]); + if (!parts.failedUpload) store.setFileUpload(draftId, "file-1", environmentId, "upload-file-1"); + } + if (parts.context) { + store.addThreadContexts(draftId, [ + threadContextRecord( + scopeThreadRef(environmentId, ThreadId.make("login-thread")), + "Fix login flow", + ), + ]); + } + if (parts.uploads) { + tab.uploads.useAttachmentUploadStore.setState({ + uploadsByImageId: { + "shot-1": { status: "ready", environmentId, attachmentId: "upload-shot-1" }, + ...(parts.file + ? { + "file-1": parts.failedUpload + ? { status: "failed", environmentId, reason: "Upload failed" } + : { status: "ready", environmentId, attachmentId: "upload-file-1" }, + } + : {}), + }, + }); + } + expect(store.getComposerDraft(draftId)?.persistedAttachments).toEqual([]); + return { draftId, threadId }; +} + +/** + * A new send in the composer hook's order: read the composer, start or retry its uploads, start + * preparing attachments, read the sent composer whole, bind, commit the turn with the uploads its + * files went out as, clear, and on any failure run the hook's own cleanup. `edit` runs while reads + * are pending, `editBeforeCommit` after binding; the faults make storage refuse or drop a write. + */ +async function sendDraft( + tab: Tab, + draft: ReturnType, + options: { + uploads: boolean; + stopAfterBind?: boolean; + edit?: () => void; + editBeforeCommit?: () => void; + launchFails?: boolean; + bindFault?: "throws" | "drops" | "landsUnread"; + commitFault?: "throws" | "drops" | "landsUnread"; + /** Distinguishes a later send's operation on the same thread. */ + label?: string; + }, +) { + const store = tab.store.useComposerDraftStore.getState(); + const sentRef = scopeThreadRef(environmentId, draft.threadId); + const before = store.getComposerDraft(draft.draftId)!; + const draftThread = store.getDraftSession(draft.draftId)!; + const snapshot = tab.view.snapshotComposerSend({ + prompt: before.prompt, + images: before.images, + files: before.files, + terminalContexts: before.terminalContexts, + sendableTerminalContexts: before.terminalContexts, + previewAnnotations: before.previewAnnotations, + reviewComments: before.reviewComments, + threadContexts: before.threadContexts, + environmentContexts: before.environmentContexts, + replyTo: before.replyTo, + }); + const plan = tab.logic.resolveDraftLaunch( + draftThread.pendingLaunch, + launchRequest(tab), + tab.store.composerDraftCopySignature(before), + ); + expect(plan.type).toBe("new"); + const operation = { + commandId: `command-${draft.threadId}${options.label ?? ""}`, + messageId: `message-${draft.threadId}${options.label ?? ""}`, + createdAt: "2026-11-18T11:00:00.000Z", + request: launchRequest(tab), + }; + if (options.uploads) { + for (const attachment of snapshot.attachments) { + const upload = + tab.uploads.readAttachmentUpload(attachment.id)?.status === "failed" + ? tab.uploads.retryAttachmentUpload + : tab.uploads.startAttachmentUpload; + upload({ environmentId, image: attachment, draftTarget: draft.draftId }); + } + } + const prepared = tab.send.prepareTurnAttachments({ + environmentId, + attachments: snapshot.attachments, + usesAttachmentUploads: options.uploads, + draftTarget: draft.draftId, + }); + const sentComposer = tab.send.readSentComposer(before); + if (options.edit) { + await vi.advanceTimersByTimeAsync(0); + options.edit(); + gate = null; + } + const composer = await sentComposer; + if (options.bindFault) storageFaults[options.bindFault] = true; + const bound = tab.store.markPromotedDraftThreadByRef(sentRef, { ...operation, composer }); + resetStorageFaults(); + // The hook's cleanup for a send that did not complete: the same seams, in the same order. + const cleanUp = (cleared: boolean) => { + tab.store.restoreFailedDraftThread( + draft.draftId, + draftThread, + draft.threadId, + tab.send.launchLeftPendingAfterFailure({ + launch: operation, + priorLaunch: draftThread.pendingLaunch ?? null, + bound, + }), + ); + return tab.send.restoreFailedSendComposer({ + draftTarget: draft.draftId, + boundDraftId: bound ? draft.draftId : null, + before, + cleared, + snapshot, + }).type; + }; + if (!bound) return { bound, committed: false, cleared: false, failed: cleanUp(false), before }; + if (options.stopAfterBind) return null; + const attachments = await prepared; + options.editBeforeCommit?.(); + const turn = { + environmentId, + input: { + commandId: CommandId.make(operation.commandId), + threadId: draft.threadId, + message: { + messageId: MessageId.make(operation.messageId), + role: "user" as const, + text: before.prompt, + attachments, + }, + modelSelection, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + createdAt: operation.createdAt, + }, + }; + const fileUploads = tab.send.preparedFileUploads({ + environmentId, + attachments: snapshot.attachments, + prepared: attachments, + usesAttachmentUploads: options.uploads, + }); + const boundLaunch = store.getDraftSession(draft.draftId)?.pendingLaunch; + if (options.commitFault) storageFaults[options.commitFault] = true; + const committed = tab.store.commitPendingLaunchPayload( + sentRef, + operation.commandId, + turn, + fileUploads, + ); + resetStorageFaults(); + if (!committed) { + const rolledBack = store.getDraftSession(draft.draftId)?.pendingLaunch; + const failed = cleanUp(false); + return { + bound, + committed, + boundLaunch, + rolledBack, + turn, + cleared: false, + failed, + before, + operation, + }; + } + const cleared = tab.send.clearSentComposerContent(draft.draftId, before); + // No launch answer proves the host did not take it. + const failed = options.launchFails ? cleanUp(cleared) : undefined; + return { bound, committed, boundLaunch, turn, cleared, failed, before, operation }; +} + +function sendAgain( + tab: Tab, + draftId: ReturnType["draftId"], + branch: string | null = null, +) { + const store = tab.store.useComposerDraftStore.getState(); + const composer = store.getComposerDraft(draftId); + return { + composer, + plan: tab.logic.resolveDraftLaunch( + store.getDraftSession(draftId)?.pendingLaunch, + launchRequest(tab, branch), + tab.store.composerDraftCopySignature(composer ?? undefined), + ), + }; +} + +describe("a draft launch interrupted by a reload", () => { + it("brings back an image-only send after its clear was stored, and resends exactly its turn", async () => { + await withReloadableStorage(async () => { + const tab = await openTab(); + const draft = composeDraft(tab, "image-only", { prompt: "" }); + const sent = (await sendDraft(tab, draft, { uploads: false }))!; + expect(sent.cleared).toBe(true); + await vi.advanceTimersByTimeAsync(300); + + const { composer, plan } = sendAgain(await reload(), draft.draftId); + expect(composer?.images.map((image) => image.id)).toEqual(["shot-1"]); + expect(composer?.persistedAttachments.map((image) => image.dataUrl)).toEqual([ + "data:image/png;base64,AQIDBA==", + ]); + expect(plan.type).toBe("retry"); + expect(plan.type === "retry" ? plan.launch.turn : null).toEqual( + JSON.parse(JSON.stringify(sent.turn)), + ); + }); + }); + + it("recognises a mixed send whose clear was not stored yet as the sent copy", async () => { + await withReloadableStorage(async () => { + const tab = await openTab(); + const draft = composeDraft(tab, "mixed", { + prompt: "Review the report", + file: true, + context: true, + uploads: true, + }); + const sent = (await sendDraft(tab, draft, { uploads: true }))!; + expect(sent.turn!.input.message.attachments.map((attachment) => attachment.id)).toEqual([ + "upload-shot-1", + "upload-file-1", + ]); + + const { composer, plan } = sendAgain(await reload(), draft.draftId); + expect(composer?.images.map((image) => image.id)).toEqual(["shot-1"]); + expect(composer?.files.map((file) => file.uploadedAttachmentId)).toEqual(["upload-file-1"]); + expect(composer?.threadContexts.map((record) => record.title)).toEqual(["Fix login flow"]); + // A reload links the file inline; the sent message keeps the text it had. + expect(composer?.prompt).toContain("(t3-context://v1/file/file_file-1)"); + expect(sent.turn!.input.message.text).toBe(sent.before.prompt); + expect(plan.type).toBe("retry"); + expect(plan.type === "retry" ? plan.launch.turn : null).toEqual( + JSON.parse(JSON.stringify(sent.turn)), + ); + }); + }); + + it("keeps a draft interrupted right after binding as that operation, image included", async () => { + await withReloadableStorage(async () => { + const tab = await openTab(); + const draft = composeDraft(tab, "bound", { + prompt: "Review the report", + file: true, + uploads: true, + }); + await sendDraft(tab, draft, { uploads: true, stopAfterBind: true }); + const bound = tab.store.useComposerDraftStore + .getState() + .getDraftSession(draft.draftId)!.pendingLaunch!; + + const reloaded = await reload(); + const { composer, plan } = sendAgain(reloaded, draft.draftId); + expect(composer?.images.map((image) => image.id)).toEqual(["shot-1"]); + expect(composer?.files.map((file) => file.uploadedAttachmentId)).toEqual(["upload-file-1"]); + // Sent unchanged, it keeps its identity; its turn is still to be prepared. + expect(plan.type).toBe("retry"); + expect(plan.type === "retry" ? plan.launch : null).toMatchObject({ + commandId: bound.commandId, + messageId: bound.messageId, + createdAt: bound.createdAt, + }); + expect(plan.type === "retry" ? plan.launch.turn : null).toBeUndefined(); + expect( + reloaded.store.useComposerDraftStore.getState().getDraftSession(draft.draftId)?.sentTo, + ).toEqual(scopeThreadRef(environmentId, draft.threadId)); + }); + }); + + it("starts a changed send afresh after a crash right after binding, on the same machine and thread", async () => { + await withReloadableStorage(async () => { + const tab = await openTab(); + const draft = composeDraft(tab, "rebound", { prompt: "Run the suite" }); + await sendDraft(tab, draft, { uploads: false, stopAfterBind: true }); + + const reloaded = await reload(); + // Nothing went out, so another branch is a new operation, not a blocked one. + expect(sendAgain(reloaded, draft.draftId, "other-branch").plan.type).toBe("new"); + // It stays bound: neither balancing nor a manual switch moves its thread elsewhere. + const store = reloaded.store.useComposerDraftStore.getState(); + const elsewhere = scopeProjectRef(otherEnvironmentId, projectRef.projectId); + store.setDraftThreadContext(draft.draftId, { + projectRef: elsewhere, + environmentSelection: "auto", + loadBalancedEnvironmentId: otherEnvironmentId, + }); + store.setProjectDraftThreadId(elsewhere, draft.draftId, { environmentSelection: "manual" }); + expect( + reloaded.store.useComposerDraftStore.getState().getDraftSession(draft.draftId), + ).toMatchObject({ + environmentId, + threadId: draft.threadId, + sentTo: scopeThreadRef(environmentId, draft.threadId), + }); + }); + }); + + it("keeps an edit made while the send was reading its attachments", async () => { + await withReloadableStorage(async () => { + const tab = await openTab(); + const draft = composeDraft(tab, "edited", { prompt: "Describe this" }); + let release!: () => void; + gate = new Promise((resolve) => { + release = resolve; + }); + const store = tab.store.useComposerDraftStore.getState(); + const sent = (await sendDraft(tab, draft, { + uploads: false, + edit: () => { + store.setPrompt(draft.draftId, "Describe this and the logs"); + release(); + }, + }))!; + // The edit is the user's, so the send leaves the composer as they made it. + expect(sent.cleared).toBe(false); + expect(store.getComposerDraft(draft.draftId)?.prompt).toBe("Describe this and the logs"); + // What was sent, and stored to resend, is the message as the send read it. + expect(sent.turn!.input.message.text).toBe("Describe this"); + expect(store.getDraftSession(draft.draftId)?.pendingLaunch?.composer?.prompt).toBe( + "Describe this", + ); + }); + }); +}); + +describe("a draft launch whose file's first upload failed", () => { + const sentFileUploads = ( + composer: + | { files: ReadonlyArray<{ id: string; uploadedAttachmentId?: string }> } + | null + | undefined, + ) => composer?.files.map((file) => [file.id, file.uploadedAttachmentId]); + + it("comes back sendable, with the upload its send made, after a crash once its clear was stored", async () => { + await withReloadableStorage(async () => { + const tab = await openTab(); + const draft = composeDraft(tab, "retried-upload", { + prompt: "Review the report", + file: true, + failedUpload: true, + uploads: true, + }); + const sent = (await sendDraft(tab, draft, { uploads: true }))!; + // The send read the file before its retried upload finished. + expect(sent.before.files[0]?.uploadedAttachmentId).toBeUndefined(); + expect(sent.turn!.input.message.attachments.map((attachment) => attachment.id)).toEqual([ + "upload-shot-1", + "upload-file-retried", + ]); + await vi.advanceTimersByTimeAsync(300); + + const reloaded = await reload(); + const { composer, plan } = sendAgain(reloaded, draft.draftId); + expect(sentFileUploads(composer)).toEqual([["file-1", "upload-file-retried"]]); + expect(composer?.files.some(reloaded.store.composerFileNeedsReattach)).toBe(false); + expect(plan.type).toBe("retry"); + expect(plan.type === "retry" ? plan.launch : null).toMatchObject({ + commandId: sent.operation!.commandId, + messageId: sent.operation!.messageId, + turn: JSON.parse(JSON.stringify(sent.turn)), + }); + }); + }); + + it("restores an uncertain failed launch with that upload, kept across a reload", async () => { + await withReloadableStorage(async () => { + const tab = await openTab(); + const draft = composeDraft(tab, "restored-upload", { + prompt: "Review the report", + file: true, + failedUpload: true, + uploads: true, + }); + const sent = (await sendDraft(tab, draft, { uploads: true, launchFails: true }))!; + const restored = tab.store.useComposerDraftStore.getState().getComposerDraft(draft.draftId); + expect(sentFileUploads(restored)).toEqual([["file-1", "upload-file-retried"]]); + await vi.advanceTimersByTimeAsync(300); + + const reloaded = await reload(); + const { composer, plan } = sendAgain(reloaded, draft.draftId); + expect(sentFileUploads(composer)).toEqual([["file-1", "upload-file-retried"]]); + expect(composer?.files.some(reloaded.store.composerFileNeedsReattach)).toBe(false); + expect(plan.type).toBe("retry"); + expect(plan.type === "retry" ? plan.launch : null).toMatchObject({ + commandId: sent.operation!.commandId, + messageId: sent.operation!.messageId, + turn: JSON.parse(JSON.stringify(sent.turn)), + }); + }); + }); + + it.each(["throws", "drops", "landsUnread"] as const)( + "keeps a bound first launch as itself through the failure cleanup (turn write fault: %s)", + async (fault) => { + await withReloadableStorage(async () => { + const tab = await openTab(); + const draft = composeDraft(tab, `fault-${fault}`, { + prompt: "Review the report", + file: true, + failedUpload: true, + uploads: true, + }); + const sent = (await sendDraft(tab, draft, { uploads: true, commitFault: fault }))!; + expect(sent.committed).toBe(false); + // The commit's rollback left the operation as bound: no turn, no upload on its composer. + expect(sent.rolledBack).toEqual(sent.boundLaunch); + expect(sent.boundLaunch?.turn).toBeUndefined(); + expect(sent.boundLaunch?.composer?.files?.[0]?.attachmentId).toBeUndefined(); + // Never cleared, never launched: the composer still is the sent copy. + expect(sent.failed).toBe("kept"); + const sentRef = scopeThreadRef(environmentId, draft.threadId); + // A reload links the uploaded file inline after the user's own text. + const expectSameLaunch = (current: Tab, prompt: string) => { + const session = current.store.useComposerDraftStore + .getState() + .getDraftSession(draft.draftId)!; + const { restoredCopy: _copy, ...committed } = session.pendingLaunch!; + expect(committed).toEqual(sent.boundLaunch); + expect(session.sentTo).toEqual(sentRef); + expect( + current.store.useComposerDraftStore.getState().getComposerDraft(draft.draftId)?.prompt, + ).toBe(prompt); + // Sent again unchanged, it is that launch: same command, message and creation time. + const { plan } = sendAgain(current, draft.draftId); + expect(plan.type).toBe("retry"); + expect(plan.type === "retry" ? plan.launch : null).toMatchObject({ + commandId: sent.operation!.commandId, + messageId: sent.operation!.messageId, + createdAt: sent.operation!.createdAt, + }); + }; + expectSameLaunch(tab, "Review the report"); + await vi.advanceTimersByTimeAsync(300); + expectSameLaunch( + await reload(), + "Review the report [report.pdf](t3-context://v1/file/file_file-1) ", + ); + }); + }, + ); + + it.each([ + { fault: "throws", emptied: false }, + { fault: "drops", emptied: false }, + { fault: "drops", emptied: true }, + // Storage takes the binding but its read back fails, so the rollback must replace it. + { fault: "landsUnread", emptied: false }, + ] as const)( + "leaves the earlier bound launch untouched when an edited send's binding $fault (emptied: $emptied)", + async ({ fault, emptied }) => { + await withReloadableStorage(async () => { + const tab = await openTab(); + const draft = composeDraft(tab, `unbound-${fault}-${emptied}`, { prompt: "Run the suite" }); + const first = (await sendDraft(tab, draft, { uploads: false, commitFault: "throws" }))!; + expect(first.failed).toBe("kept"); + const store = tab.store.useComposerDraftStore.getState(); + // A bound launch that never went out, recognised as its own copy. + const earlier = store.getDraftSession(draft.draftId)!.pendingLaunch!; + expect(earlier.turn).toBeUndefined(); + expect(earlier.restoredCopy).toBeDefined(); + // Edited, it is a new candidate; storage refuses its binding, so it never binds. + store.setPrompt(draft.draftId, "Run the suite and the linter"); + const second = (await sendDraft(tab, draft, { + uploads: false, + bindFault: fault, + label: "-2", + // Emptied while the send reads it, the composer gets the new send back on failure. + ...(emptied ? { edit: () => store.clearComposerContent(draft.draftId) } : {}), + }))!; + expect(second.bound).toBe(false); + expect(second.failed).toBe(emptied ? "restored" : "kept"); + const candidate = `command-${draft.threadId}-2`; + const expectEarlier = (current: Tab) => { + const state = current.store.useComposerDraftStore.getState(); + const session = state.getDraftSession(draft.draftId)!; + // The earlier operation exactly as it was, signature included: nothing relabelled. + expect(session.pendingLaunch).toEqual(earlier); + expect(session.sentTo).toEqual(scopeThreadRef(environmentId, draft.threadId)); + expect(state.getComposerDraft(draft.draftId)?.prompt).toBe( + "Run the suite and the linter", + ); + expect( + localStorage.getItem(current.store.COMPOSER_DRAFT_STORAGE_KEY) ?? "", + ).not.toContain(candidate); + // The new text is not the earlier launch's copy: that never went out, so this is new. + expect(sendAgain(current, draft.draftId).plan.type).toBe("new"); + }; + expectEarlier(tab); + await vi.advanceTimersByTimeAsync(300); + expectEarlier(await reload()); + }); + }, + ); + + it("keeps an edit made before a failed commit as the user's, not as the bound launch's copy", async () => { + await withReloadableStorage(async () => { + const tab = await openTab(); + const draft = composeDraft(tab, "edited-failure", { prompt: "Run the suite" }); + const store = tab.store.useComposerDraftStore.getState(); + const sent = (await sendDraft(tab, draft, { + uploads: false, + commitFault: "drops", + editBeforeCommit: () => store.setPrompt(draft.draftId, "Run only the unit tests"), + }))!; + expect(sent.failed).toBe("edited"); + const expectEdited = (current: Tab) => { + const state = current.store.useComposerDraftStore.getState(); + expect(state.getComposerDraft(draft.draftId)?.prompt).toBe("Run only the unit tests"); + const session = state.getDraftSession(draft.draftId)!; + expect(session.pendingLaunch?.commandId).toBe(sent.operation!.commandId); + expect(session.pendingLaunch?.restoredCopy).toBeUndefined(); + // Not the bound launch's copy: it never went out, so it starts afresh on the same thread. + expect(sendAgain(current, draft.draftId).plan.type).toBe("new"); + expect(session.sentTo).toEqual(scopeThreadRef(environmentId, draft.threadId)); + }; + expectEdited(tab); + await vi.advanceTimersByTimeAsync(300); + expectEdited(await reload()); + }); + }); +}); diff --git a/apps/web/src/components/chat/chatViewSend.ts b/apps/web/src/components/chat/chatViewSend.ts index 079e6d18d5ee..0b4f1169ce57 100644 --- a/apps/web/src/components/chat/chatViewSend.ts +++ b/apps/web/src/components/chat/chatViewSend.ts @@ -28,10 +28,19 @@ import { newThreadId } from "~/lib/utils"; import { type ComposerFileAttachment, type ComposerImageAttachment, + type ComposerThreadDraftState, type ComposerThreadTarget, + type PendingDraftLaunch, + type PreparedFileUpload, + composerDraftHasUserContent, + markRestoredLaunchCopy, + markUnchangedLaunchCopy, + toSentComposerDraft, useComposerDraftStore, DraftId, } from "../../composerDraftStore"; +import { composerDraftContentChanged } from "./composerSend.logic"; +import { serializeComposerImages } from "./composerImagePersistence"; import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences"; import { createModelSelection } from "@t3tools/shared/model"; import type { ProviderInstanceEntry } from "../../providerInstances"; @@ -258,6 +267,52 @@ export async function rewindToMessage(input: { } } +/** + * Clears what a send took from the composer, unless the user changed it after `before` was read: + * that edit is theirs, not the send's, so it stays. True when cleared. + */ +export function clearSentComposerContent( + draftTarget: ComposerThreadTarget, + before: ComposerThreadDraftState | null, +): boolean { + const store = useComposerDraftStore.getState(); + if (composerDraftContentChanged(before, store.getComposerDraft(draftTarget) ?? null)) + return false; + store.clearComposerContent(draftTarget); + return true; +} + +/** + * The composer a launch is sent from, stored whole so a reload can put it back: every image's + * bytes are read now, not left to the draft's own background saving. Rejects when one cannot be. + */ +export async function readSentComposer(draft: ComposerThreadDraftState) { + const images = await serializeComposerImages(draft.images, draft.persistedAttachments); + if (images.length !== draft.images.length) { + throw new Error("An image could not be saved before sending, so nothing was started."); + } + return toSentComposerDraft(draft, images); +} + +/** + * The upload each sent file went out as, keyed by its own id. `prepared` is what + * `prepareTurnAttachments` returned for `attachments`, in the same order. + */ +export function preparedFileUploads(input: { + readonly environmentId: EnvironmentId; + readonly attachments: ReadonlyArray; + readonly prepared: ReadonlyArray<{ readonly id: string }>; + readonly usesAttachmentUploads: boolean; +}): PreparedFileUpload[] { + if (!input.usesAttachmentUploads) return []; + return input.attachments.flatMap((attachment, index) => { + const upload = input.prepared[index]; + return attachment.type === "file" && upload + ? [{ fileId: attachment.id, environmentId: input.environmentId, attachmentId: upload.id }] + : []; + }); +} + /** * Writes a failed send's composer contents back into its draft. Returns the * restored images, which are fresh copies so their preview URLs outlive the @@ -281,6 +336,44 @@ export function restoreComposerDraft( return images; } +/** + * The launch a failed draft send leaves pending. Once storage held its binding its outcome is the + * open one, sent or not: sent unchanged again it stays that launch. Unbound, it leaves the prior. + */ +export function launchLeftPendingAfterFailure(input: { + readonly launch: PendingDraftLaunch | undefined; + readonly priorLaunch: PendingDraftLaunch | null; + readonly bound: boolean; +}): PendingDraftLaunch | null { + return input.bound && input.launch ? input.launch : input.priorLaunch; +} + +/** + * Leaves the composer of a failed send ready to send it again. `kept`: never cleared nor edited, it + * still is the sent copy. `edited`: the user's newer content stays as it is. `restored`: put back. + */ +export function restoreFailedSendComposer(input: { + readonly draftTarget: ComposerThreadTarget; + /** The draft whose launch this send bound; null when its binding did not commit, so no other launch is relabelled. */ + readonly boundDraftId: DraftId | null; + readonly before: ComposerThreadDraftState | null; + readonly cleared: boolean; + readonly snapshot: ComposerSendSnapshot; +}): + | { readonly type: "kept" } + | { readonly type: "edited" } + | { readonly type: "restored"; readonly images: ComposerImageAttachment[] } { + const current = useComposerDraftStore.getState().getComposerDraft(input.draftTarget) ?? null; + if (!input.cleared && !composerDraftContentChanged(input.before, current)) { + if (input.boundDraftId) markUnchangedLaunchCopy(input.boundDraftId); + return { type: "kept" }; + } + if (composerDraftHasUserContent(current)) return { type: "edited" }; + const images = restoreComposerDraft(input.draftTarget, input.snapshot); + if (input.boundDraftId) markRestoredLaunchCopy(input.boundDraftId); + return { type: "restored", images }; +} + export interface MultipleModelTarget { readonly selection: ModelSelection; readonly text: string; diff --git a/apps/web/src/components/chat/composerSend.logic.test.ts b/apps/web/src/components/chat/composerSend.logic.test.ts index dea00844d6a5..d72bc017eac5 100644 --- a/apps/web/src/components/chat/composerSend.logic.test.ts +++ b/apps/web/src/components/chat/composerSend.logic.test.ts @@ -1,4 +1,4 @@ -import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { EnvironmentId, MessageId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { describe, expect, it } from "vite-plus/test"; import type { ComposerThreadDraftState } from "../../composerDraftStore"; @@ -8,6 +8,8 @@ import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; import { approvalRedirectNotice, composerDraftContentChanged, + draftLaunchRequest, + resolveDraftLaunch, loadBalancingSendWarning, multipleModelSendBlock, referencedThreadContexts, @@ -166,3 +168,79 @@ describe("approvalRedirectNotice", () => { expect(approvalRedirectNotice(settled)).toBeNull(); }); }); + +describe("draft launch retry", () => { + const request = (model: string) => + draftLaunchRequest({ + modelSelection: { instanceId: "claudeAgent", model }, + runtimeMode: "full-access", + interactionMode: "default", + projectId: "project-1", + branch: null, + worktreePath: null, + baseBranch: null, + startFromOrigin: false, + }); + const bound = { + commandId: "command-1", + messageId: "message-1", + createdAt: "2026-11-18T00:00:00.000Z", + request: request("claude-sonnet-4-6"), + restoredCopy: "restored", + }; + // The turn is stored before the launch goes out, so this one may have. + const pending = { + ...bound, + turn: { + environmentId: EnvironmentId.make("environment-local"), + input: { + threadId: ThreadId.make("thread-1"), + message: { + messageId: MessageId.make("message-1"), + role: "user" as const, + text: "Run the suite", + attachments: [], + }, + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-sonnet-4-6", + }, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + createdAt: bound.createdAt, + }, + }, + }; + + it("keeps a bound launch that never went out as itself, and lets a change start afresh", () => { + // Unchanged, it stays the same operation, its turn still to be prepared. + expect(resolveDraftLaunch(bound, request("claude-sonnet-4-6"), "restored")).toEqual({ + type: "retry", + launch: bound, + }); + // Without a turn nothing went out, so an edit or another model is a new operation. + expect(resolveDraftLaunch(bound, request("claude-sonnet-4-6"), "edited").type).toBe("new"); + expect(resolveDraftLaunch(bound, request("claude-opus-5-5"), "restored").type).toBe("new"); + }); + + it("resends a pending launch only from its unedited restored copy and unchanged request", () => { + expect(resolveDraftLaunch(null, request("claude-sonnet-4-6"), "anything")).toEqual({ + type: "new", + }); + expect(resolveDraftLaunch(pending, request("claude-sonnet-4-6"), "restored")).toEqual({ + type: "retry", + launch: pending, + }); + // An edited composer, another model, or a copy never put back is a different request. + expect(resolveDraftLaunch(pending, request("claude-sonnet-4-6"), "edited").type).toBe( + "changed", + ); + expect(resolveDraftLaunch(pending, request("claude-opus-5-5"), "restored").type).toBe( + "changed", + ); + const { restoredCopy: _copy, ...unrestored } = pending; + expect(resolveDraftLaunch(unrestored, request("claude-sonnet-4-6"), "restored").type).toBe( + "changed", + ); + }); +}); diff --git a/apps/web/src/components/chat/composerSend.logic.ts b/apps/web/src/components/chat/composerSend.logic.ts index 5b7a5ac3a09c..01bec046b45b 100644 --- a/apps/web/src/components/chat/composerSend.logic.ts +++ b/apps/web/src/components/chat/composerSend.logic.ts @@ -1,4 +1,5 @@ import type { EnvironmentId, ThreadContextRecord } from "@t3tools/contracts"; +import type { PendingDraftLaunch } from "../../composerDraftStore"; import { collectInlineContextIds } from "../../lib/composerContextReferences"; import type { ComposerThreadDraftState } from "../../composerDraftStore"; @@ -102,3 +103,43 @@ export function approvalRedirectNotice(input: { } return null; } + +/** + * What a new thread's launch asks for besides its message: model, modes and workspace. The + * message itself is the composer, which a retry must leave as it was restored. + */ +export function draftLaunchRequest(input: { + readonly modelSelection: unknown; + readonly runtimeMode: string; + readonly interactionMode: string; + readonly projectId: string; + readonly branch: string | null; + readonly worktreePath: string | null; + readonly baseBranch: string | null; + readonly startFromOrigin: boolean; +}): string { + return JSON.stringify(input); +} + +/** + * A pending launch sent again unchanged (its restored copy, `composerDraftCopySignature`, and its + * request) stays that operation. Changed, it waits while it may have gone out; its turn is stored + * before it does, so one without a turn never did and a change starts afresh on the same binding. + */ +export function resolveDraftLaunch( + pending: PendingDraftLaunch | null | undefined, + request: string, + composerSignature: string, +): + | { readonly type: "new" } + | { readonly type: "retry"; readonly launch: PendingDraftLaunch } + | { readonly type: "changed" } { + if (!pending) return { type: "new" }; + if ( + pending.request === request && + pending.restoredCopy !== undefined && + pending.restoredCopy === composerSignature + ) + return { type: "retry", launch: pending }; + return pending.turn ? { type: "changed" } : { type: "new" }; +} diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 83503fc461f3..ab6988099e26 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -18,8 +18,10 @@ import { import { isUsageLimitsCommand } from "@t3tools/shared/usageLimits"; import { AuthOrchestrationOperateScope, + CommandId, DEFAULT_MODEL, type EnvironmentId, + MessageId, type ModelSelection, type PreviewAnnotationPayload, type ScopedThreadRef, @@ -60,7 +62,7 @@ import { type ChatMessage, DEFAULT_INTERACTION_MODE } from "../../types"; import { recordPromptSent } from "../GitHubStarPrompt"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { writeTextToClipboard } from "~/hooks/useCopyToClipboard"; -import { newMessageId, newThreadId } from "~/lib/utils"; +import { newCommandId, newMessageId, newThreadId } from "~/lib/utils"; import { useNewThreadHandler } from "../../hooks/useHandleNewThread"; import { buildThreadRouteParams } from "../../threadRoutes"; import { @@ -69,6 +71,10 @@ import { finalizePromotedDraftThreadByRef, markPromotedDraftThreadByRef, restoreFailedDraftThread, + commitPendingLaunchPayload, + composerDraftCopySignature, + type PendingLaunchTurn, + type PendingDraftLaunch, checkoutPullRequestUrlToLink, composerDraftHasUserContent, type ComposerFileAttachment, @@ -100,9 +106,11 @@ import { environmentPresentations } from "../../state/presentation"; import { approvalRedirectNotice, composerDraftContentChanged, + draftLaunchRequest, loadBalancingSendWarning, multipleModelSendBlock, referencedThreadContexts, + resolveDraftLaunch, } from "./composerSend.logic"; import { useMultipleModelSend } from "./useMultipleModelSend"; import { type ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch"; @@ -128,7 +136,11 @@ import { type MultipleModelTarget, resolveMultipleModelTargets, prepareTurnAttachments, - restoreComposerDraft, + clearSentComposerContent, + launchLeftPendingAfterFailure, + preparedFileUploads, + readSentComposer, + restoreFailedSendComposer, } from "./chatViewSend"; import type { EnvironmentProject, @@ -803,6 +815,9 @@ export function useComposerSend(input: ComposerSendInput) { environmentContexts: composerEnvironmentContextsSnapshot, messageText: messageTextForSend, } = sendSnapshot; + // What the composer held when the send read it: an edit after this is the user's, never cleared. + const draftBeforeSend = + useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) ?? null; const { missingWorktreeBaseBranch, baseBranchForWorktree, @@ -847,8 +862,6 @@ export function useComposerSend(input: ComposerSendInput) { const outgoingMessageContext = buildOutgoingMessageContext( composerAttachmentsSnapshot.map((attachment) => attachment.id), ); - const messageIdForSend = newMessageId(); - const messageCreatedAt = new Date().toISOString(); const outgoingMessageText = formatOutgoingPrompt({ provider: ctxSelectedProvider, model: ctxSelectedModel, @@ -859,6 +872,58 @@ export function useComposerSend(input: ComposerSendInput) { if (composerRef.current?.validateProviderInput(outgoingMessageText) === false) { return; } + // A new thread's launch keeps its operation until its outcome is known: a retry after a + // lost answer or a launch error resends it, so the host returns what it already accepted. + const draftSessionForSend = + isLocalDraftThread && draftId + ? useComposerDraftStore.getState().getDraftSession(draftId) + : null; + const launchRequest = draftSessionForSend + ? draftLaunchRequest({ + modelSelection: ctxSelectedModelSelection, + runtimeMode, + interactionMode: DEFAULT_INTERACTION_MODE, + projectId: activeProject.id, + branch: activeThreadBranch, + worktreePath: activeThread.worktreePath, + baseBranch: baseBranchForWorktree ?? null, + startFromOrigin, + }) + : null; + const priorLaunch = draftSessionForSend?.pendingLaunch ?? null; + const launchPlan = + launchRequest === null + ? null + : resolveDraftLaunch( + priorLaunch, + launchRequest, + composerDraftCopySignature(draftBeforeSend ?? undefined), + ); + if (launchPlan?.type === "changed") { + toastManager.add( + stackedThreadToast({ + type: "warning", + title: "Your last message may already have started", + description: + "Send it unchanged to finish that send, or start a new draft for different work.", + }), + ); + return; + } + const retriedLaunch = launchPlan?.type === "retry" ? launchPlan.launch : null; + const messageIdForSend = retriedLaunch + ? MessageId.make(retriedLaunch.messageId) + : newMessageId(); + const messageCreatedAt = retriedLaunch?.createdAt ?? new Date().toISOString(); + const launchOperation: PendingDraftLaunch | undefined = + launchRequest === null + ? undefined + : (retriedLaunch ?? { + commandId: newCommandId(), + messageId: messageIdForSend, + createdAt: messageCreatedAt, + request: launchRequest, + }); const readLiveAttachmentCapabilities = () => { const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null; @@ -889,9 +954,7 @@ export function useComposerSend(input: ComposerSendInput) { multipleTargets.push(resolved); } - const draftBeforePreparation = useComposerDraftStore - .getState() - .getComposerDraft(composerDraftTarget); + const draftBeforePreparation = draftBeforeSend; const draftChangedDuringPreparation = () => { if (composerRef.current?.hasPendingAttachments() === true) return true; const draft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); @@ -1150,12 +1213,16 @@ export function useComposerSend(input: ComposerSendInput) { ); } - const turnAttachmentsPromise = prepareTurnAttachments({ - environmentId, - attachments: composerAttachmentsSnapshot, - usesAttachmentUploads: turnUsesAttachmentUploads, - draftTarget: composerDraftTarget, - }); + // A retry resends the turn its launch committed, so nothing is prepared or uploaded again. + const turnAttachmentsPromise: ReturnType = + retriedLaunch?.turn !== undefined + ? Promise.resolve([]) + : prepareTurnAttachments({ + environmentId, + attachments: composerAttachmentsSnapshot, + usesAttachmentUploads: turnUsesAttachmentUploads, + draftTarget: composerDraftTarget, + }); if (multipleModelSelections !== null) { await sendToMultipleModels({ threadId: threadIdForSend, @@ -1222,15 +1289,33 @@ export function useComposerSend(input: ComposerSendInput) { const sentDraftThreadRef = isLocalDraftThread ? scopeThreadRef(environmentId, threadIdForSend) : null; + // A new launch is bound with the whole composer it is sent from, image bytes included. + const sentComposer = + sentDraftThreadRef && launchOperation?.composer === undefined && draftBeforeSend + ? await settlePromise(() => readSentComposer(draftBeforeSend)) + : null; // Keep new-thread flows from reusing this draft while attachments and worktree setup settle. // Its machine is committed to storage before anything launches; if that fails, nothing does. - const sendBound = sentDraftThreadRef ? markPromotedDraftThreadByRef(sentDraftThreadRef) : true; - clearComposerDraftContent(composerDraftTarget); - // The prompt ref and cursor belong to the thread on screen, which may no longer be this one. - if (currentRouteThreadKeyRef.current === routeThreadKey) { - promptRef.current = ""; - composerRef.current?.resetCursorState(); - } + const sendBound = + !sentDraftThreadRef || + (sentComposer?._tag !== "Failure" && + markPromotedDraftThreadByRef( + sentDraftThreadRef, + launchOperation && sentComposer?._tag === "Success" + ? { ...launchOperation, composer: sentComposer.value } + : launchOperation, + )); + // A draft's launch clears the composer only once its turn is stored; an edit is the user's. + let composerCleared = false; + const clearSentComposer = () => { + composerCleared = clearSentComposerContent(composerDraftTarget, draftBeforeSend); + // The prompt ref and cursor belong to the thread on screen, which may no longer be this one. + if (composerCleared && currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = ""; + composerRef.current?.resetCursorState(); + } + }; + if (!sentDraftThreadRef) clearSentComposer(); const title = deriveThreadTitleSeed({ text: messageTextForSend, @@ -1243,8 +1328,9 @@ export function useComposerSend(input: ComposerSendInput) { ctxSelectedModelSelection.options, ); - let failure: AtomCommandResult | null = null; - if (!sendBound) { + let failure: AtomCommandResult | null = + sentComposer?._tag === "Failure" ? sentComposer : null; + if (failure === null && !sendBound) { const unbound = await settlePromise(async () => { throw new Error( "This draft could not be saved before sending, so nothing was started. Free up browser storage, then send again.", @@ -1302,38 +1388,99 @@ export function useComposerSend(input: ComposerSendInput) { } } + const bootstrap = + isLocalDraftThread || baseBranchForWorktree + ? { + ...(isLocalDraftThread + ? { + createThread: { + projectId: activeProject.id, + title, + modelSelection: threadCreateModelSelection, + runtimeMode, + interactionMode: DEFAULT_INTERACTION_MODE, + branch: activeThreadBranch, + worktreePath: activeThread.worktreePath, + createdAt: activeThread.createdAt, + }, + } + : {}), + ...(baseBranchForWorktree + ? { + prepareWorktree: { + projectCwd: activeProject.workspaceRoot, + baseBranch: baseBranchForWorktree, + ...(startFromOrigin ? { startFromOrigin: true } : {}), + }, + runSetupScript: true, + } + : {}), + } + : undefined; + // Exactly what this launch sends: a retry's committed turn, or a new one built now. + const turnForLaunch: PendingLaunchTurn | null = + retriedLaunch?.turn ?? + (turnAttachmentsResult._tag === "Success" + ? { + environmentId, + input: { + ...(launchOperation ? { commandId: CommandId.make(launchOperation.commandId) } : {}), + threadId: threadIdForSend, + message: { + messageId: messageIdForSend, + role: "user", + attachments: turnAttachmentsResult.value, + ...withMessageContext({ + text: outgoingMessageText, + context: buildOutgoingMessageContext( + boundAttachmentIds(turnAttachmentsResult.value, composerAttachmentsSnapshot), + ), + }), + }, + modelSelection: ctxSelectedModelSelection, + titleSeed: title, + runtimeMode, + interactionMode: DEFAULT_INTERACTION_MODE, + dispatchMode: turnDispatchMode, + ...(freshArm === undefined ? {} : { freshContext: true }), + ...(bootstrap ? { bootstrap } : {}), + createdAt: messageCreatedAt, + }, + } + : null); + // The turn is committed before it goes out, or it does not go out. + if ( + failure === null && + turnForLaunch && + sentDraftThreadRef && + launchOperation && + launchOperation.turn === undefined && + !commitPendingLaunchPayload( + sentDraftThreadRef, + launchOperation.commandId, + turnForLaunch, + turnAttachmentsResult._tag === "Success" + ? preparedFileUploads({ + environmentId, + attachments: composerAttachmentsSnapshot, + prepared: turnAttachmentsResult.value, + usesAttachmentUploads: turnUsesAttachmentUploads, + }) + : [], + ) + ) { + const unbound = await settlePromise(async () => { + throw new Error( + "This draft could not be saved before sending, so nothing was started. Free up browser storage, then send again.", + ); + }); + if (unbound._tag === "Failure") failure = unbound; + } + if (failure === null && turnForLaunch && sentDraftThreadRef) clearSentComposer(); + let backgroundDraftOpened = false; let turnStartSucceeded = false; - if (failure === null && turnAttachmentsResult._tag === "Success") { - const bootstrap = - isLocalDraftThread || baseBranchForWorktree - ? { - ...(isLocalDraftThread - ? { - createThread: { - projectId: activeProject.id, - title, - modelSelection: threadCreateModelSelection, - runtimeMode, - interactionMode: DEFAULT_INTERACTION_MODE, - branch: activeThreadBranch, - worktreePath: activeThread.worktreePath, - createdAt: activeThread.createdAt, - }, - } - : {}), - ...(baseBranchForWorktree - ? { - prepareWorktree: { - projectCwd: activeProject.workspaceRoot, - baseBranch: baseBranchForWorktree, - ...(startFromOrigin ? { startFromOrigin: true } : {}), - }, - runSetupScript: true, - } - : {}), - } - : undefined; + if (failure === null && turnForLaunch) { const backgroundThreadRef = submissionIntent === "background" && isLocalDraftThread ? scopeThreadRef(environmentId, threadIdForSend) @@ -1346,31 +1493,7 @@ export function useComposerSend(input: ComposerSendInput) { ) : null; if (backgroundThreadRef) beginBackgroundDraftSubmissionByRef(backgroundThreadRef); - const startPromise = startThreadTurn({ - environmentId, - input: { - threadId: threadIdForSend, - message: { - messageId: messageIdForSend, - role: "user", - attachments: turnAttachmentsResult.value, - ...withMessageContext({ - text: outgoingMessageText, - context: buildOutgoingMessageContext( - boundAttachmentIds(turnAttachmentsResult.value, composerAttachmentsSnapshot), - ), - }), - }, - modelSelection: ctxSelectedModelSelection, - titleSeed: title, - runtimeMode, - interactionMode: DEFAULT_INTERACTION_MODE, - dispatchMode: turnDispatchMode, - ...(freshArm === undefined ? {} : { freshContext: true }), - ...(bootstrap ? { bootstrap } : {}), - createdAt: messageCreatedAt, - }, - }); + const startPromise = startThreadTurn(turnForLaunch); if (backgroundThreadRef) { try { backgroundDraftOpened = Boolean( @@ -1455,6 +1578,12 @@ export function useComposerSend(input: ComposerSendInput) { wasBootstrapThreadDeleted(squashAtomCommandFailure(failure)) ? newThreadId() : threadIdForSend, + // No launch answer proves the host did not accept it, so a bound launch stays pending. + launchLeftPendingAfterFailure({ + launch: launchOperation, + priorLaunch, + bound: sentDraftThreadRef !== null && sendBound, + }), ); clearBackgroundDraftSubmissionByRef(scopeThreadRef(environmentId, threadIdForSend)); } @@ -1465,11 +1594,15 @@ export function useComposerSend(input: ComposerSendInput) { }); // A restored draft clones its images, so the sent copies are no longer used. optimisticBlobPreviews.release(optimisticMessage); - if ( - composerDraftHasUserContent( - useComposerDraftStore.getState().getComposerDraft(composerDraftTarget), - ) - ) { + const failedComposer = restoreFailedSendComposer({ + draftTarget: composerDraftTarget, + boundDraftId: + isLocalDraftThread && sentDraftThreadRef !== null && sendBound ? draftId : null, + before: draftBeforeSend, + cleared: composerCleared, + snapshot: sendSnapshot, + }); + if (failedComposer.type === "edited") { // A draft typed meanwhile keeps the composer, so the failed text stays reachable here. const failedText = sendSnapshot.draftText; const hasText = failedText.trim().length > 0; @@ -1500,11 +1633,10 @@ export function useComposerSend(input: ComposerSendInput) { : {}), }), ); - } else { - const retryComposerImages = restoreComposerDraft(composerDraftTarget, sendSnapshot); + } else if (failedComposer.type === "restored") { if (currentRouteThreadKeyRef.current === routeThreadKey) { promptRef.current = sendSnapshot.draftText; - composerImagesRef.current = retryComposerImages; + composerImagesRef.current = failedComposer.images; composerFilesRef.current = composerFilesSnapshot; composerTerminalContextsRef.current = composerTerminalContextsSnapshot; composerRef.current?.resetCursorState({ diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index 69e0c5d53da3..cd10f598ab30 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -21,7 +21,10 @@ import { defaultInstanceIdForDriver, DEFAULT_MODEL, DEFAULT_MODEL_BY_PROVIDER, + ChatAttachmentId, + CommandId, EnvironmentId, + MessageId, ProjectId, ProviderDriverKind, ProviderInstanceId, @@ -75,6 +78,11 @@ function selectionsByProvider( } import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vite-plus/test"; import { createMemoryStorage } from "./lib/storage"; +import { + composerDraftContentChanged, + draftLaunchRequest, + resolveDraftLaunch, +} from "./components/chat/composerSend.logic"; import { COMPOSER_DRAFT_STORAGE_KEY, @@ -88,6 +96,8 @@ import { markPromotedDraftThreadByRef, resolveDraftPromotionNavigationTarget, restoreFailedDraftThread, + markRestoredLaunchCopy, + type PendingLaunchTurn, subscribeDraftThreadPromotion, type ComposerFileAttachment, type ComposerImageAttachment, @@ -756,6 +766,157 @@ describe("composerDraftStore context persistence", () => { vi.resetModules(); } }); + + /** Shared storage that can drop a write, or take one and then fail or misread the read after. */ + function unreliableStorage() { + const memory = createMemoryStorage(); + const faults = { drops: false, readAfterWrite: null as null | "throws" | "stale" }; + let failedRead: { readonly kind: "throws" | "stale"; readonly before: string | null } | null = + null; + const storage = { + getItem: (name: string) => { + const read = failedRead; + failedRead = null; + if (read?.kind === "throws") throw new Error("SecurityError"); + return read ? read.before : memory.getItem(name); + }, + removeItem: (name: string) => memory.removeItem(name), + setItem: (name: string, value: string) => { + const before = memory.getItem(name) as string | null; + if (!faults.drops) memory.setItem(name, value); + if (faults.readAfterWrite) failedRead = { kind: faults.readAfterWrite, before }; + faults.readAfterWrite = null; + }, + }; + return { memory, faults, storage }; + } + + async function twoTabs(storage: ReturnType["storage"]) { + vi.stubGlobal("localStorage", storage); + vi.stubGlobal("window", new EventTarget()); + vi.useFakeTimers(); + vi.resetModules(); + const thisTab = await import("./composerDraftStore"); + vi.resetModules(); + const otherTab = await import("./composerDraftStore"); + return { thisTab, otherTab }; + } + + async function reloadTab() { + vi.clearAllTimers(); + vi.resetModules(); + return (await import("./composerDraftStore")).useComposerDraftStore.getState(); + } + + const unreliableRefs = { + alpha: scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("alpha-unreliable")), + beta: scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("beta-unreliable")), + gamma: scopeThreadRef(TEST_ENVIRONMENT_ID, ThreadId.make("gamma-unreliable")), + }; + const storedPrompts = (memory: ReturnType) => { + const drafts = JSON.parse(memory.getItem(COMPOSER_DRAFT_STORAGE_KEY) as string).state + .draftsByThreadKey; + return Object.values(unreliableRefs).map((ref) => drafts[scopedThreadKey(ref)]?.prompt); + }; + + it("keeps an edit whose write storage dropped, and another tab's draft, through a reload", async () => { + const { memory, faults, storage } = unreliableStorage(); + try { + const { thisTab, otherTab } = await twoTabs(storage); + const { alpha, beta, gamma } = unreliableRefs; + thisTab.useComposerDraftStore.getState().setPrompt(alpha, "first"); + await vi.advanceTimersByTimeAsync(300); + // Storage drops the edit without saying so; it must not become this tab's merge baseline. + faults.drops = true; + thisTab.useComposerDraftStore.getState().setPrompt(alpha, "edited"); + await vi.advanceTimersByTimeAsync(300); + faults.drops = false; + otherTab.useComposerDraftStore.getState().setPrompt(beta, "beta draft"); + await vi.advanceTimersByTimeAsync(300); + window.dispatchEvent( + Object.assign(new Event("storage"), { key: COMPOSER_DRAFT_STORAGE_KEY }), + ); + thisTab.useComposerDraftStore.getState().setPrompt(gamma, "third"); + await vi.advanceTimersByTimeAsync(300); + expect(storedPrompts(memory)).toEqual(["edited", "beta draft", "third"]); + const reloaded = await reloadTab(); + expect(reloaded.getComposerDraft(alpha)?.prompt).toBe("edited"); + expect(reloaded.getComposerDraft(beta)?.prompt).toBe("beta draft"); + } finally { + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.resetModules(); + } + }); + + it("replaces a binding storage took but could not read back with the rollback", async () => { + const { memory, faults, storage } = unreliableStorage(); + try { + const { thisTab } = await twoTabs(storage); + const store = thisTab.useComposerDraftStore.getState(); + const draftId = DraftId.make("draft-unread-binding"); + const threadId = ThreadId.make("thread-unread-binding"); + store.setProjectDraftThreadId( + scopeProjectRef(TEST_ENVIRONMENT_ID, ProjectId.make("project-unread")), + draftId, + { threadId }, + ); + store.setPrompt(draftId, "Run the suite"); + await vi.advanceTimersByTimeAsync(300); + faults.readAfterWrite = "throws"; + const bound = thisTab.markPromotedDraftThreadByRef( + scopeThreadRef(TEST_ENVIRONMENT_ID, threadId), + { + commandId: "command-unread", + messageId: "message-unread", + createdAt: "2026-11-18T12:00:00.000Z", + request: "{}", + }, + ); + // Unconfirmed, it is not bound, though storage did take those bytes. + expect(bound).toBe(false); + expect(memory.getItem(COMPOSER_DRAFT_STORAGE_KEY)).toContain("command-unread"); + // Those bytes are this tab's own write, so its rollback is written over them. + await vi.advanceTimersByTimeAsync(300); + expect(memory.getItem(COMPOSER_DRAFT_STORAGE_KEY)).not.toContain("command-unread"); + const reloaded = await reloadTab(); + const session = reloaded.getDraftSession(draftId); + expect(session?.promotedTo ?? null).toBeNull(); + expect(session?.pendingLaunch ?? null).toBeNull(); + expect(reloaded.getComposerDraft(draftId)?.prompt).toBe("Run the suite"); + } finally { + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.resetModules(); + } + }); + + it("merges another tab's change over a write storage took but misread", async () => { + const { memory, faults, storage } = unreliableStorage(); + try { + const { thisTab, otherTab } = await twoTabs(storage); + const { alpha, beta, gamma } = unreliableRefs; + thisTab.useComposerDraftStore.getState().setPrompt(alpha, "first"); + await vi.advanceTimersByTimeAsync(300); + // The edit lands, but the read after it shows the old bytes: it stays unconfirmed. + faults.readAfterWrite = "stale"; + thisTab.useComposerDraftStore.getState().setPrompt(alpha, "edited"); + await vi.advanceTimersByTimeAsync(300); + // Another tab then saves its own draft over those bytes: a genuinely different document. + otherTab.useComposerDraftStore.getState().setPrompt(beta, "beta draft"); + await vi.advanceTimersByTimeAsync(300); + thisTab.useComposerDraftStore.getState().setPrompt(gamma, "third"); + await vi.advanceTimersByTimeAsync(300); + expect(storedPrompts(memory)).toEqual(["edited", "beta draft", "third"]); + const reloaded = await reloadTab(); + expect(reloaded.getComposerDraft(beta)?.prompt).toBe("beta draft"); + expect(reloaded.getComposerDraft(alpha)?.prompt).toBe("edited"); + } finally { + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.resetModules(); + } + }); }); describe("composerDraftStore thread contexts", () => { @@ -1318,6 +1479,466 @@ describe("composerDraftStore project draft thread mapping", () => { } }); + it("retries an unconfirmed launch as its original operation and recovers the accepted result, across a reload", async () => { + let storageFails = false; + let storageDrops = false; + const memory = createMemoryStorage(); + const sharedStorage = { + getItem: (name: string) => memory.getItem(name), + removeItem: (name: string) => memory.removeItem(name), + setItem: (name: string, value: string) => { + if (storageFails) throw new Error("QuotaExceededError"); + if (storageDrops) return; + memory.setItem(name, value); + }, + }; + vi.stubGlobal("localStorage", sharedStorage); + vi.stubGlobal("window", new EventTarget()); + vi.useFakeTimers(); + vi.resetModules(); + try { + // The host keeps launch receipts by command id: the same command replays its result, and + // a different one for a thread that exists is refused. + const accepted = new Map(); + // After accepting, the host can still fail the call (a read after its commit), so the + // client gets a launch error for a launch that exists. + let failsAfterAccepting = false; + // Every launch's attachment references as sent, and as storage held them at that moment. + const sends: Array<{ + commandId: string; + attachmentIds: ReadonlyArray; + persistedIds: ReadonlyArray | null; + }> = []; + const persistedAttachmentIds = (draftKey: DraftId) => { + const raw = memory.getItem(COMPOSER_DRAFT_STORAGE_KEY) as string | null; + const launch = raw + ? JSON.parse(raw).state.draftThreadsByThreadKey[draftKey]?.pendingLaunch + : undefined; + const stored = launch?.turn?.input?.message?.attachments; + return stored === undefined + ? null + : (stored as Array<{ id: string }>).map((attachment) => attachment.id); + }; + const launchThere = ( + draftKey: DraftId, + operation: { commandId: string; messageId: string }, + sent: ThreadId, + attachments: ReadonlyArray, + ) => { + sends.push({ + commandId: operation.commandId, + attachmentIds: attachments.map((attachment) => (attachment as { id: string }).id), + persistedIds: persistedAttachmentIds(draftKey), + }); + const replayed = accepted.get(operation.commandId); + if (replayed) return replayed; + if ([...accepted.values()].some((launch) => launch.threadId === sent)) + return { refused: `Thread ${sent} already exists.` }; + const launched = { + threadId: sent, + messageId: operation.messageId, + runId: `run-${accepted.size + 1}`, + }; + accepted.set(operation.commandId, launched); + return failsAfterAccepting ? { error: "Failed to launch thread" } : launched; + }; + let allocated = 0; + let uploads = 0; + let storageFailsBeforePayload = false; + let storageDropsBeforePayload = false; + // Preparing attachments uploads them again: a fresh reference each time. + const prepare = () => [ + { + type: "image" as const, + id: ChatAttachmentId.make(`pending-upload-${++uploads}`), + name: "shot.png", + mimeType: "image/png", + sizeBytes: 4, + }, + ]; + // The composer's send, in its order: bind the operation with the composer it is sent from, + // prepare the attachments, commit their references, clear the composer, launch; any failure + // restores the draft with the launch still unknown (the one sent, or before sending, the one + // pending before). + const request = draftLaunchRequest({ + modelSelection: { instanceId: "claudeAgent", model: "claude-sonnet-4-6" }, + runtimeMode: "full-access", + interactionMode: "default", + projectId: projectRef.projectId, + branch: null, + worktreePath: null, + baseBranch: null, + startFromOrigin: false, + }); + const send = ( + tab: typeof import("./composerDraftStore"), + draftKey: DraftId, + text: string, + crashBeforePayload = false, + ) => { + const store = tab.useComposerDraftStore.getState(); + // The user's composer: typing `text` if it holds something else. + if ((store.getComposerDraft(draftKey)?.prompt ?? "") !== text) + store.setPrompt(draftKey, text); + const draftBefore = store.getComposerDraft(draftKey) ?? null; + const draft = store.getDraftSession(draftKey)!; + const priorLaunch = draft.pendingLaunch ?? null; + const plan = resolveDraftLaunch( + priorLaunch, + request, + tab.composerDraftCopySignature(draftBefore ?? undefined), + ); + if (plan.type === "changed") return { changed: true } as const; + allocated += 1; + const operation = + plan.type === "retry" + ? plan.launch + : { + commandId: `command-${allocated}`, + messageId: `message-${allocated}`, + createdAt: "2026-11-18T00:00:00.000Z", + request, + composer: tab.toSentComposerDraft(draftBefore!, []), + }; + const sentRef = scopeThreadRef(draft.environmentId, draft.threadId); + // The hook's failure path: the draft and, from the send's own snapshot, its composer. + const fail = (launchAttempted: boolean) => { + tab.restoreFailedDraftThread( + draftKey, + draft, + draft.threadId, + launchAttempted ? operation : priorLaunch, + ); + tab.useComposerDraftStore.getState().setPrompt(draftKey, text); + tab.markRestoredLaunchCopy(draftKey); + }; + const bound = tab.markPromotedDraftThreadByRef(sentRef, operation); + if (!bound) { + fail(false); + return { unbound: true } as const; + } + if (crashBeforePayload) return { crashed: true } as const; + // A retry resends the turn its launch committed; a first send commits its turn first. + const turn: PendingLaunchTurn = operation.turn ?? { + environmentId: draft.environmentId, + input: { + commandId: CommandId.make(operation.commandId), + threadId: draft.threadId, + message: { + messageId: MessageId.make(operation.messageId), + role: "user" as const, + text, + attachments: prepare(), + }, + runtimeMode: "full-access", + interactionMode: "default", + }, + }; + if (storageFailsBeforePayload) storageFails = true; + if (storageDropsBeforePayload) storageDrops = true; + if ( + operation.turn === undefined && + !tab.commitPendingLaunchPayload(sentRef, operation.commandId, turn) + ) { + fail(false); + return { unbound: true } as const; + } + const now = tab.useComposerDraftStore.getState().getComposerDraft(draftKey) ?? null; + if (!composerDraftContentChanged(draftBefore, now)) store.clearComposerContent(draftKey); + const answer = launchThere( + draftKey, + operation, + draft.threadId, + turn.input.message.attachments, + ); + if ("runId" in answer) { + tab.finalizePromotedDraftThreadByRef(sentRef); + return { launched: answer, operation } as const; + } + fail(true); + return { failed: answer, operation } as const; + }; + + const before = await import("./composerDraftStore"); + before.useComposerDraftStore + .getState() + .setProjectDraftThreadId(projectRef, draftId, { threadId }); + before.useComposerDraftStore.getState().setPrompt(draftId, "Run the suite"); + await vi.advanceTimersByTimeAsync(300); + // The host takes the launch, then fails the call; the thread's shell has not arrived. + failsAfterAccepting = true; + const first = send(before, draftId, "Run the suite"); + expect(first).toMatchObject({ failed: { error: "Failed to launch thread" } }); + expect(accepted.size).toBe(1); + + // The renderer dies; the reload reads only what was committed. + vi.clearAllTimers(); + vi.resetModules(); + failsAfterAccepting = false; + const after = await import("./composerDraftStore"); + // A retry whose operation cannot be committed sends nothing and keeps that operation. + storageFails = true; + expect(send(after, draftId, "Run the suite")).toEqual({ unbound: true }); + expect( + after.useComposerDraftStore.getState().getDraftSession(draftId)?.pendingLaunch, + ).toMatchObject({ commandId: "command-1", messageId: "message-1" }); + storageFails = false; + // A changed request is not sent while the first one's outcome is unknown. + expect(send(after, draftId, "Run only the unit tests")).toEqual({ changed: true }); + expect(accepted.size).toBe(1); + // The unchanged retry is the same operation, and recovers what the host accepted. + const retried = send(after, draftId, "Run the suite"); + expect(retried).toMatchObject({ + launched: accepted.get("command-1"), + operation: { commandId: "command-1", messageId: "message-1" }, + }); + expect(accepted.size).toBe(1); + // Both sends of that operation carried the same upload, though a new one was available. + expect(sends.filter((sent) => sent.commandId === "command-1")).toEqual([ + { + commandId: "command-1", + attachmentIds: ["pending-upload-1"], + persistedIds: ["pending-upload-1"], + }, + { + commandId: "command-1", + attachmentIds: ["pending-upload-1"], + persistedIds: ["pending-upload-1"], + }, + ]); + // Settled into its thread, the accepted message is not left to be sent again. + expect(after.useComposerDraftStore.getState().getDraftSession(draftId)).toBeNull(); + expect( + after.useComposerDraftStore.getState().draftsByThreadKey[ + scopedThreadKey(scopeThreadRef(TEST_ENVIRONMENT_ID, threadId)) + ]?.prompt ?? "", + ).toBe(""); + + // When storage cannot commit the operation, nothing launches. + after.useComposerDraftStore + .getState() + .setProjectDraftThreadId(projectRef, otherDraftId, { threadId: otherThreadId }); + await vi.advanceTimersByTimeAsync(300); + storageFails = true; + expect(send(after, otherDraftId, "Another task")).toEqual({ unbound: true }); + expect(accepted.size).toBe(1); + // Nor when the references it would send cannot be committed after its binding was. + storageFails = false; + storageFailsBeforePayload = true; + const sendsBefore = sends.length; + expect(send(after, otherDraftId, "Another task")).toEqual({ unbound: true }); + expect(sends.length).toBe(sendsBefore); + expect(accepted.size).toBe(1); + // Nor when storage drops that write without saying so: only the stored bytes count. + storageFails = false; + storageFailsBeforePayload = false; + storageDropsBeforePayload = true; + expect(send(after, otherDraftId, "Another task")).toEqual({ unbound: true }); + expect(sends.length).toBe(sendsBefore); + storageDrops = false; + storageDropsBeforePayload = false; + + // The renderer dies after binding a launch, before its attachments were prepared, so its + // operation is stored without references. After the reload the draft comes back unsent. + const crashDraftId = DraftId.make("draft-crash"); + const crashThreadId = ThreadId.make("thread-crash"); + after.useComposerDraftStore + .getState() + .setProjectDraftThreadId(projectRef, crashDraftId, { threadId: crashThreadId }); + after.useComposerDraftStore.getState().setPrompt(crashDraftId, "Crash task"); + await vi.advanceTimersByTimeAsync(300); + expect(send(after, crashDraftId, "Crash task", true)).toEqual({ crashed: true }); + vi.clearAllTimers(); + vi.resetModules(); + const crashed = await import("./composerDraftStore"); + // Hydration alone brings it back as an unconfirmed send, kept on its machine. + const unsent = crashed.useComposerDraftStore.getState().getDraftSession(crashDraftId)!; + expect(unsent.promotedTo ?? null).toBeNull(); + expect(unsent.sentTo).toEqual(scopeThreadRef(TEST_ENVIRONMENT_ID, crashThreadId)); + // A retry commits its binding, then cannot commit its references, nor the restore after. + storageFailsBeforePayload = true; + expect(send(crashed, crashDraftId, "Crash task")).toEqual({ unbound: true }); + storageFails = false; + storageFailsBeforePayload = false; + // The next retry's binding write is dropped silently, while the stored binding still matches. + storageDrops = true; + const dropped = send(crashed, crashDraftId, "Crash task"); + storageDrops = false; + // Every launch went out only with references storage already held for its operation. + for (const sent of sends) expect(sent.persistedIds).toEqual(sent.attachmentIds); + expect(dropped).toEqual({ unbound: true }); + // Once storage takes the writes again, the retry goes out, its references stored first. Bound + // without a turn, it never went out, and sent unchanged it is still that operation. + expect(send(crashed, crashDraftId, "Crash task")).toMatchObject({ + launched: {}, + operation: { + commandId: unsent.pendingLaunch?.commandId, + messageId: unsent.pendingLaunch?.messageId, + createdAt: unsent.pendingLaunch?.createdAt, + }, + }); + for (const sent of sends) expect(sent.persistedIds).toEqual(sent.attachmentIds); + expect(unsent.pendingLaunch?.turn).toBeUndefined(); + expect( + [...accepted.keys()].filter((commandId) => commandId === unsent.pendingLaunch?.commandId), + ).toHaveLength(1); + } finally { + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.resetModules(); + } + }); + + it("recognizes an unchanged uploaded file as the same retry after a reload, and a swapped one as changed", async () => { + vi.stubGlobal("localStorage", createMemoryStorage()); + vi.stubGlobal("window", new EventTarget()); + vi.useFakeTimers(); + vi.resetModules(); + try { + const sentRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); + const before = await import("./composerDraftStore"); + const store = before.useComposerDraftStore.getState(); + store.setProjectDraftThreadId(projectRef, draftId, { threadId }); + store.setPrompt(draftId, "Review the report"); + const report = new File(["report bytes"], "report.pdf", { type: "application/pdf" }); + store.addFiles(draftId, [ + { + type: "file", + id: "file-1", + name: report.name, + mimeType: report.type, + sizeBytes: report.size, + file: report, + }, + ]); + store.setFileUpload(draftId, "file-1", TEST_ENVIRONMENT_ID, "pending-upload-file-1"); + const operation = { + commandId: "command-upload", + messageId: "message-upload", + createdAt: "2026-11-18T00:00:00.000Z", + request: "{}", + }; + const sentDraft = store.getDraftSession(draftId)!; + expect(before.markPromotedDraftThreadByRef(sentRef, operation)).toBe(true); + expect( + before.commitPendingLaunchPayload(sentRef, operation.commandId, { + environmentId: TEST_ENVIRONMENT_ID, + input: { + commandId: CommandId.make(operation.commandId), + threadId, + message: { + messageId: MessageId.make(operation.messageId), + role: "user" as const, + text: "Review the report", + attachments: [ + { + type: "file" as const, + id: ChatAttachmentId.make("pending-upload-file-1"), + name: report.name, + mimeType: report.type, + sizeBytes: report.size, + }, + ], + }, + modelSelection: { instanceId: CLAUDE_AGENT_INSTANCE, model: "claude-sonnet-4-6" }, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + createdAt: operation.createdAt, + }, + }), + ).toBe(true); + // An uncertain launch error: the draft and its composer come back for a retry. + before.restoreFailedDraftThread(draftId, sentDraft, threadId, operation); + before.markRestoredLaunchCopy(draftId); + await vi.advanceTimersByTimeAsync(300); + vi.clearAllTimers(); + vi.resetModules(); + const after = await import("./composerDraftStore"); + const reloaded = after.useComposerDraftStore.getState(); + const decide = () => + resolveDraftLaunch( + reloaded.getDraftSession(draftId)?.pendingLaunch, + "{}", + after.composerDraftCopySignature( + after.useComposerDraftStore.getState().getComposerDraft(draftId) ?? undefined, + ), + ).type; + // Reloaded, the file is only its upload; it is still the same retry. + expect(reloaded.getComposerDraft(draftId)?.files[0]).toMatchObject({ + file: null, + uploadedAttachmentId: "pending-upload-file-1", + }); + expect(decide()).toBe("retry"); + // The same name, type and size with other bytes is a new attachment: a different request. + const swapped = new File(["REPORT BYTES"], "report.pdf", { type: "application/pdf" }); + reloaded.removeFile(draftId, "file-1"); + reloaded.addFiles(draftId, [ + { + type: "file", + id: "file-2", + name: swapped.name, + mimeType: swapped.type, + sizeBytes: swapped.size, + file: swapped, + }, + ]); + reloaded.setFileUpload(draftId, "file-2", TEST_ENVIRONMENT_ID, "pending-upload-file-2"); + expect(swapped.size).toBe(report.size); + expect(decide()).toBe("changed"); + } finally { + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.resetModules(); + } + }); + + it("drops the restored copy of a launch the host accepted when its thread arrives", () => { + const store = useComposerDraftStore.getState(); + const sentRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); + store.setProjectDraftThreadId(projectRef, draftId, { threadId }); + const operation = { + commandId: "command-arrives", + messageId: "message-arrives", + createdAt: "2026-11-18T00:00:00.000Z", + request: "{}", + }; + const sentDraft = useComposerDraftStore.getState().getDraftSession(draftId)!; + markPromotedDraftThreadByRef(sentRef, operation); + // Its answer was lost, so the composer gives the text back for a retry. + restoreFailedDraftThread(draftId, sentDraft, threadId, operation); + store.setPrompt(draftId, "Run the suite"); + markRestoredLaunchCopy(draftId); + expect(useComposerDraftStore.getState().getDraftSession(draftId)?.pendingLaunch).toMatchObject({ + commandId: "command-arrives", + }); + // The shell arrives late: the host had accepted it, so that text is not sent again. + finalizePromotedDraftThreadByRef(sentRef); + expect(draftFor(threadId, TEST_ENVIRONMENT_ID)?.prompt ?? "").toBe(""); + }); + + it("keeps what the user added to a restored launch when its thread arrives", () => { + const store = useComposerDraftStore.getState(); + const sentRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); + store.setProjectDraftThreadId(projectRef, draftId, { threadId }); + const operation = { + commandId: "command-edited", + messageId: "message-edited", + createdAt: "2026-11-18T00:00:00.000Z", + request: "{}", + }; + const sentDraft = useComposerDraftStore.getState().getDraftSession(draftId)!; + markPromotedDraftThreadByRef(sentRef, operation); + restoreFailedDraftThread(draftId, sentDraft, threadId, operation); + store.setPrompt(draftId, "Run the suite"); + markRestoredLaunchCopy(draftId); + // The same text, now with a screenshot the user attached after the failure. + store.addImages(draftId, [makeImage({ id: "added-later", previewUrl: "blob:added-later" })]); + finalizePromotedDraftThreadByRef(sentRef); + const kept = draftFor(threadId, TEST_ENVIRONMENT_ID); + expect(kept?.prompt).toBe("Run the suite"); + expect(kept?.images.map((image) => image.id)).toEqual(["added-later"]); + }); + it("restores a failed draft without changing the fresh draft", () => { const store = useComposerDraftStore.getState(); store.setProjectDraftThreadId(projectRef, draftId, { threadId }); diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index e9b3ccab1b72..83228fa1a16e 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -4,6 +4,7 @@ import { rememberComposerImageBytes, } from "./components/chat/composerAttachmentFiles"; import { elementContextToPreviewAnnotation } from "./lib/elementContext"; +import type { StartThreadTurnInput } from "@t3tools/client-runtime/operations"; import { ResponseContextRecord, ElementContextDetails, @@ -140,8 +141,11 @@ interface ComposerDraftWrite { readonly merged: PersistedComposerDraftStoreState; } let composerDraftLoadedState: PersistedComposerDraftStoreState | null = null; +/** This tab's last write that storage was read back holding: the merge baseline. */ let composerDraftLastWrite: ComposerDraftWrite | null = null; let composerDraftPendingWrite: ComposerDraftWrite | null = null; +/** A write this tab made that was not read back; it may still have landed. */ +let composerDraftUnconfirmedWrite: ComposerDraftWrite | null = null; function readStoredComposerDraftState(): PersistedComposerDraftStoreState | null { const text = composerDraftBaseStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY); @@ -207,6 +211,15 @@ function serializeComposerDraftState(value: StorageValue): return JSON.stringify({ state: value.state, version: value.version }); } const local = partializeComposerDraftStoreState(value.state.capturedState); + // Storage holding exactly the bytes of an unconfirmed write holds this tab's write, not another's. + if (composerDraftUnconfirmedWrite) { + if ( + composerDraftBaseStorage.getItem(COMPOSER_DRAFT_STORAGE_KEY) === + composerDraftUnconfirmedWrite.text + ) + composerDraftLastWrite = composerDraftUnconfirmedWrite; + composerDraftUnconfirmedWrite = null; + } const baseline = composerDraftLastWrite?.local ?? composerDraftLoadedState; const stored = baseline ? readStoredComposerDraftState() : null; const merged = stored && baseline ? mergeComposerDraftStates(stored, local, baseline) : local; @@ -219,14 +232,20 @@ const composerDebouncedStorage = createDeferredStorage composerDraftBaseStorage.getItem(name), setItem: (name, text) => { + const attempted = composerDraftPendingWrite?.text === text ? composerDraftPendingWrite : null; + composerDraftUnconfirmedWrite = attempted; composerDraftBaseStorage.setItem(name, text); - if (composerDraftPendingWrite?.text === text) - composerDraftLastWrite = composerDraftPendingWrite; + // Storage can drop a write without saying so: only reading those bytes back confirms it. + if (attempted && composerDraftBaseStorage.getItem(name) === text) { + composerDraftLastWrite = attempted; + composerDraftUnconfirmedWrite = null; + } }, removeItem: (name) => { composerDraftBaseStorage.removeItem(name); composerDraftLoadedState = null; composerDraftLastWrite = null; + composerDraftUnconfirmedWrite = null; }, }, serializeComposerDraftState, @@ -403,6 +422,12 @@ type LegacyPersistedComposerDraftStoreState = PersistedComposerDraftStoreState & LegacyStickyModelFields & LegacyV2StoreFields; +const PendingLaunchTurnSchema = Schema.Struct({ + environmentId: Schema.String, + input: Schema.Unknown, +}); +const isPersistedComposerThreadDraft = Schema.is(PersistedComposerThreadDraftState); + const PersistedDraftThreadState = Schema.Struct({ threadId: ThreadId, environmentId: Schema.String, @@ -436,6 +461,19 @@ const PersistedDraftThreadState = Schema.Struct({ }), ), ), + pendingLaunch: Schema.optionalKey( + Schema.NullOr( + Schema.Struct({ + commandId: Schema.String, + messageId: Schema.String, + createdAt: Schema.String, + request: Schema.String, + composer: Schema.optionalKey(PersistedComposerThreadDraftState), + turn: Schema.optionalKey(PendingLaunchTurnSchema), + restoredCopy: Schema.optionalKey(Schema.String), + }), + ), + ), }); type PersistedDraftThreadState = typeof PersistedDraftThreadState.Type; @@ -529,6 +567,32 @@ export interface DraftSessionState { promotedTo?: ScopedThreadRef | null; /** A send whose outcome was not confirmed: that machine may have started this thread id. */ sentTo?: ScopedThreadRef | null; + /** The launch last sent from this draft while its outcome is unknown; a retry resends it. */ + pendingLaunch?: PendingDraftLaunch | null; +} + +/** One launch's identity and request, so a retry is the same operation, not a new one. */ +export interface PendingDraftLaunch { + readonly commandId: string; + readonly messageId: string; + readonly createdAt: string; + /** What was asked for; a different request is a different operation. */ + readonly request: string; + /** The composer as it was sent, in its stored form, so a reload can put it back. */ + readonly composer?: DeepMutable; + /** + * Exactly what the launch sends, committed before it goes out, so a retry resends it as is. + * Absent until the launch's attachments are prepared; nothing was sent before. + */ + readonly turn?: PendingLaunchTurn; + /** The composer content put back for a retry, which a settled launch must not leave behind. */ + readonly restoredCopy?: string; +} + +/** A launch's destination and full input: text, context, attachment references and bytes, ids. */ +export interface PendingLaunchTurn { + readonly environmentId: EnvironmentId; + readonly input: StartThreadTurnInput; } export type DraftThreadState = DraftSessionState; @@ -1765,6 +1829,9 @@ function createDraftThreadState( ...(existingThread?.sentTo && existingThread.threadId === threadId ? { sentTo: existingThread.sentTo } : {}), + ...(existingThread?.pendingLaunch && existingThread.threadId === threadId + ? { pendingLaunch: existingThread.pendingLaunch } + : {}), }; } @@ -1785,6 +1852,66 @@ function checkoutPullRequestsEqual( return left === right || (left?.url === right?.url && left?.branch === right?.branch); } +function hydratedPendingLaunch( + stored: NonNullable, +): PendingDraftLaunch { + // A record whose turn or composer no longer validates keeps only its identity: never resent. + const { composer: _composer, turn: _turn, ...identity } = stored; + return storedPendingLaunch(stored) ?? identity; +} + +function isPendingLaunchTurn(candidate: unknown): candidate is PendingLaunchTurn { + if (!candidate || typeof candidate !== "object") return false; + const { environmentId, input } = candidate as Record; + if (typeof environmentId !== "string" || !input || typeof input !== "object") return false; + const { threadId, message } = input as Record; + return typeof threadId === "string" && !!message && typeof message === "object"; +} + +function storedPendingLaunch(candidate: unknown): PendingDraftLaunch | null { + const record = + candidate && typeof candidate === "object" ? (candidate as Record) : null; + if (!record) return null; + const { commandId, messageId, createdAt, request, composer, turn, restoredCopy } = record; + return typeof commandId === "string" && + commandId.length > 0 && + typeof messageId === "string" && + messageId.length > 0 && + typeof createdAt === "string" && + typeof request === "string" && + (composer === undefined || isPersistedComposerThreadDraft(composer)) && + (turn === undefined || isPendingLaunchTurn(turn)) && + (restoredCopy === undefined || typeof restoredCopy === "string") + ? { + commandId, + messageId, + createdAt, + request, + ...(composer === undefined + ? {} + : { composer: composer as DeepMutable }), + ...(turn === undefined ? {} : { turn }), + ...(restoredCopy === undefined ? {} : { restoredCopy }), + } + : null; +} + +function pendingLaunchesEqual( + left: PendingDraftLaunch | null | undefined, + right: PendingDraftLaunch | null | undefined, +): boolean { + if (!left || !right) return !left === !right; + return ( + left.commandId === right.commandId && + left.messageId === right.messageId && + left.createdAt === right.createdAt && + left.request === right.request && + JSON.stringify(left.composer) === JSON.stringify(right.composer) && + JSON.stringify(left.turn) === JSON.stringify(right.turn) && + left.restoredCopy === right.restoredCopy + ); +} + function storedThreadRef(candidate: unknown): ScopedThreadRef | null { const record = candidate && typeof candidate === "object" ? (candidate as Record) : null; @@ -1844,7 +1971,8 @@ function draftThreadsEqual(left: DraftThreadState | undefined, right: DraftThrea left.startFromOrigin === right.startFromOrigin && checkoutPullRequestsEqual(left.checkoutPullRequest, right.checkoutPullRequest) && scopedThreadRefsEqual(left.promotedTo, right.promotedTo) && - scopedThreadRefsEqual(left.sentTo, right.sentTo) + scopedThreadRefsEqual(left.sentTo, right.sentTo) && + pendingLaunchesEqual(left.pendingLaunch, right.pendingLaunch) ); } @@ -1961,6 +2089,7 @@ function normalizePersistedDraftThreads( ); const promotedTo = storedThreadRef(candidateDraftThread.promotedTo); const sentTo = storedThreadRef(candidateDraftThread.sentTo); + const pendingLaunch = storedPendingLaunch(candidateDraftThread.pendingLaunch); if (typeof projectId !== "string" || projectId.length === 0 || environmentId === undefined) { continue; } @@ -2005,6 +2134,7 @@ function normalizePersistedDraftThreads( ...(checkoutPullRequest ? { checkoutPullRequest } : {}), promotedTo, ...(sentTo ? { sentTo } : {}), + ...(pendingLaunch ? { pendingLaunch } : {}), }; } } @@ -2361,6 +2491,137 @@ function migratePersistedComposerDraftStoreState( }; } +/** One composer draft in its stored form; a stored launch keeps its composer this way too. */ +function toPersistedThreadDraft( + draft: ComposerThreadDraftState, +): DeepMutable { + const hasModelData = + Object.keys(draft.modelSelectionByProvider).length > 0 || draft.activeProvider !== null; + return { + prompt: draft.prompt, + attachments: draft.persistedAttachments, + ...(draft.files.length > 0 + ? { + files: draft.files.map((file) => ({ + id: file.id, + name: file.name, + mimeType: file.mimeType, + sizeBytes: file.sizeBytes, + ...(file.source ? { source: file.source } : {}), + ...(file.uploadedAttachmentId && file.uploadEnvironmentId + ? { + attachmentId: file.uploadedAttachmentId, + environmentId: file.uploadEnvironmentId, + } + : {}), + })), + } + : {}), + ...(draft.terminalContexts.length > 0 + ? { + terminalContexts: draft.terminalContexts.map((context) => ({ + id: context.id, + threadId: context.threadId, + createdAt: context.createdAt, + terminalId: context.terminalId, + terminalLabel: context.terminalLabel, + lineStart: context.lineStart, + lineEnd: context.lineEnd, + text: context.text, + })), + } + : {}), + ...(draft.previewAnnotations.length > 0 + ? { + previewAnnotations: draft.previewAnnotations.map( + (annotation) => ({ ...annotation }) as DeepMutable, + ), + } + : {}), + ...(draft.reviewComments.length > 0 + ? { + reviewComments: draft.reviewComments.map((comment) => ({ ...comment })), + } + : {}), + ...(draft.threadContexts.length > 0 + ? { threadContexts: draft.threadContexts.map((record) => ({ ...record })) } + : {}), + ...(draft.environmentContexts.length > 0 + ? { environmentContexts: draft.environmentContexts.map((record) => ({ ...record })) } + : {}), + ...(draft.replyTo + ? { replyTo: { ...draft.replyTo } as DeepMutable } + : {}), + ...(hasModelData + ? { + modelSelectionByProvider: compactModelSelectionByProvider(draft.modelSelectionByProvider), + activeProvider: draft.activeProvider, + ...(draft.modelSelectionExplicit ? { modelSelectionExplicit: true } : {}), + } + : {}), + ...(draft.runtimeMode ? { runtimeMode: draft.runtimeMode } : {}), + ...(draft.interactionMode ? { interactionMode: draft.interactionMode } : {}), + }; +} + +/** + * The composer a launch is sent from, in stored form with `images` holding every image's bytes: + * the live draft's stored images can still be catching up with what it shows. + */ +export function toSentComposerDraft( + draft: ComposerThreadDraftState, + images: ReadonlyArray, +): DeepMutable { + return toPersistedThreadDraft({ ...draft, persistedAttachments: [...images] }); +} + +/** + * Gives the draft what the sent copy of its own attachments holds and it lacks: an image's + * bytes, a file's upload. Matched by attachment id, so a replaced attachment is left alone. + */ +function withSentAttachments( + draft: ComposerThreadDraftState, + sent: PersistedComposerThreadDraftState, +): ComposerThreadDraftState { + const stored = new Set(draft.persistedAttachments.map((attachment) => attachment.id)); + const shown = new Set(draft.images.map((image) => image.id)); + const missing = sent.attachments.filter((image) => shown.has(image.id) && !stored.has(image.id)); + const uploads = new Map( + (sent.files ?? []).flatMap((file) => + file.attachmentId !== undefined && file.environmentId !== undefined + ? [[file.id, { attachmentId: file.attachmentId, environmentId: file.environmentId }]] + : [], + ), + ); + const unstamped = draft.files.filter( + (file) => file.uploadedAttachmentId === undefined && uploads.has(file.id), + ); + if (missing.length === 0 && unstamped.length === 0) return draft; + const added = new Set(missing.map((image) => image.id)); + return { + ...draft, + persistedAttachments: [...draft.persistedAttachments, ...missing], + nonPersistedImageIds: draft.nonPersistedImageIds.filter((id) => !added.has(id)), + files: draft.files.map((file) => { + const upload = file.uploadedAttachmentId === undefined ? uploads.get(file.id) : undefined; + return upload + ? { + ...file, + uploadedAttachmentId: upload.attachmentId, + uploadEnvironmentId: upload.environmentId as EnvironmentId, + } + : file; + }), + }; +} + +/** The upload a sent file went out as, keyed by that file's own id. */ +export interface PreparedFileUpload { + readonly fileId: string; + readonly environmentId: EnvironmentId; + readonly attachmentId: string; +} + export function partializeComposerDraftStoreState( state: ComposerDraftStoreState, ): PersistedComposerDraftStoreState { @@ -2406,74 +2667,7 @@ export function partializeComposerDraftStoreState( ) { continue; } - const persistedDraft: DeepMutable = { - prompt: draft.prompt, - attachments: draft.persistedAttachments, - ...(draft.files.length > 0 - ? { - files: draft.files.map((file) => ({ - id: file.id, - name: file.name, - mimeType: file.mimeType, - sizeBytes: file.sizeBytes, - ...(file.source ? { source: file.source } : {}), - ...(file.uploadedAttachmentId && file.uploadEnvironmentId - ? { - attachmentId: file.uploadedAttachmentId, - environmentId: file.uploadEnvironmentId, - } - : {}), - })), - } - : {}), - ...(draft.terminalContexts.length > 0 - ? { - terminalContexts: draft.terminalContexts.map((context) => ({ - id: context.id, - threadId: context.threadId, - createdAt: context.createdAt, - terminalId: context.terminalId, - terminalLabel: context.terminalLabel, - lineStart: context.lineStart, - lineEnd: context.lineEnd, - text: context.text, - })), - } - : {}), - ...(draft.previewAnnotations.length > 0 - ? { - previewAnnotations: draft.previewAnnotations.map( - (annotation) => ({ ...annotation }) as DeepMutable, - ), - } - : {}), - ...(draft.reviewComments.length > 0 - ? { - reviewComments: draft.reviewComments.map((comment) => ({ ...comment })), - } - : {}), - ...(draft.threadContexts.length > 0 - ? { threadContexts: draft.threadContexts.map((record) => ({ ...record })) } - : {}), - ...(draft.environmentContexts.length > 0 - ? { environmentContexts: draft.environmentContexts.map((record) => ({ ...record })) } - : {}), - ...(draft.replyTo - ? { replyTo: { ...draft.replyTo } as DeepMutable } - : {}), - ...(hasModelData - ? { - modelSelectionByProvider: compactModelSelectionByProvider( - draft.modelSelectionByProvider, - ), - activeProvider: draft.activeProvider, - ...(draft.modelSelectionExplicit ? { modelSelectionExplicit: true } : {}), - } - : {}), - ...(draft.runtimeMode ? { runtimeMode: draft.runtimeMode } : {}), - ...(draft.interactionMode ? { interactionMode: draft.interactionMode } : {}), - }; - persistedDraftsByThreadKey[threadKey] = persistedDraft; + persistedDraftsByThreadKey[threadKey] = toPersistedThreadDraft(draft); } const persistedDraftThreadsByThreadKey: DeepMutable< PersistedComposerDraftStoreState["draftThreadsByThreadKey"] @@ -2699,6 +2893,26 @@ export function hydrateImagesFromPersisted( }); } +/** The prompt as a reload shows it: each attached context and file has its inline link. */ +function withInlineContextReferences(draft: { + readonly prompt: string; + readonly reviewComments: ReadonlyArray[0]>; + readonly previewAnnotations: ReadonlyArray< + Parameters[0] + >; + readonly threadContexts: ReadonlyArray[0]>; + readonly environmentContexts: ReadonlyArray[0]>; + readonly files: ReadonlyArray[0]>; +}): string { + return ensureInlineContextReferences(draft.prompt, [ + ...draft.reviewComments.map(reviewCommentContextReference), + ...draft.previewAnnotations.map(previewAnnotationContextReference), + ...draft.threadContexts.map(threadContextReference), + ...draft.environmentContexts.map(environmentContextReference), + ...draft.files.map(fileContextReference), + ]); +} + function toHydratedThreadDraft( persistedDraft: PersistedComposerThreadDraftState, ): ComposerThreadDraftState { @@ -2720,13 +2934,14 @@ function toHydratedThreadDraft( })) ?? []; return { - prompt: ensureInlineContextReferences(persistedDraft.prompt, [ - ...(persistedDraft.reviewComments ?? []).map(reviewCommentContextReference), - ...(persistedDraft.previewAnnotations ?? []).map(previewAnnotationContextReference), - ...(persistedDraft.threadContexts ?? []).map(threadContextReference), - ...(persistedDraft.environmentContexts ?? []).map(environmentContextReference), - ...files.map(fileContextReference), - ]), + prompt: withInlineContextReferences({ + prompt: persistedDraft.prompt, + reviewComments: persistedDraft.reviewComments ?? [], + previewAnnotations: persistedDraft.previewAnnotations ?? [], + threadContexts: persistedDraft.threadContexts ?? [], + environmentContexts: persistedDraft.environmentContexts ?? [], + files, + }), images: hydrateImagesFromPersisted(persistedDraft.attachments), files, nonPersistedImageIds: [], @@ -2798,6 +3013,9 @@ function toHydratedDraftThreadState( ), } : {}), + ...(persistedDraftThread.pendingLaunch + ? { pendingLaunch: hydratedPendingLaunch(persistedDraftThread.pendingLaunch) } + : {}), }; } @@ -3087,6 +3305,7 @@ const composerDraftStore = create()( ...(checkoutPullRequest ? { checkoutPullRequest } : {}), promotedTo: existing.promotedTo ?? null, ...(existing.sentTo ? { sentTo: existing.sentTo } : {}), + ...(existing.pendingLaunch ? { pendingLaunch: existing.pendingLaunch } : {}), }; const isUnchanged = nextDraftThread.environmentId === existing.environmentId && @@ -4525,6 +4744,7 @@ const composerDraftStore = create()( ); composerDraftLoadedState = partializeComposerDraftStoreState(composerDraftStore.getState()); +recoverUnconfirmedDraftLaunches(); export const useComposerDraftStore = composerDraftStore; @@ -4734,36 +4954,88 @@ export function usePromotingDraftThreadKeys(): ReadonlyArray { * False when storage did not take it; the caller must not launch, and each draft keeps the * promotion it had before, which an earlier send may have committed. */ -export function markPromotedDraftThreadByRef(threadRef: ScopedThreadRef): boolean { +export function markPromotedDraftThreadByRef( + threadRef: ScopedThreadRef, + /** The launch about to go out, committed with its machine so a retry resends exactly it. */ + launch?: PendingDraftLaunch, +): boolean { const draftStore = useComposerDraftStore.getState(); - const promoted = new Map(); + const promoted = new Map>(); for (const [draftId, draftThread] of Object.entries(draftStore.draftThreadsByThreadKey)) { if ( draftThread.environmentId === threadRef.environmentId && draftThread.threadId === threadRef.threadId ) { - promoted.set(draftId, draftThread.promotedTo ?? null); - draftStore.markDraftThreadPromoting(DraftId.make(draftId), threadRef); + promoted.set(draftId, { + promotedTo: draftThread.promotedTo ?? null, + pendingLaunch: draftThread.pendingLaunch ?? null, + }); } } + const update = (pick: (draftId: string) => Partial) => + useComposerDraftStore.setState((state) => ({ + draftThreadsByThreadKey: Object.fromEntries( + Object.entries(state.draftThreadsByThreadKey).map(([draftId, draftThread]) => [ + draftId, + promoted.has(draftId) ? { ...draftThread, ...pick(draftId) } : draftThread, + ]), + ), + })); + if (launch) update(() => ({ pendingLaunch: launch })); + // The drafts' own stored copies get the sent images too, so a reload shows what was sent. + if (launch?.composer) storeSentAttachments([...promoted.keys()], launch.composer); + for (const draftId of promoted.keys()) { + draftStore.markDraftThreadPromoting(DraftId.make(draftId), threadRef); + } + const draftIds = [...promoted.keys()]; if ( - promoted.size === 0 || - commitsDraftThreadBinding([...promoted.keys()], "promotedTo", threadRef) + draftIds.length === 0 || + (commitsDraftThreadBinding(draftIds, "promotedTo", threadRef) && + (!launch || commitsPendingLaunch(draftIds))) ) return true; - useComposerDraftStore.setState((state) => ({ - draftThreadsByThreadKey: Object.fromEntries( - Object.entries(state.draftThreadsByThreadKey).map(([draftId, draftThread]) => [ - draftId, - promoted.has(draftId) - ? { ...draftThread, promotedTo: promoted.get(draftId) ?? null } - : draftThread, - ]), - ), - })); + // Each draft keeps what it had, which an earlier send may have committed. + update((draftId) => promoted.get(draftId) ?? {}); return false; } +function storeSentAttachments( + draftIds: ReadonlyArray, + sent: PersistedComposerThreadDraftState, +) { + useComposerDraftStore.setState((state) => { + const draftsByThreadKey = { ...state.draftsByThreadKey }; + let changed = false; + for (const draftId of draftIds) { + const draft = draftsByThreadKey[draftId]; + const next = draft && withSentAttachments(draft, sent); + if (!next || next === draft) continue; + draftsByThreadKey[draftId] = next; + changed = true; + } + return changed ? { draftsByThreadKey } : state; + }); +} + +/** + * The stored bytes hold each draft's whole pending launch, composer and turn included; read after + * the flush that committed it. A matching command id alone is not the operation about to go out. + */ +function commitsPendingLaunch(draftIds: ReadonlyArray) { + try { + const stored = readStoredComposerDraftState(); + const current = useComposerDraftStore.getState().draftThreadsByThreadKey; + return draftIds.every((draftId) => + pendingLaunchesEqual( + storedPendingLaunch(stored?.draftThreadsByThreadKey[draftId]?.pendingLaunch), + current[draftId]?.pendingLaunch, + ), + ); + } catch { + return false; + } +} + /** Writes pending draft state now and checks the stored bytes hold `field` for each draft. */ function commitsDraftThreadBinding( draftIds: ReadonlyArray, @@ -4788,6 +5060,12 @@ export function restoreFailedDraftThread( draftId: DraftId, draftThread: DraftThreadState, threadId: ThreadId, + /** + * The launch whose outcome is still unknown: the one just sent, whose answer was lost or was + * any launch error (the host may have accepted it before failing), or, when it failed before + * anything was sent, the one pending before. A retry resends exactly it. + */ + pendingLaunch: PendingDraftLaunch | null = null, ): void { useComposerDraftStore.setState((state) => { const current = state.draftThreadsByThreadKey[draftId] ?? draftThread; @@ -4803,6 +5081,13 @@ export function restoreFailedDraftThread( ...(threadId !== draftThread.threadId ? { createdAt: new Date().toISOString() } : {}), promotedTo: null, sentTo, + // The store holds the operation as committed, with the references it sent. + pendingLaunch: + threadId !== draftThread.threadId + ? null + : pendingLaunch && current.pendingLaunch?.commandId === pendingLaunch.commandId + ? current.pendingLaunch + : pendingLaunch, }, }, }; @@ -4812,8 +5097,185 @@ export function restoreFailedDraftThread( if (sentTo) commitsDraftThreadBinding([draftId], "sentTo", sentTo); } +/** + * All the composer content a send restores, so a later edit of any of it is seen. The prompt is + * read as a reload shows it, so the same copy signs alike before and after one. + */ +export function composerDraftCopySignature(draft: ComposerThreadDraftState | undefined): string { + return JSON.stringify( + draft === undefined + ? null + : { + prompt: withInlineContextReferences(draft), + images: draft.images.map((image) => image.id), + files: draft.files.map((file) => file.id), + terminalContexts: draft.terminalContexts.map((context) => context.id), + previewAnnotations: draft.previewAnnotations.map((annotation) => annotation.id), + reviewComments: draft.reviewComments.map((comment) => comment.id), + threadContexts: draft.threadContexts.map((context) => context.contextId), + environmentContexts: draft.environmentContexts.map((context) => context.contextId), + replyTo: draft.replyTo, + }, + ); +} + +/** Records the composer content a failed launch just put back, to recognise it unedited later. */ +export function markRestoredLaunchCopy(draftId: DraftId): void { + const sent = + useComposerDraftStore.getState().draftThreadsByThreadKey[draftId]?.pendingLaunch?.composer; + if (sent) storeSentAttachments([draftId], sent); + useComposerDraftStore.setState((state) => { + const draftThread = state.draftThreadsByThreadKey[draftId]; + if (!draftThread?.pendingLaunch) return state; + return { + draftThreadsByThreadKey: { + ...state.draftThreadsByThreadKey, + [draftId]: { + ...draftThread, + pendingLaunch: { + ...draftThread.pendingLaunch, + restoredCopy: composerDraftCopySignature(state.draftsByThreadKey[draftId]), + }, + }, + }, + }; + }); +} + +/** + * Marks a composer a failed send never cleared as its pending launch's copy, only while it still + * is exactly what that launch sent: a later edit stays the user's, never taken for that copy. + */ +export function markUnchangedLaunchCopy(draftId: DraftId): void { + const state = useComposerDraftStore.getState(); + const sent = state.draftThreadsByThreadKey[draftId]?.pendingLaunch?.composer; + if ( + sent && + composerDraftCopySignature(state.draftsByThreadKey[draftId]) === + composerDraftCopySignature(toHydratedThreadDraft(sent)) + ) + markRestoredLaunchCopy(draftId); +} + +/** + * Records exactly what a launch is about to send and commits it to storage, so a retry resends it + * as is, with the uploads its files went out as on its sent composer, so a reload can send it. + * False when storage did not take the whole operation: the launch must not go out. + */ +export function commitPendingLaunchPayload( + threadRef: ScopedThreadRef, + commandId: string, + turn: PendingLaunchTurn, + fileUploads: ReadonlyArray = [], +): boolean { + const prior = new Map( + Object.entries(useComposerDraftStore.getState().draftThreadsByThreadKey).flatMap( + ([draftId, draftThread]) => + draftThread.environmentId === threadRef.environmentId && + draftThread.threadId === threadRef.threadId && + draftThread.pendingLaunch?.commandId === commandId + ? [[draftId, draftThread.pendingLaunch] as const] + : [], + ), + ); + if (prior.size === 0) return false; + const uploads = new Map(fileUploads.map((upload) => [upload.fileId, upload])); + const setLaunch = (pick: (launch: PendingDraftLaunch) => PendingDraftLaunch) => + useComposerDraftStore.setState((state) => ({ + draftThreadsByThreadKey: Object.fromEntries( + Object.entries(state.draftThreadsByThreadKey).map(([draftId, draftThread]) => { + const launch = prior.get(draftId); + return [draftId, launch ? { ...draftThread, pendingLaunch: pick(launch) } : draftThread]; + }), + ), + })); + setLaunch((launch) => ({ + ...launch, + turn, + ...(launch.composer?.files + ? { + composer: { + ...launch.composer, + files: launch.composer.files.map((file) => { + const upload = uploads.get(file.id); + return upload + ? { + ...file, + attachmentId: upload.attachmentId, + environmentId: upload.environmentId, + } + : file; + }), + }, + } + : {}), + })); + // An uncommitted operation never stays behind to pass as sent: each draft keeps what it had. + let committed = false; + try { + composerDebouncedStorage.flush(); + committed = commitsPendingLaunch([...prior.keys()]); + } catch { + committed = false; + } + if (!committed) setLaunch((launch) => launch); + return committed; +} + +/** + * A reload finds the sends whose outcome is unknown, such as one interrupted by a crash, and + * makes each its draft's unconfirmed send again: kept on its machine, with its composer back + * if that was cleared. Sending it unchanged then resends the stored turn. + */ +function recoverUnconfirmedDraftLaunches(): void { + composerDraftStore.setState((state) => { + const draftThreadsByThreadKey = { ...state.draftThreadsByThreadKey }; + const draftsByThreadKey = { ...state.draftsByThreadKey }; + let recovered = false; + for (const [draftId, draftThread] of Object.entries(state.draftThreadsByThreadKey)) { + const launch = draftThread.pendingLaunch; + if (!launch) continue; + const composer = draftsByThreadKey[draftId]; + const sent = launch.composer ? toHydratedThreadDraft(launch.composer) : undefined; + let restoredCopy = launch.restoredCopy; + if (sent && !composerDraftHasUserContent(composer)) { + draftsByThreadKey[draftId] = sent; + restoredCopy = composerDraftCopySignature(sent); + } else if ( + sent && + composerDraftCopySignature(composer) === composerDraftCopySignature(sent) + ) { + // The crash came before the composer's clear was stored: it still is the sent copy. + restoredCopy = composerDraftCopySignature(composer); + } + if (!draftThread.promotedTo && restoredCopy === launch.restoredCopy) continue; + recovered = true; + draftThreadsByThreadKey[draftId] = { + ...draftThread, + promotedTo: null, + sentTo: draftThread.sentTo ?? draftThread.promotedTo ?? null, + pendingLaunch: { ...launch, ...(restoredCopy === undefined ? {} : { restoredCopy }) }, + }; + } + return recovered ? { draftThreadsByThreadKey, draftsByThreadKey } : state; + }); +} + export function finalizePromotedDraftThreadByRef(threadRef: ScopedThreadRef): void { const draftStore = useComposerDraftStore.getState(); + // The thread exists, so its pending launch was accepted: a copy of that message restored + // for a retry is not carried into the thread to be sent again. Other edits are kept. + for (const [draftId, draftThread] of Object.entries(draftStore.draftThreadsByThreadKey)) { + const pending = draftThread.pendingLaunch; + if ( + pending && + draftThread.environmentId === threadRef.environmentId && + draftThread.threadId === threadRef.threadId && + pending.restoredCopy !== undefined && + composerDraftCopySignature(draftStore.draftsByThreadKey[draftId]) === pending.restoredCopy + ) + draftStore.clearComposerContent(DraftId.make(draftId)); + } for (const [draftId, draftThread] of Object.entries(draftStore.draftThreadsByThreadKey)) { const promotedRef = draftThread.promotedTo; const matches = promotedRef diff --git a/apps/web/src/lib/utils.ts b/apps/web/src/lib/utils.ts index 747af2d52dd3..ed4225427c85 100644 --- a/apps/web/src/lib/utils.ts +++ b/apps/web/src/lib/utils.ts @@ -1,4 +1,4 @@ -import { MessageId, ProjectId, ThreadId } from "@t3tools/contracts"; +import { CommandId, MessageId, ProjectId, ThreadId } from "@t3tools/contracts"; import { isMacPlatform } from "@t3tools/shared/keybindings"; import { type CxOptions, cx } from "class-variance-authority"; import * as Hex from "effect/encoding/Hex"; @@ -53,3 +53,5 @@ export const newThreadId = (): ThreadId => ThreadId.make(randomUUID()); export const newDraftId = (): DraftId => DraftId.make(randomUUID()); export const newMessageId = (): MessageId => MessageId.make(randomUUID()); + +export const newCommandId = (): CommandId => CommandId.make(randomUUID());