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 #10462
mason/forge:mason/10457-sessions-you-can-see-resume-and-stop-idl → main 5 commits fork
19 files
changed +1343
−36
AGENTS.md +2
| @@ -19,3 +19,5 @@ State shared between modules through process memory, not the database, is named | ||
| 19 | 19 | `src/perf/loop_worst.ts`: `loopWorst`, the worst event-loop lag of the last 10 s in ten one-second slots, fed by one unref'd 50 ms timer that the first `serve` starts (`startLoopWorst`), and read by every response's `lag;dur` and by `/healthz` asked for JSON (`loopLagMs`). Tests listing a request's phases read `requestTiming` (`test/helpers/request-timing.ts`), which leaves `lag` out. |
| 20 | 20 | |
| 21 | 21 | `src/core/transfer.ts`: the old owner/name pairs a transfer left behind (`repo_redirect`), held per database after the first request reads them and dropped by `transferRepo`, so a request under a path nothing moved from costs no statement (#569). |
| 22 | ||
| 23 | Terminal sessions (#10457): `src/machines/terminals.ts` is the one list of a person's sessions (machine shells and app terminals register there; `/settings/terminals` shows it with Resume, Stop and Stop all idle). A session stops after `FORGE_TERMINAL_IDLE_MINUTES` (default 30, `src/machines/idle.ts`) with no input, no output and no CPU in its process tree; `src/machines/snapshot.ts` keeps its scrollback and directory under the machine's workspace so Resume restores both. `src/machines/environment.ts` makes the shell's checkout, prompt, history, dotfiles (`owner/name`, set at `/settings/terminals`) and greeting. Sessions being made count against the caps in `shell.ts` (`pendingOf`, process memory). |
docs/design/attention-budget.json +2 −2
| @@ -109,12 +109,12 @@ | ||
| 109 | 109 | }, |
| 110 | 110 | "settings": { |
| 111 | 111 | "390": { |
| 112 | "words": 137, | |
| 112 | "words": 138, | |
| 113 | 113 | "blocks": 32, |
| 114 | 114 | "colours": 1 |
| 115 | 115 | }, |
| 116 | 116 | "1280": { |
| 117 | "words": 137, | |
| 117 | "words": 138, | |
| 118 | 118 | "blocks": 32, |
| 119 | 119 | "colours": 1 |
| 120 | 120 | } |
docs/design/audit.md +1
| @@ -134,6 +134,7 @@ Machine routes are not pages and have no entry: `/audit.csv`, | ||
| 134 | 134 | - `/settings/password` — `pages/account.ts` · change password · `/settings/passkeys` · colour 1. |
| 135 | 135 | - `/settings/tokens` — `pages/account.ts` · my API tokens · `/settings/keys` (credentials of two kinds on two pages) · colour 1. |
| 136 | 136 | - `/settings/keys` — `pages/account.ts` · my SSH keys · `/settings/tokens` · colour 1. |
| 137 | - `/settings/terminals` — `pages/terminals.ts` · my shell sessions, to resume or stop · `/settings/keys` · colour 1. | |
| 137 | 138 | - `/settings/passkeys` — `pages/passkeys.ts` · my passkeys · `/settings/password` · none seen. |
| 138 | 139 | - `/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. |
| 139 | 140 | - `/settings/secrets` — `pages/secrets.ts` · secrets apps may read · none · none seen. |
scripts/unreached-allow.json −1
| @@ -15,7 +15,6 @@ | ||
| 15 | 15 | "src/flow/review_rounds.ts", |
| 16 | 16 | "src/flow/shared_red.ts", |
| 17 | 17 | "src/flow/stale_fold.ts", |
| 18 | "src/kernel/why_now.ts", | |
| 19 | 18 | "src/spawn/pod.ts", |
| 20 | 19 | "src/tui/gallery.ts", |
| 21 | 20 | "src/tui/ui/qr.ts", |
src/apps/tty.ts +40 −1
| @@ -36,6 +36,9 @@ import { | ||
| 36 | 36 | } from "./data.ts"; |
| 37 | 37 | import { appEnv, signalGroup } from "./process.ts"; |
| 38 | 38 | import { appsRuntime } from "./runtime.ts"; |
| 39 | import { terminalIdleMs } from "../machines/idle.ts"; | |
| 40 | import { observe, registerTerminal, shouldStopIdle, unregisterTerminal, type LiveTerminal } from "../machines/terminals.ts"; | |
| 41 | import { id as newId } from "../kernel/id.ts"; | |
| 39 | 42 | |
| 40 | 43 | const CRLF = "\r\n"; |
| 41 | 44 | |
| @@ -165,10 +168,14 @@ export async function runAppTty( | ||
| 165 | 168 | } |
| 166 | 169 | if (live.tty === null) return err({ refusal: "no_tty", detail: "" }); |
| 167 | 170 | |
| 171 | const activity = { lastInput: Date.now(), lastOutput: Date.now(), lastBusy: Date.now() }; | |
| 168 | 172 | const terminal = new Bun.Terminal({ |
| 169 | 173 | cols: Math.max(1, host.cols || 80), |
| 170 | 174 | rows: Math.max(1, host.rows || 24), |
| 171 | data: (_t, chunk) => host.write(chunk), | |
| 175 | data: (_t, chunk) => { | |
| 176 | activity.lastOutput = Date.now(); | |
| 177 | host.write(chunk); | |
| 178 | }, | |
| 172 | 179 | }); |
| 173 | 180 | const env = appEnv({ |
| 174 | 181 | port: live.port, |
| @@ -213,7 +220,37 @@ export async function runAppTty( | ||
| 213 | 220 | user: user?.username ?? "guest", |
| 214 | 221 | }); |
| 215 | 222 | |
| 223 | // A person's app terminal is on their list of terminals, and an idle one is | |
| 224 | // hung up like any other (`machines/terminals.ts`). A guest's is nobody's. | |
| 225 | const idleMs = terminalIdleMs(); | |
| 226 | const id = newId(); | |
| 227 | let timer: ReturnType<typeof setInterval> | undefined; | |
| 228 | if (user !== undefined) { | |
| 229 | const tracked: LiveTerminal = { | |
| 230 | id, | |
| 231 | kind: "app", | |
| 232 | userId: user.id, | |
| 233 | what: "App terminal", | |
| 234 | where: `${target.app.slug} (${target.env})`, | |
| 235 | href: "", | |
| 236 | pid: program.pid, | |
| 237 | startedAt: activity.lastInput, | |
| 238 | idleMs, | |
| 239 | activity, | |
| 240 | attached: () => 1, | |
| 241 | detachedAt: () => undefined, | |
| 242 | resumable: false, | |
| 243 | stop: () => program.hangup(), | |
| 244 | }; | |
| 245 | registerTerminal(forge, tracked); | |
| 246 | timer = setInterval(() => { | |
| 247 | observe(tracked); | |
| 248 | if (shouldStopIdle(tracked)) program.hangup(); | |
| 249 | }, Math.max(10, Math.min(idleMs, 5_000))); | |
| 250 | } | |
| 251 | ||
| 216 | 252 | host.onData((chunk) => { |
| 253 | activity.lastInput = Date.now(); | |
| 217 | 254 | if (terminal.closed) return; |
| 218 | 255 | try { |
| 219 | 256 | terminal.write(chunk); |
| @@ -234,6 +271,8 @@ export async function runAppTty( | ||
| 234 | 271 | // `exited`, never the pty's own exit callback (see runEditor). |
| 235 | 272 | return ok(await program.exited); |
| 236 | 273 | } finally { |
| 274 | if (timer !== undefined) clearInterval(timer); | |
| 275 | unregisterTerminal(forge, id); | |
| 237 | 276 | terminal.close(); |
| 238 | 277 | } |
| 239 | 278 | } |
src/http/server.ts +2 −1
| @@ -574,6 +574,7 @@ import { | ||
| 574 | 574 | import { getVerifiedDomain } from "../core/domains.ts"; |
| 575 | 575 | import { previewOwner } from "../spawn/preview-owner.ts"; |
| 576 | 576 | import { cellsAvailable } from "../apps/contain.ts"; |
| 577 | import { terminalIdleMs } from "../machines/idle.ts"; | |
| 577 | 578 | import { machineShellPage, machinesSettingsPage } from "../web/pages/machines.ts"; |
| 578 | 579 | import { machineTermAsset, wasmResponse, ghosttyWasmAsset } from "../web/machine-term-asset.ts"; |
| 579 | 580 | import { |
| @@ -591,7 +592,7 @@ import { | ||
| 591 | 592 | // ---- auth ---- |
| 592 | 593 | |
| 593 | 594 | /** A machine's shell with no keystroke for this long ends (`machines/shell.ts`). */ |
| 594 | const SHELL_IDLE_MS = 30 * 60_000; | |
| 595 | const SHELL_IDLE_MS = terminalIdleMs(); | |
| 595 | 596 | |
| 596 | 597 | const NO_AUTH: Auth = { user: undefined, scope: undefined, via: "none" }; |
| 597 | 598 |
src/http/settings_routes.ts +5
| @@ -13,6 +13,7 @@ import { parentLinkStart } from "./rp.ts"; | ||
| 13 | 13 | import { accessPage } from "../web/pages/access.ts"; |
| 14 | 14 | import { capacityPage, capacitySet } from "../web/pages/capacity.ts"; |
| 15 | 15 | import { teamPage, teamSet, teamsPage, teamsStream } from "../web/pages/teams.ts"; |
| 16 | import { dotfilesSet, terminalStop, terminalsPage, terminalsStopIdle } from "../web/pages/terminals.ts"; | |
| 16 | 17 | import { telemetryPage, telemetrySet } from "../web/pages/telemetry.ts"; |
| 17 | 18 | import { flagsPage, flagsSet } from "../web/pages/flags.ts"; |
| 18 | 19 | import { economicsPage, economicsSet } from "../web/pages/economics.ts"; |
| @@ -127,6 +128,10 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea | ||
| 127 | 128 | router.add("POST", "/settings/trusted/stop", trustedStop); |
| 128 | 129 | router.add("POST", "/settings/trusted/revert", trustedRevert); |
| 129 | 130 | router.add("POST", "/settings/trusted/:id/remove", trustedRemove); |
| 131 | router.add("GET", "/settings/terminals", terminalsPage); | |
| 132 | router.add("POST", "/settings/terminals/stop-idle", terminalsStopIdle); | |
| 133 | router.add("POST", "/settings/terminals/dotfiles", dotfilesSet); | |
| 134 | router.add("POST", "/settings/terminals/:id/stop", terminalStop); | |
| 130 | 135 | router.add("GET", "/settings/telemetry", telemetryPage); |
| 131 | 136 | router.add("POST", "/settings/telemetry", telemetrySet); |
| 132 | 137 | router.add("GET", "/settings", accountPage); |
src/machines/environment.ts added +191
| @@ -0,0 +1,191 @@ | ||
| 1 | /** | |
| 2 | * What a shell finds when it opens (#10457): the repository checked out, a | |
| 3 | * prompt that names it and its branch, history that persists, sensible | |
| 4 | * defaults, the person's own dotfiles when they named a repository for | |
| 5 | * them, and one line saying what this session is and how to leave. Files | |
| 6 | * only: the shell reads them, no text a person types reaches a command line. | |
| 7 | * | |
| 8 | * Everything lives in the person's workspace (`machines/shell.ts` | |
| 9 | * `workspace`): `<workspace>/<repo>` is the checkout, `<workspace>/home` the | |
| 10 | * shell's HOME, and `home/.forge/` what this module and the shell keep. | |
| 11 | */ | |
| 12 | ||
| 13 | import { existsSync, mkdirSync, symlinkSync, writeFileSync, rmSync } from "node:fs"; | |
| 14 | import { join } from "node:path"; | |
| 15 | import type { App } from "../app.ts"; | |
| 16 | import { getRepo, canRead, type Repo } from "../core/repos.ts"; | |
| 17 | import { getUserSetting } from "../core/settings.ts"; | |
| 18 | import type { User } from "../core/users.ts"; | |
| 19 | import { runGit } from "../git/env.ts"; | |
| 20 | import { isSafeName } from "../git/guard.ts"; | |
| 21 | import { repoDir } from "../git/repos.ts"; | |
| 22 | import { readFileAt } from "../apps/checkout.ts"; | |
| 23 | import { parseManifest } from "../apps/manifest.ts"; | |
| 24 | ||
| 25 | /** `user_setting` key holding the `owner/name` of the person's dotfiles repository. */ | |
| 26 | export const DOTFILES_KEY = "dotfiles_repo"; | |
| 27 | ||
| 28 | /** `owner/name`, both safe path segments, or undefined. */ | |
| 29 | export function parseDotfilesRepo(text: string): { owner: string; name: string } | undefined { | |
| 30 | const m = /^([^/\s]+)\/([^/\s]+)$/.exec(text.trim()); | |
| 31 | if (m === null) return undefined; | |
| 32 | const [, owner, name] = m as unknown as [string, string, string]; | |
| 33 | return isSafeName(owner) && isSafeName(name) ? { owner, name } : undefined; | |
| 34 | } | |
| 35 | ||
| 36 | /** Files a dotfiles repository may offer, linked into HOME when HOME has none of its own. */ | |
| 37 | const LINKED = [".gitconfig", ".tmux.conf", ".vimrc", ".inputrc"] as const; | |
| 38 | ||
| 39 | async function clone(source: string, target: string, remote: string, branch?: string): Promise<boolean> { | |
| 40 | const cloned = await runGit(["clone", "--quiet", ...(branch === undefined ? [] : ["--branch", branch]), "--", source, target]); | |
| 41 | if (!cloned.ok) return false; | |
| 42 | await runGit(["remote", "set-url", "origin", remote], { cwd: target }); | |
| 43 | return true; | |
| 44 | } | |
| 45 | ||
| 46 | /** | |
| 47 | * The repository checked out at `<workspace>/<name>`, once. A repository | |
| 48 | * with no commits yet is cloned empty. Returns the directory when it is there. | |
| 49 | */ | |
| 50 | export async function ensureCheckout(app: App, repo: Repo, workspace: string): Promise<string | undefined> { | |
| 51 | const target = join(workspace, repo.name); | |
| 52 | if (existsSync(join(target, ".git"))) return target; | |
| 53 | const source = repoDir(app.reposRoot, repo.ownerName, repo.name); | |
| 54 | const ok = await clone(source, target, `${app.config.url}/${repo.ownerName}/${repo.name}.git`); | |
| 55 | if (!ok) rmSync(target, { recursive: true, force: true }); | |
| 56 | return ok ? target : undefined; | |
| 57 | } | |
| 58 | ||
| 59 | /** The person's dotfiles repository cloned into `<home>/.dotfiles`, if they named one they may read. */ | |
| 60 | export async function ensureDotfiles(app: App, user: User, home: string): Promise<boolean> { | |
| 61 | const named = parseDotfilesRepo(getUserSetting(app.db, user.id, DOTFILES_KEY) ?? ""); | |
| 62 | if (named === undefined) return false; | |
| 63 | const repo = getRepo(app.db, named.owner, named.name); | |
| 64 | if (repo === undefined || !canRead(app.db, repo, user)) return false; | |
| 65 | const target = join(home, ".dotfiles"); | |
| 66 | if (!existsSync(join(target, ".git"))) { | |
| 67 | const ok = await clone( | |
| 68 | repoDir(app.reposRoot, repo.ownerName, repo.name), | |
| 69 | target, | |
| 70 | `${app.config.url}/${repo.ownerName}/${repo.name}.git`, | |
| 71 | ); | |
| 72 | if (!ok) { | |
| 73 | rmSync(target, { recursive: true, force: true }); | |
| 74 | return false; | |
| 75 | } | |
| 76 | } | |
| 77 | for (const file of LINKED) { | |
| 78 | if (existsSync(join(target, file)) && !existsSync(join(home, file))) { | |
| 79 | try { | |
| 80 | symlinkSync(join(target, file), join(home, file)); | |
| 81 | } catch { | |
| 82 | /* a dotfile that cannot be linked is not worth a shell */ | |
| 83 | } | |
| 84 | } | |
| 85 | } | |
| 86 | return true; | |
| 87 | } | |
| 88 | ||
| 89 | /** The app's own `tty` command from the checkout's forge.json, if it declares one. */ | |
| 90 | export async function appTtyCommand(app: App, repo: Repo): Promise<string | undefined> { | |
| 91 | const text = await readFileAt(repoDir(app.reposRoot, repo.ownerName, repo.name), repo.defaultBranch, "forge.json"); | |
| 92 | const manifest = parseManifest(text, undefined); | |
| 93 | return manifest.ok ? (manifest.value.tty ?? undefined) : undefined; | |
| 94 | } | |
| 95 | ||
| 96 | export interface Greeting { | |
| 97 | readonly machine: string; | |
| 98 | readonly repo: string; | |
| 99 | readonly idleMinutes: number; | |
| 100 | readonly resumed: boolean; | |
| 101 | readonly dotfiles: boolean; | |
| 102 | } | |
| 103 | ||
| 104 | /** The one line a session opens with: what it is, how to leave. */ | |
| 105 | export function greetingLine(g: Greeting): string { | |
| 106 | const what = `${g.resumed ? "resumed " : ""}shell on ${g.machine} · ${g.repo}`; | |
| 107 | return `forge · ${what} — close the tab to detach (it stays, and stops after ${g.idleMinutes} min idle); "exit" ends it · /settings/terminals`; | |
| 108 | } | |
| 109 | ||
| 110 | /** The profile every shell sources: managed by the forge, rewritten at each session. */ | |
| 111 | export function profileText(): string { | |
| 112 | return `# Managed by the forge: rewritten at every session. Your own lines go in ~/.bashrc. | |
| 113 | umask 022 | |
| 114 | export EDITOR="\${EDITOR:-vi}" PAGER="\${PAGER:-less}" LESS="\${LESS:--R}" | |
| 115 | export PATH="$HOME/.bun/bin:$HOME/bin:$PATH" | |
| 116 | export HISTFILE="$HOME/.forge/history" HISTSIZE=10000 HISTFILESIZE=20000 HISTCONTROL=ignoredups | |
| 117 | alias ll='ls -la' la='ls -A' gs='git status -sb' gl='git log --oneline -n 20' | |
| 118 | [ -n "$FORGE_REPO_DIR" ] && [ -d "$FORGE_REPO_DIR/node_modules/.bin" ] && export PATH="$FORGE_REPO_DIR/node_modules/.bin:$PATH" | |
| 119 | [ -n "$FORGE_APP_TTY_COMMAND" ] && alias app-tty="$FORGE_APP_TTY_COMMAND" | |
| 120 | if [ -n "$BASH_VERSION" ]; then | |
| 121 | shopt -s histappend checkwinsize cdspell 2>/dev/null | |
| 122 | __forge_branch() { local b; b=$(git symbolic-ref --short -q HEAD 2>/dev/null) && printf ' (%s)' "$b"; } | |
| 123 | PROMPT_COMMAND='history -a; pwd > "$HOME/.forge/cwd"' | |
| 124 | PS1='\\[\\e[1m\\]$FORGE_REPO\\[\\e[0m\\]\\[\\e[36m\\]$(__forge_branch)\\[\\e[0m\\] \\w \\$ ' | |
| 125 | else | |
| 126 | PS1="$FORGE_REPO \\$ " | |
| 127 | fi | |
| 128 | if [ -f "$HOME/.dotfiles/forge.sh" ]; then . "$HOME/.dotfiles/forge.sh" | |
| 129 | elif [ -f "$HOME/.dotfiles/.bashrc" ] && [ -n "$BASH_VERSION" ]; then . "$HOME/.dotfiles/.bashrc"; fi | |
| 130 | [ -f "$HOME/.bashrc.local" ] && . "$HOME/.bashrc.local" | |
| 131 | if [ -f "$HOME/.forge/greeting" ]; then cat "$HOME/.forge/greeting"; rm -f "$HOME/.forge/greeting"; fi | |
| 132 | `; | |
| 133 | } | |
| 134 | ||
| 135 | /** | |
| 136 | * Lay the shell's home: the managed profile, the rc files that source it | |
| 137 | * (made once, then the person's), and this session's greeting. | |
| 138 | */ | |
| 139 | export function writeHome(home: string, greeting: Greeting): void { | |
| 140 | const state = join(home, ".forge"); | |
| 141 | mkdirSync(state, { recursive: true }); | |
| 142 | writeFileSync(join(state, "profile.sh"), profileText()); | |
| 143 | writeFileSync(join(state, "greeting"), `${greetingLine(greeting)}\n`); | |
| 144 | const source = '[ -f "$HOME/.forge/profile.sh" ] && . "$HOME/.forge/profile.sh"\n'; | |
| 145 | for (const [file, text] of [ | |
| 146 | [".bashrc", source], | |
| 147 | [".bash_profile", '[ -f "$HOME/.bashrc" ] && . "$HOME/.bashrc"\n'], | |
| 148 | [".profile", source], | |
| 149 | ] as const) { | |
| 150 | if (!existsSync(join(home, file))) writeFileSync(join(home, file), text); | |
| 151 | } | |
| 152 | } | |
| 153 | ||
| 154 | export interface Prepared { | |
| 155 | /** Where the shell starts. */ | |
| 156 | readonly cwd: string; | |
| 157 | readonly env: Record<string, string>; | |
| 158 | } | |
| 159 | ||
| 160 | /** The checkout, the dotfiles and the home, ready before the first keystroke. */ | |
| 161 | export async function prepareEnvironment( | |
| 162 | app: App, | |
| 163 | repo: Repo, | |
| 164 | user: User, | |
| 165 | workspace: string, | |
| 166 | machine: string, | |
| 167 | extra: { idleMinutes: number; resumed: boolean }, | |
| 168 | ): Promise<Prepared> { | |
| 169 | const home = join(workspace, "home"); | |
| 170 | const [checkout, dotfiles, tty] = await Promise.all([ | |
| 171 | ensureCheckout(app, repo, workspace), | |
| 172 | ensureDotfiles(app, user, home), | |
| 173 | appTtyCommand(app, repo), | |
| 174 | ]); | |
| 175 | writeHome(home, { | |
| 176 | machine, | |
| 177 | repo: `${repo.ownerName}/${repo.name}`, | |
| 178 | idleMinutes: extra.idleMinutes, | |
| 179 | resumed: extra.resumed, | |
| 180 | dotfiles, | |
| 181 | }); | |
| 182 | const env: Record<string, string> = { | |
| 183 | FORGE_REPO: `${repo.ownerName}/${repo.name}`, | |
| 184 | ENV: join(home, ".forge", "profile.sh"), | |
| 185 | ...(checkout === undefined ? {} : { FORGE_REPO_DIR: checkout }), | |
| 186 | ...(tty === undefined ? {} : { FORGE_APP_TTY_COMMAND: tty }), | |
| 187 | }; | |
| 188 | const shell = Bun.which("bash"); | |
| 189 | if (shell !== null) env["SHELL"] = shell; | |
| 190 | return { cwd: checkout ?? workspace, env }; | |
| 191 | } |
src/machines/idle.ts added +38
| @@ -0,0 +1,38 @@ | ||
| 1 | /** | |
| 2 | * When a terminal has been left: the one knob and the one rule. A session | |
| 3 | * with no input, no output and no work (CPU in its process tree) for the | |
| 4 | * idle time is stopped; one that is running a build or a test is not idle. | |
| 5 | */ | |
| 6 | ||
| 7 | /** Minutes, `FORGE_TERMINAL_IDLE_MINUTES`; the default for every terminal on the forge. */ | |
| 8 | export const DEFAULT_IDLE_MINUTES = 30; | |
| 9 | ||
| 10 | export function terminalIdleMs(env: Record<string, string | undefined> = process.env): number { | |
| 11 | const raw = env["FORGE_TERMINAL_IDLE_MINUTES"]; | |
| 12 | const minutes = raw === undefined || raw.trim() === "" ? NaN : Number(raw); | |
| 13 | const bounded = Number.isFinite(minutes) && minutes >= 1 && minutes <= 24 * 60 ? minutes : DEFAULT_IDLE_MINUTES; | |
| 14 | return Math.round(bounded * 60_000); | |
| 15 | } | |
| 16 | ||
| 17 | export interface Activity { | |
| 18 | readonly lastInput: number; | |
| 19 | readonly lastOutput: number; | |
| 20 | readonly lastBusy: number; | |
| 21 | } | |
| 22 | ||
| 23 | /** The last moment anything happened. */ | |
| 24 | export function lastActive(a: Activity): number { | |
| 25 | return Math.max(a.lastInput, a.lastOutput, a.lastBusy); | |
| 26 | } | |
| 27 | ||
| 28 | export function isIdle(a: Activity, now: number, idleMs: number): boolean { | |
| 29 | return now - lastActive(a) >= idleMs; | |
| 30 | } | |
| 31 | ||
| 32 | /** How long until `at`, in words: "47 min", "1 h 12 min", "under a minute". */ | |
| 33 | export function untilWords(at: number, now: number): string { | |
| 34 | const minutes = Math.ceil(Math.max(0, at - now) / 60_000); | |
| 35 | if (minutes <= 1) return "under a minute"; | |
| 36 | if (minutes < 60) return `${minutes} min`; | |
| 37 | return `${Math.floor(minutes / 60)} h ${String(minutes % 60).padStart(2, "0")} min`; | |
| 38 | } |
src/machines/shell.ts +185 −28
| @@ -13,8 +13,13 @@ | ||
| 13 | 13 | * second tab, a reload) joins the session that is running and sees the same |
| 14 | 14 | * screen. Binary frames are keystrokes in and screen bytes out; a text frame |
| 15 | 15 | * is JSON and says only `{"type":"resize","cols":n,"rows":n}`. The session |
| 16 | * ends when its program exits or after `idleMs` with no keystroke, and each | |
| 17 | * one is a row in `machine_sessions`: machine, owner, start, end and why. | |
| 16 | * ends when its program exits or after `idleMs` with no input, no output and | |
| 17 | * no work in its process tree (a build is not idle), and each one is a row in | |
| 18 | * `machine_sessions`: machine, owner, start, end and why. Closing the tab only | |
| 19 | * detaches. A session that stops idle, or is stopped by its owner | |
| 20 | * (`machines/terminals.ts`), keeps its scrollback and working directory | |
| 21 | * (`machines/snapshot.ts`), and opening the shell again resumes it. It opens | |
| 22 | * in an environment made for it (`machines/environment.ts`). | |
| 18 | 23 | * |
| 19 | 24 | * No text a person sends ever reaches a command line: the command is a |
| 20 | 25 | * constant, and the names in the path only pick a row and a directory after |
| @@ -37,6 +42,9 @@ import { repoMachines } from "../crew/machines_read.ts"; | ||
| 37 | 42 | import { reachableApps, type Machine } from "../crew/machines.ts"; |
| 38 | 43 | import { ownApp, ownAppUrls } from "../crew/app_hosts.ts"; |
| 39 | 44 | import { id as newId } from "../kernel/id.ts"; |
| 45 | import { prepareEnvironment } from "./environment.ts"; | |
| 46 | import { Scrollback, clearSnapshot, loadSnapshot, saveSnapshot, savedCwd } from "./snapshot.ts"; | |
| 47 | import { observe, registerTerminal, type LiveTerminal, shouldStopIdle, unregisterTerminal, type StopReason } from "./terminals.ts"; | |
| 40 | 48 | |
| 41 | 49 | // ---- the route ---- |
| 42 | 50 | |
| @@ -217,7 +225,7 @@ export function lastSessions(db: Database, repoId: string, limit = 20): SessionR | ||
| 217 | 225 | export const ENDED: Record<EndReason, string> = { |
| 218 | 226 | exit: "the shell exited", |
| 219 | 227 | idle: "idle too long", |
| 220 | stopped: "the forge stopped", | |
| 228 | stopped: "stopped", | |
| 221 | 229 | revoked: "its owner could no longer write here", |
| 222 | 230 | failed: "the shell could not start", |
| 223 | 231 | }; |
| @@ -231,6 +239,8 @@ export interface ShellSocket { | ||
| 231 | 239 | release?: () => void; |
| 232 | 240 | /** This connection has sent a size; its first one redraws a joined screen (`resizePlan`). */ |
| 233 | 241 | sized?: boolean; |
| 242 | /** Frames that arrived while the environment was being made, replayed once the session is joined. */ | |
| 243 | queue?: (string | Buffer)[]; | |
| 234 | 244 | } |
| 235 | 245 | |
| 236 | 246 | type Peer = Bun.ServerWebSocket<ShellSocket>; |
| @@ -245,7 +255,14 @@ interface Session { | ||
| 245 | 255 | readonly peers: Set<Peer>; |
| 246 | 256 | /** The pty's size, as last set. */ |
| 247 | 257 | size: PtySize; |
| 248 | lastInput: number; | |
| 258 | readonly activity: { lastInput: number; lastOutput: number; lastBusy: number }; | |
| 259 | readonly scrollback: Scrollback; | |
| 260 | readonly dir: string; | |
| 261 | readonly startedAt: number; | |
| 262 | /** Screen bytes of the stopped session this one resumes, sent to the first connection. */ | |
| 263 | replay: Uint8Array | undefined; | |
| 264 | /** Since when nobody is connected. */ | |
| 265 | detachedAt: number | undefined; | |
| 249 | 266 | ended: boolean; |
| 250 | 267 | readonly timer: ReturnType<typeof setInterval>; |
| 251 | 268 | } |
| @@ -304,9 +321,21 @@ function sessionsOf(app: App): Map<string, Session> { | ||
| 304 | 321 | return map; |
| 305 | 322 | } |
| 306 | 323 | |
| 307 | /** The sessions running now. */ | |
| 324 | /** Sessions whose environment is being made: held against the caps so a burst of tabs cannot pass them. */ | |
| 325 | const pending = new WeakMap<App, Map<string, string>>(); | |
| 326 | ||
| 327 | function pendingOf(app: App): Map<string, string> { | |
| 328 | let map = pending.get(app); | |
| 329 | if (map === undefined) pending.set(app, (map = new Map())); | |
| 330 | return map; | |
| 331 | } | |
| 332 | ||
| 333 | /** The sessions running now, and those being made. */ | |
| 308 | 334 | export function liveSessions(app: App): number { |
| 309 | return sessionsOf(app).size; | |
| 335 | const live = sessionsOf(app); | |
| 336 | let n = live.size; | |
| 337 | for (const key of pendingOf(app).keys()) if (!live.has(key)) n++; | |
| 338 | return n; | |
| 310 | 339 | } |
| 311 | 340 | |
| 312 | 341 | const keyOf = (g: ShellGrant): string => `${g.repo.id}\0${g.machine.name}\0${g.user.id}`; |
| @@ -323,10 +352,12 @@ function roomFor(app: App, grant: ShellGrant, now = Date.now()): boolean { | ||
| 323 | 352 | recent.push(now); |
| 324 | 353 | byUser.set(grant.user.id, recent); |
| 325 | 354 | const live = sessionsOf(app); |
| 326 | if (live.has(keyOf(grant))) return true; | |
| 327 | if (live.size >= MAX_SESSIONS.forge) return false; | |
| 355 | const making = pendingOf(app); | |
| 356 | if (live.has(keyOf(grant)) || making.has(keyOf(grant))) return true; | |
| 357 | if (liveSessions(app) >= MAX_SESSIONS.forge) return false; | |
| 328 | 358 | let mine = 0; |
| 329 | 359 | for (const s of live.values()) if (s.userId === grant.user.id) mine++; |
| 360 | for (const [key, userId] of making) if (!live.has(key) && userId === grant.user.id) mine++; | |
| 330 | 361 | return mine < MAX_SESSIONS.person; |
| 331 | 362 | } |
| 332 | 363 | |
| @@ -382,7 +413,20 @@ function end(app: App, session: Session, reason: EndReason): void { | ||
| 382 | 413 | session.ended = true; |
| 383 | 414 | clearInterval(session.timer); |
| 384 | 415 | sessionsOf(app).delete(session.key); |
| 416 | unregisterTerminal(app, session.row); | |
| 385 | 417 | recordEnd(app.db, session.row, reason); |
| 418 | // A session that is stopped, not one that finished, can be resumed. | |
| 419 | if (reason === "idle" || reason === "stopped") { | |
| 420 | try { | |
| 421 | saveSnapshot(session.dir, session.scrollback.bytes(), { | |
| 422 | startedAt: new Date(session.startedAt).toISOString(), | |
| 423 | stoppedAt: new Date().toISOString(), | |
| 424 | reason, | |
| 425 | }); | |
| 426 | } catch (error) { | |
| 427 | app.log.warn("machine shell snapshot failed", { error: String(error) }); | |
| 428 | } | |
| 429 | } | |
| 386 | 430 | if (reason !== "exit") session.program.hangup(); |
| 387 | 431 | for (const peer of session.peers) if (peer.readyState === WebSocket.OPEN) peer.close(1000, ENDED[reason]); |
| 388 | 432 | session.peers.clear(); |
| @@ -395,9 +439,24 @@ function stillMay(app: App, session: Session): boolean { | ||
| 395 | 439 | return user !== undefined && repo !== undefined && isActive(user) && canWrite(app.db, repo, user); |
| 396 | 440 | } |
| 397 | 441 | |
| 398 | function start(app: App, grant: ShellGrant, opts: ShellOptions, cols: number, rows: number): Session | undefined { | |
| 442 | /** Where a shell begins: the checkout (or a resumed session's last directory), by a constant command and a checked variable. */ | |
| 443 | const ENTER = 'cd "${FORGE_START_DIR:-.}" 2>/dev/null; '; | |
| 444 | ||
| 445 | function start( | |
| 446 | app: App, | |
| 447 | grant: ShellGrant, | |
| 448 | opts: ShellOptions, | |
| 449 | cols: number, | |
| 450 | rows: number, | |
| 451 | prepared: { cwd: string; env: Record<string, string> }, | |
| 452 | resumed: Uint8Array | undefined, | |
| 453 | ): Session | undefined { | |
| 399 | 454 | const dir = workspace(app, grant.repo, grant.machine, grant.user.id); |
| 400 | 455 | const peers = new Set<Peer>(); |
| 456 | const scrollback = new Scrollback(); | |
| 457 | if (resumed !== undefined) scrollback.push(resumed); | |
| 458 | const startedAt = Date.now(); | |
| 459 | const activity = { lastInput: startedAt, lastOutput: startedAt, lastBusy: startedAt }; | |
| 401 | 460 | let terminal: Bun.Terminal | undefined; |
| 402 | 461 | let cell: Cell | undefined; |
| 403 | 462 | let row: string | undefined; |
| @@ -408,6 +467,8 @@ function start(app: App, grant: ShellGrant, opts: ShellOptions, cols: number, ro | ||
| 408 | 467 | cols, |
| 409 | 468 | rows, |
| 410 | 469 | data: (_t, chunk) => { |
| 470 | activity.lastOutput = Date.now(); | |
| 471 | scrollback.push(chunk); | |
| 411 | 472 | for (const peer of peers) { |
| 412 | 473 | if (peer.readyState !== WebSocket.OPEN) continue; |
| 413 | 474 | // A peer that is not reading is closed, never buffered without end. |
| @@ -434,28 +495,54 @@ function start(app: App, grant: ShellGrant, opts: ShellOptions, cols: number, ro | ||
| 434 | 495 | LANG: "C.UTF-8", |
| 435 | 496 | FORGE_MACHINE: grant.machine.name, |
| 436 | 497 | FORGE_MACHINE_TOOLS: grant.machine.tools.join(" "), |
| 498 | FORGE_START_DIR: prepared.cwd, | |
| 499 | ...prepared.env, | |
| 437 | 500 | }; |
| 438 | const program = startTerminal(opts.command, { terminal, env, cwd: dir, cell }); | |
| 501 | const program = startTerminal(`${ENTER}${opts.command}`, { terminal, env, cwd: dir, cell }); | |
| 439 | 502 | const term = terminal; |
| 503 | const rowId = row; | |
| 440 | 504 | const session: Session = { |
| 441 | 505 | key: keyOf(grant), |
| 442 | 506 | userId: grant.user.id, |
| 443 | 507 | repoId: grant.repo.id, |
| 444 | row, | |
| 508 | row: rowId, | |
| 445 | 509 | terminal: term, |
| 446 | 510 | program, |
| 447 | 511 | peers, |
| 448 | 512 | size: { cols, rows }, |
| 449 | lastInput: Date.now(), | |
| 513 | activity, | |
| 514 | scrollback, | |
| 515 | dir, | |
| 516 | startedAt, | |
| 517 | replay: resumed, | |
| 518 | detachedAt: undefined, | |
| 450 | 519 | ended: false, |
| 451 | 520 | timer: setInterval( |
| 452 | 521 | () => { |
| 453 | if (Date.now() - session.lastInput >= opts.idleMs) end(app, session, "idle"); | |
| 522 | observe(tracked); | |
| 523 | if (shouldStopIdle(tracked)) end(app, session, "idle"); | |
| 454 | 524 | else if (!stillMay(app, session)) end(app, session, "revoked"); |
| 455 | 525 | }, |
| 456 | 526 | Math.max(10, Math.min(opts.idleMs, opts.checkMs ?? CHECK_MS)), |
| 457 | 527 | ), |
| 458 | 528 | }; |
| 529 | const tracked: LiveTerminal = { | |
| 530 | id: rowId, | |
| 531 | kind: "machine", | |
| 532 | userId: grant.user.id, | |
| 533 | what: `Shell on ${grant.machine.name}`, | |
| 534 | where: `${grant.repo.ownerName}/${grant.repo.name}`, | |
| 535 | href: shellPathOf(grant.repo, grant.machine.name), | |
| 536 | pid: program.pid, | |
| 537 | startedAt, | |
| 538 | idleMs: opts.idleMs, | |
| 539 | activity, | |
| 540 | attached: () => session.peers.size, | |
| 541 | detachedAt: () => session.detachedAt, | |
| 542 | resumable: true, | |
| 543 | stop: (reason: StopReason) => end(app, session, reason === "idle" ? "idle" : "stopped"), | |
| 544 | }; | |
| 545 | registerTerminal(app, tracked); | |
| 459 | 546 | void program.exited.then(() => { |
| 460 | 547 | term.close(); |
| 461 | 548 | end(app, session, "exit"); |
| @@ -481,6 +568,8 @@ function start(app: App, grant: ShellGrant, opts: ShellOptions, cols: number, ro | ||
| 481 | 568 | } |
| 482 | 569 | } |
| 483 | 570 | |
| 571 | const shellPathOf = (repo: Repo, machine: string): string => `/${repo.ownerName}/${repo.name}/machines/${machine}/shell`; | |
| 572 | ||
| 484 | 573 | /** End every session (the forge is stopping). */ |
| 485 | 574 | export function stopShells(app: App): void { |
| 486 | 575 | for (const session of [...sessionsOf(app).values()]) end(app, session, "stopped"); |
| @@ -491,28 +580,93 @@ export function isShellSocket(data: unknown): data is ShellSocket { | ||
| 491 | 580 | return typeof data === "object" && data !== null && "shell" in data; |
| 492 | 581 | } |
| 493 | 582 | |
| 583 | /** Frames held for a connection whose session is still being made: a resize and a few keystrokes, no more. */ | |
| 584 | const MAX_QUEUED_FRAMES = 32; | |
| 585 | ||
| 586 | function join_(ws: Peer, session: Session): void { | |
| 587 | const { app, user, sessionId } = ws.data.shell; | |
| 588 | session.peers.add(ws); | |
| 589 | session.detachedAt = undefined; | |
| 590 | ws.data.joined = session; | |
| 591 | ws.data.release = holdOpen(app.db, user.id, sessionId, () => { | |
| 592 | if (ws.readyState === WebSocket.OPEN) ws.close(1008, "this account was suspended"); | |
| 593 | }); | |
| 594 | // A resumed session shows what the stopped one had on its screen, once. | |
| 595 | if (session.replay !== undefined) { | |
| 596 | ws.sendBinary(session.replay); | |
| 597 | ws.sendBinary(new TextEncoder().encode("\r\n\x1b[2m— resumed: the scrollback above is from the session that stopped —\x1b[0m\r\n")); | |
| 598 | session.replay = undefined; | |
| 599 | } | |
| 600 | for (const frame of ws.data.queue ?? []) shellWebSocket.message(ws, frame); | |
| 601 | delete ws.data.queue; | |
| 602 | } | |
| 603 | ||
| 604 | /** Make the environment, start the session (or join the one a second tab started meanwhile) and join it. */ | |
| 605 | async function begin(ws: Peer, opts: ShellOptions): Promise<void> { | |
| 606 | const { app, repo, machine, user } = ws.data.shell; | |
| 607 | const dir = workspace(app, repo, machine, user.id); | |
| 608 | const snapshot = loadSnapshot(dir); | |
| 609 | let prepared: { cwd: string; env: Record<string, string> }; | |
| 610 | try { | |
| 611 | mkdirSync(join(dir, "home"), { recursive: true }); | |
| 612 | prepared = await prepareEnvironment(app, repo, user, dir, machine.name, { | |
| 613 | idleMinutes: Math.round(opts.idleMs / 60_000), | |
| 614 | resumed: snapshot !== undefined, | |
| 615 | }); | |
| 616 | } catch (error) { | |
| 617 | app.log.warn("machine shell environment failed", { machine: machine.name, error: String(error) }); | |
| 618 | if (ws.readyState === WebSocket.OPEN) ws.close(1011, ENDED.failed); | |
| 619 | return; | |
| 620 | } | |
| 621 | // The tab closed while the checkout was made: nothing to start for. | |
| 622 | if (ws.readyState !== WebSocket.OPEN) return; | |
| 623 | const key = keyOf(ws.data.shell); | |
| 624 | let session = sessionsOf(app).get(key); | |
| 625 | if (session === undefined) { | |
| 626 | const back = snapshot === undefined ? undefined : savedCwd(dir); | |
| 627 | if (snapshot !== undefined) clearSnapshot(dir); | |
| 628 | session = start( | |
| 629 | app, | |
| 630 | ws.data.shell, | |
| 631 | opts, | |
| 632 | 80, | |
| 633 | 24, | |
| 634 | back === undefined ? prepared : { ...prepared, cwd: back }, | |
| 635 | snapshot?.scrollback, | |
| 636 | ); | |
| 637 | } | |
| 638 | if (session === undefined) { | |
| 639 | ws.close(1011, ENDED.failed); | |
| 640 | return; | |
| 641 | } | |
| 642 | join_(ws, session); | |
| 643 | } | |
| 644 | ||
| 494 | 645 | export const shellWebSocket = { |
| 495 | 646 | open(ws: Peer): void { |
| 496 | const { app, user, sessionId } = ws.data.shell; | |
| 647 | const { app } = ws.data.shell; | |
| 497 | 648 | const opts = options.get(app); |
| 498 | 649 | if (opts === undefined || opts.contain === "refuse") { |
| 499 | 650 | ws.close(1011, "this forge cannot hold a machine's shell"); |
| 500 | 651 | return; |
| 501 | 652 | } |
| 502 | const session = sessionsOf(app).get(keyOf(ws.data.shell)) ?? start(app, ws.data.shell, opts, 80, 24); | |
| 503 | if (session === undefined) { | |
| 504 | ws.close(1011, ENDED.failed); | |
| 653 | const running = sessionsOf(app).get(keyOf(ws.data.shell)); | |
| 654 | if (running !== undefined) { | |
| 655 | join_(ws, running); | |
| 505 | 656 | return; |
| 506 | 657 | } |
| 507 | session.peers.add(ws); | |
| 508 | ws.data.joined = session; | |
| 509 | ws.data.release = holdOpen(app.db, user.id, sessionId, () => { | |
| 510 | if (ws.readyState === WebSocket.OPEN) ws.close(1008, "this account was suspended"); | |
| 511 | }); | |
| 658 | ws.data.queue = []; | |
| 659 | const key = keyOf(ws.data.shell); | |
| 660 | pendingOf(app).set(key, ws.data.shell.user.id); | |
| 661 | void begin(ws, opts).finally(() => pendingOf(app).delete(key)); | |
| 512 | 662 | }, |
| 513 | 663 | message(ws: Peer, message: string | Buffer): void { |
| 514 | 664 | const session = ws.data.joined; |
| 515 | if (session === undefined || session.ended) return; | |
| 665 | if (session === undefined) { | |
| 666 | if (ws.data.queue !== undefined && ws.data.queue.length < MAX_QUEUED_FRAMES) ws.data.queue.push(message); | |
| 667 | return; | |
| 668 | } | |
| 669 | if (session.ended) return; | |
| 516 | 670 | if (typeof message === "string") { |
| 517 | 671 | const resize = parseControl(message); |
| 518 | 672 | if (resize === undefined) { |
| @@ -535,7 +689,7 @@ export const shellWebSocket = { | ||
| 535 | 689 | ws.close(1009, "a keystroke frame is at most 64 KiB"); |
| 536 | 690 | return; |
| 537 | 691 | } |
| 538 | session.lastInput = Date.now(); | |
| 692 | session.activity.lastInput = Date.now(); | |
| 539 | 693 | if (session.terminal.closed) return; |
| 540 | 694 | try { |
| 541 | 695 | session.terminal.write(message); |
| @@ -548,10 +702,13 @@ export const shellWebSocket = { | ||
| 548 | 702 | const session = ws.data.joined; |
| 549 | 703 | if (session === undefined) return; |
| 550 | 704 | session.peers.delete(ws); |
| 551 | // The session stays for the next connection until it is idle or exits — | |
| 552 | // unless its owner was suspended or may no longer write here. | |
| 553 | if (session.peers.size === 0 && !stillMay(ws.data.shell.app, session)) | |
| 554 | end(ws.data.shell.app, session, "revoked"); | |
| 705 | // Closing the tab detaches: the session stays for the next connection | |
| 706 | // until it is idle or exits — unless its owner was suspended or may no | |
| 707 | // longer write here. | |
| 708 | if (session.peers.size === 0) { | |
| 709 | session.detachedAt = Date.now(); | |
| 710 | if (!stillMay(ws.data.shell.app, session)) end(ws.data.shell.app, session, "revoked"); | |
| 711 | } | |
| 555 | 712 | }, |
| 556 | 713 | }; |
| 557 | 714 |
src/machines/snapshot.ts added +131
| @@ -0,0 +1,131 @@ | ||
| 1 | /** | |
| 2 | * What a stopped shell leaves so Resume can bring it back: the tail of its | |
| 3 | * screen bytes (its scrollback) and a small record of when it started and | |
| 4 | * why it stopped. The working directory is kept by the shell itself, which | |
| 5 | * writes it at every prompt (`machines/environment.ts`). All of it lives in | |
| 6 | * the person's own workspace, `<workspace>/home/.forge/`, so it follows the | |
| 7 | * same directory the shell does and nothing else. | |
| 8 | */ | |
| 9 | ||
| 10 | import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; | |
| 11 | import { join } from "node:path"; | |
| 12 | ||
| 13 | /** The most screen bytes a session remembers: a few thousand lines. */ | |
| 14 | export const MAX_SCROLLBACK_BYTES = 256 * 1024; | |
| 15 | ||
| 16 | /** The tail of what a terminal drew, bounded. */ | |
| 17 | export class Scrollback { | |
| 18 | private chunks: Uint8Array[] = []; | |
| 19 | private size = 0; | |
| 20 | ||
| 21 | push(chunk: Uint8Array): void { | |
| 22 | this.chunks.push(chunk.slice()); | |
| 23 | this.size += chunk.byteLength; | |
| 24 | while (this.size > MAX_SCROLLBACK_BYTES && this.chunks.length > 1) this.size -= this.chunks.shift()!.byteLength; | |
| 25 | } | |
| 26 | ||
| 27 | bytes(): Uint8Array { | |
| 28 | const out = new Uint8Array(this.size); | |
| 29 | let at = 0; | |
| 30 | for (const c of this.chunks) { | |
| 31 | out.set(c, at); | |
| 32 | at += c.byteLength; | |
| 33 | } | |
| 34 | // A cut inside a line starts at the next whole one. | |
| 35 | if (out.byteLength > MAX_SCROLLBACK_BYTES) { | |
| 36 | const tail = out.subarray(out.byteLength - MAX_SCROLLBACK_BYTES); | |
| 37 | const nl = tail.indexOf(10); | |
| 38 | return nl < 0 ? tail : tail.subarray(nl + 1); | |
| 39 | } | |
| 40 | return out; | |
| 41 | } | |
| 42 | } | |
| 43 | ||
| 44 | export interface SnapshotMeta { | |
| 45 | readonly startedAt: string; | |
| 46 | readonly stoppedAt: string; | |
| 47 | readonly reason: "idle" | "stopped"; | |
| 48 | } | |
| 49 | ||
| 50 | const dirOf = (workspace: string): string => join(workspace, "home", ".forge"); | |
| 51 | ||
| 52 | export function saveSnapshot(workspace: string, scrollback: Uint8Array, meta: SnapshotMeta): void { | |
| 53 | const dir = dirOf(workspace); | |
| 54 | mkdirSync(dir, { recursive: true }); | |
| 55 | writeFileSync(join(dir, "scrollback"), scrollback); | |
| 56 | writeFileSync(join(dir, "session.json"), JSON.stringify(meta)); | |
| 57 | } | |
| 58 | ||
| 59 | export function loadSnapshot(workspace: string): { scrollback: Uint8Array; meta: SnapshotMeta } | undefined { | |
| 60 | const dir = dirOf(workspace); | |
| 61 | try { | |
| 62 | const meta = JSON.parse(readFileSync(join(dir, "session.json"), "utf8")) as Partial<SnapshotMeta>; | |
| 63 | if (typeof meta.startedAt !== "string" || typeof meta.stoppedAt !== "string") return undefined; | |
| 64 | if (meta.reason !== "idle" && meta.reason !== "stopped") return undefined; | |
| 65 | const scrollback = new Uint8Array(readFileSync(join(dir, "scrollback"))); | |
| 66 | return { scrollback, meta: { startedAt: meta.startedAt, stoppedAt: meta.stoppedAt, reason: meta.reason } }; | |
| 67 | } catch { | |
| 68 | return undefined; | |
| 69 | } | |
| 70 | } | |
| 71 | ||
| 72 | /** A resumed session has used its snapshot; the next stop writes a new one. */ | |
| 73 | export function clearSnapshot(workspace: string): void { | |
| 74 | const dir = dirOf(workspace); | |
| 75 | rmSync(join(dir, "scrollback"), { force: true }); | |
| 76 | rmSync(join(dir, "session.json"), { force: true }); | |
| 77 | } | |
| 78 | ||
| 79 | /** | |
| 80 | * The directory the shell was last in, when it is still one inside the | |
| 81 | * workspace. The shell wrote it; it is checked like any other input. | |
| 82 | */ | |
| 83 | export function savedCwd(workspace: string): string | undefined { | |
| 84 | try { | |
| 85 | const text = readFileSync(join(dirOf(workspace), "cwd"), "utf8").replace(/\n$/, ""); | |
| 86 | // eslint-disable-next-line no-control-regex | |
| 87 | if (text === "" || /[\u0000-\u001f]/.test(text)) return undefined; | |
| 88 | if (text !== workspace && !text.startsWith(`${workspace}/`)) return undefined; | |
| 89 | if (text.split("/").includes("..")) return undefined; | |
| 90 | return statSync(text).isDirectory() ? text : undefined; | |
| 91 | } catch { | |
| 92 | return undefined; | |
| 93 | } | |
| 94 | } | |
| 95 | ||
| 96 | export interface Stopped { | |
| 97 | readonly repoId: string; | |
| 98 | readonly machine: string; | |
| 99 | readonly meta: SnapshotMeta; | |
| 100 | } | |
| 101 | ||
| 102 | /** | |
| 103 | * The shells of one person that stopped and can be resumed: a snapshot in | |
| 104 | * `<data>/machines/<repo>/<machine>/<user>`. Directory names, not a table: | |
| 105 | * the files are the state, and the list is derived from them. | |
| 106 | */ | |
| 107 | export function stoppedShells(dataDir: string, userId: string): Stopped[] { | |
| 108 | const root = join(dataDir, "machines"); | |
| 109 | const out: Stopped[] = []; | |
| 110 | let repos: string[] = []; | |
| 111 | try { | |
| 112 | repos = readdirSync(root); | |
| 113 | } catch { | |
| 114 | return out; | |
| 115 | } | |
| 116 | for (const repoId of repos) { | |
| 117 | let machines: string[] = []; | |
| 118 | try { | |
| 119 | machines = readdirSync(join(root, repoId)); | |
| 120 | } catch { | |
| 121 | continue; | |
| 122 | } | |
| 123 | for (const machine of machines) { | |
| 124 | const workspace = join(root, repoId, machine, userId); | |
| 125 | if (!existsSync(workspace)) continue; | |
| 126 | const snap = loadSnapshot(workspace); | |
| 127 | if (snap !== undefined) out.push({ repoId, machine, meta: snap.meta }); | |
| 128 | } | |
| 129 | } | |
| 130 | return out.sort((a, b) => b.meta.stoppedAt.localeCompare(a.meta.stoppedAt)); | |
| 131 | } |
src/machines/terminals.ts added +151
| @@ -0,0 +1,151 @@ | ||
| 1 | /** | |
| 2 | * One list of a person's terminals (#10457): the shells they hold on | |
| 3 | * machines and the app terminals they have open, each a line with what it is, | |
| 4 | * where, when it started, its last input and what its process tree uses now. | |
| 5 | * The owners of a terminal (`machines/shell.ts`, `apps/tty.ts`) register it | |
| 6 | * here and keep it current; this module only holds, samples and lists. State | |
| 7 | * in process memory is derived: a restarted forge has no terminals, and the | |
| 8 | * files of a stopped shell (`machines/snapshot.ts`) are what Resume reads. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { App } from "../app.ts"; | |
| 12 | import { BUSY_SHARE, cpuShare, treeUsage } from "./usage.ts"; | |
| 13 | import { isIdle, lastActive, type Activity } from "./idle.ts"; | |
| 14 | ||
| 15 | export type TerminalKind = "machine" | "app"; | |
| 16 | export type StopReason = "user" | "idle"; | |
| 17 | ||
| 18 | export interface LiveTerminal { | |
| 19 | readonly id: string; | |
| 20 | readonly kind: TerminalKind; | |
| 21 | readonly userId: string; | |
| 22 | /** "Shell on standard", "App terminal". */ | |
| 23 | readonly what: string; | |
| 24 | /** "alice/lab", "notes (production)". */ | |
| 25 | readonly where: string; | |
| 26 | /** The page that attaches to it. */ | |
| 27 | readonly href: string; | |
| 28 | readonly pid: number; | |
| 29 | readonly startedAt: number; | |
| 30 | readonly idleMs: number; | |
| 31 | /** Mutated by the owner as input and output happen. */ | |
| 32 | readonly activity: { lastInput: number; lastOutput: number; lastBusy: number }; | |
| 33 | /** Connections watching it now; 0 is detached. */ | |
| 34 | attached: () => number; | |
| 35 | /** Since when nobody watches it, if nobody does. */ | |
| 36 | readonly detachedAt: () => number | undefined; | |
| 37 | /** Whether it can be resumed after it stops. */ | |
| 38 | readonly resumable: boolean; | |
| 39 | readonly stop: (reason: StopReason) => void; | |
| 40 | last?: { ticks: number; at: number; share: number; rssBytes: number }; | |
| 41 | } | |
| 42 | ||
| 43 | const registry = new WeakMap<App, Map<string, LiveTerminal>>(); | |
| 44 | ||
| 45 | function mapOf(app: App): Map<string, LiveTerminal> { | |
| 46 | let map = registry.get(app); | |
| 47 | if (map === undefined) registry.set(app, (map = new Map())); | |
| 48 | return map; | |
| 49 | } | |
| 50 | ||
| 51 | export function registerTerminal(app: App, t: LiveTerminal): void { | |
| 52 | mapOf(app).set(t.id, t); | |
| 53 | } | |
| 54 | ||
| 55 | export function unregisterTerminal(app: App, id: string): void { | |
| 56 | mapOf(app).delete(id); | |
| 57 | } | |
| 58 | ||
| 59 | /** | |
| 60 | * Read the tree's use and, if it is working, count that as activity: a | |
| 61 | * build that prints nothing is not idle. Called by each terminal's own timer | |
| 62 | * and by the list. | |
| 63 | */ | |
| 64 | export function observe(t: LiveTerminal, now = Date.now(), procRoot = "/proc"): void { | |
| 65 | const usage = treeUsage(t.pid, procRoot); | |
| 66 | if (usage === undefined) return; | |
| 67 | const before = t.last; | |
| 68 | // A second look within a second (the page right after the timer) keeps the first: a share over milliseconds is noise. | |
| 69 | if (before !== undefined && now - before.at < 1_000) return; | |
| 70 | const share = before === undefined ? 0 : cpuShare(before.ticks, usage.cpuTicks, now - before.at); | |
| 71 | t.last = { ticks: usage.cpuTicks, at: now, share, rssBytes: usage.rssBytes }; | |
| 72 | if (share >= BUSY_SHARE) t.activity.lastBusy = now; | |
| 73 | } | |
| 74 | ||
| 75 | /** Whether the owner should stop it now for being idle. */ | |
| 76 | export function shouldStopIdle(t: LiveTerminal, now = Date.now()): boolean { | |
| 77 | return isIdle(t.activity as Activity, now, t.idleMs); | |
| 78 | } | |
| 79 | ||
| 80 | /** Nothing for this long, and not working, is "idle" for Stop all idle. */ | |
| 81 | export const QUIET_MS = 5 * 60_000; | |
| 82 | ||
| 83 | export interface TerminalView { | |
| 84 | readonly id: string; | |
| 85 | readonly kind: TerminalKind; | |
| 86 | readonly what: string; | |
| 87 | readonly where: string; | |
| 88 | readonly href: string; | |
| 89 | readonly startedAt: number; | |
| 90 | readonly lastInput: number; | |
| 91 | readonly cpuShare: number; | |
| 92 | readonly rssBytes: number; | |
| 93 | readonly attached: boolean; | |
| 94 | readonly detachedAt: number | undefined; | |
| 95 | /** When it stops of itself unless there is activity or someone comes back. */ | |
| 96 | readonly stopsAt: number; | |
| 97 | readonly quiet: boolean; | |
| 98 | readonly resumable: boolean; | |
| 99 | } | |
| 100 | ||
| 101 | /** A person's live terminals, newest first, with their use read now. */ | |
| 102 | export function terminalsOf(app: App, userId: string, now = Date.now()): TerminalView[] { | |
| 103 | const out: TerminalView[] = []; | |
| 104 | for (const t of mapOf(app).values()) { | |
| 105 | if (t.userId !== userId) continue; | |
| 106 | observe(t, now); | |
| 107 | out.push({ | |
| 108 | id: t.id, | |
| 109 | kind: t.kind, | |
| 110 | what: t.what, | |
| 111 | where: t.where, | |
| 112 | href: t.href, | |
| 113 | startedAt: t.startedAt, | |
| 114 | lastInput: t.activity.lastInput, | |
| 115 | cpuShare: t.last?.share ?? 0, | |
| 116 | rssBytes: t.last?.rssBytes ?? 0, | |
| 117 | attached: t.attached() > 0, | |
| 118 | detachedAt: t.detachedAt(), | |
| 119 | stopsAt: lastActive(t.activity) + t.idleMs, | |
| 120 | quiet: now - lastActive(t.activity) >= QUIET_MS, | |
| 121 | resumable: t.resumable, | |
| 122 | }); | |
| 123 | } | |
| 124 | return out.sort((a, b) => b.startedAt - a.startedAt); | |
| 125 | } | |
| 126 | ||
| 127 | /** Stop one of the person's terminals; false when they have no such one. */ | |
| 128 | export function stopTerminal(app: App, userId: string, id: string): boolean { | |
| 129 | const t = mapOf(app).get(id); | |
| 130 | if (t === undefined || t.userId !== userId) return false; | |
| 131 | t.stop("user"); | |
| 132 | return true; | |
| 133 | } | |
| 134 | ||
| 135 | /** Stop every terminal of the person's that is quiet and not working; how many. */ | |
| 136 | export function stopQuiet(app: App, userId: string, now = Date.now()): number { | |
| 137 | let stopped = 0; | |
| 138 | for (const t of [...mapOf(app).values()]) { | |
| 139 | if (t.userId !== userId) continue; | |
| 140 | observe(t, now); | |
| 141 | if (now - lastActive(t.activity) < QUIET_MS) continue; | |
| 142 | t.stop("user"); | |
| 143 | stopped++; | |
| 144 | } | |
| 145 | return stopped; | |
| 146 | } | |
| 147 | ||
| 148 | /** The terminals on the forge now. */ | |
| 149 | export function liveTerminals(app: App): number { | |
| 150 | return mapOf(app).size; | |
| 151 | } |
src/machines/usage.ts added +90
| @@ -0,0 +1,90 @@ | ||
| 1 | /** | |
| 2 | * What a terminal's process tree is using now, read from `/proc`: the CPU | |
| 3 | * ticks and resident memory of a root pid and everything under it. A cell's | |
| 4 | * tree hangs from its bubblewrap, so the root is the pid the pty's program | |
| 5 | * was started as. Plain data in, plain data out; the proc root is a | |
| 6 | * parameter so a test can lay one out in a directory. | |
| 7 | */ | |
| 8 | ||
| 9 | import { readdirSync, readFileSync } from "node:fs"; | |
| 10 | import { join } from "node:path"; | |
| 11 | ||
| 12 | export interface TreeUsage { | |
| 13 | /** utime + stime of every process in the tree, in clock ticks. */ | |
| 14 | readonly cpuTicks: number; | |
| 15 | readonly rssBytes: number; | |
| 16 | /** How many processes the tree holds. */ | |
| 17 | readonly processes: number; | |
| 18 | } | |
| 19 | ||
| 20 | /** Clock ticks per second (`_SC_CLK_TCK`): 100 on every Linux the forge runs on. */ | |
| 21 | export const CLOCK_TICKS = 100; | |
| 22 | const PAGE_BYTES = 4096; | |
| 23 | ||
| 24 | interface Stat { | |
| 25 | readonly ppid: number; | |
| 26 | readonly ticks: number; | |
| 27 | readonly rssPages: number; | |
| 28 | } | |
| 29 | ||
| 30 | /** The fields of one `/proc/<pid>/stat` line; the command name may hold spaces and parentheses. */ | |
| 31 | export function parseStat(line: string): Stat | undefined { | |
| 32 | const close = line.lastIndexOf(")"); | |
| 33 | if (close < 0) return undefined; | |
| 34 | const f = line.slice(close + 2).split(" "); | |
| 35 | // After the name: state(0) ppid(1) ... utime(11) stime(12) ... rss(21) | |
| 36 | const ppid = Number(f[1]); | |
| 37 | const utime = Number(f[11]); | |
| 38 | const stime = Number(f[12]); | |
| 39 | const rss = Number(f[21]); | |
| 40 | if (![ppid, utime, stime, rss].every(Number.isFinite)) return undefined; | |
| 41 | return { ppid, ticks: utime + stime, rssPages: rss }; | |
| 42 | } | |
| 43 | ||
| 44 | /** The tree under `root` (the root included), or undefined when the root is gone. */ | |
| 45 | export function treeUsage(root: number, procRoot = "/proc"): TreeUsage | undefined { | |
| 46 | const stats = new Map<number, Stat>(); | |
| 47 | let names: string[]; | |
| 48 | try { | |
| 49 | names = readdirSync(procRoot); | |
| 50 | } catch { | |
| 51 | return undefined; | |
| 52 | } | |
| 53 | for (const name of names) { | |
| 54 | if (!/^[1-9]\d*$/.test(name)) continue; | |
| 55 | try { | |
| 56 | const stat = parseStat(readFileSync(join(procRoot, name, "stat"), "utf8")); | |
| 57 | if (stat !== undefined) stats.set(Number(name), stat); | |
| 58 | } catch { | |
| 59 | /* it exited while we looked */ | |
| 60 | } | |
| 61 | } | |
| 62 | if (!stats.has(root)) return undefined; | |
| 63 | const children = new Map<number, number[]>(); | |
| 64 | for (const [pid, s] of stats) children.set(s.ppid, [...(children.get(s.ppid) ?? []), pid]); | |
| 65 | let cpuTicks = 0; | |
| 66 | let rssPages = 0; | |
| 67 | let processes = 0; | |
| 68 | const walk = [root]; | |
| 69 | const seen = new Set<number>(); | |
| 70 | for (let pid = walk.pop(); pid !== undefined; pid = walk.pop()) { | |
| 71 | if (seen.has(pid)) continue; | |
| 72 | seen.add(pid); | |
| 73 | const s = stats.get(pid); | |
| 74 | if (s === undefined) continue; | |
| 75 | cpuTicks += s.ticks; | |
| 76 | rssPages += s.rssPages; | |
| 77 | processes++; | |
| 78 | walk.push(...(children.get(pid) ?? [])); | |
| 79 | } | |
| 80 | return { cpuTicks, rssBytes: rssPages * PAGE_BYTES, processes }; | |
| 81 | } | |
| 82 | ||
| 83 | /** CPU as a share of one core between two samples `ms` apart, or 0 when they cannot be compared. */ | |
| 84 | export function cpuShare(before: number, after: number, ms: number): number { | |
| 85 | if (ms <= 0 || after < before) return 0; | |
| 86 | return (after - before) / CLOCK_TICKS / (ms / 1000); | |
| 87 | } | |
| 88 | ||
| 89 | /** Below this share of a core a tree is waiting, not working. */ | |
| 90 | export const BUSY_SHARE = 0.05; |
src/web/layout.ts +1
| @@ -397,6 +397,7 @@ const STATIC_PALETTE: PaletteItem[] = [ | ||
| 397 | 397 | { t: "Account settings", h: "/settings", c: "Settings" }, |
| 398 | 398 | { t: "Access tokens", h: "/settings/tokens", c: "Settings" }, |
| 399 | 399 | { t: "SSH keys", h: "/settings/keys", c: "Settings" }, |
| 400 | { t: "Terminals: sessions to resume or stop", h: "/settings/terminals", c: "Settings" }, | |
| 400 | 401 | { t: "Origins", h: "/settings/origins", c: "Settings" }, |
| 401 | 402 | ]; |
| 402 | 403 |
src/web/pages/account.ts +1 −1
| @@ -97,7 +97,7 @@ const help = (notes: readonly (readonly [string, string | Html])[]): Html => | ||
| 97 | 97 | </dl> |
| 98 | 98 | </details>`; |
| 99 | 99 | |
| 100 | type Section = "profile" | "password" | "tokens" | "keys" | "passkeys"; | |
| 100 | type Section = "profile" | "password" | "tokens" | "keys" | "passkeys" | "terminals"; | |
| 101 | 101 | |
| 102 | 102 | // The section list lives beside the newest page that joins it, so adding one |
| 103 | 103 | // cannot leave the others pointing at a nav that has forgotten it. |
src/web/pages/machines.ts +3 −2
| @@ -17,6 +17,7 @@ import { canAdmin, canWrite, type Repo } from "../../core/repos.ts"; | ||
| 17 | 17 | import { nameFrame, notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts"; |
| 18 | 18 | import { repoMachines } from "../../crew/machines_read.ts"; |
| 19 | 19 | import type { Ctx } from "../../http/context.ts"; |
| 20 | import { terminalIdleMs } from "../../machines/idle.ts"; | |
| 20 | 21 | import { ENDED, lastSessions, type SessionRecord } from "../../machines/shell.ts"; |
| 21 | 22 | import { |
| 22 | 23 | crumbsFor, |
| @@ -148,8 +149,8 @@ function renderShell(ctx: Ctx, repo: Repo, machine: Machine, script: string | un | ||
| 148 | 149 | ...(script === undefined ? {} : { scriptAsset: script, wasm: true }), |
| 149 | 150 | body: html`${repoHeader(ctx, repo, "settings", { compact: true })} |
| 150 | 151 | ${pageHead(html`${icon("terminal")}Shell on ${machine.name}`, { |
| 151 | sub: machine.tools.length === 0 ? "No tools beyond the shell." : `Tools: ${machine.tools.join(", ")}.`, | |
| 152 | actions: btn("All machines", { href: `${base}/settings/machines`, size: "sm" }), | |
| 152 | sub: `${machine.tools.length === 0 ? "No tools beyond the shell." : `Tools: ${machine.tools.join(", ")}.`} Closing this tab detaches; the shell keeps running and stops after ${Math.round(terminalIdleMs() / 60_000)} minutes idle. Come back to this page to reattach.`, | |
| 153 | actions: html`${btn("All terminals", { href: "/settings/terminals", size: "sm" })}${btn("All machines", { href: `${base}/settings/machines`, size: "sm" })}`, | |
| 153 | 154 | })} |
| 154 | 155 | ${term}`, |
| 155 | 156 | }); |
src/web/pages/origins.ts +2
| @@ -87,6 +87,7 @@ import { | ||
| 87 | 87 | } from "../ui.ts"; |
| 88 | 88 | |
| 89 | 89 | export type AccountSection = |
| 90 | | "terminals" | |
| 90 | 91 | | "adminflows" |
| 91 | 92 | | "security" |
| 92 | 93 | | "profile" |
| @@ -142,6 +143,7 @@ const SECTION_ROWS: readonly (readonly [ | ||
| 142 | 143 | ["Account", "Passkeys", "/settings/passkeys", "key", (c) => c === "passkeys", false], |
| 143 | 144 | ["Account", "SSH keys", "/settings/keys", "lock", (c) => c === "keys", false], |
| 144 | 145 | ["Account", "Access tokens", "/settings/tokens", "key", (c) => c === "tokens", false], |
| 146 | ["Account", "Terminals", "/settings/terminals", "terminal", (c) => c === "terminals", false], | |
| 145 | 147 | ["Account", "Confirms", "/settings/confirms", "check", (c) => c === "confirms", false], |
| 146 | 148 | ["Crew and AI", "Model", "/settings/model", "key", (c) => c === "model", false], |
| 147 | 149 | ["Crew and AI", "Crew", "/settings/crew", "bot", (c) => c === "crew", true], |
src/web/pages/terminals.ts added +177
| @@ -0,0 +1,177 @@ | ||
| 1 | /** | |
| 2 | * GET /settings/terminals — one list of a person's terminals (#10457): the | |
| 3 | * shells they hold on machines and the app terminals they have open, one line | |
| 4 | * each (what, where, started, last input, CPU and memory now), with Resume | |
| 5 | * (open the same shell again: attached or detached, it is the same screen; a | |
| 6 | * stopped one comes back with its scrollback and directory), Stop, and Stop | |
| 7 | * all idle. Below them, the shells that stopped and can be resumed, and the | |
| 8 | * dotfiles repository applied to every new shell. | |
| 9 | * | |
| 10 | * POST /settings/terminals/:id/stop, /settings/terminals/stop-idle, | |
| 11 | * /settings/terminals/dotfiles. A terminal is only ever the signed-in | |
| 12 | * person's own; a stranger's id is the same answer as a missing one. | |
| 13 | */ | |
| 14 | ||
| 15 | import { canRead, canWrite, getRepo, getRepoById } from "../../core/repos.ts"; | |
| 16 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; | |
| 17 | import { getUserSetting, setUserSetting } from "../../core/settings.ts"; | |
| 18 | import type { Ctx } from "../../http/context.ts"; | |
| 19 | import { DOTFILES_KEY, parseDotfilesRepo } from "../../machines/environment.ts"; | |
| 20 | import { terminalIdleMs, untilWords } from "../../machines/idle.ts"; | |
| 21 | import { stoppedShells } from "../../machines/snapshot.ts"; | |
| 22 | import { QUIET_MS, stopQuiet, stopTerminal, terminalsOf, type TerminalView } from "../../machines/terminals.ts"; | |
| 23 | import { signInFirst } from "../chrome.ts"; | |
| 24 | import { field, readForm } from "../form.ts"; | |
| 25 | import { html, type Html } from "../html.ts"; | |
| 26 | import { flashTo } from "../layout.ts"; | |
| 27 | import { btn, empty, icon, row, time } from "../ui.ts"; | |
| 28 | import { accountShell } from "./account.ts"; | |
| 29 | ||
| 30 | const iso = (ms: number): string => new Date(ms).toISOString(); | |
| 31 | ||
| 32 | /** "3% CPU · 42 MiB". */ | |
| 33 | export function usageWords(cpuShare: number, rssBytes: number): string { | |
| 34 | const cpu = `${Math.round(cpuShare * 100)}% CPU`; | |
| 35 | const mib = rssBytes / (1024 * 1024); | |
| 36 | return `${cpu} · ${mib >= 1024 ? `${(mib / 1024).toFixed(1)} GiB` : `${Math.round(mib)} MiB`}`; | |
| 37 | } | |
| 38 | ||
| 39 | /** What a live terminal's line says about its state, in words. */ | |
| 40 | export function stateWords(t: TerminalView, now = Date.now()): string { | |
| 41 | if (t.kind === "app") return `stops in ${untilWords(t.stopsAt, now)} unless you use it`; | |
| 42 | return t.attached | |
| 43 | ? `open, stops in ${untilWords(t.stopsAt, now)} if left` | |
| 44 | : `detached, stops in ${untilWords(t.stopsAt, now)} unless you come back`; | |
| 45 | } | |
| 46 | ||
| 47 | function liveRow(t: TerminalView, now: number): Html { | |
| 48 | const ssh = process.env["FORGE_APP_SSH"]; | |
| 49 | return row({ | |
| 50 | lead: icon("terminal"), | |
| 51 | title: html`${t.what} <span class="muted small">${t.where}</span>`, | |
| 52 | meta: html`Started ${time(iso(t.startedAt))} · last input ${time(iso(t.lastInput))} · ${usageWords(t.cpuShare, t.rssBytes)} | |
| 53 | · ${stateWords(t, now)}${t.kind === "app" ? html` · reattach with ${ssh === undefined || ssh === "" ? "the terminal (off on this forge)" : html`<code>${ssh}</code>`}` : null}`, | |
| 54 | trail: html`<span class="row-fields"> | |
| 55 | ${t.kind === "machine" ? btn(t.attached ? "Open" : "Resume", { href: t.href, size: "sm", variant: "primary", label: `${t.attached ? "Open" : "Resume"} ${t.what} on ${t.where}` }) : null} | |
| 56 | <form method="post" action="/settings/terminals/${t.id}/stop"> | |
| 57 | ${btn("Stop", { size: "sm", variant: "outline", label: `Stop ${t.what} on ${t.where}` })} | |
| 58 | </form> | |
| 59 | </span>`, | |
| 60 | data: { terminal: t.id }, | |
| 61 | }); | |
| 62 | } | |
| 63 | ||
| 64 | export function terminalsPage(ctx: Ctx): Response { | |
| 65 | const user = ctx.auth.user; | |
| 66 | if (!user) return signInFirst(ctx); | |
| 67 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); | |
| 68 | const now = Date.now(); | |
| 69 | const live = timePhase(ctx.request, "terminals", () => terminalsOf(ctx.app, user.id, now)); | |
| 70 | const stopped = timePhase(ctx.request, "stopped", () => | |
| 71 | stoppedShells(ctx.app.config.dataDir, user.id).flatMap((s) => { | |
| 72 | const repo = getRepoById(ctx.app.db, s.repoId); | |
| 73 | return repo !== undefined && canWrite(ctx.app.db, repo, user) ? [{ s, repo }] : []; | |
| 74 | }), | |
| 75 | ); | |
| 76 | const quiet = live.filter((t) => t.quiet).length; | |
| 77 | const dotfiles = getUserSetting(ctx.app.db, user.id, DOTFILES_KEY) ?? ""; | |
| 78 | const body = html`<section class="settings-block" id="terminals"> | |
| 79 | <h2>Running now</h2> | |
| 80 | <p class="muted small"> | |
| 81 | Closing a tab only detaches: the terminal keeps running and stops by itself after ${Math.round(terminalIdleMs() / 60_000)} minutes | |
| 82 | with no input, no output and no work. Nothing runs for no reason. | |
| 83 | </p> | |
| 84 | ${live.length === 0 | |
| 85 | ? empty({ icon: "terminal", title: "Nothing is running", note: "Open a machine's shell from a repository's Machines settings; it appears here." }) | |
| 86 | : html`<ul class="list setting-list">${live.map((t) => liveRow(t, now))}</ul> | |
| 87 | <form method="post" action="/settings/terminals/stop-idle"> | |
| 88 | ${btn(`Stop all idle (${quiet})`, { | |
| 89 | variant: "outline", | |
| 90 | label: `Stop all idle terminals: those with nothing for ${QUIET_MS / 60_000} minutes`, | |
| 91 | })} | |
| 92 | <span class="muted small">Idle here is ${QUIET_MS / 60_000} minutes with no input, no output and no work.</span> | |
| 93 | </form>`} | |
| 94 | </section> | |
| 95 | <section class="settings-block" id="stopped-terminals"> | |
| 96 | <h2>Stopped, ready to resume</h2> | |
| 97 | ${stopped.length === 0 | |
| 98 | ? html`<p class="small">No stopped shell is waiting. One that stops idle, or that you stop, is kept here with its scrollback and directory.</p>` | |
| 99 | : html`<ul class="list setting-list">${stopped.map(({ s, repo }) => | |
| 100 | row({ | |
| 101 | lead: html`<span aria-hidden="true">–</span>`, | |
| 102 | title: html`Shell on ${s.machine} <span class="muted small">${repo.ownerName}/${repo.name}</span>`, | |
| 103 | meta: html`Stopped ${time(s.meta.stoppedAt)} · ${s.meta.reason === "idle" ? "idle too long" : "stopped"}`, | |
| 104 | trail: btn("Resume", { | |
| 105 | href: `/${repo.ownerName}/${repo.name}/machines/${s.machine}/shell`, | |
| 106 | size: "sm", | |
| 107 | variant: "primary", | |
| 108 | label: `Resume the shell on ${s.machine} in ${repo.ownerName}/${repo.name}`, | |
| 109 | }), | |
| 110 | data: { stopped: `${repo.name}/${s.machine}` }, | |
| 111 | }), | |
| 112 | )}</ul>`} | |
| 113 | </section> | |
| 114 | <section class="settings-block" id="terminal-dotfiles"> | |
| 115 | <h2>Dotfiles</h2> | |
| 116 | <p class="muted small"> | |
| 117 | A repository on this forge that you can read, as <code>owner/name</code>. Every new shell clones it to | |
| 118 | <code>~/.dotfiles</code>, links its <code>.gitconfig</code>, <code>.tmux.conf</code>, <code>.vimrc</code> and | |
| 119 | <code>.inputrc</code>, and sources its <code>forge.sh</code> (or <code>.bashrc</code>). | |
| 120 | </p> | |
| 121 | <form method="post" action="/settings/terminals/dotfiles" class="row-fields"> | |
| 122 | <label class="sr-only" for="dotfiles-repo">Dotfiles repository</label> | |
| 123 | <input id="dotfiles-repo" name="repo" value="${dotfiles}" placeholder="owner/dotfiles" maxlength="201" autocomplete="off" /> | |
| 124 | ${btn("Save", { size: "sm" })} | |
| 125 | </form> | |
| 126 | </section>`; | |
| 127 | return timePhase(ctx.request, "render", () => accountShell(ctx, "terminals", "Terminals", body)); | |
| 128 | } | |
| 129 | ||
| 130 | // POST /settings/terminals/:id/stop | |
| 131 | export async function terminalStop(ctx: Ctx): Promise<Response> { | |
| 132 | const user = ctx.auth.user; | |
| 133 | if (!user) return signInFirst(ctx); | |
| 134 | const form = await readForm(ctx, "admin"); | |
| 135 | if (form instanceof Response) return form; | |
| 136 | const stopped = stopTerminal(ctx.app, user.id, ctx.params["id"] ?? ""); | |
| 137 | return flashTo( | |
| 138 | ctx, | |
| 139 | "/settings/terminals", | |
| 140 | stopped | |
| 141 | ? { message: "Stopped. A shell keeps its scrollback and directory; Resume brings it back." } | |
| 142 | : { tone: "danger", message: "That terminal is not running any more." }, | |
| 143 | ); | |
| 144 | } | |
| 145 | ||
| 146 | // POST /settings/terminals/stop-idle | |
| 147 | export async function terminalsStopIdle(ctx: Ctx): Promise<Response> { | |
| 148 | const user = ctx.auth.user; | |
| 149 | if (!user) return signInFirst(ctx); | |
| 150 | const form = await readForm(ctx, "admin"); | |
| 151 | if (form instanceof Response) return form; | |
| 152 | const n = stopQuiet(ctx.app, user.id); | |
| 153 | return flashTo(ctx, "/settings/terminals", { | |
| 154 | message: n === 0 ? "Nothing was idle." : `Stopped ${n} idle terminal${n === 1 ? "" : "s"}.`, | |
| 155 | }); | |
| 156 | } | |
| 157 | ||
| 158 | // POST /settings/terminals/dotfiles | |
| 159 | export async function dotfilesSet(ctx: Ctx): Promise<Response> { | |
| 160 | const user = ctx.auth.user; | |
| 161 | if (!user) return signInFirst(ctx); | |
| 162 | const form = await readForm(ctx, "admin"); | |
| 163 | if (form instanceof Response) return form; | |
| 164 | const text = field(form, "repo").trim(); | |
| 165 | if (text === "") { | |
| 166 | setUserSetting(ctx.app.db, user.id, DOTFILES_KEY, ""); | |
| 167 | return flashTo(ctx, "/settings/terminals", { message: "No dotfiles repository is applied." }); | |
| 168 | } | |
| 169 | const named = parseDotfilesRepo(text); | |
| 170 | const repo = named === undefined ? undefined : getRepo(ctx.app.db, named.owner, named.name); | |
| 171 | // A repository you cannot read is the same answer as one that is not there. | |
| 172 | if (named === undefined || repo === undefined || !canRead(ctx.app.db, repo, user)) | |
| 173 | return flashTo(ctx, "/settings/terminals", { tone: "danger", message: "No such repository you can read; write it as owner/name." }); | |
| 174 | setUserSetting(ctx.app.db, user.id, DOTFILES_KEY, `${named.owner}/${named.name}`); | |
| 175 | return flashTo(ctx, "/settings/terminals", { message: `New shells apply ${named.owner}/${named.name}.` }); | |
| 176 | } | |
| 177 |
test/terminals.test.ts added +321
| @@ -0,0 +1,321 @@ | ||
| 1 | /** | |
| 2 | * Sessions you can see, resume and stop (#10457): the list shows real usage, | |
| 3 | * closing the tab detaches without killing, an idle session stops itself and | |
| 4 | * keeps its scrollback and directory so Resume brings it back, a session that | |
| 5 | * is working is not idle, and a shell opens in an environment made for it. | |
| 6 | * | |
| 7 | * This sandbox cannot hold a cell, so the shells run uncontained on purpose. | |
| 8 | */ | |
| 9 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 10 | import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; | |
| 11 | import { tmpdir } from "node:os"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { createRepo, type Repo } from "../src/core/repos.ts"; | |
| 15 | import { createSession } from "../src/core/sessions.ts"; | |
| 16 | import { setUserSetting } from "../src/core/settings.ts"; | |
| 17 | import { createUser, type User } from "../src/core/users.ts"; | |
| 18 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 19 | import { DOTFILES_KEY, greetingLine, parseDotfilesRepo, profileText } from "../src/machines/environment.ts"; | |
| 20 | import { DEFAULT_IDLE_MINUTES, isIdle, terminalIdleMs, untilWords } from "../src/machines/idle.ts"; | |
| 21 | import { lastSessions, liveSessions, setShellOptions, workspace } from "../src/machines/shell.ts"; | |
| 22 | import { MAX_SCROLLBACK_BYTES, Scrollback, savedCwd, stoppedShells } from "../src/machines/snapshot.ts"; | |
| 23 | import { terminalsOf } from "../src/machines/terminals.ts"; | |
| 24 | import { cpuShare, parseStat, treeUsage } from "../src/machines/usage.ts"; | |
| 25 | import { BUILT_IN } from "../src/crew/machines.ts"; | |
| 26 | import { quietLogs } from "./helpers/globals.ts"; | |
| 27 | ||
| 28 | quietLogs(); | |
| 29 | ||
| 30 | let app: App; | |
| 31 | let servers: Servers; | |
| 32 | let repo: Repo; | |
| 33 | let alice: User; | |
| 34 | let cookie = ""; | |
| 35 | ||
| 36 | beforeAll(async () => { | |
| 37 | app = createApp({ dataDir: mkdtempSync(join(tmpdir(), "terminals-")), port: 0 }); | |
| 38 | const made = await createUser(app.db, { username: "alice", email: "[email protected]", password: "correct horse battery", origin: "seed", isAdmin: false, trusted: true }); | |
| 39 | if (!made.ok) throw new Error(String(made.error)); | |
| 40 | alice = made.value; | |
| 41 | cookie = `forge_session=${createSession(app.db, alice.id).token}`; | |
| 42 | const lab = await createRepo(app.db, app.reposRoot, { ownerId: alice.id, name: "lab", visibility: "public" }); | |
| 43 | if (!lab.ok) throw new Error(String(lab.error)); | |
| 44 | repo = lab.value; | |
| 45 | const d = await createRepo(app.db, app.reposRoot, { ownerId: alice.id, name: "dotfiles", visibility: "private" }); | |
| 46 | if (!d.ok) throw new Error(String(d.error)); | |
| 47 | servers = await serve(app); | |
| 48 | }); | |
| 49 | ||
| 50 | afterAll(() => { | |
| 51 | servers.stop(); | |
| 52 | app.close(); | |
| 53 | }); | |
| 54 | ||
| 55 | const ORIGIN = () => new URL(servers.url).origin; | |
| 56 | const WS = () => servers.url.replace(/^http/, "ws"); | |
| 57 | ||
| 58 | function configure(idleMs: number, command = "exec bash -i"): void { | |
| 59 | setShellOptions(app, { idleMs, contain: "uncontained", command, handshakesPerMinute: 1000, checkMs: 50 }); | |
| 60 | } | |
| 61 | ||
| 62 | function open(): Promise<{ ws: WebSocket; seen: () => string }> { | |
| 63 | const ws = new WebSocket(`${WS()}/alice/lab/machines/standard/shell`, { | |
| 64 | headers: { cookie, origin: ORIGIN() }, | |
| 65 | } as unknown as string[]); | |
| 66 | ws.binaryType = "arraybuffer"; | |
| 67 | let text = ""; | |
| 68 | ws.addEventListener("message", (e) => { | |
| 69 | text += typeof e.data === "string" ? e.data : new TextDecoder().decode(e.data as ArrayBuffer); | |
| 70 | }); | |
| 71 | return new Promise((resolve, reject) => { | |
| 72 | ws.addEventListener("open", () => { | |
| 73 | ws.send(JSON.stringify({ type: "resize", cols: 100, rows: 30 })); | |
| 74 | resolve({ ws, seen: () => text }); | |
| 75 | }); | |
| 76 | ws.addEventListener("error", () => reject(new Error("refused"))); | |
| 77 | }); | |
| 78 | } | |
| 79 | ||
| 80 | async function until(what: () => boolean, ms = 8_000): Promise<void> { | |
| 81 | const end = Date.now() + ms; | |
| 82 | while (!what()) { | |
| 83 | if (Date.now() > end) throw new Error("timed out"); | |
| 84 | await Bun.sleep(25); | |
| 85 | } | |
| 86 | } | |
| 87 | ||
| 88 | const type = (ws: WebSocket, text: string) => ws.send(new TextEncoder().encode(text)); | |
| 89 | ||
| 90 | async function post(path: string, body = ""): Promise<Response> { | |
| 91 | return fetch(`${ORIGIN()}${path}`, { | |
| 92 | method: "POST", | |
| 93 | redirect: "manual", | |
| 94 | headers: { cookie, origin: ORIGIN(), "content-type": "application/x-www-form-urlencoded" }, | |
| 95 | body, | |
| 96 | }); | |
| 97 | } | |
| 98 | ||
| 99 | async function listPage(): Promise<string> { | |
| 100 | const res = await fetch(`${ORIGIN()}/settings/terminals`, { headers: { cookie } }); | |
| 101 | expect(res.status).toBe(200); | |
| 102 | return res.text(); | |
| 103 | } | |
| 104 | ||
| 105 | const mine = () => terminalsOf(app, alice.id); | |
| 106 | ||
| 107 | test("the idle time is one knob with a default of thirty minutes", () => { | |
| 108 | expect(DEFAULT_IDLE_MINUTES).toBe(30); | |
| 109 | expect(terminalIdleMs({})).toBe(30 * 60_000); | |
| 110 | expect(terminalIdleMs({ FORGE_TERMINAL_IDLE_MINUTES: "5" })).toBe(5 * 60_000); | |
| 111 | expect(terminalIdleMs({ FORGE_TERMINAL_IDLE_MINUTES: "nope" })).toBe(30 * 60_000); | |
| 112 | expect(terminalIdleMs({ FORGE_TERMINAL_IDLE_MINUTES: "0" })).toBe(30 * 60_000); | |
| 113 | }); | |
| 114 | ||
| 115 | test("idle is no input, no output and no work for the whole time", () => { | |
| 116 | const a = { lastInput: 0, lastOutput: 0, lastBusy: 0 }; | |
| 117 | expect(isIdle(a, 999, 1000)).toBe(false); | |
| 118 | expect(isIdle(a, 1000, 1000)).toBe(true); | |
| 119 | // Output, or CPU in the tree, is activity: a build that prints nothing is not idle. | |
| 120 | expect(isIdle({ ...a, lastOutput: 800 }, 1500, 1000)).toBe(false); | |
| 121 | expect(isIdle({ ...a, lastBusy: 800 }, 1500, 1000)).toBe(false); | |
| 122 | expect(untilWords(47 * 60_000, 0)).toBe("47 min"); | |
| 123 | expect(untilWords(72 * 60_000, 0)).toBe("1 h 12 min"); | |
| 124 | expect(untilWords(1_000, 0)).toBe("under a minute"); | |
| 125 | }); | |
| 126 | ||
| 127 | test("usage is read from the process tree: a laid-out /proc, and a real process", () => { | |
| 128 | expect(parseStat("12 (a (b) c) S 7 0 0 0 0 0 0 0 0 0 30 12 0 0 0 0 0 0 0 0 250 0")).toEqual({ ppid: 7, ticks: 42, rssPages: 250 }); | |
| 129 | const proc = mkdtempSync(join(tmpdir(), "fake-proc-")); | |
| 130 | const put = (pid: number, ppid: number, ticks: number, rss: number) => { | |
| 131 | mkdirSync(join(proc, String(pid))); | |
| 132 | writeFileSync(join(proc, String(pid), "stat"), `${pid} (p) S ${ppid} 0 0 0 0 0 0 0 0 0 ${ticks} 0 0 0 0 0 0 0 0 0 ${rss} 0`); | |
| 133 | }; | |
| 134 | put(10, 1, 5, 100); | |
| 135 | put(11, 10, 7, 50); | |
| 136 | put(12, 11, 1, 10); | |
| 137 | put(20, 1, 99, 999); // not under 10 | |
| 138 | expect(treeUsage(10, proc)).toEqual({ cpuTicks: 13, rssBytes: 160 * 4096, processes: 3 }); | |
| 139 | expect(treeUsage(77, proc)).toBeUndefined(); | |
| 140 | expect(cpuShare(100, 150, 1000)).toBeCloseTo(0.5); | |
| 141 | expect(cpuShare(150, 100, 1000)).toBe(0); | |
| 142 | const real = treeUsage(process.pid); | |
| 143 | expect(real?.rssBytes ?? 0).toBeGreaterThan(0); | |
| 144 | }); | |
| 145 | ||
| 146 | test("scrollback keeps the tail, from a whole line", () => { | |
| 147 | const s = new Scrollback(); | |
| 148 | const line = new TextEncoder().encode(`${"x".repeat(1023)}\n`); | |
| 149 | for (let i = 0; i < 400; i++) s.push(line); | |
| 150 | const out = s.bytes(); | |
| 151 | expect(out.byteLength).toBeLessThanOrEqual(MAX_SCROLLBACK_BYTES); | |
| 152 | expect(out.byteLength % 1024).toBe(0); | |
| 153 | }); | |
| 154 | ||
| 155 | test("the dotfiles setting names owner/name or nothing", () => { | |
| 156 | expect(parseDotfilesRepo("alice/dotfiles")).toEqual({ owner: "alice", name: "dotfiles" }); | |
| 157 | expect(parseDotfilesRepo("alice/../x")).toBeUndefined(); | |
| 158 | expect(parseDotfilesRepo("https://x.test/a/b")).toBeUndefined(); | |
| 159 | expect(parseDotfilesRepo("a b/c")).toBeUndefined(); | |
| 160 | expect(greetingLine({ machine: "standard", repo: "alice/lab", idleMinutes: 30, resumed: false, dotfiles: false })).toContain("close the tab to detach"); | |
| 161 | expect(profileText()).toContain("HISTFILE"); | |
| 162 | }); | |
| 163 | ||
| 164 | test("a shell opens in its environment: checkout, prompt, history, dotfiles and a greeting", async () => { | |
| 165 | // The dotfiles repository gets a forge.sh through a work tree pushed into the bare repo. | |
| 166 | const work = mkdtempSync(join(tmpdir(), "dots-work-")); | |
| 167 | const git = (...args: string[]) => Bun.spawnSync(["git", ...args], { cwd: work, env: { ...process.env, GIT_AUTHOR_NAME: "a", GIT_AUTHOR_EMAIL: "[email protected]", GIT_COMMITTER_NAME: "a", GIT_COMMITTER_EMAIL: "[email protected]" } }); | |
| 168 | git("init", "-q", "-b", "main"); | |
| 169 | writeFileSync(join(work, "forge.sh"), "export FROM_DOTFILES=applied\n"); | |
| 170 | git("add", "."); | |
| 171 | git("commit", "-q", "-m", "dots"); | |
| 172 | // Fetch rather than push: the bare repository's pre-receive hook is not what this test is about. | |
| 173 | Bun.spawnSync(["git", "fetch", "-q", work, "main:main"], { cwd: join(app.reposRoot, "alice", "dotfiles.git") }); | |
| 174 | setUserSetting(app.db, alice.id, DOTFILES_KEY, "alice/dotfiles"); | |
| 175 | configure(60_000); | |
| 176 | const { ws, seen } = await open(); | |
| 177 | await until(() => liveSessions(app) === 1); | |
| 178 | await until(() => seen().includes("forge · shell on standard"), 3000).catch((e) => { throw new Error(e.message + JSON.stringify(seen())); }); | |
| 179 | expect(seen()).toContain("alice/lab"); | |
| 180 | expect(seen()).toContain("close the tab to detach"); | |
| 181 | const dir = workspace(app, repo, BUILT_IN[0]!, alice.id); | |
| 182 | expect(existsSync(join(dir, "lab", ".git"))).toBe(true); | |
| 183 | type(ws, 'echo "dots=$FROM_DOTFILES repo=$FORGE_REPO hist=$HISTFILE"\n'); | |
| 184 | await until(() => seen().includes("dots=applied repo=alice/lab"), 3000).catch((e) => { throw new Error(e.message + JSON.stringify(seen())); }); | |
| 185 | expect(seen()).toContain(`hist=${join(dir, "home", ".forge", "history")}`); | |
| 186 | // The prompt remembers where the shell is, for Resume. | |
| 187 | type(ws, "cd /\n"); | |
| 188 | ws.close(); | |
| 189 | await until(() => mine().length === 1 && !mine()[0]!.attached); | |
| 190 | }); | |
| 191 | ||
| 192 | test("closing the tab detaches; the list shows it with real usage; coming back reattaches", async () => { | |
| 193 | const [t] = mine(); | |
| 194 | expect(t?.kind).toBe("machine"); | |
| 195 | expect(t?.where).toBe("alice/lab"); | |
| 196 | expect(t?.attached).toBe(false); | |
| 197 | expect(t?.detachedAt).toBeGreaterThan(0); | |
| 198 | expect(t?.rssBytes ?? 0).toBeGreaterThan(0); | |
| 199 | expect(liveSessions(app)).toBe(1); | |
| 200 | const page = await listPage(); | |
| 201 | expect(page).toContain("Shell on standard"); | |
| 202 | expect(page).toContain("detached, stops in"); | |
| 203 | expect(page).toContain("unless you come back"); | |
| 204 | expect(page).toContain("MiB"); | |
| 205 | expect(page).toContain("/alice/lab/machines/standard/shell"); | |
| 206 | const again = await open(); | |
| 207 | await until(() => mine()[0]?.attached === true); | |
| 208 | expect(liveSessions(app)).toBe(1); | |
| 209 | type(again.ws, "echo still-here-$((20+22))\n"); | |
| 210 | await until(() => again.seen().includes("still-here-42")); | |
| 211 | again.ws.close(); | |
| 212 | await until(() => mine()[0]?.attached === false); | |
| 213 | }); | |
| 214 | ||
| 215 | test("a stranger cannot stop another person's terminal", async () => { | |
| 216 | const bob = await createUser(app.db, { username: "bob", email: "[email protected]", password: "correct horse battery", origin: "seed", isAdmin: false, trusted: true }); | |
| 217 | if (!bob.ok) throw new Error("no bob"); | |
| 218 | const theirs = `forge_session=${createSession(app.db, bob.value.id).token}`; | |
| 219 | const id = mine()[0]!.id; | |
| 220 | const res = await fetch(`${ORIGIN()}/settings/terminals/${id}/stop`, { | |
| 221 | method: "POST", | |
| 222 | redirect: "manual", | |
| 223 | headers: { cookie: theirs, origin: ORIGIN(), "content-type": "application/x-www-form-urlencoded" }, | |
| 224 | body: "", | |
| 225 | }); | |
| 226 | expect(res.status).toBeLessThan(400); | |
| 227 | expect(liveSessions(app)).toBe(1); | |
| 228 | // And a post from another origin is refused outright. | |
| 229 | const cross = await fetch(`${ORIGIN()}/settings/terminals/${id}/stop`, { | |
| 230 | method: "POST", | |
| 231 | redirect: "manual", | |
| 232 | headers: { cookie, origin: "https://evil.test", "content-type": "application/x-www-form-urlencoded" }, | |
| 233 | body: "", | |
| 234 | }); | |
| 235 | expect(cross.status).toBe(403); | |
| 236 | expect(liveSessions(app)).toBe(1); | |
| 237 | }); | |
| 238 | ||
| 239 | test("Stop ends it, keeps its scrollback and directory, and Resume brings both back", async () => { | |
| 240 | const id = mine()[0]!.id; | |
| 241 | const res = await post(`/settings/terminals/${id}/stop`); | |
| 242 | expect(res.status).toBeLessThan(400); | |
| 243 | expect(liveSessions(app)).toBe(0); | |
| 244 | expect(lastSessions(app.db, repo.id)[0]?.endReason).toBe("stopped"); | |
| 245 | const dir = workspace(app, repo, BUILT_IN[0]!, alice.id); | |
| 246 | expect(savedCwd(dir)).toBeUndefined(); // "/" is outside the workspace: not trusted as a place to resume | |
| 247 | const stopped = stoppedShells(app.config.dataDir, alice.id); | |
| 248 | expect(stopped.map((s) => s.machine)).toEqual(["standard"]); | |
| 249 | const page = await listPage(); | |
| 250 | expect(page).toContain("Stopped, ready to resume"); | |
| 251 | expect(page).toContain("Resume"); | |
| 252 | // Put the shell somewhere inside the workspace, as its prompt would have. | |
| 253 | mkdirSync(join(dir, "lab", "sub"), { recursive: true }); | |
| 254 | writeFileSync(join(dir, "home", ".forge", "cwd"), `${join(dir, "lab", "sub")}\n`); | |
| 255 | expect(savedCwd(dir)).toBe(join(dir, "lab", "sub")); | |
| 256 | writeFileSync(join(dir, "home", ".forge", "cwd"), `${dir}/../../etc\n`); | |
| 257 | expect(savedCwd(dir)).toBeUndefined(); | |
| 258 | writeFileSync(join(dir, "home", ".forge", "cwd"), `${join(dir, "lab", "sub")}\n`); | |
| 259 | ||
| 260 | const back = await open(); | |
| 261 | await until(() => back.seen().includes("resumed: the scrollback above") && back.seen().includes("resumed shell on standard")); | |
| 262 | // What the stopped session drew is on the screen again. | |
| 263 | expect(back.seen()).toContain("still-here-42"); | |
| 264 | expect(back.seen()).toContain("resumed shell on standard"); | |
| 265 | type(back.ws, 'echo "at=$PWD"\n'); | |
| 266 | await until(() => back.seen().includes(`at=${join(dir, "lab", "sub")}`)); | |
| 267 | expect(stoppedShells(app.config.dataDir, alice.id)).toEqual([]); | |
| 268 | back.ws.close(); | |
| 269 | await until(() => mine()[0]?.attached === false); | |
| 270 | }); | |
| 271 | ||
| 272 | test("an idle session stops itself, and Resume still works", async () => { | |
| 273 | // Hang up what the last test left, then run with a short idle time. | |
| 274 | await post(`/settings/terminals/${mine()[0]!.id}/stop`); | |
| 275 | expect(liveSessions(app)).toBe(0); | |
| 276 | configure(700); | |
| 277 | const s = await open(); | |
| 278 | await until(() => liveSessions(app) === 1); | |
| 279 | type(s.ws, "echo remember-me-$((6*7))\n"); | |
| 280 | await until(() => s.seen().includes("remember-me-42")); | |
| 281 | s.ws.close(); | |
| 282 | await until(() => liveSessions(app) === 0, 6_000); | |
| 283 | expect(lastSessions(app.db, repo.id)[0]?.endReason).toBe("idle"); | |
| 284 | expect(stoppedShells(app.config.dataDir, alice.id)).toHaveLength(1); | |
| 285 | configure(60_000); | |
| 286 | const back = await open(); | |
| 287 | await until(() => back.seen().includes("remember-me-42")); | |
| 288 | expect(back.seen()).toContain("resumed"); | |
| 289 | back.ws.close(); | |
| 290 | }); | |
| 291 | ||
| 292 | test("a session that is running something is not idle", async () => { | |
| 293 | await post(`/settings/terminals/${mine()[0]!.id}/stop`); | |
| 294 | configure(1_200, "exec bash -c 'while :; do :; done'"); | |
| 295 | const s = await open(); | |
| 296 | await until(() => liveSessions(app) === 1); | |
| 297 | s.ws.close(); | |
| 298 | // Three idle times with no input and no output, and it is still there: the loop is work. | |
| 299 | await Bun.sleep(3_600); | |
| 300 | expect(liveSessions(app)).toBe(1); | |
| 301 | expect(mine()[0]?.cpuShare ?? 0).toBeGreaterThan(0.05); | |
| 302 | await post(`/settings/terminals/${mine()[0]!.id}/stop`); | |
| 303 | expect(liveSessions(app)).toBe(0); | |
| 304 | }); | |
| 305 | ||
| 306 | test("Stop all idle stops only those quiet for a while", async () => { | |
| 307 | configure(60_000, "exec sleep 600"); | |
| 308 | const s = await open(); | |
| 309 | await until(() => liveSessions(app) === 1); | |
| 310 | s.ws.close(); | |
| 311 | // Just started: not quiet yet. | |
| 312 | let res = await post("/settings/terminals/stop-idle"); | |
| 313 | expect(res.status).toBeLessThan(400); | |
| 314 | expect(liveSessions(app)).toBe(1); | |
| 315 | // Quiet for ten minutes (the clock is the argument, not a wait). | |
| 316 | const { stopQuiet } = await import("../src/machines/terminals.ts"); | |
| 317 | expect(stopQuiet(app, alice.id, Date.now() + 10 * 60_000)).toBe(1); | |
| 318 | expect(liveSessions(app)).toBe(0); | |
| 319 | res = await post("/settings/terminals/dotfiles", "repo=alice%2Fnothing-here"); | |
| 320 | expect(res.status).toBeLessThan(400); | |
| 321 | }); |
new above
offline