A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
feat: one continuous chat with transparent session rotation and paged history
Alan Buscaglia225596d9fbcc
diff --git a/README.md b/README.mdindex 17f681f..5f0485d 100644--- a/README.md+++ b/README.md@@ -33,7 +33,7 @@ The app puts the Dot on the desktop and an item in the menu bar, and `⌥ Space`## How it works-The daemon starts the agent (`gentle-shell --mode rpc`) as a child process and gives it the Gentle Dot identity. It restarts the agent if it crashes, reopening the same conversation, and translates its events into a small WebSocket protocol for the desktop and web interfaces. Conversations live in `~/.gentle-dot/sessions`; the access key is in `~/.gentle-dot/token`, and `~/.gentle-dot` is private to your user (mode 0700).+The daemon starts the agent (`gentle-shell --mode rpc`) as a child process and gives it the Gentle Dot identity. It restarts the agent if it crashes, reopening the same conversation, and translates its events into a small WebSocket protocol for the desktop and web interfaces. You get one continuous chat: when its session grows too large, the daemon quietly continues it in a fresh session seeded with a summary, and earlier messages stay one "Show earlier" away (set `GENTLE_DOT_CONVERSATIONS=1` for several conversations). Sessions live in `~/.gentle-dot/sessions`; the access key is in `~/.gentle-dot/token`, and `~/.gentle-dot` is private to your user (mode 0700).The assistant keeps to its own instance. The agent works in `~/.gentle-dot/workspace` and runs with its own home folder (`~/.gentle-dot/home`), so it never writes to your own Gentle Shell or Pi setup. To point it at a folder of yours, set `GENTLE_DOT_WORKSPACE` or `"workspace"` in `~/.gentle-dot/config.json`: the agent is told to work there, but nothing is written into that folder for setup. It keeps `PATH` and reads your `~/.gitconfig` for your git identity.diff --git a/docs/design.md b/docs/design.mdindex ccbb86f..fb48bca 100644--- a/docs/design.md+++ b/docs/design.md@@ -83,10 +83,11 @@ Client to daemon:| `steer` | `text` | `steer` || `abort` | — | `abort` || `ui_response` | `requestId`, `value` \| `confirmed` \| `cancelled` | `extension_ui_response` |-| `new_conversation` | — | `new_session` |+| `new_conversation` | — | `new_session`; refused with `conversations_off` unless the conversations list is on || `list_conversations` | — | daemon reads the session dir |-| `open_conversation` | `conversationId` | `switch_session` |-| `get_history` | — | `get_messages` |+| `open_conversation` | `conversationId` | `switch_session`; refused with `conversations_off` unless the conversations list is on |+| `get_history` | — | daemon reads the chat's session files (one `get_state` round trip first); waits for the agent to be ready instead of failing |+| `get_earlier` | `before` (id of the oldest message the window shows) | daemon reads the page before it, from the open session file and then the earlier files of the chain || `auth_list` | — | daemon `ModelRuntime.getProviders()` and `getProviderAuthStatus()` || `auth_login` | `providerId`, `method` (`oauth` \| `api_key`) | daemon `ModelRuntime.login()`; one flow at a time || `auth_reply` | `flowId`, `value` \| `cancelled` | answers the flow's current prompt |@@ -96,18 +97,20 @@ Daemon to client:| type | meaning ||---|---|-| `ready` | `agentState`, `conversationId`, `model` (display name only); pending asks and an `interrupted` notice follow it |+| `ready` | `agentState`, `conversationId`, `model` (display name only), `features` (`conversations`: the list and new conversation are on; default off); the current `queue`, pending asks, and an `interrupted` notice follow it || `user_message` | a user message entered from any client || `agent_state` | `starting` \| `idle` \| `thinking` \| `working` \| `needs_you` \| `restarting` \| `error` || `message_delta` | assistant text delta for message `messageId` |-| `message_done` | final assistant message |+| `message_done` | final assistant message; `stopped: true` when the user stopped it (Stop, or a switch), `error` with a plain-language explanation when it failed (shown inline in the chat, not as a toast) |+| `queue` | `steering` and `followUp`: the complete lists of messages sent while the assistant works and not taken yet (from Pi's `queue_update`); empty lists clear it, and it is cleared when the run settles or the agent restarts || `ask_resolved` | an ask was answered or timed out || `conversations` | `conversations` (`id`, `title`, `updatedAt`) and `activeId` || `interrupted` | the agent restarted while a run was active || `activity` | `messageId` plus sanitized tool activity: `id`, `kind` (`read`, `edit`, `run`, `search`, `memory`, `delegate`, `other`), `title`, `status` || `ask` | sanitized `extension_ui_request` dialog: `requestId`, `method` (`select`, `confirm`, `input`, `editor`), `title`, `message`, `options`, `timeoutMs` || `toast` | sanitized `notify` |-| `history` | conversation messages for rendering |+| `history` | the most recent messages (100 by default, `GENTLE_DOT_HISTORY_PAGE`), `hasEarlier`; messages from earlier sessions of the chat carry `earlier: true`, and the UI draws an "Earlier messages" divider after the last one |+| `earlier` | `before`, one page of `messages` before it, `hasEarlier`; message ids are `s<file index>-<turn>` in the chain || `error` | `code`, `message` safe for the user || `auth_providers` | providers with `methods`, `oauthName`, `configured`, `source`; `open: true` when the user typed `/login` || `auth_prompt` | `flowId`, `kind` (`text`, `secret`, `select`, `manual_code`), `message`, `options` — sent only to the window that started the flow |@@ -120,6 +123,16 @@ The daemon runs the Gentle Shell bundled as its `gentle-pi` dependency, with `--Every daemon message carries `seq` (monotonic per connection) so the UI can detect gaps and request `get_history`.+### Switching and history races (S21)++- Opening or starting another conversation while the assistant answers first asks the user ("Stop and switch" or "Cancel"). The daemon then aborts the run and waits, bounded to 10 s, for it to settle before it sends `new_session` or `switch_session` (abort-then-switch): Pi would otherwise end the run inside the new session. That stop is reported as `stopped`, never as an error.+- A message sent while a switch or a rotation runs waits for it, so it lands in the new session after that session's `history`.+- History replaces what a window shows, so it is read again (up to twice) when a message arrived while it was loading. Pi writes a message to its session file right after announcing it, so the daemon makes one `get_state` round trip before each read.++### One continuous chat (S22)++The UI shows one endless chat: no conversations list, no new conversation, and the header shows the assistant (the rose glyph and "Gentle Dot"). The code and protocol for several conversations stay behind `features.conversations` (`GENTLE_DOT_CONVERSATIONS=1`); with it off, the UI also ignores the menu bar's `dot://new-conversation`. The daemon rotates the session underneath when it grows (§7), and `history` / `get_earlier` read through the chain of session files, so earlier messages, including those before any compaction, stay reachable with "Show earlier".+## 5. White-label layer- **Identity**: `--append-system-prompt` with `identity.md`: the assistant is "Gentle Dot", a personal assistant; it must not mention Gentle Shell, Pi, el Gentleman, ODD, or Engram by name, and describes them as "my workflow" and "my memory" when needed. It keeps every behavior.@@ -131,7 +144,7 @@ Every daemon message carries `seq` (monotonic per connection) so the UI can dete### The Dot (collapsed)-- Our neon rose, 64 × 84 px, in a transparent window: no circle, no container. It is always on top, draggable, snaps to the nearest screen edge, and its position is persisted. Design sheet: `docs/brand/rose-design.html`.+- Our neon rose inside a black circle (S9, L24): a 66 pt disc in a 72 pt transparent window. It is always on top, draggable, snaps to the nearest screen edge, and its position is persisted. Design sheet: `docs/brand/rose-design.html`.- The rose is inline SVG built from the 178 strokes traced from the logo (`docs/brand/rose-lines.svg` → `packages/ui/src/rose/strokes.ts`, generated by `docs/brand/tools/build-rose-strokes.mjs`). The strokes carry the glow (`#FF2D7A` neon, `#FFD6E8` light core), and a light layer on the 60 longest strokes travels along them.- The state is shown by motion and glow:- `idle`: the outline breathes a soft glow; sparkles twinkle@@ -146,7 +159,8 @@ Every daemon message carries `seq` (monotonic per connection) so the UI can dete### The panel (expanded)- 420 × 640 px, rounded 20 px, translucent (macOS vibrancy), anchored to the Dot.-- Header: conversation title, new-conversation button, conversations list, collapse.+- Header (one continuous chat): the rose glyph and "Gentle Dot", then Accounts, Profiles, and Hide as 18 px stroke icons with tooltips. With `features.conversations` on, the conversation title, the conversations list, and New conversation return.+- "Show earlier" at the top of the chat loads the previous page; a subtle "Earlier messages" divider marks where the chat's earlier session ends.- Body: message list with streaming Markdown and code blocks; activity rows are collapsed one-liners grouped under the assistant turn ("Read 3 files · Ran tests").- Ask cards: when the agent needs the user, an inline card with the question and buttons (select and confirm) or a text field (input and editor). The Dot turns amber until the user answers.- Composer: multiline, Enter sends, Shift+Enter adds a new line. While the agent works, the composer offers "Stop", and sending a message steers the current run.@@ -155,7 +169,7 @@ Every daemon message carries `seq` (monotonic per connection) so the UI can dete### Menu bar- Template icon: the hand-drawn rose glyph (`docs/brand/rose-glyph.svg`), with one variant per state: ready, working (dashed outer petals; also used while thinking), needs you (a filled badge dot), and unavailable (dimmed; starting, restarting, and error).-- Menu: Open (`⌥ Space`), New conversation, Open in browser, Restart assistant, Launch at login (toggle), Quit.+- Menu: Open (`⌥ Space`), New conversation, Open in browser, Restart assistant, Launch at login (toggle), Quit. In the single chat the UI ignores New conversation; hiding the item in the tray is a follow-up for `apps/desktop`.### Web@@ -163,21 +177,27 @@ Every daemon message carries `seq` (monotonic per connection) so the UI can dete### Visual system-- Dark-first, with a light theme that follows the system setting.-- Tokens:- - `--bg` `#0E0F13`- - `--surface` `rgba(28,30,38,0.72)`- - `--text` `#ECEDEF`- - `--muted` `#8A8F98`- - `--accent` `#7C5CFF`- - `--amber` `#F5A524`- - `--danger` `#F0506E`-- Type: system UI (SF Pro), 14/20 body, 12/16 meta; monospace SF Mono for code.+- The panel and the web view follow gentlemanprogramming.com (S15, measured from the live site, L30). Dark only; there is no light theme.+- Tokens (`packages/ui/src/styles.css`):+ - `--bg` `#1a1218`, translucent header `--bg-glass` `rgba(26,18,24,0.82)` with a 12 px blur and a bottom border+ - `--surface` `#20161e`, `--surface-2` `#241822`, `--line` `#342230`+ - `--text` `#f6eff3`, `--muted` `#a78e9b`+ - `--accent` `#f095c8`; the primary button has `0 10px 30px rgba(240,149,200,.3)` and `#1a1218` text (8.60:1; white is 2.13:1)+ - notes: green `#b4e7c7`, red `#ff718f`, yellow `#e0c27a`+ - radii 8 / 12 / 16 px, pills 999 px+- Type: Inter for text, 14/20 body; an uppercase monospace eyebrow (Iosevka Term / JetBrains Mono, 12 px, letter-spacing .12em, accent color); headings in 800 weight with a light-to-pink gradient.+- The rose Dot keeps its own look (S9): neon `#FF2D7A` strokes in a black circle, with the amber `#F5A524` badge.- Motion: 180 ms ease-out for expand and collapse; the Dot animations respect "Reduce motion".## 7. Recovery-- Pi sessions persist under `~/.gentle-dot/sessions`, and the daemon reopens the last active one after any restart.+- Pi sessions persist under `~/.gentle-dot/sessions`, and the daemon reopens the last active one after any restart (`state.json` `sessionFile`).+- Rotation (S22): Pi's auto-compaction keeps the model context bounded, but the session file keeps every entry and grows forever, and detail fades with each summary. After a run settles, when the agent is idle (no run, no compaction, no open ask, no message on its way), the daemon checks the open session file. Past 20 MB (`GENTLE_DOT_ROTATE_BYTES`) or 10 compaction entries (`GENTLE_DOT_ROTATE_COMPACTIONS`), it rotates:+ 1. It writes a new session file next to the old one, in Pi's own format (a v3 `session` header with `parentSession`, then one `custom_message` with `customType` `gentle-dot.handoff` and `display: false`). The handoff text is the latest compaction `summary` from the old file, with no extra model call, or, before any compaction, the previous handoff plus the last 12 messages.+ 2. It sends `switch_session` to that file and checks that Pi opened it (`get_state` reports it) and that `get_messages` holds the handoff. Pi sends a custom message to the model as user-role context, but it is never a user message, so the chat never shows it.+ 3. If Pi did not load it (for example, its session format changed), the daemon deletes nothing, logs it, and sends `new_session` with `parentSession` instead: a fresh session without the handoff, so the user always keeps a working chat. If the handoff file cannot be written, the chat stays in the current session.+ 4. `state.json` `chains` maps the new file to the earlier ones (oldest first), so history pages read through them, and every window gets a fresh `history` with the earlier messages marked.+- Rotation never happens while the assistant is busy or an ask is open, and a failure is logged and leaves the current session working.- After a crash, the turn that was in flight is lost. The conversation history remains, and the UI shows "I was interrupted. Continue?" with a Continue button that sends "Continue where you left off."- The user's global Engram (project `gentle-dot`) keeps decisions and progress across conversations; the Gentle workflow already consults it when resuming.- Pi Durable is reconsidered only for unattended or scheduled work.@@ -216,7 +236,7 @@ The Dot drags with `getCurrentWindow().startDragging()` (permission `core:window| Event | Payload | Meaning ||---|---|---|-| `dot://new-conversation` | — | the tray item "New conversation" was chosen; the panel starts a new conversation and opens |+| `dot://new-conversation` | — | the tray item "New conversation" was chosen; with the conversations list on, the panel starts a new conversation and opens; in the single chat (default) the UI ignores it || `dot://panel-shown` | — | the panel became visible; the UI focuses the composer |### Menu bar and shortcut@@ -237,4 +257,4 @@ On launch, the app checks `GET /health`. If the daemon does not answer, the appAll keys are optional. `workspace` is the user's preferred working folder: the engine is told about it but always runs in `<dataDir>/workspace`.-Environment overrides: `GENTLE_DOT_AGENT_HOME` (default `~/.gentle-dot/agent`), `GENTLE_DOT_ENGRAM_DATA_DIR` (default: the user's Engram data folder), `GENTLE_DOT_ENGRAM` (`private` for a memory of the assistant's own), `GENTLE_DOT_ENGRAM_PORT` (private memory only, default `7438`), `GENTLE_DOT_PORT`, `GENTLE_DOT_HOST` (default `127.0.0.1`; `0.0.0.0` only inside a container), `GENTLE_DOT_DATA_DIR`, `GENTLE_DOT_WORKSPACE`, `GENTLE_DOT_UI_DIR`, `GENTLE_DOT_AGENT_BIN`, `GENTLE_DOT_AGENT_ARGS` (JSON array), `GENTLE_DOT_ALLOWED_ORIGINS` (JSON array).+Environment overrides: `GENTLE_DOT_AGENT_HOME` (default `~/.gentle-dot/agent`), `GENTLE_DOT_ENGRAM_DATA_DIR` (default: the user's Engram data folder), `GENTLE_DOT_ENGRAM` (`private` for a memory of the assistant's own), `GENTLE_DOT_ENGRAM_PORT` (private memory only, default `7438`), `GENTLE_DOT_PORT`, `GENTLE_DOT_HOST` (default `127.0.0.1`; `0.0.0.0` only inside a container), `GENTLE_DOT_DATA_DIR`, `GENTLE_DOT_WORKSPACE`, `GENTLE_DOT_UI_DIR`, `GENTLE_DOT_AGENT_BIN`, `GENTLE_DOT_AGENT_ARGS` (JSON array), `GENTLE_DOT_ALLOWED_ORIGINS` (JSON array), `GENTLE_DOT_CONVERSATIONS` (`1` turns the conversations list on), `GENTLE_DOT_ROTATE_BYTES` (default 20 MB), `GENTLE_DOT_ROTATE_COMPACTIONS` (default 10), `GENTLE_DOT_HISTORY_PAGE` (default 100).diff --git a/e2e/serve.ts b/e2e/serve.tsindex a45c828..99735df 100644--- a/e2e/serve.ts+++ b/e2e/serve.ts@@ -1,26 +1,66 @@// Starts the daemon for Playwright with the fake agent, a fresh data dir, and a known token.+// It also starts a second daemon, with the conversations list on, and waits for it first.+import { spawn } from "node:child_process";import { mkdirSync, rmSync, writeFileSync } from "node:fs";import { join } from "node:path";import { fileURLToPath } from "node:url";-import { E2E_COMMANDS_FILE, E2E_DATA_DIR, E2E_TOKEN } from "./token.ts";+import {+ E2E_COMMANDS_FILE,+ E2E_CONVERSATIONS_DATA_DIR,+ E2E_CONVERSATIONS_PORT,+ E2E_DATA_DIR,+ E2E_TOKEN,+} from "./token.ts";-const dataDir = E2E_DATA_DIR;+const conversations = process.env.E2E_CONVERSATIONS === "1";+const dataDir = conversations ? E2E_CONVERSATIONS_DATA_DIR : E2E_DATA_DIR;rmSync(dataDir, { recursive: true, force: true });mkdirSync(dataDir, { recursive: true });writeFileSync(join(dataDir, "token"), `${E2E_TOKEN}\n`, { mode: 0o600 });+if (!conversations) {+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url)], {+ env: { ...process.env, E2E_CONVERSATIONS: "1", GENTLE_DOT_PORT: String(E2E_CONVERSATIONS_PORT) },+ stdio: "inherit",+ });+ process.on("exit", () => child.kill());+ await waitForHealth(`http://127.0.0.1:${E2E_CONVERSATIONS_PORT}/health`);+}+// Provider keys in the developer's environment would mark accounts as connected.delete process.env.OPENAI_API_KEY;// Never offer to import the developer's own profiles.process.env.GENTLE_PI_CONFIG_HOME = join(dataDir, "no-shell-profiles");// Profiles are applied to <dataDir>/agent; the fake agent records the live model switch.delete process.env.GENTLE_DOT_AGENT_HOME;-process.env.FAKE_AGENT_COMMANDS_FILE = E2E_COMMANDS_FILE;+process.env.FAKE_AGENT_COMMANDS_FILE = conversations+ ? join(dataDir, "agent-commands.jsonl")+ : E2E_COMMANDS_FILE;process.env.GENTLE_DOT_DATA_DIR = dataDir;process.env.GENTLE_DOT_AGENT_BIN = process.execPath;process.env.GENTLE_DOT_AGENT_ARGS = JSON.stringify([fileURLToPath(new URL("../packages/daemon/test/fixtures/fake-agent.ts", import.meta.url)),]);+if (conversations) {+ process.env.GENTLE_DOT_CONVERSATIONS = "1";+} else {+ delete process.env.GENTLE_DOT_CONVERSATIONS;+ // Rotate after two compactions and send short history pages, so one test can cross a rotation.+ process.env.GENTLE_DOT_ROTATE_COMPACTIONS = "2";+ process.env.GENTLE_DOT_HISTORY_PAGE = "4";+}// A non-literal specifier keeps the daemon sources out of this tsconfig project.const cli = "../packages/daemon/src/cli.ts";await import(cli);++async function waitForHealth(url: string): Promise<void> {+ for (let attempt = 0; attempt < 300; attempt++) {+ const up = await fetch(url).then(+ (response) => response.ok,+ () => false,+ );+ if (up) return;+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ throw new Error(`the conversations daemon did not start: ${url}`);+}diff --git a/e2e/token.ts b/e2e/token.tsindex b0ab198..d45e7e8 100644--- a/e2e/token.ts+++ b/e2e/token.ts@@ -6,3 +6,6 @@ export const E2E_TOKEN = "e2e-token-0123456789abcdefghijklmnopqrstuv";export const E2E_DATA_DIR = join(tmpdir(), "gentle-dot-e2e");/** The fake agent appends every model command it receives here. */export const E2E_COMMANDS_FILE = join(E2E_DATA_DIR, "agent-commands.jsonl");+/** A second daemon with the conversations list on (it is off by default), for the tests of that feature. */+export const E2E_CONVERSATIONS_PORT = 4392;+export const E2E_CONVERSATIONS_DATA_DIR = join(tmpdir(), "gentle-dot-e2e-conversations");diff --git a/e2e/web.spec.ts b/e2e/web.spec.tsindex 5925766..88b4cf8 100644--- a/e2e/web.spec.ts+++ b/e2e/web.spec.ts@@ -1,7 +1,7 @@import { existsSync, readFileSync } from "node:fs";import { join } from "node:path";import { expect, type Page, test } from "@playwright/test";-import { E2E_COMMANDS_FILE, E2E_DATA_DIR, E2E_TOKEN } from "./token.ts";+import { E2E_COMMANDS_FILE, E2E_CONVERSATIONS_PORT, E2E_DATA_DIR, E2E_TOKEN } from "./token.ts";const readJson = (path: string) =>existsSync(path) ? (JSON.parse(readFileSync(path, "utf8")) as unknown) : undefined;@@ -13,8 +13,11 @@ const agentCommands = () =>.map((line) => JSON.parse(line) as unknown): [];-async function open(page: Page) {- await page.goto(`/#token=${E2E_TOKEN}`);+/** The daemon with the conversations list on; the default one keeps a single chat. */+const WITH_CONVERSATIONS = `http://127.0.0.1:${E2E_CONVERSATIONS_PORT}`;++async function open(page: Page, base = "") {+ await page.goto(`${base}/#token=${E2E_TOKEN}`);await expect(page.getByRole("textbox", { name: "Message" })).toBeEnabled();}@@ -43,7 +46,7 @@ test("answers a question card", async ({ page }) => {});test("starts a new conversation and reopens the previous one", async ({ page }) => {- await open(page);+ await open(page, WITH_CONVERSATIONS);await page.getByRole("button", { name: "New conversation" }).click();await expect(page.getByText("Hi! What can I do for you?")).toBeVisible();await say(page, "plan my trip");@@ -70,8 +73,6 @@ test("offers to continue after the assistant was interrupted", async ({ page })test("shows a message sent while the assistant works as queued, then delivers it", async ({ page }) => {await open(page);- await page.getByRole("button", { name: "New conversation" }).click();- await expect(page.getByText("Hi! What can I do for you?")).toBeVisible();await say(page, "slow");await expect(page.getByRole("button", { name: "Stop" })).toBeVisible();await say(page, "queued one");@@ -81,14 +82,16 @@ test("shows a message sent while the assistant works as queued, then delivers itawait expect(queued.locator(".message-body")).toHaveText("queued one");await expect(page.locator(".message-assistant").last()).toHaveText("Echo: queued one", { timeout: 10_000 });await expect(queued).toHaveCount(0);- await expect(page.locator(".message-user")).toHaveText(["slow", "queued one"]);- await expect(page.locator(".message-assistant")).toHaveText(["Echo: slow", "Echo: queued one"]);+ // One continuous chat: the earlier tests' messages are above these.+ const lastTwo = async (selector: string) => (await page.locator(selector).allTextContents()).slice(-2);+ await expect.poll(() => lastTwo(".message-user")).toEqual(["slow", "queued one"]);+ await expect.poll(() => lastTwo(".message-assistant")).toEqual(["Echo: slow", "Echo: queued one"]);});test("asks before leaving a running answer, then opens the other conversation with no error", async ({page,}) => {- await open(page);+ await open(page, WITH_CONVERSATIONS);await page.getByRole("button", { name: "New conversation" }).click();await expect(page.getByText("Hi! What can I do for you?")).toBeVisible();await say(page, "first chat");@@ -120,7 +123,7 @@ test("asks before leaving a running answer, then opens the other conversation witest("closes open options when the user starts typing, with titled header icons", async ({ page }) => {await open(page);- for (const name of ["Conversations", "Accounts", "Profiles", "New conversation"]) {+ for (const name of ["Accounts", "Profiles"]) {await expect(page.getByRole("button", { name })).toHaveAttribute("title", name);}await page.getByRole("button", { name: "Profiles" }).click();@@ -130,6 +133,40 @@ test("closes open options when the user starts typing, with titled header icons"await expect(page.getByRole("textbox", { name: "Message" })).toHaveValue("h");});+test("keeps one continuous chat: the header shows the assistant, with no conversations", async ({ page }) => {+ await open(page);+ await expect(page.getByRole("heading", { level: 1 })).toHaveText("Gentle Dot");+ await expect(page.getByRole("button", { name: "New conversation" })).toHaveCount(0);+ await expect(page.getByRole("button", { name: "Conversations" })).toHaveCount(0);+});++test("crosses a session rotation without a seam, and shows earlier messages on request", async ({ page }) => {+ await open(page);+ await say(page, "rotation alpha");+ await expect(page.locator(".message-assistant").last()).toHaveText("Echo: rotation alpha");+ await say(page, "compact");+ await expect(page.locator(".message-assistant").last()).toHaveText("Compacted.");+ await say(page, "compact");+ // The second compaction rotates the session (GENTLE_DOT_ROTATE_COMPACTIONS=2 in serve.ts).+ const divider = page.locator(".earlier-divider");+ await expect(divider).toHaveText("Earlier messages");+ await say(page, "recall");+ // The new session knows the earlier one through the hidden handoff, which never shows as a message.+ await expect(page.locator(".message-assistant").last()).toContainText("Summary: ");+ await expect(page.locator(".message-assistant").last()).toContainText("rotation alpha");+ await expect(page.locator(".message-user").last()).toHaveText("recall");++ // Only the latest page (4 messages, GENTLE_DOT_HISTORY_PAGE=4) loads after a reload.+ await page.reload();+ await expect(page.locator(".message-assistant").last()).toContainText("Recall: ");+ await expect(divider).toBeVisible();+ const alpha = page.locator(".message-user", { hasText: /^rotation alpha$/ });+ await expect(alpha).toHaveCount(0);+ await page.getByRole("button", { name: "Show earlier" }).click();+ await expect(alpha).toHaveCount(1);+ await expect(page.locator(".earlier-divider")).toHaveCount(1);+});+test("keeps the conversation after a page reload", async ({ page }) => {await open(page);await say(page, "remember this");diff --git a/packages/daemon/src/bridge.ts b/packages/daemon/src/bridge.tsindex d871d30..9b30c46 100644--- a/packages/daemon/src/bridge.ts+++ b/packages/daemon/src/bridge.ts@@ -3,6 +3,7 @@ import {type AgentState,type Ask,type ClientMessage,+ type Features,isThinkingLevel,type MessageQueue,parseQueue,@@ -12,8 +13,9 @@ import {import type { AuthManager } from "./auth.ts";import {conversationIdOf,- historyFromMessages,+ type HistoryPage,listConversations,+ pageHistory,resolveConversation,} from "./conversations.ts";import { describeTool, textOf } from "./presentation.ts";@@ -24,6 +26,7 @@ import {type SwitchOutcome,toModelOptions,} from "./profiles.ts";+import { DEFAULT_ROTATION, type RotationLimits, SessionRotator } from "./rotation.ts";import type { AgentRecord, AgentSupervisor, SupervisorEvent } from "./supervisor.ts";import { isBlockedInput, presentText, shouldShowToast } from "./white-label.ts";@@ -38,6 +41,12 @@ export interface BridgeOptions {profiles?: ProfileStore;/** How long switching conversations waits for a running answer to stop. Default 10 s. */stopTimeoutMs?: number;+ /** Optional parts of the app; by default one continuous chat. */+ features?: Features;+ /** When the open session is replaced by a fresh one (docs/design.md §7). */+ rotation?: RotationLimits;+ /** How many messages `history` and each `get_earlier` page carry. Default 100. */+ historyPage?: number;}type ProfileCommand = Extract<@@ -61,6 +70,7 @@ type PendingAsk = { ask: Ask; options?: string[]; timer?: NodeJS.Timeout };const REMEMBERED_REQUEST_IDS = 500;const READY_TIMEOUT_MS = 60_000;const ANSWER_FAILED = "Something went wrong while answering. Please try again.";+const HISTORY_PAGE = 100;/*** Translates between protocol v1 clients and the supervised agent: it keeps@@ -86,6 +96,10 @@ export class DotBridge {private switching: Promise<void> = Promise.resolve();/** Messages waiting for the agent, as shown to the user. */private queue: MessageQueue = { steering: [], followUp: [] };+ /** Messages on their way to the agent; the session is never rotated under them. */+ private sending = 0;+ private readonly features: Features;+ private readonly rotator: SessionRotator;private readonly liveSwitch: LiveModelSwitch;constructor(supervisor: AgentSupervisor, options: BridgeOptions) {@@ -93,6 +107,13 @@ export class DotBridge {this.options = options;this.liveSwitch = new LiveModelSwitch(supervisor, (line) => this.log(line));this.sessionDir = join(options.dataDir, "sessions");+ this.features = options.features ?? { conversations: false };+ this.rotator = new SessionRotator(supervisor, {+ limits: options.rotation ?? DEFAULT_ROTATION,+ canRotate: () =>+ supervisor.state === "ready" && !supervisor.busy && this.asks.size === 0 && this.sending === 0,+ log: (line) => this.log(line),+ });supervisor.onEvent((event) => this.onAgentEvent(event));if (options.auth) options.auth.onCredentialsChanged = () => this.afterCredentialsChange();this.state = this.deriveState();@@ -109,6 +130,7 @@ export class DotBridge {agentState: this.state,...this.conversationRef(),...(this.supervisor.model ? { model: this.supervisor.model } : {}),+ features: this.features,});if (this.queued()) this.deliver(client, { type: "queue", ...this.queue });for (const { ask } of this.asks.values()) this.deliver(client, { type: "ask", ask });@@ -177,11 +199,16 @@ export class DotBridge {await this.switching;this.interrupted = false;const busy = this.supervisor.busy;- await this.supervisor.request(- busy- ? { type: "prompt", message: message.text, streamingBehavior: "steer" }- : { type: "prompt", message: message.text },- );+ this.sending += 1;+ try {+ await this.supervisor.request(+ busy+ ? { type: "prompt", message: message.text, streamingBehavior: "steer" }+ : { type: "prompt", message: message.text },+ );+ } finally {+ this.sending -= 1;+ }return;}case "steer":@@ -215,15 +242,17 @@ export class DotBridge {return;}case "new_conversation":+ if (!this.conversationsOn(client)) return;await this.changeConversation(async () => {await this.switchAfterStop(() => this.supervisor.request({ type: "new_session" }));- this.afterConversationChange([]);+ this.afterConversationChange();});return;case "list_conversations":this.deliver(client, this.conversationsPayload());return;case "open_conversation": {+ if (!this.conversationsOn(client)) return;const path = resolveConversation(this.sessionDir, message.conversationId);if (!path) {this.deliver(client, {@@ -237,7 +266,7 @@ export class DotBridge {await this.switchAfterStop(() =>this.supervisor.request({ type: "switch_session", sessionPath: path }),);- this.afterConversationChange(await this.loadHistory());+ this.afterConversationChange(await this.currentHistory());});return;}@@ -283,12 +312,30 @@ export class DotBridge {this.deliver(client, {type: "history",...this.conversationRef(),- messages: historyFromMessages(await this.currentHistory()),+ ...(await this.currentHistory()),+ });+ return;+ case "get_earlier":+ this.deliver(client, {+ type: "earlier",+ before: message.before,+ ...pageHistory(this.chain(), this.pageSize(), message.before),});return;}}+ /** With the conversations list off there is one chat; starting or opening another is refused. */+ private conversationsOn(client: BridgeClient): boolean {+ if (this.features.conversations) return true;+ this.deliver(client, {+ type: "error",+ code: "conversations_off",+ message: "This assistant keeps one continuous chat.",+ });+ return false;+ }+/** Runs a conversation switch; a message sent meanwhile goes to the new conversation, after its history. */private changeConversation(change: () => Promise<void>): Promise<void> {const run = change();@@ -481,28 +528,44 @@ export class DotBridge {void this.liveSwitch.settle().then((outcome) => this.reportSwitch(outcome));}- private afterConversationChange(messages: unknown[]): void {+ private afterConversationChange(page: HistoryPage = { messages: [], hasEarlier: false }): void {this.interrupted = false;this.assistantId = undefined;- this.broadcast({ type: "history", ...this.conversationRef(), messages: historyFromMessages(messages) });+ this.broadcast({ type: "history", ...this.conversationRef(), ...page });this.broadcast(this.conversationsPayload());}+ /** After a run settles, replace an oversized session; every window gets the same chat, now marked earlier. */+ private rotateWhenIdle(): void {+ void this.changeConversation(async () => {+ if (!(await this.rotator.maybeRotate())) return;+ this.broadcast({ type: "history", ...this.conversationRef(), ...(await this.currentHistory()) });+ });+ }+/*** History replaces what a window shows, so it must not be older than the* messages already sent: read it again when one arrived while loading.*/- private async currentHistory(): Promise<unknown[]> {+ private async currentHistory(): Promise<HistoryPage> {for (let attempt = 0; ; attempt++) {const seen = this.nextMessage;- const messages = await this.loadHistory();- if (this.nextMessage === seen || attempt >= 2) return messages;+ // The engine writes a message to its session file right after announcing it;+ // one round trip makes sure everything announced so far is on disk.+ await this.supervisor.request({ type: "get_state" });+ const page = pageHistory(this.chain(), this.pageSize());+ if (this.nextMessage === seen || attempt >= 2) return page;}}- private async loadHistory(): Promise<unknown[]> {- const response = await this.supervisor.request({ type: "get_messages" });- return (response.data as { messages?: unknown[] } | undefined)?.messages ?? [];+ /** The open chat's session files, oldest first. */+ private chain(): string[] {+ const file = this.supervisor.sessionFile;+ return file ? [...this.supervisor.previousSessions, file] : [];+ }++ private pageSize(): number {+ return this.options.historyPage ?? HISTORY_PAGE;}private conversationsPayload(): ServerPayload {@@ -558,6 +621,7 @@ export class DotBridge {this.broadcast(this.conversationsPayload());this.settleModelSwitch();if (this.restartPending) this.restartAgent();+ else this.rotateWhenIdle();break;case "extension_ui_request":this.onUiRequest(event);diff --git a/packages/daemon/src/conversations.ts b/packages/daemon/src/conversations.tsindex 6dfa45e..6d5167c 100644--- a/packages/daemon/src/conversations.ts+++ b/packages/daemon/src/conversations.ts@@ -1,4 +1,13 @@-import { closeSync, existsSync, openSync, readdirSync, readSync, realpathSync, statSync } from "node:fs";+import {+ closeSync,+ existsSync,+ openSync,+ readdirSync,+ readFileSync,+ readSync,+ realpathSync,+ statSync,+} from "node:fs";import { join, relative, resolve, sep } from "node:path";import type { Activity, ConversationSummary, HistoryMessage } from "@gentle-dot/protocol";import { describeTool, textOf } from "./presentation.ts";@@ -6,6 +15,8 @@ import { presentText } from "./white-label.ts";const TITLE_SCAN_BYTES = 256 * 1024;const TITLE_LENGTH = 60;+const PAGE_ID = /^s(\d+)-(\d+)$/;+const CACHED_FILES = 8;/** Session files under `sessionDir` (and one level of subfolders), newest first. */export function listConversations(sessionDir: string): ConversationSummary[] {@@ -81,6 +92,73 @@ function readHead(path: string): string {}}+/** The messages a session file records, in order; context-only entries (summaries, handoffs) are not messages. */+export function readSessionMessages(file: string): unknown[] {+ if (!existsSync(file)) return [];+ const messages: unknown[] = [];+ for (const line of readFileSync(file, "utf8").split("\n")) {+ if (!line.includes('"message"')) continue;+ try {+ const entry = JSON.parse(line) as { type?: unknown; message?: unknown };+ if (entry.type === "message" && entry.message) messages.push(entry.message);+ } catch {+ // A torn last line while the engine writes; it is read again next time.+ }+ }+ return messages;+}++const turnCache = new Map<string, { size: number; mtimeMs: number; turns: HistoryMessage[] }>();++/** The display turns of one session file, cached while the file is unchanged (earlier files never change). */+function sessionTurns(file: string): HistoryMessage[] {+ if (!existsSync(file)) return [];+ const { size, mtimeMs } = statSync(file);+ const cached = turnCache.get(file);+ if (cached?.size === size && cached.mtimeMs === mtimeMs) return cached.turns;+ const turns = historyFromMessages(readSessionMessages(file));+ turnCache.delete(file);+ turnCache.set(file, { size, mtimeMs, turns });+ if (turnCache.size > CACHED_FILES) turnCache.delete(turnCache.keys().next().value as string);+ return turns;+}++export interface HistoryPage {+ messages: HistoryMessage[];+ hasEarlier: boolean;+}++/**+ * One page of the chat kept in `chain` (session files, oldest first; the last+ * one is open), ending just before the message `before`, or at the newest one.+ * Ids are `s<file index>-<turn number>`, which stay valid while the chain grows.+ * An unknown `before` yields an empty page.+ */+export function pageHistory(chain: string[], limit: number, before?: string): HistoryPage {+ let file = chain.length - 1;+ let end = Number.POSITIVE_INFINITY;+ if (before !== undefined) {+ const match = PAGE_ID.exec(before);+ if (!match || Number(match[1]) >= chain.length) return { messages: [], hasEarlier: false };+ file = Number(match[1]);+ end = Number(match[2]) - 1;+ }+ const page: HistoryMessage[] = [];+ for (; file >= 0; file--, end = Number.POSITIVE_INFINITY) {+ const turns = sessionTurns(chain[file] as string).slice(0, end);+ const start = Math.max(0, turns.length - (limit - page.length));+ const earlier = file < chain.length - 1 ? { earlier: true as const } : {};+ page.unshift(+ ...turns.slice(start).map((turn, i) => ({ ...turn, id: `s${file}-${start + i + 1}`, ...earlier })),+ );+ if (page.length >= limit) {+ const more = start > 0 || chain.slice(0, file).some((path) => sessionTurns(path).length > 0);+ return { messages: page, hasEarlier: more };+ }+ }+ return { messages: page, hasEarlier: false };+}+type AgentMessage = { role?: string; content?: unknown; toolCallId?: string; isError?: boolean };/** Converts Pi `get_messages` output into display messages; consecutive assistant messages form one turn. */diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.tsindex a8e6155..6fac896 100644--- a/packages/daemon/src/daemon.ts+++ b/packages/daemon/src/daemon.ts@@ -9,6 +9,7 @@ import { AuthManager, type AuthRuntime, createModelAuthRuntime, resolveAgentHomeimport { type BridgeClient, DotBridge } from "./bridge.ts";import { ensureMemoryProject, ensurePrivateDir, isolatedAgentEnv } from "./isolation.ts";import { defaultImportPath, ProfileStore } from "./profiles.ts";+import { type RotationLimits, rotationLimits } from "./rotation.ts";import { AgentSupervisor } from "./supervisor.ts";import { identityArgs } from "./white-label.ts";@@ -35,6 +36,12 @@ export interface DaemonOptions {/** Origins allowed to open the WebSocket, besides the daemon's own and the desktop app's. */allowedOrigins?: string[];backoffMs?: number[];+ /** Several conversations instead of one continuous chat; default `GENTLE_DOT_CONVERSATIONS=1`. */+ conversations?: boolean;+ /** When the chat's session is rotated; default from `GENTLE_DOT_ROTATE_BYTES` and `GENTLE_DOT_ROTATE_COMPACTIONS`. */+ rotation?: RotationLimits;+ /** Messages per history page; default `GENTLE_DOT_HISTORY_PAGE` or 100. */+ historyPage?: number;log?: (line: string) => void;}@@ -126,7 +133,16 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {agentHome,importPath: options.profilesImportPath ?? defaultImportPath(process.env),});- const bridge = new DotBridge(supervisor, { dataDir: options.dataDir, log, auth, profiles });+ const historyPage = options.historyPage ?? Number(process.env.GENTLE_DOT_HISTORY_PAGE);+ const bridge = new DotBridge(supervisor, {+ dataDir: options.dataDir,+ log,+ auth,+ profiles,+ features: { conversations: options.conversations ?? process.env.GENTLE_DOT_CONVERSATIONS === "1" },+ rotation: options.rotation ?? rotationLimits(process.env),+ ...(Number.isInteger(historyPage) && historyPage > 0 ? { historyPage } : {}),+ });const server = createServer((req, res) => handleHttp(req, res, options.uiDir, bridge));const wss = new WebSocketServer({ noServer: true, maxPayload: 1024 * 1024 });diff --git a/packages/daemon/src/rotation.ts b/packages/daemon/src/rotation.tsnew file mode 100644index 0000000..77cc6c4--- /dev/null+++ b/packages/daemon/src/rotation.ts@@ -0,0 +1,242 @@+import { randomUUID } from "node:crypto";+import { closeSync, existsSync, openSync, readFileSync, readSync, statSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { readSessionMessages } from "./conversations.ts";+import { textOf } from "./presentation.ts";+import type { AgentSupervisor } from "./supervisor.ts";++/** When the open session is replaced: past this file size or this many compactions. */+export interface RotationLimits {+ bytes: number;+ compactions: number;+}++export const DEFAULT_ROTATION: RotationLimits = { bytes: 20 * 1024 * 1024, compactions: 10 };++/** `customType` of the hidden message that carries the earlier session into the new one. */+export const HANDOFF_TYPE = "gentle-dot.handoff";++/** The engine's session format (`CURRENT_SESSION_VERSION` in pi-coding-agent 1.0.4). */+const SESSION_VERSION = 3;+const RECENT_MESSAGES = 12;+const MESSAGE_CHARS = 2000;+const HANDOFF_INTRO =+ "This conversation continues from an earlier session that grew too long. The user sees one continuous chat and cannot see this note; carry on naturally and do not mention it.";++export function rotationLimits(env: NodeJS.ProcessEnv): RotationLimits {+ const positive = (value: string | undefined) => {+ const number = Number(value);+ return Number.isInteger(number) && number > 0 ? number : undefined;+ };+ return {+ bytes: positive(env.GENTLE_DOT_ROTATE_BYTES) ?? DEFAULT_ROTATION.bytes,+ compactions: positive(env.GENTLE_DOT_ROTATE_COMPACTIONS) ?? DEFAULT_ROTATION.compactions,+ };+}++function entries(file: string, mark: string): Record<string, unknown>[] {+ const found: Record<string, unknown>[] = [];+ for (const line of readFileSync(file, "utf8").split("\n")) {+ if (!line.includes(mark)) continue;+ try {+ found.push(JSON.parse(line) as Record<string, unknown>);+ } catch {+ // A torn line is skipped.+ }+ }+ return found;+}++/**+ * What the new session needs to know: the latest compaction summary (the+ * engine already wrote it, so no extra model call), or, before any+ * compaction, the previous handoff plus the last messages.+ */+export function handoffText(file: string): string {+ const summary = entries(file, '"compaction"')+ .filter((e) => e.type === "compaction" && typeof e.summary === "string")+ .at(-1)?.summary as string | undefined;+ if (summary) return `${HANDOFF_INTRO}\n\nSummary of the conversation so far:\n\n${summary}`;+ const previous = entries(file, HANDOFF_TYPE)+ .filter((e) => e.type === "custom_message" && e.customType === HANDOFF_TYPE)+ .at(-1);+ const recent = readSessionMessages(file)+ .flatMap((raw) => {+ const message = raw as { role?: unknown };+ if (message.role !== "user" && message.role !== "assistant") return [];+ const text = textOf(message).trim();+ const who = message.role === "user" ? "User" : "Assistant";+ return text+ ? [`${who}: ${text.length > MESSAGE_CHARS ? `${text.slice(0, MESSAGE_CHARS)}…` : text}`]+ : [];+ })+ .slice(-RECENT_MESSAGES);+ const earlier = previous ? textOf(previous).replace(HANDOFF_INTRO, "").trim() : "";+ return [+ HANDOFF_INTRO,+ earlier ? `Earlier context:\n\n${earlier}` : "",+ recent.length > 0 ? `The latest messages:\n\n${recent.join("\n\n")}` : "",+ ]+ .filter(Boolean)+ .join("\n\n");+}++/**+ * Writes a new session next to `previousFile` holding only the handoff, as a+ * hidden custom message: the engine sends it to the model as context, and its+ * history never shows it. Field names, ids, and the file name follow what the+ * engine writes itself (pi-coding-agent 1.0.4 `dist/core/session-manager.js`:+ * header 697-704, file name 711-713, custom message 947-958, entry ids 21-29).+ */+export async function writeHandoffSession(+ previousFile: string,+ text: string,+ cwd = process.cwd(),+): Promise<string> {+ const { uuidv7 } = await import("@earendil-works/pi-ai");+ const id = uuidv7();+ const timestamp = new Date().toISOString();+ const previousCwd = entries(previousFile, '"session"')[0]?.cwd;+ const header = {+ type: "session",+ version: SESSION_VERSION,+ id,+ timestamp,+ cwd: typeof previousCwd === "string" ? previousCwd : cwd,+ parentSession: previousFile,+ };+ const handoff = {+ type: "custom_message",+ customType: HANDOFF_TYPE,+ content: text,+ display: false,+ id: randomUUID().slice(0, 8),+ parentId: null,+ timestamp,+ };+ const file = join(dirname(previousFile), `${timestamp.replace(/[:.]/g, "-")}_${id}.jsonl`);+ writeFileSync(file, `${JSON.stringify(header)}\n${JSON.stringify(handoff)}\n`, { flag: "wx", mode: 0o600 });+ return file;+}++export interface RotatorOptions {+ limits: RotationLimits;+ /** True while nothing is running, asking, or being sent. */+ canRotate: () => boolean;+ /** The engine's working folder, for a previous session without one. */+ cwd?: string;+ log?: (line: string) => void;+}++/**+ * Replaces the open session with a fresh one seeded with a handoff once the+ * session file grows too large or holds too many compactions. The chat stays+ * one: the daemon links the files, and history pages read through them.+ */+export class SessionRotator {+ private readonly supervisor: AgentSupervisor;+ private readonly options: RotatorOptions;+ private rotating = false;+ /** Compactions counted so far in one file, read incrementally. */+ private counted = { file: "", offset: 0, count: 0, rest: "" };++ constructor(supervisor: AgentSupervisor, options: RotatorOptions) {+ this.supervisor = supervisor;+ this.options = options;+ }++ /** Rotates when the open session is over a limit and the chat is idle; true when it did. */+ async maybeRotate(): Promise<boolean> {+ if (this.rotating || !this.options.canRotate()) return false;+ const file = this.supervisor.sessionFile;+ if (!file || !existsSync(file)) return false;+ const { limits } = this.options;+ const { size } = statSync(file);+ if (size < limits.bytes && this.compactionsIn(file, size) < limits.compactions) return false;+ this.rotating = true;+ try {+ const state = (await this.supervisor.request({ type: "get_state" })).data as+ | { isStreaming?: boolean; isCompacting?: boolean }+ | undefined;+ if (state?.isStreaming || state?.isCompacting || !this.options.canRotate()) return false;+ return await this.rotate(file);+ } catch (error) {+ this.log(`rotation failed, the chat stays in ${file}: ${(error as Error).message}`);+ return false;+ } finally {+ this.rotating = false;+ }+ }++ private async rotate(file: string): Promise<boolean> {+ const previous = [...this.supervisor.previousSessions, file];+ let seed: string;+ try {+ seed = await writeHandoffSession(file, handoffText(file), this.options.cwd);+ } catch (error) {+ this.log(`rotation skipped, the chat stays in ${file}: ${(error as Error).message}`);+ return false;+ }+ this.supervisor.linkSessions(seed, previous);+ try {+ await this.supervisor.request({ type: "switch_session", sessionPath: seed });+ await this.verify(seed);+ this.log(`rotation: the chat continues in ${seed}`);+ return true;+ } catch (error) {+ // The engine's session format may have drifted; never leave the user without a chat.+ this.log(+ `rotation: the engine did not load the handoff session ${seed} (${(error as Error).message}); starting a fresh session without it`,+ );+ }+ await this.supervisor.request({ type: "new_session", parentSession: file });+ const fresh = this.supervisor.sessionFile;+ if (fresh && fresh !== file) this.supervisor.linkSessions(fresh, previous);+ return true;+ }++ /** The engine opened the handoff session and its context holds the handoff. */+ private async verify(seed: string): Promise<void> {+ if (this.supervisor.sessionFile !== seed) {+ throw new Error(`the engine opened ${this.supervisor.sessionFile ?? "no session"}`);+ }+ const response = await this.supervisor.request({ type: "get_messages" });+ const messages = (response.data as { messages?: unknown[] } | undefined)?.messages ?? [];+ if (!messages.some((m) => (m as { customType?: unknown }).customType === HANDOFF_TYPE)) {+ throw new Error("the handoff is missing from its context");+ }+ }++ private compactionsIn(file: string, size: number): number {+ if (this.counted.file !== file || size < this.counted.offset) {+ this.counted = { file, offset: 0, count: 0, rest: "" };+ }+ if (size > this.counted.offset) {+ const buffer = Buffer.alloc(size - this.counted.offset);+ const fd = openSync(file, "r");+ try {+ readSync(fd, buffer, 0, buffer.length, this.counted.offset);+ } finally {+ closeSync(fd);+ }+ const lines = (this.counted.rest + buffer.toString("utf8")).split("\n");+ this.counted.rest = lines.pop() ?? "";+ this.counted.count += lines.filter(isCompaction).length;+ this.counted.offset = size;+ }+ return this.counted.count;+ }++ private log(line: string): void {+ this.options.log?.(line);+ }+}++function isCompaction(line: string): boolean {+ if (!line.includes('"compaction"')) return false;+ try {+ return (JSON.parse(line) as { type?: unknown }).type === "compaction";+ } catch {+ return false;+ }+}diff --git a/packages/daemon/src/supervisor.ts b/packages/daemon/src/supervisor.tsindex 01ed5d2..c80b7f7 100644--- a/packages/daemon/src/supervisor.ts+++ b/packages/daemon/src/supervisor.ts@@ -30,7 +30,7 @@ export interface SupervisorOptions {/** Arguments placed after the RPC arguments. */extraArgs?: string[];cwd: string;- /** Directory for `sessions/` and `state.json`. */+ /** Directory for `sessions/` and `state.json` (the open session and the chains of rotated ones). */dataDir: string;env?: NodeJS.ProcessEnv;/** Respawn delays; the last value repeats. Default 1s, 2s, 4s, 8s, 16s, 30s. */@@ -79,6 +79,8 @@ export class AgentSupervisor {private interrupted = false;private restartTimer: NodeJS.Timeout | undefined;private closeWaiters: (() => void)[] = [];+ /** For a session started by rotation, the session files it continues, oldest first. */+ private chains: Record<string, string[]> = {};private readonly sessionDir: string;private readonly stateFile: string;private readonly options: SupervisorOptions;@@ -94,6 +96,17 @@ export class AgentSupervisor {return this.child?.pid;}+ /** The earlier session files of the open chat, oldest first. */+ get previousSessions(): string[] {+ return (this.sessionFile && this.chains[this.sessionFile]) || [];+ }++ /** Records that `sessionFile` continues the chat held in `previous` (oldest first). */+ linkSessions(sessionFile: string, previous: string[]): void {+ this.chains[sessionFile] = previous;+ if (this.sessionFile) this.persistSession(this.sessionFile);+ }+onEvent(listener: (event: SupervisorEvent) => void): () => void {this.listeners.add(listener);return () => this.listeners.delete(listener);@@ -304,7 +317,16 @@ export class AgentSupervisor {private readPersistedSession(): string | undefined {try {- const saved = JSON.parse(readFileSync(this.stateFile, "utf8")) as { sessionFile?: string };+ const saved = JSON.parse(readFileSync(this.stateFile, "utf8")) as {+ sessionFile?: string;+ chains?: unknown;+ };+ if (typeof saved.chains === "object" && saved.chains !== null) {+ for (const [file, previous] of Object.entries(saved.chains)) {+ if (Array.isArray(previous) && previous.every((p) => typeof p === "string"))+ this.chains[file] = previous;+ }+ }return typeof saved.sessionFile === "string" ? saved.sessionFile : undefined;} catch {return undefined;@@ -314,7 +336,7 @@ export class AgentSupervisor {private persistSession(sessionFile: string): void {mkdirSync(this.options.dataDir, { recursive: true });const temp = `${this.stateFile}.${process.pid}.tmp`;- writeFileSync(temp, `${JSON.stringify({ sessionFile })}\n`, { mode: 0o600 });+ writeFileSync(temp, `${JSON.stringify({ sessionFile, chains: this.chains })}\n`, { mode: 0o600 });renameSync(temp, this.stateFile);}diff --git a/packages/daemon/test/bridge-stop.test.ts b/packages/daemon/test/bridge-stop.test.tsindex aac47fa..5878d59 100644--- a/packages/daemon/test/bridge-stop.test.ts+++ b/packages/daemon/test/bridge-stop.test.ts@@ -13,7 +13,12 @@ async function setup(env: NodeJS.ProcessEnv) {const { supervisor, dataDir } = fakeSupervisor({ env: { ...process.env, ...env } });supervisors.push(supervisor);const logs: string[] = [];- const bridge = new DotBridge(supervisor, { dataDir, log: (line) => logs.push(line), stopTimeoutMs: 300 });+ const bridge = new DotBridge(supervisor, {+ dataDir,+ log: (line) => logs.push(line),+ stopTimeoutMs: 300,+ features: { conversations: true },+ });const received: ServerPayload[] = [];const client = { send: (payload: ServerPayload) => received.push(payload) };bridge.attach(client);diff --git a/packages/daemon/test/fixtures/fake-agent.ts b/packages/daemon/test/fixtures/fake-agent.tsindex 355382c..93c2c2b 100644--- a/packages/daemon/test/fixtures/fake-agent.ts+++ b/packages/daemon/test/fixtures/fake-agent.ts@@ -1,7 +1,8 @@#!/usr/bin/env node// A deterministic stand-in for `gentle-shell --mode rpc`. It speaks the same JSONL-// records the daemon relies on, persists messages per session file, and has-// scripted prompts for tests:+// records the daemon relies on, persists messages per session file in Pi's format+// (a `session` header, then `message`, `compaction`, and `custom_message` entries;+// custom messages are hidden context the model sees), and has scripted prompts for tests:// "tool:<name>" runs one fake tool call// "ask:select" asks a select dialog and echoes the answer// "ask:confirm" asks a confirm dialog and echoes the answer@@ -11,6 +12,9 @@// "slow" answers after 1.5 s, leaving time to queue messages// "crash" starts a run and exits with code 1// "burst" answers and finishes the run in a single stdout write+// "compact" records a compaction entry (its summary lists the user's messages so far)+// "pad:<n>" grows the session file by about n bytes (an entry outside the context)+// "recall" answers with the hidden context messages it was given// The "noreply" command is never answered.// A prompt sent while busy (with streamingBehavior), steer, and follow_up are// queued like Pi does: a queue_update with both complete queues, then each one@@ -25,6 +29,7 @@// FAKE_AGENT_DROP_QUEUE settle without taking or reporting queued messages// FAKE_AGENT_IGNORE_ABORT answer abort but keep running (a session switch still ends the run)// FAKE_AGENT_START_DELAY_MS answer the first get_state only after this delay+// FAKE_AGENT_DROP_CUSTOM load session files without their custom messages (a format drift)// get_available_models lists MODELS; set_model and set_thinking_level change what// get_state reports, so tests can read the last values back.import { randomUUID } from "node:crypto";@@ -32,7 +37,7 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } frimport { join } from "node:path";type Rec = Record<string, unknown>;-type Message = { role: "user" | "assistant"; content: string };+type Message = { role: "user" | "assistant" | "custom"; content: string; customType?: string };const MODELS: Rec[] = [{@@ -84,6 +89,7 @@ mkdirSync(sessionDir, { recursive: true });let sessionId = "";let sessionFile = "";let messages: Message[] = [];+let lastEntryId: string | null = null;let busy = false;let hanging: ((stopReason: "aborted" | "error") => void) | undefined;/** Resolves when the current run has ended. */@@ -112,31 +118,56 @@ function out(rec: Rec): void {else process.stdout.write(`${JSON.stringify(rec)}\n`);}-function newSession(): void {+function newSession(parentSession?: unknown): void {sessionId = randomUUID();sessionFile = join(sessionDir, `${sessionId}.jsonl`);messages = [];- writeFileSync(sessionFile, "");+ lastEntryId = null;+ const header: Rec = { type: "session", version: 3, id: sessionId, timestamp: new Date().toISOString() };+ header.cwd = process.cwd();+ if (typeof parentSession === "string") header.parentSession = parentSession;+ writeFileSync(sessionFile, `${JSON.stringify(header)}\n`);}function loadSession(path: string): boolean {if (!existsSync(path)) return false;- sessionFile = path;- sessionId =- path- .split("/")- .pop()- ?.replace(/\.jsonl$/, "") ?? "";- messages = readFileSync(path, "utf8")+ const entries = readFileSync(path, "utf8").split("\n").filter(Boolean)- .map((line) => JSON.parse(line) as Message);+ .map((line) => JSON.parse(line) as Rec);+ if (entries[0]?.type !== "session") return false;+ sessionFile = path;+ sessionId = String(entries[0].id);+ messages = [];+ for (const entry of entries.slice(1)) {+ lastEntryId = String(entry.id);+ if (entry.type === "message") {+ const message = entry.message as { role: "user" | "assistant"; content: unknown };+ messages.push({ role: message.role, content: textOf(message.content) });+ }+ if (entry.type === "custom_message" && !process.env.FAKE_AGENT_DROP_CUSTOM) {+ messages.push({ role: "custom", content: textOf(entry.content), customType: String(entry.customType) });+ }+ }return true;}+function textOf(content: unknown): string {+ if (typeof content === "string") return content;+ return Array.isArray(content) ? content.map((block: { text?: string }) => block.text ?? "").join("") : "";+}++function appendEntry(entry: Rec): void {+ const id = randomUUID().slice(0, 8);+ const full = { ...entry, id, parentId: lastEntryId, timestamp: new Date().toISOString() };+ lastEntryId = id;+ appendFileSync(sessionFile, `${JSON.stringify(full)}\n`);+}+function remember(message: Message): void {messages.push(message);- appendFileSync(sessionFile, `${JSON.stringify(message)}\n`);+ const content = message.role === "assistant" ? [{ type: "text", text: message.content }] : message.content;+ appendEntry({ type: "message", message: { role: message.role, content } });}function respond(id: unknown, command: string, data?: unknown, error?: string): void {@@ -240,6 +271,22 @@ async function runPrompt(text: string) {assistantText("Echo: slow");return endRun();}+ if (text === "compact") {+ const said = messages.filter((m) => m.role === "user").map((m) => m.content);+ appendEntry({ type: "compaction", summary: `Summary: ${said.join(", ")}`, tokensBefore: 1000 });+ assistantText("Compacted.");+ return endRun();+ }+ if (text.startsWith("pad:")) {+ appendEntry({ type: "custom", customType: "pad", data: "x".repeat(Number(text.slice(4))) });+ assistantText("Padded.");+ return endRun();+ }+ if (text === "recall") {+ const hidden = messages.filter((m) => m.role === "custom").map((m) => m.content);+ assistantText(hidden.length > 0 ? `Recall: ${hidden.join(" | ")}` : "Recall: nothing");+ return endRun();+ }if (text.startsWith("tool:")) {const toolName = text.slice(5);const toolCallId = randomUUID();@@ -281,6 +328,7 @@ function handle(rec: Rec) {model: { id: model.id, name: model.name, provider: model.provider },thinkingLevel,isStreaming: busy,+ isCompacting: false,sessionFile,sessionId,messageCount: messages.length,@@ -288,11 +336,14 @@ function handle(rec: Rec) {}case "get_messages":return respond(id, "get_messages", {- messages: messages.map((m) =>- m.role === "user"+ messages: messages.map((m) => {+ if (m.role === "custom") {+ return { role: "custom", customType: m.customType, content: m.content, display: false };+ }+ return m.role === "user"? { role: "user", content: m.content }- : { role: "assistant", content: [{ type: "text", text: m.content }] },- ),+ : { role: "assistant", content: [{ type: "text", text: m.content }] };+ }),});case "get_commands":return respond(id, "get_commands", { commands: [{ name: "gentle:status" }, { name: "history" }] });@@ -367,7 +418,7 @@ async function switchSession(rec: Rec): Promise<void> {}const type = String(rec.type);if (type === "new_session") {- newSession();+ newSession(rec.parentSession);return respond(rec.id, type, { cancelled: false });}if (!loadSession(String(rec.sessionPath))) return respond(rec.id, type, undefined, "Session not found");diff --git a/packages/daemon/test/gateway.test.ts b/packages/daemon/test/gateway.test.tsindex 9855783..e5c51fb 100644--- a/packages/daemon/test/gateway.test.ts+++ b/packages/daemon/test/gateway.test.ts@@ -1,9 +1,15 @@import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";import { join } from "node:path";import type { ServerMessage } from "@gentle-dot/protocol";-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import WebSocket from "ws";-import { type DotDaemon, ensureToken, startDaemon, startupMessage } from "../src/daemon.ts";+import {+ type DaemonOptions,+ type DotDaemon,+ ensureToken,+ startDaemon,+ startupMessage,+} from "../src/daemon.ts";import { HIDDEN_NAMES, presentText } from "../src/white-label.ts";import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";@@ -12,7 +18,11 @@ afterEach(async () => {await Promise.all(daemons.splice(0).map((d) => d.close()));});-async function daemon(env: NodeJS.ProcessEnv = process.env) {+/** Most tests here cover the conversations list, so it is on unless `extra` says otherwise. */+async function daemon(+ env: NodeJS.ProcessEnv = process.env,+ extra: Partial<DaemonOptions> = { conversations: true },+) {const dataDir = tempDir();const uiDir = join(dataDir, "ui");mkdirSync(uiDir);@@ -28,6 +38,7 @@ async function daemon(env: NodeJS.ProcessEnv = process.env) {agentArgs: [FAKE_AGENT],agentEnv: env,backoffMs: [50],+ ...extra,});daemons.push(d);return d;@@ -105,6 +116,19 @@ describe("gateway", () => {await waitFor(() => client.messages.some((m) => m.type === "ready"));});+ it("keeps one continuous chat unless GENTLE_DOT_CONVERSATIONS=1 turns the conversations list on", async () => {+ vi.stubEnv("GENTLE_DOT_CONVERSATIONS", "");+ try {+ const single = await authed(await daemon(process.env, {}));+ expect(single.messages[0]).toMatchObject({ type: "ready", features: { conversations: false } });+ vi.stubEnv("GENTLE_DOT_CONVERSATIONS", "1");+ const several = await authed(await daemon(process.env, {}));+ expect(several.messages[0]).toMatchObject({ type: "ready", features: { conversations: true } });+ } finally {+ vi.unstubAllEnvs();+ }+ });+it("sends ready with the agent state and numbers every message", async () => {const d = await daemon();const client = await authed(d);diff --git a/packages/daemon/test/rotation.test.ts b/packages/daemon/test/rotation.test.tsnew file mode 100644index 0000000..68f3076--- /dev/null+++ b/packages/daemon/test/rotation.test.ts@@ -0,0 +1,317 @@+import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { basename, dirname, join } from "node:path";+import type { HistoryMessage, ServerPayload } from "@gentle-dot/protocol";+import { afterEach, describe, expect, it } from "vitest";+import { DotBridge } from "../src/bridge.ts";+import {+ DEFAULT_ROTATION,+ HANDOFF_TYPE,+ type RotationLimits,+ rotationLimits,+ SessionRotator,+ writeHandoffSession,+} from "../src/rotation.ts";+import { AgentSupervisor } from "../src/supervisor.ts";+import { FAKE_AGENT, fakeSupervisor, tempDir, waitFor } from "./helpers.ts";++const supervisors: AgentSupervisor[] = [];+afterEach(async () => {+ await Promise.all(supervisors.splice(0).map((s) => s.stop()));+});++type History = Extract<ServerPayload, { type: "history" }>;+type Earlier = Extract<ServerPayload, { type: "earlier" }>;++async function setup(options: {+ limits?: Partial<RotationLimits>;+ env?: NodeJS.ProcessEnv;+ historyPage?: number;+}) {+ const { supervisor, dataDir } = fakeSupervisor({ env: { ...process.env, ...options.env } });+ supervisors.push(supervisor);+ const logs: string[] = [];+ const bridge = new DotBridge(supervisor, {+ dataDir,+ log: (line) => logs.push(line),+ rotation: { ...DEFAULT_ROTATION, ...options.limits },+ ...(options.historyPage ? { historyPage: options.historyPage } : {}),+ });+ const received: ServerPayload[] = [];+ const client = { send: (payload: ServerPayload) => received.push(payload) };+ bridge.attach(client);+ await supervisor.start();+ /** Sends one message and waits until its answer is done and the agent is idle again. */+ const say = async (text: string) => {+ const done = received.filter((p) => p.type === "message_done").length;+ await bridge.handle(client, { type: "send", text });+ await waitFor(() => received.filter((p) => p.type === "message_done").length > done);+ await waitFor(() => bridge.agentState === "idle");+ };+ const answers = () => received.flatMap((p) => (p.type === "message_done" ? [p.text] : []));+ return { supervisor, bridge, client, received, logs, dataDir, say, answers };+}++const texts = (messages: HistoryMessage[]) => messages.map((m) => m.text);+const headerOf = (file: string) => JSON.parse(readFileSync(file, "utf8").split("\n")[0] ?? "{}");++describe("transparent rotation", () => {+ it("starts a fresh session after enough compactions, seeded with the latest summary and no user message", async () => {+ const { supervisor, received, dataDir, say, answers } = await setup({ limits: { compactions: 2 } });+ const first = supervisor.sessionFile as string;+ await say("plan the trip");+ await say("compact");+ // One compaction is below the limit.+ await new Promise((resolve) => setTimeout(resolve, 100));+ expect(supervisor.sessionFile).toBe(first);++ await say("compact");+ const second = await waitFor(() => supervisor.sessionFile !== first && supervisor.sessionFile);+ expect(supervisor.previousSessions).toEqual([first]);+ expect(headerOf(second)).toMatchObject({ type: "session", parentSession: first });+ const state = JSON.parse(readFileSync(join(dataDir, "state.json"), "utf8"));+ expect(state).toMatchObject({ sessionFile: second, chains: { [second]: [first] } });++ // The chat shows the same messages, now marked as earlier ones.+ const history = await waitFor(() =>+ received.find((p): p is History => p.type === "history" && p.messages.some((m) => m.earlier)),+ );+ expect(texts(history.messages).slice(-2)).toEqual(["compact", "Compacted."]);+ expect(history.messages.every((m) => m.earlier)).toBe(true);++ await say("recall");+ expect(answers().at(-1)).toContain("Summary: plan the trip, compact, compact");+ const userMessages = received.flatMap((p) => (p.type === "user_message" ? [p.text] : []));+ expect(userMessages).toEqual(["plan the trip", "compact", "compact", "recall"]);+ });++ it("rotates by size, handing off the last messages when nothing was compacted yet", async () => {+ const { supervisor, say, answers } = await setup({ limits: { bytes: 3000 } });+ const first = supervisor.sessionFile as string;+ await say("keep this in mind: blue");+ await say("pad:4000");+ await waitFor(() => supervisor.sessionFile !== first);+ await say("recall");+ expect(answers().at(-1)).toContain("keep this in mind: blue");+ });++ it("keeps the chain of session files across a restart of the daemon", async () => {+ const { supervisor, dataDir, say } = await setup({ limits: { compactions: 1 } });+ const first = supervisor.sessionFile as string;+ await say("compact");+ const second = await waitFor(() => supervisor.sessionFile !== first && supervisor.sessionFile);+ await supervisor.stop();+ const again = new AgentSupervisor({+ command: process.execPath,+ args: [FAKE_AGENT],+ cwd: dataDir,+ dataDir,+ });+ expect(again.sessionFile).toBe(second);+ expect(again.previousSessions).toEqual([first]);+ });++ it("leaves the current session working when the handoff cannot be written", async () => {+ const { supervisor, logs, say, answers } = await setup({ limits: { compactions: 1 } });+ const first = supervisor.sessionFile as string;+ await say("hello");+ chmodSync(dirname(first), 0o500);+ try {+ await say("compact");+ await waitFor(() => logs.some((line) => line.includes("rotation")));+ } finally {+ chmodSync(dirname(first), 0o700);+ }+ expect(supervisor.sessionFile).toBe(first);+ expect(supervisor.previousSessions).toEqual([]);+ await say("still here");+ expect(answers().at(-1)).toBe("Echo: still here");+ });++ it("falls back to a fresh session, deleting nothing, when the engine does not load the handoff", async () => {+ const { supervisor, logs, say, answers } = await setup({+ limits: { compactions: 1 },+ env: { FAKE_AGENT_DROP_CUSTOM: "1" },+ });+ const first = supervisor.sessionFile as string;+ await say("compact");+ await waitFor(() => logs.some((line) => line.includes("fresh session")));+ const current = supervisor.sessionFile as string;+ expect(current).not.toBe(first);+ expect(headerOf(current)).toMatchObject({ parentSession: first });+ expect(supervisor.previousSessions).toEqual([first]);+ // The handoff file the engine could not use stays on disk.+ const seed = logs.join("\n").match(/handoff session (\S+\.jsonl)/)?.[1];+ expect(seed && seed !== current && existsSync(seed)).toBe(true);+ await say("after");+ expect(answers().at(-1)).toBe("Echo: after");+ });+});++describe("rotation guards", () => {+ function compactedFile(compactions: number): string {+ const file = join(tempDir(), "s.jsonl");+ const lines = [{ type: "session", version: 3, id: "x", timestamp: new Date().toISOString(), cwd: "/" }];+ for (let i = 0; i < compactions; i++) lines.push({ type: "compaction", summary: `s${i}` } as never);+ writeFileSync(file, `${lines.map((l) => JSON.stringify(l)).join("\n")}\n`);+ return file;+ }++ function stub(sessionFile: string, state: { isStreaming?: boolean; isCompacting?: boolean } = {}) {+ const requests: string[] = [];+ const supervisor = {+ state: "ready",+ busy: false,+ sessionFile,+ previousSessions: [],+ linkSessions: () => {},+ request: async (command: { type: string }) => {+ requests.push(command.type);+ return { type: "response", command: command.type, success: true, data: state };+ },+ } as unknown as AgentSupervisor;+ return { supervisor, requests };+ }++ it("does nothing while the bridge says the chat is not idle", async () => {+ const { supervisor, requests } = stub(compactedFile(3));+ const rotator = new SessionRotator(supervisor, {+ limits: { ...DEFAULT_ROTATION, compactions: 1 },+ canRotate: () => false,+ });+ expect(await rotator.maybeRotate()).toBe(false);+ expect(requests).toEqual([]);+ });++ it("does nothing while the engine still streams or compacts", async () => {+ for (const state of [{ isStreaming: true }, { isCompacting: true }]) {+ const { supervisor, requests } = stub(compactedFile(3), state);+ const rotator = new SessionRotator(supervisor, {+ limits: { ...DEFAULT_ROTATION, compactions: 1 },+ canRotate: () => true,+ });+ expect(await rotator.maybeRotate()).toBe(false);+ expect(requests).toEqual(["get_state"]);+ }+ });++ it("does nothing below the limits", async () => {+ const { supervisor, requests } = stub(compactedFile(2));+ const rotator = new SessionRotator(supervisor, { limits: DEFAULT_ROTATION, canRotate: () => true });+ expect(await rotator.maybeRotate()).toBe(false);+ expect(requests).toEqual([]);+ });++ it("reads its limits from the environment, defaulting to 20 MB or 10 compactions", () => {+ expect(DEFAULT_ROTATION).toEqual({ bytes: 20 * 1024 * 1024, compactions: 10 });+ expect(rotationLimits({})).toEqual(DEFAULT_ROTATION);+ expect(rotationLimits({ GENTLE_DOT_ROTATE_BYTES: "4096", GENTLE_DOT_ROTATE_COMPACTIONS: "3" })).toEqual({+ bytes: 4096,+ compactions: 3,+ });+ expect(rotationLimits({ GENTLE_DOT_ROTATE_BYTES: "lots", GENTLE_DOT_ROTATE_COMPACTIONS: "0" })).toEqual(+ DEFAULT_ROTATION,+ );+ });+});++describe("handoff session file", () => {+ it("is a session the engine's own SessionManager opens and keeps writing to", async () => {+ const dir = join(tempDir(), "sessions");+ mkdirSync(dir);+ const previous = join(dir, "previous.jsonl");+ writeFileSync(+ previous,+ `${JSON.stringify({ type: "session", version: 3, id: "p", timestamp: new Date().toISOString(), cwd: dir })}\n`,+ );+ const file = await writeHandoffSession(previous, "Summary: the user plans a trip.");+ expect(dirname(file)).toBe(dir);+ // Pi's own naming: `<ISO timestamp with : and . as ->_<uuidv7>.jsonl`.+ expect(basename(file)).toMatch(+ /^\d{4}-\d\d-\d\dT\d\d-\d\d-\d\d-\d{3}Z_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.jsonl$/,+ );++ const { SessionManager, CURRENT_SESSION_VERSION } = await import("@earendil-works/pi-coding-agent");+ const manager = SessionManager.open(file);+ expect(manager.getHeader()).toMatchObject({+ type: "session",+ version: CURRENT_SESSION_VERSION,+ cwd: dir,+ parentSession: previous,+ });+ const [entry] = manager.getEntries();+ expect(entry).toMatchObject({+ type: "custom_message",+ customType: HANDOFF_TYPE,+ display: false,+ parentId: null,+ });+ expect(entry?.id).toMatch(/^[0-9a-f]{8}$/);+ const context = manager.buildSessionContext().messages;+ expect(context).toHaveLength(1);+ expect(context[0]).toMatchObject({ role: "custom", customType: HANDOFF_TYPE, display: false });+ expect(JSON.stringify(context[0])).toContain("Summary: the user plans a trip.");++ // The engine appends the next messages to the same file.+ manager.appendMessage({ role: "user", content: "hello again", timestamp: Date.now() });+ const reopened = SessionManager.open(file).buildSessionContext().messages;+ expect(reopened.map((m) => m.role)).toEqual(["custom", "user"]);+ });+});++describe("recent history", () => {+ it("sends only the latest page and pages back across the rotation boundary", async () => {+ const { bridge, client, received, say } = await setup({ limits: { compactions: 2 }, historyPage: 3 });+ await say("one");+ await say("compact");+ await say("compact");+ await waitFor(() => received.some((p) => p.type === "history" && p.messages.some((m) => m.earlier)));+ await say("two");++ const count = received.length;+ await bridge.handle(client, { type: "get_history" });+ const history = received.slice(count).find((p): p is History => p.type === "history") as History;+ expect(texts(history.messages)).toEqual(["Compacted.", "two", "Echo: two"]);+ expect(history.messages.map((m) => m.earlier === true)).toEqual([true, false, false]);+ expect(history.hasEarlier).toBe(true);++ const page = async (before: string) => {+ const start = received.length;+ await bridge.handle(client, { type: "get_earlier", before });+ return received.slice(start).find((p): p is Earlier => p.type === "earlier") as Earlier;+ };+ const second = await page(history.messages[0]?.id as string);+ expect(second.before).toBe(history.messages[0]?.id);+ expect(texts(second.messages)).toEqual(["compact", "Compacted.", "compact"]);+ expect(second.messages.every((m) => m.earlier)).toBe(true);+ expect(second.hasEarlier).toBe(true);++ const third = await page(second.messages[0]?.id as string);+ expect(texts(third.messages)).toEqual(["one", "Echo: one"]);+ expect(third.hasEarlier).toBe(false);++ const unknown = await page("nope");+ expect(unknown).toMatchObject({ messages: [], hasEarlier: false });+ const ids = [...history.messages, ...second.messages, ...third.messages].map((m) => m.id);+ expect(new Set(ids).size).toBe(ids.length);+ });+});++describe("single chat", () => {+ it("tells clients the conversations list is off by default and refuses to start another chat", async () => {+ const { supervisor, bridge, client, received } = await setup({});+ expect(received[0]).toMatchObject({ type: "ready", features: { conversations: false } });+ const first = supervisor.sessionFile;+ await bridge.handle(client, { type: "new_conversation" });+ expect(received.at(-1)).toMatchObject({ type: "error", code: "conversations_off" });+ expect(supervisor.sessionFile).toBe(first);+ });++ it("offers the conversations list when the flag is on", async () => {+ const { supervisor, dataDir } = fakeSupervisor();+ supervisors.push(supervisor);+ const bridge = new DotBridge(supervisor, { dataDir, features: { conversations: true } });+ const received: ServerPayload[] = [];+ bridge.attach({ send: (payload) => received.push(payload) });+ expect(received[0]).toMatchObject({ type: "ready", features: { conversations: true } });+ });+});diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.tsindex 2ca55bd..887f4cb 100644--- a/packages/protocol/src/index.ts+++ b/packages/protocol/src/index.ts@@ -34,6 +34,14 @@ export interface HistoryMessage {role: "user" | "assistant";text: string;activities: Activity[];+ /** From an earlier session of the same chat, before the daemon last rotated it. */+ earlier?: true;+}++/** Optional parts of the app the daemon turns on. */+export interface Features {+ /** Several conversations (list, new conversation); off means one continuous chat. */+ conversations: boolean;}export interface ConversationSummary {@@ -157,6 +165,8 @@ export type ClientMessage =| { type: "list_conversations" }| { type: "open_conversation"; conversationId: string }| { type: "get_history" }+ /** The page of messages before `before`, the id of the oldest message the window shows. */+ | { type: "get_earlier"; before: string }| { type: "auth_list" }| { type: "auth_login"; providerId: string; method: AuthMethod }| { type: "auth_reply"; flowId: string; value?: string; cancelled?: boolean }@@ -171,7 +181,7 @@ export type ClientMessage =| { type: "profile_save_current"; name: string };export type ServerPayload =- | { type: "ready"; agentState: AgentState; conversationId?: string; model?: string }+ | { type: "ready"; agentState: AgentState; conversationId?: string; model?: string; features?: Features }| { type: "agent_state"; state: AgentState }| { type: "user_message"; messageId: string; text: string }| { type: "message_delta"; messageId: string; delta: string }@@ -188,7 +198,14 @@ export type ServerPayload =| { type: "ask"; ask: Ask }| { type: "ask_resolved"; requestId: string }| { type: "toast"; level: "info" | "warning" | "error"; message: string }- | { type: "history"; conversationId?: string; messages: HistoryMessage[] }+ | {+ type: "history";+ conversationId?: string;+ /** Only the most recent messages; `hasEarlier` says whether `get_earlier` has more. */+ messages: HistoryMessage[];+ hasEarlier?: boolean;+ }+ | { type: "earlier"; before: string; messages: HistoryMessage[]; hasEarlier: boolean }| { type: "conversations"; conversations: ConversationSummary[]; activeId?: string }| { type: "interrupted" }| ({ type: "queue" } & MessageQueue)@@ -280,6 +297,10 @@ export function parseClientMessage(raw: string): ClientMessage | undefined {return isString(m.providerId) ? { type: "auth_logout", providerId: m.providerId } : undefined;case "auth_list":return { type: "auth_list" };+ case "get_earlier":+ return isString(m.before) && m.before.length <= 200+ ? { type: "get_earlier", before: m.before }+ : undefined;case "open_conversation":return isString(m.conversationId)? { type: "open_conversation", conversationId: m.conversationId }diff --git a/packages/protocol/test/protocol.test.ts b/packages/protocol/test/protocol.test.tsindex 72f52a0..132814d 100644--- a/packages/protocol/test/protocol.test.ts+++ b/packages/protocol/test/protocol.test.ts@@ -57,10 +57,20 @@ describe("protocol", () => {'{"type":"shell","cmd":"rm"}','{"type":"auth_login","providerId":"x","method":"password"}','{"type":"auth_reply","flowId":"f"}',+ '{"type":"get_earlier"}',+ '{"type":"get_earlier","before":7}',+ `{"type":"get_earlier","before":"${"x".repeat(201)}"}`,]) {expect(parseClientMessage(raw), raw).toBeUndefined();}});++ it("asks for the messages before one the window already shows", () => {+ expect(parseClientMessage('{"type":"get_earlier","before":"s0-12"}')).toEqual({+ type: "get_earlier",+ before: "s0-12",+ });+ });});describe("queue", () => {diff --git a/packages/ui/src/App.tsx b/packages/ui/src/App.tsxindex 30d30fe..929c658 100644--- a/packages/ui/src/App.tsx+++ b/packages/ui/src/App.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import { type ConnectionInfo, tokenFromLocation } from "./client.ts";import { ChatSurface } from "./components/ChatSurface.tsx";import { DotSurface } from "./components/DotSurface.tsx";@@ -37,6 +37,8 @@ export function App() {const [missingToken, setMissingToken] = useState(false);const [focusKey, setFocusKey] = useState(0);const { state, send, dismiss, dispatch } = useDot(info);+ const conversations = useRef(state.features.conversations);+ conversations.current = state.features.conversations;useEffect(() => {if (inDesktop()) {@@ -55,7 +57,10 @@ export function App() {useEffect(() => {if (surface !== "panel") return;const subscriptions = [- onDesktopEvent("dot://new-conversation", () => send({ type: "new_conversation" })),+ // The menu bar item starts a new chat only when the conversations list is on.+ onDesktopEvent("dot://new-conversation", () => {+ if (conversations.current) send({ type: "new_conversation" });+ }),onDesktopEvent("dot://panel-shown", () => setFocusKey((k) => k + 1)),];const onKey = (event: KeyboardEvent) => {diff --git a/packages/ui/src/components/ChatSurface.tsx b/packages/ui/src/components/ChatSurface.tsxindex dcf15be..db87a12 100644--- a/packages/ui/src/components/ChatSurface.tsx+++ b/packages/ui/src/components/ChatSurface.tsx@@ -5,7 +5,7 @@ import { activeTitle, type DotAction, type DotState, isBusy, needsAccount } fromimport { AccountsPanel } from "./AccountsPanel.tsx";import { AskCard } from "./AskCard.tsx";import { Composer } from "./Composer.tsx";-import { AccountsIcon, ConversationsIcon, MinusIcon, PlusIcon, ProfilesIcon } from "./icons.tsx";+import { AccountsIcon, ConversationsIcon, MinusIcon, PlusIcon, ProfilesIcon, RoseGlyph } from "./icons.tsx";import { MessageList } from "./MessageList.tsx";import { ProfilesPanel } from "./ProfilesPanel.tsx";import { newRequestId, type Send } from "./types.ts";@@ -69,6 +69,8 @@ export function ChatSurface({if (state.profiles.open) dispatch({ type: "profiles", open: false });};const covered = state.auth.open || state.profiles.open;+ // One continuous chat unless the daemon turns the conversations list on.+ const conversations = state.features.conversations;const status = statusText(state);const ready =state.connection === "open" && state.agentState !== "restarting" && state.agentState !== "starting";@@ -77,36 +79,47 @@ export function ChatSurface({<div className={`chat chat-${variant}`} data-state={state.agentState}><header className="chat-header" data-tauri-drag-region={variant === "panel" ? "" : undefined}><span className={`state-dot state-${state.agentState}`} aria-hidden="true" />- <h1 className="gradient-text">{activeTitle(state)}</h1>- <button- type="button"- className="icon"- aria-label="Conversations"- title="Conversations"- aria-expanded={showConversations}- onClick={() => {- if (!showConversations) send({ type: "list_conversations" });- setShowConversations(!showConversations);- }}- >- <ConversationsIcon />- </button>+ {conversations ? (+ <>+ <h1 className="gradient-text">{activeTitle(state)}</h1>+ <button+ type="button"+ className="icon"+ aria-label="Conversations"+ title="Conversations"+ aria-expanded={showConversations}+ onClick={() => {+ if (!showConversations) send({ type: "list_conversations" });+ setShowConversations(!showConversations);+ }}+ >+ <ConversationsIcon />+ </button>+ </>+ ) : (+ <h1 className="assistant-name">+ <RoseGlyph />+ <span className="gradient-text">Gentle Dot</span>+ </h1>+ )}<button type="button" className="icon" aria-label="Accounts" title="Accounts" onClick={openAccounts}><AccountsIcon /></button><button type="button" className="icon" aria-label="Profiles" title="Profiles" onClick={openProfiles}><ProfilesIcon /></button>- <button- type="button"- className="icon"- aria-label="New conversation"- title="New conversation"- disabled={!ready}- onClick={() => switchTo({ type: "new_conversation" })}- >- <PlusIcon />- </button>+ {conversations ? (+ <button+ type="button"+ className="icon"+ aria-label="New conversation"+ title="New conversation"+ disabled={!ready}+ onClick={() => switchTo({ type: "new_conversation" })}+ >+ <PlusIcon />+ </button>+ ) : null}{onHide ? (<button type="button" className="icon" aria-label="Hide" title="Hide" onClick={onHide}><MinusIcon />@@ -114,7 +127,7 @@ export function ChatSurface({) : null}</header>- {showConversations ? (+ {conversations && showConversations ? (<nav className="conversations" aria-label="Earlier conversations"><p className="eyebrow">Conversations</p>{state.conversations.length === 0 ? <p className="muted">No conversations yet.</p> : null}@@ -170,7 +183,15 @@ export function ChatSurface({) : null}<main className="chat-body" hidden={covered}>- <MessageList messages={state.messages} queued={[...state.queue.steering, ...state.queue.followUp]} />+ <MessageList+ messages={state.messages}+ queued={[...state.queue.steering, ...state.queue.followUp]}+ hasEarlier={state.hasEarlier}+ onShowEarlier={() => {+ const first = state.messages[0];+ if (first) send({ type: "get_earlier", before: first.id });+ }}+ />{state.interrupted ? (<div className="interrupted"><p>I was interrupted. Continue?</p>diff --git a/packages/ui/src/components/MessageList.tsx b/packages/ui/src/components/MessageList.tsxindex f47c6c9..c14a1f7 100644--- a/packages/ui/src/components/MessageList.tsx+++ b/packages/ui/src/components/MessageList.tsx@@ -1,5 +1,5 @@import type { Activity, ActivityKind } from "@gentle-dot/protocol";-import { useEffect, useRef, useState } from "react";+import { Fragment, useEffect, useRef, useState } from "react";import Markdown from "react-markdown";import remarkGfm from "remark-gfm";import type { ChatMessage } from "../store.ts";@@ -57,15 +57,20 @@ interface MessageListProps {messages: ChatMessage[];/** Messages waiting for the assistant, shown after the running answer. */queued?: string[];+ /** Offers "Show earlier" at the top, which calls `onShowEarlier`. */+ hasEarlier?: boolean;+ onShowEarlier?: () => void;}-export function MessageList({ messages, queued = [] }: MessageListProps) {+export function MessageList({ messages, queued = [], hasEarlier = false, onShowEarlier }: MessageListProps) {const end = useRef<HTMLDivElement>(null);const last = messages.at(-1);- // biome-ignore lint/correctness/useExhaustiveDependencies: scroll whenever the visible content grows+ const lastEarlier = messages.findLastIndex((m) => m.earlier);+ // Earlier pages are added on top, so only the newest message moves the view.+ // biome-ignore lint/correctness/useExhaustiveDependencies: scroll whenever the newest content growsuseEffect(() => {end.current?.scrollIntoView?.({ block: "end" });- }, [messages.length, last?.text, last?.activities.length, last?.note, queued.length]);+ }, [last?.id, last?.text, last?.activities.length, last?.note, queued.length]);if (messages.length === 0 && queued.length === 0) {return (@@ -76,27 +81,41 @@ export function MessageList({ messages, queued = [] }: MessageListProps) {}return (<div className="messages" aria-live="polite">- {messages.map((message) => (- <article key={message.id} className={`message message-${message.role}`}>- {message.activities.length > 0 ? <Activities activities={message.activities} /> : null}- {message.text && message.role === "user" ? (- <div className="message-body message-plain">{message.text}</div>- ) : null}- {message.text && message.role === "assistant" ? (- <div className="message-body">- <Markdown remarkPlugins={[remarkGfm]}>{message.text}</Markdown>+ {hasEarlier ? (+ <button type="button" className="show-earlier" onClick={onShowEarlier}>+ Show earlier+ </button>+ ) : null}+ {messages.map((message, index) => (+ <Fragment key={message.id}>+ <article className={`message message-${message.role}`}>+ {message.activities.length > 0 ? <Activities activities={message.activities} /> : null}+ {message.text && message.role === "user" ? (+ <div className="message-body message-plain">{message.text}</div>+ ) : null}+ {message.text && message.role === "assistant" ? (+ <div className="message-body">+ <Markdown remarkPlugins={[remarkGfm]}>{message.text}</Markdown>+ </div>+ ) : null}+ {message.streaming ? <span className="caret" aria-hidden="true" /> : null}+ {message.note ? (+ <p+ className={`message-note message-note-${message.note.kind}`}+ role={message.note.kind === "error" ? "alert" : undefined}+ >+ {message.note.text}+ </p>+ ) : null}+ </article>+ {index === lastEarlier ? (+ <div className="earlier-divider">+ <hr aria-label="Earlier messages" />+ <span aria-hidden="true">Earlier messages</span>+ <span className="earlier-line" /></div>) : null}- {message.streaming ? <span className="caret" aria-hidden="true" /> : null}- {message.note ? (- <p- className={`message-note message-note-${message.note.kind}`}- role={message.note.kind === "error" ? "alert" : undefined}- >- {message.note.text}- </p>- ) : null}- </article>+ </Fragment>))}{queued.map((text, i) => (<articlediff --git a/packages/ui/src/components/icons.tsx b/packages/ui/src/components/icons.tsxindex ec64b85..7da34fa 100644--- a/packages/ui/src/components/icons.tsx+++ b/packages/ui/src/components/icons.tsx@@ -78,6 +78,33 @@ export function SendIcon() {);}+/** The rose (the app's favicon drawing): who the user is talking to. */+export function RoseGlyph() {+ return (+ <svg+ className="rose-glyph"+ width="18"+ height="18"+ viewBox="0 0 18 18"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.25"+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden="true"+ focusable="false"+ >+ <path d="M6.6 11.1C4.2 10.3 3 8.3 3.1 5.3L5.4 6.5" />+ <path d="M11.4 11.1C13.8 10.3 15 8.3 14.9 5.3L12.6 6.5" />+ <path d="M5.4 6.5C5.5 3.9 7.1 2.5 9 2.5S12.5 3.9 12.6 6.5" />+ <path d="M5.4 6.5C5.8 9.6 7.2 11.2 9 11.6C10.8 11.2 12.2 9.6 12.6 6.5" />+ <path d="M9.05 8.7C7.7 8.7 7.2 7.3 7.9 6.5C8.6 5.8 9.9 6 10.1 6.95C10.25 7.6 9.7 8 9.15 7.8" />+ <path d="M9 11.6C9 13.6 8.6 15.1 7.5 16.6" />+ <path d="M8.85 13.7C10.1 12.6 12.2 12.6 13.1 13.5C12 14.6 10.2 14.7 8.85 13.7Z" />+ </svg>+ );+}+export function MinusIcon() {return (<Icon>diff --git a/packages/ui/src/store.ts b/packages/ui/src/store.tsindex 01c2686..f3bca2a 100644--- a/packages/ui/src/store.ts+++ b/packages/ui/src/store.ts@@ -6,6 +6,7 @@ import type {AuthPrompt,AuthProvider,ConversationSummary,+ Features,MessageQueue,ModelOption,Profile,@@ -50,6 +51,8 @@ export interface ChatMessage {activities: Activity[];/** How an answer ended when it did not finish normally. */note?: { kind: "stopped" | "error"; text: string };+ /** From an earlier session of the chat; a divider follows the last one. */+ earlier?: boolean;}export interface Notice {@@ -63,7 +66,10 @@ export interface DotState {agentState: AgentState;conversationId?: string;model?: string;+ features: Features;messages: ChatMessage[];+ /** More messages exist before the first one shown. */+ hasEarlier: boolean;/** Messages sent while the assistant works, not taken yet. */queue: MessageQueue;asks: Ask[];@@ -85,7 +91,9 @@ export type DotAction =export const initialState: DotState = {connection: "connecting",agentState: "starting",+ features: { conversations: false },messages: [],+ hasEarlier: false,queue: { steering: [], followUp: [] },asks: [],conversations: [],@@ -137,6 +145,7 @@ function reduceServer(state: DotState, message: ServerMessage): DotState {queue: initialState.queue,conversationId: message.conversationId ?? state.conversationId,model: message.model ?? state.model,+ features: message.features ?? initialState.features,};case "agent_state":return { ...state, agentState: message.state };@@ -182,7 +191,15 @@ function reduceServer(state: DotState, message: ServerMessage): DotState {interrupted: false,conversationId: message.conversationId ?? state.conversationId,messages: message.messages.map((m) => ({ ...m, streaming: false })),+ hasEarlier: message.hasEarlier === true,};+ case "earlier": {+ // A page for messages this window no longer starts with (a newer history replaced them) is dropped.+ if (state.messages[0]?.id !== message.before) return state;+ const shown = new Set(state.messages.map((m) => m.id));+ const page = message.messages.filter((m) => !shown.has(m.id)).map((m) => ({ ...m, streaming: false }));+ return { ...state, messages: [...page, ...state.messages], hasEarlier: message.hasEarlier };+ }case "conversations":return {...state,diff --git a/packages/ui/src/styles.css b/packages/ui/src/styles.cssindex ed05daf..ff426f9 100644--- a/packages/ui/src/styles.css+++ b/packages/ui/src/styles.css@@ -524,6 +524,19 @@ textarea:focus {text-overflow: ellipsis;}+/* The single chat's header: the assistant, not a conversation title. */+.chat-header h1.assistant-name {+ display: flex;+ align-items: center;+ gap: 8px;+}++.rose-glyph {+ flex: none;+ color: #ff2d7a;+ filter: drop-shadow(0 0 4px rgba(255, 45, 122, 0.45));+}+.state-dot {flex: none;width: 8px;@@ -632,6 +645,37 @@ textarea:focus {margin: 0 0 14px;}+.show-earlier {+ display: block;+ margin: 0 auto 14px;+ padding: 5px 14px;+ border-radius: var(--radius-pill);+ color: var(--muted);+ font-size: 12px;+ line-height: 16px;+}++/* Where the earlier session of the chat ends: a hairline with a quiet label. */+.earlier-divider {+ display: flex;+ align-items: center;+ gap: 10px;+ margin: 4px 0 18px;+ color: var(--muted);+ font: 600 10px / 14px var(--font-mono);+ letter-spacing: 0.12em;+ text-transform: uppercase;+}++.earlier-divider hr,+.earlier-line {+ flex: 1;+ height: 1px;+ margin: 0;+ border: 0;+ background: var(--line);+}+.message-user {display: flex;flex-direction: column;@@ -966,8 +1010,14 @@ textarea:focus {color: var(--muted);}+/* A fixed height with the global button padding left the text low; center it instead. */.composer-stop {+ display: inline-flex;+ align-items: center;+ justify-content: center;height: 32px;+ padding: 0 14px;+ line-height: 1;border-radius: var(--radius-pill);}diff --git a/packages/ui/test/components.test.tsx b/packages/ui/test/components.test.tsxindex 2076306..4cc2be4 100644--- a/packages/ui/test/components.test.tsx+++ b/packages/ui/test/components.test.tsx@@ -141,6 +141,7 @@ describe("ChatSurface", () => {<ChatSurfacevariant="web"state={state({+ features: { conversations: true },conversationId: "b.jsonl",conversations: [{ id: "b.jsonl", title: "Current", updatedAt: "2026-10-08T10:00:00.000Z" },diff --git a/packages/ui/test/header.test.tsx b/packages/ui/test/header.test.tsxindex a4a53cc..c1b5d57 100644--- a/packages/ui/test/header.test.tsx+++ b/packages/ui/test/header.test.tsx@@ -16,7 +16,8 @@ function apply(state: DotState, ...payloads: ServerPayload[]): DotState {const providers = [{ id: "openai", name: "OpenAI", methods: ["api_key" as const], configured: true }];const ready = apply(- { ...initialState, connection: "open", agentState: "idle" },+ // The conversations list is on here; single-chat.test.tsx covers the default header.+ { ...initialState, connection: "open", agentState: "idle", features: { conversations: true } },{ type: "auth_providers", providers },{ type: "profiles", profiles: [{ name: "daily", roles: {} }], roles: [], models: [], importable: false },);diff --git a/packages/ui/test/single-chat.test.tsx b/packages/ui/test/single-chat.test.tsxnew file mode 100644index 0000000..dd992f3--- /dev/null+++ b/packages/ui/test/single-chat.test.tsx@@ -0,0 +1,184 @@+import type { ClientMessage, ServerMessage, ServerPayload } from "@gentle-dot/protocol";+import { act, render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, describe, expect, it, vi } from "vitest";+import { ChatSurface } from "../src/components/ChatSurface.tsx";+import { type DotState, initialState, reduce } from "../src/store.ts";++function apply(state: DotState, ...payloads: ServerPayload[]): DotState {+ return payloads.reduce(+ (s, p) => reduce(s, { type: "server", message: { ...p, seq: 1 } as ServerMessage }),+ state,+ );+}++const open: DotState = { ...initialState, connection: "open", agentState: "idle" };+const single = apply(open, { type: "ready", agentState: "idle", features: { conversations: false } });+const withList = apply(open, { type: "ready", agentState: "idle", features: { conversations: true } });++const turn = (id: string, role: "user" | "assistant", text: string, earlier?: true) => ({+ id,+ role,+ text,+ activities: [],+ ...(earlier ? { earlier } : {}),+});++describe("one continuous chat", () => {+ it("starts with the conversations list off until the daemon turns it on", () => {+ expect(initialState.features).toEqual({ conversations: false });+ expect(single.features.conversations).toBe(false);+ expect(withList.features.conversations).toBe(true);+ // A daemon that does not say keeps the single chat.+ expect(apply(withList, { type: "ready", agentState: "idle" }).features.conversations).toBe(false);+ });++ it("shows the assistant in the header, with no new-conversation button or conversations list", () => {+ const { container } = render(+ <ChatSurface variant="panel" state={single} send={vi.fn()} dismiss={vi.fn()} onHide={vi.fn()} />,+ );+ expect(screen.queryByRole("button", { name: "New conversation" })).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Conversations" })).not.toBeInTheDocument();+ expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("Gentle Dot");+ expect(container.querySelector(".chat-header .rose-glyph")).not.toBeNull();+ for (const name of ["Accounts", "Profiles", "Hide"]) {+ expect(screen.getByRole("button", { name })).toBeInTheDocument();+ }+ });++ it("brings the conversations back when the flag is on", () => {+ render(<ChatSurface variant="web" state={withList} send={vi.fn()} dismiss={vi.fn()} />);+ expect(screen.getByRole("button", { name: "New conversation" })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Conversations" })).toBeInTheDocument();+ expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent("New conversation");+ });+});++describe("recent history", () => {+ const history = apply(single, {+ type: "history",+ messages: [+ turn("s0-5", "user", "compact", true),+ turn("s0-6", "assistant", "Compacted.", true),+ turn("s1-1", "user", "two"),+ turn("s1-2", "assistant", "Echo: two"),+ ],+ hasEarlier: true,+ });++ it("keeps whether more messages exist, and puts an earlier page on top", () => {+ expect(history.hasEarlier).toBe(true);+ const more = apply(history, {+ type: "earlier",+ before: "s0-5",+ messages: [turn("s0-3", "user", "one", true), turn("s0-4", "assistant", "Echo: one", true)],+ hasEarlier: false,+ });+ expect(more.messages.map((m) => m.text)).toEqual([+ "one",+ "Echo: one",+ "compact",+ "Compacted.",+ "two",+ "Echo: two",+ ]);+ expect(more.hasEarlier).toBe(false);+ // A page for messages this window no longer shows is dropped.+ const stale = apply(history, {+ type: "earlier",+ before: "s9-1",+ messages: [turn("s9-0", "user", "old", true)],+ hasEarlier: true,+ });+ expect(stale.messages).toBe(history.messages);+ // History without the flag means there is nothing earlier.+ expect(apply(history, { type: "history", messages: [] }).hasEarlier).toBe(false);+ });++ it("asks for the page before the first message with Show earlier", async () => {+ const send = vi.fn<(m: ClientMessage) => void>();+ render(<ChatSurface variant="web" state={history} send={send} dismiss={vi.fn()} />);+ await userEvent.click(screen.getByRole("button", { name: "Show earlier" }));+ expect(send).toHaveBeenCalledWith({ type: "get_earlier", before: "s0-5" });+ });++ it("hides Show earlier when nothing earlier exists", () => {+ render(+ <ChatSurface+ variant="web"+ state={{ ...history, hasEarlier: false }}+ send={vi.fn()}+ dismiss={vi.fn()}+ />,+ );+ expect(screen.queryByRole("button", { name: "Show earlier" })).not.toBeInTheDocument();+ });++ it("draws one subtle divider where the earlier session ends", () => {+ const { container } = render(+ <ChatSurface variant="web" state={history} send={vi.fn()} dismiss={vi.fn()} />,+ );+ expect(screen.getAllByRole("separator", { name: "Earlier messages" })).toHaveLength(1);+ expect(container.querySelector(".earlier-divider")).toHaveTextContent("Earlier messages");+ const order = [...container.querySelectorAll(".messages > *")].map((el) =>+ el.matches(".earlier-divider") ? "divider" : el.textContent,+ );+ expect(order.slice(0, 5)).toEqual(["Show earlier", "compact", "Compacted.", "divider", "two"]);+ });++ it("draws no divider when every message is from the current session", () => {+ const s = apply(single, { type: "history", messages: [turn("s0-1", "user", "hi")] });+ render(<ChatSurface variant="web" state={s} send={vi.fn()} dismiss={vi.fn()} />);+ expect(screen.queryByRole("separator", { name: "Earlier messages" })).not.toBeInTheDocument();+ });+});++const desktop = vi.hoisted(() => ({ handlers: new Map<string, () => void>() }));+const dot = vi.hoisted(() => ({ state: undefined as unknown, send: undefined as unknown }));++vi.mock("../src/desktop.ts", () => ({+ inDesktop: () => true,+ connectionInfo: () => new Promise(() => {}),+ hidePanel: () => {},+ togglePanel: () => {},+ setDotState: () => {},+ startDragging: async () => {},+ openUrl: () => {},+ onDesktopEvent: async (name: string, handler: () => void) => {+ desktop.handlers.set(name, handler);+ return () => desktop.handlers.delete(name);+ },+}));++vi.mock("../src/useDot.ts", () => ({+ useDot: () => ({ state: dot.state, send: dot.send, dismiss: () => {}, dispatch: () => {} }),+}));++describe("menu bar New conversation", () => {+ afterEach(() => {+ desktop.handlers.clear();+ window.history.replaceState(null, "", "/");+ });++ async function trayClick(state: DotState) {+ const send = vi.fn();+ dot.state = state;+ dot.send = send;+ window.history.replaceState(null, "", "/?surface=panel");+ const { App } = await import("../src/App.tsx");+ render(<App />);+ await vi.waitFor(() => expect(desktop.handlers.has("dot://new-conversation")).toBe(true));+ act(() => desktop.handlers.get("dot://new-conversation")?.());+ return send;+ }++ it("is ignored in the single chat", async () => {+ const send = await trayClick(single);+ expect(send).not.toHaveBeenCalled();+ });++ it("starts a new conversation when the list is on", async () => {+ const send = await trayClick(withList);+ expect(send).toHaveBeenCalledWith({ type: "new_conversation" });+ });+});diff --git a/packages/ui/test/switch.test.tsx b/packages/ui/test/switch.test.tsxindex b82baa8..53832e7 100644--- a/packages/ui/test/switch.test.tsx+++ b/packages/ui/test/switch.test.tsx@@ -12,7 +12,13 @@ function apply(state: DotState, ...payloads: ServerPayload[]): DotState {);}-const open: DotState = { ...initialState, connection: "open", agentState: "idle" };+// Switching only exists with the conversations list on.+const open: DotState = {+ ...initialState,+ connection: "open",+ agentState: "idle",+ features: { conversations: true },+};describe("answer outcome", () => {it("keeps an error and a stop on the answer they belong to", () => {