mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-20 15:09:57 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Operators talk to their agents on the issue detail page. An experimental "Chat-Style Tasks" view (#10606) makes that page read as a conversation instead of a ticket form. > - The first release of that view shipped with a plain-text composer, no visible narration while an agent works, and a desktop-only layout. > - Users write formatted replies, paste screenshots, and follow long agent runs from their phones. The experimental view should support all of that before it can graduate. > - This pull request is the next iteration of the same experiment: a rich-text composer with attachments, live-turn narration on the status line, cleaner settled-turn history, and a mobile layout. > - The benefit is a chat view that feels alive while the agent works and stays readable after it finishes, on desktop and mobile, still fully behind the existing opt-in flag. ## Linked Issues or Issue Description Refs #49 (chat with agents is a much-wanted feature). Refs #10606 (the merged first release of the experimental chat-style task view; this PR iterates on it). Related PRs found in the dedup search: - #8228 — open PR that polishes the classic issue chat composer. It targets the flag-off legacy path; this PR only changes the flag-on experimental view. - #10466 — merged blockquote-recovery fix in the shared MarkdownEditor. This PR now reuses that editor inside the chat composer. **What existing behavior does this improve?** The experimental "Chat-Style Tasks" view on the issue detail page (Settings → Experimental, `enableTaskChatRedesign`, default off). **Subsystem affected** UI (issue detail page, chat-style task view). **Current behavior** With the experiment enabled, the composer is a plain textarea with no formatting, no attachment preview, and no mention support. While an agent runs, the status line shows only a static label, and the agent's narration text is hidden. Finished runs render one settled row per turn, so a run with many short turns produces a long list of near-duplicate "Worked" rows, and turns without a comment append at the bottom out of order. On mobile, the desktop bounded-height thread makes the page scroll poorly. **Proposed behavior** The composer uses the shared MarkdownEditor: markdown formatting, mentions, image paste with thumbnail previews, and non-image attachment chips. Sending posts on Cmd/Ctrl+Enter. While an agent runs, the status line rotates playful status words and surfaces the agent's own narration as short interstitial updates: each update holds for a minimum dwell, is replaced only when superseded, and slides through a one-line viewport with tokenized motion. Back-to-back settled turns coalesce into one "Worked" row with summed durations and re-derived tool counts, and comment-less settled turns insert chronologically at their run's start time. On mobile, the thread renders in the document flow with window auto-follow and a sticky safe-area composer; the desktop layout is unchanged. **Reason and benefit** The chat view is only convincing if it feels like a conversation with a working agent. Rich text and screenshots are table stakes for chat input. Live narration gives moment-to-moment feedback without opening transcripts. Coalesced history keeps long-running tasks readable. Mobile support lets operators follow runs away from their desks. **Breaking changes** None. Every change is gated behind the existing `enableTaskChatRedesign` flag, which is off by default. The flag-off page is unchanged. ## What Changed - `TaskChatComposer` swaps its textarea for the shared `MarkdownEditor`: markdown formatting, mentions, image paste with object-URL thumbnail previews (revoked on clear and unmount), and posting on Cmd/Ctrl+Enter. - Non-image attachments render as chips on a new shared `ui/attachment.tsx` primitive (adds the `@base-ui/react` dependency it builds on). - New `status-whimsy.ts`: deterministic rotation of playful status words on the live status line. - Live interstitial narration: the transcript adapter tags agent self-talk, and the live status line shows it as ephemeral one-line updates with a ~4s minimum dwell, hold-until-superseded replacement, and a slide transition driven by new `--motion-line-scroll` tokens (cataloged in `motion-tokens.ts`, which a test keeps 1:1 with `index.css`). Hover affordance applies only to the status line, with no leading icon. - Settled-turn history: `coalesceSettledTurns` merges back-to-back settled agent turns into one "Worked" row (summed per-run durations, tool counts re-derived from the merged turn); `assembleThreadItems` inserts comment-less settled turns chronologically at run start instead of appending them at the bottom; settled turns render tool rows only (the separate thinking block component is removed). - The "Worked" summary attaches to the reply timestamp row, and thread timestamps are always visible. - Mobile layout: the thread renders with `scroll={false}` in the page scroll, a new `useWindowAutoFollow` hook keeps the window pinned to new content, the composer is sticky with safe-area padding, and the editor uses 16px text so iOS does not zoom on focus. The desktop bounded chain is untouched. - New `TaskChatDescriptionBubble` renders the issue description as the first chat bubble, and `McpIcon` gives MCP tools a distinct icon. - `IssueDetail.test.tsx` stubs `TaskChatThread`: the composer's `@mdxeditor` dependency cannot load under jsdom's CSSOM, and the suite exercises the flag-off path. ## Verification - `pnpm check:token-gates` — 3/3 CLEAN. - `node scripts/check-task-chat-motion.mjs` — OK (30 files scanned, seams present). - `cd ui && npx tsc -b` — clean. - `cd ui && pnpm vitest run` — 3,482 of 3,483 tests pass locally. The one failure is the `IssueProperties.test.tsx` monitor-row time-formatting test, which is timezone-sensitive: it fails identically on unmodified `origin/master` in a non-UTC timezone and passes with `TZ=UTC`. It is not related to this change. - Manual: enable "Chat-Style Tasks" in Settings → Experimental and open an issue with an assigned agent. Comment to start a run: the status line rotates status words and shows the agent's narration as short held updates. After the run, consecutive turns fold into one "Worked" row under the reply timestamp. Paste an image into the composer to see a thumbnail chip; attach a non-image file to see a file chip; send with Cmd+Enter. Open the same issue in a narrow viewport to see the document-flow layout with the sticky composer. - Visual snapshot baselines are intentionally not updated: per `doc/design/DECISION-SHEET.md`, "Per-change snapshot verification demoted to dormant (Jul 13 2026)". ## Risks - The composer now loads the shared MarkdownEditor inside the chat view. The editor is already used across the app (issue descriptions, comments), so its behavior is well exercised; composer-specific handling (paste, attachments, submit keys) is covered by new tests. - The transcript adapter changes how live narration and settled turns are derived from run logs. Malformed or legacy logs degrade to generic rows rather than crashing, and the adapter suites cover the merge and ordering rules. - Object URLs for paste previews are revoked on send-clear and unmount to avoid leaks; jsdom environments without `URL.createObjectURL` are guarded. - All changes are behind the default-off `enableTaskChatRedesign` flag. Overall risk with the flag off is low. ## Model Used - Claude (Anthropic), model id `claude-fable-5` (Claude Fable 5), extended thinking enabled, agentic tool use (file editing, shell, test execution) via Claude Code / Claude Agent SDK. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
669 lines
25 KiB
TypeScript
669 lines
25 KiB
TypeScript
/**
|
||
* Live adapter: map a run's streaming TranscriptEntry[] (from
|
||
* useLiveRunTranscripts — the same source the current thread consumes) into the
|
||
* redesign's TaskChatItem[]. This is what lets a real task stream
|
||
* thinking → tool → diff → responding while a run is in flight, rather than
|
||
* only showing the final message once the turn produces a comment.
|
||
*/
|
||
import type { TranscriptEntry } from "@/adapters";
|
||
import type {
|
||
TaskChatDiff,
|
||
TaskChatItem,
|
||
TaskChatToolItem,
|
||
TaskChatTurnChildItem,
|
||
TaskChatTurnItem,
|
||
} from "./task-chat-model";
|
||
import { isGenericToolName, mcpToolSegment, toolTaxonomy } from "./tool-taxonomy";
|
||
|
||
const TERMINAL_STATUSES = new Set([
|
||
"failed",
|
||
"timed_out",
|
||
"cancelled",
|
||
"interrupted",
|
||
"succeeded",
|
||
]);
|
||
|
||
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";
|
||
return "context";
|
||
}
|
||
|
||
/** Param keys probed (in order) for a tool call's one-line mono "target". */
|
||
const TARGET_KEYS = [
|
||
"file_path",
|
||
"path",
|
||
"notebook_path",
|
||
"command",
|
||
"pattern",
|
||
"query",
|
||
"url",
|
||
"prompt",
|
||
"description",
|
||
"skill",
|
||
"subject",
|
||
] as const;
|
||
|
||
const TARGET_MAX = 96;
|
||
|
||
function clip(text: string, max: number): string {
|
||
const oneLine = text.replace(/\s+/g, " ").trim();
|
||
return oneLine.length > max ? `${oneLine.slice(0, max - 1)}…` : oneLine;
|
||
}
|
||
|
||
/**
|
||
* Summarize a tool call's input into the v7 toolrow target: the most
|
||
* identifying parameter when the input is a keyed object, else a clipped
|
||
* rendering of the raw input. Returns undefined when there is nothing useful.
|
||
*/
|
||
export function summarizeToolInput(input: unknown): string | undefined {
|
||
if (input == null) return undefined;
|
||
if (typeof input === "string") return input.trim() ? clip(input, TARGET_MAX) : undefined;
|
||
if (typeof input !== "object") return clip(String(input), TARGET_MAX);
|
||
const record = input as Record<string, unknown>;
|
||
for (const key of TARGET_KEYS) {
|
||
const value = record[key];
|
||
if (typeof value === "string" && value.trim()) return clip(value, TARGET_MAX);
|
||
}
|
||
// The acpx log parser synthesizes { text, status } onto tool inputs from the
|
||
// event's summary line — presentation noise, not call parameters.
|
||
const entries = Object.entries(record).filter(
|
||
([k, v]) =>
|
||
(typeof v === "string" || typeof v === "number" || typeof v === "boolean") &&
|
||
k !== "text" &&
|
||
k !== "status",
|
||
);
|
||
if (entries.length === 0) return undefined;
|
||
return clip(entries.map(([k, v]) => `${k}: ${String(v)}`).join(", "), TARGET_MAX);
|
||
}
|
||
|
||
/**
|
||
* Display name for a tool call. Live acpx `tool_call` events carry real names
|
||
* ("Read", "Bash", mcp__server__tool); legacy stored logs may not — those fall
|
||
* back to a generic "Tool" row. MCP names collapse to their tool segment.
|
||
*/
|
||
export function toolDisplayName(name: string | undefined | null): string {
|
||
const raw = (name ?? "").trim();
|
||
if (isGenericToolName(raw)) return "Tool";
|
||
const mcp = mcpToolSegment(raw);
|
||
if (mcp) return mcp;
|
||
return raw.charAt(0).toUpperCase() + raw.slice(1);
|
||
}
|
||
|
||
/** "Thought for Ns" once a coalesced thinking group spans ≥1s. */
|
||
function thoughtDurationLabel(startTs: string | undefined, endTs: string): string | undefined {
|
||
if (!startTs) return undefined;
|
||
const start = Date.parse(startTs);
|
||
const end = Date.parse(endTs);
|
||
if (!Number.isFinite(start) || !Number.isFinite(end)) return undefined;
|
||
const secs = Math.round((end - start) / 1000);
|
||
if (secs < 1) return undefined;
|
||
return secs < 60 ? `Thought for ${secs}s` : `Thought for ${Math.floor(secs / 60)}m ${secs % 60}s`;
|
||
}
|
||
|
||
const DETAIL_MAX = 600;
|
||
|
||
/** Result content → the expandable mono detail block (clipped, trimmed). */
|
||
function formatToolResultDetail(content: unknown): string | undefined {
|
||
if (content == null) return undefined;
|
||
const text = typeof content === "string" ? content : String(content);
|
||
const trimmed = text.trim();
|
||
if (!trimmed) return undefined;
|
||
return trimmed.length > DETAIL_MAX ? `${trimmed.slice(0, DETAIL_MAX)}\n…` : trimmed;
|
||
}
|
||
|
||
interface TranscriptAdapterOptions {
|
||
runId: string;
|
||
agentName?: string;
|
||
/** True while the run is still in flight (drives streaming cursors). */
|
||
running: boolean;
|
||
}
|
||
|
||
/**
|
||
* Reduce a transcript into ordered items, coalescing consecutive thinking and
|
||
* assistant deltas and threading tool_result/diff onto their tool_call. Mirrors
|
||
* buildAssistantPartsFromTranscript's grouping, emitting our presentation model.
|
||
*/
|
||
export function transcriptToTaskChatItems(
|
||
entries: readonly TranscriptEntry[],
|
||
{ runId, agentName, running }: TranscriptAdapterOptions,
|
||
): TaskChatItem[] {
|
||
const items: TaskChatItem[] = [];
|
||
const toolIndexById = new Map<string, number>();
|
||
const thinkingStartTs = new Map<number, string>();
|
||
let lastToolIndex = -1;
|
||
let thinkingIndex = -1;
|
||
let messageIndex = -1;
|
||
|
||
const resetInline = () => {
|
||
thinkingIndex = -1;
|
||
messageIndex = -1;
|
||
};
|
||
|
||
for (const [i, entry] of entries.entries()) {
|
||
switch (entry.kind) {
|
||
case "thinking": {
|
||
if (!entry.text) break;
|
||
if (thinkingIndex >= 0) {
|
||
const it = items[thinkingIndex];
|
||
if (it.kind === "thinking") {
|
||
it.lines.push(...entry.text.split("\n"));
|
||
const startTs = thinkingStartTs.get(thinkingIndex);
|
||
const label = thoughtDurationLabel(startTs, entry.ts);
|
||
if (label) it.summaryLabel = label;
|
||
}
|
||
} else {
|
||
items.push({
|
||
id: `${runId}:think:${i}`,
|
||
kind: "thinking",
|
||
lines: entry.text.split("\n"),
|
||
streaming: running,
|
||
// Settled history folds its thinking behind the header (v7);
|
||
// the in-flight run streams it expanded.
|
||
collapsed: !running,
|
||
});
|
||
thinkingIndex = items.length - 1;
|
||
thinkingStartTs.set(thinkingIndex, entry.ts);
|
||
messageIndex = -1;
|
||
}
|
||
break;
|
||
}
|
||
case "assistant": {
|
||
if (!entry.text) break;
|
||
if (messageIndex >= 0) {
|
||
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",
|
||
author: "agent",
|
||
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;
|
||
}
|
||
break;
|
||
}
|
||
case "tool_call": {
|
||
const toolCallId = entry.toolUseId || `tool-${i}`;
|
||
const existingIndex = toolIndexById.get(toolCallId);
|
||
const existing = existingIndex != null ? items[existingIndex] : undefined;
|
||
if (existing?.kind === "tool") {
|
||
// tool_call_update for a call already in the list: merge. Updates
|
||
// often omit the title (acpx fills in a literal "tool call"), so a
|
||
// generic name must never displace the initial call's real one. ACP
|
||
// also retitles a call to its invocation once known ("Terminal" →
|
||
// "ls -la"); that is detail for the target slot, not a new identity.
|
||
if (!isGenericToolName(entry.name)) {
|
||
if (isGenericToolName(existing.rawName)) {
|
||
existing.name = toolDisplayName(entry.name);
|
||
existing.rawName = entry.name ?? undefined;
|
||
} else if (!existing.target && entry.name !== existing.rawName) {
|
||
existing.target = clip(entry.name!, TARGET_MAX);
|
||
}
|
||
}
|
||
lastToolIndex = existingIndex!;
|
||
} else {
|
||
items.push({
|
||
id: `${runId}:tool:${toolCallId}`,
|
||
kind: "tool",
|
||
name: toolDisplayName(entry.name),
|
||
rawName: entry.name ?? undefined,
|
||
target: summarizeToolInput(entry.input),
|
||
status: "in_progress",
|
||
});
|
||
toolIndexById.set(toolCallId, items.length - 1);
|
||
lastToolIndex = items.length - 1;
|
||
}
|
||
resetInline();
|
||
break;
|
||
}
|
||
case "tool_result": {
|
||
const toolCallId = entry.toolUseId || `tool-result-${i}`;
|
||
const idx = toolIndexById.get(toolCallId);
|
||
if (idx != null) {
|
||
const existing = items[idx];
|
||
if (existing.kind === "tool") {
|
||
existing.status = entry.isError ? "failed" : "completed";
|
||
if (isGenericToolName(existing.rawName) && !isGenericToolName(entry.toolName)) {
|
||
existing.name = toolDisplayName(entry.toolName);
|
||
existing.rawName = entry.toolName;
|
||
}
|
||
if (!existing.detail) {
|
||
const detail = formatToolResultDetail(entry.content);
|
||
if (detail) existing.detail = detail;
|
||
}
|
||
}
|
||
}
|
||
resetInline();
|
||
break;
|
||
}
|
||
case "diff": {
|
||
const line = { kind: diffKind(entry.changeType), text: entry.text ?? "" };
|
||
if (lastToolIndex >= 0 && items[lastToolIndex].kind === "tool") {
|
||
const tool = items[lastToolIndex] as TaskChatToolItem;
|
||
const diff: TaskChatDiff = tool.diff ?? { added: 0, removed: 0, lines: [] };
|
||
diff.lines = diff.lines ?? [];
|
||
diff.lines.push(line);
|
||
if (line.kind === "add") diff.added += 1;
|
||
if (line.kind === "remove") diff.removed += 1;
|
||
tool.diff = diff;
|
||
} else {
|
||
items.push({
|
||
id: `${runId}:diff:${i}`,
|
||
kind: "tool",
|
||
name: "Edit",
|
||
status: "completed",
|
||
diff: {
|
||
added: line.kind === "add" ? 1 : 0,
|
||
removed: line.kind === "remove" ? 1 : 0,
|
||
lines: [line],
|
||
},
|
||
});
|
||
lastToolIndex = items.length - 1;
|
||
}
|
||
resetInline();
|
||
break;
|
||
}
|
||
// init / result / stderr / stdout / system / user carry no thread-visible
|
||
// content in the live turn (status is rendered separately).
|
||
default:
|
||
break;
|
||
}
|
||
}
|
||
|
||
// 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);
|
||
if (totalSec < 1) return "1s";
|
||
if (totalSec < 60) return `${totalSec}s`;
|
||
const min = Math.floor(totalSec / 60);
|
||
const sec = totalSec % 60;
|
||
return sec === 0 ? `${min}m` : `${min}m ${sec}s`;
|
||
}
|
||
|
||
function formatTokensLabel(tokens: number): string | undefined {
|
||
if (!Number.isFinite(tokens) || tokens <= 0) return undefined;
|
||
const label = tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : `${tokens}`;
|
||
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
|
||
* caller-supplied run duration and falls back to the transcript's ts span.
|
||
*/
|
||
export function buildTurnSummary(
|
||
entries: readonly TranscriptEntry[],
|
||
opts: { durationMs?: number; failed?: boolean } = {},
|
||
): TaskChatTurnItem["summary"] {
|
||
const toolIds = new Set<string>();
|
||
let added = 0;
|
||
let removed = 0;
|
||
let tokens = 0;
|
||
for (const [i, entry] of entries.entries()) {
|
||
// Each status change of a call logs its own tool_call entry sharing the
|
||
// toolUseId; count unique calls so the folded summary matches the rows the
|
||
// expanded list renders (same `tool-${i}` fallback as the parser above).
|
||
if (entry.kind === "tool_call") toolIds.add(entry.toolUseId || `tool-${i}`);
|
||
else if (entry.kind === "diff") {
|
||
if (entry.changeType === "add") added += 1;
|
||
else if (entry.changeType === "remove") removed += 1;
|
||
} else if (entry.kind === "result") {
|
||
tokens += (entry.inputTokens || 0) + (entry.outputTokens || 0);
|
||
}
|
||
}
|
||
const durationMs = opts.durationMs ?? transcriptSpanMs(entries);
|
||
return {
|
||
durationLabel: durationMs != null ? formatDurationLabel(durationMs) : undefined,
|
||
toolCount: toolIds.size,
|
||
added,
|
||
removed,
|
||
tokensLabel: formatTokensLabel(tokens),
|
||
failed: opts.failed || undefined,
|
||
};
|
||
}
|
||
|
||
/** 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];
|
||
if (entry.kind === "tool_call") {
|
||
// A tail update may carry the generic placeholder name or a retitle to
|
||
// the invocation ("Terminal" → "ls -la"): the call's FIRST real name is
|
||
// its identity, and a differing later title is the invocation detail.
|
||
let name = entry.name;
|
||
let invocation: string | undefined;
|
||
if (entry.toolUseId) {
|
||
for (const prev of entries) {
|
||
if (prev === entry) break;
|
||
if (
|
||
prev.kind === "tool_call" &&
|
||
prev.toolUseId === entry.toolUseId &&
|
||
!isGenericToolName(prev.name)
|
||
) {
|
||
if (!isGenericToolName(entry.name) && entry.name !== prev.name) {
|
||
invocation = entry.name;
|
||
}
|
||
name = prev.name;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
const target =
|
||
summarizeToolInput(entry.input) ?? (invocation ? clip(invocation, TARGET_MAX) : undefined);
|
||
const display = toolDisplayName(name);
|
||
return {
|
||
label: toolTaxonomy(name).verbLabel,
|
||
detail: target ? `${display} · ${target}` : display,
|
||
toolName: name ?? undefined,
|
||
};
|
||
}
|
||
if (entry.kind === "tool_result") break;
|
||
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" };
|
||
}
|