diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-12 15:56:07 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-17 12:15:16 -0300 |
| commit | d4dfee52a67d2e2b9a52f7e7b18b3b3cc185fac4 (patch) | |
| tree | 3c1737d474bcebedb0783655ff74e7d850c06258 | |
| parent | fd7775b4e9c24b6bb8f664beb7d4fd2ccecd8d85 (diff) | |
| download | cloud9-d4dfee52a67d2e2b9a52f7e7b18b3b3cc185fac4.tar.gz cloud9-d4dfee52a67d2e2b9a52f7e7b18b3b3cc185fac4.zip | |
9web: integrate sites and services into the file browser views
Replace the standalone dark dashboard with Files, Sites and Services navigation in the existing application shell. Reuse the shared stylesheet, tables and controls; open site files and logs in the normal file browser and send build commands through the existing HTTP-to-9P mapping.
Support direct tab URLs, browser history, preserved unsaved edits and focused controls, and pause catalogue polling in hidden views. Keep catalogue tabs hidden for ordinary upstream gateways. Remove the standalone page, script and log dialog.
Document the integrated views and add a real Chromium regression suite with desktop/mobile screenshots. Validation: catalogue and HTTP filesystem suites, integrated UI suite, and all 32 original browser E2E scenarios.
| -rw-r--r-- | build.zig | 5 | ||||
| -rw-r--r-- | docs/catalog.md | 25 | ||||
| -rw-r--r-- | test/web/catalog_ui.mjs | 132 | ||||
| -rw-r--r-- | web/catalog.zig | 2 | ||||
| -rw-r--r-- | web/main.zig | 8 | ||||
| -rw-r--r-- | web/static/app.mjs | 70 | ||||
| -rw-r--r-- | web/static/catalog.html | 14 | ||||
| -rw-r--r-- | web/static/catalog.js | 56 | ||||
| -rw-r--r-- | web/static/catalog.mjs | 103 | ||||
| -rw-r--r-- | web/static/index.html | 44 | ||||
| -rw-r--r-- | web/static/style.css | 18 |
11 files changed, 387 insertions, 90 deletions
@@ -29,7 +29,7 @@ pub fn build(b: *std.Build) void { wasm.max_memory = 1024 * 1024; const web = b.step("web", "Install the standalone browser client into zig-out/web"); web.dependOn(&b.addInstallFileWithDir(wasm.getEmittedBin(), .{ .custom = "web/_cloud9" }, "cloud9.wasm").step); - for ([_][]const u8{ "index.html", "app.mjs", "client.mjs", "style.css" }) |file| { + for ([_][]const u8{ "index.html", "app.mjs", "catalog.mjs", "client.mjs", "style.css" }) |file| { web.dependOn(&b.addInstallFileWithDir(b.path(b.fmt("web/static/{s}", .{file})), .{ .custom = if (std.mem.eql(u8, file, "index.html")) "web" else "web/_cloud9" }, file).step); } const bridge = b.addExecutable(.{ .name = "9web", .root_module = b.createModule(.{ @@ -44,6 +44,9 @@ pub fn build(b: *std.Build) void { const catalog_test = b.addSystemCommand(&.{ "python3", "test/web/catalog.py" }); catalog_test.addArtifactArg(bridge); b.step("catalog-test", "Test local sites, controls, watcher and passive discovery").dependOn(&catalog_test.step); + const catalog_ui = b.addSystemCommand(&.{ "node", "test/web/catalog_ui.mjs" }); + catalog_ui.addArtifactArg(bridge); + b.step("catalog-ui-test", "Test integrated Files, Sites and Services views in Chromium").dependOn(&catalog_ui.step); } const run_bridge = b.addRunArtifact(bridge); run_bridge.addPassthruArgs(); diff --git a/docs/catalog.md b/docs/catalog.md index cd6eec9..24b6fb9 100644 --- a/docs/catalog.md +++ b/docs/catalog.md @@ -39,7 +39,15 @@ but its Cloudflare poke API is not reproduced locally. ## Builds and watch -The dashboard has Build, Watch, Cancel, and Log controls. Builds execute in the +The regular 9web interface has **files**, **sites**, and **services** views in +catalogue mode. They share the existing header, stylesheet, tables and file +browser. The root opens files; `/?view=sites` and `/?view=services` are direct +links to the other tabs. Browser history and reload preserve the selected view. +Switching tabs preserves unsaved file edits. Ordinary upstream mode shows only +files and does not poll the catalogue API. + +The sites table has build, watch and cancel controls, plus files and log links +that open the same file browser. Builds execute in the configured working directory with the service's environment. One child job runs per site. Repeated build requests during a build coalesce into one later build. Build writes enqueue work immediately; serving does not wait for compilation. @@ -101,9 +109,11 @@ durable history of every transition. 9P flush cancels parked reads. State events also work through `/fs/sites/<name>/events?follow=1` as SSE. `status` is the finite snapshot to use for ordinary polling. -The dashboard reads `GET /_cloud9/catalog.json` and uses -`POST /_cloud9/sites/<name>/ctl` with a plain-text command. The existing -`PUT /fs/sites/<name>/ctl` also reaches the same control implementation. +The sites and services views read `GET /_cloud9/catalog.json` while visible. +Build controls use `PUT /fs/sites/<name>/ctl`, through the same HTTP-to-9P mapping +as file editing. The earlier `POST /_cloud9/sites/<name>/ctl` endpoint remains +compatible for existing clients. Logs use the normal file viewer rather than a +separate dialog. Polling preserves site-row focus and pauses in background tabs. ## Passive discovery @@ -156,6 +166,7 @@ registry, which should remain writable only by its owner. ``` zig build catalog-test http-fs-test mux-test -Doptimize=ReleaseSafe +zig build catalog-ui-test -Doptimize=ReleaseSafe ``` The catalogue integration test uses temporary real sites and processes. It checks @@ -165,6 +176,12 @@ build status, process-group cancellation, nonblocking event readers, and actual socket ownership discovery. Existing gateway HTTP/filesystem and mux suites cover the original mode. +The Chromium UI test checks the shared shell and styles, view navigation and +history, direct tab links, builds through `/fs`, logs in the file browser, +preservation of unsaved edits and focused controls, and mobile layout. It writes +inspection screenshots to `.zig-cache/catalog-ui/`. It uses the installed +`google-chrome-stable` binary (or `CLOUD9_CHROME`), with no npm dependencies. + ## Installed workstation configuration The initial workstation setup uses dashboard port 8090 and site ports 8091–8095: diff --git a/test/web/catalog_ui.mjs b/test/web/catalog_ui.mjs new file mode 100644 index 0000000..bed40b2 --- /dev/null +++ b/test/web/catalog_ui.mjs @@ -0,0 +1,132 @@ +// Real Chromium regression checks for the integrated 9web views. No npm deps. +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import os from 'node:os'; +import net from 'node:net'; + +const binary = path.resolve(process.argv[2] || 'zig-out/bin/9web'); +const work = await fs.mkdtemp(path.join(os.tmpdir(), '9web-ui-')); +const children = [], exceptions = [], pending = new Map(); +let socket, serial = 0; +function start(command, args) { + const p = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] }); + p.output = ''; p.stdout.on('data', b => { p.output += b; }); p.stderr.on('data', b => { p.output += b; }); + p.on('error', e => { p.output += e.message; }); children.push(p); return p; +} +async function port() { + const s = net.createServer(); s.listen(0, '127.0.0.1'); await once(s, 'listening'); + const n = s.address().port; await new Promise(resolve => s.close(resolve)); return n; +} +async function wait(fn, message, timeout = 15000) { + const until = Date.now() + timeout; + while (Date.now() < until) { try { const value = await fn(); if (value) return value; } catch {} await new Promise(r => setTimeout(r, 50)); } + throw new Error('timeout: ' + message); +} +function cdp(method, params = {}) { + return new Promise((resolve, reject) => { + const id = ++serial; + const timer = setTimeout(() => { pending.delete(id); reject(new Error(`CDP timeout: ${method}`)); }, 10000); + pending.set(id, { resolve, reject, timer }); socket.send(JSON.stringify({ id, method, params })); + }); +} +async function evaluate(expression) { + const r = await cdp('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }); + if (r.exceptionDetails) throw new Error(JSON.stringify(r.exceptionDetails)); + return r.result.value; +} +async function click(selector) { await evaluate(`document.querySelector(${JSON.stringify(selector)}).click()`); } +async function view(name) { + await click(`#view-${name}`); + await wait(() => evaluate(`!document.getElementById('${name}-view').hidden`), name + ' view'); +} +async function readySites() { await wait(() => evaluate(`document.querySelectorAll('#sites-entries tr').length === 1`), 'site row'); } + +try { + const root = path.join(work, 'public'); await fs.mkdir(root); + await fs.writeFile(path.join(root, 'index.html'), '<h1>Fixture</h1>'); + const dashboard = await port(), sitePort = await port(), debugPort = await port(); + await fs.writeFile(path.join(work, 'config.json'), JSON.stringify({ sites: [{ name: 'fixture', title: 'Fixture notes', cwd: work, root, port: sitePort, build: ['sh', '-c', 'echo integrated-build'], inputs: ['public/index.html'] }] })); + const web = start(binary, ['--listen', `127.0.0.1:${dashboard}`, '--catalog', path.join(work, 'config.json'), '--catalog-socket', path.join(work, 'catalog.sock'), '--state-dir', path.join(work, 'state')]); + const url = `http://127.0.0.1:${dashboard}`; + await wait(async () => (await fetch(url)).ok, 'server ready'); + assert.equal((await (await fetch(url + '/_cloud9/config.json')).json()).catalog, true); + assert.equal((await fetch(url + '/_cloud9/catalog.js')).status, 404, 'standalone JS removed'); + start(process.env.CLOUD9_CHROME || 'google-chrome-stable', ['--headless=new', '--no-sandbox', '--disable-dev-shm-usage', '--no-first-run', '--no-default-browser-check', `--user-data-dir=${work}/chrome`, `--remote-debugging-port=${debugPort}`, 'about:blank']); + const target = await wait(async () => (await fetch(`http://127.0.0.1:${debugPort}/json/new?about:blank`, { method: 'PUT' })).json(), 'browser ready'); + socket = new WebSocket(target.webSocketDebuggerUrl); await once(socket, 'open'); + socket.addEventListener('message', ({ data }) => { + const m = JSON.parse(data); + if (m.id) { + const p = pending.get(m.id); if (!p) return; clearTimeout(p.timer); pending.delete(m.id); + if (m.error) p.reject(new Error(JSON.stringify(m.error))); else p.resolve(m.result); + } else if (m.method === 'Runtime.exceptionThrown') exceptions.push(m.params.exceptionDetails); + }); + await cdp('Runtime.enable'); await cdp('Page.enable'); + await cdp('Emulation.setDeviceMetricsOverride', { width: 1200, height: 850, deviceScaleFactor: 1, mobile: false }); + await cdp('Page.navigate', { url }); + await wait(() => evaluate(`document.getElementById('status')?.textContent.includes('entries')`), 'files loaded'); + assert.equal(await evaluate(`document.querySelectorAll('header').length`), 1); + assert.equal(await evaluate(`getComputedStyle(document.documentElement).backgroundColor`), 'rgb(255, 255, 255)'); + assert.equal(await evaluate(`document.getElementById('view-files').getAttribute('aria-current')`), 'page'); + await view('sites'); await readySites(); + assert.equal(await evaluate(`document.querySelector('#sites-entries .site-name').href`), `http://127.0.0.1:${sitePort}/`); + assert.equal(await evaluate(`document.querySelectorAll('link[rel=stylesheet]').length`), 1); + assert.equal(await evaluate(`document.querySelector('link[rel=stylesheet]').getAttribute('href')`), '/_cloud9/style.css'); + // Build button writes through the same /fs tree as the normal file browser. + await click('#sites-entries button'); + await wait(() => evaluate(`document.querySelector('#sites-entries .site-phase').textContent.includes('exit 0')`), 'build complete'); + await evaluate(`document.querySelector('#sites-entries button').focus()`); + await click('#sites-reload'); + await evaluate(`document.querySelector('#sites-entries button').focus()`); + await wait(() => evaluate(`!document.getElementById('sites-reload').disabled`), 'refresh complete'); + assert.equal(await evaluate(`document.activeElement === document.querySelector('#sites-entries button')`), true, 'refresh preserves focused control'); + await click('#sites-entries a[data-path$="/log"]'); + await wait(() => evaluate(`document.getElementById('editor').value.includes('integrated-build')`), 'log in file viewer'); + assert.equal(await evaluate(`document.getElementById('files-view').hidden`), false); + // Switching views preserves the existing file editor and its unsaved contents. + await evaluate(`document.getElementById('editor').value = 'unsaved note'; document.getElementById('editor').dispatchEvent(new Event('input'))`); + await view('sites'); await view('services'); + await wait(() => evaluate(`document.getElementById('services-status').textContent.includes('HTTP services')`), 'services loaded'); + await evaluate('history.back()'); + await wait(() => evaluate(`!document.getElementById('sites-view').hidden`), 'back to sites'); + await evaluate('history.back()'); + await wait(() => evaluate(`!document.getElementById('files-view').hidden`), 'back to files'); + assert.equal(await evaluate(`document.getElementById('editor').value`), 'unsaved note'); + assert.equal(await evaluate(`document.getElementById('edit-status').textContent`), 'Unsaved changes.'); + // Reload/deep-link into a tab; no synthetic 9P path is reserved for the tab. + await evaluate(`window.onbeforeunload = null; window.confirm = () => true`); + // A fresh target avoids bypassing the intentional beforeunload prompt. + const target2 = await (await fetch(`http://127.0.0.1:${debugPort}/json/new?${encodeURIComponent(url + '/?view=sites')}`, { method: 'PUT' })).json(); + socket.close(); socket = new WebSocket(target2.webSocketDebuggerUrl); await once(socket, 'open'); + socket.addEventListener('message', ({ data }) => { + const m = JSON.parse(data); if (!m.id) return; + const p = pending.get(m.id); if (!p) return; clearTimeout(p.timer); pending.delete(m.id); + if (m.error) p.reject(new Error(JSON.stringify(m.error))); else p.resolve(m.result); + }); + await cdp('Runtime.enable'); await cdp('Page.enable'); await readySites(); + assert.equal(await evaluate(`document.getElementById('view-sites').getAttribute('aria-current')`), 'page'); + await cdp('Emulation.setDeviceMetricsOverride', { width: 1200, height: 850, deviceScaleFactor: 1, mobile: false }); + await fs.mkdir('.zig-cache/catalog-ui', { recursive: true }); + await fs.writeFile('.zig-cache/catalog-ui/sites.png', Buffer.from((await cdp('Page.captureScreenshot', { format: 'png' })).data, 'base64')); + await view('services'); + await wait(() => evaluate(`document.getElementById('services-status').textContent.includes('HTTP services')`), 'services ready'); + await fs.writeFile('.zig-cache/catalog-ui/services.png', Buffer.from((await cdp('Page.captureScreenshot', { format: 'png' })).data, 'base64')); + await view('sites'); + await cdp('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true }); + assert.equal(await evaluate(`document.documentElement.scrollWidth <= innerWidth`), true, 'mobile page does not overflow'); + await fs.writeFile('.zig-cache/catalog-ui/mobile.png', Buffer.from((await cdp('Page.captureScreenshot', { format: 'png' })).data, 'base64')); + assert.deepEqual(exceptions, []); + console.log('catalog_ui: shared shell/style, tab history, file/log navigation, build control, focus, dirty edits and mobile layout passed'); +} catch (e) { + for (const child of children) console.error(child.output.slice(-5000)); + throw e; +} finally { + socket?.close(); + for (const p of children.reverse()) { + if (p.exitCode === null) { p.kill('SIGTERM'); await Promise.race([once(p, 'exit'), new Promise(r => setTimeout(r, 3000))]); if (p.exitCode === null) p.kill('SIGKILL'); } + } + await fs.rm(work, { recursive: true, force: true }); +} diff --git a/web/catalog.zig b/web/catalog.zig index 5e75555..53bab19 100644 --- a/web/catalog.zig +++ b/web/catalog.zig @@ -349,7 +349,7 @@ pub const Catalog = struct { return result; } fn content(cat: *Catalog, a: std.mem.Allocator, path: []const u8) ![]const u8 { - if (std.mem.eql(u8, path, "index.html")) return @embedFile("static/catalog.html"); + if (std.mem.eql(u8, path, "index.html")) return @embedFile("static/index.html"); if (std.mem.eql(u8, path, "listeners/index.json")) return cat.listeners; if (std.mem.eql(u8, path, "services/index.json")) { const parsed = try std.json.parseFromSlice([]std.json.Value, a, cat.listeners, .{}); diff --git a/web/main.zig b/web/main.zig index 8c3d6ad..eaf6804 100644 --- a/web/main.zig +++ b/web/main.zig @@ -200,7 +200,10 @@ pub fn main(init: std.process.Init) !void { if ((!std.mem.eql(u8, origin_uri.scheme, "https") and !std.mem.eql(u8, origin_uri.scheme, "http")) or origin_uri.host == null or origin_uri.user != null or origin_uri.password != null or origin_uri.path.percent_encoded.len != 0 or origin_uri.query != null or origin_uri.fragment != null) return error.InvalidOrigin; - const browser_config = try std.json.Stringify.valueAlloc(allocator, .{ .user = user, .tree = tree }, .{}); + const browser_config = if (cat != null) + try std.json.Stringify.valueAlloc(allocator, .{ .user = user, .tree = tree, .catalog = true }, .{}) + else + try std.json.Stringify.valueAlloc(allocator, .{ .user = user, .tree = tree }, .{}); var app: App = .{ .io = io, .m = &m, .catalog = cat, .config = .{ .host = host, @@ -402,8 +405,6 @@ fn serveHttp(s: *Session) !void { if (app.catalog) |c| { if (request.head.method != .GET and request.head.method != .HEAD and origin != null and !same_origin) return respond(&request, "Unexpected Origin\n", "text/plain", .forbidden); - if (std.mem.eql(u8, path, "/")) return respond(&request, @embedFile("static/catalog.html"), "text/html; charset=utf-8", .ok); - if (std.mem.eql(u8, path, "/_cloud9/catalog.js")) return respond(&request, @embedFile("static/catalog.js"), "text/javascript", .ok); if (std.mem.eql(u8, path, "/_cloud9/catalog.json")) { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); @@ -441,6 +442,7 @@ fn serveHttp(s: *Session) !void { return respond(&request, "Use GET\n", "text/plain", .method_not_allowed); if (std.mem.eql(u8, path, "/_cloud9/config.json")) return respond(&request, config.browser_config, "application/json", .ok); if (std.mem.eql(u8, path, "/_cloud9/app.mjs")) return respond(&request, @embedFile("static/app.mjs"), "text/javascript; charset=utf-8", .ok); + if (std.mem.eql(u8, path, "/_cloud9/catalog.mjs")) return respond(&request, @embedFile("static/catalog.mjs"), "text/javascript; charset=utf-8", .ok); if (std.mem.eql(u8, path, "/_cloud9/client.mjs")) return respond(&request, @embedFile("static/client.mjs"), "text/javascript; charset=utf-8", .ok); if (std.mem.eql(u8, path, "/_cloud9/style.css")) return respond(&request, @embedFile("static/style.css"), "text/css; charset=utf-8", .ok); if (std.mem.eql(u8, path, "/_cloud9/cloud9.wasm")) return respond(&request, @embedFile("client.wasm"), "application/wasm", .ok); diff --git a/web/static/app.mjs b/web/static/app.mjs index 429bef7..b31177a 100644 --- a/web/static/app.mjs +++ b/web/static/app.mjs @@ -1,8 +1,40 @@ import { Client } from './client.mjs'; +import { catalogViews } from './catalog.mjs'; const $ = id => document.getElementById(id); const text = new TextDecoder('utf-8', { fatal: true }); let client = null, current = null, currentPath = '/', busy = false, dirty = false; let configuration = null; +let activeView = 'files'; +const catalog = catalogViews(pathLink); + +async function loadConfiguration() { + if (!configuration) { + const response = await fetch('/_cloud9/config.json'); + if (!response.ok) throw new Error('Unable to load server settings. Reload to try again.'); + configuration = await response.json(); + for (const view of ['sites', 'services']) $(`view-${view}`).hidden = !configuration.catalog; + } + return configuration; +} +function locationView() { + const view = new URLSearchParams(location.search).get('view'); + return configuration?.catalog && ['sites', 'services'].includes(view) ? view : 'files'; +} +function viewURL(view, path = currentPath) { + return pathURL(path) + (view === 'files' ? '' : `?view=${view}`); +} +function showView(view) { + activeView = view; + for (const name of ['files', 'sites', 'services']) { + $(`${name}-view`).hidden = view !== name; + const link = $(`view-${name}`); + link.classList.toggle('selected', view === name); + if (view === name) link.setAttribute('aria-current', 'page'); else link.removeAttribute('aria-current'); + link.href = viewURL(name); + } + document.title = `${view === 'files' ? currentPath : view} — cloud9`; + catalog.show(view); +} function status(message, error = false) { $('status').textContent = message; @@ -17,7 +49,7 @@ function controls() { $('delete').disabled = busy || currentPath === '/'; $('editor').readOnly = busy; $('edit-status').textContent = dirty ? 'Unsaved changes.' : 'No unsaved changes.'; - document.querySelector('main').setAttribute('aria-busy', String(busy)); + document.querySelector('#files-view main').setAttribute('aria-busy', String(busy)); } async function action(operation) { if (busy) return; @@ -29,11 +61,7 @@ async function action(operation) { } async function connectedClient() { if (client && !client.closed) return client; - if (!configuration) { - const response = await fetch('/_cloud9/config.json'); - if (!response.ok) throw new Error('Unable to load server settings. Reload to try again.'); - configuration = await response.json(); - } + await loadConfiguration(); try { client = await Client.connect('/_cloud9/9p', configuration.user, configuration.tree); } catch { throw new Error('Unable to reach the file server. Reload to try again.'); } return client; @@ -105,10 +133,12 @@ function breadcrumbs(path) { } async function navigate(path, historyMode = 'push') { path = normalizePath(path); + showView('files'); stopFollow(); status('Loading…'); const result = await readPath(path); current = result; currentPath = path; dirty = false; + for (const view of ['files', 'sites', 'services']) $(`view-${view}`).href = viewURL(view); $('path').value = path; const url = pathURL(path); if (historyMode === 'push' && location.pathname + location.search + location.hash !== url) history.pushState(null, '', url); @@ -149,6 +179,17 @@ async function navigate(path, historyMode = 'push') { } function mayLeave() { return !dirty || window.confirm('Discard unsaved changes?'); } document.addEventListener('click', event => { + const tab = event.target.closest('a[data-view]'); + if (tab && event.button === 0 && !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey) { + event.preventDefault(); + if (busy || tab.hidden) return; + const view = tab.dataset.view; + if (view === activeView) return; + history.pushState(null, '', viewURL(view)); + showView(view); + if (view === 'files' && !current) action(() => navigate(currentPath, 'none')).then(loadTree); + return; + } const link = event.target.closest('a[data-path]'); if (!link || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return; event.preventDefault(); @@ -180,8 +221,10 @@ $('download').onclick = () => { setTimeout(() => URL.revokeObjectURL(url), 1000); }; window.addEventListener('popstate', () => { - if (busy || !mayLeave()) { history.pushState(null, '', pathURL(currentPath)); return; } - action(() => navigate(locationPath(), 'none')); + const view = locationView(), path = locationPath(); + if (busy || (view === 'files' && path !== currentPath && !mayLeave())) { history.pushState(null, '', viewURL(activeView)); return; } + showView(view); + if (view === 'files' && (!current || path !== currentPath)) action(() => navigate(path, 'none')).then(loadTree); }); window.addEventListener('beforeunload', event => { if (dirty) { event.preventDefault(); event.returnValue = ''; } @@ -357,4 +400,13 @@ $('upload-input').onchange = () => { $('upload-input').value = ''; }; -action(() => navigate(locationPath(), 'none')).then(loadTree); +async function start() { + try { + await loadConfiguration(); + currentPath = locationPath(); + const view = locationView(); + showView(view); + if (view === 'files') await action(() => navigate(currentPath, 'none')).then(loadTree); + } catch (error) { status(error.message, true); } +} +start(); diff --git a/web/static/catalog.html b/web/static/catalog.html deleted file mode 100644 index 2160612..0000000 --- a/web/static/catalog.html +++ /dev/null @@ -1,14 +0,0 @@ -<!doctype html> -<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"> -<title>9web · local sites</title> -<style> -:root{color-scheme:light dark;font:16px/1.5 system-ui;background:#151917;color:#e3e9df}body{max-width:1100px;margin:3rem auto;padding:0 1.5rem}h1{font-size:2.5rem;margin-bottom:0}a{color:#b8dfa6}header p{color:#aab8a6}.sites{display:grid;grid-template-columns:repeat(auto-fit,minmax(290px,1fr));gap:1rem}article{background:#212922;border:1px solid #3c4b3c;border-radius:10px;padding:1.2rem}article h2{margin:0 0 .6rem;font-size:1.3rem}code,pre{font:13px/1.5 monospace;overflow-wrap:anywhere}button{background:#324631;color:inherit;border:1px solid #61765a;border-radius:5px;padding:.4rem .7rem;cursor:pointer;margin:.4rem .3rem .1rem 0}button:disabled{opacity:.4}table{width:100%;border-collapse:collapse}td,th{text-align:left;border-bottom:1px solid #354234;padding:.6rem;overflow-wrap:anywhere}th{color:#aab8a6}pre{max-height:35rem;overflow:auto;background:#101410;padding:1rem;white-space:pre-wrap}small{color:#aab8a6}.error{color:#ffb4a9}.toolbar{display:flex;gap:1rem;align-items:center}dialog{width:min(850px,85vw);background:#212922;color:inherit;border:1px solid #61765a}#message{min-height:1.5em}details{margin-top:1.5rem}@media(max-width:650px){td,th{padding:.4rem;font-size:13px}.process{display:none}} -</style> -<header><h1>9web</h1><p>Local sites, builds, and listening services.</p></header> -<p id="message" role="status"></p><main><div id="sites" class="sites"></div> -<div class="toolbar"><h2>HTTP services</h2><a href="/fs/">9P tree</a></div> -<p><small>Identified from socket ownership and process arguments. No endpoint probing. Loopback links work only on this computer.</small></p> -<table><thead><tr><th>Service</th><th>Address</th><th class="process">Process</th><th>Evidence</th></tr></thead><tbody id="services"></tbody></table> -<details><summary id="unknown-title">Other listeners</summary><table><tbody id="unknown"></tbody></table></details></main> -<dialog id="logs"><button id="close-log">Close</button><h2 id="log-title"></h2><pre id="log-text"></pre></dialog> -<script src="/_cloud9/catalog.js"></script></html> diff --git a/web/static/catalog.js b/web/static/catalog.js deleted file mode 100644 index f868a16..0000000 --- a/web/static/catalog.js +++ /dev/null @@ -1,56 +0,0 @@ -const $ = id => document.getElementById(id); -let activeLog = null; -const element = (tag, text) => { const e = document.createElement(tag); e.textContent = text; return e; }; -function url(address, port, protocol = 'http') { - let host = address; - if (!host || host === '0.0.0.0' || host === '::') host = location.hostname; - host = host.replace(/^\[|\]$/g, ''); - return `${protocol}://${host.includes(':') ? `[${host}]` : host}:${port}/`; -} -async function control(name, command) { - try { - const r = await fetch(`/_cloud9/sites/${encodeURIComponent(name)}/ctl`, { method:'POST', headers:{'Content-Type':'text/plain'}, body:command }); - if (!r.ok) throw new Error(await r.text()); - $('message').textContent = `${name}: ${command} requested`; - await refresh(); - } catch (e) { $('message').textContent = e.message; } -} -function button(text, action, disabled = false) { const b = element('button', text); b.disabled = disabled; b.onclick = action; return b; } -function listenerRow(item) { - const tr = element('tr', ''); - const name = element('td', ''); - if (item.protocol !== 'unknown') { - const a = element('a', item.service); a.href = url(item.address, item.port, item.protocol); name.append(a); - } else name.textContent = item.process || 'Unknown'; - tr.append(name, element('td', `${item.address}:${item.port}${item.local ? ' · local only' : ''}`)); - const process = element('td', item.pid ? `PID ${item.pid}` : 'Unavailable'); process.className = 'process'; tr.append(process, element('td', item.evidence)); - return tr; -} -async function refresh() { - try { - const r = await fetch('/_cloud9/catalog.json'); if (!r.ok) throw new Error(`Dashboard: ${r.status}`); - const data = await r.json(); - $('sites').replaceChildren(); - for (const site of data.sites) { - const card = element('article', ''); const h = element('h2', ''); const a = element('a', site.title); a.href = url('', site.port); h.append(a); - const s = site.status; - card.append(h, element('code', site.root), element('p', `${s.phase}${s.watching ? ' · watch on' : ''}${s.queued ? ' · build queued' : ''}${s.exit_code !== null ? ` · exit ${s.exit_code}` : ''}`)); - if (s.finished) card.append(element('small', `Last finished ${new Date(s.finished * 1000).toLocaleString()}`), element('br', '')); - card.append(button('Build', () => control(site.name, 'build'), !site.build), button(s.watching ? 'Stop watching' : 'Watch', () => control(site.name, s.watching ? 'watch off' : 'watch on'), !site.watch), button('Cancel', () => control(site.name, 'cancel'), !s.pid && !s.queued), button('Log', () => { activeLog = site.name; $('log-title').textContent = site.title; $('logs').showModal(); refreshLog(); })); - $('sites').append(card); - } - const known = data.listeners.filter(x => x.protocol !== 'unknown'); - const unknown = data.listeners.filter(x => x.protocol === 'unknown'); - $('services').replaceChildren(...known.map(listenerRow)); - $('unknown').replaceChildren(...unknown.map(listenerRow)); - $('unknown-title').textContent = `Other listeners (${unknown.length})`; - if (data.discovery_error) $('message').textContent = data.discovery_error; - } catch (e) { $('message').textContent = e.message; } -} -async function refreshLog() { - if (!activeLog) return; - try { const r = await fetch(`/fs/sites/${encodeURIComponent(activeLog)}/log`); $('log-text').textContent = await r.text(); } catch (e) { $('log-text').textContent = e.message; } -} -$('close-log').onclick = () => { activeLog = null; $('logs').close(); }; -$('logs').onclose = () => { activeLog = null; }; -refresh(); setInterval(refresh, 5000); setInterval(refreshLog, 1500); diff --git a/web/static/catalog.mjs b/web/static/catalog.mjs new file mode 100644 index 0000000..d1d3444 --- /dev/null +++ b/web/static/catalog.mjs @@ -0,0 +1,103 @@ +// Sites and services are views of the same 9web application. File/log links +// use app.mjs navigation; control writes use the normal HTTP-to-9P mapping. +const $ = id => document.getElementById(id); +const element = (tag, text = '') => { const e = document.createElement(tag); e.textContent = text; return e; }; +function url(address, port, protocol = 'http') { + let host = address; + if (!host || host === '0.0.0.0' || host === '::') host = location.hostname; + host = host.replace(/^\[|\]$/g, ''); + return `${protocol}://${host.includes(':') ? `[${host}]` : host}:${port}/`; +} + +export function catalogViews(pathLink) { + let active = 'files', timer = null, request = null, revision = 0, pending = new Set(); + const rows = new Map(); + function status(view, text, error = false) { + const p = $(`${view}-status`); p.textContent = text; p.classList.toggle('error', error); + } + async function control(site, command) { + if (pending.has(site.name)) return; + pending.add(site.name); updateSite(site); + try { + const r = await fetch(`/fs/sites/${encodeURIComponent(site.name)}/ctl`, { method: 'PUT', body: command }); + if (!r.ok) throw new Error(await r.text()); + status('sites', `${site.title}: ${command} requested.`); + } catch (error) { status('sites', error.message, true); } + finally { pending.delete(site.name); updateSite(site); if (active === 'sites') await refresh(false); } + } + function updateSite(site) { + let row = rows.get(site.name); + if (!row) { + const tr = element('tr'); tr.dataset.site = site.name; + const name = element('td'), phase = element('td'), finished = element('td'), actions = element('td'); + const link = element('a'); link.className = 'site-name'; + const root = element('span'); root.className = 'site-root'; name.append(link, root); + const tools = element('div'); tools.className = 'site-actions'; + const build = element('button', 'build'), watch = element('button', 'watch'), cancel = element('button', 'cancel'); + for (const b of [build, watch, cancel]) b.type = 'button'; + tools.append(build, watch, cancel, pathLink('files', `/sites/${site.name}/public`), pathLink('log', `/sites/${site.name}/log`)); + actions.append(tools); tr.append(name, phase, finished, actions); + row = { tr, link, root, phase, finished, build, watch, cancel }; rows.set(site.name, row); + $('sites-entries').append(tr); + } + const s = site.status; + row.link.textContent = site.title; row.link.href = url('', site.port); row.root.textContent = site.root; + row.phase.textContent = `${s.phase}${s.watching ? ' · watch on' : ''}${s.queued ? ' · queued' : ''}${s.exit_code !== null ? ` · exit ${s.exit_code}` : ''}`; + row.phase.className = `site-phase${s.phase === 'failed' ? ' failed' : ''}`; + row.finished.textContent = s.finished ? new Date(s.finished * 1000).toLocaleString() : '—'; + row.build.disabled = pending.has(site.name) || !site.build; + row.watch.disabled = pending.has(site.name) || !site.watch; + row.watch.textContent = s.watching ? 'stop watching' : 'watch'; + row.cancel.disabled = pending.has(site.name) || (!s.pid && !s.queued && !s.watching); + row.build.onclick = () => control(site, 'build'); + row.watch.onclick = () => control(site, s.watching ? 'watch off' : 'watch on'); + row.cancel.onclick = () => control(site, 'cancel'); + } + function listenerRow(item, sites) { + const tr = element('tr'), name = element('td'); + if (item.protocol !== 'unknown') { + const site = item.service === '9web' && sites.find(s => s.port === item.port); + const a = element('a', site ? site.title : item.service); a.href = url(item.address, item.port, item.protocol); name.append(a); + } else name.textContent = item.process || 'Unknown'; + const address = element('td', `${item.address.includes(':') ? `[${item.address}]` : item.address}:${item.port}${item.local ? ' · local only' : ''}`); + address.className = 'listener-address'; + tr.append(name, address, element('td', item.pid ? `${item.process || ''} (${item.pid})` : 'Unavailable'), element('td', item.evidence)); + return tr; + } + async function refresh(showCount = true) { + if (active === 'files' || document.hidden) return; + request?.abort(); request = new AbortController(); + const ticket = ++revision, view = active; + $(`${view}-reload`).disabled = true; + try { + const r = await fetch('/_cloud9/catalog.json', { signal: request.signal }); + if (!r.ok) throw new Error(`Unable to load ${view}: HTTP ${r.status}`); + const data = await r.json(); + if (ticket !== revision || active !== view) return; + if (view === 'sites') { + const names = new Set(data.sites.map(s => s.name)); + for (const [name, row] of rows) if (!names.has(name)) { row.tr.remove(); rows.delete(name); } + for (const site of data.sites) updateSite(site); + $('sites-empty').hidden = data.sites.length !== 0; + if (showCount) status(view, `${data.sites.length} ${data.sites.length === 1 ? 'site' : 'sites'} · generated files are served continuously`); + } else { + const known = data.listeners.filter(x => x.protocol !== 'unknown'), unknown = data.listeners.filter(x => x.protocol === 'unknown'); + $('services-entries').replaceChildren(...known.map(x => listenerRow(x, data.sites))); + $('other-listeners-entries').replaceChildren(...unknown.map(x => listenerRow(x, data.sites))); + $('services-empty').hidden = known.length !== 0; + $('other-listeners-title').textContent = `Other listeners (${unknown.length})`; + status(view, data.discovery_error || `${known.length} HTTP services · refreshed every 5 seconds`, Boolean(data.discovery_error)); + } + } catch (error) { if (error.name !== 'AbortError' && ticket === revision) status(view, error.message, true); } + finally { if (ticket === revision) $(`${view}-reload`).disabled = false; } + } + function show(view) { + clearInterval(timer); request?.abort(); revision++; + active = view; + for (const name of ['sites', 'services']) $(`${name}-reload`).disabled = false; + if (view !== 'files') { refresh(); timer = setInterval(refresh, 5000); } + } + for (const name of ['sites', 'services']) $(`${name}-reload`).onclick = () => refresh(); + document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); }); + return { show }; +} diff --git a/web/static/index.html b/web/static/index.html index b012b3c..8e2b5cc 100644 --- a/web/static/index.html +++ b/web/static/index.html @@ -12,8 +12,13 @@ <a class="brand" href="/" data-path="/">cloud9</a> <div class="description">A web interface to your file server.</div> </header> - <nav class="toolbar" aria-label="File actions"> - <a class="selected" href="/" data-path="/">files</a> + <nav class="toolbar" id="views" aria-label="Views"> + <a class="selected" id="view-files" href="/" data-view="files" aria-current="page">files</a> + <a id="view-sites" href="/?view=sites" data-view="sites" hidden>sites</a> + <a id="view-services" href="/?view=services" data-view="services" hidden>services</a> + </nav> + <div id="files-view"> + <nav class="toolbar file-tools" aria-label="File actions"> <button id="reload" type="button">reload</button> <button id="newfile" type="button">new file</button> <button id="newdir" type="button">new folder</button> @@ -66,6 +71,41 @@ </section> </main> </div> + </div> + <main id="sites-view" class="catalog-view" aria-label="Sites" hidden> + <div class="summary"> + <p id="sites-status" role="status" aria-live="polite">Loading sites…</p> + <button id="sites-reload" type="button">reload</button> + </div> + <div class="table-scroll"> + <table> + <thead><tr><th scope="col">Site</th><th scope="col">Status</th><th scope="col">Last build</th><th scope="col">Actions</th></tr></thead> + <tbody id="sites-entries"></tbody> + </table> + </div> + <p id="sites-empty" class="muted" hidden>No sites configured.</p> + </main> + <main id="services-view" class="catalog-view" aria-label="Services" hidden> + <div class="summary"> + <p id="services-status" role="status" aria-live="polite">Loading services…</p> + <button id="services-reload" type="button">reload</button> + </div> + <p class="muted">Listeners identified from process metadata, without endpoint probes. Local-only links work on this computer.</p> + <div class="table-scroll"> + <table> + <thead><tr><th scope="col">Service</th><th scope="col">Address</th><th scope="col">Process</th><th scope="col">Evidence</th></tr></thead> + <tbody id="services-entries"></tbody> + </table> + </div> + <p id="services-empty" class="muted" hidden>No HTTP services identified.</p> + <details id="other-listeners"> + <summary id="other-listeners-title">Other listeners</summary> + <div class="table-scroll"><table> + <thead><tr><th scope="col">Process</th><th scope="col">Address</th><th scope="col">PID</th><th scope="col">Evidence</th></tr></thead> + <tbody id="other-listeners-entries"></tbody> + </table></div> + </details> + </main> <footer>served by cloud9</footer> </body> </html> diff --git a/web/static/style.css b/web/static/style.css index 965406b..53ccda3 100644 --- a/web/static/style.css +++ b/web/static/style.css @@ -26,6 +26,21 @@ header { padding: 0 8px 17px; } font-size: 15px; } .toolbar .selected { background: #ccc; color: #111; } +.file-tools { border-bottom: 1px solid #ddd; padding-top: 7px; } +.catalog-view { padding-top: 13px; } +.catalog-view .summary p { margin: 0; color: #777; } +.catalog-view .summary .error { color: #a22; } +.catalog-view td { padding-top: 8px; padding-bottom: 8px; } +.catalog-view .site-name { font-weight: bold; } +.catalog-view .site-root { display: block; color: #777; font: 12px/1.6 monospace; overflow-wrap: anywhere; } +.catalog-view .site-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 5px 9px; font-size: 12px; } +.catalog-view .site-phase { white-space: nowrap; } +.catalog-view .site-phase.failed { color: #a22; } +.catalog-view .listener-address { font-family: monospace; overflow-wrap: anywhere; } +.catalog-view .muted { color: #777; font-size: 12px; } +.table-scroll { overflow-x: auto; } +#other-listeners { margin-top: 20px; } +#other-listeners summary { cursor: pointer; padding-bottom: 8px; color: #777; } button, input, textarea { font: inherit; color: inherit; } button { cursor: pointer; @@ -90,6 +105,9 @@ footer { margin: 30px 8px 0; padding-top: 7px; border-top: 1px solid #ddd; text- a:focus-visible, button:focus-visible { outline: 2px solid #07539b; outline-offset: 2px; } [hidden] { display: none !important; } @media (max-width: 600px) { + #sites-view .site-root, #sites-view th:nth-child(3), #sites-view td:nth-child(3) { display: none; } + .catalog-view .site-phase { white-space: normal; } + #services-view table { min-width: 600px; } body { padding: 14px 10px; } header { padding-left: 3px; } .brand { font-size: 26px; } |
