Skip to content

Your lightweight open-source personal agent.

feat(webui): keep delegated work within reach (#6443)

chengyongru9b3af7b66cfe
diff --git a/docs/webui.md b/docs/webui.md
index e929ebe3a..0c7a2bfab 100644
--- a/docs/webui.md
+++ b/docs/webui.md
@@ -135,9 +135,11 @@ After a model request fails and automatic retries stop, the WebUI shows the fail
### Delegated work
-When nanobot delegates work to subagents, a work group appears under the request that started it. Progress continues to update after the main reply finishes. Completed tasks stay available for inspection, and refreshing or reopening the WebUI restores saved progress and results without restarting the work.
+When nanobot delegates work to subagents, **Subtasks** appears above the message input while tasks are queued, running, or stopping. It stays within reach as the conversation scrolls, even after the main reply finishes or you send another message. Open it for live activity; on narrow screens it opens from the bottom. The task list scrolls independently of the conversation.
-Work groups follow the browser's **Activity details** preference: **Auto** opens running work and folds it when all tasks finish; **Expanded** keeps it open by default. You can also expand or fold a group manually to check individual outcomes, including failures and partial results.
+Finished tasks leave the live list when it is closed. If you are already reading the list, they remain until you close it. When all tasks finish with the list closed, a brief completion or failure summary appears and then disappears; focusing or hovering over it keeps it available.
+
+Saved results appear as compact, expandable records beside the requests that started the work, and scroll with the conversation. Tasks without a matching request in the displayed history remain under **Other tasks**. Refreshing or reopening the WebUI restores active work in the fixed entry and finished work in the conversation, without restarting tasks or bringing all old tasks back into the live list.
Select a task for its read-only conversation and tool activity. Closing the details leaves it running; its stop button cancels only that task. Give follow-up instructions to nanobot in the main conversation.
diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsx
index ea5835744..34859f72f 100644
--- a/webui/browser/fixture.tsx
+++ b/webui/browser/fixture.tsx
@@ -44,6 +44,7 @@ import { DisplayMathFixture } from "./display-math-fixture";
import { AttachmentLayoutFixture } from "./attachment-layout-fixture";
import { LoadedSessionSearchFixture } from "./loaded-session-search-fixture";
import { AppearanceFixture } from "./appearance-fixture";
+import { installSubagentDockApi, SubagentDockFixture } from "./subagent-dock-fixture";
const history: UIMessage[] = [
{ id: "question", role: "user", content: "Earlier question", createdAt: 1_700_000_000_000 },
@@ -215,6 +216,7 @@ function AppsFixture() {
}
if (parameters.get("case") === "skeleton-additions") installSkeletonPreviewApi();
if (parameters.get("case") === "idle-compaction") installIdleCompactionApi();
+if (parameters.get("case") === "subagent-dock") installSubagentDockApi();
await initializeI18n();
if (parameters.get("case") === "appearance" && parameters.has("lang")) {
await setAppLanguage(normalizeLocale(parameters.get("lang")));
@@ -224,6 +226,8 @@ createRoot(document.getElementById("root")!).render(<TooltipProvider>
? <AppearanceFixture />
: parameters.get("case") === "loaded-session-search"
? <LoadedSessionSearchFixture />
+ : parameters.get("case") === "subagent-dock"
+ ? <SubagentDockFixture parameters={parameters} />
: parameters.get("case") === "attachments"
? <AttachmentLayoutFixture />
: parameters.get("case") === "theme-toggle"
diff --git a/webui/browser/history-boundary.spec.ts b/webui/browser/history-boundary.spec.ts
index c379a341a..d349da07d 100644
--- a/webui/browser/history-boundary.spec.ts
+++ b/webui/browser/history-boundary.spec.ts
@@ -230,7 +230,13 @@ test("wheel loading hands off to a retained 48px slot; prepend and delayed layou
const { body, header } = await openSettledHistory(page);
const nativeTop = await body.evaluate((node) => node.scrollTop);
await body.hover();
+ // Lazy Markdown can change scrollTop before the queued wheel reaches the viewport.
+ const wheelDelivered = await body.evaluateHandle((node) => ({
+ done: new Promise<void>((resolve) => node.addEventListener("wheel", () => resolve(), { once: true })),
+ }));
await page.mouse.wheel(0, -100);
+ await wheelDelivered.evaluate(({ done }) => done);
+ await wheelDelivered.dispose();
await expect.poll(() => body.evaluate((node) => node.scrollTop)).toBeLessThan(nativeTop);
expect(await displacement(body)).toBe(0);
expect(history.reads).toHaveLength(0);
@@ -299,7 +305,7 @@ test("wheel loading hands off to a retained 48px slot; prepend and delayed layou
expect(history.reads).toHaveLength(1);
});
-test("unlinked task prelude stays with the retained boundary when earlier messages load", async ({ page }) => {
+test("archived task results stay with the retained boundary when earlier messages load", async ({ page }) => {
const history = await installHistory(page);
await page.route("**/api/sessions/**/subagents", (route) => route.fulfill({ json: { tasks: [{
task_id: "legacy", revision: 1, label: "Earlier check", task_description: "Check earlier work",
diff --git a/webui/browser/subagent-dock-fixture.tsx b/webui/browser/subagent-dock-fixture.tsx
new file mode 100644
index 000000000..5a90d0895
--- /dev/null
+++ b/webui/browser/subagent-dock-fixture.tsx
@@ -0,0 +1,150 @@
+import { useEffect, useRef, useState } from "react";
+import { ThreadShell } from "@/components/thread/ThreadShell";
+import { settings } from "@/dev/gallery/settings";
+import { setAppLanguage } from "@/i18n";
+import { normalizeLocale } from "@/i18n/config";
+import { ClientProvider } from "@/providers/ClientProvider";
+import type { SubagentTaskSnapshot, ThreadProjectionEvent } from "@/lib/types";
+import { createStreamClient } from "@/tests/stream-client";
+
+const { client, receive } = createStreamClient();
+const chatId = "dock-preview";
+const turnId = "preview-turn";
+const createdAt = Date.now() / 1000;
+let streamLength = 0;
+let inputNumber = 0;
+const saveTasks = new URLSearchParams(location.search).has("saved");
+const taskStorageKey = "fixture.subagent-dock.tasks";
+const taskLabels = new URLSearchParams(location.search).has("long-labels")
+ ? ["核对多轮任务完成后的归档位置、长标题换行与独立详情入口", "Review_the_responsive_subtask_panel_and_keyboard_focus_without_interrupting_running_work", "整理交互建议"]
+ : ["检查项目实现", "核对回归测试", "整理交互建议"];
+const tasks: SubagentTaskSnapshot[] = taskLabels.map((label, index) => ({
+ task_id: `preview-${index}`, revision: 1, label, task_description: `这是虚构的演示任务:${label}。不会读取项目或调用模型。`,
+ origin_turn_id: turnId, origin_message_id: "preview-prompt", created_at: createdAt + index, completed_at: null,
+ state: index === 2 ? "queued" : "running", phase: "awaiting_model", elapsed_seconds: 20 + index * 3, iteration: 1,
+ tool_events: index === 0 ? [{ name: "read_file", status: "running" }] : index === 1 ? [{ name: "exec", status: "running" }] : [],
+ usage: null, receipts: {}, result: null, partial: false, stop_reason: null, error: null,
+}));
+const history: ThreadProjectionEvent[] = [
+ { event: "user_message", chat_id: chatId, projection_id: "preview-prompt", turn_id: turnId, text: "请让三个子任务分别检查实现、测试和交互。主对话继续讨论,不要等它们全部结束。", starts_turn: true },
+ { event: "message", chat_id: chatId, projection_id: "preview-answer", turn_id: turnId,
+ text: "已经安排。你可以继续在这里交流,子任务会独立推进。\n\n**随时查看,不必回翻聊天**\n\n输入区上方的子任务入口会留在原位。点开可以查看每一路任务的状态、真实工具活动和最终结果。\n\n" + "主对话仍然可以正常输出和滚动。任务列表与消息区分别滚动,展开详情也不会取消正在执行的任务。\n\n".repeat(12) },
+];
+
+function updateTask(index: number, patch: Partial<SubagentTaskSnapshot>) {
+ const previous = tasks[index];
+ const next = { ...previous, ...patch, revision: (previous.revision ?? 0) + 1 };
+ tasks[index] = next;
+ if (saveTasks) sessionStorage.setItem(taskStorageKey, JSON.stringify(tasks));
+ receive({ event: "subagent_task", chat_id: chatId, task: next });
+}
+
+export function installSubagentDockApi() {
+ const stored = saveTasks ? sessionStorage.getItem(taskStorageKey) : null;
+ if (stored) tasks.splice(0, tasks.length, ...JSON.parse(stored) as SubagentTaskSnapshot[]);
+ else if (new URLSearchParams(location.search).has("archived")) {
+ tasks.forEach((task, index) => {
+ tasks[index] = { ...task, state: "done", phase: "done", elapsed_seconds: [9, 89, 1234][index], completed_at: createdAt + 30, tool_events: [] };
+ });
+ } else if (new URLSearchParams(location.search).has("past")) {
+ tasks.push(...Array.from({ length: 40 }, (_, index) => ({
+ ...tasks[0], task_id: `past-${index}`, label: `Past check ${index}`, state: "done" as const,
+ origin_message_id: null, origin_turn_id: "past-turn", created_at: createdAt - 100 + index,
+ completed_at: createdAt - 50 + index, tool_events: [], result: "Saved past result",
+ })));
+ }
+ const original = window.fetch.bind(window);
+ window.fetch = async (input, init) => {
+ const url = new URL(input instanceof Request ? input.url : String(input), location.href);
+ if (url.origin !== location.origin || !url.pathname.startsWith("/api/")) return original(input, init);
+ if (url.pathname === "/api/settings") return Response.json(settings);
+ if (url.pathname === "/api/commands") return Response.json({ commands: [
+ { command: "/history", title: "Chat history", description: "Show recent messages", icon: "history", lifecycle: "side_channel", accepts_args: true },
+ ] });
+ if (url.pathname.endsWith("/subagents")) return Response.json({ tasks: url.pathname.includes(encodeURIComponent(`websocket:${chatId}`)) ? tasks : [] });
+ if (url.pathname.includes("/subagents/") && url.pathname.endsWith("/webui-thread")) {
+ const task = tasks.find(item => url.pathname.includes(`/${item.task_id}/`))!;
+ return Response.json({ schemaVersion: 3, projection: "events", events: [
+ { event: "user_message", chat_id: task.task_id, projection_id: `${task.task_id}-prompt`, turn_id: "child", starts_turn: true, text: task.task_description },
+ { event: "message", chat_id: task.task_id, projection_id: `${task.task_id}-answer`, turn_id: "child", text: task.result ?? "正在检查。这是隔离的演示内容,没有真实文件操作。" },
+ ] });
+ }
+ if (url.pathname.includes("/webui-thread")) return Response.json({ schemaVersion: 3, projection: "events", events: history });
+ return Response.json({}, { status: 404 });
+ };
+ client.requestMutation = async <T,>(action: string, payload?: Record<string, unknown>): Promise<T> => {
+ if (action !== "subagent.cancel") throw new Error(`Unexpected preview mutation: ${action}`);
+ const index = tasks.findIndex(task => task.task_id === payload?.task_id);
+ updateTask(index, { state: "cancelled", phase: "cancelled", tool_events: [], completed_at: Date.now() / 1000 });
+ return tasks[index] as T;
+ };
+}
+
+export function SubagentDockFixture({ parameters }: { parameters: URLSearchParams }) {
+ const [topic, setTopic] = useState(chatId);
+ const [active, setActive] = useState(true);
+ const [dark, setDark] = useState(parameters.has("dark"));
+ const [portal, setPortal] = useState<HTMLDivElement | null>(null);
+ const timers = useRef<number[]>([]);
+ useEffect(() => {
+ document.documentElement.classList.toggle("dark", dark);
+ void setAppLanguage(normalizeLocale(parameters.get("lang")));
+ }, [dark, parameters]);
+ useEffect(() => () => timers.current.forEach(window.clearTimeout), []);
+ const finish = () => tasks.forEach((task, index) => {
+ if (task.state === "running" || task.state === "queued") updateTask(index, {
+ state: "done", phase: "done", tool_events: [], completed_at: Date.now() / 1000,
+ result: index === 0 && parameters.has("image-result") ? "## Image result\n\n![Result image](https://example.com/dock-result.svg)"
+ : index === 0 && parameters.has("markdown-result")
+ ? "## 天气结果\n\n**北京**:约 **10°C**,有小雨。\n\n" + "这是完整的多行查询结果,保留原始段落、文字样式和详细说明,阅读时可以滚动任务列表。".repeat(30)
+ + "\n\n- **南京**:约 18°C,有雾。\n- **天津**:约 12°C,多云。\n\n[天气来源](https://example.com/weather)\n\n```text\nchecked_at: 2026-10-25T20:52:00+08:00\n```\n\n最后一条完整结论:以上结果均可继续核对。"
+ : ["已核对面板的位置与滚动边界。", "定向检查已完成,保留详情与单任务停止。", "建议让任务入口始终留在输入区附近。"][index % 3],
+ });
+ });
+ const growReply = () => {
+ streamLength += 12;
+ const replyTurn = `long-reply-${streamLength}`;
+ receive({ event: "goal_status", chat_id: chatId, turn_id: replyTurn, status: "running", started_at: Date.now() / 1000 });
+ receive({ event: "delta", chat_id: chatId, turn_id: replyTurn, stream_id: "reply", text: "主助手继续输出较长的说明,子任务入口保持在输入框上方。\n\n".repeat(streamLength) });
+ receive({ event: "stream_end", chat_id: chatId, turn_id: replyTurn, stream_id: "reply" });
+ receive({ event: "turn_end", chat_id: chatId, turn_id: replyTurn });
+ };
+ return <ClientProvider client={client} token="fixture" webuiCapabilities={["webui.core.v1", "webui.subagents.v1", "webui.subagents.events.v1", "webui.subagents.history.v1"]}>
+ <main className="thread-workspace flex min-w-0 flex-col overflow-hidden bg-background text-foreground" style={{ height: "var(--app-viewport-height, 100dvh)" }}>
+ <nav aria-label="Preview controls" className="flex shrink-0 items-center gap-4 overflow-x-auto whitespace-nowrap border-b px-4 py-2 text-xs text-muted-foreground">
+ <span>虚构任务预览</span>
+ <button onClick={() => {
+ growReply();
+ updateTask(2, { state: "running", tool_events: [{ name: "web_fetch", status: "running" }] });
+ timers.current.push(window.setTimeout(() => updateTask(0, { state: "done", tool_events: [], completed_at: Date.now() / 1000, result: "入口不会随主回复滚走。" }), 3000));
+ timers.current.push(window.setTimeout(finish, 7000));
+ }}>模拟运行</button>
+ <button onClick={growReply}>追加长回复</button>
+ <button onClick={() => updateTask(0, { state: "done", phase: "done", tool_events: [], completed_at: Date.now() / 1000, result: "第一项已完成并归档。" })}>完成第一项</button>
+ <button onClick={finish}>全部完成</button>
+ <button onClick={() => {
+ inputNumber += 1;
+ receive({ event: "user_message", chat_id: chatId, turn_id: `next-turn-${inputNumber}`, turn_seq: 1, starts_turn: true, text: `下一轮消息 ${inputNumber}` });
+ }}>新一轮消息</button>
+ <button onClick={() => updateTask(1, { state: "error", error: "演示:测试执行失败,请打开详情检查。", tool_events: [], completed_at: Date.now() / 1000 })}>模拟失败</button>
+ <button onClick={() => {
+ for (let index = 3; index < 23; index++) {
+ if (tasks[index]) continue;
+ tasks[index] = { ...tasks[0], task_id: `preview-${index}`, label: `额外检查 ${index}`, revision: 1, created_at: createdAt + index, state: "queued", completed_at: null, result: null, error: null, tool_events: [] };
+ receive({ event: "subagent_task", chat_id: chatId, task: tasks[index] });
+ }
+ }}>增加任务</button>
+ <button onClick={() => setTopic(topic === chatId ? "other-preview" : chatId)}>切换会话</button>
+ <button onClick={() => setActive(value => !value)}>切换活动面板</button>
+ <button onClick={() => setDark(value => !value)}>切换主题</button>
+ <button onClick={() => location.reload()}>重播</button>
+ </nav>
+ <ThreadShell session={{ key: `websocket:${topic}`, channel: "websocket", chatId: topic, createdAt: null, updatedAt: null, preview: "" }}
+ title="子任务交互预览" onToggleSidebar={() => {}} theme={dark ? "dark" : "light"} onToggleTheme={() => setDark(value => !value)}
+ settingsSnapshot={settings} composerActive={active} composerPortalTarget={parameters.has("portal") ? portal : undefined}
+ sessions={[{ key: "websocket:reference-preview", channel: "websocket", chatId: "reference-preview", title: "Reference conversation", preview: "", createdAt: null, updatedAt: null,
+ handle: { id: "handle_00000000000000000000000000000001", name: "reference" } }]} />
+ {parameters.has("portal") ? <div ref={setPortal} className="shrink-0 px-4 pb-4" data-testid="preview-composer-portal" /> : null}
+ </main>
+ </ClientProvider>;
+}
diff --git a/webui/browser/subagent-dock.spec.ts b/webui/browser/subagent-dock.spec.ts
new file mode 100644
index 000000000..76826c842
--- /dev/null
+++ b/webui/browser/subagent-dock.spec.ts
@@ -0,0 +1,627 @@
+import { expect, test, type Locator } from "@playwright/test";
+
+async function settledMotion(target: Locator) {
+ await target.evaluate(() => document.fonts.ready);
+ await expect.poll(() => target.evaluate(async node => {
+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ return node.getAnimations({ subtree: true }).filter(animation =>
+ animation.effect?.getTiming().iterations !== Infinity && (animation.pending || animation.playState === "running")).length;
+ })).toBe(0);
+}
+
+for (const width of [1440, 390]) {
+ test(`keeps subtasks reachable through long replies, independent list scrolling and detail handoff at ${width}px`, async ({ page }, info) => {
+ const errors: string[] = [];
+ page.on("pageerror", error => errors.push(error.message));
+ await page.setViewportSize({ width, height: 900 });
+ await page.goto("/browser/fixture.html?case=subagent-dock");
+ const trigger = page.getByTestId("subagent-task-dock-trigger");
+ const messages = page.getByTestId("thread-message-region");
+ await expect(trigger).toContainText("Running: 3");
+ await settledMotion(page.getByTestId("subagent-task-dock"));
+ const original = (await trigger.boundingBox())!;
+ const composer = page.locator(".thread-composer-surface");
+ const composerBounds = (await composer.boundingBox())!;
+ const corner = await composer.evaluate(node => Number.parseFloat(getComputedStyle(node).borderTopLeftRadius));
+ expect(original.x - composerBounds.x).toBeGreaterThanOrEqual(corner);
+ expect(composerBounds.x + composerBounds.width - original.x - original.width).toBeGreaterThanOrEqual(corner);
+ expect(original.y + original.height).toBeCloseTo(composerBounds.y, 0);
+ await page.screenshot({ path: info.outputPath("attached-handle-closed.png") });
+ expect(await messages.locator('[data-testid="subagent-task-dock"]').count()).toBe(0);
+ await page.getByRole("button", { name: "追加长回复", exact: true }).click();
+ await expect(messages.getByText(/主助手继续输出较长的说明/).first()).toBeAttached();
+ await messages.evaluate(node => { node.scrollTop = 0; });
+ await expect.poll(async () => Math.abs((await trigger.boundingBox())!.y - original.y)).toBeLessThan(1);
+ await expect(trigger).toBeInViewport();
+ await trigger.click({ position: { x: original.width - 8, y: original.height / 2 } });
+ const tree = page.getByTestId("subagent-task-tree");
+ await expect(tree).toBeVisible();
+ const dock = page.getByTestId("subagent-task-dock");
+ const panel = dock.getByRole("region", { name: "Subtasks", exact: true });
+ await settledMotion(panel);
+ const bounds = (await panel.boundingBox())!;
+ const anchor = (await dock.boundingBox())!;
+ expect(bounds.y).toBeGreaterThanOrEqual(0);
+ expect(bounds.y + bounds.height).toBeCloseTo(anchor.y + anchor.height, 0);
+ expect(bounds.y + bounds.height).toBeCloseTo((await composer.boundingBox())!.y, 0);
+ expect(bounds.width).toBeCloseTo(original.width, 0);
+ expect(bounds.height).toBeLessThanOrEqual(448);
+ await expect(panel).toHaveAccessibleDescription("0 of 3 completed");
+ await page.mouse.move(1, 1);
+ await page.screenshot({ path: info.outputPath("subtask-tree.png") });
+ const row = tree.locator('[data-subagent-id="preview-0"]');
+ await row.click();
+ const detail = page.getByRole("dialog", { name: "检查项目实现", exact: true });
+ await expect(detail).toBeVisible();
+ await expect(detail).toBeFocused();
+ await settledMotion(detail);
+ const headerStop = detail.getByRole("button", { name: "Stop 检查项目实现", exact: true });
+ await expect(detail).toHaveAccessibleDescription("Running");
+ await expect(detail.getByText("Running", { exact: true }).locator("..")).toHaveClass(/\bsr-only\b/);
+ await expect(headerStop.locator('[data-action-icon="stop"][data-active] .loading-ring-arc')).toBeVisible();
+ const headerTitle = detail.getByRole("heading", { name: "检查项目实现", exact: true });
+ const stopBounds = (await headerStop.boundingBox())!;
+ const closeBounds = (await detail.getByRole("button", { name: "Close", exact: true }).boundingBox())!;
+ expect(Math.abs(stopBounds.y + stopBounds.height / 2 - closeBounds.y - closeBounds.height / 2)).toBeLessThanOrEqual(1);
+ expect((await headerTitle.boundingBox())!.x + (await headerTitle.boundingBox())!.width).toBeLessThanOrEqual(stopBounds.x);
+ expect(stopBounds.x + stopBounds.width).toBeLessThanOrEqual(closeBounds.x);
+ if (width === 390) {
+ expect(stopBounds.width).toBeGreaterThanOrEqual(44);
+ expect(stopBounds.height).toBeGreaterThanOrEqual(44);
+ }
+ await headerTitle.locator("..").screenshot({ path: info.outputPath("running-detail-header-stop.png") });
+ await detail.getByRole("button", { name: "Close", exact: true }).click();
+ await expect(detail).toHaveCount(0);
+ await expect(tree).toBeVisible();
+ await expect(row).toBeFocused();
+ await page.keyboard.press("Escape");
+ await expect(tree).toHaveCount(0);
+ await expect(trigger).toBeFocused();
+
+ await page.getByRole("button", { name: "增加任务", exact: true }).click();
+ await trigger.click();
+ await expect(tree.locator("[data-subagent-id]")).toHaveCount(23);
+ const beforeScroll = await messages.evaluate(node => node.scrollTop);
+ await tree.hover();
+ await page.mouse.wheel(0, 3000);
+ await expect.poll(() => tree.evaluate(node => node.scrollTop)).toBeGreaterThan(0);
+ await expect(tree.locator('[data-subagent-id="preview-22"]')).toBeInViewport();
+ expect(await messages.evaluate(node => node.scrollTop)).toBe(beforeScroll);
+ await page.keyboard.press("Escape");
+ await expect(tree).toHaveCount(0);
+
+ await page.getByRole("button", { name: "全部完成", exact: true }).click();
+ await expect(trigger).toContainText("Completed: 23");
+ await trigger.click();
+ await expect(tree.locator('[data-task-state="done"]')).toHaveCount(23);
+ await page.keyboard.press("Escape");
+ await expect(tree).toHaveCount(0);
+ const input = page.getByRole("textbox").first();
+ await input.fill("The main conversation is still usable");
+ await expect(input).toHaveValue("The main conversation is still usable");
+ expect(await page.locator("body").evaluate(node => getComputedStyle(node).pointerEvents)).not.toBe("none");
+ expect(errors).toEqual([]);
+ });
+}
+
+for (const width of [1440, 390]) {
+ test(`renders complete result Markdown without clipping inside the task drawer at ${width}px`, async ({ page }, info) => {
+ await page.setViewportSize({ width, height: 844 });
+ await page.goto(`/browser/fixture.html?case=subagent-dock&markdown-result${width === 390 ? "&dark" : ""}`);
+ const trigger = page.getByTestId("subagent-task-dock-trigger");
+ const tree = page.getByTestId("subagent-task-tree");
+ const messages = page.getByTestId("thread-message-region");
+ await trigger.click();
+ const row = tree.locator('[data-subagent-id="preview-0"]');
+ const panel = page.getByTestId("subagent-task-dock").getByRole("region", { name: "Subtasks", exact: true });
+ await expect(tree).toBeVisible();
+ await expect.poll(async () => Math.abs((await panel.boundingBox())!.height - (await tree.boundingBox())!.height)).toBeLessThan(1);
+ const task = row.locator("xpath=ancestor::li[1]");
+ await expect(task.locator(".loading-ring-arc")).toHaveCount(1);
+ const labelX = (await row.locator(":scope > span").nth(1).boundingBox())!.x;
+ const statusSlot = (await row.locator(":scope > span").first().boundingBox())!;
+ await page.mouse.move(1, 1);
+ await page.screenshot({ path: info.outputPath("one-task-ring-running.png") });
+ // Finish through the existing control without dismissing the reading view.
+ await page.getByRole("button", { name: "全部完成", exact: true }).evaluate(node => (node as HTMLButtonElement).click());
+ const heading = tree.getByRole("heading", { level: 2, name: "天气结果" });
+ await expect(heading).toBeVisible();
+ await expect(row).toHaveAccessibleName(/检查项目实现 Completed/);
+ await expect(row.locator("svg")).toHaveCount(0);
+ expect((await row.locator(":scope > span").nth(1).boundingBox())!.x).toBeCloseTo(labelX, 1);
+ const completedSlot = (await row.locator(":scope > span").first().boundingBox())!;
+ expect(completedSlot.width).toBeCloseTo(statusSlot.width, 1);
+ expect(completedSlot.height).toBeCloseTo(statusSlot.height, 1);
+ await expect(tree.locator("strong").filter({ hasText: "10°C" })).toBeVisible();
+ await settledMotion(page.getByTestId("subagent-task-dock"));
+ const dimensions = await tree.evaluate(node => ({ clientWidth: node.clientWidth, scrollWidth: node.scrollWidth, clientHeight: node.clientHeight, scrollHeight: node.scrollHeight }));
+ expect(dimensions.scrollWidth).toBe(dimensions.clientWidth);
+ expect(dimensions.scrollHeight).toBeGreaterThan(dimensions.clientHeight);
+ await page.screenshot({ path: info.outputPath("result-markdown-start.png") });
+ const beforeScroll = await messages.evaluate(node => node.scrollTop);
+ const tail = tree.getByText("最后一条完整结论:以上结果均可继续核对。", { exact: true });
+ await tail.scrollIntoViewIfNeeded();
+ await expect(tail).toBeInViewport();
+ await expect(tree.getByRole("link", { name: "天气来源", exact: true })).toHaveAttribute("href", "https://example.com/weather");
+ await expect(tree.locator("pre")).toContainText("checked_at: 2026-10-25T20:52:00+08:00");
+ expect(await messages.evaluate(node => node.scrollTop)).toBe(beforeScroll);
+ await page.screenshot({ path: info.outputPath("result-markdown-end.png") });
+ const input = page.getByRole("textbox").first();
+ await input.fill("继续阅读完整结果,同时输入下一条消息");
+ await expect(trigger).toHaveAttribute("aria-expanded", "true");
+ await row.click();
+ const detail = page.getByRole("dialog", { name: "检查项目实现", exact: true });
+ await expect(detail.getByRole("heading", { level: 2, name: "天气结果" })).toBeVisible();
+ await expect(detail).toHaveAccessibleDescription("Completed");
+ const title = detail.getByRole("heading", { name: "检查项目实现", exact: true });
+ await settledMotion(detail);
+ const closeButton = await detail.getByRole("button", { name: "Close", exact: true }).elementHandle();
+ const { titleBounds, closeBounds } = await title.evaluate((node, close) => ({
+ titleBounds: node.getBoundingClientRect().toJSON(),
+ closeBounds: close!.getBoundingClientRect().toJSON(),
+ }), closeButton);
+ expect(Math.abs(titleBounds.y + titleBounds.height / 2 - closeBounds.y - closeBounds.height / 2)).toBeLessThanOrEqual(1);
+ expect(titleBounds.x + titleBounds.width).toBeLessThanOrEqual(closeBounds.x);
+ await expect(title.locator("..")).not.toContainText(/\d+s/);
+ await title.locator("..").screenshot({ path: info.outputPath("completed-detail-header.png") });
+ await page.keyboard.press("Escape");
+ await expect(row).toBeFocused();
+ });
+}
+
+test("keeps the portaled dock scoped to the active conversation and honors reduced motion", async ({ page }) => {
+ await page.emulateMedia({ reducedMotion: "reduce", colorScheme: "dark" });
+ await page.goto("/browser/fixture.html?case=subagent-dock&portal&dark");
+ const portal = page.getByTestId("preview-composer-portal");
+ const trigger = portal.getByTestId("subagent-task-dock-trigger");
+ await expect(trigger).toContainText("Running: 3");
+ await trigger.click();
+ const tree = page.getByTestId("subagent-task-tree");
+ await expect(tree).toBeVisible();
+ await expect(tree.locator(".loading-ring-arc").first()).toHaveCSS("animation-name", "none");
+ await expect(portal.getByRole("region", { name: "Subtasks", exact: true })).toHaveCSS("transition-property", "none");
+ await page.keyboard.press("Escape");
+ await page.getByRole("button", { name: "切换活动面板", exact: true }).click();
+ await expect(portal.getByTestId("subagent-task-dock")).toHaveCount(0);
+ await expect(tree).toHaveCount(0);
+ await page.getByRole("button", { name: "切换活动面板", exact: true }).click();
+ await expect(trigger).toBeVisible();
+ await expect(trigger).toHaveAttribute("aria-expanded", "false");
+ await page.getByRole("button", { name: "切换会话", exact: true }).click();
+ await expect(portal.getByTestId("subagent-task-dock")).toHaveCount(0);
+ await page.getByRole("button", { name: "切换会话", exact: true }).click();
+ await expect(trigger).toContainText("Running: 3");
+ await page.getByRole("button", { name: "模拟失败", exact: true }).click();
+ await expect(trigger).toContainText("Running: 2");
+ const results = page.getByTestId("thread-message-region").getByRole("region", { name: "Subtasks", exact: true });
+ await results.getByRole("button", { name: /Review needed: 1/ }).click();
+ const failedRow = results.getByRole("button", { name: /核对回归测试 Failed/ });
+ expect((await failedRow.getByText("Failed", { exact: true }).boundingBox())!.width).toBeGreaterThan(16);
+ await failedRow.click();
+ await expect(page.getByRole("dialog", { name: "核对回归测试", exact: true }).getByRole("alert")).toHaveText("演示:测试执行失败,请打开详情检查。");
+});
+
+test("keeps the composer editable while the task drawer stays open", async ({ page }) => {
+ await page.goto("/browser/fixture.html?case=subagent-dock");
+ await page.getByTestId("subagent-task-dock-trigger").click();
+ await expect(page.getByTestId("subagent-task-tree")).toBeVisible();
+ const input = page.getByRole("textbox").first();
+ await input.click();
+ await expect(page.getByTestId("subagent-task-tree")).toBeVisible();
+ await expect(input).toBeFocused();
+ await page.keyboard.type("Continue the conversation");
+ await expect(input).toHaveValue("Continue the conversation");
+ const imeEscapeAllowed = await input.evaluate(node => node.dispatchEvent(new KeyboardEvent("keydown", {
+ key: "Escape", isComposing: true, bubbles: true, cancelable: true,
+ })));
+ expect(imeEscapeAllowed).toBe(true);
+ await expect(page.getByTestId("subagent-task-dock-trigger")).toHaveAttribute("aria-expanded", "true");
+});
+
+for (const width of [1440, 390]) {
+ test(`preserves the top detail layer and its opener across a breakpoint change from ${width}px`, async ({ page }) => {
+ await page.setViewportSize({ width, height: 900 });
+ await page.goto("/browser/fixture.html?case=subagent-dock");
+ await page.getByTestId("subagent-task-dock-trigger").click();
+ const row = page.getByTestId("subagent-task-tree").locator('[data-subagent-id="preview-1"]');
+ await row.click();
+ const detail = page.getByRole("dialog", { name: "核对回归测试", exact: true });
+ await expect(detail).toBeFocused();
+ await page.setViewportSize({ width: width > 639 ? 390 : 1440, height: 900 });
+ await expect(detail).toBeVisible();
+ await expect(detail).toBeFocused();
+ await expect(page.getByRole("dialog")).toHaveCount(1);
+ await detail.getByRole("button", { name: "Close", exact: true }).click();
+ await expect(detail).toHaveCount(0);
+ await expect(page.getByTestId("subagent-task-tree")).toBeVisible();
+ await expect(row).toBeFocused();
+ await page.keyboard.press("Escape");
+ await expect(page.getByTestId("subagent-task-tree")).toHaveCount(0);
+ await expect(page.getByTestId("subagent-task-dock-trigger")).toBeFocused();
+ });
+}
+
+test("keeps the task drawer above the composer inside a shortened visual viewport", async ({ page }) => {
+ await page.setViewportSize({ width: 390, height: 844 });
+ await page.emulateMedia({ reducedMotion: "reduce" });
+ await page.goto("/browser/fixture.html?case=subagent-dock");
+ await page.evaluate(() => {
+ document.documentElement.style.setProperty("--app-viewport-top", "0px");
+ document.documentElement.style.setProperty("--app-viewport-height", "500px");
+ });
+ await page.getByTestId("subagent-task-dock-trigger").click();
+ const panel = page.getByTestId("subagent-task-dock").getByRole("region", { name: "Subtasks", exact: true });
+ const bounds = (await panel.boundingBox())!;
+ const input = page.getByRole("textbox").first();
+ const inputBounds = (await input.boundingBox())!;
+ expect(bounds.y).toBeGreaterThanOrEqual(0);
+ expect(bounds.y + bounds.height).toBeLessThanOrEqual(inputBounds.y);
+ expect(inputBounds.y + inputBounds.height).toBeLessThanOrEqual(500);
+ await input.fill("Keyboard viewport remains usable");
+ await expect(panel).toBeVisible();
+ await page.keyboard.press("Escape");
+ await expect(panel).toBeHidden();
+ await expect(input).toBeFocused();
+});
+
+for (const width of [1440, 390]) {
+ test(`retires completed live work into the conversation and restores only active tasks at ${width}px`, async ({ page }) => {
+ await page.setViewportSize({ width, height: 900 });
+ await page.goto("/browser/fixture.html?case=subagent-dock&saved&past");
+ const trigger = page.getByTestId("subagent-task-dock-trigger");
+ await trigger.click();
+ const tree = page.getByTestId("subagent-task-tree");
+ await expect(tree.locator("[data-subagent-id]")).toHaveCount(3);
+ await expect(tree).toContainText("检查项目实现");
+ await page.keyboard.press("Escape");
+ await page.getByRole("button", { name: "完成第一项", exact: true }).click();
+ await expect(trigger).toContainText("Running: 2");
+ await page.getByRole("button", { name: "新一轮消息", exact: true }).click();
+ await expect(trigger).toContainText("Running: 2");
+ await trigger.click();
+ await expect(tree.locator("[data-subagent-id]")).toHaveCount(2);
+ await expect(tree).toContainText("核对回归测试");
+ await expect(tree).toContainText("整理交互建议");
+ await page.keyboard.press("Escape");
+ await page.getByRole("button", { name: "全部完成", exact: true }).click();
+ await expect(trigger).toContainText("Completed: 2");
+ await expect(trigger).toHaveCount(0, { timeout: 7000 });
+ const results = page.getByTestId("thread-message-region").getByRole("region", { name: "Subtasks", exact: true });
+ await results.getByRole("button", { name: /Subtasks/ }).click();
+ await expect(results.locator("[data-subagent-id]")).toHaveCount(3);
+ await results.getByRole("button", { name: /检查项目实现 Completed/ }).click();
+ const detail = page.getByRole("dialog", { name: "检查项目实现", exact: true });
+ await expect(detail).toContainText("第一项已完成并归档。");
+ await detail.getByRole("button", { name: "Close", exact: true }).click();
+ await expect(results.getByRole("button", { name: /检查项目实现 Completed/ })).toBeFocused();
+ await page.reload();
+ await expect(page.getByTestId("thread-message-region").getByText("随时查看,不必回翻聊天", { exact: true })).toBeAttached();
+ await expect(trigger).toHaveCount(0);
+ const restoredResults = page.getByTestId("thread-message-region").getByRole("region", { name: "Subtasks", exact: true });
+ await restoredResults.getByRole("button", { name: /Subtasks/ }).click();
+ await expect(restoredResults.getByRole("button", { name: /检查项目实现 Completed/ })).toBeVisible();
+ });
+}
+
+test("does not retire a completed list or detail while it is being read", async ({ page }) => {
+ await page.goto("/browser/fixture.html?case=subagent-dock");
+ await page.getByRole("button", { name: "模拟运行", exact: true }).click();
+ const trigger = page.getByTestId("subagent-task-dock-trigger");
+ await trigger.click();
+ const tree = page.getByTestId("subagent-task-tree");
+ await tree.locator('[data-subagent-id="preview-1"]').click();
+ const detail = page.getByRole("dialog", { name: "核对回归测试", exact: true });
+ await expect(detail).toContainText("保留详情与单任务停止", { timeout: 12000 });
+ await detail.getByRole("button", { name: "Close", exact: true }).click();
+ await expect(tree.locator('[data-subagent-id="preview-1"]')).toBeFocused();
+ await expect(tree.locator('[data-task-state="done"]')).toHaveCount(3);
+ await page.keyboard.press("Escape");
+ await expect(tree).toHaveCount(0);
+ await expect(trigger).toHaveCount(0);
+ await expect(page.getByRole("textbox").first()).toBeFocused();
+});
+
+for (const width of [1440, 390]) {
+ test(`keeps the reading position when results are archived and the live entry retires at ${width}px`, async ({ page }) => {
+ await page.setViewportSize({ width, height: 900 });
+ await page.goto("/browser/fixture.html?case=subagent-dock");
+ const body = page.getByTestId("thread-message-region");
+ const paragraphs = body.getByText("主对话仍然可以正常输出和滚动。任务列表与消息区分别滚动,展开详情也不会取消正在执行的任务。", { exact: true });
+ await expect(paragraphs).toHaveCount(12);
+ await settledMotion(body);
+ const anchor = paragraphs.nth(6);
+ await anchor.scrollIntoViewIfNeeded();
+ await body.hover();
+ await page.mouse.wheel(0, -160);
+ await expect.poll(() => body.evaluate(node => node.scrollHeight - node.clientHeight - node.scrollTop)).toBeGreaterThan(100);
+ await expect(anchor).toBeInViewport();
+ await settledMotion(body);
+ await expect.poll(() => body.evaluate(node => node.scrollHeight - node.clientHeight - node.scrollTop)).toBeGreaterThan(100);
+ const before = (await anchor.boundingBox())!.y;
+ await page.getByRole("button", { name: "完成第一项", exact: true }).click();
+ await expect(page.getByTestId("subagent-task-dock-trigger")).toContainText("Running: 2");
+ await expect.poll(async () => Math.abs((await anchor.boundingBox())!.y - before)).toBeLessThan(1);
+ await page.getByRole("button", { name: "全部完成", exact: true }).click();
+ await expect(page.getByTestId("subagent-task-dock-trigger")).toHaveCount(0, { timeout: 7000 });
+ await expect.poll(async () => Math.abs((await anchor.boundingBox())!.y - before)).toBeLessThan(1);
+ });
+}
+
+test("returns to the composer when completed work is dismissed on desktop blank space", async ({ page }) => {
+ await page.goto("/browser/fixture.html?case=subagent-dock");
+ await page.getByRole("button", { name: "模拟运行", exact: true }).click();
+ await page.getByTestId("subagent-task-dock-trigger").click();
+ const tree = page.getByTestId("subagent-task-tree");
+ await expect(tree.locator('[data-task-state="done"]')).toHaveCount(3, { timeout: 12000 });
+ await page.locator("main").click({ position: { x: 4, y: 65 } });
+ await expect(tree).toHaveCount(0);
+ await expect(page.getByTestId("subagent-task-dock-trigger")).toHaveCount(0);
+ await expect(page.getByRole("textbox").first()).toBeFocused();
+});
+
+
+test("keeps long task names, stop controls and detail handoff usable on a narrow screen", async ({ page }, info) => {
+ await page.setViewportSize({ width: 320, height: 844 });
+ await page.goto("/browser/fixture.html?case=subagent-dock&long-labels");
+ await page.getByTestId("subagent-task-dock-trigger").click();
+ const panel = page.getByTestId("subagent-task-dock").getByRole("region", { name: "Subtasks", exact: true });
+ const tree = page.getByTestId("subagent-task-tree");
+ await expect(tree).toBeVisible();
+ expect(await tree.evaluate(node => node.scrollWidth)).toBe(await tree.evaluate(node => node.clientWidth));
+ const label = "核对多轮任务完成后的归档位置、长标题换行与独立详情入口";
+ const row = tree.locator('[data-subagent-id="preview-0"]');
+ await expect(row).toHaveAccessibleName(new RegExp(label));
+ const stop = panel.getByRole("button", { name: `Stop ${label}`, exact: true });
+ const stopBounds = (await stop.boundingBox())!;
+ expect(stopBounds.width).toBeGreaterThanOrEqual(44);
+ expect(stopBounds.height).toBeGreaterThanOrEqual(44);
+ await row.click();
+ const detail = page.getByRole("dialog", { name: label, exact: true });
+ await expect(detail).toBeFocused();
+ await settledMotion(detail);
+ const close = detail.getByRole("button", { name: "Close", exact: true });
+ const closeBounds = (await close.boundingBox())!;
+ expect(closeBounds.width).toBeGreaterThanOrEqual(44);
+ expect(closeBounds.height).toBeGreaterThanOrEqual(44);
+ const title = detail.getByRole("heading", { name: label, exact: true });
+ await expect(title).toHaveAttribute("title", label);
+ await expect(detail).toHaveAccessibleDescription("Running");
+ const titleBounds = (await title.boundingBox())!;
+ expect(titleBounds.height).toBeLessThan(30);
+ expect(Math.abs(titleBounds.y + titleBounds.height / 2 - closeBounds.y - closeBounds.height / 2)).toBeLessThanOrEqual(1);
+ expect(titleBounds.x + titleBounds.width).toBeLessThanOrEqual(closeBounds.x);
+ const detailStop = detail.getByRole("button", { name: `Stop ${label}`, exact: true });
+ const detailStopBounds = (await detailStop.boundingBox())!;
+ expect(detailStopBounds.width).toBeGreaterThanOrEqual(44);
+ expect(detailStopBounds.height).toBeGreaterThanOrEqual(44);
+ expect(Math.abs(detailStopBounds.y + detailStopBounds.height / 2 - closeBounds.y - closeBounds.height / 2)).toBeLessThanOrEqual(1);
+ expect(titleBounds.x + titleBounds.width).toBeLessThanOrEqual(detailStopBounds.x);
+ expect(detailStopBounds.x + detailStopBounds.width).toBeLessThanOrEqual(closeBounds.x);
+ await title.locator("..").screenshot({ path: info.outputPath("long-running-detail-header.png") });
+ await detailStop.click();
+ await expect(detail).toHaveAccessibleDescription("Cancelled");
+ await close.click();
+ await expect(row).toBeFocused();
+});
+
+test("follows the mouse before release and snaps without double toggling", async ({ page }, info) => {
+ await page.goto("/browser/fixture.html?case=subagent-dock");
+ const trigger = page.getByTestId("subagent-task-dock-trigger");
+ const tree = page.getByTestId("subagent-task-tree");
+ await expect(trigger).toHaveAttribute("aria-expanded", "false");
+ await page.getByRole("button", { name: "增加任务", exact: true }).click();
+ await expect(trigger).toContainText("Running: 23");
+ await expect(trigger).toHaveAttribute("aria-expanded", "false");
+ await expect(tree).toHaveCount(0);
+ await trigger.focus();
+ await page.keyboard.press("Tab");
+ await expect(page.getByRole("textbox").first()).toBeFocused();
+ const swipe = async (dx: number, dy: number) => {
+ const bounds = (await trigger.boundingBox())!;
+ const x = bounds.x + 8;
+ const y = bounds.y + bounds.height / 2;
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x + dx / 2, y + dy / 2, { steps: 4 });
+ if (Math.abs(dy) > Math.abs(dx)) {
+ await expect.poll(async () => (await trigger.boundingBox())!.y).toBeCloseTo(bounds.y + dy / 2, 0);
+ const panel = page.getByTestId("subagent-task-dock").getByRole("region", { name: "Subtasks", exact: true });
+ const panelBounds = (await panel.boundingBox())!;
+ const composerBounds = (await page.locator(".thread-composer-surface").boundingBox())!;
+ expect(panelBounds.y + panelBounds.height).toBeCloseTo(composerBounds.y, 0);
+ await page.screenshot({ path: info.outputPath(dy < 0 ? "mouse-drag-opening.png" : "mouse-drag-closing.png") });
+ }
+ await page.mouse.move(x + dx, y + dy, { steps: 4 });
+ await page.mouse.up();
+ };
+ await swipe(40, 2);
+ await expect(trigger).toHaveAttribute("aria-expanded", "false");
+ await swipe(0, -60);
+ await expect(tree).toBeVisible();
+ await settledMotion(page.getByTestId("subagent-task-dock"));
+ await swipe(0, 60);
+ await expect(tree).toHaveCount(0);
+ await expect(trigger).toBeFocused();
+ const bounds = (await trigger.boundingBox())!;
+ const x = bounds.x + 8;
+ const y = bounds.y + bounds.height / 2;
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x, y + 30, { steps: 4 });
+ await page.keyboard.press("Escape");
+ await page.mouse.move(x, y - 60, { steps: 6 });
+ await page.mouse.up();
+ await expect(trigger).toHaveAttribute("aria-expanded", "false");
+ await page.keyboard.press("Space");
+ await expect(tree).toBeVisible();
+});
+
+test.describe("touch task drawer", () => {
+ test.use({ hasTouch: true, isMobile: true, viewport: { width: 390, height: 844 } });
+ test("follows touch movement, restores a cancelled drag, and keeps list scrolling independent", async ({ page }, info) => {
+ await page.goto("/browser/fixture.html?case=subagent-dock");
+ const trigger = page.getByTestId("subagent-task-dock-trigger");
+ const tree = page.getByTestId("subagent-task-tree");
+ const cdp = await page.context().newCDPSession(page);
+ const swipe = async (target: typeof trigger, dy: number, cancel = false) => {
+ await settledMotion(page.getByTestId("subagent-task-dock"));
+ const bounds = (await target.boundingBox())!;
+ const x = bounds.x + bounds.width / 2;
+ const y = bounds.y + bounds.height / 2;
+ await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y }] });
+ for (let step = 1; step <= 6; step++) {
+ await cdp.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: [{ x, y: y + dy * step / 6 }] });
+ if (step === 3 && target === trigger) {
+ await expect.poll(async () => (await trigger.boundingBox())!.y).toBeCloseTo(bounds.y + dy / 2, 0);
+ await page.screenshot({ path: info.outputPath(cancel ? "touch-drag-before-cancel.png" : dy < 0 ? "touch-drag-opening.png" : "touch-drag-closing.png") });
+ }
+ }
+ await cdp.send("Input.dispatchTouchEvent", { type: cancel ? "touchCancel" : "touchEnd", touchPoints: [] });
+ };
+ await swipe(trigger, -60, true);
+ await expect(trigger).toHaveAttribute("aria-expanded", "false");
+ await swipe(trigger, -60);
+ await expect(tree).toBeVisible();
+ await settledMotion(page.getByTestId("subagent-task-dock"));
+ await swipe(trigger, 60, true);
+ await expect(trigger).toHaveAttribute("aria-expanded", "true");
+ await settledMotion(page.getByTestId("subagent-task-dock"));
+ await swipe(trigger, 60);
+ await expect(tree).toHaveCount(0);
+ await page.getByRole("button", { name: "增加任务", exact: true }).click();
+ await trigger.tap();
+ await expect(tree.locator("[data-subagent-id]")).toHaveCount(23);
+ await settledMotion(page.getByTestId("subagent-task-dock"));
+ await swipe(tree, -100);
+ await expect.poll(() => tree.evaluate(node => node.scrollTop)).toBeGreaterThan(0);
+ await expect(trigger).toHaveAttribute("aria-expanded", "true");
+ await cdp.detach();
+ });
+
+ test("preserves completion feedback when an opening drag is cancelled", async ({ page }) => {
+ await page.emulateMedia({ reducedMotion: "reduce", colorScheme: "dark" });
+ await page.goto("/browser/fixture.html?case=subagent-dock&dark");
+ const trigger = page.getByTestId("subagent-task-dock-trigger");
+ await trigger.focus();
+ const bounds = (await trigger.boundingBox())!;
+ const x = bounds.x + 12;
+ const y = bounds.y + bounds.height / 2;
+ const cdp = await page.context().newCDPSession(page);
+ await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: [{ x, y }] });
+ await cdp.send("Input.dispatchTouchEvent", { type: "touchMove", touchPoints: [{ x, y: y - 40 }] });
+ await expect.poll(async () => (await trigger.boundingBox())!.y).toBeCloseTo(bounds.y - 40, 0);
+ await page.getByRole("button", { name: "全部完成", exact: true }).evaluate(node => (node as HTMLButtonElement).click());
+ await expect(page.getByTestId("subagent-task-tree").locator('[data-task-state="done"]')).toHaveCount(3);
+ await cdp.send("Input.dispatchTouchEvent", { type: "touchCancel", touchPoints: [] });
+ await expect(trigger).toHaveAttribute("aria-expanded", "false");
+ await expect(trigger).toContainText("Completed: 3");
+ await expect(page.getByTestId("subagent-task-tree")).toHaveCount(0);
+ await cdp.detach();
+ });
+});
+
+for (const width of [1440, 390, 320]) {
+ test(`aligns archived task columns with their disclosure at ${width}px`, async ({ page }, info) => {
+ await page.setViewportSize({ width, height: 900 });
+ await page.goto(`/browser/fixture.html?case=subagent-dock&archived${width === 320 ? "&long-labels" : ""}`);
+ if (width === 1440) await page.evaluate(() => { document.documentElement.style.zoom = "1.25"; });
+ const archive = page.locator("[data-subagent-results]").first();
+ const header = archive.locator("[data-subagent-results-summary]");
+ const logo = header.locator("img");
+ await expect(logo).toHaveAttribute("src", "/brand/nanobot_mark.svg");
+ await expect.poll(() => logo.evaluate(node => (node as HTMLImageElement).naturalWidth)).toBeGreaterThan(0);
+ const rows = archive.locator('[data-subagent-surface="archive"]');
+ await expect(rows.first()).toBeHidden();
+ await header.click();
+ await expect(rows).toHaveCount(3);
+ await expect(rows.first()).toBeVisible();
+ await settledMotion(archive);
+ const geometry = await archive.evaluate(node => {
+ const header = node.querySelector<HTMLElement>("[data-subagent-results-summary]")!;
+ const bounds = (element: Element) => element.getBoundingClientRect();
+ return {
+ overflow: node.scrollWidth > node.clientWidth,
+ header: [header.children[0], header.children[1]].map(element => bounds(element).x),
+ headerCenters: [...header.children].map(element => {
+ const rect = bounds(element);
+ return rect.y + rect.height / 2;
+ }),
+ trailingEdge: bounds(header.lastElementChild!).right,
+ rows: [...node.querySelectorAll('[data-subagent-surface="archive"]')].map(row => ({
+ columns: [row.children[0], row.children[1]].map(element => bounds(element).x),
+ elapsedRight: bounds(row.children[3]).right,
+ })),
+ };
+ });
+ expect(geometry.overflow).toBe(false);
+ expect(Math.max(...geometry.headerCenters) - Math.min(...geometry.headerCenters)).toBeLessThan(0.5);
+ for (const row of geometry.rows) {
+ row.columns.forEach((position, index) => expect(Math.abs(position - geometry.header[index])).toBeLessThan(0.5));
+ expect(Math.abs(row.elapsedRight - geometry.trailingEdge)).toBeLessThan(0.5);
+ }
+ await archive.screenshot({ path: info.outputPath("archive-logo-light.png") });
+ await page.getByRole("button", { name: "切换主题", exact: true }).click();
+ await expect(logo).toBeVisible();
+ await archive.screenshot({ path: info.outputPath("archive-logo-dark.png") });
+ await rows.first().click();
+ await expect(page.getByRole("dialog")).toBeFocused();
+ await page.keyboard.press("Escape");
+ await expect(rows.first()).toBeFocused();
+ await header.click();
+ await expect(rows.first()).toBeHidden();
+ });
+}
+
+for (const width of [1440, 390]) {
+ test(`keeps composer palettes reachable above an open task drawer at ${width}px`, async ({ page }) => {
+ await page.setViewportSize({ width, height: 900 });
+ await page.goto("/browser/fixture.html?case=subagent-dock");
+ const trigger = page.getByTestId("subagent-task-dock-trigger");
+ await trigger.click();
+ await settledMotion(page.getByTestId("subagent-task-dock"));
+ const input = page.getByRole("textbox").first();
+ for (const [query, inserted] of [["/", "/history"], ["@ref", "@reference "]]) {
+ await input.fill(query);
+ const option = page.getByRole("option").first();
+ await expect(option).toBeVisible();
+ expect(await option.evaluate(node => {
+ const bounds = node.getBoundingClientRect();
+ const hit = document.elementFromPoint(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
+ return !!hit && node.contains(hit);
+ })).toBe(true);
+ await option.click();
+ await expect(input).toHaveValue(inserted);
+ await expect(trigger).toHaveAttribute("aria-expanded", "true");
+ await expect(page.getByTestId("subagent-task-tree")).toBeVisible();
+ }
+ });
+
+ test(`keeps result image portals owned by the task drawer at ${width}px`, async ({ page }) => {
+ await page.setViewportSize({ width, height: 900 });
+ await page.route("https://example.com/dock-result.svg", route => route.fulfill({
+ contentType: "image/svg+xml",
+ body: '<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="800"><rect width="1200" height="800" fill="#7788aa" /></svg>',
+ }));
+ await page.goto("/browser/fixture.html?case=subagent-dock&image-result");
+ const trigger = page.getByTestId("subagent-task-dock-trigger");
+ await trigger.click();
+ await page.getByRole("button", { name: "全部完成", exact: true }).evaluate(node => (node as HTMLButtonElement).click());
+ const tree = page.getByTestId("subagent-task-tree");
+ const thumbnail = tree.getByRole("button", { name: "View image: Result image", exact: true });
+ await thumbnail.click();
+ const viewer = page.getByRole("dialog", { name: "Result image", exact: true });
+ await expect(viewer).toBeVisible();
+ await viewer.getByRole("button", { name: "Zoom in", exact: true }).click();
+ await expect(viewer.getByRole("button", { name: "Fit image", exact: true })).toHaveText("150%");
+ await viewer.getByRole("img", { name: "Result image", exact: true }).click();
+ await expect(viewer).toBeVisible();
+ await page.keyboard.press("Escape");
+ await expect(viewer).toHaveCount(0);
+ await expect(thumbnail).toBeFocused();
+ await expect(trigger).toHaveAttribute("aria-expanded", "true");
+ await page.locator("main").click({ position: { x: 4, y: 65 } });
+ await expect(tree).toHaveCount(0);
+ await expect(trigger).toHaveCount(0);
+ await expect(page.getByRole("textbox").first()).toBeFocused();
+ });
+}
diff --git a/webui/src/components/thread/SubagentTaskDock.tsx b/webui/src/components/thread/SubagentTaskDock.tsx
new file mode 100644
index 000000000..587bc7662
--- /dev/null
+++ b/webui/src/components/thread/SubagentTaskDock.tsx
@@ -0,0 +1,240 @@
+import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+
+import { MarkdownText } from "@/components/MarkdownText";
+import { ErrorTaskIcon, StopIcon } from "@/components/icons/product-icons";
+import { SubagentTaskButton, useSubagentTasks } from "@/components/thread/SubagentTasks";
+import { Button } from "@/components/ui/button";
+import { HoverHint } from "@/components/ui/hover-hint";
+import { LoadingRing } from "@/components/ui/loading-ring";
+import { isActiveSubagentTask, type ObservedSubagentTask } from "@/lib/subagent-tasks";
+import { useSubagentActivity } from "@/components/thread/useSubagentActivity";
+
+function needsReview(task: ObservedSubagentTask) {
+ return task.state === "error" || task.state === "incomplete" || task.state === "interrupted";
+}
+
+export function SubagentTaskDock({ inputKey = null }: { inputKey?: string | null }) {
+ const context = useSubagentTasks();
+ if (!context?.available || !context.tasks.length) return null;
+ return <TaskDock key={context.sessionKey} allTasks={context.tasks} inputKey={inputKey} />;
+}
+
+function TaskDock({ allTasks, inputKey }: { allTasks: ObservedSubagentTask[]; inputKey: string | null }) {
+ const { t } = useTranslation("common");
+ const context = useSubagentTasks()!;
+ const panelId = useId();
+ const progressId = useId();
+ const root = useRef<HTMLDivElement>(null);
+ const ownedPointerDown = useRef<PointerEvent | null>(null);
+ const trigger = useRef<HTMLButtonElement>(null);
+ const panel = useRef<HTMLDivElement>(null);
+ const content = useRef<HTMLDivElement>(null);
+ const gesture = useRef<{ pointerId: number; x: number; y: number; height: number; wasOpen: boolean; dragged: boolean } | null>(null);
+ const suppressClick = useRef(false);
+ const [focused, setFocused] = useState(false);
+ const [hovered, setHovered] = useState(false);
+ const [treeMounted, setTreeMounted] = useState(false);
+ const [listMaxHeight, setListMaxHeight] = useState(400);
+ const [expandedHeight, setExpandedHeight] = useState(0);
+ const [dragHeight, setDragHeight] = useState<number | null>(null);
+ const { open, setOpen, tasks } = useSubagentActivity(allTasks, inputKey, context.detailOpen || focused || hovered || dragHeight !== null);
+ const running = allTasks.filter(isActiveSubagentTask).length;
+ const composerInput = () => root.current?.closest(".thread-composer-stack")?.querySelector("textarea");
+ const changeOpen = (next: boolean, returnFocus = false, preserveFeedback = false) => {
+ if (next === open) return;
+ if (next) setTreeMounted(true);
+ setOpen(next, { preserveFeedback });
+ if (!next && returnFocus) (running ? trigger.current : composerInput())?.focus({ preventScroll: true });
+ };
+ const finishExit = useCallback(() => setTreeMounted(false), []);
+ const cancelGesture = () => {
+ const start = gesture.current;
+ if (!start) return;
+ gesture.current = null;
+ suppressClick.current = true;
+ if (trigger.current?.hasPointerCapture(start.pointerId)) trigger.current.releasePointerCapture(start.pointerId);
+ setDragHeight(null);
+ changeOpen(start.wasOpen, false, true);
+ };
+
+ useLayoutEffect(() => {
+ if (!treeMounted || !root.current) return;
+ const anchor = root.current;
+ const composer = anchor.closest(".thread-composer-stack")!;
+ const pane = anchor.closest(".thread-conversation");
+ const viewport = window.visualViewport;
+ const measure = () => {
+ const top = Math.max(viewport?.offsetTop ?? 0, pane?.getBoundingClientRect().top ?? 0);
+ const height = Math.min(448, anchor.getBoundingClientRect().bottom - top - 12);
+ setListMaxHeight(Math.max(0, height - (trigger.current?.offsetHeight ?? 44) - 2));
+ };
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(composer);
+ if (pane) observer.observe(pane);
+ viewport?.addEventListener("resize", measure);
+ viewport?.addEventListener("scroll", measure);
+ window.addEventListener("resize", measure);
+ return () => {
+ observer.disconnect();
+ viewport?.removeEventListener("resize", measure);
+ viewport?.removeEventListener("scroll", measure);
+ window.removeEventListener("resize", measure);
+ };
+ }, [treeMounted]);
+
+ useLayoutEffect(() => {
+ if (!treeMounted || !content.current) return;
+ const node = content.current;
+ const measure = () => setExpandedHeight(node.getBoundingClientRect().height);
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(node);
+ return () => observer.disconnect();
+ }, [treeMounted]);
+
+ useEffect(() => {
+ if (open || dragHeight !== null || !treeMounted) return;
+ const animations = panel.current?.getAnimations?.() ?? [];
+ if (!animations.length) { finishExit(); return; }
+ let cancelled = false;
+ void Promise.allSettled(animations.map(animation => animation.finished)).then(() => {
+ if (!cancelled) finishExit();
+ });
+ return () => { cancelled = true; };
+ }, [open, dragHeight, treeMounted, finishExit]);
+
+ useEffect(() => {
+ if ((!open && dragHeight === null) || context.detailOpen) return;
+ const outside = (event: PointerEvent) => {
+ const target = event.target;
+ if (gesture.current || ownedPointerDown.current === event || !(target instanceof Element) || root.current?.closest(".thread-composer-stack")?.contains(target)) return;
+ // Dismissing on blank space must not strand focus after the last task.
+ const focusable = target.closest("button, a[href], input, textarea, select, [tabindex], [contenteditable=true]");
+ const returnFocus = !running && !focusable;
+ if (returnFocus) event.preventDefault();
+ changeOpen(false, returnFocus);
+ };
+ const escape = (event: KeyboardEvent) => {
+ if (event.key !== "Escape" || event.isComposing || event.defaultPrevented) return;
+ event.preventDefault();
+ if (gesture.current) cancelGesture();
+ else changeOpen(false, !!root.current?.contains(document.activeElement) || (!running && document.activeElement === document.body));
+ };
+ document.addEventListener("pointerdown", outside);
+ window.addEventListener("keydown", escape);
+ return () => {
+ document.removeEventListener("pointerdown", outside);
+ window.removeEventListener("keydown", escape);
+ };
+ });
+
+ const completed = tasks.filter(task => task.state === "done").length;
+ const attention = tasks.filter(needsReview).length;
+ const progress = t("thread.subagents.progress", { completed, total: tasks.length });
+ const summary = running ? t("thread.subagents.running", { count: running })
+ : completed === tasks.length ? t("thread.subagents.completed", { count: completed })
+ : t("thread.subagents.finished", { count: tasks.length });
+ const title = t("thread.subagents.workTitle");
+
+ if (!tasks.length) return null;
+ return <div ref={root} data-testid="subagent-task-dock" className="subagent-task-dock relative mx-auto h-11 sm:h-7"
+ onPointerDownCapture={event => { ownedPointerDown.current = event.nativeEvent; }}>
+ <div className="absolute inset-x-0 bottom-0 z-30 overflow-hidden rounded-t-2xl border border-b-0 border-border/70 bg-card shadow-[0_-4px_20px_rgba(15,23,42,0.06)] dark:shadow-[0_-4px_20px_rgba(0,0,0,0.24)]">
+ <HoverHint enabled={!open && dragHeight === null} content={`${title} · ${summary}`}>
+ <button ref={trigger} type="button" data-testid="subagent-task-dock-trigger"
+ aria-expanded={open} aria-controls={panelId}
+ onFocus={() => setFocused(true)} onBlur={() => setFocused(false)}
+ onPointerEnter={event => { if (event.pointerType === "mouse") setHovered(true); }} onPointerLeave={() => setHovered(false)}
+ onPointerDown={event => {
+ if (event.button !== 0 || !event.isPrimary || gesture.current) return;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ const height = panel.current?.getBoundingClientRect().height ?? 0;
+ gesture.current = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, height, wasOpen: open, dragged: false };
+ suppressClick.current = false;
+ setTreeMounted(true);
+ setDragHeight(height);
+ }}
+ onPointerMove={event => {
+ const start = gesture.current;
+ if (!start || start.pointerId !== event.pointerId) return;
+ const dy = event.clientY - start.y;
+ const dx = Math.abs(event.clientX - start.x);
+ suppressClick.current ||= Math.hypot(dx, dy) > 6;
+ if (!start.dragged && (Math.abs(dy) <= 6 || Math.abs(dy) <= dx)) return;
+ start.dragged = true;
+ const height = Math.max(0, Math.min(content.current!.getBoundingClientRect().height, start.height - dy));
+ if (height > 0) changeOpen(true);
+ setDragHeight(height);
+ }}
+ onPointerUp={event => {
+ const start = gesture.current;
+ if (!start || start.pointerId !== event.pointerId) return;
+ gesture.current = null;
+ const dy = event.clientY - start.y;
+ const dx = Math.abs(event.clientX - start.x);
+ suppressClick.current ||= Math.hypot(dx, dy) > 6;
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ setDragHeight(null);
+ const next = start.dragged && Math.abs(dy) >= 24 ? dy < 0 : start.wasOpen;
+ changeOpen(next, start.dragged && !next, !start.wasOpen && !next);
+ }}
+ onPointerCancel={event => { if (gesture.current?.pointerId === event.pointerId) cancelGesture(); }}
+ onLostPointerCapture={event => { if (gesture.current?.pointerId === event.pointerId) cancelGesture(); }}
+ onClick={event => {
+ if (suppressClick.current && event.detail !== 0) { suppressClick.current = false; return; }
+ changeOpen(!open, open);
+ }}
+ className="group flex h-11 w-full touch-none select-none items-center justify-center text-muted-foreground outline-none transition-colors hover:bg-muted/70 hover:text-foreground focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring active:cursor-grabbing motion-reduce:transition-none sm:h-7 sm:cursor-grab">
+ <span aria-hidden className="h-1 w-8 rounded-full bg-current opacity-30 transition-opacity group-hover:opacity-60 motion-reduce:transition-none" />
+ <span className="sr-only">{title} · {summary}
+ {attention ? ` · ${t("thread.subagents.needsReview", { count: attention })}` : ""}
+ </span>
+ </button>
+ </HoverHint>
+ <div ref={panel} id={panelId} role="region" aria-label={title} aria-describedby={progressId}
+ hidden={!treeMounted} aria-hidden={open ? undefined : true} {...(!open ? { inert: "" } : {})}
+ className="overflow-hidden transition-[height] duration-200 ease-out motion-reduce:transition-none"
+ style={{ height: dragHeight === null ? open ? expandedHeight : 0 : Math.min(dragHeight, expandedHeight), transition: dragHeight === null ? undefined : "none" }}>
+ <p id={progressId} className="sr-only">{progress}</p>
+ <div ref={content}>{treeMounted ? <TaskTree tasks={tasks} maxHeight={listMaxHeight} /> : null}</div>
+ </div>
+ </div>
+ </div>;
+}
+
+function TaskTree({ tasks, maxHeight }: { tasks: ObservedSubagentTask[]; maxHeight: number }) {
+ const { t } = useTranslation("common");
+ const context = useSubagentTasks()!;
+ return <div data-testid="subagent-task-tree" style={{ maxHeight }} className="min-h-0 overflow-y-auto overscroll-contain p-1.5 pt-0 scrollbar-thin">
+ <ol className="space-y-0.5">
+ {tasks.map(task => <li key={task.task_id} data-task-state={task.state}
+ className="rounded-lg transition-colors duration-150 hover:bg-muted/50 focus-within:bg-muted/50 motion-reduce:transition-none">
+ <div className="flex min-w-0 items-center gap-0.5">
+ <SubagentTaskButton task={task} surface="activity" />
+ {task.state === "queued" || task.state === "running" ? <HoverHint content={t("thread.subagents.stopTask", { label: task.label })}>
+ <Button type="button" variant="ghost" size="icon"
+ className="h-11 w-11 shrink-0 rounded-lg text-muted-foreground hover:bg-destructive/10 hover:text-destructive motion-reduce:transition-none sm:h-9 sm:w-9"
+ aria-label={t("thread.subagents.stopTask", { label: task.label })} aria-busy={context.stoppingId === task.task_id}
+ disabled={context.stoppingId !== null} onClick={() => void context.stop(task)}>
+ {context.stoppingId === task.task_id ? <LoadingRing className="h-3.5 w-3.5" /> : <StopIcon className="h-3.5 w-3.5" fill="currentColor" aria-hidden />}
+ </Button>
+ </HoverHint> : null}
+ </div>
+ {isActiveSubagentTask(task) && task.tool_events.length ? <ul className="ml-[21px] mr-2 space-y-1 border-l border-border/60 pb-2 pl-4 text-[11px] leading-4 text-muted-foreground">
+ {task.tool_events.map((tool, index) => <li key={`${index}:${tool.name}`} className="flex min-h-5 min-w-0 items-center gap-2">
+ {tool.status === "error" ? <ErrorTaskIcon className="h-3 w-3 shrink-0 text-destructive" aria-hidden />
+ : <span className="h-1 w-1 shrink-0 rounded-full bg-current opacity-50" aria-hidden />}
+ <span className="truncate font-mono">{tool.name}</span>
+ </li>)}
+ </ul> : null}
+ {task.error ? <p className="ml-[38px] line-clamp-2 break-words pb-2 pr-3 text-xs leading-5 text-destructive">{task.error}</p>
+ : task.state === "done" && task.result ? <div className="ml-[38px] min-w-0 pb-2 pr-3">
+ <MarkdownText className="text-muted-foreground [--text-reading-size:0.75rem]">{task.result}</MarkdownText>
+ </div> : null}
+ </li>)}
+ </ol>
+ {context.stopError ? <p role="alert" className="px-3 pt-2 text-xs text-destructive">{context.stopError}</p> : null}
+ </div>;
+}
diff --git a/webui/src/components/thread/SubagentTaskResults.tsx b/webui/src/components/thread/SubagentTaskResults.tsx
new file mode 100644
index 000000000..6857868fe
--- /dev/null
+++ b/webui/src/components/thread/SubagentTaskResults.tsx
@@ -0,0 +1,119 @@
+import { useId, useMemo, useState, type ComponentProps } from "react";
+import { ChevronRight } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { SubagentTaskButton, useSubagentTasks } from "@/components/thread/SubagentTasks";
+import { ThreadMessages } from "@/components/thread/ThreadMessages";
+import { isActiveSubagentTask, type ObservedSubagentTask } from "@/lib/subagent-tasks";
+import type { UIMessage } from "@/lib/types";
+
+export function useHasSubagentResults(): boolean {
+ const context = useSubagentTasks();
+ return context?.tasks.some((task) => !isActiveSubagentTask(task)) ?? false;
+}
+
+/** Exact initiating prompts win; replayed IDs fall back to the turn's first user message. */
+function groupResults(messages: UIMessage[], tasks: ObservedSubagentTask[]) {
+ const promptsById = new Map<string, UIMessage>();
+ const firstPromptByTurn = new Map<string, UIMessage>();
+ for (const message of messages) {
+ if (message.role !== "user") continue;
+ promptsById.set(message.id, message);
+ if (message.turnId && !firstPromptByTurn.has(message.turnId)) {
+ firstPromptByTurn.set(message.turnId, message);
+ }
+ }
+
+ const byMessage = new Map<string, ObservedSubagentTask[]>();
+ const unlinked: ObservedSubagentTask[] = [];
+ for (const task of tasks) {
+ if (isActiveSubagentTask(task)) continue;
+ const prompt = (task.origin_message_id ? promptsById.get(task.origin_message_id) : undefined)
+ ?? (task.origin_turn_id ? firstPromptByTurn.get(task.origin_turn_id) : undefined);
+ if (!prompt) {
+ unlinked.push(task);
+ continue;
+ }
+ const group = byMessage.get(prompt.id) ?? [];
+ group.push(task);
+ byMessage.set(prompt.id, group);
+ }
+ return { byMessage, unlinked };
+}
+
+export function SubagentThreadMessages(props: ComponentProps<typeof ThreadMessages>) {
+ const context = useSubagentTasks();
+ return <ResultsThreadMessages key={context?.sessionKey} {...props} tasks={context?.tasks ?? []} />;
+}
+
+function ResultsThreadMessages({ tasks, ...props }: ComponentProps<typeof ThreadMessages> & { tasks: ObservedSubagentTask[] }) {
+ const groups = useMemo(() => groupResults(props.messages, tasks), [props.messages, tasks]);
+ const [expandedTaskIds, setExpandedTaskIds] = useState<Set<string>>(() => new Set());
+ const expanded = (results: ObservedSubagentTask[]) => results.some(task => expandedTaskIds.has(task.task_id));
+ const toggle = (results: ObservedSubagentTask[]) => {
+ props.onActivityToggle?.();
+ setExpandedTaskIds(current => {
+ const next = new Set(current);
+ const close = results.some(task => current.has(task.task_id));
+ for (const task of results) {
+ if (close) next.delete(task.task_id);
+ else next.add(task.task_id);
+ }
+ return next;
+ });
+ };
+
+ return <ThreadMessages {...props}
+ beforeMessages={groups.unlinked.length ? <>
+ {props.beforeMessages}
+ <SubagentResults tasks={groups.unlinked} unlinked expanded={expanded(groups.unlinked)}
+ onToggle={() => toggle(groups.unlinked)} />
+ </> : props.beforeMessages}
+ afterUserMessage={(message) => {
+ const results = groups.byMessage.get(message.id);
+ return <>
+ {props.afterUserMessage?.(message)}
+ {results ? <SubagentResults tasks={results} expanded={expanded(results)}
+ onToggle={() => toggle(results)} /> : null}
+ </>;
+ }} />;
+}
+
+function SubagentResults({ tasks, unlinked = false, expanded, onToggle }: {
+ tasks: ObservedSubagentTask[];
+ unlinked?: boolean;
+ expanded: boolean;
+ onToggle: () => void;
+}) {
+ const { t } = useTranslation("common");
+ const rowsId = useId();
+ const completed = tasks.filter((task) => task.state === "done").length;
+ const attention = tasks.filter((task) => task.state === "error" || task.state === "incomplete" || task.state === "interrupted").length;
+ const title = t(unlinked ? "thread.subagents.otherWorkTitle" : "thread.subagents.workTitle");
+ const summary = completed === tasks.length
+ ? t("thread.subagents.completed", { count: completed })
+ : t("thread.subagents.finished", { count: tasks.length });
+
+ return <section data-subagent-results aria-label={title}
+ className={`thread-message-row mt-2 grid grid-cols-[1rem_minmax(0,1fr)_minmax(6rem,max-content)_3rem] items-center gap-x-2.5 ${unlinked ? "mb-5" : ""}`}>
+ <button type="button" data-thread-disclosure data-subagent-results-summary aria-expanded={expanded} aria-controls={rowsId}
+ onClick={onToggle}
+ className="col-span-full grid min-h-11 w-full min-w-0 grid-cols-subgrid items-center gap-y-0.5 rounded-control py-2 text-left text-[13px] leading-5 text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none sm:min-h-9 sm:py-1.5">
+ <img src="/brand/nanobot_mark.svg" alt="" draggable={false} className="h-3.5 w-3.5 shrink-0" />
+ <span className="min-w-0 truncate font-medium">{title}</span>
+ <span className="col-start-3 row-start-1 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-0.5 text-xs leading-4">
+ <span>{summary}</span>
+ {attention ? <span className="text-destructive">{t("thread.subagents.needsReview", { count: attention })}</span> : null}
+ </span>
+ <ChevronRight className={`col-start-4 row-start-1 h-3.5 w-3.5 shrink-0 justify-self-end transition-transform motion-reduce:transition-none ${expanded ? "rotate-90" : ""}`} aria-hidden />
+ </button>
+ <div id={rowsId} hidden={!expanded} className={`col-span-full grid-cols-subgrid pb-1 ${expanded ? "grid" : "hidden"}`}>
+ {unlinked ? <p className="col-span-full py-2 text-xs text-muted-foreground">{t("thread.subagents.unlinkedHelp")}</p> : null}
+ <ol className="col-span-full grid grid-cols-subgrid">
+ {tasks.map((task) => <li key={task.task_id} className="col-span-full grid min-w-0 grid-cols-subgrid">
+ <SubagentTaskButton task={task} surface="archive" />
+ </li>)}
+ </ol>
+ </div>
+ </section>;
+}
diff --git a/webui/src/components/thread/SubagentTasks.tsx b/webui/src/components/thread/SubagentTasks.tsx
index c01986bb7..dc4961b6e 100644
--- a/webui/src/components/thread/SubagentTasks.tsx
+++ b/webui/src/components/thread/SubagentTasks.tsx
@@ -1,45 +1,45 @@
import {
- DelegationIcon,
StopIcon,
QueuedTaskIcon,
- RunningTaskIcon,
StoppingTaskIcon,
- CompletedTaskIcon,
CancelledTaskIcon,
IncompleteTaskIcon,
InterruptedTaskIcon,
ErrorTaskIcon,
} from "@/components/icons/product-icons";
-import { createContext, useContext, useEffect, useId, useLayoutEffect, useRef, useState, type ComponentProps, type ReactNode } from "react";
-import { ChevronDown, ChevronRight } from "lucide-react";
+import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
+import { LoadingRing } from "@/components/ui/loading-ring";
+import { HoverHint } from "@/components/ui/hover-hint";
import { SubagentThread } from "@/components/thread/SubagentThread";
-import { ThreadMessages } from "@/components/thread/ThreadMessages";
+import { ComposerActionIcon } from "@/components/thread/ComposerActionIcon";
import { Sheet, SheetContent, SheetDescription, SheetTitle } from "@/components/ui/sheet";
import { usePageVisibility } from "@/hooks/usePageVisibility";
-import { useLocalPreferences } from "@/hooks/useLocalPreferences";
import { useThreadVisibility } from "@/hooks/useThreadVisibility";
import { cancelSubagentTask, fetchSubagentTasks } from "@/lib/api";
import type { NanobotClient } from "@/lib/nanobot-client";
-import { isSubagentTask, mergeSubagentTasks, type ObservedSubagentTask } from "@/lib/subagent-tasks";
-import type { SubagentTaskSnapshot, UIMessage } from "@/lib/types";
-
-function isActive(task: SubagentTaskSnapshot): boolean {
- return task.state === "queued" || task.state === "running" || task.state === "stopping";
-}
+import { isActiveSubagentTask, isSubagentTask, mergeSubagentTasks, type ObservedSubagentTask } from "@/lib/subagent-tasks";
+import type { SubagentTaskSnapshot } from "@/lib/types";
interface TaskContext {
+ sessionKey: string | null;
+ available: boolean;
+ detailOpen: boolean;
tasks: ObservedSubagentTask[];
stopError: string | null;
stoppingId: string | null;
open: (task: SubagentTaskSnapshot, trigger: HTMLButtonElement) => void;
stop: (task: SubagentTaskSnapshot) => Promise<void>;
- register: (id: string, button: HTMLButtonElement | null, previous: HTMLButtonElement | null) => void;
+ register: (key: string, button: HTMLButtonElement | null, previous: HTMLButtonElement | null) => void;
}
const TasksContext = createContext<TaskContext | null>(null);
+export function useSubagentTasks() {
+ return useContext(TasksContext);
+}
+
interface SubagentTasksProviderProps {
client: Pick<NanobotClient, "requestMutation" | "onChat" | "onStatus">;
sessionKey: string | null;
@@ -61,8 +61,8 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
const [stopError, setStopError] = useState<string | null>(null);
const scopeGeneration = useRef(0);
const mounted = useRef(true);
- const buttons = useRef(new Map<string, HTMLButtonElement>());
const trigger = useRef<HTMLButtonElement | null>(null);
+ const buttons = useRef(new Map<string, HTMLButtonElement>());
const detailPanel = useRef<HTMLDivElement | null>(null);
useLayoutEffect(() => {
@@ -141,13 +141,15 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
}
};
const selected = enabled && active && paneVisible ? tasks.find((task) => task.task_id === selectedId) : undefined;
+ const canStopSelected = selected?.state === "queued" || selected?.state === "running";
const value: TaskContext = {
+ sessionKey, available: enabled && active && paneVisible, detailOpen: !!selected,
tasks: enabled ? tasks : [],
stopError: enabled ? stopError : null, stoppingId,
open: (task, target) => { trigger.current = target; setSelectedId(task.task_id); }, stop,
- register: (id, button, previous) => {
- if (button) buttons.current.set(id, button);
- else if (buttons.current.get(id) === previous) buttons.current.delete(id);
+ register: (key, button, previous) => {
+ if (button) buttons.current.set(key, button);
+ else if (buttons.current.get(key) === previous) buttons.current.delete(key);
},
};
@@ -157,7 +159,7 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
<SheetContent ref={detailPanel} tabIndex={-1}
className="w-full gap-0 overflow-hidden border-l p-0 outline-none sm:w-[min(32rem,calc(100vw-1rem))] sm:max-w-none"
overlayClassName="bg-black/20 backdrop-blur-[8px]"
- closeButtonClassName="right-3 top-3 grid h-9 w-9 place-items-center rounded-full"
+ closeButtonClassName="right-2 top-2 grid h-11 w-11 place-items-center rounded-full sm:right-3 sm:top-3 sm:h-9 sm:w-9"
onOpenAutoFocus={(event) => {
event.preventDefault();
detailPanel.current?.focus({ preventScroll: true });
@@ -166,26 +168,36 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
event.preventDefault();
if (!active || !paneVisible) return;
const target = trigger.current?.isConnected ? trigger.current
- : buttons.current.get(trigger.current?.dataset.subagentId ?? "");
+ : buttons.current.get(`${trigger.current?.dataset.subagentSurface}:${trigger.current?.dataset.subagentId}`);
const focusTarget = target?.closest("[hidden]")
- ? target.closest("[data-subagent-work]")?.querySelector<HTMLButtonElement>("[aria-expanded]") : target;
+ ? target.closest("[data-subagent-results]")?.querySelector<HTMLButtonElement>("[aria-expanded]") : target;
focusTarget?.focus({ preventScroll: true });
}}>
- <div className="shrink-0 space-y-2 border-b px-5 py-5 pr-14">
- <SheetTitle className="break-words text-base">{selected?.label}</SheetTitle>
- <SheetDescription className="flex items-center gap-2">
- {selected ? <><TaskStateIcon task={selected} />
- <span className={selected.state === "done" ? "sr-only" : undefined}>{t(`thread.subagents.states.${selected.state}`)}</span>
- <span className="tabular-nums"><TaskElapsed task={selected} /></span></> : null}
+ <div className="flex min-h-[60px] shrink-0 items-center gap-3 border-b py-2 pl-5 pr-14">
+ <SheetTitle className="min-w-0 flex-1 truncate text-base" title={selected?.label}>{selected?.label}</SheetTitle>
+ <SheetDescription className={selected?.state === "done" || selected?.state === "running" ? "sr-only" : "flex shrink-0 items-center gap-2 whitespace-nowrap"}>
+ {selected ? <>
+ {selected.state !== "done" && selected.state !== "running" ? <TaskStateIcon task={selected} /> : null}
+ <span>{t(`thread.subagents.states.${selected.state}`)}</span>
+ </> : null}
</SheetDescription>
+ {selected && canStopSelected ? <HoverHint content={t("thread.subagents.stopTask", { label: selected.label })}>
+ <Button type="button" size="icon"
+ className="composer-primary-action touch-target h-11 w-11 shrink-0 rounded-full border border-transparent bg-foreground/[0.045] bg-clip-padding text-foreground/85 hover:bg-foreground/[0.08] hover:text-foreground disabled:text-muted-foreground/50 sm:h-9 sm:w-9"
+ aria-label={t("thread.subagents.stopTask", { label: selected.label })} aria-busy={stoppingId === selected.task_id}
+ disabled={stoppingId !== null} onClick={() => void stop(selected)}>
+ {selected.state === "running" ? <ComposerActionIcon state="stop" /> : <StopIcon className="h-3.5 w-3.5" aria-hidden />}
+ </Button>
+ </HoverHint> : null}
</div>
+ {canStopSelected && stopError ? <p role="alert" className="px-5 pt-3 text-xs text-destructive">{stopError}</p> : null}
{selected && sessionKey ? <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain py-5">
{selected.state === "interrupted" || selected.error ? <div className="space-y-2 px-5 pb-4 text-sm">
{selected.state === "interrupted" ? <p className="text-muted-foreground">{t("thread.subagents.interruptedHelp")}</p> : null}
{selected.error ? <p role="alert" className="whitespace-pre-wrap break-words text-destructive">{selected.error}</p> : null}
</div> : null}
<SubagentThread key={`${sessionKey}:${selected.task_id}`} token={token} sessionKey={sessionKey}
- task={selected} historyEnabled={historyEnabled} isStreaming={isActive(selected)} />
+ task={selected} historyEnabled={historyEnabled} isStreaming={isActiveSubagentTask(selected)} />
{Object.keys(selected.receipts).length ? <details className="mt-5 space-y-2 px-5 text-xs text-muted-foreground">
<summary className="cursor-pointer py-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">{t("thread.subagents.messages")}</summary>
<p>{t("thread.subagents.receiptHelp")}</p>
@@ -195,11 +207,6 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
})}
</details> : null}
</div> : null}
- {selected && (selected.state === "queued" || selected.state === "running") ? <div className="shrink-0 border-t px-5 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
- <Button type="button" variant="outline" size="sm" disabled={stoppingId !== null}
- onClick={() => void stop(selected)}><StopIcon className="mr-2 h-3 w-3" aria-hidden />{t("thread.subagents.stopTask", { label: selected.label })}</Button>
- {stopError ? <p role="alert" className="mt-2 text-xs text-destructive">{stopError}</p> : null}
- </div> : null}
</SheetContent>
</Sheet>
</TasksContext.Provider>;
@@ -207,21 +214,22 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
function TaskStateIcon({ task }: { task: SubagentTaskSnapshot }) {
const className = "h-3.5 w-3.5 shrink-0";
+ if (task.state === "running") return <LoadingRing className={`${className} text-muted-foreground`} />;
+ if (task.state === "done") return <span className={`${className} block`} aria-hidden />;
const Icon = {
- queued: QueuedTaskIcon, running: RunningTaskIcon, stopping: StoppingTaskIcon,
- done: CompletedTaskIcon, cancelled: CancelledTaskIcon, incomplete: IncompleteTaskIcon,
+ queued: QueuedTaskIcon, stopping: StoppingTaskIcon,
+ cancelled: CancelledTaskIcon, incomplete: IncompleteTaskIcon,
interrupted: InterruptedTaskIcon, error: ErrorTaskIcon,
}[task.state];
- const tone = task.state === "done" ? "text-emerald-600 dark:text-emerald-400"
- : task.state === "error" || task.state === "incomplete" ? "text-destructive" : "text-muted-foreground";
- return <Icon className={`${className} ${tone} ${task.state === "running" ? "animate-spin motion-reduce:animate-none" : ""}`} aria-hidden />;
+ const tone = task.state === "error" || task.state === "incomplete" ? "text-destructive" : "text-muted-foreground";
+ return <Icon key={task.state} className={`${className} ${tone} animate-in fade-in-0 duration-200 motion-reduce:animate-none`} aria-hidden />;
}
function TaskElapsed({ task }: { task: ObservedSubagentTask }) {
const pageVisible = usePageVisibility();
const paneVisible = useThreadVisibility();
const [now, setNow] = useState(() => performance.now());
- const running = isActive(task);
+ const running = isActiveSubagentTask(task);
useEffect(() => {
if (!running || !pageVisible || !paneVisible) return;
setNow(performance.now());
@@ -231,102 +239,23 @@ function TaskElapsed({ task }: { task: ObservedSubagentTask }) {
return <>{Math.round(task.elapsed_seconds + (running ? Math.max(0, now - task.observedAtMs) / 1000 : 0))}s</>;
}
-function TaskButton({ task }: { task: ObservedSubagentTask }) {
+export function SubagentTaskButton({ task, surface = "archive" }: { task: ObservedSubagentTask; surface?: "activity" | "archive" }) {
const context = useContext(TasksContext);
const { t } = useTranslation("common");
const button = useRef<HTMLButtonElement | null>(null);
- return <button type="button" data-subagent-id={task.task_id} ref={(node) => {
- context?.register(task.task_id, node, button.current);
+ const activity = surface === "activity";
+ const completed = task.state === "done";
+ return <button type="button" data-subagent-id={task.task_id} data-subagent-surface={surface} ref={node => {
+ context?.register(`${surface}:${task.task_id}`, node, button.current);
button.current = node;
}}
onClick={(event) => context?.open(task, event.currentTarget)}
- className="flex min-w-0 flex-1 items-center gap-2.5 rounded-control px-3 py-2.5 text-left text-sm hover:bg-muted/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
- <TaskStateIcon task={task} />
- <span className="min-w-0 flex-1 truncate">{task.label}</span>
- <span className="shrink-0 text-xs text-muted-foreground">{t(`thread.subagents.states.${task.state}`)}</span>
- <span className="shrink-0 text-xs tabular-nums text-muted-foreground"><TaskElapsed task={task} /></span>
- <ChevronRight className="h-3 w-3 shrink-0 text-muted-foreground" aria-hidden />
+ className={activity
+ ? "grid min-h-11 min-w-0 flex-1 grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-2.5 gap-y-0.5 rounded-lg px-2 py-2 text-left text-[13px] leading-5 transition-colors duration-150 hover:bg-muted/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none sm:min-h-9 sm:grid-cols-[auto_minmax(0,1fr)_auto_auto] sm:py-1.5"
+ : "col-span-full grid min-h-11 min-w-0 grid-cols-subgrid items-center gap-y-0.5 rounded-control py-2 text-left text-[13px] leading-5 hover:bg-muted/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring sm:min-h-9 sm:py-1.5"}>
+ <span className="col-start-1 row-start-1 self-center"><TaskStateIcon task={task} /></span>
+ <span className={`col-start-2 row-start-1 min-w-0 line-clamp-2 break-words font-medium sm:line-clamp-none sm:truncate ${activity ? "" : "col-span-2 sm:col-span-1"}`}>{task.label}</span>
+ <span className={completed ? "sr-only" : `col-start-2 row-start-2 text-xs leading-4 text-muted-foreground sm:col-start-3 sm:row-start-1 ${activity ? "" : "col-span-2 sm:col-span-1"}`}>{t(`thread.subagents.states.${task.state}`)}</span>
+ <span className={`${activity ? "col-start-3 sm:col-start-4" : "col-start-4"} text-right text-xs tabular-nums text-muted-foreground sm:row-start-1 sm:min-w-[5ch] ${completed ? "row-start-1" : "row-start-2"}`}><TaskElapsed task={task} /></span>
</button>;
}
-
-export function useHasSubagentContent(): boolean {
- const context = useContext(TasksContext);
- return !!context && (context.tasks.length > 0 || !!context.stopError);
-}
-
-/** Prefer an exact prompt, then its turn's first prompt when replay changed message IDs. */
-function useSubagentTaskGroups(messages: UIMessage[]) {
- const context = useContext(TasksContext);
- const prompts = messages.filter((message) => message.role === "user");
- const byMessage = new Map<string, ObservedSubagentTask[]>();
- const unlinked: ObservedSubagentTask[] = [];
- for (const task of context?.tasks ?? []) {
- const prompt = prompts.find((message) => message.id === task.origin_message_id)
- ?? prompts.find((message) => !!task.origin_turn_id && message.turnId === task.origin_turn_id);
- if (prompt) {
- const group = byMessage.get(prompt.id) ?? [];
- group.push(task);
- byMessage.set(prompt.id, group);
- } else unlinked.push(task);
- }
- return { byMessage, unlinked };
-}
-
-export function SubagentThreadMessages(props: ComponentProps<typeof ThreadMessages>) {
- const groups = useSubagentTaskGroups(props.messages);
- return <ThreadMessages {...props}
- beforeMessages={<SubagentWork tasks={groups.unlinked} unlinked />}
- afterUserMessage={(message) => <SubagentWork tasks={groups.byMessage.get(message.id) ?? []} />}
- afterMessages={<SubagentStopError />} />;
-}
-
-function SubagentWork({ tasks, unlinked = false }: { tasks: ObservedSubagentTask[]; unlinked?: boolean }) {
- const context = useContext(TasksContext);
- const { t } = useTranslation("common");
- const { activityMode } = useLocalPreferences();
- const rowsId = useId();
- const [expanded, setExpanded] = useState<boolean | null>(null);
- useEffect(() => { setExpanded(null); }, [activityMode]);
- if (!context || !tasks.length) return null;
- const activeCount = tasks.filter(isActive).length;
- const completedCount = tasks.filter((task) => task.state === "done").length;
- const failedCount = tasks.filter((task) => ["error", "incomplete", "interrupted"].includes(task.state)).length;
- const open = expanded ?? (activityMode === "expanded" || activeCount > 0);
- const summary = activeCount
- ? t("thread.subagents.progress", { completed: completedCount, total: tasks.length })
- : t("thread.subagents.finished", { count: tasks.length });
- const title = t(unlinked ? "thread.subagents.otherWorkTitle" : "thread.subagents.workTitle");
- return <section data-subagent-work aria-label={title} className={`thread-message-row mt-3 ${unlinked ? "mb-5" : ""}`}>
- <div className="overflow-hidden rounded-control border border-border/60 bg-muted/15">
- <button type="button" aria-expanded={open} aria-controls={rowsId}
- onClick={() => setExpanded(!open)}
- className="flex w-full items-center gap-2.5 px-3 py-2.5 text-left text-xs text-muted-foreground hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring">
- <DelegationIcon className="h-3.5 w-3.5 shrink-0" aria-hidden />
- <span className="font-medium">{title}</span>
- <span className="ml-auto flex min-w-0 flex-wrap justify-end gap-x-2 text-right">
- <span>{summary}</span>{" "}
- {activeCount ? <span>{t("thread.subagents.running", { count: activeCount })}</span> : null}
- {failedCount ? <span className="text-destructive">{t("thread.subagents.needsReview", { count: failedCount })}</span> : null}
- </span>
- <ChevronDown className={`h-3.5 w-3.5 shrink-0 transition-transform ${open ? "rotate-180" : ""}`} aria-hidden />
- </button>
- <div id={rowsId} hidden={!open} className="border-t border-border/50 py-0.5">
- {unlinked ? <p className="px-3 py-2 text-xs text-muted-foreground">{t("thread.subagents.unlinkedHelp")}</p> : null}
- {tasks.map((task) => <div key={task.task_id} className="flex items-center gap-1 pr-1">
- <TaskButton task={task} />
- {task.state === "queued" || task.state === "running" ? <Button type="button" variant="ghost" size="icon" className="h-9 w-9 shrink-0"
- aria-label={t("thread.subagents.stopTask", { label: task.label })} disabled={context.stoppingId !== null}
- onClick={() => void context.stop(task)}><StopIcon className="h-3 w-3" aria-hidden /></Button> : null}
- </div>)}
- </div>
- </div>
- </section>;
-}
-
-function SubagentStopError() {
- const context = useContext(TasksContext);
- if (!context?.stopError) return null;
- return <div className="thread-message-row mt-2 space-y-1 text-xs text-destructive">
- <p role="alert">{context.stopError}</p>
- </div>;
-}
diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx
index 73273693e..955ee0f74 100644
--- a/webui/src/components/thread/ThreadShell.tsx
+++ b/webui/src/components/thread/ThreadShell.tsx
@@ -14,6 +14,8 @@ import { usePromptHistory } from "@/hooks/usePromptHistory";
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
import { RecoveryNotice } from "@/components/thread/RecoveryNotice";
import { SubagentTasksProvider } from "@/components/thread/SubagentTasks";
+import { SubagentTaskDock } from "@/components/thread/SubagentTaskDock";
+import { latestSubagentInputKey } from "@/lib/subagent-tasks";
import { SessionInfoPopover } from "@/components/thread/SessionInfoPopover";
import type { ComposerDraft, ComposerDraftStore } from "@/lib/composer-draft";
import { ThreadComposer } from "@/components/thread/ThreadComposer";
@@ -1304,6 +1306,7 @@ export function ThreadShell({
{restoredFirstDraft?.chatId === chatId && restoredFirstDraft.error ? (
<p role="alert" className="px-3 text-sm text-destructive">{restoredFirstDraft.error}</p>
) : null}
+ <SubagentTaskDock inputKey={latestSubagentInputKey(displayMessages)} />
{session ? (
<ThreadComposer
key={`${draftKey}:${restoredFirstDraft?.chatId === chatId ? restoredFirstDraft.revision : 0}`}
diff --git a/webui/src/components/thread/ThreadViewport.tsx b/webui/src/components/thread/ThreadViewport.tsx
index 3c6179bed..12aadf0b4 100644
--- a/webui/src/components/thread/ThreadViewport.tsx
+++ b/webui/src/components/thread/ThreadViewport.tsx
@@ -13,7 +13,7 @@ import { ArrowDown } from "lucide-react";
import { useTranslation } from "react-i18next";
import { PromptRail } from "@/components/thread/PromptRail";
-import { SubagentThreadMessages, useHasSubagentContent } from "@/components/thread/SubagentTasks";
+import { SubagentThreadMessages, useHasSubagentResults } from "@/components/thread/SubagentTaskResults";
import { DiagramScope } from "@/components/markdown-diagrams/context";
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
import { isAgentActivityMember } from "@/components/thread/AgentActivityCluster";
@@ -403,8 +403,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
onAutoFollow: () => setAtBottom(true),
});
}
- const hasTaskContent = useHasSubagentContent();
- const hasMessages = messages.length > 0 || (hasTaskContent && conversationReady);
+ const hasTaskResults = useHasSubagentResults();
+ const hasMessages = messages.length > 0 || (hasTaskResults && conversationReady);
const hasThreadLayout = hasMessages || initialLoading;
useLayoutEffect(() => {
scrollRef.current = hasMessages
diff --git a/webui/src/components/thread/useSubagentActivity.ts b/webui/src/components/thread/useSubagentActivity.ts
new file mode 100644
index 000000000..6a5f27fb0
--- /dev/null
+++ b/webui/src/components/thread/useSubagentActivity.ts
@@ -0,0 +1,52 @@
+import { useEffect, useState } from "react";
+import { isActiveSubagentTask, type ObservedSubagentTask } from "@/lib/subagent-tasks";
+
+export const SUBAGENT_COMPLETION_FEEDBACK_MS = 4000;
+
+interface ActivityView {
+ observed: ObservedSubagentTask[];
+ inputKey: string | null;
+ cycleIds: string[];
+ retainedIds: string[];
+ open: boolean;
+}
+
+export function useSubagentActivity(tasks: ObservedSubagentTask[], inputKey: string | null, interacting: boolean) {
+ const [view, setView] = useState<ActivityView>(() => ({
+ observed: tasks, inputKey, cycleIds: tasks.filter(isActiveSubagentTask).map(task => task.task_id), retainedIds: [], open: false,
+ }));
+ const activeTasks = tasks.filter(isActiveSubagentTask);
+ const activeIds = activeTasks.map(task => task.task_id);
+ if (view.observed !== tasks || view.inputKey !== inputKey) {
+ const startsWork = activeIds.length > 0 && !view.observed.some(isActiveSubagentTask);
+ setView({
+ ...view, observed: tasks, inputKey,
+ cycleIds: startsWork || view.inputKey !== inputKey ? activeIds : [...new Set([...view.cycleIds, ...activeIds])],
+ retainedIds: view.open ? [...new Set([...view.retainedIds, ...activeIds])] : [],
+ });
+ }
+ const receiptKey = view.cycleIds.join("\0");
+ const hasActive = activeIds.length > 0;
+ useEffect(() => {
+ if (hasActive || view.open || interacting || !receiptKey) return;
+ const timer = window.setTimeout(() => setView(current => current.open || current.observed.some(isActiveSubagentTask)
+ ? current : { ...current, cycleIds: [] }), SUBAGENT_COMPLETION_FEEDBACK_MS);
+ return () => window.clearTimeout(timer);
+ }, [hasActive, view.open, interacting, receiptKey]);
+
+ const visibleIds = view.open ? view.retainedIds : hasActive ? activeIds : view.cycleIds;
+ const byId = new Map(tasks.map(task => [task.task_id, task]));
+ return {
+ open: view.open,
+ tasks: visibleIds.map(id => byId.get(id)!),
+ setOpen: (open: boolean, { preserveFeedback = false }: { preserveFeedback?: boolean } = {}) => setView(current => {
+ const currentActive = current.observed.filter(isActiveSubagentTask).map(task => task.task_id);
+ return {
+ ...current, open,
+ // Cancelling a partial drag is not a dismissal of the completion receipt.
+ cycleIds: open || preserveFeedback ? current.cycleIds : currentActive,
+ retainedIds: open ? currentActive.length ? currentActive : current.cycleIds : [],
+ };
+ }),
+ };
+}
diff --git a/webui/src/globals.css b/webui/src/globals.css
index 375a14857..80dad3ce0 100644
--- a/webui/src/globals.css
+++ b/webui/src/globals.css
@@ -9,6 +9,18 @@
.thread-composer-stack.is-hero {
--composer-content-width: 58rem;
}
+.subagent-task-dock {
+ --subagent-handle-inset: var(--radius-panel);
+ width: calc(100% - 0.5rem - 2 * var(--subagent-handle-inset));
+ max-width: calc(var(--composer-content-width, 49.5rem) - 2 * var(--subagent-handle-inset));
+}
+.thread-composer-stack.is-hero .subagent-task-dock {
+ --subagent-handle-inset: var(--radius-prominent);
+ width: calc(100% - 2 * var(--subagent-handle-inset));
+}
+.subagent-task-dock + .thread-composer-form {
+ padding-top: 0;
+}
.thread-composer-notice {
width: calc(100% - 0.5rem);
max-width: var(--composer-content-width, 49.5rem);
@@ -21,6 +33,9 @@
.thread-composer-notice {
width: 100%;
}
+ .subagent-task-dock {
+ width: calc(100% - 2 * var(--subagent-handle-inset));
+ }
}
@supports (content-visibility: auto) {
diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json
index 07fa8eb6d..5b5055589 100644
--- a/webui/src/i18n/locales/en/common.json
+++ b/webui/src/i18n/locales/en/common.json
@@ -2014,6 +2014,7 @@
"progress": "{{completed}} of {{total}} completed",
"running": "Running: {{count}}",
"finished": "Finished: {{count}}",
+ "completed": "Completed: {{count}}",
"needsReview": "Review needed: {{count}}",
"messages": "Message status"
},
diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json
index a3fdd0702..391735db3 100644
--- a/webui/src/i18n/locales/es/common.json
+++ b/webui/src/i18n/locales/es/common.json
@@ -1809,6 +1809,7 @@
"progress": "{{completed}} de {{total}} completadas",
"running": "En curso: {{count}}",
"finished": "Finalizadas: {{count}}",
+ "completed": "Completadas: {{count}}",
"needsReview": "Revisar: {{count}}",
"messages": "Estado de mensajes"
},
diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json
index 7082b5948..11a29235b 100644
--- a/webui/src/i18n/locales/fr/common.json
+++ b/webui/src/i18n/locales/fr/common.json
@@ -1808,6 +1808,7 @@
"progress": "{{completed}} sur {{total}} terminées",
"running": "En cours : {{count}}",
"finished": "Terminées : {{count}}",
+ "completed": "Réussies : {{count}}",
"needsReview": "À vérifier : {{count}}",
"messages": "État des messages"
},
diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json
index 2d0fa2dde..a7577fa60 100644
--- a/webui/src/i18n/locales/id/common.json
+++ b/webui/src/i18n/locales/id/common.json
@@ -1808,6 +1808,7 @@
"progress": "{{completed}} dari {{total}} selesai",
"running": "Berjalan: {{count}}",
"finished": "Berakhir: {{count}}",
+ "completed": "Selesai: {{count}}",
"needsReview": "Perlu diperiksa: {{count}}",
"messages": "Status pesan"
},
diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json
index d149d1213..43f79d819 100644
--- a/webui/src/i18n/locales/ja/common.json
+++ b/webui/src/i18n/locales/ja/common.json
@@ -1808,6 +1808,7 @@
"progress": "{{total}} 件中 {{completed}} 件完了",
"running": "実行中: {{count}}",
"finished": "終了: {{count}}",
+ "completed": "完了: {{count}}",
"needsReview": "要確認: {{count}}",
"messages": "メッセージの状態"
},
diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json
index b2973141c..970f9dd39 100644
--- a/webui/src/i18n/locales/ko/common.json
+++ b/webui/src/i18n/locales/ko/common.json
@@ -1808,6 +1808,7 @@
"progress": "{{total}}개 중 {{completed}}개 완료",
"running": "진행 중: {{count}}",
"finished": "종료: {{count}}",
+ "completed": "완료: {{count}}",
"needsReview": "확인 필요: {{count}}",
"messages": "메시지 상태"
},
diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json
index dbb229d9d..239fe98d5 100644
--- a/webui/src/i18n/locales/pt-BR/common.json
+++ b/webui/src/i18n/locales/pt-BR/common.json
@@ -1822,6 +1822,7 @@
"progress": "{{completed}} de {{total}} concluídas",
"running": "Em andamento: {{count}}",
"finished": "Encerradas: {{count}}",
+ "completed": "Concluídas: {{count}}",
"needsReview": "Revisar: {{count}}",
"messages": "Status das mensagens"
},
diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json
index 76f75e62d..1f3bcbb4b 100644
--- a/webui/src/i18n/locales/vi/common.json
+++ b/webui/src/i18n/locales/vi/common.json
@@ -1808,6 +1808,7 @@
"progress": "Hoàn thành {{completed}} / {{total}}",
"running": "Đang chạy: {{count}}",
"finished": "Đã kết thúc: {{count}}",
+ "completed": "Đã hoàn thành: {{count}}",
"needsReview": "Cần kiểm tra: {{count}}",
"messages": "Trạng thái tin nhắn"
},
diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json
index af21bd6f8..c013b2fe0 100644
--- a/webui/src/i18n/locales/zh-CN/common.json
+++ b/webui/src/i18n/locales/zh-CN/common.json
@@ -2014,6 +2014,7 @@
"progress": "已完成 {{completed}} / {{total}} 项",
"running": "{{count}} 项进行中",
"finished": "{{count}} 项已结束",
+ "completed": "{{count}} 项已完成",
"needsReview": "{{count}} 项需检查",
"messages": "消息状态"
},
diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json
index 3b0078007..ae9df5155 100644
--- a/webui/src/i18n/locales/zh-TW/common.json
+++ b/webui/src/i18n/locales/zh-TW/common.json
@@ -1808,6 +1808,7 @@
"progress": "已完成 {{completed}} / {{total}} 項",
"running": "{{count}} 項進行中",
"finished": "{{count}} 項已結束",
+ "completed": "{{count}} 項已完成",
"needsReview": "{{count}} 項需檢查",
"messages": "訊息狀態"
},
diff --git a/webui/src/lib/subagent-tasks.ts b/webui/src/lib/subagent-tasks.ts
index deca459ea..da7c40d6f 100644
--- a/webui/src/lib/subagent-tasks.ts
+++ b/webui/src/lib/subagent-tasks.ts
@@ -1,9 +1,23 @@
-import type { SubagentTaskSnapshot } from "./types";
+import type { SubagentTaskSnapshot, UIMessage } from "./types";
export interface ObservedSubagentTask extends SubagentTaskSnapshot {
observedAtMs: number;
}
+export function isActiveSubagentTask(task: SubagentTaskSnapshot): boolean {
+ return task.state === "queued" || task.state === "running" || task.state === "stopping";
+}
+
+export function latestSubagentInputKey(messages: readonly UIMessage[]): string | null {
+ for (let index = messages.length - 1; index >= 0; index--) {
+ const message = messages[index];
+ if (message.role === "user" && !message.sessionMessage) {
+ return message.turnId ? `user:${message.turnId}` : `replay:${message.id}`;
+ }
+ }
+ return null;
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx
index 9d5bc43d5..36631fb49 100644
--- a/webui/src/tests/app-layout.test.tsx
+++ b/webui/src/tests/app-layout.test.tsx
@@ -427,8 +427,12 @@ describe("App layout", () => {
// capability contract exercised by the timed DOM assertions below.
await act(async () => { await import("@/components/thread/ThreadShell"); });
await screen.findByRole("textbox", {}, { timeout: 5_000 });
- if (supported) await screen.findByRole("button", { name: /Config check Running/ });
- else expect(screen.queryByText("Config check")).not.toBeInTheDocument();
+ if (supported) {
+ const trigger = await screen.findByRole("button", { name: "Subtasks · Running: 1" });
+ expect(trigger).toHaveAttribute("aria-expanded", "false");
+ await userEvent.setup().click(trigger);
+ expect(await screen.findByRole("button", { name: /Config check Running/ })).toBeVisible();
+ } else expect(screen.queryByRole("button", { name: /Subtasks/ })).not.toBeInTheDocument();
const reads = vi.mocked(fetch).mock.calls.filter(([url]) => String(url).endsWith("/subagents"));
expect(reads).toHaveLength(supported ? 1 : 0);
expect(requestMutationSpy).not.toHaveBeenCalled();
diff --git a/webui/src/tests/subagent-results.test.tsx b/webui/src/tests/subagent-results.test.tsx
new file mode 100644
index 000000000..8ab6cb30c
--- /dev/null
+++ b/webui/src/tests/subagent-results.test.tsx
@@ -0,0 +1,292 @@
+import { act, cleanup, render, screen, waitFor, within } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { SubagentTaskDock } from "@/components/thread/SubagentTaskDock";
+import { SubagentThreadMessages, useHasSubagentResults } from "@/components/thread/SubagentTaskResults";
+import { SubagentTasksProvider } from "@/components/thread/SubagentTasks";
+import { setAppLanguage } from "@/i18n";
+import { DEFAULT_LOCAL_PREFS, LOCAL_PREFS_STORAGE_KEY, writeLocalPreferences } from "@/lib/local-preferences";
+import type { InboundEvent, SubagentTaskSnapshot, UIMessage } from "@/lib/types";
+
+const requestMutation = vi.fn();
+const chatHandlers = new Set<(event: InboundEvent) => void>();
+const client = {
+ requestMutation,
+ onChat: vi.fn((_chatId: string, handler: (event: InboundEvent) => void) => {
+ chatHandlers.add(handler);
+ return () => { chatHandlers.delete(handler); };
+ }),
+ onStatus: vi.fn(() => () => {}),
+};
+const messages: UIMessage[] = [
+ { id: "prompt-a", role: "user", content: "Inspect config", turnId: "turn-a", createdAt: 100_000 },
+ { id: "answer-a", role: "assistant", content: "Main answer", turnId: "turn-a", createdAt: 101_000 },
+];
+
+function task(overrides: Partial<SubagentTaskSnapshot> = {}): SubagentTaskSnapshot {
+ return {
+ task_id: "task-1", revision: 1, label: "Config check", task_description: "Check configuration values",
+ state: "done", phase: "finished", elapsed_seconds: 4, iteration: 1,
+ tool_events: [], usage: null, receipts: {}, result: null, partial: false,
+ stop_reason: null, error: null, origin_turn_id: "turn-a", origin_message_id: "prompt-a",
+ created_at: 100, completed_at: 104, ...overrides,
+ };
+}
+function response(tasks: SubagentTaskSnapshot[]): Response {
+ return new Response(JSON.stringify({ tasks }), { headers: { "content-type": "application/json" } });
+}
+function childThread(answer: string): Response {
+ return new Response(JSON.stringify({ schemaVersion: 3, projection: "events", active_turn_id: null, events: [
+ { event: "user_message", chat_id: "task-1", starts_turn: true, projection_id: "child-prompt", turn_id: "child-turn", text: "Inspect the saved child session", created_at_ms: 100_000 },
+ { event: "message", chat_id: "task-1", projection_id: "child-answer", turn_id: "child-turn", text: answer },
+ ] }), { headers: { "content-type": "application/json" } });
+}
+function emitTask(snapshot: SubagentTaskSnapshot) {
+ act(() => {
+ chatHandlers.forEach((handler) => handler({ event: "subagent_task", chat_id: "a", task: snapshot }));
+ });
+}
+function ResultsPresence() {
+ return <output data-testid="has-results">{useHasSubagentResults() ? "yes" : "no"}</output>;
+}
+function layout({ threadMessages = messages, liveEvents = true, historyEnabled = false, onActivityToggle }: {
+ threadMessages?: UIMessage[];
+ liveEvents?: boolean;
+ historyEnabled?: boolean;
+ onActivityToggle?: () => void;
+} = {}) {
+ return <SubagentTasksProvider client={client} sessionKey="websocket:a" token="tok" enabled liveEvents={liveEvents} historyEnabled={historyEnabled}>
+ <ResultsPresence />
+ <div data-testid="messages"><SubagentThreadMessages messages={threadMessages} onActivityToggle={onActivityToggle} /></div>
+ <div data-testid="composer" className="thread-composer-stack"><SubagentTaskDock /><textarea aria-label="Message" /></div>
+ </SubagentTasksProvider>;
+}
+function summary(region: HTMLElement) {
+ return within(region).getByRole("button", { name: /^(Subtasks|Other tasks) (Completed|Finished):/ });
+}
+function expectBefore(first: Node, second: Node) {
+ expect(first.compareDocumentPosition(second) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+}
+
+describe("subagent result archives", () => {
+ beforeEach(async () => {
+ localStorage.removeItem(LOCAL_PREFS_STORAGE_KEY);
+ await setAppLanguage("en");
+ requestMutation.mockReset();
+ client.onChat.mockClear();
+ client.onStatus.mockClear();
+ chatHandlers.clear();
+ vi.stubGlobal("fetch", vi.fn(async () => response([task()])));
+ });
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ localStorage.removeItem(LOCAL_PREFS_STORAGE_KEY);
+ });
+
+ it("keeps queued, running and stopping work out of chat until a terminal result arrives", async () => {
+ vi.mocked(fetch).mockImplementation(async () => response([
+ task({ state: "running", phase: "awaiting_model", completed_at: null }),
+ task({ task_id: "queued", label: "Waiting check", state: "queued", completed_at: null, created_at: 101 }),
+ task({ task_id: "stopping", label: "Stopping check", state: "stopping", completed_at: null,
+ origin_message_id: null, origin_turn_id: null, created_at: 102 }),
+ ]));
+ const user = userEvent.setup();
+ render(layout());
+ expect(await screen.findByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 3");
+ const transcript = screen.getByTestId("messages");
+ expect(transcript.querySelector("[data-subagent-results]")).toBeNull();
+ expect(screen.getByTestId("has-results")).toHaveTextContent("no");
+ expect(transcript).not.toHaveTextContent("Config check");
+ expect(transcript).not.toHaveTextContent("Waiting check");
+ expect(transcript).not.toHaveTextContent("Stopping check");
+
+ emitTask(task({ revision: 2, result: "Full findings stay in details" }));
+ const archive = screen.getByRole("region", { name: "Subtasks" });
+ expect(screen.getByTestId("has-results")).toHaveTextContent("yes");
+ expect(summary(archive)).toHaveTextContent("Completed: 1");
+ expect(summary(archive).querySelector("img")).toHaveAttribute("src", "/brand/nanobot_mark.svg");
+ expect(summary(archive).querySelector("img")).toHaveAttribute("alt", "");
+ expect(summary(archive)).toHaveAttribute("aria-expanded", "false");
+ await user.click(summary(archive));
+ expect(within(archive).getByRole("button", { name: "Config check Completed 4s" })).toBeVisible();
+ expect(within(archive).getAllByRole("listitem")).toHaveLength(1);
+ expect(transcript).not.toHaveTextContent("Waiting check");
+ expect(transcript).not.toHaveTextContent("Stopping check");
+ expect(transcript).not.toHaveTextContent("Full findings stay in details");
+ });
+
+ it("counts finished work truthfully and keeps cancellation distinct from failures", async () => {
+ vi.mocked(fetch).mockImplementation(async () => response([
+ task({ task_id: "cancelled", label: "Cancelled check", state: "cancelled", created_at: 102 }),
+ task({ task_id: "interrupted", label: "Interrupted check", state: "interrupted", created_at: 104 }),
+ task({ task_id: "incomplete", label: "Incomplete check", state: "incomplete", created_at: 103 }),
+ task({ task_id: "failed", label: "Failed check", state: "error", error: "Unreadable file", created_at: 101 }),
+ task(),
+ ]));
+ const user = userEvent.setup();
+ render(layout());
+ const archive = await screen.findByRole("region", { name: "Subtasks" });
+ const header = summary(archive);
+ expect(header).toHaveTextContent("Finished: 5");
+ expect(header).toHaveTextContent("Review needed: 3");
+ expect(header).not.toHaveTextContent("Completed: 5");
+ await user.click(header);
+ expect(within(archive).getByRole("button", { name: "Cancelled check Cancelled 4s" })).toBeVisible();
+ expect(within(archive).getByRole("button", { name: "Failed check Failed 4s" })).toBeVisible();
+ expect(within(archive).getByRole("button", { name: "Incomplete check Incomplete 4s" })).toBeVisible();
+ expect(within(archive).getByRole("button", { name: "Interrupted check Interrupted 4s" })).toBeVisible();
+ expect([...archive.querySelectorAll("[data-subagent-id]")].map((row) => row.getAttribute("data-subagent-id")))
+ .toEqual(["task-1", "failed", "cancelled", "incomplete", "interrupted"]);
+ await user.click(within(archive).getByRole("button", { name: "Failed check Failed 4s" }));
+ expect(within(screen.getByRole("dialog", { name: "Failed check" })).getByRole("alert")).toHaveTextContent("Unreadable file");
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it("restores completed work only in collapsed history and leaves full Markdown in the shared details", async () => {
+ const result = "## Saved findings\n\n- **Verified** the configuration\n\n[Evidence](https://example.com/evidence)";
+ vi.mocked(fetch).mockImplementation(async (url) => String(url).endsWith("/webui-thread")
+ ? childThread(result) : response([task({ result: "A snapshot summary, not a chat panel" })]));
+ const user = userEvent.setup();
+ const view = render(layout({ liveEvents: false, historyEnabled: true }));
+ const archive = await screen.findByRole("region", { name: "Subtasks" });
+ expect(screen.getByTestId("composer")).not.toHaveTextContent("Config check");
+ expect(screen.queryByTestId("subagent-task-dock-trigger")).not.toBeInTheDocument();
+ expect(summary(archive)).toHaveAttribute("aria-expanded", "false");
+ await user.click(summary(archive));
+ expect(screen.getByTestId("messages")).not.toHaveTextContent("A snapshot summary, not a chat panel");
+ expect(within(archive).queryByRole("link")).not.toBeInTheDocument();
+ expect(within(archive).queryByRole("heading", { name: "Saved findings" })).not.toBeInTheDocument();
+ await user.click(within(archive).getByRole("button", { name: "Config check Completed 4s" }));
+ const detail = screen.getByRole("dialog", { name: "Config check" });
+ expect(await within(detail).findByRole("heading", { name: "Saved findings" })).toBeVisible();
+ expect(within(detail).getByRole("link", { name: "Evidence" })).toHaveAttribute("href", "https://example.com/evidence");
+ view.unmount();
+
+ render(layout({ liveEvents: false, historyEnabled: true }));
+ const restored = await screen.findByRole("region", { name: "Subtasks" });
+ expect(summary(restored)).toHaveAttribute("aria-expanded", "false");
+ expect(screen.queryByTestId("subagent-task-dock-trigger")).not.toBeInTheDocument();
+ await user.click(summary(restored));
+ await user.click(within(restored).getByRole("button", { name: "Config check Completed 4s" }));
+ expect(await within(screen.getByRole("dialog", { name: "Config check" })).findByRole("heading", { name: "Saved findings" })).toBeVisible();
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it("prefers the exact initiating prompt and falls back once to the first user message of its turn", async () => {
+ vi.mocked(fetch).mockImplementation(async () => response([
+ task({ task_id: "exact", label: "Exact check", origin_message_id: "followup", created_at: 101 }),
+ task({ task_id: "fallback", label: "Turn fallback", origin_message_id: "replayed-original-id" }),
+ ]));
+ const user = userEvent.setup();
+ render(layout({ threadMessages: [
+ ...messages,
+ { id: "followup", role: "user", content: "Check the follow-up", turnId: "turn-a", createdAt: 102_000 },
+ { id: "followup-answer", role: "assistant", content: "Follow-up answer", turnId: "turn-a", createdAt: 103_000 },
+ ] }));
+ const archives = await screen.findAllByRole("region", { name: "Subtasks" });
+ expect(archives).toHaveLength(2);
+ expectBefore(screen.getByText("Inspect config"), archives[0]);
+ expectBefore(archives[0], screen.getByText("Main answer"));
+ expectBefore(screen.getByText("Check the follow-up"), archives[1]);
+ expectBefore(archives[1], screen.getByText("Follow-up answer"));
+ await user.click(summary(archives[0]));
+ await user.click(summary(archives[1]));
+ expect(within(archives[0]).getByRole("button", { name: "Turn fallback Completed 4s" })).toBeVisible();
+ expect(within(archives[1]).getByRole("button", { name: "Exact check Completed 4s" })).toBeVisible();
+ expect(screen.getByTestId("messages").querySelectorAll("[data-subagent-id]")).toHaveLength(2);
+ });
+
+ it("keeps unmatched terminal work before the chat and preserves open details when its source is loaded", async () => {
+ vi.mocked(fetch).mockImplementation(async () => response([
+ task({ task_id: "older", label: "Earlier check", origin_turn_id: "older-turn", origin_message_id: "older-prompt",
+ result: "## Earlier findings\n\nThe saved result remains available" }),
+ task({ task_id: "unlinked-active", label: "Unlinked live check", state: "running", completed_at: null,
+ origin_message_id: null, origin_turn_id: null, created_at: 200 }),
+ ]));
+ const user = userEvent.setup();
+ const view = render(layout());
+ const unlinked = await screen.findByRole("region", { name: "Other tasks" });
+ expectBefore(unlinked, screen.getByText("Inspect config"));
+ expect(summary(unlinked)).toHaveAttribute("aria-expanded", "false");
+ await user.click(summary(unlinked));
+ expect(within(unlinked).getByText("These tasks have no matching request in the displayed messages.")).toBeVisible();
+ expect(unlinked).not.toHaveTextContent("Unlinked live check");
+ await user.click(within(unlinked).getByRole("button", { name: "Earlier check Completed 4s" }));
+ const detail = screen.getByRole("dialog", { name: "Earlier check" });
+ expect(await within(detail).findByRole("heading", { name: "Earlier findings" })).toBeVisible();
+
+ view.rerender(layout({ threadMessages: [
+ { id: "older-prompt", role: "user", content: "Inspect earlier work", turnId: "older-turn", createdAt: 99_000 },
+ ...messages,
+ ] }));
+ expect(screen.getByRole("dialog", { name: "Earlier check" })).toBe(detail);
+ expect(within(detail).getByText("The saved result remains available")).toBeVisible();
+ await user.keyboard("{Escape}");
+ expect(screen.queryByRole("region", { name: "Other tasks" })).not.toBeInTheDocument();
+ const linked = screen.getByRole("region", { name: "Subtasks" });
+ const header = summary(linked);
+ expect(header).toHaveAttribute("aria-expanded", "true");
+ await waitFor(() => expect(within(linked).getByRole("button", { name: "Earlier check Completed 4s" })).toHaveFocus());
+ expect(screen.getByTestId("messages").querySelectorAll('[data-subagent-id="older"]')).toHaveLength(1);
+ expectBefore(screen.getByText("Inspect earlier work"), linked);
+ expectBefore(linked, screen.getByText("Inspect config"));
+ expect(within(linked).getByRole("button", { name: "Earlier check Completed 4s" })).toBeVisible();
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it("yields reading control before expanding and keeps the archive open when its prompt display id changes", async () => {
+ const user = userEvent.setup();
+ const onActivityToggle = vi.fn(() => {
+ expect(summary(screen.getByRole("region", { name: "Subtasks" }))).toHaveAttribute("aria-expanded", "false");
+ });
+ const view = render(layout({ onActivityToggle }));
+ const archive = await screen.findByRole("region", { name: "Subtasks" });
+ await user.click(summary(archive));
+ expect(onActivityToggle).toHaveBeenCalledTimes(1);
+ expect(summary(archive)).toHaveAttribute("data-thread-disclosure");
+ view.rerender(layout({ threadMessages: [{ ...messages[0], id: "canonical-input" }, messages[1]], onActivityToggle }));
+ const replayed = screen.getByRole("region", { name: "Subtasks" });
+ expect(summary(replayed)).toHaveAttribute("aria-expanded", "true");
+ expect(within(replayed).getByRole("button", { name: "Config check Completed 4s" })).toBeVisible();
+ });
+
+ it("preserves each disclosure through other task outcomes, history prepends and Activity preference changes", async () => {
+ act(() => { writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, activityMode: "expanded" }); });
+ vi.mocked(fetch).mockImplementation(async () => response([
+ task(),
+ task({ task_id: "second", label: "Second check", created_at: 101 }),
+ task({ task_id: "other", label: "Other check", state: "running", completed_at: null, origin_message_id: null, origin_turn_id: null, created_at: 102 }),
+ ]));
+ const user = userEvent.setup();
+ const view = render(layout());
+ const archive = await screen.findByRole("region", { name: "Subtasks" });
+ expect(summary(archive)).toHaveAttribute("aria-expanded", "false");
+ await user.click(summary(archive));
+ act(() => { writeLocalPreferences(DEFAULT_LOCAL_PREFS); });
+ expect(summary(archive)).toHaveAttribute("aria-expanded", "true");
+
+ emitTask(task({ task_id: "other", label: "Other check", revision: 2, state: "error", error: "Other work failed",
+ origin_message_id: null, origin_turn_id: null, created_at: 102 }));
+ expect(summary(archive)).toHaveAttribute("aria-expanded", "true");
+ const unlinked = screen.getByRole("region", { name: "Other tasks" });
+ expect(summary(unlinked)).toHaveAttribute("aria-expanded", "false");
+ await user.click(summary(unlinked));
+ view.rerender(layout({ threadMessages: [
+ { id: "prepended", role: "user", content: "Earlier request from this turn", turnId: "turn-a", createdAt: 99_000 },
+ ...messages,
+ ] }));
+ const retained = screen.getByRole("region", { name: "Subtasks" });
+ expect(summary(retained)).toHaveAttribute("aria-expanded", "true");
+ expect(within(retained).getByRole("button", { name: "Config check Completed 4s" })).toBeVisible();
+ expect([...retained.querySelectorAll("[data-subagent-id]")].map((row) => row.getAttribute("data-subagent-id")))
+ .toEqual(["task-1", "second"]);
+ expect(summary(screen.getByRole("region", { name: "Other tasks" }))).toHaveAttribute("aria-expanded", "true");
+ await user.click(summary(retained));
+ act(() => { writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, activityMode: "expanded" }); });
+ expect(summary(retained)).toHaveAttribute("aria-expanded", "false");
+ expect(within(retained).queryByRole("button", { name: "Config check Completed 4s" })).not.toBeInTheDocument();
+ });
+});
diff --git a/webui/src/tests/subagent-tasks.test.tsx b/webui/src/tests/subagent-tasks.test.tsx
index f068d911b..469d1ef56 100644
--- a/webui/src/tests/subagent-tasks.test.tsx
+++ b/webui/src/tests/subagent-tasks.test.tsx
@@ -2,11 +2,15 @@ import { act, fireEvent, render, screen, waitFor, within } from "@testing-librar
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { SubagentTasksProvider, SubagentThreadMessages as ThreadMessages } from "@/components/thread/SubagentTasks";
+import { preloadMarkdownText } from "@/components/MarkdownText";
+import { SubagentTasksProvider } from "@/components/thread/SubagentTasks";
+import { SubagentTaskDock } from "@/components/thread/SubagentTaskDock";
+import { SubagentThreadMessages } from "@/components/thread/SubagentTaskResults";
import { buildDisplayUnits, unitKeysForDisplay } from "@/components/thread/ThreadMessages";
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
import { setAppLanguage } from "@/i18n";
import { DEFAULT_LOCAL_PREFS, LOCAL_PREFS_STORAGE_KEY, writeLocalPreferences } from "@/lib/local-preferences";
+import { latestSubagentInputKey } from "@/lib/subagent-tasks";
import type { ConnectionStatus, InboundEvent, SubagentTaskSnapshot, UIMessage } from "@/lib/types";
const requestMutation = vi.fn();
@@ -56,14 +60,37 @@ function childThread(answer: string, active = true): Response {
],
}), { headers: { "content-type": "application/json" } });
}
-function layout({ enabled = true, liveEvents = true, historyEnabled = false, sessionKey = "websocket:a", visible = true, threadMessages = messages } = {}) {
+interface LayoutOptions {
+ enabled?: boolean;
+ liveEvents?: boolean;
+ historyEnabled?: boolean;
+ sessionKey?: string;
+ visible?: boolean;
+ active?: boolean;
+ inputKey?: string | null;
+ threadMessages?: UIMessage[];
+}
+function layout({ enabled = true, liveEvents = true, historyEnabled = false, sessionKey = "websocket:a", visible = true, active = true, inputKey = null, threadMessages = messages }: LayoutOptions = {}) {
return <ThreadVisibilityContext.Provider value={visible}>
- <SubagentTasksProvider client={client} sessionKey={sessionKey} token="tok" enabled={enabled} liveEvents={liveEvents} historyEnabled={historyEnabled}>
- <div data-testid="messages"><ThreadMessages messages={threadMessages} /></div>
- <div data-testid="composer"><textarea aria-label="Message" /></div>
+ <SubagentTasksProvider client={client} sessionKey={sessionKey} token="tok" enabled={enabled} liveEvents={liveEvents} historyEnabled={historyEnabled} active={active}>
+ <div data-testid="messages"><SubagentThreadMessages messages={threadMessages} /></div>
+ <div data-testid="composer" className="thread-composer-stack"><SubagentTaskDock inputKey={inputKey ?? latestSubagentInputKey(threadMessages)} /><textarea aria-label="Message" /></div>
</SubagentTasksProvider>
</ThreadVisibilityContext.Provider>;
}
+async function openTaskList(user: ReturnType<typeof userEvent.setup>) {
+ await user.click(await screen.findByTestId("subagent-task-dock-trigger"));
+ return screen.getByTestId("subagent-task-tree");
+}
+async function openArchive(user: ReturnType<typeof userEvent.setup>, name = "Subtasks") {
+ const archive = await within(screen.getByTestId("messages")).findByRole("region", { name });
+ const summary = within(archive).getByRole("button", { name: new RegExp(name) });
+ if (summary.getAttribute("aria-expanded") !== "true") await user.click(summary);
+ return archive;
+}
+function taskIds(container: HTMLElement) {
+ return [...container.querySelectorAll("[data-subagent-id]")].map(row => row.getAttribute("data-subagent-id"));
+}
describe("session-owned task UI", () => {
beforeEach(async () => {
@@ -76,20 +103,422 @@ describe("session-owned task UI", () => {
statusHandlers.clear();
vi.stubGlobal("fetch", vi.fn().mockImplementation(async () => response([task()])));
});
- afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); localStorage.removeItem(LOCAL_PREFS_STORAGE_KEY); });
+ afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllGlobals(); localStorage.removeItem(LOCAL_PREFS_STORAGE_KEY); });
+
+ it("keeps active work in one composer entry without mixing in a large terminal archive", async () => {
+ const older = Array.from({ length: 40 }, (_, index) => task({
+ task_id: `older-${index}`, label: `Archived check ${index}`, created_at: index + 1,
+ state: "done", completed_at: 90, result: `Saved finding ${index}`,
+ }));
+ vi.mocked(fetch).mockImplementation(async () => response([
+ ...older, task(),
+ task({ task_id: "legacy", label: "Earlier check", created_at: 91, origin_turn_id: null, origin_message_id: "missing-prompt", state: "done", completed_at: 92, result: "Saved result" }),
+ ]));
+ const user = userEvent.setup();
+ render(layout());
+ const trigger = await screen.findByTestId("subagent-task-dock-trigger");
+ expect(fetch).toHaveBeenCalledWith("/api/sessions/websocket%3Aa/subagents", expect.any(Object));
+ expect(screen.getAllByTestId("subagent-task-dock-trigger")).toEqual([trigger]);
+ expect(screen.getByTestId("composer")).toContainElement(trigger);
+ expect(trigger).toHaveTextContent("Running: 1");
+ expect(trigger).not.toHaveTextContent("Completed:");
+ expect(trigger).toHaveAttribute("aria-expanded", "false");
+ expect(screen.queryByTestId("subagent-task-tree")).not.toBeInTheDocument();
+ expect(screen.getByTestId("messages")).toHaveTextContent("Inspect config");
+ expect(screen.getByTestId("messages")).toHaveTextContent("Main answer");
+ expect(screen.getByTestId("messages")).not.toHaveTextContent("Config check");
+ expect(screen.getByTestId("messages")).not.toHaveTextContent("Saved result");
+
+ const list = await openTaskList(user);
+ expect(within(list).getByRole("button", { name: /Config check Running/ })).toBeVisible();
+ expect(taskIds(list)).toEqual(["task-1"]);
+ expect(within(list).queryByText(/Archived check|Earlier check|Saved finding|Saved result/)).not.toBeInTheDocument();
+ await user.keyboard("{Escape}");
+ expect(screen.queryByTestId("subagent-task-tree")).not.toBeInTheDocument();
+ const archive = await openArchive(user);
+ expect(taskIds(archive)).toEqual(older.map(saved => saved.task_id));
+ expect(within(archive).queryByRole("button", { name: /Config check Running/ })).not.toBeInTheDocument();
+ const other = await openArchive(user, "Other tasks");
+ await user.click(within(other).getByRole("button", { name: /Earlier check Completed/ }));
+ expect(within(screen.getByRole("dialog", { name: "Earlier check" })).getByText("Saved result")).toBeVisible();
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it("keeps collapsed task controls out of Tab order and allows typing without closing the drawer", async () => {
+ const user = userEvent.setup();
+ render(layout());
+ const trigger = await screen.findByTestId("subagent-task-dock-trigger");
+ const input = screen.getByRole("textbox", { name: "Message" });
+ expect(trigger).toHaveAccessibleName("Subtasks · Running: 1");
+ act(() => { trigger.focus(); });
+ await user.tab();
+ expect(input).toHaveFocus();
+ await user.tab({ shift: true });
+ expect(trigger).toHaveFocus();
+ await user.keyboard("{Enter}");
+ const list = screen.getByTestId("subagent-task-tree");
+ await user.tab();
+ expect(within(list).getByRole("button", { name: /Config check Running/ })).toHaveFocus();
+ await user.click(input);
+ await user.type(input, "Keep working in the conversation");
+ expect(input).toHaveValue("Keep working in the conversation");
+ const cancelComposition = new KeyboardEvent("keydown", { key: "Escape", isComposing: true, bubbles: true, cancelable: true });
+ fireEvent(input, cancelComposition);
+ expect(cancelComposition.defaultPrevented).toBe(false);
+ expect(trigger).toHaveAttribute("aria-expanded", "true");
+ await user.click(trigger);
+ expect(trigger).toHaveFocus();
+ expect(screen.queryByTestId("subagent-task-tree")).not.toBeInTheDocument();
+ await user.tab();
+ expect(input).toHaveFocus();
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it("removes a finished task from the closed dock while a sibling is still active", async () => {
+ vi.mocked(fetch).mockImplementation(async () => response([
+ task(), task({ task_id: "sibling", label: "Waiting check", state: "queued", created_at: 101 }),
+ ]));
+ const user = userEvent.setup();
+ render(layout());
+ const trigger = await screen.findByTestId("subagent-task-dock-trigger");
+ expect(trigger).toHaveTextContent("Running: 2");
+ emitTask(task({ revision: 2, state: "done", completed_at: 102, result: "Verified" }));
+ expect(trigger).toHaveTextContent("Running: 1");
+ expect(trigger).not.toHaveTextContent("Completed:");
+ const list = await openTaskList(user);
+ expect(taskIds(list)).toEqual(["sibling"]);
+ expect(within(list).getByRole("button", { name: /Waiting check Queued/ })).toBeVisible();
+ expect(within(list).queryByRole("button", { name: /Config check Completed/ })).not.toBeInTheDocument();
+ await user.keyboard("{Escape}");
+ await waitFor(() => expect(trigger).toHaveFocus());
+ const archive = await openArchive(user);
+ expect(within(archive).getByRole("button", { name: /Config check Completed/ })).toBeVisible();
+ expect(taskIds(archive)).toEqual(["task-1"]);
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { state: "done", status: "Completed", summary: "Completed: 1", error: null },
+ { state: "error", status: "Failed", summary: "Finished: 1", error: "Cannot read the file" },
+ { state: "cancelled", status: "Cancelled", summary: "Finished: 1", error: null },
+ ] as const)("expires observed $state feedback after four seconds without inventing success", async ({ state, status, summary, error }) => {
+ vi.useFakeTimers();
+ render(layout());
+ await act(async () => { await Promise.resolve(); });
+ expect(screen.getByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 1");
+ emitTask(task({ revision: 2, state, error, completed_at: 102, result: state === "done" ? "Verified" : null }));
+ const trigger = screen.getByTestId("subagent-task-dock-trigger");
+ expect(trigger).toHaveTextContent(summary);
+ if (state !== "done") expect(trigger).not.toHaveTextContent("Completed:");
+ if (state === "error") expect(trigger).toHaveTextContent("Review needed: 1");
+ expect(trigger).toHaveAttribute("aria-expanded", "false");
+ expect(screen.queryByTestId("subagent-task-tree")).not.toBeInTheDocument();
+ await act(async () => { await vi.advanceTimersByTimeAsync(3999); });
+ expect(trigger).toBeInTheDocument();
+ await act(async () => { await vi.advanceTimersByTimeAsync(1); });
+ expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
+ const archive = screen.getByRole("region", { name: "Subtasks" });
+ fireEvent.click(within(archive).getByRole("button", { name: /Subtasks/ }));
+ expect(within(archive).getByRole("button", { name: new RegExp(`Config check ${status}`) })).toBeVisible();
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it.each(["hover", "focus", "detail"] as const)("pauses completion feedback expiry during %s interaction", async interaction => {
+ vi.useFakeTimers();
+ render(layout());
+ await act(async () => { await Promise.resolve(); });
+ emitTask(task({ revision: 2, state: "done", completed_at: 102, result: "Verified" }));
+ const trigger = screen.getByTestId("subagent-task-dock-trigger");
+ await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
+ if (interaction === "hover") fireEvent.pointerEnter(trigger, { pointerType: "mouse" });
+ else if (interaction === "focus") act(() => { trigger.focus(); });
+ else {
+ const archive = screen.getByRole("region", { name: "Subtasks" });
+ fireEvent.click(within(archive).getByRole("button", { name: /Subtasks/ }));
+ fireEvent.click(within(archive).getByRole("button", { name: /Config check Completed/ }));
+ expect(within(screen.getByRole("dialog", { name: "Config check" })).getByText("Verified")).toBeVisible();
+ }
+ await act(async () => { await vi.advanceTimersByTimeAsync(8000); });
+ expect(trigger).toBeInTheDocument();
+ if (interaction === "hover") fireEvent.pointerLeave(trigger, { pointerType: "mouse" });
+ else if (interaction === "focus") act(() => { screen.getByRole("textbox", { name: "Message" }).focus(); });
+ else fireEvent.keyDown(screen.getByRole("dialog", { name: "Config check" }), { key: "Escape" });
+ await act(async () => { await vi.advanceTimersByTimeAsync(4000); });
+ expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it("retains completed rows while reading and appends newly active work without forcing the list closed", async () => {
+ vi.useFakeTimers();
+ render(layout());
+ await act(async () => { await Promise.resolve(); });
+ fireEvent.click(screen.getByTestId("subagent-task-dock-trigger"));
+ const list = screen.getByTestId("subagent-task-tree");
+ const row = within(list).getByRole("button", { name: /Config check Running/ });
+ emitTask(task({ revision: 2, state: "done", completed_at: 102, result: "Verified" }));
+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
+ expect(list).toBeVisible();
+ expect(within(list).getByRole("button", { name: /Config check Completed/ })).toBe(row);
+ emitTask(task({ task_id: "sibling", label: "Follow-up check", state: "queued", created_at: 103 }));
+ expect(taskIds(list)).toEqual(["task-1", "sibling"]);
+ expect(within(list).getByRole("button", { name: /Follow-up check Queued/ })).toBeVisible();
+ emitTask(task({ task_id: "sibling", revision: 2, label: "Follow-up check", state: "cancelled", created_at: 103, completed_at: 104 }));
+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
+ expect(within(list).getByRole("button", { name: /Config check Completed/ })).toBe(row);
+ expect(within(list).getByRole("button", { name: /Follow-up check Cancelled/ })).toBeVisible();
+ fireEvent.keyDown(list, { key: "Escape" });
+ await act(async () => { await vi.advanceTimersByTimeAsync(0); });
+ expect(screen.queryByTestId("subagent-task-tree")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
+ expect(screen.getByRole("textbox", { name: "Message" })).toHaveFocus();
+ const archive = screen.getByRole("region", { name: "Subtasks" });
+ fireEvent.click(within(archive).getByRole("button", { name: /Subtasks/ }));
+ expect(taskIds(archive)).toEqual(["task-1", "sibling"]);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it("appends a reconnect's earlier-created active task without moving an open row", async () => {
+ vi.mocked(fetch).mockImplementation(async () => response([task({ created_at: 102 })]));
+ const user = userEvent.setup();
+ render(layout());
+ const list = await openTaskList(user);
+ const row = within(list).getByRole("button", { name: /Config check Running/ });
+ vi.mocked(fetch).mockImplementation(async () => response([
+ task({ task_id: "earlier", label: "Earlier check", created_at: 100 }), task({ created_at: 102 }),
+ ]));
+ fireEvent(window, new Event("focus"));
+ await within(list).findByRole("button", { name: /Earlier check Running/ });
+ expect(taskIds(list)).toEqual(["task-1", "earlier"]);
+ expect(within(list).getByRole("button", { name: /Config check Running/ })).toBe(row);
+ });
+
+ it("keeps completion feedback when the same input is replayed with a different display id", async () => {
+ const view = render(layout());
+ await screen.findByTestId("subagent-task-dock-trigger");
+ emitTask(task({ revision: 2, state: "done", completed_at: 102, result: "Verified" }));
+ expect(screen.getByTestId("subagent-task-dock-trigger")).toHaveTextContent("Completed: 1");
+ view.rerender(layout({ threadMessages: [{ ...messages[0], id: "canonical-input" }, messages[1]] }));
+ expect(screen.getByTestId("subagent-task-dock-trigger")).toHaveTextContent("Completed: 1");
+ });
+
+ it("preserves an open reading view across new input, then reopens with only cross-turn active work", async () => {
+ vi.mocked(fetch).mockImplementation(async () => response([
+ task(), task({ task_id: "cross-turn", label: "Cross-turn check", state: "stopping", created_at: 101 }),
+ task({ task_id: "old", label: "Old check", state: "cancelled", created_at: 90, completed_at: 91 }),
+ ]));
+ const user = userEvent.setup();
+ const view = render(layout({ inputKey: "prompt-a" }));
+ const list = await openTaskList(user);
+ const crossTurn = within(list).getByRole("button", { name: /Cross-turn check Stopping/ });
+ expect(taskIds(list)).toEqual(["task-1", "cross-turn"]);
+ emitTask(task({ revision: 2, state: "done", completed_at: 102, result: "Earlier finding" }));
+ expect(within(list).getByRole("button", { name: /Config check Completed/ })).toBeVisible();
+ const nextMessages: UIMessage[] = [...messages, { id: "prompt-b", role: "user", content: "Inspect the next setting", turnId: "turn-b", createdAt: 103_000 }];
+ view.rerender(layout({ inputKey: "prompt-b", threadMessages: nextMessages }));
+ expect(screen.getByTestId("subagent-task-tree")).toBe(list);
+ expect(taskIds(list)).toEqual(["task-1", "cross-turn"]);
+ expect(within(list).getByRole("button", { name: /Cross-turn check Stopping/ })).toBe(crossTurn);
+ expect(screen.getByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 1");
+ emitTask(task({ task_id: "next", label: "Next check", created_at: 104, origin_turn_id: "turn-b", origin_message_id: "prompt-b" }));
+ expect(taskIds(list)).toEqual(["task-1", "cross-turn", "next"]);
+ await user.keyboard("{Escape}");
+ expect(screen.getByTestId("subagent-task-dock-trigger")).not.toHaveTextContent("Completed:");
+ const reopened = await openTaskList(user);
+ expect(taskIds(reopened)).toEqual(["cross-turn", "next"]);
+ await user.keyboard("{Escape}");
+ const archive = await openArchive(user);
+ expect(taskIds(archive)).toEqual(["old", "task-1"]);
+ expect(within(archive).getByRole("button", { name: /Config check Completed/ })).toBeVisible();
+ expect(within(archive).queryByRole("button", { name: /Cross-turn check|Next check/ })).not.toBeInTheDocument();
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it("clears previous-turn completion feedback on new input without deleting its archive", async () => {
+ const user = userEvent.setup();
+ const view = render(layout({ inputKey: "prompt-a" }));
+ await screen.findByTestId("subagent-task-dock-trigger");
+ emitTask(task({ revision: 2, state: "done", completed_at: 102, result: "Earlier finding" }));
+ expect(screen.getByTestId("subagent-task-dock-trigger")).toHaveTextContent("Completed: 1");
+ view.rerender(layout({ inputKey: "prompt-b" }));
+ expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
+ const archive = await openArchive(user);
+ expect(within(archive).getByRole("button", { name: /Config check Completed/ })).toBeVisible();
+ emitTask(task({ task_id: "next", label: "Next check", created_at: 103 }));
+ expect(screen.getByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 1");
+ const list = await openTaskList(user);
+ expect(taskIds(list)).toEqual(["next"]);
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it("treats an initial terminal-only snapshot and a cold refresh as history, never completion feedback", async () => {
+ vi.mocked(fetch).mockImplementation(async () => response([
+ task({ state: "done", completed_at: 102, result: "Saved finding" }),
+ task({ task_id: "failed", label: "Failed check", state: "error", created_at: 101, completed_at: 103, error: "Saved failure" }),
+ task({ task_id: "cancelled", label: "Cancelled check", state: "cancelled", created_at: 102, completed_at: 104 }),
+ ]));
+ const user = userEvent.setup();
+ const view = render(layout());
+ const archive = await screen.findByRole("region", { name: "Subtasks" });
+ expect(within(archive).getByRole("button", { name: /Subtasks/ })).toHaveAttribute("aria-expanded", "false");
+ expect(within(archive).queryByRole("button", { name: /Config check Completed/ })).not.toBeInTheDocument();
+ expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("subagent-task-tree")).not.toBeInTheDocument();
+ await openArchive(user);
+ expect(taskIds(archive)).toEqual(["task-1", "failed", "cancelled"]);
+ await user.click(within(archive).getByRole("button", { name: /Config check Completed/ }));
+ expect(within(screen.getByRole("dialog", { name: "Config check" })).getByText("Saved finding")).toBeVisible();
+ view.unmount();
+ render(layout());
+ const restored = await screen.findByRole("region", { name: "Subtasks" });
+ expect(within(restored).getByRole("button", { name: /Subtasks/ })).toHaveAttribute("aria-expanded", "false");
+ expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
+ vi.useFakeTimers();
+ await act(async () => { await vi.advanceTimersByTimeAsync(5000); });
+ expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
+ expect(restored).toBeVisible();
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it("keeps a completed task readable until the list is closed, then focuses the composer and archives it", async () => {
+ const user = userEvent.setup();
+ render(layout());
+ const trigger = await screen.findByTestId("subagent-task-dock-trigger");
+ expect(screen.getByTestId("composer")).toContainElement(trigger);
+ expect(screen.getByTestId("messages")).not.toContainElement(trigger);
+ expect(trigger).toHaveTextContent("Running: 1");
+ expect(trigger).toHaveAttribute("aria-expanded", "false");
+ await user.click(trigger);
+ const list = screen.getByTestId("subagent-task-tree");
+ const row = within(list).getByRole("button", { name: /Config check Running/ });
+ expect(row.querySelectorAll(".loading-ring-arc")).toHaveLength(1);
+ await user.click(row);
+ expect(screen.getByRole("dialog", { name: "Config check" })).toBeVisible();
+ emitTask(task({ revision: 2, state: "done", completed_at: 102, result: "Verified the configuration" }));
+ expect(screen.getByRole("dialog", { name: "Config check" })).toBeVisible();
+ await user.keyboard("{Escape}");
+ expect(trigger).toHaveAttribute("aria-expanded", "true");
+ expect(within(list).getByRole("button", { name: /Config check Completed/ })).toBe(row);
+ expect(row.querySelectorAll("svg")).toHaveLength(0);
+ expect(row.firstElementChild?.firstElementChild).toHaveAttribute("aria-hidden", "true");
+ await waitFor(() => expect(row).toHaveFocus());
+ expect(await within(list).findByText("Verified the configuration")).toBeVisible();
+ await user.keyboard("{Escape}");
+ expect(screen.queryByTestId("subagent-task-tree")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("subagent-task-dock-trigger")).not.toBeInTheDocument();
+ await waitFor(() => expect(screen.getByRole("textbox", { name: "Message" })).toHaveFocus());
+ const archive = await openArchive(user);
+ const archivedRow = within(archive).getByRole("button", { name: /Config check Completed/ });
+ await user.click(archivedRow);
+ expect(within(screen.getByRole("dialog", { name: "Config check" })).getByText("Verified the configuration")).toBeVisible();
+ await user.keyboard("{Escape}");
+ await waitFor(() => expect(archivedRow).toHaveFocus());
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
+
+ it("renders the full result as Markdown in the drawer and keeps task details available", async () => {
+ const result = "## Findings\n\n**Verified** the configuration.\n\n" + "Verified the configuration. ".repeat(30)
+ + "\n\n[Full evidence](https://example.com/evidence)\n\n[Unsafe link](javascript:alert(1))\n\n```ts\nconst verified = true;\n```\n\nFinal finding after the long result.";
+ const user = userEvent.setup();
+ render(layout());
+ const tree = await openTaskList(user);
+ emitTask(task({ revision: 2, state: "done", completed_at: 102, result }));
+ expect(await within(tree).findByRole("heading", { name: "Findings", level: 2 })).toBeVisible();
+ expect(within(tree).getByText("Verified", { selector: "strong" })).toBeVisible();
+ expect(within(tree).getByText("Final finding after the long result.")).toBeVisible();
+ const evidence = within(tree).getByRole("link", { name: "Full evidence" });
+ expect(evidence).toHaveAttribute("href", "https://example.com/evidence");
+ expect(evidence).toHaveAttribute("rel", "noreferrer noopener");
+ expect(within(tree).queryByRole("link", { name: "Unsafe link" })).not.toBeInTheDocument();
+ expect(tree.querySelector("pre")?.textContent).toContain("const verified = true;");
+ await user.click(within(tree).getByRole("button", { name: /Config check Completed/ }));
+ expect(await within(screen.getByRole("dialog", { name: "Config check" })).findByRole("link", { name: /Full evidence/ })).toHaveAttribute("href", "https://example.com/evidence");
+ });
+
+ it("keeps result-owned image portals inside the drawer interaction boundary", async () => {
+ await preloadMarkdownText();
+ const user = userEvent.setup();
+ render(layout());
+ const tree = await openTaskList(user);
+ emitTask(task({ revision: 2, state: "done", completed_at: 102, result: "![Result image](https://example.com/result.png)" }));
+ await user.click(await within(tree).findByRole("button", { name: "View image: Result image" }));
+ const viewer = screen.getByRole("dialog", { name: "Result image" });
+ fireEvent.pointerDown(within(viewer).getByRole("img", { name: "Result image" }));
+ expect(viewer).toBeInTheDocument();
+ expect(screen.getByTestId("subagent-task-dock-trigger")).toHaveAttribute("aria-expanded", "true");
+ await user.keyboard("{Escape}");
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ expect(screen.getByTestId("subagent-task-tree")).toBe(tree);
+ fireEvent.pointerDown(screen.getByTestId("messages"));
+ expect(screen.queryByTestId("subagent-task-dock-trigger")).not.toBeInTheDocument();
+ expect(screen.getByRole("textbox", { name: "Message" })).toHaveFocus();
+ });
+
+ it("keeps task order, actual tool activity and cancellation outcomes in the dock", async () => {
+ const user = userEvent.setup();
+ vi.mocked(fetch).mockImplementation(async () => response([
+ task({ task_id: "queued", label: "Waiting check", state: "queued", created_at: 101 }),
+ task({ tool_events: [{ name: "read_file", status: "running" }, { name: "exec", status: "running" }, { name: "web_fetch", status: "error" }] }),
+ ]));
+ requestMutation.mockResolvedValue(task({ revision: 2, state: "cancelled", completed_at: 102 }));
+ render(layout());
+ const trigger = await screen.findByTestId("subagent-task-dock-trigger");
+ expect(trigger).toHaveTextContent("Running: 2");
+ await user.click(trigger);
+ const list = screen.getByTestId("subagent-task-tree");
+ expect(within(list).getByText("read_file")).toBeVisible();
+ expect(within(list).getByText("exec")).toBeVisible();
+ const runningTask = within(list).getByRole("button", { name: /Config check Running/ }).closest("li")!;
+ expect(runningTask.querySelectorAll(".loading-ring-arc")).toHaveLength(1);
+ expect(runningTask.querySelector('[data-product-icon="task-error"]')).toHaveClass("text-destructive");
+ expect([...list.querySelectorAll("[data-subagent-id]")].map(row => row.getAttribute("data-subagent-id"))).toEqual(["task-1", "queued"]);
+ await user.click(within(list).getByRole("button", { name: "Stop Config check" }));
+ await within(list).findByRole("button", { name: /Config check Cancelled/ });
+ emitTask(task({ task_id: "queued", label: "Waiting check", created_at: 101, revision: 2, state: "error", error: "Cannot read the file", completed_at: 103 }));
+ expect(trigger).toHaveTextContent("Finished: 2");
+ expect(trigger).toHaveTextContent("Review needed: 1");
+ expect(within(list).getByText("Cannot read the file")).toBeVisible();
+ expect([...list.querySelectorAll("[data-subagent-id]")].map(row => row.getAttribute("data-subagent-id"))).toEqual(["task-1", "queued"]);
+ expect(requestMutation).toHaveBeenCalledTimes(1);
+ expect(requestMutation).toHaveBeenCalledWith("subagent.cancel", { session_key: "websocket:a", task_id: "task-1" }, 20_000);
+ expect(list).toBeVisible();
+ await user.keyboard("{Escape}");
+ expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
+ await waitFor(() => expect(screen.getByRole("textbox", { name: "Message" })).toHaveFocus());
+ const archive = await openArchive(user);
+ expect(within(archive).getByRole("button", { name: /Config check Cancelled/ })).toBeVisible();
+ expect(within(archive).getByRole("button", { name: /Waiting check Failed/ })).toBeVisible();
+ });
+
+ it.each(["inactive", "hidden", "session"])("closes the task drawer when its scope becomes %s", async change => {
+ const user = userEvent.setup();
+ const view = render(layout());
+ expect(await openTaskList(user)).toBeVisible();
+ view.rerender(layout({ active: change !== "inactive", visible: change !== "hidden", sessionKey: change === "session" ? "websocket:b" : "websocket:a" }));
+ await waitFor(() => expect(screen.queryByTestId("subagent-task-tree")).not.toBeInTheDocument());
+ if (change !== "session") expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
+ view.rerender(layout());
+ expect(await screen.findByTestId("subagent-task-dock-trigger")).toHaveAttribute("aria-expanded", "false");
+ expect(requestMutation).not.toHaveBeenCalled();
+ });
- it("applies the browser activity preference to delegated work and its shared child chat", async () => {
+ it("applies the browser activity preference to the child chat without auto-opening archived results", async () => {
vi.stubGlobal("fetch", vi.fn(async (url: string) => url.endsWith("/webui-thread")
? childThread("Configuration verified", false)
: response([task({ state: "done", completed_at: 102 })])));
const user = userEvent.setup();
const view = render(layout({ historyEnabled: true }));
- const work = await screen.findByRole("button", { name: /Subtasks/ });
- expect(work).toHaveAttribute("aria-expanded", "false");
+ const archive = await screen.findByRole("region", { name: "Subtasks" });
+ const summary = within(archive).getByRole("button", { name: /Subtasks/ });
+ expect(summary).toHaveAttribute("aria-expanded", "false");
+ expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
act(() => { writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, activityMode: "expanded" }); });
- expect(work).toHaveAttribute("aria-expanded", "true");
- await user.click(screen.getByRole("button", { name: /Config check Completed/ }));
+ expect(summary).toHaveAttribute("aria-expanded", "false");
+ expect(screen.queryByTestId("subagent-task-tree")).not.toBeInTheDocument();
+ await openArchive(user);
+ await user.click(within(archive).getByRole("button", { name: /Config check Completed/ }));
const detail = screen.getByRole("dialog", { name: "Config check" });
expect(await within(detail).findByText("Configuration verified")).toBeVisible();
expect(within(detail).getByTestId("agent-activity-content")).toBeVisible();
@@ -97,14 +526,18 @@ describe("session-owned task UI", () => {
expect(within(detail).queryByTestId("agent-activity-content")).not.toBeInTheDocument();
act(() => { writeLocalPreferences(DEFAULT_LOCAL_PREFS); });
- expect(work).toHaveAttribute("aria-expanded", "false");
+ expect(summary).toHaveAttribute("aria-expanded", "true");
+ expect(within(detail).queryByTestId("agent-activity-content")).not.toBeInTheDocument();
act(() => { writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, activityMode: "expanded" }); });
expect(within(detail).getByTestId("agent-activity-content")).toBeVisible();
view.unmount();
render(layout({ historyEnabled: true }));
- expect(await screen.findByRole("button", { name: /Config check Completed/ })).toBeVisible();
- await user.click(screen.getByRole("button", { name: /Config check Completed/ }));
+ const restoredArchive = await screen.findByRole("region", { name: "Subtasks" });
+ expect(within(restoredArchive).getByRole("button", { name: /Subtasks/ })).toHaveAttribute("aria-expanded", "false");
+ expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
+ await openArchive(user);
+ await user.click(within(restoredArchive).getByRole("button", { name: /Config check Completed/ }));
expect(await within(screen.getByRole("dialog")).findByTestId("agent-activity-content")).toBeVisible();
});
@@ -116,7 +549,8 @@ describe("session-owned task UI", () => {
vi.stubGlobal("fetch", fetcher);
const user = userEvent.setup();
const view = render(layout({ historyEnabled: true }));
- await user.click(await screen.findByRole("button", { name: /Config check Running/ }));
+ const list = await openTaskList(user);
+ await user.click(within(list).getByRole("button", { name: /Config check Running/ }));
const detail = screen.getByRole("dialog", { name: "Config check" });
expect(await within(detail).findByText("Inspect configuration in the child session")).toBeVisible();
expect(within(detail).getByText("Checking the configuration")).toBeVisible();
@@ -134,8 +568,9 @@ describe("session-owned task UI", () => {
fetcher.mockImplementation(async (url) => url.endsWith("/webui-thread") ? childThread("## Findings\n\nVerified the full session", false)
: response([task({ revision: 2, state: "done", completed_at: 102 })]));
render(layout({ historyEnabled: true }));
- await user.click(await screen.findByRole("button", { name: /Subtasks/ }));
- await user.click(screen.getByRole("button", { name: /Config check Completed/ }));
+ const restoredArchive = await openArchive(user);
+ expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
+ await user.click(within(restoredArchive).getByRole("button", { name: /Config check Completed/ }));
expect(await within(screen.getByRole("dialog")).findByRole("heading", { name: "Findings" })).toBeVisible();
});
@@ -155,7 +590,8 @@ describe("session-owned task UI", () => {
vi.stubGlobal("fetch", fetcher);
const user = userEvent.setup();
const view = render(layout({ historyEnabled: true }));
- await user.click(await screen.findByRole("button", { name: /Config check Running/ }));
+ const list = await openTaskList(user);
+ await user.click(within(list).getByRole("button", { name: /Config check Running/ }));
await waitFor(() => expect(reads).toBe(1));
emitTask(task({ revision: 2, iteration: 2 }));
emitTask(task({ revision: 3, iteration: 3 }));
@@ -167,11 +603,15 @@ describe("session-owned task UI", () => {
await waitFor(() => expect(reads).toBe(3));
const oldSignal = readSignals.at(-1);
view.rerender(layout({ historyEnabled: true, sessionKey: "websocket:b" }));
- await screen.findByRole("button", { name: /Config check Running/ });
+ expect(await screen.findByTestId("subagent-task-dock-trigger")).toHaveAttribute("aria-expanded", "false");
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(oldSignal?.aborted).toBe(true);
await act(async () => { resolveOld(childThread("Old session response")); });
- await user.click(screen.getByRole("button", { name: /Config check Running/ }));
- expect(await within(screen.getByRole("dialog")).findByText("Latest child response")).toBeVisible();
+ const nextList = await openTaskList(user);
+ await user.click(within(nextList).getByRole("button", { name: /Config check Running/ }));
+ const nextDetail = screen.getByRole("dialog");
+ expect(await within(nextDetail).findByText("Latest child response")).toBeVisible();
+ expect(within(nextDetail).queryByText("Old session response")).not.toBeInTheDocument();
});
it("shares history loading, actual failure details and keyboard retry with the main thread", async () => {
@@ -185,7 +625,8 @@ describe("session-owned task UI", () => {
}));
const user = userEvent.setup();
render(layout({ historyEnabled: true }));
- await user.click(await screen.findByRole("button", { name: /Config check Running/ }));
+ const list = await openTaskList(user);
+ await user.click(within(list).getByRole("button", { name: /Config check Running/ }));
const detail = screen.getByRole("dialog");
const loading = within(detail).getByRole("status");
expect(loading.querySelectorAll(".thread-history-blocks > span")).toHaveLength(9);
@@ -204,26 +645,28 @@ describe("session-owned task UI", () => {
expect(within(detail).queryByRole("status")).not.toBeInTheDocument();
});
- it("keeps the same work block under its prompt, folds completed work and restores it after refresh", async () => {
+ it("keeps the dock list open through an HTTP completion and restores saved results only in history", async () => {
+ const user = userEvent.setup();
const view = render(layout());
- const runningRow = await screen.findByRole("button", { name: /Config check Running/ });
- const work = runningRow.closest("section");
- const header = within(work!).getByRole("button", { name: /Subtasks/ });
- expect(screen.getByTestId("messages")).toContainElement(runningRow);
- expect(header).toHaveAttribute("aria-expanded", "true");
+ const list = await openTaskList(user);
+ const runningRow = within(list).getByRole("button", { name: /Config check Running/ });
+ const trigger = screen.getByTestId("subagent-task-dock-trigger");
vi.mocked(fetch).mockImplementation(async () => response([task({ revision: 2, state: "done", result: "Verified", completed_at: 102 })]));
fireEvent(window, new Event("focus"));
- await waitFor(() => expect(header).toHaveAttribute("aria-expanded", "false"));
- fireEvent.click(header);
- const row = screen.getByRole("button", { name: /Config check Completed/ });
+ const row = await within(list).findByRole("button", { name: /Config check Completed/ });
expect(row).toBe(runningRow);
- expect(row.closest("section")).toBe(work);
- expect(within(screen.getByTestId("composer")).queryByText("Config check")).not.toBeInTheDocument();
- expect(work).toHaveAccessibleName("Subtasks");
+ expect(trigger).toHaveAttribute("aria-expanded", "true");
+ expect(within(list).getByText("Verified")).toBeVisible();
+ expect(screen.getByTestId("messages")).not.toContainElement(row);
+ expect(screen.getByTestId("messages")).not.toHaveTextContent("Verified");
view.unmount();
+
render(layout());
- fireEvent.click(await screen.findByRole("button", { name: /Subtasks Finished: 1/ }));
- expect(screen.getByRole("button", { name: /Config check Completed/ })).toBeVisible();
+ const restoredArchive = await openArchive(user);
+ expect(screen.queryByTestId("subagent-task-dock-trigger")).not.toBeInTheDocument();
+ expect(screen.queryByTestId("subagent-task-tree")).not.toBeInTheDocument();
+ await user.click(within(restoredArchive).getByRole("button", { name: /Config check Completed/ }));
+ expect(within(screen.getByRole("dialog", { name: "Config check" })).getByText("Verified")).toBeVisible();
expect(requestMutation).not.toHaveBeenCalled();
});
@@ -234,8 +677,9 @@ describe("session-owned task UI", () => {
})]));
const user = userEvent.setup();
render(layout());
- await user.click(await screen.findByRole("button", { name: /Subtasks/ }));
- const row = await screen.findByRole("button", { name: /Config check Interrupted/ });
+ const archive = await openArchive(user);
+ expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
+ const row = within(archive).getByRole("button", { name: /Config check Interrupted/ });
await user.click(row);
const detail = screen.getByRole("dialog", { name: "Config check" });
expect(within(detail).getByText(/has not been restarted automatically/)).toBeVisible();
@@ -255,27 +699,47 @@ describe("session-owned task UI", () => {
requestMutation.mockImplementation(() => new Promise((resolve) => { resolveStop = resolve; }));
const user = userEvent.setup();
render(layout());
- await user.click(await screen.findByRole("button", { name: /Config check Running/ }));
- await user.keyboard("{Escape}");
- await user.click(screen.getByRole("button", { name: "Stop Config check" }));
+ const list = await openTaskList(user);
+ const activityStop = within(list).getByRole("button", { name: "Stop Config check" });
+ const row = within(list).getByRole("button", { name: /Config check Running/ });
+ await user.click(row);
+ const detail = screen.getByRole("dialog", { name: "Config check" });
+ const stop = within(detail).getByRole("button", { name: "Stop Config check" });
+ expect(within(detail).getByRole("heading", { name: "Config check" }).parentElement).toContainElement(stop);
+ expect(detail).toHaveAccessibleDescription("Running");
+ expect(within(detail).getByText("Running").parentElement).toHaveClass("sr-only");
+ expect(stop.querySelector('[data-action-icon="stop"][data-active] .loading-ring-arc')).toBeInTheDocument();
+ await user.click(stop);
+ expect(stop).toBeDisabled();
+ expect(stop).toHaveAttribute("aria-busy", "true");
+ expect(activityStop).toBeDisabled();
+ expect(activityStop).toHaveAttribute("aria-busy", "true");
vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { resolveRefresh = resolve; }));
fireEvent(window, new Event("focus"));
await waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
await act(async () => { resolveStop(task({ revision: 3, state: "cancelled", completed_at: 102 })); });
- await user.click(screen.getByRole("button", { name: /Subtasks Finished: 1/ }));
- await screen.findByRole("button", { name: /Config check Cancelled/ });
+ expect(screen.getByRole("dialog", { name: "Config check" })).toBe(detail);
+ expect(detail).toHaveTextContent("Cancelled");
await act(async () => { resolveRefresh(response([task()])); });
- expect(screen.queryByRole("button", { name: "Stop Config check" })).not.toBeInTheDocument();
+ expect(detail).toHaveTextContent("Cancelled");
+ expect(within(detail).queryByRole("button", { name: "Stop Config check" })).not.toBeInTheDocument();
+ await user.keyboard("{Escape}");
+ expect(within(list).getByRole("button", { name: /Config check Cancelled/ })).toBe(row);
+ expect(within(list).queryByRole("button", { name: "Stop Config check" })).not.toBeInTheDocument();
+ await waitFor(() => expect(row).toHaveFocus());
+ expect(requestMutation).toHaveBeenCalledTimes(1);
expect(requestMutation).toHaveBeenCalledWith("subagent.cancel", { session_key: "websocket:a", task_id: "task-1" }, 20_000);
});
it("does not request an unsupported feature and detaches events in hidden panes", async () => {
+ const user = userEvent.setup();
const view = render(layout({ enabled: false }));
expect(fetch).not.toHaveBeenCalled();
view.rerender(layout({ visible: false }));
expect(fetch).not.toHaveBeenCalled();
view.rerender(layout());
- fireEvent.click(await screen.findByRole("button", { name: /Config check Running/ }));
+ const list = await openTaskList(user);
+ await user.click(within(list).getByRole("button", { name: /Config check Running/ }));
expect(screen.getByRole("dialog", { name: "Config check" })).toBeVisible();
view.rerender(layout({ visible: false }));
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
@@ -285,24 +749,45 @@ describe("session-owned task UI", () => {
expect(statusHandlers.size).toBe(0);
});
+ it("reports a failed header stop and lets the user retry without closing details", async () => {
+ const user = userEvent.setup();
+ requestMutation.mockRejectedValueOnce(new Error("Cannot stop task"));
+ render(layout());
+ const list = await openTaskList(user);
+ await user.click(within(list).getByRole("button", { name: /Config check Running/ }));
+ const detail = screen.getByRole("dialog", { name: "Config check" });
+ const stop = within(detail).getByRole("button", { name: "Stop Config check" });
+ expect(within(detail).getByRole("heading", { name: "Config check" }).parentElement).toContainElement(stop);
+ await user.click(stop);
+ expect(await within(detail).findByRole("alert")).toHaveTextContent("Cannot stop task");
+ expect(stop).toBeEnabled();
+ requestMutation.mockResolvedValueOnce(task({ revision: 2, state: "cancelled", completed_at: 102 }));
+ await user.click(stop);
+ expect(screen.getByRole("dialog", { name: "Config check" })).toBe(detail);
+ expect(detail).toHaveTextContent("Cancelled");
+ expect(requestMutation).toHaveBeenCalledTimes(2);
+ });
+
it("preserves loaded tasks and stop errors across background snapshot failures", async () => {
const user = userEvent.setup();
requestMutation.mockRejectedValue(new Error("Cannot stop task"));
render(layout());
- await user.click(await screen.findByRole("button", { name: "Stop Config check" }));
- await screen.findByText("Cannot stop task");
+ const list = await openTaskList(user);
+ await user.click(within(list).getByRole("button", { name: "Stop Config check" }));
+ await within(list).findByText("Cannot stop task");
fireEvent(window, new Event("focus"));
await waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
- expect(screen.getByText("Cannot stop task")).toBeVisible();
+ expect(within(list).getByText("Cannot stop task")).toBeVisible();
vi.mocked(fetch).mockRejectedValue(new Error("offline"));
await act(async () => { fireEvent(window, new Event("focus")); });
- expect(screen.getByRole("button", { name: /Config check Running/ })).toBeVisible();
- expect(screen.getByText("Cannot stop task")).toBeVisible();
+ expect(within(list).getByRole("button", { name: /Config check Running/ })).toBeVisible();
+ expect(within(list).getByText("Cannot stop task")).toBeVisible();
});
it("retains the last valid snapshot after malformed reads and recovers on refresh", async () => {
+ const user = userEvent.setup();
render(layout());
- await screen.findByRole("button", { name: /Config check Running/ });
+ const list = await openTaskList(user);
vi.mocked(fetch).mockImplementation(async () => new Response(JSON.stringify({
tasks: [{ ...task(), label: { unexpected: true } }],
}), { headers: { "content-type": "application/json" } }));
@@ -314,16 +799,19 @@ describe("session-owned task UI", () => {
expect(screen.getByRole("button", { name: /Config check Running/ })).toBeVisible();
vi.mocked(fetch).mockResolvedValue(response([task({ revision: 2, state: "done", completed_at: 102 })]));
await act(async () => { fireEvent(window, new Event("focus")); });
- expect(screen.getByRole("button", { name: /Subtasks Finished: 1/ })).toBeVisible();
+ expect(within(list).getByRole("button", { name: /Config check Completed/ })).toBeVisible();
+ expect(screen.getByTestId("subagent-task-dock-trigger")).toHaveTextContent("Completed: 1");
});
it("discards reads from the previous session after switching", async () => {
let resolveOld!: (value: Response) => void;
vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve; }));
+ const user = userEvent.setup();
const view = render(layout());
vi.mocked(fetch).mockResolvedValue(response([task({ task_id: "task-b", label: "Other work" })]));
view.rerender(layout({ sessionKey: "websocket:b" }));
- await screen.findByRole("button", { name: /Other work Running/ });
+ const list = await openTaskList(user);
+ expect(within(list).getByRole("button", { name: /Other work Running/ })).toBeVisible();
await act(async () => { resolveOld(response([task()])); });
expect(screen.queryByText("Config check")).not.toBeInTheDocument();
});
@@ -331,7 +819,8 @@ describe("session-owned task UI", () => {
it("keeps task details open through completion and renders Markdown results", async () => {
const user = userEvent.setup();
render(layout());
- const row = await screen.findByRole("button", { name: /Config check Running/ });
+ const list = await openTaskList(user);
+ const row = within(list).getByRole("button", { name: /Config check Running/ });
await user.click(row);
const detail = screen.getByRole("dialog", { name: "Config check" });
vi.mocked(fetch).mockImplementation(async () => response([task({ revision: 2, state: "done", completed_at: 102,
@@ -341,44 +830,57 @@ describe("session-owned task UI", () => {
expect(await within(detail).findByRole("heading", { name: "Findings" })).toBeVisible();
expect(within(detail).getByRole("list")).toHaveTextContent("Release resources");
expect(within(detail).getByRole("table")).toHaveTextContent("CancellationPassed");
- expect(await within(detail).findByText("await connection.close()", { exact: false })).toBeVisible();
+ await waitFor(() => expect(detail.querySelector("code")).toHaveTextContent("await connection.close()"));
+ expect(detail.querySelector("code")).toBeVisible();
expect(within(detail).getByRole("link", { name: /Evidence/ })).toHaveAttribute("href", "https://example.com/review");
expect(detail).toBeVisible();
await user.keyboard("{Escape}");
- await waitFor(() => expect(screen.getByRole("button", { name: /Subtasks/ })).toHaveFocus());
+ expect(list).toBeVisible();
+ await waitFor(() => expect(row).toHaveFocus());
+ await user.keyboard("{Escape}");
+ expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
+ await waitFor(() => expect(screen.getByRole("textbox", { name: "Message" })).toHaveFocus());
+ expect(await screen.findByRole("region", { name: "Subtasks" })).toBeVisible();
expect(requestMutation).not.toHaveBeenCalled();
});
- it("anchors replay once when multiple prompts share a turn and preserves row order", async () => {
+ it("anchors terminal replay once when multiple prompts share a turn and preserves archive order", async () => {
const replay = [...messages, { id: "followup", role: "user", content: "Focus on errors", turnId: "turn-a", createdAt: 102_000 } satisfies UIMessage];
const keys = unitKeysForDisplay(buildDisplayUnits(replay));
expect(new Set(keys).size).toBe(keys.length);
vi.mocked(fetch).mockImplementation(async () => response([
task({ task_id: "second", label: "Second check", created_at: 101, origin_message_id: "old-prompt-id" }),
- task({ origin_message_id: "old-prompt-id" }),
+ task({ origin_message_id: "old-prompt-id", state: "done", completed_at: 102 }),
]));
+ const user = userEvent.setup();
render(layout({ threadMessages: replay }));
- await screen.findByRole("button", { name: /Config check Running/ });
+ const archive = await openArchive(user);
expect(screen.getAllByRole("region", { name: "Subtasks" })).toHaveLength(1);
- const rows = screen.getAllByRole("button", { name: /check Running/ });
- expect(rows.map((row) => row.dataset.subagentId)).toEqual(["task-1", "second"]);
+ expect(taskIds(archive)).toEqual(["task-1"]);
+ expect(within(archive).getByRole("button", { name: /Config check Completed/ })).toBeVisible();
+ expect(within(archive).queryByRole("button", { name: /Second check Running/ })).not.toBeInTheDocument();
vi.mocked(fetch).mockImplementation(async () => response([
- task({ task_id: "second", revision: 2, label: "Second check", created_at: 101, origin_message_id: "old-prompt-id", state: "error", error: "Unreadable file" }),
- task({ origin_message_id: "old-prompt-id" }),
+ task({ task_id: "second", revision: 2, label: "Second check", created_at: 101, origin_message_id: "old-prompt-id", state: "error", error: "Unreadable file", completed_at: 103 }),
+ task({ origin_message_id: "old-prompt-id", state: "done", completed_at: 102 }),
]));
fireEvent(window, new Event("focus"));
- await screen.findByRole("button", { name: /Second check Failed/ });
- expect(screen.getAllByRole("button", { name: /check (Running|Failed)/ }).map((row) => row.dataset.subagentId)).toEqual(["task-1", "second"]);
- expect(screen.getByRole("button", { name: /Review needed: 1/ })).toBeVisible();
- expect(screen.getByText("Main answer").compareDocumentPosition(screen.getByText("Second check")) & Node.DOCUMENT_POSITION_PRECEDING).toBeTruthy();
+ await within(archive).findByRole("button", { name: /Second check Failed/ });
+ expect(taskIds(archive)).toEqual(["task-1", "second"]);
+ expect(screen.getAllByRole("region", { name: "Subtasks" })).toHaveLength(1);
+ expect(within(archive).getByRole("button", { name: /Review needed: 1/ })).toBeVisible();
+ expect(screen.getByText("Main answer").compareDocumentPosition(archive) & Node.DOCUMENT_POSITION_PRECEDING).toBeTruthy();
+ expect(archive.compareDocumentPosition(screen.getByText("Focus on errors")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
});
- it("prefers the exact initiating follow-up over a turn fallback", async () => {
- vi.mocked(fetch).mockImplementation(async () => response([task({ origin_message_id: "followup" })]));
+ it("prefers the exact initiating follow-up over a turn fallback for archived results", async () => {
+ vi.mocked(fetch).mockImplementation(async () => response([task({ origin_message_id: "followup", state: "done", completed_at: 102 })]));
+ const user = userEvent.setup();
render(layout({ threadMessages: [...messages, { id: "followup", role: "user", content: "Check more", turnId: "turn-a", createdAt: 102_000 }] }));
- await screen.findByRole("button", { name: /Config check Running/ });
- const group = screen.getByRole("region", { name: "Subtasks" });
- expect(screen.getByText("Check more").compareDocumentPosition(group) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ const archive = await openArchive(user);
+ expect(within(archive).getByRole("button", { name: /Config check Completed/ })).toBeVisible();
+ expect(screen.getAllByRole("region", { name: "Subtasks" })).toHaveLength(1);
+ expect(screen.getByText("Check more").compareDocumentPosition(archive) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
});
it("keeps legacy work separate after refresh and preserves its disclosure through local history prepends", async () => {
@@ -389,12 +891,13 @@ describe("session-owned task UI", () => {
]));
const user = userEvent.setup();
const view = render(layout());
- await screen.findByRole("button", { name: /Config check Running/ });
+ await screen.findByTestId("subagent-task-dock-trigger");
const otherWork = screen.getByRole("region", { name: "Other tasks" });
const header = within(otherWork).getByRole("button", { name: /Other tasks/ });
expect(header).toHaveAttribute("aria-expanded", "false");
expect(otherWork.compareDocumentPosition(screen.getByText("Inspect config")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
- expect(within(screen.getByRole("region", { name: "Subtasks" })).queryByText("Nanjing weather")).not.toBeInTheDocument();
+ expect(screen.queryByRole("region", { name: "Subtasks" })).not.toBeInTheDocument();
+ expect(screen.getByTestId("messages")).not.toHaveTextContent("Config check");
await user.click(header);
expect(within(otherWork).getByText("These tasks have no matching request in the displayed messages.")).toBeVisible();
await user.click(within(otherWork).getByRole("button", { name: /Nanjing weather Completed/ }));
@@ -417,39 +920,50 @@ describe("session-owned task UI", () => {
expect(requestMutation).not.toHaveBeenCalled();
});
- it("reattaches work when its initiating prompt is loaded without duplicating it or closing details", async () => {
+ it("reattaches archived work when its prompt loads without duplicating it, closing details or losing focus", async () => {
vi.mocked(fetch).mockImplementation(async () => response([
- task({ task_id: "older", label: "Earlier check", origin_turn_id: "older-turn", origin_message_id: "older-prompt" }),
+ task({ task_id: "older", label: "Earlier check", state: "done", completed_at: 102, result: "Earlier finding", origin_turn_id: "older-turn", origin_message_id: "older-prompt" }),
task({ created_at: 200 }),
]));
const user = userEvent.setup();
const view = render(layout());
- const otherWork = await screen.findByRole("region", { name: "Other tasks" });
- await user.click(within(otherWork).getByRole("button", { name: /Earlier check Running/ }));
+ const otherWork = await openArchive(user, "Other tasks");
+ await user.click(within(otherWork).getByRole("button", { name: /Earlier check Completed/ }));
const detail = screen.getByRole("dialog", { name: "Earlier check" });
view.rerender(layout({ threadMessages: [
{ id: "older-prompt", role: "user", content: "Inspect earlier work", turnId: "older-turn", createdAt: 99_000 },
...messages,
] }));
expect(detail).toBeVisible();
+ expect(within(detail).getByText("Earlier finding")).toBeVisible();
await user.keyboard("{Escape}");
expect(screen.queryByRole("region", { name: "Other tasks" })).not.toBeInTheDocument();
- const row = screen.getByRole("button", { name: /Earlier check Running/ });
- expect(screen.getAllByRole("button", { name: /Earlier check Running/ })).toHaveLength(1);
- expect(screen.getByText("Inspect earlier work").compareDocumentPosition(row) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
- expect(screen.getByText("Inspect config").compareDocumentPosition(row) & Node.DOCUMENT_POSITION_PRECEDING).toBeTruthy();
+ const archive = screen.getByRole("region", { name: "Subtasks" });
+ const summary = within(archive).getByRole("button", { name: /Subtasks/ });
+ expect(summary).toHaveAttribute("aria-expanded", "true");
+ expect(taskIds(screen.getByTestId("messages"))).toEqual(["older"]);
+ expect(screen.getByText("Inspect earlier work").compareDocumentPosition(archive) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(screen.getByText("Inspect config").compareDocumentPosition(archive) & Node.DOCUMENT_POSITION_PRECEDING).toBeTruthy();
+ const row = within(archive).getByRole("button", { name: /Earlier check Completed/ });
await waitFor(() => expect(row).toHaveFocus());
+ expect(row).toBeVisible();
});
it("merges live work before the initial read without polling or rolling back completed work", async () => {
let resolveRead!: (value: Response) => void;
vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { resolveRead = resolve; }));
+ const user = userEvent.setup();
render(layout());
emitTask(task({ revision: 3, state: "done", result: "Verified", completed_at: 102 }));
emitTask(task({ task_id: "task-2", label: "Sibling check", created_at: 101 }));
- await screen.findByRole("button", { name: /Sibling check Running/ });
+ const list = await openTaskList(user);
+ expect(within(list).getByRole("button", { name: /Sibling check Running/ })).toBeVisible();
await act(async () => { resolveRead(response([task()])); });
- expect(screen.getByRole("button", { name: /Config check Completed/ })).toBeVisible();
+ expect(taskIds(list)).toEqual(["task-2"]);
+ expect(screen.getByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 1");
+ expect(screen.getByTestId("subagent-task-dock-trigger")).not.toHaveTextContent("Completed:");
+ const archive = await openArchive(user);
+ expect(within(archive).getByRole("button", { name: /Config check Completed/ })).toBeVisible();
expect(screen.getAllByRole("region", { name: "Subtasks" })).toHaveLength(1);
vi.useFakeTimers();
await act(async () => { vi.advanceTimersByTime(10_000); });
@@ -457,24 +971,30 @@ describe("session-owned task UI", () => {
expect(requestMutation).not.toHaveBeenCalled();
});
- it("keeps elapsed time consistent when inspecting a task long after its last event", async () => {
+ it("keeps elapsed time in task rows without repeating it in details", async () => {
vi.useFakeTimers();
vi.spyOn(performance, "now").mockImplementation(() => Date.now());
render(layout());
await act(async () => { await Promise.resolve(); });
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
- const row = screen.getByRole("button", { name: /Config check Running/ });
+ fireEvent.click(screen.getByTestId("subagent-task-dock-trigger"));
+ const row = within(screen.getByTestId("subagent-task-tree")).getByRole("button", { name: /Config check Running/ });
expect(row).toHaveTextContent("12s");
fireEvent.click(row);
- expect(screen.getByRole("dialog", { name: "Config check" })).toHaveTextContent("12s");
+ const detail = screen.getByRole("dialog", { name: "Config check" });
+ expect(detail).toHaveAccessibleDescription("Running");
+ expect(detail).not.toHaveTextContent("12s");
+ await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
+ expect(row).toHaveTextContent("13s");
expect(fetch).toHaveBeenCalledTimes(1);
vi.mocked(performance.now).mockRestore();
});
it("recovers missed siblings after reconnect even when an older read is still pending", async () => {
let resolveOld!: (value: Response) => void;
+ const user = userEvent.setup();
render(layout());
- await screen.findByRole("button", { name: /Config check Running/ });
+ const list = await openTaskList(user);
vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve; }));
fireEvent(window, new Event("focus"));
emitTask(task({ revision: 3, state: "cancelled", completed_at: 102 }));
@@ -483,11 +1003,12 @@ describe("session-owned task UI", () => {
]));
act(() => { statusHandlers.forEach((handler) => { handler("closed"); handler("open"); }); });
await act(async () => { resolveOld(response([task()])); });
- await screen.findByRole("button", { name: /Recovered check Running/ });
- expect(screen.getByRole("button", { name: /Config check Cancelled/ })).toBeVisible();
+ await within(list).findByRole("button", { name: /Recovered check Running/ });
+ expect(within(list).getByRole("button", { name: /Config check Cancelled/ })).toBeVisible();
+ expect(taskIds(list)).toEqual(["task-1", "task-2"]);
expect(fetch).toHaveBeenCalledTimes(3);
emitTask({ ...task(), revision: -1 });
- expect(screen.getByRole("button", { name: /Config check Cancelled/ })).toBeVisible();
+ expect(within(list).getByRole("button", { name: /Config check Cancelled/ })).toBeVisible();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
@@ -496,13 +1017,17 @@ describe("session-owned task UI", () => {
vi.useFakeTimers();
const view = render(layout({ liveEvents: false }));
await act(async () => { await Promise.resolve(); });
- expect(screen.getByRole("button", { name: /Config check Running/ })).toBeVisible();
+ expect(screen.getByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 1");
+ fireEvent.click(screen.getByTestId("subagent-task-dock-trigger"));
+ const list = screen.getByTestId("subagent-task-tree");
+ expect(within(list).getByRole("button", { name: /Config check Running/ })).toBeVisible();
vi.mocked(fetch).mockImplementation(async () => response([task({ revision: undefined, state: "done", completed_at: 102 })]));
await act(async () => { await vi.advanceTimersByTimeAsync(9000); });
expect(fetch).toHaveBeenCalledTimes(1);
expect(screen.getByRole("button", { name: /Config check Running/ })).toBeVisible();
await act(async () => { fireEvent(window, new Event("focus")); });
- expect(screen.getByRole("button", { name: /Subtasks Finished: 1/ })).toBeVisible();
+ expect(screen.getByTestId("subagent-task-dock-trigger")).toHaveTextContent("Completed: 1");
+ expect(within(list).getByRole("button", { name: /Config check Completed/ })).toBeVisible();
expect(client.onChat).not.toHaveBeenCalled();
view.rerender(layout({ liveEvents: false, visible: false }));
const reads = vi.mocked(fetch).mock.calls.length;
diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx
index 947b6725e..99378bbba 100644
--- a/webui/src/tests/thread-shell.test.tsx
+++ b/webui/src/tests/thread-shell.test.tsx
@@ -19,6 +19,7 @@ import type {
CliAppsPayload,
ConnectionStatus,
SettingsPayload,
+ SubagentTaskSnapshot,
ThreadProjectionEvent,
UIMessage,
WebuiThreadPersistedPayload,
@@ -544,6 +545,42 @@ describe("ThreadShell", () => {
expect(screen.getByRole("button", { name: "Stop response" })).toBeInTheDocument();
});
+ it("keeps the dock and task events alive after the parent response finishes", async () => {
+ const client = makeClient();
+ const snapshot: SubagentTaskSnapshot = {
+ task_id: "background-task", revision: 1, label: "Background inspection", task_description: "Inspect settings",
+ origin_turn_id: "parent-turn", origin_message_id: null, created_at: 100, completed_at: null,
+ state: "running", phase: "awaiting_model", elapsed_seconds: 2, iteration: 1, tool_events: [],
+ usage: null, receipts: {}, result: null, partial: false, stop_reason: null, error: null,
+ };
+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
+ if (String(input).endsWith("/subagents")) return httpJson({ tasks: [snapshot] });
+ if (String(input).includes("/webui-thread")) return httpJson(transcriptFromSimpleMessages([
+ { role: "user", content: "Delegate inspection", turnId: "parent-turn" },
+ ]));
+ return Response.json({}, { status: 404 });
+ }));
+ render(wrap(client, <ThreadShell session={session("background-work")} title="Background work" onToggleSidebar={() => {}} />,
+ null, "tok", ["webui.core.v1", "webui.subagents.v1", "webui.subagents.events.v1"]));
+ const trigger = await screen.findByTestId("subagent-task-dock-trigger");
+ act(() => client._emitChat("background-work", { event: "goal_status", chat_id: "background-work", turn_id: "parent-turn", status: "running", started_at: 100 }));
+ expect(screen.getByRole("button", { name: "Stop response" })).toBeVisible();
+ act(() => client._emitChat("background-work", { event: "turn_end", chat_id: "background-work", turn_id: "parent-turn" }));
+ expect(screen.queryByRole("button", { name: "Stop response" })).not.toBeInTheDocument();
+ expect(trigger).toHaveTextContent("Running: 1");
+ act(() => client._emitChat("background-work", { event: "user_message", chat_id: "background-work", turn_id: "next-turn", turn_seq: 1, starts_turn: true, text: "Continue with the next request" }));
+ expect(trigger).toHaveTextContent("Running: 1");
+ fireEvent.click(trigger);
+ const list = screen.getByTestId("subagent-task-tree");
+ expect(within(list).getByRole("button", { name: /Background inspection Running/ })).toBeVisible();
+ act(() => client._emitChat("background-work", { event: "subagent_task", chat_id: "background-work", task: {
+ ...snapshot, revision: 2, state: "done", completed_at: 103, result: "Inspection finished after the parent reply",
+ } }));
+ expect(trigger).toHaveTextContent("Completed: 1");
+ expect(await within(list).findByText("Inspection finished after the parent reply")).toBeVisible();
+ expect(list).toBeVisible();
+ });
+
it("renders one persisted task entry at the initiating prompt through the full shell", async () => {
const client = makeClient();
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
@@ -563,8 +600,9 @@ describe("ThreadShell", () => {
onToggleSidebar={() => {}} />, null, "tok", ["webui.core.v1", "webui.subagents.v1"]);
const view = render(shell());
await screen.findByText("Delegate inspection");
- fireEvent.click(await screen.findByRole("button", { name: /Subtasks Finished: 1/ }));
+ fireEvent.click(await screen.findByRole("button", { name: /Subtasks Completed: 1/ }));
const task = await screen.findByRole("button", { name: /Inspect settings Completed/ });
+ expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
await screen.findByText("Delegate inspection");
expect(screen.getAllByRole("button", { name: /Inspect settings/ })).toHaveLength(1);
expect(screen.getByTestId("thread-message-region")).toContainElement(task);
@@ -572,8 +610,9 @@ describe("ThreadShell", () => {
view.unmount();
render(shell());
await screen.findByText("Delegate inspection");
- fireEvent.click(await screen.findByRole("button", { name: /Subtasks Finished: 1/ }));
+ fireEvent.click(await screen.findByRole("button", { name: /Subtasks Completed: 1/ }));
await screen.findByRole("button", { name: /Inspect settings Completed/ });
+ expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
expect(client.sendMessage).not.toHaveBeenCalled();
});