neurastream 0.2.11 → 0.2.13
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/README.md +19 -1
- package/package.json +1 -1
- package/src/adapters/omp/index.ts +204 -36
- package/src/adapters/omp/sessions.ts +10 -35
- package/src/adapters/omp/traces.ts +140 -0
- package/src/cli/dispatch.ts +6 -0
- package/src/cli/guard.ts +7 -1
- package/src/cli/traces.ts +115 -0
- package/src/core/adapter.ts +36 -0
- package/src/core/guards.ts +130 -9
- package/src/core/incident-detectors.ts +34 -1
- package/src/core/owner-ui.ts +586 -100
- package/src/core/queue/lib.ts +18 -12
- package/src/core/trace-claims.ts +212 -0
- package/templates/AGENTS.md +1 -0
package/src/core/owner-ui.ts
CHANGED
|
@@ -7,9 +7,10 @@
|
|
|
7
7
|
// tests never call the binary; the peer address is an injectable seam too, so tests bind
|
|
8
8
|
// 127.0.0.1 while the real server binds only the tailnet address from `tailscale ip -4`.
|
|
9
9
|
|
|
10
|
-
import { appendFileSync, mkdirSync, readFileSync, statSync, statfsSync } from "node:fs";
|
|
10
|
+
import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync, statfsSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { randomUUID } from "node:crypto";
|
|
11
12
|
import os from "node:os";
|
|
12
|
-
import { basename } from "node:path";
|
|
13
|
+
import { basename, resolve } from "node:path";
|
|
13
14
|
import type { RunSource } from "./adapter.ts";
|
|
14
15
|
import type { Config } from "./config.ts";
|
|
15
16
|
import { nowSec, strftime } from "./clock.ts";
|
|
@@ -79,142 +80,521 @@ export function authenticate(cfg: Config, tailscale: Tailscale, peer: string): A
|
|
|
79
80
|
|
|
80
81
|
// ---- sections ----
|
|
81
82
|
|
|
82
|
-
|
|
83
|
+
function esc(s: string): string {
|
|
84
|
+
return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// ---- page data: one pure typed-row builder per source; rendering reads only these ----
|
|
88
|
+
|
|
89
|
+
export interface QuestionRow {
|
|
90
|
+
plan: string;
|
|
83
91
|
title: string;
|
|
84
|
-
|
|
92
|
+
repo: string;
|
|
93
|
+
waitingLine: string;
|
|
94
|
+
goal: string[];
|
|
95
|
+
waitingMin: number;
|
|
85
96
|
}
|
|
86
97
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
}
|
|
98
|
+
export interface AgentRow {
|
|
99
|
+
id: string;
|
|
100
|
+
model: string;
|
|
101
|
+
detail: string;
|
|
102
|
+
minutes: number;
|
|
103
|
+
status: string;
|
|
94
104
|
}
|
|
95
105
|
|
|
96
|
-
|
|
97
|
-
|
|
106
|
+
export interface QueueRow {
|
|
107
|
+
repo: string;
|
|
108
|
+
file: string;
|
|
109
|
+
title: string;
|
|
110
|
+
status: string;
|
|
111
|
+
waiting: boolean;
|
|
98
112
|
}
|
|
99
113
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
`<p><strong>${esc(basename(plan.file))}</strong><br>${esc(plan.waitingLine ?? "")}</p>`,
|
|
105
|
-
`<button type="submit" name="answer" value="yes">yes</button>`,
|
|
106
|
-
`<button type="submit" name="answer" value="no">no</button>`,
|
|
107
|
-
`<input type="text" name="answer_text" maxlength="${ANSWER_MAX}" placeholder="short answer">`,
|
|
108
|
-
`<button type="submit">send</button>`,
|
|
109
|
-
`</form>`,
|
|
110
|
-
].join("\n");
|
|
114
|
+
export interface CiRow {
|
|
115
|
+
mr: string;
|
|
116
|
+
tries: number;
|
|
117
|
+
ts: number;
|
|
111
118
|
}
|
|
112
119
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
120
|
+
export interface IncidentRow {
|
|
121
|
+
id: string;
|
|
122
|
+
kind: string;
|
|
123
|
+
summary: string;
|
|
124
|
+
count: number;
|
|
116
125
|
}
|
|
117
126
|
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
if (left > 0) state = `<p>guards <strong>unlocked</strong> for ~${left} more min</p>`;
|
|
124
|
-
} catch {}
|
|
125
|
-
const button = (minutes: number) =>
|
|
126
|
-
`<form method="post" action="/unlock"><input type="hidden" name="minutes" value="${minutes}"><button type="submit">unlock ${minutes}</button></form>`;
|
|
127
|
-
return [
|
|
128
|
-
state,
|
|
129
|
-
button(5),
|
|
130
|
-
button(15),
|
|
131
|
-
button(30),
|
|
132
|
-
`<form method="post" action="/lock"><button type="submit">lock now</button></form>`,
|
|
133
|
-
].join("\n");
|
|
127
|
+
/** A markdown table from the ranking board plus every non-table line, kept in order. */
|
|
128
|
+
export interface ScoresData {
|
|
129
|
+
header: string[];
|
|
130
|
+
rows: string[][];
|
|
131
|
+
text: string[];
|
|
134
132
|
}
|
|
135
133
|
|
|
136
|
-
|
|
134
|
+
export interface MachineRow {
|
|
135
|
+
freeGb: number;
|
|
136
|
+
diskMin: number;
|
|
137
|
+
load: number;
|
|
138
|
+
loadMax: number;
|
|
139
|
+
cores: number;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function questionRows(cfg: Config): QuestionRow[] {
|
|
143
|
+
const now = Date.now();
|
|
144
|
+
return activePlans(cfg.paths.queue_index)
|
|
145
|
+
.filter(p => p.waiting && p.status === "open" && p.waitingLine)
|
|
146
|
+
.map(p => {
|
|
147
|
+
let waitingMin = 0;
|
|
148
|
+
try {
|
|
149
|
+
waitingMin = Math.max(0, Math.round((now - statSync(p.file).mtimeMs) / 60_000));
|
|
150
|
+
} catch {}
|
|
151
|
+
return {
|
|
152
|
+
plan: p.file,
|
|
153
|
+
title: p.title,
|
|
154
|
+
repo: basename(p.repo),
|
|
155
|
+
waitingLine: p.waitingLine ?? "",
|
|
156
|
+
goal: p.goal,
|
|
157
|
+
waitingMin,
|
|
158
|
+
};
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function agentRows(cfg: Config, source: RunSource): AgentRow[] {
|
|
137
163
|
const cut = nowSec() - cfg.ledger.default_hours * 3600;
|
|
138
|
-
|
|
164
|
+
return source
|
|
139
165
|
.listRuns(cut)
|
|
140
166
|
.filter(r => r.status === "running" || r.status === "waiting")
|
|
141
|
-
.map(r =>
|
|
142
|
-
|
|
167
|
+
.map(r => ({
|
|
168
|
+
id: r.id,
|
|
169
|
+
model: r.model.slice(r.model.lastIndexOf("/") + 1),
|
|
170
|
+
detail: r.statusDetail,
|
|
171
|
+
minutes: r.startedAt === null ? 0 : Math.max(0, Math.round((nowSec() - r.startedAt) / 60)),
|
|
172
|
+
status: r.status,
|
|
173
|
+
}));
|
|
143
174
|
}
|
|
144
175
|
|
|
145
|
-
function
|
|
146
|
-
|
|
147
|
-
p =>
|
|
148
|
-
|
|
149
|
-
return plans.length ? `<pre>${esc(plans.join("\n"))}</pre>` : "<p>the queue is empty</p>";
|
|
176
|
+
export function queueRows(cfg: Config): QueueRow[] {
|
|
177
|
+
return activePlans(cfg.paths.queue_index)
|
|
178
|
+
.filter(p => p.status === "open")
|
|
179
|
+
.map(p => ({ repo: basename(p.repo), file: p.file, title: p.title, status: p.status ?? "?", waiting: p.waiting }));
|
|
150
180
|
}
|
|
151
181
|
|
|
152
|
-
function
|
|
153
|
-
|
|
182
|
+
export function ciRows(cfg: Config): CiRow[] {
|
|
183
|
+
return readMetricEvents(cfg)
|
|
154
184
|
.filter(e => e.type === "ci")
|
|
155
185
|
.slice(-10)
|
|
156
186
|
.reverse()
|
|
157
|
-
.map(e =>
|
|
158
|
-
return rows.length ? `<pre>${esc(rows.join("\n"))}</pre>` : "<p>no CI runs recorded</p>";
|
|
187
|
+
.map(e => ({ mr: String(e.mr), tries: Number(e.tries), ts: Number(e.ts) }));
|
|
159
188
|
}
|
|
160
189
|
|
|
161
|
-
function
|
|
162
|
-
|
|
163
|
-
return open.length ? `<pre>${esc(open.join("\n"))}</pre>` : "<p>no open incidents</p>";
|
|
190
|
+
export function incidentRows(cfg: Config): IncidentRow[] {
|
|
191
|
+
return openIncidents(cfg).map(i => ({ id: i.id, kind: i.kind, summary: i.summary, count: i.count }));
|
|
164
192
|
}
|
|
165
193
|
|
|
166
|
-
function
|
|
167
|
-
|
|
194
|
+
export function scoresData(cfg: Config): ScoresData {
|
|
195
|
+
const out: ScoresData = { header: [], rows: [], text: [] };
|
|
196
|
+
for (const raw of readFileSync(cfg.paths.ranking_board, "utf8").split("\n")) {
|
|
197
|
+
const line = raw.trim();
|
|
198
|
+
if (line.startsWith("|") && line.endsWith("|")) {
|
|
199
|
+
const cells = line.slice(1, -1).split("|").map(c => c.trim());
|
|
200
|
+
if (cells.every(c => /^:?-{2,}:?$/.test(c))) continue;
|
|
201
|
+
if (!out.header.length) out.header = cells;
|
|
202
|
+
else out.rows.push(cells);
|
|
203
|
+
} else if (line) {
|
|
204
|
+
out.text.push(line);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return out;
|
|
168
208
|
}
|
|
169
209
|
|
|
170
|
-
function
|
|
210
|
+
export function machineRow(cfg: Config): MachineRow {
|
|
171
211
|
const st = statfsSync(expandHome(cfg.machine.disk_path));
|
|
172
212
|
const freeGb = (Number(st.bavail) * Number(st.bsize)) / 1e9;
|
|
173
213
|
const load = os.loadavg()[0] ?? 0;
|
|
174
214
|
const cores = cpuCount();
|
|
175
215
|
const loadMax = cfg.machine.load_max > 0 ? cfg.machine.load_max : cores + cfg.machine.load_over_cores;
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
216
|
+
return { freeGb, diskMin: cfg.machine.disk_min_gb, load, loadMax, cores };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ---- rendering (consumes the rows above, never the readers directly) ----
|
|
220
|
+
|
|
221
|
+
function needCard(row: QuestionRow, i: number): string {
|
|
222
|
+
const goals = row.goal.map(g => `<li>${esc(g)}</li>`).join("");
|
|
223
|
+
const wait = row.waitingMin < 60 ? `waiting ${row.waitingMin} min` : `waiting ${Math.max(1, Math.round(row.waitingMin / 60))} h`;
|
|
224
|
+
const bg = row.goal.length ? `<details class="bg" id="bg-${i}"><summary>Background</summary><ul>${goals}</ul></details>` : "";
|
|
225
|
+
return `<article class="card need">
|
|
226
|
+
<p class="eyebrow">${esc(row.repo)} · ${esc(wait)}</p>
|
|
227
|
+
<h3>${esc(row.title)}</h3>
|
|
228
|
+
<p class="ask">What I need from you</p>
|
|
229
|
+
<p class="q">${esc(row.waitingLine)}</p>
|
|
230
|
+
${bg}
|
|
231
|
+
<form method="post" action="/answer">
|
|
232
|
+
<input type="hidden" name="plan" value="${esc(row.plan)}">
|
|
233
|
+
<div class="acts">
|
|
234
|
+
<button class="primary" type="submit" name="answer" value="yes">Yes, go ahead</button>
|
|
235
|
+
<button type="submit" name="answer" value="no">No</button>
|
|
236
|
+
<button type="button" class="replybtn">Reply…</button>
|
|
237
|
+
</div>
|
|
238
|
+
<div class="reply" hidden>
|
|
239
|
+
<textarea name="answer_text" maxlength="${ANSWER_MAX}" rows="3" placeholder="Type your reply"></textarea>
|
|
240
|
+
<button class="primary" type="submit">Send reply</button>
|
|
241
|
+
</div>
|
|
242
|
+
</form>
|
|
243
|
+
</article>`;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function agentRowHtml(r: AgentRow): string {
|
|
247
|
+
const dot = r.status === "running" ? "ok" : "warn";
|
|
248
|
+
const mins = r.minutes > 0 ? ` · ${r.minutes} min` : "";
|
|
249
|
+
return `<li class="agent"><span class="dot ${dot}" aria-hidden="true"></span><span class="aid">${esc(r.id)}</span><span class="model">${esc(r.model)}</span><span class="detail">${esc(r.detail)}${mins}</span></li>`;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function queueHtml(rows: QueueRow[]): string {
|
|
253
|
+
const cards = rows
|
|
254
|
+
.map(
|
|
255
|
+
(r, i) => `<li class="qcard" data-plan="${esc(r.file)}">
|
|
256
|
+
<span class="qrank">${i + 1}</span>
|
|
257
|
+
<span class="qhandle" title="Drag to reorder" aria-label="Drag ${esc(r.title)}">⠿</span>
|
|
258
|
+
<span class="qtitle">${esc(r.title)}</span>
|
|
259
|
+
<span class="chip repo">${esc(r.repo)}</span>
|
|
260
|
+
${r.waiting ? `<span class="chip wait">waiting</span>` : ""}
|
|
261
|
+
<span class="qbtns"><button type="button" class="qmove" data-move="top">↑ top</button><button type="button" class="qmove" data-move="up">↑</button><button type="button" class="qmove" data-move="down">↓</button></span>
|
|
262
|
+
</li>`,
|
|
263
|
+
)
|
|
264
|
+
.join("\n");
|
|
265
|
+
// before = the order this page was rendered with; the server refuses the move when the real
|
|
266
|
+
// order has drifted (409), so a stale page can never reorder on a guess.
|
|
267
|
+
const before = rows.map(r => r.file).join("\n");
|
|
268
|
+
return `<ul class="qlist" id="qlist">
|
|
269
|
+
${cards}
|
|
270
|
+
</ul>
|
|
271
|
+
<form id="reorder-form" method="post" action="/reorder" hidden>
|
|
272
|
+
<input type="hidden" name="before" value="${esc(before)}">
|
|
273
|
+
<input type="hidden" name="order" value="">
|
|
274
|
+
<input type="hidden" name="moved" value="">
|
|
275
|
+
</form>`;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function ciHtml(rows: CiRow[]): string {
|
|
279
|
+
return `<ul class="merges">${rows
|
|
280
|
+
.map(r => `<li><span class="mono">${esc(r.mr)}</span> · ${r.tries} pipeline${r.tries === 1 ? "" : "s"} · ${esc(strftime(r.ts, "%m-%d %H:%M"))}</li>`)
|
|
281
|
+
.join("")}</ul>`;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function incidentsHtml(rows: IncidentRow[]): string {
|
|
285
|
+
return `<ul class="incidents">${rows
|
|
286
|
+
.map(r => `<li><span class="mono">${esc(r.id)}</span> <span class="chip bad">${esc(r.kind)}</span> ${esc(r.summary)}${r.count > 1 ? ` · ${r.count}x` : ""}</li>`)
|
|
287
|
+
.join("")}</ul>`;
|
|
179
288
|
}
|
|
180
289
|
|
|
181
|
-
function
|
|
290
|
+
function scoresHtml(d: ScoresData): string {
|
|
291
|
+
const head = d.header.length ? `<thead><tr>${d.header.map(c => `<th>${esc(c)}</th>`).join("")}</tr></thead>` : "";
|
|
292
|
+
const body = d.rows.length ? `<tbody>${d.rows.map(r => `<tr>${r.map(c => `<td>${esc(c)}</td>`).join("")}</tr>`).join("")}</tbody>` : "";
|
|
293
|
+
const table = head ? `<table>${head}${body}</table>` : "";
|
|
294
|
+
const text = d.text.map(t => `<p>${esc(t)}</p>`).join("");
|
|
295
|
+
return table + text;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function machineHtml(cfg: Config, m: MachineRow): string {
|
|
299
|
+
const row = (label: string, value: string, bad = false) =>
|
|
300
|
+
`<div class="mrow"><span>${esc(label)}</span><span class="mono${bad ? " bad" : ""}">${esc(value)}</span></div>`;
|
|
182
301
|
return [
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
302
|
+
row("Disk free", `${m.freeGb.toFixed(0)} GB (min ${m.diskMin} GB)`, m.freeGb < m.diskMin),
|
|
303
|
+
row("Load", `${m.load.toFixed(2)} (max ${m.loadMax})`, m.load > m.loadMax),
|
|
304
|
+
row("Cores", String(m.cores)),
|
|
305
|
+
].join("");
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function detailsBlock(id: string, label: string, count: string, inner: string): string {
|
|
309
|
+
return `<details id="${id}"><summary>${esc(label)} <span class="chip">${esc(count)}</span></summary><div class="dbody">${inner}</div></details>`;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function na(label: string): string {
|
|
313
|
+
return `<p class="na">${esc(label)} unavailable</p>`;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function receiptHtml(sent: string | null, params: URLSearchParams): string {
|
|
317
|
+
if (!sent) return "";
|
|
318
|
+
let text: string;
|
|
319
|
+
switch (sent) {
|
|
320
|
+
case "answer":
|
|
321
|
+
text = `Sent to Main · ${strftime(nowSec(), "%H:%M")}`;
|
|
322
|
+
break;
|
|
323
|
+
case "unlock": {
|
|
324
|
+
const minutes = Number(params.get("minutes"));
|
|
325
|
+
text = Number.isInteger(minutes) && minutes > 0 ? `Unlocked for ${minutes} min` : "Unlocked";
|
|
326
|
+
break;
|
|
327
|
+
}
|
|
328
|
+
case "lock":
|
|
329
|
+
text = "Locked";
|
|
330
|
+
break;
|
|
331
|
+
case "reorder": {
|
|
332
|
+
const to = Number(params.get("to"));
|
|
333
|
+
text = Number.isInteger(to) && to > 0 ? `Moved to #${to} · Main sees it next turn` : "Moved · Main sees it next turn";
|
|
334
|
+
break;
|
|
335
|
+
}
|
|
336
|
+
case "unlock-off":
|
|
337
|
+
text = "Refused — chat unlock is off";
|
|
338
|
+
break;
|
|
339
|
+
default:
|
|
340
|
+
return "";
|
|
341
|
+
}
|
|
342
|
+
return `<div class="receipt" role="status">${esc(text)}</div>`;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function bottomBar(cfg: Config, lockMinutesLeft: number | null): string {
|
|
346
|
+
const state = lockMinutesLeft === null ? "Locked" : `Unlocked · ${lockMinutesLeft} min left`;
|
|
347
|
+
const unlockBtn = (minutes: number) =>
|
|
348
|
+
`<form method="post" action="/unlock"><input type="hidden" name="minutes" value="${minutes}"><button type="submit">Unlock ${minutes} min</button></form>`;
|
|
349
|
+
const off = cfg.guards.chat_unlock
|
|
350
|
+
? ""
|
|
351
|
+
: `<p class="offnote">Unlocking from the page is switched off in the config. To turn it on, set:</p><code class="offcfg">guards: chat_unlock: true</code>`;
|
|
352
|
+
return `<footer class="bar"><div class="barline"><div class="barinner"><p class="lockstate${lockMinutesLeft === null ? "" : " on"}">${esc(state)}</p><div class="barbtns">${unlockBtn(15)}${unlockBtn(30)}<form method="post" action="/lock"><button type="submit">Lock now</button></form></div></div></div>${off}</footer>`;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// ---- page assembly: one unreadable source never takes the page down ----
|
|
356
|
+
|
|
357
|
+
export interface PageData {
|
|
358
|
+
questions: QuestionRow[] | null;
|
|
359
|
+
agents: AgentRow[] | null;
|
|
360
|
+
queue: QueueRow[] | null;
|
|
361
|
+
ci: CiRow[] | null;
|
|
362
|
+
incidents: IncidentRow[] | null;
|
|
363
|
+
scores: ScoresData | null;
|
|
364
|
+
machine: MachineRow | null;
|
|
365
|
+
/** Minutes left in the guard unlock; null = locked. */
|
|
366
|
+
lockMinutesLeft: number | null;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function safe<T>(build: () => T): T | null {
|
|
370
|
+
try {
|
|
371
|
+
return build();
|
|
372
|
+
} catch {
|
|
373
|
+
// One unreadable source must never take the page down.
|
|
374
|
+
return null;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function lockMinutesLeft(cfg: Config): number | null {
|
|
379
|
+
try {
|
|
380
|
+
const end = statSync(unlockPath()).mtimeMs + cfg.guards.unlock_minutes * 60_000;
|
|
381
|
+
const left = Math.round((end - Date.now()) / 60_000);
|
|
382
|
+
return left > 0 ? left : null;
|
|
383
|
+
} catch {
|
|
384
|
+
return null;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
export function buildPageData(cfg: Config, source: RunSource): PageData {
|
|
389
|
+
return {
|
|
390
|
+
questions: safe(() => questionRows(cfg)),
|
|
391
|
+
agents: safe(() => agentRows(cfg, source)),
|
|
392
|
+
queue: safe(() => queueRows(cfg)),
|
|
393
|
+
ci: safe(() => ciRows(cfg)),
|
|
394
|
+
incidents: safe(() => incidentRows(cfg)),
|
|
395
|
+
scores: safe(() => scoresData(cfg)),
|
|
396
|
+
machine: safe(() => machineRow(cfg)),
|
|
397
|
+
lockMinutesLeft: lockMinutesLeft(cfg),
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function stripHtml(data: PageData): string {
|
|
402
|
+
const n = data.questions?.length ?? null;
|
|
403
|
+
const left =
|
|
404
|
+
n === null
|
|
405
|
+
? `<span class="count na">–</span>`
|
|
406
|
+
: n === 0
|
|
407
|
+
? `<span class="count clear">All clear</span>`
|
|
408
|
+
: `<a class="count" href="#needs" aria-label="${n} plans need you">${n}</a>`;
|
|
409
|
+
const working = data.agents === null ? "working –" : `${data.agents.length} working`;
|
|
410
|
+
const ci =
|
|
411
|
+
data.incidents === null
|
|
412
|
+
? "CI –"
|
|
413
|
+
: data.incidents.length
|
|
414
|
+
? `<span class="bad">${data.incidents.length === 1 ? "1 incident" : `${data.incidents.length} incidents`}</span>`
|
|
415
|
+
: `<span class="fine">CI ok</span>`;
|
|
416
|
+
const m = data.machine;
|
|
417
|
+
const disk =
|
|
418
|
+
m === null
|
|
419
|
+
? "disk –"
|
|
420
|
+
: m.freeGb < m.diskMin
|
|
421
|
+
? `<span class="bad">disk ${m.freeGb.toFixed(0)} GB</span>`
|
|
422
|
+
: m.load > m.loadMax
|
|
423
|
+
? `<span class="bad">load ${m.load.toFixed(1)}</span>`
|
|
424
|
+
: `disk ${m.freeGb.toFixed(0)} GB`;
|
|
425
|
+
return `<header class="strip"><div class="barinner stripinner">${left}<div class="signals"><span>${esc(working)}</span><span>${ci}</span><span>${disk}</span></div></div></header>`;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const FAVICON =
|
|
429
|
+
"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' rx='4' fill='%23D98E04'/%3E%3C/svg%3E";
|
|
430
|
+
|
|
431
|
+
const SCRIPT = `(function(){
|
|
432
|
+
if(location.search)history.replaceState(null,"",location.pathname);
|
|
433
|
+
function store(d,v){var k="nsui:"+d.id;if(v===undefined)return sessionStorage.getItem(k);sessionStorage.setItem(k,v?"1":"0");}
|
|
434
|
+
var ds=document.querySelectorAll("details[id]");
|
|
435
|
+
for(var i=0;i<ds.length;i++){(function(d){var s=store(d);if(s!==null)d.open=s==="1";d.addEventListener("toggle",function(){store(d,d.open);});})(ds[i]);}
|
|
436
|
+
var rb=document.querySelectorAll(".replybtn");
|
|
437
|
+
for(var j=0;j<rb.length;j++){rb[j].addEventListener("click",function(){var f=this.closest("form");var box=f&&f.querySelector(".reply");if(box){box.hidden=!box.hidden;if(!box.hidden){var t=box.querySelector("textarea");if(t)t.focus();}}});}
|
|
438
|
+
var qlist=document.getElementById("qlist");
|
|
439
|
+
var dragging=false;
|
|
440
|
+
if(qlist){
|
|
441
|
+
var rform=document.getElementById("reorder-form");
|
|
442
|
+
var qcards=function(){return Array.prototype.slice.call(qlist.querySelectorAll(".qcard"));};
|
|
443
|
+
var submitReorder=function(moved){if(!rform)return;var o=qcards().map(function(c){return c.getAttribute("data-plan");}).join("\\n");rform.querySelector("[name=order]").value=o;rform.querySelector("[name=moved]").value=moved;dragging=false;rform.submit();};
|
|
444
|
+
var moveCard=function(card,how){if(how==="top"){var f=qcards()[0];if(f&&f!==card)qlist.insertBefore(card,f);}else if(how==="up"){var p=card.previousElementSibling;if(p&&p.classList.contains("qcard"))qlist.insertBefore(card,p);}else if(how==="down"){var n=card.nextElementSibling;if(n&&n.classList.contains("qcard"))qlist.insertBefore(card,n.nextSibling);}};
|
|
445
|
+
qlist.addEventListener("click",function(e){var t=e.target;if(!t||!t.closest)return;var b=t.closest(".qmove");if(!b)return;var card=t.closest(".qcard");if(!card)return;moveCard(card,b.getAttribute("data-move"));submitReorder(card.getAttribute("data-plan"));});
|
|
446
|
+
var drag=null;
|
|
447
|
+
qlist.addEventListener("pointerdown",function(e){var t=e.target;if(!t||!t.closest)return;var h=t.closest(".qhandle");if(!h||drag)return;var card=t.closest(".qcard");if(!card)return;e.preventDefault();dragging=true;var r=card.getBoundingClientRect();var ph=document.createElement("li");ph.className="qph";ph.style.height=r.height+"px";qlist.insertBefore(ph,card);card.classList.add("dragging");card.style.width=r.width+"px";card.style.left=r.left+"px";card.style.top=r.top+"px";drag={card:card,ph:ph,y0:e.clientY,id:e.pointerId};try{h.setPointerCapture(e.pointerId);}catch(_){}});
|
|
448
|
+
window.addEventListener("pointermove",function(e){if(!drag||e.pointerId!==drag.id)return;var card=drag.card;card.style.transform="translateY("+(e.clientY-drag.y0)+"px)";var r=card.getBoundingClientRect();var mid=r.top+r.height/2;var els=Array.prototype.slice.call(qlist.children);for(var i=0;i<els.length;i++){var el=els[i];if(el===card||el===drag.ph)continue;var er=el.getBoundingClientRect();if(mid<er.top+er.height/2){if(el.previousElementSibling!==drag.ph)qlist.insertBefore(drag.ph,el);}else if(el.nextElementSibling!==drag.ph){qlist.insertBefore(drag.ph,el.nextSibling);}}});
|
|
449
|
+
var endDrag=function(e,submitIt){if(!drag||(e&&e.pointerId!==undefined&&e.pointerId!==drag.id))return;var card=drag.card,ph=drag.ph;card.classList.remove("dragging");card.style.transform="";card.style.width="";card.style.left="";card.style.top="";qlist.insertBefore(card,ph);qlist.removeChild(ph);drag=null;if(submitIt)submitReorder(card.getAttribute("data-plan"));else dragging=false;};
|
|
450
|
+
window.addEventListener("pointerup",function(e){endDrag(e,true);});
|
|
451
|
+
window.addEventListener("pointercancel",function(e){endDrag(e,false);});
|
|
452
|
+
}
|
|
453
|
+
function busy(){if(dragging)return true;var els=document.querySelectorAll("input:not([type=hidden]), textarea");for(var k=0;k<els.length;k++){if(els[k]===document.activeElement||els[k].value)return true;}return false;}
|
|
454
|
+
setInterval(function(){if(!busy())location.reload();},${REFRESH_SEC}000);
|
|
455
|
+
})();`;
|
|
456
|
+
|
|
457
|
+
/** The whole page as one HTML string. Exported for scripts/ui-preview.ts (no server). */
|
|
458
|
+
export function renderPage(cfg: Config, data: PageData, params: URLSearchParams, nonce: string): string {
|
|
459
|
+
const needs = data.questions === null ? na("Waiting on you") : data.questions.length ? data.questions.map(needCard).join("\n") : `<p class="empty">Nothing needs you right now</p>`;
|
|
460
|
+
const working =
|
|
461
|
+
data.agents === null ? na("Working now") : data.agents.length ? `<ul class="agents">${data.agents.map(agentRowHtml).join("")}</ul>` : `<p class="empty">No agents running</p>`;
|
|
462
|
+
const queue = detailsBlock(
|
|
463
|
+
"d-queue",
|
|
464
|
+
"Queue",
|
|
465
|
+
data.queue === null ? "–" : String(data.queue.length),
|
|
466
|
+
data.queue === null ? na("Queue") : data.queue.length ? queueHtml(data.queue) : `<p class="empty">The queue is empty</p>`,
|
|
467
|
+
);
|
|
468
|
+
const merges = detailsBlock(
|
|
469
|
+
"d-merges",
|
|
470
|
+
"Merges",
|
|
471
|
+
data.ci === null ? "–" : String(data.ci.length),
|
|
472
|
+
data.ci === null ? na("Merges") : data.ci.length ? ciHtml(data.ci) : `<p class="empty">No CI runs recorded</p>`,
|
|
473
|
+
);
|
|
474
|
+
const incidents = detailsBlock(
|
|
475
|
+
"d-incidents",
|
|
476
|
+
"Incidents",
|
|
477
|
+
data.incidents === null ? "–" : String(data.incidents.length),
|
|
478
|
+
data.incidents === null ? na("Incidents") : data.incidents.length ? incidentsHtml(data.incidents) : `<p class="empty">No open incidents</p>`,
|
|
479
|
+
);
|
|
480
|
+
const scores = detailsBlock(
|
|
481
|
+
"d-scores",
|
|
482
|
+
"Agent scores",
|
|
483
|
+
data.scores === null ? "–" : String(data.scores.rows.length + data.scores.text.length),
|
|
484
|
+
data.scores === null ? na("Agent scores") : scoresHtml(data.scores),
|
|
485
|
+
);
|
|
486
|
+
const machine = detailsBlock(
|
|
487
|
+
"d-machine",
|
|
488
|
+
"Machine",
|
|
489
|
+
data.machine === null ? "–" : `${data.machine.freeGb.toFixed(0)} GB`,
|
|
490
|
+
data.machine === null ? na("Machine") : machineHtml(cfg, data.machine),
|
|
491
|
+
);
|
|
196
492
|
return `<!doctype html>
|
|
197
493
|
<html lang="en">
|
|
198
494
|
<head>
|
|
199
495
|
<meta charset="utf-8">
|
|
200
496
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
201
|
-
<meta
|
|
497
|
+
<meta name="color-scheme" content="light dark">
|
|
202
498
|
<title>neurastream</title>
|
|
499
|
+
<link rel="icon" href="${FAVICON}">
|
|
203
500
|
<style>
|
|
204
|
-
:root { color-scheme: light dark; }
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
501
|
+
:root { color-scheme: light dark; --ink:#1C2430; --page:#EEF1F5; --card:#FFFFFF; --line:#D5DBE3; --muted:#5E6A7A; --amber:#D98E04; --teal:#0F8A8A; --red:#C8382F; --on-amber:#10141A; }
|
|
502
|
+
@media (prefers-color-scheme: dark) { :root { --ink:#E6EAF0; --page:#10141A; --card:#1A2029; --line:#2A323D; --muted:#94A0B0; } }
|
|
503
|
+
* { box-sizing: border-box; }
|
|
504
|
+
html { scroll-padding-top: 72px; }
|
|
505
|
+
body { margin: 0; background: var(--page); color: var(--ink); font: 17px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
|
|
506
|
+
.barinner { max-width: 36rem; margin: 0 auto; padding: 0 16px; }
|
|
507
|
+
.mono, .aid, .model { font-family: ui-monospace, "SF Mono", "Roboto Mono", monospace; font-size: 14px; }
|
|
508
|
+
.strip { position: sticky; top: 0; z-index: 5; background: var(--page); border-bottom: 1px solid var(--line); }
|
|
509
|
+
.stripinner { display: flex; align-items: center; justify-content: space-between; min-height: 64px; }
|
|
510
|
+
.count { color: var(--amber); font-size: 34px; font-weight: 800; font-variant-numeric: tabular-nums; text-decoration: none; }
|
|
511
|
+
.count.clear { color: var(--teal); font-size: 20px; font-weight: 700; }
|
|
512
|
+
.count.na { color: var(--muted); font-size: 20px; }
|
|
513
|
+
.signals { display: flex; gap: 12px; color: var(--muted); font-size: 14px; text-align: right; }
|
|
514
|
+
.bad { color: var(--red); font-weight: 600; }
|
|
515
|
+
.fine { color: var(--teal); }
|
|
516
|
+
main { padding-bottom: 96px; }
|
|
517
|
+
.receipt { max-width: 36rem; margin: 12px auto 0; padding: 10px 16px; background: var(--card); border: 1px solid var(--teal); border-radius: 14px; color: var(--teal); font-weight: 600; }
|
|
518
|
+
.card { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 14px 16px; margin: 16px 0; }
|
|
519
|
+
.need { border-left: 4px solid var(--amber); }
|
|
520
|
+
.eyebrow { margin: 0 0 2px; color: var(--muted); font-size: 14px; }
|
|
521
|
+
.need .eyebrow { color: var(--amber); }
|
|
522
|
+
.card h3 { margin: 2px 0 8px; font-size: 20px; font-weight: 650; }
|
|
523
|
+
.ask { margin: 0 0 2px; color: var(--muted); font-size: 14px; }
|
|
524
|
+
.q { margin: 0 0 10px; }
|
|
525
|
+
details.bg { margin: 8px 0; border-top: 1px solid var(--line); padding-top: 6px; }
|
|
526
|
+
details.bg summary, details.block summary { min-height: 48px; display: flex; align-items: center; gap: 8px; color: var(--muted); }
|
|
527
|
+
details.bg ul { margin: 4px 0 8px; padding-left: 20px; }
|
|
528
|
+
.acts { display: flex; gap: 8px; flex-wrap: wrap; }
|
|
529
|
+
button { min-height: 48px; padding: 8px 14px; border-radius: 10px; border: 1px solid var(--line); background: var(--card); color: var(--ink); font: inherit; }
|
|
530
|
+
button.primary { background: var(--amber); border-color: var(--amber); color: var(--on-amber); font-weight: 650; }
|
|
531
|
+
:focus-visible { outline: 2px solid var(--amber); outline-offset: 2px; }
|
|
532
|
+
.reply { margin-top: 8px; }
|
|
533
|
+
.reply textarea { width: 100%; padding: 10px; border-radius: 10px; border: 1px solid var(--line); background: var(--page); color: var(--ink); font: inherit; }
|
|
534
|
+
.agents { list-style: none; margin: 0; padding: 0; }
|
|
535
|
+
.agent { display: flex; align-items: baseline; gap: 8px; padding: 8px 0; border-bottom: 1px solid var(--line); flex-wrap: wrap; }
|
|
536
|
+
.agent:last-child { border-bottom: none; }
|
|
537
|
+
.dot { width: 10px; height: 10px; border-radius: 50%; align-self: center; flex: none; }
|
|
538
|
+
.dot.ok { background: var(--teal); }
|
|
539
|
+
.dot.warn { background: var(--amber); }
|
|
540
|
+
.model { color: var(--muted); }
|
|
541
|
+
.detail { color: var(--muted); }
|
|
542
|
+
details.block { background: var(--card); border: 1px solid var(--line); border-radius: 14px; padding: 4px 16px; margin: 12px 0; }
|
|
543
|
+
details.block .dbody { border-top: 1px solid var(--line); padding: 10px 0 12px; }
|
|
544
|
+
.chip { display: inline-block; padding: 1px 8px; border: 1px solid var(--line); border-radius: 999px; font-size: 13px; color: var(--muted); }
|
|
545
|
+
.chip.bad { color: var(--red); border-color: var(--red); }
|
|
546
|
+
.chip.wait { color: var(--amber); border-color: var(--amber); }
|
|
547
|
+
.qlist { list-style: none; margin: 0; padding: 0; }
|
|
548
|
+
.qcard { display: flex; align-items: center; gap: 8px; padding: 8px 0; border-bottom: 1px solid var(--line); flex-wrap: wrap; }
|
|
549
|
+
.qcard:last-child { border-bottom: none; }
|
|
550
|
+
.qcard.dragging { position: fixed; z-index: 20; background: var(--card); border: 1px solid var(--amber); border-radius: 14px; padding: 10px 12px; margin: 0; user-select: none; opacity: 0.96; }
|
|
551
|
+
.qph { list-style: none; border: 2px dashed var(--line); border-radius: 14px; margin: 4px 0; }
|
|
552
|
+
.qrank { font-family: ui-monospace, "SF Mono", "Roboto Mono", monospace; font-size: 14px; color: var(--muted); min-width: 1.6em; text-align: right; font-variant-numeric: tabular-nums; }
|
|
553
|
+
.qhandle { touch-action: none; padding: 12px 10px; color: var(--muted); font-size: 18px; user-select: none; }
|
|
554
|
+
.qtitle { flex: 1 1 12em; min-width: 0; }
|
|
555
|
+
.chip.repo { color: var(--teal); border-color: var(--teal); }
|
|
556
|
+
.qbtns { display: flex; gap: 6px; flex-wrap: wrap; margin-left: auto; }
|
|
557
|
+
.qbtns button { min-height: 48px; padding: 4px 10px; font-size: 14px; }
|
|
558
|
+
.merges, .incidents { margin: 0; padding-left: 20px; }
|
|
559
|
+
.merges li, .incidents li { margin: 6px 0; }
|
|
560
|
+
table { border-collapse: collapse; width: 100%; font-size: 14px; }
|
|
561
|
+
th, td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); font-variant-numeric: tabular-nums; }
|
|
562
|
+
th { color: var(--muted); font-weight: 600; }
|
|
563
|
+
.mrow { display: flex; justify-content: space-between; gap: 12px; padding: 6px 0; border-bottom: 1px solid var(--line); }
|
|
564
|
+
.mrow:last-child { border-bottom: none; }
|
|
565
|
+
.empty { color: var(--muted); }
|
|
566
|
+
.na { color: var(--muted); font-style: italic; }
|
|
567
|
+
.bar { position: sticky; bottom: 0; z-index: 5; background: var(--page); border-top: 1px solid var(--line); padding-bottom: env(safe-area-inset-bottom); }
|
|
568
|
+
.barline { display: flex; align-items: center; justify-content: space-between; gap: 12px; min-height: 64px; flex-wrap: wrap; padding-top: 6px; padding-bottom: 6px; }
|
|
569
|
+
.lockstate { margin: 0; font-weight: 650; color: var(--muted); }
|
|
570
|
+
.lockstate.on { color: var(--teal); }
|
|
571
|
+
.barbtns { display: flex; gap: 8px; flex-wrap: wrap; }
|
|
572
|
+
.barbtns button { min-height: 40px; padding: 6px 10px; font-size: 15px; }
|
|
573
|
+
.offnote { margin: 0; color: var(--muted); font-size: 14px; }
|
|
574
|
+
.offcfg { display: block; font-family: ui-monospace, "SF Mono", "Roboto Mono", monospace; font-size: 14px; padding: 4px 0 10px; }
|
|
575
|
+
@media (max-width: 360px) { .signals { display: none; } }
|
|
214
576
|
</style>
|
|
215
577
|
</head>
|
|
216
578
|
<body>
|
|
217
|
-
${
|
|
579
|
+
${stripHtml(data)}
|
|
580
|
+
${receiptHtml(params.get("sent"), params)}
|
|
581
|
+
<main>
|
|
582
|
+
<section id="needs"><h2 class="srt">Needs you</h2>
|
|
583
|
+
${needs}
|
|
584
|
+
</section>
|
|
585
|
+
<section id="working"><h2 class="srt">Working now</h2>
|
|
586
|
+
${working}
|
|
587
|
+
</section>
|
|
588
|
+
<div class="barinner">
|
|
589
|
+
${queue}
|
|
590
|
+
${merges}
|
|
591
|
+
${incidents}
|
|
592
|
+
${scores}
|
|
593
|
+
${machine}
|
|
594
|
+
</div>
|
|
595
|
+
</main>
|
|
596
|
+
${bottomBar(cfg, data.lockMinutesLeft)}
|
|
597
|
+
<script nonce="${nonce}">${SCRIPT}</script>
|
|
218
598
|
</body>
|
|
219
599
|
</html>`;
|
|
220
600
|
}
|
|
@@ -236,8 +616,8 @@ function textRes(body: string, status: number): Response {
|
|
|
236
616
|
return new Response(`${body}\n`, { status, headers: { "content-type": "text/plain; charset=utf-8" } });
|
|
237
617
|
}
|
|
238
618
|
|
|
239
|
-
function redirect(): Response {
|
|
240
|
-
return new Response(null, { status: 303, headers: { location:
|
|
619
|
+
function redirect(target: string): Response {
|
|
620
|
+
return new Response(null, { status: 303, headers: { location: target } });
|
|
241
621
|
}
|
|
242
622
|
|
|
243
623
|
function handleAnswer(cfg: Config, fields: Record<string, string>, login: string): Response {
|
|
@@ -251,28 +631,127 @@ function handleAnswer(cfg: Config, fields: Record<string, string>, login: string
|
|
|
251
631
|
}
|
|
252
632
|
mkdirSync(stateDirPath(), { recursive: true });
|
|
253
633
|
appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), plan: planFile, question: plan.waitingLine, answer, login })}\n`);
|
|
254
|
-
return redirect();
|
|
634
|
+
return redirect("/?sent=answer");
|
|
255
635
|
}
|
|
256
636
|
|
|
257
637
|
function handleUnlock(cfg: Config, fields: Record<string, string>, login: string): Response {
|
|
258
638
|
const minutes = fields.minutes ?? "";
|
|
259
639
|
if (minutes !== "" && !/^\d+$/.test(minutes)) return textRes("minutes must be a number", 400);
|
|
260
640
|
const result = chatUnlock(minutes === "" ? "unlock" : `unlock ${minutes}`, cfg, `ui:${login}`, "ui");
|
|
261
|
-
if (!result.applied) return
|
|
641
|
+
if (!result.applied) return redirect("/?sent=unlock-off");
|
|
262
642
|
mkdirSync(stateDirPath(), { recursive: true });
|
|
263
643
|
appendFileSync(
|
|
264
644
|
inboxPath(),
|
|
265
645
|
`${JSON.stringify({ ts: nowSec(), kind: "unlock", minutes: result.minutes, until: result.until, login })}\n`,
|
|
266
646
|
);
|
|
267
|
-
return redirect();
|
|
647
|
+
return redirect(`/?sent=unlock&minutes=${result.minutes}`);
|
|
268
648
|
}
|
|
269
649
|
|
|
270
650
|
function handleLock(cfg: Config, login: string): Response {
|
|
271
651
|
const result = chatUnlock("lock", cfg, `ui:${login}`, "ui");
|
|
272
|
-
if (!result.applied) return
|
|
652
|
+
if (!result.applied) return redirect("/?sent=unlock-off");
|
|
273
653
|
mkdirSync(stateDirPath(), { recursive: true });
|
|
274
654
|
appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), kind: "lock", login })}\n`);
|
|
275
|
-
return redirect();
|
|
655
|
+
return redirect("/?sent=lock");
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// ---- queue reorder (plan P4): the owner drags a card; INDEX.md is rewritten atomically ----
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* The index text with its open-plan groups reordered: a group is a plan line plus the non-plan
|
|
662
|
+
* lines (blank or `<!--` comment) attached above it, and the open groups — the first line of
|
|
663
|
+
* each path in `openPaths`, in file order — are replaced by the groups of `order`, so every open
|
|
664
|
+
* plan moves with its comment lines while every other plan line keeps its slot (a path listed
|
|
665
|
+
* twice keeps both lines). Lines after the last plan keep the file's end. Returns null when an
|
|
666
|
+
* order path is no longer in the file.
|
|
667
|
+
*/
|
|
668
|
+
function reorderedIndexText(index: string, order: string[], openPaths: ReadonlySet<string>): string | null {
|
|
669
|
+
let text: string;
|
|
670
|
+
try {
|
|
671
|
+
text = readFileSync(index, "utf8");
|
|
672
|
+
} catch {
|
|
673
|
+
return null;
|
|
674
|
+
}
|
|
675
|
+
const groups: { path: string; lines: string[] }[] = [];
|
|
676
|
+
let pending: string[] = [];
|
|
677
|
+
for (const raw of text.split("\n")) {
|
|
678
|
+
const norm = raw
|
|
679
|
+
.trim()
|
|
680
|
+
.replace(/^[-*]\s+/, "")
|
|
681
|
+
.trim();
|
|
682
|
+
if (!norm || norm.startsWith("<!--")) {
|
|
683
|
+
pending.push(raw);
|
|
684
|
+
continue;
|
|
685
|
+
}
|
|
686
|
+
groups.push({ path: resolve(process.cwd(), expandHome(norm.replace(/`/g, ""))), lines: [...pending, raw] });
|
|
687
|
+
pending = [];
|
|
688
|
+
}
|
|
689
|
+
// The open slots in file order: the first line of each open path; a later duplicate of the
|
|
690
|
+
// same path keeps its place like a non-open line, so a path listed twice keeps both lines.
|
|
691
|
+
const byPath = new Map<string, number>();
|
|
692
|
+
const slots: number[] = [];
|
|
693
|
+
const seen = new Set<string>();
|
|
694
|
+
for (const [i, g] of groups.entries()) {
|
|
695
|
+
if (!byPath.has(g.path)) byPath.set(g.path, i);
|
|
696
|
+
if (openPaths.has(g.path) && !seen.has(g.path)) {
|
|
697
|
+
seen.add(g.path);
|
|
698
|
+
slots.push(i);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
if (slots.length !== order.length) return null;
|
|
702
|
+
const parts: string[] = [];
|
|
703
|
+
let k = 0;
|
|
704
|
+
for (let i = 0; i < groups.length; i++) {
|
|
705
|
+
if (slots[k] === i) {
|
|
706
|
+
const at = byPath.get(order[k] ?? "");
|
|
707
|
+
if (at === undefined) return null;
|
|
708
|
+
parts.push(...groups[at]!.lines);
|
|
709
|
+
k++;
|
|
710
|
+
} else {
|
|
711
|
+
parts.push(...groups[i]!.lines);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
parts.push(...pending);
|
|
715
|
+
return parts.join("\n");
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
function handleReorder(cfg: Config, fields: Record<string, string>, login: string): Response {
|
|
719
|
+
const index = cfg.paths.queue_index;
|
|
720
|
+
const order = (fields.order ?? "")
|
|
721
|
+
.split("\n")
|
|
722
|
+
.map(l => l.trim())
|
|
723
|
+
.filter(l => l.length > 0);
|
|
724
|
+
const before = (fields.before ?? "")
|
|
725
|
+
.split("\n")
|
|
726
|
+
.map(l => l.trim())
|
|
727
|
+
.filter(l => l.length > 0);
|
|
728
|
+
const moved = (fields.moved ?? "").trim();
|
|
729
|
+
// One source of truth for the reorderable set: the open plans, the same list queueRows renders.
|
|
730
|
+
const openPaths = activePlans(index)
|
|
731
|
+
.filter(p => p.status === "open")
|
|
732
|
+
.map(p => p.file);
|
|
733
|
+
if (!moved || !order.length) return textRes("order and moved are required", 400);
|
|
734
|
+
// 400: the posted order must be exactly the open plans the page renders now — no adds, drops or duplicates.
|
|
735
|
+
if (new Set(order).size !== order.length) return textRes("order lists a plan more than once", 400);
|
|
736
|
+
const sortedOrder = [...order].sort();
|
|
737
|
+
const sortedOpen = [...openPaths].sort();
|
|
738
|
+
const sameSet = order.length === openPaths.length && sortedOrder.every((p, i) => p === sortedOpen[i]);
|
|
739
|
+
if (!sameSet) return textRes("order is not exactly the plans now on the page", 400);
|
|
740
|
+
// 409: the order the page was rendered with must still be the open plans' current order.
|
|
741
|
+
const stale = before.length !== openPaths.length || before.some((p, i) => p !== openPaths[i]);
|
|
742
|
+
if (stale) return textRes("the queue changed since the page loaded — reload and drag again", 409);
|
|
743
|
+
const from = openPaths.indexOf(moved);
|
|
744
|
+
const to = order.indexOf(moved);
|
|
745
|
+
if (from === -1 || to === -1) return textRes("moved is not one of the page's plans", 400);
|
|
746
|
+
const newText = reorderedIndexText(index, order, new Set(openPaths));
|
|
747
|
+
if (newText === null) return textRes("the queue index no longer lists every open plan", 400);
|
|
748
|
+
// Atomic write: a torn INDEX.md would break every reader, so temp file in the same dir + rename.
|
|
749
|
+
const tmp = `${index}.${randomUUID().slice(0, 8)}.tmp`;
|
|
750
|
+
writeFileSync(tmp, newText);
|
|
751
|
+
renameSync(tmp, index);
|
|
752
|
+
mkdirSync(stateDirPath(), { recursive: true });
|
|
753
|
+
appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), kind: "reorder", plan: moved, from: from + 1, to: to + 1, login })}\n`);
|
|
754
|
+
return redirect(`/?sent=reorder&to=${to + 1}`);
|
|
276
755
|
}
|
|
277
756
|
|
|
278
757
|
/** Starts the page. Refuses to start when ui.enabled is false or ui.owner_login is empty, and on the default hostname when tailscale does not answer. */
|
|
@@ -322,9 +801,13 @@ export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
|
|
|
322
801
|
res = textRes("forbidden: origin is not this page", 403);
|
|
323
802
|
code = 403;
|
|
324
803
|
} else if (req.method === "GET" && url.pathname === "/") {
|
|
325
|
-
|
|
804
|
+
const nonce = randomUUID().replaceAll("-", "");
|
|
805
|
+
res = new Response(renderPage(cfg, buildPageData(cfg, source), url.searchParams, nonce), {
|
|
326
806
|
status: 200,
|
|
327
|
-
headers: {
|
|
807
|
+
headers: {
|
|
808
|
+
"content-type": "text/html; charset=utf-8",
|
|
809
|
+
"content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; img-src data:; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
|
|
810
|
+
},
|
|
328
811
|
});
|
|
329
812
|
code = 200;
|
|
330
813
|
} else if (req.method === "POST" && url.pathname === "/answer") {
|
|
@@ -336,6 +819,9 @@ export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
|
|
|
336
819
|
} else if (req.method === "POST" && url.pathname === "/lock") {
|
|
337
820
|
res = handleLock(cfg, login);
|
|
338
821
|
code = res.status;
|
|
822
|
+
} else if (req.method === "POST" && url.pathname === "/reorder") {
|
|
823
|
+
res = handleReorder(cfg, await fieldsOf(req), login);
|
|
824
|
+
code = res.status;
|
|
339
825
|
} else {
|
|
340
826
|
res = textRes("not found", 404);
|
|
341
827
|
code = 404;
|