@devries-cameron20 / t3code-1 / commits / 0e95babaf5
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

perf(web): let the React Compiler compile ChatView (#20379)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 16, 2026 at 17:39 UTC 0e95babaf52c0b5625b6a081309f85c0d8b78356
9 files changed +631 -558
apps/web/reactCompiledFiles.ts new
+25
@@ -0,0 +1,25 @@
1 +/**
2 + * Web files the React Compiler must compile, relative to the repository root. Add a
3 + * file once it compiles cleanly. The root lint config makes the compiler's bailout
4 + * rules errors for these files, and src/reactCompiledFiles.test.ts compiles each one
5 + * to catch the bailouts lint cannot see.
6 + */
7 +export const REACT_COMPILED_FILES = [
8 + "apps/web/src/components/PersistentThreadTerminals.tsx",
9 + "apps/web/src/components/chat/usePendingThreadRequests.ts",
10 + "apps/web/src/components/chat/useQueuedRunEdit.ts",
11 + "apps/web/src/components/chat/useUsageLimitsPanel.ts",
12 + "apps/web/src/components/chat/useWorktreeSetup.ts",
13 + "apps/web/src/components/preview/useAgentOpenedPreviews.ts",
14 + "apps/web/src/components/pullRequest/useThreadLinkedPullRequest.ts",
15 + "apps/web/src/components/terminal/**",
16 + "apps/web/src/hooks/useIncrementalTimelineEntries.ts",
17 + "apps/web/src/hooks/useProactivePanels.ts",
18 + "apps/web/src/hooks/useRightPanelSurfaceClose.ts",
19 +] as const;
20 +
21 +/**
22 + * Files the compiler already compiles that still carry manual memoization or
23 + * effect-driven state, so only the compile test covers them for now.
24 + */
25 +export const REACT_COMPILED_FILES_PENDING_LINT = ["apps/web/src/components/ChatView.tsx"] as const;
apps/web/src/components/ChatView.tsx
+495 -526
@@ -173,9 +173,7 @@ import {
173 } from "../composer-logic";
174 import {
175 derivePhase,
176 - deriveTimelineEntriesFromVisibleTurnItemsWithState,
176 selectHandoffImageResources,
178 - type TimelineEntriesProjection,
177 deriveActivePlanState,
178 deriveActiveWorkStartedAt,
179 deriveCanInterruptRunningThread,
@@ -460,6 +458,7 @@ import {
458 import { QueuedRunsControl, type QueuedRunsControlHandle } from "./chat/QueuedRunsControl";
459 import { useThreadLinkedPullRequest } from "./pullRequest/useThreadLinkedPullRequest";
460 import { useProactivePanels } from "../hooks/useProactivePanels";
461 +import { useIncrementalTimelineEntries } from "../hooks/useIncrementalTimelineEntries";
462 import { useRightPanelSurfaceClose } from "../hooks/useRightPanelSurfaceClose";
463 import { useAgentOpenedPreviews } from "./preview/useAgentOpenedPreviews";
464 import type { ComposerBannerStackItem } from "./chat/ComposerBannerStack";
@@ -601,16 +600,9 @@ function useDraftHeroLayoutTransition(
600 const previousStateRef = useRef(isDraftHeroState);
601 const previousComposerRectRef = useRef<DOMRect | null>(null);
602 const animationRef = useRef<Animation | null>(null);
604 - const attachTransitionGroupRef = (element: HTMLDivElement | null) => {
605 - transitionGroupRef.current = element;
606 - };
607 - const attachComposerAnchorRef = (element: HTMLDivElement | null) => {
608 - composerAnchorRef.current = element;
609 - };
610 -
611 - const captureComposerRect = () => {
603 + const captureComposerRect = useStableCallback(() => {
604 previousComposerRectRef.current = composerAnchorRef.current?.getBoundingClientRect() ?? null;
613 - };
605 + });
606
607 useLayoutEffect(() => {
608 const transitionGroup = transitionGroupRef.current;
@@ -658,11 +650,7 @@ function useDraftHeroLayoutTransition(
650 previousComposerRectRef.current = nextComposerRect;
651 }, [animationDurationMs, animationsActive, isDraftHeroState]);
652
661 - return {
662 - transitionGroupRef: attachTransitionGroupRef,
663 - composerAnchorRef: attachComposerAnchorRef,
664 - captureComposerRect,
665 - } as const;
653 + return { transitionGroupRef, composerAnchorRef, captureComposerRect } as const;
654 }
655
656 const PreviewPanel = lazy(() =>
@@ -753,13 +741,26 @@ function pasteTextToFocusComposer(event: ClipboardEvent): string | null {
741 return text.length > 0 ? text : null;
742 }
743
756 -const draftFanoutStateAtom = Atom.family((_routeKey: string) =>
757 - Atom.make({
758 - selections: null as ReadonlyArray<ModelSelection> | null,
759 - sendInFlight: { current: false },
760 - uncertainSubmissions: { current: new Map<string, ThreadId>() },
761 - }).pipe(Atom.keepAlive),
744 +// Kept per route so a send in flight, and the multiple-model selections, survive
745 +// ChatView remounting while the user navigates.
746 +const draftFanoutSelectionsAtom = Atom.family((_routeKey: string) =>
747 + Atom.make<ReadonlyArray<ModelSelection> | null>(null).pipe(Atom.keepAlive),
748 );
749 +const draftSendStateByRouteKey = new Map<
750 + string,
751 + {
752 + readonly sendInFlight: { current: boolean };
753 + readonly uncertainSubmissions: { current: Map<string, ThreadId> };
754 + }
755 +>();
756 +function draftSendState(routeKey: string) {
757 + let state = draftSendStateByRouteKey.get(routeKey);
758 + if (!state) {
759 + state = { sendInFlight: { current: false }, uncertainSubmissions: { current: new Map() } };
760 + draftSendStateByRouteKey.set(routeKey, state);
761 + }
762 + return state;
763 +}
764
765 /**
766 * Starts one thread of a multiple-model send. A request that may have
@@ -842,6 +843,104 @@ async function startFanoutThread(input: {
843 }
844 }
845
846 +/**
847 + * Reverts the thread to before `message` and puts that message's text and
848 + * attachments back in the composer draft. Returns the restored prompt, or the
849 + * error to show; on error the draft is untouched.
850 + */
851 +async function rewindToMessage(input: {
852 + readonly message: ChatMessage;
853 + readonly environmentId: EnvironmentId;
854 + readonly routeThreadRef: ScopedThreadRef;
855 + readonly threadId: ThreadId;
856 + readonly turnCount: number;
857 + readonly restoreFiles: boolean;
858 + readonly draftTarget: ScopedThreadRef | DraftId;
859 + readonly composerHasPendingAttachments: boolean;
860 + readonly createAssetUrl: Parameters<
861 + typeof prepareRevertedMessageAttachments
862 + >[0]["createAssetUrl"];
863 + readonly revertThreadCheckpoint: (value: {
864 + environmentId: EnvironmentId;
865 + input: { commandId: CommandId; threadId: ThreadId; turnCount: number; restoreFiles: boolean };
866 + }) => Promise<AtomCommandResult<unknown, unknown>>;
867 +}): Promise<
868 + | { readonly error: string; readonly prompt?: never }
869 + | { readonly error: null; readonly prompt: string }
870 +> {
871 + const { message, environmentId, draftTarget } = input;
872 + try {
873 + if (input.composerHasPendingAttachments) {
874 + throw new Error("Wait for attachments to finish preparing before rewinding.");
875 + }
876 + const connection = readPreparedConnection(environmentId);
877 + if (!connection) throw new Error("The environment is not connected.");
878 + const files = await prepareRevertedMessageAttachments({
879 + message,
880 + environmentId,
881 + httpBaseUrl: connection.httpBaseUrl,
882 + createAssetUrl: input.createAssetUrl,
883 + });
884 + const store = useComposerDraftStore.getState();
885 + const draft = store.getComposerDraft(draftTarget);
886 + if (
887 + (draft?.images.length ?? 0) + (draft?.files.length ?? 0) + files.length >
888 + PROVIDER_SEND_TURN_MAX_ATTACHMENTS
889 + ) {
890 + throw new Error("Make room for this message's attachments in the composer before rewinding.");
891 + }
892 + const commandId = CommandId.make(randomUUID());
893 + await waitForRevertedMessage(
894 + input.routeThreadRef,
895 + message.id,
896 + input.turnCount,
897 + commandId,
898 + async () => {
899 + const result = await input.revertThreadCheckpoint({
900 + environmentId,
901 + input: {
902 + commandId,
903 + threadId: input.threadId,
904 + turnCount: input.turnCount,
905 + restoreFiles: input.restoreFiles,
906 + },
907 + });
908 + if (result._tag === "Failure") throw squashAtomCommandFailure(result);
909 + },
910 + );
911 + const currentPrompt = store.getComposerDraft(draftTarget)?.prompt ?? "";
912 + const restoredPrompt = recallableComposerPrompt(message.text);
913 + const nextPrompt =
914 + restoredPrompt.length === 0
915 + ? currentPrompt
916 + : currentPrompt.length > 0
917 + ? `${currentPrompt}\n\n${restoredPrompt}`
918 + : restoredPrompt;
919 + store.setPrompt(draftTarget, nextPrompt);
920 + const images: ComposerImageAttachment[] = [];
921 + const restoredFiles: ComposerFileAttachment[] = [];
922 + files.forEach((file, index) => {
923 + const attachment = {
924 + id: randomUUID(),
925 + name: file.name,
926 + mimeType: file.type,
927 + sizeBytes: file.size,
928 + file,
929 + };
930 + if (message.attachments?.[index]?.type === "image") {
931 + images.push({ ...attachment, type: "image", previewUrl: URL.createObjectURL(file) });
932 + } else {
933 + restoredFiles.push({ ...attachment, type: "file" });
934 + }
935 + });
936 + store.addImages(draftTarget, images, { allowDuplicates: true });
937 + store.addFiles(draftTarget, restoredFiles, { allowDuplicates: true });
938 + return { error: null, prompt: nextPrompt };
939 + } catch (error) {
940 + return { error: error instanceof Error ? error.message : "Failed to revert thread state." };
941 + }
942 +}
943 +
944 function formatOutgoingPrompt(params: {
945 provider: ProviderDriverKind;
946 model: string | null;
@@ -1338,7 +1437,9 @@ export default function ChatView(props: ChatViewProps) {
1437 (submission) => submission.status === "uploading",
1438 );
1439 const optimisticUserMessagesRef = useRef(optimisticUserMessages);
1341 - optimisticUserMessagesRef.current = optimisticUserMessages;
1440 + useLayoutEffect(() => {
1441 + optimisticUserMessagesRef.current = optimisticUserMessages;
1442 + });
1443 const [localDraftErrorsByDraftId, setLocalDraftErrorsByDraftId] = useState<
1444 Record<string, LocalThreadErrorEntry>
1445 >({});
@@ -1400,27 +1501,24 @@ export default function ChatView(props: ChatViewProps) {
1501 const [timelineOverflows, setTimelineOverflows] = useState(false);
1502 const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
1503 const attachmentPreviewPromotionInFlightByMessageIdRef = useRef<Record<string, true>>({});
1403 - const fanoutStateAtom = draftFanoutStateAtom(routeThreadKey);
1404 - const fanoutState = useAtomValue(fanoutStateAtom);
1405 - const sendInFlightRef = fanoutState.sendInFlight;
1504 + const fanoutSelectionsAtom = draftFanoutSelectionsAtom(routeThreadKey);
1505 + const { sendInFlight: sendInFlightRef, uncertainSubmissions: uncertainMultipleSubmissionsRef } =
1506 + draftSendState(routeThreadKey);
1507 const [resumingThreadKeys, setResumingThreadKeys] = useState<ReadonlySet<string>>(
1508 () => new Set(),
1509 );
1510 const isResuming = resumingThreadKeys.has(routeThreadKey);
1511 const composerSendGenerationRef = useRef(0);
1411 - const multipleModelSelections = fanoutState.selections;
1512 + const multipleModelSelections = useAtomValue(fanoutSelectionsAtom);
1513 const setMultipleModelSelections = (
1514 selections: SetStateAction<ReadonlyArray<ModelSelection> | null>,
1515 ) => {
1415 - appAtomRegistry.update(fanoutStateAtom, (current) => ({
1416 - ...current,
1417 - selections: typeof selections === "function" ? selections(current.selections) : selections,
1418 - }));
1516 + appAtomRegistry.update(fanoutSelectionsAtom, (current) =>
1517 + typeof selections === "function" ? selections(current) : selections,
1518 + );
1519 };
1520 const setMultipleModelSelectionsStable = useStableCallback(setMultipleModelSelections);
1421 - const multipleModelSelectionsRef = useRef(multipleModelSelections);
1422 - multipleModelSelectionsRef.current = multipleModelSelections;
1423 - const uncertainMultipleSubmissionsRef = fanoutState.uncertainSubmissions;
1521 + const readMultipleModelSelections = () => appAtomRegistry.get(fanoutSelectionsAtom);
1522 const environmentUnavailableSendToastSlotRef = useRef(0);
1523 const feedbackUploadsInFlightRef = useRef(new Set<string>());
1524 const terminalUiOpenByThreadRef = useRef<Record<string, boolean>>({});
@@ -1857,11 +1955,12 @@ export default function ChatView(props: ChatViewProps) {
1955 }, [activeActivityRun, activePlan, activeRuntime]);
1956 const activeComposerTaskSteps =
1957 activeComposerTasksProgress && activePlan ? activePlan.steps : null;
1860 - const activeProjectRef = useMemo(
1861 - () =>
1862 - activeThread ? scopeProjectRef(activeThread.environmentId, activeThread.projectId) : null,
1863 - [activeThread?.environmentId, activeThread?.projectId],
1864 - );
1958 + const activeThreadEnvironmentId = activeThread?.environmentId;
1959 + const activeThreadProjectId = activeThread?.projectId;
1960 + const activeProjectRef =
1961 + activeThreadEnvironmentId !== undefined && activeThreadProjectId !== undefined
1962 + ? scopeProjectRef(activeThreadEnvironmentId, activeThreadProjectId)
1963 + : null;
1964 const activeProject = useProject(activeProjectRef);
1965 const activeProjectSettings = useMemo(
1966 () => resolveProjectSettings(settings, activeProject?.id ?? null, activeProject ?? undefined),
@@ -2591,29 +2690,18 @@ export default function ChatView(props: ChatViewProps) {
2690 ),
2691 [providerStatuses, settings, activeProject?.id],
2692 );
2594 - const { selectedProviderEntry, requestedDriverKind } = useMemo(
2595 - () =>
2596 - resolveComposerProviderSelection({
2597 - entries: providerInstanceEntries,
2598 - candidateInstanceIds: [
2599 - selectedProviderByThreadId,
2600 - activeRuntime?.providerInstanceId,
2601 - activeThread?.modelSelection.instanceId,
2602 - activeProjectDefaultModelSelection?.instanceId,
2603 - ],
2604 - lockedProvider,
2605 - lockedInstanceId:
2606 - activeRuntime?.providerInstanceId ?? activeThread?.modelSelection.instanceId,
2607 - }),
2608 - [
2609 - activeProjectDefaultModelSelection?.instanceId,
2610 - activeThread?.modelSelection.instanceId,
2611 - activeRuntime?.providerInstanceId,
2612 - lockedProvider,
2613 - providerInstanceEntries,
2693 + const activeThreadModelInstanceId = activeThread?.modelSelection.instanceId;
2694 + const { selectedProviderEntry, requestedDriverKind } = resolveComposerProviderSelection({
2695 + entries: providerInstanceEntries,
2696 + candidateInstanceIds: [
2697 selectedProviderByThreadId,
2698 + activeRuntime?.providerInstanceId,
2699 + activeThreadModelInstanceId,
2700 + activeProjectDefaultModelSelection?.instanceId,
2701 ],
2616 - );
2702 + lockedProvider,
2703 + lockedInstanceId: activeRuntime?.providerInstanceId ?? activeThreadModelInstanceId,
2704 + });
2705 const selectedProvider = selectedProviderEntry?.driverKind ?? requestedDriverKind;
2706 const activeProviderInstanceId = selectedProviderEntry?.instanceId ?? null;
2707 const activeProviderStatus = selectedProviderEntry?.snapshot ?? null;
@@ -2631,20 +2719,19 @@ export default function ChatView(props: ChatViewProps) {
2719 conversationProviderStatus !== null &&
2720 conversationProviderStatus.supportsConversationRollback !== false;
2721 const phase = derivePhase(activeRuntime);
2634 - const setThreadError = useMemo(
2635 - () =>
2636 - makeThreadErrorSetter({
2637 - routeThreadRef,
2638 - routeThreadKey,
2639 - draftId,
2640 - serverThreadRef: serverThread
2641 - ? { threadId: serverThread.id, environmentId: serverThread.environmentId }
2642 - : null,
2643 - setLocalServerErrorsByThreadKey,
2644 - setLocalDraftErrorsByDraftId,
2645 - }),
2646 - [draftId, routeThreadKey, routeThreadRef, serverThread?.id, serverThread?.environmentId],
2647 - );
2722 + const serverThreadId = serverThread?.id;
2723 + const serverThreadEnvironmentId = serverThread?.environmentId;
2724 + const setThreadError = makeThreadErrorSetter({
2725 + routeThreadRef,
2726 + routeThreadKey,
2727 + draftId,
2728 + serverThreadRef:
2729 + serverThreadId !== undefined && serverThreadEnvironmentId !== undefined
2730 + ? { threadId: serverThreadId, environmentId: serverThreadEnvironmentId }
2731 + : null,
2732 + setLocalServerErrorsByThreadKey,
2733 + setLocalDraftErrorsByDraftId,
2734 + });
2735 const {
2736 pendingApprovals,
2737 pendingUserInputs,
@@ -3045,38 +3132,19 @@ export default function ChatView(props: ChatViewProps) {
3132 ),
3133 [feedbackSubmissions],
3134 );
3048 - const timelineProjectionRef = useRef<{
3049 - readonly threadKey: string | null;
3050 - readonly projection: TimelineEntriesProjection;
3051 - } | null>(null);
3052 - const serverTimelineEntries = useMemo(() => {
3053 - const previous = timelineProjectionRef.current;
3054 - const projection = deriveTimelineEntriesFromVisibleTurnItemsWithState(
3055 - {
3056 - visibleTurnItems: serverVisibleTurnItems,
3057 - optimisticMessages: optimisticUserMessages,
3058 - anchoredMessages: anchoredTimelineMessages,
3059 - attachmentUrlById: timelineAttachmentUrlById,
3060 - ...(serverProjection === null
3061 - ? {}
3062 - : {
3063 - attempts: serverProjection.attempts,
3064 - nodes: serverProjection.nodes,
3065 - plans: serverProjection.plans,
3066 - }),
3067 - },
3068 - previous?.threadKey === activeThreadKey ? previous.projection : null,
3069 - );
3070 - timelineProjectionRef.current = { threadKey: activeThreadKey, projection };
3071 - return projection.entries;
3072 - }, [
3073 - activeThreadKey,
3074 - anchoredTimelineMessages,
3075 - optimisticUserMessages,
3076 - serverVisibleTurnItems,
3077 - serverProjection,
3078 - timelineAttachmentUrlById,
3079 - ]);
3135 + const serverTimelineEntries = useIncrementalTimelineEntries(activeThreadKey, {
3136 + visibleTurnItems: serverVisibleTurnItems,
3137 + optimisticMessages: optimisticUserMessages,
3138 + anchoredMessages: anchoredTimelineMessages,
3139 + attachmentUrlById: timelineAttachmentUrlById,
3140 + ...(serverProjection === null
3141 + ? {}
3142 + : {
3143 + attempts: serverProjection.attempts,
3144 + nodes: serverProjection.nodes,
3145 + plans: serverProjection.plans,
3146 + }),
3147 + });
3148 const draftTimelineEntries = useMemo(
3149 () =>
3150 optimisticUserMessages.map(
@@ -3141,12 +3209,15 @@ export default function ChatView(props: ChatViewProps) {
3209 backgroundSubmissionPending,
3210 hasWorktreeSetupCard: worktreeSetup !== null,
3211 });
3144 - const draftHeroTransition = useDraftHeroLayoutTransition(
3212 + const {
3213 + transitionGroupRef: draftHeroTransitionGroupRef,
3214 + composerAnchorRef: draftHeroComposerAnchorRef,
3215 + captureComposerRect: captureDraftHeroComposerRect,
3216 + } = useDraftHeroLayoutTransition(
3217 isDraftHeroState,
3218 panelAnimationsActive,
3219 panelAnimationDurationMs,
3220 );
3149 - const captureDraftHeroComposerRect = draftHeroTransition.captureComposerRect;
3221 const { turnDiffSummaries } = useTurnDiffSummaries(serverProjection);
3222
3223 /**
@@ -3211,25 +3282,14 @@ export default function ChatView(props: ChatViewProps) {
3282 availableEditors,
3283 openInCwd: gitCwd,
3284 });
3214 - const manualCompactionProviderAvailable = useMemo(
3215 - () =>
3216 - hasAvailableCompactionProvider({
3217 - providers: providerInstanceEntries,
3218 - driverKind: selectedProvider,
3219 - instanceId: activeProviderInstanceId,
3220 - lockedInstanceId: lockedProvider
3221 - ? (activeRuntime?.providerInstanceId ?? activeThread?.modelSelection.instanceId ?? null)
3222 - : null,
3223 - }),
3224 - [
3225 - activeProviderInstanceId,
3226 - activeThread?.modelSelection.instanceId,
3227 - activeRuntime?.providerInstanceId,
3228 - lockedProvider,
3229 - providerInstanceEntries,
3230 - selectedProvider,
3231 - ],
3232 - );
3285 + const manualCompactionProviderAvailable = hasAvailableCompactionProvider({
3286 + providers: providerInstanceEntries,
3287 + driverKind: selectedProvider,
3288 + instanceId: activeProviderInstanceId,
3289 + lockedInstanceId: lockedProvider
3290 + ? (activeRuntime?.providerInstanceId ?? activeThread?.modelSelection.instanceId ?? null)
3291 + : null,
3292 + });
3293 const [resumeCompactionPermanentlyDismissed, setResumeCompactionPermanentlyDismissed] =
3294 useLocalStorage(
3295 `t3code:resume-compaction-dismissed:${environmentId}:${activeProviderInstanceId ?? "claudeAgent"}`,
@@ -3390,45 +3450,34 @@ export default function ChatView(props: ChatViewProps) {
3450 const onToggleDiffStable = useStableCallback(onToggleDiff);
3451
3452 const needsLoadBalancing = automaticEnvironment && !draftThread?.loadBalancedEnvironmentId;
3393 - const loadBalancingCandidates = useMemo(
3394 - () =>
3395 - needsLoadBalancing
3396 - ? logicalProjectEnvironments
3397 - .filter((candidate) => {
3398 - const environment = environmentById.get(candidate.environmentId);
3399 - return (
3400 - environment?.connection.phase === "connected" &&
3401 - (loadBalancingSettings.loadBalancingWeights[candidate.environmentId] ?? 50) > 0 &&
3402 - environment.serverConfig?.providers.some(
3403 - (provider) =>
3404 - (activeProviderInstanceId === null ||
3405 - provider.instanceId === activeProviderInstanceId) &&
3406 - provider.driver === selectedProvider &&
3407 - (environment.serverConfig?.settings
3408 - ? resolveProjectProviderInstanceEnabled(
3409 - environment.serverConfig.settings,
3410 - candidate.projectId,
3411 - provider.instanceId,
3412 - )
3413 - : provider.enabled) &&
3414 - provider.installed &&
3415 - provider.status !== "error" &&
3416 - provider.auth.status !== "unauthenticated" &&
3417 - provider.availability !== "unavailable",
3418 - )
3419 - );
3420 - })
3421 - .map((candidate) => candidate.environmentId)
3422 - : [],
3423 - [
3424 - needsLoadBalancing,
3425 - logicalProjectEnvironments,
3426 - environmentById,
3427 - loadBalancingSettings.loadBalancingWeights,
3428 - activeProviderInstanceId,
3429 - selectedProvider,
3430 - ],
3431 - );
3453 + const loadBalancingCandidates = needsLoadBalancing
3454 + ? logicalProjectEnvironments
3455 + .filter((candidate) => {
3456 + const environment = environmentById.get(candidate.environmentId);
3457 + return (
3458 + environment?.connection.phase === "connected" &&
3459 + (loadBalancingSettings.loadBalancingWeights[candidate.environmentId] ?? 50) > 0 &&
3460 + environment.serverConfig?.providers.some(
3461 + (provider) =>
3462 + (activeProviderInstanceId === null ||
3463 + provider.instanceId === activeProviderInstanceId) &&
3464 + provider.driver === selectedProvider &&
3465 + (environment.serverConfig?.settings
3466 + ? resolveProjectProviderInstanceEnabled(
3467 + environment.serverConfig.settings,
3468 + candidate.projectId,
3469 + provider.instanceId,
3470 + )
3471 + : provider.enabled) &&
3472 + provider.installed &&
3473 + provider.status !== "error" &&
3474 + provider.auth.status !== "unauthenticated" &&
3475 + provider.availability !== "unavailable",
3476 + )
3477 + );
3478 + })
3479 + .map((candidate) => candidate.environmentId)
3480 + : [];
3481 const loadBalancing = useLoadBalancedEnvironment(
3482 loadBalancingCandidates,
3483 loadBalancingSettings.loadBalancingWeights,
@@ -5289,24 +5338,22 @@ export default function ChatView(props: ChatViewProps) {
5338 return;
5339 const threadKey = scopedThreadKey(activeThreadRef);
5340 setUnsettlingThreadKey(threadKey);
5292 - try {
5293 - const result = await unsettleThreadMutation({
5294 - environmentId: activeThreadRef.environmentId,
5295 - input: { threadId: activeThreadRef.threadId, reason: "user" },
5296 - });
5297 - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
5298 - const error = squashAtomCommandFailure(result);
5299 - toastManager.add(
5300 - stackedThreadToast({
5301 - type: "error",
5302 - title: "Failed to un-settle thread",
5303 - description: error instanceof Error ? error.message : "An error occurred.",
5304 - }),
5305 - );
5306 - }
5307 - } finally {
5308 - setUnsettlingThreadKey((current) => (current === threadKey ? null : current));
5341 + // Commands settle into a result, so this always runs.
5342 + const result = await unsettleThreadMutation({
5343 + environmentId: activeThreadRef.environmentId,
5344 + input: { threadId: activeThreadRef.threadId, reason: "user" },
5345 + });
5346 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
5347 + const error = squashAtomCommandFailure(result);
5348 + toastManager.add(
5349 + stackedThreadToast({
5350 + type: "error",
5351 + title: "Failed to un-settle thread",
5352 + description: error instanceof Error ? error.message : "An error occurred.",
5353 + }),
5354 + );
5355 }
5356 + setUnsettlingThreadKey((current) => (current === threadKey ? null : current));
5357 };
5358 const handleUnsettleActiveThreadStable = useStableCallback(handleUnsettleActiveThread);
5359 const unsnoozeThreadMutation = useOrchestrationCommand(threadEnvironment.unsnooze, {
@@ -5322,38 +5369,36 @@ export default function ChatView(props: ChatViewProps) {
5369 return;
5370 const threadKey = scopedThreadKey(activeThreadRef);
5371 setUnsnoozingThreadKey(threadKey);
5325 - try {
5326 - const recovery = activeThreadShell?.limitRecovery;
5327 - const recoveryOwnsSnooze =
5328 - recovery?.snooze === true &&
5329 - recovery.runId === activeThreadShell?.latestRun?.runId &&
5330 - activeThreadShell?.snoozedUntil != null &&
5331 - Date.parse(activeThreadShell.snoozedUntil) === Date.parse(recovery.resetAt);
5332 - const result = recoveryOwnsSnooze
5333 - ? await updateThreadMetadata({
5334 - environmentId: activeThreadRef.environmentId,
5335 - input: {
5336 - threadId: activeThreadRef.threadId,
5337 - limitRecovery: { runId: recovery.runId, resetAt: recovery.resetAt, snooze: false },
5338 - },
5339 - })
5340 - : await unsnoozeThreadMutation({
5341 - environmentId: activeThreadRef.environmentId,
5342 - input: { threadId: activeThreadRef.threadId, reason: "user" },
5343 - });
5344 - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
5345 - const error = squashAtomCommandFailure(result);
5346 - toastManager.add(
5347 - stackedThreadToast({
5348 - type: "error",
5349 - title: "Failed to wake thread",
5350 - description: error instanceof Error ? error.message : "An error occurred.",
5351 - }),
5352 - );
5353 - }
5354 - } finally {
5355 - setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));
5372 + // Commands settle into a result, so this always runs.
5373 + const recovery = activeThreadShell?.limitRecovery;
5374 + const recoveryOwnsSnooze =
5375 + recovery?.snooze === true &&
5376 + recovery.runId === activeThreadShell?.latestRun?.runId &&
5377 + activeThreadShell?.snoozedUntil != null &&
5378 + Date.parse(activeThreadShell.snoozedUntil) === Date.parse(recovery.resetAt);
5379 + const result = recoveryOwnsSnooze
5380 + ? await updateThreadMetadata({
5381 + environmentId: activeThreadRef.environmentId,
5382 + input: {
5383 + threadId: activeThreadRef.threadId,
5384 + limitRecovery: { runId: recovery.runId, resetAt: recovery.resetAt, snooze: false },
5385 + },
5386 + })
5387 + : await unsnoozeThreadMutation({
5388 + environmentId: activeThreadRef.environmentId,
5389 + input: { threadId: activeThreadRef.threadId, reason: "user" },
5390 + });
5391 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
5392 + const error = squashAtomCommandFailure(result);
5393 + toastManager.add(
5394 + stackedThreadToast({
5395 + type: "error",
5396 + title: "Failed to wake thread",
5397 + description: error instanceof Error ? error.message : "An error occurred.",
5398 + }),
5399 + );
5400 }
5401 + setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));
5402 };
5403 const handleUnsnoozeActiveThreadStable = useStableCallback(handleUnsnoozeActiveThread);
5404 const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);
@@ -5541,45 +5586,41 @@ export default function ChatView(props: ChatViewProps) {
5586 },
5587 ]);
5588 scrollToEnd();
5544 - try {
5545 - const settingsResult = await persistThreadSettingsForNextTurn({
5546 - threadId,
5547 - createdAt,
5548 - ...(localCheckoutBranchMismatch
5549 - ? { branch: localCheckoutBranchMismatch.currentBranch }
5550 - : {}),
5551 - runtimeMode,
5552 - interactionMode: context.interactionMode,
5553 - });
5554 - const result =
5555 - settingsResult._tag === "Failure"
5556 - ? settingsResult
5557 - : await startThreadTurn({
5558 - environmentId,
5559 - input: {
5560 - threadId,
5561 - message: { messageId, role: "user", text, attachments: [] },
5562 - modelSelection: context.selectedModelSelection,
5563 - runtimeMode,
5564 - interactionMode: context.interactionMode,
5565 - createdAt,
5566 - },
5567 - });
5568 - if (result._tag === "Failure") {
5569 - setOptimisticUserMessages((messages) =>
5570 - messages.filter((message) => message.id !== messageId),
5571 - );
5572 - resetLocalDispatch();
5573 - if (!isAtomCommandInterrupted(result)) {
5574 - const error = squashAtomCommandFailure(result);
5575 - setThreadError(threadId, error instanceof Error ? error.message : failureMessage);
5576 - }
5577 - } else {
5578 - clearUsageLimitsFor(routeThreadKey);
5589 + // Commands settle into a result, so this always runs.
5590 + const settingsResult = await persistThreadSettingsForNextTurn({
5591 + threadId,
5592 + createdAt,
5593 + ...(localCheckoutBranchMismatch ? { branch: localCheckoutBranchMismatch.currentBranch } : {}),
5594 + runtimeMode,
5595 + interactionMode: context.interactionMode,
5596 + });
5597 + const result =
5598 + settingsResult._tag === "Failure"
5599 + ? settingsResult
5600 + : await startThreadTurn({
5601 + environmentId,
5602 + input: {
5603 + threadId,
5604 + message: { messageId, role: "user", text, attachments: [] },
5605 + modelSelection: context.selectedModelSelection,
5606 + runtimeMode,
5607 + interactionMode: context.interactionMode,
5608 + createdAt,
5609 + },
5610 + });
5611 + if (result._tag === "Failure") {
5612 + setOptimisticUserMessages((messages) =>
5613 + messages.filter((message) => message.id !== messageId),
5614 + );
5615 + resetLocalDispatch();
5616 + if (!isAtomCommandInterrupted(result)) {
5617 + const error = squashAtomCommandFailure(result);
5618 + setThreadError(threadId, error instanceof Error ? error.message : failureMessage);
5619 }
5580 - } finally {
5581 - sendInFlightRef.current = false;
5620 + } else {
5621 + clearUsageLimitsFor(routeThreadKey);
5622 }
5623 + sendInFlightRef.current = false;
5624 };
5625 const sendStandaloneCommandStable = useStableCallback(sendStandaloneCommand);
5626 const activeGoal = activeThreadShell?.goal ?? null;
@@ -5688,54 +5729,35 @@ export default function ChatView(props: ChatViewProps) {
5729 isStoppingBackgroundWork,
5730 onOpenRelatedThreadStable,
5731 ]);
5691 - const threadStatusLine = useMemo(() => {
5692 - void nowMinute;
5693 - return activeThreadSnoozed ? (
5694 - <ThreadStatusLine
5695 - icon={<AlarmClockIcon />}
5696 - label={
5697 - activeThreadShell?.snoozedUntil
5698 - ? `Snoozed, ${formatRelativeTimeUntilLabel(activeThreadShell.snoozedUntil)}`
5699 - : "Snoozed"
5700 - }
5701 - actionLabel={isUnsnoozing ? "Waking..." : "Wake now"}
5702 - actionDisabled={!canOperateThread || isUnsnoozing}
5703 - onAction={() => void handleUnsnoozeActiveThreadStable()}
5704 - />
5705 - ) : activeThreadSettled ? (
5706 - <ThreadStatusLine
5707 - icon={<CheckCircle2Icon />}
5708 - label={
5709 - activeThreadShell?.settledAt
5710 - ? `Settled ${formatRelativeTimeLabel(activeThreadShell.settledAt)}`
5711 - : "Settled"
5712 - }
5713 - actionLabel={isUnsettling ? "Un-settling..." : "Un-settle"}
5714 - actionDisabled={!canOperateThread || isUnsettling}
5715 - onAction={() => void handleUnsettleActiveThreadStable()}
5716 - />
5717 - ) : activeThreadWokeVisible ? (
5718 - <ThreadStatusLine
5719 - icon={<AlarmClockIcon />}
5720 - label="Woke from snooze"
5721 - actionLabel="Dismiss"
5722 - onAction={acknowledgeActiveThreadWokeStable}
5723 - />
5724 - ) : null;
5725 - }, [
5726 - acknowledgeActiveThreadWokeStable,
5727 - activeThreadSettled,
5728 - activeThreadShell?.settledAt,
5729 - activeThreadShell?.snoozedUntil,
5730 - activeThreadSnoozed,
5731 - activeThreadWokeVisible,
5732 - canOperateThread,
5733 - handleUnsettleActiveThreadStable,
5734 - handleUnsnoozeActiveThreadStable,
5735 - isUnsettling,
5736 - isUnsnoozing,
5737 - nowMinute,
5738 - ]);
5732 + // The relative times read the clock; nowMinute re-renders them on the minute.
5733 + const snoozedUntil = activeThreadShell?.snoozedUntil ?? null;
5734 + const settledAt = activeThreadShell?.settledAt ?? null;
5735 + const threadStatusLine = activeThreadSnoozed ? (
5736 + <ThreadStatusLine
5737 + icon={<AlarmClockIcon />}
5738 + label={snoozedUntil ? `Snoozed, ${formatRelativeTimeUntilLabel(snoozedUntil)}` : "Snoozed"}
5739 + clockMinute={nowMinute}
5740 + actionLabel={isUnsnoozing ? "Waking..." : "Wake now"}
5741 + actionDisabled={!canOperateThread || isUnsnoozing}
5742 + onAction={() => void handleUnsnoozeActiveThreadStable()}
5743 + />
5744 + ) : activeThreadSettled ? (
5745 + <ThreadStatusLine
5746 + icon={<CheckCircle2Icon />}
5747 + label={settledAt ? `Settled ${formatRelativeTimeLabel(settledAt)}` : "Settled"}
5748 + clockMinute={nowMinute}
5749 + actionLabel={isUnsettling ? "Un-settling..." : "Un-settle"}
5750 + actionDisabled={!canOperateThread || isUnsettling}
5751 + onAction={() => void handleUnsettleActiveThreadStable()}
5752 + />
5753 + ) : activeThreadWokeVisible ? (
5754 + <ThreadStatusLine
5755 + icon={<AlarmClockIcon />}
5756 + label="Woke from snooze"
5757 + actionLabel="Dismiss"
5758 + onAction={acknowledgeActiveThreadWokeStable}
5759 + />
5760 + ) : null;
5761 const activeThreadHasCompactableConversation = serverVisibleTurnItems.some(
5762 ({ item }) =>
5763 item.type === "user_message" &&
@@ -6508,81 +6530,33 @@ export default function ChatView(props: ChatViewProps) {
6530 rewindingThreadKeys: new Set(store.rewindingThreadKeys).add(routeThreadKey),
6531 }));
6532 setThreadError(activeThread.id, null);
6511 - try {
6512 - if (composerRef.current?.hasPendingAttachments()) {
6513 - throw new Error("Wait for attachments to finish preparing before rewinding.");
6514 - }
6515 - const connection = readPreparedConnection(environmentId);
6516 - if (!connection) throw new Error("The environment is not connected.");
6517 - const files = await prepareRevertedMessageAttachments({
6518 - message,
6519 - environmentId,
6520 - httpBaseUrl: connection.httpBaseUrl,
6521 - createAssetUrl: createAttachmentAssetUrl,
6522 - });
6523 - const store = useComposerDraftStore.getState();
6524 - const draft = store.getComposerDraft(composerDraftTarget);
6525 - if (
6526 - (draft?.images.length ?? 0) + (draft?.files.length ?? 0) + files.length >
6527 - PROVIDER_SEND_TURN_MAX_ATTACHMENTS
6528 - ) {
6529 - throw new Error(
6530 - "Make room for this message's attachments in the composer before rewinding.",
6531 - );
6532 - }
6533 - const commandId = CommandId.make(randomUUID());
6534 - await waitForRevertedMessage(routeThreadRef, messageId, turnCount, commandId, async () => {
6535 - const result = await revertThreadCheckpoint({
6536 - environmentId,
6537 - input: { commandId, threadId: activeThread.id, turnCount, restoreFiles },
6538 - });
6539 - if (result._tag === "Failure") throw squashAtomCommandFailure(result);
6540 - });
6541 - const currentPrompt = store.getComposerDraft(composerDraftTarget)?.prompt ?? "";
6542 - const restoredPrompt = recallableComposerPrompt(message.text);
6543 - const nextPrompt =
6544 - restoredPrompt.length === 0
6545 - ? currentPrompt
6546 - : currentPrompt.length > 0
6547 - ? `${currentPrompt}\n\n${restoredPrompt}`
6548 - : restoredPrompt;
6549 - store.setPrompt(composerDraftTarget, nextPrompt);
6550 - const images: ComposerImageAttachment[] = [];
6551 - const restoredFiles: ComposerFileAttachment[] = [];
6552 - files.forEach((file, index) => {
6553 - const attachment = {
6554 - id: randomUUID(),
6555 - name: file.name,
6556 - mimeType: file.type,
6557 - sizeBytes: file.size,
6558 - file,
6559 - };
6560 - if (message.attachments?.[index]?.type === "image") {
6561 - images.push({ ...attachment, type: "image", previewUrl: URL.createObjectURL(file) });
6562 - } else {
6563 - restoredFiles.push({ ...attachment, type: "file" });
6564 - }
6565 - });
6566 - store.addImages(composerDraftTarget, images, { allowDuplicates: true });
6567 - store.addFiles(composerDraftTarget, restoredFiles, { allowDuplicates: true });
6568 - if (currentRouteThreadKeyRef.current === routeThreadKey) {
6569 - promptRef.current = nextPrompt;
6570 - composerRef.current?.resetCursorState({ prompt: nextPrompt, cursor: nextPrompt.length });
6571 - requestAnimationFrame(() => {
6572 - if (currentRouteThreadKeyRef.current === routeThreadKey)
6573 - composerRef.current?.focusAtEnd();
6574 - });
6575 - }
6576 - } catch (error) {
6577 - setThreadError(
6578 - activeThread.id,
6579 - error instanceof Error ? error.message : "Failed to revert thread state.",
6580 - );
6581 - } finally {
6582 - useComposerDraftStore.setState((store) => {
6583 - const remaining = new Set(store.rewindingThreadKeys);
6584 - remaining.delete(routeThreadKey);
6585 - return { rewindingThreadKeys: remaining };
6533 + const rewind = await rewindToMessage({
6534 + message,
6535 + environmentId,
6536 + routeThreadRef,
6537 + threadId: activeThread.id,
6538 + turnCount,
6539 + restoreFiles,
6540 + draftTarget: composerDraftTarget,
6541 + composerHasPendingAttachments: composerRef.current?.hasPendingAttachments() === true,
6542 + createAssetUrl: createAttachmentAssetUrl,
6543 + revertThreadCheckpoint,
6544 + });
6545 + useComposerDraftStore.setState((store) => {
6546 + const remaining = new Set(store.rewindingThreadKeys);
6547 + remaining.delete(routeThreadKey);
6548 + return { rewindingThreadKeys: remaining };
6549 + });
6550 + if (rewind.error !== null) {
6551 + setThreadError(activeThread.id, rewind.error);
6552 + return;
6553 + }
6554 + if (currentRouteThreadKeyRef.current === routeThreadKey) {
6555 + const nextPrompt = rewind.prompt;
6556 + promptRef.current = nextPrompt;
6557 + composerRef.current?.resetCursorState({ prompt: nextPrompt, cursor: nextPrompt.length });
6558 + requestAnimationFrame(() => {
6559 + if (currentRouteThreadKeyRef.current === routeThreadKey) composerRef.current?.focusAtEnd();
6560 });
6561 }
6562 };
@@ -6702,65 +6676,63 @@ export default function ChatView(props: ChatViewProps) {
6676 sendInFlightRef.current = true;
6677 setResumingThreadKeys((current) => new Set(current).add(routeThreadKey));
6678 setThreadError(threadId, null);
6705 - try {
6706 - const resume = async () => {
6707 - if (resumableRunId === null) {
6708 - return resumeThreadQueue({ environmentId, input: { threadId } });
6709 - }
6710 - const createdAt = new Date().toISOString();
6711 - const settingsResult = await persistThreadSettingsForNextTurn({
6679 + // Commands settle into a result, so this always runs.
6680 + const resume = async () => {
6681 + if (resumableRunId === null) {
6682 + return resumeThreadQueue({ environmentId, input: { threadId } });
6683 + }
6684 + const createdAt = new Date().toISOString();
6685 + const settingsResult = await persistThreadSettingsForNextTurn({
6686 + threadId,
6687 + createdAt,
6688 + ...(localCheckoutBranchMismatch
6689 + ? { branch: localCheckoutBranchMismatch.currentBranch }
6690 + : {}),
6691 + runtimeMode,
6692 + interactionMode,
6693 + });
6694 + if (settingsResult._tag === "Failure") return settingsResult;
6695 + const modelSelection = composerRef.current?.getSendContext().selectedModelSelection;
6696 + const turnResult = await startThreadTurn({
6697 + environmentId,
6698 + input: {
6699 threadId,
6713 - createdAt,
6714 - ...(localCheckoutBranchMismatch
6715 - ? { branch: localCheckoutBranchMismatch.currentBranch }
6716 - : {}),
6700 + manualContinuationOfRunId: resumableRunId,
6701 + ...(modelSelection ? { modelSelection } : {}),
6702 + message: {
6703 + messageId: newMessageId(),
6704 + role: "user",
6705 + text: "Continue where you left off.",
6706 + attachments: [],
6707 + },
6708 runtimeMode,
6709 interactionMode,
6719 - });
6720 - if (settingsResult._tag === "Failure") return settingsResult;
6721 - const modelSelection = composerRef.current?.getSendContext().selectedModelSelection;
6722 - const turnResult = await startThreadTurn({
6723 - environmentId,
6724 - input: {
6725 - threadId,
6726 - manualContinuationOfRunId: resumableRunId,
6727 - ...(modelSelection ? { modelSelection } : {}),
6728 - message: {
6729 - messageId: newMessageId(),
6730 - role: "user",
6731 - text: "Continue where you left off.",
6732 - attachments: [],
6733 - },
6734 - runtimeMode,
6735 - interactionMode,
6736 - dispatchMode: "start",
6737 - },
6738 - });
6739 - if (turnResult._tag === "Failure" || !hasHeldQueuedRuns) return turnResult;
6740 - clearUsageLimitsFor(routeThreadKey);
6741 - return resumeThreadQueue({ environmentId, input: { threadId } });
6742 - };
6743 - const result = await resume();
6744 - if (result._tag === "Failure") {
6745 - if (!isAtomCommandInterrupted(result)) {
6746 - const error = squashAtomCommandFailure(result);
6747 - setThreadError(
6748 - threadId,
6749 - error instanceof Error ? error.message : "Could not resume thread.",
6750 - );
6751 - }
6752 - } else {
6753 - clearUsageLimitsFor(routeThreadKey);
6754 - if (currentRouteThreadKeyRef.current === routeThreadKey) scrollToEnd();
6755 - }
6756 - } finally {
6757 - sendInFlightRef.current = false;
6758 - setResumingThreadKeys((current) => {
6759 - const next = new Set(current);
6760 - next.delete(routeThreadKey);
6761 - return next;
6710 + dispatchMode: "start",
6711 + },
6712 });
6713 + if (turnResult._tag === "Failure" || !hasHeldQueuedRuns) return turnResult;
6714 + clearUsageLimitsFor(routeThreadKey);
6715 + return resumeThreadQueue({ environmentId, input: { threadId } });
6716 + };
6717 + const result = await resume();
6718 + if (result._tag === "Failure") {
6719 + if (!isAtomCommandInterrupted(result)) {
6720 + const error = squashAtomCommandFailure(result);
6721 + setThreadError(
6722 + threadId,
6723 + error instanceof Error ? error.message : "Could not resume thread.",
6724 + );
6725 + }
6726 + } else {
6727 + clearUsageLimitsFor(routeThreadKey);
6728 + if (currentRouteThreadKeyRef.current === routeThreadKey) scrollToEnd();
6729 }
6730 + sendInFlightRef.current = false;
6731 + setResumingThreadKeys((current) => {
6732 + const next = new Set(current);
6733 + next.delete(routeThreadKey);
6734 + return next;
6735 + });
6736 };
6737
6738 const onSend = async (
@@ -7195,7 +7167,11 @@ export default function ChatView(props: ChatViewProps) {
7167 };
7168 };
7169
7198 - const multipleTargets = [];
7170 + const multipleTargets: Array<{
7171 + readonly selection: ModelSelection;
7172 + readonly text: string;
7173 + readonly interactionMode: ProviderInteractionMode;
7174 + }> = [];
7175 for (const selection of multipleModelSelections ?? []) {
7176 const provider = providerInstanceEntries.find(
7177 (entry) => entry.instanceId === selection.instanceId,
@@ -7362,7 +7338,9 @@ export default function ChatView(props: ChatViewProps) {
7338 let releasedComposer = false;
7339 let canRestoreDraft = () => false;
7340 let startedCount = 0;
7365 - try {
7341 + // Anything thrown here (an attachment the server can no longer take)
7342 + // fails every selection; the draft restore below still runs.
7343 + const sendResult = await settlePromise(async () => {
7344 const attachments = await turnAttachmentsPromise;
7345 const fileBlockReason = readLiveAttachmentCapabilities().fileBlockReason;
7346 if (fileBlockReason !== null) throw new Error(fileBlockReason);
@@ -7385,13 +7363,13 @@ export default function ChatView(props: ChatViewProps) {
7363 const clearedDraftSnapshot = useComposerDraftStore
7364 .getState()
7365 .getComposerDraft(composerDraftTarget);
7388 - const submittedSelections = multipleModelSelectionsRef.current;
7366 + const submittedSelections = readMultipleModelSelections();
7367 canRestoreDraft = () =>
7368 currentRouteThreadKeyRef.current === routeThreadKey &&
7369 composerSendGenerationRef.current === sendGeneration &&
7370 useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) ===
7371 clearedDraftSnapshot &&
7394 - multipleModelSelectionsRef.current === submittedSelections;
7372 + readMultipleModelSelections() === submittedSelections;
7373 setThreadError(threadIdForSend, null);
7374 const starts = Promise.all(
7375 multipleTargets.map(async (target) => {
@@ -7476,84 +7454,82 @@ export default function ChatView(props: ChatViewProps) {
7454 if (failedSelections.length === 0 && turnUsesAttachmentUploads) {
7455 releaseDraftAttachments(composerAttachmentsSnapshot);
7456 }
7479 - } catch (error) {
7457 + });
7458 + if (sendResult._tag === "Failure") {
7459 + const error = squashAtomCommandFailure(sendResult);
7460 failedSelections.push(...multipleModelSelections);
7461 setThreadError(
7462 threadIdForSend,
7463 error instanceof Error ? error.message : "Failed to send messages.",
7464 );
7485 - } finally {
7486 - const restoreFailedDraft = () => {
7487 - setMultipleModelSelections(failedSelections);
7488 - if (clearedDraft) {
7489 - setComposerDraftPrompt(composerDraftTarget, messageTextForSend);
7490 - addComposerDraftImages(
7491 - composerDraftTarget,
7492 - composerImagesSnapshot.map(cloneComposerImageForRetry),
7493 - );
7494 - addComposerDraftFiles(composerDraftTarget, composerFilesSnapshot);
7495 - setComposerDraftTerminalContexts(composerDraftTarget, composerTerminalContextsSnapshot);
7496 - setComposerDraftPreviewAnnotations(
7497 - composerDraftTarget,
7498 - composerPreviewAnnotationsSnapshot,
7499 - );
7500 - setComposerDraftReviewComments(composerDraftTarget, composerReviewCommentsSnapshot);
7501 - setComposerDraftThreadContexts(composerDraftTarget, composerThreadContextsSnapshot);
7502 - if (composerRef.current && currentRouteThreadKeyRef.current === routeThreadKey) {
7503 - promptRef.current = messageTextForSend;
7504 - composerRef.current.resetCursorState({
7505 - cursor: collapseExpandedComposerCursor(
7506 - messageTextForSend,
7507 - messageTextForSend.length,
7508 - ),
7509 - prompt: messageTextForSend,
7510 - detectTrigger: true,
7511 - });
7512 - }
7513 - }
7514 - };
7515 - if (failedSelections.length > 0) {
7516 - if (canRestoreDraft() && composerRef.current) {
7517 - restoreFailedDraft();
7518 - } else if (clearedDraft) {
7519 - const recoveryToastId = toastManager.add(
7520 - stackedThreadToast({
7521 - type: "error",
7522 - title: "A background prompt could not be sent",
7523 - description:
7524 - "Your newer draft is unchanged. Restore the failed prompt when this composer is empty.",
7525 - timeout: 0,
7526 - actionProps: {
7527 - children: "Restore prompt",
7528 - onClick: () => {
7529 - if (
7530 - !draftId ||
7531 - !useComposerDraftStore.getState().getDraftSession(draftId) ||
7532 - sendInFlightRef.current ||
7533 - composerDraftHasUserContent(
7534 - useComposerDraftStore.getState().getComposerDraft(composerDraftTarget),
7535 - )
7536 - ) {
7537 - toastManager.update(recoveryToastId, {
7538 - description:
7539 - "Return to the original draft and send or clear its current prompt before restoring.",
7540 - });
7541 - return;
7542 - }
7543 - restoreFailedDraft();
7544 - void navigate({ to: "/draft/$draftId", params: { draftId } });
7545 - toastManager.close(recoveryToastId);
7546 - },
7547 - },
7548 - }),
7549 - );
7465 + }
7466 + const restoreFailedDraft = () => {
7467 + setMultipleModelSelections(failedSelections);
7468 + if (clearedDraft) {
7469 + setComposerDraftPrompt(composerDraftTarget, messageTextForSend);
7470 + addComposerDraftImages(
7471 + composerDraftTarget,
7472 + composerImagesSnapshot.map(cloneComposerImageForRetry),
7473 + );
7474 + addComposerDraftFiles(composerDraftTarget, composerFilesSnapshot);
7475 + setComposerDraftTerminalContexts(composerDraftTarget, composerTerminalContextsSnapshot);
7476 + setComposerDraftPreviewAnnotations(
7477 + composerDraftTarget,
7478 + composerPreviewAnnotationsSnapshot,
7479 + );
7480 + setComposerDraftReviewComments(composerDraftTarget, composerReviewCommentsSnapshot);
7481 + setComposerDraftThreadContexts(composerDraftTarget, composerThreadContextsSnapshot);
7482 + if (composerRef.current && currentRouteThreadKeyRef.current === routeThreadKey) {
7483 + promptRef.current = messageTextForSend;
7484 + composerRef.current.resetCursorState({
7485 + cursor: collapseExpandedComposerCursor(messageTextForSend, messageTextForSend.length),
7486 + prompt: messageTextForSend,
7487 + detectTrigger: true,
7488 + });
7489 }
7490 }
7552 - if (!releasedComposer) {
7553 - sendInFlightRef.current = false;
7554 - resetLocalDispatch();
7491 + };
7492 + if (failedSelections.length > 0) {
7493 + if (canRestoreDraft() && composerRef.current) {
7494 + restoreFailedDraft();
7495 + } else if (clearedDraft) {
7496 + const recoveryToastId = toastManager.add(
7497 + stackedThreadToast({
7498 + type: "error",
7499 + title: "A background prompt could not be sent",
7500 + description:
7501 + "Your newer draft is unchanged. Restore the failed prompt when this composer is empty.",
7502 + timeout: 0,
7503 + actionProps: {
7504 + children: "Restore prompt",
7505 + onClick: () => {
7506 + if (
7507 + !draftId ||
7508 + !useComposerDraftStore.getState().getDraftSession(draftId) ||
7509 + sendInFlightRef.current ||
7510 + composerDraftHasUserContent(
7511 + useComposerDraftStore.getState().getComposerDraft(composerDraftTarget),
7512 + )
7513 + ) {
7514 + toastManager.update(recoveryToastId, {
7515 + description:
7516 + "Return to the original draft and send or clear its current prompt before restoring.",
7517 + });
7518 + return;
7519 + }
7520 + restoreFailedDraft();
7521 + void navigate({ to: "/draft/$draftId", params: { draftId } });
7522 + toastManager.close(recoveryToastId);
7523 + },
7524 + },
7525 + }),
7526 + );
7527 }
7528 }
7529 + if (!releasedComposer) {
7530 + sendInFlightRef.current = false;
7531 + resetLocalDispatch();
7532 + }
7533 return;
7534 }
7535 const optimisticAttachments = composerAttachmentsSnapshot.map((attachment) =>
@@ -8347,18 +8323,9 @@ export default function ChatView(props: ChatViewProps) {
8323 });
8324 };
8325 const onWorktreeSetupWorkLocallyStable = useStableCallback(onWorktreeSetupWorkLocally);
8350 - const onSendRef = useRef(onSend);
8351 - onSendRef.current = onSend;
8352 - const onResumeRef = useRef(onResume);
8353 - onResumeRef.current = onResume;
8354 - const onCompactContextRef = useRef(onCompactContext);
8355 - onCompactContextRef.current = onCompactContext;
8356 - const onComposerSend = (...args: Parameters<typeof onSend>) => onSendRef.current(...args);
8357 - const onComposerSendStable = useStableCallback(onComposerSend);
8358 - const onComposerResume = () => onResumeRef.current();
8359 - const onComposerResumeStable = useStableCallback(onComposerResume);
8360 - const onComposerCompactContext = () => onCompactContextRef.current();
8361 - const onComposerCompactContextStable = useStableCallback(onComposerCompactContext);
8326 + const onComposerSendStable = useStableCallback(onSend);
8327 + const onComposerResumeStable = useStableCallback(onResume);
8328 + const onComposerCompactContextStable = useStableCallback(onCompactContext);
8329 const queuedRunsControl = useMemo(
8330 () =>
8331 isServerThread && activeThread ? (
@@ -8414,7 +8381,7 @@ export default function ChatView(props: ChatViewProps) {
8381 return;
8382 }
8383 setWorkLocallyResendDraftId(null);
8417 - void onSendRef.current();
8384 + void onComposerSendStable();
8385 }, [
8386 composerDraftTarget,
8387 routeThreadKey,
@@ -8460,12 +8427,8 @@ export default function ChatView(props: ChatViewProps) {
8427 if (!paintOnlyDisplayedTimeline) void onRollbackCheckpoint(input);
8428 };
8429 const onTimelineRollbackCheckpointStable = useStableCallback(onTimelineRollbackCheckpoint);
8463 - // The revert handler is read from a ref at call-time so the callback
8464 - // reference is fully stable and never busts TimelineRowCtx identity.
8465 - const onRevertToTurnCountRef = useRef(onRevertToTurnCountStable);
8466 - onRevertToTurnCountRef.current = onRevertToTurnCountStable;
8430 const onRevertTimelineTurn = (targetTurnCount: number, messageId: MessageId) => {
8468 - void onRevertToTurnCountRef.current(targetTurnCount, messageId);
8431 + void onRevertToTurnCountStable(targetTurnCount, messageId);
8432 };
8433 const onRevertTimelineTurnStable = useStableCallback(onRevertTimelineTurn);
8434
@@ -8502,6 +8465,15 @@ export default function ChatView(props: ChatViewProps) {
8465 pendingSidebarFileDrops,
8466 ]);
8467
8468 + const addDroppedFilesToComposer = useStableCallback(
8469 + (files: Parameters<ChatComposerHandle["addDroppedFiles"]>[0]) =>
8470 + composerRef.current?.addDroppedFiles(files),
8471 + );
8472 + const addDroppedFoldersToComposer = useStableCallback(
8473 + (folders: Parameters<ChatComposerHandle["addDroppedFolders"]>[0]) =>
8474 + composerRef.current?.addDroppedFolders(folders),
8475 + );
8476 +
8477 if (!activeThread) {
8478 return <NoActiveThreadState />;
8479 }
@@ -8784,8 +8756,8 @@ export default function ChatView(props: ChatViewProps) {
8756 );
8757 const workspaceFileDropHandlers = makeWorkspaceFileDropHandlers({
8758 setDragActive: setIsWorkspaceFileDragActive,
8787 - addFiles: (files) => composerRef.current?.addDroppedFiles(files),
8788 - addFolders: (folders) => composerRef.current?.addDroppedFolders(folders),
8759 + addFiles: addDroppedFilesToComposer,
8760 + addFolders: addDroppedFoldersToComposer,
8761 });
8762
8763 const content = (
@@ -9081,10 +9053,7 @@ export default function ChatView(props: ChatViewProps) {
9053 : "pointer-events-none absolute inset-x-0 bottom-0 z-20 pt-1.5 sm:pt-2"
9054 }
9055 >
9084 - <div
9085 - ref={draftHeroTransition.transitionGroupRef}
9086 - className="chat-composer-lane w-full"
9087 - >
9056 + <div ref={draftHeroTransitionGroupRef} className="chat-composer-lane w-full">
9057 <div
9058 data-chat-composer-stack="true"
9059 className="group/composer-stack pointer-events-auto relative z-10 mx-auto w-full max-w-(--chat-content-max-width)"
@@ -9108,7 +9077,7 @@ export default function ChatView(props: ChatViewProps) {
9077 </div>
9078 ) : null}
9079 <div
9111 - ref={draftHeroTransition.composerAnchorRef}
9080 + ref={draftHeroComposerAnchorRef}
9081 className="relative z-10"
9082 style={
9083 forceExpandedMobileComposer
apps/web/src/components/chat/ThreadStatusLine.tsx
+2
@@ -8,6 +8,8 @@ export function ThreadStatusLine(props: {
8 readonly actionLabel: string;
9 readonly actionDisabled?: boolean;
10 readonly onAction: () => void;
11 + // Set when the label reads the clock, so the line updates as time passes.
12 + readonly clockMinute?: string;
13 }) {
14 return (
15 <div
apps/web/src/hooks/useIncrementalTimelineEntries.ts new
+42
@@ -0,0 +1,42 @@
1 +import { useState } from "react";
2 +import {
3 + deriveTimelineEntriesFromVisibleTurnItemsWithState,
4 + type TimelineEntriesInput,
5 + type TimelineEntriesProjection,
6 +} from "../session-logic";
7 +
8 +function sameInput(left: TimelineEntriesInput, right: TimelineEntriesInput): boolean {
9 + return (
10 + left.visibleTurnItems === right.visibleTurnItems &&
11 + left.optimisticMessages === right.optimisticMessages &&
12 + left.anchoredMessages === right.anchoredMessages &&
13 + left.attachmentUrlById === right.attachmentUrlById &&
14 + left.attempts === right.attempts &&
15 + left.nodes === right.nodes &&
16 + left.plans === right.plans
17 + );
18 +}
19 +
20 +/**
21 + * Timeline entries for a thread, derived from the previous projection so
22 + * unchanged rows keep their identity and memoized rows skip rendering. A new
23 + * thread starts from scratch.
24 + */
25 +export function useIncrementalTimelineEntries(
26 + threadKey: string | null,
27 + input: TimelineEntriesInput,
28 +): TimelineEntriesProjection["entries"] {
29 + const [state, setState] = useState(() => ({
30 + threadKey,
31 + projection: deriveTimelineEntriesFromVisibleTurnItemsWithState(input),
32 + }));
33 + if (state.threadKey === threadKey && sameInput(state.projection.input, input)) {
34 + return state.projection.entries;
35 + }
36 + const projection = deriveTimelineEntriesFromVisibleTurnItemsWithState(
37 + input,
38 + state.threadKey === threadKey ? state.projection : null,
39 + );
40 + setState({ threadKey, projection });
41 + return projection.entries;
42 +}
apps/web/src/hooks/useLoadBalancedEnvironment.ts
+15 -11
@@ -20,21 +20,25 @@ export function useLoadBalancedEnvironment(
20 },
21 [registry],
22 );
23 + // Keyed by content: callers derive the list every render.
24 + const environmentIdsKey = environmentIds.join("\n");
25 const resourcesAtom = useMemo(
26 () =>
27 Atom.make((get) =>
26 - environmentIds.map((environmentId) => {
27 - const result = get(serverEnvironment.hostResources({ environmentId, input: {} }));
28 - return {
29 - environmentId,
30 - resources: result._tag === "Success" ? result.value : null,
31 - receivedAt: result._tag === "Success" ? result.timestamp : 0,
32 - pending: result._tag === "Initial" || result.waiting,
33 - failed: result._tag === "Failure",
34 - };
35 - }),
28 + (environmentIdsKey === "" ? [] : (environmentIdsKey.split("\n") as EnvironmentId[])).map(
29 + (environmentId) => {
30 + const result = get(serverEnvironment.hostResources({ environmentId, input: {} }));
31 + return {
32 + environmentId,
33 + resources: result._tag === "Success" ? result.value : null,
34 + receivedAt: result._tag === "Success" ? result.timestamp : 0,
35 + pending: result._tag === "Initial" || result.waiting,
36 + failed: result._tag === "Failure",
37 + };
38 + },
39 + ),
40 ),
37 - [environmentIds],
41 + [environmentIdsKey],
42 );
43 const resources = useAtomValue(resourcesAtom);
44 const pending = resources.some((resource) => resource.pending);
apps/web/src/reactCompiledFiles.test.ts new
+38
@@ -0,0 +1,38 @@
1 +// @effect-diagnostics nodeBuiltinImport:off - compiles real source files on disk.
2 +import * as NodeFS from "node:fs";
3 +import * as NodePath from "node:path";
4 +import * as NodeURL from "node:url";
5 +import { transform } from "oxc-transform-react";
6 +import { describe, expect, it } from "vite-plus/test";
7 +import { REACT_COMPILED_FILES, REACT_COMPILED_FILES_PENDING_LINT } from "../reactCompiledFiles";
8 +
9 +const repoRoot = NodePath.resolve(
10 + NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)),
11 + "../../..",
12 +);
13 +
14 +function expandPattern(pattern: string): string[] {
15 + if (!pattern.endsWith("/**")) return [pattern];
16 + const directory = pattern.slice(0, -3);
17 + return NodeFS.readdirSync(NodePath.join(repoRoot, directory), { recursive: true })
18 + .map(String)
19 + .filter((file) => /\.tsx?$/.test(file) && !/\.(test|browser)\.tsx?$/.test(file))
20 + .map((file) => `${directory}/${file}`);
21 +}
22 +
23 +// Lint reports most compiler bailouts, but not every one (try/finally, throw
24 +// inside try). A skipped file still builds, just unmemoized, so check the output.
25 +describe("React Compiler coverage", () => {
26 + it.each([...REACT_COMPILED_FILES, ...REACT_COMPILED_FILES_PENDING_LINT].flatMap(expandPattern))(
27 + "compiles %s",
28 + async (file) => {
29 + const absolute = NodePath.join(repoRoot, file);
30 + const result = await transform(absolute, NodeFS.readFileSync(absolute, "utf8"), {
31 + jsx: { runtime: "automatic", development: false, refresh: false },
32 + reactCompiler: { reportDiagnostics: true },
33 + });
34 + const bailouts = result.errors.map((error) => error.codeframe ?? error.message);
35 + expect(bailouts).toEqual([]);
36 + },
37 + );
38 +}, 120_000);
apps/web/tsconfig.json
+1
@@ -30,6 +30,7 @@
30 "vite",
31 "vite.config.ts",
32 "vercel.ts",
33 + "reactCompiledFiles.ts",
34 "test",
35 "scripts/warm-dep-cache.ts",
36 "../../scripts/lib/public-config.ts",
docs/internals/web-ui.md
+8 -5
@@ -61,8 +61,11 @@ Anything it can't prove, such as reading a ref during render or calling `setStat
61 makes it skip the whole function without a build error. Lint reports each skip as a
62 `react(...)` warning with the note "React Compiler skipped optimizing this component or hook".
63
64 -Files listed in the React Compiler override in [`vite.config.ts`](../../vite.config.ts) must
65 -compile. There those rules are errors, and `t3code/no-manual-memo` rejects `useMemo` and
66 -`useCallback`, which the compiler makes redundant. `useStableCallback` still marks handlers
67 -that leave a large component, as described above. Add a file to the list once its skips are
68 -fixed, and drop its manual memoization in the same change.
64 +Files listed in [`reactCompiledFiles.ts`](../../apps/web/reactCompiledFiles.ts) must compile.
65 +Lint makes those rules errors there, and `t3code/no-manual-memo` rejects `useMemo` and
66 +`useCallback`, which the compiler makes redundant. Lint misses some bailouts, notably `try` with
67 +`finally` and `throw` inside `try`, so [`reactCompiledFiles.test.ts`](../../apps/web/src/reactCompiledFiles.test.ts)
68 +compiles each listed file and fails on any skip. Async handlers rarely need `try`: an atom
69 +command settles into a result, so cleanup can follow the `await`. `useStableCallback` still marks
70 +handlers that leave a large component, as described above. Add a file to the list once it
71 +compiles cleanly, and drop its manual memoization in the same change.
vite.config.ts
+5 -16
@@ -1,6 +1,7 @@
1 import "vite-plus/test/config";
2 import { defineConfig } from "vite-plus";
3 import * as NodeURL from "node:url";
4 +import { REACT_COMPILED_FILES } from "./apps/web/reactCompiledFiles.ts";
5
6 const RESTRICTED_IMPORT_PATHS = [
7 {
@@ -321,22 +322,10 @@ export default defineConfig({
322 },
323 },
324 {
324 - // Files the React Compiler must compile. Any bailout (a ref read in render, a
325 - // setState in an effect, a manual memo it cannot preserve) fails lint instead of
326 - // silently leaving the file unoptimized, and manual memoization is redundant here.
327 - // Add a file once it compiles cleanly. ChatView is being split toward this list.
328 - files: [
329 - "apps/web/src/components/PersistentThreadTerminals.tsx",
330 - "apps/web/src/components/chat/usePendingThreadRequests.ts",
331 - "apps/web/src/components/chat/useQueuedRunEdit.ts",
332 - "apps/web/src/components/chat/useUsageLimitsPanel.ts",
333 - "apps/web/src/components/chat/useWorktreeSetup.ts",
334 - "apps/web/src/components/pullRequest/useThreadLinkedPullRequest.ts",
335 - "apps/web/src/components/preview/useAgentOpenedPreviews.ts",
336 - "apps/web/src/components/terminal/**",
337 - "apps/web/src/hooks/useProactivePanels.ts",
338 - "apps/web/src/hooks/useRightPanelSurfaceClose.ts",
339 - ],
325 + // Files the React Compiler must compile. Its bailout rules are errors here, and manual
326 + // memoization is redundant. apps/web/src/compiledFiles.test.ts compiles each file and
327 + // fails on any bailout lint cannot see, such as try/finally.
328 + files: [...REACT_COMPILED_FILES],
329 rules: {
330 "react/exhaustive-effect-dependencies": "error",
331 "react/globals": "error",