heyquilt 0.3.187 → 0.3.188

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,296 @@
1
+ // The program on a preview machine (plans/previews.md): `quilt preview-vm`. It is the way in
2
+ // (src/preview/proxy.js) and what runs behind it: it joins its codebase as a viewer nobody lists
3
+ // (a pass from the accounts API for the key the machine was made with), keeps a folder for each
4
+ // branch someone is looking at (a folder with no git that follows that branch's live copy), runs
5
+ // the preview's app from it (src/preview/runner.js) and fills the way in's slots. Nobody looking
6
+ // at a branch for two minutes: its app is stopped. It tells the API each minute whether anyone
7
+ // is looking; the API puts the machine to sleep when nobody is.
8
+ //
9
+ // From the environment: FLY_MACHINE_ID (Fly sets it), QUILT_PREVIEW_ROOM (the codebase),
10
+ // QUILT_PASS_PUBLIC_KEY (the accounts API's, to check tickets), PORT (8080),
11
+ // QUILT_PREVIEW_DOMAIN (preview.heyquilt.com), and to run anything: QUILT_API, QUILT_RELAY,
12
+ // QUILT_PREVIEW_KEY (the machine's own key), QUILT_PREVIEW_DATA (/data/preview).
13
+ // QUILT_PREVIEW_DEMO=1 serves a page of the machine's own instead, to prove the way in.
14
+ import http from 'node:http'
15
+ import crypto from 'node:crypto'
16
+ import fs from 'node:fs'
17
+ import path from 'node:path'
18
+ import { WebSocketServer } from 'ws'
19
+ import { startPreviewProxy } from './preview/proxy.js'
20
+ import { previewHost, MAX_SLOTS } from './preview/address.js'
21
+ import os from 'node:os'
22
+ import { startApp as realStartApp, installStamp, freePort } from './preview/runner.js'
23
+ import { Session } from './session.js'
24
+ import { PassSource } from './pass-source.js'
25
+ import { loadIdentity } from './identity.js'
26
+
27
+ // How many apps one machine runs at once (2 GB of memory), and how long one runs on after the
28
+ // last person stopped looking at it.
29
+ export const MAX_RUNNING = 3
30
+ export const LINGER_MS = 2 * 60 * 1000
31
+ export const TICK_MS = 2000
32
+ export const REPORT_MS = 60 * 1000
33
+
34
+ /** What the program needs, read from the environment; throws naming what is missing. */
35
+ export function previewVmConfig (env = process.env) {
36
+ const machine = String(env.FLY_MACHINE_ID || env.QUILT_PREVIEW_MACHINE || '').trim().toLowerCase()
37
+ const room = String(env.QUILT_PREVIEW_ROOM || '').trim()
38
+ const passPublicKey = String(env.QUILT_PASS_PUBLIC_KEY || '').trim()
39
+ const missing = [!machine && 'FLY_MACHINE_ID', !room && 'QUILT_PREVIEW_ROOM', !passPublicKey && 'QUILT_PASS_PUBLIC_KEY'].filter(Boolean)
40
+ if (missing.length) throw new Error(`A preview machine needs ${missing.join(', ')}.`)
41
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(room)) throw new Error('QUILT_PREVIEW_ROOM is not a codebase.')
42
+ const port = Number(env.PORT) || 8080
43
+ const domain = String(env.QUILT_PREVIEW_DOMAIN || '').trim() || undefined
44
+ previewHost(machine, 0, domain) // a machine id or domain that is not one stops it here
45
+ const api = String(env.QUILT_API || '').trim().replace(/\/+$/, '')
46
+ const relay = String(env.QUILT_RELAY || '').trim().replace(/\/+$/, '').replace(/^http(s?):\/\//, 'ws$1://')
47
+ const key = String(env.QUILT_PREVIEW_KEY || '').trim()
48
+ const data = path.resolve(String(env.QUILT_PREVIEW_DATA || '/data/preview'))
49
+ return { machine, room, passPublicKey, port, domain, demo: env.QUILT_PREVIEW_DEMO === '1', api, relay, key, data }
50
+ }
51
+
52
+ /**
53
+ * A page of the machine's own, on a port only the machine can reach: it says where it is served
54
+ * from and opens a WebSocket back, so one look proves pages and sockets both get through.
55
+ */
56
+ export async function startDemoApp ({ machine, room }) {
57
+ const server = http.createServer((req, res) => {
58
+ const body = `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Quilt preview machine</title><style>body{font:15px/1.5 system-ui,sans-serif;margin:40px;color:#1d1b2e}code{background:#f3f3f6;padding:2px 6px;border-radius:4px}</style></head><body>
59
+ <h1>A Quilt preview machine</h1>
60
+ <p>Machine <code>${machine}</code>, for codebase <code>${room}</code>. Asked for <code id="path"></code> at <code>${req.headers.host}</code>.</p>
61
+ <p>Socket: <code id="socket">connecting</code></p>
62
+ <script>
63
+ document.getElementById('path').textContent = location.pathname
64
+ const s = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/socket')
65
+ s.onopen = () => s.send('ping')
66
+ s.onmessage = (e) => { document.getElementById('socket').textContent = e.data }
67
+ s.onerror = () => { document.getElementById('socket').textContent = 'failed' }
68
+ </script></body></html>`
69
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' })
70
+ res.end(body)
71
+ })
72
+ const sockets = new WebSocketServer({ server })
73
+ sockets.on('connection', (ws) => ws.on('message', (m) => ws.send(`echo ${String(m).slice(0, 100)}`)))
74
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve) })
75
+ return {
76
+ port: server.address().port,
77
+ close: () => new Promise((resolve) => { sockets.close(); server.closeAllConnections?.(); server.close(() => resolve()) })
78
+ }
79
+ }
80
+
81
+ /**
82
+ * What runs the codebase's apps: one folder for each branch someone is looking at, one app for
83
+ * each preview and branch, the way in's `slots` kept up to date. `tick()` is what it does every
84
+ * two seconds; `report()` what it tells the API each minute.
85
+ */
86
+ export async function startRunner ({ c, slots, lastRequestAt = () => 0, log = () => {}, now = Date.now, fetch: fetchImpl = globalThis.fetch, startApp = realStartApp, lingerMs = LINGER_MS, maxRunning = MAX_RUNNING, sessionOptions = {} }) {
87
+ const identity = loadIdentity(path.join(c.data, 'identity.json'))
88
+ const call = async (route, body) => {
89
+ const res = await fetchImpl(`${c.api}${route}`, { method: 'POST', headers: { authorization: `Bearer ${c.key}`, 'content-type': 'application/json' }, body: JSON.stringify(body), signal: AbortSignal.timeout(30_000) })
90
+ const out = await res.json().catch(() => null)
91
+ if (!res.ok) throw Object.assign(new Error((out && out.error) || `the API answered ${res.status}`), { status: res.status })
92
+ return out
93
+ }
94
+ // The machine's pass for its codebase: view only, for this machine's own identity key.
95
+ const passes = new PassSource({ fetchPass: async () => { const r = await call('/v1/preview/pass', { publicKey: identity.publicKey }); return { pass: r.pass, expiresAt: r.expiresAt } } })
96
+ // Apps a program that died left running (it is started again by itself after a crash): stopped first, or
97
+ // they would hold their ports and files. Only ones from this same start of the machine: a process id is used again after it.
98
+ const pidsFile = path.join(c.data, 'apps.json')
99
+ const boot = Math.round((Date.now() - os.uptime() * 1000) / 60_000)
100
+ try {
101
+ const left = JSON.parse(fs.readFileSync(pidsFile, 'utf8'))
102
+ if (Math.abs(left.boot - boot) <= 1) for (const pid of left.pids || []) { if (Number.isInteger(pid) && pid > 1 && pid !== process.pid) { try { process.kill(-pid, 'SIGKILL'); log(`stopped an app left running (${pid})`) } catch {} } }
103
+ } catch {}
104
+ let pidsSaid = ''
105
+ const savePids = () => {
106
+ const pids = [...runners.values()].map((r) => r.app && r.app.pid).filter(Boolean).sort()
107
+ const next = JSON.stringify({ boot, pids })
108
+ if (next === pidsSaid) return
109
+ pidsSaid = next
110
+ try { fs.mkdirSync(c.data, { recursive: true }); fs.writeFileSync(pidsFile, next) } catch {}
111
+ }
112
+ const folders = new Map() // branch ('' : the codebase's main one) -> { dir, session, ready, leftAt }
113
+ const runners = new Map() // `${preview}\n${branch}` -> { id, branch, slot, name, app, wantedAt, again, folder }
114
+ let closed = false
115
+
116
+ /** The folder that follows `branch`, started (and synced) the first time it is asked for. */
117
+ function folderFor (branch) {
118
+ let f = folders.get(branch)
119
+ if (f) { f.leftAt = 0; return f }
120
+ const dir = path.join(c.data, 'branches', branch ? crypto.createHash('sha256').update(branch).digest('hex').slice(0, 16) : 'main')
121
+ fs.mkdirSync(dir, { recursive: true })
122
+ const session = new Session({ dir, server: c.relay, room: c.room, secret: '', name: 'Preview', tool: 'Quilt preview', identity, passes, followBranch: branch, preview: true, ...sessionOptions })
123
+ session.on('fatal', (err) => log(`${branch || 'main'}: ${err && err.message}`))
124
+ f = { dir, session, leftAt: 0, ready: session.start({ waitTimeoutMs: 60_000 }).then(() => { log(`following ${branch || 'the main branch'} in ${dir}`); return session }) }
125
+ // One that never arrived is forgotten, so the next person to open the branch starts it afresh.
126
+ f.ready.catch(() => { if (folders.get(branch) === f) folders.delete(branch); session.stop().catch(() => {}) })
127
+ folders.set(branch, f)
128
+ return f
129
+ }
130
+
131
+ const main = folderFor('')
132
+ await main.ready
133
+ // The main branch's folder is also where the machine reads who is looking and says what runs.
134
+ const control = main.session
135
+ const mainKey = () => control.branchKey()
136
+ const freeSlot = () => { for (let i = 0; i < MAX_SLOTS; i++) if (![...runners.values()].some((r) => r.slot === i)) return i; return -1 }
137
+ const portsTaken = (but) => [...runners.values()].filter((r) => r !== but && r.app && r.app.port).map((r) => r.app.port)
138
+
139
+ /** Starts (or starts again) the app of runner `r`: its branch's folder first, then the install and the command. */
140
+ function launch (r, def) {
141
+ r.app = { state: 'starting', port: 0, output: 'Getting this branch\'s files…\n', stop: async () => {} }
142
+ const mine = r.app
143
+ const fail = (text) => { if (r.app === mine) r.app = { state: 'failed', port: 0, output: text, stop: async () => {} } }
144
+ if (r.refused) return fail(r.refused)
145
+ const f = folderFor(r.branch)
146
+ r.folder = f
147
+ f.ready.then((session) => {
148
+ if (closed || r.app !== mine || !runners.has(r.key)) return
149
+ if (session.branchForm === 'diff') return fail('This branch was started by an older Quilt, which kept only its differences from git. A preview has no git, so it cannot show it. Main and newer branches work.')
150
+ const dir = path.join(f.dir, ...String(def.folder || '').split('/').filter(Boolean))
151
+ // PORT is one nothing has open now (an app from before may still hold the one this slot had).
152
+ return freePort().then((port) => {
153
+ if (closed || r.app !== mine || !runners.has(r.key)) return
154
+ r.app = startApp({ dir, command: def.command, env: def.env, port, fixedPort: def.port || 0, taken: () => portsTaken(r), onChange: () => { changed = true }, log })
155
+ changed = true
156
+ })
157
+ }).catch((err) => fail(`This branch's files did not arrive: ${err && err.message}`))
158
+ }
159
+
160
+ const howOf = (def) => JSON.stringify([def.command, def.folder, def.port, def.env])
161
+ let changed = true
162
+ let said = ''
163
+ /** Looks at who has what open and makes what runs match it. */
164
+ function tick () {
165
+ if (closed) return
166
+ const defs = control.previews().filter((p) => p.kind === 'app')
167
+ const branches = new Set(control.branchList.map((b) => b.key))
168
+ const wanted = new Map() // key -> { id, branch, again }
169
+ for (const w of control.previewsWanted()) {
170
+ const def = defs.find((p) => p.id === w.id)
171
+ if (!def) continue
172
+ const branch = !w.branch || w.branch === mainKey() ? '' : w.branch
173
+ const key = `${w.id}\n${branch}`
174
+ const had = wanted.get(key)
175
+ wanted.set(key, { id: w.id, branch, def, again: Math.max(w.again || 0, had ? had.again : 0) })
176
+ }
177
+ for (const [key, w] of wanted) {
178
+ let r = runners.get(key)
179
+ if (!r) {
180
+ const slot = freeSlot()
181
+ if (slot < 0) continue
182
+ const running = [...runners.values()].filter((x) => !x.refused).length
183
+ r = { key, id: w.id, branch: w.branch, slot, name: w.def.name, again: w.again, wantedAt: now(), app: null, folder: null, how: howOf(w.def) }
184
+ if (w.branch && !branches.has(w.branch)) r.refused = 'This branch is not in the codebase any more.'
185
+ else if (running >= maxRunning) r.refused = `This codebase's preview machine runs ${maxRunning} apps at once, and ${maxRunning} are running. Close one and try again.`
186
+ runners.set(key, r)
187
+ launch(r, w.def)
188
+ log(`${w.def.name} on ${w.branch || 'main'}: ${r.refused ? 'not started' : 'starting'} (slot ${slot})`)
189
+ changed = true
190
+ continue
191
+ }
192
+ r.wantedAt = now()
193
+ r.name = w.def.name
194
+ // "Try again" on one that did not start; and package.json or the lockfile changed under a running one.
195
+ const stale = r.app && r.app.state === 'running' && r.app.stamp && r.folder && installStamp(path.join(r.folder.dir, ...String(w.def.folder || '').split('/').filter(Boolean))) !== r.app.stamp
196
+ // What the preview runs was changed (its command, folder, port or values): started again as it is now.
197
+ const edited = howOf(w.def) !== r.how
198
+ if ((w.again > r.again && r.app && r.app.state === 'failed') || stale || edited) {
199
+ r.again = Math.max(r.again, w.again)
200
+ r.how = howOf(w.def)
201
+ const old = r.app
202
+ if (r.refused) { runners.delete(key); slots.delete(r.slot); changed = true; continue } // asked again: looked at afresh next time
203
+ Promise.resolve(old.stop()).then(() => { if (runners.get(key) === r) launch(r, w.def) })
204
+ r.app = { state: 'starting', port: 0, output: stale ? 'Its packages changed: installing again…\n' : edited ? 'This preview was changed: starting it again…\n' : 'Starting again…\n', stop: old.stop }
205
+ changed = true
206
+ }
207
+ }
208
+ // Nobody looking for a while: the app stops (one that was never started goes at once).
209
+ for (const [key, r] of runners) {
210
+ if (wanted.has(key) || now() - r.wantedAt < (r.refused ? 0 : lingerMs)) continue
211
+ runners.delete(key)
212
+ slots.delete(r.slot)
213
+ if (r.app) Promise.resolve(r.app.stop()).catch(() => {})
214
+ log(`${r.name} on ${r.branch || 'main'}: nobody is looking; stopped`)
215
+ changed = true
216
+ }
217
+ // A branch with no app left: its folder stops following (its files and packages stay on the disk).
218
+ for (const [branch, f] of folders) {
219
+ if (!branch || [...runners.values()].some((r) => r.branch === branch)) { f.leftAt = 0; continue }
220
+ if (!f.leftAt) { f.leftAt = now(); continue }
221
+ if (now() - f.leftAt < lingerMs) continue
222
+ folders.delete(branch)
223
+ f.ready.then((s) => s.stop(), () => {}).catch(() => {})
224
+ }
225
+ for (const r of runners.values()) slots.set(r.slot, { port: r.app.port, state: r.app.state, name: r.name, branch: r.branch || mainKey(), output: r.app.output })
226
+ const running = [...runners.values()].map((r) => ({ preview: r.id, branch: r.branch || mainKey(), slot: r.slot, state: r.app.state, output: r.app.output.slice(-2000) }))
227
+ savePids()
228
+ const next = JSON.stringify(running)
229
+ if (changed || next !== said) { said = next; changed = false; control.setRunning(running, c.machine) }
230
+ }
231
+
232
+ /** Tells the API the machine is up, and whether anyone is looking: a preview open in an app, or a page asked for lately. */
233
+ async function report () {
234
+ const busy = control.previewsWanted().length > 0 || now() - lastRequestAt() < REPORT_MS
235
+ try { await call('/v1/preview/report', { busy }) } catch (err) { log(`could not report to the API: ${err.message}`) }
236
+ return busy
237
+ }
238
+
239
+ async function close () {
240
+ closed = true
241
+ await Promise.all([...runners.values()].map((r) => Promise.resolve(r.app && r.app.stop()).catch(() => {})))
242
+ await Promise.all([...folders.values()].map((f) => f.ready.then((s) => s.stop(), () => {}).catch(() => {})))
243
+ }
244
+
245
+ return { tick, report, close, control, runners, folders }
246
+ }
247
+
248
+ /** Starts the preview machine's program. Resolves to { port, slots, runner, close } once it is listening. */
249
+ export async function startPreviewVm ({ env = process.env, log = console.log, host = '0.0.0.0', port, tickMs = TICK_MS, reportMs = REPORT_MS, retryMs = 15_000, ...runnerOptions } = {}) {
250
+ const c = previewVmConfig(env)
251
+ if (port !== undefined) c.port = port
252
+ const slots = new Map()
253
+ const closers = []
254
+ if (c.demo) {
255
+ const demo = await startDemoApp(c)
256
+ closers.push(demo.close)
257
+ slots.set(0, { port: demo.port, state: 'running', name: 'Demo', branch: '' })
258
+ }
259
+ const proxy = await startPreviewProxy({ port: c.port, host, machine: c.machine, room: c.room, domain: c.domain, passPublicKey: c.passPublicKey, slots, log, upstreamHost: c.demo ? '127.0.0.1' : 'localhost' })
260
+ closers.push(proxy.close)
261
+ log(`preview machine ${c.machine} for codebase ${c.room}: listening on ${proxy.port}${c.demo ? `, demo page at https://${previewHost(c.machine, 0, c.domain)}` : ''}`)
262
+ let runner = null
263
+ if (!c.demo && c.api && c.relay && c.key) {
264
+ // The way in is up first: someone opening a preview sees "Starting…" while the codebase's files arrive.
265
+ let closing = false
266
+ closers.push(async () => { closing = true })
267
+ const begin = async () => {
268
+ // The API or the relay may be a moment away when the machine wakes: tried again until it joins.
269
+ for (;;) {
270
+ try { runner = await startRunner({ c, slots, lastRequestAt: proxy.lastRequestAt, log, ...runnerOptions }); break } catch (err) {
271
+ if (closing || !retryMs) throw err
272
+ log(`could not join the codebase: ${err.message}; trying again`)
273
+ await new Promise((resolve) => setTimeout(resolve, retryMs))
274
+ if (closing) throw err
275
+ }
276
+ }
277
+ const ticker = setInterval(() => { try { runner.tick() } catch (err) { log(`tick: ${err.stack || err.message}`) } }, tickMs)
278
+ const reporter = setInterval(() => { runner.report() }, reportMs)
279
+ closers.push(async () => { clearInterval(ticker); clearInterval(reporter); await runner.close() })
280
+ runner.report()
281
+ }
282
+ const ready = begin()
283
+ ready.catch((err) => log(`could not join the codebase: ${err.stack || err.message}`))
284
+ return { port: proxy.port, slots, ready, runner: () => runner, close: async () => { closing = true; await ready.catch(() => {}); for (const close of closers.reverse()) await close() } }
285
+ }
286
+ if (!c.demo) log('QUILT_API, QUILT_RELAY or QUILT_PREVIEW_KEY is not set: nothing will run behind the way in')
287
+ return { port: proxy.port, slots, ready: Promise.resolve(), runner: () => null, close: async () => { for (const close of closers.reverse()) await close() } }
288
+ }
289
+
290
+ /** `quilt preview-vm`: runs until the machine is stopped. */
291
+ export async function runPreviewVm () {
292
+ const vm = await startPreviewVm()
293
+ const stop = () => vm.close().finally(() => process.exit(0))
294
+ process.on('SIGTERM', stop)
295
+ process.on('SIGINT', stop)
296
+ }
@@ -0,0 +1,156 @@
1
+ // Previews of a codebase (plans/previews.md), as a folder's session sees them. Pure: no document,
2
+ // no connection. Three things meet here:
3
+ // - what the codebase's previews are: a short list kept in its shared document, next to its
4
+ // tasks (`previews`: id -> { id, name, kind, command, folder, port, url, env, order });
5
+ // - who has which one open, on which branch: each person's app says so in its presence
6
+ // (`preview: { id, branch }`);
7
+ // - what the codebase's preview machine is running: it says so in its own presence
8
+ // (`running: [{ preview, branch, slot, state, output }]`, with `machine`). The machine has no
9
+ // name there, so nobody lists it as a person.
10
+ import { validBranchKey } from './branchdocs.js'
11
+
12
+ export const PREVIEW_KINDS = ['app', 'link']
13
+ export const MAX_PREVIEWS = 12
14
+ // The preview a codebase with a `dev` script has without anyone adding it.
15
+ export const APP_ID = 'app'
16
+ export const RUN_STATES = ['starting', 'running', 'failed']
17
+ const ID = /^[a-z0-9][a-z0-9-]{0,31}$/
18
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/
19
+ // Control characters, kept out of anything shown or run.
20
+ const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f]/g // eslint-disable-line no-control-regex
21
+ const line = (v, max) => String(v ?? '').replace(CONTROL, ' ').replace(/\s*\n\s*/g, ' ').trim().slice(0, max)
22
+
23
+ /** A folder inside the codebase ('' for its root), or null when it points outside. */
24
+ function cleanFolder (v) {
25
+ const parts = String(v ?? '').replace(/\\/g, '/').split('/').filter((p) => p && p !== '.')
26
+ if (parts.some((p) => p === '..' || p.length > 100) || parts.length > 12) return null
27
+ return parts.join('/')
28
+ }
29
+
30
+ /** A link's address: http or https only. */
31
+ function cleanUrl (v) {
32
+ try {
33
+ const u = new URL(String(v ?? '').trim())
34
+ return (u.protocol === 'https:' || u.protocol === 'http:') && u.href.length <= 2000 ? u.href : ''
35
+ } catch { return '' }
36
+ }
37
+
38
+ /** Plain values the app is started with (never secrets: everyone in the codebase reads them). */
39
+ function cleanEnv (v) {
40
+ const out = {}
41
+ if (!v || typeof v !== 'object' || Array.isArray(v)) return out
42
+ for (const [k, val] of Object.entries(v).slice(0, 30)) if (ENV_NAME.test(k) && ['string', 'number', 'boolean'].includes(typeof val)) out[k] = String(val).replace(CONTROL, '').slice(0, 500)
43
+ return out
44
+ }
45
+
46
+ /**
47
+ * One preview as it is kept, or null when it is not one. A link needs its address; an app's
48
+ * command, folder and port may all be left out (the codebase's `dev` script, its root, the port
49
+ * the app opens).
50
+ */
51
+ export function cleanPreview (raw) {
52
+ if (!raw || typeof raw !== 'object' || !ID.test(String(raw.id || ''))) return null
53
+ const kind = PREVIEW_KINDS.includes(raw.kind) ? raw.kind : 'app'
54
+ const name = line(raw.name, 40)
55
+ if (!name) return null
56
+ const order = Number.isFinite(raw.order) ? raw.order : 0
57
+ if (kind === 'link') {
58
+ const url = cleanUrl(raw.url)
59
+ return url ? { id: raw.id, name, kind, url, order } : null
60
+ }
61
+ const folder = cleanFolder(raw.folder)
62
+ if (folder === null) return null
63
+ const port = Number.isInteger(raw.port) && raw.port >= 1 && raw.port <= 65535 ? raw.port : 0
64
+ return { id: raw.id, name, kind, command: line(raw.command, 300), folder, port, env: cleanEnv(raw.env), order }
65
+ }
66
+
67
+ /** An id for a new preview named `name`, not one of `taken`. */
68
+ export function previewId (name, taken = []) {
69
+ const base = String(name || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 24) || 'preview'
70
+ let id = base
71
+ for (let n = 2; taken.includes(id); n++) id = `${base}-${n}`
72
+ return id
73
+ }
74
+
75
+ /**
76
+ * The codebase's previews, in order. `saved`: what the shared document keeps (id -> value).
77
+ * `hasDev`: the codebase has a `dev` script, so it has an "App" preview without anyone adding it,
78
+ * until someone changes it (then theirs is kept) or removes it (a note that it was is kept).
79
+ */
80
+ export function previewList (saved = {}, { hasDev = false } = {}) {
81
+ const list = []
82
+ for (const v of Object.values(saved || {})) { const p = cleanPreview(v); if (p && !(v && v.removed)) list.push(p) }
83
+ const app = saved && saved[APP_ID]
84
+ if (hasDev && !app) list.push({ id: APP_ID, name: 'App', kind: 'app', command: '', folder: '', port: 0, env: {}, order: -1, auto: true })
85
+ return list.sort((a, b) => a.order - b.order || a.name.localeCompare(b.name)).slice(0, MAX_PREVIEWS)
86
+ }
87
+
88
+ /** Whether a package.json's text has a `dev` script. */
89
+ export function hasDevScript (packageJson) {
90
+ try {
91
+ const p = JSON.parse(String(packageJson || ''))
92
+ return !!(p && p.scripts && typeof p.scripts.dev === 'string' && p.scripts.dev.trim())
93
+ } catch { return false }
94
+ }
95
+
96
+ /**
97
+ * What a person's presence says they have open: { id, branch }, or null. `again`: a count they
98
+ * raise to ask for an app that did not start to be started again ("Try again").
99
+ */
100
+ export function cleanLooking (raw) {
101
+ if (!raw || typeof raw !== 'object' || !ID.test(String(raw.id || ''))) return null
102
+ const again = Number.isInteger(raw.again) && raw.again > 0 && raw.again < 1e6 ? { again: raw.again } : {}
103
+ return { id: raw.id, branch: validBranchKey(raw.branch) ? raw.branch : '', ...again }
104
+ }
105
+
106
+ /** What the preview machine's presence says it runs: [{ preview, branch, slot, state, output }]. */
107
+ export function cleanRunning (raw) {
108
+ const out = []
109
+ for (const r of (Array.isArray(raw) ? raw : []).slice(0, 20)) {
110
+ if (!r || typeof r !== 'object' || !ID.test(String(r.preview || '')) || !validBranchKey(r.branch)) continue
111
+ if (!Number.isInteger(r.slot) || r.slot < 0 || r.slot > 9 || !RUN_STATES.includes(r.state)) continue
112
+ out.push({ preview: r.preview, branch: r.branch, slot: r.slot, state: r.state, output: String(r.output ?? '').replace(CONTROL, '').slice(-4000) })
113
+ }
114
+ return out
115
+ }
116
+
117
+ /**
118
+ * Each preview with who is looking at it and what runs: { ...preview, looking: [{ name, branch,
119
+ * me }], running: [{ branch, slot, state, output, machine }] }. `states`: the presence of
120
+ * everyone connected, as [clientID, state]; `clientID`: this folder's own.
121
+ */
122
+ export function previewsView ({ previews = [], states = [], clientID = null } = {}) {
123
+ const looking = []
124
+ const running = []
125
+ for (const [id, s] of states) {
126
+ if (!s || typeof s !== 'object') continue
127
+ if (s.kind === 'preview') {
128
+ const machine = typeof s.machine === 'string' && /^[0-9a-f]{8,24}$/.test(s.machine) ? s.machine : ''
129
+ for (const r of cleanRunning(s.running)) running.push({ ...r, machine })
130
+ continue
131
+ }
132
+ const l = typeof s.name === 'string' && s.name ? cleanLooking(s.preview) : null
133
+ if (l) looking.push({ id: l.id, branch: l.branch, name: s.name, me: id === clientID })
134
+ }
135
+ return previews.map((p) => ({
136
+ ...p,
137
+ looking: looking.filter((l) => l.id === p.id).map(({ name, branch, me }) => ({ name, branch, ...(me ? { me: true } : {}) })),
138
+ running: running.filter((r) => r.preview === p.id).map(({ preview, ...r }) => r)
139
+ }))
140
+ }
141
+
142
+ /**
143
+ * The branches a preview can show: main first, then each ticket that has a branch, by its title.
144
+ * `branches`: the relay's list ([{ key, default }]); `tasks`: the board's ([{ id, title, branch }]).
145
+ * [{ key, name, main?, task? }]. A detached commit is nobody's branch.
146
+ */
147
+ export function branchChoices (branches = [], tasks = []) {
148
+ const main = branches.find((b) => b && b.default)
149
+ const out = main ? [{ key: main.key, name: main.key, main: true }] : []
150
+ for (const b of branches) {
151
+ if (!b || b.default || typeof b.key !== 'string' || b.key.startsWith('@')) continue
152
+ const t = tasks.find((x) => x && x.branch === b.key && !x.archived)
153
+ out.push({ key: b.key, name: t ? t.title : b.key, ...(t ? { task: t.id } : {}) })
154
+ }
155
+ return out
156
+ }
package/src/server.js CHANGED
@@ -80,6 +80,10 @@ const MAX_SCOPES = 20
80
80
  // Removed accounts remembered per room, so an older pass's grant can't bring them back.
