Merge pull request #648 from paperclipai/paperclip-nicer-runlogs-formats

Humanize run transcripts and polish transcript UX
This commit is contained in:
Dotta authored and GitHub committed 2026-03-11 17:02:33 -05:00
commit df121c61dc
22 files changed
+2094 -1102

No files matched your search

+66 -420
View File
@@ -1,191 +1,19 @@
import { useEffect, useMemo, useRef, useState, type MutableRefObject } from "react";
import { useMemo } from "react";
import { Link } from "@/lib/router";
import { useQuery } from "@tanstack/react-query";
import type { Issue, LiveEvent } from "@paperclipai/shared";
import type { Issue } from "@paperclipai/shared";
import { heartbeatsApi, type LiveRunForIssue } from "../api/heartbeats";
import { issuesApi } from "../api/issues";
import { getUIAdapter } from "../adapters";
import type { TranscriptEntry } from "../adapters";
import { queryKeys } from "../lib/queryKeys";
import { cn, relativeTime } from "../lib/utils";
import { ExternalLink } from "lucide-react";
import { Identity } from "./Identity";
import { RunTranscriptView } from "./transcript/RunTranscriptView";
import { useLiveRunTranscripts } from "./transcript/useLiveRunTranscripts";
type FeedTone = "info" | "warn" | "error" | "assistant" | "tool";
interface FeedItem {
id: string;
ts: string;
runId: string;
agentId: string;
agentName: string;
text: string;
tone: FeedTone;
dedupeKey: string;
streamingKind?: "assistant" | "thinking";
}
const MAX_FEED_ITEMS = 40;
const MAX_FEED_TEXT_LENGTH = 220;
const MAX_STREAMING_TEXT_LENGTH = 4000;
const MIN_DASHBOARD_RUNS = 4;
function readString(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value : null;
}
function summarizeEntry(entry: TranscriptEntry): { text: string; tone: FeedTone } | null {
if (entry.kind === "assistant") {
const text = entry.text.trim();
return text ? { text, tone: "assistant" } : null;
}
if (entry.kind === "thinking") {
const text = entry.text.trim();
return text ? { text: `[thinking] ${text}`, tone: "info" } : null;
}
if (entry.kind === "tool_call") {
return { text: `tool ${entry.name}`, tone: "tool" };
}
if (entry.kind === "tool_result") {
const base = entry.content.trim();
return {
text: entry.isError ? `tool error: ${base}` : `tool result: ${base}`,
tone: entry.isError ? "error" : "tool",
};
}
if (entry.kind === "stderr") {
const text = entry.text.trim();
return text ? { text, tone: "error" } : null;
}
if (entry.kind === "system") {
const text = entry.text.trim();
return text ? { text, tone: "warn" } : null;
}
if (entry.kind === "stdout") {
const text = entry.text.trim();
return text ? { text, tone: "info" } : null;
}
return null;
}
function createFeedItem(
run: LiveRunForIssue,
ts: string,
text: string,
tone: FeedTone,
nextId: number,
options?: {
streamingKind?: "assistant" | "thinking";
preserveWhitespace?: boolean;
},
): FeedItem | null {
if (!text.trim()) return null;
const base = options?.preserveWhitespace ? text : text.trim();
const maxLength = options?.streamingKind ? MAX_STREAMING_TEXT_LENGTH : MAX_FEED_TEXT_LENGTH;
const normalized = base.length > maxLength ? base.slice(-maxLength) : base;
return {
id: `${run.id}:${nextId}`,
ts,
runId: run.id,
agentId: run.agentId,
agentName: run.agentName,
text: normalized,
tone,
dedupeKey: `feed:${run.id}:${ts}:${tone}:${normalized}`,
streamingKind: options?.streamingKind,
};
}
function parseStdoutChunk(
run: LiveRunForIssue,
chunk: string,
ts: string,
pendingByRun: Map<string, string>,
nextIdRef: MutableRefObject<number>,
): FeedItem[] {
const pendingKey = `${run.id}:stdout`;
const combined = `${pendingByRun.get(pendingKey) ?? ""}${chunk}`;
const split = combined.split(/\r?\n/);
pendingByRun.set(pendingKey, split.pop() ?? "");
const adapter = getUIAdapter(run.adapterType);
const summarized: Array<{ text: string; tone: FeedTone; streamingKind?: "assistant" | "thinking" }> = [];
const appendSummary = (entry: TranscriptEntry) => {
if (entry.kind === "assistant" && entry.delta) {
const text = entry.text;
if (!text.trim()) return;
const last = summarized[summarized.length - 1];
if (last && last.streamingKind === "assistant") {
last.text += text;
} else {
summarized.push({ text, tone: "assistant", streamingKind: "assistant" });
}
return;
}
if (entry.kind === "thinking" && entry.delta) {
const text = entry.text;
if (!text.trim()) return;
const last = summarized[summarized.length - 1];
if (last && last.streamingKind === "thinking") {
last.text += text;
} else {
summarized.push({ text: `[thinking] ${text}`, tone: "info", streamingKind: "thinking" });
}
return;
}
const summary = summarizeEntry(entry);
if (!summary) return;
summarized.push({ text: summary.text, tone: summary.tone });
};
const items: FeedItem[] = [];
for (const line of split.slice(-8)) {
const trimmed = line.trim();
if (!trimmed) continue;
const parsed = adapter.parseStdoutLine(trimmed, ts);
if (parsed.length === 0) {
const fallback = createFeedItem(run, ts, trimmed, "info", nextIdRef.current++);
if (fallback) items.push(fallback);
continue;
}
for (const entry of parsed) {
appendSummary(entry);
}
}
for (const summary of summarized) {
const item = createFeedItem(run, ts, summary.text, summary.tone, nextIdRef.current++, {
streamingKind: summary.streamingKind,
preserveWhitespace: !!summary.streamingKind,
});
if (item) items.push(item);
}
return items;
}
function parseStderrChunk(
run: LiveRunForIssue,
chunk: string,
ts: string,
pendingByRun: Map<string, string>,
nextIdRef: MutableRefObject<number>,
): FeedItem[] {
const pendingKey = `${run.id}:stderr`;
const combined = `${pendingByRun.get(pendingKey) ?? ""}${chunk}`;
const split = combined.split(/\r?\n/);
pendingByRun.set(pendingKey, split.pop() ?? "");
const items: FeedItem[] = [];
for (const line of split.slice(-8)) {
const item = createFeedItem(run, ts, line, "error", nextIdRef.current++);
if (item) items.push(item);
}
return items;
}
function isRunActive(run: LiveRunForIssue): boolean {
return run.status === "queued" || run.status === "running";
}
@@ -195,11 +23,6 @@ interface ActiveAgentsPanelProps {
}
export function ActiveAgentsPanel({ companyId }: ActiveAgentsPanelProps) {
const [feedByRun, setFeedByRun] = useState<Map<string, FeedItem[]>>(new Map());
const seenKeysRef = useRef(new Set<string>());
const pendingByRunRef = useRef(new Map<string, string>());
const nextIdRef = useRef(1);
const { data: liveRuns } = useQuery({
queryKey: [...queryKeys.liveRuns(companyId), "dashboard"],
queryFn: () => heartbeatsApi.liveRunsForCompany(companyId, MIN_DASHBOARD_RUNS),
@@ -220,179 +43,30 @@ export function ActiveAgentsPanel({ companyId }: ActiveAgentsPanelProps) {
return map;
}, [issues]);
const runById = useMemo(() => new Map(runs.map((r) => [r.id, r])), [runs]);
const activeRunIds = useMemo(() => new Set(runs.filter(isRunActive).map((r) => r.id)), [runs]);
// Clean up pending buffers for runs that ended
useEffect(() => {
const stillActive = new Set<string>();
for (const runId of activeRunIds) {
stillActive.add(`${runId}:stdout`);
stillActive.add(`${runId}:stderr`);
}
for (const key of pendingByRunRef.current.keys()) {
if (!stillActive.has(key)) {
pendingByRunRef.current.delete(key);
}
}
}, [activeRunIds]);
// WebSocket connection for streaming
useEffect(() => {
if (activeRunIds.size === 0) return;
let closed = false;
let reconnectTimer: number | null = null;
let socket: WebSocket | null = null;
const appendItems = (runId: string, items: FeedItem[]) => {
if (items.length === 0) return;
setFeedByRun((prev) => {
const next = new Map(prev);
const existing = [...(next.get(runId) ?? [])];
for (const item of items) {
if (seenKeysRef.current.has(item.dedupeKey)) continue;
seenKeysRef.current.add(item.dedupeKey);
const last = existing[existing.length - 1];
if (
item.streamingKind &&
last &&
last.runId === item.runId &&
last.streamingKind === item.streamingKind
) {
const mergedText = `${last.text}${item.text}`;
const nextText =
mergedText.length > MAX_STREAMING_TEXT_LENGTH
? mergedText.slice(-MAX_STREAMING_TEXT_LENGTH)
: mergedText;
existing[existing.length - 1] = {
...last,
ts: item.ts,
text: nextText,
dedupeKey: last.dedupeKey,
};
continue;
}
existing.push(item);
}
if (seenKeysRef.current.size > 6000) {
seenKeysRef.current.clear();
}
next.set(runId, existing.slice(-MAX_FEED_ITEMS));
return next;
});
};
const scheduleReconnect = () => {
if (closed) return;
reconnectTimer = window.setTimeout(connect, 1500);
};
const connect = () => {
if (closed) return;
const protocol = window.location.protocol === "https:" ? "wss" : "ws";
const url = `${protocol}://${window.location.host}/api/companies/${encodeURIComponent(companyId)}/events/ws`;
socket = new WebSocket(url);
socket.onmessage = (message) => {
const raw = typeof message.data === "string" ? message.data : "";
if (!raw) return;
let event: LiveEvent;
try {
event = JSON.parse(raw) as LiveEvent;
} catch {
return;
}
if (event.companyId !== companyId) return;
const payload = event.payload ?? {};
const runId = readString(payload["runId"]);
if (!runId || !activeRunIds.has(runId)) return;
const run = runById.get(runId);
if (!run) return;
if (event.type === "heartbeat.run.event") {
const seq = typeof payload["seq"] === "number" ? payload["seq"] : null;
const eventType = readString(payload["eventType"]) ?? "event";
const messageText = readString(payload["message"]) ?? eventType;
const dedupeKey = `${runId}:event:${seq ?? `${eventType}:${messageText}:${event.createdAt}`}`;
if (seenKeysRef.current.has(dedupeKey)) return;
seenKeysRef.current.add(dedupeKey);
if (seenKeysRef.current.size > 6000) seenKeysRef.current.clear();
const tone = eventType === "error" ? "error" : eventType === "lifecycle" ? "warn" : "info";
const item = createFeedItem(run, event.createdAt, messageText, tone, nextIdRef.current++);
if (item) appendItems(run.id, [item]);
return;
}
if (event.type === "heartbeat.run.status") {
const status = readString(payload["status"]) ?? "updated";
const dedupeKey = `${runId}:status:${status}:${readString(payload["finishedAt"]) ?? ""}`;
if (seenKeysRef.current.has(dedupeKey)) return;
seenKeysRef.current.add(dedupeKey);
if (seenKeysRef.current.size > 6000) seenKeysRef.current.clear();
const tone = status === "failed" || status === "timed_out" ? "error" : "warn";
const item = createFeedItem(run, event.createdAt, `run ${status}`, tone, nextIdRef.current++);
if (item) appendItems(run.id, [item]);
return;
}
if (event.type === "heartbeat.run.log") {
const chunk = readString(payload["chunk"]);
if (!chunk) return;
const stream = readString(payload["stream"]) === "stderr" ? "stderr" : "stdout";
if (stream === "stderr") {
appendItems(run.id, parseStderrChunk(run, chunk, event.createdAt, pendingByRunRef.current, nextIdRef));
return;
}
appendItems(run.id, parseStdoutChunk(run, chunk, event.createdAt, pendingByRunRef.current, nextIdRef));
}
};
socket.onerror = () => {
socket?.close();
};
socket.onclose = () => {
scheduleReconnect();
};
};
connect();
return () => {
closed = true;
if (reconnectTimer !== null) window.clearTimeout(reconnectTimer);
if (socket) {
socket.onmessage = null;
socket.onerror = null;
socket.onclose = null;
socket.close(1000, "active_agents_panel_unmount");
}
};
}, [activeRunIds, companyId, runById]);
const { transcriptByRun, hasOutputForRun } = useLiveRunTranscripts({
runs,
companyId,
maxChunksPerRun: 120,
});
return (
<div>
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide mb-3">
<h3 className="mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground">
Agents
</h3>
{runs.length === 0 ? (
<div className="border border-border rounded-lg p-4">
<div className="rounded-xl border border-border p-4">
<p className="text-sm text-muted-foreground">No recent agent runs.</p>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-2 sm:gap-4">
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2 sm:gap-4 xl:grid-cols-4">
{runs.map((run) => (
<AgentRunCard
key={run.id}
run={run}
issue={run.issueId ? issueById.get(run.issueId) : undefined}
feed={feedByRun.get(run.id) ?? []}
transcript={transcriptByRun.get(run.id) ?? []}
hasOutput={hasOutputForRun(run.id)}
isActive={isRunActive(run)}
/>
))}
@@ -405,104 +79,76 @@ export function ActiveAgentsPanel({ companyId }: ActiveAgentsPanelProps) {
function AgentRunCard({
run,
issue,
feed,
transcript,
hasOutput,
isActive,
}: {
run: LiveRunForIssue;
issue?: Issue;
feed: FeedItem[];
transcript: TranscriptEntry[];
hasOutput: boolean;
isActive: boolean;
}) {
const bodyRef = useRef<HTMLDivElement>(null);
const recent = feed.slice(-20);
useEffect(() => {
const body = bodyRef.current;
if (!body) return;
body.scrollTo({ top: body.scrollHeight, behavior: "smooth" });
}, [feed.length]);
return (
<div className={cn(
"flex flex-col rounded-lg border overflow-hidden min-h-[200px]",
"flex h-[320px] flex-col overflow-hidden rounded-xl border shadow-sm",
isActive
? "border-blue-500/30 bg-background/80 shadow-[0_0_12px_rgba(59,130,246,0.08)]"
: "border-border bg-background/50",
? "border-cyan-500/25 bg-cyan-500/[0.04] shadow-[0_16px_40px_rgba(6,182,212,0.08)]"
: "border-border bg-background/70",
)}>
{/* Header */}
<div className="flex items-center justify-between px-3 py-2 border-b border-border/50">
<div className="flex items-center gap-2 min-w-0">
{isActive ? (
<span className="relative flex h-2 w-2 shrink-0">
<span className="animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75" />
<span className="relative inline-flex rounded-full h-2 w-2 bg-blue-500" />
</span>
) : (
<span className="flex h-2 w-2 shrink-0">
<span className="inline-flex rounded-full h-2 w-2 bg-muted-foreground/40" />
</span>
)}
<Identity name={run.agentName} size="sm" />
{isActive && (
<span className="text-[11px] font-medium text-blue-600 dark:text-blue-400">Live</span>
)}
</div>
<Link
to={`/agents/${run.agentId}/runs/${run.id}`}
className="inline-flex items-center gap-1 text-[10px] text-muted-foreground hover:text-foreground shrink-0"
>
<ExternalLink className="h-2.5 w-2.5" />
</Link>
</div>
<div className="border-b border-border/60 px-3 py-3">
<div className="flex items-start justify-between gap-2">
<div className="min-w-0">
<div className="flex items-center gap-2">
{isActive ? (
<span className="relative flex h-2.5 w-2.5 shrink-0">
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-cyan-400 opacity-70" />
<span className="relative inline-flex h-2.5 w-2.5 rounded-full bg-cyan-500" />
</span>
) : (
<span className="inline-flex h-2.5 w-2.5 rounded-full bg-muted-foreground/35" />
)}
<Identity name={run.agentName} size="sm" />
</div>
<div className="mt-2 flex items-center gap-2 text-[11px] text-muted-foreground">
<span>{isActive ? "Live now" : run.finishedAt ? `Finished ${relativeTime(run.finishedAt)}` : `Started ${relativeTime(run.createdAt)}`}</span>
</div>
</div>
{/* Issue context */}
{run.issueId && (
<div className="px-3 py-1.5 border-b border-border/40 text-xs flex items-center gap-1 min-w-0">
<Link
to={`/issues/${issue?.identifier ?? run.issueId}`}
className={cn(
"hover:underline min-w-0 line-clamp-2 min-h-[2rem]",
isActive ? "text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300" : "text-muted-foreground hover:text-foreground",
)}
title={issue?.title ? `${issue?.identifier ?? run.issueId.slice(0, 8)} - ${issue.title}` : issue?.identifier ?? run.issueId.slice(0, 8)}
to={`/agents/${run.agentId}/runs/${run.id}`}
className="inline-flex items-center gap-1 rounded-full border border-border/70 bg-background/70 px-2 py-1 text-[10px] text-muted-foreground transition-colors hover:text-foreground"
>
{issue?.identifier ?? run.issueId.slice(0, 8)}
{issue?.title ? ` - ${issue.title}` : ""}
<ExternalLink className="h-2.5 w-2.5" />
</Link>
</div>
)}
{/* Feed body */}
<div ref={bodyRef} className="flex-1 max-h-[140px] overflow-y-auto p-2 font-mono text-[11px] space-y-1">
{isActive && recent.length === 0 && (
<div className="text-xs text-muted-foreground">Waiting for output...</div>
)}
{!isActive && recent.length === 0 && (
<div className="text-xs text-muted-foreground">
{run.finishedAt ? `Finished ${relativeTime(run.finishedAt)}` : `Started ${relativeTime(run.createdAt)}`}
{run.issueId && (
<div className="mt-3 rounded-lg border border-border/60 bg-background/60 px-2.5 py-2 text-xs">
<Link
to={`/issues/${issue?.identifier ?? run.issueId}`}
className={cn(
"line-clamp-2 hover:underline",
isActive ? "text-cyan-700 dark:text-cyan-300" : "text-muted-foreground hover:text-foreground",
)}
title={issue?.title ? `${issue?.identifier ?? run.issueId.slice(0, 8)} - ${issue.title}` : issue?.identifier ?? run.issueId.slice(0, 8)}
>
{issue?.identifier ?? run.issueId.slice(0, 8)}
{issue?.title ? ` - ${issue.title}` : ""}
</Link>
</div>
)}
{recent.map((item, index) => (
<div
key={item.id}
className={cn(
"flex gap-2 items-start",
index === recent.length - 1 && isActive && "animate-in fade-in slide-in-from-bottom-1 duration-300",
)}
>
<span className="text-[10px] text-muted-foreground shrink-0">{relativeTime(item.ts)}</span>
<span className={cn(
"min-w-0 break-words",
item.tone === "error" && "text-red-600 dark:text-red-300",
item.tone === "warn" && "text-amber-600 dark:text-amber-300",
item.tone === "assistant" && "text-emerald-700 dark:text-emerald-200",
item.tone === "tool" && "text-cyan-600 dark:text-cyan-300",
item.tone === "info" && "text-foreground/80",
)}>
{item.text}
</span>
</div>
))}
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-3">
<RunTranscriptView
entries={transcript}
density="compact"
limit={5}
streaming={isActive}
collapseStdout
emptyMessage={hasOutput ? "Waiting for transcript parsing..." : isActive ? "Waiting for output..." : "No transcript captured."}
/>
</div>
</div>
);
+86 -551
View File
@@ -1,262 +1,32 @@
import { useEffect, useMemo, useRef, useState, type MutableRefObject } from "react";
import { useMemo, useState } from "react";
import { Link } from "@/lib/router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import type { LiveEvent } from "@paperclipai/shared";
import { heartbeatsApi, type LiveRunForIssue } from "../api/heartbeats";
import { getUIAdapter } from "../adapters";
import type { TranscriptEntry } from "../adapters";
import { queryKeys } from "../lib/queryKeys";
import { cn, relativeTime, formatDateTime } from "../lib/utils";
import { formatDateTime } from "../lib/utils";
import { ExternalLink, Square } from "lucide-react";
import { Identity } from "./Identity";
import { StatusBadge } from "./StatusBadge";
import { RunTranscriptView } from "./transcript/RunTranscriptView";
import { useLiveRunTranscripts } from "./transcript/useLiveRunTranscripts";
interface LiveRunWidgetProps {
issueId: string;
companyId?: string | null;
}
type FeedTone = "info" | "warn" | "error" | "assistant" | "tool";
interface FeedItem {
id: string;
ts: string;
runId: string;
agentId: string;
agentName: string;
text: string;
tone: FeedTone;
dedupeKey: string;
streamingKind?: "assistant" | "thinking";
}
const MAX_FEED_ITEMS = 80;
const MAX_FEED_TEXT_LENGTH = 220;
const MAX_STREAMING_TEXT_LENGTH = 4000;
const LOG_POLL_INTERVAL_MS = 2000;
const LOG_READ_LIMIT_BYTES = 256_000;
function readString(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value : null;
}
function toIsoString(value: string | Date | null | undefined): string | null {
if (!value) return null;
return typeof value === "string" ? value : value.toISOString();
}
function summarizeEntry(entry: TranscriptEntry): { text: string; tone: FeedTone } | null {
if (entry.kind === "assistant") {
const text = entry.text.trim();
return text ? { text, tone: "assistant" } : null;
}
if (entry.kind === "thinking") {
const text = entry.text.trim();
return text ? { text: `[thinking] ${text}`, tone: "info" } : null;
}
if (entry.kind === "tool_call") {
return { text: `tool ${entry.name}`, tone: "tool" };
}
if (entry.kind === "tool_result") {
const base = entry.content.trim();
return {
text: entry.isError ? `tool error: ${base}` : `tool result: ${base}`,
tone: entry.isError ? "error" : "tool",
};
}
if (entry.kind === "stderr") {
const text = entry.text.trim();
return text ? { text, tone: "error" } : null;
}
if (entry.kind === "system") {
const text = entry.text.trim();
return text ? { text, tone: "warn" } : null;
}
if (entry.kind === "stdout") {
const text = entry.text.trim();
return text ? { text, tone: "info" } : null;
}
return null;
}
function createFeedItem(
run: LiveRunForIssue,
ts: string,
text: string,
tone: FeedTone,
nextId: number,
options?: {
streamingKind?: "assistant" | "thinking";
preserveWhitespace?: boolean;
},
): FeedItem | null {
if (!text.trim()) return null;
const base = options?.preserveWhitespace ? text : text.trim();
const maxLength = options?.streamingKind ? MAX_STREAMING_TEXT_LENGTH : MAX_FEED_TEXT_LENGTH;
const normalized = base.length > maxLength ? base.slice(-maxLength) : base;
return {
id: `${run.id}:${nextId}`,
ts,
runId: run.id,
agentId: run.agentId,
agentName: run.agentName,
text: normalized,
tone,
dedupeKey: `feed:${run.id}:${ts}:${tone}:${normalized}`,
streamingKind: options?.streamingKind,
};
}
function parseStdoutChunk(
run: LiveRunForIssue,
chunk: string,
ts: string,
pendingByRun: Map<string, string>,
nextIdRef: MutableRefObject<number>,
): FeedItem[] {
const pendingKey = `${run.id}:stdout`;
const combined = `${pendingByRun.get(pendingKey) ?? ""}${chunk}`;
const split = combined.split(/\r?\n/);
pendingByRun.set(pendingKey, split.pop() ?? "");
const adapter = getUIAdapter(run.adapterType);
const summarized: Array<{ text: string; tone: FeedTone; streamingKind?: "assistant" | "thinking" }> = [];
const appendSummary = (entry: TranscriptEntry) => {
if (entry.kind === "assistant" && entry.delta) {
const text = entry.text;
if (!text.trim()) return;
const last = summarized[summarized.length - 1];
if (last && last.streamingKind === "assistant") {
last.text += text;
} else {
summarized.push({ text, tone: "assistant", streamingKind: "assistant" });
}
return;
}
if (entry.kind === "thinking" && entry.delta) {
const text = entry.text;
if (!text.trim()) return;
const last = summarized[summarized.length - 1];
if (last && last.streamingKind === "thinking") {
last.text += text;
} else {
summarized.push({ text: `[thinking] ${text}`, tone: "info", streamingKind: "thinking" });
}
return;
}
const summary = summarizeEntry(entry);
if (!summary) return;
summarized.push({ text: summary.text, tone: summary.tone });
};
const items: FeedItem[] = [];
for (const line of split.slice(-8)) {
const trimmed = line.trim();
if (!trimmed) continue;
const parsed = adapter.parseStdoutLine(trimmed, ts);
if (parsed.length === 0) {
if (run.adapterType === "openclaw_gateway") {
continue;
}
const fallback = createFeedItem(run, ts, trimmed, "info", nextIdRef.current++);
if (fallback) items.push(fallback);
continue;
}
for (const entry of parsed) {
appendSummary(entry);
}
}
for (const summary of summarized) {
const item = createFeedItem(run, ts, summary.text, summary.tone, nextIdRef.current++, {
streamingKind: summary.streamingKind,
preserveWhitespace: !!summary.streamingKind,
});
if (item) items.push(item);
}
return items;
}
function parseStderrChunk(
run: LiveRunForIssue,
chunk: string,
ts: string,
pendingByRun: Map<string, string>,
nextIdRef: MutableRefObject<number>,
): FeedItem[] {
const pendingKey = `${run.id}:stderr`;
const combined = `${pendingByRun.get(pendingKey) ?? ""}${chunk}`;
const split = combined.split(/\r?\n/);
pendingByRun.set(pendingKey, split.pop() ?? "");
const items: FeedItem[] = [];
for (const line of split.slice(-8)) {
const item = createFeedItem(run, ts, line, "error", nextIdRef.current++);
if (item) items.push(item);
}
return items;
}
function parsePersistedLogContent(
runId: string,
content: string,
pendingByRun: Map<string, string>,
): Array<{ ts: string; stream: "stdout" | "stderr" | "system"; chunk: string }> {
if (!content) return [];
const pendingKey = `${runId}:records`;
const combined = `${pendingByRun.get(pendingKey) ?? ""}${content}`;
const split = combined.split("\n");
pendingByRun.set(pendingKey, split.pop() ?? "");
const parsed: Array<{ ts: string; stream: "stdout" | "stderr" | "system"; chunk: string }> = [];
for (const line of split) {
const trimmed = line.trim();
if (!trimmed) continue;
try {
const raw = JSON.parse(trimmed) as { ts?: unknown; stream?: unknown; chunk?: unknown };
const stream = raw.stream === "stderr" || raw.stream === "system" ? raw.stream : "stdout";
const chunk = typeof raw.chunk === "string" ? raw.chunk : "";
const ts = typeof raw.ts === "string" ? raw.ts : new Date().toISOString();
if (!chunk) continue;
parsed.push({ ts, stream, chunk });
} catch {
// Ignore malformed log rows.
}
}
return parsed;
function isRunActive(status: string): boolean {
return status === "queued" || status === "running";
}
export function LiveRunWidget({ issueId, companyId }: LiveRunWidgetProps) {
const queryClient = useQueryClient();
const [feed, setFeed] = useState<FeedItem[]>([]);
const [cancellingRunIds, setCancellingRunIds] = useState(new Set<string>());
const seenKeysRef = useRef(new Set<string>());
const pendingByRunRef = useRef(new Map<string, string>());
const pendingLogRowsByRunRef = useRef(new Map<string, string>());
const logOffsetByRunRef = useRef(new Map<string, number>());
const runMetaByIdRef = useRef(new Map<string, { agentId: string; agentName: string }>());
const nextIdRef = useRef(1);
const bodyRef = useRef<HTMLDivElement>(null);
const handleCancelRun = async (runId: string) => {
setCancellingRunIds((prev) => new Set(prev).add(runId));
try {
await heartbeatsApi.cancel(runId);
queryClient.invalidateQueries({ queryKey: queryKeys.issues.liveRuns(issueId) });
queryClient.invalidateQueries({ queryKey: queryKeys.issues.activeRun(issueId) });
} finally {
setCancellingRunIds((prev) => {
const next = new Set(prev);
next.delete(runId);
return next;
});
}
};
const { data: liveRuns } = useQuery({
queryKey: queryKeys.issues.liveRuns(issueId),
@@ -297,329 +67,94 @@ export function LiveRunWidget({ issueId, companyId }: LiveRunWidgetProps) {
);
}, [activeRun, issueId, liveRuns]);
const runById = useMemo(() => new Map(runs.map((run) => [run.id, run])), [runs]);
const activeRunIds = useMemo(() => new Set(runs.map((run) => run.id)), [runs]);
const runIdsKey = useMemo(
() => runs.map((run) => run.id).sort((a, b) => a.localeCompare(b)).join(","),
[runs],
);
const appendItems = (items: FeedItem[]) => {
if (items.length === 0) return;
setFeed((prev) => {
const next = [...prev];
for (const item of items) {
if (seenKeysRef.current.has(item.dedupeKey)) continue;
seenKeysRef.current.add(item.dedupeKey);
const { transcriptByRun, hasOutputForRun } = useLiveRunTranscripts({ runs, companyId });
const last = next[next.length - 1];
if (
item.streamingKind &&
last &&
last.runId === item.runId &&
last.streamingKind === item.streamingKind
) {
const mergedText = `${last.text}${item.text}`;
const nextText =
mergedText.length > MAX_STREAMING_TEXT_LENGTH
? mergedText.slice(-MAX_STREAMING_TEXT_LENGTH)
: mergedText;
next[next.length - 1] = {
...last,
ts: item.ts,
text: nextText,
dedupeKey: last.dedupeKey,
};
continue;
}
next.push(item);
}
if (seenKeysRef.current.size > 6000) {
seenKeysRef.current.clear();
}
if (next.length === prev.length) return prev;
return next.slice(-MAX_FEED_ITEMS);
});
const handleCancelRun = async (runId: string) => {
setCancellingRunIds((prev) => new Set(prev).add(runId));
try {
await heartbeatsApi.cancel(runId);
queryClient.invalidateQueries({ queryKey: queryKeys.issues.liveRuns(issueId) });
queryClient.invalidateQueries({ queryKey: queryKeys.issues.activeRun(issueId) });
} finally {
setCancellingRunIds((prev) => {
const next = new Set(prev);
next.delete(runId);
return next;
});
}
};
useEffect(() => {
const body = bodyRef.current;
if (!body) return;
body.scrollTo({ top: body.scrollHeight, behavior: "smooth" });
}, [feed.length]);
useEffect(() => {
for (const run of runs) {
runMetaByIdRef.current.set(run.id, { agentId: run.agentId, agentName: run.agentName });
}
}, [runs]);
useEffect(() => {
const stillActive = new Set<string>();
for (const runId of activeRunIds) {
stillActive.add(`${runId}:stdout`);
stillActive.add(`${runId}:stderr`);
}
for (const key of pendingByRunRef.current.keys()) {
if (!stillActive.has(key)) {
pendingByRunRef.current.delete(key);
}
}
const liveRunIds = new Set(activeRunIds);
for (const key of pendingLogRowsByRunRef.current.keys()) {
const runId = key.replace(/:records$/, "");
if (!liveRunIds.has(runId)) {
pendingLogRowsByRunRef.current.delete(key);
}
}
for (const runId of logOffsetByRunRef.current.keys()) {
if (!liveRunIds.has(runId)) {
logOffsetByRunRef.current.delete(runId);
}
}
}, [activeRunIds]);
useEffect(() => {
if (runs.length === 0) return;
let cancelled = false;
const readRunLog = async (run: LiveRunForIssue) => {
const offset = logOffsetByRunRef.current.get(run.id) ?? 0;
try {
const result = await heartbeatsApi.log(run.id, offset, LOG_READ_LIMIT_BYTES);
if (cancelled) return;
const rows = parsePersistedLogContent(run.id, result.content, pendingLogRowsByRunRef.current);
const items: FeedItem[] = [];
for (const row of rows) {
if (row.stream === "stderr") {
items.push(
...parseStderrChunk(run, row.chunk, row.ts, pendingByRunRef.current, nextIdRef),
);
continue;
}
if (row.stream === "system") {
const item = createFeedItem(run, row.ts, row.chunk, "warn", nextIdRef.current++);
if (item) items.push(item);
continue;
}
items.push(
...parseStdoutChunk(run, row.chunk, row.ts, pendingByRunRef.current, nextIdRef),
);
}
appendItems(items);
if (result.nextOffset !== undefined) {
logOffsetByRunRef.current.set(run.id, result.nextOffset);
return;
}
if (result.content.length > 0) {
logOffsetByRunRef.current.set(run.id, offset + result.content.length);
}
} catch {
// Ignore log read errors while run output is initializing.
}
};
const readAll = async () => {
await Promise.all(runs.map((run) => readRunLog(run)));
};
void readAll();
const interval = window.setInterval(() => {
void readAll();
}, LOG_POLL_INTERVAL_MS);
return () => {
cancelled = true;
window.clearInterval(interval);
};
}, [runIdsKey, runs]);
useEffect(() => {
if (!companyId || activeRunIds.size === 0) return;
let closed = false;
let reconnectTimer: number | null = null;
let socket: WebSocket | null = null;
const scheduleReconnect = () => {
if (closed) return;
reconnectTimer = window.setTimeout(connect, 1500);
};
const connect = () => {
if (closed) return;
const protocol = window.location.protocol === "https:" ? "wss" : "ws";
const url = `${protocol}://${window.location.host}/api/companies/${encodeURIComponent(companyId)}/events/ws`;
socket = new WebSocket(url);
socket.onmessage = (message) => {
const raw = typeof message.data === "string" ? message.data : "";
if (!raw) return;
let event: LiveEvent;
try {
event = JSON.parse(raw) as LiveEvent;
} catch {
return;
}
if (event.companyId !== companyId) return;
const payload = event.payload ?? {};
const runId = readString(payload["runId"]);
if (!runId || !activeRunIds.has(runId)) return;
const run = runById.get(runId);
if (!run) return;
if (event.type === "heartbeat.run.event") {
const seq = typeof payload["seq"] === "number" ? payload["seq"] : null;
const eventType = readString(payload["eventType"]) ?? "event";
const messageText = readString(payload["message"]) ?? eventType;
const dedupeKey = `${runId}:event:${seq ?? `${eventType}:${messageText}:${event.createdAt}`}`;
if (seenKeysRef.current.has(dedupeKey)) return;
seenKeysRef.current.add(dedupeKey);
if (seenKeysRef.current.size > 2000) {
seenKeysRef.current.clear();
}
const tone = eventType === "error" ? "error" : eventType === "lifecycle" ? "warn" : "info";
const item = createFeedItem(run, event.createdAt, messageText, tone, nextIdRef.current++);
if (item) appendItems([item]);
return;
}
if (event.type === "heartbeat.run.status") {
const status = readString(payload["status"]) ?? "updated";
const dedupeKey = `${runId}:status:${status}:${readString(payload["finishedAt"]) ?? ""}`;
if (seenKeysRef.current.has(dedupeKey)) return;
seenKeysRef.current.add(dedupeKey);
if (seenKeysRef.current.size > 2000) {
seenKeysRef.current.clear();
}
const tone = status === "failed" || status === "timed_out" ? "error" : "warn";
const item = createFeedItem(run, event.createdAt, `run ${status}`, tone, nextIdRef.current++);
if (item) appendItems([item]);
return;
}
if (event.type === "heartbeat.run.log") {
const chunk = readString(payload["chunk"]);
if (!chunk) return;
const stream = readString(payload["stream"]) === "stderr" ? "stderr" : "stdout";
if (stream === "stderr") {
appendItems(parseStderrChunk(run, chunk, event.createdAt, pendingByRunRef.current, nextIdRef));
return;
}
appendItems(parseStdoutChunk(run, chunk, event.createdAt, pendingByRunRef.current, nextIdRef));
}
};
socket.onerror = () => {
socket?.close();
};
socket.onclose = () => {
scheduleReconnect();
};
};
connect();
return () => {
closed = true;
if (reconnectTimer !== null) window.clearTimeout(reconnectTimer);
if (socket) {
socket.onmessage = null;
socket.onerror = null;
socket.onclose = null;
socket.close(1000, "issue_live_widget_unmount");
}
};
}, [activeRunIds, companyId, runById]);
if (runs.length === 0 && feed.length === 0) return null;
const recent = feed.slice(-25);
if (runs.length === 0) return null;
return (
<div className="rounded-lg border border-cyan-500/30 bg-background/80 overflow-hidden shadow-[0_0_12px_rgba(6,182,212,0.08)]">
{runs.length > 0 ? (
runs.map((run) => (
<div key={run.id} className="px-3 py-2 border-b border-border/50">
<div className="flex items-center justify-between mb-2">
<Link to={`/agents/${run.agentId}`} className="hover:underline">
<Identity name={run.agentName} size="sm" />
</Link>
<span className="text-xs text-muted-foreground">
{formatDateTime(run.startedAt ?? run.createdAt)}
</span>
</div>
<div className="flex items-center gap-2 text-xs">
<span className="text-muted-foreground">Run</span>
<Link
to={`/agents/${run.agentId}/runs/${run.id}`}
className="inline-flex items-center rounded-md border border-border bg-accent/40 px-2 py-1 font-mono text-muted-foreground hover:text-foreground hover:bg-accent/60 transition-colors"
>
{run.id.slice(0, 8)}
</Link>
<StatusBadge status={run.status} />
<div className="ml-auto flex items-center gap-2">
<button
onClick={() => handleCancelRun(run.id)}
disabled={cancellingRunIds.has(run.id)}
className="inline-flex items-center gap-1 text-[10px] text-red-600 hover:text-red-500 dark:text-red-400 dark:hover:text-red-300 disabled:opacity-50"
>
<Square className="h-2 w-2" fill="currentColor" />
{cancellingRunIds.has(run.id) ? "Stopping…" : "Stop"}
</button>
<Link
to={`/agents/${run.agentId}/runs/${run.id}`}
className="inline-flex items-center gap-1 text-[10px] text-cyan-600 hover:text-cyan-500 dark:text-cyan-300 dark:hover:text-cyan-200"
>
Open run
<ExternalLink className="h-2.5 w-2.5" />
</Link>
</div>
</div>
</div>
))
) : (
<div className="flex items-center px-3 py-2 border-b border-border/50">
<span className="text-xs font-medium text-muted-foreground">Recent run updates</span>
<div className="overflow-hidden rounded-xl border border-cyan-500/25 bg-background/80 shadow-[0_18px_50px_rgba(6,182,212,0.08)]">
<div className="border-b border-border/60 bg-cyan-500/[0.04] px-4 py-3">
<div className="text-xs font-semibold uppercase tracking-[0.18em] text-cyan-700 dark:text-cyan-300">
Live Runs
</div>
<div className="mt-1 text-xs text-muted-foreground">
Streamed with the same transcript UI used on the full run detail page.
</div>
)}
<div ref={bodyRef} className="max-h-[220px] overflow-y-auto p-2 font-mono text-[11px] space-y-1">
{recent.length === 0 && (
<div className="text-xs text-muted-foreground">Waiting for run output...</div>
)}
{recent.map((item, index) => (
<div
key={item.id}
className={cn(
"grid grid-cols-[auto_1fr] gap-2 items-start",
index === recent.length - 1 && "animate-in fade-in slide-in-from-bottom-1 duration-300",
)}
>
<span className="text-[10px] text-muted-foreground">{relativeTime(item.ts)}</span>
<div className={cn(
"min-w-0",
item.tone === "error" && "text-red-600 dark:text-red-300",
item.tone === "warn" && "text-amber-600 dark:text-amber-300",
item.tone === "assistant" && "text-emerald-700 dark:text-emerald-200",
item.tone === "tool" && "text-cyan-600 dark:text-cyan-300",
item.tone === "info" && "text-foreground/80",
)}>
<Identity name={item.agentName} size="sm" className="text-cyan-600 dark:text-cyan-400" />
<span className="text-muted-foreground"> [{item.runId.slice(0, 8)}] </span>
<span className="break-words">{item.text}</span>
</div>
</div>
))}
</div>
<div className="divide-y divide-border/60">
{runs.map((run) => {
const isActive = isRunActive(run.status);
const transcript = transcriptByRun.get(run.id) ?? [];
return (
<section key={run.id} className="px-4 py-4">
<div className="mb-3 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
<div className="min-w-0">
<Link to={`/agents/${run.agentId}`} className="inline-flex hover:underline">
<Identity name={run.agentName} size="sm" />
</Link>
<div className="mt-2 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
<Link
to={`/agents/${run.agentId}/runs/${run.id}`}
className="inline-flex items-center rounded-full border border-border/70 bg-background/70 px-2 py-1 font-mono hover:border-cyan-500/30 hover:text-foreground"
>
{run.id.slice(0, 8)}
</Link>
<StatusBadge status={run.status} />
<span>{formatDateTime(run.startedAt ?? run.createdAt)}</span>
</div>
</div>
<div className="flex items-center gap-2">
{isActive && (
<button
onClick={() => handleCancelRun(run.id)}
disabled={cancellingRunIds.has(run.id)}
className="inline-flex items-center gap-1 rounded-full border border-red-500/20 bg-red-500/[0.06] px-2.5 py-1 text-[11px] font-medium text-red-700 transition-colors hover:bg-red-500/[0.12] dark:text-red-300 disabled:opacity-50"
>
<Square className="h-2.5 w-2.5" fill="currentColor" />
{cancellingRunIds.has(run.id) ? "Stopping…" : "Stop"}
</button>
)}
<Link
to={`/agents/${run.agentId}/runs/${run.id}`}
className="inline-flex items-center gap-1 rounded-full border border-border/70 bg-background/70 px-2.5 py-1 text-[11px] font-medium text-cyan-700 transition-colors hover:border-cyan-500/30 hover:text-cyan-600 dark:text-cyan-300"
>
Open run
<ExternalLink className="h-3 w-3" />
</Link>
</div>
</div>
<div className="max-h-[320px] overflow-y-auto pr-1">
<RunTranscriptView
entries={transcript}
density="compact"
limit={8}
streaming={isActive}
collapseStdout
emptyMessage={hasOutputForRun(run.id) ? "Waiting for transcript parsing..." : "Waiting for run output..."}
/>
</div>
</section>
);
})}
</div>
</div>
);
}
@@ -0,0 +1,1000 @@
import { useMemo, useState } from "react";
import type { TranscriptEntry } from "../../adapters";
import { MarkdownBody } from "../MarkdownBody";
import { cn, formatTokens } from "../../lib/utils";
import {
Check,
ChevronDown,
ChevronRight,
CircleAlert,
TerminalSquare,
User,
Wrench,
} from "lucide-react";
export type TranscriptMode = "nice" | "raw";
export type TranscriptDensity = "comfortable" | "compact";
interface RunTranscriptViewProps {
entries: TranscriptEntry[];
mode?: TranscriptMode;
density?: TranscriptDensity;
limit?: number;
streaming?: boolean;
collapseStdout?: boolean;
emptyMessage?: string;
className?: string;
}
type TranscriptBlock =
| {
type: "message";
role: "assistant" | "user";
ts: string;
text: string;
streaming: boolean;
}
| {
type: "thinking";
ts: string;
text: string;
streaming: boolean;
}
| {
type: "tool";
ts: string;
endTs?: string;
name: string;
toolUseId?: string;
input: unknown;
result?: string;
isError?: boolean;
status: "running" | "completed" | "error";
}
| {
type: "activity";
ts: string;
activityId?: string;
name: string;
status: "running" | "completed";
}
| {
type: "command_group";
ts: string;
endTs?: string;
items: Array<{
ts: string;
endTs?: string;
input: unknown;
result?: string;
isError?: boolean;
status: "running" | "completed" | "error";
}>;
}
| {
type: "stdout";
ts: string;
text: string;
}
| {
type: "event";
ts: string;
label: string;
tone: "info" | "warn" | "error" | "neutral";
text: string;
detail?: string;
};
function asRecord(value: unknown): Record<string, unknown> | null {
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
return value as Record<string, unknown>;
}
function compactWhitespace(value: string): string {
return value.replace(/\s+/g, " ").trim();
}
function truncate(value: string, max: number): string {
return value.length > max ? `${value.slice(0, Math.max(0, max - 1))}…` : value;
}
function stripMarkdown(value: string): string {
return compactWhitespace(
value
.replace(/```[\s\S]*?```/g, " code ")
.replace(/`([^`]+)`/g, "$1")
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
.replace(/[*_#>-]/g, " "),
);
}
function humanizeLabel(value: string): string {
return value
.replace(/[_-]+/g, " ")
.trim()
.replace(/\b\w/g, (char) => char.toUpperCase());
}
function stripWrappedShell(command: string): string {
const trimmed = compactWhitespace(command);
const shellWrapped = trimmed.match(/^(?:(?:\/bin\/)?(?:zsh|bash|sh)|cmd(?:\.exe)?(?:\s+\/d)?(?:\s+\/s)?(?:\s+\/c)?)\s+(?:-lc|\/c)\s+(.+)$/i);
const inner = shellWrapped?.[1] ?? trimmed;
const quoted = inner.match(/^(['"])([\s\S]*)\1$/);
return compactWhitespace(quoted?.[2] ?? inner);
}
function formatUnknown(value: unknown): string {
if (typeof value === "string") return value;
if (value === null || value === undefined) return "";
try {
return JSON.stringify(value, null, 2);
} catch {
return String(value);
}
}
function formatToolPayload(value: unknown): string {
if (typeof value === "string") {
try {
return JSON.stringify(JSON.parse(value), null, 2);
} catch {
return value;
}
}
return formatUnknown(value);
}
function extractToolUseId(input: unknown): string | undefined {
const record = asRecord(input);
if (!record) return undefined;
const candidates = [
record.toolUseId,
record.tool_use_id,
record.callId,
record.call_id,
record.id,
];
for (const candidate of candidates) {
if (typeof candidate === "string" && candidate.trim()) {
return candidate;
}
}
return undefined;
}
function summarizeRecord(record: Record<string, unknown>, keys: string[]): string | null {
for (const key of keys) {
const value = record[key];
if (typeof value === "string" && value.trim()) {
return truncate(compactWhitespace(value), 120);
}
}
return null;
}
function summarizeToolInput(name: string, input: unknown, density: TranscriptDensity): string {
const compactMax = density === "compact" ? 72 : 120;
if (typeof input === "string") {
const normalized = isCommandTool(name, input) ? stripWrappedShell(input) : compactWhitespace(input);
return truncate(normalized, compactMax);
}
const record = asRecord(input);
if (!record) {
const serialized = compactWhitespace(formatUnknown(input));
return serialized ? truncate(serialized, compactMax) : `Inspect ${name} input`;
}
const command = typeof record.command === "string"
? record.command
: typeof record.cmd === "string"
? record.cmd
: null;
if (command && isCommandTool(name, record)) {
return truncate(stripWrappedShell(command), compactMax);
}
const direct =
summarizeRecord(record, ["command", "cmd", "path", "filePath", "file_path", "query", "url", "prompt", "message"])
?? summarizeRecord(record, ["pattern", "name", "title", "target", "tool"])
?? null;
if (direct) return truncate(direct, compactMax);
if (Array.isArray(record.paths) && record.paths.length > 0) {
const first = record.paths.find((value): value is string => typeof value === "string" && value.trim().length > 0);
if (first) {
return truncate(`${record.paths.length} paths, starting with ${first}`, compactMax);
}
}
const keys = Object.keys(record);
if (keys.length === 0) return `No ${name} input`;
if (keys.length === 1) return truncate(`${keys[0]} payload`, compactMax);
return truncate(`${keys.length} fields: ${keys.slice(0, 3).join(", ")}`, compactMax);
}
function parseStructuredToolResult(result: string | undefined) {
if (!result) return null;
const lines = result.split(/\r?\n/);
const metadata = new Map<string, string>();
let bodyStartIndex = lines.findIndex((line) => line.trim() === "");
if (bodyStartIndex === -1) bodyStartIndex = lines.length;
for (let index = 0; index < bodyStartIndex; index += 1) {
const match = lines[index]?.match(/^([a-z_]+):\s*(.+)$/i);
if (match) {
metadata.set(match[1].toLowerCase(), compactWhitespace(match[2]));
}
}
const body = lines.slice(Math.min(bodyStartIndex + 1, lines.length))
.map((line) => compactWhitespace(line))
.filter(Boolean)
.join("\n");
return {
command: metadata.get("command") ?? null,
status: metadata.get("status") ?? null,
exitCode: metadata.get("exit_code") ?? null,
body,
};
}
function isCommandTool(name: string, input: unknown): boolean {
if (name === "command_execution" || name === "shell" || name === "shellToolCall" || name === "bash") {
return true;
}
if (typeof input === "string") {
return /\b(?:bash|zsh|sh|cmd|powershell)\b/i.test(input);
}
const record = asRecord(input);
return Boolean(record && (typeof record.command === "string" || typeof record.cmd === "string"));
}
function displayToolName(name: string, input: unknown): string {
if (isCommandTool(name, input)) return "Executing command";
return humanizeLabel(name);
}
function summarizeToolResult(result: string | undefined, isError: boolean | undefined, density: TranscriptDensity): string {
if (!result) return isError ? "Tool failed" : "Waiting for result";
const structured = parseStructuredToolResult(result);
if (structured) {
if (structured.body) {
return truncate(structured.body.split("\n")[0] ?? structured.body, density === "compact" ? 84 : 140);
}
if (structured.status === "completed") return "Completed";
if (structured.status === "failed" || structured.status === "error") {
return structured.exitCode ? `Failed with exit code ${structured.exitCode}` : "Failed";
}
}
const lines = result
.split(/\r?\n/)
.map((line) => compactWhitespace(line))
.filter(Boolean);
const firstLine = lines[0] ?? result;
return truncate(firstLine, density === "compact" ? 84 : 140);
}
function parseSystemActivity(text: string): { activityId?: string; name: string; status: "running" | "completed" } | null {
const match = text.match(/^item (started|completed):\s*([a-z0-9_-]+)(?:\s+\(id=([^)]+)\))?$/i);
if (!match) return null;
return {
status: match[1].toLowerCase() === "started" ? "running" : "completed",
name: humanizeLabel(match[2] ?? "Activity"),
activityId: match[3] || undefined,
};
}
function groupCommandBlocks(blocks: TranscriptBlock[]): TranscriptBlock[] {
const grouped: TranscriptBlock[] = [];
let pending: Array<Extract<TranscriptBlock, { type: "command_group" }>["items"][number]> = [];
let groupTs: string | null = null;
let groupEndTs: string | undefined;
const flush = () => {
if (pending.length === 0 || !groupTs) return;
grouped.push({
type: "command_group",
ts: groupTs,
endTs: groupEndTs,
items: pending,
});
pending = [];
groupTs = null;
groupEndTs = undefined;
};
for (const block of blocks) {
if (block.type === "tool" && isCommandTool(block.name, block.input)) {
if (!groupTs) {
groupTs = block.ts;
}
groupEndTs = block.endTs ?? block.ts;
pending.push({
ts: block.ts,
endTs: block.endTs,
input: block.input,
result: block.result,
isError: block.isError,
status: block.status,
});
continue;
}
flush();
grouped.push(block);
}
flush();
return grouped;
}
function normalizeTranscript(entries: TranscriptEntry[], streaming: boolean): TranscriptBlock[] {
const blocks: TranscriptBlock[] = [];
const pendingToolBlocks = new Map<string, Extract<TranscriptBlock, { type: "tool" }>>();
const pendingActivityBlocks = new Map<string, Extract<TranscriptBlock, { type: "activity" }>>();
for (const entry of entries) {
const previous = blocks[blocks.length - 1];
if (entry.kind === "assistant" || entry.kind === "user") {
const isStreaming = streaming && entry.kind === "assistant" && entry.delta === true;
if (previous?.type === "message" && previous.role === entry.kind) {
previous.text += previous.text.endsWith("\n") || entry.text.startsWith("\n") ? entry.text : `\n${entry.text}`;
previous.ts = entry.ts;
previous.streaming = previous.streaming || isStreaming;
} else {
blocks.push({
type: "message",
role: entry.kind,
ts: entry.ts,
text: entry.text,
streaming: isStreaming,
});
}
continue;
}
if (entry.kind === "thinking") {
const isStreaming = streaming && entry.delta === true;
if (previous?.type === "thinking") {
previous.text += previous.text.endsWith("\n") || entry.text.startsWith("\n") ? entry.text : `\n${entry.text}`;
previous.ts = entry.ts;
previous.streaming = previous.streaming || isStreaming;
} else {
blocks.push({
type: "thinking",
ts: entry.ts,
text: entry.text,
streaming: isStreaming,
});
}
continue;
}
if (entry.kind === "tool_call") {
const toolBlock: Extract<TranscriptBlock, { type: "tool" }> = {
type: "tool",
ts: entry.ts,
name: displayToolName(entry.name, entry.input),
toolUseId: entry.toolUseId ?? extractToolUseId(entry.input),
input: entry.input,
status: "running",
};
blocks.push(toolBlock);
if (toolBlock.toolUseId) {
pendingToolBlocks.set(toolBlock.toolUseId, toolBlock);
}
continue;
}
if (entry.kind === "tool_result") {
const matched =
pendingToolBlocks.get(entry.toolUseId)
?? [...blocks].reverse().find((block): block is Extract<TranscriptBlock, { type: "tool" }> => block.type === "tool" && block.status === "running");
if (matched) {
matched.result = entry.content;
matched.isError = entry.isError;
matched.status = entry.isError ? "error" : "completed";
matched.endTs = entry.ts;
pendingToolBlocks.delete(entry.toolUseId);
} else {
blocks.push({
type: "tool",
ts: entry.ts,
endTs: entry.ts,
name: "tool",
toolUseId: entry.toolUseId,
input: null,
result: entry.content,
isError: entry.isError,
status: entry.isError ? "error" : "completed",
});
}
continue;
}
if (entry.kind === "init") {
blocks.push({
type: "event",
ts: entry.ts,
label: "init",
tone: "info",
text: `model ${entry.model}${entry.sessionId ? ` • session ${entry.sessionId}` : ""}`,
});
continue;
}
if (entry.kind === "result") {
blocks.push({
type: "event",
ts: entry.ts,
label: "result",
tone: entry.isError ? "error" : "info",
text: entry.text.trim() || entry.errors[0] || (entry.isError ? "Run failed" : "Completed"),
});
continue;
}
if (entry.kind === "stderr") {
blocks.push({
type: "event",
ts: entry.ts,
label: "stderr",
tone: "error",
text: entry.text,
});
continue;
}
if (entry.kind === "system") {
if (compactWhitespace(entry.text).toLowerCase() === "turn started") {
continue;
}
const activity = parseSystemActivity(entry.text);
if (activity) {
const existing = activity.activityId ? pendingActivityBlocks.get(activity.activityId) : undefined;
if (existing) {
existing.status = activity.status;
existing.ts = entry.ts;
if (activity.status === "completed" && activity.activityId) {
pendingActivityBlocks.delete(activity.activityId);
}
} else {
const block: Extract<TranscriptBlock, { type: "activity" }> = {
type: "activity",
ts: entry.ts,
activityId: activity.activityId,
name: activity.name,
status: activity.status,
};
blocks.push(block);
if (activity.status === "running" && activity.activityId) {
pendingActivityBlocks.set(activity.activityId, block);
}
}
continue;
}
blocks.push({
type: "event",
ts: entry.ts,
label: "system",
tone: "warn",
text: entry.text,
});
continue;
}
if (previous?.type === "stdout") {
previous.text += previous.text.endsWith("\n") || entry.text.startsWith("\n") ? entry.text : `\n${entry.text}`;
previous.ts = entry.ts;
} else {
blocks.push({
type: "stdout",
ts: entry.ts,
text: entry.text,
});
}
}
return groupCommandBlocks(blocks);
}
function TranscriptMessageBlock({
block,
density,
}: {
block: Extract<TranscriptBlock, { type: "message" }>;
density: TranscriptDensity;
}) {
const isAssistant = block.role === "assistant";
const compact = density === "compact";
return (
<div>
{!isAssistant && (
<div className="mb-1.5 flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
<User className={compact ? "h-3.5 w-3.5" : "h-4 w-4"} />
<span>User</span>
</div>
)}
{compact ? (
<div className="text-xs leading-5 text-foreground/85 whitespace-pre-wrap break-words">
{truncate(stripMarkdown(block.text), 360)}
</div>
) : (
<MarkdownBody className="text-sm [&>*:first-child]:mt-0 [&>*:last-child]:mb-0">
{block.text}
</MarkdownBody>
)}
{block.streaming && (
<div className="mt-2 inline-flex items-center gap-1 text-[10px] font-medium italic text-muted-foreground">
<span className="relative flex h-1.5 w-1.5">
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-current opacity-70" />
<span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-current" />
</span>
Streaming
</div>
)}
</div>
);
}
function TranscriptThinkingBlock({
block,
density,
}: {
block: Extract<TranscriptBlock, { type: "thinking" }>;
density: TranscriptDensity;
}) {
return (
<div
className={cn(
"whitespace-pre-wrap break-words italic text-foreground/70",
density === "compact" ? "text-[11px] leading-5" : "text-sm leading-6",
)}
>
{block.text}
</div>
);
}
function TranscriptToolCard({
block,
density,
}: {
block: Extract<TranscriptBlock, { type: "tool" }>;
density: TranscriptDensity;
}) {
const [open, setOpen] = useState(block.status === "error");
const compact = density === "compact";
const parsedResult = parseStructuredToolResult(block.result);
const statusLabel =
block.status === "running"
? "Running"
: block.status === "error"
? "Errored"
: "Completed";
const statusTone =
block.status === "running"
? "text-cyan-700 dark:text-cyan-300"
: block.status === "error"
? "text-red-700 dark:text-red-300"
: "text-emerald-700 dark:text-emerald-300";
const detailsClass = cn(
"space-y-3",
block.status === "error" && "rounded-xl border border-red-500/20 bg-red-500/[0.06] p-3",
);
const iconClass = cn(
"mt-0.5 h-3.5 w-3.5 shrink-0",
block.status === "error"
? "text-red-600 dark:text-red-300"
: block.status === "completed"
? "text-emerald-600 dark:text-emerald-300"
: "text-cyan-600 dark:text-cyan-300",
);
const summary = block.status === "running"
? summarizeToolInput(block.name, block.input, density)
: block.status === "completed" && parsedResult?.body
? truncate(parsedResult.body.split("\n")[0] ?? parsedResult.body, compact ? 84 : 140)
: summarizeToolResult(block.result, block.isError, density);
return (
<div className={cn(block.status === "error" && "rounded-xl border border-red-500/20 bg-red-500/[0.04] p-3")}>
<div className="flex items-start gap-2">
{block.status === "error" ? (
<CircleAlert className={iconClass} />
) : block.status === "completed" ? (
<Check className={iconClass} />
) : (
<Wrench className={iconClass} />
)}
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
<span className="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
{block.name}
</span>
<span className={cn("text-[10px] font-semibold uppercase tracking-[0.14em]", statusTone)}>
{statusLabel}
</span>
</div>
<div className={cn("mt-1 break-words text-foreground/80", compact ? "text-xs" : "text-sm")}>
{summary}
</div>
</div>
<button
type="button"
className="mt-0.5 inline-flex h-5 w-5 items-center justify-center text-muted-foreground transition-colors hover:text-foreground"
onClick={() => setOpen((value) => !value)}
aria-label={open ? "Collapse tool details" : "Expand tool details"}
>
{open ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
</button>
</div>
{open && (
<div className="mt-3">
<div className={detailsClass}>
<div className={cn("grid gap-3", compact ? "grid-cols-1" : "lg:grid-cols-2")}>
<div>
<div className="mb-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
Input
</div>
<pre className="overflow-x-auto whitespace-pre-wrap break-words font-mono text-[11px] text-foreground/80">
{formatToolPayload(block.input) || "<empty>"}
</pre>
</div>
<div>
<div className="mb-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
Result
</div>
<pre className={cn(
"overflow-x-auto whitespace-pre-wrap break-words font-mono text-[11px]",
block.status === "error" ? "text-red-700 dark:text-red-300" : "text-foreground/80",
)}>
{block.result ? formatToolPayload(block.result) : "Waiting for result..."}
</pre>
</div>
</div>
</div>
</div>
)}
</div>
);
}
function hasSelectedText() {
if (typeof window === "undefined") return false;
return (window.getSelection()?.toString().length ?? 0) > 0;
}
function TranscriptCommandGroup({
block,
density,
}: {
block: Extract<TranscriptBlock, { type: "command_group" }>;
density: TranscriptDensity;
}) {
const [open, setOpen] = useState(false);
const compact = density === "compact";
const runningItem = [...block.items].reverse().find((item) => item.status === "running");
const latestItem = block.items[block.items.length - 1] ?? null;
const hasError = block.items.some((item) => item.status === "error");
const isRunning = Boolean(runningItem);
const showExpandedErrorState = open && hasError;
const title = isRunning
? "Executing command"
: block.items.length === 1
? "Executed command"
: `Executed ${block.items.length} commands`;
const subtitle = runningItem
? summarizeToolInput("command_execution", runningItem.input, density)
: null;
const statusTone = isRunning
? "text-cyan-700 dark:text-cyan-300"
: "text-foreground/70";
return (
<div className={cn(showExpandedErrorState && "rounded-xl border border-red-500/20 bg-red-500/[0.04] p-3")}>
<div
role="button"
tabIndex={0}
className={cn("flex cursor-pointer gap-2", subtitle ? "items-start" : "items-center")}
onClick={() => {
if (hasSelectedText()) return;
setOpen((value) => !value);
}}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
setOpen((value) => !value);
}
}}
>
<div className={cn("flex shrink-0 items-center", subtitle && "mt-0.5")}>
{block.items.slice(0, Math.min(block.items.length, 3)).map((_, index) => (
<span
key={index}
className={cn(
"inline-flex h-6 w-6 items-center justify-center rounded-full border shadow-sm",
index > 0 && "-ml-1.5",
isRunning
? "border-cyan-500/25 bg-cyan-500/[0.08] text-cyan-600 dark:text-cyan-300"
: "border-border/70 bg-background text-foreground/55",
isRunning && "animate-pulse",
)}
>
<TerminalSquare className="h-3.5 w-3.5" />
</span>
))}
</div>
<div className="min-w-0 flex-1">
<div className="text-[11px] font-semibold uppercase leading-none tracking-[0.1em] text-muted-foreground/70">
{title}
</div>
{subtitle && (
<div className={cn("mt-1 break-words font-mono text-foreground/85", compact ? "text-xs" : "text-sm")}>
{subtitle}
</div>
)}
{!subtitle && latestItem?.status === "error" && open && (
<div className={cn("mt-1", compact ? "text-xs" : "text-sm", statusTone)}>
Command failed
</div>
)}
</div>
<button
type="button"
className={cn(
"inline-flex h-5 w-5 items-center justify-center text-muted-foreground transition-colors hover:text-foreground",
subtitle && "mt-0.5",
)}
onClick={(event) => {
event.stopPropagation();
setOpen((value) => !value);
}}
aria-label={open ? "Collapse command details" : "Expand command details"}
>
{open ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
</button>
</div>
{open && (
<div className={cn("mt-3 space-y-3", hasError && "rounded-xl border border-red-500/20 bg-red-500/[0.06] p-3")}>
{block.items.map((item, index) => (
<div key={`${item.ts}-${index}`} className="space-y-2">
<div className="flex items-center gap-2">
<span className={cn(
"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full border",
item.status === "error"
? "border-red-500/25 bg-red-500/[0.08] text-red-600 dark:text-red-300"
: item.status === "running"
? "border-cyan-500/25 bg-cyan-500/[0.08] text-cyan-600 dark:text-cyan-300"
: "border-border/70 bg-background text-foreground/55",
)}>
<TerminalSquare className="h-3 w-3" />
</span>
<span className={cn("font-mono break-all", compact ? "text-[11px]" : "text-xs")}>
{summarizeToolInput("command_execution", item.input, density)}
</span>
</div>
{item.result && (
<pre className={cn(
"overflow-x-auto whitespace-pre-wrap break-words font-mono text-[11px]",
item.status === "error" ? "text-red-700 dark:text-red-300" : "text-foreground/80",
)}>
{formatToolPayload(item.result)}
</pre>
)}
</div>
))}
</div>
)}
</div>
);
}
function TranscriptActivityRow({
block,
density,
}: {
block: Extract<TranscriptBlock, { type: "activity" }>;
density: TranscriptDensity;
}) {
return (
<div className="flex items-start gap-2">
{block.status === "completed" ? (
<Check className="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-300" />
) : (
<span className="relative mt-1 flex h-2.5 w-2.5 shrink-0">
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-cyan-400 opacity-70" />
<span className="relative inline-flex h-2.5 w-2.5 rounded-full bg-cyan-500" />
</span>
)}
<div className={cn(
"break-words text-foreground/80",
density === "compact" ? "text-xs leading-5" : "text-sm leading-6",
)}>
{block.name}
</div>
</div>
);
}
function TranscriptEventRow({
block,
density,
}: {
block: Extract<TranscriptBlock, { type: "event" }>;
density: TranscriptDensity;
}) {
const compact = density === "compact";
const toneClasses =
block.tone === "error"
? "rounded-xl border border-red-500/20 bg-red-500/[0.06] p-3 text-red-700 dark:text-red-300"
: block.tone === "warn"
? "text-amber-700 dark:text-amber-300"
: block.tone === "info"
? "text-sky-700 dark:text-sky-300"
: "text-foreground/75";
return (
<div className={toneClasses}>
<div className="flex items-start gap-2">
{block.tone === "error" ? (
<CircleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" />
) : block.tone === "warn" ? (
<TerminalSquare className="mt-0.5 h-3.5 w-3.5 shrink-0" />
) : (
<span className="mt-[7px] h-1.5 w-1.5 shrink-0 rounded-full bg-current/50" />
)}
<div className="min-w-0 flex-1">
{block.label === "result" && block.tone !== "error" ? (
<div className={cn("whitespace-pre-wrap break-words text-sky-700 dark:text-sky-300", compact ? "text-[11px]" : "text-xs")}>
{block.text}
</div>
) : (
<div className={cn("whitespace-pre-wrap break-words", compact ? "text-[11px]" : "text-xs")}>
<span className="text-[10px] font-semibold uppercase tracking-[0.1em] text-muted-foreground/70">
{block.label}
</span>
{block.text ? <span className="ml-2">{block.text}</span> : null}
</div>
)}
{block.detail && (
<pre className="mt-2 overflow-x-auto whitespace-pre-wrap break-words font-mono text-[11px] text-foreground/75">
{block.detail}
</pre>
)}
</div>
</div>
</div>
);
}
function TranscriptStdoutRow({
block,
density,
collapseByDefault,
}: {
block: Extract<TranscriptBlock, { type: "stdout" }>;
density: TranscriptDensity;
collapseByDefault: boolean;
}) {
const [open, setOpen] = useState(!collapseByDefault);
return (
<div>
<div className="flex items-center gap-2">
<span className="text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
stdout
</span>
<button
type="button"
className="inline-flex h-5 w-5 items-center justify-center text-muted-foreground transition-colors hover:text-foreground"
onClick={() => setOpen((value) => !value)}
aria-label={open ? "Collapse stdout" : "Expand stdout"}
>
{open ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
</button>
</div>
{open && (
<pre className={cn(
"mt-2 overflow-x-auto whitespace-pre-wrap break-words font-mono text-foreground/80",
density === "compact" ? "text-[11px]" : "text-xs",
)}>
{block.text}
</pre>
)}
</div>
);
}
function RawTranscriptView({
entries,
density,
}: {
entries: TranscriptEntry[];
density: TranscriptDensity;
}) {
const compact = density === "compact";
return (
<div className={cn("font-mono", compact ? "space-y-1 text-[11px]" : "space-y-1.5 text-xs")}>
{entries.map((entry, idx) => (
<div
key={`${entry.kind}-${entry.ts}-${idx}`}
className={cn(
"grid gap-x-3",
"grid-cols-[auto_1fr]",
)}
>
<span className="text-[10px] uppercase tracking-[0.18em] text-muted-foreground">
{entry.kind}
</span>
<pre className="min-w-0 whitespace-pre-wrap break-words text-foreground/80">
{entry.kind === "tool_call"
? `${entry.name}\n${formatToolPayload(entry.input)}`
: entry.kind === "tool_result"
? formatToolPayload(entry.content)
: entry.kind === "result"
? `${entry.text}\n${formatTokens(entry.inputTokens)} / ${formatTokens(entry.outputTokens)} / $${entry.costUsd.toFixed(6)}`
: entry.kind === "init"
? `model=${entry.model}${entry.sessionId ? ` session=${entry.sessionId}` : ""}`
: entry.text}
</pre>
</div>
))}
</div>
);
}
export function RunTranscriptView({
entries,
mode = "nice",
density = "comfortable",
limit,
streaming = false,
collapseStdout = false,
emptyMessage = "No transcript yet.",
className,
}: RunTranscriptViewProps) {
const blocks = useMemo(() => normalizeTranscript(entries, streaming), [entries, streaming]);
const visibleBlocks = limit ? blocks.slice(-limit) : blocks;
const visibleEntries = limit ? entries.slice(-limit) : entries;
if (entries.length === 0) {
return (
<div className={cn("rounded-2xl border border-dashed border-border/70 bg-background/40 p-4 text-sm text-muted-foreground", className)}>
{emptyMessage}
</div>
);
}
if (mode === "raw") {
return (
<div className={className}>
<RawTranscriptView entries={visibleEntries} density={density} />
</div>
);
}
return (
<div className={cn("space-y-3", className)}>
{visibleBlocks.map((block, index) => (
<div
key={`${block.type}-${block.ts}-${index}`}
className={cn(index === visibleBlocks.length - 1 && streaming && "animate-in fade-in slide-in-from-bottom-1 duration-300")}
>
{block.type === "message" && <TranscriptMessageBlock block={block} density={density} />}
{block.type === "thinking" && <TranscriptThinkingBlock block={block} density={density} />}
{block.type === "tool" && <TranscriptToolCard block={block} density={density} />}
{block.type === "command_group" && <TranscriptCommandGroup block={block} density={density} />}
{block.type === "stdout" && (
<TranscriptStdoutRow block={block} density={density} collapseByDefault={collapseStdout} />
)}
{block.type === "activity" && <TranscriptActivityRow block={block} density={density} />}
{block.type === "event" && <TranscriptEventRow block={block} density={density} />}
</div>
))}
</div>
);
}
@@ -0,0 +1,283 @@
import { useEffect, useMemo, useRef, useState } from "react";
import type { LiveEvent } from "@paperclipai/shared";
import { heartbeatsApi, type LiveRunForIssue } from "../../api/heartbeats";
import { buildTranscript, getUIAdapter, type RunLogChunk, type TranscriptEntry } from "../../adapters";
const LOG_POLL_INTERVAL_MS = 2000;
const LOG_READ_LIMIT_BYTES = 256_000;
interface UseLiveRunTranscriptsOptions {
runs: LiveRunForIssue[];
companyId?: string | null;
maxChunksPerRun?: number;
}
function readString(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value : null;
}
function isTerminalStatus(status: string): boolean {
return status === "failed" || status === "timed_out" || status === "cancelled" || status === "succeeded";
}
function parsePersistedLogContent(
runId: string,
content: string,
pendingByRun: Map<string, string>,
): Array<RunLogChunk & { dedupeKey: string }> {
if (!content) return [];
const pendingKey = `${runId}:records`;
const combined = `${pendingByRun.get(pendingKey) ?? ""}${content}`;
const split = combined.split("\n");
pendingByRun.set(pendingKey, split.pop() ?? "");
const parsed: Array<RunLogChunk & { dedupeKey: string }> = [];
for (const line of split) {
const trimmed = line.trim();
if (!trimmed) continue;
try {
const raw = JSON.parse(trimmed) as { ts?: unknown; stream?: unknown; chunk?: unknown };
const stream = raw.stream === "stderr" || raw.stream === "system" ? raw.stream : "stdout";
const chunk = typeof raw.chunk === "string" ? raw.chunk : "";
const ts = typeof raw.ts === "string" ? raw.ts : new Date().toISOString();
if (!chunk) continue;
parsed.push({
ts,
stream,
chunk,
dedupeKey: `log:${runId}:${ts}:${stream}:${chunk}`,
});
} catch {
// Ignore malformed log rows.
}
}
return parsed;
}
export function useLiveRunTranscripts({
runs,
companyId,
maxChunksPerRun = 200,
}: UseLiveRunTranscriptsOptions) {
const [chunksByRun, setChunksByRun] = useState<Map<string, RunLogChunk[]>>(new Map());
const seenChunkKeysRef = useRef(new Set<string>());
const pendingLogRowsByRunRef = useRef(new Map<string, string>());
const logOffsetByRunRef = useRef(new Map<string, number>());
const runById = useMemo(() => new Map(runs.map((run) => [run.id, run])), [runs]);
const activeRunIds = useMemo(
() => new Set(runs.filter((run) => !isTerminalStatus(run.status)).map((run) => run.id)),
[runs],
);
const runIdsKey = useMemo(
() => runs.map((run) => run.id).sort((a, b) => a.localeCompare(b)).join(","),
[runs],
);
const appendChunks = (runId: string, chunks: Array<RunLogChunk & { dedupeKey: string }>) => {
if (chunks.length === 0) return;
setChunksByRun((prev) => {
const next = new Map(prev);
const existing = [...(next.get(runId) ?? [])];
let changed = false;
for (const chunk of chunks) {
if (seenChunkKeysRef.current.has(chunk.dedupeKey)) continue;
seenChunkKeysRef.current.add(chunk.dedupeKey);
existing.push({ ts: chunk.ts, stream: chunk.stream, chunk: chunk.chunk });
changed = true;
}
if (!changed) return prev;
if (seenChunkKeysRef.current.size > 12000) {
seenChunkKeysRef.current.clear();
}
next.set(runId, existing.slice(-maxChunksPerRun));
return next;
});
};
useEffect(() => {
const knownRunIds = new Set(runs.map((run) => run.id));
setChunksByRun((prev) => {
const next = new Map<string, RunLogChunk[]>();
for (const [runId, chunks] of prev) {
if (knownRunIds.has(runId)) {
next.set(runId, chunks);
}
}
return next.size === prev.size ? prev : next;
});
for (const key of pendingLogRowsByRunRef.current.keys()) {
const runId = key.replace(/:records$/, "");
if (!knownRunIds.has(runId)) {
pendingLogRowsByRunRef.current.delete(key);
}
}
for (const runId of logOffsetByRunRef.current.keys()) {
if (!knownRunIds.has(runId)) {
logOffsetByRunRef.current.delete(runId);
}
}
}, [runs]);
useEffect(() => {
if (runs.length === 0) return;
let cancelled = false;
const readRunLog = async (run: LiveRunForIssue) => {
const offset = logOffsetByRunRef.current.get(run.id) ?? 0;
try {
const result = await heartbeatsApi.log(run.id, offset, LOG_READ_LIMIT_BYTES);
if (cancelled) return;
appendChunks(run.id, parsePersistedLogContent(run.id, result.content, pendingLogRowsByRunRef.current));
if (result.nextOffset !== undefined) {
logOffsetByRunRef.current.set(run.id, result.nextOffset);
return;
}
if (result.content.length > 0) {
logOffsetByRunRef.current.set(run.id, offset + result.content.length);
}
} catch {
// Ignore log read errors while output is initializing.
}
};
const readAll = async () => {
await Promise.all(runs.map((run) => readRunLog(run)));
};
void readAll();
const interval = window.setInterval(() => {
void readAll();
}, LOG_POLL_INTERVAL_MS);
return () => {
cancelled = true;
window.clearInterval(interval);
};
}, [runIdsKey, runs]);
useEffect(() => {
if (!companyId || activeRunIds.size === 0) return;
let closed = false;
let reconnectTimer: number | null = null;
let socket: WebSocket | null = null;
const scheduleReconnect = () => {
if (closed) return;
reconnectTimer = window.setTimeout(connect, 1500);
};
const connect = () => {
if (closed) return;
const protocol = window.location.protocol === "https:" ? "wss" : "ws";
const url = `${protocol}://${window.location.host}/api/companies/${encodeURIComponent(companyId)}/events/ws`;
socket = new WebSocket(url);
socket.onmessage = (message) => {
const raw = typeof message.data === "string" ? message.data : "";
if (!raw) return;
let event: LiveEvent;
try {
event = JSON.parse(raw) as LiveEvent;
} catch {
return;
}
if (event.companyId !== companyId) return;
const payload = event.payload ?? {};
const runId = readString(payload["runId"]);
if (!runId || !activeRunIds.has(runId)) return;
if (!runById.has(runId)) return;
if (event.type === "heartbeat.run.log") {
const chunk = readString(payload["chunk"]);
if (!chunk) return;
const ts = readString(payload["ts"]) ?? event.createdAt;
const stream =
readString(payload["stream"]) === "stderr"
? "stderr"
: readString(payload["stream"]) === "system"
? "system"
: "stdout";
appendChunks(runId, [{
ts,
stream,
chunk,
dedupeKey: `log:${runId}:${ts}:${stream}:${chunk}`,
}]);
return;
}
if (event.type === "heartbeat.run.event") {
const seq = typeof payload["seq"] === "number" ? payload["seq"] : null;
const eventType = readString(payload["eventType"]) ?? "event";
const messageText = readString(payload["message"]) ?? eventType;
appendChunks(runId, [{
ts: event.createdAt,
stream: eventType === "error" ? "stderr" : "system",
chunk: messageText,
dedupeKey: `socket:event:${runId}:${seq ?? `${eventType}:${messageText}:${event.createdAt}`}`,
}]);
return;
}
if (event.type === "heartbeat.run.status") {
const status = readString(payload["status"]) ?? "updated";
appendChunks(runId, [{
ts: event.createdAt,
stream: isTerminalStatus(status) && status !== "succeeded" ? "stderr" : "system",
chunk: `run ${status}`,
dedupeKey: `socket:status:${runId}:${status}:${readString(payload["finishedAt"]) ?? ""}`,
}]);
}
};
socket.onerror = () => {
socket?.close();
};
socket.onclose = () => {
scheduleReconnect();
};
};
connect();
return () => {
closed = true;
if (reconnectTimer !== null) window.clearTimeout(reconnectTimer);
if (socket) {
socket.onmessage = null;
socket.onerror = null;
socket.onclose = null;
socket.close(1000, "live_run_transcripts_unmount");
}
};
}, [activeRunIds, companyId, runById]);
const transcriptByRun = useMemo(() => {
const next = new Map<string, TranscriptEntry[]>();
for (const run of runs) {
const adapter = getUIAdapter(run.adapterType);
next.set(run.id, buildTranscript(chunksByRun.get(run.id) ?? [], adapter.parseStdoutLine));
}
return next;
}, [chunksByRun, runs]);
return {
transcriptByRun,
hasOutputForRun(runId: string) {
return (chunksByRun.get(runId)?.length ?? 0) > 0;
},
};
}