The best way to control Claude Code, Codex and more from any computer or phone
refactor(web): split two self-contained phases out of onSend (#20321)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 16, 2026 at 17:39 UTC
cbee9c9847d0a5db09a12d7aa1ea150f7d6ab38f
3 files changed
+259
-150
apps/web/src/components/ChatView.logic.test.ts
+62
-1
@@ -1,4 +1,8 @@
1
-import { findRecordedWorktreeSetup, resolveVisibleWorktreeSetup } from "./ChatView.logic";
1
+import {
2
+ findRecordedWorktreeSetup,
3
+ mergeDirectPreviewAnnotation,
4
+ resolveVisibleWorktreeSetup,
5
+} from "./ChatView.logic";
6
import {
7
recallCheckoutIsRepo,
8
rememberCheckoutIsRepo,
@@ -17,6 +21,7 @@ import {
21
EventId,
22
MessageId,
23
ProjectId,
24
+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
25
ProviderInstanceId,
26
ThreadId,
27
RunId,
@@ -2173,3 +2178,59 @@ describe("waitForRevertedMessage", () => {
2178
vi.useRealTimers();
2179
});
2180
});
2181
+
2182
+describe("mergeDirectPreviewAnnotation", () => {
2183
+ const annotation = (id: string) =>
2184
+ ({
2185
+ id,
2186
+ pageUrl: "http://localhost:5173/",
2187
+ pageTitle: null,
2188
+ comment: "tighten this",
2189
+ elements: [],
2190
+ regions: [],
2191
+ strokes: [],
2192
+ styleChanges: [],
2193
+ screenshot: {
2194
+ dataUrl: "data:image/png;base64,AAAA",
2195
+ width: 10,
2196
+ height: 10,
2197
+ cropRect: { x: 0, y: 0, width: 10, height: 10 },
2198
+ },
2199
+ createdAt: "2026-10-16T00:00:00.000Z",
2200
+ }) as const;
2201
+ const image = (id: string) =>
2202
+ ({ id, type: "image", name: `${id}.png`, mimeType: "image/png", sizeBytes: 1 }) as never;
2203
+
2204
+ it("appends the screenshot and claims the crop when the turn has room", () => {
2205
+ const result = mergeDirectPreviewAnnotation({
2206
+ images: [],
2207
+ fileCount: 0,
2208
+ previewAnnotations: [],
2209
+ direct: { annotation: annotation("a"), image: image("crop") },
2210
+ });
2211
+ expect(result.images.map((entry) => entry.id)).toEqual(["crop"]);
2212
+ expect(result.previewAnnotations[0]?.screenshot?.dataUrl).toBe("");
2213
+ });
2214
+
2215
+ it("drops the screenshot claim when the attachment cap is full", () => {
2216
+ const result = mergeDirectPreviewAnnotation({
2217
+ images: [],
2218
+ fileCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
2219
+ previewAnnotations: [],
2220
+ direct: { annotation: annotation("a"), image: image("crop") },
2221
+ });
2222
+ expect(result.images).toEqual([]);
2223
+ expect(result.previewAnnotations[0]?.screenshot).toBeNull();
2224
+ });
2225
+
2226
+ it("keeps an annotation already in the draft as it is", () => {
2227
+ const existing = [annotation("a")];
2228
+ const result = mergeDirectPreviewAnnotation({
2229
+ images: [],
2230
+ fileCount: 0,
2231
+ previewAnnotations: existing,
2232
+ direct: { annotation: annotation("a"), image: null },
2233
+ });
2234
+ expect(result.previewAnnotations).toBe(existing);
2235
+ });
2236
+});
apps/web/src/components/ChatView.logic.ts
+48
@@ -2,6 +2,7 @@ import * as Option from "effect/Option";
2
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
3
import {
4
ANTIGRAVITY_DEFAULT_MODEL,
5
+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
6
type AssetCreateUrlInput,
7
type AssetCreateUrlResult,
8
type ChatFileAttachment,
@@ -1291,3 +1292,50 @@ export function restorePlanFollowUpComposer(input: {
1292
detectTrigger: true,
1293
});
1294
}
1295
+
1296
+/**
1297
+ * Adds a directly sent preview annotation to the composer's images and
1298
+ * annotations. Its screenshot rides along only while the turn has room for
1299
+ * another attachment; over the cap the server rejects the whole turn.
1300
+ */
1301
+export function mergeDirectPreviewAnnotation(input: {
1302
+ readonly images: ReadonlyArray<ComposerImageAttachment>;
1303
+ readonly fileCount: number;
1304
+ readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1305
+ readonly direct:
1306
+ | {
1307
+ readonly annotation: PreviewAnnotationPayload;
1308
+ readonly image: ComposerImageAttachment | null;
1309
+ }
1310
+ | undefined;
1311
+}): {
1312
+ readonly images: ReadonlyArray<ComposerImageAttachment>;
1313
+ readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
1314
+} {
1315
+ const { direct } = input;
1316
+ if (!direct) return { images: input.images, previewAnnotations: input.previewAnnotations };
1317
+ const imageAlreadyAttached =
1318
+ direct.image !== null && input.images.some((image) => image.id === direct.image?.id);
1319
+ const imageAppended =
1320
+ direct.image !== null &&
1321
+ !imageAlreadyAttached &&
1322
+ input.images.length + input.fileCount < PROVIDER_SEND_TURN_MAX_ATTACHMENTS;
1323
+ const images = direct.image && imageAppended ? [...input.images, direct.image] : input.images;
1324
+ const previewAnnotations = input.previewAnnotations.some(
1325
+ (annotation) => annotation.id === direct.annotation.id,
1326
+ )
1327
+ ? input.previewAnnotations
1328
+ : [
1329
+ ...input.previewAnnotations,
1330
+ {
1331
+ ...direct.annotation,
1332
+ // Claim an attached crop only when the screenshot really rides
1333
+ // along; a cap-dropped image must not produce a lying prompt.
1334
+ screenshot:
1335
+ direct.annotation.screenshot && (imageAppended || imageAlreadyAttached)
1336
+ ? { ...direct.annotation.screenshot, dataUrl: "" }
1337
+ : null,
1338
+ },
1339
+ ];
1340
+ return { images, previewAnnotations };
1341
+}
apps/web/src/components/ChatView.tsx
+149
-149
@@ -2,6 +2,7 @@ import { ThreadFind, ThreadFindCanvas, type ThreadFindControls } from "./chat/Th
2
import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar";
3
import { usageLimitRecoveryBannerItem } from "./chat/UsageLimitRecoveryBanner";
4
import {
5
+ mergeDirectPreviewAnnotation,
6
resolveBackgroundDraftWorkspaceOptions,
7
resolveDraftHeroState,
8
shouldDockDraftHeroForSubmission,
@@ -759,6 +760,87 @@ const draftFanoutStateAtom = Atom.family((_routeKey: string) =>
760
}).pipe(Atom.keepAlive),
761
);
762
763
+/**
764
+ * Starts one thread of a multiple-model send. A request that may have
765
+ * reached the server before failing is remembered by `retryKey`, so sending
766
+ * again cannot silently create a duplicate thread; its failure toast offers
767
+ * to open that thread or to allow the retry.
768
+ */
769
+async function startFanoutThread(input: {
770
+ readonly retryKey: string;
771
+ readonly model: string;
772
+ readonly uncertainSubmissions: Map<string, ThreadId>;
773
+ readonly start: (threadId: ThreadId) => Promise<AtomCommandResult<unknown, unknown>>;
774
+ readonly openThread: (threadId: ThreadId) => void;
775
+}): Promise<boolean> {
776
+ const { retryKey, uncertainSubmissions } = input;
777
+ const uncertainThreadId = uncertainSubmissions.get(retryKey);
778
+ const targetThreadId = uncertainThreadId ?? newThreadId();
779
+ let requestMayHaveStarted = false;
780
+ try {
781
+ if (uncertainThreadId) {
782
+ throw new Error(
783
+ "The previous request may have started. Open its thread to check before sending again.",
784
+ );
785
+ }
786
+ requestMayHaveStarted = true;
787
+ const result = await input.start(targetThreadId);
788
+ if (result._tag === "Failure") {
789
+ const error = squashAtomCommandFailure(result);
790
+ if (wasBootstrapThreadDeleted(error) || wasBootstrapThreadNotCreated(error)) {
791
+ requestMayHaveStarted = false;
792
+ }
793
+ throw error;
794
+ }
795
+ return true;
796
+ } catch (error) {
797
+ if (requestMayHaveStarted && !uncertainSubmissions.has(retryKey)) {
798
+ uncertainSubmissions.set(retryKey, targetThreadId);
799
+ }
800
+ const retainedThreadId = uncertainSubmissions.get(retryKey);
801
+ const failureToastId = toastManager.add(
802
+ stackedThreadToast({
803
+ type: "error",
804
+ title: `Could not start ${input.model}`,
805
+ description: error instanceof Error ? error.message : "Failed to send message.",
806
+ ...(retainedThreadId
807
+ ? {
808
+ timeout: 0,
809
+ data: {
810
+ secondaryActionProps: {
811
+ children: "Allow retry",
812
+ onClick: () => {
813
+ void readLocalApi()
814
+ ?.dialogs.confirm(
815
+ "The previous request may already be running. Check its thread first. Allow another send that could create a duplicate thread?",
816
+ )
817
+ .then(
818
+ (confirmed) => {
819
+ if (
820
+ confirmed &&
821
+ uncertainSubmissions.get(retryKey) === retainedThreadId
822
+ ) {
823
+ uncertainSubmissions.delete(retryKey);
824
+ toastManager.close(failureToastId);
825
+ }
826
+ },
827
+ () => undefined,
828
+ );
829
+ },
830
+ },
831
+ },
832
+ actionProps: {
833
+ children: "Open thread",
834
+ onClick: () => input.openThread(retainedThreadId),
835
+ },
836
+ }
837
+ : {}),
838
+ }),
839
+ );
840
+ return false;
841
+ }
842
+}
843
+
844
function formatOutgoingPrompt(params: {
845
provider: ProviderDriverKind;
846
model: string | null;
@@ -6823,36 +6905,13 @@ export default function ChatView(props: ChatViewProps) {
6905
interactionMode: sendInteractionMode,
6906
interactionModeEnabled: sendInteractionModeEnabled,
6907
} = sendCtx;
6826
- const annotationImageAlreadyAttached =
6827
- directAnnotation?.image !== undefined &&
6828
- sendContextImages.some((image) => image.id === directAnnotation.image?.id);
6829
- // A full composer (e.g. 8 files) cannot take the annotation screenshot;
6830
- // over the cap the server rejects the whole turn.
6831
- const annotationImageAppended =
6832
- directAnnotation?.image !== undefined &&
6833
- !annotationImageAlreadyAttached &&
6834
- sendContextImages.length + composerFiles.length < PROVIDER_SEND_TURN_MAX_ATTACHMENTS;
6835
- const composerImages =
6836
- directAnnotation?.image && annotationImageAppended
6837
- ? [...sendContextImages, directAnnotation.image]
6838
- : sendContextImages;
6839
- const composerPreviewAnnotations =
6840
- directAnnotation &&
6841
- !sendContextPreviewAnnotations.some(
6842
- (annotation) => annotation.id === directAnnotation.annotation.id,
6843
- )
6844
- ? [
6845
- ...sendContextPreviewAnnotations,
6846
- {
6847
- ...directAnnotation.annotation,
6848
- screenshot:
6849
- directAnnotation.annotation.screenshot &&
6850
- (annotationImageAppended || annotationImageAlreadyAttached)
6851
- ? { ...directAnnotation.annotation.screenshot, dataUrl: "" }
6852
- : null,
6853
- },
6854
- ]
6855
- : sendContextPreviewAnnotations;
6908
+ const { images: composerImages, previewAnnotations: composerPreviewAnnotations } =
6909
+ mergeDirectPreviewAnnotation({
6910
+ images: sendContextImages,
6911
+ fileCount: composerFiles.length,
6912
+ previewAnnotations: sendContextPreviewAnnotations,
6913
+ direct: directAnnotation,
6914
+ });
6915
// A direct "send annotation" writes the draft and sends in the same tick; the reference
6916
// must be in the text now, not after the next render.
6917
const promptForSend = directAnnotation
@@ -7349,129 +7408,70 @@ export default function ChatView(props: ChatViewProps) {
7408
setThreadError(threadIdForSend, null);
7409
const starts = Promise.all(
7410
multipleTargets.map(async (target) => {
7352
- const retryKey = JSON.stringify([
7353
- routeThreadKey,
7354
- target.selection.instanceId,
7355
- target.selection.model,
7356
- ]);
7357
- const uncertainThreadId = uncertainMultipleSubmissionsRef.current.get(retryKey);
7358
- const targetThreadId = uncertainThreadId ?? newThreadId();
7359
- let requestMayHaveStarted = false;
7360
- try {
7361
- if (uncertainThreadId) {
7362
- throw new Error(
7363
- "The previous request may have started. Open its thread to check before sending again.",
7364
- );
7365
- }
7366
- const supportsInlineMessageContext =
7367
- appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment
7368
- .capabilities.inlineMessageContext === true;
7369
- requestMayHaveStarted = true;
7370
- const result = await startThreadTurn({
7371
- environmentId,
7372
- input: {
7373
- threadId: targetThreadId,
7374
- message: {
7375
- messageId: newMessageId(),
7376
- role: "user",
7377
- text:
7378
- context && !supportsInlineMessageContext
7379
- ? serializeLegacyContextMessage({
7380
- text: target.text,
7381
- records: context.records,
7382
- })
7383
- : target.text,
7384
- attachments,
7385
- ...(context && supportsInlineMessageContext ? { context } : {}),
7386
- },
7387
- modelSelection: target.selection,
7388
- titleSeed: title,
7389
- runtimeMode,
7390
- interactionMode: target.interactionMode,
7391
- bootstrap: {
7392
- createThread: {
7393
- projectId: activeProject.id,
7394
- title,
7395
- modelSelection: target.selection,
7396
- runtimeMode,
7397
- interactionMode: target.interactionMode,
7398
- branch: activeThreadBranch,
7399
- worktreePath: null,
7400
- createdAt: messageCreatedAt,
7411
+ const started = await startFanoutThread({
7412
+ retryKey: JSON.stringify([
7413
+ routeThreadKey,
7414
+ target.selection.instanceId,
7415
+ target.selection.model,
7416
+ ]),
7417
+ model: target.selection.model,
7418
+ uncertainSubmissions: uncertainMultipleSubmissionsRef.current,
7419
+ start: (targetThreadId) => {
7420
+ const supportsInlineMessageContext =
7421
+ appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment
7422
+ .capabilities.inlineMessageContext === true;
7423
+ return startThreadTurn({
7424
+ environmentId,
7425
+ input: {
7426
+ threadId: targetThreadId,
7427
+ message: {
7428
+ messageId: newMessageId(),
7429
+ role: "user",
7430
+ text:
7431
+ context && !supportsInlineMessageContext
7432
+ ? serializeLegacyContextMessage({
7433
+ text: target.text,
7434
+ records: context.records,
7435
+ })
7436
+ : target.text,
7437
+ attachments,
7438
+ ...(context && supportsInlineMessageContext ? { context } : {}),
7439
},
7402
- prepareWorktree: {
7403
- projectCwd: activeProject.workspaceRoot,
7404
- baseBranch: activeThreadBranch!,
7405
- requireWorktree: true,
7406
- ...(startFromOrigin ? { startFromOrigin: true } : {}),
7440
+ modelSelection: target.selection,
7441
+ titleSeed: title,
7442
+ runtimeMode,
7443
+ interactionMode: target.interactionMode,
7444
+ bootstrap: {
7445
+ createThread: {
7446
+ projectId: activeProject.id,
7447
+ title,
7448
+ modelSelection: target.selection,
7449
+ runtimeMode,
7450
+ interactionMode: target.interactionMode,
7451
+ branch: activeThreadBranch,
7452
+ worktreePath: null,
7453
+ createdAt: messageCreatedAt,
7454
+ },
7455
+ prepareWorktree: {
7456
+ projectCwd: activeProject.workspaceRoot,
7457
+ baseBranch: activeThreadBranch!,
7458
+ requireWorktree: true,
7459
+ ...(startFromOrigin ? { startFromOrigin: true } : {}),
7460
+ },
7461
+ runSetupScript: true,
7462
},
7408
- runSetupScript: true,
7463
+ createdAt: messageCreatedAt,
7464
},
7410
- createdAt: messageCreatedAt,
7411
- },
7412
- });
7413
- if (result._tag === "Failure") {
7414
- const error = squashAtomCommandFailure(result);
7415
- if (wasBootstrapThreadDeleted(error) || wasBootstrapThreadNotCreated(error)) {
7416
- requestMayHaveStarted = false;
7417
- }
7418
- throw error;
7419
- }
7420
- startedCount += 1;
7421
- } catch (error) {
7422
- if (requestMayHaveStarted && !uncertainMultipleSubmissionsRef.current.has(retryKey)) {
7423
- uncertainMultipleSubmissionsRef.current.set(retryKey, targetThreadId);
7424
- }
7425
- failedSelections.push(target.selection);
7426
- const retainedThreadId = uncertainMultipleSubmissionsRef.current.get(retryKey);
7427
- const failureToastId = toastManager.add(
7428
- stackedThreadToast({
7429
- type: "error",
7430
- title: `Could not start ${target.selection.model}`,
7431
- description: error instanceof Error ? error.message : "Failed to send message.",
7432
- ...(retainedThreadId
7433
- ? {
7434
- timeout: 0,
7435
- data: {
7436
- secondaryActionProps: {
7437
- children: "Allow retry",
7438
- onClick: () => {
7439
- void readLocalApi()
7440
- ?.dialogs.confirm(
7441
- "The previous request may already be running. Check its thread first. Allow another send that could create a duplicate thread?",
7442
- )
7443
- .then(
7444
- (confirmed) => {
7445
- if (
7446
- confirmed &&
7447
- uncertainMultipleSubmissionsRef.current.get(retryKey) ===
7448
- retainedThreadId
7449
- ) {
7450
- uncertainMultipleSubmissionsRef.current.delete(retryKey);
7451
- toastManager.close(failureToastId);
7452
- }
7453
- },
7454
- () => undefined,
7455
- );
7456
- },
7457
- },
7458
- },
7459
- actionProps: {
7460
- children: "Open thread",
7461
- onClick: () => {
7462
- void navigate({
7463
- to: "/$environmentId/$threadId",
7464
- params: buildThreadRouteParams(
7465
- scopeThreadRef(environmentId, retainedThreadId),
7466
- ),
7467
- });
7468
- },
7469
- },
7470
- }
7471
- : {}),
7465
+ });
7466
+ },
7467
+ openThread: (threadId) =>
7468
+ void navigate({
7469
+ to: "/$environmentId/$threadId",
7470
+ params: buildThreadRouteParams(scopeThreadRef(environmentId, threadId)),
7471
}),
7473
- );
7474
- }
7472
+ });
7473
+ if (started) startedCount += 1;
7474
+ else failedSelections.push(target.selection);
7475
}),
7476
);
7477
sendInFlightRef.current = false;