@surfaces-ui/devtools 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/Panel.js ADDED
@@ -0,0 +1,434 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { CodeBlock, ControlIcon, DataSourceProvider, DiscoveryProvider, PipelinesProvider, SemanticsProvider, Workspace } from "@surfaces-ui/components";
3
+ import { analyticsCatalog, resolve, surfaceOutline } from "@surfaces-ui/spec";
4
+ import { SurfaceView, lazyAnalyticsRenderers } from "@surfaces-ui/spec/react";
5
+ import { TRACE_KINDS, TRACE_STATUSES, isStep, plain, traceSteps } from "@surfaces-ui/trace";
6
+ import { TraceProvider } from "@surfaces-ui/trace/react";
7
+ import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
8
+ import { componentFindings } from "./cause.js";
9
+ import { surfaceStepDiff, surfacesAt, withControls } from "./replay.js";
10
+ import { PANEL_CSS, addStyles } from "./styles.js";
11
+ const KIND_NAME = { message: "Message", component: "Component", problem: "Problem", state: "State", event: "Event", agent: "Agent", service: "Service" };
12
+ const clock = (time) => {
13
+ const d = new Date(time);
14
+ const two = (n) => String(n).padStart(2, "0");
15
+ return `${two(d.getHours())}:${two(d.getMinutes())}:${two(d.getSeconds())}.${String(d.getMilliseconds()).padStart(3, "0")}`;
16
+ };
17
+ const took = (ms) => (ms === undefined ? "" : ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(ms < 10_000 ? 2 : 1)} s`);
18
+ const json = (value) => JSON.stringify(value ?? null, null, 2);
19
+ const short = (value, max = 90) => {
20
+ const text = typeof value === "string" ? value : JSON.stringify(value ?? null);
21
+ return text.length > max ? `${text.slice(0, max)}…` : text;
22
+ };
23
+ const record = (value) => (value !== null && typeof value === "object" && !Array.isArray(value) ? value : {});
24
+ const sqlOf = (event) => {
25
+ const query = record(record(event.detail.request).query);
26
+ return typeof query.baseSql === "string" ? query.baseSql : typeof record(event.detail.request).sql === "string" ? record(event.detail.request).sql : "";
27
+ };
28
+ /** A line about an event, for its row. */
29
+ function summary(event) {
30
+ const d = event.detail;
31
+ switch (event.kind) {
32
+ case "service": {
33
+ const response = record(d.response);
34
+ const error = record(d.error);
35
+ // A call its caller gave up on is not a failure: the component was redrawn, or asked for something else.
36
+ if (d.cancelled === true)
37
+ return ["given up before it answered", sqlOf(event).replace(/\s+/g, " ")].filter(Boolean).join(" · ");
38
+ if (typeof error.message === "string")
39
+ return error.message;
40
+ const rows = typeof response.rows === "number" ? `${response.rows} rows` : "";
41
+ return [rows, sqlOf(event).replace(/\s+/g, " ")].filter(Boolean).join(" · ");
42
+ }
43
+ case "message":
44
+ return [event.surfaceId, Array.isArray(d.issues) && d.issues.length > 0 ? `${d.issues.length} issues` : "", typeof record(d.error).message === "string" ? record(d.error).message : ""].filter(Boolean).join(" · ");
45
+ case "problem":
46
+ return [typeof d.path === "string" ? d.path : "", typeof d.message === "string" ? d.message : ""].filter(Boolean).join(" ");
47
+ case "event":
48
+ return [event.componentId, d.contract === "failed" ? "not sent: contract failed" : typeof d.summary === "string" ? d.summary : short(d.context ?? "", 60)].filter(Boolean).join(" · ");
49
+ case "agent": {
50
+ const input = record(record(d.request).input);
51
+ return typeof input.text === "string" ? input.text : typeof input.name === "string" ? `action ${input.name}` : "";
52
+ }
53
+ case "state":
54
+ return [event.componentId, typeof d.path === "string" ? `${d.path} = ${short(d.value, 40)}` : ""].filter(Boolean).join(" · ");
55
+ case "component":
56
+ return event.surfaceId ?? "";
57
+ }
58
+ }
59
+ /**
60
+ * A long list that draws only the rows in view. One tab stop: arrows, Home,
61
+ * End, Page Up and Page Down move the selection, which is followed into view.
62
+ */
63
+ function WindowList({ label, items, idOf, selected, onSelect, row, rowClass, className, rowProps, empty }) {
64
+ const ref = useRef(null);
65
+ const base = useId();
66
+ const [top, setTop] = useState(0);
67
+ const [view, setView] = useState({ height: 400, row: 28 });
68
+ useLayoutEffect(() => {
69
+ const el = ref.current;
70
+ if (!el)
71
+ return;
72
+ const measure = () => {
73
+ // A row is at least as tall as the smallest thing a person can press: 24px, 44px on a touch screen.
74
+ const target = parseFloat(getComputedStyle(el).getPropertyValue("--sf-target-min")) || 0;
75
+ setView((v) => {
76
+ const next = { height: el.clientHeight || 400, row: Math.max(28, target) };
77
+ return next.height === v.height && next.row === v.row ? v : next;
78
+ });
79
+ };
80
+ measure();
81
+ if (typeof ResizeObserver === "undefined")
82
+ return;
83
+ const watch = new ResizeObserver(measure);
84
+ watch.observe(el);
85
+ return () => watch.disconnect();
86
+ }, []);
87
+ const first = Math.max(0, Math.floor(top / view.row) - 4);
88
+ const last = Math.min(items.length, Math.ceil((top + view.height) / view.row) + 4);
89
+ const index = selected === undefined ? -1 : items.findIndex((item) => idOf(item) === selected);
90
+ const dom = (id) => `${base}-${id}`;
91
+ const go = (to) => {
92
+ const next = Math.max(0, Math.min(items.length - 1, to));
93
+ const item = items[next];
94
+ if (!item)
95
+ return;
96
+ onSelect(idOf(item));
97
+ const el = ref.current;
98
+ if (!el)
99
+ return;
100
+ if (next * view.row < el.scrollTop)
101
+ el.scrollTop = next * view.row;
102
+ else if ((next + 1) * view.row > el.scrollTop + view.height)
103
+ el.scrollTop = (next + 1) * view.row - view.height;
104
+ };
105
+ const onKeyDown = (event) => {
106
+ const page = Math.max(1, Math.floor(view.height / view.row) - 1);
107
+ const to = event.key === "ArrowDown" ? index + 1 : event.key === "ArrowUp" ? Math.max(0, index - 1) : event.key === "Home" ? 0 : event.key === "End" ? items.length - 1 : event.key === "PageDown" ? index + page : event.key === "PageUp" ? index - page : undefined;
108
+ if (to === undefined)
109
+ return;
110
+ event.preventDefault();
111
+ go(to);
112
+ };
113
+ if (items.length === 0)
114
+ return _jsx("p", { className: "sf-devtools-empty", children: empty });
115
+ return (_jsx("div", { ref: ref, role: "listbox", "aria-label": label, tabIndex: 0, "aria-activedescendant": index >= 0 ? dom(idOf(items[index])) : undefined, className: className, onScroll: (event) => setTop(event.currentTarget.scrollTop), onKeyDown: onKeyDown, children: _jsx("div", { role: "presentation", style: { height: items.length * view.row }, children: items.slice(first, last).map((item, offset) => {
116
+ const id = idOf(item);
117
+ return (_jsx("div", { id: dom(id), role: "option", "aria-selected": id === selected, className: rowClass, style: { top: (first + offset) * view.row, height: view.row }, onClick: () => onSelect(id), ...rowProps?.(item), children: row(item) }, id));
118
+ }) }) }));
119
+ }
120
+ function EventRows({ label, events, selected, onSelect, at, empty }) {
121
+ return (_jsx(WindowList, { label: label, items: events, idOf: (event) => event.id, selected: selected, onSelect: onSelect, className: "sf-devtools-rows", rowClass: "sf-devtools-row", empty: empty, rowProps: (event) => ({ "data-kind": event.kind, "data-later": at !== undefined && event.seq > at ? "" : undefined }), row: (event) => (_jsxs(_Fragment, { children: [_jsx("span", { className: "sf-devtools-time", children: clock(event.time) }), _jsx("span", { className: "sf-devtools-kind", children: KIND_NAME[event.kind] }), _jsxs("span", { className: "sf-devtools-name", children: [event.name, " ", _jsx("small", { children: summary(event) })] }), _jsx("span", { className: "sf-devtools-status", "data-status": event.detail.cancelled === true ? "cancelled" : event.status, children: event.detail.cancelled === true ? "cancelled" : event.status }), _jsx("span", { className: "sf-devtools-ms", children: took(event.durationMs) })] })) }));
122
+ }
123
+ function Facts({ event }) {
124
+ const facts = [
125
+ ["What", `${KIND_NAME[event.kind]}: ${event.name}`],
126
+ ["Status", event.status],
127
+ ["When", clock(event.time)],
128
+ ["Took", took(event.durationMs) || undefined],
129
+ ["Surface", event.surfaceId],
130
+ ["Component", event.componentId],
131
+ ["Trace", event.traceId],
132
+ ["Span", event.spanId],
133
+ ["Inside", event.parentId],
134
+ ];
135
+ return (_jsx("dl", { className: "sf-devtools-facts", children: facts.map(([name, value]) => value ? (_jsxs("div", { style: { display: "contents" }, children: [_jsx("dt", { children: name }), _jsx("dd", { children: value })] }, name)) : null) }));
136
+ }
137
+ /** Text sent to an agent, read a line at a time: runs of "- " lines are a list, a line of JSON is data, the rest is prose. */
138
+ export function saidBlocks(text) {
139
+ const blocks = [];
140
+ for (const line of text.split("\n")) {
141
+ const last = blocks.at(-1);
142
+ const trimmed = line.trim();
143
+ if (/^[-*•] /.test(trimmed)) {
144
+ if (last?.kind === "list")
145
+ last.items.push(trimmed.slice(2));
146
+ else
147
+ blocks.push({ kind: "list", items: [trimmed.slice(2)] });
148
+ }
149
+ else if (trimmed.length > 40 && /^[[{]/.test(trimmed)) {
150
+ let code = trimmed;
151
+ try {
152
+ code = JSON.stringify(JSON.parse(trimmed), null, 2);
153
+ }
154
+ catch {
155
+ // Cut short when it was recorded, or not JSON after all: shown as it is.
156
+ }
157
+ blocks.push({ kind: "json", code });
158
+ }
159
+ else if (trimmed === "") {
160
+ if (last?.kind === "text" && last.lines.length > 0)
161
+ blocks.push({ kind: "text", lines: [] });
162
+ }
163
+ else if (last?.kind === "text")
164
+ last.lines.push(line);
165
+ else
166
+ blocks.push({ kind: "text", lines: [line] });
167
+ }
168
+ return blocks.filter((block) => block.kind !== "text" || block.lines.length > 0);
169
+ }
170
+ const LABEL = /^([A-Z][A-Za-z ]{1,28}):(\s|$)/;
171
+ const LONG_LIST = 4;
172
+ /**
173
+ * What was said to an agent, laid out to be read: prose as paragraphs with a leading "Label:" marked, a list as a
174
+ * list, and data as highlighted JSON. A long list and data start folded, so the words a person wrote are not lost
175
+ * among the context sent with them. Everything is text: nothing in it is run or drawn as markup.
176
+ */
177
+ function Said({ text }) {
178
+ const blocks = saidBlocks(text);
179
+ if (blocks.length === 0)
180
+ return _jsx("p", { className: "sf-devtools-empty", children: "Nothing was recorded of what was asked." });
181
+ return (_jsx("div", { className: "sf-devtools-said", children: blocks.map((block, i) => {
182
+ if (block.kind === "text")
183
+ return (_jsx("p", { children: block.lines.map((line, n) => {
184
+ const label = LABEL.exec(line);
185
+ return (_jsxs("span", { children: [label ? _jsxs("strong", { children: [label[1], ":"] }) : null, label ? line.slice(label[1].length + 1) : line, n < block.lines.length - 1 ? "\n" : null] }, n));
186
+ }) }, i));
187
+ if (block.kind === "list") {
188
+ const list = (_jsx("ul", { children: block.items.map((item, n) => (_jsx("li", { children: item }, n))) }));
189
+ return block.items.length > LONG_LIST ? (_jsxs("details", { children: [_jsxs("summary", { children: [block.items.length, " lines"] }), list] }, i)) : (_jsx("div", { children: list }, i));
190
+ }
191
+ return (_jsxs("details", { children: [_jsxs("summary", { children: ["Data, ", block.code.length.toLocaleString(), " characters"] }), _jsx(CodeBlock, { code: block.code, language: "json", label: "Data sent with what was asked" })] }, i));
192
+ }) }));
193
+ }
194
+ /**
195
+ * One turn with an agent, laid out as it went: what was asked, each step and tool call, each approval asked for,
196
+ * the reply, the messages it sent for surfaces, usage, and who answered. A turn is one event; this is its parts.
197
+ */
198
+ function Turn({ event }) {
199
+ const d = event.detail;
200
+ const input = record(record(d.request).input);
201
+ const asked = typeof input.text === "string" ? input.text : input.case === "action" ? json(input.action ?? input) : input.case === "approval" ? json(input.approval ?? input) : "";
202
+ const steps = Array.isArray(d.steps) ? d.steps.map(record) : [];
203
+ const approvals = Array.isArray(d.approvals) ? d.approvals.map(record) : [];
204
+ const usage = Object.entries(record(d.usage)).filter(([, value]) => typeof value === "number" || typeof value === "string");
205
+ const reply = typeof d.text === "string" ? d.text : "";
206
+ const cut = typeof d.textLength === "number" && d.textLength > reply.length;
207
+ return (_jsxs(_Fragment, { children: [_jsxs("h4", { children: ["Asked", typeof input.case === "string" && input.case !== "text" ? ` (${input.case})` : ""] }), input.case === "text" || typeof input.text === "string" ? _jsx(Said, { text: asked }) : asked ? _jsx(CodeBlock, { code: asked, language: "json", label: "What was sent" }) : _jsx("p", { className: "sf-devtools-empty", children: "Nothing was recorded of what was asked." }), _jsxs("h4", { children: ["Steps: ", steps.length] }), steps.length > 0 && (_jsx("ol", { className: "sf-devtools-list", children: steps.map((step, i) => (_jsxs("li", { children: [String(step.title || step.tool || step.id), step.tool && step.title ? _jsxs("code", { children: [" ", String(step.tool)] }) : null, _jsxs("small", { className: "sf-devtools-kind", children: [" ", [typeof step.status === "string" ? step.status : "", took(Number(step.durationMs) || undefined)].filter(Boolean).join(" · ")] }), typeof step.detail === "string" && step.detail && _jsx("p", { className: "sf-devtools-said", children: step.detail })] }, i))) })), approvals.length > 0 && (_jsxs(_Fragment, { children: [_jsxs("h4", { children: ["Approvals asked for: ", approvals.length, d.waitingForApproval === true ? " (the turn is waiting on one)" : ""] }), _jsx("ul", { className: "sf-devtools-list", children: approvals.map((approval, i) => (_jsxs("li", { children: [String(approval.title || approval.id), " ", _jsx("small", { className: "sf-devtools-kind", children: [approval.risk, approval.editable === true ? "editable" : ""].filter(Boolean).join(" · ") })] }, i))) })] })), _jsxs("h4", { children: ["Reply", cut ? ` (the first ${reply.length} of ${String(d.textLength)} characters)` : ""] }), _jsx("p", { className: "sf-devtools-said", children: reply || (event.status === "running" ? "Nothing yet: the turn is still running." : "The turn ended with no text.") }), _jsxs("dl", { className: "sf-devtools-facts", children: [_jsx("dt", { children: "Surface messages" }), _jsxs("dd", { children: [String(d.surfaceMessages ?? 0), Number(d.surfaceMessages) > 0 ? " (in Messages, under this turn's trace)" : ""] }), typeof d.generatedBy === "string" && d.generatedBy && (_jsxs(_Fragment, { children: [_jsx("dt", { children: "Answered by" }), _jsx("dd", { children: d.generatedBy })] })), typeof d.sessionId === "string" && d.sessionId && (_jsxs(_Fragment, { children: [_jsx("dt", { children: "Session" }), _jsx("dd", { children: d.sessionId })] })), typeof d.suggestions === "number" && (_jsxs(_Fragment, { children: [_jsx("dt", { children: "Suggestions" }), _jsx("dd", { children: d.suggestions })] })), usage.map(([name, value]) => (_jsxs("div", { style: { display: "contents" }, children: [_jsx("dt", { children: name }), _jsx("dd", { children: String(value) })] }, name)))] })] }));
208
+ }
209
+ /** Everything known about one event. */
210
+ function EventDetail({ pane, event, onGoTo }) {
211
+ if (!event)
212
+ return _jsx("p", { className: "sf-devtools-empty", children: "Pick a row to see it in full." });
213
+ const d = event.detail;
214
+ const issues = Array.isArray(d.issues) ? d.issues : [];
215
+ const error = record(d.error);
216
+ const response = record(d.response);
217
+ const sql = sqlOf(event);
218
+ return (_jsxs("section", { className: "sf-devtools-detail", tabIndex: 0, "aria-label": `${pane}: ${KIND_NAME[event.kind]} ${event.name}, in full`, children: [_jsx(Facts, { event: event }), d.cancelled === true && (_jsx("p", { className: "sf-devtools-empty", role: "note", children: "Cancelled by its caller before it answered, which is usual when a component is redrawn or asks for something else. It is not a failure." })), typeof error.message === "string" && d.cancelled !== true && (_jsx("p", { className: "sf-devtools-problem", role: "note", children: [error.code, error.message, typeof error.line === "number" ? `(line ${error.line}${typeof error.column === "number" ? `, column ${error.column}` : ""})` : ""].filter(Boolean).join(" ") })), event.kind === "problem" && typeof d.message === "string" && (_jsxs("p", { className: "sf-devtools-problem", role: "note", children: [String(d.path ?? ""), " ", d.message] })), event.kind === "message" && (_jsxs(_Fragment, { children: [onGoTo && isStep(event) && (_jsx("div", { children: _jsx("button", { type: "button", className: "sf-button", onClick: () => onGoTo(event.seq), children: "Show the surface at this step" }) })), issues.length > 0 && (_jsxs(_Fragment, { children: [_jsx("h4", { children: "What the catalog said" }), _jsx("ul", { className: "sf-devtools-list", children: issues.map((issue, i) => (_jsxs("li", { className: "sf-devtools-problem", children: [_jsx("code", { children: issue.path }), " ", issue.message] }, i))) })] })), _jsxs("h4", { children: ["As it arrived", typeof d.version === "string" ? ` (version ${d.version})` : ""] }), _jsx(CodeBlock, { code: json(d.raw), language: "json", label: "The message as it arrived" }), d.message !== undefined && (_jsxs(_Fragment, { children: [_jsx("h4", { children: "As it was read (A2UI 1.0)" }), _jsx(CodeBlock, { code: json(d.message), language: "json", label: "The message as it was read" })] }))] })), event.kind === "service" && (_jsxs(_Fragment, { children: [sql && (_jsxs(_Fragment, { children: [_jsx("h4", { children: "SQL sent" }), _jsx(CodeBlock, { code: sql, language: "sql", label: "SQL sent" })] })), typeof response.executedSql === "string" && response.executedSql !== sql && (_jsxs(_Fragment, { children: [_jsx("h4", { children: "SQL the engine ran" }), _jsx(CodeBlock, { code: response.executedSql, language: "sql", label: "SQL the engine ran" })] }))] })), event.kind === "agent" && _jsx(Turn, { event: event }), event.kind !== "message" && (_jsxs(_Fragment, { children: [_jsx("h4", { children: "Recorded" }), _jsx(CodeBlock, { code: json(d), language: "json", label: "What was recorded" })] }))] }));
219
+ }
220
+ function Changes({ changes }) {
221
+ if (changes.length === 0)
222
+ return _jsx("p", { className: "sf-devtools-empty", children: "This step changed nothing a surface draws." });
223
+ return (_jsx("ul", { className: "sf-devtools-list", "aria-label": "What this step changed", children: changes.map((change) => (_jsxs("li", { children: [_jsx("strong", { children: change.change }), " ", _jsx("code", { children: change.path }), change.change !== "added" && _jsxs("code", { children: [" ", short(change.before)] }), change.change === "changed" && " → ", change.change !== "removed" && _jsxs("code", { children: [" ", short(change.after)] })] }, change.path))) }));
224
+ }
225
+ // One pane open in each column to begin with; the others are folded to their headings, a press away.
226
+ const WIDE = { columns: [["timeline", "services", "agent"], ["messages", "state", "events"], ["surface", "components"]], columnWidths: [0.36, 0.3, 0.34], rowHeights: [[0.98, 0.01, 0.01], [0.98, 0.01, 0.01], [0.99, 0.01]], collapsed: ["services", "agent", "state", "events", "components"] };
227
+ const NARROW = { columns: [["timeline", "surface"]], hidden: ["messages", "components", "state", "events", "services", "agent"] };
228
+ /**
229
+ * The dev tools themselves: a timeline of everything recorded, the raw
230
+ * messages, the component tree, state, events sent out, agent turns and
231
+ * service calls, with a scrubber that shows any surface as it stood at an
232
+ * earlier step. It is written against a feed of events and nothing else, so
233
+ * it can be shown in the page, in a window of its own, or by another host.
234
+ * It never calls a model.
235
+ */
236
+ export function DevToolsPanel({ feed, onClear, catalog = analyticsCatalog, renderers = lazyAnalyticsRenderers, services = {}, actions, onInspect, inspected, narrow: givenNarrow }) {
237
+ const log = useSyncExternalStore(feed.subscribe, feed.get, feed.get);
238
+ const { events } = log;
239
+ const root = useRef(null);
240
+ const [measured, setMeasured] = useState(givenNarrow);
241
+ useLayoutEffect(() => {
242
+ const el = root.current;
243
+ if (!el)
244
+ return;
245
+ // Styles go to whichever document the panel is in: the page, or a window of its own.
246
+ addStyles(el.ownerDocument, "sf-devtools-panel-css", PANEL_CSS);
247
+ if (measured === undefined)
248
+ setMeasured(el.clientWidth > 0 && el.clientWidth < 640);
249
+ }, [measured]);
250
+ const narrow = givenNarrow ?? measured;
251
+ const steps = useMemo(() => traceSteps(events), [events]);
252
+ // The step shown, by its event's number; undefined follows the page as it is now.
253
+ const [at, setAt] = useState();
254
+ const [selected, setSelected] = useState();
255
+ const [chosenSurface, setChosenSurface] = useState();
256
+ const [chosenComponent, setChosenComponent] = useState();
257
+ const [kinds, setKinds] = useState(new Set(TRACE_KINDS));
258
+ const [status, setStatus] = useState("all");
259
+ const [newest, setNewest] = useState(true);
260
+ const index = at === undefined ? steps.length - 1 : steps.findLastIndex((step) => step.seq <= at);
261
+ const step = index >= 0 ? steps[index] : undefined;
262
+ const state = useMemo(() => surfacesAt(events, at), [events, at]);
263
+ const keys = Object.keys(state.surfaces);
264
+ const surfaceKey = chosenSurface !== undefined && keys.includes(chosenSurface) ? chosenSurface : step?.surfaceId !== undefined && keys.includes(step.surfaceId) ? step.surfaceId : keys.at(-1);
265
+ const surface = surfaceKey === undefined ? undefined : state.surfaces[surfaceKey];
266
+ const upTo = at ?? Number.POSITIVE_INFINITY;
267
+ const byId = useMemo(() => new Map(events.map((event) => [event.id, event])), [events]);
268
+ const picked = selected === undefined ? undefined : byId.get(selected);
269
+ const goTo = (to) => {
270
+ const next = Math.max(0, Math.min(steps.length - 1, to));
271
+ setAt(next >= steps.length - 1 ? undefined : steps[next].seq);
272
+ if (steps[next])
273
+ setSelected(steps[next].id);
274
+ };
275
+ const surfacePick = (_jsxs("label", { children: ["Surface", " ", _jsxs("select", { className: "sf-input sf-devtools-select", value: surfaceKey ?? "", onChange: (event) => setChosenSurface(event.target.value), disabled: keys.length === 0, children: [keys.length === 0 && _jsx("option", { value: "", children: "None yet" }), keys.map((key) => (_jsx("option", { value: key, children: key }, key)))] })] }));
276
+ const outline = useMemo(() => surfaceOutline(surface), [surface]);
277
+ const componentId = chosenComponent !== undefined && surface?.components[chosenComponent] ? chosenComponent : outline[0]?.id;
278
+ const component = componentId === undefined ? undefined : surface?.components[componentId];
279
+ // Only a component a person picked is pointed at, never the one shown to begin with.
280
+ const pointedAt = chosenComponent !== undefined && chosenComponent === componentId ? chosenComponent : undefined;
281
+ const inspect = useRef(onInspect);
282
+ inspect.current = onInspect;
283
+ useEffect(() => {
284
+ inspect.current?.(pointedAt !== undefined && surfaceKey !== undefined ? { surfaceKey, componentId: pointedAt } : undefined);
285
+ }, [pointedAt, surfaceKey]);
286
+ useEffect(() => () => inspect.current?.(undefined), []);
287
+ // One picked outside the panel is shown here, as the page stands now.
288
+ const outsideKey = inspected?.surfaceKey;
289
+ const outsideId = inspected?.componentId;
290
+ useEffect(() => {
291
+ if (outsideKey === undefined || outsideId === undefined)
292
+ return;
293
+ setAt(undefined);
294
+ setChosenSurface(outsideKey);
295
+ setChosenComponent(outsideId);
296
+ }, [outsideKey, outsideId]);
297
+ // A picked component narrows the lists of what happened to what it did: it was drawn, its problems, its state,
298
+ // its events, its service calls. Messages and agent turns belong to a surface or a turn, so they are left whole.
299
+ const about = useCallback((event) => pointedAt === undefined || (event.surfaceId === surfaceKey && event.componentId === pointedAt), [pointedAt, surfaceKey]);
300
+ // A message is about a component when it sent it: the messages that made the picked component what it is.
301
+ const sends = useCallback((event) => {
302
+ if (pointedAt === undefined)
303
+ return true;
304
+ if (event.surfaceId !== surfaceKey)
305
+ return false;
306
+ const message = (event.detail.message ?? event.detail.raw);
307
+ const list = message?.updateComponents?.components ?? message?.createSurface?.components;
308
+ return Array.isArray(list) && list.some((item) => item?.id === pointedAt);
309
+ }, [pointedAt, surfaceKey]);
310
+ const timeline = useMemo(() => {
311
+ const shown = events.filter((event) => kinds.has(event.kind) && (status === "all" || event.status === status) && (event.kind === "message" ? sends(event) : about(event)));
312
+ return newest ? [...shown].reverse() : shown;
313
+ }, [events, kinds, status, newest, about, sends]);
314
+ const of = (kind) => events.filter((event) => event.kind === kind && about(event));
315
+ const messages = events.filter((event) => event.kind === "message" && sends(event));
316
+ const turns = events.filter((event) => event.kind === "agent");
317
+ const controlsHere = (surfaceKey !== undefined ? state.controls[surfaceKey] : undefined) ?? {};
318
+ const onlyComponent = pointedAt !== undefined && component ? (_jsxs("span", { className: "sf-devtools-only", children: ["Only ", String(component.component), " ", _jsx("code", { children: pointedAt }), _jsx("button", { type: "button", className: "sf-devtools-icon", "aria-label": `Show every component again, not only ${String(component.component)} ${pointedAt}`, title: "Show every component", onClick: () => setChosenComponent(undefined), children: _jsx(ControlIcon, { icon: "close" }) })] })) : null;
319
+ const noneFor = pointedAt !== undefined && component ? `Nothing here for ${String(component.component)} "${pointedAt}".` : undefined;
320
+ const resolved = useMemo(() => {
321
+ if (!component || !surface)
322
+ return undefined;
323
+ const functions = Object.fromEntries(Object.entries(catalog.functions).map(([name, fn]) => [name, fn.implementation]));
324
+ const { id: _id, component: _name, action: _action, child: _child, children: _children, ...own } = component;
325
+ try {
326
+ return plain(resolve(Object.fromEntries(Object.entries(own).filter(([key]) => !key.startsWith("@"))), { data: surface.data, scope: "/", functions }));
327
+ }
328
+ catch (error) {
329
+ return { "could not be resolved": error instanceof Error ? error.message : String(error) };
330
+ }
331
+ }, [component, surface, catalog]);
332
+ const problemsOf = (id) => events.filter((event) => event.kind === "problem" && event.surfaceId === surfaceKey && event.componentId === id && event.seq <= upTo);
333
+ const callsOf = (id) => events.filter((event) => event.kind === "service" && event.surfaceId === surfaceKey && event.componentId === id && event.seq <= upTo);
334
+ const findings = useMemo(() => (surfaceKey !== undefined && componentId !== undefined ? componentFindings({ events, surfaceKey, surface, componentId, upTo }) : []), [events, surfaceKey, surface, componentId, upTo]);
335
+ const show = (id) => {
336
+ const event = byId.get(id);
337
+ if (!event)
338
+ return;
339
+ // Its kind is switched back on if it was filtered out of the timeline.
340
+ setKinds((held) => (held.has(event.kind) ? held : new Set([...held, event.kind])));
341
+ setStatus("all");
342
+ setSelected(id);
343
+ };
344
+ const causes = component && componentId !== undefined && (_jsxs("div", { className: "sf-devtools-causes", role: "group", "aria-label": `Likely cause for ${String(component.component)} ${componentId}`, children: [_jsx("h4", { children: "Likely cause" }), findings.length === 0 ? (_jsx("p", { className: "sf-devtools-empty", children: "Nothing recorded points at a problem with this component." })) : (_jsx("ol", { className: "sf-devtools-list", children: findings.map((finding, i) => (_jsxs("li", { className: "sf-devtools-cause", "data-severity": finding.severity, children: [_jsx("span", { className: "sf-devtools-cause-mark", children: finding.severity === "error" ? "Problem" : finding.severity === "warning" ? "Check" : "Note" }), _jsxs("span", { children: [finding.title, finding.detail && _jsxs("small", { children: [" ", finding.detail] })] }), finding.eventId !== undefined && (_jsxs("button", { type: "button", className: "sf-button sf-devtools-cause-show", onClick: () => show(finding.eventId), children: ["Show", _jsxs("span", { className: "sf-visually-hidden", children: [" what was recorded for: ", finding.title] })] }))] }, i))) })), _jsx("p", { className: "sf-devtools-cause-by", children: "Worked out from this recording by fixed rules, most likely first. Not a model, and nothing was queried." })] }));
345
+ const provide = (children) => {
346
+ let out = children;
347
+ if (services.semantics)
348
+ out = _jsx(SemanticsProvider, { semantics: services.semantics, children: out });
349
+ if (services.pipelines)
350
+ out = _jsx(PipelinesProvider, { pipelines: services.pipelines, children: out });
351
+ if (services.discovery)
352
+ out = _jsx(DiscoveryProvider, { discovery: services.discovery, children: out });
353
+ if (services.dataSource)
354
+ out = _jsx(DataSourceProvider, { dataSource: services.dataSource, children: out });
355
+ // What the tools draw is not recorded: looking at a trace must not add to it.
356
+ return _jsx(TraceProvider, { recorder: undefined, children: out });
357
+ };
358
+ const panels = [
359
+ {
360
+ id: "timeline",
361
+ title: "Timeline",
362
+ icon: "history",
363
+ content: (_jsxs("div", { className: "sf-devtools-pane", children: [_jsxs("div", { className: "sf-devtools-filters", role: "group", "aria-label": "Show in the timeline", children: [TRACE_KINDS.map((kind) => (_jsx("button", { type: "button", className: "sf-devtools-chip", "aria-pressed": kinds.has(kind), onClick: () => setKinds((held) => {
364
+ const next = new Set(held);
365
+ if (next.has(kind))
366
+ next.delete(kind);
367
+ else
368
+ next.add(kind);
369
+ return next;
370
+ }), children: KIND_NAME[kind] }, kind))), _jsxs("label", { children: ["Status", " ", _jsxs("select", { className: "sf-input", value: status, onChange: (event) => setStatus(event.target.value), children: [_jsx("option", { value: "all", children: "Any" }), TRACE_STATUSES.map((s) => (_jsx("option", { value: s, children: s }, s)))] })] }), _jsxs("label", { children: ["Order", " ", _jsxs("select", { className: "sf-input", value: newest ? "newest" : "oldest", onChange: (event) => setNewest(event.target.value === "newest"), children: [_jsx("option", { value: "newest", children: "Newest first" }), _jsx("option", { value: "oldest", children: "Oldest first" })] })] })] }), onlyComponent, pointedAt !== undefined && causes, _jsx(EventRows, { label: "Timeline", events: timeline, selected: selected, onSelect: setSelected, at: at, empty: events.length === 0 ? "Nothing recorded yet. Use the page and what it does shows here." : "Nothing matches these filters." }), _jsx(EventDetail, { pane: "Timeline", event: picked && kinds.has(picked.kind) ? picked : undefined, onGoTo: (seq) => goTo(steps.findIndex((s) => s.seq === seq)) })] })),
371
+ },
372
+ {
373
+ id: "messages",
374
+ title: "Messages",
375
+ icon: "code",
376
+ content: (_jsxs("div", { className: "sf-devtools-pane", children: [onlyComponent, _jsx(EventRows, { label: "Messages", events: messages, selected: selected, onSelect: setSelected, at: at, empty: pointedAt !== undefined && component ? `No message recorded here sent ${String(component.component)} "${pointedAt}".` : "No message has arrived yet." }), _jsx(EventDetail, { pane: "Messages", event: picked?.kind === "message" ? picked : undefined, onGoTo: (seq) => goTo(steps.findIndex((s) => s.seq === seq)) })] })),
377
+ },
378
+ {
379
+ id: "components",
380
+ title: "Components",
381
+ icon: "components",
382
+ content: (_jsxs("div", { className: "sf-devtools-pane", children: [_jsx("div", { className: "sf-devtools-filters", children: surfacePick }), _jsx(WindowList, { label: "Components of the surface", items: outline, idOf: (item) => item.id, selected: componentId, onSelect: setChosenComponent, className: "sf-devtools-tree", rowClass: "sf-devtools-node sf-devtools-row-node", empty: "No surface has been drawn at this step.", row: (item) => {
383
+ const problems = problemsOf(item.id).length;
384
+ return (_jsxs("span", { style: { paddingInlineStart: `calc(${item.depth} * var(--sf-space-3))` }, children: [item.component, " ", _jsx("small", { children: item.id }), problems > 0 && _jsxs("span", { className: "sf-devtools-problem", children: [" \u00B7 ", problems, " ", problems === 1 ? "problem" : "problems"] })] }));
385
+ } }), component && componentId !== undefined && (_jsxs("section", { className: "sf-devtools-detail", tabIndex: 0, "aria-label": `${String(component.component)} ${componentId}, in full`, children: [causes, _jsx("h4", { children: "As sent" }), _jsx(CodeBlock, { code: json(component), language: "json", label: "The component as sent" }), _jsx("h4", { children: "Props after bindings and functions" }), _jsx(CodeBlock, { code: json(resolved), language: "json", label: "The component's props after bindings and functions" }), _jsxs("h4", { children: ["Service calls: ", callsOf(componentId).length] })] }))] })),
386
+ },
387
+ {
388
+ id: "state",
389
+ title: "State",
390
+ icon: "data",
391
+ content: (_jsxs("div", { className: "sf-devtools-pane", children: [_jsx("div", { className: "sf-devtools-filters", children: surfacePick }), _jsxs("section", { className: "sf-devtools-detail", tabIndex: 0, "aria-label": "State of the surface", children: [_jsxs("h4", { children: ["Changed by this step", step ? `: ${step.name}` : ""] }), step ? _jsx(Changes, { changes: surfaceStepDiff(events, step.seq) }) : _jsx("p", { className: "sf-devtools-empty", children: "No step yet." }), _jsx("h4", { children: "Data model" }), _jsx(CodeBlock, { code: json(surface?.data ?? {}), language: "json", label: "The surface's data model" }), _jsx("h4", { children: "Written by a person" }), surfaceKey !== undefined && state.writes[surfaceKey]?.length ? (_jsx("ul", { className: "sf-devtools-list", children: state.writes[surfaceKey].map(([path, value]) => (_jsxs("li", { children: [_jsx("code", { children: path }), " = ", _jsx("code", { children: short(value) })] }, path))) })) : (_jsx("p", { className: "sf-devtools-empty", children: "Nothing." })), _jsxs("h4", { children: ["Controls as a person left them", pointedAt !== undefined ? `: ${pointedAt} only` : ""] }), _jsx(CodeBlock, { code: json(pointedAt !== undefined ? (controlsHere[pointedAt] ?? {}) : controlsHere), language: "json", label: pointedAt !== undefined ? `The controls of ${pointedAt}` : "Each component's controls" })] })] })),
392
+ },
393
+ {
394
+ id: "events",
395
+ title: "Events",
396
+ icon: "note",
397
+ content: (_jsxs("div", { className: "sf-devtools-pane", children: [onlyComponent, _jsx(EventRows, { label: "Events sent out", events: of("event"), selected: selected, onSelect: setSelected, at: at, empty: noneFor ?? "Nothing has been sent out yet: no action, no context note." }), _jsx(EventDetail, { pane: "Events", event: picked?.kind === "event" ? picked : undefined })] })),
398
+ },
399
+ {
400
+ id: "services",
401
+ title: "Services",
402
+ icon: "table",
403
+ content: (_jsxs("div", { className: "sf-devtools-pane", children: [onlyComponent, _jsx(EventRows, { label: "Service calls", events: of("service"), selected: selected, onSelect: setSelected, at: at, empty: noneFor ?? "No backend has been called yet." }), _jsx(EventDetail, { pane: "Services", event: picked?.kind === "service" ? picked : undefined })] })),
404
+ },
405
+ {
406
+ id: "agent",
407
+ title: "Agent",
408
+ icon: "agent",
409
+ content: (_jsxs("div", { className: "sf-devtools-pane", children: [_jsx(EventRows, { label: "Agent turns", events: turns, selected: selected, onSelect: setSelected, at: at, empty: "No turn with an agent yet." }), _jsx(EventDetail, { pane: "Agent", event: picked?.kind === "agent" ? picked : undefined })] })),
410
+ },
411
+ {
412
+ id: "surface",
413
+ title: "Surface",
414
+ icon: "surface",
415
+ content: (_jsxs("div", { className: "sf-devtools-pane", children: [_jsx("div", { className: "sf-devtools-filters", children: surfacePick }), _jsx("p", { className: "sf-devtools-empty", role: "note", children: surface
416
+ ? `Read-only${at === undefined ? ", as it stands now" : `, as it stood after step ${index + 1} of ${steps.length}`}. Its data is queried now, so the numbers are today's. Nothing pressed here is sent to the agent.`
417
+ : "No surface has been drawn at this step." }), surface && surfaceKey !== undefined && (_jsx("div", { className: "sf-devtools-preview", role: "region", "aria-label": "The surface, drawn again", tabIndex: 0, children: provide(_jsx(SurfaceView, { surface: withControls(surface, state.controls[surfaceKey]), catalog: catalog, renderers: renderers }, `${surfaceKey}:${at ?? "live"}`)) }))] })),
418
+ },
419
+ ];
420
+ const problems = events.filter((event) => event.status === "error").length;
421
+ return (_jsxs("div", { ref: root, className: "sf-devtools", role: "region", "aria-label": "Surfaces dev tools", children: [_jsxs("div", { className: "sf-devtools-bar", children: [_jsx("h2", { className: "sf-devtools-title", children: "Dev tools" }), _jsxs("span", { className: "sf-devtools-step", children: [events.length, " recorded", problems > 0 ? `, ${problems} failed` : ""] }), _jsxs("div", { className: "sf-devtools-scrub", role: "group", "aria-label": "Time travel", children: [_jsx("button", { type: "button", className: "sf-devtools-icon", "aria-label": "Step back", title: "Step back", "aria-disabled": index <= 0, onClick: () => index > 0 && goTo(index - 1), children: _jsx(ControlIcon, { icon: "earlier" }) }), _jsx("input", { type: "range", "aria-label": "Step", min: 1, max: Math.max(1, steps.length), value: Math.max(1, index + 1), disabled: steps.length < 2, "aria-valuetext": step ? `Step ${index + 1} of ${steps.length}: ${step.name}` : "No steps yet", onChange: (event) => goTo(Number(event.target.value) - 1) }), _jsx("button", { type: "button", className: "sf-devtools-icon", "aria-label": "Step forward", title: "Step forward", "aria-disabled": at === undefined, onClick: () => at !== undefined && goTo(index + 1), children: _jsx(ControlIcon, { icon: "later" }) }), _jsx("button", { type: "button", className: "sf-devtools-chip", "aria-pressed": at === undefined, onClick: () => setAt(undefined), children: "Live" }), _jsx("span", { className: "sf-devtools-step", "aria-hidden": "true", children: step ? `${index + 1} of ${steps.length} · ${step.name}` : "No steps yet" })] }), _jsxs("div", { className: "sf-devtools-actions", children: [onClear && (_jsx("button", { type: "button", className: "sf-devtools-icon", "aria-label": "Clear what was recorded", title: "Clear what was recorded", onClick: () => {
422
+ setAt(undefined);
423
+ setSelected(undefined);
424
+ onClear();
425
+ }, children: _jsx(ControlIcon, { icon: "remove" }) })), actions] })] }), _jsx("p", { className: "sf-devtools-note", role: "status", children: [
426
+ at !== undefined && step ? `Showing step ${index + 1} of ${steps.length} (${step.name}). Surfaces are drawn as they stood then; their data is queried live.` : "",
427
+ log.dropped > 0 ? `The oldest ${log.dropped} events were let go to stay within the limit, so time travel starts from what is left.` : "",
428
+ state.skipped.length > 0 ? `${state.skipped.length} recorded ${state.skipped.length === 1 ? "message" : "messages"} could not be applied again.` : "",
429
+ ]
430
+ .filter(Boolean)
431
+ .join(" ") }), _jsx("div", { className: "sf-devtools-body", children: narrow !== undefined && _jsx(Workspace, { label: "Dev tools panels", className: "sf-devtools-workspace", height: "100%", panels: panels, defaultLayout: narrow ? NARROW : WIDE }, narrow ? "narrow" : "wide") })] }));
432
+ }
433
+ export default DevToolsPanel;
434
+ //# sourceMappingURL=Panel.js.map