@d86e/hive-panel 1.0.29 → 1.0.31

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@d86e/hive-panel",
3
- "version": "1.0.29",
3
+ "version": "1.0.31",
4
4
  "description": "A read-only board for a Hive swarm: agents, task lanes and the event tail, served from the refs and files you already have.",
5
5
  "type": "module",
6
6
  "bin": {
package/public/panel.js CHANGED
@@ -2282,6 +2282,8 @@ export const messages = Object.freeze({
2282
2282
  "events.actor.legacy": "Agent",
2283
2283
  "events.recycled": "Recycled {count} older events",
2284
2284
  "events.loadFailed": "Could not load events",
2285
+ "events.missed": "Event stream gap",
2286
+ "events.missedReloaded": "Reloaded the latest events.",
2285
2287
  "events.pageFailed": "Older events failed to load",
2286
2288
  "events.retry": "Retry",
2287
2289
  "events.details": "Details",
@@ -2327,6 +2329,12 @@ export const messages = Object.freeze({
2327
2329
  "supervisor.runningCount": "running {count}",
2328
2330
  "supervisor.idle": "idle",
2329
2331
  "supervisor.backoff": "backoff",
2332
+ "supervisor.pause": "Pause",
2333
+ "supervisor.resume": "Resume",
2334
+ "supervisor.pauseAria": "Pause the supervisor for {repo}",
2335
+ "supervisor.resumeAria": "Resume the supervisor for {repo}",
2336
+ "supervisor.pauseFailed": "Could not pause the supervisor",
2337
+ "supervisor.resumeFailed": "Could not resume the supervisor",
2330
2338
  "supervisor.paused": "Paused",
2331
2339
  "supervisor.normal": "Normal",
2332
2340
  "supervisor.unresponsive": "Unresponsive",
@@ -2651,6 +2659,8 @@ export const messages = Object.freeze({
2651
2659
  "events.actor.legacy": "智能体",
2652
2660
  "events.recycled": "已回收更早的 {count} 条",
2653
2661
  "events.loadFailed": "事件加载失败",
2662
+ "events.missed": "事件流存在缺口",
2663
+ "events.missedReloaded": "已重新加载最新事件。",
2654
2664
  "events.pageFailed": "更早的事件加载失败",
2655
2665
  "events.retry": "重试",
2656
2666
  "events.details": "详情",
@@ -2696,6 +2706,12 @@ export const messages = Object.freeze({
2696
2706
  "supervisor.runningCount": "运行中 {count}",
2697
2707
  "supervisor.idle": "空闲",
2698
2708
  "supervisor.backoff": "退避",
2709
+ "supervisor.pause": "暂停",
2710
+ "supervisor.resume": "恢复",
2711
+ "supervisor.pauseAria": "暂停 {repo} 的监督器",
2712
+ "supervisor.resumeAria": "恢复 {repo} 的监督器",
2713
+ "supervisor.pauseFailed": "暂停监督器失败",
2714
+ "supervisor.resumeFailed": "恢复监督器失败",
2699
2715
  "supervisor.paused": "已暂停",
2700
2716
  "supervisor.normal": "正常",
2701
2717
  "supervisor.unresponsive": "未响应",
@@ -3182,6 +3198,7 @@ function normalizeEvents(events) {
3182
3198
  kind: asString(event.kind),
3183
3199
  task: asString(event.task),
3184
3200
  actor: asString(event.actor),
3201
+ key: asString(event.key),
3185
3202
  raw: event,
3186
3203
  }));
3187
3204
  }
@@ -3296,6 +3313,7 @@ export function renderModel(snapshot) {
3296
3313
  prompt: typeof entry.prompt === "string" ? entry.prompt : null,
3297
3314
  promptExists: entry.promptExists === true,
3298
3315
  limit: typeof entry.limit === "number" && Number.isFinite(entry.limit) ? entry.limit : null,
3316
+ source: normalizeLimitSource(entry.source || entry.limitSource || entry.limit_source),
3299
3317
  }))
3300
3318
  .filter((entry) => entry.name)
3301
3319
  : [],
@@ -3309,7 +3327,7 @@ export function renderModel(snapshot) {
3309
3327
  const rows = lanes[state];
3310
3328
  const raw = rawLanePages && isRecord(rawLanePages[state]) ? rawLanePages[state] : null;
3311
3329
  const total = raw ? asCount(raw.total, rows.length) : rows.length;
3312
- const cursor = raw ? asCount(raw.cursor, rows.length) : rows.length;
3330
+ const cursor = raw && raw.cursor !== undefined && raw.cursor !== null ? String(raw.cursor) : "";
3313
3331
  lanePages[state] = {
3314
3332
  loaded: rows.length,
3315
3333
  total,
@@ -3358,13 +3376,21 @@ function supervisorNumber(value) {
3358
3376
  return null;
3359
3377
  }
3360
3378
 
3379
+ function normalizeLimitSource(value) {
3380
+ const text = asString(value).trim().toLowerCase();
3381
+ if (text === "limits" || text === "limits.json") return "limits";
3382
+ if (text === "config") return "config";
3383
+ if (text === "default") return "default";
3384
+ return null;
3385
+ }
3386
+
3361
3387
  function normalizeSupervisorRoles(source) {
3362
3388
  if (!isRecord(source)) return [];
3363
3389
  const rows = new Map();
3364
3390
  const ensure = (role) => {
3365
3391
  const name = asString(role).trim();
3366
3392
  if (!name) return null;
3367
- if (!rows.has(name)) rows.set(name, { role: name, limit: null, live: null, inFlight: null, queued: null });
3393
+ if (!rows.has(name)) rows.set(name, { role: name, limit: null, live: null, inFlight: null, queued: null, source: null });
3368
3394
  return rows.get(name);
3369
3395
  };
3370
3396
  const setLimit = (role, value) => {
@@ -3386,6 +3412,8 @@ function normalizeSupervisorRoles(source) {
3386
3412
  const role = asString(raw.role || raw.name || raw.key || raw.id || fallbackRole);
3387
3413
  const row = ensure(role);
3388
3414
  if (!row) return;
3415
+ const declaredSource = normalizeLimitSource(raw.source || raw.limitSource || raw.limit_source);
3416
+ if (declaredSource !== null) row.source = declaredSource;
3389
3417
  for (const field of ["limit", "max", "concurrency", "concurrencyLimit", "maxConcurrency", "max_concurrency", "concurrency_limit", "maxInFlight", "max_in_flight", "cap", "capacity", "value", "n"]) {
3390
3418
  if (supervisorNumber(raw[field]) !== null) {
3391
3419
  row.limit = supervisorNumber(raw[field]);
@@ -3544,7 +3572,9 @@ function normalizeSupervisorStatus(payload) {
3544
3572
  const repo = asString(source.repo || source.path || source.cwd || source.directory || source.root || source.name);
3545
3573
  if (!repo) continue;
3546
3574
  const rawState = asString(source.state || source.status || source.phase || source.mode).toLowerCase();
3547
- const paused = source.paused === true || source.suspended === true || /paus|stop|suspend/.test(rawState);
3575
+ const pausedBy = asString(source.pausedBy || source.paused_by);
3576
+ const paused = source.paused === true || source.suspended === true || pausedBy !== "";
3577
+ const statePaused = paused || /paus|stop|suspend/.test(rawState);
3548
3578
  const running =
3549
3579
  supervisorCount(source.running) ??
3550
3580
  supervisorCount(source.active) ??
@@ -3570,7 +3600,7 @@ function normalizeSupervisorStatus(payload) {
3570
3600
  );
3571
3601
  const lastCheckAt = asString(source.lastCheckAt || source.last_check_at);
3572
3602
  let state = "idle";
3573
- if (paused) state = "paused";
3603
+ if (statePaused) state = "paused";
3574
3604
  else if (source.backoff === true || /backoff|back-off|retry|delay|wait/.test(rawState)) state = "backoff";
3575
3605
  else if (/run|active|busy|working/.test(rawState)) state = "running";
3576
3606
  else if (/idle|ready|free/.test(rawState)) state = "idle";
@@ -3579,6 +3609,7 @@ function normalizeSupervisorStatus(payload) {
3579
3609
  repo,
3580
3610
  state,
3581
3611
  paused,
3612
+ pausedBy,
3582
3613
  running,
3583
3614
  queued,
3584
3615
  lastCheckAt,
@@ -4180,6 +4211,7 @@ export function mount(root, options = {}) {
4180
4211
  const queenDismissedFallback = new Set();
4181
4212
  let supervisorData = [];
4182
4213
  let supervisorMeta = { count: 0, last: null };
4214
+ let supervisorBusy = false;
4183
4215
  let supervisorScopeSignature = null;
4184
4216
  let supervisorRequest = null;
4185
4217
  let limitsOverlay = null;
@@ -4460,29 +4492,64 @@ export function mount(root, options = {}) {
4460
4492
  const time = Date.parse(value);
4461
4493
  return Number.isFinite(time) ? time : null;
4462
4494
  };
4495
+ let pruneCountSeq = 0;
4496
+ const pruneCountText = (count, time) => translate("events.pruneCount")
4497
+ .replace("{count}", String(count))
4498
+ .replace("{time}", time === null ? "—" : new Date(time).toLocaleString());
4463
4499
  pruneInput.addEventListener("input", () => {
4464
4500
  const time = pruneBefore();
4501
+ pruneCountSeq += 1;
4502
+ const seq = pruneCountSeq;
4465
4503
  if (time === null) {
4466
- pruneCount.textContent = translate("events.pruneCount").replace("{count}", "0").replace("{time}", "—");
4504
+ pruneCount.textContent = pruneCountText(0, null);
4467
4505
  return;
4468
4506
  }
4469
- const count = eventState.items.filter((event) => {
4507
+ const localCount = eventState.items.filter((event) => {
4470
4508
  const ts = Date.parse(event.ts);
4471
4509
  return Number.isFinite(ts) && ts < time;
4472
4510
  }).length;
4473
- pruneCount.textContent = translate("events.pruneCount").replace("{count}", String(count)).replace("{time}", new Date(time).toLocaleString());
4511
+ pruneCount.textContent = pruneCountText(localCount, time);
4512
+ if (!fetchImpl) return;
4513
+ const before = new Date(time).toISOString();
4514
+ void (async () => {
4515
+ try {
4516
+ const url = eventsUrl + (eventsUrl.includes("?") ? "&" : "?") + "before=" + encodeURIComponent(before);
4517
+ const response = await fetchImpl(url, { cache: "no-store", headers: { accept: "application/json" } });
4518
+ if (!response || response.ok === false) return;
4519
+ const payload = await response.json();
4520
+ const count = asCount(payload && payload.count, -1);
4521
+ if (seq === pruneCountSeq && count >= 0 && !destroyed) pruneCount.textContent = pruneCountText(count, time);
4522
+ } catch {
4523
+ // The local count stays visible when the count route is unavailable.
4524
+ }
4525
+ })();
4474
4526
  });
4475
- pruneConfirm.addEventListener("click", () => {
4527
+ pruneConfirm.addEventListener("click", async () => {
4476
4528
  const time = pruneBefore();
4477
4529
  if (time === null) return;
4478
- const count = eventState.items.filter((event) => {
4530
+ const before = new Date(time).toISOString();
4531
+ let count = eventState.items.filter((event) => {
4479
4532
  const ts = Date.parse(event.ts);
4480
4533
  return Number.isFinite(ts) && ts < time;
4481
4534
  }).length;
4535
+ if (fetchImpl) {
4536
+ try {
4537
+ const url = eventsUrl + (eventsUrl.includes("?") ? "&" : "?") + "before=" + encodeURIComponent(before);
4538
+ const response = await fetchImpl(url, { cache: "no-store", headers: { accept: "application/json" } });
4539
+ if (response && response.ok !== false) {
4540
+ const payload = await response.json();
4541
+ const serverCount = asCount(payload && payload.count, -1);
4542
+ if (serverCount >= 0) count = serverCount;
4543
+ }
4544
+ } catch {
4545
+ // The loaded count remains a safe fallback when the count route is unavailable.
4546
+ }
4547
+ }
4548
+ if (destroyed) return;
4482
4549
  const message = translate("events.pruneConfirm").replace("{count}", String(count)).replace("{time}", new Date(time).toLocaleString());
4483
4550
  if (!confirmImpl || !confirmImpl(message)) return;
4484
4551
  eventsPrune.className = "hive-event-prune is-hidden";
4485
- void runBatch("events-prune", { before: new Date(time).toISOString() });
4552
+ void runBatch("events-prune", { before });
4486
4553
  });
4487
4554
  eventsHead.appendChild(eventsMenu);
4488
4555
  const eventsList = element(doc, "div", "hive-scroll hive-event-list");
@@ -5078,6 +5145,8 @@ export function mount(root, options = {}) {
5078
5145
  const entry = ensure(name);
5079
5146
  entry.inFlight = supervisorNumber(role.inFlight);
5080
5147
  entry.queued = supervisorNumber(role.queued);
5148
+ const supervisorSource = normalizeLimitSource(role.source || role.limitSource || role.limit_source);
5149
+ if (supervisorSource !== null) entry.supervisorSource = supervisorSource;
5081
5150
  const limit = supervisorNumber(role.limit);
5082
5151
  if (limit !== null) entry.limit = limit;
5083
5152
  }
@@ -5090,6 +5159,8 @@ export function mount(root, options = {}) {
5090
5159
  const entry = ensure(name);
5091
5160
  if (modelRole.adapter) entry.adapter = modelRole.adapter;
5092
5161
  if (modelRole.model) entry.model = modelRole.model;
5162
+ const modelSource = normalizeLimitSource(modelRole.source || modelRole.limitSource || modelRole.limit_source);
5163
+ if (modelSource !== null) entry.modelSource = modelSource;
5093
5164
  const limit = supervisorNumber(modelRole.limit);
5094
5165
  if (limit !== null) {
5095
5166
  entry.limit = limit;
@@ -5130,9 +5201,9 @@ export function mount(root, options = {}) {
5130
5201
  entry.source = "limits";
5131
5202
  } else if (supervisorLimit !== null) {
5132
5203
  entry.limit = supervisorLimit;
5133
- entry.source = "config";
5204
+ entry.source = entry.supervisorSource || "config";
5134
5205
  } else if (entry.modelLimit) {
5135
- entry.source = "limits";
5206
+ entry.source = entry.modelSource || "limits";
5136
5207
  } else {
5137
5208
  entry.source = "default";
5138
5209
  }
@@ -6321,7 +6392,7 @@ function renderMarkdownInto(doc, host, source) {
6321
6392
  const byId = new Map();
6322
6393
  for (const task of tasks) if (task && task.id) byId.set(task.id, task);
6323
6394
  const dependsOn = (Array.isArray(card.after) ? card.after : [])
6324
- .map((id) => byId.get(id))
6395
+ .map((id) => byId.get(id) || { id, title: id, state: "unknown", missing: true })
6325
6396
  .filter(Boolean);
6326
6397
  const requiredBy = tasks.filter(
6327
6398
  (task) =>
@@ -7162,6 +7233,7 @@ function renderMarkdownInto(doc, host, source) {
7162
7233
  function setSupervisorData(rows) {
7163
7234
  supervisorData = Array.isArray(rows) ? rows : [];
7164
7235
  renderSupervisor();
7236
+ if (lastModel) renderActions(lastModel);
7165
7237
  }
7166
7238
 
7167
7239
 
@@ -7294,9 +7366,55 @@ function renderMarkdownInto(doc, host, source) {
7294
7366
  freezeSlot.appendChild(banner);
7295
7367
  }
7296
7368
 
7369
+ async function toggleSupervisorPause(row, button) {
7370
+ if (destroyed || !fetchImpl || supervisorBusy || !row) return;
7371
+ const resuming = row.paused === true;
7372
+ supervisorBusy = true;
7373
+ if (button) button.disabled = true;
7374
+ try {
7375
+ const response = await fetchImpl(supervisorEndpoint(resuming ? "resume" : "pause"), {
7376
+ method: "POST",
7377
+ headers: { "content-type": "application/json", accept: "application/json" },
7378
+ body: JSON.stringify({ repo: row.repo }),
7379
+ });
7380
+ let payload = null;
7381
+ try {
7382
+ payload = response && typeof response.json === "function" ? await response.json() : null;
7383
+ } catch {
7384
+ payload = null;
7385
+ }
7386
+ const status = response ? Number(response.status) || 0 : 0;
7387
+ if (!response || response.ok === false || (payload && payload.ok === false)) {
7388
+ const error = new Error(resuming ? "supervisor resume failed" : "supervisor pause failed");
7389
+ error.stderr = asString(payload && (payload.stderr || payload.message || payload.error)) || (status ? "HTTP " + String(status) : "");
7390
+ throw error;
7391
+ }
7392
+ if (destroyed) return;
7393
+ row.paused = !resuming;
7394
+ row.pausedBy = resuming ? "" : "manual";
7395
+ renderSupervisor();
7396
+ if (lastModel) renderActions(lastModel);
7397
+ await refreshSupervisor(true);
7398
+ if (!destroyed && lastModel) renderActions(lastModel);
7399
+ } catch (error) {
7400
+ if (!destroyed) {
7401
+ const fallback = translate(resuming ? "supervisor.resumeFailed" : "supervisor.pauseFailed");
7402
+ showToast("error", fallback, actionErrorDetail(error) || fallback);
7403
+ }
7404
+ } finally {
7405
+ supervisorBusy = false;
7406
+ if (!destroyed && button && button.parentNode) button.disabled = false;
7407
+ }
7408
+ }
7409
+
7297
7410
  function renderActions(model) {
7298
7411
  clearNode(actionsNode);
7299
- for (const action of model.actions) {
7412
+ const supervisorRow = currentSupervisorRow();
7413
+ const supervisorToggle = Boolean(model.writable !== false && supervisorRow && supervisorRow.repo && supervisorRow.unmanaged !== true);
7414
+ const actions = supervisorToggle
7415
+ ? model.actions.filter((action) => action.name !== "mode")
7416
+ : model.actions;
7417
+ for (const action of actions) {
7300
7418
  const variant = action.name === "add" ? " hive-settings-primary" : "";
7301
7419
  const button = element(doc, "button", "hive-btn" + variant, translate(action.labelKey));
7302
7420
  setAttr(button, "type", "button");
@@ -7308,6 +7426,19 @@ function renderMarkdownInto(doc, host, source) {
7308
7426
  if (action.name === "plan" && planDialogNode) planTriggerButton = button;
7309
7427
  actionsNode.appendChild(button);
7310
7428
  }
7429
+ if (!supervisorToggle) return;
7430
+ const paused = supervisorRow.paused === true;
7431
+ const labelKey = paused ? "supervisor.resume" : "supervisor.pause";
7432
+ const ariaKey = paused ? "supervisor.resumeAria" : "supervisor.pauseAria";
7433
+ const button = element(doc, "button", "hive-btn hive-supervisor-toggle", translate(labelKey));
7434
+ setAttr(button, "type", "button");
7435
+ const label = translate(ariaKey).replace("{repo}", supervisorRow.repo);
7436
+ setAttr(button, "title", label);
7437
+ setAttr(button, "aria-label", label);
7438
+ button.addEventListener("click", () => {
7439
+ void toggleSupervisorPause(supervisorRow, button);
7440
+ });
7441
+ actionsNode.appendChild(button);
7311
7442
  }
7312
7443
 
7313
7444
  function selectedCount() {
@@ -7331,11 +7462,15 @@ function renderMarkdownInto(doc, host, source) {
7331
7462
 
7332
7463
  async function readBatchResponse(response) {
7333
7464
  const status = Number(response && response.status) || 0;
7465
+ if (status === 204 || status === 205) {
7466
+ return { status, data: { ok: true, results: [] } };
7467
+ }
7334
7468
  const contentType = response && response.headers && typeof response.headers.get === "function"
7335
7469
  ? String(response.headers.get("content-type") || "")
7336
7470
  : "";
7471
+ const hasText = Boolean(response && typeof response.text === "function");
7337
7472
  let text = "";
7338
- if (response && typeof response.text === "function") {
7473
+ if (hasText) {
7339
7474
  try {
7340
7475
  text = await response.text();
7341
7476
  } catch {
@@ -7352,7 +7487,11 @@ function renderMarkdownInto(doc, host, source) {
7352
7487
  return { status, text, invalid: true };
7353
7488
  }
7354
7489
  }
7355
- if (response && typeof response.json === "function") {
7490
+ if (hasText && status >= 200 && status < 300) {
7491
+ // 204/205 and empty 2xx bodies have no result list: success, never replay a delete.
7492
+ return { status, data: { ok: true, results: [] } };
7493
+ }
7494
+ if (!hasText && response && typeof response.json === "function") {
7356
7495
  try {
7357
7496
  return { status, data: await response.json() };
7358
7497
  } catch {
@@ -7821,7 +7960,6 @@ function renderMarkdownInto(doc, host, source) {
7821
7960
  if (!next.has(key) && entry.node.parentNode) entry.node.parentNode.removeChild(entry.node);
7822
7961
  }
7823
7962
  state.visible = next;
7824
- state.count.textContent = String(total);
7825
7963
  }
7826
7964
 
7827
7965
  function taskPageUrl(state, cursor) {
@@ -7885,8 +8023,8 @@ function renderMarkdownInto(doc, host, source) {
7885
8023
  : null;
7886
8024
  if (!items) throw new Error("tasks page returned no items");
7887
8025
  const total = asCount(payload && payload.total, page.total);
7888
- const cursor = asCount(payload && payload.cursor, page.cursor + items.length);
7889
- const hasMore = payload && payload.hasMore === true ? true : cursor < total;
8026
+ const cursor = payload && payload.cursor !== undefined && payload.cursor !== null ? String(payload.cursor) : "";
8027
+ const hasMore = Boolean(payload && payload.hasMore === true);
7890
8028
  if (!lastSnapshot) throw new Error("the board is not ready");
7891
8029
  const existing = Array.isArray(lastSnapshot.tasks) ? lastSnapshot.tasks : [];
7892
8030
  const seen = new Set(existing.map((task) => String(task && task.id)));
@@ -7944,8 +8082,8 @@ function renderMarkdownInto(doc, host, source) {
7944
8082
  const payload = await response.json();
7945
8083
  const items = Array.isArray(payload && payload.items) ? payload.items : [];
7946
8084
  const total = asCount(payload && payload.total, items.length);
7947
- const cursor = asCount(payload && payload.cursor, items.length);
7948
- const hasMore = payload && payload.hasMore === true ? true : cursor < total;
8085
+ const cursor = payload && payload.cursor !== undefined && payload.cursor !== null ? String(payload.cursor) : "";
8086
+ const hasMore = Boolean(payload && payload.hasMore === true);
7949
8087
  const others = (Array.isArray(lastSnapshot.tasks) ? lastSnapshot.tasks : [])
7950
8088
  .filter((task) => (task && (task.state || "pending")) !== lane);
7951
8089
  const lanePages = { ...(isRecord(lastSnapshot.lanePages) ? lastSnapshot.lanePages : {}) };
@@ -8477,6 +8615,8 @@ function renderMarkdownInto(doc, host, source) {
8477
8615
 
8478
8616
  function eventKey(event) {
8479
8617
  const raw = event.raw || {};
8618
+ if (event.key) return String(event.key);
8619
+ if (raw.key) return String(raw.key);
8480
8620
  const ref = raw.task || event.task || "";
8481
8621
  return JSON.stringify([String(event.ts || ""), String(event.kind || ""), String(event.actor || raw.actor || ""), String(ref)]);
8482
8622
  }
@@ -8650,7 +8790,15 @@ function renderMarkdownInto(doc, host, source) {
8650
8790
  eventState.recycled = 0;
8651
8791
  eventsList.scrollTop = 0;
8652
8792
  } else if (items.length > 0) {
8653
- eventState.items = eventState.items.concat(items);
8793
+ const known = new Set(eventState.items.map((event) => eventKey(event)));
8794
+ const fresh = [];
8795
+ for (const item of items) {
8796
+ const key = eventKey(item);
8797
+ if (known.has(key)) continue;
8798
+ known.add(key);
8799
+ fresh.push(item);
8800
+ }
8801
+ eventState.items = eventState.items.concat(fresh);
8654
8802
  if (eventState.items.length > 5000) {
8655
8803
  const dropped = eventState.items.length - 5000;
8656
8804
  eventState.items = eventState.items.slice(0, 5000);
@@ -8883,7 +9031,7 @@ function renderMarkdownInto(doc, host, source) {
8883
9031
  const payload = await response.json();
8884
9032
  const items = Array.isArray(payload && payload.items) ? payload.items : [];
8885
9033
  const total = asCount(payload && payload.total, items.length);
8886
- const cursor = asCount(payload && payload.cursor, items.length);
9034
+ const cursor = payload && payload.cursor !== undefined && payload.cursor !== null ? String(payload.cursor) : "";
8887
9035
  taskSlices[lane] = items;
8888
9036
  taskSlicePages[lane] = { total, cursor, hasMore: Boolean(payload && payload.hasMore) };
8889
9037
  state.initialLoading = false;
@@ -8909,7 +9057,7 @@ function renderMarkdownInto(doc, host, source) {
8909
9057
  eventState.items = items;
8910
9058
  eventState.total = asCount(payload && payload.total, items.length);
8911
9059
  eventState.cursor = asCount(payload && payload.cursor, items.length);
8912
- eventState.pollCursor = statusData ? asCount(statusData.eventTotal, eventState.total) : eventState.total;
9060
+ eventState.pollCursor = items.length > 0 ? eventKey(items[0]) : "";
8913
9061
  eventState.filter = "";
8914
9062
  eventState.recycled = 0;
8915
9063
  eventState.paged = false;
@@ -9059,15 +9207,20 @@ function renderMarkdownInto(doc, host, source) {
9059
9207
  async function pollEventsIncremental() {
9060
9208
  if (!fetchImpl || !initialDataLoaded || eventState.filter) return;
9061
9209
  if (!isNodeVisible(eventsDrawer)) return;
9062
- const after = Math.max(0, Math.floor(Number(eventState.pollCursor) || 0));
9210
+ const after = eventState.pollCursor === undefined || eventState.pollCursor === null ? "" : String(eventState.pollCursor);
9063
9211
  try {
9064
9212
  const url = eventsUrl + (eventsUrl.includes("?") ? "&" : "?") +
9065
- "after=" + encodeURIComponent(String(after)) + "&limit=50";
9213
+ "after=" + encodeURIComponent(after) + "&limit=50";
9066
9214
  const response = await fetchImpl(url, { cache: "no-store", headers: { accept: "application/json" } });
9067
9215
  if (!response || response.ok === false) return;
9068
9216
  const payload = await response.json();
9217
+ if (payload && payload.dropped === true) {
9218
+ await loadInitialEvents();
9219
+ if (!destroyed) showToast("error", translate("events.missed"), translate("events.missedReloaded"));
9220
+ return;
9221
+ }
9069
9222
  const items = normalizeEvents(Array.isArray(payload && payload.items) ? payload.items : []);
9070
- const nextCursor = asCount(payload && payload.cursor, after);
9223
+ const nextCursor = payload && payload.cursor !== undefined && payload.cursor !== null ? String(payload.cursor) : after;
9071
9224
  const total = asCount(payload && payload.total, eventState.total);
9072
9225
  eventState.pollCursor = nextCursor;
9073
9226
  eventState.total = Math.max(total, eventState.items.length);
@@ -9232,7 +9385,20 @@ function renderMarkdownInto(doc, host, source) {
9232
9385
  }
9233
9386
  }
9234
9387
 
9388
+ function renderActionPlaceholders() {
9389
+ clearNode(actionsNode);
9390
+ for (const action of toolbarActions(true, "free")) {
9391
+ const button = element(doc, "button", "hive-btn hive-action-placeholder", translate(action.labelKey));
9392
+ setAttr(button, "type", "button");
9393
+ setAttr(button, "title", translate(action.helpKey));
9394
+ setAttr(button, "disabled", "disabled");
9395
+ button.disabled = true;
9396
+ actionsNode.appendChild(button);
9397
+ }
9398
+ }
9399
+
9235
9400
  function primeInitialUI() {
9401
+ renderActionPlaceholders();
9236
9402
  for (const lane of LANE_ORDER) {
9237
9403
  if (laneRenderState.has(lane)) continue;
9238
9404
  const state = createLaneState(lane);
package/src/cache.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { execFile } from "node:child_process";
4
- import { isInitialised } from "./data.js";
4
+ import { encodeTaskCursor, decodeTaskCursor, isTaskAfterCursor, isInitialised } from "./data.js";
5
+ import { eventLineKey, parseEventLineKey } from "./event-store.js";
5
6
 
6
7
  export const SNAPSHOT_TTL_MS = 2_000;
7
8
  export const EVENT_TAIL_MAX = 5_000;
@@ -43,15 +44,18 @@ function lanePage(rows, stats, state, cursor, limit) {
43
44
  const lane = rows.filter((task) => (task.state || "pending") === state);
44
45
  lane.sort(compareTasks);
45
46
  const total = Number(stats?.byState?.[state]);
46
- const offset = Math.max(0, Math.floor(Number(cursor) || 0));
47
+ const totalRows = Number.isFinite(total) && total >= 0 ? total : lane.length;
48
+ const parsed = decodeTaskCursor(cursor);
49
+ const remaining = parsed && parsed.legacyOffset !== undefined
50
+ ? lane.slice(parsed.legacyOffset)
51
+ : lane.filter((task) => isTaskAfterCursor(task, parsed));
47
52
  const size = Math.max(1, Math.min(LANE_PAGE_LIMIT, Math.floor(Number(limit) || LANE_PAGE_LIMIT)));
48
- const items = lane.slice(offset, offset + size);
49
- const next = offset + items.length;
53
+ const items = remaining.slice(0, size);
50
54
  return {
51
55
  items,
52
- total: Number.isFinite(total) && total >= 0 ? total : lane.length,
53
- cursor: next,
54
- hasMore: next < (Number.isFinite(total) && total >= 0 ? total : lane.length),
56
+ total: totalRows,
57
+ cursor: items.length > 0 ? encodeTaskCursor(items[items.length - 1]) : "",
58
+ hasMore: remaining.length > items.length,
55
59
  state,
56
60
  };
57
61
  }
@@ -74,7 +78,7 @@ export class SnapshotCache {
74
78
  this.building = null;
75
79
  this.lastBuildAt = 0;
76
80
  this.metrics = { builds: 0, versionChecks: 0, eventBytesRead: 0, eventLinesParsed: 0, cliCalls: 0 };
77
- this.events = { offset: 0, size: 0, mtimeMs: null, tail: [], total: 0, kinds: new Map() };
81
+ this.events = { offset: 0, size: 0, mtimeMs: null, tail: [], total: 0, lineIndex: 0, kinds: new Map() };
78
82
  }
79
83
 
80
84
  eventsPath() { return path.join(this.repo, ".hive", "events.jsonl"); }
@@ -97,13 +101,13 @@ export class SnapshotCache {
97
101
  let stat = null;
98
102
  try { stat = this.statSync(file); } catch { stat = null; }
99
103
  if (stat === null) {
100
- this.events = { offset: 0, size: 0, mtimeMs: null, tail: [], total: 0, kinds: new Map() };
104
+ this.events = { offset: 0, size: 0, mtimeMs: null, tail: [], total: 0, lineIndex: 0, kinds: new Map() };
101
105
  return;
102
106
  }
103
107
  const size = Number(stat.size) || 0;
104
108
  if (size < this.events.offset || (this.events.mtimeMs !== null && stat.mtimeMs < this.events.mtimeMs)) {
105
109
  // Truncated/rewritten log: restart the byte cursor.
106
- this.events = { offset: 0, size: 0, mtimeMs: null, tail: [], total: 0, kinds: new Map() };
110
+ this.events = { offset: 0, size: 0, mtimeMs: null, tail: [], total: 0, lineIndex: 0, kinds: new Map() };
107
111
  }
108
112
  if (size === this.events.offset && stat.mtimeMs === this.events.mtimeMs) return;
109
113
  let bytes = "";
@@ -122,10 +126,14 @@ export class SnapshotCache {
122
126
  const lines = bytes.split("\n");
123
127
  lines.pop(); // an incomplete trailing line is left for the next read
124
128
  for (const line of lines) {
129
+ if (line === "") continue;
130
+ const lineIndex = this.events.lineIndex;
131
+ this.events.lineIndex += 1;
125
132
  if (!line.trim()) continue;
126
133
  this.metrics.eventLinesParsed += 1;
127
134
  const event = parseJson(line, null);
128
135
  if (event === null || typeof event !== "object") continue;
136
+ event.key = eventLineKey(lineIndex, line);
129
137
  this.events.total += 1;
130
138
  const kind = String(event.kind || "");
131
139
  if (kind) this.events.kinds.set(kind, (this.events.kinds.get(kind) || 0) + 1);
@@ -226,7 +234,10 @@ export class SnapshotCache {
226
234
  const total = data.eventTotal;
227
235
  const tailCount = Math.min(EVENT_TAIL_MAX, total);
228
236
  const firstIndex = total - tailCount;
229
- const start = Math.max(0, Math.min(total, Math.floor(Number(after) || 0)));
237
+ const parsedKey = parseEventLineKey(after);
238
+ const start = parsedKey !== null
239
+ ? parsedKey.index + 1
240
+ : Math.max(0, Math.min(total, Math.floor(Number(after) || 0)));
230
241
  const wanted = String(kind || "");
231
242
  const fresh = [];
232
243
  for (let index = Math.max(start, firstIndex); index < total; index += 1) {
@@ -235,16 +246,35 @@ export class SnapshotCache {
235
246
  }
236
247
  const size = Math.max(1, Math.min(200, Math.floor(Number(limit) || 50)));
237
248
  const items = fresh.slice(Math.max(0, fresh.length - size)).reverse();
238
- return { items, total, cursor: total, hasMore: fresh.length > size, kind: wanted, dropped: start < firstIndex };
249
+ const latest = data.events[0];
250
+ const cursor = latest && latest.key ? latest.key : String(after || "");
251
+ return {
252
+ items,
253
+ total,
254
+ cursor,
255
+ hasMore: fresh.length > size,
256
+ kind: wanted,
257
+ dropped: parsedKey !== null ? parsedKey.index < firstIndex : start < firstIndex,
258
+ };
239
259
  }
240
- async tasksPage({ state = "", cursor = 0, limit = LANE_PAGE_LIMIT } = {}) {
260
+ async tasksPage({ state = "", cursor = "", limit = LANE_PAGE_LIMIT } = {}) {
241
261
  const data = await this.snapshot();
242
262
  const all = Array.isArray(data.allTasks) ? data.allTasks : data.tasks;
243
263
  if (!state) {
244
- const offset = Math.max(0, Number(cursor) || 0);
264
+ const sorted = [...all].sort(compareTasks);
265
+ const parsed = decodeTaskCursor(cursor);
266
+ const remaining = parsed && parsed.legacyOffset !== undefined
267
+ ? sorted.slice(parsed.legacyOffset)
268
+ : sorted.filter((task) => isTaskAfterCursor(task, parsed));
245
269
  const size = Math.max(1, Math.min(LANE_PAGE_LIMIT, Number(limit) || LANE_PAGE_LIMIT));
246
- const items = [...all].sort(compareTasks).slice(offset, offset + size);
247
- return { items, total: all.length, cursor: offset + items.length, hasMore: offset + items.length < all.length, state: "" };
270
+ const items = remaining.slice(0, size);
271
+ return {
272
+ items,
273
+ total: sorted.length,
274
+ cursor: items.length > 0 ? encodeTaskCursor(items[items.length - 1]) : "",
275
+ hasMore: remaining.length > items.length,
276
+ state: "",
277
+ };
248
278
  }
249
279
  return lanePage(all, data.stats, String(state), cursor, limit);
250
280
  }
package/src/data.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { spawnSync } from "node:child_process";
4
+ import { eventLineKey, parseEventLineKey } from "./event-store.js";
4
5
 
5
6
  function run(file, args, cwd) {
6
7
  const result = spawnSync(file, args, { cwd, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
@@ -24,8 +25,12 @@ export const EVENT_PAGE_LIMIT = 80;
24
25
  export function readEventRows(repo) {
25
26
  const file = path.join(repo, ".hive", "events.jsonl");
26
27
  if (!fs.existsSync(file)) return [];
27
- return fs.readFileSync(file, "utf8").split("\n").filter(Boolean).map((line) => {
28
- try { return JSON.parse(line); } catch { return null; }
28
+ return fs.readFileSync(file, "utf8").split("\n").filter(Boolean).map((line, index) => {
29
+ try {
30
+ const event = JSON.parse(line);
31
+ event.key = eventLineKey(index, line);
32
+ return event;
33
+ } catch { return null; }
29
34
  }).filter(Boolean).reverse();
30
35
  }
31
36
 
@@ -125,6 +130,38 @@ function laneTotal(stats, state, rows) {
125
130
  return Number.isFinite(value) && value >= 0 ? value : rows.length;
126
131
  }
127
132
 
133
+ /** Stable pagination cursor: sort timestamp plus task id, base64url encoded. */
134
+ export function encodeTaskCursor(task) {
135
+ const time = taskSortTime(task);
136
+ return Buffer.from(JSON.stringify([Number.isFinite(time) ? time : null, String(task && task.id || "")]), "utf8").toString("base64url");
137
+ }
138
+
139
+ /** Decode a cursor; numeric values are accepted for backwards compatibility. */
140
+ export function decodeTaskCursor(value) {
141
+ const text = String(value === undefined || value === null ? "" : value).trim();
142
+ if (text === "" || text === "0") return null;
143
+ if (/^\d+$/.test(text)) return { legacyOffset: Number(text) };
144
+ try {
145
+ const parsed = JSON.parse(Buffer.from(text, "base64url").toString("utf8"));
146
+ if (!Array.isArray(parsed) || parsed.length !== 2) return null;
147
+ const time = parsed[0] === null ? null : Number(parsed[0]);
148
+ if (time !== null && !Number.isFinite(time)) return null;
149
+ return { time, id: String(parsed[1] ?? "") };
150
+ } catch { return null; }
151
+ }
152
+
153
+ /** True when the task sorts after the cursor in newest-first order. */
154
+ export function isTaskAfterCursor(task, cursor) {
155
+ if (!cursor || cursor.legacyOffset !== undefined) return true;
156
+ const time = taskSortTime(task);
157
+ const id = String(task && task.id || "");
158
+ if (cursor.time === null) return !Number.isFinite(time) && id.localeCompare(cursor.id) < 0;
159
+ if (!Number.isFinite(time)) return true;
160
+ if (time < cursor.time) return true;
161
+ if (time > cursor.time) return false;
162
+ return id.localeCompare(cursor.id) < 0;
163
+ }
164
+
128
165
  export function paginateTasks(tasks, stats, limit = TASK_PAGE_LIMIT) {
129
166
  const size = Number.isFinite(limit) && limit > 0 ? Math.min(200, Math.floor(limit)) : TASK_PAGE_LIMIT;
130
167
  const lanePages = {};
@@ -137,23 +174,31 @@ export function paginateTasks(tasks, stats, limit = TASK_PAGE_LIMIT) {
137
174
  lanePages[state] = {
138
175
  items,
139
176
  total,
140
- cursor: items.length,
177
+ cursor: items.length > 0 ? encodeTaskCursor(items[items.length - 1]) : "",
141
178
  hasMore: items.length < total,
142
179
  };
143
180
  }
144
181
  return lanePages;
145
182
  }
146
183
 
147
- export function snapshotTasksPage(repo, { state = "", cursor = 0, limit = TASK_PAGE_LIMIT } = {}, env = process.env) {
184
+ export function snapshotTasksPage(repo, { state = "", cursor = "", limit = TASK_PAGE_LIMIT } = {}, env = process.env) {
148
185
  let rows = readTasks(repo, env);
149
186
  if (state) rows = rows.filter((task) => (task.state || "pending") === state);
150
187
  rows.sort(compareTasksNewestFirst);
151
188
  const total = rows.length;
152
- const offset = Math.max(0, Math.floor(Number(cursor) || 0));
189
+ const parsed = decodeTaskCursor(cursor);
190
+ const remaining = parsed && parsed.legacyOffset !== undefined
191
+ ? rows.slice(parsed.legacyOffset)
192
+ : rows.filter((task) => isTaskAfterCursor(task, parsed));
153
193
  const size = Math.max(1, Math.min(200, Math.floor(Number(limit) || TASK_PAGE_LIMIT)));
154
- const items = rows.slice(offset, offset + size);
155
- const next = offset + items.length;
156
- return { items, total, cursor: next, hasMore: next < total, state: String(state || "") };
194
+ const items = remaining.slice(0, size);
195
+ return {
196
+ items,
197
+ total,
198
+ cursor: items.length > 0 ? encodeTaskCursor(items[items.length - 1]) : "",
199
+ hasMore: remaining.length > items.length,
200
+ state: String(state || ""),
201
+ };
157
202
  }
158
203
 
159
204
  export function findTaskById(repo, id, env = process.env) {
@@ -213,13 +258,22 @@ export function readNewEvents(repo, { after = 0, limit = 50, kind = "" } = {}) {
213
258
  } catch {
214
259
  lines = [];
215
260
  }
216
- const cursor = Math.max(0, Math.floor(Number(after) || 0));
261
+ const parsedKey = parseEventLineKey(after);
262
+ const start = parsedKey !== null
263
+ ? parsedKey.index + 1
264
+ : Math.max(0, Math.floor(Number(after) || 0));
217
265
  const wanted = String(kind || "");
218
266
  const size = Math.max(1, Math.min(200, Math.floor(Number(limit) || 50)));
219
267
  const fresh = [];
220
- for (let index = Math.max(cursor, 0); index < lines.length; index += 1) {
268
+ let latestKey = "";
269
+ for (let index = 0; index < lines.length; index += 1) {
270
+ const line = lines[index];
271
+ const key = eventLineKey(index, line);
272
+ latestKey = key;
273
+ if (index < start) continue;
221
274
  try {
222
- const event = JSON.parse(lines[index]);
275
+ const event = JSON.parse(line);
276
+ event.key = key;
223
277
  if (wanted && String(event.kind || "") !== wanted) continue;
224
278
  fresh.push(event);
225
279
  } catch {
@@ -229,9 +283,10 @@ export function readNewEvents(repo, { after = 0, limit = 50, kind = "" } = {}) {
229
283
  return {
230
284
  items: fresh.slice(-size).reverse(),
231
285
  total: lines.length,
232
- cursor: lines.length,
286
+ cursor: latestKey || String(after || ""),
233
287
  hasMore: fresh.length > size,
234
288
  kind: wanted,
289
+ dropped: false,
235
290
  };
236
291
  }
237
292
 
@@ -1,3 +1,4 @@
1
+ import crypto from "node:crypto";
1
2
  import fs from "node:fs";
2
3
  import path from "node:path";
3
4
 
@@ -13,29 +14,38 @@ function readLines(file) {
13
14
  }
14
15
  }
15
16
 
16
- function eventKey(event) {
17
- const raw = event && typeof event === "object" ? event : {};
18
- return JSON.stringify([String(raw.ts ?? ""), String(raw.kind ?? ""), String(raw.actor ?? ""), String(raw.task ?? "")]);
17
+ /**
18
+ * Stable identity of one event log row: 0-based line index plus a short hash of
19
+ * the raw line. Identical event objects on different lines therefore stay
20
+ * distinct, and a stale key can never delete a different row.
21
+ * @param {number} index
22
+ * @param {string} line
23
+ * @returns {string}
24
+ */
25
+ export function eventLineKey(index, line) {
26
+ const hash = crypto.createHash("sha1").update(String(line)).digest("hex").slice(0, 16);
27
+ return String(Math.max(0, Math.floor(Number(index) || 0))) + ":" + hash;
19
28
  }
20
29
 
21
- /** Delete exact event keys, returning one result per key. Best effort, never throws. */
30
+ /** @param {unknown} key */
31
+ export function parseEventLineKey(key) {
32
+ const match = /^(\d+):([0-9a-f]{16})$/.exec(String(key || ""));
33
+ if (!match) return null;
34
+ return { index: Number(match[1]), hash: match[2] };
35
+ }
36
+
37
+ /** Delete exact event rows, returning one result per key. Best effort, never throws. */
22
38
  export function deleteEvents(repo, keys) {
23
39
  const wanted = new Set((Array.isArray(keys) ? keys : []).map(String));
24
40
  const file = eventFile(repo);
25
41
  const lines = readLines(file);
26
42
  const kept = [];
27
43
  const removed = new Set();
28
- let parseErrors = 0;
29
- for (const line of lines) {
30
- try {
31
- const event = JSON.parse(line);
32
- const key = eventKey(event);
33
- if (wanted.has(key)) removed.add(key);
34
- else kept.push(line);
35
- } catch {
36
- parseErrors += 1;
37
- kept.push(line);
38
- }
44
+ for (let index = 0; index < lines.length; index += 1) {
45
+ const line = lines[index];
46
+ const key = eventLineKey(index, line);
47
+ if (wanted.has(key)) removed.add(key);
48
+ else kept.push(line);
39
49
  }
40
50
  if (removed.size > 0) fs.writeFileSync(file, kept.length > 0 ? kept.join("\n") + "\n" : "");
41
51
  return [...wanted].map((key) => ({
@@ -66,3 +76,19 @@ export function pruneEventsBefore(repo, before) {
66
76
  if (deleted > 0) fs.writeFileSync(file, kept.length > 0 ? kept.join("\n") + "\n" : "");
67
77
  return [{ key: "before", ok: true, error: "", deleted }];
68
78
  }
79
+
80
+ /** Count events strictly older than the cutoff, for the UI confirmation. */
81
+ export function countEventsBefore(repo, before) {
82
+ const cutoff = Date.parse(before);
83
+ if (!Number.isFinite(cutoff)) return { ok: false, error: "invalid timestamp", count: 0 };
84
+ let count = 0;
85
+ for (const line of readLines(eventFile(repo))) {
86
+ try {
87
+ const ts = Date.parse(JSON.parse(line).ts);
88
+ if (Number.isFinite(ts) && ts < cutoff) count += 1;
89
+ } catch {
90
+ // Invalid lines are preserved by prune; they are not counted as prunable.
91
+ }
92
+ }
93
+ return { ok: true, count };
94
+ }
package/src/server.js CHANGED
@@ -5,6 +5,7 @@ import { execFile } from "node:child_process";
5
5
  import { isInitialised, status } from "./data.js";
6
6
  import { createSnapshotCache } from "./cache.js";
7
7
  import { listActions, runAction } from "./actions.js";
8
+ import { deleteEvents, pruneEventsBefore, countEventsBefore } from "./event-store.js";
8
9
 
9
10
  const MIME = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".svg": "image/svg+xml" };
10
11
 
@@ -31,6 +32,7 @@ export function createServer({ repo, publicDir, env = process.env, writable = fa
31
32
  const tasks = env.HIVE_TASKS_BIN || "hive-tasks";
32
33
  const snapshotCache = createSnapshotCache({ repo, env });
33
34
  const server = http.createServer(async (request, response) => {
35
+ try {
34
36
  const url = new URL(request.url, "http://localhost");
35
37
 
36
38
  if (url.pathname === "/api/health") {
@@ -87,6 +89,12 @@ export function createServer({ repo, publicDir, env = process.env, writable = fa
87
89
  return response.end(JSON.stringify(page));
88
90
  }
89
91
 
92
+ if (request.method === "GET" && url.pathname === "/api/events" && url.searchParams.get("before") !== null) {
93
+ const counted = countEventsBefore(repo, url.searchParams.get("before") || "");
94
+ response.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
95
+ return response.end(JSON.stringify(counted));
96
+ }
97
+
90
98
  if (request.method === "GET" && url.pathname === "/api/events") {
91
99
  const page = await snapshotCache.eventsPage({
92
100
  cursor: url.searchParams.get("cursor") || "0",
@@ -108,7 +116,13 @@ export function createServer({ repo, publicDir, env = process.env, writable = fa
108
116
  }
109
117
 
110
118
  if (request.method === "GET" && url.pathname.startsWith("/api/tasks/")) {
111
- const id = decodeURIComponent(url.pathname.slice("/api/tasks/".length));
119
+ let id;
120
+ try {
121
+ id = decodeURIComponent(url.pathname.slice("/api/tasks/".length));
122
+ } catch {
123
+ response.writeHead(400, { "content-type": "application/json; charset=utf-8" });
124
+ return response.end(JSON.stringify({ ok: false, error: "invalid task id encoding" }));
125
+ }
112
126
  const cached = await snapshotCache.snapshot();
113
127
  const allTasks = Array.isArray(cached.allTasks) ? cached.allTasks : cached.tasks;
114
128
  const task = allTasks.find((entry) => String(entry.id) === String(id)) ?? null;
@@ -173,6 +187,14 @@ export function createServer({ repo, publicDir, env = process.env, writable = fa
173
187
  }
174
188
  response.writeHead(200, { "content-type": MIME[path.extname(file)] || "application/octet-stream", "cache-control": "no-store" });
175
189
  fs.createReadStream(file).pipe(response);
190
+ } catch (error) {
191
+ if (response.headersSent) {
192
+ response.destroy();
193
+ return;
194
+ }
195
+ response.writeHead(500, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
196
+ response.end(JSON.stringify({ ok: false, error: "internal server error" }));
197
+ }
176
198
  });
177
199
 
178
200
  return server;