@muthuishere/klark-hub-ui 0.0.0-stage → 0.11.10

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/index.js ADDED
@@ -0,0 +1,1244 @@
1
+ import { forwardRef, useRef, useImperativeHandle, useEffect, useState, useCallback, memo, createContext, useContext, useMemo, useLayoutEffect, useId } from "react";
2
+ import { jsx, jsxs, Fragment } from "react/jsx-runtime";
3
+ function backoff(attempt, min = 1e3, max = 3e4) {
4
+ return Math.min(max, min * 2 ** attempt);
5
+ }
6
+ function connectSSE(href, o) {
7
+ const Ctor = o.EventSourceCtor ?? EventSource;
8
+ let es = null;
9
+ let timer;
10
+ let attempt = 0;
11
+ let opened = 0;
12
+ let stopped = false;
13
+ const open = () => {
14
+ var _a;
15
+ if (stopped) return;
16
+ (_a = o.onState) == null ? void 0 : _a.call(o, "connecting");
17
+ es = new Ctor(href, { withCredentials: true });
18
+ es.onopen = () => {
19
+ var _a2, _b;
20
+ attempt = 0;
21
+ (_a2 = o.onState) == null ? void 0 : _a2.call(o, "open");
22
+ if (++opened > 1) (_b = o.onResync) == null ? void 0 : _b.call(o);
23
+ };
24
+ for (const name of o.events) es.addEventListener(name, (e) => o.onEvent(name, e.data));
25
+ es.onerror = () => {
26
+ var _a2;
27
+ es == null ? void 0 : es.close();
28
+ es = null;
29
+ if (stopped) return;
30
+ (_a2 = o.onState) == null ? void 0 : _a2.call(o, "retrying");
31
+ timer = setTimeout(open, backoff(attempt++, o.minDelay, o.maxDelay));
32
+ };
33
+ };
34
+ open();
35
+ return () => {
36
+ var _a;
37
+ stopped = true;
38
+ clearTimeout(timer);
39
+ es == null ? void 0 : es.close();
40
+ (_a = o.onState) == null ? void 0 : _a.call(o, "closed");
41
+ };
42
+ }
43
+ class TransportError extends Error {
44
+ constructor(status, message) {
45
+ super(message);
46
+ this.status = status;
47
+ }
48
+ }
49
+ const enc = encodeURIComponent;
50
+ const parse = (s2) => {
51
+ try {
52
+ return JSON.parse(s2);
53
+ } catch {
54
+ return null;
55
+ }
56
+ };
57
+ function httpTransport(basePath = "/", o = {}) {
58
+ const base = basePath.endsWith("/") ? basePath : basePath + "/";
59
+ const pane = (m, a) => `${base}api/machines/${enc(m)}/panes/${enc(a)}`;
60
+ async function req(path, init = {}) {
61
+ var _a;
62
+ const { json, ...rest } = init;
63
+ const h = new Headers(rest.headers);
64
+ h.set("Accept", "application/json");
65
+ let body = rest.body;
66
+ if (json !== void 0) {
67
+ h.set("Content-Type", "application/json");
68
+ body = JSON.stringify(json);
69
+ }
70
+ let res;
71
+ try {
72
+ res = await (o.fetch ?? fetch)(path, { credentials: "same-origin", ...rest, headers: h, body });
73
+ } catch {
74
+ throw new TransportError(0, "The hub did not answer.");
75
+ }
76
+ (_a = o.onStatus) == null ? void 0 : _a.call(o, res.status);
77
+ if (res.status === 204) return void 0;
78
+ const ct = res.headers.get("content-type") ?? "";
79
+ const data = ct.includes("json") ? await res.json().catch(() => ({})) : await res.text().catch(() => "");
80
+ if (!res.ok) {
81
+ const msg = typeof data === "object" && data && "error" in data ? String(data.error) : `Error ${res.status}`;
82
+ throw new TransportError(res.status, msg);
83
+ }
84
+ return data;
85
+ }
86
+ const t = {
87
+ machines: () => req(`${base}api/machines`),
88
+ tree: (m) => req(`${base}api/machines/${enc(m)}/tree`),
89
+ feeds: (m) => req(`${base}api/machines/${enc(m)}/feeds`).then((r) => r.feeds ?? []),
90
+ getChat: (m, a) => req(`${pane(m, a)}/chat`),
91
+ events: (m, a, { frames }, h) => connectSSE(`${pane(m, a)}/events${frames ? "?frames=1" : ""}`, {
92
+ events: ["chat", "frame", "size", "offer"],
93
+ EventSourceCtor: o.EventSource,
94
+ onState: h.state,
95
+ onResync: h.resync,
96
+ onEvent: (name, data) => {
97
+ var _a, _b, _c, _d;
98
+ if (name === "chat") {
99
+ const p = parse(data);
100
+ if (p) (_a = h.chat) == null ? void 0 : _a.call(h, Array.isArray(p) ? { rows: p } : "rows" in p ? p : { rows: [p] });
101
+ } else if (name === "frame") {
102
+ const f = parse(data);
103
+ (_b = h.frame) == null ? void 0 : _b.call(h, f && typeof f === "object" ? f : { data });
104
+ } else if (name === "size") {
105
+ const s2 = parse(data);
106
+ if (s2) (_c = h.size) == null ? void 0 : _c.call(h, s2);
107
+ } else if (name === "offer") {
108
+ const of = parse(data);
109
+ if (of) (_d = h.offer) == null ? void 0 : _d.call(h, of);
110
+ }
111
+ }
112
+ }),
113
+ input: (m, a, text) => req(`${pane(m, a)}/input`, { method: "POST", json: { text } }),
114
+ keys: (m, a, keys) => req(`${pane(m, a)}/keys`, { method: "POST", json: { keys } }),
115
+ send: async (m, a, text) => {
116
+ await t.input(m, a, text);
117
+ await t.keys(m, a, ["enter"]);
118
+ },
119
+ upload: (m, a, file) => {
120
+ const fd = new FormData();
121
+ fd.append("file", file, file.name);
122
+ return req(`${pane(m, a)}/upload`, { method: "POST", body: fd });
123
+ },
124
+ fileUrl: (m, a, path, line) => `${base}m/${enc(m)}/f?path=${enc(path)}&pane=${enc(a)}${line ? "#L" + line : ""}`
125
+ };
126
+ return t;
127
+ }
128
+ const isRun = (k) => k === "tool_use" || k === "tool_result" || k === "thinking";
129
+ const make = (kind, items) => ({
130
+ key: items[0].id,
131
+ kind,
132
+ items,
133
+ // Changes only when the row's content does, so memoised rows skip re-rendering.
134
+ stamp: `${items.length}:${items[items.length - 1].id}:${items.reduce((n, i) => {
135
+ var _a, _b;
136
+ return n + (((_a = i.html) == null ? void 0 : _a.length) ?? 0) + (((_b = i.text) == null ? void 0 : _b.length) ?? 0);
137
+ }, 0)}`
138
+ });
139
+ function buildRows(items) {
140
+ const rows = [];
141
+ let run = [];
142
+ const flush = () => {
143
+ if (run.length) rows.push(make("tools", run));
144
+ run = [];
145
+ };
146
+ for (let n = 0; n < items.length; n++) {
147
+ const i = items[n];
148
+ if (isRun(i.kind)) {
149
+ run.push(i);
150
+ continue;
151
+ }
152
+ flush();
153
+ if (i.kind === "command") {
154
+ const next = items[n + 1];
155
+ rows.push(make("block", next && next.kind === "output" ? [i, items[++n]] : [i]));
156
+ continue;
157
+ }
158
+ if (i.kind === "output") {
159
+ rows.push(make("block", [i]));
160
+ continue;
161
+ }
162
+ if (!i.text && !i.html) continue;
163
+ rows.push(make(i.role === "user" || i.kind === "user" ? "user" : "text", [i]));
164
+ }
165
+ flush();
166
+ return rows;
167
+ }
168
+ function mergeItems(cur, incoming) {
169
+ if (!incoming.length) return cur;
170
+ const at = new Map(cur.map((r, i) => [r.id, i]));
171
+ const next = cur.slice();
172
+ for (const r of incoming) {
173
+ const i = at.get(r.id);
174
+ if (i === void 0) {
175
+ at.set(r.id, next.length);
176
+ next.push(r);
177
+ } else next[i] = r;
178
+ }
179
+ return next;
180
+ }
181
+ function pairCalls(items) {
182
+ const list = [];
183
+ for (const i of items) {
184
+ if (i.kind === "tool_result") {
185
+ let open = i.toolUseId ? list.findLastIndex((c) => {
186
+ var _a;
187
+ return c.kind === "tool" && ((_a = c.use) == null ? void 0 : _a.toolUseId) === i.toolUseId && !c.result;
188
+ }) : -1;
189
+ if (open < 0) open = list.findLastIndex((c) => c.kind === "tool" && c.use && !c.result);
190
+ if (open >= 0) list[open] = { ...list[open], result: i };
191
+ else list.push({ key: i.id, kind: "tool", result: i });
192
+ } else if (i.kind === "thinking") list.push({ key: i.id, kind: "thinking", use: i });
193
+ else list.push({ key: i.id, kind: "tool", use: i });
194
+ }
195
+ return list;
196
+ }
197
+ function verb(tool) {
198
+ switch (tool) {
199
+ case "Read":
200
+ case "NotebookRead":
201
+ return ["Read", "file"];
202
+ case "Edit":
203
+ case "MultiEdit":
204
+ case "str_replace":
205
+ case "NotebookEdit":
206
+ return ["Edited", "file"];
207
+ case "Write":
208
+ return ["Wrote", "file"];
209
+ case "Bash":
210
+ case "BashOutput":
211
+ case "shell":
212
+ case "exec":
213
+ return ["Ran", "command"];
214
+ case "Grep":
215
+ case "Glob":
216
+ case "search":
217
+ return ["Searched", "pattern"];
218
+ case "WebSearch":
219
+ return ["Searched the web", "query"];
220
+ case "WebFetch":
221
+ return ["Fetched", "page"];
222
+ case "Task":
223
+ case "Agent":
224
+ return ["Ran", "agent"];
225
+ case "TodoWrite":
226
+ return ["Updated", "todo list"];
227
+ default:
228
+ return [tool, "call"];
229
+ }
230
+ }
231
+ function toolIcon(tool) {
232
+ switch (verb(tool)[0]) {
233
+ case "Ran":
234
+ return tool === "Task" || tool === "Agent" ? "◆" : "$";
235
+ case "Read":
236
+ return "◉";
237
+ case "Edited":
238
+ case "Wrote":
239
+ return "✎";
240
+ case "Searched":
241
+ case "Searched the web":
242
+ return "⌕";
243
+ case "Fetched":
244
+ return "↗";
245
+ case "Updated":
246
+ return "☰";
247
+ default:
248
+ return "•";
249
+ }
250
+ }
251
+ function phrase(tools, thinking) {
252
+ const groups = /* @__PURE__ */ new Map();
253
+ for (const t of tools) {
254
+ const [v, n] = verb(t);
255
+ const k = v + "|" + n;
256
+ const g = groups.get(k) ?? { v, n, count: 0 };
257
+ g.count++;
258
+ groups.set(k, g);
259
+ }
260
+ const parts = [...groups.values()].map(({ v, n, count }) => {
261
+ if (v === n || n === "call") return count === 1 ? v : `${v} ×${count}`;
262
+ const plural = n.endsWith("y") ? n.slice(0, -1) + "ies" : n + "s";
263
+ return `${v} ${count} ${count === 1 ? n : plural}`;
264
+ });
265
+ if (thinking > 0) parts.push("thought");
266
+ return parts.join(" · ");
267
+ }
268
+ function offsets(count, heights, key, estimate) {
269
+ const out = new Array(count + 1);
270
+ out[0] = 0;
271
+ for (let i = 0; i < count; i++) {
272
+ const h = typeof heights === "function" ? heights(i) : heights.get(key(i)) ?? estimate;
273
+ out[i + 1] = out[i] + h;
274
+ }
275
+ return out;
276
+ }
277
+ function computeWindow(offs, scrollTop, viewport, overscan) {
278
+ const count = offs.length - 1;
279
+ const total = offs[count] ?? 0;
280
+ if (count <= 0) return { start: 0, end: 0, padTop: 0, padBottom: 0, total };
281
+ const lo = Math.max(0, scrollTop - overscan);
282
+ const hi = scrollTop + viewport + overscan;
283
+ const find = (y) => {
284
+ let a = 0, b = count;
285
+ while (a < b) {
286
+ const m = a + b >> 1;
287
+ if (offs[m + 1] > y) b = m;
288
+ else a = m + 1;
289
+ }
290
+ return a;
291
+ };
292
+ const start = Math.min(find(lo), count - 1);
293
+ let end = find(hi) + 1;
294
+ end = Math.min(count, Math.max(end, start + 1));
295
+ return { start, end, padTop: offs[start], padBottom: total - offs[end], total };
296
+ }
297
+ function atBottom(scrollTop, viewport, total, slack = 80) {
298
+ return total - (scrollTop + viewport) <= slack;
299
+ }
300
+ const paneId = (p) => p.pane_id;
301
+ const paneCwd = (p) => p.foreground_cwd || p.cwd || "";
302
+ const paneAgent = (p) => p.display_agent || p.agent || "";
303
+ const paneStatus = (p) => p.agent_status && p.agent_status !== "unknown" ? p.agent_status : "";
304
+ const isAgent = (p) => paneAgent(p).length > 0 || paneStatus(p) !== "";
305
+ function agentKey(agent) {
306
+ const a = agent.toLowerCase();
307
+ return a.includes("claude") ? "claude" : a.includes("devin") ? "devin" : a.includes("codex") ? "codex" : a.includes("opencode") ? "opencode" : a === "" ? "shell" : "other";
308
+ }
309
+ function agentIcon(agent) {
310
+ switch (agentKey(agent)) {
311
+ case "claude":
312
+ return "✻";
313
+ case "devin":
314
+ return "◆";
315
+ case "codex":
316
+ return "◎";
317
+ case "opencode":
318
+ return "◇";
319
+ case "shell":
320
+ return "$";
321
+ default:
322
+ return agent ? agent[0].toUpperCase() : "•";
323
+ }
324
+ }
325
+ function folderName(cwd) {
326
+ const s2 = (cwd ?? "").trim().replace(/\/+$/, "");
327
+ if (s2 === "" || s2 === "~" || /^\/(Users|home)\/[^/]+$/.test(s2)) return "~";
328
+ return s2.slice(s2.lastIndexOf("/") + 1);
329
+ }
330
+ function displayName(p) {
331
+ const title = (p.label || p.title || p.terminal_title_stripped || p.pane_id || "").replace(/^[✳✻✽✶·*⠂⠐ ]+/, "");
332
+ const agent = paneAgent(p);
333
+ const cwd = paneCwd(p);
334
+ const raw = title === "" || title === p.pane_id || /^w?\d+[:/]p?\d+$/.test(title) || title.toLowerCase() === agent.toLowerCase() || title === cwd || ["zsh", "bash", "sh", "fish"].includes(title) || /^(?:[\w.-]+@[\w.-]+:)?(?:~|\.{0,2})?\//.test(title);
335
+ if (!raw) return title;
336
+ const folder = cwd.replace(/\/+$/, "") ? cwd.replace(/\/+$/, "").split("/").pop() ?? "" : "";
337
+ if (agent) return folder ? `${agent} · ${folder}` : agent;
338
+ return folder || title || p.pane_id;
339
+ }
340
+ function workspaceLabel(t, id) {
341
+ var _a;
342
+ const w = (_a = t == null ? void 0 : t.workspaces) == null ? void 0 : _a.find((x) => x.workspace_id === id);
343
+ return w ? w.label || `workspace ${w.number ?? ""}`.trim() : id ?? "";
344
+ }
345
+ const statusRank = (s2) => s2 === "blocked" ? 3 : s2 === "working" ? 2 : s2 === "idle" ? 1 : 0;
346
+ function matches(r, words) {
347
+ if (!words.length) return true;
348
+ const p = r.pane;
349
+ const hay = `${r.machineName} ${r.session} ${displayName(p)} ${p.title ?? ""} ${paneAgent(p)} ${paneStatus(p)} ${paneCwd(p)} ${folderName(paneCwd(p))} ${p.pane_id}`.toLowerCase();
350
+ return words.every((w) => hay.includes(w.toLowerCase()));
351
+ }
352
+ function groupRows(rows, filter, showAll) {
353
+ const words = filter.split(/\s+/).filter(Boolean);
354
+ const kept = rows.filter((r) => (showAll || isAgent(r.pane)) && matches(r, words));
355
+ const by = /* @__PURE__ */ new Map();
356
+ for (const r of kept) {
357
+ const k = folderName(paneCwd(r.pane));
358
+ by.set(k, [...by.get(k) ?? [], r]);
359
+ }
360
+ const rank = (rs) => Math.max(...rs.map((r) => statusRank(paneStatus(r.pane))));
361
+ return [...by.entries()].map(([key, rs]) => ({
362
+ key,
363
+ name: key,
364
+ path: paneCwd(rs[0].pane),
365
+ rows: rs.slice().sort((a, b) => statusRank(paneStatus(b.pane)) - statusRank(paneStatus(a.pane)) || displayName(a.pane).localeCompare(displayName(b.pane)))
366
+ })).sort((a, b) => rank(b.rows) - rank(a.rows) || a.name.localeCompare(b.name, void 0, { sensitivity: "base" }));
367
+ }
368
+ function webStorage(area, prefix = "") {
369
+ const a = area ?? (() => localStorage);
370
+ return {
371
+ get(key) {
372
+ try {
373
+ return a().getItem(prefix + key);
374
+ } catch {
375
+ return null;
376
+ }
377
+ },
378
+ set(key, value) {
379
+ try {
380
+ if (value === null || value === "") a().removeItem(prefix + key);
381
+ else a().setItem(prefix + key, value);
382
+ } catch {
383
+ }
384
+ }
385
+ };
386
+ }
387
+ function memoryStorage() {
388
+ const m = /* @__PURE__ */ new Map();
389
+ return { get: (k) => m.get(k) ?? null, set: (k, v) => {
390
+ if (v === null || v === "") m.delete(k);
391
+ else m.set(k, v);
392
+ } };
393
+ }
394
+ const defaultStorage = webStorage();
395
+ const MIN_SCALE = 0.55;
396
+ function decodeBase64(b64) {
397
+ const bin = atob(b64);
398
+ const out = new Uint8Array(bin.length);
399
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
400
+ return out;
401
+ }
402
+ const Terminal = forwardRef(function Terminal2({ cols, rows, visible, theme, fontSize = 13 }, ref) {
403
+ const wrap = useRef(null);
404
+ const sizer = useRef(null);
405
+ const inner = useRef(null);
406
+ const term = useRef(null);
407
+ const queue = useRef([]);
408
+ const geom = useRef({ cols, rows });
409
+ geom.current = { cols, rows };
410
+ const scale = () => {
411
+ var _a;
412
+ const screen = (_a = inner.current) == null ? void 0 : _a.querySelector(".xterm-screen");
413
+ const w = wrap.current, sz = sizer.current, inn = inner.current;
414
+ if (!screen || !w || !sz || !inn || !w.clientWidth) return;
415
+ const sw = screen.offsetWidth, sh = screen.offsetHeight;
416
+ if (!sw || !sh) return;
417
+ const s2 = Math.max(MIN_SCALE, Math.min(1, (w.clientWidth - 2) / sw));
418
+ inn.style.transform = `scale(${s2})`;
419
+ sz.style.width = `${Math.ceil(sw * s2)}px`;
420
+ sz.style.height = `${Math.ceil(sh * s2)}px`;
421
+ };
422
+ const run = (f) => {
423
+ if (term.current) f();
424
+ else queue.current.push(f);
425
+ };
426
+ useImperativeHandle(ref, () => ({
427
+ write: (b) => run(() => {
428
+ var _a;
429
+ return (_a = term.current) == null ? void 0 : _a.write(b);
430
+ }),
431
+ reset: (b) => run(() => {
432
+ var _a, _b;
433
+ (_a = term.current) == null ? void 0 : _a.reset();
434
+ (_b = term.current) == null ? void 0 : _b.write(b);
435
+ }),
436
+ resize: (c, r) => run(() => {
437
+ if (term.current && (term.current.cols !== c || term.current.rows !== r)) {
438
+ term.current.resize(c, r);
439
+ requestAnimationFrame(scale);
440
+ }
441
+ })
442
+ }));
443
+ useEffect(() => {
444
+ if (!visible || term.current) return;
445
+ let dead = false;
446
+ (async () => {
447
+ const [{ Terminal: XTerm }, { Unicode11Addon }] = await Promise.all([import("@xterm/xterm"), import("@xterm/addon-unicode11"), import("@xterm/xterm/css/xterm.css")]);
448
+ if (dead || !inner.current) return;
449
+ const t = new XTerm({
450
+ cols: geom.current.cols,
451
+ rows: geom.current.rows,
452
+ convertEol: false,
453
+ disableStdin: true,
454
+ allowProposedApi: true,
455
+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
456
+ fontSize,
457
+ scrollback: 5e3,
458
+ theme: theme ?? { background: "#0d1117", foreground: "#e6edf3", cursor: "#e6edf3", selectionBackground: "#264f78" }
459
+ });
460
+ t.loadAddon(new Unicode11Addon());
461
+ t.unicode.activeVersion = "11";
462
+ t.open(inner.current);
463
+ term.current = t;
464
+ queue.current.splice(0).forEach((f) => f());
465
+ requestAnimationFrame(scale);
466
+ })();
467
+ return () => {
468
+ dead = true;
469
+ };
470
+ }, [visible]);
471
+ useEffect(() => {
472
+ const w = wrap.current;
473
+ if (!w || typeof ResizeObserver === "undefined") return;
474
+ const ro = new ResizeObserver(scale);
475
+ ro.observe(w);
476
+ return () => ro.disconnect();
477
+ }, []);
478
+ useEffect(() => () => {
479
+ var _a;
480
+ (_a = term.current) == null ? void 0 : _a.dispose();
481
+ term.current = null;
482
+ }, []);
483
+ useEffect(() => {
484
+ if (visible) requestAnimationFrame(scale);
485
+ }, [visible]);
486
+ return /* @__PURE__ */ jsx("div", { className: "terminal-view", style: { display: visible ? void 0 : "none" }, "aria-label": "Terminal", children: /* @__PURE__ */ jsx("div", { className: "term-wrap", ref: wrap, children: /* @__PURE__ */ jsx("div", { className: "term-sizer", ref: sizer, children: /* @__PURE__ */ jsx("div", { className: "term-inner", ref: inner }) }) }) });
487
+ });
488
+ function useChat(transport, machine, agent, frames = false, term) {
489
+ const [items, setItems] = useState([]);
490
+ const [offers, setOffers] = useState([]);
491
+ const [loading, setLoading] = useState(true);
492
+ const [error, setError] = useState(null);
493
+ const [live, setLive] = useState("connecting");
494
+ const [size, setSize] = useState({ cols: 120, rows: 40 });
495
+ const [blocked, setBlocked] = useState(null);
496
+ const load = useCallback(() => transport.getChat(machine, agent).then((p) => {
497
+ setBlocked(p.blocked ?? null);
498
+ setItems((cur) => cur.length ? mergeItems(cur, p.rows ?? []) : p.rows ?? []);
499
+ setOffers(p.offers ?? []);
500
+ setError(null);
501
+ }).catch((e) => setError(e.message)).finally(() => setLoading(false)), [transport, machine, agent]);
502
+ useEffect(() => {
503
+ setItems([]);
504
+ setOffers([]);
505
+ setBlocked(null);
506
+ setLoading(true);
507
+ void load();
508
+ }, [load]);
509
+ useEffect(() => transport.events(machine, agent, { frames }, {
510
+ state: setLive,
511
+ resync: () => void load(),
512
+ chat: (p) => {
513
+ setBlocked(p.blocked ?? null);
514
+ setItems((cur) => mergeItems(cur, p.rows ?? []));
515
+ },
516
+ frame: (f) => {
517
+ var _a, _b;
518
+ const b = decodeBase64(f.data);
519
+ if (f.reset) (_a = term == null ? void 0 : term.current) == null ? void 0 : _a.reset(b);
520
+ else (_b = term == null ? void 0 : term.current) == null ? void 0 : _b.write(b);
521
+ },
522
+ size: (s2) => {
523
+ var _a;
524
+ setSize(s2);
525
+ (_a = term == null ? void 0 : term.current) == null ? void 0 : _a.resize(s2.cols, s2.rows);
526
+ },
527
+ offer: (o) => setOffers((cur) => cur.some((x) => x.id === o.id) ? cur : [...cur, o])
528
+ }), [transport, machine, agent, frames, load, term]);
529
+ return { items, offers, loading, error, live, size, blocked, reload: load };
530
+ }
531
+ const OpenCtx = createContext({ has: () => false, set: () => {
532
+ } });
533
+ const FileHrefCtx = createContext(null);
534
+ const fmt = (t) => t ? new Date(t).toLocaleString() : void 0;
535
+ function Details({ k, defaultOpen, className, children }) {
536
+ const o = useContext(OpenCtx);
537
+ const open = o.has("x:" + k) ? o.has(k) : !!defaultOpen;
538
+ return /* @__PURE__ */ jsx("details", { className, open, onToggle: (e) => {
539
+ const v = e.currentTarget.open;
540
+ if (v !== open) {
541
+ o.set("x:" + k, true);
542
+ o.set(k, v);
543
+ }
544
+ }, children: children(open) });
545
+ }
546
+ function Html({ html, cls }) {
547
+ return /* @__PURE__ */ jsx("div", { className: cls, dangerouslySetInnerHTML: { __html: html ?? "" } });
548
+ }
549
+ function Call({ c }) {
550
+ var _a, _b, _c, _d;
551
+ const fileHref = useContext(FileHrefCtx);
552
+ if (c.kind === "thinking") {
553
+ return /* @__PURE__ */ jsx(Details, { k: "t:" + c.key, className: "tool", children: () => {
554
+ var _a2;
555
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
556
+ /* @__PURE__ */ jsxs("summary", { children: [
557
+ /* @__PURE__ */ jsx("span", { className: "ico", children: "✦" }),
558
+ /* @__PURE__ */ jsx("span", { className: "t", children: "Thought" })
559
+ ] }),
560
+ /* @__PURE__ */ jsx("pre", { className: "tool-body", children: (_a2 = c.use) == null ? void 0 : _a2.text })
561
+ ] });
562
+ } });
563
+ }
564
+ const name = ((_a = c.use) == null ? void 0 : _a.tool) ?? ((_b = c.result) == null ? void 0 : _b.tool) ?? "Tool";
565
+ const arg = ((_c = c.use) == null ? void 0 : _c.summary) ?? "";
566
+ const [v, noun] = verb(name);
567
+ const isFile = noun === "file" && arg.startsWith("/") && !!fileHref;
568
+ const failed = ((_d = c.result) == null ? void 0 : _d.ok) === false;
569
+ return /* @__PURE__ */ jsx(Details, { k: "t:" + c.key, className: "tool" + (failed ? " failed" : ""), children: () => {
570
+ var _a2, _b2, _c2, _d2;
571
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
572
+ /* @__PURE__ */ jsxs("summary", { title: fmt(((_a2 = c.use) == null ? void 0 : _a2.time) ?? ((_b2 = c.result) == null ? void 0 : _b2.time)), children: [
573
+ /* @__PURE__ */ jsx("span", { className: "ico", children: toolIcon(name) }),
574
+ /* @__PURE__ */ jsx("span", { className: "t", children: v }),
575
+ arg && (isFile ? /* @__PURE__ */ jsx("a", { className: "arg fpath", href: fileHref(arg), children: arg }) : /* @__PURE__ */ jsx("span", { className: "arg", children: arg })),
576
+ !c.result ? /* @__PURE__ */ jsx("span", { className: "state", children: "…" }) : failed ? /* @__PURE__ */ jsx("span", { className: "state bad", "aria-label": "failed", children: "✗" }) : c.result.ok ? /* @__PURE__ */ jsx("span", { className: "state ok", "aria-label": "done", children: "✓" }) : null
577
+ ] }),
578
+ ((_c2 = c.use) == null ? void 0 : _c2.input) && /* @__PURE__ */ jsx("pre", { className: "tool-body", children: c.use.input }),
579
+ ((_d2 = c.result) == null ? void 0 : _d2.text) && /* @__PURE__ */ jsx("pre", { className: "tool-body result", children: c.result.text })
580
+ ] });
581
+ } });
582
+ }
583
+ function Body({ item }) {
584
+ if (item.kind === "output") return /* @__PURE__ */ jsx("pre", { className: "out", dangerouslySetInnerHTML: { __html: item.html ?? "" } });
585
+ return item.html != null ? /* @__PURE__ */ jsx(Html, { html: item.html, cls: "md" }) : /* @__PURE__ */ jsx("div", { className: "md", children: /* @__PURE__ */ jsx("p", { children: item.text }) });
586
+ }
587
+ function ChatRowImpl({ row }) {
588
+ const first = row.items[0];
589
+ switch (row.kind) {
590
+ case "user":
591
+ return /* @__PURE__ */ jsx("div", { className: "msg user", "data-id": row.key, title: fmt(first.time), children: /* @__PURE__ */ jsx("div", { className: "bubble", children: first.text ?? stripTags(first.html) }) });
592
+ case "text":
593
+ return /* @__PURE__ */ jsx("div", { className: "msg asst", "data-id": row.key, title: fmt(first.time), children: /* @__PURE__ */ jsx(Body, { item: first }) });
594
+ case "block": {
595
+ const cmd = row.items.find((i) => i.kind === "command");
596
+ const out = row.items.find((i) => i.kind === "output");
597
+ const lines = (out == null ? void 0 : out.lines) ?? ((out == null ? void 0 : out.html) ? out.html.split("\n").length : 0);
598
+ return /* @__PURE__ */ jsx(Details, { k: "b:" + row.key, className: "block", defaultOpen: lines <= 40, children: () => /* @__PURE__ */ jsxs(Fragment, { children: [
599
+ /* @__PURE__ */ jsxs("summary", { children: [
600
+ /* @__PURE__ */ jsx("span", { className: "prompt", children: "$" }),
601
+ /* @__PURE__ */ jsx("span", { className: "cmd", children: (cmd == null ? void 0 : cmd.text) ?? "output" }),
602
+ lines > 0 && /* @__PURE__ */ jsxs("span", { className: "state", children: [
603
+ lines,
604
+ " ",
605
+ lines === 1 ? "line" : "lines"
606
+ ] })
607
+ ] }),
608
+ out && /* @__PURE__ */ jsx(Body, { item: out })
609
+ ] }) });
610
+ }
611
+ default: {
612
+ const calls = pairCalls(row.items);
613
+ if (calls.length === 1) return /* @__PURE__ */ jsx("div", { "data-id": row.key, children: /* @__PURE__ */ jsx(Call, { c: calls[0] }) });
614
+ const tools = calls.filter((c) => c.kind === "tool");
615
+ const label = phrase(tools.map((c) => {
616
+ var _a, _b;
617
+ return ((_a = c.use) == null ? void 0 : _a.tool) ?? ((_b = c.result) == null ? void 0 : _b.tool) ?? "Tool";
618
+ }), calls.length - tools.length);
619
+ const bad = tools.some((c) => {
620
+ var _a;
621
+ return ((_a = c.result) == null ? void 0 : _a.ok) === false;
622
+ });
623
+ const pending = tools.some((c) => !c.result);
624
+ const ok = tools.length > 0 && tools.every((c) => {
625
+ var _a;
626
+ return ((_a = c.result) == null ? void 0 : _a.ok) === true;
627
+ });
628
+ return /* @__PURE__ */ jsx(Details, { k: "g:" + row.key, className: "tools", children: () => /* @__PURE__ */ jsxs(Fragment, { children: [
629
+ /* @__PURE__ */ jsxs("summary", { children: [
630
+ /* @__PURE__ */ jsx("span", { className: "ico", children: "⋯" }),
631
+ /* @__PURE__ */ jsx("span", { className: "t", children: label }),
632
+ bad ? /* @__PURE__ */ jsx("span", { className: "state bad", "aria-label": "failed", children: "✗" }) : pending ? /* @__PURE__ */ jsx("span", { className: "state", children: "…" }) : ok ? /* @__PURE__ */ jsx("span", { className: "state ok", "aria-label": "done", children: "✓" }) : null
633
+ ] }),
634
+ /* @__PURE__ */ jsx("div", { className: "tool-list", children: calls.map((c) => /* @__PURE__ */ jsx(Call, { c }, c.key)) })
635
+ ] }) });
636
+ }
637
+ }
638
+ }
639
+ function stripTags(html) {
640
+ return (html ?? "").replace(/<[^>]*>/g, "").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&");
641
+ }
642
+ const ChatRow = memo(ChatRowImpl, (a, b) => a.row.stamp === b.row.stamp && a.row.kind === b.row.kind);
643
+ function choiceKeys(b, key) {
644
+ const keys = (b.choices ?? []).map((c) => c.key);
645
+ const to = keys.indexOf(key);
646
+ const from = b.selected ? keys.indexOf(b.selected) : -1;
647
+ if (to < 0) return [];
648
+ if (from < 0) return [key];
649
+ const d = to - from;
650
+ return [...Array(Math.abs(d)).fill(d > 0 ? "down" : "up"), "enter"];
651
+ }
652
+ function ChoiceBar({ blocked, onKeys }) {
653
+ const [busy, setBusy] = useState(false);
654
+ const choices = blocked.choices ?? [];
655
+ if (!choices.length) return null;
656
+ const pick = async (keys) => {
657
+ if (!keys.length || busy) return;
658
+ setBusy(true);
659
+ try {
660
+ await onKeys(keys);
661
+ } finally {
662
+ setBusy(false);
663
+ }
664
+ };
665
+ return /* @__PURE__ */ jsxs("div", { className: "blocked chat-col", role: "group", "aria-label": "Agent is waiting for your answer", children: [
666
+ /* @__PURE__ */ jsx("div", { className: "blocked-label", children: "Waiting for you" }),
667
+ blocked.question && /* @__PURE__ */ jsx("pre", { className: "blocked-q", children: blocked.question }),
668
+ /* @__PURE__ */ jsxs("div", { className: "quick", children: [
669
+ choices.map((c) => /* @__PURE__ */ jsxs(
670
+ "button",
671
+ {
672
+ type: "button",
673
+ disabled: busy,
674
+ className: c.key === blocked.selected ? "chosen" : void 0,
675
+ onClick: () => void pick(choiceKeys(blocked, c.key)),
676
+ children: [
677
+ c.key,
678
+ ". ",
679
+ c.label
680
+ ]
681
+ },
682
+ c.key
683
+ )),
684
+ /* @__PURE__ */ jsx("button", { type: "button", className: "ghost", disabled: busy, onClick: () => void pick(["esc"]), children: "Esc" })
685
+ ] })
686
+ ] });
687
+ }
688
+ function VirtualListInner({ items, getKey, render, estimate = 90, overscan = 900, className = "", onPinnedChange, header }, ref) {
689
+ const sc = useRef(null);
690
+ const heights = useRef(/* @__PURE__ */ new Map());
691
+ const nodes = useRef(/* @__PURE__ */ new Map());
692
+ const [version, setVersion] = useState(0);
693
+ const [scrollTop, setScrollTop] = useState(0);
694
+ const [viewport, setViewport] = useState(() => typeof window === "undefined" ? 800 : window.innerHeight);
695
+ const pinned = useRef(true);
696
+ const ro = useRef(null);
697
+ const offs = useMemo(
698
+ () => offsets(items.length, heights.current, (i) => getKey(items[i]), estimate),
699
+ // eslint-disable-next-line react-hooks/exhaustive-deps
700
+ [items, version, estimate]
701
+ );
702
+ const total = offs[items.length];
703
+ const effTop = pinned.current ? Math.max(0, total - viewport) : scrollTop;
704
+ const w = computeWindow(offs, effTop, viewport, overscan);
705
+ const measure = useCallback(() => {
706
+ let changed = false;
707
+ let above = 0;
708
+ const el = sc.current;
709
+ const top = (el == null ? void 0 : el.scrollTop) ?? 0;
710
+ const o = offs;
711
+ items.forEach((it, i) => {
712
+ const n = nodes.current.get(getKey(it));
713
+ if (!n) return;
714
+ const h = n.offsetHeight;
715
+ if (h <= 0) return;
716
+ const k = getKey(it);
717
+ const prev = heights.current.get(k) ?? estimate;
718
+ if (Math.abs(prev - h) > 0.5) {
719
+ heights.current.set(k, h);
720
+ changed = true;
721
+ if (o[i + 1] <= top) above += h - prev;
722
+ } else if (!heights.current.has(k)) heights.current.set(k, h);
723
+ });
724
+ if (changed) {
725
+ if (above && el && !pinned.current) el.scrollTop = top + above;
726
+ setVersion((v) => v + 1);
727
+ }
728
+ }, [items, getKey, estimate, offs]);
729
+ useLayoutEffect(() => {
730
+ measure();
731
+ if (pinned.current && sc.current) sc.current.scrollTop = sc.current.scrollHeight;
732
+ });
733
+ useLayoutEffect(() => {
734
+ const el = sc.current;
735
+ if (!el) return;
736
+ const size = () => setViewport(el.clientHeight || window.innerHeight);
737
+ size();
738
+ if (typeof ResizeObserver === "undefined") return;
739
+ const obs = new ResizeObserver(() => {
740
+ size();
741
+ });
742
+ obs.observe(el);
743
+ ro.current = new ResizeObserver(() => measure());
744
+ nodes.current.forEach((n) => {
745
+ var _a;
746
+ return (_a = ro.current) == null ? void 0 : _a.observe(n);
747
+ });
748
+ return () => {
749
+ var _a;
750
+ obs.disconnect();
751
+ (_a = ro.current) == null ? void 0 : _a.disconnect();
752
+ };
753
+ }, []);
754
+ const onScroll = () => {
755
+ const el = sc.current;
756
+ if (!el) return;
757
+ setScrollTop(el.scrollTop);
758
+ const p = atBottom(el.scrollTop, el.clientHeight || viewport, el.scrollHeight);
759
+ if (p !== pinned.current) {
760
+ pinned.current = p;
761
+ onPinnedChange == null ? void 0 : onPinnedChange(p);
762
+ }
763
+ };
764
+ useImperativeHandle(ref, () => ({
765
+ scrollToBottom() {
766
+ pinned.current = true;
767
+ onPinnedChange == null ? void 0 : onPinnedChange(true);
768
+ if (sc.current) sc.current.scrollTop = sc.current.scrollHeight;
769
+ setVersion((v) => v + 1);
770
+ },
771
+ scrollToIndex(i) {
772
+ pinned.current = false;
773
+ onPinnedChange == null ? void 0 : onPinnedChange(false);
774
+ const y = Math.max(0, (offs[i] ?? 0) - 60);
775
+ if (sc.current) sc.current.scrollTop = y;
776
+ setScrollTop(y);
777
+ }
778
+ }));
779
+ return /* @__PURE__ */ jsx("div", { className: "chat-scroll " + className, ref: sc, onScroll, "data-testid": "chat-scroll", children: /* @__PURE__ */ jsxs("div", { className: "chat-col", children: [
780
+ header,
781
+ /* @__PURE__ */ jsx("div", { className: "chat-pad", style: { height: w.padTop }, "aria-hidden": "true" }),
782
+ items.slice(w.start, w.end).map((it, n) => {
783
+ const k = getKey(it);
784
+ return /* @__PURE__ */ jsx(
785
+ "div",
786
+ {
787
+ className: "vrow",
788
+ "data-key": k,
789
+ ref: (el) => {
790
+ var _a, _b;
791
+ const prev = nodes.current.get(k);
792
+ if (prev && prev !== el) (_a = ro.current) == null ? void 0 : _a.unobserve(prev);
793
+ if (el) {
794
+ nodes.current.set(k, el);
795
+ (_b = ro.current) == null ? void 0 : _b.observe(el);
796
+ } else nodes.current.delete(k);
797
+ },
798
+ children: render(it, w.start + n)
799
+ },
800
+ k
801
+ );
802
+ }),
803
+ /* @__PURE__ */ jsx("div", { className: "chat-pad", style: { height: w.padBottom }, "aria-hidden": "true" })
804
+ ] }) });
805
+ }
806
+ const VirtualList = forwardRef(VirtualListInner);
807
+ const keyOf = (r) => r.key;
808
+ const ChatView = forwardRef(function ChatView2({ items, loading, error, blocked, status, offline, onKeys, fileHref, onNavigate, searchOpen, onSearchClose, footer, className = "" }, ref) {
809
+ const list = useRef(null);
810
+ const rows = useMemo(() => buildRows(items), [items]);
811
+ const [pinned, setPinned] = useState(true);
812
+ const [needle, setNeedle] = useState("");
813
+ const [hit, setHit] = useState(0);
814
+ const open = useRef(/* @__PURE__ */ new Set());
815
+ const openCtx = useMemo(() => ({ has: (k) => open.current.has(k), set: (k, v) => {
816
+ if (v) open.current.add(k);
817
+ else open.current.delete(k);
818
+ } }), []);
819
+ useImperativeHandle(ref, () => ({ scrollToBottom: () => {
820
+ var _a;
821
+ return (_a = list.current) == null ? void 0 : _a.scrollToBottom();
822
+ } }));
823
+ const matches2 = useMemo(() => {
824
+ const n = needle.trim().toLowerCase();
825
+ if (!n) return [];
826
+ return rows.flatMap((r, i) => r.items.some((it) => (it.text ?? stripTags(it.html) + " " + (it.summary ?? "")).toLowerCase().includes(n)) ? [i] : []);
827
+ }, [rows, needle]);
828
+ const jump = (d) => {
829
+ var _a;
830
+ if (!matches2.length) return;
831
+ const n = (hit + d + matches2.length) % matches2.length;
832
+ setHit(n);
833
+ (_a = list.current) == null ? void 0 : _a.scrollToIndex(matches2[n]);
834
+ };
835
+ const onClick = (e) => {
836
+ var _a, _b, _c;
837
+ const t = e.target;
838
+ const copy = t.closest(".codeblk .copy");
839
+ if (copy) {
840
+ const code = ((_b = (_a = copy.closest(".codeblk")) == null ? void 0 : _a.querySelector("code")) == null ? void 0 : _b.textContent) ?? "";
841
+ void ((_c = navigator.clipboard) == null ? void 0 : _c.writeText(code).then(() => {
842
+ copy.textContent = "Copied";
843
+ setTimeout(() => {
844
+ copy.textContent = "Copy";
845
+ }, 1500);
846
+ }));
847
+ return;
848
+ }
849
+ const a = t.closest("a[href]");
850
+ if (!a || !onNavigate || a.target === "_blank" || e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
851
+ if (onNavigate(a.href, a)) e.preventDefault();
852
+ };
853
+ const header = loading ? /* @__PURE__ */ jsxs("div", { className: "skel-chat", "aria-hidden": "true", children: [
854
+ /* @__PURE__ */ jsx("div", { className: "skel bubble-r" }),
855
+ /* @__PURE__ */ jsx("div", { className: "skel line w90" }),
856
+ /* @__PURE__ */ jsx("div", { className: "skel line w80" }),
857
+ /* @__PURE__ */ jsx("div", { className: "skel tool" })
858
+ ] }) : rows.length === 0 ? /* @__PURE__ */ jsx("p", { className: "empty chat-empty", children: error ?? "Nothing here yet." }) : null;
859
+ return /* @__PURE__ */ jsxs("div", { className: "chat " + className, onClick, children: [
860
+ searchOpen && /* @__PURE__ */ jsxs("div", { className: "chat-search", role: "search", children: [
861
+ /* @__PURE__ */ jsx(
862
+ "input",
863
+ {
864
+ type: "search",
865
+ autoFocus: true,
866
+ "aria-label": "Search in chat",
867
+ placeholder: "Search in chat",
868
+ value: needle,
869
+ onChange: (e) => {
870
+ setNeedle(e.target.value);
871
+ setHit(0);
872
+ },
873
+ onKeyDown: (e) => {
874
+ if (e.key === "Enter") jump(e.shiftKey ? -1 : 1);
875
+ if (e.key === "Escape") onSearchClose == null ? void 0 : onSearchClose();
876
+ }
877
+ }
878
+ ),
879
+ /* @__PURE__ */ jsx("span", { className: "muted", "aria-live": "polite", children: needle ? `${matches2.length ? hit + 1 : 0}/${matches2.length}` : "" }),
880
+ /* @__PURE__ */ jsx("button", { type: "button", className: "icon", "aria-label": "Previous match", onClick: () => jump(-1), children: "↑" }),
881
+ /* @__PURE__ */ jsx("button", { type: "button", className: "icon", "aria-label": "Next match", onClick: () => jump(1), children: "↓" })
882
+ ] }),
883
+ /* @__PURE__ */ jsx(FileHrefCtx.Provider, { value: fileHref ?? null, children: /* @__PURE__ */ jsx(OpenCtx.Provider, { value: openCtx, children: /* @__PURE__ */ jsx(VirtualList, { ref: list, items: rows, getKey: keyOf, onPinnedChange: setPinned, header, render: (r) => /* @__PURE__ */ jsx(ChatRow, { row: r }) }) }) }),
884
+ footer,
885
+ blocked && !offline && onKeys && /* @__PURE__ */ jsx(ChoiceBar, { blocked, onKeys: async (keys) => {
886
+ var _a;
887
+ await onKeys(keys);
888
+ (_a = list.current) == null ? void 0 : _a.scrollToBottom();
889
+ } }),
890
+ !pinned && /* @__PURE__ */ jsx("button", { type: "button", className: "jump show", onClick: () => {
891
+ var _a;
892
+ return (_a = list.current) == null ? void 0 : _a.scrollToBottom();
893
+ }, children: "Jump to latest" }),
894
+ status === "working" && !offline && /* @__PURE__ */ jsxs("div", { className: "live live-working", role: "status", children: [
895
+ /* @__PURE__ */ jsx("span", { className: "dot", "aria-hidden": "true" }),
896
+ "working…"
897
+ ] })
898
+ ] });
899
+ });
900
+ const s = { width: 20, height: 20, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true };
901
+ const IconSidebar = () => /* @__PURE__ */ jsxs("svg", { ...s, children: [
902
+ /* @__PURE__ */ jsx("rect", { x: "3", y: "4", width: "18", height: "16", rx: "3" }),
903
+ /* @__PURE__ */ jsx("path", { d: "M9 4v16" })
904
+ ] });
905
+ const IconBack = () => /* @__PURE__ */ jsx("svg", { ...s, children: /* @__PURE__ */ jsx("path", { d: "m15 18-6-6 6-6" }) });
906
+ const IconMore = () => /* @__PURE__ */ jsxs("svg", { ...s, children: [
907
+ /* @__PURE__ */ jsx("circle", { cx: "5", cy: "12", r: "1" }),
908
+ /* @__PURE__ */ jsx("circle", { cx: "12", cy: "12", r: "1" }),
909
+ /* @__PURE__ */ jsx("circle", { cx: "19", cy: "12", r: "1" })
910
+ ] });
911
+ const IconTerminal = () => /* @__PURE__ */ jsxs("svg", { ...s, children: [
912
+ /* @__PURE__ */ jsx("path", { d: "m4 17 6-5-6-5" }),
913
+ /* @__PURE__ */ jsx("path", { d: "M12 19h8" })
914
+ ] });
915
+ const IconChat = () => /* @__PURE__ */ jsx("svg", { ...s, children: /* @__PURE__ */ jsx("path", { d: "M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12Z" }) });
916
+ const IconPlus = () => /* @__PURE__ */ jsx("svg", { ...s, children: /* @__PURE__ */ jsx("path", { d: "M12 5v14M5 12h14" }) });
917
+ const IconUp = () => /* @__PURE__ */ jsx("svg", { ...s, children: /* @__PURE__ */ jsx("path", { d: "M12 19V5M5 12l7-7 7 7" }) });
918
+ const IconFile = () => /* @__PURE__ */ jsxs("svg", { ...s, children: [
919
+ /* @__PURE__ */ jsx("path", { d: "M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8Z" }),
920
+ /* @__PURE__ */ jsx("path", { d: "M14 3v5h5" })
921
+ ] });
922
+ function slashMatches(text, commands) {
923
+ if (!/^\/[^\s]*$/.test(text)) return [];
924
+ const t = text.toLowerCase();
925
+ return commands.filter((c) => c.name.toLowerCase().startsWith(t) && c.name.toLowerCase() !== t).slice(0, 60);
926
+ }
927
+ const none = [];
928
+ function Composer({ draftKey, storage = defaultStorage, commands = none, terminal = false, attachments = none, uploading = false, onRemoveAttachment, onFiles, onSend, onKey }) {
929
+ const [text, setText] = useState(() => storage.get("draft:" + draftKey) ?? "");
930
+ const [sel, setSel] = useState(0);
931
+ const [dismissed, setDismissed] = useState(false);
932
+ const ta = useRef(null);
933
+ const file = useRef(null);
934
+ const id = useId();
935
+ const popId = "slash-" + id;
936
+ useEffect(() => {
937
+ storage.set("draft:" + draftKey, text || null);
938
+ }, [text, draftKey, storage]);
939
+ useEffect(() => {
940
+ const t = ta.current;
941
+ if (t) {
942
+ t.style.height = "auto";
943
+ t.style.height = Math.min(t.scrollHeight, 220) + "px";
944
+ }
945
+ }, [text]);
946
+ const options = useMemo(() => dismissed ? [] : slashMatches(text, commands), [text, commands, dismissed]);
947
+ const open = options.length > 0;
948
+ const pick = (c) => {
949
+ var _a;
950
+ setText(c.name + " ");
951
+ setSel(0);
952
+ (_a = ta.current) == null ? void 0 : _a.focus();
953
+ };
954
+ const coarse = typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches;
955
+ const send = async () => {
956
+ const t = text.trimEnd();
957
+ if (!t && attachments.length === 0) return;
958
+ setText("");
959
+ setDismissed(false);
960
+ await onSend(t);
961
+ };
962
+ const keydown = (e) => {
963
+ if (open) {
964
+ if (e.key === "ArrowDown") {
965
+ e.preventDefault();
966
+ setSel((s2) => (s2 + 1) % options.length);
967
+ return;
968
+ }
969
+ if (e.key === "ArrowUp") {
970
+ e.preventDefault();
971
+ setSel((s2) => (s2 - 1 + options.length) % options.length);
972
+ return;
973
+ }
974
+ if (e.key === "Tab" || e.key === "Enter" && !e.shiftKey) {
975
+ e.preventDefault();
976
+ pick(options[Math.min(sel, options.length - 1)]);
977
+ return;
978
+ }
979
+ if (e.key === "Escape") {
980
+ e.preventDefault();
981
+ setDismissed(true);
982
+ return;
983
+ }
984
+ }
985
+ if (e.key === "Enter" && !e.shiftKey && !coarse && !e.nativeEvent.isComposing) {
986
+ e.preventDefault();
987
+ void send();
988
+ }
989
+ };
990
+ const paste = (e) => {
991
+ const imgs = [...e.clipboardData.files].filter((f) => f.type.startsWith("image/"));
992
+ if (imgs.length && onFiles) {
993
+ e.preventDefault();
994
+ onFiles(imgs);
995
+ }
996
+ };
997
+ return /* @__PURE__ */ jsxs("div", { className: "composer-wrap", children: [
998
+ /* @__PURE__ */ jsx("div", { className: "slash-pop", role: "listbox", id: popId, "aria-label": "Commands", hidden: !open, children: options.map((c, i) => /* @__PURE__ */ jsxs("div", { id: `${popId}-${i}`, role: "option", "aria-selected": i === sel, onMouseDown: (e) => {
999
+ e.preventDefault();
1000
+ pick(c);
1001
+ }, children: [
1002
+ /* @__PURE__ */ jsx("span", { className: "slash-name", children: c.name }),
1003
+ /* @__PURE__ */ jsx("span", { className: "slash-desc", children: c.description })
1004
+ ] }, c.name)) }),
1005
+ /* @__PURE__ */ jsxs("div", { className: "composer", children: [
1006
+ attachments.length > 0 && /* @__PURE__ */ jsx("div", { className: "attachments", children: attachments.map((a) => /* @__PURE__ */ jsxs("span", { className: "attachment", title: a.path, children: [
1007
+ a.preview && /* @__PURE__ */ jsx("img", { className: "thumb", src: a.preview, alt: "" }),
1008
+ a.name,
1009
+ /* @__PURE__ */ jsx("button", { type: "button", "aria-label": "Remove " + a.name, onClick: () => onRemoveAttachment == null ? void 0 : onRemoveAttachment(a), children: "×" })
1010
+ ] }, a.path)) }),
1011
+ /* @__PURE__ */ jsx(
1012
+ "textarea",
1013
+ {
1014
+ ref: ta,
1015
+ rows: 1,
1016
+ value: text,
1017
+ "aria-label": "Message",
1018
+ "aria-autocomplete": "list",
1019
+ "aria-controls": popId,
1020
+ "aria-expanded": open,
1021
+ "aria-activedescendant": open ? `${popId}-${Math.min(sel, options.length - 1)}` : void 0,
1022
+ placeholder: uploading ? "Uploading image…" : attachments.length ? "Add a message, or send the image" : terminal ? "Type into the terminal" : "Type a message",
1023
+ onChange: (e) => {
1024
+ setText(e.target.value);
1025
+ setSel(0);
1026
+ setDismissed(false);
1027
+ },
1028
+ onKeyDown: keydown,
1029
+ onPaste: paste
1030
+ }
1031
+ ),
1032
+ /* @__PURE__ */ jsxs("div", { className: "composer-row", children: [
1033
+ onFiles && /* @__PURE__ */ jsxs(Fragment, { children: [
1034
+ /* @__PURE__ */ jsx(
1035
+ "input",
1036
+ {
1037
+ ref: file,
1038
+ className: "hidden-file",
1039
+ type: "file",
1040
+ accept: "image/*",
1041
+ multiple: true,
1042
+ tabIndex: -1,
1043
+ "aria-label": "Attach an image",
1044
+ onChange: (e) => {
1045
+ var _a;
1046
+ if ((_a = e.target.files) == null ? void 0 : _a.length) onFiles == null ? void 0 : onFiles([...e.target.files]);
1047
+ e.target.value = "";
1048
+ }
1049
+ }
1050
+ ),
1051
+ /* @__PURE__ */ jsx("button", { type: "button", className: "icon attach", title: "Attach an image (paste and drop work too)", "aria-label": "Attach an image", onClick: () => {
1052
+ var _a;
1053
+ return (_a = file.current) == null ? void 0 : _a.click();
1054
+ }, children: /* @__PURE__ */ jsx(IconPlus, {}) })
1055
+ ] }),
1056
+ terminal && /* @__PURE__ */ jsxs(Fragment, { children: [
1057
+ /* @__PURE__ */ jsx("button", { type: "button", className: "key", title: "Esc", onClick: () => onKey == null ? void 0 : onKey("esc"), children: "esc" }),
1058
+ /* @__PURE__ */ jsx("button", { type: "button", className: "key", title: "Ctrl-C", onClick: () => onKey == null ? void 0 : onKey("ctrl+c"), children: "^C" })
1059
+ ] }),
1060
+ /* @__PURE__ */ jsx("span", { className: "grow" }),
1061
+ /* @__PURE__ */ jsx("button", { type: "button", className: "send", "aria-label": "Send", onClick: () => void send(), children: /* @__PURE__ */ jsx(IconUp, {}) })
1062
+ ] })
1063
+ ] })
1064
+ ] });
1065
+ }
1066
+ function PaneHeader({ title, agent = "", session, status = "", statusText = "", cwd, leading, view = "chat", onToggleView, actions }) {
1067
+ return /* @__PURE__ */ jsxs("header", { className: "pane-bar", children: [
1068
+ leading,
1069
+ /* @__PURE__ */ jsxs("div", { className: "who", title: cwd || void 0, children: [
1070
+ /* @__PURE__ */ jsx("span", { className: "badge-a", "data-agent": agentKey(agent), "aria-hidden": "true", children: agentIcon(agent) }),
1071
+ /* @__PURE__ */ jsx("h1", { className: "name", children: title }),
1072
+ session && /* @__PURE__ */ jsx("span", { className: "pill", children: session }),
1073
+ /* @__PURE__ */ jsx("span", { className: "state state-" + (status || "none"), role: "status", children: statusText })
1074
+ ] }),
1075
+ onToggleView && /* @__PURE__ */ jsx("button", { type: "button", className: "icon tgl" + (view === "terminal" ? " on" : ""), "aria-pressed": view === "terminal", "aria-label": "Terminal", title: view === "terminal" ? "Back to chat" : "Terminal", onClick: onToggleView, children: view === "terminal" ? /* @__PURE__ */ jsx(IconChat, {}) : /* @__PURE__ */ jsx(IconTerminal, {}) }),
1076
+ actions
1077
+ ] });
1078
+ }
1079
+ const plainClick = (e) => e.button === 0 && !e.metaKey && !e.ctrlKey && !e.shiftKey && !e.altKey;
1080
+ function Sidebar({ items, loaded = true, current, hrefFor, onOpen, filter: filterProp, onFilterChange, store = defaultStorage, renderGroupExtra, renderSubtitle, header, footer, empty }) {
1081
+ const [own, setOwn] = useState("");
1082
+ const filter = filterProp ?? own;
1083
+ const setFilter = (f) => {
1084
+ if (filterProp === void 0) setOwn(f);
1085
+ onFilterChange == null ? void 0 : onFilterChange(f);
1086
+ };
1087
+ const [showAll, setShowAll] = useState(() => store.get("showall") === "1");
1088
+ const [folded, setFolded] = useState(() => new Set((store.get("folded") ?? "").split("\n").filter(Boolean)));
1089
+ const search = useRef(null);
1090
+ useEffect(() => {
1091
+ const k = (e) => {
1092
+ var _a;
1093
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
1094
+ e.preventDefault();
1095
+ (_a = search.current) == null ? void 0 : _a.focus();
1096
+ }
1097
+ };
1098
+ window.addEventListener("keydown", k);
1099
+ return () => window.removeEventListener("keydown", k);
1100
+ }, []);
1101
+ const rows = useMemo(() => items.filter((i) => i.machine.online).flatMap(({ machine, tree }) => ((tree == null ? void 0 : tree.panes) ?? []).map((pane) => ({ machineId: machine.id, machineName: machine.name, pane, session: workspaceLabel(tree, pane.workspace_id) }))), [items]);
1102
+ const groups = useMemo(() => groupRows(rows, filter, showAll), [rows, filter, showAll]);
1103
+ const offline = items.filter((i) => !i.machine.online);
1104
+ const fold = (k) => {
1105
+ const n = new Set(folded);
1106
+ if (!n.delete(k)) n.add(k);
1107
+ setFolded(n);
1108
+ store.set("folded", [...n].join("\n"));
1109
+ };
1110
+ const click = (m, p) => (e) => {
1111
+ if (!onOpen || !plainClick(e)) return;
1112
+ e.preventDefault();
1113
+ onOpen(m, p, e);
1114
+ };
1115
+ return /* @__PURE__ */ jsxs("aside", { className: "side", "aria-label": "Agents", children: [
1116
+ header && /* @__PURE__ */ jsx("div", { className: "side-head", children: header }),
1117
+ /* @__PURE__ */ jsxs("div", { className: "side-search", children: [
1118
+ /* @__PURE__ */ jsx("input", { ref: search, type: "search", placeholder: "Search agents", "aria-label": "Search agents", value: filter, onChange: (e) => setFilter(e.target.value) }),
1119
+ /* @__PURE__ */ jsx("kbd", { children: "⌘K" })
1120
+ ] }),
1121
+ /* @__PURE__ */ jsxs("nav", { className: "side-list", "aria-label": "Panes", children: [
1122
+ loaded && items.length === 0 && (empty ?? /* @__PURE__ */ jsx("p", { className: "empty pad", children: "No machines are linked yet." })),
1123
+ groups.map((g) => {
1124
+ const open = !folded.has(g.key);
1125
+ return /* @__PURE__ */ jsxs("section", { className: "proj", children: [
1126
+ /* @__PURE__ */ jsxs("button", { type: "button", className: "proj-head", title: g.path, "aria-expanded": open, onClick: () => fold(g.key), children: [
1127
+ /* @__PURE__ */ jsx("span", { className: "chev", children: open ? "▾" : "▸" }),
1128
+ /* @__PURE__ */ jsx("span", { className: "proj-name", children: g.name }),
1129
+ /* @__PURE__ */ jsx("span", { className: "proj-n", children: g.rows.length }),
1130
+ renderGroupExtra == null ? void 0 : renderGroupExtra(g)
1131
+ ] }),
1132
+ open && g.rows.map((r) => {
1133
+ const st = paneStatus(r.pane);
1134
+ const agent = paneAgent(r.pane);
1135
+ const cur = (current == null ? void 0 : current.machine) === r.machineId && (current == null ? void 0 : current.pane) === r.pane.pane_id;
1136
+ return /* @__PURE__ */ jsxs(
1137
+ "a",
1138
+ {
1139
+ href: hrefFor == null ? void 0 : hrefFor(r.machineId, r.pane.pane_id),
1140
+ className: "ent" + (cur ? " cur" : ""),
1141
+ title: paneCwd(r.pane),
1142
+ onClick: click(r.machineId, r.pane.pane_id),
1143
+ "aria-current": cur ? "page" : void 0,
1144
+ children: [
1145
+ /* @__PURE__ */ jsx("span", { className: "dot dot-" + (st || "none"), "aria-hidden": "true" }),
1146
+ /* @__PURE__ */ jsx("span", { className: "badge-a", "data-agent": agentKey(agent), "aria-hidden": "true", children: agentIcon(agent) }),
1147
+ /* @__PURE__ */ jsx("span", { className: "ent-title", children: displayName(r.pane) }),
1148
+ /* @__PURE__ */ jsx("span", { className: "ent-time", children: st === "blocked" ? "!" : "" }),
1149
+ /* @__PURE__ */ jsxs("span", { className: "ent-sub", children: [
1150
+ st === "blocked" && /* @__PURE__ */ jsx("b", { className: "needs", children: "needs you · " }),
1151
+ renderSubtitle ? renderSubtitle(r) : /* @__PURE__ */ jsxs(Fragment, { children: [
1152
+ agent && /* @__PURE__ */ jsxs(Fragment, { children: [
1153
+ /* @__PURE__ */ jsx("b", { className: "kind", children: agent.toLowerCase() }),
1154
+ " · "
1155
+ ] }),
1156
+ r.machineName,
1157
+ " · ",
1158
+ r.session
1159
+ ] })
1160
+ ] })
1161
+ ]
1162
+ },
1163
+ r.machineId + "/" + r.pane.pane_id
1164
+ );
1165
+ })
1166
+ ] }, g.key);
1167
+ }),
1168
+ filter && groups.length === 0 && /* @__PURE__ */ jsx("p", { className: "empty pad", children: "No match." }),
1169
+ offline.length > 0 && !filter && /* @__PURE__ */ jsxs("section", { className: "proj", children: [
1170
+ /* @__PURE__ */ jsx("div", { className: "proj-head static", children: /* @__PURE__ */ jsx("span", { className: "proj-name", children: "Offline machines" }) }),
1171
+ offline.map(({ machine }) => /* @__PURE__ */ jsxs("a", { href: hrefFor == null ? void 0 : hrefFor(machine.id), className: "ent off", onClick: click(machine.id), children: [
1172
+ /* @__PURE__ */ jsx("span", { className: "dot dot-none" }),
1173
+ /* @__PURE__ */ jsx("span", { className: "ent-title", children: machine.name || machine.id }),
1174
+ /* @__PURE__ */ jsx("span", {})
1175
+ ] }, machine.id))
1176
+ ] })
1177
+ ] }),
1178
+ /* @__PURE__ */ jsxs("div", { className: "side-foot", children: [
1179
+ /* @__PURE__ */ jsxs("label", { className: "toggle", children: [
1180
+ /* @__PURE__ */ jsx("input", { type: "checkbox", checked: showAll, onChange: (e) => {
1181
+ setShowAll(e.target.checked);
1182
+ store.set("showall", e.target.checked ? "1" : null);
1183
+ } }),
1184
+ " Show all panes"
1185
+ ] }),
1186
+ footer
1187
+ ] })
1188
+ ] });
1189
+ }
1190
+ export {
1191
+ ChatRow,
1192
+ ChatView,
1193
+ ChoiceBar,
1194
+ Composer,
1195
+ FileHrefCtx,
1196
+ IconBack,
1197
+ IconChat,
1198
+ IconFile,
1199
+ IconMore,
1200
+ IconPlus,
1201
+ IconSidebar,
1202
+ IconTerminal,
1203
+ IconUp,
1204
+ OpenCtx,
1205
+ PaneHeader,
1206
+ Sidebar,
1207
+ Terminal,
1208
+ TransportError,
1209
+ VirtualList,
1210
+ agentIcon,
1211
+ agentKey,
1212
+ atBottom,
1213
+ backoff,
1214
+ buildRows,
1215
+ choiceKeys,
1216
+ computeWindow,
1217
+ connectSSE,
1218
+ decodeBase64,
1219
+ defaultStorage,
1220
+ displayName,
1221
+ folderName,
1222
+ groupRows,
1223
+ httpTransport,
1224
+ isAgent,
1225
+ matches,
1226
+ memoryStorage,
1227
+ mergeItems,
1228
+ offsets,
1229
+ pairCalls,
1230
+ paneAgent,
1231
+ paneCwd,
1232
+ paneId,
1233
+ paneStatus,
1234
+ phrase,
1235
+ slashMatches,
1236
+ statusRank,
1237
+ stripTags,
1238
+ toolIcon,
1239
+ useChat,
1240
+ verb,
1241
+ webStorage,
1242
+ workspaceLabel
1243
+ };
1244
+ //# sourceMappingURL=index.js.map