81
81
  const MAX_REMOVED = 200
82
82
  const ROLES = ['editor', 'viewer']
83
+ // A codebase's preview machine (plans/previews.md): the accounts API signs it a pass of kind
84
+ // "preview" for that one room. It reads every file, writes and says nothing, and is no member.
85
+ const isPreviewPass = (pass) => !!pass && pass.kind === 'preview'
86
+ const PREVIEW_ACCESS = Object.freeze({ role: 'viewer', scopes: [], scopesExcept: [], talk: false })
83
87
  const MB = 1024 * 1024
84
88
  const DAY = 24 * 60 * 60 * 1000
85
89
  // How often a branch's "last used" time (see Room.noteBranchSeen) is saved while it is busy.
@@ -347,6 +351,7 @@ class Room {
347
351
  * to approve anyone, still need the link.
348
352
  */
349
353
  letsInByAccount (pass) {
354
+ if (isPreviewPass(pass)) return this.exists && pass.room === this.name
350
355
  if (!this.controlled || !pass || pass.room !== this.name) return false
351
356
  const account = `${pass.kind}:${pass.sub}`
352
357
  if (this.meta.ownerSub === account) return true
@@ -365,6 +370,9 @@ class Room {
365
370
  * on: then they are their account, on any computer, not their key.
366
371
  */
367
372
  accessFor (key, name, kind, invitedAs, account = '', pass = null) {
373
+ // The codebase's preview machine (plans/previews.md): it reads every file and nothing more. It is
374
+ // no member: never the owner, never kept on the member list, never waiting to be approved.
375
+ if (isPreviewPass(pass)) return pass.room === this.name ? { state: 'approved', ...PREVIEW_ACCESS, owner: false, id: account } : { state: 'pending', invitedAs: 'viewer' }
368
376
  if (!this.controlled) return { state: 'approved', role: 'editor', scopes: [], owner: false }
369
377
  if (!this.meta.owner) {
370
378
  // The room's creator becomes its owner when they sign in, and nobody else, however much
@@ -473,6 +481,7 @@ class Room {
473
481
  * and someone in the room gets the new access, both without the owner.
474
482
  */
475
483
  passRenewed (ws) {
484
+ if (isPreviewPass(ws.pass)) return // a preview machine's access never changes
476
485
  const granted = this.passGrant(ws.pass)
477
486
  if (!granted) return
478
487
  const id = `${ws.pass.kind}:${ws.pass.sub}`
@@ -1078,7 +1087,7 @@ class Room {
1078
1087
  const exists = !!this.meta.branches[to]
1079
1088
  if (!exists && !create) throw new Error(`${key} isn't in this codebase. Pass create: true to start it from a copy of the files on ${from}.`)
1080
1089
  if (exists && create) throw new Error(`${key} is already in this codebase: switch to it without create.`)
1081
- if (!exists) { } else if (!exists) {
1090
+ if (!exists) {
1082
1091
  this.assertMigrated()
1083
1092
  this.assertBranchRoom(editor, this.store.size(from)) // a copy of `from`'s files
1084
1093
  const src = this.branchDoc(from, { by })
@@ -1489,6 +1498,13 @@ class Room {
1489
1498
  if (this.samePerson(other, ws)) { ids.delete(id); other.endReason = 'replaced'; other.terminate(); continue }
1490
1499
  return false
1491
1500
  }
1501
+ // The codebase's preview machine has no name in presence (so nobody lists it as a person) and
1502
+ // says what it runs; nobody else may say that, or pass for it.
1503
+ if (isPreviewPass(ws.pass)) {
1504
+ if (state !== null && (state.name !== undefined || state.kind !== 'preview')) return false
1505
+ continue
1506
+ }
1507
+ if (state !== null && (state.kind === 'preview' || state.running !== undefined)) return false
1492
1508
  if (state !== null && state.name !== name) return false
1493
1509
  // Only a person's cloud AI says whose AI it is, and only its own person's (its pass says so).
1494
1510
  if (state !== null && state.aiOf !== undefined && state.aiOf !== (ws.pass && ws.pass.of ? ws.pass.ofName : undefined)) return false
@@ -1870,6 +1886,12 @@ class Room {
1870
1886
  this.setAccess(ws, a)
1871
1887
  this.noteTurns(ws, a)
1872
1888
  // Presence: an account's visit starts once it's let in (never while it waits for the owner).
1889
+ // A preview machine is nobody's visit, and wakes nobody's AI.
1890
+ if (isPreviewPass(ws.pass)) {
1891
+ send(ws, jsonMessage(MSG_ACCESS, this.accessMessage(a)))
1892
+ this.join(ws, a.name)
1893
+ return
1894
+ }
1873
1895
  if (ws.pass && this.presence && !ws.visit) {
1874
1896
  ws.visit = this.presence.visitStart({ room: this.name, account: `${ws.pass.kind}:${ws.pass.sub}`, name: a.name, owner: !!a.owner, via: 'app', tool: ws.tool || '' })
1875
1897
  // The accounts API learns who owns a session from this report, and only the owner may
@@ -2158,6 +2180,8 @@ export function startServer ({ port = 4321, host = '0.0.0.0', dataDir = null, lo
2158
2180
  const httpPass = (req, room = '') => {
2159
2181
  if (!passKey) return {}
2160
2182
  const p = verifyPass(String(req.headers['x-quilt-pass'] || ''), passKey)
2183
+ // A preview machine's pass opens its live connection and nothing else.
2184
+ if (isPreviewPass(p)) return null
2161
2185
  // A room pass is good in its own room only.
2162
2186
  return p && (!p.room || !room || p.room === room) ? p : null
2163
2187
  }
@@ -2624,7 +2648,8 @@ export function startServer ({ port = 4321, host = '0.0.0.0', dataDir = null, lo
2624
2648
  const whereTo = async (room, req, pass = '') => {
2625
2649
  const src = replaySource(req)
2626
2650
  // Only someone signed in may have a new session placed (and so started); anyone else finds existing ones only.
2627
- const create = !!(passKey && pass && verifyPass(String(pass), passKey))
2651
+ const who = passKey && pass ? verifyPass(String(pass), passKey) : null
2652
+ const create = !!who && !isPreviewPass(who)
2628
2653
  const w = await cluster.locate(room, { fresh: !!src, create })
2629
2654
  return w.machine && w.machine === src ? { error: ELSEWHERE } : w
2630
2655
  }
@@ -3006,7 +3031,7 @@ export function startServer ({ port = 4321, host = '0.0.0.0', dataDir = null, lo
3006
3031
  const pass = passKey ? verifyPass(header('x-quilt-pass') || url.searchParams.get('pass') || '', passKey) : null
3007
3032
  if (passKey && (!pass || pass.key !== publicKey || (pass.room && pass.room !== name))) return reject(socket, 401, SIGN_IN)
3008
3033
  const person = pass ? pass.name : (url.searchParams.get('name') || '').trim()
3009
- const kind = pass ? (pass.kind === 'agent' ? 'agent' : 'human') : (url.searchParams.get('kind') === 'agent' ? 'agent' : 'human')
3034
+ const kind = pass ? (pass.kind === 'agent' ? 'agent' : isPreviewPass(pass) ? 'preview' : 'human') : (url.searchParams.get('kind') === 'agent' ? 'agent' : 'human')
3010
3035
  // People and agents come from different id spaces, so the kind is part of who they are.
3011
3036
  const account = pass ? `${pass.kind}:${pass.sub}` : ''
3012
3037
  // Checked before the room is touched: a room's creator is recorded by this key (see authorize).