fix(webui): keep completed subagent results with loaded prompts (#6630)
This commit is contained in:
1 parent
e6b0aec2a8
commit
c37af82e3f
19 files changed
+157
-148
No files matched your search
@@ -304,23 +304,27 @@ test("wheel loading hands off to a retained 48px slot; prepend and delayed layou
|
||||
expect(history.reads).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("archived task results stay with the retained boundary when earlier messages load", async ({ page }) => {
|
||||
test("task results stay with their prompts and retain the reading boundary when earlier messages load", async ({ page }) => {
|
||||
const history = await installHistory(page);
|
||||
await page.route("**/api/sessions/**/subagents", (route) => route.fulfill({ json: { tasks: [{
|
||||
task_id: "legacy", revision: 1, label: "Earlier check", task_description: "Check earlier work",
|
||||
await page.route("**/api/sessions/**/subagents", (route) => route.fulfill({ json: { tasks: [
|
||||
{ task_id: "current", label: "Current check", origin_message_id: "u40" },
|
||||
{ task_id: "earlier", label: "Earlier check", origin_message_id: "u28" },
|
||||
].map((task) => ({
|
||||
...task, revision: 1, task_description: "Check work",
|
||||
state: "done", phase: "completed", elapsed_seconds: 2, iteration: 1,
|
||||
tool_events: [], usage: null, receipts: {}, result: "Verified", partial: false,
|
||||
stop_reason: null, error: null, origin_turn_id: "legacy-turn", origin_message_id: null,
|
||||
created_at: 100, completed_at: 102,
|
||||
}] } }));
|
||||
stop_reason: null, error: null, origin_turn_id: null, created_at: 100, completed_at: 102,
|
||||
})) } }));
|
||||
await page.goto("/browser/fixture.html?case=history-boundary&tasks");
|
||||
const body = page.getByTestId("thread-message-region");
|
||||
const otherTasks = body.getByRole("region", { name: "Other tasks" });
|
||||
await expect(otherTasks).toBeAttached();
|
||||
const currentResults = body.locator('[data-user-prompt-id="u40"] + [data-subagent-results]');
|
||||
const earlierResults = body.locator('[data-user-prompt-id="u28"] + [data-subagent-results]');
|
||||
await expect(body.locator("[data-subagent-results]")).toHaveCount(1);
|
||||
await expect(currentResults).toHaveCount(1);
|
||||
// Clicking an offscreen disclosure scrolls it into view and can prefetch history.
|
||||
await positionAtTop(body);
|
||||
await otherTasks.getByRole("button", { name: /Other tasks/ }).click();
|
||||
await expect(otherTasks.getByRole("button", { name: /Earlier check Completed/ })).toBeVisible();
|
||||
await currentResults.locator("[data-subagent-results-summary]").click();
|
||||
await expect(currentResults.getByRole("button", { name: /Current check Completed/ })).toBeVisible();
|
||||
await stableLayout(body);
|
||||
const originalTop = await positionAtTop(body);
|
||||
await body.hover();
|
||||
@@ -336,9 +340,13 @@ test("archived task results stay with the retained boundary when earlier message
|
||||
await expect(page.locator(".thread-history-slot")).toHaveCount(0);
|
||||
await stableLayout(body);
|
||||
await expectAnchorCoordinate(body, "Question 40", preCompletionAnchorTop);
|
||||
await expect(otherTasks).toHaveCount(1);
|
||||
await expect(otherTasks.getByRole("button", { name: /Other tasks/ })).toHaveAttribute("aria-expanded", "true");
|
||||
await expect(body.locator("[data-subagent-results]")).toHaveCount(2);
|
||||
await expect(currentResults.locator("[data-subagent-results-summary]")).toHaveAttribute("aria-expanded", "true");
|
||||
await expect(currentResults.getByRole("button", { name: /Current check Completed/ })).toBeVisible();
|
||||
await expect(earlierResults.locator("[data-subagent-results-summary]")).toHaveAttribute("aria-expanded", "false");
|
||||
expect(history.reads).toHaveLength(1);
|
||||
await earlierResults.locator("[data-subagent-results-summary]").click();
|
||||
await expect(earlierResults.getByRole("button", { name: /Earlier check Completed/ })).toBeVisible();
|
||||
});
|
||||
|
||||
test("touch reveals a static partial ready header, arms only on release, and retains a stable full loading header", async ({ browser, baseURL }) => {
|
||||
|
||||
@@ -10,6 +10,27 @@ async function settledMotion(target: Locator) {
|
||||
}
|
||||
|
||||
for (const width of [1440, 390]) {
|
||||
test(`opens a session without detached past results at ${width}px`, async ({ page }, info) => {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await page.goto("/browser/fixture.html?case=subagent-dock&past&saved");
|
||||
const messages = page.getByTestId("thread-message-region");
|
||||
const archives = messages.locator("[data-subagent-results]");
|
||||
await expect(page.getByTestId("subagent-task-dock-trigger")).toContainText("Running: 3");
|
||||
await expect(archives).toHaveCount(0);
|
||||
await page.getByRole("button", { name: "全部完成", exact: true }).click();
|
||||
await expect(archives).toHaveCount(1);
|
||||
await expect(archives).toContainText("Completed: 3");
|
||||
await archives.locator("[data-subagent-results-summary]").click();
|
||||
await expect(archives.locator("[data-subagent-id]")).toHaveCount(3);
|
||||
await messages.evaluate(node => { node.scrollTop = 0; });
|
||||
await settledMotion(messages);
|
||||
await page.screenshot({ path: info.outputPath("results-with-prompt.png") });
|
||||
await page.reload();
|
||||
await expect(archives).toHaveCount(1);
|
||||
await expect(archives).toContainText("Completed: 3");
|
||||
await expect(page.getByTestId("subagent-task-dock-trigger")).toHaveCount(0);
|
||||
});
|
||||
|
||||
test(`keeps subtasks reachable through long replies, independent list scrolling and detail handoff at ${width}px`, async ({ page }, info) => {
|
||||
const errors: string[] = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
|
||||
@@ -7,11 +7,6 @@ import { ThreadMessages } from "@/components/thread/ThreadMessages";
|
||||
import { isActiveSubagentTask, type ObservedSubagentTask } from "@/lib/subagent-tasks";
|
||||
import type { UIMessage } from "@/lib/types";
|
||||
|
||||
export function useHasSubagentResults(): boolean {
|
||||
const context = useSubagentTasks();
|
||||
return context?.tasks.some((task) => !isActiveSubagentTask(task)) ?? false;
|
||||
}
|
||||
|
||||
/** Exact initiating prompts win; replayed IDs fall back to the turn's first user message. */
|
||||
function groupResults(messages: UIMessage[], tasks: ObservedSubagentTask[]) {
|
||||
const promptsById = new Map<string, UIMessage>();
|
||||
@@ -25,20 +20,16 @@ function groupResults(messages: UIMessage[], tasks: ObservedSubagentTask[]) {
|
||||
}
|
||||
|
||||
const byMessage = new Map<string, ObservedSubagentTask[]>();
|
||||
const unlinked: ObservedSubagentTask[] = [];
|
||||
for (const task of tasks) {
|
||||
if (isActiveSubagentTask(task)) continue;
|
||||
const prompt = (task.origin_message_id ? promptsById.get(task.origin_message_id) : undefined)
|
||||
?? (task.origin_turn_id ? firstPromptByTurn.get(task.origin_turn_id) : undefined);
|
||||
if (!prompt) {
|
||||
unlinked.push(task);
|
||||
continue;
|
||||
}
|
||||
if (!prompt) continue;
|
||||
const group = byMessage.get(prompt.id) ?? [];
|
||||
group.push(task);
|
||||
byMessage.set(prompt.id, group);
|
||||
}
|
||||
return { byMessage, unlinked };
|
||||
return byMessage;
|
||||
}
|
||||
|
||||
export function SubagentThreadMessages(props: ComponentProps<typeof ThreadMessages>) {
|
||||
@@ -65,13 +56,8 @@ export function SubagentThreadMessages(props: ComponentProps<typeof ThreadMessag
|
||||
};
|
||||
|
||||
return <ThreadMessages {...props}
|
||||
beforeMessages={groups.unlinked.length ? <>
|
||||
{props.beforeMessages}
|
||||
<SubagentResults tasks={groups.unlinked} unlinked expanded={expanded(groups.unlinked)}
|
||||
onToggle={() => toggle(groups.unlinked)} />
|
||||
</> : props.beforeMessages}
|
||||
afterUserMessage={(message) => {
|
||||
const results = groups.byMessage.get(message.id);
|
||||
const results = groups.get(message.id);
|
||||
return <>
|
||||
{props.afterUserMessage?.(message)}
|
||||
{results ? <SubagentResults tasks={results} expanded={expanded(results)}
|
||||
@@ -80,9 +66,8 @@ export function SubagentThreadMessages(props: ComponentProps<typeof ThreadMessag
|
||||
}} />;
|
||||
}
|
||||
|
||||
function SubagentResults({ tasks, unlinked = false, expanded, onToggle }: {
|
||||
function SubagentResults({ tasks, expanded, onToggle }: {
|
||||
tasks: ObservedSubagentTask[];
|
||||
unlinked?: boolean;
|
||||
expanded: boolean;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
@@ -90,13 +75,13 @@ function SubagentResults({ tasks, unlinked = false, expanded, onToggle }: {
|
||||
const rowsId = useId();
|
||||
const completed = tasks.filter((task) => task.state === "done").length;
|
||||
const attention = tasks.filter((task) => task.state === "error" || task.state === "incomplete" || task.state === "interrupted").length;
|
||||
const title = t(unlinked ? "thread.subagents.otherWorkTitle" : "thread.subagents.workTitle");
|
||||
const title = t("thread.subagents.workTitle");
|
||||
const summary = completed === tasks.length
|
||||
? t("thread.subagents.completed", { count: completed })
|
||||
: t("thread.subagents.finished", { count: tasks.length });
|
||||
|
||||
return <section data-subagent-results aria-label={title}
|
||||
className={`thread-message-row mt-2 grid grid-cols-[1rem_minmax(0,1fr)_minmax(6rem,max-content)_3rem] items-center gap-x-2.5 ${unlinked ? "mb-5" : ""}`}>
|
||||
className="thread-message-row mt-2 grid grid-cols-[1rem_minmax(0,1fr)_minmax(6rem,max-content)_3rem] items-center gap-x-2.5">
|
||||
<button type="button" data-thread-disclosure data-subagent-results-summary aria-expanded={expanded} aria-controls={rowsId}
|
||||
onClick={onToggle}
|
||||
className="col-span-full grid min-h-11 w-full min-w-0 grid-cols-subgrid items-center gap-y-0.5 rounded-control py-2 text-left text-[13px] leading-5 text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none sm:min-h-9 sm:py-1.5">
|
||||
@@ -109,7 +94,6 @@ function SubagentResults({ tasks, unlinked = false, expanded, onToggle }: {
|
||||
<ChevronRight className={`col-start-4 row-start-1 h-3.5 w-3.5 shrink-0 justify-self-end transition-transform motion-reduce:transition-none ${expanded ? "rotate-90" : ""}`} aria-hidden />
|
||||
</button>
|
||||
<div id={rowsId} hidden={!expanded} className={`col-span-full grid-cols-subgrid pb-1 ${expanded ? "grid" : "hidden"}`}>
|
||||
{unlinked ? <p className="col-span-full py-2 text-xs text-muted-foreground">{t("thread.subagents.unlinkedHelp")}</p> : null}
|
||||
<ol className="col-span-full grid grid-cols-subgrid">
|
||||
{tasks.map((task) => <li key={task.task_id} className="col-span-full grid min-w-0 grid-cols-subgrid">
|
||||
<SubagentTaskButton task={task} surface="archive" />
|
||||
|
||||
@@ -16,6 +16,7 @@ import { useMediaQuery } from "@/hooks/useMediaQuery";
|
||||
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
|
||||
import { fmtDateTime, formatMessageHoverTime } from "@/lib/format-time";
|
||||
import { projectActivityTimeline, type TurnUnit } from "@/lib/activity-timeline";
|
||||
import { withoutSubagentCreateActivity } from "@/lib/subagent-create-activity";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types";
|
||||
|
||||
@@ -107,10 +108,12 @@ export function ThreadMessages({
|
||||
const { activityMode } = useLocalPreferences();
|
||||
const messageListRef = useRef<HTMLDivElement>(null);
|
||||
const mobileActions = useMediaQuery("(max-width: 767px)");
|
||||
const units = useMemo(
|
||||
() => buildDisplayUnits(messages),
|
||||
[messages],
|
||||
);
|
||||
const rawUnits = useMemo(() => buildDisplayUnits(messages), [messages]);
|
||||
const units = useMemo(() => rawUnits.map((unit) => unit.type === "activity"
|
||||
? { ...unit, messages: unit.messages.flatMap((message) => {
|
||||
const visible = withoutSubagentCreateActivity(message);
|
||||
return visible ? [visible] : [];
|
||||
}) } : unit), [rawUnits]);
|
||||
const forkBoundaryAfterUnitIndex = useMemo(
|
||||
() => unitIndexAfterMessageCount(units, forkBoundaryMessageCount),
|
||||
[forkBoundaryMessageCount, units],
|
||||
@@ -135,8 +138,8 @@ export function ThreadMessages({
|
||||
const currentTurnStartIndex = isStreaming
|
||||
? activeTurnStartIndex(units, activeTurnId)
|
||||
: units.length;
|
||||
const unitKeys = useMemo(() => unitKeysForDisplay(units), [units]);
|
||||
const scrollAnchors = useMemo(() => scrollAnchorsForUnits(units), [units]);
|
||||
const unitKeys = useMemo(() => unitKeysForDisplay(rawUnits), [rawUnits]);
|
||||
const scrollAnchors = useMemo(() => scrollAnchorsForUnits(rawUnits), [rawUnits]);
|
||||
const messageBlocks = useMemo(
|
||||
() => completedMessageBlocks(
|
||||
units,
|
||||
@@ -920,6 +923,7 @@ function currentActivityClusterIndices(
|
||||
for (let i = units.length - 1; i >= 0; i -= 1) {
|
||||
const unit = units[i];
|
||||
if (unit.type === "activity") {
|
||||
if (!unit.messages.length) continue;
|
||||
if (!markedCurrentActivity) {
|
||||
indices.add(i);
|
||||
markedCurrentActivity = true;
|
||||
@@ -1046,7 +1050,8 @@ function completedMessageBlocks(
|
||||
const result: CompletedMessageBlocks = {
|
||||
blockKeys: new Array<string | undefined>(units.length),
|
||||
blockIndices: new Set<number>(),
|
||||
suppressedActivityIndices: new Set<number>(),
|
||||
suppressedActivityIndices: new Set(units.flatMap((unit, index) =>
|
||||
unit.type === "activity" && !unit.messages.length ? [index] : [])),
|
||||
activityByBlock: new Map(),
|
||||
};
|
||||
let groupStart = 0;
|
||||
@@ -1077,7 +1082,7 @@ function completedMessageBlocks(
|
||||
const activityByBlock = new Map<number, Array<Extract<DisplayUnit, { type: "activity" }>>>();
|
||||
for (const index of indices) {
|
||||
const unit = units[index];
|
||||
if (unit.type !== "activity") continue;
|
||||
if (unit.type !== "activity" || !unit.messages.length) continue;
|
||||
const blockIndex = blockIndices.find((candidate) => candidate > index) ?? blockIndices.at(-1);
|
||||
if (blockIndex === undefined) continue;
|
||||
result.suppressedActivityIndices.add(index);
|
||||
|
||||
@@ -13,7 +13,7 @@ import { ArrowDown } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { PromptRail } from "@/components/thread/PromptRail";
|
||||
import { SubagentThreadMessages, useHasSubagentResults } from "@/components/thread/SubagentTaskResults";
|
||||
import { SubagentThreadMessages } from "@/components/thread/SubagentTaskResults";
|
||||
import { DiagramScope } from "@/components/markdown-diagrams/context";
|
||||
import { DiffViewportContext } from "./activity/DiffViewportContext";
|
||||
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
|
||||
@@ -460,8 +460,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
},
|
||||
});
|
||||
}
|
||||
const hasTaskResults = useHasSubagentResults();
|
||||
const hasMessages = messages.length > 0 || (hasTaskResults && conversationReady);
|
||||
const hasMessages = messages.length > 0;
|
||||
const hasThreadLayout = hasMessages || initialLoading;
|
||||
useLayoutEffect(() => {
|
||||
scrollRef.current = hasMessages
|
||||
|
||||
@@ -1979,8 +1979,6 @@
|
||||
},
|
||||
"interruptedHelp": "The host restarted before this task finished. It has not been restarted automatically.",
|
||||
"workTitle": "Subtasks",
|
||||
"otherWorkTitle": "Other tasks",
|
||||
"unlinkedHelp": "These tasks have no matching request in the displayed messages.",
|
||||
"progress": "{{completed}} of {{total}} completed",
|
||||
"running": "Running: {{count}}",
|
||||
"finished": "Finished: {{count}}",
|
||||
|
||||
@@ -1797,8 +1797,6 @@
|
||||
},
|
||||
"interruptedHelp": "El servidor se reinició antes de terminar esta tarea. No se ha vuelto a ejecutar automáticamente.",
|
||||
"workTitle": "Subtareas",
|
||||
"otherWorkTitle": "Otras tareas",
|
||||
"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}}",
|
||||
|
||||
@@ -1797,8 +1797,6 @@
|
||||
},
|
||||
"interruptedHelp": "Le serveur a redémarré avant la fin de cette tâche. Elle n’a pas été relancée automatiquement.",
|
||||
"workTitle": "Sous-tâches",
|
||||
"otherWorkTitle": "Autres tâches",
|
||||
"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}}",
|
||||
|
||||
@@ -1797,8 +1797,6 @@
|
||||
},
|
||||
"interruptedHelp": "Server dimulai ulang sebelum tugas ini selesai. Tugas tidak dijalankan ulang secara otomatis.",
|
||||
"workTitle": "Subtugas",
|
||||
"otherWorkTitle": "Tugas lain",
|
||||
"unlinkedHelp": "Permintaan yang sesuai dengan tugas ini tidak ditemukan dalam pesan yang ditampilkan.",
|
||||
"progress": "{{completed}} dari {{total}} selesai",
|
||||
"running": "Berjalan: {{count}}",
|
||||
"finished": "Berakhir: {{count}}",
|
||||
|
||||
@@ -1797,8 +1797,6 @@
|
||||
},
|
||||
"interruptedHelp": "タスクの完了前にサーバーが再起動しました。タスクは自動的に再実行されていません。",
|
||||
"workTitle": "サブタスク",
|
||||
"otherWorkTitle": "ほかのタスク",
|
||||
"unlinkedHelp": "表示中のメッセージには、これらのタスクに対応する依頼がありません。",
|
||||
"progress": "{{total}} 件中 {{completed}} 件完了",
|
||||
"running": "実行中: {{count}}",
|
||||
"finished": "終了: {{count}}",
|
||||
|
||||
@@ -1797,8 +1797,6 @@
|
||||
},
|
||||
"interruptedHelp": "작업이 완료되기 전에 서버가 다시 시작되었습니다. 작업은 자동으로 다시 실행되지 않았습니다.",
|
||||
"workTitle": "하위 작업",
|
||||
"otherWorkTitle": "다른 작업",
|
||||
"unlinkedHelp": "표시된 메시지에서 이 작업에 해당하는 요청을 찾을 수 없습니다.",
|
||||
"progress": "{{total}}개 중 {{completed}}개 완료",
|
||||
"running": "진행 중: {{count}}",
|
||||
"finished": "종료: {{count}}",
|
||||
|
||||
@@ -1799,8 +1799,6 @@
|
||||
},
|
||||
"interruptedHelp": "O servidor reiniciou antes de concluir esta tarefa. Ela não foi executada novamente automaticamente.",
|
||||
"workTitle": "Subtarefas",
|
||||
"otherWorkTitle": "Outras tarefas",
|
||||
"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}}",
|
||||
|
||||
@@ -1797,8 +1797,6 @@
|
||||
},
|
||||
"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": "Tác vụ con",
|
||||
"otherWorkTitle": "Tác vụ 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}}",
|
||||
|
||||
@@ -1979,8 +1979,6 @@
|
||||
},
|
||||
"interruptedHelp": "后端重启时此任务尚未结束,任务没有自动恢复或重新执行。",
|
||||
"workTitle": "子任务",
|
||||
"otherWorkTitle": "其他任务",
|
||||
"unlinkedHelp": "未找到这些任务在当前显示消息中的原始请求。",
|
||||
"progress": "已完成 {{completed}} / {{total}} 项",
|
||||
"running": "{{count}} 项进行中",
|
||||
"finished": "{{count}} 项已结束",
|
||||
|
||||
@@ -1797,8 +1797,6 @@
|
||||
},
|
||||
"interruptedHelp": "後端重新啟動時此任務尚未結束,任務沒有自動恢復或重新執行。",
|
||||
"workTitle": "子任務",
|
||||
"otherWorkTitle": "其他任務",
|
||||
"unlinkedHelp": "未找到這些任務在目前顯示訊息中的原始請求。",
|
||||
"progress": "已完成 {{completed}} / {{total}} 項",
|
||||
"running": "{{count}} 項進行中",
|
||||
"finished": "{{count}} 項已結束",
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { canonicalToolTrace, formatToolCallTrace } from "@/lib/tool-traces";
|
||||
import type { ToolProgressEvent, UIMessage } from "@/lib/types";
|
||||
|
||||
/** Only successful create activity has a dedicated task surface. */
|
||||
function isSubagentCreateActivity(event: ToolProgressEvent): boolean {
|
||||
if (event.name !== "subagent" || (event.phase !== "start" && event.phase !== "end")
|
||||
|| event.error != null) return false;
|
||||
let args = event.arguments;
|
||||
if (typeof args === "string") {
|
||||
try { args = JSON.parse(args); } catch { return false; }
|
||||
}
|
||||
return args != null && typeof args === "object" && !Array.isArray(args)
|
||||
&& (args as Record<string, unknown>).action === "create";
|
||||
}
|
||||
|
||||
/** Strip only redundant create traces from a display copy; null means no visible activity remains. */
|
||||
export function withoutSubagentCreateActivity(message: UIMessage): UIMessage | null {
|
||||
if (message.kind !== "trace" || !message.toolEvents?.some(isSubagentCreateActivity)) return message;
|
||||
const hidden = message.toolEvents.filter(isSubagentCreateActivity);
|
||||
const remaining = message.toolEvents.filter((event) => !isSubagentCreateActivity(event));
|
||||
const traceSet = (events: ToolProgressEvent[]) => new Set(events.map(formatToolCallTrace)
|
||||
.filter((line): line is string => line !== null).map(canonicalToolTrace));
|
||||
const hiddenLines = traceSet(hidden);
|
||||
const retainedLines = traceSet(remaining);
|
||||
const original = message.traces?.length ? message.traces : message.content ? [message.content] : [];
|
||||
const traces = original.filter((line) => !hiddenLines.has(canonicalToolTrace(line))
|
||||
|| retainedLines.has(canonicalToolTrace(line)));
|
||||
if (!remaining.length && !traces.length && !message.fileEdits?.length && !message.traceDetail
|
||||
&& !message.media?.length && !message.images?.length && !message.reasoning && !message.reasoningStreaming) return null;
|
||||
return { ...message, toolEvents: remaining.length ? remaining : undefined,
|
||||
traces, content: traces.at(-1) ?? "" };
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { SubagentTaskDock } from "@/components/thread/SubagentTaskDock";
|
||||
import { SubagentThreadMessages, useHasSubagentResults } from "@/components/thread/SubagentTaskResults";
|
||||
import { SubagentThreadMessages } from "@/components/thread/SubagentTaskResults";
|
||||
import { SubagentTasksProvider } from "@/components/thread/SubagentTasks";
|
||||
import { setAppLanguage } from "@/i18n";
|
||||
import { DEFAULT_LOCAL_PREFS, LOCAL_PREFS_STORAGE_KEY, writeLocalPreferences } from "@/lib/local-preferences";
|
||||
@@ -47,9 +47,6 @@ function emitTask(snapshot: SubagentTaskSnapshot) {
|
||||
chatHandlers.forEach((handler) => handler({ event: "subagent_task", chat_id: "a", task: snapshot }));
|
||||
});
|
||||
}
|
||||
function ResultsPresence() {
|
||||
return <output data-testid="has-results">{useHasSubagentResults() ? "yes" : "no"}</output>;
|
||||
}
|
||||
function layout({ threadMessages = messages, sessionKey = "websocket:a", liveEvents = true, historyEnabled = false, onActivityToggle }: {
|
||||
threadMessages?: UIMessage[];
|
||||
sessionKey?: string;
|
||||
@@ -58,13 +55,12 @@ function layout({ threadMessages = messages, sessionKey = "websocket:a", liveEve
|
||||
onActivityToggle?: () => void;
|
||||
} = {}) {
|
||||
return <SubagentTasksProvider client={client} sessionKey={sessionKey} token="tok" enabled liveEvents={liveEvents} historyEnabled={historyEnabled}>
|
||||
<ResultsPresence />
|
||||
<div data-testid="messages"><SubagentThreadMessages messages={threadMessages} onActivityToggle={onActivityToggle} /></div>
|
||||
<div data-testid="composer" className="thread-composer-stack"><SubagentTaskDock /><textarea aria-label="Message" /></div>
|
||||
</SubagentTasksProvider>;
|
||||
}
|
||||
function summary(region: HTMLElement) {
|
||||
return within(region).getByRole("button", { name: /^(Subtasks|Other tasks) (Completed|Finished):/ });
|
||||
return within(region).getByRole("button", { name: /^Subtasks (Completed|Finished):/ });
|
||||
}
|
||||
function expectBefore(first: Node, second: Node) {
|
||||
expect(first.compareDocumentPosition(second) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
@@ -99,14 +95,12 @@ describe("subagent result archives", () => {
|
||||
expect(await screen.findByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 3");
|
||||
const transcript = screen.getByTestId("messages");
|
||||
expect(transcript.querySelector("[data-subagent-results]")).toBeNull();
|
||||
expect(screen.getByTestId("has-results")).toHaveTextContent("no");
|
||||
expect(transcript).not.toHaveTextContent("Config check");
|
||||
expect(transcript).not.toHaveTextContent("Waiting check");
|
||||
expect(transcript).not.toHaveTextContent("Stopping check");
|
||||
|
||||
emitTask(task({ revision: 2, result: "Full findings stay in details" }));
|
||||
const archive = screen.getByRole("region", { name: "Subtasks" });
|
||||
expect(screen.getByTestId("has-results")).toHaveTextContent("yes");
|
||||
expect(summary(archive)).toHaveTextContent("Completed: 1");
|
||||
expect(summary(archive).querySelector("img")).toHaveAttribute("src", "/brand/nanobot_mark.svg");
|
||||
expect(summary(archive).querySelector("img")).toHaveAttribute("alt", "");
|
||||
@@ -237,7 +231,7 @@ describe("subagent result archives", () => {
|
||||
expect(screen.getByTestId("messages").querySelectorAll("[data-subagent-id]")).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("keeps unmatched terminal work before the chat and preserves open details when its source is loaded", async () => {
|
||||
it("shows older results only with their loaded prompt and preserves details through history navigation", async () => {
|
||||
vi.mocked(fetch).mockImplementation(async () => response([
|
||||
task({ task_id: "older", label: "Earlier check", origin_turn_id: "older-turn", origin_message_id: "older-prompt",
|
||||
result: "## Earlier findings\n\nThe saved result remains available" }),
|
||||
@@ -246,27 +240,26 @@ describe("subagent result archives", () => {
|
||||
]));
|
||||
const user = userEvent.setup();
|
||||
const view = render(layout());
|
||||
const unlinked = await screen.findByRole("region", { name: "Other tasks" });
|
||||
expectBefore(unlinked, screen.getByText("Inspect config"));
|
||||
expect(summary(unlinked)).toHaveAttribute("aria-expanded", "false");
|
||||
await user.click(summary(unlinked));
|
||||
expect(within(unlinked).getByText("These tasks have no matching request in the displayed messages.")).toBeVisible();
|
||||
expect(unlinked).not.toHaveTextContent("Unlinked live check");
|
||||
await user.click(within(unlinked).getByRole("button", { name: "Earlier check Completed 4s" }));
|
||||
const detail = screen.getByRole("dialog", { name: "Earlier check" });
|
||||
expect(await within(detail).findByRole("heading", { name: "Earlier findings" })).toBeVisible();
|
||||
|
||||
view.rerender(layout({ threadMessages: [
|
||||
expect(await screen.findByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 1");
|
||||
expect(screen.getByTestId("messages").querySelector("[data-subagent-results]")).toBeNull();
|
||||
const olderMessages: UIMessage[] = [
|
||||
{ id: "older-prompt", role: "user", content: "Inspect earlier work", turnId: "older-turn", createdAt: 99_000 },
|
||||
...messages,
|
||||
] }));
|
||||
expect(screen.getByRole("dialog", { name: "Earlier check" })).toBe(detail);
|
||||
];
|
||||
view.rerender(layout({ threadMessages: olderMessages }));
|
||||
let linked = screen.getByRole("region", { name: "Subtasks" });
|
||||
expect(summary(linked)).toHaveAttribute("aria-expanded", "false");
|
||||
await user.click(summary(linked));
|
||||
await user.click(within(linked).getByRole("button", { name: "Earlier check Completed 4s" }));
|
||||
const detail = screen.getByRole("dialog", { name: "Earlier check" });
|
||||
expect(await within(detail).findByRole("heading", { name: "Earlier findings" })).toBeVisible();
|
||||
view.rerender(layout());
|
||||
expect(screen.getByTestId("messages").querySelector("[data-subagent-results]")).toBeNull();
|
||||
expect(within(detail).getByText("The saved result remains available")).toBeVisible();
|
||||
view.rerender(layout({ threadMessages: olderMessages }));
|
||||
await user.keyboard("{Escape}");
|
||||
expect(screen.queryByRole("region", { name: "Other tasks" })).not.toBeInTheDocument();
|
||||
const linked = screen.getByRole("region", { name: "Subtasks" });
|
||||
const header = summary(linked);
|
||||
expect(header).toHaveAttribute("aria-expanded", "true");
|
||||
linked = screen.getByRole("region", { name: "Subtasks" });
|
||||
expect(summary(linked)).toHaveAttribute("aria-expanded", "true");
|
||||
await waitFor(() => expect(within(linked).getByRole("button", { name: "Earlier check Completed 4s" })).toHaveFocus());
|
||||
expect(screen.getByTestId("messages").querySelectorAll('[data-subagent-id="older"]')).toHaveLength(1);
|
||||
expectBefore(screen.getByText("Inspect earlier work"), linked);
|
||||
@@ -291,7 +284,7 @@ describe("subagent result archives", () => {
|
||||
expect(within(replayed).getByRole("button", { name: "Config check Completed 4s" })).toBeVisible();
|
||||
});
|
||||
|
||||
it("preserves each disclosure through other task outcomes, history prepends and Activity preference changes", async () => {
|
||||
it("preserves disclosure through off-page task outcomes, history prepends and Activity preference changes", async () => {
|
||||
act(() => { writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, activityMode: "expanded" }); });
|
||||
vi.mocked(fetch).mockImplementation(async () => response([
|
||||
task(),
|
||||
@@ -309,9 +302,7 @@ describe("subagent result archives", () => {
|
||||
emitTask(task({ task_id: "other", label: "Other check", revision: 2, state: "error", error: "Other work failed",
|
||||
origin_message_id: null, origin_turn_id: null, created_at: 102 }));
|
||||
expect(summary(archive)).toHaveAttribute("aria-expanded", "true");
|
||||
const unlinked = screen.getByRole("region", { name: "Other tasks" });
|
||||
expect(summary(unlinked)).toHaveAttribute("aria-expanded", "false");
|
||||
await user.click(summary(unlinked));
|
||||
expect(screen.getByTestId("messages").querySelector('[data-subagent-id="other"]')).toBeNull();
|
||||
view.rerender(layout({ threadMessages: [
|
||||
{ id: "prepended", role: "user", content: "Earlier request from this turn", turnId: "turn-a", createdAt: 99_000 },
|
||||
...messages,
|
||||
@@ -321,7 +312,6 @@ describe("subagent result archives", () => {
|
||||
expect(within(retained).getByRole("button", { name: "Config check Completed 4s" })).toBeVisible();
|
||||
expect([...retained.querySelectorAll("[data-subagent-id]")].map((row) => row.getAttribute("data-subagent-id")))
|
||||
.toEqual(["task-1", "second"]);
|
||||
expect(summary(screen.getByRole("region", { name: "Other tasks" }))).toHaveAttribute("aria-expanded", "true");
|
||||
await user.click(summary(retained));
|
||||
act(() => { writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, activityMode: "expanded" }); });
|
||||
expect(summary(retained)).toHaveAttribute("aria-expanded", "false");
|
||||
|
||||
@@ -138,9 +138,7 @@ describe("session-owned task UI", () => {
|
||||
const archive = await openArchive(user);
|
||||
expect(taskIds(archive)).toEqual(older.map(saved => saved.task_id));
|
||||
expect(within(archive).queryByRole("button", { name: /Config check Running/ })).not.toBeInTheDocument();
|
||||
const other = await openArchive(user, "Other tasks");
|
||||
await user.click(within(other).getByRole("button", { name: /Earlier check Completed/ }));
|
||||
expect(within(screen.getByRole("dialog", { name: "Earlier check" })).getByText("Saved result")).toBeVisible();
|
||||
expect(taskIds(screen.getByTestId("messages"))).toEqual(older.map(saved => saved.task_id));
|
||||
expect(requestMutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -901,7 +899,7 @@ describe("session-owned task UI", () => {
|
||||
expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps legacy work separate after refresh and preserves its disclosure through local history prepends", async () => {
|
||||
it("keeps unmatched legacy work out of the transcript through refresh and unrelated history prepends", 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**" }),
|
||||
@@ -910,63 +908,20 @@ describe("session-owned task UI", () => {
|
||||
const user = userEvent.setup();
|
||||
const view = render(layout());
|
||||
await screen.findByTestId("subagent-task-dock-trigger");
|
||||
const otherWork = screen.getByRole("region", { name: "Other tasks" });
|
||||
const header = within(otherWork).getByRole("button", { name: /Other tasks/ });
|
||||
expect(header).toHaveAttribute("aria-expanded", "false");
|
||||
expect(otherWork.compareDocumentPosition(screen.getByText("Inspect config")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(screen.queryByRole("region", { name: "Subtasks" })).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId("messages")).not.toHaveTextContent("Config check");
|
||||
await user.click(header);
|
||||
expect(within(otherWork).getByText("These tasks have no matching request in the displayed messages.")).toBeVisible();
|
||||
await user.click(within(otherWork).getByRole("button", { name: /Nanjing weather Completed/ }));
|
||||
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}");
|
||||
expect(taskIds(await openTaskList(user))).toEqual(["task-1"]);
|
||||
expect(taskIds(screen.getByTestId("messages"))).toEqual([]);
|
||||
view.rerender(layout({ threadMessages: [
|
||||
{ id: "cached-prompt", role: "user", content: "Earlier cached prompt", createdAt: 99_000 },
|
||||
...messages,
|
||||
] }));
|
||||
const expanded = screen.getByRole("region", { name: "Other tasks" });
|
||||
expect(within(expanded).getByRole("button", { name: /Other tasks/ })).toHaveAttribute("aria-expanded", "true");
|
||||
expect(within(expanded).getByRole("button", { name: /Nanjing weather Completed/ })).toBeVisible();
|
||||
expect(taskIds(screen.getByTestId("messages"))).toEqual([]);
|
||||
view.unmount();
|
||||
render(layout());
|
||||
const restored = await screen.findByRole("region", { name: "Other tasks" });
|
||||
expect(within(restored).getByRole("button", { name: /Other tasks/ })).toHaveAttribute("aria-expanded", "false");
|
||||
expect(restored.compareDocumentPosition(screen.getByText("Inspect config")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(taskIds(await openTaskList(user))).toEqual(["task-1"]);
|
||||
expect(taskIds(screen.getByTestId("messages"))).toEqual([]);
|
||||
expect(requestMutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reattaches archived work when its prompt loads without duplicating it, closing details or losing focus", async () => {
|
||||
vi.mocked(fetch).mockImplementation(async () => response([
|
||||
task({ task_id: "older", label: "Earlier check", state: "done", completed_at: 102, result: "Earlier finding", origin_turn_id: "older-turn", origin_message_id: "older-prompt" }),
|
||||
task({ created_at: 200 }),
|
||||
]));
|
||||
const user = userEvent.setup();
|
||||
const view = render(layout());
|
||||
const otherWork = await openArchive(user, "Other tasks");
|
||||
await user.click(within(otherWork).getByRole("button", { name: /Earlier check Completed/ }));
|
||||
const detail = screen.getByRole("dialog", { name: "Earlier check" });
|
||||
view.rerender(layout({ threadMessages: [
|
||||
{ id: "older-prompt", role: "user", content: "Inspect earlier work", turnId: "older-turn", createdAt: 99_000 },
|
||||
...messages,
|
||||
] }));
|
||||
expect(detail).toBeVisible();
|
||||
expect(within(detail).getByText("Earlier finding")).toBeVisible();
|
||||
await user.keyboard("{Escape}");
|
||||
expect(screen.queryByRole("region", { name: "Other tasks" })).not.toBeInTheDocument();
|
||||
const archive = screen.getByRole("region", { name: "Subtasks" });
|
||||
const summary = within(archive).getByRole("button", { name: /Subtasks/ });
|
||||
expect(summary).toHaveAttribute("aria-expanded", "true");
|
||||
expect(taskIds(screen.getByTestId("messages"))).toEqual(["older"]);
|
||||
expect(screen.getByText("Inspect earlier work").compareDocumentPosition(archive) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(screen.getByText("Inspect config").compareDocumentPosition(archive) & Node.DOCUMENT_POSITION_PRECEDING).toBeTruthy();
|
||||
const row = within(archive).getByRole("button", { name: /Earlier check Completed/ });
|
||||
await waitFor(() => expect(row).toHaveFocus());
|
||||
expect(row).toBeVisible();
|
||||
});
|
||||
|
||||
it("merges live work before the initial read without polling or rolling back completed work", async () => {
|
||||
let resolveRead!: (value: Response) => void;
|
||||
vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { resolveRead = resolve; }));
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
unitKeysForDisplay,
|
||||
} from "@/components/thread/ThreadMessages";
|
||||
import { preloadMarkdownText } from "@/components/MarkdownText";
|
||||
import { projectThreadEvents } from "@/lib/thread-event-projection";
|
||||
import type { UIMessage } from "@/lib/types";
|
||||
|
||||
// These DOM tests exercise disclosure/source contracts; the real shadow renderer runs in browser tests.
|
||||
@@ -1179,6 +1180,40 @@ describe("ThreadMessages", () => {
|
||||
expect(dividerIndex).toBe(branchPromptIndex - 1);
|
||||
});
|
||||
|
||||
it("hides redundant task creation while retaining failed creates and other tool activity", async () => {
|
||||
const messages = projectThreadEvents([
|
||||
{ event: "user_message", chat_id: "a", starts_turn: true, turn_id: "turn", text: "Inspect" },
|
||||
{ event: "message", chat_id: "a", turn_id: "turn", kind: "progress", text: "Tools", tool_events: [
|
||||
{ call_id: "create", name: "subagent", phase: "end", arguments: { action: "create" } },
|
||||
{ call_id: "failed", name: "subagent", phase: "error", arguments: { action: "create" }, error: "Creation failed" },
|
||||
{ call_id: "check", name: "subagent", phase: "end", arguments: { action: "check" } },
|
||||
{ call_id: "exec", name: "exec", phase: "end", arguments: { command: "pwd" } },
|
||||
] },
|
||||
{ event: "message", chat_id: "a", turn_id: "turn", text: "Done" },
|
||||
]);
|
||||
render(<ThreadMessages messages={messages} />);
|
||||
openAssistantBlockMenu();
|
||||
fireEvent.click(await screen.findByRole("button", { name: /worked/i }));
|
||||
expect(screen.getByText(/could not create subtask/i)).toBeVisible();
|
||||
expect(screen.getByText(/subtask status retrieved/i)).toBeVisible();
|
||||
expect(screen.getByText(/ran command/i)).toBeVisible();
|
||||
expect(screen.queryByText(/^subtask created/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps the fork boundary after a hidden subagent create activity", () => {
|
||||
const messages: UIMessage[] = [
|
||||
{ id: "original", role: "user", content: "original", createdAt: 1 },
|
||||
{ id: "created", role: "tool", kind: "trace", content: 'subagent({"action":"create"})',
|
||||
traces: ['subagent({"action":"create"})'], createdAt: 2,
|
||||
toolEvents: [{ call_id: "call-1", name: "subagent", phase: "end", arguments: { action: "create" } }] },
|
||||
{ id: "branch", role: "user", content: "branch prompt", createdAt: 3 },
|
||||
];
|
||||
render(<ThreadMessages messages={messages} forkBoundaryMessageCount={2} />);
|
||||
const divider = screen.getByText("Forked from history");
|
||||
expect(divider.compareDocumentPosition(screen.getByText("branch prompt")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||||
expect(screen.queryByText(/subtask created/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps turn unit keys stable across replayed ids and mutable turn sequence", () => {
|
||||
const liveUnits = buildDisplayUnits([
|
||||
{ id: "optimistic-user", role: "user", content: "go", turnId: "turn-1", turnPhase: "user", turnSeq: 0, createdAt: 1 },
|
||||
|
||||
Reference in new issue
Block a user