File size: 11,584 Bytes
7c5ed63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import { useVirtualizer } from '@tanstack/react-virtual';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';

import { useSession } from '../../hooks/useSession';
import { useWire } from '../../hooks/useWire';
import { computeIssues, topSeverity } from '../../lib/issues';
import type { AgentRecord, WireEntry } from '../../types';
import { IssuesDrawer } from './IssuesDrawer';
import { WireRow, type PairHint } from './WireRow';

interface PairRecord {
  callLineNo: number | null;
  resultLineNo: number | null;
  callTime: number | null;
  resultTime: number | null;
}

/** Scan all entries and pair every `tool.call` with its `tool.result`
 *  by `toolCallId`. Used to render the inline "→ #N" / "← #N" cross-
 *  references, the call→result duration, and to drive the hover-pair
 *  highlight. */
function computePairMap(entries: readonly WireEntry[]): Map<string, PairRecord> {
  const map = new Map<string, PairRecord>();
  const ensure = (id: string): PairRecord => {
    const existing = map.get(id);
    if (existing) return existing;
    const fresh: PairRecord = { callLineNo: null, resultLineNo: null, callTime: null, resultTime: null };
    map.set(id, fresh);
    return fresh;
  };
  for (const entry of entries) {
    if (entry.data.type !== 'context.append_loop_event') continue;
    const ev = entry.data.event;
    const time = entry.data.time ?? null;
    if (ev.type === 'tool.call') {
      const rec = ensure(ev.toolCallId);
      rec.callLineNo = entry.lineNo;
      rec.callTime = time;
    } else if (ev.type === 'tool.result') {
      const rec = ensure(ev.toolCallId);
      rec.resultLineNo = entry.lineNo;
      rec.resultTime = time;
    }
  }
  return map;
}

function pairInfoFor(record: AgentRecord, map: Map<string, PairRecord>): PairHint | undefined {
  if (record.type !== 'context.append_loop_event') return undefined;
  const ev = record.event;
  if (ev.type !== 'tool.call' && ev.type !== 'tool.result') return undefined;
  const entry = map.get(ev.toolCallId);
  if (entry === undefined) return undefined;
  const durationMs =
    entry.callTime !== null && entry.resultTime !== null ? entry.resultTime - entry.callTime : null;
  return {
    toolCallId: ev.toolCallId,
    kind: ev.type === 'tool.call' ? 'call' : 'result',
    callLineNo: entry.callLineNo,
    resultLineNo: entry.resultLineNo,
    durationMs,
  };
}

interface WireTabProps {
  sessionId: string;
  /** Override starting agentId; defaults to 'main'. */
  initialAgentId?: string;
}

