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(map): keep open sessions open across a reload
Erenfd0293c3d3ff
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4c3dfc3..3d98caf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,7 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- The map no longer draws the dashed return arrow and the "↩ mN" mark (a branch already shows the return; the details panel still lists it), nor the epoch tag on session rows.### Changed-- Each session on the map now keeps its own message row width: dragging one session's edge leaves the others alone. The width is stored in the project's local `.cogit/state/row-widths.json` (never committed, so teammates keep their own), and survives a reload or a different browser.+- Each session on the map now keeps its own message row width: dragging one session's edge leaves the others alone. The width is stored in the project's local `.cogit/state/map.json` (never committed, so teammates keep their own), and survives a reload or a different browser.+- Sessions left open on the map stay open after a reload; the view still lands on where you left off. Stored in the same local `.cogit/state/map.json`.## [0.22.0] - 2026-10-30### Addeddiff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.tsindex 1cceaea..a47a7a5 100644--- a/packages/cli/src/commands/build.ts+++ b/packages/cli/src/commands/build.ts@@ -29,10 +29,10 @@ import {import { applyEvents, readEvents } from "../store/events.js";import { atomicWrite } from "../store/fs.js";import { withLock } from "../store/lock.js";+import { readMapView } from "../store/map-view.js";import { projectPaths } from "../store/paths.js";import { readReadState } from "../store/read-state.js";import { resolveProjectRoot } from "../store/root.js";-import { readRowWidths } from "../store/row-widths.js";import { loadAllSessions, loadConfig, loadProject } from "../store/stores.js";import { attachThoughtTrailers, earliestSessionStart, readThoughtTrailers } from "../thought.js";import { attachChanges } from "../view/change.js";@@ -357,7 +357,9 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModel});built.switcher = switcher;built.read = [...read].sort();- built.rowWidths = await readRowWidths(root);+ const view = await readMapView(root);+ built.rowWidths = view.rowWidths;+ built.openSessions = view.open;// Story 11.1: the map head carries this project's rows only. The panel// already collected them from the registry; a project outside it (a// broken registry, a hand-made directory) is read here instead.diff --git a/packages/cli/src/server.ts b/packages/cli/src/server.tsindex c69b3c8..21aae30 100644--- a/packages/cli/src/server.ts+++ b/packages/cli/src/server.ts@@ -19,9 +19,9 @@ import { Config } from "./schema/config.js";import { refreshShareConversations } from "./share.js";import { dismissInboxSession } from "./store/inbox-state.js";import { LockBusyError } from "./store/lock.js";+import { MAX_OPEN, readMapView, setOpenSessions, setRowWidth } from "./store/map-view.js";import { globalPaths, projectPaths } from "./store/paths.js";import { setMessageRead } from "./store/read-state.js";-import { readRowWidths, setRowWidth } from "./store/row-widths.js";import { loadConfig, loadRegistry, updateConfig } from "./store/stores.js";import { isPanelEditableKey, LIVE_META_NAME, TOKEN_META_NAME } from "./view/model.js";import { buildPanel, panelSettings } from "./view/panel.js";@@ -403,12 +403,12 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>}/**- * `GET /api/row-width?dir`: the stored row widths as they are now. The page- * embeds them at build time, but a reload can come before the rebuild that a- * drag's write starts, so the page asks here too. Same Origin and token checks- * as the settings read, and a registered project only.+ * `GET /api/map-view?dir`: how the user left the map (open sessions, row+ * widths) as stored now. The page embeds it at build time, but a reload can+ * come before the rebuild that a write starts, so the page asks here too. Same+ * Origin and token checks as the settings read, and a registered project only.*/- async function readRowWidthsRequest(+ async function readMapViewRequest(req: IncomingMessage,res: ServerResponse,port: number,@@ -435,7 +435,8 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>"content-type": "application/json","cache-control": "no-store",});- res.end(JSON.stringify({ ok: true, widths: await readRowWidths(root) }));+ const view = await readMapView(root);+ res.end(JSON.stringify({ ok: true, rowWidths: view.rowWidths, open: view.open }));}/**@@ -698,23 +699,21 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>}/**- * `POST /api/row-width` { dir, sessionId, width } : the map's row edge, sent- * when a drag ends. `width` null forgets the session (the double-click reset).- * It writes the project's local state file, never a committed one. Same Host,- * Origin, content-type and token checks as a read mark, and `dir` must be- * registered.+ * The checks every map-view write shares: Origin and token, a JSON object body+ * within the size cap, and a registered `dir`. Answers the request itself and+ * returns null when one fails.*/- async function writeRowWidth(+ async function mapViewWrite(req: IncomingMessage,res: ServerResponse,port: number,- ): Promise<void> {+ ): Promise<{ root: string; body: Record<string, unknown> } | null> {if (!originAllowed(req.headers.origin, port) ||!tokenMatches(req.headers[CONFIG_TOKEN_HEADER])) {respond(res, 403, "forbidden");- return;+ return null;}const type = req.headers["content-type"];if (@@ -722,56 +721,104 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>type.split(";")[0]?.trim().toLowerCase() !== "application/json") {respond(res, 415, "content-type must be application/json");- return;+ return null;}- const body = await readLimitedBody(req);- if (body === null) {+ const raw = await readLimitedBody(req);+ if (raw === null) {respond(res, 413, "request body too large");- return;+ return null;}let parsed: unknown;try {- parsed = JSON.parse(body);+ parsed = JSON.parse(raw);} catch {respond(res, 400, "invalid JSON");- return;+ return null;}if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {respond(res, 400, "expected a JSON object");- return;+ return null;+ }+ const body = parsed as Record<string, unknown>;+ if (typeof body.dir !== "string") {+ respond(res, 400, "dir is required");+ return null;+ }+ const root = await registeredRoot(env, body.dir);+ if (root === null) {+ respond(res, 403, "not a registered project");+ return null;}- const { dir, sessionId, width } = parsed as Record<string, unknown>;+ return { root, body };+ }++ /**+ * `POST /api/row-width` { dir, sessionId, width }: the map's row edge, sent+ * when a drag ends. `width` null forgets the session (the double-click reset).+ * It writes the project's local state file, never a committed one.+ */+ async function writeRowWidth(+ req: IncomingMessage,+ res: ServerResponse,+ port: number,+ ): Promise<void> {+ const write = await mapViewWrite(req, res, port);+ if (write === null) return;+ const { sessionId, width } = write.body;if (- typeof dir !== "string" ||typeof sessionId !== "string" ||- (width !== null && typeof width !== "number")+ !/^[A-Za-z0-9._:-]{1,128}$/.test(sessionId) ||+ (width !== null &&+ !(typeof width === "number" && Number.isInteger(width) && width > 0 && width <= 10_000))) {respond(res, 400, "expected { dir, sessionId, width }");return;}- if (- !/^[A-Za-z0-9._:-]{1,128}$/.test(sessionId) ||- (width !== null && !(Number.isInteger(width) && width > 0 && width <= 10_000))- ) {- respond(res, 400, "sessionId or width is not valid");+ try {+ await setRowWidth(write.root, sessionId, width);+ } catch {+ respond(res, 500, "could not write the row width");return;}- const root = await registeredRoot(env, dir);- if (root === null) {- respond(res, 403, "not a registered project");+ res.writeHead(200, {+ "content-type": "application/json",+ "cache-control": "no-store",+ });+ res.end(JSON.stringify({ ok: true, sessionId, width }));+ }++ /**+ * `POST /api/open-sessions` { dir, open }: the sessions open on the map, sent+ * whenever one opens or closes, so a reload opens them again. It writes the+ * project's local state file, never a committed one.+ */+ async function writeOpenSessions(+ req: IncomingMessage,+ res: ServerResponse,+ port: number,+ ): Promise<void> {+ const write = await mapViewWrite(req, res, port);+ if (write === null) return;+ const { open } = write.body;+ if (+ !Array.isArray(open) ||+ open.length > MAX_OPEN ||+ !open.every((id) => typeof id === "string" && /^[A-Za-z0-9._:-]{1,128}$/.test(id))+ ) {+ respond(res, 400, "expected { dir, open: [session ids] }");return;}try {- await setRowWidth(root, sessionId, width);+ await setOpenSessions(write.root, open as string[]);} catch {- respond(res, 500, "could not write the row width");+ respond(res, 500, "could not write the open sessions");return;}res.writeHead(200, {"content-type": "application/json","cache-control": "no-store",});- res.end(JSON.stringify({ ok: true, sessionId, width }));+ res.end(JSON.stringify({ ok: true, open }));}async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {@@ -805,6 +852,10 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>await writeRowWidth(req, res, port);return;}+ if (url.pathname === "/api/open-sessions") {+ await writeOpenSessions(req, res, port);+ return;+ }if (url.pathname !== "/api/config") {respond(res, 405, "method not allowed");return;@@ -829,12 +880,12 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>await readDiff(req, res, port, url);return;}- if (url.pathname === "/api/row-width") {+ if (url.pathname === "/api/map-view") {if (req.method !== "GET") {respond(res, 405, "method not allowed");return;}- await readRowWidthsRequest(req, res, port, url);+ await readMapViewRequest(req, res, port, url);return;}if (url.pathname === "/api/config") {diff --git a/packages/cli/src/store/map-view.ts b/packages/cli/src/store/map-view.tsnew file mode 100644index 0000000..366e17f--- /dev/null+++ b/packages/cli/src/store/map-view.ts@@ -0,0 +1,81 @@+import { z } from "zod";+import { atomicWriteJson, readJson } from "./fs.js";+import { withLock } from "./lock.js";+import { projectPaths } from "./paths.js";++/**+ * How the user left the map: which sessions were open and how wide each one's+ * message rows were dragged. A view preference, so it is local per-user state+ * under `.cogit/state/` like the read marks: never committed, so one person's+ * map never reshapes a teammate's. The page keeps widths in range; this file+ * only checks that they are sane numbers.+ */++export const MAP_VIEW_SCHEMA = 1;++const SESSION_ID = /^[A-Za-z0-9._:-]{1,128}$/;+/** Far past anything the map lets a drag reach. */+const MAX_WIDTH = 10_000;+/** More open sessions than any map shows; a cap on what one request may store. */+export const MAX_OPEN = 500;++export const MapView = z.object({+ schema: z.literal(MAP_VIEW_SCHEMA),+ /** Session id → the message rows' width in map pixels. */+ rowWidths: z.record(z.string(), z.number().int().positive().max(MAX_WIDTH)).default({}),+ /** Sessions open on the map, in the order the page sent them. */+ open: z.array(z.string().regex(SESSION_ID)).max(MAX_OPEN).default([]),+});++export type MapView = z.infer<typeof MapView>;++/** The stored view. A missing or unreadable file is "nothing stored yet". */+export async function readMapView(root: string): Promise<MapView> {+ const read = await readJson(projectPaths(root).mapView);+ const empty: MapView = { schema: MAP_VIEW_SCHEMA, rowWidths: {}, open: [] };+ if (!read.found || "error" in read) return empty;+ const parsed = MapView.safeParse(read.value);+ return parsed.success ? parsed.data : empty;+}++/** Reads, changes and writes the view under its lock; an unreadable file is replaced. */+async function updateMapView(root: string, change: (view: MapView) => void): Promise<void> {+ const paths = projectPaths(root);+ await withLock(+ paths.lock("map-view"),+ async () => {+ const view = await readMapView(root);+ change(view);+ const rowWidths = Object.fromEntries(+ Object.entries(view.rowWidths).sort(([a], [b]) => a.localeCompare(b)),+ );+ await atomicWriteJson(paths.mapView, { schema: MAP_VIEW_SCHEMA, rowWidths, open: view.open });+ },+ { timeoutMs: 2000 },+ );+}++/** Stores one session's width, or forgets it (`null`, the double-click reset). */+export async function setRowWidth(+ root: string,+ sessionId: string,+ width: number | null,+): Promise<void> {+ if (!SESSION_ID.test(sessionId)) throw new Error(`not a session id: ${sessionId}`);+ if (width !== null && !(Number.isInteger(width) && width > 0 && width <= MAX_WIDTH))+ throw new Error(`not a row width: ${width}`);+ await updateMapView(root, (view) => {+ if (width === null) delete view.rowWidths[sessionId];+ else view.rowWidths[sessionId] = width;+ });+}++/** Stores which sessions are open, replacing the previous list. */+export async function setOpenSessions(root: string, open: readonly string[]): Promise<void> {+ if (open.length > MAX_OPEN) throw new Error(`too many open sessions: ${open.length}`);+ for (const sessionId of open)+ if (!SESSION_ID.test(sessionId)) throw new Error(`not a session id: ${sessionId}`);+ await updateMapView(root, (view) => {+ view.open = [...new Set(open)];+ });+}diff --git a/packages/cli/src/store/paths.ts b/packages/cli/src/store/paths.tsindex a17ca40..968cc54 100644--- a/packages/cli/src/store/paths.ts+++ b/packages/cli/src/store/paths.ts@@ -40,8 +40,8 @@ export function projectPaths(root: string) {readState: join(base, "state", "read.json"),/** Inbox rows the user dismissed, per session (Story 11.1); also local. */inboxState: join(base, "state", "inbox.json"),- /** How wide the user dragged each session's message rows on the map; also local. */- rowWidths: join(base, "state", "row-widths.json"),+ /** How the user left the map: open sessions and dragged row widths; also local. */+ mapView: join(base, "state", "map.json"),/** What the detached hook children (build, side run) printed; local, capped. */detachedLog: join(base, "state", "detached.log"),locks: join(base, "locks"),diff --git a/packages/cli/src/store/row-widths.ts b/packages/cli/src/store/row-widths.tsdeleted file mode 100644index ccaddb1..0000000--- a/packages/cli/src/store/row-widths.ts+++ /dev/null@@ -1,63 +0,0 @@-import { z } from "zod";-import { atomicWriteJson, readJson } from "./fs.js";-import { withLock } from "./lock.js";-import { projectPaths } from "./paths.js";--/**- * How wide the user dragged each session's message rows on the map. A view- * preference, so it is local per-user state under `.cogit/state/` like the read- * marks: never committed, so one person's wide screen never reshapes a- * teammate's map. The page keeps the width in range; this file only checks that- * it is a sane number.- */--export const ROW_WIDTHS_SCHEMA = 1;--const SESSION_ID = /^[A-Za-z0-9._:-]{1,128}$/;-/** Far past anything the map lets a drag reach. */-const MAX_WIDTH = 10_000;--export const RowWidths = z.object({- schema: z.literal(ROW_WIDTHS_SCHEMA),- /** Session id → the message rows' width in map pixels. */- widths: z.record(z.string(), z.number().int().positive().max(MAX_WIDTH)).default({}),-});--export type RowWidths = z.infer<typeof RowWidths>;--/** The stored widths. A missing or unreadable file is "nothing dragged yet". */-export async function readRowWidths(root: string): Promise<Record<string, number>> {- const read = await readJson(projectPaths(root).rowWidths);- if (!read.found || "error" in read) return {};- const parsed = RowWidths.safeParse(read.value);- return parsed.success ? parsed.data.widths : {};-}--/**- * Stores one session's width, or forgets it (`null`, the double-click reset).- * The file is derived state: an unreadable one is replaced rather than blocking- * the drag.- */-export async function setRowWidth(- root: string,- sessionId: string,- width: number | null,-): Promise<void> {- if (!SESSION_ID.test(sessionId)) throw new Error(`not a session id: ${sessionId}`);- if (width !== null && !(Number.isInteger(width) && width > 0 && width <= MAX_WIDTH))- throw new Error(`not a row width: ${width}`);- const paths = projectPaths(root);- await withLock(- paths.lock("row-widths"),- async () => {- const widths = await readRowWidths(root);- if (width === null) delete widths[sessionId];- else widths[sessionId] = width;- const sorted = Object.fromEntries(- Object.entries(widths).sort(([a], [b]) => a.localeCompare(b)),- );- await atomicWriteJson(paths.rowWidths, { schema: ROW_WIDTHS_SCHEMA, widths: sorted });- },- { timeoutMs: 2000 },- );-}diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.tsindex 2da80f2..9d4b9b2 100644--- a/packages/cli/src/view/model.ts+++ b/packages/cli/src/view/model.ts@@ -313,10 +313,15 @@ export interface LineageViewModel {read?: string[];/*** How wide the user dragged each session's message rows, by session id, from- * `.cogit/state/row-widths.json` at build time. Local state like `read`.- * Absent on pages built before it.+ * `.cogit/state/map.json` at build time. Local state like `read`. Absent on+ * pages built before it.*/rowWidths?: Record<string, number>;+ /**+ * Sessions the user left open on the map, from `.cogit/state/map.json` at+ * build time, so a reload opens them again. Absent on pages built before it.+ */+ openSessions?: string[];/*** The "your turn" inbox for this project only (Story 11.1). Absent on pages* built before it; a project's map never carries another project's rows.diff --git a/packages/cli/test/map-view.test.ts b/packages/cli/test/map-view.test.tsnew file mode 100644index 0000000..0296102--- /dev/null+++ b/packages/cli/test/map-view.test.ts@@ -0,0 +1,54 @@+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { MAX_OPEN, readMapView, setOpenSessions, setRowWidth } from "../src/store/map-view.js";+import { projectPaths } from "../src/store/paths.js";++describe("map view state", () => {+ let root: string;+ beforeEach(async () => {+ root = await mkdtemp(join(tmpdir(), "cogit-map-view-"));+ });+ afterEach(async () => {+ await rm(root, { recursive: true, force: true });+ });++ it("stores, replaces and forgets a session's width", async () => {+ expect((await readMapView(root)).rowWidths).toEqual({});+ await setRowWidth(root, "b", 700);+ await setRowWidth(root, "a", 900);+ await setRowWidth(root, "b", 640);+ expect((await readMapView(root)).rowWidths).toEqual({ a: 900, b: 640 });+ await setRowWidth(root, "a", null);+ expect((await readMapView(root)).rowWidths).toEqual({ b: 640 });+ });++ it("stores the open sessions next to the widths without touching them", async () => {+ await setRowWidth(root, "a", 700);+ await setOpenSessions(root, ["b", "a", "b"]);+ expect(await readMapView(root)).toEqual({ schema: 1, rowWidths: { a: 700 }, open: ["b", "a"] });+ await setOpenSessions(root, []);+ expect((await readMapView(root)).open).toEqual([]);+ expect((await readMapView(root)).rowWidths).toEqual({ a: 700 });+ });++ it("refuses a bad session id, width or list", async () => {+ await expect(setRowWidth(root, "bad id!", 700)).rejects.toThrow("not a session id");+ await expect(setRowWidth(root, "a", 0)).rejects.toThrow("not a row width");+ await expect(setRowWidth(root, "a", 1.5)).rejects.toThrow("not a row width");+ await expect(setRowWidth(root, "a", 20_000)).rejects.toThrow("not a row width");+ await expect(setOpenSessions(root, ["bad id!"])).rejects.toThrow("not a session id");+ const many = Array.from({ length: MAX_OPEN + 1 }, (_, at) => `s${at}`);+ await expect(setOpenSessions(root, many)).rejects.toThrow("too many open sessions");+ });++ it("reads a damaged file as nothing stored, and replaces it on the next write", async () => {+ const file = projectPaths(root).mapView;+ await mkdir(join(file, ".."), { recursive: true });+ await writeFile(file, '{"schema":1,"rowWidths":{"a":"wide"}}');+ expect(await readMapView(root)).toEqual({ schema: 1, rowWidths: {}, open: [] });+ await setRowWidth(root, "a", 700);+ expect((await readMapView(root)).rowWidths).toEqual({ a: 700 });+ });+});diff --git a/packages/cli/test/row-widths.test.ts b/packages/cli/test/row-widths.test.tsdeleted file mode 100644index 263d024..0000000--- a/packages/cli/test/row-widths.test.ts+++ /dev/null@@ -1,42 +0,0 @@-import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { projectPaths } from "../src/store/paths.js";-import { readRowWidths, setRowWidth } from "../src/store/row-widths.js";--describe("row widths state", () => {- let root: string;- beforeEach(async () => {- root = await mkdtemp(join(tmpdir(), "cogit-row-widths-"));- });- afterEach(async () => {- await rm(root, { recursive: true, force: true });- });-- it("stores, replaces and forgets a session's width", async () => {- expect(await readRowWidths(root)).toEqual({});- await setRowWidth(root, "b", 700);- await setRowWidth(root, "a", 900);- await setRowWidth(root, "b", 640);- expect(await readRowWidths(root)).toEqual({ a: 900, b: 640 });- await setRowWidth(root, "a", null);- expect(await readRowWidths(root)).toEqual({ b: 640 });- });-- it("refuses a bad session id or width", async () => {- await expect(setRowWidth(root, "bad id!", 700)).rejects.toThrow("not a session id");- await expect(setRowWidth(root, "a", 0)).rejects.toThrow("not a row width");- await expect(setRowWidth(root, "a", 1.5)).rejects.toThrow("not a row width");- await expect(setRowWidth(root, "a", 20_000)).rejects.toThrow("not a row width");- });-- it("reads a damaged file as nothing stored, and replaces it on the next write", async () => {- const file = projectPaths(root).rowWidths;- await mkdir(join(file, ".."), { recursive: true });- await writeFile(file, '{"schema":1,"widths":{"a":"wide"}}');- expect(await readRowWidths(root)).toEqual({});- await setRowWidth(root, "a", 700);- expect(await readRowWidths(root)).toEqual({ a: 700 });- });-});diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.tsindex c1571b0..336c0b1 100644--- a/packages/cli/test/server.test.ts+++ b/packages/cli/test/server.test.ts@@ -29,9 +29,9 @@ import {} from "../src/server.js";import { atomicWrite } from "../src/store/fs.js";import { readInboxDismissed } from "../src/store/inbox-state.js";+import { readMapView } from "../src/store/map-view.js";import { globalPaths, projectPaths } from "../src/store/paths.js";import { readReadState } from "../src/store/read-state.js";-import { readRowWidths } from "../src/store/row-widths.js";import { loadConfig, updateConfig } from "../src/store/stores.js";import { DATA_ELEMENT_ID, LIVE_META_NAME, TOKEN_META_NAME } from "../src/view/model.js";import { envFor, fakeIo, noGitProject, tempDir } from "./helpers.js";@@ -913,9 +913,9 @@ describe("row width endpoint", () => {const reply = await widthWrite(server, token, { dir: root, sessionId: SESSION, width: 840 });expect(reply.status).toBe(200);expect(JSON.parse(reply.body)).toEqual({ ok: true, sessionId: SESSION, width: 840 });- expect(await readRowWidths(root)).toEqual({ [SESSION]: 840 });+ expect((await readMapView(root)).rowWidths).toEqual({ [SESSION]: 840 });await widthWrite(server, token, { dir: root, sessionId: SESSION, width: null });- expect(await readRowWidths(root)).toEqual({});+ expect((await readMapView(root)).rowWidths).toEqual({});});it("refuses a foreign project, a bad payload, a bad token and a bad body", async () => {@@ -945,21 +945,36 @@ describe("row width endpoint", () => {expect((await widthWrite(server, token, { ...good, pad: "x".repeat(5000) })).status).toBe(413);});- it("reads the stored widths back for a reload that beats the rebuild", async () => {+ it("stores the open sessions and reads the whole view back for a reload", async () => {const server = await start();const token = await panelToken(server);await widthWrite(server, token, { dir: root, sessionId: SESSION, width: 840 });+ const post = (payload: unknown): Promise<Reply> =>+ postConfig(`${server.url}/api/open-sessions`, JSON.stringify(payload), {+ origin: `http://127.0.0.1:${server.port}`,+ [CONFIG_TOKEN_HEADER]: token,+ });+ expect((await post({ dir: root, open: [SESSION] })).status).toBe(200);+ expect((await post({ dir: root, open: ["bad id!"] })).status).toBe(400);+ expect((await post({ dir: root, open: "x" })).status).toBe(400);+ expect((await post({ dir: join(dir, "elsewhere"), open: [] })).status).toBe(403);+ expect((await post({ open: [] })).status).toBe(400);+const headers = { origin: `http://127.0.0.1:${server.port}`, [CONFIG_TOKEN_HEADER]: token };- const url = `${server.url}/api/row-width?dir=${encodeURIComponent(root)}`;+ const url = `${server.url}/api/map-view?dir=${encodeURIComponent(root)}`;const reply = await request(url, headers);expect(reply.status).toBe(200);- expect(JSON.parse(reply.body)).toEqual({ ok: true, widths: { [SESSION]: 840 } });+ expect(JSON.parse(reply.body)).toEqual({+ ok: true,+ rowWidths: { [SESSION]: 840 },+ open: [SESSION],+ });expect((await request(url, { ...headers, [CONFIG_TOKEN_HEADER]: "nope" })).status).toBe(403);- expect((await request(`${server.url}/api/row-width`, headers)).status).toBe(400);+ expect((await request(`${server.url}/api/map-view`, headers)).status).toBe(400);expect((await request(- `${server.url}/api/row-width?dir=${encodeURIComponent(join(dir, "elsewhere"))}`,+ `${server.url}/api/map-view?dir=${encodeURIComponent(join(dir, "elsewhere"))}`,headers,)).status,@@ -970,9 +985,15 @@ describe("row width endpoint", () => {it("answers 500 instead of crashing when the state cannot be written", async () => {const server = await start();const token = await panelToken(server);- await mkdir(projectPaths(root).rowWidths, { recursive: true });+ await mkdir(projectPaths(root).mapView, { recursive: true });const reply = await widthWrite(server, token, { dir: root, sessionId: SESSION, width: 700 });expect(reply.status).toBe(500);+ const open = await postConfig(+ `${server.url}/api/open-sessions`,+ JSON.stringify({ dir: root, open: [SESSION] }),+ { origin: `http://127.0.0.1:${server.port}`, [CONFIG_TOKEN_HEADER]: token },+ );+ expect(open.status).toBe(500);});});diff --git a/packages/template/src/Graph.tsx b/packages/template/src/Graph.tsxindex acbfff0..2c5b56a 100644--- a/packages/template/src/Graph.tsx+++ b/packages/template/src/Graph.tsx@@ -10,11 +10,19 @@ import {useReactFlow,} from "@xyflow/react";import "@xyflow/react/dist/style.css";-import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";+import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";import { unreadViewMessages } from "../../cli/src/view/change.js";import type { LineageViewModel, ViewSession } from "../../cli/src/view/model.js";import { hitMessageIds, hitSessionIds } from "../../cli/src/view/search.js";-import { loadRowWidths, pageToken, saveRead, saveRowWidth } from "./data.js";+import { loadMapView, pageToken, saveOpenSessions, saveRead, saveRowWidth } from "./data.js";import { type FilesTarget, FilesView } from "./FilesView.js";import { useFullscreen } from "./fullscreen.js";import { GitGraph } from "./GitGraph.js";@@ -26,7 +34,7 @@ import { RowEdge, type RowWidths, rowWidthsOf } from "./RowEdge.js";import { OPEN_LINK_DROP, SessionMap } from "./SessionMap.js";import { DrillDown, type Selection } from "./SidePanel.js";import { usePageWheel } from "./scroll.js";-import { layoutSessionGraph, type SessionGraph } from "./sessionLayout.js";+import { layoutSessionGraph, openAtLoad, type SessionGraph } from "./sessionLayout.js";import { useTheme } from "./ThemeButton.js";import { UnreadView } from "./UnreadView.js";@@ -221,6 +229,10 @@ function readTarget(model: LineageViewModel): Target | null {return { sessionId };}+function sameSet(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {+ return a.size === b.size && [...a].every((id) => b.has(id));+}+function findSession(model: LineageViewModel, id: string): ViewSession | undefined {for (const epoch of model.epochs) {const session = epoch.sessions.find((candidate) => candidate.sessionId === id);@@ -239,8 +251,8 @@ function Flow({ model, search }: { model: LineageViewModel; search: MapSearchStaif (initial?.messageId !== undefined)document.querySelector(".lineage-map")?.scrollIntoView({ block: "start" });}, [initial]);- const [openIds, setOpenIds] = useState<ReadonlySet<string>>(- () => new Set(initial === null ? [] : [initial.sessionId]),+ const [openIds, setOpenIds] = useState<ReadonlySet<string>>(() =>+ openAtLoad(model, model.openSessions, initial),);const [selection, setSelection] = useState<Selection | null>(() => {if (initial === null || initial.quiet) return null;@@ -250,17 +262,44 @@ function Flow({ model, search }: { model: LineageViewModel; search: MapSearchStaconst [unfolded, setUnfolded] = useState<Set<string>>(() => new Set());/** Each session's message row width, dragged at the rows' right edge. */const [rowWidths, setRowWidths] = useState<RowWidths>(() => rowWidthsOf(model.rowWidths));- // The embedded widths are as of the last build; a reload right after a drag- // can beat the rebuild, so a served page asks for the stored ones once.+ /** Bumped when the stored view opens other sessions than the embedded one did. */+ const [refocus, setRefocus] = useState(0);+ /** Open sessions are stored only once the stored view has been read. */+ const viewLoaded = useRef(false);+ // The embedded view is as of the last build; a reload right after a change+ // can beat the rebuild, so a served page asks for the stored one once.useEffect(() => {const token = pageToken();if (token === null) return;- void loadRowWidths(model.project.path, token)- .then((widths) => setRowWidths(rowWidthsOf(widths)))+ void loadMapView(model.project.path, token)+ .then((view) => {+ setRowWidths(rowWidthsOf(view.rowWidths));+ const open = openAtLoad(model, view.open, initial);+ setOpenIds((previous) => {+ if (sameSet(previous, open)) return previous;+ setRefocus((value) => value + 1);+ return open;+ });+ }).catch(() => {- // The embedded widths stay; they are at most one drag behind.+ // The embedded view stays; it is at most one change behind.+ })+ .finally(() => {+ viewLoaded.current = true;});- }, [model.project.path]);+ // Once per page: later model swaps carry the view the page itself wrote.+ }, []);+ // Every open or close is stored, so a reload opens the same sessions again.+ useEffect(() => {+ const token = pageToken();+ if (token === null || !viewLoaded.current) return;+ const timer = window.setTimeout(() => {+ void saveOpenSessions(model.project.path, [...openIds], token).catch((err: unknown) => {+ console.warn("cogit: could not save the open sessions", err);+ });+ }, 300);+ return () => window.clearTimeout(timer);+ }, [openIds, model.project.path]);const resizeRows = useCallback((sessionId: string, width: number) => {setRowWidths((previous) => {// Back at the default (double-click): forget the session.@@ -818,6 +857,7 @@ function Flow({ model, search }: { model: LineageViewModel; search: MapSearchStasearchJump={searchJump}fileJump={fileJump}fit={fits}+ refocus={refocus}/>)}<DrillDown@@ -855,6 +895,7 @@ function MapCanvas({searchJump,fileJump,fit,+ refocus,}: {nodes: MapFlowNode[];/** Point to centre on at load; null fits the whole graph. */@@ -867,6 +908,8 @@ function MapCanvas({fileJump: { key: number; point: { x: number; y: number } } | null;/** A new value frames the whole map again (after "Fold all"). */fit: number;+ /** A new value centres on `focusRow` again: the stored view opened more sessions. */+ refocus: number;}) {const { fitView, setViewport } = useReactFlow();const theme = useTheme();@@ -912,6 +955,13 @@ function MapCanvas({centre(filePoint);}, [fileKey, filePoint]);+ useEffect(() => {+ if (refocus === 0 || focusRow === null) return;+ const canvas = document.querySelector(".react-flow")?.getBoundingClientRect();+ if (canvas) void setViewport(centreViewport(focusRow, canvas, 0.9));+ // Only the stored view arriving moves the view; `focusRow` follows it.+ }, [refocus]);+useEffect(() => {const timer = window.setTimeout(() => {const canvas = document.querySelector(".react-flow")?.getBoundingClientRect();diff --git a/packages/template/src/data.ts b/packages/template/src/data.tsindex 9dee868..08ce7b2 100644--- a/packages/template/src/data.ts+++ b/packages/template/src/data.ts@@ -99,20 +99,40 @@ export async function saveRead(}/**- * The stored row widths as they are now. The page embeds them at build time,- * but a reload right after a drag can beat the rebuild, so the page asks too.+ * How the user left the map (open sessions, row widths) as stored now. The page+ * embeds it at build time, but a reload right after a change can beat the+ * rebuild, so the page asks too.*/-export async function loadRowWidths(dir: string, token: string): Promise<unknown> {- const response = await fetch(`/api/row-width?dir=${encodeURIComponent(dir)}`, {+export async function loadMapView(+ dir: string,+ token: string,+): Promise<{ rowWidths?: unknown; open?: unknown }> {+ const response = await fetch(`/api/map-view?dir=${encodeURIComponent(dir)}`, {headers: { "x-cogit-token": token },cache: "no-store",});if (!response.ok) {const text = (await response.text()).trim();- throw new Error(text || `could not read the row widths (HTTP ${response.status})`);+ throw new Error(text || `could not read the map view (HTTP ${response.status})`);+ }+ return (await response.json()) as { rowWidths?: unknown; open?: unknown };+}++/** Stores which sessions are open, so a reload opens them again; needs the local server. */+export async function saveOpenSessions(+ dir: string,+ open: readonly string[],+ token: string,+): Promise<void> {+ const response = await fetch("/api/open-sessions", {+ method: "POST",+ headers: { "content-type": "application/json", "x-cogit-token": token },+ body: JSON.stringify({ dir, open }),+ });+ if (!response.ok) {+ const text = (await response.text()).trim();+ throw new Error(text || `could not save the open sessions (HTTP ${response.status})`);}- const body = (await response.json()) as { widths?: unknown };- return body.widths;}/**diff --git a/packages/template/src/sessionLayout.ts b/packages/template/src/sessionLayout.tsindex 04580f3..b317e8f 100644--- a/packages/template/src/sessionLayout.ts+++ b/packages/template/src/sessionLayout.ts@@ -109,3 +109,20 @@ export function layoutSessionGraph(});return { git, sessions: byId, parents };}++/**+ * Sessions open when the page loads: the ones the user left open that still+ * exist, plus the session the page lands on.+ */+export function openAtLoad(+ model: LineageViewModel,+ stored: unknown,+ initial: { sessionId: string } | null,+): ReadonlySet<string> {+ const known = new Set(allSessions(model).map((session) => session.sessionId));+ const open = new Set<string>();+ if (Array.isArray(stored))+ for (const id of stored) if (typeof id === "string" && known.has(id)) open.add(id);+ if (initial !== null) open.add(initial.sessionId);+ return open;+}diff --git a/packages/template/test/sessionLayout.test.ts b/packages/template/test/sessionLayout.test.tsindex 2ce0ca3..24735d9 100644--- a/packages/template/test/sessionLayout.test.ts+++ b/packages/template/test/sessionLayout.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from "vitest";import type { LineageViewModel, ViewNode, ViewSession } from "../../cli/src/view/model.js";-import { allSessions, layoutSessionGraph, sessionParentOf } from "../src/sessionLayout.js";+import {+ allSessions,+ layoutSessionGraph,+ openAtLoad,+ sessionParentOf,+} from "../src/sessionLayout.js";/** Minutes after 2026-10-24T10:00Z, so spans are easy to read. */function at(minutes: number): string {@@ -140,3 +145,15 @@ describe("layoutSessionGraph", () => {expect(head?.head).toBe(true);});});++describe("openAtLoad", () => {+ it("reopens the stored sessions that still exist, plus the one the page lands on", () => {+ const model = modelOf([session("a", 0, 30), session("b", 60, 90), session("c", 100, 120)]);+ expect([...openAtLoad(model, ["a", "gone", 7, "b"], { sessionId: "c" })]).toEqual([+ "a",+ "b",+ "c",+ ]);+ expect([...openAtLoad(model, "junk", null)]).toEqual([]);+ });+});