Files
archie/ui/src/workflows/AgentTranscript.vue
T

315 lines
14 KiB
Vue

<script setup lang="ts">
import { ArrowUpRightIcon, BotIcon, BrainIcon, CircleAlertIcon, CircleCheckIcon, FlagIcon, FlaskConicalIcon, FoldVerticalIcon, GlobeIcon, ScrollTextIcon, SparklesIcon, SquareTerminalIcon, TargetIcon } from "@lucide/vue";
import { createReusableTemplate } from "@vueuse/core";
import { computed, onUnmounted, ref, watch } from "vue";
import { Bubble, BubbleContent } from "@/components/ui/bubble";
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Message, MessageContent } from "@/components/ui/message";
import { Spinner } from "@/components/ui/spinner";
import {
Trace,
TraceCollapsible,
TraceCollapsibleContent,
TraceCollapsibleTrigger,
TraceDescription,
TraceIcon,
TraceLine,
TraceTitle,
} from "@/components/ui/trace";
import ChatMarkdown from "@/chat/ChatMarkdown.vue";
import { api } from "@/lib/api";
import { errors } from "@/copy/errors";
import { keepValue } from "@/lib/keep-unchanged";
import { useLiveResource } from "@/stores/session";
import { duration } from "@/tasks/timeline-event";
import type { TaskEvent } from "@/tasks/task-run";
/** One agent_transcript entry, as the State Store records it. */
interface Entry {
seq: number;
kind: string;
text?: string;
text_bytes?: number;
reasoning?: string;
reasoning_bytes?: number;
tool_calls?: { id?: string; name: string }[];
call_id?: string;
tool?: string;
args?: string;
args_bytes?: number;
output?: string;
output_bytes?: number;
error?: string;
finish_reason?: string;
usage?: { prompt_tokens?: number; completion_tokens?: number; cached_tokens?: number };
latency_ms?: number;
}
/** The text as recorded, with a note when it was clipped. */
function withClip(text: string | undefined, bytes: number | undefined): string {
if (!bytes) return text ?? "";
return `${text ?? ""}\n… clipped, ${(bytes / 1024).toFixed(1)} KB in full`;
}
/**
* How one tool call is drawn: a shell command as a terminal, the gate as a
* test run, a fetch as a source, finish as the run's own verdict, anything
* else as input then output.
*/
function toolView(tool: Entry) {
let args: Record<string, unknown> = {};
try {
const parsed: unknown = JSON.parse(tool.args ?? "");
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) args = parsed as Record<string, unknown>;
} catch {
// Unparseable arguments draw as the raw text below.
}
const failed = !!tool.error;
const kind = tool.tool === "shell" ? "terminal" : tool.tool === "check" ? "tests" : tool.tool === "web_fetch" ? "source" : tool.tool === "finish" ? "finish" : "tool";
const command = String(args.command ?? "");
const url = String(args.url ?? "");
let host = url;
try {
host = new URL(url).hostname;
} catch {
// Not a URL: the row names it as given.
}
// A plain call is named by its main value, as "read src/main.go" rather
// than its JSON: the first string argument.
const first = Object.values(args).find((v) => typeof v === "string" && v);
const argument = typeof first === "string" ? first.split("\n", 1)[0] : "";
const ran = failed ? errors.workflows.transcript.tool.failedToRun : "Ran";
const title =
kind === "terminal" ? `${ran} ${command.split("\n", 1)[0]}`
: kind === "tests" ? (failed ? errors.workflows.transcript.tool.gateFailed : "Ran the gate")
: kind === "source" ? `${failed ? errors.workflows.transcript.tool.failedToRead : "Read"} ${host}`
: kind === "finish" ? `Finished as ${String(args.status ?? "unknown")}`
: `${ran} ${tool.tool} ${argument}`;
return { args, failed, kind, command, url, title, output: withClip(tool.output, tool.output_bytes) };
}
const [DefineTool, ToolView] = createReusableTemplate<{ tool: Entry; view: ReturnType<typeof toolView> }>();
/** One step's agent conversations for one attempt, oldest first. */
const props = defineProps<{ taskId: number | string; attempt: number; match: (event: TaskEvent) => boolean; running: boolean }>();
interface Step { model: Entry; tools: Entry[] }
type Row =
| { kind: "prompt"; title: string; entry: Entry }
| { kind: "user"; entry: Entry }
| { kind: "compaction"; entry: Entry }
| { kind: "step"; number: number; step: Step };
interface Conversation { key: string; label: string; rows: Row[]; steps: number; tools: number; failed: number }
const [DefineConversation, ConversationView] = createReusableTemplate<{ conversation: Conversation }>();
const events = ref<TaskEvent[]>();
const failed = ref(false);
let generation = 0;
let timer: ReturnType<typeof setInterval> | undefined;
async function load(): Promise<void> {
const current = ++generation;
try {
const view = await api.taskTranscript<{ entries?: TaskEvent[] }>(String(props.taskId), { attempt: props.attempt });
if (current !== generation) return;
events.value = keepValue(events.value, view.entries ?? []);
failed.value = false;
} catch {
if (current === generation) failed.value = true;
}
}
watch(() => [props.taskId, props.attempt], () => { events.value = undefined; failed.value = false; void load(); }, { immediate: true });
watch(() => props.running, (running) => {
clearInterval(timer);
if (running) timer = setInterval(() => void load(), 3000);
}, { immediate: true });
useLiveResource("tasks", () => void load(), 1000);
onUnmounted(() => { generation++; clearInterval(timer); });
function usage(entry: Entry): string {
const u = entry.usage;
const parts = [];
if (u?.prompt_tokens) parts.push(`${u.prompt_tokens.toLocaleString()} in`);
if (u?.cached_tokens) parts.push(`${u.cached_tokens.toLocaleString()} cached`);
if (u?.completion_tokens) parts.push(`${u.completion_tokens.toLocaleString()} out`);
if (entry.latency_ms) parts.push(duration(entry.latency_ms));
return parts.join(" · ");
}
function plural(n: number, word: string): string {
return `${n} ${word}${n === 1 ? "" : "s"}`;
}
// Tool results sit under the step whose response asked for them.
function conversation(key: string, label: string, entries: Entry[]): Conversation {
const rows: Row[] = [];
const owner = new Map<string, Step>();
let prompted = false;
let steps = 0;
for (const entry of entries) {
if (entry.kind === "system") rows.push({ kind: "prompt", title: "System prompt", entry });
else if (entry.kind === "user") {
rows.push(prompted ? { kind: "user", entry } : { kind: "prompt", title: "Mission", entry });
prompted = true;
} else if (entry.kind === "compaction") rows.push({ kind: "compaction", entry });
else if (entry.kind === "model") {
const step: Step = { model: entry, tools: [] };
for (const call of entry.tool_calls ?? []) if (call.id) owner.set(call.id, step);
rows.push({ kind: "step", number: ++steps, step });
} else if (entry.kind === "tool") {
const step = entry.call_id ? owner.get(entry.call_id) : undefined;
if (step) step.tools.push(entry);
else rows.push({ kind: "step", number: ++steps, step: { model: { seq: entry.seq, kind: "model" }, tools: [entry] } });
}
}
const tools = entries.filter((entry) => entry.kind === "tool");
return { key, label, rows, steps, tools: tools.length, failed: tools.filter((tool) => tool.error).length };
}
// Each agent in the step (a fan-out branch, or a retry) keeps its own
// conversation, numbered from 1.
const conversations = computed(() => {
const byAgent = new Map<string, Entry[][]>();
for (const event of (events.value ?? []).filter(props.match)) {
const key = [event.data?.branch, event.stage].filter(Boolean).join("/");
const entry = event.data as unknown as Entry;
const runs = byAgent.get(key) ?? [];
if (!runs.length || entry.seq === 1) runs.push([]);
runs.at(-1)!.push(entry);
byAgent.set(key, runs);
}
return [...byAgent.entries()].flatMap(([label, runs]) => runs.map((entries, i) => conversation(`${label}#${i}`, label, entries)));
});
</script>
<template>
<DefineTool v-slot="{ tool, view }">
<TraceCollapsible :default-open="view.failed">
<TraceCollapsibleTrigger>
<TraceLine :status="view.failed ? 'error' : undefined">
<TraceIcon>
<CircleAlertIcon v-if="view.failed" />
<SquareTerminalIcon v-else-if="view.kind === 'terminal'" />
<FlaskConicalIcon v-else-if="view.kind === 'tests'" />
<GlobeIcon v-else-if="view.kind === 'source'" />
<FlagIcon v-else-if="view.kind === 'finish'" />
<CircleCheckIcon v-else />
</TraceIcon>
<TraceTitle :class="view.kind === 'terminal' && 'font-mono'">{{ view.title }}</TraceTitle>
<TraceDescription v-if="tool.latency_ms">{{ duration(tool.latency_ms) }}</TraceDescription>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent class="flex flex-col gap-2">
<template v-if="view.kind === 'terminal'">
<CodeBlock size="sm" :variant="view.failed ? 'destructive' : 'default'">
<CodeBlockContent wrap class="max-h-64 font-mono">$ {{ view.command }}
{{ view.output }}{{ tool.error ? `\n${tool.error}` : '' }}</CodeBlockContent>
</CodeBlock>
</template>
<template v-else-if="view.kind === 'finish'">
<p class="whitespace-pre-wrap">{{ String(view.args.summary ?? '') }}</p>
</template>
<template v-else>
<Trace v-if="view.kind === 'source' && view.url">
<a :href="view.url" target="_blank" rel="noreferrer">
<TraceLine>
<TraceIcon><GlobeIcon /></TraceIcon>
<TraceTitle>{{ view.url }}<span class="sr-only"> (opens in a new tab)</span></TraceTitle>
<TraceIcon><ArrowUpRightIcon /></TraceIcon>
</TraceLine>
</a>
</Trace>
<CodeBlock v-if="view.kind === 'tool'" size="sm">
<CodeBlockContent wrap class="max-h-48">{{ withClip(tool.args, tool.args_bytes) }}</CodeBlockContent>
</CodeBlock>
<CodeBlock v-if="tool.error" size="sm" variant="destructive">
<CodeBlockContent wrap class="max-h-64">{{ tool.error }}</CodeBlockContent>
</CodeBlock>
<CodeBlock v-if="tool.output || !tool.error" size="sm">
<CodeBlockContent wrap class="max-h-64">{{ view.output }}</CodeBlockContent>
</CodeBlock>
</template>
</TraceCollapsibleContent>
</TraceCollapsible>
</DefineTool>
<DefineConversation v-slot="{ conversation: c }">
<div class="flex flex-col gap-4">
<template v-for="row in c.rows" :key="`${row.kind}-${row.kind === 'step' ? row.number : row.entry.seq}`">
<Trace v-if="row.kind === 'prompt' || row.kind === 'compaction'">
<TraceCollapsible>
<TraceCollapsibleTrigger>
<TraceLine>
<TraceIcon>
<FoldVerticalIcon v-if="row.kind === 'compaction'" />
<TargetIcon v-else-if="row.title === 'Mission'" />
<ScrollTextIcon v-else />
</TraceIcon>
<TraceTitle>{{ row.kind === 'compaction' ? 'Compacted the history' : row.title }}</TraceTitle>
<TraceDescription v-if="row.kind === 'compaction' && usage(row.entry)">{{ usage(row.entry) }}</TraceDescription>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent>
<CodeBlock size="sm">
<CodeBlockContent wrap class="max-h-96">{{ withClip(row.entry.text || row.entry.error, row.entry.text_bytes) }}</CodeBlockContent>
</CodeBlock>
</TraceCollapsibleContent>
</TraceCollapsible>
</Trace>
<Message v-else-if="row.kind === 'user'" align="end">
<MessageContent>
<Bubble align="end" variant="muted">
<BubbleContent class="whitespace-pre-wrap [overflow-wrap:anywhere]">{{ withClip(row.entry.text, row.entry.text_bytes) }}</BubbleContent>
</Bubble>
</MessageContent>
</Message>
<Message v-else>
<MessageContent class="gap-2">
<Trace v-if="row.step.model.reasoning">
<TraceCollapsible>
<TraceCollapsibleTrigger>
<TraceLine>
<TraceIcon><BrainIcon /></TraceIcon>
<TraceTitle>Thought</TraceTitle>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent class="whitespace-pre-wrap">{{ withClip(row.step.model.reasoning, row.step.model.reasoning_bytes) }}</TraceCollapsibleContent>
</TraceCollapsible>
</Trace>
<ChatMarkdown v-if="row.step.model.text" :text="withClip(row.step.model.text, row.step.model.text_bytes)" />
<Trace>
<TraceLine :status="row.step.model.error ? 'error' : undefined">
<TraceIcon><CircleAlertIcon v-if="row.step.model.error" /><SparklesIcon v-else /></TraceIcon>
<TraceTitle>{{ row.step.model.error ? errors.workflows.transcript.stepFailed(row.number, row.step.model.error) : `Step ${row.number}` }}</TraceTitle>
<TraceDescription v-if="usage(row.step.model)">{{ usage(row.step.model) }}</TraceDescription>
</TraceLine>
<ToolView v-for="tool in row.step.tools" :key="tool.seq" :tool="tool" :view="toolView(tool)" />
</Trace>
</MessageContent>
</Message>
</template>
</div>
</DefineConversation>
<p v-if="failed" role="alert" class="text-danger">{{ errors.workflows.transcript.notLoaded }}</p>
<Spinner v-else-if="!events" />
<Empty v-else-if="!conversations.length"><EmptyHeader><EmptyTitle>No transcript recorded</EmptyTitle></EmptyHeader></Empty>
<ConversationView v-else-if="conversations.length === 1" :conversation="conversations[0]!" />
<Trace v-else>
<TraceCollapsible v-for="c in conversations" :key="c.key">
<TraceCollapsibleTrigger>
<TraceLine :status="c.failed ? 'error' : undefined">
<TraceIcon><BotIcon /></TraceIcon>
<TraceTitle class="font-mono">{{ c.label }}</TraceTitle>
<TraceDescription>{{ plural(c.steps, 'step') }} · {{ plural(c.tools, 'tool call') }}{{ c.failed ? `, ${c.failed} failed` : '' }}</TraceDescription>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent>
<ConversationView :conversation="c" />
</TraceCollapsibleContent>
</TraceCollapsible>
</Trace>
</template>