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

Sessions you can see, resume and stop; idle ones stop themselves; a nice environment from the first keystroke #10490

Parked opened this in answer to
Closed without merging

scout/forge:scout/10457-sessions-you-can-see-resume-and-stop-idl → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
17 files changed +586 −13
docs/design/attention-budget.json +2 −2
@@ -109,12 +109,12 @@
109109 },
110110 "settings": {
111111 "390": {
112 "words": 137,
112 "words": 138,
113113 "blocks": 32,
114114 "colours": 1
115115 },
116116 "1280": {
117 "words": 137,
117 "words": 138,
118118 "blocks": 32,
119119 "colours": 1
120120 }
docs/design/audit.md +1
@@ -134,6 +134,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
134134 - `/settings/password` — `pages/account.ts` · change password · `/settings/passkeys` · colour 1.
135135 - `/settings/tokens` — `pages/account.ts` · my API tokens · `/settings/keys` (credentials of two kinds on two pages) · colour 1.
136136 - `/settings/keys` — `pages/account.ts` · my SSH keys · `/settings/tokens` · colour 1.
137 - `/settings/terminals` — `pages/terminals.ts` · my running machine shells · `/settings/keys` · colour 1.
137138 - `/settings/passkeys` — `pages/passkeys.ts` · my passkeys · `/settings/password` · none seen.
138139 - `/settings/confirms` — `pages/confirms.ts` · what the forge's agent asked to do and waits for my yes · the terminal's Confirms (y) · none seen.
139140 - `/settings/secrets` — `pages/secrets.ts` · secrets apps may read · none · none seen.
docs/features/terminals.md added +10
@@ -0,0 +1,10 @@
1 # Terminals: sessions you can see, resume and stop
2
3 `/settings/terminals` lists the signed-in person's running machine shells: the machine, the repository, when it started, its last input, the CPU seconds and memory of its whole process tree now (from /proc), and whether it is attached or detached with the time it stops itself. **Resume** opens the shell page and reattaches; **Stop** ends it; **Stop all idle** ends every session with no input and no output for a minute.
4
5 - Closing a tab detaches; the session keeps running.
6 - A session with no input and no output for `FORGE_SESSION_IDLE_MIN` minutes (default 30, 1–1440) stops itself. Output counts as activity, so a build that prints is not idle.
7 - After a stop, the person's directory and home (shell history in `~/.forge_history`) stay; Resume starts a fresh shell there.
8 - A shell opens with a one-line greeting, a prompt `user owner/repo@branch cwd $`, persistent history and a few aliases (`~/.forge-rc`; the person's own `~/.bashrc` is never overwritten).
9
10 Not done: scrollback surviving a stop, a repository checkout and tool install in the home, dotfiles from a named repo, and app `tty` sessions (ssh) in this list.
src/apps/feature.ts +1 −1
@@ -32,7 +32,7 @@ export const SETTING_TYPES: readonly SettingType[] = ["bool", "int", "string", "
3232 /** The labels the forge's own menus use: a feature may not borrow one. */
3333 const BUILT_IN_MENU_LABELS = [
3434 "your profile", "repositories", "apps", "notes", "talk", "explore", "packs", "displays", "map", "features",
35 "new app", "new repository", "new issue", "new organization", "migrate", "settings", "access tokens", "ssh keys",
35 "new app", "new repository", "new issue", "new organization", "migrate", "settings", "access tokens", "ssh keys", "terminals",
3636 "origins", "boards", "crew", "system memory", "help", "sign out", "log out", "sign in", "admin", "administration",
3737 "theme", "create", "new forge", "create new", "appearance and help", "features from apps", "keyboard shortcuts",
3838 ];
src/http/server.ts +2 −4
@@ -583,6 +583,7 @@ import {
583583 shellOptions,
584584 shellTarget,
585585 stopShells,
586 sessionIdleMs,
586587 withShells,
587588 type ForgeSocket,
588589 type ShellSocket,
@@ -590,9 +591,6 @@ import {
590591
591592 // ---- auth ----
592593
593 /** A machine's shell with no keystroke for this long ends (`machines/shell.ts`). */
594 const SHELL_IDLE_MS = 30 * 60_000;
595
596594 const NO_AUTH: Auth = { user: undefined, scope: undefined, via: "none" };
597595
598596 async function resolveAuth(app: App, request: Request): Promise<Auth> {
@@ -2610,7 +2608,7 @@ export async function serve(app: App): Promise<Servers> {
26102608 const cells = await cellsAvailable();
26112609 if (shellOptions(app) === undefined)
26122610 setShellOptions(app, {
2613 idleMs: SHELL_IDLE_MS,
2611 idleMs: sessionIdleMs(),
26142612 contain: cells.ok ? "cell" : "refuse",
26152613 command: defaultCommand(),
26162614 });
src/http/settings_routes.ts +4
@@ -10,6 +10,7 @@
1010 import type { Handler } from "./context.ts";
1111 import type { Router } from "./router.ts";
1212 import { parentLinkStart } from "./rp.ts";
13 import { terminalsPage, terminalsStop, terminalsStopIdle } from "../web/pages/terminals.ts";
1314 import { accessPage } from "../web/pages/access.ts";
1415 import { capacityPage, capacitySet } from "../web/pages/capacity.ts";
1516 import { teamPage, teamSet, teamsPage, teamsStream } from "../web/pages/teams.ts";
@@ -148,6 +149,9 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
148149 router.add("POST", "/settings/tokens", tokenCreate);
149150 router.add("POST", "/settings/tokens/:id/delete", tokenDelete);
150151 router.add("POST", "/settings/sessions/:id/delete", sessionDelete);
152 router.add("GET", "/settings/terminals", terminalsPage);
153 router.add("POST", "/settings/terminals/stop-idle", terminalsStopIdle);
154 router.add("POST", "/settings/terminals/:id/stop", terminalsStop);
151155 router.add("GET", "/settings/confirms", confirmsList);
152156 router.add("POST", "/settings/confirms/:id", confirmYes);
153157 router.add("GET", "/settings/passkeys", passkeysPage);
src/machines/environment.ts added +54
@@ -0,0 +1,54 @@
1 /**
2 * What a session's home holds from the first keystroke: a prompt that names
3 * the repository and branch, history that persists in the person's own
4 * directory, sensible defaults, and a one-line greeting. Written into the
5 * person's home before the shell starts; their own dotfiles stay theirs
6 * (`.profile` and `.bashrc` are written only where absent, and both just
7 * source `.forge-rc`, which is rewritten each start).
8 *
9 * Every value reaches the shell as an environment variable, never spliced
10 * into the script, so no name can become a command.
11 */
12
13 import { existsSync, writeFileSync } from "node:fs";
14 import { join } from "node:path";
15
16 export interface Greeting {
17 readonly user: string;
18 readonly machine: string;
19 readonly repo: string;
20 readonly idleMinutes: number;
21 }
22
23 /** The one line a session opens with. */
24 export function greeting(g: Greeting): string {
25 return `forge · ${g.user} on ${g.machine} (${g.repo}) · closing the tab keeps this running; it stops after ${g.idleMinutes} min quiet · exit ends it · resume it from /settings/terminals`;
26 }
27
28 export const FORGE_RC = `# written by the forge each start; put your own in ~/.bashrc
29 export HISTFILE="$HOME/.forge_history" HISTSIZE=20000 HISTFILESIZE=20000 HISTCONTROL=ignoredups
30 export EDITOR="\${EDITOR:-vi}" LESS="-FRX" PAGER="\${PAGER:-less}"
31 export PATH="$HOME/.bun/bin:$HOME/bin:$PATH"
32 alias ll='ls -lah'
33 alias gs='git status -sb'
34 __forge_branch() {
35 b=$(git branch --show-current 2>/dev/null)
36 printf '%s' "\${b:-$FORGE_BRANCH}"
37 }
38 PS1='\\u $FORGE_REPO@$(__forge_branch) \\w \\$ '
39 if [ -z "$FORGE_GREETED" ]; then
40 export FORGE_GREETED=1
41 printf '%s\\n' "$FORGE_GREETING"
42 fi
43 `;
44
45 const SOURCE = '[ -f "$HOME/.forge-rc" ] && . "$HOME/.forge-rc"\n';
46
47 /** Write the rc into `home`, and the files that source it where the person has none. */
48 export function prepareHome(home: string): void {
49 writeFileSync(join(home, ".forge-rc"), FORGE_RC);
50 for (const name of [".profile", ".bashrc", ".bash_profile"]) {
51 const path = join(home, name);
52 if (!existsSync(path)) writeFileSync(path, SOURCE);
53 }
54 }
src/machines/shell.ts +97 −2
@@ -37,6 +37,8 @@ import { repoMachines } from "../crew/machines_read.ts";
3737 import { reachableApps, type Machine } from "../crew/machines.ts";
3838 import { ownApp, ownAppUrls } from "../crew/app_hosts.ts";
3939 import { id as newId } from "../kernel/id.ts";
40 import { greeting, prepareHome } from "./environment.ts";
41 import { treeUsage } from "./usage.ts";
4042
4143 // ---- the route ----
4244
@@ -217,7 +219,7 @@ export function lastSessions(db: Database, repoId: string, limit = 20): SessionR
217219 export const ENDED: Record<EndReason, string> = {
218220 exit: "the shell exited",
219221 idle: "idle too long",
220 stopped: "the forge stopped",
222 stopped: "it was stopped",
221223 revoked: "its owner could no longer write here",
222224 failed: "the shell could not start",
223225 };
@@ -243,9 +245,14 @@ interface Session {
243245 readonly terminal: Bun.Terminal;
244246 readonly program: TerminalProgram;
245247 readonly peers: Set<Peer>;
248 readonly machine: string;
249 readonly repoLabel: string;
250 readonly startedAt: number;
246251 /** The pty's size, as last set. */
247252 size: PtySize;
248253 lastInput: number;
254 /** When the program last wrote: a build that prints is not idle. */
255 lastOutput: number;
249256 ended: boolean;
250257 readonly timer: ReturnType<typeof setInterval>;
251258 }
@@ -401,6 +408,7 @@ function start(app: App, grant: ShellGrant, opts: ShellOptions, cols: number, ro
401408 let terminal: Bun.Terminal | undefined;
402409 let cell: Cell | undefined;
403410 let row: string | undefined;
411 let made: Session | undefined;
404412 try {
405413 mkdirSync(join(dir, "home"), { recursive: true });
406414 row = recordStart(app.db, grant.repo.id, grant.machine.name, grant.user.id);
@@ -408,6 +416,7 @@ function start(app: App, grant: ShellGrant, opts: ShellOptions, cols: number, ro
408416 cols,
409417 rows,
410418 data: (_t, chunk) => {
419 if (made !== undefined) made.lastOutput = Date.now();
411420 for (const peer of peers) {
412421 if (peer.readyState !== WebSocket.OPEN) continue;
413422 // A peer that is not reading is closed, never buffered without end.
@@ -426,6 +435,8 @@ function start(app: App, grant: ShellGrant, opts: ShellOptions, cols: number, ro
426435 ownAppUrls(ownApp(app, grant.repo)),
427436 ),
428437 );
438 prepareHome(join(dir, "home"));
439 const repoLabel = `${grant.repo.ownerName}/${grant.repo.name}`;
429440 const env: Record<string, string> = {
430441 PATH: process.env["PATH"] ?? "/usr/bin:/bin",
431442 HOME: join(dir, "home"),
@@ -434,6 +445,16 @@ function start(app: App, grant: ShellGrant, opts: ShellOptions, cols: number, ro
434445 LANG: "C.UTF-8",
435446 FORGE_MACHINE: grant.machine.name,
436447 FORGE_MACHINE_TOOLS: grant.machine.tools.join(" "),
448 FORGE_REPO: repoLabel,
449 FORGE_BRANCH: grant.repo.defaultBranch,
450 FORGE_GREETING: greeting({
451 user: grant.user.username,
452 machine: grant.machine.name,
453 repo: repoLabel,
454 idleMinutes: Math.round(opts.idleMs / 60_000),
455 }),
456 ENV: join(dir, "home", ".forge-rc"),
457 SHELL: Bun.which("bash") ?? "/bin/sh",
437458 };
438459 const program = startTerminal(opts.command, { terminal, env, cwd: dir, cell });
439460 const term = terminal;
@@ -445,12 +466,16 @@ function start(app: App, grant: ShellGrant, opts: ShellOptions, cols: number, ro
445466 terminal: term,
446467 program,
447468 peers,
469 machine: grant.machine.name,
470 repoLabel,
471 startedAt: Date.now(),
448472 size: { cols, rows },
449473 lastInput: Date.now(),
474 lastOutput: Date.now(),
450475 ended: false,
451476 timer: setInterval(
452477 () => {
453 if (Date.now() - session.lastInput >= opts.idleMs) end(app, session, "idle");
478 if (Date.now() - lastActive(session) >= opts.idleMs) end(app, session, "idle");
454479 else if (!stillMay(app, session)) end(app, session, "revoked");
455480 },
456481 Math.max(10, Math.min(opts.idleMs, opts.checkMs ?? CHECK_MS)),
@@ -460,6 +485,7 @@ function start(app: App, grant: ShellGrant, opts: ShellOptions, cols: number, ro
460485 term.close();
461486 end(app, session, "exit");
462487 });
488 made = session;
463489 sessionsOf(app).set(session.key, session);
464490 app.log.info("machine shell started", {
465491 repo: `${grant.repo.ownerName}/${grant.repo.name}`,
@@ -481,6 +507,75 @@ function start(app: App, grant: ShellGrant, opts: ShellOptions, cols: number, ro
481507 }
482508 }
483509
510 const lastActive = (s: Session): number => Math.max(s.lastInput, s.lastOutput);
511
512 /** No input and no output for this long is idle to "Stop all idle"; the idle limit itself is `idleMs`. */
513 export const QUIET_MS = 60_000;
514
515 /** The sessions' one-line facts, as the list shows them. */
516 export interface SessionView {
517 readonly id: string;
518 readonly machine: string;
519 readonly repo: string;
520 readonly startedAt: string;
521 readonly lastInput: string;
522 readonly attached: boolean;
523 /** When it stops itself unless input or output comes first. */
524 readonly stopsAt: string;
525 readonly idle: boolean;
526 readonly cpuSeconds: number | undefined;
527 readonly memoryMiB: number | undefined;
528 }
529
530 /** One person's running sessions, oldest first, with their usage now. */
531 export function mySessions(app: App, userId: string, now = Date.now()): SessionView[] {
532 const idleMs = options.get(app)?.idleMs ?? 0;
533 const out: SessionView[] = [];
534 for (const s of sessionsOf(app).values()) {
535 if (s.userId !== userId) continue;
536 const usage = treeUsage(s.program.pid);
537 out.push({
538 id: s.row,
539 machine: s.machine,
540 repo: s.repoLabel,
541 startedAt: new Date(s.startedAt).toISOString(),
542 lastInput: new Date(s.lastInput).toISOString(),
543 attached: s.peers.size > 0,
544 stopsAt: new Date(lastActive(s) + idleMs).toISOString(),
545 idle: now - lastActive(s) >= QUIET_MS,
546 cpuSeconds: usage?.cpuSeconds,
547 memoryMiB: usage?.memoryMiB,
548 });
549 }
550 return out.sort((a, b) => a.startedAt.localeCompare(b.startedAt));
551 }
552
553 /** Stop one of this person's sessions; false when they have none by that id. */
554 export function stopSession(app: App, userId: string, id: string): boolean {
555 for (const s of sessionsOf(app).values()) {
556 if (s.row === id && s.userId === userId) {
557 end(app, s, "stopped");
558 return true;
559 }
560 }
561 return false;
562 }
563
564 /** Stop this person's sessions quiet for `QUIET_MS`; how many. */
565 export function stopIdle(app: App, userId: string, now = Date.now()): number {
566 let n = 0;
567 for (const s of [...sessionsOf(app).values()]) {
568 if (s.userId === userId && now - lastActive(s) >= QUIET_MS) (end(app, s, "stopped"), n++);
569 }
570 return n;
571 }
572
573 /** The idle limit in ms: `FORGE_SESSION_IDLE_MIN` minutes (1–1440), default 30. The one knob. */
574 export function sessionIdleMs(env: Record<string, string | undefined> = process.env): number {
575 const n = Number(env["FORGE_SESSION_IDLE_MIN"]);
576 return Number.isInteger(n) && n >= 1 && n <= 1440 ? n * 60_000 : 30 * 60_000;
577 }
578
484579 /** End every session (the forge is stopping). */
485580 export function stopShells(app: App): void {
486581 for (const session of [...sessionsOf(app).values()]) end(app, session, "stopped");
src/machines/usage.ts added +74
@@ -0,0 +1,74 @@
1 /**
2 * What a session is using now: the CPU time and resident memory of its
3 * program and everything under it, read from /proc (Linux). Plain data out;
4 * undefined where /proc has no such process or the host has no /proc.
5 */
6
7 import { readdirSync, readFileSync } from "node:fs";
8
9 export interface Usage {
10 /** CPU seconds spent by the tree since it started. */
11 readonly cpuSeconds: number;
12 /** Resident memory of the tree, MiB. */
13 readonly memoryMiB: number;
14 }
15
16 const TICKS_PER_SECOND = 100;
17 const PAGE_BYTES = 4096;
18
19 interface Proc {
20 readonly ppid: number;
21 readonly ticks: number;
22 readonly pages: number;
23 }
24
25 /** One /proc/<pid>/stat line: the fields after the command, which may hold spaces and parentheses. */
26 export function parseStat(line: string): { ppid: number; ticks: number } | undefined {
27 const close = line.lastIndexOf(")");
28 if (close === -1) return undefined;
29 const f = line.slice(close + 2).split(" ");
30 // f[0] is state, f[1] ppid, f[11] utime, f[12] stime.
31 const ppid = Number(f[1]);
32 const ticks = Number(f[11]) + Number(f[12]);
33 return Number.isInteger(ppid) && Number.isFinite(ticks) ? { ppid, ticks } : undefined;
34 }
35
36 function readProc(pid: number): Proc | undefined {
37 try {
38 const stat = parseStat(readFileSync(`/proc/${pid}/stat`, "utf8"));
39 if (stat === undefined) return undefined;
40 const pages = Number(readFileSync(`/proc/${pid}/statm`, "utf8").split(" ")[1]);
41 return { ...stat, pages: Number.isFinite(pages) ? pages : 0 };
42 } catch {
43 return undefined;
44 }
45 }
46
47 /** The tree rooted at `root`, summed; undefined when `root` is not running. */
48 export function treeUsage(root: number): Usage | undefined {
49 const procs = new Map<number, Proc>();
50 try {
51 for (const name of readdirSync("/proc")) {
52 if (!/^[1-9]\d*$/.test(name)) continue;
53 const p = readProc(Number(name));
54 if (p !== undefined) procs.set(Number(name), p);
55 }
56 } catch {
57 return undefined;
58 }
59 if (!procs.has(root)) return undefined;
60 const inTree = new Set<number>([root]);
61 // Parents may have higher pids than children, so settle by passes.
62 for (let grew = true; grew; ) {
63 grew = false;
64 for (const [pid, p] of procs) if (!inTree.has(pid) && inTree.has(p.ppid)) (inTree.add(pid), (grew = true));
65 }
66 let ticks = 0;
67 let pages = 0;
68 for (const pid of inTree) {
69 const p = procs.get(pid)!;
70 ticks += p.ticks;
71 pages += p.pages;
72 }
73 return { cpuSeconds: ticks / TICKS_PER_SECOND, memoryMiB: Math.round((pages * PAGE_BYTES) / 1048576) };
74 }
src/web/layout.ts +2
@@ -323,6 +323,7 @@ function userMenu(
323323 { separator: true, label: "" },
324324 { label: "Settings", href: "/settings", icon: "settings" },
325325 { label: "Access tokens", href: "/settings/tokens", icon: "key" },
326 { label: "Terminals", href: "/settings/terminals", icon: "terminal" },
326327 { label: "SSH keys", href: "/settings/keys", icon: "lock" },
327328 { label: "Origins", href: "/settings/origins", icon: "globe" },
328329 ...(!user.isAdmin && administersAny(ctx.app.db, user)
@@ -396,6 +397,7 @@ const STATIC_PALETTE: PaletteItem[] = [
396397 { t: "Search", h: "/search", c: "Go to" },
397398 { t: "Account settings", h: "/settings", c: "Settings" },
398399 { t: "Access tokens", h: "/settings/tokens", c: "Settings" },
400 { t: "Terminals: sessions to resume or stop", h: "/settings/terminals", c: "Settings" },
399401 { t: "SSH keys", h: "/settings/keys", c: "Settings" },
400402 { t: "Origins", h: "/settings/origins", c: "Settings" },
401403 ];
src/web/machine-term-wire.ts +2 −1
@@ -38,7 +38,8 @@ export function resizeFrame(size: Size): string {
3838 /** Why a closed socket closed, in words a person can act on. */
3939 export function closedWords(code: number, reason: string): string {
4040 const why = reason.trim() !== "" ? reason.trim() : code === 1000 ? "the shell exited" : "the connection dropped";
41 return `Disconnected: ${why}. Reload to reattach.`;
41 // A dropped connection only detaches: the session is still there.
42 return code === 1000 ? `Disconnected: ${why}. Reload to reattach.` : `Disconnected: ${why}. The session keeps running and stops itself when quiet; reload to reattach.`;
4243 }
4344
4445 export interface Wired {
src/web/pages/origins.ts +2
@@ -93,6 +93,7 @@ export type AccountSection =
9393 | "confirms"
9494 | "password"
9595 | "tokens"
96 | "terminals"
9697 | "keys"
9798 | "model"
9899 | "passkeys"
@@ -142,6 +143,7 @@ const SECTION_ROWS: readonly (readonly [
142143 ["Account", "Passkeys", "/settings/passkeys", "key", (c) => c === "passkeys", false],
143144 ["Account", "SSH keys", "/settings/keys", "lock", (c) => c === "keys", false],
144145 ["Account", "Access tokens", "/settings/tokens", "key", (c) => c === "tokens", false],
146 ["Account", "Terminals", "/settings/terminals", "terminal", (c) => c === "terminals", false],
145147 ["Account", "Confirms", "/settings/confirms", "check", (c) => c === "confirms", false],
146148 ["Crew and AI", "Model", "/settings/model", "key", (c) => c === "model", false],
147149 ["Crew and AI", "Crew", "/settings/crew", "bot", (c) => c === "crew", true],
src/web/pages/terminals.ts added +101
@@ -0,0 +1,101 @@
1 /**
2 * GET /settings/terminals — the person's running machine shells in one list
3 * (`machines/shell.ts`): what each is, where, when it started, its last
4 * input, the CPU and memory it uses now, and when it stops itself unless it
5 * is used. Resume opens its page and reattaches; Stop ends it; Stop all idle
6 * ends every one quiet for a minute. A closed tab only detaches: the list is
7 * where a session left running is found. Account-only: a session is its
8 * owner's alone, and the stop routes act on the caller's own.
9 */
10
11 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
12 import type { Ctx } from "../../http/context.ts";
13 import { mySessions, sessionIdleMs, stopIdle, stopSession, type SessionView } from "../../machines/shell.ts";
14 import { settingsLayout, signInFirst } from "../chrome.ts";
15 import { readForm } from "../form.ts";
16 import { html } from "../html.ts";
17 import { flashTo, page } from "../layout.ts";
18 import { badge, btn, icon, row, time } from "../ui.ts";
19 import { accountSections } from "./origins.ts";
20
21 /** "00:47" from a number of ms: hours and minutes until it stops. */
22 export function untilWords(ms: number): string {
23 const minutes = Math.max(0, Math.ceil(ms / 60_000));
24 return `${String(Math.floor(minutes / 60)).padStart(2, "0")}:${String(minutes % 60).padStart(2, "0")}`;
25 }
26
27 const usageWords = (s: SessionView): string =>
28 s.cpuSeconds === undefined || s.memoryMiB === undefined
29 ? "usage unavailable"
30 : `CPU ${s.cpuSeconds.toFixed(1)} s · memory ${s.memoryMiB} MiB`;
31
32 function line(s: SessionView, now: number) {
33 const left = Date.parse(s.stopsAt) - now;
34 return row({
35 lead: icon("terminal"),
36 title: html`${s.machine} <span class="muted small mono">${s.repo}</span>
37 ${s.attached
38 ? badge("attached", { tone: "success" })
39 : badge(`detached, stops at ${untilWords(left)} unless you come back`, { variant: "outline", icon: "clock" })}`,
40 meta: html`Started ${time(s.startedAt)} · last input ${time(s.lastInput)} · ${usageWords(s)}`,
41 trail: html`${btn("Resume", { href: `/${s.repo}/machines/${s.machine}/shell`, size: "sm" })}
42 <form class="row-fields" method="post" action="/settings/terminals/${s.id}/stop">
43 ${btn("Stop", { size: "sm", variant: "outline", label: `Stop the ${s.machine} session on ${s.repo}` })}
44 </form>`,
45 data: { session: s.id },
46 });
47 }
48
49 export function terminalsPage(ctx: Ctx): Response {
50 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
51 const user = ctx.auth.user;
52 if (user === undefined) return signInFirst(ctx);
53 const now = Date.now();
54 const list = mySessions(ctx.app, user.id, now);
55 const minutes = Math.round(sessionIdleMs() / 60_000);
56 const body = html`<section class="settings-block">
57 <h2>Running sessions</h2>
58 <p class="muted small">
59 Closing a tab detaches; it does not stop the session. A session with no input and no output for
60 ${minutes} minutes stops itself (<code>FORGE_SESSION_IDLE_MIN</code>); its files and shell history stay in
61 your directory on the machine, and Resume starts a fresh shell there.
62 </p>
63 ${list.length === 0
64 ? html`<p class="small" id="terminals-none">Nothing is running for you.</p>`
65 : html`<ul class="list setting-list" id="terminals">${list.map((s) => line(s, now))}</ul>
66 <form class="row-fields" method="post" action="/settings/terminals/stop-idle">
67 ${btn("Stop all idle", { size: "sm", variant: "outline" })}
68 <span class="muted small">every session quiet for a minute or more</span>
69 </form>`}
70 </section>`;
71 return timePhase(ctx.request, "render", () =>
72 page({
73 ctx,
74 title: "Terminals",
75 body: html`<div class="page-head"><h1>Terminals</h1></div>
76 ${settingsLayout(accountSections("terminals", { admin: ctx.auth.user?.isAdmin === true }), body, "Account settings")}`,
77 }),
78 );
79 }
80
81 export async function terminalsStop(ctx: Ctx): Promise<Response> {
82 const user = ctx.auth.user;
83 if (user === undefined) return signInFirst(ctx);
84 const form = await readForm(ctx, "rw");
85 if (form instanceof Response) return form;
86 const stopped = stopSession(ctx.app, user.id, ctx.params.id ?? "");
87 return flashTo(
88 ctx,
89 "/settings/terminals",
90 stopped ? { message: "Stopped." } : { tone: "danger", message: "That session is not running." },
91 );
92 }
93
94 export async function terminalsStopIdle(ctx: Ctx): Promise<Response> {
95 const user = ctx.auth.user;
96 if (user === undefined) return signInFirst(ctx);
97 const form = await readForm(ctx, "rw");
98 if (form instanceof Response) return form;
99 const n = stopIdle(ctx.app, user.id);
100 return flashTo(ctx, "/settings/terminals", { message: n === 0 ? "Nothing was idle." : `Stopped ${n} idle session${n === 1 ? "" : "s"}.` });
101 }
test/machine-shell-page.test.ts +1 −1
@@ -148,7 +148,7 @@ test("the wiring sends the size on open, one frame per new size, and keystrokes
148148 wired.received(new Uint8Array([104, 105]));
149149 expect(written).toHaveLength(1);
150150 wired.closed(1011, "this forge cannot hold a machine's shell");
151 expect(said.at(-1)).toBe("Disconnected: this forge cannot hold a machine's shell. Reload to reattach.");
151 expect(said.at(-1)).toBe("Disconnected: this forge cannot hold a machine's shell. The session keeps running and stops itself when quiet; reload to reattach.");
152152 const count = frames.length;
153153 typed("late");
154154 box.size = { cols: 100, rows: 30 };
test/pull-quiet.test.ts +2 −2
@@ -66,8 +66,8 @@ afterAll(async () => {
6666 const get = async (path: string) => (await fetch(`${servers.url}${path}`, { headers: { cookie } })).text();
6767 const bytes = (t: string) => new TextEncoder().encode(t).length;
6868
69 // Measured 31,084 (pull) and 25,064 (list) with the Displays entry in the account menu and palette. Each budget is that plus ~160 B, the spread the port digits and times in the page showed, so it holds the page from growing and is not a tighter squeeze.
70 const BUDGET = { pull: 31_250, list: 25_230 };
69 // Measured 31,459 (pull) and 25,265 (list) with the Displays and Terminals entries in the account menu and palette. Each budget is that plus ~160 B, the spread the port digits and times in the page showed, so it holds the page from growing and is not a tighter squeeze.
70 const BUDGET = { pull: 31_620, list: 25_430 };
7171
7272 test("the pull page's check is a line with a dot and its word, not a card around a badge", async () => {
7373 const text = await get(`/alice/r/pulls/${number}`);
test/terminals.test.ts added +230
@@ -0,0 +1,230 @@
1 /**
2 * The person's sessions as a list they can act on: real usage, detach on a
3 * closed tab, Stop and Stop all idle, idle stopping only what is quiet (a
4 * session that prints is not idle), Resume into the same directory, the
5 * one idle knob, and the environment a shell opens with.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { existsSync, mkdtempSync, readFileSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { createRepo, type Repo } from "../src/core/repos.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { greeting } from "../src/machines/environment.ts";
17 import {
18 QUIET_MS,
19 lastSessions,
20 liveSessions,
21 mySessions,
22 sessionIdleMs,
23 setShellOptions,
24 stopIdle,
25 stopSession,
26 stopShells,
27 workspace,
28 } from "../src/machines/shell.ts";
29 import { parseStat } from "../src/machines/usage.ts";
30 import { BUILT_IN } from "../src/crew/machines.ts";
31 import { untilWords } from "../src/web/pages/terminals.ts";
32 import { quietLogs } from "./helpers/globals.ts";
33
34 quietLogs();
35
36 let app: App;
37 let servers: Servers;
38 let repo: Repo;
39 let aliceId: string;
40 let base: string;
41 const cookies: Record<string, string> = {};
42 const OPTS = { idleMs: 60_000, contain: "uncontained", command: "exec /bin/sh -i", handshakesPerMinute: 1000 } as const;
43
44 async function person(name: string): Promise<string> {
45 const made = await createUser(app.db, { username: name, email: `${name}@x.test`, password: "correct horse battery", origin: "seed", trusted: true });
46 if (!made.ok) throw new Error(String(made.error));
47 cookies[name] = `forge_session=${createSession(app.db, made.value.id).token}`;
48 return made.value.id;
49 }
50
51 beforeAll(async () => {
52 app = createApp({ dataDir: mkdtempSync(join(tmpdir(), "terminals-")), port: 0 });
53 setShellOptions(app, OPTS);
54 aliceId = await person("alice");
55 await person("bob");
56 const made = await createRepo(app.db, app.reposRoot, { ownerId: aliceId, name: "lab", visibility: "public" });
57 if (!made.ok) throw new Error(String(made.error));
58 repo = made.value;
59 servers = await serve(app);
60 base = servers.url.replace(/^http/, "ws");
61 });
62
63 afterAll(() => {
64 stopShells(app);
65 servers.stop();
66 app.close();
67 });
68
69 const origin = () => new URL(servers.url).origin;
70
71 function open(who = "alice"): Promise<{ ws: WebSocket; seen: () => string }> {
72 const ws = new WebSocket(`${base}/alice/lab/machines/standard/shell`, {
73 headers: { cookie: cookies[who]!, origin: origin() },
74 } as unknown as string[]);
75 ws.binaryType = "arraybuffer";
76 let text = "";
77 ws.addEventListener("message", (e) => {
78 text += typeof e.data === "string" ? e.data : new TextDecoder().decode(e.data as ArrayBuffer);
79 });
80 return new Promise((resolve, reject) => {
81 ws.addEventListener("open", () => resolve({ ws, seen: () => text }));
82 ws.addEventListener("error", () => reject(new Error("refused")));
83 });
84 }
85
86 async function until(what: () => boolean, ms = 5_000): Promise<void> {
87 const end = Date.now() + ms;
88 while (!what()) {
89 if (Date.now() > end) throw new Error("timed out");
90 await Bun.sleep(20);
91 }
92 }
93
94 const type = (ws: WebSocket, text: string) => ws.send(new TextEncoder().encode(text));
95 const post = (path: string, who = "alice") =>
96 fetch(`${origin()}${path}`, { method: "POST", redirect: "manual", headers: { cookie: cookies[who]!, origin: origin() } });
97 const page = async (who = "alice") =>
98 (await fetch(`${origin()}/settings/terminals`, { headers: { cookie: cookies[who]! } })).text();
99
100 test("the shell opens with a greeting, a prompt naming the repo and branch, and history in the person's home", async () => {
101 const { ws, seen } = await open();
102 await until(() => seen().includes("forge · alice on standard (alice/lab)"));
103 expect(seen()).toContain("resume it from /settings/terminals");
104 type(ws, "echo $FORGE_REPO@$FORGE_BRANCH $HISTFILE\n");
105 await until(() => seen().includes(`alice/lab@${repo.defaultBranch} ${workspace(app, repo, BUILT_IN[0]!, aliceId)}/home/.forge_history`));
106 ws.close();
107 await until(() => liveSessions(app) === 1 && mySessions(app, aliceId)[0]?.attached === false);
108 stopShells(app);
109 });
110
111 test("the list shows what is running with real usage; closing the tab detaches and does not kill", async () => {
112 const { ws } = await open();
113 await until(() => mySessions(app, aliceId).length === 1);
114 const attached = await page();
115 expect(attached).toContain('id="terminals"');
116 expect(attached).toContain("standard");
117 expect(attached).toContain("alice/lab");
118 expect(attached).toMatch(/memory [1-9]\d* MiB/);
119 expect(attached).toContain("attached");
120 expect(attached).toContain("/alice/lab/machines/standard/shell");
121 expect(attached).toContain("Stop all idle");
122
123 ws.close();
124 await until(() => mySessions(app, aliceId)[0]?.attached === false);
125 expect(liveSessions(app)).toBe(1);
126 expect(lastSessions(app.db, repo.id)[0]?.endedAt).toBeUndefined();
127 expect(await page()).toMatch(/detached, stops at \d\d:\d\d unless you come back/);
128 // Another account sees none of it.
129 expect(await page("bob")).toContain("Nothing is running for you.");
130 expect(untilWords(47 * 60_000 - 1)).toBe("00:47");
131 expect(untilWords(90 * 60_000)).toBe("01:30");
132 });
133
134 test("Resume reattaches to the same running session, with its scrollback", async () => {
135 const { ws } = await open();
136 type(ws, "echo marker''-one\n");
137 await until(() => liveSessions(app) === 1);
138 const back = await open();
139 expect(liveSessions(app)).toBe(1);
140 type(ws, "echo again''-two\n");
141 await until(() => back.seen().includes("again-two"));
142 ws.close();
143 back.ws.close();
144 await until(() => mySessions(app, aliceId)[0]?.attached === false);
145 });
146
147 test("Stop ends your own session and nobody else's can; Stop all idle ends only the quiet", async () => {
148 const id = mySessions(app, aliceId)[0]!.id;
149 expect(stopSession(app, "someone-else", id)).toBe(false);
150 expect((await post(`/settings/terminals/${id}/stop`, "bob")).status).toBe(303);
151 expect(liveSessions(app)).toBe(1);
152 expect((await post(`/settings/terminals/${id}/stop`)).status).toBe(303);
153 expect(liveSessions(app)).toBe(0);
154 expect(lastSessions(app.db, repo.id)[0]).toMatchObject({ id, endReason: "stopped" });
155
156 const { ws } = await open();
157 await until(() => liveSessions(app) === 1);
158 // Just used: nothing is idle. A minute on, it is.
159 expect(stopIdle(app, aliceId)).toBe(0);
160 expect(mySessions(app, aliceId)[0]?.idle).toBe(false);
161 expect(mySessions(app, aliceId, Date.now() + QUIET_MS + 1)[0]?.idle).toBe(true);
162 expect(stopIdle(app, aliceId, Date.now() + QUIET_MS + 1)).toBe(1);
163 expect(liveSessions(app)).toBe(0);
164 ws.close();
165 const none = await post("/settings/terminals/stop-idle");
166 expect(none.status).toBe(303);
167 });
168
169 test("a cross-origin or signed-out stop does nothing", async () => {
170 const { ws } = await open();
171 await until(() => liveSessions(app) === 1);
172 const id = mySessions(app, aliceId)[0]!.id;
173 const evil = await fetch(`${origin()}/settings/terminals/${id}/stop`, {
174 method: "POST",
175 redirect: "manual",
176 headers: { cookie: cookies["alice"]!, origin: "https://evil.example" },
177 });
178 expect(evil.status).toBe(403);
179 const out = await fetch(`${origin()}/settings/terminals/${id}/stop`, { method: "POST", redirect: "manual" });
180 expect(out.status).not.toBe(200);
181 expect(liveSessions(app)).toBe(1);
182 ws.close();
183 stopShells(app);
184 });
185
186 test("idle stops a quiet session, keeps one that prints, and Resume comes back to the same files", async () => {
187 stopShells(app);
188 setShellOptions(app, { ...OPTS, idleMs: 600 });
189 const { ws, seen } = await open();
190 type(ws, "echo kept > $HOME/kept.txt\n");
191 await until(() => existsSync(join(workspace(app, repo, BUILT_IN[0]!, aliceId), "home", "kept.txt")));
192 // Quiet: ends as idle.
193 ws.close();
194 await until(() => lastSessions(app.db, repo.id)[0]?.endReason === "idle", 4_000);
195 expect(liveSessions(app)).toBe(0);
196
197 // Running something that prints is not idle, though no key is pressed.
198 const busy = await open();
199 type(busy.ws, "i=0; while [ $i -lt 40 ]; do echo tick; i=$((i+1)); sleep 0.05; done; echo done''-busy\n");
200 await Bun.sleep(1_200);
201 expect(liveSessions(app)).toBe(1);
202 await until(() => busy.seen().includes("done-busy"));
203 void seen;
204
205 // Resume after the idle stop: a new shell in the same home.
206 const idled = await until(() => liveSessions(app) === 0, 4_000).then(() => true);
207 expect(idled).toBe(true);
208 const again = await open();
209 type(again.ws, "cat $HOME/kept.txt\n");
210 await until(() => again.seen().includes("kept"));
211 expect(readFileSync(join(workspace(app, repo, BUILT_IN[0]!, aliceId), "home", "kept.txt"), "utf8")).toBe("kept\n");
212 again.ws.close();
213 stopShells(app);
214 setShellOptions(app, OPTS);
215 });
216
217 test("the idle limit is one knob, FORGE_SESSION_IDLE_MIN, 30 minutes by default and never garbage", () => {
218 expect(sessionIdleMs({})).toBe(30 * 60_000);
219 expect(sessionIdleMs({ FORGE_SESSION_IDLE_MIN: "5" })).toBe(5 * 60_000);
220 for (const bad of ["0", "-3", "abc", "1.5", "99999", ""]) expect(sessionIdleMs({ FORGE_SESSION_IDLE_MIN: bad })).toBe(30 * 60_000);
221 });
222
223 test("the greeting says what the session is and how to leave; a stat line is read past a command with parentheses", () => {
224 const g = greeting({ user: "alice", machine: "standard", repo: "alice/lab", idleMinutes: 30 });
225 expect(g).toContain("alice on standard (alice/lab)");
226 expect(g).toContain("exit ends it");
227 expect(g).toContain("30 min quiet");
228 expect(parseStat("123 (a b) c) S 77 1 1 0 -1 0 0 0 0 0 40 2 0 0")).toEqual({ ppid: 77, ticks: 42 });
229 expect(parseStat("garbage")).toBeUndefined();
230 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs