@bom0792/herdgate 0.9.37 → 0.9.38
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/.agents/skills/herdr/SKILL.md +65 -0
- package/DESIGN.md +28 -0
- package/README.md +55 -1
- package/package.json +2 -1
- package/plugin/herdr-plugin.toml +17 -0
- package/plugin/server/attachments.mjs +184 -0
- package/plugin/server/git-safe.mjs +126 -0
- package/plugin/server/index.mjs +300 -3
- package/plugin/server/mobile-tui-core.mjs +141 -45
- package/plugin/server/mobile-tui-stream.mjs +258 -1
- package/plugin/server/pi-receipt-gc.mjs +183 -0
- package/plugin/server/pi-receipt-search.mjs +217 -0
- package/plugin/server/pi-receipts.mjs +121 -13
- package/plugin/server/pi-transcript.mjs +217 -0
- package/plugin/server/pi-usage.mjs +84 -0
- package/plugin/server/pi-wake.mjs +319 -0
- package/plugin/server/pi-worker.mjs +16 -3
- package/plugin/server/port-attr.mjs +172 -0
- package/plugin/server/sysmon.mjs +212 -0
- package/plugin/server/wake-event.mjs +255 -0
- package/src/agent/index.ts +4 -2
- package/src/agent/qr.ts +70 -0
- package/src/cloud/gateway.ts +5 -1
- package/src/host/main.ts +14 -1
- package/src/web/app.css +356 -0
- package/src/web/app.js +1395 -14
- package/src/web/index.html +1 -0
- package/windows/npm-update.mjs +261 -11
- package/windows/update-policy.mjs +98 -0
package/src/web/app.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// - the token lives in localStorage on this device and is never sent anywhere but the
|
|
12
12
|
// cloud's own WS endpoint.
|
|
13
13
|
|
|
14
|
-
const BUILD = "v0.9.
|
|
14
|
+
const BUILD = "v0.9.34-web.3";
|
|
15
15
|
|
|
16
16
|
const $ = (id) => document.getElementById(id);
|
|
17
17
|
const TOKEN_KEY = "herdgate.token";
|
|
@@ -159,9 +159,126 @@ const state = {
|
|
|
159
159
|
termBody: null,
|
|
160
160
|
termPre: null,
|
|
161
161
|
retry: 0,
|
|
162
|
-
worker: { health: null, jobs: new Map(), error: null },
|
|
162
|
+
worker: { health: null, jobs: new Map(), error: null, search: null, searchError: null, tab: "jobs", usage: null, chatError: null, bodyError: null, draft: null, enrich: null },
|
|
163
|
+
diff: null,
|
|
164
|
+
chat: { filter: null, spawn: null },
|
|
163
165
|
};
|
|
164
166
|
|
|
167
|
+
// ---- fetch discipline: generation tokens + in-flight sharing ----------------
|
|
168
|
+
// Every rendered fetch is fenced by the generation of the view that asked for
|
|
169
|
+
// it (a fresh uuid per room mount). A reply answering an older generation is
|
|
170
|
+
// dropped on arrival — it can never overwrite newer state. Identical calls
|
|
171
|
+
// already in flight are joined instead of re-sent; `fresh: true` marks a read
|
|
172
|
+
// that must start AFTER writes that already left, so it never joins an older
|
|
173
|
+
// flight. Transport-level failures keep the last snapshot and raise a banner —
|
|
174
|
+
// a list never silently blanks.
|
|
175
|
+
|
|
176
|
+
const OP_TIMEOUT_MS = 15_000;
|
|
177
|
+
const fetches = { gen: "", inflight: new Map(), pending: new Map() };
|
|
178
|
+
|
|
179
|
+
/** A local fault marker (never a wire op): transport loss, a late host, or a
|
|
180
|
+
* flight superseded by a fresher read. Callers keep their snapshot and say so. */
|
|
181
|
+
function faultOf(p) {
|
|
182
|
+
return p && typeof p === "object" && typeof p.fault === "string" ? p.fault : null;
|
|
183
|
+
}
|
|
184
|
+
const isTransportFault = (p) => {
|
|
185
|
+
const fault = faultOf(p);
|
|
186
|
+
return fault === "transport" || fault === "fetch-timeout";
|
|
187
|
+
};
|
|
188
|
+
const USAGE_ERR_CODES = new Set(["usage-unavailable", "usage.rollup"]);
|
|
189
|
+
const SEARCH_ERR_CODES = new Set(["pi_receipts_disabled", "receipt.search"]);
|
|
190
|
+
const BODY_ERR_CODES = new Set(["pi_receipts_disabled", "pi_receipt_body_disabled", "receipt.body"]);
|
|
191
|
+
|
|
192
|
+
function cryptoUUID() {
|
|
193
|
+
const uuid = globalThis.crypto?.randomUUID; // globalThis: no ReferenceError where crypto is absent
|
|
194
|
+
return typeof uuid === "function" ? uuid.call(globalThis.crypto) : `gen-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** A fresh generation per view mount; replies from older ones fall into the void. */
|
|
198
|
+
function newGeneration() {
|
|
199
|
+
fetches.gen = cryptoUUID();
|
|
200
|
+
return fetches.gen;
|
|
201
|
+
}
|
|
202
|
+
function currentGeneration() {
|
|
203
|
+
return fetches.gen || newGeneration();
|
|
204
|
+
}
|
|
205
|
+
function generationCurrent(gen) {
|
|
206
|
+
return gen === fetches.gen;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function transportOpen() {
|
|
210
|
+
return Boolean(state.ws?.readyState === WebSocket.OPEN && state.roomId && !e2e.keyChanged);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* One fenced op call. The same op already flying under the same generation is
|
|
215
|
+
* joined rather than re-sent (one wire call, many surfaces); `fresh: true`
|
|
216
|
+
* refuses to join a flight that started before the caller's writes — the older
|
|
217
|
+
* flight is superseded instead. Host refusals resolve as `{op:"error"}`
|
|
218
|
+
* payloads; transport faults resolve with a local `{fault}` marker so callers
|
|
219
|
+
* keep their snapshot and say so.
|
|
220
|
+
*/
|
|
221
|
+
function opFetch(op, replyOp, payload = {}, { fresh = false, key = op, errCodes = null } = {}) {
|
|
222
|
+
const gen = currentGeneration();
|
|
223
|
+
const flying = fetches.inflight.get(key);
|
|
224
|
+
if (flying && flying.gen === gen && (!fresh || flying.fresh)) return flying.promise;
|
|
225
|
+
if (flying) finishFetch(flying, { fault: "superseded", message: "một lượt đọc mới hơn đã thay thế lượt này" });
|
|
226
|
+
let settle;
|
|
227
|
+
const promise = new Promise((resolve) => { settle = resolve; });
|
|
228
|
+
const entry = { key, op, replyOp, gen, fresh, promise, errCodes, settle, timer: 0 };
|
|
229
|
+
fetches.inflight.set(key, entry);
|
|
230
|
+
const stack = fetches.pending.get(replyOp) ?? [];
|
|
231
|
+
stack.push(entry);
|
|
232
|
+
fetches.pending.set(replyOp, stack);
|
|
233
|
+
entry.timer = setTimeout(
|
|
234
|
+
() => finishFetch(entry, { fault: "fetch-timeout", message: "máy không trả lời kịp — giữ dữ liệu gần nhất" }),
|
|
235
|
+
OP_TIMEOUT_MS,
|
|
236
|
+
);
|
|
237
|
+
if (transportOpen()) sendPayload({ op, ...payload });
|
|
238
|
+
else finishFetch(entry, { fault: "transport", message: "mất kết nối tới máy — giữ dữ liệu gần nhất" });
|
|
239
|
+
return promise;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function finishFetch(entry, payload) {
|
|
243
|
+
clearTimeout(entry.timer);
|
|
244
|
+
if (fetches.inflight.get(entry.key) === entry) fetches.inflight.delete(entry.key);
|
|
245
|
+
const stack = fetches.pending.get(entry.replyOp);
|
|
246
|
+
const at = stack ? stack.indexOf(entry) : -1;
|
|
247
|
+
if (at !== -1) stack.splice(at, 1);
|
|
248
|
+
entry.settle(payload);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Hand an inbound payload to the waiting fetch, if any. True = consumed: the
|
|
252
|
+
* surface that asked applies the answer itself, after its generation check. */
|
|
253
|
+
function routeFencedReply(payload) {
|
|
254
|
+
if (!payload || typeof payload !== "object" || typeof payload.op !== "string") return false;
|
|
255
|
+
let consumed = false;
|
|
256
|
+
if (payload.op !== "error") {
|
|
257
|
+
const entry = fetches.pending.get(payload.op)?.shift();
|
|
258
|
+
if (entry) {
|
|
259
|
+
finishFetch(entry, payload);
|
|
260
|
+
consumed = true;
|
|
261
|
+
}
|
|
262
|
+
} else if (typeof payload.code === "string") {
|
|
263
|
+
for (const stack of fetches.pending.values()) {
|
|
264
|
+
for (const entry of [...stack]) {
|
|
265
|
+
if (entry.errCodes?.has(payload.code)) {
|
|
266
|
+
finishFetch(entry, payload);
|
|
267
|
+
consumed = true;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return consumed;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** The socket died: every waiting fetch keeps its caller's snapshot and hears why. */
|
|
276
|
+
function failAllFencedFetches(message) {
|
|
277
|
+
for (const stack of [...fetches.pending.values()]) {
|
|
278
|
+
for (const entry of [...stack]) finishFetch(entry, { fault: "transport", message });
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
165
282
|
/** The cloud base: an explicit setting, else this page's origin (same-origin deployment). */
|
|
166
283
|
function cloudBase() {
|
|
167
284
|
const raw = (state.cloud || location.origin).replace(/\/$/, "");
|
|
@@ -366,6 +483,724 @@ const WORKER_ERROR_CODES = new Set([
|
|
|
366
483
|
"receipt.watch", "pi_receipts_disabled", "pi_receipt_body_disabled",
|
|
367
484
|
]);
|
|
368
485
|
|
|
486
|
+
// Diff/pane refusals are scoped the same way: they fault one view, never the room.
|
|
487
|
+
const DIFF_ERROR_CODES = new Set(["bad-ref", "diff", "diff.ref", "diff.repo"]);
|
|
488
|
+
const PANE_ERROR_CODES = new Set(["pane.focus", "bad-pane"]); // no surface yet — swallow, never blank the room
|
|
489
|
+
// Attachment refusals fault the 📎 pick only — the composer and its draft stay.
|
|
490
|
+
const ATTACH_ERROR_CODES = new Set(["attachment"]);
|
|
491
|
+
|
|
492
|
+
/** One transient line at the bottom of the screen — upload refusals and reader
|
|
493
|
+
* faults say so without blanking any view. Gone on its own after a few seconds. */
|
|
494
|
+
function toast(message) {
|
|
495
|
+
const el = document.createElement("div");
|
|
496
|
+
el.className = "toast";
|
|
497
|
+
el.textContent = message;
|
|
498
|
+
document.body.append(el);
|
|
499
|
+
setTimeout(() => el.remove(), 5_000);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// Recap answers "đến lượt ai?" — whose move it is — for every tracked job; Usage
|
|
503
|
+
// rolls the host's receipt journal into daily and per-principal tables.
|
|
504
|
+
const RECAP_GROUPS = [
|
|
505
|
+
{ key: "working", title: "Working" },
|
|
506
|
+
{ key: "needs-you", title: "Needs you" },
|
|
507
|
+
{ key: "fixing", title: "Needs fixing" },
|
|
508
|
+
{ key: "done", title: "Done" },
|
|
509
|
+
];
|
|
510
|
+
|
|
511
|
+
function recapBucket(job) {
|
|
512
|
+
const opened = typeof job.body === "string"; // the report was opened on this device
|
|
513
|
+
if (job.status === "queued" || job.status === "running" || job.status === "pending") return "working";
|
|
514
|
+
if (job.status === "failed") return "fixing";
|
|
515
|
+
if (job.status === "replied") return opened || job.duplicate ? "done" : "needs-you";
|
|
516
|
+
return "done"; // canceled or unknown verdicts — nothing waits on us
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// Herdr's status glyphs — one verdict per row in every list (Recap, Jobs/Receipts,
|
|
520
|
+
// Search): ◉ needs you (an unopened reply, an unknown or failed request),
|
|
521
|
+
// ◐ working, ● done (replied and read), ✓ idle (nothing waits on anyone).
|
|
522
|
+
function statusGlyph(job) {
|
|
523
|
+
const status = job?.status;
|
|
524
|
+
if (status === "queued" || status === "running" || status === "pending") return { glyph: "◐", cls: "glyph-working", title: "working" };
|
|
525
|
+
if (status === "unknown" || status === "failed") return { glyph: "◉", cls: "glyph-needs", title: status === "failed" ? "needs fixing" : "needs you" };
|
|
526
|
+
if (status === "replied") {
|
|
527
|
+
const opened = typeof job.body === "string" || job.duplicate || job.opened === true;
|
|
528
|
+
return opened ? { glyph: "●", cls: "glyph-done", title: "done" } : { glyph: "◉", cls: "glyph-needs", title: "needs you" };
|
|
529
|
+
}
|
|
530
|
+
return { glyph: "✓", cls: "glyph-idle", title: "idle" }; // canceled — nothing waits on us
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function glyphNode(job) {
|
|
534
|
+
const g = statusGlyph(job);
|
|
535
|
+
const span = document.createElement("span");
|
|
536
|
+
span.className = `glyph ${g.cls}`;
|
|
537
|
+
span.textContent = g.glyph;
|
|
538
|
+
span.title = g.title;
|
|
539
|
+
return span;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
const usageUsd = (value) => `$${(Number.isFinite(value) ? value : 0).toFixed(4)}`;
|
|
543
|
+
const usageClock = (ts) => {
|
|
544
|
+
const at = new Date(ts);
|
|
545
|
+
return Number.isFinite(at.getTime())
|
|
546
|
+
? `${String(at.getHours()).padStart(2, "0")}:${String(at.getMinutes()).padStart(2, "0")}`
|
|
547
|
+
: "";
|
|
548
|
+
};
|
|
549
|
+
|
|
550
|
+
// ---- receipt.enrich: the detail panel under a receipt row ---------------------
|
|
551
|
+
// Transcript facts for one receipt (model · context · turns · usage · last
|
|
552
|
+
// activity). The context bar only renders when a real window cap is known —
|
|
553
|
+
// the host never sends one and we do not invent thresholds, so
|
|
554
|
+
// CONTEXT_WINDOW_MAX stays null and the tokens render bare.
|
|
555
|
+
const CONTEXT_WINDOW_MAX = null;
|
|
556
|
+
|
|
557
|
+
/** 12345 -> "12,345" without betting the runtime on ICU locale data. */
|
|
558
|
+
const fmtTokens = (n) => (Number.isFinite(n) && n >= 0 ? String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ",") : null);
|
|
559
|
+
|
|
560
|
+
/** Context fill % against a known cap; null without one (never a guessed bar). */
|
|
561
|
+
function contextPctOf(tokens, max = CONTEXT_WINDOW_MAX) {
|
|
562
|
+
if (!Number.isFinite(tokens) || !(tokens >= 0) || !Number.isFinite(max) || !(max > 0)) return null;
|
|
563
|
+
return Math.min(100, Math.max(0, Math.round((tokens / max) * 100)));
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/** receipt.enrich.result → the panel's display rows (string-or-null; null hides). */
|
|
567
|
+
function enrichRows(result) {
|
|
568
|
+
const r = result && typeof result === "object" ? result : {};
|
|
569
|
+
const ctx = Number.isFinite(r.contextTokens) ? r.contextTokens : null;
|
|
570
|
+
const pct = contextPctOf(ctx);
|
|
571
|
+
const u = r.usageTotal && typeof r.usageTotal === "object" ? r.usageTotal : {};
|
|
572
|
+
const usageTokens = fmtTokens(u.totalTokens);
|
|
573
|
+
return {
|
|
574
|
+
model: typeof r.model === "string" && r.model ? r.model : null,
|
|
575
|
+
context: ctx !== null ? `${fmtTokens(ctx)} tokens${pct !== null ? ` · ${pct}%` : ""}` : null,
|
|
576
|
+
contextPct: pct,
|
|
577
|
+
turns: Number.isFinite(r.turns) ? String(r.turns) : null,
|
|
578
|
+
usage: usageTokens !== null ? `${usageTokens} tokens${Number.isFinite(u.costUsd) ? ` · ${usageUsd(u.costUsd)}` : ""}` : null,
|
|
579
|
+
last: Number.isFinite(r.lastTs) ? usageClock(r.lastTs) : null,
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
function renderWorkerRecap(box, w) {
|
|
584
|
+
box.replaceChildren();
|
|
585
|
+
const buckets = new Map(RECAP_GROUPS.map((group) => [group.key, []]));
|
|
586
|
+
for (const job of w.jobs.values()) {
|
|
587
|
+
buckets.get(recapBucket(job))?.push(job);
|
|
588
|
+
}
|
|
589
|
+
let shown = 0;
|
|
590
|
+
for (const group of RECAP_GROUPS) {
|
|
591
|
+
const items = buckets.get(group.key);
|
|
592
|
+
if (!items || items.length === 0) continue; // empty groups stay hidden
|
|
593
|
+
shown += items.length;
|
|
594
|
+
const head = document.createElement("p");
|
|
595
|
+
head.textContent = `${group.title} (${items.length})`;
|
|
596
|
+
const list = document.createElement("ul");
|
|
597
|
+
list.className = "list";
|
|
598
|
+
for (const job of items) {
|
|
599
|
+
const row = document.createElement("li");
|
|
600
|
+
row.className = "row";
|
|
601
|
+
const span = document.createElement("span");
|
|
602
|
+
span.textContent = `${job.id.slice(0, 8)} · ${job.status}${job.reason ? ` (${job.reason})` : ""}`;
|
|
603
|
+
row.append(span, glyphNode(job));
|
|
604
|
+
attachReceiptDetail(row, job.id);
|
|
605
|
+
list.append(row);
|
|
606
|
+
}
|
|
607
|
+
box.append(head, list);
|
|
608
|
+
}
|
|
609
|
+
if (shown === 0) {
|
|
610
|
+
const empty = document.createElement("p");
|
|
611
|
+
empty.className = "muted small";
|
|
612
|
+
empty.textContent = "no jobs yet — submit one from the Jobs tab";
|
|
613
|
+
box.append(empty);
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
const u = w.usage;
|
|
617
|
+
const today = !u || u.unavailable ? null : (Array.isArray(u.days) ? u.days[0] : null);
|
|
618
|
+
if (today && (today.requests ?? 0) > 0) {
|
|
619
|
+
const line = document.createElement("p");
|
|
620
|
+
line.className = "muted small";
|
|
621
|
+
line.textContent = `hôm nay: ${today.requests ?? 0} requests, ${today.tokens ?? 0} tokens, ${usageUsd(today.costUsd)}`;
|
|
622
|
+
box.append(line);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
function renderWorkerUsage(box, w, online) {
|
|
627
|
+
box.replaceChildren();
|
|
628
|
+
const fetchUsage = document.createElement("button");
|
|
629
|
+
fetchUsage.type = "button";
|
|
630
|
+
fetchUsage.textContent = "Fetch usage";
|
|
631
|
+
fetchUsage.addEventListener("click", () => fetchChatUsage(true));
|
|
632
|
+
box.append(fetchUsage);
|
|
633
|
+
const line = (text) => {
|
|
634
|
+
const p = document.createElement("p");
|
|
635
|
+
p.className = "muted small";
|
|
636
|
+
p.textContent = text;
|
|
637
|
+
box.append(p);
|
|
638
|
+
};
|
|
639
|
+
if (!online) {
|
|
640
|
+
line("host offline");
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
const u = w.usage;
|
|
644
|
+
if (!u) {
|
|
645
|
+
line("7-day roll-up over the host's receipt journal.");
|
|
646
|
+
return;
|
|
647
|
+
}
|
|
648
|
+
if (u.unavailable) {
|
|
649
|
+
line("usage unavailable on this host");
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
const rowOf = (tag, cells) => {
|
|
653
|
+
const tr = document.createElement("tr");
|
|
654
|
+
for (const value of cells) {
|
|
655
|
+
const cell = document.createElement(tag);
|
|
656
|
+
cell.textContent = String(value);
|
|
657
|
+
tr.append(cell);
|
|
658
|
+
}
|
|
659
|
+
return tr;
|
|
660
|
+
};
|
|
661
|
+
const days = document.createElement("table");
|
|
662
|
+
days.className = "usage-days";
|
|
663
|
+
days.append(rowOf("th", ["date", "req", "replied", "failed", "tokens", "$"]));
|
|
664
|
+
for (const day of Array.isArray(u.days) ? u.days : []) {
|
|
665
|
+
days.append(rowOf("td", [day.date, day.requests ?? 0, day.replied ?? 0, day.failed ?? 0, day.tokens ?? 0, usageUsd(day.costUsd)]));
|
|
666
|
+
}
|
|
667
|
+
const byPrincipal = document.createElement("table");
|
|
668
|
+
byPrincipal.className = "usage-principals";
|
|
669
|
+
byPrincipal.append(rowOf("th", ["principal", "req", "tokens", "$", "last"]));
|
|
670
|
+
for (const p of Array.isArray(u.byPrincipal) ? u.byPrincipal : []) {
|
|
671
|
+
byPrincipal.append(rowOf("td", [p.principal, p.requests ?? 0, p.tokens ?? 0, usageUsd(p.costUsd), usageClock(p.lastTs)]));
|
|
672
|
+
}
|
|
673
|
+
box.append(days, byPrincipal);
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
// Chat (the Timeline tab, re-imagined as threads): one thread per session over
|
|
677
|
+
// data the host already serves. A locally submitted job is a session this device
|
|
678
|
+
// knows end-to-end — prompt bubble, folded tool-run receipt events, reply bubble.
|
|
679
|
+
// Background spawn principals roll up into Delegation cards (name + status +
|
|
680
|
+
// tokens); clicking one filters the chat to that subagent. Anything the data
|
|
681
|
+
// lacks simply does not render — no spinners, no invented rows.
|
|
682
|
+
function renderWorkerChat(box, w, online) {
|
|
683
|
+
box.replaceChildren();
|
|
684
|
+
const head = document.createElement("p");
|
|
685
|
+
head.textContent = "Chat — mỗi session một thread";
|
|
686
|
+
const again = document.createElement("button");
|
|
687
|
+
again.type = "button";
|
|
688
|
+
again.className = "link";
|
|
689
|
+
again.textContent = "tải lại";
|
|
690
|
+
again.addEventListener("click", () => fetchChatUsage(true));
|
|
691
|
+
box.append(head, again);
|
|
692
|
+
if (w.chatError) box.append(note(w.chatError, "error")); // transport fault: the data below stays
|
|
693
|
+
const u = w.usage;
|
|
694
|
+
const today = !u || u.unavailable ? null : (Array.isArray(u.days) ? u.days[0] : null);
|
|
695
|
+
if (today && (today.requests ?? 0) > 0) {
|
|
696
|
+
const line = document.createElement("p");
|
|
697
|
+
line.className = "muted small";
|
|
698
|
+
line.textContent = `hôm nay: ${today.requests ?? 0} requests, ${today.tokens ?? 0} tokens, ${usageUsd(today.costUsd)}`;
|
|
699
|
+
box.append(line);
|
|
700
|
+
}
|
|
701
|
+
// Delegation cards — one per background `spawn:<id>` principal in the roll-up.
|
|
702
|
+
const byPrincipal = !u || u.unavailable ? [] : (Array.isArray(u.byPrincipal) ? u.byPrincipal : []);
|
|
703
|
+
const spawns = byPrincipal.filter((p) => /^spawn:[A-Za-z0-9._-]{1,64}$/.test(String(p.principal ?? "")));
|
|
704
|
+
if (spawns.length) {
|
|
705
|
+
const cards = document.createElement("div");
|
|
706
|
+
cards.className = "subagent-cards";
|
|
707
|
+
for (const s of spawns) cards.append(subagentCard(s, online));
|
|
708
|
+
box.append(cards);
|
|
709
|
+
}
|
|
710
|
+
const filter = state.chat.filter;
|
|
711
|
+
if (filter) box.append(spawnThread(filter, online));
|
|
712
|
+
const jobs = [...w.jobs.values()].filter((job) => !filter || job.principal === filter).slice(-12).reverse();
|
|
713
|
+
const threads = document.createElement("div");
|
|
714
|
+
threads.className = "threads";
|
|
715
|
+
for (const job of jobs) threads.append(chatThread(job));
|
|
716
|
+
box.append(threads);
|
|
717
|
+
if (!jobs.length) {
|
|
718
|
+
box.append(note(filter
|
|
719
|
+
? `không có session nào của ${filter} trên máy này`
|
|
720
|
+
: "chưa có session nào — gửi một job từ tab Jobs", "muted"));
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
function subagentStatus(p) {
|
|
725
|
+
if (Number.isFinite(p.lastTs) && Date.now() - p.lastTs < 5 * 60_000) return "running";
|
|
726
|
+
const failed = p.failed ?? 0;
|
|
727
|
+
return failed > 0 ? `failed ×${failed}` : `done ×${p.replied ?? 0}`;
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/** A Delegation card for one `spawn:<id>` principal: name, status, tokens.
|
|
731
|
+
* Click filters the chat to that subagent (and fetches its receipts). */
|
|
732
|
+
function subagentCard(s, online) {
|
|
733
|
+
const card = document.createElement("button");
|
|
734
|
+
card.type = "button";
|
|
735
|
+
card.className = "subagent" + (state.chat.filter === s.principal ? " active" : "");
|
|
736
|
+
const name = document.createElement("span");
|
|
737
|
+
name.className = "subagent-name";
|
|
738
|
+
name.textContent = s.principal.slice("spawn:".length);
|
|
739
|
+
const status = document.createElement("span");
|
|
740
|
+
status.className = "subagent-status";
|
|
741
|
+
status.textContent = subagentStatus(s);
|
|
742
|
+
const tokens = document.createElement("span");
|
|
743
|
+
tokens.className = "subagent-tokens";
|
|
744
|
+
tokens.textContent = `${s.tokens ?? 0} tokens · ${usageUsd(s.costUsd)}`;
|
|
745
|
+
card.append(name, status, tokens);
|
|
746
|
+
card.addEventListener("click", () => {
|
|
747
|
+
state.chat.filter = state.chat.filter === s.principal ? null : s.principal;
|
|
748
|
+
if (state.chat.filter) fetchSpawnReceipts(state.chat.filter);
|
|
749
|
+
state.roomUi?.updateWorker?.(online);
|
|
750
|
+
});
|
|
751
|
+
return card;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
/** The filtered view of one subagent: its receipts, listed like tool-runs. */
|
|
755
|
+
function spawnThread(principal, online) {
|
|
756
|
+
const box = document.createElement("div");
|
|
757
|
+
box.className = "spawn-thread";
|
|
758
|
+
const head = document.createElement("p");
|
|
759
|
+
head.textContent = `Delegation · ${principal}`;
|
|
760
|
+
box.append(head);
|
|
761
|
+
const clear = document.createElement("button");
|
|
762
|
+
clear.type = "button";
|
|
763
|
+
clear.className = "link";
|
|
764
|
+
clear.textContent = "bỏ lọc";
|
|
765
|
+
clear.addEventListener("click", () => {
|
|
766
|
+
state.chat.filter = null;
|
|
767
|
+
state.roomUi?.updateWorker?.(online);
|
|
768
|
+
});
|
|
769
|
+
box.append(clear);
|
|
770
|
+
const spawn = state.chat.spawn?.principal === principal ? state.chat.spawn : null;
|
|
771
|
+
if (spawn?.error) box.append(note(spawn.error, "error")); // transport: the hits above stay
|
|
772
|
+
if (spawn?.settled) {
|
|
773
|
+
if (Array.isArray(spawn.hits) && spawn.hits.length) {
|
|
774
|
+
const rows = document.createElement("ul");
|
|
775
|
+
rows.className = "list";
|
|
776
|
+
for (const hit of spawn.hits) {
|
|
777
|
+
const row = document.createElement("li");
|
|
778
|
+
row.className = "row";
|
|
779
|
+
const span = document.createElement("span");
|
|
780
|
+
span.textContent = `${hit.id.slice(0, 8)} · ${hit.status}${hit.reason ? ` (${hit.reason})` : ""} · ${hit.usage?.totalTokens ?? 0} tokens`;
|
|
781
|
+
row.append(span, glyphNode(hit));
|
|
782
|
+
rows.append(row);
|
|
783
|
+
}
|
|
784
|
+
box.append(rows);
|
|
785
|
+
} else if (!spawn.error) {
|
|
786
|
+
box.append(note("chưa có receipt nào của subagent này", "muted"));
|
|
787
|
+
}
|
|
788
|
+
} else {
|
|
789
|
+
box.append(note("đang tải receipts của subagent…", "muted"));
|
|
790
|
+
}
|
|
791
|
+
return box;
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/** One session: user prompt → folded tool-run receipt events → assistant reply. */
|
|
795
|
+
function chatThread(job) {
|
|
796
|
+
const thread = document.createElement("div");
|
|
797
|
+
thread.className = "thread";
|
|
798
|
+
if (job.prompt) {
|
|
799
|
+
const user = document.createElement("div");
|
|
800
|
+
user.className = "msg user";
|
|
801
|
+
user.textContent = job.prompt;
|
|
802
|
+
thread.append(user);
|
|
803
|
+
}
|
|
804
|
+
const events = Array.isArray(job.events) ? job.events : [];
|
|
805
|
+
if (events.length) {
|
|
806
|
+
// tool-run FOLD: one muted line; click opens the run underneath it.
|
|
807
|
+
const fold = document.createElement("details");
|
|
808
|
+
fold.className = "fold toolrun";
|
|
809
|
+
const sum = document.createElement("summary");
|
|
810
|
+
sum.textContent = `⚙ tool-run · receipt ${job.id.slice(0, 8)} · ${events.length} sự kiện`;
|
|
811
|
+
fold.append(sum);
|
|
812
|
+
const body = document.createElement("div");
|
|
813
|
+
body.className = "folddetail";
|
|
814
|
+
for (const ev of events) {
|
|
815
|
+
const line = document.createElement("div");
|
|
816
|
+
line.className = "toolevent";
|
|
817
|
+
line.textContent = `${usageClock(ev.at)} · ${ev.status}${ev.reason ? ` (${ev.reason})` : ""}${ev.tokens ? ` · ${ev.tokens} tokens` : ""}`;
|
|
818
|
+
body.append(line);
|
|
819
|
+
}
|
|
820
|
+
fold.append(body);
|
|
821
|
+
thread.append(fold);
|
|
822
|
+
}
|
|
823
|
+
const reply = document.createElement("div");
|
|
824
|
+
reply.className = "msg assistant";
|
|
825
|
+
if (typeof job.body === "string") {
|
|
826
|
+
appendLinkedText(reply, job.body); // `path:line` in a reply jumps into the Diff view
|
|
827
|
+
} else if (job.body && typeof job.body === "object") {
|
|
828
|
+
reply.textContent = `report not available (${job.body.reason ?? "unavailable"})`;
|
|
829
|
+
} else {
|
|
830
|
+
const line = document.createElement("span");
|
|
831
|
+
line.textContent = `${job.status ?? "unknown"}${job.reason ? ` (${job.reason})` : ""}`;
|
|
832
|
+
reply.append(glyphNode(job), line);
|
|
833
|
+
}
|
|
834
|
+
thread.append(reply);
|
|
835
|
+
return thread;
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
const PATH_LINE_RE = /((?:[A-Za-z0-9_.\-]+\/)*[A-Za-z0-9_.\-]+\.[A-Za-z0-9]{1,8})(?::(\d{1,7})(?:-\d{1,7})?|#L\d{1,7}(?:-L?\d{1,7})?)/g;
|
|
839
|
+
|
|
840
|
+
/** Text with `path:line` tokens becomes text nodes + jump links (no innerHTML). */
|
|
841
|
+
function appendLinkedText(box, text) {
|
|
842
|
+
const src = String(text ?? "");
|
|
843
|
+
let at = 0;
|
|
844
|
+
for (const m of src.matchAll(PATH_LINE_RE)) {
|
|
845
|
+
box.append(src.slice(at, m.index));
|
|
846
|
+
const btn = document.createElement("button");
|
|
847
|
+
btn.type = "button";
|
|
848
|
+
btn.className = "link pathline";
|
|
849
|
+
btn.textContent = m[0];
|
|
850
|
+
btn.addEventListener("click", () => gotoDiffLine(m[0]));
|
|
851
|
+
box.append(btn);
|
|
852
|
+
at = m.index + m[0].length;
|
|
853
|
+
}
|
|
854
|
+
box.append(src.slice(at));
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
/** usage.rollup behind the fence: the Chat and Usage surfaces share one flight. */
|
|
858
|
+
function fetchChatUsage(fresh = false) {
|
|
859
|
+
const gen = currentGeneration();
|
|
860
|
+
opFetch("usage.rollup", "usage.rollup.result", { days: 7 }, { key: "chat-usage", fresh, errCodes: USAGE_ERR_CODES })
|
|
861
|
+
.then((p) => {
|
|
862
|
+
if (!generationCurrent(gen)) return; // a newer mount owns the screen now
|
|
863
|
+
if (faultOf(p) === "superseded") return; // a fresher flight replaces this one
|
|
864
|
+
if (isTransportFault(p)) {
|
|
865
|
+
state.worker.chatError = p.message; // the snapshot below stays
|
|
866
|
+
} else if (p.op === "error") {
|
|
867
|
+
state.worker.usage = { unavailable: true }; // scoped refusal, not a transport fault
|
|
868
|
+
state.worker.chatError = null;
|
|
869
|
+
} else {
|
|
870
|
+
state.worker.usage = p;
|
|
871
|
+
state.worker.chatError = null;
|
|
872
|
+
}
|
|
873
|
+
state.roomUi?.updateWorker?.(Boolean(state.hello?.agents?.find((r) => r.roomId === state.roomId)?.online));
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/** Receipt search behind the fence; a transport fault keeps the last hits. */
|
|
878
|
+
function fetchReceiptSearch(query) {
|
|
879
|
+
const gen = currentGeneration();
|
|
880
|
+
opFetch("receipt.search", "receipt.search.result", { query, limit: 8 }, { key: "search", fresh: true, errCodes: SEARCH_ERR_CODES })
|
|
881
|
+
.then((p) => {
|
|
882
|
+
if (!generationCurrent(gen)) return;
|
|
883
|
+
if (faultOf(p) === "superseded") return;
|
|
884
|
+
if (isTransportFault(p)) {
|
|
885
|
+
state.worker.searchError = p.message; // the hit list stays
|
|
886
|
+
} else if (p.op === "error") {
|
|
887
|
+
state.worker.search = { hits: [], reason: p.code };
|
|
888
|
+
state.worker.searchError = null;
|
|
889
|
+
} else {
|
|
890
|
+
state.worker.search = { hits: Array.isArray(p.hits) ? p.hits : [], reason: p.reason ?? null };
|
|
891
|
+
state.worker.searchError = null;
|
|
892
|
+
}
|
|
893
|
+
state.roomUi?.updateWorker?.(Boolean(state.hello?.agents?.find((r) => r.roomId === state.roomId)?.online));
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
/** One retained report behind the fence; a transport fault leaves the rows as they were. */
|
|
898
|
+
function fetchReceiptBody(id) {
|
|
899
|
+
const gen = currentGeneration();
|
|
900
|
+
opFetch("receipt.body", "receipt.body.result", { id }, { key: `body:${id}`, errCodes: BODY_ERR_CODES })
|
|
901
|
+
.then((p) => {
|
|
902
|
+
if (!generationCurrent(gen)) return;
|
|
903
|
+
if (faultOf(p) === "superseded") return;
|
|
904
|
+
if (isTransportFault(p)) {
|
|
905
|
+
state.worker.bodyError = p.message; // rows keep their state, a banner says why
|
|
906
|
+
} else {
|
|
907
|
+
state.worker.bodyError = null;
|
|
908
|
+
applyBodyResult(p); // a refusal is also an answer (report not available)
|
|
909
|
+
}
|
|
910
|
+
});
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/** Receipt enrich behind the fence: transcript facts for the row's detail
|
|
914
|
+
* panel. A host refusal is also an answer — its message shows verbatim
|
|
915
|
+
* ("no readable transcript…" is data, not a bug to swallow); a transport
|
|
916
|
+
* fault keeps the shared never-blank banner instead of closing the panel. */
|
|
917
|
+
const ENRICH_ERR_CODES = new Set(["receipt.enrich", "pi_receipts_disabled"]);
|
|
918
|
+
|
|
919
|
+
function fetchReceiptEnrich(id) {
|
|
920
|
+
state.worker.enrich = { id, loading: true, error: null, result: null };
|
|
921
|
+
const online = () => Boolean(state.hello?.agents?.find((r) => r.roomId === state.roomId)?.online);
|
|
922
|
+
const gen = currentGeneration();
|
|
923
|
+
opFetch("receipt.enrich", "receipt.enrich.result", { id }, { key: `enrich:${id}`, errCodes: ENRICH_ERR_CODES })
|
|
924
|
+
.then((p) => {
|
|
925
|
+
if (!generationCurrent(gen)) return;
|
|
926
|
+
if (faultOf(p) === "superseded") return;
|
|
927
|
+
const cur = state.worker.enrich;
|
|
928
|
+
if (!cur || cur.id !== id) return; // another receipt owns the detail now
|
|
929
|
+
if (isTransportFault(p)) {
|
|
930
|
+
state.worker.enrich = { id, loading: false, error: p.message, result: null };
|
|
931
|
+
} else if (p.op === "error") {
|
|
932
|
+
state.worker.enrich = { id, loading: false, error: p.message ?? p.code ?? "receipt.enrich bị từ chối", result: null };
|
|
933
|
+
} else if (typeof p.reason === "string") {
|
|
934
|
+
state.worker.enrich = { id, loading: false, error: `receipt enrich không khả dụng (${p.reason})`, result: null };
|
|
935
|
+
} else {
|
|
936
|
+
state.worker.enrich = { id, loading: false, error: null, result: p };
|
|
937
|
+
}
|
|
938
|
+
state.roomUi?.updateWorker?.(online());
|
|
939
|
+
});
|
|
940
|
+
state.roomUi?.updateWorker?.(online());
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
/** Tap a receipt row → toggle its detail; opening one closes any other. */
|
|
944
|
+
function toggleReceiptEnrich(id) {
|
|
945
|
+
if (state.worker.enrich?.id === id) state.worker.enrich = null;
|
|
946
|
+
else fetchReceiptEnrich(id);
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
/** The detail expansion itself: loading line, verbatim refusal, or the facts. */
|
|
950
|
+
function receiptDetailNode(id) {
|
|
951
|
+
const box = document.createElement("div");
|
|
952
|
+
box.className = "receipt-detail";
|
|
953
|
+
const e = state.worker.enrich;
|
|
954
|
+
if (!e || e.id !== id) return box; // closed — the row stays a row
|
|
955
|
+
if (e.loading) {
|
|
956
|
+
box.append(note("đang tải chi tiết phiên…"));
|
|
957
|
+
return box;
|
|
958
|
+
}
|
|
959
|
+
if (e.error) {
|
|
960
|
+
box.append(note(e.error, "error")); // the host's words, kept visible
|
|
961
|
+
return box;
|
|
962
|
+
}
|
|
963
|
+
const rows = enrichRows(e.result);
|
|
964
|
+
const dl = document.createElement("dl");
|
|
965
|
+
const add = (label, value) => {
|
|
966
|
+
if (value === null || value === undefined || value === "") return;
|
|
967
|
+
const dt = document.createElement("dt");
|
|
968
|
+
dt.textContent = label;
|
|
969
|
+
const dd = document.createElement("dd");
|
|
970
|
+
dd.textContent = value;
|
|
971
|
+
dl.append(dt, dd);
|
|
972
|
+
};
|
|
973
|
+
add("model", rows.model);
|
|
974
|
+
add("context", rows.context);
|
|
975
|
+
add("turns", rows.turns);
|
|
976
|
+
add("usage", rows.usage);
|
|
977
|
+
add("last", rows.last);
|
|
978
|
+
box.append(dl);
|
|
979
|
+
if (rows.contextPct !== null) { // only with a real cap — never a guessed bar
|
|
980
|
+
const bar = document.createElement("div");
|
|
981
|
+
bar.className = "ctxbar";
|
|
982
|
+
const fill = document.createElement("i");
|
|
983
|
+
fill.style.width = `${rows.contextPct}%`;
|
|
984
|
+
bar.append(fill);
|
|
985
|
+
box.append(bar);
|
|
986
|
+
}
|
|
987
|
+
return box;
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
/** A receipt row opens its detail on tap — anywhere except its own buttons. */
|
|
991
|
+
function attachReceiptDetail(row, id) {
|
|
992
|
+
row.addEventListener("click", (event) => {
|
|
993
|
+
if (event.target instanceof Element && event.target.closest("button")) return;
|
|
994
|
+
toggleReceiptEnrich(id);
|
|
995
|
+
state.roomUi?.updateWorker?.(Boolean(state.hello?.agents?.find((r) => r.roomId === state.roomId)?.online));
|
|
996
|
+
});
|
|
997
|
+
row.append(receiptDetailNode(id));
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
/** Fold a receipt.body answer back into the job row and the search hit that asked. */
|
|
1001
|
+
function applyBodyResult(payload) {
|
|
1002
|
+
workerJobTouched(payload.id, payload.text !== undefined
|
|
1003
|
+
? { body: payload.text }
|
|
1004
|
+
: { body: { reason: payload.reason ?? payload.code ?? "unavailable" } });
|
|
1005
|
+
const s = state.worker.search;
|
|
1006
|
+
const hit = Array.isArray(s?.hits) ? s.hits.find((h) => h.id === payload.id) : null;
|
|
1007
|
+
if (hit) {
|
|
1008
|
+
hit.body = payload.text !== undefined ? payload.text : { reason: payload.reason ?? payload.code ?? "unavailable" };
|
|
1009
|
+
state.roomUi?.updateWorker?.(Boolean(state.hello?.agents?.find((r) => r.roomId === state.roomId)?.online));
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
/** Receipts of one spawn principal (the Delegation filter's backing data). */
|
|
1014
|
+
function fetchSpawnReceipts(principal) {
|
|
1015
|
+
const gen = currentGeneration();
|
|
1016
|
+
const prior = state.chat.spawn?.principal === principal ? state.chat.spawn : null;
|
|
1017
|
+
state.chat.spawn = { principal, settled: false, hits: prior?.hits ?? null, error: null };
|
|
1018
|
+
opFetch("receipt.search", "receipt.search.result", { query: principal, limit: 12 }, { key: `spawn:${principal}`, fresh: true, errCodes: SEARCH_ERR_CODES })
|
|
1019
|
+
.then((p) => {
|
|
1020
|
+
if (!generationCurrent(gen)) return;
|
|
1021
|
+
if (faultOf(p) === "superseded") return;
|
|
1022
|
+
const keep = state.chat.spawn?.principal === principal ? state.chat.spawn : null;
|
|
1023
|
+
if (p.op === "error") {
|
|
1024
|
+
state.chat.spawn = { principal, settled: true, hits: [], error: `subagent search bị từ chối (${p.code})` };
|
|
1025
|
+
} else {
|
|
1026
|
+
const hits = (Array.isArray(p.hits) ? p.hits : []).filter((h) => h?.principal === principal);
|
|
1027
|
+
state.chat.spawn = { principal, settled: true, hits, error: null };
|
|
1028
|
+
}
|
|
1029
|
+
if (isTransportFault(p)) {
|
|
1030
|
+
state.chat.spawn = { principal, settled: true, hits: keep?.hits ?? null, error: p.message }; // the hits stay
|
|
1031
|
+
}
|
|
1032
|
+
state.roomUi?.updateWorker?.(Boolean(state.hello?.agents?.find((r) => r.roomId === state.roomId)?.online));
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
/** filev open_target `parse_line_suffix`, web form: `src/app.rs:42`, `:42-48`,
|
|
1037
|
+
* `#L42`, `#L42-L48` → {path, line, end}. Null when the target names no file. */
|
|
1038
|
+
function parseLineSuffix(target) {
|
|
1039
|
+
const m = /^(.+?)(?::(\d{1,7})(?:-(\d{1,7}))?|#L(\d{1,7})(?:-L?(\d{1,7}))?)$/.exec(String(target ?? "").trim());
|
|
1040
|
+
if (!m) return null;
|
|
1041
|
+
const path = m[1];
|
|
1042
|
+
if (!path || path.length > 512 || /\s/.test(path) || !/[A-Za-z\u00C0-\u024F]/.test(path)) return null;
|
|
1043
|
+
const line = Number(m[2] ?? m[4]);
|
|
1044
|
+
const end = Number(m[3] ?? m[5] ?? line);
|
|
1045
|
+
if (!(line >= 1) || end < line) return null;
|
|
1046
|
+
return { path, line, end };
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
function diffGotoPathMatches(file, path) {
|
|
1050
|
+
return file === path || file.endsWith(`/${path}`) || (!path.includes("/") && file.split("/").pop() === path);
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
/** Row indexes of `path:line(-end)` inside a unified diff's patch lines: walk
|
|
1054
|
+
* the file headers, then each `@@ -a,b +c,d @@` hunk counting the NEW side.
|
|
1055
|
+
* An absent path simply yields no rows — the caller says so, gently. */
|
|
1056
|
+
function diffGotoIndexes(lines, goto) {
|
|
1057
|
+
if (!Array.isArray(lines) || !goto || !goto.path || !(goto.line >= 1)) return [];
|
|
1058
|
+
const file = goto.path;
|
|
1059
|
+
const end = Math.max(goto.line, goto.end ?? goto.line);
|
|
1060
|
+
const hits = [];
|
|
1061
|
+
let current = null;
|
|
1062
|
+
let newline = 0;
|
|
1063
|
+
let inHunk = false;
|
|
1064
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
1065
|
+
const t = String(lines[i] ?? "");
|
|
1066
|
+
if (t.startsWith("diff --git ")) {
|
|
1067
|
+
const m = /^diff --git a\/(\S+) b\/(\S+)$/.exec(t.trim());
|
|
1068
|
+
current = m ? m[2] : null;
|
|
1069
|
+
inHunk = false;
|
|
1070
|
+
continue;
|
|
1071
|
+
}
|
|
1072
|
+
if (current === null || !diffGotoPathMatches(current, file)) {
|
|
1073
|
+
inHunk = false;
|
|
1074
|
+
continue;
|
|
1075
|
+
}
|
|
1076
|
+
if (t.startsWith("@@")) {
|
|
1077
|
+
const m = /@@\s+-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@/.exec(t);
|
|
1078
|
+
newline = m ? Number(m[1]) : 0;
|
|
1079
|
+
inHunk = true;
|
|
1080
|
+
continue;
|
|
1081
|
+
}
|
|
1082
|
+
if (!inHunk) continue;
|
|
1083
|
+
if (t.startsWith("-")) continue; // old-side only: it carries no new-side number
|
|
1084
|
+
if (newline >= goto.line && newline <= end) hits.push(i); // + and context rows alike
|
|
1085
|
+
newline += 1;
|
|
1086
|
+
}
|
|
1087
|
+
return hits;
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
/** Load a diff behind the fence. `goto` (a path:line deep-link) survives the
|
|
1091
|
+
* round-trip; a transport fault restores the last good patch, never a blank. */
|
|
1092
|
+
function loadDiff(ref, goto = null) {
|
|
1093
|
+
const prev = state.diff && typeof state.diff.text === "string" ? state.diff : null;
|
|
1094
|
+
state.diff = { ref, text: null, truncated: false, bytes: 0, error: null, loading: true, goto, prev };
|
|
1095
|
+
const gen = currentGeneration();
|
|
1096
|
+
opFetch("diff.get", "diff.result", { ref }, { key: "diff", fresh: true, errCodes: DIFF_ERROR_CODES })
|
|
1097
|
+
.then((p) => {
|
|
1098
|
+
if (!generationCurrent(gen)) return;
|
|
1099
|
+
if (faultOf(p) === "superseded") return;
|
|
1100
|
+
if (isTransportFault(p)) {
|
|
1101
|
+
// transport: keep the last good patch and say so — never a silent blank.
|
|
1102
|
+
const message = p.message;
|
|
1103
|
+
state.diff = prev
|
|
1104
|
+
? { ...prev, error: message, loading: false }
|
|
1105
|
+
: { ref, text: null, truncated: false, bytes: 0, error: message, loading: false, goto };
|
|
1106
|
+
} else if (p.op === "error") {
|
|
1107
|
+
const message = p.message ?? p.code ?? "the host refused";
|
|
1108
|
+
state.diff = { ref, text: null, truncated: false, bytes: 0, error: message, loading: false, goto };
|
|
1109
|
+
} else {
|
|
1110
|
+
state.diff = {
|
|
1111
|
+
ref: typeof p.ref === "string" ? p.ref : ref,
|
|
1112
|
+
text: typeof p.text === "string" ? p.text : "",
|
|
1113
|
+
bytes: p.bytes ?? 0,
|
|
1114
|
+
truncated: p.truncated === true,
|
|
1115
|
+
error: null,
|
|
1116
|
+
loading: false,
|
|
1117
|
+
goto,
|
|
1118
|
+
};
|
|
1119
|
+
}
|
|
1120
|
+
state.roomUi?.updateWorker?.(Boolean(state.hello?.agents?.find((r) => r.roomId === state.roomId)?.online));
|
|
1121
|
+
});
|
|
1122
|
+
state.roomUi?.updateWorker?.(Boolean(state.hello?.agents?.find((r) => r.roomId === state.roomId)?.online));
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
/** A `path:line` deep-link (Cmd+K palette or a chat-card link) → the Diff view. */
|
|
1126
|
+
function gotoDiffLine(target) {
|
|
1127
|
+
const goto = parseLineSuffix(target);
|
|
1128
|
+
if (!goto) return false;
|
|
1129
|
+
state.openWorkerTab?.("diff");
|
|
1130
|
+
loadDiff(state.diff?.ref || "HEAD", goto);
|
|
1131
|
+
return true;
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
// Diff: render one `git show --stat --patch` answer — the stat block first, then
|
|
1135
|
+
// the patch with + green, - red, @@ purple. A truncated patch says so plainly.
|
|
1136
|
+
function renderWorkerDiff(out, d) {
|
|
1137
|
+
out.replaceChildren();
|
|
1138
|
+
if (!d) {
|
|
1139
|
+
out.append(note("Nhập một ref (hash / branch / tag) rồi Load — diff chạy `git show --stat --patch` trên máy, chỉ đọc."));
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
if (d.loading) {
|
|
1143
|
+
out.append(note(`đang tải ${d.ref}…`));
|
|
1144
|
+
return;
|
|
1145
|
+
}
|
|
1146
|
+
if (d.error) {
|
|
1147
|
+
out.append(note(d.error, "error"));
|
|
1148
|
+
return;
|
|
1149
|
+
}
|
|
1150
|
+
const text = typeof d.text === "string" ? d.text : "";
|
|
1151
|
+
const statLines = [];
|
|
1152
|
+
const patchLines = [];
|
|
1153
|
+
let inPatch = false;
|
|
1154
|
+
for (const line of text.split("\n")) {
|
|
1155
|
+
if (line.startsWith("diff --git ")) inPatch = true;
|
|
1156
|
+
(inPatch ? patchLines : statLines).push(line);
|
|
1157
|
+
}
|
|
1158
|
+
if (statLines.length) {
|
|
1159
|
+
const stat = document.createElement("pre");
|
|
1160
|
+
stat.className = "diff-stat";
|
|
1161
|
+
stat.textContent = statLines.join("\n");
|
|
1162
|
+
out.append(stat);
|
|
1163
|
+
}
|
|
1164
|
+
if (d.truncated) {
|
|
1165
|
+
const warn = document.createElement("p");
|
|
1166
|
+
warn.className = "muted small";
|
|
1167
|
+
warn.textContent = `patch quá dài — đã cắt còn 128KB (bản đầy đủ ${d.bytes ?? "?"} bytes)`;
|
|
1168
|
+
out.append(warn);
|
|
1169
|
+
}
|
|
1170
|
+
const patch = document.createElement("div");
|
|
1171
|
+
patch.className = "diff-patch";
|
|
1172
|
+
const rows = [];
|
|
1173
|
+
for (const line of patchLines) {
|
|
1174
|
+
const row = document.createElement("div");
|
|
1175
|
+
if (line.startsWith("+")) row.className = "diff-add";
|
|
1176
|
+
else if (line.startsWith("-")) row.className = "diff-del";
|
|
1177
|
+
else if (line.startsWith("@@")) row.className = "diff-hunk";
|
|
1178
|
+
else row.className = "diff-ctx";
|
|
1179
|
+
row.textContent = line || " ";
|
|
1180
|
+
rows.push(row);
|
|
1181
|
+
patch.append(row);
|
|
1182
|
+
}
|
|
1183
|
+
out.append(patch);
|
|
1184
|
+
// path:line deep-link: scroll the target row into view and flash it for 3s
|
|
1185
|
+
// (filev OpenRangeFlash — the highlight fades on its own).
|
|
1186
|
+
if (d.goto) {
|
|
1187
|
+
const hit = diffGotoIndexes(patchLines, d.goto);
|
|
1188
|
+
if (hit.length) {
|
|
1189
|
+
for (const i of hit) rows[i]?.classList?.add?.("flash");
|
|
1190
|
+
rows[hit[0]]?.scrollIntoView?.({ block: "center" });
|
|
1191
|
+
setTimeout(() => {
|
|
1192
|
+
for (const i of hit) rows[i]?.classList?.remove?.("flash");
|
|
1193
|
+
}, 3_000);
|
|
1194
|
+
} else {
|
|
1195
|
+
const miss = document.createElement("p");
|
|
1196
|
+
miss.className = "muted small";
|
|
1197
|
+
miss.textContent = `${d.goto.path}:${d.goto.line} không nằm trong diff này`;
|
|
1198
|
+
out.append(miss);
|
|
1199
|
+
}
|
|
1200
|
+
d.goto = null; // one reveal per deep-link, not per re-render
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
|
|
369
1204
|
function renderWorkerBox(box) {
|
|
370
1205
|
const details = document.createElement("details");
|
|
371
1206
|
details.className = "worker";
|
|
@@ -377,6 +1212,19 @@ function renderWorkerBox(box) {
|
|
|
377
1212
|
refresh.type = "button";
|
|
378
1213
|
refresh.className = "link";
|
|
379
1214
|
refresh.textContent = "refresh";
|
|
1215
|
+
// Activity bar: Jobs / Search / Recap / Usage share one surface; the chosen tab
|
|
1216
|
+
// lives in state.worker.tab. Jobs keeps its old DOM slots — submit form first,
|
|
1217
|
+
// jobs list last — so long-standing expectations keep matching.
|
|
1218
|
+
const bar = document.createElement("div");
|
|
1219
|
+
bar.className = "activity-bar";
|
|
1220
|
+
const tabButtons = new Map();
|
|
1221
|
+
for (const [key, label] of [["jobs", "Jobs"], ["search", "Search"], ["recap", "Recap"], ["usage", "Usage"], ["timeline", "Chat"], ["diff", "Diff"]]) {
|
|
1222
|
+
const tab = document.createElement("button");
|
|
1223
|
+
tab.type = "button";
|
|
1224
|
+
tab.textContent = label;
|
|
1225
|
+
bar.append(tab);
|
|
1226
|
+
tabButtons.set(key, tab);
|
|
1227
|
+
}
|
|
380
1228
|
const form = document.createElement("form");
|
|
381
1229
|
form.autocomplete = "off";
|
|
382
1230
|
const promptLabel = document.createElement("label");
|
|
@@ -396,13 +1244,106 @@ function renderWorkerBox(box) {
|
|
|
396
1244
|
const submit = document.createElement("button");
|
|
397
1245
|
submit.type = "submit";
|
|
398
1246
|
submit.textContent = "Submit job";
|
|
1247
|
+
// 📎 — attach a photo from the phone: capped 4MB client-side, read as base64,
|
|
1248
|
+
// uploaded to the AGENT MACHINE (attachment.upload), and the returned hint
|
|
1249
|
+
// ("Please open and inspect this image: <path>") lands in the prompt box so
|
|
1250
|
+
// the user sees — and sends — exactly the instruction the agent will act on.
|
|
1251
|
+
const attach = document.createElement("button");
|
|
1252
|
+
attach.type = "button";
|
|
1253
|
+
attach.className = "attach";
|
|
1254
|
+
attach.textContent = "📎";
|
|
1255
|
+
attach.title = "Đính kèm ảnh (image/*, tối đa 4MB) — tải về máy agent";
|
|
1256
|
+
const attachFile = document.createElement("input");
|
|
1257
|
+
attachFile.type = "file";
|
|
1258
|
+
attachFile.accept = "image/*";
|
|
1259
|
+
attachFile.hidden = true;
|
|
1260
|
+
attach.addEventListener("click", () => attachFile.click());
|
|
1261
|
+
attachFile.addEventListener("change", () => {
|
|
1262
|
+
const picked = attachFile.files && attachFile.files[0];
|
|
1263
|
+
attachFile.value = ""; // allow re-picking the same file
|
|
1264
|
+
if (!picked) return;
|
|
1265
|
+
if (picked.size > 4 * 1024 * 1024) {
|
|
1266
|
+
toast("Ảnh quá lớn — tối đa 4MB");
|
|
1267
|
+
return;
|
|
1268
|
+
}
|
|
1269
|
+
const reader = new FileReader();
|
|
1270
|
+
reader.onerror = () => toast("Không đọc được ảnh đã chọn");
|
|
1271
|
+
reader.onload = () => {
|
|
1272
|
+
const url = String(reader.result ?? "");
|
|
1273
|
+
const comma = url.indexOf(",");
|
|
1274
|
+
const dataBase64 = comma >= 0 ? url.slice(comma + 1) : "";
|
|
1275
|
+
if (!dataBase64) {
|
|
1276
|
+
toast("Không đọc được ảnh đã chọn");
|
|
1277
|
+
return;
|
|
1278
|
+
}
|
|
1279
|
+
void (async () => {
|
|
1280
|
+
const reply = await opFetch("attachment.upload", "attachment.uploaded",
|
|
1281
|
+
{ name: picked.name || "photo", dataBase64 },
|
|
1282
|
+
{ key: `attach:${picked.name}:${picked.size}:${picked.lastModified}`, fresh: true, errCodes: ATTACH_ERROR_CODES });
|
|
1283
|
+
if (!reply || reply.op !== "attachment.uploaded" || typeof reply.hint !== "string") {
|
|
1284
|
+
toast((reply && reply.message) || "Không tải được ảnh lên máy agent");
|
|
1285
|
+
return; // nothing is inserted into the prompt
|
|
1286
|
+
}
|
|
1287
|
+
prompt.value = prompt.value ? `${prompt.value.replace(/\s+$/, "")}\n${reply.hint}` : reply.hint;
|
|
1288
|
+
})();
|
|
1289
|
+
};
|
|
1290
|
+
reader.readAsDataURL(picked);
|
|
1291
|
+
});
|
|
399
1292
|
const formError = document.createElement("p");
|
|
400
1293
|
formError.className = "error small";
|
|
401
1294
|
formError.hidden = true;
|
|
402
|
-
form.append(promptLabel, prompt, wsLabel, workspace, submit, formError);
|
|
1295
|
+
form.append(promptLabel, prompt, wsLabel, workspace, attach, attachFile, submit, formError);
|
|
403
1296
|
const jobs = document.createElement("ul");
|
|
404
1297
|
jobs.className = "list";
|
|
405
|
-
|
|
1298
|
+
// Receipt search: BM25 over the host journal (receipt.search op). Metadata
|
|
1299
|
+
// hits only — the device fetches a retained reply per-hit through receipt.body,
|
|
1300
|
+
// exactly like the job rows above. A plain tab view now, not a nested disclosure.
|
|
1301
|
+
const search = document.createElement("div");
|
|
1302
|
+
search.className = "receipt-search";
|
|
1303
|
+
const searchForm = document.createElement("form");
|
|
1304
|
+
const searchLabel = document.createElement("label");
|
|
1305
|
+
searchLabel.textContent = "Find previous work by content";
|
|
1306
|
+
const searchInput = document.createElement("input");
|
|
1307
|
+
searchInput.type = "search";
|
|
1308
|
+
searchInput.placeholder = "noise rekey, cron bucket, …";
|
|
1309
|
+
searchInput.maxLength = 200;
|
|
1310
|
+
const searchButton = document.createElement("button");
|
|
1311
|
+
searchButton.type = "submit";
|
|
1312
|
+
searchButton.textContent = "Search";
|
|
1313
|
+
searchForm.append(searchLabel, searchInput, searchButton);
|
|
1314
|
+
const searchHits = document.createElement("ul");
|
|
1315
|
+
searchHits.className = "list";
|
|
1316
|
+
search.append(searchForm, searchHits);
|
|
1317
|
+
const recap = document.createElement("div");
|
|
1318
|
+
recap.className = "recap-view";
|
|
1319
|
+
recap.hidden = true;
|
|
1320
|
+
const usageView = document.createElement("div");
|
|
1321
|
+
usageView.className = "usage-view";
|
|
1322
|
+
usageView.hidden = true;
|
|
1323
|
+
// Timeline (usage.rollup as daily mini bars) and Diff (git show of one ref)
|
|
1324
|
+
// share the same activity-bar surface; both stay above the jobs list.
|
|
1325
|
+
const timelineView = document.createElement("div");
|
|
1326
|
+
timelineView.className = "chat-view";
|
|
1327
|
+
timelineView.hidden = true;
|
|
1328
|
+
const diffView = document.createElement("div");
|
|
1329
|
+
diffView.className = "diff-view";
|
|
1330
|
+
diffView.hidden = true;
|
|
1331
|
+
const diffForm = document.createElement("form");
|
|
1332
|
+
diffForm.autocomplete = "off";
|
|
1333
|
+
const diffLabel = document.createElement("label");
|
|
1334
|
+
diffLabel.textContent = "Diff — một ref (hash / branch / tag) trên máy, chỉ đọc";
|
|
1335
|
+
const diffInput = document.createElement("input");
|
|
1336
|
+
diffInput.type = "text";
|
|
1337
|
+
diffInput.maxLength = 64;
|
|
1338
|
+
diffInput.placeholder = "HEAD · main · v1.2.0 · <commit sha>";
|
|
1339
|
+
const diffButton = document.createElement("button");
|
|
1340
|
+
diffButton.type = "submit";
|
|
1341
|
+
diffButton.textContent = "Load";
|
|
1342
|
+
diffForm.append(diffLabel, diffInput, diffButton);
|
|
1343
|
+
const diffOut = document.createElement("div");
|
|
1344
|
+
diffOut.className = "diff-out";
|
|
1345
|
+
diffView.append(diffForm, diffOut);
|
|
1346
|
+
details.append(summary, health, refresh, bar, form, formError, search, recap, usageView, timelineView, diffView, jobs);
|
|
406
1347
|
box.append(details);
|
|
407
1348
|
|
|
408
1349
|
const askHealth = () => sendPayload({ op: "worker.health" });
|
|
@@ -413,14 +1354,57 @@ function renderWorkerBox(box) {
|
|
|
413
1354
|
formError.hidden = true;
|
|
414
1355
|
const text = prompt.value.trim();
|
|
415
1356
|
if (!text) return;
|
|
1357
|
+
state.worker.draft = text; // the thread's user bubble when the host echoes the id
|
|
416
1358
|
sendPayload({ op: "worker.submit", prompt: text, ...(workspace.value.trim() ? { workspace: workspace.value.trim() } : {}) });
|
|
417
1359
|
prompt.value = "";
|
|
418
1360
|
});
|
|
1361
|
+
searchForm.addEventListener("submit", (event) => {
|
|
1362
|
+
event.preventDefault();
|
|
1363
|
+
const query = searchInput.value.trim();
|
|
1364
|
+
if (!query) return;
|
|
1365
|
+
state.worker.lastQuery = query;
|
|
1366
|
+
fetchReceiptSearch(query);
|
|
1367
|
+
});
|
|
1368
|
+
diffForm.addEventListener("submit", (event) => {
|
|
1369
|
+
event.preventDefault();
|
|
1370
|
+
const ref = diffInput.value.trim();
|
|
1371
|
+
if (!ref) return;
|
|
1372
|
+
const goto = parseLineSuffix(ref); // a path:line typed straight into the box
|
|
1373
|
+
if (goto) loadDiff(state.diff?.ref || "HEAD", goto);
|
|
1374
|
+
else loadDiff(ref);
|
|
1375
|
+
});
|
|
419
1376
|
|
|
420
1377
|
const ui = { details, health, jobs, formError, asked: false };
|
|
1378
|
+
let liveOnline = false;
|
|
1379
|
+
for (const [key, tab] of tabButtons) {
|
|
1380
|
+
tab.addEventListener("click", () => {
|
|
1381
|
+
state.worker.tab = key;
|
|
1382
|
+
if (key === "timeline" && !state.worker.usage) fetchChatUsage();
|
|
1383
|
+
update(liveOnline);
|
|
1384
|
+
});
|
|
1385
|
+
}
|
|
1386
|
+
// The Cmd+K palette jumps here: open the surface, pick the tab, fetch on demand.
|
|
1387
|
+
state.openWorkerTab = (key) => {
|
|
1388
|
+
details.open = true;
|
|
1389
|
+
state.worker.tab = key;
|
|
1390
|
+
if (key === "timeline" && !state.worker.usage) fetchChatUsage();
|
|
1391
|
+
update(liveOnline);
|
|
1392
|
+
};
|
|
421
1393
|
const update = (online) => {
|
|
1394
|
+
liveOnline = online;
|
|
422
1395
|
const w = state.worker;
|
|
423
|
-
|
|
1396
|
+
const tab = ["search", "recap", "usage", "timeline", "diff"].includes(w.tab) ? w.tab : "jobs";
|
|
1397
|
+
const working = [...w.jobs.values()].filter((job) => ["queued", "running", "pending"].includes(job.status)).length;
|
|
1398
|
+
tabButtons.get("jobs").textContent = `Jobs (${working})`;
|
|
1399
|
+
for (const [key, button] of tabButtons) button.className = key === tab ? "active" : "";
|
|
1400
|
+
form.hidden = !online || tab !== "jobs";
|
|
1401
|
+
search.hidden = !online || tab !== "search";
|
|
1402
|
+
recap.hidden = tab !== "recap";
|
|
1403
|
+
usageView.hidden = tab !== "usage";
|
|
1404
|
+
timelineView.hidden = tab !== "timeline";
|
|
1405
|
+
diffView.hidden = tab !== "diff";
|
|
1406
|
+
jobs.hidden = tab !== "jobs";
|
|
1407
|
+
if (state.diff?.ref && diffInput.value !== state.diff.ref) diffInput.value = state.diff.ref;
|
|
424
1408
|
if (online && details.open && !ui.asked) { ui.asked = true; askHealth(); }
|
|
425
1409
|
const h = w.health;
|
|
426
1410
|
if (!online) {
|
|
@@ -435,20 +1419,84 @@ function renderWorkerBox(box) {
|
|
|
435
1419
|
}
|
|
436
1420
|
formError.hidden = !w.error;
|
|
437
1421
|
formError.textContent = w.error ?? "";
|
|
1422
|
+
searchHits.replaceChildren();
|
|
1423
|
+
if (w.searchError) {
|
|
1424
|
+
const banner = document.createElement("li");
|
|
1425
|
+
banner.className = "error small";
|
|
1426
|
+
banner.textContent = w.searchError; // transport fault — the hits below stay
|
|
1427
|
+
searchHits.append(banner);
|
|
1428
|
+
}
|
|
1429
|
+
const s = w.search;
|
|
1430
|
+
if (s) {
|
|
1431
|
+
if (Array.isArray(s.hits) && s.hits.length) {
|
|
1432
|
+
for (const hit of s.hits) {
|
|
1433
|
+
const row = document.createElement("li");
|
|
1434
|
+
row.className = "row";
|
|
1435
|
+
const head = document.createElement("span");
|
|
1436
|
+
head.textContent = `${hit.id.slice(0, 8)} · ${hit.status}${hit.reason ? ` (${hit.reason})` : ""}`
|
|
1437
|
+
+ `${hit.principal ? ` · ${hit.principal}` : ""} · score ${hit.score}`;
|
|
1438
|
+
row.append(head, glyphNode(hit));
|
|
1439
|
+
if (hit.status === "replied") {
|
|
1440
|
+
const view = document.createElement("button");
|
|
1441
|
+
view.type = "button";
|
|
1442
|
+
view.className = "link";
|
|
1443
|
+
view.textContent = hit.body === undefined ? "view report" : "hide report";
|
|
1444
|
+
view.addEventListener("click", () => {
|
|
1445
|
+
if (hit.body === undefined) fetchReceiptBody(hit.id);
|
|
1446
|
+
else hit.body = undefined;
|
|
1447
|
+
update(online);
|
|
1448
|
+
});
|
|
1449
|
+
row.append(" ", view);
|
|
1450
|
+
if (typeof hit.body === "string") {
|
|
1451
|
+
const pre = document.createElement("pre");
|
|
1452
|
+
pre.textContent = hit.body;
|
|
1453
|
+
row.append(pre);
|
|
1454
|
+
} else if (hit.body && typeof hit.body === "object") {
|
|
1455
|
+
const why = document.createElement("span");
|
|
1456
|
+
why.className = "muted small";
|
|
1457
|
+
why.textContent = `report not available (${hit.body.reason ?? "unavailable"})`;
|
|
1458
|
+
row.append(why);
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
if (hit.status === "unknown") {
|
|
1462
|
+
// An unknown receipt may be a settle this device never saw: ack retires
|
|
1463
|
+
// the push intent, receipt.get refreshes the row's verdict in place.
|
|
1464
|
+
const ack = document.createElement("button");
|
|
1465
|
+
ack.type = "button";
|
|
1466
|
+
ack.className = "link";
|
|
1467
|
+
ack.textContent = "ack";
|
|
1468
|
+
ack.addEventListener("click", () => {
|
|
1469
|
+
sendPayload({ op: "receipt.ack", id: hit.id });
|
|
1470
|
+
sendPayload({ op: "receipt.get", id: hit.id });
|
|
1471
|
+
});
|
|
1472
|
+
row.append(" ", ack);
|
|
1473
|
+
}
|
|
1474
|
+
attachReceiptDetail(row, hit.id);
|
|
1475
|
+
searchHits.append(row);
|
|
1476
|
+
}
|
|
1477
|
+
} else {
|
|
1478
|
+
const none = document.createElement("li");
|
|
1479
|
+
none.className = "muted small";
|
|
1480
|
+
none.textContent = s.reason === "pi_receipts_disabled"
|
|
1481
|
+
? "receipt search disabled on this host (HERDGATE_PI_RECEIPTS)"
|
|
1482
|
+
: s.hits && s.hits.length === 0 ? "no receipts match" : "search failed";
|
|
1483
|
+
searchHits.append(none);
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
438
1486
|
jobs.replaceChildren();
|
|
439
1487
|
for (const job of [...w.jobs.values()].slice(-12).reverse()) {
|
|
440
1488
|
const row = document.createElement("li");
|
|
441
1489
|
row.className = "row";
|
|
442
1490
|
const head = document.createElement("span");
|
|
443
1491
|
head.textContent = `${job.id.slice(0, 8)} · ${job.status}${job.reason ? ` (${job.reason})` : ""}${job.duplicate ? " · duplicate" : ""}`;
|
|
444
|
-
row.append(head);
|
|
1492
|
+
row.append(head, glyphNode(job));
|
|
445
1493
|
if (job.status === "replied" && job.hasBody) {
|
|
446
1494
|
const view = document.createElement("button");
|
|
447
1495
|
view.type = "button";
|
|
448
1496
|
view.className = "link";
|
|
449
1497
|
view.textContent = job.body === undefined ? "view report" : "hide report";
|
|
450
1498
|
view.addEventListener("click", () => {
|
|
451
|
-
if (job.body === undefined)
|
|
1499
|
+
if (job.body === undefined) fetchReceiptBody(job.id);
|
|
452
1500
|
else job.body = undefined;
|
|
453
1501
|
update(online);
|
|
454
1502
|
});
|
|
@@ -464,8 +1512,24 @@ function renderWorkerBox(box) {
|
|
|
464
1512
|
row.append(why);
|
|
465
1513
|
}
|
|
466
1514
|
}
|
|
1515
|
+
if (job.status === "unknown") {
|
|
1516
|
+
const ack = document.createElement("button");
|
|
1517
|
+
ack.type = "button";
|
|
1518
|
+
ack.className = "link";
|
|
1519
|
+
ack.textContent = "ack";
|
|
1520
|
+
ack.addEventListener("click", () => {
|
|
1521
|
+
sendPayload({ op: "receipt.ack", id: job.id });
|
|
1522
|
+
sendPayload({ op: "receipt.get", id: job.id });
|
|
1523
|
+
});
|
|
1524
|
+
row.append(" ", ack);
|
|
1525
|
+
}
|
|
1526
|
+
attachReceiptDetail(row, job.id);
|
|
467
1527
|
jobs.append(row);
|
|
468
1528
|
}
|
|
1529
|
+
renderWorkerRecap(recap, w);
|
|
1530
|
+
renderWorkerUsage(usageView, w, online);
|
|
1531
|
+
renderWorkerChat(timelineView, w, online);
|
|
1532
|
+
renderWorkerDiff(diffOut, state.diff);
|
|
469
1533
|
};
|
|
470
1534
|
return update;
|
|
471
1535
|
}
|
|
@@ -473,7 +1537,18 @@ function renderWorkerBox(box) {
|
|
|
473
1537
|
function workerJobTouched(id, fields) {
|
|
474
1538
|
const job = state.worker.jobs.get(id);
|
|
475
1539
|
if (!job) return;
|
|
1540
|
+
const prevStatus = job.status;
|
|
476
1541
|
Object.assign(job, fields);
|
|
1542
|
+
if (fields.status && fields.status !== prevStatus) {
|
|
1543
|
+
// The receipt machinery running under a thread: one line in the chat, the
|
|
1544
|
+
// detail (status, reason, tokens) folded behind it.
|
|
1545
|
+
(job.events ??= []).push({
|
|
1546
|
+
at: Date.now(),
|
|
1547
|
+
status: fields.status,
|
|
1548
|
+
reason: fields.reason ?? null,
|
|
1549
|
+
tokens: fields.usage?.totalTokens ?? null,
|
|
1550
|
+
});
|
|
1551
|
+
}
|
|
477
1552
|
state.roomUi?.updateWorker?.(Boolean(state.hello?.agents?.find((r) => r.roomId === state.roomId)?.online));
|
|
478
1553
|
}
|
|
479
1554
|
|
|
@@ -998,6 +2073,7 @@ function connect() {
|
|
|
998
2073
|
if (state.ws !== ws) return;
|
|
999
2074
|
state.ws = null;
|
|
1000
2075
|
e2eReset();
|
|
2076
|
+
failAllFencedFetches("mất kết nối tới máy — giữ dữ liệu gần nhất"); // snapshots stay
|
|
1001
2077
|
if (state.roomId && pinnedHost()) clearRoomPayload();
|
|
1002
2078
|
if (event.code === 4001 && ["unknown device credentials", "revoked"].includes(event.reason)) {
|
|
1003
2079
|
dropDevice();
|
|
@@ -1169,6 +2245,7 @@ function askView() {
|
|
|
1169
2245
|
return sendPayload({ op: "view" });
|
|
1170
2246
|
}
|
|
1171
2247
|
function applyPayload(payload) {
|
|
2248
|
+
if (routeFencedReply(payload)) return; // fenced: the surface that asked applies it
|
|
1172
2249
|
// The plaintext (or decrypted) payload from the host lands here.
|
|
1173
2250
|
if (payload && typeof payload === "object" && payload.op === "view") {
|
|
1174
2251
|
state.view = payload.view;
|
|
@@ -1189,27 +2266,84 @@ function applyPayload(payload) {
|
|
|
1189
2266
|
state.roomUi?.updateWorker?.(true);
|
|
1190
2267
|
return;
|
|
1191
2268
|
} else if (payload && typeof payload === "object" && payload.op === "worker.submitted") {
|
|
1192
|
-
state.worker.jobs.set(payload.id, {
|
|
2269
|
+
state.worker.jobs.set(payload.id, {
|
|
2270
|
+
id: payload.id,
|
|
2271
|
+
status: payload.state,
|
|
2272
|
+
duplicate: payload.duplicate === true,
|
|
2273
|
+
hasBody: false,
|
|
2274
|
+
prompt: state.worker.draft ?? undefined, // the session's user bubble, when we typed it
|
|
2275
|
+
ts: Date.now(),
|
|
2276
|
+
principal: state.deviceId ? `device:${state.deviceId}` : null,
|
|
2277
|
+
events: [],
|
|
2278
|
+
});
|
|
2279
|
+
state.worker.draft = null;
|
|
1193
2280
|
sendPayload({ op: "receipt.watch", id: payload.id, wantBody: true });
|
|
1194
2281
|
state.roomUi?.updateWorker?.(true);
|
|
1195
2282
|
return;
|
|
1196
2283
|
} else if (payload && typeof payload === "object" && payload.op === "worker.status.result") {
|
|
1197
|
-
workerJobTouched(payload.id, { status: payload.state, ...(payload.reason ? { reason: payload.reason } : {}) });
|
|
2284
|
+
workerJobTouched(payload.id, { status: payload.state, ...(payload.reason ? { reason: payload.reason } : {}), ...(payload.usage ? { usage: payload.usage } : {}) });
|
|
1198
2285
|
return;
|
|
1199
2286
|
} else if (payload && typeof payload === "object" && payload.op === "receipt.watched") {
|
|
1200
|
-
workerJobTouched(payload.id, payload.pending
|
|
2287
|
+
workerJobTouched(payload.id, payload.pending
|
|
2288
|
+
? { status: "pending" }
|
|
2289
|
+
: { status: payload.status, ...(payload.reason ? { reason: payload.reason } : {}), ...(payload.usage ? { usage: payload.usage } : {}) });
|
|
1201
2290
|
return;
|
|
1202
2291
|
} else if (payload && typeof payload === "object" && payload.op === "receipt.push") {
|
|
1203
|
-
workerJobTouched(payload.id, { status: payload.status, ...(payload.reason ? { reason: payload.reason } : {}), hasBody: payload.hasBody === true });
|
|
2292
|
+
workerJobTouched(payload.id, { status: payload.status, ...(payload.reason ? { reason: payload.reason } : {}), hasBody: payload.hasBody === true, ...(payload.usage ? { usage: payload.usage } : {}) });
|
|
1204
2293
|
sendPayload({ op: "receipt.ack", id: payload.id }); // displayed — retire the intent
|
|
1205
2294
|
return;
|
|
2295
|
+
} else if (payload && typeof payload === "object" && payload.op === "receipt.search.result") {
|
|
2296
|
+
// Metadata hits (id/score/status/reason/usage/principal); snippets and session
|
|
2297
|
+
// files are host-local privileges the channel never carries.
|
|
2298
|
+
state.worker.search = { hits: Array.isArray(payload.hits) ? payload.hits : [], reason: payload.reason ?? null };
|
|
2299
|
+
state.roomUi?.updateWorker?.(Boolean(state.hello?.agents?.find((r) => r.roomId === state.roomId)?.online));
|
|
2300
|
+
return;
|
|
1206
2301
|
} else if (payload && typeof payload === "object" && payload.op === "receipt.body.result") {
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
2302
|
+
applyBodyResult(payload); // unfenced fallback (pushes); fenced replies apply at their caller
|
|
2303
|
+
return;
|
|
2304
|
+
} else if (payload && typeof payload === "object" && payload.op === "diff.result") {
|
|
2305
|
+
state.diff = {
|
|
2306
|
+
ref: typeof payload.ref === "string" ? payload.ref : (state.diff?.ref ?? ""),
|
|
2307
|
+
text: typeof payload.text === "string" ? payload.text : "",
|
|
2308
|
+
bytes: payload.bytes ?? 0,
|
|
2309
|
+
truncated: payload.truncated === true,
|
|
2310
|
+
error: null,
|
|
2311
|
+
loading: false,
|
|
2312
|
+
};
|
|
2313
|
+
state.roomUi?.updateWorker?.(Boolean(state.hello?.agents?.find((r) => r.roomId === state.roomId)?.online));
|
|
2314
|
+
return;
|
|
2315
|
+
} else if (payload && typeof payload === "object" && payload.op === "receipt.result") {
|
|
2316
|
+
// An ack/refresh follow-up: fold the verdict back into the row that asked.
|
|
2317
|
+
if (payload.id) {
|
|
2318
|
+
workerJobTouched(payload.id, { status: payload.status ?? "unknown", ...(payload.reason ? { reason: payload.reason } : {}) });
|
|
2319
|
+
const s = state.worker.search;
|
|
2320
|
+
const hit = Array.isArray(s?.hits) ? s.hits.find((h) => h.id === payload.id) : null;
|
|
2321
|
+
if (hit) {
|
|
2322
|
+
hit.status = payload.status ?? "unknown";
|
|
2323
|
+
if (payload.reason) hit.reason = payload.reason;
|
|
2324
|
+
state.roomUi?.updateWorker?.(Boolean(state.hello?.agents?.find((r) => r.roomId === state.roomId)?.online));
|
|
2325
|
+
}
|
|
2326
|
+
}
|
|
2327
|
+
return;
|
|
2328
|
+
} else if (payload && typeof payload === "object" && payload.op === "usage.rollup.result") {
|
|
2329
|
+
state.worker.usage = payload;
|
|
2330
|
+
state.roomUi?.updateWorker?.(Boolean(state.hello?.agents?.find((r) => r.roomId === state.roomId)?.online));
|
|
2331
|
+
return;
|
|
2332
|
+
} else if (payload && typeof payload === "object" && payload.op === "error"
|
|
2333
|
+
&& (payload.code === "usage-unavailable" || payload.reason === "usage-unavailable" || payload.code === "usage.rollup")) {
|
|
2334
|
+
// Older hosts have no usage roll-up wired: scoped to the Usage tab, never the room.
|
|
2335
|
+
state.worker.usage = { unavailable: true };
|
|
2336
|
+
state.roomUi?.updateWorker?.(true);
|
|
1210
2337
|
return;
|
|
1211
2338
|
} else if (payload && typeof payload === "object" && payload.op === "error" && payload.code === "busy") {
|
|
1212
2339
|
return; // our poll raced the host's 1/s throttle — the next tick catches up
|
|
2340
|
+
} else if (payload && typeof payload === "object" && payload.op === "error" && DIFF_ERROR_CODES.has(payload.code)) {
|
|
2341
|
+
// A refused diff faults only the Diff view, never the room.
|
|
2342
|
+
state.diff = { ...(state.diff ?? { ref: "", text: null }), error: payload.message ?? payload.code ?? "the host refused", loading: false };
|
|
2343
|
+
state.roomUi?.updateWorker?.(true);
|
|
2344
|
+
return;
|
|
2345
|
+
} else if (payload && typeof payload === "object" && payload.op === "error" && PANE_ERROR_CODES.has(payload.code)) {
|
|
2346
|
+
return; // no pane-focus surface yet — the refusal is not the room's problem
|
|
1213
2347
|
} else if (payload && typeof payload === "object" && payload.op === "error" && WORKER_ERROR_CODES.has(payload.code)) {
|
|
1214
2348
|
// Scoped to the worker panel: a refused submit/watch must not blank the room view.
|
|
1215
2349
|
state.worker.error = payload.message ?? payload.code ?? "the host refused";
|
|
@@ -1294,6 +2428,177 @@ function deviceName() {
|
|
|
1294
2428
|
return "browser";
|
|
1295
2429
|
}
|
|
1296
2430
|
|
|
2431
|
+
// ---- Cmd+K fuzzy jump -------------------------------------------------------
|
|
2432
|
+
|
|
2433
|
+
// The palette's fixed destinations: the activity-bar views of the open room.
|
|
2434
|
+
const CMDK_VIEWS = [
|
|
2435
|
+
["jobs", "Jobs — hàng đợi và receipts"],
|
|
2436
|
+
["search", "Search — tìm receipt theo nội dung"],
|
|
2437
|
+
["recap", "Recap — đến lượt ai?"],
|
|
2438
|
+
["usage", "Usage — bảng 7 ngày"],
|
|
2439
|
+
["timeline", "Chat — thread mỗi session"],
|
|
2440
|
+
["diff", "Diff — git show một ref"],
|
|
2441
|
+
];
|
|
2442
|
+
|
|
2443
|
+
/** Subsequence match with a small score: earlier + consecutive hits win. */
|
|
2444
|
+
function fuzzyScore(query, target) {
|
|
2445
|
+
const q = query.toLowerCase();
|
|
2446
|
+
const t = target.toLowerCase();
|
|
2447
|
+
if (!q) return 1;
|
|
2448
|
+
let qi = 0;
|
|
2449
|
+
let score = 0;
|
|
2450
|
+
let streak = 0;
|
|
2451
|
+
let last = -2;
|
|
2452
|
+
for (let ti = 0; ti < t.length && qi < q.length; ti += 1) {
|
|
2453
|
+
if (t[ti] !== q[qi]) continue;
|
|
2454
|
+
qi += 1;
|
|
2455
|
+
streak = last === ti - 1 ? streak + 1 : 1;
|
|
2456
|
+
score += 1 + streak * 2 + (ti === 0 ? 3 : 0);
|
|
2457
|
+
last = ti;
|
|
2458
|
+
}
|
|
2459
|
+
return qi === q.length ? score - t.length * 0.05 : -1;
|
|
2460
|
+
}
|
|
2461
|
+
|
|
2462
|
+
/** Everything Enter can open right now: views, recent receipts/jobs, and — when
|
|
2463
|
+
* the query itself is a legal ref — a diff of exactly that ref. */
|
|
2464
|
+
function cmdkItems(query) {
|
|
2465
|
+
const items = [];
|
|
2466
|
+
for (const [key, label] of CMDK_VIEWS) {
|
|
2467
|
+
items.push({ label: `View · ${label}`, score: fuzzyScore(query, `${key} ${label}`), run: () => state.openWorkerTab?.(key) });
|
|
2468
|
+
}
|
|
2469
|
+
const goto = parseLineSuffix(query);
|
|
2470
|
+
if (goto) {
|
|
2471
|
+
items.push({
|
|
2472
|
+
label: `Goto · ${goto.path}:${goto.line}${goto.end > goto.line ? `-${goto.end}` : ""}`,
|
|
2473
|
+
score: 2,
|
|
2474
|
+
run: () => gotoDiffLine(query),
|
|
2475
|
+
});
|
|
2476
|
+
}
|
|
2477
|
+
for (const job of [...state.worker.jobs.values()].slice(-10).reverse()) {
|
|
2478
|
+
items.push({
|
|
2479
|
+
label: `Receipt · ${job.id.slice(0, 8)} · ${job.status}${job.reason ? ` (${job.reason})` : ""}`,
|
|
2480
|
+
score: fuzzyScore(query, `${job.id} ${job.status} ${job.reason ?? ""}`),
|
|
2481
|
+
run: () => {
|
|
2482
|
+
state.openWorkerTab?.("jobs");
|
|
2483
|
+
if (job.status === "replied") fetchReceiptBody(job.id);
|
|
2484
|
+
else if (job.status === "unknown") sendPayload({ op: "receipt.get", id: job.id });
|
|
2485
|
+
},
|
|
2486
|
+
});
|
|
2487
|
+
}
|
|
2488
|
+
if (/^[A-Za-z0-9._\/-]{3,64}$/.test(query)) {
|
|
2489
|
+
items.push({ label: `Diff · git show ${query}`, score: 0.5, run: () => openDiffRef(query) });
|
|
2490
|
+
}
|
|
2491
|
+
return items.filter((item) => item.score >= 0).sort((a, b) => b.score - a.score).slice(0, 9);
|
|
2492
|
+
}
|
|
2493
|
+
|
|
2494
|
+
/** Jump straight to the Diff view with a ref (palette or URL hand-off). */
|
|
2495
|
+
function openDiffRef(ref) {
|
|
2496
|
+
state.openWorkerTab?.("diff");
|
|
2497
|
+
loadDiff(ref);
|
|
2498
|
+
}
|
|
2499
|
+
|
|
2500
|
+
let cmdk = null;
|
|
2501
|
+
|
|
2502
|
+
function ensureCmdk() {
|
|
2503
|
+
if (cmdk) return cmdk;
|
|
2504
|
+
const root = document.createElement("div");
|
|
2505
|
+
root.className = "cmdk";
|
|
2506
|
+
root.hidden = true;
|
|
2507
|
+
const box = document.createElement("div");
|
|
2508
|
+
box.className = "cmdk-box";
|
|
2509
|
+
const input = document.createElement("input");
|
|
2510
|
+
input.type = "search";
|
|
2511
|
+
input.placeholder = "nhảy tới… (view, receipt, git ref)";
|
|
2512
|
+
const list = document.createElement("ul");
|
|
2513
|
+
list.className = "cmdk-list";
|
|
2514
|
+
const hint = document.createElement("p");
|
|
2515
|
+
hint.className = "muted small";
|
|
2516
|
+
hint.textContent = "↑ ↓ chọn · Enter mở · Esc đóng";
|
|
2517
|
+
box.append(input, list, hint);
|
|
2518
|
+
root.append(box);
|
|
2519
|
+
root.addEventListener("click", (event) => {
|
|
2520
|
+
if (event.target === root) closeCmdk();
|
|
2521
|
+
});
|
|
2522
|
+
document.documentElement.append(root);
|
|
2523
|
+
const ui = { root, input, list, items: [], sel: 0 };
|
|
2524
|
+
input.addEventListener("input", () => {
|
|
2525
|
+
ui.sel = 0;
|
|
2526
|
+
renderCmdk(ui);
|
|
2527
|
+
});
|
|
2528
|
+
input.addEventListener("keydown", (event) => {
|
|
2529
|
+
if (event.key === "ArrowDown") {
|
|
2530
|
+
event.preventDefault();
|
|
2531
|
+
ui.sel = Math.min(ui.sel + 1, ui.items.length - 1);
|
|
2532
|
+
renderCmdk(ui);
|
|
2533
|
+
} else if (event.key === "ArrowUp") {
|
|
2534
|
+
event.preventDefault();
|
|
2535
|
+
ui.sel = Math.max(ui.sel - 1, 0);
|
|
2536
|
+
renderCmdk(ui);
|
|
2537
|
+
} else if (event.key === "Enter") {
|
|
2538
|
+
event.preventDefault();
|
|
2539
|
+
const item = ui.items[ui.sel];
|
|
2540
|
+
if (item) {
|
|
2541
|
+
closeCmdk();
|
|
2542
|
+
item.run();
|
|
2543
|
+
}
|
|
2544
|
+
} else if (event.key === "Escape") {
|
|
2545
|
+
event.preventDefault();
|
|
2546
|
+
closeCmdk();
|
|
2547
|
+
}
|
|
2548
|
+
});
|
|
2549
|
+
cmdk = ui;
|
|
2550
|
+
return ui;
|
|
2551
|
+
}
|
|
2552
|
+
|
|
2553
|
+
function renderCmdk(ui) {
|
|
2554
|
+
ui.items = cmdkItems(ui.input.value.trim());
|
|
2555
|
+
if (ui.sel >= ui.items.length) ui.sel = Math.max(0, ui.items.length - 1);
|
|
2556
|
+
ui.list.replaceChildren();
|
|
2557
|
+
ui.items.forEach((item, i) => {
|
|
2558
|
+
const row = document.createElement("li");
|
|
2559
|
+
row.className = i === ui.sel ? "active" : "";
|
|
2560
|
+
row.textContent = item.label;
|
|
2561
|
+
row.addEventListener("click", () => {
|
|
2562
|
+
closeCmdk();
|
|
2563
|
+
item.run();
|
|
2564
|
+
});
|
|
2565
|
+
ui.list.append(row);
|
|
2566
|
+
});
|
|
2567
|
+
if (!ui.items.length) {
|
|
2568
|
+
const none = document.createElement("li");
|
|
2569
|
+
none.className = "muted small";
|
|
2570
|
+
none.textContent = "không có gì khớp";
|
|
2571
|
+
ui.list.append(none);
|
|
2572
|
+
}
|
|
2573
|
+
}
|
|
2574
|
+
|
|
2575
|
+
function openCmdk() {
|
|
2576
|
+
const ui = ensureCmdk();
|
|
2577
|
+
ui.root.hidden = false;
|
|
2578
|
+
ui.input.value = "";
|
|
2579
|
+
ui.sel = 0;
|
|
2580
|
+
renderCmdk(ui);
|
|
2581
|
+
ui.input.focus();
|
|
2582
|
+
}
|
|
2583
|
+
|
|
2584
|
+
function closeCmdk() {
|
|
2585
|
+
if (cmdk) cmdk.root.hidden = true;
|
|
2586
|
+
}
|
|
2587
|
+
|
|
2588
|
+
function toggleCmdk() {
|
|
2589
|
+
if (cmdk && !cmdk.root.hidden) closeCmdk();
|
|
2590
|
+
else openCmdk();
|
|
2591
|
+
}
|
|
2592
|
+
|
|
2593
|
+
// The standard web chord, captured wherever it lands; the header button says so.
|
|
2594
|
+
document.addEventListener("keydown", (event) => {
|
|
2595
|
+
if ((event.metaKey || event.ctrlKey) && String(event.key ?? "").toLowerCase() === "k") {
|
|
2596
|
+
event.preventDefault();
|
|
2597
|
+
toggleCmdk();
|
|
2598
|
+
}
|
|
2599
|
+
});
|
|
2600
|
+
$("cmdk-open")?.addEventListener("click", () => toggleCmdk());
|
|
2601
|
+
|
|
1297
2602
|
// ---- pairing ---------------------------------------------------------------
|
|
1298
2603
|
|
|
1299
2604
|
function openPair(roomId) {
|
|
@@ -1444,6 +2749,14 @@ function resetRoomView() {
|
|
|
1444
2749
|
state.view = null;
|
|
1445
2750
|
state.viewError = null;
|
|
1446
2751
|
state.roomUi = null;
|
|
2752
|
+
state.diff = null;
|
|
2753
|
+
state.chat = { filter: null, spawn: null };
|
|
2754
|
+
state.worker.chatError = null;
|
|
2755
|
+
state.worker.searchError = null;
|
|
2756
|
+
state.worker.bodyError = null;
|
|
2757
|
+
state.worker.enrich = null;
|
|
2758
|
+
state.openWorkerTab = null;
|
|
2759
|
+
newGeneration(); // a new mount: replies answering the old generation are dropped
|
|
1447
2760
|
$("view").replaceChildren();
|
|
1448
2761
|
}
|
|
1449
2762
|
|
|
@@ -1481,6 +2794,16 @@ function forgetToken() {
|
|
|
1481
2794
|
if (el) el.textContent = "herdgate " + BUILD;
|
|
1482
2795
|
}
|
|
1483
2796
|
|
|
2797
|
+
// QR pairing round: a scan opens the app with #pair=<code> — prefill the one-line
|
|
2798
|
+
// approval input so the owner only has to press Approve.
|
|
2799
|
+
{
|
|
2800
|
+
const m = /#pair=([A-Za-z0-9]{4,64})/.exec(location.hash ?? "");
|
|
2801
|
+
if (m) {
|
|
2802
|
+
const input = $("addmachine-code");
|
|
2803
|
+
if (input) input.value = m[1];
|
|
2804
|
+
}
|
|
2805
|
+
}
|
|
2806
|
+
|
|
1484
2807
|
render();
|
|
1485
2808
|
if (state.token) connect();
|
|
1486
2809
|
|
|
@@ -1503,3 +2826,61 @@ if ("serviceWorker" in navigator && location.protocol !== "file:") {
|
|
|
1503
2826
|
});
|
|
1504
2827
|
});
|
|
1505
2828
|
}
|
|
2829
|
+
|
|
2830
|
+
// ---- node:test seam ----------------------------------------------------------
|
|
2831
|
+
// The PWA suite runs this file in a bare VM and anchors these helpers through
|
|
2832
|
+
// `globalThis.__herdgateWebTest`. The browser never defines the anchor, so this
|
|
2833
|
+
// block is inert in production.
|
|
2834
|
+
{
|
|
2835
|
+
const anchor = globalThis.__herdgateWebTest;
|
|
2836
|
+
if (anchor) {
|
|
2837
|
+
Object.assign(anchor, {
|
|
2838
|
+
parseLineSuffix,
|
|
2839
|
+
newGeneration,
|
|
2840
|
+
generationCurrent,
|
|
2841
|
+
diffGotoIndexes,
|
|
2842
|
+
fetchInfo: () => ({
|
|
2843
|
+
gen: fetches.gen,
|
|
2844
|
+
inflight: [...fetches.inflight.values()].map((e) => ({ key: e.key, gen: e.gen, fresh: e.fresh })),
|
|
2845
|
+
}),
|
|
2846
|
+
fetchDrive: (op, replyOp, payload, opts) => {
|
|
2847
|
+
const sent = [];
|
|
2848
|
+
state.roomId ??= "pwa3-room";
|
|
2849
|
+
state.ws = { readyState: 1, send: (raw) => sent.push(JSON.parse(raw)) };
|
|
2850
|
+
return { sent, promise: opFetch(op, replyOp, payload, opts) };
|
|
2851
|
+
},
|
|
2852
|
+
fetchReply: (payload) => routeFencedReply(payload),
|
|
2853
|
+
online: () => {
|
|
2854
|
+
state.roomId ??= "pwa3-room";
|
|
2855
|
+
state.ws = { readyState: 1, send() {} };
|
|
2856
|
+
},
|
|
2857
|
+
offline: () => { state.ws = null; },
|
|
2858
|
+
chatFetch: (fresh) => fetchChatUsage(fresh),
|
|
2859
|
+
chatSnap: () => ({
|
|
2860
|
+
usage: state.worker.usage ?? null,
|
|
2861
|
+
chatError: state.worker.chatError ?? null,
|
|
2862
|
+
filter: state.chat.filter ?? null,
|
|
2863
|
+
}),
|
|
2864
|
+
enrichSnap: () => {
|
|
2865
|
+
const e = state.worker.enrich;
|
|
2866
|
+
return e ? { id: e.id, loading: e.loading, error: e.error ?? null, result: e.result ?? null } : null;
|
|
2867
|
+
},
|
|
2868
|
+
enrichToggle: (id) => toggleReceiptEnrich(id),
|
|
2869
|
+
enrichRows: (result) => JSON.parse(JSON.stringify(enrichRows(result))),
|
|
2870
|
+
contextPctOf: (tokens, max) => contextPctOf(tokens, max),
|
|
2871
|
+
probe: {
|
|
2872
|
+
detail: (id) => receiptDetailNode(id),
|
|
2873
|
+
thread: (job) => chatThread(job),
|
|
2874
|
+
subagent: (name, extra = {}) => subagentCard({
|
|
2875
|
+
principal: `spawn:${name}`, requests: 1, replied: 1, failed: 0,
|
|
2876
|
+
tokens: 4321, costUsd: 0.01, lastTs: Date.now() - 60_000, ...extra,
|
|
2877
|
+
}, true),
|
|
2878
|
+
linked: (text) => {
|
|
2879
|
+
const el = document.createElement("div");
|
|
2880
|
+
appendLinkedText(el, text);
|
|
2881
|
+
return el;
|
|
2882
|
+
},
|
|
2883
|
+
},
|
|
2884
|
+
});
|
|
2885
|
+
}
|
|
2886
|
+
}
|