neurastream 0.2.26 → 0.2.27
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 +1 -1
- package/package.json +1 -1
- package/src/adapters/omp/index.ts +33 -2
- package/src/core/owner-ui.ts +382 -72
package/README.md
CHANGED
|
@@ -117,7 +117,7 @@ One setting decides how much Main does without asking: `autonomy.tier` in the co
|
|
|
117
117
|
|
|
118
118
|
`neurastream ui on --login <tailscale login> [--port N]` does the whole setup in one sentence: it writes `ui.enabled: true` and `ui.owner_login` (plus `ui.port` with `--port`) into `~/.config/neurastream/config.yml` — every other line of the file is kept byte-for-byte — copies `templates/systemd/neurastream-ui.service` to `~/.config/systemd/user/neurastream-ui.service`, runs `systemctl --user daemon-reload`, `enable` and `restart`, then prints the phone link `http://<MagicDNS name>:<port>`. The login must be one the tailnet knows (`tailscale status --json`); when tailscale cannot answer, the check is skipped with a printed warning, never a refusal. `neurastream ui off` stops and disables the unit and sets `ui.enabled: false`, keeping `ui.owner_login` for the next `on`.
|
|
119
119
|
|
|
120
|
-
With `ui.enabled: true` and `ui.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream ui` serves one page bound to this machine's tailnet address only (port `ui.port`, default 7787; `templates/systemd/neurastream-ui.service` runs it as a user unit). A sticky top bar holds the "ns" logo, four pill tabs — Now, Queue, Agents, Spend, each a server-rendered view (`/?tab=…`, an unknown value falls back to Now) — and the lock pill ("🔒 Off" / "🔓 12 min") that opens the guard unlock ("Unlock 15 min", "Unlock 30 min", "Lock now"; when `guards.chat_unlock` is off it says so in plain words with the exact config line). Now is the home tab: a Today tile card over the last 24 h (needs-you count in warn color, list-price spend with a sparkline and the Main/agents split, agent runs with running/died counts and a sparkline, open plans), then one card per open `WAITING on owner:` plan — the plan's `#` title, the ask in plain words, the goal folded into a Background block, and "Yes"/"No"/"Reply…" actions whose answer shows as a one-time receipt ("Sent to Main · 08:12"); once the owner inbox already holds an answer for a plan, the card says so ("You answered ‘yes' · 14:19 — Main is on it") with a small change-answer link. The queue is one flat ranked list in `INDEX.md` order — drag a card by its ≡ handle, or tap "↑ top"/"↑"/"↓"; the drop rewrites `INDEX.md`, Main gets the move as a message and the page confirms "Moved to #2" — shown on Now as the first 8 rows with a "Show all N ›" link to the Queue tab. The Agents tab lists working-now rows, the agent-score table, open incidents, recent merges/CI and machine health; the Spend tab pairs the spend tile with per-model spend over 24 h. Light and dark follow the OS; there are no external assets and no build step — one server-rendered HTML string, inline CSS and one small inline script under a per-response CSP nonce (`bun scripts/ui-preview.ts <out.html> [--tab <name>]` renders a preview without a server). No chat, no plan editing, no shell.
|
|
120
|
+
With `ui.enabled: true` and `ui.owner_login` set (`neurastream config`, `docs/config.md`), `neurastream ui` serves one page bound to this machine's tailnet address only (port `ui.port`, default 7787; `templates/systemd/neurastream-ui.service` runs it as a user unit). A sticky top bar holds the "ns" logo, four pill tabs — Now, Queue, Agents, Spend, each a server-rendered view (`/?tab=…`, an unknown value falls back to Now) — and the lock pill ("🔒 Off" / "🔓 12 min") that opens the guard unlock ("Unlock 15 min", "Unlock 30 min", "Lock now"; when `guards.chat_unlock` is off it says so in plain words with the exact config line). Now is the home tab: a Today tile card over the last 24 h (needs-you count in warn color, list-price spend with a sparkline and the Main/agents split, agent runs with running/died counts and a sparkline, open plans), then one card per open `WAITING on owner:` plan — the plan's `#` title, the ask in plain words, the goal folded into a Background block, and "Yes"/"No"/"Reply…" actions whose answer shows as a one-time receipt ("Sent to Main · 08:12"); once the owner inbox already holds an answer for a plan, the card says so ("You answered ‘yes' · 14:19 — Main is on it") with a small change-answer link. The queue is one flat ranked list in `INDEX.md` order — drag a card by its ≡ handle, or tap "↑ top"/"↑"/"↓"; the drop rewrites `INDEX.md`, Main gets the move as a message and the page confirms "Moved to #2" — shown on Now as the first 8 rows with a "Show all N ›" link to the Queue tab. The Agents tab lists working-now rows, the agent-score table, open incidents, recent merges/CI and machine health; the Spend tab pairs the spend tile with per-model spend over 24 h. The Now tab also has a "Tell Main" message box for a text note and up to four images; Main receives the text and pictures, and the page keeps a "Sent today" list for 12 hours before removing those messages and their image files. Light and dark follow the OS; there are no external assets and no build step — one server-rendered HTML string, inline CSS and one small inline script under a per-response CSP nonce (`bun scripts/ui-preview.ts <out.html> [--tab <name>]` renders a preview without a server). No chat, no plan editing, no shell.
|
|
121
121
|
|
|
122
122
|
A request is served only when the peer is a tailnet address that is neither loopback nor this machine's own tailnet IP, `tailscale whois` names the `ui.owner_login` login — and the Host header is this machine: the tailnet address or the MagicDNS name, with the served port. The Host check runs on every request before whois, and a POST's Origin must match it, so a DNS-rebinding page (foreign Host, matching Origin, owner's phone) gets a 403 like everyone else. Every request logs one `UI <method> <path> login=<l> → <code>` line to the guard log.
|
|
123
123
|
|
package/package.json
CHANGED
|
@@ -45,7 +45,7 @@ import "./package-ops.ts";
|
|
|
45
45
|
export interface ExtensionHost {
|
|
46
46
|
on(event: string, cb: (...args: unknown[]) => unknown): void;
|
|
47
47
|
registerCommand(name: string, opts: { description?: string; handler: (args: unknown, ctx: unknown) => unknown }): void;
|
|
48
|
-
sendUserMessage(content: string): void;
|
|
48
|
+
sendUserMessage(content: string | ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[]): void;
|
|
49
49
|
sendMessage(message: { customType: string; content: string; display: boolean }, options: { triggerTurn: boolean; deliverAs: "nextTurn" }): void;
|
|
50
50
|
}
|
|
51
51
|
|
|
@@ -368,7 +368,7 @@ function writeOwnerInboxCursor(n: number): void {
|
|
|
368
368
|
|
|
369
369
|
/** The user message one inbox record becomes, or null when the record is not one Main can act on.
|
|
370
370
|
* Records without `kind` are page answers (the original shape). */
|
|
371
|
-
export function ownerInboxMessage(rec: Record<string, unknown>): string | null {
|
|
371
|
+
export function ownerInboxMessage(rec: Record<string, unknown>): string | ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[] | null {
|
|
372
372
|
const kind = rec.kind === undefined ? "answer" : asString(rec.kind);
|
|
373
373
|
const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
|
|
374
374
|
switch (kind) {
|
|
@@ -394,6 +394,37 @@ export function ownerInboxMessage(rec: Record<string, unknown>): string | null {
|
|
|
394
394
|
if (!plan || from === null || to === null) return null;
|
|
395
395
|
return `Owner moved ${basename(plan)} from #${from} to #${to} on the phone page; INDEX.md has the new order — work by it.`;
|
|
396
396
|
}
|
|
397
|
+
case "message": {
|
|
398
|
+
const ts = num(rec.ts);
|
|
399
|
+
const id = asString(rec.id);
|
|
400
|
+
if (ts === null || !/^[0-9]+-[0-9a-f]{6}$/.test(id)) return null;
|
|
401
|
+
const at = strftime(ts, "%H:%M");
|
|
402
|
+
const dir = join(q.stateDirPath(), "owner-messages", id);
|
|
403
|
+
let message: Record<string, unknown>;
|
|
404
|
+
try {
|
|
405
|
+
message = JSON.parse(readFileSync(join(dir, "message.json"), "utf8")) as Record<string, unknown>;
|
|
406
|
+
} catch {
|
|
407
|
+
return [{ type: "text", text: `Owner sent a message from the phone page at ${at}; it expired (12 h) before delivery.` }];
|
|
408
|
+
}
|
|
409
|
+
const text = asString(message.text);
|
|
410
|
+
const names = Array.isArray(message.images) ? message.images.filter((name): name is string => typeof name === "string" && /^[1-4]\.(png|jpg|gif|webp)$/.test(name)) : [];
|
|
411
|
+
const parts: ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[] = [];
|
|
412
|
+
const paths = names.map(name => join(dir, name));
|
|
413
|
+
parts.push({
|
|
414
|
+
type: "text",
|
|
415
|
+
text: `Owner message from the phone page (${at}): ${text}${paths.length ? `\nImages:\n${paths.map(path => `- ${path}`).join("\n")}` : ""}`,
|
|
416
|
+
});
|
|
417
|
+
for (const name of names) {
|
|
418
|
+
const ext = name.slice(name.lastIndexOf(".") + 1);
|
|
419
|
+
const mimeType = ext === "jpg" ? "image/jpeg" : `image/${ext}`;
|
|
420
|
+
try {
|
|
421
|
+
parts.push({ type: "image", data: readFileSync(join(dir, name)).toString("base64"), mimeType });
|
|
422
|
+
} catch {
|
|
423
|
+
return [{ type: "text", text: `Owner sent a message from the phone page at ${at}; it expired (12 h) before delivery.` }];
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
return parts;
|
|
427
|
+
}
|
|
397
428
|
default:
|
|
398
429
|
return null;
|
|
399
430
|
}
|
package/src/core/owner-ui.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
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, renameSync, statSync, statfsSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { appendFileSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, statfsSync, writeFileSync } from "node:fs";
|
|
11
11
|
import { randomUUID } from "node:crypto";
|
|
12
12
|
import os from "node:os";
|
|
13
13
|
import { basename, resolve } from "node:path";
|
|
@@ -23,6 +23,11 @@ import { activePlans, chatUnlock, expandHome, stateDirPath, unlockPath, type Pla
|
|
|
23
23
|
import type { Tailscale } from "./tailscale.ts";
|
|
24
24
|
|
|
25
25
|
const ANSWER_MAX = 2000;
|
|
26
|
+
const MESSAGE_MAX = 4000;
|
|
27
|
+
const MESSAGE_IMAGES_MAX = 4;
|
|
28
|
+
const MESSAGE_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
|
|
29
|
+
/** How long the page keeps an owner message: 12 h, then the sweep removes it (owner, 2026-10-25 19:10). */
|
|
30
|
+
export const OWNER_MESSAGE_KEEP_SEC = 43200;
|
|
26
31
|
const REFRESH_SEC = 20;
|
|
27
32
|
// Tailscale hands out addresses from 100.64.0.0/10 (CGNAT) and its own ULA /48 for IPv6.
|
|
28
33
|
const TAILNET6 = /^fd7a:115c:a1e0:/i;
|
|
@@ -304,9 +309,122 @@ export function nowStats(cfg: Config, source: RunSource, now: number): NowStats
|
|
|
304
309
|
return { spend24, mainSpend, agentSpend, runs24, running, died, spendByHour, runsByHour, byModel, openPlans: queueRows(cfg).length };
|
|
305
310
|
}
|
|
306
311
|
|
|
312
|
+
// ---- owner messages (plan P13): a one-way note plus images, kept for 12 h ----
|
|
313
|
+
|
|
314
|
+
/** Where the page stores owner messages: under the queue state dir, one dir per message. */
|
|
315
|
+
function ownerMessagesDir(): string {
|
|
316
|
+
return `${stateDirPath()}/owner-messages`;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export interface MessageRow {
|
|
320
|
+
id: string;
|
|
321
|
+
ts: number;
|
|
322
|
+
text: string;
|
|
323
|
+
images: string[];
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** The image type from the first bytes — PNG, JPEG, GIF or WEBP — never from the client's name or content type. */
|
|
327
|
+
function imageType(bytes: Uint8Array): "png" | "jpeg" | "gif" | "webp" | null {
|
|
328
|
+
if (
|
|
329
|
+
bytes.length >= 8 &&
|
|
330
|
+
bytes[0] === 0x89 &&
|
|
331
|
+
bytes[1] === 0x50 &&
|
|
332
|
+
bytes[2] === 0x4e &&
|
|
333
|
+
bytes[3] === 0x47 &&
|
|
334
|
+
bytes[4] === 0x0d &&
|
|
335
|
+
bytes[5] === 0x0a &&
|
|
336
|
+
bytes[6] === 0x1a &&
|
|
337
|
+
bytes[7] === 0x0a
|
|
338
|
+
)
|
|
339
|
+
return "png";
|
|
340
|
+
if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "jpeg";
|
|
341
|
+
if (bytes.length >= 6 && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38) return "gif";
|
|
342
|
+
if (
|
|
343
|
+
bytes.length >= 12 &&
|
|
344
|
+
bytes[0] === 0x52 &&
|
|
345
|
+
bytes[1] === 0x49 &&
|
|
346
|
+
bytes[2] === 0x46 &&
|
|
347
|
+
bytes[3] === 0x46 &&
|
|
348
|
+
bytes[8] === 0x57 &&
|
|
349
|
+
bytes[9] === 0x45 &&
|
|
350
|
+
bytes[10] === 0x42 &&
|
|
351
|
+
bytes[11] === 0x50
|
|
352
|
+
)
|
|
353
|
+
return "webp";
|
|
354
|
+
return null;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
const IMAGE_EXT: Record<string, string> = { png: "png", jpeg: "jpg", gif: "gif", webp: "webp" };
|
|
358
|
+
const IMAGE_MIME: Record<string, string> = { png: "image/png", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
|
|
359
|
+
|
|
360
|
+
/** Removes every message dir older than the keep window; runs on every GET / and every POST /message. */
|
|
361
|
+
export function sweepOwnerMessages(now: number): void {
|
|
362
|
+
let names: string[];
|
|
363
|
+
try {
|
|
364
|
+
names = readdirSync(ownerMessagesDir());
|
|
365
|
+
} catch {
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
for (const name of names) {
|
|
369
|
+
const ts = Number(name.slice(0, name.indexOf("-")));
|
|
370
|
+
if (Number.isFinite(ts) && now - ts <= OWNER_MESSAGE_KEEP_SEC) continue;
|
|
371
|
+
rmSync(`${ownerMessagesDir()}/${name}`, { recursive: true, force: true });
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** The messages newer than the keep window for the "Sent today" list, newest first. A torn dir is skipped, not fatal. */
|
|
376
|
+
export function recentOwnerMessages(now: number): MessageRow[] {
|
|
377
|
+
let names: string[] = [];
|
|
378
|
+
try {
|
|
379
|
+
names = readdirSync(ownerMessagesDir());
|
|
380
|
+
} catch {
|
|
381
|
+
return [];
|
|
382
|
+
}
|
|
383
|
+
const rows: MessageRow[] = [];
|
|
384
|
+
for (const id of names) {
|
|
385
|
+
const dirTs = Number(id.slice(0, id.indexOf("-")));
|
|
386
|
+
if (!Number.isFinite(dirTs) || now - dirTs >= OWNER_MESSAGE_KEEP_SEC) continue;
|
|
387
|
+
try {
|
|
388
|
+
const meta = JSON.parse(readFileSync(`${ownerMessagesDir()}/${id}/message.json`, "utf8")) as Record<string, unknown>;
|
|
389
|
+
rows.push({
|
|
390
|
+
id,
|
|
391
|
+
ts: Number(meta.ts) || dirTs,
|
|
392
|
+
text: typeof meta.text === "string" ? meta.text : "",
|
|
393
|
+
images: Array.isArray(meta.images) ? meta.images.filter((n): n is string => typeof n === "string") : [],
|
|
394
|
+
});
|
|
395
|
+
} catch {}
|
|
396
|
+
}
|
|
397
|
+
return rows.sort((a, b) => b.ts - a.ts);
|
|
398
|
+
}
|
|
399
|
+
|
|
307
400
|
// ---- rendering (consumes the rows above, never the readers directly) ----
|
|
308
401
|
|
|
309
|
-
|
|
402
|
+
/** The "Tell Main" card: one textarea, image picks, a Send button — no chat thread. Under it, "Sent today": this view's messages newer than the keep window, newest first, thumbnails served from /message-image. */
|
|
403
|
+
function messageCard(messages: MessageRow[] | null): string {
|
|
404
|
+
const form = `<form class="msgform" method="post" action="/message" enctype="multipart/form-data">
|
|
405
|
+
<textarea name="text" maxlength="${MESSAGE_MAX}" rows="3" placeholder="What Main should know — a fix, a link, a photo"></textarea>
|
|
406
|
+
<input type="file" name="images" accept="image/*" multiple>
|
|
407
|
+
<button class="btn pri" type="submit">Send</button>
|
|
408
|
+
</form>`;
|
|
409
|
+
let sent = "";
|
|
410
|
+
if (messages === null) sent = na("Sent today");
|
|
411
|
+
else if (messages.length) {
|
|
412
|
+
const rows = messages
|
|
413
|
+
.map(m => {
|
|
414
|
+
const imgs = m.images.map(n => `<a href="/message-image/${esc(m.id)}/${esc(n)}"><img class="mthumb" src="/message-image/${esc(m.id)}/${esc(n)}" alt=""></a>`).join("");
|
|
415
|
+
return `<div class="msg"><span class="mtime">${esc(strftime(m.ts, "%H:%M"))}</span><span class="mtext">${esc(m.text)}</span>${imgs ? `<span class="mimgs">${imgs}</span>` : ""}</div>`;
|
|
416
|
+
})
|
|
417
|
+
.join("");
|
|
418
|
+
sent = `<p class="mlabel">Sent today</p>${rows}`;
|
|
419
|
+
}
|
|
420
|
+
return `<h2>Tell Main</h2>
|
|
421
|
+
<div class="card">
|
|
422
|
+
${form}
|
|
423
|
+
${sent}
|
|
424
|
+
</div>`;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function needCard(row: QuestionRow, i: number, tab: string): string {
|
|
310
428
|
const goals = row.goal.map(g => `<li>${esc(g)}</li>`).join("");
|
|
311
429
|
const wait = row.waitingMin < 60 ? `waiting ${row.waitingMin} min` : `waiting ${Math.max(1, Math.round(row.waitingMin / 60))} h`;
|
|
312
430
|
const bg = row.goal.length ? `<details class="bg" id="bg-${i}"><summary>Background</summary><ul>${goals}</ul></details>` : "";
|
|
@@ -332,6 +450,7 @@ function needCard(row: QuestionRow, i: number): string {
|
|
|
332
450
|
${bg}
|
|
333
451
|
<form method="post" action="/answer">
|
|
334
452
|
<input type="hidden" name="plan" value="${esc(row.plan)}">
|
|
453
|
+
<input type="hidden" name="tab" value="${esc(tab)}">
|
|
335
454
|
${acts}
|
|
336
455
|
<div class="reply" hidden>
|
|
337
456
|
<textarea name="answer_text" maxlength="${ANSWER_MAX}" rows="3" placeholder="Type your reply"></textarea>
|
|
@@ -347,7 +466,7 @@ function agentRowHtml(r: AgentRow): string {
|
|
|
347
466
|
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>`;
|
|
348
467
|
}
|
|
349
468
|
|
|
350
|
-
function queueHtml(rows: QueueRow[]): string {
|
|
469
|
+
function queueHtml(rows: QueueRow[], tab: string): string {
|
|
351
470
|
const cards = rows
|
|
352
471
|
.map(
|
|
353
472
|
(r, i) => `<li class="qcard" data-plan="${esc(r.file)}">
|
|
@@ -369,6 +488,7 @@ ${cards}
|
|
|
369
488
|
<input type="hidden" name="before" value="${esc(before)}">
|
|
370
489
|
<input type="hidden" name="order" value="">
|
|
371
490
|
<input type="hidden" name="moved" value="">
|
|
491
|
+
<input type="hidden" name="tab" value="${esc(tab)}">
|
|
372
492
|
</form>`;
|
|
373
493
|
}
|
|
374
494
|
|
|
@@ -441,25 +561,26 @@ function topBarHtml(tab: string, lockMinutesLeft: number | null, cfg: Config): s
|
|
|
441
561
|
const tabs: [string, string][] = [["now", "Now"], ["queue", "Queue"], ["agents", "Agents"], ["spend", "Spend"]];
|
|
442
562
|
const pills = tabs.map(([id, label]) => `<a href="/?tab=${id}"${tab === id ? ` class="on"` : ""}>${label}</a>`).join("");
|
|
443
563
|
const lockLabel = lockMinutesLeft === null ? "🔒 Off" : `🔓 ${lockMinutesLeft} min`;
|
|
564
|
+
const tabField = `<input type="hidden" name="tab" value="${esc(tab)}">`;
|
|
444
565
|
const unlockForm = (minutes: number) =>
|
|
445
|
-
`<form method="post" action="/unlock"><input type="hidden" name="minutes" value="${minutes}"
|
|
566
|
+
`<form method="post" action="/unlock"><input type="hidden" name="minutes" value="${minutes}">${tabField}<button class="btn" type="submit">Unlock ${minutes} min</button></form>`;
|
|
446
567
|
const tierForm = (name: Tier, label: string) =>
|
|
447
|
-
`<form method="post" action="/tier"><input type="hidden" name="tier" value="${name}"
|
|
568
|
+
`<form method="post" action="/tier"><input type="hidden" name="tier" value="${name}">${tabField}<button class="btn${currentTier(cfg) === name ? " on" : ""}" type="submit">${label}</button></form>`;
|
|
448
569
|
const off = cfg.guards.chat_unlock
|
|
449
570
|
? ""
|
|
450
571
|
: `<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>`;
|
|
451
572
|
return `<div class="top"><span class="logo">ns</span>
|
|
452
573
|
<nav class="pills" aria-label="Sections">${pills}</nav>
|
|
453
|
-
<details class="lock" id="lock-pill"><summary>${lockLabel}</summary><div class="lockmenu">${unlockForm(15)}${unlockForm(30)}<form method="post" action="/lock"
|
|
574
|
+
<details class="lock" id="lock-pill"><summary>${lockLabel}</summary><div class="lockmenu">${unlockForm(15)}${unlockForm(30)}<form method="post" action="/lock">${tabField}<button class="btn" type="submit">Lock now</button></form><hr>${tierForm("strict", "Tier: strict")}${tierForm("opinionated", "Tier: opinionated")}${tierForm("full", "Tier: full")}${off}</div></details>
|
|
454
575
|
</div>`;
|
|
455
576
|
}
|
|
456
577
|
|
|
457
578
|
/** The queue card. Full on the Queue tab; the Now tab shows the first 8 rows plus the "Show all" link — the drag script merges the hidden rest from the form's before field, so a drag still posts the complete order. */
|
|
458
|
-
function queueCard(rows: QueueRow[] | null, full: boolean): string {
|
|
579
|
+
function queueCard(rows: QueueRow[] | null, full: boolean, tab: string): string {
|
|
459
580
|
const head = full ? "" : `<h2>Queue <small>drag ≡ to sort</small></h2>`;
|
|
460
581
|
if (rows === null) return `${head}<div class="card">${na("Queue")}</div>`;
|
|
461
582
|
if (!rows.length) return `${head}<div class="card"><p class="empty">The queue is empty</p></div>`;
|
|
462
|
-
const body = queueHtml(full ? rows : rows.slice(0, 8));
|
|
583
|
+
const body = queueHtml(full ? rows : rows.slice(0, 8), tab);
|
|
463
584
|
const more = !full && rows.length > 8 ? `<a class="more" href="/?tab=queue">Show all ${rows.length} ›</a>` : "";
|
|
464
585
|
return `${head}<div class="card">${body}${more}</div>`;
|
|
465
586
|
}
|
|
@@ -475,11 +596,11 @@ function na(label: string): string {
|
|
|
475
596
|
return `<p class="na">${esc(label)} unavailable</p>`;
|
|
476
597
|
}
|
|
477
598
|
|
|
478
|
-
function
|
|
479
|
-
if (!sent) return "";
|
|
599
|
+
function receiptText(sent: string, params: URLSearchParams): string | null {
|
|
480
600
|
let text: string;
|
|
481
601
|
switch (sent) {
|
|
482
602
|
case "answer":
|
|
603
|
+
case "message":
|
|
483
604
|
text = `Sent to Main · ${strftime(nowSec(), "%H:%M")}`;
|
|
484
605
|
break;
|
|
485
606
|
case "unlock": {
|
|
@@ -491,8 +612,9 @@ function receiptHtml(sent: string | null, params: URLSearchParams): string {
|
|
|
491
612
|
text = "Locked";
|
|
492
613
|
break;
|
|
493
614
|
case "reorder": {
|
|
615
|
+
// The rank counts the OPEN plans (what the page shows), not every INDEX.md line.
|
|
494
616
|
const to = Number(params.get("to"));
|
|
495
|
-
text = Number.isInteger(to) && to > 0 ? `Moved to #${to} · Main sees it next turn` : "Moved · Main sees it next turn";
|
|
617
|
+
text = Number.isInteger(to) && to > 0 ? `Moved to #${to} of open plans · Main sees it next turn` : "Moved · Main sees it next turn";
|
|
496
618
|
break;
|
|
497
619
|
}
|
|
498
620
|
case "unlock-off":
|
|
@@ -502,9 +624,24 @@ function receiptHtml(sent: string | null, params: URLSearchParams): string {
|
|
|
502
624
|
text = "Already handled — Main cleared this question before your answer; your answer was still passed on.";
|
|
503
625
|
break;
|
|
504
626
|
default:
|
|
505
|
-
return
|
|
627
|
+
return null;
|
|
506
628
|
}
|
|
507
|
-
return
|
|
629
|
+
return text;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
function receiptHtml(sent: string | null, params: URLSearchParams): string {
|
|
633
|
+
if (!sent) return "";
|
|
634
|
+
const text = receiptText(sent, params);
|
|
635
|
+
return text === null ? "" : `<div class="receipt" role="status">${esc(text)}</div>`;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/** The JSON POST replies (P11b): the receipt text rides along so the page script never re-derives it. */
|
|
639
|
+
function jsonSent(sent: string, receipt?: string | null): Response {
|
|
640
|
+
return Response.json(receipt ? { ok: true, sent, receipt } : { ok: true, sent });
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
function jsonFail(error: string, status: number): Response {
|
|
644
|
+
return Response.json({ ok: false, error }, { status });
|
|
508
645
|
}
|
|
509
646
|
|
|
510
647
|
// ---- page assembly: one unreadable source never takes the page down ----
|
|
@@ -519,6 +656,8 @@ export interface PageData {
|
|
|
519
656
|
machine: MachineRow | null;
|
|
520
657
|
/** The 24 h tile numbers; null when the run source is unreadable. */
|
|
521
658
|
stats: NowStats | null;
|
|
659
|
+
/** The owner's messages newer than the keep window, newest first; null when unreadable. */
|
|
660
|
+
messages: MessageRow[] | null;
|
|
522
661
|
/** Minutes left in the guard unlock; null = locked. */
|
|
523
662
|
lockMinutesLeft: number | null;
|
|
524
663
|
}
|
|
@@ -552,6 +691,7 @@ export function buildPageData(cfg: Config, source: RunSource): PageData {
|
|
|
552
691
|
scores: safe(() => scoresData(cfg)),
|
|
553
692
|
machine: safe(() => machineRow(cfg)),
|
|
554
693
|
stats: safe(() => nowStats(cfg, source, nowSec())),
|
|
694
|
+
messages: safe(() => recentOwnerMessages(nowSec())),
|
|
555
695
|
lockMinutesLeft: lockMinutesLeft(cfg),
|
|
556
696
|
};
|
|
557
697
|
}
|
|
@@ -559,30 +699,96 @@ export function buildPageData(cfg: Config, source: RunSource): PageData {
|
|
|
559
699
|
const FAVICON =
|
|
560
700
|
"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";
|
|
561
701
|
|
|
702
|
+
/**
|
|
703
|
+
* Where a dropped card goes among the other cards, by vertical midpoint (y grows downward):
|
|
704
|
+
* in front of the FIRST card whose midpoint is greater than the dragged card's, else after the
|
|
705
|
+
* last card. Returns an index into `mids` (the first slot) or `mids.length` (after the last).
|
|
706
|
+
* Pure and exported so the page script — which inlines this exact source via toString() — and
|
|
707
|
+
* the test run the same code: dragging card 1 toward card 2 lands it at 2, never second-to-last.
|
|
708
|
+
*/
|
|
709
|
+
export function dropSlot(mids: number[], mid: number): number {
|
|
710
|
+
for (let i = 0; i < mids.length; i++) if (mids[i]! > mid) return i;
|
|
711
|
+
return mids.length;
|
|
712
|
+
}
|
|
713
|
+
|
|
562
714
|
const SCRIPT = `(function(){
|
|
563
|
-
|
|
715
|
+
var dropSlot=${dropSlot.toString()};
|
|
716
|
+
// Keep only the tab in the address bar: receipts are one-time DOM, not a reloadable URL.
|
|
717
|
+
if(location.search){var keep=new URLSearchParams(location.search).get("tab");history.replaceState(null,"",location.pathname+(keep?"?tab="+keep:""));}
|
|
564
718
|
function store(d,v){var k="nsui:"+d.id;if(v===undefined)return sessionStorage.getItem(k);sessionStorage.setItem(k,v?"1":"0");}
|
|
565
|
-
var ds=
|
|
566
|
-
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]);}
|
|
567
|
-
var rb=document.querySelectorAll(".replybtn");
|
|
568
|
-
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();}}});}
|
|
569
|
-
var qlist=document.getElementById("qlist");
|
|
719
|
+
function bindDetails(root){var ds=root.querySelectorAll("details[id]");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]);}}
|
|
570
720
|
var dragging=false;
|
|
571
|
-
if(
|
|
572
|
-
var
|
|
573
|
-
|
|
574
|
-
var
|
|
575
|
-
var
|
|
576
|
-
|
|
721
|
+
function showReceipt(text){var main=document.querySelector("main");if(!main)return null;var old=document.querySelector(".receipt[data-js]");if(old&&old.parentNode)old.parentNode.removeChild(old);var d=document.createElement("div");d.className="receipt";d.setAttribute("role","status");d.setAttribute("data-js","1");d.textContent=text;main.parentNode.insertBefore(d,main);return d;}
|
|
722
|
+
function renumber(list){var cards=list.querySelectorAll(".qcard");for(var i=0;i<cards.length;i++){var n=cards[i].querySelector(".qrank");if(n)n.textContent=String(i+1);}}
|
|
723
|
+
function sendReorder(moved,list){
|
|
724
|
+
var rform=document.getElementById("reorder-form");if(!rform||!moved)return;
|
|
725
|
+
var cards=list.querySelectorAll(".qcard");var shown=[];for(var i=0;i<cards.length;i++)shown.push(cards[i].getAttribute("data-plan"));
|
|
726
|
+
var bf=(rform.querySelector("[name=before]").value||"").split("\\n").filter(function(x){return x;});
|
|
727
|
+
var o=shown.slice();for(var j=0;j<bf.length;j++){if(shown.indexOf(bf[j])<0)o.push(bf[j]);}
|
|
728
|
+
dragging=false;
|
|
729
|
+
fetch("/reorder",{method:"POST",headers:{"accept":"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({order:o.join("\\n"),before:bf.join("\\n"),moved:moved}).toString()}).then(function(r){return r.json().then(function(j){return{s:r.status,j:j};});}).then(function(res){
|
|
730
|
+
if(res.s===200&&res.j&&res.j.ok){renumber(list);var b=rform.querySelector("[name=before]");if(b)b.value=o.join("\\n");showReceipt("Moved to #"+res.j.to+" of open plans · Main sees it next turn");}
|
|
731
|
+
else if(res.s===409){showReceipt((res.j&&res.j.error?res.j.error:"the queue changed since the page loaded")+" — showing the current order");refreshNow();}
|
|
732
|
+
else{showReceipt(res.j&&res.j.error?res.j.error:"the move was refused");}
|
|
733
|
+
}).catch(function(){showReceipt("could not reach the page server — try again");});
|
|
734
|
+
}
|
|
735
|
+
var swapping=false;
|
|
736
|
+
// Fetch a page URL and swap only <main> plus the tabs' active pill. push: new history entry; scroll: to top (tab change only).
|
|
737
|
+
function swapMain(href,push,scroll){
|
|
738
|
+
return fetch(href,{headers:{"accept":"text/html"}}).then(function(r){return r.text();}).then(function(html){
|
|
739
|
+
var doc=document.implementation.createHTMLDocument("");doc.body.innerHTML=html;
|
|
740
|
+
var fresh=doc.querySelector("main");var cur=document.querySelector("main");
|
|
741
|
+
if(fresh&&cur){cur.innerHTML=fresh.innerHTML;bindPage();
|
|
742
|
+
var pills=document.querySelectorAll(".pills a");var fp=doc.querySelectorAll(".pills a");for(var i=0;i<pills.length&&i<fp.length;i++)pills[i].className=fp[i].className;}
|
|
743
|
+
if(push)history.pushState(null,"",href);
|
|
744
|
+
if(scroll)window.scrollTo(0,0);})}
|
|
745
|
+
function navigate(href){swapMain(href,true,true).catch(function(){showNetErr();});}
|
|
746
|
+
function refreshNow(){if(swapping)return;swapping=true;swapMain(location.href,false,false).catch(function(){}).then(function(){swapping=false;});}
|
|
747
|
+
function showNetErr(){var d=showReceipt("Couldn't reach the page — tap to retry");if(d)d.setAttribute("data-js","neterr");}
|
|
577
748
|
var drag=null;
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
749
|
+
window.addEventListener("pointermove",function(e){if(!drag||e.pointerId!==drag.id)return;var card=drag.card,list=drag.list;card.style.transform="translateY("+(e.clientY-drag.y0)+"px)";var r=card.getBoundingClientRect();var mid=r.top+r.height/2;var mids=[];var els=[];var ch=list.children;for(var i=0;i<ch.length;i++){var el=ch[i];if(el===card||el===drag.ph)continue;var er=el.getBoundingClientRect();mids.push(er.top+er.height/2);els.push(el);}
|
|
750
|
+
var k=dropSlot(mids,mid);
|
|
751
|
+
if(k<mids.length){if(els[k].previousElementSibling!==drag.ph)list.insertBefore(drag.ph,els[k]);}else if(mids.length&&els[mids.length-1].nextElementSibling!==drag.ph){list.insertBefore(drag.ph,els[mids.length-1].nextSibling);}});
|
|
752
|
+
var endDrag=function(e,submitIt){if(!drag||(e&&e.pointerId!==undefined&&e.pointerId!==drag.id))return;var card=drag.card,ph=drag.ph,list=drag.list;card.classList.remove("dragging");card.style.transform="";card.style.width="";card.style.left="";card.style.top="";list.insertBefore(card,ph);list.removeChild(ph);drag=null;if(submitIt)sendReorder(card.getAttribute("data-plan"),list);else dragging=false;};
|
|
581
753
|
window.addEventListener("pointerup",function(e){endDrag(e,true);});
|
|
582
754
|
window.addEventListener("pointercancel",function(e){endDrag(e,false);});
|
|
755
|
+
// Every POST form goes over fetch and swaps main in place (P11b); a no-JS browser still submits for real and gets the 303s.
|
|
756
|
+
document.addEventListener("submit",function(e){
|
|
757
|
+
var f=e.target;if(!f||!f.getAttribute)return;
|
|
758
|
+
var action=f.getAttribute("action")||"/";
|
|
759
|
+
if((f.getAttribute("method")||"").toLowerCase()!=="post"||action.charAt(0)!=="/")return;
|
|
760
|
+
e.preventDefault();
|
|
761
|
+
fetch(action,{method:"POST",headers:{"accept":"application/json"},body:new FormData(f,e.submitter||undefined)}).then(function(r){return r.json().then(function(j){return{s:r.status,j:j};});}).then(function(res){
|
|
762
|
+
if(res.j&&res.j.receipt)showReceipt(res.j.receipt);else if(res.j&&res.j.error)showReceipt(res.j.error);
|
|
763
|
+
refreshNow();
|
|
764
|
+
}).catch(function(){showNetErr();});
|
|
765
|
+
});
|
|
766
|
+
// Same-origin links (tab pills, the queue's more link) swap main and pushState; Back swaps back via popstate; the net-error line retries on tap.
|
|
767
|
+
document.addEventListener("click",function(e){
|
|
768
|
+
if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;
|
|
769
|
+
var t=e.target;if(!t||!t.closest)return;
|
|
770
|
+
if(t.closest('.receipt[data-js="neterr"]')){e.preventDefault();refreshNow();return;}
|
|
771
|
+
var a=t.closest("a");if(!a)return;var href=a.getAttribute("href");
|
|
772
|
+
if(!href||a.target||href.charAt(0)!=="/")return;
|
|
773
|
+
e.preventDefault();navigate(href);
|
|
774
|
+
});
|
|
775
|
+
window.addEventListener("popstate",function(){swapMain(location.href,false,false).catch(function(){showNetErr();});});
|
|
776
|
+
function bindPage(){
|
|
777
|
+
var main=document.querySelector("main");if(!main)return;
|
|
778
|
+
bindDetails(main);
|
|
779
|
+
var rb=main.querySelectorAll(".replybtn");
|
|
780
|
+
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();}}});}
|
|
781
|
+
var qlist=main.querySelector("#qlist");
|
|
782
|
+
if(qlist){
|
|
783
|
+
var moveCard=function(card,how){if(how==="top"){var f=qlist.querySelector(".qcard");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);}};
|
|
784
|
+
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"));sendReorder(card.getAttribute("data-plan"),qlist);});
|
|
785
|
+
qlist.addEventListener("pointerdown",function(e){var t=e.target;if(!t||!t.closest)return;var h=t.closest(".qhandle");if(h&&!drag){var card=t.closest(".qcard");if(card){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,list:qlist};try{h.setPointerCapture(e.pointerId);}catch(_){}}}});
|
|
786
|
+
}
|
|
583
787
|
}
|
|
584
788
|
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;}
|
|
585
|
-
setInterval(function(){if(!busy())
|
|
789
|
+
setInterval(function(){if(!busy()&&!swapping)refreshNow();},${REFRESH_SEC}000);
|
|
790
|
+
bindDetails(document);
|
|
791
|
+
bindPage();
|
|
586
792
|
})();`;
|
|
587
793
|
|
|
588
794
|
/** The whole page as one HTML string. Exported for scripts/ui-preview.ts (no server). */
|
|
@@ -594,7 +800,7 @@ export function renderPage(cfg: Config, data: PageData, params: URLSearchParams,
|
|
|
594
800
|
data.questions === null
|
|
595
801
|
? na("Waiting on you")
|
|
596
802
|
: data.questions.length
|
|
597
|
-
? data.questions.map(needCard).join("\n")
|
|
803
|
+
? data.questions.map((row, i) => needCard(row, i, tab)).join("\n")
|
|
598
804
|
: `<p class="empty">Nothing needs you right now</p>`;
|
|
599
805
|
const working =
|
|
600
806
|
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>`;
|
|
@@ -604,7 +810,8 @@ export function renderPage(cfg: Config, data: PageData, params: URLSearchParams,
|
|
|
604
810
|
const machine = data.machine === null ? na("Machine") : machineHtml(cfg, data.machine);
|
|
605
811
|
const body =
|
|
606
812
|
tab === "now"
|
|
607
|
-
?
|
|
813
|
+
? `${messageCard(data.messages)}
|
|
814
|
+
<h1>Today</h1>
|
|
608
815
|
<p class="sub">What your agents did in the last 24 hours.</p>
|
|
609
816
|
<div class="card">
|
|
610
817
|
${tilesHtml(data)}
|
|
@@ -613,11 +820,11 @@ ${tilesHtml(data)}
|
|
|
613
820
|
<div class="card">
|
|
614
821
|
${needsBody}
|
|
615
822
|
</div>
|
|
616
|
-
${queueCard(data.queue, false)}`
|
|
823
|
+
${queueCard(data.queue, false, tab)}`
|
|
617
824
|
: tab === "queue"
|
|
618
825
|
? `<h1>Queue</h1>
|
|
619
826
|
<p class="sub">Drag ≡ to sort — Main works by the new order on its next turn.</p>
|
|
620
|
-
${queueCard(data.queue, true)}`
|
|
827
|
+
${queueCard(data.queue, true, tab)}`
|
|
621
828
|
: tab === "agents"
|
|
622
829
|
? `<h1>Agents</h1>
|
|
623
830
|
<p class="sub">Who is working right now, how they score, and what went wrong.</p>
|
|
@@ -703,6 +910,16 @@ svg.spark{width:130px;height:40px;flex:none}
|
|
|
703
910
|
:focus-visible{outline:2px solid var(--acc);outline-offset:2px}
|
|
704
911
|
.reply{margin-top:8px}
|
|
705
912
|
.reply textarea{width:100%;padding:10px;border-radius:10px;border:1px solid var(--bd);background:var(--bg);color:var(--fg);font:inherit}
|
|
913
|
+
.msgform{padding:14px 16px;display:flex;flex-direction:column;gap:10px}
|
|
914
|
+
.msgform textarea{width:100%;padding:10px;border-radius:10px;border:1px solid var(--bd);background:var(--bg);color:var(--fg);font:inherit}
|
|
915
|
+
.msgform input[type=file]{font-size:13px;color:var(--mut);max-width:100%}
|
|
916
|
+
.mlabel{margin:0;padding:10px 16px 2px;color:var(--mut);font-size:13px}
|
|
917
|
+
.msg{display:flex;gap:10px;padding:10px 16px;border-top:1px solid var(--bd);align-items:baseline;flex-wrap:wrap}
|
|
918
|
+
.msg:first-of-type{border-top:0}
|
|
919
|
+
.mtime{color:var(--mut);font-size:12px;font-variant-numeric:tabular-nums;flex:none}
|
|
920
|
+
.mtext{flex:1 1 12em;min-width:0;font-size:14px}
|
|
921
|
+
.mimgs{display:flex;gap:6px}
|
|
922
|
+
img.mthumb{width:56px;height:56px;object-fit:cover;border-radius:10px;border:1px solid var(--bd);display:block}
|
|
706
923
|
details.bg{margin:8px 0;border-top:1px solid var(--bd);padding-top:6px}
|
|
707
924
|
details.bg summary{color:var(--mut)}
|
|
708
925
|
details.bg ul{margin:4px 0 8px;padding-left:20px;color:var(--mut);font-size:13px}
|
|
@@ -776,6 +993,12 @@ function redirect(target: string): Response {
|
|
|
776
993
|
return new Response(null, { status: 303, headers: { location: target } });
|
|
777
994
|
}
|
|
778
995
|
|
|
996
|
+
/** The POST reply target: the tab the owner was on (a hidden `tab` field; unknown = now, the default), then the receipt. */
|
|
997
|
+
function sentTo(tab: string, sent: string): string {
|
|
998
|
+
const t = tab === "queue" || tab === "agents" || tab === "spend" ? tab : "now";
|
|
999
|
+
return t === "now" ? `/?${sent}` : `/?tab=${t}&${sent}`;
|
|
1000
|
+
}
|
|
1001
|
+
|
|
779
1002
|
/** The normal page (the GET layout) as a POST reply; the stale-answer reply is this with sent=stale. */
|
|
780
1003
|
function pageRes(cfg: Config, source: RunSource, params: URLSearchParams): Response {
|
|
781
1004
|
const nonce = randomUUID().replaceAll("-", "");
|
|
@@ -783,7 +1006,7 @@ function pageRes(cfg: Config, source: RunSource, params: URLSearchParams): Respo
|
|
|
783
1006
|
status: 200,
|
|
784
1007
|
headers: {
|
|
785
1008
|
"content-type": "text/html; charset=utf-8",
|
|
786
|
-
"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'`,
|
|
1009
|
+
"content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; img-src 'self' data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
|
|
787
1010
|
},
|
|
788
1011
|
});
|
|
789
1012
|
}
|
|
@@ -802,41 +1025,107 @@ function appendAnswer(plan: string, question: string, answer: string, login: str
|
|
|
802
1025
|
lastAnswerByPlan.set(plan, { answer, ts: now });
|
|
803
1026
|
}
|
|
804
1027
|
|
|
805
|
-
function handleAnswer(cfg: Config, source: RunSource, fields: Record<string, string>, login: string): Response {
|
|
1028
|
+
function handleAnswer(cfg: Config, source: RunSource, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
|
|
806
1029
|
const planFile = (fields.plan ?? "").trim();
|
|
807
1030
|
const answer = (fields.answer_text ?? "").trim() || (fields.answer ?? "").trim();
|
|
808
|
-
if (!planFile || !answer) return textRes("plan and answer are required", 400);
|
|
809
|
-
if (answer.length > ANSWER_MAX) return textRes(`answer is longer than ${ANSWER_MAX} chars`, 400);
|
|
1031
|
+
if (!planFile || !answer) return wantsJson ? jsonFail("plan and answer are required", 400) : textRes("plan and answer are required", 400);
|
|
1032
|
+
if (answer.length > ANSWER_MAX) return wantsJson ? jsonFail(`answer is longer than ${ANSWER_MAX} chars`, 400) : textRes(`answer is longer than ${ANSWER_MAX} chars`, 400);
|
|
810
1033
|
const plan = activePlans(cfg.paths.queue_index).find(p => p.file === planFile);
|
|
811
|
-
if (!plan) return textRes("plan is not open and waiting", 409);
|
|
1034
|
+
if (!plan) return wantsJson ? jsonFail("plan is not open and waiting", 409) : textRes("plan is not open and waiting", 409);
|
|
812
1035
|
if (plan.status !== "open" || !plan.waiting || !plan.waitingLine) {
|
|
813
1036
|
// Stale answer (P8b): Main cleared the question before the answer arrived; pass it on anyway.
|
|
814
1037
|
appendAnswer(planFile, "(already cleared)", answer, login);
|
|
1038
|
+
if (wantsJson) return jsonSent("stale", receiptText("stale", new URLSearchParams()));
|
|
815
1039
|
return pageRes(cfg, source, new URLSearchParams({ sent: "stale" }));
|
|
816
1040
|
}
|
|
817
1041
|
appendAnswer(planFile, plan.waitingLine, answer, login);
|
|
818
|
-
return
|
|
1042
|
+
if (wantsJson) return jsonSent("answer", receiptText("answer", new URLSearchParams()));
|
|
1043
|
+
return redirect(sentTo(fields.tab ?? "", "sent=answer"));
|
|
819
1044
|
}
|
|
820
1045
|
|
|
821
|
-
|
|
1046
|
+
// ---- POST /message (plan P13): the owner's one-way note plus images, inboxed by id ----
|
|
1047
|
+
|
|
1048
|
+
async function handleMessage(req: Request, login: string, wantsJson: boolean): Promise<Response> {
|
|
1049
|
+
sweepOwnerMessages(nowSec());
|
|
1050
|
+
const form = await req.formData();
|
|
1051
|
+
let text = "";
|
|
1052
|
+
const files: File[] = [];
|
|
1053
|
+
for (const [key, value] of form.entries()) {
|
|
1054
|
+
if (key === "text" && typeof value === "string") text = value.trim();
|
|
1055
|
+
else if (key === "images" && typeof value !== "string") files.push(value);
|
|
1056
|
+
}
|
|
1057
|
+
const fail = (error: string): Response => (wantsJson ? jsonFail(error, 400) : textRes(error, 400));
|
|
1058
|
+
if (!text && !files.length) return fail("write a text or attach an image");
|
|
1059
|
+
if (text.length > MESSAGE_MAX) return fail(`text is longer than ${MESSAGE_MAX} chars`);
|
|
1060
|
+
if (files.length > MESSAGE_IMAGES_MAX) return fail(`at most ${MESSAGE_IMAGES_MAX} images per message`);
|
|
1061
|
+
const images: { bytes: Uint8Array; kind: string }[] = [];
|
|
1062
|
+
for (const file of files) {
|
|
1063
|
+
if (file.size > MESSAGE_IMAGE_MAX_BYTES) return fail("an image is larger than 10 MB");
|
|
1064
|
+
const data = new Uint8Array(await file.arrayBuffer());
|
|
1065
|
+
const kind = imageType(data);
|
|
1066
|
+
if (!kind) return fail("attachments must be PNG, JPEG, GIF or WEBP images — the type is read from the file itself");
|
|
1067
|
+
images.push({ bytes: data, kind });
|
|
1068
|
+
}
|
|
1069
|
+
const ts = nowSec();
|
|
1070
|
+
// The dir name starts with a whole-second ts: the sweep and the image route both parse it.
|
|
1071
|
+
const id = `${Math.floor(ts)}-${randomUUID().slice(0, 6)}`;
|
|
1072
|
+
const dir = `${ownerMessagesDir()}/${id}`;
|
|
1073
|
+
mkdirSync(dir, { recursive: true });
|
|
1074
|
+
const names: string[] = [];
|
|
1075
|
+
for (let i = 0; i < images.length; i++) {
|
|
1076
|
+
const name = `${i + 1}.${IMAGE_EXT[images[i]!.kind]}`;
|
|
1077
|
+
writeFileSync(`${dir}/${name}`, images[i]!.bytes);
|
|
1078
|
+
names.push(name);
|
|
1079
|
+
}
|
|
1080
|
+
writeFileSync(`${dir}/message.json`, `${JSON.stringify({ ts, text, login, images: names })}\n`);
|
|
1081
|
+
mkdirSync(stateDirPath(), { recursive: true });
|
|
1082
|
+
// The text stays out of owner-inbox.jsonl; Main reads message.json through the id (P14).
|
|
1083
|
+
appendFileSync(inboxPath(), `${JSON.stringify({ ts, kind: "message", id, login })}\n`);
|
|
1084
|
+
if (wantsJson) return jsonSent("message", receiptText("message", new URLSearchParams()));
|
|
1085
|
+
return redirect("/?sent=message");
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
/** Serves one stored message image. Both path pieces are shape-checked and the name must be in message.json — raw input never reaches a path join. */
|
|
1089
|
+
function handleMessageImage(id: string, file: string): Response {
|
|
1090
|
+
if (!/^[0-9]+-[0-9a-f]{6}$/.test(id) || !/^[0-9]+\.(png|jpg|gif|webp)$/.test(file)) return textRes("not found", 404);
|
|
1091
|
+
let meta: Record<string, unknown>;
|
|
1092
|
+
try {
|
|
1093
|
+
meta = JSON.parse(readFileSync(`${ownerMessagesDir()}/${id}/message.json`, "utf8")) as Record<string, unknown>;
|
|
1094
|
+
} catch {
|
|
1095
|
+
return textRes("not found", 404);
|
|
1096
|
+
}
|
|
1097
|
+
const names = Array.isArray(meta.images) ? meta.images.filter((n): n is string => typeof n === "string") : [];
|
|
1098
|
+
if (!names.includes(file)) return textRes("not found", 404);
|
|
1099
|
+
try {
|
|
1100
|
+
return new Response(readFileSync(`${ownerMessagesDir()}/${id}/${file}`), {
|
|
1101
|
+
headers: { "content-type": IMAGE_MIME[file.slice(file.lastIndexOf(".") + 1)] ?? "application/octet-stream" },
|
|
1102
|
+
});
|
|
1103
|
+
} catch {
|
|
1104
|
+
return textRes("not found", 404);
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
function handleUnlock(cfg: Config, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
|
|
822
1109
|
const minutes = fields.minutes ?? "";
|
|
823
|
-
if (minutes !== "" && !/^\d+$/.test(minutes)) return textRes("minutes must be a number", 400);
|
|
1110
|
+
if (minutes !== "" && !/^\d+$/.test(minutes)) return wantsJson ? jsonFail("minutes must be a number", 400) : textRes("minutes must be a number", 400);
|
|
824
1111
|
const result = chatUnlock(minutes === "" ? "unlock" : `unlock ${minutes}`, cfg, `ui:${login}`, "ui");
|
|
825
|
-
if (!result.applied) return redirect("
|
|
1112
|
+
if (!result.applied) return wantsJson ? jsonFail("Refused — chat unlock is off", 400) : redirect(sentTo(fields.tab ?? "", "sent=unlock-off"));
|
|
826
1113
|
mkdirSync(stateDirPath(), { recursive: true });
|
|
827
1114
|
appendFileSync(
|
|
828
1115
|
inboxPath(),
|
|
829
1116
|
`${JSON.stringify({ ts: nowSec(), kind: "unlock", minutes: result.minutes, until: result.until, login })}\n`,
|
|
830
1117
|
);
|
|
831
|
-
return
|
|
1118
|
+
if (wantsJson) return jsonSent("unlock", receiptText("unlock", new URLSearchParams({ minutes: String(result.minutes) })));
|
|
1119
|
+
return redirect(sentTo(fields.tab ?? "", `sent=unlock&minutes=${result.minutes}`));
|
|
832
1120
|
}
|
|
833
1121
|
|
|
834
|
-
function handleLock(cfg: Config, login: string): Response {
|
|
1122
|
+
function handleLock(cfg: Config, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
|
|
835
1123
|
const result = chatUnlock("lock", cfg, `ui:${login}`, "ui");
|
|
836
|
-
if (!result.applied) return redirect("
|
|
1124
|
+
if (!result.applied) return wantsJson ? jsonFail("Refused — chat unlock is off", 400) : redirect(sentTo(fields.tab ?? "", "sent=unlock-off"));
|
|
837
1125
|
mkdirSync(stateDirPath(), { recursive: true });
|
|
838
1126
|
appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), kind: "lock", login })}\n`);
|
|
839
|
-
return
|
|
1127
|
+
if (wantsJson) return jsonSent("lock", receiptText("lock", new URLSearchParams()));
|
|
1128
|
+
return redirect(sentTo(fields.tab ?? "", "sent=lock"));
|
|
840
1129
|
}
|
|
841
1130
|
|
|
842
1131
|
const TIERS: readonly Tier[] = ["strict", "opinionated", "full"];
|
|
@@ -844,14 +1133,15 @@ const TIERS: readonly Tier[] = ["strict", "opinionated", "full"];
|
|
|
844
1133
|
// Autonomy tier from the phone page (plan 20261025_1940 P3): behind the same auth as every other
|
|
845
1134
|
// route, written by the core chatTier with the owner's tapped name; a bad name is a 400 before
|
|
846
1135
|
// the core is called, and the chat gate off redirects to the plain-words note like unlock/lock.
|
|
847
|
-
function handleTier(cfg: Config, fields: Record<string, string>, login: string): Response {
|
|
1136
|
+
function handleTier(cfg: Config, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
|
|
848
1137
|
const name = (fields.tier ?? "").trim().toLowerCase();
|
|
849
|
-
if (!(TIERS as readonly string[]).includes(name)) return textRes("tier must be strict, opinionated or full", 400);
|
|
1138
|
+
if (!(TIERS as readonly string[]).includes(name)) return wantsJson ? jsonFail("tier must be strict, opinionated or full", 400) : textRes("tier must be strict, opinionated or full", 400);
|
|
850
1139
|
const result = chatTier(`tier ${name}`, cfg, `ui:${login}`, "ui");
|
|
851
|
-
if (!result.applied) return redirect("
|
|
1140
|
+
if (!result.applied) return wantsJson ? jsonFail("Refused — chat unlock is off", 400) : redirect(sentTo(fields.tab ?? "", "sent=unlock-off"));
|
|
852
1141
|
mkdirSync(stateDirPath(), { recursive: true });
|
|
853
1142
|
appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), kind: "tier", tier: result.tier, login })}\n`);
|
|
854
|
-
return
|
|
1143
|
+
if (wantsJson) return jsonSent("tier");
|
|
1144
|
+
return redirect(sentTo(fields.tab ?? "", `sent=tier&tier=${result.tier}`));
|
|
855
1145
|
}
|
|
856
1146
|
|
|
857
1147
|
// ---- queue reorder (plan P4): the owner drags a card; INDEX.md is rewritten atomically ----
|
|
@@ -914,7 +1204,7 @@ function reorderedIndexText(index: string, order: string[], openPaths: ReadonlyS
|
|
|
914
1204
|
return parts.join("\n");
|
|
915
1205
|
}
|
|
916
1206
|
|
|
917
|
-
function handleReorder(cfg: Config, fields: Record<string, string>, login: string): Response {
|
|
1207
|
+
function handleReorder(cfg: Config, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
|
|
918
1208
|
const index = cfg.paths.queue_index;
|
|
919
1209
|
const order = (fields.order ?? "")
|
|
920
1210
|
.split("\n")
|
|
@@ -925,32 +1215,37 @@ function handleReorder(cfg: Config, fields: Record<string, string>, login: strin
|
|
|
925
1215
|
.map(l => l.trim())
|
|
926
1216
|
.filter(l => l.length > 0);
|
|
927
1217
|
const moved = (fields.moved ?? "").trim();
|
|
1218
|
+
// The page's drag and arrow buttons send this over fetch (accept: application/json) and read
|
|
1219
|
+
// the JSON reply; a no-JS form post still gets the 303. Errors follow the same split.
|
|
1220
|
+
const fail = (error: string, status: number): Response =>
|
|
1221
|
+
wantsJson ? Response.json({ ok: false, error }, { status }) : textRes(error, status);
|
|
928
1222
|
// One source of truth for the reorderable set: the open plans, the same list queueRows renders.
|
|
929
1223
|
const openPaths = activePlans(index)
|
|
930
1224
|
.filter(p => p.status === "open")
|
|
931
1225
|
.map(p => p.file);
|
|
932
|
-
if (!moved || !order.length) return
|
|
1226
|
+
if (!moved || !order.length) return fail("order and moved are required", 400);
|
|
933
1227
|
// 400: the posted order must be exactly the open plans the page renders now — no adds, drops or duplicates.
|
|
934
|
-
if (new Set(order).size !== order.length) return
|
|
1228
|
+
if (new Set(order).size !== order.length) return fail("order lists a plan more than once", 400);
|
|
935
1229
|
const sortedOrder = [...order].sort();
|
|
936
1230
|
const sortedOpen = [...openPaths].sort();
|
|
937
1231
|
const sameSet = order.length === openPaths.length && sortedOrder.every((p, i) => p === sortedOpen[i]);
|
|
938
|
-
if (!sameSet) return
|
|
1232
|
+
if (!sameSet) return fail("order is not exactly the plans now on the page", 400);
|
|
939
1233
|
// 409: the order the page was rendered with must still be the open plans' current order.
|
|
940
1234
|
const stale = before.length !== openPaths.length || before.some((p, i) => p !== openPaths[i]);
|
|
941
|
-
if (stale) return
|
|
1235
|
+
if (stale) return fail("the queue changed since the page loaded — reload and drag again", 409);
|
|
942
1236
|
const from = openPaths.indexOf(moved);
|
|
943
1237
|
const to = order.indexOf(moved);
|
|
944
|
-
if (from === -1 || to === -1) return
|
|
1238
|
+
if (from === -1 || to === -1) return fail("moved is not one of the page's plans", 400);
|
|
945
1239
|
const newText = reorderedIndexText(index, order, new Set(openPaths));
|
|
946
|
-
if (newText === null) return
|
|
1240
|
+
if (newText === null) return fail("the queue index no longer lists every open plan", 400);
|
|
947
1241
|
// Atomic write: a torn INDEX.md would break every reader, so temp file in the same dir + rename.
|
|
948
1242
|
const tmp = `${index}.${randomUUID().slice(0, 8)}.tmp`;
|
|
949
1243
|
writeFileSync(tmp, newText);
|
|
950
1244
|
renameSync(tmp, index);
|
|
951
1245
|
mkdirSync(stateDirPath(), { recursive: true });
|
|
952
1246
|
appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), kind: "reorder", plan: moved, from: from + 1, to: to + 1, login })}\n`);
|
|
953
|
-
return
|
|
1247
|
+
if (wantsJson) return Response.json({ ok: true, to: to + 1 });
|
|
1248
|
+
return redirect(sentTo(fields.tab ?? "", `sent=reorder&to=${to + 1}`));
|
|
954
1249
|
}
|
|
955
1250
|
|
|
956
1251
|
/** 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. */
|
|
@@ -1003,23 +1298,38 @@ export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
|
|
|
1003
1298
|
res = textRes("forbidden: origin is not this page", 403);
|
|
1004
1299
|
code = 403;
|
|
1005
1300
|
} else if (req.method === "GET" && url.pathname === "/") {
|
|
1301
|
+
sweepOwnerMessages(nowSec());
|
|
1006
1302
|
res = pageRes(cfg, source, url.searchParams);
|
|
1007
1303
|
code = 200;
|
|
1008
|
-
} else if (req.method === "
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
} else if (req.method === "POST" && url.pathname === "/unlock") {
|
|
1012
|
-
res = handleUnlock(cfg, await fieldsOf(req), login);
|
|
1013
|
-
code = res.status;
|
|
1014
|
-
} else if (req.method === "POST" && url.pathname === "/lock") {
|
|
1015
|
-
res = handleLock(cfg, login);
|
|
1016
|
-
code = res.status;
|
|
1017
|
-
} else if (req.method === "POST" && url.pathname === "/tier") {
|
|
1018
|
-
res = handleTier(cfg, await fieldsOf(req), login);
|
|
1019
|
-
code = res.status;
|
|
1020
|
-
} else if (req.method === "POST" && url.pathname === "/reorder") {
|
|
1021
|
-
res = handleReorder(cfg, await fieldsOf(req), login);
|
|
1304
|
+
} else if (req.method === "GET" && url.pathname.startsWith("/message-image/")) {
|
|
1305
|
+
const mim = /^\/message-image\/([^/]+)\/([^/]+)$/.exec(url.pathname);
|
|
1306
|
+
res = mim ? handleMessageImage(mim[1]!, mim[2]!) : textRes("not found", 404);
|
|
1022
1307
|
code = res.status;
|
|
1308
|
+
} else if (req.method === "POST") {
|
|
1309
|
+
// The page's script asks for JSON on every POST (P11b); a no-JS form post gets today's 303s.
|
|
1310
|
+
const wantsJson = (req.headers.get("accept") ?? "").includes("application/json");
|
|
1311
|
+
if (url.pathname === "/message") {
|
|
1312
|
+
res = await handleMessage(req, login, wantsJson);
|
|
1313
|
+
code = res.status;
|
|
1314
|
+
} else if (url.pathname === "/answer") {
|
|
1315
|
+
res = handleAnswer(cfg, source, await fieldsOf(req), login, wantsJson);
|
|
1316
|
+
code = res.status;
|
|
1317
|
+
} else if (url.pathname === "/unlock") {
|
|
1318
|
+
res = handleUnlock(cfg, await fieldsOf(req), login, wantsJson);
|
|
1319
|
+
code = res.status;
|
|
1320
|
+
} else if (url.pathname === "/lock") {
|
|
1321
|
+
res = handleLock(cfg, await fieldsOf(req), login, wantsJson);
|
|
1322
|
+
code = res.status;
|
|
1323
|
+
} else if (url.pathname === "/tier") {
|
|
1324
|
+
res = handleTier(cfg, await fieldsOf(req), login, wantsJson);
|
|
1325
|
+
code = res.status;
|
|
1326
|
+
} else if (url.pathname === "/reorder") {
|
|
1327
|
+
res = handleReorder(cfg, await fieldsOf(req), login, wantsJson);
|
|
1328
|
+
code = res.status;
|
|
1329
|
+
} else {
|
|
1330
|
+
res = textRes("not found", 404);
|
|
1331
|
+
code = 404;
|
|
1332
|
+
}
|
|
1023
1333
|
} else {
|
|
1024
1334
|
res = textRes("not found", 404);
|
|
1025
1335
|
code = 404;
|