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): every hosted page state says what to do next [N26,H5]

Corey Olson71b70266687c
diff --git a/src/cockpit.js b/src/cockpit.js
index 8294864f..c71a008f 100644
--- a/src/cockpit.js
+++ b/src/cockpit.js
@@ -5,6 +5,12 @@ import {
} from './machine.js';
import { commandPhrases } from './help.js';
import { personNeeds } from './needs.js';
+import {
+ drawHosted,
+ hostedBrowser,
+ hostedMarkup,
+ hostedState,
+} from './view/hosted.js';
/** The CLI's default phrases, ordered by depth for the existing prose inventory guard. */
export const PULLBOARD_COMMANDS = Object.freeze(commandPhrases().sort((left, right) => right.split(' ').length - left.split(' ').length));
@@ -81,7 +87,7 @@ export function cockpitPage(key = '', { snapshot = false, readOnly = false, requ
</div>
<div class="side-body" id="side-body">
<div class="label">Projects</div>
- <nav id="proj-list" aria-label="Projects on this machine"></nav>
+ <nav id="proj-list" aria-label="Projects on this machine"></nav><p class="side-hint" id="side-hint" hidden></p>
<section class="products" id="products" aria-label="Products" hidden><div class="label">Products</div><div id="prod-list"></div></section>
</div>
</aside>
@@ -103,10 +109,7 @@ export function cockpitPage(key = '', { snapshot = false, readOnly = false, requ
<p>Run <code>pullboard init</code> in a git repo, or ask an agent to. Its board shows up here by itself.</p>
</section>
<p class="empty" id="project-loading" role="status" hidden>Loading project…</p>
- <section class="card-panel" id="local-note" role="status" hidden>
- <p id="local-note-text"></p>
- <p id="local-note-links" hidden><a id="local-note-view" href="http://127.0.0.1:4890/local/view">Open the local view</a> <a id="local-note-sign-in" hidden>Sign in to see linked boards</a> <button class="ghost" id="local-note-retry" type="button">Try again</button></p>
- </section>
+ ${hostedMarkup('http://127.0.0.1:4890')}
<section class="card-panel snapshot-controls" id="snapshot-controls" ${snapshot ? '' : 'hidden'} aria-label="Snapshot replay">
<span>Read-only snapshot</span>
<button class="ghost" id="replay-play" type="button">Play from first event</button>
@@ -304,14 +307,12 @@ let detailRead = null;
const addressedShouts = new Map();
const $ = (id) => document.getElementById(id);
-/** Say in one line what the page is doing about this machine's view, or why it cannot read it, with the ways on. */
-function localNote(text, ways = false) {
- $('local-note').hidden = !text;
- $('local-note-text').textContent = text || '';
- $('local-note-links').hidden = !ways;
- $('local-note-view').href = (localSession?.origin || LOCAL_VIEW) + '/local/view';
- $('local-note-sign-in').hidden = !hosted.signIn || hosted.relaySession;
- if (hosted.signIn) $('local-note-sign-in').href = hosted.signIn;
+const hostedState = (${hostedState.toString()});
+const hostedBrowser = (${hostedBrowser.toString()});
+const drawHosted = (${drawHosted.toString()});
+/** Show the hosted state the page is in (src/view/hosted.js), with its next step, or none with null. */
+function localNote(state, facts = {}) {
+ drawHosted(document, hostedState(state, { browser: hostedBrowser(navigator), ...facts }), { view: localSession?.origin || LOCAL_VIEW, signIn: hosted.signIn, session: hosted.relaySession });
}
/** Hide the relay's own banner, which speaks for the relay, on a page the relay does not serve this time. */
@@ -325,7 +326,7 @@ function localTrip(base) {
const trips = Number(tabValue(LOCAL_TRIPS) || 0);
if (trips >= 2) {
tabValue(LOCAL_TRIPS, null);
- localNote('The local view did not give this page a session it accepts. Open the local view, or try again.', true);
+ localNote('problem', { detail: 'The local view did not give this page a session it accepts. Open the local view to see its boards.' });
return false;
}
tabValue(LOCAL_TRIPS, String(trips + 1));
@@ -355,24 +356,27 @@ async function connectLocal() {
try { permission = (await navigator.permissions.query({ name })).state; break; } catch { /* this browser has no such permission */ }
}
if (permission === 'denied') {
- localNote('This browser has refused this page access to apps on this device, so it cannot read the board running here. Allow it in the site settings for app.pullboard.dev, or open the local view.', true);
+ localNote('blocked');
return 'unreachable';
}
if (permission !== 'granted') {
- localNote('Your browser may ask to let this page reach apps on this device: allow it, and the page reads the board pullboard view runs here, which never leaves this machine.');
+ localNote('asking');
// The line is on screen before the request that can raise the browser's prompt.
await new Promise((painted) => requestAnimationFrame(() => requestAnimationFrame(painted)));
}
let reply;
try { reply = await fetch(base + '/local/protocol', { signal: AbortSignal.timeout(3000), credentials: 'omit', redirect: 'error' }); }
catch {
- localNote('This page cannot reach a local view: pullboard view may not be running, this browser may have refused it access to this device, or the installed Pullboard may be older than this page. Start pullboard view and try again, or open the link it printed.', true);
+ // A view from before 0.8.29 answers without the header that lets this page read it; an opaque answer still
+ // says something listens there, where a closed port answers nothing at all.
+ const listening = await fetch(base + '/local/protocol', { mode: 'no-cors', signal: AbortSignal.timeout(3000), credentials: 'omit' }).then(() => true, () => false);
+ localNote(listening ? 'too-old' : 'not-running');
return 'unreachable';
}
let protocol = null;
try { protocol = await reply.json(); } catch { /* not this protocol */ }
if (!reply.ok || protocol?.version !== 1 || protocol?.apiVersion !== 1 || protocol?.hostedOrigin !== location.origin) {
- localNote('The installed Pullboard does not match this page. Open the link pullboard view printed, or update Pullboard.', true);
+ localNote('mismatch');
return 'unreachable';
}
if (!localSession) return localTrip(base) ? 'away' : 'unreachable';
@@ -995,7 +999,7 @@ async function listedBoards() {
try { await loadTransport(); } catch { /* Keep the local refusal when neither source can be read. */ }
}
if (!transport) throw error;
- localNote(String(error.message || error), true);
+ localNote('local-failed', { detail: String(error.message || error) });
}
}
if (hosted.local && hasLocal && hosted.relaySession && configuredTransportModule && !transport) {
@@ -1005,14 +1009,14 @@ async function listedBoards() {
const linked = await jsonRequest('/api/v1/boards', undefined, '', {}, 'no-store');
const localIds = new Set((local.boards || []).map(board => board.id));
if (linked.boards?.some(board => typeof board.id === 'string' && /^[0-9a-f]{32}$/.test(board.id) && typeof board.repository === 'string' && !localIds.has(board.id))) await loadTransport();
- } catch (error) { localNote('Linked boards are unavailable: ' + String(error.message || error), true); }
+ } catch (error) { localNote('linked-failed', { detail: String(error.message || error) }); }
}
if (!hasLocal && transportModule && !transport) throw transportLoadError || new Error('The browser transport is still loading.');
if (transport) {
try { relay = await transport.request('/api/v1/boards'); }
catch (error) {
if (!hosted.local || !hasLocal) throw error;
- localNote('Linked boards are unavailable: ' + String(error.message || error), true);
+ localNote('linked-failed', { detail: String(error.message || error) });
}
}
boardSources.clear();
@@ -1027,13 +1031,27 @@ async function listedBoards() {
}
for (const board of relay.boards || []) {
if (typeof board.id !== 'string' || boardSources.has(board.id)) continue;
- const row = { ...board, root: board.id, source: 'relay' };
+ // A linked board reads by its own name, as it does locally, with its owner as a quiet prefix.
+ const [owner, name] = String(board.name || '').includes('/') ? board.name.split('/') : ['', board.name];
+ const row = { ...board, root: board.id, source: 'relay', name, owner };
boardSources.set(row.id, { kind: 'relay', board: row });
boards.push(row);
}
+ if (hosted.local) await hostedListed(boards, hasLocal);
return { version: 1, boards, warnings: [...(local.warnings || []), ...(relay.warnings || [])] };
}
+/** After a hosted board list: a list clears a state it stood in for, and a signed-in empty one says why it is empty. */
+async function hostedListed(boards, hasLocal) {
+ const shown = $('local-note').dataset.state || '';
+ if (boards.length) { if (['not-running', 'no-linked', 'unpaired', 'signed-out'].includes(shown)) localNote(null); return; }
+ if (hasLocal || !hosted.relaySession || !['', 'not-running', 'no-linked', 'unpaired'].includes(shown)) return;
+ let linked;
+ try { linked = await jsonRequest('/api/v1/boards', undefined, '', {}, 'no-store'); } catch { return; /* the relay's banner says why */ }
+ const names = (linked.boards || []).filter((board) => typeof board.repository === 'string').map((board) => board.repository);
+ localNote(names.length ? 'unpaired' : 'no-linked', { linked: names });
+}
+
/** Set presentation controls for the selected board; API routing still checks the target board independently. */
function syncBoardMode(root) {
if (snapshot) return;
@@ -1752,7 +1770,7 @@ function renderSide() {
const on = x.root === view.root;
const parts = doing(x).split(' · '), asks = [x.decisions, x.pending, x.drafts, x.holds].filter(Boolean).length;
const line = x.loading ? 'Loading…' : (asks ? '<span class="asks">' + esc(parts.slice(0, asks).join(' · ')) + '</span>' + (parts.length > asks ? ' · ' : '') : '') + esc(parts.slice(asks).join(' · '));
- return '<button class="proj repo' + (on ? ' on' : '') + '"' + (on ? ' aria-current="true"' : '') + ' data-root="' + esc(x.root) + '" title="' + esc(x.root) + '" type="button"><span class="pname">' + esc(x.name) + '</span><small>' + line + '</small></button>';
+ return '<button class="proj repo' + (on ? ' on' : '') + '"' + (on ? ' aria-current="true"' : '') + ' data-root="' + esc(x.root) + '" title="' + esc(x.root) + '" type="button"><span class="pname">' + (x.owner ? '<span class="owner">' + esc(x.owner) + '/</span>' : '') + esc(x.name) + '</span><small>' + (hosted.local && x.source ? '<span class="src">' + (x.source === 'relay' ? 'linked' : 'this computer') + '</span> · ' : '') + line + '</small></button>';
};
const groupedRoots = new Set(data.groups.flatMap((group) => group.repos.map((repo) => repo.root)));
const grouped = data.groups.map((group) => {
@@ -3501,7 +3519,7 @@ if (hosted.local) $('local-note-retry').addEventListener('click', () => {
tabValue(LOCAL_TRIPS, null);
// Reload both source-scoped connections together when relay streams are already active.
if (transport) { location.reload(); return; }
- connectLocal().then((local) => local === 'local' ? refresh() : null).catch((error) => localNote(error.message, true));
+ connectLocal().then((local) => local === 'local' ? refresh() : null).catch((error) => localNote('problem', { detail: error.message }));
});
/** Load the configured decrypting transport once, only when relay reads or pairing need it. */
let transportLoading = null;
@@ -3525,13 +3543,16 @@ async function loadTransport() {
async function startPage() {
let local = 'unreachable';
if (hosted.local && !relayPairing) {
- if (localProblem) localNote(localProblem, true);
+ if (localProblem) localNote('problem', { detail: localProblem });
else local = await connectLocal();
if (local === 'away') return;
if (local === 'unreachable' && !hosted.relaySession) { hideRelayNotice(); return; }
}
if (hosted.local && local === 'local') transportModule = null;
- else if (configuredTransportModule) await loadTransport();
+ else if (configuredTransportModule) {
+ // Signed out, a pairing link waits for sign-in, which its own state asks for.
+ try { await loadTransport(); } catch (error) { if (!hosted.local || hosted.relaySession) throw error; localNote('signed-out'); return; }
+ }
await refresh();
}
startPage().catch((error) => { document.body.classList.remove('loading'); $('live').textContent = 'cannot reach the view: ' + error.message; });
diff --git a/src/view.css b/src/view.css
index 70967c54..015dfcb7 100644
--- a/src/view.css
+++ b/src/view.css
@@ -135,6 +135,41 @@ main { padding: 16px 18px 56px; }
.first code { font: 600 13px var(--mono); color: var(--ink); }
.boardless .first { display: block; }
.loading .top, .loading [data-pane], .boardless .top, .boardless [data-pane] { display: none; }
+/* The hosted page's states (#749): a card with a heading, one line and the next step, then the Ways in panel. In
+ * place of a board they stand alone in the middle of the page; over a list a note is one quiet card. */
+a { color: var(--accent-strong); text-underline-offset: 2px; }
+a.go, a.ghost { display: inline-flex; align-items: center; text-decoration: none; }
+a.ghost { color: var(--ink); }
+.hosted { display: grid; gap: 14px; margin: 0 0 14px; }
+.loading .hosted, .boardless .hosted, .hosted-state .hosted { max-width: 560px; margin: 10vh auto 56px; }
+.hosted-card { display: grid; gap: 8px; padding: 22px 24px; }
+.hosted h2 { margin: 0; font-size: 18px; }
+.hosted-card p { margin: 0; color: var(--ink-muted); }
+.hosted-card .hosted-hint { color: var(--ink); }
+.hosted-cmd { display: flex; align-items: center; gap: 8px; margin-top: 6px; padding: 5px 5px 5px 12px; border: 1px solid var(--line); border-radius: 8px; background: var(--surface-2); }
+.hosted-cmd code { flex: 1; min-width: 0; overflow-x: auto; font: 600 13px var(--mono); color: var(--ink); white-space: nowrap; }
+.hosted-cmd .ghost { flex: none; padding: 3px 10px; font-size: 12px; }
+.hosted-card .hosted-step { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 6px; }
+.hosted-ways { padding: 16px 24px 6px; }
+.hosted-ways h2 { margin-bottom: 2px; font: 600 11px/1 var(--sans); letter-spacing: .06em; text-transform: uppercase; color: var(--ink-faint); }
+.hosted-ways dl { margin: 0; }
+.way { padding: 10px 0; border-top: 1px solid var(--line); }
+.way:first-child { border-top: 0; }
+.way dt { font-weight: 600; }
+.way dd { margin: 2px 0 0; color: var(--ink-muted); font-size: 13px; }
+.way code { font: 12px var(--mono); color: var(--ink); white-space: nowrap; }
+.way .ghost { display: flex; width: fit-content; margin-top: 8px; }
+.hosted-state .first, .hosted-state #proj-list .empty { display: none; }
+.proj small .src { color: var(--ink-muted); }
+.proj .pname .owner { color: var(--ink-faint); font-weight: 400; }
+.side-hint { margin: 0; padding: 4px 8px; color: var(--ink-faint); font-size: 12.5px; line-height: 1.45; }
+/* The relay's banner, filled by its client: the same quiet card. */
+#relay-notice { display: grid; gap: 6px; margin: 0 0 14px; padding: 14px 16px; }
+#relay-notice p { margin: 0; color: var(--ink-muted); }
+#relay-notice a { justify-self: start; font-weight: 600; }
+.loading #relay-notice, .boardless #relay-notice { max-width: 560px; margin: 10vh auto 14px; }
+.loading #relay-notice:not([hidden]) ~ .hosted, .boardless #relay-notice:not([hidden]) ~ .hosted { margin-top: 0; }
+#pairing-storage-notice { margin: 0 0 14px; padding: 12px 16px; color: var(--ink-muted); }
.two { display: grid; grid-template-columns: minmax(0, 1fr) clamp(300px, 42%, 600px); gap: 16px; align-items: start; }
.two.narrow { grid-template-columns: minmax(0, 1fr) var(--agents-w); }
.roadmap-layout { display: grid; grid-template-columns: minmax(0, 1fr) clamp(260px, 30%, 360px); gap: 16px; align-items: start; }
diff --git a/src/view/hosted.js b/src/view/hosted.js
new file mode 100644
index 00000000..8c5f04c0
--- /dev/null
+++ b/src/view/hosted.js
@@ -0,0 +1,124 @@
+/**
+ * The hosted page's states at https://app.pullboard.dev [N26,H5]. Each state is a heading, one line on what it
+ * means and the one next step, and a short "Ways in" panel lists every route to a board in plain words.
+ * hostedMarkup builds the panel on the server; hostedState, hostedBrowser and drawHosted run in the page, which
+ * inlines them by their source, so each reads nothing beyond its own arguments.
+ */
+
+/** The routes to a board, as the Ways in panel lists them: a title, then one line with its commands. */
+const WAYS_IN = [
+ ['The local view', 'Run <code>pullboard view</code> on the computer that holds your boards. It opens them in a browser tab.'],
+ ['This computer through pullboard.dev', 'While <code>pullboard view</code> runs, this page opens the same boards, and their data stays on this computer.'],
+ ['Your phone and other devices', 'Run <code>pullboard relay on --all</code> to link your boards, then scan the QR it prints and sign in.'],
+ ['A second computer', 'Run <code>pullboard relay pair</code> on this one, then <code>pullboard relay join &lt;code&gt;</code> on the other.'],
+];
+
+/**
+ * The hosted panel's markup: the state card, with its heading, line, command and buttons, and the Ways in panel.
+ * The ids are the ones the page always had (local-note, local-note-text, local-note-links, local-note-view,
+ * local-note-sign-in, local-note-retry), so what reads them keeps working.
+ *
+ * @param {string} localView - The local view's address, the default the page links before it knows another.
+ * @returns {string}
+ */
+export function hostedMarkup(localView) {
+ const ways = WAYS_IN.map(([title, line], n) => `<div class="way"><dt>${title}</dt><dd>${line}${n === 2 ? ' <a class="ghost" id="local-note-sign-in" hidden>Sign in with GitHub</a>' : ''}</dd></div>`).join('');
+ return `<section class="hosted" id="local-note" role="status" hidden>
+ <div class="card-panel hosted-card"><h2 id="local-note-title"></h2><p id="local-note-text"></p><p class="hosted-hint" id="local-note-hint" hidden></p>
+ <div class="hosted-cmd" id="local-note-cmd" hidden><code id="local-note-code"></code><button class="ghost" id="local-note-copy" type="button">Copy</button></div>
+ <p class="hosted-step" id="local-note-links" hidden><a class="go" id="local-note-view" href="${localView}/local/view" hidden>Open the local view</a><a class="go" id="local-note-go" hidden>Sign in with GitHub</a><button class="go" id="local-note-retry" type="button" hidden>Try again</button></p></div>
+ <section class="card-panel hosted-ways" id="ways-in" aria-labelledby="ways-in-title" hidden><h2 id="ways-in-title">Ways in</h2><dl>${ways}</dl></section>
+ </section>`;
+}
+
+/**
+ * Name the browser the page runs in, for the step that lifts its block. Only Chromium browsers answer the
+ * local network permission the page asks about, so they are the ones a block is ever reported from.
+ *
+ * @param {{userAgent?: string, userAgentData?: {brands?: {brand: string}[]}}} agent - The page's navigator.
+ * @returns {string}
+ */
+export function hostedBrowser(agent) {
+ const brands = (agent?.userAgentData?.brands || []).map((entry) => entry.brand).join(' ');
+ const said = brands + ' ' + (agent?.userAgent || '');
+ if (/Edge|Edg\//.test(said)) return 'Edge';
+ if (/Opera|OPR\//.test(said)) return 'Opera';
+ if (/Chrom/.test(said)) return 'Chrome';
+ if (/Firefox\//.test(said)) return 'Firefox';
+ if (/Safari\//.test(said)) return 'Safari';
+ return 'This browser';
+}
+
+/**
+ * What the hosted page says in one state, or null for none. A "state" stands in for the board; a "note" sits
+ * over a list that shows; "wait" is the line on screen while the browser may ask its question.
+ *
+ * @param {string|null} state - asking, not-running, blocked, mismatch, too-old, problem, signed-out, no-linked, unpaired, linked-failed or local-failed.
+ * @param {{browser?: string, linked?: string[], detail?: string}} [facts] - The browser's name, the linked boards this browser cannot open, and a refusal's own words.
+ * @returns {null|{state: string, kind: string, heading: string, text: string, hint?: string, command?: string, button?: string, side?: string}}
+ */
+export function hostedState(state, facts = {}) {
+ const browser = facts.browser || 'This browser';
+ const linked = facts.linked || [];
+ const chromium = ['Chrome', 'Edge', 'Opera'].includes(browser);
+ const models = {
+ 'asking': { kind: 'wait', heading: 'Looking for Pullboard on this computer', text: 'Your browser may ask to let this page reach apps on this device. Allow it to open the boards running here.' },
+ 'not-running': { kind: 'state', heading: 'Start Pullboard on this computer', text: 'This page cannot reach a local view on this computer. Run this in a terminal, then try again.', command: 'pullboard view', button: 'retry', side: 'Boards on this computer show here once pullboard view runs.', offline: 'not connected' },
+ 'blocked': { kind: 'state', heading: 'Let this page reach Pullboard', text: browser + ' has refused this page access to apps on this device, so it cannot open the board running here.',
+ hint: chromium ? 'In ' + browser + ', click the icon at the left of the address bar, turn on Local network access, then try again.' : 'Allow this site to reach apps on this device in the browser\'s site settings, then try again.',
+ button: 'retry', side: 'Boards on this computer show here once ' + (browser === 'This browser' ? 'the browser' : browser) + ' allows it.', offline: 'not connected' },
+ 'mismatch': { kind: 'state', heading: 'Update Pullboard on this computer', text: 'The Pullboard view running here does not match this page. Update Pullboard, restart pullboard view, then try again.', command: 'npm i -g pullboard', button: 'retry', side: 'Boards on this computer show here once the versions match.', offline: 'not connected' },
+ 'too-old': { kind: 'state', heading: 'Update Pullboard on this computer', text: 'Something answered at the local view\'s address without the connection this page needs, as a Pullboard older than 0.8.29 does. Update Pullboard, restart pullboard view, then try again.', command: 'npm i -g pullboard', button: 'retry', side: 'Boards on this computer show here once Pullboard is updated.', offline: 'not connected' },
+ 'problem': { kind: 'state', heading: 'Open the local view', text: facts.detail || 'This page could not take the connection the local view sent back.', button: 'view', side: 'Boards on this computer show in the local view.', offline: 'not connected' },
+ 'signed-out': { kind: 'state', heading: 'Sign in to pair this browser', text: 'This link pairs this browser with your boards. Sign in with GitHub to finish, and they open here.', button: 'sign-in', side: 'Your linked boards show here after you sign in.', offline: 'not signed in' },
+ 'no-linked': { kind: 'state', heading: 'No linked boards yet', text: 'Your account has no linked boards. Link them from the computer that runs them:', command: 'pullboard relay on --all', side: 'Linked boards show here.' },
+ 'unpaired': { kind: 'state', heading: 'Pair this browser', text: 'You are signed in, and your account has ' + (linked.length === 1 ? 'a linked board: ' : 'linked boards: ') + linked.join(', ') + '. Each browser pairs once before it can read ' + (linked.length === 1 ? 'it' : 'them') + '. On the computer that linked ' + (linked.length === 1 ? 'it' : 'them') + ', run this, then open the link it prints here or scan its QR:', command: 'pullboard relay on --all',
+ side: linked.length + (linked.length === 1 ? ' linked board waits' : ' linked boards wait') + ' for this browser to pair.' },
+ 'linked-failed': { kind: 'note', heading: 'Linked boards did not load', text: facts.detail || 'The relay did not answer.', button: 'retry' },
+ 'local-failed': { kind: 'note', heading: 'This computer\'s boards did not load', text: facts.detail || 'The local view did not answer.', button: 'retry' },
+ };
+ const model = state ? models[state] : null;
+ return model ? { state, ...model } : null;
+}
+
+/**
+ * Draw one hosted state into the page, or clear it with null. A state stands in for the board, so it brings the
+ * Ways in panel and a line in the empty sidebar, and the relay's own banner steps aside while it speaks for it.
+ *
+ * @param {Document} doc - The page.
+ * @param {ReturnType<typeof hostedState>} model - What to show.
+ * @param {{view: string, signIn: string|null, session: boolean}} place - The local view's address, the sign-in path and whether the person is signed in.
+ */
+export function drawHosted(doc, model, place) {
+ const $ = (id) => doc.getElementById(id);
+ const full = Boolean(model && model.kind === 'state');
+ const note = $('local-note');
+ note.hidden = !model;
+ note.dataset.state = model ? model.state : '';
+ doc.body.classList.toggle('hosted-state', full);
+ $('local-note-title').textContent = model ? model.heading : '';
+ $('local-note-text').textContent = model ? model.text : '';
+ $('local-note-hint').hidden = !model?.hint;
+ $('local-note-hint').textContent = model?.hint || '';
+ if (full && model.offline) $('live').textContent = model.offline;
+ $('local-note-cmd').hidden = !model?.command;
+ $('local-note-code').textContent = model?.command || '';
+ const copy = $('local-note-copy');
+ copy.textContent = 'Copy';
+ copy.onclick = () => navigator.clipboard?.writeText(model.command).then(() => { copy.textContent = 'Copied'; }, () => { copy.textContent = 'Select and copy'; });
+ const button = model?.button;
+ $('local-note-links').hidden = !button;
+ $('local-note-view').hidden = button !== 'view';
+ $('local-note-view').href = place.view + '/local/view';
+ $('local-note-go').hidden = button !== 'sign-in' || !place.signIn;
+ $('local-note-retry').hidden = button !== 'retry';
+ $('local-note-sign-in').hidden = !place.signIn || place.session;
+ for (const link of [$('local-note-go'), $('local-note-sign-in')]) if (place.signIn) link.href = place.signIn;
+ $('ways-in').hidden = !full;
+ $('side-hint').hidden = !full || !model.side;
+ $('side-hint').textContent = full ? model.side || '' : '';
+ // The relay's banner says what the state now says; it comes back when the state goes.
+ const banner = $('relay-notice');
+ if (banner && full && ['signed-out', 'no-linked', 'unpaired'].includes(model.state)) { banner.hidden = true; banner.dataset.hostedHid = '1'; }
+ else if (banner && banner.dataset.hostedHid && !full) { banner.hidden = false; delete banner.dataset.hostedHid; }
+}
diff --git a/test/cockpit/local-origin.test.js b/test/cockpit/local-origin.test.js
index 17053e8a..05ae93f7 100644
--- a/test/cockpit/local-origin.test.js
+++ b/test/cockpit/local-origin.test.js
@@ -7,7 +7,9 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { test } from 'node:test';
import { cockpitPage } from '../../src/cockpit.js';
-import { BIN, machine, project, startView, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, styleOf } from './fixture.js';
+import { Refused } from '../../src/refused.js';
+import { createRelayBrowserHandler } from '../../relay/browser-page.js';
+import { BIN, machine, project, startView, chromeExecutable, openSnapshotChrome, closeSnapshotChrome, styleOf, proofShot } from './fixture.js';
const HOSTED = 'https://app.pullboard.dev';
const LOCAL = 'http://127.0.0.1:4890';
@@ -322,6 +324,160 @@ test('a foreign origin or wrong Host is refused by the local view [N26,A2]', { t
}
});
+test('every hosted page state says what it is and what to do next [N26,H5]', { timeout: 120_000 }, async () => { // budget: hang ceiling for six hosted page loads in Chrome, one with a real round trip.
+ const executable = chromeExecutable();
+ assert.ok(executable, 'the hosted page check needs real Chrome');
+ const box = machine();
+ const board = project(box, 'hosted-states');
+ box.run(board.repo, 'add', 'web', 'A board the hosted page lists', '--specs', 'G1');
+ const profile = mkdtempSync(join(tmpdir(), 'pullboard-hosted-states-'));
+ const relay = createRelayBrowserHandler({ authenticate: async () => { if (stand.signedIn) return { kind: 'session' }; throw new Refused('AUTH_REQUIRED', 'Sign in.'); } });
+ // What the stand-in answers: the relay's real page and assets, a relay client that has paired no board, the
+ // account's linked boards, and this machine's default view address, closed unless the test names a view.
+ const stand = { signedIn: false, linked: [], local: null };
+ const client = 'export function rememberPairing() { return null; }\nexport async function createTransport() { return { async request(path) { if (path === "/api/v1/boards") return { version: 1, boards: [], warnings: [] }; throw new Error("no paired board"); } }; }\n';
+ let view, chrome, listener, old;
+ const failures = [];
+ try {
+ view = await startView(box);
+ chrome = await openSnapshotChrome(executable, 'about:blank', profile);
+ listener = ({ data }) => {
+ const message = JSON.parse(String(data));
+ if (message.method !== 'Fetch.requestPaused') return;
+ const { requestId, request: asked } = message.params;
+ const address = new URL(asked.url);
+ const fulfil = (type, body, headers = []) => chrome.send('Fetch.fulfillRequest', { requestId, responseCode: 200, responseHeaders: [{ name: 'Content-Type', value: type }, { name: 'Cache-Control', value: 'no-store' }, ...headers], body: Buffer.from(body).toString('base64') });
+ (async () => {
+ if (address.origin === LOCAL) {
+ if (!stand.local) return chrome.send('Fetch.failRequest', { requestId, errorReason: 'ConnectionRefused' });
+ const reply = await call({ base: stand.local }, address.pathname + address.search, { method: asked.method, headers: Object.fromEntries(Object.entries(asked.headers).filter(([name]) => name.toLowerCase() !== 'host')) });
+ return chrome.send('Fetch.fulfillRequest', { requestId, responseCode: reply.status, responseHeaders: Object.entries(reply.headers).filter(([name]) => !['content-length', 'transfer-encoding', 'connection', 'keep-alive', 'date'].includes(name)).map(([name, value]) => ({ name, value: String(value) })), body: Buffer.from(reply.body).toString('base64') });
+ }
+ if (address.pathname === '/relay/client.js') return fulfil('text/javascript', client);
+ if (address.pathname === '/api/v1/boards') return fulfil('application/json', JSON.stringify({ version: 1, boards: stand.linked, warnings: [] }));
+ let head = {}, body = '';
+ const handled = await relay({ method: 'GET', url: address.pathname, headers: {} }, { writeHead: (status, headers) => { head = headers; }, end: (content) => { body = content ?? ''; } });
+ if (!handled) return chrome.send('Fetch.failRequest', { requestId, errorReason: 'Failed' });
+ // The relay's own policy, which also lets the page reach the test view's own port the round trip names.
+ const policy = head['content-security-policy'].replace("connect-src 'self'", "connect-src 'self' " + view.base);
+ return fulfil(head['content-type'], body, [{ name: 'Content-Security-Policy', value: policy }]);
+ })().catch((error) => failures.push(error.message));
+ };
+ chrome.socket.addEventListener('message', listener);
+ await chrome.send('Fetch.enable', { patterns: [{ urlPattern: HOSTED + '/*', requestStage: 'Request' }, { urlPattern: LOCAL + '/*', requestStage: 'Request' }] });
+ // A browser that has refused this page its local network permission, as Chrome reports it.
+ await chrome.send('Page.addScriptToEvaluateOnNewDocument', { source: `(() => {
+ if (location.origin !== ${JSON.stringify(HOSTED)} || location.search !== '?blocked') return;
+ const query = navigator.permissions.query.bind(navigator.permissions);
+ navigator.permissions.query = (asked) => ['loopback-network', 'local-network-access'].includes(asked?.name) ? Promise.resolve({ state: 'denied' }) : query(asked);
+ })()` });
+ const shown = `JSON.stringify((() => {
+ const on = (element) => Boolean(element) && !element.hidden && element.getClientRects().length > 0;
+ const text = (id) => on(document.getElementById(id)) ? document.getElementById(id).textContent.trim() : null;
+ const probe = document.body.appendChild(document.createElement('span'));
+ const tokens = ['--accent-strong', '--ink', '--ink-muted', '--surface'].map((token) => { probe.style.color = 'var(' + token + ')'; return getComputedStyle(probe).color; });
+ probe.remove();
+ return {
+ state: document.getElementById('local-note').dataset.state, heading: text('local-note-title'), text: text('local-note-text'), hint: text('local-note-hint'), command: text('local-note-code'),
+ steps: [...document.querySelectorAll('#local-note-links a, #local-note-links button')].filter(on).map((step) => [step.textContent.trim(), step.getAttribute('href')]),
+ ways: on(document.getElementById('ways-in')) ? [...document.querySelectorAll('#ways-in dt')].map((title) => title.textContent) : null,
+ waysText: text('ways-in'), side: document.getElementById('side-hint').hidden ? null : document.getElementById('side-hint').textContent, banner: on(document.getElementById('relay-notice')), browser: hostedBrowser(navigator),
+ defaults: [...document.querySelectorAll('*')].filter((element) => ['rgb(0, 0, 238)', 'rgb(85, 26, 139)'].includes(getComputedStyle(element).color)).map((element) => element.outerHTML.slice(0, 80)),
+ bare: [...document.querySelectorAll('a')].filter((link) => on(link) && !link.className && !tokens.includes(getComputedStyle(link).color)).map((link) => link.outerHTML.slice(0, 80)),
+ };
+ })())`;
+ /** Open the hosted page at this address and read the state it settles in. */
+ const open = async (address, state) => {
+ await chrome.send('Page.navigate', { url: HOSTED + '/' + address });
+ await chrome.waitFor(`location.search === ${JSON.stringify(address.split('#')[0])} && document.querySelector('#local-note')?.dataset.state === ${JSON.stringify(state)} && !document.querySelector('#local-note').hidden`, 20_000); // budget: hang ceiling for one refused loopback request and an empty relay list.
+ const seen = JSON.parse(await chrome.stable(shown));
+ await proofShot(chrome, 'hosted-' + state + '-phone', 390);
+ await proofShot(chrome, 'hosted-' + state, 1280);
+ assert.deepEqual(seen.defaults, [], `${state}: no element keeps the browser's default link colours`);
+ assert.deepEqual(seen.bare, [], `${state}: every link has a class or the view's colours`);
+ assert.deepEqual(seen.ways, ['The local view', 'This computer through pullboard.dev', 'Your phone and other devices', 'A second computer'], `${state}: the Ways in panel lists every route`);
+ for (const command of ['pullboard view', 'pullboard relay on --all', 'pullboard relay pair', 'pullboard relay join <code>']) assert.ok(seen.waysText.includes(command), `${state}: Ways in names ${command}`);
+ assert.ok(seen.side, `${state}: the empty sidebar says what fills it`);
+ return seen;
+ };
+ const retry = [['Try again', null]];
+
+ const blocked = await open('?blocked', 'blocked');
+ assert.equal(blocked.heading, 'Let this page reach Pullboard');
+ assert.match(blocked.text, new RegExp('^' + blocked.browser + ' has refused this page access to apps on this device'), 'the line names the browser and what it refused');
+ assert.equal(blocked.browser, 'Chrome', 'the fixture Chrome is named as Chrome');
+ assert.match(blocked.hint ?? '', /^In Chrome, click the icon at the left of the address bar, turn on Local network access, then try again\.$/, 'the step is the one for this browser');
+ assert.deepEqual(blocked.steps, retry, 'and its button tries again');
+
+ const absent = await open('?absent', 'not-running');
+ assert.equal(absent.heading, 'Start Pullboard on this computer');
+ assert.match(absent.text, /cannot reach a local view on this computer/);
+ assert.equal(absent.command, 'pullboard view', 'the next step is the command that starts the local view');
+ assert.deepEqual(absent.steps, retry);
+ assert.equal(await chrome.stable("document.querySelector('#local-note-copy').textContent"), 'Copy', 'the command has a copy button');
+ assert.equal(absent.banner, false, 'the relay\'s banner stays out of it');
+
+ const out = await open('?out#board=' + 'b'.repeat(32) + '&key=k1', 'signed-out');
+ assert.equal(out.heading, 'Sign in to pair this browser');
+ assert.deepEqual(out.steps, [['Sign in with GitHub', '/auth/github/start']], 'the next step is signing in');
+ assert.equal(out.banner, false, 'the state speaks for the relay\'s banner');
+
+ stand.signedIn = true;
+ const none = await open('?in', 'no-linked');
+ assert.equal(none.heading, 'No linked boards yet');
+ assert.equal(none.command, 'pullboard relay on --all', 'the next step links the boards');
+ assert.equal(none.banner, false);
+ assert.equal(await chrome.stable("document.querySelector('#local-note-sign-in').hidden"), true, 'a signed-in person is not asked to sign in');
+
+ stand.linked = [{ id: 'a'.repeat(32), repository: 'acme/web', linkedAt: 0 }];
+ const unpaired = await open('?linked', 'unpaired');
+ assert.equal(unpaired.heading, 'Pair this browser');
+ assert.match(unpaired.text, /^You are signed in, .*acme\/web\. Each browser pairs once before it can read it\..*scan its QR:$/, 'the line says the person is signed in, names the board, that each browser pairs once, and the QR');
+ assert.equal(unpaired.command, 'pullboard relay on --all', 'the next step prints the QR');
+
+ // This machine's view: the normal list, with no state over it.
+ stand.signedIn = false;
+ stand.linked = [];
+ stand.local = view.base;
+ // The person allowed this page to reach this device, under whichever permission names this Chrome knows.
+ for (const permissions of [['loopbackNetwork', 'localNetwork', 'localNetworkAccess'], ['localNetworkAccess']]) {
+ try { await chrome.send('Browser.grantPermissions', { origin: HOSTED, permissions }); break; } catch { /* a name this Chrome does not have */ }
+ }
+ // A view from before 0.8.29 refuses the hosted page without the header that would let it read the refusal.
+ old = createServer((req, res) => { res.writeHead(403, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: 'this view needs its own address and secret: open the link pullboard view printed' })); });
+ await new Promise((ready) => old.listen(0, '127.0.0.1', ready));
+ stand.local = 'http://127.0.0.1:' + old.address().port;
+ const outdated = await open('?old', 'too-old');
+ assert.equal(outdated.heading, 'Update Pullboard on this computer', 'an old view is told apart from none');
+ assert.equal(outdated.command, 'npm i -g pullboard', 'the next step updates Pullboard');
+ assert.deepEqual(outdated.steps, retry);
+ stand.local = view.base;
+ await chrome.send('Page.navigate', { url: HOSTED + '/?list' });
+ await chrome.waitFor("location.origin === 'https://app.pullboard.dev' && document.querySelector('#chain')?.textContent.includes('A board the hosted page lists')", 30_000); // budget: hang ceiling for the discovery, one round trip and the first board read.
+ const list = JSON.parse(await chrome.stable(`JSON.stringify({ note: document.querySelector('#local-note').hidden, ways: document.querySelector('#ways-in').hidden, heading: document.querySelector('#proj-list .proj.on .pname')?.textContent, source: document.querySelector('#proj-list .proj.on .src')?.textContent, tab: document.querySelector('.tab.on')?.textContent, step: document.querySelector('#new-item').getClientRects().length > 0, side: document.querySelector('#side-hint').hidden, state: JSON.parse(${shown}) })`));
+ await proofShot(chrome, 'hosted-list-phone', 390);
+ await proofShot(chrome, 'hosted-list', 1280);
+ assert.deepEqual({ note: list.note, ways: list.ways, side: list.side }, { note: true, ways: true, side: true }, 'the list shows with no state, panel or hint over it');
+ assert.equal(list.heading, 'hosted-states', 'the sidebar names the board shown');
+ assert.equal(list.source, 'this computer', 'with a quiet label for where it comes from');
+ assert.equal(list.tab, 'Items', 'its items are open');
+ assert.equal(list.step, true, 'and the next step is a new item');
+ assert.deepEqual(list.state.defaults, [], 'no element keeps the browser\'s default link colours');
+ assert.deepEqual(list.state.bare, [], 'every link has a class or the view\'s colours');
+ assert.deepEqual(chrome.exceptions, [], 'Chrome reports no uncaught exceptions');
+ } finally {
+ try { if (chrome) { if (listener) chrome.socket.removeEventListener('message', listener); await closeSnapshotChrome(chrome); } }
+ finally {
+ try { if (old) await new Promise((closed) => { old.close(closed); old.closeAllConnections(); }); }
+ finally {
+ try { if (view) await view.stop(); }
+ finally { rmSync(profile, { recursive: true, force: true }); }
+ }
+ }
+ }
+ assert.deepEqual(failures, [], 'the stand-in hosted page was served');
+});
+
test('the local view hands its secret only to the hosted page [N26,A2]', { timeout: 60_000 }, async () => { // budget: hang ceiling for one real view and a few local requests.
const box = machine();
project(box, 'local-origin-handoff');