The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
doc-viewer: survive malformed requests and verdicts; server and state fully tested
deeab5d8b75b104
diff --git a/store/viewers/doc-viewer/lib/workspace.mjs b/store/viewers/doc-viewer/lib/workspace.mjsindex dbf37c0eb..2d8fe2f7a 100644--- a/store/viewers/doc-viewer/lib/workspace.mjs+++ b/store/viewers/doc-viewer/lib/workspace.mjs@@ -76,7 +76,9 @@ export function readVerdict(workspace) {const st = statSync(path)const json = JSON.parse(readFileSync(path, 'utf8'))if (!json || typeof json !== 'object') return null- return { ...json, findings: Array.isArray(json.findings) ? json.findings : [], mtimeMs: st.mtimeMs }+ // Only object findings: a `null` in the list is a malformed verdict, not a reason to fail the pane.+ const findings = Array.isArray(json.findings) ? json.findings.filter((f) => f && typeof f === 'object') : []+ return { ...json, findings, mtimeMs: st.mtimeMs }} catch {return null}@@ -131,7 +133,7 @@ export function docState(workspace, requested = '', now = Date.now()) {const verdict = readVerdict(workspace)const pdfT = pdf?.mtimeMs ?? 0, srcT = source?.mtimeMs ?? 0, verT = verdict?.mtimeMs ?? 0const aboutThis = verdict && (!verdict.artifact || !file || verdict.artifact === file)- const errors = aboutThis ? verdict.findings.filter((f) => f && f.severity === 'error') : []+ const errors = aboutThis ? verdict.findings.filter((f) => f.severity === 'error') : []let build = 'idle'if (source && srcT > pdfT && srcT > verT) build = 'building'else if (aboutThis && verdict.ready === false && errors.length && verT >= pdfT) build = 'failed'diff --git a/store/viewers/doc-viewer/test/helpers.mjs b/store/viewers/doc-viewer/test/helpers.mjsnew file mode 100644index 000000000..d091a5ead--- /dev/null+++ b/store/viewers/doc-viewer/test/helpers.mjs@@ -0,0 +1,163 @@+// What the server tests share: a scratch workspace, the viewer started the way Harness starts it (a+// real process on a free loopback port), raw HTTP for what fetch will not send, and an SSE reader.+import { spawn } from 'node:child_process'+import { once } from 'node:events'+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'+import { request } from 'node:http'+import { connect, createServer } from 'node:net'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'++export const here = dirname(fileURLToPath(import.meta.url))+export const pkg = join(here, '..')++const roots = []+/** A temp directory with `files` ({ rel: body | { body, at } }) written into it; removed by cleanup(). */+export function scratch(files = {}, prefix = 'doc-viewer-') {+ const root = mkdtempSync(join(tmpdir(), prefix))+ roots.push(root)+ for (const [rel, spec] of Object.entries(files)) put(root, rel, spec)+ return root+}+export function put(root, rel, spec = '') {+ const { body = '', at } = typeof spec === 'object' && !Buffer.isBuffer(spec) ? spec : { body: spec }+ const full = join(root, rel)+ mkdirSync(dirname(full), { recursive: true })+ writeFileSync(full, body)+ if (at) utimesSync(full, at, at)+ return full+}+export function cleanup() {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })+}++export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))++/** Poll until `check()` is truthy; its value, or a failure naming `what`. */+export async function until(check, what, ms = 10_000) {+ const deadline = Date.now() + ms+ for (;;) {+ const value = await check()+ if (value) return value+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`)+ await sleep(25)+ }+}++export const freePort = () => new Promise((resolve) => {+ const probe = createServer().listen(0, '127.0.0.1', () => { const { port } = probe.address(); probe.close(() => resolve(port)) })+})++/**+ * viewer.mjs on a free port with the test preload. `env` values of undefined are removed from the+ * environment. Retries on a port another process took between the probe and the listen.+ */+export async function startViewer(workspace, env = {}) {+ for (let attempt = 0; ; attempt++) {+ const port = await freePort()+ const merged = { ...process.env, HARNESS_VIEWER_PORT: String(port), HARNESS_WORKSPACE: workspace, ...env }+ for (const key of Object.keys(merged)) if (merged[key] === undefined) delete merged[key]+ const child = spawn(process.execPath, ['--import', join(here, 'preload.mjs'), join(pkg, 'viewer.mjs')], { env: merged, stdio: ['ignore', 'pipe', 'pipe'] })+ let out = '', err = ''+ child.stdout.on('data', (d) => { out += d })+ child.stderr.on('data', (d) => { err += d })+ const exited = once(child, 'exit')+ const started = await Promise.race([until(() => out.includes('listening'), 'the viewer to listen', 15_000).then(() => true), exited.then(() => false)])+ if (!started) {+ if (attempt < 3 && err.includes('EADDRINUSE')) continue+ throw new Error(`viewer exited before listening: ${err}`)+ }+ return {+ port,+ base: `http://127.0.0.1:${port}`,+ child,+ output: () => out,+ errors: () => err,+ alive: () => child.exitCode === null && child.signalCode === null,+ /** SIGTERM, and wait for the exit (so V8 writes its coverage). */+ async stop() {+ if (child.exitCode === null && child.signalCode === null) { child.kill('SIGTERM'); await exited }+ return child.exitCode+ },+ }+ }+}++/** A request fetch would refuse or normalise: any path, headers (Host included), method and body. */+export function raw(port, { path = '/', method = 'GET', headers = {}, body } = {}) {+ return new Promise((resolve, reject) => {+ const req = request({ host: '127.0.0.1', port, path, method, headers }, (res) => {+ const chunks = []+ res.on('data', (c) => chunks.push(c))+ res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, text: Buffer.concat(chunks).toString('utf8') }))+ })+ req.on('error', reject)+ req.end(body)+ })+}++/** Bytes straight onto a socket; the first line of whatever comes back ('' when the server closes). */+export function socket(port, bytes, { holdMs = 0 } = {}) {+ return new Promise((resolve) => {+ const s = connect(port, '127.0.0.1', () => {+ s.write(bytes)+ if (holdMs) setTimeout(() => s.destroy(), holdMs)+ })+ let out = ''+ s.on('data', (d) => { out += d })+ s.on('close', () => resolve(out.split('\r\n')[0]))+ s.on('error', () => {})+ })+}++/** An open /events stream: `next(predicate)` resolves with the first block it accepts. */+export async function openEvents(base, path) {+ const controller = new AbortController()+ const response = await fetch(base + path, { signal: controller.signal })+ const reader = response.body.getReader()+ const decoder = new TextDecoder()+ let buffer = ''+ let pending = null+ let ended = false+ const blocks = []+ const pump = async (ms) => {+ pending ??= reader.read().catch(() => ({ done: true }))+ const result = await Promise.race([pending, sleep(ms).then(() => null)])+ if (!result) return+ pending = null+ if (result.done) { ended = true; return }+ buffer += decoder.decode(result.value, { stream: true })+ const parts = buffer.split('\n\n')+ buffer = parts.pop()+ blocks.push(...parts)+ }+ return {+ response,+ get ended() { return ended },+ async next(predicate, what = 'an event', ms = 10_000) {+ const deadline = Date.now() + ms+ for (;;) {+ const i = blocks.findIndex(predicate)+ if (i >= 0) return blocks.splice(0, i + 1).pop()+ blocks.length = 0+ if (ended) throw new Error(`stream ended before ${what}`)+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`)+ await pump(100)+ }+ },+ /** Resolves true once the server ends the stream. */+ async end(ms = 10_000) {+ const deadline = Date.now() + ms+ while (!ended && Date.now() < deadline) await pump(100)+ return ended+ },+ close() { controller.abort() },+ }+}++/** The state carried by an `event: state` block, or null. */+export function stateOf(block) {+ if (!block.startsWith('event: state\n')) return null+ return JSON.parse(block.slice(block.indexOf('data: ') + 6))+}diff --git a/store/viewers/doc-viewer/test/live.test.mjs b/store/viewers/doc-viewer/test/live.test.mjsnew file mode 100644index 000000000..b7d5291c0--- /dev/null+++ b/store/viewers/doc-viewer/test/live.test.mjs@@ -0,0 +1,86 @@+// The live feed: /events pushes the document state when the workspace changes (fs.watch, backed by a+// slow poll), only when the state really changed, keeps the connection alive with a ping, and ends+// cleanly when Harness stops the pane. The preload shortens the poll and the ping (3 s, 20 s).+import assert from 'node:assert/strict'+import { join } from 'node:path'+import { after, test } from 'node:test'+import { cleanup, openEvents, put, scratch, sleep, startViewer, stateOf, until } from './helpers.mjs'++after(cleanup)+const at = (s) => new Date(Date.UTC(2026, 8, 16, 12, 0, s))+const isState = (b) => Boolean(stateOf(b))++test('a source edit reads as building, the new PDF as idle; nothing changed means nothing sent; stopping ends the stream', async () => {+ const ws = scratch({ 'main.typ': { body: '= Hi', at: at(0) }, 'out/main.pdf': { body: '%PDF', at: at(10) } })+ const viewer = await startViewer(ws, {+ TEST_TIMERS: '3000=150,20000=250',+ // Besides what really changes: names the watcher must ignore, a change with no filename, and a second+ // change straight after it (which restarts the settle timer).+ TEST_WATCH_EMIT: JSON.stringify(['node_modules/pdfjs-dist/x.js', '.git/index', '.claude/settings.json', '.agents/skills', null, 'main.typ']),+ })+ // The poll runs with nobody listening first.+ await sleep(400)+ const events = await openEvents(viewer.base, '/events?file=out/main.pdf')+ try {+ const first = stateOf(await events.next(isState, 'the state on connect'))+ assert.equal(first.file, 'out/main.pdf')+ assert.equal(first.build, 'idle')++ await events.next((b) => b === ': ping', 'a ping')+ // The poll keeps running, but the state is the same: no event.+ await assert.rejects(events.next(isState, 'no state event', 700), /timed out/)++ put(ws, 'main.typ', '= Hi again')+ const building = stateOf(await events.next((b) => stateOf(b)?.build === 'building', 'building after the source edit'))+ assert.equal(building.source.path, 'main.typ')+ put(ws, 'out/main.pdf', '%PDF-1.7 new')+ const idle = stateOf(await events.next((b) => stateOf(b)?.build === 'idle', 'idle after the PDF'))+ assert.equal(idle.pdf.size, 12)++ assert.equal(await viewer.stop(), 0, 'a clean exit on SIGTERM')+ assert.equal(await events.end(), true, 'the stream ended with the server')+ } finally {+ events.close()+ await viewer.stop()+ }+})++test('where fs.watch is not available the poll delivers, and a state that cannot be built is logged, not fatal', async () => {+ const ws = scratch({ 'out/a.pdf': { body: '%PDF', at: at(10) } })+ const viewer = await startViewer(ws, { TEST_WATCH: 'throw', TEST_TIMERS: '3000=100' })+ const events = await openEvents(viewer.base, '/events')+ try {+ assert.match(viewer.output(), /\[doc-viewer\] watch failed: watch unavailable here/)+ assert.equal(stateOf(await events.next(isState, 'the state on connect')).file, 'out/a.pdf')+ put(ws, 'out/b.pdf', '%PDF-1.7')+ const next = stateOf(await events.next((b) => stateOf(b)?.file === 'out/b.pdf', 'the new PDF, by polling'))+ assert.deepEqual(next.pdfs.map((p) => p.path), ['out/b.pdf', 'out/a.pdf'])++ put(ws, '.harness/verdict.json', JSON.stringify({ spec: 1, ready: false, findings: [{ severity: 'error', message: { toString: 0 } }] }))+ await until(() => viewer.output().includes('[doc-viewer] state failed:'), 'the failed state to be logged')+ put(ws, '.harness/verdict.json', JSON.stringify({ spec: 1, ready: false, summary: 'one error', findings: [{ severity: 'error', message: 'x' }] }))+ const failed = stateOf(await events.next((b) => stateOf(b)?.verdict?.summary === 'one error', 'the state once the verdict reads'))+ assert.equal(failed.build, 'failed')+ assert.ok(viewer.alive())+ } finally {+ events.close()+ await viewer.stop()+ }+})++test('a workspace that is not there yet: no watch, an empty state, no error', async () => {+ const missing = join(scratch(), 'not-yet')+ const viewer = await startViewer(missing, {})+ try {+ assert.match(viewer.output(), /\[doc-viewer\] watch failed: ENOENT/)+ const r = await fetch(viewer.base + '/api/state')+ assert.equal(r.status, 200)+ const s = await r.json()+ assert.equal(s.workspace, 'not-yet')+ assert.equal(s.file, null)+ assert.equal(s.build, 'idle')+ assert.deepEqual(s.pdfs, [])+ } finally {+ await viewer.stop()+ }+})diff --git a/store/viewers/doc-viewer/test/open.test.mjs b/store/viewers/doc-viewer/test/open.test.mjsnew file mode 100644index 000000000..63e63ba04--- /dev/null+++ b/store/viewers/doc-viewer/test/open.test.mjs@@ -0,0 +1,183 @@+// POST /api/open, for real: the viewer spawns `open` (macOS) or `xdg-open` (Linux) — here stubs on+// PATH that write down what they were asked to open — and only for its own page, only web links and+// files inside the workspace. process.platform is set by the test preload, so both systems run anywhere.+import assert from 'node:assert/strict'+import { chmodSync, existsSync, mkdirSync, readFileSync } from 'node:fs'+import { join } from 'node:path'+import { request } from 'node:http'+import { after, test } from 'node:test'+import { cleanup, put, raw, scratch, socket, startViewer, until } from './helpers.mjs'++after(cleanup)++/** A bin directory holding a stub for `name` that appends its argv (tab-separated) to `log`. */+function stubBin(root, name, log) {+ const bin = join(root, 'bin')+ mkdirSync(bin, { recursive: true })+ // One write per call, so calls that run at the same time do not interleave.+ const stub = put(bin, name, `#!/bin/sh\nline=''\nfor a in "$@"; do line="$line$a\t"; done\nprintf '%s\\n' "$line" >> '${log}'\n`)+ chmodSync(stub, 0o755)+ return bin+}+const calls = (log) => (existsSync(log) ? readFileSync(log, 'utf8').split('\n').filter(Boolean).map((line) => line.split('\t').slice(0, -1)) : [])++function workspaceWithPdf() {+ const root = scratch({ 'outside.pdf': '%PDF' })+ const ws = join(root, 'ws')+ put(ws, 'out/main.pdf', '%PDF-1.7\n')+ return { root, ws }+}++const post = (viewer, body, { headers = { 'x-doc-viewer': '1' }, rawBody } = {}) =>+ raw(viewer.port, { path: '/api/open', method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: rawBody ?? JSON.stringify(body) })++test('macOS: web links and workspace files open with `open`, a reveal with `open -R`', async () => {+ const { root, ws } = workspaceWithPdf()+ const log = join(root, 'open.log')+ const viewer = await startViewer(ws, { DOC_VIEWER_OPEN: undefined, TEST_PLATFORM: 'darwin', PATH: stubBin(root, 'open', log) })+ try {+ assert.equal((await (await fetch(viewer.base + '/api/state')).json()).canOpen, true, 'opening is on by default on macOS')+ assert.equal((await post(viewer, { kind: 'url', url: 'https://typst.app/docs' })).status, 200)+ assert.equal((await post(viewer, { kind: 'url', url: 'mailto:[email protected]' })).status, 200)+ assert.equal((await post(viewer, { kind: 'open', path: 'out/main.pdf' })).status, 200)+ assert.equal((await post(viewer, { kind: 'reveal', path: 'out/main.pdf' })).status, 200)+ const expected = [['https://typst.app/docs'], ['mailto:[email protected]'], [join(ws, 'out/main.pdf')], ['-R', join(ws, 'out/main.pdf')]]+ const seen = await until(() => { const c = calls(log); return c.length >= 4 && c }, 'the four opens')+ assert.deepEqual([...seen].sort(), [...expected].sort())+ } finally {+ await viewer.stop()+ }+})++test('Linux: `xdg-open` for a file, and its folder for a reveal', async () => {+ const { root, ws } = workspaceWithPdf()+ const log = join(root, 'xdg.log')+ const viewer = await startViewer(ws, { DOC_VIEWER_OPEN: undefined, TEST_PLATFORM: 'linux', PATH: stubBin(root, 'xdg-open', log) })+ try {+ assert.equal((await (await fetch(viewer.base + '/api/state')).json()).canOpen, true, 'opening is on by default on Linux')+ assert.equal((await post(viewer, { kind: 'reveal', path: 'out/main.pdf' })).status, 200)+ assert.deepEqual(await until(() => calls(log)[0], 'the reveal'), [join(ws, 'out')])+ assert.equal((await post(viewer, { kind: 'open', path: 'out/main.pdf' })).status, 200)+ assert.deepEqual(await until(() => calls(log)[1], 'the open'), [join(ws, 'out/main.pdf')])+ } finally {+ await viewer.stop()+ }+})++test('elsewhere opening is off: the state says so and the route answers 501', async () => {+ const { ws } = workspaceWithPdf()+ const viewer = await startViewer(ws, { DOC_VIEWER_OPEN: undefined, TEST_PLATFORM: 'win32' })+ try {+ assert.equal((await (await fetch(viewer.base + '/api/state')).json()).canOpen, false)+ assert.equal((await post(viewer, { kind: 'url', url: 'https://typst.app' })).status, 501)+ } finally {+ await viewer.stop()+ }+})++test('DOC_VIEWER_OPEN=off turns it off anywhere', async () => {+ const { ws } = workspaceWithPdf()+ const viewer = await startViewer(ws, { DOC_VIEWER_OPEN: 'off', TEST_PLATFORM: 'darwin' })+ try {+ assert.equal((await (await fetch(viewer.base + '/api/state')).json()).canOpen, false)+ assert.equal((await post(viewer, { kind: 'open', path: 'out/main.pdf' })).status, 501)+ } finally {+ await viewer.stop()+ }+})++test('only the page itself may ask: its header, and a loopback Host naming this port', async () => {+ const { root, ws } = workspaceWithPdf()+ const log = join(root, 'open.log')+ const viewer = await startViewer(ws, { DOC_VIEWER_OPEN: undefined, TEST_PLATFORM: 'darwin', PATH: stubBin(root, 'open', log) })+ try {+ const link = { kind: 'url', url: 'https://example.com/' }+ assert.equal((await post(viewer, link, { headers: {} })).status, 403, 'no header')+ assert.equal((await post(viewer, link, { headers: { 'x-doc-viewer': '0' } })).status, 403, 'the wrong header')+ assert.equal((await post(viewer, link, { headers: { 'x-doc-viewer': '1', host: `evil.example:${viewer.port}` } })).status, 403, 'a rebinding Host')+ assert.equal((await post(viewer, link, { headers: { 'x-doc-viewer': '1', host: '127.0.0.1:1' } })).status, 403, 'another port')+ // HTTP/1.0 may leave Host out altogether.+ const body = JSON.stringify(link)+ assert.equal(await socket(viewer.port, `POST /api/open HTTP/1.0\r\nx-doc-viewer: 1\r\ncontent-type: application/json\r\ncontent-length: ${body.length}\r\n\r\n${body}`), 'HTTP/1.1 403 Forbidden')+ assert.equal((await post(viewer, link, { headers: { 'x-doc-viewer': '1', host: `localhost:${viewer.port}` } })).status, 200, 'localhost is loopback too')+ assert.deepEqual(await until(() => calls(log)[0], 'the one open that was allowed'), ['https://example.com/'])+ } finally {+ await viewer.stop()+ }+})++test('refused: other schemes, huge links, files outside the workspace or not there, and bodies that are not an object', async () => {+ const { root, ws } = workspaceWithPdf()+ const log = join(root, 'open.log')+ const viewer = await startViewer(ws, { DOC_VIEWER_OPEN: undefined, TEST_PLATFORM: 'darwin', PATH: stubBin(root, 'open', log) })+ try {+ assert.equal((await post(viewer, { kind: 'url', url: 'file:///etc/hosts' })).status, 400)+ assert.equal((await post(viewer, { kind: 'url', url: 'javascript:alert(1)' })).status, 400)+ assert.equal((await post(viewer, { kind: 'url' })).status, 400, 'no link at all')+ assert.equal((await post(viewer, { kind: 'url', url: 'https://example.com/' + 'a'.repeat(4096) })).status, 400, 'longer than 4096')+ assert.equal((await post(viewer, { kind: 'open', path: '../outside.pdf' })).status, 404)+ assert.equal((await post(viewer, { kind: 'reveal', path: 'out/nope.pdf' })).status, 404)+ // Not JSON, or JSON that is not an object: a 400, where `null` used to be a 500 (it was read as an object).+ for (const rawBody of ['{not json', 'null', '1', '"out/main.pdf"']) {+ const r = await post(viewer, null, { rawBody })+ assert.equal(r.status, 400, rawBody)+ assert.deepEqual(JSON.parse(r.text), { ok: false, error: 'bad request' })+ }+ // A path left out names the workspace itself, which exists.+ assert.equal((await post(viewer, { kind: 'reveal' })).status, 200)+ assert.deepEqual(await until(() => calls(log)[0], 'the reveal of the workspace'), ['-R', ws])+ assert.equal(calls(log).length, 1, 'nothing refused was opened')+ } finally {+ await viewer.stop()+ }+})++test('a link spawn cannot take (a NUL byte) is a 500, and the server carries on', async () => {+ const { root, ws } = workspaceWithPdf()+ const viewer = await startViewer(ws, { DOC_VIEWER_OPEN: undefined, TEST_PLATFORM: 'darwin', PATH: stubBin(root, 'open', join(root, 'open.log')) })+ try {+ const r = await post(viewer, { kind: 'url', url: 'https://example.com/ ' })+ assert.equal(r.status, 500)+ assert.match(JSON.parse(r.text).error, /null bytes/)+ assert.equal((await fetch(viewer.base + '/api/state')).status, 200)+ } finally {+ await viewer.stop()+ }+})++test('no opener on PATH: the request is answered and the failure logged, not thrown', async () => {+ const { root, ws } = workspaceWithPdf()+ const empty = join(root, 'empty-bin')+ mkdirSync(empty)+ const viewer = await startViewer(ws, { DOC_VIEWER_OPEN: undefined, TEST_PLATFORM: 'darwin', PATH: empty })+ try {+ assert.equal((await post(viewer, { kind: 'url', url: 'https://example.com/' })).status, 200)+ await until(() => viewer.output().includes('[doc-viewer] open failed:'), 'the spawn error to be logged')+ assert.ok(viewer.alive())+ } finally {+ await viewer.stop()+ }+})++test('a body over 16 KB is cut off, and one abandoned half-way is dropped; the server carries on', async () => {+ const { root, ws } = workspaceWithPdf()+ const log = join(root, 'open.log')+ const viewer = await startViewer(ws, { DOC_VIEWER_OPEN: undefined, TEST_PLATFORM: 'darwin', PATH: stubBin(root, 'open', log) })+ try {+ const big = JSON.stringify({ kind: 'url', url: 'https://example.com/', pad: 'x'.repeat(40_000) })+ const answer = await post(viewer, null, { rawBody: big }).then((r) => r.status, (e) => e.code)+ assert.notEqual(answer, 200)+ // Half a body, then the client goes away.+ await new Promise((resolve) => {+ const req = request({ host: '127.0.0.1', port: viewer.port, path: '/api/open', method: 'POST', headers: { 'x-doc-viewer': '1', 'content-type': 'application/json', 'content-length': 1000 } })+ req.on('error', () => resolve())+ req.write('{"kind": "url", "url": "https://exa')+ setTimeout(() => { req.destroy(); resolve() }, 150)+ })+ assert.equal((await post(viewer, { kind: 'url', url: 'https://example.com/after' })).status, 200)+ assert.deepEqual(await until(() => calls(log)[0], 'the open after'), ['https://example.com/after'])+ assert.equal(calls(log).length, 1, 'neither the cut-off nor the abandoned body opened anything')+ } finally {+ await viewer.stop()+ }+})diff --git a/store/viewers/doc-viewer/test/preload.mjs b/store/viewers/doc-viewer/test/preload.mjsnew file mode 100644index 000000000..a3c23c722--- /dev/null+++ b/store/viewers/doc-viewer/test/preload.mjs@@ -0,0 +1,30 @@+// Loaded into the viewer under test with `node --import`, so the server itself carries no test hooks.+// Everything is driven by the environment the test starts it with:+//+// TEST_TIMERS="20000=50,3000=40" those exact setTimeout/setInterval delays run faster+// TEST_WATCH=throw fs.watch is unavailable, as on filesystems that cannot watch+// TEST_WATCH_EMIT='["a", null]' the real watcher also reports these names (null: no filename)+// TEST_PLATFORM=linux|win32 process.platform, for the per-OS branches+import fs from 'node:fs'+import { syncBuiltinESMExports } from 'node:module'++const timers = new Map(String(process.env.TEST_TIMERS ?? '').split(',').filter(Boolean).map((pair) => pair.split('=').map(Number)))+for (const name of ['setTimeout', 'setInterval']) {+ const original = globalThis[name]+ globalThis[name] = (fn, ms, ...args) => original(fn, timers.get(ms) ?? ms, ...args)+}++if (process.env.TEST_PLATFORM) Object.defineProperty(process, 'platform', { value: process.env.TEST_PLATFORM })++const realWatch = fs.watch+if (process.env.TEST_WATCH === 'throw') {+ fs.watch = () => { throw new Error('watch unavailable here') }+} else if (process.env.TEST_WATCH_EMIT) {+ const names = JSON.parse(process.env.TEST_WATCH_EMIT)+ fs.watch = (...args) => {+ const watcher = realWatch(...args)+ setTimeout(() => { for (const name of names) watcher.emit('change', 'change', name) }, 30)+ return watcher+ }+}+syncBuiltinESMExports()diff --git a/store/viewers/doc-viewer/test/routes.test.mjs b/store/viewers/doc-viewer/test/routes.test.mjsnew file mode 100644index 000000000..19cc3d9d0--- /dev/null+++ b/store/viewers/doc-viewer/test/routes.test.mjs@@ -0,0 +1,102 @@+// Every route the server has, what it refuses, and what it survives: a real viewer process on a+// scratch workspace, raw HTTP where fetch would clean the path up before the server saw it.+import assert from 'node:assert/strict'+import { join } from 'node:path'+import { after, before, test } from 'node:test'+import { cleanup, openEvents, put, raw, scratch, socket, startViewer, stateOf, until } from './helpers.mjs'++let viewer, ws, root+before(async () => {+ root = scratch({ 'outside.pdf': '%PDF-1.7 not yours\n' })+ ws = join(root, 'ws')+ put(ws, 'main.typ', { body: '= Hi', at: new Date(Date.UTC(2026, 8, 16, 12, 0, 0)) })+ put(ws, 'out/main.pdf', { body: '%PDF-1.7\n%%EOF\n', at: new Date(Date.UTC(2026, 8, 16, 12, 0, 10)) })+ put(ws, 'notes.xyz', 'what is this')+ put(ws, 'quote"d.pdf', { body: '%PDF-1.7\n', at: new Date(Date.UTC(2026, 8, 16, 11, 0, 0)) })+ viewer = await startViewer(ws, { DOC_VIEWER_OPEN: 'log' })+})+after(async () => { await viewer?.stop(); cleanup() })++test('the reader, and HEAD without a body', async () => {+ const index = await fetch(viewer.base + '/index.html')+ assert.equal(index.status, 200)+ assert.match(index.headers.get('content-type'), /text\/html/)+ const head = await raw(viewer.port, { path: '/ws/out/main.pdf', method: 'HEAD' })+ assert.equal(head.status, 200)+ assert.equal(head.headers['content-length'], '15')+ assert.equal(head.headers['content-type'], 'application/pdf')+ assert.ok(head.headers['last-modified'])+ assert.equal(head.text, '')+})++test('workspace files: an unknown type is bytes, a folder or a missing file is not found', async () => {+ const unknown = await fetch(viewer.base + '/ws/notes.xyz')+ assert.equal(unknown.headers.get('content-type'), 'application/octet-stream')+ assert.equal(await unknown.text(), 'what is this')+ assert.equal((await fetch(viewer.base + '/ws/out')).status, 404)+ assert.equal((await fetch(viewer.base + '/ws/out/missing.pdf')).status, 404)+ assert.equal((await fetch(viewer.base + '/app/')).status, 404, 'the app folder itself is not a file')+ assert.equal((await fetch(viewer.base + '/vendor/web/')).status, 404, 'nor a pdf.js folder')+})++test('a download keeps the file name, without the quote that would end the header', async () => {+ const r = await fetch(viewer.base + '/ws/quote%22d.pdf?download=1')+ assert.equal(r.status, 200)+ assert.equal(r.headers.get('content-disposition'), 'attachment; filename="quoted.pdf"')+ assert.equal((await fetch(viewer.base + '/ws/quote%22d.pdf')).headers.get('content-disposition'), null)+})++test('nothing outside the reader, pdf.js or the workspace, however the path is spelled', async () => {+ // %2F is not a separator to the URL parser, so these reach the server's own check with the dots intact.+ for (const path of ['/app/..%2Fviewer.mjs', '/vendor/build/..%2F..%2F..%2Fpackage.json', '/ws/..%2Foutside.pdf', '/ws/..%2F..%2F..%2Fetc%2Fhosts', '/..%2Foutside.pdf']) {+ const r = await raw(viewer.port, { path })+ assert.equal(r.status, 404, path)+ assert.doesNotMatch(r.text, /not yours/, path)+ }+ assert.equal((await raw(viewer.port, { path: '/main.typ' })).status, 404, 'the old root URLs serve PDFs only')+ assert.equal((await raw(viewer.port, { path: '/api/open' })).status, 404, 'open is POST only')+})++test('a path or a target that is not a URL is a 400, and the server is still there', async () => {+ assert.equal((await raw(viewer.port, { path: '/ws/%zz' })).status, 400)+ // An absolute-form request target with an impossible port: the URL parser throws on it.+ assert.equal(await socket(viewer.port, 'GET http://a:99999/ HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n'), 'HTTP/1.1 400 Bad Request')+ assert.equal((await fetch(viewer.base + '/api/state')).status, 200)+ assert.ok(viewer.alive())+})++test('the state without a file names the newest PDF', async () => {+ const s = await (await fetch(viewer.base + '/api/state')).json()+ assert.equal(s.requested, '')+ assert.equal(s.file, 'out/main.pdf')+ assert.equal(s.canOpen, true)+})++test('a verdict with a null finding is read without it, and never takes the server down', async () => {+ put(ws, '.harness/verdict.json', JSON.stringify({ spec: 1, ready: false, artifact: 'out/main.pdf', findings: [null, { severity: 'error', message: 'boom', ref: 'main.typ:1:1' }] }))+ const r = await fetch(viewer.base + '/api/state?file=out/main.pdf')+ assert.equal(r.status, 200)+ const s = await r.json()+ assert.deepEqual(s.verdict.findings.map((f) => f.message), ['boom'])+ assert.ok(viewer.alive())+})++test('a verdict the state cannot be built from is a 500 for the request and a log line for the stream; both recover', async () => {+ const events = await openEvents(viewer.base, '/events?file=out/main.pdf')+ try {+ await events.next((b) => stateOf(b), 'the first state')+ // A message whose toString is not a function: String() of it throws.+ put(ws, '.harness/verdict.json', JSON.stringify({ spec: 1, ready: false, findings: [{ severity: 'error', message: { toString: 0 } }] }))+ const r = await fetch(viewer.base + '/api/state?file=out/main.pdf')+ assert.equal(r.status, 500)+ assert.match((await r.json()).error, /primitive/)+ await until(() => viewer.output().includes('[doc-viewer] state failed'), 'the stream to log the failure')+ put(ws, '.harness/verdict.json', JSON.stringify({ spec: 1, ready: true, summary: 'fixed', findings: [] }))+ const next = stateOf(await events.next((b) => stateOf(b)?.verdict?.summary === 'fixed', 'the state after the fix'))+ assert.equal(next.verdict.ready, true)+ assert.equal((await fetch(viewer.base + '/api/state')).status, 200)+ assert.ok(viewer.alive())+ } finally {+ events.close()+ }+})diff --git a/store/viewers/doc-viewer/test/server.test.mjs b/store/viewers/doc-viewer/test/server.test.mjsindex 0aa14888a..48a3b8e6f 100644--- a/store/viewers/doc-viewer/test/server.test.mjs+++ b/store/viewers/doc-viewer/test/server.test.mjs@@ -28,7 +28,11 @@ before(async () => {child.on('exit', (code) => fail(new Error(`viewer exited ${code}`)))})})-after(() => { child?.kill(); rmSync(ws, { recursive: true, force: true }) })+after(async () => {+ // Wait for the exit: the server ends its streams and exits on SIGTERM (and V8 writes its coverage then).+ if (child && child.exitCode === null) { const exited = new Promise((ok) => child.once('exit', ok)); child.kill(); await exited }+ rmSync(ws, { recursive: true, force: true })+})test('serves the reader and pdf.js from the package', async () => {const page = await fetch(base + '/')diff --git a/store/viewers/doc-viewer/test/workspace.test.mjs b/store/viewers/doc-viewer/test/workspace.test.mjsindex 1970414dd..a1716e68f 100644--- a/store/viewers/doc-viewer/test/workspace.test.mjs+++ b/store/viewers/doc-viewer/test/workspace.test.mjs@@ -2,11 +2,12 @@//// npm testimport assert from 'node:assert/strict'-import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'+import { spawnSync } from 'node:child_process'+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, truncateSync, utimesSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { after, test } from 'node:test'-import { docState, safeJoin, scan, snippet, stateKey } from '../lib/workspace.mjs'+import { docState, readVerdict, safeJoin, scan, snippet, stateKey } from '../lib/workspace.mjs'const roots = []function workspace(files) {@@ -126,3 +127,88 @@ test('stateKey ignores the clock', () => {const ws = workspace({ 'out/main.pdf': { body: '%PDF', at: t(1) } })assert.equal(stateKey(docState(ws, '', 1)), stateKey(docState(ws, '', 2)))})++test('the scan goes six folders deep and no deeper', () => {+ const ws = workspace({+ 'a/b/c/d/e/f/deep.pdf': { body: '%PDF', at: t(1) },+ 'a/b/c/d/e/f/g/deeper.pdf': { body: '%PDF', at: t(2) },+ })+ assert.deepEqual(scan(ws).pdfs.map((p) => p.path), ['a/b/c/d/e/f/deep.pdf'])+})++test('the scan stops after 20,000 entries', () => {+ // 10,002 folders of one PDF each: two entries apiece, so the 10,001st folder is the 20,001st entry,+ // whatever order the filesystem lists them in. Exactly 10,000 PDFs are seen.+ const ws = workspace({})+ for (let i = 0; i < 10_002; i++) {+ mkdirSync(join(ws, `d${i}`))+ writeFileSync(join(ws, `d${i}`, 'x.pdf'), '')+ }+ assert.equal(scan(ws).pdfs.length, 10_000)+})++test('files with no extension, special files and dangling links are neither PDFs nor sources', () => {+ const ws = workspace({ 'main.typ': { body: '= Hi', at: t(0) }, Makefile: { body: 'all:', at: t(30) } })+ symlinkSync(join(ws, 'nowhere.typ'), join(ws, 'gone.typ'))+ symlinkSync(join(ws, 'nowhere.pdf'), join(ws, 'gone.pdf'))+ assert.equal(spawnSync('mkfifo', [join(ws, 'pipe.typ')]).status, 0, 'mkfifo')+ const found = scan(ws)+ assert.equal(found.source.path, 'main.typ', 'the newer FIFO and link are not the source')+ assert.deepEqual(found.pdfs, [])+})++test('a verdict that is not an object is no verdict; findings that are not a list, or not objects, are dropped', () => {+ assert.equal(readVerdict(workspace({ '.harness/verdict.json': { body: 'null' } })), null)+ assert.equal(readVerdict(workspace({ '.harness/verdict.json': { body: '3' } })), null)+ assert.deepEqual(readVerdict(workspace({ '.harness/verdict.json': { body: verdict({ findings: 'none' }) } })).findings, [])+ // A null finding used to reach `f.severity` in docState and throw, which took the server down.+ const ws = workspace({+ 'out/main.pdf': { body: '%PDF', at: t(10) },+ '.harness/verdict.json': { body: verdict({ ready: false, findings: [null, 'text', { severity: 'error', message: 'real' }] }), at: t(20) },+ })+ const s = docState(ws, 'out/main.pdf')+ assert.deepEqual(s.verdict.findings.map((f) => f.message), ['real'])+ assert.equal(s.build, 'failed')+})++test('findings are normalised: no message is empty, hints are strings and at most five', () => {+ const ws = workspace({+ '.harness/verdict.json': { body: verdict({ ready: true, findings: [{ severity: 'info', hints: [1, 'two', true, 4, 5, 6] }] }) },+ })+ const [f] = docState(ws, '').verdict.findings+ assert.deepEqual(f, { severity: 'info', kind: null, message: '', ref: null, hints: ['1', 'two', 'true', '4', '5'], snippet: null })+})++test('snippet skips a file it cannot read and one over 2 MB', () => {+ const ws = workspace({ 'huge.typ': { body: 'x' }, 'small.typ': { body: 'one\ntwo' } })+ truncateSync(join(ws, 'huge.typ'), 2_000_001)+ assert.equal(snippet(ws, 'huge.typ:1:1'), null)+ assert.equal(snippet(ws, 'missing.typ:1:1'), null)+ assert.equal(snippet(ws, 'small.typ:0:1'), null, 'line 0 is not a line')+ assert.deepEqual(snippet(ws, 'small.typ:1:1', 0).lines, [{ n: 1, text: 'one' }, { n: 2, text: 'two' }], 'no context before, one line after')+})++test('a folder that cannot be listed is empty, not an error', () => {+ assert.deepEqual(scan(join(workspace({}), 'not-there')), { pdfs: [], source: null })+})++test('the verdict the pane shows: its summary, artifact and time, or empty ones', () => {+ const full = workspace({ '.harness/verdict.json': { body: verdict({ ready: true, summary: '12 pages', artifact: 'out/main.pdf', updatedAt: '2026-09-16T12:00:00Z', findings: [] }), at: t(5) } })+ assert.deepEqual(docState(full, '').verdict, { ready: true, summary: '12 pages', artifact: 'out/main.pdf', updatedAt: '2026-09-16T12:00:00Z', mtimeMs: t(5).getTime(), findings: [] })+ const bare = workspace({ '.harness/verdict.json': { body: verdict({ ready: 'yes', summary: 3 }), at: t(5) } })+ assert.deepEqual(docState(bare, '').verdict, { ready: false, summary: '', artifact: null, updatedAt: null, mtimeMs: t(5).getTime(), findings: [] })+})++test('the requested file: not a string is none, not written yet or a folder is no PDF', () => {+ const ws = workspace({ 'out/main.pdf': { body: '%PDF', at: t(10) } })+ assert.equal(docState(ws, null).file, 'out/main.pdf')+ assert.equal(docState(ws, 42).requested, '')+ const later = docState(ws, '/out/later.pdf')+ assert.equal(later.requested, 'out/later.pdf', 'leading slashes are dropped')+ assert.equal(later.file, 'out/later.pdf')+ assert.equal(later.pdf, null)+ const folder = docState(ws, 'out')+ assert.equal(folder.file, 'out')+ assert.equal(folder.pdf, null)+ assert.equal(docState(ws, '../elsewhere.pdf').file, 'out/main.pdf', 'a path outside is ignored')+})diff --git a/store/viewers/doc-viewer/viewer.mjs b/store/viewers/doc-viewer/viewer.mjsindex 3dac53031..38f3b129b 100644--- a/store/viewers/doc-viewer/viewer.mjs+++ b/store/viewers/doc-viewer/viewer.mjs@@ -80,7 +80,8 @@ async function handleOpen(req, res) {if (!trusted(req)) return json(res, 403, { ok: false, error: 'forbidden' })if (OPEN_MODE === 'off') return json(res, 501, { ok: false, error: 'opening is not available here' })let body- try { body = JSON.parse(await readBody(req)) } catch { return json(res, 400, { ok: false, error: 'bad request' }) }+ try { body = JSON.parse(await readBody(req)) } catch { body = null }+ if (!body || typeof body !== 'object') return json(res, 400, { ok: false, error: 'bad request' })if (body.kind === 'url') {const url = String(body.url ?? '')if (!/^(https?:\/\/|mailto:)/i.test(url) || url.length > 4096) return json(res, 400, { ok: false, error: 'only http(s) and mailto links open' })@@ -98,10 +99,13 @@ function state(file) {return { ...docState(workspace, file), canOpen: OPEN_MODE !== 'off' }}-createServer((req, res) => {- const url = new URL(req.url ?? '/', `http://127.0.0.1:${port}`)- let path- try { path = decodeURIComponent(url.pathname) } catch { res.writeHead(400); res.end(); return }+const server = createServer((req, res) => {+ // An absolute-form target (`GET http://a:99999/`) is not a URL either: both answer 400, neither throws.+ let url, path+ try {+ url = new URL(req.url, `http://127.0.0.1:${port}`)+ path = decodeURIComponent(url.pathname)+ } catch { res.writeHead(400); res.end(); return }if (path === '/' || path === '/index.html') return sendFile(req, res, join(APP, 'index.html'))if (path.startsWith('/app/')) {const full = safeJoin(APP, path.slice('/app/'.length))@@ -116,7 +120,12 @@ createServer((req, res) => {const full = safeJoin(workspace, path.slice('/ws/'.length))return full ? sendFile(req, res, full, { download: url.searchParams.has('download') }) : (res.writeHead(404), res.end())}- if (path === '/api/state') return json(res, 200, state(url.searchParams.get('file') ?? ''))+ if (path === '/api/state') {+ // A verdict the agent wrote badly is an error for this request, never the end of the pane.+ let body+ try { body = state(url.searchParams.get('file') ?? '') } catch (error) { return json(res, 500, { error: error.message }) }+ return json(res, 200, body)+ }if (path === '/api/open' && req.method === 'POST') { handleOpen(req, res).catch((e) => json(res, 500, { ok: false, error: e.message })); return }if (path === '/events') {res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })@@ -156,3 +165,5 @@ try {}setInterval(() => { if (clients.size) flush() }, 3000).unref()setInterval(() => { for (const c of clients) c.res.write(': ping\n\n') }, 20_000).unref()+// Harness stops the pane with a signal: end the event streams and exit, rather than dying mid-write.+for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => { for (const c of clients) c.res.end(); server.close(); process.exit(0) })