export function WireTab({ sessionId, initialAgentId = 'main' }: WireTabProps) {
  const [agentId, setAgentId] = useState<string>(initialAgentId);
  // Re-sync when the route changes either the session or the agent id
  // while this component stays mounted. Without `sessionId` in the deps,
  // navigating /sessions/A → /sessions/B (with default initialAgentId)
  // would preserve a subagent selection from the previous session and
  // 404 on the new one.
  useEffect(() => {
    setAgentId(initialAgentId);
  }, [sessionId, initialAgentId]);
  const { data: detail } = useSession(sessionId);
  const { data: wire, isLoading, error } = useWire(sessionId, agentId);
  const parentRef = useRef<HTMLDivElement>(null);

  const [search, setSearch] = useState('');
  const [expanded, setExpanded] = useState<Set<number>>(new Set());
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [hoveredPairId, setHoveredPairId] = useState<string | null>(null);

  const entries: WireEntry[] = useMemo(() => {
    return (wire?.records ?? []) as WireEntry[];
  }, [wire?.records]);
  const warnings = wire?.warnings ?? [];

  const pairMap = useMemo(() => computePairMap(entries), [entries]);
  // Precompute the per-entry PairHint so the object identity is stable
  // across hover state changes. Without this, every hover would create
  // fresh pair objects and bust WireRow's memo for every tool row.
  const pairByLineNo = useMemo(() => {
    const m = new Map<number, PairHint>();
    for (const entry of entries) {
      const p = pairInfoFor(entry.data, pairMap);
      if (p !== undefined) m.set(entry.lineNo, p);
    }
    return m;
  }, [entries, pairMap]);
  const onHoverPair = useCallback((id: string | null) => {
    setHoveredPairId(id);
  }, []);

  const filtered = useMemo(() => {
    if (search.length === 0) return entries;
    const needle = search.toLowerCase();
    return entries.filter((e) => {
      if (e.data.type.toLowerCase().includes(needle)) return true;
      try {
        return JSON.stringify(e.data).toLowerCase().includes(needle);
      } catch {
        return false;
      }
    });
  }, [entries, search]);

  const issues = useMemo(() => computeIssues(entries, warnings), [entries, warnings]);
  const issuesSeverity = topSeverity(issues);

  const virt = useVirtualizer({
    count: filtered.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 28,
    overscan: 10,
    getItemKey: (i) => filtered[i]?.lineNo ?? i,
  });

  const toggle = useCallback((lineNo: number) => {
    setExpanded((prev) => {
      const next = new Set(prev);
      if (next.has(lineNo)) next.delete(lineNo);
      else next.add(lineNo);
      return next;
    });
  }, []);

  const filteredLineIdx = useMemo(() => {
    const m = new Map<number, number>();
    for (let i = 0; i < filtered.length; i += 1) {
      const e = filtered[i];
      if (e !== undefined) m.set(e.lineNo, i);
    }
    return m;
  }, [filtered]);

  const jumpToLine = useCallback(
    (lineNo: number) => {
      const idx = filteredLineIdx.get(lineNo);
      if (idx === undefined) return;
      virt.scrollToIndex(idx, { align: 'center' });
      setExpanded((prev) => (prev.has(lineNo) ? prev : new Set(prev).add(lineNo)));
    },
    [filteredLineIdx, virt],
  );

  const expandAll = () => {
    setExpanded(new Set(filtered.map((e) => e.lineNo)));
  };
  const collapseAll = () => {
    setExpanded(new Set());
  };

  const agents = detail?.agents ?? [];

  return (
    <div className="relative flex min-h-0 flex-1 flex-col">
      {/* Toolbar */}
      <div className="flex shrink-0 items-center gap-3 border-b border-border bg-surface-1 px-3 py-2">
        <label className="flex items-center gap-2 font-mono text-[11px] text-fg-2">
          <span className="text-fg-3">agent</span>
          <select
            value={agentId}
            onChange={(e) => {
              setAgentId(e.target.value);
            }}
            className="border border-border bg-surface-0 px-2 py-1 font-mono text-[12px] text-fg-0 focus:border-border-strong focus:outline-none"
          >
            {agents.length === 0 ? <option value={agentId}>{agentId}</option> : null}
            {agents.map((a) => (
              <option key={a.agentId} value={a.agentId}>
                {a.agentId} ({a.type}
                {a.profileName ? ` · ${a.profileName}` : ''}
                {a.parentAgentId ? ` ← ${a.parentAgentId}` : ''})
              </option>
            ))}
          </select>
        </label>
        <input
          type="text"
          placeholder="search records (substring)"
          value={search}
          onChange={(e) => {
            setSearch(e.target.value);
          }}
          className="w-80 border border-border bg-surface-0 px-2 py-1 font-mono text-[12px] text-fg-0 placeholder:text-fg-3 focus:border-border-strong focus:outline-none"
        />
        <div className="ml-auto flex items-center gap-3 font-mono text-[11px] text-fg-2">
          <span className="tabular">
            {filtered.length} / {entries.length} ev
          </span>
          {issues.length > 0 && issuesSeverity !== null ? (
            <button
              onClick={() => {
                setDrawerOpen(true);
              }}
              title={`${issues.length} issue${issues.length > 1 ? 's' : ''} — click to inspect`}
              className="flex items-center gap-1 border px-2 py-0.5"
              style={{
                borderColor: `var(--color-sev-${issuesSeverity})`,
                color: `var(--color-sev-${issuesSeverity})`,
                backgroundColor: `color-mix(in oklab, var(--color-sev-${issuesSeverity}) 10%, transparent)`,
              }}
            >
              <span>
                {issuesSeverity === 'error' ? '⚠' : issuesSeverity === 'warning' ? '⚠' : 'ℹ'}
              </span>
              <span className="tabular">{issues.length}</span>
            </button>
          ) : null}
          <button
            onClick={expandAll}
            className="border border-border px-2 py-0.5 text-fg-2 hover:border-border-strong hover:text-fg-0"
          >
            expand all
          </button>
          <button
            onClick={collapseAll}
            className="border border-border px-2 py-0.5 text-fg-2 hover:border-border-strong hover:text-fg-0"
          >
            collapse
          </button>
        </div>
      </div>

      {warnings.length > 0 ? (
        <div className="shrink-0 border-b border-[var(--color-sev-warning)] bg-[color-mix(in_oklab,var(--color-sev-warning)_8%,transparent)] px-3 py-1 font-mono text-[11px] text-[var(--color-sev-warning)]">
          {warnings.length} warning{warnings.length > 1 ? 's' : ''} · first: {warnings[0]}
        </div>
      ) : null}

      {isLoading ? (
        <div className="p-6 font-mono text-[12px] text-fg-3">loading wire…</div>
      ) : error ? (
        <div className="p-6 font-mono text-[12px] text-[var(--color-sev-error)]">
          {(error as Error).message}
        </div>
      ) : (
        <div ref={parentRef} className="min-h-0 flex-1 overflow-y-auto">
          {filtered.length === 0 ? (
            <div className="p-6 font-mono text-[12px] text-fg-3">
              no records match the current filter
            </div>
          ) : (
            <div
              style={{
                height: virt.getTotalSize(),
                position: 'relative',
              }}
            >
              {virt.getVirtualItems().map((vi) => {
                const e = filtered[vi.index];
                if (!e) return null;
                const pair = pairByLineNo.get(e.lineNo);
                const highlighted =
                  pair !== undefined && hoveredPairId === pair.toolCallId;
                return (
                  <div
                    key={vi.key}
                    data-index={vi.index}
                    ref={virt.measureElement}
                    style={{
                      position: 'absolute',
                      top: 0,
                      left: 0,
                      width: '100%',
                      transform: `translateY(${vi.start}px)`,
                    }}
                  >
                    <WireRow
                      entry={e}
                      expanded={expanded.has(e.lineNo)}
                      onToggle={() => {
                        toggle(e.lineNo);
                      }}
                      onJumpTo={jumpToLine}
                      pair={pair}
                      highlighted={highlighted}
                      onHoverPair={onHoverPair}
                    />
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}

      {drawerOpen ? (
        <IssuesDrawer
          issues={issues}
          onClose={() => {
            setDrawerOpen(false);
          }}
          onJumpTo={jumpToLine}
          isLineVisible={(lineNo) => filteredLineIdx.has(lineNo)}
        />
      ) : null}
    </div>
  );
}