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(inbox): show every project's "your turn" sessions with where-were-we
Erenb82f7980c32f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7f1cb11..5bec0e9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,8 @@ 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+- A "Your turn" inbox above the panel's project cards and in a project map's head: one row per session whose transcript ends with the agent (read through the agent adapter) or whose record has `needsUser` items, oldest first, with the project, session title, how long it has waited, the agent's last message (first 300 characters, verbatim), the record's goal/last decision/open items labelled as the record's, and buttons to open the map at the session's newest message, copy the resume command, and dismiss. The dismissal lives in `.cogit/state/inbox.json` (local, never committed) and a newer agent turn brings the row back; `inboxMaxAgeDays` (default 7) hides older sessions, and the local server writes a dismissal through `POST /api/inbox/dismiss`.## [0.13.0] - 2026-10-27### Addeddiff --git a/docs/schema/config.json b/docs/schema/config.jsonindex a1b4b4c..36df914 100644--- a/docs/schema/config.json+++ b/docs/schema/config.json@@ -79,6 +79,12 @@"default": true,"type": "boolean"},+ "inboxMaxAgeDays": {+ "default": 7,+ "type": "integer",+ "minimum": 1,+ "maximum": 3650+ },"agents": {"default": ["claude-code"@@ -113,6 +119,7 @@"trailerMaxAgeHours","bigChangeLines","tryBeforeNotes",+ "inboxMaxAgeDays","agents","setupHintOff"],diff --git a/packages/cli/src/agents/claude/index.ts b/packages/cli/src/agents/claude/index.tsindex 026504a..568a1aa 100644--- a/packages/cli/src/agents/claude/index.ts+++ b/packages/cli/src/agents/claude/index.ts@@ -17,6 +17,7 @@ import {excerpt,findTranscript,readConversation,+ readLastTurn,readsHandoff,} from "./transcripts.js";@@ -41,6 +42,7 @@ export const claude: AgentAdapter = {collectTranscriptIds,readConversation,readsHandoff,+ readLastTurn,countUserLines,displayTurn,excerpt,diff --git a/packages/cli/src/agents/claude/transcripts.ts b/packages/cli/src/agents/claude/transcripts.tsindex 73939d2..a89a27f 100644--- a/packages/cli/src/agents/claude/transcripts.ts+++ b/packages/cli/src/agents/claude/transcripts.ts@@ -1,9 +1,9 @@import { createReadStream } from "node:fs";-import { access, readdir } from "node:fs/promises";+import { access, type FileHandle, open, readdir } from "node:fs/promises";import { homedir } from "node:os";import { join } from "node:path";import { createInterface } from "node:readline";-import type { ChatTurn, ToolUse, UserMessage } from "../types.js";+import type { ChatTurn, LastTurn, ToolUse, UserMessage } from "../types.js";/*** Reading Claude Code's transcripts. A session is one JSONL file under@@ -250,6 +250,132 @@ export async function readConversation(file: string): Promise<ChatTurn[]> {return turns;}+/**+ * How many bytes from the end of a transcript `readLastTurn` reads first+ * (Story 11.1). The last turn is nearly always in here; a longer turn makes the+ * reader walk further back a window at a time.+ */+export const LAST_TURN_TAIL_BYTES = 256 * 1024;++/** What scanning a transcript for its ending keeps. */+interface TurnState {+ /** A user message was typed somewhere in the scanned window. */+ userSeen: boolean;+ userAt: string | null;+ /** The last agent text line after the newest user message. */+ agentAt: string | null;+ agentText: string | null;+}++/** Reads a byte range from an open file, however many reads the OS needs. */+async function readRange(handle: FileHandle, start: number, end: number): Promise<Buffer> {+ const buffer = Buffer.allocUnsafe(end - start);+ let offset = 0;+ // A POSIX read may return less than asked; `end` is inside the file, so this+ // loop cannot stall at zero.+ while (offset < buffer.length) {+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, start + offset);+ offset += bytesRead;+ }+ return buffer.subarray(0, offset);+}++/**+ * Applies the lines of one transcript stretch to the tail state. A user line is+ * a message only when {@link messageText} says the user typed it, so tool+ * results and injected reminders leave the turn alone; an assistant line with+ * written text is the agent's reply. A new user message starts a new turn.+ */+function scanLastTurn(raw: string, state: TurnState): void {+ for (const line of raw.split("\n")) {+ const user = line.includes('"type":"user"');+ if (!user && !line.includes('"type":"assistant"')) continue;+ let parsed: Record<string, unknown>;+ try {+ parsed = JSON.parse(line);+ } catch {+ continue;+ }+ if (parsed.type === "user") {+ if (messageText(parsed) === null || typeof parsed.timestamp !== "string") continue;+ state.userSeen = true;+ state.userAt = parsed.timestamp;+ state.agentAt = null;+ state.agentText = null;+ continue;+ }+ if (parsed.type !== "assistant" || parsed.isSidechain) continue;+ const content = (parsed.message as { content?: unknown } | undefined)?.content;+ if (!Array.isArray(content)) continue;+ const texts = content+ .filter(+ (block): block is { type: "text"; text: string } =>+ block?.type === "text" && typeof block.text === "string" && block.text.trim() !== "",+ )+ .map((block) => block.text);+ if (texts.length === 0 || typeof parsed.timestamp !== "string") continue;+ state.agentAt = parsed.timestamp;+ state.agentText = texts.join("\n");+ }+}++/** Whether one downloaded window holds a user message, without keeping its state. */+function containsUserMessage(raw: string): boolean {+ const probe: TurnState = { userSeen: false, userAt: null, agentAt: null, agentText: null };+ scanLastTurn(raw, probe);+ return probe.userSeen;+}++/**+ * Who spoke last, read from the end of the transcript (Story 11.1). The state is+ * the last user message plus the agent's last written reply after it: the agent+ * wrote last means it is the user's turn, the user wrote last means the agent is+ * still working (or has not started). Null when no user message was typed.+ *+ * Reads the last {@link LAST_TURN_TAIL_BYTES} first and walks back only as far+ * as the newest user message, so a panel over every project does not reread+ * whole transcripts. Unreadable files are the caller's to handle.+ */+export async function readLastTurn(file: string): Promise<LastTurn | null> {+ const handle = await open(file, "r");+ try {+ const { size } = await handle.stat();+ if (size === 0) return null;+ // Windows are kept newest first, then joined in file order and decoded once,+ // so a multi-byte character split by a window edge is still intact.+ const windows: Buffer[] = [];+ let end = size;+ let start = 0;+ let found = false;+ let text = "";+ while (end > 0) {+ start = Math.max(0, end - LAST_TURN_TAIL_BYTES);+ windows.unshift(await readRange(handle, start, end));+ text = Buffer.concat(windows).toString("utf8");+ // A window that starts mid-file starts mid-line; that line is complete in+ // the newer window it continues into, so only the first partial goes.+ if (start > 0) {+ const newline = text.indexOf("\n");+ text = newline === -1 ? "" : text.slice(newline + 1);+ }+ if (containsUserMessage(text)) {+ found = true;+ break;+ }+ end = start;+ }+ // No user message anywhere: a transcript the user never typed into.+ if (!found) return null;+ const state: TurnState = { userSeen: false, userAt: null, agentAt: null, agentText: null };+ scanLastTurn(text, state);+ if (state.userAt === null) return null;+ if (state.agentAt === null) return { speaker: "user", at: state.userAt, text: "" };+ return { speaker: "agent", at: state.agentAt, text: state.agentText ?? "" };+ } finally {+ await handle.close();+ }+}+/*** Whether the transcript shows the agent reading a handoff file (Story 8.6): a* cheap hint that this session continues earlier work. A tool-use line names thediff --git a/packages/cli/src/agents/index.ts b/packages/cli/src/agents/index.tsindex 2214cf0..57c0b51 100644--- a/packages/cli/src/agents/index.ts+++ b/packages/cli/src/agents/index.ts@@ -19,6 +19,7 @@ export type {ChatTurn,FileChange,HookInput,+ LastTurn,ToolUse,UserMessage,} from "./types.js";diff --git a/packages/cli/src/agents/types.ts b/packages/cli/src/agents/types.tsindex 0f44ede..0da80bd 100644--- a/packages/cli/src/agents/types.ts+++ b/packages/cli/src/agents/types.ts@@ -43,6 +43,20 @@ export interface ChatTurn extends UserMessage {tools: ToolUse;}+/**+ * How a transcript ends (Story 11.1): the deterministic "your turn" signal.+ * The agent wrote after the newest user message, or that message is still+ * waiting for an answer. Who asked what is never guessed from the text.+ */+export interface LastTurn {+ /** `agent` when the agent wrote after the newest user message; else `user`. */+ speaker: "agent" | "user";+ /** Time of the last agent line (`agent`) or of the newest user message (`user`). */+ at: string;+ /** The agent's last written text, verbatim (empty for a `user` tail). */+ text: string;+}+/** The fields of a hook payload cogit relies on, however the agent names them. */export interface HookInput {session_id: string;@@ -106,6 +120,11 @@ export interface AgentAdapter {readConversation(file: string): Promise<ChatTurn[]>;/** Whether the transcript shows the agent reading a handoff file (Story 8.6). */readsHandoff(file: string): Promise<boolean>;+ /**+ * Who spoke last (Story 11.1), read from the end of the transcript. Null when+ * no user message was ever typed there.+ */+ readLastTurn(file: string): Promise<LastTurn | null>;/** Counts user-role lines, to tell "no messages" from "unreadable format". */countUserLines(file: string): Promise<number>;/** A turn as the map shows it: injected text removed, long text cut, paths relative. */diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.tsindex 4361bb4..853f7c0 100644--- a/packages/cli/src/commands/build.ts+++ b/packages/cli/src/commands/build.ts@@ -1,3 +1,4 @@+import { resolve } from "node:path";import { type ChatTurn, defaultAgent } from "../agents/index.js";import {type CommitChange,@@ -37,8 +38,9 @@ import { buildViewModel, embedViewModel } from "../view/lineage.js";import type { LineageViewModel, ViewChatTurn, ViewPendingMessage } from "../view/model.js";import {buildPanel,- type CollectedProject,- collectRegistryProjects,+ collectInboxForProject,+ collectRegistryData,+ type PanelData,panelSettings,} from "../view/panel.js";import { switcherEntries } from "../view/switcher.js";@@ -260,13 +262,13 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModel// The map's switcher (8.12) and the panel read the same project list; collect// it once. A broken registry is a warning: it must never fail the map.const generatedAt = io.now();- let panelProjects: CollectedProject[] = [];+ let panelData: PanelData = { projects: [], inbox: [] };try {- panelProjects = await collectRegistryProjects(io.env, generatedAt, io.warn, root);+ panelData = await collectRegistryData(io.env, generatedAt, io.warn, root);} catch (err) {io.warn(`could not read the project list: ${(err as Error).message}`);}- const switcher = switcherEntries(panelProjects, root);+ const switcher = switcherEntries(panelData.projects, root);// The Stop hook skips a turn while this lock is held, and a second build waits// for the first instead of interleaving reads and writes of the same files.@@ -308,6 +310,21 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModel});built.switcher = switcher;built.read = [...read].sort();+ // 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.+ const registered = panelData.projects.some(+ (candidate) => resolve(candidate.path) === resolve(root),+ );+ built.inbox = registered+ ? panelData.inbox.filter((row) => resolve(row.projectPath) === resolve(root))+ : await collectInboxForProject(+ { name: project.data.name, path: root },+ views.sessions,+ transcripts,+ config,+ generatedAt,+ );// The files view (8.15) unions each message's own files with the files of// its commits, so a message the agent listed no paths for still lands.built.files = buildFileHistory(modelSessions(built), commits.files);@@ -331,7 +348,7 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModelenv: io.env,io,templateHtml: opts.templateHtml ?? TEMPLATE_HTML,- projects: panelProjects,+ data: panelData,});} catch (err) {io.warn(`could not build panel.html: ${(err as Error).message}`);diff --git a/packages/cli/src/schema/config.ts b/packages/cli/src/schema/config.tsindex eaeb280..d04a001 100644--- a/packages/cli/src/schema/config.ts+++ b/packages/cli/src/schema/config.ts@@ -52,6 +52,11 @@ export const Config = z.object({* the record, never a rule; off means silence.*/tryBeforeNotes: z.boolean().default(true),+ /**+ * How many days a session stays in the "your turn" inbox (Story 11.1). Older+ * sessions are hidden; nothing is deleted.+ */+ inboxMaxAgeDays: z.int().min(1).max(3650).default(7),agents: z.array(z.string().min(1)).default(["claude-code"]),/** Project roots ("don't ask again" in this project) where the setup hint stays silent. */setupHintOff: z.array(z.string().min(1)).default([]),diff --git a/packages/cli/src/server.ts b/packages/cli/src/server.tsindex 3231d44..b3239f0 100644--- a/packages/cli/src/server.ts+++ b/packages/cli/src/server.ts@@ -17,6 +17,7 @@ import { diffTooLarge, isDiffSha, readCommitDiff } from "./diff.js";import { defaultsPrompter, type Io } from "./io.js";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 { globalPaths, projectPaths } from "./store/paths.js";import { setMessageRead } from "./store/read-state.js";@@ -590,6 +591,75 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>res.end(JSON.stringify({ ok: true, id, read }));}+ /**+ * `POST /api/inbox/dismiss` { dir, sessionId, at } (Story 11.1): the inbox's+ * dismiss button. It writes the project's local state file, and the turn time+ * is stored so a newer agent turn brings the row back. Same Host, Origin,+ * content-type and token checks as a read mark, and `dir` must be registered.+ */+ async function writeInboxDismiss(+ req: IncomingMessage,+ res: ServerResponse,+ port: number,+ ): Promise<void> {+ if (+ !originAllowed(req.headers.origin, port) ||+ !tokenMatches(req.headers[CONFIG_TOKEN_HEADER])+ ) {+ respond(res, 403, "forbidden");+ return;+ }+ const type = req.headers["content-type"];+ if (+ typeof type !== "string" ||+ type.split(";")[0]?.trim().toLowerCase() !== "application/json"+ ) {+ respond(res, 415, "content-type must be application/json");+ return;+ }+ const body = await readLimitedBody(req);+ if (body === null) {+ respond(res, 413, "request body too large");+ return;+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(body);+ } catch {+ respond(res, 400, "invalid JSON");+ return;+ }+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {+ respond(res, 400, "expected a JSON object");+ return;+ }+ const { dir, sessionId, at } = parsed as Record<string, unknown>;+ if (typeof dir !== "string" || typeof sessionId !== "string" || typeof at !== "string") {+ respond(res, 400, "expected { dir, sessionId, at }");+ return;+ }+ if (!/^[A-Za-z0-9._:-]{1,128}$/.test(sessionId) || Number.isNaN(Date.parse(at))) {+ respond(res, 400, "sessionId or at is not valid");+ return;+ }+ const root = await registeredRoot(env, dir);+ if (root === null) {+ respond(res, 403, "not a registered project");+ return;+ }+ try {+ await dismissInboxSession(root, sessionId, at);+ } catch {+ respond(res, 500, "could not write the inbox state");+ return;+ }+ res.writeHead(200, {+ "content-type": "application/json",+ "cache-control": "no-store",+ });+ res.end(JSON.stringify({ ok: true, sessionId, at }));+ }+async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {const port = (server.address() as AddressInfo | null)?.port ?? opts.port;if (req.method === "POST") {@@ -613,6 +683,10 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>await writeRead(req, res, port);return;}+ if (url.pathname === "/api/inbox/dismiss") {+ await writeInboxDismiss(req, res, port);+ return;+ }if (url.pathname !== "/api/config") {respond(res, 405, "method not allowed");return;diff --git a/packages/cli/src/store/inbox-state.ts b/packages/cli/src/store/inbox-state.tsnew file mode 100644index 0000000..c85f82d--- /dev/null+++ b/packages/cli/src/store/inbox-state.ts@@ -0,0 +1,63 @@+import { z } from "zod";+import { IsoDate } from "../schema/common.js";+import { atomicWriteJson, readJson } from "./fs.js";+import { withLock } from "./lock.js";+import { projectPaths } from "./paths.js";++/**+ * Which inbox rows the user dismissed (Story 11.1), local per project like the+ * read marks: a dismissal is an action the user took, never inferred. The stored+ * value is the turn time that was dismissed, so a newer agent turn on the same+ * session brings the row back without a second flag.+ */++export const INBOX_STATE_SCHEMA = 1;++const SESSION_ID = /^[A-Za-z0-9._:-]{1,128}$/;++export const InboxState = z.object({+ schema: z.literal(INBOX_STATE_SCHEMA),+ /** Session id → the ISO turn time the user dismissed. */+ dismissed: z.record(z.string(), IsoDate).default({}),+});++export type InboxState = z.infer<typeof InboxState>;++/**+ * Dismissed turn times by session id. A missing or unreadable file is "nothing+ * dismissed": the inbox is derived state and must not fail a build over it.+ */+export async function readInboxDismissed(root: string): Promise<Map<string, string>> {+ const read = await readJson(projectPaths(root).inboxState);+ if (!read.found || "error" in read) return new Map();+ const parsed = InboxState.safeParse(read.value);+ return new Map(parsed.success ? Object.entries(parsed.data.dismissed) : []);+}++/**+ * Records that the user dismissed a session at one turn time. The file is+ * derived state: an unreadable one is replaced rather than blocking the click.+ */+export async function dismissInboxSession(+ root: string,+ sessionId: string,+ at: string,+): Promise<void> {+ if (!SESSION_ID.test(sessionId)) throw new Error(`not a session id: ${sessionId}`);+ const stamp = Date.parse(at);+ if (Number.isNaN(stamp)) throw new Error(`not a time: ${at}`);+ const paths = projectPaths(root);+ await withLock(+ paths.lock("inbox-state"),+ async () => {+ const dismissed = await readInboxDismissed(root);+ dismissed.set(sessionId, at);+ const sorted = Object.fromEntries([...dismissed].sort(([a], [b]) => a.localeCompare(b)));+ await atomicWriteJson(paths.inboxState, {+ schema: INBOX_STATE_SCHEMA,+ dismissed: sorted,+ });+ },+ { timeoutMs: 2000 },+ );+}diff --git a/packages/cli/src/store/paths.ts b/packages/cli/src/store/paths.tsindex db0e867..a14c848 100644--- a/packages/cli/src/store/paths.ts+++ b/packages/cli/src/store/paths.ts@@ -38,6 +38,8 @@ export function projectPaths(root: string) {* policies).*/readState: join(base, "state", "read.json"),+ /** Inbox rows the user dismissed, per session (Story 11.1); also local. */+ inboxState: join(base, "state", "inbox.json"),locks: join(base, "locks"),/** Where the skill drops session JSON for `session write --file`. */inbox: (id: string) => join(base, "inbox", `${id}.json`),diff --git a/packages/cli/src/view/inbox.ts b/packages/cli/src/view/inbox.tsnew file mode 100644index 0000000..825ab8f--- /dev/null+++ b/packages/cli/src/view/inbox.ts@@ -0,0 +1,137 @@+import type { ViewInboxRow, ViewPendingItem } from "./model.js";++/**+ * The "your turn" inbox (Story 11.1), as pure data work: collection reads+ * transcripts and records, this module decides what a page shows. Kept free of+ * Node imports because the browser template imports it too.+ */++/** How much of the agent's last message a row keeps, verbatim. */+export const INBOX_MESSAGE_LIMIT = 300;++/** How many open pending items a where-were-we line lists. */+export const INBOX_PENDING_LIMIT = 5;++/** One session as the builder found it, before age and dismissal are applied. */+export interface InboxCandidate {+ projectName: string;+ projectPath: string;+ /** `file://` URL of the project's map. */+ mapUrl: string;+ sessionId: string;+ sessionTitle: string;+ /** The agent's last turn, when the transcript ends with it. */+ turn: { at: string; text: string } | null;+ /** The newest time the record knows about, for a record-only row. */+ lastActivity: string | null;+ /** Open pending items flagged `needsUser`. */+ needsUser: string[];+ goal: string;+ lastDecision: string;+ pending: ViewPendingItem[];+ /** The session's newest message id, when it has one. */+ messageId: string | null;+ transcriptAvailable: boolean;+}++/** A dismissal is per session, and a project keeps its own copy of the state. */+export function dismissKey(projectPath: string, sessionId: string): string {+ return `${projectPath}\0${sessionId}`;+}++const DAY_MS = 24 * 60 * 60 * 1000;++function parsed(iso: string | null): number {+ if (iso === null) return Number.NEGATIVE_INFINITY;+ const time = Date.parse(iso);+ return Number.isNaN(time) ? Number.NEGATIVE_INFINITY : time;+}++/** First `limit` characters of a message, with an ellipsis when it was cut. */+export function clipMessage(text: string, limit = INBOX_MESSAGE_LIMIT): string {+ return text.length <= limit ? text : `${text.slice(0, limit - 1)}…`;+}++/**+ * The rows a page shows, oldest first. A candidate is a row when it has a turn+ * or a `needsUser` item; a session older than `maxAgeDays` is hidden, and so is+ * one the user dismissed at that same turn (a newer turn brings it back).+ * `dismissed` is keyed by {@link dismissKey}; an unparseable time never hides a+ * row, because a broken value must not silently lose work.+ */+export function inboxRows(+ candidates: InboxCandidate[],+ dismissed: ReadonlyMap<string, string>,+ now: string,+ maxAgeDays: number,+): ViewInboxRow[] {+ const cutoff = Date.parse(now) - maxAgeDays * DAY_MS;+ const rows: ViewInboxRow[] = [];+ for (const candidate of candidates) {+ const turnAt = candidate.turn?.at ?? null;+ const at = turnAt ?? candidate.lastActivity;+ if (at === null) continue;+ const atMs = parsed(at);+ // The age filter applies to every row, including a record-only one.+ if (atMs === Number.NEGATIVE_INFINITY) continue;+ if (!Number.isNaN(cutoff) && atMs < cutoff) continue;+ const dismissedAt = dismissed.get(dismissKey(candidate.projectPath, candidate.sessionId));+ if (dismissedAt !== undefined && parsed(dismissedAt) >= atMs) continue;+ const signal: ViewInboxRow["signal"] =+ turnAt !== null && candidate.needsUser.length > 0+ ? "both"+ : turnAt !== null+ ? "turn"+ : "record";+ rows.push({+ projectName: candidate.projectName,+ projectPath: candidate.projectPath,+ mapUrl: candidate.mapUrl,+ sessionId: candidate.sessionId,+ sessionTitle: candidate.sessionTitle,+ signal,+ at,+ ...(turnAt !== null && candidate.turn !== null+ ? { lastMessage: clipMessage(candidate.turn.text) }+ : {}),+ goal: candidate.goal,+ lastDecision: candidate.lastDecision,+ pending: candidate.pending,+ ...(candidate.messageId === null ? {} : { messageId: candidate.messageId }),+ transcriptAvailable: candidate.transcriptAvailable,+ });+ }+ rows.sort(compareInboxRows);+ return rows;+}++/**+ * Oldest first, so the row that has waited longest is the one to go back to.+ * Name, path and session id keep equal times deterministic.+ */+export function compareInboxRows(a: ViewInboxRow, b: ViewInboxRow): number {+ return (+ parsed(a.at) - parsed(b.at) ||+ a.projectName.localeCompare(b.projectName) ||+ a.projectPath.localeCompare(b.projectPath) ||+ a.sessionId.localeCompare(b.sessionId)+ );+}++/**+ * How long ago a moment was, in the page's words ("2 h", "3 days"). The label+ * never decides anything; an unparseable value renders as an empty string.+ */+export function timeSince(at: string, now: string): string {+ const then = Date.parse(at);+ const reference = Date.parse(now);+ if (Number.isNaN(then) || Number.isNaN(reference)) return "";+ const seconds = Math.max(0, Math.floor((reference - then) / 1000));+ if (seconds < 60) return "under a minute";+ const minutes = Math.floor(seconds / 60);+ if (minutes < 60) return `${minutes} min`;+ const hours = Math.floor(minutes / 60);+ if (hours < 24) return `${hours} h`;+ const days = Math.floor(hours / 24);+ return days === 1 ? "1 day" : `${days} days`;+}diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.tsindex 37cf699..3aaccab 100644--- a/packages/cli/src/view/model.ts+++ b/packages/cli/src/view/model.ts@@ -243,6 +243,36 @@ export interface ViewSwitcherProject {current: boolean;}+/**+ * One row of the "your turn" inbox (Story 11.1): a session across the registered+ * projects whose transcript ends with the agent's turn, or whose record has+ * pending items flagged `needsUser`. The two signals stay apart: `signal` says+ * which put the row there, and a record-only row carries no `lastMessage`.+ */+export interface ViewInboxRow {+ projectName: string;+ projectPath: string;+ /** `file://` URL of the project's map; ignored by a page the server serves. */+ mapUrl: string;+ sessionId: string;+ /** The session's title, or its id when the record has none yet. */+ sessionTitle: string;+ /** `turn` when the transcript ends with the agent, `record` for `needsUser`. */+ signal: "turn" | "record" | "both";+ /** Newest signal time (ISO): the agent's last turn, else the record's activity. */+ at: string;+ /** The agent's last written message, first ~300 characters, verbatim. */+ lastMessage?: string;+ /** Where-were-we, as the record wrote it; the page labels it as the record's. */+ goal: string;+ lastDecision: string;+ pending: ViewPendingItem[];+ /** The session's newest message id, for opening the map at it. */+ messageId?: string;+ /** False when the transcript is gone, so resume cannot work. */+ transcriptAvailable: boolean;+}+export interface LineageViewModel {kind: "lineage";schema: typeof VIEW_SCHEMA;@@ -279,6 +309,11 @@ export interface LineageViewModel {* a rebuild embeds the new list.*/read?: 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.+ */+ inbox?: ViewInboxRow[];}/**@@ -368,6 +403,11 @@ export interface PanelViewModel {settings: PanelSettings;/** Registry order. */projects: PanelProject[];+ /**+ * Every project's "your turn" rows, oldest first (Story 11.1). Absent on+ * pages built before it.+ */+ inbox?: ViewInboxRow[];}/** Either page the template can render; the embedded data decides which. */diff --git a/packages/cli/src/view/panel.ts b/packages/cli/src/view/panel.tsindex 5d106be..f1c5d3c 100644--- a/packages/cli/src/view/panel.ts+++ b/packages/cli/src/view/panel.ts@@ -1,17 +1,31 @@import { pathToFileURL } from "node:url";+import { defaultAgent } from "../agents/index.js";import type { Io } from "../io.js";import { redactDeep } from "../redact.js";import type { Config, RegistryEntry } from "../schema/config.js";import type { Session } from "../schema/session.js";import { readProjectChanges } from "../store/changes.js";import { atomicWrite, isDirectory } from "../store/fs.js";+import { readInboxDismissed } from "../store/inbox-state.js";import { globalPaths, projectPaths } from "../store/paths.js";import { readReadState } from "../store/read-state.js";import { loadAllSessions, loadConfig, loadRegistry } from "../store/stores.js";import { attachThoughtTrailers, earliestSessionStart, readThoughtTrailers } from "../thought.js";import { countBigUnread } from "./change.js";+import {+ compareInboxRows,+ dismissKey,+ INBOX_PENDING_LIMIT,+ type InboxCandidate,+ inboxRows,+} from "./inbox.js";import { embedViewModel, lastActive, statusCard } from "./lineage.js";-import { type PanelSettings, type PanelViewModel, VIEW_SCHEMA } from "./model.js";+import {+ type PanelSettings,+ type PanelViewModel,+ VIEW_SCHEMA,+ type ViewInboxRow,+} from "./model.js";import type { SwitcherSource } from "./switcher.js";import { TEMPLATE_HTML } from "./template.js";@@ -23,10 +37,10 @@ export interface PanelOptions {/** A project whose session warnings were already printed by the map build. */quietPath?: string;/**- * Projects the caller already collected (the map build needs the same data for+ * What the caller already collected (the map build needs the same projects for* its switcher); skipped, the panel reads the registry itself.*/- projects?: CollectedProject[];+ data?: PanelData;}/**@@ -60,9 +74,6 @@ export function panelSettings(config: Config): PanelSettings {};}-/** The schema default, for callers that collect cards without a config. */-const DEFAULT_BIG_CHANGE_LINES = 300;-/*** How many unread messages in this project crossed the threshold (Story 10.3).* The card count never fails a panel build: a missing git, a broken record or@@ -118,18 +129,127 @@ export function leftOffLine(sessions: Session[]): string {return newest.status.next.trim() || lastMessageTitle(newest);}+/** The newest message of a session, from the record's append order. */+function newestMessageId(session: Session): string | null {+ for (let index = session.nodes.length - 1; index >= 0; index -= 1) {+ const node = session.nodes[index];+ if (node?.kind === "message") return node.id;+ }+ return null;+}+/**- * One card per registry entry. A directory that is gone is marked missing- * instead of failing the panel; one unreadable project is a warning.+ * The record's last decision: the newest `decision` node, or the newest choice+ * the agent recorded on a message. Read as written; never inferred from text.*/-export async function collectPanelProjects(+export function lastDecisionOf(session: Session): string {+ let found = "";+ for (const node of session.nodes) {+ if (node.kind === "decision") found = node.title;+ else {+ const latest = node.agentDecisions?.at(-1);+ if (latest !== undefined) found = latest.title;+ }+ }+ return found;+}++/** The session's newest activity as ISO, or null when it has no usable time. */+function activityIso(session: Session): string | null {+ const time = lastActive(session);+ return Number.isFinite(time) ? new Date(time).toISOString() : null;+}++/** The open items the inbox's where-were-we line lists, capped for size. */+function openPending(session: Session) {+ return session.status.pending+ .slice(0, INBOX_PENDING_LIMIT)+ .map((item) => ({ text: item.text, needsUser: item.needsUser }));+}++/**+ * The "your turn" rows of one project (Story 11.1). The primary signal is the+ * transcript's ending through the agent adapter: the agent wrote last, so the+ * user has something to read or answer. The record's `needsUser` items are a+ * second signal and stay labelled as the record's. A session older than+ * `inboxMaxAgeDays` is skipped before its transcript is read.+ */+export async function collectInboxForProject(+ project: { name: string; path: string },+ sessions: Session[],+ transcripts: ReadonlyMap<string, string>,+ config: Config,+ now: string,+): Promise<ViewInboxRow[]> {+ const agent = defaultAgent();+ const cutoff = Date.parse(now) - config.inboxMaxAgeDays * 24 * 60 * 60 * 1000;+ const candidates: InboxCandidate[] = [];+ for (const session of sessions) {+ // Skip the transcript read for a session the age filter would hide anyway;+ // one day of grace keeps a reply that landed after the last message.+ const activity = lastActive(session);+ if (!Number.isNaN(cutoff) && activity < cutoff - 24 * 60 * 60 * 1000) continue;+ const file = transcripts.get(session.sessionId);+ let turn: InboxCandidate["turn"] = null;+ if (file !== undefined) {+ try {+ const last = await agent.readLastTurn(file);+ if (last?.speaker === "agent") turn = { at: last.at, text: last.text };+ } catch {+ // An unreadable transcript is a missing signal, never a failed build.+ }+ }+ const needsUser = session.status.pending+ .filter((item) => item.needsUser)+ .map((item) => item.text);+ if (turn === null && needsUser.length === 0) continue;+ candidates.push({+ projectName: project.name,+ projectPath: project.path,+ mapUrl: pathToFileURL(projectPaths(project.path).html).href,+ sessionId: session.sessionId,+ sessionTitle: session.title || session.sessionId,+ turn,+ lastActivity: activityIso(session),+ needsUser,+ goal: session.status.goal.trim(),+ lastDecision: lastDecisionOf(session),+ pending: openPending(session),+ messageId: newestMessageId(session),+ transcriptAvailable: file !== undefined,+ });+ }+ const dismissed = new Map(+ [...(await readInboxDismissed(project.path))].map(([id, at]) => [+ dismissKey(project.path, id),+ at,+ ]),+ );+ return inboxRows(candidates, dismissed, now, config.inboxMaxAgeDays);+}++/** A panel card plus the inbox rows, collected in one pass per project. */+export interface PanelData {+ projects: CollectedProject[];+ inbox: ViewInboxRow[];+}++/**+ * One card per registry entry, and the inbox rows they carry. A directory that+ * is gone is marked missing instead of failing the panel; one unreadable+ * project is a warning.+ */+export async function collectPanelData(entries: RegistryEntry[],+ env: NodeJS.ProcessEnv,generatedAt: string,warn: (line: string) => void,quietPath?: string,- bigChangeLines = DEFAULT_BIG_CHANGE_LINES,-): Promise<CollectedProject[]> {+): Promise<PanelData> {+ const config = await loadConfig(env);+ const transcripts = await defaultAgent().collectTranscripts(env);const projects: CollectedProject[] = [];+ const inbox: ViewInboxRow[] = [];for (const entry of entries) {if (!(await isDirectory(entry.path))) {projects.push({@@ -148,6 +268,15 @@ export async function collectPanelProjects(const sessionWarn = entry.path === quietPath ? () => {} : warn;const sessions = await loadAllSessions(entry.path, sessionWarn);const card = statusCard(sessions, generatedAt);+ // Rows first: a failure inside the inbox must leave one fallback card,+ // never a card pushed twice.+ const rows = await collectInboxForProject(+ { name: entry.name, path: entry.path },+ sessions,+ transcripts,+ config,+ generatedAt,+ );projects.push({name: entry.name,path: entry.path,@@ -156,8 +285,9 @@ export async function collectPanelProjects(needsUserCount: card.pending.filter((item) => item.needsUser).length,lineageUrl: pathToFileURL(projectPaths(entry.path).html).href,leftOff: leftOffLine(sessions),- unreadBigCount: await unreadBigCount(entry.path, sessions, bigChangeLines),+ unreadBigCount: await unreadBigCount(entry.path, sessions, config.bigChangeLines),});+ inbox.push(...rows);} catch (err) {warn(`skipping project ${entry.path}: ${(err as Error).message}`);projects.push({@@ -172,7 +302,21 @@ export async function collectPanelProjects(});}}- return projects;+ // Each project's rows are aged and sorted on their own; the panel reads them+ // as one list, so the longest-waiting session across projects comes first.+ inbox.sort(compareInboxRows);+ return { projects, inbox };+}++/** The panel cards only; kept for callers that do not need the inbox. */+export async function collectPanelProjects(+ entries: RegistryEntry[],+ env: NodeJS.ProcessEnv,+ generatedAt: string,+ warn: (line: string) => void,+ quietPath?: string,+): Promise<CollectedProject[]> {+ return (await collectPanelData(entries, env, generatedAt, warn, quietPath)).projects;}/**@@ -180,29 +324,32 @@ export async function collectPanelProjects(* warning and no projects, never a failed build: the panel and the map's* switcher are derived state.*/-export async function collectRegistryProjects(+export async function collectRegistryData(env: NodeJS.ProcessEnv,generatedAt: string,warn: (line: string) => void,quietPath?: string,-): Promise<CollectedProject[]> {+): Promise<PanelData> {const registry = await loadRegistry(env);if (registry.found && !registry.ok) {warn(`registry: ${registry.error}; showing no projects`);- return [];+ return { projects: [], inbox: [] };}if (registry.found) {for (const warning of registry.warnings) warn(warning);}- if (!registry.found || !registry.ok) return [];- const config = await loadConfig(env);- return await collectPanelProjects(- registry.data.projects,- generatedAt,- warn,- quietPath,- config.bigChangeLines,- );+ if (!registry.found || !registry.ok) return { projects: [], inbox: [] };+ return await collectPanelData(registry.data.projects, env, generatedAt, warn, quietPath);+}++/** The map's switcher and panel cards, without the inbox rows. */+export async function collectRegistryProjects(+ env: NodeJS.ProcessEnv,+ generatedAt: string,+ warn: (line: string) => void,+ quietPath?: string,+): Promise<CollectedProject[]> {+ return (await collectRegistryData(env, generatedAt, warn, quietPath)).projects;}/**@@ -214,9 +361,8 @@ export async function buildPanel(opts: PanelOptions): Promise<PanelViewModel> {const { io } = opts;const generatedAt = io.now();const config = await loadConfig(opts.env);- const projects =- opts.projects ??- (await collectRegistryProjects(opts.env, generatedAt, io.warn, opts.quietPath));+ const data =+ opts.data ?? (await collectRegistryData(opts.env, generatedAt, io.warn, opts.quietPath));const model: PanelViewModel = {kind: "panel",@@ -224,7 +370,9 @@ export async function buildPanel(opts: PanelOptions): Promise<PanelViewModel> {generatedAt,settings: panelSettings(config),// `leftOff` belongs to the map's switcher; the panel page stays as it was.- projects: projects.map(({ leftOff: _leftOff, ...project }) => project),+ projects: data.projects.map(({ leftOff: _leftOff, ...project }) => project),+ // Oldest first: the row that has waited longest is the one to go back to.+ inbox: data.inbox,};// Same safety net as the map: nothing leaves this process unredacted.diff --git a/packages/cli/test/inbox.test.ts b/packages/cli/test/inbox.test.tsnew file mode 100644index 0000000..04f700d--- /dev/null+++ b/packages/cli/test/inbox.test.ts@@ -0,0 +1,604 @@+import { mkdir, readFile, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { pathToFileURL } from "node:url";+import { beforeEach, describe, expect, it } from "vitest";+import { readLastTurn } from "../src/agents/claude/transcripts.js";+import { buildProject } from "../src/commands/build.js";+import { configSet } from "../src/commands/config.js";+import { init } from "../src/commands/init.js";+import { dismissInboxSession, readInboxDismissed } from "../src/store/inbox-state.js";+import { globalPaths, projectPaths } from "../src/store/paths.js";+import { loadAllSessions } from "../src/store/stores.js";+import {+ clipMessage,+ dismissKey,+ INBOX_MESSAGE_LIMIT,+ type InboxCandidate,+ inboxRows,+ timeSince,+} from "../src/view/inbox.js";+import { DATA_ELEMENT_ID, type PanelViewModel } from "../src/view/model.js";+import {+ buildPanel,+ collectInboxForProject,+ collectPanelProjects,+ collectRegistryData,+ collectRegistryProjects,+ lastDecisionOf,+} from "../src/view/panel.js";+import { envFor, fakeIo, T0, tempDir } from "./helpers.js";++const TEMPLATE = `<!doctype html><html><head><title>cogit — lineage</title></head><body>+ <div id="root"></div>+ <script id="${DATA_ELEMENT_ID}" type="application/json"></script></body></html>`;++const DATA_PREFIX = `<script id="${DATA_ELEMENT_ID}" type="application/json">`;++function embedded(html: string): unknown {+ const start = html.indexOf(DATA_PREFIX);+ expect(start).toBeGreaterThanOrEqual(0);+ const end = html.indexOf("</script>", start);+ return JSON.parse(html.slice(start + DATA_PREFIX.length, end));+}++const at = (minute: number) => `2026-10-21T10:${String(minute).padStart(2, "0")}:00.000Z`;++function userLine(text: string, stamp = at(0)) {+ return { type: "user", timestamp: stamp, message: { role: "user", content: text } };+}++function agentLine(text: string, stamp = at(1), extra: Record<string, unknown> = {}) {+ return {+ type: "assistant",+ timestamp: stamp,+ message: { content: [{ type: "text", text }] },+ ...extra,+ };+}++async function transcriptFile(env: NodeJS.ProcessEnv, sessionId: string): Promise<string> {+ const folder = join(env.CLAUDE_CONFIG_DIR as string, "projects", "-proj");+ await mkdir(folder, { recursive: true });+ return join(folder, `${sessionId}.jsonl`);+}++async function writeTranscript(+ env: NodeJS.ProcessEnv,+ sessionId: string,+ lines: unknown[],+): Promise<string> {+ const file = await transcriptFile(env, sessionId);+ // Strings are written as they are, so a test can hand over a broken line.+ await writeFile(+ file,+ lines.map((line) => (typeof line === "string" ? line : JSON.stringify(line))).join("\n"),+ );+ return file;+}++async function initProject(root: string, env: NodeJS.ProcessEnv): Promise<void> {+ await mkdir(root, { recursive: true });+ await init(root, { retention: "keep", language: "auto" }, fakeIo(env));+}++interface SessionInput {+ sessionId: string;+ at?: string;+ goal?: string;+ pending?: { text: string; needsUser: boolean }[];+ nodes?: Record<string, unknown>[];+}++async function writeSession(root: string, input: SessionInput): Promise<void> {+ await writeFile(+ projectPaths(root).session(input.sessionId),+ JSON.stringify({+ schema: 1,+ sessionId: input.sessionId,+ startedAt: input.at ?? T0,+ updatedAt: input.at ?? T0,+ status: {+ goal: input.goal ?? "",+ done: [],+ pending: input.pending ?? [],+ next: "",+ },+ nodes: input.nodes ?? [],+ }),+ );+}++let dir: string;+let env: NodeJS.ProcessEnv;++beforeEach(async () => {+ dir = await tempDir();+ env = envFor(dir);+});++describe("readLastTurn", () => {+ it("says the agent spoke last when its reply follows the user's message", async () => {+ const file = await writeTranscript(env, "s1", [+ userLine("Fix it"),+ agentLine("Done — the card uses the new key."),+ ]);+ expect(await readLastTurn(file)).toEqual({+ speaker: "agent",+ at: at(1),+ text: "Done — the card uses the new key.",+ });+ });++ it("says the user spoke last when no reply came after the message", async () => {+ const file = await writeTranscript(env, "s1", [userLine("Fix it")]);+ expect(await readLastTurn(file)).toEqual({ speaker: "user", at: at(0), text: "" });+ });++ it("starts a new turn at the newest user message", async () => {+ const file = await writeTranscript(env, "s1", [+ userLine("First", at(0)),+ agentLine("Answer", at(1)),+ userLine("Second", at(2)),+ ]);+ expect(await readLastTurn(file)).toEqual({ speaker: "user", at: at(2), text: "" });+ });++ it("ignores tool results, sidechains and lines that are not messages", async () => {+ const file = await writeTranscript(env, "s1", [+ { type: "system", subtype: "init" },+ '{"type":"user":',+ { type: "user", message: { content: "no stamp" } },+ userLine("Fix it", at(0)),+ { type: "user", timestamp: at(1), message: { content: [{ type: "tool_result" }] } },+ agentLine("Answer", at(2), { isSidechain: true }),+ agentLine("Real answer", at(3)),+ { type: "assistant", timestamp: at(4), message: { content: "plain" } },+ { type: "assistant", timestamp: at(5), message: { content: [{ type: "tool_use" }] } },+ { type: "assistant", message: { content: [{ type: "text", text: "no stamp" }] } },+ ]);+ expect(await readLastTurn(file)).toEqual({+ speaker: "agent",+ at: at(3),+ text: "Real answer",+ });+ });++ it("returns null for an empty transcript and for one with no user message", async () => {+ const empty = await writeTranscript(env, "s1", []);+ expect(await readLastTurn(empty)).toBeNull();+ const noUser = await writeTranscript(env, "s2", [agentLine("hello")]);+ expect(await readLastTurn(noUser)).toBeNull();+ });++ it("walks back past a long final turn to find the user message", async () => {+ const long = "x".repeat(300_000);+ const file = await writeTranscript(env, "s1", [+ userLine("Fix it", at(0)),+ agentLine(long, at(1)),+ ]);+ const last = await readLastTurn(file);+ expect(last?.speaker).toBe("agent");+ expect(last?.at).toBe(at(1));+ expect(last?.text).toHaveLength(long.length);+ });+});++function candidate(overrides: Partial<InboxCandidate> = {}): InboxCandidate {+ return {+ projectName: "proj",+ projectPath: "/tmp/proj",+ mapUrl: "file:///tmp/proj/.cogit/map.html",+ sessionId: "s1",+ sessionTitle: "Fix the card",+ turn: { at: at(30), text: "Ready for review." },+ lastActivity: at(29),+ needsUser: [],+ goal: "Ship the card",+ lastDecision: "",+ pending: [],+ messageId: "m1",+ transcriptAvailable: true,+ ...overrides,+ };+}++describe("inboxRows", () => {+ const now = "2026-10-21T12:00:00.000Z";++ it("keeps the two signals apart and orders rows oldest first", async () => {+ const rows = inboxRows(+ [+ candidate({+ projectName: "b",+ projectPath: "/b",+ sessionId: "s2",+ turn: null,+ lastActivity: at(5),+ needsUser: ["answer"],+ }),+ candidate({+ projectName: "a",+ projectPath: "/a",+ sessionId: "s1",+ turn: { at: at(10), text: "hi" },+ }),+ candidate({ projectName: "c", projectPath: "/c", sessionId: "s3", needsUser: ["decide"] }),+ ],+ new Map(),+ now,+ 7,+ );+ expect(rows.map((row) => [row.projectName, row.sessionId, row.signal])).toEqual([+ ["b", "s2", "record"],+ ["a", "s1", "turn"],+ ["c", "s3", "both"],+ ]);+ expect(rows[0]?.lastMessage).toBeUndefined();+ expect(rows[1]?.lastMessage).toBe("hi");+ });++ it("hides a row past inboxMaxAgeDays and one with no usable time", async () => {+ const rows = inboxRows(+ [+ candidate({+ sessionId: "old",+ turn: { at: "2026-10-01T10:00:00.000Z", text: "hi" },+ lastActivity: "2026-10-01T09:00:00.000Z",+ }),+ candidate({ sessionId: "notime", turn: null, lastActivity: null }),+ candidate({ sessionId: "bad", turn: null, lastActivity: "not a time" }),+ ],+ new Map(),+ "2026-10-25T12:00:00.000Z",+ 7,+ );+ expect(rows).toEqual([]);+ });++ it("hides a dismissed turn and brings the row back on a newer turn", async () => {+ const key = dismissKey("/tmp/proj", "s1");+ const dismissed = new Map([[key, at(30)]]);+ expect(inboxRows([candidate()], dismissed, now, 7)).toEqual([]);+ const newer = candidate({ turn: { at: at(45), text: "Moved on." }, lastActivity: at(44) });+ expect(inboxRows([newer], dismissed, now, 7)).toHaveLength(1);+ // An unparseable stored time must not hide work.+ expect(inboxRows([candidate()], new Map([[key, "nope"]]), now, 7)).toHaveLength(1);+ });++ it("does not apply an age filter when now is unparseable, and breaks ties by name, path and id", async () => {+ const rows = inboxRows(+ [+ candidate({ projectName: "b", projectPath: "/b", sessionId: "s2" }),+ candidate({ projectName: "a", projectPath: "/z", sessionId: "s9" }),+ candidate({ projectName: "a", projectPath: "/a", sessionId: "s8" }),+ candidate({ projectName: "a", projectPath: "/a", sessionId: "s7" }),+ ],+ new Map(),+ "not a time",+ 7,+ );+ expect(rows.map((row) => row.sessionId)).toEqual(["s7", "s8", "s9", "s2"]);+ });++ it("clips the agent's message to the limit and keeps pending items", async () => {+ const long = "y".repeat(INBOX_MESSAGE_LIMIT + 50);+ const [row] = inboxRows(+ [+ candidate({+ turn: { at: at(10), text: long },+ pending: [{ text: "decide", needsUser: true }],+ }),+ ],+ new Map(),+ now,+ 7,+ );+ expect(row?.lastMessage).toHaveLength(INBOX_MESSAGE_LIMIT);+ expect(row?.lastMessage?.endsWith("…")).toBe(true);+ expect(row?.pending).toEqual([{ text: "decide", needsUser: true }]);+ });+});++describe("timeSince", () => {+ it("renders the units the inbox uses", () => {+ const now = "2026-10-21T12:00:00.000Z";+ expect(timeSince("2026-10-21T11:59:30.000Z", now)).toBe("under a minute");+ expect(timeSince("2026-10-21T11:30:00.000Z", now)).toBe("30 min");+ expect(timeSince("2026-10-21T10:00:00.000Z", now)).toBe("2 h");+ expect(timeSince("2026-10-20T11:00:00.000Z", now)).toBe("1 day");+ expect(timeSince("2026-10-18T11:00:00.000Z", now)).toBe("3 days");+ expect(timeSince("nope", now)).toBe("");+ });++ it("leaves a short message alone", () => {+ expect(clipMessage("short")).toBe("short");+ });+});++describe("collectInboxForProject", () => {+ it("reads the transcript ending, the record's signals and the record's summary", async () => {+ const root = join(dir, "alpha");+ await initProject(root, env);+ const file = await writeTranscript(env, "s1", [userLine("Fix it"), agentLine("Ready.")]);+ await writeSession(root, {+ sessionId: "s1",+ goal: "Ship the card",+ pending: Array.from({ length: 6 }, (_, index) => ({+ text: `item ${index}`,+ needsUser: index === 0,+ })),+ nodes: [+ {+ id: "m1",+ kind: "message",+ title: "Fix it",+ at: at(0),+ agentDecisions: [{ title: "Use the cache", why: "cheaper" }],+ },+ { id: "d1", kind: "decision", title: "Keep the API" },+ ],+ });+ const transcripts = new Map([["s1", file]]);+ const config = { inboxMaxAgeDays: 7, bigChangeLines: 300 } as never;+ const rows = await collectInboxForProject(+ { name: "alpha", path: root },+ await loadSessions(root),+ transcripts,+ config,+ T0,+ );+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({+ sessionId: "s1",+ signal: "both",+ goal: "Ship the card",+ lastDecision: "Keep the API",+ messageId: "m1",+ transcriptAvailable: true,+ lastMessage: "Ready.",+ });+ expect(rows[0]?.pending).toHaveLength(5);+ });++ it("skips an old session before reading its transcript and treats a broken one as silence", async () => {+ const root = join(dir, "alpha");+ await initProject(root, env);+ await writeSession(root, { sessionId: "old", at: "2026-09-01T10:00:00.000Z" });+ await writeSession(root, {+ sessionId: "broken",+ pending: [{ text: "decide", needsUser: true }],+ });+ const transcripts = new Map([["broken", root]]);+ const config = { inboxMaxAgeDays: 7, bigChangeLines: 300 } as never;+ const rows = await collectInboxForProject(+ { name: "alpha", path: root },+ await loadSessions(root),+ transcripts,+ config,+ T0,+ );+ expect(rows.map((row) => row.sessionId)).toEqual(["broken"]);+ expect(rows[0]?.transcriptAvailable).toBe(true);+ });++ it("does not filter by age when the given now is unparseable, and keeps a timeless record out", async () => {+ const root = join(dir, "alpha");+ await initProject(root, env);+ const config = { inboxMaxAgeDays: 7, bigChangeLines: 300 } as never;+ const rows = await collectInboxForProject(+ { name: "alpha", path: root },+ [+ {+ sessionId: "s1",+ title: "Timeless",+ startedAt: "x",+ updatedAt: "x",+ status: { goal: "", done: [], pending: [{ text: "decide", needsUser: true }], next: "" },+ nodes: [],+ },+ ] as never,+ new Map(),+ config,+ "not a time",+ );+ expect(rows).toEqual([]);+ });++ it("has no rows for a session with no message id, and reads lastDecision from messages", async () => {+ const root = join(dir, "alpha");+ await initProject(root, env);+ await writeSession(root, {+ sessionId: "s1",+ pending: [{ text: "decide", needsUser: true }],+ nodes: [{ id: "d1", kind: "decision", title: "One" }],+ });+ const config = { inboxMaxAgeDays: 7, bigChangeLines: 300 } as never;+ const rows = await collectInboxForProject(+ { name: "alpha", path: root },+ await loadSessions(root),+ new Map(),+ config,+ T0,+ );+ expect(rows[0]?.messageId).toBeUndefined();+ expect(rows[0]?.lastDecision).toBe("One");+ expect(rows[0]?.signal).toBe("record");+ });+});++async function loadSessions(root: string) {+ return await loadAllSessions(root, () => {});+}++describe("panel and map inbox", () => {+ async function setup(): Promise<{ alpha: string; beta: string }> {+ const alpha = join(dir, "alpha");+ const beta = join(dir, "beta");+ await initProject(alpha, env);+ await initProject(beta, env);+ await writeTranscript(env, "sa", [userLine("A", at(0)), agentLine("Ready A", at(30))]);+ await writeTranscript(env, "sb", [userLine("B", at(0)), agentLine("Ready B", at(10))]);+ await writeSession(alpha, {+ sessionId: "sa",+ at: at(30),+ nodes: [{ id: "m1", kind: "message", title: "A", at: at(0) }],+ });+ await writeSession(beta, {+ sessionId: "sb",+ at: at(10),+ nodes: [{ id: "m1", kind: "message", title: "B", at: at(0) }],+ });+ return { alpha, beta };+ }++ it("puts every project's rows, oldest first, into the panel", async () => {+ const { alpha, beta } = await setup();+ const io = fakeIo(env);+ const model = await buildPanel({ env, io, templateHtml: TEMPLATE });+ expect(model.inbox?.map((row) => [row.projectName, row.sessionId])).toEqual([+ ["beta", "sb"],+ ["alpha", "sa"],+ ]);+ const html = await readFile(globalPaths(env).panel, "utf8");+ expect((embedded(html) as PanelViewModel).inbox).toEqual(model.inbox);+ expect(model.projects.map((project) => project.path)).toEqual([alpha, beta]);+ });++ it("hides a dismissed row until a newer agent turn arrives", async () => {+ const { alpha } = await setup();+ await dismissInboxSession(alpha, "sa", at(30));+ expect((await readInboxDismissed(alpha)).get("sa")).toBe(at(30));+ let model = await buildPanel({ env, io: fakeIo(env), templateHtml: TEMPLATE });+ expect(model.inbox?.map((row) => row.sessionId)).toEqual(["sb"]);+ await writeTranscript(env, "sa", [+ userLine("A", at(0)),+ agentLine("Ready A", at(30)),+ userLine("More", at(40)),+ agentLine("Ready again", at(45)),+ ]);+ model = await buildPanel({ env, io: fakeIo(env), templateHtml: TEMPLATE });+ expect(model.inbox?.map((row) => row.sessionId)).toEqual(["sb", "sa"]);+ });++ it("honours inboxMaxAgeDays from the config", async () => {+ const root = join(dir, "old");+ await initProject(root, env);+ await writeTranscript(env, "s1", [+ userLine("Old", "2026-10-18T10:00:00.000Z"),+ agentLine("Old reply", "2026-10-18T10:05:00.000Z"),+ ]);+ await writeSession(root, { sessionId: "s1", at: "2026-10-18T10:00:00.000Z" });+ let model = await buildPanel({ env, io: fakeIo(env), templateHtml: TEMPLATE });+ expect(model.inbox?.map((row) => row.sessionId)).toEqual(["s1"]);+ await configSet("inboxMaxAgeDays", "1", fakeIo(env));+ model = await buildPanel({ env, io: fakeIo(env), templateHtml: TEMPLATE });+ expect(model.inbox).toEqual([]);+ });++ it("keeps another project's rows off the map", async () => {+ const { alpha } = await setup();+ const model = await buildProject({+ dir: alpha,+ io: fakeIo(env),+ templateHtml: TEMPLATE,+ quiet: true,+ });+ expect(model.inbox?.map((row) => row.sessionId)).toEqual(["sa"]);+ const html = await readFile(projectPaths(alpha).html, "utf8");+ expect((embedded(html) as { inbox: unknown }).inbox).toEqual(model.inbox);+ });++ it("collects the map's own rows when the project is not registered", async () => {+ const { alpha } = await setup();+ await writeFile(globalPaths(env).registry, JSON.stringify({ schema: 1, projects: [] }));+ const model = await buildProject({+ dir: alpha,+ io: fakeIo(env),+ templateHtml: TEMPLATE,+ quiet: true,+ });+ expect(model.inbox?.map((row) => row.sessionId)).toEqual(["sa"]);+ });++ it("collects rows through the card-only helpers and keeps an unreadable registry empty", async () => {+ await setup();+ const io = fakeIo(env);+ const data = await collectRegistryData(env, T0, io.warn);+ expect(data.projects).toHaveLength(2);+ expect(data.inbox).toHaveLength(2);+ expect(await collectRegistryProjects(env, T0, io.warn)).toHaveLength(2);+ expect(await collectPanelProjects([], env, T0, io.warn)).toEqual([]);+ await writeFile(globalPaths(env).registry, JSON.stringify({ schema: 1, projects: [] }));+ expect(await collectRegistryData(env, T0, io.warn)).toEqual({ projects: [], inbox: [] });+ });++ it("marks a missing project rowless and warns for a broken one", async () => {+ const missing = join(dir, "gone");+ const broken = join(dir, "broken");+ await mkdir(dirname(projectPaths(broken).sessions), { recursive: true });+ await writeFile(projectPaths(broken).sessions, "not a directory");+ const io = fakeIo(env);+ const data = await collectPanelProjects(+ [+ { path: missing, name: "gone", addedAt: T0 },+ { path: broken, name: "broken", addedAt: T0 },+ ],+ env,+ T0,+ io.warn,+ );+ expect(data).toHaveLength(2);+ expect(data[0]?.missing).toBe(true);+ expect(io.warnings.some((line) => line.startsWith("skipping project"))).toBe(true);+ });+});++describe("inbox dismiss state", () => {+ it("treats a missing or unreadable file as nothing dismissed and replaces it on the next write", async () => {+ const root = join(dir, "alpha");+ await initProject(root, env);+ expect((await readInboxDismissed(root)).size).toBe(0);+ await mkdir(dirname(projectPaths(root).inboxState), { recursive: true });+ await writeFile(projectPaths(root).inboxState, "{nope");+ expect((await readInboxDismissed(root)).size).toBe(0);+ await dismissInboxSession(root, "s1", T0);+ expect([...(await readInboxDismissed(root))]).toEqual([["s1", T0]]);+ });++ it("rejects an id or a time it cannot store", async () => {+ const root = join(dir, "alpha");+ await initProject(root, env);+ await expect(dismissInboxSession(root, "bad id!", T0)).rejects.toThrow(/not a session id/);+ await expect(dismissInboxSession(root, "s1", "not a time")).rejects.toThrow(/not a time/);+ });+});++describe("lastDecisionOf", () => {+ it("prefers the newest decision node and falls back to a message's agent choice", () => {+ const session = {+ nodes: [+ {+ id: "m1",+ kind: "message",+ title: "one",+ agentDecisions: [{ title: "Agent A", why: "" }],+ },+ { id: "d1", kind: "decision", title: "Decision" },+ ],+ } as never;+ expect(lastDecisionOf(session)).toBe("Decision");+ expect(+ lastDecisionOf({+ nodes: [+ {+ id: "m1",+ kind: "message",+ title: "one",+ agentDecisions: [{ title: "Agent A", why: "" }],+ },+ ],+ } as never),+ ).toBe("Agent A");+ expect(lastDecisionOf({ nodes: [] } as never)).toBe("");+ });+});diff --git a/packages/cli/test/panel.test.ts b/packages/cli/test/panel.test.tsindex e4754b8..35385fa 100644--- a/packages/cli/test/panel.test.ts+++ b/packages/cli/test/panel.test.ts@@ -114,6 +114,25 @@ describe("buildPanel", () => {unreadBigCount: 0,},],+ // Story 11.1: the record's `needsUser` item is a row on its own signal.+ inbox: [+ {+ projectName: "alpha",+ projectPath: alpha,+ mapUrl: pathToFileURL(projectPaths(alpha).html).href,+ sessionId: "s1",+ sessionTitle: "s1",+ signal: "record",+ at: T0,+ goal: "",+ lastDecision: "",+ pending: [+ { text: "decide", needsUser: true },+ { text: "later", needsUser: false },+ ],+ transcriptAvailable: false,+ },+ ],});const html = await readFile(globalPaths(env).panel, "utf8");diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.tsindex fada7ec..d9f6d6f 100644--- a/packages/cli/test/server.test.ts+++ b/packages/cli/test/server.test.ts@@ -28,6 +28,7 @@ import {stopStaleServer,} from "../src/server.js";import { atomicWrite } from "../src/store/fs.js";+import { readInboxDismissed } from "../src/store/inbox-state.js";import { globalPaths, projectPaths } from "../src/store/paths.js";import { readReadState } from "../src/store/read-state.js";import { loadConfig, updateConfig } from "../src/store/stores.js";@@ -812,6 +813,80 @@ describe("read marks (10.3)", () => {});});+describe("inbox dismiss endpoint (Story 11.1)", () => {+ const AT = "2026-10-21T10:00:00.000Z";+ const SESSION = "3f2b1c4d-0000-4000-8000-000000000001";++ function dismissWrite(+ server: MapServer,+ token: string,+ payload: unknown,+ overrides: Record<string, string> = {},+ ): Promise<Reply> {+ return postConfig(`${server.url}/api/inbox/dismiss`, JSON.stringify(payload), {+ origin: `http://127.0.0.1:${server.port}`,+ [CONFIG_TOKEN_HEADER]: token,+ ...overrides,+ });+ }++ it("stores the dismissed turn for a registered project", async () => {+ const server = await start();+ const token = await panelToken(server);+ const reply = await dismissWrite(server, token, { dir: root, sessionId: SESSION, at: AT });+ expect(reply.status).toBe(200);+ expect(JSON.parse(reply.body)).toEqual({ ok: true, sessionId: SESSION, at: AT });+ expect([...(await readInboxDismissed(root))]).toEqual([[SESSION, AT]]);+ });++ it("refuses a foreign project, a bad payload, a bad token and a bad body", async () => {+ const server = await start();+ const token = await panelToken(server);+ const good = { dir: root, sessionId: SESSION, at: AT };+ expect(+ (await dismissWrite(server, token, { ...good, dir: join(dir, "elsewhere") })).status,+ ).toBe(403);+ expect((await dismissWrite(server, "nope", good)).status).toBe(403);+ expect((await dismissWrite(server, token, good, { "content-type": "text/plain" })).status).toBe(+ 415,+ );+ expect(+ (await dismissWrite(server, token, { dir: root, sessionId: "bad id!", at: AT })).status,+ ).toBe(400);+ expect(+ (await dismissWrite(server, token, { dir: root, sessionId: SESSION, at: "x" })).status,+ ).toBe(400);+ expect((await dismissWrite(server, token, { dir: root, at: AT })).status).toBe(400);+ expect((await dismissWrite(server, token, [])).status).toBe(400);+ expect(+ (+ await postConfig(`${server.url}/api/inbox/dismiss`, "{oops", {+ origin: `http://127.0.0.1:${server.port}`,+ [CONFIG_TOKEN_HEADER]: token,+ })+ ).status,+ ).toBe(400);+ expect((await dismissWrite(server, token, { ...good, pad: "x".repeat(5000) })).status).toBe(+ 413,+ );+ expect(+ (+ await dismissWrite(server, token, good, {+ origin: "http://evil.example",+ })+ ).status,+ ).toBe(403);+ });++ 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).inboxState, { recursive: true });+ const reply = await dismissWrite(server, token, { dir: root, sessionId: SESSION, at: AT });+ expect(reply.status).toBe(500);+ });+});+describe("commit diff endpoint (Story 10.5)", () => {const run = promisify(execFile);diff --git a/packages/template/src/App.tsx b/packages/template/src/App.tsxindex e7aecd6..16166c1 100644--- a/packages/template/src/App.tsx+++ b/packages/template/src/App.tsx@@ -10,6 +10,7 @@ import {import { BackToPanel, Brand } from "./Brand.js";import { formatTime } from "./format.js";import { Graph } from "./Graph.js";+import { Inbox } from "./Inbox.js";import { type MapSearchState, SearchBox } from "./MapSearch.js";import { ProjectSwitcher } from "./ProjectSwitcher.js";import { SettingsButton } from "./SettingsModal.js";@@ -81,6 +82,9 @@ export function App({ model }: { model: LineageViewModel }) {<span className="muted">generated {formatTime(model.project.generatedAt)}</span></div></header>++ {/* Story 11.1: only this project's rows, same as the panel's inbox. */}+ <Inbox rows={model.inbox ?? []} /></div><Graph model={model} search={search} />diff --git a/packages/template/src/Graph.tsx b/packages/template/src/Graph.tsxindex 59a2e22..9b25463 100644--- a/packages/template/src/Graph.tsx+++ b/packages/template/src/Graph.tsx@@ -518,6 +518,19 @@ function Flow({ model, search }: { model: LineageViewModel; search: MapSearchStaif (hashHit === null) return;openNode(hashHit.sessionId, hashHit.messageId);}, [hashHit?.sessionId, hashHit?.messageId, openNode]);+ // An inbox row (Story 11.1) links to a message in this same page, so the hash+ // changes without a reload; open it the way opening the page there would.+ useEffect(() => {+ function onHashChange(): void {+ const target = readTarget(model);+ if (target === null) return;+ ensureOpen(target.sessionId);+ if (target.messageId !== undefined) openNode(target.sessionId, target.messageId);+ document.querySelector(".lineage-map")?.scrollIntoView({ block: "start" });+ }+ window.addEventListener("hashchange", onHashChange);+ return () => window.removeEventListener("hashchange", onHashChange);+ }, [model, ensureOpen, openNode]);const unfold = useCallback((segmentId: string) => {setUnfolded((previous) => {const next = new Set(previous);diff --git a/packages/template/src/Inbox.tsx b/packages/template/src/Inbox.tsxnew file mode 100644index 0000000..206a065--- /dev/null+++ b/packages/template/src/Inbox.tsx@@ -0,0 +1,122 @@+import { useState } from "react";+import { dismissKey, timeSince } from "../../cli/src/view/inbox.js";+import type { ViewInboxRow } from "../../cli/src/view/model.js";+import { isLivePage, pageToken, saveDismiss } from "./data.js";+import { formatTime } from "./format.js";+import { ResumeButton } from "./ResumeButton.js";++/**+ * The "your turn" inbox (Story 11.1): one row per session whose transcript ends+ * with the agent, or whose record has `needsUser` items. The two signals stay+ * apart — the turn is a transcript fact, the record summary is labelled as the+ * record's — and the agent's last message is shown verbatim so the user judges+ * it, never a guess about whether it asked a question.+ */++/** The map of the row's project, opened at the session's newest message. */+function rowHref(row: ViewInboxRow): string {+ const base = isLivePage() ? `/map?dir=${encodeURIComponent(row.projectPath)}` : row.mapUrl;+ const params = new URLSearchParams({ s: row.sessionId });+ if (row.messageId !== undefined) params.set("m", row.messageId);+ return `${base}#${params.toString()}`;+}++function WhereWereWe({ row }: { row: ViewInboxRow }) {+ const parts = [+ row.goal === "" ? "" : `Goal: ${row.goal}`,+ row.lastDecision === "" ? "" : `Last decision: ${row.lastDecision}`,+ row.pending.length === 0 ? "" : `Open: ${row.pending.map((item) => item.text).join("; ")}`,+ ].filter((part) => part !== "");+ if (parts.length === 0) return null;+ return (+ <p className="inbox-where">+ <span className="muted">Where we were, from the record:</span> {parts.join(" · ")}+ </p>+ );+}++export function Inbox({ rows }: { rows: ViewInboxRow[] }) {+ // A `file://` page has no server to persist a dismissal; the row hides for+ // this open page, which is what the button's title says.+ const [hidden, setHidden] = useState<ReadonlySet<string>>(new Set());+ const [error, setError] = useState<string | null>(null);+ const visible = rows.filter((row) => !hidden.has(dismissKey(row.projectPath, row.sessionId)));+ if (visible.length === 0) return null;+ // The page is a snapshot; the age still moves while it stays open.+ const now = new Date().toISOString();++ function dismiss(row: ViewInboxRow): void {+ const key = dismissKey(row.projectPath, row.sessionId);+ setError(null);+ setHidden((previous) => new Set(previous).add(key));+ const token = pageToken();+ if (token === null) return;+ void saveDismiss(row.projectPath, row.sessionId, row.at, token).catch((err: unknown) => {+ setError(err instanceof Error ? err.message : String(err));+ setHidden((previous) => {+ const next = new Set(previous);+ next.delete(key);+ return next;+ });+ });+ }++ return (+ <section className="inbox" aria-labelledby="inbox-title">+ <h2 id="inbox-title">+ Your turn <span className="muted inbox-count">{visible.length}</span>+ </h2>+ <ul className="inbox-rows">+ {visible.map((row) => (+ <li className="inbox-row" key={dismissKey(row.projectPath, row.sessionId)}>+ <div className="inbox-head">+ <span className="inbox-project" title={row.projectPath}>+ {row.projectName}+ </span>+ <span className="inbox-session">{row.sessionTitle}</span>+ <span+ className={row.signal === "record" ? "inbox-age is-record" : "inbox-age"}+ title={formatTime(row.at)}+ >+ {row.signal === "record"+ ? `the record says it needs you · ${timeSince(row.at, now)}`+ : `your turn for ${timeSince(row.at, now)}`}+ </span>+ </div>+ {row.lastMessage === undefined ? null : (+ <p className="inbox-message">{row.lastMessage}</p>+ )}+ {row.signal !== "both" ? null : (+ <p className="inbox-signal">The record says it needs you.</p>+ )}+ <WhereWereWe row={row} />+ <div className="inbox-actions">+ <a className="inbox-open" href={rowHref(row)}>+ {row.messageId === undefined ? "Open the map →" : "Open at this message →"}+ </a>+ <ResumeButton+ projectPath={row.projectPath}+ sessionId={row.sessionId}+ available={row.transcriptAvailable}+ revealCommand+ />+ <button+ type="button"+ className="inbox-dismiss"+ title={+ pageToken() === null+ ? "Hide until this page is reloaded"+ : "Hide until a new agent turn"+ }+ onClick={() => dismiss(row)}+ >+ Dismiss+ </button>+ </div>+ </li>+ ))}+ </ul>+ {error === null ? null : <p className="muted inbox-error">{error}</p>}+ </section>+ );+}diff --git a/packages/template/src/Panel.tsx b/packages/template/src/Panel.tsxindex 1b5b4b4..a0c0cfe 100644--- a/packages/template/src/Panel.tsx+++ b/packages/template/src/Panel.tsx@@ -2,6 +2,7 @@ import type { PanelProject, PanelViewModel } from "../../cli/src/view/model.js";import { Brand } from "./Brand.js";import { isLivePage } from "./data.js";import { formatTime } from "./format.js";+import { Inbox } from "./Inbox.js";import { SettingsButton } from "./SettingsModal.js";/**@@ -37,6 +38,9 @@ export function Panel({ model }: { model: PanelViewModel }) {</div></header>+ {/* Story 11.1: sessions waiting on the user, across every project. */}+ <Inbox rows={model.inbox ?? []} />+{model.projects.length === 0 ? (<p className="empty">No projects registered yet. Run `cogit init` in a project.</p>) : (diff --git a/packages/template/src/ResumeButton.tsx b/packages/template/src/ResumeButton.tsxnew file mode 100644index 0000000..4278b8a--- /dev/null+++ b/packages/template/src/ResumeButton.tsx@@ -0,0 +1,63 @@+import { useState } from "react";+import { resumeCommand } from "../../cli/src/view/resume.js";+import { type CopyState, copyText } from "./clipboard.js";++/**+ * The resume control (Story 8.7, reused by the inbox in 11.1): copies+ * `cd '<project>' && claude --resume <id>` so the user can go back to the+ * session in a terminal. `onFailed` lets a page that shows the command select+ * it, so Ctrl+C still works when both clipboard paths fail over `file://`.+ */+export function ResumeButton({+ projectPath,+ sessionId,+ available = true,+ revealCommand = false,+ onFailed,+}: {+ projectPath: string;+ sessionId: string;+ /** False when the transcript is gone, so resuming cannot work. */+ available?: boolean;+ /**+ * Shows the command when the clipboard fails, for a page with no command of+ * its own on screen (the inbox row); the side panel already prints it.+ */+ revealCommand?: boolean;+ onFailed?: () => void;+}) {+ const [state, setState] = useState<CopyState>("idle");++ if (!available) {+ return (+ <button type="button" className="resume-button" disabled>+ Copy resume command+ </button>+ );+ }++ const copy = (): void => {+ setState("idle");+ void copyText(resumeCommand(projectPath, sessionId)).then((ok) => {+ if (!ok) onFailed?.();+ setState(ok ? "copied" : "failed");+ });+ };++ return (+ <>+ <button type="button" className="resume-button" onClick={copy}>+ Copy resume command+ </button>+ {state === "copied" ? <span className="muted resume-note">Copied.</span> : null}+ {state === "failed" ? (+ <span className="muted resume-note">Copy failed — press Ctrl+C to copy.</span>+ ) : null}+ {revealCommand && state === "failed" ? (+ <code className="resume-command inbox-resume-command">+ {resumeCommand(projectPath, sessionId)}+ </code>+ ) : null}+ </>+ );+}diff --git a/packages/template/src/SidePanel.tsx b/packages/template/src/SidePanel.tsxindex f60d780..5ddc745 100644--- a/packages/template/src/SidePanel.tsx+++ b/packages/template/src/SidePanel.tsx@@ -7,6 +7,7 @@ import type {ViewSession,} from "../../cli/src/view/model.js";import { resumeCommand } from "../../cli/src/view/resume.js";+import { type CopyState, copyText } from "./clipboard.js";import { parseSubject, splitPath, typeColour } from "./codeRefs.js";import { DiffView } from "./DiffView.js";import { isLivePage, pageToken } from "./data.js";@@ -22,6 +23,7 @@ import {toNodeDetail,} from "./graph.js";import type { OutlineTarget } from "./Outline.js";+import { ResumeButton } from "./ResumeButton.js";/*** What the drill-down shows: a message (with the branch it belongs to) or a@@ -45,40 +47,6 @@ function findMessage(session: ViewSession, id: string): ViewNode | undefined {return session.messages.find((message) => message.id === id);}-/**- * `navigator.clipboard` is unavailable or rejected in some `file://` contexts,- * so fall back to the hidden-textarea + `execCommand("copy")` path.- * Returns false when both fail, letting the caller select the text instead.- */-export async function copyText(text: string): Promise<boolean> {- try {- if (navigator.clipboard?.writeText) {- await navigator.clipboard.writeText(text);- return true;- }- } catch {- // fall through to the legacy path- }-- try {- const area = document.createElement("textarea");- area.value = text;- area.setAttribute("readonly", "");- area.style.position = "fixed";- area.style.top = "-1000px";- area.style.opacity = "0";- document.body.appendChild(area);- area.select();- const copied = document.execCommand("copy");- area.remove();- return copied;- } catch {- return false;- }-}--type CopyState = "idle" | "copied" | "failed";-/*** The message's stable hash with a copy button (Story 8.10): the user pastes it* to the agent, which runs `cogit show <hash>` for the full record.@@ -123,7 +91,6 @@ function MessageHash({ value }: { value: string }) {}function ResumeRow({ model, session }: { model: LineageViewModel; session: ViewSession }) {- const [state, setState] = useState<CopyState>("idle");const code = useRef<HTMLElement>(null);const command = resumeCommand(model.project.path, session.sessionId);@@ -138,35 +105,22 @@ function ResumeRow({ model, session }: { model: LineageViewModel; session: ViewS);}- const copy = (): void => {- setState("idle");- void copyText(command).then((ok) => {- if (ok) {- setState("copied");- return;- }- // Last resort: select the command so the user can press Ctrl+C.- const element = code.current;- if (element) {- const range = document.createRange();- range.selectNodeContents(element);- const selection = window.getSelection();- selection?.removeAllRanges();- selection?.addRange(range);- }- setState("failed");- });- };-return (<div className="resume">- <button type="button" className="resume-button" onClick={copy}>- Copy resume command- </button>- {state === "copied" ? <p className="muted resume-note">Copied.</p> : null}- {state === "failed" ? (- <p className="muted resume-note">Copy failed — press Ctrl+C to copy.</p>- ) : null}+ {/* Last resort on a failed copy: selecting the command allows Ctrl+C. */}+ <ResumeButton+ projectPath={model.project.path}+ sessionId={session.sessionId}+ onFailed={() => {+ const element = code.current;+ if (!element) return;+ const range = document.createRange();+ range.selectNodeContents(element);+ const selection = window.getSelection();+ selection?.removeAllRanges();+ selection?.addRange(range);+ }}+ /><pre className="resume-command"><code ref={code}>{command}</code></pre>diff --git a/packages/template/src/clipboard.ts b/packages/template/src/clipboard.tsnew file mode 100644index 0000000..06a249f--- /dev/null+++ b/packages/template/src/clipboard.ts@@ -0,0 +1,34 @@+/** Copy state shared by the hash and resume buttons. */+export type CopyState = "idle" | "copied" | "failed";++/**+ * `navigator.clipboard` is unavailable or rejected in some `file://` contexts,+ * so fall back to the hidden-textarea + `execCommand("copy")` path.+ * Returns false when both fail, letting the caller select the text instead.+ */+export async function copyText(text: string): Promise<boolean> {+ try {+ if (navigator.clipboard?.writeText) {+ await navigator.clipboard.writeText(text);+ return true;+ }+ } catch {+ // fall through to the legacy path+ }++ try {+ const area = document.createElement("textarea");+ area.value = text;+ area.setAttribute("readonly", "");+ area.style.position = "fixed";+ area.style.top = "-1000px";+ area.style.opacity = "0";+ document.body.appendChild(area);+ area.select();+ const copied = document.execCommand("copy");+ area.remove();+ return copied;+ } catch {+ return false;+ }+}diff --git a/packages/template/src/data.ts b/packages/template/src/data.tsindex 81f2c24..24f8498 100644--- a/packages/template/src/data.ts+++ b/packages/template/src/data.ts@@ -98,6 +98,29 @@ export async function saveRead(}}+/**+ * Dismisses one inbox row (Story 11.1). The state lives in the project's+ * `.cogit/state/`, so this needs the local server; over `file://` the row+ * stays hidden for the open page only. The turn time is what was dismissed, so+ * a newer agent turn brings the row back.+ */+export async function saveDismiss(+ dir: string,+ sessionId: string,+ at: string,+ token: string,+): Promise<void> {+ const response = await fetch("/api/inbox/dismiss", {+ method: "POST",+ headers: { "content-type": "application/json", "x-cogit-token": token },+ body: JSON.stringify({ dir, sessionId, at }),+ });+ if (!response.ok) {+ const text = (await response.text()).trim();+ throw new Error(text || `could not dismiss the row (HTTP ${response.status})`);+ }+}+/*** One commit's patch for the message details (Story 10.5). Only the local* server answers this; over `file://` the diff rows do not expand.diff --git a/packages/template/src/styles.css b/packages/template/src/styles.cssindex 1e18c69..c65ca8d 100644--- a/packages/template/src/styles.css+++ b/packages/template/src/styles.css@@ -1552,6 +1552,146 @@ time {font-size: 12px;}+/* "Your turn" inbox (Story 11.1): the panel above its cards, the map head for+ this project. Rows are ordered oldest first, so the longest wait is on top. */+.inbox {+ margin: 20px 0 8px;+}++.inbox h2 {+ font-size: 16px;+ margin: 0;+}++.inbox-count {+ font-size: 13px;+ font-weight: 400;+}++.inbox-rows {+ display: grid;+ gap: 8px;+ margin: 10px 0 0;+ padding: 0;+ list-style: none;+}++.inbox-row {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 10px 12px;+ background: var(--panel);+ border: 1px solid var(--line);+ border-left: 3px solid var(--accent);+ border-radius: 8px;+}++.inbox-head {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: 8px;+}++.inbox-project {+ font-weight: 600;+}++.inbox-session {+ color: var(--muted);+ font-size: 13px;+}++.inbox-age {+ margin-left: auto;+ padding: 1px 8px;+ color: var(--accent);+ font-size: 12px;+ border: 1px solid var(--accent);+ border-radius: 999px;+ white-space: nowrap;+}++.inbox-age.is-record {+ color: var(--muted);+ border-color: var(--line);+}++.inbox-message {+ display: -webkit-box;+ overflow: hidden;+ margin: 0;+ font-size: 13px;+ line-height: 1.45;+ white-space: pre-wrap;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 3;+}++.inbox-signal,+.inbox-where {+ margin: 0;+ font-size: 12px;+}++.inbox-where {+ color: var(--text);+}++.inbox-actions {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 10px;+}++.inbox-actions a {+ color: var(--accent);+}++/* The shared resume button fills its side-panel column; an inbox row wants a+ compact control next to the link and Dismiss. */+.inbox-actions .resume-button {+ width: auto;+ padding: 2px 8px;+ font-size: 12px;+}++.inbox-actions .resume-note {+ margin: 0;+ font-size: 12px;+}++.inbox-resume-command {+ flex-basis: 100%;+ margin: 0;+ padding: 6px 8px;+ overflow-wrap: anywhere;+ font-size: 12px;+}++.inbox-dismiss {+ margin-left: auto;+ color: var(--muted);+ background: none;+ border: 1px solid var(--line);+ border-radius: 6px;+ padding: 2px 8px;+ font-size: 12px;+ cursor: pointer;+}++.inbox-dismiss:hover {+ color: var(--text);+ border-color: var(--muted);+}++.inbox-error {+ margin: 6px 0 0;+ font-size: 12px;+}+/* Global panel: one card per registered project. */.panel-grid {display: grid;