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

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

View File

@@ -2,7 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { describe, expect, it } from "vitest";
import { afterEach, describe, expect, it } from "vitest";
import {
copyGitHooksToWorktreeGitDir,
copySeededSecretsKey,
@@ -22,6 +22,20 @@ import {
} from "../commands/worktree-lib.js";
import type { PaperclipConfig } from "../config/schema.js";
const ORIGINAL_CWD = process.cwd();
const ORIGINAL_ENV = { ...process.env };
afterEach(() => {
process.chdir(ORIGINAL_CWD);
for (const key of Object.keys(process.env)) {
if (!(key in ORIGINAL_ENV)) delete process.env[key];
}
for (const [key, value] of Object.entries(ORIGINAL_ENV)) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
function buildSourceConfig(): PaperclipConfig {
return {
$meta: {

View File

@@ -119,6 +119,14 @@ function nonEmpty(value: string | null | undefined): string | null {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
function isCurrentSourceConfigPath(sourceConfigPath: string): boolean {
const currentConfigPath = process.env.PAPERCLIP_CONFIG;
if (!currentConfigPath || currentConfigPath.trim().length === 0) {
return false;
}
return path.resolve(currentConfigPath) === path.resolve(sourceConfigPath);
}
function resolveWorktreeMakeName(name: string): string {
const value = nonEmpty(name);
if (!value) {
@@ -440,9 +448,10 @@ export function copySeededSecretsKey(input: {
mkdirSync(path.dirname(input.targetKeyFilePath), { recursive: true });
const allowProcessEnvFallback = isCurrentSourceConfigPath(input.sourceConfigPath);
const sourceInlineMasterKey =
nonEmpty(input.sourceEnvEntries.PAPERCLIP_SECRETS_MASTER_KEY) ??
nonEmpty(process.env.PAPERCLIP_SECRETS_MASTER_KEY);
(allowProcessEnvFallback ? nonEmpty(process.env.PAPERCLIP_SECRETS_MASTER_KEY) : null);
if (sourceInlineMasterKey) {
writeFileSync(input.targetKeyFilePath, sourceInlineMasterKey, {
encoding: "utf8",
@@ -458,7 +467,7 @@ export function copySeededSecretsKey(input: {
const sourceKeyFileOverride =
nonEmpty(input.sourceEnvEntries.PAPERCLIP_SECRETS_MASTER_KEY_FILE) ??
nonEmpty(process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE);
(allowProcessEnvFallback ? nonEmpty(process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE) : null);
const sourceConfiguredKeyPath = sourceKeyFileOverride ?? input.sourceConfig.secrets.localEncrypted.keyFilePath;
const sourceKeyFilePath = resolveRuntimeLikePath(sourceConfiguredKeyPath, input.sourceConfigPath);

View File

@@ -189,7 +189,7 @@ export type TranscriptEntry =
| { kind: "assistant"; ts: string; text: string; delta?: boolean }
| { kind: "thinking"; ts: string; text: string; delta?: boolean }
| { kind: "user"; ts: string; text: string }
| { kind: "tool_call"; ts: string; name: string; input: unknown }
| { kind: "tool_call"; ts: string; name: string; input: unknown; toolUseId?: string }
| { kind: "tool_result"; ts: string; toolUseId: string; content: string; isError: boolean }
| { kind: "init"; ts: string; model: string; sessionId: string }
| { kind: "result"; ts: string; text: string; inputTokens: number; outputTokens: number; cachedTokens: number; costUsd: number; subtype: string; isError: boolean; errors: string[] }

View File

@@ -71,6 +71,12 @@ export function parseClaudeStdoutLine(line: string, ts: string): TranscriptEntry
kind: "tool_call",
ts,
name: typeof block.name === "string" ? block.name : "unknown",
toolUseId:
typeof block.id === "string"
? block.id
: typeof block.tool_use_id === "string"
? block.tool_use_id
: undefined,
input: block.input ?? {},
});
}

View File

@@ -64,6 +64,7 @@ function parseCommandExecutionItem(
kind: "tool_call",
ts,
name: "command_execution",
toolUseId: id || command || "command_execution",
input: {
id,
command,
@@ -148,6 +149,7 @@ function parseCodexItem(
kind: "tool_call",
ts,
name: asString(item.name, "unknown"),
toolUseId: asString(item.id),
input: item.input ?? {},
}];
}

View File

@@ -142,6 +142,12 @@ function parseAssistantMessage(messageRaw: unknown, ts: string): TranscriptEntry
kind: "tool_call",
ts,
name,
toolUseId:
asString(part.tool_use_id) ||
asString(part.toolUseId) ||
asString(part.call_id) ||
asString(part.id) ||
undefined,
input,
});
continue;
@@ -199,6 +205,7 @@ function parseCursorToolCallEvent(event: Record<string, unknown>, ts: string): T
kind: "tool_call",
ts,
name: toolName,
toolUseId: callId,
input,
}];
}

View File

@@ -50,6 +50,7 @@ function parseToolUse(parsed: Record<string, unknown>, ts: string): TranscriptEn
kind: "tool_call",
ts,
name: toolName,
toolUseId: asString(part.callID) || asString(part.id) || undefined,
input,
};

View File

@@ -46,6 +46,7 @@ describe("resolveDatabaseTarget", () => {
const projectDir = path.join(tempDir, "repo");
fs.mkdirSync(projectDir, { recursive: true });
process.chdir(projectDir);
delete process.env.PAPERCLIP_CONFIG;
writeJson(path.join(projectDir, ".paperclip", "config.json"), {
database: { mode: "embedded-postgres", embeddedPostgresPort: 54329 },
});

View File

@@ -70,6 +70,7 @@ describe("codex_local ui stdout parser", () => {
kind: "tool_call",
ts,
name: "command_execution",
toolUseId: "item_2",
input: { id: "item_2", command: "/bin/zsh -lc ls" },
},
]);

View File

@@ -165,6 +165,7 @@ describe("cursor ui stdout parser", () => {
kind: "tool_call",
ts,
name: "shellToolCall",
toolUseId: "call_shell_1",
input: { command: longCommand },
},
]);
@@ -254,7 +255,7 @@ describe("cursor ui stdout parser", () => {
}),
ts,
),
).toEqual([{ kind: "tool_call", ts, name: "readToolCall", input: { path: "README.md" } }]);
).toEqual([{ kind: "tool_call", ts, name: "readToolCall", toolUseId: "call_1", input: { path: "README.md" } }]);
expect(
parseCursorStdoutLine(

View File

@@ -103,6 +103,7 @@ describe("opencode_local ui stdout parser", () => {
kind: "tool_call",
ts,
name: "bash",
toolUseId: "call_1",
input: { command: "ls -1" },
},
{

View File

@@ -1368,12 +1368,13 @@ export function heartbeatService(db: Db) {
const onLog = async (stream: "stdout" | "stderr", chunk: string) => {
if (stream === "stdout") stdoutExcerpt = appendExcerpt(stdoutExcerpt, chunk);
if (stream === "stderr") stderrExcerpt = appendExcerpt(stderrExcerpt, chunk);
const ts = new Date().toISOString();
if (handle) {
await runLogStore.append(handle, {
stream,
chunk,
ts: new Date().toISOString(),
ts,
});
}
@@ -1388,6 +1389,7 @@ export function heartbeatService(db: Db) {
payload: {
runId: run.id,
agentId: run.agentId,
ts,
stream,
chunk: payloadChunk,
truncated: payloadChunk.length !== chunk.length,

View File

@@ -23,6 +23,7 @@ import { Activity } from "./pages/Activity";
import { Inbox } from "./pages/Inbox";
import { CompanySettings } from "./pages/CompanySettings";
import { DesignGuide } from "./pages/DesignGuide";
import { RunTranscriptUxLab } from "./pages/RunTranscriptUxLab";
import { OrgChart } from "./pages/OrgChart";
import { NewAgent } from "./pages/NewAgent";
import { AuthPage } from "./pages/Auth";
@@ -145,6 +146,7 @@ function boardRoutes() {
<Route path="inbox/all" element={<Inbox />} />
<Route path="inbox/new" element={<Navigate to="/inbox/recent" replace />} />
<Route path="design-guide" element={<DesignGuide />} />
<Route path="tests/ux/runs" element={<RunTranscriptUxLab />} />
<Route path="*" element={<NotFoundPage scope="board" />} />
</>
);
@@ -246,6 +248,7 @@ export function App() {
<Route path="projects/:projectId/issues" element={<UnprefixedBoardRedirect />} />
<Route path="projects/:projectId/issues/:filter" element={<UnprefixedBoardRedirect />} />
<Route path="projects/:projectId/configuration" element={<UnprefixedBoardRedirect />} />
<Route path="tests/ux/runs" element={<UnprefixedBoardRedirect />} />
<Route path=":companyPrefix" element={<Layout />}>
{boardRoutes()}
</Route>

View File

@@ -6,3 +6,4 @@ export type {
UIAdapterModule,
AdapterConfigFieldsProps,
} from "./types";
export type { RunLogChunk } from "./transcript";

View File

@@ -1,8 +1,8 @@
import type { TranscriptEntry, StdoutLineParser } from "./types";
type RunLogChunk = { ts: string; stream: "stdout" | "stderr" | "system"; chunk: string };
export type RunLogChunk = { ts: string; stream: "stdout" | "stderr" | "system"; chunk: string };
function appendTranscriptEntry(entries: TranscriptEntry[], entry: TranscriptEntry) {
export function appendTranscriptEntry(entries: TranscriptEntry[], entry: TranscriptEntry) {
if ((entry.kind === "thinking" || entry.kind === "assistant") && entry.delta) {
const last = entries[entries.length - 1];
if (last && last.kind === entry.kind && last.delta) {
@@ -14,6 +14,12 @@ function appendTranscriptEntry(entries: TranscriptEntry[], entry: TranscriptEntr
entries.push(entry);
}
export function appendTranscriptEntries(entries: TranscriptEntry[], incoming: TranscriptEntry[]) {
for (const entry of incoming) {
appendTranscriptEntry(entries, entry);
}
}
export function buildTranscript(chunks: RunLogChunk[], parser: StdoutLineParser): TranscriptEntry[] {
const entries: TranscriptEntry[] = [];
let stdoutBuffer = "";
@@ -34,18 +40,14 @@ export function buildTranscript(chunks: RunLogChunk[], parser: StdoutLineParser)
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) continue;
for (const entry of parser(trimmed, chunk.ts)) {
appendTranscriptEntry(entries, entry);
}
appendTranscriptEntries(entries, parser(trimmed, chunk.ts));
}
}
const trailing = stdoutBuffer.trim();
if (trailing) {
const ts = chunks.length > 0 ? chunks[chunks.length - 1]!.ts : new Date().toISOString();
for (const entry of parser(trailing, ts)) {
appendTranscriptEntry(entries, entry);
}
appendTranscriptEntries(entries, parser(trailing, ts));
}
return entries;

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>
);

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>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -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;
},
};
}

View File

@@ -0,0 +1,226 @@
import type { TranscriptEntry } from "../adapters";
export interface RunTranscriptFixtureMeta {
sourceRunId: string;
fixtureLabel: string;
agentName: string;
agentId: string;
issueIdentifier: string;
issueTitle: string;
startedAt: string;
finishedAt: string | null;
}
export const runTranscriptFixtureMeta: RunTranscriptFixtureMeta = {
sourceRunId: "65a79d5d-5f85-4392-a5cc-8fb48beb9e71",
fixtureLabel: "Sanitized development fixture",
agentName: "CodexCoder",
agentId: "codexcoder-fixture",
issueIdentifier: "PAP-473",
issueTitle: "Humanize run transcripts across run detail and live surfaces",
startedAt: "2026-03-11T15:21:05.948Z",
finishedAt: null,
};
// Sanitized from a real development run. Paths, secrets, env vars, and user-local identifiers
// are replaced with safe placeholders while preserving the interaction shape.
export const runTranscriptFixtureEntries: TranscriptEntry[] = [
{
kind: "stderr",
ts: "2026-03-11T15:21:05.594Z",
text: "[paperclip] Skipping saved session resume for task \"PAP-473\" because wake reason is issue_assigned.",
},
{
kind: "init",
ts: "2026-03-11T15:21:05.948Z",
model: "codex",
sessionId: "sess_fixture_01",
},
{
kind: "system",
ts: "2026-03-11T15:21:07.249Z",
text: "turn started",
},
{
kind: "assistant",
ts: "2026-03-11T15:21:18.851Z",
text: "Im starting with the Paperclip heartbeat procedure and the repo-required docs so I can see what task is actually assigned and then work only on that scope.",
},
{
kind: "tool_call",
ts: "2026-03-11T15:21:19.026Z",
name: "command_execution",
toolUseId: "item_1",
input: {
command: "sed -n '1,220p' doc/GOAL.md",
cwd: "/workspace/paperclip",
},
},
{
kind: "tool_call",
ts: "2026-03-11T15:21:19.026Z",
name: "command_execution",
toolUseId: "item_2",
input: {
command: "sed -n '1,320p' doc/SPEC-implementation.md",
cwd: "/workspace/paperclip",
},
},
{
kind: "tool_result",
ts: "2026-03-11T15:21:19.034Z",
toolUseId: "item_1",
content: "command: sed -n '1,220p' doc/GOAL.md\nstatus: completed\nexit_code: 0\n\n# Paperclip\n\nPaperclip is the backbone of the autonomous economy.",
isError: false,
},
{
kind: "tool_result",
ts: "2026-03-11T15:21:19.035Z",
toolUseId: "item_2",
content: "command: sed -n '1,320p' doc/SPEC-implementation.md\nstatus: completed\nexit_code: 0\n\n# Paperclip V1 Implementation Spec\n\nPaperclip V1 must provide a full control-plane loop for autonomous agents.",
isError: false,
},
{
kind: "assistant",
ts: "2026-03-11T15:22:08.806Z",
text: "Ive got the rendering entry points. Im reading the existing transcript parser and the three UI surfaces together so I can collapse them onto one renderer instead of layering another one-off view.",
},
{
kind: "thinking",
ts: "2026-03-11T15:22:12.044Z",
text: "The current transcript UX duplicates parsing logic in multiple surfaces. A shared presentation layer will make the detail page and live surfaces behave the same way while keeping raw fallback available.",
},
{
kind: "tool_call",
ts: "2026-03-11T15:22:15.401Z",
name: "command_execution",
toolUseId: "item_3",
input: {
command: "rg -n \"LiveRunWidget|ActiveAgentsPanel|buildTranscript|TranscriptEntry|transcript\" ui/src server/src packages",
cwd: "/workspace/paperclip",
},
},
{
kind: "tool_result",
ts: "2026-03-11T15:22:15.982Z",
toolUseId: "item_3",
content: "command: rg -n ...\nstatus: completed\nexit_code: 0\n\nui/src/components/ActiveAgentsPanel.tsx\nui/src/components/LiveRunWidget.tsx\nui/src/pages/AgentDetail.tsx",
isError: false,
},
{
kind: "system",
ts: "2026-03-11T15:22:21.617Z",
text: "item started: web_search (id=ws_fixture_reasoning_ui)",
},
{
kind: "system",
ts: "2026-03-11T15:22:24.806Z",
text: "item completed: web_search (id=ws_fixture_reasoning_ui)",
},
{
kind: "assistant",
ts: "2026-03-11T15:22:29.214Z",
text: "Ive confirmed the duplication: the run page has the only full transcript renderer, while live surfaces still collapse output into feed strings. Im pulling markdown utilities and adapter shapes now so the new renderer can stay shared.",
},
{
kind: "tool_call",
ts: "2026-03-11T15:23:04.251Z",
name: "command_execution",
toolUseId: "item_4",
input: {
command: "pnpm -r typecheck",
cwd: "/workspace/paperclip",
},
},
{
kind: "tool_result",
ts: "2026-03-11T15:23:26.903Z",
toolUseId: "item_4",
content: "command: pnpm -r typecheck\nstatus: completed\nexit_code: 0\n\npackages/adapter-utils typecheck: Done\nserver typecheck: Done\nui typecheck: Done\ncli typecheck: Done",
isError: false,
},
{
kind: "assistant",
ts: "2026-03-11T15:23:34.102Z",
text: "Typecheck is clean. Im running the remaining repo checks now so the transcript work is verified under the full workspace build, not just the UI package.",
},
{
kind: "tool_call",
ts: "2026-03-11T15:23:40.511Z",
name: "command_execution",
toolUseId: "item_5",
input: {
command: "pnpm test:run",
cwd: "/workspace/paperclip",
},
},
{
kind: "tool_result",
ts: "2026-03-11T15:23:56.944Z",
toolUseId: "item_5",
content: "command: pnpm test:run\nstatus: failed\nexit_code: 1\n\nFAIL packages/db/src/runtime-config.test.ts\nFAIL src/__tests__/worktree.test.ts\n\nAll transcript-adapter tests passed after snapshot updates.",
isError: true,
},
{
kind: "thinking",
ts: "2026-03-11T15:24:02.188Z",
text: "The remaining failures are unrelated to transcript rendering, so I should isolate them in the handoff and keep the UI change set focused.",
},
{
kind: "assistant",
ts: "2026-03-11T15:24:08.490Z",
text: "The new parser metadata changed a few adapter test snapshots exactly where expected, and the remaining red tests are outside this change set. Im keeping the transcript patch focused and shipping with that caveat called out.",
},
{
kind: "tool_call",
ts: "2026-03-11T15:24:21.327Z",
name: "command_execution",
toolUseId: "item_6",
input: {
command: "pnpm build",
cwd: "/workspace/paperclip",
},
},
{
kind: "tool_result",
ts: "2026-03-11T15:24:44.030Z",
toolUseId: "item_6",
content: "command: pnpm build\nstatus: completed\nexit_code: 0\n\nui build: built successfully\ncli build: Done",
isError: false,
},
{
kind: "tool_call",
ts: "2026-03-11T15:24:52.504Z",
name: "command_execution",
toolUseId: "item_7",
input: {
command: "git commit -m \"Humanize run transcripts across run detail and live surfaces\"",
cwd: "/workspace/paperclip",
},
},
{
kind: "tool_result",
ts: "2026-03-11T15:24:53.104Z",
toolUseId: "item_7",
content: "command: git commit ...\nstatus: completed\nexit_code: 0\n\n87b8e21 Humanize run transcripts across run detail and live surfaces",
isError: false,
},
{
kind: "assistant",
ts: "2026-03-11T15:25:00.908Z",
text: "Implemented the transcript UI refactor and switched the run detail page, issue live widget, and dashboard agent card onto the same rendering language.",
},
{
kind: "result",
ts: "2026-03-11T15:25:05.440Z",
text: "Transcript rollout complete with shared nice/raw rendering and compact live variants.",
inputTokens: 11240,
outputTokens: 3460,
cachedTokens: 520,
costUsd: 0.048121,
subtype: "success",
isError: false,
errors: [],
},
];

View File

@@ -17,7 +17,6 @@ import { AgentConfigForm } from "../components/AgentConfigForm";
import { PageTabBar } from "../components/PageTabBar";
import { adapterLabels, roleLabels } from "../components/agent-config-primitives";
import { getUIAdapter, buildTranscript } from "../adapters";
import type { TranscriptEntry } from "../adapters";
import { StatusBadge } from "../components/StatusBadge";
import { agentStatusDot, agentStatusDotDefault } from "../lib/status-colors";
import { MarkdownBody } from "../components/MarkdownBody";
@@ -58,6 +57,7 @@ import {
} from "lucide-react";
import { Input } from "@/components/ui/input";
import { AgentIcon, AgentIconPicker } from "../components/AgentIconPicker";
import { RunTranscriptView, type TranscriptMode } from "../components/transcript/RunTranscriptView";
import { isUuidLike, type Agent, type HeartbeatRun, type HeartbeatRunEvent, type AgentRuntimeState, type LiveEvent } from "@paperclipai/shared";
import { agentRouteRef } from "../lib/utils";
@@ -1675,6 +1675,7 @@ function LogViewer({ run, adapterType }: { run: HeartbeatRun; adapterType: strin
const [logOffset, setLogOffset] = useState(0);
const [isFollowing, setIsFollowing] = useState(false);
const [isStreamingConnected, setIsStreamingConnected] = useState(false);
const [transcriptMode, setTranscriptMode] = useState<TranscriptMode>("nice");
const logEndRef = useRef<HTMLDivElement>(null);
const pendingLogLineRef = useRef("");
const scrollContainerRef = useRef<ScrollContainer | null>(null);
@@ -2028,6 +2029,10 @@ function LogViewer({ run, adapterType }: { run: HeartbeatRun; adapterType: strin
const adapter = useMemo(() => getUIAdapter(adapterType), [adapterType]);
const transcript = useMemo(() => buildTranscript(logLines, adapter.parseStdoutLine), [logLines, adapter]);
useEffect(() => {
setTranscriptMode("nice");
}, [run.id]);
if (loading && logLoading) {
return <p className="text-xs text-muted-foreground">Loading run logs...</p>;
}
@@ -2120,6 +2125,23 @@ function LogViewer({ run, adapterType }: { run: HeartbeatRun; adapterType: strin
Transcript ({transcript.length})
</span>
<div className="flex items-center gap-2">
<div className="inline-flex rounded-lg border border-border/70 bg-background/70 p-0.5">
{(["nice", "raw"] as const).map((mode) => (
<button
key={mode}
type="button"
className={cn(
"rounded-md px-2.5 py-1 text-[11px] font-medium capitalize transition-colors",
transcriptMode === mode
? "bg-accent text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground",
)}
onClick={() => setTranscriptMode(mode)}
>
{mode}
</button>
))}
</div>
{isLive && !isFollowing && (
<Button
variant="ghost"
@@ -2146,123 +2168,18 @@ function LogViewer({ run, adapterType }: { run: HeartbeatRun; adapterType: strin
)}
</div>
</div>
<div className="bg-neutral-100 dark:bg-neutral-950 rounded-lg p-3 font-mono text-xs space-y-0.5 overflow-x-hidden">
{transcript.length === 0 && !run.logRef && (
<div className="text-neutral-500">No persisted transcript for this run.</div>
<div className="max-h-[38rem] overflow-y-auto rounded-2xl border border-border/70 bg-background/40 p-3 sm:p-4">
<RunTranscriptView
entries={transcript}
mode={transcriptMode}
streaming={isLive}
emptyMessage={run.logRef ? "Waiting for transcript..." : "No persisted transcript for this run."}
/>
{logError && (
<div className="mt-3 rounded-xl border border-red-500/20 bg-red-500/[0.06] px-3 py-2 text-xs text-red-700 dark:text-red-300">
{logError}
</div>
)}
{transcript.map((entry, idx) => {
const time = new Date(entry.ts).toLocaleTimeString("en-US", { hour12: false });
const grid = "grid grid-cols-[auto_auto_1fr] gap-x-2 sm:gap-x-3 items-baseline";
const tsCell = "text-neutral-400 dark:text-neutral-600 select-none w-12 sm:w-16 text-[10px] sm:text-xs";
const lblCell = "w-14 sm:w-20 text-[10px] sm:text-xs";
const contentCell = "min-w-0 whitespace-pre-wrap break-words overflow-hidden";
const expandCell = "col-span-full md:col-start-3 md:col-span-1";
if (entry.kind === "assistant") {
return (
<div key={`${entry.ts}-assistant-${idx}`} className={cn(grid, "py-0.5")}>
<span className={tsCell}>{time}</span>
<span className={cn(lblCell, "text-green-700 dark:text-green-300")}>assistant</span>
<span className={cn(contentCell, "text-green-900 dark:text-green-100")}>{entry.text}</span>
</div>
);
}
if (entry.kind === "thinking") {
return (
<div key={`${entry.ts}-thinking-${idx}`} className={cn(grid, "py-0.5")}>
<span className={tsCell}>{time}</span>
<span className={cn(lblCell, "text-green-600/60 dark:text-green-300/60")}>thinking</span>
<span className={cn(contentCell, "text-green-800/60 dark:text-green-100/60 italic")}>{entry.text}</span>
</div>
);
}
if (entry.kind === "user") {
return (
<div key={`${entry.ts}-user-${idx}`} className={cn(grid, "py-0.5")}>
<span className={tsCell}>{time}</span>
<span className={cn(lblCell, "text-neutral-500 dark:text-neutral-400")}>user</span>
<span className={cn(contentCell, "text-neutral-700 dark:text-neutral-300")}>{entry.text}</span>
</div>
);
}
if (entry.kind === "tool_call") {
return (
<div key={`${entry.ts}-tool-${idx}`} className={cn(grid, "gap-y-1 py-0.5")}>
<span className={tsCell}>{time}</span>
<span className={cn(lblCell, "text-yellow-700 dark:text-yellow-300")}>tool_call</span>
<span className="text-yellow-900 dark:text-yellow-100 min-w-0">{entry.name}</span>
<pre className={cn(expandCell, "bg-neutral-200 dark:bg-neutral-900 rounded p-2 text-[11px] overflow-x-auto whitespace-pre-wrap text-neutral-800 dark:text-neutral-200")}>
{JSON.stringify(entry.input, null, 2)}
</pre>
</div>
);
}
if (entry.kind === "tool_result") {
return (
<div key={`${entry.ts}-toolres-${idx}`} className={cn(grid, "gap-y-1 py-0.5")}>
<span className={tsCell}>{time}</span>
<span className={cn(lblCell, entry.isError ? "text-red-600 dark:text-red-300" : "text-purple-600 dark:text-purple-300")}>tool_result</span>
{entry.isError ? <span className="text-red-600 dark:text-red-400 min-w-0">error</span> : <span />}
<pre className={cn(expandCell, "bg-neutral-100 dark:bg-neutral-900 rounded p-2 text-[11px] overflow-x-auto whitespace-pre-wrap text-neutral-700 dark:text-neutral-300 max-h-60 overflow-y-auto")}>
{(() => { try { return JSON.stringify(JSON.parse(entry.content), null, 2); } catch { return entry.content; } })()}
</pre>
</div>
);
}
if (entry.kind === "init") {
return (
<div key={`${entry.ts}-init-${idx}`} className={grid}>
<span className={tsCell}>{time}</span>
<span className={cn(lblCell, "text-blue-700 dark:text-blue-300")}>init</span>
<span className={cn(contentCell, "text-blue-900 dark:text-blue-100")}>model: {entry.model}{entry.sessionId ? `, session: ${entry.sessionId}` : ""}</span>
</div>
);
}
if (entry.kind === "result") {
return (
<div key={`${entry.ts}-result-${idx}`} className={cn(grid, "gap-y-1 py-0.5")}>
<span className={tsCell}>{time}</span>
<span className={cn(lblCell, "text-cyan-700 dark:text-cyan-300")}>result</span>
<span className={cn(contentCell, "text-cyan-900 dark:text-cyan-100")}>
tokens in={formatTokens(entry.inputTokens)} out={formatTokens(entry.outputTokens)} cached={formatTokens(entry.cachedTokens)} cost=${entry.costUsd.toFixed(6)}
</span>
{(entry.subtype || entry.isError || entry.errors.length > 0) && (
<div className={cn(expandCell, "text-red-600 dark:text-red-300 whitespace-pre-wrap break-words")}>
subtype={entry.subtype || "unknown"} is_error={entry.isError ? "true" : "false"}
{entry.errors.length > 0 ? ` errors=${entry.errors.join(" | ")}` : ""}
</div>
)}
{entry.text && (
<div className={cn(expandCell, "whitespace-pre-wrap break-words text-neutral-800 dark:text-neutral-100")}>{entry.text}</div>
)}
</div>
);
}
const rawText = entry.text;
const label =
entry.kind === "stderr" ? "stderr" :
entry.kind === "system" ? "system" :
"stdout";
const color =
entry.kind === "stderr" ? "text-red-600 dark:text-red-300" :
entry.kind === "system" ? "text-blue-600 dark:text-blue-300" :
"text-neutral-500";
return (
<div key={`${entry.ts}-raw-${idx}`} className={grid}>
<span className={tsCell}>{time}</span>
<span className={cn(lblCell, color)}>{label}</span>
<span className={cn(contentCell, color)}>{rawText}</span>
</div>
)
})}
{logError && <div className="text-red-600 dark:text-red-300">{logError}</div>}
<div ref={logEndRef} />
</div>

View File

@@ -0,0 +1,334 @@
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { cn, formatDateTime } from "../lib/utils";
import { Identity } from "../components/Identity";
import { StatusBadge } from "../components/StatusBadge";
import { RunTranscriptView, type TranscriptDensity, type TranscriptMode } from "../components/transcript/RunTranscriptView";
import { runTranscriptFixtureEntries, runTranscriptFixtureMeta } from "../fixtures/runTranscriptFixtures";
import { ExternalLink, FlaskConical, LayoutPanelLeft, MonitorCog, PanelsTopLeft, RadioTower } from "lucide-react";
type SurfaceId = "detail" | "live" | "dashboard";
const surfaceOptions: Array<{
id: SurfaceId;
label: string;
eyebrow: string;
description: string;
icon: typeof LayoutPanelLeft;
}> = [
{
id: "detail",
label: "Run Detail",
eyebrow: "Full transcript",
description: "The long-form run page with the `Nice | Raw` toggle and the most inspectable transcript view.",
icon: MonitorCog,
},
{
id: "live",
label: "Issue Widget",
eyebrow: "Live stream",
description: "The issue-detail live run widget, optimized for following an active run without leaving the task page.",
icon: RadioTower,
},
{
id: "dashboard",
label: "Dashboard Card",
eyebrow: "Dense card",
description: "The active-agents dashboard card, tuned for compact scanning while keeping the same transcript language.",
icon: PanelsTopLeft,
},
];
function previewEntries(surface: SurfaceId) {
if (surface === "dashboard") {
return runTranscriptFixtureEntries.slice(-9);
}
if (surface === "live") {
return runTranscriptFixtureEntries.slice(-14);
}
return runTranscriptFixtureEntries;
}
function RunDetailPreview({
mode,
streaming,
density,
}: {
mode: TranscriptMode;
streaming: boolean;
density: TranscriptDensity;
}) {
return (
<div className="overflow-hidden rounded-xl border border-border/70 bg-background/80 shadow-[0_24px_60px_rgba(15,23,42,0.08)]">
<div className="border-b border-border/60 bg-background/90 px-5 py-4">
<div className="flex flex-wrap items-center gap-2">
<Badge variant="outline" className="uppercase tracking-[0.18em] text-[10px]">
Run Detail
</Badge>
<StatusBadge status={streaming ? "running" : "succeeded"} />
<span className="text-xs text-muted-foreground">
{formatDateTime(runTranscriptFixtureMeta.startedAt)}
</span>
</div>
<div className="mt-2 text-sm font-medium">
Transcript ({runTranscriptFixtureEntries.length})
</div>
</div>
<div className="max-h-[720px] overflow-y-auto bg-[radial-gradient(circle_at_top_left,rgba(8,145,178,0.08),transparent_36%),radial-gradient(circle_at_bottom_right,rgba(245,158,11,0.10),transparent_28%)] p-5">
<RunTranscriptView
entries={runTranscriptFixtureEntries}
mode={mode}
density={density}
streaming={streaming}
/>
</div>
</div>
);
}
function LiveWidgetPreview({
streaming,
mode,
density,
}: {
streaming: boolean;
mode: TranscriptMode;
density: TranscriptDensity;
}) {
return (
<div className="overflow-hidden rounded-xl border border-cyan-500/25 bg-background/85 shadow-[0_20px_50px_rgba(6,182,212,0.10)]">
<div className="border-b border-border/60 bg-cyan-500/[0.05] px-5 py-4">
<div className="text-xs font-semibold uppercase tracking-[0.2em] text-cyan-700 dark:text-cyan-300">
Live Runs
</div>
<div className="mt-1 text-xs text-muted-foreground">
Compact live transcript stream for the issue detail page.
</div>
</div>
<div className="px-5 py-4">
<div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
<div className="min-w-0">
<Identity name={runTranscriptFixtureMeta.agentName} size="sm" />
<div className="mt-2 flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
<span className="rounded-full border border-border/70 bg-background/70 px-2 py-1 font-mono">
{runTranscriptFixtureMeta.sourceRunId.slice(0, 8)}
</span>
<StatusBadge status={streaming ? "running" : "succeeded"} />
<span>{formatDateTime(runTranscriptFixtureMeta.startedAt)}</span>
</div>
</div>
<span className="inline-flex items-center gap-1 rounded-full border border-border/70 bg-background/70 px-2.5 py-1 text-[11px] text-muted-foreground">
Open run
<ExternalLink className="h-3 w-3" />
</span>
</div>
<div className="max-h-[460px] overflow-y-auto pr-1">
<RunTranscriptView
entries={previewEntries("live")}
mode={mode}
density={density}
limit={density === "compact" ? 10 : 12}
streaming={streaming}
/>
</div>
</div>
</div>
);
}
function DashboardPreview({
streaming,
mode,
density,
}: {
streaming: boolean;
mode: TranscriptMode;
density: TranscriptDensity;
}) {
return (
<div className="max-w-md">
<div className={cn(
"flex h-[320px] flex-col overflow-hidden rounded-xl border shadow-[0_20px_40px_rgba(15,23,42,0.10)]",
streaming
? "border-cyan-500/25 bg-cyan-500/[0.04]"
: "border-border bg-background/75",
)}>
<div className="border-b border-border/60 px-4 py-4">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="flex items-center gap-2">
<span className={cn(
"inline-flex h-2.5 w-2.5 rounded-full",
streaming ? "bg-cyan-500 shadow-[0_0_0_6px_rgba(34,211,238,0.12)]" : "bg-muted-foreground/35",
)} />
<Identity name={runTranscriptFixtureMeta.agentName} size="sm" />
</div>
<div className="mt-2 text-[11px] text-muted-foreground">
{streaming ? "Live now" : "Finished 2m ago"}
</div>
</div>
<span className="rounded-full border border-border/70 bg-background/70 px-2 py-1 text-[10px] text-muted-foreground">
<ExternalLink className="h-2.5 w-2.5" />
</span>
</div>
<div className="mt-3 rounded-lg border border-border/60 bg-background/60 px-3 py-2 text-xs text-cyan-700 dark:text-cyan-300">
{runTranscriptFixtureMeta.issueIdentifier} - {runTranscriptFixtureMeta.issueTitle}
</div>
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-4">
<RunTranscriptView
entries={previewEntries("dashboard")}
mode={mode}
density={density}
limit={density === "compact" ? 6 : 8}
streaming={streaming}
/>
</div>
</div>
</div>
);
}
export function RunTranscriptUxLab() {
const [selectedSurface, setSelectedSurface] = useState<SurfaceId>("detail");
const [detailMode, setDetailMode] = useState<TranscriptMode>("nice");
const [streaming, setStreaming] = useState(true);
const [density, setDensity] = useState<TranscriptDensity>("comfortable");
const selected = surfaceOptions.find((option) => option.id === selectedSurface) ?? surfaceOptions[0];
return (
<div className="space-y-6">
<div className="overflow-hidden rounded-2xl border border-border/70 bg-[linear-gradient(135deg,rgba(8,145,178,0.08),transparent_28%),linear-gradient(180deg,rgba(245,158,11,0.08),transparent_40%),var(--background)] shadow-[0_28px_70px_rgba(15,23,42,0.10)]">
<div className="grid gap-6 lg:grid-cols-[260px_minmax(0,1fr)]">
<aside className="border-b border-border/60 bg-background/75 p-5 lg:border-b-0 lg:border-r">
<div className="mb-5">
<div className="inline-flex items-center gap-2 rounded-full border border-cyan-500/25 bg-cyan-500/[0.08] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.24em] text-cyan-700 dark:text-cyan-300">
<FlaskConical className="h-3.5 w-3.5" />
UX Lab
</div>
<h1 className="mt-4 text-2xl font-semibold tracking-tight">Run Transcript Fixtures</h1>
<p className="mt-2 text-sm text-muted-foreground">
Built from a real Paperclip development run, then sanitized so no secrets, local paths, or environment details survive into the fixture.
</p>
</div>
<div className="space-y-2">
{surfaceOptions.map((option) => {
const Icon = option.icon;
return (
<button
key={option.id}
type="button"
onClick={() => setSelectedSurface(option.id)}
className={cn(
"w-full rounded-xl border px-4 py-3 text-left transition-all",
selectedSurface === option.id
? "border-cyan-500/35 bg-cyan-500/[0.10] shadow-[0_12px_24px_rgba(6,182,212,0.12)]"
: "border-border/70 bg-background/70 hover:border-cyan-500/20 hover:bg-cyan-500/[0.04]",
)}
>
<div className="flex items-start gap-3">
<span className="rounded-lg border border-current/15 p-2 text-cyan-700 dark:text-cyan-300">
<Icon className="h-4 w-4" />
</span>
<span className="min-w-0">
<span className="block text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
{option.eyebrow}
</span>
<span className="mt-1 block text-sm font-medium">{option.label}</span>
<span className="mt-1 block text-xs text-muted-foreground">
{option.description}
</span>
</span>
</div>
</button>
);
})}
</div>
</aside>
<main className="min-w-0 p-5">
<div className="mb-5 flex flex-col gap-4 xl:flex-row xl:items-end xl:justify-between">
<div>
<div className="text-[11px] font-semibold uppercase tracking-[0.22em] text-muted-foreground">
{selected.eyebrow}
</div>
<h2 className="mt-1 text-2xl font-semibold">{selected.label}</h2>
<p className="mt-2 max-w-2xl text-sm text-muted-foreground">
{selected.description}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<Badge variant="outline" className="rounded-full px-3 py-1 text-[10px] uppercase tracking-[0.18em]">
Source run {runTranscriptFixtureMeta.sourceRunId.slice(0, 8)}
</Badge>
<Badge variant="outline" className="rounded-full px-3 py-1 text-[10px] uppercase tracking-[0.18em]">
{runTranscriptFixtureMeta.issueIdentifier}
</Badge>
</div>
</div>
<div className="mb-5 flex flex-wrap items-center gap-2">
<span className="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">
Controls
</span>
<div className="inline-flex rounded-full border border-border/70 bg-background/80 p-1">
{(["nice", "raw"] as const).map((mode) => (
<button
key={mode}
type="button"
className={cn(
"rounded-full px-3 py-1 text-xs font-medium capitalize transition-colors",
detailMode === mode ? "bg-accent text-foreground" : "text-muted-foreground hover:text-foreground",
)}
onClick={() => setDetailMode(mode)}
>
{mode}
</button>
))}
</div>
<div className="inline-flex rounded-full border border-border/70 bg-background/80 p-1">
{(["comfortable", "compact"] as const).map((nextDensity) => (
<button
key={nextDensity}
type="button"
className={cn(
"rounded-full px-3 py-1 text-xs font-medium capitalize transition-colors",
density === nextDensity ? "bg-accent text-foreground" : "text-muted-foreground hover:text-foreground",
)}
onClick={() => setDensity(nextDensity)}
>
{nextDensity}
</button>
))}
</div>
<Button
variant="outline"
size="sm"
className="rounded-full"
onClick={() => setStreaming((value) => !value)}
>
{streaming ? "Show settled state" : "Show streaming state"}
</Button>
</div>
{selectedSurface === "detail" ? (
<div className={cn(density === "compact" && "max-w-5xl")}>
<RunDetailPreview mode={detailMode} streaming={streaming} density={density} />
</div>
) : selectedSurface === "live" ? (
<div className={cn(density === "compact" && "max-w-4xl")}>
<LiveWidgetPreview streaming={streaming} mode={detailMode} density={density} />
</div>
) : (
<DashboardPreview streaming={streaming} mode={detailMode} density={density} />
)}
</main>
</div>
</div>
</div>
);
}