Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

feat(view): init and resume keep the view running [H5,N26]

Corey Olson7ff322f59690
diff --git a/bin/run-tests.js b/bin/run-tests.js
index a2cd2931..6d3a2e1b 100644
--- a/bin/run-tests.js
+++ b/bin/run-tests.js
@@ -220,6 +220,8 @@ function testEnvironment(sandbox, gateMarkers = {}) {
env.PULLBOARD_HOME = home;
env.PULLBOARD_MODEL = 'Test Model';
env.PULLBOARD_MACHINE_HOME = join(sandbox, 'machine');
+ // init and resume start a background view by default; a test opts back in by deleting this.
+ env.PULLBOARD_VIEW_BACKGROUND = '0';
env.TMPDIR = sandbox;
env.TMP = sandbox;
env.TEMP = sandbox;
diff --git a/docs/api.md b/docs/api.md
index 3640a60c..59f30cf4 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -16,6 +16,8 @@ The machine gate pool admits landings first and then everything else in arrival
Release priority is separately opt-in with `"gate": { "queue": { "currentReleaseFirst": true } }`. Before queueing, a gate run captures its board identity and its item's roadmap rank. The first unfinished milestone is current, counting only this board's own items as verified out of total; `repo#id` references are left out and never opened. Later milestones follow in roadmap order, then already completed earlier milestones, then unplanned work. Within otherwise-tied positions belonging to one board, current-release work goes first: `A-later, B, A-current` becomes `A-current, B, A-later`. Different boards retain their opportunity positions. Global admission classes and landings retain their existing precedence, and a waiter older than `agingMinutes` keeps its position against release reordering. Queued ranks do not change if the roadmap changes. With the setting off, no board is read for release priority. Unknown board identities keep their positions; while any older client is waiting, all clients fall back together to landings then arrival. `pullboard settings` prints `gate.queue.currentReleaseFirst`, default `false`.
+`pullboard init` and `pullboard resume` keep `pullboard view` running in the background, so pullboard.dev finds this computer's boards with no command. When no view answers on the view port (4890, or `PULLBOARD_VIEW_PORT`), they start one detached, writing its output to a private `view-<port>.log` beside the view's session record in `~/.pullboard`; a view already running is left alone, and a busy port is one line that fails neither command. init prints one line naming where the view runs, its log and the `kill <pid>` that stops it; resume prints that line only when it starts the view or cannot. Both JSON results carry `view` with `state` (`started`, `running`, `busy`, `off` or `failed`), `port` and, for a view, `pid`. It is on unless the machine sets `"view": { "background": false }` in `~/.pullboard/settings.json`; `PULLBOARD_VIEW_BACKGROUND=0` turns it off for one process tree, and the test runner sets it so tests leave no view behind.
+
The memory hold is opt-in per machine with `"gate": { "memoryFloorMB": <n> }` in `~/.pullboard/settings.json`; absent, it is off and the pool admits by slots alone, as before. When set, before admitting a run the machine gate pool reads the machine's memory: on macOS the kernel's memory pressure level and free percentage, on Linux `MemAvailable` and the pressure stall averages in `/proc/pressure/memory`. The whole queue, landings included, waits in place while pressure is critical or free memory is under that many megabytes (`0` leaves only the pressure check). A held run prints one line naming why and the three biggest processes by memory, with pid, size and working directory, and starts once memory recovers. While the floor is set, `pullboard resources` prints the same line and returns it as `memory` in JSON; with no floor it reads no memory and `memory` is `null`. Where memory cannot be read, the pool admits by slots alone and prints one warning that memory is not checked there.
When `add` or `edit` supplies a new nonempty check, it records the item before measuring that check in a background temporary checkout of the captured `main` commit. Use `--wait` to wait for the measurement before returning, or `args.wait: true` for an HTTP add/edit move. The item returned by `add`, `edit`, `show`, and `next --verify` may include `item_check_baseline`: `{command, main, result, request?, seconds?, reason?, warning?}`. `main` is the commit id or `null`, and `result` is `pending`, `green`, `red`, or `unavailable`. A background request carries an opaque `request` identity; an older completion cannot overwrite a newly edited or cleared check.
diff --git a/src/background-view.js b/src/background-view.js
new file mode 100644
index 00000000..beac6536
--- /dev/null
+++ b/src/background-view.js
@@ -0,0 +1,191 @@
+/**
+ * Keep `pullboard view` running in the background [H5,N26].
+ *
+ * pullboard.dev reads this computer's boards from the view on 127.0.0.1:4890, so a newcomer who
+ * never typed `pullboard view` would meet an empty page. `pullboard init` and `pullboard resume`
+ * therefore start the view detached when none is running, with its own log. A running view is
+ * left alone, a busy port is one line and never a failure, and the machine setting
+ * `view.background` (on unless set to false) turns it off.
+ */
+import { spawn } from 'node:child_process';
+import { closeSync, mkdirSync, openSync } from 'node:fs';
+import { connect } from 'node:net';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { Refused } from './refused.js';
+import { registryFile } from './projects.js';
+import { LOOPBACK } from './serve.js';
+import { defaultViewPort } from './view-port.js';
+import { portHolder, runningView } from './view-session.js';
+import { machineSettingsFile, viewBackgroundEnabled } from './settings.js';
+
+const BIN = fileURLToPath(new URL('../bin/pullboard.js', import.meta.url));
+
+/** The environment opt-out, for a process tree that must never leave a view behind (test runs). */
+export const BACKGROUND_ENV = 'PULLBOARD_VIEW_BACKGROUND';
+
+/** The exact stop action for a view process on this platform. */
+export function stopCommand(pid) {
+ return process.platform === 'win32' ? `taskkill /PID ${pid} /T` : `kill ${pid}`;
+}
+
+/** Print a live or reused view link and the exact stop action for its owning process. */
+export function reportView(io, view) {
+ io.result?.({ url: view.url, port: view.port, pid: view.pid, boundAt: view.boundAt, reused: view.reused });
+ io.say(`Pullboard view: ${view.url}`);
+ io.say(`Only this machine can reach it, and only with that link. To stop it: ${stopCommand(view.pid)}`);
+}
+
+/**
+ * Spawn a detached `pullboard view` child and wait for its bind over IPC. The child is the plain
+ * foreground view (PULLBOARD_VIEW_BACKGROUND_CHILD), so it records its own private session.
+ *
+ * @param {{ args: string[], cwd: string, stdio: any[] }} options
+ * @returns {Promise<{ child: import('node:child_process').ChildProcess, view: any }>}
+ */
+function startDetachedView({ args, cwd, stdio }) {
+ const child = spawn(process.execPath, [BIN, 'view', '--no-open', ...args], {
+ cwd,
+ env: { ...process.env, PULLBOARD_VIEW_BACKGROUND_CHILD: '1' },
+ detached: true,
+ stdio,
+ });
+ let stderr = '';
+ child.stderr?.setEncoding('utf8').on('data', (part) => { stderr += part; });
+ return new Promise((resolveStartup, rejectStartup) => {
+ let settled = false;
+ const finish = (error, view) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ if (!error) return resolveStartup({ child, view });
+ child.kill('SIGTERM');
+ rejectStartup(error);
+ };
+ const timer = setTimeout(() => finish(new Refused('VIEW_START', 'the view did not bind in time; run pullboard view in the foreground for details')),
+ 35_000); // budget: the 30s registry lock ceiling plus 5s for local bind and IPC delivery.
+ child.on('message', (message) => {
+ if (message?.type === 'ready') finish(null, message);
+ else if (message?.type === 'startup-error') {
+ const prefix = `[${message.code}] `;
+ finish(new Refused(message.code, message.message.startsWith(prefix) ? message.message.slice(prefix.length) : message.message));
+ }
+ });
+ child.once('error', (error) => finish(new Refused('VIEW_START', `could not start the view: ${error.message}`)));
+ child.once('exit', (code, signal) => {
+ finish(new Refused('VIEW_START', `the view stopped before binding (exit ${code ?? signal ?? 'unknown'}): ${stderr.trim() || 'no startup details'}`));
+ });
+ });
+}
+
+/** Let a started child outlive this command: no pipes, no IPC channel, no reference. */
+function release(child) {
+ child.stderr?.destroy();
+ child.unref();
+ if (child.connected) child.disconnect();
+}
+
+/**
+ * `pullboard view` from an agent shell or a non-terminal: start the view detached and print its
+ * link, forwarding only its bound address over IPC.
+ *
+ * @param {any} io
+ * @param {number} port
+ * @param {string} [projectRoot]
+ * @returns {Promise<number>}
+ */
+export async function launchBackgroundView(io, port, projectRoot) {
+ const { child, view } = await startDetachedView({
+ args: [...(projectRoot ? ['--project'] : []), '--port', String(port)],
+ cwd: projectRoot ?? io.cwd,
+ stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
+ });
+ release(child);
+ reportView(io, { ...view, reused: false });
+ io.flush?.(0);
+ return 0;
+}
+
+/** Whether something already accepts connections on this loopback port. */
+function portAnswers(port) {
+ return new Promise((answer) => {
+ const socket = connect({ host: LOOPBACK, port });
+ const done = (open) => { socket.destroy(); answer(open); };
+ socket.setTimeout(1_000, () => done(true)); // budget: a loopback connect answers at once; a silent socket is taken as held.
+ socket.once('connect', () => done(true));
+ socket.once('error', () => done(false));
+ });
+}
+
+/**
+ * The background view's own log file, beside its private session record. It holds the view's
+ * output, link included, so it is private to this account.
+ *
+ * @param {number} port
+ * @returns {string}
+ */
+export function backgroundViewLog(port) {
+ return join(dirname(registryFile()), `view-${port}.log`);
+}
+
+/**
+ * Make sure a view serves this machine's boards for pullboard.dev, starting one detached when
+ * none runs. Never throws: init and resume go on whatever happens here, and the outcome says
+ * what to print.
+ *
+ * The child starts in the private home folder, outside any repository, so starting it records no
+ * board's "view opened" receipt: the person has still not been shown the board.
+ *
+ * @param {NodeJS.ProcessEnv} [env]
+ * @returns {Promise<{ state: 'off' | 'running' | 'started' | 'busy' | 'failed', port?: number, pid?: number, log?: string, holder?: { pid: number, name: string } | null, message?: string }>}
+ */
+export async function keepViewRunning(env = process.env) {
+ let port;
+ try {
+ if (['0', 'false', 'off'].includes(String(env[BACKGROUND_ENV] ?? '').toLowerCase()) || !viewBackgroundEnabled()) return { state: 'off' };
+ port = defaultViewPort(env);
+ } catch (error) {
+ if (!(error instanceof Refused)) throw error;
+ return { state: 'failed', message: error.message };
+ }
+ if (port === 0) return { state: 'off' };
+ const existing = await runningView(port);
+ if (existing) return { state: 'running', port, pid: existing.pid };
+ if (await portAnswers(port)) return { state: 'busy', port, holder: portHolder(port) };
+ const log = backgroundViewLog(port);
+ let fd;
+ try {
+ mkdirSync(dirname(log), { recursive: true });
+ fd = openSync(log, 'w', 0o600);
+ const { child, view } = await startDetachedView({ args: ['--port', String(port)], cwd: dirname(log), stdio: ['ignore', fd, fd, 'ipc'] });
+ release(child);
+ return { state: 'started', port, pid: view.pid, log };
+ } catch (error) {
+ if (error instanceof Refused && error.code === 'PORT_BUSY') return { state: 'busy', port, holder: portHolder(port) };
+ return { state: 'failed', port, log, message: error.message };
+ } finally {
+ if (fd !== undefined) closeSync(fd);
+ }
+}
+
+/**
+ * The one line init and resume print about the background view, or null when there is nothing
+ * to say. Every line that names a running view says how to stop it.
+ *
+ * @param {Awaited<ReturnType<typeof keepViewRunning>>} outcome
+ * @returns {string | null}
+ */
+export function backgroundViewLine(outcome) {
+ const where = `http://${LOOPBACK}:${outcome.port}`;
+ const off = `turn this off with "view": { "background": false } in ${machineSettingsFile()}`;
+ if (outcome.state === 'started') {
+ return `Pullboard view is running in the background at ${where}, so pullboard.dev finds this computer's boards (log: ${outcome.log}). To stop it: ${stopCommand(outcome.pid)}; ${off}`;
+ }
+ if (outcome.state === 'running') return `Pullboard view is running at ${where}, so pullboard.dev finds this computer's boards. To stop it: ${stopCommand(outcome.pid)}`;
+ if (outcome.state === 'busy') {
+ const { holder } = outcome;
+ return `Port ${outcome.port} is in use${holder ? ` by ${holder.name} (pid ${holder.pid})` : ''}, so the background view did not start, and pullboard.dev looks for your view on that port: stop ${holder ? `it with ${stopCommand(holder.pid)}` : 'the program there'}, then run pullboard resume`;
+ }
+ if (outcome.state === 'failed') return `The background view did not start: ${outcome.message}${outcome.log ? ` (log: ${outcome.log})` : ''}. Run pullboard view to see why`;
+ return null;
+}
diff --git a/src/cli.js b/src/cli.js
index 62e74d64..8e31c88b 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -8,7 +8,7 @@ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, realp
import { hostname, loadavg } from 'node:os';
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { performance } from 'node:perf_hooks';
-import { fileURLToPath, pathToFileURL } from 'node:url';
+import { pathToFileURL } from 'node:url';
import { parseArgs } from 'node:util';
import * as store from './board.js';
import { CONFIG_FILE, COORDINATOR, DOCTRINE_FILE, LEGACY_DOCTRINE_FILE, loadConfig } from './config.js';
@@ -78,6 +78,7 @@ import { listResources, memoryVerdict, readMachineMemory, runnerResourceStatus }
import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';
import { exportView, serveView } from './serve.js';
import { forgetView, portHolder, rememberView, runningView } from './view-session.js';
+import { backgroundViewLine, keepViewRunning, launchBackgroundView, reportView } from './background-view.js';
import { serveApi } from './api.js';
import { serveMcp } from './mcp.js';
import { doctorProblems, doctrineProblems } from './doctor.js';
@@ -1275,9 +1276,10 @@ function boardSetup(ctx, card, identity) {
* a restart or a compaction, from the board rather than from a summary.
*
* @param {any} io
+ * @param {Awaited<ReturnType<typeof keepViewRunning>>} view what keeping the background view running did
* @returns {number}
*/
-function resumeHere(io) {
+function resumeHere(io, view) {
const ctx = context(io);
const { root, isMain } = ctx.info;
const mainRoot = primaryCheckoutRoot(ctx.info);
@@ -1342,6 +1344,9 @@ function resumeHere(io) {
for (const problem of card.hookProblems) say(`${problem.message}; ${problem.next}`);
const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
say(`resume: ${me.displayName}${me.family ? ` [family ${me.family}]` : ''}, ${me.lane} lane${isMain ? ', the main checkout' : ''}, at ${root}`);
+ card.view = view;
+ // A view left running needs no line at every session start; a start, a busy port or a failure does.
+ if (view.state !== 'running' && backgroundViewLine(view)) say(backgroundViewLine(view));
if (card.inbox) for (const line of coordinatorInboxLines(card.inbox, name, (at) => span(ctx, at), firstLine)) say(line);
say(`New agent worktrees: ${card.newWorktreeLocation}`);
card.setup = boardSetup(ctx, card, setupScope);
@@ -1553,62 +1558,6 @@ async function viewHere(io, values) {
return 0;
}
-/** Print a live or reused view link and the exact stop action for its owning process. */
-function reportView(io, view) {
- io.result?.({ url: view.url, port: view.port, pid: view.pid, boundAt: view.boundAt, reused: view.reused });
- io.say(`Pullboard view: ${view.url}`);
- io.say(`Only this machine can reach it, and only with that link. To stop it: ${process.platform === 'win32' ? `taskkill /PID ${view.pid} /T` : `kill ${view.pid}`}`);
-}
-
-/** Start the view in a detached CLI child, forwarding only its bound address over IPC. */
-async function launchBackgroundView(io, port, projectRoot) {
- const args = [fileURLToPath(new URL('../bin/pullboard.js', import.meta.url)), 'view', '--no-open'];
- if (projectRoot) args.push('--project');
- args.push('--port', String(port));
- const child = spawn(process.execPath, args, {
- cwd: projectRoot ?? io.cwd,
- env: { ...process.env, PULLBOARD_VIEW_BACKGROUND_CHILD: '1' },
- detached: true,
- stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
- });
- let stderr = '';
- child.stderr.setEncoding('utf8').on('data', (part) => { stderr += part; });
- const startup = new Promise((resolveStartup, rejectStartup) => {
- let settled = false;
- const finish = (error, result) => {
- if (settled) return;
- settled = true;
- clearTimeout(timer);
- error ? rejectStartup(error) : resolveStartup(result);
- };
- const timer = setTimeout(() => finish(new Refused('VIEW_START', 'the view did not bind in time; run pullboard view in the foreground for details')),
- 35_000); // budget: the 30s registry lock ceiling plus 5s for local bind and IPC delivery.
- child.on('message', (message) => {
- if (message?.type === 'ready') finish(null, message);
- else if (message?.type === 'startup-error') {
- const prefix = `[${message.code}] `;
- finish(new Refused(message.code, message.message.startsWith(prefix) ? message.message.slice(prefix.length) : message.message));
- }
- });
- child.once('error', (error) => finish(new Refused('VIEW_START', `could not start the view: ${error.message}`)));
- child.once('exit', (code, signal) => {
- finish(new Refused('VIEW_START', `the view stopped before binding (exit ${code ?? signal ?? 'unknown'}): ${stderr.trim() || 'no startup details'}`));
- });
- });
- try {
- const view = await startup;
- child.stderr.destroy();
- child.unref();
- child.disconnect();
- reportView(io, { ...view, reused: false });
- io.flush?.(0);
- return 0;
- } catch (error) {
- child.kill('SIGTERM');
- throw error;
- }
-}
-
/**
* Serve MCP over stdio as this checkout's agent (A9). Stdout carries only the protocol, so the command
* takes no --json; each tool call runs its own CLI command, with its own relay sync, through main.
@@ -1692,9 +1641,10 @@ function setupCommands(io, { first, second, rest = [], values }) {
]));
// Keep blueprint initialization and the person's unwritten lane proposals in the same result.
const added = blueprint ? await addBlueprintHere(io, values.blueprint, { report: false, blueprint }) : null;
- io.result?.({ root: info.root, notes, proposedLanes: proposeLanes(info.root),
+ const result = { root: info.root, notes, proposedLanes: proposeLanes(info.root),
...(added ? { blueprint: { name: added.blueprint.name, title: added.blueprint.title,
- section: added.section, waiting: added.rows.length, items: added.items.length, gate: added.gate, checksNotRun: added.checksNotRun } } : {}) });
+ section: added.section, waiting: added.rows.length, items: added.items.length, gate: added.gate, checksNotRun: added.checksNotRun } } : {}) };
+ io.result?.(result);
const staging = notes.at(-1)?.startsWith('git add -f -- ') ? notes.at(-1) : null;
(staging ? notes.slice(0, -1) : notes).forEach((note) => io.say(note));
if (added) {
@@ -1704,6 +1654,11 @@ function setupCommands(io, { first, second, rest = [], values }) {
if (added.checksNotRun.length) io.say(` checks stored, not run: ${added.checksNotRun.map((id) => `#${id}`).join(', ')}; no check baseline ran, so read each check before work starts: pullboard show <id>`);
}
if (await registerProjectAndLink(info.root, new Date(), loadConfig(info.root), io)) io.say('registered this project on this machine, so pullboard view lists it');
+ // Once registered, a background view lists this board for pullboard.dev [H5,N26].
+ const view = await keepViewRunning();
+ io.result?.({ ...result, view });
+ const viewLine = backgroundViewLine(view);
+ if (viewLine) io.say(viewLine);
io.say(agentSessionDigest()
? 'Next: run pullboard resume now to continue setup in this session; the new skills load next session, and setup does not need them.'
: 'Next: ask your agent to set up Pullboard here; in Claude Code, start a new session first so it loads the Pullboard skills.');
@@ -1993,7 +1948,10 @@ function readCommands(io, { first, second, rest, values }) {
for (const runner of runners) io.say(`runner ${runner.host}: ${runner.inUse}/${runner.slots} slots, ${runner.browserInUse}/${runner.browser} browser${runner.unavailable ? ' (unavailable; re-register after checking the host)' : ''}`);
return 0;
},
- resume: () => resumeHere(io),
+ resume: async () => {
+ repoInfo(io.cwd);
+ return resumeHere(io, await keepViewRunning());
+ },
whoami: () => {
const ctx = context(io);
const me = withBoard(ctx, (board) => whoAmI(ctx, board));
@@ -3281,6 +3239,7 @@ function settingsCommand(io, { first, second, rest }) {
io.say(`gate.queue.currentReleaseFirst: ${queue.currentReleaseFirst}${queue.currentReleaseFirst ? '' : ' (release priority is off)'}`);
io.say(`gate.queue.agingMinutes: ${queue.agingMinutes}${queue.reviewsFirst || queue.currentReleaseFirst ? '' : ' (used only while reviewsFirst or currentReleaseFirst is true)'}`);
io.say(`gate.memoryFloorMB: ${memoryFloorMB() ?? 'off (the gate queue does not wait for memory)'}`);
+ io.say(`view.background: ${settings.view?.background !== false}${settings.view?.background === false ? ' (init and resume leave the view to you)' : ' (init and resume keep pullboard view running for pullboard.dev)'}`);
return 0;
}
if (!['gateSlots', 'browserSlots'].includes(first) || !second || rest.length) {
diff --git a/src/settings.js b/src/settings.js
index b7e67c6e..90c0704e 100644
--- a/src/settings.js
+++ b/src/settings.js
@@ -22,6 +22,10 @@ export function loadMachineSettings() {
throw new Refused('BAD_MACHINE_SETTINGS', `gate.browserFreeChecks in ${file} must be true or false`);
}
validateGateQueue(value, file);
+ if (value.view !== undefined && (!value.view || typeof value.view !== 'object' || Array.isArray(value.view)
+ || (value.view.background !== undefined && typeof value.view.background !== 'boolean'))) {
+ throw new Refused('BAD_MACHINE_SETTINGS', `view in ${file} must be an object whose background is true or false; fix it before running Pullboard`);
+ }
if (value.gate?.memoryFloorMB !== undefined && (!Number.isSafeInteger(value.gate.memoryFloorMB) || value.gate.memoryFloorMB < 0)) {
throw new Refused('BAD_MACHINE_SETTINGS', `gate.memoryFloorMB in ${file} must be a whole number of megabytes, 0 or more; fix it before running Pullboard`);
}
@@ -49,6 +53,16 @@ export function browserFreeChecksEnabled() {
return loadMachineSettings().gate?.browserFreeChecks === true;
}
+/**
+ * Whether init and resume keep a view running in the background [H5,N26]. Unlike the gate's
+ * settings this is on by default: pullboard.dev can only open a computer's boards while its view
+ * runs, and a newcomer should never need a command for that. Only `"view": { "background": false }`
+ * turns it off.
+ */
+export function viewBackgroundEnabled() {
+ return loadMachineSettings().view?.background !== false;
+}
+
/**
* The free-memory floor, in megabytes, below which the machine gate pool holds its queue, or null
* when the hold is off. Gate and queue behavior is off by default, the person's rule, so an absent
diff --git a/test/background-view.test.js b/test/background-view.test.js
new file mode 100644
index 00000000..497347e2
--- /dev/null
+++ b/test/background-view.test.js
@@ -0,0 +1,184 @@
+/** init and resume keep pullboard view running in the background for pullboard.dev [H5,N26]. */
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { createServer } from 'node:net';
+import { join } from 'node:path';
+import { after, test } from 'node:test';
+import { createE2eHelpers } from './e2e-helpers.js';
+import { fetchFresh } from './http-fixture.js';
+import { takeDefaultViewPort } from './view-port-fixture.js';
+
+const e2e = createE2eHelpers();
+after(e2e.cleanup);
+
+/**
+ * A fresh repository in a private home whose default view port is a leased stand-in for 4890, so
+ * the person's real view is never touched, with the test runner's background opt-out removed.
+ */
+async function backgroundBox(t, name) {
+ const box = e2e.sandbox();
+ const lease = await takeDefaultViewPort(box.dir, { agent: `background-view-${name}-${process.pid}` });
+ t.after(() => lease.release());
+ box.env.PULLBOARD_VIEW_PORT = String(lease.port);
+ delete box.env.PULLBOARD_VIEW_BACKGROUND;
+ delete box.env.PULLBOARD_VIEW_FOREGROUND;
+ delete box.env.PULLBOARD_VIEW_BACKGROUND_CHILD;
+ const repo = join(box.dir, name);
+ mkdirSync(repo);
+ box.git(repo, 'init', '-q', '-b', 'main');
+ return { box, repo, port: lease.port };
+}
+
+/** Whether a process id is still alive. */
+function alive(pid) {
+ try { process.kill(pid, 0); return true; }
+ catch (error) { return error.code === 'EPERM'; }
+}
+
+/** Stop one view this test started, by its own pid, and wait until it is gone. */
+async function stopView(pid) {
+ if (!alive(pid)) return;
+ try { process.kill(pid, 'SIGTERM'); }
+ catch (error) { if (error.code !== 'ESRCH') throw error; }
+ const deadline = Date.now() + 5_000; // budget: ceiling for the view's graceful close after SIGTERM.
+ while (alive(pid) && Date.now() < deadline) await new Promise((done) => setTimeout(done, 25)); // budget: poll interval while the owned view exits.
+ if (alive(pid)) process.kill(pid, 'SIGKILL');
+}
+
+/** The pids of view processes on this test's leased port, listed (never killed) from ps. */
+function viewProcesses(port) {
+ const listed = spawnSync('ps', ['-A', '-o', 'pid=,command='], { encoding: 'utf8' });
+ return listed.stdout.split('\n')
+ .filter((line) => line.includes('pullboard.js view --no-open') && line.includes(`--port ${port}`))
+ .map((line) => Number(line.trim().split(/\s+/u)[0]));
+}
+
+/** The private session record a background view left for this port. */
+function sessionRecord(box, port) {
+ return JSON.parse(readFileSync(join(box.env.PULLBOARD_HOME, `view-${port}.json`), 'utf8'));
+}
+
+/** Whether something answers on the leased loopback port. */
+async function answers(port, secret) {
+ try {
+ const response = await fetchFresh(`http://127.0.0.1:${port}/api/v1/boards`, {
+ headers: { 'x-pullboard-key': secret ?? 'none' }, redirect: 'manual', signal: AbortSignal.timeout(2_000), // budget: a local listener answers at once.
+ });
+ const body = response.ok ? await response.json() : (await response.body?.cancel(), null);
+ return { status: response.status, body };
+ } catch (error) {
+ if (error.cause?.code === 'ECONNREFUSED') return null;
+ throw error;
+ }
+}
+
+/** The lines of a command's output that speak about the background view. */
+function viewLines(out) {
+ return out.split('\n').filter((line) => /background view|Pullboard view is running|^Port \d+ is in use/u.test(line));
+}
+
+test('init leaves a view running for pullboard.dev [H5,N26]', async (t) => {
+ const { box, repo, port } = await backgroundBox(t, 'init-view');
+ const init = box.run(repo, 'init');
+ assert.equal(init.code, 0, init.err || init.out);
+ const record = sessionRecord(box, port);
+ t.after(() => stopView(record.pid));
+ assert.ok(alive(record.pid), 'the view is still running after init exited');
+ assert.notEqual(record.pid, process.pid);
+
+ const lines = viewLines(init.out);
+ assert.equal(lines.length, 1, `init prints one line about the view:\n${init.out}`);
+ const log = join(box.env.PULLBOARD_HOME, `view-${port}.log`);
+ assert.equal(lines[0], `Pullboard view is running in the background at http://127.0.0.1:${port}, so pullboard.dev finds this computer's boards (log: ${log}). `
+ + `To stop it: kill ${record.pid}; turn this off with "view": { "background": false } in ${join(box.env.PULLBOARD_MACHINE_HOME, 'settings.json')}`);
+ assert.ok(!init.out.includes(record.secret), 'the line names where the view is, never its secret');
+
+ const listing = await answers(port, record.secret);
+ assert.equal(listing?.status, 200, 'the view answers on the port pullboard.dev reads');
+ assert.ok(listing.body.boards.some((board) => board.root === repo || board.path === repo || JSON.stringify(board).includes(repo)),
+ `the background view lists the board init just made: ${JSON.stringify(listing.body.boards)}`);
+
+ // Detached: its own process group, so closing init's terminal does not stop it.
+ const group = spawnSync('ps', ['-o', 'pgid=', '-p', String(record.pid)], { encoding: 'utf8' }).stdout.trim();
+ assert.equal(Number(group), record.pid, 'the view leads its own process group');
+ assert.ok(existsSync(log), 'the view has its own log');
+ assert.equal(statSync(log).mode & 0o777, 0o600, 'the log is private: it holds the view link');
+ assert.match(readFileSync(log, 'utf8'), new RegExp(`^Pullboard view: http://127\\.0\\.0\\.1:${port}/`, 'mu'));
+ assert.equal(existsSync(join(repo, '.git', 'pullboard', 'view-bind.json')), false,
+ 'a background start does not count as the person opening the board');
+
+ // A second init leaves the running view alone.
+ const again = box.run(repo, 'init', '--json');
+ assert.equal(again.code, 0, again.err || again.out);
+ const view = JSON.parse(again.out).view;
+ assert.deepEqual({ state: view.state, pid: view.pid }, { state: 'running', pid: record.pid });
+ assert.deepEqual(viewProcesses(port), [record.pid], 'one view process, never a second one');
+
+ await stopView(record.pid);
+ assert.deepEqual(viewProcesses(port), [], 'no view process is left behind');
+});
+
+test('resume starts the view once and the setting turns it off [H5,N26]', async (t) => {
+ const { box, repo, port } = await backgroundBox(t, 'resume-view');
+ box.env.PULLBOARD_VIEW_BACKGROUND = '0';
+ const init = box.run(repo, 'init');
+ assert.equal(init.code, 0, init.err || init.out);
+ assert.deepEqual(viewLines(init.out), [], 'the opt-out is quiet');
+ assert.equal(await answers(port), null, 'with the opt-out, init starts no view');
+ delete box.env.PULLBOARD_VIEW_BACKGROUND;
+ const started = [];
+ t.after(async () => { for (const pid of started) await stopView(pid); });
+
+ const first = box.run(repo, 'resume');
+ assert.equal(first.code, 0, first.err || first.out);
+ const record = sessionRecord(box, port);
+ started.push(record.pid);
+ assert.equal(viewLines(first.out).length, 1, `resume says it started the view:\n${first.out}`);
+ assert.match(viewLines(first.out)[0], new RegExp(`^Pullboard view is running in the background at http://127\\.0\\.0\\.1:${port},.* To stop it: kill ${record.pid};`, 'u'));
+ assert.equal((await answers(port, record.secret))?.status, 200);
+
+ const second = box.run(repo, 'resume', '--json');
+ assert.equal(second.code, 0, second.err || second.out);
+ const card = JSON.parse(second.out);
+ assert.deepEqual({ state: card.view.state, pid: card.view.pid }, { state: 'running', pid: record.pid }, 'a running view is left alone');
+ assert.equal(sessionRecord(box, port).pid, record.pid, 'same pid');
+ assert.deepEqual(viewProcesses(port), [record.pid], 'one process');
+ const quiet = box.run(repo, 'resume');
+ assert.deepEqual(viewLines(quiet.out), [], 'a view already running is not announced at every session start');
+
+ await stopView(record.pid);
+ assert.equal(await answers(port), null);
+ // The machine setting turns it off for init and resume alike.
+ mkdirSync(box.env.PULLBOARD_MACHINE_HOME, { recursive: true });
+ const settings = join(box.env.PULLBOARD_MACHINE_HOME, 'settings.json');
+ writeFileSync(settings, `${JSON.stringify({ view: { background: false } })}\n`);
+ const off = box.run(repo, 'resume', '--json');
+ assert.equal(off.code, 0, off.err || off.out);
+ assert.equal(JSON.parse(off.out).view.state, 'off');
+ const offInit = box.run(repo, 'init');
+ assert.equal(offInit.code, 0, offInit.err || offInit.out);
+ assert.deepEqual(viewLines(offInit.out), []);
+ assert.equal(await answers(port), null, 'with view.background false, neither init nor resume starts it');
+ assert.deepEqual(viewProcesses(port), []);
+ const shown = box.run(repo, 'settings');
+ assert.match(shown.out, /^view\.background: false/mu, 'pullboard settings shows the setting');
+
+ // A busy port is reported once and fails nothing.
+ rmSync(settings);
+ const held = createServer();
+ await new Promise((done, fail) => { held.once('error', fail); held.listen(port, '127.0.0.1', done); });
+ t.after(() => new Promise((done) => held.close(done)));
+ const busy = box.run(repo, 'resume', '--json');
+ assert.equal(busy.code, 0, busy.err || busy.out);
+ assert.equal(JSON.parse(busy.out).view.state, 'busy');
+ const busyText = box.run(repo, 'resume');
+ assert.equal(busyText.code, 0, busyText.err || busyText.out);
+ const busyLines = viewLines(busyText.out);
+ assert.equal(busyLines.length, 1, `one line for a busy port:\n${busyText.out}`);
+ assert.match(busyLines[0], new RegExp(`^Port ${port} is in use.*, so the background view did not start, and pullboard\\.dev looks for your view on that port: stop .+, then run pullboard resume$`, 'u'));
+ const busyInit = box.run(repo, 'init');
+ assert.equal(busyInit.code, 0, busyInit.err || busyInit.out);
+ assert.equal(viewLines(busyInit.out).length, 1);
+ assert.deepEqual(viewProcesses(port), [], 'a busy port starts no view');
+});