@d86e/hive-panel 1.0.29 → 1.0.30
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 +1 -1
- package/public/panel.js +114 -24
- package/src/cache.js +46 -16
- package/src/data.js +67 -12
- package/src/event-store.js +41 -15
- package/src/server.js +23 -1
package/package.json
CHANGED
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",
|
|
@@ -2651,6 +2653,8 @@ export const messages = Object.freeze({
|
|
|
2651
2653
|
"events.actor.legacy": "智能体",
|
|
2652
2654
|
"events.recycled": "已回收更早的 {count} 条",
|
|
2653
2655
|
"events.loadFailed": "事件加载失败",
|
|
2656
|
+
"events.missed": "事件流存在缺口",
|
|
2657
|
+
"events.missedReloaded": "已重新加载最新事件。",
|
|
2654
2658
|
"events.pageFailed": "更早的事件加载失败",
|
|
2655
2659
|
"events.retry": "重试",
|
|
2656
2660
|
"events.details": "详情",
|
|
@@ -3182,6 +3186,7 @@ function normalizeEvents(events) {
|
|
|
3182
3186
|
kind: asString(event.kind),
|
|
3183
3187
|
task: asString(event.task),
|
|
3184
3188
|
actor: asString(event.actor),
|
|
3189
|
+
key: asString(event.key),
|
|
3185
3190
|
raw: event,
|
|
3186
3191
|
}));
|
|
3187
3192
|
}
|
|
@@ -3296,6 +3301,7 @@ export function renderModel(snapshot) {
|
|
|
3296
3301
|
prompt: typeof entry.prompt === "string" ? entry.prompt : null,
|
|
3297
3302
|
promptExists: entry.promptExists === true,
|
|
3298
3303
|
limit: typeof entry.limit === "number" && Number.isFinite(entry.limit) ? entry.limit : null,
|
|
3304
|
+
source: normalizeLimitSource(entry.source || entry.limitSource || entry.limit_source),
|
|
3299
3305
|
}))
|
|
3300
3306
|
.filter((entry) => entry.name)
|
|
3301
3307
|
: [],
|
|
@@ -3309,7 +3315,7 @@ export function renderModel(snapshot) {
|
|
|
3309
3315
|
const rows = lanes[state];
|
|
3310
3316
|
const raw = rawLanePages && isRecord(rawLanePages[state]) ? rawLanePages[state] : null;
|
|
3311
3317
|
const total = raw ? asCount(raw.total, rows.length) : rows.length;
|
|
3312
|
-
const cursor = raw ?
|
|
3318
|
+
const cursor = raw && raw.cursor !== undefined && raw.cursor !== null ? String(raw.cursor) : "";
|
|
3313
3319
|
lanePages[state] = {
|
|
3314
3320
|
loaded: rows.length,
|
|
3315
3321
|
total,
|
|
@@ -3358,13 +3364,21 @@ function supervisorNumber(value) {
|
|
|
3358
3364
|
return null;
|
|
3359
3365
|
}
|
|
3360
3366
|
|
|
3367
|
+
function normalizeLimitSource(value) {
|
|
3368
|
+
const text = asString(value).trim().toLowerCase();
|
|
3369
|
+
if (text === "limits" || text === "limits.json") return "limits";
|
|
3370
|
+
if (text === "config") return "config";
|
|
3371
|
+
if (text === "default") return "default";
|
|
3372
|
+
return null;
|
|
3373
|
+
}
|
|
3374
|
+
|
|
3361
3375
|
function normalizeSupervisorRoles(source) {
|
|
3362
3376
|
if (!isRecord(source)) return [];
|
|
3363
3377
|
const rows = new Map();
|
|
3364
3378
|
const ensure = (role) => {
|
|
3365
3379
|
const name = asString(role).trim();
|
|
3366
3380
|
if (!name) return null;
|
|
3367
|
-
if (!rows.has(name)) rows.set(name, { role: name, limit: null, live: null, inFlight: null, queued: null });
|
|
3381
|
+
if (!rows.has(name)) rows.set(name, { role: name, limit: null, live: null, inFlight: null, queued: null, source: null });
|
|
3368
3382
|
return rows.get(name);
|
|
3369
3383
|
};
|
|
3370
3384
|
const setLimit = (role, value) => {
|
|
@@ -3386,6 +3400,8 @@ function normalizeSupervisorRoles(source) {
|
|
|
3386
3400
|
const role = asString(raw.role || raw.name || raw.key || raw.id || fallbackRole);
|
|
3387
3401
|
const row = ensure(role);
|
|
3388
3402
|
if (!row) return;
|
|
3403
|
+
const declaredSource = normalizeLimitSource(raw.source || raw.limitSource || raw.limit_source);
|
|
3404
|
+
if (declaredSource !== null) row.source = declaredSource;
|
|
3389
3405
|
for (const field of ["limit", "max", "concurrency", "concurrencyLimit", "maxConcurrency", "max_concurrency", "concurrency_limit", "maxInFlight", "max_in_flight", "cap", "capacity", "value", "n"]) {
|
|
3390
3406
|
if (supervisorNumber(raw[field]) !== null) {
|
|
3391
3407
|
row.limit = supervisorNumber(raw[field]);
|
|
@@ -4460,29 +4476,64 @@ export function mount(root, options = {}) {
|
|
|
4460
4476
|
const time = Date.parse(value);
|
|
4461
4477
|
return Number.isFinite(time) ? time : null;
|
|
4462
4478
|
};
|
|
4479
|
+
let pruneCountSeq = 0;
|
|
4480
|
+
const pruneCountText = (count, time) => translate("events.pruneCount")
|
|
4481
|
+
.replace("{count}", String(count))
|
|
4482
|
+
.replace("{time}", time === null ? "—" : new Date(time).toLocaleString());
|
|
4463
4483
|
pruneInput.addEventListener("input", () => {
|
|
4464
4484
|
const time = pruneBefore();
|
|
4485
|
+
pruneCountSeq += 1;
|
|
4486
|
+
const seq = pruneCountSeq;
|
|
4465
4487
|
if (time === null) {
|
|
4466
|
-
pruneCount.textContent =
|
|
4488
|
+
pruneCount.textContent = pruneCountText(0, null);
|
|
4467
4489
|
return;
|
|
4468
4490
|
}
|
|
4469
|
-
const
|
|
4491
|
+
const localCount = eventState.items.filter((event) => {
|
|
4470
4492
|
const ts = Date.parse(event.ts);
|
|
4471
4493
|
return Number.isFinite(ts) && ts < time;
|
|
4472
4494
|
}).length;
|
|
4473
|
-
pruneCount.textContent =
|
|
4495
|
+
pruneCount.textContent = pruneCountText(localCount, time);
|
|
4496
|
+
if (!fetchImpl) return;
|
|
4497
|
+
const before = new Date(time).toISOString();
|
|
4498
|
+
void (async () => {
|
|
4499
|
+
try {
|
|
4500
|
+
const url = eventsUrl + (eventsUrl.includes("?") ? "&" : "?") + "before=" + encodeURIComponent(before);
|
|
4501
|
+
const response = await fetchImpl(url, { cache: "no-store", headers: { accept: "application/json" } });
|
|
4502
|
+
if (!response || response.ok === false) return;
|
|
4503
|
+
const payload = await response.json();
|
|
4504
|
+
const count = asCount(payload && payload.count, -1);
|
|
4505
|
+
if (seq === pruneCountSeq && count >= 0 && !destroyed) pruneCount.textContent = pruneCountText(count, time);
|
|
4506
|
+
} catch {
|
|
4507
|
+
// The local count stays visible when the count route is unavailable.
|
|
4508
|
+
}
|
|
4509
|
+
})();
|
|
4474
4510
|
});
|
|
4475
|
-
pruneConfirm.addEventListener("click", () => {
|
|
4511
|
+
pruneConfirm.addEventListener("click", async () => {
|
|
4476
4512
|
const time = pruneBefore();
|
|
4477
4513
|
if (time === null) return;
|
|
4478
|
-
const
|
|
4514
|
+
const before = new Date(time).toISOString();
|
|
4515
|
+
let count = eventState.items.filter((event) => {
|
|
4479
4516
|
const ts = Date.parse(event.ts);
|
|
4480
4517
|
return Number.isFinite(ts) && ts < time;
|
|
4481
4518
|
}).length;
|
|
4519
|
+
if (fetchImpl) {
|
|
4520
|
+
try {
|
|
4521
|
+
const url = eventsUrl + (eventsUrl.includes("?") ? "&" : "?") + "before=" + encodeURIComponent(before);
|
|
4522
|
+
const response = await fetchImpl(url, { cache: "no-store", headers: { accept: "application/json" } });
|
|
4523
|
+
if (response && response.ok !== false) {
|
|
4524
|
+
const payload = await response.json();
|
|
4525
|
+
const serverCount = asCount(payload && payload.count, -1);
|
|
4526
|
+
if (serverCount >= 0) count = serverCount;
|
|
4527
|
+
}
|
|
4528
|
+
} catch {
|
|
4529
|
+
// The loaded count remains a safe fallback when the count route is unavailable.
|
|
4530
|
+
}
|
|
4531
|
+
}
|
|
4532
|
+
if (destroyed) return;
|
|
4482
4533
|
const message = translate("events.pruneConfirm").replace("{count}", String(count)).replace("{time}", new Date(time).toLocaleString());
|
|
4483
4534
|
if (!confirmImpl || !confirmImpl(message)) return;
|
|
4484
4535
|
eventsPrune.className = "hive-event-prune is-hidden";
|
|
4485
|
-
void runBatch("events-prune", { before
|
|
4536
|
+
void runBatch("events-prune", { before });
|
|
4486
4537
|
});
|
|
4487
4538
|
eventsHead.appendChild(eventsMenu);
|
|
4488
4539
|
const eventsList = element(doc, "div", "hive-scroll hive-event-list");
|
|
@@ -5078,6 +5129,8 @@ export function mount(root, options = {}) {
|
|
|
5078
5129
|
const entry = ensure(name);
|
|
5079
5130
|
entry.inFlight = supervisorNumber(role.inFlight);
|
|
5080
5131
|
entry.queued = supervisorNumber(role.queued);
|
|
5132
|
+
const supervisorSource = normalizeLimitSource(role.source || role.limitSource || role.limit_source);
|
|
5133
|
+
if (supervisorSource !== null) entry.supervisorSource = supervisorSource;
|
|
5081
5134
|
const limit = supervisorNumber(role.limit);
|
|
5082
5135
|
if (limit !== null) entry.limit = limit;
|
|
5083
5136
|
}
|
|
@@ -5090,6 +5143,8 @@ export function mount(root, options = {}) {
|
|
|
5090
5143
|
const entry = ensure(name);
|
|
5091
5144
|
if (modelRole.adapter) entry.adapter = modelRole.adapter;
|
|
5092
5145
|
if (modelRole.model) entry.model = modelRole.model;
|
|
5146
|
+
const modelSource = normalizeLimitSource(modelRole.source || modelRole.limitSource || modelRole.limit_source);
|
|
5147
|
+
if (modelSource !== null) entry.modelSource = modelSource;
|
|
5093
5148
|
const limit = supervisorNumber(modelRole.limit);
|
|
5094
5149
|
if (limit !== null) {
|
|
5095
5150
|
entry.limit = limit;
|
|
@@ -5130,9 +5185,9 @@ export function mount(root, options = {}) {
|
|
|
5130
5185
|
entry.source = "limits";
|
|
5131
5186
|
} else if (supervisorLimit !== null) {
|
|
5132
5187
|
entry.limit = supervisorLimit;
|
|
5133
|
-
entry.source = "config";
|
|
5188
|
+
entry.source = entry.supervisorSource || "config";
|
|
5134
5189
|
} else if (entry.modelLimit) {
|
|
5135
|
-
entry.source = "limits";
|
|
5190
|
+
entry.source = entry.modelSource || "limits";
|
|
5136
5191
|
} else {
|
|
5137
5192
|
entry.source = "default";
|
|
5138
5193
|
}
|
|
@@ -6321,7 +6376,7 @@ function renderMarkdownInto(doc, host, source) {
|
|
|
6321
6376
|
const byId = new Map();
|
|
6322
6377
|
for (const task of tasks) if (task && task.id) byId.set(task.id, task);
|
|
6323
6378
|
const dependsOn = (Array.isArray(card.after) ? card.after : [])
|
|
6324
|
-
.map((id) => byId.get(id))
|
|
6379
|
+
.map((id) => byId.get(id) || { id, title: id, state: "unknown", missing: true })
|
|
6325
6380
|
.filter(Boolean);
|
|
6326
6381
|
const requiredBy = tasks.filter(
|
|
6327
6382
|
(task) =>
|
|
@@ -7331,11 +7386,15 @@ function renderMarkdownInto(doc, host, source) {
|
|
|
7331
7386
|
|
|
7332
7387
|
async function readBatchResponse(response) {
|
|
7333
7388
|
const status = Number(response && response.status) || 0;
|
|
7389
|
+
if (status === 204 || status === 205) {
|
|
7390
|
+
return { status, data: { ok: true, results: [] } };
|
|
7391
|
+
}
|
|
7334
7392
|
const contentType = response && response.headers && typeof response.headers.get === "function"
|
|
7335
7393
|
? String(response.headers.get("content-type") || "")
|
|
7336
7394
|
: "";
|
|
7395
|
+
const hasText = Boolean(response && typeof response.text === "function");
|
|
7337
7396
|
let text = "";
|
|
7338
|
-
if (
|
|
7397
|
+
if (hasText) {
|
|
7339
7398
|
try {
|
|
7340
7399
|
text = await response.text();
|
|
7341
7400
|
} catch {
|
|
@@ -7352,7 +7411,11 @@ function renderMarkdownInto(doc, host, source) {
|
|
|
7352
7411
|
return { status, text, invalid: true };
|
|
7353
7412
|
}
|
|
7354
7413
|
}
|
|
7355
|
-
if (
|
|
7414
|
+
if (hasText && status >= 200 && status < 300) {
|
|
7415
|
+
// 204/205 and empty 2xx bodies have no result list: success, never replay a delete.
|
|
7416
|
+
return { status, data: { ok: true, results: [] } };
|
|
7417
|
+
}
|
|
7418
|
+
if (!hasText && response && typeof response.json === "function") {
|
|
7356
7419
|
try {
|
|
7357
7420
|
return { status, data: await response.json() };
|
|
7358
7421
|
} catch {
|
|
@@ -7821,7 +7884,6 @@ function renderMarkdownInto(doc, host, source) {
|
|
|
7821
7884
|
if (!next.has(key) && entry.node.parentNode) entry.node.parentNode.removeChild(entry.node);
|
|
7822
7885
|
}
|
|
7823
7886
|
state.visible = next;
|
|
7824
|
-
state.count.textContent = String(total);
|
|
7825
7887
|
}
|
|
7826
7888
|
|
|
7827
7889
|
function taskPageUrl(state, cursor) {
|
|
@@ -7885,8 +7947,8 @@ function renderMarkdownInto(doc, host, source) {
|
|
|
7885
7947
|
: null;
|
|
7886
7948
|
if (!items) throw new Error("tasks page returned no items");
|
|
7887
7949
|
const total = asCount(payload && payload.total, page.total);
|
|
7888
|
-
const cursor =
|
|
7889
|
-
const hasMore = payload && payload.hasMore === true
|
|
7950
|
+
const cursor = payload && payload.cursor !== undefined && payload.cursor !== null ? String(payload.cursor) : "";
|
|
7951
|
+
const hasMore = Boolean(payload && payload.hasMore === true);
|
|
7890
7952
|
if (!lastSnapshot) throw new Error("the board is not ready");
|
|
7891
7953
|
const existing = Array.isArray(lastSnapshot.tasks) ? lastSnapshot.tasks : [];
|
|
7892
7954
|
const seen = new Set(existing.map((task) => String(task && task.id)));
|
|
@@ -7944,8 +8006,8 @@ function renderMarkdownInto(doc, host, source) {
|
|
|
7944
8006
|
const payload = await response.json();
|
|
7945
8007
|
const items = Array.isArray(payload && payload.items) ? payload.items : [];
|
|
7946
8008
|
const total = asCount(payload && payload.total, items.length);
|
|
7947
|
-
const cursor =
|
|
7948
|
-
const hasMore = payload && payload.hasMore === true
|
|
8009
|
+
const cursor = payload && payload.cursor !== undefined && payload.cursor !== null ? String(payload.cursor) : "";
|
|
8010
|
+
const hasMore = Boolean(payload && payload.hasMore === true);
|
|
7949
8011
|
const others = (Array.isArray(lastSnapshot.tasks) ? lastSnapshot.tasks : [])
|
|
7950
8012
|
.filter((task) => (task && (task.state || "pending")) !== lane);
|
|
7951
8013
|
const lanePages = { ...(isRecord(lastSnapshot.lanePages) ? lastSnapshot.lanePages : {}) };
|
|
@@ -8477,6 +8539,8 @@ function renderMarkdownInto(doc, host, source) {
|
|
|
8477
8539
|
|
|
8478
8540
|
function eventKey(event) {
|
|
8479
8541
|
const raw = event.raw || {};
|
|
8542
|
+
if (event.key) return String(event.key);
|
|
8543
|
+
if (raw.key) return String(raw.key);
|
|
8480
8544
|
const ref = raw.task || event.task || "";
|
|
8481
8545
|
return JSON.stringify([String(event.ts || ""), String(event.kind || ""), String(event.actor || raw.actor || ""), String(ref)]);
|
|
8482
8546
|
}
|
|
@@ -8650,7 +8714,15 @@ function renderMarkdownInto(doc, host, source) {
|
|
|
8650
8714
|
eventState.recycled = 0;
|
|
8651
8715
|
eventsList.scrollTop = 0;
|
|
8652
8716
|
} else if (items.length > 0) {
|
|
8653
|
-
|
|
8717
|
+
const known = new Set(eventState.items.map((event) => eventKey(event)));
|
|
8718
|
+
const fresh = [];
|
|
8719
|
+
for (const item of items) {
|
|
8720
|
+
const key = eventKey(item);
|
|
8721
|
+
if (known.has(key)) continue;
|
|
8722
|
+
known.add(key);
|
|
8723
|
+
fresh.push(item);
|
|
8724
|
+
}
|
|
8725
|
+
eventState.items = eventState.items.concat(fresh);
|
|
8654
8726
|
if (eventState.items.length > 5000) {
|
|
8655
8727
|
const dropped = eventState.items.length - 5000;
|
|
8656
8728
|
eventState.items = eventState.items.slice(0, 5000);
|
|
@@ -8883,7 +8955,7 @@ function renderMarkdownInto(doc, host, source) {
|
|
|
8883
8955
|
const payload = await response.json();
|
|
8884
8956
|
const items = Array.isArray(payload && payload.items) ? payload.items : [];
|
|
8885
8957
|
const total = asCount(payload && payload.total, items.length);
|
|
8886
|
-
const cursor =
|
|
8958
|
+
const cursor = payload && payload.cursor !== undefined && payload.cursor !== null ? String(payload.cursor) : "";
|
|
8887
8959
|
taskSlices[lane] = items;
|
|
8888
8960
|
taskSlicePages[lane] = { total, cursor, hasMore: Boolean(payload && payload.hasMore) };
|
|
8889
8961
|
state.initialLoading = false;
|
|
@@ -8909,7 +8981,7 @@ function renderMarkdownInto(doc, host, source) {
|
|
|
8909
8981
|
eventState.items = items;
|
|
8910
8982
|
eventState.total = asCount(payload && payload.total, items.length);
|
|
8911
8983
|
eventState.cursor = asCount(payload && payload.cursor, items.length);
|
|
8912
|
-
eventState.pollCursor =
|
|
8984
|
+
eventState.pollCursor = items.length > 0 ? eventKey(items[0]) : "";
|
|
8913
8985
|
eventState.filter = "";
|
|
8914
8986
|
eventState.recycled = 0;
|
|
8915
8987
|
eventState.paged = false;
|
|
@@ -9059,15 +9131,20 @@ function renderMarkdownInto(doc, host, source) {
|
|
|
9059
9131
|
async function pollEventsIncremental() {
|
|
9060
9132
|
if (!fetchImpl || !initialDataLoaded || eventState.filter) return;
|
|
9061
9133
|
if (!isNodeVisible(eventsDrawer)) return;
|
|
9062
|
-
const after =
|
|
9134
|
+
const after = eventState.pollCursor === undefined || eventState.pollCursor === null ? "" : String(eventState.pollCursor);
|
|
9063
9135
|
try {
|
|
9064
9136
|
const url = eventsUrl + (eventsUrl.includes("?") ? "&" : "?") +
|
|
9065
|
-
"after=" + encodeURIComponent(
|
|
9137
|
+
"after=" + encodeURIComponent(after) + "&limit=50";
|
|
9066
9138
|
const response = await fetchImpl(url, { cache: "no-store", headers: { accept: "application/json" } });
|
|
9067
9139
|
if (!response || response.ok === false) return;
|
|
9068
9140
|
const payload = await response.json();
|
|
9141
|
+
if (payload && payload.dropped === true) {
|
|
9142
|
+
await loadInitialEvents();
|
|
9143
|
+
if (!destroyed) showToast("error", translate("events.missed"), translate("events.missedReloaded"));
|
|
9144
|
+
return;
|
|
9145
|
+
}
|
|
9069
9146
|
const items = normalizeEvents(Array.isArray(payload && payload.items) ? payload.items : []);
|
|
9070
|
-
const nextCursor =
|
|
9147
|
+
const nextCursor = payload && payload.cursor !== undefined && payload.cursor !== null ? String(payload.cursor) : after;
|
|
9071
9148
|
const total = asCount(payload && payload.total, eventState.total);
|
|
9072
9149
|
eventState.pollCursor = nextCursor;
|
|
9073
9150
|
eventState.total = Math.max(total, eventState.items.length);
|
|
@@ -9232,7 +9309,20 @@ function renderMarkdownInto(doc, host, source) {
|
|
|
9232
9309
|
}
|
|
9233
9310
|
}
|
|
9234
9311
|
|
|
9312
|
+
function renderActionPlaceholders() {
|
|
9313
|
+
clearNode(actionsNode);
|
|
9314
|
+
for (const action of toolbarActions(true, "free")) {
|
|
9315
|
+
const button = element(doc, "button", "hive-btn hive-action-placeholder", translate(action.labelKey));
|
|
9316
|
+
setAttr(button, "type", "button");
|
|
9317
|
+
setAttr(button, "title", translate(action.helpKey));
|
|
9318
|
+
setAttr(button, "disabled", "disabled");
|
|
9319
|
+
button.disabled = true;
|
|
9320
|
+
actionsNode.appendChild(button);
|
|
9321
|
+
}
|
|
9322
|
+
}
|
|
9323
|
+
|
|
9235
9324
|
function primeInitialUI() {
|
|
9325
|
+
renderActionPlaceholders();
|
|
9236
9326
|
for (const lane of LANE_ORDER) {
|
|
9237
9327
|
if (laneRenderState.has(lane)) continue;
|
|
9238
9328
|
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
|
|
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 =
|
|
49
|
-
const next = offset + items.length;
|
|
53
|
+
const items = remaining.slice(0, size);
|
|
50
54
|
return {
|
|
51
55
|
items,
|
|
52
|
-
total:
|
|
53
|
-
cursor:
|
|
54
|
-
hasMore:
|
|
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
|
|
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
|
-
|
|
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 =
|
|
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
|
|
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 =
|
|
247
|
-
return {
|
|
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 {
|
|
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 =
|
|
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
|
|
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 =
|
|
155
|
-
|
|
156
|
-
|
|
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
|
|
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
|
-
|
|
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(
|
|
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:
|
|
286
|
+
cursor: latestKey || String(after || ""),
|
|
233
287
|
hasMore: fresh.length > size,
|
|
234
288
|
kind: wanted,
|
|
289
|
+
dropped: false,
|
|
235
290
|
};
|
|
236
291
|
}
|
|
237
292
|
|
package/src/event-store.js
CHANGED
|
@@ -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
|
-
|
|
17
|
-
|
|
18
|
-
|
|
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
|
-
/**
|
|
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
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
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
|
-
|
|
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;
|