Skip to content

The open-source app everyone uses to manage agents at work

feat(ui): chat-style tasks polish — rich-text composer, attachment chips, live-turn interstitials, mobile layout (#10707)

scotttong9b9631b72448
diff --git a/ui/package.json b/ui/package.json
index c58649e49b..ce25a72fb5 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -29,6 +29,7 @@
},
"dependencies": {
"@assistant-ui/react": "0.14.14",
+ "@base-ui/react": "^1.6.0",
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
diff --git a/ui/src/components/FoldCurtain.tsx b/ui/src/components/FoldCurtain.tsx
index 0a42356720..14ca7beff8 100644
--- a/ui/src/components/FoldCurtain.tsx
+++ b/ui/src/components/FoldCurtain.tsx
@@ -19,6 +19,8 @@ interface FoldCurtainProps {
lessLabel?: string;
className?: string;
contentClassName?: string;
+ /** Extra classes for the Show more/less button (e.g. contrast lift on a colored bubble). */
+ toggleClassName?: string;
}
const MOBILE_BREAKPOINT = 640;
@@ -64,6 +66,7 @@ export function FoldCurtain({
lessLabel = "Show less",
className,
contentClassName,
+ toggleClassName,
}: FoldCurtainProps) {
const collapsedHeight = useResponsiveCollapsedHeight(explicitCollapsedHeight);
const contentRef = useRef<HTMLDivElement>(null);
@@ -129,7 +132,7 @@ export function FoldCurtain({
setAllowTransition(true);
setExpanded((v) => !v);
}}
- className="h-7 px-2 text-xs text-muted-foreground hover:text-foreground"
+ className={cn("h-7 px-2 text-xs text-muted-foreground hover:text-foreground", toggleClassName)}
>
{expanded ? lessLabel : moreLabel}
{expanded ? (
diff --git a/ui/src/components/InlineEditor.tsx b/ui/src/components/InlineEditor.tsx
index 77f6905adc..52f658e182 100644
--- a/ui/src/components/InlineEditor.tsx
+++ b/ui/src/components/InlineEditor.tsx
@@ -24,6 +24,13 @@ interface InlineEditorProps {
* `MarkdownBody` so resolved URLs render with the inline status icon prefix.
*/
externalReferences?: MarkdownExternalReferenceMap;
+ /**
+ * Mount the multiline editor already in edit mode, focused — for hosts whose
+ * own affordance opens the editor (the description bubble's pencil, PAP-375).
+ */
+ defaultEditing?: boolean;
+ /** Notified when the multiline editor swaps between display and edit mode. */
+ onEditingChange?: (editing: boolean) => void;
}
/** Shared padding so display and edit modes occupy the exact same box. */
@@ -61,9 +68,11 @@ export function InlineEditor({
mentions,
foldable = false,
externalReferences,
+ defaultEditing = false,
+ onEditingChange,
}: InlineEditorProps) {
const [editing, setEditing] = useState(false);
- const [multilineEditing, setMultilineEditing] = useState(false);
+ const [multilineEditing, setMultilineEditing] = useState(multiline && defaultEditing);
const [multilineFocused, setMultilineFocused] = useState(false);
const [draft, setDraft] = useState(value);
const lastPropValueRef = useRef(value);
@@ -72,7 +81,7 @@ export function InlineEditor({
const autosaveDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const blurCommitFrameRef = useRef<(() => void) | null>(null);
const pendingFocusFrameRef = useRef<number | null>(null);
- const justEnteredEditRef = useRef(false);
+ const justEnteredEditRef = useRef(multiline && defaultEditing);
const hasBeenFocusedRef = useRef(false);
const {
state: autosaveState,
@@ -156,7 +165,8 @@ export function InlineEditor({
if (autosaveState !== "idle") return;
hasBeenFocusedRef.current = false;
setMultilineEditing(false);
- }, [multiline, multilineEditing, multilineFocused, autosaveState]);
+ onEditingChange?.(false);
+ }, [multiline, multilineEditing, multilineFocused, autosaveState, onEditingChange]);
const commit = useCallback(async (nextValue = draft) => {
@@ -223,6 +233,7 @@ export function InlineEditor({
if (multiline) {
setMultilineFocused(false);
setMultilineEditing(false);
+ onEditingChange?.(false);
hasBeenFocusedRef.current = false;
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur();
@@ -269,6 +280,7 @@ export function InlineEditor({
if (multilineEditing) return;
justEnteredEditRef.current = true;
setMultilineEditing(true);
+ onEditingChange?.(true);
};
return (
<div
diff --git a/ui/src/components/IssueChatThread.tsx b/ui/src/components/IssueChatThread.tsx
index 0bcb0c6136..7ef8f2d5c9 100644
--- a/ui/src/components/IssueChatThread.tsx
+++ b/ui/src/components/IssueChatThread.tsx
@@ -108,6 +108,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { MarkdownBody, type MarkdownExternalReferenceMap } from "./MarkdownBody";
+import type { TaskChatIssueBrief } from "./task-chat/TaskChatDescriptionBubble";
import { WorkspaceFileMarkdownBody } from "./WorkspaceFileMarkdownBody";
import { MarkdownEditor, type MentionOption, type MarkdownEditorRef } from "./MarkdownEditor";
import { Identity } from "./Identity";
@@ -507,6 +508,13 @@ interface IssueChatThreadProps {
* the legacy thread ignores it — its header stays in the page flow.
*/
threadHeader?: ReactNode;
+ /**
+ * The task description rendered as the requester's first chat bubble
+ * (PAP-375). Only the redesigned TaskChatThread consumes it (flag:
+ * enableTaskChatRedesign); the legacy thread ignores it — its description
+ * stays in the page header via InlineEditor.
+ */
+ issueBrief?: TaskChatIssueBrief;
variant?: "full" | "embedded";
enableLiveTranscriptPolling?: boolean;
transcriptsByRunId?: ReadonlyMap<string, readonly IssueChatTranscriptEntry[]>;
diff --git a/ui/src/components/MarkdownBody.test.tsx b/ui/src/components/MarkdownBody.test.tsx
index bdcfd28393..85a96837f7 100644
--- a/ui/src/components/MarkdownBody.test.tsx
+++ b/ui/src/components/MarkdownBody.test.tsx
@@ -584,19 +584,20 @@ describe("MarkdownBody", () => {
expect(html).toContain('href="/issues/JIRA-2"');
});
- it("renders the inline mention status glyph at lg (20px / h-5 w-5)", () => {
+ it("renders the inline mention status glyph at md (16px / h-4 w-4)", () => {
const html = renderMarkdown("See PAP-1271 for context.", [
{ identifier: "PAP-1271", status: "in_progress" },
]);
- // Unified glyph at 20px, with the h-5 w-5 class override so the Tailwind
- // sizing matches the intrinsic SVG size.
+ // Unified glyph at 16px (PAP-349 round 4: stepped down from lg), with the
+ // h-4 w-4 class override so the Tailwind sizing matches the intrinsic SVG
+ // size.
expect(html).toContain('viewBox="0 0 24 24"');
- expect(html).toContain('width="20"');
- expect(html).toContain('height="20"');
- expect(html).toContain("h-5");
- expect(html).toContain("w-5");
- // PAP-243b: the lg glyph is optically centered to the body text
+ expect(html).toContain('width="16"');
+ expect(html).toContain('height="16"');
+ expect(html).toContain("h-4");
+ expect(html).toContain("w-4");
+ // PAP-243b: the glyph is optically centered to the body text
// (vertical-align: middle + a 1px lift), not floating off the baseline.
expect(html).toContain("align-middle");
expect(html).not.toContain("align-(--va-0_125em)");
diff --git a/ui/src/components/MarkdownBody.tsx b/ui/src/components/MarkdownBody.tsx
index 99fa9a6a2f..ff84f2e077 100644
--- a/ui/src/components/MarkdownBody.tsx
+++ b/ui/src/components/MarkdownBody.tsx
@@ -118,7 +118,7 @@ function MarkdownIssueLink({
aria-label={issueLabel}
>
{status ? (
- <StatusIcon status={status} size="lg" className="relative -top-px mr-1 inline-block h-5 w-5 align-middle" />
+ <StatusIcon status={status} size="md" className="relative -top-px mr-1 inline-block h-4 w-4 align-middle" />
) : null}
{children}
</Link>
diff --git a/ui/src/components/MarkdownEditor.tsx b/ui/src/components/MarkdownEditor.tsx
index 217a2438ad..9d7dc7415b 100644
--- a/ui/src/components/MarkdownEditor.tsx
+++ b/ui/src/components/MarkdownEditor.tsx
@@ -13,6 +13,7 @@ import {
type MouseEvent as ReactMouseEvent,
type PointerEvent as ReactPointerEvent,
type TouchEvent as ReactTouchEvent,
+ type ReactElement,
type ReactNode,
} from "react";
import { createPortal } from "react-dom";
@@ -32,6 +33,8 @@ import {
quotePlugin,
tablePlugin,
thematicBreakPlugin,
+ defaultSvgIcons,
+ type IconKey,
type RealmPlugin,
} from "@mdxeditor/editor";
import {
@@ -41,7 +44,7 @@ import {
buildRoutineMentionHref,
buildUserMentionHref,
} from "@paperclipai/shared";
-import { Boxes, CalendarClock, Hash, User } from "lucide-react";
+import { Boxes, CalendarClock, Hash, User, X } from "lucide-react";
import { AgentIcon } from "./AgentIconPicker";
import { applyMentionChipDecoration, clearMentionChipDecoration, parseMentionChipHref } from "../lib/mention-chips";
import { MentionAwareLinkNode, mentionAwareLinkNodeReplacement } from "../lib/mention-aware-link-node";
@@ -126,6 +129,12 @@ function readHtmlAttribute(attrs: string, name: string): string | null {
return match?.[2] ?? match?.[3] ?? match?.[4] ?? null;
}
+/** MDXEditor icon override: the image chip's delete button gets the lucide X. */
+function editorIconFor(name: IconKey): ReactElement {
+ if (name === "delete_small") return <X aria-hidden />;
+ return defaultSvgIcons[name];
+}
+
function convertHtmlImagesToMarkdown(text: string): string {
return text.replace(/<img\b([^>]*?)\/?>/gi, (tag, attrs: string) => {
const src = readHtmlAttribute(attrs, "src");
@@ -722,7 +731,11 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
const insertMarkdown = useCallback((markdown: string) => {
if (readOnly) return;
if (!richEditorError && ref.current) {
- ref.current.insertMarkdown(markdown);
+ // MDXEditor's insertMarkdown silently no-ops without a Lexical selection
+ // (an editor that was never focused). Focus first — the callback runs
+ // once focus (and a selection: caret kept, else rootEnd) is in place.
+ const editor = ref.current;
+ editor.focus(() => editor.insertMarkdown(markdown), { defaultSelection: "rootEnd" });
return;
}
const textarea = fallbackTextareaRef.current;
@@ -855,7 +868,9 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
markdownShortcutPlugin(),
];
if (imageHandler) {
- all.push(imagePlugin({ imageUploadHandler: imageHandler }));
+ // The inline image chip keeps only its remove affordance — no settings
+ // dialog, and the X glyph instead of MDXEditor's default trash can.
+ all.push(imagePlugin({ imageUploadHandler: imageHandler, disableImageSettingsButton: true }));
}
return all;
}, [hasImageUpload]);
@@ -1325,6 +1340,7 @@ export const MarkdownEditor = forwardRef<MarkdownEditorRef, MarkdownEditorProps>
<MDXEditor
ref={setEditorRef}
markdown={editorValue}
+ iconComponentFor={editorIconFor}
suppressHtmlProcessing
placeholder={placeholder}
readOnly={readOnly}
diff --git a/ui/src/components/TaskChatThread.tsx b/ui/src/components/TaskChatThread.tsx
index 8e64458107..a0575b3ba0 100644
--- a/ui/src/components/TaskChatThread.tsx
+++ b/ui/src/components/TaskChatThread.tsx
@@ -3,20 +3,30 @@ import { IssueChatThread } from "@/components/IssueChatThread";
import { useLiveRunTranscripts, type RunTranscriptSource } from "@/components/transcript/useLiveRunTranscripts";
import { commentsToTaskChatItems } from "@/components/task-chat/task-chat-adapter";
import {
+ assembleThreadItems,
+ attachSettledTurns,
buildTurnSummary,
+ coalesceSettledTurns,
deriveRunStatusLabel,
+ isNestableLiveChild,
isTerminalRunStatus,
+ prependIssueBrief,
+ settledRunChildren,
transcriptToTaskChatItems,
+ type SettledTurnMergeMeta,
} from "@/components/task-chat/transcript-adapter";
+import { TaskChatDescriptionBubble } from "@/components/task-chat/TaskChatDescriptionBubble";
import type {
TaskChatInteractionItem,
TaskChatItem,
- TaskChatTurnChildItem,
TaskChatTurnItem,
} from "@/components/task-chat/task-chat-model";
import { TaskChatInteractionCard } from "@/components/task-chat/TaskChatInteractionCard";
-import { TaskChatThreadView } from "@/components/task-chat/TaskChatThreadView";
+import { TaskChatThreadView, taskChatContentKey } from "@/components/task-chat/TaskChatThreadView";
import { TaskChatComposer } from "@/components/task-chat/TaskChatComposer";
+import { useWindowAutoFollow } from "@/components/task-chat/useWindowAutoFollow";
+import { useSidebar } from "@/context/SidebarContext";
+import { cn } from "@/lib/utils";
import { useIssuePlanDocument } from "@/hooks/useIssuePlanDocument";
import { latestSameRunHandoffTimestamp, type IssueChatComment } from "@/lib/issue-chat-messages";
import { workModeInEffectAt } from "@/lib/issue-timeline-events";
@@ -45,13 +55,20 @@ export type TaskChatThreadProps = ComponentProps<typeof IssueChatThread>;
* pill.
*
* Run activity is grouped into TaskChatTurnItem: the in-flight run renders as
- * an unsettled (expanded) turn; when it terminates the same turn id flips
- * settled, so TaskChatTurn plays the ~--motion-turn-fold collapse down to the
- * one-line "✓ Worked · …" summary (runs already terminal at mount collapse
- * instantly). Settled turns interleave after the run's last comment
- * (comment.runId linkage) — the agent's reply bubble above, the folded activity
- * summary below, so the live "Running…" pill reads as being replaced by the
- * summary in place. flag-OFF remains byte-for-byte IssueChatThread.
+ * ONE expandable parent row — its status line (whimsy gerund or in-flight
+ * tool state + elapsed + tokens) is the turn's single visible line, with the
+ * chronological tool activity nested behind an expand (PAP-354). Mid-run
+ * agent text (interstitial updates between tool calls) is ephemeral
+ * (PAP-361, round 9): while one streams it occupies a dedicated one-line row
+ * PERMANENTLY RESERVED above the status line (so the layout above never
+ * jumps), and when it finishes the text slides out and the slot sits empty —
+ * nothing persists; the run log and the classic transcript remain the
+ * archive. When the run terminates, its settled turn anchors after the run's
+ * last comment (comment.runId linkage) and — when it directly follows that
+ * reply bubble — attaches to it: the "✓ Worked · …" summary renders appended
+ * to the bubble's always-visible timestamp line (round 9), still expandable
+ * to the tool history. Turns without a reply bubble keep the standalone
+ * folded row. flag-OFF remains byte-for-byte IssueChatThread.
*/
export function TaskChatThread(props: TaskChatThreadProps) {
const {
@@ -76,6 +93,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
activeRun,
onAttachImage,
imageUploadHandler,
+ mentions,
enableReassign,
reassignOptions,
currentAssigneeValue,
@@ -88,6 +106,7 @@ export function TaskChatThread(props: TaskChatThreadProps) {
externalReferences,
threadHeader,
workModeChanges,
+ issueBrief,
} = props;
const linkedRunMetaById = useMemo(() => {
@@ -164,7 +183,9 @@ export function TaskChatThread(props: TaskChatThreadProps) {
// Each terminal run's turn anchors immediately after the run's last comment
// (its reply bubble), via the comment.runId linkage — the summary line lands
- // below the bubble, where the live "Running…" pill sat.
+ // below the bubble, where the live "Running…" pill sat. A run with no linked
+ // comment (stopped run, or reply not yet fetched) instead slots into the
+ // backbone chronologically at its start time (PAP-367).
const lastCommentIdByRun = useMemo(() => {
const map = new Map<string, string>();
for (const comment of comments) {
@@ -232,11 +253,20 @@ export function TaskChatThread(props: TaskChatThreadProps) {
);
}, [comments, commentItems, interactions, timelineEvents, linkedRuns, liveRuns, planDocument]);
+ // Boolean gate (stable across the host's per-render brief objects) so the
+ // heavy assembly memo doesn't recompute on every parent render.
+ const hasBrief = Boolean(issueBrief);
+
const items = useMemo<TaskChatItem[]>(() => {
- // Settled turns for every terminal run whose transcript we have. The
- // transcript's assistant text is excluded — it already landed as the run's
- // comment bubble; the turn holds the activity (thinking/tools/diffs).
- const settledTurns: { turn: TaskChatTurnItem; anchorCommentId: string | null; order: number }[] = [];
+ // Settled turns for every terminal run whose transcript we have. Messages
+ // and thinking are excluded entirely (PAP-361): the final reply already
+ // landed as the run's comment bubble, interstitial updates are ephemeral
+ // (live-line only), and thinking stays in the run log / classic
+ // transcript — "Worked · N tools" expands to exactly the tool rows.
+ const settledTurns: { turn: TaskChatTurnItem; anchorCommentId: string | null; startMs: number }[] = [];
+ // Raw summary inputs per turn id, so back-to-back same-agent runs can
+ // coalesce into one "Worked" row in the final pass (PAP-362).
+ const turnMergeMetaById = new Map<string, SettledTurnMergeMeta>();
for (const source of runs) {
if (!isTerminalRunStatus(source.status)) continue;
if (liveRun && source.id === liveRun.id) continue;
@@ -249,12 +279,20 @@ export function TaskChatThread(props: TaskChatThreadProps) {
Number.isFinite(started) && Number.isFinite(finished)
? Math.max(0, finished - started)
: undefined;
- const children = transcriptToTaskChatItems(entries, {
+ const parsed = transcriptToTaskChatItems(entries, {
runId: source.id,
agentName: meta?.agentName,
running: false,
- }).filter((it): it is TaskChatTurnChildItem => it.kind !== "turn" && it.kind !== "message");
+ });
+ const children = settledRunChildren(parsed);
if (children.length === 0) continue;
+ const failed = source.status !== "succeeded";
+ const startSlotRaw = meta?.startedAt ?? meta?.createdAt;
+ turnMergeMetaById.set(`${source.id}:turn`, {
+ agentKey: meta?.agentId ?? "",
+ agentName: meta?.agentName,
+ parts: [{ entries, durationMs, failed }],
+ });
settledTurns.push({
turn: {
id: `${source.id}:turn`,
@@ -262,70 +300,86 @@ export function TaskChatThread(props: TaskChatThreadProps) {
settled: true,
animateFold: liveSeenRef.current.has(source.id),
items: children,
- summary: buildTurnSummary(entries, {
- durationMs,
- failed: source.status !== "succeeded",
- }),
+ summary: buildTurnSummary(entries, { durationMs, failed }),
},
anchorCommentId: lastCommentIdByRun.get(source.id) ?? null,
- order: meta?.createdAt ? new Date(meta.createdAt).getTime() : 0,
+ // Chronological slot for a turn with no reply comment to anchor to
+ // (PAP-367): the run's start time. A run with no linked meta yet
+ // (just-settled, list not refetched) sits at the thread tail —
+ // where it last rendered as the live turn — until meta arrives.
+ startMs: startSlotRaw ? toMs(startSlotRaw) : Number.POSITIVE_INFINITY,
});
}
- settledTurns.sort((a, b) => a.order - b.order);
+ settledTurns.sort((a, b) => (a.startMs < b.startMs ? -1 : a.startMs > b.startMs ? 1 : 0));
const turnsByAnchor = new Map<string, TaskChatTurnItem[]>();
- const unanchored: TaskChatTurnItem[] = [];
- for (const { turn, anchorCommentId } of settledTurns) {
+ const unanchored: { turn: TaskChatTurnItem; startMs: number }[] = [];
+ for (const { turn, anchorCommentId, startMs } of settledTurns) {
if (anchorCommentId) {
const list = turnsByAnchor.get(anchorCommentId) ?? [];
list.push(turn);
turnsByAnchor.set(anchorCommentId, list);
} else {
- unanchored.push(turn);
+ unanchored.push({ turn, startMs });
}
}
- const out: TaskChatItem[] = [];
- for (const entry of orderedEntries) {
- out.push(entry.item);
- const following = turnsByAnchor.get(entry.id);
- if (following) out.push(...following);
- }
- out.push(...unanchored);
+ // Anchored turns follow their run's reply comment; comment-less turns
+ // (stopped runs, or a reply not yet fetched) interleave chronologically at
+ // their run's start time instead of piling up under the newest message
+ // (PAP-367).
+ const out = assembleThreadItems(orderedEntries, turnsByAnchor, unanchored);
if (liveRun) {
const entries = transcriptByRun.get(liveRun.id) ?? [];
- const children = transcriptToTaskChatItems(entries, {
+ const parsed = transcriptToTaskChatItems(entries, {
runId: liveRun.id,
agentName: liveRun.agentName,
running: true,
- }).filter((it): it is TaskChatTurnChildItem => it.kind !== "turn");
- if (children.length > 0) {
- out.push({
- id: `${liveRun.id}:turn`,
- kind: "turn",
- settled: false,
- items: children,
- summary: buildTurnSummary(entries),
- });
- }
+ });
+ // Parent-row model (PAP-354): the run's status line IS the live turn —
+ // one expandable row owning the activity. Only tool/usage rows nest
+ // inside it; a streaming interstitial update renders in the reserved row
+ // above the status line (liveStatus.selfTalk, PAP-361/round 9) and
+ // vanishes when it completes. The parent row sits last; on settle its
+ // summary attaches to the reply bubble's timestamp line.
+ const children = parsed.filter(isNestableLiveChild);
const startedAt = liveRun.startedAt ? new Date(liveRun.startedAt).getTime() : null;
const queued = liveRun.status === "queued";
const status = queued
- ? { label: "Queued", detail: "Waiting to start", toolName: undefined }
+ ? { label: "Queued", detail: "Waiting to start", toolName: undefined, selfTalk: undefined }
: deriveRunStatusLabel(entries);
out.push({
- id: `${liveRun.id}:status`,
- kind: "status",
- status: "running",
- label: status.label,
- detail: status.detail,
- toolName: status.toolName,
- startedAtMs: startedAt ?? undefined,
+ id: `${liveRun.id}:turn`,
+ kind: "turn",
+ settled: false,
+ items: children,
+ summary: buildTurnSummary(entries),
+ liveStatus: {
+ id: `${liveRun.id}:status`,
+ kind: "status",
+ status: "running",
+ label: status.label,
+ detail: status.detail,
+ toolName: status.toolName,
+ selfTalk: status.selfTalk,
+ startedAtMs: startedAt ?? undefined,
+ },
});
}
- return out;
- }, [orderedEntries, runs, liveRun, transcriptByRun, linkedRunMetaById, lastCommentIdByRun]);
+ // PAP-362: two runs replying back-to-back (same agent, nothing but the
+ // agent's own bubbles between) fold into ONE "Worked" row below the last
+ // reply; a user message, interaction, or the live turn keeps them apart.
+ // Round 9: a settled turn directly following its own agent's reply bubble
+ // then attaches to that bubble — the "Worked · …" summary renders on the
+ // bubble's always-visible timestamp line instead of as a standalone row.
+ // PAP-375: the description-as-first-bubble placeholder prepends LAST, after
+ // every assembly/merge pass, so nothing can ever sort above it.
+ return prependIssueBrief(
+ attachSettledTurns(coalesceSettledTurns(out, turnMergeMetaById), turnMergeMetaById),
+ hasBrief,
+ );
+ }, [orderedEntries, runs, liveRun, transcriptByRun, linkedRunMetaById, lastCommentIdByRun, hasBrief]);
const renderInteraction = useCallback(
(item: TaskChatInteractionItem) => (
@@ -357,14 +411,22 @@ export function TaskChatThread(props: TaskChatThreadProps) {
],
);
+ // Mobile (PAP-360): the app shell scrolls the DOCUMENT (Layout's main is
+ // overflow-visible with auto height), so the desktop bounded h-dvh chain
+ // collapses the absolute-inset transcript viewport to 0px. Render the thread
+ // in document flow instead (the same scroll={false} path the previews use)
+ // and track auto-follow against window scroll. Desktop stays byte-identical.
+ const { isMobile } = useSidebar();
+ useWindowAutoFollow(isMobile ? taskChatContentKey(items) : 0, isMobile);
+
return (
<div
- className="flex h-(--tc-thread-max-h) min-h-0 flex-1 flex-col"
+ className={cn("flex flex-col", !isMobile && "h-(--tc-thread-max-h) min-h-0 flex-1")}
data-testid="task-chat-thread"
>
- <div className="flex min-h-0 flex-1 flex-col">
+ <div className={cn("flex flex-col", !isMobile && "min-h-0 flex-1")}>
{items.length === 0 ? (
- <div className="min-h-0 flex-1 overflow-y-auto">
+ <div className={isMobile ? undefined : "min-h-0 flex-1 overflow-y-auto"}>
{threadHeader ? (
<div
className="mx-auto flex w-full max-w-(--tc-shell-max-w) flex-col gap-6 px-4 pt-4"
@@ -376,11 +438,26 @@ export function TaskChatThread(props: TaskChatThreadProps) {
<div className="px-3 py-10 text-center text-sm text-muted-foreground">{emptyMessage}</div>
</div>
) : (
- <TaskChatThreadView items={items} header={threadHeader} renderInteraction={renderInteraction} />
+ <TaskChatThreadView
+ items={items}
+ header={threadHeader}
+ renderInteraction={renderInteraction}
+ renderBrief={issueBrief ? () => <TaskChatDescriptionBubble brief={issueBrief} /> : undefined}
+ scroll={!isMobile}
+ />
)}
</div>
{showComposer ? (
- <div className="sticky bottom-0 z-10 mx-auto flex w-full max-w-(--tc-shell-max-w) flex-col gap-2 bg-background/80 px-1 pb-2 pt-1 backdrop-blur supports-[backdrop-filter]:bg-background/60">
+ <div
+ className={cn(
+ "sticky",
+ // Mobile mirrors the flag-off thread's dock: lifted above the
+ // safe-area inset (and clear of the auto-hiding bottom nav), above
+ // page content in the document-flow stacking context.
+ isMobile ? "bottom-(--sz-calc-8) z-20" : "bottom-0 z-10",
+ "mx-auto flex w-full max-w-(--tc-shell-max-w) flex-col gap-2 bg-background/80 px-1 pb-2 pt-1 backdrop-blur supports-[backdrop-filter]:bg-background/60",
+ )}
+ >
{composerAccessory}
<TaskChatComposer
onAdd={onAdd}
@@ -390,10 +467,12 @@ export function TaskChatThread(props: TaskChatThreadProps) {
disabledReason={composerDisabledReason}
onAttachImage={onAttachImage}
onImageUpload={imageUploadHandler}
+ mentions={mentions}
enableReassign={enableReassign}
reassignOptions={reassignOptions}
currentAssigneeValue={currentAssigneeValue}
issueStatus={issueStatus}
+ mobile={isMobile}
/>
{footer}
</div>
diff --git a/ui/src/components/task-chat/McpIcon.tsx b/ui/src/components/task-chat/McpIcon.tsx
new file mode 100644
index 0000000000..c4612b0d37
--- /dev/null
+++ b/ui/src/components/task-chat/McpIcon.tsx
@@ -0,0 +1,24 @@
+import type { SVGProps } from "react";
+
+/**
+ * Official Model Context Protocol logo (wikimedia commons), redrawn as a
+ * lucide-compatible stroke icon: currentColor, sized via className like any
+ * other taxonomy glyph.
+ */
+export function McpIcon(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ viewBox="0 0 180 180"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={14}
+ strokeLinecap="round"
+ xmlns="http://www.w3.org/2000/svg"
+ {...props}
+ >
+ <path d="M18 84.8528L85.8822 16.9706C95.2548 7.59798 110.451 7.59798 119.823 16.9706C129.196 26.3431 129.196 41.5391 119.823 50.9117L68.5581 102.177" />
+ <path d="M69.2652 101.47L119.823 50.9117C129.196 41.5391 144.392 41.5391 153.765 50.9117L154.118 51.2652C163.491 60.6378 163.491 75.8338 154.118 85.2063L92.7248 146.6C89.6006 149.724 89.6006 154.789 92.7248 157.913L105.331 170.52" />
+ <path d="M102.853 33.9411L52.6482 84.1457C43.2756 93.5183 43.2756 108.714 52.6482 118.087C62.0208 127.459 77.2167 127.459 86.5893 118.087L136.794 67.8822" />
+ </svg>
+ );
+}
diff --git a/ui/src/components/task-chat/TaskChatBubble.test.tsx b/ui/src/components/task-chat/TaskChatBubble.test.tsx
new file mode 100644
index 0000000000..e16c4a20f9
--- /dev/null
+++ b/ui/src/components/task-chat/TaskChatBubble.test.tsx
@@ -0,0 +1,169 @@
+// @vitest-environment jsdom
+
+import type { ReactNode } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { ThemeProvider } from "@/context/ThemeContext";
+import { TaskChatBubble } from "./TaskChatBubble";
+import type { TaskChatMessageItem } from "./task-chat-model";
+
+describe("TaskChatBubble attachment chips", () => {
+ let container: HTMLDivElement;
+ let root: Root | null = null;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ flushSync(() => root?.unmount());
+ root = null;
+ container.remove();
+ });
+
+ function renderMessage(text: string, author: TaskChatMessageItem["author"] = "human") {
+ const item: TaskChatMessageItem = { id: "m1", kind: "message", author, text };
+ flushSync(() =>
+ root!.render(
+ <ThemeProvider>
+ <TaskChatBubble item={item} />
+ </ThemeProvider>,
+ ),
+ );
+ }
+
+ it("renders a file reference as an attachment chip linking to the file", () => {
+ renderMessage("Here you go.\n\n[notes.txt](/api/attachments/abc/content) ");
+
+ const group = container.querySelector('[data-testid="task-chat-bubble-attachments"]');
+ expect(group).not.toBeNull();
+ expect(group?.textContent).toContain("notes.txt");
+ expect(group?.textContent).toContain("Text");
+ const link = group?.querySelector<HTMLAnchorElement>("a[href='/api/attachments/abc/content']");
+ expect(link).not.toBeNull();
+ // The link-only line left the rendered body; the prose stayed.
+ expect(container.textContent).toContain("Here you go.");
+ expect(container.textContent).not.toContain("(/api/attachments/abc/content)");
+ });
+
+ it("renders a chip-only row when the message body is just the file link", () => {
+ renderMessage("[report.pdf](/api/attachments/r1/content)", "agent");
+
+ expect(container.querySelector('[data-testid="task-chat-bubble-attachments"]')).not.toBeNull();
+ // No empty bubble is left behind once the only line is chipped.
+ expect(container.textContent).toContain("report.pdf");
+ expect(container.textContent).toContain("PDF");
+ });
+
+ it("leaves messages without file references untouched", () => {
+ renderMessage("Just words and a [normal link](https://example.com).");
+
+ expect(container.querySelector('[data-testid="task-chat-bubble-attachments"]')).toBeNull();
+ expect(container.textContent).toContain("Just words");
+ });
+});
+
+describe("TaskChatBubble interstitial self-talk (PAP-357)", () => {
+ let container: HTMLDivElement;
+ let root: Root | null = null;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ flushSync(() => root?.unmount());
+ root = null;
+ container.remove();
+ });
+
+ function renderItem(item: TaskChatMessageItem) {
+ flushSync(() =>
+ root!.render(
+ <ThemeProvider>
+ <TaskChatBubble item={item} />
+ </ThemeProvider>,
+ ),
+ );
+ }
+
+ it("renders nothing — self-talk is ambient signal, suppressed in this view", () => {
+ renderItem({
+ id: "m1",
+ kind: "message",
+ author: "agent",
+ authorName: "CEO",
+ text: "Let me check the **adapter** first.",
+ interstitial: true,
+ streaming: true,
+ });
+ expect(container.textContent).toBe("");
+ expect(container.querySelector('[data-testid="task-chat-agent-avatar"]')).toBeNull();
+ });
+
+ it("keeps the bubble and avatar header for non-interstitial agent replies", () => {
+ renderItem({
+ id: "m1",
+ kind: "message",
+ author: "agent",
+ authorName: "CEO",
+ text: "Final reply.",
+ });
+ expect(container.querySelector('[data-testid="task-chat-interstitial"]')).toBeNull();
+ expect(container.querySelector('[data-testid="task-chat-agent-avatar"]')).not.toBeNull();
+ expect(container.textContent).toContain("CEO");
+ });
+});
+
+describe("TaskChatBubble footer line (round 9)", () => {
+ let container: HTMLDivElement;
+ let root: Root | null = null;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ flushSync(() => root?.unmount());
+ root = null;
+ container.remove();
+ });
+
+ function renderBubble(item: TaskChatMessageItem, attachedTurn?: ReactNode) {
+ flushSync(() =>
+ root!.render(
+ <ThemeProvider>
+ <TaskChatBubble item={item} attachedTurn={attachedTurn} />
+ </ThemeProvider>,
+ ),
+ );
+ }
+
+ it("shows the timestamp always — not only on hover", () => {
+ renderBubble({ id: "m1", kind: "message", author: "agent", authorName: "CEO", text: "Done.", timestamp: "2:34 PM" });
+ const stamp = [...container.querySelectorAll("span")].find((el) => el.textContent === "2:34 PM");
+ expect(stamp).not.toBeNull();
+ expect(stamp?.className).not.toContain("opacity-0");
+ expect(stamp?.className).not.toContain("group-hover");
+ });
+
+ it("renders the attached turn in place of the plain timestamp footer", () => {
+ renderBubble(
+ { id: "m1", kind: "message", author: "agent", authorName: "CEO", text: "Done.", timestamp: "2:34 PM" },
+ <div data-testid="fake-attached-turn">2:34 PM · Worked</div>,
+ );
+ const slot = container.querySelector('[data-testid="task-chat-bubble-attached-turn"]');
+ expect(slot).not.toBeNull();
+ expect(slot?.querySelector('[data-testid="fake-attached-turn"]')).not.toBeNull();
+ // The plain footer timestamp is replaced (the attached line carries it).
+ const plain = [...container.querySelectorAll("span")].filter((el) => el.textContent === "2:34 PM");
+ expect(plain).toHaveLength(0);
+ });
+});
diff --git a/ui/src/components/task-chat/TaskChatBubble.tsx b/ui/src/components/task-chat/TaskChatBubble.tsx
index db353504ab..e164abf8cc 100644
--- a/ui/src/components/task-chat/TaskChatBubble.tsx
+++ b/ui/src/components/task-chat/TaskChatBubble.tsx
@@ -1,11 +1,29 @@
+import type { ReactNode } from "react";
import { cn } from "@/lib/utils";
import { MarkdownBody } from "@/components/MarkdownBody";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { AgentIcon } from "@/components/AgentIconPicker";
+import {
+ Attachment,
+ AttachmentContent,
+ AttachmentDescription,
+ AttachmentGroup,
+ AttachmentMedia,
+ AttachmentTitle,
+ AttachmentTrigger,
+} from "@/components/ui/attachment";
+import { extractAttachmentRefs, fileKindForName } from "./task-chat-attachments";
import type { TaskChatMessageItem } from "./task-chat-model";
interface TaskChatBubbleProps {
item: TaskChatMessageItem;
+ /**
+ * The settled run turn rendered on this bubble's footer line (round 9):
+ * replaces the plain timestamp with "2:34 PM · ✓ Worked · 38s · 3 tools"
+ * (the timestamp leads the summary), expandable to the nested tool history.
+ * Supplied by TaskChatThreadView when `item.attachedTurn` is set.
+ */
+ attachedTurn?: ReactNode;
}
function initialsForName(name: string) {
@@ -22,7 +40,15 @@ function initialsForName(name: string) {
* bubble with an avatar author header (the agent's assigned icon + name · mode
* chip); system notices are centered and recede.
*/
-export function TaskChatBubble({ item }: TaskChatBubbleProps) {
+export function TaskChatBubble({ item, attachedTurn }: TaskChatBubbleProps) {
+ if (item.interstitial) {
+ // Interstitial updates are ephemeral (PAP-361): while streaming the text
+ // lives on the live parent row's line (TaskChatStatusItem.selfTalk), and
+ // once finished it renders nowhere — the run log / classic transcript
+ // remain the archive. Never rendered as a bubble.
+ return null;
+ }
+
if (item.author === "system") {
return (
<div className="tc-enter-bubble flex justify-center py-1">
@@ -32,8 +58,11 @@ export function TaskChatBubble({ item }: TaskChatBubbleProps) {
}
const isHuman = item.author === "human";
+ // Non-image file references ("[name](/api/attachments/…/content)") render as
+ // attachment chips under the bubble; link-only lines leave the body text.
+ const { refs: attachmentRefs, text: bodyText } = extractAttachmentRefs(item.text);
return (
- <div className={cn("tc-enter-bubble group flex w-full flex-col gap-1", isHuman ? "items-end" : "items-start")}>
+ <div className={cn("tc-enter-bubble flex w-full flex-col gap-1", isHuman ? "items-end" : "items-start")}>
{!isHuman && item.authorName ? (
<span className="flex items-center gap-2 px-1">
<Avatar size="sm" className="shrink-0" data-testid="task-chat-agent-avatar">
@@ -53,25 +82,60 @@ export function TaskChatBubble({ item }: TaskChatBubbleProps) {
) : null}
</span>
) : null}
- <div
- className={cn(
- "max-w-(--pct-85) break-words px-3.5 py-2 text-sm",
- isHuman
- ? "rounded-2xl rounded-br-sm bg-(--liveness-blue) text-white"
- : "rounded-2xl rounded-bl-sm bg-(--bubble-agent) text-foreground",
- item.optimistic ? "opacity-80" : null,
- )}
- >
- <MarkdownBody softBreaks linkIssueReferences>
- {item.text}
- </MarkdownBody>
- </div>
+ {bodyText.length > 0 ? (
+ <div
+ className={cn(
+ "max-w-(--pct-85) break-words px-3.5 py-2 text-sm",
+ isHuman
+ ? "rounded-2xl rounded-br-sm bg-(--liveness-blue) text-white"
+ : "rounded-2xl rounded-bl-sm bg-(--bubble-agent) text-foreground",
+ item.optimistic ? "opacity-80" : null,
+ )}
+ >
+ <MarkdownBody softBreaks linkIssueReferences>
+ {bodyText}
+ </MarkdownBody>
+ </div>
+ ) : null}
+ {attachmentRefs.length > 0 ? (
+ <AttachmentGroup
+ className="max-w-(--pct-85)"
+ data-testid="task-chat-bubble-attachments"
+ >
+ {attachmentRefs.map((ref) => {
+ const kind = fileKindForName(ref.name);
+ const KindIcon = kind.icon;
+ return (
+ <Attachment key={ref.url} size="sm" className={cn(item.optimistic && "opacity-80")}>
+ <AttachmentMedia>
+ <KindIcon aria-hidden />
+ </AttachmentMedia>
+ <AttachmentContent>
+ <AttachmentTitle className="max-w-48">{ref.name}</AttachmentTitle>
+ <AttachmentDescription className="max-w-48">{kind.label}</AttachmentDescription>
+ </AttachmentContent>
+ <AttachmentTrigger
+ aria-label={`Open ${ref.name}`}
+ render={<a href={ref.url} target="_blank" rel="noreferrer" />}
+ />
+ </Attachment>
+ );
+ })}
+ </AttachmentGroup>
+ ) : null}
{item.optimistic ? (
<span className="px-1 text-(length:--text-micro) text-muted-foreground">
{item.optimistic === "queued" ? "Queued" : "Sending…"}
</span>
+ ) : attachedTurn ? (
+ // The settled turn takes over the footer line: timestamp + "✓ Worked"
+ // summary, always visible; expanding stretches beneath the bubble.
+ <div className="self-stretch" data-testid="task-chat-bubble-attached-turn">
+ {attachedTurn}
+ </div>
) : item.timestamp ? (
- <span className="px-1 text-(length:--text-micro) text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100">
+ // Timestamps are always visible (round 9) — no longer hover-revealed.
+ <span className="px-1 text-(length:--text-micro) text-muted-foreground">
{item.timestamp}
</span>
) : null}
diff --git a/ui/src/components/task-chat/TaskChatComposer.test.tsx b/ui/src/components/task-chat/TaskChatComposer.test.tsx
index 2860cc9ba1..215580b088 100644
--- a/ui/src/components/task-chat/TaskChatComposer.test.tsx
+++ b/ui/src/components/task-chat/TaskChatComposer.test.tsx
@@ -4,66 +4,241 @@ import type { ReactElement } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { buildAgentMentionHref, buildSkillMentionHref } from "@paperclipai/shared";
import { TaskChatComposer } from "./TaskChatComposer";
+/**
+ * MDXEditor-in-jsdom weight (mirrors MarkdownEditor.test.tsx): the real editor
+ * is mocked with a contenteditable bridge — typing is simulated by setting
+ * textContent and dispatching an input event, imperative setMarkdown /
+ * insertMarkdown mutate the same content, and imagePlugin's config is captured
+ * so the inline upload handler can be exercised directly.
+ */
+const mdxEditorMockState = vi.hoisted(() => ({
+ imagePluginOptions: null as { imageUploadHandler?: (file: File) => Promise<string> } | null,
+}));
+
+vi.mock("@mdxeditor/editor", async () => {
+ const React = await import("react");
+
+ function setForwardedRef<T>(ref: React.ForwardedRef<T | null>, value: T | null) {
+ if (typeof ref === "function") {
+ ref(value);
+ return;
+ }
+ if (ref) {
+ (ref as React.MutableRefObject<T | null>).current = value;
+ }
+ }
+
+ interface MockHandle {
+ setMarkdown: (value: string) => void;
+ insertMarkdown: (value: string) => void;
+ focus: (callback?: () => void) => void;
+ }
+
+ const MDXEditor = React.forwardRef(function MockMDXEditor(
+ {
+ markdown,
+ onChange,
+ readOnly,
+ }: {
+ markdown: string;
+ onChange?: (value: string) => void;
+ readOnly?: boolean;
+ },
+ forwardedRef: React.ForwardedRef<MockHandle | null>,
+ ) {
+ const editableRef = React.useRef<HTMLDivElement>(null);
+ const contentRef = React.useRef(markdown);
+ const onChangeRef = React.useRef(onChange);
+ onChangeRef.current = onChange;
+
+ const handle = React.useMemo<MockHandle>(() => ({
+ setMarkdown: (value: string) => {
+ contentRef.current = value;
+ if (editableRef.current) editableRef.current.textContent = value;
+ },
+ insertMarkdown: (value: string) => {
+ const next = contentRef.current ? `${contentRef.current}${value}` : value;
+ contentRef.current = next;
+ if (editableRef.current) editableRef.current.textContent = next;
+ onChangeRef.current?.(next);
+ },
+ focus: (callback?: () => void) => {
+ editableRef.current?.focus();
+ callback?.();
+ },
+ }), []);
+
+ React.useEffect(() => {
+ if (editableRef.current && contentRef.current) {
+ editableRef.current.textContent = contentRef.current;
+ }
+ setForwardedRef(forwardedRef, handle);
+ return () => setForwardedRef(forwardedRef, null);
+ }, [forwardedRef, handle]);
+
+ return (
+ <div
+ ref={editableRef}
+ data-testid="mdx-editor"
+ contentEditable={!readOnly}
+ suppressContentEditableWarning
+ onInput={(e) => {
+ const next = e.currentTarget.textContent ?? "";
+ contentRef.current = next;
+ onChangeRef.current?.(next);
+ }}
+ />
+ );
+ });
+
+ return {
+ CodeMirrorEditor: () => null,
+ MDXEditor,
+ codeBlockPlugin: () => ({}),
+ codeMirrorPlugin: () => ({}),
+ createRootEditorSubscription$: Symbol("createRootEditorSubscription$"),
+ headingsPlugin: () => ({}),
+ imagePlugin: (options: { imageUploadHandler?: (file: File) => Promise<string> }) => {
+ mdxEditorMockState.imagePluginOptions = options;
+ return {};
+ },
+ linkDialogPlugin: () => ({}),
+ linkPlugin: () => ({}),
+ listsPlugin: () => ({}),
+ markdownShortcutPlugin: () => ({}),
+ quotePlugin: () => ({}),
+ realmPlugin: (plugin: unknown) => plugin,
+ tablePlugin: () => ({}),
+ thematicBreakPlugin: () => ({}),
+ };
+});
+
+vi.mock("../../lib/mention-deletion", () => ({
+ mentionDeletionPlugin: () => ({}),
+}));
+
+vi.mock("../../lib/paste-normalization", () => ({
+ pasteNormalizationPlugin: () => ({}),
+}));
+
+const SLASH_HREF = buildSkillMentionHref("skill-1", "deploy");
+
+vi.mock("../../context/EditorAutocompleteContext", () => ({
+ useEditorAutocomplete: () => ({
+ slashCommands: [
+ {
+ id: "skill:skill-1",
+ kind: "skill",
+ skillId: "skill-1",
+ key: "deploy",
+ name: "Deploy",
+ slug: "deploy",
+ description: null,
+ href: SLASH_HREF,
+ aliases: ["deploy", "Deploy"],
+ },
+ ],
+ }),
+}));
+
let container: HTMLDivElement;
let root: Root | null = null;
+let originalRangeRect: typeof Range.prototype.getBoundingClientRect;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
- // jsdom has no object-URL support; the composer uses it for image previews.
- URL.createObjectURL = vi.fn(() => "blob:mock-preview");
- URL.revokeObjectURL = vi.fn();
+ mdxEditorMockState.imagePluginOptions = null;
+ // jsdom ranges have zero-size rects; the mention menu measures the caret.
+ originalRangeRect = Range.prototype.getBoundingClientRect;
+ Range.prototype.getBoundingClientRect = () => ({
+ x: 32, y: 24, width: 12, height: 18, top: 24, right: 44, bottom: 42, left: 32,
+ toJSON: () => ({}),
+ });
});
afterEach(() => {
flushSync(() => root?.unmount());
root = null;
container.remove();
+ Range.prototype.getBoundingClientRect = originalRangeRect;
+ window.getSelection()?.removeAllRanges();
});
function render(ui: ReactElement) {
flushSync(() => root!.render(ui));
}
-function setTextareaValue(textarea: HTMLTextAreaElement, value: string) {
- const nativeSetter = Object.getOwnPropertyDescriptor(
- window.HTMLTextAreaElement.prototype,
- "value",
- )!.set!;
+async function flushAsync() {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+}
+
+function editable() {
+ return container.querySelector<HTMLDivElement>('[data-testid="mdx-editor"]')!;
+}
+
+function sendButton() {
+ return container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-send"]')!;
+}
+
+/** Simulate typing: set the contenteditable's text and fire an input event. */
+function typeText(value: string) {
+ const el = editable();
flushSync(() => {
- nativeSetter.call(textarea, value);
- textarea.dispatchEvent(new Event("input", { bubbles: true }));
+ el.textContent = value;
+ el.dispatchEvent(new Event("input", { bubbles: true }));
});
}
-function pressEnter(
- textarea: HTMLTextAreaElement,
+function pressKey(
+ key: string,
modifiers: { metaKey?: boolean; ctrlKey?: boolean; shiftKey?: boolean } = {},
) {
flushSync(() => {
- textarea.dispatchEvent(
- new KeyboardEvent("keydown", { key: "Enter", ...modifiers, bubbles: true, cancelable: true }),
+ editable().dispatchEvent(
+ new KeyboardEvent("keydown", { key, ...modifiers, bubbles: true, cancelable: true }),
);
});
}
-function pressCmdEnter(textarea: HTMLTextAreaElement) {
- pressEnter(textarea, { metaKey: true });
-}
-
-async function flushAsync() {
- await new Promise((resolve) => setTimeout(resolve, 0));
+function pasteFiles(files: File[]) {
+ const paste = new Event("paste", { bubbles: true, cancelable: true });
+ Object.defineProperty(paste, "clipboardData", { value: { files, types: ["Files"] } });
+ flushSync(() => {
+ editable().dispatchEvent(paste);
+ });
+ return paste;
}
-function input() {
- return container.querySelector<HTMLTextAreaElement>('[data-testid="task-chat-composer-input"]')!;
+/** Place the caret at the end of the editable's first text node and announce it. */
+async function placeCaretAtEnd() {
+ const textNode = editable().firstChild;
+ expect(textNode?.nodeType).toBe(Node.TEXT_NODE);
+ const selection = window.getSelection();
+ const range = document.createRange();
+ range.setStart(textNode!, textNode!.textContent!.length);
+ range.collapse(true);
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+ flushSync(() => {
+ document.dispatchEvent(new Event("selectionchange"));
+ });
+ // Mention detection defers via requestAnimationFrame after input events.
+ await flushAsync();
+ await flushAsync();
}
-function sendButton() {
- return container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-send"]')!;
+function autocompleteOption(matchText: string) {
+ const menu = document.body.querySelector('[data-testid="mention-autocomplete-menu"]');
+ expect(menu).toBeTruthy();
+ const option = Array.from(menu!.querySelectorAll<HTMLButtonElement>('button[type="button"]'))
+ .find((node) => node.textContent?.includes(matchText));
+ expect(option).toBeTruthy();
+ return option!;
}
describe("TaskChatComposer", () => {
@@ -72,38 +247,38 @@ describe("TaskChatComposer", () => {
render(<TaskChatComposer onAdd={onAdd} workMode="standard" />);
expect(sendButton().disabled).toBe(true);
- setTextareaValue(input(), " hello there ");
+ typeText(" hello there ");
expect(sendButton().disabled).toBe(false);
- pressCmdEnter(input());
+ pressKey("Enter", { metaKey: true });
await flushAsync();
expect(onAdd).toHaveBeenCalledWith("hello there", undefined, undefined);
- expect(input().value).toBe("");
+ expect(editable().textContent).toBe("");
});
it("submits on Ctrl+Enter", async () => {
const onAdd = vi.fn().mockResolvedValue(undefined);
render(<TaskChatComposer onAdd={onAdd} workMode="standard" />);
- setTextareaValue(input(), "hello");
- pressEnter(input(), { ctrlKey: true });
+ typeText("hello");
+ pressKey("Enter", { ctrlKey: true });
await flushAsync();
expect(onAdd).toHaveBeenCalledWith("hello", undefined, undefined);
});
- it("does not submit on plain Enter or Shift+Enter (newline stays in the draft)", async () => {
+ it("does not submit on plain Enter or Shift+Enter (newline stays with the editor)", async () => {
const onAdd = vi.fn().mockResolvedValue(undefined);
render(<TaskChatComposer onAdd={onAdd} workMode="standard" />);
- setTextareaValue(input(), "line one");
- pressEnter(input());
- pressEnter(input(), { shiftKey: true });
+ typeText("line one");
+ pressKey("Enter");
+ pressKey("Enter", { shiftKey: true });
await flushAsync();
expect(onAdd).not.toHaveBeenCalled();
- expect(input().value).toBe("line one");
+ expect(editable().textContent).toBe("line one");
});
it("cycles the pending mode with Shift+Tab and applies it on submit", async () => {
@@ -117,16 +292,12 @@ describe("TaskChatComposer", () => {
expect(chip.getAttribute("data-pending-work-mode")).toBe("standard");
expect(chip.textContent).toContain("Agent");
- flushSync(() => {
- input().dispatchEvent(
- new KeyboardEvent("keydown", { key: "Tab", shiftKey: true, bubbles: true, cancelable: true }),
- );
- });
+ pressKey("Tab", { shiftKey: true });
expect(chip.getAttribute("data-pending-work-mode")).toBe("planning");
expect(chip.textContent).toContain("Plan");
- setTextareaValue(input(), "do the plan");
- pressCmdEnter(input());
+ typeText("do the plan");
+ pressKey("Enter", { metaKey: true });
await flushAsync();
expect(onWorkModeChange).toHaveBeenCalledWith("planning");
@@ -144,8 +315,8 @@ describe("TaskChatComposer", () => {
/>,
);
- setTextareaValue(input(), "wake up");
- pressCmdEnter(input());
+ typeText("wake up");
+ pressKey("Enter", { metaKey: true });
await flushAsync();
expect(onAdd).toHaveBeenCalledWith("wake up", true, undefined);
@@ -165,51 +336,173 @@ describe("TaskChatComposer", () => {
expect(container.querySelector('[data-testid="task-chat-composer-attach"]')).not.toBeNull();
});
- it("uploads pasted files via onAttachImage and inserts the reference into the draft", async () => {
+ it("wires the editor's inline image upload to onAttachImage and returns the attachment URL", async () => {
const onAttachImage = vi.fn().mockResolvedValue({
contentPath: "/attachments/shot.png",
originalFilename: "shot.png",
});
render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" onAttachImage={onAttachImage} />);
+ const handler = mdxEditorMockState.imagePluginOptions?.imageUploadHandler;
+ expect(handler).toBeTypeOf("function");
+
const file = new File(["png-bytes"], "shot.png", { type: "image/png" });
- const paste = new Event("paste", { bubbles: true, cancelable: true });
- Object.defineProperty(paste, "clipboardData", { value: { files: [file] } });
- flushSync(() => {
- input().dispatchEvent(paste);
+ await expect(handler!(file)).resolves.toBe("/attachments/shot.png");
+ expect(onAttachImage).toHaveBeenCalledWith(file);
+ // Inline images do not go through the attachment chip row.
+ expect(container.querySelector('[data-testid="task-chat-composer-attachments"]')).toBeNull();
+ });
+
+ it("does not register the image plugin without an upload handler", () => {
+ render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" />);
+ expect(mdxEditorMockState.imagePluginOptions).toBeNull();
+ });
+
+ it("attaches pasted non-image files to the chip row and posts a link reference", async () => {
+ const onAdd = vi.fn().mockResolvedValue(undefined);
+ const onAttachImage = vi.fn().mockResolvedValue({
+ contentPath: "/attachments/notes.txt",
+ originalFilename: "notes.txt",
});
+ render(<TaskChatComposer onAdd={onAdd} workMode="standard" onAttachImage={onAttachImage} />);
+
+ const file = new File(["plain"], "notes.txt", { type: "text/plain" });
+ const paste = pasteFiles([file]);
await flushAsync();
+ // The all-non-image paste is swallowed before the editor sees it.
+ expect(paste.defaultPrevented).toBe(true);
expect(onAttachImage).toHaveBeenCalledWith(file);
- expect(input().value).toContain("![shot.png](/attachments/shot.png)");
const chips = container.querySelector('[data-testid="task-chat-composer-attachments"]');
- expect(chips?.textContent).toContain("shot.png");
+ expect(chips?.textContent).toContain("notes.txt");
+ // base/attachment chip: kind · size description and a settled state.
+ expect(chips?.textContent).toContain("Text · 5 B");
+ expect(chips?.querySelector('[data-slot="attachment"]')?.getAttribute("data-state")).toBe("done");
+
+ // The editor stays prose-only; the reference rides along at submit time,
+ // and an attached chip alone is enough to enable send.
+ expect(editable().textContent ?? "").not.toContain("notes.txt");
+ const send = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-send"]')!;
+ expect(send.disabled).toBe(false);
+ flushSync(() => send.click());
+ await flushAsync();
+ expect(onAdd).toHaveBeenCalledWith(
+ "[notes.txt](/attachments/notes.txt)",
+ undefined,
+ undefined,
+ );
+ // Chips clear once the message posts.
+ expect(container.querySelector('[data-testid="task-chat-composer-attachments"]')).toBeNull();
});
- it("shows an object-URL thumbnail for a pasted image attachment", async () => {
+ it("appends file references after typed prose on submit", async () => {
+ const onAdd = vi.fn().mockResolvedValue(undefined);
const onAttachImage = vi.fn().mockResolvedValue({
- contentPath: "/attachments/shot.png",
- originalFilename: "shot.png",
+ contentPath: "/attachments/notes.txt",
+ originalFilename: "notes.txt",
});
- render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" onAttachImage={onAttachImage} />);
+ render(<TaskChatComposer onAdd={onAdd} workMode="standard" onAttachImage={onAttachImage} />);
- const file = new File(["png-bytes"], "shot.png", { type: "image/png" });
- const paste = new Event("paste", { bubbles: true, cancelable: true });
- Object.defineProperty(paste, "clipboardData", { value: { files: [file] } });
- flushSync(() => {
- input().dispatchEvent(paste);
- });
+ typeText("Please review this.");
+ pasteFiles([new File(["plain"], "notes.txt", { type: "text/plain" })]);
+ await flushAsync();
+
+ const send = container.querySelector<HTMLButtonElement>('[data-testid="task-chat-composer-send"]')!;
+ flushSync(() => send.click());
+ await flushAsync();
+ expect(onAdd).toHaveBeenCalledWith(
+ "Please review this.\n\n[notes.txt](/attachments/notes.txt)",
+ undefined,
+ undefined,
+ );
+ });
+
+ it("blocks send while a file upload is pending, then includes the file once it lands", async () => {
+ const onAdd = vi.fn().mockResolvedValue(undefined);
+ let resolveUpload!: (value: { contentPath: string; originalFilename: string }) => void;
+ const onAttachImage = vi.fn().mockReturnValue(
+ new Promise<{ contentPath: string; originalFilename: string }>((resolve) => {
+ resolveUpload = resolve;
+ }),
+ );
+ render(<TaskChatComposer onAdd={onAdd} workMode="standard" onAttachImage={onAttachImage} />);
+
+ typeText("Here is the file.");
+ pasteFiles([new File(["plain"], "notes.txt", { type: "text/plain" })]);
+ await flushAsync();
+
+ // Text alone would enable send, but the in-flight upload must hold it —
+ // otherwise the comment posts without the file the user selected.
+ expect(sendButton().disabled).toBe(true);
+ pressKey("Enter", { metaKey: true });
await flushAsync();
+ expect(onAdd).not.toHaveBeenCalled();
- expect(URL.createObjectURL).toHaveBeenCalledWith(file);
- const thumb = container.querySelector<HTMLImageElement>(
- '[data-testid="task-chat-composer-attachments"] img',
+ resolveUpload({ contentPath: "/attachments/notes.txt", originalFilename: "notes.txt" });
+ await flushAsync();
+ expect(sendButton().disabled).toBe(false);
+ flushSync(() => sendButton().click());
+ await flushAsync();
+ expect(onAdd).toHaveBeenCalledWith(
+ "Here is the file.\n\n[notes.txt](/attachments/notes.txt)",
+ undefined,
+ undefined,
);
- expect(thumb?.src).toBe("blob:mock-preview");
- expect(thumb?.alt).toBe("");
});
- it("renders no thumbnail for non-image attachments and revokes previews on unmount", async () => {
+ it("blocks send while a failed attachment chip remains, then sends after it is removed", async () => {
+ const onAdd = vi.fn().mockResolvedValue(undefined);
+ const onAttachImage = vi.fn().mockRejectedValue(new Error("Too large"));
+ render(<TaskChatComposer onAdd={onAdd} workMode="standard" onAttachImage={onAttachImage} />);
+
+ typeText("Here is the file.");
+ pasteFiles([new File(["plain"], "notes.txt", { type: "text/plain" })]);
+ await flushAsync();
+
+ // Text alone would enable send, but the failed chip must hold it —
+ // otherwise the comment posts without the file and the error chip clears.
+ expect(sendButton().disabled).toBe(true);
+ pressKey("Enter", { metaKey: true });
+ await flushAsync();
+ expect(onAdd).not.toHaveBeenCalled();
+
+ const remove = container.querySelector<HTMLButtonElement>('button[aria-label="Remove notes.txt"]');
+ flushSync(() => remove!.click());
+ expect(sendButton().disabled).toBe(false);
+ flushSync(() => sendButton().click());
+ await flushAsync();
+ expect(onAdd).toHaveBeenCalledWith("Here is the file.", undefined, undefined);
+ });
+
+ it("removes an attachment chip via its remove button", async () => {
+ const onAttachImage = vi.fn().mockResolvedValue({
+ contentPath: "/attachments/notes.txt",
+ originalFilename: "notes.txt",
+ });
+ render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" onAttachImage={onAttachImage} />);
+
+ pasteFiles([new File(["plain"], "notes.txt", { type: "text/plain" })]);
+ await flushAsync();
+
+ const remove = container.querySelector<HTMLButtonElement>('button[aria-label="Remove notes.txt"]');
+ expect(remove).not.toBeNull();
+ flushSync(() => remove!.click());
+ expect(container.querySelector('[data-testid="task-chat-composer-attachments"]')).toBeNull();
+ });
+
+ it("shows an error-state chip when a non-image upload fails", async () => {
+ const onAttachImage = vi.fn().mockRejectedValue(new Error("Too large"));
+ render(<TaskChatComposer onAdd={vi.fn()} workMode="standard" onAttachImage={onAttachImage} />);
+
+ pasteFiles([new File(["plain"], "notes.txt", { type: "text/plain" })]);
+ await flushAsync();
+
+ const chips = container.querySelector('[data-testid="task-chat-composer-attachments"]');
+ expect(chips?.querySelector('[data-slot="attachment"]')?.getAttribute("data-state")).toBe("error");
+ expect(chips?.textContent).toContain("Too large");
+ });
+
+ it("leaves pasted images to the editor's image plugin (no chip, paste not swallowed)", async () => {
const onAttachImage = vi.fn().mockResolvedValue({
contentPath: "/attachments/notes.txt",
originalFilename: "notes.txt",
@@ -218,22 +511,59 @@ describe("TaskChatComposer", () => {
const image = new File(["png-bytes"], "shot.png", { type: "image/png" });
const text = new File(["plain"], "notes.txt", { type: "text/plain" });
- const paste = new Event("paste", { bubbles: true, cancelable: true });
- Object.defineProperty(paste, "clipboardData", { value: { files: [image, text] } });
- flushSync(() => {
- input().dispatchEvent(paste);
- });
+ const paste = pasteFiles([image, text]);
await flushAsync();
- // Only the image chip carries a thumbnail; the text chip stays text-only.
+ // Mixed paste: the non-image is chipped, the image flows through untouched.
+ expect(paste.defaultPrevented).toBe(false);
const chips = container.querySelector('[data-testid="task-chat-composer-attachments"]')!;
expect(chips.textContent).toContain("notes.txt");
- expect(chips.querySelectorAll("img")).toHaveLength(1);
- expect(URL.createObjectURL).toHaveBeenCalledTimes(1);
+ expect(chips.textContent).not.toContain("shot.png");
+ expect(onAttachImage).toHaveBeenCalledTimes(1);
+ expect(onAttachImage).toHaveBeenCalledWith(text);
+ });
+
+ it("inserts an @-mention from the autocomplete menu and posts it", async () => {
+ const onAdd = vi.fn().mockResolvedValue(undefined);
+ render(
+ <TaskChatComposer
+ onAdd={onAdd}
+ workMode="standard"
+ mentions={[{ id: "agent:a1", kind: "agent", name: "Clippy", agentId: "a1" }]}
+ />,
+ );
+
+ typeText("@Cl");
+ await placeCaretAtEnd();
+
+ const option = autocompleteOption("Clippy");
+ flushSync(() => {
+ option.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));
+ });
+ await flushAsync();
+
+ const expected = `[@Clippy](${buildAgentMentionHref("a1", null)}) `;
+ expect(editable().textContent).toBe(expected);
+
+ pressKey("Enter", { metaKey: true });
+ await flushAsync();
+ expect(onAdd).toHaveBeenCalledWith(expected.trim(), undefined, undefined);
+ });
+
+ it("inserts a /-command from the autocomplete menu", async () => {
+ const onAdd = vi.fn().mockResolvedValue(undefined);
+ render(<TaskChatComposer onAdd={onAdd} workMode="standard" />);
+
+ typeText("/dep");
+ await placeCaretAtEnd();
+
+ const option = autocompleteOption("/deploy");
+ flushSync(() => {
+ option.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));
+ });
+ await flushAsync();
- flushSync(() => root!.unmount());
- root = null;
- expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:mock-preview");
+ expect(editable().textContent).toBe(`[/deploy](${SLASH_HREF}) `);
});
it("shows the assignee combobox only when reassign is enabled, with the current label", () => {
diff --git a/ui/src/components/task-chat/TaskChatComposer.tsx b/ui/src/components/task-chat/TaskChatComposer.tsx
index 58c1c2a1d7..5c7cca635b 100644
--- a/ui/src/components/task-chat/TaskChatComposer.tsx
+++ b/ui/src/components/task-chat/TaskChatComposer.tsx
@@ -1,22 +1,33 @@
import {
- useEffect,
useRef,
useState,
type ChangeEvent,
type ClipboardEvent as ReactClipboardEvent,
type CSSProperties,
- type DragEvent as ReactDragEvent,
} from "react";
import { cn } from "@/lib/utils";
-import { AlertTriangle, ArrowUp, Check, ChevronDown, Loader2, Plus } from "lucide-react";
+import { ArrowUp, Check, ChevronDown, Loader2, Plus, X } from "lucide-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+import {
+ Attachment,
+ AttachmentAction,
+ AttachmentActions,
+ AttachmentContent,
+ AttachmentDescription,
+ AttachmentGroup,
+ AttachmentMedia,
+ AttachmentTitle,
+} from "@/components/ui/attachment";
+import { fileKindForName, formatFileSize } from "./task-chat-attachments";
+import { MarkdownEditor, type MarkdownEditorRef } from "@/components/MarkdownEditor";
import { nextWorkMode, workModeMetaFor, workModeMetaList } from "@/lib/work-mode-meta";
import type { InlineEntityOption } from "@/components/InlineEntitySelector";
+import type { MentionOption } from "@/components/MarkdownEditor";
import type { IssueAttachment, IssueWorkMode } from "@paperclipai/shared";
/** Structurally identical to IssueChatThread's module-private CommentReassignment. */
@@ -36,10 +47,14 @@ interface TaskChatComposerProps {
onAttachImage?: (file: File) => Promise<IssueAttachment | void>;
/** Fallback upload path: returns a URL for inline image markdown. */
onImageUpload?: (file: File) => Promise<string>;
+ /** Mentionable entities for the editor's @-autocomplete. */
+ mentions?: MentionOption[];
enableReassign?: boolean;
reassignOptions?: InlineEntityOption[];
currentAssigneeValue?: string;
issueStatus?: string;
+ /** Mobile document-flow host: 16px editor text so iOS doesn't zoom on focus. */
+ mobile?: boolean;
}
/** Per-mode hue token (see ui/src/index.css `--tc-mode-*`). */
@@ -74,11 +89,11 @@ function modePlaceholder(mode: IssueWorkMode, agentName: string): string {
type ComposerAttachment = {
id: string;
name: string;
+ size?: number;
status: "uploading" | "attached" | "error";
error?: string;
- /** Object URL for an immediate thumbnail while (and after) uploading. */
- previewUrl?: string;
- isImage?: boolean;
+ /** Set once uploaded; the submit path appends `[name](contentPath)` lines. */
+ contentPath?: string;
};
/** Local duplicate of IssueChatThread's module-private helper (same rule). */
@@ -99,17 +114,22 @@ function parseAssigneeValue(value: string): CommentReassignment | undefined {
return undefined;
}
-function hasFilePayload(evt: ReactDragEvent<HTMLDivElement>) {
- return Array.from(evt.dataTransfer?.types ?? []).includes("Files");
+function escapeMarkdownLabel(name: string): string {
+ return name.replace(/[[\]]/g, "\\$&");
}
/**
- * Composer for the redesigned thread (v7 spec): textarea over a 32px comp-bar
- * of [attach] [mode chip] … [assignee] [send]. The mode chip is a status-chip
- * rectangle carrying the pending mode's hue; the composer chrome itself stays
- * neutral. Shift+Tab cycles modes; the picked mode is applied on submit.
- * Attachments upload via `onAttachImage` (or the inline `onImageUpload`
- * fallback) from the + button, paste, or drag-drop.
+ * Composer for the redesigned thread (v7 spec): the shared MarkdownEditor
+ * (rich lists, @-mentions, /-commands, inline pasted images) over a 32px
+ * comp-bar of [attach] [mode chip] … [assignee] [send]. The mode chip is a
+ * status-chip rectangle carrying the pending mode's hue; the composer chrome
+ * itself stays neutral. Shift+Tab cycles modes (captured before Lexical);
+ * Cmd/Ctrl+Enter posts via the editor's native onSubmit; plain Enter stays a
+ * newline / next list item. Pasted or dropped images upload through
+ * `onAttachImage` (or the `onImageUpload` fallback) and land inline at the
+ * caret via the editor's image plugin; non-image files render as shadcn
+ * base/attachment chips (kind icon · name · size, remove ×, uploading/error
+ * states) between the editor and the comp-bar.
*/
export function TaskChatComposer({
onAdd,
@@ -120,36 +140,22 @@ export function TaskChatComposer({
placeholder,
onAttachImage,
onImageUpload,
+ mentions,
enableReassign = false,
reassignOptions,
currentAssigneeValue = "",
issueStatus,
+ mobile = false,
}: TaskChatComposerProps) {
const [body, setBody] = useState("");
const [submitting, setSubmitting] = useState(false);
const [pendingMode, setPendingMode] = useState<IssueWorkMode>(workMode);
const [pendingAssignee, setPendingAssignee] = useState<string | null>(null);
const [attachments, setAttachments] = useState<ComposerAttachment[]>([]);
- const [isDragOver, setIsDragOver] = useState(false);
- const dragDepthRef = useRef(0);
const fileInputRef = useRef<HTMLInputElement | null>(null);
- const previewUrlsRef = useRef<Set<string>>(new Set());
-
- // Object URLs created for image previews must be revoked or they leak the
- // underlying blobs for the page's lifetime.
- useEffect(() => {
- const urls = previewUrlsRef.current;
- return () => {
- for (const url of urls) URL.revokeObjectURL(url);
- urls.clear();
- };
- }, []);
-
- function releasePreview(url: string | undefined) {
- if (!url) return;
- URL.revokeObjectURL(url);
- previewUrlsRef.current.delete(url);
- }
+ const editorRef = useRef<MarkdownEditorRef>(null);
+ const bodyRef = useRef(body);
+ bodyRef.current = body;
const modeMeta = workModeMetaFor(pendingMode);
const canAcceptFiles = Boolean(onAttachImage || onImageUpload);
@@ -160,40 +166,23 @@ export function TaskChatComposer({
const assigneeName = assigneeLabel === "Unassigned" ? "the agent" : assigneeLabel;
const effectivePlaceholder = placeholder ?? modePlaceholder(pendingMode, assigneeName);
- function insertReference(name: string, url: string, asImage: boolean) {
- const safeName = name.replace(/[[\]]/g, "\\$&");
- const markdown = asImage ? `![${safeName}](${url})` : `[${safeName}](${url})`;
- setBody((prev) => (prev ? `${prev}\n\n${markdown}` : markdown));
+ /** Upload an image and return its URL for inline `![](src)` markdown. */
+ async function uploadInlineImage(file: File): Promise<string> {
+ if (onAttachImage) {
+ const attachment = await onAttachImage(file);
+ if (attachment?.contentPath) return attachment.contentPath;
+ throw new Error("Upload did not return a file URL");
+ }
+ if (onImageUpload) return onImageUpload(file);
+ throw new Error("This file type cannot be attached here");
}
- async function attachFile(file: File) {
+ /** Non-image files: attach to the task and track in the chip row. */
+ async function attachNonImageFile(file: File) {
const id = `${file.name}:${file.size}:${file.lastModified}:${Math.random().toString(36).slice(2)}`;
- const isImage = file.type.startsWith("image/");
- // Create the preview up front so the thumbnail appears while uploading.
- const previewUrl =
- isImage && typeof URL.createObjectURL === "function" ? URL.createObjectURL(file) : undefined;
- if (previewUrl) previewUrlsRef.current.add(previewUrl);
- setAttachments((prev) => [
- ...prev,
- { id, name: file.name, status: "uploading", previewUrl, isImage: isImage || undefined },
- ]);
+ setAttachments((prev) => [...prev, { id, name: file.name, size: file.size, status: "uploading" }]);
try {
- if (onAttachImage) {
- const attachment = await onAttachImage(file);
- const name = attachment?.originalFilename ?? file.name;
- if (attachment?.contentPath) {
- insertReference(name, attachment.contentPath, file.type.startsWith("image/"));
- }
- setAttachments((prev) =>
- prev.map((item) => (item.id === id ? { ...item, name, status: "attached" } : item)),
- );
- } else if (onImageUpload && file.type.startsWith("image/")) {
- const url = await onImageUpload(file);
- insertReference(file.name, url, true);
- setAttachments((prev) =>
- prev.map((item) => (item.id === id ? { ...item, status: "attached" } : item)),
- );
- } else {
+ if (!onAttachImage) {
setAttachments((prev) =>
prev.map((item) =>
item.id === id
@@ -201,7 +190,17 @@ export function TaskChatComposer({
: item,
),
);
+ return;
}
+ const attachment = await onAttachImage(file);
+ const name = attachment?.originalFilename ?? file.name;
+ setAttachments((prev) =>
+ prev.map((item) =>
+ item.id === id
+ ? { ...item, name, status: "attached", contentPath: attachment?.contentPath }
+ : item,
+ ),
+ );
} catch (err) {
setAttachments((prev) =>
prev.map((item) =>
@@ -213,59 +212,86 @@ export function TaskChatComposer({
}
}
- async function attachFiles(files: Iterable<File>) {
- for (const file of files) {
- await attachFile(file);
+ /** Images picked from the + button go inline at the caret, like paste/drop. */
+ async function attachPickedFile(file: File) {
+ if (!file.type.startsWith("image/")) {
+ await attachNonImageFile(file);
+ return;
+ }
+ const id = `${file.name}:${file.size}:${file.lastModified}:${Math.random().toString(36).slice(2)}`;
+ try {
+ const url = await uploadInlineImage(file);
+ editorRef.current?.insertMarkdown(`![${escapeMarkdownLabel(file.name)}](${url})`);
+ } catch (err) {
+ setAttachments((prev) => [
+ ...prev,
+ {
+ id,
+ name: file.name,
+ size: file.size,
+ status: "error",
+ error: err instanceof Error ? err.message : "Upload failed",
+ },
+ ]);
}
}
function handleFileInputChange(evt: ChangeEvent<HTMLInputElement>) {
const files = evt.target.files;
- if (files && files.length > 0) void attachFiles(Array.from(files));
+ if (files && files.length > 0) {
+ void (async () => {
+ for (const file of Array.from(files)) await attachPickedFile(file);
+ })();
+ }
evt.target.value = "";
}
- function handlePaste(evt: ReactClipboardEvent<HTMLTextAreaElement>) {
+ /**
+ * Pasted image files fall through to the editor's image plugin (inline at
+ * the caret); non-image files are attached to the task here. Only swallow
+ * the paste when it carries no images the plugin should handle.
+ */
+ function handlePasteCapture(evt: ReactClipboardEvent<HTMLDivElement>) {
if (!canAcceptFiles) return;
const files = Array.from(evt.clipboardData?.files ?? []);
if (files.length === 0) return;
- evt.preventDefault();
- void attachFiles(files);
- }
-
- function handleFileDragEnter(evt: ReactDragEvent<HTMLDivElement>) {
- if (!canAcceptFiles || !hasFilePayload(evt)) return;
- evt.preventDefault();
- dragDepthRef.current += 1;
- setIsDragOver(true);
- }
-
- function handleFileDragOver(evt: ReactDragEvent<HTMLDivElement>) {
- if (!canAcceptFiles || !hasFilePayload(evt)) return;
- evt.preventDefault();
- evt.dataTransfer.dropEffect = "copy";
- }
-
- function handleFileDragLeave(evt: ReactDragEvent<HTMLDivElement>) {
- if (!canAcceptFiles || !hasFilePayload(evt)) return;
- evt.preventDefault();
- dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
- if (dragDepthRef.current === 0) setIsDragOver(false);
+ const nonImages = files.filter((file) => !file.type.startsWith("image/"));
+ if (nonImages.length === 0) return;
+ if (nonImages.length === files.length) {
+ evt.preventDefault();
+ evt.stopPropagation();
+ }
+ void (async () => {
+ for (const file of nonImages) await attachNonImageFile(file);
+ })();
}
- function handleFileDrop(evt: ReactDragEvent<HTMLDivElement>) {
- if (!canAcceptFiles || !hasFilePayload(evt)) return;
- evt.preventDefault();
- dragDepthRef.current = 0;
- setIsDragOver(false);
- const files = evt.dataTransfer?.files;
- if (files && files.length > 0) void attachFiles(Array.from(files));
- }
+ // Uploaded file references ride along as trailing `[name](contentPath)`
+ // lines — the bubble renderer folds those link-only lines back into chips.
+ const attachedRefs = attachments.filter(
+ (item) => item.status === "attached" && item.contentPath,
+ );
+ // Sending mid-upload would silently drop the pending file from the comment;
+ // sending past a failed chip would discard the file the user selected and
+ // clear its error state, so both hold submission until resolved or removed.
+ const uploadPending = attachments.some((item) => item.status === "uploading");
+ const uploadFailed = attachments.some((item) => item.status === "error");
async function submit() {
- const trimmed = body.trim();
- if (!trimmed || submitting || disabled) return;
-
+ const trimmed = bodyRef.current.trim();
+ if (
+ (!trimmed && attachedRefs.length === 0) ||
+ uploadPending ||
+ uploadFailed ||
+ submitting ||
+ disabled
+ )
+ return;
+
+ const refLines = attachedRefs
+ .map((item) => `[${escapeMarkdownLabel(item.name)}](${item.contentPath})`)
+ .join("\n");
+ const fullBody = [trimmed, refLines].filter(Boolean).join("\n\n");
const hasReassignment = showAssignee && assigneeValue !== currentAssigneeValue;
const reassignment = hasReassignment ? parseAssigneeValue(assigneeValue) : undefined;
const reopen = shouldImplicitlyReopenComment(issueStatus, assigneeValue) ? true : undefined;
@@ -276,14 +302,11 @@ export function TaskChatComposer({
if (pendingMode !== workMode && onWorkModeChange) {
await onWorkModeChange(pendingMode);
}
- await onAdd(trimmed, reopen, reassignment);
- setAttachments((prev) => {
- for (const item of prev) releasePreview(item.previewUrl);
- return [];
- });
+ await onAdd(fullBody, reopen, reassignment);
+ setAttachments([]);
setPendingAssignee(null);
} catch {
- setBody(trimmed); // restore on failure
+ setBody(trimmed); // restore on failure (chips stay for retry)
} finally {
setSubmitting(false);
}
@@ -293,75 +316,89 @@ export function TaskChatComposer({
<div
className={cn(
"rounded-xl border border-input bg-card p-2 shadow-(--shadow-extract-7) transition-[border-color,box-shadow] focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/15",
- isDragOver && "ring-2 ring-primary/40",
)}
- onDragEnter={handleFileDragEnter}
- onDragOver={handleFileDragOver}
- onDragLeave={handleFileDragLeave}
- onDrop={handleFileDrop}
+ onKeyDownCapture={(e) => {
+ // Shift+Tab cycles the pending mode; captured on the wrapper so it
+ // wins over Lexical's list-outdent binding inside the editor.
+ if (disabled) return;
+ if (e.key === "Tab" && e.shiftKey) {
+ e.preventDefault();
+ e.stopPropagation();
+ setPendingMode((mode) => nextWorkMode(mode));
+ }
+ }}
+ onPasteCapture={handlePasteCapture}
>
- <textarea
- value={body}
- onChange={(e) => setBody(e.target.value)}
- onKeyDown={(e) => {
- // Cmd/Ctrl+Enter posts; plain Enter inserts a newline (Enter alone
- // was too easy to trip while drafting).
- if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
- e.preventDefault();
- void submit();
- return;
+ <div data-testid="task-chat-composer-input">
+ <MarkdownEditor
+ ref={editorRef}
+ value={body}
+ onChange={setBody}
+ placeholder={disabled ? (disabledReason ?? "Composer disabled") : effectivePlaceholder}
+ readOnly={disabled}
+ mentions={mentions}
+ onSubmit={() => void submit()}
+ imageUploadHandler={canAcceptFiles ? uploadInlineImage : undefined}
+ onDropFile={canAcceptFiles ? attachNonImageFile : undefined}
+ bordered={false}
+ className={cn(disabled && "opacity-60")}
+ contentClassName={
+ mobile
+ ? "max-h-(--sz-28dvh) min-h-(--sz-48px) overflow-y-auto px-1 py-1 text-base scrollbar-auto-hide"
+ : "max-h-(--sz-28dvh) min-h-(--sz-48px) overflow-y-auto px-1 py-1 text-sm scrollbar-auto-hide"
}
- if (e.key === "Tab" && e.shiftKey) {
- e.preventDefault();
- setPendingMode((mode) => nextWorkMode(mode));
- }
- }}
- onPaste={handlePaste}
- disabled={disabled}
- placeholder={disabled ? (disabledReason ?? "Composer disabled") : effectivePlaceholder}
- rows={2}
- className="w-full resize-none bg-transparent px-1 py-1 text-sm outline-none placeholder:text-muted-foreground disabled:opacity-60"
- data-testid="task-chat-composer-input"
- />
+ />
+ </div>
{attachments.length > 0 ? (
- <div className="mb-1 flex flex-wrap gap-1 px-1" data-testid="task-chat-composer-attachments">
- {attachments.map((attachment) => (
- <span
- key={attachment.id}
- className={cn(
- "inline-flex min-w-0 items-center gap-1 rounded-md border px-2 py-0.5 text-xs",
- attachment.status === "error"
- ? "border-destructive/50 bg-destructive/10 text-destructive"
- : "border-border bg-muted/30 text-muted-foreground",
- )}
- >
- {attachment.isImage && attachment.previewUrl ? (
- <img
- src={attachment.previewUrl}
- alt=""
- className="size-10 shrink-0 rounded object-cover"
- />
- ) : null}
- {attachment.status === "uploading" ? (
- <Loader2 className="h-3 w-3 shrink-0 animate-spin" aria-hidden />
- ) : attachment.status === "error" ? (
- <AlertTriangle className="h-3 w-3 shrink-0" aria-hidden />
- ) : (
- <Check className="h-3 w-3 shrink-0" aria-hidden />
- )}
- <span className="max-w-40 truncate font-medium text-foreground">{attachment.name}</span>
- <span className="shrink-0">
- ·{" "}
- {attachment.status === "uploading"
- ? "Uploading…"
- : attachment.status === "error"
- ? (attachment.error ?? "Upload failed")
- : "Attached"}
- </span>
- </span>
- ))}
- </div>
+ <AttachmentGroup className="mb-1 px-1" data-testid="task-chat-composer-attachments">
+ {attachments.map((attachment) => {
+ const kind = fileKindForName(attachment.name);
+ const KindIcon = kind.icon;
+ const sizeLabel = formatFileSize(attachment.size);
+ return (
+ <Attachment
+ key={attachment.id}
+ size="sm"
+ state={
+ attachment.status === "uploading"
+ ? "uploading"
+ : attachment.status === "error"
+ ? "error"
+ : "done"
+ }
+ >
+ <AttachmentMedia>
+ {attachment.status === "uploading" ? (
+ <Loader2 className="animate-spin" aria-hidden />
+ ) : (
+ <KindIcon aria-hidden />
+ )}
+ </AttachmentMedia>
+ <AttachmentContent>
+ <AttachmentTitle className="max-w-48">{attachment.name}</AttachmentTitle>
+ <AttachmentDescription className="max-w-48">
+ {attachment.status === "uploading"
+ ? "Uploading…"
+ : attachment.status === "error"
+ ? (attachment.error ?? "Upload failed")
+ : [kind.label, sizeLabel].filter(Boolean).join(" · ")}
+ </AttachmentDescription>
+ </AttachmentContent>
+ <AttachmentActions>
+ <AttachmentAction
+ aria-label={`Remove ${attachment.name}`}
+ onClick={() =>
+ setAttachments((prev) => prev.filter((item) => item.id !== attachment.id))
+ }
+ >
+ <X aria-hidden />
+ </AttachmentAction>
+ </AttachmentActions>
+ </Attachment>
+ );
+ })}
+ </AttachmentGroup>
) : null}
<div className="mt-1 flex items-center gap-2">
@@ -370,7 +407,6 @@ export function TaskChatComposer({
<input
ref={fileInputRef}
type="file"
- accept="image/*"
className="hidden"
onChange={handleFileInputChange}
/>
@@ -457,8 +493,20 @@ export function TaskChatComposer({
<button
type="button"
onClick={() => void submit()}
- disabled={disabled || submitting || body.trim().length === 0}
- title="Send (⌘+Enter)"
+ disabled={
+ disabled ||
+ submitting ||
+ uploadPending ||
+ uploadFailed ||
+ (body.trim().length === 0 && attachedRefs.length === 0)
+ }
+ title={
+ uploadPending
+ ? "Waiting for upload to finish"
+ : uploadFailed
+ ? "Remove the failed attachment to send"
+ : "Send (⌘+Enter)"
+ }
aria-label="Send"
className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-primary text-primary-foreground transition-transform hover:scale-105 disabled:scale-100 disabled:bg-muted disabled:text-muted-foreground"
data-testid="task-chat-composer-send"
diff --git a/ui/src/components/task-chat/TaskChatDescriptionBubble.test.tsx b/ui/src/components/task-chat/TaskChatDescriptionBubble.test.tsx
new file mode 100644
index 0000000000..172f8118af
--- /dev/null
+++ b/ui/src/components/task-chat/TaskChatDescriptionBubble.test.tsx
@@ -0,0 +1,187 @@
+// @vitest-environment jsdom
+
+import { act, forwardRef, useImperativeHandle, useRef } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+// Same mock the InlineEditor tests use: the rich markdown editor is not
+// jsdom-renderable; a textarea keeps the InlineEditor edit-mode contract.
+vi.mock("@/components/MarkdownEditor", () => ({
+ MarkdownEditor: forwardRef<
+ { focus: () => void },
+ { value: string; onChange: (value: string) => void }
+ >(function MarkdownEditorMock(props, ref) {
+ const taRef = useRef<HTMLTextAreaElement>(null);
+ useImperativeHandle(ref, () => ({
+ focus: () => taRef.current?.focus(),
+ }));
+ return (
+ <textarea
+ ref={taRef}
+ data-testid="description-md-editor"
+ value={props.value}
+ onChange={(e) => props.onChange(e.target.value)}
+ />
+ );
+ }),
+}));
+
+import { ThemeProvider } from "@/context/ThemeContext";
+import { TaskChatDescriptionBubble, type TaskChatIssueBrief } from "./TaskChatDescriptionBubble";
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+function makeBrief(overrides: Partial<TaskChatIssueBrief> = {}): TaskChatIssueBrief {
+ return {
+ description: "Ship the widget by **Friday**.",
+ author: "human",
+ onSave: () => Promise.resolve(),
+ ...overrides,
+ };
+}
+
+describe("TaskChatDescriptionBubble (PAP-375)", () => {
+ let container: HTMLDivElement;
+ let root: Root | null = null;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => root?.unmount());
+ root = null;
+ container.remove();
+ });
+
+ function render(brief: TaskChatIssueBrief) {
+ act(() =>
+ root!.render(
+ <ThemeProvider>
+ <TaskChatDescriptionBubble brief={brief} />
+ </ThemeProvider>,
+ ),
+ );
+ }
+
+ function click(el: Element | null) {
+ expect(el).not.toBeNull();
+ act(() => {
+ el!.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ }
+
+ it("renders a human-created task as the blue user bubble, right-aligned, without an author header", () => {
+ render(makeBrief({ createdAt: "2026-08-02T14:34:00.000Z" }));
+ const bubble = container.querySelector('[data-testid="task-chat-description-bubble"]');
+ expect(bubble).not.toBeNull();
+ expect(bubble?.getAttribute("data-author")).toBe("human");
+ expect(bubble?.className).toContain("items-end");
+ expect(bubble?.querySelector('[data-testid="task-chat-agent-avatar"]')).toBeNull();
+ const body = bubble?.querySelector(".bg-\\(--liveness-blue\\)");
+ expect(body).not.toBeNull();
+ expect(body?.textContent).toContain("Ship the widget by");
+ // Markdown renders (bold), not raw asterisks.
+ expect(body?.querySelector("strong")?.textContent).toBe("Friday");
+ });
+
+ it("renders an agent-created task as the agent-side bubble with the avatar author header", () => {
+ render(makeBrief({ author: "agent", authorName: "CEO" }));
+ const bubble = container.querySelector('[data-testid="task-chat-description-bubble"]');
+ expect(bubble?.getAttribute("data-author")).toBe("agent");
+ expect(bubble?.className).toContain("items-start");
+ expect(bubble?.querySelector('[data-testid="task-chat-agent-avatar"]')).not.toBeNull();
+ expect(bubble?.textContent).toContain("CEO");
+ expect(bubble?.querySelector(".bg-\\(--bubble-agent\\)")).not.toBeNull();
+ expect(bubble?.querySelector(".bg-\\(--liveness-blue\\)")).toBeNull();
+ });
+
+ it("renders the live description — a new value shows without remount", () => {
+ render(makeBrief());
+ render(makeBrief({ description: "Updated brief." }));
+ expect(container.textContent).toContain("Updated brief.");
+ expect(container.textContent).not.toContain("Ship the widget");
+ });
+
+ it("swaps to the InlineEditor on pencil click and returns to the bubble on Escape", () => {
+ render(makeBrief());
+ click(container.querySelector('[data-testid="task-chat-description-edit"]'));
+
+ const editorWrap = container.querySelector('[data-testid="task-chat-description-editor"]');
+ expect(editorWrap).not.toBeNull();
+ expect(container.querySelector('[data-testid="task-chat-description-bubble"]')).toBeNull();
+ const textarea = editorWrap?.querySelector<HTMLTextAreaElement>(
+ '[data-testid="description-md-editor"]',
+ );
+ // The editor opens immediately (defaultEditing) on the live description.
+ expect(textarea).not.toBeNull();
+ expect(textarea?.value).toBe("Ship the widget by **Friday**.");
+
+ act(() => {
+ textarea!.dispatchEvent(
+ new KeyboardEvent("keydown", { key: "Escape", bubbles: true }),
+ );
+ });
+ expect(container.querySelector('[data-testid="task-chat-description-editor"]')).toBeNull();
+ expect(container.querySelector('[data-testid="task-chat-description-bubble"]')).not.toBeNull();
+ });
+
+ it("renders a muted ghost row for an empty description — never an empty bubble — and opens the editor", () => {
+ render(makeBrief({ description: "" }));
+ expect(container.querySelector('[data-testid="task-chat-description-bubble"]')).toBeNull();
+ const ghost = container.querySelector('[data-testid="task-chat-description-ghost"]');
+ expect(ghost?.textContent).toContain("Add a description");
+
+ click(ghost);
+ expect(container.querySelector('[data-testid="task-chat-description-ghost"]')).toBeNull();
+ expect(
+ container.querySelector('[data-testid="task-chat-description-editor"] [data-testid="description-md-editor"]'),
+ ).not.toBeNull();
+ });
+
+ describe("folding", () => {
+ const scrollHeightDescriptor = Object.getOwnPropertyDescriptor(
+ HTMLElement.prototype,
+ "scrollHeight",
+ );
+
+ afterEach(() => {
+ if (scrollHeightDescriptor) {
+ Object.defineProperty(HTMLElement.prototype, "scrollHeight", scrollHeightDescriptor);
+ } else {
+ delete (HTMLElement.prototype as { scrollHeight?: number }).scrollHeight;
+ }
+ });
+
+ function stubScrollHeight(value: number) {
+ Object.defineProperty(HTMLElement.prototype, "scrollHeight", {
+ configurable: true,
+ get: () => value,
+ });
+ }
+
+ it("folds a long description at the 12-line height with a Show more expander", () => {
+ stubScrollHeight(900);
+ render(makeBrief({ description: Array.from({ length: 40 }, (_, i) => `line ${i}`).join("\n\n") }));
+ const content = container.querySelector<HTMLElement>(".fold-curtain__content");
+ expect(content?.style.maxHeight).toBe("240px");
+ const toggle = [...container.querySelectorAll("button")].find((b) =>
+ b.textContent?.includes("Show more"),
+ );
+ expect(toggle).not.toBeUndefined();
+
+ click(toggle!);
+ expect(container.textContent).toContain("Show less");
+ expect(content?.style.maxHeight).toBe("900px");
+ });
+
+ it("does not fold a short description", () => {
+ stubScrollHeight(120);
+ render(makeBrief());
+ expect(container.textContent).not.toContain("Show more");
+ });
+ });
+});
diff --git a/ui/src/components/task-chat/TaskChatDescriptionBubble.tsx b/ui/src/components/task-chat/TaskChatDescriptionBubble.tsx
new file mode 100644
index 0000000000..025d101f25
--- /dev/null
+++ b/ui/src/components/task-chat/TaskChatDescriptionBubble.tsx
@@ -0,0 +1,171 @@
+import { useState } from "react";
+import { Pencil } from "lucide-react";
+import { cn } from "@/lib/utils";
+import { FoldCurtain } from "@/components/FoldCurtain";
+import { InlineEditor } from "@/components/InlineEditor";
+import { MarkdownBody, type MarkdownExternalReferenceMap } from "@/components/MarkdownBody";
+import { Avatar, AvatarFallback } from "@/components/ui/avatar";
+import { AgentIcon } from "@/components/AgentIconPicker";
+import type { MentionOption } from "@/components/MarkdownEditor";
+import { formatTaskChatTimestamp } from "./task-chat-adapter";
+
+/**
+ * Host binding for the description-as-first-bubble (PAP-375): the LIVE issue
+ * description plus everything the edit surface needs. Carried on the shared
+ * thread props (`issueBrief`); only the redesigned TaskChatThread consumes it.
+ */
+export interface TaskChatIssueBrief {
+ /** LIVE issue.description (never a frozen copy) — empty string when unset. */
+ description: string;
+ /** Originating actor: human-created → blue user bubble, agent-created → agent-side bubble. */
+ author: "human" | "agent";
+ /** Creating agent's name, shown in the agent-side avatar header. */
+ authorName?: string;
+ /** Creating agent's assigned icon (AgentIconName) for the avatar header. */
+ agentIcon?: string | null;
+ /** issue.createdAt — rendered like the other bubbles' footer timestamps. */
+ createdAt?: string | Date;
+ onSave: (description: string) => void | Promise<unknown>;
+ mentions?: MentionOption[];
+ externalReferences?: MarkdownExternalReferenceMap;
+ imageUploadHandler?: (file: File) => Promise<string>;
+ onDropFile?: (file: File) => Promise<void>;
+}
+
+interface TaskChatDescriptionBubbleProps {
+ brief: TaskChatIssueBrief;
+}
+
+/** ~12 text-sm lines (20px line-height) — the accepted fold default (PAP-375). */
+const FOLD_COLLAPSED_HEIGHT_PX = 240;
+
+function initialsForName(name: string) {
+ const parts = name.trim().split(/\s+/);
+ if (parts.length >= 2) {
+ return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
+ }
+ return name.slice(0, 2).toUpperCase();
+}
+
+/**
+ * The task description as the requester's first chat bubble (PAP-375):
+ * human-created tasks get the blue user bubble, agent-created tasks the
+ * agent-side card with the avatar header — same chrome as TaskChatBubble. The
+ * body is the live issue.description; a hover pencil swaps the bubble for the
+ * same InlineEditor the pre-redesign page used (mentions, image paste/drop,
+ * autosave), restoring the edit surface the redesign had gated off. Long
+ * descriptions fold at ~12 lines behind a Show more curtain; an empty
+ * description renders a muted ghost row that opens the editor — never an
+ * empty bubble.
+ */
+export function TaskChatDescriptionBubble({ brief }: TaskChatDescriptionBubbleProps) {
+ const [editing, setEditing] = useState(false);
+ const isHuman = brief.author === "human";
+ const hasDescription = brief.description.trim().length > 0;
+
+ if (editing) {
+ return (
+ <div
+ className="tc-enter-bubble w-full rounded-lg border border-border bg-card px-2 py-1"
+ data-testid="task-chat-description-editor"
+ >
+ <InlineEditor
+ value={brief.description}
+ onSave={brief.onSave}
+ as="p"
+ className="text-sm leading-7 text-foreground"
+ placeholder="Add a description..."
+ multiline
+ defaultEditing
+ onEditingChange={(next) => {
+ if (!next) setEditing(false);
+ }}
+ mentions={brief.mentions}
+ externalReferences={brief.externalReferences}
+ imageUploadHandler={brief.imageUploadHandler}
+ onDropFile={brief.onDropFile}
+ />
+ </div>
+ );
+ }
+
+ if (!hasDescription) {
+ // Accepted default: no fabricated empty bubble — a muted ghost affordance.
+ return (
+ <button
+ type="button"
+ className="flex w-full items-center gap-1.5 rounded-lg px-1 py-1.5 text-left text-sm text-muted-foreground/70 transition-colors hover:bg-accent/20 hover:text-muted-foreground"
+ onClick={() => setEditing(true)}
+ data-testid="task-chat-description-ghost"
+ >
+ <Pencil className="h-3.5 w-3.5 shrink-0" aria-hidden />
+ Add a description...
+ </button>
+ );
+ }
+
+ const timestamp = formatTaskChatTimestamp(brief.createdAt);
+ return (
+ <div
+ className={cn(
+ "tc-enter-bubble group/brief flex w-full flex-col gap-1",
+ isHuman ? "items-end" : "items-start",
+ )}
+ data-testid="task-chat-description-bubble"
+ data-author={brief.author}
+ >
+ {!isHuman && brief.authorName ? (
+ <span className="flex items-center gap-2 px-1">
+ <Avatar size="sm" className="shrink-0" data-testid="task-chat-agent-avatar">
+ {brief.agentIcon ? (
+ <AvatarFallback>
+ <AgentIcon icon={brief.agentIcon} className="h-3.5 w-3.5" />
+ </AvatarFallback>
+ ) : (
+ <AvatarFallback>{initialsForName(brief.authorName)}</AvatarFallback>
+ )}
+ </Avatar>
+ <span className="text-sm font-semibold text-foreground">{brief.authorName}</span>
+ </span>
+ ) : null}
+ <div
+ className={cn(
+ "flex w-full items-start gap-1.5",
+ isHuman ? "flex-row-reverse" : "flex-row",
+ )}
+ >
+ <div
+ className={cn(
+ "max-w-(--pct-85) break-words px-3.5 py-2 text-sm",
+ isHuman
+ ? "rounded-2xl rounded-br-sm bg-(--liveness-blue) text-white"
+ : "rounded-2xl rounded-bl-sm bg-(--bubble-agent) text-foreground",
+ )}
+ >
+ <FoldCurtain
+ collapsedHeight={FOLD_COLLAPSED_HEIGHT_PX}
+ // The curtain's fade is a mask (background-agnostic); only the
+ // toggle's muted colors need a lift on the solid blue bubble.
+ toggleClassName={isHuman ? "text-white/80 hover:text-white hover:bg-white/10" : undefined}
+ >
+ <MarkdownBody softBreaks linkIssueReferences externalReferences={brief.externalReferences}>
+ {brief.description}
+ </MarkdownBody>
+ </FoldCurtain>
+ </div>
+ <button
+ type="button"
+ className="mt-1 shrink-0 rounded-md p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent/50 hover:text-foreground focus-visible:opacity-100 group-hover/brief:opacity-100"
+ onClick={() => setEditing(true)}
+ aria-label="Edit description"
+ data-testid="task-chat-description-edit"
+ >
+ <Pencil className="h-3.5 w-3.5" aria-hidden />
+ </button>
+ </div>
+ {timestamp ? (
+ <span className="px-1 text-(length:--text-micro) text-muted-foreground">{timestamp}</span>
+ ) : null}
+ </div>
+ );
+}
diff --git a/ui/src/components/task-chat/TaskChatStatusPill.test.tsx b/ui/src/components/task-chat/TaskChatStatusPill.test.tsx
new file mode 100644
index 0000000000..4ef908e3bf
--- /dev/null
+++ b/ui/src/components/task-chat/TaskChatStatusPill.test.tsx
@@ -0,0 +1,297 @@
+// @vitest-environment jsdom
+
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { lineScrollOffset, TaskChatStatusPill } from "./TaskChatStatusPill";
+import { whimsyWord, WHIMSY_ROTATE_MS } from "./status-whimsy";
+import type { TaskChatStatusItem } from "./task-chat-model";
+
+function liveStatus(overrides: Partial<TaskChatStatusItem> = {}): TaskChatStatusItem {
+ return {
+ id: "run-42:status",
+ kind: "status",
+ status: "running",
+ label: "Running",
+ startedAtMs: Date.now(),
+ ...overrides,
+ };
+}
+
+describe("TaskChatStatusPill whimsy", () => {
+ let container: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ });
+
+ afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ document.documentElement.style.removeProperty("--motion-interstitial-dwell");
+ document.documentElement.style.removeProperty("--motion-line-scroll");
+ vi.useRealTimers();
+ });
+
+ const render = (item: TaskChatStatusItem) => {
+ act(() => {
+ root.render(<TaskChatStatusPill item={item} />);
+ });
+ };
+
+ it("swaps the generic Running label for a deterministic whimsical word", () => {
+ const item = liveStatus();
+ render(item);
+ const expected = whimsyWord(item.id, 0);
+ expect(container.textContent).toContain(`${expected}…`);
+ expect(container.textContent).not.toContain("Running…");
+ });
+
+ it("rotates the word roughly every 10s while live", () => {
+ const item = liveStatus();
+ render(item);
+ const first = whimsyWord(item.id, 0);
+ expect(container.textContent).toContain(`${first}…`);
+ act(() => {
+ vi.advanceTimersByTime(WHIMSY_ROTATE_MS + 100);
+ });
+ const second = whimsyWord(item.id, WHIMSY_ROTATE_MS + 100);
+ expect(second).not.toBe(first);
+ expect(container.textContent).toContain(`${second}…`);
+ expect(container.textContent).not.toContain(`${first}…`);
+ });
+
+ it("keeps the informative taxonomy verb when the tail identifies a real tool", () => {
+ render(
+ liveStatus({
+ label: "Running a command",
+ detail: "Terminal · ls -la",
+ toolName: "Bash",
+ }),
+ );
+ expect(container.textContent).toContain("Running a command…");
+ expect(container.textContent).toContain("Terminal · ls -la");
+ });
+
+ it("keeps Queued copy untouched", () => {
+ render(liveStatus({ label: "Queued", detail: "Waiting to start" }));
+ expect(container.textContent).toContain("Queued…");
+ });
+
+ it("keeps elapsed and token readouts alongside the whimsical word", () => {
+ const item = liveStatus({ tokens: { used: 18240, size: 200000 } });
+ render(item);
+ act(() => {
+ vi.advanceTimersByTime(1200);
+ });
+ expect(container.textContent).toContain("1.2s");
+ expect(container.textContent).toContain("18,240/200,000 ctx");
+ });
+
+ it("permanently reserves the interstitial row while live so layout never jumps (round 9)", () => {
+ const item = liveStatus({ tokens: { used: 18240, size: 200000 } });
+ render(item);
+ // No message streaming: the row is still mounted as an empty one-line
+ // slot (same height as when text occupies it) — nothing above shifts when
+ // a message later appears.
+ const row = container.querySelector('[data-testid="task-chat-interstitial-row"]');
+ expect(row).not.toBeNull();
+ expect(container.querySelector('[data-testid="task-chat-live-self-talk"]')).toBeNull();
+ // The empty slot keeps the 1lh viewport height.
+ expect(row?.querySelector(".tc-line-scroll")).not.toBeNull();
+ });
+
+ it("mounts a streaming interstitial as its own row above the status line (PAP-361 amended)", () => {
+ const item = liveStatus({
+ label: "Responding",
+ selfTalk: "I'll extend the ipRateLimit helper with a per-account bucket.",
+ tokens: { used: 18240, size: 200000 },
+ });
+ render(item);
+ act(() => {
+ vi.advanceTimersByTime(1200);
+ });
+ const row = container.querySelector('[data-testid="task-chat-interstitial-row"]');
+ const line = container.querySelector('[data-testid="task-chat-live-self-talk"]');
+ expect(row).not.toBeNull();
+ expect(line?.textContent).toBe("I'll extend the ipRateLimit helper with a per-account bucket.");
+ // The row sits DIRECTLY ABOVE the status line — never sharing it: the
+ // gerund rotation runs uninterrupted below (no "Responding…" copy), with
+ // meta and pulse dot in place.
+ expect(row?.nextElementSibling?.textContent).toContain(`${whimsyWord(item.id, 1200)}…`);
+ expect(row?.contains(line)).toBe(true);
+ expect(container.textContent).not.toContain("Responding…");
+ expect(container.textContent).toContain("1.2s");
+ expect(container.textContent).toContain("18,240/200,000 ctx");
+ expect(container.querySelector(".animate-pulse")).not.toBeNull();
+ // Viewport + transition classes: 1lh clip outside, transform-only inner.
+ expect(line?.className).toContain("tc-line-scroll");
+ expect(line?.firstElementChild?.className).toContain("tc-line-scroll-inner");
+ });
+
+ it("holds the finished update through the dwell, then slides it away (PAP-376)", () => {
+ document.documentElement.style.setProperty("--motion-interstitial-dwell", "4000ms");
+ document.documentElement.style.setProperty("--motion-line-scroll", "240ms");
+ render(liveStatus({ label: "Responding", selfTalk: "Almost there." }));
+ render(liveStatus({}));
+ // selfTalk gone → held as a static single-line readout while the dwell
+ // runs.
+ act(() => {
+ vi.advanceTimersByTime(3900);
+ });
+ let line = container.querySelector('[data-testid="task-chat-live-self-talk"]');
+ expect(line?.textContent).toBe("Almost there.");
+ expect(line?.getAttribute("data-streaming")).toBeNull();
+ expect(line?.getAttribute("data-leaving")).toBeNull();
+ expect(line?.firstElementChild?.className).toContain("truncate");
+ // Dwell expired with no successor: the line slides up out of the 1lh
+ // viewport with the transition re-enabled…
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+ line = container.querySelector('[data-testid="task-chat-live-self-talk"]');
+ expect(line?.getAttribute("data-leaving")).toBe("true");
+ const inner = line?.firstElementChild as HTMLElement;
+ expect(inner.style.transform).toContain("-1");
+ expect(inner.style.transition).toBe("");
+ // …and unmounts back to the reserved empty slot; gerund + dot carry on.
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
+ expect(container.querySelector('[data-testid="task-chat-live-self-talk"]')).toBeNull();
+ const row = container.querySelector('[data-testid="task-chat-interstitial-row"]');
+ expect(row).not.toBeNull();
+ expect(row?.querySelector(".tc-line-scroll")).not.toBeNull();
+ expect(container.querySelector(".animate-pulse")).not.toBeNull();
+ });
+
+ it("swaps a new update straight in after the held line has slid away", () => {
+ document.documentElement.style.setProperty("--motion-interstitial-dwell", "4000ms");
+ render(liveStatus({ label: "Responding", selfTalk: "First." }));
+ render(liveStatus({}));
+ act(() => {
+ vi.advanceTimersByTime(4100);
+ });
+ expect(container.querySelector('[data-testid="task-chat-live-self-talk"]')).toBeNull();
+ render(liveStatus({ label: "Responding", selfTalk: "Second." }));
+ const line = container.querySelector('[data-testid="task-chat-live-self-talk"]');
+ expect(line?.textContent).toBe("Second.");
+ expect(line?.getAttribute("data-streaming")).toBe("true");
+ });
+
+ it("renders the interstitial text without a leading icon (PAP-376)", () => {
+ render(liveStatus({ label: "Responding", selfTalk: "No icon on this row." }));
+ const row = container.querySelector('[data-testid="task-chat-interstitial-row"]');
+ expect(row?.textContent).toBe("No icon on this row.");
+ expect(row?.querySelector("svg")).toBeNull();
+ // The empty lead slot still column-aligns the text with the status label.
+ expect(row?.firstElementChild?.getAttribute("aria-hidden")).toBe("true");
+ });
+
+ it("streams the tail line without a transition once the enter slide settles", () => {
+ render(liveStatus({ label: "Responding", selfTalk: "Streaming along nicely." }));
+ act(() => {
+ vi.advanceTimersByTime(50);
+ });
+ const line = container.querySelector('[data-testid="task-chat-live-self-talk"]');
+ expect(line?.getAttribute("data-streaming")).toBe("true");
+ // Post-enter (--motion-line-scroll reads 0ms in jsdom) the inline
+ // transition is disabled: mid-stream wraps snap instead of gliding.
+ const inner = line?.firstElementChild as HTMLElement;
+ expect(inner.style.transition).toBe("none");
+ expect(inner.className).not.toContain("truncate");
+ });
+
+ it("respects the minimum dwell between swaps and collapses bursts latest-wins", () => {
+ document.documentElement.style.setProperty("--motion-interstitial-dwell", "4000ms");
+ // Update A streams and finishes → held.
+ render(liveStatus({ label: "Responding", selfTalk: "Update A." }));
+ render(liveStatus({}));
+ const innerBefore = container.querySelector(".tc-line-scroll-inner");
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ // Update B arrives 1s after A swapped in: inside the dwell → queued.
+ render(liveStatus({ label: "Responding", selfTalk: "Update B." }));
+ act(() => {
+ vi.advanceTimersByTime(2000);
+ });
+ expect(container.textContent).toContain("Update A.");
+ // Update C supersedes B while still queued (latest-wins queue of one).
+ render(liveStatus({ label: "Responding", selfTalk: "Update C." }));
+ act(() => {
+ vi.advanceTimersByTime(900);
+ });
+ // 3.9s since A swapped in — still inside the dwell.
+ expect(container.textContent).toContain("Update A.");
+ expect(container.textContent).not.toContain("Update B.");
+ act(() => {
+ vi.advanceTimersByTime(200);
+ });
+ // Dwell expired → only the NEWEST pending update swaps in; B never shows.
+ const line = container.querySelector('[data-testid="task-chat-live-self-talk"]');
+ expect(line?.textContent).toBe("Update C.");
+ expect(container.textContent).not.toContain("Update A.");
+ expect(container.textContent).not.toContain("Update B.");
+ // The swap remounts the line (new key) so the slide plays exactly then.
+ expect(container.querySelector(".tc-line-scroll-inner")).not.toBe(innerBefore);
+ // C was still streaming at swap time → it keeps tracking the tail.
+ expect(line?.getAttribute("data-streaming")).toBe("true");
+ });
+
+ it("swaps a queued update in as held when its stream already ended", () => {
+ document.documentElement.style.setProperty("--motion-interstitial-dwell", "4000ms");
+ render(liveStatus({ label: "Responding", selfTalk: "Update A." }));
+ render(liveStatus({}));
+ act(() => {
+ vi.advanceTimersByTime(1000);
+ });
+ // B streams and ENDS while A's dwell is still running.
+ render(liveStatus({ label: "Responding", selfTalk: "Update B, done already." }));
+ render(liveStatus({}));
+ act(() => {
+ vi.advanceTimersByTime(3100);
+ });
+ const line = container.querySelector('[data-testid="task-chat-live-self-talk"]');
+ expect(line?.textContent).toBe("Update B, done already.");
+ expect(line?.getAttribute("data-streaming")).toBeNull();
+ expect(line?.firstElementChild?.className).toContain("truncate");
+ });
+
+ it("clears the held line when the turn ends", () => {
+ render(liveStatus({ label: "Responding", selfTalk: "Held across the turn?" }));
+ render(liveStatus({}));
+ expect(container.textContent).toContain("Held across the turn?");
+ // Turn settles into a non-live status: the row (and held text) is gone;
+ // a later live turn must not resurrect the old update.
+ render(liveStatus({ status: "interrupted", label: "Interrupted" }));
+ act(() => {
+ vi.advanceTimersByTime(50);
+ });
+ expect(container.querySelector('[data-testid="task-chat-interstitial-row"]')).toBeNull();
+ render(liveStatus({}));
+ act(() => {
+ vi.advanceTimersByTime(50);
+ });
+ expect(container.textContent).not.toContain("Held across the turn?");
+ expect(container.querySelector('[data-testid="task-chat-live-self-talk"]')).toBeNull();
+ });
+});
+
+describe("lineScrollOffset", () => {
+ it("translates up one line-height per wrapped line", () => {
+ expect(lineScrollOffset(16, 16)).toBe(0); // one line — no shift
+ expect(lineScrollOffset(32, 16)).toBe(1);
+ expect(lineScrollOffset(48.5, 16)).toBe(2); // sub-pixel scrollHeight rounds
+ });
+
+ it("never goes negative and guards bad measurements", () => {
+ expect(lineScrollOffset(0, 16)).toBe(0);
+ expect(lineScrollOffset(32, 0)).toBe(0);
+ expect(lineScrollOffset(Number.NaN, 16)).toBe(0);
+ });
+});
diff --git a/ui/src/components/task-chat/TaskChatStatusPill.tsx b/ui/src/components/task-chat/TaskChatStatusPill.tsx
index 2b1275ecc1..b52cc044e5 100644
--- a/ui/src/components/task-chat/TaskChatStatusPill.tsx
+++ b/ui/src/components/task-chat/TaskChatStatusPill.tsx
@@ -1,8 +1,10 @@
-import { useEffect, useState } from "react";
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";
-import { Loader2, ShieldQuestion, OctagonX, Ban, Scissors } from "lucide-react";
+import { ChevronRight, Loader2, ShieldQuestion, OctagonX, Ban, Scissors } from "lucide-react";
import type { TaskChatStatusItem } from "./task-chat-model";
-import { toolTaxonomy } from "./tool-taxonomy";
+import { statusLabelIcon, toolTaxonomy } from "./tool-taxonomy";
+import { isGenericStatusLabel, whimsyWord } from "./status-whimsy";
+import { parseCssTimeMs } from "./motion-tokens";
function elapsedLabel(ms?: number): string | null {
if (ms == null) return null;
@@ -19,7 +21,7 @@ function liveElapsedLabel(ms?: number): string | null {
return `${Math.floor(s / 60)}m ${(s % 60).toFixed(1)}s`;
}
-/** Elapsed ms since `startedAtMs`, ticking every 100ms while `live`. */
+/** Elapsed ms since `startedAtMs`, ticking ten times a second while `live`. */
function useLiveElapsedMs(startedAtMs: number | undefined, live: boolean): number | undefined {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
@@ -30,6 +32,223 @@ function useLiveElapsedMs(startedAtMs: number | undefined, live: boolean): numbe
return startedAtMs == null ? undefined : Math.max(0, now - startedAtMs);
}
+/**
+ * How many line-heights the streaming interstitial block is shifted up so only
+ * its LAST line shows in the 1lh viewport: lines − 1 (never negative).
+ */
+export function lineScrollOffset(scrollHeight: number, lineHeightPx: number): number {
+ if (!Number.isFinite(scrollHeight) || !Number.isFinite(lineHeightPx) || lineHeightPx <= 0) {
+ return 0;
+ }
+ return Math.max(0, Math.round(scrollHeight / lineHeightPx) - 1);
+}
+
+/** Read a `--motion-*` time token off :root in ms (0 when unset, e.g. jsdom). */
+function motionTokenMs(name: string): number {
+ const raw = getComputedStyle(document.documentElement).getPropertyValue(name);
+ const ms = parseCssTimeMs(raw);
+ return Number.isFinite(ms) ? ms : 0;
+}
+
+/**
+ * The interstitial update inside a one-line-height clipped viewport.
+ *
+ * The `.tc-line-scroll` slide plays ONLY at swap moments (PAP-368): on mount —
+ * i.e. when a new update replaces the previous one, the parent keys this
+ * component by swap — the text slides up from below the 1lh clip, and once
+ * that enter window (--motion-line-scroll) elapses the transition is disabled
+ * inline. While `streaming`, the block is shifted up by whole line-heights so
+ * only the tail line shows, but with the transition off the shift SNAPS — no
+ * per-wrap glide keeping the row in constant motion. Once the update finishes
+ * (`streaming` false) the held text renders single-line ellipsized, static.
+ * When `leaving` (held past the dwell with no successor, PAP-376), the
+ * transition re-enables and the line continues up out of the clip. Line count
+ * is measured from scrollHeight / line-height, re-checked on resize.
+ */
+function LiveSelfTalkLine({
+ text,
+ streaming,
+ leaving,
+}: {
+ text: string;
+ streaming: boolean;
+ leaving?: boolean;
+}) {
+ const innerRef = useRef<HTMLSpanElement | null>(null);
+ const [offset, setOffset] = useState(0);
+ const [entered, setEntered] = useState(false);
+ const [settled, setSettled] = useState(false);
+ useLayoutEffect(() => {
+ const el = innerRef.current;
+ if (!el) return;
+ const measure = () => {
+ const lineHeight = parseFloat(window.getComputedStyle(el).lineHeight);
+ setOffset(lineScrollOffset(el.scrollHeight, lineHeight));
+ };
+ measure();
+ if (typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver(measure);
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [text, streaming]);
+ useEffect(() => {
+ const id = requestAnimationFrame(() => setEntered(true));
+ const timer = window.setTimeout(() => setSettled(true), motionTokenMs("--motion-line-scroll"));
+ return () => {
+ cancelAnimationFrame(id);
+ window.clearTimeout(timer);
+ };
+ }, []);
+ const shift = !entered ? 1 : leaving ? -1 : streaming ? -offset : 0;
+ return (
+ <span
+ className="tc-line-scroll min-w-0 flex-1"
+ data-testid="task-chat-live-self-talk"
+ data-streaming={streaming || undefined}
+ data-leaving={leaving || undefined}
+ >
+ <span
+ ref={innerRef}
+ className={cn("tc-line-scroll-inner block", !streaming && "truncate")}
+ style={{
+ transform: shift !== 0 ? `translateY(calc(${shift} * 1lh))` : undefined,
+ transition: settled && !leaving ? "none" : undefined,
+ }}
+ >
+ {text}
+ </span>
+ </span>
+ );
+}
+
+interface HeldSelfTalk {
+ text: string;
+ /** The displayed update is the currently-streaming tail message. */
+ streaming: boolean;
+ /** Increments at each swap — keys LiveSelfTalkLine so the slide replays. */
+ swapKey: number;
+ /** Sliding out after sitting held for the full dwell (PAP-376). */
+ leaving?: boolean;
+}
+
+/**
+ * Held interstitial state (PAP-368, amended by PAP-376): a finished update
+ * stays visible, static, for --motion-interstitial-dwell (~4s) — then, if
+ * nothing superseded it, slides away rather than sitting until the next
+ * update happens to push it out. The same dwell paces swaps (~4s minimum
+ * between them) so visibility tracks reading time, not streaming speed.
+ * Updates that arrive inside the dwell window collapse latest-wins (a queue
+ * of one: only the newest pending update swaps in when the dwell expires).
+ *
+ * Message boundaries are the `selfTalk` gaps: the transcript tail clears it
+ * between assistant messages (tool calls / thinking in between), so a
+ * defined→undefined→defined sequence marks a new update.
+ */
+function useHeldSelfTalk(selfTalk: string | undefined, live: boolean): HeldSelfTalk | null {
+ const [line, setLine] = useState<HeldSelfTalk | null>(null);
+ const lineRef = useRef<HeldSelfTalk | null>(line);
+ const pendingRef = useRef<string | null>(null);
+ const tailRef = useRef<string | undefined>(selfTalk);
+ const lastSwapAtRef = useRef(0);
+ const timerRef = useRef<number | null>(null);
+ const leaveTimerRef = useRef<number | null>(null);
+ const exitTimerRef = useRef<number | null>(null);
+ tailRef.current = selfTalk;
+
+ useEffect(() => {
+ const clear = (ref: { current: number | null }) => {
+ if (ref.current != null) {
+ window.clearTimeout(ref.current);
+ ref.current = null;
+ }
+ };
+ const show = (next: HeldSelfTalk | null) => {
+ lineRef.current = next;
+ setLine(next);
+ };
+ // Held past the dwell with nothing queued: slide the line out of the 1lh
+ // viewport (--motion-line-scroll) and unmount it back to the empty slot.
+ const scheduleLeave = () => {
+ clear(leaveTimerRef);
+ clear(exitTimerRef);
+ leaveTimerRef.current = window.setTimeout(() => {
+ leaveTimerRef.current = null;
+ // A queued update's swap timer fires no later than this — let the
+ // swap replace the line instead of playing the exit first.
+ if (pendingRef.current != null) return;
+ const cur = lineRef.current;
+ if (cur == null || cur.streaming) return;
+ show({ ...cur, leaving: true });
+ exitTimerRef.current = window.setTimeout(() => {
+ exitTimerRef.current = null;
+ if (lineRef.current?.leaving) show(null);
+ }, motionTokenMs("--motion-line-scroll"));
+ }, motionTokenMs("--motion-interstitial-dwell"));
+ };
+ const swapIn = (text: string, streaming: boolean) => {
+ clear(leaveTimerRef);
+ clear(exitTimerRef);
+ lastSwapAtRef.current = Date.now();
+ show({ text, streaming, swapKey: (lineRef.current?.swapKey ?? 0) + 1 });
+ // Swapped in with its stream already over: its idle clock starts now.
+ if (!streaming) scheduleLeave();
+ };
+ if (!live) {
+ // Turn end clears the row (the reserved slot itself unmounts with it).
+ clear(timerRef);
+ clear(leaveTimerRef);
+ clear(exitTimerRef);
+ pendingRef.current = null;
+ if (lineRef.current) show(null);
+ return;
+ }
+ const cur = lineRef.current;
+ if (selfTalk == null) {
+ // Stream ended: the update becomes held and its idle clock starts.
+ if (cur?.streaming) {
+ show({ ...cur, streaming: false });
+ scheduleLeave();
+ }
+ return;
+ }
+ if (cur == null) {
+ swapIn(selfTalk, true);
+ return;
+ }
+ if (cur.streaming) {
+ // Same message growing — update in place, no swap.
+ if (cur.text !== selfTalk) show({ ...cur, text: selfTalk });
+ return;
+ }
+ // A new update while one is held (or leaving): queue it latest-wins and
+ // swap when the dwell since the last swap has elapsed.
+ pendingRef.current = selfTalk;
+ if (timerRef.current == null) {
+ const dwellMs = motionTokenMs("--motion-interstitial-dwell");
+ const delay = Math.max(0, lastSwapAtRef.current + dwellMs - Date.now());
+ timerRef.current = window.setTimeout(() => {
+ timerRef.current = null;
+ const text = pendingRef.current;
+ pendingRef.current = null;
+ // Still streaming iff the tail message is live at swap time; if so the
+ // next effect pass keeps the text tracking the tail.
+ if (text != null) swapIn(text, tailRef.current != null);
+ }, delay);
+ }
+ }, [selfTalk, live]);
+
+ useEffect(
+ () => () => {
+ if (timerRef.current != null) window.clearTimeout(timerRef.current);
+ if (leaveTimerRef.current != null) window.clearTimeout(leaveTimerRef.current);
+ if (exitTimerRef.current != null) window.clearTimeout(exitTimerRef.current);
+ },
+ [],
+ );
+
+ return line;
+}
+
const CONFIG = {
running: { Icon: Loader2, spin: true, tone: "text-(--status-agent-running)" },
working: { Icon: Loader2, spin: true, tone: "text-(--status-agent-running)" },
@@ -42,6 +261,19 @@ const CONFIG = {
interface TaskChatStatusPillProps {
item: TaskChatStatusItem;
onApprovalDecision?: (optionId: string) => void;
+ /**
+ * When set, the live line is the header of an expandable parent row
+ * (TaskChatTurn): render a trailing chevron reflecting the open state —
+ * the same expand grammar as tool rows and the settled "Worked ·" line.
+ */
+ chevronOpen?: boolean;
+ /**
+ * Expand toggle for the parent row. The button (hover + click target) wraps
+ * ONLY the gerund status line — the interstitial row above it stays outside
+ * (PAP-376): its text vanishes on expand, so hovering it as part of the
+ * header read as covering two unrelated lines.
+ */
+ onToggle?: () => void;
}
/**
@@ -51,27 +283,55 @@ interface TaskChatStatusPillProps {
* card chrome — awaiting-approval elevates with an attention pulse and
* exposes the ACP permission options as actions.
*/
-export function TaskChatStatusPill({ item, onApprovalDecision }: TaskChatStatusPillProps) {
+export function TaskChatStatusPill({
+ item,
+ onApprovalDecision,
+ chevronOpen,
+ onToggle,
+}: TaskChatStatusPillProps) {
const { Icon, spin, tone } = CONFIG[item.status];
const awaiting = item.status === "awaiting_approval";
const live = item.status === "running" || item.status === "working";
const liveElapsedMs = useLiveElapsedMs(item.startedAtMs, live);
+ const heldSelfTalk = useHeldSelfTalk(live ? item.selfTalk : undefined, live);
const elapsed = elapsedLabel(item.elapsedMs);
if (live) {
const liveElapsed = liveElapsedLabel(liveElapsedMs ?? item.elapsedMs);
- const ToolIcon = item.toolName ? toolTaxonomy(item.toolName).icon : null;
- return (
+ // While an interstitial streams, its text lives on its OWN row above; the
+ // status line below keeps the uninterrupted gerund rotation ("Responding"
+ // never takes the line, and no Responding icon appears here).
+ const streamingInterstitial = item.selfTalk != null;
+ const ToolIcon = item.toolName
+ ? toolTaxonomy(item.toolName).icon
+ : streamingInterstitial
+ ? null
+ : statusLabelIcon(item.label);
+ // Whimsy fills gaps, never replaces signal: only the generic
+ // "Running"/"Working" labels — and the interstitial-streaming state, whose
+ // text renders on the row above — swap for a deterministic whimsical
+ // gerund (seeded by the run-scoped item id, rotating ~10s via the live
+ // tick).
+ const label = streamingInterstitial || isGenericStatusLabel(item.label)
+ ? whimsyWord(item.id, liveElapsedMs ?? item.elapsedMs ?? 0)
+ : item.label;
+ const statusLine = (
<div className="tc-enter-status flex items-center gap-2 py-0.5 text-xs text-muted-foreground">
- <span
- aria-hidden
- className="h-2 w-2 shrink-0 animate-pulse rounded-full bg-(--status-agent-running)"
- />
+ {/* Fixed-size lead slot keeps the label from moving as tool icons
+ come and go; the pulse dot renders unconditionally. */}
+ <span className="flex h-3.5 w-3.5 shrink-0 items-center justify-center">
+ <span
+ aria-hidden
+ className="h-2 w-2 animate-pulse rounded-full bg-(--status-agent-running)"
+ />
+ </span>
{ToolIcon ? <ToolIcon className="h-3.5 w-3.5 shrink-0" aria-hidden /> : null}
{/* Text cells share a baseline row so the smaller mono readouts don't
float above the label's baseline. */}
<span className="flex min-w-0 flex-1 items-baseline gap-2">
- <span className="shimmer-text shimmer-text-muted shrink-0 font-medium">{item.label}…</span>
+ <span className="shimmer-text shimmer-text-muted shrink-0 font-medium">
+ {label}…
+ </span>
{liveElapsed ? (
<span className="shrink-0 font-mono tabular-nums text-(length:--text-micro)">
{liveElapsed}
@@ -86,6 +346,56 @@ export function TaskChatStatusPill({ item, onApprovalDecision }: TaskChatStatusP
</span>
) : null}
</span>
+ {chevronOpen !== undefined ? (
+ <ChevronRight
+ className={cn("h-3 w-3 shrink-0 transition-transform", chevronOpen ? "rotate-90" : null)}
+ aria-hidden
+ />
+ ) : null}
+ </div>
+ );
+ // The interstitial row is PERMANENTLY RESERVED while the turn is live
+ // (round 9): the layout above never jumps to make room. A streaming
+ // interstitial gets this bubble-less, icon-less single-line row DIRECTLY
+ // ABOVE the status line — the two never share a line. The latest update is
+ // held after its stream ends (PAP-368) and slides away once it has sat
+ // for the full --motion-interstitial-dwell without a successor (PAP-376);
+ // the .tc-line-scroll slide otherwise plays only when a new update swaps
+ // in (keyed remount). Before the first update the row is an empty one-line
+ // slot of identical height; the empty lead slot keeps the text
+ // column-aligned with the status label. The expand button wraps ONLY the
+ // status line, so the interstitial row never picks up its hover.
+ return (
+ <div className="flex flex-col">
+ <div
+ className="flex items-center gap-2 py-0.5 text-xs text-muted-foreground"
+ data-testid="task-chat-interstitial-row"
+ >
+ <span aria-hidden className="h-3.5 w-3.5 shrink-0" />
+ {heldSelfTalk ? (
+ <LiveSelfTalkLine
+ key={heldSelfTalk.swapKey}
+ text={heldSelfTalk.text}
+ streaming={heldSelfTalk.streaming}
+ leaving={heldSelfTalk.leaving}
+ />
+ ) : (
+ <span aria-hidden className="tc-line-scroll min-w-0 flex-1" />
+ )}
+ </div>
+ {onToggle ? (
+ <button
+ type="button"
+ onClick={onToggle}
+ aria-expanded={chevronOpen}
+ className="-mx-1.5 block w-full rounded-sm px-1.5 text-left transition-colors hover:bg-muted/60"
+ data-testid="task-chat-live-turn"
+ >
+ {statusLine}
+ </button>
+ ) : (
+ statusLine
+ )}
</div>
);
}
diff --git a/ui/src/components/task-chat/TaskChatThinkingBlock.tsx b/ui/src/components/task-chat/TaskChatThinkingBlock.tsx
deleted file mode 100644
index 4e4d9432ec..0000000000
--- a/ui/src/components/task-chat/TaskChatThinkingBlock.tsx
+++ /dev/null
@@ -1,50 +0,0 @@
-import { useState } from "react";
-import { cn } from "@/lib/utils";
-import { ChevronRight } from "lucide-react";
-import type { TaskChatThinkingItem } from "./task-chat-model";
-
-/**
- * Chain-of-thought (ACP agent_thought_chunk) as a flat left-railed block (v7):
- * a chevron header whose label shimmers while streaming ("Thinking…") and
- * settles to "Thought for Ns", over a recessed pre-wrap body. Streams open;
- * settled history arrives collapsed and re-expands on click. No card chrome —
- * thinking is activity metadata, subordinate to real content.
- */
-export function TaskChatThinkingBlock({ item }: { item: TaskChatThinkingItem }) {
- const [open, setOpen] = useState(!item.collapsed);
- const settledLabel = item.summaryLabel ?? "Thought process";
-
- return (
- <div className="border-l-2 border-border pl-3 text-xs text-muted-foreground">
- <button
- type="button"
- onClick={() => setOpen((v) => !v)}
- aria-expanded={open}
- className="flex items-center gap-1.5 py-0.5 transition-colors hover:text-foreground"
- >
- <ChevronRight className={cn("h-3 w-3 shrink-0 transition-transform", open ? "rotate-90" : null)} aria-hidden />
- {item.streaming ? (
- <span className="shimmer-text shimmer-text-muted font-medium">Thinking…</span>
- ) : (
- <span className="font-medium">{settledLabel}</span>
- )}
- </button>
- {open ? (
- <div className="space-y-1 pb-1 pt-0.5">
- {item.lines.map((line, i) => (
- <p
- key={i}
- className="tc-enter-cot-line whitespace-pre-wrap"
- style={{ animationDelay: `calc(var(--motion-cot-line-stagger) * ${i})` }}
- >
- {line}
- </p>
- ))}
- {item.streaming ? (
- <span className="tc-cursor inline-block h-3 w-1.5 bg-muted-foreground align-baseline" />
- ) : null}
- </div>
- ) : null}
- </div>
- );
-}
diff --git a/ui/src/components/task-chat/TaskChatThreadView.tsx b/ui/src/components/task-chat/TaskChatThreadView.tsx
index 87c27f1f22..9916837b3c 100644
--- a/ui/src/components/task-chat/TaskChatThreadView.tsx
+++ b/ui/src/components/task-chat/TaskChatThreadView.tsx
@@ -6,7 +6,6 @@ import { TaskChatBubble } from "./TaskChatBubble";
import { TaskChatMarker } from "./TaskChatMarker";
import { TaskChatStatusPill } from "./TaskChatStatusPill";
import { TaskChatToolCard } from "./TaskChatToolCard";
-import { TaskChatThinkingBlock } from "./TaskChatThinkingBlock";
import { TaskChatUsageReadout } from "./TaskChatUsageReadout";
import { TaskMessageScroller } from "./TaskMessageScroller";
@@ -25,6 +24,12 @@ interface TaskChatThreadViewProps {
* items render nothing without it — the harness has no control plane.
*/
renderInteraction?: (item: TaskChatInteractionItem) => ReactNode;
+ /**
+ * Renders the description-as-first-bubble placeholder (PAP-375). The live
+ * thread binds TaskChatDescriptionBubble to the issue; brief items render
+ * nothing without it.
+ */
+ renderBrief?: () => ReactNode;
className?: string;
/** When false, render the list without the scroll container (e.g. previews). */
scroll?: boolean;
@@ -34,14 +39,32 @@ function renderItem(
item: TaskChatItem,
onApprovalDecision?: (statusItemId: string, optionId: string) => void,
renderInteraction?: (item: TaskChatInteractionItem) => ReactNode,
+ renderBrief?: () => ReactNode,
) {
switch (item.kind) {
case "message":
- return <TaskChatBubble item={item} />;
+ return (
+ <TaskChatBubble
+ item={item}
+ attachedTurn={
+ item.attachedTurn ? (
+ <TaskChatTurn
+ item={item.attachedTurn}
+ timestampPrefix={item.timestamp}
+ renderChild={(child) => renderItem(child, onApprovalDecision)}
+ />
+ ) : undefined
+ }
+ />
+ );
case "marker":
return <TaskChatMarker item={item} />;
case "thinking":
- return <TaskChatThinkingBlock item={item} />;
+ // Thinking never renders as a row (PAP-361): its live signal is the
+ // pill's "Thinking…" state, and the text stays in the run log / classic
+ // transcript. The kind survives in the model because the transcript
+ // parser still emits it (both nesting rules filter it out).
+ return null;
case "tool":
return <TaskChatToolCard item={item} />;
case "status":
@@ -55,6 +78,8 @@ function renderItem(
return <TaskChatUsageReadout item={item} />;
case "interaction":
return renderInteraction ? renderInteraction(item) : null;
+ case "brief":
+ return renderBrief ? renderBrief() : null;
case "turn":
return (
<TaskChatTurn
@@ -81,6 +106,7 @@ export function TaskChatThreadView({
header,
onApprovalDecision,
renderInteraction,
+ renderBrief,
className,
scroll = true,
}: TaskChatThreadViewProps) {
@@ -92,25 +118,38 @@ export function TaskChatThreadView({
</div>
) : null}
{items.map((item) => (
- <div key={item.id}>{renderItem(item, onApprovalDecision, renderInteraction)}</div>
+ <div key={item.id}>{renderItem(item, onApprovalDecision, renderInteraction, renderBrief)}</div>
))}
</div>
);
if (!scroll) return body;
- // Include a cheap content signature so streaming growth (text lengthening
- // without the item count changing) still advances the auto-follow key.
- const signatureOf = (it: TaskChatItem): number => {
- if (it.kind === "message") return it.text.length;
- if (it.kind === "thinking") return it.lines.reduce((n, l) => n + l.length, 0);
- if (it.kind === "tool") return (it.diff?.lines?.length ?? 0) + (it.status === "completed" ? 1 : 0);
- if (it.kind === "turn") {
- return it.settled ? 1 : it.items.reduce((n, child) => n + signatureOf(child), it.items.length);
- }
- return 1;
- };
- const contentKey = items.reduce((acc, it) => acc + signatureOf(it), items.length);
+ return <TaskMessageScroller contentKey={taskChatContentKey(items)}>{body}</TaskMessageScroller>;
+}
+
+// Cheap content signature so streaming growth (text lengthening without the
+// item count changing) still advances the auto-follow key. Shared by the
+// desktop scroller above and the mobile window-scroll follow (TaskChatThread).
+function signatureOf(it: TaskChatItem): number {
+ if (it.kind === "message") return it.text.length + (it.attachedTurn ? 1 : 0);
+ if (it.kind === "thinking") return it.lines.reduce((n, l) => n + l.length, 0);
+ if (it.kind === "tool") return (it.diff?.lines?.length ?? 0) + (it.status === "completed" ? 1 : 0);
+ if (it.kind === "turn") {
+ if (it.settled) return 1;
+ // The live parent row's header changes (gerund ↔ tool-state flashes,
+ // streaming interstitial text growing) count too, so the collapsed
+ // single-line turn still advances the key.
+ const headerSig = it.liveStatus
+ ? it.liveStatus.label.length +
+ (it.liveStatus.detail?.length ?? 0) +
+ (it.liveStatus.selfTalk?.length ?? 0)
+ : 0;
+ return it.items.reduce((n, child) => n + signatureOf(child), it.items.length + headerSig);
+ }
+ return 1;
+}
- return <TaskMessageScroller contentKey={contentKey}>{body}</TaskMessageScroller>;
+export function taskChatContentKey(items: TaskChatItem[]): number {
+ return items.reduce((acc, it) => acc + signatureOf(it), items.length);
}
diff --git a/ui/src/components/task-chat/TaskChatTurn.test.tsx b/ui/src/components/task-chat/TaskChatTurn.test.tsx
index 2377d29845..eec4c9e083 100644
--- a/ui/src/components/task-chat/TaskChatTurn.test.tsx
+++ b/ui/src/components/task-chat/TaskChatTurn.test.tsx
@@ -1,12 +1,25 @@
// @vitest-environment jsdom
+import { act } from "react";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { TaskChatTurn, turnSummaryText } from "./TaskChatTurn";
import { buildTurnSummary } from "./transcript-adapter";
import type { TranscriptEntry } from "@/adapters";
-import type { TaskChatTurnItem } from "./task-chat-model";
+import type {
+ TaskChatStatusItem,
+ TaskChatToolStatus,
+ TaskChatTurnChildItem,
+ TaskChatTurnItem,
+} from "./task-chat-model";
+
+const tool = (id: string, status: TaskChatToolStatus = "completed"): TaskChatTurnChildItem => ({
+ id,
+ kind: "tool",
+ name: "Read",
+ status,
+});
const SETTLED: TaskChatTurnItem = {
id: "t1",
@@ -16,6 +29,26 @@ const SETTLED: TaskChatTurnItem = {
items: [{ id: "c1", kind: "tool", name: "read auth.ts", status: "completed" }],
};
+// Non-generic label so the header shows it verbatim (no whimsy substitution).
+const LIVE_STATUS: TaskChatStatusItem = {
+ id: "t1:status",
+ kind: "status",
+ status: "working",
+ label: "Editing files",
+ detail: "Edit · server/src/routes/auth.ts",
+ toolName: "Edit",
+};
+
+const parentRowTurn = (
+ children: TaskChatTurnChildItem[],
+ status: TaskChatStatusItem = LIVE_STATUS,
+): TaskChatTurnItem => ({
+ ...SETTLED,
+ settled: false,
+ liveStatus: status,
+ items: children,
+});
+
describe("turnSummaryText", () => {
it("joins the known parts with dots", () => {
expect(turnSummaryText(SETTLED.summary)).toBe("Worked · 38s · 3 tools · +34 −3 · 12.3k tokens");
@@ -80,6 +113,8 @@ describe("TaskChatTurn", () => {
const fold = () => container.querySelector(".tc-turn-fold");
const summaryBtn = () =>
container.querySelector<HTMLButtonElement>('[data-testid="task-chat-turn-summary"]');
+ const liveHeaderBtn = () =>
+ container.querySelector<HTMLButtonElement>('[data-testid="task-chat-live-turn"]');
it("renders a settled turn folded with its summary line", () => {
renderTurn(SETTLED);
@@ -95,15 +130,112 @@ describe("TaskChatTurn", () => {
expect(fold()?.getAttribute("data-folded")).toBe("false");
});
- it("renders a live turn expanded with no summary line", () => {
+ it("a headerless live turn renders expanded with no summary line", () => {
renderTurn({ ...SETTLED, settled: false });
expect(summaryBtn()).toBeNull();
+ expect(liveHeaderBtn()).toBeNull();
expect(fold()?.getAttribute("data-folded")).toBe("false");
});
- it("folds when the item settles while mounted", () => {
+ it("a headerless live turn folds when it settles while mounted", () => {
renderTurn({ ...SETTLED, settled: false });
renderTurn({ ...SETTLED, animateFold: true });
expect(fold()?.getAttribute("data-folded")).toBe("true");
});
+
+ it("collapses a live parent-row turn to its single status line", () => {
+ renderTurn(parentRowTurn([tool("a"), tool("b"), tool("c", "in_progress")]));
+ const header = liveHeaderBtn();
+ expect(header?.textContent).toContain("Editing files…");
+ expect(header?.textContent).toContain("Edit · server/src/routes/auth.ts");
+ expect(header?.getAttribute("aria-expanded")).toBe("false");
+ // All activity is folded behind it — no rows visible, no summary line.
+ expect(fold()?.getAttribute("data-folded")).toBe("true");
+ expect(summaryBtn()).toBeNull();
+ });
+
+ it("flashes the in-flight tool state through the header", () => {
+ renderTurn(parentRowTurn([tool("a")]));
+ expect(liveHeaderBtn()?.textContent).toContain("Editing files…");
+ renderTurn(
+ parentRowTurn([tool("a")], { ...LIVE_STATUS, label: "Reading a file", detail: "Read · auth.ts", toolName: "Read" }),
+ );
+ expect(liveHeaderBtn()?.textContent).toContain("Reading a file…");
+ expect(liveHeaderBtn()?.textContent).toContain("Read · auth.ts");
+ });
+
+ it("expands to the nested chronological history on click", () => {
+ renderTurn(parentRowTurn([tool("a"), tool("b")]));
+ flushSync(() => liveHeaderBtn()!.click());
+ expect(liveHeaderBtn()?.getAttribute("aria-expanded")).toBe("true");
+ expect(fold()?.getAttribute("data-folded")).toBe("false");
+ expect(fold()?.textContent).toContain("a");
+ expect(fold()?.textContent).toContain("b");
+ });
+
+ it("appends new rows live while expanded and re-collapses on click", () => {
+ renderTurn(parentRowTurn([tool("a")]));
+ flushSync(() => liveHeaderBtn()!.click());
+ renderTurn(parentRowTurn([tool("a"), tool("b", "in_progress")]));
+ expect(fold()?.getAttribute("data-folded")).toBe("false");
+ expect(fold()?.textContent).toContain("b");
+ flushSync(() => liveHeaderBtn()!.click());
+ expect(fold()?.getAttribute("data-folded")).toBe("true");
+ });
+
+ it("keeps the interstitial row outside the expand button's hover target (PAP-376)", () => {
+ // act() so the held-line effect state (useHeldSelfTalk) flushes.
+ act(() => {
+ renderTurn(
+ parentRowTurn([tool("a")], { ...LIVE_STATUS, selfTalk: "Streaming an update." }),
+ );
+ });
+ const btn = liveHeaderBtn();
+ expect(btn).not.toBeNull();
+ // The button (hover + click target) wraps ONLY the gerund status line;
+ // the interstitial text renders above it, outside the button.
+ expect(btn?.querySelector('[data-testid="task-chat-interstitial-row"]')).toBeNull();
+ expect(btn?.textContent).not.toContain("Streaming an update.");
+ const row = container.querySelector('[data-testid="task-chat-interstitial-row"]');
+ expect(row?.textContent).toContain("Streaming an update.");
+ // Expanding still works from the status line alone.
+ flushSync(() => btn!.click());
+ expect(liveHeaderBtn()?.getAttribute("aria-expanded")).toBe("true");
+ expect(fold()?.getAttribute("data-folded")).toBe("false");
+ });
+
+ it("renders the status line without an expand affordance while there is no activity", () => {
+ renderTurn(parentRowTurn([]));
+ expect(liveHeaderBtn()).toBeNull();
+ expect(container.textContent).toContain("Editing files…");
+ });
+
+ it("morphs a collapsed parent row into the settled summary in place", () => {
+ renderTurn(parentRowTurn([tool("a")]));
+ renderTurn({ ...SETTLED, animateFold: true, items: [tool("a")] });
+ expect(liveHeaderBtn()).toBeNull();
+ expect(summaryBtn()?.textContent).toContain("Worked");
+ expect(fold()?.getAttribute("data-folded")).toBe("true");
+ });
+
+ it("keeps the expand state across the settle morph", () => {
+ renderTurn(parentRowTurn([tool("a")]));
+ flushSync(() => liveHeaderBtn()!.click());
+ renderTurn({ ...SETTLED, animateFold: true, items: [tool("a")] });
+ expect(summaryBtn()?.getAttribute("aria-expanded")).toBe("true");
+ expect(fold()?.getAttribute("data-folded")).toBe("false");
+ });
+
+ it("leads the settled summary with the bubble timestamp when attached (round 9)", () => {
+ flushSync(() => {
+ root.render(
+ <TaskChatTurn item={SETTLED} timestampPrefix="2:34 PM" renderChild={(c) => <span>{c.id}</span>} />,
+ );
+ });
+ // "2:34 PM · ✓ Worked · …" — timestamp first, always visible, and the
+ // expand affordance still works from the same line.
+ expect(summaryBtn()?.textContent).toMatch(/^2:34 PM·Worked/);
+ flushSync(() => summaryBtn()!.click());
+ expect(fold()?.getAttribute("data-folded")).toBe("false");
+ });
});
diff --git a/ui/src/components/task-chat/TaskChatTurn.tsx b/ui/src/components/task-chat/TaskChatTurn.tsx
index f871c0b169..314396e583 100644
--- a/ui/src/components/task-chat/TaskChatTurn.tsx
+++ b/ui/src/components/task-chat/TaskChatTurn.tsx
@@ -2,10 +2,17 @@ import { useState, type ReactNode } from "react";
import { cn } from "@/lib/utils";
import { Check, ChevronRight, X } from "lucide-react";
import type { TaskChatTurnItem, TaskChatTurnChildItem } from "./task-chat-model";
+import { TaskChatStatusPill } from "./TaskChatStatusPill";
interface TaskChatTurnProps {
item: TaskChatTurnItem;
renderChild: (child: TaskChatTurnChildItem) => ReactNode;
+ /**
+ * When the settled turn is attached to its reply bubble (round 9), the
+ * bubble's timestamp leads the summary line — "2:34 PM · ✓ Worked · 38s" —
+ * always visible, in the slot the hover-only timestamp used to occupy.
+ */
+ timestampPrefix?: string;
}
/** Metric segments after the label: "38s · 3 tools · +34 −3 · 12.3k tokens". */
@@ -26,30 +33,44 @@ export function turnSummaryText(summary: TaskChatTurnItem["summary"]): string {
}
/**
- * One agent turn's activity, foldable to a one-line summary once settled.
+ * One agent turn's activity behind a single expandable header row.
*
- * While the turn is live it renders fully interleaved with no summary line.
- * When it settles the activity folds behind a "✓ Worked · …" line — animated
- * (grid-rows via .tc-turn-fold, --motion-turn-fold) when the settle happens
- * on-screen, instant for turns that load already settled (the fold class only
- * transitions on state CHANGE, so first paint in the folded state never
- * animates). Clicking the summary folds/unfolds with the same motion.
- * prefers-reduced-motion zeroes the transition in CSS.
+ * While the turn is live and carries `liveStatus`, that status line (whimsy or
+ * taxonomy gerund + elapsed + tokens) IS the turn: one parent row, collapsed
+ * by default, owning all activity (PAP-354). Expanding nests the chronological
+ * tool/thinking history underneath — each row keeping its own expand — and new
+ * rows append live while open. On settle the header morphs in place into the
+ * "✓ Worked · …" summary, preserving the expand state, so the running line
+ * reads as being replaced by the summary in the same slot.
+ *
+ * Both directions of the fold reuse the .tc-turn-fold grid-rows motion
+ * (--motion-turn-fold, zeroed under prefers-reduced-motion). The fold class
+ * only transitions on state CHANGE, so first paint in the folded state (e.g. a
+ * turn that loads already settled) never animates. A live turn without
+ * `liveStatus` (harness fixtures) renders its children expanded with no header
+ * and folds when it settles.
*/
-export function TaskChatTurn({ item, renderChild }: TaskChatTurnProps) {
- const [open, setOpen] = useState(!item.settled);
+export function TaskChatTurn({ item, renderChild, timestampPrefix }: TaskChatTurnProps) {
+ const parentRow = !item.settled && item.liveStatus != null;
+ // Parent-row live turns and settled turns start as their one-line header;
+ // only the headerless legacy live turn starts expanded.
+ const [open, setOpen] = useState(() => !item.settled && item.liveStatus == null);
const [prevSettled, setPrevSettled] = useState(item.settled);
+ const [wasParentRow, setWasParentRow] = useState(parentRow);
- // Live → settled transition observed while mounted: fold (animated via CSS
- // unless reduced motion). Adjusted during render (not in an effect) so the
- // fold state lands in the same commit — no unfolded flash. Turns mounted
- // already-settled start folded via the useState initializers.
+ // Render-adjusted state (not effects) so transitions land in the same
+ // commit — no flash of the wrong fold state.
+ if (parentRow && !wasParentRow) setWasParentRow(true);
+ // Live → settled while mounted: a parent-row turn keeps its expand state
+ // (the header morphs in place); a headerless expanded turn folds (animated
+ // via CSS unless reduced motion).
if (item.settled !== prevSettled) {
setPrevSettled(item.settled);
- if (item.settled) setOpen(false);
+ if (item.settled && !wasParentRow) setOpen(false);
}
- const folded = item.settled && !open;
+ const expandable = item.items.length > 0;
+ const folded = (item.settled || parentRow) && !open;
const SummaryIcon = item.summary.failed ? X : Check;
return (
@@ -62,6 +83,12 @@ export function TaskChatTurn({ item, renderChild }: TaskChatTurnProps) {
className="group flex items-center gap-2 px-1 py-0.5 text-xs text-muted-foreground transition-colors hover:text-foreground"
data-testid="task-chat-turn-summary"
>
+ {timestampPrefix ? (
+ <>
+ <span className="text-(length:--text-micro)">{timestampPrefix}</span>
+ <span aria-hidden className="text-(length:--text-micro)">·</span>
+ </>
+ ) : null}
<SummaryIcon className="h-3.5 w-3.5 shrink-0" />
<span>{item.summary.failed ? "Stopped" : "Worked"}</span>
{turnSummaryMetrics(item.summary) ? (
@@ -69,6 +96,16 @@ export function TaskChatTurn({ item, renderChild }: TaskChatTurnProps) {
) : null}
<ChevronRight className={cn("h-3 w-3 shrink-0 transition-transform", open ? "rotate-90" : null)} />
</button>
+ ) : parentRow ? (
+ // The pill renders the expand button itself, wrapped around only the
+ // gerund status line — the interstitial row above stays outside the
+ // hover/click target (PAP-376). Without activity there is no
+ // chevron/button.
+ <TaskChatStatusPill
+ item={item.liveStatus!}
+ chevronOpen={expandable ? open : undefined}
+ onToggle={expandable ? () => setOpen((o) => !o) : undefined}
+ />
) : null}
<div className="tc-turn-fold" data-folded={folded ? "true" : "false"} aria-hidden={folded}>
<div>
diff --git a/ui/src/components/task-chat/motion-tokens.ts b/ui/src/components/task-chat/motion-tokens.ts
index 6af9101a6b..2b598c0a2b 100644
--- a/ui/src/components/task-chat/motion-tokens.ts
+++ b/ui/src/components/task-chat/motion-tokens.ts
@@ -58,6 +58,8 @@ export const MOTION_TOKENS: MotionTokenDef[] = [
{ name: "--motion-count-tween", group: "States", kind: "time", min: 0, max: 1500, step: 10 },
{ name: "--motion-streaming-cursor-blink", group: "States", kind: "time", min: 0, max: 3000, step: 20 },
{ name: "--motion-turn-fold", group: "States", kind: "time", min: 0, max: 1500, step: 10 },
+ { name: "--motion-line-scroll", group: "States", kind: "time", min: 0, max: 1500, step: 10 },
+ { name: "--motion-interstitial-dwell", group: "States", kind: "time", min: 0, max: 10000, step: 100 },
{ name: "--motion-scroll-pill-enter", group: "States", kind: "time", min: 0, max: 1500, step: 10 },
{ name: "--motion-scroll-pill-exit", group: "States", kind: "time", min: 0, max: 1500, step: 10 },
{ name: "--motion-pane-glide", group: "States", kind: "time", min: 0, max: 1500, step: 10 },
diff --git a/ui/src/components/task-chat/status-whimsy.test.ts b/ui/src/components/task-chat/status-whimsy.test.ts
new file mode 100644
index 0000000000..988989f55e
--- /dev/null
+++ b/ui/src/components/task-chat/status-whimsy.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, it } from "vitest";
+import {
+ ANALOG_OFFICE_WORDS,
+ CLAUDE_CODE_WORDS,
+ WHIMSY_ROTATE_MS,
+ WHIMSY_WORDS,
+ isGenericStatusLabel,
+ whimsyWord,
+} from "./status-whimsy";
+
+describe("whimsy word pools", () => {
+ it("always includes the Clipping brand nod in the analog-office pool", () => {
+ expect(ANALOG_OFFICE_WORDS).toContain("Clipping");
+ expect(WHIMSY_WORDS).toContain("Clipping");
+ });
+
+ it("keeps the pools unique and analog-office dominant (round-2 curation)", () => {
+ expect(new Set(WHIMSY_WORDS).size).toBe(WHIMSY_WORDS.length);
+ expect(WHIMSY_WORDS.length).toBe(ANALOG_OFFICE_WORDS.length + CLAUDE_CODE_WORDS.length);
+ expect(ANALOG_OFFICE_WORDS.length).toBeGreaterThan(CLAUDE_CODE_WORDS.length);
+ });
+
+ it("holds only the four board-kept Claude-Code words", () => {
+ expect([...CLAUDE_CODE_WORDS]).toEqual(["Brewing", "Tinkering", "Distilling", "Deliberating"]);
+ });
+
+ it("applies the round-2 analog-office edits", () => {
+ for (const removed of ["Cataloguing", "Carbon-copying", "Archiving"]) {
+ expect(ANALOG_OFFICE_WORDS).not.toContain(removed);
+ }
+ for (const added of [
+ "Trimming",
+ "Aligning",
+ "Combining",
+ "Whiteboarding",
+ "Diagramming",
+ "Sketching",
+ "Labeling",
+ "Sticky-noting",
+ ]) {
+ expect(ANALOG_OFFICE_WORDS).toContain(added);
+ }
+ // "Grepping" is an informative taxonomy verb, never random whimsy.
+ expect(WHIMSY_WORDS).not.toContain("Grepping");
+ });
+
+ it("keeps every word a gerund so it reads sensibly after-the-fact", () => {
+ for (const word of WHIMSY_WORDS) expect(word).toMatch(/^[A-Z][a-z]+(?:-[a-z]+)*ing$/);
+ });
+});
+
+describe("isGenericStatusLabel", () => {
+ it("flags only the signal-free labels", () => {
+ expect(isGenericStatusLabel("Running")).toBe(true);
+ expect(isGenericStatusLabel("Working")).toBe(true);
+ expect(isGenericStatusLabel("running")).toBe(true);
+ });
+
+ it("keeps informative copy untouched", () => {
+ for (const label of ["Queued", "Thinking", "Responding", "Running a command", "Searching", "", undefined]) {
+ expect(isGenericStatusLabel(label)).toBe(false);
+ }
+ });
+});
+
+describe("whimsyWord", () => {
+ it("picks deterministically from the seed", () => {
+ expect(whimsyWord("run-1:status")).toBe(whimsyWord("run-1:status"));
+ expect(whimsyWord("run-1:status", 0)).toBe(whimsyWord("run-1:status", WHIMSY_ROTATE_MS - 1));
+ });
+
+ it("rotates to the next word every rotation interval", () => {
+ const first = whimsyWord("run-1:status", 0);
+ const second = whimsyWord("run-1:status", WHIMSY_ROTATE_MS);
+ const index = WHIMSY_WORDS.indexOf(first);
+ expect(second).toBe(WHIMSY_WORDS[(index + 1) % WHIMSY_WORDS.length]);
+ expect(second).not.toBe(first);
+ });
+
+ it("cycles through the whole pool and wraps", () => {
+ const seen = new Set<string>();
+ for (let tick = 0; tick < WHIMSY_WORDS.length; tick++) {
+ seen.add(whimsyWord("run-1:status", tick * WHIMSY_ROTATE_MS));
+ }
+ expect(seen.size).toBe(WHIMSY_WORDS.length);
+ expect(whimsyWord("run-1:status", WHIMSY_WORDS.length * WHIMSY_ROTATE_MS)).toBe(
+ whimsyWord("run-1:status", 0),
+ );
+ });
+
+ it("spreads different seeds across the pool", () => {
+ const words = new Set(
+ Array.from({ length: 20 }, (_, i) => whimsyWord(`run-${i}:status`)),
+ );
+ expect(words.size).toBeGreaterThan(5);
+ });
+});
diff --git a/ui/src/components/task-chat/status-whimsy.ts b/ui/src/components/task-chat/status-whimsy.ts
new file mode 100644
index 0000000000..b9bc3d23f0
--- /dev/null
+++ b/ui/src/components/task-chat/status-whimsy.ts
@@ -0,0 +1,97 @@
+/**
+ * Whimsical gerunds for the live status pill when the label carries no real
+ * signal ("Running"/"Working"). Two curated pools: Paperclip's analog-office
+ * vocabulary (led by the "Clipping" brand nod) and Claude-Code-style whimsy.
+ * Every word is chosen to still read sensibly after-the-fact — a settled turn
+ * that once said "Collating…" shouldn't feel like a lie.
+ *
+ * The pick is deterministic from a seed (the run-scoped status item id) so a
+ * re-render never reshuffles the word, and it rotates to the next word every
+ * ~10s of elapsed run time.
+ */
+
+/** Paperclip / analog-office pool — "Clipping" is the guaranteed brand nod.
+ * Board-curated round 2 (PAP-349): dropped Cataloguing / Carbon-copying /
+ * Archiving, added the workshop-and-whiteboard verbs. */
+export const ANALOG_OFFICE_WORDS: readonly string[] = [
+ "Clipping",
+ "Organizing",
+ "Sorting",
+ "Synthesizing",
+ "Analyzing",
+ "Filing",
+ "Collating",
+ "Stapling",
+ "Indexing",
+ "Annotating",
+ "Drafting",
+ "Proofreading",
+ "Alphabetizing",
+ "Photocopying",
+ "Laminating",
+ "Hole-punching",
+ "Bookmarking",
+ "Highlighting",
+ "Typing",
+ "Trimming",
+ "Aligning",
+ "Combining",
+ "Whiteboarding",
+ "Diagramming",
+ "Sketching",
+ "Labeling",
+ "Sticky-noting",
+];
+
+/** Claude-Code-style whimsy pool — board-curated round 2 kept only these four. */
+export const CLAUDE_CODE_WORDS: readonly string[] = [
+ "Brewing",
+ "Tinkering",
+ "Distilling",
+ "Deliberating",
+];
+
+/** Interleaved so consecutive rotations alternate flavors rather than running
+ * through one pool before the other. */
+export const WHIMSY_WORDS: readonly string[] = (() => {
+ const out: string[] = [];
+ const max = Math.max(ANALOG_OFFICE_WORDS.length, CLAUDE_CODE_WORDS.length);
+ for (let i = 0; i < max; i++) {
+ if (i < ANALOG_OFFICE_WORDS.length) out.push(ANALOG_OFFICE_WORDS[i]);
+ if (i < CLAUDE_CODE_WORDS.length) out.push(CLAUDE_CODE_WORDS[i]);
+ }
+ return out;
+})();
+
+/** How long each word holds before rotating to the next. */
+export const WHIMSY_ROTATE_MS = 10_000;
+
+/**
+ * Labels that carry no tool identity, where a whimsical word fills the gap.
+ * Informative labels (taxonomy verbs, "Thinking", "Responding", "Queued")
+ * always keep their copy — whimsy never replaces signal.
+ */
+export function isGenericStatusLabel(label: string | undefined | null): boolean {
+ const raw = (label ?? "").trim().toLowerCase();
+ return raw === "running" || raw === "working";
+}
+
+/** FNV-1a 32-bit — stable, dependency-free string hash for the seed. */
+function fnv1a(str: string): number {
+ let h = 0x811c9dc5;
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i);
+ h = Math.imul(h, 0x01000193);
+ }
+ return h >>> 0;
+}
+
+/**
+ * Deterministic whimsical word: the seed fixes the starting offset into the
+ * pool and each elapsed `WHIMSY_ROTATE_MS` advances one word. Same seed and
+ * elapsed always yield the same word.
+ */
+export function whimsyWord(seed: string, elapsedMs = 0): string {
+ const tick = Math.floor(Math.max(0, elapsedMs) / WHIMSY_ROTATE_MS);
+ return WHIMSY_WORDS[(fnv1a(seed) + tick) % WHIMSY_WORDS.length];
+}
diff --git a/ui/src/components/task-chat/task-chat-adapter.test.ts b/ui/src/components/task-chat/task-chat-adapter.test.ts
new file mode 100644
index 0000000000..3af1b5b707
--- /dev/null
+++ b/ui/src/components/task-chat/task-chat-adapter.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+import type { IssueChatComment } from "@/lib/issue-chat-messages";
+import { commentsToTaskChatItems } from "./task-chat-adapter";
+
+describe("commentsToTaskChatItems", () => {
+ it("never tags posted comments interstitial — the run's final reply keeps its bubble", () => {
+ const comments = [
+ {
+ id: "c1",
+ body: "Here is the finished work.",
+ authorType: "agent",
+ authorAgentId: "agent-1",
+ runId: "run-1",
+ createdAt: "2026-07-31T12:00:10.000Z",
+ } as unknown as IssueChatComment,
+ ];
+ const items = commentsToTaskChatItems(comments);
+ expect(items).toHaveLength(1);
+ const item = items[0];
+ expect(item.kind).toBe("message");
+ if (item.kind !== "message") return;
+ expect(item.author).toBe("agent");
+ expect(item.interstitial).toBeUndefined();
+ });
+});
diff --git a/ui/src/components/task-chat/task-chat-adapter.ts b/ui/src/components/task-chat/task-chat-adapter.ts
index e77036ffd0..cc1bfb635e 100644
--- a/ui/src/components/task-chat/task-chat-adapter.ts
+++ b/ui/src/components/task-chat/task-chat-adapter.ts
@@ -34,7 +34,8 @@ function authorKind(comment: IssueChatComment): TaskChatAuthorKind {
return "system";
}
-function formatTimestamp(value: unknown): string | undefined {
+/** Shared bubble-footer time format ("2:34 PM") — also used by the description bubble (PAP-375). */
+export function formatTaskChatTimestamp(value: unknown): string | undefined {
if (!value) return undefined;
const d = value instanceof Date ? value : new Date(value as string);
if (Number.isNaN(d.getTime())) return undefined;
@@ -71,7 +72,7 @@ export function commentsToTaskChatItems(
author: kind,
authorName,
text: comment.body,
- timestamp: formatTimestamp(comment.createdAt),
+ timestamp: formatTaskChatTimestamp(comment.createdAt),
optimistic,
agentIcon,
modeLabel: kind === "agent" ? ctx.agentModeLabelFor?.(comment) : undefined,
diff --git a/ui/src/components/task-chat/task-chat-attachments.test.ts b/ui/src/components/task-chat/task-chat-attachments.test.ts
new file mode 100644
index 0000000000..9a7ee240cb
--- /dev/null
+++ b/ui/src/components/task-chat/task-chat-attachments.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it } from "vitest";
+import {
+ extractAttachmentRefs,
+ fileKindForName,
+ formatFileSize,
+ isImageFilename,
+} from "./task-chat-attachments";
+
+describe("fileKindForName", () => {
+ it("maps known extensions to kind labels", () => {
+ expect(fileKindForName("report.pdf").label).toBe("PDF");
+ expect(fileKindForName("data.csv").label).toBe("CSV");
+ expect(fileKindForName("bundle.zip").label).toBe("ZIP");
+ expect(fileKindForName("script.ts").label).toBe("Code");
+ });
+
+ it("falls back to File for unknown or missing extensions", () => {
+ expect(fileKindForName("mystery.xyz").label).toBe("File");
+ expect(fileKindForName("README").label).toBe("File");
+ });
+});
+
+describe("isImageFilename", () => {
+ it("detects image extensions case-insensitively", () => {
+ expect(isImageFilename("shot.PNG")).toBe(true);
+ expect(isImageFilename("photo.jpeg")).toBe(true);
+ expect(isImageFilename("notes.txt")).toBe(false);
+ });
+});
+
+describe("formatFileSize", () => {
+ it("formats byte tiers", () => {
+ expect(formatFileSize(512)).toBe("512 B");
+ expect(formatFileSize(2048)).toBe("2.0 KB");
+ expect(formatFileSize(3 * 1024 * 1024)).toBe("3.0 MB");
+ });
+
+ it("returns empty for missing or non-positive sizes", () => {
+ expect(formatFileSize(undefined)).toBe("");
+ expect(formatFileSize(0)).toBe("");
+ });
+});
+
+describe("extractAttachmentRefs", () => {
+ it("extracts attachment links and strips link-only lines", () => {
+ const body = "Here are the notes.\n\n[notes.txt](/api/attachments/abc/content) ";
+ const { refs, text } = extractAttachmentRefs(body);
+ expect(refs).toEqual([{ name: "notes.txt", url: "/api/attachments/abc/content" }]);
+ expect(text).toBe("Here are the notes.");
+ });
+
+ it("keeps links woven into prose while still chipping them", () => {
+ const body = "See [report.pdf](/api/attachments/r1/content) for details.";
+ const { refs, text } = extractAttachmentRefs(body);
+ expect(refs).toEqual([{ name: "report.pdf", url: "/api/attachments/r1/content" }]);
+ expect(text).toBe(body);
+ });
+
+ it("ignores image embeds and image-named links", () => {
+ const body =
+ "![shot.png](/api/attachments/img/content)\n[photo.jpg](/api/attachments/p/content)\n[notes.txt](/api/attachments/n/content)";
+ const { refs } = extractAttachmentRefs(body);
+ expect(refs).toEqual([{ name: "notes.txt", url: "/api/attachments/n/content" }]);
+ });
+
+ it("ignores non-attachment links entirely", () => {
+ const body = "[docs](https://example.com/content) and [PAP-1](/issues/PAP-1)";
+ const { refs, text } = extractAttachmentRefs(body);
+ expect(refs).toEqual([]);
+ expect(text).toBe(body);
+ });
+
+ it("dedupes repeated references to the same attachment", () => {
+ const body =
+ "[notes.txt](/api/attachments/n/content)\n[notes.txt](/api/attachments/n/content)";
+ const { refs, text } = extractAttachmentRefs(body);
+ expect(refs).toHaveLength(1);
+ expect(text).toBe("");
+ });
+
+ it("unescapes bracket-escaped labels and accepts asset content paths", () => {
+ const body = String.raw`[weird \[name\].txt](/api/assets/a1/content?download=1)`;
+ const { refs } = extractAttachmentRefs(body);
+ expect(refs).toEqual([
+ { name: "weird [name].txt", url: "/api/assets/a1/content?download=1" },
+ ]);
+ });
+});
diff --git a/ui/src/components/task-chat/task-chat-attachments.ts b/ui/src/components/task-chat/task-chat-attachments.ts
new file mode 100644
index 0000000000..5746cae43f
--- /dev/null
+++ b/ui/src/components/task-chat/task-chat-attachments.ts
@@ -0,0 +1,154 @@
+/**
+ * Attachment-chip helpers for the task-chat redesign (PAP-351): map a filename
+ * to a kind icon + label for the shadcn base/attachment chips, and extract the
+ * non-image file references the composer writes into message bodies
+ * ("[name](/api/attachments/<id>/content)") so posted bubbles can render them
+ * as the same chips instead of bare links.
+ */
+import {
+ FileArchive,
+ FileAudio,
+ FileCode,
+ FileSpreadsheet,
+ FileText,
+ FileVideo,
+ File as FileIcon,
+} from "lucide-react";
+import type { LucideIcon } from "lucide-react";
+
+export interface FileKind {
+ icon: LucideIcon;
+ /** Short kind label for the chip description, e.g. "PDF", "ZIP". */
+ label: string;
+}
+
+const IMAGE_EXTENSIONS = new Set([
+ "png",
+ "jpg",
+ "jpeg",
+ "gif",
+ "webp",
+ "svg",
+ "avif",
+ "bmp",
+ "ico",
+ "heic",
+]);
+
+const KIND_BY_EXTENSION: Record<string, FileKind> = {
+ pdf: { icon: FileText, label: "PDF" },
+ doc: { icon: FileText, label: "Doc" },
+ docx: { icon: FileText, label: "Doc" },
+ txt: { icon: FileText, label: "Text" },
+ md: { icon: FileText, label: "Markdown" },
+ rtf: { icon: FileText, label: "Text" },
+ csv: { icon: FileSpreadsheet, label: "CSV" },
+ tsv: { icon: FileSpreadsheet, label: "TSV" },
+ xls: { icon: FileSpreadsheet, label: "Sheet" },
+ xlsx: { icon: FileSpreadsheet, label: "Sheet" },
+ zip: { icon: FileArchive, label: "ZIP" },
+ gz: { icon: FileArchive, label: "Archive" },
+ tar: { icon: FileArchive, label: "Archive" },
+ tgz: { icon: FileArchive, label: "Archive" },
+ rar: { icon: FileArchive, label: "Archive" },
+ "7z": { icon: FileArchive, label: "Archive" },
+ mp3: { icon: FileAudio, label: "Audio" },
+ wav: { icon: FileAudio, label: "Audio" },
+ m4a: { icon: FileAudio, label: "Audio" },
+ ogg: { icon: FileAudio, label: "Audio" },
+ mp4: { icon: FileVideo, label: "Video" },
+ mov: { icon: FileVideo, label: "Video" },
+ webm: { icon: FileVideo, label: "Video" },
+ json: { icon: FileCode, label: "JSON" },
+ yaml: { icon: FileCode, label: "YAML" },
+ yml: { icon: FileCode, label: "YAML" },
+ xml: { icon: FileCode, label: "XML" },
+ html: { icon: FileCode, label: "HTML" },
+ css: { icon: FileCode, label: "CSS" },
+ js: { icon: FileCode, label: "Code" },
+ jsx: { icon: FileCode, label: "Code" },
+ ts: { icon: FileCode, label: "Code" },
+ tsx: { icon: FileCode, label: "Code" },
+ py: { icon: FileCode, label: "Code" },
+ rb: { icon: FileCode, label: "Code" },
+ go: { icon: FileCode, label: "Code" },
+ rs: { icon: FileCode, label: "Code" },
+ sh: { icon: FileCode, label: "Code" },
+ sql: { icon: FileCode, label: "SQL" },
+ log: { icon: FileText, label: "Log" },
+ patch: { icon: FileCode, label: "Patch" },
+ diff: { icon: FileCode, label: "Patch" },
+};
+
+function extensionOf(name: string): string {
+ const match = /\.([a-z0-9]+)$/i.exec(name.trim());
+ return match ? match[1].toLowerCase() : "";
+}
+
+export function isImageFilename(name: string): boolean {
+ return IMAGE_EXTENSIONS.has(extensionOf(name));
+}
+
+/** Kind icon + short label for a filename; unknown extensions get File/"File". */
+export function fileKindForName(name: string): FileKind {
+ return KIND_BY_EXTENSION[extensionOf(name)] ?? { icon: FileIcon, label: "File" };
+}
+
+/** "2.4 MB"-style size for chip descriptions (same tiers as IssueChatThread). */
+export function formatFileSize(bytes: number | undefined): string {
+ if (bytes === undefined || !Number.isFinite(bytes) || bytes <= 0) return "";
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+export interface AttachmentRef {
+ name: string;
+ url: string;
+}
+
+/**
+ * Markdown links (not `![]` embeds) pointing at attachment/asset content. The
+ * label admits backslash-escaped characters — the composer escapes `[`/`]` in
+ * filenames when inserting references.
+ */
+const ATTACHMENT_LINK_RE =
+ /(?<!!)\[((?:\\.|[^\]\\])+)\]\((\/api\/(?:attachments|assets)\/[^()\s]+\/content(?:\?[^()\s]*)?)\)/g;
+
+export interface ExtractedAttachmentRefs {
+ refs: AttachmentRef[];
+ /** Body with lines that were nothing but extracted links removed. */
+ text: string;
+}
+
+/**
+ * Pull non-image attachment references out of a message body. Every matching
+ * link becomes a chip; a line is stripped from the rendered body only when it
+ * contains nothing but extracted links (the shape the composer inserts), so
+ * links woven into prose keep their sentence.
+ */
+export function extractAttachmentRefs(body: string): ExtractedAttachmentRefs {
+ const refs: AttachmentRef[] = [];
+ const seen = new Set<string>();
+ for (const match of body.matchAll(ATTACHMENT_LINK_RE)) {
+ const [, name, url] = match;
+ if (isImageFilename(name) || isImageFilename(url.split("?")[0])) continue;
+ if (seen.has(url)) continue;
+ seen.add(url);
+ refs.push({ name: name.replace(/\\([[\]])/g, "$1"), url });
+ }
+ if (refs.length === 0) return { refs, text: body };
+
+ const kept = body.split("\n").filter((line) => {
+ const withoutLinks = line.replace(ATTACHMENT_LINK_RE, (full, name: string, url: string) => {
+ return seen.has(url) ? "" : full;
+ });
+ return withoutLinks.trim().length > 0 || line.trim().length === 0;
+ });
+ // Collapse the blank run left behind where a link-only line was removed.
+ const text = kept
+ .join("\n")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+ return { refs, text };
+}
diff --git a/ui/src/components/task-chat/task-chat-fixtures.ts b/ui/src/components/task-chat/task-chat-fixtures.ts
index 9d95d638d4..fd332908f7 100644
--- a/ui/src/components/task-chat/task-chat-fixtures.ts
+++ b/ui/src/components/task-chat/task-chat-fixtures.ts
@@ -54,19 +54,79 @@ export function buildScenario(id: TaskChatStateId): TaskChatScenario {
],
};
case "thinking":
+ // The surviving thinking signal (PAP-361): the live line's "Thinking…"
+ // state — Brain icon + shimmer on the pill. Thinking rows no longer
+ // render in the thread or nest under turns.
return {
surface: "thread",
items: [
...exchangePrefix(),
- { id: "th-1", kind: "thinking", streaming: true, lines: ["The login route is in server/src/routes/auth.ts.", "There's already an ipRateLimit helper I can reuse.", "I'll add a per-account bucket keyed on the email."] },
+ {
+ id: "turn-thinking",
+ kind: "turn",
+ settled: false,
+ summary: { toolCount: 1, added: 0, removed: 0 },
+ liveStatus: { id: "st-thinking", kind: "status", status: "running", label: "Thinking", startedAtMs: Date.now() - 6100, tokens: { used: 18240, size: 200000 } },
+ items: [
+ { id: "th-grep", kind: "tool", name: "Grep", target: "rateLimit", toolKind: "search", status: "completed" },
+ ],
+ },
],
};
case "responding":
+ // A streaming interstitial update gets its own row directly above the
+ // status line (PAP-361, amended): it wraps into the 1lh viewport
+ // line-scroll while the gerund rotation below runs uninterrupted.
+ // Ephemeral — when it finishes, the row slides out and the text renders
+ // nowhere.
+ return {
+ surface: "thread",
+ items: [
+ ...exchangePrefix(),
+ {
+ id: "turn-responding",
+ kind: "turn",
+ settled: false,
+ summary: { toolCount: 1, added: 0, removed: 0 },
+ liveStatus: {
+ id: "st-responding", kind: "status", status: "running", label: "Responding", startedAtMs: Date.now() - 9300, tokens: { used: 18240, size: 200000 },
+ selfTalk:
+ "I found an existing ipRateLimit helper, so I'll extend it with a per-account token bucket keyed on the email address instead of adding a second limiter. The bucket refills at six requests a minute, matching the lockout policy the auth spec documents, and failed attempts drain it twice as fast so brute-force runs hit the ceiling quickly while a fat-fingered password barely registers.",
+ },
+ items: [
+ { id: "resp-read", kind: "tool", name: "Read", target: "server/src/routes/auth.ts", toolKind: "read", status: "completed" },
+ ],
+ },
+ ],
+ };
+ case "responding-burst":
+ // A run emitting several interstitial updates in quick succession
+ // (PAP-368): the lab replay streams each blank-line-separated segment as
+ // its own update with a short gap between. The pill HOLDS each finished
+ // update until the next swaps in, paced by --motion-interstitial-dwell
+ // (latest-wins when updates outpace the dwell).
return {
surface: "thread",
items: [
...exchangePrefix(),
- { id: "m-agent-stream", kind: "message", author: "agent", authorName: AGENT, streaming: true, text: "I found an existing ipRateLimit helper, so I'll extend it with a per-account bucket and" },
+ {
+ id: "turn-responding-burst",
+ kind: "turn",
+ settled: false,
+ summary: { toolCount: 2, added: 0, removed: 0 },
+ liveStatus: {
+ id: "st-responding-burst", kind: "status", status: "running", label: "Responding", startedAtMs: Date.now() - 21400, tokens: { used: 18240, size: 200000 },
+ selfTalk:
+ "Found the existing ipRateLimit helper — extending it beats adding a second limiter.\n\n" +
+ "Wiring a per-account token bucket keyed on the email address, refilling at six requests a minute per the auth spec.\n\n" +
+ "Failed attempts drain the bucket twice as fast, so brute-force runs hit the ceiling while a fat-fingered password barely registers.\n\n" +
+ "Now updating the login route to consume from the bucket before the password check and adding tests for the lockout path.",
+ },
+ items: [
+ { id: "burst-read", kind: "tool", name: "Read", target: "server/src/routes/auth.ts", toolKind: "read", status: "completed" },
+ { id: "burst-grep", kind: "tool", name: "Grep", target: "ipRateLimit", toolKind: "search", status: "completed" },
+ ],
+ },
],
};
case "tool-call":
@@ -96,17 +156,41 @@ export function buildScenario(id: TaskChatStateId): TaskChatScenario {
],
};
case "working":
+ // Parent-row live turn (PAP-354): the tool-state line owns the activity;
+ // expanding nests the chronological history underneath.
return {
surface: "thread",
items: [
- { id: "st-working", kind: "status", status: "working", label: "Editing files", detail: "Edit · server/src/routes/auth.ts", toolName: "Edit", startedAtMs: Date.now() - 4200 },
+ ...exchangePrefix(),
+ {
+ id: "turn-working",
+ kind: "turn",
+ settled: false,
+ summary: { toolCount: 2, added: 0, removed: 0 },
+ liveStatus: { id: "st-working", kind: "status", status: "working", label: "Editing files", detail: "Edit · server/src/routes/auth.ts", toolName: "Edit", startedAtMs: Date.now() - 4200 },
+ items: [
+ { id: "w-read", kind: "tool", name: "Read", target: "server/src/routes/auth.ts", toolKind: "read", status: "completed" },
+ { id: "w-edit", kind: "tool", name: "Edit", target: "server/src/routes/auth.ts", toolKind: "edit", status: "in_progress" },
+ ],
+ },
],
};
case "running":
+ // Generic label → the parent row header rotates whimsical gerunds.
return {
surface: "thread",
items: [
- { id: "st-running", kind: "status", status: "running", label: "Running", detail: "no output for 3s — still running", startedAtMs: Date.now() - 12000, tokens: { used: 18240, size: 200000 } },
+ ...exchangePrefix(),
+ {
+ id: "turn-running",
+ kind: "turn",
+ settled: false,
+ summary: { toolCount: 1, added: 0, removed: 0 },
+ liveStatus: { id: "st-running", kind: "status", status: "running", label: "Running", detail: "no output for 3s — still running", startedAtMs: Date.now() - 12000, tokens: { used: 18240, size: 200000 } },
+ items: [
+ { id: "r-grep", kind: "tool", name: "Grep", target: "rateLimit", toolKind: "search", status: "completed" },
+ ],
+ },
],
};
case "completed":
@@ -114,18 +198,31 @@ export function buildScenario(id: TaskChatStateId): TaskChatScenario {
surface: "thread",
items: [
...exchangePrefix(),
+ // Round 9: the settled turn attaches to the final reply bubble — the
+ // "✓ Worked · …" summary renders on the bubble's always-visible
+ // timestamp line ("2:34 PM · ✓ Worked · 38s · 2 tools").
{
- id: "turn-done",
- kind: "turn",
- settled: true,
- summary: { durationLabel: "38s", toolCount: 3, added: 34, removed: 3, tokensLabel: "12.3k tokens" },
- items: [
- { id: "th-done", kind: "thinking", lines: ["Read auth.ts", "Added rate-limiter util", "Wired into POST /login"] },
- { id: "tool-done-1", kind: "tool", name: "Read", target: "server/src/routes/auth.ts", toolKind: "read", status: "completed" },
- { id: "tool-done-2", kind: "tool", name: "Edit", target: "server/src/routes/auth.ts", toolKind: "edit", status: "completed", diff: { path: "server/src/routes/auth.ts", added: 34, removed: 3 } },
- ],
+ id: "m-done",
+ kind: "message",
+ author: "agent",
+ authorName: AGENT,
+ agentIcon: "bot",
+ modeLabel: "Agent mode",
+ text: "Done — added a per-account token-bucket limiter and wired it into the login route. Tests pass.",
+ timestamp: "2:34 PM",
+ attachedTurn: {
+ id: "turn-done",
+ kind: "turn",
+ settled: true,
+ // "Worked · N tools" expands to exactly the tool rows (PAP-361):
+ // toolCount matches the nested rows, no thinking row.
+ summary: { durationLabel: "38s", toolCount: 2, added: 34, removed: 3, tokensLabel: "12.3k tokens" },
+ items: [
+ { id: "tool-done-1", kind: "tool", name: "Read", target: "server/src/routes/auth.ts", toolKind: "read", status: "completed" },
+ { id: "tool-done-2", kind: "tool", name: "Edit", target: "server/src/routes/auth.ts", toolKind: "edit", status: "completed", diff: { path: "server/src/routes/auth.ts", added: 34, removed: 3 } },
+ ],
+ },
},
- { id: "m-done", kind: "message", author: "agent", authorName: AGENT, agentIcon: "bot", modeLabel: "Agent mode", text: "Done — added a per-account token-bucket limiter and wired it into the login route. Tests pass.", timestamp: "2:34 PM" },
],
};
case "awaiting-approval":
diff --git a/ui/src/components/task-chat/task-chat-model.ts b/ui/src/components/task-chat/task-chat-model.ts
index ad3e4c105e..00d99f35ad 100644
--- a/ui/src/components/task-chat/task-chat-model.ts
+++ b/ui/src/components/task-chat/task-chat-model.ts
@@ -76,6 +76,24 @@ export interface TaskChatMessageItem {
modeLabel?: string;
/** Assigned agent icon name (AgentIconName) for the avatar header. */
agentIcon?: string | null;
+ /**
+ * Agent text streamed inside a run turn (interstitial updates between tool
+ * calls). Ephemeral in the redesigned view (PAP-361): while streaming it
+ * takes the live parent row's line (TaskChatStatusItem.selfTalk); once
+ * finished it renders nowhere — the run log / classic transcript remain the
+ * archive. Tagged for live and settled transcripts alike.
+ */
+ interstitial?: boolean;
+ /** Epoch ms of the message's first streamed chunk. */
+ atMs?: number;
+ /**
+ * The settled run turn "attached" to this bubble (round 9): when the run's
+ * final reply lands, the live parent row transforms into the "Worked · …"
+ * summary rendered on this bubble's always-visible timestamp line —
+ * "2:34 PM · ✓ Worked · 38s · 3 tools" — instead of a standalone row.
+ * Expanding still nests the tool history beneath the bubble.
+ */
+ attachedTurn?: TaskChatTurnItem;
}
/** Collapsed chain-of-thought (ACP agent_thought_chunk). */
@@ -130,6 +148,17 @@ export interface TaskChatStatusItem {
detail?: string;
/** Raw tool name of the in-flight tail tool_call (drives the pill's icon). */
toolName?: string;
+ /**
+ * Flattened plain text of the interstitial update currently streaming
+ * (PAP-361, round 9): it renders in a dedicated single-line row directly
+ * above the status line — a slot PERMANENTLY RESERVED while the turn is
+ * live, so the layout above never jumps — inside a one-line viewport
+ * showing the streaming tail line; the gerund rotation below runs
+ * uninterrupted. When the message finishes the pill HOLDS the text as a
+ * static ellipsized line until the next update supersedes it or the turn
+ * ends (PAP-368) — nothing persists in the settled thread.
+ */
+ selfTalk?: string;
elapsedMs?: number;
/** Run start epoch ms; live states tick their own elapsed from this. */
startedAtMs?: number;
@@ -154,6 +183,18 @@ export interface TaskChatUsageItem {
usage: TaskChatTokenUsage;
}
+/**
+ * The task description rendered as the requester's first chat bubble
+ * (PAP-375). A placeholder kind only — the host supplies the render
+ * (TaskChatThread binds TaskChatDescriptionBubble to the live issue), mirroring
+ * how interaction items defer to renderInteraction. Always prepended AFTER
+ * thread assembly, so no backbone entry or settled turn can sort above it.
+ */
+export interface TaskChatBriefItem {
+ id: string;
+ kind: "brief";
+}
+
/**
* An issue-thread interaction (plan confirmation, question card, suggested
* tasks…) interleaved chronologically into the thread. The payload is the
@@ -178,15 +219,23 @@ export type TaskChatTurnChildItem =
/**
* One agent turn's activity (thinking/tools/diffs) grouped so a finished turn
* can fold into a one-line expandable summary ("✓ Worked · 38s · 3 tools ·
- * +34 −3"). While `settled` is false the children render fully interleaved;
- * on the live → settled transition the fold animates (~ --motion-turn-fold),
- * while turns that load already-settled collapse instantly.
+ * +34 −3"). A live turn carrying `liveStatus` renders as a single expandable
+ * parent row headed by that status line (gerund/tool-state + elapsed +
+ * tokens); expanding nests the chronological activity underneath, and on
+ * settle the header morphs in place into the summary. The live → settled
+ * fold animates (~ --motion-turn-fold), while turns that load already-settled
+ * collapse instantly.
*/
export interface TaskChatTurnItem {
id: string;
kind: "turn";
items: TaskChatTurnChildItem[];
settled: boolean;
+ /**
+ * The in-flight run's status line, hoisted to be THE turn's single visible
+ * row while collapsed (PAP-354 parent-row model). Absent once settled.
+ */
+ liveStatus?: TaskChatStatusItem;
/** Animate the fold when settling (false = collapse instantly, e.g. history). */
animateFold?: boolean;
summary: {
@@ -210,7 +259,8 @@ export type TaskChatItem =
| TaskChatMarkerItem
| TaskChatUsageItem
| TaskChatInteractionItem
- | TaskChatTurnItem;
+ | TaskChatTurnItem
+ | TaskChatBriefItem;
/** A structured plan entry (ACP PlanEntry) for the Plans tab. */
export interface TaskChatPlanEntry {
diff --git a/ui/src/components/task-chat/task-chat-states.ts b/ui/src/components/task-chat/task-chat-states.ts
index fbdcd58869..01fafc2d45 100644
--- a/ui/src/components/task-chat/task-chat-states.ts
+++ b/ui/src/components/task-chat/task-chat-states.ts
@@ -18,6 +18,7 @@ export const TASK_CHAT_STATES = [
"agent-message",
"thinking",
"responding",
+ "responding-burst",
"tool-call",
"diff",
"working",
@@ -81,6 +82,13 @@ export const TASK_CHAT_STATE_META: Record<TaskChatStateId, TaskChatStateMeta> =
surface: "thread",
protocol: "text_delta stream:output, streaming",
},
+ "responding-burst": {
+ id: "responding-burst",
+ label: "Responding (update burst)",
+ tier: "live",
+ surface: "thread",
+ protocol: "text_delta stream:output ×N, tool calls between (PAP-368 dwell)",
+ },
"tool-call": {
id: "tool-call",
label: "Tool call",
diff --git a/ui/src/components/task-chat/tool-taxonomy.test.ts b/ui/src/components/task-chat/tool-taxonomy.test.ts
index 52f9fb09c0..0758e1986f 100644
--- a/ui/src/components/task-chat/tool-taxonomy.test.ts
+++ b/ui/src/components/task-chat/tool-taxonomy.test.ts
@@ -1,31 +1,38 @@
import { describe, expect, it } from "vitest";
import {
BookOpen,
- Bot,
- FileSearch,
- Globe,
- Pencil,
- Plug,
- SquareTerminal,
+ Brain,
+ ChevronsLeftRightEllipsis,
+ MessageSquareReply,
+ Network,
+ Search,
+ SearchCode,
+ Terminal,
Wrench,
} from "lucide-react";
-import { isGenericToolName, mcpToolSegment, toolTaxonomy } from "./tool-taxonomy";
+import { McpIcon } from "./McpIcon";
+import { isGenericToolName, mcpToolSegment, statusLabelIcon, toolTaxonomy } from "./tool-taxonomy";
describe("toolTaxonomy", () => {
it("maps each family to its icon and verb", () => {
expect(toolTaxonomy("Bash")).toEqual({
family: "terminal",
- icon: SquareTerminal,
+ icon: Terminal,
verbLabel: "Running a command",
});
expect(toolTaxonomy("Shell").family).toBe("terminal");
expect(toolTaxonomy("Grep")).toEqual({
+ family: "grep",
+ icon: SearchCode,
+ verbLabel: "Grepping",
+ });
+
+ expect(toolTaxonomy("Glob")).toEqual({
family: "search",
- icon: FileSearch,
+ icon: Search,
verbLabel: "Searching",
});
- expect(toolTaxonomy("Glob").family).toBe("search");
expect(toolTaxonomy("WebSearch").family).toBe("search");
expect(toolTaxonomy("Read")).toEqual({
@@ -35,9 +42,10 @@ describe("toolTaxonomy", () => {
});
expect(toolTaxonomy("NotebookRead").family).toBe("read");
+ // Round-4 board feedback: edits share the terminal glyph.
expect(toolTaxonomy("Edit")).toEqual({
family: "edit",
- icon: Pencil,
+ icon: Terminal,
verbLabel: "Editing files",
});
expect(toolTaxonomy("Write").family).toBe("edit");
@@ -46,22 +54,22 @@ describe("toolTaxonomy", () => {
expect(toolTaxonomy("WebFetch")).toEqual({
family: "web",
- icon: Globe,
+ icon: ChevronsLeftRightEllipsis,
verbLabel: "Fetching the web",
});
expect(toolTaxonomy("Task")).toEqual({
family: "agent",
- icon: Bot,
+ icon: Network,
verbLabel: "Delegating",
});
expect(toolTaxonomy("Agent").family).toBe("agent");
});
- it("collapses mcp__ names to a Plug entry with the tool segment verb", () => {
+ it("collapses mcp__ names to the MCP logo with the tool segment verb", () => {
const entry = toolTaxonomy("mcp__linear-server__search_issues");
expect(entry.family).toBe("mcp");
- expect(entry.icon).toBe(Plug);
+ expect(entry.icon).toBe(McpIcon);
expect(entry.verbLabel).toBe("Using Search_issues");
});
@@ -80,9 +88,23 @@ describe("toolTaxonomy", () => {
describe("toolTaxonomy multi-word ACP titles", () => {
it("classifies by the first word", () => {
expect(toolTaxonomy("Read File").icon).toBe(BookOpen);
- expect(toolTaxonomy("Edit File").icon).toBe(Pencil);
- expect(toolTaxonomy("Write File").icon).toBe(Pencil);
- expect(toolTaxonomy("Terminal").icon).toBe(SquareTerminal);
+ expect(toolTaxonomy("Edit File").icon).toBe(Terminal);
+ expect(toolTaxonomy("Write File").icon).toBe(Terminal);
+ expect(toolTaxonomy("Terminal").icon).toBe(Terminal);
+ });
+});
+
+describe("statusLabelIcon", () => {
+ it("gives the tool-free informative statuses their glyphs", () => {
+ expect(statusLabelIcon("Thinking")).toBe(Brain);
+ expect(statusLabelIcon("Responding")).toBe(MessageSquareReply);
+ expect(statusLabelIcon("Responding (streaming)")).toBe(MessageSquareReply);
+ });
+
+ it("leaves whimsified and generic labels glyph-free", () => {
+ for (const label of ["Running", "Working", "Clipping", "Brewing", "Queued", "", undefined, null]) {
+ expect(statusLabelIcon(label)).toBeNull();
+ }
});
});
diff --git a/ui/src/components/task-chat/tool-taxonomy.ts b/ui/src/components/task-chat/tool-taxonomy.ts
index 6ea54e8173..c9ee6579f7 100644
--- a/ui/src/components/task-chat/tool-taxonomy.ts
+++ b/ui/src/components/task-chat/tool-taxonomy.ts
@@ -7,18 +7,24 @@
*/
import {
BookOpen,
- Bot,
- FileSearch,
- Globe,
- Pencil,
- Plug,
- SquareTerminal,
+ Brain,
+ ChevronsLeftRightEllipsis,
+ MessageSquareReply,
+ Network,
+ Search,
+ SearchCode,
+ Terminal,
Wrench,
} from "lucide-react";
-import type { LucideIcon } from "lucide-react";
+import type { ComponentType, SVGProps } from "react";
+import { McpIcon } from "./McpIcon";
+
+/** Lucide icons and hand-rolled SVGs (the MCP logo) share this shape. */
+export type ToolIcon = ComponentType<SVGProps<SVGSVGElement>>;
export type ToolFamily =
| "terminal"
+ | "grep"
| "search"
| "read"
| "edit"
@@ -29,7 +35,7 @@ export type ToolFamily =
export interface ToolTaxonomyEntry {
family: ToolFamily;
- icon: LucideIcon;
+ icon: ToolIcon;
/** Progressive verb for the status pill, without the trailing ellipsis. */
verbLabel: string;
}
@@ -63,12 +69,14 @@ export function mcpToolSegment(name: string): string | null {
}
const FAMILY_META: Record<Exclude<ToolFamily, "mcp">, Omit<ToolTaxonomyEntry, "family">> = {
- terminal: { icon: SquareTerminal, verbLabel: "Running a command" },
- search: { icon: FileSearch, verbLabel: "Searching" },
+ terminal: { icon: Terminal, verbLabel: "Running a command" },
+ grep: { icon: SearchCode, verbLabel: "Grepping" },
+ search: { icon: Search, verbLabel: "Searching" },
read: { icon: BookOpen, verbLabel: "Reading files" },
- edit: { icon: Pencil, verbLabel: "Editing files" },
- web: { icon: Globe, verbLabel: "Fetching the web" },
- agent: { icon: Bot, verbLabel: "Delegating" },
+ // Board round-4 feedback asked for the terminal glyph on edits as well.
+ edit: { icon: Terminal, verbLabel: "Editing files" },
+ web: { icon: ChevronsLeftRightEllipsis, verbLabel: "Fetching the web" },
+ agent: { icon: Network, verbLabel: "Delegating" },
other: { icon: Wrench, verbLabel: "Working" },
};
@@ -83,7 +91,10 @@ function classify(n: string): Exclude<ToolFamily, "mcp"> {
if (first === "bash" || first === "shell" || first === "run" || n.includes("terminal")) {
return "terminal";
}
- if (first === "grep" || first === "glob" || n.includes("search")) return "search";
+ // Content grep is its own action (search-code glyph); file-name globbing and
+ // generic searches stay under the plain Search family.
+ if (first === "grep") return "grep";
+ if (first === "glob" || n.includes("search")) return "search";
if (n.includes("fetch") || n.includes("web") || n.includes("http")) return "web";
if (first === "task" || first === "agent") return "agent";
return "other";
@@ -94,7 +105,19 @@ export function toolTaxonomy(name: string | undefined | null): ToolTaxonomyEntry
const raw = (name ?? "").trim();
if (!raw) return { family: "other", ...FAMILY_META.other };
const mcpTool = mcpToolSegment(raw);
- if (mcpTool) return { family: "mcp", icon: Plug, verbLabel: `Using ${mcpTool}` };
+ if (mcpTool) return { family: "mcp", icon: McpIcon, verbLabel: `Using ${mcpTool}` };
const family = classify(raw.toLowerCase());
return { family, ...FAMILY_META[family] };
}
+
+/**
+ * Icons for the tool-free informative statuses ("Thinking", "Responding",
+ * "Responding (streaming)"). Whimsified and generic labels get no glyph — the
+ * pulse dot alone carries those.
+ */
+export function statusLabelIcon(label: string | undefined | null): ToolIcon | null {
+ const raw = (label ?? "").trim().toLowerCase();
+ if (raw === "thinking") return Brain;
+ if (raw === "responding" || raw.startsWith("responding (")) return MessageSquareReply;
+ return null;
+}
diff --git a/ui/src/components/task-chat/transcript-adapter.test.ts b/ui/src/components/task-chat/transcript-adapter.test.ts
index 8a64d06d52..674656eb2d 100644
--- a/ui/src/components/task-chat/transcript-adapter.test.ts
+++ b/ui/src/components/task-chat/transcript-adapter.test.ts
@@ -1,11 +1,23 @@
import { describe, expect, it } from "vitest";
import type { TranscriptEntry } from "@/adapters";
import {
+ assembleThreadItems,
+ attachSettledTurns,
+ buildMergedTurnSummary,
buildTurnSummary,
+ coalesceSettledTurns,
deriveRunStatusLabel,
+ flattenSelfTalk,
+ isNestableLiveChild,
+ ISSUE_BRIEF_ITEM_ID,
+ prependIssueBrief,
+ settledRunChildren,
toolDisplayName,
transcriptToTaskChatItems,
+ type SettledTurnMergeMeta,
+ type ThreadBackboneEntry,
} from "./transcript-adapter";
+import type { TaskChatItem, TaskChatTurnItem } from "./task-chat-model";
const TS = "2026-07-31T12:00:00.000Z";
@@ -16,7 +28,7 @@ function toolCall(name: string, input?: unknown): TranscriptEntry {
describe("deriveRunStatusLabel", () => {
it("labels a tail tool_call with the taxonomy verb and tool · target detail", () => {
const status = deriveRunStatusLabel([toolCall("Grep", { pattern: "ui/src/components" })]);
- expect(status.label).toBe("Searching");
+ expect(status.label).toBe("Grepping");
expect(status.detail).toBe("Grep · ui/src/components");
expect(status.toolName).toBe("Grep");
});
@@ -208,3 +220,475 @@ describe("deriveRunStatusLabel with generic tail updates", () => {
expect(status.detail).toBe("Terminal · pnpm test");
});
});
+
+describe("isNestableLiveChild", () => {
+ const items: TaskChatItem[] = [
+ { id: "t", kind: "tool", name: "Read", status: "completed" },
+ { id: "th", kind: "thinking", lines: ["hm"] },
+ { id: "u", kind: "usage", usage: { used: 1, size: 2 } },
+ { id: "m", kind: "message", author: "agent", text: "finished self-talk", interstitial: true },
+ { id: "mk", kind: "marker", variant: "session_start", label: "Session started" },
+ { id: "s", kind: "status", status: "running", label: "Running" },
+ { id: "i", kind: "interaction", interaction: {} as never },
+ ];
+
+ it("nests only tool and usage rows inside the live parent row (PAP-361)", () => {
+ expect(items.filter(isNestableLiveChild).map((it) => it.kind)).toEqual([
+ "tool",
+ "usage",
+ ]);
+ });
+
+ it("keeps messages, thinking, markers, statuses and interactions out", () => {
+ // Interstitial updates — finished or streaming — never nest: they are
+ // ephemeral, living on the live line only while streaming. Thinking never
+ // nests either (its live signal is the pill's "Thinking…" state), and the
+ // final reply keeps its bubble.
+ for (const kind of ["message", "thinking", "marker", "status", "interaction"]) {
+ const item = items.find((it) => it.kind === kind)!;
+ expect(isNestableLiveChild(item)).toBe(false);
+ }
+ expect(
+ isNestableLiveChild({
+ id: "m2",
+ kind: "message",
+ author: "agent",
+ text: "typing…",
+ interstitial: true,
+ streaming: true,
+ }),
+ ).toBe(false);
+ expect(
+ isNestableLiveChild({ id: "m3", kind: "message", author: "agent", text: "Final reply." }),
+ ).toBe(false);
+ });
+});
+
+describe("interstitial self-talk classification (PAP-355)", () => {
+ const stream: TranscriptEntry[] = [
+ { kind: "assistant", ts: TS, text: "Let me check the adapter." } as TranscriptEntry,
+ toolCall("Read", { file_path: "a.ts" }),
+ { kind: "assistant", ts: "2026-07-31T12:00:05.000Z", text: "Found it — fixing now." } as TranscriptEntry,
+ ];
+
+ it("tags agent messages streamed inside a live run turn as interstitial", () => {
+ const messages = transcriptToTaskChatItems(stream, { runId: "run-1", running: true }).filter(
+ (it) => it.kind === "message",
+ );
+ expect(messages).toHaveLength(2);
+ for (const m of messages) {
+ if (m.kind !== "message") continue;
+ expect(m.interstitial).toBe(true);
+ }
+ });
+
+ it("marks only the message still open at the tail as streaming", () => {
+ const items = transcriptToTaskChatItems(stream, { runId: "run-1", running: true });
+ const messages = items.filter((it) => it.kind === "message");
+ if (messages[0].kind !== "message" || messages[1].kind !== "message") return;
+ // The first message was closed by the tool call — finished self-talk.
+ expect(messages[0].streaming).toBe(false);
+ expect(messages[1].streaming).toBe(true);
+ });
+
+ it("marks no message streaming when the tail is a tool call", () => {
+ const items = transcriptToTaskChatItems(
+ [...stream, toolCall("Bash", { command: "pnpm test" })],
+ { runId: "run-1", running: true },
+ );
+ for (const m of items) {
+ if (m.kind === "message") expect(m.streaming).toBe(false);
+ }
+ });
+
+ it("tags settled-history messages interstitial too, so live and history agree", () => {
+ const messages = transcriptToTaskChatItems(stream, { runId: "run-1", running: false }).filter(
+ (it) => it.kind === "message",
+ );
+ expect(messages).toHaveLength(2);
+ for (const m of messages) {
+ if (m.kind !== "message") continue;
+ expect(m.interstitial).toBe(true);
+ expect(m.streaming).toBe(false);
+ }
+ });
+
+ it("stamps atMs from the first streamed chunk", () => {
+ const messages = transcriptToTaskChatItems(stream, { runId: "run-1", running: false }).filter(
+ (it) => it.kind === "message",
+ );
+ if (messages[0].kind !== "message" || messages[1].kind !== "message") return;
+ expect(messages[0].atMs).toBe(Date.parse(TS));
+ expect(messages[1].atMs).toBe(Date.parse("2026-07-31T12:00:05.000Z"));
+ });
+});
+
+describe("flattenSelfTalk", () => {
+ it("strips markdown markers to one plain line", () => {
+ expect(
+ flattenSelfTalk("## Plan\n\nI'll **extend** the `ipRateLimit` helper:\n- read it\n- patch it"),
+ ).toBe("Plan I'll extend the ipRateLimit helper: read it patch it");
+ });
+
+ it("keeps link text, drops the url, and is stream-safe on unclosed markers", () => {
+ expect(flattenSelfTalk("see [the docs](https://x) for **bol")).toBe("see the docs for bol");
+ expect(flattenSelfTalk("```ts\nconst a = 1;")).toBe("const a = 1;");
+ });
+});
+
+describe("deriveRunStatusLabel streaming interstitial text (PAP-361)", () => {
+ it("returns the trailing message's flattened text with the Responding label", () => {
+ const status = deriveRunStatusLabel([
+ { kind: "assistant", ts: TS, text: "I'll **extend** " } as TranscriptEntry,
+ { kind: "assistant", ts: TS, text: "the `ipRateLimit` helper." } as TranscriptEntry,
+ ]);
+ expect(status.label).toBe("Responding");
+ expect(status.selfTalk).toBe("I'll extend the ipRateLimit helper.");
+ expect(status.detail).toBeUndefined();
+ });
+
+ it("only accumulates the trailing message, not one closed by a tool call", () => {
+ const status = deriveRunStatusLabel([
+ { kind: "assistant", ts: TS, text: "Earlier note." } as TranscriptEntry,
+ toolCall("Read", { file_path: "a.ts" }),
+ { kind: "assistant", ts: TS, text: "Fresh line." } as TranscriptEntry,
+ ]);
+ expect(status.selfTalk).toBe("Fresh line.");
+ });
+
+ it("carries no selfTalk for tool or thinking tails", () => {
+ expect(deriveRunStatusLabel([toolCall("Read")]).selfTalk).toBeUndefined();
+ expect(
+ deriveRunStatusLabel([{ kind: "thinking", ts: TS, text: "hm" } as TranscriptEntry]).selfTalk,
+ ).toBeUndefined();
+ expect(deriveRunStatusLabel([]).selfTalk).toBeUndefined();
+ });
+});
+
+describe("settledRunChildren (PAP-361)", () => {
+ const transcript: TranscriptEntry[] = [
+ { kind: "assistant", ts: TS, text: "Checking the adapter first." } as TranscriptEntry,
+ toolCall("Read", { file_path: "a.ts" }),
+ { kind: "thinking", ts: TS, text: "wire it in" } as TranscriptEntry,
+ toolCall("Edit", { file_path: "a.ts" }),
+ { kind: "assistant", ts: TS, text: "Done — the limiter is wired in." } as TranscriptEntry,
+ ];
+ const parsed = transcriptToTaskChatItems(transcript, { runId: "run-1", running: false });
+
+ it("keeps exactly the tool rows — messages AND thinking are excluded", () => {
+ const children = settledRunChildren(parsed);
+ expect(children.map((c) => c.kind)).toEqual(["tool", "tool"]);
+ });
+
+ it("matches the folded summary's tool count exactly (row-count parity)", () => {
+ const children = settledRunChildren(parsed);
+ const summary = buildTurnSummary(transcript);
+ expect(children.filter((c) => c.kind === "tool")).toHaveLength(summary.toolCount);
+ });
+});
+
+describe("buildMergedTurnSummary (PAP-362)", () => {
+ const runA: TranscriptEntry[] = [
+ { kind: "tool_call", ts: "2026-07-31T12:00:00.000Z", name: "Read", toolUseId: "a-1" } as TranscriptEntry,
+ { kind: "tool_call", ts: "2026-07-31T12:00:05.000Z", name: "Edit", toolUseId: "a-2" } as TranscriptEntry,
+ { kind: "diff", ts: "2026-07-31T12:00:06.000Z", changeType: "add", text: "+x" } as TranscriptEntry,
+ { kind: "result", ts: "2026-07-31T12:00:10.000Z", inputTokens: 500, outputTokens: 300 } as TranscriptEntry,
+ ];
+ const runB: TranscriptEntry[] = [
+ { kind: "tool_call", ts: "2026-07-31T12:30:00.000Z", name: "Bash", toolUseId: "b-1" } as TranscriptEntry,
+ { kind: "result", ts: "2026-07-31T12:30:05.000Z", inputTokens: 300, outputTokens: 100 } as TranscriptEntry,
+ ];
+
+ it("sums tool count, diffs, tokens, and duration across runs", () => {
+ const summary = buildMergedTurnSummary([
+ { entries: runA, durationMs: 30_000 },
+ { entries: runB, durationMs: 15_000 },
+ ]);
+ expect(summary.toolCount).toBe(3);
+ expect(summary.added).toBe(1);
+ expect(summary.tokensLabel).toBe("1.2k tokens");
+ expect(summary.durationLabel).toBe("45s");
+ expect(summary.failed).toBeUndefined();
+ });
+
+ it("sums per-run ts spans — never the idle gap between runs", () => {
+ // runA spans 10s, runB spans 5s, the gap between them is ~30min.
+ const summary = buildMergedTurnSummary([{ entries: runA }, { entries: runB }]);
+ expect(summary.durationLabel).toBe("15s");
+ });
+
+ it("marks the merged turn failed when any run failed", () => {
+ const summary = buildMergedTurnSummary([
+ { entries: runA, durationMs: 1000 },
+ { entries: runB, durationMs: 1000, failed: true },
+ ]);
+ expect(summary.failed).toBe(true);
+ });
+});
+
+describe("coalesceSettledTurns (PAP-362)", () => {
+ const runA: TranscriptEntry[] = [
+ { kind: "tool_call", ts: TS, name: "Read", toolUseId: "a-1" } as TranscriptEntry,
+ { kind: "tool_call", ts: TS, name: "Edit", toolUseId: "a-2" } as TranscriptEntry,
+ ];
+ const runB: TranscriptEntry[] = [
+ { kind: "tool_call", ts: TS, name: "Bash", toolUseId: "b-1" } as TranscriptEntry,
+ ];
+
+ function agentBubble(id: string): TaskChatItem {
+ return { id, kind: "message", author: "agent", authorName: "CEO", text: "Done." };
+ }
+ function turn(id: string, entries: TranscriptEntry[], durationMs: number): TaskChatItem {
+ return {
+ id,
+ kind: "turn",
+ settled: true,
+ items: entries.map((e, i) => ({
+ id: `${id}:tool:${i}`,
+ kind: "tool" as const,
+ name: (e as { name: string }).name,
+ status: "completed" as const,
+ })),
+ summary: buildTurnSummary(entries, { durationMs }),
+ };
+ }
+ const metaById = new Map<string, SettledTurnMergeMeta>([
+ ["run-a:turn", { agentKey: "agent-1", agentName: "CEO", parts: [{ entries: runA, durationMs: 30_000 }] }],
+ ["run-b:turn", { agentKey: "agent-1", agentName: "CEO", parts: [{ entries: runB, durationMs: 15_000 }] }],
+ ]);
+
+ it("merges two back-to-back runs into ONE Worked row summing tools and duration", () => {
+ // Two terminal runs, same agent, consecutive comments, no user message
+ // between → the merged turn sits below the LAST bubble.
+ const items: TaskChatItem[] = [
+ agentBubble("msg-a"),
+ turn("run-a:turn", runA, 30_000),
+ agentBubble("msg-b"),
+ turn("run-b:turn", runB, 15_000),
+ ];
+ const out = coalesceSettledTurns(items, metaById);
+ expect(out.map((i) => i.kind)).toEqual(["message", "message", "turn"]);
+ const merged = out[2] as Extract<TaskChatItem, { kind: "turn" }>;
+ expect(merged.id).toBe("run-a:turn"); // stable: keeps the first run's id
+ expect(merged.summary.toolCount).toBe(3);
+ expect(merged.summary.durationLabel).toBe("45s");
+ expect(merged.items.map((c) => c.id)).toEqual([
+ "run-a:turn:tool:0",
+ "run-a:turn:tool:1",
+ "run-b:turn:tool:0",
+ ]);
+ });
+
+ it("keeps two rows when a user message sits between the runs", () => {
+ const items: TaskChatItem[] = [
+ agentBubble("msg-a"),
+ turn("run-a:turn", runA, 30_000),
+ { id: "msg-u", kind: "message", author: "human", text: "also do X" },
+ agentBubble("msg-b"),
+ turn("run-b:turn", runB, 15_000),
+ ];
+ const out = coalesceSettledTurns(items, metaById);
+ expect(out.filter((i) => i.kind === "turn")).toHaveLength(2);
+ expect(out.map((i) => i.id)).toEqual(["msg-a", "run-a:turn", "msg-u", "msg-b", "run-b:turn"]);
+ });
+
+ it("does not merge across an interaction or into another agent's turn", () => {
+ const withInteraction: TaskChatItem[] = [
+ turn("run-a:turn", runA, 30_000),
+ { id: "int-1", kind: "interaction", interaction: {} } as TaskChatItem,
+ turn("run-b:turn", runB, 15_000),
+ ];
+ expect(coalesceSettledTurns(withInteraction, metaById).filter((i) => i.kind === "turn")).toHaveLength(2);
+
+ const otherAgent = new Map(metaById);
+ otherAgent.set("run-b:turn", { agentKey: "agent-2", agentName: "QA", parts: [{ entries: runB }] });
+ const sameShape: TaskChatItem[] = [turn("run-a:turn", runA, 30_000), turn("run-b:turn", runB, 15_000)];
+ expect(coalesceSettledTurns(sameShape, otherAgent).filter((i) => i.kind === "turn")).toHaveLength(2);
+ });
+
+ it("never merges the live (unsettled) turn and preserves animateFold", () => {
+ const live: TaskChatItem = { id: "run-b:turn", kind: "turn", settled: false, items: [], summary: buildTurnSummary([]) };
+ const out = coalesceSettledTurns([turn("run-a:turn", runA, 30_000), live], metaById);
+ expect(out).toHaveLength(2);
+
+ const seenLive = { ...turn("run-b:turn", runB, 15_000), animateFold: true } as TaskChatItem;
+ const merged = coalesceSettledTurns([turn("run-a:turn", runA, 30_000), seenLive], metaById);
+ expect(merged).toHaveLength(1);
+ expect((merged[0] as Extract<TaskChatItem, { kind: "turn" }>).animateFold).toBe(true);
+ });
+});
+
+describe("attachSettledTurns (round 9)", () => {
+ const runA: TranscriptEntry[] = [
+ { kind: "tool_call", ts: TS, name: "Read", toolUseId: "a-1" } as TranscriptEntry,
+ ];
+
+ function agentBubble(id: string, authorName = "CEO"): TaskChatItem {
+ return { id, kind: "message", author: "agent", authorName, text: "Done." };
+ }
+ function settledTurn(id: string): TaskChatItem {
+ return {
+ id,
+ kind: "turn",
+ settled: true,
+ items: [{ id: `${id}:tool:0`, kind: "tool", name: "Read", status: "completed" }],
+ summary: buildTurnSummary(runA, { durationMs: 30_000 }),
+ };
+ }
+ const metaById = new Map<string, SettledTurnMergeMeta>([
+ ["run-a:turn", { agentKey: "agent-1", agentName: "CEO", parts: [{ entries: runA, durationMs: 30_000 }] }],
+ ]);
+
+ it("folds a settled turn into the agent reply bubble directly above it", () => {
+ const out = attachSettledTurns([agentBubble("msg-a"), settledTurn("run-a:turn")], metaById);
+ expect(out).toHaveLength(1);
+ const bubble = out[0] as Extract<TaskChatItem, { kind: "message" }>;
+ expect(bubble.id).toBe("msg-a");
+ expect(bubble.attachedTurn?.id).toBe("run-a:turn");
+ expect(bubble.attachedTurn?.summary.durationLabel).toBe("30s");
+ });
+
+ it("keeps the standalone row when the preceding item is not that agent's bubble", () => {
+ // Human message directly above.
+ const afterHuman = attachSettledTurns(
+ [{ id: "msg-u", kind: "message", author: "human", text: "hi" }, settledTurn("run-a:turn")],
+ metaById,
+ );
+ expect(afterHuman.map((i) => i.kind)).toEqual(["message", "turn"]);
+ // Another agent's bubble above.
+ const otherAgent = attachSettledTurns([agentBubble("msg-q", "QA"), settledTurn("run-a:turn")], metaById);
+ expect(otherAgent.map((i) => i.kind)).toEqual(["message", "turn"]);
+ // No meta (unknown identity) → conservative standalone fallback.
+ const noMeta = attachSettledTurns([agentBubble("msg-a"), settledTurn("run-x:turn")], metaById);
+ expect(noMeta.map((i) => i.kind)).toEqual(["message", "turn"]);
+ // Nothing above at all.
+ const first = attachSettledTurns([settledTurn("run-a:turn")], metaById);
+ expect(first.map((i) => i.kind)).toEqual(["turn"]);
+ });
+
+ it("never attaches the live (unsettled) turn and attaches at most one turn per bubble", () => {
+ const live: TaskChatItem = {
+ id: "run-live:turn",
+ kind: "turn",
+ settled: false,
+ items: [],
+ summary: buildTurnSummary([]),
+ };
+ const out = attachSettledTurns([agentBubble("msg-a"), live], metaById);
+ expect(out.map((i) => i.kind)).toEqual(["message", "turn"]);
+
+ // A second settled turn behind an already-attached bubble stays standalone
+ // (coalesceSettledTurns runs first, so same-agent turns arrive pre-merged).
+ const twice = attachSettledTurns(
+ [agentBubble("msg-a"), settledTurn("run-a:turn"), settledTurn("run-a:turn")],
+ metaById,
+ );
+ expect(twice.map((i) => i.kind)).toEqual(["message", "turn"]);
+ expect((twice[0] as Extract<TaskChatItem, { kind: "message" }>).attachedTurn?.id).toBe("run-a:turn");
+ });
+});
+
+describe("assembleThreadItems (PAP-367)", () => {
+ function entry(id: string, ms: number, item?: Partial<TaskChatItem>): ThreadBackboneEntry {
+ return {
+ ms,
+ id,
+ item: { id, kind: "message", author: "human", text: `msg ${id}`, ...item } as TaskChatItem,
+ };
+ }
+ function settledTurn(id: string): TaskChatTurnItem {
+ return {
+ id,
+ kind: "turn",
+ settled: true,
+ items: [{ id: `${id}:tool:0`, kind: "tool", name: "Read", status: "completed" }],
+ summary: buildTurnSummary([toolCall("Read")], { durationMs: 34_000 }),
+ };
+ }
+ const noAnchors = new Map<string, TaskChatTurnItem[]>();
+
+ it("inserts a comment-less settled turn chronologically at its run's start time", () => {
+ const backbone = [entry("u1", 1_000), entry("a1", 2_000, { author: "agent", authorName: "CEO" }), entry("u2", 3_000)];
+ const out = assembleThreadItems(backbone, noAnchors, [{ turn: settledTurn("run-x:turn"), startMs: 2_500 }]);
+ expect(out.map((i) => i.id)).toEqual(["u1", "a1", "run-x:turn", "u2"]);
+ });
+
+ it("does not append a comment-less turn after the newest user message (the P11 bug)", () => {
+ // The screenshot bug: an OLD stopped run (start 1_500) re-pinning its
+ // "Worked · 34s" row under every NEW user bubble (3_000).
+ const backbone = [entry("u1", 1_000), entry("u2", 3_000)];
+ const out = assembleThreadItems(backbone, noAnchors, [{ turn: settledTurn("run-x:turn"), startMs: 1_500 }]);
+ expect(out.map((i) => i.id)).toEqual(["u1", "run-x:turn", "u2"]);
+ expect(out[out.length - 1].id).toBe("u2");
+ });
+
+ it("keeps anchored turns directly after their run's reply comment", () => {
+ const backbone = [entry("u1", 1_000), entry("a1", 2_000, { author: "agent", authorName: "CEO" }), entry("u2", 3_000)];
+ const anchors = new Map([["a1", [settledTurn("run-a:turn")]]]);
+ const out = assembleThreadItems(backbone, anchors, []);
+ expect(out.map((i) => i.id)).toEqual(["u1", "a1", "run-a:turn", "u2"]);
+ });
+
+ it("keeps the tail slot for a turn with unknown start, and puts ties after the entry", () => {
+ const backbone = [entry("u1", 1_000), entry("u2", 3_000)];
+ // Unknown start (no linked meta yet — just-settled run): Infinity → tail.
+ const tail = assembleThreadItems(backbone, noAnchors, [
+ { turn: settledTurn("run-x:turn"), startMs: Number.POSITIVE_INFINITY },
+ ]);
+ expect(tail.map((i) => i.id)).toEqual(["u1", "u2", "run-x:turn"]);
+ // Tie with the trigger comment: comment renders first.
+ const tie = assembleThreadItems(backbone, noAnchors, [{ turn: settledTurn("run-y:turn"), startMs: 1_000 }]);
+ expect(tie.map((i) => i.id)).toEqual(["u1", "run-y:turn", "u2"]);
+ });
+
+ it("chronological insertion after a user message stays a standalone row through coalesce+attach", () => {
+ // Interplay guard: the inserted turn sits below a HUMAN bubble, so the
+ // later passes must neither merge it into anything nor attach it.
+ const backbone = [entry("u1", 1_000), entry("u2", 3_000)];
+ const metaById = new Map<string, SettledTurnMergeMeta>([
+ ["run-x:turn", { agentKey: "agent-1", agentName: "CEO", parts: [{ entries: [toolCall("Read")], durationMs: 34_000 }] }],
+ ]);
+ const assembled = assembleThreadItems(backbone, noAnchors, [{ turn: settledTurn("run-x:turn"), startMs: 1_500 }]);
+ const out = attachSettledTurns(coalesceSettledTurns(assembled, metaById), metaById);
+ expect(out.map((i) => i.id)).toEqual(["u1", "run-x:turn", "u2"]);
+ expect(out.every((i) => i.kind !== "message" || (i as Extract<TaskChatItem, { kind: "message" }>).attachedTurn == null)).toBe(true);
+ });
+});
+
+describe("prependIssueBrief (PAP-375)", () => {
+ function entry(id: string, ms: number): ThreadBackboneEntry {
+ return {
+ ms,
+ id,
+ item: { id, kind: "message", author: "human", text: `msg ${id}` } as TaskChatItem,
+ };
+ }
+ function settledTurn(id: string): TaskChatTurnItem {
+ return {
+ id,
+ kind: "turn",
+ settled: true,
+ items: [{ id: `${id}:tool:0`, kind: "tool", name: "Read", status: "completed" }],
+ summary: buildTurnSummary([toolCall("Read")], { durationMs: 34_000 }),
+ };
+ }
+
+ it("keeps the description bubble above an unanchored turn that predates every backbone entry (F15)", () => {
+ // A stopped run whose startMs (0) is EARLIER than the oldest comment: it
+ // sorts to the very top of the assembled thread — the brief must still
+ // render above it, because the prepend runs after assembly.
+ const backbone = [entry("u1", 1_000), entry("u2", 3_000)];
+ const assembled = assembleThreadItems(backbone, new Map(), [
+ { turn: settledTurn("run-x:turn"), startMs: 0 },
+ ]);
+ const out = prependIssueBrief(assembled, true);
+ expect(out.map((i) => i.id)).toEqual([ISSUE_BRIEF_ITEM_ID, "run-x:turn", "u1", "u2"]);
+ expect(out[0].kind).toBe("brief");
+ });
+
+ it("is the first item of an otherwise empty thread, and a no-op without a brief", () => {
+ expect(prependIssueBrief([], true).map((i) => i.kind)).toEqual(["brief"]);
+ const items = [entry("u1", 1_000).item];
+ expect(prependIssueBrief(items, false)).toBe(items);
+ });
+});
diff --git a/ui/src/components/task-chat/transcript-adapter.ts b/ui/src/components/task-chat/transcript-adapter.ts
index b75e00e4fa..1745e8aa16 100644
--- a/ui/src/components/task-chat/transcript-adapter.ts
+++ b/ui/src/components/task-chat/transcript-adapter.ts
@@ -10,6 +10,7 @@ import type {
TaskChatDiff,
TaskChatItem,
TaskChatToolItem,
+ TaskChatTurnChildItem,
TaskChatTurnItem,
} from "./task-chat-model";
import { isGenericToolName, mcpToolSegment, toolTaxonomy } from "./tool-taxonomy";
@@ -26,6 +27,38 @@ export function isTerminalRunStatus(status: string | undefined | null): boolean
return status != null && TERMINAL_STATUSES.has(status);
}
+/**
+ * The live parent row's nesting rule (PAP-354, narrowed by PAP-361): only tool
+ * calls and usage readouts nest inside the expandable live turn. Messages
+ * never nest — an interstitial update streams on the parent row's own line
+ * (TaskChatStatusItem.selfTalk) and vanishes when it completes, and the run's
+ * final reply lands as its posted comment bubble. Thinking never nests either:
+ * its live signal is the pill's "Thinking…" state, and the text stays in the
+ * run log / classic transcript. Markers, statuses and interaction cards stay
+ * in the thread outside.
+ */
+export function isNestableLiveChild(item: TaskChatItem): item is TaskChatTurnChildItem {
+ return item.kind === "tool" || item.kind === "usage";
+}
+
+/**
+ * Flatten markdown-ish interstitial text to one plain line for the live parent
+ * row. Stream-safe: markers are stripped without requiring pairs.
+ */
+export function flattenSelfTalk(text: string): string {
+ return text
+ .replace(/```[a-z]*\n?/gi, " ")
+ .replace(/`/g, "")
+ .replace(/^#{1,6}\s+/gm, "")
+ .replace(/^\s*[-*+]\s+/gm, "")
+ .replace(/^\s*>\s?/gm, "")
+ .replace(/!?\[([^\]]*)\]\(([^)]*)\)/g, "$1")
+ .replace(/\*+/g, "")
+ .replace(/__/g, "")
+ .replace(/\s+/g, " ")
+ .trim();
+}
+
function diffKind(changeType: string): "add" | "remove" | "context" {
if (changeType === "add") return "add";
if (changeType === "remove") return "remove";
@@ -177,6 +210,7 @@ export function transcriptToTaskChatItems(
const it = items[messageIndex];
if (it.kind === "message") it.text += entry.text;
} else {
+ const atMs = Date.parse(entry.ts);
items.push({
id: `${runId}:msg:${i}`,
kind: "message",
@@ -184,6 +218,10 @@ export function transcriptToTaskChatItems(
authorName: agentName,
text: entry.text,
streaming: running,
+ // Everything the agent says inside a run turn is self-talk until it
+ // lands as the posted comment — live and history tag it alike.
+ interstitial: true,
+ atMs: Number.isFinite(atMs) ? atMs : undefined,
});
messageIndex = items.length - 1;
thinkingIndex = -1;
@@ -278,9 +316,32 @@ export function transcriptToTaskChatItems(
}
}
+ // Only the message still open at the transcript tail is streaming; earlier
+ // self-talk is finished and nests as a settled row even mid-run.
+ if (running) {
+ for (const [idx, it] of items.entries()) {
+ if (it.kind === "message" && idx !== messageIndex) it.streaming = false;
+ }
+ }
+
return items;
}
+/**
+ * A settled run's nested children (PAP-361): exactly the tool rows (plus usage
+ * readouts) in transcript order, under the "✓ Worked ·" summary — parity with
+ * the summary's tool count. Messages are excluded: the final reply already
+ * landed as the run's posted comment bubble, and interstitial updates are
+ * ephemeral (they take the live line while streaming, then vanish). Thinking
+ * is excluded too — the run log / classic transcript remain its archive.
+ */
+export function settledRunChildren(parsed: readonly TaskChatItem[]): TaskChatTurnChildItem[] {
+ return parsed.filter(
+ (it): it is TaskChatTurnChildItem =>
+ it.kind !== "turn" && it.kind !== "message" && it.kind !== "thinking",
+ );
+}
+
function formatDurationLabel(ms: number): string | undefined {
if (!Number.isFinite(ms) || ms <= 0) return undefined;
const totalSec = Math.round(ms / 1000);
@@ -297,6 +358,15 @@ function formatTokensLabel(tokens: number): string | undefined {
return `${label} tokens`;
}
+/** First→last ts span of a transcript, or undefined when unknowable. */
+function transcriptSpanMs(entries: readonly TranscriptEntry[]): number | undefined {
+ if (entries.length < 2) return undefined;
+ const first = Date.parse(entries[0].ts);
+ const last = Date.parse(entries[entries.length - 1].ts);
+ if (!Number.isFinite(first) || !Number.isFinite(last)) return undefined;
+ return Math.max(0, last - first);
+}
+
/**
* Aggregate a turn's transcript into the folded one-line summary
* ("✓ Worked · 38s · 3 tools · +34 −3 · 12.3k tokens"). Duration prefers the
@@ -322,12 +392,7 @@ export function buildTurnSummary(
tokens += (entry.inputTokens || 0) + (entry.outputTokens || 0);
}
}
- let durationMs = opts.durationMs;
- if (durationMs == null && entries.length >= 2) {
- const first = Date.parse(entries[0].ts);
- const last = Date.parse(entries[entries.length - 1].ts);
- if (Number.isFinite(first) && Number.isFinite(last)) durationMs = last - first;
- }
+ const durationMs = opts.durationMs ?? transcriptSpanMs(entries);
return {
durationLabel: durationMs != null ? formatDurationLabel(durationMs) : undefined,
toolCount: toolIds.size,
@@ -338,15 +403,207 @@ export function buildTurnSummary(
};
}
+/** One settled run's raw summary inputs, kept so back-to-back runs can coalesce (PAP-362). */
+export interface TurnSummaryPart {
+ entries: readonly TranscriptEntry[];
+ durationMs?: number;
+ failed?: boolean;
+}
+
+/**
+ * Summary for a turn coalesced from several back-to-back runs (PAP-362).
+ * Tool/diff/token counts re-derive from the concatenated transcripts; duration
+ * is the SUM of the per-run durations (each with its own ts-span fallback) —
+ * never the wall span across the idle gap between runs.
+ */
+export function buildMergedTurnSummary(
+ parts: readonly TurnSummaryPart[],
+): TaskChatTurnItem["summary"] {
+ const all: TranscriptEntry[] = [];
+ let durationMs: number | undefined;
+ let failed = false;
+ for (const part of parts) {
+ all.push(...part.entries);
+ if (part.failed) failed = true;
+ const d = part.durationMs ?? transcriptSpanMs(part.entries);
+ if (d != null && Number.isFinite(d)) durationMs = (durationMs ?? 0) + Math.max(0, d);
+ }
+ // durationMs: 0 suppresses the concatenated-span fallback (which would count
+ // the gap between runs); the summed label is applied over it below.
+ const counts = buildTurnSummary(all, { durationMs: 0, failed });
+ return {
+ ...counts,
+ durationLabel: durationMs != null ? formatDurationLabel(durationMs) : undefined,
+ };
+}
+
+/** One chronological backbone entry (comment / interaction / marker). */
+export interface ThreadBackboneEntry {
+ /** Chronological sort key in ms (backbone is already sorted by it). */
+ ms: number;
+ /** Stable entry id — the anchor key settled turns attach after. */
+ id: string;
+ item: TaskChatItem;
+}
+
+/**
+ * Assemble the thread body (PAP-367): backbone entries in order, each followed
+ * by the settled turns anchored to it (run → reply-comment linkage), with
+ * comment-less settled turns — stopped runs, or a reply not yet fetched —
+ * interleaved chronologically at their run's start time instead of
+ * bottom-appended under the newest message. Ties go after the backbone entry
+ * (trigger comment first); turns with no known start (startMs = Infinity) keep
+ * the tail slot. `unanchored` must be sorted ascending by startMs.
+ */
+export function assembleThreadItems(
+ entries: readonly ThreadBackboneEntry[],
+ turnsByAnchor: ReadonlyMap<string, readonly TaskChatTurnItem[]>,
+ unanchored: readonly { turn: TaskChatTurnItem; startMs: number }[],
+): TaskChatItem[] {
+ const out: TaskChatItem[] = [];
+ let next = 0;
+ for (const entry of entries) {
+ while (next < unanchored.length && unanchored[next].startMs < entry.ms) {
+ out.push(unanchored[next++].turn);
+ }
+ out.push(entry.item);
+ const following = turnsByAnchor.get(entry.id);
+ if (following) out.push(...following);
+ }
+ while (next < unanchored.length) out.push(unanchored[next++].turn);
+ return out;
+}
+
+/** Stable id of the description-as-first-bubble item (PAP-375). */
+export const ISSUE_BRIEF_ITEM_ID = "issue-brief";
+
+/**
+ * Prepend the issue-brief placeholder (PAP-375) to the fully assembled thread.
+ * Running AFTER assembleThreadItems/coalesce/attach makes the ordering
+ * guarantee structural rather than data-dependent: even an unanchored settled
+ * turn whose startMs predates every backbone entry (F15) lands below the
+ * description bubble.
+ */
+export function prependIssueBrief(items: TaskChatItem[], hasBrief: boolean): TaskChatItem[] {
+ if (!hasBrief) return items;
+ return [{ id: ISSUE_BRIEF_ITEM_ID, kind: "brief" }, ...items];
+}
+
+/** Per-turn identity + raw summary inputs for coalescing (keyed by turn item id). */
+export interface SettledTurnMergeMeta {
+ /** Stable agent identity (agentId); empty/unknown turns never merge. */
+ agentKey: string;
+ /** Display name, used to keep another agent's bubble from bridging a merge. */
+ agentName?: string;
+ parts: TurnSummaryPart[];
+}
+
+/**
+ * Final assembly pass (PAP-362): merge runs of settled turns from the SAME
+ * agent that arrive back-to-back — two runs replying consecutively — into one
+ * "Worked" row. The agent's own reply bubbles do not break the run (the merged
+ * row lands below the last bubble, in the last run's slot); a human/system
+ * message, an interaction, a marker, or the live in-flight turn does. Child
+ * items concatenate in order, the summary re-derives via buildMergedTurnSummary,
+ * the merged turn keeps the FIRST run's id (stable across re-renders), and
+ * animateFold survives if any merged run was seen live.
+ */
+export function coalesceSettledTurns(
+ items: readonly TaskChatItem[],
+ metaById: ReadonlyMap<string, SettledTurnMergeMeta>,
+): TaskChatItem[] {
+ const out: TaskChatItem[] = [];
+ // Overlay for merged turns' accumulated parts (metaById stays untouched).
+ const mergedMeta = new Map<string, SettledTurnMergeMeta>();
+ const metaFor = (id: string) => mergedMeta.get(id) ?? metaById.get(id);
+ let heldIdx = -1; // index in `out` of the last mergeable settled turn
+ for (const item of items) {
+ if (item.kind === "turn" && item.settled) {
+ const meta = metaFor(item.id);
+ const held = heldIdx >= 0 ? (out[heldIdx] as TaskChatTurnItem) : null;
+ const heldMeta = held ? metaFor(held.id) : undefined;
+ if (held && meta && heldMeta && meta.agentKey && meta.agentKey === heldMeta.agentKey) {
+ out.splice(heldIdx, 1);
+ const parts = [...heldMeta.parts, ...meta.parts];
+ out.push({
+ ...held,
+ items: [...held.items, ...item.items],
+ animateFold: held.animateFold || item.animateFold || undefined,
+ summary: buildMergedTurnSummary(parts),
+ });
+ mergedMeta.set(held.id, { ...heldMeta, parts });
+ } else {
+ out.push(item);
+ }
+ heldIdx = meta?.agentKey ? out.length - 1 : -1;
+ continue;
+ }
+ out.push(item);
+ if (item.kind === "message" && item.author === "agent") {
+ // The same agent's reply bubble sits between its runs — keep merging
+ // across it. A different agent's bubble ends the run of turns.
+ const heldMeta = heldIdx >= 0 ? metaFor((out[heldIdx] as TaskChatTurnItem).id) : undefined;
+ if (heldMeta?.agentName && item.authorName && item.authorName !== heldMeta.agentName) {
+ heldIdx = -1;
+ }
+ } else {
+ heldIdx = -1;
+ }
+ }
+ return out;
+}
+
+/**
+ * Final assembly pass (round 9, after coalesceSettledTurns): a settled turn
+ * that directly follows its own agent's reply bubble folds INTO that bubble as
+ * `attachedTurn` — the "Worked · …" summary renders appended to the bubble's
+ * always-visible timestamp line instead of as a standalone row. The turn must
+ * belong to the same agent as the bubble (metaById identity); turns without
+ * meta, or preceded by anything other than that agent's non-interstitial
+ * bubble, keep the standalone-row fallback.
+ */
+export function attachSettledTurns(
+ items: readonly TaskChatItem[],
+ metaById: ReadonlyMap<string, SettledTurnMergeMeta>,
+): TaskChatItem[] {
+ const out: TaskChatItem[] = [];
+ for (const item of items) {
+ const prev = out[out.length - 1];
+ if (
+ item.kind === "turn" &&
+ item.settled &&
+ prev?.kind === "message" &&
+ prev.author === "agent" &&
+ !prev.interstitial &&
+ !prev.streaming &&
+ prev.attachedTurn == null
+ ) {
+ const meta = metaById.get(item.id);
+ const sameAgent =
+ meta != null && (meta.agentName == null || prev.authorName == null || meta.agentName === prev.authorName);
+ if (sameAgent) {
+ out[out.length - 1] = { ...prev, attachedTurn: item };
+ continue;
+ }
+ }
+ out.push(item);
+ }
+ return out;
+}
+
/**
* Human-readable label for the live status pill from the tail of a transcript.
* A tail tool_call yields the taxonomy verb ("Searching", "Running a command")
* with tool + target as detail; `toolName` lets the pill show the family icon.
+ * A tail assistant message yields "Responding" plus `selfTalk` — the flattened
+ * text of the interstitial update streamed so far, which takes over the parent
+ * row's line while it streams (PAP-361).
*/
export function deriveRunStatusLabel(entries: readonly TranscriptEntry[]): {
label: string;
detail?: string;
toolName?: string;
+ selfTalk?: string;
} {
for (let i = entries.length - 1; i >= 0; i--) {
const entry = entries[i];
@@ -382,7 +639,29 @@ export function deriveRunStatusLabel(entries: readonly TranscriptEntry[]): {
};
}
if (entry.kind === "tool_result") break;
- if (entry.kind === "assistant") return { label: "Responding" };
+ if (entry.kind === "assistant") {
+ // Accumulate the trailing message's deltas (the same coalescing run the
+ // parser groups into one item: broken by tool/thinking/diff, not by
+ // status-only entries like stdout).
+ const parts: string[] = [];
+ for (let j = i; j >= 0; j--) {
+ const prev = entries[j];
+ if (prev.kind === "assistant") {
+ if (prev.text) parts.unshift(prev.text);
+ continue;
+ }
+ if (
+ prev.kind === "tool_call" ||
+ prev.kind === "tool_result" ||
+ prev.kind === "thinking" ||
+ prev.kind === "diff"
+ ) {
+ break;
+ }
+ }
+ const selfTalk = flattenSelfTalk(parts.join(""));
+ return { label: "Responding", selfTalk: selfTalk || undefined };
+ }
if (entry.kind === "thinking") return { label: "Thinking" };
}
return { label: "Running" };
diff --git a/ui/src/components/task-chat/useWindowAutoFollow.test.tsx b/ui/src/components/task-chat/useWindowAutoFollow.test.tsx
new file mode 100644
index 0000000000..ce84c32701
--- /dev/null
+++ b/ui/src/components/task-chat/useWindowAutoFollow.test.tsx
@@ -0,0 +1,104 @@
+// @vitest-environment jsdom
+
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useWindowAutoFollow } from "./useWindowAutoFollow";
+
+function Host({ contentKey, enabled }: { contentKey: unknown; enabled: boolean }) {
+ useWindowAutoFollow(contentKey, enabled);
+ return <div>thread</div>;
+}
+
+/**
+ * jsdom has no layout: document scroll geometry is faked on the scrolling
+ * element, window.scrollTo is stubbed to record calls and update scrollY.
+ */
+describe("useWindowAutoFollow", () => {
+ let container: HTMLDivElement;
+ let root: Root;
+ let scrollToCalls: number[];
+
+ function fakeWindowGeometry({ scrollHeight = 2000, innerHeight = 800 } = {}) {
+ const el = document.scrollingElement ?? document.documentElement;
+ Object.defineProperty(el, "scrollHeight", { value: scrollHeight, configurable: true });
+ Object.defineProperty(window, "innerHeight", { value: innerHeight, configurable: true });
+ }
+
+ function setWindowScrollY(y: number) {
+ Object.defineProperty(window, "scrollY", { value: y, configurable: true });
+ }
+
+ function render(contentKey: unknown, enabled = true) {
+ flushSync(() => {
+ root.render(<Host contentKey={contentKey} enabled={enabled} />);
+ });
+ }
+
+ /** Fire a window scroll event and flush the continuous-priority update. */
+ function scrollWindowTo(y: number) {
+ setWindowScrollY(y);
+ window.dispatchEvent(new Event("scroll"));
+ return new Promise<void>((resolve) => {
+ setTimeout(resolve);
+ });
+ }
+
+ /** Wait out the mount effect's rAF re-follow so it can't leak into asserts. */
+ function flushRaf() {
+ return new Promise<void>((resolve) => {
+ requestAnimationFrame(() => setTimeout(resolve));
+ });
+ }
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ scrollToCalls = [];
+ fakeWindowGeometry();
+ setWindowScrollY(0);
+ vi.stubGlobal("scrollTo", (options?: ScrollToOptions | number) => {
+ const top = typeof options === "number" ? options : (options?.top ?? 0);
+ scrollToCalls.push(top);
+ // Mirror the browser: a follow to the bottom leaves the window pinned.
+ setWindowScrollY(Math.max(0, top - window.innerHeight));
+ });
+ });
+
+ afterEach(() => {
+ flushSync(() => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+ });
+
+ it("scrolls the window to the bottom on mount", () => {
+ render(0);
+ expect(scrollToCalls).toContain(2000);
+ });
+
+ it("follows content growth while pinned to the bottom", async () => {
+ render(0);
+ await flushRaf();
+ await scrollWindowTo(1200); // pinned: 2000 - 1200 - 800 = 0
+ scrollToCalls = [];
+ render(1);
+ expect(scrollToCalls).toContain(2000);
+ });
+
+ it("holds position when the user has scrolled up", async () => {
+ render(0);
+ await flushRaf();
+ await scrollWindowTo(100); // far from the bottom
+ scrollToCalls = [];
+ render(1);
+ expect(scrollToCalls).toHaveLength(0);
+ });
+
+ it("does nothing when disabled", () => {
+ render(0, false);
+ expect(scrollToCalls).toHaveLength(0);
+ render(1, false);
+ expect(scrollToCalls).toHaveLength(0);
+ });
+});
diff --git a/ui/src/components/task-chat/useWindowAutoFollow.ts b/ui/src/components/task-chat/useWindowAutoFollow.ts
new file mode 100644
index 0000000000..8aa1ca30a9
--- /dev/null
+++ b/ui/src/components/task-chat/useWindowAutoFollow.ts
@@ -0,0 +1,63 @@
+import { useEffect, useLayoutEffect, useRef } from "react";
+
+const PIN_THRESHOLD_PX = 48;
+
+function scrollingElement(): Element | null {
+ return document.scrollingElement ?? document.documentElement;
+}
+
+function windowPinned(): boolean {
+ const el = scrollingElement();
+ if (!el) return true;
+ return el.scrollHeight - window.scrollY - window.innerHeight <= PIN_THRESHOLD_PX;
+}
+
+function scrollWindowToBottom(): void {
+ const el = scrollingElement();
+ if (!el) return;
+ window.scrollTo({ top: el.scrollHeight, left: 0, behavior: "auto" });
+}
+
+/**
+ * Window-scroll counterpart of TaskMessageScroller's auto-follow rule, for the
+ * mobile document-flow thread (the mobile app shell scrolls the document, not
+ * an inner viewport — see Layout.tsx). While the window is pinned to the
+ * bottom (within a small threshold) content growth follows with INSTANT
+ * scroll; once the user scrolls up we hold their position.
+ *
+ * The initial follow runs in a passive effect plus one rAF: Layout's
+ * navigation scroll handling (reset-to-top on PUSH, scroll-memory re-apply on
+ * POP) runs in ancestor layout effects, which fire AFTER this component's
+ * layout effects in the same commit — deferring past them keeps the reset
+ * from clobbering the follow.
+ */
+export function useWindowAutoFollow(contentKey: unknown, enabled: boolean): void {
+ const pinnedRef = useRef(true);
+
+ useEffect(() => {
+ if (!enabled) return;
+ const onScroll = () => {
+ pinnedRef.current = windowPinned();
+ };
+ window.addEventListener("scroll", onScroll, { passive: true });
+ return () => window.removeEventListener("scroll", onScroll);
+ }, [enabled]);
+
+ // Follow new content only when already pinned; otherwise hold position.
+ useLayoutEffect(() => {
+ if (!enabled) return;
+ if (pinnedRef.current) scrollWindowToBottom();
+ }, [contentKey, enabled]);
+
+ useEffect(() => {
+ if (!enabled) return;
+ scrollWindowToBottom();
+ const raf = requestAnimationFrame(() => {
+ scrollWindowToBottom();
+ pinnedRef.current = true;
+ });
+ return () => cancelAnimationFrame(raf);
+ // Initial follow only — content-driven follow is the layout effect above.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [enabled]);
+}
diff --git a/ui/src/components/ui/attachment.tsx b/ui/src/components/ui/attachment.tsx
new file mode 100644
index 0000000000..d25b8547c6
--- /dev/null
+++ b/ui/src/components/ui/attachment.tsx
@@ -0,0 +1,210 @@
+import * as React from "react";
+import { mergeProps } from "@base-ui/react/merge-props";
+import { useRender } from "@base-ui/react/use-render";
+import { cva, type VariantProps } from "class-variance-authority";
+
+import { cn } from "@/lib/utils";
+import { Button } from "@/components/ui/button";
+
+// shadcn base/attachment (base-lyra registry variant), ported verbatim except
+// for the import paths above. https://ui.shadcn.com/docs/components/base/attachment
+
+const attachmentVariants = cva(
+ "group/attachment relative flex w-fit max-w-full min-w-0 shrink-0 flex-wrap rounded-none border bg-card text-card-foreground transition-colors focus-within:ring-1 focus-within:ring-ring/50 has-[>a,>button]:hover:bg-muted/50 data-[state=error]:border-destructive/30 data-[state=idle]:border-dashed",
+ {
+ variants: {
+ size: {
+ default:
+ "gap-2 text-xs has-data-[slot=attachment-content]:px-2 has-data-[slot=attachment-content]:py-1.5 has-data-[slot=attachment-media]:p-1.5",
+ sm: "gap-2.5 text-xs has-data-[slot=attachment-content]:px-1.5 has-data-[slot=attachment-content]:py-1 has-data-[slot=attachment-media]:p-1",
+ xs: "gap-1.5 rounded-none text-xs has-data-[slot=attachment-content]:px-1.5 has-data-[slot=attachment-content]:py-1 has-data-[slot=attachment-media]:p-1",
+ },
+ orientation: {
+ horizontal: "min-w-40 items-center",
+ vertical: "w-24 flex-col has-data-[slot=attachment-content]:w-30",
+ },
+ },
+ },
+);
+
+function Attachment({
+ className,
+ state = "done",
+ size = "default",
+ orientation = "horizontal",
+ ...props
+}: React.ComponentProps<"div"> &
+ VariantProps<typeof attachmentVariants> & {
+ state?: "idle" | "uploading" | "processing" | "error" | "done";
+ }) {
+ return (
+ <div
+ data-slot="attachment"
+ data-state={state}
+ data-size={size}
+ data-orientation={orientation}
+ className={cn(attachmentVariants({ size, orientation }), className)}
+ {...props}
+ />
+ );
+}
+
+const attachmentMediaVariants = cva(
+ "relative flex aspect-square w-10 shrink-0 items-center justify-center overflow-hidden rounded-none bg-muted text-foreground group-data-[orientation=vertical]/attachment:w-full group-data-[size=sm]/attachment:w-8 group-data-[size=xs]/attachment:w-7 group-data-[size=xs]/attachment:rounded-none group-data-[state=error]/attachment:bg-destructive/10 group-data-[state=error]/attachment:text-destructive group-data-[orientation=vertical]/attachment:*:data-[slot=spinner]:size-6! [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 group-data-[orientation=vertical]/attachment:[&_svg:not([class*='size-'])]:size-6 group-data-[size=xs]/attachment:[&_svg:not([class*='size-'])]:size-3.5",
+ {
+ variants: {
+ variant: {
+ icon: "",
+ image:
+ "opacity-60 group-data-[state=done]/attachment:opacity-100 group-data-[state=idle]/attachment:opacity-100 *:[img]:aspect-square *:[img]:w-full *:[img]:object-cover",
+ },
+ },
+ defaultVariants: {
+ variant: "icon",
+ },
+ },
+);
+
+function AttachmentMedia({
+ className,
+ variant = "icon",
+ ...props
+}: React.ComponentProps<"div"> & VariantProps<typeof attachmentMediaVariants>) {
+ return (
+ <div
+ data-slot="attachment-media"
+ data-variant={variant}
+ className={cn(attachmentMediaVariants({ variant }), className)}
+ {...props}
+ />
+ );
+}
+
+function AttachmentContent({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="attachment-content"
+ className={cn(
+ "max-w-full min-w-0 flex-1 leading-tight group-data-[orientation=vertical]/attachment:px-1",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AttachmentTitle({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="attachment-title"
+ className={cn(
+ "block max-w-full min-w-0 truncate font-medium group-data-[state=processing]/attachment:shimmer group-data-[state=uploading]/attachment:shimmer",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AttachmentDescription({
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="attachment-description"
+ className={cn(
+ "mt-0.5 block min-w-0 truncate text-xs text-muted-foreground group-data-[state=error]/attachment:text-destructive/80",
+ "max-w-full",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AttachmentActions({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="attachment-actions"
+ className={cn(
+ "relative z-20 flex shrink-0 items-center group-data-[orientation=vertical]/attachment:absolute group-data-[orientation=vertical]/attachment:top-3 group-data-[orientation=vertical]/attachment:right-3 group-data-[orientation=vertical]/attachment:gap-1",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AttachmentAction({
+ className,
+ variant,
+ size = "icon-xs",
+ ...props
+}: React.ComponentProps<typeof Button>) {
+ return (
+ <Button
+ data-slot="attachment-action"
+ variant={variant ?? "ghost"}
+ size={size}
+ className={cn(className)}
+ {...props}
+ />
+ );
+}
+
+function AttachmentTrigger({
+ className,
+ render,
+ type,
+ ...props
+}: useRender.ComponentProps<"button">) {
+ return useRender({
+ defaultTagName: "button",
+ props: mergeProps<"button">(
+ {
+ type: render ? type : (type ?? "button"),
+ className: cn("absolute inset-0 z-10 outline-none", className),
+ },
+ props,
+ ),
+ render,
+ state: {
+ slot: "attachment-trigger",
+ },
+ });
+}
+
+function AttachmentGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="attachment-group"
+ className={cn(
+ "flex min-w-0 scroll-fade-x snap-x snap-mandatory scroll-px-1 scrollbar-none gap-3 overflow-x-auto overscroll-x-contain py-1 *:data-[slot=attachment]:flex-none *:data-[slot=attachment]:snap-start",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+export {
+ Attachment,
+ AttachmentGroup,
+ AttachmentMedia,
+ AttachmentContent,
+ AttachmentTitle,
+ AttachmentDescription,
+ AttachmentActions,
+ AttachmentAction,
+ AttachmentTrigger,
+};
diff --git a/ui/src/index.css b/ui/src/index.css
index d47c46a931..3b4b143346 100644
--- a/ui/src/index.css
+++ b/ui/src/index.css
@@ -236,6 +236,8 @@
--motion-count-tween: var(--motion-duration-slow);
--motion-streaming-cursor-blink: 1.1s;
--motion-turn-fold: 380ms; /* finished-turn activity folding into its summary line */
+ --motion-line-scroll: 240ms; /* completed interstitial line sliding out of the 1lh live-line viewport */
+ --motion-interstitial-dwell: 4000ms; /* interstitial update hold: minimum before the next swaps in, and how long a finished update sits before sliding away */
--motion-scroll-pill-enter: 200ms; /* scroll-to-latest pill entry */
--motion-scroll-pill-exit: 400ms; /* scroll-to-latest pill exit */
--motion-ease-scroll-pill-in: cubic-bezier(0.23, 1, 0.32, 1);
@@ -535,6 +537,10 @@
--motion-plan-entry-stagger: 0ms;
--motion-streaming-cursor-blink: 0ms;
--motion-turn-fold: 0ms;
+ --motion-line-scroll: 0ms;
+ /* --motion-interstitial-dwell is deliberately NOT zeroed: it is a pacing
+ hold, not a movement — zeroing it would make the interstitial line churn
+ faster under reduced motion. Swaps themselves snap (line-scroll: 0). */
--motion-scroll-pill-enter: 0ms;
--motion-scroll-pill-exit: 0ms;
--motion-pane-glide: 0ms;
@@ -570,7 +576,6 @@
0%, 45% { opacity: 1; }
55%, 100% { opacity: 0; }
}
-
.tc-enter-bubble { animation: tc-fade-rise var(--motion-bubble-enter) var(--motion-ease-out-expo) both; }
.tc-enter-marker { animation: tc-fade-in var(--motion-marker-enter) var(--motion-ease-out) both; }
.tc-enter-tool { animation: tc-fade-rise var(--motion-tool-enter) var(--motion-ease-out-expo) both; }
@@ -580,6 +585,13 @@
.tc-approval { animation: tc-approval-pulse var(--motion-approval-pulse) var(--motion-ease-standard) infinite; }
.tc-cursor { animation: tc-cursor-blink var(--motion-streaming-cursor-blink) step-end infinite; }
.tc-enter-plan-entry { animation: tc-fade-rise var(--motion-plan-check) var(--motion-ease-out-expo) both; }
+/* Live-line viewport (PAP-361): exactly one line-height tall, clipping the
+ wrapped interstitial block. On wrap, the inner block translates up whole
+ line-heights (set inline as translateY(-(n−1)·1lh)) so the completed line
+ slides out the top — transform-only, same motion grammar as tool rows
+ animating in. */
+.tc-line-scroll { display: block; height: 1lh; overflow: hidden; }
+.tc-line-scroll-inner { transition: transform var(--motion-line-scroll) var(--motion-ease-standard); will-change: transform; }
/* Scroll-to-latest pill (stock shadcn MessageScrollerButton motion, tokenized).
The pill is centered with translateX(-50%), so the keyframes carry the X
@@ -621,6 +633,7 @@
.tc-scroll-pill-out,
.tc-enter-plan-entry { animation: none; }
.tc-turn-fold,
+ .tc-line-scroll-inner,
.tc-pane-glide { transition: none; }
/* The pill keyframes carry the X-centering; with animation:none restore it. */
.tc-scroll-pill-in,
@@ -896,6 +909,44 @@
--shimmer-highlight: color-mix(in oklch, var(--muted-foreground) 30%, transparent);
}
+/* Utilities expected by shadcn base components (ui/attachment.tsx). Declared
+ with @utility so variant forms (e.g. group-data-[state=uploading]:shimmer)
+ compile under Tailwind v4. */
+@utility shimmer {
+ --shimmer-base: var(--foreground);
+ --shimmer-highlight: color-mix(in oklch, var(--foreground) 35%, transparent);
+ background: linear-gradient(
+ 90deg,
+ var(--shimmer-base) 0%,
+ var(--shimmer-base) 40%,
+ var(--shimmer-highlight) 50%,
+ var(--shimmer-base) 60%,
+ var(--shimmer-base) 100%
+ );
+ background-size: 200% 100%;
+ -webkit-background-clip: text;
+ background-clip: text;
+ -webkit-text-fill-color: transparent;
+ animation: shimmer-text-slide 2.5s linear infinite;
+}
+
+@utility scrollbar-none {
+ scrollbar-width: none;
+ &::-webkit-scrollbar {
+ display: none;
+ }
+}
+
+@utility scroll-fade-x {
+ mask-image: linear-gradient(
+ to right,
+ transparent,
+ black 12px,
+ black calc(100% - 12px),
+ transparent
+ );
+}
+
@media (prefers-reduced-motion: reduce) {
.shimmer-text {
animation: none;
diff --git a/ui/src/pages/IssueDetail.test.tsx b/ui/src/pages/IssueDetail.test.tsx
index cc0efb5071..cb06be0c7c 100644
--- a/ui/src/pages/IssueDetail.test.tsx
+++ b/ui/src/pages/IssueDetail.test.tsx
@@ -282,6 +282,13 @@ vi.mock("../components/IssueChatThread", () => ({
},
}));
+// The redesign thread pulls in the MarkdownEditor composer, whose @mdxeditor
+// dependency cannot load under jsdom's CSSOM. These tests exercise the legacy
+// (flag-off) path, so an inert stub keeps the suite unit-scoped.
+vi.mock("../components/TaskChatThread", () => ({
+ TaskChatThread: () => <div data-testid="task-chat-thread">Task chat thread</div>,
+}));
+
vi.mock("../components/IssueDocumentsSection", () => ({
IssueDocumentsSection: () => <div>Documents</div>,
}));
diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx
index 268020aaec..8d35428482 100644
--- a/ui/src/pages/IssueDetail.tsx
+++ b/ui/src/pages/IssueDetail.tsx
@@ -91,6 +91,7 @@ import {
type IssueChatRunFinalizationAction,
} from "../components/IssueChatThread";
import { TaskChatThread } from "../components/TaskChatThread";
+import type { TaskChatIssueBrief } from "../components/task-chat/TaskChatDescriptionBubble";
import { useTaskChatRedesignEnabled } from "../hooks/useTaskChatRedesignEnabled";
import { workModeMetaFor } from "../lib/work-mode-meta";
import { IssueContinuationHandoff } from "../components/IssueContinuationHandoff";
@@ -913,6 +914,11 @@ type IssueDetailChatTabProps = {
* messages (flag: enableTaskChatRedesign). Ignored by the legacy thread.
*/
threadHeader?: ReactNode;
+ /**
+ * The task description rendered as the requester's first chat bubble in the
+ * redesigned thread (PAP-375). Ignored by the legacy thread.
+ */
+ issueBrief?: TaskChatIssueBrief;
footer?: ReactNode;
feedbackVotes?: FeedbackVote[];
feedbackDataSharingPreference: "allowed" | "not_allowed" | "prompt";
@@ -1003,6 +1009,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({
composerRef,
composerAccessory,
threadHeader,
+ issueBrief,
footer,
feedbackVotes,
feedbackDataSharingPreference,
@@ -1219,6 +1226,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({
</>
) : undefined
}
+ issueBrief={issueBrief}
comments={commentsWithRunMeta}
interactions={interactions}
feedbackVotes={feedbackVotes}
@@ -4576,10 +4584,13 @@ export function IssueDetail() {
<div
className={
taskChatShellEnabled
- ? // Fill main exactly so the outer page never scrolls — the thread's
- // own viewport is the only scroll surface (h-full is inert on
- // mobile, where main has no fixed height and the page scrolls).
- "flex h-full min-h-0 w-full flex-col gap-6"
+ ? isMobile
+ ? // Mobile shell scrolls the DOCUMENT (main is overflow-visible,
+ // auto height) — the thread renders in normal flow (PAP-360).
+ "flex w-full flex-col gap-6"
+ : // Fill main exactly so the outer page never scrolls — the
+ // thread's own viewport is the only scroll surface.
+ "flex h-full min-h-0 w-full flex-col gap-6"
: "max-w-3xl space-y-6"
}
>
@@ -4842,7 +4853,7 @@ export function IssueDetail() {
<Tabs
value={resolvedDetailTab}
onValueChange={setDetailTab}
- className={taskChatShellEnabled ? "min-h-0 flex-1" : "space-y-3"}
+ className={taskChatShellEnabled ? (isMobile ? undefined : "min-h-0 flex-1") : "space-y-3"}
>
{/* Redesign: the chat IS the page — the Chat/Activity/Related-work tab
strip is hidden and the thread renders as the only surface. */}
@@ -4873,11 +4884,44 @@ export function IssueDetail() {
scrollbar sits flush against the properties-pane border. */}
<TabsContent
value="chat"
- className={taskChatShellEnabled ? "-mx-4 md:-mx-6 flex min-h-0 flex-col" : undefined}
+ className={
+ taskChatShellEnabled
+ ? isMobile
+ ? "-mx-4"
+ : "-mx-4 md:-mx-6 flex min-h-0 flex-col"
+ : undefined
+ }
>
{resolvedDetailTab === "chat" ? (
<IssueDetailChatTab
threadHeader={taskChatThreadHeader}
+ issueBrief={
+ taskChatShellEnabled
+ ? {
+ description: issue.description ?? "",
+ author: issue.createdByAgentId ? "agent" : "human",
+ authorName: issue.createdByAgentId
+ ? agentMap.get(issue.createdByAgentId)?.name ?? "Agent"
+ : undefined,
+ agentIcon: issue.createdByAgentId
+ ? agentMap.get(issue.createdByAgentId)?.icon
+ : undefined,
+ createdAt: issue.createdAt,
+ onSave: (description) => updateIssue.mutateAsync({ description }),
+ mentions: mentionOptions,
+ externalReferences: externalObjectsState.isEnabled
+ ? externalObjectsState.markdownReferences
+ : undefined,
+ imageUploadHandler: async (file) => {
+ const attachment = await uploadAttachment.mutateAsync(file);
+ return attachment.contentPath;
+ },
+ onDropFile: async (file) => {
+ await uploadAttachment.mutateAsync(file);
+ },
+ }
+ : undefined
+ }
issueId={issue.id}
companyId={issue.companyId}
projectId={issue.projectId ?? null}
diff --git a/ui/src/pages/TaskChatLab.tsx b/ui/src/pages/TaskChatLab.tsx
index ab7e3f16b8..ca79e6cb52 100644
--- a/ui/src/pages/TaskChatLab.tsx
+++ b/ui/src/pages/TaskChatLab.tsx
@@ -11,7 +11,38 @@ import { TaskChatPlanView } from "@/components/task-chat/TaskChatPlanView";
import { TweakPanel } from "@/components/task-chat/TweakPanel";
import type { TaskChatItem } from "@/components/task-chat/task-chat-model";
-/** Progressively reveal any streaming message/thinking text at `speed`. */
+/** Replay ticks of selfTalk gap between scripted interstitial updates (~0.7s at 1×). */
+const SELF_TALK_GAP_TICKS = 30;
+
+/** A fixture's scripted interstitial updates: blank-line-separated segments. */
+function selfTalkSegments(script: string): string[] {
+ return script
+ .split(/\n{2,}/)
+ .map((s) => s.trim())
+ .filter(Boolean);
+}
+
+/**
+ * The selfTalk visible at replay tick `tick`: each segment streams one char
+ * per tick as its own update, with a gap (selfTalk undefined — the real
+ * adapter clears it between assistant messages) before the next; after the
+ * last segment ends, selfTalk stays undefined so the pill's hold-until-
+ * superseded behavior (PAP-368) is visible in the lab.
+ */
+function selfTalkAtTick(segments: string[], tick: number): string | undefined {
+ let t = tick;
+ for (let i = 0; i < segments.length; i++) {
+ const seg = segments[i];
+ if (t <= seg.length) return seg.slice(0, t) || undefined;
+ t -= seg.length;
+ if (i === segments.length - 1) return undefined;
+ if (t <= SELF_TALK_GAP_TICKS) return undefined;
+ t -= SELF_TALK_GAP_TICKS;
+ }
+ return undefined;
+}
+
+/** Progressively reveal any streaming message / live-line interstitial text at `speed`. */
function useStreamingReplay(
baseItems: TaskChatItem[],
speed: number,
@@ -19,15 +50,23 @@ function useStreamingReplay(
): TaskChatItem[] {
const [chars, setChars] = useState<number>(Number.MAX_SAFE_INTEGER);
const streamingIndex = baseItems.findIndex(
- (i) => (i.kind === "message" && i.streaming) || (i.kind === "thinking" && i.streaming),
+ (i) =>
+ (i.kind === "message" && i.streaming) ||
+ (i.kind === "turn" && !i.settled && i.liveStatus?.selfTalk != null),
);
+ const streamingItem = baseItems[streamingIndex];
+ const isInterstitial = streamingItem?.kind === "turn";
const fullText = useMemo(() => {
const it = baseItems[streamingIndex];
if (!it) return "";
if (it.kind === "message") return it.text;
- if (it.kind === "thinking") return it.lines.join("\n");
+ if (it.kind === "turn") return it.liveStatus?.selfTalk ?? "";
return "";
}, [baseItems, streamingIndex]);
+ const segments = useMemo(
+ () => (isInterstitial ? selfTalkSegments(fullText) : []),
+ [isInterstitial, fullText],
+ );
useEffect(() => {
if (streamingIndex < 0) {
@@ -36,14 +75,21 @@ function useStreamingReplay(
}
setChars(0);
let n = 0;
+ // One extra tick past the last segment lands on the trailing undefined
+ // (message ended) state.
+ const stopAt = isInterstitial
+ ? segments.reduce((a, s) => a + s.length, 0) +
+ SELF_TALK_GAP_TICKS * Math.max(0, segments.length - 1) +
+ 1
+ : fullText.length;
const baseIntervalMs = 24;
const interval = window.setInterval(() => {
n += 1;
setChars(n);
- if (n >= fullText.length) window.clearInterval(interval);
+ if (n >= stopAt) window.clearInterval(interval);
}, Math.max(4, baseIntervalMs / speed));
return () => window.clearInterval(interval);
- }, [streamingIndex, fullText, speed, playToken]);
+ }, [streamingIndex, fullText, isInterstitial, segments, speed, playToken]);
if (streamingIndex < 0) return baseItems;
return baseItems.map((it, idx) => {
@@ -51,7 +97,12 @@ function useStreamingReplay(
const shown = fullText.slice(0, chars);
const done = chars >= fullText.length;
if (it.kind === "message") return { ...it, text: shown, streaming: !done };
- if (it.kind === "thinking") return { ...it, lines: shown.split("\n"), streaming: !done };
+ // Parent-row interstitial (PAP-361/368): reveal the scripted updates
+ // segment by segment; the pill holds each finished one until the next
+ // swaps in.
+ if (it.kind === "turn" && it.liveStatus) {
+ return { ...it, liveStatus: { ...it.liveStatus, selfTalk: selfTalkAtTick(segments, chars) } };
+ }
return it;
});
}