feat(subagent): add session-owned task messaging and cancellation (#5985)
let's go!
This commit is contained in:
1 parent
f75470e72f
commit
6ff96f2a8f
93 files changed
+5632
-1156
No files matched your search
@@ -52,6 +52,7 @@ import {
|
||||
isReasoningOnlyAssistant,
|
||||
} from "@/lib/activity-timeline";
|
||||
import { useFileEditDisplayMode } from "@/hooks/useFileEditDisplayMode";
|
||||
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
|
||||
import { useLogoFallback } from "@/hooks/useLogoFallback";
|
||||
import { usePageVisibility } from "@/hooks/usePageVisibility";
|
||||
import { useThreadVisibility } from "@/hooks/useThreadVisibility";
|
||||
@@ -250,7 +251,7 @@ function FoldedAgentActivity({
|
||||
detailsId,
|
||||
}: AgentActivityClusterProps) {
|
||||
const { t } = useTranslation();
|
||||
const fileEditDisplayMode = useFileEditDisplayMode();
|
||||
const { activityMode, fileEditDisplayMode } = useLocalPreferences();
|
||||
const pageVisible = usePageVisibility();
|
||||
const threadVisible = useThreadVisibility();
|
||||
const activityMessages = useMemo(() => coalesceActivityMessages(messages), [messages]);
|
||||
@@ -288,12 +289,15 @@ function FoldedAgentActivity({
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
const wasTurnStreamingRef = useRef(isTurnStreaming);
|
||||
const wasTurnStreaming = wasTurnStreamingRef.current;
|
||||
/** Live work stays open; completed work briefly shows the done state, then tucks away. */
|
||||
/** Auto follows execution; expanded keeps details open unless manually collapsed. */
|
||||
const outerExpanded = expanded ?? (
|
||||
userToggledOuter
|
||||
? outerOpenLocal
|
||||
: isTurnStreaming || completionHoldOpen || (wasTurnStreaming && !isTurnStreaming)
|
||||
: activityMode === "expanded" || isTurnStreaming || completionHoldOpen || (wasTurnStreaming && !isTurnStreaming)
|
||||
);
|
||||
useEffect(() => {
|
||||
setUserToggledOuter(false);
|
||||
}, [activityMode]);
|
||||
const deferredTraceRefs = useMemo(
|
||||
() => Array.from(new Set(
|
||||
messages
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
import { createContext, useContext, useEffect, useId, useLayoutEffect, useRef, useState, type ComponentProps, type ReactNode } from "react";
|
||||
import { Bot, CheckCircle2, ChevronDown, ChevronRight, CircleAlert, CircleMinus, LoaderCircle, Square } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { SubagentThread } from "@/components/thread/SubagentThread";
|
||||
import { ThreadMessages } from "@/components/thread/ThreadMessages";
|
||||
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";
|
||||
}
|
||||
|
||||
interface TaskContext {
|
||||
tasks: ObservedSubagentTask[];
|
||||
loadError: string | null;
|
||||
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;
|
||||
}
|
||||
const TasksContext = createContext<TaskContext | null>(null);
|
||||
|
||||
interface SubagentTasksProviderProps {
|
||||
client: Pick<NanobotClient, "requestMutation" | "onChat" | "onStatus">;
|
||||
sessionKey: string | null;
|
||||
token: string;
|
||||
enabled: boolean;
|
||||
liveEvents: boolean;
|
||||
historyEnabled?: boolean;
|
||||
active?: boolean;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function SubagentTasksProvider({ client, sessionKey, token, enabled, liveEvents, historyEnabled = false, active = true, children }: SubagentTasksProviderProps) {
|
||||
const { t } = useTranslation("common");
|
||||
const pageVisible = usePageVisibility();
|
||||
const paneVisible = useThreadVisibility();
|
||||
const [tasks, setTasks] = useState<ObservedSubagentTask[]>([]);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [stoppingId, setStoppingId] = useState<string | null>(null);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
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 detailPanel = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
scopeGeneration.current += 1;
|
||||
setTasks([]);
|
||||
setSelectedId(null);
|
||||
setStoppingId(null);
|
||||
setLoadError(null);
|
||||
setStopError(null);
|
||||
return () => { scopeGeneration.current += 1; };
|
||||
}, [client, sessionKey]);
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => { mounted.current = false; };
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || !paneVisible) setSelectedId(null);
|
||||
}, [active, paneVisible]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !active || !pageVisible || !paneVisible || !sessionKey || !token) return;
|
||||
let cancelled = false;
|
||||
let refreshing = false;
|
||||
let refreshPending = false;
|
||||
const refresh = async () => {
|
||||
if (refreshing) { refreshPending = true; return; }
|
||||
refreshing = true;
|
||||
try {
|
||||
const payload = await fetchSubagentTasks(token, sessionKey);
|
||||
if (!cancelled) {
|
||||
setTasks((current) => mergeSubagentTasks(current, payload.tasks));
|
||||
setLoadError(null);
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) setLoadError(t("thread.subagents.loadFailed"));
|
||||
} finally {
|
||||
refreshing = false;
|
||||
if (refreshPending && !cancelled) {
|
||||
refreshPending = false;
|
||||
void refresh();
|
||||
}
|
||||
}
|
||||
};
|
||||
const unsubscribeChat = liveEvents ? client.onChat(sessionKey.slice("websocket:".length), (event) => {
|
||||
if (cancelled || event.event !== "subagent_task") return;
|
||||
if (!isSubagentTask(event.task)) {
|
||||
setLoadError(t("thread.subagents.loadFailed"));
|
||||
return;
|
||||
}
|
||||
setTasks((current) => mergeSubagentTasks(current, [event.task]));
|
||||
}) : undefined;
|
||||
const unsubscribeStatus = liveEvents ? client.onStatus((status) => {
|
||||
if (status === "open") void refresh();
|
||||
}) : undefined;
|
||||
if (!refreshing) void refresh();
|
||||
// Protocol 1 hosts may support task reads without the optional event stream.
|
||||
const timer = liveEvents ? undefined : window.setInterval(() => void refresh(), 3000);
|
||||
const focus = () => void refresh();
|
||||
window.addEventListener("focus", focus);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
window.clearInterval(timer);
|
||||
unsubscribeChat?.();
|
||||
unsubscribeStatus?.();
|
||||
window.removeEventListener("focus", focus);
|
||||
};
|
||||
}, [client, enabled, liveEvents, active, sessionKey, token, pageVisible, paneVisible, t]);
|
||||
|
||||
const stop = async (task: SubagentTaskSnapshot) => {
|
||||
if (!sessionKey) return;
|
||||
const generation = scopeGeneration.current;
|
||||
setStoppingId(task.task_id);
|
||||
setStopError(null);
|
||||
try {
|
||||
const next = await cancelSubagentTask(client, sessionKey, task.task_id);
|
||||
if (!mounted.current || generation !== scopeGeneration.current) return;
|
||||
setTasks((current) => mergeSubagentTasks(current, [next]));
|
||||
} catch (reason) {
|
||||
if (mounted.current && generation === scopeGeneration.current) setStopError(reason instanceof Error ? reason.message : t("thread.subagents.stopFailed"));
|
||||
} finally {
|
||||
if (mounted.current && generation === scopeGeneration.current) setStoppingId(null);
|
||||
}
|
||||
};
|
||||
const selected = enabled && active && paneVisible ? tasks.find((task) => task.task_id === selectedId) : undefined;
|
||||
const value: TaskContext = {
|
||||
tasks: enabled ? tasks : [], loadError: enabled ? loadError : null,
|
||||
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);
|
||||
},
|
||||
};
|
||||
|
||||
return <TasksContext.Provider value={value}>
|
||||
{children}
|
||||
<Sheet open={!!selected} onOpenChange={(open) => { if (!open) setSelectedId(null); }}>
|
||||
<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 hover:bg-muted"
|
||||
onOpenAutoFocus={(event) => {
|
||||
event.preventDefault();
|
||||
detailPanel.current?.focus({ preventScroll: true });
|
||||
}}
|
||||
onCloseAutoFocus={(event) => {
|
||||
event.preventDefault();
|
||||
if (!active || !paneVisible) return;
|
||||
const target = trigger.current?.isConnected ? trigger.current
|
||||
: buttons.current.get(trigger.current?.dataset.subagentId ?? "");
|
||||
const focusTarget = target?.closest("[hidden]")
|
||||
? target.closest("[data-subagent-work]")?.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">{selected.state !== "done" ? "· " : null}<TaskElapsed task={selected} /></span></> : null}
|
||||
</SheetDescription>
|
||||
</div>
|
||||
{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)} />
|
||||
{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>
|
||||
{(["accepted", "delivered", "undelivered"] as const).map((receipt) => {
|
||||
const count = Object.values(selected.receipts).filter((entry) => entry === receipt).length;
|
||||
return count ? <p key={receipt}>{t(`thread.subagents.receipts.${receipt}`, { count })}</p> : null;
|
||||
})}
|
||||
</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)}><Square 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>;
|
||||
}
|
||||
|
||||
function TaskStateIcon({ task }: { task: SubagentTaskSnapshot }) {
|
||||
const className = "h-3.5 w-3.5 shrink-0";
|
||||
if (isActive(task)) return <LoaderCircle className={`${className} animate-spin motion-reduce:animate-none text-muted-foreground`} aria-hidden />;
|
||||
if (task.state === "done") return <CheckCircle2 className={`${className} text-emerald-600 dark:text-emerald-400`} aria-hidden />;
|
||||
if (task.state === "cancelled") return <CircleMinus className={`${className} text-muted-foreground`} aria-hidden />;
|
||||
return <CircleAlert className={`${className} text-destructive`} aria-hidden />;
|
||||
}
|
||||
|
||||
function TaskElapsed({ task }: { task: ObservedSubagentTask }) {
|
||||
const pageVisible = usePageVisibility();
|
||||
const paneVisible = useThreadVisibility();
|
||||
const [now, setNow] = useState(() => performance.now());
|
||||
const running = isActive(task);
|
||||
useEffect(() => {
|
||||
if (!running || !pageVisible || !paneVisible) return;
|
||||
setNow(performance.now());
|
||||
const timer = window.setInterval(() => setNow(performance.now()), 1000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [running, pageVisible, paneVisible]);
|
||||
return <>{Math.round(task.elapsed_seconds + (running ? Math.max(0, now - task.observedAtMs) / 1000 : 0))}s</>;
|
||||
}
|
||||
|
||||
function TaskButton({ task }: { task: ObservedSubagentTask }) {
|
||||
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);
|
||||
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 />
|
||||
</button>;
|
||||
}
|
||||
|
||||
export function useHasSubagentContent(): boolean {
|
||||
const context = useContext(TasksContext);
|
||||
return !!context && (context.tasks.length > 0 || !!context.loadError || !!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={<SubagentTaskErrors />} />;
|
||||
}
|
||||
|
||||
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">
|
||||
<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">
|
||||
<Bot className="h-3.5 w-3.5 shrink-0" aria-hidden />
|
||||
<span className="font-medium">{title}</span>
|
||||
<span className="ml-auto min-w-0 text-right">
|
||||
{summary}{activeCount ? ` · ${t("thread.subagents.running", { count: activeCount })}` : ""}
|
||||
{failedCount ? <span className="ml-2 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)}><Square className="h-3 w-3" aria-hidden /></Button> : null}
|
||||
</div>)}
|
||||
</div>
|
||||
</div>
|
||||
</section>;
|
||||
}
|
||||
|
||||
function SubagentTaskErrors() {
|
||||
const context = useContext(TasksContext);
|
||||
if (!context?.loadError && !context?.stopError) return null;
|
||||
return <div className="thread-message-row mt-2 space-y-1 text-xs text-destructive">
|
||||
{context.loadError ? <p role="alert">{context.loadError}</p> : null}
|
||||
{context.stopError ? <p role="alert">{context.stopError}</p> : null}
|
||||
</div>;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { LoaderCircle } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { ThreadMessages } from "@/components/thread/ThreadMessages";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { usePageVisibility } from "@/hooks/usePageVisibility";
|
||||
import { fetchSubagentThread } from "@/lib/api";
|
||||
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
|
||||
import { projectThreadEvents } from "@/lib/thread-event-projection";
|
||||
import type { SubagentTaskSnapshot, UIMessage, WebuiThreadPersistedPayload } from "@/lib/types";
|
||||
|
||||
interface SubagentThreadProps {
|
||||
token: string;
|
||||
sessionKey: string;
|
||||
task: SubagentTaskSnapshot;
|
||||
historyEnabled: boolean;
|
||||
isStreaming: boolean;
|
||||
}
|
||||
|
||||
export function SubagentThread({ token, sessionKey, task, historyEnabled, isStreaming }: SubagentThreadProps) {
|
||||
const { t } = useTranslation();
|
||||
const pageVisible = usePageVisibility();
|
||||
const [thread, setThread] = useState<WebuiThreadPersistedPayload | null>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const refreshRef = useRef<(() => void) | null>(null);
|
||||
const taskId = task.task_id;
|
||||
|
||||
useEffect(() => {
|
||||
if (!historyEnabled || !pageVisible) return;
|
||||
let cancelled = false;
|
||||
let refreshing = false;
|
||||
let pending = false;
|
||||
const controller = new AbortController();
|
||||
const refresh = async () => {
|
||||
if (refreshing) { pending = true; return; }
|
||||
refreshing = true;
|
||||
try {
|
||||
const payload = await fetchSubagentThread(token, sessionKey, taskId, controller.signal);
|
||||
if (!cancelled) { setThread(payload); setFailed(false); }
|
||||
} catch {
|
||||
if (!cancelled) setFailed(true);
|
||||
} finally {
|
||||
refreshing = false;
|
||||
if (pending && !cancelled) { pending = false; void refresh(); }
|
||||
}
|
||||
};
|
||||
refreshRef.current = () => { void refresh(); };
|
||||
return () => { cancelled = true; refreshRef.current = null; controller.abort(); };
|
||||
}, [historyEnabled, pageVisible, sessionKey, taskId, token]);
|
||||
|
||||
// Task revisions already arrive through the owning chat's event stream.
|
||||
useEffect(() => {
|
||||
refreshRef.current?.();
|
||||
}, [historyEnabled, pageVisible, sessionKey, taskId, task.revision, token]);
|
||||
|
||||
const messages = useMemo(() => {
|
||||
if (historyEnabled) return thread ? projectWebuiThreadMessages(projectThreadEvents(thread.events)) : [];
|
||||
// Protocol 1 hosts without history still expose a task description and result.
|
||||
const summary: UIMessage[] = [{ id: `${taskId}-description`, role: "user", content: task.task_description, createdAt: task.created_at * 1000 }];
|
||||
if (task.result) summary.push({ id: `${taskId}-result`, role: "assistant", content: task.result,
|
||||
createdAt: (task.completed_at ?? task.created_at) * 1000 });
|
||||
return summary;
|
||||
}, [historyEnabled, taskId, task.task_description, task.created_at, task.completed_at, task.result, thread]);
|
||||
|
||||
return <>
|
||||
{failed ? <div role="alert" className="mb-4 flex items-center gap-2 px-5 text-sm text-destructive">
|
||||
<span>{t("thread.history.error")}</span>
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => refreshRef.current?.()}>{t("thread.history.retry")}</Button>
|
||||
</div> : historyEnabled && thread === null ? <p role="status" className="flex items-center gap-2 px-5 text-sm text-muted-foreground">
|
||||
<LoaderCircle className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" aria-hidden />{t("chat.loading")}
|
||||
</p> : null}
|
||||
<ThreadMessages messages={messages} isStreaming={isStreaming} activeTurnId={thread?.active_turn_id}
|
||||
runStartedAt={task.created_at} />
|
||||
</>;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import { Fragment, memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
|
||||
import { MoreHorizontal } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { MessageBlockMenuActions, MessageBubble, MessageCopyButton } from "@/components/MessageBubble";
|
||||
@@ -14,6 +14,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover
|
||||
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useMediaQuery } from "@/hooks/useMediaQuery";
|
||||
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
|
||||
import { fmtDateTime, formatMessageHoverTime } from "@/lib/format";
|
||||
import { projectActivityTimeline, type TurnUnit } from "@/lib/activity-timeline";
|
||||
import { cn } from "@/lib/utils";
|
||||
@@ -21,6 +22,9 @@ import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage }
|
||||
|
||||
interface ThreadMessagesProps {
|
||||
messages: UIMessage[];
|
||||
beforeMessages?: ReactNode;
|
||||
afterUserMessage?: (message: UIMessage) => ReactNode;
|
||||
afterMessages?: ReactNode;
|
||||
temporary?: boolean;
|
||||
/** When true, agent turn still in flight — keeps activity timeline expanded. */
|
||||
isStreaming?: boolean;
|
||||
@@ -76,6 +80,9 @@ export function assistantForkFlags(units: DisplayUnit[]): boolean[] {
|
||||
|
||||
export function ThreadMessages({
|
||||
messages,
|
||||
beforeMessages,
|
||||
afterUserMessage,
|
||||
afterMessages,
|
||||
temporary = false,
|
||||
isStreaming = false,
|
||||
activeTurnId = null,
|
||||
@@ -94,6 +101,7 @@ export function ThreadMessages({
|
||||
onActivityToggle,
|
||||
}: ThreadMessagesProps) {
|
||||
const { t } = useTranslation();
|
||||
const { activityMode } = useLocalPreferences();
|
||||
const messageListRef = useRef<HTMLDivElement>(null);
|
||||
const mobileActions = useMediaQuery("(max-width: 767px)");
|
||||
const units = useMemo(
|
||||
@@ -135,17 +143,19 @@ export function ThreadMessages({
|
||||
),
|
||||
[activeTurnId, currentTurnStartIndex, isStreaming, unitKeys, units],
|
||||
);
|
||||
const [expandedActivityKeys, setExpandedActivityKeys] = useState<Set<string>>(() => new Set());
|
||||
const [activityOverrides, setActivityOverrides] = useState<Map<string, boolean>>(() => new Map());
|
||||
useEffect(() => {
|
||||
setActivityOverrides(new Map());
|
||||
}, [activityMode]);
|
||||
const [activeContextBlockKey, setActiveContextBlockKey] = useState<string | null>(null);
|
||||
const [openContextBlockKey, setOpenContextBlockKey] = useState<string | null>(null);
|
||||
const pointedContextBlockRef = useRef<string | null>(null);
|
||||
const setActivityExpanded = useCallback((key: string, expanded: boolean) => {
|
||||
onActivityToggle?.();
|
||||
setExpandedActivityKeys((current) => {
|
||||
if (current.has(key) === expanded) return current;
|
||||
const next = new Set(current);
|
||||
if (expanded) next.add(key);
|
||||
else next.delete(key);
|
||||
setActivityOverrides((current) => {
|
||||
if (current.get(key) === expanded) return current;
|
||||
const next = new Map(current);
|
||||
next.set(key, expanded);
|
||||
return next;
|
||||
});
|
||||
}, [onActivityToggle]);
|
||||
@@ -171,6 +181,7 @@ export function ThreadMessages({
|
||||
containerRef={messageListRef}
|
||||
onQuoteSelection={onQuoteSelection}
|
||||
/>
|
||||
{beforeMessages}
|
||||
{units.map((unit, index) => {
|
||||
const next = units[index + 1];
|
||||
const hasBodyBelow =
|
||||
@@ -193,7 +204,7 @@ export function ThreadMessages({
|
||||
: marginAfterPrevUnit(units[previousVisibleIndex]);
|
||||
const blockActivityExpanded = showBlockContext
|
||||
&& contextBlockKey !== undefined
|
||||
&& expandedActivityKeys.has(contextBlockKey);
|
||||
&& (activityOverrides.get(contextBlockKey) ?? activityMode === "expanded");
|
||||
const deferOffscreenRender =
|
||||
index < units.length - 1
|
||||
&& (
|
||||
@@ -223,6 +234,7 @@ export function ThreadMessages({
|
||||
) nextUserIndex += 1;
|
||||
|
||||
return (
|
||||
<Fragment key={unitKeys[index]}>
|
||||
<ThreadDisplayUnit
|
||||
key={unitKeys[index]}
|
||||
unitKey={unitKeys[index]}
|
||||
@@ -264,8 +276,13 @@ export function ThreadMessages({
|
||||
onContextBlockFocusChange={setContextBlockFocused}
|
||||
onContextBlockMenuOpenChange={setContextBlockMenuOpen}
|
||||
/>
|
||||
{unit.type === "message" && unit.message.role === "user" ? (
|
||||
afterUserMessage?.(unit.message)
|
||||
) : null}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
{afterMessages}
|
||||
{pendingActivity ? (
|
||||
<div className={cn("thread-message-row", units.length > 0 && "mt-5")}>
|
||||
<AgentActivityCluster
|
||||
@@ -908,10 +925,10 @@ export function unitKeysForDisplay(units: DisplayUnit[]): string[] {
|
||||
const occurrences = new Map<string, number>();
|
||||
return units.map((unit, index) => {
|
||||
const base = unitKeyBase(unit, index);
|
||||
if (!base.startsWith("turn-") || base.endsWith("-user")) return base;
|
||||
if (!base.startsWith("turn-")) return base;
|
||||
const next = (occurrences.get(base) ?? 0) + 1;
|
||||
occurrences.set(base, next);
|
||||
return `${base}-${next}`;
|
||||
return base.endsWith("-user") && next === 1 ? base : `${base}-${next}`;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import { SessionHandleLabel } from "@/components/SessionHandleLabel";
|
||||
import { PromptNavigator } from "@/components/thread/PromptNavigator";
|
||||
import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";
|
||||
import { RecoveryNotice } from "@/components/thread/RecoveryNotice";
|
||||
import { SubagentTasksProvider } from "@/components/thread/SubagentTasks";
|
||||
import { SessionInfoPopover } from "@/components/thread/SessionInfoPopover";
|
||||
import type { ComposerDraftStore } from "@/lib/composer-draft";
|
||||
import { ThreadComposer } from "@/components/thread/ThreadComposer";
|
||||
@@ -696,7 +697,7 @@ export function ThreadShell({
|
||||
version: historyVersion,
|
||||
forkBoundaryMessageCount,
|
||||
} = useSessionHistory(historyKey);
|
||||
const { client, getToken, ingressLimits, modelName, token } = useClient();
|
||||
const { client, getToken, ingressLimits, modelName, token, webuiCapabilities } = useClient();
|
||||
const pickWorkspaceFolder = useCallback(async (): Promise<string | null> => {
|
||||
const response = await client.requestMutation<{ path: unknown }>(
|
||||
"workspace.pick_folder",
|
||||
@@ -1879,6 +1880,12 @@ export function ThreadShell({
|
||||
) : null;
|
||||
|
||||
return (
|
||||
<SubagentTasksProvider client={client} token={token}
|
||||
sessionKey={session?.key ?? null}
|
||||
liveEvents={webuiCapabilities.includes("webui.subagents.events.v1")}
|
||||
historyEnabled={webuiCapabilities.includes("webui.subagents.history.v1")}
|
||||
active={composerActive}
|
||||
enabled={!temporary && !!session?.key.startsWith("websocket:") && webuiCapabilities.includes("webui.subagents.v1")}>
|
||||
<section ref={shellRef} data-preview-open={previewOpen || undefined} className="thread-preview-layout relative flex min-h-0 flex-1 overflow-hidden">
|
||||
<div className={cn(
|
||||
"thread-conversation relative flex min-w-0 flex-1 flex-col overflow-hidden",
|
||||
@@ -1977,5 +1984,6 @@ export function ThreadShell({
|
||||
</FileActionsProvider>
|
||||
) : null}
|
||||
</section>
|
||||
</SubagentTasksProvider>
|
||||
);
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import { ArrowDown } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { PromptRail } from "@/components/thread/PromptRail";
|
||||
import { ThreadMessages } from "@/components/thread/ThreadMessages";
|
||||
import { SubagentThreadMessages, useHasSubagentContent } from "@/components/thread/SubagentTasks";
|
||||
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
|
||||
import { isAgentActivityMember } from "@/components/thread/AgentActivityCluster";
|
||||
import { ThreadCameraController } from "@/components/thread/thread-camera";
|
||||
@@ -344,7 +344,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
onAutoFollow: () => setAtBottom(true),
|
||||
});
|
||||
}
|
||||
const hasMessages = messages.length > 0;
|
||||
const hasTaskContent = useHasSubagentContent();
|
||||
const hasMessages = messages.length > 0 || (hasTaskContent && conversationReady);
|
||||
useLayoutEffect(() => {
|
||||
scrollRef.current = hasMessages
|
||||
? messageRegionRef.current
|
||||
@@ -973,7 +974,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
)}
|
||||
>
|
||||
<div ref={messageContentRef} className="w-full">
|
||||
<ThreadMessages
|
||||
<SubagentThreadMessages
|
||||
messages={visibleMessages}
|
||||
temporary={temporary}
|
||||
isStreaming={isStreaming}
|
||||
|
||||
@@ -88,7 +88,9 @@ export function parseGenericToolTrace(line: string): GenericToolTrace | null {
|
||||
const call = parseCall(line);
|
||||
if (!call || isExcludedTool(call.name)) return null;
|
||||
const family = toolFamily(call.name);
|
||||
const fields = safeFields(call.args);
|
||||
const fields: ToolField[] = call.name === "subagent" && typeof call.args === "string"
|
||||
? [{ key: "action", value: call.args.trim() }]
|
||||
: safeFields(call.args);
|
||||
if (call.name === "rg" && call.args && typeof call.args === "object") {
|
||||
const argv = (call.args as Record<string, unknown>).args;
|
||||
if (Array.isArray(argv) && argv.every((arg) => typeof arg === "string")) {
|
||||
@@ -98,12 +100,14 @@ export function parseGenericToolTrace(line: string): GenericToolTrace | null {
|
||||
}
|
||||
}
|
||||
const collectedSource = fields.some((field) => isCollectedSourcePath(field.value));
|
||||
let groupKey = family === "generic"
|
||||
? `${family}:${call.name}`
|
||||
: `${family}:${collectedSource ? "collected" : "workspace"}`;
|
||||
if (call.name === "subagent") groupKey += `:${fields.find((field) => field.key === "action")?.value.toLowerCase() ?? ""}`;
|
||||
return {
|
||||
name: call.name,
|
||||
family,
|
||||
groupKey: family === "generic"
|
||||
? `${family}:${call.name}`
|
||||
: `${family}:${collectedSource ? "collected" : "workspace"}`,
|
||||
groupKey,
|
||||
fields,
|
||||
collectedSource,
|
||||
};
|
||||
@@ -256,6 +260,12 @@ function activityLabel(
|
||||
return activityStatus(t, status, "generatingImage", "generatedImage", "generateImageFailed");
|
||||
case "spawn":
|
||||
return activityStatus(t, status, "delegatingTask", "delegatedTask", "delegateTaskFailed");
|
||||
case "subagent":
|
||||
if (action === "create") return activityStatus(t, status, "delegatingTask", "delegatedTask", "delegateTaskFailed");
|
||||
if (action === "check") return activityStatus(t, status, "checkingSubtask", "checkedSubtask", "checkSubtaskFailed");
|
||||
if (action === "send") return activityStatus(t, status, "messagingSubtask", "queuedSubtaskMessage", "messageSubtaskFailed");
|
||||
if (action === "cancel") return activityStatus(t, status, "stoppingSubtask", "requestedSubtaskStop", "stopSubtaskFailed");
|
||||
return activityStatus(t, status, "managingSubtasks", "managedSubtasks", "manageSubtasksFailed");
|
||||
case "message":
|
||||
return activityStatus(t, status, "sendingMessage", "sentMessage", "sendMessageFailed");
|
||||
case "my":
|
||||
@@ -311,6 +321,7 @@ function activityDetail(items: GenericToolRunItem[], family: ToolFamily, name: s
|
||||
|
||||
switch (name) {
|
||||
case "spawn":
|
||||
case "subagent":
|
||||
return safeText(fieldValue(trace, "label"));
|
||||
case "message":
|
||||
return safeText(fieldValue(trace, "channel"));
|
||||
|
||||
Reference in new issue
Block a user