Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cae72c7f28 | ||
|
|
2025185489 | ||
|
|
936abbef9d | ||
|
|
2fc5f99f59 |
@@ -17,5 +17,6 @@
|
||||
- [2026-11-16] **Web UI shell (#12):** top bar (tabs, live state, Chat/Terminal), notebook sidebar only on Notebooks, parameter panel beside the notebook via a container query (above it when narrow), dialogs/menus from `ui.tsx`. Page and notebook live in the URL hash (`route.ts`); typed non-secret values are remembered per notebook in localStorage (`paramMemory.ts`, secrets and undeclared names are dropped on read and write).
|
||||
- [2026-11-16] **Collapsible parameters (#13):** the form and each included group collapse (remembered via `uiPrefs.ts`). Collapsed, only missing required values and values changed from their default are listed as chips; untouched defaults are just counted, so the bar stays one line.
|
||||
- [2026-11-16] **Icon (#14):** `apps/web/public/shellbook.svg` (mint notebook with `>_` on a dark tile) is the single source for favicon, top bar, sign-in, setup and README. The PNGs (192, 512, 180 apple-touch on a full dark square) are rendered from it with headless Edge; give the SVG fixed px sizes, since headless Edge enforces a minimum viewport width and `100vw` overshoots.
|
||||
- [2026-11-16] **Self-update from Settings (#15):** the unprivileged service only writes `<data>/update-request`; root-owned `shellbook-update.path` (PathChanged) starts oneshot `shellbook-update.service` → fixed `/usr/local/sbin/shellbook-update`, output to `/var/log/shellbook-update.log`. Server reads `systemctl show --timestamp=unix` + log tail; UI polls through the restart and ignores runs that started before the request. Installs predating #15 need one CLI `shellbook-update` to get the units.
|
||||
|
||||
## Archive
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
> Always-loaded. Everything else is on-demand. Update TOC when files change.
|
||||
|
||||
## Current Focus
|
||||
- [2026-11-16] M0–M3 (#1–#4), UI-first follow-ups (#7–#10) and chained notebooks (#11: when/use/host, LXC + web-server templates) the UI/UX overhaul (#12) and collapsible parameters (#13) and the app icon (#14) closed.
|
||||
- [2026-11-16] M0–M3 (#1–#4), UI-first follow-ups (#7–#10) and chained notebooks (#11: when/use/host, LXC + web-server templates) the UI/UX overhaul (#12) and collapsible parameters (#13) the app icon (#14) and self-update from Settings (#15) closed.
|
||||
- [2026-11-16] Open: #5/#6 need a real CT 501 deploy (bootstrap.sh one-liner, setup token, real SSH run, tmux terminal). Not yet verified in a real browser or against real OpenSSH.
|
||||
|
||||
## Invariants
|
||||
@@ -15,7 +15,7 @@
|
||||
- Everything doable from the web UI; files are storage, not the only way in.
|
||||
|
||||
## Table of Contents
|
||||
- `architecture.md` — 16 entries — why custom app, stack, AI integration, workspace split, deploy/update, chained notebooks, template delivery, web UI shell, collapsible params, app icon
|
||||
- `architecture.md` — 17 entries — why custom app, stack, AI integration, workspace split, deploy/update, chained notebooks, template delivery, web UI shell, collapsible params, app icon, UI self-update
|
||||
- `attempts.md` — 4 entries — marimo + marimo-pair trial and why it was dropped
|
||||
- `open.md` — 2 entries — open design questions (sudo password, chat history)
|
||||
- `gotchas.md` — 17 entries — integration foot-guns (CRLF, host-key events, tmux/systemd, env names, pct exec PATH, TUN, chat paths, watcher timing, capture-default deadlock, heredocs, YAML flow commas, orphaned dev servers)
|
||||
|
||||
@@ -10,6 +10,7 @@ import { createNotebookWatcher } from "./watch";
|
||||
import { registerAuth, type AuthOptions } from "./auth";
|
||||
import { registerStatic } from "./static";
|
||||
import { chatPlugin } from "./chat";
|
||||
import { defaultUpdateOptions, registerUpdate, type UpdateOptions } from "./update";
|
||||
|
||||
export interface AppOptions {
|
||||
logger?: boolean;
|
||||
@@ -26,6 +27,8 @@ export interface AppOptions {
|
||||
/** Watch workspace notebooks and publish file.changed/file.deleted on /api/events. */
|
||||
watchNotebooks?: boolean;
|
||||
terminal?: Omit<TerminalOptions, "workspaceDir">;
|
||||
/** Overrides for the self-update trigger (tests). */
|
||||
update?: Partial<UpdateOptions>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -33,7 +36,7 @@ export interface AppOptions {
|
||||
* src/auth/ login, persistent session secret (registered first: its hook guards every /api route)
|
||||
* src/workspace/ notebooks, hosts.yaml; src/ssh/, src/runs/ queue, audit, artifacts, /api/events
|
||||
* src/terminal/ node-pty + tmux, /api/terminal; src/watch/ file.changed events into the events hub
|
||||
* src/static/ built web app with SPA fallback
|
||||
* src/static/ built web app with SPA fallback; src/update/ self-update trigger (root runs it via systemd)
|
||||
*/
|
||||
export async function buildApp(options: AppOptions = {}): Promise<FastifyInstance> {
|
||||
const config = loadConfig(options.config);
|
||||
@@ -41,6 +44,7 @@ export async function buildApp(options: AppOptions = {}): Promise<FastifyInstanc
|
||||
const app = Fastify({ logger: options.logger ?? false, trustProxy: options.trustProxy ?? false });
|
||||
if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth });
|
||||
await registerSettings(app, config);
|
||||
await registerUpdate(app, { ...defaultUpdateOptions(config.dataDir), ...options.update });
|
||||
await app.register(websocket);
|
||||
const builtins = () => builtinValues(config);
|
||||
await app.register(workspacePlugin, { config, builtins });
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { access, mkdir, open, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type {
|
||||
UpdateCheckResponse,
|
||||
UpdateStartResponse,
|
||||
UpdateState,
|
||||
UpdateStatusResponse,
|
||||
} from "@shellbook/core";
|
||||
|
||||
/**
|
||||
* Self-update from the web UI (#15). The service never gains privileges: it only writes
|
||||
* a request file. A root-owned systemd path unit (deploy/install.sh) watches that file
|
||||
* and starts `shellbook-update.service`, which runs the fixed root-owned updater and
|
||||
* writes its output to a root-owned log. Here we only read that state back.
|
||||
*/
|
||||
export interface UpdateOptions {
|
||||
/** Written to request an update; watched by shellbook-update.path. */
|
||||
requestFile: string;
|
||||
/** Present when the trigger units are installed. */
|
||||
triggerUnit: string;
|
||||
/** Output of the last update run (StandardOutput of the update unit). */
|
||||
logFile: string;
|
||||
/** The git checkout the server runs from. */
|
||||
repoDir: string;
|
||||
/** Runs a program with argv (no shell) and returns stdout; rejects on failure. */
|
||||
run(file: string, args: string[], timeoutMs: number): Promise<string>;
|
||||
}
|
||||
|
||||
const UNIT = "shellbook-update.service";
|
||||
const LOG_BYTES = 64 * 1024;
|
||||
const LOG_LINES = 200;
|
||||
|
||||
function run(file: string, args: string[], timeoutMs: number): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(
|
||||
file,
|
||||
args,
|
||||
// Never wait for credentials on a terminal that is not there.
|
||||
{ timeout: timeoutMs, maxBuffer: 1024 * 1024, windowsHide: true, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } },
|
||||
(error, stdout) => (error ? reject(error) : resolve(stdout)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function defaultUpdateOptions(dataDir: string): UpdateOptions {
|
||||
return {
|
||||
requestFile: join(dataDir, "update-request"),
|
||||
triggerUnit: "/etc/systemd/system/shellbook-update.path",
|
||||
logFile: "/var/log/shellbook-update.log",
|
||||
// systemd starts the service in the checkout (WorkingDirectory=/opt/shellbook).
|
||||
repoDir: process.cwd(),
|
||||
run,
|
||||
};
|
||||
}
|
||||
|
||||
/** `--timestamp=unix` prints `@<seconds>`; empty or `n/a` means never. */
|
||||
function timestamp(value: string | undefined): string | null {
|
||||
const match = value?.match(/^@(\d+)$/);
|
||||
return match ? new Date(Number(match[1]) * 1000).toISOString() : null;
|
||||
}
|
||||
|
||||
/** The last lines of the log, reading at most LOG_BYTES from its end. */
|
||||
async function logTail(path: string): Promise<string> {
|
||||
let file;
|
||||
try {
|
||||
file = await open(path, "r");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
const { size } = await file.stat();
|
||||
const length = Math.min(size, LOG_BYTES);
|
||||
const buffer = Buffer.alloc(length);
|
||||
await file.read(buffer, 0, length, size - length);
|
||||
const lines = buffer.toString("utf8").split("\n");
|
||||
// Drop a partial first line when the read started mid-file.
|
||||
if (length < size) lines.shift();
|
||||
if (lines.at(-1) === "") lines.pop();
|
||||
return lines.slice(-LOG_LINES).join("\n");
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
}
|
||||
|
||||
export function createUpdater(options: UpdateOptions) {
|
||||
const git = (args: string[], timeoutMs = 5000) =>
|
||||
options.run("git", ["-C", options.repoDir, ...args], timeoutMs).then((out) => out.trim());
|
||||
const current = () => git(["rev-parse", "--short", "HEAD"]).catch(() => null);
|
||||
const available = () => access(options.triggerUnit).then(() => true, () => false);
|
||||
|
||||
async function unitState(): Promise<Pick<UpdateStatusResponse, "state" | "startedAt" | "finishedAt">> {
|
||||
let output: string;
|
||||
try {
|
||||
output = await options.run(
|
||||
"systemctl",
|
||||
["show", UNIT, "--timestamp=unix", "--property=ActiveState,Result,ExecMainStartTimestamp,ExecMainExitTimestamp"],
|
||||
5000,
|
||||
);
|
||||
} catch {
|
||||
return { state: "unknown", startedAt: null, finishedAt: null };
|
||||
}
|
||||
const props: Record<string, string> = Object.fromEntries(
|
||||
output.split("\n").filter((line) => line.includes("=")).map((line) => {
|
||||
const at = line.indexOf("=");
|
||||
return [line.slice(0, at), line.slice(at + 1).trim()];
|
||||
}),
|
||||
);
|
||||
const startedAt = timestamp(props.ExecMainStartTimestamp);
|
||||
const finishedAt = timestamp(props.ExecMainExitTimestamp);
|
||||
let state: UpdateState;
|
||||
if (["activating", "active", "reloading", "deactivating"].includes(props.ActiveState ?? "")) state = "running";
|
||||
else if (props.ActiveState === "failed" || (startedAt && props.Result !== "success")) state = "failed";
|
||||
else state = startedAt ? "succeeded" : "idle";
|
||||
return { state, startedAt, finishedAt: state === "running" ? null : finishedAt };
|
||||
}
|
||||
|
||||
return {
|
||||
async status(): Promise<UpdateStatusResponse> {
|
||||
const [isAvailable, commit] = await Promise.all([available(), current()]);
|
||||
if (!isAvailable)
|
||||
return { available: false, state: "idle", current: commit, startedAt: null, finishedAt: null, log: "" };
|
||||
return { available: true, current: commit, ...(await unitState()), log: await logTail(options.logFile) };
|
||||
},
|
||||
|
||||
/** Fetches the tracked branch (FETCH_HEAD only) and lists the commits an update would bring. */
|
||||
async check(): Promise<UpdateCheckResponse> {
|
||||
const commit = await current();
|
||||
const branch = await git(["symbolic-ref", "-q", "--short", "HEAD"]).catch(() => null);
|
||||
// A detached HEAD is a pinned SHELLBOOK_REF: the installer never pulls it.
|
||||
if (!branch) return { current: commit, latest: null, pinned: true, changes: [] };
|
||||
const upstream = await git(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
|
||||
const slash = upstream.indexOf("/");
|
||||
if (slash <= 0) throw new Error(`Unexpected upstream: ${upstream}`);
|
||||
await git(["fetch", "--quiet", "--no-tags", "--", upstream.slice(0, slash), upstream.slice(slash + 1)], 30_000);
|
||||
const latest = await git(["rev-parse", "--short", "FETCH_HEAD"]);
|
||||
const log = await git(["log", "--format=%h%x09%s", "-n", "50", "HEAD..FETCH_HEAD"]);
|
||||
const changes = log
|
||||
? log.split("\n").map((line) => {
|
||||
const tab = line.indexOf("\t");
|
||||
return { commit: line.slice(0, tab), subject: line.slice(tab + 1) };
|
||||
})
|
||||
: [];
|
||||
return { current: commit, latest, pinned: false, changes };
|
||||
},
|
||||
|
||||
/** Requests an update; systemd runs it as root. Returns null when it cannot start. */
|
||||
async start(): Promise<{ ok: true; response: UpdateStartResponse } | { ok: false; error: string }> {
|
||||
if (!(await available())) return { ok: false, error: "Updating from the web UI is not installed here. Run shellbook-update as root." };
|
||||
if ((await unitState()).state === "running") return { ok: false, error: "An update is already running." };
|
||||
const requestedAt = new Date().toISOString();
|
||||
await mkdir(dirname(options.requestFile), { recursive: true });
|
||||
// Closing the written file is what triggers the path unit (PathChanged=).
|
||||
await writeFile(options.requestFile, requestedAt + "\n", { mode: 0o600 });
|
||||
return { ok: true, response: { requestedAt } };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function registerUpdate(app: FastifyInstance, options: UpdateOptions): Promise<void> {
|
||||
const updater = createUpdater(options);
|
||||
app.get("/api/settings/update", async (_request, reply) =>
|
||||
reply.header("Cache-Control", "no-store").send(await updater.status()),
|
||||
);
|
||||
app.post("/api/settings/update/check", async (_request, reply) => {
|
||||
if ((await updater.status()).state === "running")
|
||||
return reply.code(409).send({ error: "An update is running." });
|
||||
try {
|
||||
return reply.header("Cache-Control", "no-store").send(await updater.check());
|
||||
} catch (error) {
|
||||
app.log.warn({ err: error }, "update check failed");
|
||||
return reply.code(502).send({ error: "Could not check the repository for updates." });
|
||||
}
|
||||
});
|
||||
app.post("/api/settings/update", async (_request, reply) => {
|
||||
const result = await updater.start();
|
||||
return result.ok ? reply.code(202).send(result.response) : reply.code(409).send({ error: result.error });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { buildApp } from "../src/app";
|
||||
import type { UpdateOptions } from "../src/update";
|
||||
|
||||
const dirs: string[] = [];
|
||||
const apps: FastifyInstance[] = [];
|
||||
afterEach(async () => {
|
||||
for (const app of apps.splice(0)) await app.close();
|
||||
for (const path of dirs.splice(0)) await rm(path, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
type Reply = string | Error;
|
||||
/** Fake for `git`/`systemctl`: answers by "file arg arg…" prefix and records every call. */
|
||||
function fakeRun(answers: Record<string, Reply>) {
|
||||
const calls: string[][] = [];
|
||||
const run: UpdateOptions["run"] = async (file, args) => {
|
||||
calls.push([file, ...args]);
|
||||
const line = [file, ...args].join(" ");
|
||||
const key = Object.keys(answers).sort((a, b) => b.length - a.length).find((k) => line.startsWith(k));
|
||||
if (key === undefined) throw new Error(`unexpected command: ${line}`);
|
||||
const answer = answers[key]!;
|
||||
if (answer instanceof Error) throw answer;
|
||||
return answer;
|
||||
};
|
||||
return { run, calls };
|
||||
}
|
||||
|
||||
const show = (state: string, result = "success", start = "@1763300000", exit = "@1763300090") =>
|
||||
`ActiveState=${state}\nResult=${result}\nExecMainStartTimestamp=${start}\nExecMainExitTimestamp=${exit}\n`;
|
||||
const git = (repo: string) => `git -C ${repo}`;
|
||||
|
||||
async function setup(answers: Record<string, Reply>, installed = true, withAuth = false) {
|
||||
const root = await mkdtemp(join(tmpdir(), "update-"));
|
||||
dirs.push(root);
|
||||
const triggerUnit = join(root, "shellbook-update.path");
|
||||
if (installed) await writeFile(triggerUnit, "[Path]\n");
|
||||
const fake = fakeRun(answers);
|
||||
const options: Partial<UpdateOptions> = {
|
||||
triggerUnit,
|
||||
logFile: join(root, "update.log"),
|
||||
repoDir: join(root, "repo"),
|
||||
run: fake.run,
|
||||
};
|
||||
const app = await buildApp({ config: { dataDir: join(root, "data") }, auth: withAuth ? undefined : false, update: options });
|
||||
apps.push(app);
|
||||
return { app, root, repo: options.repoDir!, calls: fake.calls, requestFile: join(root, "data", "update-request"), logFile: options.logFile! };
|
||||
}
|
||||
|
||||
it("reports the installed commit, the last run and the end of its log", async () => {
|
||||
const { app, logFile, calls } = await setup({
|
||||
"git -C": "abc1234\n",
|
||||
"systemctl show shellbook-update.service": show("inactive"),
|
||||
});
|
||||
const lines = Array.from({ length: 400 }, (_, i) => `line ${i}`);
|
||||
await writeFile(logFile, lines.join("\n") + "\n");
|
||||
const status = (await app.inject("/api/settings/update")).json();
|
||||
expect(status).toMatchObject({
|
||||
available: true,
|
||||
state: "succeeded",
|
||||
current: "abc1234",
|
||||
startedAt: new Date(1763300000 * 1000).toISOString(),
|
||||
finishedAt: new Date(1763300090 * 1000).toISOString(),
|
||||
});
|
||||
// Only the end of a long log is returned.
|
||||
expect(status.log.split("\n")[0]).toBe("line 200");
|
||||
expect(status.log).toContain("line 399");
|
||||
// Read-only queries only, with argv (no shell).
|
||||
expect(calls.map((c) => c[0])).toEqual(expect.arrayContaining(["git", "systemctl"]));
|
||||
expect(calls.find((c) => c[0] === "systemctl")).toEqual([
|
||||
"systemctl", "show", "shellbook-update.service", "--timestamp=unix",
|
||||
"--property=ActiveState,Result,ExecMainStartTimestamp,ExecMainExitTimestamp",
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[show("activating", "success", "@1763300000", ""), "running"],
|
||||
[show("failed", "exit-code"), "failed"],
|
||||
[show("inactive", "success", "", ""), "idle"],
|
||||
])("maps unit state %#", async (output, state) => {
|
||||
const { app } = await setup({ "git -C": "abc1234\n", "systemctl show": output });
|
||||
expect((await app.inject("/api/settings/update")).json().state).toBe(state);
|
||||
});
|
||||
|
||||
it("says so when systemd cannot be asked, and is unavailable without the trigger unit", async () => {
|
||||
const broken = await setup({ "git -C": new Error("no git"), "systemctl show": new Error("no systemd") });
|
||||
expect((await broken.app.inject("/api/settings/update")).json()).toMatchObject({ available: true, state: "unknown", current: null });
|
||||
const missing = await setup({ "git -C": "abc1234\n" }, false);
|
||||
expect((await missing.app.inject("/api/settings/update")).json()).toMatchObject({ available: false, state: "idle", current: "abc1234" });
|
||||
// Never asks systemd or writes a request without the units.
|
||||
expect(missing.calls.some((c) => c[0] === "systemctl")).toBe(false);
|
||||
expect((await missing.app.inject({ method: "POST", url: "/api/settings/update", payload: {} })).statusCode).toBe(409);
|
||||
await expect(stat(missing.requestFile)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it("starts an update only by writing the request file, and never twice at once", async () => {
|
||||
const idle = await setup({ "git -C": "abc1234\n", "systemctl show": show("inactive") });
|
||||
const started = await idle.app.inject({ method: "POST", url: "/api/settings/update", payload: {} });
|
||||
expect(started.statusCode).toBe(202);
|
||||
const { requestedAt } = started.json();
|
||||
expect(Date.parse(requestedAt)).not.toBeNaN();
|
||||
expect((await readFile(idle.requestFile, "utf8")).trim()).toBe(requestedAt);
|
||||
// The server itself never starts units or runs the updater.
|
||||
expect(idle.calls.filter((c) => c[0] === "systemctl").every((c) => c[1] === "show")).toBe(true);
|
||||
const busy = await setup({ "git -C": "abc1234\n", "systemctl show": show("active", "success", "@1763300000", "") });
|
||||
expect((await busy.app.inject({ method: "POST", url: "/api/settings/update", payload: {} })).statusCode).toBe(409);
|
||||
});
|
||||
|
||||
it("checks the tracked branch and lists the commits an update would bring", async () => {
|
||||
const answers: Record<string, Reply> = {};
|
||||
const target = await setup(answers);
|
||||
Object.assign(answers, {
|
||||
[`${git(target.repo)} rev-parse --short HEAD`]: "abc1234\n",
|
||||
[`${git(target.repo)} symbolic-ref -q --short HEAD`]: "main\n",
|
||||
[`${git(target.repo)} rev-parse --abbrev-ref --symbolic-full-name @{u}`]: "origin/main\n",
|
||||
[`${git(target.repo)} fetch --quiet --no-tags -- origin main`]: "",
|
||||
[`${git(target.repo)} rev-parse --short FETCH_HEAD`]: "def5678\n",
|
||||
[`${git(target.repo)} log --format=%h%x09%s -n 50 HEAD..FETCH_HEAD`]: "def5678\tfeat(web): b\nbbb0000\tfix: a\ttab\n",
|
||||
"systemctl show": show("inactive"),
|
||||
});
|
||||
const result = await target.app.inject({ method: "POST", url: "/api/settings/update/check", payload: {} });
|
||||
expect(result.statusCode).toBe(200);
|
||||
expect(result.json()).toEqual({
|
||||
current: "abc1234",
|
||||
latest: "def5678",
|
||||
pinned: false,
|
||||
changes: [
|
||||
{ commit: "def5678", subject: "feat(web): b" },
|
||||
{ commit: "bbb0000", subject: "fix: a\ttab" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("reports a pinned checkout without fetching, and a failed fetch as 502", async () => {
|
||||
const pinnedAnswers: Record<string, Reply> = {};
|
||||
const pinned = await setup(pinnedAnswers);
|
||||
Object.assign(pinnedAnswers, {
|
||||
[`${git(pinned.repo)} rev-parse --short HEAD`]: "abc1234\n",
|
||||
[`${git(pinned.repo)} symbolic-ref -q --short HEAD`]: new Error("detached"),
|
||||
"systemctl show": show("inactive"),
|
||||
});
|
||||
const result = await pinned.app.inject({ method: "POST", url: "/api/settings/update/check", payload: {} });
|
||||
expect(result.json()).toEqual({ current: "abc1234", latest: null, pinned: true, changes: [] });
|
||||
expect(pinned.calls.some((c) => c.includes("fetch"))).toBe(false);
|
||||
|
||||
const offlineAnswers: Record<string, Reply> = {};
|
||||
const offline = await setup(offlineAnswers);
|
||||
Object.assign(offlineAnswers, {
|
||||
[`${git(offline.repo)} rev-parse --short HEAD`]: "abc1234\n",
|
||||
[`${git(offline.repo)} symbolic-ref -q --short HEAD`]: "main\n",
|
||||
[`${git(offline.repo)} rev-parse --abbrev-ref --symbolic-full-name @{u}`]: "origin/main\n",
|
||||
[`${git(offline.repo)} fetch`]: new Error("Could not resolve host"),
|
||||
"systemctl show": show("inactive"),
|
||||
});
|
||||
const failed = await offline.app.inject({ method: "POST", url: "/api/settings/update/check", payload: {} });
|
||||
expect(failed.statusCode).toBe(502);
|
||||
// The git error text stays in the server log, not in the response.
|
||||
expect(failed.body).not.toContain("resolve host");
|
||||
});
|
||||
|
||||
it("requires a session", async () => {
|
||||
const { app } = await setup({ "git -C": "abc1234\n", "systemctl show": show("inactive") }, true, true);
|
||||
expect((await app.inject("/api/settings/update")).statusCode).toBe(401);
|
||||
expect((await app.inject({ method: "POST", url: "/api/settings/update", payload: {} })).statusCode).toBe(401);
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
} from "@shellbook/core";
|
||||
import { settingsApi } from "./settingsApi";
|
||||
import { PasswordForm } from "./PasswordForm";
|
||||
import { UpdatePanel } from "./UpdatePanel";
|
||||
|
||||
function duration(seconds: number): string {
|
||||
const days = seconds / 86400;
|
||||
@@ -150,10 +151,8 @@ export function SettingsPage({
|
||||
) : (
|
||||
<p className="muted">Loading…</p>
|
||||
)}
|
||||
<p className="muted">
|
||||
Update from the container with <code>shellbook-update</code>.
|
||||
</p>
|
||||
</section>
|
||||
<UpdatePanel />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import type { UpdateCheckResponse, UpdateStatusResponse } from "@shellbook/core";
|
||||
import { settingsApi } from "./settingsApi";
|
||||
import { Dialog } from "./ui";
|
||||
|
||||
type UpdateApi = Pick<typeof settingsApi, "updateStatus" | "checkUpdate" | "startUpdate">;
|
||||
|
||||
/** How long a requested update may take to show up in systemd before we say so. */
|
||||
const START_TIMEOUT_MS = 30_000;
|
||||
/** systemd timestamps have second resolution; allow for that and small clock steps. */
|
||||
const START_SLACK_MS = 5_000;
|
||||
|
||||
type Watch =
|
||||
| { phase: "starting" | "running" | "restarting"; since: number }
|
||||
| { phase: "done" | "failed" | "stalled" };
|
||||
|
||||
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString() : "");
|
||||
|
||||
/**
|
||||
* Settings card that starts ShellBook's own update. The server only requests it; systemd
|
||||
* runs the updater as root and restarts the service, so this card keeps polling through
|
||||
* the restart and then offers a reload for the new web app.
|
||||
*/
|
||||
export function UpdatePanel({ api = settingsApi, pollMs = 2000 }: { api?: UpdateApi; pollMs?: number }) {
|
||||
const [status, setStatus] = useState<UpdateStatusResponse | "error">();
|
||||
const [check, setCheck] = useState<UpdateCheckResponse | "checking" | "error">();
|
||||
const [watch, setWatch] = useState<Watch>();
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const logRef = useRef<HTMLPreElement>(null);
|
||||
|
||||
// Initial load; an update already running (e.g. after a reload) is followed as well.
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
api.updateStatus().then(
|
||||
(next) => {
|
||||
if (!active) return;
|
||||
setStatus(next);
|
||||
if (next.state === "running") setWatch({ phase: "running", since: Date.parse(next.startedAt ?? "") || Date.now() });
|
||||
},
|
||||
() => active && setStatus("error"),
|
||||
);
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [api]);
|
||||
|
||||
const following = watch && (watch.phase === "starting" || watch.phase === "running" || watch.phase === "restarting");
|
||||
const since = watch && "since" in watch ? watch.since : 0;
|
||||
const poll = useCallback(async () => {
|
||||
let next: UpdateStatusResponse;
|
||||
try {
|
||||
next = await api.updateStatus();
|
||||
} catch {
|
||||
// The update restarts ShellBook; the API is gone for a moment.
|
||||
setWatch((current) => (current && "since" in current ? { ...current, phase: "restarting" } : current));
|
||||
return;
|
||||
}
|
||||
setStatus(next);
|
||||
const started = next.startedAt !== null && Date.parse(next.startedAt) >= since - START_SLACK_MS;
|
||||
if (next.state === "running") setWatch({ phase: "running", since });
|
||||
else if (!started)
|
||||
setWatch(Date.now() - since > START_TIMEOUT_MS ? { phase: "stalled" } : { phase: "starting", since });
|
||||
else setWatch({ phase: next.state === "succeeded" ? "done" : "failed" });
|
||||
}, [api, since]);
|
||||
useEffect(() => {
|
||||
if (!following) return;
|
||||
const timer = setInterval(() => void poll(), pollMs);
|
||||
return () => clearInterval(timer);
|
||||
}, [following, poll, pollMs]);
|
||||
|
||||
// Keep the newest log lines in view while an update runs.
|
||||
const log = status && status !== "error" ? status.log : "";
|
||||
useEffect(() => {
|
||||
if (following && logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight;
|
||||
}, [log, following]);
|
||||
|
||||
const start = async () => {
|
||||
setConfirming(false);
|
||||
setError("");
|
||||
try {
|
||||
const { requestedAt } = await api.startUpdate();
|
||||
setWatch({ phase: "starting", since: Date.parse(requestedAt) });
|
||||
} catch {
|
||||
setError("Unable to start the update. It may already be running; reload this page.");
|
||||
}
|
||||
};
|
||||
|
||||
if (status === undefined)
|
||||
return (
|
||||
<section className="card">
|
||||
<h2>Updates</h2>
|
||||
<p className="muted">Loading…</p>
|
||||
</section>
|
||||
);
|
||||
if (status === "error")
|
||||
return (
|
||||
<section className="card">
|
||||
<h2>Updates</h2>
|
||||
<p className="error">Unable to load the update status.</p>
|
||||
</section>
|
||||
);
|
||||
|
||||
return (
|
||||
<section className="card update-panel" aria-label="Updates">
|
||||
<h2>Updates</h2>
|
||||
<dl className="facts">
|
||||
<dt>Installed</dt>
|
||||
<dd>{status.current ? <code>{status.current}</code> : "unknown (not a git checkout)"}</dd>
|
||||
{status.available && status.startedAt && !following && (
|
||||
<>
|
||||
<dt>Last update</dt>
|
||||
<dd>
|
||||
{status.state === "failed" ? "failed" : status.state === "succeeded" ? "succeeded" : status.state},{" "}
|
||||
{when(status.finishedAt ?? status.startedAt)}
|
||||
</dd>
|
||||
</>
|
||||
)}
|
||||
</dl>
|
||||
{!status.available ? (
|
||||
<p className="muted">
|
||||
Updating from the web UI is not set up on this installation. Run <code>shellbook-update</code> as root in the
|
||||
container (from the Proxmox host: <code>pct exec <ctid> -- shellbook-update</code>); that run also
|
||||
adds the button here.
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
{watch && (
|
||||
<p role="status" className={`banner${watch.phase === "failed" || watch.phase === "stalled" ? " error" : ""}`}>
|
||||
{watch.phase === "starting" && "Starting the update…"}
|
||||
{watch.phase === "running" && "Updating… This takes a few minutes; ShellBook restarts at the end."}
|
||||
{watch.phase === "restarting" && "ShellBook is restarting…"}
|
||||
{watch.phase === "done" && (
|
||||
<>
|
||||
Update finished{status.current ? ` (${status.current})` : ""}. Reload to use the new version.
|
||||
<button className="primary" onClick={() => location.reload()}>
|
||||
Reload
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{watch.phase === "failed" && "The update failed. The log below shows why."}
|
||||
{watch.phase === "stalled" &&
|
||||
"The update did not start. Check systemctl status shellbook-update.path in the container."}
|
||||
</p>
|
||||
)}
|
||||
{error && <p className="banner error">{error}</p>}
|
||||
{check === "error" && <p className="error">Unable to reach the repository.</p>}
|
||||
{check && check !== "checking" && check !== "error" && (
|
||||
check.pinned ? (
|
||||
<p className="muted">This installation is pinned to a fixed version and is not updated from the branch.</p>
|
||||
) : check.changes.length === 0 ? (
|
||||
<p className="ok">Up to date{check.latest ? ` (${check.latest})` : ""}.</p>
|
||||
) : (
|
||||
<div>
|
||||
<p>
|
||||
{check.changes.length === 1 ? "1 new change" : `${check.changes.length} new changes`} (
|
||||
<code>{check.current}</code> → <code>{check.latest}</code>):
|
||||
</p>
|
||||
<ul className="changes">
|
||||
{check.changes.map((change) => (
|
||||
<li key={change.commit}>
|
||||
<code>{change.commit}</code> {change.subject}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
<div className="actions">
|
||||
<button
|
||||
disabled={following || check === "checking"}
|
||||
onClick={() => {
|
||||
setCheck("checking");
|
||||
api.checkUpdate().then(setCheck, () => setCheck("error"));
|
||||
}}
|
||||
>
|
||||
{check === "checking" ? "Checking…" : "Check for updates"}
|
||||
</button>
|
||||
<button className="primary" disabled={following} onClick={() => setConfirming(true)}>
|
||||
Update now
|
||||
</button>
|
||||
</div>
|
||||
{status.log && (following || watch?.phase === "failed" || watch?.phase === "done" || !watch) && (
|
||||
<details open={following || watch?.phase === "failed"}>
|
||||
<summary>{following ? "Update output" : "Output of the last update"}</summary>
|
||||
<pre ref={logRef} className="update-log">
|
||||
{status.log}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{confirming && (
|
||||
<Dialog title="Update ShellBook?" onClose={() => setConfirming(false)}>
|
||||
<p>
|
||||
Downloads the installer from the repository, pulls the newest version, rebuilds and restarts ShellBook. Running
|
||||
steps are interrupted by the restart; terminal sessions keep running.
|
||||
</p>
|
||||
<div className="dialog-actions">
|
||||
<button onClick={() => setConfirming(false)}>Cancel</button>
|
||||
<button className="primary" onClick={() => void start()}>
|
||||
Update now
|
||||
</button>
|
||||
</div>
|
||||
</Dialog>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,9 @@ import type {
|
||||
SessionSettingsResponse,
|
||||
ClaudeStatusResponse,
|
||||
SystemInfoResponse,
|
||||
UpdateCheckResponse,
|
||||
UpdateStartResponse,
|
||||
UpdateStatusResponse,
|
||||
} from "@shellbook/core";
|
||||
import { HttpError } from "./api";
|
||||
async function request<T>(path: string, body?: unknown): Promise<T> {
|
||||
@@ -29,4 +32,7 @@ export const settingsApi = {
|
||||
session: () => request<SessionSettingsResponse>("/settings/session"),
|
||||
claude: () => request<ClaudeStatusResponse>("/settings/claude"),
|
||||
system: () => request<SystemInfoResponse>("/settings/system"),
|
||||
updateStatus: () => request<UpdateStatusResponse>("/settings/update"),
|
||||
checkUpdate: () => request<UpdateCheckResponse>("/settings/update/check", {}),
|
||||
startUpdate: () => request<UpdateStartResponse>("/settings/update", {}),
|
||||
};
|
||||
|
||||
@@ -971,6 +971,38 @@ pre.script {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.update-panel .changes {
|
||||
margin: 0 0 12px;
|
||||
padding-left: 18px;
|
||||
max-height: 240px;
|
||||
overflow: auto;
|
||||
}
|
||||
.update-panel .changes code {
|
||||
color: var(--muted);
|
||||
}
|
||||
.update-panel details {
|
||||
margin-top: 12px;
|
||||
}
|
||||
.update-panel summary {
|
||||
cursor: pointer;
|
||||
color: var(--muted);
|
||||
}
|
||||
pre.update-log {
|
||||
background: var(--code);
|
||||
margin: 8px 0 0;
|
||||
padding: 12px 14px;
|
||||
max-height: 320px;
|
||||
overflow: auto;
|
||||
border-radius: 6px;
|
||||
font:
|
||||
12.5px/1.6 "Cascadia Code",
|
||||
Consolas,
|
||||
monospace;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
user-select: text;
|
||||
}
|
||||
|
||||
/* Sign-in */
|
||||
.login {
|
||||
max-width: 360px;
|
||||
|
||||
@@ -67,10 +67,19 @@ it("renders system/session/Claude information and opens the terminal", async ()
|
||||
version: "Claude 1",
|
||||
loginAppearsPresent: true,
|
||||
});
|
||||
vi.spyOn(settingsApi, "updateStatus").mockResolvedValue({
|
||||
available: true,
|
||||
state: "idle",
|
||||
current: "abc1234",
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
log: "",
|
||||
});
|
||||
const revoke = vi.spyOn(settingsApi, "revoke").mockResolvedValue();
|
||||
const open = vi.fn();
|
||||
render(<SettingsPage openTerminal={open} />);
|
||||
expect(await screen.findByText("/workspace")).toBeInTheDocument();
|
||||
expect(await screen.findByRole("button", { name: "Update now" })).toBeInTheDocument();
|
||||
expect(screen.getByText(/86400 seconds/)).toBeInTheDocument();
|
||||
expect(screen.getByText("Available: Claude 1")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByText("Open terminal to log in"));
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import type { UpdateStatusResponse } from "@shellbook/core";
|
||||
import { UpdatePanel } from "../UpdatePanel";
|
||||
|
||||
const idle: UpdateStatusResponse = {
|
||||
available: true,
|
||||
state: "idle",
|
||||
current: "abc1234",
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
log: "",
|
||||
};
|
||||
|
||||
function fakeApi(statuses: (UpdateStatusResponse | Error)[]) {
|
||||
let index = 0;
|
||||
return {
|
||||
// Returns the statuses in order and then keeps returning the last one.
|
||||
updateStatus: vi.fn(async () => {
|
||||
const next = statuses[Math.min(index++, statuses.length - 1)]!;
|
||||
if (next instanceof Error) throw next;
|
||||
return next;
|
||||
}),
|
||||
checkUpdate: vi.fn(),
|
||||
startUpdate: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
it("explains the manual update when the trigger is not installed", async () => {
|
||||
const api = fakeApi([{ ...idle, available: false }]);
|
||||
render(<UpdatePanel api={api} />);
|
||||
expect(await screen.findByText("abc1234")).toBeInTheDocument();
|
||||
expect(screen.getByText(/not set up on this installation/)).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Update now" })).toBeNull();
|
||||
});
|
||||
|
||||
it("lists the commits an update would bring, or says it is up to date", async () => {
|
||||
const api = fakeApi([idle]);
|
||||
api.checkUpdate
|
||||
.mockResolvedValueOnce({
|
||||
current: "abc1234",
|
||||
latest: "def5678",
|
||||
pinned: false,
|
||||
changes: [
|
||||
{ commit: "def5678", subject: "feat(web): newer" },
|
||||
{ commit: "bbb0000", subject: "fix: older" },
|
||||
],
|
||||
})
|
||||
.mockResolvedValueOnce({ current: "def5678", latest: "def5678", pinned: false, changes: [] })
|
||||
.mockResolvedValueOnce({ current: "abc1234", latest: null, pinned: true, changes: [] })
|
||||
.mockRejectedValueOnce(new Error("502"));
|
||||
render(<UpdatePanel api={api} />);
|
||||
const check = await screen.findByRole("button", { name: "Check for updates" });
|
||||
fireEvent.click(check);
|
||||
expect(await screen.findByText(/2 new changes/)).toBeInTheDocument();
|
||||
expect(screen.getByText("feat(web): newer")).toBeInTheDocument();
|
||||
fireEvent.click(check);
|
||||
expect(await screen.findByText("Up to date (def5678).")).toBeInTheDocument();
|
||||
fireEvent.click(check);
|
||||
expect(await screen.findByText(/pinned to a fixed version/)).toBeInTheDocument();
|
||||
fireEvent.click(check);
|
||||
expect(await screen.findByText("Unable to reach the repository.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("asks first, then follows the update through the restart and offers a reload", async () => {
|
||||
const requestedAt = new Date().toISOString();
|
||||
const startedAt = new Date(Date.parse(requestedAt) + 1000).toISOString();
|
||||
const api = fakeApi([
|
||||
idle,
|
||||
{ ...idle, state: "running", startedAt, log: "Pulling…\nBuilding…" },
|
||||
new Error("502"),
|
||||
{ ...idle, state: "succeeded", current: "def5678", startedAt, finishedAt: startedAt, log: "Done" },
|
||||
]);
|
||||
api.startUpdate.mockResolvedValue({ requestedAt });
|
||||
render(<UpdatePanel api={api} pollMs={5} />);
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Update now" }));
|
||||
// Nothing starts before the confirmation.
|
||||
const dialog = screen.getByRole("dialog", { name: "Update ShellBook?" });
|
||||
expect(api.startUpdate).not.toHaveBeenCalled();
|
||||
fireEvent.click(within(dialog).getByRole("button", { name: "Update now" }));
|
||||
await waitFor(() => expect(api.startUpdate).toHaveBeenCalledOnce());
|
||||
expect(await screen.findByText(/Building…/)).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Update now" })).toBeDisabled();
|
||||
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Update finished (def5678)"));
|
||||
expect(screen.getByRole("button", { name: "Reload" })).toBeInTheDocument();
|
||||
// The restart in between was shown instead of an error.
|
||||
expect(screen.queryByText(/Unable to load/)).toBeNull();
|
||||
});
|
||||
|
||||
it("does not mistake the previous run for the requested one", async () => {
|
||||
const requestedAt = new Date().toISOString();
|
||||
const old = new Date(Date.parse(requestedAt) - 3_600_000).toISOString();
|
||||
const api = fakeApi([{ ...idle, state: "succeeded", startedAt: old, finishedAt: old, log: "old run" }]);
|
||||
api.startUpdate.mockResolvedValue({ requestedAt });
|
||||
render(<UpdatePanel api={api} pollMs={5} />);
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Update now" }));
|
||||
fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Update now" }));
|
||||
await waitFor(() => expect(api.updateStatus.mock.calls.length).toBeGreaterThan(3));
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Starting the update…");
|
||||
});
|
||||
|
||||
it("shows a failed update with its log", async () => {
|
||||
const requestedAt = new Date().toISOString();
|
||||
const api = fakeApi([
|
||||
idle,
|
||||
{ ...idle, state: "failed", startedAt: requestedAt, finishedAt: requestedAt, log: "pnpm: build failed" },
|
||||
]);
|
||||
api.startUpdate.mockResolvedValue({ requestedAt });
|
||||
render(<UpdatePanel api={api} pollMs={5} />);
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Update now" }));
|
||||
fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Update now" }));
|
||||
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("The update failed"));
|
||||
expect(screen.getByText("pnpm: build failed")).toBeVisible();
|
||||
expect(screen.getByRole("button", { name: "Update now" })).toBeEnabled();
|
||||
});
|
||||
@@ -49,6 +49,14 @@ scripts from `/opt/shellbook`, which the service user (and the terminal panel)
|
||||
can modify. A failed build leaves the running service in place; check
|
||||
`journalctl -u shellbook`.
|
||||
|
||||
Settings → Updates shows the installed commit, checks the repository for new
|
||||
commits, and starts the same update with **Update now**, following its output
|
||||
through the restart. The button needs the trigger units the installer adds
|
||||
(`shellbook-update.path` watches `/var/lib/shellbook/update-request` and starts
|
||||
`shellbook-update.service` as root; output in `/var/log/shellbook-update.log`). Older
|
||||
installations get them with one `shellbook-update` run from the CLI. If the button
|
||||
does nothing, check `systemctl status shellbook-update.path shellbook-update`.
|
||||
|
||||
Configuration is `/etc/shellbook/env`; data is `/var/lib/shellbook` (back it up
|
||||
along with workspace and service-user home). `SHELLBOOK_SESSION_SECONDS` defaults
|
||||
to 2592000 (30 days). Cookies survive restart. Logout clears the browser cookie;
|
||||
|
||||
@@ -120,6 +120,33 @@ PATH=/home/shellbook/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||
EOF
|
||||
fi
|
||||
chmod 600 /etc/shellbook/env
|
||||
# Updates from the web UI (#15). The service stays unprivileged and may only change a
|
||||
# request file in its data directory; systemd then runs the fixed root-owned updater
|
||||
# above. Its output goes to root-owned /var/log, readable by the service.
|
||||
data_dir=$(sed -n 's/^SHELLBOOK_DATA_DIR=//p' /etc/shellbook/env)
|
||||
[[ $data_dir =~ ^/[A-Za-z0-9._/-]+$ ]] || { echo 'Invalid SHELLBOOK_DATA_DIR' >&2; exit 1; }
|
||||
cat > /etc/systemd/system/shellbook-update.service <<'EOF'
|
||||
[Unit]
|
||||
Description=Update ShellBook (requested from the web UI)
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/local/sbin/shellbook-update
|
||||
StandardOutput=truncate:/var/log/shellbook-update.log
|
||||
StandardError=inherit
|
||||
TimeoutStartSec=30min
|
||||
EOF
|
||||
cat > /etc/systemd/system/shellbook-update.path <<EOF
|
||||
[Unit]
|
||||
Description=Start a ShellBook update when the web UI requests one
|
||||
|
||||
[Path]
|
||||
PathChanged=$data_dir/update-request
|
||||
Unit=shellbook-update.service
|
||||
|
||||
[Install]
|
||||
WantedBy=paths.target
|
||||
EOF
|
||||
cat > /etc/systemd/system/shellbook.service <<'EOF'
|
||||
[Unit]
|
||||
Description=ShellBook runbook server
|
||||
@@ -162,6 +189,7 @@ if [[ -n ${TS_AUTHKEY:-} ]]; then
|
||||
fi
|
||||
systemctl daemon-reload
|
||||
systemctl enable shellbook
|
||||
systemctl enable --now shellbook-update.path
|
||||
systemctl restart shellbook
|
||||
# Wait until the server answers before reporting success.
|
||||
listen_host=$(sed -n 's/^SHELLBOOK_HOST=//p' /etc/shellbook/env)
|
||||
|
||||
@@ -37,4 +37,17 @@ tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
|
||||
[[ ! -e $tmp/w/notebooks/infra/lxc.md ]] || { echo 'offer_templates: deleted template came back' >&2; exit 1; }
|
||||
[[ $(sort "$tmp/offered" | tr '\n' ' ') == 'notebooks/a.md notebooks/infra/lxc.md ' ]] || { echo 'offer_templates: wrong list' >&2; exit 1; }
|
||||
)
|
||||
printf '9 install script checks passed\n'
|
||||
# Updates from the web UI: the service only touches a request file; root runs the fixed updater.
|
||||
unit_body() { sed -n "/^cat > \/etc\/systemd\/system\/$1 <<'\{0,1\}EOF'\{0,1\}$/,/^EOF$/p" "$dir/install.sh" | sed '1d;$d'; }
|
||||
update_service=$(unit_body shellbook-update.service)
|
||||
update_path=$(unit_body shellbook-update.path)
|
||||
[[ -n $update_service && -n $update_path ]] || { echo 'install.sh: update units not generated' >&2; exit 1; }
|
||||
grep -qxF 'ExecStart=/usr/local/sbin/shellbook-update' <<< "$update_service" || { echo 'update unit: wrong ExecStart' >&2; exit 1; }
|
||||
grep -qxF 'Type=oneshot' <<< "$update_service" || { echo 'update unit: not oneshot' >&2; exit 1; }
|
||||
[[ $update_service$update_path != */opt/shellbook* ]] || { echo 'update units: reference /opt/shellbook' >&2; exit 1; }
|
||||
# Root writes its output only below root-owned /var/log, never into the service user's data dir.
|
||||
grep -qxF 'StandardOutput=truncate:/var/log/shellbook-update.log' <<< "$update_service" || { echo 'update unit: log not in /var/log' >&2; exit 1; }
|
||||
grep -qxF 'PathChanged=$data_dir/update-request' <<< "$update_path" || { echo 'update path unit: wrong request file' >&2; exit 1; }
|
||||
grep -qxF 'Unit=shellbook-update.service' <<< "$update_path" || { echo 'update path unit: wrong unit' >&2; exit 1; }
|
||||
grep -qxF 'systemctl enable --now shellbook-update.path' "$dir/install.sh" || { echo 'install.sh: update trigger not enabled' >&2; exit 1; }
|
||||
printf '17 install script checks passed\n'
|
||||
|
||||
@@ -276,6 +276,14 @@ checks and responses disable caching.
|
||||
service user home; credential contents are never read or returned.
|
||||
- Listens on `127.0.0.1` or LAN; intended behind Traefik + firewall (LAN/Tailscale only).
|
||||
- Terminal panel = shell as the service user: same trust level as the app itself.
|
||||
- Self-update from Settings never gives the service privileges: POST
|
||||
`/api/settings/update` only writes `<data dir>/update-request`. A root-owned systemd
|
||||
path unit starts the oneshot `shellbook-update.service`, which runs the fixed
|
||||
root-owned `/usr/local/sbin/shellbook-update` (it fetches the installer from the
|
||||
repository and never executes the service-writable checkout) and writes its output
|
||||
to `/var/log/shellbook-update.log`. The server reads state only through
|
||||
`systemctl show` and that log; "check for updates" runs `git fetch` into
|
||||
`FETCH_HEAD` only. A request can only start that fixed updater, nothing else.
|
||||
- No secrets in notebooks, audit log or artifacts metadata.
|
||||
|
||||
## 8. Architecture
|
||||
|
||||
@@ -145,6 +145,33 @@ export interface SessionSettingsResponse { lifetimeSeconds: number }
|
||||
export interface ClaudeStatusResponse { available: boolean; version: string | null; loginAppearsPresent: boolean }
|
||||
export interface SystemInfoResponse { version: string; workspacePath: string; dataDirPath: string; nodeVersion: string }
|
||||
|
||||
// Self-update from the UI (#15). The service stays unprivileged: POST only touches a
|
||||
// request file that a root-owned systemd path unit watches (deploy/install.sh).
|
||||
// GET /api/settings/update
|
||||
export type UpdateState = "idle" | "running" | "succeeded" | "failed" | "unknown";
|
||||
export interface UpdateStatusResponse {
|
||||
/** The trigger units are installed; otherwise updates need `shellbook-update` as root. */
|
||||
available: boolean;
|
||||
state: UpdateState;
|
||||
/** Installed commit (short hash) when the app runs from a git checkout. */
|
||||
current: string | null;
|
||||
startedAt: string | null;
|
||||
finishedAt: string | null;
|
||||
/** End of the last update's output. */
|
||||
log: string;
|
||||
}
|
||||
// POST /api/settings/update/check: fetches the tracked branch, changes nothing else.
|
||||
export interface UpdateCheckResponse {
|
||||
current: string | null;
|
||||
latest: string | null;
|
||||
/** The checkout is pinned to a ref (SHELLBOOK_REF) and is never pulled. */
|
||||
pinned: boolean;
|
||||
/** Commits the update would bring, newest first (at most 50). */
|
||||
changes: { commit: string; subject: string }[];
|
||||
}
|
||||
// POST /api/settings/update: 202, or 409 when unavailable or already running.
|
||||
export interface UpdateStartResponse { requestedAt: string }
|
||||
|
||||
// ---- notebook management (#9) ------------------------------------------------
|
||||
// Paths are relative to notebooks/. Mutations return 409 on stale versions or occupied targets.
|
||||
// POST /api/notebooks
|
||||
|
||||
Reference in New Issue
Block a user