feat(v2): add agent tree, status bar, notifications, settings dialog (Phase 5)

Agent tree visualization (SVG) with horizontal layout and bezier edges.
Global status bar with pane counts, active agents pulse, token/cost totals.
Toast notification system with auto-dismiss and agent dispatcher integration.
Settings dialog with SQLite persistence for shell, cwd, and max panes.
Keyboard shortcuts: Ctrl+W close pane, Ctrl+, open settings.
This commit is contained in:
Hibryda 2026-03-06 13:46:21 +01:00
parent cd1271adf0
commit be24d07c65
13 changed files with 809 additions and 2 deletions

View file

@ -132,6 +132,23 @@ fn layout_load(state: State<'_, AppState>) -> Result<LayoutState, String> {
state.session_db.load_layout()
}
// --- Settings commands ---
#[tauri::command]
fn settings_get(state: State<'_, AppState>, key: String) -> Result<Option<String>, String> {
state.session_db.get_setting(&key)
}
#[tauri::command]
fn settings_set(state: State<'_, AppState>, key: String, value: String) -> Result<(), String> {
state.session_db.set_setting(&key, &value)
}
#[tauri::command]
fn settings_list(state: State<'_, AppState>) -> Result<Vec<(String, String)>, String> {
state.session_db.get_all_settings()
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
let pty_manager = Arc::new(PtyManager::new());
@ -175,6 +192,9 @@ pub fn run() {
session_touch,
layout_save,
layout_load,
settings_get,
settings_set,
settings_list,
])
.setup(move |app| {
if cfg!(debug_assertions) {

View file

@ -68,11 +68,51 @@ impl SessionDb {
);
INSERT OR IGNORE INTO layout_state (id, preset, pane_ids) VALUES (1, '1-col', '[]');
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
"
).map_err(|e| format!("Migration failed: {e}"))?;
Ok(())
}
pub fn get_setting(&self, key: &str) -> Result<Option<String>, String> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn
.prepare("SELECT value FROM settings WHERE key = ?1")
.map_err(|e| format!("Settings query failed: {e}"))?;
let result = stmt.query_row(params![key], |row| row.get(0));
match result {
Ok(val) => Ok(Some(val)),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(e) => Err(format!("Settings read failed: {e}")),
}
}
pub fn set_setting(&self, key: &str, value: &str) -> Result<(), String> {
let conn = self.conn.lock().unwrap();
conn.execute(
"INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)",
params![key, value],
).map_err(|e| format!("Settings write failed: {e}"))?;
Ok(())
}
pub fn get_all_settings(&self) -> Result<Vec<(String, String)>, String> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn
.prepare("SELECT key, value FROM settings ORDER BY key")
.map_err(|e| format!("Settings query failed: {e}"))?;
let settings = stmt
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
.map_err(|e| format!("Settings query failed: {e}"))?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| format!("Settings read failed: {e}"))?;
Ok(settings)
}
pub fn list_sessions(&self) -> Result<Vec<Session>, String> {
let conn = self.conn.lock().unwrap();
let mut stmt = conn

View file

@ -2,7 +2,12 @@
import { onMount, onDestroy } from 'svelte';
import SessionList from './lib/components/Sidebar/SessionList.svelte';
import TilingGrid from './lib/components/Layout/TilingGrid.svelte';
import { addPane, focusPaneByIndex, getPanes, restoreFromDb } from './lib/stores/layout.svelte';
import StatusBar from './lib/components/StatusBar/StatusBar.svelte';
import ToastContainer from './lib/components/Notifications/ToastContainer.svelte';
import SettingsDialog from './lib/components/Settings/SettingsDialog.svelte';
import { addPane, focusPaneByIndex, removePane, getPanes, restoreFromDb } from './lib/stores/layout.svelte';
let settingsOpen = $state(false);
import { startAgentDispatcher, stopAgentDispatcher } from './lib/agent-dispatcher';
function newTerminal() {
@ -50,6 +55,21 @@
focusPaneByIndex(parseInt(e.key) - 1);
return;
}
// Ctrl+, — settings
if (e.ctrlKey && e.key === ',') {
e.preventDefault();
settingsOpen = !settingsOpen;
return;
}
// Ctrl+W — close focused pane
if (e.ctrlKey && !e.shiftKey && e.key === 'w') {
e.preventDefault();
const focused = getPanes().find(p => p.focused);
if (focused) removePane(focused.id);
return;
}
}
window.addEventListener('keydown', handleKeydown);
@ -66,6 +86,9 @@
<main class="workspace">
<TilingGrid />
</main>
<StatusBar />
<ToastContainer />
<SettingsDialog open={settingsOpen} onClose={() => settingsOpen = false} />
<style>
.sidebar {

View file

@ -25,7 +25,7 @@ html, body {
width: 100%;
display: grid;
grid-template-columns: var(--sidebar-width) 1fr;
grid-template-rows: 1fr;
grid-template-rows: 1fr auto;
}
/* Ultrawide: show right panel */

View file

@ -0,0 +1,13 @@
import { invoke } from '@tauri-apps/api/core';
export async function getSetting(key: string): Promise<string | null> {
return invoke('settings_get', { key });
}
export async function setSetting(key: string, value: string): Promise<void> {
return invoke('settings_set', { key, value });
}
export async function listSettings(): Promise<[string, string][]> {
return invoke('settings_list');
}

View file

@ -12,6 +12,7 @@ import {
updateAgentCost,
getAgentSessions,
} from './stores/agents.svelte';
import { notify } from './stores/notifications.svelte';
let unlistenMsg: (() => void) | null = null;
let unlistenExit: (() => void) | null = null;
@ -47,10 +48,12 @@ export async function startAgentDispatcher(): Promise<void> {
case 'agent_stopped':
updateAgentStatus(sessionId, 'done');
notify('success', `Agent ${sessionId.slice(0, 8)} completed`);
break;
case 'agent_error':
updateAgentStatus(sessionId, 'error', msg.message);
notify('error', `Agent error: ${msg.message ?? 'Unknown'}`);
break;
case 'agent_log':
@ -60,6 +63,7 @@ export async function startAgentDispatcher(): Promise<void> {
unlistenExit = await onSidecarExited(() => {
sidecarAlive = false;
notify('error', 'Sidecar process crashed — agent features unavailable');
// Mark all running sessions as errored
for (const session of getAgentSessions()) {
if (session.status === 'running' || session.status === 'starting') {
@ -92,8 +96,10 @@ function handleAgentEvent(sessionId: string, event: Record<string, unknown>): vo
});
if (cost.isError) {
updateAgentStatus(sessionId, 'error', cost.errors?.join('; '));
notify('error', `Agent failed: ${cost.errors?.[0] ?? 'Unknown error'}`);
} else {
updateAgentStatus(sessionId, 'done');
notify('success', `Agent done — $${cost.totalCostUsd.toFixed(4)}, ${cost.numTurns} turns`);
}
break;
}

View file

@ -8,6 +8,7 @@
type AgentSession,
} from '../../stores/agents.svelte';
import { isSidecarAlive, setSidecarAlive } from '../../agent-dispatcher';
import AgentTree from './AgentTree.svelte';
import type {
AgentMessage,
TextContent,
@ -32,6 +33,8 @@
let scrollContainer: HTMLDivElement | undefined = $state();
let autoScroll = $state(true);
let restarting = $state(false);
let showTree = $state(false);
let hasToolCalls = $derived(session?.messages.some(m => m.type === 'tool_call') ?? false);
onMount(async () => {
if (initialPrompt) {
@ -142,6 +145,16 @@
</form>
</div>
{:else}
{#if hasToolCalls}
<div class="tree-toggle">
<button class="tree-btn" onclick={() => showTree = !showTree}>
{showTree ? '▼' : '▶'} Agent Tree
</button>
</div>
{#if showTree && session}
<AgentTree {session} />
{/if}
{/if}
<div class="messages" bind:this={scrollContainer} onscroll={handleScroll}>
{#each session.messages as msg (msg.id)}
<div class="message msg-{msg.type}">
@ -229,6 +242,24 @@
font-size: 13px;
}
.tree-toggle {
padding: 4px 12px;
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.tree-btn {
background: none;
border: none;
color: var(--ctp-mauve);
font-size: 11px;
cursor: pointer;
font-family: var(--font-mono);
padding: 2px 4px;
}
.tree-btn:hover { color: var(--text-primary); }
.prompt-area {
display: flex;
align-items: center;

View file

@ -0,0 +1,162 @@
<script lang="ts">
import { buildAgentTree, type AgentTreeNode } from '../../utils/agent-tree';
import type { AgentSession } from '../../stores/agents.svelte';
interface Props {
session: AgentSession;
onNodeClick?: (nodeId: string) => void;
}
let { session, onNodeClick }: Props = $props();
let tree = $derived(buildAgentTree(
session.id,
session.messages,
session.status,
session.costUsd,
session.inputTokens + session.outputTokens,
));
// Layout constants
const NODE_W = 100;
const NODE_H = 32;
const H_GAP = 24;
const V_GAP = 12;
interface LayoutNode {
node: AgentTreeNode;
x: number;
y: number;
children: LayoutNode[];
}
function layoutTree(node: AgentTreeNode, x: number, y: number): { layout: LayoutNode; height: number } {
if (node.children.length === 0) {
return {
layout: { node, x, y, children: [] },
height: NODE_H,
};
}
const childLayouts: LayoutNode[] = [];
let childY = y;
let totalHeight = 0;
for (const child of node.children) {
const result = layoutTree(child, x + NODE_W + H_GAP, childY);
childLayouts.push(result.layout);
childY += result.height + V_GAP;
totalHeight += result.height + V_GAP;
}
totalHeight -= V_GAP; // remove trailing gap
// Center parent vertically relative to children
const parentY = childLayouts.length > 0
? (childLayouts[0].y + childLayouts[childLayouts.length - 1].y) / 2
: y;
return {
layout: { node, x, y: parentY, children: childLayouts },
height: Math.max(NODE_H, totalHeight),
};
}
let layoutResult = $derived(layoutTree(tree, 8, 8));
let svgHeight = $derived(Math.max(80, layoutResult.height + 24));
let svgWidth = $derived(computeWidth(layoutResult.layout));
function computeWidth(layout: LayoutNode): number {
let maxX = layout.x + NODE_W;
for (const child of layout.children) {
maxX = Math.max(maxX, computeWidth(child));
}
return maxX + 16;
}
function statusColor(status: string): string {
switch (status) {
case 'running': return 'var(--ctp-blue)';
case 'done': return 'var(--ctp-green)';
case 'error': return 'var(--ctp-red)';
default: return 'var(--ctp-overlay1)';
}
}
function truncateLabel(text: string, maxLen: number): string {
return text.length > maxLen ? text.slice(0, maxLen - 1) + '…' : text;
}
</script>
<div class="agent-tree">
<svg width={svgWidth} height={svgHeight}>
{#snippet renderNode(layout: LayoutNode)}
<!-- Edges to children -->
{#each layout.children as child}
<path
d="M {layout.x + NODE_W} {layout.y + NODE_H / 2}
C {layout.x + NODE_W + H_GAP / 2} {layout.y + NODE_H / 2},
{child.x - H_GAP / 2} {child.y + NODE_H / 2},
{child.x} {child.y + NODE_H / 2}"
fill="none"
stroke="var(--border)"
stroke-width="1.5"
/>
{/each}
<!-- Node rectangle -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<!-- svelte-ignore a11y_no_static_element_interactions -->
<g
class="tree-node"
onclick={() => onNodeClick?.(layout.node.id)}
style="cursor: {onNodeClick ? 'pointer' : 'default'}"
>
<rect
x={layout.x}
y={layout.y}
width={NODE_W}
height={NODE_H}
rx="4"
fill="var(--bg-surface)"
stroke={statusColor(layout.node.status)}
stroke-width="1.5"
/>
<!-- Status dot -->
<circle
cx={layout.x + 10}
cy={layout.y + NODE_H / 2}
r="3"
fill={statusColor(layout.node.status)}
/>
<!-- Label -->
<text
x={layout.x + 18}
y={layout.y + NODE_H / 2 + 1}
fill="var(--text-primary)"
font-size="10"
font-family="var(--font-mono)"
dominant-baseline="middle"
>{truncateLabel(layout.node.label, 10)}</text>
</g>
<!-- Recurse children -->
{#each layout.children as child}
{@render renderNode(child)}
{/each}
{/snippet}
{@render renderNode(layoutResult.layout)}
</svg>
</div>
<style>
.agent-tree {
overflow: auto;
padding: 4px;
background: var(--bg-primary);
}
.tree-node:hover rect {
fill: var(--bg-surface-hover, var(--ctp-surface1));
}
</style>

View file

@ -0,0 +1,94 @@
<script lang="ts">
import { getNotifications, dismissNotification } from '../../stores/notifications.svelte';
let toasts = $derived(getNotifications());
</script>
{#if toasts.length > 0}
<div class="toast-container">
{#each toasts as toast (toast.id)}
<div class="toast toast-{toast.type}" role="alert">
<span class="toast-icon">
{#if toast.type === 'success'}
{:else if toast.type === 'error'}
{:else if toast.type === 'warning'}!
{:else}i
{/if}
</span>
<span class="toast-message">{toast.message}</span>
<button class="toast-close" onclick={() => dismissNotification(toast.id)}>&times;</button>
</div>
{/each}
</div>
{/if}
<style>
.toast-container {
position: fixed;
top: 12px;
right: 12px;
z-index: 9999;
display: flex;
flex-direction: column;
gap: 6px;
max-width: 360px;
}
.toast {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
border-radius: var(--border-radius);
font-size: 12px;
color: var(--text-primary);
background: var(--bg-surface);
border: 1px solid var(--border);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
animation: slide-in 0.2s ease-out;
}
@keyframes slide-in {
from { opacity: 0; transform: translateX(20px); }
to { opacity: 1; transform: translateX(0); }
}
.toast-icon {
width: 18px;
height: 18px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 10px;
font-weight: 700;
flex-shrink: 0;
}
.toast-success .toast-icon { background: var(--ctp-green); color: var(--ctp-crust); }
.toast-error .toast-icon { background: var(--ctp-red); color: var(--ctp-crust); }
.toast-warning .toast-icon { background: var(--ctp-yellow); color: var(--ctp-crust); }
.toast-info .toast-icon { background: var(--ctp-blue); color: var(--ctp-crust); }
.toast-success { border-color: color-mix(in srgb, var(--ctp-green) 30%, transparent); }
.toast-error { border-color: color-mix(in srgb, var(--ctp-red) 30%, transparent); }
.toast-warning { border-color: color-mix(in srgb, var(--ctp-yellow) 30%, transparent); }
.toast-info { border-color: color-mix(in srgb, var(--ctp-blue) 30%, transparent); }
.toast-message {
flex: 1;
line-height: 1.3;
}
.toast-close {
background: none;
border: none;
color: var(--text-muted);
cursor: pointer;
font-size: 14px;
padding: 0 2px;
flex-shrink: 0;
}
.toast-close:hover { color: var(--text-primary); }
</style>

View file

@ -0,0 +1,199 @@
<script lang="ts">
import { onMount } from 'svelte';
import { getSetting, setSetting } from '../../adapters/settings-bridge';
import { notify } from '../../stores/notifications.svelte';
interface Props {
open: boolean;
onClose: () => void;
}
let { open, onClose }: Props = $props();
let defaultShell = $state('');
let defaultCwd = $state('');
let maxPanes = $state('4');
onMount(async () => {
try {
defaultShell = (await getSetting('default_shell')) ?? '';
defaultCwd = (await getSetting('default_cwd')) ?? '';
maxPanes = (await getSetting('max_panes')) ?? '4';
} catch {
// Use defaults
}
});
async function handleSave() {
try {
if (defaultShell) await setSetting('default_shell', defaultShell);
if (defaultCwd) await setSetting('default_cwd', defaultCwd);
await setSetting('max_panes', maxPanes);
notify('success', 'Settings saved');
onClose();
} catch (e) {
notify('error', `Failed to save settings: ${e}`);
}
}
function handleKeydown(e: KeyboardEvent) {
if (e.key === 'Escape') onClose();
}
</script>
{#if open}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="overlay" onkeydown={handleKeydown}>
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div class="backdrop" onclick={onClose}></div>
<div class="dialog" role="dialog" aria-label="Settings">
<div class="dialog-header">
<h2>Settings</h2>
<button class="close-btn" onclick={onClose}>&times;</button>
</div>
<div class="dialog-body">
<label class="field">
<span class="field-label">Default Shell</span>
<input type="text" bind:value={defaultShell} placeholder="$SHELL (auto-detect)" />
<span class="field-hint">Leave empty to use system default</span>
</label>
<label class="field">
<span class="field-label">Default Working Directory</span>
<input type="text" bind:value={defaultCwd} placeholder="$HOME" />
<span class="field-hint">Leave empty for home directory</span>
</label>
<label class="field">
<span class="field-label">Max Panes</span>
<input type="number" bind:value={maxPanes} min="1" max="8" />
<span class="field-hint">Maximum simultaneous panes (1-8)</span>
</label>
</div>
<div class="dialog-footer">
<button class="btn-cancel" onclick={onClose}>Cancel</button>
<button class="btn-save" onclick={handleSave}>Save</button>
</div>
</div>
</div>
{/if}
<style>
.overlay {
position: fixed;
inset: 0;
z-index: 9000;
display: flex;
align-items: center;
justify-content: center;
}
.backdrop {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.5);
}
.dialog {
position: relative;
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 8px;
width: 400px;
max-height: 80vh;
overflow-y: auto;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
}
.dialog-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 16px;
border-bottom: 1px solid var(--border);
}
.dialog-header h2 {
font-size: 14px;
font-weight: 600;
color: var(--text-primary);
}
.close-btn {
background: none;
border: none;
color: var(--text-muted);
font-size: 18px;
cursor: pointer;
}
.close-btn:hover { color: var(--text-primary); }
.dialog-body {
padding: 16px;
display: flex;
flex-direction: column;
gap: 14px;
}
.field {
display: flex;
flex-direction: column;
gap: 4px;
}
.field-label {
font-size: 12px;
font-weight: 600;
color: var(--text-secondary);
}
.field input {
background: var(--bg-surface);
border: 1px solid var(--border);
border-radius: var(--border-radius);
color: var(--text-primary);
font-family: var(--font-mono);
font-size: 12px;
padding: 6px 8px;
}
.field input:focus {
outline: none;
border-color: var(--accent);
}
.field-hint {
font-size: 10px;
color: var(--text-muted);
}
.dialog-footer {
display: flex;
justify-content: flex-end;
gap: 8px;
padding: 12px 16px;
border-top: 1px solid var(--border);
}
.btn-cancel, .btn-save {
border: none;
border-radius: var(--border-radius);
padding: 6px 14px;
font-size: 12px;
font-weight: 600;
cursor: pointer;
}
.btn-cancel {
background: var(--bg-surface);
color: var(--text-secondary);
}
.btn-cancel:hover { color: var(--text-primary); }
.btn-save {
background: var(--accent);
color: var(--ctp-crust);
}
.btn-save:hover { opacity: 0.9; }
</style>

View file

@ -0,0 +1,95 @@
<script lang="ts">
import { getPanes } from '../../stores/layout.svelte';
import { getAgentSessions } from '../../stores/agents.svelte';
let panes = $derived(getPanes());
let agentSessions = $derived(getAgentSessions());
let activeAgents = $derived(agentSessions.filter(s => s.status === 'running' || s.status === 'starting').length);
let totalCost = $derived(agentSessions.reduce((sum, s) => sum + s.costUsd, 0));
let totalTokens = $derived(agentSessions.reduce((sum, s) => sum + s.inputTokens + s.outputTokens, 0));
let terminalCount = $derived(panes.filter(p => p.type === 'terminal').length);
let agentCount = $derived(panes.filter(p => p.type === 'agent').length);
</script>
<div class="status-bar">
<div class="left">
<span class="item" title="Terminal panes">{terminalCount} terminals</span>
<span class="sep"></span>
<span class="item" title="Agent panes">{agentCount} agents</span>
{#if activeAgents > 0}
<span class="sep"></span>
<span class="item active">
<span class="pulse"></span>
{activeAgents} running
</span>
{/if}
</div>
<div class="right">
{#if totalTokens > 0}
<span class="item tokens">{totalTokens.toLocaleString()} tokens</span>
<span class="sep"></span>
{/if}
{#if totalCost > 0}
<span class="item cost">${totalCost.toFixed(4)}</span>
<span class="sep"></span>
{/if}
<span class="item version">BTerminal v2</span>
</div>
</div>
<style>
.status-bar {
grid-column: 1 / -1;
display: flex;
align-items: center;
justify-content: space-between;
height: 24px;
padding: 0 10px;
background: var(--bg-secondary);
border-top: 1px solid var(--border);
font-size: 11px;
color: var(--text-muted);
font-family: var(--font-mono);
user-select: none;
}
.left, .right {
display: flex;
align-items: center;
gap: 6px;
}
.sep {
width: 1px;
height: 10px;
background: var(--border);
}
.item {
display: flex;
align-items: center;
gap: 4px;
}
.active {
color: var(--ctp-blue);
}
.pulse {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--ctp-blue);
animation: pulse 1.5s ease-in-out infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.3; }
}
.tokens { color: var(--ctp-overlay1); }
.cost { color: var(--ctp-yellow); }
.version { color: var(--ctp-overlay0); }
</style>

View file

@ -0,0 +1,36 @@
// Notification store — ephemeral toast messages
export type NotificationType = 'info' | 'success' | 'warning' | 'error';
export interface Notification {
id: string;
type: NotificationType;
message: string;
timestamp: number;
}
let notifications = $state<Notification[]>([]);
const MAX_TOASTS = 5;
const TOAST_DURATION_MS = 4000;
export function getNotifications(): Notification[] {
return notifications;
}
export function notify(type: NotificationType, message: string): void {
const id = crypto.randomUUID();
notifications.push({ id, type, message, timestamp: Date.now() });
// Cap visible toasts
if (notifications.length > MAX_TOASTS) {
notifications = notifications.slice(-MAX_TOASTS);
}
// Auto-dismiss
setTimeout(() => dismissNotification(id), TOAST_DURATION_MS);
}
export function dismissNotification(id: string): void {
notifications = notifications.filter(n => n.id !== id);
}

View file

@ -0,0 +1,88 @@
// Agent tree builder — constructs hierarchical tree from agent messages
// Subagents are identified by parent_tool_use_id on their messages
import type { AgentMessage, ToolCallContent, CostContent } from '../adapters/sdk-messages';
export interface AgentTreeNode {
id: string;
label: string;
toolName?: string;
status: 'running' | 'done' | 'error';
costUsd: number;
tokens: number;
children: AgentTreeNode[];
}
/**
* Build a tree from a flat list of agent messages.
* Root node represents the main agent session.
* Child nodes represent tool_use calls (potential subagents).
*/
export function buildAgentTree(
sessionId: string,
messages: AgentMessage[],
sessionStatus: string,
sessionCost: number,
sessionTokens: number,
): AgentTreeNode {
const root: AgentTreeNode = {
id: sessionId,
label: sessionId.slice(0, 8),
status: sessionStatus === 'running' || sessionStatus === 'starting' ? 'running' :
sessionStatus === 'error' ? 'error' : 'done',
costUsd: sessionCost,
tokens: sessionTokens,
children: [],
};
// Map tool_use_id -> node for nesting
const toolNodes = new Map<string, AgentTreeNode>();
for (const msg of messages) {
if (msg.type === 'tool_call') {
const tc = msg.content as ToolCallContent;
const node: AgentTreeNode = {
id: tc.toolUseId,
label: tc.name,
toolName: tc.name,
status: 'running', // will be updated by result
costUsd: 0,
tokens: 0,
children: [],
};
toolNodes.set(tc.toolUseId, node);
if (msg.parentId) {
// This is a subagent tool call — attach to parent tool node
const parent = toolNodes.get(msg.parentId);
if (parent) {
parent.children.push(node);
} else {
root.children.push(node);
}
} else {
root.children.push(node);
}
}
if (msg.type === 'tool_result') {
const tr = msg.content as { toolUseId: string };
const node = toolNodes.get(tr.toolUseId);
if (node) {
node.status = 'done';
}
}
}
return root;
}
/** Flatten tree to get total count of nodes */
export function countTreeNodes(node: AgentTreeNode): number {
return 1 + node.children.reduce((sum, c) => sum + countTreeNodes(c), 0);
}
/** Aggregate cost across a subtree */
export function subtreeCost(node: AgentTreeNode): number {
return node.costUsd + node.children.reduce((sum, c) => sum + subtreeCost(c), 0);
}