Public: anyone can read this; the crew can change it.

A repository with a compose file shows one button, Start my environment, with a link to open and Stop, Reset and Share #18636

opened this

Its check is queued, place 5 of 11

scout/forge:scout/18604-a-repository-with-a-compose-file-shows-o → main 8 commits fork

Review

Sign in to review this change.
16 files changed +692 −5
docs/features/my-environment.md added +23
@@ -0,0 +1,23 @@
1 ---
2 topic: Your apps
3 row: Start my environment: a repository with a compose file runs on a machine you may use, with Open, Stop, Reset and Share
4 ---
5 # Start my environment: a repository with a compose file runs on a machine you may use (#18604)
6
7 A repository whose default branch holds a compose file (`compose.yaml`, `compose.yml`,
8 `docker-compose.yaml` or `docker-compose.yml`) shows **Your environment** on its page
9 (`src/web/pages/repo.ts`, the card is `src/web/studio/environment.ts`) to anyone signed in who may
10 read it. In the terminal it is the palette's "My environment" (`src/tui/screens/environments.ts`).
11 Both use the same read and actions, `src/actions/environment.ts`.
12
13 - **Start my environment** runs it on a machine you may use and gives a link to **Open**.
14 - **Stop** asks nothing and keeps your work; **Undo** takes it back for a minute.
15 - **Reset** shows what it loses (the database and files go back to what the repository holds) and
16 waits for one more press.
17 - **Share** makes one link that opens your running environment and nothing else: no sign-in, no
18 access to the repository. **Stop sharing** deletes it at once. The link stops opening while the
19 environment is stopped.
20 - With no machine you may use, the button is off and says why and where to go.
21
22 The machine is `src/machines/environment.ts`'s host. The forge ships no machine-making host yet,
23 so until one is set up every person sees the no-machine words. Tests use a fake host.
src/actions/environment.ts added +211
@@ -0,0 +1,211 @@
1 /**
2 * "Start my environment" for a repository with a compose file (#18604): the one read and the
3 * actions behind the repository page's card, the terminal's screen and the tests. One row per
4 * person and repository (`environment`); the machine it runs on is `machines/environment.ts`'s
5 * host, chosen for this person alone. No door adds its own words or its own gate.
6 *
7 * Share is one random link the owner can delete: it opens the running environment's address and
8 * nothing else (no sign-in, no repository access, no other page), and it stops working the
9 * moment it is taken back or the environment stops.
10 */
11
12 import type { App } from "../app.ts";
13 import { blobOidAt } from "../git/read.ts";
14 import { resolveOid } from "../git/merge.ts";
15 import { repoDir } from "../git/repos.ts";
16 import { err, ok, type Result } from "../kernel/result.ts";
17 import type { Repo } from "../core/repos.ts";
18 import type { User } from "../core/users.ts";
19 import { NO_MACHINE_WORDS, host, type EnvironmentKey, type Machine } from "../machines/environment.ts";
20 import { requireParticipant, requireReader } from "./access.ts";
21
22 /** The files that make a repository one with an environment. */
23 export const ENVIRONMENT_FILES: readonly string[] = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"];
24 /** How long a stop can be taken back. */
25 export const UNDO_MS = 60_000;
26
27 export const RESET_LOSES = "Reset erases everything you changed in your environment: its database and its files go back to what the repository holds. Your share link keeps working.";
28 export const STOPPED_SAYS = "Stopped. Your work is kept.";
29
30 interface Row {
31 readonly machine: string;
32 readonly state: "running" | "stopped";
33 readonly url: string;
34 readonly share_token: string;
35 readonly stopped_at: string;
36 }
37
38 export type EnvironmentView =
39 | { readonly kind: "none"; readonly why: string; readonly settings: string }
40 | { readonly kind: "off" }
41 | { readonly kind: "running"; readonly open: string; readonly share: string }
42 | { readonly kind: "stopped"; readonly undo: boolean; readonly share: string };
43
44 const rowOf = (app: App, repo: Repo, user: User): Row | undefined =>
45 app.db.query<Row, [string, string]>("SELECT machine, state, url, share_token, stopped_at FROM environment WHERE repo_id = ?1 AND user_id = ?2").get(repo.id, user.id) ?? undefined;
46
47 const keyOf = (repo: Repo, user: User): EnvironmentKey => ({ repo: repo.id, person: user.id });
48
49 /** The path a share token opens through; the token is the whole credential. */
50 export const shareHref = (repo: Repo, token: string): string => (token === "" ? "" : `/${repo.ownerName}/${repo.name}/environment/shared/${token}`);
51
52 /** Whether the default branch holds a compose file: a few pooled-reader stats, no process. */
53 export async function hasEnvironmentFile(app: App, repo: Repo): Promise<boolean> {
54 const dir = repoDir(app.reposRoot, repo.ownerName, repo.name);
55 const tip = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`);
56 if (tip === undefined) return false;
57 for (const name of ENVIRONMENT_FILES) if ((await blobOidAt(dir, tip, name)) !== undefined) return true;
58 return false;
59 }
60
61 /** An address a host handed back is opened only as http or https. */
62 export function openable(url: string): boolean {
63 try {
64 const u = new URL(url);
65 return u.protocol === "https:" || u.protocol === "http:";
66 } catch {
67 return false;
68 }
69 }
70
71 /**
72 * What the card shows this person: undefined when it shows nothing (anyone signed out, no compose
73 * file is the caller's check).
74 */
75 export function environmentView(app: App, actor: User | undefined, repo: Repo, now = Date.now()): EnvironmentView | undefined {
76 if (actor === undefined || !requireReader(app, actor, repo).ok) return undefined;
77 const row = rowOf(app, repo, actor);
78 if (row?.state === "running") return { kind: "running", open: row.url, share: shareHref(repo, row.share_token) };
79 if (row?.state === "stopped") {
80 const at = Date.parse(row.stopped_at);
81 return { kind: "stopped", undo: Number.isFinite(at) && now - at < UNDO_MS && host().machineFor(app, actor) !== undefined, share: shareHref(repo, row.share_token) };
82 }
83 if (host().machineFor(app, actor) === undefined) return { kind: "none", why: NO_MACHINE_WORDS(), settings: "/settings/cloud" };
84 return { kind: "off" };
85 }
86
87 type Why = string;
88
89 function gate(app: App, actor: User | undefined, repo: Repo): Result<{ user: User; machine: Machine }, Why> {
90 const who = requireParticipant(app, actor, repo);
91 if (!who.ok) return err("Sign in to use an environment.");
92 const machine = host().machineFor(app, who.value);
93 if (machine === undefined) return err(NO_MACHINE_WORDS());
94 return ok({ user: who.value, machine });
95 }
96
97 function save(app: App, repo: Repo, user: User, machine: string, state: "running" | "stopped", url: string, now: Date): void {
98 const stamp = now.toISOString();
99 app.db
100 .query(
101 `INSERT INTO environment (repo_id, user_id, machine, state, url, started_at, stopped_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
102 ON CONFLICT (repo_id, user_id) DO UPDATE SET machine = ?3, state = ?4, url = ?5,
103 started_at = CASE WHEN ?4 = 'running' THEN ?6 ELSE started_at END, stopped_at = ?7`,
104 )
105 .run(repo.id, user.id, machine, state, url, stamp, state === "stopped" ? stamp : "");
106 }
107
108 async function bring(app: App, actor: User | undefined, repo: Repo, how: "start" | "reset", now: Date): Promise<Result<string, Why>> {
109 const g = gate(app, actor, repo);
110 if (!g.ok) return g;
111 if (!(await hasEnvironmentFile(app, repo))) return err("This repository has no environment to start.");
112 const made = await host()[how](g.value.machine, keyOf(repo, g.value.user));
113 if (!made.ok) return err(made.error);
114 if (!openable(made.value.url)) return err("The machine gave an address that cannot be opened.");
115 save(app, repo, g.value.user, g.value.machine.id, "running", made.value.url, now);
116 app.bus.append({ kind: `environment.${how === "start" ? "started" : "reset"}`, repoId: repo.id, actorId: g.value.user.id, payload: { machine: g.value.machine.id } });
117 return ok(made.value.url);
118 }
119
120 /** Start my environment (or find it already running): the address to open. */
121 export async function startEnvironment(app: App, actor: User | undefined, repo: Repo, now = new Date()): Promise<Result<string, Why>> {
122 const g = gate(app, actor, repo);
123 if (g.ok) {
124 const row = rowOf(app, repo, g.value.user);
125 if (row?.state === "running") return ok(row.url);
126 }
127 return bring(app, actor, repo, "start", now);
128 }
129
130 /**
131 * Reset: only with the person's yes to `RESET_LOSES`; their work goes back to what the repository
132 * holds.
133 */
134 export async function resetEnvironment(app: App, actor: User | undefined, repo: Repo, confirmed: boolean, now = new Date()): Promise<Result<string, Why>> {
135 if (!confirmed) return err(RESET_LOSES);
136 return bring(app, actor, repo, "reset", now);
137 }
138
139 /** Stop: no question asked; `UNDO_MS` to take it back. */
140 export async function stopEnvironment(app: App, actor: User | undefined, repo: Repo, now = new Date()): Promise<Result<true, Why>> {
141 const g = gate(app, actor, repo);
142 if (!g.ok) return g;
143 const row = rowOf(app, repo, g.value.user);
144 if (row?.state !== "running") return err("Your environment is not running.");
145 const stopped = await host().stop(g.value.machine, keyOf(repo, g.value.user));
146 if (!stopped.ok) return err(stopped.error);
147 save(app, repo, g.value.user, g.value.machine.id, "stopped", row.url, now);
148 app.bus.append({ kind: "environment.stopped", repoId: repo.id, actorId: g.value.user.id, payload: { machine: g.value.machine.id } });
149 return ok(true);
150 }
151
152 /** Take a stop back within `UNDO_MS`: it starts again with its work. */
153 export async function undoStop(app: App, actor: User | undefined, repo: Repo, now = new Date()): Promise<Result<string, Why>> {
154 const who = requireParticipant(app, actor, repo);
155 if (!who.ok) return err("Sign in to use an environment.");
156 const row = rowOf(app, repo, who.value);
157 const at = row === undefined ? NaN : Date.parse(row.stopped_at);
158 if (row?.state !== "stopped" || !(now.getTime() - at < UNDO_MS)) return err("It is too late to undo; start it again.");
159 return bring(app, actor, repo, "start", now);
160 }
161
162 /**
163 * Make (or keep) the one share link; only the person whose environment it is, and only while it
164 * runs.
165 */
166 export function shareEnvironment(app: App, actor: User | undefined, repo: Repo): Result<string, Why> {
167 const who = requireParticipant(app, actor, repo);
168 if (!who.ok) return err("Sign in to use an environment.");
169 const row = rowOf(app, repo, who.value);
170 if (row?.state !== "running") return err("Start your environment first, then share it.");
171 let token = row.share_token;
172 if (token === "") {
173 token = [...crypto.getRandomValues(new Uint8Array(24))].map((b) => b.toString(16).padStart(2, "0")).join("");
174 app.db.query("UPDATE environment SET share_token = ?3 WHERE repo_id = ?1 AND user_id = ?2").run(repo.id, who.value.id, token);
175 app.bus.append({ kind: "environment.shared", repoId: repo.id, actorId: who.value.id, payload: {} });
176 }
177 return ok(shareHref(repo, token));
178 }
179
180 /** Take the link back: it stops opening at once. */
181 export function unshareEnvironment(app: App, actor: User | undefined, repo: Repo): Result<true, Why> {
182 const who = requireParticipant(app, actor, repo);
183 if (!who.ok) return err("Sign in to use an environment.");
184 app.db.query("UPDATE environment SET share_token = '' WHERE repo_id = ?1 AND user_id = ?2").run(repo.id, who.value.id);
185 app.bus.append({ kind: "environment.unshared", repoId: repo.id, actorId: who.value.id, payload: {} });
186 return ok(true);
187 }
188
189 /** Where a share link leads: the running environment's address of this repository, or undefined. */
190 export function sharedAddress(app: App, repo: Repo, token: string): string | undefined {
191 if (!/^[0-9a-f]{48}$/.test(token)) return undefined;
192 const row = app.db.query<{ url: string }, [string, string]>("SELECT url FROM environment WHERE repo_id = ?1 AND share_token = ?2 AND state = 'running'").get(repo.id, token);
193 return row !== null && row !== undefined && openable(row.url) ? row.url : undefined;
194 }
195
196 /**
197 * The one line a door without buttons says about the environment (the terminal's, and a screen
198 * reader's).
199 */
200 export function environmentSays(v: EnvironmentView, base: string): string {
201 switch (v.kind) {
202 case "none":
203 return v.why;
204 case "off":
205 return "Not running. Start my environment to run it on your machine.";
206 case "running":
207 return `Running. Open it at ${v.open}${v.share === "" ? "" : `; shared at ${base}${v.share}`}.`;
208 case "stopped":
209 return `${STOPPED_SAYS}${v.undo ? " Undo, or start it again." : " Start it again."}`;
210 }
211 }
src/core/migration-pins/20261206190000-environment.pin added +1
@@ -0,0 +1,1 @@
1 2bf08d024ace9b5c8f03a1e1e00dac291695b32dc1bc870699d57fe832b1d35a
src/core/migrations/20261206190000-environment.ts added +17
@@ -0,0 +1,17 @@
1 // A person's own working environment for a repository with a compose file (#18604): one row per
2 // person and repository, the machine it runs on, where to open it, and the share link (a random
3 // token the owner can delete). Nothing else is kept; the machine holds the work itself.
4 export default `
5 CREATE TABLE IF NOT EXISTS environment (
6 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
7 user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
8 machine TEXT NOT NULL,
9 state TEXT NOT NULL CHECK (state IN ('running', 'stopped')),
10 url TEXT NOT NULL DEFAULT '',
11 share_token TEXT NOT NULL DEFAULT '',
12 started_at TEXT NOT NULL,
13 stopped_at TEXT NOT NULL DEFAULT '',
14 PRIMARY KEY (repo_id, user_id)
15 );
16 CREATE INDEX IF NOT EXISTS environment_share ON environment (share_token) WHERE share_token != '';
17 `;
src/http/lazy_lists.ts +3
@@ -837,6 +837,9 @@ export const REPO_APP_ROUTES = [
837837 ["GET", "/:owner/:name/app/jobs"],
838838 ["POST", "/:owner/:name/app/jobs/:id/:action"],
839839 ["POST", "/:owner/:name/app/schedules/:schedule/:action"],
840 ["GET", "/:owner/:name/environment/reset"],
841 ["GET", "/:owner/:name/environment/shared/:token"],
842 ["POST", "/:owner/:name/environment/:action"],
840843 ["GET", "/:owner/:name/data-move"],
841844 ["POST", "/:owner/:name/data-move"],
842845 ["GET", "/:owner/:name/cut-over"],
src/http/routes/repo_app.ts +4
@@ -17,6 +17,7 @@ import { cutOverPage, cutOverAct } from "../../web/studio/cut_over.ts";
1717 import { dataMovePage, dataMoveAct } from "../../web/studio/data_move.ts";
1818 import { dropPageGet, uploadDropPage, removeDropPage } from "../../web/studio/drop.ts";
1919 import { errorResolve } from "../../web/studio/errors.ts";
20 import { environmentAct, environmentResetPage, environmentShared } from "../../web/studio/environment.ts";
2021 import { jobsPage, steerJobPage } from "../../web/studio/jobs.ts";
2122 import { appMilestonesFragment } from "../../web/studio/milestone_lines.ts";
2223 import { noteModerate } from "../../web/studio/notes.ts";
@@ -47,6 +48,9 @@ export function repoAppRoutes(router: Router<Handler>): void {
4748 router.add("GET", "/:owner/:name/app/jobs", jobsPage);
4849 router.add("POST", "/:owner/:name/app/jobs/:id/:action", steerJobPage);
4950 router.add("POST", "/:owner/:name/app/schedules/:schedule/:action", steerSchedulePage);
51 router.add("GET", "/:owner/:name/environment/reset", environmentResetPage);
52 router.add("GET", "/:owner/:name/environment/shared/:token", environmentShared);
53 router.add("POST", "/:owner/:name/environment/:action", environmentAct);
5054 router.add("GET", "/:owner/:name/data-move", dataMovePage);
5155 router.add("POST", "/:owner/:name/data-move", dataMoveAct);
5256 router.add("GET", "/:owner/:name/cut-over", cutOverPage);
src/machines/environment.ts added +59
@@ -0,0 +1,59 @@
1 /**
2 * The machine a person's environment runs on (#18604), as one small seam: which machine this
3 * person may use, and starting, stopping and resetting an environment on it. Plain data in, plain
4 * data out; the page, the terminal and the tests all go through `host`. A person's token and
5 * `may()` decide the machine, inside the host's `machineFor`, never in a door.
6 *
7 * The forge ships no machine-making host yet: `noHost` finds none, and every door says so and what
8 * to do. A host is swapped in with `useHost` (tests do; a real one is the next change).
9 */
10
11 import type { App } from "../app.ts";
12 import type { User } from "../core/users.ts";
13 import { err, type Result } from "../kernel/result.ts";
14
15 export interface Machine {
16 readonly id: string;
17 readonly name: string;
18 }
19
20 /** What a host is told about the environment it runs: whose, for which repository. */
21 export interface EnvironmentKey {
22 readonly repo: string;
23 readonly person: string;
24 }
25
26 export interface Host {
27 /** The machine this person may use, or undefined. */
28 machineFor(app: App, actor: User): Machine | undefined;
29 /** Start (or start again) the environment; the address to open it at. */
30 start(machine: Machine, key: EnvironmentKey): Promise<Result<{ readonly url: string }, string>>;
31 /** Stop it, keeping its work. */
32 stop(machine: Machine, key: EnvironmentKey): Promise<Result<true, string>>;
33 /** Throw its work away and start from what the repository holds; the address to open it at. */
34 reset(machine: Machine, key: EnvironmentKey): Promise<Result<{ readonly url: string }, string>>;
35 }
36
37 export const noHost: Host = {
38 machineFor: () => undefined,
39 start: async () => err(NO_MACHINE_WORDS()),
40 stop: async () => err(NO_MACHINE_WORDS()),
41 reset: async () => err(NO_MACHINE_WORDS()),
42 };
43
44 /** Why there is nothing to start on, and what to do about it. */
45 export function NO_MACHINE_WORDS(): string {
46 return "No machine is set up for you to use yet. Connect one under Settings, then start.";
47 }
48
49 let current: Host = noHost;
50
51 /** The host in use. */
52 export const host = (): Host => current;
53
54 /** Swap the host (a test's fake machine); returns what to restore. */
55 export function useHost(next: Host): Host {
56 const was = current;
57 current = next;
58 return was;
59 }
src/tui/screens/environments.ts +91 −1
@@ -5,6 +5,19 @@
55 * refused in the same words.
66 */
77
8 import {
9 RESET_LOSES,
10 environmentSays,
11 environmentView,
12 hasEnvironmentFile,
13 resetEnvironment,
14 shareEnvironment,
15 startEnvironment,
16 stopEnvironment,
17 undoStop,
18 unshareEnvironment,
19 } from "../../actions/environment.ts";
20 import type { Result } from "../../kernel/result.ts";
821 import { removeEnvironmentEntry, setEnvironmentEntry } from "../../actions/environments.ts";
922 import { listEntries, type EntryKind, type EntryName, type SetError } from "../../checks/environment.ts";
1023 import { canAdmin, type Repo } from "../../core/repos.ts";
@@ -12,7 +25,7 @@ import type { Ctx, Screen } from "../app/app.ts";
1225 import { binding } from "../app/keys.ts";
1326 import type { Command } from "../app/palette.ts";
1427 import { style } from "../term/style.ts";
15 import { truncate } from "../term/width.ts";
28 import { truncate, wrap } from "../term/width.ts";
1629 import { fill, len, split } from "../ui/layout.ts";
1730 import type { Session } from "../session.ts";
1831 import { ListState, drawList, promptScreen, type ListRow } from "./common.ts";
@@ -110,3 +123,80 @@ export function environmentsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
110123 };
111124 return screen;
112125 }
126
127 /*
128 * "Start my environment" in the terminal (#18604): the repository page's card from the same read
129 * and actions (`actions/environment.ts`), gated the same way. `s` starts, `x` stops (`u` takes it
130 * back for a minute), `r` resets after saying what it loses and a second `r`, `l` shares, `n` stops
131 * sharing.
132 */
133 export function myEnvironmentScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
134 let has = false;
135 let asking = false;
136 const said = (r: Result<unknown, string>, good: string): void => {
137 ctx.toast(r.ok ? good : r.error, r.ok ? undefined : "danger");
138 ctx.invalidate();
139 };
140 return {
141 title: `${repo.ownerName}/${repo.name} — Environment`,
142 keys: [binding(["s"], "start"), binding(["x"], "stop"), binding(["u"], "undo a stop"), binding(["r"], "reset"), binding(["l"], "share"), binding(["n"], "stop sharing")],
143 async load() {
144 has = await hasEnvironmentFile(f.app, repo);
145 ctx.invalidate();
146 },
147 render(area, s) {
148 const c = ctx.theme.c;
149 const v = environmentView(f.app, f.user, repo);
150 const text = !has ? "This repository has no environment to start." : v === undefined ? "Sign in to use an environment." : environmentSays(v, f.app.config.url ?? "");
151 const lines = [...wrap(text, area.w), ...(asking ? ["", ...wrap(`${RESET_LOSES} Press r again to reset, any other key to keep it.`, area.w)] : [])];
152 lines.forEach((l, i) => {
153 if (i < area.h) s.text(area.x, area.y + i, truncate(l, area.w), style(c.mutedFg, c.bg), area.x + area.w);
154 });
155 },
156 key(e) {
157 if (e.ctrl || e.alt) return false;
158 if (asking) {
159 asking = false;
160 if (e.key === "r") void resetEnvironment(f.app, f.user, repo, true).then((r) => said(r, "Reset."));
161 ctx.invalidate();
162 return true;
163 }
164 switch (e.key) {
165 case "s":
166 void startEnvironment(f.app, f.user, repo).then((r) => said(r, "Running."));
167 return true;
168 case "x":
169 void stopEnvironment(f.app, f.user, repo).then((r) => said(r, "Stopped. Press u within a minute to undo."));
170 return true;
171 case "u":
172 void undoStop(f.app, f.user, repo).then((r) => said(r, "Running again."));
173 return true;
174 case "r":
175 asking = true;
176 ctx.invalidate();
177 return true;
178 case "l":
179 said(shareEnvironment(f.app, f.user, repo), "Shared.");
180 return true;
181 case "n":
182 said(unshareEnvironment(f.app, f.user, repo), "No longer shared.");
183 return true;
184 default:
185 return false;
186 }
187 },
188 };
189 }
190
191 /** The palette's command while a repository is open and its viewer is signed in. */
192 export function myEnvironmentCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
193 if (repo === undefined || environmentView(f.app, f.user, repo) === undefined) return [];
194 return [
195 {
196 id: "my-environment",
197 title: `${repo.ownerName}/${repo.name} — My environment`,
198 hint: "start, open, stop, reset or share your own working copy",
199 run: () => ctx.push(myEnvironmentScreen(f, ctx, repo)),
200 },
201 ];
202 }
src/tui/screens/workspace.ts +2 −3
@@ -154,7 +154,7 @@ import { iterationsCommands } from "./iterations.ts";
154154 import { labelsCommands } from "./labels.ts";
155155 import { appEnvCommands } from "./appenv.ts";
156156 import { appSecretCommands } from "./appsecrets.ts";
157 import { environmentCommands } from "./environments.ts";
157 import { environmentCommands, myEnvironmentCommands } from "./environments.ts";
158158 import { appFlagCommands } from "./appflags.ts";
159159 import { appRegistryCommands } from "./appregistry.ts";
160160 import { changesCommands } from "./app_changes.ts";
@@ -245,7 +245,6 @@ function formatSize(bytes: number): string {
245245 return `${(bytes / 1024 / 1024).toFixed(1)} M`;
246246 }
247247
248
249248 // ---- what a workspace remembers between visits ----
250249
251250 /**
@@ -1408,6 +1407,7 @@ export function workspaceScreen(
14081407 ...appEnvCommands(f, ctx, repo),
14091408 ...appSecretCommands(f, ctx, repo),
14101409 ...environmentCommands(f, ctx, repo),
1410 ...myEnvironmentCommands(f, ctx, repo),
14111411 ...appFlagCommands(f, ctx, repo),
14121412 ...appRegistryCommands(f, ctx, repo),
14131413 ...changesCommands(f, ctx, repo),
@@ -2667,7 +2667,6 @@ function findKey(t: Tab, e: KeyEvent): boolean {
26672667 return true;
26682668 }
26692669
2670
26712670 // ---- the doors other screens knock on ----
26722671
26732672 /** Open a repository's workspace. */
src/web/pages/repo.ts +3 −1
@@ -111,6 +111,7 @@ import { crashCard } from "../studio/crash_card.ts";
111111 import { declaresFeature } from "../../actions/features.ts";
112112 import { declaredJobs } from "../../actions/declared_jobs.ts";
113113 import { declaredJobsCard } from "../studio/declared_jobs.ts";
114 import { environmentSection } from "../studio/environment.ts";
114115 import { getAppByRepo } from "../../core/apps.ts";
115116 import { field, readForm } from "../form.ts";
116117 import { hexdump, HEX_BYTES } from "../render/hexdump.ts";
@@ -1668,6 +1669,7 @@ async function codeHome(ctx: Ctx, repo: Repo, appOf: { readonly isApp: boolean;
16681669 : upstreamOffer(ctx.app, ctx.auth.user, repo, parent, drift?.ahead);
16691670 const declares = isApp && (await timePhaseAsync(ctx.request, "feature", () => declaresFeature(ctx.app, ctx.auth.user, repo)));
16701671 const jobs = await timePhaseAsync(ctx.request, "jobs", () => declaredJobs(ctx.app, repo));
1672 const environment = await timePhaseAsync(ctx.request, "environment", () => environmentSection(ctx, repo));
16711673 const credit = await timePhaseAsync(ctx.request, "credit", () =>
16721674 creditLine(ctx, repo, scope.source, ref),
16731675 );
@@ -1688,7 +1690,7 @@ async function codeHome(ctx: Ctx, repo: Repo, appOf: { readonly isApp: boolean;
16881690 : html`<p class="muted latest-wave">Latest:
16891691 <a href="${repoBase(repo)}/waves/${encodeURIComponent(latest.version)}">${latest.version}</a>
16901692 · ${latest.headline} · ${latest.date}</p>`}
1691 ${reviewCard(ctx, repo)}${frozenBlock(ctx, repo)} ${appStrip(ctx, repo, declares)}${declaredJobsCard(jobs)}
1693 ${reviewCard(ctx, repo)}${frozenBlock(ctx, repo)} ${appStrip(ctx, repo, declares)}${environment}${declaredJobsCard(jobs)}
16921694 ${isApp ? null : crashCard(ctx, repo)}
16931695 ${ctx.auth.user?.id === repo.ownerId && isContributionFork(ctx.app.db, repo.id)
16941696 ? contributionBar(repo)
src/web/studio/environment.ts added +126
@@ -0,0 +1,126 @@
1 /**
2 * "Start my environment" on a repository's page (#18604): one button for a repository with a
3 * compose file; once it runs, a link to open it and Stop, Reset and Share beside it. Stop asks
4 * nothing and offers Undo; Reset goes through a page that says what it loses; Share makes the one
5 * link its owner can take back. The words and gates are `actions/environment.ts`'s, shared with
6 * the terminal. Forms POST to `/:owner/:name/environment/:action`, same-origin checked by
7 * `readForm`; a share link is a GET that only redirects to the running address.
8 */
9
10 import {
11 RESET_LOSES,
12 STOPPED_SAYS,
13 environmentView,
14 hasEnvironmentFile,
15 resetEnvironment,
16 sharedAddress,
17 shareEnvironment,
18 startEnvironment,
19 stopEnvironment,
20 undoStop,
21 unshareEnvironment,
22 type EnvironmentView,
23 } from "../../actions/environment.ts";
24 import type { Repo } from "../../core/repos.ts";
25 import type { Ctx } from "../../http/context.ts";
26 import { crumbsFor, loadRepo, notFoundPage, pageHead, repoBase, signInFirst } from "../chrome.ts";
27 import { field, readForm } from "../form.ts";
28 import { html, type Html } from "../html.ts";
29 import { page, redirect } from "../layout.ts";
30 import { btn } from "../ui.ts";
31
32 const post = (repo: Repo, action: string): string => `${repoBase(repo)}/environment/${action}`;
33
34 /** The card's body for one view; the same one-line facts as the terminal's. */
35 export function environmentCard(ctx: Ctx, repo: Repo, v: EnvironmentView): Html {
36 const form = (action: string, label: string, variant: "primary" | "outline" | "danger" = "outline"): Html =>
37 html`<form method="post" action="${post(repo, action)}">${btn(label, { variant, size: "sm" })}</form>`;
38 const share = (link: string): Html =>
39 link === ""
40 ? form("share", "Share")
41 : html`<span class="muted">Link: <a href="${link}"><code>${`${ctx.app.config.url ?? ""}${link}`}</code></a></span>${form("unshare", "Stop sharing")}`;
42 const inner =
43 v.kind === "none"
44 ? html`<p><button type="button" disabled>Start my environment</button></p><p class="muted">${v.why} <a href="${v.settings}">Settings</a></p>`
45 : v.kind === "off"
46 ? form("start", "Start my environment", "primary")
47 : v.kind === "running"
48 ? html`<div class="row">${btn("Open", { href: v.open, variant: "primary", size: "sm", external: true })}${form("stop", "Stop")}<a class="btn" data-variant="outline" data-size="sm" href="${post(repo, "reset")}">Reset</a>${share(v.share)}</div>`
49 : html`<div class="row"><span class="muted">${STOPPED_SAYS}</span>${v.undo ? form("undo", "Undo", "primary") : null}${form("start", "Start my environment", v.undo ? "outline" : "primary")}</div>`;
50 return html`<section class="stack environment" id="environment"><h2>Your environment</h2>${inner}</section>`;
51 }
52
53 /**
54 * The card for the repository page: nothing unless the viewer is signed in and the repository holds
55 * a compose file.
56 */
57 export async function environmentSection(ctx: Ctx, repo: Repo): Promise<Html | null> {
58 const v = environmentView(ctx.app, ctx.auth.user, repo);
59 if (v === undefined || !(await hasEnvironmentFile(ctx.app, repo))) return null;
60 return environmentCard(ctx, repo, v);
61 }
62
63 const back = (ctx: Ctx, repo: Repo, why?: string): Response =>
64 redirect(`${repoBase(repo)}#environment`, { url: ctx.url, forgeUrl: ctx.app.config.url, ...(why === undefined ? {} : { flash: { tone: "danger", message: why } }) });
65
66 // POST /:owner/:name/environment/:action
67 export async function environmentAct(ctx: Ctx): Promise<Response> {
68 const repo = loadRepo(ctx);
69 if (!repo) return notFoundPage(ctx);
70 if (ctx.auth.user === undefined) return signInFirst(ctx);
71 const form = await readForm(ctx, "rw");
72 if (form instanceof Response) return form;
73 const { app } = ctx;
74 const actor = ctx.auth.user;
75 switch (ctx.params["action"]) {
76 case "start": {
77 const r = await startEnvironment(app, actor, repo);
78 return back(ctx, repo, r.ok ? undefined : r.error);
79 }
80 case "stop": {
81 const r = await stopEnvironment(app, actor, repo);
82 return back(ctx, repo, r.ok ? undefined : r.error);
83 }
84 case "undo": {
85 const r = await undoStop(app, actor, repo);
86 return back(ctx, repo, r.ok ? undefined : r.error);
87 }
88 case "reset": {
89 const r = await resetEnvironment(app, actor, repo, field(form, "confirm") === "yes");
90 return back(ctx, repo, r.ok ? undefined : r.error);
91 }
92 case "share": {
93 const r = shareEnvironment(app, actor, repo);
94 return back(ctx, repo, r.ok ? undefined : r.error);
95 }
96 case "unshare": {
97 unshareEnvironment(app, actor, repo);
98 return back(ctx, repo);
99 }
100 default:
101 return notFoundPage(ctx);
102 }
103 }
104
105 // GET /:owner/:name/environment/reset — what a reset loses, and the one button that does it.
106 export function environmentResetPage(ctx: Ctx): Response {
107 const repo = loadRepo(ctx);
108 if (!repo) return notFoundPage(ctx);
109 if (ctx.auth.user === undefined) return signInFirst(ctx);
110 return page({
111 ctx,
112 title: `Reset your environment · ${repo.name}`,
113 crumbs: crumbsFor(repo),
114 body: html`${pageHead("Reset your environment")}<section class="stack"><p>${RESET_LOSES}</p>
115 <form method="post" action="${post(repo, "reset")}"><input type="hidden" name="confirm" value="yes">${btn("Reset and lose my changes", { variant: "danger" })}</form>
116 <p><a href="${repoBase(repo)}#environment">Keep my environment</a></p></section>`,
117 });
118 }
119
120 // GET /:owner/:name/environment/shared/:token — the shared link: the running address, nothing else.
121 export function environmentShared(ctx: Ctx): Response {
122 const repo = loadRepo(ctx);
123 const to = repo === undefined ? undefined : sharedAddress(ctx.app, repo, ctx.params["token"] ?? "");
124 if (to === undefined) return notFoundPage(ctx, { plain: true });
125 return new Response(null, { status: 303, headers: { location: to, "cache-control": "no-store" } });
126 }
test/budgets/unfixtured/owner-name-environment-shared-token.json added +4
@@ -0,0 +1,4 @@
1 {
2 "pattern": "/:owner/:name/environment/shared/:token",
3 "why": "a shared environment's link: the seed has no running environment to share; test/my-environment.test.ts shares one and reads it"
4 }
test/keymap-terminal.test.ts +1
@@ -32,6 +32,7 @@ const OWN_R: Record<string, string> = {
3232 "src/tui/screens/dataimport.ts": "import, replace",
3333 "src/tui/screens/design.ts": "revert",
3434 "src/tui/screens/devices.ts": "revoke an app",
35 "src/tui/screens/environments.ts": "reset your environment",
3536 "src/tui/screens/estimates.ts": "record an estimate",
3637 "src/tui/screens/experiments.ts": "record result",
3738 "src/tui/screens/featurefeed.ts": "run scheduled now",
test/my-environment.test.ts added +145
@@ -0,0 +1,145 @@
1 /**
2 * "Start my environment" (#18604): a repository with a compose file shows one button; start, open,
3 * stop with undo, reset after saying what it loses, share and unshare, against a fake machine
4 * (no model call, no cloud). The terminal reads the same rows.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtempSync, rmSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { RESET_LOSES, environmentView, resetEnvironment, startEnvironment, stopEnvironment, undoStop } from "../src/actions/environment.ts";
12 import { createUser } from "../src/core/users.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import { err, ok } from "../src/kernel/result.ts";
15 import { noHost, useHost, type Host } from "../src/machines/environment.ts";
16 import { myEnvironmentCommands } from "../src/tui/screens/environments.ts";
17 import type { Ctx } from "../src/tui/app/app.ts";
18 import type { Session } from "../src/tui/session.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20 import { promote } from "./helpers/members.ts";
21 import { seededRepo } from "./helpers/seeded_repo.ts";
22 import { signInCookie } from "./helpers/studio-signin.ts";
23
24 quietLogs();
25
26 const calls: string[] = [];
27 let allowed = new Set<string>();
28 const fake: Host = {
29 machineFor: (_app, actor) => (allowed.has(actor.id) ? { id: "m1", name: "Spare laptop" } : undefined),
30 start: async (_m, k) => (calls.push(`start ${k.person}`), ok({ url: "https://env.example/mine" })),
31 stop: async () => (calls.push("stop"), ok(true as const)),
32 reset: async () => (calls.push("reset"), ok({ url: "https://env.example/fresh" })),
33 };
34
35 let root = "";
36 let app: App;
37 let servers: Servers;
38 let was: Host;
39
40 beforeAll(() => {
41 root = mkdtempSync(join(tmpdir(), "forge-env-"));
42 app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge" });
43 });
44 afterAll(() => {
45 useHost(was ?? noHost);
46 servers?.stop();
47 app.close();
48 rmSync(root, { recursive: true, force: true });
49 });
50
51 test("start, open, stop with undo, reset and share, from the page", async () => {
52 servers = await serve(app);
53 was = useHost(fake);
54 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
55 if (!u.ok) throw new Error(u.error);
56 promote(app.db, u.value);
57 const repo = await seededRepo(app, u.value, "shop", "public", [{ message: "stack", files: [{ path: "docker-compose.yml", content: "services: {}\n" }] }]);
58 const plain = await seededRepo(app, u.value, "plain", "public", [{ message: "x", files: [{ path: "a.txt", content: "a" }] }]);
59 const cookie = await signInCookie(servers.url, "alice");
60 const get = async (path: string, c = cookie) => (await fetch(`${servers.url}${path}`, { headers: c === "" ? {} : { cookie: c }, redirect: "manual" }));
61 const post = (path: string, body: Record<string, string> = {}) =>
62 fetch(`${servers.url}${path}`, { method: "POST", headers: { cookie, origin: servers.url }, body: new URLSearchParams(body), redirect: "manual" });
63
64 // no machine: the button says why and what to do
65 let page = await (await get("/alice/shop")).text();
66 expect(page).toContain("Start my environment");
67 expect(page).toContain("No machine is set up for you to use yet");
68 expect(page).toContain('href="/settings/cloud"');
69 expect((await post("/alice/shop/environment/start")).status).toBe(303);
70 expect(calls).toEqual([]);
71
72 // a repository with no compose file, and a visitor who is signed out, see no card
73 expect(await (await get("/alice/plain")).text()).not.toContain('id="environment"');
74 expect(await (await get("/alice/shop", "")).text()).not.toContain('id="environment"');
75
76 allowed = new Set([u.value.id]);
77 page = await (await get("/alice/shop")).text();
78 expect(page).toContain("Start my environment");
79 expect(page).not.toContain("No machine is set up");
80 await post("/alice/shop/environment/start");
81 page = await (await get("/alice/shop")).text();
82 expect(page).toContain('href="https://env.example/mine"');
83 const card = /<section class="stack environment" id="environment">[\s\S]*?<\/section>/.exec(page)?.[0] ?? "";
84 for (const word of ["Stop", "Reset", "Share"]) expect(card).toContain(word); // beside the link
85 expect(card.toLowerCase()).not.toMatch(/docker|container|image|compose|volume/);
86
87 // a post from another origin changes nothing
88 expect((await fetch(`${servers.url}/alice/shop/environment/stop`, { method: "POST", headers: { cookie, origin: "https://evil.example" }, body: new URLSearchParams() })).status).toBe(403);
89 expect(calls).toEqual([`start ${u.value.id}`]);
90
91 // reset names what it loses, and does nothing until said yes
92 expect(await (await get("/alice/shop/environment/reset")).text()).toContain("go back to what the repository holds");
93 await post("/alice/shop/environment/reset");
94 expect(calls).not.toContain("reset");
95 await post("/alice/shop/environment/reset", { confirm: "yes" });
96 expect(calls).toContain("reset");
97 expect(await (await get("/alice/shop")).text()).toContain('href="https://env.example/fresh"');
98
99 // share: one link, opens the address with no sign-in, gone when taken back
100 await post("/alice/shop/environment/share");
101 const link = /href="(\/alice\/shop\/environment\/shared\/[0-9a-f]{48})"/.exec(await (await get("/alice/shop")).text())?.[1];
102 expect(link).toBeDefined();
103 const open = await get(link!, "");
104 expect(open.status).toBe(303);
105 expect(open.headers.get("location")).toBe("https://env.example/fresh");
106 expect((await get("/alice/shop/environment/shared/" + "0".repeat(48), "")).status).toBe(404);
107 await post("/alice/shop/environment/unshare");
108 expect((await get(link!, "")).status).toBe(404);
109
110 // stop asks nothing and offers undo
111 const stopped = await post("/alice/shop/environment/stop");
112 expect(stopped.status).toBe(303);
113 page = await (await get("/alice/shop")).text();
114 expect(page).toContain("Undo");
115 await post("/alice/shop/environment/undo");
116 expect(await (await get("/alice/shop")).text()).toContain('href="https://env.example/mine"');
117 void repo;
118 void plain;
119 });
120
121 test("the actions: a stop can be undone for a minute only, reset needs the yes, a stranger has none", async () => {
122 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
123 if (!u.ok) throw new Error(u.error);
124 promote(app.db, u.value);
125 allowed = new Set([u.value.id]);
126 const repo = await seededRepo(app, u.value, "stack", "private", [{ message: "stack", files: [{ path: "compose.yaml", content: "services: {}\n" }] }]);
127 const t0 = new Date("2026-12-06T10:00:00Z");
128 expect((await startEnvironment(app, u.value, repo, t0)).ok).toBe(true);
129 expect(await resetEnvironment(app, u.value, repo, false, t0)).toEqual(err(RESET_LOSES));
130 expect((await stopEnvironment(app, u.value, repo, t0)).ok).toBe(true);
131 expect(environmentView(app, u.value, repo, t0.getTime() + 30_000)).toEqual({ kind: "stopped", undo: true, share: "" });
132 expect(environmentView(app, u.value, repo, t0.getTime() + 61_000)).toEqual({ kind: "stopped", undo: false, share: "" });
133 expect((await undoStop(app, u.value, repo, new Date(t0.getTime() + 61_000))).ok).toBe(false);
134 expect((await undoStop(app, u.value, repo, new Date(t0.getTime() + 30_000))).ok).toBe(true);
135 // a person who may not use a machine, or may not read the repository, gets nothing
136 const other = await createUser(app.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "a-good-passphrase" });
137 if (!other.ok) throw new Error(other.error);
138 expect(environmentView(app, other.value, repo)).toBeUndefined();
139 expect(environmentView(app, undefined, repo)).toBeUndefined();
140 expect((await startEnvironment(app, other.value, repo)).ok).toBe(false);
141 // the terminal offers the same door to whoever the page does
142 const as = (user: typeof u.value | undefined) => ({ app, user, db: app.db }) as unknown as Session;
143 expect(myEnvironmentCommands(as(u.value), {} as Ctx, repo)).toHaveLength(1);
144 expect(myEnvironmentCommands(as(undefined), {} as Ctx, repo)).toEqual([]);
145 });
test/no-polling.test.ts +1
@@ -307,6 +307,7 @@ const NOT_WALKED: Record<string, string> = {
307307 "/:owner/:name/settings/crew/seat/:role": "one seat of the crew card as an HTML fragment, not a page; :role is a seat the seed does not name",
308308 "/games/:box/@cycle": "the machine block of a game box as an HTML fragment, not a page; no document to weigh, and test/game-machine.test.ts seeds a box and reads it",
309309 "/settings/origins/:id/connection": "one origin's connection block as an HTML fragment, not a page; no document to weigh, and test/origins-page-shape.test.ts seeds an origin and reads it",
310 "/:owner/:name/environment/shared/:token": "a shared environment proxied from a running cell, not a page; the seed starts none",
310311 "/talk/dev/:token": "a frame proxied from a running dev cell, not a page; the seed starts none",
311312 "/talk/dev/:token/*path": "a file proxied from a running dev cell, not a page; the seed starts none",
312313 "/infra/end/:act/*path": "the plan of a stop or delete, a page for a cloud resource the seed does not have; the action word is not in the seed",
test/security-floor-routes.test.ts +1
@@ -87,6 +87,7 @@ const UNSEEDED: Record<string, string> = {
8787 "/games/:box/@spark/:key": "a spark profile of a game box, which the seed does not make (test/game-spark.test.ts covers it)",
8888 "/games/head/:uuid": "a player's head picture, by a Minecraft UUID only a game box's agent reports",
8989 "/games/jar/:id/:name": "a kept plugin jar of a game box, behind a signed URL the seed does not make",
90 "/:owner/:name/environment/shared/:token": "a shared view of someone's environment behind a token the seed does not mint (test/my-environment.test.ts covers it)",
9091 "/talk/dev/:token": "a dev cell reached by a one-time token the seed does not mint (test/dev-cell.test.ts covers it)",
9192 "/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)",
9293 "/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)",

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs