devcontour-harness-ui 0.0.0-stage → 0.1.0-alpha.2

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.
Files changed (58) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +143 -2
  3. package/dist/app/assets/index-Det9VYJC.css +1 -0
  4. package/dist/app/assets/index-veveke8K.js +9 -0
  5. package/dist/app/index.html +13 -0
  6. package/dist/demo/ru/view.sample.json +483 -0
  7. package/dist/demo/ru/work.accepted.sample.json +187 -0
  8. package/dist/demo/ru/work.sample.json +171 -0
  9. package/dist/demo/view.sample.json +483 -0
  10. package/dist/demo/work.accepted.sample.json +187 -0
  11. package/dist/demo/work.sample.json +171 -0
  12. package/dist/lib/cli.d.ts +2 -0
  13. package/dist/lib/cli.js +160 -0
  14. package/dist/lib/components/Activity.d.ts +13 -0
  15. package/dist/lib/components/Activity.js +19 -0
  16. package/dist/lib/components/Decisions.d.ts +6 -0
  17. package/dist/lib/components/Decisions.js +19 -0
  18. package/dist/lib/components/Health.d.ts +8 -0
  19. package/dist/lib/components/Health.js +24 -0
  20. package/dist/lib/components/History.d.ts +32 -0
  21. package/dist/lib/components/History.js +129 -0
  22. package/dist/lib/components/Overview.d.ts +19 -0
  23. package/dist/lib/components/Overview.js +54 -0
  24. package/dist/lib/components/Reviews.d.ts +23 -0
  25. package/dist/lib/components/Reviews.js +22 -0
  26. package/dist/lib/components/Settings.d.ts +21 -0
  27. package/dist/lib/components/Settings.js +77 -0
  28. package/dist/lib/components/WorkDetail.d.ts +18 -0
  29. package/dist/lib/components/WorkDetail.js +96 -0
  30. package/dist/lib/components/common.d.ts +71 -0
  31. package/dist/lib/components/common.js +85 -0
  32. package/dist/lib/index.d.ts +10 -0
  33. package/dist/lib/index.js +12 -0
  34. package/dist/lib/model/compat.d.ts +36 -0
  35. package/dist/lib/model/compat.js +365 -0
  36. package/dist/lib/model/dict.d.ts +387 -0
  37. package/dist/lib/model/dict.js +1119 -0
  38. package/dist/lib/model/format.d.ts +34 -0
  39. package/dist/lib/model/format.js +88 -0
  40. package/dist/lib/model/i18n.d.ts +44 -0
  41. package/dist/lib/model/i18n.js +109 -0
  42. package/dist/lib/model/index.d.ts +6 -0
  43. package/dist/lib/model/index.js +8 -0
  44. package/dist/lib/model/source.d.ts +16 -0
  45. package/dist/lib/model/source.js +57 -0
  46. package/dist/lib/model/view.d.ts +474 -0
  47. package/dist/lib/model/view.js +10 -0
  48. package/dist/lib/server/harness.d.ts +44 -0
  49. package/dist/lib/server/harness.js +172 -0
  50. package/dist/lib/server/serve.d.ts +62 -0
  51. package/dist/lib/server/serve.js +302 -0
  52. package/dist/lib/styles.css +485 -0
  53. package/docs/design.md +1689 -0
  54. package/docs/harness-proposals.md +560 -0
  55. package/docs/release-notes/0.1.0-alpha.1.md +96 -0
  56. package/docs/release-notes/0.1.0-alpha.2.md +218 -0
  57. package/package.json +75 -4
  58. package/skills/harness-ui/SKILL.md +246 -0
@@ -0,0 +1,172 @@
1
+ // Live view route (`--state`): the view is computed by the harness the user
2
+ // installed, never by this package. `harness capabilities` decides whether
3
+ // the installed harness has `view` (0.1.0-alpha.55 or newer) and whether it
4
+ // takes `--lang`; `harness view --state <dir> [--policy <file>] [--lang ru|en]`
5
+ // prints the envelope `{ ok, data }` on stdout. The harness CLI prints JSON
6
+ // by default and has no `--json` flag, so none is passed.
7
+ import { spawn } from 'node:child_process';
8
+ export class HarnessUnavailable extends Error {
9
+ code = 'HARNESS_VIEW_UNAVAILABLE';
10
+ }
11
+ const TIMEOUT_MS = 30_000;
12
+ /** After SIGTERM, how long a run may take to exit before SIGKILL. */
13
+ const KILL_GRACE_MS = 2_000;
14
+ // The view is at most 256 KB; the capabilities catalog carries JSON Schemas.
15
+ const MAX_BUFFER = 8 * 1024 * 1024;
16
+ const posix = process.platform !== 'win32';
17
+ /** Harness runs still alive; `stopHarnessRuns` ends them on shutdown. */
18
+ const active = new Set();
19
+ function signal(child, sig) {
20
+ try {
21
+ // The run is its own process group, so a wrapper (sh, npx) and its
22
+ // children go with it.
23
+ if (posix && child.pid !== undefined)
24
+ process.kill(-child.pid, sig);
25
+ else
26
+ child.kill(sig);
27
+ }
28
+ catch {
29
+ // Already gone.
30
+ }
31
+ }
32
+ /** SIGTERM now, SIGKILL after the grace period if it is still running. */
33
+ function terminate(child) {
34
+ signal(child, 'SIGTERM');
35
+ const t = setTimeout(() => signal(child, 'SIGKILL'), KILL_GRACE_MS);
36
+ t.unref();
37
+ child.once('exit', () => clearTimeout(t));
38
+ }
39
+ /**
40
+ * Terminates every running harness process (panel shutdown) and resolves
41
+ * once they exited; one that ignores SIGTERM is killed after the grace period.
42
+ */
43
+ export function stopHarnessRuns() {
44
+ const exits = [...active].map((child) => new Promise((ok) => {
45
+ if (child.exitCode !== null || child.signalCode !== null)
46
+ return ok();
47
+ const t = setTimeout(ok, KILL_GRACE_MS + 1_000);
48
+ child.once('exit', () => {
49
+ clearTimeout(t);
50
+ ok();
51
+ });
52
+ terminate(child);
53
+ }));
54
+ return Promise.all(exits).then(() => undefined);
55
+ }
56
+ /**
57
+ * Runs the harness with a hard deadline: the promise settles at the deadline
58
+ * even if the process ignores SIGTERM (it is then killed after a grace period).
59
+ */
60
+ function run(bin, args, timeoutMs = TIMEOUT_MS) {
61
+ return new Promise((ok) => {
62
+ let settled = false;
63
+ const done = (r) => {
64
+ if (settled)
65
+ return;
66
+ settled = true;
67
+ clearTimeout(deadline);
68
+ ok(r);
69
+ };
70
+ let child;
71
+ try {
72
+ child = spawn(bin, args, {
73
+ stdio: ['ignore', 'pipe', 'ignore'],
74
+ detached: posix,
75
+ windowsHide: true,
76
+ });
77
+ }
78
+ catch (err) {
79
+ ok({ stdout: '', exit: undefined, spawnError: err.message });
80
+ return;
81
+ }
82
+ active.add(child);
83
+ const chunks = [];
84
+ let size = 0;
85
+ child.stdout.on('data', (c) => {
86
+ size += c.length;
87
+ if (size > MAX_BUFFER) {
88
+ terminate(child);
89
+ done({ stdout: '', exit: undefined, spawnError: 'output exceeds 8 MB' });
90
+ }
91
+ else
92
+ chunks.push(c);
93
+ });
94
+ const deadline = setTimeout(() => {
95
+ terminate(child);
96
+ done({ stdout: '', exit: undefined, spawnError: `timed out after ${timeoutMs} ms` });
97
+ }, timeoutMs);
98
+ child.once('error', (err) => {
99
+ active.delete(child);
100
+ done({ stdout: '', exit: undefined, spawnError: err.message });
101
+ });
102
+ child.once('close', (code, sig) => {
103
+ active.delete(child);
104
+ const stdout = Buffer.concat(chunks).toString('utf8');
105
+ if (code === null)
106
+ done({ stdout, exit: undefined, spawnError: `terminated by ${sig ?? 'a signal'}` });
107
+ else
108
+ done({ stdout, exit: code });
109
+ });
110
+ });
111
+ }
112
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
113
+ function parseEnvelope(stdout) {
114
+ try {
115
+ const parsed = JSON.parse(stdout);
116
+ return isObject(parsed) ? parsed : undefined;
117
+ }
118
+ catch {
119
+ return undefined;
120
+ }
121
+ }
122
+ /**
123
+ * Reads `harness capabilities`. A harness that cannot be started or prints
124
+ * no catalog is `HarnessUnavailable`; a catalog without `view` is reported
125
+ * as `{ view: false }` so the caller can name the installed version.
126
+ */
127
+ export async function probeHarness(bin) {
128
+ const r = await run(bin, ['capabilities']);
129
+ if (r.exit === undefined)
130
+ throw new HarnessUnavailable(`Cannot start \`${bin} capabilities\`: ${r.spawnError}.`);
131
+ const env = parseEnvelope(r.stdout);
132
+ const data = r.exit === 0 && env?.ok === true && isObject(env.data) ? env.data : undefined;
133
+ if (!data)
134
+ throw new HarnessUnavailable(`\`${bin} capabilities\` printed no capabilities catalog.`);
135
+ const tools = Array.isArray(data.tools) ? data.tools : [];
136
+ const view = tools.find((t) => isObject(t) && t.name === 'view');
137
+ const props = view?.inputSchema?.properties;
138
+ return {
139
+ ...(typeof data.version === 'string' ? { version: data.version } : {}),
140
+ view: view !== undefined,
141
+ lang: isObject(props) && Object.hasOwn(props, 'lang'),
142
+ };
143
+ }
144
+ /**
145
+ * Runs `harness view` once (`--work <id>` for the work detail document); a
146
+ * harness refusal comes back as `{ ok: false }`. The work id is passed as
147
+ * `--work=<id>` so an id can never be read as another flag.
148
+ */
149
+ export async function harnessView(o, lang, workId) {
150
+ const args = ['view', '--state', o.state];
151
+ if (o.policy !== undefined)
152
+ args.push('--policy', o.policy);
153
+ if (lang !== undefined)
154
+ args.push('--lang', lang);
155
+ if (workId !== undefined)
156
+ args.push(`--work=${workId}`);
157
+ const r = await run(o.bin, args, o.timeoutMs);
158
+ if (r.exit === undefined)
159
+ return { ok: false, code: 'VIEW_UNAVAILABLE', message: `harness view: ${r.spawnError}.` };
160
+ const env = parseEnvelope(r.stdout);
161
+ // Success needs both: exit 0 and a success envelope.
162
+ if (r.exit === 0 && env?.ok === true && 'data' in env)
163
+ return { ok: true, view: env.data };
164
+ const error = isObject(env?.error) ? env.error : undefined;
165
+ const code = typeof error?.code === 'string' && env?.ok === false ? error.code : `exit ${r.exit}`;
166
+ const message = env?.ok === false && typeof error?.message === 'string'
167
+ ? error.message
168
+ : env?.ok === true
169
+ ? 'a success envelope with a nonzero exit'
170
+ : 'no JSON envelope';
171
+ return { ok: false, code: 'VIEW_UNAVAILABLE', message: `harness view: ${code}: ${message}` };
172
+ }
@@ -0,0 +1,62 @@
1
+ import { type HarnessViewOptions } from './harness.ts';
2
+ export declare const LOOPBACK_HOSTS: readonly ["127.0.0.1", "::1", "localhost"];
3
+ export declare const DEFAULT_PORT = 4790;
4
+ /** How many consecutive ports the probe tries when no port was given. */
5
+ export declare const PORT_PROBE_SPAN = 20;
6
+ /** Harness processes the live route runs at once; more requests queue. */
7
+ export declare const MAX_RUNS = 4;
8
+ /** Requests queued behind the running ones; beyond that a request gets 503 at once. */
9
+ export declare const MAX_WAITING = 16;
10
+ export interface ServeOptions {
11
+ /** File with an operator view JSON; re-read on every request. */
12
+ viewFile?: string;
13
+ /**
14
+ * Work detail documents of a file view, by work id (the demo); re-read on
15
+ * every request. A file view without one has no detail route (503).
16
+ */
17
+ workFiles?: Record<string, string>;
18
+ /**
19
+ * File views written in another language (the demo): a request with
20
+ * `?lang=<lang>` gets these files instead of `viewFile` / `workFiles`.
21
+ */
22
+ localized?: Partial<Record<'ru' | 'en', {
23
+ viewFile: string;
24
+ workFiles?: Record<string, string>;
25
+ }>>;
26
+ /**
27
+ * Live route instead of a file: `harness view` runs on every request
28
+ * (concurrent requests for one language share a run).
29
+ */
30
+ harness?: HarnessViewOptions & {
31
+ /** The installed harness takes `--lang`; otherwise it is not passed. */
32
+ lang: boolean;
33
+ /** Language when the request has no valid `?lang=ru|en`. */
34
+ defaultLang: 'ru' | 'en';
35
+ };
36
+ /** Directory of the built app (dist/app); missing = a plain fallback page. */
37
+ appDir: string;
38
+ host?: string;
39
+ /** Interface language of the CLI (`--lang` or the system locale), reported by /api/health. */
40
+ lang?: 'ru' | 'en';
41
+ /** Explicit port: used as is, busy = error. Absent: probe from DEFAULT_PORT. */
42
+ port?: number;
43
+ version: string;
44
+ }
45
+ export interface RunningServer {
46
+ url: string;
47
+ host: string;
48
+ port: number;
49
+ close(): Promise<void>;
50
+ }
51
+ export declare class ServeError extends Error {
52
+ readonly code: 'HOST_NOT_LOOPBACK' | 'PORT_BUSY' | 'PORT_INVALID';
53
+ constructor(code: 'HOST_NOT_LOOPBACK' | 'PORT_BUSY' | 'PORT_INVALID', message: string);
54
+ }
55
+ /**
56
+ * The view file holds either a bare view or the harness envelope
57
+ * `{ ok: true, data: <view> }` exactly as `harness view` prints it.
58
+ */
59
+ export declare function unwrapView(parsed: unknown): unknown;
60
+ /** Work ids as the harness graph schema allows them (`[A-Za-z0-9_-]{1,80}`). */
61
+ export declare const WORK_ID: RegExp;
62
+ export declare function startServer(options: ServeOptions): Promise<RunningServer>;
@@ -0,0 +1,302 @@
1
+ // Local read-only server of the standalone app: static files of the built
2
+ // app and the view document at /api/view. Loopback only, GET/HEAD only, no
3
+ // telemetry, no outbound requests. No React import: the CLI runs without it.
4
+ import { createHash } from 'node:crypto';
5
+ import { readFile, realpath, stat } from 'node:fs/promises';
6
+ import { createServer } from 'node:http';
7
+ import { extname, join, resolve, sep } from 'node:path';
8
+ import { checkView, checkWorkDetail } from "../model/compat.js";
9
+ import { harnessView, stopHarnessRuns, } from "./harness.js";
10
+ export const LOOPBACK_HOSTS = ['127.0.0.1', '::1', 'localhost'];
11
+ export const DEFAULT_PORT = 4790;
12
+ /** How many consecutive ports the probe tries when no port was given. */
13
+ export const PORT_PROBE_SPAN = 20;
14
+ /** Harness processes the live route runs at once; more requests queue. */
15
+ export const MAX_RUNS = 4;
16
+ /** Requests queued behind the running ones; beyond that a request gets 503 at once. */
17
+ export const MAX_WAITING = 16;
18
+ export class ServeError extends Error {
19
+ code;
20
+ constructor(code, message) {
21
+ super(message);
22
+ this.code = code;
23
+ }
24
+ }
25
+ const types = {
26
+ '.html': 'text/html; charset=utf-8',
27
+ '.js': 'text/javascript; charset=utf-8',
28
+ '.css': 'text/css; charset=utf-8',
29
+ '.json': 'application/json; charset=utf-8',
30
+ '.svg': 'image/svg+xml',
31
+ '.png': 'image/png',
32
+ '.ico': 'image/x-icon',
33
+ };
34
+ const securityHeaders = {
35
+ 'content-security-policy': "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; " +
36
+ "connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'",
37
+ 'x-content-type-options': 'nosniff',
38
+ 'referrer-policy': 'no-referrer',
39
+ 'x-frame-options': 'DENY',
40
+ 'cross-origin-resource-policy': 'same-origin',
41
+ };
42
+ const fallbackPage = `<!doctype html><html lang="en"><head><meta charset="utf-8">
43
+ <meta name="viewport" content="width=device-width, initial-scale=1"><title>Harness panel</title></head>
44
+ <body><p>The app bundle is not built. Run <code>npm run build</code>; the raw view is at
45
+ <a href="api/view">api/view</a>.</p></body></html>`;
46
+ function send(res, status, body, type, extra = {}) {
47
+ res.writeHead(status, { ...securityHeaders, 'content-type': type, ...extra });
48
+ res.end(res.req.method === 'HEAD' ? undefined : body);
49
+ }
50
+ /** Host header must name this loopback listener (DNS-rebinding guard). */
51
+ function hostAllowed(req, port) {
52
+ const host = req.headers.host;
53
+ if (!host)
54
+ return false;
55
+ return [`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`].includes(host.toLowerCase());
56
+ }
57
+ const jsonError = (res, status, code, message) => send(res, status, JSON.stringify({ error: { code, message } }), types['.json']);
58
+ /**
59
+ * The view file holds either a bare view or the harness envelope
60
+ * `{ ok: true, data: <view> }` exactly as `harness view` prints it.
61
+ */
62
+ export function unwrapView(parsed) {
63
+ if (typeof parsed === 'object' &&
64
+ parsed !== null &&
65
+ parsed.ok === true &&
66
+ 'data' in parsed) {
67
+ return parsed.data;
68
+ }
69
+ return parsed;
70
+ }
71
+ /** Work ids as the harness graph schema allows them (`[A-Za-z0-9_-]{1,80}`). */
72
+ export const WORK_ID = /^[A-Za-z0-9_-]{1,80}$/;
73
+ const viewGate = checkView;
74
+ const detailGate = checkWorkDetail;
75
+ async function serveViewFile(req, res, file, gate = viewGate) {
76
+ let bytes;
77
+ try {
78
+ bytes = await readFile(file);
79
+ }
80
+ catch {
81
+ return jsonError(res, 503, 'VIEW_UNAVAILABLE', 'View file is not readable yet.');
82
+ }
83
+ let parsed;
84
+ try {
85
+ parsed = JSON.parse(bytes.toString('utf8'));
86
+ }
87
+ catch {
88
+ return jsonError(res, 502, 'NOT_A_VIEW', 'View file is not JSON.');
89
+ }
90
+ if (typeof parsed === 'object' && parsed !== null && parsed.ok === false) {
91
+ return jsonError(res, 502, 'NOT_A_VIEW', 'View file holds a harness error envelope.');
92
+ }
93
+ return sendView(req, res, unwrapView(parsed), gate);
94
+ }
95
+ function sendView(req, res, view, gate = viewGate) {
96
+ const check = gate(view);
97
+ if (!check.ok)
98
+ return jsonError(res, 409, check.code, check.message);
99
+ // The ETag is derived from the content, never from a store counter.
100
+ const body = Buffer.from(JSON.stringify(view));
101
+ const etag = '"' + createHash('sha256').update(body).digest('hex').slice(0, 32) + '"';
102
+ const headers = { etag, 'cache-control': 'no-store' };
103
+ if (req.headers['if-none-match'] === etag)
104
+ return send(res, 304, '', types['.json'], headers);
105
+ return send(res, 200, body, types['.json'], headers);
106
+ }
107
+ const inside = (root, file) => file === root || file.startsWith(root + sep);
108
+ async function serveStatic(res, appDir, pathname) {
109
+ const notFound = () => send(res, 404, 'Not found', 'text/plain; charset=utf-8');
110
+ const wanted = pathname === '/' ? '/index.html' : pathname;
111
+ let root;
112
+ try {
113
+ root = await realpath(resolve(appDir));
114
+ }
115
+ catch {
116
+ return wanted === '/index.html' ? send(res, 200, fallbackPage, types['.html']) : notFound();
117
+ }
118
+ const lexical = resolve(join(root, wanted));
119
+ if (!inside(root, lexical))
120
+ return notFound();
121
+ try {
122
+ // Containment is checked on the real path too: a symlink inside the app
123
+ // directory must not reach files outside it.
124
+ const real = await realpath(lexical);
125
+ if (!inside(root, real) || !(await stat(real)).isFile())
126
+ return notFound();
127
+ return send(res, 200, await readFile(real), types[extname(real)] ?? 'application/octet-stream');
128
+ }
129
+ catch {
130
+ if (wanted === '/index.html')
131
+ return send(res, 200, fallbackPage, types['.html']);
132
+ return notFound();
133
+ }
134
+ }
135
+ function listen(server, host, port) {
136
+ return new Promise((ok, fail) => {
137
+ const onError = (err) => {
138
+ server.off('listening', onListening);
139
+ if (err.code === 'EADDRINUSE')
140
+ ok(false);
141
+ else
142
+ fail(err);
143
+ };
144
+ const onListening = () => {
145
+ server.off('error', onError);
146
+ ok(true);
147
+ };
148
+ server.once('error', onError);
149
+ server.once('listening', onListening);
150
+ server.listen({ host, port, exclusive: true });
151
+ });
152
+ }
153
+ export async function startServer(options) {
154
+ const host = options.host ?? '127.0.0.1';
155
+ if (!LOOPBACK_HOSTS.includes(host)) {
156
+ throw new ServeError('HOST_NOT_LOOPBACK', `Refusing to listen on ${host}: the panel binds only to 127.0.0.1, ::1 or localhost.`);
157
+ }
158
+ if (options.port !== undefined &&
159
+ (!Number.isInteger(options.port) || options.port < 1 || options.port > 65535)) {
160
+ throw new ServeError('PORT_INVALID', `Port ${options.port} is not in 1-65535.`);
161
+ }
162
+ if ((options.viewFile === undefined) === (options.harness === undefined))
163
+ throw new TypeError('startServer: pass exactly one of viewFile and harness');
164
+ const live = options.harness;
165
+ // One `harness view` run per language at a time; later requests share it.
166
+ const inFlight = new Map();
167
+ // At most MAX_RUNS harness processes at once and MAX_WAITING queued behind
168
+ // them: distinct work ids cannot fan out into unbounded processes.
169
+ let running = 0;
170
+ const waiting = [];
171
+ const limited = (run) => {
172
+ if (running >= MAX_RUNS && waiting.length >= MAX_WAITING)
173
+ return Promise.resolve({
174
+ ok: false,
175
+ code: 'VIEW_UNAVAILABLE',
176
+ message: 'The panel is busy with other harness runs; try again shortly.',
177
+ });
178
+ const start = () => {
179
+ running++;
180
+ return run().finally(() => {
181
+ running--;
182
+ waiting.shift()?.();
183
+ });
184
+ };
185
+ if (running < MAX_RUNS)
186
+ return start();
187
+ return new Promise((ok) => waiting.push(() => void start().then(ok)));
188
+ };
189
+ const liveView = (lang, workId) => {
190
+ const key = (live.lang ? lang : '') + (workId !== undefined ? '\0' + workId : '');
191
+ let p = inFlight.get(key);
192
+ if (!p) {
193
+ p = limited(() => harnessView(live, live.lang ? lang : undefined, workId)).finally(() => inFlight.delete(key));
194
+ inFlight.set(key, p);
195
+ }
196
+ return p;
197
+ };
198
+ /** The file view for a request: the localized files of `?lang=`, else the defaults. */
199
+ const fileSource = (params) => {
200
+ const asked = params.get('lang');
201
+ const l = asked === 'ru' || asked === 'en' ? options.localized?.[asked] : undefined;
202
+ return l ?? { viewFile: options.viewFile, workFiles: options.workFiles };
203
+ };
204
+ let port = 0;
205
+ const server = createServer((req, res) => {
206
+ const failed = () => {
207
+ if (!res.headersSent)
208
+ send(res, 500, 'Internal error', 'text/plain; charset=utf-8');
209
+ else
210
+ res.destroy();
211
+ };
212
+ try {
213
+ handle(req, res).catch(failed);
214
+ }
215
+ catch {
216
+ failed();
217
+ }
218
+ });
219
+ async function handle(req, res) {
220
+ if (!hostAllowed(req, port))
221
+ return send(res, 421, 'Misdirected request', 'text/plain; charset=utf-8');
222
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
223
+ return send(res, 405, 'The panel is read-only', 'text/plain; charset=utf-8', {
224
+ allow: 'GET, HEAD',
225
+ });
226
+ }
227
+ let pathname;
228
+ try {
229
+ pathname = decodeURIComponent(new URL(req.url ?? '/', 'http://local').pathname);
230
+ }
231
+ catch {
232
+ return send(res, 400, 'Bad request', 'text/plain; charset=utf-8');
233
+ }
234
+ if (pathname.includes('\0'))
235
+ return send(res, 400, 'Bad request', 'text/plain; charset=utf-8');
236
+ const params = new URL(req.url ?? '/', 'http://local').searchParams;
237
+ // Work detail: `/api/work/<id>`, or `/api/view?work=<id>` as in the design contract.
238
+ const workId = pathname.startsWith('/api/work/')
239
+ ? pathname.slice('/api/work/'.length)
240
+ : pathname === '/api/view' && params.has('work')
241
+ ? (params.get('work') ?? '')
242
+ : undefined;
243
+ if (workId !== undefined) {
244
+ if (!WORK_ID.test(workId))
245
+ return jsonError(res, 404, 'VIEW_UNAVAILABLE', 'There is no such work order id.');
246
+ if (live) {
247
+ const asked = params.get('lang');
248
+ const lang = asked === 'ru' || asked === 'en' ? asked : live.defaultLang;
249
+ const r = await liveView(lang, workId);
250
+ return r.ok
251
+ ? sendView(req, res, r.view, detailGate)
252
+ : jsonError(res, 503, r.code, r.message);
253
+ }
254
+ const files = fileSource(params).workFiles;
255
+ const file = files && Object.hasOwn(files, workId) ? files[workId] : undefined;
256
+ if (!file)
257
+ return jsonError(res, 503, 'VIEW_UNAVAILABLE', `No work detail for ${workId} in this file view; the live route (--state) computes it with \`harness view --work\`.`);
258
+ return serveViewFile(req, res, file, detailGate);
259
+ }
260
+ if (pathname === '/api/view') {
261
+ if (live) {
262
+ const asked = params.get('lang');
263
+ const lang = asked === 'ru' || asked === 'en' ? asked : live.defaultLang;
264
+ const r = await liveView(lang);
265
+ return r.ok ? sendView(req, res, r.view) : jsonError(res, 503, r.code, r.message);
266
+ }
267
+ return serveViewFile(req, res, fileSource(params).viewFile);
268
+ }
269
+ if (pathname === '/api/health') {
270
+ return send(res, 200, JSON.stringify({
271
+ ok: true,
272
+ version: options.version,
273
+ readOnly: true,
274
+ ...(options.lang ? { lang: options.lang } : {}),
275
+ }), types['.json']);
276
+ }
277
+ return serveStatic(res, options.appDir, pathname);
278
+ }
279
+ const candidates = options.port !== undefined
280
+ ? [options.port]
281
+ : Array.from({ length: PORT_PROBE_SPAN }, (_, i) => DEFAULT_PORT + i);
282
+ for (const candidate of candidates) {
283
+ if (await listen(server, host, candidate)) {
284
+ port = candidate;
285
+ const shown = host === '::1' ? '[::1]' : host;
286
+ return {
287
+ url: `http://${shown}:${port}/`,
288
+ host,
289
+ port,
290
+ close: () => new Promise((ok) => {
291
+ // Running `harness view` processes end with the panel.
292
+ const runs = live ? stopHarnessRuns() : Promise.resolve();
293
+ server.close(() => void runs.then(() => ok()));
294
+ server.closeAllConnections();
295
+ }),
296
+ };
297
+ }
298
+ }
299
+ throw new ServeError('PORT_BUSY', options.port !== undefined
300
+ ? `Port ${options.port} is busy. Pick another with --port or omit it to probe.`
301
+ : `Ports ${DEFAULT_PORT}-${DEFAULT_PORT + PORT_PROBE_SPAN - 1} are busy. Pass --port.`);
302
+ }