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

@@ -9,7 +9,6 @@ export function ComposerActionFixture({ parameters }: { parameters: URLSearchPar
variant={parameters.get("composerVariant") === "thread" ? "thread" : "hero"}
placeholder={parameters.has("opening") ? "Opening a new topic…" : undefined}
modelLabel="Preview"
goalState={parameters.has("goal") ? { active: true, objective: "Keep the work in focus." } : undefined}
isStreaming={running}
onTranscribeAudio={async () => "Voice draft"}
onSend={() => { setStopRequested(false); setRunning(true); }}
-22
View File
@@ -33,27 +33,5 @@ for (const theme of ["light", "dark"]) {
await expect(input).toHaveValue("Keep the work in focus.");
});
test("composer focus preserves the active goal's blue ring", async ({ page }) => {
await page.emulateMedia({ reducedMotion: "reduce" });
await page.goto("/browser/fixture.html?case=composer-action&goal");
const surface = page.locator(".thread-composer-surface");
await expect(surface).toBeVisible();
const ring = await surface.evaluate(element => {
const probe = document.createElement("span");
probe.style.color = getComputedStyle(element).getPropertyValue("--tw-ring-color");
document.body.append(probe);
const color = getComputedStyle(probe).color;
probe.remove();
return color;
});
const input = page.getByRole("textbox", { name: "Message input" });
await input.blur();
const rest = await surface.evaluate(element => getComputedStyle(element).boxShadow);
expect(rest).toContain(ring);
await input.focus();
const focused = await surface.evaluate(element => getComputedStyle(element).boxShadow);
expect(focused).toContain(ring);
expect(focused).toBe(rest);
});
});
}
+4 -1
View File
@@ -50,6 +50,7 @@ import { AttachmentLayoutFixture } from "./attachment-layout-fixture";
import { LoadedSessionSearchFixture } from "./loaded-session-search-fixture";
import { AppearanceFixture } from "./appearance-fixture";
import { ContinuityFixture } from "./continuity-fixture";
import { SessionTransitionFixture } from "./session-transition-fixture";
import { installSubagentDockApi, SubagentDockFixture } from "./subagent-dock-fixture";
const history: UIMessage[] = [
@@ -233,7 +234,9 @@ if (parameters.get("case") === "appearance" && parameters.has("lang")) {
await setAppLanguage(normalizeLocale(parameters.get("lang")));
}
createRoot(document.getElementById("root")!).render(<TooltipProvider>
{parameters.get("case") === "continuity"
{parameters.get("case") === "session-transition"
? <SessionTransitionFixture />
: parameters.get("case") === "continuity"
? <ContinuityFixture />
: parameters.get("case") === "appearance"
? <AppearanceFixture />
+64
View File
@@ -0,0 +1,64 @@
import { useRef, useState } from "react";
import { createRoot } from "react-dom/client";
import { FallbackResponseSources } from "@/components/ResponseSourceBadge";
import { ModelPresetBadge } from "@/components/thread/ModelPresetBadge";
import { PromptNavigator } from "@/components/thread/PromptNavigator";
import { SessionInfoPopoverView } from "@/components/thread/SessionInfoPopoverView";
import { SettingsFeature } from "@/components/settings/shared/SettingsFeature";
import { WorkspaceProjectPicker } from "@/components/thread/WorkspaceControls";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { TooltipProvider } from "@/components/ui/tooltip";
import { initializeI18n } from "@/i18n";
import "../src/globals.css";
function OverlayFocusFixture() {
const composer = useRef<HTMLTextAreaElement>(null);
const [preset, setPreset] = useState("First model");
const [managing, setManaging] = useState(false);
const [featureEnabled, setFeatureEnabled] = useState(false);
const [featureSaving, setFeatureSaving] = useState(false);
return <main style={{ maxWidth: 760, margin: "48px auto", padding: 24, display: "flex", flexDirection: "column", gap: 24 }}>
<textarea ref={composer} aria-label="Composer draft" className="rounded-control border p-3" defaultValue="Keep editing here" />
<div className="flex items-center gap-6">
<ModelPresetBadge label={preset} modelPreset={preset} isHero={false}
modelPresets={[{ name: "First model" }, { name: "Second model" }]}
onPresetChange={setPreset} onRequestComposerFocus={() => composer.current?.focus()}
onManageModels={() => setManaging(true)} />
<PromptNavigator messages={[{ id: "prompt", role: "user", content: "Earlier question", createdAt: 1_700_000_000_000 }]}
onJumpToPrompt={() => composer.current?.focus()} />
<SessionInfoPopoverView jobs={[]} loading={false} loadFailed={false} now={Date.now()}
onAction={async () => []} onEdit={async () => []} />
<FallbackResponseSources sources={[{ preset: "Fallback model", provider: "openai", model: "gpt-4", fallback: true }]} />
</div>
<div className="flex items-center gap-6">
<Dialog><DialogTrigger asChild><Button variant="outline">Open dialog</Button></DialogTrigger>
<DialogContent aria-describedby={undefined}><DialogTitle>Example dialog</DialogTitle><input aria-label="Dialog field" /></DialogContent>
</Dialog>
<DropdownMenu modal={false}><DropdownMenuTrigger asChild><Button variant="outline">Open menu</Button></DropdownMenuTrigger>
<DropdownMenuContent><DropdownMenuItem>Example action</DropdownMenuItem></DropdownMenuContent>
</DropdownMenu>
<Select defaultValue="first"><SelectTrigger aria-label="Example select"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem value="first">First option</SelectItem><SelectItem value="second">Second option</SelectItem></SelectContent>
</Select>
</div>
<WorkspaceProjectPicker scope={{ project_path: "/workspace", access_mode: "restricted" }}
defaultScope={{ project_path: "/workspace", access_mode: "restricted" }}
controls={{ can_change_project: true, can_browse_directories: true }} onChange={() => {}}
onBrowseDirectories={async () => ({ path: "/workspace", parent: "/", entries: [{ name: "project", path: "/workspace/project" }], truncated: false, host: "fixture", platform: "Linux" })} />
<SettingsFeature title="Example feature" enabled={featureEnabled} disabled={featureSaving}
onChange={setFeatureEnabled} onClose={() => { if (featureEnabled) setFeatureSaving(true); }}>
<p>Feature configuration</p>
</SettingsFeature>
<input aria-label="Outside field" className="rounded-control border p-3" />
<Button variant="outline">Outside button</Button>
<Dialog open={managing} onOpenChange={setManaging}>
<DialogContent aria-describedby={undefined}><DialogTitle>Manage models fixture</DialogTitle><input aria-label="Management field" /></DialogContent>
</Dialog>
</main>;
}
await initializeI18n();
createRoot(document.getElementById("root")!).render(<TooltipProvider><OverlayFocusFixture /></TooltipProvider>);
+5
View File
@@ -0,0 +1,5 @@
<!doctype html>
<html lang="en">
<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Overlay focus regression fixture</title></head>
<body><div id="root"></div><script type="module" src="/browser/overlay-focus-fixture.tsx"></script></body>
</html>
+195
View File
@@ -0,0 +1,195 @@
import { expect, test, type BrowserContext, type Page } from "@playwright/test";
let overlayFocusContext: BrowserContext;
let page: Page;
test.beforeEach(async ({ browser, baseURL }) => {
overlayFocusContext = await browser.newContext({ baseURL });
page = await overlayFocusContext.newPage();
await page.goto("/browser/overlay-focus.html");
await expect(page.getByRole("textbox", { name: "Composer draft" })).toBeVisible();
});
test.afterEach(async () => { await overlayFocusContext.close(); });
async function armFocusCleanup() {
// The outer overlay owns the focus scope; pickers can contain nested listboxes.
await page.locator('[role="dialog"], [role="menu"], [role="listbox"]').first().evaluate(node => {
document.documentElement.removeAttribute("data-overlay-focus-settled");
node.addEventListener("focusScope.autoFocusOnUnmount", () => {
queueMicrotask(() => document.documentElement.setAttribute("data-overlay-focus-settled", "true"));
}, { once: true });
});
}
async function settleClose(action: () => Promise<unknown>) {
await armFocusCleanup();
await action();
await expect(page.locator("html")).toHaveAttribute("data-overlay-focus-settled", "true");
}
test("model picker outside click keeps the clicked input focused", async () => {
await page.getByRole("textbox", { name: "Composer draft" }).click();
await page.getByRole("button", { name: "First model", exact: true }).click();
await settleClose(() => page.getByRole("textbox", { name: "Outside field" }).click());
await expect(page.getByRole("textbox", { name: "Outside field" })).toBeFocused();
});
test("model picker selection returns to the composer after its exit", async () => {
await page.getByRole("button", { name: "First model", exact: true }).click();
await settleClose(() => page.getByRole("option", { name: "Second model" }).click());
await expect(page.getByRole("textbox", { name: "Composer draft" })).toBeFocused();
});
test("model picker keyboard Escape returns visible focus to its trigger", async () => {
await page.getByRole("textbox", { name: "Composer draft" }).click();
await page.keyboard.press("Tab");
const trigger = page.getByRole("button", { name: "First model", exact: true });
await expect(trigger).toBeFocused();
await page.keyboard.press("Enter");
await expect(page.getByRole("option", { name: "First model" })).toBeFocused();
await page.getByRole("dialog").evaluate(async (node) => { await Promise.all(node.getAnimations().map((animation) => animation.finished)); });
await settleClose(() => page.keyboard.press("Escape"));
await expect(trigger).toBeFocused();
expect(await trigger.evaluate((node) => node.matches(":focus-visible"))).toBe(true);
});
test("model picker management handoff keeps focus in the new dialog", async () => {
await page.getByRole("button", { name: "First model", exact: true }).click();
await settleClose(() => page.getByRole("button", { name: "Manage presets" }).click());
await expect(page.getByRole("dialog", { name: "Manage models fixture" })).toBeVisible();
await expect(page.getByRole("dialog", { name: "Manage models fixture" })).toBeFocused();
});
test("prompt search shortcut Escape restores the editing field", async () => {
const composer = page.getByRole("textbox", { name: "Composer draft" });
await composer.click();
await page.keyboard.press("Control+f");
await expect(page.getByRole("textbox", { name: "Search messages" })).toBeFocused();
await page.getByRole("dialog").evaluate(async (node) => { await Promise.all(node.getAnimations().map((animation) => animation.finished)); });
await settleClose(() => page.keyboard.press("Escape"));
await expect(composer).toBeFocused();
});
for (const name of ["First model", "Session details", "This reply switched to a fallback model, answered by Fallback model."]) {
test(`pointer-open / Escape restores the interrupted editor: ${name}`, async () => {
const composer = page.getByRole("textbox", { name: "Composer draft" });
const trigger = page.getByRole("button", { name, exact: true });
await composer.click();
await trigger.click();
await expect(page.getByRole("dialog")).toBeVisible();
await page.getByRole("dialog").evaluate(async (node) => { await Promise.all(node.getAnimations().map((animation) => animation.finished)); });
await settleClose(() => page.keyboard.press("Escape"));
await expect(composer).toBeFocused();
expect(await trigger.evaluate((node) => node.matches(":focus-visible"))).toBe(false);
});
if (name !== "First model") {
test(`Space-open / Escape retains visible keyboard focus: ${name}`, async () => {
const trigger = page.getByRole("button", { name, exact: true });
await page.getByRole("textbox", { name: "Composer draft" }).click();
for (let count = 0; count < 4 && !await trigger.evaluate((node) => node === document.activeElement); count++) await page.keyboard.press("Tab");
await expect(trigger).toBeFocused();
await page.keyboard.press("Space");
await expect(page.getByRole("dialog")).toBeVisible();
await page.getByRole("dialog").evaluate(async (node) => { await Promise.all(node.getAnimations().map((animation) => animation.finished)); });
await settleClose(() => page.keyboard.press("Escape"));
await expect(trigger).toBeFocused();
expect(await trigger.evaluate((node) => node.matches(":focus-visible"))).toBe(true);
expect(await trigger.evaluate((node) => getComputedStyle(node).boxShadow)).not.toBe("none");
});
test(`outside click retains the clicked control: ${name}`, async () => {
await page.getByRole("button", { name, exact: true }).click();
const outside = page.getByRole("button", { name: "Outside button", exact: true });
await settleClose(() => outside.click());
await expect(outside).toBeFocused();
});
}
}
for (const name of ["Open dialog", "Open menu", "Example select"]) {
test(`shared overlay keyboard Escape preserves trigger focus: ${name}`, async () => {
const trigger = page.getByRole(name === "Example select" ? "combobox" : "button", { name, exact: true, includeHidden: true });
await trigger.focus();
await page.keyboard.press("Enter");
await expect(trigger).toHaveAttribute("aria-expanded", "true");
await page.locator('[role="dialog"], [role="menu"], [role="listbox"]').evaluate(async (node) => { await Promise.all(node.getAnimations().map((animation) => animation.finished)); });
await settleClose(() => page.keyboard.press("Escape"));
await expect(trigger).toHaveAttribute("aria-expanded", "false");
await expect(trigger).toBeFocused();
expect(await trigger.evaluate((node) => node.matches(":focus-visible"))).toBe(true);
});
}
test("feature dialog returns to the title trigger that opened it, not the other Configure trigger", async () => {
const trigger = page.getByRole("button", { name: "Example feature", exact: true });
await trigger.click();
const dialog = page.getByRole("dialog", { name: "Example feature", exact: true });
await expect(dialog).toBeFocused();
await dialog.evaluate(async (node) => { await Promise.all(node.getAnimations().map((animation) => animation.finished)); });
await settleClose(() => page.keyboard.press("Escape"));
await expect(trigger).toBeFocused();
});
test("feature save-on-close restores keyboard focus when it disables the opening switch", async () => {
const toggle = page.getByRole("switch", { name: "Example feature", includeHidden: true });
await toggle.focus();
await page.keyboard.press("Space");
const dialog = page.getByRole("dialog", { name: "Example feature", exact: true });
await expect(dialog).toBeFocused();
await expect(toggle).toBeChecked();
await dialog.evaluate(async node => { await Promise.all(node.getAnimations().map(animation => animation.finished)); });
await settleClose(() => page.keyboard.press("Escape"));
await expect(dialog).toBeHidden();
await expect(toggle).toBeDisabled();
const configure = page.getByRole("button", { name: "Configure", exact: true });
await expect(configure).toBeFocused();
expect(await configure.evaluate(node => node.matches(":focus-visible"))).toBe(true);
await page.keyboard.press("Tab");
await expect(page.getByRole("textbox", { name: "Outside field" })).toBeFocused();
});
test("prompt search button Escape returns to its keyboard trigger", async () => {
const trigger = page.getByRole("button", { name: "Message navigation", exact: true });
await page.getByRole("textbox", { name: "Composer draft" }).click();
await page.keyboard.press("Tab");
await page.keyboard.press("Tab");
await expect(trigger).toBeFocused();
await page.keyboard.press("Space");
const dialog = page.getByRole("dialog");
await expect(page.getByRole("textbox", { name: "Search messages" })).toBeFocused();
await dialog.evaluate(async (node) => { await Promise.all(node.getAnimations().map((animation) => animation.finished)); });
await settleClose(() => page.keyboard.press("Escape"));
await expect(trigger).toBeFocused();
});
test("workspace pointer-open / Escape restores the interrupted editor instead of dropping focus", async () => {
const composer = page.getByRole("textbox", { name: "Composer draft" });
await composer.click();
await page.getByRole("button", { name: "Switch directory", exact: true }).click();
await expect(page.getByRole("option", { name: "/workspace/project", exact: true })).toBeVisible();
await page.getByRole("dialog").evaluate(async (node) => { await Promise.all(node.getAnimations().map((animation) => animation.finished)); });
await settleClose(() => page.keyboard.press("Escape"));
await expect(composer).toBeFocused();
});
test("an outside interaction during Escape's exit keeps the newly chosen focus", async () => {
await page.getByRole("textbox", { name: "Composer draft" }).click();
await page.getByRole("button", { name: "First model", exact: true }).click();
const dialog = page.getByRole("dialog");
await dialog.evaluate(async node => { await Promise.all(node.getAnimations().map(animation => animation.finished)); });
await armFocusCleanup();
await dialog.evaluate(node => {
node.addEventListener("animationstart", () => {
for (const animation of node.getAnimations()) animation.pause();
}, { once: true });
});
await page.keyboard.press("Escape");
await expect(dialog).toHaveAttribute("data-state", "closed");
await expect.poll(() => dialog.evaluate(node => node.getAnimations().some(animation => animation.playState === "paused"))).toBe(true);
const outside = page.getByRole("textbox", { name: "Outside field" });
await outside.click();
await dialog.evaluate(node => { for (const animation of node.getAnimations()) animation.finish(); });
await expect(page.locator("html")).toHaveAttribute("data-overlay-focus-settled", "true");
await expect(outside).toBeFocused();
});
@@ -0,0 +1,60 @@
import { useState } from "react";
import { ThreadShell } from "@/components/thread/ThreadShell";
import { PaneWorkbench } from "@/components/workbench/PaneWorkbench";
import { transitionSession } from "@/components/thread/session-transition";
import { settings } from "@/dev/gallery/settings";
import { ComposerDraftStore } from "@/lib/composer-draft";
import { ThreadMessageCache } from "@/lib/thread-message-cache";
import { ClientProvider } from "@/providers/ClientProvider";
import { createStreamClient } from "@/tests/stream-client";
const { client, receive } = createStreamClient();
const goalSummary = new URLSearchParams(location.search).has("long-goal")
? "完成会话切换和目标状态界面的优化,统一明暗主题下的布局、文字、图标与交互,验证桌面和窄屏体验后提交代码并更新发布说明"
: "Keep the composer stable";
for (const topic of ["goal", "together", "blocked"]) {
receive({ event: "goal_state", chat_id: topic, goal_state: {
active: topic !== "blocked", status: topic === "blocked" ? "blocked" : "active",
ui_summary: goalSummary,
objective: "Verify session navigation with real components.\n\n" + "- Preserve drafts, reading position and usable header controls.\n".repeat(6),
...(topic === "blocked" ? { recap: "Waiting for a workspace permission decision." } : {}),
} });
}
export function SessionTransitionFixture() {
const workbench = new URLSearchParams(location.search).has("workbench");
const [topic, setTopic] = useState(workbench ? "goal" : "plain");
const [cache] = useState(() => new ThreadMessageCache(() => false));
const [drafts] = useState(() => new ComposerDraftStore());
const dark = new URLSearchParams(location.search).has("dark");
document.documentElement.classList.toggle("dark", dark);
return <ClientProvider client={client} token="fixture" webuiCapabilities={["webui.core.v1", "webui.subagents.v1"]}>
<main className="thread-workspace flex min-w-0 flex-col overflow-hidden bg-background text-foreground" style={{ height: "100dvh" }} data-session={topic}>
<nav aria-label="Sessions" className="flex shrink-0 flex-wrap gap-4 px-4 py-2 text-xs">
{(workbench ? ["goal", "blocked"] : ["plain", "goal", "tasks", "together", "blocked", "cold"]).map(key => <button key={key} onClick={() => transitionSession(() => setTopic(key), !workbench && key !== topic)}>{key}</button>)}
<button onClick={() => receive({ event: "goal_state", chat_id: topic, goal_state: {
...client.getGoalState(topic), active: false, status: "blocked", recap: "Waiting for a workspace permission decision.",
} })}>Block goal</button>
<button onClick={() => receive({ event: "goal_state", chat_id: topic, goal_state: { active: false } })}>Clear goal</button>
<button onClick={() => {
receive({ event: "goal_status", chat_id: topic, turn_id: "live-turn", status: "running", started_at: Date.now() / 1000 });
receive({ event: "delta", chat_id: topic, turn_id: "live-turn", stream_id: "live", text: "Live reply continues" });
}}>Stream reply</button>
</nav>
{workbench ? <PaneWorkbench
panes={["goal", "blocked"].map(key => ({ key, title: key }))} activePaneKey={topic} layout="columns"
showLayoutControl={false} onActivatePane={setTopic} onAddPane={() => {}} onLayoutChange={() => {}} onPaneOrderChange={() => {}}
renderPane={(pane, context) => <ThreadShell
session={{ key: `websocket:${pane.key}`, channel: "websocket", chatId: pane.key, createdAt: null, updatedAt: null, preview: "" }}
title={pane.title} hideHeaderTitle onToggleSidebar={() => {}} theme={dark ? "dark" : "light"}
settingsSnapshot={settings} messageCache={cache} draftStore={drafts} emptyComposerVariant="thread"
headerPortalTarget={context.headerPortalTarget} headerActive={context.active}
composerPortalTarget={context.composerPortalTarget} composerActive={context.active} headerActions={context.headerActions}
/>}
/> : <ThreadShell session={{ key: `websocket:${topic}`, channel: "websocket", chatId: topic, createdAt: null, updatedAt: null, preview: "" }}
title={topic} hideHeaderTitle onToggleSidebar={() => {}} theme={dark ? "dark" : "light"}
settingsSnapshot={settings} messageCache={cache} draftStore={drafts} emptyComposerVariant="thread" />}
</main>
</ClientProvider>;
}
+344
View File
@@ -0,0 +1,344 @@
import { expect, test, type Page } from "@playwright/test";
async function installPreview(page: Page) {
await page.addInitScript(() => { localStorage.setItem("nanobot.locale", "en"); });
const cdp = await page.context().newCDPSession(page);
await cdp.send("Emulation.setEmulatedMedia", { features: [{ name: "prefers-reduced-transparency", value: "no-preference" }] });
await page.route("**/api/commands", route => route.fulfill({ json: { commands: [] } }));
await page.route("**/api/sessions/*/webui-thread?*", route => {
const topic = decodeURIComponent(new URL(route.request().url()).pathname.split("/")[3]).split(":")[1];
return route.fulfill({ json: { schemaVersion: 3, projection: "events", events: [
{ event: "user_message", chat_id: topic, projection_id: `${topic}-prompt`, turn_id: "fixture-turn", starts_turn: true, text: `Question for ${topic}` },
{ event: "message", chat_id: topic, projection_id: `${topic}-answer`, turn_id: "fixture-turn", text: `Answer for ${topic}\n\n` + "A long conversation stays at its reading position.\n\n".repeat(25) },
] } });
});
await page.route("**/api/sessions/*/subagents?*", route => route.fulfill({ json: { tasks: /tasks|together|blocked/.test(route.request().url()) ? [{
task_id: "preview-task", revision: 1, label: "Check navigation", task_description: "Synthetic preview task",
origin_turn_id: "fixture-turn", origin_message_id: "tasks-prompt", created_at: Date.now() / 1000, completed_at: null,
state: "running", phase: "awaiting_model", elapsed_seconds: 12, iteration: 1, tool_events: [],
usage: null, receipts: {}, result: null, partial: false, stop_reason: null, error: null,
}] : [] } }));
}
async function select(page: Page, topic: string) {
await page.getByRole("button", { name: topic, exact: true }).click();
await expect(page.locator("main[data-session]")).toHaveAttribute("data-session", topic);
await expect(page.getByText(`Question for ${topic}`, { exact: true })).toBeVisible();
await expect.poll(() => page.evaluate(() => document.documentElement.hasAttribute("data-session-transition"))).toBe(false);
}
async function armGoalMotionFreeze(page: Page, state: "open" | "closed", time: number) {
await page.evaluate(({ state, time }) => {
document.addEventListener("animationstart", function pauseMotion(event) {
const el = event.target;
if (!(el instanceof HTMLElement) || !el.matches(`.goal-island-panel[data-state="${state}"]`)) return;
for (const animation of el.getAnimations({ subtree: true })) { animation.pause(); animation.currentTime = time; }
document.removeEventListener("animationstart", pauseMotion);
});
}, { state, time });
}
test("blocked goal remains visible until cleared and survives session switching", async ({ page }) => {
await installPreview(page);
await page.goto("/browser/fixture.html?case=session-transition");
await select(page, "goal");
await page.getByRole("button", { name: "Show full goal" }).click();
const dialog = page.getByRole("dialog", { name: "Goal", exact: true });
const body = dialog.locator(".goal-island-body");
await body.evaluate(el => { el.scrollTop = el.scrollHeight; });
expect(await body.evaluate(el => el.scrollTop)).toBeGreaterThan(0);
// Emit a live goal event without an outside pointer click dismissing the open panel.
await page.getByRole("button", { name: "Block goal" }).evaluate(button => (button as HTMLButtonElement).click());
await expect(page.getByRole("status", { name: "Blocked · Waiting for a workspace permission decision." })).toBeVisible();
await expect.poll(() => body.evaluate(el => el.scrollTop)).toBe(0);
await expect(dialog.locator(".goal-island-status-icon")).toBeVisible();
const reason = dialog.getByText("Waiting for a workspace permission decision.");
await expect(reason).toBeVisible();
expect(await reason.evaluate(el => {
const body = el.closest(".goal-island-body")!;
return el.getBoundingClientRect().bottom <= body.getBoundingClientRect().bottom;
})).toBe(true);
await page.keyboard.press("Escape");
await select(page, "plain");
await expect(page.locator(".goal-island")).toHaveCount(0);
await select(page, "goal");
await expect(page.locator('.goal-island[data-goal-status="blocked"]')).toBeVisible();
await page.getByRole("button", { name: "Clear goal" }).click();
await expect(page.locator(".goal-island")).toHaveCount(0);
});
for (const viewport of [{ width: 390, height: 844 }, { width: 844, height: 390 }]) {
test(`long goal summaries leave the objective readable at ${viewport.width}x${viewport.height}`, async ({ page }) => {
await page.setViewportSize(viewport);
await installPreview(page);
await page.goto("/browser/fixture.html?case=session-transition&long-goal");
await select(page, "goal");
await page.getByRole("button", { name: "Show full goal" }).click();
const dialog = page.getByRole("dialog", { name: "Goal", exact: true });
await dialog.evaluate(async el => { await Promise.all(el.getAnimations({ subtree: true }).map(animation => animation.finished)); });
const bounds = await dialog.evaluate(el => {
const title = el.querySelector(".goal-island-summary")!.getBoundingClientRect();
const body = el.querySelector(".goal-island-body")!;
const paragraph = body.querySelector("p")!;
return { titleBottom: title.bottom, panel: el.getBoundingClientRect().toJSON(), body: body.getBoundingClientRect().toJSON(), lineHeight: Number.parseFloat(getComputedStyle(paragraph).lineHeight) };
});
expect(bounds.panel.height).toBeLessThanOrEqual(viewport.height / 4);
expect(bounds.body.height).toBeGreaterThanOrEqual(bounds.lineHeight);
expect(bounds.titleBottom).toBeLessThanOrEqual(bounds.body.top);
expect(bounds.body.bottom).toBeLessThanOrEqual(bounds.panel.bottom);
const body = dialog.locator(".goal-island-body");
await body.hover();
await page.mouse.wheel(0, 10_000);
await expect(body).toHaveAttribute("data-overflow-top");
await expect(body).not.toHaveAttribute("data-overflow-bottom");
});
}
for (const width of [320, 390, 1440]) for (const dark of [false, true]) {
test(`session motion preserves composer anchors at ${width}px ${dark ? "dark" : "light"}`, async ({ page }) => {
await page.setViewportSize({ width, height: 844 });
await installPreview(page);
await page.goto(`/browser/fixture.html?case=session-transition${dark ? "&dark" : ""}`);
await expect(page.getByText("Question for plain", { exact: true })).toBeVisible();
await select(page, "goal");
await expect(page.getByRole("status", { name: "Goal: Keep the composer stable", exact: true })).toBeVisible();
await select(page, "tasks");
await expect(page.getByTestId("subagent-task-dock")).toBeVisible();
await select(page, "plain");
await page.getByRole("textbox").fill("Plain draft");
const composer = await page.locator(".thread-composer-surface").boundingBox();
const toolbar = await page.locator(".thread-composer-footer").boundingBox();
const input = await page.locator(".thread-composer-input").boundingBox();
expect(input!.y).toBeGreaterThan(0);
expect(toolbar!.y + toolbar!.height).toBeLessThanOrEqual(844);
expect((await page.getByTestId("thread-message-region").boundingBox())!.height).toBeGreaterThan(100);
const sample = await page.evaluate(async () => {
const start = document.startViewTransition.bind(document);
let ready!: () => void;
const captured = new Promise<void>(resolve => { ready = resolve; });
document.startViewTransition = callback => {
const transition = start(callback);
void transition.ready.then(ready);
return transition;
};
const goal = [...document.querySelectorAll("nav button")].find(button => button.textContent === "goal") as HTMLButtonElement;
goal.click();
await captured;
document.startViewTransition = start;
const animations = document.getAnimations().filter(animation => animation.effect instanceof KeyframeEffect && animation.effect.pseudoElement);
const frames = animations.map(animation => ({
target: (animation.effect as KeyframeEffect).pseudoElement,
keyframes: (animation.effect as KeyframeEffect).getKeyframes(),
}));
for (const animation of animations) { animation.pause(); animation.currentTime = 100; }
await new Promise(requestAnimationFrame);
const transform = getComputedStyle(document.documentElement, "::view-transition-group(session-input)").transform;
const inputMatrix = new DOMMatrix(transform);
const frameHeight = Number.parseFloat(getComputedStyle(document.documentElement, "::view-transition-group(session-composer)").height);
const threadOut = getComputedStyle(document.documentElement, "::view-transition-old(session-thread-0)").opacity;
const threadIn = getComputedStyle(document.documentElement, "::view-transition-new(session-thread-0)").opacity;
for (const animation of animations) animation.play();
return { frames, scale: [inputMatrix.a, inputMatrix.d], frameHeight, threadOut: Number(threadOut), threadIn: Number(threadIn) };
});
expect(sample.scale).toEqual([1, 1]);
expect(Math.abs(sample.frameHeight - composer!.height)).toBeLessThanOrEqual(1);
expect(sample.threadOut).toBe(0);
expect(sample.threadIn).toBeGreaterThan(0);
expect(sample.threadIn).toBeLessThan(1);
await expect.poll(() => page.evaluate(() => document.documentElement.hasAttribute("data-session-transition"))).toBe(false);
const goalInput = await page.locator(".thread-composer-input").boundingBox();
const goalToolbar = await page.locator(".thread-composer-footer").boundingBox();
expect(Math.abs(goalInput!.y - input!.y)).toBeLessThanOrEqual(1);
expect(Math.abs(goalToolbar!.y - toolbar!.y)).toBeLessThanOrEqual(1);
await page.getByRole("textbox").fill("Goal draft\nsecond line\nthird line");
await select(page, "tasks");
await page.getByRole("textbox").fill("Tasks draft");
await select(page, "plain");
await expect(page.getByRole("textbox")).toHaveValue("Plain draft");
await select(page, "goal");
await expect(page.getByRole("textbox")).toHaveValue("Goal draft\nsecond line\nthird line");
expect(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth)).toBe(false);
await select(page, "together");
await expect(page.getByTestId("subagent-task-dock")).toBeVisible();
await page.getByRole("textbox").fill("Draft beside a running task");
const beforeOpen = await page.locator(".thread-composer-surface").boundingBox();
const island = await page.locator(".goal-island").boundingBox();
const controls = await page.locator('[data-header-controls="end"]').boundingBox();
expect(island!.y + island!.height < controls!.y || island!.y >= controls!.y + controls!.height || island!.x + island!.width <= controls!.x).toBe(true);
await page.getByRole("button", { name: "Show full goal" }).click();
const dialog = page.getByRole("dialog", { name: "Goal", exact: true });
await expect(dialog).toBeVisible();
await expect(dialog).toContainText("Verify session navigation with real components.");
await dialog.evaluate(async el => { await Promise.all(el.getAnimations({ subtree: true }).map(animation => animation.finished)); });
expect(await dialog.locator(":scope > .goal-island-surface").evaluate(el => getComputedStyle(el, "::before").backdropFilter)).toContain("blur(20px)");
const panel = await dialog.boundingBox();
expect(panel!.x).toBeGreaterThanOrEqual(24);
expect(panel!.x + panel!.width).toBeLessThanOrEqual(width - 24);
expect(panel!.y + panel!.height).toBeLessThan(844);
expect(panel!.height).toBeLessThanOrEqual(844 / 4);
const heading = dialog.getByRole("heading", { name: "Keep the composer stable" });
const headingPosition = await heading.boundingBox();
if (width < 768) {
expect(headingPosition!.y).toBeGreaterThanOrEqual(controls!.y + controls!.height);
expect(await page.locator('[data-header-controls="end"] button').evaluateAll(buttons => buttons.every(button => {
const rect = button.getBoundingClientRect();
return button.contains(document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2));
}))).toBe(true);
}
const typography = await dialog.evaluate(el => {
const title = getComputedStyle(el.querySelector("h2")!);
const body = getComputedStyle(el.querySelector(".goal-island-document p")!);
return { title: Number.parseFloat(title.fontSize), body: Number.parseFloat(body.fontSize), titleFont: title.fontFamily, bodyFont: body.fontFamily };
});
expect(typography.title).toBeCloseTo(typography.body * 1.5, 1);
expect(typography.titleFont).toBe(typography.bodyFont);
const scrollBody = page.locator(".goal-island-body");
expect(await scrollBody.evaluate(el => el.scrollHeight > el.clientHeight)).toBe(true);
await expect(scrollBody).toHaveAttribute("data-overflow-bottom");
await scrollBody.hover();
await page.mouse.wheel(0, 10_000);
await expect(scrollBody).toHaveAttribute("data-overflow-top");
await expect(scrollBody).not.toHaveAttribute("data-overflow-bottom");
expect(await heading.boundingBox()).toEqual(headingPosition);
await page.keyboard.press("Escape");
await expect(dialog).not.toBeVisible();
await expect(page.getByRole("textbox")).toBeFocused();
expect(await page.locator(".thread-composer-surface").boundingBox()).toEqual(beforeOpen);
await expect(page.getByRole("textbox")).toHaveValue("Draft beside a running task");
await select(page, "blocked");
await expect(page.locator('.goal-island[data-goal-status="blocked"]')).toBeVisible();
await page.getByRole("button", { name: "Show full goal" }).click();
await expect(dialog.locator(".goal-island-reason p")).toHaveText("Waiting for a workspace permission decision.");
const reasonColor = await dialog.locator(".goal-island-reason p").evaluate(el => getComputedStyle(el).color);
expect(await dialog.locator(".goal-island-status-icon").evaluate(el => getComputedStyle(el).color)).toBe(reasonColor);
await page.getByRole("textbox").click();
await expect(dialog).not.toBeVisible();
await page.emulateMedia({ reducedMotion: "reduce", contrast: "more" });
await page.getByRole("button", { name: "Show full goal" }).click();
await expect(dialog).toBeVisible();
expect(await dialog.locator(":scope > .goal-island-surface").evaluate(el => getComputedStyle(el, "::before").backdropFilter)).toBe("none");
await page.keyboard.press("Escape");
await select(page, "plain");
await expect(page.getByRole("textbox")).toHaveValue("Plain draft");
await page.getByRole("button", { name: "Stream reply" }).click();
await expect(page.getByText("Live reply continues", { exact: true })).toBeVisible();
});
}
test("rapid navigation and cold history keep the latest target and its draft usable", async ({ page }) => {
await installPreview(page);
let release!: () => void;
const gate = new Promise<void>(resolve => { release = resolve; });
await page.route("**/api/sessions/websocket%3Acold/webui-thread?*", async route => { await gate; await route.fallback(); });
await page.goto("/browser/fixture.html?case=session-transition");
await expect(page.getByText("Question for plain", { exact: true })).toBeVisible();
await page.evaluate(() => {
const buttons = [...document.querySelectorAll<HTMLButtonElement>("nav button")];
for (const name of ["goal", "tasks", "plain", "cold"]) buttons.find(button => button.textContent === name)!.click();
});
await expect(page.locator("main[data-session]")).toHaveAttribute("data-session", "cold");
await expect(page.getByRole("status", { name: "Loading conversation…" })).toBeVisible();
await page.getByRole("textbox").fill("Cold draft remains editable");
release();
await expect(page.getByText("Question for cold", { exact: true })).toBeVisible();
await expect(page.getByRole("textbox")).toHaveValue("Cold draft remains editable");
await expect(page.locator("main[data-session]")).toHaveAttribute("data-session", "cold");
});
for (const width of [390, 1440]) {
test(`goal notch follows the active workbench pane at ${width}px`, async ({ page }) => {
await page.setViewportSize({ width, height: 844 });
await installPreview(page);
await page.goto("/browser/fixture.html?case=session-transition&workbench");
await expect(page.locator(".goal-island")).toHaveCount(1);
await expect(page.getByTestId("active-pane-composer").getByRole("textbox")).toBeVisible();
await page.getByRole("button", { name: "Show full goal" }).click();
await expect(page.getByRole("dialog", { name: "Goal", exact: true })).toBeVisible();
await page.getByRole("button", { name: "blocked", exact: true }).click();
await expect(page.getByRole("dialog", { name: "Goal", exact: true })).toHaveCount(0);
await expect(page.locator('.goal-island[data-goal-status="blocked"]')).toHaveCount(1);
await page.getByRole("button", { name: "Show full goal" }).click();
await expect(page.getByRole("dialog", { name: "Goal", exact: true })).toContainText("Waiting for a workspace permission decision.");
const panel = await page.getByRole("dialog", { name: "Goal", exact: true }).boundingBox();
expect(panel!.x).toBeGreaterThanOrEqual(0);
expect(panel!.x + panel!.width).toBeLessThanOrEqual(width);
expect(panel!.height).toBeLessThanOrEqual(844 / 4);
await page.getByTestId("active-pane-composer").getByRole("textbox").click();
await expect(page.getByRole("dialog", { name: "Goal", exact: true })).toHaveCount(0);
});
}
for (const width of [390, 1440]) {
test(`goal notch collapses to its summary before unmounting at ${width}px`, async ({ page }) => {
await page.setViewportSize({ width, height: 844 });
await installPreview(page);
await page.goto("/browser/fixture.html?case=session-transition");
await select(page, "goal");
const trigger = page.getByRole("button", { name: "Show full goal" });
const input = page.getByRole("textbox");
await input.fill("Keep editing after closing the goal");
const compact = await trigger.boundingBox();
await trigger.click();
const panel = page.locator(".goal-island-panel");
await panel.evaluate(async el => { await Promise.all(el.getAnimations({ subtree: true }).map(animation => animation.finished)); });
const expanded = await panel.locator(":scope > .goal-island-surface").boundingBox();
await armGoalMotionFreeze(page, "closed", 0);
await input.click();
await expect(panel).toHaveAttribute("data-state", "closed");
await expect.poll(() => panel.evaluate(el => el.getAnimations().some(animation => animation.playState === "paused"))).toBe(true);
await panel.evaluate(el => { for (const animation of el.getAnimations({ subtree: true })) animation.currentTime = 120; });
const middle = await panel.locator(":scope > .goal-island-surface").boundingBox();
expect(middle!.height).toBeGreaterThan(compact!.height);
expect(middle!.height).toBeLessThan(expanded!.height);
expect(middle!.width).toBeGreaterThan(compact!.width);
expect(middle!.width).toBeLessThan(expanded!.width);
expect(await trigger.evaluate(el => getComputedStyle(el).opacity)).toBe("0");
await expect(input).toBeFocused();
await expect(input).toHaveValue("Keep editing after closing the goal");
await panel.evaluate(el => { for (const animation of el.getAnimations({ subtree: true })) animation.finish(); });
await expect(panel).toHaveCount(0);
await expect(trigger).toBeVisible();
expect(await trigger.evaluate(el => getComputedStyle(el).opacity)).toBe("1");
await expect(input).toBeFocused();
});
}
test("goal notch reverses interrupted motion from its rendered shape", async ({ page }) => {
await installPreview(page);
await page.goto("/browser/fixture.html?case=session-transition");
await select(page, "goal");
const trigger = page.getByRole("button", { name: "Show full goal" });
const panel = page.locator(".goal-island-panel");
const surface = panel.locator(":scope > .goal-island-surface");
const input = page.getByRole("textbox");
await input.fill("Interruptible goal details");
await armGoalMotionFreeze(page, "open", 150);
await trigger.click();
await expect.poll(() => panel.evaluate(el => el.getAnimations().some(animation => animation.playState === "paused"))).toBe(true);
const opening = await surface.boundingBox();
await armGoalMotionFreeze(page, "closed", 0);
await page.keyboard.press("Escape");
await expect(panel).toHaveAttribute("data-state", "closed");
await expect.poll(() => panel.evaluate(el => el.getAnimations().some(animation => animation.playState === "paused"))).toBe(true);
const closingStart = await surface.boundingBox();
expect(Math.abs(closingStart!.width - opening!.width)).toBeLessThan(1);
expect(Math.abs(closingStart!.height - opening!.height)).toBeLessThan(1);
await panel.evaluate(el => { for (const animation of el.getAnimations({ subtree: true })) animation.currentTime = 120; });
const closing = await surface.boundingBox();
await armGoalMotionFreeze(page, "open", 0);
await trigger.click();
await expect(panel).toHaveAttribute("data-state", "open");
await expect.poll(() => panel.evaluate(el => el.getAnimations().some(animation => animation.playState === "paused"))).toBe(true);
const reopening = await surface.boundingBox();
expect(Math.abs(reopening!.width - closing!.width)).toBeLessThan(1);
expect(Math.abs(reopening!.height - closing!.height)).toBeLessThan(1);
await panel.evaluate(el => { for (const animation of el.getAnimations({ subtree: true })) animation.finish(); });
await page.keyboard.press("Escape");
await expect(panel).toHaveCount(0);
await expect(input).toBeFocused();
await expect(input).toHaveValue("Interruptible goal details");
});