feat(webui): show the latest activity in collapsed turns

This commit is contained in:
Xubin Ren committed 2026-11-14 14:37:30 +08:00
1 parent 5e9810c1ad
commit 83ad917d6b
26 files changed
+476 -115

No files matched your search

+77
View File
@@ -0,0 +1,77 @@
import { useEffect, useState } from "react";
import { ThreadMessages } from "@/components/thread/ThreadMessages";
import { Button } from "@/components/ui/button";
import { formatToolCallTrace } from "@/lib/tool-traces";
import type { ToolProgressEvent, UIMessage } from "@/lib/types";
const turnId = "activity-wheel-demo";
const read: ToolProgressEvent = {
phase: "start", call_id: "read-brief", name: "read_file", arguments: { path: "workspace/research/brief.md" },
};
const search: ToolProgressEvent = {
phase: "start", call_id: "search", name: "web_search", arguments: { query: "夜间列车旅行指南" },
};
const results: ToolProgressEvent = {
...search,
phase: "end",
result: [
{ title: "Night train routes across Europe", url: "https://www.seat61.com/night-trains.htm" },
{ title: "A field guide to sleeper trains", url: "https://www.bbc.com/travel/train-guide" },
{ title: "Planning an overnight rail trip", url: "https://www.nationalgeographic.com/travel/rail" },
],
};
const updates = [
{ ...read, phase: "end" },
search,
results,
...["www.bbc.com", "www.nationalgeographic.com", "www.theguardian.com"].map((host, index): ToolProgressEvent => ({
phase: "end", call_id: `page-${index}`, name: "web_fetch", arguments: { url: `https://${host}/travel/trains` },
result: { title: ["How to book a sleeper cabin", "The best overnight rail journeys", "A better way to travel overnight"][index] },
})),
];
export function ActivityWheelFixture() {
const [step, setStep] = useState(0);
const [cadence, setCadence] = useState<number>();
const [dark, setDark] = useState(false);
const [startedAt] = useState(Date.now);
useEffect(() => {
if (cadence === undefined || step >= updates.length) return;
const timer = window.setTimeout(() => setStep(step + 1), cadence);
return () => window.clearTimeout(timer);
}, [cadence, step]);
useEffect(() => {
document.documentElement.classList.toggle("dark", dark);
}, [dark]);
const tools = new Map([read, ...updates.slice(0, step)].map((event) => [event.call_id, event]));
const toolEvents = [...tools.values()];
const traces = toolEvents.map((event) => formatToolCallTrace(event)!);
const messages: UIMessage[] = [
{ id: "question", role: "user", content: "帮我搜几条夜间列车的旅行路线", createdAt: startedAt, turnId },
{ id: "trace", role: "tool", kind: "trace", content: traces.at(-1)!, traces, toolEvents, createdAt: startedAt + 1, turnId },
];
function play(interval: number) {
setStep(0);
setCadence(interval);
}
return <main className="mx-auto space-y-8 px-5 py-8" style={{ maxWidth: 760 }}>
<header className="space-y-3">
<p className="text-xs text-muted-foreground">nanobot · 组件预览 / 模拟活动</p>
<h1 className="text-xl font-semibold">折叠活动滚轮</h1>
<p className="text-sm text-muted-foreground">试试慢速或快速播放。点开「处理中」可以看全部记录。</p>
<div className="flex flex-wrap gap-2">
<Button variant="outline" size="sm" onClick={() => play(850)}>慢速播放</Button>
<Button variant="outline" size="sm" onClick={() => play(110)}>快速播放</Button>
<Button variant="outline" size="sm" onClick={() => { setCadence(undefined); setStep((value) => Math.min(value + 1, updates.length)); }}>下一条</Button>
<Button variant="ghost" size="sm" onClick={() => setDark(!dark)}>切换主题</Button>
</div>
</header>
<ThreadMessages messages={messages} isStreaming activeTurnId={turnId} runStartedAt={startedAt} />
</main>;
}
+123
View File
@@ -0,0 +1,123 @@
import { expect, test } from "@playwright/test";
const path = "/browser/fixture.html?case=activity-wheel";
test.beforeEach(async ({ page }) => {
// Keep network timing out of this test; the real favicon component loads the image.
await page.route(/https:\/\/favicon\.im\//, (route) => route.fulfill({
contentType: "image/svg+xml",
body: '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16" rx="3" fill="#17624c"/></svg>',
}));
await page.goto(path);
});
test("the collapsed row rolls with its icon and a burst lands on the latest activity", async ({ page }) => {
const toggle = page.getByRole("button", { name: /处理中/ });
const wheel = page.getByTestId("latest-activity-wheel");
const next = page.getByRole("button", { name: "下一条" });
await expect(toggle).toHaveAttribute("aria-expanded", "false");
await expect(page.getByTestId("agent-activity-content")).toHaveCount(0);
await expect(wheel).toContainText("brief.md");
const headerBox = (await toggle.boundingBox())!;
const wheelBox = (await wheel.boundingBox())!;
expect(wheelBox.x).toBeGreaterThan(headerBox.x + headerBox.width);
expect(wheelBox.y + wheelBox.height / 2).toBeCloseTo(headerBox.y + headerBox.height / 2, 0);
const iconOffset = await wheel.evaluate((element) => {
const icon = element.querySelector("[data-activity-marker] svg")!.getBoundingClientRect();
const label = element.previousElementSibling!.querySelector("span")!.getBoundingClientRect();
return icon.top + icon.height / 2 - (label.top + label.height / 2);
});
expect(Math.abs(iconOffset)).toBeLessThan(0.2);
const height = (await toggle.boundingBox())!.height;
// This is a status update on the same tool, not a new row.
await next.click();
await expect(wheel).toContainText("读取文件");
await expect(wheel.getByTestId("activity-step")).toHaveCount(1);
// Observe the two real row boxes during the animation, including the incoming logo.
await next.click();
await expect(wheel).toContainText("夜间列车旅行指南");
const motion = await wheel.evaluate(async (element) => {
const button = [...document.querySelectorAll("button")].find((item) => item.textContent === "下一条")!;
button.click();
const end = performance.now() + 600;
do {
await new Promise(requestAnimationFrame);
const rows = element.querySelectorAll<HTMLElement>('[data-testid="activity-step"]');
const incoming = rows[1];
if (!incoming?.querySelector("img")) continue;
const top = incoming.parentElement!.getBoundingClientRect().top - element.getBoundingClientRect().top;
if (top > 1 && top < element.clientHeight) {
return {
gap: top + element.getBoundingClientRect().top - rows[0].parentElement!.getBoundingClientRect().top,
height: element.clientHeight,
};
}
} while (performance.now() < end);
return null;
});
expect(motion).not.toBeNull();
expect(motion!.gap).toBeCloseTo(motion!.height, 0);
await expect(wheel.getByTestId("activity-step")).toHaveCount(1);
await expect(wheel).toContainText("Planning an overnight rail trip");
await expect(wheel.locator("img")).toHaveJSProperty("complete", true);
expect((await toggle.boundingBox())!.height).toBe(height);
await page.getByRole("button", { name: "快速播放" }).click();
await expect(wheel).toContainText("A better way to travel overnight", { timeout: 2200 });
await expect(wheel.getByTestId("activity-step")).toHaveCount(1, { timeout: 500 });
await toggle.focus();
await toggle.press("Enter");
await expect(toggle).toHaveAttribute("aria-expanded", "true");
await expect(wheel).toHaveCount(0);
await expect(toggle).toBeFocused();
await expect(page.getByRole("link", { name: /Night train routes across Europe/ })).toBeVisible();
await expect(page.getByRole("link", { name: /A better way to travel overnight/ })).toBeVisible();
await toggle.press("Enter");
await expect(toggle).toHaveAttribute("aria-expanded", "false");
await expect(wheel).toContainText("A better way to travel overnight");
});
test("narrow reduced-motion preview replaces the row without scrolling the page", async ({ page }) => {
await page.setViewportSize({ width: 360, height: 740 });
await page.emulateMedia({ reducedMotion: "reduce" });
await page.reload();
await page.getByRole("button", { name: "切换主题" }).click();
const toggle = page.getByRole("button", { name: /处理中/ });
const wheel = page.getByTestId("latest-activity-wheel");
await page.getByRole("button", { name: "下一条" }).click({ clickCount: 3 });
await expect(wheel).toContainText("Planning an overnight rail trip");
await expect(wheel.getByTestId("activity-step")).toHaveCount(1);
expect(await wheel.evaluate((element) => {
const row = element.firstElementChild!;
return Math.abs(row.getBoundingClientRect().top - element.getBoundingClientRect().top);
})).toBeLessThan(1);
const header = (await toggle.boundingBox())!;
const row = (await wheel.boundingBox())!;
expect(row.y).toBeGreaterThanOrEqual(header.y + header.height - 0.2);
expect(row.width).toBeGreaterThan(header.width);
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe(360);
});
test("the elapsed label does not shift the collapsed activity horizontally", async ({ page }) => {
await page.setViewportSize({ width: 960, height: 740 });
const start = new Date("2026-01-01T00:00:00Z");
await page.clock.install({ time: start });
await page.clock.pauseAt(new Date(start.getTime() + 60_000));
await page.reload();
const toggle = page.getByRole("button", { name: /处理中/ });
const wheel = page.getByTestId("latest-activity-wheel");
await expect(wheel).toBeVisible();
let initialX: number | undefined;
let elapsed = 0;
for (const [seconds, label] of [[1, "1s"], [9, "9s"], [10, "10s"], [20, "20s"], [59, "59s"], [60, "1m"], [61, "1m 1s"]] as const) {
await page.clock.fastForward((seconds - elapsed) * 1000);
elapsed = seconds;
await expect(toggle).toHaveAccessibleName(`处理中 ${label}`);
const { x } = (await wheel.boundingBox())!;
initialX ??= x;
expect(Math.abs(x - initialX), `wheel displacement at ${label}`).toBeLessThan(0.2);
}
});
+9 -3
View File
@@ -138,16 +138,18 @@ test.describe("answer order", () => {
{ event: "stream_end", ...base, stream_id: "live-empty", turn_seq: 4, resuming: true },
{ event: "message", ...base, turn_seq: 5, kind: "tool_hint", text: "read_file({\"path\":\"beta\"})" },
);
await expect(page.getByTestId("agent-activity-content")).toContainText("网页");
const wheel = page.getByTestId("latest-activity-wheel");
await expect(wheel).toContainText("beta");
await expect(page.getByTestId("agent-activity-content")).toHaveCount(0);
await expect(page.getByText("思考过程", { exact: true })).toHaveCount(0);
await expect(page.getByTestId("activity-reasoning-marker")).toHaveCount(0);
await page.getByRole("button", { name: "Switch topic" }).click();
await expect(page.getByText("检查工具", { exact: true })).toHaveCount(0);
await page.getByRole("button", { name: "Switch topic" }).click();
await expect(page.getByTestId("agent-activity-content")).toContainText("网页");
await expect(wheel).toContainText("beta");
await expect(page.getByTestId("activity-reasoning-marker")).toHaveCount(0);
await dropAndReconnect();
await expect(page.getByTestId("agent-activity-content")).toContainText("网页");
await expect(wheel).toContainText("beta");
await expect(page.getByTestId("activity-reasoning-marker")).toHaveCount(0);
emit(
@@ -157,6 +159,8 @@ test.describe("answer order", () => {
{ event: "delta", ...base, stream_id: "answer", turn_seq: 9, text: "最终答案" },
);
await expect(page.getByText("最终答案", { exact: true })).toHaveCount(1);
await expect(wheel).toContainText("真正的推理");
await page.getByRole("button", { name: /^处理中/ }).click();
await expect(page.getByText("真正的推理", { exact: true })).toHaveCount(1);
const activity = await page.getByTestId("agent-activity-content").textContent();
expect(activity).toContain("网页");
@@ -181,6 +185,8 @@ test.describe("answer order", () => {
await expect(page.getByRole("status", { name: /^Working for / })).toBeVisible();
await expect(page.getByTestId("activity-reasoning-marker")).toHaveCount(0);
emit({ event: "message", ...base, turn_seq: 2, kind: "tool_hint", text: "web_search({\"query\":\"alpha\"})" });
await expect(page.getByTestId("latest-activity-wheel")).toContainText("alpha");
await page.getByRole("button", { name: /^Working for / }).click();
await expect(page.getByTestId("agent-activity-content")).toContainText("web");
await expect(page.getByTestId("activity-reasoning-marker")).toHaveCount(0);
expect(errors).toEqual([]);
+10 -2
View File
@@ -98,7 +98,7 @@ test("appearance explanations open on demand and follow the selected display mod
const explanations = [
["Reading text size", "Adjust messages, code and the composer—not navigation."],
["Activity display", "Choose how much detail appears as nanobot works."],
["Activity details", "Show progress while working; keep finished work compact."],
["Activity details", "Keep details collapsed by default. Show the latest activity while working."],
["Edit preview", "Show changed files and line counts."],
];
for (const [label, description] of explanations) {
@@ -109,12 +109,20 @@ test("appearance explanations open on demand and follow the selected display mod
await expect(page.getByRole("tooltip")).toBeHidden();
}
await page.getByRole("button", { name: "Expanded", exact: true }).click();
const collapsed = page.getByRole("button", { name: "Collapsed", exact: true });
const expanded = page.getByRole("button", { name: "Expanded", exact: true });
await expect(collapsed).toHaveAttribute("aria-pressed", "true");
await expanded.click();
await page.reload();
await expect(expanded).toHaveAttribute("aria-pressed", "true");
const activity = page.getByRole("button", { name: "Activity details", exact: true });
await activity.focus();
await expect(page.getByRole("tooltip")).toHaveText("Keep activity details expanded by default.");
await activity.press("Escape");
await expect(page.getByRole("tooltip")).toBeHidden();
await collapsed.click();
await page.reload();
await expect(collapsed).toHaveAttribute("aria-pressed", "true");
await page.getByRole("button", { name: "Diff", exact: true }).click();
const edits = page.getByRole("button", { name: "Edit preview", exact: true });
await edits.focus();
+2
View File
@@ -14,6 +14,8 @@ for (const width of [1280, 360]) {
await page.getByRole("button", { name: "failed", exact: true }).click();
await expect(activity).toContainText("Command failed (exit code 7) curl -u •••• https://example.invalid");
await page.getByRole("button", { name: "many", exact: true }).click();
await expect(activity.getByTestId("latest-activity-wheel")).toContainText("Command was still running at the last check");
await activity.getByRole("button", { name: /^Working for / }).click();
const disclosure = activity.getByRole("button", { name: "Show earlier command checks (24)" });
await expect(activity.getByTestId("activity-step")).toHaveCount(1);
await disclosure.click();
+4
View File
@@ -33,6 +33,7 @@ import { ThreadLoadingFixture } from "./thread-loading-fixture";
import { AnswerOrderFixture } from "./answer-order-fixture";
import { SidebarActivityFixture } from "./sidebar-activity-fixture";
import { ActivityLogosFixture } from "./activity-logos-fixture";
import { ActivityWheelFixture } from "./activity-wheel-fixture";
import { ExecSessionFixture } from "./exec-session-fixture";
import { HistoryHydrationFixture } from "./history-hydration-fixture";
import { IdleCompactionFixture, installIdleCompactionApi } from "./idle-compaction-fixture";
@@ -230,6 +231,7 @@ if (parameters.get("case") === "tools-catalog") installToolsCatalogPreviewApi();
if (parameters.get("case") === "idle-compaction") installIdleCompactionApi();
if (parameters.get("case") === "subagent-dock") installSubagentDockApi();
await initializeI18n();
if (parameters.get("case") === "activity-wheel") await setAppLanguage("zh-CN");
if (parameters.get("case") === "appearance" && parameters.has("lang")) {
await setAppLanguage(normalizeLocale(parameters.get("lang")));
}
@@ -266,6 +268,8 @@ createRoot(document.getElementById("root")!).render(<TooltipProvider>
? <AnswerOrderFixture />
: parameters.get("case") === "activity-logos"
? <ActivityLogosFixture parameters={parameters} />
: parameters.get("case") === "activity-wheel"
? <ActivityWheelFixture />
: parameters.get("case") === "exec-session"
? <ExecSessionFixture />
: parameters.get("case") === "sidebar-activity"