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
@@ -116,8 +116,14 @@ type BootState =
|
||||
modelName: string | null;
|
||||
ingressLimits: BootstrapResponse["limits"] | null;
|
||||
runtimeSurface: RuntimeSurface;
|
||||
webuiCapabilities: string[];
|
||||
};
|
||||
|
||||
function bootstrapCapabilities(boot: BootstrapResponse): string[] {
|
||||
const capabilities = boot.terminal?.webui?.capabilities;
|
||||
return Array.isArray(capabilities) ? capabilities.filter((entry) => typeof entry === "string") : [];
|
||||
}
|
||||
|
||||
const SIDEBAR_STORAGE_KEY = "nanobot-webui.sidebar";
|
||||
const SESSION_UPDATES_STORAGE_KEY = "nanobot-webui.sidebar.session-updates.v1";
|
||||
const LEGACY_COMPLETED_RUNS_STORAGE_KEY = "nanobot-webui.sidebar.completed-runs.v1";
|
||||
@@ -924,6 +930,7 @@ export default function App() {
|
||||
modelName: boot.model_name ?? current.modelName,
|
||||
ingressLimits: boot.limits ?? current.ingressLimits,
|
||||
runtimeSurface,
|
||||
webuiCapabilities: bootstrapCapabilities(boot),
|
||||
}
|
||||
: current,
|
||||
);
|
||||
@@ -971,6 +978,7 @@ export default function App() {
|
||||
modelName: boot.model_name ?? null,
|
||||
ingressLimits: boot.limits ?? null,
|
||||
runtimeSurface,
|
||||
webuiCapabilities: bootstrapCapabilities(boot),
|
||||
});
|
||||
} catch (e) {
|
||||
if (cancelled) return;
|
||||
@@ -1090,6 +1098,7 @@ export default function App() {
|
||||
token={state.token}
|
||||
modelName={state.modelName}
|
||||
ingressLimits={state.ingressLimits}
|
||||
webuiCapabilities={state.webuiCapabilities}
|
||||
>
|
||||
<RemoteInstances><Shell
|
||||
runtimeSurface={state.runtimeSurface}
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -62,6 +62,7 @@ interface SheetContentProps
|
||||
VariantProps<typeof sheetVariants> {
|
||||
closeButtonClassName?: string;
|
||||
showCloseButton?: boolean;
|
||||
overlayClassName?: string;
|
||||
}
|
||||
|
||||
const SheetContent = React.forwardRef<
|
||||
@@ -74,6 +75,7 @@ const SheetContent = React.forwardRef<
|
||||
children,
|
||||
closeButtonClassName,
|
||||
showCloseButton = true,
|
||||
overlayClassName,
|
||||
...props
|
||||
},
|
||||
ref,
|
||||
@@ -81,7 +83,7 @@ const SheetContent = React.forwardRef<
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetOverlay className={overlayClassName} />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
|
||||
@@ -1,37 +1,6 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import {
|
||||
LOCAL_PREFS_CHANGED_EVENT,
|
||||
normalizeFileEditDisplayMode,
|
||||
readLocalPreferences,
|
||||
type FileEditDisplayMode,
|
||||
type LocalPreferences,
|
||||
} from "@/lib/local-preferences";
|
||||
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
|
||||
import type { FileEditDisplayMode } from "@/lib/local-preferences";
|
||||
|
||||
export function useFileEditDisplayMode(): FileEditDisplayMode {
|
||||
const [mode, setMode] = useState<FileEditDisplayMode>(() =>
|
||||
readLocalPreferences().fileEditDisplayMode,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const refresh = () => setMode(readLocalPreferences().fileEditDisplayMode);
|
||||
const refreshFromLocalPreferenceEvent = (event: Event) => {
|
||||
const detail = (event as CustomEvent<Partial<LocalPreferences> | undefined>).detail;
|
||||
setMode(
|
||||
detail
|
||||
? normalizeFileEditDisplayMode(detail.fileEditDisplayMode)
|
||||
: readLocalPreferences().fileEditDisplayMode,
|
||||
);
|
||||
};
|
||||
window.addEventListener("storage", refresh);
|
||||
window.addEventListener("focus", refresh);
|
||||
window.addEventListener(LOCAL_PREFS_CHANGED_EVENT, refreshFromLocalPreferenceEvent);
|
||||
return () => {
|
||||
window.removeEventListener("storage", refresh);
|
||||
window.removeEventListener("focus", refresh);
|
||||
window.removeEventListener(LOCAL_PREFS_CHANGED_EVENT, refreshFromLocalPreferenceEvent);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return mode;
|
||||
return useLocalPreferences().fileEditDisplayMode;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import {
|
||||
LOCAL_PREFS_CHANGED_EVENT,
|
||||
readLocalPreferences,
|
||||
type LocalPreferences,
|
||||
} from "@/lib/local-preferences";
|
||||
|
||||
export function useLocalPreferences(): LocalPreferences {
|
||||
const [preferences, setPreferences] = useState(readLocalPreferences);
|
||||
|
||||
useEffect(() => {
|
||||
const refresh = () => setPreferences(readLocalPreferences());
|
||||
const refreshFromEvent = (event: Event) => {
|
||||
const detail = (event as CustomEvent<LocalPreferences | undefined>).detail;
|
||||
setPreferences(detail ?? readLocalPreferences());
|
||||
};
|
||||
window.addEventListener("storage", refresh);
|
||||
window.addEventListener("focus", refresh);
|
||||
window.addEventListener(LOCAL_PREFS_CHANGED_EVENT, refreshFromEvent);
|
||||
return () => {
|
||||
window.removeEventListener("storage", refresh);
|
||||
window.removeEventListener("focus", refresh);
|
||||
window.removeEventListener(LOCAL_PREFS_CHANGED_EVENT, refreshFromEvent);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return preferences;
|
||||
}
|
||||
@@ -1761,6 +1761,36 @@
|
||||
"error": "Connection error"
|
||||
},
|
||||
"thread": {
|
||||
"subagents": {
|
||||
"loadFailed": "Could not load subtasks.",
|
||||
"stopFailed": "Could not stop this task.",
|
||||
"stopTask": "Stop {{label}}",
|
||||
"receiptHelp": "Delivered means the message was included in the subtask’s next model request. It does not mean the instructions have been carried out.",
|
||||
"states": {
|
||||
"queued": "Queued",
|
||||
"running": "Running",
|
||||
"stopping": "Stopping",
|
||||
"done": "Completed",
|
||||
"incomplete": "Incomplete",
|
||||
"error": "Failed",
|
||||
"cancelled": "Cancelled",
|
||||
"interrupted": "Interrupted"
|
||||
},
|
||||
"receipts": {
|
||||
"accepted": "Queued: {{count}}",
|
||||
"delivered": "Delivered: {{count}}",
|
||||
"undelivered": "Undelivered: {{count}}"
|
||||
},
|
||||
"interruptedHelp": "The host restarted before this task finished. It has not been restarted automatically.",
|
||||
"workTitle": "Delegated work",
|
||||
"otherWorkTitle": "Other delegated work",
|
||||
"unlinkedHelp": "These tasks have no matching request in the displayed messages.",
|
||||
"progress": "{{completed}} of {{total}} completed",
|
||||
"running": "Running: {{count}}",
|
||||
"finished": "Finished: {{count}}",
|
||||
"needsReview": "Review needed: {{count}}",
|
||||
"messages": "Message delivery"
|
||||
},
|
||||
"compaction": {
|
||||
"cancelled": "Context compaction cancelled",
|
||||
"empty": "Nothing to compact.",
|
||||
@@ -2136,9 +2166,21 @@
|
||||
"generatingImage": "Generating image",
|
||||
"generatedImage": "Generated image",
|
||||
"generateImageFailed": "Could not generate image",
|
||||
"delegatingTask": "Delegating task",
|
||||
"delegatedTask": "Delegated task",
|
||||
"delegateTaskFailed": "Could not delegate task",
|
||||
"delegatingTask": "Creating subtask",
|
||||
"delegatedTask": "Subtask created",
|
||||
"delegateTaskFailed": "Could not create subtask",
|
||||
"checkingSubtask": "Checking subtask status",
|
||||
"checkedSubtask": "Subtask status retrieved",
|
||||
"checkSubtaskFailed": "Could not check subtask status",
|
||||
"messagingSubtask": "Sending message to subtask",
|
||||
"queuedSubtaskMessage": "Message queued for subtask",
|
||||
"messageSubtaskFailed": "Could not send message to subtask",
|
||||
"stoppingSubtask": "Stopping subtask",
|
||||
"requestedSubtaskStop": "Stop request processed",
|
||||
"stopSubtaskFailed": "Could not stop subtask",
|
||||
"managingSubtasks": "Managing subtasks",
|
||||
"managedSubtasks": "Subtask operation complete",
|
||||
"manageSubtasksFailed": "Subtask operation failed",
|
||||
"sendingMessage": "Sending message",
|
||||
"sentMessage": "Sent message",
|
||||
"sendMessageFailed": "Could not send message",
|
||||
|
||||
@@ -1562,6 +1562,36 @@
|
||||
"error": "Error de conexión"
|
||||
},
|
||||
"thread": {
|
||||
"subagents": {
|
||||
"loadFailed": "No se pudieron cargar las subtareas.",
|
||||
"stopFailed": "No se pudo detener esta tarea.",
|
||||
"stopTask": "Detener {{label}}",
|
||||
"receiptHelp": "Entregado significa que el mensaje se incluyó en la siguiente solicitud del subagente, sin confirmar su ejecución.",
|
||||
"states": {
|
||||
"queued": "En cola",
|
||||
"running": "En curso",
|
||||
"stopping": "Deteniendo",
|
||||
"done": "Completada",
|
||||
"incomplete": "Incompleta",
|
||||
"error": "Fallida",
|
||||
"cancelled": "Cancelada",
|
||||
"interrupted": "Interrumpida"
|
||||
},
|
||||
"receipts": {
|
||||
"accepted": "En cola: {{count}}",
|
||||
"delivered": "Entregados: {{count}}",
|
||||
"undelivered": "Sin entregar: {{count}}"
|
||||
},
|
||||
"interruptedHelp": "El servidor se reinició antes de terminar esta tarea. No se ha vuelto a ejecutar automáticamente.",
|
||||
"workTitle": "Trabajo delegado",
|
||||
"otherWorkTitle": "Otros trabajos delegados",
|
||||
"unlinkedHelp": "No se encontró la solicitud correspondiente a estas tareas en los mensajes mostrados.",
|
||||
"progress": "{{completed}} de {{total}} completadas",
|
||||
"running": "En curso: {{count}}",
|
||||
"finished": "Finalizadas: {{count}}",
|
||||
"needsReview": "Revisar: {{count}}",
|
||||
"messages": "Estado de los mensajes"
|
||||
},
|
||||
"compaction": {
|
||||
"cancelled": "Compresión de contexto cancelada",
|
||||
"empty": "No hay contexto que comprimir.",
|
||||
@@ -1965,9 +1995,21 @@
|
||||
"generatingImage": "Generando imagen",
|
||||
"generatedImage": "Imagen generada",
|
||||
"generateImageFailed": "No se pudo generar la imagen",
|
||||
"delegatingTask": "Delegando tarea",
|
||||
"delegatedTask": "Tarea delegada",
|
||||
"delegateTaskFailed": "No se pudo delegar la tarea",
|
||||
"delegatingTask": "Creando subtarea",
|
||||
"delegatedTask": "Subtarea creada",
|
||||
"delegateTaskFailed": "No se pudo crear la subtarea",
|
||||
"checkingSubtask": "Consultando el estado de la subtarea",
|
||||
"checkedSubtask": "Estado de la subtarea consultado",
|
||||
"checkSubtaskFailed": "No se pudo consultar el estado de la subtarea",
|
||||
"messagingSubtask": "Enviando mensaje a la subtarea",
|
||||
"queuedSubtaskMessage": "Mensaje en cola para la subtarea",
|
||||
"messageSubtaskFailed": "No se pudo enviar el mensaje a la subtarea",
|
||||
"stoppingSubtask": "Deteniendo subtarea",
|
||||
"requestedSubtaskStop": "Solicitud de detención procesada",
|
||||
"stopSubtaskFailed": "No se pudo detener la subtarea",
|
||||
"managingSubtasks": "Gestionando subtareas",
|
||||
"managedSubtasks": "Operación de subtarea completada",
|
||||
"manageSubtasksFailed": "Falló la operación de subtarea",
|
||||
"sendingMessage": "Enviando mensaje",
|
||||
"sentMessage": "Mensaje enviado",
|
||||
"sendMessageFailed": "No se pudo enviar el mensaje",
|
||||
|
||||
@@ -1561,6 +1561,36 @@
|
||||
"error": "Erreur de connexion"
|
||||
},
|
||||
"thread": {
|
||||
"subagents": {
|
||||
"loadFailed": "Impossible de charger les sous-tâches.",
|
||||
"stopFailed": "Impossible d’arrêter cette tâche.",
|
||||
"stopTask": "Arrêter {{label}}",
|
||||
"receiptHelp": "Livré signifie que le message a été inclus dans la prochaine requête du sous-agent, sans confirmer son exécution.",
|
||||
"states": {
|
||||
"queued": "En attente",
|
||||
"running": "En cours",
|
||||
"stopping": "Arrêt en cours",
|
||||
"done": "Terminée",
|
||||
"incomplete": "Incomplète",
|
||||
"error": "Échec",
|
||||
"cancelled": "Annulée",
|
||||
"interrupted": "Interrompue"
|
||||
},
|
||||
"receipts": {
|
||||
"accepted": "En attente : {{count}}",
|
||||
"delivered": "Livrés : {{count}}",
|
||||
"undelivered": "Non livrés : {{count}}"
|
||||
},
|
||||
"interruptedHelp": "Le serveur a redémarré avant la fin de cette tâche. Elle n’a pas été relancée automatiquement.",
|
||||
"workTitle": "Travail délégué",
|
||||
"otherWorkTitle": "Autres travaux délégués",
|
||||
"unlinkedHelp": "Aucune demande correspondant à ces tâches ne figure dans les messages affichés.",
|
||||
"progress": "{{completed}} sur {{total}} terminées",
|
||||
"running": "En cours : {{count}}",
|
||||
"finished": "Terminées : {{count}}",
|
||||
"needsReview": "À vérifier : {{count}}",
|
||||
"messages": "État des messages"
|
||||
},
|
||||
"compaction": {
|
||||
"cancelled": "Compression du contexte annulée",
|
||||
"empty": "Aucun contexte à compresser.",
|
||||
@@ -1964,9 +1994,21 @@
|
||||
"generatingImage": "Génération de l’image",
|
||||
"generatedImage": "Image générée",
|
||||
"generateImageFailed": "Impossible de générer l’image",
|
||||
"delegatingTask": "Délégation de la tâche",
|
||||
"delegatedTask": "Tâche déléguée",
|
||||
"delegateTaskFailed": "Impossible de déléguer la tâche",
|
||||
"delegatingTask": "Création de la sous-tâche",
|
||||
"delegatedTask": "Sous-tâche créée",
|
||||
"delegateTaskFailed": "Impossible de créer la sous-tâche",
|
||||
"checkingSubtask": "Vérification de l’état de la sous-tâche",
|
||||
"checkedSubtask": "État de la sous-tâche obtenu",
|
||||
"checkSubtaskFailed": "Impossible de vérifier l’état de la sous-tâche",
|
||||
"messagingSubtask": "Envoi d’un message à la sous-tâche",
|
||||
"queuedSubtaskMessage": "Message mis en attente pour la sous-tâche",
|
||||
"messageSubtaskFailed": "Impossible d’envoyer un message à la sous-tâche",
|
||||
"stoppingSubtask": "Arrêt de la sous-tâche en cours",
|
||||
"requestedSubtaskStop": "Demande d’arrêt traitée",
|
||||
"stopSubtaskFailed": "Impossible d’arrêter la sous-tâche",
|
||||
"managingSubtasks": "Opération sur les sous-tâches en cours",
|
||||
"managedSubtasks": "Opération sur les sous-tâches terminée",
|
||||
"manageSubtasksFailed": "Échec de l’opération sur les sous-tâches",
|
||||
"sendingMessage": "Envoi du message",
|
||||
"sentMessage": "Message envoyé",
|
||||
"sendMessageFailed": "Impossible d’envoyer le message",
|
||||
|
||||
@@ -1561,6 +1561,36 @@
|
||||
"error": "Kesalahan koneksi"
|
||||
},
|
||||
"thread": {
|
||||
"subagents": {
|
||||
"loadFailed": "Tidak dapat memuat subtugas.",
|
||||
"stopFailed": "Tidak dapat menghentikan tugas ini.",
|
||||
"stopTask": "Hentikan {{label}}",
|
||||
"receiptHelp": "Terkirim berarti pesan disertakan dalam permintaan model berikutnya dari subagen, bukan konfirmasi bahwa pekerjaan selesai.",
|
||||
"states": {
|
||||
"queued": "Dalam antrean",
|
||||
"running": "Berjalan",
|
||||
"stopping": "Menghentikan",
|
||||
"done": "Selesai",
|
||||
"incomplete": "Belum selesai",
|
||||
"error": "Gagal",
|
||||
"cancelled": "Dibatalkan",
|
||||
"interrupted": "Terputus"
|
||||
},
|
||||
"receipts": {
|
||||
"accepted": "Dalam antrean: {{count}}",
|
||||
"delivered": "Terkirim: {{count}}",
|
||||
"undelivered": "Tidak terkirim: {{count}}"
|
||||
},
|
||||
"interruptedHelp": "Server dimulai ulang sebelum tugas ini selesai. Tugas tidak dijalankan ulang secara otomatis.",
|
||||
"workTitle": "Pekerjaan yang didelegasikan",
|
||||
"otherWorkTitle": "Pekerjaan lain yang didelegasikan",
|
||||
"unlinkedHelp": "Permintaan yang sesuai dengan tugas ini tidak ditemukan dalam pesan yang ditampilkan.",
|
||||
"progress": "{{completed}} dari {{total}} selesai",
|
||||
"running": "Berjalan: {{count}}",
|
||||
"finished": "Berakhir: {{count}}",
|
||||
"needsReview": "Perlu diperiksa: {{count}}",
|
||||
"messages": "Status pengiriman pesan"
|
||||
},
|
||||
"compaction": {
|
||||
"cancelled": "Pemadatan konteks dibatalkan",
|
||||
"empty": "Tidak ada konteks yang perlu dipadatkan.",
|
||||
@@ -1964,9 +1994,21 @@
|
||||
"generatingImage": "Membuat gambar",
|
||||
"generatedImage": "Gambar dibuat",
|
||||
"generateImageFailed": "Tidak dapat membuat gambar",
|
||||
"delegatingTask": "Mendelegasikan tugas",
|
||||
"delegatedTask": "Tugas didelegasikan",
|
||||
"delegateTaskFailed": "Tidak dapat mendelegasikan tugas",
|
||||
"delegatingTask": "Membuat subtugas",
|
||||
"delegatedTask": "Subtugas dibuat",
|
||||
"delegateTaskFailed": "Tidak dapat membuat subtugas",
|
||||
"checkingSubtask": "Memeriksa status subtugas",
|
||||
"checkedSubtask": "Status subtugas diperoleh",
|
||||
"checkSubtaskFailed": "Tidak dapat memeriksa status subtugas",
|
||||
"messagingSubtask": "Mengirim pesan ke subtugas",
|
||||
"queuedSubtaskMessage": "Pesan masuk antrean subtugas",
|
||||
"messageSubtaskFailed": "Tidak dapat mengirim pesan ke subtugas",
|
||||
"stoppingSubtask": "Menghentikan subtugas",
|
||||
"requestedSubtaskStop": "Permintaan penghentian diproses",
|
||||
"stopSubtaskFailed": "Tidak dapat menghentikan subtugas",
|
||||
"managingSubtasks": "Mengelola subtugas",
|
||||
"managedSubtasks": "Operasi subtugas selesai",
|
||||
"manageSubtasksFailed": "Operasi subtugas gagal",
|
||||
"sendingMessage": "Mengirim pesan",
|
||||
"sentMessage": "Pesan terkirim",
|
||||
"sendMessageFailed": "Tidak dapat mengirim pesan",
|
||||
|
||||
@@ -1561,6 +1561,36 @@
|
||||
"error": "接続エラー"
|
||||
},
|
||||
"thread": {
|
||||
"subagents": {
|
||||
"loadFailed": "サブタスクを読み込めませんでした。",
|
||||
"stopFailed": "このタスクを停止できませんでした。",
|
||||
"stopTask": "{{label}} を停止",
|
||||
"receiptHelp": "配信済みは子タスクの次のモデルリクエストにメッセージが含まれたことを示し、実行完了を意味しません。",
|
||||
"states": {
|
||||
"queued": "待機中",
|
||||
"running": "実行中",
|
||||
"stopping": "停止中",
|
||||
"done": "完了",
|
||||
"incomplete": "未完了",
|
||||
"error": "失敗",
|
||||
"cancelled": "キャンセル済み",
|
||||
"interrupted": "中断"
|
||||
},
|
||||
"receipts": {
|
||||
"accepted": "待機中: {{count}}",
|
||||
"delivered": "配信済み: {{count}}",
|
||||
"undelivered": "未配信: {{count}}"
|
||||
},
|
||||
"interruptedHelp": "タスクの完了前にサーバーが再起動しました。タスクは自動的に再実行されていません。",
|
||||
"workTitle": "委任した作業",
|
||||
"otherWorkTitle": "その他の委任した作業",
|
||||
"unlinkedHelp": "表示中のメッセージには、これらのタスクに対応する依頼がありません。",
|
||||
"progress": "{{total}} 件中 {{completed}} 件完了",
|
||||
"running": "実行中: {{count}}",
|
||||
"finished": "終了: {{count}}",
|
||||
"needsReview": "要確認: {{count}}",
|
||||
"messages": "メッセージの送信状況"
|
||||
},
|
||||
"compaction": {
|
||||
"cancelled": "コンテキストの圧縮をキャンセルしました",
|
||||
"empty": "圧縮するコンテキストはありません。",
|
||||
@@ -1964,9 +1994,21 @@
|
||||
"generatingImage": "画像を生成中",
|
||||
"generatedImage": "画像を生成しました",
|
||||
"generateImageFailed": "画像を生成できませんでした",
|
||||
"delegatingTask": "タスクを委任中",
|
||||
"delegatedTask": "タスクを委任しました",
|
||||
"delegateTaskFailed": "タスクを委任できませんでした",
|
||||
"delegatingTask": "サブタスクを作成中",
|
||||
"delegatedTask": "サブタスクを作成しました",
|
||||
"delegateTaskFailed": "サブタスクを作成できませんでした",
|
||||
"checkingSubtask": "サブタスクの状態を確認中",
|
||||
"checkedSubtask": "サブタスクの状態を取得しました",
|
||||
"checkSubtaskFailed": "サブタスクの状態を確認できませんでした",
|
||||
"messagingSubtask": "サブタスクにメッセージを送信中",
|
||||
"queuedSubtaskMessage": "サブタスクへのメッセージをキューに追加しました",
|
||||
"messageSubtaskFailed": "サブタスクにメッセージを送信できませんでした",
|
||||
"stoppingSubtask": "サブタスクを停止中",
|
||||
"requestedSubtaskStop": "停止要求を処理しました",
|
||||
"stopSubtaskFailed": "サブタスクを停止できませんでした",
|
||||
"managingSubtasks": "サブタスクの操作を実行中",
|
||||
"managedSubtasks": "サブタスクの操作が完了しました",
|
||||
"manageSubtasksFailed": "サブタスクの操作に失敗しました",
|
||||
"sendingMessage": "メッセージを送信中",
|
||||
"sentMessage": "メッセージを送信しました",
|
||||
"sendMessageFailed": "メッセージを送信できませんでした",
|
||||
|
||||
@@ -1561,6 +1561,36 @@
|
||||
"error": "연결 오류"
|
||||
},
|
||||
"thread": {
|
||||
"subagents": {
|
||||
"loadFailed": "하위 작업을 불러올 수 없습니다.",
|
||||
"stopFailed": "이 작업을 중지할 수 없습니다.",
|
||||
"stopTask": "{{label}} 중지",
|
||||
"receiptHelp": "전달됨은 메시지가 하위 작업의 다음 모델 요청에 포함되었음을 뜻하며, 실행 완료를 의미하지 않습니다.",
|
||||
"states": {
|
||||
"queued": "대기 중",
|
||||
"running": "실행 중",
|
||||
"stopping": "중지 중",
|
||||
"done": "완료",
|
||||
"incomplete": "미완료",
|
||||
"error": "실패",
|
||||
"cancelled": "취소됨",
|
||||
"interrupted": "중단됨"
|
||||
},
|
||||
"receipts": {
|
||||
"accepted": "대기 중: {{count}}",
|
||||
"delivered": "전달됨: {{count}}",
|
||||
"undelivered": "미전달: {{count}}"
|
||||
},
|
||||
"interruptedHelp": "작업이 완료되기 전에 서버가 다시 시작되었습니다. 작업은 자동으로 다시 실행되지 않았습니다.",
|
||||
"workTitle": "위임한 작업",
|
||||
"otherWorkTitle": "기타 위임한 작업",
|
||||
"unlinkedHelp": "표시된 메시지에서 이 작업에 해당하는 요청을 찾을 수 없습니다.",
|
||||
"progress": "{{total}}개 중 {{completed}}개 완료",
|
||||
"running": "진행 중: {{count}}",
|
||||
"finished": "종료: {{count}}",
|
||||
"needsReview": "확인 필요: {{count}}",
|
||||
"messages": "메시지 전달 상태"
|
||||
},
|
||||
"compaction": {
|
||||
"cancelled": "컨텍스트 압축이 취소되었습니다",
|
||||
"empty": "압축할 컨텍스트가 없습니다.",
|
||||
@@ -1964,9 +1994,21 @@
|
||||
"generatingImage": "이미지 생성 중",
|
||||
"generatedImage": "이미지 생성 완료",
|
||||
"generateImageFailed": "이미지를 생성하지 못함",
|
||||
"delegatingTask": "작업 위임 중",
|
||||
"delegatedTask": "작업 위임 완료",
|
||||
"delegateTaskFailed": "작업을 위임하지 못함",
|
||||
"delegatingTask": "하위 작업 생성 중",
|
||||
"delegatedTask": "하위 작업 생성 완료",
|
||||
"delegateTaskFailed": "하위 작업을 생성하지 못했습니다",
|
||||
"checkingSubtask": "하위 작업 상태 확인 중",
|
||||
"checkedSubtask": "하위 작업 상태 확인 완료",
|
||||
"checkSubtaskFailed": "하위 작업 상태를 확인하지 못했습니다",
|
||||
"messagingSubtask": "하위 작업에 메시지 전송 중",
|
||||
"queuedSubtaskMessage": "하위 작업 메시지가 대기열에 추가되었습니다",
|
||||
"messageSubtaskFailed": "하위 작업에 메시지를 전송하지 못했습니다",
|
||||
"stoppingSubtask": "하위 작업 중지 중",
|
||||
"requestedSubtaskStop": "중지 요청이 처리되었습니다",
|
||||
"stopSubtaskFailed": "하위 작업을 중지하지 못했습니다",
|
||||
"managingSubtasks": "하위 작업 처리 중",
|
||||
"managedSubtasks": "하위 작업 처리 완료",
|
||||
"manageSubtasksFailed": "하위 작업을 처리하지 못했습니다",
|
||||
"sendingMessage": "메시지 전송 중",
|
||||
"sentMessage": "메시지 전송 완료",
|
||||
"sendMessageFailed": "메시지를 보내지 못함",
|
||||
|
||||
@@ -1575,6 +1575,36 @@
|
||||
"error": "Erro de conexão"
|
||||
},
|
||||
"thread": {
|
||||
"subagents": {
|
||||
"loadFailed": "Não foi possível carregar as subtarefas.",
|
||||
"stopFailed": "Não foi possível interromper esta tarefa.",
|
||||
"stopTask": "Interromper {{label}}",
|
||||
"receiptHelp": "Entregue significa que a mensagem foi incluída na próxima solicitação do subagente, sem confirmar sua execução.",
|
||||
"states": {
|
||||
"queued": "Na fila",
|
||||
"running": "Em execução",
|
||||
"stopping": "Interrompendo",
|
||||
"done": "Concluída",
|
||||
"incomplete": "Incompleta",
|
||||
"error": "Falhou",
|
||||
"cancelled": "Cancelada",
|
||||
"interrupted": "Interrompida"
|
||||
},
|
||||
"receipts": {
|
||||
"accepted": "Na fila: {{count}}",
|
||||
"delivered": "Entregues: {{count}}",
|
||||
"undelivered": "Não entregues: {{count}}"
|
||||
},
|
||||
"interruptedHelp": "O servidor reiniciou antes de concluir esta tarefa. Ela não foi executada novamente automaticamente.",
|
||||
"workTitle": "Trabalho delegado",
|
||||
"otherWorkTitle": "Outros trabalhos delegados",
|
||||
"unlinkedHelp": "Não foi encontrada uma solicitação correspondente a estas tarefas nas mensagens exibidas.",
|
||||
"progress": "{{completed}} de {{total}} concluídas",
|
||||
"running": "Em andamento: {{count}}",
|
||||
"finished": "Encerradas: {{count}}",
|
||||
"needsReview": "Revisar: {{count}}",
|
||||
"messages": "Status das mensagens"
|
||||
},
|
||||
"compaction": {
|
||||
"cancelled": "Compactação do contexto cancelada",
|
||||
"empty": "Não há contexto para compactar.",
|
||||
@@ -1950,9 +1980,21 @@
|
||||
"generatingImage": "Gerando imagem",
|
||||
"generatedImage": "Imagem gerada",
|
||||
"generateImageFailed": "Não foi possível gerar a imagem",
|
||||
"delegatingTask": "Delegando tarefa",
|
||||
"delegatedTask": "Tarefa delegada",
|
||||
"delegateTaskFailed": "Não foi possível delegar a tarefa",
|
||||
"delegatingTask": "Criando subtarefa",
|
||||
"delegatedTask": "Subtarefa criada",
|
||||
"delegateTaskFailed": "Não foi possível criar a subtarefa",
|
||||
"checkingSubtask": "Consultando o status da subtarefa",
|
||||
"checkedSubtask": "Status da subtarefa consultado",
|
||||
"checkSubtaskFailed": "Não foi possível consultar o status da subtarefa",
|
||||
"messagingSubtask": "Enviando mensagem para a subtarefa",
|
||||
"queuedSubtaskMessage": "Mensagem na fila da subtarefa",
|
||||
"messageSubtaskFailed": "Não foi possível enviar a mensagem para a subtarefa",
|
||||
"stoppingSubtask": "Interrompendo subtarefa",
|
||||
"requestedSubtaskStop": "Solicitação de interrupção processada",
|
||||
"stopSubtaskFailed": "Não foi possível interromper a subtarefa",
|
||||
"managingSubtasks": "Gerenciando subtarefas",
|
||||
"managedSubtasks": "Operação da subtarefa concluída",
|
||||
"manageSubtasksFailed": "Falha na operação da subtarefa",
|
||||
"sendingMessage": "Enviando mensagem",
|
||||
"sentMessage": "Mensagem enviada",
|
||||
"sendMessageFailed": "Não foi possível enviar a mensagem",
|
||||
|
||||
@@ -1561,6 +1561,36 @@
|
||||
"error": "Lỗi kết nối"
|
||||
},
|
||||
"thread": {
|
||||
"subagents": {
|
||||
"loadFailed": "Không thể tải tác vụ con.",
|
||||
"stopFailed": "Không thể dừng tác vụ này.",
|
||||
"stopTask": "Dừng {{label}}",
|
||||
"receiptHelp": "Đã chuyển nghĩa là tin nhắn đã được đưa vào yêu cầu mô hình tiếp theo của tác nhân con, không xác nhận công việc đã hoàn tất.",
|
||||
"states": {
|
||||
"queued": "Đang chờ",
|
||||
"running": "Đang chạy",
|
||||
"stopping": "Đang dừng",
|
||||
"done": "Hoàn tất",
|
||||
"incomplete": "Chưa hoàn tất",
|
||||
"error": "Thất bại",
|
||||
"cancelled": "Đã hủy",
|
||||
"interrupted": "Bị gián đoạn"
|
||||
},
|
||||
"receipts": {
|
||||
"accepted": "Đang chờ: {{count}}",
|
||||
"delivered": "Đã chuyển: {{count}}",
|
||||
"undelivered": "Chưa chuyển: {{count}}"
|
||||
},
|
||||
"interruptedHelp": "Máy chủ khởi động lại trước khi tác vụ hoàn thành. Tác vụ không tự động chạy lại.",
|
||||
"workTitle": "Công việc được giao",
|
||||
"otherWorkTitle": "Công việc được giao khác",
|
||||
"unlinkedHelp": "Không tìm thấy yêu cầu tương ứng với các tác vụ này trong tin nhắn đang hiển thị.",
|
||||
"progress": "Hoàn thành {{completed}} / {{total}}",
|
||||
"running": "Đang chạy: {{count}}",
|
||||
"finished": "Đã kết thúc: {{count}}",
|
||||
"needsReview": "Cần kiểm tra: {{count}}",
|
||||
"messages": "Trạng thái tin nhắn"
|
||||
},
|
||||
"compaction": {
|
||||
"cancelled": "Đã hủy nén ngữ cảnh",
|
||||
"empty": "Không có ngữ cảnh cần nén.",
|
||||
@@ -1964,9 +1994,21 @@
|
||||
"generatingImage": "Đang tạo ảnh",
|
||||
"generatedImage": "Đã tạo ảnh",
|
||||
"generateImageFailed": "Không thể tạo ảnh",
|
||||
"delegatingTask": "Đang giao nhiệm vụ",
|
||||
"delegatedTask": "Đã giao nhiệm vụ",
|
||||
"delegateTaskFailed": "Không thể giao nhiệm vụ",
|
||||
"delegatingTask": "Đang tạo tác vụ con",
|
||||
"delegatedTask": "Đã tạo tác vụ con",
|
||||
"delegateTaskFailed": "Không thể tạo tác vụ con",
|
||||
"checkingSubtask": "Đang kiểm tra trạng thái tác vụ con",
|
||||
"checkedSubtask": "Đã lấy trạng thái tác vụ con",
|
||||
"checkSubtaskFailed": "Không thể kiểm tra trạng thái tác vụ con",
|
||||
"messagingSubtask": "Đang gửi tin nhắn đến tác vụ con",
|
||||
"queuedSubtaskMessage": "Tin nhắn đã vào hàng đợi của tác vụ con",
|
||||
"messageSubtaskFailed": "Không thể gửi tin nhắn đến tác vụ con",
|
||||
"stoppingSubtask": "Đang dừng tác vụ con",
|
||||
"requestedSubtaskStop": "Đã xử lý yêu cầu dừng",
|
||||
"stopSubtaskFailed": "Không thể dừng tác vụ con",
|
||||
"managingSubtasks": "Đang thao tác với tác vụ con",
|
||||
"managedSubtasks": "Thao tác với tác vụ con đã hoàn tất",
|
||||
"manageSubtasksFailed": "Thao tác với tác vụ con thất bại",
|
||||
"sendingMessage": "Đang gửi tin nhắn",
|
||||
"sentMessage": "Đã gửi tin nhắn",
|
||||
"sendMessageFailed": "Không thể gửi tin nhắn",
|
||||
|
||||
@@ -1761,6 +1761,36 @@
|
||||
"error": "连接出错"
|
||||
},
|
||||
"thread": {
|
||||
"subagents": {
|
||||
"loadFailed": "无法加载子任务。",
|
||||
"stopFailed": "无法停止此任务。",
|
||||
"stopTask": "停止 {{label}}",
|
||||
"receiptHelp": "已送达表示消息已进入子任务的下一次模型请求,不代表已执行完成。",
|
||||
"states": {
|
||||
"queued": "排队中",
|
||||
"running": "执行中",
|
||||
"stopping": "正在停止",
|
||||
"done": "已完成",
|
||||
"incomplete": "未完成",
|
||||
"error": "失败",
|
||||
"cancelled": "已取消",
|
||||
"interrupted": "已中断"
|
||||
},
|
||||
"receipts": {
|
||||
"accepted": "已排队:{{count}}",
|
||||
"delivered": "已送达:{{count}}",
|
||||
"undelivered": "未送达:{{count}}"
|
||||
},
|
||||
"interruptedHelp": "后端重启时此任务尚未结束,任务没有自动恢复或重新执行。",
|
||||
"workTitle": "委派工作",
|
||||
"otherWorkTitle": "其他委派工作",
|
||||
"unlinkedHelp": "未找到这些任务在当前显示消息中的原始请求。",
|
||||
"progress": "已完成 {{completed}} / {{total}} 项",
|
||||
"running": "{{count}} 项进行中",
|
||||
"finished": "{{count}} 项已结束",
|
||||
"needsReview": "{{count}} 项需检查",
|
||||
"messages": "消息送达状态"
|
||||
},
|
||||
"compaction": {
|
||||
"cancelled": "上下文压缩已取消",
|
||||
"empty": "无需压缩上下文",
|
||||
@@ -2135,9 +2165,21 @@
|
||||
"generatingImage": "正在生成图片",
|
||||
"generatedImage": "已生成图片",
|
||||
"generateImageFailed": "无法生成图片",
|
||||
"delegatingTask": "正在委派任务",
|
||||
"delegatedTask": "已委派任务",
|
||||
"delegateTaskFailed": "无法委派任务",
|
||||
"delegatingTask": "正在创建子任务",
|
||||
"delegatedTask": "子任务已创建",
|
||||
"delegateTaskFailed": "无法创建子任务",
|
||||
"checkingSubtask": "正在查询子任务状态",
|
||||
"checkedSubtask": "已获取子任务状态",
|
||||
"checkSubtaskFailed": "无法查询子任务状态",
|
||||
"messagingSubtask": "正在向子任务发送消息",
|
||||
"queuedSubtaskMessage": "消息已加入子任务队列",
|
||||
"messageSubtaskFailed": "无法向子任务发送消息",
|
||||
"stoppingSubtask": "正在停止子任务",
|
||||
"requestedSubtaskStop": "已处理停止请求",
|
||||
"stopSubtaskFailed": "无法停止子任务",
|
||||
"managingSubtasks": "正在处理子任务操作",
|
||||
"managedSubtasks": "子任务操作已完成",
|
||||
"manageSubtasksFailed": "子任务操作失败",
|
||||
"sendingMessage": "正在发送消息",
|
||||
"sentMessage": "已发送消息",
|
||||
"sendMessageFailed": "无法发送消息",
|
||||
|
||||
@@ -1561,6 +1561,36 @@
|
||||
"error": "連線錯誤"
|
||||
},
|
||||
"thread": {
|
||||
"subagents": {
|
||||
"loadFailed": "無法載入子任務。",
|
||||
"stopFailed": "無法停止此任務。",
|
||||
"stopTask": "停止 {{label}}",
|
||||
"receiptHelp": "已送達表示訊息已進入子任務的下一次模型請求,不代表已執行完成。",
|
||||
"states": {
|
||||
"queued": "排隊中",
|
||||
"running": "執行中",
|
||||
"stopping": "正在停止",
|
||||
"done": "已完成",
|
||||
"incomplete": "未完成",
|
||||
"error": "失敗",
|
||||
"cancelled": "已取消",
|
||||
"interrupted": "已中斷"
|
||||
},
|
||||
"receipts": {
|
||||
"accepted": "已排隊:{{count}}",
|
||||
"delivered": "已送達:{{count}}",
|
||||
"undelivered": "未送達:{{count}}"
|
||||
},
|
||||
"interruptedHelp": "後端重新啟動時此任務尚未結束,任務沒有自動恢復或重新執行。",
|
||||
"workTitle": "委派工作",
|
||||
"otherWorkTitle": "其他委派工作",
|
||||
"unlinkedHelp": "未找到這些任務在目前顯示訊息中的原始請求。",
|
||||
"progress": "已完成 {{completed}} / {{total}} 項",
|
||||
"running": "{{count}} 項進行中",
|
||||
"finished": "{{count}} 項已結束",
|
||||
"needsReview": "{{count}} 項需檢查",
|
||||
"messages": "訊息傳送狀態"
|
||||
},
|
||||
"compaction": {
|
||||
"cancelled": "上下文壓縮已取消",
|
||||
"empty": "無需壓縮上下文",
|
||||
@@ -1963,9 +1993,21 @@
|
||||
"generatingImage": "正在產生圖片",
|
||||
"generatedImage": "已產生圖片",
|
||||
"generateImageFailed": "無法產生圖片",
|
||||
"delegatingTask": "正在委派任務",
|
||||
"delegatedTask": "已委派任務",
|
||||
"delegateTaskFailed": "無法委派任務",
|
||||
"delegatingTask": "正在建立子任務",
|
||||
"delegatedTask": "已建立子任務",
|
||||
"delegateTaskFailed": "無法建立子任務",
|
||||
"checkingSubtask": "正在查詢子任務狀態",
|
||||
"checkedSubtask": "已取得子任務狀態",
|
||||
"checkSubtaskFailed": "無法查詢子任務狀態",
|
||||
"messagingSubtask": "正在傳送訊息至子任務",
|
||||
"queuedSubtaskMessage": "訊息已加入子任務佇列",
|
||||
"messageSubtaskFailed": "無法傳送訊息至子任務",
|
||||
"stoppingSubtask": "正在停止子任務",
|
||||
"requestedSubtaskStop": "已處理停止請求",
|
||||
"stopSubtaskFailed": "無法停止子任務",
|
||||
"managingSubtasks": "正在處理子任務操作",
|
||||
"managedSubtasks": "子任務操作已完成",
|
||||
"manageSubtasksFailed": "子任務操作失敗",
|
||||
"sendingMessage": "正在傳送訊息",
|
||||
"sentMessage": "已傳送訊息",
|
||||
"sendMessageFailed": "無法傳送訊息",
|
||||
|
||||
@@ -38,6 +38,8 @@ import type {
|
||||
SkillsTrendingPayload,
|
||||
SlashCommand,
|
||||
SlashCommandLifecycle,
|
||||
SubagentTaskSnapshot,
|
||||
SubagentTasksPayload,
|
||||
TranscriptionSettingsUpdate,
|
||||
ThreadProjectionEvent,
|
||||
WebSearchSettingsUpdate,
|
||||
@@ -47,6 +49,7 @@ import type {
|
||||
WorkspaceScopePayload,
|
||||
} from "./types";
|
||||
import { fetchWithTimeout } from "./http";
|
||||
import { isSubagentTask } from "./subagent-tasks";
|
||||
|
||||
const API_READ_TIMEOUT_MS = 20_000;
|
||||
const API_MUTATION_TIMEOUT_MS = 20_000;
|
||||
@@ -547,6 +550,37 @@ export async function updateAutomation(
|
||||
return mutation<AutomationsPayload>(transport, "automation.update", { id, values });
|
||||
}
|
||||
|
||||
export async function fetchSubagentTasks(token: string, sessionKey: string): Promise<SubagentTasksPayload> {
|
||||
const payload = await request<unknown>(
|
||||
`/api/sessions/${encodeURIComponent(sessionKey)}/subagents`, token, undefined, API_READ_TIMEOUT_MS,
|
||||
);
|
||||
if (!isRecord(payload) || !Array.isArray(payload.tasks) || !payload.tasks.every(isSubagentTask)
|
||||
|| new Set(payload.tasks.map((task) => task.task_id)).size !== payload.tasks.length) {
|
||||
throw new Error("Invalid subagent tasks response");
|
||||
}
|
||||
return { tasks: payload.tasks };
|
||||
}
|
||||
|
||||
export async function fetchSubagentThread(
|
||||
token: string, sessionKey: string, taskId: string, signal?: AbortSignal,
|
||||
): Promise<WebuiThreadPersistedPayload> {
|
||||
const payload = await request<unknown>(
|
||||
`/api/sessions/${encodeURIComponent(sessionKey)}/subagents/${encodeURIComponent(taskId)}/webui-thread`,
|
||||
token, { signal, cache: "no-store" }, API_READ_TIMEOUT_MS,
|
||||
);
|
||||
return parseWebuiThreadPayload(payload);
|
||||
}
|
||||
|
||||
export async function cancelSubagentTask(
|
||||
transport: WebUIMutationTransport, sessionKey: string, taskId: string,
|
||||
): Promise<SubagentTaskSnapshot> {
|
||||
const result = await mutation<unknown>(transport, "subagent.cancel", {
|
||||
session_key: sessionKey, task_id: taskId,
|
||||
});
|
||||
if (!isSubagentTask(result) || result.task_id !== taskId) throw new Error("Invalid subagent cancellation response");
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function fetchSkills(
|
||||
token: string,
|
||||
base: string = "",
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { SubagentTaskSnapshot } from "./types";
|
||||
|
||||
export interface ObservedSubagentTask extends SubagentTaskSnapshot {
|
||||
observedAtMs: number;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function isSubagentTask(value: unknown): value is SubagentTaskSnapshot {
|
||||
if (!isRecord(value)) return false;
|
||||
const nullableText = (entry: unknown) => entry === null || typeof entry === "string";
|
||||
return typeof value.task_id === "string" && value.task_id.length > 0
|
||||
&& (value.revision === undefined || (typeof value.revision === "number" && Number.isSafeInteger(value.revision) && value.revision >= 0))
|
||||
&& typeof value.label === "string" && typeof value.task_description === "string"
|
||||
&& typeof value.phase === "string" && typeof value.state === "string"
|
||||
&& ["queued", "running", "stopping", "done", "incomplete", "error", "cancelled", "interrupted"].includes(value.state)
|
||||
&& typeof value.elapsed_seconds === "number" && Number.isFinite(value.elapsed_seconds) && value.elapsed_seconds >= 0
|
||||
&& typeof value.iteration === "number" && Number.isInteger(value.iteration) && value.iteration >= 0
|
||||
&& typeof value.created_at === "number" && Number.isFinite(value.created_at)
|
||||
&& (value.completed_at === null || (typeof value.completed_at === "number" && Number.isFinite(value.completed_at)))
|
||||
&& nullableText(value.origin_turn_id) && nullableText(value.origin_message_id)
|
||||
&& nullableText(value.result) && nullableText(value.error) && nullableText(value.stop_reason)
|
||||
&& typeof value.partial === "boolean"
|
||||
&& Array.isArray(value.tool_events) && value.tool_events.every((entry: unknown) => isRecord(entry) && typeof entry.name === "string" && typeof entry.status === "string")
|
||||
&& isRecord(value.receipts) && Object.values(value.receipts).every((entry) => typeof entry === "string" && ["accepted", "delivered", "undelivered"].includes(entry))
|
||||
&& (value.usage === null || (isRecord(value.usage) && Object.values(value.usage).every((entry) => entry === null || typeof entry === "string" || (typeof entry === "number" && Number.isFinite(entry)))));
|
||||
}
|
||||
|
||||
/** Merge observations from initial reads, live events and control replies. */
|
||||
export function mergeSubagentTasks(
|
||||
current: ObservedSubagentTask[], incoming: SubagentTaskSnapshot[],
|
||||
): ObservedSubagentTask[] {
|
||||
const tasks = new Map(current.map((task) => [task.task_id, task]));
|
||||
let changed = false;
|
||||
for (const task of incoming) {
|
||||
const previous = tasks.get(task.task_id);
|
||||
if (previous) {
|
||||
const revision = task.revision ?? 0;
|
||||
const previousRevision = previous.revision ?? 0;
|
||||
if (revision < previousRevision || (revision > 0 && revision === previousRevision)) continue;
|
||||
// Read-only hosts predating events have no revision. Their late reads
|
||||
// must still respect cancellation and the immutable terminal outcome.
|
||||
if (revision === 0 && previousRevision === 0) {
|
||||
if (!["queued", "running", "stopping"].includes(previous.state)) continue;
|
||||
if (previous.state === "stopping" && ["queued", "running"].includes(task.state)) continue;
|
||||
if (previous.state === "running" && task.state === "queued") continue;
|
||||
}
|
||||
}
|
||||
tasks.set(task.task_id, { ...task, observedAtMs: performance.now() });
|
||||
changed = true;
|
||||
}
|
||||
return changed ? [...tasks.values()].sort((a, b) => a.created_at - b.created_at || a.task_id.localeCompare(b.task_id)) : current;
|
||||
}
|
||||
@@ -64,6 +64,34 @@ interface TurnUsage {
|
||||
|
||||
export type RoundUsage = TurnUsage;
|
||||
|
||||
export type SubagentTaskState = "queued" | "running" | "stopping" | "done" | "incomplete" | "error" | "cancelled" | "interrupted";
|
||||
|
||||
export interface SubagentTaskSnapshot {
|
||||
task_id: string;
|
||||
revision?: number;
|
||||
origin_message_id: string | null;
|
||||
origin_turn_id: string | null;
|
||||
created_at: number;
|
||||
completed_at: number | null;
|
||||
label: string;
|
||||
task_description: string;
|
||||
state: SubagentTaskState;
|
||||
phase: string;
|
||||
elapsed_seconds: number;
|
||||
iteration: number;
|
||||
tool_events: { name: string; status: string }[];
|
||||
usage: Record<string, number | string | null> | null;
|
||||
receipts: Record<string, "accepted" | "delivered" | "undelivered">;
|
||||
result: string | null;
|
||||
partial: boolean;
|
||||
stop_reason: string | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export interface SubagentTasksPayload {
|
||||
tasks: SubagentTaskSnapshot[];
|
||||
}
|
||||
|
||||
export interface ResponseSource {
|
||||
provider: string;
|
||||
model: string;
|
||||
@@ -488,6 +516,9 @@ export interface SidebarStatePayload {
|
||||
}
|
||||
|
||||
export interface BootstrapResponse {
|
||||
terminal?: {
|
||||
webui?: { capabilities?: string[] };
|
||||
};
|
||||
token?: string;
|
||||
api_token?: string;
|
||||
ws_path: string;
|
||||
@@ -1353,6 +1384,7 @@ interface InboundTurnMetadata {
|
||||
}
|
||||
|
||||
export type InboundEvent =
|
||||
| { event: "subagent_task"; chat_id: string; task: SubagentTaskSnapshot }
|
||||
| { event: "ready"; chat_id: string; client_id: string }
|
||||
| {
|
||||
event: "attached";
|
||||
|
||||
@@ -16,6 +16,7 @@ interface ClientContextValue {
|
||||
getToken: () => string;
|
||||
modelName: string | null;
|
||||
ingressLimits: WebUIIngressLimits | null;
|
||||
webuiCapabilities: string[];
|
||||
}
|
||||
|
||||
const ClientContext = createContext<ClientContextValue | null>(null);
|
||||
@@ -25,20 +26,22 @@ export function ClientProvider({
|
||||
token,
|
||||
modelName = null,
|
||||
ingressLimits = null,
|
||||
webuiCapabilities = [],
|
||||
children,
|
||||
}: {
|
||||
client: NanobotClient;
|
||||
token: string;
|
||||
modelName?: string | null;
|
||||
ingressLimits?: WebUIIngressLimits | null;
|
||||
webuiCapabilities?: string[];
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const tokenRef = useRef(token);
|
||||
tokenRef.current = token;
|
||||
const getToken = useCallback(() => tokenRef.current, []);
|
||||
const value = useMemo(
|
||||
() => ({ client, token, getToken, modelName, ingressLimits }),
|
||||
[client, getToken, ingressLimits, modelName, token],
|
||||
() => ({ client, token, getToken, modelName, ingressLimits, webuiCapabilities }),
|
||||
[client, getToken, ingressLimits, modelName, token, webuiCapabilities],
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster";
|
||||
import { preloadMarkdownText } from "@/components/MarkdownText";
|
||||
import { setAppLanguage } from "@/i18n";
|
||||
import { DEFAULT_LOCAL_PREFS, writeLocalPreferences } from "@/lib/local-preferences";
|
||||
import { DEFAULT_LOCAL_PREFS, LOCAL_PREFS_STORAGE_KEY, writeLocalPreferences } from "@/lib/local-preferences";
|
||||
import type { CliAppInfo, McpPresetInfo, UIMessage } from "@/lib/types";
|
||||
|
||||
const BLENDER_CLI_APP: CliAppInfo = {
|
||||
@@ -98,6 +98,21 @@ function installReducedMotion() {
|
||||
}
|
||||
|
||||
describe("AgentActivityCluster", () => {
|
||||
afterEach(() => { localStorage.removeItem(LOCAL_PREFS_STORAGE_KEY); });
|
||||
|
||||
it("honors the activity preference for standalone completed activity with manual overrides", () => {
|
||||
render(<AgentActivityCluster messages={activityMessages()} isTurnStreaming={false} hasBodyBelow={false} />);
|
||||
const disclosure = screen.getByRole("button", { name: /Worked/ });
|
||||
expect(disclosure).toHaveAttribute("aria-expanded", "false");
|
||||
act(() => { writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, activityMode: "expanded" }); });
|
||||
expect(disclosure).toHaveAttribute("aria-expanded", "true");
|
||||
fireEvent.click(disclosure);
|
||||
expect(disclosure).toHaveAttribute("aria-expanded", "false");
|
||||
act(() => { writeLocalPreferences(DEFAULT_LOCAL_PREFS); });
|
||||
expect(disclosure).toHaveAttribute("aria-expanded", "false");
|
||||
act(() => { writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, activityMode: "expanded" }); });
|
||||
expect(disclosure).toHaveAttribute("aria-expanded", "true");
|
||||
});
|
||||
it("updates existing activity when the language changes without altering raw values", async () => {
|
||||
const query = "release notes";
|
||||
const path = "src/app.tsx";
|
||||
|
||||
@@ -58,7 +58,8 @@ function mockFetchRoutes(routes: Record<string, unknown>): void {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
const route = routes[String(input)];
|
||||
const route = routes[String(input)]
|
||||
?? (/^\/api\/sessions\/[^/]+\/subagents$/.test(String(input)) ? { tasks: [] } : undefined);
|
||||
const body =
|
||||
typeof route === "function"
|
||||
? await (route as () => unknown | Promise<unknown>)()
|
||||
@@ -338,13 +339,7 @@ describe("App layout", () => {
|
||||
expires_in: 300,
|
||||
});
|
||||
vi.mocked(deriveWsUrl).mockReset().mockReturnValue("ws://test");
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 404,
|
||||
}),
|
||||
);
|
||||
mockFetchRoutes({});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -366,6 +361,34 @@ describe("App layout", () => {
|
||||
expect(screen.queryByText("Loading nanobot…")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([false, true])("enables task controls only when bootstrap advertises support: %s", async (supported) => {
|
||||
mockSessions = [{
|
||||
key: "websocket:chat-a", channel: "websocket", chatId: "chat-a",
|
||||
createdAt: null, updatedAt: null, title: "Inspection", preview: "Inspect config",
|
||||
}];
|
||||
window.history.replaceState(null, "", "/#/chat/websocket%3Achat-a");
|
||||
vi.mocked(fetchBootstrap).mockResolvedValue({
|
||||
token: "tok", api_token: "api-tok", ws_path: "/", expires_in: 300,
|
||||
terminal: { webui: { capabilities: supported ? ["webui.core.v1", "webui.subagents.v1"] : ["webui.core.v1"] } },
|
||||
});
|
||||
mockFetchRoutes({
|
||||
"/api/sessions/websocket%3Achat-a/subagents": { tasks: [{
|
||||
task_id: "task-1", label: "Config check", task_description: "Inspect configuration",
|
||||
state: "running", phase: "awaiting_model", elapsed_seconds: 2, iteration: 1,
|
||||
tool_events: [], usage: null, receipts: {}, result: null, partial: false,
|
||||
stop_reason: null, error: null, origin_turn_id: null, origin_message_id: null,
|
||||
created_at: 100, completed_at: null,
|
||||
}] },
|
||||
});
|
||||
render(<App />);
|
||||
await screen.findByRole("textbox");
|
||||
if (supported) await screen.findByRole("button", { name: /Config check Running/ });
|
||||
else expect(screen.queryByText("Config check")).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();
|
||||
});
|
||||
|
||||
it("shows the auth form without an invalid-password error on first load", async () => {
|
||||
vi.mocked(fetchBootstrap).mockRejectedValueOnce(
|
||||
new Error("bootstrap failed: HTTP 401"),
|
||||
|
||||
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { redactActivityText } from "@/components/thread/activity/activity-text";
|
||||
import {
|
||||
describeGenericToolRun,
|
||||
canGroupGenericToolRuns,
|
||||
parseGenericToolTrace,
|
||||
type GenericToolStatus,
|
||||
} from "@/components/thread/activity/generic-tool-model";
|
||||
@@ -39,7 +40,12 @@ describe("generic tool activity semantics", () => {
|
||||
['read_file({"path":"docs/guide.md"})', "Read file", "docs/guide.md"],
|
||||
['memory_search({"query":"launch date"})', "Searched memory", "“launch date”"],
|
||||
['generate_image({"prompt":"private launch art"})', "Generated image", ""],
|
||||
['spawn({"label":"Research competitors","task":"private task"})', "Delegated task", "Research competitors"],
|
||||
['spawn({"label":"Research competitors","task":"private task"})', "Subtask created", "Research competitors"],
|
||||
['subagent("create")', "Subtask created", ""],
|
||||
['subagent({"action":"create","label":"Research competitors","task":"private task"})', "Subtask created", "Research competitors"],
|
||||
['subagent("check")', "Subtask status retrieved", ""],
|
||||
['subagent("send")', "Message queued for subtask", ""],
|
||||
['subagent("cancel")', "Stop request processed", ""],
|
||||
['message({"channel":"telegram","content":"private message"})', "Sent message", "telegram"],
|
||||
['my({"action":"check","key":"context_window_tokens"})', "Checked agent settings", "context_window_tokens"],
|
||||
['my({"action":"set","key":"model","value":"private-model"})', "Updated agent settings", "model"],
|
||||
@@ -125,6 +131,13 @@ describe("generic tool activity semantics", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps different subtask actions separate while grouping repeated status checks", () => {
|
||||
const item = (action: string) => ({ trace: parseGenericToolTrace(`subagent("${action}")`)!, status: "done" as const });
|
||||
expect(canGroupGenericToolRuns(item("create"), item("check"))).toBe(false);
|
||||
expect(canGroupGenericToolRuns(item("send"), item("cancel"))).toBe(false);
|
||||
expect(canGroupGenericToolRuns(item("check"), item("check"))).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Authorization: Bearer top-secret-token", "Authorization: <redacted>"],
|
||||
["API_KEY=sk-proj-1234567890abcdef", "API_KEY=<redacted>"],
|
||||
|
||||
@@ -28,6 +28,21 @@ describe("localized agent activity contracts", () => {
|
||||
expect(translated.actionTargetRich).toContain("<target></target>");
|
||||
|
||||
await setAppLanguage(locale);
|
||||
for (const [action, keys] of [
|
||||
["create", ["delegatingTask", "delegatedTask", "delegateTaskFailed"]],
|
||||
["check", ["checkingSubtask", "checkedSubtask", "checkSubtaskFailed"]],
|
||||
["send", ["messagingSubtask", "queuedSubtaskMessage", "messageSubtaskFailed"]],
|
||||
["cancel", ["stoppingSubtask", "requestedSubtaskStop", "stopSubtaskFailed"]],
|
||||
] as const) {
|
||||
for (const line of [`subagent("${action}")`, `subagent({"action":"${action}","task_id":"private-id","message":"private instructions"})`]) {
|
||||
const subtask = parseGenericToolTrace(line)!;
|
||||
for (const [index, status] of (["running", "done", "error"] as const).entries()) {
|
||||
expect(describeGenericToolRun([{ trace: subtask, status }], i18n.t)).toMatchObject({
|
||||
label: translated[keys[index]], detail: "", status,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
const trace = parseGenericToolTrace('read_file({"path":"src/app.tsx"})')!;
|
||||
const rg = parseGenericToolTrace('rg({"args":["-n","hello world","src"]})')!;
|
||||
for (const status of ["running", "done", "error"] as const) {
|
||||
@@ -99,4 +114,24 @@ describe("localized agent activity contracts", () => {
|
||||
expect(screen.getByText("Could not search release notes")).toBeInTheDocument();
|
||||
expect(JSON.stringify(messages)).toBe(original);
|
||||
});
|
||||
|
||||
it("renders recorded subtask actions in Chinese and English without implying execution is complete", async () => {
|
||||
const messages: UIMessage[] = [{
|
||||
id: "subtask-replay", role: "tool", kind: "trace", createdAt: 1,
|
||||
content: 'subagent("create")',
|
||||
traces: ['subagent("create")', 'subagent("check")', 'subagent("send")', 'subagent("cancel")'],
|
||||
}];
|
||||
const original = JSON.stringify(messages);
|
||||
await setAppLanguage("zh-CN");
|
||||
render(<AgentActivityCluster messages={messages} isTurnStreaming={false} hasBodyBelow expanded />);
|
||||
for (const label of ["子任务已创建", "已获取子任务状态", "消息已加入子任务队列", "已处理停止请求"]) {
|
||||
expect(screen.getByText(label)).toBeInTheDocument();
|
||||
}
|
||||
expect(screen.queryByText("已完成 Subagent")).not.toBeInTheDocument();
|
||||
await act(async () => setAppLanguage("en"));
|
||||
for (const label of ["Subtask created", "Subtask status retrieved", "Message queued for subtask", "Stop request processed"]) {
|
||||
expect(screen.getByText(label)).toBeInTheDocument();
|
||||
}
|
||||
expect(JSON.stringify(messages)).toBe(original);
|
||||
});
|
||||
});
|
||||
@@ -1619,6 +1619,18 @@ describe("NanobotClient", () => {
|
||||
|
||||
expect(chatHandler).toHaveBeenCalledTimes(deliveredBeforeLateFrames);
|
||||
expect(client.getRunStartedAt("chat-canonical")).toBeNull();
|
||||
const otherChat = vi.fn();
|
||||
client.onChat("other-chat", otherChat);
|
||||
const taskUpdate = {
|
||||
event: "subagent_task", chat_id: "chat-canonical",
|
||||
task: { task_id: "child", origin_turn_id: "turn-canonical", state: "done", revision: 4 },
|
||||
};
|
||||
lastSocket().fakeMessage(taskUpdate);
|
||||
expect(chatHandler).toHaveBeenLastCalledWith(taskUpdate);
|
||||
expect(chatHandler).toHaveBeenCalledTimes(deliveredBeforeLateFrames + 1);
|
||||
expect(otherChat).not.toHaveBeenCalled();
|
||||
expect(client.hasUnsettledRun("chat-canonical")).toBe(false);
|
||||
expect(client.getRunStartedAt("chat-canonical")).toBeNull();
|
||||
});
|
||||
|
||||
it("notifies run status subscribers and replays running chats", () => {
|
||||
|
||||
@@ -0,0 +1,485 @@
|
||||
import { act, fireEvent, 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 { SubagentTasksProvider, SubagentThreadMessages as ThreadMessages } from "@/components/thread/SubagentTasks";
|
||||
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 type { ConnectionStatus, InboundEvent, SubagentTaskSnapshot, UIMessage } from "@/lib/types";
|
||||
|
||||
const requestMutation = vi.fn();
|
||||
const chatHandlers = new Map<string, Set<(event: InboundEvent) => void>>();
|
||||
const statusHandlers = new Set<(status: ConnectionStatus) => void>();
|
||||
const client = {
|
||||
requestMutation,
|
||||
onChat: vi.fn((chatId: string, handler: (event: InboundEvent) => void) => {
|
||||
const handlers = chatHandlers.get(chatId) ?? new Set();
|
||||
chatHandlers.set(chatId, handlers);
|
||||
handlers.add(handler);
|
||||
return () => { handlers.delete(handler); };
|
||||
}),
|
||||
onStatus: vi.fn((handler: (status: ConnectionStatus) => void) => {
|
||||
statusHandlers.add(handler);
|
||||
handler("open");
|
||||
return () => { statusHandlers.delete(handler); };
|
||||
}),
|
||||
};
|
||||
function emitTask(snapshot: SubagentTaskSnapshot, chatId = "a") {
|
||||
act(() => { chatHandlers.get(chatId)?.forEach((handler) => handler({ event: "subagent_task", chat_id: chatId, task: snapshot })); });
|
||||
}
|
||||
const messages: UIMessage[] = [
|
||||
{ id: "prompt-a", role: "user", content: "Inspect config", turnId: "turn-a" },
|
||||
{ id: "answer-a", role: "assistant", content: "Main answer", turnId: "turn-a" },
|
||||
];
|
||||
|
||||
function task(overrides: Partial<SubagentTaskSnapshot> = {}): SubagentTaskSnapshot {
|
||||
return {
|
||||
task_id: "task-1", revision: 1, label: "Config check", task_description: "Check configuration values",
|
||||
state: "running", phase: "awaiting_model", elapsed_seconds: 2, iteration: 1,
|
||||
tool_events: [], usage: null, receipts: {}, result: null, partial: false,
|
||||
stop_reason: null, error: null, origin_turn_id: "turn-a", origin_message_id: null,
|
||||
created_at: 100, completed_at: null, ...overrides,
|
||||
};
|
||||
}
|
||||
function response(tasks: SubagentTaskSnapshot[]): Response {
|
||||
return new Response(JSON.stringify({ tasks }), { headers: { "content-type": "application/json" } });
|
||||
}
|
||||
function childThread(answer: string, active = true): Response {
|
||||
return new Response(JSON.stringify({ schemaVersion: 3, projection: "events", active_turn_id: active ? "child-turn" : null,
|
||||
events: [
|
||||
{ event: "user_message", chat_id: "task-1", starts_turn: true, projection_id: "child-prompt", turn_id: "child-turn", text: "Inspect configuration in the child session", created_at_ms: 100000 },
|
||||
{ event: "message", chat_id: "task-1", projection_id: "child-tool", turn_id: "child-turn", kind: "tool_hint", text: 'read_file({"path":"config.py"})',
|
||||
tool_events: [{ call_id: "read-1", name: "read_file", arguments: { path: "config.py" }, phase: "end", result: "configuration values" }] },
|
||||
{ event: "message", chat_id: "task-1", projection_id: "child-answer", turn_id: "child-turn", text: answer },
|
||||
],
|
||||
}), { headers: { "content-type": "application/json" } });
|
||||
}
|
||||
function layout({ enabled = true, liveEvents = true, historyEnabled = false, sessionKey = "websocket:a", visible = true, threadMessages = messages } = {}) {
|
||||
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>
|
||||
</ThreadVisibilityContext.Provider>;
|
||||
}
|
||||
|
||||
describe("session-owned task UI", () => {
|
||||
beforeEach(async () => {
|
||||
localStorage.removeItem(LOCAL_PREFS_STORAGE_KEY);
|
||||
await setAppLanguage("en");
|
||||
requestMutation.mockReset();
|
||||
client.onChat.mockClear();
|
||||
client.onStatus.mockClear();
|
||||
chatHandlers.clear();
|
||||
statusHandlers.clear();
|
||||
vi.stubGlobal("fetch", vi.fn().mockImplementation(async () => response([task()])));
|
||||
});
|
||||
afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); localStorage.removeItem(LOCAL_PREFS_STORAGE_KEY); });
|
||||
|
||||
it("applies the browser activity preference to delegated work and its shared child chat", 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: /Delegated work/ });
|
||||
expect(work).toHaveAttribute("aria-expanded", "false");
|
||||
|
||||
act(() => { writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, activityMode: "expanded" }); });
|
||||
expect(work).toHaveAttribute("aria-expanded", "true");
|
||||
await user.click(screen.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();
|
||||
await user.click(within(detail).getByRole("button", { name: /Collapse activity details/ }));
|
||||
expect(within(detail).queryByTestId("agent-activity-content")).not.toBeInTheDocument();
|
||||
|
||||
act(() => { writeLocalPreferences(DEFAULT_LOCAL_PREFS); });
|
||||
expect(work).toHaveAttribute("aria-expanded", "false");
|
||||
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/ }));
|
||||
expect(await within(screen.getByRole("dialog")).findByTestId("agent-activity-content")).toBeVisible();
|
||||
});
|
||||
|
||||
it("renders the child Session in the shared chat view and refreshes it from task events", async () => {
|
||||
let completed = false;
|
||||
const fetcher = vi.fn(async (url: string) => url.endsWith("/webui-thread")
|
||||
? childThread(completed ? "## Findings\n\n- **Verified** the full session\n\n| Check | Result |\n| --- | --- |\n| Configuration | Passed |" : "Checking the configuration", !completed)
|
||||
: response([task()]));
|
||||
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 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();
|
||||
expect(fetcher).toHaveBeenCalledWith(
|
||||
"/api/sessions/websocket%3Aa/subagents/task-1/webui-thread", expect.objectContaining({ signal: expect.any(AbortSignal) }),
|
||||
);
|
||||
completed = true;
|
||||
emitTask(task({ revision: 2, state: "done", completed_at: 102, result: "Bounded task summary" }));
|
||||
expect(await within(detail).findByRole("heading", { name: "Findings" })).toBeVisible();
|
||||
expect(within(detail).getByRole("table")).toHaveTextContent("ConfigurationPassed");
|
||||
expect(within(detail).getByText("Inspect configuration in the child session")).toBeVisible();
|
||||
// Opening and reading details never mutates execution; a fresh view reads the same saved child.
|
||||
expect(requestMutation).not.toHaveBeenCalled();
|
||||
view.unmount();
|
||||
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: /Delegated work/ }));
|
||||
await user.click(screen.getByRole("button", { name: /Config check Completed/ }));
|
||||
expect(await within(screen.getByRole("dialog")).findByRole("heading", { name: "Findings" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("coalesces history reads and discards an outstanding read when the session changes", async () => {
|
||||
let resolveFirst!: (value: Response) => void;
|
||||
let resolveOld!: (value: Response) => void;
|
||||
let reads = 0;
|
||||
const readSignals: AbortSignal[] = [];
|
||||
const fetcher = vi.fn(async (url: string, init?: RequestInit) => {
|
||||
if (!url.endsWith("/webui-thread")) return response([task()]);
|
||||
if (init?.signal) readSignals.push(init.signal);
|
||||
reads += 1;
|
||||
if (reads === 1) return new Promise<Response>((resolve) => { resolveFirst = resolve; });
|
||||
if (reads === 3) return new Promise<Response>((resolve) => { resolveOld = resolve; });
|
||||
return childThread("Latest child response", false);
|
||||
});
|
||||
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/ }));
|
||||
await waitFor(() => expect(reads).toBe(1));
|
||||
emitTask(task({ revision: 2, iteration: 2 }));
|
||||
emitTask(task({ revision: 3, iteration: 3 }));
|
||||
expect(reads).toBe(1);
|
||||
await act(async () => { resolveFirst(childThread("Earlier checkpoint")); });
|
||||
expect(await within(screen.getByRole("dialog")).findByText("Latest child response")).toBeVisible();
|
||||
expect(reads).toBe(2);
|
||||
emitTask(task({ revision: 4, iteration: 4 }));
|
||||
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(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();
|
||||
});
|
||||
|
||||
it("retries a failed history read through the shared history controls", async () => {
|
||||
let offline = true;
|
||||
vi.stubGlobal("fetch", vi.fn(async (url: string) => {
|
||||
if (!url.endsWith("/webui-thread")) return response([task()]);
|
||||
if (offline) throw new Error("offline");
|
||||
return childThread("Recovered child response");
|
||||
}));
|
||||
const user = userEvent.setup();
|
||||
render(layout({ historyEnabled: true }));
|
||||
await user.click(await screen.findByRole("button", { name: /Config check Running/ }));
|
||||
const detail = screen.getByRole("dialog");
|
||||
expect(await within(detail).findByRole("alert")).toHaveTextContent("Loading failed.");
|
||||
offline = false;
|
||||
await user.click(within(detail).getByRole("button", { name: "Retry" }));
|
||||
expect(await within(detail).findByText("Recovered child response")).toBeVisible();
|
||||
});
|
||||
|
||||
it("keeps the same work block under its prompt, folds completed work and restores it after refresh", async () => {
|
||||
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: /Delegated work/ });
|
||||
expect(screen.getByTestId("messages")).toContainElement(runningRow);
|
||||
expect(header).toHaveAttribute("aria-expanded", "true");
|
||||
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/ });
|
||||
expect(row).toBe(runningRow);
|
||||
expect(row.closest("section")).toBe(work);
|
||||
expect(within(screen.getByTestId("composer")).queryByText("Config check")).not.toBeInTheDocument();
|
||||
expect(work).toHaveAccessibleName("Delegated work");
|
||||
view.unmount();
|
||||
render(layout());
|
||||
fireEvent.click(await screen.findByRole("button", { name: /Delegated work Finished: 1/ }));
|
||||
expect(screen.getByRole("button", { name: /Config check Completed/ })).toBeVisible();
|
||||
expect(requestMutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows truthful partial output, interruption and receipts, and restores keyboard focus", async () => {
|
||||
vi.mocked(fetch).mockResolvedValue(response([task({
|
||||
state: "interrupted", partial: true, result: "Found a conflicting setting",
|
||||
stop_reason: "host_restarted", completed_at: 102, receipts: { a: "delivered", b: "undelivered" },
|
||||
})]));
|
||||
const user = userEvent.setup();
|
||||
render(layout());
|
||||
await user.click(await screen.findByRole("button", { name: /Delegated work/ }));
|
||||
const row = await screen.findByRole("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();
|
||||
expect(detail).toHaveFocus();
|
||||
expect(within(detail).getByText("Interrupted")).toBeVisible();
|
||||
expect(within(detail).getByText("Found a conflicting setting")).toBeVisible();
|
||||
await user.click(within(detail).getByText("Message delivery"));
|
||||
expect(within(detail).getByText("Delivered: 1")).toBeVisible();
|
||||
expect(screen.queryByRole("button", { name: "Stop Config check" })).not.toBeInTheDocument();
|
||||
await user.keyboard("{Escape}");
|
||||
await waitFor(() => expect(row).toHaveFocus());
|
||||
});
|
||||
|
||||
it("keeps cancellation and an open detail consistent when an older read completes later", async () => {
|
||||
let resolveRefresh!: (value: Response) => void;
|
||||
let resolveStop!: (value: SubagentTaskSnapshot) => void;
|
||||
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" }));
|
||||
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: /Delegated work Finished: 1/ }));
|
||||
await screen.findByRole("button", { name: /Config check Cancelled/ });
|
||||
await act(async () => { resolveRefresh(response([task()])); });
|
||||
expect(screen.queryByRole("button", { name: "Stop Config check" })).not.toBeInTheDocument();
|
||||
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 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/ }));
|
||||
expect(screen.getByRole("dialog", { name: "Config check" })).toBeVisible();
|
||||
view.rerender(layout({ visible: false }));
|
||||
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
|
||||
fireEvent(window, new Event("focus"));
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
expect(chatHandlers.get("a")?.size).toBe(0);
|
||||
expect(statusHandlers.size).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps load failures visible and keeps stop failures across a successful refresh", 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");
|
||||
fireEvent(window, new Event("focus"));
|
||||
await waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
|
||||
expect(screen.getByText("Cannot stop task")).toBeVisible();
|
||||
vi.mocked(fetch).mockRejectedValue(new Error("offline"));
|
||||
fireEvent(window, new Event("focus"));
|
||||
await screen.findByText("Could not load subtasks.");
|
||||
expect(screen.getByRole("button", { name: /Config check Running/ })).toBeVisible();
|
||||
});
|
||||
|
||||
it("shows a read error for malformed or duplicate task records", async () => {
|
||||
vi.mocked(fetch).mockImplementation(async () => new Response(JSON.stringify({
|
||||
tasks: [{ ...task(), label: { unexpected: true } }],
|
||||
}), { headers: { "content-type": "application/json" } }));
|
||||
render(layout());
|
||||
await screen.findByText("Could not load subtasks.");
|
||||
expect(screen.queryByText("Config check")).not.toBeInTheDocument();
|
||||
vi.mocked(fetch).mockImplementation(async () => response([task(), task()]));
|
||||
fireEvent(window, new Event("focus"));
|
||||
await waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
|
||||
expect(screen.getByText("Could not load subtasks.")).toBeVisible();
|
||||
expect(screen.queryByText("Config check")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
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 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/ });
|
||||
await act(async () => { resolveOld(response([task()])); });
|
||||
expect(screen.queryByText("Config check")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
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/ });
|
||||
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,
|
||||
result: "## Findings\n\n- **Release** resources\n- Cover exceptions\n\n```python\nawait connection.close()\n```\n\n| Check | Result |\n| --- | --- |\n| Cancellation | Passed |\n\n[Evidence](https://example.com/review)",
|
||||
})]));
|
||||
fireEvent(window, new Event("focus"));
|
||||
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();
|
||||
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: /Delegated work/ })).toHaveFocus());
|
||||
expect(requestMutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("anchors replay once when multiple prompts share a turn and preserves row order", async () => {
|
||||
const replay = [...messages, { id: "followup", role: "user", content: "Focus on errors", turnId: "turn-a" } 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" }),
|
||||
]));
|
||||
render(layout({ threadMessages: replay }));
|
||||
await screen.findByRole("button", { name: /Config check Running/ });
|
||||
expect(screen.getAllByRole("region", { name: "Delegated work" })).toHaveLength(1);
|
||||
const rows = screen.getAllByRole("button", { name: /check Running/ });
|
||||
expect(rows.map((row) => row.dataset.subagentId)).toEqual(["task-1", "second"]);
|
||||
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" }),
|
||||
]));
|
||||
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();
|
||||
});
|
||||
|
||||
it("prefers the exact initiating follow-up over a turn fallback", async () => {
|
||||
vi.mocked(fetch).mockImplementation(async () => response([task({ origin_message_id: "followup" })]));
|
||||
render(layout({ threadMessages: [...messages, { id: "followup", role: "user", content: "Check more", turnId: "turn-a" }] }));
|
||||
await screen.findByRole("button", { name: /Config check Running/ });
|
||||
const group = screen.getByRole("region", { name: "Delegated work" });
|
||||
expect(screen.getByText("Check more").compareDocumentPosition(group) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
});
|
||||
|
||||
it("keeps legacy work with an unknown origin separate from the latest request after refresh", async () => {
|
||||
vi.mocked(fetch).mockImplementation(async () => response([
|
||||
task({ task_id: "legacy", revision: 0, label: "Nanjing weather", state: "done", completed_at: 102,
|
||||
origin_turn_id: "websocket:a:1791046873588004336", result: "## Nanjing\n\n- **Rain**" }),
|
||||
task({ created_at: 200 }),
|
||||
]));
|
||||
const user = userEvent.setup();
|
||||
const view = render(layout());
|
||||
await screen.findByRole("button", { name: /Config check Running/ });
|
||||
const otherWork = screen.getByRole("region", { name: "Other delegated work" });
|
||||
const header = within(otherWork).getByRole("button", { name: /Other delegated work/ });
|
||||
expect(header).toHaveAttribute("aria-expanded", "false");
|
||||
expect(otherWork.compareDocumentPosition(screen.getByText("Inspect config")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(within(screen.getByRole("region", { name: "Delegated work" })).queryByText("Nanjing weather")).not.toBeInTheDocument();
|
||||
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/ }));
|
||||
const detail = screen.getByRole("dialog", { name: "Nanjing weather" });
|
||||
expect(within(detail).getByRole("heading", { name: "Nanjing" })).toBeVisible();
|
||||
expect(within(detail).getByRole("list")).toHaveTextContent("Rain");
|
||||
await user.keyboard("{Escape}");
|
||||
view.unmount();
|
||||
render(layout());
|
||||
const restored = await screen.findByRole("region", { name: "Other delegated work" });
|
||||
expect(within(restored).getByRole("button", { name: /Other delegated work/ })).toHaveAttribute("aria-expanded", "false");
|
||||
expect(restored.compareDocumentPosition(screen.getByText("Inspect config")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(requestMutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reattaches work when its initiating prompt is loaded without duplicating it or closing details", 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({ created_at: 200 }),
|
||||
]));
|
||||
const user = userEvent.setup();
|
||||
const view = render(layout());
|
||||
const otherWork = await screen.findByRole("region", { name: "Other delegated work" });
|
||||
await user.click(within(otherWork).getByRole("button", { name: /Earlier check Running/ }));
|
||||
const detail = screen.getByRole("dialog", { name: "Earlier check" });
|
||||
view.rerender(layout({ threadMessages: [
|
||||
{ id: "older-prompt", role: "user", content: "Inspect earlier work", turnId: "older-turn" },
|
||||
...messages,
|
||||
] }));
|
||||
expect(detail).toBeVisible();
|
||||
await user.keyboard("{Escape}");
|
||||
expect(screen.queryByRole("region", { name: "Other delegated work" })).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();
|
||||
await waitFor(() => expect(row).toHaveFocus());
|
||||
});
|
||||
|
||||
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; }));
|
||||
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/ });
|
||||
await act(async () => { resolveRead(response([task()])); });
|
||||
expect(screen.getByRole("button", { name: /Config check Completed/ })).toBeVisible();
|
||||
expect(screen.getAllByRole("region", { name: "Delegated work" })).toHaveLength(1);
|
||||
vi.useFakeTimers();
|
||||
await act(async () => { vi.advanceTimersByTime(10_000); });
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
expect(requestMutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps elapsed time consistent when inspecting a task long after its last event", 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/ });
|
||||
expect(row).toHaveTextContent("12s");
|
||||
fireEvent.click(row);
|
||||
expect(screen.getByRole("dialog", { name: "Config check" })).toHaveTextContent("12s");
|
||||
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;
|
||||
render(layout());
|
||||
await screen.findByRole("button", { name: /Config check Running/ });
|
||||
vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve; }));
|
||||
fireEvent(window, new Event("focus"));
|
||||
emitTask(task({ revision: 3, state: "cancelled", completed_at: 102 }));
|
||||
vi.mocked(fetch).mockImplementationOnce(async () => response([
|
||||
task({ revision: 2 }), task({ task_id: "task-2", label: "Recovered check", created_at: 101 }),
|
||||
]));
|
||||
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();
|
||||
expect(fetch).toHaveBeenCalledTimes(3);
|
||||
emitTask({ ...task(), revision: -1 });
|
||||
expect(screen.getByText("Could not load subtasks.")).toBeVisible();
|
||||
});
|
||||
|
||||
it("keeps protocol 1 task controls usable on a host without event support", async () => {
|
||||
vi.mocked(fetch).mockImplementation(async () => response([task({ revision: undefined })]));
|
||||
vi.useFakeTimers();
|
||||
const view = render(layout({ liveEvents: false }));
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(screen.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(3000); });
|
||||
expect(screen.getByRole("button", { name: /Delegated work Finished: 1/ })).toBeVisible();
|
||||
expect(client.onChat).not.toHaveBeenCalled();
|
||||
view.rerender(layout({ liveEvents: false, visible: false }));
|
||||
const reads = vi.mocked(fetch).mock.calls.length;
|
||||
await act(async () => { vi.advanceTimersByTime(6000); });
|
||||
expect(fetch).toHaveBeenCalledTimes(reads);
|
||||
});
|
||||
});
|
||||
@@ -222,12 +222,14 @@ function wrap(
|
||||
children: ReactNode,
|
||||
modelName?: string | null,
|
||||
token = "tok",
|
||||
webuiCapabilities: string[] = [],
|
||||
) {
|
||||
return (
|
||||
<ClientProvider
|
||||
client={client as unknown as import("@/lib/nanobot-client").NanobotClient}
|
||||
token={token}
|
||||
modelName={modelName ?? null}
|
||||
webuiCapabilities={webuiCapabilities}
|
||||
>
|
||||
{children}
|
||||
</ClientProvider>
|
||||
@@ -491,6 +493,39 @@ describe("ThreadShell", () => {
|
||||
);
|
||||
});
|
||||
|
||||
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) => {
|
||||
if (String(input).endsWith("/subagents")) return httpJson({ tasks: [{
|
||||
task_id: "completed-task", label: "Inspect settings", task_description: "Inspect settings",
|
||||
origin_turn_id: "delegation-turn", origin_message_id: null, created_at: 100, completed_at: 102,
|
||||
state: "done", phase: "done", elapsed_seconds: 2, iteration: 1, tool_events: [],
|
||||
usage: null, receipts: {}, result: "Verified", partial: false, stop_reason: "completed", error: null,
|
||||
}] });
|
||||
if (String(input).includes("/webui-thread")) return httpJson(transcriptFromSimpleMessages([
|
||||
{ role: "user", content: "Delegate inspection", turnId: "delegation-turn" },
|
||||
{ role: "assistant", content: "Parent conclusion", turnId: "delegation-turn" },
|
||||
]));
|
||||
return { ok: false, status: 404, json: async () => ({}) };
|
||||
}));
|
||||
const shell = () => wrap(client, <ThreadShell session={session("persisted-tasks")} title="Task history"
|
||||
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: /Delegated work Finished: 1/ }));
|
||||
const task = await screen.findByRole("button", { name: /Inspect settings Completed/ });
|
||||
await screen.findByText("Delegate inspection");
|
||||
expect(screen.getAllByRole("button", { name: /Inspect settings/ })).toHaveLength(1);
|
||||
expect(screen.getByTestId("thread-message-region")).toContainElement(task);
|
||||
expect(within(screen.getByTestId("thread-composer-motion")).queryByText("Inspect settings")).not.toBeInTheDocument();
|
||||
view.unmount();
|
||||
render(shell());
|
||||
await screen.findByText("Delegate inspection");
|
||||
fireEvent.click(await screen.findByRole("button", { name: /Delegated work Finished: 1/ }));
|
||||
await screen.findByRole("button", { name: /Inspect settings Completed/ });
|
||||
expect(client.sendMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("clears the welcome draft after a delayed new-chat send and an unchanged round-trip", async () => {
|
||||
const client = makeClient();
|
||||
const store = new ComposerDraftStore();
|
||||
|
||||
Reference in new issue
Block a user