Files
alzeo/dashboard/static/js/agent.js
T
Hasan BasbunarandClaude Opus 5.5 026d6004b0 cockpit: a login's Origin over plain HTTP, [::1] sent on to localhost, and its key to its own cockpit alone
A browser sends no Sec-Fetch header over plain HTTP to a tailnet or a LAN address, the cockpit's own case: its Origin has to
be the host it asked there. A content policy has no name for an IPv6 address, so nothing of the Agent view opened at [::1]:
the cockpit sends on to localhost. On a pair, the proxy asks what answers on the loopback to prove it is this box's cockpit
before it logs in: an ssh tunnel to the other box's held that port and got this box's key. The banner of a cockpit that does
not answer says nothing of the loopback's IPv6 address. (review of v1.60.0)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:12:08 +01:00

282 lines
20 KiB
JavaScript

"use strict";
/* Agent: opencode's own web interface, framed from the relay behind this login.
The relay lives on this same host (cookies ignore ports), so the frame carries the
cockpit session and opencode never asks for its own password. The frame is created
the first time the view opens and then kept: leaving the view must not lose a session.
Nothing is framed before this cockpit's own relay has answered this browser. A port that
nothing answers at is a grey screen (the cockpit opened by localhost on the box's own display,
2026-11-30), and at the end of a tunnel a port can be another program's, framed in opencode's
place and given the session. Out of reach, the view says why and what opens it. */
const AG = {mounted: false, wasReady: null,
door: null, // open, session, other or closed: what the last look found
url: null, id: null, at: 0, asking: false};
const AG_AGAIN_MS = 5000, AG_WAIT_MS = 4000;
// An explicit fullscreen choice wins on every device; with none stored, a hand-held
// viewport gets fullscreen, where the head above the frame is a third of the screen.
// The choice made on this page holds even where storage throws (private mode).
let agentMaxChoice = null;
function verCmp(a, b){
const x = String(a).split('.').map(Number), y = String(b).split('.').map(Number);
for (let i = 0; i < Math.max(x.length, y.length); i++){ const d = (x[i] || 0) - (y[i] || 0); if (d) return d; }
return 0;
}
function agentMaxDefault(){
if (agentMaxChoice !== null) return agentMaxChoice;
let pref = null;
try { pref = localStorage.getItem('cockpit.agent.max'); } catch { /* storage may be unavailable */ }
if (pref === '1') return true;
if (pref === '0') return false;
return window.matchMedia('(max-width:980px)').matches;
}
const agentReady = () => !!(F.agent && F.agent.enabled && F.agent.relay && F.agent.relay.listening && F.agent.server && F.agent.server.healthy);
const agentPage = () => Number(location.port) || (location.protocol === 'https:' ? 443 : 80);
// Where this page may look for the relay, as its policy allows (cockpit.py, relay_sources): on the host name it was
// opened by, which the session is kept for, the relay's own port, then the port after the page's when a tunnel or a
// proxy shows the cockpit on another than its own.
function agentUrls(){
const d = F.agent, own = (d.cockpit || {}).port, page = agentPage(), ports = [d.relay.port];
if (own && page !== own && page < 65535 && page + 1 !== d.relay.port) ports.push(page + 1);
return ports.map(p => `${location.protocol}//${location.hostname}:${p}/`);
}
async function agentFetch(url, init, read){
const stop = new AbortController(), t = setTimeout(() => stop.abort(), AG_WAIT_MS);
try { return await read(await fetch(url, {cache: 'no-store', signal: stop.signal, ...init})); }
catch { return null; } finally { clearTimeout(t); }
}
const agentAsk = (url, credentials) => agentFetch(url + '__cockpit/relay', {credentials}, async r => r.ok ? await r.json() : {});
// an answer of any kind, read or not: what is there is no relay of this cockpit's
const agentAnyone = url => agentFetch(url, {mode: 'no-cors', credentials: 'omit'}, () => true);
async function agentLook(){
const id = F.agent.relay.id;
AG.asking = true; AG.at = Date.now(); AG.id = id;
let door = 'closed', url = null;
for (const u of agentUrls()){
const who = await agentAsk(u, 'omit'); // who it is first: the session goes to no other program
if (who && who.relay === id){
const me = await agentAsk(u, 'include');
door = me && me.relay === id && me.session ? 'open' : 'session'; url = u;
break;
}
if (door === 'closed' && (who || await agentAnyone(u))) door = 'other';
}
// a session past its 12 h while the page stayed open: the event stream it opened goes on, the relay refuses it
const ended = door === 'session' && await agentFetch('/api/actions', {}, r => r.status === 401);
AG.asking = false; AG.door = door; AG.url = url;
if (ended) return login();
if (door === 'open' && activeView === 'agent') mountAgent();
if (F.agent) agentRender(F.agent);
}
// The frame, as soon as the relay answers this browser; asked again while it does not.
function agentSeek(){
if (!agentReady() || AG.mounted || AG.asking || activeView !== 'agent') return;
const id = F.agent.relay.id;
if (!id) mountAgent(); // a cockpit process older than this page cannot say whose relay answers
else if (AG.id !== id || Date.now() - AG.at >= AG_AGAIN_MS) agentLook();
}
function agentMessage(text, cmd, ways = []){
show('ag-msg', true); setText('ag-msg-text', text);
const c = $('ag-cmd'); c.hidden = !cmd; if (cmd) c.textContent = cmd;
const list = $('ag-ways'), sig = JSON.stringify(ways);
list.hidden = !ways.length; $('ag-msg').classList.toggle('ways', ways.length > 0);
if (list.dataset.sig === sig) return; // drawn when it changes: a selection in it outlives a refresh
list.dataset.sig = sig; clear(list);
ways.forEach(w => {
const li = el('li'); li.append(el('p', null, w.say));
if (w.href){ const a = el('a', null, w.href); a.href = w.href; li.append(a); }
if (w.cmd){
const pre = el('pre', 'cmd', w.cmd), btn = el('button', 'icon-btn copy-icon'), box = el('div', 'copy-field');
btn.type = 'button'; wireCopyButton(btn, w.cmd, 'Copy the command');
box.append(pre, btn); li.append(box);
}
list.append(li);
});
}
// Why the relay is out of this browser's reach, and what opens it: [sentence, ways]. The server says where the page's
// own requests arrive (here) and where the relay listens; the look says what this browser gets there.
const agentLoop = h => h === 'localhost' || h === '[::1]' || h === '::1' || /^127(\.\d{1,3}){3}$/.test(h);
const agentPortWays = R => [{say: 'To see which program holds the port, on the box:', cmd: `sudo ss -ltnp 'sport = :${R}'`},
{say: 'Or give the relay another port, on the box:', cmd: `cd ${(F.config || {}).repo_dir || '~/dgx-spark-qwen38'} && AGENT_PORT=${R + 100} dashboard/install-agent.sh`}];
const agentAnd = xs => xs.length > 1 ? xs.slice(0, -1).join(', ') + ' and ' + xs[xs.length - 1] : xs.join('');
function agentWhy(){
const d = F.agent, r = d.relay, c = d.cockpit || {}, here = F.here || {}, list = r.listeners || [];
const R = r.port, P = c.port, host = location.hostname, page = agentPage();
const up = list.filter(l => l.listening).map(l => l.addr), hears = a => up.includes(a) || up.includes('0.0.0.0');
const local = here.local || host, onLoop = agentLoop(local), url = h => `http://${h}:${P}/#agent`;
const screen = {say: 'On the box\'s own screen:', href: url('localhost')};
const nets = up.filter(a => !agentLoop(a) && a !== '0.0.0.0' && a !== local && (c.bind === '0.0.0.0' || c.bind === a))
.map(a => ({say: isTailnet(a) ? 'From a device on your tailnet:' : 'From a device on that network:', href: url(a)}));
// the two ports of the box on two ports of the computer the browser is on, where this page then looks for the relay
const ssh = (from, to) => `ssh -N -L ${from}:127.0.0.1:${P} -L ${from === P ? R : from + 1}:127.0.0.1:${R} ${c.user}@${to}`;
const over = (to, from = P) => ({say: `From this computer, through SSH: run this on it, leave it open, and go to http://localhost:${from}/#agent`, cmd: ssh(from, to)});
const carry = `Have it carry the agent's relay too: ${location.protocol}//${host}:${page + 1} to http://127.0.0.1:${R}, with WebSocket, and the Host header as it came.`;
if (AG.door === 'session') return ['The agent\'s relay answers here, and your session does not reach it: this browser keeps the cookie of this page from the port beside it.',
[{say: 'Open the agent in a tab of its own:', href: AG.url}]];
if (location.protocol === 'https:') return [`This page came over https, and a browser frames nothing that comes over http inside it: the agent's relay has to come over https too, and nothing answers for it at ${host}.`,
[{say: carry.replace('Have it', 'Have the proxy that serves this page'), cmd: host.endsWith('.ts.net') ? `tailscale serve --bg --https=${page + 1} http://127.0.0.1:${R}` : null}, ...nets, screen]];
const mine = list.find(l => l.addr === local && !l.listening);
if (mine) return [`The agent's relay cannot listen where you came: ${mine.error}.`, [...agentPortWays(R), ...nets]];
if (onLoop && !hears(local)) return [`You opened the cockpit at ${local}, where the agent's relay does not listen: another address of the box's own loopback.`,
[{say: 'Here, by localhost:', href: url('localhost')}, ...nets]];
if (onLoop && agentLoop(host)) return AG.door === 'other'
? [`You came through a tunnel, and what answers at ${host}:${R} on this computer is another program, not this cockpit's relay.`,
[over(c.host, page === P + 1000 ? P + 2000 : P + 1000), ...nets]]
: ['You came through a tunnel, and it carries the cockpit\'s port alone: the agent\'s relay has one of its own.',
[{say: 'Run this beside your tunnel, with its user and host, and leave it open. The agent then opens here by itself.',
cmd: `ssh -N -L ${page === P ? R : page + 1}:127.0.0.1:${R} ${c.user}@${c.host}`},
...(page === P ? [{say: `With NVIDIA Sync: Settings, Custom, Add New, port ${R}.`}] : []), ...nets]];
if (onLoop) return [`You came through a proxy at ${host}, and it carries the cockpit alone.`, [{say: carry}, ...nets, screen]];
if (hears(local)) return [`The agent's relay listens on ${local}:${R}, and this browser gets no answer from it: a firewall, or an access rule of the tailnet, lets port ${P} through and not ${R}.`,
[{say: `Let TCP port ${R} through as ${P} is. With ufw, on the box:`, cmd: `sudo ufw allow ${R}/tcp`}, over(host), screen]];
const onBox = here.peer === here.local;
return [`The agent runs commands on the box, so its relay answers only on ${agentAnd(up.some(a => a !== '::1') ? up.filter(a => a !== '::1') : up)}, and you opened the cockpit at ${host === local ? host : `${host} (${local})`}. docs/cockpit.md says how to give it another address.`,
[...(onBox ? [{say: 'You are on the box itself. Here, by localhost:', href: url('localhost')}] : []), ...nets, ...(onBox ? [] : [over(host), screen])]];
}
function mountAgent(){
if (!agentReady()) return;
if (!AG.mounted){
const f = document.createElement('iframe');
f.id = 'ag-iframe'; f.title = 'opencode'; f.src = AG.url || agentUrls()[0];
f.setAttribute('allow', 'clipboard-read; clipboard-write'); f.setAttribute('referrerpolicy', 'no-referrer');
$('ag-frame').append(f); $('ag-frame').classList.add('mounted'); AG.mounted = true;
if (activeView === 'agent') fitAgentFrame(); // once, when the frame first exists: never on a refresh
}
show('ag-msg', false);
}
// The frame loads again where the relay answers now; where it no longer does, the reason takes its place.
async function reloadAgent(){
if (!agentReady() || AG.asking) return;
if (F.agent.relay.id) await agentLook();
const f = $('ag-iframe');
if (!f) return agentSeek();
if (!F.agent.relay.id || AG.door === 'open'){ f.src = AG.url || agentUrls()[0]; return; }
f.remove(); $('ag-frame').classList.remove('mounted', 'fitted'); AG.mounted = false;
setAgentMax(false, false); agentRender(F.agent);
}
// Never cover the reason the panel is empty: fullscreen over an explanation is a blank screen.
function applyAgentMax(){
if (!agentMaxDefault() || document.body.classList.contains('agentmax')) return;
if (!agentReady() || !AG.mounted || !$('ag-msg').hidden) return;
setAgentMax(true, false);
}
// The inline frame fills the screen below where it really starts, so opencode's composer,
// at its foot, is on screen. It was sized on a guess of 150 px above it, which left the
// composer under the fold on a phone, a tablet and a laptop (2026-09-30). When too little
// room is left under the view's buttons (a phone on its side), the frame is a screen tall
// and the page brings it under the head instead.
function fitAgentFrame(scroll = true){
const f = $('ag-frame');
if (!f || !f.classList.contains('mounted') || document.body.classList.contains('agentmax') || activeView !== 'agent') return;
const vh = window.innerHeight, head = $('spine').getBoundingClientRect().height;
const top = f.getBoundingClientRect().top + window.scrollY, room = Math.floor(vh - top - 16);
f.classList.add('fitted');
if (room >= vh * 0.6){ f.style.setProperty('--agh', room + 'px'); return; }
f.style.setProperty('--agh', Math.max(200, Math.floor(vh - head - 32)) + 'px');
if (scroll && f.scrollIntoView) f.scrollIntoView({block: 'start'});
}
function setAgentMax(on, persist = true){
document.body.classList.toggle('agentmax', on);
const b = $('ag-max'); if (b){ setText(b, on ? 'Exit fullscreen' : 'Fullscreen'); b.setAttribute('aria-pressed', String(on)); }
if (on) agexitPlace(); else if (activeView === 'agent') fitAgentFrame();
if (persist){ agentMaxChoice = on; try { localStorage.setItem('cockpit.agent.max', on ? '1' : '0'); } catch { /* private mode */ } }
}
function agentRender(d){
if (!d.enabled){
cap('ag-cap', 'not installed', '');
setText('ag-line', 'One install on the box adds opencode here, behind this login.');
['ag-open', 'ag-reload', 'ag-max', 'ag-restart'].forEach(id => show(id, false));
if (d.opencode_found === null) agentMessage(`opencode is not installed on this box, and this view runs it. On the box, re-run the installer: it installs the opencode this repo tests${d.pinned ? ` (${d.pinned})` : ''}, then this view.`,
((F.config || {}).terminal_only || {}).update_stack || 'cd ~/dgx-spark-qwen38 && ./install.sh');
else agentMessage('The Agent view is not installed on this cockpit. opencode is on the box; to add the view, run on the box:', ((F.config || {}).terminal_only || {}).install_agent || 'dashboard/install-agent.sh');
badge('agent', '', ''); return;
}
const r = d.relay || {}, sv = d.server || {}, u = d.unit || {};
const ready = agentReady(), unitOn = u.active === 'active', shut = ready && !AG.mounted && AG.id === r.id && AG.door && AG.door !== 'open';
const [txt, kind] = !ready ? (!r.listening ? ['relay waiting', 'warn'] : !unitOn ? [u.active === 'failed' ? 'server failed' : 'server stopped', 'err'] : ['server starting', 'warn'])
: AG.mounted ? ['ready', 'ok'] : shut ? ['out of reach', 'warn'] : ['reaching the relay', ''];
cap('ag-cap', txt, kind, AG.mounted && ready ? true : 'live');
const parts = [];
if (sv.version) parts.push('opencode ' + sv.version);
if (d.binary && sv.version && d.binary !== sv.version) parts.push(`binary ${d.binary} installed, restart to serve it`);
if (d.pinned && sv.version && sv.version !== d.pinned) parts.push(verCmp(sv.version, d.pinned) < 0 ? `this repo tests ${d.pinned}: ./install.sh brings it in line` : `newer than the ${d.pinned} this repo tests`);
if (d.auto_live != null) parts.push(d.auto_live ? 'tool calls run without asking' : 'asks before risky tool calls');
if (d.guard_ok === false) parts.push('the exfiltration guard is NOT in force on the server');
if (d.auto != null && d.auto_live != null && d.auto !== d.auto_live) parts.push('permission mode changed in the unit, restart to apply');
if (!ready && unitOn && sv.error) parts.push(sv.error);
setText('ag-line', parts.join(', '));
const framed = ready && AG.mounted;
show('ag-open', framed); show('ag-reload', framed); show('ag-max', framed); show('ag-restart', !!d.unit_installed);
if (framed) $('ag-open').href = AG.url || agentUrls()[0];
if (ready){
if (AG.wasReady === false && AG.mounted) reloadAgent(); // the server came back
if (AG.mounted) show('ag-msg', false);
else if (shut){ const [why, ways] = agentWhy(); agentMessage(why, null, ways); }
else agentMessage('Reaching the agent\'s relay from this browser…');
if (activeView === 'agent') applyAgentMax();
} else {
agentMessage(!r.listening ? `The relay is not listening yet: ${r.error || 'waiting for its address'}.`
: !unitOn ? `The opencode server is ${u.active === 'failed' ? 'failed' : 'stopped'}. Restart it from here or read its journal in Logs.`
: `The opencode server is not answering yet${sv.error ? ` (${sv.error})` : ''}. The panel reconnects by itself.`, null,
!r.listening && /cannot bind/.test(r.error || '') ? agentPortWays(r.port) : []);
}
AG.wasReady = ready;
badge('agent', ready ? '' : 'down', 'err');
}
on('agent', d => { agentSeek(); agentRender(d); });
onShow('agent', () => { agentSeek(); if (F.agent) agentRender(F.agent); applyAgentMax(); fitAgentFrame(); });
// The back button floats where the person parks it; the place is a fraction of the
// frame, so a rotation keeps it on the same side. A drag is never a click.
const AGEXIT_KEY = 'cockpit.agent.exitpos';
function agexitPlace(){
const b = $('ag-exit'), f = $('ag-frame'); if (!f) return;
let p = null; try { p = JSON.parse(localStorage.getItem(AGEXIT_KEY)); } catch { /* unparseable: the default */ }
if (!p || !(p.x >= 0 && p.x <= 1) || !(p.y >= 0 && p.y <= 1)){ b.style.left = b.style.top = b.style.right = b.style.transform = ''; return; }
const fr = f.getBoundingClientRect(), w = b.offsetWidth || 160, h = b.offsetHeight || 32;
b.style.transform = 'none'; b.style.right = 'auto';
b.style.left = Math.max(6, Math.min(fr.width - w - 6, p.x * fr.width)) + 'px';
b.style.top = Math.max(6, Math.min(fr.height - h - 6, p.y * fr.height)) + 'px';
}
function wireAgent(){
$('ag-reload').addEventListener('click', reloadAgent);
$('ag-max').addEventListener('click', () => setAgentMax(!document.body.classList.contains('agentmax')));
$('ag-restart').addEventListener('click', () => askAction('unit', {verb: 'restart', unit: AGENT_UNIT},
['A generation in flight in the agent is lost; the panel reconnects when the server is back.']));
let start = null, moved = false;
const exit = $('ag-exit');
exit.addEventListener('pointerdown', e => {
if (e.pointerType === 'mouse' && e.button !== 0) return;
const r = exit.getBoundingClientRect(), fr = $('ag-frame').getBoundingClientRect();
start = {x: e.clientX, y: e.clientY, ox: r.left - fr.left, oy: r.top - fr.top, w: r.width, h: r.height}; moved = false;
exit.setPointerCapture(e.pointerId);
});
exit.addEventListener('pointermove', e => {
if (!start) return;
const dx = e.clientX - start.x, dy = e.clientY - start.y;
if (!moved && Math.hypot(dx, dy) < 6) return;
moved = true; const fr = $('ag-frame').getBoundingClientRect();
exit.style.transform = 'none'; exit.style.right = 'auto';
exit.style.left = Math.max(6, Math.min(fr.width - start.w - 6, start.ox + dx)) + 'px';
exit.style.top = Math.max(6, Math.min(fr.height - start.h - 6, start.oy + dy)) + 'px';
});
const end = () => {
if (!start) return; start = null; if (!moved) return;
const fr = $('ag-frame').getBoundingClientRect(), r = exit.getBoundingClientRect();
try { localStorage.setItem(AGEXIT_KEY, JSON.stringify({x: (r.left - fr.left) / fr.width, y: (r.top - fr.top) / fr.height})); } catch { /* this page only */ }
};
exit.addEventListener('pointerup', end); exit.addEventListener('pointercancel', end);
exit.addEventListener('click', () => { if (moved){ moved = false; return; } setAgentMax(false); });
document.addEventListener('keydown', e => { if (e.key === 'Escape' && document.body.classList.contains('agentmax') && $('scrim').hidden) setAgentMax(false); });
window.addEventListener('resize', () => { if (document.body.classList.contains('agentmax')) agexitPlace(); else fitAgentFrame(false); });
// the visual viewport: on iOS the keyboard shrinks it without touching the layout
// viewport, so a fullscreen frame sized in dvh would keep the composer under the keyboard
const vvp = window.visualViewport;
if (vvp){
const sync = () => { const s = document.documentElement.style; s.setProperty('--vvh', Math.round(vvp.height) + 'px'); s.setProperty('--vvtop', Math.round(vvp.offsetTop) + 'px'); };
vvp.addEventListener('resize', sync); vvp.addEventListener('scroll', sync); sync();
}
}
// leaving the view always shrinks the frame back: it covers every other view
VIEWS.filter(v => v !== 'agent').forEach(v => onShow(v, () => { if (document.body.classList.contains('agentmax')) setAgentMax(false, false); }));