The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 20:45 UTC
refactor(web): ChatView's module-level helpers live in their own files (#22665)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 21, 2026 at 01:36 UTC
9c3e743a4560d91bfb480d46a4b6bc1f979b7bd7
6 files changed
+587
-530
apps/web/src/components/ChatView.logic.ts
+108
-1
@@ -1,4 +1,8 @@
1
import * as Option from "effect/Option";
2
+import type { SetStateAction } from "react";
3
+import { applyClaudePromptEffortPrefix, resolvePromptInjectedEffort } from "@t3tools/shared/model";
4
+import { getProviderModelCapabilities } from "../providerModels";
5
+import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
6
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
7
import {
8
ANTIGRAVITY_DEFAULT_MODEL,
@@ -48,7 +52,11 @@ import {
52
type Thread,
53
type TurnDiffSummary,
54
} from "../types";
51
-import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
55
+import {
56
+ type ComposerImageAttachment,
57
+ type DraftId,
58
+ type DraftThreadState,
59
+} from "../composerDraftStore";
60
import * as Schema from "effect/Schema";
61
import { appAtomRegistry } from "../rpc/atomRegistry";
62
import { environmentThreadShells, environmentThreadDetails } from "../state/threads";
@@ -1335,3 +1343,102 @@ export function mergeDirectPreviewAnnotation(input: {
1343
}
1344
1345
export { isThreadWokeUnseen } from "@t3tools/client-runtime/state/thread-settled";
1346
+
1347
+export function formatOutgoingPrompt(params: {
1348
+ provider: ProviderDriverKind;
1349
+ model: string | null;
1350
+ models: ReadonlyArray<ServerProvider["models"][number]>;
1351
+ effort: string | null;
1352
+ text: string;
1353
+}): string {
1354
+ const caps = getProviderModelCapabilities(params.models, params.model, params.provider);
1355
+ const promptEffort = resolvePromptInjectedEffort(caps, params.effort);
1356
+ return applyClaudePromptEffortPrefix(params.text, promptEffort);
1357
+}
1358
+
1359
+export function isCompactCommandMessage(message: ChatMessage): boolean {
1360
+ const text = message.text.trim().toLowerCase();
1361
+ return message.role === "user" && text === "/compact" && !message.attachments?.length;
1362
+}
1363
+
1364
+// Errors surface through two maps (draft-keyed and thread-keyed) whose entries
1365
+// can race around promotion, so each write carries its time to let the latest
1366
+// one win when they collide.
1367
+export type LocalThreadErrorEntry = {
1368
+ readonly message: string | null;
1369
+ readonly at: number;
1370
+};
1371
+
1372
+export function chatActionErrorMessage(error: unknown): string {
1373
+ return error instanceof Error ? error.message : "An error occurred.";
1374
+}
1375
+
1376
+export function releaseChatTimelineAnchor<T extends { readonly messageId: MessageId | null }>(
1377
+ current: T,
1378
+): T {
1379
+ return current.messageId === null ? current : { ...current, messageId: null };
1380
+}
1381
+
1382
+// The factories below build functions ChatView calls during render, or hands
1383
+// to ChatComposer, which can call them after an await. They live outside the
1384
+// component so each closure keeps only its inputs, not a whole render scope
1385
+// (see useStableCallback), while still acting on the render that made them.
1386
+
1387
+/** Records a thread error in local state, keyed by the route the making render saw. */
1388
+export function makeThreadErrorSetter(input: {
1389
+ readonly routeThreadRef: ScopedThreadRef;
1390
+ readonly routeThreadKey: string;
1391
+ readonly draftId: DraftId | null;
1392
+ readonly serverThreadRef: ScopedThreadRef | null;
1393
+ readonly setLocalServerErrorsByThreadKey: (
1394
+ update: SetStateAction<Record<string, LocalThreadErrorEntry>>,
1395
+ ) => void;
1396
+ readonly setLocalDraftErrorsByDraftId: (
1397
+ update: SetStateAction<Record<string, LocalThreadErrorEntry>>,
1398
+ ) => void;
1399
+}) {
1400
+ return (targetThreadId: ThreadId | null, error: string | null) => {
1401
+ if (!targetThreadId) return;
1402
+ const nextError = sanitizeThreadErrorMessage(error);
1403
+ const nextEntry: LocalThreadErrorEntry = { message: nextError, at: Date.now() };
1404
+ const { routeThreadRef, serverThreadRef } = input;
1405
+ if (
1406
+ serverThreadRef &&
1407
+ targetThreadId === routeThreadRef.threadId &&
1408
+ serverThreadRef.environmentId === routeThreadRef.environmentId &&
1409
+ serverThreadRef.threadId === targetThreadId
1410
+ ) {
1411
+ input.setLocalServerErrorsByThreadKey((existing) => {
1412
+ if ((existing[input.routeThreadKey]?.message ?? null) === nextError) {
1413
+ return existing;
1414
+ }
1415
+ return { ...existing, [input.routeThreadKey]: nextEntry };
1416
+ });
1417
+ return;
1418
+ }
1419
+ const localDraftErrorKey = input.draftId ?? targetThreadId;
1420
+ input.setLocalDraftErrorsByDraftId((existing) => {
1421
+ if ((existing[localDraftErrorKey]?.message ?? null) === nextError) {
1422
+ return existing;
1423
+ }
1424
+ return { ...existing, [localDraftErrorKey]: nextEntry };
1425
+ });
1426
+ };
1427
+}
1428
+
1429
+/** Why the model picker should disable a model, or null when it can be chosen. */
1430
+export function makeModelDisabledReason(
1431
+ context: Omit<
1432
+ Parameters<typeof getStartedThreadModelChangeBlockReason>[0],
1433
+ "nextModelSelection"
1434
+ > | null,
1435
+) {
1436
+ return (instanceId: ProviderInstanceId, model: string): string | null => {
1437
+ if (!context) return null;
1438
+ const reason = getStartedThreadModelChangeBlockReason({
1439
+ ...context,
1440
+ nextModelSelection: { instanceId, model },
1441
+ });
1442
+ return reason ? `${reason.description} Start a new thread to use this model.` : null;
1443
+ };
1444
+}
apps/web/src/components/ChatView.tsx
+21
-529
@@ -60,7 +60,6 @@ import {
60
AuthTerminalOperateScope,
61
type AssistantCitation,
62
type ChatFileAttachment,
63
- CommandId,
63
DEFAULT_MODEL,
64
isProviderNativeSubagentThread,
65
type EnvironmentId,
@@ -75,19 +74,13 @@ import {
74
type ThreadId,
75
type RunId,
76
type RunAttemptId,
78
- type RuntimeRequestId,
79
- PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
77
ProviderInteractionMode,
81
- ProviderDriverKind,
78
resolveProjectProviderInstanceEnabled,
79
RuntimeMode,
80
} from "@t3tools/contracts";
81
import { type EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
82
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
87
-import {
88
- wasBootstrapThreadDeleted,
89
- wasBootstrapThreadNotCreated,
90
-} from "@t3tools/client-runtime/errors";
83
+import { wasBootstrapThreadDeleted } from "@t3tools/client-runtime/errors";
84
import { readPastedComposerContext } from "./composerInlineTokenPaste";
85
import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste";
86
import { effectiveSnoozed, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
@@ -128,10 +121,8 @@ import {
121
scopeThreadRef,
122
} from "@t3tools/client-runtime/environment";
123
import {
131
- applyClaudePromptEffortPrefix,
124
createModelSelection,
125
formatModelSlugName,
134
- resolvePromptInjectedEffort,
126
resolveSelectableModel,
127
} from "@t3tools/shared/model";
128
import {
@@ -152,7 +143,6 @@ import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReferenc
143
import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
144
import { Debouncer } from "@tanstack/react-pacer";
145
import { useAtomValue } from "@effect/atom-react";
155
-import { Atom } from "effect/reactivity";
146
import {
147
Fragment,
148
type SetStateAction,
@@ -214,13 +204,7 @@ import {
204
buildPlanImplementationPrompt,
205
resolvePlanFollowUpSubmission,
206
} from "../proposedPlan";
217
-import {
218
- DEFAULT_INTERACTION_MODE,
219
- MAX_TERMINALS_PER_GROUP,
220
- type ChatMessage,
221
- type SessionPhase,
222
- type Thread,
223
-} from "../types";
207
+import { DEFAULT_INTERACTION_MODE, MAX_TERMINALS_PER_GROUP, type ChatMessage } from "../types";
208
import { useTheme } from "../hooks/useTheme";
209
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
210
import { isCommandPaletteOpen } from "../commandPaletteBus";
@@ -284,13 +268,12 @@ import {
268
TargetIcon,
269
WifiOffIcon,
270
} from "lucide-react";
287
-import { cn, randomUUID } from "~/lib/utils";
271
+import { cn } from "~/lib/utils";
272
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
273
import { stackedThreadToast, toastManager } from "./ui/toast";
274
import { projectScriptIdFromCommand } from "~/projectScripts";
275
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
276
import { registerFaviconProjectForThread } from "~/browserFaviconStore";
293
-import { getProviderModelCapabilities } from "../providerModels";
277
import {
278
applyProviderInstanceSettings,
279
deriveProviderInstanceEntries,
@@ -395,7 +378,6 @@ import {
378
useThreadStatus,
379
useThreadHistory,
380
useQuietThreadShell,
398
- useThreadShell,
381
useChildThreadInputs,
382
useThreadRefs,
383
useThreadVisibleTurnItems,
@@ -480,8 +462,6 @@ import {
462
latestProviderTurnTokenUsage,
463
} from "../lib/contextWindow";
464
import {
483
- DRAFT_HERO_TRANSITION_ANIMATION_ID,
484
- DRAFT_HERO_TRANSITION_EASING,
465
MOBILE_COMPOSER_VIEW_TRANSITION_NAME,
466
MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,
467
runMobileComposerTransition,
@@ -493,13 +473,11 @@ import {
473
buildExpiredTerminalContextToastCopy,
474
buildLocalDraftThread,
475
collectUserMessageBlobPreviewUrls,
496
- createLocalDispatchSnapshot,
476
deriveCommittedServerUserMessageIds,
477
deriveComposerSendState,
478
dismissBranchMismatchForSession,
479
hasEnvironmentReconnectWarningGraceElapsed,
480
scheduleEnvironmentReconnectWarning,
502
- hasServerAcknowledgedLocalDispatch,
481
isBranchMismatchDismissedForSession,
482
shouldShowBranchMismatchBanner,
483
shouldShowPlanFollowUpPrompt,
@@ -508,13 +486,10 @@ import {
486
getStartedThreadModelChangeBlockReason,
487
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
488
LastInvokedScriptByProjectSchema,
511
- type LocalDispatchSnapshot,
489
cloneComposerImageForRetry,
490
deriveLockedProvider,
491
readFileAsDataUrl,
492
resolveFileAttachmentUrl,
516
- prepareRevertedMessageAttachments,
517
- waitForRevertedMessage,
493
reconcileMountedTerminalThreadIds,
494
resolveComposerInteractionMode,
495
resolveComposerProviderSelection,
@@ -538,7 +513,6 @@ import {
513
retryAttachmentUpload,
514
startAttachmentUpload,
515
} from "../lib/attachmentUploadQueue";
541
-import { sanitizeThreadErrorMessage } from "~/rpc/transportError";
516
import { RightPanelSheet } from "./RightPanelSheet";
517
import { previewEnvironment } from "../state/preview";
518
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
@@ -571,8 +545,25 @@ import {
545
ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
546
threadContextsOutsideEnvironment,
547
} from "@t3tools/shared/composerContextReferences";
574
-import { recallableComposerPrompt } from "./chat/composerPromptHistory";
548
import { observeResize } from "~/lib/observeResize";
549
+import { ThreadVisitWatermark } from "./chat/ThreadVisitWatermark";
550
+import { useDraftHeroLayoutTransition } from "./chat/useDraftHeroLayoutTransition";
551
+import { useLocalDispatchState } from "./chat/useLocalDispatchState";
552
+import {
553
+ draftFanoutSelectionsAtom,
554
+ draftSendState,
555
+ rewindToMessage,
556
+ startFanoutThread,
557
+} from "./chat/chatViewSend";
558
+import {
559
+ chatActionErrorMessage,
560
+ formatOutgoingPrompt,
561
+ isCompactCommandMessage,
562
+ type LocalThreadErrorEntry,
563
+ makeModelDisabledReason,
564
+ makeThreadErrorSetter,
565
+ releaseChatTimelineAnchor,
566
+} from "./ChatView.logic";
567
568
const EMPTY_PROVIDERS: ServerProvider[] = [];
569
const EMPTY_PROVIDER_MODELS: ServerProvider["models"] = [];
@@ -581,75 +572,9 @@ import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplat
572
573
const TIMELINE_SCROLL_CANCEL_SENTINEL = Object.freeze({});
574
const EMPTY_FEEDBACK_SUBMISSIONS: ReadonlyArray<CodexFeedbackSubmission> = [];
584
-// During an active turn the thread's updatedAt advances several times per
585
-// second, and every server-side visit is a full command dispatch plus a
586
-// broadcast to all shell subscribers.
587
-const VISIT_DISPATCH_THROTTLE_MS = 10_000;
575
const RELATED_THREAD_SHELL_WAIT_MS = 1_000;
576
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
577
const EMPTY_AUTO_UPDATE_ENVIRONMENTS: ReadonlyArray<EnvironmentPresentation> = [];
591
-function useDraftHeroLayoutTransition(
592
- isDraftHeroState: boolean,
593
- animationsActive: boolean,
594
- animationDurationMs: number,
595
-) {
596
- const transitionGroupRef = useRef<HTMLDivElement | null>(null);
597
- const composerAnchorRef = useRef<HTMLDivElement | null>(null);
598
- const previousStateRef = useRef(isDraftHeroState);
599
- const previousComposerRectRef = useRef<DOMRect | null>(null);
600
- const animationRef = useRef<Animation | null>(null);
601
- const captureComposerRect = useStableCallback(() => {
602
- previousComposerRectRef.current = composerAnchorRef.current?.getBoundingClientRect() ?? null;
603
- });
604
-
605
- useLayoutEffect(() => {
606
- const transitionGroup = transitionGroupRef.current;
607
- const nextComposerRect = composerAnchorRef.current?.getBoundingClientRect() ?? null;
608
- const stateChanged = previousStateRef.current !== isDraftHeroState;
609
- const mobileComposerTransitionActive =
610
- typeof document !== "undefined" &&
611
- document.documentElement.dataset.mobileComposerRouteTransition === "true";
612
-
613
- animationRef.current?.cancel();
614
- animationRef.current = null;
615
- const previousComposerRect = previousComposerRectRef.current;
616
- if (
617
- stateChanged &&
618
- animationsActive &&
619
- !mobileComposerTransitionActive &&
620
- transitionGroup &&
621
- previousComposerRect &&
622
- nextComposerRect &&
623
- typeof transitionGroup.animate === "function"
624
- ) {
625
- const translateX = previousComposerRect.left - nextComposerRect.left;
626
- const translateY = previousComposerRect.top - nextComposerRect.top;
627
- if (Math.abs(translateX) >= 0.5 || Math.abs(translateY) >= 0.5) {
628
- const animation = transitionGroup.animate(
629
- [
630
- { transform: `translate3d(${translateX}px, ${translateY}px, 0)` },
631
- { transform: "translate3d(0, 0, 0)" },
632
- ],
633
- {
634
- duration: animationDurationMs,
635
- easing: DRAFT_HERO_TRANSITION_EASING,
636
- },
637
- );
638
- animation.id = DRAFT_HERO_TRANSITION_ANIMATION_ID;
639
- animationRef.current = animation;
640
- void animation.finished
641
- .catch(() => undefined)
642
- .then(() => {
643
- if (animationRef.current === animation) animationRef.current = null;
644
- });
645
- }
646
- }
647
- previousStateRef.current = isDraftHeroState;
648
- previousComposerRectRef.current = nextComposerRect;
649
- }, [animationDurationMs, animationsActive, isDraftHeroState]);
650
-
651
- return { transitionGroupRef, composerAnchorRef, captureComposerRect } as const;
652
-}
578
579
const EMPTY_PENDING_FILE_SURFACE_IDS: ReadonlySet<string> = new Set();
580
type EnvironmentUnavailableState = {
@@ -658,230 +583,9 @@ type EnvironmentUnavailableState = {
583
readonly connection: EnvironmentConnectionPresentation;
584
};
585
661
-// Kept per route so a send in flight, and the multiple-model selections, survive
662
-// ChatView remounting while the user navigates.
663
-const draftFanoutSelectionsAtom = Atom.family((_routeKey: string) =>
664
- Atom.make<ReadonlyArray<ModelSelection> | null>(null).pipe(Atom.keepAlive),
665
-);
666
-const draftSendStateByRouteKey = new Map<
667
- string,
668
- {
669
- readonly sendInFlight: { current: boolean };
670
- readonly uncertainSubmissions: { current: Map<string, ThreadId> };
671
- }
672
->();
673
-function draftSendState(routeKey: string) {
674
- let state = draftSendStateByRouteKey.get(routeKey);
675
- if (!state) {
676
- state = { sendInFlight: { current: false }, uncertainSubmissions: { current: new Map() } };
677
- draftSendStateByRouteKey.set(routeKey, state);
678
- }
679
- return state;
680
-}
681
-
682
-/**
683
- * Starts one thread of a multiple-model send. A request that may have
684
- * reached the server before failing is remembered by `retryKey`, so sending
685
- * again cannot silently create a duplicate thread; its failure toast offers
686
- * to open that thread or to allow the retry.
687
- */
688
-async function startFanoutThread(input: {
689
- readonly retryKey: string;
690
- readonly model: string;
691
- readonly uncertainSubmissions: Map<string, ThreadId>;
692
- readonly start: (threadId: ThreadId) => Promise<AtomCommandResult<unknown, unknown>>;
693
- readonly openThread: (threadId: ThreadId) => void;
694
-}): Promise<boolean> {
695
- const { retryKey, uncertainSubmissions } = input;
696
- const uncertainThreadId = uncertainSubmissions.get(retryKey);
697
- const targetThreadId = uncertainThreadId ?? newThreadId();
698
- let requestMayHaveStarted = false;
699
- try {
700
- if (uncertainThreadId) {
701
- throw new Error(
702
- "The previous request may have started. Open its thread to check before sending again.",
703
- );
704
- }
705
- requestMayHaveStarted = true;
706
- const result = await input.start(targetThreadId);
707
- if (result._tag === "Failure") {
708
- const error = squashAtomCommandFailure(result);
709
- if (wasBootstrapThreadDeleted(error) || wasBootstrapThreadNotCreated(error)) {
710
- requestMayHaveStarted = false;
711
- }
712
- throw error;
713
- }
714
- return true;
715
- } catch (error) {
716
- if (requestMayHaveStarted && !uncertainSubmissions.has(retryKey)) {
717
- uncertainSubmissions.set(retryKey, targetThreadId);
718
- }
719
- const retainedThreadId = uncertainSubmissions.get(retryKey);
720
- const failureToastId = toastManager.add(
721
- stackedThreadToast({
722
- type: "error",
723
- title: `Could not start ${input.model}`,
724
- description: error instanceof Error ? error.message : "Failed to send message.",
725
- ...(retainedThreadId
726
- ? {
727
- timeout: 0,
728
- data: {
729
- secondaryActionProps: {
730
- children: "Allow retry",
731
- onClick: () => {
732
- void readLocalApi()
733
- ?.dialogs.confirm(
734
- "The previous request may already be running. Check its thread first. Allow another send that could create a duplicate thread?",
735
- )
736
- .then(
737
- (confirmed) => {
738
- if (
739
- confirmed &&
740
- uncertainSubmissions.get(retryKey) === retainedThreadId
741
- ) {
742
- uncertainSubmissions.delete(retryKey);
743
- toastManager.close(failureToastId);
744
- }
745
- },
746
- () => undefined,
747
- );
748
- },
749
- },
750
- },
751
- actionProps: {
752
- children: "Open thread",
753
- onClick: () => input.openThread(retainedThreadId),
754
- },
755
- }
756
- : {}),
757
- }),
758
- );
759
- return false;
760
- }
761
-}
762
-
763
-/**
764
- * Reverts the thread to before `message` and puts that message's text and
765
- * attachments back in the composer draft. Returns the restored prompt, or the
766
- * error to show; on error the draft is untouched.
767
- */
768
-async function rewindToMessage(input: {
769
- readonly message: ChatMessage;
770
- readonly environmentId: EnvironmentId;
771
- readonly routeThreadRef: ScopedThreadRef;
772
- readonly threadId: ThreadId;
773
- readonly turnCount: number;
774
- readonly restoreFiles: boolean;
775
- readonly checkpoint: ReturnType<typeof findRevertCheckpoint>;
776
- readonly draftTarget: ScopedThreadRef | DraftId;
777
- readonly composerHasPendingAttachments: boolean;
778
- readonly createAssetUrl: Parameters<
779
- typeof prepareRevertedMessageAttachments
780
- >[0]["createAssetUrl"];
781
- readonly revertThreadCheckpoint: (value: {
782
- environmentId: EnvironmentId;
783
- input: {
784
- commandId: CommandId;
785
- threadId: ThreadId;
786
- turnCount: number;
787
- restoreFiles: boolean;
788
- checkpointId?: string;
789
- scopeId?: string;
790
- };
791
- }) => Promise<AtomCommandResult<unknown, unknown>>;
792
-}): Promise<
793
- | { readonly error: string; readonly prompt?: never }
794
- | { readonly error: null; readonly prompt: string }
795
-> {
796
- const { message, environmentId, draftTarget } = input;
797
- try {
798
- if (input.composerHasPendingAttachments) {
799
- throw new Error("Wait for attachments to finish preparing before rewinding.");
800
- }
801
- const connection = readPreparedConnection(environmentId);
802
- if (!connection) throw new Error("The environment is not connected.");
803
- const files = await prepareRevertedMessageAttachments({
804
- message,
805
- environmentId,
806
- httpBaseUrl: connection.httpBaseUrl,
807
- createAssetUrl: input.createAssetUrl,
808
- });
809
- const store = useComposerDraftStore.getState();
810
- const draft = store.getComposerDraft(draftTarget);
811
- if (
812
- (draft?.images.length ?? 0) + (draft?.files.length ?? 0) + files.length >
813
- PROVIDER_SEND_TURN_MAX_ATTACHMENTS
814
- ) {
815
- throw new Error("Make room for this message's attachments in the composer before rewinding.");
816
- }
817
- const commandId = CommandId.make(randomUUID());
818
- await waitForRevertedMessage(input.routeThreadRef, input.turnCount, commandId, async () => {
819
- const result = await input.revertThreadCheckpoint({
820
- environmentId,
821
- input: {
822
- commandId,
823
- threadId: input.threadId,
824
- turnCount: input.turnCount,
825
- restoreFiles: input.restoreFiles,
826
- ...(input.checkpoint === undefined
827
- ? {}
828
- : { checkpointId: input.checkpoint.id, scopeId: input.checkpoint.scopeId }),
829
- },
830
- });
831
- if (result._tag === "Failure") throw squashAtomCommandFailure(result);
832
- });
833
- const currentPrompt = store.getComposerDraft(draftTarget)?.prompt ?? "";
834
- const restoredPrompt = recallableComposerPrompt(message.text);
835
- const nextPrompt =
836
- restoredPrompt.length === 0
837
- ? currentPrompt
838
- : currentPrompt.length > 0
839
- ? `${currentPrompt}\n\n${restoredPrompt}`
840
- : restoredPrompt;
841
- store.setPrompt(draftTarget, nextPrompt);
842
- const images: ComposerImageAttachment[] = [];
843
- const restoredFiles: ComposerFileAttachment[] = [];
844
- files.forEach((file, index) => {
845
- const attachment = {
846
- id: randomUUID(),
847
- name: file.name,
848
- mimeType: file.type,
849
- sizeBytes: file.size,
850
- file,
851
- };
852
- if (message.attachments?.[index]?.type === "image") {
853
- images.push({ ...attachment, type: "image", previewUrl: URL.createObjectURL(file) });
854
- } else {
855
- restoredFiles.push({ ...attachment, type: "file" });
856
- }
857
- });
858
- store.addImages(draftTarget, images, { allowDuplicates: true });
859
- store.addFiles(draftTarget, restoredFiles, { allowDuplicates: true });
860
- return { error: null, prompt: nextPrompt };
861
- } catch (error) {
862
- return { error: error instanceof Error ? error.message : "Failed to revert thread state." };
863
- }
864
-}
865
-
866
-function formatOutgoingPrompt(params: {
867
- provider: ProviderDriverKind;
868
- model: string | null;
869
- models: ReadonlyArray<ServerProvider["models"][number]>;
870
- effort: string | null;
871
- text: string;
872
-}): string {
873
- const caps = getProviderModelCapabilities(params.models, params.model, params.provider);
874
- const promptEffort = resolvePromptInjectedEffort(caps, params.effort);
875
- return applyClaudePromptEffortPrefix(params.text, promptEffort);
876
-}
586
const SCRIPT_TERMINAL_COLS = 120;
587
const SCRIPT_TERMINAL_ROWS = 30;
588
880
-function isCompactCommandMessage(message: ChatMessage): boolean {
881
- const text = message.text.trim().toLowerCase();
882
- return message.role === "user" && text === "/compact" && !message.attachments?.length;
883
-}
884
-
589
type ChatViewProps =
590
| {
591
environmentId: EnvironmentId;
@@ -908,151 +612,12 @@ interface TerminalLaunchContext {
612
worktreePath: string | null;
613
}
614
911
-function useLocalDispatchState(input: {
912
- activeThread: Thread | undefined;
913
- activeLatestRun: Thread["latestRun"] | null;
914
- latestUserMessageId: MessageId | null;
915
- phase: SessionPhase;
916
- activePendingApproval: RuntimeRequestId | null;
917
- activePendingUserInput: RuntimeRequestId | null;
918
- threadError: string | null | undefined;
919
-}) {
920
- const [localDispatch, setLocalDispatch] = useState<LocalDispatchSnapshot | null>(null);
921
-
922
- const resetLocalDispatch = () => {
923
- setLocalDispatch(null);
924
- };
925
-
926
- const serverAcknowledgedLocalDispatch = hasServerAcknowledgedLocalDispatch({
927
- localDispatch,
928
- phase: input.phase,
929
- latestRun: input.activeLatestRun,
930
- latestUserMessageId: input.latestUserMessageId,
931
- runtime: input.activeThread?.runtime ?? null,
932
- hasPendingApproval: input.activePendingApproval !== null,
933
- hasPendingUserInput: input.activePendingUserInput !== null,
934
- threadError: input.threadError,
935
- });
936
- const activeLocalDispatch = serverAcknowledgedLocalDispatch ? null : localDispatch;
937
- const beginLocalDispatch = (options?: {
938
- preparingWorktree?: boolean;
939
- submissionIntent?: ComposerSubmissionIntent;
940
- }) => {
941
- const preparingWorktree = Boolean(options?.preparingWorktree);
942
- setLocalDispatch((current) => {
943
- const active = serverAcknowledgedLocalDispatch ? null : current;
944
- if (active) {
945
- const submissionIntent = options?.submissionIntent ?? active.submissionIntent;
946
- return active.preparingWorktree === preparingWorktree &&
947
- active.submissionIntent === submissionIntent
948
- ? active
949
- : { ...active, preparingWorktree, submissionIntent };
950
- }
951
- return createLocalDispatchSnapshot(input.activeThread, {
952
- ...options,
953
- latestUserMessageId: input.latestUserMessageId,
954
- });
955
- });
956
- };
957
-
958
- return {
959
- beginLocalDispatch,
960
- resetLocalDispatch,
961
- localDispatchStartedAt: activeLocalDispatch?.startedAt ?? null,
962
- isPreparingWorktree: activeLocalDispatch?.preparingWorktree ?? false,
963
- isSendBusy: activeLocalDispatch !== null,
964
- backgroundSubmissionPending: activeLocalDispatch?.submissionIntent === "background",
965
- };
966
-}
967
-
968
-// Errors surface through two maps (draft-keyed and thread-keyed) whose entries
969
-// can race around promotion, so each write carries its time to let the latest
970
-// one win when they collide.
971
-type LocalThreadErrorEntry = {
972
- readonly message: string | null;
973
- readonly at: number;
974
-};
975
-
976
-function chatActionErrorMessage(error: unknown): string {
977
- return error instanceof Error ? error.message : "An error occurred.";
978
-}
979
-
615
const ENVIRONMENT_UNAVAILABLE_SEND_TOAST_TRAIL_SIZE = 3;
616
const EMPTY_HELD_TURN_DIFF_SUMMARIES: readonly never[] = [];
617
const noopHeldTurnDiff = (_turnId: RunId, _filePath?: string) => {};
618
const noopHeldRevert = (_targetTurnCount: number) => {};
619
const noopHeldAttachment = (_attachment: ChatFileAttachment) => {};
620
986
-function releaseChatTimelineAnchor<T extends { readonly messageId: MessageId | null }>(
987
- current: T,
988
-): T {
989
- return current.messageId === null ? current : { ...current, messageId: null };
990
-}
991
-
992
-// The factories below build functions ChatView calls during render, or hands
993
-// to ChatComposer, which can call them after an await. They live outside the
994
-// component so each closure keeps only its inputs, not a whole render scope
995
-// (see useStableCallback), while still acting on the render that made them.
996
-
997
-/** Records a thread error in local state, keyed by the route the making render saw. */
998
-function makeThreadErrorSetter(input: {
999
- readonly routeThreadRef: ScopedThreadRef;
1000
- readonly routeThreadKey: string;
1001
- readonly draftId: DraftId | null;
1002
- readonly serverThreadRef: ScopedThreadRef | null;
1003
- readonly setLocalServerErrorsByThreadKey: (
1004
- update: SetStateAction<Record<string, LocalThreadErrorEntry>>,
1005
- ) => void;
1006
- readonly setLocalDraftErrorsByDraftId: (
1007
- update: SetStateAction<Record<string, LocalThreadErrorEntry>>,
1008
- ) => void;
1009
-}) {
1010
- return (targetThreadId: ThreadId | null, error: string | null) => {
1011
- if (!targetThreadId) return;
1012
- const nextError = sanitizeThreadErrorMessage(error);
1013
- const nextEntry: LocalThreadErrorEntry = { message: nextError, at: Date.now() };
1014
- const { routeThreadRef, serverThreadRef } = input;
1015
- if (
1016
- serverThreadRef &&
1017
- targetThreadId === routeThreadRef.threadId &&
1018
- serverThreadRef.environmentId === routeThreadRef.environmentId &&
1019
- serverThreadRef.threadId === targetThreadId
1020
- ) {
1021
- input.setLocalServerErrorsByThreadKey((existing) => {
1022
- if ((existing[input.routeThreadKey]?.message ?? null) === nextError) {
1023
- return existing;
1024
- }
1025
- return { ...existing, [input.routeThreadKey]: nextEntry };
1026
- });
1027
- return;
1028
- }
1029
- const localDraftErrorKey = input.draftId ?? targetThreadId;
1030
- input.setLocalDraftErrorsByDraftId((existing) => {
1031
- if ((existing[localDraftErrorKey]?.message ?? null) === nextError) {
1032
- return existing;
1033
- }
1034
- return { ...existing, [localDraftErrorKey]: nextEntry };
1035
- });
1036
- };
1037
-}
1038
-
1039
-/** Why the model picker should disable a model, or null when it can be chosen. */
1040
-function makeModelDisabledReason(
1041
- context: Omit<
1042
- Parameters<typeof getStartedThreadModelChangeBlockReason>[0],
1043
- "nextModelSelection"
1044
- > | null,
1045
-) {
1046
- return (instanceId: ProviderInstanceId, model: string): string | null => {
1047
- if (!context) return null;
1048
- const reason = getStartedThreadModelChangeBlockReason({
1049
- ...context,
1050
- nextModelSelection: { instanceId, model },
1051
- });
1052
- return reason ? `${reason.description} Start a new thread to use this model.` : null;
1053
- };
1054
-}
1055
-
621
export default function ChatView(props: ChatViewProps) {
622
const {
623
environmentId,
@@ -9018,76 +8583,3 @@ function PreviewSessionSync(props: { readonly threadRef: ScopedThreadRef }) {
8583
usePreviewSession(props.threadRef);
8584
return null;
8585
}
9021
-
9022
-// The visit watermark is the one part of the chat view that follows the
9023
-// shell's updatedAt, which ticks while a run streams. Keeping it in a leaf lets
9024
-// ChatView read the quiet shell.
9025
-function ThreadVisitWatermark(props: { readonly threadRef: ScopedThreadRef }) {
9026
- const serverThread = useThreadShell(props.threadRef);
9027
- const threadKey = scopedThreadKey(props.threadRef);
9028
- const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
9029
- const activeThreadLocalLastVisitedAt = useUiStateStore(
9030
- (store) => store.threadLastVisitedAtById[threadKey],
9031
- );
9032
- const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
9033
- const lastDispatchedVisitRef = useRef<string | null>(null);
9034
- const lastVisitDispatchAtRef = useRef(0);
9035
-
9036
- useEffect(() => {
9037
- if (!serverThread?.id) return;
9038
- const threadUpdatedAt = Date.parse(serverThread.updatedAt);
9039
- if (Number.isNaN(threadUpdatedAt)) return;
9040
- const effectiveLastVisitedAt = resolveThreadLastVisitedAt(
9041
- serverThread.lastVisitedAt,
9042
- activeThreadLocalLastVisitedAt,
9043
- );
9044
- const lastVisitedAt = effectiveLastVisitedAt ? Date.parse(effectiveLastVisitedAt) : NaN;
9045
- if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= threadUpdatedAt) return;
9046
-
9047
- if (serverThread.lastVisitedAt !== undefined) {
9048
- // Dedupe per watermark — the effect re-runs before the command's echo
9049
- // lands. The dedupe also keeps a mark-unread on the open thread sticky:
9050
- // the rewind leaves updatedAt untouched, so the already-dispatched key
9051
- // skips a fresh visit until new activity lands or the thread is reopened.
9052
- const dispatchKey = `${threadKey}:${serverThread.updatedAt}`;
9053
- if (lastDispatchedVisitRef.current === dispatchKey) return;
9054
- const dispatch = () => {
9055
- lastDispatchedVisitRef.current = dispatchKey;
9056
- lastVisitDispatchAtRef.current = Date.now();
9057
- void visitThreadMutation({
9058
- environmentId: serverThread.environmentId,
9059
- input: { threadId: serverThread.id, visitedAt: serverThread.updatedAt },
9060
- });
9061
- };
9062
- const latestRunCompletedAtMs = serverThread.latestRun?.completedAt
9063
- ? Date.parse(serverThread.latestRun.completedAt)
9064
- : NaN;
9065
- const hasUnseenCompletion =
9066
- !Number.isNaN(latestRunCompletedAtMs) &&
9067
- (Number.isNaN(lastVisitedAt) || latestRunCompletedAtMs > lastVisitedAt);
9068
- const elapsed = Date.now() - lastVisitDispatchAtRef.current;
9069
- if (hasUnseenCompletion || elapsed >= VISIT_DISPATCH_THROTTLE_MS) {
9070
- dispatch();
9071
- return;
9072
- }
9073
- const timer = setTimeout(dispatch, VISIT_DISPATCH_THROTTLE_MS - elapsed);
9074
- return () => clearTimeout(timer);
9075
- }
9076
-
9077
- markThreadVisited(
9078
- scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)),
9079
- serverThread.updatedAt,
9080
- );
9081
- }, [
9082
- activeThreadLocalLastVisitedAt,
9083
- markThreadVisited,
9084
- threadKey,
9085
- serverThread?.environmentId,
9086
- serverThread?.id,
9087
- serverThread?.lastVisitedAt,
9088
- serverThread?.latestRun?.completedAt,
9089
- serverThread?.updatedAt,
9090
- visitThreadMutation,
9091
- ]);
9092
- return null;
9093
-}
apps/web/src/components/chat/ThreadVisitWatermark.tsx
new
+86
@@ -0,0 +1,86 @@
1
+import { type ScopedThreadRef } from "@t3tools/contracts";
2
+import { resolveThreadLastVisitedAt } from "../Sidebar.logic";
3
+import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
4
+import { useEffect, useRef } from "react";
5
+import { useUiStateStore } from "../../uiStateStore";
6
+import { threadEnvironment } from "../../state/threads";
7
+import { useThreadShell } from "../../state/entities";
8
+import { useAtomCommand } from "../../state/use-atom-command";
9
+
10
+// During an active turn the thread's updatedAt advances several times per
11
+// second, and every server-side visit is a full command dispatch plus a
12
+// broadcast to all shell subscribers.
13
+const VISIT_DISPATCH_THROTTLE_MS = 10_000;
14
+
15
+// The visit watermark is the one part of the chat view that follows the
16
+// shell's updatedAt, which ticks while a run streams. Keeping it in a leaf lets
17
+// ChatView read the quiet shell.
18
+export function ThreadVisitWatermark(props: { readonly threadRef: ScopedThreadRef }) {
19
+ const serverThread = useThreadShell(props.threadRef);
20
+ const threadKey = scopedThreadKey(props.threadRef);
21
+ const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
22
+ const activeThreadLocalLastVisitedAt = useUiStateStore(
23
+ (store) => store.threadLastVisitedAtById[threadKey],
24
+ );
25
+ const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
26
+ const lastDispatchedVisitRef = useRef<string | null>(null);
27
+ const lastVisitDispatchAtRef = useRef(0);
28
+
29
+ useEffect(() => {
30
+ if (!serverThread?.id) return;
31
+ const threadUpdatedAt = Date.parse(serverThread.updatedAt);
32
+ if (Number.isNaN(threadUpdatedAt)) return;
33
+ const effectiveLastVisitedAt = resolveThreadLastVisitedAt(
34
+ serverThread.lastVisitedAt,
35
+ activeThreadLocalLastVisitedAt,
36
+ );
37
+ const lastVisitedAt = effectiveLastVisitedAt ? Date.parse(effectiveLastVisitedAt) : NaN;
38
+ if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= threadUpdatedAt) return;
39
+
40
+ if (serverThread.lastVisitedAt !== undefined) {
41
+ // Dedupe per watermark — the effect re-runs before the command's echo
42
+ // lands. The dedupe also keeps a mark-unread on the open thread sticky:
43
+ // the rewind leaves updatedAt untouched, so the already-dispatched key
44
+ // skips a fresh visit until new activity lands or the thread is reopened.
45
+ const dispatchKey = `${threadKey}:${serverThread.updatedAt}`;
46
+ if (lastDispatchedVisitRef.current === dispatchKey) return;
47
+ const dispatch = () => {
48
+ lastDispatchedVisitRef.current = dispatchKey;
49
+ lastVisitDispatchAtRef.current = Date.now();
50
+ void visitThreadMutation({
51
+ environmentId: serverThread.environmentId,
52
+ input: { threadId: serverThread.id, visitedAt: serverThread.updatedAt },
53
+ });
54
+ };
55
+ const latestRunCompletedAtMs = serverThread.latestRun?.completedAt
56
+ ? Date.parse(serverThread.latestRun.completedAt)
57
+ : NaN;
58
+ const hasUnseenCompletion =
59
+ !Number.isNaN(latestRunCompletedAtMs) &&
60
+ (Number.isNaN(lastVisitedAt) || latestRunCompletedAtMs > lastVisitedAt);
61
+ const elapsed = Date.now() - lastVisitDispatchAtRef.current;
62
+ if (hasUnseenCompletion || elapsed >= VISIT_DISPATCH_THROTTLE_MS) {
63
+ dispatch();
64
+ return;
65
+ }
66
+ const timer = setTimeout(dispatch, VISIT_DISPATCH_THROTTLE_MS - elapsed);
67
+ return () => clearTimeout(timer);
68
+ }
69
+
70
+ markThreadVisited(
71
+ scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)),
72
+ serverThread.updatedAt,
73
+ );
74
+ }, [
75
+ activeThreadLocalLastVisitedAt,
76
+ markThreadVisited,
77
+ threadKey,
78
+ serverThread?.environmentId,
79
+ serverThread?.id,
80
+ serverThread?.lastVisitedAt,
81
+ serverThread?.latestRun?.completedAt,
82
+ serverThread?.updatedAt,
83
+ visitThreadMutation,
84
+ ]);
85
+ return null;
86
+}
apps/web/src/components/chat/chatViewSend.ts
new
+237
@@ -0,0 +1,237 @@
1
+import {
2
+ CommandId,
3
+ type EnvironmentId,
4
+ type ModelSelection,
5
+ type ScopedThreadRef,
6
+ type ThreadId,
7
+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
8
+} from "@t3tools/contracts";
9
+import {
10
+ wasBootstrapThreadDeleted,
11
+ wasBootstrapThreadNotCreated,
12
+} from "@t3tools/client-runtime/errors";
13
+import { Atom } from "effect/reactivity";
14
+import {
15
+ squashAtomCommandFailure,
16
+ type AtomCommandResult,
17
+} from "@t3tools/client-runtime/state/runtime";
18
+import { readLocalApi } from "../../localApi";
19
+import { findRevertCheckpoint } from "../../session-logic";
20
+import { type ChatMessage } from "../../types";
21
+import { randomUUID } from "~/lib/utils";
22
+import { stackedThreadToast, toastManager } from "../ui/toast";
23
+import { newThreadId } from "~/lib/utils";
24
+import {
25
+ type ComposerFileAttachment,
26
+ type ComposerImageAttachment,
27
+ useComposerDraftStore,
28
+ DraftId,
29
+} from "../../composerDraftStore";
30
+import { prepareRevertedMessageAttachments, waitForRevertedMessage } from "../ChatView.logic";
31
+import { readPreparedConnection } from "../../state/session";
32
+import { recallableComposerPrompt } from "./composerPromptHistory";
33
+
34
+// Kept per route so a send in flight, and the multiple-model selections, survive
35
+// ChatView remounting while the user navigates.
36
+export const draftFanoutSelectionsAtom = Atom.family((_routeKey: string) =>
37
+ Atom.make<ReadonlyArray<ModelSelection> | null>(null).pipe(Atom.keepAlive),
38
+);
39
+const draftSendStateByRouteKey = new Map<
40
+ string,
41
+ {
42
+ readonly sendInFlight: { current: boolean };
43
+ readonly uncertainSubmissions: { current: Map<string, ThreadId> };
44
+ }
45
+>();
46
+export function draftSendState(routeKey: string) {
47
+ let state = draftSendStateByRouteKey.get(routeKey);
48
+ if (!state) {
49
+ state = { sendInFlight: { current: false }, uncertainSubmissions: { current: new Map() } };
50
+ draftSendStateByRouteKey.set(routeKey, state);
51
+ }
52
+ return state;
53
+}
54
+
55
+/**
56
+ * Starts one thread of a multiple-model send. A request that may have
57
+ * reached the server before failing is remembered by `retryKey`, so sending
58
+ * again cannot silently create a duplicate thread; its failure toast offers
59
+ * to open that thread or to allow the retry.
60
+ */
61
+export async function startFanoutThread(input: {
62
+ readonly retryKey: string;
63
+ readonly model: string;
64
+ readonly uncertainSubmissions: Map<string, ThreadId>;
65
+ readonly start: (threadId: ThreadId) => Promise<AtomCommandResult<unknown, unknown>>;
66
+ readonly openThread: (threadId: ThreadId) => void;
67
+}): Promise<boolean> {
68
+ const { retryKey, uncertainSubmissions } = input;
69
+ const uncertainThreadId = uncertainSubmissions.get(retryKey);
70
+ const targetThreadId = uncertainThreadId ?? newThreadId();
71
+ let requestMayHaveStarted = false;
72
+ try {
73
+ if (uncertainThreadId) {
74
+ throw new Error(
75
+ "The previous request may have started. Open its thread to check before sending again.",
76
+ );
77
+ }
78
+ requestMayHaveStarted = true;
79
+ const result = await input.start(targetThreadId);
80
+ if (result._tag === "Failure") {
81
+ const error = squashAtomCommandFailure(result);
82
+ if (wasBootstrapThreadDeleted(error) || wasBootstrapThreadNotCreated(error)) {
83
+ requestMayHaveStarted = false;
84
+ }
85
+ throw error;
86
+ }
87
+ return true;
88
+ } catch (error) {
89
+ if (requestMayHaveStarted && !uncertainSubmissions.has(retryKey)) {
90
+ uncertainSubmissions.set(retryKey, targetThreadId);
91
+ }
92
+ const retainedThreadId = uncertainSubmissions.get(retryKey);
93
+ const failureToastId = toastManager.add(
94
+ stackedThreadToast({
95
+ type: "error",
96
+ title: `Could not start ${input.model}`,
97
+ description: error instanceof Error ? error.message : "Failed to send message.",
98
+ ...(retainedThreadId
99
+ ? {
100
+ timeout: 0,
101
+ data: {
102
+ secondaryActionProps: {
103
+ children: "Allow retry",
104
+ onClick: () => {
105
+ void readLocalApi()
106
+ ?.dialogs.confirm(
107
+ "The previous request may already be running. Check its thread first. Allow another send that could create a duplicate thread?",
108
+ )
109
+ .then(
110
+ (confirmed) => {
111
+ if (
112
+ confirmed &&
113
+ uncertainSubmissions.get(retryKey) === retainedThreadId
114
+ ) {
115
+ uncertainSubmissions.delete(retryKey);
116
+ toastManager.close(failureToastId);
117
+ }
118
+ },
119
+ () => undefined,
120
+ );
121
+ },
122
+ },
123
+ },
124
+ actionProps: {
125
+ children: "Open thread",
126
+ onClick: () => input.openThread(retainedThreadId),
127
+ },
128
+ }
129
+ : {}),
130
+ }),
131
+ );
132
+ return false;
133
+ }
134
+}
135
+
136
+/**
137
+ * Reverts the thread to before `message` and puts that message's text and
138
+ * attachments back in the composer draft. Returns the restored prompt, or the
139
+ * error to show; on error the draft is untouched.
140
+ */
141
+export async function rewindToMessage(input: {
142
+ readonly message: ChatMessage;
143
+ readonly environmentId: EnvironmentId;
144
+ readonly routeThreadRef: ScopedThreadRef;
145
+ readonly threadId: ThreadId;
146
+ readonly turnCount: number;
147
+ readonly restoreFiles: boolean;
148
+ readonly checkpoint: ReturnType<typeof findRevertCheckpoint>;
149
+ readonly draftTarget: ScopedThreadRef | DraftId;
150
+ readonly composerHasPendingAttachments: boolean;
151
+ readonly createAssetUrl: Parameters<
152
+ typeof prepareRevertedMessageAttachments
153
+ >[0]["createAssetUrl"];
154
+ readonly revertThreadCheckpoint: (value: {
155
+ environmentId: EnvironmentId;
156
+ input: {
157
+ commandId: CommandId;
158
+ threadId: ThreadId;
159
+ turnCount: number;
160
+ restoreFiles: boolean;
161
+ checkpointId?: string;
162
+ scopeId?: string;
163
+ };
164
+ }) => Promise<AtomCommandResult<unknown, unknown>>;
165
+}): Promise<
166
+ | { readonly error: string; readonly prompt?: never }
167
+ | { readonly error: null; readonly prompt: string }
168
+> {
169
+ const { message, environmentId, draftTarget } = input;
170
+ try {
171
+ if (input.composerHasPendingAttachments) {
172
+ throw new Error("Wait for attachments to finish preparing before rewinding.");
173
+ }
174
+ const connection = readPreparedConnection(environmentId);
175
+ if (!connection) throw new Error("The environment is not connected.");
176
+ const files = await prepareRevertedMessageAttachments({
177
+ message,
178
+ environmentId,
179
+ httpBaseUrl: connection.httpBaseUrl,
180
+ createAssetUrl: input.createAssetUrl,
181
+ });
182
+ const store = useComposerDraftStore.getState();
183
+ const draft = store.getComposerDraft(draftTarget);
184
+ if (
185
+ (draft?.images.length ?? 0) + (draft?.files.length ?? 0) + files.length >
186
+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS
187
+ ) {
188
+ throw new Error("Make room for this message's attachments in the composer before rewinding.");
189
+ }
190
+ const commandId = CommandId.make(randomUUID());
191
+ await waitForRevertedMessage(input.routeThreadRef, input.turnCount, commandId, async () => {
192
+ const result = await input.revertThreadCheckpoint({
193
+ environmentId,
194
+ input: {
195
+ commandId,
196
+ threadId: input.threadId,
197
+ turnCount: input.turnCount,
198
+ restoreFiles: input.restoreFiles,
199
+ ...(input.checkpoint === undefined
200
+ ? {}
201
+ : { checkpointId: input.checkpoint.id, scopeId: input.checkpoint.scopeId }),
202
+ },
203
+ });
204
+ if (result._tag === "Failure") throw squashAtomCommandFailure(result);
205
+ });
206
+ const currentPrompt = store.getComposerDraft(draftTarget)?.prompt ?? "";
207
+ const restoredPrompt = recallableComposerPrompt(message.text);
208
+ const nextPrompt =
209
+ restoredPrompt.length === 0
210
+ ? currentPrompt
211
+ : currentPrompt.length > 0
212
+ ? `${currentPrompt}\n\n${restoredPrompt}`
213
+ : restoredPrompt;
214
+ store.setPrompt(draftTarget, nextPrompt);
215
+ const images: ComposerImageAttachment[] = [];
216
+ const restoredFiles: ComposerFileAttachment[] = [];
217
+ files.forEach((file, index) => {
218
+ const attachment = {
219
+ id: randomUUID(),
220
+ name: file.name,
221
+ mimeType: file.type,
222
+ sizeBytes: file.size,
223
+ file,
224
+ };
225
+ if (message.attachments?.[index]?.type === "image") {
226
+ images.push({ ...attachment, type: "image", previewUrl: URL.createObjectURL(file) });
227
+ } else {
228
+ restoredFiles.push({ ...attachment, type: "file" });
229
+ }
230
+ });
231
+ store.addImages(draftTarget, images, { allowDuplicates: true });
232
+ store.addFiles(draftTarget, restoredFiles, { allowDuplicates: true });
233
+ return { error: null, prompt: nextPrompt };
234
+ } catch (error) {
235
+ return { error: error instanceof Error ? error.message : "Failed to revert thread state." };
236
+ }
237
+}
apps/web/src/components/chat/useDraftHeroLayoutTransition.ts
new
+69
@@ -0,0 +1,69 @@
1
+import { useStableCallback } from "../../hooks/useStableCallback";
2
+import { useLayoutEffect, useRef } from "react";
3
+import {
4
+ DRAFT_HERO_TRANSITION_ANIMATION_ID,
5
+ DRAFT_HERO_TRANSITION_EASING,
6
+} from "./draftHeroTransition";
7
+
8
+export function useDraftHeroLayoutTransition(
9
+ isDraftHeroState: boolean,
10
+ animationsActive: boolean,
11
+ animationDurationMs: number,
12
+) {
13
+ const transitionGroupRef = useRef<HTMLDivElement | null>(null);
14
+ const composerAnchorRef = useRef<HTMLDivElement | null>(null);
15
+ const previousStateRef = useRef(isDraftHeroState);
16
+ const previousComposerRectRef = useRef<DOMRect | null>(null);
17
+ const animationRef = useRef<Animation | null>(null);
18
+ const captureComposerRect = useStableCallback(() => {
19
+ previousComposerRectRef.current = composerAnchorRef.current?.getBoundingClientRect() ?? null;
20
+ });
21
+
22
+ useLayoutEffect(() => {
23
+ const transitionGroup = transitionGroupRef.current;
24
+ const nextComposerRect = composerAnchorRef.current?.getBoundingClientRect() ?? null;
25
+ const stateChanged = previousStateRef.current !== isDraftHeroState;
26
+ const mobileComposerTransitionActive =
27
+ typeof document !== "undefined" &&
28
+ document.documentElement.dataset.mobileComposerRouteTransition === "true";
29
+
30
+ animationRef.current?.cancel();
31
+ animationRef.current = null;
32
+ const previousComposerRect = previousComposerRectRef.current;
33
+ if (
34
+ stateChanged &&
35
+ animationsActive &&
36
+ !mobileComposerTransitionActive &&
37
+ transitionGroup &&
38
+ previousComposerRect &&
39
+ nextComposerRect &&
40
+ typeof transitionGroup.animate === "function"
41
+ ) {
42
+ const translateX = previousComposerRect.left - nextComposerRect.left;
43
+ const translateY = previousComposerRect.top - nextComposerRect.top;
44
+ if (Math.abs(translateX) >= 0.5 || Math.abs(translateY) >= 0.5) {
45
+ const animation = transitionGroup.animate(
46
+ [
47
+ { transform: `translate3d(${translateX}px, ${translateY}px, 0)` },
48
+ { transform: "translate3d(0, 0, 0)" },
49
+ ],
50
+ {
51
+ duration: animationDurationMs,
52
+ easing: DRAFT_HERO_TRANSITION_EASING,
53
+ },
54
+ );
55
+ animation.id = DRAFT_HERO_TRANSITION_ANIMATION_ID;
56
+ animationRef.current = animation;
57
+ void animation.finished
58
+ .catch(() => undefined)
59
+ .then(() => {
60
+ if (animationRef.current === animation) animationRef.current = null;
61
+ });
62
+ }
63
+ }
64
+ previousStateRef.current = isDraftHeroState;
65
+ previousComposerRectRef.current = nextComposerRect;
66
+ }, [animationDurationMs, animationsActive, isDraftHeroState]);
67
+
68
+ return { transitionGroupRef, composerAnchorRef, captureComposerRect } as const;
69
+}
apps/web/src/components/chat/useLocalDispatchState.ts
new
+66
@@ -0,0 +1,66 @@
1
+import { type MessageId, type RuntimeRequestId } from "@t3tools/contracts";
2
+import { useState } from "react";
3
+import { type ComposerSubmissionIntent } from "../../composer-logic";
4
+import { type SessionPhase, type Thread } from "../../types";
5
+import {
6
+ createLocalDispatchSnapshot,
7
+ hasServerAcknowledgedLocalDispatch,
8
+ type LocalDispatchSnapshot,
9
+} from "../ChatView.logic";
10
+
11
+export function useLocalDispatchState(input: {
12
+ activeThread: Thread | undefined;
13
+ activeLatestRun: Thread["latestRun"] | null;
14
+ latestUserMessageId: MessageId | null;
15
+ phase: SessionPhase;
16
+ activePendingApproval: RuntimeRequestId | null;
17
+ activePendingUserInput: RuntimeRequestId | null;
18
+ threadError: string | null | undefined;
19
+}) {
20
+ const [localDispatch, setLocalDispatch] = useState<LocalDispatchSnapshot | null>(null);
21
+
22
+ const resetLocalDispatch = () => {
23
+ setLocalDispatch(null);
24
+ };
25
+
26
+ const serverAcknowledgedLocalDispatch = hasServerAcknowledgedLocalDispatch({
27
+ localDispatch,
28
+ phase: input.phase,
29
+ latestRun: input.activeLatestRun,
30
+ latestUserMessageId: input.latestUserMessageId,
31
+ runtime: input.activeThread?.runtime ?? null,
32
+ hasPendingApproval: input.activePendingApproval !== null,
33
+ hasPendingUserInput: input.activePendingUserInput !== null,
34
+ threadError: input.threadError,
35
+ });
36
+ const activeLocalDispatch = serverAcknowledgedLocalDispatch ? null : localDispatch;
37
+ const beginLocalDispatch = (options?: {
38
+ preparingWorktree?: boolean;
39
+ submissionIntent?: ComposerSubmissionIntent;
40
+ }) => {
41
+ const preparingWorktree = Boolean(options?.preparingWorktree);
42
+ setLocalDispatch((current) => {
43
+ const active = serverAcknowledgedLocalDispatch ? null : current;
44
+ if (active) {
45
+ const submissionIntent = options?.submissionIntent ?? active.submissionIntent;
46
+ return active.preparingWorktree === preparingWorktree &&
47
+ active.submissionIntent === submissionIntent
48
+ ? active
49
+ : { ...active, preparingWorktree, submissionIntent };
50
+ }
51
+ return createLocalDispatchSnapshot(input.activeThread, {
52
+ ...options,
53
+ latestUserMessageId: input.latestUserMessageId,
54
+ });
55
+ });
56
+ };
57
+
58
+ return {
59
+ beginLocalDispatch,
60
+ resetLocalDispatch,
61
+ localDispatchStartedAt: activeLocalDispatch?.startedAt ?? null,
62
+ isPreparingWorktree: activeLocalDispatch?.preparingWorktree ?? false,
63
+ isSendBusy: activeLocalDispatch !== null,
64
+ backgroundSubmissionPending: activeLocalDispatch?.submissionIntent === "background",
65
+ };
66
+}