Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.
JavaScript ai-codingclaudeclaude-codeclaude-code-pluginclicoding-agentsdeveloper-toolsgitllmtypescript
feat(settings): one modal on every page, opened from the top bar
Eren441e03db8ff1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex da1e34c..f76f1ff 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).## [Unreleased]+### Added+- Settings modal on every page: a ⚙ Settings button in the top bar of both the project map and the panel opens the same dialog (close with ×, Esc or a click outside; focus moves into the dialog and back to the button), with one help line per setting and a "Saved" line per change. The panel's old settings box at the bottom is gone. The dialog reads the current values with `GET /api/config` (same Host / Origin / token checks as the write, and only the editable keys), and the local server now puts its per-start token in map pages too, so a map built before a change still shows the current value; over `file://` it shows the values embedded at build time read-only with a hint to use `codelineage open` or `codelineage config set`.+### Changed- Map: the page head spans the window like the map; "Unfold all" opens every session and every folded branch, "Fold all" closes them and frames the whole map again; the outline is open by default.diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.tsindex 2eb8c86..a5af873 100644--- a/packages/cli/src/commands/build.ts+++ b/packages/cli/src/commands/build.ts@@ -23,7 +23,12 @@ import { loadAllSessions, loadConfig, loadProject } from "../store/stores.js";import { type ChatTurn, displayTurn, excerpt, readConversation } from "../transcript.js";import { buildViewModel, embedViewModel } from "../view/lineage.js";import type { LineageViewModel, ViewChatTurn, ViewPendingMessage } from "../view/model.js";-import { buildPanel, type CollectedProject, collectRegistryProjects } from "../view/panel.js";+import {+ buildPanel,+ type CollectedProject,+ collectRegistryProjects,+ panelSettings,+} from "../view/panel.js";import { switcherEntries } from "../view/switcher.js";import { TEMPLATE_HTML } from "../view/template.js";import { collectTranscripts } from "../view/transcripts.js";@@ -257,6 +262,9 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModelchats: views.chats,pending: views.pending,commitSubjects: subjects,+ // Over `file://` the settings modal shows these; a server page reads the+ // live values instead, so a map built before a change still agrees.+ settings: panelSettings(config),// With the catch-up on, the hook records the tail at session end, so the// count would only be a stale warning about work already scheduled.unrecorded: config.sessionEndCatchUp ? undefined : views.unrecorded,diff --git a/packages/cli/src/server.ts b/packages/cli/src/server.tsindex c093bfa..528cdfd 100644--- a/packages/cli/src/server.ts+++ b/packages/cli/src/server.ts@@ -16,13 +16,9 @@ import { Config } from "./schema/config.js";import { LockBusyError } from "./store/lock.js";import { globalPaths, projectPaths } from "./store/paths.js";import { loadConfig, loadRegistry, updateConfig } from "./store/stores.js";-import {- isPanelEditableKey,- LIVE_META_NAME,- type PanelEditableKey,- TOKEN_META_NAME,-} from "./view/model.js";-import { buildPanel } from "./view/panel.js";+import { isPanelEditableKey, LIVE_META_NAME, TOKEN_META_NAME } from "./view/model.js";+import { buildPanel, panelSettings } from "./view/panel.js";+import { editableSettings } from "./view/settings.js";/** A page nobody is looking at is a dead server after this long. */export const DEFAULT_IDLE_MS = 30 * 60 * 1000;@@ -50,8 +46,9 @@ export function injectLiveMeta(html: string): string {}/**- * Carries the per-server token into the served panel page. Only the panel needs- * it (it is the only page that writes); maps get no token at all.+ * Carries the per-server token into every page the server serves (Story 8.13):+ * both the panel and each project map open a settings modal that reads and+ * writes through `/api/config`.*/export function injectTokenMeta(html: string, token: string): string {const meta = `<meta name="${TOKEN_META_NAME}" content="${token}">`;@@ -83,8 +80,6 @@ interface PageTarget {file: string;/** Directory to watch: atomic writes replace the file, the directory keeps its name. */dir: string;- /** Only the panel page gets the settings token. */- panel: boolean;}interface WatchedPage {@@ -121,7 +116,7 @@ async function registeredRoot(env: NodeJS.ProcessEnv, dir: string): Promise<striasync function pageTarget(env: NodeJS.ProcessEnv, url: URL): Promise<PageTarget | null> {const panel = (): PageTarget => {const paths = globalPaths(env);- return { file: paths.panel, dir: paths.base, panel: true };+ return { file: paths.panel, dir: paths.base };};if (url.pathname === "/") return panel();if (url.pathname === "/map" || url.pathname === "/events") {@@ -131,7 +126,7 @@ async function pageTarget(env: NodeJS.ProcessEnv, url: URL): Promise<PageTargetconst root = await registeredRoot(env, raw);if (!root) return null;const paths = projectPaths(root);- return { file: paths.html, dir: paths.base, panel: false };+ return { file: paths.html, dir: paths.base };}return null;}@@ -229,6 +224,14 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>return origin === `http://${HOST}:${port}` || origin === `http://localhost:${port}`;}+ /**+ * A same-origin GET carries no Origin header, so absence is fine; a present+ * Origin must still be this server (Story 8.13).+ */+ function readOriginAllowed(origin: string | undefined, port: number): boolean {+ return origin === undefined || originAllowed(origin, port);+ }+async function readLimitedBody(req: IncomingMessage): Promise<string | null> {const chunks: Buffer[] = [];let size = 0;@@ -281,8 +284,33 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>}/**- * `POST /api/config` { key, value }: the panel's only write. Host, Origin,- * content type and token all have to match, the key must be one the panel may+ * `GET /api/config`: the values the settings modal opens with (Story 8.13).+ * Same Host, Origin and token checks as the write, and only the keys the modal+ * may change; the setup-time keys never leave the config file.+ */+ async function readConfig(+ req: IncomingMessage,+ res: ServerResponse,+ port: number,+ ): Promise<void> {+ if (+ !readOriginAllowed(req.headers.origin, port) ||+ !tokenMatches(req.headers[CONFIG_TOKEN_HEADER])+ ) {+ respond(res, 403, "forbidden");+ return;+ }+ const config = await loadConfig(env);+ res.writeHead(200, {+ "content-type": "application/json",+ "cache-control": "no-store",+ });+ res.end(JSON.stringify({ ok: true, settings: editableSettings(panelSettings(config)) }));+ }++ /**+ * `POST /api/config` { key, value }: the modal's only write. Host, Origin,+ * content type and token all have to match, the key must be one the modal may* change and the value has to pass the config schema. Anything else is a 4xx* and the file stays untouched.*/@@ -371,6 +399,14 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>return;}const url = new URL(req.url ?? "/", `http://${HOST}:${port}`);+ if (url.pathname === "/api/config") {+ if (req.method !== "GET") {+ respond(res, 405, "method not allowed");+ return;+ }+ await readConfig(req, res, port);+ return;+ }if (url.pathname === "/health") {res.writeHead(200, {"content-type": "application/json",@@ -417,13 +453,7 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>"content-type": "text/html; charset=utf-8","cache-control": "no-store",});- res.end(- req.method === "HEAD"- ? undefined- : target.panel- ? injectTokenMeta(injectLiveMeta(html), token)- : injectLiveMeta(html),- );+ res.end(req.method === "HEAD" ? undefined : injectTokenMeta(injectLiveMeta(html), token));}await new Promise<void>((done, fail) => {diff --git a/packages/cli/src/view/lineage.ts b/packages/cli/src/view/lineage.tsindex cb5e859..f1fc0cc 100644--- a/packages/cli/src/view/lineage.ts+++ b/packages/cli/src/view/lineage.ts@@ -4,6 +4,7 @@ import {DATA_ELEMENT_ID,type LineageViewModel,type PageModel,+ type PanelSettings,type StatusCard,VIEW_SCHEMA,type ViewChatTurn,@@ -236,6 +237,8 @@ export interface ViewModelInput {pending?: ReadonlyMap<string, ViewPendingMessage[]> | undefined;/** Commit subjects read from git at build time (Story 8.8). */commitSubjects?: ReadonlyMap<string, string> | undefined;+ /** Settings embedded for the modal's `file://` view (Story 8.13). */+ settings?: PanelSettings | undefined;}/**@@ -308,6 +311,7 @@ export function buildViewModel(input: ViewModelInput): LineageViewModel {status: statusCard(sessions, input.generatedAt),epochs,unassigned,+ ...(input.settings === undefined ? {} : { settings: input.settings }),};}diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.tsindex a950e66..5659a89 100644--- a/packages/cli/src/view/model.ts+++ b/packages/cli/src/view/model.ts@@ -18,9 +18,10 @@ export const DATA_ELEMENT_ID = "codelineage-data";export const LIVE_META_NAME = "codelineage-live";/**- * Meta tag the local map server puts in the panel page: a random token for this- * server start that a settings write must echo. Other sites cannot read it, so- * they cannot post a change even when the host check is bypassed.+ * Meta tag the local map server puts in every page it serves: a random token+ * for this server start that a settings read or write must echo. Other sites+ * cannot read it, so they cannot post a change even when the host check is+ * bypassed. A `file://` page has no token and its settings stay read-only.*/export const TOKEN_META_NAME = "codelineage-token";@@ -232,6 +233,12 @@ export interface LineageViewModel {* have no switcher.*/switcher?: ViewSwitcherProject[];+ /**+ * Settings embedded at build time (Story 8.13). The settings modal shows them+ * read-only over `file://`; over the local server it reads the live values+ * instead. Absent on pages built before 8.13.+ */+ settings?: PanelSettings;}/** One project card in the global panel. */@@ -264,6 +271,12 @@ export interface PanelSettings {agents: string[];}+/**+ * The subset `GET /api/config` returns and a settings modal may change+ * (Story 8.13). Everything else stays on `codelineage config set`.+ */+export type PanelEditableSettings = Pick<PanelSettings, PanelEditableKey>;+export interface PanelViewModel {kind: "panel";schema: typeof VIEW_SCHEMA;diff --git a/packages/cli/src/view/panel.ts b/packages/cli/src/view/panel.tsindex 634aa17..09e255c 100644--- a/packages/cli/src/view/panel.ts+++ b/packages/cli/src/view/panel.ts@@ -1,13 +1,13 @@import { pathToFileURL } from "node:url";import type { Io } from "../io.js";import { redactDeep } from "../redact.js";-import type { RegistryEntry } from "../schema/config.js";+import type { Config, RegistryEntry } from "../schema/config.js";import type { Session } from "../schema/session.js";import { atomicWrite, isDirectory } from "../store/fs.js";import { globalPaths, projectPaths } from "../store/paths.js";import { loadAllSessions, loadConfig, loadRegistry } from "../store/stores.js";import { embedViewModel, statusCard } from "./lineage.js";-import { type PanelViewModel, VIEW_SCHEMA } from "./model.js";+import { type PanelSettings, type PanelViewModel, VIEW_SCHEMA } from "./model.js";import type { SwitcherSource } from "./switcher.js";import { TEMPLATE_HTML } from "./template.js";@@ -34,6 +34,24 @@ export type CollectedProject = SwitcherSource;const PANEL_TITLE = "<title>codelineage — panel</title>";+/**+ * The settings both pages embed (Stories 8.9, 8.13). The map needs them for the+ * settings modal over `file://`, the panel for its model; the server reads the+ * same values live through `GET /api/config`.+ */+export function panelSettings(config: Config): PanelSettings {+ return {+ language: config.language,+ updateEveryTurns: config.updateEveryTurns,+ sessionEndCatchUp: config.sessionEndCatchUp,+ catchUpModel: config.catchUpModel,+ messageSummaries: config.messageSummaries,+ startupContext: config.startupContext,+ gitPolicy: config.gitPolicy,+ agents: config.agents,+ };+}+/** The title of the newest message in a session, in send order. */function lastMessageTitle(session: Session): string {const messages = session.nodes.filter((node) => node.kind === "message");@@ -159,16 +177,7 @@ export async function buildPanel(opts: PanelOptions): Promise<PanelViewModel> {kind: "panel",schema: VIEW_SCHEMA,generatedAt,- settings: {- language: config.language,- updateEveryTurns: config.updateEveryTurns,- sessionEndCatchUp: config.sessionEndCatchUp,- catchUpModel: config.catchUpModel,- messageSummaries: config.messageSummaries,- startupContext: config.startupContext,- gitPolicy: config.gitPolicy,- agents: config.agents,- },+ settings: panelSettings(config),// `leftOff` belongs to the map's switcher; the panel page stays as it was.projects: projects.map(({ leftOff: _leftOff, ...project }) => project),};diff --git a/packages/cli/src/view/settings.ts b/packages/cli/src/view/settings.tsnew file mode 100644index 0000000..8fc2a53--- /dev/null+++ b/packages/cli/src/view/settings.ts@@ -0,0 +1,142 @@+import type { PanelEditableSettings, PanelSettings } from "./model.js";++/**+ * The settings modal's model (Story 8.13): one description per field, the+ * sections it is laid out in, and the values shown when the page was built+ * before the current setting changed. Runtime-free so the template can import+ * it and tests can check the modal without a DOM.+ */++/** What a setting's control looks like. */+export type SettingKind = "text" | "number" | "boolean";++export interface SettingField {+ key: keyof PanelSettings;+ label: string;+ /** One short line under the label, so nobody has to read the docs. */+ help: string;+ kind: SettingKind;+ /** False over `file://` and for the setup-time keys the modal only shows. */+ editable: boolean;+}++export interface SettingsSection {+ title: string;+ fields: SettingField[];+}++interface FieldSpec {+ key: keyof PanelSettings;+ label: string;+ help: string;+ kind: SettingKind;+}++const EDITABLE: FieldSpec[] = [+ {+ key: "messageSummaries",+ label: "Message summaries",+ help: "Write a one-line summary for each recorded message.",+ kind: "boolean",+ },+ {+ key: "startupContext",+ label: "Lineage at session start",+ help: "Hand the agent the previous session's lineage when a chat starts.",+ kind: "boolean",+ },+ {+ key: "language",+ label: "Language",+ help: "Language the agent writes records in; `auto` follows the chat.",+ kind: "text",+ },+ {+ key: "updateEveryTurns",+ label: "Update every turns",+ help: "Ask the agent to record after this many turns.",+ kind: "number",+ },+ {+ key: "sessionEndCatchUp",+ label: "Catch up on session end",+ help: "Record the unrecorded messages when a session ends.",+ kind: "boolean",+ },+ {+ key: "catchUpModel",+ label: "Catch-up model",+ help: "Model the catch-up and backfill use to summarize.",+ kind: "text",+ },+];++const READ_ONLY: FieldSpec[] = [+ {+ key: "gitPolicy",+ label: "Git policy",+ help: "Whether captures are committed to git; change it per project with `codelineage config set`.",+ kind: "text",+ },+ {+ key: "agents",+ label: "Agents",+ help: "Which agents record lineage; change it with `codelineage config set`.",+ kind: "text",+ },+];++/**+ * One section today, "Recording", so later groups slot in without a redesign.+ * Over `file://` (`canEdit` false) the editable fields still appear, read-only,+ * with the build-time values.+ */+export function settingsSections(canEdit: boolean): SettingsSection[] {+ return [+ {+ title: "Recording",+ fields: [+ ...EDITABLE.map((field) => ({ ...field, editable: canEdit })),+ ...READ_ONLY.map((field) => ({ ...field, editable: false })),+ ],+ },+ ];+}++/**+ * The values a modal starts with when no server answers (a `file://` page):+ * the defaults from the config schema, overridden by what the build embedded.+ */+export const DEFAULT_SETTINGS: PanelSettings = {+ language: "auto",+ updateEveryTurns: 5,+ sessionEndCatchUp: true,+ catchUpModel: "haiku",+ messageSummaries: false,+ startupContext: true,+ gitPolicy: "ignore",+ agents: ["claude-code"],+};++export function withDefaults(settings: Partial<PanelSettings> | undefined): PanelSettings {+ return { ...DEFAULT_SETTINGS, ...settings };+}++/** The keys `GET /api/config` returns; never the setup-time or security-adjacent ones. */+export function editableSettings(settings: PanelSettings): PanelEditableSettings {+ return {+ messageSummaries: settings.messageSummaries,+ startupContext: settings.startupContext,+ language: settings.language,+ updateEveryTurns: settings.updateEveryTurns,+ sessionEndCatchUp: settings.sessionEndCatchUp,+ catchUpModel: settings.catchUpModel,+ };+}++/** How a read-only value reads in the modal. */+export function formatSetting(value: PanelSettings[keyof PanelSettings] | undefined): string {+ if (Array.isArray(value)) return value.length > 0 ? value.join(", ") : "—";+ if (typeof value === "boolean") return value ? "yes" : "no";+ return value === undefined ? "—" : String(value);+}diff --git a/packages/cli/test/build.test.ts b/packages/cli/test/build.test.tsindex d16d8a8..2941698 100644--- a/packages/cli/test/build.test.ts+++ b/packages/cli/test/build.test.ts@@ -504,6 +504,19 @@ describe("codelineage build", () => {expect(embedded(html)).toEqual(model);});+ it("embeds the current settings in the map for the file:// modal", async () => {+ await configSet("messageSummaries", "true", io);+ const model = await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });+ expect(model.settings).toMatchObject({+ messageSummaries: true,+ startupContext: true,+ updateEveryTurns: 5,+ gitPolicy: "ignore",+ agents: ["claude-code"],+ });+ expect(embedded(await readFile(paths().html, "utf8"))).toEqual(model);+ });+it("puts the conversation of message sessions into the map, never into the record", async () => {const folder = join(dir, "claude", "projects", "-proj");await mkdir(folder, { recursive: true });diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.tsindex 8e7ca3c..e98b5f7 100644--- a/packages/cli/test/server.test.ts+++ b/packages/cli/test/server.test.ts@@ -139,6 +139,18 @@ function configWrite(});}+function configRead(+ server: MapServer,+ token: string,+ overrides: Record<string, string> = {},+): Promise<Reply> {+ return request(`${server.url}/api/config`, {+ origin: `http://127.0.0.1:${server.port}`,+ [CONFIG_TOKEN_HEADER]: token,+ ...overrides,+ });+}+function openEvents(url: string): {waitFor: (needle: string, ms?: number) => Promise<boolean>;close: () => void;@@ -305,12 +317,12 @@ describe("map server", () => {});describe("settings write", () => {- it("gives the panel a token and leaves maps without one", async () => {+ it("gives every served page a token", async () => {const server = await start();const panel = await request(`${server.url}/`);expect(panel.body).toContain(`name="${TOKEN_META_NAME}"`);const map = await request(mapPageUrl(server.url, root));- expect(map.body).not.toContain(`name="${TOKEN_META_NAME}"`);+ expect(map.body).toContain(`name="${TOKEN_META_NAME}"`);});it("accepts a valid write, stores it and refreshes the panel", async () => {@@ -454,11 +466,65 @@ describe("settings write", () => {[CONFIG_TOKEN_HEADER]: token,});expect(notJson.status).toBe(400);- expect((await request(`${server.url}/api/config`)).status).toBe(404);+ // A bare GET is not a settings read: it carries no token.+ expect((await request(`${server.url}/api/config`)).status).toBe(403);expect((await loadConfig(env)).language).toBe("auto");});});+describe("settings read", () => {+ it("returns only the editable keys and their current values", async () => {+ const server = await start();+ const token = await panelToken(server);+ const reply = await configRead(server, token);+ expect(reply.status).toBe(200);+ expect(reply.headers["cache-control"]).toBe("no-store");+ expect(JSON.parse(reply.body)).toEqual({+ ok: true,+ settings: {+ messageSummaries: false,+ startupContext: true,+ language: "auto",+ updateEveryTurns: 5,+ sessionEndCatchUp: true,+ catchUpModel: "haiku",+ },+ });+ });++ it("accepts a same-origin GET without an Origin header", async () => {+ const server = await start();+ const token = await panelToken(server);+ const reply = await request(`${server.url}/api/config`, {+ [CONFIG_TOKEN_HEADER]: token,+ });+ expect(reply.status).toBe(200);+ expect(JSON.parse(reply.body).settings.updateEveryTurns).toBe(5);+ });++ it("shows a value changed after the page was built", async () => {+ const server = await start();+ const token = await panelToken(server);+ const write = await configWrite(server, token, { key: "updateEveryTurns", value: 8 });+ expect(write.status).toBe(200);+ const reply = await configRead(server, token);+ expect(JSON.parse(reply.body).settings.updateEveryTurns).toBe(8);+ });++ it("rejects a wrong token, a foreign origin and a foreign Host", async () => {+ const server = await start();+ const token = await panelToken(server);+ expect((await configRead(server, "nope")).status).toBe(403);+ expect((await configRead(server, token, { origin: "http://evil.example" })).status).toBe(403);+ expect((await configRead(server, token, { host: "evil.example:4747" })).status).toBe(403);+ });++ it("refuses a method other than GET", async () => {+ const server = await start();+ expect((await request(`${server.url}/api/config`, {}, "HEAD")).status).toBe(405);+ });+});+describe("spawnServerProcess", () => {it("runs the CLI detached with hooks silenced", () => {const calls: unknown[][] = [];diff --git a/packages/cli/test/settings.test.ts b/packages/cli/test/settings.test.tsnew file mode 100644index 0000000..e3d18b2--- /dev/null+++ b/packages/cli/test/settings.test.ts@@ -0,0 +1,80 @@+import { describe, expect, it } from "vitest";+import { CONFIG_SCHEMA, Config } from "../src/schema/config.js";+import { PANEL_EDITABLE_KEYS } from "../src/view/model.js";+import {+ DEFAULT_SETTINGS,+ editableSettings,+ formatSetting,+ settingsSections,+ withDefaults,+} from "../src/view/settings.js";++describe("settings model", () => {+ it("keeps the defaults in step with the config schema", () => {+ const parsed = Config.parse({ schema: CONFIG_SCHEMA });+ expect(DEFAULT_SETTINGS).toEqual({+ language: parsed.language,+ updateEveryTurns: parsed.updateEveryTurns,+ sessionEndCatchUp: parsed.sessionEndCatchUp,+ catchUpModel: parsed.catchUpModel,+ messageSummaries: parsed.messageSummaries,+ startupContext: parsed.startupContext,+ gitPolicy: parsed.gitPolicy,+ agents: parsed.agents,+ });+ });++ it("lets the embedded values override the defaults", () => {+ expect(withDefaults(undefined)).toEqual(DEFAULT_SETTINGS);+ expect(withDefaults({ updateEveryTurns: 9, gitPolicy: "commit" })).toEqual({+ ...DEFAULT_SETTINGS,+ updateEveryTurns: 9,+ gitPolicy: "commit",+ });+ });++ it("has one section with every field and edits only the allow-listed keys over http", () => {+ const sections = settingsSections(true);+ expect(sections.map((section) => section.title)).toEqual(["Recording"]);+ const fields = sections[0]?.fields ?? [];+ expect(fields.map((field) => field.key)).toEqual([+ ...PANEL_EDITABLE_KEYS,+ "gitPolicy",+ "agents",+ ]);+ for (const field of fields) {+ expect(field.label).not.toBe("");+ expect(field.help.length).toBeGreaterThan(10);+ expect(field.editable).toBe((PANEL_EDITABLE_KEYS as readonly string[]).includes(field.key));+ }+ });++ it("shows everything read-only over file://", () => {+ const fields = settingsSections(false).flatMap((section) => section.fields);+ expect(fields).toHaveLength(PANEL_EDITABLE_KEYS.length + 2);+ expect(fields.every((field) => !field.editable)).toBe(true);+ });++ it("returns only the editable keys with their current values", () => {+ const settings = { ...DEFAULT_SETTINGS, language: "tr", updateEveryTurns: 8 };+ expect(editableSettings(settings)).toEqual({+ messageSummaries: false,+ startupContext: true,+ language: "tr",+ updateEveryTurns: 8,+ sessionEndCatchUp: true,+ catchUpModel: "haiku",+ });+ expect(Object.keys(editableSettings(settings)).sort()).toEqual([...PANEL_EDITABLE_KEYS].sort());+ });++ it("formats a read-only value for the modal", () => {+ expect(formatSetting(true)).toBe("yes");+ expect(formatSetting(false)).toBe("no");+ expect(formatSetting(["claude-code", "codex"])).toBe("claude-code, codex");+ expect(formatSetting([])).toBe("—");+ expect(formatSetting("auto")).toBe("auto");+ expect(formatSetting(5)).toBe("5");+ expect(formatSetting(undefined)).toBe("—");+ });+});diff --git a/packages/template/src/App.tsx b/packages/template/src/App.tsxindex 6c9aa5a..4036ed0 100644--- a/packages/template/src/App.tsx+++ b/packages/template/src/App.tsx@@ -2,6 +2,7 @@ import type { LineageViewModel } from "../../cli/src/view/model.js";import { formatTime } from "./format.js";import { Graph } from "./Graph.js";import { ProjectSwitcher } from "./ProjectSwitcher.js";+import { SettingsButton } from "./SettingsModal.js";export function App({ model }: { model: LineageViewModel }) {const sessionCount =@@ -10,7 +11,10 @@ export function App({ model }: { model: LineageViewModel }) {return (<main><div className="page-head">- <ProjectSwitcher model={model} />+ <div className="page-bar">+ <ProjectSwitcher model={model} />+ <SettingsButton settings={model.settings} />+ </div><header className="project"><div>diff --git a/packages/template/src/Panel.tsx b/packages/template/src/Panel.tsxindex 2ca5f1c..ca2b429 100644--- a/packages/template/src/Panel.tsx+++ b/packages/template/src/Panel.tsx@@ -1,33 +1,7 @@-import { type FormEvent, useEffect, useState } from "react";-import type {- PanelEditableKey,- PanelProject,- PanelSettings,- PanelViewModel,-} from "../../cli/src/view/model.js";-import { isLivePage, pageToken, saveSetting } from "./data.js";+import type { PanelProject, PanelViewModel } from "../../cli/src/view/model.js";+import { isLivePage } from "./data.js";import { formatTime } from "./format.js";--interface EditableSpec {- key: PanelEditableKey;- label: string;- kind: "text" | "number" | "boolean";-}--/** The keys the panel may change (Story 8.9); the server enforces the same list. */-const EDITABLE: EditableSpec[] = [- { key: "messageSummaries", label: "Message summaries", kind: "boolean" },- { key: "startupContext", label: "Lineage at session start", kind: "boolean" },- { key: "language", label: "Language", kind: "text" },- { key: "updateEveryTurns", label: "Update every turns", kind: "number" },- { key: "sessionEndCatchUp", label: "Catch up on session end", kind: "boolean" },- { key: "catchUpModel", label: "Catch-up model", kind: "text" },-];--const READ_ONLY: [keyof PanelSettings, string][] = [- ["gitPolicy", "Git policy"],- ["agents", "Agents"],-];+import { SettingsButton } from "./SettingsModal.js";/*** From the local server, maps open as pages of that server so they refresh too;@@ -38,96 +12,7 @@ function mapHref(project: PanelProject): string | null {return isLivePage() ? `/map?dir=${encodeURIComponent(project.path)}` : project.lineageUrl;}-function settingText(value: PanelSettings[keyof PanelSettings]): string {- if (Array.isArray(value)) return value.length > 0 ? value.join(", ") : "—";- if (typeof value === "boolean") return value ? "yes" : "no";- return String(value);-}--/**- * One setting with a control and a Save button. The draft follows the model, so- * a live page swap after a rebuild shows the value the server actually stored.- */-function EditableSetting({- spec,- value,- token,-}: {- spec: EditableSpec;- value: PanelSettings[PanelEditableKey];- token: string;-}) {- const [draft, setDraft] = useState(String(value));- const [checked, setChecked] = useState(Boolean(value));- const [saving, setSaving] = useState(false);- const [status, setStatus] = useState<string | null>(null);- const [error, setError] = useState<string | null>(null);-- useEffect(() => {- setDraft(String(value));- setChecked(Boolean(value));- setSaving(false);- setStatus(null);- setError(null);- }, [value]);-- const dirty = spec.kind === "boolean" ? checked !== Boolean(value) : draft !== String(value);-- async function submit(event: FormEvent): Promise<void> {- event.preventDefault();- if (!dirty || saving) return;- const next = spec.kind === "boolean" ? checked : spec.kind === "number" ? Number(draft) : draft;- setSaving(true);- setStatus(null);- setError(null);- try {- await saveSetting(spec.key, next, token);- setStatus("Saved");- } catch (err) {- setError(err instanceof Error ? err.message : String(err));- } finally {- setSaving(false);- }- }-- const id = `setting-${spec.key}`;- return (- <div>- <dt>- <label htmlFor={id}>{spec.label}</label>- </dt>- <dd>- <form className="setting-form" onSubmit={submit}>- {spec.kind === "boolean" ? (- <input- id={id}- type="checkbox"- checked={checked}- onChange={(event) => setChecked(event.target.checked)}- />- ) : (- <input- id={id}- type={spec.kind === "number" ? "number" : "text"}- value={draft}- onChange={(event) => setDraft(event.target.value)}- />- )}- <button type="submit" disabled={!dirty || saving}>- {saving ? "Saving…" : "Save"}- </button>- {status ? <span className="setting-status">{status}</span> : null}- {error ? <span className="setting-error">{error}</span> : null}- </form>- </dd>- </div>- );-}-export function Panel({ model }: { model: PanelViewModel }) {- // No token over `file://`: the page cannot write, so the settings stay text.- const token = isLivePage() ? pageToken() : null;-return (<main><header className="project">@@ -135,11 +20,14 @@ export function Panel({ model }: { model: PanelViewModel }) {<h1>Projects</h1><p className="muted">Every project codelineage knows about.</p></div>- <div className="meta">- <span>- {model.projects.length} {model.projects.length === 1 ? "project" : "projects"}- </span>- <span className="muted">generated {formatTime(model.generatedAt)}</span>+ <div className="page-actions">+ <SettingsButton settings={model.settings} />+ <div className="meta">+ <span>+ {model.projects.length} {model.projects.length === 1 ? "project" : "projects"}+ </span>+ <span className="muted">generated {formatTime(model.generatedAt)}</span>+ </div></div></header>@@ -176,38 +64,6 @@ export function Panel({ model }: { model: PanelViewModel }) {})}</ul>)}-- <section className="settings" aria-label="Settings">- <h2>Settings</h2>- <p className="muted">- {token- ? "A change here applies to new builds and chats."- : "Read-only; change them with `codelineage config set`, or run `codelineage open` to edit them here."}- </p>- <dl>- {EDITABLE.map((spec) =>- token ? (- <EditableSetting- key={spec.key}- spec={spec}- value={model.settings[spec.key]}- token={token}- />- ) : (- <div key={spec.key}>- <dt>{spec.label}</dt>- <dd>{settingText(model.settings[spec.key])}</dd>- </div>- ),- )}- {READ_ONLY.map(([key, label]) => (- <div key={key}>- <dt>{label}</dt>- <dd>{settingText(model.settings[key])}</dd>- </div>- ))}- </dl>- </section></main>);}diff --git a/packages/template/src/SettingsModal.tsx b/packages/template/src/SettingsModal.tsxnew file mode 100644index 0000000..ddd123f--- /dev/null+++ b/packages/template/src/SettingsModal.tsx@@ -0,0 +1,258 @@+import { type FormEvent, useEffect, useRef, useState } from "react";+import type { PanelSettings } from "../../cli/src/view/model.js";+import {+ formatSetting,+ type SettingField,+ settingsSections,+ withDefaults,+} from "../../cli/src/view/settings.js";+import { isLivePage, loadSettings, pageToken, saveSetting } from "./data.js";++/**+ * The settings modal (Story 8.13). Every page carries a ⚙ Settings button in+ * its top bar; the modal is the one place settings are changed. Over the local+ * server it reads the live values with `GET /api/config` and writes with the+ * 8.9 path; over `file://` it shows the values embedded at build time read-only.+ */++type SettingValue = PanelSettings[keyof PanelSettings];++interface EditableProps {+ id: string;+ field: SettingField;+ value: SettingValue;+ token: string;+ onSaved: (key: keyof PanelSettings, value: SettingValue) => void;+}++/**+ * One editable setting with its control and Save button. The draft follows the+ * parent value, so the live value from `GET /api/config` (or a successful save)+ * is what the form shows.+ */+function EditableSetting({ id, field, value, token, onSaved }: EditableProps) {+ const [draft, setDraft] = useState(String(value));+ const [checked, setChecked] = useState(Boolean(value));+ const [saving, setSaving] = useState(false);+ const [status, setStatus] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ setDraft(String(value));+ setChecked(Boolean(value));+ setSaving(false);+ setError(null);+ }, [value]);++ const dirty = field.kind === "boolean" ? checked !== Boolean(value) : draft !== String(value);++ /** A new edit supersedes the previous "Saved" / error line. */+ function edited(): void {+ setStatus(null);+ setError(null);+ }++ async function submit(event: FormEvent): Promise<void> {+ event.preventDefault();+ if (!dirty || saving) return;+ const next: SettingValue =+ field.kind === "boolean" ? checked : field.kind === "number" ? Number(draft) : draft;+ setSaving(true);+ setStatus(null);+ setError(null);+ try {+ await saveSetting(field.key, next, token);+ onSaved(field.key, next);+ setStatus("Saved");+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setSaving(false);+ }+ }++ return (+ <div className="settings-field">+ <div className="settings-field-text">+ <label className="settings-label" htmlFor={id}>+ {field.label}+ </label>+ <p className="settings-help" id={`${id}-help`}>+ {field.help}+ </p>+ </div>+ <form className="setting-form" onSubmit={submit}>+ {field.kind === "boolean" ? (+ <input+ id={id}+ type="checkbox"+ checked={checked}+ aria-describedby={`${id}-help`}+ onChange={(event) => {+ setChecked(event.target.checked);+ edited();+ }}+ />+ ) : (+ <input+ id={id}+ type={field.kind === "number" ? "number" : "text"}+ value={draft}+ aria-describedby={`${id}-help`}+ onChange={(event) => {+ setDraft(event.target.value);+ edited();+ }}+ />+ )}+ <button type="submit" disabled={!dirty || saving}>+ {saving ? "Saving…" : "Save"}+ </button>+ {status ? <span className="setting-status">{status}</span> : null}+ {error ? <span className="setting-error">{error}</span> : null}+ </form>+ </div>+ );+}++function SettingsDialog({+ embedded,+ onClose,+}: {+ embedded: PanelSettings | undefined;+ onClose: () => void;+}) {+ // A map built before a change carries old values; the server answer wins.+ const token = isLivePage() ? pageToken() : null;+ const [values, setValues] = useState<PanelSettings>(() => withDefaults(embedded));+ const [loading, setLoading] = useState(token !== null);+ const [loadError, setLoadError] = useState<string | null>(null);+ const closeRef = useRef<HTMLButtonElement>(null);++ useEffect(() => {+ // Focus goes into the dialog on open; the button takes it back on close.+ closeRef.current?.focus();+ }, []);++ useEffect(() => {+ function onKey(event: KeyboardEvent): void {+ if (event.key === "Escape") onClose();+ }+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [onClose]);++ useEffect(() => {+ if (!token) return;+ let alive = true;+ loadSettings(token)+ .then((live) => {+ if (alive) setValues((current) => ({ ...current, ...live }));+ })+ .catch((err: unknown) => {+ if (alive) setLoadError(err instanceof Error ? err.message : String(err));+ })+ .finally(() => {+ if (alive) setLoading(false);+ });+ return () => {+ alive = false;+ };+ }, [token]);++ const canEdit = token !== null;+ const sections = settingsSections(canEdit);++ return (+ <div+ className="settings-overlay"+ onMouseDown={(event) => {+ if (event.target === event.currentTarget) onClose();+ }}+ >+ <div+ className="settings-dialog"+ role="dialog"+ aria-modal="true"+ aria-labelledby="settings-title"+ >+ <div className="settings-head">+ <h2 id="settings-title">Settings</h2>+ <button+ ref={closeRef}+ type="button"+ className="settings-close"+ aria-label="Close settings"+ onClick={onClose}+ >+ ×+ </button>+ </div>+ <p className="muted">+ {canEdit+ ? "A change here applies to new builds and chats."+ : "Read-only. Open this page with `codelineage open` to change settings, or use `codelineage config set <key> <value>`."}+ </p>+ {loading ? <p className="settings-help">Reading the current settings…</p> : null}+ {loadError ? <p className="setting-error">{loadError}</p> : null}++ {sections.map((section) => (+ <section key={section.title} className="settings-section" aria-label={section.title}>+ <h3>{section.title}</h3>+ {section.fields.map((field) => {+ const id = `setting-${field.key}`;+ const value = values[field.key];+ return field.editable && token ? (+ <EditableSetting+ key={field.key}+ id={id}+ field={field}+ value={value}+ token={token}+ onSaved={(key, next) => setValues((current) => ({ ...current, [key]: next }))}+ />+ ) : (+ <div key={field.key} className="settings-field">+ <div className="settings-field-text">+ <span className="settings-label">{field.label}</span>+ <p className="settings-help" id={`${id}-help`}>+ {field.help}+ </p>+ </div>+ <span className="settings-value">{formatSetting(value)}</span>+ </div>+ );+ })}+ </section>+ ))}+ </div>+ </div>+ );+}++/** The ⚙ Settings button both pages put in their top bar. */+export function SettingsButton({ settings }: { settings?: PanelSettings | undefined }) {+ const [open, setOpen] = useState(false);+ const buttonRef = useRef<HTMLButtonElement>(null);++ function close(): void {+ setOpen(false);+ buttonRef.current?.focus();+ }++ return (+ <>+ <button+ ref={buttonRef}+ type="button"+ className="settings-button"+ aria-haspopup="dialog"+ aria-expanded={open}+ onClick={() => setOpen(true)}+ >+ <span aria-hidden="true">⚙</span> Settings+ </button>+ {open ? <SettingsDialog embedded={settings} onClose={close} /> : null}+ </>+ );+}diff --git a/packages/template/src/data.ts b/packages/template/src/data.tsindex ead572b..77957dd 100644--- a/packages/template/src/data.ts+++ b/packages/template/src/data.ts@@ -2,6 +2,7 @@ import {DATA_ELEMENT_ID,LIVE_META_NAME,type PageModel,+ type PanelSettings,TOKEN_META_NAME,} from "../../cli/src/view/model.js";@@ -57,8 +58,30 @@ export function pageToken(doc: Document = document): string | null {return content ? content : null;}+/**+ * The live settings the modal opens with (Story 8.13). The server answers with+ * only the keys the modal may change, so a map built before a change still+ * shows the current value.+ */+export async function loadSettings(token: string): Promise<Partial<PanelSettings>> {+ const response = await fetch("/api/config", {+ headers: { "x-codelineage-token": token },+ cache: "no-store",+ });+ if (!response.ok) {+ const text = (await response.text()).trim();+ throw new Error(text || `could not read settings (HTTP ${response.status})`);+ }+ const body = (await response.json()) as { settings?: Partial<PanelSettings> };+ return body.settings ?? {};+}+/** One settings write; the server validates the key, the value and the token. */-export async function saveSetting(key: string, value: unknown, token: string): Promise<void> {+export async function saveSetting(+ key: string,+ value: unknown,+ token: string,+): Promise<PanelSettings[keyof PanelSettings]> {const response = await fetch("/api/config", {method: "POST",headers: { "content-type": "application/json", "x-codelineage-token": token },@@ -68,4 +91,8 @@ export async function saveSetting(key: string, value: unknown, token: string): Pconst text = (await response.text()).trim();throw new Error(text || `could not save (HTTP ${response.status})`);}+ const body = (await response.json().catch(() => null)) as {+ value?: PanelSettings[keyof PanelSettings];+ } | null;+ return body?.value ?? (value as PanelSettings[keyof PanelSettings]);}diff --git a/packages/template/src/fixture.ts b/packages/template/src/fixture.tsindex 2b91ea3..e7e66ca 100644--- a/packages/template/src/fixture.ts+++ b/packages/template/src/fixture.ts@@ -51,6 +51,16 @@ export const fixture: LineageViewModel = {next: "Render the fixture through the template and check the single-file build.",lastActivity: "2026-10-24T11:42:00.000Z",},+ settings: {+ language: "auto",+ updateEveryTurns: 5,+ sessionEndCatchUp: true,+ catchUpModel: "haiku",+ messageSummaries: false,+ startupContext: true,+ gitPolicy: "ignore",+ agents: ["claude-code"],+ },epochs: [{id: "map",diff --git a/packages/template/src/styles.css b/packages/template/src/styles.cssindex 0f1cef5..97afc76 100644--- a/packages/template/src/styles.css+++ b/packages/template/src/styles.css@@ -41,6 +41,44 @@ main {margin: 0;}+/* Settings button (Story 8.13) sits in the top bar of every page. */+.page-bar {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 12px;+}++.page-bar .switcher {+ flex: 1 1 auto;+ min-width: 0;+}++.page-actions {+ display: flex;+ flex-direction: column;+ align-items: flex-end;+ gap: 8px;+}++.settings-button {+ flex: none;+ margin-left: auto;+ padding: 6px 12px;+ color: var(--muted);+ font: inherit;+ font-size: 13px;+ background: #151922;+ border: 1px solid var(--line);+ border-radius: 8px;+ cursor: pointer;+}++.settings-button:hover {+ color: var(--text);+ border-color: var(--accent);+}+h1,h2,h3 {@@ -244,6 +282,107 @@ ul {padding: 8px 10px;}+/* Settings modal (Story 8.13): one place for every setting, on every page. */+.settings-overlay {+ position: fixed;+ inset: 0;+ z-index: 250;+ display: flex;+ align-items: flex-start;+ justify-content: center;+ padding: 10vh 16px 32px;+ background: rgba(5, 7, 10, 0.62);+}++.settings-dialog {+ width: min(640px, 100%);+ max-height: 80vh;+ padding: 18px 20px 22px;+ overflow: auto;+ background: var(--panel);+ border: 1px solid var(--line);+ border-radius: 12px;+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);+}++.settings-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+}++.settings-close {+ width: 28px;+ height: 28px;+ color: var(--muted);+ font: inherit;+ font-size: 18px;+ line-height: 1;+ background: transparent;+ border: 1px solid var(--line);+ border-radius: 8px;+ cursor: pointer;+}++.settings-close:hover {+ color: var(--text);+ border-color: var(--accent);+}++.settings-section {+ margin-top: 16px;+}++.settings-section h3 {+ color: var(--muted);+ font-size: 12px;+ letter-spacing: 0.08em;+ text-transform: uppercase;+}++.settings-field {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 16px;+ padding: 10px 0;+ border-bottom: 1px solid var(--line);+}++.settings-field:last-child {+ border-bottom: 0;+}++.settings-field-text {+ min-width: 0;+}++.settings-label {+ font-size: 14px;+}++.settings-help {+ margin: 2px 0 0;+ color: var(--muted);+ font-size: 12px;+}++.settings-value {+ flex: none;+ max-width: 40%;+ color: var(--muted);+ font-size: 13px;+ text-align: right;+}++.settings-field .setting-form {+ flex: none;+ flex-wrap: wrap;+ justify-content: flex-end;+ max-width: 50%;+}+.project {display: flex;align-items: flex-end;@@ -850,6 +989,29 @@ time {align-items: flex-start;}+ .page-actions {+ align-items: flex-start;+ }++ .page-bar {+ flex-wrap: wrap;+ }++ .settings-field {+ flex-direction: column;+ gap: 6px;+ }++ .settings-field .setting-form {+ max-width: none;+ justify-content: flex-start;+ }++ .settings-value {+ max-width: none;+ text-align: left;+ }+.graph-wrap {flex-direction: column;height: auto;diff --git a/packages/template/test/panel.test.ts b/packages/template/test/panel.test.tsnew file mode 100644index 0000000..1329822--- /dev/null+++ b/packages/template/test/panel.test.ts@@ -0,0 +1,33 @@+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vitest";+import type { PanelViewModel } from "../../cli/src/view/model.js";+import { Panel } from "../src/Panel.js";++const model: PanelViewModel = {+ kind: "panel",+ schema: 1,+ generatedAt: "2026-10-26T10:00:00.000Z",+ settings: {+ language: "auto",+ updateEveryTurns: 5,+ sessionEndCatchUp: true,+ catchUpModel: "haiku",+ messageSummaries: false,+ startupContext: true,+ gitPolicy: "ignore",+ agents: ["claude-code"],+ },+ projects: [],+};++describe("Panel", () => {+ it("puts the settings in the top bar and not in the old bottom box", () => {+ // No projects: mapHref would read the document, which a server render lacks.+ const html = renderToStaticMarkup(createElement(Panel, { model }));+ expect(html).toContain('class="settings-button"');+ expect(html).toContain("Settings");+ expect(html).not.toContain('aria-label="Settings"');+ expect(html).not.toContain("Read-only; change them with");+ });+});