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( ? : parameters.get("case") === "loaded-session-search" ? + : parameters.get("case") === "subagent-dock" + ? : parameters.get("case") === "attachments" ? : 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((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) { + 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 (action: string, payload?: Record): Promise => { + 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(null); + const timers = useRef([]); + 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 +
+ + {}} 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") ?
: null} +
+
; +} 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("[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: '', + })); + 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 ; +} + +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(null); + const ownedPointerDown = useRef(null); + const trigger = useRef(null); + const panel = useRef(null); + const content = useRef(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(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
{ ownedPointerDown.current = event.nativeEvent; }}> +
+ + + + +
+
; +} + +function TaskTree({ tasks, maxHeight }: { tasks: ObservedSubagentTask[]; maxHeight: number }) { + const { t } = useTranslation("common"); + const context = useSubagentTasks()!; + return
+
    + {tasks.map(task =>
  1. +
    + + {task.state === "queued" || task.state === "running" ? + + : null} +
    + {isActiveSubagentTask(task) && task.tool_events.length ?
      + {task.tool_events.map((tool, index) =>
    • + {tool.status === "error" ? + : } + {tool.name} +
    • )} +
    : null} + {task.error ?

    {task.error}

    + : task.state === "done" && task.result ?
    + {task.result} +
    : null} +
  2. )} +
+ {context.stopError ?

{context.stopError}

: null} +
; +} 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(); + const firstPromptByTurn = new Map(); + 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(); + 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) { + const context = useSubagentTasks(); + return ; +} + +function ResultsThreadMessages({ tasks, ...props }: ComponentProps & { tasks: ObservedSubagentTask[] }) { + const groups = useMemo(() => groupResults(props.messages, tasks), [props.messages, tasks]); + const [expandedTaskIds, setExpandedTaskIds] = useState>(() => 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 + {props.beforeMessages} + toggle(groups.unlinked)} /> + : props.beforeMessages} + afterUserMessage={(message) => { + const results = groups.byMessage.get(message.id); + return <> + {props.afterUserMessage?.(message)} + {results ? 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
+ + +
; +} 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; - register: (id: string, button: HTMLButtonElement | null, previous: HTMLButtonElement | null) => void; + register: (key: string, button: HTMLButtonElement | null, previous: HTMLButtonElement | null) => void; } const TasksContext = createContext(null); +export function useSubagentTasks() { + return useContext(TasksContext); +} + interface SubagentTasksProviderProps { client: Pick; sessionKey: string | null; @@ -61,8 +61,8 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live const [stopError, setStopError] = useState(null); const scopeGeneration = useRef(0); const mounted = useRef(true); - const buttons = useRef(new Map()); const trigger = useRef(null); + const buttons = useRef(new Map()); const detailPanel = useRef(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 { 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("[aria-expanded]") : target; + ? target.closest("[data-subagent-results]")?.querySelector("[aria-expanded]") : target; focusTarget?.focus({ preventScroll: true }); }}> -
- {selected?.label} - - {selected ? <> - {t(`thread.subagents.states.${selected.state}`)} - : null} +
+ {selected?.label} + + {selected ? <> + {selected.state !== "done" && selected.state !== "running" ? : null} + {t(`thread.subagents.states.${selected.state}`)} + : null} + {selected && canStopSelected ? + + : null}
+ {canStopSelected && stopError ?

{stopError}

: null} {selected && sessionKey ?
{selected.state === "interrupted" || selected.error ?
{selected.state === "interrupted" ?

{t("thread.subagents.interruptedHelp")}

: null} {selected.error ?

{selected.error}

: null}
: null} + task={selected} historyEnabled={historyEnabled} isStreaming={isActiveSubagentTask(selected)} /> {Object.keys(selected.receipts).length ?
{t("thread.subagents.messages")}

{t("thread.subagents.receiptHelp")}

@@ -195,11 +207,6 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live })}
: null}
: null} - {selected && (selected.state === "queued" || selected.state === "running") ?
- - {stopError ?

{stopError}

: null} -
: null} ; @@ -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 ; + if (task.state === "done") return ; 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 ; + const tone = task.state === "error" || task.state === "incomplete" ? "text-destructive" : "text-muted-foreground"; + return ; } 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(null); - return ; } - -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(); - 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) { - const groups = useSubagentTaskGroups(props.messages); - return } - afterUserMessage={(message) => } - afterMessages={} />; -} - -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(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
-
- - -
-
; -} - -function SubagentStopError() { - const context = useContext(TasksContext); - if (!context?.stopError) return null; - return
-

{context.stopError}

-
; -} 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 ? (

{restoredFirstDraft.error}

) : null} + {session ? ( 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(() => ({ + 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 { 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 { + 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 {useHasSubagentResults() ? "yes" : "no"}; +} +function layout({ threadMessages = messages, liveEvents = true, historyEnabled = false, onActivityToggle }: { + threadMessages?: UIMessage[]; + liveEvents?: boolean; + historyEnabled?: boolean; + onActivityToggle?: () => void; +} = {}) { + return + +
+