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.
package/RELEASES.md CHANGED
@@ -11,6 +11,18 @@ Format: `## <version> — <YYYY-MM-DD>`, an optional one-line summary, then bull
11
11
  Lead each bullet with a short bold phrase. Inline `code` and **bold** are rendered;
12
12
  nothing else is.
13
13
 
14
+ ## 0.3.188 — 2026-11-23
15
+
16
+ Previews: a codebase's app, running, for everyone in it.
17
+
18
+ - **Previews.** A codebase has a short list of previews in its sidebar. A codebase with a `dev` script has one called App without anyone adding it. Opening it shows the codebase's app running on a cloud machine, inside Quilt, with nothing to set up on anyone's computer.
19
+ - **Pick the branch.** A preview shows main, or the branch of any ticket, from a picker at the top. It shows that branch as it is right now, saved work that nobody has committed included. Each person picks their own, so two people can look at two branches at once, and the page says who else is looking.
20
+ - **It runs only while someone has it open.** The first open takes about half a minute. An app nobody is looking at stops after two minutes, and the machine sleeps ten minutes after the last person leaves.
21
+ - **When an app does not start**, the page shows the last of what it printed and a Try again button.
22
+ - **Links.** A preview can also be a link everyone in the codebase should have at hand, such as the live site. It opens in your browser.
23
+ - **Add, change or remove a preview** with the plus beside Previews and the pencil on a preview's page: its name, and for an app the command, the folder it runs in and its port, all optional.
24
+ - **Only the codebase's members** can open its previews. For now a preview runs Node apps (npm, pnpm, yarn or bun), and the codebase's secrets do not reach it.
25
+
14
26
  ## 0.3.187 — 2026-11-23
15
27
 
16
28
  Projects, and a new layout around them.
package/bin/quilt.js CHANGED
@@ -56,6 +56,7 @@ Usage:
56
56
  quilt doctor [folder] [--watch 30] Check what quilt can see of your Claude Code / Cursor chats
57
57
  quilt mcp Run the MCP server (used by AI tools)
58
58
  quilt ai-vm Run a person's AI on its own cloud machine (Quilt starts it there)
59
+ quilt preview-vm Run a codebase's previews on a cloud machine (Quilt starts it there)
59
60
  quilt hook Claude Code hook (installed by quilt setup; reads the event on stdin)
60
61
 
61
62
  Join options:
