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);
|
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);
|
const history = await installHistory(page);
|
||||||
await page.route("**/api/sessions/**/subagents", (route) => route.fulfill({ json: { tasks: [{
|
await page.route("**/api/sessions/**/subagents", (route) => route.fulfill({ json: { tasks: [
|
||||||
task_id: "legacy", revision: 1, label: "Earlier check", task_description: "Check earlier work",
|
{ 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,
|
state: "done", phase: "completed", elapsed_seconds: 2, iteration: 1,
|
||||||
tool_events: [], usage: null, receipts: {}, result: "Verified", partial: false,
|
tool_events: [], usage: null, receipts: {}, result: "Verified", partial: false,
|
||||||
stop_reason: null, error: null, origin_turn_id: "legacy-turn", origin_message_id: null,
|
stop_reason: null, error: null, origin_turn_id: null, created_at: 100, completed_at: 102,
|
||||||
created_at: 100, completed_at: 102,
|
})) } }));
|
||||||
}] } }));
|
|
||||||
await page.goto("/browser/fixture.html?case=history-boundary&tasks");
|
await page.goto("/browser/fixture.html?case=history-boundary&tasks");
|
||||||
const body = page.getByTestId("thread-message-region");
|
const body = page.getByTestId("thread-message-region");
|
||||||
const otherTasks = body.getByRole("region", { name: "Other tasks" });
|
const currentResults = body.locator('[data-user-prompt-id="u40"] + [data-subagent-results]');
|
||||||
await expect(otherTasks).toBeAttached();
|
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.
|
// Clicking an offscreen disclosure scrolls it into view and can prefetch history.
|
||||||
await positionAtTop(body);
|
await positionAtTop(body);
|
||||||
await otherTasks.getByRole("button", { name: /Other tasks/ }).click();
|
await currentResults.locator("[data-subagent-results-summary]").click();
|
||||||
await expect(otherTasks.getByRole("button", { name: /Earlier check Completed/ })).toBeVisible();
|
await expect(currentResults.getByRole("button", { name: /Current check Completed/ })).toBeVisible();
|
||||||
await stableLayout(body);
|
await stableLayout(body);
|
||||||
const originalTop = await positionAtTop(body);
|
const originalTop = await positionAtTop(body);
|
||||||
await body.hover();
|
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 expect(page.locator(".thread-history-slot")).toHaveCount(0);
|
||||||
await stableLayout(body);
|
await stableLayout(body);
|
||||||
await expectAnchorCoordinate(body, "Question 40", preCompletionAnchorTop);
|
await expectAnchorCoordinate(body, "Question 40", preCompletionAnchorTop);
|
||||||
await expect(otherTasks).toHaveCount(1);
|
await expect(body.locator("[data-subagent-results]")).toHaveCount(2);
|
||||||
await expect(otherTasks.getByRole("button", { name: /Other tasks/ })).toHaveAttribute("aria-expanded", "true");
|
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);
|
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 }) => {
|
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]) {
|
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) => {
|
test(`keeps subtasks reachable through long replies, independent list scrolling and detail handoff at ${width}px`, async ({ page }, info) => {
|
||||||
const errors: string[] = [];
|
const errors: string[] = [];
|
||||||
page.on("pageerror", error => errors.push(error.message));
|
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 { isActiveSubagentTask, type ObservedSubagentTask } from "@/lib/subagent-tasks";
|
||||||
import type { UIMessage } from "@/lib/types";
|
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. */
|
/** Exact initiating prompts win; replayed IDs fall back to the turn's first user message. */
|
||||||
function groupResults(messages: UIMessage[], tasks: ObservedSubagentTask[]) {
|
function groupResults(messages: UIMessage[], tasks: ObservedSubagentTask[]) {
|
||||||
const promptsById = new Map<string, UIMessage>();
|
const promptsById = new Map<string, UIMessage>();
|
||||||
@@ -25,20 +20,16 @@ function groupResults(messages: UIMessage[], tasks: ObservedSubagentTask[]) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const byMessage = new Map<string, ObservedSubagentTask[]>();
|
const byMessage = new Map<string, ObservedSubagentTask[]>();
|
||||||
const unlinked: ObservedSubagentTask[] = [];
|
|
||||||
for (const task of tasks) {
|
for (const task of tasks) {
|
||||||
if (isActiveSubagentTask(task)) continue;
|
if (isActiveSubagentTask(task)) continue;
|
||||||
const prompt = (task.origin_message_id ? promptsById.get(task.origin_message_id) : undefined)
|
const prompt = (task.origin_message_id ? promptsById.get(task.origin_message_id) : undefined)
|
||||||
?? (task.origin_turn_id ? firstPromptByTurn.get(task.origin_turn_id) : undefined);
|
?? (task.origin_turn_id ? firstPromptByTurn.get(task.origin_turn_id) : undefined);
|
||||||
if (!prompt) {
|
if (!prompt) continue;
|
||||||
unlinked.push(task);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const group = byMessage.get(prompt.id) ?? [];
|
const group = byMessage.get(prompt.id) ?? [];
|
||||||
group.push(task);
|
group.push(task);
|
||||||
byMessage.set(prompt.id, group);
|
byMessage.set(prompt.id, group);
|
||||||
}
|
}
|
||||||
return { byMessage, unlinked };
|
return byMessage;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function SubagentThreadMessages(props: ComponentProps<typeof ThreadMessages>) {
|
export function SubagentThreadMessages(props: ComponentProps<typeof ThreadMessages>) {
|
||||||
@@ -65,13 +56,8 @@ export function SubagentThreadMessages(props: ComponentProps<typeof ThreadMessag
|
|||||||
};
|
};
|
||||||
|
|
||||||
return <ThreadMessages {...props}
|
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) => {
|
afterUserMessage={(message) => {
|
||||||
const results = groups.byMessage.get(message.id);
|
const results = groups.get(message.id);
|
||||||
return <>
|
return <>
|
||||||
{props.afterUserMessage?.(message)}
|
{props.afterUserMessage?.(message)}
|
||||||
{results ? <SubagentResults tasks={results} expanded={expanded(results)}
|
{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[];
|
tasks: ObservedSubagentTask[];
|
||||||
unlinked?: boolean;
|
|
||||||
expanded: boolean;
|
expanded: boolean;
|
||||||
onToggle: () => void;
|
onToggle: () => void;
|
||||||
}) {
|
}) {
|
||||||
@@ -90,13 +75,13 @@ function SubagentResults({ tasks, unlinked = false, expanded, onToggle }: {
|
|||||||
const rowsId = useId();
|
const rowsId = useId();
|
||||||
const completed = tasks.filter((task) => task.state === "done").length;
|
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 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
|
const summary = completed === tasks.length
|
||||||
? t("thread.subagents.completed", { count: completed })
|
? t("thread.subagents.completed", { count: completed })
|
||||||
: t("thread.subagents.finished", { count: tasks.length });
|
: t("thread.subagents.finished", { count: tasks.length });
|
||||||
|
|
||||||
return <section data-subagent-results aria-label={title}
|
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}
|
<button type="button" data-thread-disclosure data-subagent-results-summary aria-expanded={expanded} aria-controls={rowsId}
|
||||||
onClick={onToggle}
|
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">
|
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 />
|
<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>
|
</button>
|
||||||
<div id={rowsId} hidden={!expanded} className={`col-span-full grid-cols-subgrid pb-1 ${expanded ? "grid" : "hidden"}`}>
|
<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">
|
<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">
|
{tasks.map((task) => <li key={task.task_id} className="col-span-full grid min-w-0 grid-cols-subgrid">
|
||||||
<SubagentTaskButton task={task} surface="archive" />
|
<SubagentTaskButton task={task} surface="archive" />
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import { useMediaQuery } from "@/hooks/useMediaQuery";
|
|||||||
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
|
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
|
||||||
import { fmtDateTime, formatMessageHoverTime } from "@/lib/format-time";
|
import { fmtDateTime, formatMessageHoverTime } from "@/lib/format-time";
|
||||||
import { projectActivityTimeline, type TurnUnit } from "@/lib/activity-timeline";
|
import { projectActivityTimeline, type TurnUnit } from "@/lib/activity-timeline";
|
||||||
|
import { withoutSubagentCreateActivity } from "@/lib/subagent-create-activity";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types";
|
import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types";
|
||||||
|
|
||||||
@@ -107,10 +108,12 @@ export function ThreadMessages({
|
|||||||
const { activityMode } = useLocalPreferences();
|
const { activityMode } = useLocalPreferences();
|
||||||
const messageListRef = useRef<HTMLDivElement>(null);
|
const messageListRef = useRef<HTMLDivElement>(null);
|
||||||
const mobileActions = useMediaQuery("(max-width: 767px)");
|
const mobileActions = useMediaQuery("(max-width: 767px)");
|
||||||
const units = useMemo(
|
const rawUnits = useMemo(() => buildDisplayUnits(messages), [messages]);
|
||||||
() => buildDisplayUnits(messages),
|
const units = useMemo(() => rawUnits.map((unit) => unit.type === "activity"
|
||||||
[messages],
|
? { ...unit, messages: unit.messages.flatMap((message) => {
|
||||||
);
|
const visible = withoutSubagentCreateActivity(message);
|
||||||
|
return visible ? [visible] : [];
|
||||||
|
}) } : unit), [rawUnits]);
|
||||||
const forkBoundaryAfterUnitIndex = useMemo(
|
const forkBoundaryAfterUnitIndex = useMemo(
|
||||||
() => unitIndexAfterMessageCount(units, forkBoundaryMessageCount),
|
() => unitIndexAfterMessageCount(units, forkBoundaryMessageCount),
|
||||||
[forkBoundaryMessageCount, units],
|
[forkBoundaryMessageCount, units],
|
||||||
@@ -135,8 +138,8 @@ export function ThreadMessages({
|
|||||||
const currentTurnStartIndex = isStreaming
|
const currentTurnStartIndex = isStreaming
|
||||||
? activeTurnStartIndex(units, activeTurnId)
|
? activeTurnStartIndex(units, activeTurnId)
|
||||||
: units.length;
|
: units.length;
|
||||||
const unitKeys = useMemo(() => unitKeysForDisplay(units), [units]);
|
const unitKeys = useMemo(() => unitKeysForDisplay(rawUnits), [rawUnits]);
|
||||||
const scrollAnchors = useMemo(() => scrollAnchorsForUnits(units), [units]);
|
const scrollAnchors = useMemo(() => scrollAnchorsForUnits(rawUnits), [rawUnits]);
|
||||||
const messageBlocks = useMemo(
|
const messageBlocks = useMemo(
|
||||||
() => completedMessageBlocks(
|
() => completedMessageBlocks(
|
||||||
units,
|
units,
|
||||||
@@ -920,6 +923,7 @@ function currentActivityClusterIndices(
|
|||||||
for (let i = units.length - 1; i >= 0; i -= 1) {
|
for (let i = units.length - 1; i >= 0; i -= 1) {
|
||||||
const unit = units[i];
|
const unit = units[i];
|
||||||
if (unit.type === "activity") {
|
if (unit.type === "activity") {
|
||||||
|
if (!unit.messages.length) continue;
|
||||||
if (!markedCurrentActivity) {
|
if (!markedCurrentActivity) {
|
||||||
indices.add(i);
|
indices.add(i);
|
||||||
markedCurrentActivity = true;
|
markedCurrentActivity = true;
|
||||||
@@ -1046,7 +1050,8 @@ function completedMessageBlocks(
|
|||||||
const result: CompletedMessageBlocks = {
|
const result: CompletedMessageBlocks = {
|
||||||
blockKeys: new Array<string | undefined>(units.length),
|
blockKeys: new Array<string | undefined>(units.length),
|
||||||
blockIndices: new Set<number>(),
|
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(),
|
activityByBlock: new Map(),
|
||||||
};
|
};
|
||||||
let groupStart = 0;
|
let groupStart = 0;
|
||||||
@@ -1077,7 +1082,7 @@ function completedMessageBlocks(
|
|||||||
const activityByBlock = new Map<number, Array<Extract<DisplayUnit, { type: "activity" }>>>();
|
const activityByBlock = new Map<number, Array<Extract<DisplayUnit, { type: "activity" }>>>();
|
||||||
for (const index of indices) {
|
for (const index of indices) {
|
||||||
const unit = units[index];
|
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);
|
const blockIndex = blockIndices.find((candidate) => candidate > index) ?? blockIndices.at(-1);
|
||||||
if (blockIndex === undefined) continue;
|
if (blockIndex === undefined) continue;
|
||||||
result.suppressedActivityIndices.add(index);
|
result.suppressedActivityIndices.add(index);
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import { ArrowDown } from "lucide-react";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import { PromptRail } from "@/components/thread/PromptRail";
|
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 { DiagramScope } from "@/components/markdown-diagrams/context";
|
||||||
import { DiffViewportContext } from "./activity/DiffViewportContext";
|
import { DiffViewportContext } from "./activity/DiffViewportContext";
|
||||||
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
|
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
|
||||||
@@ -460,8 +460,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const hasTaskResults = useHasSubagentResults();
|
const hasMessages = messages.length > 0;
|
||||||
const hasMessages = messages.length > 0 || (hasTaskResults && conversationReady);
|
|
||||||
const hasThreadLayout = hasMessages || initialLoading;
|
const hasThreadLayout = hasMessages || initialLoading;
|
||||||
useLayoutEffect(() => {
|
useLayoutEffect(() => {
|
||||||
scrollRef.current = hasMessages
|
scrollRef.current = hasMessages
|
||||||
|
|||||||
@@ -1979,8 +1979,6 @@
|
|||||||
},
|
},
|
||||||
"interruptedHelp": "The host restarted before this task finished. It has not been restarted automatically.",
|
"interruptedHelp": "The host restarted before this task finished. It has not been restarted automatically.",
|
||||||
"workTitle": "Subtasks",
|
"workTitle": "Subtasks",
|
||||||
"otherWorkTitle": "Other tasks",
|
|
||||||
"unlinkedHelp": "These tasks have no matching request in the displayed messages.",
|
|
||||||
"progress": "{{completed}} of {{total}} completed",
|
"progress": "{{completed}} of {{total}} completed",
|
||||||
"running": "Running: {{count}}",
|
"running": "Running: {{count}}",
|
||||||
"finished": "Finished: {{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.",
|
"interruptedHelp": "El servidor se reinició antes de terminar esta tarea. No se ha vuelto a ejecutar automáticamente.",
|
||||||
"workTitle": "Subtareas",
|
"workTitle": "Subtareas",
|
||||||
"otherWorkTitle": "Otras tareas",
|
|
||||||
"unlinkedHelp": "No se encontró la solicitud correspondiente a estas tareas en los mensajes mostrados.",
|
|
||||||
"progress": "{{completed}} de {{total}} completadas",
|
"progress": "{{completed}} de {{total}} completadas",
|
||||||
"running": "En curso: {{count}}",
|
"running": "En curso: {{count}}",
|
||||||
"finished": "Finalizadas: {{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.",
|
"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",
|
"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",
|
"progress": "{{completed}} sur {{total}} terminées",
|
||||||
"running": "En cours : {{count}}",
|
"running": "En cours : {{count}}",
|
||||||
"finished": "Terminées : {{count}}",
|
"finished": "Terminées : {{count}}",
|
||||||
|
|||||||
@@ -1797,8 +1797,6 @@
|
|||||||
},
|
},
|
||||||
"interruptedHelp": "Server dimulai ulang sebelum tugas ini selesai. Tugas tidak dijalankan ulang secara otomatis.",
|
"interruptedHelp": "Server dimulai ulang sebelum tugas ini selesai. Tugas tidak dijalankan ulang secara otomatis.",
|
||||||
"workTitle": "Subtugas",
|
"workTitle": "Subtugas",
|
||||||
"otherWorkTitle": "Tugas lain",
|
|
||||||
"unlinkedHelp": "Permintaan yang sesuai dengan tugas ini tidak ditemukan dalam pesan yang ditampilkan.",
|
|
||||||
"progress": "{{completed}} dari {{total}} selesai",
|
"progress": "{{completed}} dari {{total}} selesai",
|
||||||
"running": "Berjalan: {{count}}",
|
"running": "Berjalan: {{count}}",
|
||||||
"finished": "Berakhir: {{count}}",
|
"finished": "Berakhir: {{count}}",
|
||||||
|
|||||||
@@ -1797,8 +1797,6 @@
|
|||||||
},
|
},
|
||||||
"interruptedHelp": "タスクの完了前にサーバーが再起動しました。タスクは自動的に再実行されていません。",
|
"interruptedHelp": "タスクの完了前にサーバーが再起動しました。タスクは自動的に再実行されていません。",
|
||||||
"workTitle": "サブタスク",
|
"workTitle": "サブタスク",
|
||||||
"otherWorkTitle": "ほかのタスク",
|
|
||||||
"unlinkedHelp": "表示中のメッセージには、これらのタスクに対応する依頼がありません。",
|
|
||||||
"progress": "{{total}} 件中 {{completed}} 件完了",
|
"progress": "{{total}} 件中 {{completed}} 件完了",
|
||||||
"running": "実行中: {{count}}",
|
"running": "実行中: {{count}}",
|
||||||
"finished": "終了: {{count}}",
|
"finished": "終了: {{count}}",
|
||||||
|
|||||||
@@ -1797,8 +1797,6 @@
|
|||||||
},
|
},
|
||||||
"interruptedHelp": "작업이 완료되기 전에 서버가 다시 시작되었습니다. 작업은 자동으로 다시 실행되지 않았습니다.",
|
"interruptedHelp": "작업이 완료되기 전에 서버가 다시 시작되었습니다. 작업은 자동으로 다시 실행되지 않았습니다.",
|
||||||
"workTitle": "하위 작업",
|
"workTitle": "하위 작업",
|
||||||
"otherWorkTitle": "다른 작업",
|
|
||||||
"unlinkedHelp": "표시된 메시지에서 이 작업에 해당하는 요청을 찾을 수 없습니다.",
|
|
||||||
"progress": "{{total}}개 중 {{completed}}개 완료",
|
"progress": "{{total}}개 중 {{completed}}개 완료",
|
||||||
"running": "진행 중: {{count}}",
|
"running": "진행 중: {{count}}",
|
||||||
"finished": "종료: {{count}}",
|
"finished": "종료: {{count}}",
|
||||||
|
|||||||
@@ -1799,8 +1799,6 @@
|
|||||||
},
|
},
|
||||||
"interruptedHelp": "O servidor reiniciou antes de concluir esta tarefa. Ela não foi executada novamente automaticamente.",
|
"interruptedHelp": "O servidor reiniciou antes de concluir esta tarefa. Ela não foi executada novamente automaticamente.",
|
||||||
"workTitle": "Subtarefas",
|
"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",
|
"progress": "{{completed}} de {{total}} concluídas",
|
||||||
"running": "Em andamento: {{count}}",
|
"running": "Em andamento: {{count}}",
|
||||||
"finished": "Encerradas: {{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.",
|
"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",
|
"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}}",
|
"progress": "Hoàn thành {{completed}} / {{total}}",
|
||||||
"running": "Đang chạy: {{count}}",
|
"running": "Đang chạy: {{count}}",
|
||||||
"finished": "Đã kết thúc: {{count}}",
|
"finished": "Đã kết thúc: {{count}}",
|
||||||
|
|||||||
@@ -1979,8 +1979,6 @@
|
|||||||
},
|
},
|
||||||
"interruptedHelp": "后端重启时此任务尚未结束,任务没有自动恢复或重新执行。",
|
"interruptedHelp": "后端重启时此任务尚未结束,任务没有自动恢复或重新执行。",
|
||||||
"workTitle": "子任务",
|
"workTitle": "子任务",
|
||||||
"otherWorkTitle": "其他任务",
|
|
||||||
"unlinkedHelp": "未找到这些任务在当前显示消息中的原始请求。",
|
|
||||||
"progress": "已完成 {{completed}} / {{total}} 项",
|
"progress": "已完成 {{completed}} / {{total}} 项",
|
||||||
"running": "{{count}} 项进行中",
|
"running": "{{count}} 项进行中",
|
||||||
"finished": "{{count}} 项已结束",
|
"finished": "{{count}} 项已结束",
|
||||||
|
|||||||
@@ -1797,8 +1797,6 @@
|
|||||||
},
|
},
|
||||||
"interruptedHelp": "後端重新啟動時此任務尚未結束,任務沒有自動恢復或重新執行。",
|
"interruptedHelp": "後端重新啟動時此任務尚未結束,任務沒有自動恢復或重新執行。",
|
||||||
"workTitle": "子任務",
|
"workTitle": "子任務",
|
||||||
"otherWorkTitle": "其他任務",
|
|
||||||
"unlinkedHelp": "未找到這些任務在目前顯示訊息中的原始請求。",
|
|
||||||
"progress": "已完成 {{completed}} / {{total}} 項",
|
"progress": "已完成 {{completed}} / {{total}} 項",
|
||||||
"running": "{{count}} 項進行中",
|
"running": "{{count}} 項進行中",
|
||||||
"finished": "{{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 { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
import { SubagentTaskDock } from "@/components/thread/SubagentTaskDock";
|
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 { SubagentTasksProvider } from "@/components/thread/SubagentTasks";
|
||||||
import { setAppLanguage } from "@/i18n";
|
import { setAppLanguage } from "@/i18n";
|
||||||
import { DEFAULT_LOCAL_PREFS, LOCAL_PREFS_STORAGE_KEY, writeLocalPreferences } from "@/lib/local-preferences";
|
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 }));
|
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 }: {
|
function layout({ threadMessages = messages, sessionKey = "websocket:a", liveEvents = true, historyEnabled = false, onActivityToggle }: {
|
||||||
threadMessages?: UIMessage[];
|
threadMessages?: UIMessage[];
|
||||||
sessionKey?: string;
|
sessionKey?: string;
|
||||||
@@ -58,13 +55,12 @@ function layout({ threadMessages = messages, sessionKey = "websocket:a", liveEve
|
|||||||
onActivityToggle?: () => void;
|
onActivityToggle?: () => void;
|
||||||
} = {}) {
|
} = {}) {
|
||||||
return <SubagentTasksProvider client={client} sessionKey={sessionKey} token="tok" enabled liveEvents={liveEvents} historyEnabled={historyEnabled}>
|
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="messages"><SubagentThreadMessages messages={threadMessages} onActivityToggle={onActivityToggle} /></div>
|
||||||
<div data-testid="composer" className="thread-composer-stack"><SubagentTaskDock /><textarea aria-label="Message" /></div>
|
<div data-testid="composer" className="thread-composer-stack"><SubagentTaskDock /><textarea aria-label="Message" /></div>
|
||||||
</SubagentTasksProvider>;
|
</SubagentTasksProvider>;
|
||||||
}
|
}
|
||||||
function summary(region: HTMLElement) {
|
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) {
|
function expectBefore(first: Node, second: Node) {
|
||||||
expect(first.compareDocumentPosition(second) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
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");
|
expect(await screen.findByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 3");
|
||||||
const transcript = screen.getByTestId("messages");
|
const transcript = screen.getByTestId("messages");
|
||||||
expect(transcript.querySelector("[data-subagent-results]")).toBeNull();
|
expect(transcript.querySelector("[data-subagent-results]")).toBeNull();
|
||||||
expect(screen.getByTestId("has-results")).toHaveTextContent("no");
|
|
||||||
expect(transcript).not.toHaveTextContent("Config check");
|
expect(transcript).not.toHaveTextContent("Config check");
|
||||||
expect(transcript).not.toHaveTextContent("Waiting check");
|
expect(transcript).not.toHaveTextContent("Waiting check");
|
||||||
expect(transcript).not.toHaveTextContent("Stopping check");
|
expect(transcript).not.toHaveTextContent("Stopping check");
|
||||||
|
|
||||||
emitTask(task({ revision: 2, result: "Full findings stay in details" }));
|
emitTask(task({ revision: 2, result: "Full findings stay in details" }));
|
||||||
const archive = screen.getByRole("region", { name: "Subtasks" });
|
const archive = screen.getByRole("region", { name: "Subtasks" });
|
||||||
expect(screen.getByTestId("has-results")).toHaveTextContent("yes");
|
|
||||||
expect(summary(archive)).toHaveTextContent("Completed: 1");
|
expect(summary(archive)).toHaveTextContent("Completed: 1");
|
||||||
expect(summary(archive).querySelector("img")).toHaveAttribute("src", "/brand/nanobot_mark.svg");
|
expect(summary(archive).querySelector("img")).toHaveAttribute("src", "/brand/nanobot_mark.svg");
|
||||||
expect(summary(archive).querySelector("img")).toHaveAttribute("alt", "");
|
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);
|
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([
|
vi.mocked(fetch).mockImplementation(async () => response([
|
||||||
task({ task_id: "older", label: "Earlier check", origin_turn_id: "older-turn", origin_message_id: "older-prompt",
|
task({ task_id: "older", label: "Earlier check", origin_turn_id: "older-turn", origin_message_id: "older-prompt",
|
||||||
result: "## Earlier findings\n\nThe saved result remains available" }),
|
result: "## Earlier findings\n\nThe saved result remains available" }),
|
||||||
@@ -246,27 +240,26 @@ describe("subagent result archives", () => {
|
|||||||
]));
|
]));
|
||||||
const user = userEvent.setup();
|
const user = userEvent.setup();
|
||||||
const view = render(layout());
|
const view = render(layout());
|
||||||
const unlinked = await screen.findByRole("region", { name: "Other tasks" });
|
expect(await screen.findByTestId("subagent-task-dock-trigger")).toHaveTextContent("Running: 1");
|
||||||
expectBefore(unlinked, screen.getByText("Inspect config"));
|
expect(screen.getByTestId("messages").querySelector("[data-subagent-results]")).toBeNull();
|
||||||
expect(summary(unlinked)).toHaveAttribute("aria-expanded", "false");
|
const olderMessages: UIMessage[] = [
|
||||||
await user.click(summary(unlinked));
|
|
||||||
expect(within(unlinked).getByText("These tasks have no matching request in the displayed messages.")).toBeVisible();
|
|
||||||
expect(unlinked).not.toHaveTextContent("Unlinked live check");
|
|
||||||
await user.click(within(unlinked).getByRole("button", { name: "Earlier check Completed 4s" }));
|
|
||||||
const detail = screen.getByRole("dialog", { name: "Earlier check" });
|
|
||||||
expect(await within(detail).findByRole("heading", { name: "Earlier findings" })).toBeVisible();
|
|
||||||
|
|
||||||
view.rerender(layout({ threadMessages: [
|
|
||||||
{ id: "older-prompt", role: "user", content: "Inspect earlier work", turnId: "older-turn", createdAt: 99_000 },
|
{ id: "older-prompt", role: "user", content: "Inspect earlier work", turnId: "older-turn", createdAt: 99_000 },
|
||||||
...messages,
|
...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();
|
expect(within(detail).getByText("The saved result remains available")).toBeVisible();
|
||||||
|
view.rerender(layout({ threadMessages: olderMessages }));
|
||||||
await user.keyboard("{Escape}");
|
await user.keyboard("{Escape}");
|
||||||
expect(screen.queryByRole("region", { name: "Other tasks" })).not.toBeInTheDocument();
|
linked = screen.getByRole("region", { name: "Subtasks" });
|
||||||
const linked = screen.getByRole("region", { name: "Subtasks" });
|
expect(summary(linked)).toHaveAttribute("aria-expanded", "true");
|
||||||
const header = summary(linked);
|
|
||||||
expect(header).toHaveAttribute("aria-expanded", "true");
|
|
||||||
await waitFor(() => expect(within(linked).getByRole("button", { name: "Earlier check Completed 4s" })).toHaveFocus());
|
await waitFor(() => expect(within(linked).getByRole("button", { name: "Earlier check Completed 4s" })).toHaveFocus());
|
||||||
expect(screen.getByTestId("messages").querySelectorAll('[data-subagent-id="older"]')).toHaveLength(1);
|
expect(screen.getByTestId("messages").querySelectorAll('[data-subagent-id="older"]')).toHaveLength(1);
|
||||||
expectBefore(screen.getByText("Inspect earlier work"), linked);
|
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();
|
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" }); });
|
act(() => { writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, activityMode: "expanded" }); });
|
||||||
vi.mocked(fetch).mockImplementation(async () => response([
|
vi.mocked(fetch).mockImplementation(async () => response([
|
||||||
task(),
|
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",
|
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 }));
|
origin_message_id: null, origin_turn_id: null, created_at: 102 }));
|
||||||
expect(summary(archive)).toHaveAttribute("aria-expanded", "true");
|
expect(summary(archive)).toHaveAttribute("aria-expanded", "true");
|
||||||
const unlinked = screen.getByRole("region", { name: "Other tasks" });
|
expect(screen.getByTestId("messages").querySelector('[data-subagent-id="other"]')).toBeNull();
|
||||||
expect(summary(unlinked)).toHaveAttribute("aria-expanded", "false");
|
|
||||||
await user.click(summary(unlinked));
|
|
||||||
view.rerender(layout({ threadMessages: [
|
view.rerender(layout({ threadMessages: [
|
||||||
{ id: "prepended", role: "user", content: "Earlier request from this turn", turnId: "turn-a", createdAt: 99_000 },
|
{ id: "prepended", role: "user", content: "Earlier request from this turn", turnId: "turn-a", createdAt: 99_000 },
|
||||||
...messages,
|
...messages,
|
||||||
@@ -321,7 +312,6 @@ describe("subagent result archives", () => {
|
|||||||
expect(within(retained).getByRole("button", { name: "Config check Completed 4s" })).toBeVisible();
|
expect(within(retained).getByRole("button", { name: "Config check Completed 4s" })).toBeVisible();
|
||||||
expect([...retained.querySelectorAll("[data-subagent-id]")].map((row) => row.getAttribute("data-subagent-id")))
|
expect([...retained.querySelectorAll("[data-subagent-id]")].map((row) => row.getAttribute("data-subagent-id")))
|
||||||
.toEqual(["task-1", "second"]);
|
.toEqual(["task-1", "second"]);
|
||||||
expect(summary(screen.getByRole("region", { name: "Other tasks" }))).toHaveAttribute("aria-expanded", "true");
|
|
||||||
await user.click(summary(retained));
|
await user.click(summary(retained));
|
||||||
act(() => { writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, activityMode: "expanded" }); });
|
act(() => { writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, activityMode: "expanded" }); });
|
||||||
expect(summary(retained)).toHaveAttribute("aria-expanded", "false");
|
expect(summary(retained)).toHaveAttribute("aria-expanded", "false");
|
||||||
|
|||||||
@@ -138,9 +138,7 @@ describe("session-owned task UI", () => {
|
|||||||
const archive = await openArchive(user);
|
const archive = await openArchive(user);
|
||||||
expect(taskIds(archive)).toEqual(older.map(saved => saved.task_id));
|
expect(taskIds(archive)).toEqual(older.map(saved => saved.task_id));
|
||||||
expect(within(archive).queryByRole("button", { name: /Config check Running/ })).not.toBeInTheDocument();
|
expect(within(archive).queryByRole("button", { name: /Config check Running/ })).not.toBeInTheDocument();
|
||||||
const other = await openArchive(user, "Other tasks");
|
expect(taskIds(screen.getByTestId("messages"))).toEqual(older.map(saved => saved.task_id));
|
||||||
await user.click(within(other).getByRole("button", { name: /Earlier check Completed/ }));
|
|
||||||
expect(within(screen.getByRole("dialog", { name: "Earlier check" })).getByText("Saved result")).toBeVisible();
|
|
||||||
expect(requestMutation).not.toHaveBeenCalled();
|
expect(requestMutation).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -901,7 +899,7 @@ describe("session-owned task UI", () => {
|
|||||||
expect(screen.queryByTestId("subagent-task-dock")).not.toBeInTheDocument();
|
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([
|
vi.mocked(fetch).mockImplementation(async () => response([
|
||||||
task({ task_id: "legacy", revision: 0, label: "Nanjing weather", state: "done", completed_at: 102,
|
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**" }),
|
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 user = userEvent.setup();
|
||||||
const view = render(layout());
|
const view = render(layout());
|
||||||
await screen.findByTestId("subagent-task-dock-trigger");
|
await screen.findByTestId("subagent-task-dock-trigger");
|
||||||
const otherWork = screen.getByRole("region", { name: "Other tasks" });
|
expect(taskIds(await openTaskList(user))).toEqual(["task-1"]);
|
||||||
const header = within(otherWork).getByRole("button", { name: /Other tasks/ });
|
expect(taskIds(screen.getByTestId("messages"))).toEqual([]);
|
||||||
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}");
|
|
||||||
view.rerender(layout({ threadMessages: [
|
view.rerender(layout({ threadMessages: [
|
||||||
{ id: "cached-prompt", role: "user", content: "Earlier cached prompt", createdAt: 99_000 },
|
{ id: "cached-prompt", role: "user", content: "Earlier cached prompt", createdAt: 99_000 },
|
||||||
...messages,
|
...messages,
|
||||||
] }));
|
] }));
|
||||||
const expanded = screen.getByRole("region", { name: "Other tasks" });
|
expect(taskIds(screen.getByTestId("messages"))).toEqual([]);
|
||||||
expect(within(expanded).getByRole("button", { name: /Other tasks/ })).toHaveAttribute("aria-expanded", "true");
|
|
||||||
expect(within(expanded).getByRole("button", { name: /Nanjing weather Completed/ })).toBeVisible();
|
|
||||||
view.unmount();
|
view.unmount();
|
||||||
render(layout());
|
render(layout());
|
||||||
const restored = await screen.findByRole("region", { name: "Other tasks" });
|
expect(taskIds(await openTaskList(user))).toEqual(["task-1"]);
|
||||||
expect(within(restored).getByRole("button", { name: /Other tasks/ })).toHaveAttribute("aria-expanded", "false");
|
expect(taskIds(screen.getByTestId("messages"))).toEqual([]);
|
||||||
expect(restored.compareDocumentPosition(screen.getByText("Inspect config")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
|
||||||
expect(requestMutation).not.toHaveBeenCalled();
|
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 () => {
|
it("merges live work before the initial read without polling or rolling back completed work", async () => {
|
||||||
let resolveRead!: (value: Response) => void;
|
let resolveRead!: (value: Response) => void;
|
||||||
vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { resolveRead = resolve; }));
|
vi.mocked(fetch).mockImplementationOnce(() => new Promise((resolve) => { resolveRead = resolve; }));
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
unitKeysForDisplay,
|
unitKeysForDisplay,
|
||||||
} from "@/components/thread/ThreadMessages";
|
} from "@/components/thread/ThreadMessages";
|
||||||
import { preloadMarkdownText } from "@/components/MarkdownText";
|
import { preloadMarkdownText } from "@/components/MarkdownText";
|
||||||
|
import { projectThreadEvents } from "@/lib/thread-event-projection";
|
||||||
import type { UIMessage } from "@/lib/types";
|
import type { UIMessage } from "@/lib/types";
|
||||||
|
|
||||||
// These DOM tests exercise disclosure/source contracts; the real shadow renderer runs in browser tests.
|
// 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);
|
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", () => {
|
it("keeps turn unit keys stable across replayed ids and mutable turn sequence", () => {
|
||||||
const liveUnits = buildDisplayUnits([
|
const liveUnits = buildDisplayUnits([
|
||||||
{ id: "optimistic-user", role: "user", content: "go", turnId: "turn-1", turnPhase: "user", turnSeq: 0, createdAt: 1 },
|
{ id: "optimistic-user", role: "user", content: "go", turnId: "turn-1", turnPhase: "user", turnSeq: 0, createdAt: 1 },
|
||||||
|
|||||||
Reference in new issue
Block a user