@bom0792/herdgate 0.9.39 → 0.9.41

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/src/web/app.js CHANGED
@@ -38,6 +38,7 @@ function clearLegacyPair() {
38
38
  }
39
39
 
40
40
  import { DeviceChannel, generateKeyPair, needsRekey } from "/e2e.js";
41
+ import { hgFuzzy } from "/fuzzy.js";
41
42
 
42
43
  // E2E payloads: this device's Noise_XX identity (kept locally, never sent to the cloud
43
44
  // in the clear) and the host fingerprints it has pinned (TOFU per room).
@@ -159,7 +160,7 @@ const state = {
159
160
  termBody: null,
160
161
  termPre: null,
161
162
  retry: 0,
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
+ worker: { health: null, jobs: new Map(), error: null, search: null, searchError: null, tab: "jobs", usage: null, chatError: null, bodyError: null, draft: null, enrich: null, files: { tree: null, total: 0, capped: false, loading: false, error: null, query: "", open: null, text: null, lines: 0, truncated: false, goto: null, search: "" }, review: { scope: "uncommitted", files: null, base: null, capped: false, loading: false, error: null, open: null, diff: null, truncated: false, comments: {}, boxLine: null, sending: false, sent: null } },
163
164
  diff: null,
164
165
  chat: { filter: null, spawn: null },
165
166
  };
