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

This commit is contained in:
chengyongru authored and GitHub committed 2026-10-26 13:16:44 +08:00
1 parent 9270137d65
commit 9b3af7b66c
27 files changed
+2265 -234

No files matched your search

@@ -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>;
}
@@ -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>;
}
+59 -130
View File
@@ -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>;
}
@@ -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}`}
@@ -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
@@ -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 : [],
};
}),
};
}
+15
View File
@@ -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) {
+1
View File
@@ -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"
},
+1
View File
@@ -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"
},
+1
View File
@@ -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"
},
+1
View File
@@ -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"
},
+1
View File
@@ -1808,6 +1808,7 @@
"progress": "{{total}} 件中 {{completed}} 件完了",
"running": "実行中: {{count}}",
"finished": "終了: {{count}}",
"completed": "完了: {{count}}",
"needsReview": "要確認: {{count}}",
"messages": "メッセージの状態"
},
+1
View File
@@ -1808,6 +1808,7 @@
"progress": "{{total}}개 중 {{completed}}개 완료",
"running": "진행 중: {{count}}",
"finished": "종료: {{count}}",
"completed": "완료: {{count}}",
"needsReview": "확인 필요: {{count}}",
"messages": "메시지 상태"
},
+1
View File
@@ -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"
},
+1
View File
@@ -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"
},
+1
View File
@@ -2014,6 +2014,7 @@
"progress": "已完成 {{completed}} / {{total}} 项",
"running": "{{count}} 项进行中",
"finished": "{{count}} 项已结束",
"completed": "{{count}} 项已完成",
"needsReview": "{{count}} 项需检查",
"messages": "消息状态"
},
+1
View File
@@ -1808,6 +1808,7 @@
"progress": "已完成 {{completed}} / {{total}} 項",
"running": "{{count}} 項進行中",
"finished": "{{count}} 項已結束",
"completed": "{{count}} 項已完成",
"needsReview": "{{count}} 項需檢查",
"messages": "訊息狀態"
},
+15 -1
View File
@@ -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);
}
+6 -2
View File
@@ -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();
+292
View File
@@ -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();
});
});
+618 -93
View File
@@ -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("applies the browser activity preference to delegated work and its shared child chat", async () => {
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 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;
+41 -2
View File
@@ -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();
});