Public: anyone can read this; the crew can change it.
Talk workspace W2: a hot-reloading dev cell per workspace #17154
Merged 37h 20m ago, live in production
scout/forge:scout/17140-talk-workspace-w2-a-hot-reloading-dev-ce → main 0 commits fork 7 threads · 7 unresolved
20 files
changed +1140
−18
- docs/features/talk-workspace.md
- src/actions/dev_workspace.ts
- src/apps/dev_cell.ts
- src/apps/dev_command.ts
- src/apps/dev_launch.ts
- src/core/event_audience.ts
- src/http/server.ts
- src/tui/screens/talk_chats.ts
- src/web/pages/talk_dev.ts
- src/web/pages/talk_preview.ts
- test/budgets/pages/talk.json
- test/budgets/unfixtured/talk-dev-token-path.json
- test/budgets/unfixtured/talk-dev-token.json
- test/dev-cell-launch.test.ts
- test/dev-cell.test.ts
- test/job-slices.test.ts
- test/no-polling.test.ts
- test/security-floor-routes.test.ts
- test/talk-pane-bar.test.ts
- test/tui-talk-chats.test.ts
docs/features/talk-workspace.md +13 −1
| @@ -9,4 +9,16 @@ The bar over Talk's preview (`src/web/pages/talk_preview.ts`) names the environm | ||
| 9 | 9 | |
| 10 | 10 | In the terminal, the `p` view of the Talk screen (`src/tui/screens/talk_chats.ts`) prints the same `Status:` line; `w` picks the branch's version as before. |
| 11 | 11 | |
| 12 | Not yet: a hot-reloading dev cell per workspace, which will drive the status from the dev server itself (W2, #17140). Where the page shows only **Error**, the file and line sit in its title; the terminal's `p` view prints them: "Error in src/app.ts:12; ask the crew to fix it". Both read `paneStatus`. | |
| 12 | ## The dev server (#17140, W2) | |
| 13 | ||
| 14 | **Start dev server** in the bar (`d` in the terminal's `p` view) starts a long-lived dev cell for you on the branch shown: the branch is checked out under `<data>/dev/` and its dev command runs in the same cell an app of the repository runs in, with hot reload. The command is `app.dev` in `forge.json`, else `bun run dev` when `package.json` has a `dev` script, else the app's `run` command with `bun` made `bun --hot` (`src/apps/dev_command.ts`). Only a writer can start one, and only for a repository that is an app. | |
| 15 | ||
| 16 | While it runs, the frame is the dev server itself and the status is its own (`paneStatus`, `dev`): **Starting** until its port answers, **Live**, **Reloading** while the crew works on top of it, and **Error in file:line** from the last lines it printed if it stops. A commit to the branch (by you, by Talk, or by hand on the edit page) is synced into the checkout when it is pushed (the push event, not a page read), and the server reloads on its own. | |
| 17 | ||
| 18 | It sleeps after ten minutes nobody looks at it (the process stops, the checkout stays, so the next start is quick). Only a looked-at cell stays awake: a page read does not count, the frame's own requests do (`src/apps/dev_cell.ts`). There is no forge-wide cap and nobody's cell is stopped for another's; the idle sleep is the bound. | |
| 19 | ||
| 20 | The frame is served by the forge at `/talk/dev/<token>/…` (`src/web/pages/talk_dev.ts`), never as the forge's own origin: the iframe is sandboxed without `allow-same-origin`, every answer carries `Content-Security-Policy: sandbox`, no cookie goes either way, and only GET and HEAD are relayed. Because a sandboxed frame sends no session, the 192-bit token in the path is the credential: it is in the page of the person who started the cell and nowhere else. If you lose write access to the repository the cell stops at its next request and the token is dead. A redirect to the server's own address is rewritten under the token; a redirect anywhere else is refused. The dev process gets none of the app's secrets: its identity key is derived for the dev environment alone and it has no forge token. | |
| 21 | ||
| 22 | What the frame cannot do, said on the page too: it is a sandboxed frame, so an app that signs people in or posts forms does not work in it, and absolute links like `/x` that the app writes itself point at the forge, not the app; use relative links. | |
| 23 | ||
| 24 | Where the page shows only **Error**, the file and line sit in its title; the terminal's `p` view prints them: "Error in src/app.ts:12; ask the crew to fix it". Both read `paneStatus`. |
src/actions/dev_workspace.ts +99 −5
| @@ -1,9 +1,21 @@ | ||
| 1 | import type { App } from "../app.ts"; | |
| 2 | import { getAppByRepo } from "../core/apps.ts"; | |
| 3 | import { getPull } from "../core/pulls.ts"; | |
| 4 | import { getRepoById, type Repo } from "../core/repos.ts"; | |
| 5 | import type { User } from "../core/users.ts"; | |
| 6 | import { repoDir } from "../git/repos.ts"; | |
| 7 | import { devCellsOf, type DevCell, type DevReading } from "../apps/dev_cell.ts"; | |
| 8 | import { devKey, launcherFor, syncCheckout } from "../apps/dev_launch.ts"; | |
| 9 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 10 | import { requireWriter } from "./access.ts"; | |
| 11 | ||
| 1 | 12 | /** |
| 2 | 13 | * The state of a Talk workspace as its bar says it (#17119, W1 of #16940): `repo ▸ branch` and one |
| 3 | 14 | * status word: starting, live, reloading, or the error with its file and line. Plain data in, plain |
| 4 | 15 | * data out, so the page's bar and the terminal's `p` view say the same. The dev cell that hot |
| 5 | * reloads a branch is W2's; for now the status is read from what the forge already knows: the | |
| 6 | * address that answers and the crew's newest run. | |
| 16 | * reloads a branch is W2's (#17140, `apps/dev_cell.ts`): where one runs, the status is the dev | |
| 17 | * server's own; where none does, it is read from what the forge already knows: the address that | |
| 18 | * answers and the crew's newest run. | |
| 7 | 19 | */ |
| 8 | 20 | |
| 9 | 21 | export type DevState = "starting" | "live" | "reloading" | "error"; |
| @@ -53,9 +65,91 @@ export function devStatus(facts: DevFacts): DevStatus { | ||
| 53 | 65 | /** |
| 54 | 66 | * The facts the bar reads, built once for both doors: whether an address answers, the crew's newest |
| 55 | 67 | * run (queued or running is work under way; failed is the error, with the words it ended on), and |
| 56 | * whether an ask is being answered. | |
| 68 | * whether an ask is being answered. A dev cell's reading (`dev`) is the server itself: up when it | |
| 69 | * answers, the error it ended on when it did not; the crew's work on top of a live server is a | |
| 70 | * reload. | |
| 57 | 71 | */ |
| 58 | export function paneStatus(input: { readonly url: string | undefined; readonly crew: { readonly state: string; readonly line: { readonly says: string } } | undefined; readonly busy?: boolean }): DevStatus { | |
| 72 | export function paneStatus(input: { readonly url: string | undefined; readonly crew: { readonly state: string; readonly line: { readonly says: string } } | undefined; readonly busy?: boolean; readonly dev?: Pick<DevReading, "state" | "error"> | undefined }): DevStatus { | |
| 59 | 73 | const going = input.crew !== undefined && (input.crew.state === "queued" || input.crew.state === "running"); |
| 60 | return devStatus({ up: input.url !== undefined, working: going || input.busy === true, ...(input.crew?.state === "failed" ? { failed: input.crew.line.says } : {}) }); | |
| 74 | const failed = input.dev !== undefined ? (input.dev.state === "error" ? (input.dev.error ?? "the dev server stopped") : undefined) : input.crew?.state === "failed" ? input.crew.line.says : undefined; | |
| 75 | return devStatus({ up: input.dev !== undefined ? input.dev.state === "live" : input.url !== undefined, working: going || input.busy === true, ...(failed === undefined ? {} : { failed }) }); | |
| 76 | } | |
| 77 | ||
| 78 | /** The branch a workspace's dev cell runs: the shown pull's head, else the default branch. */ | |
| 79 | export function devBranch(app: App, repo: Repo, shows: number | undefined): string { | |
| 80 | const pull = shows === undefined ? undefined : getPull(app.db, repo.id, shows); | |
| 81 | return pull !== undefined && !pull.crossRepo ? pull.headBranch : repo.defaultBranch; | |
| 82 | } | |
| 83 | ||
| 84 | export type DevAsk = Result<DevReading, "not_found" | "unauthorized" | "forbidden" | "no_app">; | |
| 85 | ||
| 86 | /** | |
| 87 | * Start (or find) this person's dev cell for `branch`; a writer's only, and only where the | |
| 88 | * repository is an app. | |
| 89 | */ | |
| 90 | export function startDev(app: App, user: User, repo: Repo, branch: string): DevAsk { | |
| 91 | const allowed = requireWriter(app, user, repo); | |
| 92 | if (!allowed.ok) return err(allowed.error); | |
| 93 | const record = getAppByRepo(app.db, repo.id); | |
| 94 | if (record === undefined) return err("no_app"); | |
| 95 | watchPushes(app); | |
| 96 | const cell = devCellsOf(app).ensure(devKey(user.id, repo.id, branch), user.id, repo.id, launcherFor(app, record, repo, user.id, branch, "")); | |
| 97 | cell.branch = branch; | |
| 98 | return ok({ state: cell.state, token: cell.token }); | |
| 99 | } | |
| 100 | ||
| 101 | export async function stopDev(app: App, user: User, repo: Repo, branch: string): Promise<boolean> { | |
| 102 | return requireWriter(app, user, repo).ok && (await devCellsOf(app).stop(devKey(user.id, repo.id, branch))); | |
| 103 | } | |
| 104 | ||
| 105 | /** | |
| 106 | * This person's cell for `branch`, as the bar reads it. A read only reads: it spawns nothing and | |
| 107 | * does not keep the cell awake. | |
| 108 | */ | |
| 109 | export function devReading(app: App, user: User, repo: Repo, branch: string): DevReading | undefined { | |
| 110 | return devCellsOf(app).reading(devKey(user.id, repo.id, branch)); | |
| 111 | } | |
| 112 | ||
| 113 | /** Sync the checkout to the branch's tip; a push that lands meanwhile is synced after, not lost. */ | |
| 114 | function syncCell(cell: DevCell, bare: string): void { | |
| 115 | if (cell.syncing === true) { | |
| 116 | cell.resync = true; | |
| 117 | return; | |
| 118 | } | |
| 119 | if (cell.dir === undefined || cell.branch === undefined) return; | |
| 120 | cell.syncing = true; | |
| 121 | void syncCheckout(bare, cell.dir, cell.branch) | |
| 122 | .then((synced) => { | |
| 123 | if (synced.ok) cell.oid = synced.value; | |
| 124 | }) | |
| 125 | .catch(() => undefined) | |
| 126 | .finally(() => { | |
| 127 | cell.syncing = false; | |
| 128 | if (cell.resync === true) { | |
| 129 | cell.resync = false; | |
| 130 | syncCell(cell, bare); | |
| 131 | } | |
| 132 | }); | |
| 133 | } | |
| 134 | ||
| 135 | const watching = new WeakSet<object>(); | |
| 136 | ||
| 137 | /** | |
| 138 | * A push to a branch a dev cell runs is synced into its checkout, so the hot-reloading server sees | |
| 139 | * the files change. It listens once per forge, on the push event itself: nothing is checked when a | |
| 140 | * pane is read. | |
| 141 | */ | |
| 142 | function watchPushes(app: App): void { | |
| 143 | if (watching.has(app)) return; | |
| 144 | watching.add(app); | |
| 145 | app.bus.subscribe((event) => { | |
| 146 | if (event.kind !== "push" || event.repoId === null) return; | |
| 147 | const updates = event.payload["updates"]; | |
| 148 | const refs = new Set(Array.isArray(updates) ? updates.map((u: unknown) => (typeof u === "object" && u !== null ? (u as { ref?: unknown }).ref : undefined)) : []); | |
| 149 | const cells = devCellsOf(app).ofRepo(event.repoId).filter((c) => c.state === "live" && c.branch !== undefined && refs.has(`refs/heads/${c.branch}`)); | |
| 150 | const repo = cells.length === 0 ? undefined : getRepoById(app.db, event.repoId); | |
| 151 | if (repo === undefined) return; | |
| 152 | const bare = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 153 | for (const cell of cells) syncCell(cell, bare); | |
| 154 | }); | |
| 61 | 155 | } |
src/apps/dev_cell.ts added +208
| @@ -0,0 +1,208 @@ | ||
| 1 | /** | |
| 2 | * The dev cells of Talk's workspaces (#17140, W2 of #16940): one long-lived process per person and | |
| 3 | * branch, running the repository's dev command with hot reload in the branch's checkout. This | |
| 4 | * module is the registry: what is running, its state as the dev server itself reports it (starting | |
| 5 | * until the port answers, live, or the error its last words name), and the idle sleep. How a | |
| 6 | * process is launched is `dev_launch.ts`'s; here it is a function handed in, so the rest is plain | |
| 7 | * data. | |
| 8 | */ | |
| 9 | ||
| 10 | import { randomBytes } from "node:crypto"; | |
| 11 | import { during } from "../perf/jobs.ts"; | |
| 12 | import { heldOf } from "../perf/held.ts"; | |
| 13 | import type { App } from "../app.ts"; | |
| 14 | import type { Result } from "../kernel/result.ts"; | |
| 15 | ||
| 16 | /** A dev cell left untouched this long goes to sleep: the process stops, the checkout stays. */ | |
| 17 | export const DEV_IDLE_MS = 10 * 60_000; | |
| 18 | const TAIL = 20; | |
| 19 | ||
| 20 | export interface DevRun { | |
| 21 | readonly port: number; | |
| 22 | readonly exited: Promise<unknown>; | |
| 23 | stop(): Promise<void>; | |
| 24 | /** The newest lines it printed, newest last. */ | |
| 25 | recent(): readonly string[]; | |
| 26 | /** | |
| 27 | * The checkout it runs in, and the commit that checkout holds (what a sync compares the tip to). | |
| 28 | */ | |
| 29 | readonly dir?: string; | |
| 30 | readonly oid?: string; | |
| 31 | } | |
| 32 | ||
| 33 | /** What a launch is told: the cell's secret path and the branch's checkout it runs in. */ | |
| 34 | export interface DevLaunchInput { | |
| 35 | readonly token: string; | |
| 36 | readonly signal: AbortSignal; | |
| 37 | } | |
| 38 | export type DevLaunch = (input: DevLaunchInput) => Promise<Result<DevRun, string>>; | |
| 39 | ||
| 40 | export interface DevCell { | |
| 41 | readonly key: string; | |
| 42 | /** The unguessable path segment the frame is served under (`/talk/dev/<token>/`). */ | |
| 43 | readonly token: string; | |
| 44 | readonly userId: string; | |
| 45 | readonly repoId: string; | |
| 46 | /** The branch it runs, set by the one who starts it; a push to it is synced into the checkout. */ | |
| 47 | branch?: string; | |
| 48 | readonly startedAt: number; | |
| 49 | touchedAt: number; | |
| 50 | /** The checkout's commit last synced; a newer tip is synced into it so the server reloads. */ | |
| 51 | oid?: string; | |
| 52 | dir?: string; | |
| 53 | /** A sync of the checkout is under way. */ | |
| 54 | syncing?: boolean; | |
| 55 | /** A push landed while it was syncing: sync once more after. */ | |
| 56 | resync?: boolean; | |
| 57 | state: "starting" | "live" | "error"; | |
| 58 | /** Words the cell ended on, when it did not stay up. */ | |
| 59 | error?: string; | |
| 60 | run?: DevRun; | |
| 61 | readonly abort: AbortController; | |
| 62 | } | |
| 63 | ||
| 64 | /** What the workspace's status reads: nothing when no cell is held. */ | |
| 65 | export interface DevReading { | |
| 66 | readonly state: DevCell["state"]; | |
| 67 | readonly error?: string; | |
| 68 | readonly token: string; | |
| 69 | } | |
| 70 | ||
| 71 | export interface DevCells { | |
| 72 | /** Start the cell for `key` unless one is held; returns the one held either way. */ | |
| 73 | ensure(key: string, userId: string, repoId: string, launch: DevLaunch, now?: number): DevCell; | |
| 74 | /** The cell behind a frame path's token, touched (its use is what keeps it awake). */ | |
| 75 | byToken(token: string, now?: number): DevCell | undefined; | |
| 76 | /** The cell for `key`, touched when `touch`. */ | |
| 77 | get(key: string, touch?: boolean, now?: number): DevCell | undefined; | |
| 78 | /** What the bar reads of the cell for `key`; a read leaves the idle clock alone. */ | |
| 79 | reading(key: string): DevReading | undefined; | |
| 80 | /** The cells running for a repository. */ | |
| 81 | ofRepo(repoId: string): DevCell[]; | |
| 82 | /** Stop every cell of `userId` on `repoId` (their access ended). */ | |
| 83 | stopOf(userId: string, repoId: string): Promise<number>; | |
| 84 | stop(key: string): Promise<boolean>; | |
| 85 | /** Stop every cell idle past `idleMs`; the keys that went to sleep. */ | |
| 86 | sweep(now?: number, idleMs?: number): Promise<string[]>; | |
| 87 | readonly size: number; | |
| 88 | } | |
| 89 | ||
| 90 | const registries = new WeakMap<object, DevCells>(); | |
| 91 | ||
| 92 | const wordsOf = (lines: readonly string[]): string => lines.slice(-TAIL).join("\n").slice(-2000) || "the dev server stopped"; | |
| 93 | ||
| 94 | function make(changed: (cell: DevCell) => void): DevCells { | |
| 95 | const cells = new Map<string, DevCell>(); | |
| 96 | const tokens = new Map<string, DevCell>(); | |
| 97 | const drop = (cell: DevCell): Promise<void> => { | |
| 98 | cells.delete(cell.key); | |
| 99 | tokens.delete(cell.token); | |
| 100 | cell.abort.abort(); | |
| 101 | return cell.run === undefined ? Promise.resolve() : cell.run.stop().catch(() => undefined); | |
| 102 | }; | |
| 103 | return { | |
| 104 | ensure(key, userId, repoId, launch, now = Date.now()) { | |
| 105 | const held = cells.get(key); | |
| 106 | if (held !== undefined && held.state !== "error") { | |
| 107 | held.touchedAt = now; | |
| 108 | return held; | |
| 109 | } | |
| 110 | if (held !== undefined) void drop(held); | |
| 111 | const cell: DevCell = { key, token: randomBytes(24).toString("hex"), userId, repoId, startedAt: now, touchedAt: now, state: "starting", abort: new AbortController() }; | |
| 112 | cells.set(key, cell); | |
| 113 | tokens.set(cell.token, cell); | |
| 114 | void launch({ token: cell.token, signal: cell.abort.signal }).then( | |
| 115 | (started) => { | |
| 116 | if (cells.get(key) !== cell) { | |
| 117 | if (started.ok) void started.value.stop(); | |
| 118 | return; | |
| 119 | } | |
| 120 | if (!started.ok) { | |
| 121 | cell.state = "error"; | |
| 122 | cell.error = started.error; | |
| 123 | changed(cell); | |
| 124 | return; | |
| 125 | } | |
| 126 | cell.run = started.value; | |
| 127 | if (started.value.dir !== undefined) cell.dir = started.value.dir; | |
| 128 | if (started.value.oid !== undefined) cell.oid = started.value.oid; | |
| 129 | cell.state = "live"; | |
| 130 | changed(cell); | |
| 131 | // The server ending is the cell's end: it is read as the error it printed last, and the | |
| 132 | // next start begins again. | |
| 133 | void started.value.exited.then(() => { | |
| 134 | if (cells.get(key) !== cell || cell.abort.signal.aborted) return; | |
| 135 | cell.state = "error"; | |
| 136 | cell.error = wordsOf(started.value.recent()); | |
| 137 | changed(cell); | |
| 138 | }); | |
| 139 | }, | |
| 140 | (cause: unknown) => { | |
| 141 | if (cells.get(key) !== cell) return; | |
| 142 | cell.state = "error"; | |
| 143 | cell.error = cause instanceof Error ? cause.message : String(cause); | |
| 144 | changed(cell); | |
| 145 | }, | |
| 146 | ); | |
| 147 | return cell; | |
| 148 | }, | |
| 149 | byToken(token, now = Date.now()) { | |
| 150 | const cell = tokens.get(token); | |
| 151 | if (cell !== undefined) cell.touchedAt = now; | |
| 152 | return cell; | |
| 153 | }, | |
| 154 | get(key, touch = false, now = Date.now()) { | |
| 155 | const cell = cells.get(key); | |
| 156 | if (cell !== undefined && touch) cell.touchedAt = now; | |
| 157 | return cell; | |
| 158 | }, | |
| 159 | reading(key) { | |
| 160 | const cell = cells.get(key); | |
| 161 | if (cell === undefined) return undefined; | |
| 162 | return { state: cell.state, token: cell.token, ...(cell.error === undefined ? {} : { error: cell.error }) }; | |
| 163 | }, | |
| 164 | ofRepo(repoId) { | |
| 165 | return [...cells.values()].filter((c) => c.repoId === repoId); | |
| 166 | }, | |
| 167 | async stopOf(userId, repoId) { | |
| 168 | const mine = [...cells.values()].filter((c) => c.userId === userId && c.repoId === repoId); | |
| 169 | await Promise.all(mine.map(drop)); | |
| 170 | return mine.length; | |
| 171 | }, | |
| 172 | async stop(key) { | |
| 173 | const cell = cells.get(key); | |
| 174 | if (cell === undefined) return false; | |
| 175 | await drop(cell); | |
| 176 | return true; | |
| 177 | }, | |
| 178 | async sweep(now = Date.now(), idleMs = DEV_IDLE_MS) { | |
| 179 | const idle = [...cells.values()].filter((c) => now - c.touchedAt > idleMs); | |
| 180 | await Promise.all(idle.map(drop)); | |
| 181 | return idle.map((c) => c.key); | |
| 182 | }, | |
| 183 | get size() { | |
| 184 | return cells.size; | |
| 185 | }, | |
| 186 | }; | |
| 187 | } | |
| 188 | ||
| 189 | /** This forge's dev cells; its idle sweep starts with the first one asked for. */ | |
| 190 | export function devCellsOf(app: App): DevCells { | |
| 191 | let cells = registries.get(app); | |
| 192 | if (cells === undefined) { | |
| 193 | // A cell's change of state is an event, so a pane that shows it redraws | |
| 194 | // (`data-live="dev.state"`). | |
| 195 | cells = make((cell) => { | |
| 196 | try { | |
| 197 | app.bus.append({ kind: "dev.state", repoId: cell.repoId, actorId: cell.userId, payload: { state: cell.state } }); | |
| 198 | } catch { | |
| 199 | // A pane that is not told redraws when it is next opened; the cell goes on. | |
| 200 | } | |
| 201 | }); | |
| 202 | registries.set(app, cells); | |
| 203 | const held = cells; | |
| 204 | heldOf(app).add("dev cells", () => held.size); | |
| 205 | setInterval(() => during("dev-cell-sweep", () => void held.sweep()), 60_000).unref(); | |
| 206 | } | |
| 207 | return cells; | |
| 208 | } |
src/apps/dev_command.ts added +35
| @@ -0,0 +1,35 @@ | ||
| 1 | /** | |
| 2 | * The command a workspace's dev cell runs (#17140, W2 of #16940), chosen from what the repository | |
| 3 | * declares: `app.dev` in forge.json, else `scripts.dev` in package.json, else the app's own run | |
| 4 | * command with `bun` made `bun --hot`. Plain text in, a command or nothing out. | |
| 5 | */ | |
| 6 | ||
| 7 | const COMMAND_MAX = 500; | |
| 8 | ||
| 9 | /** The member `key` of the JSON object `text`, when it is an object too; else nothing. */ | |
| 10 | const section = (text: string | undefined, key: string): Record<string, unknown> | undefined => { | |
| 11 | try { | |
| 12 | const member = (JSON.parse(text ?? "") as Record<string, unknown> | null)?.[key]; | |
| 13 | return typeof member === "object" && member !== null && !Array.isArray(member) ? (member as Record<string, unknown>) : undefined; | |
| 14 | } catch { | |
| 15 | return undefined; | |
| 16 | } | |
| 17 | }; | |
| 18 | ||
| 19 | const command = (value: unknown): string | undefined => | |
| 20 | typeof value === "string" && value.trim() !== "" && value.length <= COMMAND_MAX && !value.includes("\n") && !value.includes("\0") ? value.trim() : undefined; | |
| 21 | ||
| 22 | /** `bun run x.ts` / `bun x.ts` becomes the same with `--hot`; anything else is left alone. */ | |
| 23 | export const hot = (run: string): string => { | |
| 24 | if (/^bun\s+--(hot|watch)\b/.test(run)) return run; | |
| 25 | const m = /^bun\s+(?:run\s+)?(\S.*)$/.exec(run); | |
| 26 | return m === null ? run : `bun --hot ${m[1]!.replace(/^run\s+/, "")}`; | |
| 27 | }; | |
| 28 | ||
| 29 | export function devCommand(input: { readonly forgeJson?: string | undefined; readonly packageJson?: string | undefined; readonly run?: string | undefined }): string | undefined { | |
| 30 | const declared = command(section(input.forgeJson, "app")?.["dev"]); | |
| 31 | if (declared !== undefined) return declared; | |
| 32 | if (command(section(input.packageJson, "scripts")?.["dev"]) !== undefined) return "bun run dev"; | |
| 33 | const run = command(input.run); | |
| 34 | return run === undefined ? undefined : hot(run); | |
| 35 | } |
src/apps/dev_launch.ts added +113
| @@ -0,0 +1,113 @@ | ||
| 1 | /** | |
| 2 | * How a dev cell starts (#17140): the branch's checkout under `<data>/dev/<repo>/<branch>` (cloned | |
| 3 | * the first time, synced to the branch's tip after, so a commit to the branch is a file change the | |
| 4 | * hot-reloading server picks up), the repository's manifest with its dev command in place of `run`, | |
| 5 | * and `startProcess` in the same cell an app of this repository runs in. The branch's code is | |
| 6 | * whatever a writer pushed, so none of the app's secrets are handed over: the identity key is one | |
| 7 | * derived for this dev environment alone (it verifies nothing the forge signs for the app), and no | |
| 8 | * forge token is given. | |
| 9 | */ | |
| 10 | ||
| 11 | import { createHash, createHmac } from "node:crypto"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { mkdir } from "node:fs/promises"; | |
| 14 | import type { App } from "../app.ts"; | |
| 15 | import type { AppRecord } from "../core/apps.ts"; | |
| 16 | import type { Repo } from "../core/repos.ts"; | |
| 17 | import { repoDir } from "../git/repos.ts"; | |
| 18 | import { runLocal } from "../git/local.ts"; | |
| 19 | import { resolveOid } from "../git/merge.ts"; | |
| 20 | import { isSafeRef } from "../git/guard.ts"; | |
| 21 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 22 | import { appsRuntime } from "./runtime.ts"; | |
| 23 | import { identityKey } from "./grants.ts"; | |
| 24 | import { envDataDir, type EnvName } from "./data.ts"; | |
| 25 | import { parseManifest } from "./manifest.ts"; | |
| 26 | import { startProcess, type ProcessHandle } from "./process.ts"; | |
| 27 | import { devCommand } from "./dev_command.ts"; | |
| 28 | import type { DevLaunch, DevRun } from "./dev_cell.ts"; | |
| 29 | ||
| 30 | const LINES = 20; | |
| 31 | ||
| 32 | /** | |
| 33 | * One cell per person and branch: its key, and the environment name its data and home live under. | |
| 34 | */ | |
| 35 | export const devKey = (userId: string, repoId: string, branch: string): string => `${userId}:${repoId}:${branch}`; | |
| 36 | export const devEnv = (key: string): EnvName => `variant-d${createHash("sha256").update(key).digest("hex").slice(0, 10)}`; | |
| 37 | ||
| 38 | /** A key for one dev environment, derived one way from the app's: it does not reveal the app's. */ | |
| 39 | const devIdentityKey = (appKey: string, env: EnvName): string => createHmac("sha256", appKey).update(`dev-cell:${env}`).digest("hex"); | |
| 40 | ||
| 41 | const read = async (dir: string, name: string): Promise<string | undefined> => { | |
| 42 | const file = Bun.file(join(dir, name)); | |
| 43 | return (await file.exists()) ? file.text() : undefined; | |
| 44 | }; | |
| 45 | ||
| 46 | /** The branch's tip in the checkout `dir`, synced from the bare repository; its commit. */ | |
| 47 | export async function syncCheckout(bare: string, dir: string, branch: string): Promise<Result<string, string>> { | |
| 48 | if (!isSafeRef(branch)) return err("not a branch name"); | |
| 49 | const tip = await resolveOid(bare, `refs/heads/${branch}`); | |
| 50 | if (tip === undefined) return err(`no branch ${branch}`); | |
| 51 | const cloned = await Bun.file(join(dir, ".git", "HEAD")).exists(); | |
| 52 | if (!cloned) { | |
| 53 | await mkdir(join(dir, ".."), { recursive: true }); | |
| 54 | const made = await runLocal(["clone", "--quiet", "--no-hardlinks", "--no-checkout", bare, dir], { cwd: join(dir, "..") }); | |
| 55 | if (!made.ok) return err("could not check the branch out"); | |
| 56 | } | |
| 57 | const got = await runLocal(["fetch", "--quiet", bare, `+refs/heads/${branch}:refs/remotes/dev/head`], { cwd: dir }); | |
| 58 | if (!got.ok) return err("could not read the branch"); | |
| 59 | const set = await runLocal(["reset", "--quiet", "--hard", tip], { cwd: dir }); | |
| 60 | return set.ok ? ok(tip) : err("could not check the branch out"); | |
| 61 | } | |
| 62 | ||
| 63 | const wrap = (handle: ProcessHandle, recent: string[], dir: string, oid: string): DevRun => ({ | |
| 64 | dir, | |
| 65 | oid, | |
| 66 | port: handle.port, | |
| 67 | exited: handle.exited, | |
| 68 | stop: () => handle.stop(), | |
| 69 | recent: () => recent, | |
| 70 | }); | |
| 71 | ||
| 72 | /** | |
| 73 | * The launcher for `branch` of `repo`, for `userId`: checked out, then the dev server started and | |
| 74 | * waited for. An error is words a person can read: no app here, nothing to run, or the server's | |
| 75 | * last lines. | |
| 76 | */ | |
| 77 | export function launcherFor(app: App, record: AppRecord, repo: Repo, userId: string, branch: string, base: string): DevLaunch { | |
| 78 | const key = devKey(userId, repo.id, branch); | |
| 79 | const env = devEnv(key); | |
| 80 | return async ({ token, signal }) => { | |
| 81 | const rt = appsRuntime(app); | |
| 82 | if (rt === undefined) return err("apps are not running on this forge"); | |
| 83 | const dir = join(app.config.dataDir, "dev", repo.id, createHash("sha256").update(key).digest("hex").slice(0, 16)); | |
| 84 | const synced = await syncCheckout(repoDir(app.reposRoot, repo.ownerName, repo.name), dir, branch); | |
| 85 | if (!synced.ok) return synced; | |
| 86 | const forgeJson = await read(dir, "forge.json"); | |
| 87 | const packageJson = await read(dir, "package.json"); | |
| 88 | const parsed = parseManifest(forgeJson, packageJson); | |
| 89 | if (!parsed.ok) return err("this branch is not an app: it has no forge.json app section or start script"); | |
| 90 | const run = devCommand({ forgeJson, packageJson, run: parsed.value.run }); | |
| 91 | if (run === undefined) return err("this branch declares no dev command"); | |
| 92 | const recent: string[] = []; | |
| 93 | const started = await startProcess({ | |
| 94 | dir, | |
| 95 | dataDir: envDataDir(app.config.dataDir, record.id, env), | |
| 96 | manifest: { ...parsed.value, run, test: null, ready: Math.max(parsed.value.ready, 60) }, | |
| 97 | env, | |
| 98 | url: `${base}/talk/dev/${token}/`, | |
| 99 | commitOid: synced.value, | |
| 100 | forgeUrl: rt.options.forgeUrl, | |
| 101 | repo: `${repo.ownerName}/${repo.name}`, | |
| 102 | identityKey: devIdentityKey(identityKey(app.config.dataDir, record.id), env), | |
| 103 | log: (line) => { | |
| 104 | recent.push(line.slice(0, 300)); | |
| 105 | if (recent.length > LINES) recent.shift(); | |
| 106 | }, | |
| 107 | signal, | |
| 108 | cell: rt.cellFor(record, env), | |
| 109 | }); | |
| 110 | if (!started.ok) return err(`${started.error.stage}: ${started.error.message}`); | |
| 111 | return ok(wrap(started.value.handle, recent, dir, synced.value)); | |
| 112 | }; | |
| 113 | } |
src/core/event_audience.ts +3 −1
| @@ -416,7 +416,9 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 416 | 416 | kind === "account.close_kept" || |
| 417 | 417 | kind.startsWith("thought.") || |
| 418 | 418 | // A conversation's own plan changed (`keep_plan` from Talk): the person's alone. |
| 419 | kind === "conversation.plan" | |
| 419 | kind === "conversation.plan" || | |
| 420 | // A person's own dev cell changed state (`apps/dev_cell.ts`): theirs alone. | |
| 421 | kind === "dev.state" | |
| 420 | 422 | ) |
| 421 | 423 | return "actor"; |
| 422 | 424 | // A run's summary, an app's serving state and its pictures can carry the |
src/http/server.ts +4
| @@ -190,6 +190,7 @@ import { | ||
| 190 | 190 | } from "../web/pages/site.ts"; |
| 191 | 191 | import { talkBuild, talkPublish, talkRestore } from "../web/talk_build.ts"; |
| 192 | 192 | import { talkModel } from "../web/talk_model.ts"; |
| 193 | import { talkDev, talkDevFrame } from "../web/pages/talk_dev.ts"; | |
| 193 | 194 | import { talkAct, talkAgainSend, talkArchive, talkConfirm, talkDisplaySave, talkDownload, talkNew, talkPin, talkQueueCancel, talkRename, talkSend, talkUndo, talkStream, talkView, talkWall } from "../web/pages/talk.ts"; |
| 194 | 195 | import { liveTalkCrew, liveTalkPlan, liveTalkWork } from "../web/talk_lines.ts"; |
| 195 | 196 | import { peekRoute } from "../web/peek.ts"; |
| @@ -1285,6 +1286,9 @@ export function buildRouter(): Router<Handler> { | ||
| 1285 | 1286 | router.add("POST", "/talk/new", talkNew); |
| 1286 | 1287 | router.add("POST", "/talk/display", talkDisplaySave); |
| 1287 | 1288 | router.add("POST", "/talk/build", talkBuild); |
| 1289 | router.add("POST", "/talk/dev", talkDev); | |
| 1290 | router.add("GET", "/talk/dev/:token", talkDevFrame); | |
| 1291 | router.add("GET", "/talk/dev/:token/*path", talkDevFrame); | |
| 1288 | 1292 | router.add("GET", "/talk/:id", talkView); |
| 1289 | 1293 | router.add("GET", "/talk/:id/download", talkDownload); |
| 1290 | 1294 | router.add("POST", "/talk/:id", talkSend); |
src/tui/screens/talk_chats.ts +26 −2
| @@ -35,7 +35,7 @@ import { filesOf, receiptIssues, repoOf, steerOf, stepOf } from "../../core/talk | ||
| 35 | 35 | import { cardsPlaced, holdsCard, plainVoice } from "../../core/talk_voice.ts"; |
| 36 | 36 | import { setTalkDisplay, talkDisplay } from "../../core/settings.ts"; |
| 37 | 37 | import { talkDisplayScreen } from "./talk_display.ts"; |
| 38 | import { paneStatus } from "../../actions/dev_workspace.ts"; | |
| 38 | import { devBranch, devReading, paneStatus, startDev, stopDev } from "../../actions/dev_workspace.ts"; | |
| 39 | 39 | import { conversationPulls, liveReceipts, paneCrew, paneFell, paneInfo, type LiveReceipt } from "../../core/talk_work.ts"; |
| 40 | 40 | import { tapRunLogs } from "../../runs/log.ts"; |
| 41 | 41 | import { mayReadRunLog, mayReadRuns, requeueRepoRun } from "../../actions/runs.ts"; |
| @@ -265,12 +265,15 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr | ||
| 265 | 265 | const ws = workspaceOf(f.app, f.user, name, undefined, pointedAt(picked, steer)); |
| 266 | 266 | if (ws === undefined) return ["Not a repository you can see."]; |
| 267 | 267 | const files = filesOf(recent, name); |
| 268 | const branch = devBranch(f.app, ws.repo, ws.shows); | |
| 269 | const dev = devReading(f.app, f.user, ws.repo, branch); | |
| 268 | 270 | const url = ws.url; |
| 269 | 271 | const fell = paneFell(f.app.db, ws.repo.id, ws.fell); |
| 270 | 272 | return [ |
| 271 | 273 | `${name} · ${ws.shows === undefined ? "Production" : `Pull #${String(ws.shows)}`}${pointedAt(picked, steer).path === undefined ? "" : ` · ${pointedAt(picked, steer).path ?? ""}`}`, |
| 272 | 274 | paneInfo(f.app.db, ws.repo, ws.shows), |
| 273 | `Status: ${((st) => (st.state === "error" ? `${st.word}; ask the crew to fix it` : st.word))(paneStatus({ url, crew: paneCrew(f.app.db, f.app.config.dataDir, ws.repo.id, f.user, { runs: mayReadRuns(f.app, f.user, ws.repo), logs: false }) }))}`, | |
| 275 | `Status: ${((st) => (st.state === "error" ? `${st.word}; ask the crew to fix it` : st.word))(paneStatus({ url, dev, crew: paneCrew(f.app.db, f.app.config.dataDir, ws.repo.id, f.user, { runs: mayReadRuns(f.app, f.user, ws.repo), logs: false }) }))}`, | |
| 276 | `Dev server: ${dev === undefined ? `not running; d starts ${branch} with hot reload` : `${dev.state} on ${branch}; d stops it`}${dev?.state === "live" ? " (the page frames it, sandboxed: sign-in and forms that post do not work in it; it sleeps after 10 minutes unused)" : ""}`, | |
| 274 | 277 | ...(fell === undefined ? [] : [fell]), |
| 275 | 278 | // Who else is here and what was done lately, in the page's words (`togetherOf`). |
| 276 | 279 | ...((t) => [...(t.here === undefined ? [] : [`Here: ${t.here.words}`]), ...(t.lately.length === 0 ? [] : [`Lately: ${t.lately.map((l) => `${l.words} · ${agoWords(l.at, Date.now())}`).join(" · ")}`]), ...(t.elsewhere === undefined ? [] : [`Elsewhere: ${t.elsewhere}`]), ...t.held, ...(t.landed === undefined ? [] : [`${t.landed.words} (L shows Live)`])])(togetherOf(f.app.db, ws.repo, f.user)), |
| @@ -368,6 +371,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr | ||
| 368 | 371 | binding([keyOf("reread")], "reload"), |
| 369 | 372 | binding(["p"], "pane"), |
| 370 | 373 | binding(["o", "w", "l", "L"], "in the pane: repository, version, path, Live"), |
| 374 | binding(["d"], "in the pane: start or stop the dev server"), | |
| 371 | 375 | binding(["b"], "a result's buttons"), |
| 372 | 376 | binding(["v"], "steps open or folded"), |
| 373 | 377 | binding(["D"], "display"), |
| @@ -477,6 +481,26 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr | ||
| 477 | 481 | ); |
| 478 | 482 | return true; |
| 479 | 483 | } |
| 484 | if (pane && e.key === "d") { | |
| 485 | // The dev server of the branch shown: started or stopped as the page's button does, by a | |
| 486 | // writer. | |
| 487 | const name = paneRepo(); | |
| 488 | const who = f.user; | |
| 489 | const ws = name === undefined || who === undefined ? undefined : workspaceOf(f.app, who, name, undefined, pointedAt(choice(), steerOn(name))); | |
| 490 | if (ws === undefined || who === undefined) return true; | |
| 491 | const branch = devBranch(f.app, ws.repo, ws.shows); | |
| 492 | runAsync(ctx, async () => { | |
| 493 | if (devReading(f.app, who, ws.repo, branch) !== undefined) { | |
| 494 | await stopDev(f.app, who, ws.repo, branch); | |
| 495 | note = `Stopped the dev server of ${branch}.`; | |
| 496 | } else { | |
| 497 | const started = startDev(f.app, who, ws.repo, branch); | |
| 498 | note = started.ok ? `Starting ${branch} with hot reload.` : started.error === "no_app" ? "This repository is not an app: nothing to run." : started.error === "forbidden" ? "Only someone who can write here can start its dev server." : "Not started."; | |
| 499 | } | |
| 500 | ctx.invalidate(); | |
| 501 | }); | |
| 502 | return true; | |
| 503 | } | |
| 480 | 504 | if (pane && e.key === "L") { |
| 481 | 505 | // Live, as the together line's "See Live" does: the person's own move, never one made for them. |
| 482 | 506 | const { pull: _was, ...rest } = choice(); |
src/web/pages/talk_dev.ts added +122
| @@ -0,0 +1,122 @@ | ||
| 1 | /** | |
| 2 | * The doors of a workspace's dev cell (#17140, W2 of #16940): `POST /talk/dev` starts or stops this | |
| 3 | * person's dev server for the branch the pane shows, and `GET /talk/dev/:token/*` serves what it | |
| 4 | * answers, so the pane can frame it. | |
| 5 | * | |
| 6 | * The dev server runs the branch's code, so it is never served as the forge: the frame is sandboxed | |
| 7 | * without `allow-same-origin` (an opaque origin, no cookie, no reading the page around it) and | |
| 8 | * every answer carries `Content-Security-Policy: sandbox`. Since a sandboxed frame sends no | |
| 9 | * session, the path's token is the credential: 192 random bits, shown only in the page of the | |
| 10 | * person who started the cell, and only GET and HEAD are relayed (a form post from a sandboxed page | |
| 11 | * has no origin the forge could check). | |
| 12 | */ | |
| 13 | ||
| 14 | import { devBranch, startDev, stopDev } from "../../actions/dev_workspace.ts"; | |
| 15 | import { devCellsOf } from "../../apps/dev_cell.ts"; | |
| 16 | import { canWrite, getRepo, getRepoById } from "../../core/repos.ts"; | |
| 17 | import { getUserById } from "../../core/users.ts"; | |
| 18 | import { safeBack, type Ctx } from "../../http/context.ts"; | |
| 19 | import { field, readForm } from "../form.ts"; | |
| 20 | import { notFoundPage, signInFirst } from "../chrome.ts"; | |
| 21 | import { flashTo } from "../layout.ts"; | |
| 22 | ||
| 23 | const REPO = /^([A-Za-z0-9_.-]{1,100})\/([A-Za-z0-9_.-]{1,100})$/; | |
| 24 | const RELAY_MS = 30_000; | |
| 25 | const DEV_FRAME_POLICY = "sandbox allow-scripts allow-forms allow-popups; frame-ancestors 'self'"; | |
| 26 | ||
| 27 | const WORDS: Record<string, string> = { | |
| 28 | not_found: "That repository is not here.", | |
| 29 | unauthorized: "Sign in to start a dev server.", | |
| 30 | forbidden: "Only someone who can write to this repository can start its dev server.", | |
| 31 | no_app: "This repository is not an app: it has no forge.json app section to run.", | |
| 32 | }; | |
| 33 | ||
| 34 | /** | |
| 35 | * POST /talk/dev — `repo` (owner/name), `pull` (the pull shown, or empty for the default branch), | |
| 36 | * `act` (start or stop). | |
| 37 | */ | |
| 38 | export async function talkDev(ctx: Ctx): Promise<Response> { | |
| 39 | const user = ctx.auth.user; | |
| 40 | if (user === undefined) return signInFirst(ctx); | |
| 41 | const form = await readForm(ctx, "rw"); | |
| 42 | if (form instanceof Response) return form; | |
| 43 | const back = safeBack(ctx) ?? "/talk"; | |
| 44 | const named = REPO.exec(field(form, "repo") ?? ""); | |
| 45 | const repo = named === null ? undefined : getRepo(ctx.app.db, named[1]!, named[2]!); | |
| 46 | const pull = /^[1-9]\d{0,8}$/.test(field(form, "pull") ?? "") ? Number(field(form, "pull")) : undefined; | |
| 47 | const act = field(form, "act"); | |
| 48 | if (repo === undefined || (act !== "start" && act !== "stop")) return flashTo(ctx, back, { tone: "danger", message: "Not a repository you can see." }); | |
| 49 | const branch = devBranch(ctx.app, repo, pull); | |
| 50 | if (act === "stop") { | |
| 51 | await stopDev(ctx.app, user, repo, branch); | |
| 52 | return flashTo(ctx, back, { tone: "success", message: `Stopped the dev server of ${branch}.` }); | |
| 53 | } | |
| 54 | const started = startDev(ctx.app, user, repo, branch); | |
| 55 | return started.ok ? flashTo(ctx, back, { tone: "success", message: `Starting ${branch} with hot reload.` }) : flashTo(ctx, back, { tone: "danger", message: WORDS[started.error] ?? "Not started." }); | |
| 56 | } | |
| 57 | ||
| 58 | // Only the request's own asking is passed on: no cookie, no authorization, nothing of the forge. | |
| 59 | const PASSED = ["accept", "accept-language", "if-none-match", "if-modified-since", "range"]; | |
| 60 | ||
| 61 | /** | |
| 62 | * Where a redirect of the dev server goes in the frame: a path of its own stays under the token's | |
| 63 | * path, an absolute address of the server itself (its loopback port) is the same path, and any | |
| 64 | * other address is refused (undefined), never passed on. | |
| 65 | */ | |
| 66 | export function relayedLocation(where: string, port: number, base: string): string | undefined { | |
| 67 | if (where.startsWith("//") || where.includes("\\")) return undefined; | |
| 68 | if (where.startsWith("/")) return base + where.slice(1); | |
| 69 | let url: URL; | |
| 70 | try { | |
| 71 | url = new URL(where); | |
| 72 | } catch { | |
| 73 | return undefined; | |
| 74 | } | |
| 75 | const own = url.protocol === "http:" && (url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "[::1]") && url.port === String(port); | |
| 76 | return own ? base + url.pathname.slice(1) + url.search : undefined; | |
| 77 | } | |
| 78 | ||
| 79 | /** GET /talk/dev/:token/*path — the dev server's answer, under the sandbox. */ | |
| 80 | export async function talkDevFrame(ctx: Ctx): Promise<Response> { | |
| 81 | const token = ctx.params["token"] ?? ""; | |
| 82 | const cell = /^[0-9a-f]{48}$/.test(token) ? devCellsOf(ctx.app).byToken(token) : undefined; | |
| 83 | if (cell === undefined || cell.state !== "live" || cell.run === undefined) return notFoundPage(ctx, { plain: true, noEcho: true }); | |
| 84 | // The token is the credential, but it is the person's: when they can no longer write here the | |
| 85 | // cell ends with their access. | |
| 86 | const owner = getUserById(ctx.app.db, cell.userId); | |
| 87 | const repo = getRepoById(ctx.app.db, cell.repoId); | |
| 88 | if (owner === undefined || repo === undefined || !canWrite(ctx.app.db, repo, owner)) { | |
| 89 | void devCellsOf(ctx.app).stopOf(cell.userId, cell.repoId); | |
| 90 | return notFoundPage(ctx, { plain: true, noEcho: true }); | |
| 91 | } | |
| 92 | const rest = (ctx.params["path"] ?? "").replace(/^\/+/, ""); | |
| 93 | if (rest.split("/").some((s) => s === ".." || s.includes("\\") || s.includes("\0"))) return notFoundPage(ctx, { plain: true, noEcho: true }); | |
| 94 | const headers = new Headers(); | |
| 95 | for (const name of PASSED) { | |
| 96 | const v = ctx.request.headers.get(name); | |
| 97 | if (v !== null) headers.set(name, v); | |
| 98 | } | |
| 99 | const base = `/talk/dev/${token}/`; | |
| 100 | let answer: Response; | |
| 101 | try { | |
| 102 | answer = await fetch(`http://127.0.0.1:${String(cell.run.port)}/${rest}${ctx.url.search}`, { method: ctx.request.method === "HEAD" ? "HEAD" : "GET", headers, redirect: "manual", signal: AbortSignal.timeout(RELAY_MS) }); | |
| 103 | } catch { | |
| 104 | return new Response("The dev server did not answer.", { status: 502, headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" } }); | |
| 105 | } | |
| 106 | const out = new Headers(); | |
| 107 | for (const name of ["content-type", "etag", "last-modified", "content-range", "accept-ranges"]) { | |
| 108 | const v = answer.headers.get(name); | |
| 109 | if (v !== null) out.set(name, v); | |
| 110 | } | |
| 111 | const where = answer.headers.get("location"); | |
| 112 | if (where !== null) { | |
| 113 | const to = relayedLocation(where, cell.run.port, base); | |
| 114 | if (to === undefined) return new Response("The dev server redirected somewhere this frame will not follow.", { status: 502, headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" } }); | |
| 115 | out.set("location", to); | |
| 116 | } | |
| 117 | out.set("content-security-policy", DEV_FRAME_POLICY); | |
| 118 | out.set("cache-control", "no-store"); | |
| 119 | // A sandboxed frame is another origin to the browser: its own subresources need this said. | |
| 120 | out.set("cross-origin-resource-policy", "cross-origin"); | |
| 121 | return new Response(answer.status === 204 || answer.status === 304 ? null : answer.body, { status: answer.status === 101 ? 502 : answer.status, headers: out }); | |
| 122 | } |
src/web/pages/talk_preview.ts +20 −7
| @@ -11,7 +11,8 @@ | ||
| 11 | 11 | * streaming beside it carries on. |
| 12 | 12 | */ |
| 13 | 13 | |
| 14 | import { paneStatus } from "../../actions/dev_workspace.ts"; | |
| 14 | import { devBranch, devReading, paneStatus } from "../../actions/dev_workspace.ts"; | |
| 15 | import { requireWriter } from "../../actions/access.ts"; | |
| 15 | 16 | import { offersOwnToken } from "../../actions/own_token.ts"; |
| 16 | 17 | import { getRun } from "../../core/runs.ts"; |
| 17 | 18 | import { ownTokenBox } from "../own_token.ts"; |
| @@ -82,7 +83,13 @@ export async function talkPane(ctx: Ctx, user: User, name: string | undefined, w | ||
| 82 | 83 | const path = pointed.path; |
| 83 | 84 | const ws = workspaceOf(ctx.app, user, name, apps, pointed); |
| 84 | 85 | if (ws === undefined) return empty(emptyLine("talkHidden")); |
| 85 | const { pull, url } = ws; | |
| 86 | const { pull } = ws; | |
| 87 | // This person's dev cell for the shown branch: while it answers, the frame is the dev server | |
| 88 | // itself (served under a secret path, `web/pages/talk_dev.ts`) and the status is its own. | |
| 89 | const branch = devBranch(ctx.app, ws.repo, ws.shows); | |
| 90 | const dev = devReading(ctx.app, user, ws.repo, branch); | |
| 91 | const devFrame = dev?.state === "live" ? `${ctx.url.origin}/talk/dev/${dev.token}${path ?? "/"}` : undefined; | |
| 92 | const url = devFrame ?? ws.url; | |
| 86 | 93 | // Every link and fragment of the pane carries the address bar's choice, so none loses it. |
| 87 | 94 | const q = paneQuery(at); |
| 88 | 95 | const amp = q === "" ? "" : `&${q}`; |
| @@ -103,7 +110,7 @@ export async function talkPane(ctx: Ctx, user: User, name: string | undefined, w | ||
| 103 | 110 | ? await diffView(ctx.app, work, ask.version, ask.mine === undefined ? undefined : { ...ask.mine, picked: at.pull }) |
| 104 | 111 | : url === undefined || ask.wait !== undefined |
| 105 | 112 | ? html`<div class="talk-stage talk-stage-wait" data-stage${ask.busy === true ? raw(" data-busy") : null}><p class="talk-stage-note" data-stage-note>${ask.wait ?? ask.idle ?? "Nothing is running yet: the app appears here once it is built."}</p>${crew === undefined ? null : crewBlock(crew, `/${ws.repo.ownerName}/${ws.repo.name}`, ws.repo, liveSrc, () => ctx.url.pathname, undefined, offer)}</div>${ask.build === undefined ? null : html`<h2 class="talk-stage-files small muted">The files it starts from</h2>${await codeView(ctx.app, work)}`}` |
| 106 | : html`${steer === undefined || steer.try === "" ? null : html`<p class="talk-try small" data-pane-try>Try: ${steer.try}</p>`}<div class="talk-stage" data-stage data-env="${ws.shows === undefined ? "production" : previewEnv(ws.shows)}"><iframe class="talk-frame" data-frame src="${url}" title="Live preview of ${name}" referrerpolicy="no-referrer" sandbox="allow-scripts allow-same-origin allow-forms allow-popups"></iframe><p class="talk-stage-note small" data-stage-note hidden>Updating the preview…</p></div>${crewRegion(crew !== undefined && (going || crew.state === "failed") ? crew : undefined, ws.repo, liveSrc, () => ctx.url.pathname, ws.shows, offer)}`; | |
| 113 | : html`${steer === undefined || steer.try === "" ? null : html`<p class="talk-try small" data-pane-try>Try: ${steer.try}</p>`}<div class="talk-stage" data-stage data-env="${ws.shows === undefined ? "production" : previewEnv(ws.shows)}"><iframe class="talk-frame" data-frame src="${url}" title="Live preview of ${name}" referrerpolicy="no-referrer" sandbox="${devFrame === undefined ? "allow-scripts allow-same-origin allow-forms allow-popups" : "allow-scripts allow-forms allow-popups"}"></iframe><p class="talk-stage-note small" data-stage-note hidden>Updating the preview…</p></div>${crewRegion(crew !== undefined && (going || crew.state === "failed") ? crew : undefined, ws.repo, liveSrc, () => ctx.url.pathname, ws.shows, offer)}`; | |
| 107 | 114 | // The address bar of what runs: which environment, where it lives, reload and open on its own. |
| 108 | 115 | const where = url === undefined ? null : html`<span class="talk-addr small" title="${url}"><span class="muted">${ws.shows === undefined ? "Production" : `Pull #${String(ws.shows)}`}</span> ${new URL(url).host}</span>`; |
| 109 | 116 | // Waiting, the pane is a live region on the repository's runs: a deploy that turns running swaps |
| @@ -126,23 +133,29 @@ export async function talkPane(ctx: Ctx, user: User, name: string | undefined, w | ||
| 126 | 133 | </form>`; |
| 127 | 134 | // The workspace's status, in one word: starting, live, reloading, or the error with its file and |
| 128 | 135 | // line. |
| 129 | const status = paneStatus({ url, crew, busy: ask.busy === true }); | |
| 136 | const status = paneStatus({ url, crew, busy: ask.busy === true, dev }); | |
| 130 | 137 | const statusPill = html`<span class="talk-dev-status small" data-dev-status="${status.state}" role="status" title="${status.word}${status.state === "error" ? "; ask the crew to fix it" : ""}">${status.state === "error" ? "Error" : status.word}</span>`; |
| 138 | // Start or stop the dev server: a writer's, and only for a repository that is an app. | |
| 139 | const mayDev = requireWriter(ctx.app, user, ws.repo).ok && getAppByRepo(ctx.app.db, ws.repo.id) !== undefined; | |
| 140 | const devForm = !mayDev | |
| 141 | ? null | |
| 142 | : html`<form class="talk-dev-form" method="post" action="/talk/dev"><input type="hidden" name="repo" value="${name}"><input type="hidden" name="pull" value="${ws.shows === undefined ? "" : String(ws.shows)}"><button class="btn btn-sm" name="act" value="${dev === undefined || dev.state === "error" ? "start" : "stop"}" type="submit" title="${dev === undefined || dev.state === "error" ? `Run ${branch} with hot reload` : `Stop the dev server of ${branch}`}">${dev === undefined ? "Start dev server" : dev.state === "error" ? "Restart dev server" : "Stop dev server"}</button></form>`; | |
| 131 | 143 | const fell = paneFell(ctx.app.db, ws.repo.id, ws.fell); |
| 132 | 144 | const fellLine = fell === undefined ? null : html`<p class="talk-pane-fell small" role="status">${fell}</p>`; |
| 133 | 145 | return { |
| 134 | frame: ws.origin ?? (going ? productionOrigin(ctx, ws.repo.id) : undefined), | |
| 146 | frame: devFrame !== undefined ? ctx.url.origin : ws.origin ?? (going ? productionOrigin(ctx, ws.repo.id) : undefined), | |
| 135 | 147 | live: url !== undefined, |
| 136 | 148 | crew: going, |
| 137 | html: html`<aside class="talk-pane" id="talk-pane" aria-label="Preview of ${name}" data-pane-of="${name}" data-presence="${name}" data-pane-q="${q}"${waiting ? html` data-live="run.*" data-live-repo="${ws.repo.ownerName}/${ws.repo.name}" data-live-src="${liveSrc}"` : null}> | |
| 149 | html: html`<aside class="talk-pane" id="talk-pane" aria-label="Preview of ${name}" data-pane-of="${name}" data-presence="${name}" data-pane-q="${q}"${waiting || dev?.state === "starting" ? html` data-live="${waiting ? "run.*," : ""}dev.state" data-live-repo="${ws.repo.ownerName}/${ws.repo.name}" data-live-src="${liveSrc}"` : null}> | |
| 138 | 150 | <div class="talk-pane-bar"> |
| 139 | 151 | <nav class="seg" aria-label="Preview, code or diff">${tab("preview", "Preview")}${tab("code", "Code")}${tab("diff", "Diff")}</nav> |
| 140 | 152 | ${bar} |
| 141 | 153 | ${statusPill} |
| 154 | ${devForm} | |
| 142 | 155 | ${url === undefined || view !== "preview" ? null : iconBtn("sync", "Reload the preview", { variant: "ghost", type: "button", extra: "js-only talk-reload" })} |
| 143 | 156 | ${url === undefined ? null : btn(icon("external"), { href: url, label: `Open ${name} on its own`, title: "Open on its own", variant: "ghost", external: true, extra: "btn-icon" })} |
| 144 | 157 | </div> |
| 145 | <p class="talk-pane-info small muted" data-pane-info>${paneInfo(ctx.app.db, ws.repo, ws.shows)}${ws.shows === undefined ? null : html` · <a href="/${name}/pulls/${String(ws.shows)}">the pull</a>`}</p> | |
| 158 | <p class="talk-pane-info small muted" data-pane-info>${paneInfo(ctx.app.db, ws.repo, ws.shows)}${ws.shows === undefined ? null : html` · <a href="/${name}/pulls/${String(ws.shows)}">the pull</a>`}${devFrame === undefined ? null : html` · The dev server runs in a sandboxed frame: sign-in and forms that post do not work in it.`}</p> | |
| 146 | 159 | ${togetherHtml(ctx.app.db, ws.repo, user, "live")} |
| 147 | 160 | ${fellLine} |
| 148 | 161 | ${panel} |
test/budgets/pages/talk.json +2 −2
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "pattern": "/talk", |
| 3 | "statements": 62, | |
| 4 | "why": "+1 on a conversation with no message yet, as the fixture's is: the person's unsent files (a picture shared from a phone, #16311) ride the read of the sent ones, so a conversation with messages pays nothing more; +1: the conversation's own plan, pinned at the top, one primary-key read (#16575)" | |
| 3 | "statements": 64, | |
| 4 | "why": "+1 on a conversation with no message yet, as the fixture's is: the person's unsent files (a picture shared from a phone, #16311) ride the read of the sent ones, so a conversation with messages pays nothing more; +1: the conversation's own plan, pinned at the top, one primary-key read (#16575); +2: the workspace bar reads the repository and its dev cell (#17135, #17140)" | |
| 5 | 5 | } |
test/budgets/unfixtured/talk-dev-token-path.json added +4
test/budgets/unfixtured/talk-dev-token.json added +4
test/dev-cell-launch.test.ts added +69
| @@ -0,0 +1,69 @@ | ||
| 1 | /** | |
| 2 | * The real launcher (#17140): an app's branch checked out, its `app.dev` command run through | |
| 3 | * `startProcess`, the bar reading the server's own state, a commit to the branch reaching the | |
| 4 | * running server, and the frame path relaying it. No cell: the host here may not hold one, and the | |
| 5 | * process then runs as an app's does. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { rm } from "node:fs/promises"; | |
| 9 | import { newApp } from "../src/actions/apps.ts"; | |
| 10 | import { commitToBranch } from "../src/actions/repos.ts"; | |
| 11 | import { devReading, startDev, stopDev } from "../src/actions/dev_workspace.ts"; | |
| 12 | import { identityKey } from "../src/apps/grants.ts"; | |
| 13 | import { getAppByRepo } from "../src/core/apps.ts"; | |
| 14 | import { getRepo } from "../src/core/repos.ts"; | |
| 15 | import { startAppsForge, type AppsForge } from "./helpers/apps-forge.ts"; | |
| 16 | import { pollUntil } from "./helpers/poll.ts"; | |
| 17 | import { quietLogs } from "./helpers/globals.ts"; | |
| 18 | ||
| 19 | quietLogs(); | |
| 20 | ||
| 21 | const SERVER = `Bun.serve({ port: Number(process.env.PORT), hostname: "127.0.0.1", fetch: (r) => new URL(r.url).pathname === "/key" ? new Response(String(process.env.FORGE_APP_IDENTITY_KEY) + "|" + String(process.env.FORGE_TOKEN)) : new Response(require("fs").readFileSync("message.txt", "utf8")) });`; | |
| 22 | ||
| 23 | describe("a dev cell for a branch", () => { | |
| 24 | let forge: AppsForge; | |
| 25 | beforeAll(async () => { | |
| 26 | forge = await startAppsForge(); | |
| 27 | }); | |
| 28 | afterAll(async () => { | |
| 29 | await forge.runtime.stop?.(); | |
| 30 | await forge.servers.stop?.(); | |
| 31 | await rm(forge.dataDir, { recursive: true, force: true }); | |
| 32 | }); | |
| 33 | ||
| 34 | test("runs the declared command on the branch, and a commit to the branch shows in it", async () => { | |
| 35 | const made = await newApp(forge.app, forge.alice, { name: "devapp", visibility: "private" }); | |
| 36 | if (!made.ok) throw new Error(String(made.error)); | |
| 37 | const repo = getRepo(forge.app.db, forge.alice.username, "devapp"); | |
| 38 | if (repo === undefined) throw new Error("repo"); | |
| 39 | const put = async (message: string): Promise<void> => { | |
| 40 | const c = await commitToBranch(forge.app, forge.alice, repo, { | |
| 41 | branch: repo.defaultBranch, | |
| 42 | message: "files", | |
| 43 | files: [ | |
| 44 | { path: "forge.json", content: JSON.stringify({ app: { run: "bun server.ts", dev: "bun --hot server.ts", ready: 30 } }) }, | |
| 45 | { path: "server.ts", content: SERVER }, | |
| 46 | { path: "message.txt", content: message }, | |
| 47 | ], | |
| 48 | }); | |
| 49 | if (!c.ok) throw new Error(JSON.stringify(c.error)); | |
| 50 | }; | |
| 51 | await put("first"); | |
| 52 | expect(startDev(forge.app, forge.alice, repo, repo.defaultBranch).ok).toBe(true); | |
| 53 | const read = () => devReading(forge.app, forge.alice, repo, repo.defaultBranch); | |
| 54 | await pollUntil(() => read()?.state !== "starting", "the dev server answering", 30_000); | |
| 55 | const reading = read(); | |
| 56 | if (reading?.state !== "live") throw new Error(reading?.error ?? "not live"); | |
| 57 | const ask = async (): Promise<string> => (await fetch(`${forge.servers.url}/talk/dev/${reading.token}/`)).text(); | |
| 58 | expect(await ask()).toBe("first"); | |
| 59 | // The branch's code is a writer's: it is not given the app's identity key, nor a forge token. | |
| 60 | const seen = await (await fetch(`${forge.servers.url}/talk/dev/${reading.token}/key`)).text(); | |
| 61 | expect(seen).not.toContain(identityKey(forge.app.config.dataDir, getAppByRepo(forge.app.db, repo.id)!.id)); | |
| 62 | expect(seen).toEndWith("|undefined"); | |
| 63 | await put("second"); | |
| 64 | // The push event syncs the branch's new tip in; the hot server then answers with the new file. | |
| 65 | await pollUntil(async () => (await ask()) === "second", "the commit reaching the running server", 30_000); | |
| 66 | expect(await stopDev(forge.app, forge.alice, repo, repo.defaultBranch)).toBe(true); | |
| 67 | expect(devReading(forge.app, forge.alice, repo, repo.defaultBranch)).toBeUndefined(); | |
| 68 | }, 60_000); | |
| 69 | }); |
test/dev-cell.test.ts added +363
| @@ -0,0 +1,363 @@ | ||
| 1 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 2 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { createApp, type App } from "../src/app.ts"; | |
| 6 | import { devCommand, hot } from "../src/apps/dev_command.ts"; | |
| 7 | import { devCellsOf, type DevLaunch, type DevRun } from "../src/apps/dev_cell.ts"; | |
| 8 | import { devEnv, devKey, syncCheckout } from "../src/apps/dev_launch.ts"; | |
| 9 | import { devReading, paneStatus, startDev, stopDev } from "../src/actions/dev_workspace.ts"; | |
| 10 | import { relayedLocation } from "../src/web/pages/talk_dev.ts"; | |
| 11 | import { createApp as createAppRecord } from "../src/core/apps.ts"; | |
| 12 | import { tokenFor } from "./helpers/tokens.ts"; | |
| 13 | import { createRepo, type Repo } from "../src/core/repos.ts"; | |
| 14 | import { createUser, type User } from "../src/core/users.ts"; | |
| 15 | import { runLocal } from "../src/git/local.ts"; | |
| 16 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 17 | import { err, ok } from "../src/kernel/result.ts"; | |
| 18 | import { pollUntil } from "./helpers/poll.ts"; | |
| 19 | import { quietLogs } from "./helpers/globals.ts"; | |
| 20 | ||
| 21 | quietLogs(); | |
| 22 | ||
| 23 | const git = async (cwd: string, ...args: string[]): Promise<void> => { | |
| 24 | const made = await runLocal(["-c", "user.name=t", "-c", "user.email=t@t", ...args], { cwd }); | |
| 25 | if (!made.ok) throw new Error(`git ${args.join(" ")}: ${made.error.stderr}`); | |
| 26 | }; | |
| 27 | ||
| 28 | /** A run that is a real function of a fake server: ends when told, says what it printed last. */ | |
| 29 | const fake = (port: number, lines: string[] = []): { run: DevRun; end: () => void; stopped: () => boolean } => { | |
| 30 | let end: () => void = () => {}; | |
| 31 | let stopped = false; | |
| 32 | const exited = new Promise<void>((r) => (end = r)); | |
| 33 | return { run: { port, exited, recent: () => lines, stop: async () => { stopped = true; end(); } }, end: () => end(), stopped: () => stopped }; | |
| 34 | }; | |
| 35 | const until = async <T>(read: () => T | undefined): Promise<T> => { | |
| 36 | await pollUntil(() => read() !== undefined, "the state asked for", 10_000); | |
| 37 | return read() as T; | |
| 38 | }; | |
| 39 | ||
| 40 | describe("the dev command (#17140)", () => { | |
| 41 | test("app.dev wins, then scripts.dev, then the run command made hot", () => { | |
| 42 | expect(devCommand({ forgeJson: JSON.stringify({ app: { run: "bun a.ts", dev: "bun --hot a.ts --dev" } }), packageJson: JSON.stringify({ scripts: { dev: "x" } }) })).toBe("bun --hot a.ts --dev"); | |
| 43 | expect(devCommand({ forgeJson: JSON.stringify({ app: { run: "bun a.ts" } }), packageJson: JSON.stringify({ scripts: { dev: "vite" } }) })).toBe("bun run dev"); | |
| 44 | expect(devCommand({ run: "bun run src/main.ts" })).toBe("bun --hot src/main.ts"); | |
| 45 | expect(devCommand({ run: "node server.js" })).toBe("node server.js"); | |
| 46 | }); | |
| 47 | test("a command on several lines, empty or past the cap is not taken; bun --hot is left as it is", () => { | |
| 48 | expect(devCommand({ forgeJson: JSON.stringify({ app: { dev: "a\nb" } }) })).toBeUndefined(); | |
| 49 | expect(devCommand({ forgeJson: "not json", packageJson: "{" })).toBeUndefined(); | |
| 50 | expect(devCommand({ run: "x".repeat(501) })).toBeUndefined(); | |
| 51 | expect(hot("bun --hot a.ts")).toBe("bun --hot a.ts"); | |
| 52 | }); | |
| 53 | }); | |
| 54 | ||
| 55 | describe("the registry of dev cells", () => { | |
| 56 | let app: App; | |
| 57 | let dir: string; | |
| 58 | beforeAll(async () => { | |
| 59 | dir = await mkdtemp(join(tmpdir(), "forge-dev-cell-")); | |
| 60 | app = createApp({ dataDir: dir, port: 0 }); | |
| 61 | }); | |
| 62 | afterAll(() => rm(dir, { recursive: true, force: true })); | |
| 63 | ||
| 64 | test("a cell is starting until its server answers, then live; asking again finds the same one", async () => { | |
| 65 | const cells = devCellsOf(app); | |
| 66 | const f = fake(1234); | |
| 67 | let release: () => void = () => {}; | |
| 68 | const gate = new Promise<void>((r) => (release = r)); | |
| 69 | const launch: DevLaunch = async () => { await gate; return ok(f.run); }; | |
| 70 | const a = cells.ensure("k1", "u", "r", launch); | |
| 71 | expect(cells.reading("k1")?.state).toBe("starting"); | |
| 72 | expect(cells.ensure("k1", "u", "r", launch)).toBe(a); | |
| 73 | release(); | |
| 74 | await until(() => (cells.reading("k1")?.state === "live" ? true : undefined)); | |
| 75 | expect(cells.byToken(a.token)?.run?.port).toBe(1234); | |
| 76 | expect(cells.byToken("nope")).toBeUndefined(); | |
| 77 | await cells.stop("k1"); | |
| 78 | expect(f.stopped()).toBe(true); | |
| 79 | expect(cells.reading("k1")).toBeUndefined(); | |
| 80 | }); | |
| 81 | ||
| 82 | test("a server that ends is an error with its last words, and asking again starts a fresh one", async () => { | |
| 83 | const cells = devCellsOf(app); | |
| 84 | const f = fake(1, ["warming", "error: Unexpected token at src/app.ts:7:3"]); | |
| 85 | const a = cells.ensure("k2", "u", "r", async () => ok(f.run)); | |
| 86 | await until(() => (cells.reading("k2")?.state === "live" ? true : undefined)); | |
| 87 | f.end(); | |
| 88 | const read = await until(() => (cells.reading("k2")?.state === "error" ? cells.reading("k2") : undefined)); | |
| 89 | expect(read.error).toContain("src/app.ts:7"); | |
| 90 | expect(paneStatus({ url: undefined, crew: undefined, dev: read }).word).toBe("Error in src/app.ts:7"); | |
| 91 | const b = cells.ensure("k2", "u", "r", async () => ok(fake(2).run)); | |
| 92 | expect(b.token).not.toBe(a.token); | |
| 93 | await cells.stop("k2"); | |
| 94 | }); | |
| 95 | ||
| 96 | test("a launch that fails is the words it failed with", async () => { | |
| 97 | const cells = devCellsOf(app); | |
| 98 | cells.ensure("k3", "u", "r", async () => err("install: bun install failed")); | |
| 99 | expect(await until(() => cells.reading("k3")?.error)).toBe("install: bun install failed"); | |
| 100 | await cells.stop("k3"); | |
| 101 | }); | |
| 102 | ||
| 103 | test("an idle cell sleeps (its process stops), a touched one stays, and no one's cells are ever stopped to make room for another's", async () => { | |
| 104 | const cells = devCellsOf(app); | |
| 105 | const a = fake(1); | |
| 106 | const b = fake(2); | |
| 107 | cells.ensure("idle", "u", "r", async () => ok(a.run), 1_000); | |
| 108 | cells.ensure("busy", "u", "r", async () => ok(b.run), 1_000); | |
| 109 | await until(() => (cells.get("busy")?.state === "live" && cells.get("idle")?.state === "live" ? true : undefined)); | |
| 110 | cells.get("busy", true, 90_000); | |
| 111 | expect(await cells.sweep(100_000, 60_000)).toEqual(["idle"]); | |
| 112 | expect(a.stopped()).toBe(true); | |
| 113 | expect(b.stopped()).toBe(false); | |
| 114 | await cells.stop("busy"); | |
| 115 | const runs: ReturnType<typeof fake>[] = []; | |
| 116 | for (let i = 0; i < 12; i++) { | |
| 117 | const f = fake(i); | |
| 118 | runs.push(f); | |
| 119 | cells.ensure(`n${i}`, `person${i % 3}`, "r", async () => ok(f.run), 2_000 + i); | |
| 120 | await until(() => (cells.get(`n${i}`)?.state === "live" ? true : undefined)); | |
| 121 | } | |
| 122 | expect(cells.size).toBe(12); | |
| 123 | expect(runs.some((r) => r.stopped())).toBe(false); | |
| 124 | for (let i = 0; i < 12; i++) await cells.stop(`n${i}`); | |
| 125 | }); | |
| 126 | ||
| 127 | test("a read of the bar leaves the idle clock alone; the frame's own request keeps it awake; a token finds its cell", async () => { | |
| 128 | const cells = devCellsOf(app); | |
| 129 | const c = cells.ensure("clock", "u", "r", async () => ok(fake(7).run), 1_000); | |
| 130 | await until(() => (c.state === "live" ? true : undefined)); | |
| 131 | cells.reading("clock"); | |
| 132 | expect(c.touchedAt).toBe(1_000); | |
| 133 | expect(cells.byToken(c.token, 5_000)).toBe(c); | |
| 134 | expect(c.touchedAt).toBe(5_000); | |
| 135 | expect(await cells.stopOf("someone-else", "r")).toBe(0); | |
| 136 | expect(await cells.stopOf("u", "r")).toBeGreaterThanOrEqual(1); | |
| 137 | expect(cells.byToken(c.token)).toBeUndefined(); | |
| 138 | }); | |
| 139 | ||
| 140 | test("two people on one branch have two cells", () => { | |
| 141 | expect(devKey("a", "r", "main")).not.toBe(devKey("b", "r", "main")); | |
| 142 | expect(devEnv(devKey("a", "r", "main"))).toMatch(/^variant-d[0-9a-f]{10}$/); | |
| 143 | }); | |
| 144 | }); | |
| 145 | ||
| 146 | describe("the checkout of a branch", () => { | |
| 147 | test("is cloned, then synced to each new tip, so the running server sees the files change", async () => { | |
| 148 | const dir = await mkdtemp(join(tmpdir(), "forge-dev-sync-")); | |
| 149 | try { | |
| 150 | const work = join(dir, "work"); | |
| 151 | const bare = join(dir, "bare.git"); | |
| 152 | await git(dir, "init", "-q", "-b", "main", work); | |
| 153 | await Bun.write(join(work, "a.txt"), "one"); | |
| 154 | await git(work, "add", "."); | |
| 155 | await git(work, "commit", "-q", "-m", "one"); | |
| 156 | await git(dir, "clone", "-q", "--bare", work, bare); | |
| 157 | const checkout = join(dir, "dev", "x"); | |
| 158 | const first = await syncCheckout(bare, checkout, "main"); | |
| 159 | expect(first.ok && (await Bun.file(join(checkout, "a.txt")).text())).toBe("one"); | |
| 160 | await Bun.write(join(work, "a.txt"), "two"); | |
| 161 | await git(work, "commit", "-q", "-am", "two"); | |
| 162 | await git(bare, "fetch", "-q", work, "+main:refs/heads/main"); | |
| 163 | const second = await syncCheckout(bare, checkout, "main"); | |
| 164 | expect(second.ok && second.value).not.toBe(first.ok && first.value); | |
| 165 | expect(await Bun.file(join(checkout, "a.txt")).text()).toBe("two"); | |
| 166 | expect((await syncCheckout(bare, checkout, "nope")).ok).toBe(false); | |
| 167 | expect((await syncCheckout(bare, checkout, "--upload-pack=x")).ok).toBe(false); | |
| 168 | } finally { | |
| 169 | await rm(dir, { recursive: true, force: true }); | |
| 170 | } | |
| 171 | }); | |
| 172 | }); | |
| 173 | ||
| 174 | describe("the doors", () => { | |
| 175 | let dir: string; | |
| 176 | let app: App; | |
| 177 | let servers: Servers; | |
| 178 | let alice: User; | |
| 179 | let bob: User; | |
| 180 | let repo: Repo; | |
| 181 | let upstream: ReturnType<typeof Bun.serve>; | |
| 182 | beforeAll(async () => { | |
| 183 | dir = await mkdtemp(join(tmpdir(), "forge-dev-doors-")); | |
| 184 | app = createApp({ dataDir: dir, port: 0 }); | |
| 185 | servers = await serve(app); | |
| 186 | const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 187 | const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 188 | if (!a.ok || !b.ok) throw new Error("users"); | |
| 189 | alice = a.value; | |
| 190 | bob = b.value; | |
| 191 | const made = await createRepo(app.db, app.reposRoot, { ownerId: alice.id, name: "plain", visibility: "public" }); | |
| 192 | if (!made.ok) throw new Error("repo"); | |
| 193 | repo = made.value; | |
| 194 | upstream = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: (req) => { | |
| 195 | const u = new URL(req.url); | |
| 196 | if (u.pathname === "/go") return new Response(null, { status: 302, headers: { location: "/there" } }); | |
| 197 | return new Response(`<p>hi ${u.pathname}${u.search} cookie=${req.headers.get("cookie") ?? "none"}</p>`, { headers: { "content-type": "text/html", "set-cookie": "s=1" } }); | |
| 198 | } }); | |
| 199 | }); | |
| 200 | afterAll(async () => { | |
| 201 | upstream.stop(true); | |
| 202 | await servers.stop?.(); | |
| 203 | await rm(dir, { recursive: true, force: true }); | |
| 204 | }); | |
| 205 | ||
| 206 | test("the frame path serves the dev server sandboxed, with no cookie either way, and only by its token", async () => { | |
| 207 | const cell = devCellsOf(app).ensure("relay", alice.id, repo.id, async () => ok(fake(upstream.port ?? 0).run)); | |
| 208 | await until(() => (cell.state === "live" ? true : undefined)); | |
| 209 | const res = await fetch(`${servers.url}/talk/dev/${cell.token}/a/b?x=1`, { headers: { cookie: "forge=secret" } }); | |
| 210 | expect(res.status).toBe(200); | |
| 211 | const body = await res.text(); | |
| 212 | expect(body).toContain("hi /a/b?x=1"); | |
| 213 | expect(body).toContain("cookie=none"); | |
| 214 | expect(res.headers.get("set-cookie")).toBeNull(); | |
| 215 | expect(res.headers.get("content-security-policy")).toStartWith("sandbox allow-scripts"); | |
| 216 | expect(res.headers.get("cross-origin-resource-policy")).toBe("cross-origin"); | |
| 217 | const moved = await fetch(`${servers.url}/talk/dev/${cell.token}/go`, { redirect: "manual" }); | |
| 218 | expect(moved.headers.get("location")).toBe(`/talk/dev/${cell.token}/there`); | |
| 219 | expect((await fetch(`${servers.url}/talk/dev/${"0".repeat(48)}/`)).status).toBe(404); | |
| 220 | expect((await fetch(`${servers.url}/talk/dev/${cell.token}/%2e%2e/x`)).status).not.toBe(500); | |
| 221 | expect((await fetch(`${servers.url}/talk/dev/${cell.token}/`, { method: "POST", body: "x" })).status).not.toBe(200); | |
| 222 | await devCellsOf(app).stop("relay"); | |
| 223 | }); | |
| 224 | ||
| 225 | test("a redirect of the dev server stays under the token; its own absolute address is the same path; any other is refused", () => { | |
| 226 | const base = "/talk/dev/t/"; | |
| 227 | expect(relayedLocation("/there?x=1", 4000, base)).toBe("/talk/dev/t/there?x=1"); | |
| 228 | expect(relayedLocation("http://127.0.0.1:4000/a/b?c=d", 4000, base)).toBe("/talk/dev/t/a/b?c=d"); | |
| 229 | expect(relayedLocation("http://localhost:4000/a", 4000, base)).toBe("/talk/dev/t/a"); | |
| 230 | expect(relayedLocation("http://127.0.0.1:9999/a", 4000, base)).toBeUndefined(); | |
| 231 | expect(relayedLocation("https://evil.example/a", 4000, base)).toBeUndefined(); | |
| 232 | expect(relayedLocation("//evil.example/a", 4000, base)).toBeUndefined(); | |
| 233 | expect(relayedLocation("/\\evil.example", 4000, base)).toBeUndefined(); | |
| 234 | expect(relayedLocation("relative", 4000, base)).toBeUndefined(); | |
| 235 | }); | |
| 236 | ||
| 237 | test("an absolute redirect to the server's own port is rewritten in the frame, and one elsewhere is a 502 that names no port", async () => { | |
| 238 | const cells = devCellsOf(app); | |
| 239 | const abs = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: (req, self) => { | |
| 240 | const u = new URL(req.url); | |
| 241 | const to = u.pathname === "/own" ? `http://127.0.0.1:${String(self.port)}/landed` : "http://169.254.169.254/x"; | |
| 242 | return new Response(null, { status: 302, headers: { location: to } }); | |
| 243 | } }); | |
| 244 | try { | |
| 245 | const cell = cells.ensure("abs", alice.id, repo.id, async () => ok(fake(abs.port ?? 0).run)); | |
| 246 | await until(() => (cell.state === "live" ? true : undefined)); | |
| 247 | const own = await fetch(`${servers.url}/talk/dev/${cell.token}/own`, { redirect: "manual" }); | |
| 248 | expect(own.headers.get("location")).toBe(`/talk/dev/${cell.token}/landed`); | |
| 249 | const other = await fetch(`${servers.url}/talk/dev/${cell.token}/else`, { redirect: "manual" }); | |
| 250 | expect(other.status).toBe(502); | |
| 251 | expect(other.headers.get("location")).toBeNull(); | |
| 252 | expect(await other.text()).not.toContain(String(abs.port)); | |
| 253 | } finally { | |
| 254 | await cells.stop("abs"); | |
| 255 | abs.stop(true); | |
| 256 | } | |
| 257 | }); | |
| 258 | ||
| 259 | test("a writer who loses write access loses the cell: the token stops answering and the cell is stopped", async () => { | |
| 260 | const cells = devCellsOf(app); | |
| 261 | const lost = await createRepo(app.db, app.reposRoot, { ownerId: alice.id, name: "lost", visibility: "public" }); | |
| 262 | if (!lost.ok) throw new Error("repo"); | |
| 263 | // Bob is not a writer of it: a cell of his on it ends at its first request. | |
| 264 | const f = fake(upstream.port ?? 0); | |
| 265 | const cell = cells.ensure("lost", bob.id, lost.value.id, async () => ok(f.run)); | |
| 266 | await until(() => (cell.state === "live" ? true : undefined)); | |
| 267 | expect((await fetch(`${servers.url}/talk/dev/${cell.token}/`)).status).toBe(404); | |
| 268 | await until(() => (f.stopped() ? true : undefined)); | |
| 269 | expect(cells.get("lost")).toBeUndefined(); | |
| 270 | }); | |
| 271 | ||
| 272 | test("a push to the branch a cell runs is synced when it happens; a read of the bar does not look", async () => { | |
| 273 | const cells = devCellsOf(app); | |
| 274 | const f = fake(1); | |
| 275 | const { run } = f; | |
| 276 | const checkout = await mkdtemp(join(tmpdir(), "forge-dev-push-")); | |
| 277 | let repoId = ""; | |
| 278 | try { | |
| 279 | const made = await createRepo(app.db, app.reposRoot, { ownerId: alice.id, name: "pushy", visibility: "public" }); | |
| 280 | if (!made.ok) throw new Error("repo"); | |
| 281 | repoId = made.value.id; | |
| 282 | createAppRecord(app.db, { repoId: made.value.id, slug: "pushy", access: "private" }); | |
| 283 | const bare = join(app.reposRoot, "alice", "pushy.git"); | |
| 284 | const work = join(checkout, "work"); | |
| 285 | await git(checkout, "init", "-q", "-b", "main", work); | |
| 286 | await Bun.write(join(work, "a.txt"), "one"); | |
| 287 | await git(work, "add", "."); | |
| 288 | await git(work, "commit", "-q", "-m", "one"); | |
| 289 | await git(bare, "fetch", "-q", work, "+main:refs/heads/main"); | |
| 290 | const dir = join(checkout, "dev"); | |
| 291 | const first = await syncCheckout(bare, dir, "main"); | |
| 292 | if (!first.ok) throw new Error(first.error); | |
| 293 | const started = startDev(app, alice, made.value, "main"); | |
| 294 | expect(started.ok).toBe(true); | |
| 295 | await cells.stop(devKey(alice.id, made.value.id, "main")); | |
| 296 | const cell = cells.ensure(devKey(alice.id, made.value.id, "main"), alice.id, made.value.id, async () => ok({ ...run, dir, oid: first.value })); | |
| 297 | cell.branch = "main"; | |
| 298 | await until(() => (cell.state === "live" ? true : undefined)); | |
| 299 | await Bun.write(join(work, "a.txt"), "two"); | |
| 300 | await git(work, "commit", "-q", "-am", "two"); | |
| 301 | await git(bare, "fetch", "-q", work, "+main:refs/heads/main"); | |
| 302 | expect(devReading(app, alice, made.value, "main")?.state).toBe("live"); | |
| 303 | expect(await Bun.file(join(dir, "a.txt")).text()).toBe("one"); | |
| 304 | app.bus.append({ kind: "push", repoId: made.value.id, actorId: alice.id, payload: { updates: [{ ref: "refs/heads/main", oldOid: "a", newOid: "b" }] } }); | |
| 305 | await pollUntil(async () => (await Bun.file(join(dir, "a.txt")).text()) === "two", "the checkout to follow the push", 10_000); | |
| 306 | } finally { | |
| 307 | await cells.stop(devKey(alice.id, repoId, "main")); | |
| 308 | await rm(checkout, { recursive: true, force: true }); | |
| 309 | } | |
| 310 | }); | |
| 311 | ||
| 312 | test("POST /talk/dev: another origin, a guest, a non-writer, a repository that is no app are each refused; a writer's start and stop work", async () => { | |
| 313 | const post = (token: string | undefined, fields: Record<string, string>, origin?: string): Promise<Response> => | |
| 314 | fetch(`${servers.url}/talk/dev`, { | |
| 315 | method: "POST", | |
| 316 | redirect: "manual", | |
| 317 | headers: { "content-type": "application/x-www-form-urlencoded", ...(token === undefined ? {} : { authorization: `Bearer ${token}` }), ...(origin === undefined ? {} : { origin }) }, | |
| 318 | body: new URLSearchParams(fields).toString(), | |
| 319 | }); | |
| 320 | const aliceToken = tokenFor(app, "alice", "rw"); | |
| 321 | const bobToken = tokenFor(app, "bob", "rw"); | |
| 322 | const form = { repo: "alice/plain", pull: "", act: "start" }; | |
| 323 | const posty = await createRepo(app.db, app.reposRoot, { ownerId: alice.id, name: "posty", visibility: "public" }); | |
| 324 | if (!posty.ok) throw new Error("repo"); | |
| 325 | const appForm = { ...form, repo: "alice/posty" }; | |
| 326 | const none = devCellsOf(app).size; | |
| 327 | expect((await post(aliceToken, form, "https://evil.example")).status).toBe(403); | |
| 328 | expect((await post(undefined, form)).status).not.toBeLessThan(300); | |
| 329 | expect(devReading(app, alice, repo, "main")).toBeUndefined(); | |
| 330 | // A non-writer: flashed away, nothing started. | |
| 331 | const denied = await post(bobToken, form); | |
| 332 | expect(denied.status).toBe(303); | |
| 333 | expect(devReading(app, bob, repo, "main")).toBeUndefined(); | |
| 334 | // A repository that is not an app. | |
| 335 | const noApp = await post(aliceToken, form); | |
| 336 | expect(noApp.status).toBe(303); | |
| 337 | expect(devReading(app, alice, repo, "main")).toBeUndefined(); | |
| 338 | // An app: a writer's start holds a cell; its stop ends it. | |
| 339 | createAppRecord(app.db, { repoId: posty.value.id, slug: "posty", access: "private" }); | |
| 340 | expect((await post(aliceToken, appForm)).status).toBe(303); | |
| 341 | expect(devReading(app, alice, posty.value, "main")).toBeDefined(); | |
| 342 | expect(devReading(app, bob, posty.value, "main")).toBeUndefined(); | |
| 343 | expect((await post(aliceToken, { ...appForm, act: "stop" })).status).toBe(303); | |
| 344 | expect(devReading(app, alice, posty.value, "main")).toBeUndefined(); | |
| 345 | expect(await stopDev(app, bob, posty.value, "main")).toBe(false); | |
| 346 | expect(devCellsOf(app).size).toBe(none); | |
| 347 | }); | |
| 348 | ||
| 349 | test("only a writer starts one, and only for an app", () => { | |
| 350 | expect(startDev(app, bob, repo, "main")).toEqual({ ok: false, error: "forbidden" }); | |
| 351 | expect(startDev(app, alice, repo, "main")).toEqual({ ok: false, error: "no_app" }); | |
| 352 | }); | |
| 353 | ||
| 354 | test("the bar's status is the server's: starting, live, the error it ended on; nothing held reads as before", async () => { | |
| 355 | expect(devReading(app, alice, repo, "main")).toBeUndefined(); | |
| 356 | expect(paneStatus({ url: "https://x", crew: undefined }).state).toBe("live"); | |
| 357 | expect(paneStatus({ url: "https://x", crew: undefined, dev: { state: "starting" } }).state).toBe("starting"); | |
| 358 | expect(paneStatus({ url: undefined, crew: undefined, dev: { state: "live" } }).state).toBe("live"); | |
| 359 | expect(paneStatus({ url: undefined, crew: { state: "running", line: { says: "" } }, dev: { state: "live" } }).state).toBe("reloading"); | |
| 360 | expect(paneStatus({ url: "https://x", crew: { state: "failed", line: { says: "at src/z.ts:1" } }, dev: { state: "live" } }).state).toBe("live"); | |
| 361 | expect(paneStatus({ url: "https://x", crew: undefined, dev: { state: "error" } }).word).toBe("Error"); | |
| 362 | }); | |
| 363 | }); |
test/job-slices.test.ts +1
| @@ -266,6 +266,7 @@ function jobs(): Record<string, () => unknown> { | ||
| 266 | 266 | * on. |
| 267 | 267 | */ |
| 268 | 268 | const UNTIMED: Record<string, string> = { |
| 269 | "dev-cell-sweep": "a minute timer that stops dev cells idle past their limit (apps/dev_cell.ts sweep): a walk of the in-memory entries (one per person and branch), a kill only for an idle one; dev-cell.test.ts drives sweep", | |
| 269 | 270 | "machine-beats": "a 15 s timer (spawn/machine_beats.ts) whose beat only starts an async import and the machines' asks; its synchronous slice is the call that starts them; machine-load.test.ts drives sampleBeats and placeNew directly", |
| 270 | 271 | "osv-mirror": "hourly: fetches advisories for the pins the forge holds from api.osv.dev, then files fix issues; network and git reads off the loop (security/duty.ts, fix_issues.ts); security-osv.test.ts drives both", |
| 271 | 272 | "config-poll": "a short timer that re-reads one small row per scope and fires listeners only when another process changed it (core/config.ts start/refresh); config-store.test.ts drives a change from a second handle", |
test/no-polling.test.ts +2
| @@ -303,6 +303,8 @@ export function findPolling(source: string): string[] { | ||
| 303 | 303 | */ |
| 304 | 304 | const ORIGIN = "needs a connected origin account; the seed connects none"; |
| 305 | 305 | const NOT_WALKED: Record<string, string> = { |
| 306 | "/talk/dev/:token": "a frame proxied from a running dev cell, not a page; the seed starts none", | |
| 307 | "/talk/dev/:token/*path": "a file proxied from a running dev cell, not a page; the seed starts none", | |
| 306 | 308 | "/edge/config/:file": "a published config file for the edge, JSON or a key, not a page; the seed publishes none", |
| 307 | 309 | "/:owner/-/teams/:team": "needs an organization and a team", |
| 308 | 310 | "/:owner/:name/app/:env/open": "needs a running app environment to open", |
test/security-floor-routes.test.ts +2
| @@ -74,6 +74,8 @@ const UNSEEDED: Record<string, string> = { | ||
| 74 | 74 | "/games/:box/:service": "a game box, which the seed does not make (test/games.test.ts covers it)", |
| 75 | 75 | "/games/:box/:service/stream": "a game box, which the seed does not make (test/games.test.ts covers it)", |
| 76 | 76 | "/games/jar/:id/:name": "a kept plugin jar of a game box, behind a signed URL the seed does not make", |
| 77 | "/talk/dev/:token": "a dev cell reached by a one-time token the seed does not mint (test/dev-cell.test.ts covers it)", | |
| 78 | "/talk/dev/:token/*path": "a dev cell reached by a one-time token the seed does not mint (test/dev-cell.test.ts covers it)", | |
| 77 | 79 | "/edge/config/:file": "a published file name, written by a config change the seed does not make (test/config-store.test.ts covers its headers)", |
| 78 | 80 | "/:owner/-/teams/:team": ORG, |
| 79 | 81 | "/api/v1/repos/:owner/:name/changes/:room": "an app's change stream needs forge.json sync:true on its default branch, which the seed does not declare (test/app-changes.test.ts covers it)", |
test/talk-pane-bar.test.ts +27
| @@ -10,6 +10,10 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | ||
| 10 | 10 | import { mkdtemp, rm } from "node:fs/promises"; |
| 11 | 11 | import { tmpdir } from "node:os"; |
| 12 | 12 | import { join } from "node:path"; |
| 13 | import { devCellsOf } from "../src/apps/dev_cell.ts"; | |
| 14 | import { devKey } from "../src/apps/dev_launch.ts"; | |
| 15 | import { ok } from "../src/kernel/result.ts"; | |
| 16 | import { pollUntil } from "./helpers/poll.ts"; | |
| 13 | 17 | import { newApp } from "../src/actions/apps.ts"; |
| 14 | 18 | import { |
| 15 | 19 | paneAtOf, |
| @@ -162,6 +166,29 @@ const page = async ( | ||
| 162 | 166 | }; |
| 163 | 167 | }; |
| 164 | 168 | |
| 169 | describe("the pane's dev server button (#17140)", () => { | |
| 170 | test("a writer of an app is offered Start dev server, a reader is not; while a cell is live the frame is sandboxed without same-origin and the page says what it cannot do", async () => { | |
| 171 | const mine = (await page(alice, talkOn(alice, "alice/two"))).html; | |
| 172 | expect(mine).toContain('action="/talk/dev"'); | |
| 173 | expect(mine).toContain("Start dev server"); | |
| 174 | expect(mine).not.toContain("sandboxed frame: sign-in"); | |
| 175 | expect((await page(bob, talkOn(bob, "alice/two"))).html).not.toContain('action="/talk/dev"'); | |
| 176 | const cells = devCellsOf(app); | |
| 177 | const key = devKey(alice.id, repos["alice/two"]!.id, "main"); | |
| 178 | cells.ensure(key, alice.id, repos["alice/two"]!.id, async () => ok({ port: 1, exited: new Promise<void>(() => {}), recent: () => [], stop: async () => {} })); | |
| 179 | await pollUntil(() => cells.get(key)?.state === "live", "the cell to be live", 5_000); | |
| 180 | try { | |
| 181 | const live = (await page(alice, talkOn(alice, "alice/two"))).html; | |
| 182 | expect(live).toContain("Stop dev server"); | |
| 183 | expect(live).toContain(`/talk/dev/${cells.get(key)!.token}/`); | |
| 184 | expect(live).toContain('sandbox="allow-scripts allow-forms allow-popups"'); | |
| 185 | expect(live).toContain("sandboxed frame: sign-in and forms that post do not work in it"); | |
| 186 | } finally { | |
| 187 | await cells.stop(key); | |
| 188 | } | |
| 189 | }); | |
| 190 | }); | |
| 191 | ||
| 165 | 192 | describe("the address bar's choice", () => { |
| 166 | 193 | test("a path is the pane's one hostile-path check: anything that could leave the app's address is dropped", () => { |
| 167 | 194 | for (const bad of [ |
test/tui-talk-chats.test.ts +23
| @@ -9,6 +9,8 @@ import { tmpdir } from "node:os"; | ||
| 9 | 9 | import { join } from "node:path"; |
| 10 | 10 | import { createApp, type App } from "../src/app.ts"; |
| 11 | 11 | import { appendTurn, archiveConversation, CONVERSATIONS_MAX, createConversation, listConversations, listTurns, renameConversation } from "../src/core/conversations.ts"; |
| 12 | import { createApp as createAppRecord } from "../src/core/apps.ts"; | |
| 13 | import { devReading } from "../src/actions/dev_workspace.ts"; | |
| 12 | 14 | import { createIssue } from "../src/core/issues.ts"; |
| 13 | 15 | import { createRun } from "../src/core/runs.ts"; |
| 14 | 16 | import { createUser, type User } from "../src/core/users.ts"; |
| @@ -264,6 +266,27 @@ describe("the terminal's conversations screen", () => { | ||
| 264 | 266 | expect(await drive(alice, [...open, "\r", "p"])).toContain("Not a repository you can see."); |
| 265 | 267 | }); |
| 266 | 268 | |
| 269 | test("d in the pane starts and stops the dev server for a writer, says why for a non-writer or a repository that is no app, and the pane says what the frame cannot do", async () => { | |
| 270 | const repo = await createRepo(app, alice, { name: "devpane", visibility: "public" }); | |
| 271 | if (!repo.ok) throw new Error(repo.error); | |
| 272 | const turn = { role: "tool" as const, text: 'mcp__forge__write_file {"repo":"alice/devpane","path":"src/y.ts","content":"a"}' }; | |
| 273 | for (const who of [alice, bob]) { | |
| 274 | const made = createConversation(app.db, who.id); | |
| 275 | if (!made.ok) throw new Error(made.error); | |
| 276 | appendTurn(app.db, who.id, made.value.id, turn); | |
| 277 | } | |
| 278 | expect(await drive(alice, [...open, "\r", "p", "d"])).toContain("This repository is not an app: nothing to run."); | |
| 279 | createAppRecord(app.db, { repoId: repo.value.id, slug: "devpane", access: "private" }); | |
| 280 | expect(await drive(bob, [...open, "\r", "p", "d"])).toContain("Only someone who can write here can start its dev server."); | |
| 281 | expect(devReading(app, bob, repo.value, "main")).toBeUndefined(); | |
| 282 | const started = await drive(alice, [...open, "\r", "p", "d"]); | |
| 283 | expect(started).toContain("Starting main with hot reload."); | |
| 284 | expect(devReading(app, alice, repo.value, "main")).toBeDefined(); | |
| 285 | expect(await drive(alice, [...open, "\r", "p"])).toContain("d stops it"); | |
| 286 | expect(await drive(alice, [...open, "\r", "p", "d"])).toContain("Stopped the dev server of main."); | |
| 287 | expect(devReading(app, alice, repo.value, "main")).toBeUndefined(); | |
| 288 | }); | |
| 289 | ||
| 267 | 290 | test("p says Error in file:line when the crew's newest run failed, as the page's bar does (#17119)", async () => { |
| 268 | 291 | const made = createConversation(app.db, alice.id); |
| 269 | 292 | if (!made.ok) throw new Error(made.error); |
new above
offline
MEDIUM: a git spawn on every pane read or TUI render, and it touches the cell. Move it off the read path or rate-limit it.