@bypane/cli 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/LICENSE +21 -0
- package/README.md +188 -2
- package/dist/app-host.js +408 -0
- package/dist/app-protocol.js +1 -0
- package/dist/app-worker.js +556 -0
- package/dist/cli.js +810 -0
- package/dist/config.js +42 -0
- package/dist/demo.js +430 -0
- package/dist/expr.js +460 -0
- package/dist/ipc.js +201 -0
- package/dist/mcp.js +416 -0
- package/dist/multiplexer.js +281 -0
- package/dist/png.js +208 -0
- package/dist/primitives.js +669 -0
- package/dist/selection.js +170 -0
- package/dist/setup.js +329 -0
- package/dist/skill.js +219 -0
- package/dist/state.js +1147 -0
- package/dist/types.js +1 -0
- package/dist/ui-surface.js +744 -0
- package/dist/ui.js +1466 -0
- package/examples/spring-studio.ts +420 -0
- package/package.json +58 -4
- package/skills/bypane/SKILL.md +136 -0
package/dist/state.js
ADDED
|
@@ -0,0 +1,1147 @@
|
|
|
1
|
+
import { readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { basename, extname, resolve } from "node:path";
|
|
3
|
+
import { decodePng, isPngBuffer } from "./png.js";
|
|
4
|
+
import { collectUiDefaults } from "./ui-surface.js";
|
|
5
|
+
const CHECKLIST_RE = /^(\s*[-*+]\s+\[)([ xX])(\]\s+)(.*)$/;
|
|
6
|
+
export function extractChecklist(markdown) {
|
|
7
|
+
const lines = markdown.split(/\r?\n/);
|
|
8
|
+
const items = [];
|
|
9
|
+
let idx = 0;
|
|
10
|
+
for (let i = 0; i < lines.length; i++) {
|
|
11
|
+
const match = CHECKLIST_RE.exec(lines[i]);
|
|
12
|
+
if (match) {
|
|
13
|
+
items.push({
|
|
14
|
+
index: idx++,
|
|
15
|
+
line: i,
|
|
16
|
+
checked: match[2].toLowerCase() === "x",
|
|
17
|
+
text: match[4].trim(),
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return items;
|
|
22
|
+
}
|
|
23
|
+
export function applyChecklistState(markdown, checkedIndexes) {
|
|
24
|
+
const lines = markdown.split(/\r?\n/);
|
|
25
|
+
let idx = 0;
|
|
26
|
+
for (let i = 0; i < lines.length; i++) {
|
|
27
|
+
const match = CHECKLIST_RE.exec(lines[i]);
|
|
28
|
+
if (match) {
|
|
29
|
+
const checked = checkedIndexes.has(idx);
|
|
30
|
+
lines[i] = `${match[1]}${checked ? "x" : " "}${match[3]}${match[4]}`;
|
|
31
|
+
idx++;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const content = lines.join("\n");
|
|
35
|
+
return { content, checklist: extractChecklist(content) };
|
|
36
|
+
}
|
|
37
|
+
const IMAGE_EXTS = new Set([".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".svg", ".ico"]);
|
|
38
|
+
const BINARY_EXTS = new Set([
|
|
39
|
+
".pdf",
|
|
40
|
+
".mp4",
|
|
41
|
+
".mov",
|
|
42
|
+
".webm",
|
|
43
|
+
".mkv",
|
|
44
|
+
".mp3",
|
|
45
|
+
".wav",
|
|
46
|
+
".ogg",
|
|
47
|
+
".zip",
|
|
48
|
+
".tar",
|
|
49
|
+
".gz",
|
|
50
|
+
".tgz",
|
|
51
|
+
".7z",
|
|
52
|
+
".rar",
|
|
53
|
+
".wasm",
|
|
54
|
+
".exe",
|
|
55
|
+
".dmg",
|
|
56
|
+
".pkg",
|
|
57
|
+
".deb",
|
|
58
|
+
".rpm",
|
|
59
|
+
".sqlite",
|
|
60
|
+
".db",
|
|
61
|
+
".parquet",
|
|
62
|
+
".xlsx",
|
|
63
|
+
".docx",
|
|
64
|
+
".pptx",
|
|
65
|
+
".ttf",
|
|
66
|
+
".otf",
|
|
67
|
+
".woff",
|
|
68
|
+
".woff2",
|
|
69
|
+
]);
|
|
70
|
+
function mimeHintFor(filePath) {
|
|
71
|
+
const ext = extname(filePath).toLowerCase();
|
|
72
|
+
const map = {
|
|
73
|
+
".png": "image/png",
|
|
74
|
+
".jpg": "image/jpeg",
|
|
75
|
+
".jpeg": "image/jpeg",
|
|
76
|
+
".webp": "image/webp",
|
|
77
|
+
".gif": "image/gif",
|
|
78
|
+
".svg": "image/svg+xml",
|
|
79
|
+
".pdf": "application/pdf",
|
|
80
|
+
".mp4": "video/mp4",
|
|
81
|
+
".mov": "video/quicktime",
|
|
82
|
+
".webm": "video/webm",
|
|
83
|
+
".zip": "application/zip",
|
|
84
|
+
".json": "application/json",
|
|
85
|
+
".md": "text/markdown",
|
|
86
|
+
".ts": "text/typescript",
|
|
87
|
+
".tsx": "text/typescript",
|
|
88
|
+
".js": "text/javascript",
|
|
89
|
+
".py": "text/x-python",
|
|
90
|
+
".go": "text/x-go",
|
|
91
|
+
".rs": "text/x-rust",
|
|
92
|
+
".sql": "application/sql",
|
|
93
|
+
".csv": "text/csv",
|
|
94
|
+
".html": "text/html",
|
|
95
|
+
};
|
|
96
|
+
return map[ext] ?? (ext ? `file (${ext.slice(1)})` : "file");
|
|
97
|
+
}
|
|
98
|
+
function looksBinaryBuffer(buf) {
|
|
99
|
+
const sampleLen = Math.min(buf.length, 4096);
|
|
100
|
+
let nonText = 0;
|
|
101
|
+
for (let i = 0; i < sampleLen; i++) {
|
|
102
|
+
const b = buf[i];
|
|
103
|
+
if (b === 0)
|
|
104
|
+
return true;
|
|
105
|
+
if (b < 7 || (b > 13 && b < 32 && b !== 27))
|
|
106
|
+
nonText++;
|
|
107
|
+
}
|
|
108
|
+
return sampleLen > 0 && nonText / sampleLen > 0.12;
|
|
109
|
+
}
|
|
110
|
+
export function formatBytes(bytes) {
|
|
111
|
+
if (bytes === undefined || !Number.isFinite(bytes))
|
|
112
|
+
return "";
|
|
113
|
+
if (bytes < 1024)
|
|
114
|
+
return `${bytes} B`;
|
|
115
|
+
if (bytes < 1024 * 1024)
|
|
116
|
+
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
117
|
+
if (bytes < 1024 * 1024 * 1024)
|
|
118
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
119
|
+
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
|
|
120
|
+
}
|
|
121
|
+
export class WorkspaceStore {
|
|
122
|
+
session;
|
|
123
|
+
surfaces = [];
|
|
124
|
+
activeId = "";
|
|
125
|
+
toast = null;
|
|
126
|
+
idCounter = 1;
|
|
127
|
+
listeners = new Set();
|
|
128
|
+
askWaiters = new Map();
|
|
129
|
+
uiWaiters = new Map();
|
|
130
|
+
appWaiters = new Map();
|
|
131
|
+
constructor(session) {
|
|
132
|
+
this.session = session;
|
|
133
|
+
}
|
|
134
|
+
subscribe(fn) {
|
|
135
|
+
this.listeners.add(fn);
|
|
136
|
+
return () => this.listeners.delete(fn);
|
|
137
|
+
}
|
|
138
|
+
notify() {
|
|
139
|
+
for (const fn of this.listeners)
|
|
140
|
+
fn();
|
|
141
|
+
}
|
|
142
|
+
setToast(text, tone = "info", durationMs = 2800) {
|
|
143
|
+
this.toast = { text, tone, until: Date.now() + durationMs };
|
|
144
|
+
this.notify();
|
|
145
|
+
}
|
|
146
|
+
activeSurface() {
|
|
147
|
+
if (this.surfaces.length === 0)
|
|
148
|
+
return undefined;
|
|
149
|
+
const found = this.surfaces.find((s) => s.id === this.activeId);
|
|
150
|
+
if (found)
|
|
151
|
+
return found;
|
|
152
|
+
this.activeId = this.surfaces[0].id;
|
|
153
|
+
return this.surfaces[0];
|
|
154
|
+
}
|
|
155
|
+
get(id) {
|
|
156
|
+
return this.surfaces.find((s) => s.id === id);
|
|
157
|
+
}
|
|
158
|
+
focus(id) {
|
|
159
|
+
const s = this.get(id);
|
|
160
|
+
if (!s)
|
|
161
|
+
return false;
|
|
162
|
+
this.activeId = s.id;
|
|
163
|
+
s.unread = false;
|
|
164
|
+
this.notify();
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
focusIndex(index) {
|
|
168
|
+
const s = this.surfaces[index];
|
|
169
|
+
if (!s)
|
|
170
|
+
return false;
|
|
171
|
+
return this.focus(s.id);
|
|
172
|
+
}
|
|
173
|
+
focusDelta(delta) {
|
|
174
|
+
if (this.surfaces.length <= 1)
|
|
175
|
+
return false;
|
|
176
|
+
const idx = Math.max(0, this.surfaces.findIndex((s) => s.id === this.activeId));
|
|
177
|
+
const next = (idx + delta + this.surfaces.length) % this.surfaces.length;
|
|
178
|
+
return this.focusIndex(next);
|
|
179
|
+
}
|
|
180
|
+
close(id) {
|
|
181
|
+
const targetId = id ?? this.activeId;
|
|
182
|
+
const idx = this.surfaces.findIndex((s) => s.id === targetId);
|
|
183
|
+
if (idx < 0)
|
|
184
|
+
return false;
|
|
185
|
+
const [removed] = this.surfaces.splice(idx, 1);
|
|
186
|
+
if (removed && removed.kind === "ask" && removed.answer.status === "pending") {
|
|
187
|
+
this.resolveAskWaiters(removed.id, { status: "cancelled", submittedAt: Date.now() });
|
|
188
|
+
}
|
|
189
|
+
if (removed && removed.kind === "ui" && removed.submission.status === "pending") {
|
|
190
|
+
this.resolveUiWaiters(removed.id, { status: "cancelled", submittedAt: Date.now() });
|
|
191
|
+
}
|
|
192
|
+
if (removed && removed.kind === "app" && removed.submission.status === "pending") {
|
|
193
|
+
this.resolveAppWaiters(removed.id, { status: "cancelled", submittedAt: Date.now() });
|
|
194
|
+
}
|
|
195
|
+
if (this.activeId === targetId) {
|
|
196
|
+
const next = this.surfaces[Math.min(idx, this.surfaces.length - 1)];
|
|
197
|
+
this.activeId = next ? next.id : "";
|
|
198
|
+
if (next)
|
|
199
|
+
next.unread = false;
|
|
200
|
+
}
|
|
201
|
+
this.notify();
|
|
202
|
+
return true;
|
|
203
|
+
}
|
|
204
|
+
addNote(surfaceId, noteText) {
|
|
205
|
+
const trimmed = noteText.trim();
|
|
206
|
+
if (!trimmed)
|
|
207
|
+
return null;
|
|
208
|
+
const s = this.get(surfaceId);
|
|
209
|
+
if (!s)
|
|
210
|
+
return null;
|
|
211
|
+
const now = Date.now();
|
|
212
|
+
const context = captureNoteContext(s);
|
|
213
|
+
const note = {
|
|
214
|
+
id: `note-${now}-${Math.random().toString(36).slice(2, 6)}`,
|
|
215
|
+
text: trimmed,
|
|
216
|
+
...(context ? { context } : {}),
|
|
217
|
+
createdAt: now,
|
|
218
|
+
};
|
|
219
|
+
s.notes.push(note);
|
|
220
|
+
s.updatedAt = now;
|
|
221
|
+
this.notify();
|
|
222
|
+
return note;
|
|
223
|
+
}
|
|
224
|
+
nextId(prefix) {
|
|
225
|
+
return `${prefix}-${this.idCounter++}`;
|
|
226
|
+
}
|
|
227
|
+
present(input) {
|
|
228
|
+
const now = Date.now();
|
|
229
|
+
const existing = input.id ? this.get(input.id) : undefined;
|
|
230
|
+
const id = input.id || this.nextId(input.kind);
|
|
231
|
+
const existingNotes = existing ? existing.notes : [];
|
|
232
|
+
const createdAt = existing ? existing.createdAt : now;
|
|
233
|
+
let surface;
|
|
234
|
+
switch (input.kind) {
|
|
235
|
+
case "markdown":
|
|
236
|
+
surface = this.buildMarkdown(id, input, existingNotes, createdAt, now);
|
|
237
|
+
break;
|
|
238
|
+
case "file":
|
|
239
|
+
surface = this.buildFileOrImage(id, input, existingNotes, createdAt, now);
|
|
240
|
+
break;
|
|
241
|
+
case "image":
|
|
242
|
+
surface = this.buildImage(id, input, existingNotes, createdAt, now);
|
|
243
|
+
break;
|
|
244
|
+
case "table":
|
|
245
|
+
surface = this.buildTable(id, input, existing, existingNotes, createdAt, now);
|
|
246
|
+
break;
|
|
247
|
+
case "chart":
|
|
248
|
+
surface = this.buildChart(id, input, existingNotes, createdAt, now);
|
|
249
|
+
break;
|
|
250
|
+
case "log":
|
|
251
|
+
surface = this.buildLog(id, input, existing, existingNotes, createdAt, now);
|
|
252
|
+
break;
|
|
253
|
+
case "ask":
|
|
254
|
+
surface = this.buildAsk(id, input, existingNotes, createdAt, now);
|
|
255
|
+
break;
|
|
256
|
+
case "ui":
|
|
257
|
+
surface = this.buildUi(id, input, existing, existingNotes, createdAt, now);
|
|
258
|
+
break;
|
|
259
|
+
case "app":
|
|
260
|
+
surface = this.buildApp(id, input, existing, existingNotes, createdAt, now);
|
|
261
|
+
break;
|
|
262
|
+
}
|
|
263
|
+
const idx = this.surfaces.findIndex((s) => s.id === id);
|
|
264
|
+
if (idx >= 0) {
|
|
265
|
+
this.surfaces[idx] = surface;
|
|
266
|
+
}
|
|
267
|
+
else {
|
|
268
|
+
this.surfaces.push(surface);
|
|
269
|
+
}
|
|
270
|
+
const shouldFocus = input.focus ??
|
|
271
|
+
(this.surfaces.length === 1 ||
|
|
272
|
+
input.kind === "ask" ||
|
|
273
|
+
((input.kind === "ui" || input.kind === "app") && Boolean(input.wait)) ||
|
|
274
|
+
idx < 0);
|
|
275
|
+
if (shouldFocus) {
|
|
276
|
+
this.activeId = surface.id;
|
|
277
|
+
surface.unread = false;
|
|
278
|
+
}
|
|
279
|
+
else if (this.activeId !== surface.id) {
|
|
280
|
+
surface.unread = true;
|
|
281
|
+
}
|
|
282
|
+
this.notify();
|
|
283
|
+
return surface;
|
|
284
|
+
}
|
|
285
|
+
appendLog(surfaceId, lines) {
|
|
286
|
+
const existing = this.get(surfaceId);
|
|
287
|
+
if (!existing || existing.kind !== "log")
|
|
288
|
+
return null;
|
|
289
|
+
for (const line of lines)
|
|
290
|
+
existing.lines.push(line);
|
|
291
|
+
existing.updatedAt = Date.now();
|
|
292
|
+
if (this.activeId !== existing.id)
|
|
293
|
+
existing.unread = true;
|
|
294
|
+
this.notify();
|
|
295
|
+
return existing;
|
|
296
|
+
}
|
|
297
|
+
updateChecklist(surfaceId, checkedValues) {
|
|
298
|
+
const s = this.get(surfaceId);
|
|
299
|
+
if (!s || s.kind !== "markdown")
|
|
300
|
+
return false;
|
|
301
|
+
const set = new Set();
|
|
302
|
+
for (const v of checkedValues) {
|
|
303
|
+
const n = Number(v);
|
|
304
|
+
if (Number.isInteger(n))
|
|
305
|
+
set.add(n);
|
|
306
|
+
}
|
|
307
|
+
const next = applyChecklistState(s.content, set);
|
|
308
|
+
s.content = next.content;
|
|
309
|
+
s.checklist = next.checklist;
|
|
310
|
+
s.updatedAt = Date.now();
|
|
311
|
+
this.notify();
|
|
312
|
+
return true;
|
|
313
|
+
}
|
|
314
|
+
submitAsk(surfaceId, value) {
|
|
315
|
+
const s = this.get(surfaceId);
|
|
316
|
+
if (!s || s.kind !== "ask")
|
|
317
|
+
return false;
|
|
318
|
+
const answer = {
|
|
319
|
+
status: "submitted",
|
|
320
|
+
value,
|
|
321
|
+
submittedAt: Date.now(),
|
|
322
|
+
};
|
|
323
|
+
s.answer = answer;
|
|
324
|
+
s.updatedAt = answer.submittedAt;
|
|
325
|
+
this.resolveAskWaiters(surfaceId, answer);
|
|
326
|
+
this.setToast(`Submitted: ${s.title}`, "success");
|
|
327
|
+
return true;
|
|
328
|
+
}
|
|
329
|
+
cancelAsk(surfaceId) {
|
|
330
|
+
const s = this.get(surfaceId);
|
|
331
|
+
if (!s || s.kind !== "ask")
|
|
332
|
+
return false;
|
|
333
|
+
const answer = { status: "cancelled", submittedAt: Date.now() };
|
|
334
|
+
s.answer = answer;
|
|
335
|
+
s.updatedAt = answer.submittedAt;
|
|
336
|
+
this.resolveAskWaiters(surfaceId, answer);
|
|
337
|
+
this.setToast(`Cancelled: ${s.title}`, "info");
|
|
338
|
+
return true;
|
|
339
|
+
}
|
|
340
|
+
waitForAsk(surfaceId, timeoutMs) {
|
|
341
|
+
const s = this.get(surfaceId);
|
|
342
|
+
if (!s || s.kind !== "ask") {
|
|
343
|
+
return Promise.resolve({ status: "cancelled", submittedAt: Date.now() });
|
|
344
|
+
}
|
|
345
|
+
if (s.answer.status !== "pending") {
|
|
346
|
+
return Promise.resolve(s.answer);
|
|
347
|
+
}
|
|
348
|
+
return new Promise((resolvePromise) => {
|
|
349
|
+
const waiter = { resolve: resolvePromise };
|
|
350
|
+
if (timeoutMs && timeoutMs > 0) {
|
|
351
|
+
waiter.timer = setTimeout(() => {
|
|
352
|
+
const list = this.askWaiters.get(surfaceId);
|
|
353
|
+
if (list) {
|
|
354
|
+
const i = list.indexOf(waiter);
|
|
355
|
+
if (i >= 0)
|
|
356
|
+
list.splice(i, 1);
|
|
357
|
+
}
|
|
358
|
+
resolvePromise({ status: "pending" });
|
|
359
|
+
}, timeoutMs);
|
|
360
|
+
}
|
|
361
|
+
const list = this.askWaiters.get(surfaceId) ?? [];
|
|
362
|
+
list.push(waiter);
|
|
363
|
+
this.askWaiters.set(surfaceId, list);
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
resolveAskWaiters(surfaceId, answer) {
|
|
367
|
+
const list = this.askWaiters.get(surfaceId);
|
|
368
|
+
if (!list)
|
|
369
|
+
return;
|
|
370
|
+
this.askWaiters.delete(surfaceId);
|
|
371
|
+
for (const w of list) {
|
|
372
|
+
if (w.timer)
|
|
373
|
+
clearTimeout(w.timer);
|
|
374
|
+
w.resolve(answer);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
setUiValue(surfaceId, key, value) {
|
|
378
|
+
const s = this.get(surfaceId);
|
|
379
|
+
if (!s || s.kind !== "ui")
|
|
380
|
+
return false;
|
|
381
|
+
s.state[key] = value;
|
|
382
|
+
s.updatedAt = Date.now();
|
|
383
|
+
this.notify();
|
|
384
|
+
return true;
|
|
385
|
+
}
|
|
386
|
+
recordUiAction(surfaceId, action) {
|
|
387
|
+
const s = this.get(surfaceId);
|
|
388
|
+
if (!s || s.kind !== "ui")
|
|
389
|
+
return false;
|
|
390
|
+
const now = Date.now();
|
|
391
|
+
s.lastAction = { action, at: now };
|
|
392
|
+
s.updatedAt = now;
|
|
393
|
+
this.setToast(`Action: ${action} (press 's' to send state to agent)`, "info", 2200);
|
|
394
|
+
return true;
|
|
395
|
+
}
|
|
396
|
+
hasUiWaiter(surfaceId) {
|
|
397
|
+
return (this.uiWaiters.get(surfaceId)?.length ?? 0) > 0;
|
|
398
|
+
}
|
|
399
|
+
submitUi(surfaceId, action) {
|
|
400
|
+
const s = this.get(surfaceId);
|
|
401
|
+
if (!s || s.kind !== "ui")
|
|
402
|
+
return false;
|
|
403
|
+
const now = Date.now();
|
|
404
|
+
const submission = {
|
|
405
|
+
status: "submitted",
|
|
406
|
+
action,
|
|
407
|
+
state: { ...s.state },
|
|
408
|
+
submittedAt: now,
|
|
409
|
+
};
|
|
410
|
+
s.submission = submission;
|
|
411
|
+
s.lastAction = { action, at: now };
|
|
412
|
+
s.updatedAt = now;
|
|
413
|
+
this.resolveUiWaiters(surfaceId, submission);
|
|
414
|
+
this.setToast(`Submitted: ${s.title} (${action})`, "success");
|
|
415
|
+
return true;
|
|
416
|
+
}
|
|
417
|
+
cancelUi(surfaceId) {
|
|
418
|
+
const s = this.get(surfaceId);
|
|
419
|
+
if (!s || s.kind !== "ui")
|
|
420
|
+
return false;
|
|
421
|
+
const submission = { status: "cancelled", submittedAt: Date.now() };
|
|
422
|
+
s.submission = submission;
|
|
423
|
+
s.updatedAt = submission.submittedAt;
|
|
424
|
+
this.resolveUiWaiters(surfaceId, submission);
|
|
425
|
+
this.setToast(`Cancelled: ${s.title}`, "info");
|
|
426
|
+
return true;
|
|
427
|
+
}
|
|
428
|
+
waitForUi(surfaceId, timeoutMs) {
|
|
429
|
+
const s = this.get(surfaceId);
|
|
430
|
+
if (!s || s.kind !== "ui") {
|
|
431
|
+
return Promise.resolve({ status: "cancelled", submittedAt: Date.now() });
|
|
432
|
+
}
|
|
433
|
+
if (s.submission.status === "submitted" || s.submission.status === "cancelled") {
|
|
434
|
+
return Promise.resolve(s.submission);
|
|
435
|
+
}
|
|
436
|
+
return new Promise((resolvePromise) => {
|
|
437
|
+
const waiter = { resolve: resolvePromise };
|
|
438
|
+
if (timeoutMs && timeoutMs > 0) {
|
|
439
|
+
waiter.timer = setTimeout(() => {
|
|
440
|
+
const list = this.uiWaiters.get(surfaceId);
|
|
441
|
+
if (list) {
|
|
442
|
+
const i = list.indexOf(waiter);
|
|
443
|
+
if (i >= 0)
|
|
444
|
+
list.splice(i, 1);
|
|
445
|
+
}
|
|
446
|
+
resolvePromise({ status: "pending" });
|
|
447
|
+
}, timeoutMs);
|
|
448
|
+
}
|
|
449
|
+
const list = this.uiWaiters.get(surfaceId) ?? [];
|
|
450
|
+
list.push(waiter);
|
|
451
|
+
this.uiWaiters.set(surfaceId, list);
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
resolveUiWaiters(surfaceId, submission) {
|
|
455
|
+
const list = this.uiWaiters.get(surfaceId);
|
|
456
|
+
if (!list)
|
|
457
|
+
return;
|
|
458
|
+
this.uiWaiters.delete(surfaceId);
|
|
459
|
+
for (const w of list) {
|
|
460
|
+
if (w.timer)
|
|
461
|
+
clearTimeout(w.timer);
|
|
462
|
+
w.resolve(submission);
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
setAppState(surfaceId, nextState, customSummary) {
|
|
466
|
+
const s = this.get(surfaceId);
|
|
467
|
+
if (!s || s.kind !== "app")
|
|
468
|
+
return false;
|
|
469
|
+
s.state = { ...nextState };
|
|
470
|
+
if (customSummary !== undefined)
|
|
471
|
+
s.customSummary = customSummary || undefined;
|
|
472
|
+
s.updatedAt = Date.now();
|
|
473
|
+
this.notify();
|
|
474
|
+
return true;
|
|
475
|
+
}
|
|
476
|
+
setAppMeta(surfaceId, meta) {
|
|
477
|
+
const s = this.get(surfaceId);
|
|
478
|
+
if (!s || s.kind !== "app")
|
|
479
|
+
return false;
|
|
480
|
+
if (meta.hints !== undefined)
|
|
481
|
+
s.hints = meta.hints;
|
|
482
|
+
if (meta.captureKeys !== undefined)
|
|
483
|
+
s.captureKeys = meta.captureKeys;
|
|
484
|
+
if (meta.customSummary !== undefined)
|
|
485
|
+
s.customSummary = meta.customSummary || undefined;
|
|
486
|
+
this.notify();
|
|
487
|
+
return true;
|
|
488
|
+
}
|
|
489
|
+
setAppRuntime(surfaceId, status, error) {
|
|
490
|
+
const s = this.get(surfaceId);
|
|
491
|
+
if (!s || s.kind !== "app")
|
|
492
|
+
return false;
|
|
493
|
+
s.runtimeStatus = status;
|
|
494
|
+
s.runtimeError = error;
|
|
495
|
+
s.updatedAt = Date.now();
|
|
496
|
+
this.notify();
|
|
497
|
+
return true;
|
|
498
|
+
}
|
|
499
|
+
hasAppWaiter(surfaceId) {
|
|
500
|
+
return (this.appWaiters.get(surfaceId)?.length ?? 0) > 0;
|
|
501
|
+
}
|
|
502
|
+
submitApp(surfaceId, action, state) {
|
|
503
|
+
const s = this.get(surfaceId);
|
|
504
|
+
if (!s || s.kind !== "app")
|
|
505
|
+
return false;
|
|
506
|
+
if (state)
|
|
507
|
+
s.state = { ...state };
|
|
508
|
+
const now = Date.now();
|
|
509
|
+
const submission = {
|
|
510
|
+
status: "submitted",
|
|
511
|
+
action,
|
|
512
|
+
state: { ...s.state },
|
|
513
|
+
submittedAt: now,
|
|
514
|
+
};
|
|
515
|
+
s.submission = submission;
|
|
516
|
+
s.updatedAt = now;
|
|
517
|
+
this.resolveAppWaiters(surfaceId, submission);
|
|
518
|
+
this.setToast(`Submitted: ${s.title} (${action})`, "success");
|
|
519
|
+
return true;
|
|
520
|
+
}
|
|
521
|
+
cancelApp(surfaceId) {
|
|
522
|
+
const s = this.get(surfaceId);
|
|
523
|
+
if (!s || s.kind !== "app")
|
|
524
|
+
return false;
|
|
525
|
+
const submission = { status: "cancelled", submittedAt: Date.now() };
|
|
526
|
+
s.submission = submission;
|
|
527
|
+
s.updatedAt = submission.submittedAt;
|
|
528
|
+
this.resolveAppWaiters(surfaceId, submission);
|
|
529
|
+
this.setToast(`Cancelled: ${s.title}`, "info");
|
|
530
|
+
return true;
|
|
531
|
+
}
|
|
532
|
+
waitForApp(surfaceId, timeoutMs) {
|
|
533
|
+
const s = this.get(surfaceId);
|
|
534
|
+
if (!s || s.kind !== "app") {
|
|
535
|
+
return Promise.resolve({ status: "cancelled", submittedAt: Date.now() });
|
|
536
|
+
}
|
|
537
|
+
if (s.submission.status === "submitted" || s.submission.status === "cancelled") {
|
|
538
|
+
return Promise.resolve(s.submission);
|
|
539
|
+
}
|
|
540
|
+
return new Promise((resolvePromise) => {
|
|
541
|
+
const waiter = { resolve: resolvePromise };
|
|
542
|
+
if (timeoutMs && timeoutMs > 0) {
|
|
543
|
+
waiter.timer = setTimeout(() => {
|
|
544
|
+
const list = this.appWaiters.get(surfaceId);
|
|
545
|
+
if (list) {
|
|
546
|
+
const i = list.indexOf(waiter);
|
|
547
|
+
if (i >= 0)
|
|
548
|
+
list.splice(i, 1);
|
|
549
|
+
}
|
|
550
|
+
resolvePromise({ status: "pending" });
|
|
551
|
+
}, timeoutMs);
|
|
552
|
+
}
|
|
553
|
+
const list = this.appWaiters.get(surfaceId) ?? [];
|
|
554
|
+
list.push(waiter);
|
|
555
|
+
this.appWaiters.set(surfaceId, list);
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
resolveAppWaiters(surfaceId, submission) {
|
|
559
|
+
const list = this.appWaiters.get(surfaceId);
|
|
560
|
+
if (!list)
|
|
561
|
+
return;
|
|
562
|
+
this.appWaiters.delete(surfaceId);
|
|
563
|
+
for (const w of list) {
|
|
564
|
+
if (w.timer)
|
|
565
|
+
clearTimeout(w.timer);
|
|
566
|
+
w.resolve(submission);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
buildMarkdown(id, input, notes, createdAt, now) {
|
|
570
|
+
return {
|
|
571
|
+
id,
|
|
572
|
+
kind: "markdown",
|
|
573
|
+
title: input.title || "Document",
|
|
574
|
+
content: input.content,
|
|
575
|
+
checklist: extractChecklist(input.content),
|
|
576
|
+
origin: input.origin,
|
|
577
|
+
notes,
|
|
578
|
+
unread: false,
|
|
579
|
+
createdAt,
|
|
580
|
+
updatedAt: now,
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
buildFileOrImage(id, input, notes, createdAt, now) {
|
|
584
|
+
const absPath = resolve(input.origin?.cwd ?? process.cwd(), input.path);
|
|
585
|
+
const ext = extname(absPath).toLowerCase();
|
|
586
|
+
const title = input.title || basename(absPath);
|
|
587
|
+
if (input.content === undefined && IMAGE_EXTS.has(ext) && ext !== ".svg") {
|
|
588
|
+
return this.buildImage(id, {
|
|
589
|
+
id,
|
|
590
|
+
kind: "image",
|
|
591
|
+
title,
|
|
592
|
+
path: absPath,
|
|
593
|
+
origin: input.origin,
|
|
594
|
+
focus: input.focus,
|
|
595
|
+
}, notes, createdAt, now);
|
|
596
|
+
}
|
|
597
|
+
let content = input.content;
|
|
598
|
+
let binary = false;
|
|
599
|
+
let sizeBytes;
|
|
600
|
+
const mimeHint = mimeHintFor(absPath);
|
|
601
|
+
if (content === undefined) {
|
|
602
|
+
try {
|
|
603
|
+
const st = statSync(absPath);
|
|
604
|
+
sizeBytes = st.size;
|
|
605
|
+
if (BINARY_EXTS.has(ext) || st.size > 2 * 1024 * 1024) {
|
|
606
|
+
binary = true;
|
|
607
|
+
}
|
|
608
|
+
else {
|
|
609
|
+
const buf = readFileSync(absPath);
|
|
610
|
+
if (looksBinaryBuffer(buf)) {
|
|
611
|
+
binary = true;
|
|
612
|
+
}
|
|
613
|
+
else {
|
|
614
|
+
content = buf.toString("utf8");
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
catch (err) {
|
|
619
|
+
content = `Unable to read file: ${err.message}`;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
else {
|
|
623
|
+
sizeBytes = Buffer.byteLength(content, "utf8");
|
|
624
|
+
}
|
|
625
|
+
return {
|
|
626
|
+
id,
|
|
627
|
+
kind: "file",
|
|
628
|
+
title,
|
|
629
|
+
path: absPath,
|
|
630
|
+
content,
|
|
631
|
+
binary,
|
|
632
|
+
sizeBytes,
|
|
633
|
+
mimeHint,
|
|
634
|
+
highlightStart: input.highlightStart,
|
|
635
|
+
highlightEnd: input.highlightEnd,
|
|
636
|
+
origin: input.origin,
|
|
637
|
+
notes,
|
|
638
|
+
unread: false,
|
|
639
|
+
createdAt,
|
|
640
|
+
updatedAt: now,
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
buildImage(id, input, notes, createdAt, now) {
|
|
644
|
+
const absPath = resolve(input.origin?.cwd ?? process.cwd(), input.path);
|
|
645
|
+
const title = input.title || basename(absPath);
|
|
646
|
+
let sizeBytes;
|
|
647
|
+
let width;
|
|
648
|
+
let height;
|
|
649
|
+
let rgba;
|
|
650
|
+
let error;
|
|
651
|
+
try {
|
|
652
|
+
const buf = readFileSync(absPath);
|
|
653
|
+
sizeBytes = buf.length;
|
|
654
|
+
if (isPngBuffer(buf)) {
|
|
655
|
+
const decoded = decodePng(buf);
|
|
656
|
+
width = decoded.width;
|
|
657
|
+
height = decoded.height;
|
|
658
|
+
rgba = decoded.rgba;
|
|
659
|
+
}
|
|
660
|
+
else {
|
|
661
|
+
error = `Inline preview supports PNG (${mimeHintFor(absPath)} detected). Press 'o' to open on host.`;
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
catch (err) {
|
|
665
|
+
error = err.message;
|
|
666
|
+
}
|
|
667
|
+
return {
|
|
668
|
+
id,
|
|
669
|
+
kind: "image",
|
|
670
|
+
title,
|
|
671
|
+
path: absPath,
|
|
672
|
+
width,
|
|
673
|
+
height,
|
|
674
|
+
sizeBytes,
|
|
675
|
+
caption: input.caption,
|
|
676
|
+
rgba,
|
|
677
|
+
error,
|
|
678
|
+
origin: input.origin,
|
|
679
|
+
notes,
|
|
680
|
+
unread: false,
|
|
681
|
+
createdAt,
|
|
682
|
+
updatedAt: now,
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
buildTable(id, input, existing, notes, createdAt, now) {
|
|
686
|
+
const columns = input.columns.map((c) => typeof c === "string" ? { key: c, label: c } : c);
|
|
687
|
+
const rows = input.rows.map((r, index) => {
|
|
688
|
+
if (Array.isArray(r)) {
|
|
689
|
+
return { id: String(index), cells: r.map((v) => String(v ?? "")) };
|
|
690
|
+
}
|
|
691
|
+
return {
|
|
692
|
+
id: String(r.id ?? index),
|
|
693
|
+
cells: columns.map((col) => {
|
|
694
|
+
const val = r[col.key] ?? r[col.label];
|
|
695
|
+
return val === undefined || val === null ? "" : String(val);
|
|
696
|
+
}),
|
|
697
|
+
};
|
|
698
|
+
});
|
|
699
|
+
const prev = existing && existing.kind === "table" ? existing : undefined;
|
|
700
|
+
return {
|
|
701
|
+
id,
|
|
702
|
+
kind: "table",
|
|
703
|
+
title: input.title || "Table",
|
|
704
|
+
columns,
|
|
705
|
+
rows,
|
|
706
|
+
filter: prev?.filter ?? "",
|
|
707
|
+
sortColumn: prev?.sortColumn ?? -1,
|
|
708
|
+
sortDir: prev?.sortDir ?? "asc",
|
|
709
|
+
selectedRowId: prev?.selectedRowId ?? rows[0]?.id ?? "",
|
|
710
|
+
highlightedRowId: prev?.highlightedRowId ?? rows[0]?.id ?? "",
|
|
711
|
+
origin: input.origin,
|
|
712
|
+
notes,
|
|
713
|
+
unread: false,
|
|
714
|
+
createdAt,
|
|
715
|
+
updatedAt: now,
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
buildChart(id, input, notes, createdAt, now) {
|
|
719
|
+
return {
|
|
720
|
+
id,
|
|
721
|
+
kind: "chart",
|
|
722
|
+
title: input.title || "Chart",
|
|
723
|
+
series: input.series.map((s) => ({
|
|
724
|
+
name: s.name,
|
|
725
|
+
values: s.values.map((v) => Number(v)),
|
|
726
|
+
color: s.color,
|
|
727
|
+
})),
|
|
728
|
+
unit: input.unit,
|
|
729
|
+
min: input.min,
|
|
730
|
+
max: input.max,
|
|
731
|
+
caption: input.caption,
|
|
732
|
+
origin: input.origin,
|
|
733
|
+
notes,
|
|
734
|
+
unread: false,
|
|
735
|
+
createdAt,
|
|
736
|
+
updatedAt: now,
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
buildLog(id, input, existing, notes, createdAt, now) {
|
|
740
|
+
const prev = existing && existing.kind === "log" ? existing : undefined;
|
|
741
|
+
const lines = input.append && prev ? [...prev.lines, ...input.lines] : [...input.lines];
|
|
742
|
+
return {
|
|
743
|
+
id,
|
|
744
|
+
kind: "log",
|
|
745
|
+
title: input.title || "Log",
|
|
746
|
+
lines,
|
|
747
|
+
filter: prev?.filter ?? "",
|
|
748
|
+
stickToEnd: prev?.stickToEnd ?? true,
|
|
749
|
+
origin: input.origin,
|
|
750
|
+
notes,
|
|
751
|
+
unread: false,
|
|
752
|
+
createdAt,
|
|
753
|
+
updatedAt: now,
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
buildAsk(id, input, notes, createdAt, now) {
|
|
757
|
+
const options = (input.options ?? []).map((o) => typeof o === "string" ? { value: o, label: o } : o);
|
|
758
|
+
if (input.mode === "confirm" && options.length === 0) {
|
|
759
|
+
options.push({ value: "confirm", label: input.confirmLabel || "Approve / Confirm" }, { value: "cancel", label: input.cancelLabel || "Decline / Cancel" });
|
|
760
|
+
}
|
|
761
|
+
const defaultSelect = typeof input.defaultValue === "string" ? input.defaultValue : (options[0]?.value ?? "");
|
|
762
|
+
const defaultMulti = Array.isArray(input.defaultValue) ? [...input.defaultValue] : [];
|
|
763
|
+
const defaultText = typeof input.defaultValue === "string" ? input.defaultValue : "";
|
|
764
|
+
return {
|
|
765
|
+
id,
|
|
766
|
+
kind: "ask",
|
|
767
|
+
title: input.title || "Decision",
|
|
768
|
+
mode: input.mode,
|
|
769
|
+
prompt: input.prompt,
|
|
770
|
+
context: input.context,
|
|
771
|
+
options,
|
|
772
|
+
defaultValue: input.defaultValue,
|
|
773
|
+
placeholder: input.placeholder,
|
|
774
|
+
confirmLabel: input.confirmLabel,
|
|
775
|
+
cancelLabel: input.cancelLabel,
|
|
776
|
+
draftSelect: defaultSelect,
|
|
777
|
+
draftMulti: defaultMulti,
|
|
778
|
+
draftText: defaultText,
|
|
779
|
+
answer: { status: "pending" },
|
|
780
|
+
origin: input.origin,
|
|
781
|
+
notes,
|
|
782
|
+
unread: false,
|
|
783
|
+
createdAt,
|
|
784
|
+
updatedAt: now,
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
buildUi(id, input, existing, notes, createdAt, now) {
|
|
788
|
+
const prev = existing && existing.kind === "ui" ? existing : undefined;
|
|
789
|
+
const root = input.root ?? input.body ?? { type: "text", content: "(empty ui surface)", tone: "muted" };
|
|
790
|
+
const preserve = input.preserveState !== false;
|
|
791
|
+
const state = {
|
|
792
|
+
...(input.state ?? {}),
|
|
793
|
+
...(preserve && prev ? prev.state : {}),
|
|
794
|
+
};
|
|
795
|
+
collectUiDefaults(root, state);
|
|
796
|
+
const submission = input.wait
|
|
797
|
+
? { status: "pending" }
|
|
798
|
+
: prev && prev.submission.status !== "idle"
|
|
799
|
+
? prev.submission
|
|
800
|
+
: { status: "idle" };
|
|
801
|
+
return {
|
|
802
|
+
id,
|
|
803
|
+
kind: "ui",
|
|
804
|
+
title: input.title || "Interactive UI",
|
|
805
|
+
root,
|
|
806
|
+
state,
|
|
807
|
+
lastAction: prev?.lastAction,
|
|
808
|
+
submission,
|
|
809
|
+
origin: input.origin,
|
|
810
|
+
notes,
|
|
811
|
+
unread: false,
|
|
812
|
+
createdAt,
|
|
813
|
+
updatedAt: now,
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
buildApp(id, input, existing, notes, createdAt, now) {
|
|
817
|
+
const prev = existing && existing.kind === "app" ? existing : undefined;
|
|
818
|
+
const resolvedPath = input.path ? resolve(input.path) : undefined;
|
|
819
|
+
const hasNewSource = Boolean(resolvedPath || input.code !== undefined);
|
|
820
|
+
const entryPath = resolvedPath ?? (input.code !== undefined ? undefined : prev?.entryPath);
|
|
821
|
+
const code = input.code !== undefined ? input.code : resolvedPath ? undefined : prev?.code;
|
|
822
|
+
// Live state patch onto an existing running app without restarting its worker when no new source was sent.
|
|
823
|
+
const stateOnlyUpdate = Boolean(prev && !hasNewSource);
|
|
824
|
+
const revision = prev ? (stateOnlyUpdate ? prev.revision : prev.revision + 1) : 1;
|
|
825
|
+
const stateRevision = prev ? (input.state ? prev.stateRevision + 1 : prev.stateRevision) : 1;
|
|
826
|
+
const state = stateOnlyUpdate
|
|
827
|
+
? { ...prev.state, ...(input.state ?? {}) }
|
|
828
|
+
: { ...(input.state ?? {}) };
|
|
829
|
+
const submission = input.wait
|
|
830
|
+
? { status: "pending" }
|
|
831
|
+
: prev && prev.submission.status !== "idle" && stateOnlyUpdate
|
|
832
|
+
? prev.submission
|
|
833
|
+
: { status: "idle" };
|
|
834
|
+
const defaultTitle = entryPath ? basename(entryPath) : "Custom App";
|
|
835
|
+
return {
|
|
836
|
+
id,
|
|
837
|
+
kind: "app",
|
|
838
|
+
title: input.title || prev?.title || defaultTitle,
|
|
839
|
+
entryPath,
|
|
840
|
+
code,
|
|
841
|
+
revision,
|
|
842
|
+
stateRevision,
|
|
843
|
+
state,
|
|
844
|
+
customSummary: stateOnlyUpdate ? prev?.customSummary : undefined,
|
|
845
|
+
hints: stateOnlyUpdate ? prev?.hints : undefined,
|
|
846
|
+
captureKeys: stateOnlyUpdate ? prev?.captureKeys : undefined,
|
|
847
|
+
submission,
|
|
848
|
+
runtimeStatus: stateOnlyUpdate ? prev.runtimeStatus : "starting",
|
|
849
|
+
runtimeError: stateOnlyUpdate ? prev?.runtimeError : undefined,
|
|
850
|
+
origin: input.origin ?? prev?.origin,
|
|
851
|
+
notes,
|
|
852
|
+
unread: false,
|
|
853
|
+
createdAt,
|
|
854
|
+
updatedAt: now,
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
listSummaries() {
|
|
858
|
+
return this.surfaces.map((s) => ({
|
|
859
|
+
id: s.id,
|
|
860
|
+
kind: s.kind,
|
|
861
|
+
title: s.title,
|
|
862
|
+
unread: s.unread,
|
|
863
|
+
active: s.id === this.activeId,
|
|
864
|
+
notesCount: s.notes.length,
|
|
865
|
+
updatedAt: s.updatedAt,
|
|
866
|
+
origin: s.origin,
|
|
867
|
+
status: s.kind === "ask"
|
|
868
|
+
? s.answer.status
|
|
869
|
+
: s.kind === "ui" && s.submission.status !== "idle"
|
|
870
|
+
? s.submission.status
|
|
871
|
+
: s.kind === "app"
|
|
872
|
+
? s.runtimeStatus === "error"
|
|
873
|
+
? "error"
|
|
874
|
+
: s.submission.status !== "idle"
|
|
875
|
+
? s.submission.status
|
|
876
|
+
: s.runtimeStatus
|
|
877
|
+
: undefined,
|
|
878
|
+
}));
|
|
879
|
+
}
|
|
880
|
+
serializeSurface(surface) {
|
|
881
|
+
if (surface.kind === "image") {
|
|
882
|
+
const { rgba: _omit, ...rest } = surface;
|
|
883
|
+
return { ...rest, hasPixels: Boolean(surface.rgba) };
|
|
884
|
+
}
|
|
885
|
+
if (surface.kind === "app") {
|
|
886
|
+
const { code: rawCode, ...rest } = surface;
|
|
887
|
+
return { ...rest, hasInlineCode: Boolean(rawCode), codeLength: rawCode?.length ?? 0 };
|
|
888
|
+
}
|
|
889
|
+
if (surface.kind === "table") {
|
|
890
|
+
const selected = surface.rows.find((r) => r.id === surface.selectedRowId);
|
|
891
|
+
const highlighted = surface.rows.find((r) => r.id === surface.highlightedRowId);
|
|
892
|
+
return {
|
|
893
|
+
id: surface.id,
|
|
894
|
+
kind: surface.kind,
|
|
895
|
+
title: surface.title,
|
|
896
|
+
filter: surface.filter,
|
|
897
|
+
sortColumn: surface.sortColumn,
|
|
898
|
+
sortDir: surface.sortDir,
|
|
899
|
+
rowCount: surface.rows.length,
|
|
900
|
+
columns: surface.columns,
|
|
901
|
+
selectedRow: selected,
|
|
902
|
+
highlightedRow: highlighted,
|
|
903
|
+
notes: surface.notes,
|
|
904
|
+
origin: surface.origin,
|
|
905
|
+
updatedAt: surface.updatedAt,
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
if (surface.kind === "log") {
|
|
909
|
+
return {
|
|
910
|
+
id: surface.id,
|
|
911
|
+
kind: surface.kind,
|
|
912
|
+
title: surface.title,
|
|
913
|
+
lineCount: surface.lines.length,
|
|
914
|
+
filter: surface.filter,
|
|
915
|
+
tail: surface.lines.slice(-20),
|
|
916
|
+
notes: surface.notes,
|
|
917
|
+
origin: surface.origin,
|
|
918
|
+
updatedAt: surface.updatedAt,
|
|
919
|
+
};
|
|
920
|
+
}
|
|
921
|
+
return { ...surface };
|
|
922
|
+
}
|
|
923
|
+
serializeState(surfaceId) {
|
|
924
|
+
if (surfaceId) {
|
|
925
|
+
const s = this.get(surfaceId);
|
|
926
|
+
if (!s)
|
|
927
|
+
return { error: `Surface "${surfaceId}" not found` };
|
|
928
|
+
return this.serializeSurface(s);
|
|
929
|
+
}
|
|
930
|
+
const active = this.activeSurface();
|
|
931
|
+
return {
|
|
932
|
+
session: this.session,
|
|
933
|
+
activeId: this.activeId,
|
|
934
|
+
surfaces: this.listSummaries(),
|
|
935
|
+
active: active ? this.serializeSurface(active) : null,
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
export function sortTableRows(surface) {
|
|
940
|
+
const rows = [...surface.rows];
|
|
941
|
+
if (surface.sortColumn < 0 || surface.sortColumn >= surface.columns.length) {
|
|
942
|
+
return rows;
|
|
943
|
+
}
|
|
944
|
+
const col = surface.sortColumn;
|
|
945
|
+
const dir = surface.sortDir === "asc" ? 1 : -1;
|
|
946
|
+
rows.sort((a, b) => {
|
|
947
|
+
const av = a.cells[col] ?? "";
|
|
948
|
+
const bv = b.cells[col] ?? "";
|
|
949
|
+
const an = Number.parseFloat(av.replace(/[,%$]/g, ""));
|
|
950
|
+
const bn = Number.parseFloat(bv.replace(/[,%$]/g, ""));
|
|
951
|
+
if (!Number.isNaN(an) && !Number.isNaN(bn) && /^\s*[-+]?[\d.,]+/.test(av) && /^\s*[-+]?[\d.,]+/.test(bv)) {
|
|
952
|
+
return (an - bn) * dir;
|
|
953
|
+
}
|
|
954
|
+
return av.localeCompare(bv) * dir;
|
|
955
|
+
});
|
|
956
|
+
return rows;
|
|
957
|
+
}
|
|
958
|
+
function compactQuote(raw, maxLen = 120) {
|
|
959
|
+
const flat = raw.replace(/\s+/g, " ").trim();
|
|
960
|
+
if (flat.length <= maxLen)
|
|
961
|
+
return `"${flat}"`;
|
|
962
|
+
return `"${flat.slice(0, Math.max(1, maxLen - 1)).trimEnd()}…"`;
|
|
963
|
+
}
|
|
964
|
+
/**
|
|
965
|
+
* Captures a concise snapshot of the surface's active state/selection at the moment a note is created.
|
|
966
|
+
*/
|
|
967
|
+
export function captureNoteContext(surface) {
|
|
968
|
+
if (surface.kind === "ui") {
|
|
969
|
+
const entries = Object.entries(surface.state);
|
|
970
|
+
if (entries.length === 0)
|
|
971
|
+
return undefined;
|
|
972
|
+
return entries.map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(", ");
|
|
973
|
+
}
|
|
974
|
+
if (surface.kind === "app") {
|
|
975
|
+
if (surface.customSummary)
|
|
976
|
+
return surface.customSummary;
|
|
977
|
+
const entries = Object.entries(surface.state);
|
|
978
|
+
if (entries.length === 0)
|
|
979
|
+
return undefined;
|
|
980
|
+
return entries.map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(", ");
|
|
981
|
+
}
|
|
982
|
+
if (surface.kind === "table") {
|
|
983
|
+
const row = surface.rows.find((r) => r.id === surface.selectedRowId) ??
|
|
984
|
+
surface.rows.find((r) => r.id === surface.highlightedRowId);
|
|
985
|
+
if (row) {
|
|
986
|
+
const first = row.cells[0] ?? row.id;
|
|
987
|
+
const second = row.cells[1];
|
|
988
|
+
return second ? `${first} (${second})` : first;
|
|
989
|
+
}
|
|
990
|
+
return surface.filter ? `filter="${surface.filter}"` : undefined;
|
|
991
|
+
}
|
|
992
|
+
if (surface.kind === "file") {
|
|
993
|
+
const name = basename(surface.path);
|
|
994
|
+
if (surface.selection?.text) {
|
|
995
|
+
const s = surface.selection.startLine;
|
|
996
|
+
const e = surface.selection.endLine;
|
|
997
|
+
const range = s !== undefined ? `:L${s}${e && e !== s ? `-${e}` : ""}` : "";
|
|
998
|
+
return `${name}${range} ${compactQuote(surface.selection.text, 80)}`;
|
|
999
|
+
}
|
|
1000
|
+
if (surface.highlightStart !== undefined) {
|
|
1001
|
+
const range = surface.highlightEnd && surface.highlightEnd !== surface.highlightStart
|
|
1002
|
+
? `L${surface.highlightStart}-${surface.highlightEnd}`
|
|
1003
|
+
: `L${surface.highlightStart}`;
|
|
1004
|
+
return `${name}:${range}`;
|
|
1005
|
+
}
|
|
1006
|
+
return name;
|
|
1007
|
+
}
|
|
1008
|
+
if (surface.kind === "markdown") {
|
|
1009
|
+
if (surface.selection?.text) {
|
|
1010
|
+
return compactQuote(surface.selection.text, 100);
|
|
1011
|
+
}
|
|
1012
|
+
if (surface.checklist.length > 0) {
|
|
1013
|
+
const done = surface.checklist.filter((c) => c.checked).length;
|
|
1014
|
+
return `${done}/${surface.checklist.length} checked`;
|
|
1015
|
+
}
|
|
1016
|
+
return undefined;
|
|
1017
|
+
}
|
|
1018
|
+
if (surface.kind === "log") {
|
|
1019
|
+
return surface.filter ? `filter="${surface.filter}"` : undefined;
|
|
1020
|
+
}
|
|
1021
|
+
if (surface.kind === "ask") {
|
|
1022
|
+
return surface.answer.status === "submitted"
|
|
1023
|
+
? `answer=${JSON.stringify(surface.answer.value)}`
|
|
1024
|
+
: undefined;
|
|
1025
|
+
}
|
|
1026
|
+
return undefined;
|
|
1027
|
+
}
|
|
1028
|
+
function shallowStateEqual(a, b) {
|
|
1029
|
+
const ka = Object.keys(a);
|
|
1030
|
+
const kb = Object.keys(b);
|
|
1031
|
+
if (ka.length !== kb.length)
|
|
1032
|
+
return false;
|
|
1033
|
+
for (const k of ka) {
|
|
1034
|
+
if (JSON.stringify(a[k]) !== JSON.stringify(b[k]))
|
|
1035
|
+
return false;
|
|
1036
|
+
}
|
|
1037
|
+
return true;
|
|
1038
|
+
}
|
|
1039
|
+
/**
|
|
1040
|
+
* Formats a compact, clean feedback message for human -> agent push-back.
|
|
1041
|
+
* By default omits notes already transmitted to the agent pane so consecutive sends never duplicate them.
|
|
1042
|
+
*/
|
|
1043
|
+
export function formatFeedbackSummary(surface, options) {
|
|
1044
|
+
const singleNote = options?.singleNote;
|
|
1045
|
+
const lines = [`[bypane · ${surface.title} (${surface.kind})]`];
|
|
1046
|
+
if (surface.kind === "markdown") {
|
|
1047
|
+
if (surface.selection?.text) {
|
|
1048
|
+
lines.push(`Quote: ${compactQuote(surface.selection.text, 280)}`);
|
|
1049
|
+
}
|
|
1050
|
+
if (surface.checklist.length > 0) {
|
|
1051
|
+
const done = surface.checklist.filter((c) => c.checked).map((c) => c.text);
|
|
1052
|
+
const todo = surface.checklist.filter((c) => !c.checked).map((c) => c.text);
|
|
1053
|
+
if (done.length > 0)
|
|
1054
|
+
lines.push(`Checked (${done.length}): ${done.join("; ")}`);
|
|
1055
|
+
if (todo.length > 0)
|
|
1056
|
+
lines.push(`Unchecked (${todo.length}): ${todo.join("; ")}`);
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
else if (surface.kind === "file") {
|
|
1060
|
+
const start = surface.selection?.startLine ?? surface.highlightStart;
|
|
1061
|
+
const end = surface.selection?.endLine ?? surface.highlightEnd;
|
|
1062
|
+
const range = start !== undefined ? `:${start}${end && end !== start ? `-${end}` : ""}` : "";
|
|
1063
|
+
lines.push(`File: ${surface.path}${range}`);
|
|
1064
|
+
if (surface.selection?.text) {
|
|
1065
|
+
lines.push(`Quote: ${compactQuote(surface.selection.text, 280)}`);
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
else if (surface.kind === "image") {
|
|
1069
|
+
lines.push(`Image: ${surface.path}`);
|
|
1070
|
+
if (surface.caption)
|
|
1071
|
+
lines.push(`Caption: ${surface.caption}`);
|
|
1072
|
+
}
|
|
1073
|
+
else if (surface.kind === "table") {
|
|
1074
|
+
const row = surface.rows.find((r) => r.id === surface.selectedRowId) ??
|
|
1075
|
+
surface.rows.find((r) => r.id === surface.highlightedRowId);
|
|
1076
|
+
if (row) {
|
|
1077
|
+
const pairs = surface.columns.map((c, i) => `${c.label}=${row.cells[i] ?? ""}`);
|
|
1078
|
+
lines.push(`Selected row: ${pairs.join(", ")}`);
|
|
1079
|
+
}
|
|
1080
|
+
if (surface.filter)
|
|
1081
|
+
lines.push(`Filter: "${surface.filter}"`);
|
|
1082
|
+
}
|
|
1083
|
+
else if (surface.kind === "chart") {
|
|
1084
|
+
const stats = surface.series.map((s) => {
|
|
1085
|
+
const last = s.values[s.values.length - 1];
|
|
1086
|
+
return `${s.name}=${last ?? "n/a"}${surface.unit ? ` ${surface.unit}` : ""}`;
|
|
1087
|
+
});
|
|
1088
|
+
lines.push(`Series: ${stats.join(", ")}`);
|
|
1089
|
+
}
|
|
1090
|
+
else if (surface.kind === "log") {
|
|
1091
|
+
lines.push(`Lines: ${surface.lines.length}${surface.filter ? ` (filter: "${surface.filter}")` : ""}`);
|
|
1092
|
+
}
|
|
1093
|
+
else if (surface.kind === "ask") {
|
|
1094
|
+
if (surface.answer.status === "submitted") {
|
|
1095
|
+
lines.push(`Answer: ${JSON.stringify(surface.answer.value)}`);
|
|
1096
|
+
}
|
|
1097
|
+
else {
|
|
1098
|
+
lines.push(`Status: ${surface.answer.status}`);
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
else if (surface.kind === "ui") {
|
|
1102
|
+
const entries = Object.entries(surface.state);
|
|
1103
|
+
if (entries.length > 0) {
|
|
1104
|
+
const formatted = entries.map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(", ");
|
|
1105
|
+
lines.push(`State: ${formatted}`);
|
|
1106
|
+
}
|
|
1107
|
+
if (!singleNote) {
|
|
1108
|
+
if (surface.submission.status === "submitted" &&
|
|
1109
|
+
shallowStateEqual(surface.state, surface.submission.state)) {
|
|
1110
|
+
lines.push(`Submitted action: ${surface.submission.action}`);
|
|
1111
|
+
}
|
|
1112
|
+
else if (surface.lastAction && surface.submission.status !== "submitted") {
|
|
1113
|
+
lines.push(`Last action: ${surface.lastAction.action}`);
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
else if (surface.kind === "app") {
|
|
1118
|
+
if (surface.customSummary) {
|
|
1119
|
+
lines.push(`Summary: ${surface.customSummary}`);
|
|
1120
|
+
}
|
|
1121
|
+
const entries = Object.entries(surface.state);
|
|
1122
|
+
if (entries.length > 0) {
|
|
1123
|
+
const formatted = entries.map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(", ");
|
|
1124
|
+
lines.push(`State: ${formatted}`);
|
|
1125
|
+
}
|
|
1126
|
+
if (!singleNote &&
|
|
1127
|
+
surface.submission.status === "submitted" &&
|
|
1128
|
+
shallowStateEqual(surface.state, surface.submission.state)) {
|
|
1129
|
+
lines.push(`Submitted action: ${surface.submission.action}`);
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
if (singleNote) {
|
|
1133
|
+
lines.push(`Note: ${singleNote.text}`);
|
|
1134
|
+
}
|
|
1135
|
+
else {
|
|
1136
|
+
const notes = options?.includeAllNotes
|
|
1137
|
+
? surface.notes
|
|
1138
|
+
: surface.notes.filter((n) => n.sentAt === undefined);
|
|
1139
|
+
if (notes.length > 0) {
|
|
1140
|
+
lines.push("Notes:");
|
|
1141
|
+
for (const n of notes) {
|
|
1142
|
+
lines.push(`- ${n.context ? `[${n.context}] ` : ""}${n.text}`);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
return lines.join("\n");
|
|
1147
|
+
}
|