Skip to content
TypeScript

refactor(web): split two self-contained phases out of onSend (#20321)

Julius Marmingecbee9c9847d0
diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts
index 43c970053e7..fdd16a34e53 100644
--- a/apps/web/src/components/ChatView.logic.test.ts
+++ b/apps/web/src/components/ChatView.logic.test.ts
@@ -1,4 +1,8 @@
-import { findRecordedWorktreeSetup, resolveVisibleWorktreeSetup } from "./ChatView.logic";
+import {
+ findRecordedWorktreeSetup,
+ mergeDirectPreviewAnnotation,
+ resolveVisibleWorktreeSetup,
+} from "./ChatView.logic";
import {
recallCheckoutIsRepo,
rememberCheckoutIsRepo,
@@ -17,6 +21,7 @@ import {
EventId,
MessageId,
ProjectId,
+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
ProviderInstanceId,
ThreadId,
RunId,
@@ -2173,3 +2178,59 @@ describe("waitForRevertedMessage", () => {
vi.useRealTimers();
});
});
+
+describe("mergeDirectPreviewAnnotation", () => {
+ const annotation = (id: string) =>
+ ({
+ id,
+ pageUrl: "http://localhost:5173/",
+ pageTitle: null,
+ comment: "tighten this",
+ elements: [],
+ regions: [],
+ strokes: [],
+ styleChanges: [],
+ screenshot: {
+ dataUrl: "data:image/png;base64,AAAA",
+ width: 10,
+ height: 10,
+ cropRect: { x: 0, y: 0, width: 10, height: 10 },
+ },
+ createdAt: "2026-10-16T00:00:00.000Z",
+ }) as const;
+ const image = (id: string) =>
+ ({ id, type: "image", name: `${id}.png`, mimeType: "image/png", sizeBytes: 1 }) as never;
+
+ it("appends the screenshot and claims the crop when the turn has room", () => {
+ const result = mergeDirectPreviewAnnotation({
+ images: [],
+ fileCount: 0,
+ previewAnnotations: [],
+ direct: { annotation: annotation("a"), image: image("crop") },
+ });
+ expect(result.images.map((entry) => entry.id)).toEqual(["crop"]);
+ expect(result.previewAnnotations[0]?.screenshot?.dataUrl).toBe("");
+ });
+
+ it("drops the screenshot claim when the attachment cap is full", () => {
+ const result = mergeDirectPreviewAnnotation({
+ images: [],
+ fileCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
+ previewAnnotations: [],
+ direct: { annotation: annotation("a"), image: image("crop") },
+ });
+ expect(result.images).toEqual([]);
+ expect(result.previewAnnotations[0]?.screenshot).toBeNull();
+ });
+
+ it("keeps an annotation already in the draft as it is", () => {
+ const existing = [annotation("a")];
+ const result = mergeDirectPreviewAnnotation({
+ images: [],
+ fileCount: 0,
+ previewAnnotations: existing,
+ direct: { annotation: annotation("a"), image: null },
+ });
+ expect(result.previewAnnotations).toBe(existing);
+ });
+});
diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts
index f01fa322757..7765ad6edbe 100644
--- a/apps/web/src/components/ChatView.logic.ts
+++ b/apps/web/src/components/ChatView.logic.ts
@@ -2,6 +2,7 @@ import * as Option from "effect/Option";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import {
ANTIGRAVITY_DEFAULT_MODEL,
+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
type AssetCreateUrlInput,
type AssetCreateUrlResult,
type ChatFileAttachment,
@@ -1291,3 +1292,50 @@ export function restorePlanFollowUpComposer(input: {
detectTrigger: true,
});
}
+
+/**
+ * Adds a directly sent preview annotation to the composer's images and
+ * annotations. Its screenshot rides along only while the turn has room for
+ * another attachment; over the cap the server rejects the whole turn.
+ */
+export function mergeDirectPreviewAnnotation(input: {
+ readonly images: ReadonlyArray<ComposerImageAttachment>;
+ readonly fileCount: number;
+ readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
+ readonly direct:
+ | {
+ readonly annotation: PreviewAnnotationPayload;
+ readonly image: ComposerImageAttachment | null;
+ }
+ | undefined;
+}): {
+ readonly images: ReadonlyArray<ComposerImageAttachment>;
+ readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
+} {
+ const { direct } = input;
+ if (!direct) return { images: input.images, previewAnnotations: input.previewAnnotations };
+ const imageAlreadyAttached =
+ direct.image !== null && input.images.some((image) => image.id === direct.image?.id);
+ const imageAppended =
+ direct.image !== null &&
+ !imageAlreadyAttached &&
+ input.images.length + input.fileCount < PROVIDER_SEND_TURN_MAX_ATTACHMENTS;
+ const images = direct.image && imageAppended ? [...input.images, direct.image] : input.images;
+ const previewAnnotations = input.previewAnnotations.some(
+ (annotation) => annotation.id === direct.annotation.id,
+ )
+ ? input.previewAnnotations
+ : [
+ ...input.previewAnnotations,
+ {
+ ...direct.annotation,
+ // Claim an attached crop only when the screenshot really rides
+ // along; a cap-dropped image must not produce a lying prompt.
+ screenshot:
+ direct.annotation.screenshot && (imageAppended || imageAlreadyAttached)
+ ? { ...direct.annotation.screenshot, dataUrl: "" }
+ : null,
+ },
+ ];
+ return { images, previewAnnotations };
+}
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 121e7f295a5..7e49209c206 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -2,6 +2,7 @@ import { ThreadFind, ThreadFindCanvas, type ThreadFindControls } from "./chat/Th
import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar";
import { usageLimitRecoveryBannerItem } from "./chat/UsageLimitRecoveryBanner";
import {
+ mergeDirectPreviewAnnotation,
resolveBackgroundDraftWorkspaceOptions,
resolveDraftHeroState,
shouldDockDraftHeroForSubmission,
@@ -759,6 +760,87 @@ const draftFanoutStateAtom = Atom.family((_routeKey: string) =>
}).pipe(Atom.keepAlive),
);
+/**
+ * Starts one thread of a multiple-model send. A request that may have
+ * reached the server before failing is remembered by `retryKey`, so sending
+ * again cannot silently create a duplicate thread; its failure toast offers
+ * to open that thread or to allow the retry.
+ */
+async function startFanoutThread(input: {
+ readonly retryKey: string;
+ readonly model: string;
+ readonly uncertainSubmissions: Map<string, ThreadId>;
+ readonly start: (threadId: ThreadId) => Promise<AtomCommandResult<unknown, unknown>>;
+ readonly openThread: (threadId: ThreadId) => void;
+}): Promise<boolean> {
+ const { retryKey, uncertainSubmissions } = input;
+ const uncertainThreadId = uncertainSubmissions.get(retryKey);
+ const targetThreadId = uncertainThreadId ?? newThreadId();
+ let requestMayHaveStarted = false;
+ try {
+ if (uncertainThreadId) {
+ throw new Error(
+ "The previous request may have started. Open its thread to check before sending again.",
+ );
+ }
+ requestMayHaveStarted = true;
+ const result = await input.start(targetThreadId);
+ if (result._tag === "Failure") {
+ const error = squashAtomCommandFailure(result);
+ if (wasBootstrapThreadDeleted(error) || wasBootstrapThreadNotCreated(error)) {
+ requestMayHaveStarted = false;
+ }
+ throw error;
+ }
+ return true;
+ } catch (error) {
+ if (requestMayHaveStarted && !uncertainSubmissions.has(retryKey)) {
+ uncertainSubmissions.set(retryKey, targetThreadId);
+ }
+ const retainedThreadId = uncertainSubmissions.get(retryKey);
+ const failureToastId = toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: `Could not start ${input.model}`,
+ description: error instanceof Error ? error.message : "Failed to send message.",
+ ...(retainedThreadId
+ ? {
+ timeout: 0,
+ data: {
+ secondaryActionProps: {
+ children: "Allow retry",
+ onClick: () => {
+ void readLocalApi()
+ ?.dialogs.confirm(
+ "The previous request may already be running. Check its thread first. Allow another send that could create a duplicate thread?",
+ )
+ .then(
+ (confirmed) => {
+ if (
+ confirmed &&
+ uncertainSubmissions.get(retryKey) === retainedThreadId
+ ) {
+ uncertainSubmissions.delete(retryKey);
+ toastManager.close(failureToastId);
+ }
+ },
+ () => undefined,
+ );
+ },
+ },
+ },
+ actionProps: {
+ children: "Open thread",
+ onClick: () => input.openThread(retainedThreadId),
+ },
+ }
+ : {}),
+ }),
+ );
+ return false;
+ }
+}
+
function formatOutgoingPrompt(params: {
provider: ProviderDriverKind;
model: string | null;
@@ -6823,36 +6905,13 @@ export default function ChatView(props: ChatViewProps) {
interactionMode: sendInteractionMode,
interactionModeEnabled: sendInteractionModeEnabled,
} = sendCtx;
- const annotationImageAlreadyAttached =
- directAnnotation?.image !== undefined &&
- sendContextImages.some((image) => image.id === directAnnotation.image?.id);
- // A full composer (e.g. 8 files) cannot take the annotation screenshot;
- // over the cap the server rejects the whole turn.
- const annotationImageAppended =
- directAnnotation?.image !== undefined &&
- !annotationImageAlreadyAttached &&
- sendContextImages.length + composerFiles.length < PROVIDER_SEND_TURN_MAX_ATTACHMENTS;
- const composerImages =
- directAnnotation?.image && annotationImageAppended
- ? [...sendContextImages, directAnnotation.image]
- : sendContextImages;
- const composerPreviewAnnotations =
- directAnnotation &&
- !sendContextPreviewAnnotations.some(
- (annotation) => annotation.id === directAnnotation.annotation.id,
- )
- ? [
- ...sendContextPreviewAnnotations,
- {
- ...directAnnotation.annotation,
- screenshot:
- directAnnotation.annotation.screenshot &&
- (annotationImageAppended || annotationImageAlreadyAttached)
- ? { ...directAnnotation.annotation.screenshot, dataUrl: "" }
- : null,
- },
- ]
- : sendContextPreviewAnnotations;
+ const { images: composerImages, previewAnnotations: composerPreviewAnnotations } =
+ mergeDirectPreviewAnnotation({
+ images: sendContextImages,
+ fileCount: composerFiles.length,
+ previewAnnotations: sendContextPreviewAnnotations,
+ direct: directAnnotation,
+ });
// A direct "send annotation" writes the draft and sends in the same tick; the reference
// must be in the text now, not after the next render.
const promptForSend = directAnnotation
@@ -7349,129 +7408,70 @@ export default function ChatView(props: ChatViewProps) {
setThreadError(threadIdForSend, null);
const starts = Promise.all(
multipleTargets.map(async (target) => {
- const retryKey = JSON.stringify([
- routeThreadKey,
- target.selection.instanceId,
- target.selection.model,
- ]);
- const uncertainThreadId = uncertainMultipleSubmissionsRef.current.get(retryKey);
- const targetThreadId = uncertainThreadId ?? newThreadId();
- let requestMayHaveStarted = false;
- try {
- if (uncertainThreadId) {
- throw new Error(
- "The previous request may have started. Open its thread to check before sending again.",
- );
- }
- const supportsInlineMessageContext =
- appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment
- .capabilities.inlineMessageContext === true;
- requestMayHaveStarted = true;
- const result = await startThreadTurn({
- environmentId,
- input: {
- threadId: targetThreadId,
- message: {
- messageId: newMessageId(),
- role: "user",
- text:
- context && !supportsInlineMessageContext
- ? serializeLegacyContextMessage({
- text: target.text,
- records: context.records,
- })
- : target.text,
- attachments,
- ...(context && supportsInlineMessageContext ? { context } : {}),
- },
- modelSelection: target.selection,
- titleSeed: title,
- runtimeMode,
- interactionMode: target.interactionMode,
- bootstrap: {
- createThread: {
- projectId: activeProject.id,
- title,
- modelSelection: target.selection,
- runtimeMode,
- interactionMode: target.interactionMode,
- branch: activeThreadBranch,
- worktreePath: null,
- createdAt: messageCreatedAt,
+ const started = await startFanoutThread({
+ retryKey: JSON.stringify([
+ routeThreadKey,
+ target.selection.instanceId,
+ target.selection.model,
+ ]),
+ model: target.selection.model,
+ uncertainSubmissions: uncertainMultipleSubmissionsRef.current,
+ start: (targetThreadId) => {
+ const supportsInlineMessageContext =
+ appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment
+ .capabilities.inlineMessageContext === true;
+ return startThreadTurn({
+ environmentId,
+ input: {
+ threadId: targetThreadId,
+ message: {
+ messageId: newMessageId(),
+ role: "user",
+ text:
+ context && !supportsInlineMessageContext
+ ? serializeLegacyContextMessage({
+ text: target.text,
+ records: context.records,
+ })
+ : target.text,
+ attachments,
+ ...(context && supportsInlineMessageContext ? { context } : {}),
},
- prepareWorktree: {
- projectCwd: activeProject.workspaceRoot,
- baseBranch: activeThreadBranch!,
- requireWorktree: true,
- ...(startFromOrigin ? { startFromOrigin: true } : {}),
+ modelSelection: target.selection,
+ titleSeed: title,
+ runtimeMode,
+ interactionMode: target.interactionMode,
+ bootstrap: {
+ createThread: {
+ projectId: activeProject.id,
+ title,
+ modelSelection: target.selection,
+ runtimeMode,
+ interactionMode: target.interactionMode,
+ branch: activeThreadBranch,
+ worktreePath: null,
+ createdAt: messageCreatedAt,
+ },
+ prepareWorktree: {
+ projectCwd: activeProject.workspaceRoot,
+ baseBranch: activeThreadBranch!,
+ requireWorktree: true,
+ ...(startFromOrigin ? { startFromOrigin: true } : {}),
+ },
+ runSetupScript: true,
},
- runSetupScript: true,
+ createdAt: messageCreatedAt,
},
- createdAt: messageCreatedAt,
- },
- });
- if (result._tag === "Failure") {
- const error = squashAtomCommandFailure(result);
- if (wasBootstrapThreadDeleted(error) || wasBootstrapThreadNotCreated(error)) {
- requestMayHaveStarted = false;
- }
- throw error;
- }
- startedCount += 1;
- } catch (error) {
- if (requestMayHaveStarted && !uncertainMultipleSubmissionsRef.current.has(retryKey)) {
- uncertainMultipleSubmissionsRef.current.set(retryKey, targetThreadId);
- }
- failedSelections.push(target.selection);
- const retainedThreadId = uncertainMultipleSubmissionsRef.current.get(retryKey);
- const failureToastId = toastManager.add(
- stackedThreadToast({
- type: "error",
- title: `Could not start ${target.selection.model}`,
- description: error instanceof Error ? error.message : "Failed to send message.",
- ...(retainedThreadId
- ? {
- timeout: 0,
- data: {
- secondaryActionProps: {
- children: "Allow retry",
- onClick: () => {
- void readLocalApi()
- ?.dialogs.confirm(
- "The previous request may already be running. Check its thread first. Allow another send that could create a duplicate thread?",
- )
- .then(
- (confirmed) => {
- if (
- confirmed &&
- uncertainMultipleSubmissionsRef.current.get(retryKey) ===
- retainedThreadId
- ) {
- uncertainMultipleSubmissionsRef.current.delete(retryKey);
- toastManager.close(failureToastId);
- }
- },
- () => undefined,
- );
- },
- },
- },
- actionProps: {
- children: "Open thread",
- onClick: () => {
- void navigate({
- to: "/$environmentId/$threadId",
- params: buildThreadRouteParams(
- scopeThreadRef(environmentId, retainedThreadId),
- ),
- });
- },
- },
- }
- : {}),
+ });
+ },
+ openThread: (threadId) =>
+ void navigate({
+ to: "/$environmentId/$threadId",
+ params: buildThreadRouteParams(scopeThreadRef(environmentId, threadId)),
}),
- );
- }
+ });
+ if (started) startedCount += 1;
+ else failedSelections.push(target.selection);
}),
);
sendInFlightRef.current = false;