@@ -915,6 +916,8 @@ function fetchReceiptBody(id) {
915
916
  * ("no readable transcript…" is data, not a bug to swallow); a transport
916
917
  * fault keeps the shared never-blank banner instead of closing the panel. */
917
918
  const ENRICH_ERR_CODES = new Set(["receipt.enrich", "pi_receipts_disabled"]);
919
+ const FILE_ERR_CODES = new Set(["diff.repo", "files.tree", "files.read", "bad-path", "no-file", "file.tree", "file.read"]);
920
+ const REVIEW_ERR_CODES = new Set(["diff.repo", "review", "bad-scope", "no-base", "no-anchor", "bad-path", "no-file"]);
918
921
 
919
922
  function fetchReceiptEnrich(id) {
920
923
  state.worker.enrich = { id, loading: true, error: null, result: null };
@@ -1131,6 +1134,411 @@ function gotoDiffLine(target) {
1131
1134
  return true;
1132
1135
  }
1133
1136
 
1137
+ // ---- Files (filev): fuzzy find, read one, smartcase in-file search -------------
1138
+
1139
+ function fetchFileTree() {
1140
+ const w = state.worker.files;
1141
+ w.loading = true;
1142
+ const gen = currentGeneration();
1143
+ opFetch("file.tree", "file.tree.result", {}, { key: "file-tree", fresh: true, errCodes: FILE_ERR_CODES })
1144
+ .then((p) => {
1145
+ if (!generationCurrent(gen)) return;
1146
+ w.loading = false;
1147
+ if (isTransportFault(p)) { w.error = p.message; return; }
1148
+ if (p.op === "error") { w.error = p.message; return; }
1149
+ w.error = null;
1150
+ w.tree = p.files ?? [];
1151
+ w.total = p.total ?? w.tree.length;
1152
+ w.capped = Boolean(p.capped);
1153
+ })
1154
+ .catch(() => { if (generationCurrent(gen)) { w.loading = false; w.error = "file.tree không trả lời"; } });
1155
+ }
1156
+
1157
+ function openFileAt(path, goto) {
1158
+ const w = state.worker.files;
1159
+ state.openWorkerTab?.("files");
1160
+ w.open = path;
1161
+ w.text = null;
1162
+ w.error = null;
1163
+ w.goto = goto ?? null;
1164
+ w.search = "";
1165
+ const gen = currentGeneration();
1166
+ opFetch("file.read", "file.read.result", { path }, { key: `file-read:${path}`, fresh: true, errCodes: FILE_ERR_CODES })
1167
+ .then((p) => {
1168
+ if (!generationCurrent(gen) || w.open !== path) return;
1169
+ if (isTransportFault(p)) { w.error = p.message; return; }
1170
+ if (p.op === "error") { w.error = p.message; return; }
1171
+ w.error = null;
1172
+ w.text = typeof p.text === "string" ? p.text : "";
1173
+ w.lines = p.lines ?? 0;
1174
+ w.truncated = Boolean(p.truncated);
1175
+ })
1176
+ .catch(() => { if (generationCurrent(gen) && w.open === path) w.error = "file.read không trả lời"; });
1177
+ }
1178
+
1179
+ /** Render the Files surface into its slot: the fuzzy list, or the open file with
1180
+ * line numbers, search highlighting and a path:line flash. Wire-only — the
1181
+ * scoring lives in /fuzzy.js, the hardening on the host. */
1182
+ function renderWorkerFiles(out, w) {
1183
+ out.replaceChildren();
1184
+ if (w.error) {
1185
+ out.append(note(w.error, "error"));
1186
+ const back = document.createElement("button");
1187
+ back.type = "button";
1188
+ back.className = "link";
1189
+ back.textContent = "← danh sách file";
1190
+ back.addEventListener("click", () => { const f = state.worker.files; f.error = null; f.open = null; f.text = null; });
1191
+ out.append(back);
1192
+ return;
1193
+ }
1194
+ if (w.open) {
1195
+ renderFileBody(out, w);
1196
+ return;
1197
+ }
1198
+ if (w.loading) {
1199
+ out.append(note("đang đọc cây file…"));
1200
+ return;
1201
+ }
1202
+ if (!w.tree) {
1203
+ out.append(note("chưa có cây file — mở tab Files khi host online."));
1204
+ return;
1205
+ }
1206
+ const paths = w.tree.map((f) => f.path);
1207
+ const statusOf = new Map(w.tree.map((f) => [f.path, f.status]));
1208
+ const ranked = w.query ? hgFuzzy.matchAndRank(w.query, paths) : paths.map((_, i) => i);
1209
+ const shown = ranked.slice(0, 100).map((i) => w.tree[i]);
1210
+ if (w.capped) out.append(note(`cây bị giới hạn ${w.tree.length}/${w.total} file — tìm mờ để lọc.`));
1211
+ const list = document.createElement("ul");
1212
+ list.className = "files-list";
1213
+ for (const f of shown) {
1214
+ const li = document.createElement("li");
1215
+ const row = document.createElement("button");
1216
+ row.type = "button";
1217
+ const mark = document.createElement("span");
1218
+ mark.className = `fstat ${f.status ? "fstat-" + f.status[0] : ""}`;
1219
+ mark.textContent = f.status ? f.status[0] : "·";
1220
+ const name = document.createElement("span");
1221
+ name.className = "fpath";
1222
+ name.textContent = f.path;
1223
+ row.append(mark, name);
1224
+ row.addEventListener("click", () => openFileAt(f.path));
1225
+ li.append(row);
1226
+ list.append(li);
1227
+ }
1228
+ out.append(list);
1229
+ if (!shown.length) out.append(note(w.query ? "không file nào khớp truy vấn." : "repo rỗng (không có file nào được git theo dõi)."));
1230
+ }
1231
+
1232
+ function renderFileBody(out, w) {
1233
+ const head = document.createElement("div");
1234
+ head.className = "files-head";
1235
+ const back = document.createElement("button");
1236
+ back.type = "button";
1237
+ back.className = "link";
1238
+ back.textContent = "← files";
1239
+ back.addEventListener("click", () => { w.open = null; w.text = null; w.goto = null; });
1240
+ const title = document.createElement("span");
1241
+ title.className = "fpath";
1242
+ title.textContent = w.open;
1243
+ head.append(back, title);
1244
+ if (w.truncated) head.append(note(" (capped 256KiB)", "small"));
1245
+ const search = document.createElement("input");
1246
+ search.type = "text";
1247
+ search.placeholder = "tìm trong file (smartcase)";
1248
+ search.maxLength = 128;
1249
+ search.className = "file-search";
1250
+ search.value = w.search;
1251
+ search.addEventListener("input", () => { w.search = search.value; });
1252
+ head.append(search);
1253
+ out.append(head);
1254
+ if (w.text === null) {
1255
+ out.append(note(`đang đọc ${w.open}…`));
1256
+ return;
1257
+ }
1258
+ const lines = w.text.split("\n");
1259
+ const body = document.createElement("div");
1260
+ body.className = "file-body";
1261
+ let firstHit = -1;
1262
+ for (let i = 0; i < lines.length; i++) {
1263
+ const row = document.createElement("div");
1264
+ row.className = "file-line";
1265
+ const no = document.createElement("span");
1266
+ no.className = "line-no";
1267
+ no.textContent = String(i + 1);
1268
+ row.append(no);
1269
+ const text = lines[i] || " ";
1270
+ if (w.search) {
1271
+ const hits = hgFuzzy.searchLine(text, w.search);
1272
+ let at = 0;
1273
+ for (const [s, e] of hits) {
1274
+ if (s > at) row.append(document.createTextNode(text.slice(at, s)));
1275
+ const hit = document.createElement("span");
1276
+ hit.className = "file-hit";
1277
+ hit.textContent = text.slice(s, e);
1278
+ row.append(hit);
1279
+ at = e;
1280
+ if (firstHit === -1) firstHit = i;
1281
+ }
1282
+ row.append(document.createTextNode(text.slice(at)));
1283
+ } else {
1284
+ row.append(document.createTextNode(text));
1285
+ }
1286
+ body.append(row);
1287
+ }
1288
+ out.append(body);
1289
+ // path:line flash (the same 3s reveal the diff uses) — goto wins over search.
1290
+ const target = w.goto;
1291
+ w.goto = null;
1292
+ const flashRows = body.children;
1293
+ const applyFlash = (idx) => {
1294
+ for (let k = Math.max(0, idx - 2); k <= Math.min(flashRows.length - 1, idx + 2); k++) flashRows[k]?.classList?.add?.("flash");
1295
+ flashRows[idx]?.scrollIntoView?.({ block: "center" });
1296
+ setTimeout(() => {
1297
+ for (let k = 0; k < flashRows.length; k++) flashRows[k]?.classList?.remove?.("flash");
1298
+ }, 3000);
1299
+ };
1300
+ if (target && target.line >= 1 && target.line <= lines.length) applyFlash(target.line - 1);
1301
+ else if (firstHit >= 0) applyFlash(firstHit);
1302
+ }
1303
+
1304
+ // ---- Review (reviewr mobile): scoped change lists, per-line comments, send ---
1305
+
1306
+ const REVIEW_SCOPES = [["uncommitted", "Chưa commit"], ["branch", "Chưa đẩy"], ["turn", "Lượt cuối"]];
1307
+
1308
+ /** Unified diff → typed rows with old/new line numbers. Pure — the wire gives
1309
+ * text, the view needs structure (hunk headers, +/-/ctx, numbering). */
1310
+ function parseUnifiedDiff(text) {
1311
+ const rows = [];
1312
+ let a = 0;
1313
+ let b = 0;
1314
+ for (const line of String(text ?? "").split("\n")) {
1315
+ const hunk = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line);
1316
+ if (hunk) { a = Number(hunk[1]); b = Number(hunk[2]); rows.push({ type: "hunk", text: line }); continue; }
1317
+ if (line.startsWith("+++") || line.startsWith("---") || line.startsWith("diff ") || line.startsWith("index ") || line.startsWith("\\ No newline")) { rows.push({ type: "meta", text: line }); continue; }
1318
+ if (line.startsWith("+")) { rows.push({ type: "add", b, text: line.slice(1) }); b++; continue; }
1319
+ if (line.startsWith("-")) { rows.push({ type: "del", a, text: line.slice(1) }); a++; continue; }
1320
+ if (line.startsWith(" ")) { rows.push({ type: "ctx", a, b, text: line.slice(1) }); a++; b++; continue; }
1321
+ rows.push({ type: "meta", text: line }); // diff/index/---/+++ headers and \ No newline
1322
+ }
1323
+ return rows;
1324
+ }
1325
+
1326
+ function fetchReviewFiles(scope) {
1327
+ const w = state.worker.review;
1328
+ w.scope = scope;
1329
+ w.loading = true;
1330
+ w.error = null;
1331
+ w.files = null;
1332
+ w.open = null;
1333
+ w.diff = null;
1334
+ const gen = currentGeneration();
1335
+ opFetch("review.files", "review.files.result", { scope }, { key: `review-files:${scope}`, fresh: true, errCodes: REVIEW_ERR_CODES })
1336
+ .then((p) => {
1337
+ if (!generationCurrent(gen)) return;
1338
+ w.loading = false;
1339
+ if (isTransportFault(p)) { w.error = p.message; return; }
1340
+ if (p.op === "error") { w.error = p.message; return; }
1341
+ w.error = null;
1342
+ w.files = p.files ?? [];
1343
+ w.base = p.base ?? null;
1344
+ w.capped = Boolean(p.capped);
1345
+ })
1346
+ .catch(() => { if (generationCurrent(gen)) { w.loading = false; w.error = "review.files không trả lời"; } });
1347
+ }
1348
+
1349
+ function openReviewDiff(path) {
1350
+ const w = state.worker.review;
1351
+ w.open = path;
1352
+ w.diff = null;
1353
+ w.error = null;
1354
+ w.boxLine = null;
1355
+ const gen = currentGeneration();
1356
+ opFetch("review.diff", "review.diff.result", { scope: w.scope, path }, { key: `review-diff:${w.scope}:${path}`, fresh: true, errCodes: REVIEW_ERR_CODES })
1357
+ .then((p) => {
1358
+ if (!generationCurrent(gen) || w.open !== path) return;
1359
+ if (isTransportFault(p)) { w.error = p.message; return; }
1360
+ if (p.op === "error") { w.error = p.message; return; }
1361
+ w.error = null;
1362
+ w.diff = typeof p.text === "string" ? p.text : "";
1363
+ w.truncated = Boolean(p.truncated);
1364
+ })
1365
+ .catch(() => { if (generationCurrent(gen) && w.open === path) w.error = "review.diff không trả lời"; });
1366
+ }
1367
+
1368
+ /** Session-only comment store — nothing crosses the wire until Send (the
1369
+ * reviewr discipline: the worktree and the gate stay untouched while reviewing). */
1370
+ function setReviewComment(path, line, text) {
1371
+ const w = state.worker.review;
1372
+ const key = `${path}:${line}`;
1373
+ if (!text || !text.trim()) delete w.comments[key];
1374
+ else w.comments[key] = [{ path, line, text: text.trim().slice(0, 500) }];
1375
+ w.boxLine = null;
1376
+ state.roomUi?.updateWorker?.(true);
1377
+ }
1378
+
1379
+ function sendReviewComments() {
1380
+ const w = state.worker.review;
1381
+ const all = Object.values(w.comments ?? {}).flat();
1382
+ if (!all.length || w.sending) return;
1383
+ w.sending = true;
1384
+ w.sent = null;
1385
+ w.error = null;
1386
+ sendPayload({ op: "review.send", comments: all });
1387
+ // The reply (review.sent) or refusal lands in the frame router above.
1388
+ }
1389
+
1390
+ function renderWorkerReview(out, w) {
1391
+ out.replaceChildren();
1392
+ const r = w.review;
1393
+ if (r.error) out.append(note(r.error, "error"));
1394
+ const chips = document.createElement("div");
1395
+ chips.className = "rev-scopes";
1396
+ for (const [key, label] of REVIEW_SCOPES) {
1397
+ const chip = document.createElement("button");
1398
+ chip.type = "button";
1399
+ chip.className = `rev-chip${r.scope === key ? " active" : ""}`;
1400
+ chip.textContent = label;
1401
+ chip.addEventListener("click", () => { if (r.scope !== key) fetchReviewFiles(key); });
1402
+ chips.append(chip);
1403
+ }
1404
+ out.append(chips);
1405
+ if (r.open) { renderReviewDiff(out, r); return; }
1406
+ if (r.loading) { out.append(note("đang đọc danh sách thay đổi…")); return; }
1407
+ if (r.sent) {
1408
+ const sent = note(`đã gửi ${r.sent.count} comment — job ${String(r.sent.id).slice(0, 8)} (xem Jobs/Chat)`);
1409
+ sent.classList.add("rev-sent");
1410
+ out.append(sent);
1411
+ }
1412
+ if (!r.files) {
1413
+ if (!r.error) out.append(note("chọn scope: thay đổi chưa commit / cả nhánh / đúng lượt agent vừa settle."));
1414
+ return;
1415
+ }
1416
+ const list = document.createElement("ul");
1417
+ list.className = "rev-list";
1418
+ for (const f of r.files) {
1419
+ const li = document.createElement("li");
1420
+ const row = document.createElement("button");
1421
+ row.type = "button";
1422
+ const name = document.createElement("span");
1423
+ name.className = "fpath";
1424
+ name.textContent = f.path;
1425
+ row.append(name);
1426
+ if (f.status === "??") {
1427
+ const badge = document.createElement("span");
1428
+ badge.className = "rev-stat new";
1429
+ badge.textContent = "mới";
1430
+ row.append(badge);
1431
+ } else if (f.plus !== null && f.plus !== undefined) {
1432
+ const stat = document.createElement("span");
1433
+ stat.className = "rev-stat";
1434
+ stat.textContent = `+${f.plus} −${f.minus}`;
1435
+ row.append(stat);
1436
+ }
1437
+ const nComments = Object.keys(r.comments).filter((k) => k.startsWith(`${f.path}:`)).length;
1438
+ if (nComments) {
1439
+ const c = document.createElement("span");
1440
+ c.className = "rev-stat comments";
1441
+ c.textContent = `✎ ${nComments}`;
1442
+ row.append(c);
1443
+ }
1444
+ row.addEventListener("click", () => openReviewDiff(f.path));
1445
+ li.append(row);
1446
+ list.append(li);
1447
+ }
1448
+ out.append(list);
1449
+ if (r.capped) out.append(note("danh sách bị giới hạn 5000 file."));
1450
+ if (!r.files.length && !r.error) out.append(note("scope này không có thay đổi nào."));
1451
+ }
1452
+
1453
+ function renderReviewDiff(out, r) {
1454
+ const head = document.createElement("div");
1455
+ head.className = "files-head";
1456
+ const back = document.createElement("button");
1457
+ back.type = "button";
1458
+ back.className = "link";
1459
+ back.textContent = "← review";
1460
+ back.addEventListener("click", () => { r.open = null; r.diff = null; r.boxLine = null; });
1461
+ const title = document.createElement("span");
1462
+ title.className = "fpath";
1463
+ title.textContent = r.open;
1464
+ head.append(back, title);
1465
+ if (r.truncated) head.append(note(" (capped 128KiB)", "small"));
1466
+ out.append(head);
1467
+ if (r.diff === null) { out.append(note(`đang đọc diff ${r.open}…`)); return; }
1468
+ const body = document.createElement("div");
1469
+ body.className = "file-body rev-diff";
1470
+ const hint = document.createElement("div");
1471
+ hint.className = "rev-hint";
1472
+ hint.textContent = "chạm một dòng để comment";
1473
+ body.append(hint);
1474
+ for (const row of parseUnifiedDiff(r.diff)) {
1475
+ if (row.type === "meta") continue; // headers hidden — the path is in the title
1476
+ const line = document.createElement("div");
1477
+ line.className = `rev-row ${row.type === "hunk" ? "dhunk" : `d${row.type}`}`;
1478
+ if (row.type === "hunk") {
1479
+ line.textContent = row.text;
1480
+ body.append(line);
1481
+ continue;
1482
+ }
1483
+ const num = row.type === "del" ? row.a : row.b;
1484
+ const no = document.createElement("span");
1485
+ no.className = "line-no";
1486
+ no.textContent = num ?? "";
1487
+ const text = document.createElement("span");
1488
+ text.className = "rev-text";
1489
+ text.textContent = row.text;
1490
+ line.append(no, text);
1491
+ if (row.type !== "del") line.addEventListener("click", () => {
1492
+ r.boxLine = r.boxLine === num ? null : num;
1493
+ state.roomUi?.updateWorker?.(true);
1494
+ });
1495
+ body.append(line);
1496
+ const lineComments = r.comments[`${r.open}:${num}`];
1497
+ if (lineComments) for (const c of lineComments) {
1498
+ const chip = document.createElement("div");
1499
+ chip.className = "rev-chip-comment";
1500
+ const label = document.createElement("span");
1501
+ label.textContent = `✎ ${c.text}`;
1502
+ const del = document.createElement("button");
1503
+ del.type = "button";
1504
+ del.className = "link";
1505
+ del.textContent = "×";
1506
+ del.addEventListener("click", () => setReviewComment(r.open, num, null));
1507
+ chip.append(label, del);
1508
+ body.append(chip);
1509
+ }
1510
+ if (r.boxLine === num) {
1511
+ const box = document.createElement("div");
1512
+ box.className = "rev-cbox";
1513
+ const ta = document.createElement("textarea");
1514
+ ta.rows = 2;
1515
+ ta.maxLength = 500;
1516
+ ta.placeholder = `comment cho dòng ${num}`;
1517
+ ta.value = r.comments[`${r.open}:${num}`]?.[0]?.text ?? "";
1518
+ const save = document.createElement("button");
1519
+ save.type = "button";
1520
+ save.textContent = "Lưu";
1521
+ save.addEventListener("click", () => { if (ta.value.trim()) setReviewComment(r.open, num, ta.value); });
1522
+ const cancel = document.createElement("button");
1523
+ cancel.type = "button";
1524
+ cancel.className = "link";
1525
+ cancel.textContent = "Đóng";
1526
+ cancel.addEventListener("click", () => { r.boxLine = null; state.roomUi?.updateWorker?.(true); });
1527
+ box.append(ta, save, cancel);
1528
+ body.append(box);
1529
+ }
1530
+ }
1531
+ out.append(body);
1532
+ const count = Object.values(r.comments).flat().length;
1533
+ const send = document.createElement("button");
1534
+ send.type = "button";
1535
+ send.className = "rev-send";
1536
+ send.textContent = r.sending ? "đang gửi…" : `Gửi ${count} comment về agent`;
1537
+ send.disabled = !count || r.sending;
1538
+ send.addEventListener("click", sendReviewComments);
1539
+ out.append(send);
1540
+ }
1541
+
1134
1542
  // Diff: render one `git show --stat --patch` answer — the stat block first, then
1135
1543
  // the patch with + green, - red, @@ purple. A truncated patch says so plainly.
1136
1544
  function renderWorkerDiff(out, d) {
@@ -1196,6 +1604,16 @@ function renderWorkerDiff(out, d) {
1196
1604
  miss.className = "muted small";
1197
1605
  miss.textContent = `${d.goto.path}:${d.goto.line} không nằm trong diff này`;
1198
1606
  out.append(miss);
1607
+ const direct = document.createElement("button");
1608
+ direct.type = "button";
1609
+ direct.className = "link";
1610
+ direct.textContent = "mở trực tiếp file này →";
1611
+ direct.addEventListener("click", () => {
1612
+ const goto = d.goto;
1613
+ d.goto = null;
1614
+ openFileAt(goto.path, goto);
1615
+ });
1616
+ out.append(direct);
1199
1617
  }
1200
1618
  d.goto = null; // one reveal per deep-link, not per re-render
1201
1619
  }
@@ -1218,7 +1636,7 @@ function renderWorkerBox(box) {
1218
1636
  const bar = document.createElement("div");
1219
1637
  bar.className = "activity-bar";
1220
1638
  const tabButtons = new Map();
1221
- for (const [key, label] of [["jobs", "Jobs"], ["search", "Search"], ["recap", "Recap"], ["usage", "Usage"], ["timeline", "Chat"], ["diff", "Diff"]]) {
1639
+ for (const [key, label] of [["jobs", "Jobs"], ["search", "Search"], ["recap", "Recap"], ["usage", "Usage"], ["timeline", "Chat"], ["diff", "Diff"], ["files", "Files"], ["review", "Review"]]) {
1222
1640
  const tab = document.createElement("button");
1223
1641
  tab.type = "button";
1224
1642
  tab.textContent = label;
@@ -1343,9 +1761,49 @@ function renderWorkerBox(box) {
1343
1761
  const diffOut = document.createElement("div");
1344
1762
  diffOut.className = "diff-out";
1345
1763
  diffView.append(diffForm, diffOut);
1346
- details.append(summary, health, refresh, bar, form, formError, search, recap, usageView, timelineView, diffView, jobs);
1764
+
1765
+ // Files (filev pattern): the host repo's tracked files — fuzzy find, read one
1766
+ // file, smartcase in-file search, path:line jump. Read-only like every view op.
1767
+ const filesView = document.createElement("div");
1768
+ filesView.className = "files-view";
1769
+ filesView.hidden = true;
1770
+ const filesForm = document.createElement("form");
1771
+ filesForm.autocomplete = "off";
1772
+ const filesLabel = document.createElement("label");
1773
+ filesLabel.textContent = "Files — repo trên máy, chỉ đọc (tìm mờ · enter mở file đầu tiên)";
1774
+ const filesInput = document.createElement("input");
1775
+ filesInput.type = "text";
1776
+ filesInput.maxLength = 128;
1777
+ filesInput.placeholder = "vd: index.mjs · wake · test/push";
1778
+ filesForm.append(filesLabel, filesInput);
1779
+ const filesOut = document.createElement("div");
1780
+ filesOut.className = "files-out";
1781
+ filesView.append(filesForm, filesOut);
1782
+
1783
+ // Review (reviewr mobile): scoped change lists, tap-line comments, one Send.
1784
+ const reviewView = document.createElement("div");
1785
+ reviewView.className = "review-view";
1786
+ reviewView.hidden = true;
1787
+ const reviewOut = document.createElement("div");
1788
+ reviewOut.className = "review-out";
1789
+ reviewView.append(reviewOut);
1790
+ details.append(summary, health, refresh, bar, form, formError, search, recap, usageView, timelineView, diffView, filesView, reviewView, jobs);
1347
1791
  box.append(details);
1348
1792
 
1793
+ filesForm.addEventListener("submit", (event) => {
1794
+ event.preventDefault();
1795
+ const f = state.worker.files;
1796
+ f.query = filesInput.value.trim();
1797
+ // Enter opens the best match — the fuzzy finder's one-keystroke path.
1798
+ if (f.tree && f.query) {
1799
+ const best = hgFuzzy.matchAndRank(f.query, f.tree.map((x) => x.path))[0];
1800
+ if (best !== undefined) openFileAt(f.tree[best].path);
1801
+ }
1802
+ });
1803
+ filesInput.addEventListener("input", () => {
1804
+ state.worker.files.query = filesInput.value.trim();
1805
+ });
1806
+
1349
1807
  const askHealth = () => sendPayload({ op: "worker.health" });
1350
1808
  refresh.addEventListener("click", askHealth);
1351
1809
  details.addEventListener("toggle", () => { if (details.open) askHealth(); });
@@ -1393,7 +1851,7 @@ function renderWorkerBox(box) {
1393
1851
  const update = (online) => {
1394
1852
  liveOnline = online;
1395
1853
  const w = state.worker;
1396
- const tab = ["search", "recap", "usage", "timeline", "diff"].includes(w.tab) ? w.tab : "jobs";
1854
+ const tab = ["search", "recap", "usage", "timeline", "diff", "files", "review"].includes(w.tab) ? w.tab : "jobs";
1397
1855
  const working = [...w.jobs.values()].filter((job) => ["queued", "running", "pending"].includes(job.status)).length;
1398
1856
  tabButtons.get("jobs").textContent = `Jobs (${working})`;
1399
1857
  for (const [key, button] of tabButtons) button.className = key === tab ? "active" : "";
@@ -1403,7 +1861,11 @@ function renderWorkerBox(box) {
1403
1861
  usageView.hidden = tab !== "usage";
1404
1862
  timelineView.hidden = tab !== "timeline";
1405
1863
  diffView.hidden = tab !== "diff";
1864
+ filesView.hidden = tab !== "files";
1865
+ reviewView.hidden = tab !== "review";
1406
1866
  jobs.hidden = tab !== "jobs";
1867
+ if (online && tab === "files" && !w.files.tree && !w.files.loading) fetchFileTree();
1868
+ if (online && tab === "review" && !w.review.files && !w.review.loading) fetchReviewFiles(w.review.scope);
1407
1869
  if (state.diff?.ref && diffInput.value !== state.diff.ref) diffInput.value = state.diff.ref;
1408
1870
  if (online && details.open && !ui.asked) { ui.asked = true; askHealth(); }
1409
1871
  const h = w.health;
@@ -1530,6 +1992,8 @@ function renderWorkerBox(box) {
1530
1992
  renderWorkerUsage(usageView, w, online);
1531
1993
  renderWorkerChat(timelineView, w, online);
1532
1994
  renderWorkerDiff(diffOut, state.diff);
1995
+ renderWorkerFiles(filesOut, w.files);
1996
+ renderWorkerReview(reviewOut, w);
1533
1997
  };
1534
1998
  return update;
1535
1999
  }
@@ -2248,6 +2712,11 @@ function applyPayload(payload) {
2248
2712
  if (routeFencedReply(payload)) return; // fenced: the surface that asked applies it
2249
2713
  // The plaintext (or decrypted) payload from the host lands here.
2250
2714
  if (payload && typeof payload === "object" && payload.op === "view") {
2715
+ if (state.pendingFileLink) {
2716
+ const link = state.pendingFileLink;
2717
+ state.pendingFileLink = null;
2718
+ openFileAt(link.path, link.goto);
2719
+ }
2251
2720
  state.view = payload.view;
2252
2721
  state.viewError = null;
2253
2722
  } else if (payload && typeof payload === "object" && payload.op === "term.list") {
@@ -2265,6 +2734,28 @@ function applyPayload(payload) {
2265
2734
  state.worker.error = payload.enabled === false ? payload.message ?? "worker queue disabled on this host" : null;
2266
2735
  state.roomUi?.updateWorker?.(true);
2267
2736
  return;
2737
+ } else if (payload && typeof payload === "object" && payload.op === "error" && payload.code === "pi_worker_disabled" && state.worker.review?.sending) {
2738
+ // A refused review.send faults the Review tab only — the comments stay.
2739
+ state.worker.review.sending = false;
2740
+ state.worker.review.error = payload.message ?? payload.code ?? "host từ chối review.send";
2741
+ state.roomUi?.updateWorker?.(true);
2742
+ return;
2743
+ } else if (payload && typeof payload === "object" && payload.op === "error" && ["requires-act", "bad-comments", "bad-comment", "queue-full", "worker-queue"].includes(payload.code) && state.worker.review?.sending) {
2744
+ state.worker.review.sending = false;
2745
+ state.worker.review.error = payload.code === "requires-act" ? "cần cấp quyền act cho điện thoại để gửi review" : payload.message ?? payload.code;
2746
+ state.roomUi?.updateWorker?.(true);
2747
+ return;
2748
+ } else if (payload && typeof payload === "object" && payload.op === "review.sent") {
2749
+ const r = state.worker.review;
2750
+ if (r) {
2751
+ r.sending = false;
2752
+ r.sent = { id: payload.id, count: payload.count, at: Date.now() };
2753
+ r.comments = {}; // delivered — the queue owns them now
2754
+ r.boxLine = null;
2755
+ r.open = null; // back to the list; the job lands in Jobs/Chat like any turn
2756
+ }
2757
+ state.roomUi?.updateWorker?.(true);
2758
+ return;
2268
2759
  } else if (payload && typeof payload === "object" && payload.op === "worker.submitted") {
2269
2760
  state.worker.jobs.set(payload.id, {
2270
2761
  id: payload.id,
@@ -2362,7 +2853,11 @@ function applyPayload(payload) {
2362
2853
 
2363
2854
  // ---- push wake ---------------------------------------------------------------
2364
2855
 
2365
- /** Subscribe this device to silent wake pushes; ask for permission only once paired. */
2856
+ /** Subscribe this device to silent wake pushes; ask for permission only once paired.
2857
+ * The subscription's p256dh/auth keys ride along so the gate can send ENCRYPTED
2858
+ * payloads (RFC 8291) — and if the gate ever rotates its VAPID keypair, the old
2859
+ * subscription would silently stop delivering, so the key is checked every time
2860
+ * and a mismatch re-subscribes fresh (a subscription is bound to its birth key). */
2366
2861
  async function subscribePush() {
2367
2862
  const { deviceId, deviceSecret } = state;
2368
2863
  const base = cloudBase();
@@ -2370,26 +2865,41 @@ async function subscribePush() {
2370
2865
  if (!("serviceWorker" in navigator) || !("PushManager" in window)) return;
2371
2866
  try {
2372
2867
  const reg = await navigator.serviceWorker.ready;
2868
+ const keyRes = await fetch(`${base}/v1/push/key`);
2869
+ if (!keyRes.ok) return; // push disabled on this cloud
2870
+ const { publicKey } = await keyRes.json();
2871
+ const raw = Uint8Array.from(atob(publicKey.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
2373
2872
  let sub = await reg.pushManager.getSubscription();
2873
+ if (sub && !keysMatch(sub.options.applicationServerKey, raw)) {
2874
+ await sub.unsubscribe(); // born under an older VAPID key — dead weight
2875
+ sub = null;
2876
+ }
2374
2877
  if (!sub) {
2375
- const keyRes = await fetch(`${base}/v1/push/key`);
2376
- if (!keyRes.ok) return; // push disabled on this cloud
2377
- const { publicKey } = await keyRes.json();
2378
- const raw = Uint8Array.from(atob(publicKey.replace(/-/g, "+").replace(/_/g, "/")), (c) => c.charCodeAt(0));
2379
2878
  sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: raw });
2380
2879
  }
2381
2880
  const endpoint = sub.endpoint;
2382
2881
  if (cloudBase() !== base || state.deviceId !== deviceId) return;
2882
+ const j = sub.toJSON();
2383
2883
  await fetch(`${base}/v1/device/push`, {
2384
2884
  method: "POST",
2385
2885
  headers: { "content-type": "application/json" },
2386
- body: JSON.stringify({ device: deviceId, deviceSecret, endpoint }),
2886
+ body: JSON.stringify({ device: deviceId, deviceSecret, endpoint, p256dh: j.keys?.p256dh, auth: j.keys?.auth }),
2387
2887
  });
2388
2888
  } catch {
2389
2889
  /* permission denied or push unavailable: the gate still works without it */
2390
2890
  }
2391
2891
  }
2392
2892
 
2893
+ /** A push subscription is permanently bound to the VAPID key it was created with.
2894
+ * Byte-compare the subscription's key with the server's current one. */
2895
+ function keysMatch(existing, serverKey) {
2896
+ if (!existing) return false;
2897
+ const a = "buffer" in existing ? new Uint8Array(existing.buffer, existing.byteOffset, existing.byteLength) : new Uint8Array(0);
2898
+ if (a.length !== serverKey.length) return false;
2899
+ for (let i = 0; i < a.length; i++) if (a[i] !== serverKey[i]) return false;
2900
+ return true;
2901
+ }
2902
+
2393
2903
  /** The host answered our handshake: finish it, pin its fingerprint (TOFU). */
2394
2904
  async function onE2eReply(payload) {
2395
2905
  const ch = e2e.ch;
@@ -2804,8 +3314,118 @@ function forgetToken() {
2804
3314
  }
2805
3315
  }
2806
3316
 
3317
+ // Deep link #room=<id>: a notification tap opens the app straight into that room.
3318
+ // The saved pairing is enough to enter; an unknown room falls back to the list.
3319
+ function roomFromHash() {
3320
+ const m = /^#room=([A-Za-z0-9_-]{1,64})$/.exec(location.hash ?? "");
3321
+ if (!m) return null;
3322
+ const id = m[1];
3323
+ const pair = roomPairs().get(id);
3324
+ if (pair && state.token) selectRoom(id, pair, true);
3325
+ return id;
3326
+ }
3327
+
3328
+ // Files deep-link #f=<path>[:line[-end]] — a receipt or diff link can land straight
3329
+ // in the viewer at the exact line (the filev open_target shape). At boot the socket
3330
+ // may not be open yet; the link waits for the first live view (askView path).
3331
+ function filesFromHash() {
3332
+ const m = /^#f=([^&\s]{1,512})$/.exec(location.hash ?? "");
3333
+ if (!m) return null;
3334
+ const goto = parseLineSuffix(m[1]) ?? { path: m[1], line: 1, end: 1 };
3335
+ if (!state.token || !goto.path) return null;
3336
+ const target = goto.line >= 1 ? goto : null;
3337
+ if (state.ws?.readyState === WebSocket.OPEN && state.roomId) {
3338
+ openFileAt(goto.path, target);
3339
+ } else {
3340
+ state.pendingFileLink = { path: goto.path, goto: target };
3341
+ }
3342
+ return goto.path;
3343
+ }
3344
+ if (typeof addEventListener === "function") addEventListener("hashchange", () => { roomFromHash(); filesFromHash(); });
3345
+
3346
+ // A notification tap on an OPEN window arrives as { t: "nav", room } from the SW —
3347
+ // navigate in place, no reload (pairing and drafts survive).
3348
+ if ("serviceWorker" in navigator) {
3349
+ navigator.serviceWorker.addEventListener("message", (event) => {
3350
+ const d = event.data;
3351
+ if (d?.t === "nav" && typeof d.room === "string" && state.token) {
3352
+ const pair = roomPairs().get(d.room);
3353
+ if (pair) selectRoom(d.room, pair, true);
3354
+ }
3355
+ });
3356
+ }
3357
+
3358
+ // ---- self-update --------------------------------------------------------------
3359
+ // The gate stamps its build id on /healthz (x-hg-build). When the serving gate is
3360
+ // NEWER than the bundle this page booted from, reload — but only after two agreeing
3361
+ // polls (hysteresis: an atomic dist swap must not half-trigger), at most once per
3362
+ // build id (sessionStorage guard against a reload loop), and never while the user
3363
+ // is typing (an input holding text holds the reload; the banner shows instead).
3364
+ {
3365
+ const SEEN_KEY = "hg:build-seen";
3366
+ let pendingBuild = null;
3367
+ let banner = null;
3368
+ const reloadedKey = (id) => `hg:auto-reloaded:${id}`;
3369
+ const holdActive = () => {
3370
+ const el = document.activeElement;
3371
+ return !!el && /^(INPUT|TEXTAREA)$/.test(el.tagName) && el.value !== "";
3372
+ };
3373
+ const showBanner = (on) => {
3374
+ let node = document.getElementById("upd");
3375
+ if (!node && on) {
3376
+ node = document.createElement("div");
3377
+ node.id = "upd";
3378
+ const btn = document.createElement("button");
3379
+ btn.type = "button";
3380
+ btn.textContent = "Bản mới — chạm để cập nhật";
3381
+ btn.addEventListener("click", () => {
3382
+ localStorage.setItem(SEEN_KEY, pendingBuild ?? "");
3383
+ location.reload();
3384
+ });
3385
+ node.append(btn);
3386
+ document.body.append(node);
3387
+ }
3388
+ banner = node;
3389
+ if (node) node.hidden = !on;
3390
+ };
3391
+ const act = (id) => {
3392
+ let already = false;
3393
+ try { already = sessionStorage.getItem(reloadedKey(id)) !== null; } catch { already = false; }
3394
+ if (already || holdActive()) return showBanner(true);
3395
+ try { sessionStorage.setItem(reloadedKey(id), "1"); } catch { /* storage off — reload anyway */ }
3396
+ localStorage.setItem(SEEN_KEY, id);
3397
+ location.reload();
3398
+ };
3399
+ const checkBuild = async () => {
3400
+ try {
3401
+ const res = await fetch("/healthz", { cache: "no-store" });
3402
+ const id = res.headers.get("x-hg-build");
3403
+ if (!id) return;
3404
+ let seen = null;
3405
+ try { seen = localStorage.getItem(SEEN_KEY); } catch { seen = null; }
3406
+ if (!seen) { localStorage.setItem(SEEN_KEY, id); return; } // first boot on this device
3407
+ if (id === seen) { pendingBuild = null; showBanner(false); return; }
3408
+ if (id === pendingBuild) { act(id); return; } // second agreeing sighting
3409
+ pendingBuild = id; // first sighting — wait one more poll
3410
+ } catch {
3411
+ /* offline: try again on the next tick */
3412
+ }
3413
+ };
3414
+ if (typeof addEventListener === "function") {
3415
+ addEventListener("load", () => {
3416
+ void checkBuild();
3417
+ if (typeof setInterval === "function") setInterval(checkBuild, 5 * 60_000);
3418
+ });
3419
+ }
3420
+ }
3421
+
2807
3422
  render();
2808
- if (state.token) connect();
3423
+ roomFromHash();
3424
+ filesFromHash();
3425
+ if (state.token) {
3426
+ connect();
3427
+ void subscribePush(); // upgrade an existing subscription (keys, VAPID rotation check)
3428
+ }
2809
3429
 
2810
3430
  // A phone that wakes up should not show a dead screen.
2811
3431
  document.addEventListener("visibilitychange", () => {
@@ -2868,6 +3488,16 @@ if ("serviceWorker" in navigator && location.protocol !== "file:") {
2868
3488
  enrichToggle: (id) => toggleReceiptEnrich(id),
2869
3489
  enrichRows: (result) => JSON.parse(JSON.stringify(enrichRows(result))),
2870
3490
  contextPctOf: (tokens, max) => contextPctOf(tokens, max),
3491
+ parseUnifiedDiff, reviewSnap: () => JSON.parse(JSON.stringify(state.worker.review)),
3492
+ reviewComment: (path, line, text) => setReviewComment(path, line, text),
3493
+ reviewSend: () => {
3494
+ const sent = [];
3495
+ state.roomId ??= "pwa3-room";
3496
+ state.ws = { readyState: 1, send: (raw) => sent.push(JSON.parse(raw)) };
3497
+ sendReviewComments();
3498
+ return sent;
3499
+ },
3500
+ apply: (payload) => applyPayload(payload),
2871
3501
  probe: {
2872
3502
  detail: (id) => receiptDetailNode(id),
2873
3503
  thread: (job) => chatThread(job),