From b4782964ce41d16b56d759fb616a20607bf00057 Mon Sep 17 00:00:00 2001 From: J Date: Thu, 29 Oct 2026 16:25:10 -0700 Subject: [PATCH 1/2] Reach the engine through one object the hooks module builds The plugin directory reads a mod's calls from its hooks module alone and refuses $ handed to a function in another file, even from a hook's body. The developer portal flagged 24 such lines in hooks/register.ts, ten a round. hooks/register.ts now builds ioOf($), each member of which makes one plain call on $, with the variable or program it uses written out (HOME, git, du, rm), and the modules in src take that object (src/io.ts) instead of $. A $.state call takes its plugin and key written out in the hooks module, so stateOf spells out the pad's nine values; read and update in src/state.ts reach them through it. What the mod does is unchanged. scripts/dollar_check.ts applies the directory's rule locally and lists every place that breaks it at once: on e658483 it finds the same 24 lines as the portal, in the same order. just dollar_check runs it, and just check runs its tests. --- CHANGELOG.md | 2 + README.md | 6 +- justfile | 17 +- scripts/dollar_check.test.ts | 147 ++++++++++++++++ scripts/dollar_check.ts | 322 +++++++++++++++++++++++++++++++++++ sessionpad/hooks/register.ts | 221 ++++++++++++++++++++---- sessionpad/src/drafts.ts | 10 +- sessionpad/src/export.ts | 55 +++--- sessionpad/src/git.ts | 22 +-- sessionpad/src/io.ts | 54 ++++++ sessionpad/src/pad.ts | 78 ++++----- sessionpad/src/prune.ts | 83 +++++---- sessionpad/src/settings.ts | 12 +- sessionpad/src/state.ts | 108 +++++------- sessionpad/src/store.ts | 62 ++++--- sessionpad/src/summary.ts | 7 +- sessionpad/src/timeline.ts | 49 +++--- sessionpad/src/turns.ts | 43 ++--- sessionpad/src/ui.tsx | 197 ++++++++++----------- sessionpad/src/usage.ts | 15 +- sessionpad/src/workspace.ts | 114 ++++++------- sessionpad/tests/io.test.ts | 195 +++++++++++++++++++++ 22 files changed, 1319 insertions(+), 500 deletions(-) create mode 100644 scripts/dollar_check.test.ts create mode 100644 scripts/dollar_check.ts create mode 100644 sessionpad/src/io.ts create mode 100644 sessionpad/tests/io.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2cccea2..5047829 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ - The READMEs call sessionpad beta software rather than alpha. - The Timeline tab's summary offer says how to turn summary lines on (set `summaryModel` to `haiku`) and has a **Got it** button, instead of a **Turn on summaries** button that changed the setting: the plugin directory accepts no settings call from a mod that keeps its engine for later, as every button and timer in this one does. A change in `/config` reloads the mod with the new value. +- The modules in `sessionpad/src` no longer take Claude Code's `$`. The hooks module builds one object from it, `ioOf($)`, with every call the mod makes written out there, and hands them that: the plugin directory reads a mod's calls from its hooks module alone and refuses `$` passed to another file. What the mod does is unchanged. +- `just dollar_check` applies the plugin directory's whole rule for `$` (`scripts/dollar_check.ts`) and lists every place that breaks it, and `just check` runs the script's tests (`just script_test`). ### Added diff --git a/README.md b/README.md index a2a869b..73e5908 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ Status: beta. Version 0.4.0, not released yet; 0.3.0 was released 2026-10-29, wi ## Requirements -Claude Code 2.1.299 or later, in the Desktop app's Code tab or a terminal. Mods themselves run from 2.1.286 (Desktop) and 2.1.287 (terminal), but releases before 2.1.299 refuse this mod's hooks module, which passes `$` to functions in its other files. Mods don't run in regular claude.ai chats, in Cowork or in Desktop WSL sessions. In `claude -p` and the Agent SDK the commands and tools work but nothing is drawn. The tests run on 2.1.299 (CI) and on the newest release when developing; the releases between aren't tested. +Claude Code 2.1.299 or later, in the Desktop app's Code tab or a terminal. Mods themselves run from 2.1.286 (Desktop) and 2.1.287 (terminal), but releases before 2.1.299 refused this mod's hooks module while it passed `$` to functions in its other files, and the mod hasn't been tried on them since it stopped. Mods don't run in regular claude.ai chats, in Cowork or in Desktop WSL sessions. In `claude -p` and the Agent SDK the commands and tools work but nothing is drawn. The tests run on 2.1.299 (CI) and on the newest release when developing; the releases between aren't tested. ## Install @@ -151,7 +151,7 @@ env reads: CLAUDE_CONFIG_DIR, HOME, USERPROFILE env writes: nothing ``` -There is no `$.http`: the only thing that leaves your machine is the summary line's model call, described above. `$.process.run` runs `git` (read-only commands), `du -sk` and `rm` on the mod's own files. The mod changes no settings: the plugin directory accepts no settings call from a mod that, as this one does in its buttons and timers, keeps the engine for later, so the Timeline tab says how to turn summary lines on instead of doing it. The hooks on `prompt.submit`, `turn.start` and the `tool.call` for Edit, Write, NotebookEdit and Bash only watch: each passes the event on and hands back what came back, untouched. Run `claude plugin validate sessionpad` in a clone to see the full report. +There is no `$.http`: the only thing that leaves your machine is the summary line's model call, described above. `$.process.run` runs `git` (read-only commands), `du -sk` and `rm` on the mod's own files. The mod changes no settings: the plugin directory accepts no settings call from a mod that, as this one does in its buttons and timers, keeps the engine for later, so the Timeline tab says how to turn summary lines on instead of doing it. The hooks on `prompt.submit`, `turn.start` and the `tool.call` for Edit, Write, NotebookEdit and Bash only watch: each passes the event on and hands back what came back, untouched. Run `claude plugin validate sessionpad` in a clone to see the full report. Every one of these calls is written in `sessionpad/hooks/register.ts`, most of them in `ioOf`, which builds the one object the rest of the code reaches Claude Code through. ## Development @@ -171,7 +171,7 @@ Decisions made while building, and places where this build of Claude Code (2.1.3 - **Name and label.** The name is `sessionpad`, which installs and updates go by, so it won't change. The label the plugin lists show is its `displayName`, `Session Pad`. - **The mod is in a subfolder, not the repository root.** `claude plugin validate` warns that a `CLAUDE.md` at a plugin root isn't loaded, and `--strict` turns that into an error; the subfolder also keeps the repository's tooling out of what users install. The marketplace file sits at the repository root, `.claude-plugin/marketplace.json`, with `"source": "./sessionpad"` rather than `"./"`. -- **The hooks module imports sibling files**, with three rules the validator enforces: a hook is written inline or as a function declared at the top of its file; a function in another file that receives `$` is a `function` declaration, not an arrow; and every read and write of a `$.state` value happens in the file that declares it, which is why all of it goes through `src/state.ts`. +- **The hooks module imports sibling files, but hands them no `$`.** The plugin directory lists a mod's calls from its hooks module alone, and refuses `$` passed to a function in another file, even from a hook's body; a hook is written inline or as a function declared at the top of its file. So `hooks/register.ts` builds one object from a hook's `$`, `ioOf($)`, each member of which makes one plain call on `$`, with the program or variable it uses written out (`git`, `du`, `rm`, `HOME`), and the modules in `src` take that object instead (`src/io.ts` is its type). A `$.state` call names its value with the plugin and key written out in the hooks module, so `stateOf` there spells out each of the pad's nine values, and `read` and `update` in `src/state.ts` reach them through it. `just dollar_check` applies the directory's rule locally, and lists every place that breaks it where the developer portal shows ten at a time. - **Drawing is in `src/ui.tsx`**, not `src/ui.ts`, because it uses JSX. - **Session ids.** `/clear` ends the session (`session.end` with reason `clear`) and continues under a new id with no `session.start`; the mod sees it as `classic.SessionStart` with source `clear`. `/resume` reports source `resume`. `/branch` reports source `fork` there (and `resume` at `session.end`). The mod tracks the id it loaded and carries the pad from that id. A pad the new id already has is never overwritten. This comes from the docs and the types; a manual check in a live session is still to do. - **Pane width.** `bodyColumns` already leaves out the pane's close mark, which sits on the frame, so the first row is not drawn two cells shorter. diff --git a/justfile b/justfile index 62c3380..4c89780 100644 --- a/justfile +++ b/justfile @@ -8,13 +8,17 @@ clean: # Run every check: formatting, types, tests. CI runs this recipe on pull # requests into main, and you run it before pushing. -check: format_check validate type_check dollar_check test +check: format_check validate type_check dollar_check script_test test # Fail when a call on $ is split across lines or a property of $ is read: # the plugin directory reads $ only as whole $.noun.method(...) calls. It # reads each line with its comments taken off; it doesn't see a $ taken # apart by destructuring, a call split between noun and method, or anything # after a "//" inside a string on the same line. +# Then scripts/dollar_check.ts applies the directory's whole rule for $, the +# way it reads the source: in the hooks module, $ goes only to a function +# declared at the top of that file, and no module in src holds $ at all. It +# lists every place at once, where the developer portal shows ten a round. dollar_check: #!/usr/bin/env bash set -uo pipefail @@ -23,14 +27,19 @@ dollar_check: if [ "$status" -gt 1 ]; then echo "dollar_check: grep failed"; exit "$status"; fi found=$(printf '%s\n' "$lines" | sed -E 's#//.*$##; s#/\*.*\*/##g' | grep -vE '^[^:]+:[0-9]+:[[:space:]]*\*' | grep -E '\$\.[a-z]+(\.[a-zA-Z]+)?[[:space:]]*$|\$\.[a-z]+\.[a-zA-Z]+[^a-zA-Z(<]|\$\.[a-z]+[^a-zA-Z.]' || true) if [ -n "$found" ]; then echo "$found"; echo "Write each call on \$ whole, on one line: \$.noun.method(...)"; exit 1; fi + bun scripts/dollar_check.ts -# Check formatting of the mod, the marketplace file and the docs +# Run the tests of the repository's own scripts (scripts/*.test.ts) +script_test: + bun test ./scripts + +# Check formatting of the mod, the scripts, the marketplace file and the docs format_check: - bunx prettier --check sessionpad .claude-plugin README.md CHANGELOG.md package.json + bunx prettier --check sessionpad scripts .claude-plugin README.md CHANGELOG.md package.json # Rewrite files into Prettier's format format: - bunx prettier --write sessionpad .claude-plugin README.md CHANGELOG.md package.json + bunx prettier --write sessionpad scripts .claude-plugin README.md CHANGELOG.md package.json # Read the mod, then the marketplace file that lists it, the way Claude Code # will, treating warnings as errors diff --git a/scripts/dollar_check.test.ts b/scripts/dollar_check.test.ts new file mode 100644 index 0000000..6f0e5d3 --- /dev/null +++ b/scripts/dollar_check.test.ts @@ -0,0 +1,147 @@ +import { describe, expect, test } from "bun:test"; + +import { + blankOut, + hooksProblems, + moduleProblems, + topLevelFunctions, +} from "./dollar_check"; + +/** The lines of a hooks module the check reports, given its body. */ +const hookLines = (source: string): number[] => + hooksProblems(source, "register.ts").map((one) => one.line); + +describe("blankOut", () => { + test("blanks comments and string text, keeping offsets", () => { + const source = 'a($) // $.x\nb("$") /* $ */ c'; + const code = blankOut(source); + expect(code.length).toBe(source.length); + expect(code).toBe('a($) \nb(" ") c'); + }); + + test("keeps the code inside a template's ${...}", () => { + const code = blankOut("`t $ ${f($)} u ${`in ${g($)}`}`"); + expect(code).toContain("f($)"); + expect(code).toContain("g($)"); + expect(code.replace(/[fg]\(\$\)/g, "")).not.toContain("$"); + }); + + test("blanks a regular expression but not a division", () => { + expect(blankOut("x.replace(/\\.$/, '')")).not.toContain("$"); + expect(blankOut("const y = (a) / $b / 2;")).toContain("$b"); + }); +}); + +describe("hooksProblems", () => { + test("allows plain calls, parameters and $ handed to this file's functions", () => { + const source = [ + 'import { other } from "../src/other";', + "function helper($: EngineInterface) {", + " return $.store.get(`k`);", + "}", + "export const register: Register = (on, options) => {", + ' on("session.start", async ($, e, next) => {', + " await helper($);", + ' $.ui.log(`a ${String(e)}`, { to: "debug" });', + " return next(e);", + " }).catch(($, e, next) => next(e));", + ' on("ui.render", ($) => other(helper($)));', + "};", + ].join("\n"); + expect(hookLines(source)).toEqual([]); + }); + + test("refuses $ handed to another file's function", () => { + const source = [ + 'import { loadSession } from "../src/pad";', + "export const register: Register = (on) => {", + ' on("session.start", async ($, e, next) => {', + " await loadSession($, e.cwd);", + " return next(e);", + " });", + "};", + ].join("\n"); + expect(hookLines(source)).toEqual([4]); + }); + + test("refuses every other shape of $", () => { + const shapes = [ + "const own = $.plugin.name;", + "($.ui).log('x');", + "$.ui?.log('x');", + "$['ui'].log('x');", + "const kept = $;", + "helper($);", + "helper(!$);", + "thing.helper($);", + "$.ui.log;", + ]; + const source = [ + "function helper($: EngineInterface) {}", + ...shapes.map((line, i) => `function f${i}($: E) { ${line} }`), + ].join("\n"); + expect(hookLines(source)).toEqual([2, 3, 4, 5, 6, 7, 8, 9, 10]); + }); + + test("refuses a call split between its noun and its method", () => { + const source = [ + "function f($: EngineInterface) {", + " $.ui", + " .log('x');", + "}", + ].join("\n"); + expect(hookLines(source)).toEqual([2]); + }); + + test("refuses on used other than as on(...)", () => { + const source = [ + "function helper(on: On) {}", + "export const register: Register = (on) => {", + " helper(on);", + " const kept = on;", + "};", + ].join("\n"); + expect(hookLines(source)).toEqual([4]); + }); + + test("ignores $ in comments, strings and template text", () => { + const source = [ + "// loadSession($)", + "/* other($) */", + "const a = 'other($)';", + "const b = `other($) costs $5`;", + "const c = jquery.$;", + ].join("\n"); + expect(hookLines(source)).toEqual([]); + }); +}); + +describe("topLevelFunctions", () => { + test("names the functions declared at the top, not inner ones or consts", () => { + const code = [ + "function a() {}", + "export async function b() {", + " function inner() {}", + "}", + "const c = () => {};", + ].join("\n"); + expect([...topLevelFunctions(code)]).toEqual(["a", "b"]); + }); +}); + +describe("moduleProblems", () => { + test("refuses $ held in a module, but not ${ or a regular expression", () => { + const source = [ + "export async function f(io: Io) {", + " const t = `${io.x}`.replace(/\\.$/, '');", + " return io.store.get(t);", + "}", + "export function g($: EngineInterface) {", + " return $.store.get('k');", + "}", + ].join("\n"); + expect(moduleProblems(source, "m.ts").map((one) => one.line)).toEqual([ + 5, 6, + ]); + }); +}); diff --git a/scripts/dollar_check.ts b/scripts/dollar_check.ts new file mode 100644 index 0000000..99f12de --- /dev/null +++ b/scripts/dollar_check.ts @@ -0,0 +1,322 @@ +// The plugin directory's rule for $ in a mod's code, checked here so every +// place that breaks it shows at once (the developer portal lists ten at a +// time). Its words: "Write each call on the capability object as +// $.noun.method(...), each registration as on("event", hook) on a line of +// its own, and pass $ or the on function only as one whole argument to a +// function declared at the top of the same file." +// +// In the hooks module, each $ must be a parameter, the start of a plain +// $.noun.method(...) call, or a whole argument to a function declared with +// `function` at the top of that file; each `on` must be register's +// parameter or the callee of on(...). The modules in src never hold $: they +// take the object hooks/register.ts builds from it (see src/io.ts). +// +// Run from the repository root: `bun scripts/dollar_check.ts`. + +export type Problem = { file: string; line: number; text: string }; + +/** + * The source with everything that isn't code blanked out: comments, the text + * of strings, template literals (but not their ${...} parts) and regular + * expressions. Newlines and every offset stay where they were. + */ +export function blankOut(source: string): string { + const out = source.split(""); + const blank = (from: number, to: number): void => { + for (let i = from; i < to; i++) if (out[i] !== "\n") out[i] = " "; + }; + // One entry per template literal open, holding the brace depth its ${...} + // started at; code inside ${...} is scanned as code. + const templates: number[] = []; + let depth = 0; + let i = 0; + while (i < source.length) { + const c = source[i]!; + const next = source[i + 1]; + if (c === "/" && next === "/") { + const end = source.indexOf("\n", i); + const stop = end === -1 ? source.length : end; + blank(i, stop); + i = stop; + } else if (c === "/" && next === "*") { + const end = source.indexOf("*/", i + 2); + const stop = end === -1 ? source.length : end + 2; + blank(i, stop); + i = stop; + } else if (c === '"' || c === "'") { + let j = i + 1; + while (j < source.length && source[j] !== c && source[j] !== "\n") { + j += source[j] === "\\" ? 2 : 1; + } + blank(i + 1, j); + i = j + 1; + } else if (c === "`" || (c === "}" && templates.at(-1) === depth - 1)) { + // A template's text, from its opening backquote or the } that closes + // one of its ${...}, to its closing backquote or its next ${. + if (c === "}") { + templates.pop(); + depth--; + } + let j = i + 1; + while (j < source.length) { + if (source[j] === "\\") j += 2; + else if (source[j] === "`") break; + else if (source[j] === "$" && source[j + 1] === "{") break; + else j++; + } + if (source[j] === "$") { + // The $ of ${ goes with the text; its { and the } that closes it + // stay, so the code inside is read as code, braces balanced. + blank(i + 1, j + 1); + templates.push(depth); + depth++; + i = j + 2; + } else { + blank(i + 1, j); + i = j + 1; + } + } else if (c === "/" && isRegexStart(out, i)) { + let j = i + 1; + let inClass = false; + while (j < source.length && source[j] !== "\n") { + if (source[j] === "\\") j += 2; + else if (source[j] === "[") ((inClass = true), j++); + else if (source[j] === "]") ((inClass = false), j++); + else if (source[j] === "/" && !inClass) break; + else j++; + } + j++; + while (j < source.length && /[a-z]/.test(source[j]!)) j++; + blank(i + 1, j); + i = j; + } else { + if (c === "{") depth++; + if (c === "}") depth--; + i++; + } + } + return out.join(""); +} + +const REGEX_AFTER_WORDS = new Set([ + "return", + "typeof", + "case", + "in", + "of", + "void", + "throw", + "new", + "delete", + "await", + "yield", +]); + +/** Whether a / at `at` starts a regular expression rather than dividing. */ +function isRegexStart(code: string[], at: number): boolean { + let i = at - 1; + while (i >= 0 && /\s/.test(code[i]!)) i--; + if (i < 0) return true; + const c = code[i]!; + if (/[\w$]/.test(c)) { + let j = i; + while (j >= 0 && /[\w$]/.test(code[j]!)) j--; + return REGEX_AFTER_WORDS.has(code.slice(j + 1, i + 1).join("")); + } + return !/[)\]]/.test(c); +} + +const isWordChar = (c: string | undefined): boolean => + c !== undefined && /[\w$]/.test(c); + +/** The index of the ( that encloses `at`, or -1. */ +function openParenBefore(code: string, at: number): number { + let level = 0; + for (let i = at - 1; i >= 0; i--) { + const c = code[i]; + if (c === ")" || c === "]" || c === "}") level++; + else if (c === "(" || c === "[" || c === "{") { + if (level === 0) return c === "(" ? i : -1; + level--; + } + } + return -1; +} + +/** The index of the ) that closes the ( at `open`, or -1. */ +function closeParenAfter(code: string, open: number): number { + let level = 0; + for (let i = open; i < code.length; i++) { + const c = code[i]; + if (c === "(" || c === "[" || c === "{") level++; + else if (c === ")" || c === "]" || c === "}") { + level--; + if (level === 0) return i; + } + } + return -1; +} + +/** The identifier ending right before `at`, with no space between. */ +function wordEndingAt( + code: string, + at: number +): { word: string; start: number } { + let start = at; + while (start > 0 && isWordChar(code[start - 1])) start--; + return { word: code.slice(start, at), start }; +} + +/** The identifier before `at`, skipping spaces. */ +function wordBefore(code: string, at: number): string { + let i = at; + while (i > 0 && /\s/.test(code[i - 1]!)) i--; + return wordEndingAt(code, i).word; +} + +/** The first character before `at` that isn't a space. */ +function charBefore(code: string, at: number): string | undefined { + let i = at - 1; + while (i >= 0 && /\s/.test(code[i]!)) i--; + return code[i]; +} + +/** The first character from `at` on that isn't a space. */ +function charFrom(code: string, at: number): string | undefined { + let i = at; + while (i < code.length && /\s/.test(code[i]!)) i++; + return code[i]; +} + +/** + * Whether the identifier at `at` (of length `size`) is a parameter: in a + * function's or an arrow's parameter list, or an arrow's lone parameter. + */ +function isParameter(code: string, at: number, size: number): boolean { + if (/^\s*=>/.test(code.slice(at + size))) return true; + const open = openParenBefore(code, at); + if (open === -1) return false; + const callee = wordEndingAt(code, open); + if (callee.word !== "" && callee.word !== "async") { + // function name(...) declares; name(...) calls. + return wordBefore(code, callee.start) === "function"; + } + const close = closeParenAfter(code, open); + if (close === -1) return false; + // An arrow's parameters, with or without a return type before the =>. + return /^\s*(:[^=;{}]*)?=>/.test(code.slice(close + 1)); +} + +/** The names of the functions declared with `function` at the top level. */ +export function topLevelFunctions(code: string): Set { + const names = new Set(); + const pattern = + /^(?:export\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/gm; + for (const match of code.matchAll(pattern)) names.add(match[1]!); + return names; +} + +const lineOf = (source: string, at: number): number => + source.slice(0, at).split("\n").length; + +/** Where the hooks module breaks the directory's rule for $ and on. */ +export function hooksProblems(source: string, file: string): Problem[] { + const code = blankOut(source); + const own = topLevelFunctions(code); + const problems: Problem[] = []; + const report = (at: number, text: string): void => { + problems.push({ file, line: lineOf(source, at), text }); + }; + + // A whole argument to a function of this file, or else what it is passed to. + const argumentTo = (at: number, size: number): string | null => { + const before = charBefore(code, at); + const after = charFrom(code, at + size); + if ( + (before !== "(" && before !== ",") || + (after !== "," && after !== ")") + ) { + return null; + } + const open = openParenBefore(code, at); + if (open === -1) return null; + const callee = wordEndingAt(code, open); + if (callee.word === "" || code[callee.start - 1] === ".") return "?"; + return callee.word; + }; + + for (let at = code.indexOf("$"); at !== -1; at = code.indexOf("$", at + 1)) { + if (isWordChar(code[at - 1]) || isWordChar(code[at + 1])) continue; + if (code[at - 1] === ".") continue; + if (/^\.[a-z]+\.[a-zA-Z]+(<[^<>()]*>)?\(/.test(code.slice(at + 1))) + continue; + if (isParameter(code, at, 1)) continue; + const callee = argumentTo(at, 1); + if (callee !== null && own.has(callee)) continue; + report( + at, + callee === null + ? "$ used other than in a plain $.noun.method(...) call or as a whole argument" + : `$ passed to ${callee === "?" ? "a method or an expression" : callee}, not to a function declared at the top of this file` + ); + } + + for (const match of code.matchAll(/(? { + const root = "sessionpad"; + const hooks = (await Bun.file(`${root}/hooks/hooks.json`).json()) as { + modules?: string[]; + }; + const problems: Problem[] = []; + for (const module of hooks.modules ?? []) { + const file = `${root}/hooks/${module.replace(/^\.\//, "")}`; + problems.push(...hooksProblems(await Bun.file(file).text(), file)); + } + const glob = new Bun.Glob("src/**/*.{ts,tsx}"); + for await (const path of glob.scan({ cwd: root })) { + const file = `${root}/${path}`; + problems.push(...moduleProblems(await Bun.file(file).text(), file)); + } + for (const one of problems) + console.log(`${one.file}:${one.line}: ${one.text}`); + if (problems.length > 0) { + console.log( + `dollar_check: ${problems.length} place(s) break the plugin directory's rule for $` + ); + process.exit(1); + } +} + +if (import.meta.main) await main(); diff --git a/sessionpad/hooks/register.ts b/sessionpad/hooks/register.ts index cada517..a372479 100644 --- a/sessionpad/hooks/register.ts +++ b/sessionpad/hooks/register.ts @@ -1,10 +1,19 @@ // sessionpad: a notepad for each session. This module wires the hooks; the // pieces live in ../src (data in store.ts, $.state in state.ts, actions in -// pad.ts, drawing in ui.tsx). - -import type { EngineInterface, Register } from "claude-code"; +// pad.ts, drawing in ui.tsx). They reach the engine through ioOf below. + +import type { + EngineInterface, + PluginState, + Register, + StateAddress, + StateRead, + StateSetOptions, + StateSetResult, +} from "claude-code"; import type { Pad } from "../types"; +import type { Io } from "../src/io"; import { emptyNoteField, forgetEditDrafts } from "../src/drafts"; import { describeExport, exportThisSession } from "../src/export"; import { formatTime } from "../src/format"; @@ -89,6 +98,153 @@ export function describePad(pad: Pad): string { return lines.join("\n"); } +// The pad's values in $.state. A $.state call names its value with the +// plugin and key written out, here or in a const of this file. +const TAB = { plugin: "sessionpad", key: "tab" } as const; +const HEADLINE = { plugin: "sessionpad", key: "headline" } as const; +const NOTES = { plugin: "sessionpad", key: "notes" } as const; +const RECENT = { plugin: "sessionpad", key: "recent" } as const; +const WORKSPACE = { plugin: "sessionpad", key: "workspace" } as const; +const EDITING = { plugin: "sessionpad", key: "editing" } as const; +const DELETED = { plugin: "sessionpad", key: "deleted" } as const; +const USAGE = { plugin: "sessionpad", key: "usage" } as const; +const OFFER = { plugin: "sessionpad", key: "offer" } as const; + +type PadState = PluginState["sessionpad"]; + +/** The refusal for a value the pad doesn't keep in $.state. */ +const notPads = (ref: StateAddress): Promise => + Promise.reject( + new Error( + `sessionpad: the pad keeps no state value ${ref.plugin}.${ref.key}` + ) + ); + +/** + * $.state for the atoms in ../src/state.ts, which `read` and `update` reach + * through: each value's get and set, under its own key. + */ +function stateOf($: EngineInterface): Io["state"] { + const get = (ref: StateAddress): Promise> => { + if (ref.plugin !== "sessionpad" || ref.id !== undefined) { + return notPads(ref); + } + switch (ref.key) { + case "tab": + return $.state.get(TAB); + case "headline": + return $.state.get(HEADLINE); + case "notes": + return $.state.get(NOTES); + case "recent": + return $.state.get(RECENT); + case "workspace": + return $.state.get(WORKSPACE); + case "editing": + return $.state.get(EDITING); + case "deleted": + return $.state.get(DELETED); + case "usage": + return $.state.get(USAGE); + case "offer": + return $.state.get(OFFER); + default: + return notPads(ref); + } + }; + const set = ( + ref: StateAddress, + value: unknown, + options: StateSetOptions = {} + ): Promise => { + if (ref.plugin !== "sessionpad" || ref.id !== undefined) { + return notPads(ref); + } + switch (ref.key) { + case "tab": + return $.state.set(TAB, value as PadState["tab"], options); + case "headline": + return $.state.set(HEADLINE, value as PadState["headline"], options); + case "notes": + return $.state.set(NOTES, value as PadState["notes"], options); + case "recent": + return $.state.set(RECENT, value as PadState["recent"], options); + case "workspace": + return $.state.set(WORKSPACE, value as PadState["workspace"], options); + case "editing": + return $.state.set(EDITING, value as PadState["editing"], options); + case "deleted": + return $.state.set(DELETED, value as PadState["deleted"], options); + case "usage": + return $.state.set(USAGE, value as PadState["usage"], options); + case "offer": + return $.state.set(OFFER, value as PadState["offer"], options); + default: + return notPads(ref); + } + }; + // The engine's get and set are generic over the contract's keys; these + // two answer the same keys, by name. + return { get, set } as unknown as Io["state"]; +} + +/** + * Everything the modules in ../src do outside themselves, built from a + * hook's $: each member makes one call on $, written out here. The plugin + * directory reads a mod's calls from its hooks module alone and refuses $ + * handed to a function in another file, so the modules take this instead. + * Timers and buttons the modules set up keep it, as they kept $ before. + */ +export function ioOf($: EngineInterface): Io { + return { + state: stateOf($), + store: { + get: (key) => $.store.get(key), + set: (key, value) => $.store.set(key, value), + delete: (key) => $.store.delete(key), + keys: () => $.store.keys(), + }, + clock: { + now: () => $.clock.now(), + after: (ms, fn) => $.clock.after(ms, fn), + every: (ms, fn) => $.clock.every(ms, fn), + }, + fs: { + read: (path) => $.fs.read(path), + write: (path, text) => $.fs.write(path, text), + list: (path) => $.fs.list(path), + exists: (path) => $.fs.exists(path), + stat: (path, options) => + options === undefined ? $.fs.stat(path) : $.fs.stat(path, options), + }, + session: { + id: () => $.session.id(), + cwd: () => $.session.cwd(), + repo: () => $.session.repo(), + }, + ui: { + resolve: (e) => $.ui.resolve(e), + invalidate: (event) => $.ui.invalidate(event), + open: (pane) => $.ui.open(pane), + log: (text, options) => $.ui.log(text, options), + toast: (text) => $.ui.toast(text), + }, + model: { + complete: (request) => $.model.complete(request), + }, + env: { + home: () => $.env.get("HOME"), + userProfile: () => $.env.get("USERPROFILE"), + configDir: () => $.env.get("CLAUDE_CONFIG_DIR"), + }, + run: { + git: (args, init) => $.process.run(["git", ...args], init), + du: (path, init) => $.process.run(["du", "-sk", "--", path], init), + rm: (paths, init) => $.process.run(["rm", "-f", "--", ...paths], init), + }, + }; +} + /** Command names another plugin or Claude Code itself already uses. */ async function takenCommands($: EngineInterface): Promise> { try { @@ -321,24 +477,25 @@ export const register: Register = (on, options) => { const warned = new Set(); on("session.start", async ($, e, next) => { + const io = ioOf($); try { loadedId = await $.session.id(); - await loadSession($, loadedId, e.cwd); + await loadSession(io, loadedId, e.cwd); } catch (error) { $.ui.log(`sessionpad: could not load the pad: ${String(error)}`, { to: "debug", }); } - await refreshOffer($, isSummaryOff); + await refreshOffer(io, isSummaryOff); // A new session or a reload: no `du` from before is still this module's. forgetMeasuring(); forgetRenewals(); - await showWorkspace($); + await showWorkspace(io); await registerTools($); // Commands go last: a name clash there must not stop the rest. served = await registerCommands($); - if (loadedId !== undefined) schedulePrune($, retention, loadedId); - keepSeen($, retention); + if (loadedId !== undefined) schedulePrune(io, retention, loadedId); + keepSeen(io, retention); return next(e); }); @@ -350,8 +507,9 @@ export const register: Register = (on, options) => { async ($, e, next) => { // The old session's typing goes: an open note's at once, the note // field's in two draws (see emptyNoteField), whatever the move draws. + const io = ioOf($); forgetEditDrafts(); - emptyNoteField($); + emptyNoteField(io); try { let id = e.session_id; if (!id) id = await $.session.id(); @@ -366,7 +524,7 @@ export const register: Register = (on, options) => { ? "branch" : undefined; try { - if (how !== undefined) await carryPad($, previous, id, how); + if (how !== undefined) await carryPad(io, previous, id, how); } catch (error) { $.ui.log(`sessionpad: could not carry the pad: ${String(error)}`, { to: "debug", @@ -381,7 +539,7 @@ export const register: Register = (on, options) => { } let isTaken = false; if (how !== undefined) { - isTaken = await carryTimeline($, previous, id, how); + isTaken = await carryTimeline(io, previous, id, how); } if (how === "clear" && !isTaken) clearedTo.delete(previous); } catch (error) { @@ -391,7 +549,7 @@ export const register: Register = (on, options) => { ); } } - await loadSession($, id, e.cwd); + await loadSession(io, id, e.cwd); } catch (error) { $.ui.log(`sessionpad: could not reload the pad: ${String(error)}`, { to: "debug", @@ -401,12 +559,12 @@ export const register: Register = (on, options) => { // The Undo card and an open note belonged to the pad left behind, so // they go too, should a host keep $.state. try { - await forgetPaneEdits($); + await forgetPaneEdits(io); } catch { // Left as they were: the next delete or open replaces them. } - await refreshOffer($, isSummaryOff); - await showWorkspace($); + await refreshOffer(io, isSummaryOff); + await showWorkspace(io); return next(e); } ).catch(($, e, next) => next(e)); @@ -419,7 +577,7 @@ export const register: Register = (on, options) => { on("command.run", { command: ["pad", "sessionpad"] }, async ($, e, next) => { if (!served.has(e.command)) return next(e); - return openPane($); + return openPane(ioOf($)); }).catch(($, e, next) => next.called || !served.has(e.command) ? next(e) @@ -427,13 +585,14 @@ export const register: Register = (on, options) => { ); // The commands do their work in the hook's own body. The plugin directory - // reads $ handed to another file's function only from a hook's own body; a - // function in this file may use $ in plain $.noun.method(...) calls and hand - // it, alone, only to another function in this file. + // refuses $ handed to another file's function, from a hook's own body too; + // a function in this file may use $ in plain $.noun.method(...) calls and + // hand it, alone, only to another function in this file. The modules in + // ../src get ioOf($) instead. on("command.run", { command: ["note", "pad-note"] }, async ($, e, next) => { if (!served.has(e.command)) return next(e); try { - const added = await addThisNote($, e.args, "user", next.signal); + const added = await addThisNote(ioOf($), e.args, "user", next.signal); if (added.status === "blank") { return { text: `Usage: /${e.command} ` }; } @@ -453,7 +612,7 @@ export const register: Register = (on, options) => { async ($, e, next) => { if (!served.has(e.command)) return next(e); try { - const set = await setThisHeadline($, e.args, next.signal); + const set = await setThisHeadline(ioOf($), e.args, next.signal); return { text: describeHeadline(set) }; } catch (error) { return { @@ -470,8 +629,9 @@ export const register: Register = (on, options) => { on("command.run", { command: "pad-export" }, async ($, e, next) => { if (!served.has(e.command)) return next(e); try { - const path = await exportThisSession($, e.args); - const text = await describeExport($, path); + const io = ioOf($); + const path = await exportThisSession(io, e.args); + const text = await describeExport(io, path); return { text }; } catch (error) { return { text: `sessionpad: the export failed: ${String(error)}` }; @@ -563,7 +723,7 @@ export const register: Register = (on, options) => { const isChanged = log.fileCount > 0 || log.commands > 0; // The slow parts (git, the model) run on a timer, from turns.ts. finishTurnLater( - $, + ioOf($), finished, timeline, (id) => followersOf(clearedTo, id, finished.at), @@ -586,10 +746,10 @@ export const register: Register = (on, options) => { return { deny: "sessionpad: `text` must be a non-empty string." }; } if (input.kind === "headline") { - const set = await setThisHeadline($, text, next.signal); + const set = await setThisHeadline(ioOf($), text, next.signal); return { result: describeHeadline(set) }; } - const added = await addThisNote($, text, "claude", next.signal); + const added = await addThisNote(ioOf($), text, "claude", next.signal); if (added.status !== "added") return { deny: describeAdd(added) }; return { result: describeAdd(added) }; }).catch(($, e, next) => { @@ -601,7 +761,7 @@ export const register: Register = (on, options) => { }); on("tool.call", { tool: "mcp__sessionpad__notes_read" }, async ($) => { - const pad = await readThisPad($); + const pad = await readThisPad(ioOf($)); return { result: describePad(pad) }; }).catch(($, e, next) => { $.ui.log( @@ -612,14 +772,15 @@ export const register: Register = (on, options) => { }); on("ui.render", { component: "Pane", requestId: "sessionpad" }, ($, e) => - renderPane($, e) + renderPane(ioOf($), e) ); on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => { if (!showBand || e.props.hasSurvey) return next(e); - const headline = await readHeadline($); + const io = ioOf($); + const headline = await readHeadline(io); // A terminal's band is the headline alone (see renderBand): none without. if (headline === "" && !isBandAlways(e)) return next(e); - return renderBand($, e, headline, await next(e)); + return renderBand(io, e, headline, await next(e)); }); }; diff --git a/sessionpad/src/drafts.ts b/sessionpad/src/drafts.ts index f375122..e18b6fa 100644 --- a/sessionpad/src/drafts.ts +++ b/sessionpad/src/drafts.ts @@ -9,7 +9,7 @@ // empties, and a note open for editing stays open but shows its own text // again, losing what was typed in it and not saved. -import type { EngineInterface } from "claude-code"; +import type { Io } from "./io"; /** * The wait between the two draws that empty the note field: longer than the @@ -54,12 +54,12 @@ export function forgetEditDrafts(): void { * once with what it holds, then, once that draw is out, empty. If more is * typed meanwhile, the field keeps it. */ -export function emptyNoteField($: EngineInterface): void { +export function emptyNoteField(io: Io): void { const held = noteDraft; - $.ui.invalidate("ui.render"); - $.clock.after(EMPTY_GAP_MS, () => { + io.ui.invalidate("ui.render"); + io.clock.after(EMPTY_GAP_MS, () => { if (noteDraft !== held) return; noteDraft = ""; - $.ui.invalidate("ui.render"); + io.ui.invalidate("ui.render"); }); } diff --git a/sessionpad/src/export.ts b/sessionpad/src/export.ts index 1df3de8..a4f59f3 100644 --- a/sessionpad/src/export.ts +++ b/sessionpad/src/export.ts @@ -1,8 +1,7 @@ // /pad-export: the session's headline, notes and whole timeline as one // Markdown file, to read later or keep beside the work. -import type { EngineInterface } from "claude-code"; - +import type { Io } from "./io"; import type { Note, NoteAuthor, Pad, TimelineEntry, TurnEntry } from "../types"; import { formatClock, formatDay, formatDuration, formatTime } from "./format"; import { readPad } from "./store"; @@ -197,7 +196,7 @@ export function exportMarkdown( /** Where an export goes: the path asked for, `~` read as home, else the default. */ async function exportPath( - $: EngineInterface, + io: Io, sessionId: string, asked: string ): Promise { @@ -205,20 +204,20 @@ async function exportPath( // Absolute or a network path: used as given. So is a Windows drive // path, on Windows only; elsewhere `c:x` is a relative name. if (/^[\\/]/.test(asked)) return asked; - const isWindows = ((await $.env.get("USERPROFILE")) ?? "") !== ""; + const isWindows = ((await io.env.userProfile()) ?? "") !== ""; if (isWindows && /^[A-Za-z]:/.test(asked)) return asked; if (!/^~(?=$|[\\/])/.test(asked)) { // Relative: under the session's folder, said in full so it can be found. - const cwd = await $.session.cwd(); + const cwd = await io.session.cwd(); return `${cwd.replace(/[\\/]+$/, "")}/${asked}`; } - const home = (await $.env.get("HOME")) || (await $.env.get("USERPROFILE")); + const home = (await io.env.home()) || (await io.env.userProfile()); if (home === undefined || home === "") { throw new Error("no home folder is set, so `~` can't be read"); } return `${home.replace(/[\\/]+$/, "")}${asked.slice(1)}`; } - const dir = await dataDir($); + const dir = await dataDir(io); if (dir === null) { throw new Error("no home folder is set; give a path: /pad-export "); } @@ -230,13 +229,13 @@ async function exportPath( * there but can't be checked (a refused stat) is refused, never written over * unchecked. */ -async function statOf($: EngineInterface, path: string) { +async function statOf(io: Io, path: string) { try { - return await $.fs.stat(path); + return await io.fs.stat(path); } catch (error) { const isMissing = /ENOENT/.test(String(error)) || - !(await $.fs.exists(path).catch(() => true)); + !(await io.fs.exists(path).catch(() => true)); if (isMissing) return undefined; throw new Error( `${path} couldn't be checked, so nothing was written: ${String(error)}` @@ -253,19 +252,19 @@ const unquote = (text: string): string => * export, or to a new file; never over a file that isn't an export. */ async function safeTarget( - $: EngineInterface, + io: Io, sessionId: string, path: string ): Promise { let target = path; - let stat = await statOf($, target); + let stat = await statOf(io, target); if (stat?.kind === "dir") { target = `${path.replace(/[\\/]+$/, "")}/${fileName(sessionId)}.md`; - stat = await statOf($, target); + stat = await statOf(io, target); } if (stat === undefined) return target; if (stat.kind !== "file") throw new Error(`${target} is not a file`); - const text = await $.fs.read(target); + const text = await io.fs.read(target); if (!text.startsWith(EXPORT_MARK)) { throw new Error( `${target} already exists and isn't a sessionpad export, so it was left alone; choose another path` @@ -275,24 +274,21 @@ async function safeTarget( } /** Writes this session's export and resolves the path written. */ -export async function exportThisSession( - $: EngineInterface, - asked = "" -): Promise { - const sessionId = await $.session.id(); +export async function exportThisSession(io: Io, asked = ""): Promise { + const sessionId = await io.session.id(); const named = unquote(asked.trim()); - const path = await exportPath($, sessionId, named); + const path = await exportPath(io, sessionId, named); // The default path is sessionpad's own; a named one is checked first. - const target = named === "" ? path : await safeTarget($, sessionId, path); - const timeline = await loadTimeline($, sessionId); + const target = named === "" ? path : await safeTarget(io, sessionId, path); + const timeline = await loadTimeline(io, sessionId); const markdown = exportMarkdown( sessionId, - await readPad($, sessionId), + await readPad(io, sessionId), timeline.entries, - await $.clock.now(), + await io.clock.now(), timeline.problem ); - await $.fs.write(target, markdown); + await io.fs.write(target, markdown); return target; } @@ -327,15 +323,12 @@ export function isInside(path: string, dir: string): boolean { * the session's folder, how to open it. The Desktop app's file pane opens * only files inside the session's folders. */ -export async function describeExport( - $: EngineInterface, - path: string -): Promise { +export async function describeExport(io: Io, path: string): Promise { const said = `Exported to ${path}`; - const cwd = await $.session.cwd().catch(() => ""); + const cwd = await io.session.cwd().catch(() => ""); // Where each really is, links followed (/tmp is /private/tmp on a Mac). const real = async (one: string): Promise => - (await $.fs.stat(one, { resolve: true }).catch(() => undefined)) + (await io.fs.stat(one, { resolve: true }).catch(() => undefined)) ?.realPath ?? one; if (cwd === "" || isInside(await real(path), await real(cwd))) return said; return `${said}. It's outside this project, so the Desktop app's file pane can't open it: open it from Finder or your file manager, or export into the project with /pad-export , such as /pad-export notes/pad.md.`; diff --git a/sessionpad/src/git.ts b/sessionpad/src/git.ts index edc400e..4083855 100644 --- a/sessionpad/src/git.ts +++ b/sessionpad/src/git.ts @@ -1,8 +1,7 @@ // Where the session's work lives, read from git through $.process.run. Never // called while drawing: the end of a turn runs it on a timer. -import type { EngineInterface } from "claude-code"; - +import type { Io } from "./io"; import type { Worktree } from "../types"; /** The branch and the working tree's top folder; both null outside a repo. */ @@ -11,12 +10,9 @@ export type GitPlace = { branch: string | null; worktree: string | null }; const GIT_TIMEOUT_MS = 5000; /** One git command's trimmed output, or null when it failed or wouldn't start. */ -async function git( - $: EngineInterface, - args: readonly string[] -): Promise { +async function git(io: Io, args: readonly string[]): Promise { try { - const ran = await $.process.run(["git", ...args], { + const ran = await io.run.git(args, { timeoutMs: GIT_TIMEOUT_MS, }); const out = ran.stdout.trim(); @@ -30,14 +26,14 @@ async function git( * The branch checked out in the session's working directory, `detached at * ` for a detached HEAD, and the working tree's top folder. */ -export async function gitPlace($: EngineInterface): Promise { - const worktree = await git($, ["rev-parse", "--show-toplevel"]); +export async function gitPlace(io: Io): Promise { + const worktree = await git(io, ["rev-parse", "--show-toplevel"]); if (worktree === null) return { branch: null, worktree: null }; // symbolic-ref names the branch even before its first commit, where // `rev-parse --abbrev-ref HEAD` fails; it fails on a detached HEAD. - const branch = await git($, ["symbolic-ref", "--short", "-q", "HEAD"]); + const branch = await git(io, ["symbolic-ref", "--short", "-q", "HEAD"]); if (branch !== null) return { branch, worktree }; - const sha = await git($, ["rev-parse", "--short", "HEAD"]); + const sha = await git(io, ["rev-parse", "--short", "HEAD"]); return { branch: sha === null ? "detached HEAD" : `detached at ${sha}`, worktree, @@ -91,10 +87,10 @@ export function parseWorktrees(porcelain: string, current: string): Worktree[] { * branch `gitPlace` read for it; just that one when the list can't be read. */ export async function listWorktrees( - $: EngineInterface, + io: Io, current: GitPlace & { worktree: string } ): Promise { - const listed = await git($, ["worktree", "list", "--porcelain"]); + const listed = await git(io, ["worktree", "list", "--porcelain"]); const others = listed === null ? [] diff --git a/sessionpad/src/io.ts b/sessionpad/src/io.ts new file mode 100644 index 0000000..367d61c --- /dev/null +++ b/sessionpad/src/io.ts @@ -0,0 +1,54 @@ +// What the mod's code reaches outside itself. hooks/register.ts builds it +// from a hook's $ (see ioOf there), writing out every call on $ the mod +// makes: the plugin directory lists a mod's calls from its hooks module +// alone, and refuses $ handed to a function in another file. So no module +// here holds $ itself; each takes this instead, and it does what $ would. +// +// Each member is the engine's own method under the same noun and name, cut +// down to the arguments the mod passes, except `env` and `run`, which name +// the one variable or program each reads or runs. + +import type { EngineInterface, StateDollar } from "claude-code"; + +type Engine = EngineInterface; +type RunInit = NonNullable[1]>; +type Ran = ReturnType; +type LogOptions = NonNullable[1]>; + +export type Io = StateDollar & { + store: Pick; + clock: Pick; + fs: { + read: (path: string) => Promise; + write: Engine["fs"]["write"]; + list: (path: string) => ReturnType; + exists: Engine["fs"]["exists"]; + stat: Engine["fs"]["stat"]; + }; + session: Pick; + ui: Pick & { + log: (text: string, options: LogOptions) => void; + toast: (text: string) => void; + }; + model: { + complete: ( + request: Parameters[0] + ) => ReturnType; + }; + env: { + /** `HOME`, or undefined where it isn't set. */ + home: () => Promise; + /** `USERPROFILE`, Windows' home folder. */ + userProfile: () => Promise; + /** `CLAUDE_CONFIG_DIR`, set when Claude Code keeps its files elsewhere. */ + configDir: () => Promise; + }; + run: { + /** `git `. */ + git: (args: readonly string[], init: RunInit) => Ran; + /** `du -sk -- `: one tree's size in kibibytes. */ + du: (path: string, init: RunInit) => Ran; + /** `rm -f -- `: the mod's own timeline files, when pruned. */ + rm: (paths: readonly string[], init: RunInit) => Ran; + }; +}; diff --git a/sessionpad/src/pad.ts b/sessionpad/src/pad.ts index bc25eda..69d5cb4 100644 --- a/sessionpad/src/pad.ts +++ b/sessionpad/src/pad.ts @@ -1,8 +1,7 @@ // What the commands, the tools and the pane's buttons do to this session's // pad: change the stored pad, then show it through $.state. -import type { EngineInterface } from "claude-code"; - +import type { Io } from "./io"; import type { DeletedNote, Note, NoteAuthor, Pad } from "../types"; import { showPad, showTimeline, showUsage } from "./state"; import { @@ -43,7 +42,7 @@ export type HeadlineResult = { headline: string; isShortened: boolean }; * rest from loading; the first such failure rejects once all were tried. */ export async function loadSession( - $: EngineInterface, + io: Io, sessionId: string, cwd: string ): Promise { @@ -51,22 +50,22 @@ export async function loadSession( // Seen first: another session's prune looks again right before it deletes, // and must find this one seen before its pad is read. try { - const repo = await $.session.repo().catch(() => null); - await touchIndex($, sessionId, { + const repo = await io.session.repo().catch(() => null); + await touchIndex(io, sessionId, { cwd, repo: repo?.root ?? null, - lastSeen: await $.clock.now(), + lastSeen: await io.clock.now(), }); } catch (error) { failures.push(error); } try { - await showPad($, await readPad($, sessionId)); + await showPad(io, await readPad(io, sessionId)); } catch (error) { failures.push(error); } - await showTimeline($, await readTimeline($, sessionId).catch(() => [])); - await showUsage($, await readSummaryUsage($).catch(() => EMPTY_USAGE)); + await showTimeline(io, await readTimeline(io, sessionId).catch(() => [])); + await showUsage(io, await readSummaryUsage(io).catch(() => EMPTY_USAGE)); if (failures.length > 0) throw failures[0]; } @@ -76,44 +75,44 @@ export async function loadSession( * notes plus a note pointing back. A pad the new id already has is kept. */ export async function carryPad( - $: EngineInterface, + io: Io, fromId: string, toId: string, how: "clear" | "branch" ): Promise { - const at = await $.clock.now(); - await changePad($, toId, async (target) => { + const at = await io.clock.now(); + await changePad(io, toId, async (target) => { if (!isEmptyPad(target)) return target; - const source = await readPad($, fromId); + const source = await readPad(io, fromId); return how === "clear" ? source : branchedPad(source, fromId, at); }); } -export async function readThisPad($: EngineInterface): Promise { - return readPad($, await $.session.id()); +export async function readThisPad(io: Io): Promise { + return readPad(io, await io.session.id()); } /** Adds a note to this session's pad, unless it is blank or the pad is full. */ export async function addThisNote( - $: EngineInterface, + io: Io, text: string, by: NoteAuthor, signal?: AbortSignal ): Promise { const clean = cleanNote(text); if (clean === "") return { status: "blank" }; - const note = makeNote(clean, await $.clock.now(), by); + const note = makeNote(clean, await io.clock.now(), by); let isFull = false; const pad = await changePad( - $, - await $.session.id(), + io, + await io.session.id(), (pad) => { isFull = pad.notes.length >= MAX_NOTES; return isFull ? pad : addNote(pad, note); }, signal ); - await showPad($, pad); + await showPad(io, pad); if (isFull) return { status: "full" }; return { status: "added", note, isShortened: clean !== text.trim() }; } @@ -140,7 +139,7 @@ export type EditResult = * is deleted instead) or the note is gone. */ export async function editThisNote( - $: EngineInterface, + io: Io, id: string, text: string ): Promise { @@ -149,11 +148,11 @@ export async function editThisNote( // Set by the change, which runs once; `as` keeps TypeScript from reading // it as always false. let isFound = false as boolean; - const pad = await changePad($, await $.session.id(), (pad) => { + const pad = await changePad(io, await io.session.id(), (pad) => { isFound = pad.notes.some((note) => note.id === id); return isFound ? editNote(pad, id, clean) : pad; }); - await showPad($, pad); + await showPad(io, pad); if (!isFound) return { status: "missing" }; return { status: "saved", isShortened: clean !== text.trim() }; } @@ -173,18 +172,18 @@ export function describeEdit(result: EditResult): string { /** Deletes a note, handing back what Undo needs to put it back. */ export async function deleteThisNote( - $: EngineInterface, + io: Io, id: string ): Promise { - const sessionId = await $.session.id(); + const sessionId = await io.session.id(); let removed = null as DeletedNote | null; - const pad = await changePad($, sessionId, (pad) => { + const pad = await changePad(io, sessionId, (pad) => { const index = pad.notes.findIndex((note) => note.id === id); const note = pad.notes[index]; removed = note === undefined ? null : { sessionId, note, index }; return deleteNote(pad, id); }); - await showPad($, pad); + await showPad(io, pad); return removed; } @@ -196,11 +195,11 @@ export type RestoreResult = "restored" | "present" | "full"; * that has filled up since keeps its notes, and the note waits for room. */ export async function restoreDeletedNote( - $: EngineInterface, + io: Io, deleted: DeletedNote ): Promise { let result: RestoreResult = "restored"; - const pad = await changePad($, deleted.sessionId, (pad) => { + const pad = await changePad(io, deleted.sessionId, (pad) => { if (pad.notes.some((note) => note.id === deleted.note.id)) { result = "present"; return pad; @@ -212,7 +211,7 @@ export async function restoreDeletedNote( result = "restored"; return restoreNote(pad, deleted.note, deleted.index); }); - if (deleted.sessionId === (await $.session.id())) await showPad($, pad); + if (deleted.sessionId === (await io.session.id())) await showPad(io, pad); return result; } @@ -228,22 +227,19 @@ export function describeRestore(result: RestoreResult): string { * Makes a note this session's headline, unless the headline it replaces * would need a place the full pad doesn't have; resolves false then. */ -export async function promoteThisNote( - $: EngineInterface, - id: string -): Promise { - const at = await $.clock.now(); +export async function promoteThisNote(io: Io, id: string): Promise { + const at = await io.clock.now(); // Set by the change, which runs once; `as` keeps TypeScript from reading // it as always false. let isFull = false as boolean; - const pad = await changePad($, await $.session.id(), (pad) => { + const pad = await changePad(io, await io.session.id(), (pad) => { const promoted = promoteNote(pad, id, at); isFull = promoted.notes.length > pad.notes.length && promoted.notes.length > MAX_NOTES; return isFull ? pad : promoted; }); - await showPad($, pad); + await showPad(io, pad); return !isFull; } @@ -252,18 +248,18 @@ export const PROMOTE_FULL = `The pad already holds ${MAX_NOTES} notes, so the he /** Sets this session's headline, or clears it for blank text. */ export async function setThisHeadline( - $: EngineInterface, + io: Io, text: string, signal?: AbortSignal ): Promise { const headline = cleanHeadline(text); const pad = await changePad( - $, - await $.session.id(), + io, + await io.session.id(), (pad) => setHeadline(pad, headline), signal ); - await showPad($, pad); + await showPad(io, pad); const whole = text.replace(/\s+/g, " ").trim(); return { headline: pad.headline, diff --git a/sessionpad/src/prune.ts b/sessionpad/src/prune.ts index 3d03de6..1d00984 100644 --- a/sessionpad/src/prune.ts +++ b/sessionpad/src/prune.ts @@ -4,8 +4,6 @@ // measured that long ago is dropped. Exports are the person's own files and // are never touched. -import type { EngineInterface } from "claude-code"; - import { INDEX_KEY, adoptRows, @@ -13,6 +11,7 @@ import { notesKey, parseIndex, } from "./store"; +import type { Io } from "./io"; import { dataDir, fileName } from "./timeline"; import { parseSize } from "./workspace"; @@ -67,30 +66,30 @@ const isPlainObject = (value: unknown): boolean => * on its own; one that fails is tried again later. */ export async function pruneOld( - $: EngineInterface, + io: Io, days: number, keepIds: readonly string[] ): Promise { const pruned: Pruned = { sessions: 0, files: 0, sizes: 0 }; if (days === 0) return pruned; - const now = await $.clock.now(); - const last = await $.store.get(PRUNE_AT_KEY).catch(() => undefined); + const now = await io.clock.now(); + const last = await io.store.get(PRUNE_AT_KEY).catch(() => undefined); if (typeof last === "number" && last <= now && now - last < DAY_MS) { return pruned; } const before = now - days * DAY_MS; // An index that can't be read stops the prune: every old file would look // like one no session owns. So does one that isn't an index at all. - const stored = await $.store.get(INDEX_KEY); + const stored = await io.store.get(INDEX_KEY); if (stored !== undefined && !isPlainObject(stored)) { throw new Error("the session index isn't one, so nothing was pruned"); } - await $.store.set(PRUNE_AT_KEY, now).catch(() => undefined); + await io.store.set(PRUNE_AT_KEY, now).catch(() => undefined); const index = parseIndex(stored); - const dir = await dataDir($); + const dir = await dataDir(io); const timelineDir = dir === null ? null : `${dir}/timeline`; const listed = ( - timelineDir === null ? [] : await $.fs.list(timelineDir).catch(() => []) + timelineDir === null ? [] : await io.fs.list(timelineDir).catch(() => []) ).filter((entry) => Number.isFinite(entry.mtimeMs)); // When each session's files were last written, by the id their names hold. @@ -109,12 +108,12 @@ export async function pruneOld( // Notes whose index row was lost (two sessions writing it at once) get a // row now, so they age out like any other rather than staying forever. - const keys = await $.store.keys().catch((): string[] => []); + const keys = await io.store.keys().catch((): string[] => []); const rowless = keys .filter((key) => key.startsWith("notes:")) .map((key) => key.slice("notes:".length)) .filter((id) => index[id] === undefined && !keep.has(id)); - await adoptRows($, rowless, now).catch(() => undefined); + await adoptRows(io, rowless, now).catch(() => undefined); // As the index now has them: seen just now, so their files are theirs. for (const id of rowless) index[id] = { cwd: "", repo: null, lastSeen: now }; @@ -122,14 +121,14 @@ export async function pruneOld( const gone: string[] = []; for (const id of unseen) { try { - if (!(await isStillUnseen($, id, before, timelineDir))) continue; - const notes = await $.store.get(notesKey(id)); - await $.store.delete(notesKey(id)); + if (!(await isStillUnseen(io, id, before, timelineDir))) continue; + const notes = await io.store.get(notesKey(id)); + await io.store.delete(notesKey(id)); // Opened in that moment: its notes go back, unless it wrote new ones. - if (!(await isStillUnseen($, id, before, timelineDir))) { - const since = await $.store.get(notesKey(id)); + if (!(await isStillUnseen(io, id, before, timelineDir))) { + const since = await io.store.get(notesKey(id)); if (notes !== undefined && since === undefined) { - await $.store.set(notesKey(id), notes); + await io.store.set(notesKey(id), notes); } continue; } @@ -158,16 +157,16 @@ export async function pruneOld( }); } if (timelineDir !== null) { - pruned.files += await removeFiles($, timelineDir, doomed, before); + pruned.files += await removeFiles(io, timelineDir, doomed, before); } for (const key of keys) { if (!key.startsWith("size:")) continue; try { - const size = parseSize(await $.store.get(key)); + const size = parseSize(await io.store.get(key)); // A value it can't read may be a newer mod's: left alone. if (size === undefined || size.at >= before) continue; - await $.store.delete(key); + await io.store.delete(key); pruned.sizes++; } catch { // Left for the next start. @@ -175,7 +174,7 @@ export async function pruneOld( } // Only the rows of sessions pruned: one kept by a second look keeps its row. - await dropFromIndex($, gone, before).catch(() => undefined); + await dropFromIndex(io, gone, before).catch(() => undefined); return pruned; } @@ -195,11 +194,11 @@ type Doomed = { * whose name spells `fileId`: one that gained its row during the prune. */ async function isOwnedNow( - $: EngineInterface, + io: Io, fileId: string, before: number ): Promise { - const index = parseIndex(await $.store.get(INDEX_KEY)); + const index = parseIndex(await io.store.get(INDEX_KEY)); return Object.entries(index).some( ([id, row]) => fileName(id) === fileId && row.lastSeen >= before ); @@ -211,17 +210,17 @@ async function isOwnedNow( * file, written at every turn, still keeps a session at work. */ async function isStillUnseen( - $: EngineInterface, + io: Io, id: string, before: number, timelineDir: string | null ): Promise { - const row = parseIndex(await $.store.get(INDEX_KEY))[id]; + const row = parseIndex(await io.store.get(INDEX_KEY))[id]; if (row !== undefined && row.lastSeen >= before) return false; if (timelineDir === null) return true; // Kept on one line: the directory's check reads $.noun.method(...) whole. const path = `${timelineDir}/${fileName(id)}.json`; - const file = await $.fs.stat(path).catch(() => undefined); + const file = await io.fs.stat(path).catch(() => undefined); return file === undefined || file.mtimeMs < before; } @@ -234,7 +233,7 @@ async function isStillUnseen( * isn't written again. Resolves how many went. */ async function removeFiles( - $: EngineInterface, + io: Io, timelineDir: string, files: readonly Doomed[], before: number @@ -247,10 +246,10 @@ async function removeFiles( // Looked at again: written, or its session seen, since the listing. const isOwned = file.owner === undefined - ? await isOwnedNow($, file.fileId, before) - : !(await isStillUnseen($, file.owner, before, timelineDir)); + ? await isOwnedNow(io, file.fileId, before) + : !(await isStillUnseen(io, file.owner, before, timelineDir)); if (isOwned) continue; - const stat = await $.fs.stat(file.path).catch(() => undefined); + const stat = await io.fs.stat(file.path).catch(() => undefined); if (stat === undefined || !(stat.mtimeMs < before)) continue; batch.push(file); } catch { @@ -259,8 +258,8 @@ async function removeFiles( } if (batch.length === 0) continue; try { - const ran = await $.process.run( - ["rm", "-f", "--", ...batch.map((file) => file.path)], + const ran = await io.run.rm( + batch.map((file) => file.path), { cwd: timelineDir, timeoutMs: 10_000 } ); if (ran.exitCode === 0) { @@ -273,12 +272,12 @@ async function removeFiles( for (const file of batch) { try { // rm may have removed some before it failed: those are gone. - if (!(await $.fs.exists(file.path))) { + if (!(await io.fs.exists(file.path))) { removed++; continue; } if (file.size <= 3) continue; - await $.fs.write(file.path, "[]\n"); + await io.fs.write(file.path, "[]\n"); removed++; } catch { // Left for the next prune. @@ -293,24 +292,20 @@ async function removeFiles( * has loaded, so a start never waits on it and sessions starting alongside * have marked themselves seen first. */ -export function schedulePrune( - $: EngineInterface, - days: number, - keepId: string -): void { - $.clock.after(PRUNE_DELAY_MS, async () => { +export function schedulePrune(io: Io, days: number, keepId: string): void { + io.clock.after(PRUNE_DELAY_MS, async () => { try { // The session it is now too: a /resume may have moved it. - const current = await $.session.id().catch(() => keepId); - const pruned = await pruneOld($, days, [keepId, current]); + const current = await io.session.id().catch(() => keepId); + const pruned = await pruneOld(io, days, [keepId, current]); if (pruned.sessions + pruned.files + pruned.sizes > 0) { - $.ui.log( + io.ui.log( `sessionpad: pruned ${pruned.sessions} sessions, ${pruned.files} files and ${pruned.sizes} sizes not seen for ${days} days`, { to: "debug" } ); } } catch (error) { - $.ui.log(`sessionpad: pruning failed: ${String(error)}`, { + io.ui.log(`sessionpad: pruning failed: ${String(error)}`, { to: "debug", }); } diff --git a/sessionpad/src/settings.ts b/sessionpad/src/settings.ts index 0c78536..fb0b239 100644 --- a/sessionpad/src/settings.ts +++ b/sessionpad/src/settings.ts @@ -4,8 +4,7 @@ // to turn summary lines on, and a change in /config reloads the mod with the // new value. -import type { EngineInterface } from "claude-code"; - +import type { Io } from "./io"; import { showOffer } from "./state"; /** @@ -19,13 +18,10 @@ export const OFFER_KEY = "summary-offer"; * Shows the Timeline tab's offer to turn summary lines on while they are off * and nobody has dismissed it yet; never fails the caller. */ -export async function refreshOffer( - $: EngineInterface, - isOff: boolean -): Promise { +export async function refreshOffer(io: Io, isOff: boolean): Promise { try { - const isAnswered = (await $.store.get(OFFER_KEY)) !== undefined; - await showOffer($, isOff && !isAnswered); + const isAnswered = (await io.store.get(OFFER_KEY)) !== undefined; + await showOffer(io, isOff && !isAnswered); } catch { // No offer this time: the store couldn't say whether it was answered. } diff --git a/sessionpad/src/state.ts b/sessionpad/src/state.ts index dc287f5..f9c4b35 100644 --- a/sessionpad/src/state.ts +++ b/sessionpad/src/state.ts @@ -6,7 +6,6 @@ // calls on them sit side by side. import { atom, read, update } from "claude-code"; -import type { EngineInterface } from "claude-code"; import type { DeletedNote, @@ -18,6 +17,7 @@ import type { TimelineEntry, WorkspaceView, } from "../types"; +import type { Io } from "./io"; import { recentEntries } from "./timeline"; import { EMPTY_USAGE } from "./usage"; @@ -76,86 +76,83 @@ const usageAtom = atom( ); /** Read while drawing, these subscribe the site to later writes. */ -export function readTab($: EngineInterface): Promise { - return read($, tabAtom); +export function readTab(io: Io): Promise { + return read(io, tabAtom); } -export function readHeadline($: EngineInterface): Promise { - return read($, headlineAtom); +export function readHeadline(io: Io): Promise { + return read(io, headlineAtom); } -export function readNotes($: EngineInterface): Promise { - return read($, notesAtom); +export function readNotes(io: Io): Promise { + return read(io, notesAtom); } -export function readRecent($: EngineInterface): Promise { - return read($, recentAtom); +export function readRecent(io: Io): Promise { + return read(io, recentAtom); } -export function readWorkspace($: EngineInterface): Promise { - return read($, workspaceAtom); +export function readWorkspace(io: Io): Promise { + return read(io, workspaceAtom); } -export function readEditing($: EngineInterface): Promise { - return read($, editingAtom); +export function readEditing(io: Io): Promise { + return read(io, editingAtom); } -export function readDeleted($: EngineInterface): Promise { - return read($, deletedAtom); +export function readDeleted(io: Io): Promise { + return read(io, deletedAtom); } -export function readUsage($: EngineInterface): Promise { - return read($, usageAtom); +export function readUsage(io: Io): Promise { + return read(io, usageAtom); } -export function readOffer($: EngineInterface): Promise { - return read($, offerAtom); +export function readOffer(io: Io): Promise { + return read(io, offerAtom); } /** Never call these while drawing: write from a handler or another event. */ -export async function showTab($: EngineInterface, tab: Tab): Promise { - await update($, tabAtom, () => tab); +export async function showTab(io: Io, tab: Tab): Promise { + await update(io, tabAtom, () => tab); } /** Puts a pad's headline and notes where the pane and the band read them. */ -export async function showPad($: EngineInterface, pad: Pad): Promise { - await update($, headlineAtom, () => pad.headline); - await update($, notesAtom, () => pad.notes); +export async function showPad(io: Io, pad: Pad): Promise { + await update(io, headlineAtom, () => pad.headline); + await update(io, notesAtom, () => pad.notes); } /** Puts a timeline's newest entries where the Timeline tab reads them. */ export async function showTimeline( - $: EngineInterface, + io: Io, entries: readonly TimelineEntry[] ): Promise { - await update($, recentAtom, () => recentEntries(entries)); + await update(io, recentAtom, () => recentEntries(entries)); } /** Changes what the Workspace tab shows; `change` may run more than once. */ export async function changeWorkspace( - $: EngineInterface, + io: Io, change: (view: WorkspaceView) => WorkspaceView ): Promise { - await update($, workspaceAtom, change); + await update(io, workspaceAtom, change); } /** Opens a note for editing, or closes the one open with null. */ export async function showEditing( - $: EngineInterface, + io: Io, editing: Editing | null ): Promise { - await update($, editingAtom, () => editing); + await update(io, editingAtom, () => editing); } /** * Closes the open note, if it is still this one: a press drawn before another * note opened must not close that one. */ -export async function closeEditing( - $: EngineInterface, - id: string -): Promise { - await update($, editingAtom, (editing) => +export async function closeEditing(io: Io, id: string): Promise { + await update(io, editingAtom, (editing) => editing?.id === id ? null : editing ); } @@ -165,21 +162,15 @@ export async function closeEditing( * whose Undo the full pad refused stays, since this delete made its room, * and waits no more: the delete after it takes the card as any other does. */ -export async function keepDeleted( - $: EngineInterface, - deleted: DeletedNote -): Promise { - await update($, deletedAtom, (kept) => +export async function keepDeleted(io: Io, deleted: DeletedNote): Promise { + await update(io, deletedAtom, (kept) => kept?.isWaiting === true ? { ...kept, isWaiting: false } : deleted ); } /** Marks the kept note as waiting for room, if it is still this one. */ -export async function holdDeleted( - $: EngineInterface, - noteId: string -): Promise { - await update($, deletedAtom, (kept) => +export async function holdDeleted(io: Io, noteId: string): Promise { + await update(io, deletedAtom, (kept) => kept?.note.id === noteId ? { ...kept, isWaiting: true } : kept ); } @@ -188,33 +179,24 @@ export async function holdDeleted( * Forgets the kept note once it is back, if it is still this one: an Undo * drawn before a newer delete must not take that delete's card away. */ -export async function forgetDeleted( - $: EngineInterface, - noteId: string -): Promise { - await update($, deletedAtom, (kept) => +export async function forgetDeleted(io: Io, noteId: string): Promise { + await update(io, deletedAtom, (kept) => kept?.note.id === noteId ? null : kept ); } /** Shows or hides the Timeline tab's offer to turn summary lines on. */ -export async function showOffer( - $: EngineInterface, - isShown: boolean -): Promise { - await update($, offerAtom, () => isShown); +export async function showOffer(io: Io, isShown: boolean): Promise { + await update(io, offerAtom, () => isShown); } /** Puts what the summary lines have cost where the Timeline tab reads it. */ -export async function showUsage( - $: EngineInterface, - usage: SummaryUsage -): Promise { - await update($, usageAtom, () => usage); +export async function showUsage(io: Io, usage: SummaryUsage): Promise { + await update(io, usageAtom, () => usage); } /** Drops the open note and the kept one, for a session that starts afresh. */ -export async function forgetPaneEdits($: EngineInterface): Promise { - await update($, editingAtom, () => null); - await update($, deletedAtom, () => null); +export async function forgetPaneEdits(io: Io): Promise { + await update(io, editingAtom, () => null); + await update(io, deletedAtom, () => null); } diff --git a/sessionpad/src/store.ts b/sessionpad/src/store.ts index 72e00e0..c8dafdf 100644 --- a/sessionpad/src/store.ts +++ b/sessionpad/src/store.ts @@ -6,8 +6,9 @@ // land. Two processes writing the same key can still race; each session id // normally lives in one process. -import type { EngineInterface, Timer } from "claude-code"; +import type { Timer } from "claude-code"; +import type { Io } from "./io"; import type { Note, NoteAuthor, Pad } from "../types"; export const MAX_HEADLINE_LENGTH = 200; @@ -138,23 +139,20 @@ export const branchedPad = (from: Pad, fromId: string, at: number): Pad => makeNote(`Branched from session \`${fromId}\`.`, at, "sessionpad") ); -export async function readPad( - $: EngineInterface, - sessionId: string -): Promise { - return parsePad(await $.store.get(notesKey(sessionId))); +export async function readPad(io: Io, sessionId: string): Promise { + return parsePad(await io.store.get(notesKey(sessionId))); } /** Writes the pad, or removes its key when it holds nothing. */ export async function writePad( - $: EngineInterface, + io: Io, sessionId: string, pad: Pad ): Promise { if (isEmptyPad(pad)) { - await $.store.delete(notesKey(sessionId)); + await io.store.delete(notesKey(sessionId)); } else { - await $.store.set(notesKey(sessionId), pad); + await io.store.set(notesKey(sessionId), pad); } } @@ -186,30 +184,30 @@ export function oneAtATime( * call changePad itself, which would wait on itself. */ export async function changePad( - $: EngineInterface, + io: Io, sessionId: string, change: (pad: Pad) => Pad | Promise, signal?: AbortSignal ): Promise { return oneAtATime(async () => { - const changed = await change(await readPad($, sessionId)); - await writePad($, sessionId, changed); + const changed = await change(await readPad(io, sessionId)); + await writePad(io, sessionId, changed); return changed; }, signal); } /** Records that a session was seen, re-reading the shared index first. */ export async function touchIndex( - $: EngineInterface, + io: Io, sessionId: string, entry: IndexEntry ): Promise { await oneAtATime(async () => { - const stored = await $.store.get(INDEX_KEY); + const stored = await io.store.get(INDEX_KEY); // One that isn't an index is left as found: pruning stops on it, where // a fresh one would make every other session's files look unowned. if (stored !== undefined && !isRecord(stored)) return; - await $.store.set(INDEX_KEY, { ...(stored ?? {}), [sessionId]: entry }); + await io.store.set(INDEX_KEY, { ...(stored ?? {}), [sessionId]: entry }); }); } @@ -247,7 +245,7 @@ export function forgetRenewals(): void { * `refreshMs`) per session. */ export async function touchSeen( - $: EngineInterface, + io: Io, sessionId: string, now: number, refreshMs = SEEN_REFRESH_MS @@ -256,10 +254,10 @@ export async function touchSeen( if (renewed !== undefined && renewed <= now && now - renewed < refreshMs) { return; } - const cwd = await $.session.cwd().catch(() => ""); - const repo = await $.session.repo().catch(() => null); + const cwd = await io.session.cwd().catch(() => ""); + const repo = await io.session.repo().catch(() => null); await oneAtATime(async () => { - const stored = await $.store.get(INDEX_KEY); + const stored = await io.store.get(INDEX_KEY); if (stored !== undefined && !isRecord(stored)) return; const index = stored ?? {}; const row = index[sessionId]; @@ -268,7 +266,7 @@ export async function touchSeen( renewedAt.set(sessionId, row.lastSeen); return; } - await $.store.set(INDEX_KEY, { + await io.store.set(INDEX_KEY, { ...index, [sessionId]: { ...row, lastSeen: now }, }); @@ -278,7 +276,7 @@ export async function touchSeen( repo: repo?.root ?? null, lastSeen: now, }; - await $.store.set(INDEX_KEY, { ...index, [sessionId]: fresh }); + await io.store.set(INDEX_KEY, { ...index, [sessionId]: fresh }); } renewedAt.set(sessionId, now); }); @@ -289,13 +287,13 @@ export async function touchSeen( * the index first, so they age out like any other. */ export async function adoptRows( - $: EngineInterface, + io: Io, sessionIds: readonly string[], now: number ): Promise { if (sessionIds.length === 0) return; await oneAtATime(async () => { - const stored = await $.store.get(INDEX_KEY); + const stored = await io.store.get(INDEX_KEY); if (stored !== undefined && !isRecord(stored)) return; const index = { ...(stored ?? {}) }; let isChanged = false; @@ -304,7 +302,7 @@ export async function adoptRows( index[id] = { cwd: "", repo: null, lastSeen: now }; isChanged = true; } - if (isChanged) await $.store.set(INDEX_KEY, index); + if (isChanged) await io.store.set(INDEX_KEY, index); }); } @@ -313,13 +311,13 @@ export async function adoptRows( * still not seen since `before`: one seen meanwhile stays. */ export async function dropFromIndex( - $: EngineInterface, + io: Io, sessionIds: readonly string[], before: number ): Promise { if (sessionIds.length === 0) return; await oneAtATime(async () => { - const stored = await $.store.get(INDEX_KEY); + const stored = await io.store.get(INDEX_KEY); if (!isRecord(stored)) return; const kept = { ...stored }; for (const id of sessionIds) { @@ -332,7 +330,7 @@ export async function dropFromIndex( delete kept[id]; } } - await $.store.set(INDEX_KEY, kept); + await io.store.set(INDEX_KEY, kept); }); } @@ -348,18 +346,18 @@ let seenTimer: Timer | undefined; * enough that its row is never older than half of `days`. A later * session.start in this module replaces the timer. */ -export function keepSeen($: EngineInterface, days: number): void { +export function keepSeen(io: Io, days: number): void { seenTimer?.cancel(); seenTimer = undefined; if (days === 0) return; const every = Math.min(SEEN_TIMER_MS, (days * 24 * 60 * 60 * 1000) / 4); - seenTimer = $.clock.every(every, () => { + seenTimer = io.clock.every(every, () => { (async () => { // The session it is now: a /clear or /resume may have moved it. - const id = await $.session.id(); - await touchSeen($, id, await $.clock.now(), every); + const id = await io.session.id(); + await touchSeen(io, id, await io.clock.now(), every); })().catch((error: unknown) => { - $.ui.log(`sessionpad: could not renew the session: ${String(error)}`, { + io.ui.log(`sessionpad: could not renew the session: ${String(error)}`, { to: "debug", }); }); diff --git a/sessionpad/src/summary.ts b/sessionpad/src/summary.ts index 1014268..2f1d00c 100644 --- a/sessionpad/src/summary.ts +++ b/sessionpad/src/summary.ts @@ -3,8 +3,9 @@ // names of the files written, on the person's own plan or key; nothing else // leaves the machine. -import type { EngineInterface, ModelUsage } from "claude-code"; +import type { ModelUsage } from "claude-code"; +import type { Io } from "./io"; import type { TurnEntry } from "../types"; import { cleanSummary } from "./timeline"; @@ -67,13 +68,13 @@ export type SummaryReply = { line: string | null; usage: ModelUsage | null }; /** Asks the model for a turn's line. */ export async function modelSummary( - $: EngineInterface, + io: Io, model: string, entry: TurnEntry, answer: string ): Promise { try { - const reply = await $.model.complete({ + const reply = await io.model.complete({ model, system: SUMMARY_SYSTEM, prompt: summaryPrompt(entry, answer), diff --git a/sessionpad/src/timeline.ts b/sessionpad/src/timeline.ts index 47e6420..cd8f07f 100644 --- a/sessionpad/src/timeline.ts +++ b/sessionpad/src/timeline.ts @@ -3,8 +3,7 @@ // shared $.store, which holds 4 MiB for every session together. Each session // writes only its own file, and this module's writes run one at a time. -import type { EngineInterface } from "claude-code"; - +import type { Io } from "./io"; import type { MarkEntry, TimelineEntry, TurnEntry, TurnTokens } from "../types"; import { oldOpening } from "./origin"; import { oneAtATime } from "./store"; @@ -356,21 +355,21 @@ export const fileName = (sessionId: string): string => * config folder (`CLAUDE_CONFIG_DIR`, else `~/.claude`), or null when no home * folder is known. */ -export async function dataDir($: EngineInterface): Promise { - const config = await $.env.get("CLAUDE_CONFIG_DIR"); +export async function dataDir(io: Io): Promise { + const config = await io.env.configDir(); if (config !== undefined && config !== "") { return `${config.replace(/[\\/]+$/, "")}/sessionpad`; } - const home = (await $.env.get("HOME")) || (await $.env.get("USERPROFILE")); + const home = (await io.env.home()) || (await io.env.userProfile()); if (home === undefined || home === "") return null; return `${home.replace(/[\\/]+$/, "")}/.claude/sessionpad`; } export async function timelinePath( - $: EngineInterface, + io: Io, sessionId: string ): Promise { - const dir = await dataDir($); + const dir = await dataDir(io); return dir === null ? null : `${dir}/timeline/${fileName(sessionId)}.json`; } @@ -385,14 +384,14 @@ type FileRead = | { status: "corrupt"; text: string } | { status: "unreadable"; reason: string }; -async function readFile($: EngineInterface, path: string): Promise { +async function readFile(io: Io, path: string): Promise { let text: string; try { - if (!(await $.fs.exists(path))) return { status: "missing" }; - text = await $.fs.read(path); + if (!(await io.fs.exists(path))) return { status: "missing" }; + text = await io.fs.read(path); } catch (error) { // Deleted between the two calls: as good as never there. - const isGone = await $.fs.exists(path).then( + const isGone = await io.fs.exists(path).then( (exists) => !exists, () => false ); @@ -420,13 +419,13 @@ export type LoadedTimeline = { entries: TimelineEntry[]; problem?: string }; /** The session's timeline for showing; never rejects. */ export async function loadTimeline( - $: EngineInterface, + io: Io, sessionId: string ): Promise { try { - const path = await timelinePath($, sessionId); + const path = await timelinePath(io, sessionId); if (path === null) return { entries: [] }; - const read = await readFile($, path); + const read = await readFile(io, path); if (read.status === "read") return { entries: read.entries }; if (read.status === "unreadable") { return { entries: [], problem: `${path} could not be read` }; @@ -442,10 +441,10 @@ export async function loadTimeline( /** The session's whole timeline, oldest first; empty when there is none to read. */ export async function readTimeline( - $: EngineInterface, + io: Io, sessionId: string ): Promise { - return (await loadTimeline($, sessionId)).entries; + return (await loadTimeline(io, sessionId)).entries; } /** @@ -457,29 +456,29 @@ export async function readTimeline( * Resolves null when there is no folder to write in. */ export async function changeTimeline( - $: EngineInterface, + io: Io, sessionId: string, change: ( entries: TimelineEntry[] ) => TimelineEntry[] | Promise ): Promise { return oneAtATime(async () => { - const path = await timelinePath($, sessionId); + const path = await timelinePath(io, sessionId); if (path === null) return null; - const read = await readFile($, path); + const read = await readFile(io, path); if (read.status === "unreadable") { throw new Error(`the timeline file could not be read: ${read.reason}`); } const isPartial = read.status === "read" && !read.isWhole; if (read.status === "corrupt" || isPartial) { - await $.fs.write(`${path}.corrupt-${await $.clock.now()}`, read.text); + await io.fs.write(`${path}.corrupt-${await io.clock.now()}`, read.text); } const changed = fitEntries( await change(read.status === "read" ? read.entries : []) ); // Nothing to keep and no file yet: leave no empty file behind. if (read.status === "missing" && changed.length === 0) return changed; - await $.fs.write(path, timelineText(changed)); + await io.fs.write(path, timelineText(changed)); return changed; }); } @@ -492,21 +491,21 @@ export async function changeTimeline( * to send it the entry of a turn that ended just before and isn't written yet. */ export async function carryTimeline( - $: EngineInterface, + io: Io, fromId: string, toId: string, how: "clear" | "branch" ): Promise { - const at = await $.clock.now(); + const at = await io.clock.now(); let isTaken = false; - await changeTimeline($, toId, async (target) => { + await changeTimeline(io, toId, async (target) => { if (target.length > 0) return target; isTaken = true; if (how === "branch") { return [markEntry(at, `Branched from session \`${fromId}\`.`)]; } // Read here, in the queue, so a write to the source just before is in it. - const source = await readTimeline($, fromId); + const source = await readTimeline(io, fromId); if (source.length === 0) return []; return [...source, markEntry(at, "The conversation was cleared.")]; }); diff --git a/sessionpad/src/turns.ts b/sessionpad/src/turns.ts index c150b0a..891373b 100644 --- a/sessionpad/src/turns.ts +++ b/sessionpad/src/turns.ts @@ -3,8 +3,9 @@ // model's summary line. The slow parts (git, the model) run after the turn, // on a timer, so the next prompt never waits for them. -import type { EngineInterface, ToolCallResult, TurnUsage } from "claude-code"; +import type { ToolCallResult, TurnUsage } from "claude-code"; +import type { Io } from "./io"; import type { TimelineEntry, TurnTokens } from "../types"; import { gitPlace } from "./git"; import { showTimeline, showUsage } from "./state"; @@ -80,19 +81,19 @@ export function followersOf( return followers; } -function debug($: EngineInterface, text: string): void { - $.ui.log(`sessionpad: ${text}`, { to: "debug" }); +function debug(io: Io, text: string): void { + io.ui.log(`sessionpad: ${text}`, { to: "debug" }); } /** Shows the entries, if the session they belong to is still the one open. */ async function showIfOpen( - $: EngineInterface, + io: Io, sessionId: string, entries: TimelineEntry[] | null ): Promise { if (entries === null) return; - const open = await $.session.id().catch(() => undefined); - if (open === sessionId) await showTimeline($, entries); + const open = await io.session.id().catch(() => undefined); + if (open === sessionId) await showTimeline(io, entries); } /** @@ -114,12 +115,12 @@ async function showIfOpen( * reads as a timeline that isn't being kept. */ export async function finishTurn( - $: EngineInterface, + io: Io, turn: FinishedTurn, settings: TimelineSettings, followers: (sessionId: string) => readonly string[] = () => [] ): Promise { - const place = await gitPlace($); + const place = await gitPlace(io); const entry = turnEntry(turn, place.branch, place.worktree); const failures: unknown[] = []; const writeEach = async ( @@ -128,13 +129,13 @@ export async function finishTurn( for (const id of [turn.sessionId, ...followers(turn.sessionId)]) { let entries: TimelineEntry[] | null; try { - entries = await changeTimeline($, id, change); + entries = await changeTimeline(io, id, change); } catch (error) { failures.push(error); continue; } - await showIfOpen($, id, entries).catch((error: unknown) => - debug($, `the timeline was written but not shown: ${String(error)}`) + await showIfOpen(io, id, entries).catch((error: unknown) => + debug(io, `the timeline was written but not shown: ${String(error)}`) ); } }; @@ -142,7 +143,7 @@ export async function finishTurn( await writeEach((entries) => addEntry(entries, entry, settings.cap)); if (settings.summaryModel !== null && isWorthSummary(entry)) { const { line, usage } = await modelSummary( - $, + io, settings.summaryModel, entry, turn.answer @@ -152,9 +153,9 @@ export async function finishTurn( } if (usage !== null && isSpent(usage)) { try { - await showUsage($, await recordUsage($, usage, await $.clock.now())); + await showUsage(io, await recordUsage(io, usage, await io.clock.now())); } catch (error) { - debug($, `the summary's cost was not counted: ${String(error)}`); + debug(io, `the summary's cost was not counted: ${String(error)}`); } } } @@ -168,25 +169,25 @@ export async function finishTurn( * logged, and toasted once per session (`warned` holds the ones told). */ export function finishTurnLater( - $: EngineInterface, + io: Io, finished: FinishedTurn, settings: TimelineSettings, followers: (sessionId: string) => readonly string[], isChanged: boolean, warned: Set ): void { - $.clock.after(0, () => { - scheduleRefresh($, isChanged ? "changed" : "none"); + io.clock.after(0, () => { + scheduleRefresh(io, isChanged ? "changed" : "none"); // A session at work stays seen, however long it stays open. - touchSeen($, finished.sessionId, finished.at).catch(() => undefined); - finishTurn($, finished, settings, followers).catch((error: unknown) => { + touchSeen(io, finished.sessionId, finished.at).catch(() => undefined); + finishTurn(io, finished, settings, followers).catch((error: unknown) => { const why = String(error); - $.ui.log(`sessionpad: the turn was not recorded: ${why}`, { + io.ui.log(`sessionpad: the turn was not recorded: ${why}`, { to: "debug", }); if (warned.has(finished.sessionId)) return; warned.add(finished.sessionId); - $.ui.toast( + io.ui.toast( `sessionpad: turns in this session aren't being added to the timeline: ${why}` ); }); diff --git a/sessionpad/src/ui.tsx b/sessionpad/src/ui.tsx index 16533d3..d09a470 100644 --- a/sessionpad/src/ui.tsx +++ b/sessionpad/src/ui.tsx @@ -15,12 +15,7 @@ // does in its own label. A hover group's name was also held to 64 characters, // which a stored note id may run past. -import type { - EngineInterface, - RenderElement, - RenderInputOf, - RenderSurface, -} from "claude-code"; +import type { RenderElement, RenderInputOf, RenderSurface } from "claude-code"; import type { DeletedNote, @@ -43,6 +38,7 @@ import { keepNoteDraft, noteDraftText, } from "./drafts"; +import type { Io } from "./io"; import { describeExport, exportThisSession, formatTokens } from "./export"; import { formatClock, formatDay, formatDuration, formatTime } from "./format"; import { @@ -133,14 +129,14 @@ function cardLook(isTerminal: boolean, fill: keyof typeof FILL = "neutral") { * store rejects every write) instead of losing it without a word. */ async function guarded( - $: EngineInterface, + io: Io, what: string, work: () => Promise ): Promise { try { await work(); } catch (error) { - $.ui.toast(`sessionpad: ${what} failed: ${String(error)}`); + io.ui.toast(`sessionpad: ${what} failed: ${String(error)}`); } } @@ -148,18 +144,18 @@ async function guarded( * Adds the field's note and empties the field; says so only when it was cut * short or refused. A refused note stays in the field, to try again. */ -async function submitNote($: EngineInterface, value: string): Promise { - await guarded($, "adding the note", async () => { - const added = await addThisNote($, value, "user"); +async function submitNote(io: Io, value: string): Promise { + await guarded(io, "adding the note", async () => { + const added = await addThisNote(io, value, "user"); if (added.status === "added" || added.status === "blank") { // What was submitted is what the field holds, whatever onInput saw. keepNoteDraft(value); - emptyNoteField($); + emptyNoteField(io); } const isQuiet = added.status === "blank" || (added.status === "added" && !added.isShortened); - if (!isQuiet) $.ui.toast(describeAdd(added)); + if (!isQuiet) io.ui.toast(describeAdd(added)); }); } @@ -167,10 +163,10 @@ async function submitNote($: EngineInterface, value: string): Promise { * Deletes a note and keeps it for Undo. An open note has no Delete: its card * holds only the field, Save and Cancel. */ -async function pressDelete($: EngineInterface, note: Note): Promise { - await guarded($, "deleting the note", async () => { - const removed = await deleteThisNote($, note.id); - if (removed !== null) await keepDeleted($, removed); +async function pressDelete(io: Io, note: Note): Promise { + await guarded(io, "deleting the note", async () => { + const removed = await deleteThisNote(io, note.id); + if (removed !== null) await keepDeleted(io, removed); }); } @@ -178,28 +174,22 @@ async function pressDelete($: EngineInterface, note: Note): Promise { * Puts the deleted note back. A full pad keeps the Undo card up, waiting: * the next delete makes its room rather than taking the card over. */ -async function pressUndo( - $: EngineInterface, - deleted: DeletedNote -): Promise { - await guarded($, "restoring the note", async () => { - const result = await restoreDeletedNote($, deleted); +async function pressUndo(io: Io, deleted: DeletedNote): Promise { + await guarded(io, "restoring the note", async () => { + const result = await restoreDeletedNote(io, deleted); if (result === "full") { - await holdDeleted($, deleted.note.id); - $.ui.toast(describeRestore(result)); + await holdDeleted(io, deleted.note.id); + io.ui.toast(describeRestore(result)); return; } - await forgetDeleted($, deleted.note.id); + await forgetDeleted(io, deleted.note.id); }); } /** Takes the Undo card away; the deleted note is gone for good. */ -async function pressDismiss( - $: EngineInterface, - deleted: DeletedNote -): Promise { - await guarded($, "dismissing the deleted note", () => - forgetDeleted($, deleted.note.id) +async function pressDismiss(io: Io, deleted: DeletedNote): Promise { + await guarded(io, "dismissing the deleted note", () => + forgetDeleted(io, deleted.note.id) ); } @@ -207,21 +197,17 @@ async function pressDismiss( * Saves the open note's text and closes it; a blank save keeps it open, so * nothing typed is lost. */ -async function submitEdit( - $: EngineInterface, - id: string, - value: string -): Promise { - await guarded($, "saving the note", async () => { - const result = await editThisNote($, id, value); +async function submitEdit(io: Io, id: string, value: string): Promise { + await guarded(io, "saving the note", async () => { + const result = await editThisNote(io, id, value); if (result.status === "blank") { - $.ui.toast(describeEdit(result)); + io.ui.toast(describeEdit(result)); return; } - await closeEditing($, id); + await closeEditing(io, id); forgetEditDraft(id); if (result.status === "missing" || result.isShortened) { - $.ui.toast(describeEdit(result)); + io.ui.toast(describeEdit(result)); } }); } @@ -239,21 +225,18 @@ function whenText(at: number, now: number): string { return formatDay(at) === formatDay(now) ? formatClock(at) : formatTime(at); } -export async function renderPane( - $: EngineInterface, - e: PaneInput -): Promise { - const { Box, Text, Button } = $.ui.resolve(e); - const tab = await readTab($); +export async function renderPane(io: Io, e: PaneInput): Promise { + const { Box, Text, Button } = io.ui.resolve(e); + const tab = await readTab(io); // A digit presses a tab only while the pane holds the keyboard, which a // terminal gives it (ctrl+x tab); elsewhere the digits would only puzzle. const isTerminal = e.surface === "terminal"; const open = (id: Tab) => () => - guarded($, "switching tabs", async () => { - await showTab($, id); + guarded(io, "switching tabs", async () => { + await showTab(io, id); // Opening the tab measures what is more than 10 minutes old. - if (id === "workspace") scheduleRefresh($, "stale"); + if (id === "workspace") scheduleRefresh(io, "stale"); }); // On Desktop the open tab is the app's primary pill, black in light mode @@ -294,11 +277,11 @@ export async function renderPane( let body: RenderElement; if (tab === "notes") { - body = await renderNotesTab($, e); + body = await renderNotesTab(io, e); } else if (tab === "timeline") { - body = await renderTimelineTab($, e); + body = await renderTimelineTab(io, e); } else { - body = await renderWorkspaceTab($, e); + body = await renderWorkspaceTab(io, e); } return ( @@ -311,20 +294,17 @@ export async function renderPane( ); } -async function renderNotesTab( - $: EngineInterface, - e: PaneInput -): Promise { - const elements = $.ui.resolve(e); +async function renderNotesTab(io: Io, e: PaneInput): Promise { + const elements = io.ui.resolve(e); const { Box, Text, Button, Markdown } = elements; const Input = "Input" in elements ? elements.Input : undefined; const isTerminal = e.surface === "terminal"; - const headline = await readHeadline($); - const notes = await readNotes($); + const headline = await readHeadline(io); + const notes = await readNotes(io); const draft = noteDraftText(); - const editing = await readEditing($); - const deleted = await readDeleted($); - const now = await $.clock.now(); + const editing = await readEditing(io); + const deleted = await readDeleted(io); + const now = await io.clock.now(); // One note opens at a time: while one is, the others offer no Edit, so its // typed text can't be dropped by opening another. An open id whose note is // gone (deleted by another process) holds nothing open. @@ -378,12 +358,12 @@ async function renderNotesTab( key="undo-delete" label="Undo" variant="primary" - onPress={() => pressUndo($, gone)} + onPress={() => pressUndo(io, gone)} />