feat(settings): add browser setup and administration (#10)

This commit is contained in:
Florian Schmidt
2026-11-16 10:15:04 +01:00
parent 4fe7e4e376
commit 02a22bef40
20 changed files with 939 additions and 24 deletions
+18 -3
View File
@@ -1,3 +1,7 @@
import { HeaderNavigation, type NavigationPage } from "./HeaderNavigation";
import { SettingsPage } from "./SettingsPage";
import { SetupScreen } from "./SetupScreen";
import { settingsApi } from "./settingsApi";
import {
lazy,
Suspense,
@@ -46,7 +50,8 @@ function steps(blocks: Block[]): Step[] {
);
}
export function App({ api }: { api: Api }) {
const [auth, setAuth] = useState<"loading" | "login" | "ready">("loading");
const [auth, setAuth] = useState<"loading" | "login" | "setup" | "ready">("loading");
const [page, setPage] = useState<NavigationPage>("Notebooks");
const [password, setPassword] = useState("");
const [list, setList] = useState<NotebookSummary[]>([]);
const [hosts, setHosts] = useState<HostInfo[]>([]);
@@ -103,8 +108,12 @@ export function App({ api }: { api: Api }) {
.me()
.then(() => setAuth("ready"))
.catch((e) => {
if (e instanceof HttpError && e.status === 401) setAuth("login");
else setError(String(e));
if (e instanceof HttpError && e.status === 401) {
setAuth("login");
void settingsApi.setupStatus()
.then(status => { if (status.required) setAuth("setup"); })
.catch(() => {});
} else setError(String(e));
});
}, [api]);
useEffect(() => {
@@ -281,6 +290,7 @@ export function App({ api }: { api: Api }) {
const keyPrompt = Object.values(session.runs).find(
(run) => run.status === "hostKey" && requests.current.has(run.runId),
);
if (auth === "setup") return <SetupScreen onComplete={() => setAuth("ready")} />;
if (auth === "login")
return (
<main className="login">
@@ -347,6 +357,10 @@ export function App({ api }: { api: Api }) {
</small>
</aside>
<main>
<HeaderNavigation page={page} onChange={setPage} />
{page === "Settings" && <SettingsPage openTerminal={() => { setTerminalOpened(true); setTerminal(true); }} />}
{page === "Hosts" && <p>Host management will appear here.</p>}
<div hidden={page !== "Notebooks"}>
<div className="toolbar">
<span>{doc?.notebook.title ?? "Loading workspace…"}</span>
<button onClick={() => setEdit(!edit)}>
@@ -468,6 +482,7 @@ export function App({ api }: { api: Api }) {
</div>
</>
)}
</div>
</main>
{terminalOpened && (
<Suspense fallback={<p>Loading terminal...</p>}>
+24
View File
@@ -0,0 +1,24 @@
// Feature navigation: add entries here and mount their view in App. Hosts is a placeholder for #7.
export const navigationItems = ["Notebooks", "Hosts", "Settings"] as const;
export type NavigationPage = (typeof navigationItems)[number];
export function HeaderNavigation({
page,
onChange,
}: {
page: NavigationPage;
onChange: (page: NavigationPage) => void;
}) {
return (
<nav aria-label="Main navigation">
{navigationItems.map((item) => (
<button
key={item}
aria-current={page === item ? "page" : undefined}
onClick={() => onChange(item)}
>
{item}
</button>
))}
</nav>
);
}
+98
View File
@@ -0,0 +1,98 @@
import { useState } from "react";
import type { ChangePasswordRequest, SetupRequest } from "@shellbook/core";
export function PasswordForm({
setup = false,
submit,
}: {
setup?: boolean;
submit: (body: ChangePasswordRequest & SetupRequest) => Promise<void>;
}) {
const [token, setToken] = useState("");
const [currentPassword, setCurrent] = useState("");
const [newPassword, setNew] = useState("");
const [confirmPassword, setConfirm] = useState("");
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState("");
return (
<form
onSubmit={async (event) => {
event.preventDefault();
if (newPassword !== confirmPassword) {
setMessage("Passwords do not match");
return;
}
setBusy(true);
setMessage("");
try {
await submit({
token,
currentPassword,
newPassword,
confirmPassword,
});
setToken("");
setCurrent("");
setNew("");
setConfirm("");
setMessage("Password saved. Other sessions have been signed out.");
} catch {
setMessage(
"Unable to save. Check your credentials and try again; too many attempts require waiting a minute.",
);
} finally {
setBusy(false);
}
}}
>
{setup ? (
<label>
Setup token
<input
required
autoComplete="off"
value={token}
onChange={(e) => setToken(e.target.value)}
/>
</label>
) : (
<label>
Current password
<input
required
type="password"
autoComplete="current-password"
value={currentPassword}
onChange={(e) => setCurrent(e.target.value)}
/>
</label>
)}
<label>
New password
<input
required
type="password"
minLength={12}
autoComplete="new-password"
value={newPassword}
onChange={(e) => setNew(e.target.value)}
/>
</label>
<label>
Confirm password
<input
required
type="password"
minLength={12}
autoComplete="new-password"
value={confirmPassword}
onChange={(e) => setConfirm(e.target.value)}
/>
</label>
<p>Use at least 12 characters (maximum 4096 bytes).</p>
<button disabled={busy}>
{setup ? "Set up ShellBook" : "Change password"}
</button>
{message && <p role="status">{message}</p>}
</form>
);
}
+110
View File
@@ -0,0 +1,110 @@
import { useEffect, useState } from "react";
import type {
ClaudeStatusResponse,
SystemInfoResponse,
SessionSettingsResponse,
} from "@shellbook/core";
import { settingsApi } from "./settingsApi";
import { PasswordForm } from "./PasswordForm";
export function SettingsPage({ openTerminal }: { openTerminal: () => void }) {
const [info, setInfo] = useState<SystemInfoResponse>();
const [claude, setClaude] = useState<ClaudeStatusResponse>();
const [session, setSession] = useState<SessionSettingsResponse>();
const [message, setMessage] = useState("");
const [busy, setBusy] = useState(false);
useEffect(() => {
let active = true;
Promise.all([
settingsApi.system(),
settingsApi.claude(),
settingsApi.session(),
])
.then(([i, c, s]) => {
if (active) {
setInfo(i);
setClaude(c);
setSession(s);
}
})
.catch(() => {
if (active)
setMessage("Unable to load settings. Sign in again or retry.");
});
return () => {
active = false;
};
}, []);
return (
<div className="notebook">
<h1>Settings</h1>
<section>
<h2>Password and sessions</h2>
<PasswordForm submit={settingsApi.password} />
{session && (
<p>
Session lifetime: {session.lifetimeSeconds} seconds (
{session.lifetimeSeconds / 86400} days).
</p>
)}
<button
disabled={busy}
onClick={async () => {
setBusy(true);
try {
await settingsApi.revoke();
setMessage(
"Other sessions signed out. This browser remains signed in.",
);
} catch {
setMessage("Unable to sign out sessions. Try again.");
} finally {
setBusy(false);
}
}}
>
Sign out all sessions
</button>
</section>
<section>
<h2>Claude CLI</h2>
{claude ? (
<>
<p>
{claude.available
? `Available: ${claude.version}`
: "Claude is unavailable on PATH or did not respond."}
</p>
<p>
{claude.loginAppearsPresent
? "Credentials file exists; login may be available."
: "No credentials file found."}
</p>
</>
) : (
<p>Checking CLI...</p>
)}
<button onClick={openTerminal}>Open terminal to log in</button>
<p>
Run <code>claude</code>, then <code>/login</code>. Credentials are
checked for existence only.
</p>
</section>
<section>
<h2>About/System</h2>
{info && (
<dl>
<dt>ShellBook version</dt>
<dd>{info.version}</dd>
<dt>Workspace</dt>
<dd>{info.workspacePath}</dd>
<dt>Data directory</dt>
<dd>{info.dataDirPath}</dd>
<dt>Node version</dt>
<dd>{info.nodeVersion}</dd>
</dl>
)}
</section>
{message && <p role="status">{message}</p>}
</div>
);
}
+20
View File
@@ -0,0 +1,20 @@
import { PasswordForm } from "./PasswordForm";
import { settingsApi } from "./settingsApi";
export function SetupScreen({ onComplete }: { onComplete: () => void }) {
return (
<main className="login">
<h1>Set up ShellBook</h1>
<p>
Enter the one-time token from the setup-token file in the server data
directory.
</p>
<PasswordForm
setup
submit={async (body) => {
await settingsApi.setup(body);
onComplete();
}}
/>
</main>
);
}
+31
View File
@@ -0,0 +1,31 @@
import type {
SetupStatusResponse,
SetupRequest,
ChangePasswordRequest,
SessionSettingsResponse,
ClaudeStatusResponse,
SystemInfoResponse,
} from "@shellbook/core";
import { HttpError } from "./api";
async function request<T>(path: string, body?: unknown): Promise<T> {
const response = await fetch(`/api${path}`, {
method: body === undefined ? "GET" : "POST",
credentials: "same-origin",
headers: body === undefined ? {} : { "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
if (!response.ok) throw new HttpError(response.status);
return response.status === 204
? (undefined as T)
: (response.json() as Promise<T>);
}
export const settingsApi = {
setupStatus: () => request<SetupStatusResponse>("/auth/setup"),
setup: (body: SetupRequest) => request<void>("/auth/setup", body),
password: (body: ChangePasswordRequest) =>
request<void>("/settings/password", body),
revoke: () => request<void>("/settings/sessions/revoke", {}),
session: () => request<SessionSettingsResponse>("/settings/session"),
claude: () => request<ClaudeStatusResponse>("/settings/claude"),
system: () => request<SystemInfoResponse>("/settings/system"),
};
+91
View File
@@ -0,0 +1,91 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
import { PasswordForm } from "../PasswordForm";
import { SetupScreen } from "../SetupScreen";
import { SettingsPage } from "../SettingsPage";
import { HeaderNavigation } from "../HeaderNavigation";
import { settingsApi } from "../settingsApi";
afterEach(() => vi.restoreAllMocks());
function fill(label: string, value: string) {
fireEvent.change(screen.getByLabelText(label), { target: { value } });
}
it("validates confirmation and clears credentials after setup", async () => {
const submit = vi.fn().mockResolvedValue(undefined);
render(<PasswordForm setup submit={submit} />);
fill("Setup token", "token");
fill("New password", "long password here");
fill("Confirm password", "wrong password here");
fireEvent.click(screen.getByRole("button", { name: "Set up ShellBook" }));
expect(await screen.findByText("Passwords do not match")).toBeInTheDocument();
expect(submit).not.toHaveBeenCalled();
fill("Confirm password", "long password here");
fireEvent.click(screen.getByRole("button", { name: "Set up ShellBook" }));
await waitFor(() =>
expect(submit).toHaveBeenCalledWith({
token: "token",
currentPassword: "",
newPassword: "long password here",
confirmPassword: "long password here",
}),
);
await waitFor(() =>
expect(screen.getByLabelText("New password")).toHaveValue(""),
);
});
it("submits setup and enters the app", async () => {
vi.spyOn(settingsApi, "setup").mockResolvedValue();
const done = vi.fn();
render(<SetupScreen onComplete={done} />);
fill("Setup token", "token");
fill("New password", "long password here");
fill("Confirm password", "long password here");
fireEvent.click(screen.getByRole("button", { name: "Set up ShellBook" }));
await waitFor(() => expect(done).toHaveBeenCalledOnce());
});
it("shows password failure and preserves the form for retry", async () => {
render(
<PasswordForm submit={vi.fn().mockRejectedValue(new Error("invalid"))} />,
);
fill("Current password", "wrong");
fill("New password", "long password here");
fill("Confirm password", "long password here");
fireEvent.click(screen.getByRole("button", { name: "Change password" }));
expect(await screen.findByRole("status")).toHaveTextContent("Unable to save");
});
it("renders system/session/Claude information and opens the terminal", async () => {
vi.spyOn(settingsApi, "system").mockResolvedValue({
version: "1.2",
workspacePath: "/workspace",
dataDirPath: "/data",
nodeVersion: "v22",
});
vi.spyOn(settingsApi, "session").mockResolvedValue({
lifetimeSeconds: 86400,
});
vi.spyOn(settingsApi, "claude").mockResolvedValue({
available: true,
version: "Claude 1",
loginAppearsPresent: true,
});
const revoke = vi.spyOn(settingsApi, "revoke").mockResolvedValue();
const open = vi.fn();
render(<SettingsPage openTerminal={open} />);
expect(await screen.findByText("/workspace")).toBeInTheDocument();
expect(screen.getByText(/86400 seconds/)).toBeInTheDocument();
expect(screen.getByText("Available: Claude 1")).toBeInTheDocument();
fireEvent.click(screen.getByText("Open terminal to log in"));
expect(open).toHaveBeenCalledOnce();
fireEvent.click(screen.getByText("Sign out all sessions"));
await waitFor(() => expect(revoke).toHaveBeenCalledOnce());
expect(await screen.findByRole("status")).toHaveTextContent(
"This browser remains signed in",
);
});
it("provides the shared feature navigation", () => {
const change = vi.fn();
render(<HeaderNavigation page="Notebooks" onChange={change} />);
fireEvent.click(screen.getByText("Settings"));
expect(change).toHaveBeenCalledWith("Settings");
expect(screen.getByText("Hosts")).toBeInTheDocument();
expect(screen.getByText("Notebooks")).toHaveAttribute("aria-current", "page");
});