@@ -92,6 +93,7 @@ async function main () {
92
93
  case 'setup': return doSetup()
93
94
  case 'mcp': return (await import('../src/mcp.js')).runMcp()
94
95
  case 'ai-vm': try { await (await import('../src/ai-vm.js')).runAiVm() } catch (err) { fail(err.message) } return
96
+ case 'preview-vm': try { await (await import('../src/preview-vm.js')).runPreviewVm() } catch (err) { fail(err.message) } return
95
97
  case 'hook': process.exitCode = await (await import('../src/hooks.js')).runHook(); return
96
98
  case 'status': return status()
97
99
  case 'history': return history()
@@ -242,6 +244,9 @@ async function apiCmd () {
242
244
  },
243
245
  // People's cloud AI machines (FLY_API_TOKEN, AI_VM_APP, AI_VM_IMAGE, AI_VM_REGION); off when not set.
244
246
  fly: (await import('../src/api/fly-machines.js')).flyFromEnv(env),
247
+ // Previews of a codebase on cloud machines (PREVIEW_FLY_TOKEN, PREVIEW_APP, PREVIEW_IMAGE; plans/previews.md); off when not set.
248
+ previewFly: (await import('../src/api/fly-machines.js')).previewFlyFromEnv(env),
249
+ ...(env.PREVIEW_DOMAIN ? { previewDomain: env.PREVIEW_DOMAIN } : {}),
245
250
  fileStore: makeFileStore(
246
251
  { storageUrl: env.QUILT_STORAGE_URL, storageKey: env.QUILT_STORAGE_KEY, storageBucket: env.QUILT_STORAGE_WS_BUCKET },
247
252
  values.memory ? fs.mkdtempSync(path.join(os.tmpdir(), 'quilt-api-files-')) : path.resolve(env.QUILT_API_DATA || './quilt-api-data')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heyquilt",
3
- "version": "0.3.187",
3
+ "version": "0.3.188",
4
4
  "description": "Real-time, tool-agnostic pair vibe coding: sync a project folder live between collaborators using any AI coding tool.",
5
5
  "author": {
6
6
  "name": "Daniel Carmichael",
package/src/account.js CHANGED
@@ -607,6 +607,14 @@ export async function aiVmDisconnect ({ token, api = apiUrl(), fetch: fetchImpl
607
607
  * Voice (plans/voice.md): the servers a call connects through, { iceServers, expiresAt }. With
608
608
  * Cloudflare set up on the API, short-lived TURN credentials for networks that block a direct line.
609
609
  */
610
+ /**
611
+ * A member opened a preview of codebase `room`, or still has one open (asked again each minute):
612
+ * the codebase's preview machine is made or woken. { state, machine, domain, ticket, idleMs }.
613
+ */
614
+ export async function openPreview ({ token, room, api = apiUrl(), fetch: fetchImpl = globalThis.fetch }) {
615
+ return call(fetchImpl, api, 'POST', `/v1/sessions/${encodeURIComponent(room)}/preview/open`, {}, token)
616
+ }
617
+
610
618
  export async function voiceIce ({ token, api = apiUrl(), fetch: fetchImpl = globalThis.fetch }) {
611
619
  return call(fetchImpl, api, 'GET', '/v1/voice/ice', null, token)
612
620
  }
@@ -2,6 +2,9 @@
2
2
  // volume per person, in the app AI_VM_APP (never the relay's). Plain fetch, so tests point it
3
3
  // at a fake server. See https://fly.io/docs/machines/api/.
4
4
  //
5
+ // Preview machines (routes/preview.js, plans/previews.md) use the same client on an app of their
6
+ // own (PREVIEW_APP): one machine and one volume per codebase, with a public https service.
7
+ //
5
8
  // Spares: machines made ahead of anyone connecting, with their volume, running `quilt ai-vm` as
6
9
  // a spare: it reads the AI tools into memory (a tool read cold off the disk takes up to 18 s
7
10
  // before it prints anything) and is then suspended, memory and all, which costs only its disk.
@@ -14,6 +17,18 @@ export const GUEST = { cpu_kind: 'shared', cpus: 2, memory_mb: 2048 }
14
17
  export const VOLUME_GB = 5
15
18
  export const SPARE = 'ai-vm-spare'
16
19
  const OWNED = 'ai-vm'
20
+ export const PREVIEW = 'preview'
21
+ export const PREVIEW_VOLUME_GB = 10
22
+ // A preview machine's way in (src/preview/proxy.js, port 8080) over https. Fly never starts or
23
+ // stops one by itself for traffic: the API wakes it when someone opens a preview and suspends it
24
+ // when nobody is looking. (A request Fly is told to hand to a sleeping machine does wake it.)
25
+ export const PREVIEW_SERVICES = [{
26
+ protocol: 'tcp',
27
+ internal_port: 8080,
28
+ autostart: false,
29
+ autostop: 'off',
30
+ ports: [{ port: 443, handlers: ['tls', 'http'] }, { port: 80, handlers: ['http'], force_https: true }]
31
+ }]
17
32
  const ID = /^[A-Za-z0-9_-]{1,64}$/
18
33
 
19
34
  const needId = (id, what) => {
@@ -30,16 +45,18 @@ export function flyMachines ({ token, app, image, region = 'iad', spares = 0, ba
30
45
 
31
46
  /**
32
47
  * The image's own command, restarted on a crash. A spare's metadata says so, with the hash of
33
- * the key it asks the API for its claim with (`spareHash`).
48
+ * the key it asks the API for its claim with (`spareHash`). `services` gives it public ports
49
+ * (a preview machine's); `metadata` replaces the cloud AI's labels.
34
50
  */
35
- const config = ({ volumeId, env = {}, spareHash = '' }) => ({
51
+ const config = ({ volumeId, env = {}, spareHash = '', services = null, metadata = null }) => ({
36
52
  image,
37
53
  env,
38
54
  guest: GUEST,
39
55
  mounts: [{ volume: needId(volumeId, 'volume'), path: '/data' }],
40
56
  restart: { policy: 'on-failure', max_retries: 5 },
41
57
  auto_destroy: false,
42
- metadata: spareHash ? { quilt: SPARE, quilt_spare: spareHash } : { quilt: OWNED }
58
+ ...(services ? { services } : {}),
59
+ metadata: metadata || (spareHash ? { quilt: SPARE, quilt_spare: spareHash } : { quilt: OWNED })
43
60
  })
44
61
 
45
62
  // Fly lets a few writes through at once, then answers 429 for a moment: those are asked again.
@@ -81,7 +98,22 @@ export function flyMachines ({ token, app, image, region = 'iad', spares = 0, ba
81
98
  /** A new volume for one person's machine; encrypted, in this app's region. */
82
99
  createVolume: async ({ name, sizeGb = VOLUME_GB }) => call('POST', '/volumes', { name, region, size_gb: sizeGb, encrypted: true }),
83
100
  /** A machine running the AI image with the volume as /data. It restarts on a crash, never on its own after a stop. */
84
- createMachine: async ({ name, volumeId, env = {}, spareHash = '' }) => call('POST', '/machines', { name, region, config: config({ volumeId, env, spareHash }) }),
101
+ createMachine: async ({ name, volumeId, env = {}, spareHash = '', services = null, metadata = null }) => call('POST', '/machines', { name, region, config: config({ volumeId, env, spareHash, services, metadata }) }),
102
+ /** This app's machines labelled `kind` (metadata `quilt`): { id, volumeId, image, state, room, region, createdAt }. */
103
+ listKind: async (kind) => {
104
+ const list = await call('GET', `/machines?metadata.quilt=${encodeURIComponent(kind)}`)
105
+ return (Array.isArray(list) ? list : [])
106
+ .filter((m) => m && m.config && m.config.metadata && m.config.metadata.quilt === kind && ID.test(String(m.id)))
107
+ .map((m) => ({
108
+ id: m.id,
109
+ volumeId: (m.config.mounts && m.config.mounts[0] && m.config.mounts[0].volume) || '',
110
+ image: m.config.image || '',
111
+ state: m.state || '',
112
+ room: String(m.config.metadata.quilt_room || ''),
113
+ region: m.region || region,
114
+ createdAt: Date.parse(m.created_at || '') || 0
115
+ }))
116
+ },
85
117
  /** The spare machines there are now: { id, volumeId, image, state, hash, region, createdAt }. */
86
118
  listSpares: async () => {
87
119
  const list = await call('GET', `/machines?metadata.quilt=${SPARE}`)
@@ -141,3 +173,13 @@ export function flyFromEnv (env = process.env) {
141
173
  const spares = env.AI_VM_SPARES === undefined || env.AI_VM_SPARES === '' ? 2 : Math.max(0, Math.min(20, Math.floor(Number(env.AI_VM_SPARES)) || 0))
142
174
  return flyMachines({ token: env.FLY_API_TOKEN, app: env.AI_VM_APP, image: env.AI_VM_IMAGE, region: env.AI_VM_REGION || 'iad', spares })
143
175
  }
176
+
177
+ /**
178
+ * The client for preview machines (plans/previews.md), or null when previews aren't set up here:
179
+ * PREVIEW_FLY_TOKEN (a key for that app alone), PREVIEW_APP, PREVIEW_IMAGE and PREVIEW_REGION.
180
+ */
181
+ export function previewFlyFromEnv (env = process.env) {
182
+ const token = env.PREVIEW_FLY_TOKEN || ''
183
+ if (!token || !env.PREVIEW_APP || !env.PREVIEW_IMAGE) return null
184
+ return flyMachines({ token, app: env.PREVIEW_APP, image: env.PREVIEW_IMAGE, region: env.PREVIEW_REGION || 'iad' })
185
+ }
@@ -51,6 +51,7 @@ export function createMemoryStore ({ now = Date.now } = {}) {
51
51
  const agentPlacements = new Map(); const workspaceAgentOverrides = new Map()
52
52
  const sessionAgentExclusions = new Map(); const agentWebhooks = new Map()
53
53
  const aiVms = new Map() // user id -> the person's cloud AI machine (ai_vms)
54
+ const previewMachines = new Map() // room -> the codebase's preview machine (preview_machines)
54
55
  // The relay on many machines (20261017100000_relay_cluster.sql, 20261018100000_relay_autoscale.sql).
55
56
  const relayMachines = new Map(); const relayRooms = new Map(); const relayJobs = new Map()
56
57
  const apiLeases = new Map() // name -> { holder, expiresAt } (api_leases)
@@ -115,7 +116,7 @@ export function createMemoryStore ({ now = Date.now } = {}) {
115
116
  // Deleting an account takes the sessions it owns (with everyone's visits in them) and its
116
117
  // own visits, like delete_account_activity.
117
118
  const dropActivity = (accounts) => {
118
- for (const [room, s] of relaySessions) if (accounts.includes(s.ownerAccount)) relaySessions.delete(room)
119
+ for (const [room, s] of relaySessions) if (accounts.includes(s.ownerAccount)) { relaySessions.delete(room); previewMachines.delete(room) }
119
120
  for (const [id, v] of visits) if (accounts.includes(v.account) || !relaySessions.has(v.room)) visits.delete(id)
120
121
  dropOrphans()
121
122
  }
@@ -602,7 +603,7 @@ export function createMemoryStore ({ now = Date.now } = {}) {
602
603
  },
603
604
  async pruneActivity ({ before, seenBefore }) {
604
605
  for (const [id, v] of visits) if (v.endedAt != null && v.endedAt < before) visits.delete(id)
605
- for (const [room, s] of relaySessions) if (s.lastActiveAt < before && !all(visits, (v) => v.room === room).length) relaySessions.delete(room)
606
+ for (const [room, s] of relaySessions) if (s.lastActiveAt < before && !all(visits, (v) => v.room === room).length) { relaySessions.delete(room); previewMachines.delete(room) }
606
607
  for (const [id, at] of seenEvents) if (at < seenBefore) seenEvents.delete(id)
607
608
  dropOrphans()
608
609
  },
@@ -1114,6 +1115,24 @@ export function createMemoryStore ({ now = Date.now } = {}) {
1114
1115
  },
1115
1116
  async deleteAiVm (userId) { return aiVms.delete(userId) },
1116
1117
 
1118
+ // A codebase's preview machine (see 20261123000000_preview_machines.sql): one per codebase.
1119
+ async createPreviewMachine ({ room, owner, keyHash, region = '' }) {
1120
+ if (!relaySessions.has(room)) throw fkViolation('codebase', 'does not exist')
1121
+ if (previewMachines.has(room)) throw duplicate('preview machine')
1122
+ const row = { room, owner, keyHash, machineId: null, volumeId: null, region, state: 'creating', error: '', lastOpenAt: null, lastBusyAt: null, lastReportAt: null, createdAt: now(), updatedAt: now() }
1123
+ previewMachines.set(room, row); return copy(row)
1124
+ },
1125
+ async previewMachineOf (room) { return copy(previewMachines.get(room)) },
1126
+ async previewMachineByKey (keyHash) { return copy(all(previewMachines, (m) => !!keyHash && m.keyHash === keyHash)[0]) },
1127
+ async listPreviewMachines () { return [...previewMachines.values()].map(copy) },
1128
+ async updatePreviewMachine (room, patch) {
1129
+ const row = previewMachines.get(room)
1130
+ if (!row) return null
1131
+ Object.assign(row, structuredClone(patch), { updatedAt: now() })
1132
+ return copy(row)
1133
+ },
1134
+ async deletePreviewMachine (room) { return previewMachines.delete(room) },
1135
+
1117
1136
  // Workspace files (see 20261005000000_workspace_files.sql).
1118
1137
  async createWorkspaceFile ({ workspaceId, path, kind, size = 0, mime = '', sha256 = '', objectKey = '', note = '', uploadedBy }) {
1119
1138
  if (!workspaces.has(workspaceId)) throw fkViolation('workspace', 'does not exist')
@@ -0,0 +1,240 @@
1
+ // Previews of a codebase (plans/previews.md): one Fly machine and one volume per codebase, in an
2
+ // app of their own (PREVIEW_APP), running the codebase's app for whoever has a preview open.
3
+ // These routes are a member's (open a preview, and say each minute that it is still open) and
4
+ // the machine's own (a pass to join its codebase as a viewer, its reports). The leading API
5
+ // machine also looks over every preview machine each minute: one nobody has open is suspended,
6
+ // one nobody opened for two weeks is removed with its disk.
7
+ //
8
+ // A member gets the machine's id and a ticket (src/preview/ticket.js); the app puts both into
9
+ // the preview's address (src/preview/address.js). Nothing here serves a preview: the machine does.
10
+ import crypto from 'node:crypto'
11
+ import { HttpError } from '../http.js'
12
+ import { newToken, hashToken } from '../tokens.js'
13
+ import { isAgentKey } from '../agent-auth.js'
14
+ import { sessionMember } from '../secrets-access.js'
15
+ import { signPass, passPublicKey, PASS_VERSION, PASS_TTL_MS } from '../../passes.js'
16
+ import { parsePublicKey } from '../../identity.js'
17
+ import { signPreviewTicket, TICKET_TTL_MS } from '../../preview/ticket.js'
18
+ import { previewDomain } from '../../preview/address.js'
19
+ import { PREVIEW, PREVIEW_SERVICES, PREVIEW_VOLUME_GB } from '../fly-machines.js'
20
+ import { HOSTED_RELAY } from '../../settings.js'
21
+
22
+ // Nobody has had it open for this long: suspended. The app says "still open" each minute.
23
+ export const PREVIEW_IDLE_MS = 10 * 60 * 1000
24
+ // Nobody opened it for this long: removed with its disk. The next open makes a new one.
25
+ export const PREVIEW_UNUSED_MS = 14 * 24 * 60 * 60 * 1000
26
+ // How many preview machines may be awake at once for one owner's codebases.
27
+ export const PREVIEW_PER_OWNER = 3
28
+ export const PREVIEW_SWEEP_MS = 60 * 1000
29
+ // A machine told to start is given this long to come up before it is started again.
30
+ const STARTING_MS = 2 * 60 * 1000
31
+ // A record that never got its machine, or a machine that never got its record, after this long: removed.
32
+ const STUCK_MS = 15 * 60 * 1000
33
+ const ROOM = /^[A-Za-z0-9_-]{1,64}$/
34
+ const AWAKE = ['creating', 'starting', 'running']
35
+ // What the machine may do in its codebase: read every file, write nothing, say nothing.
36
+ const VIEWER = Object.freeze({ files: 'view', folders: [], foldersExcept: [], talk: false })
37
+
38
+ export function previewRoutes ({ store, person, agentAuth, bearer, now, apiUrl, log = () => {}, makeLimiter, fly = null, passKey = '', domain, relayUrl = HOSTED_RELAY, leads = () => true, sweepEveryMs = PREVIEW_SWEEP_MS, idleMs = PREVIEW_IDLE_MS, unusedMs = PREVIEW_UNUSED_MS, perOwner = PREVIEW_PER_OWNER }) {
39
+ const dom = previewDomain(domain)
40
+ const on = !!(fly && passKey)
41
+ const needOn = () => { if (!on) throw new HttpError(503, "Previews aren't set up on this server.") }
42
+ // A page with a preview open asks once a minute; a few previews and a reload or two fit easily.
43
+ const limitOpens = makeLimiter(30, 'too many tries; wait a minute and try again', { keyOf: (account) => account })
44
+
45
+ /** The member calling (a person, or an agent with its key), and the codebase. Anyone else: 404. */
46
+ async function member (req, room) {
47
+ let account = ''
48
+ let agent = null
49
+ if (isAgentKey(bearer(req))) {
50
+ agent = (await agentAuth.agentFromRequest(req)).agent
51
+ account = `agent:${agent.id}`
52
+ } else account = `person:${(await person(req)).userId}`
53
+ const session = ROOM.test(room) ? await store.sessionByRoom(room) : null
54
+ if (!session || !(await sessionMember(store, room, account, { agent }))) throw new HttpError(404, 'no such codebase')
55
+ return { account, session }
56
+ }
57
+
58
+ /** Whose codebase it is, for the limit: its project's owner (a person or a team), else its own. */
59
+ async function ownerOf (session) {
60
+ const ws = session.workspaceId ? await store.workspaceById(session.workspaceId) : null
61
+ if (ws && ws.ownerUserId) return `person:${ws.ownerUserId}`
62
+ if (ws && ws.orgId) return `org:${ws.orgId}`
63
+ return session.ownerAccount || `room:${session.room}`
64
+ }
65
+
66
+ async function needRoom (pm) {
67
+ const awake = (await store.listPreviewMachines()).filter((m) => m.owner === pm.owner && m.room !== pm.room && AWAKE.includes(m.state))
68
+ if (awake.length >= perOwner) throw new HttpError(429, `Previews are running for ${perOwner} of this owner's codebases, which is the most at once. One stops ten minutes after everyone has closed it.`)
69
+ }
70
+
71
+ /** The codebase's machine and disk, made now. Two people opening at once: the second waits on the first's. */
72
+ async function make (session) {
73
+ const room = session.room
74
+ const key = newToken('qp_')
75
+ const owner = await ownerOf(session)
76
+ await needRoom({ owner, room })
77
+ try {
78
+ await store.createPreviewMachine({ room, owner, keyHash: hashToken(key), region: fly.region })
79
+ } catch (err) {
80
+ if (err && err.code === '23505') return store.previewMachineOf(room)
81
+ throw err
82
+ }
83
+ const short = crypto.createHash('sha256').update(room).digest('hex').slice(0, 20)
84
+ try {
85
+ const volume = await fly.createVolume({ name: `pv_${short}`, sizeGb: PREVIEW_VOLUME_GB })
86
+ try {
87
+ const env = { QUILT_API: apiUrl, QUILT_RELAY: relayUrl, QUILT_PREVIEW_ROOM: room, QUILT_PREVIEW_KEY: key, QUILT_PASS_PUBLIC_KEY: passPublicKey(passKey), QUILT_PREVIEW_DOMAIN: dom, HOME: '/data/home' }
88
+ const m = await fly.createMachine({ name: `pv-${short}`, volumeId: volume.id, env, services: PREVIEW_SERVICES, metadata: { quilt: PREVIEW, quilt_room: room } })
89
+ log(`preview ${room}: made ${m.id}`)
90
+ return await store.updatePreviewMachine(room, { machineId: m.id, volumeId: volume.id, region: m.region || volume.region || fly.region, state: 'starting', error: '' })
91
+ } catch (err) {
92
+ await fly.destroyVolume(volume.id).catch(() => {})
93
+ throw err
94
+ }
95
+ } catch (err) {
96
+ log(`preview ${room}: could not make it: ${err.message}`)
97
+ await store.deletePreviewMachine(room).catch(() => {})
98
+ throw new HttpError(502, `Couldn't start the preview. ${err.message}`)
99
+ }
100
+ }
101
+
102
+ /** Resumes a sleeping machine (on the current image, when it was made on an older one). */
103
+ async function wake (pm) {
104
+ if (!pm.machineId) return pm // being made right now, by someone else's open
105
+ if (pm.state === 'running') return pm
106
+ if (pm.state === 'starting' && pm.updatedAt && now() - pm.updatedAt < STARTING_MS) return pm
107
+ await needRoom(pm)
108
+ try {
109
+ try {
110
+ if (await fly.moveToImage(pm.machineId)) log(`preview ${pm.room}: moved to ${fly.image}`)
111
+ } catch (err) { log(`preview ${pm.room}: could not move it to the new image: ${err.message}`) }
112
+ await fly.start(pm.machineId)
113
+ log(`preview ${pm.room}: woken`)
114
+ return (await store.updatePreviewMachine(pm.room, { state: 'starting', error: '' })) || pm
115
+ } catch (err) {
116
+ log(`preview ${pm.room}: could not wake it: ${err.message}`)
117
+ // Fly no longer has it (removed by hand): the record goes, and the next open makes a new one.
118
+ if (err.status === 404) { await remove(pm).catch(() => {}); throw new HttpError(502, "Couldn't start the preview. Open it again.") }
119
+ throw new HttpError(502, `Couldn't start the preview. ${err.message}`)
120
+ }
121
+ }
122
+
123
+ /** Deletes a codebase's machine, its disk and its record. Fly answering "already gone" is fine. */
124
+ async function remove (pm) {
125
+ if (pm.machineId) await fly.destroyMachine(pm.machineId)
126
+ if (pm.volumeId) await fly.destroyVolume(pm.volumeId)
127
+ await store.deletePreviewMachine(pm.room)
128
+ }
129
+
130
+ /**
131
+ * Looks over every preview machine: one awake with nobody looking is suspended, one unused for
132
+ * two weeks is removed, and what Fly and the records disagree on is put right. Fly is asked
133
+ * what is running, so a machine woken by a stray request, or one whose program never reports,
134
+ * still goes back to sleep. One run at a time, on the leading API machine only.
135
+ */
136
+ let sweeping = null
137
+ function sweep () {
138
+ if (!on || !leads()) return Promise.resolve()
139
+ if (sweeping) return sweeping
140
+ sweeping = (async () => {
141
+ const there = new Map((await fly.listKind(PREVIEW)).map((m) => [m.id, m]))
142
+ for (const pm of await store.listPreviewMachines()) {
143
+ try {
144
+ if (!pm.machineId) {
145
+ if (now() - pm.createdAt > STUCK_MS) await store.deletePreviewMachine(pm.room)
146
+ continue
147
+ }
148
+ const m = there.get(pm.machineId)
149
+ there.delete(pm.machineId)
150
+ const last = Math.max(pm.lastOpenAt || 0, pm.lastBusyAt || 0, pm.createdAt || 0)
151
+ if (!m || now() - last > unusedMs) {
152
+ await remove(pm)
153
+ log(`preview ${pm.room}: removed (${m ? 'not opened for two weeks' : 'its machine is gone'})`)
154
+ continue
155
+ }
156
+ if (m.state === 'started') {
157
+ if (now() - last > idleMs) {
158
+ // A machine too big to suspend is stopped: it starts cold, but costs nothing meanwhile.
159
+ await fly.suspend(pm.machineId).catch(() => fly.stop(pm.machineId))
160
+ await store.updatePreviewMachine(pm.room, { state: 'suspended' })
161
+ log(`preview ${pm.room}: nobody has it open; suspended`)
162
+ } else if (pm.state !== 'running') await store.updatePreviewMachine(pm.room, { state: 'running' })
163
+ } else if (['stopped', 'suspended'].includes(m.state) && pm.state !== 'suspended' && !(pm.state === 'starting' && now() - pm.updatedAt < STARTING_MS)) {
164
+ await store.updatePreviewMachine(pm.room, { state: 'suspended' })
165
+ }
166
+ } catch (err) { log(`preview ${pm.room}: ${err.message}`) }
167
+ }
168
+ // A machine with no record (its codebase was deleted): removed with its disk.
169
+ for (const m of there.values()) {
170
+ if (!m.createdAt || Date.now() - m.createdAt < STUCK_MS) continue
171
+ await fly.destroyMachine(m.id).catch((err) => log(`preview machine ${m.id}: could not delete it: ${err.message}`))
172
+ if (m.volumeId) await fly.destroyVolume(m.volumeId).catch(() => {})
173
+ log(`preview machine ${m.id}: removed (no codebase has it)`)
174
+ }
175
+ })().catch((err) => log(`previews: ${err.message}`)).finally(() => { sweeping = null })
176
+ return sweeping
177
+ }
178
+ let timer = null
179
+ if (on && sweepEveryMs > 0) {
180
+ timer = setInterval(() => { sweep() }, sweepEveryMs)
181
+ timer.unref?.()
182
+ }
183
+
184
+ /** The preview machine calling, by the key it was made with. */
185
+ async function machine (req) {
186
+ const key = bearer(req)
187
+ const pm = key.startsWith('qp_') ? await store.previewMachineByKey(hashToken(key)) : null
188
+ if (!pm) throw new HttpError(401, 'a preview machine\'s key is needed')
189
+ return pm
190
+ }
191
+
192
+ const routes = [
193
+ // A member opened a preview, or still has one open (the app asks again each minute). The
194
+ // codebase's machine is made the first time and woken when asleep. The answer is what the
195
+ // app builds the preview's address from: the machine, the domain and a ticket for this member.
196
+ ['POST', /^\/v1\/sessions\/([^/]+)\/preview\/open$/, async (req, body, [room]) => {
197
+ const { account, session } = await member(req, room)
198
+ needOn()
199
+ limitOpens(account)
200
+ let pm = await store.previewMachineOf(room)
201
+ pm = pm ? await wake(pm) : await make(session)
202
+ if (!pm) throw new HttpError(502, "Couldn't start the preview. Open it again.")
203
+ pm = (await store.updatePreviewMachine(room, { lastOpenAt: now() })) || pm
204
+ return {
205
+ state: pm.state,
206
+ machine: pm.machineId || '',
207
+ domain: dom,
208
+ ticket: signPreviewTicket({ room, sub: account, now: now() }, passKey),
209
+ ticketExpiresAt: now() + TICKET_TTL_MS,
210
+ idleMs
211
+ }
212
+ }],
213
+
214
+ // The machine joins its codebase with this: a pass for that one room, as a viewer that is
215
+ // no person and no agent (kind "preview"), for the identity key the machine made for itself.
216
+ ['POST', /^\/v1\/preview\/pass$/, async (req, body) => {
217
+ const pm = await machine(req)
218
+ needOn()
219
+ const key = typeof body.publicKey === 'string' ? body.publicKey : ''
220
+ if (!key || !parsePublicKey(key)) throw new HttpError(400, 'publicKey: the machine\'s identity key')
221
+ const iat = now()
222
+ const exp = iat + PASS_TTL_MS
223
+ return { pass: signPass({ v: PASS_VERSION, sub: pm.room, kind: 'preview', name: 'Preview', key, room: pm.room, iat, access: VIEWER, exp }, passKey), expiresAt: exp, room: pm.room, relay: relayUrl }
224
+ }],
225
+
226
+ // The machine says it is up, and whether anyone asked it for a page lately (`busy`): a tab
227
+ // left open in a browser counts as someone looking, as a preview open in the app does.
228
+ ['POST', /^\/v1\/preview\/report$/, async (req, body) => {
229
+ const pm = await machine(req)
230
+ const patch = { state: 'running', error: '', lastReportAt: now() }
231
+ if (body.busy === true) patch.lastBusyAt = now()
232
+ await store.updatePreviewMachine(pm.room, patch)
233
+ return { ok: true, idleMs }
234
+ }]
235
+ ]
236
+
237
+ const close = () => { if (timer) clearInterval(timer) }
238
+
239
+ return { routes, on, sweep, close }
240
+ }
package/src/api/server.js CHANGED
@@ -42,6 +42,7 @@ import { roomAccessFrom } from './access.js'
42
42
  import { joiningRoom, sessionArg } from '../mcp-room.js'
43
43
  import { issueRoutes } from './routes/issues.js'
44
44
  import { aiVmRoutes, cloudAiOf, WAIT_MS as AI_VM_WAIT_MS } from './routes/ai-vm.js'
45
+ import { previewRoutes } from './routes/preview.js'
45
46
  import { aiName } from '../persona.js'
46
47
  import { routeName, cleanEvent } from './issues.js'
47
48
  import { secretRoutes } from './routes/secrets.js'
@@ -76,7 +77,7 @@ const MCP_TIMEOUT_MS = 30 * 1000
76
77
  // a change to its grant reaches it as soon as it reaches a connected app.
77
78
  const PASS_REUSE_MARGIN_MS = 5 * 60 * 1000
78
79
 
79
- export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, siteUrl, apiUrl = 'https://api.heyquilt.com', mailer = { send: async () => { throw new Error('no mailer configured') } }, now = Date.now, log = () => {}, startLimit = 10, inviteLimit = 10, inviteSendLimit = 20, tokenLimit = 30, joinLimit = 20, trustProxy = false, maxStartKeys = 10_000, passKey = '', passLimit = 60, relayUrl = HOSTED_RELAY, mcpLimit = 600, reportKey = '', reportLimit = 10, slowMs = 2000, pruneEveryMs = 60 * 60 * 1000, keepEventsMs = 30 * 24 * 60 * 60 * 1000, keepIssuesMs = 90 * 24 * 60 * 60 * 1000, pruneStartMs = 10_000, relaySecret = '', workspaces = false, fileStore = null, maxFileBytes = 500 * 1024 * 1024, workspaceQuotaBytes = 5 * 1024 * 1024 * 1024, maxWorkspaceFiles = 2000, webhookFetch = globalThis.fetch, webhookLookup, allowLocalWebhooks = false, github = null, githubFetch = globalThis.fetch, fly = null, aiVmWaitMs = AI_VM_WAIT_MS, aiVmSpareSuspendMs, relayFetch = null, relayFly = null, heavy = null, relayTargets = null, clusterTiming = {}, vaultSecret = '', vaultUrl = 'https://vault.heyquilt.com', allowLocalUpstreams = false, secretWaitMs, voice = {}, voiceFetch = globalThis.fetch, voiceSocket, mail = {}, mailFetch = globalThis.fetch, composioKey = '', composioFetch = globalThis.fetch, appCallsPerDay = 500, appWaitMs, machineId = '', leaderTiming = {}, autoscaleTiming = {}, exit = () => process.exit(0), apiFly = null, maxMachines, notifyEveryMs = NOTIFY_EVERY_MS }) {
80
+ export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, siteUrl, apiUrl = 'https://api.heyquilt.com', mailer = { send: async () => { throw new Error('no mailer configured') } }, now = Date.now, log = () => {}, startLimit = 10, inviteLimit = 10, inviteSendLimit = 20, tokenLimit = 30, joinLimit = 20, trustProxy = false, maxStartKeys = 10_000, passKey = '', passLimit = 60, relayUrl = HOSTED_RELAY, mcpLimit = 600, reportKey = '', reportLimit = 10, slowMs = 2000, pruneEveryMs = 60 * 60 * 1000, keepEventsMs = 30 * 24 * 60 * 60 * 1000, keepIssuesMs = 90 * 24 * 60 * 60 * 1000, pruneStartMs = 10_000, relaySecret = '', workspaces = false, fileStore = null, maxFileBytes = 500 * 1024 * 1024, workspaceQuotaBytes = 5 * 1024 * 1024 * 1024, maxWorkspaceFiles = 2000, webhookFetch = globalThis.fetch, webhookLookup, allowLocalWebhooks = false, github = null, githubFetch = globalThis.fetch, fly = null, aiVmWaitMs = AI_VM_WAIT_MS, aiVmSpareSuspendMs, relayFetch = null, relayFly = null, heavy = null, relayTargets = null, clusterTiming = {}, vaultSecret = '', vaultUrl = 'https://vault.heyquilt.com', allowLocalUpstreams = false, secretWaitMs, voice = {}, voiceFetch = globalThis.fetch, voiceSocket, mail = {}, mailFetch = globalThis.fetch, composioKey = '', composioFetch = globalThis.fetch, appCallsPerDay = 500, appWaitMs, machineId = '', leaderTiming = {}, autoscaleTiming = {}, exit = () => process.exit(0), apiFly = null, maxMachines, notifyEveryMs = NOTIFY_EVERY_MS, previewFly = null, previewDomain, previewTiming = {} }) {
80
81
  // PASS_SIGNING_KEY. A bad one should stop the API at start, not fail every pass later.
81
82
  if (passKey) passPublicKey(passKey)
82
83
  const site = String(siteUrl || '').replace(/\/+$/, '')
@@ -253,7 +254,7 @@ export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, sit
253
254
  ['GET', /^\/healthz$/, async () => ({ ok: true })],
254
255
 
255
256
  // Which optional parts this API has on, for the app and the MCPs to decide what to show. Public.
256
- ['GET', /^\/v1\/features$/, async () => ({ workspaces: !!workspaces, secrets: !!vaultSecret, connections: !!composioKey })],
257
+ ['GET', /^\/v1\/features$/, async () => ({ workspaces: !!workspaces, secrets: !!vaultSecret, connections: !!composioKey, previews: !!(previewFly && passKey) })],
257
258
 
258
259
  ['POST', /^\/v1\/device\/start$/, async (req, body) => {
259
260
  limitStarts(req)
@@ -441,6 +442,9 @@ export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, sit
441
442
  // A person's AI on its own cloud machine (routes/ai-vm.js): off (503) without Fly set up. Only the leader runs it.
442
443
  const aiVm = aiVmRoutes({ ...ctx, relayUrl, fly, waitMs: aiVmWaitMs, spareSuspendMs: aiVmSpareSuspendMs, leads: lead.leads })
443
444
  routes.push(...aiVm.routes)
445
+ // Previews of a codebase on a cloud machine of its own (routes/preview.js): off (503) without their Fly app set up.
446
+ const previews = previewRoutes({ ...ctx, makeLimiter, fly: previewFly, passKey, domain: previewDomain, relayUrl, leads: lead.leads, ...previewTiming })
447
+ routes.push(...previews.routes)
444
448
  // Email notices people turned on in the website's Settings › Notifications (notify.js): the leader sends them.
445
449
  const notices = notifier({ store, mailer, ask: nowAsker({ store, cluster, relayOn: !!(relay && relaySecret), log }), overview: (account, t) => overviewOf(store, account, 'UTC', t), now, log, site, leads: lead.leads, everyMs: notifyEveryMs })
446
450
  if (notifyEveryMs > 0) notices.start()
@@ -730,7 +734,7 @@ export function startApi ({ port = 0, host = '127.0.0.1', store, verifyUser, sit
730
734
 
731
735
  return new Promise((resolve) => server.listen(port, host, () => {
732
736
  const p = server.address().port
733
- resolve({ port: p, url: `http://${host}:${p}`, cluster, lead, scaler, grow, fillSpares: aiVm.fillSpares, notices, close: () => { clearInterval(prune); clearTimeout(firstPrune); aiVm.close(); notices.stop(); lead.close(); scaler.close(); grow.close(); return new Promise((r) => server.close(r)) }, startKeys: () => limitStarts.size(), sweepFiles: (at) => wsFiles.sweep(at), flushWebhooks, githubReady })
737
+ resolve({ port: p, url: `http://${host}:${p}`, cluster, lead, scaler, grow, fillSpares: aiVm.fillSpares, sweepPreviews: previews.sweep, notices, close: () => { clearInterval(prune); clearTimeout(firstPrune); aiVm.close(); previews.close(); notices.stop(); lead.close(); scaler.close(); grow.close(); return new Promise((r) => server.close(r)) }, startKeys: () => limitStarts.size(), sweepFiles: (at) => wsFiles.sweep(at), flushWebhooks, githubReady })
734
738
  }))
735
739
  }
736
740
 
@@ -39,6 +39,7 @@ const AGENT_PLACEMENT = 'agent_id, reach, workspace_ids, sessions, access, scope
39
39
  const WORKSPACE_AGENT_OVERRIDE = 'workspace_id, agent_id, sessions, excluded'
40
40
  const SESSION_AGENT_EXCLUSION = 'room, agent_id, excluded_by, created_at'
41
41
  const AGENT_WEBHOOK = 'agent_id, url, secret, created_at, updated_at'
42
+ const PREVIEW_MACHINE = 'room, owner, key_hash, machine_id, volume_id, region, state, error, last_open_at, last_busy_at, last_report_at, created_at, updated_at'
42
43
  const AI_VM = 'user_id, tool, model, prompt, cap, name, color, tasks, files, wake, sessions_mode, rooms, agent_id, invite_id, machine_id, volume_id, region, state, error, signed_in, usage_today, sessions, last_report_at, created_at, updated_at'
43
44
  const RELAY_MACHINE = 'id, region, capacity, state, dedicated_room, load, hot_at, over_at, empty_at, hello_at, reported_at, created_at'
44
45
  const RELAY_ROOM = 'room, machine_id, state, stats, busy_minutes, heavy, placed_at, reported_at, moved_at'
@@ -618,6 +619,21 @@ export function createSupabaseStore ({ url, serviceKey, client, fetch: authFetch
618
619
  return (await one(db.from('ai_vms').delete().eq('user_id', userId).select('user_id'))).length > 0
619
620
  },
620
621
 
622
+ // A codebase's preview machine (see 20261123000000_preview_machines.sql): one per codebase.
623
+ async createPreviewMachine ({ room, owner, keyHash, region = '' }) {
624
+ return rowFrom(await one(db.from('preview_machines').insert({ room, owner, key_hash: keyHash, region }).select(PREVIEW_MACHINE).single()))
625
+ },
626
+ async previewMachineOf (room) { return rowFrom(await one(db.from('preview_machines').select(PREVIEW_MACHINE).eq('room', room).maybeSingle())) },
627
+ async previewMachineByKey (keyHash) { return keyHash ? rowFrom(await one(db.from('preview_machines').select(PREVIEW_MACHINE).eq('key_hash', keyHash).maybeSingle())) : null },
628
+ async listPreviewMachines () { return (await one(db.from('preview_machines').select(PREVIEW_MACHINE).order('created_at'))).map(rowFrom) },
629
+ async updatePreviewMachine (room, patch) {
630
+ const set = toSnake({ ...patch, lastOpenAt: ts(patch.lastOpenAt), lastBusyAt: ts(patch.lastBusyAt), lastReportAt: ts(patch.lastReportAt) })
631
+ return rowFrom(await one(db.from('preview_machines').update({ ...set, updated_at: new Date().toISOString() }).eq('room', room).select(PREVIEW_MACHINE).maybeSingle()))
632
+ },
633
+ async deletePreviewMachine (room) {
634
+ return (await one(db.from('preview_machines').delete().eq('room', room).select('room'))).length > 0
635
+ },
636
+
621
637
  // Workspace files (see 20261005000000_workspace_files.sql).
622
638
  async createWorkspaceFile ({ workspaceId, path, kind, size = 0, mime = '', sha256 = '', objectKey = '', note = '', uploadedBy }) {
623
639
  return rowFrom(await one(db.from('workspace_files').insert({ workspace_id: workspaceId, path, kind, size, mime, sha256, object_key: objectKey, note, uploaded_by: uploadedBy }).select(WORKSPACE_FILE).single()))
package/src/passes.js CHANGED
@@ -9,7 +9,8 @@ import { generateIdentity, parsePublicKey } from './identity.js'
9
9
  export const PASS_VERSION = 1
10
10
  export const PASS_TTL_MS = 10 * 60 * 1000
11
11
  const MAX_NAME = 64
12
- const KINDS = ['person', 'agent']
12
+ // 'preview': a codebase's preview machine (plans/previews.md), always for one room, where it only reads.
13
+ const KINDS = ['person', 'agent', 'preview']
13
14
  const ROOM = /^[A-Za-z0-9_-]{1,64}$/
14
15
 
15
16
  /** A new signing pair, encoded like identity keys: SPKI and PKCS8 DER, in base64url. */
@@ -58,6 +59,7 @@ export function verifyPass (pass, key, { now = Date.now() } = {}) {
58
59
  if (typeof p.name !== 'string' || !p.name.trim() || p.name.length > MAX_NAME) return null
59
60
  // A room pass is good in that room only (see access in session-access.js).
60
61
  if (p.room !== undefined && (typeof p.room !== 'string' || !ROOM.test(p.room))) return null
62
+ if (p.kind === 'preview' && (!p.room || !p.key)) return null
61
63
  // No key: an HTTP-only pass (a hosted agent, see relay-mcp.js); it can't open a WebSocket.
62
64
  if (typeof p.key !== 'string' || (p.key && !parsePublicKey(p.key))) return null
63
65
  return p
@@ -0,0 +1,40 @@
1
+ // A preview's address (plans/previews.md). Every preview machine is behind one wildcard address,
2
+ // `*.preview.heyquilt.com`; an address names its machine and the slot of the branch it shows:
3
+ // `<machine id>-<slot>.preview.heyquilt.com`. So nothing has to be looked up to send a request to
4
+ // the right machine, and each branch has an origin of its own, as a dev server needs.
5
+ export const PREVIEW_DOMAIN = 'preview.heyquilt.com'
6
+ // A machine runs a few branches at once, each in a slot.
7
+ export const MAX_SLOTS = 10
8
+ const MACHINE = /^[0-9a-f]{8,24}$/
9
+ const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/
10
+
11
+ /** The domain previews are served under, checked: a bad one stops the program at start. */
12
+ export function previewDomain (domain = PREVIEW_DOMAIN) {
13
+ const d = String(domain || '').trim().toLowerCase()
14
+ if (!DOMAIN.test(d)) throw new Error(`"${String(domain).slice(0, 80)}" is not a domain for previews.`)
15
+ return d
16
+ }
17
+
18
+ /** The host for `slot` on `machine`: `<machine>-<slot>.<domain>`. */
19
+ export function previewHost (machine, slot, domain = PREVIEW_DOMAIN) {
20
+ const m = String(machine || '').toLowerCase()
21
+ if (!MACHINE.test(m)) throw new Error('That is not a machine.')
22
+ if (!Number.isInteger(slot) || slot < 0 || slot >= MAX_SLOTS) throw new Error('That is not a slot.')
23
+ return `${m}-${slot}.${previewDomain(domain)}`
24
+ }
25
+
26
+ /** `https://<host>`, the origin a preview's pages are served from. */
27
+ export const previewOrigin = (machine, slot, domain = PREVIEW_DOMAIN) => `https://${previewHost(machine, slot, domain)}`
28
+
29
+ /**
30
+ * The machine and slot a `Host` header names, or null when it is not a preview's address under
31
+ * `domain` (a port on it is ignored: Fly's proxy may leave one).
32
+ */
33
+ export function parsePreviewHost (host, domain = PREVIEW_DOMAIN) {
34
+ const h = String(host || '').trim().toLowerCase().replace(/:\d{1,5}$/, '')
35
+ const tail = `.${previewDomain(domain)}`
36
+ if (!h.endsWith(tail)) return null
37
+ const m = /^([0-9a-f]{8,24})-(\d)$/.exec(h.slice(0, -tail.length))
38
+ if (!m) return null
39
+ return { machine: m[1], slot: Number(m[2]) }
40
+ }