feat(webui): stabilize session transitions and goal presentation

Keep the composer stable during interruptible session changes. Move active and blocked goals into the header with localized gallery previews, and preserve focus when overlays close. Include the reviewed navigation, layout and accessibility fixes.
This commit is contained in:
chengyongru authored and chengyongru committed 2026-11-13 23:37:07 +08:00
1 parent e65bec9a6e
commit ce3f36983d
58 files changed
+1874 -453

No files matched your search

+28 -13
View File
@@ -30,6 +30,7 @@ import { webuiThreadCache } from "@/lib/webui-thread-cache";
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
import type { SettingsExitGuard, SettingsFocusTarget } from "@/components/settings/contracts";
import { PaneWorkbench } from "@/components/workbench/PaneWorkbench";
import { transitionSession } from "@/components/thread/session-transition";
import {
MAX_WORKBENCH_PANES,
addWorkbenchPane,
@@ -1023,15 +1024,24 @@ function Shell({
temporary: route.temporary || Boolean(route.activeKey && temporarySessionsRef.current[route.activeKey]),
}, options?.replace);
}, []);
const changesVisibleSession = useCallback((current: ShellRoute, next: ShellRoute) => {
if (current.view !== "chat" || next.view !== "chat" || current.activeKey === next.activeKey) return false;
if (mobileWorkbench || !current.activeKey || !next.activeKey) return true;
return workbenchTabForPane(workbenchState, current.activeKey).tabKey
!== workbenchTabForPane(workbenchState, next.activeKey).tabKey;
}, [mobileWorkbench, workbenchState]);
const navigate = useCallback(
(route: ShellRoute, options?: { replace?: boolean }) => {
const leave = () => commitNavigation(route, options);
(route: ShellRoute, options?: { replace?: boolean; animate?: boolean }) => {
const current = currentShellRouteRef.current;
const leave = () => transitionSession(
() => commitNavigation(route, options),
options?.animate !== false && changesVisibleSession(current, route),
);
if (changesSettingsSurface(current, route) && settingsExitGuardRef.current) {
settingsExitGuardRef.current(leave, { promptRestart: current.view !== route.view });
} else leave();
},
[commitNavigation],
[commitNavigation, changesVisibleSession],
);
useEffect(() => {
@@ -1052,14 +1062,16 @@ function Shell({
}, { promptRestart: current.view !== route.view });
return;
}
setActiveKey(route.activeKey);
setView(route.view);
setSettingsInitialSection(route.settingsSection);
setSettingsFocus(route.settingsFocus);
setWorkspaceError(null);
if (route.view === "chat" && !route.activeKey) {
setDraftWorkspaceScope(null);
}
transitionSession(() => {
setActiveKey(route.activeKey);
setView(route.view);
setSettingsInitialSection(route.settingsSection);
setSettingsFocus(route.settingsFocus);
setWorkspaceError(null);
if (route.view === "chat" && !route.activeKey) {
setDraftWorkspaceScope(null);
}
}, changesVisibleSession(current, route));
};
window.addEventListener("hashchange", applyRoute);
window.addEventListener("popstate", applyRoute);
@@ -1067,7 +1079,7 @@ function Shell({
window.removeEventListener("hashchange", applyRoute);
window.removeEventListener("popstate", applyRoute);
};
}, []);
}, [changesVisibleSession]);
useEffect(() => {
temporarySessionsRef.current = temporarySessions;
@@ -1562,12 +1574,15 @@ function Shell({
if (activeKey === key) {
if (remaining.length === 0) setDraftWorkspaceScope(null);
setWorkspaceError(null);
// Closing invalidates the source session immediately. Commit its replacement
// in the same batch rather than leaving cleanup an invalid active route
// while a view-transition capture is pending.
navigate({
view: "chat",
activeKey: remaining[0]?.key ?? null,
settingsSection: "overview",
...(remaining[0] ? { temporary: true } : {}),
}, { replace: true });
}, { replace: true, animate: false });
}
setMobileSidebarOpen(false);
}, [activeKey, client, navigate, temporarySessionList]);
+4 -2
View File
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { HoverHint } from "@/components/ui/tooltip";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import { useOverlayEscapeFocus } from "@/hooks/useOverlayEscapeFocus";
import { providerBrand } from "@/lib/provider-brand";
import type { ResponseSource } from "@/lib/types";
import { cn } from "@/lib/utils";
@@ -38,6 +39,7 @@ function ResponseSourceBadge({
}) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const escapeFocus = useOverlayEscapeFocus();
const description = t("message.fallbackResponse", { preset: source.preset });
const brand = providerBrand(source.provider);
const { logoUrl, logoLoaded, onLogoLoad, onLogoError } = useLogoFallback(brand?.logoUrls);
@@ -47,7 +49,7 @@ function ResponseSourceBadge({
<HoverHint content={description} enabled={!open} side="top" align="end"
contentClassName="max-w-[min(18rem,calc(100vw-2rem))]">
<PopoverTrigger asChild>
<button type="button" aria-label={description} className={cn(
<button type="button" {...escapeFocus.triggerProps} aria-label={description} className={cn(
"touch-target inline-flex min-h-8 min-w-0 max-w-full items-center gap-1.5 rounded-control px-1.5 text-xs",
"transition-colors hover:bg-muted/55 hover:text-foreground",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
@@ -67,7 +69,7 @@ function ResponseSourceBadge({
</button>
</PopoverTrigger>
</HoverHint>
<PopoverContent side="top" align="end" aria-label={description}
<PopoverContent side="top" align="end" aria-label={description} {...escapeFocus.contentProps}
onOpenAutoFocus={(event) => event.preventDefault()}
className="max-w-[min(18rem,calc(100vw-2rem))] rounded-control px-3 py-2 text-xs leading-relaxed break-words">
{description}
@@ -37,6 +37,11 @@ export function SettingsFeature({
const { t } = useTranslation();
const [open, setOpen] = useState(initialOpen && enabled);
const section = useRef<HTMLElement>(null);
const opener = useRef<HTMLElement | null>(null);
const changeOpen = (next: boolean) => {
if (next) opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
setOpen(next);
};
useEffect(() => {
if (initialOpen && enabled) {
setOpen(true);
@@ -46,7 +51,7 @@ export function SettingsFeature({
return (
<section ref={section} aria-label={title}>
<Dialog open={Boolean(children) && open} onOpenChange={(next) => {
setOpen(next);
changeOpen(next);
if (!next) onClose?.();
}}>
<SettingsGroup>
@@ -65,10 +70,17 @@ export function SettingsFeature({
</button>
</DialogTrigger> : null}
<ToggleButton checked={enabled} disabled={disabled} ariaLabel={title} label={title}
onChange={(next) => { setOpen(next); onChange(next); }} />
onChange={(next) => { changeOpen(next); onChange(next); }} />
</SettingsRow>
</SettingsGroup>
{children ? <DialogContent aria-describedby={undefined} className="settings-grid max-h-[85dvh] w-[min(calc(100vw-2rem),40rem)] max-w-none overflow-y-auto p-0 [--settings-surface:var(--background)]">
{children ? <DialogContent aria-describedby={undefined} onCloseAutoFocus={(event) => {
if (opener.current?.isConnected && !opener.current.matches(":disabled")) {
opener.current.focus({ preventScroll: true });
// Saving on close can disable the switch that opened this dialog.
// Let Radix restore its Configure trigger if the opener cannot focus.
if (document.activeElement === opener.current) event.preventDefault();
}
}} className="settings-grid max-h-[85dvh] w-[min(calc(100vw-2rem),40rem)] max-w-none overflow-y-auto p-0 [--settings-surface:var(--background)]">
<DialogTitle className="sr-only">{title}</DialogTitle>
<div className="pb-4 pt-8">{children}</div>
</DialogContent> : null}
+107
View File
@@ -0,0 +1,107 @@
import { CircleAlert } from "lucide-react";
import { useLayoutEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { MarkdownText, preloadMarkdownText } from "@/components/MarkdownText";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useOverlayEscapeFocus } from "@/hooks/useOverlayEscapeFocus";
import type { GoalStateWsPayload } from "@/lib/types";
import "./goal-island.css";
export function GoalIsland({ goal }: { goal: GoalStateWsPayload }) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const [scrollBody, setScrollBody] = useState<HTMLDivElement | null>(null);
const panelRef = useRef<HTMLDivElement>(null);
const escapeFocus = useOverlayEscapeFocus();
const changeOpen = (nextOpen: boolean) => {
const panel = panelRef.current;
const surface = panel?.querySelector<HTMLElement>(":scope > .goal-island-surface");
const content = panel?.querySelector<HTMLElement>(".goal-island-panel-content");
if (panel && surface && content) {
const shape = getComputedStyle(surface);
const text = getComputedStyle(content);
panel.style.setProperty("--goal-from-width", shape.width);
panel.style.setProperty("--goal-from-height", shape.height);
panel.style.setProperty("--goal-from-radius", shape.getPropertyValue("--goal-island-radius"));
panel.style.setProperty("--goal-from-opacity", text.opacity);
panel.style.setProperty("--goal-from-transform", text.transform);
}
setOpen(nextOpen);
};
const summary = goal.ui_summary?.trim() ?? "";
const objective = goal.objective?.trim() ?? "";
const label = summary || objective || t("thread.composer.goalStateFallback");
const status = goal.status === "blocked" ? "blocked" : "active";
const recap = goal.recap?.trim() ?? "";
const collapsedLabel = status === "blocked" ? recap : label;
useLayoutEffect(() => {
if (!scrollBody) return;
if (status === "blocked") scrollBody.scrollTop = 0;
const measure = () => {
scrollBody.toggleAttribute("data-overflow-top", scrollBody.scrollTop > 1);
scrollBody.toggleAttribute("data-overflow-bottom", scrollBody.scrollHeight - scrollBody.clientHeight - scrollBody.scrollTop > 1);
};
measure();
const observer = new ResizeObserver(measure);
observer.observe(scrollBody);
if (scrollBody.firstElementChild) observer.observe(scrollBody.firstElementChild);
scrollBody.addEventListener("scroll", measure, { passive: true });
return () => {
observer.disconnect();
scrollBody.removeEventListener("scroll", measure);
};
}, [scrollBody, status]);
return (
<div className="goal-island-position">
<Popover open={open} onOpenChange={changeOpen}>
<div className="goal-island" data-goal-status={status} data-detail-mounted={!!scrollBody} role="status" aria-label={status === "blocked" ? [t("thread.composer.goalBlocked"), recap].filter(Boolean).join(" · ") : t("thread.composer.goalStateStrip", { label })}>
<PopoverTrigger asChild>
<button
type="button"
className="goal-island-trigger"
aria-label={t("thread.composer.goalStateExpandAria")}
{...escapeFocus.triggerProps}
onPointerEnter={() => { void preloadMarkdownText(); }}
onFocus={() => { void preloadMarkdownText(); }}
>
<span className="goal-island-surface" aria-hidden />
{status === "blocked" ? <CircleAlert className="goal-island-status-icon" strokeWidth={2.5} aria-hidden="true" /> : null}
{collapsedLabel ? <span className={status === "blocked" ? "goal-island-reason min-w-0 truncate" : "min-w-0 truncate"}>{collapsedLabel}</span> : null}
</button>
</PopoverTrigger>
</div>
<PopoverContent
ref={panelRef}
{...escapeFocus.contentProps}
className="goal-island-panel max-h-[min(25dvh,var(--radix-popover-content-available-height))] overflow-visible rounded-t-none rounded-b-[28px] bg-transparent p-0 shadow-none dark:shadow-none"
motionClassName=""
data-goal-status={status}
side="bottom"
sideOffset={-40}
collisionPadding={{ top: 0, bottom: 12, left: 32, right: 32 }}
aria-label={t("thread.composer.goalStateSheetTitle")}
>
<div className="goal-island-surface" aria-hidden />
<div className="goal-island-panel-content">
{status !== "blocked" && summary ? <div className="goal-island-summary markdown-content"><h2>{summary}</h2></div> : null}
<div ref={setScrollBody} className="goal-island-body">
<div className="goal-island-document">
{status === "blocked" ? <div className="goal-island-blocked">
<CircleAlert className="goal-island-status-icon" strokeWidth={2.5} aria-hidden="true" />
<span className="sr-only">{t("thread.composer.goalBlocked")}</span>
{recap ? <MarkdownText className="goal-island-reason">{recap}</MarkdownText> : null}
</div> : null}
{objective ? <MarkdownText className={status === "blocked" ? "mt-4" : undefined}>{objective}</MarkdownText> : null}
{status !== "blocked" && recap ? <MarkdownText className="mt-4 text-muted-foreground">{recap}</MarkdownText> : null}
</div>
</div>
</div>
</PopoverContent>
</Popover>
</div>
);
}
@@ -20,6 +20,7 @@ import {
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import { useOverlayEscapeFocus } from "@/hooks/useOverlayEscapeFocus";
import { inferProviderFromModelName, providerBrand } from "@/lib/provider-brand";
import { cn } from "@/lib/utils";
@@ -124,6 +125,8 @@ export function ModelPresetBadge({
const [motionWidth, setMotionWidth] = useState<number | null>(null);
const gestureRef = useRef<PresetGesture | null>(null);
const suppressClickRef = useRef(false);
const escapeFocus = useOverlayEscapeFocus();
const focusAfterClose = useRef<"composer" | "management" | null>(null);
const activeName = modelPreset?.trim() || "";
const listedIndex = modelPresets.findIndex((preset) => preset.name === activeName);
const activePreset: ModelPresetOption = {
@@ -158,12 +161,14 @@ export function ModelPresetBadge({
});
const selectPreset = (name: string) => {
if (open) focusAfterClose.current = "composer";
else requestAnimationFrame(() => onRequestComposerFocus?.());
setOpen(false);
if (name !== activeName) onPresetChange?.(name);
requestAnimationFrame(() => onRequestComposerFocus?.());
};
const openModelSettings = () => {
focusAfterClose.current = "management";
setOpen(false);
onManageModels?.();
};
@@ -306,13 +311,7 @@ export function ModelPresetBadge({
</Container>
</TooltipTrigger>
) : (
<Popover
open={open}
onOpenChange={(nextOpen) => {
setOpen(nextOpen);
if (!nextOpen) requestAnimationFrame(() => onRequestComposerFocus?.());
}}
>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<TooltipTrigger asChild>
<button
@@ -320,6 +319,7 @@ export function ModelPresetBadge({
data-switching={motion ? "true" : undefined}
aria-label={label}
aria-expanded={open}
{...escapeFocus.triggerProps}
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerLeave={(event) => {
@@ -404,6 +404,16 @@ export function ModelPresetBadge({
collisionPadding={12}
role="dialog"
aria-label={switchModelLabel}
onEscapeKeyDown={escapeFocus.contentProps.onEscapeKeyDown}
onCloseAutoFocus={(event) => {
if (focusAfterClose.current === "management") event.preventDefault();
else if (focusAfterClose.current === "composer" && onRequestComposerFocus) {
event.preventDefault();
onRequestComposerFocus();
}
escapeFocus.contentProps.onCloseAutoFocus(event);
focusAfterClose.current = null;
}}
onOpenAutoFocus={(event) => {
event.preventDefault();
const content = event.currentTarget;
@@ -39,6 +39,7 @@ export function PromptNavigator({
const [highlighted, setHighlighted] = useState(0);
const inputRef = useRef<HTMLInputElement>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
const openerRef = useRef<HTMLElement | null>(null);
useEffect(() => {
const keyDown = (event: KeyboardEvent) => {
@@ -93,8 +94,16 @@ export function PromptNavigator({
<DialogContent
showCloseButton={false}
aria-describedby={undefined}
onOpenAutoFocus={(event) => { event.preventDefault(); inputRef.current?.focus(); }}
onCloseAutoFocus={(event) => { event.preventDefault(); triggerRef.current?.focus(); }}
onOpenAutoFocus={(event) => {
event.preventDefault();
openerRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
inputRef.current?.focus();
}}
onCloseAutoFocus={(event) => {
event.preventDefault();
const target = openerRef.current?.isConnected ? openerRef.current : triggerRef.current;
target?.focus({ preventScroll: true });
}}
className="session-search-dialog flex max-h-[min(40rem,100%)] w-[calc(100vw-2rem)] max-w-[42rem] flex-col gap-0 overflow-hidden p-0"
>
<DialogTitle className="sr-only">
@@ -18,6 +18,7 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { useOverlayEscapeFocus } from "@/hooks/useOverlayEscapeFocus";
import { currentLocale } from "@/i18n";
import { fmtDateTime } from "@/lib/format-time";
import type {
@@ -63,6 +64,7 @@ export function SessionInfoPopoverView({ jobs, loading, loadFailed, now, onActio
}) {
const { t } = useTranslation("common");
const [open, setOpen] = useState(false);
const escapeFocus = useOverlayEscapeFocus();
const [inspectedJob, setInspectedJob] = useState<SessionAutomationJob | null>(null);
// Keep requested dialogs mounted through their close and focus-restoration lifecycle.
const [dialogsRequested, setDialogsRequested] = useState(false);
@@ -179,6 +181,7 @@ export function SessionInfoPopoverView({ jobs, loading, loadFailed, now, onActio
<PopoverTrigger asChild>
<Button
ref={triggerRef}
{...escapeFocus.triggerProps}
variant="ghost"
size="icon"
aria-label={t("thread.header.sessionInfo")}
@@ -194,8 +197,10 @@ export function SessionInfoPopoverView({ jobs, loading, loadFailed, now, onActio
align="end"
sideOffset={8}
className="w-[min(23rem,calc(100vw-1.5rem))] overflow-hidden p-0"
onEscapeKeyDown={escapeFocus.contentProps.onEscapeKeyDown}
onCloseAutoFocus={(event) => {
if (detailOpen) event.preventDefault();
escapeFocus.contentProps.onCloseAutoFocus(event);
}}
>
<div className="flex max-h-[min(var(--radix-popover-content-available-height),32rem)] flex-col">
+1 -229
View File
@@ -36,7 +36,6 @@ import {
type Ref,
} from "react";
import { MarkdownText, preloadMarkdownText } from "@/components/MarkdownText";
import {
CapabilityMentionToken,
cliAppInitials,
@@ -56,8 +55,6 @@ import {
import { INLINE_REFERENCE_HIGHLIGHT_COLOR, INLINE_TOKEN_HIGHLIGHT_COLOR, InlineTokenHighlight } from "@/components/InlineTokenHighlight";
import { SlashCommandText } from "@/components/SlashCommandText";
import {
ChevronDown,
ChevronUp,
CornerDownRight,
Loader2,
Quote,
@@ -73,7 +70,6 @@ import { ComposerActionIcon, type ComposerActionState } from "@/components/threa
import {
floatingItemClassName,
floatingItemFocusClassName,
floatingSurfaceElevationClassName,
floatingSurfaceVisualClassName,
} from "@/components/ui/floating-surface";
import {
@@ -512,40 +508,6 @@ function getVisibleBounds(el: HTMLElement): { top: number; bottom: number } {
return { top, bottom };
}
function goalStateStripPreview(
goal: GoalStateWsPayload | undefined,
t: (key: string) => string,
): string | null {
if (!goal?.active) return null;
const summary = goal.ui_summary?.trim();
if (summary) return summary;
const obj = goal.objective?.trim();
if (obj) return obj.length > 72 ? `${obj.slice(0, 72)}…` : obj;
return t("thread.composer.goalStateFallback");
}
const GOAL_PANEL_VIEWPORT_TOP_PAD = 20;
const GOAL_PANEL_GAP_ABOVE_STRIP_PX = 10;
const GOAL_PANEL_MIN_HEIGHT_PX = 112;
const GOAL_PANEL_MAX_VIEWPORT_RATIO = 0.62;
function measureGoalPanelMaxCssHeight(stripTopY: number): number {
const viewport = visualViewportBounds();
const spaceAboveStrip =
stripTopY - viewport.top - GOAL_PANEL_VIEWPORT_TOP_PAD - GOAL_PANEL_GAP_ABOVE_STRIP_PX;
return Math.min(
Math.max(spaceAboveStrip, GOAL_PANEL_MIN_HEIGHT_PX),
Math.floor(viewport.height * GOAL_PANEL_MAX_VIEWPORT_RATIO),
);
}
function buildGoalMarkdownBody(summary: string, objective: string): string {
const s = summary.trim();
const o = objective.trim();
if (s && o) return `${s}\n\n---\n\n${o}`;
return o || s;
}
function cliAppMentionPayload(app: CliAppInfo): OutboundCliAppMention {
return {
name: app.name,
@@ -570,193 +532,6 @@ function mcpPresetMentionPayload(preset: McpPresetInfo): OutboundMcpPresetMentio
};
}
function GoalStateStrip({
goalState,
}: {
goalState?: GoalStateWsPayload;
}) {
const { t } = useTranslation();
const [goalPanelOpen, setGoalPanelOpen] = useState(false);
const stripLabel = goalStateStripPreview(goalState, t);
const active = !!stripLabel?.trim();
const [, setTick] = useState(0);
const stripWrapperRef = useRef<HTMLDivElement>(null);
const panelRef = useRef<HTMLDivElement>(null);
const expandToggleRef = useRef<HTMLButtonElement>(null);
const stripSnapshotRef = useRef<{
goalState?: GoalStateWsPayload;
stripLabel: string | null;
} | null>(null);
const [panelMaxPx, setPanelMaxPx] = useState(280);
if (active) {
stripSnapshotRef.current = { goalState, stripLabel };
}
useEffect(() => {
if (!active) setGoalPanelOpen(false);
}, [active]);
const display = active
? { goalState, stripLabel }
: stripSnapshotRef.current;
const displayGoalState = display?.goalState;
const displayStripLabel = display?.stripLabel ?? null;
const objectiveFull = displayGoalState?.objective?.trim() ?? "";
const summaryFull = displayGoalState?.ui_summary?.trim() ?? "";
const canExpandGoal = !!(active && displayGoalState?.active && (objectiveFull || summaryFull));
const markdownBody =
objectiveFull || summaryFull
? buildGoalMarkdownBody(summaryFull, objectiveFull)
: "";
useLayoutEffect(() => {
if (!goalPanelOpen) return;
function relayout(): void {
const el = stripWrapperRef.current;
if (!el) return;
const top = el.getBoundingClientRect().top;
setPanelMaxPx(measureGoalPanelMaxCssHeight(top));
}
relayout();
void preloadMarkdownText();
const ro =
typeof ResizeObserver !== "undefined"
? new ResizeObserver(() => relayout())
: null;
if (stripWrapperRef.current && ro) {
ro.observe(stripWrapperRef.current);
}
const viewport = window.visualViewport;
viewport?.addEventListener("resize", relayout);
viewport?.addEventListener("scroll", relayout);
window.addEventListener("resize", relayout);
window.addEventListener("scroll", relayout, true);
return () => {
ro?.disconnect();
viewport?.removeEventListener("resize", relayout);
viewport?.removeEventListener("scroll", relayout);
window.removeEventListener("resize", relayout);
window.removeEventListener("scroll", relayout, true);
};
}, [goalPanelOpen]);
useEffect(() => {
if (!goalPanelOpen) return;
function onPointerDown(ev: MouseEvent): void {
const target = ev.target as Node | null;
if (!target) return;
if (panelRef.current?.contains(target)) return;
if (expandToggleRef.current?.contains(target)) return;
setGoalPanelOpen(false);
}
function onKey(ev: KeyboardEvent): void {
if (ev.key === "Escape") setGoalPanelOpen(false);
}
window.addEventListener("mousedown", onPointerDown);
window.addEventListener("keydown", onKey);
return () => {
window.removeEventListener("mousedown", onPointerDown);
window.removeEventListener("keydown", onKey);
};
}, [goalPanelOpen]);
if (!display) return null;
const ariaLabel = displayStripLabel
? t("thread.composer.goalStateStrip", { label: displayStripLabel })
: t("thread.composer.goalStateFallback");
return (
<div
ref={stripWrapperRef}
className="composer-status-drawer relative z-30"
data-composer-status-drawer=""
data-state={active ? "open" : "closed"}
aria-hidden={active ? undefined : true}
onTransitionEnd={(event) => {
if (active || event.target !== event.currentTarget) return;
stripSnapshotRef.current = null;
setTick((n) => n + 1);
}}
>
{goalPanelOpen && canExpandGoal && markdownBody ? (
<div
ref={panelRef}
id="nanobot-goal-panel-root"
role="dialog"
aria-modal="false"
aria-label={t("thread.composer.goalStateSheetTitle")}
tabIndex={-1}
className={cn(
"absolute bottom-[calc(100%+8px)] left-3 right-3 z-[50] flex max-w-none flex-col overflow-hidden",
"rounded-2xl",
floatingSurfaceElevationClassName,
)}
style={{ maxHeight: `${Math.round(panelMaxPx)}px` }}
>
<div
id="nanobot-goal-panel-scroll"
className="min-h-0 flex-1 overflow-y-auto scrollbar-thin p-3"
>
<MarkdownText className="max-w-none text-foreground/90">
{markdownBody}
</MarkdownText>
</div>
</div>
) : null}
<div className="composer-status-drawer-clip">
{display ? (
<div
className="composer-status-drawer-content flex min-h-[36px] items-center gap-2 px-3 py-2"
role="status"
aria-label={ariaLabel}
>
<GoalIcon className="h-4 w-4 shrink-0 text-primary/75" aria-hidden />
<span className="flex min-w-0 flex-1 items-center gap-1.5 text-[12px] font-medium text-foreground/75">
{displayStripLabel ? (
<span className="truncate">
{t("thread.composer.goalStateStrip", { label: displayStripLabel })}
</span>
) : null}
</span>
{canExpandGoal ? (
<button
ref={expandToggleRef}
type="button"
className={cn(
"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full",
"text-muted-foreground transition-colors hover:text-foreground",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
)}
aria-expanded={goalPanelOpen}
aria-controls={goalPanelOpen ? "nanobot-goal-panel-root" : undefined}
aria-label={t("thread.composer.goalStateExpandAria")}
title={t("thread.composer.goalStateExpandAria")}
onClick={() => setGoalPanelOpen((o) => !o)}
>
{goalPanelOpen ? (
<ChevronDown className="h-4 w-4" aria-hidden />
) : (
<ChevronUp className="h-4 w-4" aria-hidden />
)}
</button>
) : null}
</div>
) : null}
</div>
</div>
);
}
function autosizeTextarea(input: HTMLTextAreaElement) {
const container = input.parentElement!;
const previousMinHeight = container.style.minHeight;
@@ -2163,7 +1938,7 @@ export function ThreadComposer({
const relaxedHeroInput = isHero && images.length === 0 && !isStreaming;
const compactIdle = compactWhenIdle && !compactControls && !isHero && !composerFocused
&& value.length === 0 && images.length === 0 && !inlineError
&& !normalizedQuotedContext && !queuedPrompt && !goalState?.active
&& !normalizedQuotedContext && !queuedPrompt
&& !isDragging && !sessionDragPreview && !voiceRecorder.isRecording && !showProjectPicker;
useLayoutEffect(() => {
if (!compactWhenIdle || compactControls) return;
@@ -2328,8 +2103,6 @@ export function ThreadComposer({
interactionDisabled && "opacity-60",
sessionDragPreview && "ring-1 ring-primary/25",
isDragging && "ring-2 ring-primary/40 motion-reduce:ring-0 motion-reduce:border-primary",
goalState?.active &&
"ring-1 ring-sky-400/35 motion-reduce:ring-sky-400/25 dark:ring-sky-400/45",
)}
>
{queuedPrompt ? (
@@ -2398,7 +2171,6 @@ export function ThreadComposer({
</button>
</div>
) : null}
<GoalStateStrip goalState={goalState} />
<div className="thread-composer-input relative min-w-0">
{placeholder === undefined ? (
<span className="pointer-events-none invisible absolute h-0 w-0 overflow-hidden">
+8 -2
View File
@@ -38,6 +38,7 @@ interface ThreadHeaderProps {
minimal?: boolean;
promptNavigatorAction?: ReactNode;
sessionInfoAction?: ReactNode;
goal?: ReactNode;
temporaryChatEnabled?: boolean;
temporaryChatDisabled?: boolean;
onTemporaryChatEnabledChange?: (enabled: boolean) => void;
@@ -58,6 +59,7 @@ export function ThreadHeader({
minimal = false,
promptNavigatorAction,
sessionInfoAction,
goal,
temporaryChatEnabled = false,
temporaryChatDisabled = false,
onTemporaryChatEnabledChange,
@@ -68,7 +70,8 @@ export function ThreadHeader({
<div
data-testid="thread-header"
className={cn(
"pointer-events-none inset-x-0 top-0 z-30 flex shrink-0 items-center justify-between gap-3 px-3 py-1",
"thread-header-container pointer-events-none inset-x-0 top-0 z-30 flex shrink-0 items-center justify-between gap-3 px-3 py-1",
goal && "thread-header-with-goal",
"[position:var(--thread-header-position,absolute)]",
minimal && "h-11",
className,
@@ -76,6 +79,7 @@ export function ThreadHeader({
>
<div
data-theme-surface
data-header-controls="start"
className={cn(
controlsClassName,
"relative min-w-0",
@@ -103,6 +107,7 @@ export function ThreadHeader({
) : null}
{handle ? (
<span
data-header-handle
className="flex shrink-0 items-center rounded-md px-1.5 py-1 text-[12px] font-medium"
>
<SessionHandleLabel id={handle.id}>
@@ -112,7 +117,8 @@ export function ThreadHeader({
) : null}
</div>
<div data-theme-surface className={cn(controlsClassName, "ml-auto shrink-0")}>
{goal}
<div data-theme-surface data-header-controls="end" className={cn(controlsClassName, "ml-auto shrink-0")}>
{sessionInfoAction}
{promptNavigatorAction}
{actions}
@@ -34,6 +34,7 @@ import {
toModelBadgeInfo,
} from "@/components/thread/model-preset";
import { ThreadHeader } from "@/components/thread/ThreadHeader";
import { GoalIsland } from "@/components/thread/GoalIsland";
import { ThreadLoadingSkeleton } from "@/components/thread/ThreadLoadingSkeleton";
import { StreamErrorNotice } from "@/components/thread/StreamErrorNotice";
import { ThreadViewport, type ThreadViewportHandle } from "@/components/thread/ThreadViewport";
@@ -1427,6 +1428,8 @@ export function ThreadShell({
<ThreadHeader
className={previewOpen ? "h-10" : undefined}
title={title}
goal={currentGoalState && (currentGoalState.active || currentGoalState.status === "blocked")
? <GoalIsland key={historyKey} goal={currentGoalState} /> : undefined}
onToggleSidebar={onToggleSidebar}
theme={theme}
onToggleTheme={onToggleTheme}
@@ -1334,6 +1334,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
initialLoading
? "overflow-hidden"
: cn("flex items-center justify-center", hasComposer && "sm:items-end sm:pb-8"),
"thread-empty-region",
)}
>
{emptyState}
@@ -15,6 +15,7 @@ import { SidebarSelectionHighlight, SIDEBAR_SELECTION_ITEM_CLASS } from "@/compo
import type { WorkspaceScopePayload, ProjectDirectory, WorkspaceDirectoriesPayload, WorkspacesPayload } from "@/lib/types";
import { createWorkspaceDirectoryCache } from "@/lib/workspace-directory-cache";
import { useMediaQuery } from "@/hooks/useMediaQuery";
import { useOverlayEscapeFocus } from "@/hooks/useOverlayEscapeFocus";
import { cn } from "@/lib/utils";
import { isAbsoluteWorkspacePath, projectNameFromPath, sameWorkspacePath, scopeWithAccessMode, workspaceBreadcrumbs, workspacePathCompletionQuery, workspaceDirectoryPrefix, selectedProjectScope, type BrowseWorkspaceDirectories } from "@/lib/workspace";
@@ -211,6 +212,7 @@ export function WorkspaceProjectPicker({ disabled, scope, defaultScope, controls
const triggerRef = useRef<HTMLButtonElement>(null);
const [keyboardInteraction, setKeyboardInteraction] = useState(false);
const openedWithKeyboard = useRef(false);
const escapeFocus = useOverlayEscapeFocus();
const inputRef = useRef<HTMLInputElement>(null);
const confirmRef = useRef<HTMLButtonElement>(null);
const optionsId = useId();
@@ -556,7 +558,7 @@ export function WorkspaceProjectPicker({ disabled, scope, defaultScope, controls
<Dialog open={open} onOpenChange={setOpen}>
<HoverHint content={`${t("workspace.picker.switchDirectory")}\n${displayedScope?.project_path ?? ""}`}>
<DialogTrigger asChild>
<button ref={triggerRef} onClick={event => { openedWithKeyboard.current = event.detail === 0; }} onPointerDown={() => setKeyboardInteraction(false)} onKeyDown={() => setKeyboardInteraction(true)} type="button" disabled={disabled} aria-label={t("workspace.picker.switchDirectory")} className="thread-composer-workspace touch-target inline-flex h-7 min-w-0 max-w-full items-center gap-1.5 rounded-md px-2 text-[12px] font-medium text-muted-foreground outline-none transition-colors motion-reduce:transition-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-55">
<button ref={triggerRef} {...escapeFocus.triggerProps} onClick={event => { openedWithKeyboard.current = event.detail === 0; }} onPointerDown={() => setKeyboardInteraction(false)} onKeyDown={() => setKeyboardInteraction(true)} type="button" disabled={disabled} aria-label={t("workspace.picker.switchDirectory")} className="thread-composer-workspace touch-target inline-flex h-7 min-w-0 max-w-full items-center gap-1.5 rounded-md px-2 text-[12px] font-medium text-muted-foreground outline-none transition-colors motion-reduce:transition-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-55">
<WorkspaceIcon className="h-3.5 w-3.5 shrink-0" />
<span className="min-w-0 truncate">{projectLabel}</span>
<ChevronDown className="h-3 w-3 shrink-0" aria-hidden />
@@ -571,8 +573,14 @@ export function WorkspaceProjectPicker({ disabled, scope, defaultScope, controls
if (!canBrowse || pickingFolder || event.nativeEvent.isComposing) return;
if ((event.metaKey || event.ctrlKey) && event.shiftKey && event.key.toLowerCase() === "g") { event.preventDefault(); editPath(); }
}}
onEscapeKeyDown={event => { if (editingPath) { event.preventDefault(); cancelPathEditing(); } }}
onCloseAutoFocus={event => { if (!openedWithKeyboard.current) event.preventDefault(); }}>
onEscapeKeyDown={event => {
if (editingPath) { event.preventDefault(); cancelPathEditing(); }
else escapeFocus.contentProps.onEscapeKeyDown();
}}
onCloseAutoFocus={event => {
escapeFocus.contentProps.onCloseAutoFocus(event);
if (!openedWithKeyboard.current) event.preventDefault();
}}>
<DialogTitle className="sr-only">{t("workspace.picker.title")}</DialogTitle>
<DialogDescription className="sr-only">{t("workspace.picker.description")}</DialogDescription>
<div className="flex shrink-0 items-center gap-1 bg-muted px-[var(--picker-toolbar-inset)] pt-[var(--picker-toolbar-inset)] pb-3">
+284
View File
@@ -0,0 +1,284 @@
@property --goal-island-width {
syntax: "<length-percentage>";
inherits: true;
initial-value: 100%;
}
@property --goal-island-height {
syntax: "<length-percentage>";
inherits: true;
initial-value: 100%;
}
@property --goal-island-radius {
syntax: "<length>";
inherits: true;
initial-value: 16px;
}
.thread-header-container {
container-type: inline-size;
}
.thread-header-with-goal > [data-header-controls="start"] {
max-width: calc(50% - min(18cqw, 10rem) - 24px);
}
.thread-header-with-goal [data-header-handle] {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.goal-island-position {
position: absolute;
top: 0;
left: 50%;
width: min(36cqw, 20rem);
transform: translateX(-50%);
pointer-events: auto;
}
.goal-island,
.goal-island-panel {
--goal-surface: hsl(var(--sidebar) / 94%);
--goal-highlight: rgb(255 255 255 / 80%);
--goal-shadow: rgb(20 20 24 / 10%);
--goal-blocked-color: hsl(0 42% 48%);
color: hsl(var(--sidebar-foreground));
}
:where(.dark) .goal-island,
:where(.dark) .goal-island-panel {
--goal-highlight: rgb(255 255 255 / 12%);
--goal-shadow: rgb(0 0 0 / 26%);
--goal-blocked-color: hsl(0 42% 70%);
}
.goal-island-trigger {
position: relative;
isolation: isolate;
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
width: 100%;
height: 40px;
padding: 0 16px;
border-radius: 0 0 16px 16px;
font-size: 12px;
text-align: center;
}
.goal-island[data-detail-mounted="true"] .goal-island-trigger {
opacity: 0;
}
.goal-island-trigger:focus-visible {
outline: none;
}
.goal-island-trigger:focus-visible > span:last-child {
text-decoration: underline;
text-decoration-thickness: 2px;
text-underline-offset: 4px;
}
.goal-island-panel {
--goal-island-radius: 28px;
isolation: isolate;
width: min(36rem, calc(100vw - 64px));
outline: none;
}
.goal-island-surface {
position: absolute;
z-index: -1;
top: 0;
left: 50%;
width: var(--goal-island-width);
height: var(--goal-island-height);
transform: translateX(-50%);
filter: drop-shadow(0 1px 0 var(--goal-highlight)) drop-shadow(0 7px 12px var(--goal-shadow));
pointer-events: none;
}
.goal-island-panel > .goal-island-surface {
filter: drop-shadow(0 1px 0 var(--goal-highlight)) drop-shadow(0 4px 5px hsl(240 10% 16% / 0.12));
}
:where(.dark) .goal-island-panel > .goal-island-surface {
filter: drop-shadow(0 1px 0 var(--goal-highlight)) drop-shadow(0 4px 5px hsl(240 12% 3% / 0.12));
}
.goal-island-surface::before {
content: "";
position: absolute;
inset: 0 -24px;
background: var(--goal-surface);
backdrop-filter: blur(20px) saturate(1.2);
-webkit-backdrop-filter: blur(20px) saturate(1.2);
clip-path: shape(
from 0 0,
hline to 100%,
curve to calc(100% - 24px) 24px with calc(100% - 13.255px) 0 / calc(100% - 24px) 10.745px,
vline to calc(100% - var(--goal-island-radius)),
arc to calc(100% - 24px - var(--goal-island-radius)) 100% of var(--goal-island-radius) cw,
hline to calc(24px + var(--goal-island-radius)),
arc to 24px calc(100% - var(--goal-island-radius)) of var(--goal-island-radius) cw,
vline to 24px,
curve to 0 0 with 24px 10.745px / 13.255px 0,
close
);
}
.goal-island-panel-content {
display: flex;
flex-direction: column;
max-height: inherit;
}
.goal-island-summary {
flex-shrink: 0;
margin: 0;
padding: 22px 24px 12px;
color: hsl(var(--foreground));
}
.goal-island-summary h2 {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
overflow-wrap: anywhere;
}
.goal-island-body {
--goal-fade-top: 0px;
--goal-fade-bottom: 0px;
min-height: 0;
overflow: auto;
overscroll-behavior: contain;
scrollbar-width: none;
overflow-wrap: anywhere;
mask-image: linear-gradient(to bottom, transparent, #000 var(--goal-fade-top), #000 calc(100% - var(--goal-fade-bottom)), transparent);
}
.goal-island-body::-webkit-scrollbar {
display: none;
}
.goal-island-body[data-overflow-top] {
--goal-fade-top: min(28px, 25%);
}
.goal-island-body[data-overflow-bottom] {
--goal-fade-bottom: min(36px, 25%);
}
.goal-island-document {
padding: 0 24px 24px;
}
.goal-island-body:first-child .goal-island-document {
padding-top: 24px;
}
.goal-island-body .markdown-content {
overflow-wrap: anywhere;
}
.goal-island-blocked {
display: flex;
align-items: flex-start;
gap: 8px;
padding-bottom: 12px;
border-bottom: 1px solid hsl(var(--foreground) / 0.08);
color: hsl(var(--foreground));
font-size: 14px;
line-height: 1.45;
}
.goal-island-blocked .markdown-content.goal-island-reason {
--tw-prose-body: var(--goal-blocked-color);
--tw-prose-headings: var(--goal-blocked-color);
--tw-prose-bold: var(--goal-blocked-color);
--tw-prose-lead: var(--goal-blocked-color);
min-width: 0;
color: var(--goal-blocked-color);
font-size: 14px;
line-height: 1.45;
}
.goal-island-panel[data-goal-status="blocked"] .goal-island-body[data-overflow-bottom] {
--goal-fade-bottom: 16px;
}
.goal-island-status-icon {
width: 1em;
height: 1em;
flex: none;
color: var(--goal-blocked-color);
}
.goal-island-reason {
color: var(--goal-blocked-color);
}
.goal-island-blocked .goal-island-status-icon {
margin-top: 0.225em;
}
.goal-island-panel[data-state="open"] {
animation: goal-island-expand 400ms cubic-bezier(0.2, 0.9, 0.1, 1) both;
}
.goal-island-panel[data-state="open"] .goal-island-panel-content {
animation: goal-island-content-in 200ms ease-out 100ms both;
}
.goal-island-panel[data-state="closed"] {
animation: goal-island-collapse 240ms cubic-bezier(0.4, 0, 0.2, 1) both;
pointer-events: none;
}
[data-radix-popper-content-wrapper]:has(> .goal-island-panel[data-state="closed"]) {
pointer-events: none;
}
.goal-island-panel[data-state="closed"] .goal-island-panel-content {
animation: goal-island-content-out 80ms ease-in both;
}
@keyframes goal-island-expand {
from {
--goal-island-width: var(--goal-from-width, var(--radix-popover-trigger-width));
--goal-island-height: var(--goal-from-height, 40px);
--goal-island-radius: var(--goal-from-radius, 16px);
}
to { --goal-island-width: 100%; --goal-island-height: 100%; --goal-island-radius: 28px; }
}
@keyframes goal-island-collapse {
from {
--goal-island-width: var(--goal-from-width);
--goal-island-height: var(--goal-from-height);
--goal-island-radius: var(--goal-from-radius);
}
to { --goal-island-width: var(--radix-popover-trigger-width); --goal-island-height: 40px; --goal-island-radius: 16px; }
}
@keyframes goal-island-content-in {
from { opacity: var(--goal-from-opacity, 0); transform: var(--goal-from-transform, translateY(-8px)); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes goal-island-content-out {
from { opacity: var(--goal-from-opacity); transform: var(--goal-from-transform); }
to { opacity: 0; transform: translateY(-8px); }
}
@media (max-width: 767px) {
.thread-header-with-goal:has(.goal-island[data-detail-mounted="true"]) {
z-index: 60;
}
.goal-island-summary {
padding-top: 44px;
}
.goal-island-body:first-child .goal-island-document {
padding-top: 44px;
}
}
@media (max-height: 600px) {
.goal-island-summary h2 {
-webkit-line-clamp: 1;
}
}
@media (prefers-reduced-motion: reduce) {
.goal-island-panel[data-state],
.goal-island-panel[data-state] .goal-island-panel-content {
animation: none;
}
}
@media (prefers-reduced-transparency: reduce), (prefers-contrast: more) {
.goal-island,
.goal-island-panel {
--goal-surface: hsl(var(--sidebar));
}
.goal-island-surface::before {
backdrop-filter: none;
-webkit-backdrop-filter: none;
}
}
@media (forced-colors: active) {
.goal-island,
.goal-island-panel {
--goal-surface: Canvas;
}
.goal-island-surface {
outline: 1px solid CanvasText;
}
.goal-island,
.goal-island-panel {
color: CanvasText;
}
}
@@ -0,0 +1,87 @@
:root[data-session-transition] {
view-transition-name: none;
}
:root[data-session-transition] :is(.thread-message-viewport, .thread-empty-region) {
view-transition-name: var(--session-thread-name, session-thread-0);
view-transition-class: session-thread;
}
:root[data-session-transition] [data-active-composer] .thread-composer-surface {
view-transition-name: session-composer;
}
:root[data-session-transition] [data-active-composer] .thread-composer-input {
view-transition-name: session-input;
}
:root[data-session-transition] [data-active-composer] .thread-composer-footer {
view-transition-name: session-toolbar;
}
:root[data-session-transition] [data-active-composer] .thread-composer-meta {
view-transition-name: session-meta;
}
:root[data-session-transition] .goal-island {
view-transition-name: session-goal;
}
:root[data-session-transition] [data-active-composer] .subagent-task-dock {
view-transition-name: session-tasks;
}
:root[data-session-transition]::view-transition {
pointer-events: none;
}
:root[data-session-transition]::view-transition-group(*) {
animation-duration: 200ms;
animation-timing-function: cubic-bezier(0.2, 0, 0, 1);
}
/* The frame may change size; keep text at its original raster size and bottom anchor. */
:root[data-session-transition]::view-transition-old(*),
:root[data-session-transition]::view-transition-new(*) {
object-fit: none;
object-position: bottom left;
mix-blend-mode: normal;
}
:root[data-session-transition]::view-transition-old(session-composer),
:root[data-session-transition]::view-transition-old(session-input),
:root[data-session-transition]::view-transition-old(session-toolbar),
:root[data-session-transition]::view-transition-old(session-meta) {
display: none;
}
:root[data-session-transition]::view-transition-new(session-composer),
:root[data-session-transition]::view-transition-new(session-input),
:root[data-session-transition]::view-transition-new(session-toolbar),
:root[data-session-transition]::view-transition-new(session-meta) {
animation: none;
}
:root[data-session-transition]::view-transition-group(.session-thread) {
animation: none;
}
:root[data-session-transition]::view-transition-old(.session-thread),
:root[data-session-transition]::view-transition-new(.session-thread) {
object-position: top left;
}
:root[data-session-transition]::view-transition-old(.session-thread) {
animation: session-thread-out 80ms ease-in both;
}
:root[data-session-transition]::view-transition-new(.session-thread) {
animation: session-thread-in 120ms ease-out 60ms both;
}
@keyframes session-thread-out {
to { opacity: 0; }
}
@keyframes session-thread-in {
from { opacity: 0; }
to { opacity: 1; }
}
@media (prefers-reduced-motion: reduce) {
:root[data-session-transition]::view-transition-group(*),
:root[data-session-transition]::view-transition-new(*) {
animation: none;
}
:root[data-session-transition]::view-transition-old(*) {
display: none;
}
}
@@ -0,0 +1,46 @@
import { flushSync } from "react-dom";
import "./session-transition.css";
let active: ViewTransition | null = null;
let pending: (() => void) | null = null;
export function finishSessionTransition(): void {
const update = pending;
pending = null;
active?.skipTransition();
active = null;
delete document.documentElement.dataset.sessionTransition;
if (update) flushSync(update);
}
export function transitionSession(update: () => void, animate = true): void {
pending = update;
active?.skipTransition();
const root = document.documentElement;
if (!animate || !document.startViewTransition
|| window.matchMedia("(prefers-reduced-motion: reduce)").matches
|| root.hasAttribute("data-theme-snapshot")) {
active = null;
pending = null;
delete root.dataset.sessionTransition;
update();
return;
}
root.dataset.sessionTransition = "";
const transition = document.startViewTransition(() => {
if (pending !== update) return;
pending = null;
flushSync(update);
});
active = transition;
// Skipped captures still run their update; only the latest navigation may commit.
void transition.ready.catch(() => {});
const release = () => {
if (active !== transition) return;
active = null;
delete root.dataset.sessionTransition;
};
void transition.finished.then(release, release);
}
+3 -2
View File
@@ -15,12 +15,13 @@ const PopoverTrigger = PopoverPrimitive.Trigger;
interface PopoverContentProps
extends React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content> {
portalContainer?: HTMLElement | null;
motionClassName?: string;
}
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
PopoverContentProps
>(({ className, sideOffset = 4, portalContainer, ...props }, ref) => {
>(({ className, sideOffset = 4, portalContainer, motionClassName = floatingSurfaceMotionClassName, ...props }, ref) => {
const dialogContainer = useFloatingPortal();
return (
<PopoverPrimitive.Portal container={portalContainer ?? dialogContainer ?? undefined}>
@@ -29,7 +30,7 @@ const PopoverContent = React.forwardRef<
sideOffset={sideOffset}
className={cn(
floatingSurfaceClassName,
floatingSurfaceMotionClassName,
motionClassName,
"origin-[var(--radix-popover-content-transform-origin)] max-h-[min(var(--radix-popover-content-available-height),28rem)]",
className,
)}
@@ -8,6 +8,7 @@ import {
type LucideIcon,
} from "lucide-react";
import {
type CSSProperties,
type FocusEvent,
type KeyboardEvent,
type PointerEvent as ReactPointerEvent,
@@ -723,7 +724,10 @@ export function PaneWorkbench({
"workbench-pane relative flex min-h-0 min-w-0 overflow-hidden bg-background",
chrome && displayedPanes.length > 1 && "shadow-[0_0_0_1px_hsl(var(--border)/0.55)]",
)}
style={layoutGeometry.paneStyles[index]}
style={{
...layoutGeometry.paneStyles[index],
"--session-thread-name": `session-thread-${index}`,
} as CSSProperties}
>
{renderPane(pane, {
active,
+16
View File
@@ -6,6 +6,7 @@ import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster";
import { ComposerUsagePopover, type ComposerRoundUsage } from "@/components/thread/ComposerUsagePopover";
import type { ContextSnapshot } from "@/lib/types";
import { ContextCompactionNotice } from "@/components/thread/ContextCompactionNotice";
import { GoalIsland } from "@/components/thread/GoalIsland";
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
import { SandboxNotice, type SandboxIssue } from "@/components/thread/SandboxNotice";
import { ModelPresetBadge, type ModelPresetOption } from "@/components/thread/ModelPresetBadge";
@@ -89,6 +90,18 @@ function ComposerPreview() {
</div>;
}
function GoalPreview() {
const { t } = useGalleryTranslation();
const [status, setStatus] = useState<"active" | "blocked">("active");
return <div>
<StatePicker label={t("previews.goal.state")} value={status} options={["active", "blocked"]} onChange={setStatus} />
<div className="thread-header-container relative h-56 overflow-hidden rounded-control border bg-background">
<GoalIsland goal={{ active: status === "active", status, ui_summary: t("previews.goal.summary"), objective: t("previews.goal.objective"),
...(status === "blocked" ? { recap: t("previews.goal.recap") } : {}) }} />
</div>
</div>;
}
function ModelPresetPreview() {
const { t } = useTranslation();
const { t: g } = useGalleryTranslation();
@@ -343,6 +356,9 @@ function ResponseSourcesPreview() {
const components = "webui/src/components/";
export const conversationExamples: ComponentExample[] = [
{ title: "previews.goal.title", files: ["thread/GoalIsland"], Preview: GoalPreview,
description: "previews.goal.description", options: "previews.goal.options",
code: '<GoalIsland goal={{ active: true, status: "active", ui_summary: summary, objective }} />' },
{ title: "previews.composer.title", files: ["thread/ThreadComposer"], Preview: ComposerPreview,
description: "previews.composer.description", options: "previews.composer.options",
code: '<ThreadComposer onSend={send} modelPresets={presets} onModelPresetChange={setPreset} slashCommands={commands} />' },
@@ -1,4 +1,13 @@
{
"goal": {
"title": "GoalIsland · Goal",
"description": "Preview the goal and its details.",
"options": "Pass the goal status, summary, objective and optional recap.",
"state": "Status",
"summary": "Prepare the release",
"objective": "Review the changes and verify the release.\n\n- Check tests\n- Review documentation\n- Confirm readiness",
"recap": "Waiting for approval."
},
"rename": {
"title": "RenameDialog · Rename groups and projects",
"description": "Try the rename dialog for groups and projects. Topics are renamed inline in the chat list.",
@@ -1,4 +1,13 @@
{
"goal": {
"title": "GoalIsland · Objetivo",
"description": "Previsualiza el objetivo y sus detalles.",
"options": "Proporciona el estado, resumen, objetivo y un avance opcional.",
"state": "Estado",
"summary": "Preparar la versión",
"objective": "Revisa los cambios y verifica la versión.\n\n- Comprobar las pruebas\n- Revisar la documentación\n- Confirmar que está lista",
"recap": "Esperando aprobación."
},
"rename": {
"title": "RenameDialog · Renombrar grupos y proyectos",
"description": "Prueba el cambio de nombre de grupos y proyectos. Los temas se renombran en la lista de chats.",
@@ -1,4 +1,13 @@
{
"goal": {
"title": "GoalIsland · Objectif",
"description": "Prévisualisez l’objectif et ses détails.",
"options": "Fournissez l’état, le résumé, l’objectif et un bilan facultatif.",
"state": "État",
"summary": "Préparer la publication",
"objective": "Examinez les modifications et vérifiez la publication.\n\n- Vérifier les tests\n- Relire la documentation\n- Confirmer que tout est prêt",
"recap": "En attente d’approbation."
},
"rename": {
"title": "RenameDialog · Renommer groupes et projets",
"description": "Essayez le renommage des groupes et projets. Les sujets se renomment dans la liste des discussions.",
@@ -1,4 +1,13 @@
{
"goal": {
"title": "GoalIsland · Tujuan",
"description": "Pratinjau tujuan dan detailnya.",
"options": "Berikan status, ringkasan, tujuan, dan laporan opsional.",
"state": "Status",
"summary": "Siapkan rilis",
"objective": "Tinjau perubahan dan verifikasi rilis.\n\n- Periksa pengujian\n- Tinjau dokumentasi\n- Pastikan rilis siap",
"recap": "Menunggu persetujuan."
},
"rename": {
"title": "RenameDialog · Ubah nama grup dan proyek",
"description": "Coba dialog pengubahan nama grup dan proyek. Nama topik diubah langsung di daftar percakapan.",
@@ -1,4 +1,13 @@
{
"goal": {
"title": "GoalIsland · 目標",
"description": "目標と詳細をプレビューします。",
"options": "目標の状態、要約、内容、任意の進捗を渡します。",
"state": "状態",
"summary": "リリースの準備",
"objective": "変更を確認し、リリースを検証します。\n\n- テストを確認\n- ドキュメントを確認\n- リリースの準備を確認",
"recap": "承認待ち。"
},
"rename": {
"title": "RenameDialog · グループとプロジェクトの名前変更",
"description": "グループとプロジェクトの名前変更を試せます。トピック名はチャット一覧内で変更します。",
@@ -1,4 +1,13 @@
{
"goal": {
"title": "GoalIsland · 목표",
"description": "목표와 세부 내용을 미리 봅니다.",
"options": "목표 상태, 요약, 내용 및 선택적 진행 내용을 전달합니다.",
"state": "상태",
"summary": "릴리스 준비",
"objective": "변경 사항을 검토하고 릴리스를 검증합니다.\n\n- 테스트 확인\n- 문서 검토\n- 릴리스 준비 확인",
"recap": "승인 대기 중."
},
"rename": {
"title": "RenameDialog · 그룹 및 프로젝트 이름 변경",
"description": "그룹과 프로젝트의 이름 변경을 시험합니다. 주제 이름은 채팅 목록에서 바로 바꿉니다.",
@@ -1,4 +1,13 @@
{
"goal": {
"title": "GoalIsland · Objetivo",
"description": "Visualize o objetivo e seus detalhes.",
"options": "Informe o estado, resumo, objetivo e um balanço opcional.",
"state": "Estado",
"summary": "Preparar o lançamento",
"objective": "Revise as alterações e verifique o lançamento.\n\n- Verificar os testes\n- Revisar a documentação\n- Confirmar que está pronto",
"recap": "Aguardando aprovação."
},
"rename": {
"title": "RenameDialog · Renomear grupos e projetos",
"description": "Teste a renomeação de grupos e projetos. Os tópicos são renomeados na lista de conversas.",
@@ -1,4 +1,13 @@
{
"goal": {
"title": "GoalIsland · Mục tiêu",
"description": "Xem trước mục tiêu và chi tiết.",
"options": "Truyền trạng thái, tóm tắt, mục tiêu và báo cáo tùy chọn.",
"state": "Trạng thái",
"summary": "Chuẩn bị phát hành",
"objective": "Xem lại thay đổi và xác minh bản phát hành.\n\n- Kiểm tra thử nghiệm\n- Xem lại tài liệu\n- Xác nhận sẵn sàng",
"recap": "Đang chờ phê duyệt."
},
"rename": {
"title": "RenameDialog · Đổi tên nhóm và dự án",
"description": "Thử hộp thoại đổi tên nhóm và dự án. Chủ đề được đổi tên ngay trong danh sách trò chuyện.",
@@ -1,4 +1,13 @@
{
"goal": {
"title": "GoalIsland · 目标",
"description": "预览目标及其详情。",
"options": "传入目标状态、摘要、内容及可选的进展说明。",
"state": "状态",
"summary": "准备发布",
"objective": "检查变更并验证发布。\n\n- 检查测试\n- 审阅文档\n- 确认发布准备就绪",
"recap": "等待批准。"
},
"rename": {
"title": "RenameDialog · 分组与项目改名",
"description": "预览分组和项目改名;话题在列表行内改名。",
@@ -1,4 +1,13 @@
{
"goal": {
"title": "GoalIsland · 目標",
"description": "預覽目標及其詳情。",
"options": "傳入目標狀態、摘要、內容及選用的進度說明。",
"state": "狀態",
"summary": "準備發布",
"objective": "檢查變更並驗證發布。\n\n- 檢查測試\n- 審閱文件\n- 確認發布準備就緒",
"recap": "等待批准。"
},
"rename": {
"title": "RenameDialog · 群組與專案改名",
"description": "預覽群組與專案改名;話題在清單內改名。",
-40
View File
@@ -759,39 +759,6 @@
.composer-status-strip[data-state="enter"] {
animation: composer-status-strip-enter 280ms cubic-bezier(0.16, 1, 0.3, 1) both;
}
.composer-status-drawer {
--composer-status-drawer-duration: 220ms;
--composer-status-drawer-easing: ease-out;
display: grid;
grid-template-rows: 0fr;
pointer-events: none;
transition:
grid-template-rows var(--composer-status-drawer-duration)
var(--composer-status-drawer-easing);
}
.composer-status-drawer[data-state="open"] {
grid-template-rows: 1fr;
pointer-events: auto;
}
.composer-status-drawer-clip {
min-height: 0;
overflow: hidden;
}
.composer-status-drawer-content {
opacity: 0;
transform: translateY(8px);
transform-origin: bottom center;
transition:
opacity var(--composer-status-drawer-duration)
var(--composer-status-drawer-easing),
transform var(--composer-status-drawer-duration)
var(--composer-status-drawer-easing);
}
.composer-status-drawer[data-state="open"] .composer-status-drawer-content {
opacity: 1;
transform: translateY(0);
}
.inline-disclosure {
--inline-disclosure-duration: 220ms;
@@ -837,13 +804,6 @@
.composer-status-strip[data-state] {
animation: none;
}
.composer-status-drawer {
transition-duration: 0.01ms;
}
.composer-status-drawer-content {
transform: none;
transition-duration: 120ms, 0.01ms;
}
.thread-layout {
transition-duration: 0.01ms;
}
+40
View File
@@ -0,0 +1,40 @@
import { useRef, type KeyboardEvent, type PointerEvent } from "react";
/** Return Escape to the control that opening an overlay interrupted. */
export function useOverlayEscapeFocus() {
const opener = useRef<HTMLElement | null>(null);
const trigger = useRef<HTMLElement | null>(null);
const escaped = useRef(false);
return {
triggerProps: {
onPointerDownCapture: (event: PointerEvent<HTMLElement>) => {
if (event.button !== 0) return;
if (!escaped.current) opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
escaped.current = false;
trigger.current = event.currentTarget;
},
onKeyDownCapture: (event: KeyboardEvent<HTMLElement>) => {
if (event.key === "Enter" || event.key === " ") {
escaped.current = false;
trigger.current = event.currentTarget;
opener.current = event.currentTarget;
}
},
},
contentProps: {
onEscapeKeyDown: () => { escaped.current = true; },
onCloseAutoFocus: (event: Event) => {
const target = escaped.current ? opener.current : null;
opener.current = null;
escaped.current = false;
if (!event.defaultPrevented && target?.isConnected && target !== document.body) {
event.preventDefault();
const active = document.activeElement;
if (active === document.body || active === trigger.current || (event.target instanceof HTMLElement && event.target.contains(active))) {
target.focus({ preventScroll: true });
}
}
},
},
};
}
+2
View File
@@ -9,6 +9,7 @@ import {
type ReactNode,
} from "react";
import { flushSync } from "react-dom";
import { finishSessionTransition } from "@/components/thread/session-transition";
import "./theme-transition.css";
import { useMediaQuery } from "@/hooks/useMediaQuery";
@@ -93,6 +94,7 @@ export function useTheme(): {
// Same-palette choices, such as switching to System, must remain selectable.
if (changesPalette) {
if (switchTimer.current !== null || viewTransition.current !== null) return;
finishSessionTransition();
root.dataset.themeTransition = next;
switchTimer.current = setTimeout(() => {
switchTimer.current = null;
+1 -1
View File
@@ -2117,8 +2117,8 @@
"goalStateStrip": "Goal: {{label}}",
"goalStateFallback": "Goal",
"goalStateExpandAria": "Show full goal",
"goalBlocked": "Blocked",
"goalStateSheetTitle": "Goal",
"goalStateCloseAria": "Close goal",
"send": "Send message",
"stop": "Stop response",
"quotedContext": "Quoted context",
+1 -1
View File
@@ -1935,8 +1935,8 @@
"goalStateStrip": "Objetivo: {{label}}",
"goalStateFallback": "Objetivo",
"goalStateExpandAria": "Ver objetivo completo",
"goalBlocked": "Bloqueado",
"goalStateSheetTitle": "Objetivo",
"goalStateCloseAria": "Cerrar objetivo",
"send": "Enviar mensaje",
"stop": "Detener respuesta",
"quotedContext": "Contexto citado",
+1 -1
View File
@@ -1935,8 +1935,8 @@
"goalStateStrip": "Objectif: {{label}}",
"goalStateFallback": "Objectif",
"goalStateExpandAria": "Afficher l’objectif complet",
"goalBlocked": "Bloqué",
"goalStateSheetTitle": "Objectif",
"goalStateCloseAria": "Fermer l’objectif",
"send": "Envoyer le message",
"stop": "Arrêter la réponse",
"quotedContext": "Contexte cité",
+1 -1
View File
@@ -1935,8 +1935,8 @@
"goalStateStrip": "Tujuan: {{label}}",
"goalStateFallback": "Tujuan",
"goalStateExpandAria": "Lihat tujuan lengkap",
"goalBlocked": "Terhambat",
"goalStateSheetTitle": "Tujuan",
"goalStateCloseAria": "Tutup tujuan",
"send": "Kirim pesan",
"stop": "Hentikan respons",
"quotedContext": "Konteks kutipan",
+1 -1
View File
@@ -1935,8 +1935,8 @@
"goalStateStrip": "目標: {{label}}",
"goalStateFallback": "目標",
"goalStateExpandAria": "目標の全文を表示",
"goalBlocked": "進行不可",
"goalStateSheetTitle": "目標",
"goalStateCloseAria": "目標を閉じる",
"send": "メッセージを送信",
"stop": "応答を停止",
"quotedContext": "引用したコンテキスト",
+1 -1
View File
@@ -1935,8 +1935,8 @@
"goalStateStrip": "목표: {{label}}",
"goalStateFallback": "목표",
"goalStateExpandAria": "전체 목표 보기",
"goalBlocked": "진행 막힘",
"goalStateSheetTitle": "목표",
"goalStateCloseAria": "목표 닫기",
"send": "메시지 보내기",
"stop": "응답 중지",
"quotedContext": "인용한 문맥",
+1 -1
View File
@@ -1937,8 +1937,8 @@
"goalStateStrip": "Objetivo: {{label}}",
"goalStateFallback": "Objetivo",
"goalStateExpandAria": "Mostrar objetivo completo",
"goalBlocked": "Bloqueado",
"goalStateSheetTitle": "Objetivo",
"goalStateCloseAria": "Fechar objetivo",
"send": "Enviar mensagem",
"stop": "Parar resposta",
"quotedContext": "Contexto citado",
+1 -1
View File
@@ -1935,8 +1935,8 @@
"goalStateStrip": "Mục tiêu: {{label}}",
"goalStateFallback": "Mục tiêu",
"goalStateExpandAria": "Xem đầy đủ mục tiêu",
"goalBlocked": "Bị chặn",
"goalStateSheetTitle": "Mục tiêu",
"goalStateCloseAria": "Đóng mục tiêu",
"send": "Gửi tin nhắn",
"stop": "Dừng phản hồi",
"quotedContext": "Ngữ cảnh được trích dẫn",
+1 -1
View File
@@ -2117,6 +2117,7 @@
"goalStateStrip": "目标:{{label}}",
"goalStateFallback": "目标",
"goalStateExpandAria": "查看完整目标",
"goalBlocked": "已阻塞",
"goalStateSheetTitle": "目标",
"send": "发送消息",
"stop": "停止响应",
@@ -2310,7 +2311,6 @@
"total_too_large": "附件总大小过大,请移除部分文件或使用更小的文件",
"io": "无法读取该文件"
},
"goalStateCloseAria": "关闭目标",
"workspace": {
"accessAria": "工作区访问权限",
"projectAria": "选择项目",
+1 -1
View File
@@ -1935,8 +1935,8 @@
"goalStateStrip": "目標:{{label}}",
"goalStateFallback": "目標",
"goalStateExpandAria": "檢視完整目標",
"goalBlocked": "已受阻",
"goalStateSheetTitle": "目標",
"goalStateCloseAria": "關閉目標",
"send": "送出訊息",
"stop": "停止回覆",
"quotedContext": "引用內容",
+97 -30
View File
@@ -926,13 +926,13 @@ describe("App layout", () => {
expect(await screen.findByText(firstMessage)).toBeInTheDocument();
});
it("creates a new temporary chat from the hero each time", async () => {
it.each([false, true])("closes the active temporary chat without losing its replacement (pending capture=%s)", async (pendingCapture) => {
const { unmount } = render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
expect(within(sidebar).queryByRole("button", { name: "Temporary chat" })).not.toBeInTheDocument();
const firstToggle = screen.getByRole("button", { name: "Temporary chat" });
const firstToggle = await screen.findByRole("button", { name: "Temporary chat" });
expect(firstToggle).toHaveAttribute("aria-pressed", "false");
fireEvent.click(firstToggle);
expect(firstToggle).toHaveAttribute("aria-pressed", "true");
@@ -974,36 +974,66 @@ describe("App layout", () => {
name: "second private message",
})).toBeInTheDocument();
fireEvent.click(within(sidebar).getByRole("button", {
name: "first private message",
}));
await waitFor(() => expect(window.location.hash).toBe(firstHash));
expect(within(screen.getByTestId("thread-header")).getByText(
"first private message",
)).toBeInTheDocument();
await waitFor(() => expect(document.title).toBe("first private message"));
expect(screen.queryByRole("button", { name: "Temporary chat" })).not.toBeInTheDocument();
// Native capture delays the update callback, so React can run the route
// cleanup effect before it. Do not replace transitionSession with a sync mock.
const descriptor = Object.getOwnPropertyDescriptor(document, "startViewTransition");
const captures: (() => void)[] = [];
const capture = vi.fn((update: () => void) => {
const finished = new Promise<void>((resolve) => {
captures.push(() => { update(); resolve(); });
});
return { ready: finished, finished, skipTransition: vi.fn() };
});
const completeCaptures = async () => {
while (captures.length) await act(async () => { captures.shift()!(); });
};
Object.defineProperty(document, "startViewTransition", { configurable: true, value: capture });
try {
fireEvent.click(within(sidebar).getByRole("button", {
name: "first private message",
}));
expect(capture).toHaveBeenCalledTimes(1);
expect(window.location.hash).toBe(secondHash);
await completeCaptures();
await waitFor(() => expect(window.location.hash).toBe(firstHash));
expect(within(screen.getByTestId("thread-header")).getByText(
"first private message",
)).toBeInTheDocument();
await waitFor(() => expect(document.title).toBe("first private message"));
expect(screen.queryByRole("button", { name: "Temporary chat" })).not.toBeInTheDocument();
fireEvent.click(within(sidebar).getByRole("button", {
name: "Close temporary chat: first private message",
}));
await waitFor(() => expect(window.location.hash).toBe(secondHash));
expect(within(sidebar).queryByRole("button", {
name: "first private message",
})).not.toBeInTheDocument();
expect(within(sidebar).getByRole("button", {
name: "second private message",
})).toBeInTheDocument();
expect(discardTemporaryChatSpy).toHaveBeenCalledTimes(1);
if (pendingCapture) {
fireEvent.click(within(sidebar).getByRole("button", { name: "second private message" }));
expect(window.location.hash).toBe(firstHash);
expect(captures).toHaveLength(1);
}
fireEvent.click(within(sidebar).getByRole("button", {
name: "Close temporary chat: first private message",
}));
await completeCaptures();
await waitFor(() => expect(window.location.hash).toBe(secondHash));
expect(within(screen.getByTestId("thread-header")).getByText("second private message")).toBeInTheDocument();
expect(within(sidebar).queryByRole("button", {
name: "first private message",
})).not.toBeInTheDocument();
expect(within(sidebar).getByRole("button", {
name: "second private message",
})).toBeInTheDocument();
expect(discardTemporaryChatSpy).toHaveBeenCalledTimes(1);
unmount();
await waitFor(() => expect(discardTemporaryChatSpy).toHaveBeenCalledTimes(2));
const discardedChatIds = discardTemporaryChatSpy.mock.calls.map(([chatId]) => chatId);
expect(new Set(discardedChatIds).size).toBe(2);
expect(discardedChatIds).toEqual([
"00000000-0000-4000-8000-000000000001",
"00000000-0000-4000-8000-000000000002",
]);
unmount();
await waitFor(() => expect(discardTemporaryChatSpy).toHaveBeenCalledTimes(2));
const discardedChatIds = discardTemporaryChatSpy.mock.calls.map(([chatId]) => chatId);
expect(new Set(discardedChatIds).size).toBe(2);
expect(discardedChatIds).toEqual([
"00000000-0000-4000-8000-000000000001",
"00000000-0000-4000-8000-000000000002",
]);
} finally {
await completeCaptures();
if (descriptor) Object.defineProperty(document, "startViewTransition", descriptor);
else Reflect.deleteProperty(document, "startViewTransition");
}
});
it("shows the temporary-chat control only on the new-topic hero", async () => {
@@ -3927,6 +3957,43 @@ describe("App layout", () => {
expect(screen.queryByRole("menuitem", { name: "Move to" })).not.toBeInTheDocument();
});
it.each([false, true])("animates replaced threads rather than focusing a visible pane (mobile=%s)", async mobile => {
vi.stubGlobal("matchMedia", vi.fn((query: string) => ({
matches: mobile && query.includes("max-width: 767px"), media: query, onchange: null,
addListener: vi.fn(), removeListener: vi.fn(), addEventListener: vi.fn(), removeEventListener: vi.fn(), dispatchEvent: vi.fn(),
})));
mockSessions = ["alpha", "child", "other"].map(chatId => ({
key: `websocket:${chatId}`, channel: "websocket", chatId,
createdAt: null, updatedAt: null, title: `${chatId} topic`, preview: "",
}));
window.history.replaceState(null, "", "/#/chat/websocket%3Aalpha");
mockFetchRoutes({ "/api/webui/sidebar-state": { workbench: { version: 1, tabs: {
"tab:alpha": { explicit: true, title: "Group", paneKeys: ["websocket:alpha", "websocket:child"], layout: "columns" },
} } } });
render(<App />);
await act(async () => { await import("@/components/thread/ThreadShell"); });
await screen.findByTestId("workbench-pane-websocket:alpha");
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
await within(sidebar).findByRole("button", { name: "Group: Group" });
const descriptor = Object.getOwnPropertyDescriptor(document, "startViewTransition");
const capture = vi.fn((update: () => void) => {
update();
return { ready: Promise.resolve(), finished: Promise.resolve(), skipTransition: vi.fn() };
});
Object.defineProperty(document, "startViewTransition", { configurable: true, value: capture });
try {
fireEvent.click(within(sidebar).getByRole("button", { name: "child topic" }));
await waitFor(() => expect(screen.getByTestId("workbench-pane-websocket:child")).toHaveAttribute("data-active", "true"));
expect(capture).toHaveBeenCalledTimes(mobile ? 1 : 0);
fireEvent.click(within(sidebar).getByRole("button", { name: "other topic" }));
await screen.findByTestId("workbench-pane-websocket:other");
expect(capture).toHaveBeenCalledTimes(mobile ? 2 : 1);
} finally {
if (descriptor) Object.defineProperty(document, "startViewTransition", descriptor);
else Reflect.deleteProperty(document, "startViewTransition");
}
});
it("materializes a singleton tab without linking it to another pane", async () => {
mockSessions = [
{
+64
View File
@@ -0,0 +1,64 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { GoalIsland } from "@/components/thread/GoalIsland";
import { ThreadComposer } from "@/components/thread/ThreadComposer";
import { ThreadHeader } from "@/components/thread/ThreadHeader";
const goal = { active: true, ui_summary: "Ship the release", objective: "Verify the full release checklist." };
function Conversation({ blocked = false }: { blocked?: boolean }) {
return <>
<ThreadHeader title="Release planning" onToggleSidebar={vi.fn()} theme="light" onToggleTheme={vi.fn()}
goal={<GoalIsland goal={{ ...goal, active: !blocked, status: blocked ? "blocked" : "active", ...(blocked ? { recap: "Waiting for approval." } : {}) }} />} />
<ThreadComposer onSend={vi.fn()} persistDraft={false} goalState={goal} />
</>;
}
describe("GoalIsland", () => {
it("shows the summary and complete objective, dismissing through Escape and outside input without losing its draft", async () => {
const user = userEvent.setup();
render(<Conversation />);
const input = screen.getByRole("textbox", { name: "Message input" });
await user.type(input, "Keep my draft");
const trigger = screen.getByRole("button", { name: "Show full goal" });
await user.click(trigger);
const dialog = await screen.findByRole("dialog", { name: "Goal" });
expect(dialog).toHaveTextContent(goal.ui_summary);
expect(dialog).toHaveTextContent(goal.objective);
expect(trigger).toHaveAttribute("aria-expanded", "true");
await user.keyboard("{Escape}");
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(input).toHaveFocus();
await user.click(trigger);
await user.click(input);
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(input).toHaveValue("Keep my draft");
expect(input).toHaveFocus();
});
it("returns keyboard-opened details to their trigger on Escape", async () => {
const user = userEvent.setup();
render(<Conversation />);
await user.click(screen.getByRole("textbox", { name: "Message input" }));
const trigger = screen.getByRole("button", { name: "Show full goal" });
trigger.focus();
await user.keyboard("{Enter}");
expect(screen.getByRole("dialog", { name: "Goal" })).toBeVisible();
await user.keyboard("{Escape}");
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(trigger).toHaveFocus();
});
it("updates the active goal to blocked with the gateway recap while keeping the expanded view", async () => {
const user = userEvent.setup();
const { rerender } = render(<Conversation />);
await user.click(screen.getByRole("button", { name: "Show full goal" }));
expect(screen.getByRole("heading", { name: goal.ui_summary })).toBeVisible();
rerender(<Conversation blocked />);
const dialog = screen.getByRole("dialog");
expect(dialog).toHaveTextContent("Blocked");
expect(dialog).toHaveTextContent(/Waiting for approval\..*Verify the full release checklist\./);
});
});
@@ -185,3 +185,42 @@ describe("ModelPresetBadge selected preset tooltip", () => {
await waitFor(() => expect(screen.queryByRole("tooltip")).not.toBeInTheDocument());
});
});
describe("ModelPresetBadge dismissal focus", () => {
it("does not request composer focus for an outside click", async () => {
const user = userEvent.setup();
const onRequestComposerFocus = vi.fn();
render(<><ModelPresetBadge label="zhipu" modelPreset="zhipu" modelPresets={presets}
onPresetChange={vi.fn()} onRequestComposerFocus={onRequestComposerFocus} isHero /><input aria-label="Other field" /></>);
await user.click(screen.getByRole("button", { name: "zhipu" }));
const outside = screen.getByRole("textbox", { name: "Other field" });
await user.click(outside);
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(outside).toHaveFocus();
expect(onRequestComposerFocus).not.toHaveBeenCalled();
});
it("returns keyboard Escape to the picker rather than requesting composer focus", async () => {
const user = userEvent.setup();
const onRequestComposerFocus = vi.fn();
render(<ModelPresetBadge label="zhipu" modelPreset="zhipu" modelPresets={presets}
onPresetChange={vi.fn()} onRequestComposerFocus={onRequestComposerFocus} isHero />);
const trigger = screen.getByRole("button", { name: "zhipu" });
await user.tab();
await user.keyboard("{Enter}{Escape}");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
await waitFor(() => expect(trigger).toHaveFocus());
expect(onRequestComposerFocus).not.toHaveBeenCalled();
});
it("requests composer focus once after a picker selection closes", async () => {
const user = userEvent.setup();
const onRequestComposerFocus = vi.fn();
render(<ModelPresetBadge label="zhipu" modelPreset="zhipu" modelPresets={presets}
onPresetChange={vi.fn()} onRequestComposerFocus={onRequestComposerFocus} isHero />);
await user.click(screen.getByRole("button", { name: "zhipu" }));
await user.click(screen.getByRole("option", { name: "codex" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(onRequestComposerFocus).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,67 @@
import { useRef } from "react";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, expect, it } from "vitest";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { useOverlayEscapeFocus } from "@/hooks/useOverlayEscapeFocus";
import { mockBrowserFocus } from "./browser-focus";
let restoreBrowserFocus: () => void;
beforeEach(() => { restoreBrowserFocus = mockBrowserFocus(); });
afterEach(() => restoreBrowserFocus());
function FocusFixture({ override = false }: { override?: boolean }) {
const escapeFocus = useOverlayEscapeFocus();
const destination = useRef<HTMLInputElement>(null);
return <>
<input aria-label="Editing field" />
<Popover><PopoverTrigger asChild><button {...escapeFocus.triggerProps}>Open information</button></PopoverTrigger>
<PopoverContent {...escapeFocus.contentProps} onCloseAutoFocus={(event) => {
if (override) { event.preventDefault(); destination.current?.focus(); }
escapeFocus.contentProps.onCloseAutoFocus(event);
}}><input aria-label="Popover field" /></PopoverContent>
</Popover>
<input ref={destination} aria-label="Destination field" />
</>;
}
it("returns pointer-open / Escape to the interrupted editing field", async () => {
const user = userEvent.setup();
render(<FocusFixture />);
const editor = screen.getByRole("textbox", { name: "Editing field" });
await user.click(editor);
await user.click(screen.getByRole("button", { name: "Open information" }));
await user.keyboard("{Escape}");
await waitFor(() => expect(editor).toHaveFocus());
});
it("returns keyboard-open / Escape to the trigger", async () => {
const user = userEvent.setup();
render(<FocusFixture />);
await user.tab();
await user.tab();
const trigger = screen.getByRole("button", { name: "Open information" });
expect(trigger).toHaveFocus();
await user.keyboard("{Enter}{Escape}");
await waitFor(() => expect(trigger).toHaveFocus());
});
it("leaves outside-click focus with the clicked field", async () => {
const user = userEvent.setup();
render(<FocusFixture />);
await user.click(screen.getByRole("textbox", { name: "Editing field" }));
await user.click(screen.getByRole("button", { name: "Open information" }));
const destination = screen.getByRole("textbox", { name: "Destination field" });
await user.click(destination);
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(destination).toHaveFocus();
});
it("honors a caller's explicit close-focus handoff", async () => {
const user = userEvent.setup();
render(<FocusFixture override />);
await user.click(screen.getByRole("textbox", { name: "Editing field" }));
await user.click(screen.getByRole("button", { name: "Open information" }));
await user.keyboard("{Escape}");
await waitFor(() => expect(screen.getByRole("textbox", { name: "Destination field" })).toHaveFocus());
});
+13
View File
@@ -79,3 +79,16 @@ it("keeps an unknown recovered time blank while the prompt remains navigable", a
await user.click(prompt);
expect(onJumpToPrompt).toHaveBeenCalledWith("undated");
});
it("returns shortcut-opened search to the interrupted editor", async () => {
const user = userEvent.setup();
render(<><input aria-label="Draft" /><PromptNavigator messages={[
{ id: "one", role: "user", content: "alpha", createdAt: 1 },
]} onJumpToPrompt={vi.fn()} /></>);
const editor = screen.getByRole("textbox", { name: "Draft" });
await user.click(editor);
await user.keyboard("{Control>}f{/Control}");
await waitFor(() => expect(screen.getByRole("textbox", { name: "Search messages" })).toHaveFocus());
await user.keyboard("{Escape}");
await waitFor(() => expect(editor).toHaveFocus());
});
@@ -0,0 +1,81 @@
import { afterEach, expect, it, vi } from "vitest";
import { finishSessionTransition, transitionSession } from "@/components/thread/session-transition";
const nativeTransition = Object.getOwnPropertyDescriptor(document, "startViewTransition");
afterEach(() => {
transitionSession(() => {}, false);
vi.restoreAllMocks();
vi.unstubAllGlobals();
if (nativeTransition) Object.defineProperty(document, "startViewTransition", nativeTransition);
else Reflect.deleteProperty(document, "startViewTransition");
delete document.documentElement.dataset.themeSnapshot;
});
function nativeCaptures() {
const captures: { update: () => void; finish: () => void; skipTransition: ReturnType<typeof vi.fn> }[] = [];
const start = vi.fn((update: () => void) => {
let finish!: () => void;
const finished = new Promise<void>(resolve => { finish = resolve; });
const capture = { update, finish, skipTransition: vi.fn() };
captures.push(capture);
return { ready: Promise.resolve(), finished, skipTransition: capture.skipTransition };
});
vi.stubGlobal("matchMedia", () => ({ matches: false }));
Object.defineProperty(document, "startViewTransition", { configurable: true, value: start });
return { captures, start };
}
it("commits only the latest navigation when native captures are interrupted", async () => {
const { captures } = nativeCaptures();
const old = vi.fn();
const latest = vi.fn();
transitionSession(old);
transitionSession(latest);
expect(captures[0].skipTransition).toHaveBeenCalledOnce();
captures[0].update();
captures[1].update();
expect(old).not.toHaveBeenCalled();
expect(latest).toHaveBeenCalledOnce();
captures[0].finish();
await Promise.resolve();
expect(document.documentElement).toHaveAttribute("data-session-transition");
captures[1].finish();
await Promise.resolve();
expect(document.documentElement).not.toHaveAttribute("data-session-transition");
});
it("leaving chat invalidates a pending session capture", () => {
const { captures } = nativeCaptures();
const stale = vi.fn();
const settings = vi.fn();
transitionSession(stale);
transitionSession(settings, false);
captures[0].update();
expect(settings).toHaveBeenCalledOnce();
expect(stale).not.toHaveBeenCalled();
});
it.each(["reduced-motion", "theme-snapshot", "no-native-capture"])("navigates immediately with %s", mode => {
const { start } = nativeCaptures();
if (mode === "reduced-motion") vi.stubGlobal("matchMedia", () => ({ matches: true }));
if (mode === "theme-snapshot") document.documentElement.dataset.themeSnapshot = "";
if (mode === "no-native-capture") Object.defineProperty(document, "startViewTransition", { configurable: true, value: undefined });
const update = vi.fn();
transitionSession(update);
expect(update).toHaveBeenCalledOnce();
expect(start).not.toHaveBeenCalled();
});
it("finishes an accepted navigation before handing snapshots to the theme toggle", () => {
const { captures } = nativeCaptures();
const update = vi.fn();
transitionSession(update);
finishSessionTransition();
expect(update).toHaveBeenCalledOnce();
expect(captures[0].skipTransition).toHaveBeenCalledOnce();
expect(document.documentElement).not.toHaveAttribute("data-session-transition");
captures[0].update();
expect(update).toHaveBeenCalledOnce();
});
@@ -0,0 +1,40 @@
import { useState } from "react";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, it } from "vitest";
import { SettingsFeature } from "@/components/settings/shared/SettingsFeature";
function FeatureFixture({ saveOnClose = false }: { saveOnClose?: boolean }) {
const [enabled, setEnabled] = useState(false);
const [saving, setSaving] = useState(false);
return <SettingsFeature title="Example feature" enabled={enabled} disabled={saving}
onChange={setEnabled} onClose={() => { if (saveOnClose) setSaving(true); }}>
<p>Configuration</p>
</SettingsFeature>;
}
it.each(["title", "configure", "toggle"] as const)("returns Escape to the actual %s opener", async (opener) => {
const user = userEvent.setup();
render(<FeatureFixture />);
const trigger = opener === "toggle" ? screen.getByRole("switch", { name: "Example feature" })
: screen.getByRole("button", { name: opener === "title" ? "Example feature" : "Configure" });
await user.click(trigger);
await screen.findByRole("dialog");
await user.keyboard("{Escape}");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
await waitFor(() => expect(trigger).toHaveFocus());
});
it("returns Escape to Configure when saving disables the opening switch", async () => {
const user = userEvent.setup();
render(<FeatureFixture saveOnClose />);
const toggle = screen.getByRole("switch", { name: "Example feature" });
toggle.focus();
await user.keyboard(" ");
await screen.findByRole("dialog");
expect(toggle).toBeChecked();
await user.keyboard("{Escape}");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(toggle).toBeDisabled();
await waitFor(() => expect(screen.getByRole("button", { name: "Configure" })).toHaveFocus());
});
-81
View File
@@ -1697,87 +1697,6 @@ describe("ThreadComposer", () => {
});
it("closes the sustained goal through its existing drawer", () => {
const { container, rerender } = render(
<ThreadComposer
onSend={vi.fn()}
placeholder="Type your message..."
goalState={{
active: true,
objective: "Ship the release",
ui_summary: "Preparing release",
}}
/>,
);
const drawer = container.querySelector("[data-composer-status-drawer]");
expect(drawer).not.toBeNull();
expect(drawer).toHaveAttribute("data-state", "open");
expect(drawer).not.toHaveAttribute("aria-hidden");
const status = screen.getByRole("status");
expect(status).toHaveClass("composer-status-drawer-content");
rerender(
<ThreadComposer
onSend={vi.fn()}
placeholder="Type your message..."
goalState={{ active: false }}
/>,
);
expect(container.querySelector("[data-composer-status-drawer]")).toBe(drawer);
expect(drawer).toHaveAttribute("data-state", "closed");
expect(drawer).toHaveAttribute("aria-hidden", "true");
expect(screen.queryByRole("status")).not.toBeInTheDocument();
expect(drawer?.querySelector('[role="status"]')).toBe(status);
fireEvent.transitionEnd(drawer as Element, { propertyName: "grid-template-rows" });
expect(container.querySelector("[data-composer-status-drawer]")).toBeNull();
});
it("shows full goal content and dismisses it without losing the composer draft", async () => {
const user = userEvent.setup();
const longObjective =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz0123456789GoalTail";
render(
<ThreadComposer
onSend={vi.fn()}
persistDraft={false}
placeholder="Type your message..."
goalState={{
active: true,
objective: longObjective,
ui_summary: "Short summary for strip",
}}
/>,
);
const input = screen.getByRole("textbox", { name: "Message input" });
const trigger = screen.getByRole("button", { name: "Show full goal" });
await user.type(input, "Keep my draft");
await user.click(trigger);
const dialog = await screen.findByRole("dialog", { name: "Goal" });
expect(dialog).toHaveTextContent("Short summary for strip");
expect(dialog).toHaveTextContent(longObjective);
expect(trigger).toHaveAttribute("aria-expanded", "true");
await user.click(trigger);
expect(screen.queryByRole("dialog", { name: "Goal" })).not.toBeInTheDocument();
expect(trigger).toHaveAttribute("aria-expanded", "false");
await user.click(trigger);
expect(await screen.findByRole("dialog", { name: "Goal" })).toBeVisible();
await user.keyboard("{Escape}");
expect(screen.queryByRole("dialog", { name: "Goal" })).not.toBeInTheDocument();
await user.click(trigger);
expect(await screen.findByRole("dialog", { name: "Goal" })).toBeVisible();
await user.click(input);
expect(screen.queryByRole("dialog", { name: "Goal" })).not.toBeInTheDocument();
expect(input).toHaveValue("Keep my draft");
});
it("opens a slash command palette and inserts the selected command", () => {
const onSend = vi.fn();
render(
+6 -3
View File
@@ -24,9 +24,12 @@ describe("Workspace project picker", () => {
it.each(["pointer", "keyboard"])("restores the opening focus context after %s entry and Escape", async (entry) => {
const user = userEvent.setup();
const onChange = vi.fn();
render(<WorkspaceProjectPicker scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={vi.fn().mockResolvedValue(directory)} onChange={onChange} />);
render(<><input aria-label="Draft" /><WorkspaceProjectPicker scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={vi.fn().mockResolvedValue(directory)} onChange={onChange} /></>);
const trigger = screen.getByRole("button", { name: "Switch directory" });
if (entry === "pointer") await user.click(trigger);
if (entry === "pointer") {
await user.click(screen.getByRole("textbox", { name: "Draft" }));
await user.click(trigger);
}
else {
act(() => trigger.focus());
await user.keyboard("{Enter}");
@@ -37,7 +40,7 @@ describe("Workspace project picker", () => {
// FocusScope restores focus in a task after its exit cleanup.
await act(() => new Promise(resolve => setTimeout(resolve, 0)));
if (entry === "keyboard") expect(trigger).toHaveFocus();
else expect(trigger).not.toHaveFocus();
else expect(screen.getByRole("textbox", { name: "Draft" })).toHaveFocus();
expect(onChange).not.toHaveBeenCalled();
});