From b8da7459527c78da2865d6d7eb49928d395edd9a Mon Sep 17 00:00:00 2001 From: Kameron Smith <112618179+nullStack65@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:45:28 +0000 Subject: [PATCH 1/4] wip(placement): retry a new thread's uncertain launch as its original operation (held) PR70-R1-F2, HELD after two failed fixes; not for merge. The included regression "retries an unconfirmed launch as its original operation..." fails on purpose: when commitPendingLaunchPayload cannot commit, it leaves the attachment references in memory, and a later retry treats them as committed and launches with references never stored before the effect. What this carries: a new-thread draft launch records its command id, message id, request (text, attachment content identity by SHA-256 or upload id, model, modes, project, workspace) and the exact attachment references it sent, and commits them before launching. Any launch error keeps that operation (a typed error can follow an accepted launch); a retry resends exactly it, a changed request is refused while it is pending, and settlement drops only an unedited restored copy. A post-claim launch failure seam proves the same command recovers the accepted launch. Model: claude-opus-5-5 Task: CLO-866 universal native thread placement, PR70-R1-F2 original operation identity for web/desktop composer retries Agent: Claude Code in T3 Code, existing CLO-866 source owner thread (Opus 5.5) Co-Authored-By: Claude Opus 5.5 --- .../ThreadLaunchService.test.ts | 57 +++- .../chat/composerSend.logic.test.ts | 65 ++++- .../src/components/chat/composerSend.logic.ts | 106 ++++++- .../src/components/chat/useComposerSend.ts | 141 ++++++++- apps/web/src/composerDraftStore.test.ts | 235 +++++++++++++++ apps/web/src/composerDraftStore.ts | 270 ++++++++++++++++-- apps/web/src/lib/utils.ts | 4 +- 7 files changed, 847 insertions(+), 31 deletions(-) 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/composerSend.logic.test.ts b/apps/web/src/components/chat/composerSend.logic.test.ts index dea00844d6a5..4fb8852dc651 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 { ChatAttachmentId, EnvironmentId, 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,11 @@ import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; import { approvalRedirectNotice, composerDraftContentChanged, + attachmentContentIdentity, + draftLaunchRequest, + replayLaunchAttachments, + resolveDraftLaunch, + sentLaunchAttachments, loadBalancingSendWarning, multipleModelSendBlock, referencedThreadContexts, @@ -166,3 +171,61 @@ describe("approvalRedirectNotice", () => { expect(approvalRedirectNotice(settled)).toBeNull(); }); }); + +describe("draft launch identity", () => { + const request = async (file: File) => + draftLaunchRequest({ + text: "Review this screenshot", + attachments: [ + { + name: file.name, + mimeType: file.type, + sizeBytes: file.size, + content: await attachmentContentIdentity({ file }), + }, + ], + modelSelection: { instanceId: "claudeAgent", model: "claude-sonnet-4-6" }, + runtimeMode: "full-access", + interactionMode: "default", + projectId: "project-1", + branch: null, + worktreePath: null, + baseBranch: null, + startFromOrigin: false, + }); + + it("treats a same-named, same-sized attachment with other bytes as a different request", async () => { + const sent = new File([new Uint8Array([1, 2, 3, 4])], "shot.png", { type: "image/png" }); + const swapped = new File([new Uint8Array([9, 9, 9, 9])], "shot.png", { type: "image/png" }); + const pending = { + commandId: "command-1", + messageId: "message-1", + createdAt: "2026-11-18T00:00:00.000Z", + request: await request(sent), + }; + expect(resolveDraftLaunch(pending, await request(swapped))).toEqual({ type: "changed" }); + // The same bytes restored under a new attachment id are the same request. + const restored = new File([new Uint8Array([1, 2, 3, 4])], "shot.png", { type: "image/png" }); + expect(resolveDraftLaunch(pending, await request(restored))).toEqual({ + type: "retry", + launch: pending, + }); + }); + + it("replays exactly the references and ids a launch sent", async () => { + const shot = { type: "image" as const, name: "shot.png", mimeType: "image/png", sizeBytes: 4 }; + const upload = { ...shot, id: ChatAttachmentId.make("pending-upload-1") }; + const inline = { ...shot, id: ChatAttachmentId.make("inline-original") }; + const bytes = "data:image/png;base64,AQIDBA=="; + const sent = sentLaunchAttachments([upload, { ...inline, dataUrl: bytes }]); + // What is kept carries no image bytes. + expect(sent).toEqual([ + { attachment: upload, inline: false }, + { attachment: inline, inline: true }, + ]); + // The restored composer holds copies under new ids; the replay keeps the sent ones. + const file = new File([new Uint8Array([1, 2, 3, 4])], "shot.png", { type: "image/png" }); + const replayed = await replayLaunchAttachments(sent, [{ file }, { file }], async () => bytes); + expect(replayed).toEqual([upload, { ...inline, dataUrl: bytes }]); + }); +}); diff --git a/apps/web/src/components/chat/composerSend.logic.ts b/apps/web/src/components/chat/composerSend.logic.ts index 5b7a5ac3a09c..2fd4ab8aa2ee 100644 --- a/apps/web/src/components/chat/composerSend.logic.ts +++ b/apps/web/src/components/chat/composerSend.logic.ts @@ -1,4 +1,10 @@ -import type { EnvironmentId, ThreadContextRecord } from "@t3tools/contracts"; +import type { + ChatAttachment, + EnvironmentId, + ThreadContextRecord, + UploadChatAttachment, +} from "@t3tools/contracts"; +import type { PendingDraftLaunch, SentLaunchAttachment } from "../../composerDraftStore"; import { collectInlineContextIds } from "../../lib/composerContextReferences"; import type { ComposerThreadDraftState } from "../../composerDraftStore"; @@ -102,3 +108,101 @@ export function approvalRedirectNotice(input: { } return null; } + +/** + * What identifies an attachment's content: the SHA-256 of its bytes, or the upload that holds + * them when the composer kept only that. Name, type and size do not: two files can share them. + */ +export async function attachmentContentIdentity(attachment: { + readonly file: File | null; + readonly uploadedAttachmentId?: string; +}): Promise { + if (attachment.file !== null) { + const digest = await crypto.subtle.digest("SHA-256", await attachment.file.arrayBuffer()); + return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`; + } + // Neither bytes nor an upload: nothing can show a retry carries the same content. + if (attachment.uploadedAttachmentId === undefined) + throw new Error("An attachment needs to be attached again before sending."); + return `upload:${attachment.uploadedAttachmentId}`; +} + +/** The attachments as the launch sends them, without an inline image's bytes. */ +export function sentLaunchAttachments( + sent: ReadonlyArray, +): SentLaunchAttachment[] { + return sent.map((attachment) => { + if (!("dataUrl" in attachment)) return { attachment, inline: false }; + const { dataUrl: _bytes, ...reference } = attachment; + return { attachment: reference as ChatAttachment, inline: true }; + }); +} + +/** + * Exactly what a launch sent, again: the same references and ids. An inline image's bytes come + * from the restored file, which the request's content identity already proved unchanged. + */ +export function replayLaunchAttachments( + sent: ReadonlyArray, + current: ReadonlyArray<{ readonly file: File | null }>, + readDataUrl: (file: File) => Promise, +): Promise> { + return Promise.all( + sent.map(async ({ attachment, inline }, index) => { + if (!inline) return attachment; + const file = current[index]?.file; + if (!file) throw new Error(`Attachment '${attachment.name}' is no longer here to resend.`); + return { ...attachment, dataUrl: await readDataUrl(file) } as UploadChatAttachment; + }), + ); +} + +/** + * What a new thread's launch asks for. Attachments compare by content identity, not id: a + * restored draft clones them under new ids and is still the same request. + */ +export function draftLaunchRequest(input: { + readonly text: string; + readonly attachments: ReadonlyArray<{ + readonly name: string; + readonly mimeType: string; + readonly sizeBytes: number; + /** From `attachmentContentIdentity`. */ + readonly content: string; + }>; + 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, + attachments: input.attachments.map(({ name, mimeType, sizeBytes, content }) => ({ + name, + mimeType, + sizeBytes, + content, + })), + }); +} + +/** + * A launch whose outcome is unknown is resent as itself; a different request waits until it + * settles, since the host may already be running the first one. + */ +export function resolveDraftLaunch( + pending: PendingDraftLaunch | null | undefined, + request: string, +): + | { readonly type: "new" } + | { readonly type: "retry"; readonly launch: PendingDraftLaunch } + | { + readonly type: "changed"; + } { + if (!pending) return { type: "new" }; + return pending.request === request ? { type: "retry", launch: pending } : { type: "changed" }; +} diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 83503fc461f3..f511f4fdd0e6 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,9 @@ import { finalizePromotedDraftThreadByRef, markPromotedDraftThreadByRef, restoreFailedDraftThread, + commitPendingLaunchPayload, + markRestoredLaunchCopy, + type PendingDraftLaunch, checkoutPullRequestUrlToLink, composerDraftHasUserContent, type ComposerFileAttachment, @@ -99,11 +104,17 @@ import { useStableCallback } from "../../hooks/useStableCallback"; import { environmentPresentations } from "../../state/presentation"; import { approvalRedirectNotice, + attachmentContentIdentity, composerDraftContentChanged, + draftLaunchRequest, loadBalancingSendWarning, multipleModelSendBlock, referencedThreadContexts, + replayLaunchAttachments, + resolveDraftLaunch, + sentLaunchAttachments, } from "./composerSend.logic"; +import { readFileAsDataUrl } from "../../lib/imageCompression"; import { useMultipleModelSend } from "./useMultipleModelSend"; import { type ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch"; import { @@ -847,8 +858,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 +868,79 @@ 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; + // A retry must carry the same content, which only the attachments' bytes identify. + let attachmentContents: ReadonlyArray = []; + if (draftSessionForSend && composerAttachmentsSnapshot.length > 0) { + sendInFlightRef.current = true; + try { + attachmentContents = await Promise.all( + composerAttachmentsSnapshot.map(attachmentContentIdentity), + ); + } catch (error) { + setThreadError( + threadIdForSend, + error instanceof Error ? error.message : "Could not read the attachments.", + ); + return; + } finally { + sendInFlightRef.current = false; + } + } + const launchRequest = draftSessionForSend + ? draftLaunchRequest({ + text: outgoingMessageText, + attachments: composerAttachmentsSnapshot.map((attachment, index) => ({ + name: attachment.name, + mimeType: attachment.mimeType, + sizeBytes: attachment.sizeBytes, + content: attachmentContents[index] ?? "", + })), + 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); + 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, + // Nothing to prepare, so nothing to commit again before it goes out. + ...(composerAttachmentsSnapshot.length === 0 ? { attachments: [] } : {}), + }); const readLiveAttachmentCapabilities = () => { const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null; @@ -1150,12 +1232,21 @@ export function useComposerSend(input: ComposerSendInput) { ); } - const turnAttachmentsPromise = prepareTurnAttachments({ - environmentId, - attachments: composerAttachmentsSnapshot, - usesAttachmentUploads: turnUsesAttachmentUploads, - draftTarget: composerDraftTarget, - }); + // A retry sends the references its launch committed, not a new upload under the same command. + const turnAttachmentsPromise = + retriedLaunch?.attachments !== undefined + ? // The same wire shapes as freshly prepared ones. + (replayLaunchAttachments( + retriedLaunch.attachments, + composerAttachmentsSnapshot, + readFileAsDataUrl, + ) as ReturnType) + : prepareTurnAttachments({ + environmentId, + attachments: composerAttachmentsSnapshot, + usesAttachmentUploads: turnUsesAttachmentUploads, + draftTarget: composerDraftTarget, + }); if (multipleModelSelections !== null) { await sendToMultipleModels({ threadId: threadIdForSend, @@ -1224,7 +1315,11 @@ export function useComposerSend(input: ComposerSendInput) { : 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; + const sendBound = sentDraftThreadRef + ? markPromotedDraftThreadByRef(sentDraftThreadRef, launchOperation) + : true; + // Set once the launch itself goes out; failures before it sent nothing. + let launchAttempted = false; clearComposerDraftContent(composerDraftTarget); // The prompt ref and cursor belong to the thread on screen, which may no longer be this one. if (currentRouteThreadKeyRef.current === routeThreadKey) { @@ -1302,6 +1397,27 @@ export function useComposerSend(input: ComposerSendInput) { } } + // The references this launch sends are committed before it goes out, or it does not go out. + if ( + failure === null && + turnAttachmentsResult._tag === "Success" && + sentDraftThreadRef && + launchOperation && + launchOperation.attachments === undefined && + !commitPendingLaunchPayload( + sentDraftThreadRef, + launchOperation.commandId, + sentLaunchAttachments(turnAttachmentsResult.value), + ) + ) { + 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; + } + let backgroundDraftOpened = false; let turnStartSucceeded = false; if (failure === null && turnAttachmentsResult._tag === "Success") { @@ -1346,9 +1462,11 @@ export function useComposerSend(input: ComposerSendInput) { ) : null; if (backgroundThreadRef) beginBackgroundDraftSubmissionByRef(backgroundThreadRef); + launchAttempted = true; const startPromise = startThreadTurn({ environmentId, input: { + ...(launchOperation ? { commandId: CommandId.make(launchOperation.commandId) } : {}), threadId: threadIdForSend, message: { messageId: messageIdForSend, @@ -1455,6 +1573,8 @@ export function useComposerSend(input: ComposerSendInput) { wasBootstrapThreadDeleted(squashAtomCommandFailure(failure)) ? newThreadId() : threadIdForSend, + // No launch answer proves the host did not accept it, so a sent launch stays pending. + launchAttempted ? (launchOperation ?? null) : priorLaunch, ); clearBackgroundDraftSubmissionByRef(scopeThreadRef(environmentId, threadIdForSend)); } @@ -1502,6 +1622,7 @@ export function useComposerSend(input: ComposerSendInput) { ); } else { const retryComposerImages = restoreComposerDraft(composerDraftTarget, sendSnapshot); + if (isLocalDraftThread && draftId) markRestoredLaunchCopy(draftId); if (currentRouteThreadKeyRef.current === routeThreadKey) { promptRef.current = sendSnapshot.draftText; composerImagesRef.current = retryComposerImages; diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index 69e0c5d53da3..17d70e5f7660 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -21,6 +21,7 @@ import { defaultInstanceIdForDriver, DEFAULT_MODEL, DEFAULT_MODEL_BY_PROVIDER, + ChatAttachmentId, EnvironmentId, ProjectId, ProviderDriverKind, @@ -88,6 +89,7 @@ import { markPromotedDraftThreadByRef, resolveDraftPromotionNavigationTarget, restoreFailedDraftThread, + markRestoredLaunchCopy, subscribeDraftThreadPromotion, type ComposerFileAttachment, type ComposerImageAttachment, @@ -1318,6 +1320,239 @@ 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. + const sends: Array<{ commandId: string; attachmentIds: ReadonlyArray }> = []; + const launchThere = ( + operation: { commandId: string; messageId: string }, + sent: ThreadId, + attachments: ReadonlyArray<{ id: string }>, + ) => { + sends.push({ + commandId: operation.commandId, + attachmentIds: attachments.map((attachment) => attachment.id), + }); + 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: the draft's own pending operation, or new ids; committed, then launched. + const send = ( + tab: typeof import("./composerDraftStore"), + draftKey: DraftId, + text: string, + ) => { + const store = tab.useComposerDraftStore.getState(); + const draft = store.getDraftSession(draftKey)!; + const request = JSON.stringify({ + text, + model: "claude-sonnet-4-6", + runtimeMode: "full-access", + }); + const pending = draft.pendingLaunch; + if (pending && pending.request !== request) return { changed: true } as const; + allocated += 1; + const operation = pending ?? { + commandId: `command-${allocated}`, + messageId: `message-${allocated}`, + createdAt: "2026-11-18T00:00:00.000Z", + request, + }; + const sentRef = scopeThreadRef(draft.environmentId, draft.threadId); + if (tab.markPromotedDraftThreadByRef(sentRef, operation) === false) + return { unbound: true } as const; + // A retry sends the references its launch committed; a first send commits them first. + const attachments = operation.attachments?.map(({ attachment }) => attachment) ?? prepare(); + if (storageFailsBeforePayload) storageFails = true; + if (storageDropsBeforePayload) storageDrops = true; + if ( + operation.attachments === undefined && + !tab.commitPendingLaunchPayload( + sentRef, + operation.commandId, + attachments.map((attachment) => ({ attachment, inline: false })), + ) + ) + return { unbound: true } as const; + store.clearComposerContent(draftKey); + const answer = launchThere(operation, draft.threadId, attachments); + if ("runId" in answer) { + tab.finalizePromotedDraftThreadByRef(sentRef); + return { launched: answer, operation } as const; + } + tab.restoreFailedDraftThread(draftKey, draft, draft.threadId, operation); + tab.useComposerDraftStore.getState().setPrompt(draftKey, text); + tab.markRestoredLaunchCopy(draftKey); + 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"] }, + { commandId: "command-1", attachmentIds: ["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); + } 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..124ab6ff91e5 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -5,6 +5,7 @@ import { } from "./components/chat/composerAttachmentFiles"; import { elementContextToPreviewAnnotation } from "./lib/elementContext"; import { + ChatAttachment, ResponseContextRecord, ElementContextDetails, DEFAULT_MODEL, @@ -403,6 +404,12 @@ type LegacyPersistedComposerDraftStoreState = PersistedComposerDraftStoreState & LegacyStickyModelFields & LegacyV2StoreFields; +const SentLaunchAttachmentSchema = Schema.Struct({ + attachment: ChatAttachment, + inline: Schema.Boolean, +}); +const isSentLaunchAttachments = Schema.is(Schema.Array(SentLaunchAttachmentSchema)); + const PersistedDraftThreadState = Schema.Struct({ threadId: ThreadId, environmentId: Schema.String, @@ -436,6 +443,18 @@ const PersistedDraftThreadState = Schema.Struct({ }), ), ), + pendingLaunch: Schema.optionalKey( + Schema.NullOr( + Schema.Struct({ + commandId: Schema.String, + messageId: Schema.String, + createdAt: Schema.String, + request: Schema.String, + attachments: Schema.optionalKey(Schema.Array(SentLaunchAttachmentSchema)), + restoredCopy: Schema.optionalKey(Schema.String), + }), + ), + ), }); type PersistedDraftThreadState = typeof PersistedDraftThreadState.Type; @@ -529,6 +548,31 @@ 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 attachment references the launch sent, committed before it went out, so a retry sends + * exactly them. Absent until the launch's attachments are prepared; nothing was sent before. + */ + readonly attachments?: SentLaunchAttachment[]; + /** The composer content put back for a retry, which a settled launch must not leave behind. */ + readonly restoredCopy?: string; +} + +/** An attachment as a launch sent it; an inline image's bytes are re-read, never stored. */ +export interface SentLaunchAttachment { + readonly attachment: ChatAttachment; + /** Sent as a data URL with this id; the restored file supplies the same bytes again. */ + readonly inline: boolean; } export type DraftThreadState = DraftSessionState; @@ -1765,6 +1809,9 @@ function createDraftThreadState( ...(existingThread?.sentTo && existingThread.threadId === threadId ? { sentTo: existingThread.sentTo } : {}), + ...(existingThread?.pendingLaunch && existingThread.threadId === threadId + ? { pendingLaunch: existingThread.pendingLaunch } + : {}), }; } @@ -1785,6 +1832,52 @@ function checkoutPullRequestsEqual( return left === right || (left?.url === right?.url && left?.branch === right?.branch); } +function hydratedPendingLaunch( + stored: NonNullable, +): PendingDraftLaunch { + const { attachments, ...launch } = stored; + return { ...launch, ...(attachments === undefined ? {} : { attachments: [...attachments] }) }; +} + +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, attachments, restoredCopy } = record; + return typeof commandId === "string" && + commandId.length > 0 && + typeof messageId === "string" && + messageId.length > 0 && + typeof createdAt === "string" && + typeof request === "string" && + (attachments === undefined || isSentLaunchAttachments(attachments)) && + (restoredCopy === undefined || typeof restoredCopy === "string") + ? { + commandId, + messageId, + createdAt, + request, + ...(attachments === undefined ? {} : { attachments: [...attachments] }), + ...(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.attachments) === JSON.stringify(right.attachments) && + left.restoredCopy === right.restoredCopy + ); +} + function storedThreadRef(candidate: unknown): ScopedThreadRef | null { const record = candidate && typeof candidate === "object" ? (candidate as Record) : null; @@ -1844,7 +1937,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 +2055,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 +2100,7 @@ function normalizePersistedDraftThreads( ...(checkoutPullRequest ? { checkoutPullRequest } : {}), promotedTo, ...(sentTo ? { sentTo } : {}), + ...(pendingLaunch ? { pendingLaunch } : {}), }; } } @@ -2798,6 +2894,9 @@ function toHydratedDraftThreadState( ), } : {}), + ...(persistedDraftThread.pendingLaunch + ? { pendingLaunch: hydratedPendingLaunch(persistedDraftThread.pendingLaunch) } + : {}), }; } @@ -3087,6 +3186,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 && @@ -4734,36 +4834,62 @@ 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 })); + 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, launch))) ) 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; } +/** The stored bytes hold `launch` for each draft; read after the flush that committed it. */ +function commitsPendingLaunch(draftIds: ReadonlyArray, launch: PendingDraftLaunch) { + try { + const stored = readStoredComposerDraftState(); + return draftIds.every( + (draftId) => + stored?.draftThreadsByThreadKey[draftId]?.pendingLaunch?.commandId === launch.commandId, + ); + } catch { + return false; + } +} + /** Writes pending draft state now and checks the stored bytes hold `field` for each draft. */ function commitsDraftThreadBinding( draftIds: ReadonlyArray, @@ -4788,6 +4914,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 +4935,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 +4951,105 @@ 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. */ +export function composerDraftCopySignature(draft: ComposerThreadDraftState | undefined): string { + return JSON.stringify( + draft === undefined + ? null + : { + prompt: draft.prompt, + 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 { + 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]), + }, + }, + }, + }; + }); +} + +/** + * Records the attachment references a launch is about to send and commits them to storage, so a + * retry resends exactly them. False when storage did not take them: the launch must not go out. + */ +export function commitPendingLaunchPayload( + threadRef: ScopedThreadRef, + commandId: string, + attachments: ReadonlyArray, +): boolean { + const draftIds = Object.entries(useComposerDraftStore.getState().draftThreadsByThreadKey) + .filter( + ([, draftThread]) => + draftThread.environmentId === threadRef.environmentId && + draftThread.threadId === threadRef.threadId && + draftThread.pendingLaunch?.commandId === commandId, + ) + .map(([draftId]) => draftId); + if (draftIds.length === 0) return false; + useComposerDraftStore.setState((state) => ({ + draftThreadsByThreadKey: Object.fromEntries( + Object.entries(state.draftThreadsByThreadKey).map(([draftId, draftThread]) => [ + draftId, + draftIds.includes(draftId) && draftThread.pendingLaunch + ? { + ...draftThread, + pendingLaunch: { ...draftThread.pendingLaunch, attachments: [...attachments] }, + } + : draftThread, + ]), + ), + })); + try { + composerDebouncedStorage.flush(); + const stored = readStoredComposerDraftState(); + const expected = JSON.stringify(attachments); + return draftIds.every( + (draftId) => + JSON.stringify(stored?.draftThreadsByThreadKey[draftId]?.pendingLaunch?.attachments) === + expected, + ); + } catch { + return false; + } +} + 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()); From ed9075cc3dd15a62306730187a4eff33497f4c1b Mon Sep 17 00:00:00 2001 From: Kameron Smith <112618179+nullStack65@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:06:28 +0000 Subject: [PATCH 2/4] fix(placement): launch only an operation storage holds in full PR70-R1-F2, caller-authorized continuation C1 (global attempt 3) on the held b8da7459. A renderer that died after binding a launch, before preparing its attachments, left the operation stored without references. A retry whose reference commit failed then kept those unsaved references in memory, and a later retry whose binding write storage dropped silently still passed the check, which compared only the bound thread and command id. It skipped the reference commit and launched with references storage never held. The binding check now compares the whole stored operation, references included, and a failed reference commit puts back what each draft had. The regression follows the composer's actual order and failure restore, and checks at every launch that storage already held the references sent. The held commit's last silent-drop assertion was not evidence of an unsafe launch: its binding write was healthy and had already stored those references, and its helper skipped the composer's failure restore. The helper now follows the composer, and that case remains as a check of a dropped reference write. ARC also runs the composer send logic tests. Model: claude-opus-5-5 Task: CLO-866 universal native thread placement, PR70-R1-F2 original operation identity for web/desktop composer retries Agent: Claude Code in T3 Code, existing CLO-866 source owner thread (Opus 5.5) Co-Authored-By: Claude Opus 5.5 --- .github/workflows/closura-arc-ci.yml | 3 +- apps/web/src/composerDraftStore.test.ts | 110 ++++++++++++++++++++---- apps/web/src/composerDraftStore.ts | 59 +++++++++---- 3 files changed, 140 insertions(+), 32 deletions(-) diff --git a/.github/workflows/closura-arc-ci.yml b/.github/workflows/closura-arc-ci.yml index dcabe3208295..2993a8c21c14 100644 --- a/.github/workflows/closura-arc-ci.yml +++ b/.github/workflows/closura-arc-ci.yml @@ -152,7 +152,8 @@ 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 - name: Build native T3 server shell: bash diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index 17d70e5f7660..96f66bb80923 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -1344,9 +1344,25 @@ describe("composerDraftStore project draft thread mapping", () => { // 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. - const sends: Array<{ commandId: string; attachmentIds: ReadonlyArray }> = []; + // 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; + return launch?.attachments === undefined + ? null + : (launch.attachments as Array<{ attachment: { id: string } }>).map( + ({ attachment }) => attachment.id, + ); + }; const launchThere = ( + draftKey: DraftId, operation: { commandId: string; messageId: string }, sent: ThreadId, attachments: ReadonlyArray<{ id: string }>, @@ -1354,6 +1370,7 @@ describe("composerDraftStore project draft thread mapping", () => { sends.push({ commandId: operation.commandId, attachmentIds: attachments.map((attachment) => attachment.id), + persistedIds: persistedAttachmentIds(draftKey), }); const replayed = accepted.get(operation.commandId); if (replayed) return replayed; @@ -1381,11 +1398,14 @@ describe("composerDraftStore project draft thread mapping", () => { sizeBytes: 4, }, ]; - // The composer's send: the draft's own pending operation, or new ids; committed, then launched. + // The composer's send, in its order: bind the operation, clear the composer, prepare the + // attachments, commit their references, launch; any failure restores the draft with the + // launch still unknown (the one sent, or before sending, the one pending before). const send = ( tab: typeof import("./composerDraftStore"), draftKey: DraftId, text: string, + crashBeforePayload = false, ) => { const store = tab.useComposerDraftStore.getState(); const draft = store.getDraftSession(draftKey)!; @@ -1394,18 +1414,33 @@ describe("composerDraftStore project draft thread mapping", () => { model: "claude-sonnet-4-6", runtimeMode: "full-access", }); - const pending = draft.pendingLaunch; - if (pending && pending.request !== request) return { changed: true } as const; + const priorLaunch = draft.pendingLaunch ?? null; + if (priorLaunch && priorLaunch.request !== request) return { changed: true } as const; allocated += 1; - const operation = pending ?? { + const operation = priorLaunch ?? { commandId: `command-${allocated}`, messageId: `message-${allocated}`, createdAt: "2026-11-18T00:00:00.000Z", request, }; const sentRef = scopeThreadRef(draft.environmentId, draft.threadId); - if (tab.markPromotedDraftThreadByRef(sentRef, operation) === false) + 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); + store.clearComposerContent(draftKey); + if (!bound) { + fail(false); return { unbound: true } as const; + } + if (crashBeforePayload) return { crashed: true } as const; // A retry sends the references its launch committed; a first send commits them first. const attachments = operation.attachments?.map(({ attachment }) => attachment) ?? prepare(); if (storageFailsBeforePayload) storageFails = true; @@ -1417,17 +1452,16 @@ describe("composerDraftStore project draft thread mapping", () => { operation.commandId, attachments.map((attachment) => ({ attachment, inline: false })), ) - ) + ) { + fail(false); return { unbound: true } as const; - store.clearComposerContent(draftKey); - const answer = launchThere(operation, draft.threadId, attachments); + } + const answer = launchThere(draftKey, operation, draft.threadId, attachments); if ("runId" in answer) { tab.finalizePromotedDraftThreadByRef(sentRef); return { launched: answer, operation } as const; } - tab.restoreFailedDraftThread(draftKey, draft, draft.threadId, operation); - tab.useComposerDraftStore.getState().setPrompt(draftKey, text); - tab.markRestoredLaunchCopy(draftKey); + fail(true); return { failed: answer, operation } as const; }; @@ -1467,8 +1501,16 @@ describe("composerDraftStore project draft thread mapping", () => { 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"] }, - { commandId: "command-1", attachmentIds: ["pending-upload-1"] }, + { + 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(); @@ -1499,6 +1541,44 @@ describe("composerDraftStore project draft thread mapping", () => { 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"); + const unsent = crashed.useComposerDraftStore.getState().getDraftSession(crashDraftId)!; + crashed.restoreFailedDraftThread(crashDraftId, unsent, crashThreadId, unsent.pendingLaunch); + crashed.useComposerDraftStore.getState().setPrompt(crashDraftId, "Crash task"); + crashed.markRestoredLaunchCopy(crashDraftId); + // 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. + expect(send(crashed, crashDraftId, "Crash task")).toMatchObject({ launched: {} }); + for (const sent of sends) expect(sent.persistedIds).toEqual(sent.attachmentIds); + expect( + [...accepted.keys()].filter((commandId) => commandId === unsent.pendingLaunch?.commandId), + ).toHaveLength(1); } finally { vi.useRealTimers(); vi.unstubAllGlobals(); diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 124ab6ff91e5..2abc1b9ba68c 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -4877,13 +4877,18 @@ export function markPromotedDraftThreadByRef( return false; } -/** The stored bytes hold `launch` for each draft; read after the flush that committed it. */ +/** + * The stored bytes hold all of `launch` for each draft, references 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, launch: PendingDraftLaunch) { try { const stored = readStoredComposerDraftState(); - return draftIds.every( - (draftId) => - stored?.draftThreadsByThreadKey[draftId]?.pendingLaunch?.commandId === launch.commandId, + return draftIds.every((draftId) => + pendingLaunchesEqual( + storedPendingLaunch(stored?.draftThreadsByThreadKey[draftId]?.pendingLaunch), + launch, + ), ); } catch { return false; @@ -5008,19 +5013,41 @@ export function commitPendingLaunchPayload( ) .map(([draftId]) => draftId); if (draftIds.length === 0) return false; - useComposerDraftStore.setState((state) => ({ - draftThreadsByThreadKey: Object.fromEntries( - Object.entries(state.draftThreadsByThreadKey).map(([draftId, draftThread]) => [ - draftId, - draftIds.includes(draftId) && draftThread.pendingLaunch - ? { + const prior = new Map( + draftIds.map((draftId) => [ + draftId, + useComposerDraftStore.getState().draftThreadsByThreadKey[draftId]?.pendingLaunch?.attachments, + ]), + ); + const setAttachments = (pick: (draftId: string) => SentLaunchAttachment[] | undefined) => + useComposerDraftStore.setState((state) => ({ + draftThreadsByThreadKey: Object.fromEntries( + Object.entries(state.draftThreadsByThreadKey).map(([draftId, draftThread]) => { + if (!draftIds.includes(draftId) || !draftThread.pendingLaunch) + return [draftId, draftThread]; + const { attachments: _replaced, ...launch } = draftThread.pendingLaunch; + const next = pick(draftId); + return [ + draftId, + { ...draftThread, - pendingLaunch: { ...draftThread.pendingLaunch, attachments: [...attachments] }, - } - : draftThread, - ]), - ), - })); + pendingLaunch: next === undefined ? launch : { ...launch, attachments: next }, + }, + ]; + }), + ), + })); + setAttachments(() => [...attachments]); + // Uncommitted references never stay behind to pass as sent: each draft keeps what it had. + const committed = commitsLaunchAttachments(draftIds, attachments); + if (!committed) setAttachments((draftId) => prior.get(draftId)); + return committed; +} + +function commitsLaunchAttachments( + draftIds: ReadonlyArray, + attachments: ReadonlyArray, +): boolean { try { composerDebouncedStorage.flush(); const stored = readStoredComposerDraftState(); From 3958e32b414e3e68e278b306dbb51c0ba9b642d7 Mon Sep 17 00:00:00 2001 From: Kameron Smith <112618179+nullStack65@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:42:37 +0000 Subject: [PATCH 3/4] fix(placement): resend a draft's launch exactly as stored after a reload A draft's pending launch could not always be resent after a reload or an uncertain failure: the restored-copy signature drifted when hydration added inline file links, a just-attached image depended on background saving that may not have finished, a file whose first upload failed came back without the upload its send made (so Send stayed blocked on "attach again"), the composer was cleared before the turn was stored, and a launch bound but not yet sent lost its identity. The launch is now bound with the whole composer it was sent from, image bytes read at send time, and its turn is committed together with the uploads its files went out as (matched by attachment id, in preparation order), verified as one stored operation before the composer clears or the launch goes out; a failed or dropped write restores the prior operation. The signature reads the prompt as a reload shows it; recovery and a failure restore give the draft the sent attachments it lacks. An unchanged resend keeps the original operation, turn or not; a change waits while the launch may have gone out, and otherwise starts afresh on the same machine and thread. ARC CI now also runs chatViewSend and composerImagePersistence. Model: claude-opus-5-5 Task: CLO-866 universal native thread placement, PR70-R1-F2 / PR71-R1-F1..F3 original operation identity for web/desktop composer retries (caller disposition C4, global attempt 6) Agent: Claude Code in T3 Code, existing CLO-866 source owner thread (Opus 5.5) Co-Authored-By: Claude Opus 5.5 --- .github/workflows/closura-arc-ci.yml | 4 +- .../src/components/chat/chatViewSend.test.ts | 547 ++++++++++++++++++ apps/web/src/components/chat/chatViewSend.ts | 51 ++ .../chat/composerSend.logic.test.ts | 105 ++-- .../src/components/chat/composerSend.logic.ts | 97 +--- .../src/components/chat/useComposerSend.ts | 248 ++++---- apps/web/src/composerDraftStore.test.ts | 227 ++++++-- apps/web/src/composerDraftStore.ts | 462 ++++++++++----- 8 files changed, 1311 insertions(+), 430 deletions(-) create mode 100644 apps/web/src/components/chat/chatViewSend.test.ts diff --git a/.github/workflows/closura-arc-ci.yml b/.github/workflows/closura-arc-ci.yml index 2993a8c21c14..f5a9e0ce4161 100644 --- a/.github/workflows/closura-arc-ci.yml +++ b/.github/workflows/closura-arc-ci.yml @@ -153,7 +153,9 @@ jobs: apps/server/src/mcp/OrchestratorMcpService.test.ts \ apps/server/src/cli/thread.test.ts \ apps/web/src/composerDraftStore.test.ts \ - apps/web/src/components/chat/composerSend.logic.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/web/src/components/chat/chatViewSend.test.ts b/apps/web/src/components/chat/chatViewSend.test.ts new file mode 100644 index 000000000000..fd8c45929d0a --- /dev/null +++ b/apps/web/src/components/chat/chatViewSend.test.ts @@ -0,0 +1,547 @@ +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, or drop it without saying so. +const storageFaults = { throws: false, drops: false }; +function faultyStorage() { + const memory = createMemoryStorage(); + return { + getItem: (name: string) => 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); + }, + }; +} + +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; + storageFaults.throws = false; + storageFaults.drops = false; + 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 first 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 an uncertain launch error restore the draft. `edit` runs while + * reads are pending; `commitFault` makes storage refuse or drop the turn's commit. + */ +async function sendDraft( + tab: Tab, + draft: ReturnType, + options: { + uploads: boolean; + stopAfterBind?: boolean; + edit?: () => void; + launchFails?: boolean; + commitFault?: "throws" | "drops"; + }, +) { + 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}`, + messageId: `message-${draft.threadId}`, + 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; + expect(tab.store.markPromotedDraftThreadByRef(sentRef, { ...operation, composer })).toBe(true); + if (options.stopAfterBind) return null; + const attachments = await prepared; + 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, + ); + storageFaults.throws = false; + storageFaults.drops = false; + if (!committed) return { committed, boundLaunch, turn, cleared: false, before, operation }; + const cleared = tab.send.clearSentComposerContent(draft.draftId, before); + if (options.launchFails) { + // No launch answer proves the host did not take it: the hook's restore for an emptied draft. + tab.store.restoreFailedDraftThread(draft.draftId, draftThread, draft.threadId, operation); + tab.send.restoreComposerDraft(draft.draftId, snapshot); + tab.store.markRestoredLaunchCopy(draft.draftId); + } + return { committed, boundLaunch, turn, cleared, 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"] as const)( + "keeps the bound operation, its composer and the draft when storage %s the turn's commit", + 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); + const session = tab.store.useComposerDraftStore.getState().getDraftSession(draft.draftId)!; + // In memory and in storage: the operation as bound, no turn, no upload on its composer. + expect(session.pendingLaunch).toEqual(sent.boundLaunch); + expect(session.pendingLaunch?.turn).toBeUndefined(); + expect(session.pendingLaunch?.composer?.files?.[0]?.attachmentId).toBeUndefined(); + expect(session.promotedTo).toEqual(scopeThreadRef(environmentId, draft.threadId)); + expect( + tab.store.useComposerDraftStore.getState().getComposerDraft(draft.draftId)?.prompt, + ).toBe("Review the report"); + const reloaded = await reload(); + const stored = reloaded.store.useComposerDraftStore + .getState() + .getDraftSession(draft.draftId); + expect(stored?.pendingLaunch?.turn).toBeUndefined(); + expect(stored?.pendingLaunch?.commandId).toBe(sent.operation.commandId); + expect(stored?.sentTo).toEqual(scopeThreadRef(environmentId, draft.threadId)); + }); + }, + ); +}); diff --git a/apps/web/src/components/chat/chatViewSend.ts b/apps/web/src/components/chat/chatViewSend.ts index 079e6d18d5ee..ac99a513a08c 100644 --- a/apps/web/src/components/chat/chatViewSend.ts +++ b/apps/web/src/components/chat/chatViewSend.ts @@ -28,10 +28,15 @@ import { newThreadId } from "~/lib/utils"; import { type ComposerFileAttachment, type ComposerImageAttachment, + type ComposerThreadDraftState, type ComposerThreadTarget, + type PreparedFileUpload, + 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 +263,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 diff --git a/apps/web/src/components/chat/composerSend.logic.test.ts b/apps/web/src/components/chat/composerSend.logic.test.ts index 4fb8852dc651..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 { ChatAttachmentId, 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,11 +8,8 @@ import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; import { approvalRedirectNotice, composerDraftContentChanged, - attachmentContentIdentity, draftLaunchRequest, - replayLaunchAttachments, resolveDraftLaunch, - sentLaunchAttachments, loadBalancingSendWarning, multipleModelSendBlock, referencedThreadContexts, @@ -172,19 +169,10 @@ describe("approvalRedirectNotice", () => { }); }); -describe("draft launch identity", () => { - const request = async (file: File) => +describe("draft launch retry", () => { + const request = (model: string) => draftLaunchRequest({ - text: "Review this screenshot", - attachments: [ - { - name: file.name, - mimeType: file.type, - sizeBytes: file.size, - content: await attachmentContentIdentity({ file }), - }, - ], - modelSelection: { instanceId: "claudeAgent", model: "claude-sonnet-4-6" }, + modelSelection: { instanceId: "claudeAgent", model }, runtimeMode: "full-access", interactionMode: "default", projectId: "project-1", @@ -193,39 +181,66 @@ describe("draft launch identity", () => { 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("treats a same-named, same-sized attachment with other bytes as a different request", async () => { - const sent = new File([new Uint8Array([1, 2, 3, 4])], "shot.png", { type: "image/png" }); - const swapped = new File([new Uint8Array([9, 9, 9, 9])], "shot.png", { type: "image/png" }); - const pending = { - commandId: "command-1", - messageId: "message-1", - createdAt: "2026-11-18T00:00:00.000Z", - request: await request(sent), - }; - expect(resolveDraftLaunch(pending, await request(swapped))).toEqual({ type: "changed" }); - // The same bytes restored under a new attachment id are the same request. - const restored = new File([new Uint8Array([1, 2, 3, 4])], "shot.png", { type: "image/png" }); - expect(resolveDraftLaunch(pending, await request(restored))).toEqual({ + 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: pending, + 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("replays exactly the references and ids a launch sent", async () => { - const shot = { type: "image" as const, name: "shot.png", mimeType: "image/png", sizeBytes: 4 }; - const upload = { ...shot, id: ChatAttachmentId.make("pending-upload-1") }; - const inline = { ...shot, id: ChatAttachmentId.make("inline-original") }; - const bytes = "data:image/png;base64,AQIDBA=="; - const sent = sentLaunchAttachments([upload, { ...inline, dataUrl: bytes }]); - // What is kept carries no image bytes. - expect(sent).toEqual([ - { attachment: upload, inline: false }, - { attachment: inline, inline: true }, - ]); - // The restored composer holds copies under new ids; the replay keeps the sent ones. - const file = new File([new Uint8Array([1, 2, 3, 4])], "shot.png", { type: "image/png" }); - const replayed = await replayLaunchAttachments(sent, [{ file }, { file }], async () => bytes); - expect(replayed).toEqual([upload, { ...inline, dataUrl: bytes }]); + 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 2fd4ab8aa2ee..01bec046b45b 100644 --- a/apps/web/src/components/chat/composerSend.logic.ts +++ b/apps/web/src/components/chat/composerSend.logic.ts @@ -1,10 +1,5 @@ -import type { - ChatAttachment, - EnvironmentId, - ThreadContextRecord, - UploadChatAttachment, -} from "@t3tools/contracts"; -import type { PendingDraftLaunch, SentLaunchAttachment } from "../../composerDraftStore"; +import type { EnvironmentId, ThreadContextRecord } from "@t3tools/contracts"; +import type { PendingDraftLaunch } from "../../composerDraftStore"; import { collectInlineContextIds } from "../../lib/composerContextReferences"; import type { ComposerThreadDraftState } from "../../composerDraftStore"; @@ -110,66 +105,10 @@ export function approvalRedirectNotice(input: { } /** - * What identifies an attachment's content: the SHA-256 of its bytes, or the upload that holds - * them when the composer kept only that. Name, type and size do not: two files can share them. - */ -export async function attachmentContentIdentity(attachment: { - readonly file: File | null; - readonly uploadedAttachmentId?: string; -}): Promise { - if (attachment.file !== null) { - const digest = await crypto.subtle.digest("SHA-256", await attachment.file.arrayBuffer()); - return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`; - } - // Neither bytes nor an upload: nothing can show a retry carries the same content. - if (attachment.uploadedAttachmentId === undefined) - throw new Error("An attachment needs to be attached again before sending."); - return `upload:${attachment.uploadedAttachmentId}`; -} - -/** The attachments as the launch sends them, without an inline image's bytes. */ -export function sentLaunchAttachments( - sent: ReadonlyArray, -): SentLaunchAttachment[] { - return sent.map((attachment) => { - if (!("dataUrl" in attachment)) return { attachment, inline: false }; - const { dataUrl: _bytes, ...reference } = attachment; - return { attachment: reference as ChatAttachment, inline: true }; - }); -} - -/** - * Exactly what a launch sent, again: the same references and ids. An inline image's bytes come - * from the restored file, which the request's content identity already proved unchanged. - */ -export function replayLaunchAttachments( - sent: ReadonlyArray, - current: ReadonlyArray<{ readonly file: File | null }>, - readDataUrl: (file: File) => Promise, -): Promise> { - return Promise.all( - sent.map(async ({ attachment, inline }, index) => { - if (!inline) return attachment; - const file = current[index]?.file; - if (!file) throw new Error(`Attachment '${attachment.name}' is no longer here to resend.`); - return { ...attachment, dataUrl: await readDataUrl(file) } as UploadChatAttachment; - }), - ); -} - -/** - * What a new thread's launch asks for. Attachments compare by content identity, not id: a - * restored draft clones them under new ids and is still the same request. + * 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 text: string; - readonly attachments: ReadonlyArray<{ - readonly name: string; - readonly mimeType: string; - readonly sizeBytes: number; - /** From `attachmentContentIdentity`. */ - readonly content: string; - }>; readonly modelSelection: unknown; readonly runtimeMode: string; readonly interactionMode: string; @@ -179,30 +118,28 @@ export function draftLaunchRequest(input: { readonly baseBranch: string | null; readonly startFromOrigin: boolean; }): string { - return JSON.stringify({ - ...input, - attachments: input.attachments.map(({ name, mimeType, sizeBytes, content }) => ({ - name, - mimeType, - sizeBytes, - content, - })), - }); + return JSON.stringify(input); } /** - * A launch whose outcome is unknown is resent as itself; a different request waits until it - * settles, since the host may already be running the first one. + * 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"; - } { + | { readonly type: "changed" } { if (!pending) return { type: "new" }; - return pending.request === request ? { type: "retry", launch: pending } : { type: "changed" }; + 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 f511f4fdd0e6..41dd3ab5cf74 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -72,6 +72,8 @@ import { markPromotedDraftThreadByRef, restoreFailedDraftThread, commitPendingLaunchPayload, + composerDraftCopySignature, + type PendingLaunchTurn, markRestoredLaunchCopy, type PendingDraftLaunch, checkoutPullRequestUrlToLink, @@ -104,17 +106,13 @@ import { useStableCallback } from "../../hooks/useStableCallback"; import { environmentPresentations } from "../../state/presentation"; import { approvalRedirectNotice, - attachmentContentIdentity, composerDraftContentChanged, draftLaunchRequest, loadBalancingSendWarning, multipleModelSendBlock, referencedThreadContexts, - replayLaunchAttachments, resolveDraftLaunch, - sentLaunchAttachments, } from "./composerSend.logic"; -import { readFileAsDataUrl } from "../../lib/imageCompression"; import { useMultipleModelSend } from "./useMultipleModelSend"; import { type ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch"; import { @@ -139,6 +137,9 @@ import { type MultipleModelTarget, resolveMultipleModelTargets, prepareTurnAttachments, + clearSentComposerContent, + preparedFileUploads, + readSentComposer, restoreComposerDraft, } from "./chatViewSend"; import type { @@ -814,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, @@ -874,33 +878,8 @@ export function useComposerSend(input: ComposerSendInput) { isLocalDraftThread && draftId ? useComposerDraftStore.getState().getDraftSession(draftId) : null; - // A retry must carry the same content, which only the attachments' bytes identify. - let attachmentContents: ReadonlyArray = []; - if (draftSessionForSend && composerAttachmentsSnapshot.length > 0) { - sendInFlightRef.current = true; - try { - attachmentContents = await Promise.all( - composerAttachmentsSnapshot.map(attachmentContentIdentity), - ); - } catch (error) { - setThreadError( - threadIdForSend, - error instanceof Error ? error.message : "Could not read the attachments.", - ); - return; - } finally { - sendInFlightRef.current = false; - } - } const launchRequest = draftSessionForSend ? draftLaunchRequest({ - text: outgoingMessageText, - attachments: composerAttachmentsSnapshot.map((attachment, index) => ({ - name: attachment.name, - mimeType: attachment.mimeType, - sizeBytes: attachment.sizeBytes, - content: attachmentContents[index] ?? "", - })), modelSelection: ctxSelectedModelSelection, runtimeMode, interactionMode: DEFAULT_INTERACTION_MODE, @@ -913,7 +892,13 @@ export function useComposerSend(input: ComposerSendInput) { : null; const priorLaunch = draftSessionForSend?.pendingLaunch ?? null; const launchPlan = - launchRequest === null ? null : resolveDraftLaunch(priorLaunch, launchRequest); + launchRequest === null + ? null + : resolveDraftLaunch( + priorLaunch, + launchRequest, + composerDraftCopySignature(draftBeforeSend ?? undefined), + ); if (launchPlan?.type === "changed") { toastManager.add( stackedThreadToast({ @@ -938,8 +923,6 @@ export function useComposerSend(input: ComposerSendInput) { messageId: messageIdForSend, createdAt: messageCreatedAt, request: launchRequest, - // Nothing to prepare, so nothing to commit again before it goes out. - ...(composerAttachmentsSnapshot.length === 0 ? { attachments: [] } : {}), }); const readLiveAttachmentCapabilities = () => { @@ -971,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); @@ -1232,15 +1213,10 @@ export function useComposerSend(input: ComposerSendInput) { ); } - // A retry sends the references its launch committed, not a new upload under the same command. - const turnAttachmentsPromise = - retriedLaunch?.attachments !== undefined - ? // The same wire shapes as freshly prepared ones. - (replayLaunchAttachments( - retriedLaunch.attachments, - composerAttachmentsSnapshot, - readFileAsDataUrl, - ) as ReturnType) + // 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, @@ -1313,19 +1289,35 @@ 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, launchOperation) - : true; + const sendBound = + !sentDraftThreadRef || + (sentComposer?._tag !== "Failure" && + markPromotedDraftThreadByRef( + sentDraftThreadRef, + launchOperation && sentComposer?._tag === "Success" + ? { ...launchOperation, composer: sentComposer.value } + : launchOperation, + )); // Set once the launch itself goes out; failures before it sent nothing. let launchAttempted = false; - 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(); - } + // 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, @@ -1338,8 +1330,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.", @@ -1397,17 +1390,85 @@ export function useComposerSend(input: ComposerSendInput) { } } - // The references this launch sends are committed before it goes out, or it does not go out. + 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 && - turnAttachmentsResult._tag === "Success" && + turnForLaunch && sentDraftThreadRef && launchOperation && - launchOperation.attachments === undefined && + launchOperation.turn === undefined && !commitPendingLaunchPayload( sentDraftThreadRef, launchOperation.commandId, - sentLaunchAttachments(turnAttachmentsResult.value), + turnForLaunch, + turnAttachmentsResult._tag === "Success" + ? preparedFileUploads({ + environmentId, + attachments: composerAttachmentsSnapshot, + prepared: turnAttachmentsResult.value, + usesAttachmentUploads: turnUsesAttachmentUploads, + }) + : [], ) ) { const unbound = await settlePromise(async () => { @@ -1417,39 +1478,11 @@ export function useComposerSend(input: ComposerSendInput) { }); 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) @@ -1463,32 +1496,7 @@ export function useComposerSend(input: ComposerSendInput) { : null; if (backgroundThreadRef) beginBackgroundDraftSubmissionByRef(backgroundThreadRef); launchAttempted = true; - const startPromise = startThreadTurn({ - 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, - }, - }); + const startPromise = startThreadTurn(turnForLaunch); if (backgroundThreadRef) { try { backgroundDraftOpened = Boolean( @@ -1585,11 +1593,11 @@ 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 composerAfterFailure = + useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) ?? null; + if (!composerCleared && !composerDraftContentChanged(draftBeforeSend, composerAfterFailure)) { + // Never cleared, the composer still holds the message to send again. + } else if (composerDraftHasUserContent(composerAfterFailure)) { // A draft typed meanwhile keeps the composer, so the failed text stays reachable here. const failedText = sendSnapshot.draftText; const hasText = failedText.trim().length > 0; diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index 96f66bb80923..56ce823ffa62 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -22,7 +22,9 @@ import { DEFAULT_MODEL, DEFAULT_MODEL_BY_PROVIDER, ChatAttachmentId, + CommandId, EnvironmentId, + MessageId, ProjectId, ProviderDriverKind, ProviderInstanceId, @@ -76,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, @@ -90,6 +97,7 @@ import { resolveDraftPromotionNavigationTarget, restoreFailedDraftThread, markRestoredLaunchCopy, + type PendingLaunchTurn, subscribeDraftThreadPromotion, type ComposerFileAttachment, type ComposerImageAttachment, @@ -1355,21 +1363,20 @@ describe("composerDraftStore project draft thread mapping", () => { const launch = raw ? JSON.parse(raw).state.draftThreadsByThreadKey[draftKey]?.pendingLaunch : undefined; - return launch?.attachments === undefined + const stored = launch?.turn?.input?.message?.attachments; + return stored === undefined ? null - : (launch.attachments as Array<{ attachment: { id: string } }>).map( - ({ attachment }) => attachment.id, - ); + : (stored as Array<{ id: string }>).map((attachment) => attachment.id); }; const launchThere = ( draftKey: DraftId, operation: { commandId: string; messageId: string }, sent: ThreadId, - attachments: ReadonlyArray<{ id: string }>, + attachments: ReadonlyArray, ) => { sends.push({ commandId: operation.commandId, - attachmentIds: attachments.map((attachment) => attachment.id), + attachmentIds: attachments.map((attachment) => (attachment as { id: string }).id), persistedIds: persistedAttachmentIds(draftKey), }); const replayed = accepted.get(operation.commandId); @@ -1398,9 +1405,20 @@ describe("composerDraftStore project draft thread mapping", () => { sizeBytes: 4, }, ]; - // The composer's send, in its order: bind the operation, clear the composer, prepare the - // attachments, commit their references, launch; any failure restores the draft with the - // launch still unknown (the one sent, or before sending, the one pending before). + // 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, @@ -1408,22 +1426,31 @@ describe("composerDraftStore project draft thread mapping", () => { 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 request = JSON.stringify({ - text, - model: "claude-sonnet-4-6", - runtimeMode: "full-access", - }); const priorLaunch = draft.pendingLaunch ?? null; - if (priorLaunch && priorLaunch.request !== request) return { changed: true } as const; - allocated += 1; - const operation = priorLaunch ?? { - commandId: `command-${allocated}`, - messageId: `message-${allocated}`, - createdAt: "2026-11-18T00:00:00.000Z", + 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, @@ -1435,28 +1462,44 @@ describe("composerDraftStore project draft thread mapping", () => { tab.markRestoredLaunchCopy(draftKey); }; const bound = tab.markPromotedDraftThreadByRef(sentRef, operation); - store.clearComposerContent(draftKey); if (!bound) { fail(false); return { unbound: true } as const; } if (crashBeforePayload) return { crashed: true } as const; - // A retry sends the references its launch committed; a first send commits them first. - const attachments = operation.attachments?.map(({ attachment }) => attachment) ?? prepare(); + // 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.attachments === undefined && - !tab.commitPendingLaunchPayload( - sentRef, - operation.commandId, - attachments.map((attachment) => ({ attachment, inline: false })), - ) + operation.turn === undefined && + !tab.commitPendingLaunchPayload(sentRef, operation.commandId, turn) ) { fail(false); return { unbound: true } as const; } - const answer = launchThere(draftKey, operation, draft.threadId, attachments); + 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; @@ -1557,10 +1600,10 @@ describe("composerDraftStore project draft thread mapping", () => { 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)!; - crashed.restoreFailedDraftThread(crashDraftId, unsent, crashThreadId, unsent.pendingLaunch); - crashed.useComposerDraftStore.getState().setPrompt(crashDraftId, "Crash task"); - crashed.markRestoredLaunchCopy(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 }); @@ -1573,9 +1616,18 @@ describe("composerDraftStore project draft thread mapping", () => { // 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. - expect(send(crashed, crashDraftId, "Crash task")).toMatchObject({ launched: {} }); + // 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); @@ -1586,6 +1638,109 @@ describe("composerDraftStore project draft thread mapping", () => { } }); + 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); diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 2abc1b9ba68c..eba46abb15e5 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -4,8 +4,8 @@ import { rememberComposerImageBytes, } from "./components/chat/composerAttachmentFiles"; import { elementContextToPreviewAnnotation } from "./lib/elementContext"; +import type { StartThreadTurnInput } from "@t3tools/client-runtime/operations"; import { - ChatAttachment, ResponseContextRecord, ElementContextDetails, DEFAULT_MODEL, @@ -404,11 +404,11 @@ type LegacyPersistedComposerDraftStoreState = PersistedComposerDraftStoreState & LegacyStickyModelFields & LegacyV2StoreFields; -const SentLaunchAttachmentSchema = Schema.Struct({ - attachment: ChatAttachment, - inline: Schema.Boolean, +const PendingLaunchTurnSchema = Schema.Struct({ + environmentId: Schema.String, + input: Schema.Unknown, }); -const isSentLaunchAttachments = Schema.is(Schema.Array(SentLaunchAttachmentSchema)); +const isPersistedComposerThreadDraft = Schema.is(PersistedComposerThreadDraftState); const PersistedDraftThreadState = Schema.Struct({ threadId: ThreadId, @@ -450,7 +450,8 @@ const PersistedDraftThreadState = Schema.Struct({ messageId: Schema.String, createdAt: Schema.String, request: Schema.String, - attachments: Schema.optionalKey(Schema.Array(SentLaunchAttachmentSchema)), + composer: Schema.optionalKey(PersistedComposerThreadDraftState), + turn: Schema.optionalKey(PendingLaunchTurnSchema), restoredCopy: Schema.optionalKey(Schema.String), }), ), @@ -559,20 +560,21 @@ export interface PendingDraftLaunch { 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; /** - * The attachment references the launch sent, committed before it went out, so a retry sends - * exactly them. Absent until the launch's attachments are prepared; nothing was sent before. + * 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 attachments?: SentLaunchAttachment[]; + readonly turn?: PendingLaunchTurn; /** The composer content put back for a retry, which a settled launch must not leave behind. */ readonly restoredCopy?: string; } -/** An attachment as a launch sent it; an inline image's bytes are re-read, never stored. */ -export interface SentLaunchAttachment { - readonly attachment: ChatAttachment; - /** Sent as a data URL with this id; the restored file supplies the same bytes again. */ - readonly inline: boolean; +/** 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; @@ -1835,29 +1837,42 @@ function checkoutPullRequestsEqual( function hydratedPendingLaunch( stored: NonNullable, ): PendingDraftLaunch { - const { attachments, ...launch } = stored; - return { ...launch, ...(attachments === undefined ? {} : { attachments: [...attachments] }) }; + // 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, attachments, restoredCopy } = record; + 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" && - (attachments === undefined || isSentLaunchAttachments(attachments)) && + (composer === undefined || isPersistedComposerThreadDraft(composer)) && + (turn === undefined || isPendingLaunchTurn(turn)) && (restoredCopy === undefined || typeof restoredCopy === "string") ? { commandId, messageId, createdAt, request, - ...(attachments === undefined ? {} : { attachments: [...attachments] }), + ...(composer === undefined + ? {} + : { composer: composer as DeepMutable }), + ...(turn === undefined ? {} : { turn }), ...(restoredCopy === undefined ? {} : { restoredCopy }), } : null; @@ -1873,7 +1888,8 @@ function pendingLaunchesEqual( left.messageId === right.messageId && left.createdAt === right.createdAt && left.request === right.request && - JSON.stringify(left.attachments) === JSON.stringify(right.attachments) && + JSON.stringify(left.composer) === JSON.stringify(right.composer) && + JSON.stringify(left.turn) === JSON.stringify(right.turn) && left.restoredCopy === right.restoredCopy ); } @@ -2457,6 +2473,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 { @@ -2502,74 +2649,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"] @@ -2795,6 +2875,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 { @@ -2816,13 +2916,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: [], @@ -4625,6 +4726,7 @@ const composerDraftStore = create()( ); composerDraftLoadedState = partializeComposerDraftStoreState(composerDraftStore.getState()); +recoverUnconfirmedDraftLaunches(); export const useComposerDraftStore = composerDraftStore; @@ -4862,6 +4964,8 @@ export function markPromotedDraftThreadByRef( ), })); 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); } @@ -4869,7 +4973,7 @@ export function markPromotedDraftThreadByRef( if ( draftIds.length === 0 || (commitsDraftThreadBinding(draftIds, "promotedTo", threadRef) && - (!launch || commitsPendingLaunch(draftIds, launch))) + (!launch || commitsPendingLaunch(draftIds))) ) return true; // Each draft keeps what it had, which an earlier send may have committed. @@ -4877,17 +4981,36 @@ export function markPromotedDraftThreadByRef( 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 all of `launch` for each draft, references included; read after the - * flush that committed it. A matching command id alone is not the operation about to go out. + * 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, launch: PendingDraftLaunch) { +function commitsPendingLaunch(draftIds: ReadonlyArray) { try { const stored = readStoredComposerDraftState(); + const current = useComposerDraftStore.getState().draftThreadsByThreadKey; return draftIds.every((draftId) => pendingLaunchesEqual( storedPendingLaunch(stored?.draftThreadsByThreadKey[draftId]?.pendingLaunch), - launch, + current[draftId]?.pendingLaunch, ), ); } catch { @@ -4956,13 +5079,16 @@ 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. */ +/** + * 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: draft.prompt, + prompt: withInlineContextReferences(draft), images: draft.images.map((image) => image.id), files: draft.files.map((file) => file.id), terminalContexts: draft.terminalContexts.map((context) => context.id), @@ -4977,6 +5103,9 @@ export function composerDraftCopySignature(draft: ComposerThreadDraftState | und /** 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; @@ -4996,70 +5125,107 @@ export function markRestoredLaunchCopy(draftId: DraftId): void { } /** - * Records the attachment references a launch is about to send and commits them to storage, so a - * retry resends exactly them. False when storage did not take them: the launch must not go out. + * 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, - attachments: ReadonlyArray, + turn: PendingLaunchTurn, + fileUploads: ReadonlyArray = [], ): boolean { - const draftIds = Object.entries(useComposerDraftStore.getState().draftThreadsByThreadKey) - .filter( - ([, draftThread]) => + const prior = new Map( + Object.entries(useComposerDraftStore.getState().draftThreadsByThreadKey).flatMap( + ([draftId, draftThread]) => draftThread.environmentId === threadRef.environmentId && draftThread.threadId === threadRef.threadId && - draftThread.pendingLaunch?.commandId === commandId, - ) - .map(([draftId]) => draftId); - if (draftIds.length === 0) return false; - const prior = new Map( - draftIds.map((draftId) => [ - draftId, - useComposerDraftStore.getState().draftThreadsByThreadKey[draftId]?.pendingLaunch?.attachments, - ]), + draftThread.pendingLaunch?.commandId === commandId + ? [[draftId, draftThread.pendingLaunch] as const] + : [], + ), ); - const setAttachments = (pick: (draftId: string) => SentLaunchAttachment[] | undefined) => + 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]) => { - if (!draftIds.includes(draftId) || !draftThread.pendingLaunch) - return [draftId, draftThread]; - const { attachments: _replaced, ...launch } = draftThread.pendingLaunch; - const next = pick(draftId); - return [ - draftId, - { - ...draftThread, - pendingLaunch: next === undefined ? launch : { ...launch, attachments: next }, - }, - ]; + const launch = prior.get(draftId); + return [draftId, launch ? { ...draftThread, pendingLaunch: pick(launch) } : draftThread]; }), ), })); - setAttachments(() => [...attachments]); - // Uncommitted references never stay behind to pass as sent: each draft keeps what it had. - const committed = commitsLaunchAttachments(draftIds, attachments); - if (!committed) setAttachments((draftId) => prior.get(draftId)); - return committed; -} - -function commitsLaunchAttachments( - draftIds: ReadonlyArray, - attachments: ReadonlyArray, -): boolean { + 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(); - const stored = readStoredComposerDraftState(); - const expected = JSON.stringify(attachments); - return draftIds.every( - (draftId) => - JSON.stringify(stored?.draftThreadsByThreadKey[draftId]?.pendingLaunch?.attachments) === - expected, - ); + committed = commitsPendingLaunch([...prior.keys()]); } catch { - return false; + 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 { From 4d1cdfe69d052c17c96460df3f5b7246920894f2 Mon Sep 17 00:00:00 2001 From: Kameron Smith <112618179+nullStack65@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:23:09 +0000 Subject: [PATCH 4/4] fix(placement): keep a bound draft launch, and later edits, through a failed send A first send whose binding was stored but whose turn could not be stored lost its operation in the failure cleanup, which restored the launch pending before (none), and a composer the send never cleared was not marked as that launch's copy; sent again unchanged, it became a new operation. Separately, a draft write storage dropped without saying so still became the tab's cross-tab merge baseline, so its next write kept the stale stored text over the user's edit. The cleanup now keeps the launch whose binding storage held, and marks the uncleared composer as its copy only when this send's own binding committed and the composer still equals what that launch sent; the hook and tests share these helpers. Draft publication advances the merge baseline only when the exact bytes are read back; a write that was not read back is kept unconfirmed, and serialization treats storage holding exactly those bytes as this tab's own write before choosing its next baseline. Model: claude-opus-5-5 Task: CLO-866 universal native thread placement, PR70-R1-F2 / PR71-R1-F2 residual (caller disposition C6, global attempt 8) Agent: Claude Code in T3 Code, existing CLO-866 source owner thread (Opus 5.5) Co-Authored-By: Claude Opus 5.5 --- .../src/components/chat/chatViewSend.test.ts | 242 ++++++++++++++---- apps/web/src/components/chat/chatViewSend.ts | 42 +++ .../src/components/chat/useComposerSend.ts | 35 +-- apps/web/src/composerDraftStore.test.ts | 151 +++++++++++ apps/web/src/composerDraftStore.ts | 37 ++- 5 files changed, 441 insertions(+), 66 deletions(-) diff --git a/apps/web/src/components/chat/chatViewSend.test.ts b/apps/web/src/components/chat/chatViewSend.test.ts index fd8c45929d0a..83de6940aa18 100644 --- a/apps/web/src/components/chat/chatViewSend.test.ts +++ b/apps/web/src/components/chat/chatViewSend.test.ts @@ -57,16 +57,29 @@ async function openTab() { } type Tab = Awaited>; -// Storage that can refuse a write, or drop it without saying so. -const storageFaults = { throws: false, drops: false }; +// 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) => memory.getItem(name), + 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; }, }; } @@ -81,8 +94,7 @@ async function withReloadableStorage(run: () => Promise) { await run(); } finally { gate = null; - storageFaults.throws = false; - storageFaults.drops = false; + resetStorageFaults(); vi.useRealTimers(); vi.unstubAllGlobals(); vi.resetModules(); @@ -179,10 +191,10 @@ function composeDraft( } /** - * A first send in the composer hook's order: read the composer, start or retry its uploads, start + * 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 an uncertain launch error restore the draft. `edit` runs while - * reads are pending; `commitFault` makes storage refuse or drop the turn's commit. + * 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, @@ -191,8 +203,12 @@ async function sendDraft( uploads: boolean; stopAfterBind?: boolean; edit?: () => void; + editBeforeCommit?: () => void; launchFails?: boolean; - commitFault?: "throws" | "drops"; + 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(); @@ -218,8 +234,8 @@ async function sendDraft( ); expect(plan.type).toBe("new"); const operation = { - commandId: `command-${draft.threadId}`, - messageId: `message-${draft.threadId}`, + commandId: `command-${draft.threadId}${options.label ?? ""}`, + messageId: `message-${draft.threadId}${options.label ?? ""}`, createdAt: "2026-11-18T11:00:00.000Z", request: launchRequest(tab), }; @@ -245,9 +261,33 @@ async function sendDraft( gate = null; } const composer = await sentComposer; - expect(tab.store.markPromotedDraftThreadByRef(sentRef, { ...operation, composer })).toBe(true); + 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: { @@ -279,17 +319,26 @@ async function sendDraft( turn, fileUploads, ); - storageFaults.throws = false; - storageFaults.drops = false; - if (!committed) return { committed, boundLaunch, turn, cleared: false, before, operation }; - const cleared = tab.send.clearSentComposerContent(draft.draftId, before); - if (options.launchFails) { - // No launch answer proves the host did not take it: the hook's restore for an emptied draft. - tab.store.restoreFailedDraftThread(draft.draftId, draftThread, draft.threadId, operation); - tab.send.restoreComposerDraft(draft.draftId, snapshot); - tab.store.markRestoredLaunchCopy(draft.draftId); + 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, + }; } - return { committed, boundLaunch, turn, cleared, 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( @@ -340,7 +389,7 @@ describe("a draft launch interrupted by a reload", () => { uploads: true, }); const sent = (await sendDraft(tab, draft, { uploads: true }))!; - expect(sent.turn.input.message.attachments.map((attachment) => attachment.id)).toEqual([ + expect(sent.turn!.input.message.attachments.map((attachment) => attachment.id)).toEqual([ "upload-shot-1", "upload-file-1", ]); @@ -351,7 +400,7 @@ describe("a draft launch interrupted by a reload", () => { 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(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)), @@ -438,7 +487,7 @@ describe("a draft launch interrupted by a reload", () => { 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(sent.turn!.input.message.text).toBe("Describe this"); expect(store.getDraftSession(draft.draftId)?.pendingLaunch?.composer?.prompt).toBe( "Describe this", ); @@ -466,7 +515,7 @@ describe("a draft launch whose file's first upload failed", () => { 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([ + expect(sent.turn!.input.message.attachments.map((attachment) => attachment.id)).toEqual([ "upload-shot-1", "upload-file-retried", ]); @@ -478,8 +527,8 @@ describe("a draft launch whose file's first upload failed", () => { 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, + commandId: sent.operation!.commandId, + messageId: sent.operation!.messageId, turn: JSON.parse(JSON.stringify(sent.turn)), }); }); @@ -505,15 +554,15 @@ describe("a draft launch whose file's first upload failed", () => { 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, + commandId: sent.operation!.commandId, + messageId: sent.operation!.messageId, turn: JSON.parse(JSON.stringify(sent.turn)), }); }); }); - it.each(["throws", "drops"] as const)( - "keeps the bound operation, its composer and the draft when storage %s the turn's commit", + 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(); @@ -525,23 +574,120 @@ describe("a draft launch whose file's first upload failed", () => { }); const sent = (await sendDraft(tab, draft, { uploads: true, commitFault: fault }))!; expect(sent.committed).toBe(false); - const session = tab.store.useComposerDraftStore.getState().getDraftSession(draft.draftId)!; - // In memory and in storage: the operation as bound, no turn, no upload on its composer. - expect(session.pendingLaunch).toEqual(sent.boundLaunch); - expect(session.pendingLaunch?.turn).toBeUndefined(); - expect(session.pendingLaunch?.composer?.files?.[0]?.attachmentId).toBeUndefined(); - expect(session.promotedTo).toEqual(scopeThreadRef(environmentId, draft.threadId)); - expect( - tab.store.useComposerDraftStore.getState().getComposerDraft(draft.draftId)?.prompt, - ).toBe("Review the report"); - const reloaded = await reload(); - const stored = reloaded.store.useComposerDraftStore - .getState() - .getDraftSession(draft.draftId); - expect(stored?.pendingLaunch?.turn).toBeUndefined(); - expect(stored?.pendingLaunch?.commandId).toBe(sent.operation.commandId); - expect(stored?.sentTo).toEqual(scopeThreadRef(environmentId, draft.threadId)); + // 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 ac99a513a08c..0b4f1169ce57 100644 --- a/apps/web/src/components/chat/chatViewSend.ts +++ b/apps/web/src/components/chat/chatViewSend.ts @@ -30,7 +30,11 @@ import { type ComposerImageAttachment, type ComposerThreadDraftState, type ComposerThreadTarget, + type PendingDraftLaunch, type PreparedFileUpload, + composerDraftHasUserContent, + markRestoredLaunchCopy, + markUnchangedLaunchCopy, toSentComposerDraft, useComposerDraftStore, DraftId, @@ -332,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/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 41dd3ab5cf74..ab6988099e26 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -74,7 +74,6 @@ import { commitPendingLaunchPayload, composerDraftCopySignature, type PendingLaunchTurn, - markRestoredLaunchCopy, type PendingDraftLaunch, checkoutPullRequestUrlToLink, composerDraftHasUserContent, @@ -138,9 +137,10 @@ import { resolveMultipleModelTargets, prepareTurnAttachments, clearSentComposerContent, + launchLeftPendingAfterFailure, preparedFileUploads, readSentComposer, - restoreComposerDraft, + restoreFailedSendComposer, } from "./chatViewSend"; import type { EnvironmentProject, @@ -1305,8 +1305,6 @@ export function useComposerSend(input: ComposerSendInput) { ? { ...launchOperation, composer: sentComposer.value } : launchOperation, )); - // Set once the launch itself goes out; failures before it sent nothing. - let launchAttempted = false; // A draft's launch clears the composer only once its turn is stored; an edit is the user's. let composerCleared = false; const clearSentComposer = () => { @@ -1495,7 +1493,6 @@ export function useComposerSend(input: ComposerSendInput) { ) : null; if (backgroundThreadRef) beginBackgroundDraftSubmissionByRef(backgroundThreadRef); - launchAttempted = true; const startPromise = startThreadTurn(turnForLaunch); if (backgroundThreadRef) { try { @@ -1581,8 +1578,12 @@ export function useComposerSend(input: ComposerSendInput) { wasBootstrapThreadDeleted(squashAtomCommandFailure(failure)) ? newThreadId() : threadIdForSend, - // No launch answer proves the host did not accept it, so a sent launch stays pending. - launchAttempted ? (launchOperation ?? null) : priorLaunch, + // 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)); } @@ -1593,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); - const composerAfterFailure = - useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) ?? null; - if (!composerCleared && !composerDraftContentChanged(draftBeforeSend, composerAfterFailure)) { - // Never cleared, the composer still holds the message to send again. - } else if (composerDraftHasUserContent(composerAfterFailure)) { + 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; @@ -1628,12 +1633,10 @@ export function useComposerSend(input: ComposerSendInput) { : {}), }), ); - } else { - const retryComposerImages = restoreComposerDraft(composerDraftTarget, sendSnapshot); - if (isLocalDraftThread && draftId) markRestoredLaunchCopy(draftId); + } 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 56ce823ffa62..cd10f598ab30 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -766,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", () => { diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index eba46abb15e5..83228fa1a16e 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -141,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); @@ -208,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; @@ -220,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, @@ -5124,6 +5142,21 @@ export function markRestoredLaunchCopy(draftId: DraftId): void { }); } +/** + * 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.