neurastream 0.3.18 → 0.3.21
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 +88 -490
- package/package.json +1 -1
- package/src/adapters/index.ts +3 -2
- package/src/adapters/omp/adapter.ts +2 -1
- package/src/adapters/omp/auto-close.ts +64 -0
- package/src/adapters/omp/chat-commands.ts +161 -0
- package/src/adapters/omp/inbox.ts +221 -0
- package/src/adapters/omp/index.ts +138 -1050
- package/src/adapters/omp/launch.ts +35 -9
- package/src/adapters/omp/rate-limit-controller.ts +196 -0
- package/src/adapters/omp/rollover-controller.ts +334 -0
- package/src/adapters/omp/types.ts +143 -0
- package/src/cli/claim.ts +1 -3
- package/src/cli/commands.ts +33 -2
- package/src/cli/dispatch.ts +55 -30
- package/src/cli/guard.ts +0 -3
- package/src/cli/incident.ts +2 -2
- package/src/cli/metrics.ts +1 -1
- package/src/cli/recall.ts +6 -8
- package/src/cli/results-build.ts +2 -4
- package/src/cli/workspace.ts +13 -5
- package/src/core/adapter.ts +16 -0
- package/src/core/autonomy.ts +24 -21
- package/src/core/blockers.ts +326 -30
- package/src/core/file-lock.ts +71 -12
- package/src/core/guards/plan-edit.ts +338 -0
- package/src/core/guards/planner.ts +70 -0
- package/src/core/guards/review.ts +391 -0
- package/src/core/guards/spawn.ts +699 -0
- package/src/core/guards/state.ts +581 -0
- package/src/core/guards/stop.ts +235 -0
- package/src/core/guards/tool.ts +541 -0
- package/src/core/guards.ts +12 -2661
- package/src/core/incidents.ts +134 -99
- package/src/core/machine-guard.ts +23 -5
- package/src/core/main-start.ts +11 -9
- package/src/core/mr-sweep.ts +4 -2
- package/src/core/notify.ts +15 -15
- package/src/core/owner-log.ts +19 -17
- package/src/core/owner-topics.ts +38 -48
- package/src/core/owner-ui/auth.ts +164 -0
- package/src/core/owner-ui/data.ts +437 -0
- package/src/core/owner-ui/handlers.ts +250 -0
- package/src/core/owner-ui/messages.ts +209 -0
- package/src/core/owner-ui/render.ts +714 -0
- package/src/core/owner-ui/results.ts +266 -0
- package/src/core/owner-ui/server.ts +142 -0
- package/src/core/owner-ui.ts +11 -2118
- package/src/core/page-notes.ts +25 -0
- package/src/core/pages.ts +452 -78
- package/src/core/plan-approval.ts +24 -26
- package/src/core/queue/lib.ts +170 -137
- package/src/core/queue-cancel.ts +29 -15
- package/src/core/queue-check.ts +5 -7
- package/src/core/queue-close.ts +54 -29
- package/src/core/queue-finished.ts +9 -10
- package/src/core/queue-migrate.ts +1 -3
- package/src/core/queue-trim.ts +2 -4
- package/src/core/results.ts +0 -2
- package/src/core/rollover.ts +2 -3
- package/src/core/secret-redact.ts +65 -14
- package/src/core/tailscale.ts +79 -3
- package/src/core/team-client.ts +18 -6
- package/src/core/uninstall.ts +2 -0
- package/src/core/watch.ts +3 -2
- package/src/core/queue/env.ts +0 -14
package/src/core/owner-ui.ts
CHANGED
|
@@ -1,2118 +1,11 @@
|
|
|
1
|
-
// Owner phone page
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
import os from "node:os";
|
|
13
|
-
import { basename, resolve } from "node:path";
|
|
14
|
-
import type { RunSource } from "./adapter.ts";
|
|
15
|
-
import { chatTier, currentTier, type Tier } from "./autonomy.ts";
|
|
16
|
-
import { summaryHolder, postTeamAnswer, teamPlans, teamViews, type TeamEarlier, type TeamPlanRow, type TeamView } from "./team-client.ts";
|
|
17
|
-
import type { Unreachable } from "./claims.ts";
|
|
18
|
-
import type { Config } from "./config.ts";
|
|
19
|
-
import { nowSec, strftime } from "./clock.ts";
|
|
20
|
-
import { cpuCount } from "./host.ts";
|
|
21
|
-
import { dismissIncident, isFindingKind, openIncidents } from "./incidents.ts";
|
|
22
|
-
import { byText, knowledgeManifest, readKnowledgeTopicFile, urlField, urlValue, type KnowledgeEntry } from "./knowledge.ts";
|
|
23
|
-
import { isBusy } from "./file-lock.ts";
|
|
24
|
-
import { log, MAIN_ID_RE } from "./guards.ts";
|
|
25
|
-
import { publishedPages } from "./pages-expiry.ts";
|
|
26
|
-
import { readMetricEvents } from "./metrics.ts";
|
|
27
|
-
import { activePlans, chatUnlock, dependencyOrderProblems, expandHome, gitTop, stateDirPath, unlockPath, writeIndex, type Plan } from "./queue/lib.ts";
|
|
28
|
-
import { featuresReport, gatherTags, loadPlans, releasesReport, type FeaturesReport, type ReleaseRow, type ReleaseSideStats, type ReleasesReport } from "./results.ts";
|
|
29
|
-
import type { Tailscale } from "./tailscale.ts";
|
|
30
|
-
import { recheckHolds, staleFiles, type HoldRunner } from "./waiting-check.ts";
|
|
31
|
-
|
|
32
|
-
export const ANSWER_MAX = 2000;
|
|
33
|
-
const MESSAGE_MAX = 4000;
|
|
34
|
-
const MESSAGE_IMAGES_MAX = 4;
|
|
35
|
-
const MESSAGE_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
|
|
36
|
-
/** How long the page keeps an owner message: 12 h, then the sweep removes it (owner, 2026-10-25 19:10). */
|
|
37
|
-
export const OWNER_MESSAGE_KEEP_SEC = 43200;
|
|
38
|
-
const REFRESH_SEC = 20;
|
|
39
|
-
/** The page's tabs, in pill order; anything else in `?tab=` renders Now. */
|
|
40
|
-
const TABS: [string, string][] = [["now", "Now"], ["queue", "Queue"], ["agents", "Agents"], ["spend", "Spend"], ["knowledge", "Base"], ["results", "Results"]];
|
|
41
|
-
const TAB_IDS = TABS.map(([id]) => id);
|
|
42
|
-
// Tailscale hands out addresses from 100.64.0.0/10 (CGNAT) and its own ULA /48 for IPv6.
|
|
43
|
-
const TAILNET6 = /^fd7a:115c:a1e0:/i;
|
|
44
|
-
|
|
45
|
-
/** The slice of Bun's server the page needs: the peer address of a request. Bun.serve's return satisfies it. */
|
|
46
|
-
export interface UiHttpServer {
|
|
47
|
-
requestIP(req: Request): { address: string; family: string; port: number } | null;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export interface OwnerUiServer {
|
|
51
|
-
stop(): void;
|
|
52
|
-
hostname: string;
|
|
53
|
-
port: number;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
export interface OwnerUiOptions {
|
|
57
|
-
cfg: Config;
|
|
58
|
-
tailscale: Tailscale;
|
|
59
|
-
source: RunSource;
|
|
60
|
-
/** Bind address. Default: the tailnet address from `tailscale ip -4`. Tests bind 127.0.0.1. */
|
|
61
|
-
hostname?: string;
|
|
62
|
-
/** Bind port. Default: workspace.port; 0 picks a free port (tests). */
|
|
63
|
-
port?: number;
|
|
64
|
-
/** The peer address of a request. Default: the socket address. Tests inject fixture peers. */
|
|
65
|
-
peerOf?: (req: Request, server: UiHttpServer) => string;
|
|
66
|
-
/** Starts a background Results build. Default: spawnResultsBuild. Tests inject a recorder. */
|
|
67
|
-
resultsBuild?: ResultsBuild;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
export type Auth = { ok: true; login: string } | { ok: false; why: string };
|
|
71
|
-
|
|
72
|
-
/** The inbox the page appends answers to and the adapter delivers from: under the queue state dir. */
|
|
73
|
-
export function inboxPath(): string {
|
|
74
|
-
return `${stateDirPath()}/owner-inbox.jsonl`;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
export function isLoopback(peer: string): boolean {
|
|
78
|
-
return peer === "::1" || peer === "localhost" || peer.startsWith("127.");
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
export function isTailnet(peer: string): boolean {
|
|
82
|
-
const v4 = /^(\d+)\.(\d+)\./.exec(peer);
|
|
83
|
-
if (v4) return v4[1] === "100" && Number(v4[2]) >= 64 && Number(v4[2]) <= 127;
|
|
84
|
-
return TAILNET6.test(peer);
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/** Serve only the owner's phone: a tailnet peer that is not this machine and not loopback, whose tailscale whois login equals workspace.owner_login. Everything else is a 403. With `workspace.allow_this_machine`, this machine itself (loopback and its own tailnet IP) is served as the owner too — any local process can then press the buttons. */
|
|
88
|
-
export function authenticate(cfg: Config, tailscale: Tailscale, peer: string): Auth {
|
|
89
|
-
if (!cfg.workspace.owner_login) return { ok: false, why: "workspace.owner_login is empty" };
|
|
90
|
-
if (cfg.workspace.allow_this_machine && (isLoopback(peer) || peer === tailscale.ip4())) return { ok: true, login: cfg.workspace.owner_login };
|
|
91
|
-
if (isLoopback(peer)) return { ok: false, why: "loopback peer" };
|
|
92
|
-
if (!isTailnet(peer)) return { ok: false, why: "peer is not a tailnet address" };
|
|
93
|
-
if (peer === tailscale.ip4()) return { ok: false, why: "this machine's own tailnet address" };
|
|
94
|
-
const login = tailscale.whois(peer);
|
|
95
|
-
if (!login) return { ok: false, why: "tailscale whois failed" };
|
|
96
|
-
if (login !== cfg.workspace.owner_login) return { ok: false, why: "not the owner's login" };
|
|
97
|
-
return { ok: true, login };
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
// ---- sections ----
|
|
101
|
-
|
|
102
|
-
function esc(s: string): string {
|
|
103
|
-
return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
// ---- page data: one pure typed-row builder per source; rendering reads only these ----
|
|
107
|
-
|
|
108
|
-
export interface QuestionRow {
|
|
109
|
-
plan: string;
|
|
110
|
-
title: string;
|
|
111
|
-
repo: string;
|
|
112
|
-
waitingLine: string;
|
|
113
|
-
/** What to do, from the WAITING line. */
|
|
114
|
-
waitingAsk: string;
|
|
115
|
-
/** What stays stuck until then, or null. */
|
|
116
|
-
waitingBlocked: string | null;
|
|
117
|
-
/** Why Main cannot do it, or null. */
|
|
118
|
-
waitingWhy: string | null;
|
|
119
|
-
/** Titles of other open plans whose Waits on names this plan. */
|
|
120
|
-
unblocks: string[];
|
|
121
|
-
goal: string[];
|
|
122
|
-
waitingMin: number;
|
|
123
|
-
/** The last answer this plan already got (from the owner inbox, so the card can say so; for a team plan, the newest server answer). */
|
|
124
|
-
answered: { answer: string; at: number; login?: string } | null;
|
|
125
|
-
/** The team this card belongs to; `plan` is then the server plan id, not a local path (P4). */
|
|
126
|
-
team?: string;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
/** The newest inbox record that carries an answer for this plan, if any. A missing or torn inbox is simply "no answer". */
|
|
130
|
-
function lastAnswerFor(plan: string): { answer: string; at: number } | null {
|
|
131
|
-
let lines: string[];
|
|
132
|
-
try {
|
|
133
|
-
lines = readFileSync(inboxPath(), "utf8").split("\n");
|
|
134
|
-
} catch {
|
|
135
|
-
return null;
|
|
136
|
-
}
|
|
137
|
-
for (let i = lines.length - 1; i >= 0; i--) {
|
|
138
|
-
const line = lines[i]!.trim();
|
|
139
|
-
if (!line) continue;
|
|
140
|
-
try {
|
|
141
|
-
const rec = JSON.parse(line) as Record<string, unknown>;
|
|
142
|
-
if (rec.plan === plan && typeof rec.answer === "string" && rec.answer) return { answer: rec.answer, at: Number(rec.ts) || 0 };
|
|
143
|
-
} catch {}
|
|
144
|
-
}
|
|
145
|
-
return null;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
export interface AgentRow {
|
|
149
|
-
id: string;
|
|
150
|
-
model: string;
|
|
151
|
-
detail: string;
|
|
152
|
-
minutes: number;
|
|
153
|
-
status: string;
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
export interface QueueRow {
|
|
157
|
-
repo: string;
|
|
158
|
-
file: string;
|
|
159
|
-
title: string;
|
|
160
|
-
status: string;
|
|
161
|
-
waiting: boolean;
|
|
162
|
-
/** `Summary:` header, else the first Goal bullet with a leading Owner/INCIDENT prefix cut off. */
|
|
163
|
-
summary: string | null;
|
|
164
|
-
/** The Main id holding this plan's claim, else null (P5 multi-main). */
|
|
165
|
-
holder: string | null;
|
|
166
|
-
/** Chip text: waits you, waits on a plan, not started, phase K of N, or all N done. */
|
|
167
|
-
state: string;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
export interface CiRow {
|
|
171
|
-
mr: string;
|
|
172
|
-
tries: number;
|
|
173
|
-
ts: number;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
export interface IncidentRow {
|
|
177
|
-
id: string;
|
|
178
|
-
kind: string;
|
|
179
|
-
summary: string;
|
|
180
|
-
count: number;
|
|
181
|
-
/** Main's latest written reason for a finding incident; null when none or not a finding. */
|
|
182
|
-
proposal: string | null;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
/** A markdown table from the ranking board plus every non-table line, kept in order. */
|
|
186
|
-
export interface ScoresData {
|
|
187
|
-
header: string[];
|
|
188
|
-
rows: string[][];
|
|
189
|
-
text: string[];
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
export interface MachineRow {
|
|
193
|
-
freeGb: number;
|
|
194
|
-
diskMin: number;
|
|
195
|
-
load: number;
|
|
196
|
-
loadMax: number;
|
|
197
|
-
cores: number;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
export function questionRows(cfg: Config, run?: HoldRunner): QuestionRow[] {
|
|
201
|
-
const now = Date.now();
|
|
202
|
-
const plans = activePlans(cfg.paths.queue_index);
|
|
203
|
-
const stale = staleFiles(recheckHolds(cfg, plans, run));
|
|
204
|
-
return plans
|
|
205
|
-
.filter(p => p.waiting && p.status === "open" && p.waitingLine && !stale.has(p.file))
|
|
206
|
-
.map(p => {
|
|
207
|
-
let waitingMin = 0;
|
|
208
|
-
try {
|
|
209
|
-
waitingMin = Math.max(0, Math.round((now - statSync(p.file).mtimeMs) / 60_000));
|
|
210
|
-
} catch {}
|
|
211
|
-
return {
|
|
212
|
-
plan: p.file,
|
|
213
|
-
title: p.title,
|
|
214
|
-
repo: basename(p.repo),
|
|
215
|
-
waitingLine: p.waitingLine ?? "",
|
|
216
|
-
waitingAsk: p.waitingAsk ?? p.waitingLine ?? "",
|
|
217
|
-
waitingBlocked: p.waitingBlocked,
|
|
218
|
-
waitingWhy: p.waitingWhy,
|
|
219
|
-
unblocks: plans.filter(o => o.status === "open" && o.file !== p.file && o.waitsOn.includes(p.file)).map(o => o.title),
|
|
220
|
-
goal: p.goal,
|
|
221
|
-
waitingMin,
|
|
222
|
-
answered: lastAnswerFor(p.file),
|
|
223
|
-
};
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
export function agentRows(cfg: Config, source: RunSource): AgentRow[] {
|
|
228
|
-
const cut = nowSec() - cfg.ledger.default_hours * 3600;
|
|
229
|
-
return source
|
|
230
|
-
.listRuns(cut)
|
|
231
|
-
.filter(r => r.status === "running" || r.status === "waiting")
|
|
232
|
-
.map(r => ({
|
|
233
|
-
id: r.id,
|
|
234
|
-
model: r.model.slice(r.model.lastIndexOf("/") + 1),
|
|
235
|
-
detail: r.statusDetail,
|
|
236
|
-
minutes: r.startedAt === null ? 0 : Math.max(0, Math.round((nowSec() - r.startedAt) / 60)),
|
|
237
|
-
status: r.status,
|
|
238
|
-
}));
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
/** Cut a leading `Owner (…):` or `INCIDENT <id>` prefix off a Goal bullet used as the card line. */
|
|
242
|
-
function goalSummary(line: string): string {
|
|
243
|
-
let s = line.trim();
|
|
244
|
-
for (;;) {
|
|
245
|
-
const next = s.replace(/^Owner\s*\([^)]*\):\s*/, "").replace(/^INCIDENT\s+\S+\.?\s*/, "").trim();
|
|
246
|
-
if (next === s) return s;
|
|
247
|
-
s = next;
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
function queueState(p: Plan, plans: Plan[]): string {
|
|
252
|
-
if (p.waiting) return "waits you";
|
|
253
|
-
const target = p.waitsOn[0];
|
|
254
|
-
if (target) {
|
|
255
|
-
const title = plans.find(w => w.file === target)?.title ?? target.split("/").pop()?.replace(/\.md$/, "") ?? target;
|
|
256
|
-
return `waits on ${title}`;
|
|
257
|
-
}
|
|
258
|
-
const { done, total } = p.phases;
|
|
259
|
-
if (done === total && total > 0) return `all ${total} done · checking`;
|
|
260
|
-
if (!p.started) return `not started · 0/${total}`;
|
|
261
|
-
return `phase ${Math.min(done + 1, total)} of ${total}`;
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
export function queueRows(cfg: Config, views?: Map<string, TeamView | Unreachable>): QueueRow[] {
|
|
265
|
-
const plans = activePlans(cfg.paths.queue_index).filter(p => p.status === "open");
|
|
266
|
-
const claims = summaryHolder(cfg, {}, views);
|
|
267
|
-
return plans.map(p => {
|
|
268
|
-
const holder = claims.holder(p.file);
|
|
269
|
-
return {
|
|
270
|
-
repo: basename(p.repo),
|
|
271
|
-
file: p.file,
|
|
272
|
-
title: p.title,
|
|
273
|
-
status: p.status ?? "?",
|
|
274
|
-
waiting: p.waiting,
|
|
275
|
-
summary: p.summary ?? (goalSummary(p.goal[0] ?? "") || null),
|
|
276
|
-
state: queueState(p, plans),
|
|
277
|
-
holder: holder === null ? null : "unreachable" in holder ? "team server unreachable" : holder.main,
|
|
278
|
-
};
|
|
279
|
-
});
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
/** One team's card on the phone page: its plans as queue rows and its open WAITING lines. */
|
|
283
|
-
export interface TeamSection {
|
|
284
|
-
name: string;
|
|
285
|
-
server: string;
|
|
286
|
-
/** False when the team server did not answer: the card says so instead of listing plans. */
|
|
287
|
-
reachable: boolean;
|
|
288
|
-
rows: QueueRow[];
|
|
289
|
-
questions: QuestionRow[];
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
/**
|
|
293
|
-
* The team half of the phone page (P4): each team's already-read view mapped to the page's own
|
|
294
|
-
* row types, so the render stays one shape. A plan is a QueueRow whose `file` is the server id
|
|
295
|
-
* (team order is not INDEX order, so no drag and no /reorder) and whose state is queueState over
|
|
296
|
-
* the team's own parsed plans; each open plan with a WAITING line is a QuestionRow whose newest
|
|
297
|
-
* server answer fills `answered`. Sends nothing.
|
|
298
|
-
*/
|
|
299
|
-
export function teamSections(cfg: Config, views: Map<string, TeamView | Unreachable>): TeamSection[] {
|
|
300
|
-
return cfg.teams.map(team => {
|
|
301
|
-
const view = views.get(team.name);
|
|
302
|
-
if (view === undefined || "unreachable" in view) return { name: team.name, server: team.server, reachable: false, rows: [], questions: [] };
|
|
303
|
-
return teamSection(team.name, team.server, teamPlans(cfg, team, view));
|
|
304
|
-
});
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
/** One reachable team's card from its parsed plans: the phone page and the team page both build it here. */
|
|
308
|
-
export function teamSection(name: string, server: string, plans: TeamPlanRow[]): TeamSection {
|
|
309
|
-
const parsed = plans.map(p => p.plan);
|
|
310
|
-
const rows: QueueRow[] = plans.map(p => ({
|
|
311
|
-
repo: p.relPath,
|
|
312
|
-
file: p.id,
|
|
313
|
-
title: p.plan.title,
|
|
314
|
-
status: p.plan.status ?? "?",
|
|
315
|
-
waiting: p.plan.waiting,
|
|
316
|
-
summary: p.plan.summary ?? (goalSummary(p.plan.goal[0] ?? "") || null),
|
|
317
|
-
holder: p.holder ? `${p.holder.main} (${p.holder.login})` : null,
|
|
318
|
-
state: queueState(p.plan, parsed),
|
|
319
|
-
}));
|
|
320
|
-
const questions: QuestionRow[] = plans
|
|
321
|
-
.filter(p => p.plan.status === "open" && p.plan.waiting && p.plan.waitingLine)
|
|
322
|
-
.map(p => {
|
|
323
|
-
const first = p.answered;
|
|
324
|
-
return {
|
|
325
|
-
plan: p.id,
|
|
326
|
-
team: name,
|
|
327
|
-
title: p.plan.title,
|
|
328
|
-
repo: p.relPath,
|
|
329
|
-
waitingLine: p.plan.waitingLine ?? "",
|
|
330
|
-
waitingAsk: p.plan.waitingAsk ?? p.plan.waitingLine ?? "",
|
|
331
|
-
waitingBlocked: p.plan.waitingBlocked,
|
|
332
|
-
waitingWhy: p.plan.waitingWhy,
|
|
333
|
-
unblocks: [],
|
|
334
|
-
goal: p.plan.goal,
|
|
335
|
-
waitingMin: 0,
|
|
336
|
-
answered: first ? { answer: first.answer, at: first.time, login: first.login } : null,
|
|
337
|
-
};
|
|
338
|
-
});
|
|
339
|
-
return { name, server, reachable: true, rows, questions };
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
export function ciRows(cfg: Config): CiRow[] {
|
|
343
|
-
return readMetricEvents(cfg)
|
|
344
|
-
.filter(e => e.type === "ci")
|
|
345
|
-
.slice(-10)
|
|
346
|
-
.reverse()
|
|
347
|
-
.map(e => ({ mr: String(e.mr), tries: Number(e.tries), ts: Number(e.ts) }));
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
export function incidentRows(cfg: Config): IncidentRow[] {
|
|
351
|
-
return openIncidents(cfg).map(i => ({
|
|
352
|
-
id: i.id,
|
|
353
|
-
kind: i.kind,
|
|
354
|
-
summary: i.summary,
|
|
355
|
-
count: i.count,
|
|
356
|
-
proposal: isFindingKind(i.kind) ? (i.proposal?.why ?? null) : null,
|
|
357
|
-
}));
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
export function scoresData(cfg: Config): ScoresData {
|
|
361
|
-
const out: ScoresData = { header: [], rows: [], text: [] };
|
|
362
|
-
for (const raw of readFileSync(cfg.paths.ranking_board, "utf8").split("\n")) {
|
|
363
|
-
const line = raw.trim();
|
|
364
|
-
if (line.startsWith("|") && line.endsWith("|")) {
|
|
365
|
-
const cells = line.slice(1, -1).split("|").map(c => c.trim());
|
|
366
|
-
if (cells.every(c => /^:?-{2,}:?$/.test(c))) continue;
|
|
367
|
-
if (!out.header.length) out.header = cells;
|
|
368
|
-
else out.rows.push(cells);
|
|
369
|
-
} else if (line) {
|
|
370
|
-
out.text.push(line);
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
return out;
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
export function machineRow(cfg: Config): MachineRow {
|
|
377
|
-
const st = statfsSync(expandHome(cfg.machine.disk_path));
|
|
378
|
-
const freeGb = (Number(st.bavail) * Number(st.bsize)) / 1e9;
|
|
379
|
-
const load = os.loadavg()[0] ?? 0;
|
|
380
|
-
const cores = cpuCount();
|
|
381
|
-
const loadMax = cfg.machine.load_max > 0 ? cfg.machine.load_max : cores + cfg.machine.load_over_cores;
|
|
382
|
-
return { freeGb, diskMin: cfg.machine.disk_min_gb, load, loadMax, cores };
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
/** The numbers behind the top tiles: everything in the last 24 h plus the open-plan count. */
|
|
386
|
-
export interface NowStats {
|
|
387
|
-
/** Total list-price spend over the last 24 h. */
|
|
388
|
-
spend24: number;
|
|
389
|
-
/** The "main" kind's share of spend24. */
|
|
390
|
-
mainSpend: number;
|
|
391
|
-
/** The "sub" kind's share of spend24. */
|
|
392
|
-
agentSpend: number;
|
|
393
|
-
/** Runs seen in the last 24 h. */
|
|
394
|
-
runs24: number;
|
|
395
|
-
/** Of those, the ones still running. */
|
|
396
|
-
running: number;
|
|
397
|
-
/** Of those, the ones that died. */
|
|
398
|
-
died: number;
|
|
399
|
-
/** Spend per hour over the last 24 h: 24 buckets, oldest → newest. */
|
|
400
|
-
spendByHour: number[];
|
|
401
|
-
/** Runs started per hour over the last 24 h: 24 buckets, oldest → newest. */
|
|
402
|
-
runsByHour: number[];
|
|
403
|
-
/** Spend and run count per short model name (after the last /), costliest first. */
|
|
404
|
-
byModel: { model: string; spend: number; runs: number }[];
|
|
405
|
-
/** Open plans in INDEX.md. */
|
|
406
|
-
openPlans: number;
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
/**
|
|
410
|
-
* Pure tile math over `source.listRuns(now - 86400)`: a run is in the window when its
|
|
411
|
-
* bucket time — `startedAt`, else `lastWriteAt` — is newer than exactly 24 h ago, and it
|
|
412
|
-
* counts in the hourly bucket of that time. The run source pre-filters by its own mtime,
|
|
413
|
-
* so the strict window check here is the one rule that decides.
|
|
414
|
-
*/
|
|
415
|
-
export function nowStats(cfg: Config, source: RunSource, now: number): NowStats {
|
|
416
|
-
const cut = now - 86400;
|
|
417
|
-
const spendByHour = Array.from({ length: 24 }, () => 0);
|
|
418
|
-
const runsByHour = Array.from({ length: 24 }, () => 0);
|
|
419
|
-
const models = new Map<string, { spend: number; runs: number }>();
|
|
420
|
-
let spend24 = 0;
|
|
421
|
-
let mainSpend = 0;
|
|
422
|
-
let agentSpend = 0;
|
|
423
|
-
let runs24 = 0;
|
|
424
|
-
let running = 0;
|
|
425
|
-
let died = 0;
|
|
426
|
-
for (const r of source.listRuns(cut)) {
|
|
427
|
-
const ts = r.startedAt ?? r.lastWriteAt;
|
|
428
|
-
if (ts <= cut) continue;
|
|
429
|
-
spend24 += r.cost;
|
|
430
|
-
runs24++;
|
|
431
|
-
if (r.kind === "main") mainSpend += r.cost;
|
|
432
|
-
else agentSpend += r.cost;
|
|
433
|
-
if (r.status === "running") running++;
|
|
434
|
-
if (r.status === "died") died++;
|
|
435
|
-
// A future clock (skew) clamps into the newest bucket, never out of the array.
|
|
436
|
-
const hoursAgo = Math.min(23, Math.max(0, Math.floor((now - ts) / 3600)));
|
|
437
|
-
const at = 23 - hoursAgo;
|
|
438
|
-
spendByHour[at]! += r.cost;
|
|
439
|
-
runsByHour[at]! += 1;
|
|
440
|
-
const short = r.model.slice(r.model.lastIndexOf("/") + 1);
|
|
441
|
-
const m = models.get(short) ?? { spend: 0, runs: 0 };
|
|
442
|
-
m.spend += r.cost;
|
|
443
|
-
m.runs += 1;
|
|
444
|
-
models.set(short, m);
|
|
445
|
-
}
|
|
446
|
-
const byModel = [...models.entries()].map(([model, v]) => ({ model, spend: v.spend, runs: v.runs })).sort((a, b) => b.spend - a.spend);
|
|
447
|
-
// The tile counts the open plans the queue card renders; a holder read here would ask every
|
|
448
|
-
// team server a second time on a page that already read one view per team (P4).
|
|
449
|
-
return { spend24, mainSpend, agentSpend, runs24, running, died, spendByHour, runsByHour, byModel, openPlans: activePlans(cfg.paths.queue_index).filter(p => p.status === "open").length };
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
// ---- owner messages (plan P13): a one-way note plus images, kept for 12 h ----
|
|
453
|
-
|
|
454
|
-
/** Where the page stores owner messages: under the queue state dir, one dir per message. */
|
|
455
|
-
function ownerMessagesDir(): string {
|
|
456
|
-
return `${stateDirPath()}/owner-messages`;
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
/** Main ids with a live running.lock in their main state dir (P5 multi-main): the page's picker list and the @-routing target set. */
|
|
460
|
-
export function runningMains(cfg: Config): string[] {
|
|
461
|
-
let dirs: string[];
|
|
462
|
-
try {
|
|
463
|
-
dirs = readdirSync(`${cfg.paths.queue_state}/mains`);
|
|
464
|
-
} catch {
|
|
465
|
-
return [];
|
|
466
|
-
}
|
|
467
|
-
return dirs
|
|
468
|
-
.filter(d => MAIN_ID_RE.test(d) && isBusy(`${cfg.paths.queue_state}/mains/${d}/running.lock`))
|
|
469
|
-
.toSorted();
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
/** Resolves where a message goes (P5 multi-main): an `@<id> ` prefix or the picker's `to` field names one running Main; empty is every Main. A stale target is refused before anything is stored. */
|
|
473
|
-
export function ownerMessageTarget(text: string, cfg: Config, formTo = ""): { to: string } | { refuse: string } {
|
|
474
|
-
const at = /^@([a-z0-9-]{1,24})(?:\s|$)/.exec(text);
|
|
475
|
-
const target = (at ? at[1] : formTo) ?? "";
|
|
476
|
-
if (!target || !MAIN_ID_RE.test(target)) return { to: "" };
|
|
477
|
-
const running = runningMains(cfg);
|
|
478
|
-
if (running.includes(target)) return { to: target };
|
|
479
|
-
return { refuse: `Main ${target} is not running; running: ${running.length ? running.join(", ") : "none"}` };
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
export interface MessageRow {
|
|
483
|
-
id: string;
|
|
484
|
-
ts: number;
|
|
485
|
-
text: string;
|
|
486
|
-
images: string[];
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
/** The image type from the first bytes — PNG, JPEG, GIF or WEBP — never from the client's name or content type. */
|
|
490
|
-
function imageType(bytes: Uint8Array): "png" | "jpeg" | "gif" | "webp" | null {
|
|
491
|
-
if (
|
|
492
|
-
bytes.length >= 8 &&
|
|
493
|
-
bytes[0] === 0x89 &&
|
|
494
|
-
bytes[1] === 0x50 &&
|
|
495
|
-
bytes[2] === 0x4e &&
|
|
496
|
-
bytes[3] === 0x47 &&
|
|
497
|
-
bytes[4] === 0x0d &&
|
|
498
|
-
bytes[5] === 0x0a &&
|
|
499
|
-
bytes[6] === 0x1a &&
|
|
500
|
-
bytes[7] === 0x0a
|
|
501
|
-
)
|
|
502
|
-
return "png";
|
|
503
|
-
if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "jpeg";
|
|
504
|
-
if (bytes.length >= 6 && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38) return "gif";
|
|
505
|
-
if (
|
|
506
|
-
bytes.length >= 12 &&
|
|
507
|
-
bytes[0] === 0x52 &&
|
|
508
|
-
bytes[1] === 0x49 &&
|
|
509
|
-
bytes[2] === 0x46 &&
|
|
510
|
-
bytes[3] === 0x46 &&
|
|
511
|
-
bytes[8] === 0x57 &&
|
|
512
|
-
bytes[9] === 0x45 &&
|
|
513
|
-
bytes[10] === 0x42 &&
|
|
514
|
-
bytes[11] === 0x50
|
|
515
|
-
)
|
|
516
|
-
return "webp";
|
|
517
|
-
return null;
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
const IMAGE_EXT: Record<string, string> = { png: "png", jpeg: "jpg", gif: "gif", webp: "webp" };
|
|
521
|
-
const IMAGE_MIME: Record<string, string> = { png: "image/png", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
|
|
522
|
-
|
|
523
|
-
/** Removes every message dir older than the keep window; runs on every GET / and every POST /message. */
|
|
524
|
-
export function sweepOwnerMessages(now: number): void {
|
|
525
|
-
let names: string[];
|
|
526
|
-
try {
|
|
527
|
-
names = readdirSync(ownerMessagesDir());
|
|
528
|
-
} catch {
|
|
529
|
-
return;
|
|
530
|
-
}
|
|
531
|
-
for (const name of names) {
|
|
532
|
-
const ts = Number(name.slice(0, name.indexOf("-")));
|
|
533
|
-
if (Number.isFinite(ts) && now - ts <= OWNER_MESSAGE_KEEP_SEC) continue;
|
|
534
|
-
rmSync(`${ownerMessagesDir()}/${name}`, { recursive: true, force: true });
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
/** The messages newer than the keep window for the "Sent today" list, newest first. A torn dir is skipped, not fatal. */
|
|
539
|
-
export function recentOwnerMessages(now: number): MessageRow[] {
|
|
540
|
-
let names: string[] = [];
|
|
541
|
-
try {
|
|
542
|
-
names = readdirSync(ownerMessagesDir());
|
|
543
|
-
} catch {
|
|
544
|
-
return [];
|
|
545
|
-
}
|
|
546
|
-
const rows: MessageRow[] = [];
|
|
547
|
-
for (const id of names) {
|
|
548
|
-
const dirTs = Number(id.slice(0, id.indexOf("-")));
|
|
549
|
-
if (!Number.isFinite(dirTs) || now - dirTs >= OWNER_MESSAGE_KEEP_SEC) continue;
|
|
550
|
-
try {
|
|
551
|
-
const meta = JSON.parse(readFileSync(`${ownerMessagesDir()}/${id}/message.json`, "utf8")) as Record<string, unknown>;
|
|
552
|
-
rows.push({
|
|
553
|
-
id,
|
|
554
|
-
ts: Number(meta.ts) || dirTs,
|
|
555
|
-
text: typeof meta.text === "string" ? meta.text : "",
|
|
556
|
-
images: Array.isArray(meta.images) ? meta.images.filter((n): n is string => typeof n === "string") : [],
|
|
557
|
-
});
|
|
558
|
-
} catch {}
|
|
559
|
-
}
|
|
560
|
-
return rows.sort((a, b) => b.ts - a.ts);
|
|
561
|
-
}
|
|
562
|
-
|
|
563
|
-
// ---- rendering (consumes the rows above, never the readers directly) ----
|
|
564
|
-
|
|
565
|
-
/** 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. */
|
|
566
|
-
function messageCard(messages: MessageRow[] | null, running: string[]): string {
|
|
567
|
-
const form = `<form class="msgform" method="post" action="/message" enctype="multipart/form-data">
|
|
568
|
-
<textarea name="text" maxlength="${MESSAGE_MAX}" rows="3" placeholder="What Main should know — a fix, a link, a photo"></textarea>
|
|
569
|
-
<select name="to"><option value="">All</option>${running.map(id => `<option value="${esc(id)}">Main ${esc(id)}</option>`).join("")}</select>
|
|
570
|
-
<input type="file" name="images" accept="image/*" multiple>
|
|
571
|
-
<button class="btn pri" type="submit">Send</button>
|
|
572
|
-
</form>`;
|
|
573
|
-
let sent = "";
|
|
574
|
-
if (messages === null) sent = na("Sent today");
|
|
575
|
-
else if (messages.length) {
|
|
576
|
-
const rows = messages
|
|
577
|
-
.map(m => {
|
|
578
|
-
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("");
|
|
579
|
-
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>`;
|
|
580
|
-
})
|
|
581
|
-
.join("");
|
|
582
|
-
sent = `<p class="mlabel">Sent today</p>${rows}`;
|
|
583
|
-
}
|
|
584
|
-
return `<h2>Tell Main</h2>
|
|
585
|
-
<div class="card">
|
|
586
|
-
${form}
|
|
587
|
-
${sent}
|
|
588
|
-
</div>`;
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
function needCard(row: QuestionRow, i: number, tab: string): string {
|
|
592
|
-
const goals = row.goal.map(g => `<li>${esc(g)}</li>`).join("");
|
|
593
|
-
const bg = row.goal.length ? `<details class="bg" id="bg-${i}"><summary>Background</summary><ul>${goals}</ul></details>` : "";
|
|
594
|
-
const ask = row.waitingAsk || row.waitingLine;
|
|
595
|
-
const parts: string[] = [];
|
|
596
|
-
if (ask) parts.push(`<p class="q"><b>Do</b> ${esc(ask)}</p>`);
|
|
597
|
-
if (row.waitingBlocked || row.unblocks.length) {
|
|
598
|
-
const extra = row.unblocks.length ? `also unblocks: ${row.unblocks.join(", ")}` : "";
|
|
599
|
-
const stuck = [row.waitingBlocked, extra].filter(Boolean).join(" ");
|
|
600
|
-
parts.push(`<p class="q"><b>Stuck until then</b> ${esc(stuck)}</p>`);
|
|
601
|
-
}
|
|
602
|
-
if (row.waitingWhy) parts.push(`<p class="q"><b>Why you</b> ${esc(row.waitingWhy)}</p>`);
|
|
603
|
-
let said = "";
|
|
604
|
-
if (row.answered) {
|
|
605
|
-
const text = row.answered.answer;
|
|
606
|
-
const quote = text.length > 80 ? `${text.slice(0, 80)}…` : text;
|
|
607
|
-
const verb = text.toLowerCase() === "yes" || text.toLowerCase() === "no" ? "answered" : "replied";
|
|
608
|
-
said = `<p class="answered">${row.answered.login ? esc(row.answered.login) : "You"} ${verb} "${esc(quote)}" · ${esc(strftime(row.answered.at, "%H:%M"))} — Main is on it</p>
|
|
609
|
-
<button type="button" class="replybtn link">change answer</button>`;
|
|
610
|
-
}
|
|
611
|
-
const question = ask.endsWith("?");
|
|
612
|
-
const acts = row.answered
|
|
613
|
-
? said
|
|
614
|
-
: question
|
|
615
|
-
? `<div class="acts">
|
|
616
|
-
<button class="btn pri" type="submit" name="answer" value="yes">Yes</button>
|
|
617
|
-
<button class="btn" type="submit" name="answer" value="no">No</button>
|
|
618
|
-
<button type="button" class="btn replybtn">Reply…</button>
|
|
619
|
-
</div>`
|
|
620
|
-
: `<div class="acts">
|
|
621
|
-
<button class="btn pri" type="submit" name="answer" value="done">Done ✓</button>
|
|
622
|
-
<button type="button" class="btn replybtn">Reply…</button>
|
|
623
|
-
</div>`;
|
|
624
|
-
return `<article class="ask">
|
|
625
|
-
<p class="eyebrow">${esc(row.repo)}</p>
|
|
626
|
-
<b>${esc(row.title)}</b>
|
|
627
|
-
${parts.join("\n")}
|
|
628
|
-
${bg}
|
|
629
|
-
<form method="post" action="/answer">
|
|
630
|
-
<input type="hidden" name="plan" value="${esc(row.plan)}">
|
|
631
|
-
${row.team ? `<input type="hidden" name="team" value="${esc(row.team)}">\n` : ""}<input type="hidden" name="tab" value="${esc(tab)}">
|
|
632
|
-
${acts}
|
|
633
|
-
<div class="reply" hidden>
|
|
634
|
-
<textarea name="answer_text" maxlength="${ANSWER_MAX}" rows="3" placeholder="Type your reply"></textarea>
|
|
635
|
-
<button class="btn pri" type="submit">Send reply</button>
|
|
636
|
-
</div>
|
|
637
|
-
</form>
|
|
638
|
-
</article>`;
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
function agentRowHtml(r: AgentRow): string {
|
|
642
|
-
const dot = r.status === "running" ? "ok" : r.status === "waiting" ? "warn" : "bad";
|
|
643
|
-
const mins = r.minutes > 0 ? ` · ${r.minutes} min` : "";
|
|
644
|
-
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>`;
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
/** The queue list. `reorder` false is a team card (P4): no drag handle, no ↑/↓ buttons and no /reorder form — team order is the server's, not INDEX order. */
|
|
648
|
-
function queueHtml(rows: QueueRow[], tab: string, reorder = true): string {
|
|
649
|
-
const handle = (r: QueueRow): string => `<span class="qhandle" title="Drag to reorder" aria-label="Drag ${esc(r.title)}">≡</span>
|
|
650
|
-
`;
|
|
651
|
-
const btns = `<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>`;
|
|
652
|
-
const cards = rows
|
|
653
|
-
.map(
|
|
654
|
-
(r, i) => `<li class="qcard" data-plan="${esc(r.file)}">
|
|
655
|
-
${reorder ? handle(r) : ""}<span class="qrank">${i + 1}</span>
|
|
656
|
-
<span class="qtitle">${esc(r.title)}${r.summary ? `<span class="qsum">${esc(r.summary)}</span>` : ""}</span>
|
|
657
|
-
${r.holder ? `<span class="chip c-held">${r.holder === "team server unreachable" ? esc(r.holder) : `Main ${esc(r.holder)}`}</span>` : ""}<span class="chip ${r.state.startsWith("waits") ? "c-wait" : "c-ready"}">${esc(r.state)}</span>
|
|
658
|
-
${reorder ? btns : ""}
|
|
659
|
-
</li>`,
|
|
660
|
-
)
|
|
661
|
-
.join("\n");
|
|
662
|
-
// before = the order this page was rendered with; the server refuses the move when the real
|
|
663
|
-
// order has drifted (409), so a stale page can never reorder on a guess.
|
|
664
|
-
const before = rows.map(r => r.file).join("\n");
|
|
665
|
-
const form = `<form id="reorder-form" method="post" action="/reorder" hidden>
|
|
666
|
-
<input type="hidden" name="before" value="${esc(before)}">
|
|
667
|
-
<input type="hidden" name="order" value="">
|
|
668
|
-
<input type="hidden" name="moved" value="">
|
|
669
|
-
<input type="hidden" name="tab" value="${esc(tab)}">
|
|
670
|
-
</form>`;
|
|
671
|
-
return `<ul class="qlist"${reorder ? ` id="qlist"` : ""}>
|
|
672
|
-
${cards}
|
|
673
|
-
</ul>
|
|
674
|
-
${reorder ? form : ""}`;
|
|
675
|
-
}
|
|
676
|
-
|
|
677
|
-
function ciHtml(rows: CiRow[]): string {
|
|
678
|
-
return `<ul class="merges">${rows
|
|
679
|
-
.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>`)
|
|
680
|
-
.join("")}</ul>`;
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
function incidentsHtml(rows: IncidentRow[], tab: string): string {
|
|
684
|
-
return `<ul class="incidents">${rows
|
|
685
|
-
.map(r => {
|
|
686
|
-
const head = `<span class="mono">${esc(r.id)}</span> <span class="chip bad">${esc(r.kind)}</span> ${esc(r.summary)}${r.count > 1 ? ` · ${r.count}x` : ""}`;
|
|
687
|
-
if (!isFindingKind(r.kind)) return `<li>${head}</li>`;
|
|
688
|
-
const why = r.proposal === null ? `<em>Main has not said why yet</em>` : esc(r.proposal);
|
|
689
|
-
return `<li>${head}<div class="sub">${why}</div>
|
|
690
|
-
<form method="post" action="/incident" class="inline">
|
|
691
|
-
<input type="hidden" name="id" value="${esc(r.id)}">
|
|
692
|
-
<input type="hidden" name="tab" value="${esc(tab)}">
|
|
693
|
-
<button class="btn" type="submit" name="choice" value="bug">It's a bug — plan it</button>
|
|
694
|
-
<button class="btn" type="submit" name="choice" value="false">False alarm</button>
|
|
695
|
-
</form></li>`;
|
|
696
|
-
})
|
|
697
|
-
.join("")}</ul>`;
|
|
698
|
-
}
|
|
699
|
-
|
|
700
|
-
function scoresHtml(d: ScoresData): string {
|
|
701
|
-
const head = d.header.length ? `<thead><tr>${d.header.map(c => `<th>${esc(c)}</th>`).join("")}</tr></thead>` : "";
|
|
702
|
-
const body = d.rows.length ? `<tbody>${d.rows.map(r => `<tr>${r.map(c => `<td>${esc(c)}</td>`).join("")}</tr>`).join("")}</tbody>` : "";
|
|
703
|
-
const table = head ? `<table>${head}${body}</table>` : "";
|
|
704
|
-
const text = d.text.map(t => `<p>${esc(t)}</p>`).join("");
|
|
705
|
-
return table + text;
|
|
706
|
-
}
|
|
707
|
-
|
|
708
|
-
function machineHtml(cfg: Config, m: MachineRow): string {
|
|
709
|
-
const row = (label: string, value: string, bad = false) =>
|
|
710
|
-
`<div class="mrow"><span>${esc(label)}</span><span class="mono${bad ? " bad" : ""}">${esc(value)}</span></div>`;
|
|
711
|
-
return [
|
|
712
|
-
row("Disk free", `${m.freeGb.toFixed(0)} GB (min ${m.diskMin} GB)`, m.freeGb < m.diskMin),
|
|
713
|
-
row("Load", `${m.load.toFixed(2)} (max ${m.loadMax})`, m.load > m.loadMax),
|
|
714
|
-
row("Cores", String(m.cores)),
|
|
715
|
-
].join("");
|
|
716
|
-
}
|
|
717
|
-
|
|
718
|
-
/** Inline SVG sparkline (mockup: a 130×40 polyline, oldest → newest, left → right). */
|
|
719
|
-
function sparkSvg(points: number[], stroke: string): string {
|
|
720
|
-
const max = Math.max(...points, 0);
|
|
721
|
-
const n = points.length;
|
|
722
|
-
const pts = points
|
|
723
|
-
.map((v, i) => {
|
|
724
|
-
const x = n <= 1 ? 0 : (i / (n - 1)) * 130;
|
|
725
|
-
const y = max > 0 ? 34 - (v / max) * 28 : 34;
|
|
726
|
-
return `${x.toFixed(1)},${y.toFixed(1)}`;
|
|
727
|
-
})
|
|
728
|
-
.join(" ");
|
|
729
|
-
return `<svg class="spark" viewBox="0 0 130 40" aria-hidden="true"><polyline points="${pts}" fill="none" stroke="${stroke}" stroke-width="2"/></svg>`;
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
function tile(label: string, num: string, numStyle: string, note: string, spark = ""): string {
|
|
733
|
-
return `<div class="tile"><div><div class="lbl">${esc(label)}</div><div class="num"${numStyle ? ` style="${numStyle}"` : ""}>${num}</div><div class="note">${note}</div></div>${spark}</div>`;
|
|
734
|
-
}
|
|
735
|
-
|
|
736
|
-
function spendTileHtml(data: PageData): string {
|
|
737
|
-
const s = data.stats;
|
|
738
|
-
return s
|
|
739
|
-
? tile("Spend (list price)", `$${s.spend24.toFixed(2)}`, "", `Main $${s.mainSpend.toFixed(2)} · agents $${s.agentSpend.toFixed(2)}`, sparkSvg(s.spendByHour, "var(--acc)"))
|
|
740
|
-
: tile("Spend (list price)", "–", "", "–");
|
|
741
|
-
}
|
|
742
|
-
|
|
743
|
-
/** The mockup's Today tile card: needs-you, spend, agent runs, open plans. */
|
|
744
|
-
function tilesHtml(data: PageData): string {
|
|
745
|
-
const needs = data.questions === null ? null : data.questions.length;
|
|
746
|
-
const needsTile = needs === null ? tile("Needs you", "–", "", "–") : needs > 0 ? tile("Needs you", String(needs), "color:var(--warn)", "answer below ↓") : tile("Needs you", "0", "", "all clear");
|
|
747
|
-
const runs = data.stats ? tile("Agent runs", String(data.stats.runs24), "", `${data.stats.running} running · ${data.stats.died} died`, sparkSvg(data.stats.runsByHour, "var(--teal)")) : tile("Agent runs", "–", "", "–");
|
|
748
|
-
const plans = data.stats ? tile("Plans", String(data.stats.openPlans), "", `<span style="color:var(--ok)">open</span>`) : tile("Plans", "–", "", "–");
|
|
749
|
-
return [needsTile, spendTileHtml(data), runs, plans].join("\n");
|
|
750
|
-
}
|
|
751
|
-
|
|
752
|
-
/** The sticky mockup top bar: logo, pill tabs, and the lock pill that posts the unlock/lock and tier forms. */
|
|
753
|
-
function topBarHtml(tab: string, lockMinutesLeft: number | null, cfg: Config): string {
|
|
754
|
-
const pills = TABS.map(([id, label]) => `<a href="/?tab=${id}"${tab === id ? ` class="on"` : ""}>${label}</a>`).join("");
|
|
755
|
-
const lockLabel = lockMinutesLeft === null ? "🔒 Off" : `🔓 ${lockMinutesLeft} min`;
|
|
756
|
-
const tabField = `<input type="hidden" name="tab" value="${esc(tab)}">`;
|
|
757
|
-
const unlockForm = (minutes: number) =>
|
|
758
|
-
`<form method="post" action="/unlock"><input type="hidden" name="minutes" value="${minutes}">${tabField}<button class="btn" type="submit">Unlock ${minutes} min</button></form>`;
|
|
759
|
-
const tierForm = (name: Tier, label: string) =>
|
|
760
|
-
`<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>`;
|
|
761
|
-
const off = cfg.guards.chat_unlock
|
|
762
|
-
? ""
|
|
763
|
-
: `<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>`;
|
|
764
|
-
return `<div class="top"><span class="logo">ns</span>
|
|
765
|
-
<nav class="pills" aria-label="Sections">${pills}</nav>
|
|
766
|
-
<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>
|
|
767
|
-
</div>`;
|
|
768
|
-
}
|
|
769
|
-
|
|
770
|
-
/** 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. */
|
|
771
|
-
function queueCard(rows: QueueRow[] | null, full: boolean, tab: string): string {
|
|
772
|
-
const head = full ? "" : `<h2>Queue <small>drag ≡ to sort</small></h2>`;
|
|
773
|
-
if (rows === null) return `${head}<div class="card">${na("Queue")}</div>`;
|
|
774
|
-
if (!rows.length) return `${head}<div class="card"><p class="empty">The queue is empty</p></div>`;
|
|
775
|
-
const body = queueHtml(full ? rows : rows.slice(0, 8), tab);
|
|
776
|
-
const more = !full && rows.length > 8 ? `<a class="more" href="/?tab=queue">Show all ${rows.length} ›</a>` : "";
|
|
777
|
-
return `${head}<div class="card">${body}${more}</div>`;
|
|
778
|
-
}
|
|
779
|
-
|
|
780
|
-
/**
|
|
781
|
-
* Each team as its own card under the queue card (P4): its plans through queueHtml with
|
|
782
|
-
* `reorder` off, then one question card per open WAITING line. A team the server did not answer
|
|
783
|
-
* says so instead of showing a stale list. Nothing here counts in the "Needs you" tile.
|
|
784
|
-
*/
|
|
785
|
-
function teamCardsHtml(sections: TeamSection[] | null, tab: string): string {
|
|
786
|
-
if (sections === null) return `<h2>Team queue</h2><div class="card">${na("Team queue")}</div>`;
|
|
787
|
-
return sections
|
|
788
|
-
.map(s => {
|
|
789
|
-
const body = s.reachable ? (s.rows.length ? queueHtml(s.rows, tab, false) : `<p class="empty">No team plans</p>`) : `<p class="empty">team server ${esc(s.server)} unreachable</p>`;
|
|
790
|
-
const asks = s.questions.map((row, i) => needCard(row, i, tab)).join("\n");
|
|
791
|
-
return `<h2>Team ${esc(s.name)}</h2>
|
|
792
|
-
<div class="card">
|
|
793
|
-
${body}${asks ? `\n${asks}` : ""}
|
|
794
|
-
</div>`;
|
|
795
|
-
})
|
|
796
|
-
.join("\n");
|
|
797
|
-
}
|
|
798
|
-
|
|
799
|
-
function modelSpendTable(stats: NowStats | null): string {
|
|
800
|
-
if (stats === null) return na("Spend");
|
|
801
|
-
if (!stats.byModel.length) return `<p class="empty">No spend recorded in the last 24 hours</p>`;
|
|
802
|
-
const rows = stats.byModel.map(m => `<tr><td>${esc(m.model)}</td><td>$${m.spend.toFixed(2)}</td><td>${m.runs}</td></tr>`).join("");
|
|
803
|
-
return `<table><thead><tr><th>Model</th><th>Spend</th><th>Runs</th></tr></thead><tbody>${rows}</tbody></table>`;
|
|
804
|
-
}
|
|
805
|
-
|
|
806
|
-
function na(label: string): string {
|
|
807
|
-
return `<p class="na">${esc(label)} unavailable</p>`;
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
function receiptText(sent: string, params: URLSearchParams): string | null {
|
|
811
|
-
let text: string;
|
|
812
|
-
switch (sent) {
|
|
813
|
-
case "answer":
|
|
814
|
-
case "message":
|
|
815
|
-
text = `Sent to Main · ${strftime(nowSec(), "%H:%M")}`;
|
|
816
|
-
break;
|
|
817
|
-
case "team-answer": {
|
|
818
|
-
const team = params.get("team") ?? "";
|
|
819
|
-
text = `Sent to team ${team} · ${strftime(nowSec(), "%H:%M")}`;
|
|
820
|
-
break;
|
|
821
|
-
}
|
|
822
|
-
case "incident-closed":
|
|
823
|
-
text = `Marked as a false alarm · ${strftime(nowSec(), "%H:%M")}`;
|
|
824
|
-
break;
|
|
825
|
-
case "incident-bug":
|
|
826
|
-
text = `Sent to Main to plan the fix · ${strftime(nowSec(), "%H:%M")}`;
|
|
827
|
-
break;
|
|
828
|
-
case "unlock": {
|
|
829
|
-
const minutes = Number(params.get("minutes"));
|
|
830
|
-
text = Number.isInteger(minutes) && minutes > 0 ? `Unlocked for ${minutes} min` : "Unlocked";
|
|
831
|
-
break;
|
|
832
|
-
}
|
|
833
|
-
case "lock":
|
|
834
|
-
text = "Locked";
|
|
835
|
-
break;
|
|
836
|
-
case "reorder": {
|
|
837
|
-
// The rank counts the OPEN plans (what the page shows), not every INDEX.md line.
|
|
838
|
-
const to = Number(params.get("to"));
|
|
839
|
-
text = Number.isInteger(to) && to > 0 ? `Moved to #${to} of open plans · Main sees it next turn` : "Moved · Main sees it next turn";
|
|
840
|
-
break;
|
|
841
|
-
}
|
|
842
|
-
case "unlock-off":
|
|
843
|
-
text = "Refused — chat unlock is off";
|
|
844
|
-
break;
|
|
845
|
-
case "stale":
|
|
846
|
-
text = "Already handled — Main cleared this question before your answer; your answer was still passed on.";
|
|
847
|
-
break;
|
|
848
|
-
default:
|
|
849
|
-
return null;
|
|
850
|
-
}
|
|
851
|
-
return text;
|
|
852
|
-
}
|
|
853
|
-
|
|
854
|
-
function receiptHtml(sent: string | null, params: URLSearchParams): string {
|
|
855
|
-
if (!sent) return "";
|
|
856
|
-
const text = receiptText(sent, params);
|
|
857
|
-
return text === null ? "" : `<div class="receipt" role="status">${esc(text)}</div>`;
|
|
858
|
-
}
|
|
859
|
-
|
|
860
|
-
/** The JSON POST replies (P11b): the receipt text rides along so the page script never re-derives it. */
|
|
861
|
-
export function jsonSent(sent: string, receipt?: string | null): Response {
|
|
862
|
-
return Response.json(receipt ? { ok: true, sent, receipt } : { ok: true, sent });
|
|
863
|
-
}
|
|
864
|
-
|
|
865
|
-
export function jsonFail(error: string, status: number): Response {
|
|
866
|
-
return Response.json({ ok: false, error }, { status });
|
|
867
|
-
}
|
|
868
|
-
|
|
869
|
-
// ---- page assembly: one unreadable source never takes the page down ----
|
|
870
|
-
|
|
871
|
-
/** One published page row for the Base tab: the pages-server link is built once, at data build. */
|
|
872
|
-
export interface PublishedPageRow { name: string; repo: string; published: string; url: string }
|
|
873
|
-
|
|
874
|
-
export interface PageData {
|
|
875
|
-
questions: QuestionRow[] | null;
|
|
876
|
-
agents: AgentRow[] | null;
|
|
877
|
-
queue: QueueRow[] | null;
|
|
878
|
-
ci: CiRow[] | null;
|
|
879
|
-
incidents: IncidentRow[] | null;
|
|
880
|
-
scores: ScoresData | null;
|
|
881
|
-
machine: MachineRow | null;
|
|
882
|
-
/** Repo-local HTML explainers from the knowledge manifest; null when unreadable. */
|
|
883
|
-
knowledge: KnowledgeEntry[] | null;
|
|
884
|
-
/** Published pages (plan 20261029_1436 P2), newest first, with their pages-server URL; null when unreadable. */
|
|
885
|
-
pages: PublishedPageRow[] | null;
|
|
886
|
-
/** The 24 h tile numbers; null when the run source is unreadable. */
|
|
887
|
-
stats: NowStats | null;
|
|
888
|
-
/** Each team's card, built from one already-read view per team (P4); absent or null when the views could not be read. */
|
|
889
|
-
teams?: TeamSection[] | null;
|
|
890
|
-
/** The Results tab's saved numbers and build state; absent on every other tab. The numbers come from a background process (computeResults), never from the request. */
|
|
891
|
-
results?: ResultsView | null;
|
|
892
|
-
/** The owner's messages newer than the keep window, newest first; null when unreadable. */
|
|
893
|
-
messages: MessageRow[] | null;
|
|
894
|
-
/** Minutes left in the guard unlock; null = locked. */
|
|
895
|
-
lockMinutesLeft: number | null;
|
|
896
|
-
}
|
|
897
|
-
|
|
898
|
-
function safe<T>(build: () => T): T | null {
|
|
899
|
-
try {
|
|
900
|
-
return build();
|
|
901
|
-
} catch {
|
|
902
|
-
// One unreadable source must never take the page down.
|
|
903
|
-
return null;
|
|
904
|
-
}
|
|
905
|
-
}
|
|
906
|
-
|
|
907
|
-
function publishedRows(cfg: Config, host: string): PublishedPageRow[] {
|
|
908
|
-
return publishedPages(cfg.pages.dir, new Date()).map(p => ({ ...p, url: `http://${host}:${cfg.pages.port}/${urlValue(p.name)}` }));
|
|
909
|
-
}
|
|
910
|
-
|
|
911
|
-
function lockMinutesLeft(cfg: Config): number | null {
|
|
912
|
-
try {
|
|
913
|
-
const end = statSync(unlockPath()).mtimeMs + cfg.guards.unlock_minutes * 60_000;
|
|
914
|
-
const left = Math.round((end - Date.now()) / 60_000);
|
|
915
|
-
return left > 0 ? left : null;
|
|
916
|
-
} catch {
|
|
917
|
-
return null;
|
|
918
|
-
}
|
|
919
|
-
}
|
|
920
|
-
|
|
921
|
-
export function buildPageData(cfg: Config, source: RunSource, tab: string, build: ResultsBuild = spawnResultsBuild, pagesHost = "tailnet"): PageData {
|
|
922
|
-
// P4: one GET /view per team, read once and handed to the queue rows' holder and the team
|
|
923
|
-
// cards, so a render makes no second request per team.
|
|
924
|
-
const views = safe(() => teamViews(cfg));
|
|
925
|
-
return {
|
|
926
|
-
questions: safe(() => questionRows(cfg)),
|
|
927
|
-
agents: safe(() => agentRows(cfg, source)),
|
|
928
|
-
queue: safe(() => queueRows(cfg, views ?? undefined)),
|
|
929
|
-
ci: safe(() => ciRows(cfg)),
|
|
930
|
-
incidents: safe(() => incidentRows(cfg)),
|
|
931
|
-
scores: safe(() => scoresData(cfg)),
|
|
932
|
-
machine: safe(() => machineRow(cfg)),
|
|
933
|
-
knowledge: safe(() => knowledgeManifest(cfg)),
|
|
934
|
-
pages: safe(() => publishedRows(cfg, pagesHost)),
|
|
935
|
-
stats: safe(() => nowStats(cfg, source, nowSec())),
|
|
936
|
-
teams: views === null ? null : safe(() => teamSections(cfg, views)),
|
|
937
|
-
results: tab === "results" ? safe(() => resultsView(nowSec(), build)) : undefined,
|
|
938
|
-
messages: safe(() => recentOwnerMessages(nowSec())),
|
|
939
|
-
lockMinutesLeft: lockMinutesLeft(cfg),
|
|
940
|
-
};
|
|
941
|
-
}
|
|
942
|
-
|
|
943
|
-
const FAVICON =
|
|
944
|
-
"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";
|
|
945
|
-
|
|
946
|
-
/**
|
|
947
|
-
* Where a dropped card goes among the other cards, by vertical midpoint (y grows downward):
|
|
948
|
-
* in front of the FIRST card whose midpoint is greater than the dragged card's, else after the
|
|
949
|
-
* last card. Returns an index into `mids` (the first slot) or `mids.length` (after the last).
|
|
950
|
-
* Pure and exported so the page script — which inlines this exact source via toString() — and
|
|
951
|
-
* the test run the same code: dragging card 1 toward card 2 lands it at 2, never second-to-last.
|
|
952
|
-
*/
|
|
953
|
-
export function dropSlot(mids: number[], mid: number): number {
|
|
954
|
-
for (let i = 0; i < mids.length; i++) if (mids[i]! > mid) return i;
|
|
955
|
-
return mids.length;
|
|
956
|
-
}
|
|
957
|
-
|
|
958
|
-
/**
|
|
959
|
-
* Autoscroll speed in px/frame while a drag is held near the screen edge (P5b): 0 outside a
|
|
960
|
-
* 72 px band, negative in the top band, positive in the bottom band, growing toward the edge,
|
|
961
|
-
* capped at 24 px/frame. Pure and exported so the page script — which inlines this exact
|
|
962
|
-
* source via toString() — and the test run the same code.
|
|
963
|
-
*/
|
|
964
|
-
export function edgeScrollStep(y: number, viewportH: number): number {
|
|
965
|
-
const BAND = 72;
|
|
966
|
-
const CAP = 24;
|
|
967
|
-
const fromTop = BAND - y;
|
|
968
|
-
const fromBottom = y - (viewportH - BAND);
|
|
969
|
-
if (fromTop > 0) return -Math.min(CAP, Math.ceil((CAP * fromTop) / BAND));
|
|
970
|
-
if (fromBottom > 0) return Math.min(CAP, Math.ceil((CAP * fromBottom) / BAND));
|
|
971
|
-
return 0;
|
|
972
|
-
}
|
|
973
|
-
|
|
974
|
-
const SCRIPT = `(function(){
|
|
975
|
-
var dropSlot=${dropSlot.toString()};
|
|
976
|
-
var edgeScrollStep=${edgeScrollStep.toString()};
|
|
977
|
-
// Keep the tab in the address bar (receipts are one-time DOM, not a reloadable URL); the Results tab keeps y/x so the 20 s refresh renders the same selection.
|
|
978
|
-
if(location.search){var q=new URLSearchParams(location.search);var keep=new URLSearchParams();if(q.get("tab"))keep.set("tab",q.get("tab"));if(q.get("tab")==="results"){if(q.get("y"))keep.set("y",q.get("y"));if(q.get("x"))keep.set("x",q.get("x"));}var ks=keep.toString();history.replaceState(null,"",location.pathname+(ks?"?"+ks:""));}
|
|
979
|
-
function store(d,v){var k="nsui:"+d.id;if(v===undefined)return sessionStorage.getItem(k);sessionStorage.setItem(k,v?"1":"0");}
|
|
980
|
-
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]);}}
|
|
981
|
-
var dragging=false;
|
|
982
|
-
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;}
|
|
983
|
-
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);}}
|
|
984
|
-
function sendReorder(moved,list){
|
|
985
|
-
var rform=document.getElementById("reorder-form");if(!rform||!moved)return;
|
|
986
|
-
var cards=list.querySelectorAll(".qcard");var shown=[];for(var i=0;i<cards.length;i++)shown.push(cards[i].getAttribute("data-plan"));
|
|
987
|
-
var bf=(rform.querySelector("[name=before]").value||"").split("\\n").filter(function(x){return x;});
|
|
988
|
-
var o=shown.slice();for(var j=0;j<bf.length;j++){if(shown.indexOf(bf[j])<0)o.push(bf[j]);}
|
|
989
|
-
dragging=false;
|
|
990
|
-
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){
|
|
991
|
-
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");}
|
|
992
|
-
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();}
|
|
993
|
-
else{showReceipt(res.j&&res.j.error?res.j.error:"the move was refused");}
|
|
994
|
-
}).catch(function(){showReceipt("could not reach the page server — try again");});
|
|
995
|
-
}
|
|
996
|
-
var swapping=false;
|
|
997
|
-
// Fetch a page URL and swap only <main> plus the tabs' active pill. push: new history entry; scroll: to top (tab change only).
|
|
998
|
-
function swapMain(href,push,scroll){
|
|
999
|
-
return fetch(href,{headers:{"accept":"text/html"}}).then(function(r){return r.text();}).then(function(html){
|
|
1000
|
-
var doc=document.implementation.createHTMLDocument("");doc.body.innerHTML=html;
|
|
1001
|
-
var fresh=doc.querySelector("main");var cur=document.querySelector("main");
|
|
1002
|
-
if(fresh&&cur){cur.innerHTML=fresh.innerHTML;bindPage();
|
|
1003
|
-
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;}
|
|
1004
|
-
if(push)history.pushState(null,"",href);
|
|
1005
|
-
if(scroll)window.scrollTo(0,0);})}
|
|
1006
|
-
function navigate(href){swapMain(href,true,true).catch(function(){showNetErr();});}
|
|
1007
|
-
function refreshNow(){if(swapping)return;swapping=true;swapMain(location.href,false,false).catch(function(){}).then(function(){swapping=false;});}
|
|
1008
|
-
function showNetErr(){var d=showReceipt("Couldn't reach the page — tap to retry");if(d)d.setAttribute("data-js","neterr");}
|
|
1009
|
-
var drag=null;
|
|
1010
|
-
// One drag move: place the floating card at pointer Y and drop the placeholder between the
|
|
1011
|
-
// cards around it. Also re-run after every autoscroll step, since scrolling moved the midpoints.
|
|
1012
|
-
function dragMove(y){if(!drag)return;var card=drag.card,list=drag.list;card.style.transform="translateY("+(y-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);}
|
|
1013
|
-
var k=dropSlot(mids,mid);
|
|
1014
|
-
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);}}
|
|
1015
|
-
window.addEventListener("pointermove",function(e){if(!drag||e.pointerId!==drag.id)return;drag.y=e.clientY;dragMove(drag.y);});
|
|
1016
|
-
// P5b: a finger held still at the screen edge fires no pointermove, so a rAF loop keeps
|
|
1017
|
-
// scrolling by edgeScrollStep and re-drops the placeholder while it scrolls; endDrag stops it.
|
|
1018
|
-
function dragFrame(){if(!drag)return;var dy=edgeScrollStep(drag.y,window.innerHeight);if(dy){window.scrollBy(0,dy);dragMove(drag.y);}requestAnimationFrame(dragFrame);}
|
|
1019
|
-
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;if(drag.raf)cancelAnimationFrame(drag.raf);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;};
|
|
1020
|
-
window.addEventListener("pointerup",function(e){endDrag(e,true);});
|
|
1021
|
-
window.addEventListener("pointercancel",function(e){endDrag(e,false);});
|
|
1022
|
-
// Every POST form goes over fetch and swaps main in place (P11b); a no-JS browser still submits for real and gets the 303s.
|
|
1023
|
-
document.addEventListener("submit",function(e){
|
|
1024
|
-
var f=e.target;if(!f||!f.getAttribute)return;
|
|
1025
|
-
var action=f.getAttribute("action")||"/";
|
|
1026
|
-
if((f.getAttribute("method")||"").toLowerCase()!=="post"||action.charAt(0)!=="/")return;
|
|
1027
|
-
e.preventDefault();
|
|
1028
|
-
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){
|
|
1029
|
-
if(res.j&&res.j.receipt)showReceipt(res.j.receipt);else if(res.j&&res.j.error)showReceipt(res.j.error);
|
|
1030
|
-
refreshNow();
|
|
1031
|
-
}).catch(function(){showNetErr();});
|
|
1032
|
-
});
|
|
1033
|
-
// 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.
|
|
1034
|
-
document.addEventListener("click",function(e){
|
|
1035
|
-
if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;
|
|
1036
|
-
var t=e.target;if(!t||!t.closest)return;
|
|
1037
|
-
if(t.closest('.receipt[data-js="neterr"]')){e.preventDefault();refreshNow();return;}
|
|
1038
|
-
var a=t.closest("a");if(!a)return;var href=a.getAttribute("href");
|
|
1039
|
-
if(!href||a.target||href.charAt(0)!=="/")return;
|
|
1040
|
-
e.preventDefault();navigate(href);
|
|
1041
|
-
});
|
|
1042
|
-
window.addEventListener("popstate",function(){swapMain(location.href,false,false).catch(function(){showNetErr();});});
|
|
1043
|
-
function bindPage(){
|
|
1044
|
-
var main=document.querySelector("main");if(!main)return;
|
|
1045
|
-
bindDetails(main);
|
|
1046
|
-
var rb=main.querySelectorAll(".replybtn");
|
|
1047
|
-
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();}}});}
|
|
1048
|
-
var qlist=main.querySelector("#qlist");
|
|
1049
|
-
if(qlist){
|
|
1050
|
-
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);}};
|
|
1051
|
-
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);});
|
|
1052
|
-
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,y:e.clientY,id:e.pointerId,list:qlist,raf:0};try{h.setPointerCapture(e.pointerId);}catch(_){}requestAnimationFrame(dragFrame);}}});
|
|
1053
|
-
}
|
|
1054
|
-
}
|
|
1055
|
-
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;}
|
|
1056
|
-
setInterval(function(){if(!busy()&&!swapping)refreshNow();},${REFRESH_SEC}000);
|
|
1057
|
-
bindDetails(document);
|
|
1058
|
-
bindPage();
|
|
1059
|
-
})();`;
|
|
1060
|
-
|
|
1061
|
-
/**
|
|
1062
|
-
* The Knowledge tab: repo cards, one repo's topic cards, or one topic in a frame. The breadcrumb's
|
|
1063
|
-
* earlier segments link back — knowledge-base → every repo, `<repo>` → its topics. Topics are
|
|
1064
|
-
* read-only files at docs/knowledge/<topic>.html in a repo under the configured roots; the page
|
|
1065
|
-
* bytes come from /knowledge/<repo>/<topic> and there is no route that writes one.
|
|
1066
|
-
*/
|
|
1067
|
-
function knowledgeHtml(entries: KnowledgeEntry[], repo: string, topic: string, pages: PublishedPageRow[]): string {
|
|
1068
|
-
const repoHref = `/?tab=knowledge&repo=${urlValue(repo)}`;
|
|
1069
|
-
const crumb =
|
|
1070
|
-
repo === ""
|
|
1071
|
-
? ""
|
|
1072
|
-
: `<p class="sub"><a href="/?tab=knowledge">knowledge-base</a> / ${topic === "" ? esc(repo) : `<a href="${repoHref}">${esc(repo)}</a>`}${topic === "" ? "" : ` / ${esc(topic)}`}</p>`;
|
|
1073
|
-
if (entries.length === 0 && pages.length === 0) {
|
|
1074
|
-
return `<h1>Base</h1><div class="card"><p class="empty">Nothing here yet. Any repo under the configured roots counts: put a page in <span class="mono">docs/knowledge/</span> or publish one with <span class="mono">pages publish</span>, and it shows up here on the next reload.</p></div>`;
|
|
1075
|
-
}
|
|
1076
|
-
if (repo === "") {
|
|
1077
|
-
// One card per repo NAME (plan 20261029_1436 P2): a repo's knowledge topics and its published
|
|
1078
|
-
// pages share the card; a worktree's page was already tagged with the main checkout's name.
|
|
1079
|
-
const repos = new Map<string, { topics: KnowledgeEntry[]; pages: PublishedPageRow[] }>();
|
|
1080
|
-
const slot = (name: string) => {
|
|
1081
|
-
const r = repos.get(name) ?? { topics: [], pages: [] };
|
|
1082
|
-
repos.set(name, r);
|
|
1083
|
-
return r;
|
|
1084
|
-
};
|
|
1085
|
-
for (const e of entries) slot(e.repo).topics.push(e);
|
|
1086
|
-
for (const p of pages) slot(p.repo).pages.push(p);
|
|
1087
|
-
const rows = [...repos.entries()]
|
|
1088
|
-
.sort((a, b) => byText(a[0], b[0]))
|
|
1089
|
-
.map(([name, r]) => {
|
|
1090
|
-
const n = r.topics.length + r.pages.length;
|
|
1091
|
-
const newest = [...r.topics.map(e => e.updated), ...r.pages.map(p => p.published)].sort().at(-1)!.slice(0, 10);
|
|
1092
|
-
return `<div class="mrow"><a href="/?tab=knowledge&repo=${urlValue(name)}">${esc(name)}</a><span class="mono">${n} page${n === 1 ? "" : "s"} · ${newest}</span></div>`;
|
|
1093
|
-
})
|
|
1094
|
-
.join("");
|
|
1095
|
-
return `<h1>Base</h1><p class="sub">One card per repo: its <span class="mono">docs/knowledge/</span> pages and the pages Main published from it — tap a repo to open its list.</p><div class="card">${rows}</div>`;
|
|
1096
|
-
}
|
|
1097
|
-
const topics = entries.filter(e => e.repo === repo);
|
|
1098
|
-
const repoPages = pages.filter(p => p.repo === repo);
|
|
1099
|
-
if (topics.length === 0 && repoPages.length === 0) return `${crumb}<div class="card"><p class="empty">No repo named "${esc(repo)}" has a page under the configured roots.</p></div>`;
|
|
1100
|
-
if (topic === "") {
|
|
1101
|
-
const topicRows = topics
|
|
1102
|
-
.map(e => `<div class="mrow"><a href="${repoHref}&topic=${urlValue(e.topic)}">${esc(e.title)}</a><span class="mono">${e.updated.slice(0, 10)}</span></div>`)
|
|
1103
|
-
.join("");
|
|
1104
|
-
// Published pages after the topics, newest first (publishedPages sorts them that way).
|
|
1105
|
-
const pageRows = repoPages.map(p => `<div class="mrow"><a href="${p.url}">${esc(p.name)}</a><span class="mono">${p.published.slice(0, 10)}</span></div>`).join("");
|
|
1106
|
-
return `${crumb}<div class="card">${topicRows}${pageRows}</div>`;
|
|
1107
|
-
}
|
|
1108
|
-
const hit = topics.find(e => e.topic === topic);
|
|
1109
|
-
if (hit === undefined) return `${crumb}<div class="card"><p class="empty">No topic "${esc(topic)}" in ${esc(repo)}.</p></div>`;
|
|
1110
|
-
return `${crumb}<h1>${esc(hit.title)}</h1><div class="card"><iframe class="knowframe" title="${esc(hit.title)}" src="/knowledge/${urlValue(repo)}/${urlValue(topic)}"></iframe></div>`;
|
|
1111
|
-
}
|
|
1112
|
-
|
|
1113
|
-
// ---- Results tab (plan 20261025_2148 P4): $ per finished feature, releases before vs after ----
|
|
1114
|
-
|
|
1115
|
-
export interface ResultsData {
|
|
1116
|
-
/** The ledger over the last `metrics.report_days` days — only the empty state reads it. */
|
|
1117
|
-
features: FeaturesReport;
|
|
1118
|
-
/** Per release, the N-day before/after windows: the chart's series and the table's rows. */
|
|
1119
|
-
releases: ReleasesReport;
|
|
1120
|
-
}
|
|
1121
|
-
|
|
1122
|
-
/** The tab as the page sees it: the last saved numbers (if any), when they were saved, and whether a build runs now. */
|
|
1123
|
-
export interface ResultsView {
|
|
1124
|
-
data: ResultsData | null;
|
|
1125
|
-
at: number | null;
|
|
1126
|
-
building: boolean;
|
|
1127
|
-
}
|
|
1128
|
-
|
|
1129
|
-
/** Saved numbers older than this start a fresh background build. */
|
|
1130
|
-
const RESULTS_MAX_AGE_SEC = 3600;
|
|
1131
|
-
/** A build that failed or got killed is retried no sooner than this. */
|
|
1132
|
-
const RESULTS_RETRY_SEC = 600;
|
|
1133
|
-
|
|
1134
|
-
export function resultsCachePath(): string {
|
|
1135
|
-
return `${stateDirPath()}/results-cache.json`;
|
|
1136
|
-
}
|
|
1137
|
-
|
|
1138
|
-
/**
|
|
1139
|
-
* The tab's numbers from the P2/P3 functions. A release's before window reaches back months, so
|
|
1140
|
-
* one build parses GBs of sessions for over a minute: it runs only in the separate process
|
|
1141
|
-
* src/cli/results-build.ts, never in the server, which it froze (I-20261030-121).
|
|
1142
|
-
*/
|
|
1143
|
-
export function computeResults(cfg: Config, source: RunSource, now: number): ResultsData {
|
|
1144
|
-
const days = 7;
|
|
1145
|
-
const selfRepo = gitTop(import.meta.dir)?.repo ?? null;
|
|
1146
|
-
const tags = gatherTags(selfRepo);
|
|
1147
|
-
const events = readMetricEvents(cfg);
|
|
1148
|
-
const oldest = Math.min(now, ...tags.map(t => t.ts), ...events.filter(e => e.type === "ci").map(e => Number(e.ts)));
|
|
1149
|
-
const runs = source.listRuns(oldest - days * 86400);
|
|
1150
|
-
const plans = loadPlans(cfg);
|
|
1151
|
-
return {
|
|
1152
|
-
features: featuresReport(runs, plans, selfRepo, now - cfg.metrics.report_days * 86400, now),
|
|
1153
|
-
releases: releasesReport(runs, plans, selfRepo, days, now, tags, events),
|
|
1154
|
-
};
|
|
1155
|
-
}
|
|
1156
|
-
|
|
1157
|
-
/** Starts one background build; calls `done` when it exits, whatever the outcome. */
|
|
1158
|
-
export type ResultsBuild = (done: () => void) => void;
|
|
1159
|
-
|
|
1160
|
-
export const spawnResultsBuild: ResultsBuild = done => {
|
|
1161
|
-
const proc = Bun.spawn(["nice", "-n", "19", process.execPath, `${import.meta.dir}/../cli/results-build.ts`], { stdout: "ignore", stderr: "inherit" });
|
|
1162
|
-
void proc.exited.then(done, done);
|
|
1163
|
-
};
|
|
1164
|
-
|
|
1165
|
-
let buildRunning = false;
|
|
1166
|
-
let lastBuildStart = 0;
|
|
1167
|
-
|
|
1168
|
-
/** Reads the saved numbers and, when they are missing or stale, starts one build in the background. */
|
|
1169
|
-
function resultsView(now: number, build: ResultsBuild): ResultsView {
|
|
1170
|
-
let saved: { at: number; data: ResultsData } | null = null;
|
|
1171
|
-
try {
|
|
1172
|
-
saved = JSON.parse(readFileSync(resultsCachePath(), "utf8"));
|
|
1173
|
-
} catch {
|
|
1174
|
-
// No build has finished yet.
|
|
1175
|
-
}
|
|
1176
|
-
if ((!saved || now - saved.at >= RESULTS_MAX_AGE_SEC) && !buildRunning && now - lastBuildStart >= RESULTS_RETRY_SEC) {
|
|
1177
|
-
buildRunning = true;
|
|
1178
|
-
lastBuildStart = now;
|
|
1179
|
-
build(() => {
|
|
1180
|
-
buildRunning = false;
|
|
1181
|
-
});
|
|
1182
|
-
}
|
|
1183
|
-
return { data: saved?.data ?? null, at: saved?.at ?? null, building: buildRunning };
|
|
1184
|
-
}
|
|
1185
|
-
|
|
1186
|
-
/** One y axis choice: where the number sits on a release side and which way is better. */
|
|
1187
|
-
interface YMetric {
|
|
1188
|
-
key: string;
|
|
1189
|
-
label: string;
|
|
1190
|
-
axis: string;
|
|
1191
|
-
/** null = no known direction (product numbers): the table's arrow carries no color. */
|
|
1192
|
-
better: "lower" | "higher" | null;
|
|
1193
|
-
fmt(v: number): string;
|
|
1194
|
-
get(side: ReleaseSideStats): number | null;
|
|
1195
|
-
}
|
|
1196
|
-
|
|
1197
|
-
const LEDGER_METRICS: YMetric[] = [
|
|
1198
|
-
{ key: "usd", label: "$/feat", axis: "$ per feature", better: "lower", fmt: v => `$${v.toFixed(2)}`, get: s => s.perFeature },
|
|
1199
|
-
{ key: "perday", label: "/day", axis: "features per day", better: "higher", fmt: v => v.toFixed(2), get: s => s.featuresPerDay },
|
|
1200
|
-
{ key: "calls", label: "calls", axis: "main calls per feature", better: "lower", fmt: v => v.toFixed(1), get: s => s.callsPerFeature },
|
|
1201
|
-
{ key: "tok", label: "tok", axis: "tokens per call", better: "lower", fmt: v => v.toFixed(0), get: s => s.tokensPerCall },
|
|
1202
|
-
{ key: "fix", label: "fix", axis: "fix plans per feature", better: "lower", fmt: v => v.toFixed(2), get: s => s.fixPlansPerFeature },
|
|
1203
|
-
];
|
|
1204
|
-
|
|
1205
|
-
/** One metric per recorded product number, keyed `p:<name>` (repo-qualified when names clash). */
|
|
1206
|
-
function productMetrics(releases: ReleasesReport): YMetric[] {
|
|
1207
|
-
const pairs = new Map<string, { repo: string; name: string }>();
|
|
1208
|
-
for (const row of releases.rows) for (const p of [...row.before.products, ...row.after.products]) pairs.set(`${p.repo}|${p.name}`, p);
|
|
1209
|
-
const clashes: Record<string, number> = {};
|
|
1210
|
-
for (const { name } of pairs.values()) clashes[name] = (clashes[name] ?? 0) + 1;
|
|
1211
|
-
return [...pairs.values()]
|
|
1212
|
-
.sort((a, b) => (a.name + a.repo).localeCompare(b.name + b.repo))
|
|
1213
|
-
.map(({ repo, name }) => {
|
|
1214
|
-
const clash = (clashes[name] ?? 0) > 1;
|
|
1215
|
-
return {
|
|
1216
|
-
key: clash ? `p:${basename(repo)}:${name}` : `p:${name}`,
|
|
1217
|
-
label: clash ? `${basename(repo)}/${name}` : name,
|
|
1218
|
-
axis: `${name} (product number)`,
|
|
1219
|
-
better: null,
|
|
1220
|
-
fmt: (v: number) => String(Math.round(v * 100) / 100),
|
|
1221
|
-
get: (s: ReleaseSideStats): number | null => s.products.find(p => p.repo === repo && p.name === name)?.value ?? null,
|
|
1222
|
-
};
|
|
1223
|
-
});
|
|
1224
|
-
}
|
|
1225
|
-
|
|
1226
|
-
const RESULT_KINDS = ["product", "neurastream"] as const;
|
|
1227
|
-
const KIND_COLOR: Record<(typeof RESULT_KINDS)[number], string> = { product: "var(--acc)", neurastream: "var(--teal)" };
|
|
1228
|
-
const CHART_W = 390;
|
|
1229
|
-
const CHART_H = 200;
|
|
1230
|
-
const CHART_L = 48;
|
|
1231
|
-
const CHART_R = 8;
|
|
1232
|
-
const CHART_T = 10;
|
|
1233
|
-
const CHART_B = 20;
|
|
1234
|
-
|
|
1235
|
-
interface ChartPoint {
|
|
1236
|
-
px: number;
|
|
1237
|
-
py: number;
|
|
1238
|
-
label: string;
|
|
1239
|
-
value: number;
|
|
1240
|
-
}
|
|
1241
|
-
interface ChartSeries {
|
|
1242
|
-
label: string;
|
|
1243
|
-
color: string;
|
|
1244
|
-
points: ChartPoint[];
|
|
1245
|
-
}
|
|
1246
|
-
|
|
1247
|
-
/** The tab's controls: plain links, so the page's existing fetch/pushState swap handles them with no new script. */
|
|
1248
|
-
function resultsControls(all: YMetric[], y: YMetric, x: "time" | "feature"): string {
|
|
1249
|
-
const yLinks = all
|
|
1250
|
-
.map(m => `<a href="/?tab=results&y=${m.key}&x=${x}"${m.key === y.key ? ` class="on"` : ""}>${esc(m.label)}</a>`)
|
|
1251
|
-
.join("");
|
|
1252
|
-
const xLinks = (["time", "feature"] as const)
|
|
1253
|
-
.map(v => `<a href="/?tab=results&y=${y.key}&x=${v}"${v === x ? ` class="on"` : ""}>${v === "time" ? "time" : "feature"}</a>`)
|
|
1254
|
-
.join("");
|
|
1255
|
-
return `<div class="rlinks"><span>y</span>${yLinks}</div><div class="rlinks"><span>x</span>${xLinks}</div>`;
|
|
1256
|
-
}
|
|
1257
|
-
|
|
1258
|
-
/**
|
|
1259
|
-
* Hand-written inline SVG under the page's CSP: one polyline per series (product vs neurastream
|
|
1260
|
-
* for a ledger metric, one per product number), points carrying <title> tooltips, releases as
|
|
1261
|
-
* dashed verticals on the time axis, theme colors via the page's CSS variables.
|
|
1262
|
-
*/
|
|
1263
|
-
function resultsChart(releases: ReleasesReport, y: YMetric, x: "time" | "feature"): string {
|
|
1264
|
-
const rows = releases.rows;
|
|
1265
|
-
const mid = CHART_L + (CHART_W - CHART_L - CHART_R) / 2;
|
|
1266
|
-
const t0 = rows[0]!.ts;
|
|
1267
|
-
const t1 = rows[rows.length - 1]!.ts;
|
|
1268
|
-
const pxOf = (i: number, ts: number): number =>
|
|
1269
|
-
x === "feature" ? (rows.length < 2 ? mid : CHART_L + (i / (rows.length - 1)) * (CHART_W - CHART_L - CHART_R))
|
|
1270
|
-
: t1 === t0 ? mid : CHART_L + ((ts - t0) / (t1 - t0)) * (CHART_W - CHART_L - CHART_R);
|
|
1271
|
-
const tip = (row: ReleaseRow, v: number): string => `${row.name} · ${y.fmt(v)} · ${strftime(row.ts, "%m-%d %H:%M")}`;
|
|
1272
|
-
const point = (row: ReleaseRow, i: number, v: number): ChartPoint => ({ px: pxOf(i, row.ts), py: 0, label: tip(row, v), value: v });
|
|
1273
|
-
const series: ChartSeries[] = LEDGER_METRICS.includes(y)
|
|
1274
|
-
? RESULT_KINDS.map(kind => ({
|
|
1275
|
-
label: kind,
|
|
1276
|
-
color: KIND_COLOR[kind],
|
|
1277
|
-
points: rows.flatMap((row, i) => {
|
|
1278
|
-
if (row.kind !== kind) return [];
|
|
1279
|
-
const v = y.get(row.after);
|
|
1280
|
-
return v === null ? [] : [point(row, i, v)];
|
|
1281
|
-
}),
|
|
1282
|
-
}))
|
|
1283
|
-
: [
|
|
1284
|
-
{
|
|
1285
|
-
label: y.label,
|
|
1286
|
-
color: "var(--warn)",
|
|
1287
|
-
points: rows.flatMap((row, i) => {
|
|
1288
|
-
const v = y.get(row.after);
|
|
1289
|
-
return v === null ? [] : [point(row, i, v)];
|
|
1290
|
-
}),
|
|
1291
|
-
},
|
|
1292
|
-
];
|
|
1293
|
-
const yMax = Math.max(...series.flatMap(s => s.points.map(p => p.value)), 1e-9);
|
|
1294
|
-
const pyOf = (v: number): number => CHART_T + (1 - v / yMax) * (CHART_H - CHART_T - CHART_B);
|
|
1295
|
-
const parts: string[] = [];
|
|
1296
|
-
for (const v of [0, yMax / 2, yMax]) {
|
|
1297
|
-
parts.push(`<line x1="${CHART_L}" x2="${CHART_W - CHART_R}" y1="${pyOf(v).toFixed(1)}" y2="${pyOf(v).toFixed(1)}" stroke="var(--bd)"/>`);
|
|
1298
|
-
parts.push(`<text x="${CHART_L - 5}" y="${(pyOf(v) + 3).toFixed(1)}" text-anchor="end" font-size="10" fill="var(--mut)">${esc(y.fmt(v))}</text>`);
|
|
1299
|
-
}
|
|
1300
|
-
if (x === "time") {
|
|
1301
|
-
for (const row of rows) {
|
|
1302
|
-
const px = pxOf(0, row.ts).toFixed(1);
|
|
1303
|
-
parts.push(
|
|
1304
|
-
`<line x1="${px}" x2="${px}" y1="${CHART_T}" y2="${CHART_H - CHART_B}" stroke="var(--bd)" stroke-dasharray="3 3"><title>${esc(`${row.name} · ${strftime(row.ts, "%m-%d %H:%M")}`)}</title></line>`,
|
|
1305
|
-
);
|
|
1306
|
-
}
|
|
1307
|
-
parts.push(`<text x="${CHART_L}" y="${CHART_H - 6}" font-size="10" fill="var(--mut)">${esc(strftime(t0, "%m-%d"))}</text>`);
|
|
1308
|
-
parts.push(`<text x="${CHART_W - CHART_R}" y="${CHART_H - 6}" text-anchor="end" font-size="10" fill="var(--mut)">${esc(strftime(t1, "%m-%d"))}</text>`);
|
|
1309
|
-
}
|
|
1310
|
-
for (const s of series) {
|
|
1311
|
-
if (s.points.length > 1) {
|
|
1312
|
-
const pts = s.points.map(p => `${p.px.toFixed(1)},${pyOf(p.value).toFixed(1)}`).join(" ");
|
|
1313
|
-
parts.push(`<polyline points="${pts}" fill="none" stroke="${s.color}" stroke-width="2"/>`);
|
|
1314
|
-
}
|
|
1315
|
-
for (const p of s.points) {
|
|
1316
|
-
parts.push(`<circle cx="${p.px.toFixed(1)}" cy="${pyOf(p.value).toFixed(1)}" r="3" fill="${s.color}"><title>${esc(p.label)}</title></circle>`);
|
|
1317
|
-
}
|
|
1318
|
-
}
|
|
1319
|
-
const legend = series.map(s => `<span style="color:${s.color}">— ${esc(s.label)}</span>`).join("");
|
|
1320
|
-
return `<p class="rlegend">${legend}</p><svg class="rchart" role="img" aria-label="${esc(`${y.axis} by ${x === "time" ? "day" : "release"}`)}" viewBox="0 0 ${CHART_W} ${CHART_H}">${parts.join("")}</svg>`;
|
|
1321
|
-
}
|
|
1322
|
-
|
|
1323
|
-
/** One row per release, the `metrics releases` table: before→after cells with ▲/▼, green when the change is for the better. */
|
|
1324
|
-
function resultsTable(releases: ReleasesReport, all: YMetric[]): string {
|
|
1325
|
-
const cell = (row: ReleaseRow, m: YMetric): string => {
|
|
1326
|
-
const before = m.get(row.before);
|
|
1327
|
-
const after = m.get(row.after);
|
|
1328
|
-
if (before === null || after === null) return `<td class="mutcell">–</td>`;
|
|
1329
|
-
const arrow = after > before ? "▲" : after < before ? "▼" : "·";
|
|
1330
|
-
const cls = m.better !== null && after !== before ? ((m.better === "lower") === (after < before) ? ` class="good"` : ` class="badv"`) : "";
|
|
1331
|
-
return `<td>${esc(m.fmt(before))}→${esc(m.fmt(after))}<span${cls}>${arrow}</span></td>`;
|
|
1332
|
-
};
|
|
1333
|
-
const head = `<tr><th>release</th>${all.map(m => `<th>${esc(m.label)}</th>`).join("")}</tr>`;
|
|
1334
|
-
const body = releases.rows
|
|
1335
|
-
.map(row =>
|
|
1336
|
-
`<tr><td>${esc(row.name)} <span class="note">${strftime(row.ts, "%m-%d")}</span>${row.measuring ? ` <span class="chip c-ready">measuring</span>` : ""}</td>${all.map(m => cell(row, m)).join("")}</tr>`,
|
|
1337
|
-
)
|
|
1338
|
-
.join("");
|
|
1339
|
-
return `<div class="tscroll"><table><thead>${head}</thead><tbody>${body}</tbody></table></div>`;
|
|
1340
|
-
}
|
|
1341
|
-
|
|
1342
|
-
const RESULTS_CAVEAT = "Fixes inside the same plan are not split out; plans that do not cite an earlier stem are not linked. Product numbers carry no better/worse color.";
|
|
1343
|
-
|
|
1344
|
-
function resultsTabHtml(view: ResultsView | null | undefined, params: URLSearchParams): string {
|
|
1345
|
-
const d = view?.data;
|
|
1346
|
-
if (!d) {
|
|
1347
|
-
if (view?.building) return `<h1>Results</h1><div class="card"><p class="empty">Working out the numbers from your past sessions — the first time takes a few minutes. This page refreshes by itself.</p></div>`;
|
|
1348
|
-
return `<h1>Results</h1>${na("Results")}`;
|
|
1349
|
-
}
|
|
1350
|
-
if (!d.releases.rows.length) {
|
|
1351
|
-
const empty = d.features.rows.length ? "No releases recorded yet" : "No finished features yet";
|
|
1352
|
-
return `<h1>Results</h1><div class="card"><p class="empty">${empty}</p></div><p class="sub">${RESULTS_CAVEAT}</p>`;
|
|
1353
|
-
}
|
|
1354
|
-
const x = params.get("x") === "feature" ? "feature" : "time";
|
|
1355
|
-
const all = [...LEDGER_METRICS, ...productMetrics(d.releases)];
|
|
1356
|
-
// An unknown y falls back to $/feature.
|
|
1357
|
-
const y = all.find(m => m.key === params.get("y")) ?? all[0]!;
|
|
1358
|
-
return `<h1>Results</h1>
|
|
1359
|
-
<p class="sub">What features cost and whether releases made it better or worse. Updated ${Math.max(0, Math.round((nowSec() - (view.at ?? nowSec())) / 60))} min ago${view.building ? " · updating now" : ""}.</p>
|
|
1360
|
-
<div class="card">
|
|
1361
|
-
${resultsControls(all, y, x)}
|
|
1362
|
-
${resultsChart(d.releases, y, x)}
|
|
1363
|
-
</div>
|
|
1364
|
-
<h2>Releases <small>${d.releases.days} days before → after</small></h2>
|
|
1365
|
-
<div class="card">
|
|
1366
|
-
${resultsTable(d.releases, all)}
|
|
1367
|
-
</div>
|
|
1368
|
-
<p class="sub">${RESULTS_CAVEAT}</p>`;
|
|
1369
|
-
}
|
|
1370
|
-
|
|
1371
|
-
/** The owner page's stylesheet (P5 lift): one string shared by the phone page (renderPage) and the team page (renderTeamPage). */
|
|
1372
|
-
const PAGE_CSS = `
|
|
1373
|
-
:root{--bg:#f4f4f6;--card:#fff;--fg:#111;--mut:#6b6b76;--bd:#e4e4ea;--acc:#c026d3;--teal:#0d9488;--warn:#d97706;--ok:#16a34a;--red:#dc2626}
|
|
1374
|
-
@media(prefers-color-scheme:dark){:root{--bg:#0e0e11;--card:#18181c;--fg:#f2f2f4;--mut:#9a9aa6;--bd:#2a2a31}}
|
|
1375
|
-
*{box-sizing:border-box}
|
|
1376
|
-
html{scroll-padding-top:64px}
|
|
1377
|
-
body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.4 system-ui,-apple-system,sans-serif}
|
|
1378
|
-
.top{position:sticky;top:0;display:flex;align-items:center;gap:8px;padding:10px 12px;background:var(--bg);z-index:2}
|
|
1379
|
-
.logo{font-weight:800;color:var(--acc)}
|
|
1380
|
-
.pills{display:flex;background:var(--card);border:1px solid var(--bd);border-radius:999px;padding:3px;flex:1;gap:3px;overflow-x:auto}
|
|
1381
|
-
.pills a{flex:none;text-align:center;padding:5px 10px;border-radius:999px;color:var(--mut);text-decoration:none;font-size:13px;white-space:nowrap}
|
|
1382
|
-
.pills a.on{background:var(--bg);color:var(--fg);font-weight:600;box-shadow:0 0 0 1px var(--bd)}
|
|
1383
|
-
.lock{border:1px solid var(--bd);background:var(--card);border-radius:999px;padding:6px 10px;font-size:13px;color:var(--fg);position:relative;flex:none}
|
|
1384
|
-
.lock summary{list-style:none;white-space:nowrap}
|
|
1385
|
-
.lock summary::-webkit-details-marker{display:none}
|
|
1386
|
-
.lockmenu{position:absolute;right:0;top:calc(100% + 6px);background:var(--card);border:1px solid var(--bd);border-radius:14px;padding:10px;display:flex;flex-direction:column;gap:6px;min-width:170px;z-index:10}
|
|
1387
|
-
.lockmenu .btn{margin:0}
|
|
1388
|
-
.offnote{margin:0;color:var(--mut);font-size:12px}
|
|
1389
|
-
.offcfg{font-family:ui-monospace,"SF Mono","Roboto Mono",monospace;font-size:12px}
|
|
1390
|
-
main{padding:4px 12px 40px}
|
|
1391
|
-
h1{font-size:26px;margin:8px 0 2px}
|
|
1392
|
-
h2{font-size:17px;margin:22px 4px 8px;display:flex;justify-content:space-between;align-items:baseline}
|
|
1393
|
-
h2 small{font-size:12px;color:var(--mut);font-weight:400}
|
|
1394
|
-
.sub{color:var(--mut);font-size:13px;margin:0 0 12px}
|
|
1395
|
-
.card{background:var(--card);border:1px solid var(--bd);border-radius:14px;overflow:hidden}
|
|
1396
|
-
.tile{padding:14px 16px;border-top:1px solid var(--bd);display:flex;justify-content:space-between;align-items:flex-end;gap:8px}
|
|
1397
|
-
.tile:first-child{border-top:0}
|
|
1398
|
-
.lbl{font-size:13px;color:var(--mut)}
|
|
1399
|
-
.num{font-size:30px;font-weight:700;line-height:1.1;font-variant-numeric:tabular-nums}
|
|
1400
|
-
.note{font-size:12px;color:var(--mut)}
|
|
1401
|
-
svg.spark{width:130px;height:40px;flex:none}
|
|
1402
|
-
.receipt{margin:12px 12px 0;padding:10px 16px;background:var(--card);border:1px solid var(--teal);border-radius:14px;color:var(--teal);font-weight:600}
|
|
1403
|
-
.eyebrow{margin:0 0 2px;color:var(--mut);font-size:13px}
|
|
1404
|
-
.ask{padding:14px 16px;border-top:1px solid var(--bd)}
|
|
1405
|
-
.ask:first-child{border-top:0}
|
|
1406
|
-
.ask b{display:block;font-size:16px}
|
|
1407
|
-
.ask p{margin:2px 0 10px;color:var(--mut);font-size:13px}
|
|
1408
|
-
.ask .q{color:var(--fg);font-size:14px;margin:0 0 8px}
|
|
1409
|
-
.answered{color:var(--ok)!important;margin:0 0 4px!important}
|
|
1410
|
-
.link{border:0;background:none;color:var(--mut);text-decoration:underline;padding:0;font:inherit;font-size:13px}
|
|
1411
|
-
.acts{display:flex;gap:6px;flex-wrap:wrap}
|
|
1412
|
-
.btn{border:1px solid var(--bd);background:var(--card);color:var(--fg);border-radius:999px;padding:6px 16px;font-size:14px;margin-right:6px;font-family:inherit}
|
|
1413
|
-
.btn.pri{background:var(--acc);border-color:var(--acc);color:#fff}
|
|
1414
|
-
:focus-visible{outline:2px solid var(--acc);outline-offset:2px}
|
|
1415
|
-
.reply{margin-top:8px}
|
|
1416
|
-
.reply textarea{width:100%;padding:10px;border-radius:10px;border:1px solid var(--bd);background:var(--bg);color:var(--fg);font:inherit}
|
|
1417
|
-
.msgform{padding:14px 16px;display:flex;flex-direction:column;gap:10px}
|
|
1418
|
-
.msgform textarea{width:100%;padding:10px;border-radius:10px;border:1px solid var(--bd);background:var(--bg);color:var(--fg);font:inherit}
|
|
1419
|
-
.msgform input[type=file]{font-size:13px;color:var(--mut);max-width:100%}
|
|
1420
|
-
.mlabel{margin:0;padding:10px 16px 2px;color:var(--mut);font-size:13px}
|
|
1421
|
-
.msg{display:flex;gap:10px;padding:10px 16px;border-top:1px solid var(--bd);align-items:baseline;flex-wrap:wrap}
|
|
1422
|
-
.msg:first-of-type{border-top:0}
|
|
1423
|
-
.mtime{color:var(--mut);font-size:12px;font-variant-numeric:tabular-nums;flex:none}
|
|
1424
|
-
.mtext{flex:1 1 12em;min-width:0;font-size:14px}
|
|
1425
|
-
.mimgs{display:flex;gap:6px}
|
|
1426
|
-
img.mthumb{width:56px;height:56px;object-fit:cover;border-radius:10px;border:1px solid var(--bd);display:block}
|
|
1427
|
-
details.bg{margin:8px 0;border-top:1px solid var(--bd);padding-top:6px}
|
|
1428
|
-
details.bg summary{color:var(--mut)}
|
|
1429
|
-
details.bg ul{margin:4px 0 8px;padding-left:20px;color:var(--mut);font-size:13px}
|
|
1430
|
-
.qlist{list-style:none;margin:0;padding:0}
|
|
1431
|
-
.qcard{display:flex;align-items:center;gap:10px;padding:12px 14px;border-top:1px solid var(--bd);flex-wrap:wrap}
|
|
1432
|
-
.qcard:first-child{border-top:0}
|
|
1433
|
-
.qcard.dragging{position:fixed;z-index:20;background:var(--card);border:1px solid var(--acc);border-radius:14px;margin:0;user-select:none;opacity:0.96}
|
|
1434
|
-
.qph{list-style:none;border:2px dashed var(--bd);margin:4px 0}
|
|
1435
|
-
.qhandle{color:var(--mut);font-size:18px;touch-action:none;padding:2px 2px;user-select:none;flex:none}
|
|
1436
|
-
.qrank{color:var(--mut);width:18px;font-size:13px;text-align:right;font-variant-numeric:tabular-nums;flex:none}
|
|
1437
|
-
.qtitle{flex:1 1 12em;min-width:0}
|
|
1438
|
-
.qsum{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;color:var(--mut);font-size:13px;font-weight:400}
|
|
1439
|
-
.chip{font-size:11px;padding:2px 8px;border-radius:999px;white-space:nowrap;flex:none}
|
|
1440
|
-
.c-wait{background:color-mix(in srgb,var(--warn) 18%,transparent);color:var(--warn)}
|
|
1441
|
-
.c-run{background:color-mix(in srgb,var(--teal) 18%,transparent);color:var(--teal)}
|
|
1442
|
-
.c-ready{background:color-mix(in srgb,var(--mut) 15%,transparent);color:var(--mut)}
|
|
1443
|
-
.c-held{background:color-mix(in srgb,var(--acc) 15%,transparent);color:var(--acc)}
|
|
1444
|
-
.chip.bad{color:var(--red)}
|
|
1445
|
-
.qbtns{display:flex;gap:4px;flex-wrap:wrap;margin-left:auto}
|
|
1446
|
-
.qbtns button{min-height:32px;padding:2px 10px;font-size:12px;border-radius:999px;border:1px solid var(--bd);background:var(--card);color:var(--mut)}
|
|
1447
|
-
.more{display:block;text-align:center;padding:12px;color:var(--acc);text-decoration:none;border-top:1px solid var(--bd);font-size:14px}
|
|
1448
|
-
.agents{list-style:none;margin:0;padding:8px 14px}
|
|
1449
|
-
.agent{display:flex;align-items:baseline;gap:8px;padding:8px 0;border-bottom:1px solid var(--bd);flex-wrap:wrap}
|
|
1450
|
-
.agent:last-child{border-bottom:none}
|
|
1451
|
-
.dot{width:10px;height:10px;border-radius:50%;align-self:center;flex:none}
|
|
1452
|
-
.dot.ok{background:var(--teal)}
|
|
1453
|
-
.dot.warn{background:var(--warn)}
|
|
1454
|
-
.dot.bad{background:var(--red)}
|
|
1455
|
-
.mono,.aid,.model{font-family:ui-monospace,"SF Mono","Roboto Mono",monospace;font-size:13px}
|
|
1456
|
-
.model,.detail{color:var(--mut)}
|
|
1457
|
-
table{border-collapse:collapse;width:100%;font-size:13px}
|
|
1458
|
-
th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--bd);font-variant-numeric:tabular-nums}
|
|
1459
|
-
th{color:var(--mut);font-weight:600}
|
|
1460
|
-
tr:last-child td{border-bottom:none}
|
|
1461
|
-
.tscroll{overflow-x:auto}
|
|
1462
|
-
td.mutcell{color:var(--mut)}
|
|
1463
|
-
span.good{color:var(--ok);font-weight:600}
|
|
1464
|
-
span.badv{color:var(--red);font-weight:600}
|
|
1465
|
-
.rlinks{display:flex;gap:6px;align-items:center;flex-wrap:wrap;padding:10px 14px 0;font-size:12px;color:var(--mut)}
|
|
1466
|
-
.rlinks a{border:1px solid var(--bd);border-radius:999px;padding:3px 10px;color:var(--mut);text-decoration:none;background:var(--card)}
|
|
1467
|
-
.rlinks a.on{color:var(--fg);background:var(--bg);font-weight:600;box-shadow:0 0 0 1px var(--bd)}
|
|
1468
|
-
.rlegend{margin:0;padding:10px 14px 0;font-size:12px;color:var(--mut);display:flex;gap:12px}
|
|
1469
|
-
.rchart{width:100%;height:auto;display:block;padding:4px 2px 8px}
|
|
1470
|
-
.merges,.incidents{margin:0;padding:8px 14px 8px 32px}
|
|
1471
|
-
.merges li,.incidents li{margin:6px 0}
|
|
1472
|
-
.mrow{display:flex;justify-content:space-between;gap:12px;padding:6px 0;border-bottom:1px solid var(--bd)}
|
|
1473
|
-
.mrow:last-child{border-bottom:none}
|
|
1474
|
-
.bad{color:var(--red);font-weight:600}
|
|
1475
|
-
.empty{color:var(--mut);padding:14px 16px;margin:0}
|
|
1476
|
-
.knowframe{display:block;width:100%;height:calc(100vh - 220px);min-height:360px;border:0;background:#fff}
|
|
1477
|
-
.na{color:var(--mut);font-style:italic;padding:14px 16px;margin:0}
|
|
1478
|
-
`;
|
|
1479
|
-
|
|
1480
|
-
/** The whole page as one HTML string. Exported for scripts/ui-preview.ts (no server). */
|
|
1481
|
-
export function renderPage(cfg: Config, data: PageData, params: URLSearchParams, nonce: string): string {
|
|
1482
|
-
const req = params.get("tab") ?? "";
|
|
1483
|
-
// Server-rendered tabs: the pill links carry ?tab=; anything unknown renders Now.
|
|
1484
|
-
const tab = TAB_IDS.includes(req) ? req : "now";
|
|
1485
|
-
const needsBody =
|
|
1486
|
-
data.questions === null
|
|
1487
|
-
? na("Waiting on you")
|
|
1488
|
-
: data.questions.length
|
|
1489
|
-
? data.questions.map((row, i) => needCard(row, i, tab)).join("\n")
|
|
1490
|
-
: `<p class="empty">Nothing needs you right now</p>`;
|
|
1491
|
-
const working =
|
|
1492
|
-
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>`;
|
|
1493
|
-
const scores = data.scores === null ? na("Agent scores") : scoresHtml(data.scores);
|
|
1494
|
-
const incidents = data.incidents === null ? na("Incidents") : data.incidents.length ? incidentsHtml(data.incidents, tab) : `<p class="empty">No open incidents</p>`;
|
|
1495
|
-
const merges = data.ci === null ? na("Merges") : data.ci.length ? ciHtml(data.ci) : `<p class="empty">No CI runs recorded</p>`;
|
|
1496
|
-
const machine = data.machine === null ? na("Machine") : machineHtml(cfg, data.machine);
|
|
1497
|
-
// P4: one card per team, under the queue card on the two tabs that show the queue.
|
|
1498
|
-
const teams = tab === "now" || tab === "queue" ? teamCardsHtml(data.teams ?? null, tab) : "";
|
|
1499
|
-
const body =
|
|
1500
|
-
tab === "now"
|
|
1501
|
-
? `${messageCard(data.messages, runningMains(cfg))}
|
|
1502
|
-
<h1>Today</h1>
|
|
1503
|
-
<p class="sub">What your agents did in the last 24 hours.</p>
|
|
1504
|
-
<div class="card">
|
|
1505
|
-
${tilesHtml(data)}
|
|
1506
|
-
</div>
|
|
1507
|
-
<h2>Needs you</h2>
|
|
1508
|
-
<div class="card">
|
|
1509
|
-
${needsBody}
|
|
1510
|
-
</div>
|
|
1511
|
-
${queueCard(data.queue, false, tab)}${teams ? `\n${teams}` : ""}`
|
|
1512
|
-
: tab === "queue"
|
|
1513
|
-
? `<h1>Queue</h1>
|
|
1514
|
-
<p class="sub">Drag ≡ to sort — Main works by the new order on its next turn.</p>
|
|
1515
|
-
${queueCard(data.queue, true, tab)}${teams ? `\n${teams}` : ""}`
|
|
1516
|
-
: tab === "agents"
|
|
1517
|
-
? `<h1>Agents</h1>
|
|
1518
|
-
<p class="sub">Who is working right now, how they score, and what went wrong.</p>
|
|
1519
|
-
<h2>Working now</h2>
|
|
1520
|
-
<div class="card">
|
|
1521
|
-
${working}
|
|
1522
|
-
</div>
|
|
1523
|
-
<h2>Agent scores</h2>
|
|
1524
|
-
<div class="card">
|
|
1525
|
-
${scores}
|
|
1526
|
-
</div>
|
|
1527
|
-
<h2>Incidents</h2>
|
|
1528
|
-
<div class="card">
|
|
1529
|
-
${incidents}
|
|
1530
|
-
</div>
|
|
1531
|
-
<h2>Merges</h2>
|
|
1532
|
-
<div class="card">
|
|
1533
|
-
${merges}
|
|
1534
|
-
</div>
|
|
1535
|
-
<h2>Machine</h2>
|
|
1536
|
-
<div class="card">
|
|
1537
|
-
${machine}
|
|
1538
|
-
</div>`
|
|
1539
|
-
: tab === "knowledge"
|
|
1540
|
-
? `${data.knowledge === null ? na("Base") : knowledgeHtml(data.knowledge, params.get("repo") ?? "", params.get("topic") ?? "", data.pages ?? [])}`
|
|
1541
|
-
: tab === "spend"
|
|
1542
|
-
? `<h1>Spend</h1
|
|
1543
|
-
<p class="sub">List price over the last 24 hours.</p>
|
|
1544
|
-
<div class="card">
|
|
1545
|
-
${spendTileHtml(data)}
|
|
1546
|
-
</div>
|
|
1547
|
-
<h2>By model</h2>
|
|
1548
|
-
<div class="card">
|
|
1549
|
-
${modelSpendTable(data.stats)}
|
|
1550
|
-
</div>`
|
|
1551
|
-
: resultsTabHtml(data.results, params);
|
|
1552
|
-
return `<!doctype html>
|
|
1553
|
-
<html lang="en">
|
|
1554
|
-
<head>
|
|
1555
|
-
<meta charset="utf-8">
|
|
1556
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1557
|
-
<meta name="color-scheme" content="light dark">
|
|
1558
|
-
<title>neurastream</title>
|
|
1559
|
-
<link rel="icon" href="${FAVICON}">
|
|
1560
|
-
<style>${PAGE_CSS}</style>
|
|
1561
|
-
</head>
|
|
1562
|
-
<body>
|
|
1563
|
-
${topBarHtml(tab, data.lockMinutesLeft, cfg)}
|
|
1564
|
-
${receiptHtml(params.get("sent"), params)}
|
|
1565
|
-
<main>
|
|
1566
|
-
${body}
|
|
1567
|
-
</main>
|
|
1568
|
-
<script nonce="${nonce}">${SCRIPT}</script>
|
|
1569
|
-
</body>
|
|
1570
|
-
</html>`;
|
|
1571
|
-
}
|
|
1572
|
-
|
|
1573
|
-
// ---- request plumbing ----
|
|
1574
|
-
|
|
1575
|
-
export async function fieldsOf(req: Request): Promise<Record<string, string>> {
|
|
1576
|
-
const ct = req.headers.get("content-type") ?? "";
|
|
1577
|
-
if (ct.includes("application/json")) {
|
|
1578
|
-
const raw: unknown = await req.json();
|
|
1579
|
-
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
|
1580
|
-
return Object.fromEntries(Object.entries(raw as Record<string, unknown>).map(([k, v]) => [k, String(v)]));
|
|
1581
|
-
}
|
|
1582
|
-
const form = await req.formData();
|
|
1583
|
-
return Object.fromEntries([...form.entries()].map(([k, v]) => [k, typeof v === "string" ? v : ""]));
|
|
1584
|
-
}
|
|
1585
|
-
|
|
1586
|
-
export function textRes(body: string, status: number): Response {
|
|
1587
|
-
return new Response(`${body}\n`, { status, headers: { "content-type": "text/plain; charset=utf-8" } });
|
|
1588
|
-
}
|
|
1589
|
-
|
|
1590
|
-
function redirect(target: string): Response {
|
|
1591
|
-
return new Response(null, { status: 303, headers: { location: target } });
|
|
1592
|
-
}
|
|
1593
|
-
|
|
1594
|
-
/** The POST reply target: the tab the owner was on (a hidden `tab` field; unknown = now, the default), then the receipt. */
|
|
1595
|
-
function sentTo(tab: string, sent: string): string {
|
|
1596
|
-
const t = TAB_IDS.includes(tab) ? tab : "now";
|
|
1597
|
-
return t === "now" ? `/?${sent}` : `/?tab=${t}&${sent}`;
|
|
1598
|
-
}
|
|
1599
|
-
|
|
1600
|
-
/** The owner pages' CSP: the one inline script takes this response's nonce; the team page shares it. */
|
|
1601
|
-
export function pageCsp(nonce: string): string {
|
|
1602
|
-
return `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; img-src 'self' data:; connect-src 'self'; frame-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`;
|
|
1603
|
-
}
|
|
1604
|
-
|
|
1605
|
-
/** The normal page (the GET layout) as a POST reply; the stale-answer reply is this with sent=stale. */
|
|
1606
|
-
function pageRes(cfg: Config, source: RunSource, params: URLSearchParams, build: ResultsBuild = spawnResultsBuild, pagesHost = "tailnet"): Response {
|
|
1607
|
-
const nonce = randomUUID().replaceAll("-", "");
|
|
1608
|
-
return new Response(renderPage(cfg, buildPageData(cfg, source, params.get("tab") ?? "", build, pagesHost), params, nonce), {
|
|
1609
|
-
status: 200,
|
|
1610
|
-
headers: {
|
|
1611
|
-
"content-type": "text/html; charset=utf-8",
|
|
1612
|
-
"content-security-policy": pageCsp(nonce),
|
|
1613
|
-
},
|
|
1614
|
-
});
|
|
1615
|
-
}
|
|
1616
|
-
|
|
1617
|
-
/** What the team page shows: one team's section (shared with the phone page), its plans' approvals, members, and audit. */
|
|
1618
|
-
export interface TeamPageData {
|
|
1619
|
-
team: string;
|
|
1620
|
-
login: string;
|
|
1621
|
-
admin: boolean;
|
|
1622
|
-
leader: boolean;
|
|
1623
|
-
adminLogin: string;
|
|
1624
|
-
section: TeamSection;
|
|
1625
|
-
plans: { id: string; relPath: string; title: string; approvals: string[] }[];
|
|
1626
|
-
members: string[];
|
|
1627
|
-
/** Newest first, already formatted; null for a viewer who may not read the audit. */
|
|
1628
|
-
audit: { at: string; login: string; route: string }[] | null;
|
|
1629
|
-
}
|
|
1630
|
-
|
|
1631
|
-
/** The team page (P5): plain forms that POST to the team server's routes; no script, so no nonce. */
|
|
1632
|
-
export function renderTeamPage(data: TeamPageData): string {
|
|
1633
|
-
const waiting = data.section.questions.length
|
|
1634
|
-
? data.section.questions.map(row => `<div class="ask"><b>${esc(row.title)}</b><p class="q">${esc(row.waitingAsk || row.waitingLine || "")}</p>${row.answered ? `<p class="answered">${row.answered.login ? esc(row.answered.login) : "You"} answered "${esc(row.answered.answer)}"</p>` : ""}<form method="post" action="/answer"><input type="hidden" name="plan" value="${esc(row.plan)}"><textarea name="answer_text" rows="2" required maxlength="2000"></textarea><div class="acts"><button class="btn pri" type="submit">Send</button></div></form></div>`).join("")
|
|
1635
|
-
: `<p class="empty">Nothing waiting</p>`;
|
|
1636
|
-
const approve = data.plans.length
|
|
1637
|
-
? data.plans.map(p => {
|
|
1638
|
-
const chip = p.approvals.length ? ` <span class="chip c-ready">approved by ${p.approvals.map(a => esc(a)).join(", ")}</span>` : "";
|
|
1639
|
-
const form = p.approvals.includes(data.login) ? "" : `<form method="post" action="/approve"><input type="hidden" name="plan" value="${esc(p.id)}"><button class="btn pri" type="submit">Approve</button></form>`;
|
|
1640
|
-
return `<div class="ask"><b>${esc(p.title)}</b><p>${esc(p.relPath)}${chip}</p>${form}</div>`;
|
|
1641
|
-
}).join("")
|
|
1642
|
-
: `<p class="empty">No team plans to approve</p>`;
|
|
1643
|
-
const ranking = data.plans.length
|
|
1644
|
-
? `<form method="post" action="/vote">${data.plans.map(p => `<div class="mrow"><span>${esc(p.title)}</span><input name="rank:${esc(p.id)}" inputmode="numeric" size="4" placeholder="rank"></div>`).join("")}<div class="acts"><button class="btn pri" type="submit">Save ranks</button></div></form>`
|
|
1645
|
-
: `<p class="empty">No team plans to rank</p>`;
|
|
1646
|
-
const override = data.leader && data.plans.length
|
|
1647
|
-
? `<h2>Override<small>leader: this order wins over the ranks</small></h2><div class="card"><form method="post" action="/override">${data.plans.map((p, i) => `<div class="mrow"><span>${esc(p.title)}</span><input name="pos:${esc(p.id)}" inputmode="numeric" size="4" value="${i + 1}"></div>`).join("")}<div class="acts"><button class="btn pri" type="submit">Save override</button></div></form></div>`
|
|
1648
|
-
: "";
|
|
1649
|
-
const members = data.members.map(m => {
|
|
1650
|
-
const remove = data.admin && m !== data.adminLogin ? `<form method="post" action="/member"><input type="hidden" name="op" value="remove"><input type="hidden" name="login" value="${esc(m)}"><button class="btn" type="submit">Remove</button></form>` : "";
|
|
1651
|
-
return `<div class="tile"><span>${esc(m)}</span>${remove}</div>`;
|
|
1652
|
-
}).join("");
|
|
1653
|
-
const addMember = data.admin ? `<form class="msgform" method="post" action="/member"><input type="hidden" name="op" value="add"><input name="login" required placeholder="login"><div class="acts"><button class="btn pri" type="submit">Add member</button></div></form>` : "";
|
|
1654
|
-
const audit = data.audit === null ? "" : `<h2>Audit<small>newest 20</small></h2><div class="card">${data.audit.slice(0, 20).map(a => `<div class="mrow"><span>${esc(a.at)} ${esc(a.login)}</span><span class="mono">${esc(a.route)}</span></div>`).join("") || `<p class="empty">No audit rows</p>`}</div>`;
|
|
1655
|
-
return `<!doctype html>
|
|
1656
|
-
<html lang="en">
|
|
1657
|
-
<head>
|
|
1658
|
-
<meta charset="utf-8">
|
|
1659
|
-
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
1660
|
-
<title>neurastream · team ${esc(data.team)}</title>
|
|
1661
|
-
<link rel="icon" href="${FAVICON}">
|
|
1662
|
-
<style>${PAGE_CSS}</style>
|
|
1663
|
-
</head>
|
|
1664
|
-
<body>
|
|
1665
|
-
<div class="top"><span class="logo">ns</span><span class="sub">Team ${esc(data.team)} · ${esc(data.login)}</span></div>
|
|
1666
|
-
<main>
|
|
1667
|
-
<h2>Queue<small>team order</small></h2>
|
|
1668
|
-
<div class="card">${data.section.rows.length ? queueHtml(data.section.rows, "now", false) : `<p class="empty">No team plans</p>`}</div>
|
|
1669
|
-
<h2>Rank<small>your order for the team</small></h2>
|
|
1670
|
-
<div class="card">${ranking}</div>
|
|
1671
|
-
${override}
|
|
1672
|
-
<h2>Waiting</h2>
|
|
1673
|
-
<div class="card">${waiting}</div>
|
|
1674
|
-
<h2>Approve</h2>
|
|
1675
|
-
<div class="card">${approve}</div>
|
|
1676
|
-
<h2>Members</h2>
|
|
1677
|
-
<div class="card">${members}${addMember}</div>
|
|
1678
|
-
${audit}
|
|
1679
|
-
</main>
|
|
1680
|
-
</body>
|
|
1681
|
-
</html>
|
|
1682
|
-
`;
|
|
1683
|
-
}
|
|
1684
|
-
|
|
1685
|
-
/** The last answer appended per plan, for the double-press guard (P8c): memory only, no file. */
|
|
1686
|
-
const lastAnswerByPlan = new Map<string, { answer: string; ts: number }>();
|
|
1687
|
-
const DOUBLE_PRESS_SEC = 10;
|
|
1688
|
-
|
|
1689
|
-
/** Appends the answer to the owner inbox unless this plan got the same trimmed answer in the last 10 s (P8c). */
|
|
1690
|
-
function appendAnswer(plan: string, question: string, answer: string, login: string): void {
|
|
1691
|
-
const now = nowSec();
|
|
1692
|
-
const last = lastAnswerByPlan.get(plan);
|
|
1693
|
-
if (last !== undefined && last.answer === answer && now - last.ts < DOUBLE_PRESS_SEC) return;
|
|
1694
|
-
mkdirSync(stateDirPath(), { recursive: true });
|
|
1695
|
-
appendFileSync(inboxPath(), `${JSON.stringify({ ts: now, plan, question, answer, login })}\n`);
|
|
1696
|
-
lastAnswerByPlan.set(plan, { answer, ts: now });
|
|
1697
|
-
}
|
|
1698
|
-
|
|
1699
|
-
function handleAnswer(cfg: Config, source: RunSource, fields: Record<string, string>, login: string, wantsJson: boolean, pagesHost: string): Response {
|
|
1700
|
-
const planFile = (fields.plan ?? "").trim();
|
|
1701
|
-
const answer = (fields.answer_text ?? "").trim() || (fields.answer ?? "").trim();
|
|
1702
|
-
if (!planFile || !answer) return wantsJson ? jsonFail("plan and answer are required", 400) : textRes("plan and answer are required", 400);
|
|
1703
|
-
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);
|
|
1704
|
-
// P4: a team plan is answered on its server, never in this machine's inbox; the branch sits
|
|
1705
|
-
// before the INDEX lookup, which knows only this machine's own plans.
|
|
1706
|
-
if ((fields.team ?? "").trim()) return handleTeamAnswer(cfg, fields, planFile, answer, wantsJson);
|
|
1707
|
-
const plan = activePlans(cfg.paths.queue_index).find(p => p.file === planFile);
|
|
1708
|
-
if (!plan) return wantsJson ? jsonFail("plan is not open and waiting", 409) : textRes("plan is not open and waiting", 409);
|
|
1709
|
-
if (plan.status !== "open" || !plan.waiting || !plan.waitingLine) {
|
|
1710
|
-
// Stale answer (P8b): Main cleared the question before the answer arrived; pass it on anyway.
|
|
1711
|
-
appendAnswer(planFile, "(already cleared)", answer, login);
|
|
1712
|
-
if (wantsJson) return jsonSent("stale", receiptText("stale", new URLSearchParams()));
|
|
1713
|
-
return pageRes(cfg, source, new URLSearchParams({ sent: "stale" }), undefined, pagesHost);
|
|
1714
|
-
}
|
|
1715
|
-
appendAnswer(planFile, plan.waitingLine, answer, login);
|
|
1716
|
-
if (wantsJson) return jsonSent("answer", receiptText("answer", new URLSearchParams()));
|
|
1717
|
-
return redirect(sentTo(fields.tab ?? "", "sent=answer"));
|
|
1718
|
-
}
|
|
1719
|
-
|
|
1720
|
-
/**
|
|
1721
|
-
* An answer to a team plan (P4): `POST /answer/<id>` on that team's server with the answer
|
|
1722
|
-
* alone — the server stores the whois login — and nothing is written to this machine's inbox,
|
|
1723
|
-
* which belongs to its own Main. The double-press guard is the page's own memory, keyed
|
|
1724
|
-
* `<team>/<id>`; a repeated press within 10 s sends nothing again.
|
|
1725
|
-
*/
|
|
1726
|
-
function handleTeamAnswer(cfg: Config, fields: Record<string, string>, planId: string, answer: string, wantsJson: boolean): Response {
|
|
1727
|
-
const name = (fields.team ?? "").trim();
|
|
1728
|
-
const team = cfg.teams.find(t => t.name === name);
|
|
1729
|
-
if (!team) return wantsJson ? jsonFail("unknown team", 400) : textRes("unknown team", 400);
|
|
1730
|
-
const key = `${team.name}/${planId}`;
|
|
1731
|
-
const now = nowSec();
|
|
1732
|
-
const last = lastAnswerByPlan.get(key);
|
|
1733
|
-
const repeat = last !== undefined && last.answer === answer && now - last.ts < DOUBLE_PRESS_SEC;
|
|
1734
|
-
let earlier: TeamEarlier | null = null;
|
|
1735
|
-
if (!repeat) {
|
|
1736
|
-
const out = postTeamAnswer(team, planId, answer);
|
|
1737
|
-
if ("unreachable" in out) return wantsJson ? jsonFail(`team server ${out.unreachable} unreachable`, 503) : textRes(`team server ${out.unreachable} unreachable`, 503);
|
|
1738
|
-
if (!out.ok) {
|
|
1739
|
-
const error = out.status === 404 ? "plan is not on the team server" : out.error;
|
|
1740
|
-
return wantsJson ? jsonFail(error, out.status === 404 ? 409 : out.status) : textRes(error, out.status === 404 ? 409 : out.status);
|
|
1741
|
-
}
|
|
1742
|
-
lastAnswerByPlan.set(key, { answer, ts: now });
|
|
1743
|
-
earlier = out.earlier;
|
|
1744
|
-
}
|
|
1745
|
-
const note = earlier ? `answer kept; an earlier answer by ${earlier.login} at ${strftime(earlier.time, "%H:%M")} won: "${earlier.answer}"` : null;
|
|
1746
|
-
if (wantsJson) return jsonSent("team-answer", note ?? receiptText("team-answer", new URLSearchParams({ team: team.name })));
|
|
1747
|
-
if (note) return textRes(note, 200);
|
|
1748
|
-
return redirect(sentTo(fields.tab ?? "", `sent=team-answer&team=${encodeURIComponent(team.name)}`));
|
|
1749
|
-
}
|
|
1750
|
-
|
|
1751
|
-
// ---- POST /incident (plan P3): the owner's tap on a finding: "false alarm" closes it, "bug" plans it ----
|
|
1752
|
-
function handleIncident(cfg: Config, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
|
|
1753
|
-
const id = (fields.id ?? "").trim();
|
|
1754
|
-
const choice = (fields.choice ?? "").trim();
|
|
1755
|
-
const fail = (error: string, status: number): Response => (wantsJson ? jsonFail(error, status) : textRes(error, status));
|
|
1756
|
-
if (choice !== "bug" && choice !== "false") return fail("choice must be bug or false", 400);
|
|
1757
|
-
const view = openIncidents(cfg).find(i => i.id === id);
|
|
1758
|
-
if (!view) return fail("incident is not open", 409);
|
|
1759
|
-
if (!isFindingKind(view.kind)) return fail("only a finding is tapped here", 409);
|
|
1760
|
-
if (choice === "false") {
|
|
1761
|
-
const why = `owner tapped "false alarm" on the phone page (${login}): ${view.proposal?.why ?? "no reason given"}`;
|
|
1762
|
-
const err = dismissIncident(cfg, id, why, undefined, login);
|
|
1763
|
-
if (err) return fail(err, 409);
|
|
1764
|
-
if (wantsJson) return jsonSent("incident-closed", receiptText("incident-closed", new URLSearchParams()));
|
|
1765
|
-
return redirect(sentTo(fields.tab ?? "", "sent=incident-closed"));
|
|
1766
|
-
}
|
|
1767
|
-
storeOwnerMessage(`${id}: it's a bug — plan it`, login, [], "");
|
|
1768
|
-
if (wantsJson) return jsonSent("incident-bug", receiptText("incident-bug", new URLSearchParams()));
|
|
1769
|
-
return redirect(sentTo(fields.tab ?? "", "sent=incident-bug"));
|
|
1770
|
-
}
|
|
1771
|
-
|
|
1772
|
-
/** Stores an owner message (text and images) under a new id and inboxes it for Main (P13/P14). */
|
|
1773
|
-
function storeOwnerMessage(text: string, login: string, images: { bytes: Uint8Array; kind: string }[], to: string): void {
|
|
1774
|
-
const ts = nowSec();
|
|
1775
|
-
// The dir name starts with a whole-second ts: the sweep and the image route both parse it.
|
|
1776
|
-
const id = `${Math.floor(ts)}-${randomUUID().slice(0, 6)}`;
|
|
1777
|
-
const dir = `${ownerMessagesDir()}/${id}`;
|
|
1778
|
-
mkdirSync(dir, { recursive: true });
|
|
1779
|
-
const names: string[] = [];
|
|
1780
|
-
for (let i = 0; i < images.length; i++) {
|
|
1781
|
-
const name = `${i + 1}.${IMAGE_EXT[images[i]!.kind]}`;
|
|
1782
|
-
writeFileSync(`${dir}/${name}`, images[i]!.bytes);
|
|
1783
|
-
names.push(name);
|
|
1784
|
-
}
|
|
1785
|
-
writeFileSync(`${dir}/message.json`, `${JSON.stringify({ ts, text, login, to, images: names })}\n`);
|
|
1786
|
-
mkdirSync(stateDirPath(), { recursive: true });
|
|
1787
|
-
// The text stays out of owner-inbox.jsonl; Main reads message.json through the id (P14).
|
|
1788
|
-
appendFileSync(inboxPath(), `${JSON.stringify({ ts, kind: "message", id, login, to })}\n`);
|
|
1789
|
-
}
|
|
1790
|
-
|
|
1791
|
-
// ---- POST /message (plan P13): the owner's one-way note plus images, inboxed by id ----
|
|
1792
|
-
|
|
1793
|
-
async function handleMessage(req: Request, cfg: Config, login: string, wantsJson: boolean): Promise<Response> {
|
|
1794
|
-
sweepOwnerMessages(nowSec());
|
|
1795
|
-
const form = await req.formData();
|
|
1796
|
-
let text = "";
|
|
1797
|
-
let toField = "";
|
|
1798
|
-
const files: File[] = [];
|
|
1799
|
-
for (const [key, value] of form.entries()) {
|
|
1800
|
-
if (key === "text" && typeof value === "string") text = value.trim();
|
|
1801
|
-
else if (key === "to" && typeof value === "string") toField = value;
|
|
1802
|
-
// A form sent with no file chosen still carries one empty, nameless file part (Bun parses it as a nameless Blob).
|
|
1803
|
-
else if (key === "images" && (value as unknown) instanceof Blob) {
|
|
1804
|
-
const part = value as unknown as File;
|
|
1805
|
-
if (part.size > 0 || Boolean(part.name)) files.push(part);
|
|
1806
|
-
}
|
|
1807
|
-
}
|
|
1808
|
-
const fail = (error: string): Response => (wantsJson ? jsonFail(error, 400) : textRes(error, 400));
|
|
1809
|
-
if (!text && !files.length) return fail("write a text or attach an image");
|
|
1810
|
-
if (text.length > MESSAGE_MAX) return fail(`text is longer than ${MESSAGE_MAX} chars`);
|
|
1811
|
-
if (files.length > MESSAGE_IMAGES_MAX) return fail(`at most ${MESSAGE_IMAGES_MAX} images per message`);
|
|
1812
|
-
const images: { bytes: Uint8Array; kind: string }[] = [];
|
|
1813
|
-
for (const file of files) {
|
|
1814
|
-
if (file.size > MESSAGE_IMAGE_MAX_BYTES) return fail("an image is larger than 10 MB");
|
|
1815
|
-
const data = new Uint8Array(await file.arrayBuffer());
|
|
1816
|
-
const kind = imageType(data);
|
|
1817
|
-
if (!kind) return fail("attachments must be PNG, JPEG, GIF or WEBP images — the type is read from the file itself");
|
|
1818
|
-
images.push({ bytes: data, kind });
|
|
1819
|
-
}
|
|
1820
|
-
// P5: an `@<id>` prefix or the picker's to field names one Main; a stale name is refused before anything is stored.
|
|
1821
|
-
const pick = ownerMessageTarget(text, cfg, toField);
|
|
1822
|
-
if ("refuse" in pick) return fail(pick.refuse);
|
|
1823
|
-
storeOwnerMessage(text, login, images, pick.to);
|
|
1824
|
-
if (wantsJson) return jsonSent("message", receiptText("message", new URLSearchParams()));
|
|
1825
|
-
return redirect("/?sent=message");
|
|
1826
|
-
}
|
|
1827
|
-
|
|
1828
|
-
/** 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. */
|
|
1829
|
-
function handleMessageImage(id: string, file: string): Response {
|
|
1830
|
-
if (!/^[0-9]+-[0-9a-f]{6}$/.test(id) || !/^[0-9]+\.(png|jpg|gif|webp)$/.test(file)) return textRes("not found", 404);
|
|
1831
|
-
let meta: Record<string, unknown>;
|
|
1832
|
-
try {
|
|
1833
|
-
meta = JSON.parse(readFileSync(`${ownerMessagesDir()}/${id}/message.json`, "utf8")) as Record<string, unknown>;
|
|
1834
|
-
} catch {
|
|
1835
|
-
return textRes("not found", 404);
|
|
1836
|
-
}
|
|
1837
|
-
const names = Array.isArray(meta.images) ? meta.images.filter((n): n is string => typeof n === "string") : [];
|
|
1838
|
-
if (!names.includes(file)) return textRes("not found", 404);
|
|
1839
|
-
try {
|
|
1840
|
-
return new Response(readFileSync(`${ownerMessagesDir()}/${id}/${file}`), {
|
|
1841
|
-
headers: { "content-type": IMAGE_MIME[file.slice(file.lastIndexOf(".") + 1)] ?? "application/octet-stream" },
|
|
1842
|
-
});
|
|
1843
|
-
} catch {
|
|
1844
|
-
return textRes("not found", 404);
|
|
1845
|
-
}
|
|
1846
|
-
}
|
|
1847
|
-
|
|
1848
|
-
function handleUnlock(cfg: Config, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
|
|
1849
|
-
const minutes = fields.minutes ?? "";
|
|
1850
|
-
if (minutes !== "" && !/^\d+$/.test(minutes)) return wantsJson ? jsonFail("minutes must be a number", 400) : textRes("minutes must be a number", 400);
|
|
1851
|
-
const result = chatUnlock(minutes === "" ? "unlock" : `unlock ${minutes}`, cfg, `ui:${login}`, "ui");
|
|
1852
|
-
if (!result.applied) return wantsJson ? jsonFail("Refused — chat unlock is off", 400) : redirect(sentTo(fields.tab ?? "", "sent=unlock-off"));
|
|
1853
|
-
mkdirSync(stateDirPath(), { recursive: true });
|
|
1854
|
-
appendFileSync(
|
|
1855
|
-
inboxPath(),
|
|
1856
|
-
`${JSON.stringify({ ts: nowSec(), kind: "unlock", minutes: result.minutes, until: result.until, login })}\n`,
|
|
1857
|
-
);
|
|
1858
|
-
if (wantsJson) return jsonSent("unlock", receiptText("unlock", new URLSearchParams({ minutes: String(result.minutes) })));
|
|
1859
|
-
return redirect(sentTo(fields.tab ?? "", `sent=unlock&minutes=${result.minutes}`));
|
|
1860
|
-
}
|
|
1861
|
-
|
|
1862
|
-
function handleLock(cfg: Config, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
|
|
1863
|
-
const result = chatUnlock("lock", cfg, `ui:${login}`, "ui");
|
|
1864
|
-
if (!result.applied) return wantsJson ? jsonFail("Refused — chat unlock is off", 400) : redirect(sentTo(fields.tab ?? "", "sent=unlock-off"));
|
|
1865
|
-
mkdirSync(stateDirPath(), { recursive: true });
|
|
1866
|
-
appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), kind: "lock", login })}\n`);
|
|
1867
|
-
if (wantsJson) return jsonSent("lock", receiptText("lock", new URLSearchParams()));
|
|
1868
|
-
return redirect(sentTo(fields.tab ?? "", "sent=lock"));
|
|
1869
|
-
}
|
|
1870
|
-
|
|
1871
|
-
const TIERS: readonly Tier[] = ["strict", "opinionated", "full"];
|
|
1872
|
-
|
|
1873
|
-
// Autonomy tier from the phone page (plan 20261025_1940 P3): behind the same auth as every other
|
|
1874
|
-
// route, written by the core chatTier with the owner's tapped name; a bad name is a 400 before
|
|
1875
|
-
// the core is called, and the chat gate off redirects to the plain-words note like unlock/lock.
|
|
1876
|
-
function handleTier(cfg: Config, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
|
|
1877
|
-
const name = (fields.tier ?? "").trim().toLowerCase();
|
|
1878
|
-
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);
|
|
1879
|
-
const result = chatTier(`tier ${name}`, cfg, `ui:${login}`, "ui");
|
|
1880
|
-
if (!result.applied) return wantsJson ? jsonFail("Refused — chat unlock is off", 400) : redirect(sentTo(fields.tab ?? "", "sent=unlock-off"));
|
|
1881
|
-
mkdirSync(stateDirPath(), { recursive: true });
|
|
1882
|
-
appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), kind: "tier", tier: result.tier, login })}\n`);
|
|
1883
|
-
if (wantsJson) return jsonSent("tier");
|
|
1884
|
-
return redirect(sentTo(fields.tab ?? "", `sent=tier&tier=${result.tier}`));
|
|
1885
|
-
}
|
|
1886
|
-
|
|
1887
|
-
// ---- queue reorder (plan P4): the owner drags a card; INDEX.md is rewritten atomically ----
|
|
1888
|
-
|
|
1889
|
-
/**
|
|
1890
|
-
* The index text with its open-plan groups reordered: a group is a plan line plus the non-plan
|
|
1891
|
-
* lines (blank or `<!--` comment) attached above it, and the open groups — the first line of
|
|
1892
|
-
* each path in `openPaths`, in file order — are replaced by the groups of `order`, so every open
|
|
1893
|
-
* plan moves with its comment lines while every other plan line keeps its slot (a path listed
|
|
1894
|
-
* twice keeps both lines). Lines after the last plan keep the file's end. Returns null when an
|
|
1895
|
-
* order path is no longer in the file.
|
|
1896
|
-
*/
|
|
1897
|
-
function reorderedIndexText(index: string, order: string[], openPaths: ReadonlySet<string>): string | null {
|
|
1898
|
-
let text: string;
|
|
1899
|
-
try {
|
|
1900
|
-
text = readFileSync(index, "utf8");
|
|
1901
|
-
} catch {
|
|
1902
|
-
return null;
|
|
1903
|
-
}
|
|
1904
|
-
const groups: { path: string; lines: string[] }[] = [];
|
|
1905
|
-
let pending: string[] = [];
|
|
1906
|
-
for (const raw of text.split("\n")) {
|
|
1907
|
-
const norm = raw
|
|
1908
|
-
.trim()
|
|
1909
|
-
.replace(/^[-*]\s+/, "")
|
|
1910
|
-
.trim();
|
|
1911
|
-
if (!norm || norm.startsWith("<!--")) {
|
|
1912
|
-
pending.push(raw);
|
|
1913
|
-
continue;
|
|
1914
|
-
}
|
|
1915
|
-
groups.push({ path: resolve(process.cwd(), expandHome(norm.replace(/`/g, ""))), lines: [...pending, raw] });
|
|
1916
|
-
pending = [];
|
|
1917
|
-
}
|
|
1918
|
-
// The open slots in file order: the first line of each open path; a later duplicate of the
|
|
1919
|
-
// same path keeps its place like a non-open line, so a path listed twice keeps both lines.
|
|
1920
|
-
const byPath = new Map<string, number>();
|
|
1921
|
-
const slots: number[] = [];
|
|
1922
|
-
const seen = new Set<string>();
|
|
1923
|
-
for (const [i, g] of groups.entries()) {
|
|
1924
|
-
if (!byPath.has(g.path)) byPath.set(g.path, i);
|
|
1925
|
-
if (openPaths.has(g.path) && !seen.has(g.path)) {
|
|
1926
|
-
seen.add(g.path);
|
|
1927
|
-
slots.push(i);
|
|
1928
|
-
}
|
|
1929
|
-
}
|
|
1930
|
-
if (slots.length !== order.length) return null;
|
|
1931
|
-
const parts: string[] = [];
|
|
1932
|
-
let k = 0;
|
|
1933
|
-
for (let i = 0; i < groups.length; i++) {
|
|
1934
|
-
if (slots[k] === i) {
|
|
1935
|
-
const at = byPath.get(order[k] ?? "");
|
|
1936
|
-
if (at === undefined) return null;
|
|
1937
|
-
parts.push(...groups[at]!.lines);
|
|
1938
|
-
k++;
|
|
1939
|
-
} else {
|
|
1940
|
-
parts.push(...groups[i]!.lines);
|
|
1941
|
-
}
|
|
1942
|
-
}
|
|
1943
|
-
parts.push(...pending);
|
|
1944
|
-
return parts.join("\n");
|
|
1945
|
-
}
|
|
1946
|
-
|
|
1947
|
-
function handleReorder(cfg: Config, fields: Record<string, string>, login: string, wantsJson: boolean): Response {
|
|
1948
|
-
const index = cfg.paths.queue_index;
|
|
1949
|
-
const order = (fields.order ?? "")
|
|
1950
|
-
.split("\n")
|
|
1951
|
-
.map(l => l.trim())
|
|
1952
|
-
.filter(l => l.length > 0);
|
|
1953
|
-
const before = (fields.before ?? "")
|
|
1954
|
-
.split("\n")
|
|
1955
|
-
.map(l => l.trim())
|
|
1956
|
-
.filter(l => l.length > 0);
|
|
1957
|
-
const moved = (fields.moved ?? "").trim();
|
|
1958
|
-
// The page's drag and arrow buttons send this over fetch (accept: application/json) and read
|
|
1959
|
-
// the JSON reply; a no-JS form post still gets the 303. Errors follow the same split.
|
|
1960
|
-
const fail = (error: string, status: number): Response =>
|
|
1961
|
-
wantsJson ? Response.json({ ok: false, error }, { status }) : textRes(error, status);
|
|
1962
|
-
// One source of truth for the reorderable set: the open plans, the same list queueRows renders.
|
|
1963
|
-
const openPlans = activePlans(index).filter(p => p.status === "open");
|
|
1964
|
-
const openPaths = openPlans.map(p => p.file);
|
|
1965
|
-
const openPlan: Record<string, Plan> = Object.fromEntries(openPlans.map(p => [p.file, p]));
|
|
1966
|
-
if (!moved || !order.length) return fail("order and moved are required", 400);
|
|
1967
|
-
// 400: the posted order must be exactly the open plans the page renders now — no adds, drops or duplicates.
|
|
1968
|
-
if (new Set(order).size !== order.length) return fail("order lists a plan more than once", 400);
|
|
1969
|
-
const sortedOrder = [...order].sort();
|
|
1970
|
-
const sortedOpen = [...openPaths].sort();
|
|
1971
|
-
const sameSet = order.length === openPaths.length && sortedOrder.every((p, i) => p === sortedOpen[i]);
|
|
1972
|
-
if (!sameSet) return fail("order is not exactly the plans now on the page", 400);
|
|
1973
|
-
// 409: the order the page was rendered with must still be the open plans' current order.
|
|
1974
|
-
const stale = before.length !== openPaths.length || before.some((p, i) => p !== openPaths[i]);
|
|
1975
|
-
if (stale) return fail("the queue changed since the page loaded — reload and drag again", 409);
|
|
1976
|
-
// 409: the index is priority (I-20261025-208), so the posted order itself may not put a plan
|
|
1977
|
-
// above the open plan it waits on. Checked before any write: the index file and the reorder
|
|
1978
|
-
// inbox stay untouched, and the page's 409 branch shows the message and reloads the real order.
|
|
1979
|
-
const firstBlock = dependencyOrderProblems(order.map(o => openPlan[o]!))[0];
|
|
1980
|
-
if (firstBlock) return fail(`blocked: ${firstBlock}`, 409);
|
|
1981
|
-
const from = openPaths.indexOf(moved);
|
|
1982
|
-
const to = order.indexOf(moved);
|
|
1983
|
-
if (from === -1 || to === -1) return fail("moved is not one of the page's plans", 400);
|
|
1984
|
-
const newText = reorderedIndexText(index, order, new Set(openPaths));
|
|
1985
|
-
if (newText === null) return fail("the queue index no longer lists every open plan", 400);
|
|
1986
|
-
// The queue library owns every index write (plan 20261031_0911 P2): a reorder is the same plan
|
|
1987
|
-
// set, so no removal reason, and the write lands temp+rename and leaves the file 0444.
|
|
1988
|
-
writeIndex(newText.trimEnd().split("\n"), undefined, index);
|
|
1989
|
-
mkdirSync(stateDirPath(), { recursive: true });
|
|
1990
|
-
appendFileSync(inboxPath(), `${JSON.stringify({ ts: nowSec(), kind: "reorder", plan: moved, from: from + 1, to: to + 1, login })}\n`);
|
|
1991
|
-
if (wantsJson) return Response.json({ ok: true, to: to + 1 });
|
|
1992
|
-
return redirect(sentTo(fields.tab ?? "", `sent=reorder&to=${to + 1}`));
|
|
1993
|
-
}
|
|
1994
|
-
|
|
1995
|
-
/**
|
|
1996
|
-
* DNS-rebinding guard, built once per server. A page on another host sends that Host with a
|
|
1997
|
-
* matching Origin, so the peer and Origin checks alone would pass it. The Host header must
|
|
1998
|
-
* name this server — the tailnet address or the MagicDNS name (dnsName(), trailing dot already
|
|
1999
|
-
* stripped) — with the served port. No bound port: nothing is allowed. The phone page and the
|
|
2000
|
-
* team server both call this.
|
|
2001
|
-
*/
|
|
2002
|
-
export function hostAllowlist(tailscale: { ip4(): string | null; dnsName(): string | null }): (hostHeader: string, port: number | undefined) => boolean {
|
|
2003
|
-
let allowedHosts: string[] | null = null;
|
|
2004
|
-
return (hostHeader, port) => {
|
|
2005
|
-
// No bound port (never expected): nothing is allowed — fail closed.
|
|
2006
|
-
if (port === undefined) return false;
|
|
2007
|
-
if (allowedHosts === null) {
|
|
2008
|
-
const dns = tailscale.dnsName();
|
|
2009
|
-
allowedHosts = [tailscale.ip4(), dns].filter((h): h is string => Boolean(h)).map(h => `${h}:${port}`);
|
|
2010
|
-
}
|
|
2011
|
-
return allowedHosts.includes(hostHeader);
|
|
2012
|
-
};
|
|
2013
|
-
}
|
|
2014
|
-
|
|
2015
|
-
/** True when Origin is exactly `http://` plus the Host header. Callers apply it to the methods they write. */
|
|
2016
|
-
export function originIsHost(origin: string | null, hostHeader: string): boolean {
|
|
2017
|
-
return origin === `http://${hostHeader}`;
|
|
2018
|
-
}
|
|
2019
|
-
|
|
2020
|
-
/** Starts the page. Refuses to start when workspace.enabled is false or workspace.owner_login is empty, and on the default hostname when tailscale does not answer. */
|
|
2021
|
-
export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
|
|
2022
|
-
const { cfg, tailscale, source } = opts;
|
|
2023
|
-
const resultsBuild = opts.resultsBuild ?? spawnResultsBuild;
|
|
2024
|
-
// The Base tab links to the pages server by its MagicDNS name, the same URL `pages publish` prints.
|
|
2025
|
-
const pagesHost = tailscale.dnsName() ?? "tailnet";
|
|
2026
|
-
// The double-press guard (P8c) is per-server memory: a fresh server starts empty, which also
|
|
2027
|
-
// keeps the tests (one server per test) hermetic.
|
|
2028
|
-
lastAnswerByPlan.clear();
|
|
2029
|
-
if (!cfg.workspace.enabled) throw new Error("owner ui: workspace.enabled is false — set it in the config first");
|
|
2030
|
-
if (!cfg.workspace.owner_login) throw new Error("owner ui: workspace.owner_login is empty — set the tailscale login that may open the page");
|
|
2031
|
-
const hostname = opts.hostname ?? tailscale.ip4();
|
|
2032
|
-
if (!hostname) throw new Error("owner ui: tailscale ip -4 did not answer — is tailscale up?");
|
|
2033
|
-
const peerOf = opts.peerOf ?? ((req: Request, server: UiHttpServer) => server.requestIP(req)?.address ?? "");
|
|
2034
|
-
const hostAllowed = hostAllowlist(tailscale);
|
|
2035
|
-
const server = Bun.serve({
|
|
2036
|
-
hostname,
|
|
2037
|
-
port: opts.port ?? cfg.workspace.port,
|
|
2038
|
-
fetch: async (req, srv) => {
|
|
2039
|
-
const url = new URL(req.url);
|
|
2040
|
-
let code = 500;
|
|
2041
|
-
let login: string | null = null;
|
|
2042
|
-
let res: Response;
|
|
2043
|
-
try {
|
|
2044
|
-
const hostHeader = req.headers.get("host") ?? "";
|
|
2045
|
-
if (!hostAllowed(hostHeader, srv.port)) {
|
|
2046
|
-
res = textRes("forbidden: host is not this page", 403);
|
|
2047
|
-
code = 403;
|
|
2048
|
-
} else {
|
|
2049
|
-
const auth = authenticate(cfg, tailscale, peerOf(req, srv));
|
|
2050
|
-
if (!auth.ok) {
|
|
2051
|
-
res = textRes("forbidden: this page serves only the owner", 403);
|
|
2052
|
-
code = 403;
|
|
2053
|
-
} else {
|
|
2054
|
-
login = auth.login;
|
|
2055
|
-
if (req.method === "POST" && !originIsHost(req.headers.get("origin"), hostHeader)) {
|
|
2056
|
-
res = textRes("forbidden: origin is not this page", 403);
|
|
2057
|
-
code = 403;
|
|
2058
|
-
} else if (req.method === "GET" && url.pathname === "/") {
|
|
2059
|
-
sweepOwnerMessages(nowSec());
|
|
2060
|
-
res = pageRes(cfg, source, url.searchParams, resultsBuild, pagesHost);
|
|
2061
|
-
code = 200;
|
|
2062
|
-
} else if (req.method === "GET" && url.pathname.startsWith("/knowledge/")) {
|
|
2063
|
-
// The Knowledge tab's frame: the topic's own file bytes, GET only, no write path.
|
|
2064
|
-
const topicPath = /^\/knowledge\/([^/]+)\/([^/]+)$/.exec(url.pathname);
|
|
2065
|
-
const bytes =
|
|
2066
|
-
topicPath === null
|
|
2067
|
-
? null
|
|
2068
|
-
: readKnowledgeTopicFile(cfg, urlField(topicPath[1]!), urlField(topicPath[2]!));
|
|
2069
|
-
res = bytes === null ? textRes("not found", 404) : new Response(bytes, { headers: { "content-type": "text/html; charset=utf-8" } });
|
|
2070
|
-
code = res.status;
|
|
2071
|
-
} else if (req.method === "GET" && url.pathname.startsWith("/message-image/")) {
|
|
2072
|
-
const mim = /^\/message-image\/([^/]+)\/([^/]+)$/.exec(url.pathname);
|
|
2073
|
-
res = mim ? handleMessageImage(mim[1]!, mim[2]!) : textRes("not found", 404);
|
|
2074
|
-
code = res.status;
|
|
2075
|
-
} else if (req.method === "POST") {
|
|
2076
|
-
// The page's script asks for JSON on every POST (P11b); a no-JS form post gets today's 303s.
|
|
2077
|
-
const wantsJson = (req.headers.get("accept") ?? "").includes("application/json");
|
|
2078
|
-
if (url.pathname === "/message") {
|
|
2079
|
-
res = await handleMessage(req, cfg, login, wantsJson);
|
|
2080
|
-
code = res.status;
|
|
2081
|
-
} else if (url.pathname === "/incident") {
|
|
2082
|
-
res = handleIncident(cfg, await fieldsOf(req), login, wantsJson);
|
|
2083
|
-
code = res.status;
|
|
2084
|
-
} else if (url.pathname === "/answer") {
|
|
2085
|
-
res = handleAnswer(cfg, source, await fieldsOf(req), login, wantsJson, pagesHost);
|
|
2086
|
-
code = res.status;
|
|
2087
|
-
} else if (url.pathname === "/unlock") {
|
|
2088
|
-
res = handleUnlock(cfg, await fieldsOf(req), login, wantsJson);
|
|
2089
|
-
code = res.status;
|
|
2090
|
-
} else if (url.pathname === "/lock") {
|
|
2091
|
-
res = handleLock(cfg, await fieldsOf(req), login, wantsJson);
|
|
2092
|
-
code = res.status;
|
|
2093
|
-
} else if (url.pathname === "/tier") {
|
|
2094
|
-
res = handleTier(cfg, await fieldsOf(req), login, wantsJson);
|
|
2095
|
-
code = res.status;
|
|
2096
|
-
} else if (url.pathname === "/reorder") {
|
|
2097
|
-
res = handleReorder(cfg, await fieldsOf(req), login, wantsJson);
|
|
2098
|
-
code = res.status;
|
|
2099
|
-
} else {
|
|
2100
|
-
res = textRes("not found", 404);
|
|
2101
|
-
code = 404;
|
|
2102
|
-
}
|
|
2103
|
-
} else {
|
|
2104
|
-
res = textRes("not found", 404);
|
|
2105
|
-
code = 404;
|
|
2106
|
-
}
|
|
2107
|
-
}
|
|
2108
|
-
}
|
|
2109
|
-
} catch {
|
|
2110
|
-
res = textRes("internal error", 500);
|
|
2111
|
-
code = 500;
|
|
2112
|
-
}
|
|
2113
|
-
log(cfg.paths.guard_log, `UI ${req.method} ${url.pathname} login=${login ?? "-"} → ${code}`);
|
|
2114
|
-
return res;
|
|
2115
|
-
},
|
|
2116
|
-
});
|
|
2117
|
-
return { stop: () => server.stop(true), hostname, port: Number(server.port) };
|
|
2118
|
-
}
|
|
1
|
+
// Owner phone page barrel: re-exports the decomposed modules under src/core/owner-ui/.
|
|
2
|
+
// `owner-ui/auth.ts` is exported first so shared constants (`ANSWER_MAX`, `fieldsOf`, `hostAllowlist`,
|
|
3
|
+
// `pageCsp`, etc.) imported by `team-server.ts` and `pages-server.ts` initialize cleanly.
|
|
4
|
+
|
|
5
|
+
export * from "./owner-ui/auth.ts";
|
|
6
|
+
export * from "./owner-ui/messages.ts";
|
|
7
|
+
export * from "./owner-ui/results.ts";
|
|
8
|
+
export * from "./owner-ui/data.ts";
|
|
9
|
+
export * from "./owner-ui/render.ts";
|
|
10
|
+
export * from "./owner-ui/handlers.ts";
|
|
11
|
+
export * from "./owner-ui/server.ts";
|