Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(frontend/copilot): chain UI polish — card resize, expert skeletons, minimap and artifact tweaks (#14158)

Abhimanyu Yadavdc95d8accc52
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/ArtifactPanel.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/ArtifactPanel.tsx
index ee867553fe..292480febc 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/ArtifactPanel.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/ArtifactPanel.tsx
@@ -1,5 +1,6 @@
"use client";
+import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
import { useEffect, useRef, useState } from "react";
import { Drawer } from "vaul";
import { MIN_ARTIFACT_PANEL_WIDTH, PANEL_RESERVED_WIDTH } from "../../store";
@@ -8,6 +9,10 @@ import { ArtifactContent } from "./components/ArtifactContent";
import { ArtifactPanelHeader } from "./components/ArtifactPanelHeader";
import { useArtifactPanel } from "./useArtifactPanel";
+// Matched to the context panel so the two side rails move as one system.
+const PANEL_EASE: [number, number, number, number] = [0.32, 0.72, 0, 1];
+const PANEL_DURATION = 0.3;
+
interface Props {
mobile?: boolean;
/** The desktop copilot chat renders its own sidebar-right close control;
@@ -33,11 +38,10 @@ export function ArtifactPanel({ mobile, hasExternalClose }: Props) {
setArtifactPanelWidth,
} = useArtifactPanel();
- // Hold the last live artifact so the mobile drawer can keep rendering its
- // contents while vaul plays the slide-out animation — by then
- // `activeArtifact` is already null, and unmounting the whole drawer would
- // snap it shut without animating. Desktop returns null immediately (no exit
- // animation expected there).
+ // Hold the last live artifact so both the mobile drawer and the desktop
+ // panel can keep rendering its contents while the close animation plays —
+ // by then `activeArtifact` is already null, and unmounting outright would
+ // snap the panel shut without animating.
const lastShownRef = useRef<{
artifact: NonNullable<typeof activeArtifact>;
classification: NonNullable<typeof classification>;
@@ -53,6 +57,8 @@ export function ArtifactPanel({ mobile, hasExternalClose }: Props) {
// width is left untouched and applies again once the viewport grows.
const panelRef = useRef<HTMLDivElement>(null);
const [availableWidth, setAvailableWidth] = useState<number | null>(null);
+ const [isResizing, setIsResizing] = useState(false);
+ const shouldReduceMotion = useReducedMotion();
const showDesktopPanel = !mobile && !!activeArtifact && !!classification;
useEffect(() => {
if (!showDesktopPanel || typeof ResizeObserver === "undefined") return;
@@ -128,7 +134,9 @@ export function ArtifactPanel({ mobile, hasExternalClose }: Props) {
);
}
- if (!activeArtifact || !classification) return null;
+ // Keep painting the outgoing artifact through the close tween — by then
+ // `activeArtifact` is already null, same reason the mobile drawer holds it.
+ const shown = lastShownRef.current;
// jsdom reports offsetWidth 0 — treat non-positive readings as "unknown"
// and fall back to the stored width.
@@ -137,40 +145,66 @@ export function ArtifactPanel({ mobile, hasExternalClose }: Props) {
? artifactPanelWidth
: Math.min(artifactPanelWidth, availableWidth);
+ // Width is the animated property because the panel pushes the chat column
+ // rather than overlaying it. Dragging the handle bypasses the tween — a
+ // queued 300ms tween per pointer move would trail the cursor.
+ const transition =
+ shouldReduceMotion || isResizing
+ ? { duration: 0 }
+ : { duration: PANEL_DURATION, ease: PANEL_EASE };
+
return (
- <div
- ref={panelRef}
- data-artifact-panel
- style={{ width: renderedWidth, userSelect: "text" }}
- className="relative flex h-full shrink-0 flex-col border-l border-l-[#80808017] bg-sidebar"
- >
- <PanelResizeHandle
- panelSelector="[data-artifact-panel]"
- onWidthChange={setArtifactPanelWidth}
- minWidth={MIN_ARTIFACT_PANEL_WIDTH}
- />
- <div className="flex min-h-0 w-full flex-1 flex-col overflow-hidden">
- <ArtifactPanelHeader
- artifact={activeArtifact}
- classification={classification}
- hasExternalClose={hasExternalClose}
- canGoBack={history.length > 0}
- isSourceView={isSourceView}
- hasSourceToggle={classification.hasSourceToggle}
- canCopy={canCopy}
- onBack={goBackArtifact}
- onClose={clearArtifactPreview}
- onCopy={handleCopy}
- onDownload={handleDownload}
- onOpenFiles={showFilesTab}
- onSourceToggle={setIsSourceView}
- />
- <ArtifactContent
- artifact={activeArtifact}
- isSourceView={isSourceView}
- classification={classification}
- />
- </div>
- </div>
+ <AnimatePresence initial={false}>
+ {showDesktopPanel && shown && (
+ <motion.div
+ ref={panelRef}
+ data-artifact-panel
+ initial={{ width: 0, opacity: 0 }}
+ animate={{ width: renderedWidth, opacity: 1 }}
+ exit={{ width: 0, opacity: 0 }}
+ transition={transition}
+ style={{ userSelect: "text" }}
+ className="relative h-full shrink-0 border-l border-l-[#80808017] bg-sidebar"
+ >
+ {/* Sibling of the clip, not a child of it: the handle straddles the
+ border, so clipping it here would halve the drag target. */}
+ <PanelResizeHandle
+ panelSelector="[data-artifact-panel]"
+ onWidthChange={setArtifactPanelWidth}
+ onResizingChange={setIsResizing}
+ minWidth={MIN_ARTIFACT_PANEL_WIDTH}
+ />
+ <div className="h-full overflow-hidden">
+ {/* Fixed inner width so the header and content keep their final
+ layout while the shell widens — nothing reflows mid-tween. */}
+ <div
+ style={{ width: renderedWidth }}
+ className="flex h-full min-h-0 flex-col overflow-hidden"
+ >
+ <ArtifactPanelHeader
+ artifact={shown.artifact}
+ classification={shown.classification}
+ hasExternalClose={hasExternalClose}
+ canGoBack={history.length > 0}
+ isSourceView={isSourceView}
+ hasSourceToggle={shown.classification.hasSourceToggle}
+ canCopy={canCopy}
+ onBack={goBackArtifact}
+ onClose={clearArtifactPreview}
+ onCopy={handleCopy}
+ onDownload={handleDownload}
+ onOpenFiles={showFilesTab}
+ onSourceToggle={setIsSourceView}
+ />
+ <ArtifactContent
+ artifact={shown.artifact}
+ isSourceView={isSourceView}
+ classification={shown.classification}
+ />
+ </div>
+ </div>
+ </motion.div>
+ )}
+ </AnimatePresence>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/__tests__/ArtifactPanel.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/__tests__/ArtifactPanel.test.tsx
index d4ab80d999..2e57331d1d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/__tests__/ArtifactPanel.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactPanel/__tests__/ArtifactPanel.test.tsx
@@ -1,4 +1,10 @@
-import { act, cleanup, render, screen } from "@/tests/integrations/test-utils";
+import {
+ act,
+ cleanup,
+ render,
+ screen,
+ waitFor,
+} from "@/tests/integrations/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ArtifactRef } from "../../../store";
import {
@@ -42,6 +48,12 @@ function getPanel(): HTMLElement {
return panel;
}
+/** The panel tweens its width open, so the inline style passes through
+ * intermediate values before settling on the clamped result. */
+async function expectPanelWidth(px: number) {
+ await waitFor(() => expect(getPanel().style.width).toBe(`${px}px`));
+}
+
describe("ArtifactPanel (desktop) width clamping", () => {
let offsetWidthSpy: ReturnType<typeof vi.spyOn>;
@@ -91,7 +103,7 @@ describe("ArtifactPanel (desktop) width clamping", () => {
render(<ArtifactPanel />);
expect(await screen.findByText("notes.txt")).toBeDefined();
- expect(getPanel().style.width).toBe(`${1000 - PANEL_RESERVED_WIDTH}px`);
+ await expectPanelWidth(1000 - PANEL_RESERVED_WIDTH);
});
it("keeps the stored width when the row leaves enough space", async () => {
@@ -102,7 +114,7 @@ describe("ArtifactPanel (desktop) width clamping", () => {
render(<ArtifactPanel />);
expect(await screen.findByText("notes.txt")).toBeDefined();
- expect(getPanel().style.width).toBe(`${DEFAULT_ARTIFACT_PANEL_WIDTH}px`);
+ await expectPanelWidth(DEFAULT_ARTIFACT_PANEL_WIDTH);
});
it("re-clamps when the row is resized", async () => {
@@ -112,12 +124,12 @@ describe("ArtifactPanel (desktop) width clamping", () => {
render(<ArtifactPanel />);
expect(await screen.findByText("notes.txt")).toBeDefined();
- expect(getPanel().style.width).toBe(`${DEFAULT_ARTIFACT_PANEL_WIDTH}px`);
+ await expectPanelWidth(DEFAULT_ARTIFACT_PANEL_WIDTH);
offsetWidthSpy.mockReturnValue(900);
act(() => ResizeObserverMock.instances[0].trigger());
- expect(getPanel().style.width).toBe(`${900 - PANEL_RESERVED_WIDTH}px`);
+ await expectPanelWidth(900 - PANEL_RESERVED_WIDTH);
});
it("keeps the header Close button for standalone hosts", async () => {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx
index 1d7b2df3b1..bd33d0e31a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx
@@ -41,6 +41,7 @@ import { getWorkRunMetadata, toPreview } from "../WorkCard/helpers";
import { AssistantMessageActions } from "./components/AssistantMessageActions";
import { ChainMessageParts } from "./components/ChainMessageParts";
import { CopyButton } from "./components/CopyButton";
+import { TailSpacer } from "./components/TailSpacer";
import { MessageAttachments } from "./components/MessageAttachments";
import { MessagePartRenderer } from "./components/MessagePartRenderer";
import { QueueBadge } from "./components/QueueBadge";
@@ -328,6 +329,8 @@ export function ChatMessagesContainer({
const hideForScroll = messagesReady && !settled;
const lastMessage = messages[messages.length - 1];
+ const lastUserMessageID =
+ messages.findLast((message) => message.role === "user")?.id ?? null;
const graphExecId = useMemo(() => extractGraphExecId(messages), [messages]);
// The backend appends a persisted error marker to ``session.messages`` AND
@@ -784,6 +787,10 @@ export function ChatMessagesContainer({
</pre>
</details>
)}
+ <TailSpacer
+ messageID={lastUserMessageID}
+ bottomInset={bottomContentPadding ?? 0}
+ />
</ConversationContent>
<ConversationScrollButton />
</Conversation>
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChainMessageParts.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChainMessageParts.tsx
index 23582997de..7500d9a665 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChainMessageParts.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChainMessageParts.tsx
@@ -32,11 +32,7 @@ export function ChainMessageParts({
liveCompactionCallId,
liveCompactionStats,
}: Props) {
- const segments = buildChainSegments(
- parts,
- isChainableToolPart,
- isCurrentlyStreaming,
- );
+ const segments = buildChainSegments(parts, isChainableToolPart);
const lastChainSegmentIndex = segments.findLastIndex(
(segment) => segment.kind === "chain",
);
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/TailSpacer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/TailSpacer.tsx
new file mode 100644
index 0000000000..8c996b8167
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/TailSpacer.tsx
@@ -0,0 +1,70 @@
+"use client";
+
+import { useLayoutEffect, useRef, useState } from "react";
+import { useStickToBottomContext } from "use-stick-to-bottom";
+
+interface Props {
+ messageID: string | null;
+ bottomInset: number;
+}
+
+// Breathing room above the composer so the pinned turn does not sit flush
+// against the bottom inset.
+const TAIL_GAP = 24;
+
+// Share of the viewport the newest turn is allowed to occupy. The turn is
+// bottom-aligned, so this is also where the user's message lands: 0.5 parks
+// it mid-screen, 1 would pin it to the very top.
+const TAIL_VIEWPORT_RATIO = 0.5;
+
+/** Reserves room below the newest turn so that sticking to the bottom parks
+ * the user's message around the middle of the viewport, leaving the lower
+ * half of the screen for the reply. Collapses to zero once the reply is tall
+ * enough to fill that space, handing scrolling back to StickToBottom. */
+export function TailSpacer({ messageID, bottomInset }: Props) {
+ const { scrollRef } = useStickToBottomContext();
+ const spacerRef = useRef<HTMLDivElement>(null);
+ const [height, setHeight] = useState(0);
+
+ useLayoutEffect(() => {
+ const scroller = scrollRef.current;
+ const spacer = spacerRef.current;
+ // The spacer is the last child of the scroll content, so its parent is
+ // the element whose growth we care about.
+ const content = spacer?.parentElement;
+ if (!scroller || !content || !spacer || !messageID) {
+ setHeight(0);
+ return;
+ }
+ const message = content.querySelector(
+ `[data-message-id="${CSS.escape(messageID)}"]`,
+ );
+ if (!(message instanceof HTMLElement)) {
+ setHeight(0);
+ return;
+ }
+
+ function measure() {
+ if (!scroller || !spacer || !(message instanceof HTMLElement)) return;
+ // Measured against the spacer's own top, which sits above its height —
+ // reading the content box instead would feed this back into itself.
+ const turnHeight =
+ spacer.getBoundingClientRect().top -
+ message.getBoundingClientRect().top;
+ const viewport = scroller.clientHeight - bottomInset - TAIL_GAP;
+ setHeight(Math.max(0, viewport * TAIL_VIEWPORT_RATIO - turnHeight));
+ }
+
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(content);
+ observer.observe(scroller);
+ return () => observer.disconnect();
+ }, [messageID, bottomInset, scrollRef]);
+
+ // `-mt-6` cancels the parent's `gap-6` so zero height really is zero —
+ // without it every thread keeps an extra gap above the composer.
+ return (
+ <div ref={spacerRef} aria-hidden className="-mt-6" style={{ height }} />
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/ChatMinimap.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/ChatMinimap.tsx
index cb97a750a5..d888764d77 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/ChatMinimap.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/ChatMinimap.tsx
@@ -14,9 +14,9 @@ interface Props {
}
/**
- * A tick rail down the chat's left gutter — one mark per message. Ticks sit
- * shrunk until the cursor comes near, then swell toward it; hovering one
- * reveals that turn's opening line, and clicking scrolls the transcript to
+ * A tick rail down the chat's left gutter — one mark per message you sent.
+ * Ticks sit shrunk until the cursor comes near, then swell toward it; hovering
+ * one reveals that turn's opening line, and clicking scrolls the transcript to
* it, so a long thread stays navigable without dragging the scrollbar.
*/
export function ChatMinimap({ messages }: Props) {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/__tests__/ChatMinimap.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/__tests__/ChatMinimap.test.tsx
index 6f3e5ef7ac..30520c5273 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/__tests__/ChatMinimap.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/__tests__/ChatMinimap.test.tsx
@@ -16,18 +16,22 @@ const MESSAGES = [
textMessage("m1", "user", "Plan my week\nMonday first"),
textMessage("m2", "assistant", "Here is the plan"),
textMessage("m3", "user", "Now the budget"),
+ textMessage("m4", "assistant", "Budget done"),
+ textMessage("m5", "user", "And travel"),
];
describe("ChatMinimap", () => {
- it("renders one tick per message once the thread is long enough", () => {
+ it("renders one tick per user message, skipping assistant turns", () => {
render(<ChatMinimap messages={MESSAGES} />);
expect(screen.getAllByRole("button")).toHaveLength(3);
expect(screen.getByLabelText("Jump to: Plan my week")).toBeDefined();
+ expect(screen.queryByLabelText("Jump to: Here is the plan")).toBeNull();
});
- it("renders nothing for short threads", () => {
+ it("renders nothing until enough of the messages are yours", () => {
+ // Four messages, but only two of them sent by the user.
const { container } = render(
- <ChatMinimap messages={MESSAGES.slice(0, 2)} />,
+ <ChatMinimap messages={MESSAGES.slice(0, 4)} />,
);
expect(container.textContent).toBe("");
});
@@ -63,13 +67,14 @@ describe("ChatMinimap", () => {
});
describe("minimap helpers", () => {
- it("falls back to role labels for text-free turns", () => {
+ it("drops assistant turns and labels text-free user messages", () => {
const entries = toMinimapEntries([
{ id: "t1", role: "assistant", parts: [] } as unknown as UIMessage,
{ id: "t2", role: "user", parts: [] } as unknown as UIMessage,
]);
- expect(entries[0].title).toBe("Autopilot worked on this");
- expect(entries[1].title).toBe("Your message");
+ expect(entries).toHaveLength(1);
+ expect(entries[0].id).toBe("t2");
+ expect(entries[0].title).toBe("Your message");
});
it("truncates long titles with an ellipsis", () => {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/helpers.ts
index ae024d009b..452a151c24 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMinimap/helpers.ts
@@ -9,23 +9,22 @@ export interface MinimapEntry {
const TITLE_CHARS = 60;
const BODY_CHARS = 220;
-/** One tick per message, no exceptions — the rail mirrors the transcript, so
- * a tool-only turn still gets its mark and falls back to a role label. */
+/** One tick per user message. The rail is a way back to what *you* asked —
+ * ticking every assistant turn as well doubled the marks without adding a
+ * distinct destination, since a reply sits directly under its question. */
export function toMinimapEntries(
messages: UIMessage<unknown, UIDataTypes, UITools>[],
): MinimapEntry[] {
- return messages.map((message) => {
- const [title, body] = splitPreview(messageText(message));
- return {
- id: message.id,
- title: title || roleFallback(message.role),
- body,
- };
- });
-}
-
-function roleFallback(role: string): string {
- return role === "user" ? "Your message" : "Autopilot worked on this";
+ return messages
+ .filter((message) => message.role === "user")
+ .map((message) => {
+ const [title, body] = splitPreview(messageText(message));
+ return {
+ id: message.id,
+ title: title || "Your message",
+ body,
+ };
+ });
}
function messageText(
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/PanelResizeHandle.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PanelResizeHandle.tsx
index 7df35f3547..ccae05fce4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/PanelResizeHandle.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/PanelResizeHandle.tsx
@@ -46,6 +46,9 @@ export function PanelResizeHandle({
useEffect(() => {
onResizingChangeRef.current?.(isDragging);
}, [isDragging]);
+ // A panel closed mid-drag unmounts the handle before the pointer comes up —
+ // say the drag ended, or the panel opens at zero duration the next time.
+ useEffect(() => () => onResizingChangeRef.current?.(false), []);
// DOM integration: document-level pointer listeners bound only while
// dragging, torn down on unmount so closing the panel mid-drag is safe.
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/AgentCards.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/AgentCards.tsx
index 2dbd8d0263..04afd18229 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/AgentCards.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/AgentCards.tsx
@@ -171,7 +171,14 @@ export function AgentPreviewCard({ output }: OutputCardProps) {
);
}
-export function SubSessionCard({ output }: OutputCardProps) {
+interface SubSessionCardProps extends OutputCardProps {
+ minimal?: boolean;
+}
+
+export function SubSessionCard({
+ output,
+ minimal = false,
+}: SubSessionCardProps) {
const frozenStatus = str(output, "status");
const response = str(output, "response");
const link = str(output, "sub_autopilot_session_link");
@@ -203,7 +210,7 @@ export function SubSessionCard({ output }: OutputCardProps) {
{status && <StatusPill status={status} />}
{link && <CardLink href={link} label="Open sub-session" />}
</div>
- {response && (
+ {!minimal && response && (
<p className="mt-1.5 line-clamp-2 pl-9 text-xs text-zinc-500">
{response}
</p>
@@ -211,7 +218,7 @@ export function SubSessionCard({ output }: OutputCardProps) {
{/* Keyed to the FROZEN status on purpose: once mounted for a running
output, the live view stays up after completion showing the final
steps + answer (it stops polling on its own). */}
- {subSessionId && (
+ {!minimal && subSessionId && (
<SubSessionLive
subSessionId={subSessionId}
active={["running", "queued"].includes(
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ChainRowView.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ChainRowView.tsx
index 10322aa72e..2e5a0929c8 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ChainRowView.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ChainRowView.tsx
@@ -6,6 +6,7 @@ import { Icon } from "@/components/atoms/Icon/Icon";
import { cn } from "@/lib/utils";
import { useCopilotUIStore } from "../../store";
import { ACCORDION_PANEL, accordionState, PANEL_REVEAL } from "./accordion";
+import { EXPERT_CHANGE_TOOLS } from "./ExpertCards";
import type { ChainRow } from "./helpers";
import { ProviderIcon, RowIcon } from "./RowIcon";
import { useSubSessionEffectiveStatus } from "./SubSessionLive";
@@ -76,6 +77,11 @@ export function ChainRowView({ row, isLast }: Props) {
const isReasoning = row.category === "reasoning";
const artifactPanelOpen = useCopilotUIStore((s) => s.artifactPanel.isOpen);
+ // What the row needs from the user is only known once the output lands, so
+ // a live row mounts closed and flips here — the user can still collapse it.
+ useEffect(() => {
+ if (row.requiresAction) setOpen(true);
+ }, [row.requiresAction]);
// Browser steps carry the page screenshots the artifact panel shows —
// auto-expand them while the panel is open so the steps are visible
// from the start.
@@ -102,20 +108,35 @@ export function ChainRowView({ row, isLast }: Props) {
: null,
isSubTool && typeof output?.status === "string" ? output.status : null,
);
+ // "unknown" means the poll died, not that the teammate finished — the row
+ // only has a running label and a done label, and claiming a result landed
+ // is the worse of the two guesses. It also keeps this row consistent with
+ // the card below it, whose poll caps on its own mount clock.
const stillWorking =
isSubTool &&
row.state === "done" &&
- ["running", "queued"].includes(effectiveStatus?.toLowerCase() ?? "");
+ ["running", "queued", "unknown"].includes(
+ effectiveStatus?.toLowerCase() ?? "",
+ );
const liveReasoning =
isReasoning && row.state === "running" && !!row.reasoningText;
+ // An expert being hired/raised has no output until it lands — the skeleton
+ // card stands in for it, so the row has something to show while running.
+ const pendingExpertChange =
+ !!row.tool &&
+ EXPERT_CHANGE_TOOLS.has(row.tool) &&
+ row.output === undefined &&
+ row.state === "running";
const hasContent = isReasoning
? !!row.reasoningText
: !row.supersededSubSession &&
- ((row.output !== undefined && row.output !== "") || liveSubSession);
- // Action-required cards (credential setup, review, login) must stay on
- // screen until resolved — the row cannot be collapsed.
- const forcedOpen = row.requiresAction === true && hasContent;
- const showContent = liveReasoning || forcedOpen || (open && hasContent);
+ ((row.output !== undefined && row.output !== "") ||
+ liveSubSession ||
+ pendingExpertChange);
+ useEffect(() => {
+ if (pendingExpertChange) setOpen(true);
+ }, [pendingExpertChange]);
+ const showContent = liveReasoning || (open && hasContent);
const rowText = (
<SwapText
text={
@@ -153,7 +174,7 @@ export function ChainRowView({ row, isLast }: Props) {
)}
</div>
<div className={cn("min-w-0 flex-1", isLast ? "pb-0" : "pb-3")}>
- {hasContent && !forcedOpen ? (
+ {hasContent ? (
<button
type="button"
onClick={() => setOpen(!open)}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx
index 74bbc64f3d..75a68a7b71 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx
@@ -1,15 +1,27 @@
"use client";
import {
+ ArrowDown01Icon,
BubbleChatIcon,
CheckmarkCircle02Icon,
PencilIcon,
} from "@hugeicons/core-free-icons";
import Link from "next/link";
+import { useId, useState } from "react";
import { Icon } from "@/components/atoms/Icon/Icon";
+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
import { ExpertAvatar } from "@/components/molecules/ExpertAvatar/ExpertAvatar";
-import { CARD, HALF } from "./ResultCards";
+import { cn } from "@/lib/utils";
+import { CARD } from "./ResultCards";
import { asObject, str } from "./resultHelpers";
+import { useCardResize } from "./useCardResize";
+
+export const EXPERT_CHANGE_TOOLS = new Set([
+ "hire_expert",
+ "raise_expert",
+ "update_expert",
+ "confirm_expert_change",
+]);
interface Props {
output: Record<string, unknown>;
@@ -34,6 +46,9 @@ function failedWorkflows(output: Record<string, unknown>): string[] {
* ``confirm_expert_change`` actually created. Once they exist, the card
* offers the two things the user does next: adjust them or talk to them. */
export function ExpertChangeCard({ output }: Props) {
+ const [expanded, setExpanded] = useState(false);
+ const detailsID = useId();
+ const { contentRef, height } = useCardResize(expanded);
const applied = output.applied === true;
const expert = asObject(output.expert) ?? asObject(output.preview);
if (!expert) return null;
@@ -47,9 +62,11 @@ export function ExpertChangeCard({ output }: Props) {
typeof expert.weekly_budget === "number" ? expert.weekly_budget : null;
const appliedLabel = APPLIED_LABELS[str(output, "kind") ?? ""] ?? "Done";
const failed = applied ? failedWorkflows(output) : [];
+ const clampable = !!about || !!boundaries;
+ const clamp = expanded ? undefined : "line-clamp-2";
return (
- <div className={`${CARD} ${HALF} p-2.5`}>
+ <div className={cn(CARD, "w-full rounded-3xl p-2.5")}>
<div className="flex items-center gap-2.5">
<ExpertAvatar
name={name}
@@ -72,46 +89,88 @@ export function ExpertChangeCard({ output }: Props) {
Needs your OK
</span>
)}
- </div>
- {about && (
- <p className="mt-1.5 line-clamp-2 pl-9 text-xs text-zinc-500">
- {about}
- </p>
- )}
- {boundaries && (
- <p className="mt-1 line-clamp-2 pl-9 text-xs text-zinc-400">
- Stops at: {boundaries}
- </p>
- )}
- {budget !== null && (
- <p className="mt-1 pl-9 text-[11px] text-zinc-400">
- Weekly budget: {budget} credits
- </p>
- )}
- {failed.length > 0 && (
- <p className="mt-1 pl-9 text-[11px] text-amber-700">
- Couldn&apos;t set up: {failed.join(", ")}. Everything else is ready —
- add {failed.length > 1 ? "them" : "it"} from the expert&apos;s page.
- </p>
- )}
- {applied && id && (
- <div className="mt-2.5 flex items-center gap-1.5 pl-9">
- <Link
- href={`/team/${id}`}
- className="inline-flex h-7 items-center gap-1.5 rounded-full border border-zinc-200 px-3 text-xs font-medium text-zinc-600 transition-colors hover:bg-zinc-50 hover:text-zinc-900"
+ {clampable && (
+ <button
+ type="button"
+ onClick={() => setExpanded(!expanded)}
+ aria-expanded={expanded}
+ aria-controls={detailsID}
+ aria-label={expanded ? "Show less" : "Show more"}
+ className="group/expand -mr-0.5 flex size-6 shrink-0 items-center justify-center rounded-full transition-colors hover:bg-zinc-100"
>
- <Icon icon={PencilIcon} size={13} />
- Edit
- </Link>
- <Link
- href={`/copilot?expertId=${id}`}
- className="inline-flex h-7 items-center gap-1.5 rounded-full bg-zinc-900 px-3 text-xs font-medium text-white transition-colors hover:bg-zinc-700"
- >
- <Icon icon={BubbleChatIcon} size={13} />
- Chat
- </Link>
+ <Icon
+ icon={ArrowDown01Icon}
+ size={12}
+ className={cn(
+ "text-zinc-300 transition-transform duration-300 ease-out-quint group-hover/expand:text-zinc-500",
+ expanded && "rotate-180",
+ )}
+ />
+ </button>
+ )}
+ </div>
+ <div
+ id={detailsID}
+ className="overflow-hidden transition-[height] duration-300 ease-out-quint motion-reduce:transition-none"
+ style={{ height }}
+ >
+ <div ref={contentRef} className="flex flex-col gap-1 pt-1.5">
+ {about && (
+ <p className={cn("pl-9 text-sm text-zinc-500", clamp)}>{about}</p>
+ )}
+ {boundaries && (
+ <p className={cn("pl-9 text-sm text-zinc-400", clamp)}>
+ Stops at: {boundaries}
+ </p>
+ )}
+ {budget !== null && (
+ <p className="pl-9 text-sm text-zinc-600">
+ Weekly budget: {budget} credits
+ </p>
+ )}
+ {failed.length > 0 && (
+ <p className="pl-9 text-[11px] text-amber-700">
+ Couldn&apos;t set up: {failed.join(", ")}. Everything else is
+ ready — add {failed.length > 1 ? "them" : "it"} from the
+ expert&apos;s page.
+ </p>
+ )}
+ {applied && id && (
+ <div className="mt-1.5 flex items-center gap-1.5 pl-9">
+ <Link
+ href={`/team/${id}`}
+ className="inline-flex h-7 items-center gap-1.5 rounded-full border border-zinc-200 px-3 text-xs font-medium text-zinc-600 transition-colors hover:bg-zinc-50 hover:text-zinc-900"
+ >
+ <Icon icon={PencilIcon} size={13} />
+ Edit
+ </Link>
+ <Link
+ href={`/copilot?expertId=${id}`}
+ className="inline-flex h-7 items-center gap-1.5 rounded-full bg-zinc-900 px-3 text-xs font-medium text-white transition-colors hover:bg-zinc-700"
+ >
+ <Icon icon={BubbleChatIcon} size={13} />
+ Chat
+ </Link>
+ </div>
+ )}
</div>
- )}
+ </div>
+ </div>
+ );
+}
+
+export function ExpertChangeCardSkeleton() {
+ return (
+ <div className={cn(CARD, "w-full rounded-3xl p-2.5")}>
+ <div className="flex items-center gap-2.5">
+ <Skeleton className="size-7 shrink-0 rounded-full" />
+ <Skeleton className="h-3.5 w-40" />
+ <Skeleton className="ml-auto h-4 w-20 rounded-md" />
+ </div>
+ <div className="flex flex-col gap-1.5 pl-9 pt-2.5">
+ <Skeleton className="h-3 w-full" />
+ <Skeleton className="h-3 w-4/5" />
+ </div>
</div>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/SubSessionLive.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/SubSessionLive.tsx
index f06f2717e8..d4adce5391 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/SubSessionLive.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/SubSessionLive.tsx
@@ -238,7 +238,15 @@ function toMiniRow(step: LiveStep, index: number, running: boolean): ChainRow {
* polling their session list; when only the session is known, the expert
* is read off the polled session itself. Swapped for the full
* SubSessionCard the moment the tool returns. */
-export function SubSessionPendingCard({ input }: { input: unknown }) {
+interface PendingCardProps {
+ input: unknown;
+ minimal?: boolean;
+}
+
+export function SubSessionPendingCard({
+ input,
+ minimal = false,
+}: PendingCardProps) {
const { expertsById } = useExpertMap();
const args = asObject(input) ?? {};
const inputExpertId = str(args, "expert_id");
@@ -248,7 +256,7 @@ export function SubSessionPendingCard({ input }: { input: unknown }) {
inputSessionId ? null : inputExpertId,
);
const liveSessionId = inputSessionId ?? discoveredId;
- // Cache-shared with SubSessionLive's query below — no extra request.
+ // Same query key as the live view below, so a full card polls once.
const {
session: liveSession,
isError,
@@ -289,12 +297,14 @@ export function SubSessionPendingCard({ input }: { input: unknown }) {
</Link>
)}
</div>
- {prompt && (
+ {!minimal && prompt && (
<p className="mt-1.5 line-clamp-2 pl-9 text-sm text-zinc-500">
{prompt}
</p>
)}
- {liveSessionId && <SubSessionLive subSessionId={liveSessionId} active />}
+ {!minimal && liveSessionId && (
+ <SubSessionLive subSessionId={liveSessionId} active />
+ )}
</div>
);
}
@@ -339,24 +349,28 @@ function useDelegatedSessionId(expertId: string | null) {
/** A sub-session tool output freezes the status it had when the tool
* returned — a "running" card would say running forever after the work
* lands. While the frozen status is running/queued, read the truth off the
- * polled session (cache-shared with the live view) and flip to completed
- * once it goes idle. */
+ * polled session and flip to completed once it goes idle.
+ *
+ * Owns the poll through `useLiveSubSession` rather than piggybacking on a
+ * mounted live view: a minimal delegate card renders no live view, so this
+ * is the only thing left that can flip running → completed. On a full card
+ * it is the same query key, so the two share one poll. */
export function useSubSessionEffectiveStatus(
subSessionId: string | null,
status: string | null,
) {
const stale = ["running", "queued"].includes(status?.toLowerCase() ?? "");
- const { data, isError } = useGetV2GetSession(subSessionId ?? "", undefined, {
- query: {
- enabled: stale && !!subSessionId,
- select: (res) => (res.status === 200 ? res.data : null),
- },
- });
+ const { session, isError, isPaused } = useLiveSubSession(
+ subSessionId ?? "",
+ stale && !!subSessionId,
+ );
if (!stale) return status;
- // The frozen status is only trustworthy while the poll can refute it.
- if (isError) return "unknown";
- if (!data) return status;
- return isSessionLive(data) ? status : "completed";
+ // The frozen status is only trustworthy while the poll can refute it. A
+ // minimal card has no "Live updates paused" notice to fall back on, so a
+ // dead poll has to show up in the pill or it reads as fact.
+ if (isError || isPaused) return "unknown";
+ if (!session) return status;
+ return isSessionLive(session) ? status : "completed";
}
function isSessionLive(session: SessionDetailResponse): boolean {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx
index 3344bff218..ed6e620650 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolChain.tsx
@@ -132,10 +132,10 @@ export function ToolChain({ parts, isStreaming, readOnly = false }: Props) {
// screen. A manual toggle overrides either direction and sticks.
const open = manualExpanded ?? isStreaming;
const windowMode = isStreaming && !expanded && !hasRequiredAction;
- // Action-required cards (credential setup etc.) can never leave the
- // screen: collapsing the chain hides the other rows but keeps the
- // action rows visible, and the streaming window is disabled for them.
- const actionOnly = !open && hasRequiredAction;
+ // Action-required cards (credential setup etc.) stay on screen by default:
+ // a chain that has collapsed on its own still shows its action rows. An
+ // explicit collapse from the user closes them like any other row.
+ const actionOnly = !open && hasRequiredAction && manualExpanded !== false;
const panelOpen = open || actionOnly;
// Rows stay mounted while closed so the 0fr collapse can animate — but
// only the streaming window's rows. Mounting the full list the moment the
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResult.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResult.tsx
index 648f0ab27b..af7a1e1eb4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResult.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ToolResult.tsx
@@ -14,7 +14,7 @@ import {
} from "./AgentCards";
import { BlockListCard, BlockOutputCard } from "./BlockCards";
import { ExecutionCard } from "./ExecutionCard";
-import { ExpertChangeCard } from "./ExpertCards";
+import { ExpertChangeCard, ExpertChangeCardSkeleton } from "./ExpertCards";
import { FileDiff } from "./FileDiff";
import { isDiffText } from "./fileDiffHelpers";
import type { ChainRow } from "./helpers";
@@ -255,22 +255,36 @@ function toolCard(row: ChainRow, output: Record<string, unknown> | null) {
case "run_sub_session":
case "get_sub_session_result":
case "delegate_to_expert":
- case "handoff_to_expert":
+ case "handoff_to_expert": {
+ // A teammate's thread is their own workspace: delegated cards stay
+ // minimal (who, status, elapsed, link) — no response preview, no live
+ // step feed. Only the model's own run_sub_session shows its work here,
+ // and it always will: `expert` is written solely by the backend's
+ // apply_delegated_expert, which run_sub_session never calls (its subs
+ // are same-scope by construction, so the identity is None anyway).
+ const delegated =
+ row.tool === "delegate_to_expert" ||
+ row.tool === "handoff_to_expert" ||
+ !!(output && asObject(output.expert));
if (output && str(output, "status"))
- return <SubSessionCard output={output} />;
+ return <SubSessionCard output={output} minimal={delegated} />;
// A blocking delegate has no output while the teammate works — show
// who's on it and what they were asked from the tool input instead.
// Not for result polls: the delegation card above is already showing
// this sub-session live, a second identical card would stack under it.
return row.state === "running" &&
row.tool !== "get_sub_session_result" ? (
- <SubSessionPendingCard input={row.input} />
+ <SubSessionPendingCard input={row.input} minimal={delegated} />
) : null;
+ }
case "hire_expert":
case "raise_expert":
case "update_expert":
case "confirm_expert_change":
- return output ? <ExpertChangeCard output={output} /> : null;
+ if (output) return <ExpertChangeCard output={output} />;
+ // The expert is still being written — hold the card's shape so the
+ // real one swaps in without the row jumping.
+ return row.state === "running" ? <ExpertChangeCardSkeleton /> : null;
case "find_agent":
case "find_library_agent": {
const agents = output && asItems(output.agents);
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ChainRowView.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ChainRowView.test.tsx
index fd69d2ccfd..06e9b54a0e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ChainRowView.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ChainRowView.test.tsx
@@ -1,6 +1,7 @@
import { getGetV2GetSessionMockHandler200 } from "@/app/api/__generated__/endpoints/chat/chat.msw";
import { server } from "@/mocks/mock-server";
import { render, screen } from "@/tests/integrations/test-utils";
+import { http, HttpResponse } from "msw";
import { afterEach, describe, expect, it } from "vitest";
import type { ChainRow } from "../helpers";
import { ChainRowView } from "../ChainRowView";
@@ -45,7 +46,9 @@ describe("ChainRowView - live sub-session rows", () => {
);
expect(await screen.findByText("Sub-AutoPilot")).toBeDefined();
- expect(screen.getByText("Create a chat app")).toBeDefined();
+ // Delegated cards are status-only — the prompt stays in the teammate's
+ // own thread, not in the parent chain.
+ expect(screen.queryByText("Create a chat app")).toBeNull();
});
it("does not auto-open a result-poll row with no output (nothing to show)", () => {
@@ -102,6 +105,36 @@ describe("ChainRowView - live sub-session rows", () => {
).toBeDefined();
});
+ it("does not claim the teammate finished when the poll dies", async () => {
+ server.use(
+ http.get("*/api/chat/sessions/:sessionId", () => {
+ return new HttpResponse(null, { status: 500 });
+ }),
+ );
+
+ render(
+ <ChainRowView
+ row={row({
+ tool: "delegate_to_expert",
+ state: "done",
+ text: 'Teammate handled: "Create a chat app"',
+ output: { status: "running", sub_session_id: "sub-1" },
+ input: { prompt: "Create a chat app" },
+ })}
+ isLast
+ />,
+ );
+
+ // A dead poll can't refute the frozen "running", so the done label must
+ // never land — the row keeps saying the teammate is on it.
+ await expect(
+ screen.findByText('Teammate handled: "Create a chat app"'),
+ ).rejects.toThrow();
+ expect(
+ screen.getByText('Handing off to a teammate: "Create a chat app"…'),
+ ).toBeDefined();
+ });
+
it("switches to the done label once the polled sub-session goes idle", async () => {
server.use(subSession({ chat_status: "completed" }));
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/SubSessionLive.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/SubSessionLive.test.tsx
index 75d3d6cceb..4dd5470bf1 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/SubSessionLive.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/SubSessionLive.test.tsx
@@ -3,10 +3,14 @@ import { server } from "@/mocks/mock-server";
import { render, screen } from "@/tests/integrations/test-utils";
import { cleanup } from "@testing-library/react";
import { http, HttpResponse } from "msw";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { SubSessionCard } from "../AgentCards";
import { ToolResult } from "../ToolResult";
+/** Mirrors POLL_CAP_MS in SubSessionLive.tsx — the poll gives up after this.
+ * Kept local so the test states the contract rather than importing it. */
+const POLL_CAP_MS = 5 * 60_000;
+
const SESSION_ROUTE = "/api/proxy/api/chat/sessions/:sessionId";
const SESSION_LIST_ROUTE = "/api/proxy/api/chat/sessions";
@@ -48,13 +52,17 @@ function expertSessions() {
});
}
-function subSession(messages: Record<string, unknown>[]) {
+function subSession(
+ messages: Record<string, unknown>[],
+ extra: Record<string, unknown> = {},
+) {
return getGetV2GetSessionMockHandler200({
id: "sub-1",
created_at: "2026-08-21T00:00:00Z",
updated_at: "2026-08-21T00:00:00Z",
user_id: "u-1",
messages,
+ ...extra,
});
}
@@ -127,7 +135,7 @@ describe("SubSessionLive", () => {
expect(screen.queryByText("Done. Discord clone is built.")).toBeNull();
});
- it("shows who is on it before a blocking delegate returns", () => {
+ it("shows who is on it — and nothing else — before a blocking delegate returns", () => {
render(
<ToolResult
row={{
@@ -142,8 +150,155 @@ describe("SubSessionLive", () => {
);
expect(screen.getByText("Sub-AutoPilot")).toBeDefined();
- expect(screen.getByText("Create a chat app")).toBeDefined();
expect(screen.getByText("running")).toBeDefined();
+ // A teammate's thread is their own workspace: the delegated card is
+ // status-only, so the prompt preview stays out of the parent chain.
+ expect(screen.queryByText("Create a chat app")).toBeNull();
+ });
+
+ it("keeps a finished delegate card to name, role, status, time, and link", () => {
+ render(
+ <ToolResult
+ row={{
+ key: "delegate",
+ category: "agent",
+ text: "Teammate handled it",
+ state: "done",
+ tool: "delegate_to_expert",
+ input: {},
+ output: {
+ status: "completed",
+ response: "Here is the full brief the teammate wrote.",
+ sub_session_id: "sub-1",
+ sub_autopilot_session_link: "/copilot?sessionId=sub-1",
+ elapsed_seconds: 75,
+ expert: { name: "Vera", role: "Research" },
+ },
+ }}
+ />,
+ );
+
+ expect(screen.getByText(/Vera/)).toBeDefined();
+ expect(screen.getByText("Research")).toBeDefined();
+ expect(screen.getByText("completed")).toBeDefined();
+ expect(screen.getByText("1m 15s")).toBeDefined();
+ expect(
+ screen
+ .getByRole("link", { name: "Open sub-session" })
+ .getAttribute("href"),
+ ).toBe("/copilot?sessionId=sub-1");
+ expect(
+ screen.queryByText("Here is the full brief the teammate wrote."),
+ ).toBeNull();
+ });
+
+ /** The delegate/handoff tools name themselves, but a result poll is the
+ * same tool for the model's own scratch sub and for a teammate's thread —
+ * the `expert` on the output is the only thing telling them apart. */
+ it("keeps a delegated result poll minimal and still flips its pill when the teammate lands", async () => {
+ server.use(
+ subSession(
+ [
+ {
+ role: "assistant",
+ content: "Looking for the right agent now.",
+ tool_calls: null,
+ },
+ ],
+ { chat_status: "idle", active_stream: null },
+ ),
+ );
+
+ render(
+ <ToolResult
+ row={{
+ key: "poll",
+ category: "agent",
+ text: "Checking on the teammate",
+ state: "done",
+ tool: "get_sub_session_result",
+ input: {},
+ output: {
+ status: "running",
+ response: "Half of the brief so far.",
+ sub_session_id: "sub-1",
+ sub_autopilot_session_link: "/copilot?sessionId=sub-1",
+ expert: { name: "Vera", role: "Research" },
+ },
+ }}
+ />,
+ );
+
+ // The pill can only flip off the frozen "running" once the poll this hook
+ // owns has answered — so this also proves the card polls with no live
+ // view mounted to do it for them.
+ expect(await screen.findByText("completed")).toBeDefined();
+ expect(screen.queryByText("Looking for the right agent now.")).toBeNull();
+ expect(screen.queryByText("Half of the brief so far.")).toBeNull();
+ });
+
+ /** The pill is the only status surface a minimal card has — the full card's
+ * "Live updates paused" notice is exactly what got removed — so a dead
+ * poll has to reach it instead of leaving "running" standing as fact. */
+ it("stops asserting running on a minimal card once its poll dies", async () => {
+ server.use(failingSubSession());
+
+ render(
+ <ToolResult
+ row={{
+ key: "delegate",
+ category: "agent",
+ text: "Teammate is on it",
+ state: "done",
+ tool: "delegate_to_expert",
+ input: {},
+ output: {
+ status: "running",
+ sub_session_id: "sub-1",
+ expert: { name: "Vera", role: "Research" },
+ },
+ }}
+ />,
+ );
+
+ expect(await screen.findByText("unknown")).toBeDefined();
+ expect(screen.queryByText("running")).toBeNull();
+ });
+
+ /** The other way a poll dies: it is capped after 5 minutes so a forgotten
+ * tab stops hammering the API. A long delegation reaches that cap while
+ * the teammate is genuinely still working, so the pill must stop claiming
+ * to know — same contract as the failed-fetch case above. */
+ it("stops asserting running on a minimal card once the poll cap expires", async () => {
+ server.use(subSession([], { chat_status: "running", active_stream: null }));
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+
+ try {
+ render(
+ <ToolResult
+ row={{
+ key: "delegate",
+ category: "agent",
+ text: "Teammate is on it",
+ state: "done",
+ tool: "delegate_to_expert",
+ input: {},
+ output: {
+ status: "running",
+ sub_session_id: "sub-1",
+ expert: { name: "Vera", role: "Research" },
+ },
+ }}
+ />,
+ );
+
+ await vi.advanceTimersByTimeAsync(POLL_CAP_MS + 1);
+
+ expect(screen.getByText("unknown")).toBeDefined();
+ expect(screen.queryByText("running")).toBeNull();
+ } finally {
+ vi.useRealTimers();
+ }
});
it("finds the delegate's running session behind a wall of pinned ones", async () => {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolChain.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolChain.test.tsx
index e2448d59ec..85b047258c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolChain.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolChain.test.tsx
@@ -59,6 +59,26 @@ function getPanel(header: HTMLElement): HTMLElement | null {
return panelId ? document.getElementById(panelId) : null;
}
+// An action row shares its label with the chain heading, and both are
+// collapse toggles now — only the chain header owns the panel.
+function getChainHeader(name: RegExp): HTMLElement {
+ const header = screen
+ .getAllByRole("button", { name })
+ .find((button) => button.hasAttribute("aria-controls"));
+ if (!header) throw new Error(`No chain header matching ${name}`);
+ return header;
+}
+
+// The row's own toggle is the one without a panel — its `aria-expanded` says
+// whether the row's card is showing.
+function getRowToggle(name: RegExp): HTMLElement {
+ const toggle = screen
+ .getAllByRole("button", { name })
+ .find((button) => !button.hasAttribute("aria-controls"));
+ if (!toggle) throw new Error(`No row toggle matching ${name}`);
+ return toggle;
+}
+
describe("ToolChain", () => {
afterEach(() => {
cleanup();
@@ -267,9 +287,7 @@ describe("ToolChain", () => {
/>,
);
- const header = screen.getByRole("button", {
- name: /review send email/i,
- });
+ const header = getChainHeader(/review send email/i);
expect(getPanel(header)?.getAttribute("aria-hidden")).toBe("false");
expect(screen.getAllByText("Review Send Email").length).toBeGreaterThan(1);
@@ -304,9 +322,7 @@ describe("ToolChain", () => {
/>,
);
- const header = screen.getByRole("button", {
- name: /approve the new expert/i,
- });
+ const header = getChainHeader(/approve the new expert/i);
expect(getPanel(header)?.getAttribute("aria-hidden")).toBe("false");
expect(screen.getByText("Otto")).toBeDefined();
@@ -318,6 +334,68 @@ describe("ToolChain", () => {
expect(screen.getByText("Weekly budget: 2000 credits")).toBeDefined();
});
+ it("lets the user collapse an expert approval card", async () => {
+ const user = userEvent.setup();
+ render(
+ <ToolChain
+ parts={[
+ toolPart("hire_expert", "output-available", {
+ output: {
+ type: "expert_change_proposed",
+ applied: false,
+ confirmation_id: "conf-1",
+ preview: { kind: "hire", name: "Otto", role: "Inbox triage" },
+ },
+ }),
+ ]}
+ isStreaming={false}
+ />,
+ );
+
+ const header = getChainHeader(/approve the new expert/i);
+ expect(getPanel(header)?.getAttribute("aria-hidden")).toBe("false");
+
+ await user.click(header);
+ await user.click(header);
+
+ expect(getPanel(header)?.getAttribute("aria-hidden")).toBe("true");
+ });
+
+ // A live row mounts before its output exists, so "needs you" is only known
+ // on a later render — the reveal has to react to it, not read it once.
+ it("reveals an action row when its output arrives mid-stream", () => {
+ const pending = toolPart("run_block", "input-available");
+ const { rerender } = render(
+ <ToolChain parts={[pending]} isStreaming={true} />,
+ );
+
+ rerender(
+ <ToolChain
+ parts={[
+ toolPart("run_block", "output-available", {
+ output: { type: "review_required", block_name: "Send Email" },
+ }),
+ ]}
+ isStreaming={true}
+ />,
+ );
+
+ expect(
+ getRowToggle(/review send email/i).getAttribute("aria-expanded"),
+ ).toBe("true");
+ });
+
+ it("holds a card's shape while an expert is still being written", () => {
+ const { container } = render(
+ <ToolChain
+ parts={[toolPart("hire_expert", "input-available")]}
+ isStreaming={true}
+ />,
+ );
+
+ expect(container.querySelectorAll(".animate-pulse").length).toBe(5);
+ });
+
it("drafts answered questions into the chat input and dismisses on send", async () => {
const user = userEvent.setup();
const pending: PendingQuestions = {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/helpers.test.ts
index 4aeca3747f..13ee0917b1 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/helpers.test.ts
@@ -407,18 +407,23 @@ describe("getChainHeading", () => {
});
describe("buildChainSegments edge cases", () => {
- it("folds trailing narration optimistically while streaming", () => {
+ // Trailing text is the answer until a tool call proves otherwise. Folding
+ // it in optimistically meant it rendered as a chain row and then jumped
+ // out to message text when the text outgrew the narration cap or the
+ // turn settled.
+ it("keeps trailing narration out of the chain while streaming", () => {
const parts = [toolPart("web_search"), textPart("Wrapping up.")];
- expect(buildChainSegments(parts, isChainPart, true)).toEqual([
- { kind: "chain", parts, index: 0 },
+ expect(buildChainSegments(parts, isChainPart)).toEqual([
+ { kind: "chain", parts: [parts[0]], index: 0 },
+ { kind: "part", part: parts[1], index: 1 },
]);
});
it("keeps trailing narration out of a settled chain", () => {
const parts = [toolPart("web_search"), textPart("Here you go.")];
- expect(buildChainSegments(parts, isChainPart, false)).toEqual([
+ expect(buildChainSegments(parts, isChainPart)).toEqual([
{ kind: "chain", parts: [parts[0]], index: 0 },
{ kind: "part", part: parts[1], index: 1 },
]);
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts
index ab83a46b83..43199d033a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts
@@ -314,7 +314,6 @@ export type ChainSegment =
export function buildChainSegments(
parts: MessagePart[],
isChainable: (part: MessagePart) => boolean = isChainPart,
- isStreaming = false,
): ChainSegment[] {
const segments: ChainSegment[] = [];
let chain: Extract<ChainSegment, { kind: "chain" }> | null = null;
@@ -340,16 +339,12 @@ export function buildChainSegments(
chain.parts.push(part);
return;
}
- // Fold short progress narration into the surrounding chain. While
- // streaming, fold optimistically so the text lands inside the chain
- // from the first token; once settled, keep it only when another tool
- // call follows, so the turn's final answer (even a short one) always
- // renders as regular message text.
- if (
- chain &&
- narrationText(part) !== null &&
- (isStreaming || hasChainableAhead(index + 1))
- ) {
+ // Fold short progress narration into the surrounding chain, but only
+ // once a later tool call proves it was narration and not the answer.
+ // Folding optimistically while streaming made every trailing answer
+ // render inside the chain and then jump out to regular message text —
+ // either when it outgrew NARRATION_MAX_CHARS or when the stream ended.
+ if (chain && narrationText(part) !== null && hasChainableAhead(index + 1)) {
chain.parts.push(part);
return;
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/useCardResize.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/useCardResize.ts
new file mode 100644
index 0000000000..0a37968361
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/useCardResize.ts
@@ -0,0 +1,26 @@
+"use client";
+
+import { useLayoutEffect, useRef, useState } from "react";
+
+/** Measures the card body so its clipping wrapper can tween between the
+ * collapsed and expanded heights — `height: auto` is not interpolable, so
+ * the transition needs a real pixel value on both sides of the change. */
+export function useCardResize(expanded: boolean) {
+ const contentRef = useRef<HTMLDivElement>(null);
+ const [height, setHeight] = useState<number>();
+
+ useLayoutEffect(() => {
+ const el = contentRef.current;
+ if (!el) return;
+ function measure() {
+ if (el) setHeight(el.getBoundingClientRect().height);
+ }
+ measure();
+ // Text reflow (window resize, font swap) changes the clamped height too.
+ const observer = new ResizeObserver(measure);
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [expanded]);
+
+ return { contentRef, height };
+}