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

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

fix(web): composer banners, menus and pickers act in their handlers (#25238)

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

Julius Marminge committed Oct 25, 2026 at 20:37 UTC f512ff6159ba8d6c0cab4fe66f3c723b50edd2c7
11 files changed +316 -316
apps/web/src/components/chat/ChatComposer.tsx
+11 -13
@@ -2277,7 +2277,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2277 stashQueue,
2278 isStashMenuOpen,
2279 setIsStashMenuOpen,
2280 - stashPulse,
2280 + stashPulseKey,
2281 restoreStashEntryStable,
2282 deleteStashEntryStable,
2283 toggleStashMenuStable,
@@ -2285,26 +2285,25 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
2285 environmentId,
2286 composerDraftTarget,
2287 promptRef,
2288 - composerImagesRef,
2289 - composerFilesRef,
2290 - composerTerminalContextsRef,
2291 - keybindings,
2292 - terminalOpen,
2288 + readAttachmentDraft: () => ({
2289 + images: composerImagesRef.current,
2290 + files: composerFilesRef.current,
2291 + }),
2292 + readTerminalContexts: () => composerTerminalContextsRef.current,
2293 + routeThreadRef,
2294 projectSelectionRequired,
2294 - isRevertingCheckpoint,
2295 pendingUserInputs,
2296 activePendingProgress,
2297 prompt,
2298 composerMenuOpen,
2299 - isComposerModelPickerOpen,
2299 isComposerCollapsedMobile,
2300 composerPreviewAnnotations,
2301 composerReviewComments,
2302 composerThreadContexts,
2304 - attachmentTargetKeyRef,
2305 - composerDraftTargetKeyRef,
2303 + attachmentTargetKey,
2304 + isComposerDraftTargetOpen: (key) => composerDraftTargetKeyRef.current === key,
2305 composerEditorRef,
2307 - isRevertingCheckpointRef,
2306 + isRevertingCheckpoint: () => isRevertingCheckpointRef.current,
2307 pendingThreadImportsRef,
2308 setComposerCursor,
2309 setComposerTrigger,
@@ -3578,8 +3577,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
3577 <ComposerStashBadge
3578 count={stashQueue.length}
3579 menuOpen={isStashMenuOpen}
3581 - pulseKey={stashPulse.key}
3582 - pulsing={stashPulse.active}
3580 + pulseKey={stashPulseKey}
3581 onToggleMenu={toggleStashMenuStable}
3582 />
3583 </ComposerBanner.Dock>
apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx new
+25
@@ -0,0 +1,25 @@
1 +import { InfoIcon } from "lucide-react";
2 +import { expect, it, vi } from "vite-plus/test";
3 +import { userEvent } from "vite-plus/test/browser";
4 +
5 +import { render } from "../../../test/render";
6 +import { ComposerBannerStack, type ComposerBannerStackItem } from "./ComposerBannerStack";
7 +
8 +it("commits a dismissal when the thread switches during the exit transition", async () => {
9 + const onDismiss = vi.fn();
10 + const item: ComposerBannerStackItem = {
11 + id: "notice",
12 + variant: "info",
13 + icon: <InfoIcon />,
14 + title: "Thread A notice",
15 + dismissLabel: "Dismiss notice",
16 + onDismiss,
17 + };
18 + await using screen = await render(<ComposerBannerStack key="thread-a" items={[item]} />);
19 +
20 + await userEvent.click(screen.getByRole("button", { name: "Dismiss notice" }));
21 + // The composer keys the stack by thread, so switching threads remounts it mid-exit.
22 + await screen.rerender(<ComposerBannerStack key="thread-b" items={[]} />);
23 +
24 + await vi.waitFor(() => expect(onDismiss).toHaveBeenCalledTimes(1));
25 +});
apps/web/src/components/chat/ComposerBannerStack.tsx
+18 -35
@@ -1,5 +1,6 @@
1 import { InfoIcon } from "lucide-react";
2 -import { useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } from "react";
2 +import { useId, useLayoutEffect, useRef, useState, type ReactNode } from "react";
3 +import { flushSync } from "react-dom";
4
5 import { cn } from "~/lib/utils";
6 import { Button } from "../ui/button";
@@ -51,39 +52,25 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose
52 const noticesRef = useRef<HTMLDivElement>(null);
53 const peekRef = useRef<HTMLButtonElement>(null);
54 const expandedItemsRef = useRef<HTMLDivElement>(null);
54 - const pendingFocusRef = useRef<"peek" | "notice" | null>(null);
55 const expandedItemsId = useId();
56 const [requestedExitingItemId, setExitingItemId] = useState<string | null>(null);
57 - const dismissTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
57 const exitingItemId =
58 requestedExitingItemId !== null && items.some((item) => item.id === requestedExitingItemId)
59 ? requestedExitingItemId
60 : null;
61
63 - useEffect(() => {
64 - return () => {
65 - if (dismissTimeoutRef.current) {
66 - clearTimeout(dismissTimeoutRef.current);
67 - }
68 - };
69 - }, []);
70 -
62 if (items.length < 2 && stackExpanded) {
63 setStackExpanded(false);
64 }
65
75 - useLayoutEffect(() => {
76 - if (stackExpanded && pendingFocusRef.current === "notice") {
77 - pendingFocusRef.current = null;
78 - const firstControl = expandedItemsRef.current?.querySelector<HTMLElement>(
79 - 'button:not(:disabled), a[href], input:not(:disabled), [tabindex="0"]',
80 - );
81 - (firstControl ?? expandedItemsRef.current)?.focus({ preventScroll: true });
82 - } else if (!stackExpanded && pendingFocusRef.current === "peek") {
83 - pendingFocusRef.current = null;
84 - peekRef.current?.focus({ preventScroll: true });
85 - }
86 - }, [stackExpanded]);
66 + const expandAndFocusNotice = () => {
67 + flushSync(() => setStackExpanded(true));
68 + const container = expandedItemsRef.current;
69 + const firstControl = container?.querySelector<HTMLElement>(
70 + 'button:not(:disabled), a[href], input:not(:disabled), [tabindex="0"]',
71 + );
72 + (firstControl ?? container)?.focus({ preventScroll: true });
73 + };
74
75 const orderedItems = items.toSorted((a, b) => bannerPriority(a) - bannerPriority(b));
76 const frontItem = orderedItems[0];
@@ -106,13 +93,9 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose
93 return;
94 }
95 setExitingItemId(item.id);
109 - if (dismissTimeoutRef.current) {
110 - clearTimeout(dismissTimeoutRef.current);
111 - }
112 - dismissTimeoutRef.current = setTimeout(() => {
113 - dismissTimeoutRef.current = null;
114 - item.onDismiss?.();
115 - }, DISMISS_TRANSITION_MS);
96 + // A timer, not transitionend: the dismissal must commit even when the stack unmounts
97 + // (thread switch) or a collapsed composer hides it mid-exit, and transitionend never fires then.
98 + setTimeout(() => item.onDismiss?.(), DISMISS_TRANSITION_MS);
99 };
100
101 return (
@@ -126,7 +109,8 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose
109 onPointerEnter={(event) => {
110 if (event.pointerType === "touch") return;
111 if (document.activeElement === peekRef.current) {
129 - pendingFocusRef.current = "notice";
112 + expandAndFocusNotice();
113 + return;
114 }
115 setStackExpanded(true);
116 }}
@@ -145,8 +129,8 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose
129 if (event.key !== "Escape" || !stackExpanded) return;
130 event.preventDefault();
131 event.stopPropagation();
148 - pendingFocusRef.current = "peek";
149 - setStackExpanded(false);
132 + flushSync(() => setStackExpanded(false));
133 + peekRef.current?.focus({ preventScroll: true });
134 }}
135 >
136 {showCollapsedStackCap && firstStackedItem ? (
@@ -160,8 +144,7 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose
144 tabIndex={stackExpanded ? -1 : 0}
145 onClick={(event) => {
146 event.currentTarget.focus({ preventScroll: true });
163 - pendingFocusRef.current = "notice";
164 - setStackExpanded(true);
147 + expandAndFocusNotice();
148 }}
149 className={cn(stackExpanded && "pointer-events-none invisible opacity-0")}
150 />
apps/web/src/components/chat/ComposerImageThumbnail.tsx
+19 -14
@@ -1,11 +1,24 @@
1 -import { memo, useEffect, useState, type ReactNode } from "react";
1 +import { memo, Suspense, use, type ReactNode } from "react";
2
3 import {
4 createComposerImageThumbnail,
5 readComposerImageThumbnail,
6 } from "../../lib/imageCompression";
7
8 -export const ComposerImageThumbnail = memo(function ComposerImageThumbnail({
8 +export const ComposerImageThumbnail = memo(function ComposerImageThumbnail(props: {
9 + file: File;
10 + alt: string;
11 + className: string;
12 + fallback: ReactNode;
13 +}) {
14 + return (
15 + <Suspense fallback={props.fallback}>
16 + <ThumbnailImage {...props} />
17 + </Suspense>
18 + );
19 +});
20 +
21 +function ThumbnailImage({
22 file,
23 alt,
24 className,
@@ -16,16 +29,8 @@ export const ComposerImageThumbnail = memo(function ComposerImageThumbnail({
29 className: string;
30 fallback: ReactNode;
31 }) {
19 - const [preview, setPreview] = useState<{ file: File; src: string | null } | null>(null);
20 - useEffect(() => {
21 - let active = true;
22 - void createComposerImageThumbnail(file).then((src) => {
23 - if (active) setPreview({ file, src });
24 - });
25 - return () => {
26 - active = false;
27 - };
28 - }, [file]);
29 - const src = preview?.file === file ? preview.src : (readComposerImageThumbnail(file) ?? null);
32 + // A settled thumbnail paints synchronously instead of suspending for a tick.
33 + const settled = readComposerImageThumbnail(file);
34 + const src = settled === undefined ? use(createComposerImageThumbnail(file)) : settled;
35 return src ? <img src={src} alt={alt} className={className} /> : fallback;
31 -});
36 +}
apps/web/src/components/chat/ComposerStashBadge.tsx
+11 -7
@@ -7,18 +7,20 @@ import { ComposerBanner } from "./ComposerBanner";
7 export const ComposerStashBadge = memo(function ComposerStashBadge(props: {
8 count: number;
9 menuOpen: boolean;
10 + /** Bumped per stash; each new key replays the pulse. 0 means never pulsed. */
11 pulseKey: number;
11 - pulsing: boolean;
12 onToggleMenu: () => void;
13 }) {
14 if (props.count === 0) return null;
15 + const pulsed = props.pulseKey > 0;
16 const count = (
17 <ComposerBanner.Count
18 + // Remounting the count per stash restarts its CSS pulse; no timer has to end it.
19 key={props.pulseKey}
20 className={cn(
19 - props.pulsing
20 - ? "text-primary transition-[opacity,translate] duration-180 ease-out starting:translate-y-0.5 starting:opacity-0 motion-reduce:transition-none"
21 - : "text-muted-foreground",
21 + "text-muted-foreground",
22 + pulsed &&
23 + "animate-stash-pulse-count transition-[opacity,translate] duration-180 ease-out starting:translate-y-0.5 starting:opacity-0 motion-reduce:transition-none",
24 )}
25 >
26 {props.count}
@@ -40,9 +42,11 @@ export const ComposerStashBadge = memo(function ComposerStashBadge(props: {
42 className={cn(
43 "transition-colors duration-200",
44 props.menuOpen && "pointer-events-none",
43 - props.menuOpen || props.pulsing
44 - ? "text-foreground"
45 - : "text-muted-foreground hover:text-foreground",
45 + props.menuOpen ? "text-foreground" : "text-muted-foreground hover:text-foreground",
46 + // The button keeps its identity (focus, hover) across stashes. Swapping between two
47 + // identical keyframes restarts the row's animation instead.
48 + pulsed &&
49 + (props.pulseKey % 2 === 0 ? "animate-stash-pulse-row-alt" : "animate-stash-pulse-row"),
50 )}
51 onPointerDown={(event) => event.preventDefault()}
52 onClick={props.onToggleMenu}
apps/web/src/components/chat/ComposerStashMenu.tsx
+75 -69
@@ -1,5 +1,5 @@
1 import { BookmarkIcon, FileIcon, FileTextIcon } from "lucide-react";
2 -import { memo, useEffect, useRef, useState, type RefObject } from "react";
2 +import { memo, useEffect, useEffectEvent, useRef, useState, type RefObject } from "react";
3 import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
4
5 import { RelativeTime } from "../RelativeTime";
@@ -38,83 +38,89 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
38 onClose: () => void;
39 }) {
40 const { entries, stashShortcutLabel, composerFormRef, onRestore, onDelete, onClose } = props;
41 - const drawerRef = useRef<HTMLDivElement>(null);
41 const [highlightedId, setHighlightedId] = useState<string | null>(entries[0]?.id ?? null);
42
43 const highlightedEntry = entries.find((entry) => entry.id === highlightedId) ?? entries[0];
44 + const drawerRef = useRef<HTMLDivElement>(null);
45
46 - useEffect(() => {
47 - const closeOnOutsidePointer = (event: PointerEvent) => {
48 - const drawer = drawerRef.current;
49 - if (
50 - (drawer && event.composedPath().includes(drawer)) ||
51 - (event.target instanceof Element &&
52 - event.target.closest('[data-prompt-stash-badge="true"]'))
53 - ) {
54 - return;
55 - }
56 - onClose();
57 - };
58 - document.addEventListener("pointerdown", closeOnOutsidePointer, true);
59 - return () => document.removeEventListener("pointerdown", closeOnOutsidePointer, true);
60 - }, [onClose]);
46 + // Both listeners read entries, highlight and callbacks at event time, so they subscribe
47 + // once for the menu's lifetime instead of on every highlight change.
48 + const closeOnOutsidePointer = useEffectEvent((event: PointerEvent) => {
49 + const drawer = drawerRef.current;
50 + if (
51 + (drawer && event.composedPath().includes(drawer)) ||
52 + (event.target instanceof Element && event.target.closest('[data-prompt-stash-badge="true"]'))
53 + ) {
54 + return;
55 + }
56 + onClose();
57 + });
58
62 - useEffect(() => {
63 - const handler = (event: KeyboardEvent) => {
64 - const target = event.target;
65 - if (
66 - !(target instanceof Node) ||
67 - (target !== document.body &&
68 - !(target instanceof Element && target.closest('[data-prompt-stash-badge="true"]')) &&
69 - !drawerRef.current?.contains(target) &&
70 - !composerFormRef.current?.querySelector('textarea, [role="textbox"]')?.contains(target))
71 - ) {
72 - return;
73 - }
74 - if (event.key === "Escape") {
75 - event.preventDefault();
76 - event.stopPropagation();
77 - onClose();
78 - return;
79 - }
80 - if (event.key === "ArrowDown" || event.key === "ArrowUp") {
81 - if (entries.length === 0) return;
82 - event.preventDefault();
83 - event.stopPropagation();
84 - const currentIndex = entries.findIndex((entry) => entry.id === highlightedEntry?.id);
85 - const offset = event.key === "ArrowDown" ? 1 : -1;
86 - const normalizedIndex = currentIndex >= 0 ? currentIndex : offset === 1 ? -1 : 0;
87 - const nextIndex = (normalizedIndex + offset + entries.length) % entries.length;
88 - setHighlightedId(entries[nextIndex]?.id ?? null);
89 - const nextButton =
90 - drawerRef.current?.querySelectorAll<HTMLButtonElement>("[data-stash-restore]")[nextIndex];
91 - nextButton?.scrollIntoView({ block: "nearest" });
92 - if (drawerRef.current?.contains(document.activeElement)) {
93 - nextButton?.focus({ preventScroll: true });
94 - }
95 - return;
59 + const handleKeyDown = useEffectEvent((event: KeyboardEvent) => {
60 + const drawer = drawerRef.current;
61 + if (!drawer) return;
62 + const target = event.target;
63 + if (
64 + !(target instanceof Node) ||
65 + (target !== document.body &&
66 + !(target instanceof Element && target.closest('[data-prompt-stash-badge="true"]')) &&
67 + !drawer.contains(target) &&
68 + !composerFormRef.current?.querySelector('textarea, [role="textbox"]')?.contains(target))
69 + ) {
70 + return;
71 + }
72 + if (event.key === "Escape") {
73 + event.preventDefault();
74 + event.stopPropagation();
75 + onClose();
76 + return;
77 + }
78 + if (event.key === "ArrowDown" || event.key === "ArrowUp") {
79 + if (entries.length === 0) return;
80 + event.preventDefault();
81 + event.stopPropagation();
82 + const currentIndex = entries.findIndex((entry) => entry.id === highlightedEntry?.id);
83 + const offset = event.key === "ArrowDown" ? 1 : -1;
84 + const normalizedIndex = currentIndex >= 0 ? currentIndex : offset === 1 ? -1 : 0;
85 + const nextIndex = (normalizedIndex + offset + entries.length) % entries.length;
86 + setHighlightedId(entries[nextIndex]?.id ?? null);
87 + const nextButton =
88 + drawer.querySelectorAll<HTMLButtonElement>("[data-stash-restore]")[nextIndex];
89 + nextButton?.scrollIntoView({ block: "nearest" });
90 + if (drawer.contains(document.activeElement)) {
91 + nextButton?.focus({ preventScroll: true });
92 }
97 - if (event.key === "Enter") {
98 - // Let the delete button handle Enter instead of restoring its row.
99 - if (event.target instanceof HTMLElement && event.target.closest("button[aria-label]")) {
100 - return;
101 - }
102 - if (!highlightedEntry) return;
103 - event.preventDefault();
104 - event.stopPropagation();
105 - onRestore(highlightedEntry);
93 + return;
94 + }
95 + if (event.key === "Enter") {
96 + // Let the delete button handle Enter instead of restoring its row.
97 + if (event.target instanceof HTMLElement && event.target.closest("button[aria-label]")) {
98 return;
99 }
108 - if (event.key === "Backspace" && (event.metaKey || event.ctrlKey)) {
109 - if (!highlightedEntry) return;
110 - event.preventDefault();
111 - event.stopPropagation();
112 - onDelete(highlightedEntry);
113 - }
100 + if (!highlightedEntry) return;
101 + event.preventDefault();
102 + event.stopPropagation();
103 + onRestore(highlightedEntry);
104 + return;
105 + }
106 + if (event.key === "Backspace" && (event.metaKey || event.ctrlKey)) {
107 + if (!highlightedEntry) return;
108 + event.preventDefault();
109 + event.stopPropagation();
110 + onDelete(highlightedEntry);
111 + }
112 + });
113 +
114 + useEffect(() => {
115 + const onPointerDown = (event: PointerEvent) => closeOnOutsidePointer(event);
116 + const onKeyDown = (event: KeyboardEvent) => handleKeyDown(event);
117 + document.addEventListener("pointerdown", onPointerDown, true);
118 + window.addEventListener("keydown", onKeyDown, true);
119 + return () => {
120 + document.removeEventListener("pointerdown", onPointerDown, true);
121 + window.removeEventListener("keydown", onKeyDown, true);
122 };
115 - window.addEventListener("keydown", handler, true);
116 - return () => window.removeEventListener("keydown", handler, true);
117 - }, [composerFormRef, entries, highlightedEntry, onClose, onDelete, onRestore]);
123 + }, []);
124
125 return (
126 <ComposerBanner.Root ref={drawerRef} data-composer-stash-drawer="true">
apps/web/src/components/chat/DraftHeroHeadline.tsx
+18 -19
@@ -5,7 +5,7 @@ import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/envir
5 import { isScratchProject } from "@t3tools/client-runtime/state/projects";
6 import { FolderPlusIcon } from "lucide-react";
7 import { useAtomValue } from "@effect/atom-react";
8 -import { useEffect, useRef, useState } from "react";
8 +import { useRef, useState } from "react";
9
10 import { openCommandPalette } from "~/commandPaletteBus";
11 import { shortcutLabelForCommand } from "~/keybindings";
@@ -159,21 +159,23 @@ export function DraftHeroHeadline({
159 );
160 const selectedPickerItem = pickerItems.find((item) => item.value === activeProjectKey) ?? null;
161
162 - // Picker changes invalidate pending no-project home continuations.
163 - const latestTargetRef = useRef({ draftId, activeProjectKey, scratchTargetEnvironmentId });
164 - useEffect(() => {
165 - latestTargetRef.current = { draftId, activeProjectKey, scratchTargetEnvironmentId };
166 - }, [activeProjectKey, scratchTargetEnvironmentId, draftId]);
162 + // The picker can change the draft's target while the no-project home is
163 + // still being opened; a stale continuation must not retarget it again. Picking
164 + // a project clears the pending request, and the draft session is compared
165 + // against the store when the scratch project arrives.
166 + const pendingScratchRef = useRef<symbol | null>(null);
167 + const draftTargetKey = () => {
168 + const session = draftId ? useComposerDraftStore.getState().getDraftSession(draftId) : null;
169 + return session
170 + ? `${session.environmentId}:${session.projectId}:${session.logicalProjectKey}`
171 + : null;
172 + };
173 // Retargeting an empty draft would overwrite the project's draft and strand browser tabs.
174 const selectProject = (project: (typeof projects)[number], logicalProjectKey: string) => {
175 if (!draftId) {
176 return;
177 }
172 - latestTargetRef.current = {
173 - draftId,
174 - activeProjectKey: logicalProjectKey,
175 - scratchTargetEnvironmentId: project.environmentId,
176 - };
178 + pendingScratchRef.current = null;
179 const currentDraft = getComposerDraft(draftId);
180 if (!composerDraftHasUserContent(currentDraft)) {
181 void openProjectDraft(scopeProjectRef(project.environmentId, project.id));
@@ -204,17 +206,14 @@ export function DraftHeroHeadline({
206 if (scratchTargetEnvironmentId === null || isScratchDraft) {
207 return false;
208 }
207 - const requested = { draftId, activeProjectKey, scratchTargetEnvironmentId };
209 + const request = Symbol("scratch");
210 + pendingScratchRef.current = request;
211 + const requestedTarget = draftTargetKey();
212 const project = await openScratchProject(scratchTargetEnvironmentId);
209 - const latest = latestTargetRef.current;
210 - if (
211 - !project ||
212 - latest.draftId !== requested.draftId ||
213 - latest.activeProjectKey !== requested.activeProjectKey ||
214 - latest.scratchTargetEnvironmentId !== requested.scratchTargetEnvironmentId
215 - ) {
213 + if (!project || pendingScratchRef.current !== request || draftTargetKey() !== requestedTarget) {
214 return false;
215 }
216 + pendingScratchRef.current = null;
217 selectProject(project, deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings));
218 return true;
219 };
apps/web/src/components/chat/ModelPickerContent.tsx
+3 -15
@@ -355,8 +355,11 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
355 onOpenProviderSetup?: (instanceId: ProviderInstanceId) => void;
356 getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
357 onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
358 + /** The owning popup moves focus here when it opens (its `initialFocus`). */
359 + searchInputRef: RefObject<HTMLInputElement | null>;
360 }) {
361 const {
362 + searchInputRef,
363 keybindings: providedKeybindings,
364 modelOptionsByInstance,
365 instanceEntries,
@@ -367,7 +370,6 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
370 onOpenProviderSetup,
371 } = props;
372 const [searchQuery, setSearchQuery] = useState("");
370 - const searchInputRef = useRef<HTMLInputElement>(null);
373 const modelListRef = useRef<LegendListRef | null>(null);
374 const pickerContentRef = useRef<HTMLDivElement>(null);
375 const highlightedModelKeyRef = useRef<string | null>(null);
@@ -453,20 +455,6 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
455 });
456 };
457
456 - useLayoutEffect(() => {
457 - focusSearchInput();
458 - const frame = window.requestAnimationFrame(() => {
459 - focusSearchInput();
460 - });
461 - const timeout = window.setTimeout(() => {
462 - focusSearchInput();
463 - }, 0);
464 - return () => {
465 - window.cancelAnimationFrame(frame);
466 - window.clearTimeout(timeout);
467 - };
468 - }, [focusSearchInput]);
469 -
458 const toggleLegacySection = (instanceId: ProviderInstanceId) => {
459 setExpandedLegacyInstances((expanded) => {
460 const next = new Set(expanded);
apps/web/src/components/chat/ProviderModelPicker.tsx
+51 -49
@@ -5,7 +5,7 @@ import {
5 type ProviderDriverKind,
6 type ResolvedKeybindingsConfig,
7 } from "@t3tools/contracts";
8 -import { memo, useEffect, useState } from "react";
8 +import { memo, useRef, useState } from "react";
9 import { Badge } from "../ui/badge";
10 import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
11 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -27,6 +27,52 @@ import {
27 import { useComposerMenuProps } from "./composerEventScope";
28 import { shortcutLabelForCommand } from "../../keybindings";
29
30 +/** Holds the page still behind the open picker; its lifetime is the popup element's. */
31 +function lockBackgroundScroll(popup: HTMLElement | null) {
32 + if (!popup) return;
33 + const { documentElement, body } = document;
34 + const previousDocumentOverscrollBehavior = documentElement.style.overscrollBehavior;
35 + const previousBodyOverflow = body.style.overflow;
36 + const previousBodyPaddingRight = body.style.paddingRight;
37 + const scrollbarWidth = window.innerWidth - documentElement.clientWidth;
38 +
39 + documentElement.style.overscrollBehavior = "contain";
40 + body.style.overflow = "hidden";
41 + if (scrollbarWidth > 0) {
42 + body.style.paddingRight = `${scrollbarWidth}px`;
43 + }
44 +
45 + const shouldAllowOverlayScroll = (target: EventTarget | null) => {
46 + return target instanceof Element && target.closest("[data-model-picker-content]");
47 + };
48 + const preventBackgroundWheel = (event: WheelEvent) => {
49 + if (shouldAllowOverlayScroll(event.target)) {
50 + return;
51 + }
52 + event.preventDefault();
53 + };
54 + const preventBackgroundTouchMove = (event: TouchEvent) => {
55 + if (shouldAllowOverlayScroll(event.target)) {
56 + return;
57 + }
58 + event.preventDefault();
59 + };
60 +
61 + document.addEventListener("wheel", preventBackgroundWheel, { capture: true, passive: false });
62 + document.addEventListener("touchmove", preventBackgroundTouchMove, {
63 + capture: true,
64 + passive: false,
65 + });
66 +
67 + return () => {
68 + document.removeEventListener("wheel", preventBackgroundWheel, { capture: true });
69 + document.removeEventListener("touchmove", preventBackgroundTouchMove, { capture: true });
70 + documentElement.style.overscrollBehavior = previousDocumentOverscrollBehavior;
71 + body.style.overflow = previousBodyOverflow;
72 + body.style.paddingRight = previousBodyPaddingRight;
73 + };
74 +}
75 +
76 export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
77 environmentId: EnvironmentId | null;
78 activeInstanceId: ProviderInstanceId;
@@ -57,6 +103,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
103 const composerFloatingLayerProps = useComposerMenuProps();
104 const [uncontrolledIsMenuOpen, setUncontrolledIsMenuOpen] = useState(false);
105 const isMenuOpen = props.open ?? uncontrolledIsMenuOpen;
106 + const searchInputRef = useRef<HTMLInputElement>(null);
107 const size = props.size ?? "sm";
108
109 const activeEntry =
@@ -91,54 +138,6 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
138 }
139 };
140
94 - useEffect(() => {
95 - if (!isMenuOpen) {
96 - return;
97 - }
98 -
99 - const { documentElement, body } = document;
100 - const previousDocumentOverscrollBehavior = documentElement.style.overscrollBehavior;
101 - const previousBodyOverflow = body.style.overflow;
102 - const previousBodyPaddingRight = body.style.paddingRight;
103 - const scrollbarWidth = window.innerWidth - documentElement.clientWidth;
104 -
105 - documentElement.style.overscrollBehavior = "contain";
106 - body.style.overflow = "hidden";
107 - if (scrollbarWidth > 0) {
108 - body.style.paddingRight = `${scrollbarWidth}px`;
109 - }
110 -
111 - const shouldAllowOverlayScroll = (target: EventTarget | null) => {
112 - return target instanceof Element && target.closest("[data-model-picker-content]");
113 - };
114 - const preventBackgroundWheel = (event: WheelEvent) => {
115 - if (shouldAllowOverlayScroll(event.target)) {
116 - return;
117 - }
118 - event.preventDefault();
119 - };
120 - const preventBackgroundTouchMove = (event: TouchEvent) => {
121 - if (shouldAllowOverlayScroll(event.target)) {
122 - return;
123 - }
124 - event.preventDefault();
125 - };
126 -
127 - document.addEventListener("wheel", preventBackgroundWheel, { capture: true, passive: false });
128 - document.addEventListener("touchmove", preventBackgroundTouchMove, {
129 - capture: true,
130 - passive: false,
131 - });
132 -
133 - return () => {
134 - document.removeEventListener("wheel", preventBackgroundWheel, { capture: true });
135 - document.removeEventListener("touchmove", preventBackgroundTouchMove, { capture: true });
136 - documentElement.style.overscrollBehavior = previousDocumentOverscrollBehavior;
137 - body.style.overflow = previousBodyOverflow;
138 - body.style.paddingRight = previousBodyPaddingRight;
139 - };
140 - }, [isMenuOpen]);
141 -
141 const handleInstanceModelChange = (instanceId: ProviderInstanceId, model: string) => {
142 if (props.disabled) return;
143 props.onInstanceModelChange(instanceId, model);
@@ -275,12 +274,15 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
274 </PopoverTrigger>
275 <PopoverPopup
276 {...(props.isComposerOwned ? composerFloatingLayerProps : {})}
277 + ref={lockBackgroundScroll}
278 + initialFocus={searchInputRef}
279 align="start"
280 className="before:hidden"
281 padding="none"
282 touchBackdrop
283 >
284 <ModelPickerContent
285 + searchInputRef={searchInputRef}
286 environmentId={props.environmentId}
287 activeInstanceId={activeInstanceId}
288 model={props.model}
apps/web/src/components/chat/useComposerStash.ts
+62 -95
@@ -8,6 +8,7 @@ import {
8 } from "@t3tools/contracts";
9 import {
10 type ComposerFileAttachment,
11 + type ComposerThreadDraftState,
12 type PersistedComposerFileAttachment,
13 type PersistedComposerImageAttachment,
14 composerFileDedupKey,
@@ -29,7 +30,6 @@ import { type ReviewCommentContext } from "../../reviewCommentContext";
30 import { collapseExpandedComposerCursor } from "../../composer-logic";
31 import { compressImageForStash } from "../../lib/imageCompression";
32 import { formatInlineContextReference } from "~/lib/composerContextReferences";
32 -import { getTerminalFocusOwner } from "../../lib/terminalFocus";
33 import { isCommandPaletteOpen } from "../../commandPaletteBus";
34 import { pendingDraftWork } from "./pendingDraftWork";
35 import {
@@ -47,7 +47,8 @@ import {
47 import { remainingComposerAttachmentSlots } from "./composerThreadImport";
48 import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
49 import { resizeSnapShotSource } from "../../lib/snapShotSource";
50 -import { resolveShortcutCommand } from "../../keybindings";
50 +import { registerCommands } from "../../shortcuts/dispatcher";
51 +import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../../terminalUiStateStore";
52 import { toastManager } from "../ui/toast";
53 import type { useComposerTriggerState } from "./useComposerTriggerState";
54 import {
@@ -70,26 +71,22 @@ export function useComposerStash(input: {
71 readonly environmentId: EnvironmentId;
72 readonly composerDraftTarget: ChatComposerProps["composerDraftTarget"];
73 readonly promptRef: ChatComposerProps["promptRef"];
73 - readonly composerImagesRef: ChatComposerProps["composerImagesRef"];
74 - readonly composerFilesRef: ChatComposerProps["composerFilesRef"];
75 - readonly composerTerminalContextsRef: ChatComposerProps["composerTerminalContextsRef"];
76 - readonly keybindings: ChatComposerProps["keybindings"];
77 - readonly terminalOpen: boolean;
74 + readonly readAttachmentDraft: () => Pick<ComposerThreadDraftState, "images" | "files">;
75 + readonly readTerminalContexts: () => ComposerThreadDraftState["terminalContexts"];
76 + readonly routeThreadRef: ChatComposerProps["routeThreadRef"];
77 readonly projectSelectionRequired: boolean;
79 - readonly isRevertingCheckpoint: boolean;
78 readonly pendingUserInputs: ReadonlyArray<PendingUserInput>;
79 readonly activePendingProgress: ChatComposerProps["activePendingProgress"];
80 readonly prompt: string;
81 readonly composerMenuOpen: boolean;
84 - readonly isComposerModelPickerOpen: boolean;
82 readonly isComposerCollapsedMobile: boolean;
83 readonly composerPreviewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
84 readonly composerReviewComments: ReadonlyArray<ReviewCommentContext>;
85 readonly composerThreadContexts: ReadonlyArray<ThreadContextRecord>;
89 - readonly attachmentTargetKeyRef: RefObject<string>;
90 - readonly composerDraftTargetKeyRef: RefObject<string>;
86 + readonly attachmentTargetKey: string;
87 + readonly isComposerDraftTargetOpen: (targetKey: string) => boolean;
88 readonly composerEditorRef: RefObject<ComposerPromptEditorHandle | null>;
92 - readonly isRevertingCheckpointRef: RefObject<boolean>;
89 + readonly isRevertingCheckpoint: () => boolean;
90 readonly pendingThreadImportsRef: RefObject<Map<string, number>>;
91 readonly setComposerCursor: Dispatch<SetStateAction<number>>;
92 readonly setComposerTrigger: ReturnType<typeof useComposerTriggerState>["setTrigger"];
@@ -104,26 +101,22 @@ export function useComposerStash(input: {
101 environmentId,
102 composerDraftTarget,
103 promptRef,
107 - composerImagesRef,
108 - composerFilesRef,
109 - composerTerminalContextsRef,
110 - keybindings,
111 - terminalOpen,
104 + readAttachmentDraft,
105 + readTerminalContexts,
106 + routeThreadRef,
107 projectSelectionRequired,
113 - isRevertingCheckpoint,
108 pendingUserInputs,
109 activePendingProgress,
110 prompt,
111 composerMenuOpen,
118 - isComposerModelPickerOpen,
112 isComposerCollapsedMobile,
113 composerPreviewAnnotations,
114 composerReviewComments,
115 composerThreadContexts,
123 - attachmentTargetKeyRef,
124 - composerDraftTargetKeyRef,
116 + attachmentTargetKey,
117 + isComposerDraftTargetOpen,
118 composerEditorRef,
126 - isRevertingCheckpointRef,
119 + isRevertingCheckpoint,
120 pendingThreadImportsRef,
121 setComposerCursor,
122 setComposerTrigger,
@@ -148,12 +141,8 @@ export function useComposerStash(input: {
141 );
142 const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts);
143 const [isStashMenuOpen, setIsStashMenuOpen] = useState(false);
151 - const [stashPulse, setStashPulse] = useState<{ key: number; active: boolean }>({
152 - key: 0,
153 - active: false,
154 - });
155 - const stashPulseKeyRef = useRef(0);
156 - const stashPulseTimeoutRef = useRef<number | null>(null);
144 + // Each stash bumps the key; the badge replays its one-shot pulse animation per key.
145 + const [stashPulseKey, setStashPulseKey] = useState(0);
146 const stashInFlightRef = useRef<Set<string>>(new Set());
147
148 const stashQueue = usePromptStashStore((state) => state.entries);
@@ -161,24 +150,8 @@ export function useComposerStash(input: {
150 const takeStashEntry = usePromptStashStore((state) => state.takeEntry);
151 const finalizeStashEntryImages = usePromptStashStore((state) => state.finalizeEntryImages);
152
164 - useEffect(() => {
165 - return () => {
166 - if (stashPulseTimeoutRef.current !== null) {
167 - window.clearTimeout(stashPulseTimeoutRef.current);
168 - }
169 - };
170 - }, []);
171 -
153 const pulseStashBadge = () => {
173 - stashPulseKeyRef.current += 1;
174 - setStashPulse({ key: stashPulseKeyRef.current, active: true });
175 - if (stashPulseTimeoutRef.current !== null) {
176 - window.clearTimeout(stashPulseTimeoutRef.current);
177 - }
178 - stashPulseTimeoutRef.current = window.setTimeout(() => {
179 - stashPulseTimeoutRef.current = null;
180 - setStashPulse((current) => ({ ...current, active: false }));
181 - }, 1200);
154 + setStashPulseKey((key) => key + 1);
155 };
156
157 const restoreStashEntry = async (menuEntry: PromptStashEntry) => {
@@ -212,8 +185,8 @@ export function useComposerStash(input: {
185 // prompt with this invocation's captured target. Nothing was taken yet,
186 // so abort and leave the entry restorable where the user now is.
187 if (
215 - isRevertingCheckpointRef.current ||
216 - composerTargetKey(composerDraftTarget) !== composerDraftTargetKeyRef.current
188 + isRevertingCheckpoint() ||
189 + !isComposerDraftTargetOpen(composerTargetKey(composerDraftTarget))
190 ) {
191 return;
192 }
@@ -263,7 +236,7 @@ export function useComposerStash(input: {
236 let restoredFileCount = 0;
237 const stashedFiles = entry.files ?? [];
238 if (stashedFiles.length > 0) {
266 - const composerFilesNow = composerFilesRef.current;
239 + const composerFilesNow = readAttachmentDraft().files;
240 const existingFileIds = new Set(composerFilesNow.map((file) => file.id));
241 const retainedUploadIds = new Set(
242 composerFilesNow.flatMap((file) =>
@@ -329,7 +302,7 @@ export function useComposerStash(input: {
302 appendedFiles.push(restored);
303 }
304 const capacity = remainingComposerAttachmentSlots(
332 - composerImagesRef.current.length + composerFilesNow.length,
305 + readAttachmentDraft().images.length + composerFilesNow.length,
306 pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
307 );
308 const filesToAppend = appendedFiles.slice(0, capacity);
@@ -373,18 +346,19 @@ export function useComposerStash(input: {
346
347 let unrestoredImageNames: string[] = [];
348 if (entry.attachments.length > 0) {
376 - const existingIds = new Set(composerImagesRef.current.map((image) => image.id));
349 + const attachmentDraft = readAttachmentDraft();
350 + const existingIds = new Set(attachmentDraft.images.map((image) => image.id));
351 // The draft store also dedupes by mimeType+sizeBytes+name, so filter
352 // on the same key here. Counting a duplicate against capacity would
353 // burn a slot the store then refuses to fill, pushing a genuinely
354 // unique image into the overflow list for nothing.
355 const existingDedupKeys = new Set(
382 - composerImagesRef.current.map(
356 + attachmentDraft.images.map(
357 (image) => `${image.mimeType}\0${image.sizeBytes}\0${image.name}`,
358 ),
359 );
360 const capacity = remainingComposerAttachmentSlots(
387 - composerImagesRef.current.length + composerFilesRef.current.length + restoredFileCount,
361 + attachmentDraft.images.length + attachmentDraft.files.length + restoredFileCount,
362 pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
363 );
364 const pending = entry.attachments.filter(
@@ -472,7 +446,7 @@ export function useComposerStash(input: {
446 const stashCurrentPrompt = async () => {
447 // Stashing clears the draft. A pasted attachment still downloading would then land in the
448 // emptied composer instead of travelling with the entry it belongs to.
475 - if (pendingDraftWork.has(attachmentTargetKeyRef.current)) {
449 + if (pendingDraftWork.has(attachmentTargetKey)) {
450 toastManager.add({
451 type: "info",
452 title: "Still bringing attached context into this message.",
@@ -481,11 +455,12 @@ export function useComposerStash(input: {
455 return;
456 }
457 const prompt = promptRef.current.trim();
484 - const images = [...composerImagesRef.current];
485 - const files = [...composerFilesRef.current];
458 + const attachmentDraft = readAttachmentDraft();
459 + const images = [...attachmentDraft.images];
460 + const files = [...attachmentDraft.files];
461 const stashedRecords: ComposerContextRecord[] = [
462 ...composerThreadContexts,
488 - ...composerTerminalContextsRef.current.map(terminalContextRecord),
463 + ...readTerminalContexts().map(terminalContextRecord),
464 ...composerReviewComments.map(reviewCommentContextRecord),
465 ...composerPreviewAnnotations.map((annotation) =>
466 previewAnnotationContextRecord(annotation, {
@@ -693,53 +668,45 @@ export function useComposerStash(input: {
668 if (stashMenuClosesOn.prompt !== prompt || composerMenuOpen) setIsStashMenuOpen(false);
669 }
670
671 + // Read at event time, so the scope registers once per mounted composer instead of
672 + // re-registering (and reshuffling capture-scope priority) whenever a guard flips.
673 + const handleStashShortcut = useStableCallback((event: KeyboardEvent) => {
674 + // Always claim the shortcut so the browser save dialog never opens,
675 + // even when the composer is in a state that can't stash.
676 + event.preventDefault();
677 + event.stopPropagation();
678 + if (isCommandPaletteOpen() || isRevertingCheckpoint()) return;
679 + if (pendingUserInputs.length > 0) {
680 + setIsStashMenuOpen((open) => !open);
681 + return;
682 + }
683 + if (projectSelectionRequired || activePendingProgress !== null) return;
684 + void stashCurrentPromptStable();
685 + });
686 + // Capture phase while the composer is mounted, so Mod+S never reaches the browser's save
687 + // dialog even when a focused widget (the model picker search) stops the key.
688 const backgroundThread = use(BackgroundThreadContext);
689 + const readShortcutContext = useStableCallback(() => ({
690 + terminalOpen: Boolean(
691 + selectThreadTerminalUiState(
692 + useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
693 + routeThreadRef,
694 + ).terminalOpen,
695 + ),
696 + }));
697 useEffect(() => {
698 if (backgroundThread) return;
699 - const handler = (event: globalThis.KeyboardEvent) => {
700 - const command = resolveShortcutCommand(event, keybindings, {
701 - context: {
702 - terminalFocus: getTerminalFocusOwner() !== null,
703 - terminalOpen,
704 - modelPickerOpen: isComposerModelPickerOpen,
705 - },
706 - });
707 - if (command !== "composer.stash") return;
708 - // Always claim the shortcut so the browser save dialog never opens,
709 - // even when the composer is in a state that can't stash.
710 - event.preventDefault();
711 - event.stopPropagation();
712 - if (isCommandPaletteOpen() || isRevertingCheckpoint) {
713 - return;
714 - }
715 - if (pendingUserInputs.length > 0) {
716 - setIsStashMenuOpen((open) => !open);
717 - return;
718 - }
719 - if (projectSelectionRequired || activePendingProgress !== null) {
720 - return;
721 - }
722 - void stashCurrentPromptStable();
723 - };
724 - window.addEventListener("keydown", handler, true);
725 - return () => window.removeEventListener("keydown", handler, true);
726 - }, [
727 - activePendingProgress,
728 - backgroundThread,
729 - isComposerModelPickerOpen,
730 - keybindings,
731 - pendingUserInputs.length,
732 - projectSelectionRequired,
733 - stashCurrentPromptStable,
734 - isRevertingCheckpoint,
735 - terminalOpen,
736 - ]);
699 + return registerCommands(
700 + { "composer.stash": handleStashShortcut },
701 + { capture: true, context: readShortcutContext },
702 + );
703 + }, [backgroundThread, handleStashShortcut, readShortcutContext]);
704
705 return {
706 stashQueue,
707 isStashMenuOpen,
708 setIsStashMenuOpen,
742 - stashPulse,
709 + stashPulseKey,
710 restoreStashEntryStable,
711 deleteStashEntryStable,
712 toggleStashMenuStable,
apps/web/src/index.css
+23
@@ -226,6 +226,11 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
226 compositor updates discrete frames instead of every vsync. */
227 --animate-status-pulse: status-pulse 2s infinite;
228 --animate-status-ping: status-ping 2s infinite;
229 + /* Stash pulses hold a highlight for 1.2s; the row then eases back over 200ms, the count snaps.
230 + The row alternates two identical keyframes so each stash restarts it without a remount. */
231 + --animate-stash-pulse-row: stash-pulse-row 1400ms;
232 + --animate-stash-pulse-row-alt: stash-pulse-row-alt 1400ms;
233 + --animate-stash-pulse-count: stash-pulse-count 1400ms step-start;
234 --color-warning-foreground: var(--warning-foreground);
235 --color-warning: var(--warning);
236 --color-warning-surface: var(--warning-surface);
@@ -310,6 +315,24 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
315 opacity: 1;
316 }
317 }
318 + @keyframes stash-pulse-row {
319 + from,
320 + 85.7% {
321 + color: var(--color-foreground);
322 + }
323 + }
324 + @keyframes stash-pulse-row-alt {
325 + from,
326 + 85.7% {
327 + color: var(--color-foreground);
328 + }
329 + }
330 + @keyframes stash-pulse-count {
331 + from,
332 + 85.7% {
333 + color: var(--color-primary);
334 + }
335 + }
336 @keyframes status-pulse {
337 0%,
338 40% {