Skip to content
TypeScript

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

Julius Marmingef512ff6159ba
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index 9932df357a1..2420604c8aa 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -2277,7 +2277,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
stashQueue,
isStashMenuOpen,
setIsStashMenuOpen,
- stashPulse,
+ stashPulseKey,
restoreStashEntryStable,
deleteStashEntryStable,
toggleStashMenuStable,
@@ -2285,26 +2285,25 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
environmentId,
composerDraftTarget,
promptRef,
- composerImagesRef,
- composerFilesRef,
- composerTerminalContextsRef,
- keybindings,
- terminalOpen,
+ readAttachmentDraft: () => ({
+ images: composerImagesRef.current,
+ files: composerFilesRef.current,
+ }),
+ readTerminalContexts: () => composerTerminalContextsRef.current,
+ routeThreadRef,
projectSelectionRequired,
- isRevertingCheckpoint,
pendingUserInputs,
activePendingProgress,
prompt,
composerMenuOpen,
- isComposerModelPickerOpen,
isComposerCollapsedMobile,
composerPreviewAnnotations,
composerReviewComments,
composerThreadContexts,
- attachmentTargetKeyRef,
- composerDraftTargetKeyRef,
+ attachmentTargetKey,
+ isComposerDraftTargetOpen: (key) => composerDraftTargetKeyRef.current === key,
composerEditorRef,
- isRevertingCheckpointRef,
+ isRevertingCheckpoint: () => isRevertingCheckpointRef.current,
pendingThreadImportsRef,
setComposerCursor,
setComposerTrigger,
@@ -3578,8 +3577,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
<ComposerStashBadge
count={stashQueue.length}
menuOpen={isStashMenuOpen}
- pulseKey={stashPulse.key}
- pulsing={stashPulse.active}
+ pulseKey={stashPulseKey}
onToggleMenu={toggleStashMenuStable}
/>
</ComposerBanner.Dock>
diff --git a/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx b/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx
new file mode 100644
index 00000000000..e64d52850eb
--- /dev/null
+++ b/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx
@@ -0,0 +1,25 @@
+import { InfoIcon } from "lucide-react";
+import { expect, it, vi } from "vite-plus/test";
+import { userEvent } from "vite-plus/test/browser";
+
+import { render } from "../../../test/render";
+import { ComposerBannerStack, type ComposerBannerStackItem } from "./ComposerBannerStack";
+
+it("commits a dismissal when the thread switches during the exit transition", async () => {
+ const onDismiss = vi.fn();
+ const item: ComposerBannerStackItem = {
+ id: "notice",
+ variant: "info",
+ icon: <InfoIcon />,
+ title: "Thread A notice",
+ dismissLabel: "Dismiss notice",
+ onDismiss,
+ };
+ await using screen = await render(<ComposerBannerStack key="thread-a" items={[item]} />);
+
+ await userEvent.click(screen.getByRole("button", { name: "Dismiss notice" }));
+ // The composer keys the stack by thread, so switching threads remounts it mid-exit.
+ await screen.rerender(<ComposerBannerStack key="thread-b" items={[]} />);
+
+ await vi.waitFor(() => expect(onDismiss).toHaveBeenCalledTimes(1));
+});
diff --git a/apps/web/src/components/chat/ComposerBannerStack.tsx b/apps/web/src/components/chat/ComposerBannerStack.tsx
index 530415424a5..8661d5df09c 100644
--- a/apps/web/src/components/chat/ComposerBannerStack.tsx
+++ b/apps/web/src/components/chat/ComposerBannerStack.tsx
@@ -1,5 +1,6 @@
import { InfoIcon } from "lucide-react";
-import { useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } from "react";
+import { useId, useLayoutEffect, useRef, useState, type ReactNode } from "react";
+import { flushSync } from "react-dom";
import { cn } from "~/lib/utils";
import { Button } from "../ui/button";
@@ -51,39 +52,25 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose
const noticesRef = useRef<HTMLDivElement>(null);
const peekRef = useRef<HTMLButtonElement>(null);
const expandedItemsRef = useRef<HTMLDivElement>(null);
- const pendingFocusRef = useRef<"peek" | "notice" | null>(null);
const expandedItemsId = useId();
const [requestedExitingItemId, setExitingItemId] = useState<string | null>(null);
- const dismissTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const exitingItemId =
requestedExitingItemId !== null && items.some((item) => item.id === requestedExitingItemId)
? requestedExitingItemId
: null;
- useEffect(() => {
- return () => {
- if (dismissTimeoutRef.current) {
- clearTimeout(dismissTimeoutRef.current);
- }
- };
- }, []);
-
if (items.length < 2 && stackExpanded) {
setStackExpanded(false);
}
- useLayoutEffect(() => {
- if (stackExpanded && pendingFocusRef.current === "notice") {
- pendingFocusRef.current = null;
- const firstControl = expandedItemsRef.current?.querySelector<HTMLElement>(
- 'button:not(:disabled), a[href], input:not(:disabled), [tabindex="0"]',
- );
- (firstControl ?? expandedItemsRef.current)?.focus({ preventScroll: true });
- } else if (!stackExpanded && pendingFocusRef.current === "peek") {
- pendingFocusRef.current = null;
- peekRef.current?.focus({ preventScroll: true });
- }
- }, [stackExpanded]);
+ const expandAndFocusNotice = () => {
+ flushSync(() => setStackExpanded(true));
+ const container = expandedItemsRef.current;
+ const firstControl = container?.querySelector<HTMLElement>(
+ 'button:not(:disabled), a[href], input:not(:disabled), [tabindex="0"]',
+ );
+ (firstControl ?? container)?.focus({ preventScroll: true });
+ };
const orderedItems = items.toSorted((a, b) => bannerPriority(a) - bannerPriority(b));
const frontItem = orderedItems[0];
@@ -106,13 +93,9 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose
return;
}
setExitingItemId(item.id);
- if (dismissTimeoutRef.current) {
- clearTimeout(dismissTimeoutRef.current);
- }
- dismissTimeoutRef.current = setTimeout(() => {
- dismissTimeoutRef.current = null;
- item.onDismiss?.();
- }, DISMISS_TRANSITION_MS);
+ // A timer, not transitionend: the dismissal must commit even when the stack unmounts
+ // (thread switch) or a collapsed composer hides it mid-exit, and transitionend never fires then.
+ setTimeout(() => item.onDismiss?.(), DISMISS_TRANSITION_MS);
};
return (
@@ -126,7 +109,8 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose
onPointerEnter={(event) => {
if (event.pointerType === "touch") return;
if (document.activeElement === peekRef.current) {
- pendingFocusRef.current = "notice";
+ expandAndFocusNotice();
+ return;
}
setStackExpanded(true);
}}
@@ -145,8 +129,8 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose
if (event.key !== "Escape" || !stackExpanded) return;
event.preventDefault();
event.stopPropagation();
- pendingFocusRef.current = "peek";
- setStackExpanded(false);
+ flushSync(() => setStackExpanded(false));
+ peekRef.current?.focus({ preventScroll: true });
}}
>
{showCollapsedStackCap && firstStackedItem ? (
@@ -160,8 +144,7 @@ export function ComposerBannerStack({ className, items, attachedAbove }: Compose
tabIndex={stackExpanded ? -1 : 0}
onClick={(event) => {
event.currentTarget.focus({ preventScroll: true });
- pendingFocusRef.current = "notice";
- setStackExpanded(true);
+ expandAndFocusNotice();
}}
className={cn(stackExpanded && "pointer-events-none invisible opacity-0")}
/>
diff --git a/apps/web/src/components/chat/ComposerImageThumbnail.tsx b/apps/web/src/components/chat/ComposerImageThumbnail.tsx
index 31fff763a67..e9de2aa93b3 100644
--- a/apps/web/src/components/chat/ComposerImageThumbnail.tsx
+++ b/apps/web/src/components/chat/ComposerImageThumbnail.tsx
@@ -1,11 +1,24 @@
-import { memo, useEffect, useState, type ReactNode } from "react";
+import { memo, Suspense, use, type ReactNode } from "react";
import {
createComposerImageThumbnail,
readComposerImageThumbnail,
} from "../../lib/imageCompression";
-export const ComposerImageThumbnail = memo(function ComposerImageThumbnail({
+export const ComposerImageThumbnail = memo(function ComposerImageThumbnail(props: {
+ file: File;
+ alt: string;
+ className: string;
+ fallback: ReactNode;
+}) {
+ return (
+ <Suspense fallback={props.fallback}>
+ <ThumbnailImage {...props} />
+ </Suspense>
+ );
+});
+
+function ThumbnailImage({
file,
alt,
className,
@@ -16,16 +29,8 @@ export const ComposerImageThumbnail = memo(function ComposerImageThumbnail({
className: string;
fallback: ReactNode;
}) {
- const [preview, setPreview] = useState<{ file: File; src: string | null } | null>(null);
- useEffect(() => {
- let active = true;
- void createComposerImageThumbnail(file).then((src) => {
- if (active) setPreview({ file, src });
- });
- return () => {
- active = false;
- };
- }, [file]);
- const src = preview?.file === file ? preview.src : (readComposerImageThumbnail(file) ?? null);
+ // A settled thumbnail paints synchronously instead of suspending for a tick.
+ const settled = readComposerImageThumbnail(file);
+ const src = settled === undefined ? use(createComposerImageThumbnail(file)) : settled;
return src ? <img src={src} alt={alt} className={className} /> : fallback;
-});
+}
diff --git a/apps/web/src/components/chat/ComposerStashBadge.tsx b/apps/web/src/components/chat/ComposerStashBadge.tsx
index 637152106d3..9f196a2879c 100644
--- a/apps/web/src/components/chat/ComposerStashBadge.tsx
+++ b/apps/web/src/components/chat/ComposerStashBadge.tsx
@@ -7,18 +7,20 @@ import { ComposerBanner } from "./ComposerBanner";
export const ComposerStashBadge = memo(function ComposerStashBadge(props: {
count: number;
menuOpen: boolean;
+ /** Bumped per stash; each new key replays the pulse. 0 means never pulsed. */
pulseKey: number;
- pulsing: boolean;
onToggleMenu: () => void;
}) {
if (props.count === 0) return null;
+ const pulsed = props.pulseKey > 0;
const count = (
<ComposerBanner.Count
+ // Remounting the count per stash restarts its CSS pulse; no timer has to end it.
key={props.pulseKey}
className={cn(
- props.pulsing
- ? "text-primary transition-[opacity,translate] duration-180 ease-out starting:translate-y-0.5 starting:opacity-0 motion-reduce:transition-none"
- : "text-muted-foreground",
+ "text-muted-foreground",
+ pulsed &&
+ "animate-stash-pulse-count transition-[opacity,translate] duration-180 ease-out starting:translate-y-0.5 starting:opacity-0 motion-reduce:transition-none",
)}
>
{props.count}
@@ -40,9 +42,11 @@ export const ComposerStashBadge = memo(function ComposerStashBadge(props: {
className={cn(
"transition-colors duration-200",
props.menuOpen && "pointer-events-none",
- props.menuOpen || props.pulsing
- ? "text-foreground"
- : "text-muted-foreground hover:text-foreground",
+ props.menuOpen ? "text-foreground" : "text-muted-foreground hover:text-foreground",
+ // The button keeps its identity (focus, hover) across stashes. Swapping between two
+ // identical keyframes restarts the row's animation instead.
+ pulsed &&
+ (props.pulseKey % 2 === 0 ? "animate-stash-pulse-row-alt" : "animate-stash-pulse-row"),
)}
onPointerDown={(event) => event.preventDefault()}
onClick={props.onToggleMenu}
diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx
index 03096bdc446..2f135cd1e34 100644
--- a/apps/web/src/components/chat/ComposerStashMenu.tsx
+++ b/apps/web/src/components/chat/ComposerStashMenu.tsx
@@ -1,5 +1,5 @@
import { BookmarkIcon, FileIcon, FileTextIcon } from "lucide-react";
-import { memo, useEffect, useRef, useState, type RefObject } from "react";
+import { memo, useEffect, useEffectEvent, useRef, useState, type RefObject } from "react";
import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
import { RelativeTime } from "../RelativeTime";
@@ -38,83 +38,89 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: {
onClose: () => void;
}) {
const { entries, stashShortcutLabel, composerFormRef, onRestore, onDelete, onClose } = props;
- const drawerRef = useRef<HTMLDivElement>(null);
const [highlightedId, setHighlightedId] = useState<string | null>(entries[0]?.id ?? null);
const highlightedEntry = entries.find((entry) => entry.id === highlightedId) ?? entries[0];
+ const drawerRef = useRef<HTMLDivElement>(null);
- useEffect(() => {
- const closeOnOutsidePointer = (event: PointerEvent) => {
- const drawer = drawerRef.current;
- if (
- (drawer && event.composedPath().includes(drawer)) ||
- (event.target instanceof Element &&
- event.target.closest('[data-prompt-stash-badge="true"]'))
- ) {
- return;
- }
- onClose();
- };
- document.addEventListener("pointerdown", closeOnOutsidePointer, true);
- return () => document.removeEventListener("pointerdown", closeOnOutsidePointer, true);
- }, [onClose]);
+ // Both listeners read entries, highlight and callbacks at event time, so they subscribe
+ // once for the menu's lifetime instead of on every highlight change.
+ const closeOnOutsidePointer = useEffectEvent((event: PointerEvent) => {
+ const drawer = drawerRef.current;
+ if (
+ (drawer && event.composedPath().includes(drawer)) ||
+ (event.target instanceof Element && event.target.closest('[data-prompt-stash-badge="true"]'))
+ ) {
+ return;
+ }
+ onClose();
+ });
- useEffect(() => {
- const handler = (event: KeyboardEvent) => {
- const target = event.target;
- if (
- !(target instanceof Node) ||
- (target !== document.body &&
- !(target instanceof Element && target.closest('[data-prompt-stash-badge="true"]')) &&
- !drawerRef.current?.contains(target) &&
- !composerFormRef.current?.querySelector('textarea, [role="textbox"]')?.contains(target))
- ) {
- return;
- }
- if (event.key === "Escape") {
- event.preventDefault();
- event.stopPropagation();
- onClose();
- return;
- }
- if (event.key === "ArrowDown" || event.key === "ArrowUp") {
- if (entries.length === 0) return;
- event.preventDefault();
- event.stopPropagation();
- const currentIndex = entries.findIndex((entry) => entry.id === highlightedEntry?.id);
- const offset = event.key === "ArrowDown" ? 1 : -1;
- const normalizedIndex = currentIndex >= 0 ? currentIndex : offset === 1 ? -1 : 0;
- const nextIndex = (normalizedIndex + offset + entries.length) % entries.length;
- setHighlightedId(entries[nextIndex]?.id ?? null);
- const nextButton =
- drawerRef.current?.querySelectorAll<HTMLButtonElement>("[data-stash-restore]")[nextIndex];
- nextButton?.scrollIntoView({ block: "nearest" });
- if (drawerRef.current?.contains(document.activeElement)) {
- nextButton?.focus({ preventScroll: true });
- }
- return;
+ const handleKeyDown = useEffectEvent((event: KeyboardEvent) => {
+ const drawer = drawerRef.current;
+ if (!drawer) return;
+ const target = event.target;
+ if (
+ !(target instanceof Node) ||
+ (target !== document.body &&
+ !(target instanceof Element && target.closest('[data-prompt-stash-badge="true"]')) &&
+ !drawer.contains(target) &&
+ !composerFormRef.current?.querySelector('textarea, [role="textbox"]')?.contains(target))
+ ) {
+ return;
+ }
+ if (event.key === "Escape") {
+ event.preventDefault();
+ event.stopPropagation();
+ onClose();
+ return;
+ }
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
+ if (entries.length === 0) return;
+ event.preventDefault();
+ event.stopPropagation();
+ const currentIndex = entries.findIndex((entry) => entry.id === highlightedEntry?.id);
+ const offset = event.key === "ArrowDown" ? 1 : -1;
+ const normalizedIndex = currentIndex >= 0 ? currentIndex : offset === 1 ? -1 : 0;
+ const nextIndex = (normalizedIndex + offset + entries.length) % entries.length;
+ setHighlightedId(entries[nextIndex]?.id ?? null);
+ const nextButton =
+ drawer.querySelectorAll<HTMLButtonElement>("[data-stash-restore]")[nextIndex];
+ nextButton?.scrollIntoView({ block: "nearest" });
+ if (drawer.contains(document.activeElement)) {
+ nextButton?.focus({ preventScroll: true });
}
- if (event.key === "Enter") {
- // Let the delete button handle Enter instead of restoring its row.
- if (event.target instanceof HTMLElement && event.target.closest("button[aria-label]")) {
- return;
- }
- if (!highlightedEntry) return;
- event.preventDefault();
- event.stopPropagation();
- onRestore(highlightedEntry);
+ return;
+ }
+ if (event.key === "Enter") {
+ // Let the delete button handle Enter instead of restoring its row.
+ if (event.target instanceof HTMLElement && event.target.closest("button[aria-label]")) {
return;
}
- if (event.key === "Backspace" && (event.metaKey || event.ctrlKey)) {
- if (!highlightedEntry) return;
- event.preventDefault();
- event.stopPropagation();
- onDelete(highlightedEntry);
- }
+ if (!highlightedEntry) return;
+ event.preventDefault();
+ event.stopPropagation();
+ onRestore(highlightedEntry);
+ return;
+ }
+ if (event.key === "Backspace" && (event.metaKey || event.ctrlKey)) {
+ if (!highlightedEntry) return;
+ event.preventDefault();
+ event.stopPropagation();
+ onDelete(highlightedEntry);
+ }
+ });
+
+ useEffect(() => {
+ const onPointerDown = (event: PointerEvent) => closeOnOutsidePointer(event);
+ const onKeyDown = (event: KeyboardEvent) => handleKeyDown(event);
+ document.addEventListener("pointerdown", onPointerDown, true);
+ window.addEventListener("keydown", onKeyDown, true);
+ return () => {
+ document.removeEventListener("pointerdown", onPointerDown, true);
+ window.removeEventListener("keydown", onKeyDown, true);
};
- window.addEventListener("keydown", handler, true);
- return () => window.removeEventListener("keydown", handler, true);
- }, [composerFormRef, entries, highlightedEntry, onClose, onDelete, onRestore]);
+ }, []);
return (
<ComposerBanner.Root ref={drawerRef} data-composer-stash-drawer="true">
diff --git a/apps/web/src/components/chat/DraftHeroHeadline.tsx b/apps/web/src/components/chat/DraftHeroHeadline.tsx
index b2041df5500..46fed2ddc00 100644
--- a/apps/web/src/components/chat/DraftHeroHeadline.tsx
+++ b/apps/web/src/components/chat/DraftHeroHeadline.tsx
@@ -5,7 +5,7 @@ import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/envir
import { isScratchProject } from "@t3tools/client-runtime/state/projects";
import { FolderPlusIcon } from "lucide-react";
import { useAtomValue } from "@effect/atom-react";
-import { useEffect, useRef, useState } from "react";
+import { useRef, useState } from "react";
import { openCommandPalette } from "~/commandPaletteBus";
import { shortcutLabelForCommand } from "~/keybindings";
@@ -159,21 +159,23 @@ export function DraftHeroHeadline({
);
const selectedPickerItem = pickerItems.find((item) => item.value === activeProjectKey) ?? null;
- // Picker changes invalidate pending no-project home continuations.
- const latestTargetRef = useRef({ draftId, activeProjectKey, scratchTargetEnvironmentId });
- useEffect(() => {
- latestTargetRef.current = { draftId, activeProjectKey, scratchTargetEnvironmentId };
- }, [activeProjectKey, scratchTargetEnvironmentId, draftId]);
+ // The picker can change the draft's target while the no-project home is
+ // still being opened; a stale continuation must not retarget it again. Picking
+ // a project clears the pending request, and the draft session is compared
+ // against the store when the scratch project arrives.
+ const pendingScratchRef = useRef<symbol | null>(null);
+ const draftTargetKey = () => {
+ const session = draftId ? useComposerDraftStore.getState().getDraftSession(draftId) : null;
+ return session
+ ? `${session.environmentId}:${session.projectId}:${session.logicalProjectKey}`
+ : null;
+ };
// Retargeting an empty draft would overwrite the project's draft and strand browser tabs.
const selectProject = (project: (typeof projects)[number], logicalProjectKey: string) => {
if (!draftId) {
return;
}
- latestTargetRef.current = {
- draftId,
- activeProjectKey: logicalProjectKey,
- scratchTargetEnvironmentId: project.environmentId,
- };
+ pendingScratchRef.current = null;
const currentDraft = getComposerDraft(draftId);
if (!composerDraftHasUserContent(currentDraft)) {
void openProjectDraft(scopeProjectRef(project.environmentId, project.id));
@@ -204,17 +206,14 @@ export function DraftHeroHeadline({
if (scratchTargetEnvironmentId === null || isScratchDraft) {
return false;
}
- const requested = { draftId, activeProjectKey, scratchTargetEnvironmentId };
+ const request = Symbol("scratch");
+ pendingScratchRef.current = request;
+ const requestedTarget = draftTargetKey();
const project = await openScratchProject(scratchTargetEnvironmentId);
- const latest = latestTargetRef.current;
- if (
- !project ||
- latest.draftId !== requested.draftId ||
- latest.activeProjectKey !== requested.activeProjectKey ||
- latest.scratchTargetEnvironmentId !== requested.scratchTargetEnvironmentId
- ) {
+ if (!project || pendingScratchRef.current !== request || draftTargetKey() !== requestedTarget) {
return false;
}
+ pendingScratchRef.current = null;
selectProject(project, deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings));
return true;
};
diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx
index 4a6011c5a9c..6802afeb39b 100644
--- a/apps/web/src/components/chat/ModelPickerContent.tsx
+++ b/apps/web/src/components/chat/ModelPickerContent.tsx
@@ -355,8 +355,11 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
onOpenProviderSetup?: (instanceId: ProviderInstanceId) => void;
getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
+ /** The owning popup moves focus here when it opens (its `initialFocus`). */
+ searchInputRef: RefObject<HTMLInputElement | null>;
}) {
const {
+ searchInputRef,
keybindings: providedKeybindings,
modelOptionsByInstance,
instanceEntries,
@@ -367,7 +370,6 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
onOpenProviderSetup,
} = props;
const [searchQuery, setSearchQuery] = useState("");
- const searchInputRef = useRef<HTMLInputElement>(null);
const modelListRef = useRef<LegendListRef | null>(null);
const pickerContentRef = useRef<HTMLDivElement>(null);
const highlightedModelKeyRef = useRef<string | null>(null);
@@ -453,20 +455,6 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
});
};
- useLayoutEffect(() => {
- focusSearchInput();
- const frame = window.requestAnimationFrame(() => {
- focusSearchInput();
- });
- const timeout = window.setTimeout(() => {
- focusSearchInput();
- }, 0);
- return () => {
- window.cancelAnimationFrame(frame);
- window.clearTimeout(timeout);
- };
- }, [focusSearchInput]);
-
const toggleLegacySection = (instanceId: ProviderInstanceId) => {
setExpandedLegacyInstances((expanded) => {
const next = new Set(expanded);
diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx
index e836a92f587..d70c151c2ea 100644
--- a/apps/web/src/components/chat/ProviderModelPicker.tsx
+++ b/apps/web/src/components/chat/ProviderModelPicker.tsx
@@ -5,7 +5,7 @@ import {
type ProviderDriverKind,
type ResolvedKeybindingsConfig,
} from "@t3tools/contracts";
-import { memo, useEffect, useState } from "react";
+import { memo, useRef, useState } from "react";
import { Badge } from "../ui/badge";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -27,6 +27,52 @@ import {
import { useComposerMenuProps } from "./composerEventScope";
import { shortcutLabelForCommand } from "../../keybindings";
+/** Holds the page still behind the open picker; its lifetime is the popup element's. */
+function lockBackgroundScroll(popup: HTMLElement | null) {
+ if (!popup) return;
+ const { documentElement, body } = document;
+ const previousDocumentOverscrollBehavior = documentElement.style.overscrollBehavior;
+ const previousBodyOverflow = body.style.overflow;
+ const previousBodyPaddingRight = body.style.paddingRight;
+ const scrollbarWidth = window.innerWidth - documentElement.clientWidth;
+
+ documentElement.style.overscrollBehavior = "contain";
+ body.style.overflow = "hidden";
+ if (scrollbarWidth > 0) {
+ body.style.paddingRight = `${scrollbarWidth}px`;
+ }
+
+ const shouldAllowOverlayScroll = (target: EventTarget | null) => {
+ return target instanceof Element && target.closest("[data-model-picker-content]");
+ };
+ const preventBackgroundWheel = (event: WheelEvent) => {
+ if (shouldAllowOverlayScroll(event.target)) {
+ return;
+ }
+ event.preventDefault();
+ };
+ const preventBackgroundTouchMove = (event: TouchEvent) => {
+ if (shouldAllowOverlayScroll(event.target)) {
+ return;
+ }
+ event.preventDefault();
+ };
+
+ document.addEventListener("wheel", preventBackgroundWheel, { capture: true, passive: false });
+ document.addEventListener("touchmove", preventBackgroundTouchMove, {
+ capture: true,
+ passive: false,
+ });
+
+ return () => {
+ document.removeEventListener("wheel", preventBackgroundWheel, { capture: true });
+ document.removeEventListener("touchmove", preventBackgroundTouchMove, { capture: true });
+ documentElement.style.overscrollBehavior = previousDocumentOverscrollBehavior;
+ body.style.overflow = previousBodyOverflow;
+ body.style.paddingRight = previousBodyPaddingRight;
+ };
+}
+
export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
environmentId: EnvironmentId | null;
activeInstanceId: ProviderInstanceId;
@@ -57,6 +103,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
const composerFloatingLayerProps = useComposerMenuProps();
const [uncontrolledIsMenuOpen, setUncontrolledIsMenuOpen] = useState(false);
const isMenuOpen = props.open ?? uncontrolledIsMenuOpen;
+ const searchInputRef = useRef<HTMLInputElement>(null);
const size = props.size ?? "sm";
const activeEntry =
@@ -91,54 +138,6 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
}
};
- useEffect(() => {
- if (!isMenuOpen) {
- return;
- }
-
- const { documentElement, body } = document;
- const previousDocumentOverscrollBehavior = documentElement.style.overscrollBehavior;
- const previousBodyOverflow = body.style.overflow;
- const previousBodyPaddingRight = body.style.paddingRight;
- const scrollbarWidth = window.innerWidth - documentElement.clientWidth;
-
- documentElement.style.overscrollBehavior = "contain";
- body.style.overflow = "hidden";
- if (scrollbarWidth > 0) {
- body.style.paddingRight = `${scrollbarWidth}px`;
- }
-
- const shouldAllowOverlayScroll = (target: EventTarget | null) => {
- return target instanceof Element && target.closest("[data-model-picker-content]");
- };
- const preventBackgroundWheel = (event: WheelEvent) => {
- if (shouldAllowOverlayScroll(event.target)) {
- return;
- }
- event.preventDefault();
- };
- const preventBackgroundTouchMove = (event: TouchEvent) => {
- if (shouldAllowOverlayScroll(event.target)) {
- return;
- }
- event.preventDefault();
- };
-
- document.addEventListener("wheel", preventBackgroundWheel, { capture: true, passive: false });
- document.addEventListener("touchmove", preventBackgroundTouchMove, {
- capture: true,
- passive: false,
- });
-
- return () => {
- document.removeEventListener("wheel", preventBackgroundWheel, { capture: true });
- document.removeEventListener("touchmove", preventBackgroundTouchMove, { capture: true });
- documentElement.style.overscrollBehavior = previousDocumentOverscrollBehavior;
- body.style.overflow = previousBodyOverflow;
- body.style.paddingRight = previousBodyPaddingRight;
- };
- }, [isMenuOpen]);
-
const handleInstanceModelChange = (instanceId: ProviderInstanceId, model: string) => {
if (props.disabled) return;
props.onInstanceModelChange(instanceId, model);
@@ -275,12 +274,15 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
</PopoverTrigger>
<PopoverPopup
{...(props.isComposerOwned ? composerFloatingLayerProps : {})}
+ ref={lockBackgroundScroll}
+ initialFocus={searchInputRef}
align="start"
className="before:hidden"
padding="none"
touchBackdrop
>
<ModelPickerContent
+ searchInputRef={searchInputRef}
environmentId={props.environmentId}
activeInstanceId={activeInstanceId}
model={props.model}
diff --git a/apps/web/src/components/chat/useComposerStash.ts b/apps/web/src/components/chat/useComposerStash.ts
index 100bcf3646f..ee7bacf4dbb 100644
--- a/apps/web/src/components/chat/useComposerStash.ts
+++ b/apps/web/src/components/chat/useComposerStash.ts
@@ -8,6 +8,7 @@ import {
} from "@t3tools/contracts";
import {
type ComposerFileAttachment,
+ type ComposerThreadDraftState,
type PersistedComposerFileAttachment,
type PersistedComposerImageAttachment,
composerFileDedupKey,
@@ -29,7 +30,6 @@ import { type ReviewCommentContext } from "../../reviewCommentContext";
import { collapseExpandedComposerCursor } from "../../composer-logic";
import { compressImageForStash } from "../../lib/imageCompression";
import { formatInlineContextReference } from "~/lib/composerContextReferences";
-import { getTerminalFocusOwner } from "../../lib/terminalFocus";
import { isCommandPaletteOpen } from "../../commandPaletteBus";
import { pendingDraftWork } from "./pendingDraftWork";
import {
@@ -47,7 +47,8 @@ import {
import { remainingComposerAttachmentSlots } from "./composerThreadImport";
import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
import { resizeSnapShotSource } from "../../lib/snapShotSource";
-import { resolveShortcutCommand } from "../../keybindings";
+import { registerCommands } from "../../shortcuts/dispatcher";
+import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../../terminalUiStateStore";
import { toastManager } from "../ui/toast";
import type { useComposerTriggerState } from "./useComposerTriggerState";
import {
@@ -70,26 +71,22 @@ export function useComposerStash(input: {
readonly environmentId: EnvironmentId;
readonly composerDraftTarget: ChatComposerProps["composerDraftTarget"];
readonly promptRef: ChatComposerProps["promptRef"];
- readonly composerImagesRef: ChatComposerProps["composerImagesRef"];
- readonly composerFilesRef: ChatComposerProps["composerFilesRef"];
- readonly composerTerminalContextsRef: ChatComposerProps["composerTerminalContextsRef"];
- readonly keybindings: ChatComposerProps["keybindings"];
- readonly terminalOpen: boolean;
+ readonly readAttachmentDraft: () => Pick<ComposerThreadDraftState, "images" | "files">;
+ readonly readTerminalContexts: () => ComposerThreadDraftState["terminalContexts"];
+ readonly routeThreadRef: ChatComposerProps["routeThreadRef"];
readonly projectSelectionRequired: boolean;
- readonly isRevertingCheckpoint: boolean;
readonly pendingUserInputs: ReadonlyArray<PendingUserInput>;
readonly activePendingProgress: ChatComposerProps["activePendingProgress"];
readonly prompt: string;
readonly composerMenuOpen: boolean;
- readonly isComposerModelPickerOpen: boolean;
readonly isComposerCollapsedMobile: boolean;
readonly composerPreviewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
readonly composerReviewComments: ReadonlyArray<ReviewCommentContext>;
readonly composerThreadContexts: ReadonlyArray<ThreadContextRecord>;
- readonly attachmentTargetKeyRef: RefObject<string>;
- readonly composerDraftTargetKeyRef: RefObject<string>;
+ readonly attachmentTargetKey: string;
+ readonly isComposerDraftTargetOpen: (targetKey: string) => boolean;
readonly composerEditorRef: RefObject<ComposerPromptEditorHandle | null>;
- readonly isRevertingCheckpointRef: RefObject<boolean>;
+ readonly isRevertingCheckpoint: () => boolean;
readonly pendingThreadImportsRef: RefObject<Map<string, number>>;
readonly setComposerCursor: Dispatch<SetStateAction<number>>;
readonly setComposerTrigger: ReturnType<typeof useComposerTriggerState>["setTrigger"];
@@ -104,26 +101,22 @@ export function useComposerStash(input: {
environmentId,
composerDraftTarget,
promptRef,
- composerImagesRef,
- composerFilesRef,
- composerTerminalContextsRef,
- keybindings,
- terminalOpen,
+ readAttachmentDraft,
+ readTerminalContexts,
+ routeThreadRef,
projectSelectionRequired,
- isRevertingCheckpoint,
pendingUserInputs,
activePendingProgress,
prompt,
composerMenuOpen,
- isComposerModelPickerOpen,
isComposerCollapsedMobile,
composerPreviewAnnotations,
composerReviewComments,
composerThreadContexts,
- attachmentTargetKeyRef,
- composerDraftTargetKeyRef,
+ attachmentTargetKey,
+ isComposerDraftTargetOpen,
composerEditorRef,
- isRevertingCheckpointRef,
+ isRevertingCheckpoint,
pendingThreadImportsRef,
setComposerCursor,
setComposerTrigger,
@@ -148,12 +141,8 @@ export function useComposerStash(input: {
);
const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts);
const [isStashMenuOpen, setIsStashMenuOpen] = useState(false);
- const [stashPulse, setStashPulse] = useState<{ key: number; active: boolean }>({
- key: 0,
- active: false,
- });
- const stashPulseKeyRef = useRef(0);
- const stashPulseTimeoutRef = useRef<number | null>(null);
+ // Each stash bumps the key; the badge replays its one-shot pulse animation per key.
+ const [stashPulseKey, setStashPulseKey] = useState(0);
const stashInFlightRef = useRef<Set<string>>(new Set());
const stashQueue = usePromptStashStore((state) => state.entries);
@@ -161,24 +150,8 @@ export function useComposerStash(input: {
const takeStashEntry = usePromptStashStore((state) => state.takeEntry);
const finalizeStashEntryImages = usePromptStashStore((state) => state.finalizeEntryImages);
- useEffect(() => {
- return () => {
- if (stashPulseTimeoutRef.current !== null) {
- window.clearTimeout(stashPulseTimeoutRef.current);
- }
- };
- }, []);
-
const pulseStashBadge = () => {
- stashPulseKeyRef.current += 1;
- setStashPulse({ key: stashPulseKeyRef.current, active: true });
- if (stashPulseTimeoutRef.current !== null) {
- window.clearTimeout(stashPulseTimeoutRef.current);
- }
- stashPulseTimeoutRef.current = window.setTimeout(() => {
- stashPulseTimeoutRef.current = null;
- setStashPulse((current) => ({ ...current, active: false }));
- }, 1200);
+ setStashPulseKey((key) => key + 1);
};
const restoreStashEntry = async (menuEntry: PromptStashEntry) => {
@@ -212,8 +185,8 @@ export function useComposerStash(input: {
// prompt with this invocation's captured target. Nothing was taken yet,
// so abort and leave the entry restorable where the user now is.
if (
- isRevertingCheckpointRef.current ||
- composerTargetKey(composerDraftTarget) !== composerDraftTargetKeyRef.current
+ isRevertingCheckpoint() ||
+ !isComposerDraftTargetOpen(composerTargetKey(composerDraftTarget))
) {
return;
}
@@ -263,7 +236,7 @@ export function useComposerStash(input: {
let restoredFileCount = 0;
const stashedFiles = entry.files ?? [];
if (stashedFiles.length > 0) {
- const composerFilesNow = composerFilesRef.current;
+ const composerFilesNow = readAttachmentDraft().files;
const existingFileIds = new Set(composerFilesNow.map((file) => file.id));
const retainedUploadIds = new Set(
composerFilesNow.flatMap((file) =>
@@ -329,7 +302,7 @@ export function useComposerStash(input: {
appendedFiles.push(restored);
}
const capacity = remainingComposerAttachmentSlots(
- composerImagesRef.current.length + composerFilesNow.length,
+ readAttachmentDraft().images.length + composerFilesNow.length,
pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
);
const filesToAppend = appendedFiles.slice(0, capacity);
@@ -373,18 +346,19 @@ export function useComposerStash(input: {
let unrestoredImageNames: string[] = [];
if (entry.attachments.length > 0) {
- const existingIds = new Set(composerImagesRef.current.map((image) => image.id));
+ const attachmentDraft = readAttachmentDraft();
+ const existingIds = new Set(attachmentDraft.images.map((image) => image.id));
// The draft store also dedupes by mimeType+sizeBytes+name, so filter
// on the same key here. Counting a duplicate against capacity would
// burn a slot the store then refuses to fill, pushing a genuinely
// unique image into the overflow list for nothing.
const existingDedupKeys = new Set(
- composerImagesRef.current.map(
+ attachmentDraft.images.map(
(image) => `${image.mimeType}\0${image.sizeBytes}\0${image.name}`,
),
);
const capacity = remainingComposerAttachmentSlots(
- composerImagesRef.current.length + composerFilesRef.current.length + restoredFileCount,
+ attachmentDraft.images.length + attachmentDraft.files.length + restoredFileCount,
pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0,
);
const pending = entry.attachments.filter(
@@ -472,7 +446,7 @@ export function useComposerStash(input: {
const stashCurrentPrompt = async () => {
// Stashing clears the draft. A pasted attachment still downloading would then land in the
// emptied composer instead of travelling with the entry it belongs to.
- if (pendingDraftWork.has(attachmentTargetKeyRef.current)) {
+ if (pendingDraftWork.has(attachmentTargetKey)) {
toastManager.add({
type: "info",
title: "Still bringing attached context into this message.",
@@ -481,11 +455,12 @@ export function useComposerStash(input: {
return;
}
const prompt = promptRef.current.trim();
- const images = [...composerImagesRef.current];
- const files = [...composerFilesRef.current];
+ const attachmentDraft = readAttachmentDraft();
+ const images = [...attachmentDraft.images];
+ const files = [...attachmentDraft.files];
const stashedRecords: ComposerContextRecord[] = [
...composerThreadContexts,
- ...composerTerminalContextsRef.current.map(terminalContextRecord),
+ ...readTerminalContexts().map(terminalContextRecord),
...composerReviewComments.map(reviewCommentContextRecord),
...composerPreviewAnnotations.map((annotation) =>
previewAnnotationContextRecord(annotation, {
@@ -693,53 +668,45 @@ export function useComposerStash(input: {
if (stashMenuClosesOn.prompt !== prompt || composerMenuOpen) setIsStashMenuOpen(false);
}
+ // Read at event time, so the scope registers once per mounted composer instead of
+ // re-registering (and reshuffling capture-scope priority) whenever a guard flips.
+ const handleStashShortcut = useStableCallback((event: KeyboardEvent) => {
+ // Always claim the shortcut so the browser save dialog never opens,
+ // even when the composer is in a state that can't stash.
+ event.preventDefault();
+ event.stopPropagation();
+ if (isCommandPaletteOpen() || isRevertingCheckpoint()) return;
+ if (pendingUserInputs.length > 0) {
+ setIsStashMenuOpen((open) => !open);
+ return;
+ }
+ if (projectSelectionRequired || activePendingProgress !== null) return;
+ void stashCurrentPromptStable();
+ });
+ // Capture phase while the composer is mounted, so Mod+S never reaches the browser's save
+ // dialog even when a focused widget (the model picker search) stops the key.
const backgroundThread = use(BackgroundThreadContext);
+ const readShortcutContext = useStableCallback(() => ({
+ terminalOpen: Boolean(
+ selectThreadTerminalUiState(
+ useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
+ routeThreadRef,
+ ).terminalOpen,
+ ),
+ }));
useEffect(() => {
if (backgroundThread) return;
- const handler = (event: globalThis.KeyboardEvent) => {
- const command = resolveShortcutCommand(event, keybindings, {
- context: {
- terminalFocus: getTerminalFocusOwner() !== null,
- terminalOpen,
- modelPickerOpen: isComposerModelPickerOpen,
- },
- });
- if (command !== "composer.stash") return;
- // Always claim the shortcut so the browser save dialog never opens,
- // even when the composer is in a state that can't stash.
- event.preventDefault();
- event.stopPropagation();
- if (isCommandPaletteOpen() || isRevertingCheckpoint) {
- return;
- }
- if (pendingUserInputs.length > 0) {
- setIsStashMenuOpen((open) => !open);
- return;
- }
- if (projectSelectionRequired || activePendingProgress !== null) {
- return;
- }
- void stashCurrentPromptStable();
- };
- window.addEventListener("keydown", handler, true);
- return () => window.removeEventListener("keydown", handler, true);
- }, [
- activePendingProgress,
- backgroundThread,
- isComposerModelPickerOpen,
- keybindings,
- pendingUserInputs.length,
- projectSelectionRequired,
- stashCurrentPromptStable,
- isRevertingCheckpoint,
- terminalOpen,
- ]);
+ return registerCommands(
+ { "composer.stash": handleStashShortcut },
+ { capture: true, context: readShortcutContext },
+ );
+ }, [backgroundThread, handleStashShortcut, readShortcutContext]);
return {
stashQueue,
isStashMenuOpen,
setIsStashMenuOpen,
- stashPulse,
+ stashPulseKey,
restoreStashEntryStable,
deleteStashEntryStable,
toggleStashMenuStable,
diff --git a/apps/web/src/index.css b/apps/web/src/index.css
index 828a6b00877..f720507b31b 100644
--- a/apps/web/src/index.css
+++ b/apps/web/src/index.css
@@ -226,6 +226,11 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
compositor updates discrete frames instead of every vsync. */
--animate-status-pulse: status-pulse 2s infinite;
--animate-status-ping: status-ping 2s infinite;
+ /* Stash pulses hold a highlight for 1.2s; the row then eases back over 200ms, the count snaps.
+ The row alternates two identical keyframes so each stash restarts it without a remount. */
+ --animate-stash-pulse-row: stash-pulse-row 1400ms;
+ --animate-stash-pulse-row-alt: stash-pulse-row-alt 1400ms;
+ --animate-stash-pulse-count: stash-pulse-count 1400ms step-start;
--color-warning-foreground: var(--warning-foreground);
--color-warning: var(--warning);
--color-warning-surface: var(--warning-surface);
@@ -310,6 +315,24 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
opacity: 1;
}
}
+ @keyframes stash-pulse-row {
+ from,
+ 85.7% {
+ color: var(--color-foreground);
+ }
+ }
+ @keyframes stash-pulse-row-alt {
+ from,
+ 85.7% {
+ color: var(--color-foreground);
+ }
+ }
+ @keyframes stash-pulse-count {
+ from,
+ 85.7% {
+ color: var(--color-primary);
+ }
+ }
@keyframes status-pulse {
0%,
40% {