From c05e252d791f7059749295d9c4848b8b0613b939 Mon Sep 17 00:00:00 2001 From: Factor Date: Thu, 19 Nov 2026 11:06:12 +0100 Subject: [PATCH] chore: import ovis-composer into repo with baseline tests Co-Authored-By: Claude Sonnet 5.5 --- .gitignore | 2 + README.md | 31 + layouts/ovis-composer.json | 203 ++++ mod/ovis-composer/attachments.js | 171 ++++ mod/ovis-composer/catalog.js | 367 +++++++ mod/ovis-composer/delivery.js | 268 ++++++ mod/ovis-composer/jsconfig.json | 32 + mod/ovis-composer/main.js | 1522 ++++++++++++++++++++++++++++++ mod/ovis-composer/mod.json | 4 + mod/ovis-composer/state.js | 312 ++++++ mod/ovis-composer/storage.js | 359 +++++++ mod/ovis-composer/suggest.js | 189 ++++ mod/ovis-composer/view.js | 464 +++++++++ package.json | 1 + scripts/install.ps1 | 97 ++ tests/attachments.test.mjs | 38 + tests/delivery.test.mjs | 37 + tests/state.test.mjs | 60 ++ tests/storage.test.mjs | 58 ++ tests/suggest.test.mjs | 42 + tests/view.test.mjs | 55 ++ 21 files changed, 4312 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 layouts/ovis-composer.json create mode 100644 mod/ovis-composer/attachments.js create mode 100644 mod/ovis-composer/catalog.js create mode 100644 mod/ovis-composer/delivery.js create mode 100644 mod/ovis-composer/jsconfig.json create mode 100644 mod/ovis-composer/main.js create mode 100644 mod/ovis-composer/mod.json create mode 100644 mod/ovis-composer/state.js create mode 100644 mod/ovis-composer/storage.js create mode 100644 mod/ovis-composer/suggest.js create mode 100644 mod/ovis-composer/view.js create mode 100644 package.json create mode 100644 scripts/install.ps1 create mode 100644 tests/attachments.test.mjs create mode 100644 tests/delivery.test.mjs create mode 100644 tests/state.test.mjs create mode 100644 tests/storage.test.mjs create mode 100644 tests/suggest.test.mjs create mode 100644 tests/view.test.mjs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fb23925 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +mod/ovis-composer/gpui-kit.d.ts +node_modules/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..e22d96d --- /dev/null +++ b/README.md @@ -0,0 +1,31 @@ +# herdrMario + +Source of the `ovis-composer` Herdr mod (Unified Prompt Experience). + +- `mod/ovis-composer/` - the mod (ES modules, hot-reloaded by Herdr) +- `layouts/ovis-composer.json` - its layout +- `tests/` - Node tests for the pure modules (`npm test`) +- `docs/superpowers/` - spec and plan + +## Install + +```powershell +.\scripts\install.ps1 +``` + +Idempotent. An existing real `mods\ovis-composer` directory is renamed to +`ovis-composer.bak-20261119` (never deleted), a junction to `mod\ovis-composer` +takes its place, and the layout is copied to `~\.config\herdr-app\layouts\` +(existing file backed up once as `.bak-20261119`). + +Then switch: `herdr-app do layout.switch '{"name":"ovis-composer"}'` and check +with `herdr-app check \ovis-composer` and `herdr-app status`. + +## Uninstall + +```powershell +.\scripts\install.ps1 -Uninstall +``` + +Removes the junction (the repo files stay), restores the `.bak-20261119` mod +directory, layout and `keys.json` backups, and switches to the `main` layout. diff --git a/layouts/ovis-composer.json b/layouts/ovis-composer.json new file mode 100644 index 0000000..7e4fc7a --- /dev/null +++ b/layouts/ovis-composer.json @@ -0,0 +1,203 @@ +{ + "id": "root", + "cloned_from": { + "name": "main", + "version": "0.1.16" + }, + "type": "row", + "children": [ + { + "id": "sidebar", + "type": "column", + "children": [ + { + "id": "brand", + "type": "block", + "content": { + "mod": "workspace-chrome" + }, + "size": { + "px": 46 + }, + "window_drag": true + }, + { + "id": "sidebar-lists", + "type": "column", + "children": [ + { + "id": "spaces", + "type": "block", + "content": { + "mod": "spaces" + }, + "size": { + "weight": 1 + }, + "min": 90 + }, + { + "id": "agents", + "type": "block", + "content": { + "mod": "agents" + }, + "size": { + "weight": 1 + }, + "min": 90 + } + ] + }, + { + "id": "sidebar-footer", + "type": "block", + "content": { + "mod": "workspace-chrome", + "props": { + "footer": true + } + }, + "size": { + "px": 69 + } + } + ], + "size": { + "px": 268 + }, + "min": 44, + "max": 480, + "background": "chrome", + "resizable": false + }, + { + "id": "work", + "type": "column", + "children": [ + { + "id": "tabs", + "type": "block", + "content": { + "mod": "tabs" + }, + "size": { + "px": 42 + }, + "window_drag": true + }, + { + "id": "work-body", + "type": "row", + "children": [ + { + "id": "main", + "type": "block", + "content": { + "tab": "active", + "pane": { + "header": { + "content": { + "mod": "pane" + }, + "reveal": "always", + "height": 30, + "position": "top" + }, + "background": "background", + "border": { + "width": 1, + "color": "border" + }, + "focus": { + "width": 1, + "color": "accent" + }, + "radius": 10, + "gap": 8, + "lone": true + } + } + }, + { + "id": "panel", + "type": "column", + "children": [ + { + "id": "panel-body", + "type": "stack", + "children": [ + { + "id": "files", + "type": "block", + "content": { + "mod": "files" + } + }, + { + "id": "changes", + "type": "block", + "content": { + "mod": "changes" + } + } + ], + "active": "files" + } + ], + "size": { + "px": 368 + }, + "min": 280, + "max": 900, + "hidden": true + } + ], + "padding": 8, + "gap": 8 + }, + { + "id": "composer", + "type": "block", + "size": { + "px": 260 + }, + "focus": { + "border": { + "width": 1, + "color": "accent" + } + }, + "content": { + "mod": "ovis-composer" + } + }, + { + "id": "status", + "type": "block", + "content": { + "mod": "workspace-status" + }, + "size": { + "px": 28 + } + } + ], + "resizable": false + } + ], + "background": "canvas", + "terminal_padding": [ + 14, + 12 + ], + "divider": { + "width": 1, + "color": "border" + }, + "titlebar": "none", + "traffic_lights": [ + 12, + 16 + ] +} diff --git a/mod/ovis-composer/attachments.js b/mod/ovis-composer/attachments.js new file mode 100644 index 0000000..d3f519c --- /dev/null +++ b/mod/ovis-composer/attachments.js @@ -0,0 +1,171 @@ +// attachments.js - what may be attached to a message and how it is named. +// +// Pure: no gpui-kit, no gpui-base, no herdr. The limits and the mention rules +// live here, so the view (Task 8) has one place to ask and the tests +// (tests/attachments.test.mjs) can check them in plain Node. +// +// The mention holds the path on the AGENT's machine - the path `hc put` +// printed, the file as it landed there - and not the local path of the file +// that was dropped. For a remote machine the local path does not even exist. + +/** The limits the composer keeps to (the same numbers Ovis uses). */ +export const LIMITS = { + fileBytes: 32 * 1024 * 1024, + filesPerAction: 100, + messageChars: 20000, +}; + +/** The extensions that make a file an image (the design's §13.8 list). */ +const IMAGE_EXTENSIONS = new Set(["png", "jpg", "jpeg", "gif", "webp", "svg", "bmp"]); + +/** + * May this file be attached? + * + * Two rules: the file may not be bigger than 32 MiB, and the composer has to + * know what it is - a file it can carry or an image it can show a thumbnail + * of. A size that could not be measured is not a size that broke the limit, + * so it passes; a size that is not a number at all is a broken file. + * + * @param {{name?:string, path?:string, bytes?:number, kind?:string}} file + * @returns {{ok:true} | {ok:false, reason:string}} + */ +export function validate(file) { + if (!file || typeof file !== "object" || Array.isArray(file)) { + return { ok: false, reason: "Nieznany plik" }; + } + + const bytes = file.bytes; + if (bytes !== undefined && bytes !== null && !Number.isFinite(bytes)) { + return { ok: false, reason: "Nieznany rozmiar pliku" }; + } + if (Number.isFinite(bytes) && bytes > LIMITS.fileBytes) { + return { ok: false, reason: `Plik przekracza limit ${LIMITS.fileBytes / 1024 / 1024} MiB` }; + } + + const kind = kindOf(file); + if (kind !== "file" && kind !== "image") { + return { ok: false, reason: "Nieobsługiwany typ pliku" }; + } + + return { ok: true }; +} + +/** + * May this many files be attached in one go? + * + * One action - one drop, one send - carries at most 100 files, and every one + * of them has to pass on its own. + * + * @param {object[]} files + * @returns {{ok:true} | {ok:false, reason:string}} + */ +export function validateMany(files) { + const list = Array.isArray(files) ? files : []; + if (list.length > LIMITS.filesPerAction) { + return { ok: false, reason: `Za dużo plików (limit ${LIMITS.filesPerAction})` }; + } + + for (const file of list) { + const result = validate(file); + if (!result.ok) return result; + } + + return { ok: true }; +} + +/** + * The mention of an attachment - the path as the agent sees it. + * + * @param {string} path - the path on the agent's machine + * @returns {string} the mention, or nothing when there is no path + */ +export function mention(path) { + if (typeof path !== "string") return ""; + const clean = path.trim(); + return clean === "" ? "" : `@${clean}`; +} + +/** + * Take the mention of an attachment out of the text. + * + * Only the mention itself goes: a longer word that starts with the same + * characters (`@src/a.rsx`) is left alone. The space that separated the + * mention from the rest of the sentence goes with it, so the text does not + * keep a hole where the mention was. + * + * @param {string} text + * @param {string} path - the agent-side path, the one `mention` builds + * @returns {string} + */ +export function removeMention(text, path) { + if (typeof text !== "string") return ""; + const token = mention(path); + if (token === "" || text === "") return text; + + const kept = []; + let rest = text; + + for (;;) { + const at = rest.indexOf(token); + if (at < 0) break; + + const before = at === 0 ? "" : rest[at - 1]; + const after = rest[at + token.length] ?? ""; + const afterNext = rest[at + token.length + 1] ?? ""; + + if (!standalone(before, after, afterNext)) { + // a longer word that starts with the same characters - not our mention + kept.push(rest.slice(0, at + token.length)); + rest = rest.slice(at + token.length); + continue; + } + + kept.push(rest.slice(0, at)); + rest = rest.slice(at + token.length).replace(/^[ \t]+/, ""); + + // the mention ended the line - the space before it goes too + const tail = kept[kept.length - 1]; + if (/[ \t]$/.test(tail) && (rest === "" || rest.startsWith("\n"))) { + kept[kept.length - 1] = tail.replace(/[ \t]+$/, ""); + } + } + + kept.push(rest); + return kept.join(""); +} + +/** + * What the file is: what the caller says it is, or - when it says nothing - + * what the name says. Anything else than a file or an image is a type the + * composer cannot carry. + * + * @param {{name?:string, kind?:string}} file + * @returns {string} + */ +function kindOf(file) { + if (typeof file.kind === "string" && file.kind !== "") return file.kind.toLowerCase(); + + const name = typeof file.name === "string" ? file.name.toLowerCase() : ""; + const dot = name.lastIndexOf("."); + if (dot < 0) return "file"; + + const extension = name.slice(dot + 1); + return IMAGE_EXTENSIONS.has(extension) ? "image" : "file"; +} + +/** + * Is the mention a word of its own? A word may not be glued to the mention + * on either side, and a dot that continues the path (`@src/a.rs.txt`) makes + * it a different file. + * + * @param {string} before - the character in front of the mention + * @param {string} after - the character behind the mention + * @param {string} afterNext - the character behind that one + * @returns {boolean} + */ +function standalone(before, after, afterNext) { + if (before !== "" && /[\w/\\-]/.test(before)) return false; + if (after !== "" && /[\w/\\-]/.test(after)) return false; + if (after === "." && /[\w/\\-]/.test(afterNext)) return false; + return true; +} diff --git a/mod/ovis-composer/catalog.js b/mod/ovis-composer/catalog.js new file mode 100644 index 0000000..5580c71 --- /dev/null +++ b/mod/ovis-composer/catalog.js @@ -0,0 +1,367 @@ +// catalog.js - where the composer's suggestions come from. +// +// The workspace is reached only through the injected `exec` (the mod's +// `herdr.exec`), so this module runs in plain Node (tests/suggest.test.mjs) +// with a fake runner. It has no clock and no storage of its own: the view +// reads the person's snippets and passes them in, and it schedules the retry +// and the debounce with the numbers exported here. +// +// Three sources for `/` (the design's §5.3): the built-in commands of the +// agent, the project's own `.claude/commands/*.md` and +// `.claude/skills/*/SKILL.md`, and the person's saved snippets. One source +// for `@`: the files git tracks in the pane's folder. +// +// A read that fails is not an empty list: the failure is reported through +// `onReadError` and the menu keeps what it knows. A caller with no handler +// gets the failure itself - nobody may mistake a broken catalog for one +// with nothing to show. An empty list without a failure means the catalog +// was read and nothing fit. + +import { GROUP_BUILTIN, GROUP_PROJECT, GROUP_USER, rank } from "./suggest.js"; + +/** + * @typedef {import("./suggest.js").Item} Item + * + * @typedef {object} ExecResult + * @property {number} code + * @property {string} stdout + * @property {string} stderr + * + * @typedef {(command:string, args?:string[], options?:{cwd?:string}) => Promise} Exec + */ + +/** How long the composer waits before it asks the workspace again. */ +export const DEBOUNCE_MS = 150; + +/** The waits between the tries after a read failed: 2 s, 5 s, 15 s, 30 s. */ +export const RETRY_DELAYS = [2000, 5000, 15000, 30000]; + +/** The catalog could not be read - the person may keep typing. */ +export const READ_ERROR_MESSAGE = + "Nie udało się wczytać podpowiedzi. Pisz dalej, spróbujemy ponownie."; + +/** The catalog was read and nothing fit the needle. */ +export const NO_MATCH_MESSAGE = "Żadna komenda nie pasuje. Zmień słowo albo pisz dalej."; + +/** The same, for the files of an `@`. */ +export const NO_FILE_MATCH_MESSAGE = "Żaden plik nie pasuje. Zmień słowo albo pisz dalej."; + +/** The built-in commands of the agents, the small list the design names. */ +export const BUILTINS = { + "claude-code": [ + { key: "clear", desc: "Czyści historię rozmowy." }, + { key: "compact", desc: "Ścisza historię do podsumowania." }, + { key: "model", desc: "Wybiera model." }, + { key: "permissions", desc: "Ustawia uprawnienia narzędzi." }, + { key: "config", desc: "Otwiera ustawienia." }, + { key: "resume", desc: "Wznawia wcześniejszą sesję." }, + ], + codex: [ + { key: "model", desc: "Wybiera model." }, + { key: "approvals", desc: "Ustawia sposób zatwierdzania poleceń." }, + { key: "new", desc: "Zaczyna nową sesję." }, + { key: "resume", desc: "Wznawia wcześniejszą sesję." }, + ], +}; + +/** The same agent under the name the program's table gives it. */ +const AGENT_ALIASES = { claude: "claude-code" }; + +/** How many files the `@` menu shows at most. */ +const FILE_LIMIT = 20; + +/** The project's command files, as a shell finds them. */ +const LIST_SH = + 'for f in .claude/commands/*.md .claude/skills/*/SKILL.md; do [ -f "$f" ] && printf \'%s\\n\' "$f"; done; exit 0'; + +/** The same in PowerShell, for a machine without a POSIX shell. */ +const LIST_PS = + "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); " + + "@(Get-ChildItem -Path '.claude/commands/*.md','.claude/skills/*/SKILL.md' -File -ErrorAction SilentlyContinue) " + + "| ForEach-Object { Resolve-Path -Relative -LiteralPath $_.FullName }"; + +/** Reading one file with a POSIX shell. */ +const READ_SH = 'cat -- "$1"'; + +/** + * How long to wait before the next try after a read failed. The last wait + * repeats: the composer keeps trying every 30 s until the catalog is read. + * + * @param {number} attempt - 0 for the first wait + * @returns {number} milliseconds + */ +export function retryDelay(attempt) { + const index = Number.isFinite(attempt) ? Math.max(0, Math.floor(attempt)) : 0; + return RETRY_DELAYS[Math.min(index, RETRY_DELAYS.length - 1)]; +} + +/** + * The commands the `/` menu offers: the agent's built-ins, the project's own + * and the person's snippets. + * + * A source that cannot be read does not take the others with it: the menu + * shows what is known and the failure goes to `onReadError`, so the caller + * can tell a catalog it could not read from one with nothing to show. + * Without a handler the call rejects - the failure is never swallowed. + * + * @param {string} cwd - the folder of the pane + * @param {Exec} exec + * @param {{agent?:string, snippets?:object[], onReadError?:(error:Error) => void}} [options] + * @returns {Promise} + */ +export async function commands(cwd, exec, options = {}) { + const builtins = builtinItems(options.agent); + const snippets = snippetItems(options.snippets); + + let project = []; + try { + project = await projectItems(cwd, exec); + } catch (err) { + // Nobody to tell: the caller gets the failure instead of a list that + // looks empty - an empty list would say "nothing fits" and the caller + // would never try again. + if (options.onReadError) options.onReadError(err); + else throw err; + } + + return [...builtins, ...project, ...snippets]; +} + +/** + * The files the `@` menu offers: the ones git tracks in the pane's folder. + * + * The best matches come first and only then are they cut to twenty - a file + * that fits is never hidden behind twenty names that do not. Without a + * handler the call rejects when git fails. + * + * @param {string} cwd - the folder of the pane + * @param {Exec} exec + * @param {{needle?:string, limit?:number, onReadError?:(error:Error) => void}} [options] + * @returns {Promise} + */ +export async function files(cwd, exec, options = {}) { + const needle = String(options.needle ?? "").toLowerCase(); + const limit = Number.isFinite(options.limit) ? options.limit : FILE_LIMIT; + + let paths = []; + try { + paths = await gitFiles(cwd, exec); + } catch (err) { + // Nobody to tell: the caller gets the failure instead of an empty list + // that would say "nothing fits". + if (options.onReadError) options.onReadError(err); + else throw err; + } + + const items = paths.map((path) => ({ key: path, desc: "", insert: `@${path} ` })); + return rank(items, needle, { atLineStart: true }).slice(0, limit); +} + +/** The built-in commands of one agent - an agent we do not know has none. */ +function builtinItems(agent) { + const name = String(agent ?? ""); + const list = BUILTINS[name] ?? BUILTINS[AGENT_ALIASES[name]]; + if (!list) return []; + return list.map((item) => ({ + key: item.key, + desc: item.desc, + group: GROUP_BUILTIN, + insert: `/${item.key} `, + })); +} + +/** The commands the project has: its command files and its skills. */ +async function projectItems(cwd, exec) { + const { kind, paths } = await listProjectFiles(cwd, exec); + + const items = []; + for (const path of paths) { + const name = commandName(path); + if (!name) continue; + const text = await readFile(cwd, exec, path, kind); + if (text === null) continue; + items.push({ key: name, desc: describe(text), group: GROUP_PROJECT, insert: `/${name} ` }); + } + return items; +} + +/** The person's own snippets, as the view read them from the storage. */ +function snippetItems(snippets) { + if (!Array.isArray(snippets)) return []; + + const items = []; + for (const snippet of snippets) { + const key = String(snippet?.key ?? snippet?.name ?? "").trim(); + if (!key) continue; + const item = { + key, + desc: String(snippet?.desc ?? snippet?.description ?? ""), + group: GROUP_USER, + insert: `/${key} `, + }; + if (Number.isFinite(snippet?.uses)) item.uses = snippet.uses; + items.push(item); + } + return items; +} + +/** + * The project's command files. A POSIX shell is asked first - it is what a + * Linux or macOS machine has - and PowerShell after it, for a Windows machine + * without one. Neither is there: the catalog could not be read. + */ +async function listProjectFiles(cwd, exec) { + const viaShell = await tryList(exec, "sh", ["-c", LIST_SH, "catalog"], cwd, false); + if (viaShell) return { kind: "sh", paths: viaShell }; + + const viaPowerShell = await tryList( + exec, + "powershell", + ["-NoProfile", "-Command", LIST_PS], + cwd, + true, + ); + if (viaPowerShell) return { kind: "powershell", paths: viaPowerShell }; + + throw new Error("nie udało się wczytać katalogu projektu"); +} + +/** One listing, or `null` when the program is not there or it failed. */ +async function tryList(exec, command, args, cwd, windowsPaths) { + let result; + try { + result = await exec(command, args, { cwd }); + } catch { + return null; + } + if (!result || result.code !== 0) return null; + + return String(result.stdout ?? "") + .split("\n") + .map((line) => { + const path = line.trim(); + // PowerShell writes the separators of its own platform. + return windowsPaths ? path.replace(/\\/g, "/") : path; + }) + .filter(Boolean); +} + +/** + * One file of the project. The file may be gone between the listing and the + * read - then it is left out of the menu, not a reason to fail the catalog. + */ +async function readFile(cwd, exec, path, kind) { + const shells = kind === "sh" ? ["sh", "powershell"] : ["powershell", "sh"]; + + for (const shell of shells) { + const text = await tryRead(exec, shell, path, cwd); + if (text !== null) return text; + } + return null; +} + +/** One read, or `null` when the file is not there or cannot be read. */ +async function tryRead(exec, shell, path, cwd) { + const args = + shell === "sh" + ? ["-c", READ_SH, "catalog", path] + : ["-NoProfile", "-Command", readScript(path)]; + + let result; + try { + result = await exec(shell, args, { cwd }); + } catch { + return null; + } + if (!result || result.code !== 0) return null; + return String(result.stdout ?? ""); +} + +/** The PowerShell that reads one file; the path goes in as a literal. */ +function readScript(path) { + const literal = path.replace(/'/g, "''"); + return ( + "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); " + + // A file that is gone writes nothing and says nothing - the command + // would be a ghost. Without the encoding, Windows PowerShell reads a file + // without a BOM as the system's own code page, and the text comes out + // garbled. + `if (-not (Test-Path -LiteralPath '${literal}')) { exit 1 }; ` + + `Get-Content -Raw -Encoding utf8 -ErrorAction Stop -LiteralPath '${literal}'` + ); +} + +/** The name of the command a file holds: the file's name, or a skill's folder. */ +function commandName(path) { + const parts = path.split("/"); + const file = parts[parts.length - 1] ?? ""; + if (file.toLowerCase() === "skill.md") return parts[parts.length - 2] ?? ""; + return file.replace(/\.md$/i, ""); +} + +/** + * What the menu says about a command: the description of the front matter if + * there is one, else the first line that says something. + */ +function describe(markdown) { + const { fields, body } = frontmatter(String(markdown ?? "")); + if (fields.description) return clip(fields.description); + + const line = body + .split("\n") + .map((part) => part.trim()) + .find((part) => part !== "" && !part.startsWith("#")); + return clip(line ?? ""); +} + +/** The front matter of a markdown file, if it has one. */ +function frontmatter(text) { + const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text); + if (!match) return { fields: {}, body: text }; + + const fields = {}; + for (const line of match[1].split(/\r?\n/)) { + const field = /^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/.exec(line); + if (!field) continue; + fields[field[1].toLowerCase()] = field[2].trim().replace(/^["']|["']$/g, ""); + } + return { fields, body: text.slice(match[0].length) }; +} + +/** One line of text, no longer than the menu has room for. */ +function clip(text) { + const flat = String(text).replace(/\s+/g, " ").trim(); + if (flat.length <= 160) return flat; + return `${flat.slice(0, 160).replace(/\s\S*$/, "")}…`; +} + +/** + * The files git tracks in the folder. `-z` keeps the names as they are - git + * would otherwise write a name with a non-ASCII character in it quoted and + * escaped. + */ +async function gitFiles(cwd, exec) { + let result; + try { + result = await exec("git", ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], { + cwd, + }); + } catch (err) { + throw new Error(`nie udało się wczytać plików: ${err?.message ?? String(err)}`); + } + + if (!result || result.code !== 0) { + const stderr = String(result?.stderr ?? ""); + // A folder that is not a repository has no files to offer - that is an + // empty list, not a catalog that could not be read. + if (result?.code === 128 && /repo/i.test(stderr)) return []; + throw new Error( + `nie udało się wczytać plików: ${stderr.trim() || `git zakończone kodem ${result?.code}`}`, + ); + } + + return String(result.stdout ?? "") + .split("\0") + .map((path) => path.trim()) + .filter(Boolean); +} diff --git a/mod/ovis-composer/delivery.js b/mod/ovis-composer/delivery.js new file mode 100644 index 0000000..12816fc --- /dev/null +++ b/mod/ovis-composer/delivery.js @@ -0,0 +1,268 @@ +// delivery.js - sending, the queue and the turn gate. +// +// Plain ES module: no gpui-kit, no gpui-base, no herdr. The `hc` runner is +// injected (ctx.hc), so the whole delivery layer runs in plain Node +// (tests/delivery.test.mjs) without the app. +// +// The state model is the only writer: drain takes the state, moves the entry +// through `reduce` and hands a new state back. Nothing here changes a queue +// on its own. +// +// FACT (measured 2026-11-17 on herdr-core 0.1.16, `hc send --json`): +// `hc send` returns {"started":null,"status":null,"turn":0} and exits 0 - also +// for a plain shell with no agent, and also when it fails. Neither the exit +// code nor those fields say whether the agent got the message. Therefore: +// - ok:true means "the text was pasted and Enter pressed", NOT "the agent +// received it" - the UI says "Wysłano do terminala"; +// - the only failure is a non-zero exit code (its stderr becomes the notice); +// - every `--json` call checks the payload for an "error" field, because `hc` +// exits 0 even on error (measured: `hc wait t3 --json` for a missing +// terminal -> {"error":{"kind":"not_found",...}}, exit 0); +// - a payload that is not JSON at all is an unknown result, not a success; +// - delivery confirmation comes from the agent's status (agents() / +// `hc get --json`), never from the result of `hc send`; +// - exit codes are not mapped to meanings (9/11 - unproven, against the +// measurement); +// - the runner's `ok` flag carries no information the exit code does not +// already carry, so only the code and the payload are looked at. + +import { reduce } from "./state.js"; + +/** + * @typedef {"idle"|"working"|"blocked"|"done"} Status + * + * @typedef {object} HcResult + * @property {boolean} [ok] + * @property {number} code + * @property {string} stdout + * @property {string} stderr + * + * @typedef {object} Ctx + * @property {string} terminal + * @property {(args:string[]) => Promise} hc + * + * @typedef {object} DrainCtx + * @property {string} agent - whose queue this is; the queue is `state.queue[agent]` + * @property {string} terminal + * @property {(args:string[]) => Promise} hc + * @property {() => Status} status + * @property {() => boolean} gate + * @property {(state:object) => void} [onState] - the caller persists the state + * here; it is called after every transition, the first time while the entry + * is on the wire (before the send runs), so a crash during the send leaves + * "sending" on disk and not "queued" + * + * @typedef {{ok:true} | {ok:false, code:number, message:string}} Result + * @typedef {{kind:"send"|"queue"|"hold"}} Decision + * @typedef {{state:object, sent:boolean, id?:string, reason?:string}} DrainResult + * + * @typedef {object} QueueItem + * @property {string} id + * @property {string} text + * @property {"queued"|"sending"|"held"|"uncertain"} state + * @property {number} createdAt + * @property {string} [reason] + */ + +/** + * What to do with a message, given the agent's status. + * + * @param {Status|string} status + * @returns {Decision} + */ +export function decide(status) { + switch (status) { + case "idle": + case "done": + return { kind: "send" }; + case "working": + return { kind: "queue" }; + case "blocked": + return { kind: "hold" }; + default: + // A status we do not know (the core also reports "error") - wait for a + // known one instead of pasting into an agent that may not be there. + return { kind: "queue" }; + } +} + +/** + * The turn gate: the next message goes out only after a whole turn was seen - + * the agent was working and then came back to idle/done. Without that + * transition a message could land in the middle of the agent's turn. + * + * @param {Status|string} status + * @param {boolean} seenWorking + * @returns {boolean} + */ +export function gateAfter(status, seenWorking) { + if (!seenWorking) return false; + return status === "idle" || status === "done"; +} + +/** + * Paste the text into the terminal and press Enter. + * + * `ok:true` means the text was pasted - not that the agent read it. The only + * failure is a non-zero exit code, an "error" in the `--json` payload, or a + * payload that is not JSON at all. + * + * @param {Ctx} ctx + * @param {string} text + * @returns {Promise} + */ +export async function sendNow(ctx, text) { + const res = await callHc(ctx, ["send", ctx.terminal, text, "--json"]); + + if (res.failure) { + // The runner itself failed - there is no exit code to report. + return { ok: false, code: 0, message: res.failure }; + } + + if (res.code !== 0) { + return { + ok: false, + code: res.code, + message: res.stderr.trim() || `hc send zakończone kodem ${res.code}`, + }; + } + + const payload = parseJson(res.stdout); + if (!isPayload(payload)) { + // An unknown result is not a success: the text may or may not have gone + // out, so the caller must not treat this as delivered. + return { ok: false, code: res.code, message: "Nieznany wynik hc send" }; + } + + const failure = errorFrom(payload); + if (failure) return { ok: false, code: res.code, message: failure }; + + return { ok: true }; +} + +/** + * Send the first queued entry of the agent's queue, if the agent is ready and + * the gate is open. The queue is `state.queue[ctx.agent]` - the queues are per + * agent, and the status and the gate belong to that one agent. + * + * The state model is the only writer: the entry is claimed (`sending`) before + * we wait for `hc`, so it is on the wire while the send runs. On success the + * entry leaves the queue; on a failure it becomes `uncertain` - never + * `queued`, because `hc` exits 0 even on error and the text may have gone + * out. Nothing is repeated on its own. + * + * Every transition is handed to `ctx.onState` (the caller persists it) before + * the next step - the first time while the entry is on the wire, so a crash + * during the send leaves `sending` on disk and the restart turns it into + * `uncertain` instead of sending the message a second time. + * + * The gate is the caller's (ctx.gate()); the caller also resets it (sawWorking + * = false) after a successful send. + * + * @param {DrainCtx} ctx + * @param {object} state - the composer's state + * @returns {Promise} + */ +export async function drain(ctx, state) { + const agent = ctx.agent; + const items = state.queue?.[agent] ?? []; + const item = items.find(sendable); + if (!item) return { state, sent: false }; + + if (!ready(ctx.status())) return { state, sent: false }; + if (!ctx.gate()) return { state, sent: false }; + + // On the wire before we wait for `hc`: a restart in the middle must find the + // entry as `sending` and turn it into `uncertain`. + const claimed = reduce(state, { type: "claim", agent, id: item.id }); + ctx.onState?.(claimed); + + const result = await sendNow(ctx, item.text); + + if (result.ok) { + const sent = reduce(claimed, { type: "settle", agent, id: item.id, outcome: "sent" }); + ctx.onState?.(sent); + return { state: sent, sent: true, id: item.id }; + } + + const failed = reduce(claimed, { + type: "settle", + agent, + id: item.id, + outcome: "uncertain", + reason: result.message, + }); + ctx.onState?.(failed); + return { state: failed, sent: false, reason: result.message }; +} + +/** + * After a restart an entry that was on the wire is `uncertain`: the message + * may or may not have reached the agent, so it is never sent again on its own. + * + * @param {QueueItem[]} queue + * @returns {QueueItem[]} + */ +export function onRestart(queue) { + if (!Array.isArray(queue)) return []; + return queue.map((item) => (item.state === "sending" ? { ...item, state: "uncertain" } : item)); +} + +/** The agent can take the next message when it is not working and not blocked. */ +function ready(status) { + // "done" counts as ready: the core reports "done" for a turn that finished + // unseen, and it turns into "idle" only once somebody looks at it + // (herdr-app src/model.rs:596-604). A queue that waited for "idle" would + // never drain for an agent nobody watches. + return status === "idle" || status === "done"; +} + +/** Only an entry that waits in the queue may go out. */ +function sendable(item) { + return item?.state === "queued"; +} + +/** Run `hc` and normalize what comes back. */ +async function callHc(ctx, args) { + try { + const res = await ctx.hc(args); + return { + code: Number.isFinite(res?.code) ? res.code : 0, + stdout: typeof res?.stdout === "string" ? res.stdout : "", + stderr: typeof res?.stderr === "string" ? res.stderr : "", + failure: null, + }; + } catch (err) { + return { + code: 0, + stdout: "", + stderr: "", + failure: err?.message ?? String(err), + }; + } +} + +/** The "error" of a `--json` payload, if it carries one. */ +function errorFrom(payload) { + if (!payload.error) return null; + + const err = payload.error; + if (typeof err === "string") return err; + if (typeof err.message === "string" && err.message) return err.message; + if (typeof err.kind === "string" && err.kind) return err.kind; + return JSON.stringify(err); +} + +/** A `--json` payload is an object - anything else is an unknown result. */ +function isPayload(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function parseJson(text) { + if (typeof text !== "string" || text.trim() === "") return null; + try { + return JSON.parse(text); + } catch { + return null; + } +} diff --git a/mod/ovis-composer/jsconfig.json b/mod/ovis-composer/jsconfig.json new file mode 100644 index 0000000..f131959 --- /dev/null +++ b/mod/ovis-composer/jsconfig.json @@ -0,0 +1,32 @@ +{ + "// why": [ + "Written once by gpui-shell, then yours: an existing jsconfig.json or", + "tsconfig.json is never replaced, and this file is not rewritten.", + "", + "`moduleResolution` is how a bare specifier is answered. Left to be", + "inferred it can still land on the resolution that never looks in", + "node_modules, and a Git dependency the runtime resolves fine is", + "underlined as a module the editor cannot find.", + "", + "`lib` decides which globals exist. The default hands a script the", + "browser's — a `console`, a `localStorage`, a `Window` this runtime does", + "not have — and their declarations collide with the ones gpui-kit.d.ts makes,", + "so the file describing the API is itself reported as the error.", + "", + "`strictNullChecks` is off, and this one is the runtime's shape rather than", + "a preference. A view assigns its state in `init`, which TypeScript cannot", + "see as definite assignment the way it sees a constructor, so every field", + "would read as possibly-undefined and every use would want a `?.` that", + "means nothing at run time. Turning it on would buy noise, not safety." + ], + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "moduleResolution": "bundler", + "lib": ["ES2022"], + "checkJs": true, + "strict": true, + "strictNullChecks": false, + "noEmit": true + } +} diff --git a/mod/ovis-composer/main.js b/mod/ovis-composer/main.js new file mode 100644 index 0000000..d7e5d15 --- /dev/null +++ b/mod/ovis-composer/main.js @@ -0,0 +1,1522 @@ +// main.js - the composer: the visible message bar under the terminal. +// +// The field, the queue above it, the suggestion menu, the attachments, the +// context strip and the agent chip. What needs no GPUI lives in view.js +// (tests/main.test.mjs); the state model is state.js, the sending is +// delivery.js, the suggestions are suggest.js and catalog.js, the limits are +// attachments.js and the persistence is storage.js. +// +// The composer talks to one agent at a time - the focused one. Everything that +// belongs to an agent (the draft, the queue, the attachments) is keyed by the +// agent's address, so switching agents never mixes two of them. +// +// The keyboard belongs to the composer: the terminal only shows. The field +// takes the keyboard back when it loses it, and the shortcuts that belong to +// the agent's own program (Ctrl+C, Esc) are passed on with `hc`. +// +// `hc send` does not confirm a delivery - it pastes the text and presses +// Enter. The composer says "Wysłano do terminala" and takes the confirmation +// from the agent's status. + +import { View, div } from "gpui-kit"; +import { v_flex, h_flex, TextareaState, Textarea } from "gpui-base"; +import { + agents as liveAgents, + panes as livePanes, + focused as liveFocused, + theme, + exec, + hc, + shared, + setShared, + notify, + nextCommand, +} from "herdr"; +import * as fs from "fs/promises"; + +import { createState, reduce } from "./state.js"; +import { decide, sendNow as sendToTerminal } from "./delivery.js"; +import { detect as detectTrigger, rank, merge, startsLine } from "./suggest.js"; +import * as catalog from "./catalog.js"; +import { LIMITS, validateMany, mention, removeMention } from "./attachments.js"; +import * as storage from "./storage.js"; +import { + agentKey, + agentName, + agentStatus, + applySuggestion, + closeGate, + createGate, + drainAll, + failedHookOutcome, + gatePasses, + groupItems, + guardedStore, + hcOk, + insertMentions, + insertedNewline, + isPlainEnter, + menuAction, + moveCaret, + openGate, + overLimit, + paneContext, + parseJson, + queueLabel, + shortPath, + statusText, + targetAgent, +} from "./view.js"; + +/** The placeholder of the field. */ +const PLACEHOLDER = "Napisz do agenta…"; + +/** How many rows the menu of the suggestions shows at most. */ +const MENU_LIMIT = 20; + +/** How much room the menu takes - the same with one row and with twenty. */ +const MENU_HEIGHT = 118; + +/** The key context of the composer - the bindings of the mod sit on it. */ +const CONTEXT = "ovis-composer"; + +export default class Composer extends View { + init(_props, cx) { + this.state = createState(); + this.store = guardedStore({ get: shared, set: setShared }); + + // Per agent: the turn gate, whether a drain is in flight, whether the + // core is already waiting for the agent, and whether the queue of that + // agent was read from the disk. + this.gates = new Map(); + this.draining = new Set(); + this.waiting = new Set(); + this.restored = new Set(); + + // The menu of suggestions: what it shows, which row is picked. + this.menu = null; + this.debounce = null; + this.retry = null; + this.retryAttempt = 0; + + // The text of the field and the text before the newline that Enter put in. + this.value = ""; + this.enterText = null; + this.enterCaret = 0; + this.currentKey = ""; + this.focusTerminal = null; + this.counter = 0; + this.closed = false; + + this.textarea = TextareaState.new({ value: "", placeholder: PLACEHOLDER, rows: 1 }); + this.textarea.set_auto_grow(1, 6); + this.textarea.set_soft_wrap(true); + this.textarea.on("change", (event, cx) => this.changed(cx)); + this.textarea.on("submit", (event, cx) => this.submitted(event, cx)); + this.textarea.on("focus", () => { + this.hasKeyboard = true; + }); + this.textarea.on("blur", (event, cx) => { + this.hasKeyboard = false; + // The composer does not grab the keyboard back here: the field may have + // lost it to another field of the app. It takes it back when the app's + // focus moves to a terminal (see watchFocus). + }); + this.handle = cx.focus_handle(); + + // The keys the field swallows: it binds Ctrl+C to "copy" and the arrows + // to the movement of the cursor, and it eats them before they reach the + // element. The composer takes them as actions of its own - the app hands + // every action named "." to the mod's nextCommand(). + // + // The bindings sit on the "Input" context - the context of a text field - + // so they only ever fire where a field has the keyboard. The composer's + // own actions are bound deeper than the field's own ones, so the field's + // actions would win and the composer would never hear of the key; the + // composer therefore gets the key first and the field gets what is left. + // + // What the composer does with the key depends on the keyboard: only the + // copy of the composer whose own field has the keyboard acts - the other + // copies (a composer in another pane) leave the key alone. + cx.bind_keys([ + { keystroke: "ctrl-c", action: "ovis-composer.interrupt", context: "Input" }, + { keystroke: "up", action: "ovis-composer.up", context: "Input" }, + { keystroke: "down", action: "ovis-composer.down", context: "Input" }, + { keystroke: "tab", action: "ovis-composer.accept", context: "Input" }, + ]); + + // The keyboard belongs to the composer: the field takes it, and takes it + // back when the terminal takes it (see reclaim). + this.textarea.focus(); + cx.timer.after(600, () => this.textarea.focus()); + + this.syncAgent(cx); + // The agent under the focus can change without the composer being + // touched - the sidebar, another pane. The draft that goes with it has to + // follow, so the composer watches who it talks to. + cx.timer.every(500, (cx) => { + this.syncAgent(cx); + this.watchFocus(cx); + }); + + cx.spawn(async (cx) => { + for (;;) { + const command = await nextCommand(); + if (command === "focus") this.textarea.focus(); + if (command === "interrupt") this.interruptKey(cx); + if (command === "up") this.arrow(-1, cx); + if (command === "down") { const before = this.menu; this.arrow(1, cx); this.notice(`dbg down kb=${this.hasKeyboard} index=${this.menu?.index} same=${before === this.menu}`, "error"); } + if (command === "accept") this.acceptFromKey(cx); + cx.notify(); + } + }); + } + + /** The copy is gone - it must not take the keyboard with it. */ + close(cx) { + this.closed = true; + } + + // --- the agent ----------------------------------------------------------- + + /** The agent the composer talks to. */ + target() { + return targetAgent(liveAgents(), liveFocused()); + } + + /** + * The composer follows the agent under the focus. + * + * The draft of the agent we leave goes back to the state, the draft of the + * agent we come to comes out of it, and the queue of that agent comes back + * from the disk. + */ + syncAgent(cx) { + const agent = this.target(); + const key = agent ? agentKey(agent) : ""; + if (key === this.currentKey) return; + + if (this.currentKey) { + this.state = reduce(this.state, { + type: "draft", + agent: this.currentKey, + text: this.textarea.value(), + }); + } + this.currentKey = key; + if (!key) return; + + this.restoreQueue(key); + + const draft = this.state.drafts[key] ?? ""; + if (draft !== this.textarea.value()) { + this.textarea.set_value(draft); + this.value = draft; + } + cx.notify(); + } + + /** The queue of an agent comes back from the disk; what was on the wire is uncertain. */ + restoreQueue(key) { + if (this.restored.has(key)) return; + this.restored.add(key); + + const items = storage.loadQueue(this.store, key); + if (items.length === 0) return; + + this.state = reduce(this.state, { type: "restore", agent: key, items }); + this.state = reduce(this.state, { type: "restart", agent: key }); + this.persistQueue(key); + } + + /** The turn gate of an agent. */ + gateFor(key) { + let gate = this.gates.get(key); + if (!gate) { + gate = createGate(); + this.gates.set(key, gate); + } + return gate; + } + + /** The status of an agent; the gate learns that a turn began. */ + statusOf(agent) { + const live = liveAgents().find((entry) => entry.address === agent.address); + const status = agentStatus(live ?? agent); + if (status === "working") this.gateFor(agentKey(agent)).sawWorking = true; + return status; + } + + // --- the field ----------------------------------------------------------- + + /** Where the cursor is in the field. */ + caret() { + try { + const range = this.textarea.selected_range(); + return Number.isInteger(range?.end) ? range.end : 0; + } catch { + return 0; + } + } + + /** The field changed: the draft follows and the menu looks at the new text. */ + changed(cx) { + const next = this.textarea.value(); + const previous = this.value; + this.value = next; + + // Enter puts a newline into the field before the composer sends it - the + // newline is not part of the message. + const inserted = insertedNewline(previous, next); + this.enterText = inserted ? previous : null; + this.enterCaret = inserted ? inserted.index : this.caret(); + + const agent = this.target(); + if (agent) { + this.state = reduce(this.state, { type: "draft", agent: agentKey(agent), text: next }); + } + + // The newline of the keyboard does not move the menu. + if (!inserted) this.updateSuggestions(agent, cx); + cx.notify(); + } + + /** Enter in the field: the message goes out, or the menu takes the key. */ + submitted(event, cx) { + // The newline that Enter put into the field is not part of the message - + // the text of the field as it was before it. + const text = this.enterText ?? this.value; + const caret = this.enterText !== null ? this.enterCaret : this.caret(); + const plain = isPlainEnter(event); + this.enterText = null; + + // Shift+Enter is a new line and the secondary Enter (the one an IME + // sends) is not a message either. + if (!plain) return; + + // The menu takes the key - but only when it has something to offer. + if (this.menu && (this.menu.items ?? []).length > 0) { + this.accept(cx, text, caret); + return; + } + this.submit(text, cx); + } + + /** The keyboard of the composer. */ + key(event, cx) { + const menu = this.menu; + + if (menu) { + // The arrows and Tab come as actions of the mod (the field swallows + // them); this is the way in when they do arrive. + if (event.key === "down" || event.key === "arrowdown") { + this.arrow(1, cx); + cx.stop_propagation(); + return; + } + if (event.key === "up" || event.key === "arrowup") { + this.arrow(-1, cx); + cx.stop_propagation(); + return; + } + if (event.key === "tab") { + this.acceptFromKey(cx); + cx.stop_propagation(); + return; + } + if (event.key === "escape") { + this.closeMenu(); + cx.stop_propagation(); + return cx.notify(); + } + } + + if (event.key === "escape") { + const agent = this.target(); + if (agent && this.value.trim() === "" && this.statusOf(agent) === "working") { + this.interrupt(agent, cx); + } + cx.stop_propagation(); + return; + } + + if (isControlC(event)) { + const agent = this.target(); + if (agent) this.passKey(agent, "ctrl+c", cx); + cx.stop_propagation(); + return; + } + } + + /** + * The menu moves one row up or down. + * + * The arrows come as actions of the mod: the field binds them to the + * movement of the cursor and eats them before they reach the element. The + * cursor goes back to where the menu was opened, so the text does not move + * under the person. + */ + /** + * The up and down arrows. + * + * With the menu open they move the menu; without it they move the cursor + * between the lines of the field - the field of this app version does not do + * that by itself. + */ + arrow(step, cx) { + if (!this.hasKeyboard) return; + if (menuAction(this.hasKeyboard, this.menu, step < 0 ? "up" : "down") === "menu") { + this.moveMenu(step, cx); + return; + } + this.moveCaret(step); + } + + /** The cursor goes one line up or down. */ + moveCaret(step) { + const caret = this.caret(); + const moved = moveCaret(this.value, caret, step); + if (moved === caret) return; + this.textarea.set_selected_range({ start: moved, end: moved }); + } + + moveMenu(step, cx) { + if (menuAction(this.hasKeyboard, this.menu, step < 0 ? "up" : "down") !== "menu") return; + const menu = this.menu; + const count = (menu.items ?? []).length; + menu.index = (menu.index + step + count) % count; + this.restoreCaret(menu.caret); + cx.notify(); + } + + /** The picked row goes into the field - the keyboard way (Tab). */ + acceptFromKey(cx) { + if (menuAction(this.hasKeyboard, this.menu, "tab") !== "accept") return; + this.accept(cx); + } + + /** + * The keyboard belongs to the composer: the terminal only shows. + * + * The composer takes the keyboard back only when the focus that left it went + * to a terminal. The app says which terminal has the focus, and a click in + * another field of the app does not change that - so that field keeps the + * keyboard it took. The composer follows the app's focus: it takes the + * keyboard back when the focus moves to a terminal. + */ + reclaim(cx) { + if (this.closed) return; + if (!this.target()) return; + + const focus = liveFocused(); + if (!focus || !focus.terminal) return; + + try { + this.textarea.focus(); + } catch { + // The copy is going away - there is nothing to focus any more. + } + } + + /** The app's focus moved - a terminal may have taken the keyboard. */ + watchFocus(cx) { + const focus = liveFocused(); + const terminal = focus?.terminal ?? null; + if (terminal === this.focusTerminal) return; + this.focusTerminal = terminal; + if (this.hasKeyboard) return; + this.reclaim(cx); + } + + /** The caret goes back where it was - the menu moves, the text does not. */ + restoreCaret(at) { + if (!Number.isInteger(at)) return; + try { + this.textarea.set_selected_range({ start: at, end: at }); + } catch { + // The field does not answer - the caret stays where it is. + } + } + + // --- sending ------------------------------------------------------------- + + /** The message goes out, or it waits in the queue. */ + submit(text, cx) { + const agent = this.target(); + if (!agent) { + this.notice("Composer nie ma do kogo pisać — brak agenta.", "error", cx); + return; + } + const body = text.trim(); + if (body === "") return; + + const over = overLimit(text); + if (over > 0) { + this.notice(`Limit ${LIMITS.messageChars} znaków · ${over} za dużo`, "error", cx); + return; + } + + const key = agentKey(agent); + const attached = this.state.attachments[key] ?? []; + const broken = attached.find((file) => file.state === "error"); + if (broken) { + // A file that did not make it to the agent is still in the way - the + // person removes it or fixes it first. + this.notice(`Plik ${broken.name} nie dotarł do agenta — usuń go albo wyślij go jeszcze raz.`, "error", cx); + return; + } + const files = attached.filter((file) => file.state === "ready"); + + // The field is free again - the message is on its way. + this.clearField(cx); + for (const file of files) { + this.state = reduce(this.state, { type: "removeAttachment", agent: key, id: file.id }); + } + + // The files go to the agent's machine first; the mention in the text + // points at the path the agent sees, not at the path on this machine. + cx.spawn(async (cx) => { + let message = body; + for (const file of files) { + const landed = await this.putFile(agent, file); + if (!landed) { + // The agent cannot see that file - the message does not talk about + // it, and the tile stays with the reason. + message = removeMention(message, file.path); + continue; + } + message = message.split(mention(file.path)).join(mention(landed)); + } + this.finish(agent, message, cx); + }); + } + + /** The field is empty again. */ + clearField(cx) { + this.textarea.set_value(""); + this.value = ""; + this.enterText = null; + this.closeMenu(); + cx.notify(); + } + + /** The message goes out now or waits in the queue - the agent's status decides. */ + finish(agent, message, cx) { + const key = agentKey(agent); + const decision = decide(this.statusOf(agent)); + + // A message that is already on the wire: the new one waits in the queue + // instead of vanishing. + if (decision.kind === "send" && !this.draining.has(key)) { + this.sendNow(agent, message, cx); + return; + } + + const held = decision.kind === "hold"; + const item = { + id: this.newId(), + text: message, + createdAt: Date.now(), + state: held ? "held" : "queued", + ...(held ? { reason: "Agent czeka na Ciebie" } : {}), + }; + this.state = reduce(this.state, { type: "queue", agent: key, item }); + this.persistQueue(key); + + if (held) { + this.notice("Agent czeka na Ciebie — wiadomość czeka na „Wyślij teraz”.", "error"); + } else { + this.notice("Wiadomość w kolejce — następna tura."); + this.watch(agent, cx); + } + cx.notify(); + } + + /** The message goes to the terminal now. */ + async sendNow(agent, message, cx) { + const key = agentKey(agent); + if (this.draining.has(key)) { + this.notice("Ta wiadomość jest już w locie.", "error", cx); + return; + } + this.draining.add(key); + + const id = this.newId(); + // The entry goes to the disk before it goes on the wire: a crash in the + // middle must not send the message a second time. + this.state = reduce(this.state, { + type: "queue", + agent: key, + item: { id, text: message, createdAt: Date.now() }, + }); + this.state = reduce(this.state, { type: "claim", agent: key, id }); + if (!this.claimed(key, id)) { + // The entry did not go on the wire - it must not be sent. + this.draining.delete(key); + return; + } + this.persistQueue(key); + + try { + const result = await sendToTerminal({ terminal: agent.address, hc }, message); + if (result.ok) { + this.state = reduce(this.state, { type: "settle", agent: key, id, outcome: "sent" }); + this.persistQueue(key); + this.gates.set(key, closeGate(this.gateFor(key))); + this.notice("Wysłano do terminala."); + } else { + this.state = reduce(this.state, { + type: "settle", + agent: key, + id, + outcome: "uncertain", + reason: result.message, + }); + this.persistQueue(key); + this.notice(result.message, "error"); + } + } finally { + this.draining.delete(key); + this.watchAgain(agent, cx); + cx.notify(); + } + } + + /** + * The queue is watched again. + * + * A message that waited for a send to finish would sit in the queue for + * ever: the watch that was waiting for the agent has already returned. The + * composer starts a new one - but only when the agent is working, so an idle + * agent does not spin the wait in a loop. + */ + watchAgain(agent, cx) { + const key = agentKey(agent); + const waiting = (this.state.queue[key] ?? []).some((item) => item.state === "queued"); + if (!waiting) return; + if (this.statusOf(agent) !== "working") return; + this.watch(agent, cx); + } + + /** Did the entry go on the wire? An entry that did not must not be sent. */ + claimed(key, id) { + const item = (this.state.queue[key] ?? []).find((entry) => entry.id === id); + return Boolean(item && item.state === "sending"); + } + + /** The core tells us when the agent stops working - then the queue may go out. */ + watch(agent, cx) { + const key = agentKey(agent); + if (this.waiting.has(key)) return; + this.waiting.add(key); + + cx.spawn(async (cx) => { + try { + const res = await hc(["wait", agent.address, "--json"]); + if (!hcOk(res)) { + // The core did not wait for anything - the queue stays where it is. + return; + } + } catch { + // The core is gone - the queue stays where it is. + return; + } finally { + this.waiting.delete(key); + } + await this.drainQueue(agent, cx); + }); + } + + /** + * The queue of an agent goes out when the agent is ready and the gate is + * open - one message after another, while the gate is open. + */ + async drainQueue(agent, cx) { + const key = agentKey(agent); + // One drain at a time per agent: the state it works on is immutable, so + // two of them would send the same message twice. The queue is watched + // anyway - the drain that is in flight will not empty it. + if (this.draining.has(key)) { + this.watchAgain(agent, cx); + return; + } + this.draining.add(key); + + let claimed = ""; + let sent = false; + try { + const result = await drainAll( + { + agent: key, + terminal: agent.address, + hc, + status: () => this.statusOf(agent), + gate: () => gatePasses(this.gateFor(key), this.statusOf(agent)), + onState: (next) => { + const items = next.queue?.[key] ?? []; + const sending = items.find((item) => item.state === "sending"); + if (sending) { + // The entry is on the wire: the state goes to the disk at once, + // so a crash now leaves "sending" behind and the restart turns + // it into "uncertain" instead of sending the message again. + const mine = (this.state.queue[key] ?? []).find((item) => item.id === sending.id); + if (mine && mine.state === "sending") return; + claimed = sending.id; + this.state = reduce(this.state, { type: "claim", agent: key, id: sending.id }); + this.persistQueue(key); + return; + } + // The entry's fate is known: it left the queue (sent) or it + // became uncertain (the send failed). + if (!claimed) return; + const left = !items.some((item) => item.id === claimed); + const failed = items.find((item) => item.id === claimed && item.state === "uncertain"); + if (left) { + this.state = reduce(this.state, { type: "settle", agent: key, id: claimed, outcome: "sent" }); + this.persistQueue(key); + sent = true; + } else if (failed) { + this.state = reduce(this.state, { + type: "settle", + agent: key, + id: claimed, + outcome: "uncertain", + ...(failed.reason ? { reason: failed.reason } : {}), + }); + this.persistQueue(key); + } + }, + }, + this.state, + ); + + if (result.sent > 0) { + this.gates.set(key, closeGate(this.gateFor(key))); + this.notice("Wysłano do terminala."); + } else if (claimed && !sent) { + this.notice("Wiadomość nie poszła do terminala.", "error"); + } + } catch (err) { + // A hook that fails after the message went out must not send it again: + // the entry left the queue, so it is sent. + const outcome = claimed ? failedHookOutcome(this.state.queue[key], claimed) : "uncertain"; + if (outcome === "sent") { + this.notice("Wysłano do terminala."); + } else { + if (claimed) { + this.state = reduce(this.state, { + type: "settle", + agent: key, + id: claimed, + outcome: "uncertain", + reason: errorText(err), + }); + this.persistQueue(key); + } + this.notice(errorText(err), "error"); + } + } finally { + this.draining.delete(key); + // The agent may have gone back to work with the queue not empty - the + // queue is watched again, so it empties itself. + const waiting = (this.state.queue[key] ?? []).some((item) => item.state === "queued"); + if (waiting && this.statusOf(agent) === "working") this.watch(agent, cx); + cx.notify(); + } + } + + /** The queued message goes out now, whatever the agent is doing. */ + async sendQueued(agent, id, cx) { + const key = agentKey(agent); + if (this.draining.has(key)) { + this.notice("Ta wiadomość jest już w locie.", "error", cx); + return; + } + + // A held entry goes back to the queue first, and the turn gate of the + // agent steps aside - this is a send outside a turn. + this.state = reduce(this.state, { type: "requeue", agent: key, id }); + this.gates.set(key, openGate(this.gateFor(key))); + + const item = (this.state.queue[key] ?? []).find((entry) => entry.id === id); + if (!item) { + // Nothing to send - the gate closes again right away. + this.gates.set(key, closeGate(this.gateFor(key))); + return; + } + + this.draining.add(key); + this.state = reduce(this.state, { type: "claim", agent: key, id }); + if (!this.claimed(key, id)) { + // The entry did not go on the wire - it must not be sent. + this.draining.delete(key); + this.gates.set(key, closeGate(this.gateFor(key))); + this.notice("Wiadomość nie poszła na drogę — nie została wysłana.", "error", cx); + return; + } + this.persistQueue(key); + + try { + const result = await sendToTerminal({ terminal: agent.address, hc }, item.text); + if (result.ok) { + this.state = reduce(this.state, { type: "settle", agent: key, id, outcome: "sent" }); + this.persistQueue(key); + // The gate closes again: the next message waits for the next turn. + this.gates.set(key, closeGate(this.gateFor(key))); + this.notice("Wysłano do terminala."); + } else { + this.state = reduce(this.state, { + type: "settle", + agent: key, + id, + outcome: "uncertain", + reason: result.message, + }); + this.persistQueue(key); + // The send outside a turn is over - the gate closes again. + this.gates.set(key, closeGate(this.gateFor(key))); + this.notice(result.message, "error"); + } + } finally { + this.draining.delete(key); + this.watchAgain(agent, cx); + cx.notify(); + } + } + + /** The queued message is not wanted any more. */ + discard(agent, id, cx) { + const key = agentKey(agent); + this.state = reduce(this.state, { type: "discard", agent: key, id }); + this.persistQueue(key); + // The notice about the queue is stale now. + if (!(this.state.queue[key] ?? []).length) { + this.state = reduce(this.state, { type: "notice", notice: null }); + } + cx.notify(); + } + + /** The file lands beside the agent's terminal; the path it got is the one the agent sees. */ + async putFile(agent, file) { + try { + const res = await hc(["put", agent.address, file.path, "--json"]); + const payload = parseJson(res.stdout); + if (res.code !== 0 || (payload && payload.error)) { + this.putFailed(agent, file, resultError(res, payload)); + return ""; + } + return landedPath(payload, res.stdout); + } catch (err) { + this.putFailed(agent, file, errorText(err)); + return ""; + } + } + + /** The file did not make it to the agent: the tile stays, with the reason. */ + putFailed(agent, file, reason) { + const key = agentKey(agent); + this.notice(`Nie udało się dostarczyć pliku ${file.name}: ${reason}`, "error"); + this.state = reduce(this.state, { + type: "attach", + agent: key, + file: { ...file, state: "error", error: reason }, + }); + } + + /** The stop key of the agent's program. */ + interrupt(agent, cx) { + cx.spawn(async (cx) => { + try { + const res = await hc(["interrupt", agent.address, "--json"]); + const payload = parseJson(res.stdout); + if (res.code !== 0 || (payload && payload.error)) { + this.notice(`Nie udało się zatrzymać agenta: ${resultError(res, payload)}`, "error"); + } + } catch (err) { + this.notice(`Nie udało się zatrzymać agenta: ${errorText(err)}`, "error"); + } + cx.notify(); + }); + } + + /** The shortcut of the agent's own program - the keyboard here is not the terminal's. */ + passKey(agent, keys, cx) { + cx.spawn(async (cx) => { + try { + const res = await hc(["keys", agent.address, keys, "--json"]); + if (!hcOk(res)) { + this.notice(`Klawisz nie dotarł do agenta: ${resultError(res, parseJson(res.stdout))}`, "error"); + } + } catch { + // The core is gone - the key goes nowhere. + } + cx.notify(); + }); + } + + /** + * Ctrl+C reaches the agent's program. + * + * The binding is on every field of the app (the composer cannot tell its + * own field from another one by the key alone), so the composer only acts + * when its own field holds the keyboard. + */ + interruptKey(cx) { + if (!this.hasKeyboard) return; + const agent = this.target(); + if (!agent) return; + this.passKey(agent, "ctrl+c", cx); + } + + // --- the suggestions ----------------------------------------------------- + + /** The caret sits in a `/` or `@` token - the menu looks at it. */ + updateSuggestions(agent, cx) { + const token = detectTrigger(this.value, this.caret()); + if (!token || !agent) { + this.closeMenu(); + return; + } + this.scheduleLoad(agent, token, cx); + } + + /** The menu is closed and the pending load with it. */ + closeMenu() { + if (this.debounce) { + this.debounce.cancel(); + this.debounce = null; + } + if (!this.menu) return; + this.menu = null; + } + + /** The catalog is read after a moment - the person is still typing. */ + scheduleLoad(agent, token, cx) { + if (this.debounce) { + this.debounce.cancel(); + this.debounce = null; + } + this.debounce = cx.timer.after(catalog.DEBOUNCE_MS, (cx) => { + this.debounce = null; + this.loadSuggestions(agent, token, cx); + }); + } + + /** The catalog of the suggestions, read from the workspace. */ + async loadSuggestions(agent, token, cx) { + const text = this.value; + const cwd = paneContext(livePanes(), agent.address).cwd ?? ""; + let failed = false; + const onReadError = () => { + failed = true; + this.scheduleRetry(agent, token, cx); + }; + + let items = []; + try { + if (token.trigger === "/") { + const raw = await catalog.commands(cwd, exec, { + agent: agentName(agent), + snippets: [], + onReadError, + }); + const usage = storage.loadUsage(this.store); + const withUses = raw.map((item) => ({ ...item, uses: usage[item.key] ?? 0 })); + items = + token.needle === "" + ? merge(groupItems(withUses)) + : rank(withUses, token.needle, { atLineStart: startsLine(text, token.start) }); + } else { + items = await catalog.files(cwd, exec, { needle: token.needle, onReadError }); + } + } catch (err) { + failed = true; + this.scheduleRetry(agent, token, cx); + } + + // The field moved on while the catalog was read - the next change asks + // again. + if (this.value !== text) return; + + this.menu = { ...token, caret: this.caret(), items, index: 0, error: failed }; + if (!failed) this.retryAttempt = 0; + cx.notify(); + } + + /** A read that failed is tried again: 2 s, 5 s, 15 s, 30 s. */ + scheduleRetry(agent, token, cx) { + if (this.retry) { + this.retry.cancel(); + this.retry = null; + } + const delay = catalog.retryDelay(this.retryAttempt); + this.retryAttempt += 1; + this.retry = cx.timer.after(delay, (cx) => { + this.retry = null; + this.loadSuggestions(agent, token, cx); + }); + } + + /** The picked suggestion goes into the field, at the place of the trigger. */ + accept(cx, text = this.value, caret = this.caret()) { + const menu = this.menu; + if (!menu) return; + const item = (menu.items ?? [])[menu.index]; + if (!item) return; + + const result = applySuggestion(text, caret, menu, item.insert ?? item.key); + + this.textarea.set_value(result.value); + this.value = result.value; + this.enterText = null; + this.menu = null; + this.restoreCaret(result.caret); + this.countUse(item.key); + cx.notify(); + } + + /** + * The command was used - the ranking breaks its ties with that number. + * + * The counters live in the shared store, so they are the same in every pane + * and they outlive the app. + */ + countUse(key) { + const name = String(key ?? "").replace(/^\//, ""); + if (!name) return; + try { + const usage = storage.loadUsage(this.store); + usage[name] = (usage[name] ?? 0) + 1; + storage.saveUsage(this.store, usage); + } catch { + // A counter that cannot be written is not worth a notice. + } + } + + // --- the attachments ----------------------------------------------------- + + /** Files were dropped on the composer. */ + drop(event, cx) { + const agent = this.target(); + if (!agent) return; + const paths = Array.isArray(event.paths) ? event.paths : []; + if (!paths.length) return; + + cx.spawn(async (cx) => { + const files = []; + for (const path of paths) { + files.push({ id: this.newId(), name: nameOf(path), path, bytes: await sizeOf(path) }); + } + + const check = validateMany(files); + if (!check.ok) { + this.notice(check.reason, "error"); + return cx.notify(); + } + + const key = agentKey(agent); + for (const file of files) { + this.state = reduce(this.state, { type: "attach", agent: key, file }); + } + + // The mention of the file goes into the message. + const result = insertMentions( + this.value, + files.map((file) => mention(file.path)), + ); + this.textarea.set_value(result.value); + this.value = result.value; + cx.notify(); + }); + } + + /** The file is not wanted any more - the mention goes with it. */ + removeFile(agent, id, cx) { + const key = agentKey(agent); + const file = (this.state.attachments[key] ?? []).find((entry) => entry.id === id); + if (!file) return; + + this.state = reduce(this.state, { type: "removeAttachment", agent: key, id }); + + const text = removeMention(this.value, file.path); + if (text !== this.value) { + this.textarea.set_value(text); + this.value = text; + } + cx.notify(); + } + + // --- the state on the disk ----------------------------------------------- + + /** The queue of an agent goes to the disk at once - a crash must not send a message twice. */ + persistQueue(key) { + try { + storage.saveQueue(this.store, key, this.state.queue[key] ?? []); + } catch (err) { + this.notice(`Nie udało się zapisać kolejki: ${errorText(err)}`, "error"); + } + } + + /** + * What the composer says under the card. + * + * The notice is part of the state, so the composer has to be redrawn for it + * to show up - the caller says when that happens. + */ + notice(text, level = "info", cx = null) { + this.state = reduce(this.state, { type: "notice", notice: { text, level } }); + if (level === "error") { + notify({ title: "Composer", body: text, level: "error" }); + } + cx?.notify(); + } + + /** An id of its own - the queue and the attachments count on it. */ + newId() { + this.counter += 1; + return `${Date.now().toString(36)}-${this.counter.toString(36)}`; + } + + // --- the view ------------------------------------------------------------ + + render(cx) { + const t = theme(); + const agent = this.target(); + const key = agent ? agentKey(agent) : ""; + const status = agent ? this.statusOf(agent) : "idle"; + + return v_flex() + .id("ovis-composer") + .track_focus(this.handle) + .key_context(CONTEXT) + .on_key_down((event, cx) => this.key(event, cx)) + .size_full() + .p(8) + .gap(6) + .bg(t.canvas) + .text_color(t.foreground) + .children( + [ + this.renderMenu(t), + this.renderQueue(t, agent, key), + this.renderNotice(t), + this.renderCard(t, agent, key, status), + this.renderContext(t, agent), + ].filter(Boolean), + ); + } + + /** The menu of the suggestions, above the card. */ + renderMenu(t) { + const menu = this.menu; + if (!menu) return null; + + const all = menu.items ?? []; + const items = all.slice(0, MENU_LIMIT); + const empty = menu.error + ? catalog.READ_ERROR_MESSAGE + : menu.trigger === "@" + ? catalog.NO_FILE_MATCH_MESSAGE + : catalog.NO_MATCH_MESSAGE; + + return v_flex() + .id("composer-menu") + .gap(1) + .p(6) + .rounded(10) + .border(1) + .border_color(t.border) + .bg(t.popover) + // The menu takes the same room whether it has one row or twenty - the + // card under it does not move while the person types. + .child( + v_flex() + .id("composer-menu-list") + .h(MENU_HEIGHT) + .overflow_y_scroll() + .gap(1) + .children( + [ + menu.error || all.length === 0 + ? div().px(6).py(5).text_size(11.5).text_color(menu.error ? t.blocked : t.dim).child(empty) + : null, + ...items.map((item, index) => this.renderMenuItem(t, item, index, menu)), + all.length > items.length + ? div().px(6).py(3).text_size(11).text_color(t.dim).child(`…i jeszcze ${all.length - items.length}`) + : null, + ].filter(Boolean), + ), + ); + } + + /** One row of the menu: the name of the item and what it says about itself. */ + renderMenuItem(t, item, index, menu) { + const on = index === menu.index; + const items = menu.items ?? []; + const group = typeof item.group === "string" ? item.group : ""; + const before = index > 0 ? items[index - 1] : null; + // The group is named once - at its first item. + const named = group !== "" && (!before || before.group !== group); + + return div() + .id(`menu-${index}`) + .px(6) + .py(3) + .rounded(6) + .cursor_pointer() + .when(on, (el) => el.bg(t.selected)) + .hover((s) => s.bg(t.hover)) + .on_click((event, cx) => this.acceptIndex(index, cx)) + .children( + [ + named ? div().text_size(10).text_color(t.dim).child(group) : null, + h_flex() + .gap(8) + .items_center() + .child(div().flex_none().text_size(12.5).text_color(t.foreground).child(item.key)) + .when( + item.desc, + (el) => el.child(div().flex_1().min_w(0).truncate().text_size(11).text_color(t.dim).child(item.desc)), + ), + ].filter(Boolean), + ); + } + + /** The picked row goes into the field. */ + acceptIndex(index, cx) { + if (!this.menu) return; + this.menu.index = index; + this.accept(cx); + } + + /** The queue of the agent, above the card. */ + renderQueue(t, agent, key) { + const items = this.state.queue[key] ?? []; + if (!items.length) return null; + + return v_flex() + .id("composer-queue") + .gap(4) + .children(items.map((item) => this.renderQueueRow(t, agent, item))); + } + + /** One row of the queue. */ + renderQueueRow(t, agent, item) { + const color = + item.state === "uncertain" + ? (t.unknown ?? t.dim) + : item.state === "held" + ? t.blocked + : t.accent; + + return h_flex() + .id(`queue-${item.id}`) + .gap(8) + .items_center() + .px(8) + .py(6) + .rounded(8) + .bg(t.surface) + .child(div().size(7).rounded(4).flex_none().bg(color)) + .child(div().flex_1().min_w(0).truncate().text_size(12).text_color(t.foreground).child(queueLabel(item))) + .when(item.reason, (el) => el.child(div().text_size(11).text_color(t.dim).truncate().child(item.reason))) + .child(this.renderQueueButtons(t, agent, item)); + } + + /** The buttons of a queue row. */ + renderQueueButtons(t, agent, item) { + if (item.state === "sending") { + return div().text_size(11).text_color(t.dim).child("wysyłanie…"); + } + + const buttons = []; + // An uncertain entry may have reached the agent - it is not sent again. + if (item.state !== "uncertain") { + buttons.push( + this.renderButton(t, "Wyślij teraz", `send-${item.id}`, (event, cx) => + this.sendQueued(agent, item.id, cx), + ), + ); + } + buttons.push( + this.renderButton(t, "Odrzuć", `drop-${item.id}`, (event, cx) => this.discard(agent, item.id, cx)), + ); + + return h_flex().gap(6).flex_none().children(buttons); + } + + /** A small button of the composer. */ + renderButton(t, text, id, action) { + return div() + .id(id) + .px(8) + .h(22) + .rounded(6) + .flex() + .items_center() + .text_size(11.5) + .text_color(t.muted) + .bg(t.chrome) + .cursor_pointer() + .hover((s) => s.bg(t.hover).text_color(t.foreground)) + .on_click(action) + .child(text); + } + + /** What the composer says under the card. */ + renderNotice(t) { + const notice = this.state.notice; + if (!notice) return null; + const error = notice.level === "error"; + + return div() + .id("composer-notice") + .px(10) + .py(6) + .rounded(8) + .bg(error ? t.blocked + "26" : t.chrome) + .text_size(11.5) + .text_color(error ? t.blocked : t.dim) + .child(notice.text); + } + + /** The card: the files, the field and the row of controls. */ + renderCard(t, agent, key, status) { + const files = this.state.attachments[key] ?? []; + const active = Boolean(agent); + const over = overLimit(this.value); + const stop = !this.value.trim() && status === "working"; + + return v_flex() + .id("composer-card") + .gap(8) + .p(10) + .rounded(12) + .border(1) + .border_color(active ? t.border : t.input) + .bg(t.raised) + .on_drop((event, cx) => this.drop(event, cx)) + .children( + [ + files.length ? this.renderFiles(t, agent) : null, + Textarea.new(this.textarea) + .w_full() + .px(10) + .py(8) + .rounded(8) + .bg(t.background) + .text_color(active ? t.foreground : t.dim) + .text_size(13), + h_flex() + .gap(8) + .items_center() + .child(this.renderChip(t, agent, status)) + .child(div().flex_1()) + .child(stop ? this.renderStop(t, agent) : this.renderSend(t, agent, over)), + ].filter(Boolean), + ); + } + + /** The tiles of the files that go with the message. */ + renderFiles(t, agent) { + const key = agentKey(agent); + const files = this.state.attachments[key] ?? []; + + return h_flex() + .id("composer-files") + .gap(6) + .flex_wrap() + .children( + files.map((file) => + h_flex() + .id(`file-${file.id}`) + .gap(6) + .px(8) + .h(24) + .rounded(8) + .bg(file.state === "error" ? t.blocked + "26" : t.chrome) + .items_center() + .child( + div() + .text_size(11.5) + .text_color(file.state === "error" ? t.blocked : t.foreground) + .truncate() + .child(file.name), + ) + .child( + div() + .id(`file-x-${file.id}`) + .px(4) + .text_size(12) + .text_color(t.dim) + .cursor_pointer() + .hover((s) => s.text_color(t.foreground)) + .on_click((event, cx) => this.removeFile(agent, file.id, cx)) + .child("✕"), + ), + ), + ); + } + + /** The chip of the agent: its program and what it is doing. */ + renderChip(t, agent, status) { + if (!agent) { + return div() + .px(8) + .h(24) + .rounded(12) + .bg(t.chrome) + .flex() + .items_center() + .text_size(11.5) + .text_color(t.dim) + .child("brak agenta"); + } + + const name = agent.program?.name ?? agentName(agent); + const color = t[status] ?? t.dim; + + return h_flex() + .px(8) + .h(24) + .rounded(12) + .gap(6) + .items_center() + .bg(t.chrome) + .child(div().size(7).rounded(4).flex_none().bg(color)) + .child(div().text_size(11.5).text_color(t.foreground).child(name)) + .child(div().text_size(11).text_color(color).child(statusText(status))); + } + + /** The button that sends the message. */ + renderSend(t, agent, over) { + const disabled = !agent || over > 0; + + return div() + .id("composer-send") + .size(32) + .rounded(999) + .bg(disabled ? t.chrome : t.solid) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .when(!disabled, (el) => el.hover((s) => s.opacity(0.88))) + .on_click((event, cx) => { + if (!disabled) this.submit(this.value, cx); + }) + .child( + div() + .text_size(13) + .font_semibold() + .text_color(disabled ? t.dim : t.solid_foreground) + .child("↵"), + ); + } + + /** The button that stops the agent. */ + renderStop(t, agent) { + return div() + .id("composer-stop") + .size(32) + .rounded(999) + .bg(t.foreground) + .flex() + .items_center() + .justify_center() + .cursor_pointer() + .hover((s) => s.opacity(0.85)) + .on_click((event, cx) => this.interrupt(agent, cx)) + .child(div().size(10).rounded(2).bg(t.background)); + } + + /** The strip under the card: where the agent works and how long the message is. */ + renderContext(t, agent) { + const context = agent ? paneContext(livePanes(), agent.address) : { cwd: null, branch: null }; + const over = overLimit(this.value); + + return h_flex() + .id("composer-context") + .gap(10) + .items_center() + .px(2) + .text_size(11) + .text_color(t.dim) + .child(div().truncate().child(context.cwd ? shortPath(context.cwd) : "")) + .when(context.branch, (el) => el.child(div().flex_none().child(context.branch))) + .child(div().flex_1()) + .child( + div() + .flex_none() + .text_color(over > 0 ? t.blocked : t.dim) + .child( + over > 0 + ? `Limit ${LIMITS.messageChars} znaków · ${over} za dużo` + : `${this.value.length} / ${LIMITS.messageChars}`, + ), + ); + } +} + +// --- helpers ---------------------------------------------------------------- + +/** + * Is this the Ctrl+C of the agent's own program? + * + * The keyboard here is not the terminal's: Ctrl+C has to be passed on with + * `hc keys`. GPUI spells the chord with a hyphen ("ctrl-c"); the key and the + * modifier are the surer way to recognise it. + */ +function isControlC(event) { + if (!event) return false; + if (event.keystroke === "ctrl-c" || event.keystroke === "ctrl+c") return true; + return event.key === "c" && event.modifiers?.control === true; +} + +/** The name of a file out of its path. */ +function nameOf(path) { + const parts = String(path ?? "").split(/[\\/]/); + return parts[parts.length - 1] || String(path ?? ""); +} + +/** The text of an error - an exception, a string or the error of a payload. */ +function errorText(value) { + if (value === null || value === undefined) return ""; + if (typeof value === "string") return value; + if (typeof value.message === "string" && value.message) return value.message; + if (typeof value.kind === "string" && value.kind) return value.kind; + return String(value); +} + +/** The text of a failed `hc` call - its stderr or the error of the payload. */ +function resultError(res, payload) { + const stderr = String(res?.stderr ?? "").trim(); + if (stderr) return stderr; + if (payload?.error) return errorText(payload.error); + return `hc zakończone kodem ${res?.code ?? 0}`; +} + +/** The path the file got on the agent's machine. */ +function landedPath(payload, stdout) { + if (payload) { + for (const key of ["path", "landed", "file", "target", "destination", "dst", "remote"]) { + if (typeof payload[key] === "string" && payload[key].trim() !== "") return payload[key].trim(); + } + } + const lines = String(stdout ?? "") + .trim() + .split(/\r?\n/) + .filter(Boolean); + return lines.length ? lines[lines.length - 1].trim() : ""; +} + +/** The size of a file, when it can be measured. */ +async function sizeOf(path) { + try { + const info = await fs.stat(path); + return Number.isFinite(info?.size) ? info.size : undefined; + } catch { + // A size that could not be measured is not a size that broke the limit. + return undefined; + } +} diff --git a/mod/ovis-composer/mod.json b/mod/ovis-composer/mod.json new file mode 100644 index 0000000..4beb480 --- /dev/null +++ b/mod/ovis-composer/mod.json @@ -0,0 +1,4 @@ +{ + "place": "none", + "focusable": true +} diff --git a/mod/ovis-composer/state.js b/mod/ovis-composer/state.js new file mode 100644 index 0000000..dfd3ae5 --- /dev/null +++ b/mod/ovis-composer/state.js @@ -0,0 +1,312 @@ +// state.js - the composer's state model. +// +// Pure: no GPUI, no herdr, no IO, no clock. `reduce` returns a new state and +// never mutates the one it was given, so the model can be tested in plain Node +// (tests/state.test.mjs) and reasoned about without a running app. +// +// Drafts, attachments and the queue are keyed by agent name ("claude-code", +// "codex"): each belongs to the agent it was written for, and switching agents +// must not lose any of them. + +import { onRestart } from "./delivery.js"; + +/** + * @typedef {"image"|"file"} AttachmentKind + * @typedef {"ready"|"error"} AttachmentState + * @typedef {object} Attachment + * @property {string} id + * @property {string} name + * @property {string} path + * @property {number} bytes + * @property {AttachmentKind} kind + * @property {AttachmentState} state + * @property {string} [error] + * + * @typedef {"queued"|"sending"|"held"|"uncertain"} QueueItemState + * @typedef {object} QueueItem + * @property {string} id + * @property {string} text + * @property {QueueItemState} state + * @property {number} createdAt + * @property {string} [reason] + * + * @typedef {object} Notice + * @property {string} text + * @property {string} [level] + * + * @typedef {object} MenuState + * @property {boolean} open + * @property {string|null} trigger + * @property {object[]} items + * @property {number} index + * + * @typedef {object} State + * @property {Record} drafts + * @property {Record} attachments + * @property {Record} queue + * @property {Notice|null} notice + * @property {MenuState|null} menu + * @property {null} conflict + */ + +/** @returns {State} */ +export function createState() { + return { + drafts: {}, + attachments: {}, + queue: {}, + notice: null, + menu: null, + conflict: null, + }; +} + +/** + * Is a message of this agent on the wire? The send state belongs to the agent, + * not to the composer: two agents may have one message each in flight, so a + * global flag would let one agent's settle clear the other's. + * + * @param {State} state + * @param {string} agent + * @returns {boolean} + */ +export function isSending(state, agent) { + return list(state.queue, agent).some((item) => item.state === "sending"); +} + +/** + * The one way the state changes. Never mutates `state`. + * + * @param {State} state + * @param {{type:string, agent?:string, id?:string, text?:string, file?:object, item?:object, items?:object[], notice?:object|null, outcome?:string, reason?:string}} action + * @returns {State} + */ +export function reduce(state, action) { + switch (action.type) { + case "draft": + return { ...state, drafts: { ...state.drafts, [action.agent]: action.text } }; + + case "send": + return { ...state, drafts: { ...state.drafts, [action.agent]: "" } }; + + case "attach": + return { + ...state, + attachments: { + ...state.attachments, + [action.agent]: [...list(state.attachments, action.agent), toAttachment(action.file)], + }, + }; + + case "removeAttachment": + return { + ...state, + attachments: { + ...state.attachments, + [action.agent]: list(state.attachments, action.agent).filter((a) => a.id !== action.id), + }, + }; + + case "queue": + return { + ...state, + queue: { + ...state.queue, + [action.agent]: [...list(state.queue, action.agent), toQueueItem(action.item)], + }, + }; + + case "restore": + return restore(state, action); + + case "discard": + return discard(state, action); + + case "requeue": + return requeue(state, action); + + case "claim": + return claim(state, action); + + case "settle": + return settle(state, action); + + case "restart": + return restart(state, action); + + case "notice": + return { ...state, notice: action.notice ?? null }; + + default: + return state; + } +} + +/** + * The queue of an agent comes back from the disk. + * + * The entries are put back as they were written - in the state they were in + * when the app went down. The `restart` action turns the ones that were on + * the wire into `uncertain`. + */ +function restore(state, action) { + const items = Array.isArray(action.items) ? action.items : []; + return { + ...state, + queue: { + ...state.queue, + [action.agent]: items.map((item) => ({ ...item })), + }, + }; +} + +/** + * The entry is dropped: the person does not want it any more. + * + * Nothing is sent and nothing is written to the terminal - the entry only + * leaves the queue. + */ +function discard(state, action) { + const items = list(state.queue, action.agent); + if (!items.some((item) => item.id === action.id)) return state; + return { + ...state, + queue: { + ...state.queue, + [action.agent]: items.filter((item) => item.id !== action.id), + }, + }; +} + +/** + * A held entry goes back to the queue. + * + * The hold said "the agent is waiting for you"; the person answered by asking + * for the message to go out anyway. The entry waits in the queue like any + * other and its reason goes with the hold. The turn gate of the agent is the + * view's business - it steps aside for a send outside a turn. + */ +function requeue(state, action) { + const items = list(state.queue, action.agent); + const item = items.find((entry) => entry.id === action.id); + if (!item || item.state !== "held") return state; + return { + ...state, + queue: { + ...state.queue, + [action.agent]: items.map((entry) => + entry.id === action.id ? withoutReason({ ...entry, state: "queued" }) : entry, + ), + }, + }; +} + +/** The entry without its reason - the reason belonged to the hold. */ +function withoutReason(item) { + const { reason, ...rest } = item; + return rest; +} + +/** + * The entry goes on the wire: a `queued` entry becomes `sending`, and the + * composer shows it as in flight. + * + * Only `queued` entries are claimed. A `held` entry waits for the user and an + * `uncertain` one may already have reached the agent - claiming either of + * them would send the same message twice, so they stay as they are. + */ +function claim(state, action) { + const items = list(state.queue, action.agent); + const item = items.find((entry) => entry.id === action.id); + if (!item || item.state !== "queued") return state; + return { + ...state, + queue: { + ...state.queue, + [action.agent]: items.map((entry) => + entry.id === action.id ? { ...entry, state: "sending" } : entry, + ), + }, + }; +} + +/** + * The entry's fate is known: `sent` drops it from the queue, `held` and + * `uncertain` keep it with a reason to show. + */ +function settle(state, action) { + const items = list(state.queue, action.agent); + if (!items.some((item) => item.id === action.id)) return state; + + if (action.outcome === "sent") { + return { + ...state, + queue: { ...state.queue, [action.agent]: items.filter((item) => item.id !== action.id) }, + }; + } + + if (action.outcome !== "held" && action.outcome !== "uncertain") return state; + + return { + ...state, + queue: { + ...state.queue, + [action.agent]: items.map((item) => + item.id === action.id + ? { ...item, state: action.outcome, ...(action.reason ? { reason: action.reason } : {}) } + : item, + ), + }, + }; +} + +/** + * The app restarted: an entry that was on the wire may or may not have reached + * the agent, so it becomes `uncertain` - it is never sent again on its own. + * Only the queue of that agent is touched. + */ +function restart(state, action) { + const items = list(state.queue, action.agent); + if (items.length === 0) return state; + return { + ...state, + queue: { + ...state.queue, + [action.agent]: onRestart(items), + }, + }; +} + +/** The list of one agent - an agent without entries yet has an empty list. */ +function list(map, agent) { + return map[agent] ?? []; +} + +/** The caller names the file; the model only fills in the defaults. */ +function toAttachment(file) { + return { + id: file.id, + name: file.name, + path: file.path, + bytes: file.bytes, + kind: file.kind ?? "file", + state: file.state ?? "ready", + ...(file.error !== undefined ? { error: file.error } : {}), + }; +} + +/** The caller names the entry and stamps it; the model defaults the rest. */ +function toQueueItem(item) { + if (!item || !Number.isFinite(item.createdAt)) { + // A missing timestamp would sort as epoch 0 and silently misorder the + // queue - the caller has to say when the entry was written. + throw new TypeError("queue entry needs a createdAt timestamp"); + } + return { + id: item.id, + text: item.text, + state: item.state ?? "queued", + createdAt: item.createdAt, + ...(item.reason !== undefined ? { reason: item.reason } : {}), + }; +} diff --git a/mod/ovis-composer/storage.js b/mod/ovis-composer/storage.js new file mode 100644 index 0000000..0ca0082 --- /dev/null +++ b/mod/ovis-composer/storage.js @@ -0,0 +1,359 @@ +// storage.js - what the composer keeps between runs. +// +// The store is injected: `store = { get(key): unknown, set(key, value): void }`. +// The view (Task 8) hands it `{ get: shared, set: setShared }` from the +// `herdr` module. `shared()` is app-wide and persisted in +// ~/.config/herdr-app/shared.json, so the history is the same in every pane +// and outlives the app. `localStorage` would be per mod copy - per pane - and +// would not outlive a restart. +// +// The queue has to outlive a crash in the middle of a send: Task 5's `drain` +// marks the entry `sending` BEFORE the send goes on the wire and hands the +// state to the caller through `ctx.onState`, so the caller writes it down at +// once. After a restart the composer loads the queue and turns `sending` into +// `uncertain` (the `restart` action of state.js) - the message may have +// reached the agent, so it is never sent again on its own. +// +// Reading never throws: a key that was never written, a value that is not a +// list, a store that is not there - the composer always gets a list to show. +// Writing rubbish does not throw either, but it does not write: the stored +// list stays as it was, so a bug in the caller cannot wipe the history. A +// store that cannot be written to at all throws - the queue on disk is what +// keeps a crash from sending a message twice, so that must not pass quietly. +// +// What comes back is checked: an entry that lost a field on the way to the +// disk is dropped, not handed to the view. A queue entry without a moment +// (`createdAt`) would make state.js throw, and one with a state it does not +// know would wait for ever - and a cut entry that came back would be sent +// again. + +/** + * @typedef {object} Store + * @property {(key:string) => unknown} get + * @property {(key:string, value:unknown) => unknown} set + * + * @typedef {object} HistoryEntry + * @property {string} id + * @property {string} text + * @property {number} at + * @property {string} agent + * @property {string} space + * @property {string} spaceName + * @property {string} tab + * @property {string} pane + * @property {string|null} machine + * @property {string[]} attachments + * @property {"sent"|"queued"|"failed"} outcome + * + * @typedef {object} FavoriteEntry + * @property {string} id + * @property {string} text + * @property {number} at + * @property {string} agent + * @property {"history"|"manual"} source + * + * @typedef {object} QueueEntry + * @property {string} id + * @property {string} text + * @property {"queued"|"sending"|"held"|"uncertain"} state + * @property {number} createdAt + * @property {string} [reason] + */ + +/** The states a queue entry may be in (the ones state.js knows). */ +const QUEUE_STATES = new Set(["queued", "sending", "held", "uncertain"]); + +/** The keys the composer writes into the shared store. */ +export const KEYS = { + history: "ovis-composer.history", + favorites: "ovis-composer.favorites", + usage: "ovis-composer.usage", + /** The queue is per agent: `ovis-composer.queue:`. */ + queue: "ovis-composer.queue", +}; + +/** How many entries the history keeps. */ +export const HISTORY_LIMIT = 500; + +/** How many entries the favourites keep. */ +export const FAVORITES_LIMIT = 100; + +/** + * The key of one agent's queue. + * + * @param {string} agent + * @returns {string} + */ +export function queueKey(agent) { + return `${KEYS.queue}:${agent}`; +} + +/** + * The history of the sent messages. + * + * The list is chronological - the oldest entry first, the newest last - and + * the oldest entries drop out when the list grows over the limit. + * + * @param {Store} store + * @returns {HistoryEntry[]} + */ +export function loadHistory(store) { + return readList(store, KEYS.history, HISTORY_LIMIT, isTextEntry); +} + +/** + * @param {Store} store + * @param {HistoryEntry[]} items + * @returns {void} + */ +export function saveHistory(store, items) { + writeList(store, KEYS.history, items, HISTORY_LIMIT, isTextEntry); +} + +/** + * The favourites - the texts the person marked, kept apart from the history + * so they outlive a cleared history. + * + * @param {Store} store + * @returns {FavoriteEntry[]} + */ +export function loadFavorites(store) { + return readList(store, KEYS.favorites, FAVORITES_LIMIT, isTextEntry); +} + +/** + * @param {Store} store + * @param {FavoriteEntry[]} items + * @returns {void} + */ +export function saveFavorites(store, items) { + writeList(store, KEYS.favorites, items, FAVORITES_LIMIT, isTextEntry); +} + +/** + * The queue of one agent - the messages that wait for their turn. + * + * The state is what it was when it was written: an entry that was on the wire + * (`sending`) is still `sending` here after a restart, and the composer + * turns it into `uncertain` (state.js, the `restart` action). The queue is + * never sent again on its own. + * + * @param {Store} store + * @param {string} agent + * @returns {QueueEntry[]} + */ +export function loadQueue(store, agent) { + return readList(store, queueKey(agent), 0, isQueueEntry); +} + +/** + * @param {Store} store + * @param {string} agent + * @param {QueueEntry[]} items + * @returns {void} + */ +export function saveQueue(store, agent, items) { + if (typeof agent !== "string" || agent === "") return; + writeList(store, queueKey(agent), items, 0, isQueueEntry); +} + +/** + * How often each command was used - the numbers the ranking of the + * suggestions breaks its ties with (`suggest.rank` reads `item.uses`). + * + * The key is the key of the catalog (`catalog.js`): the name of the command + * without the slash - "review", not "/review" - because that is the name + * `suggest.rank` compares. + * + * @param {Store} store + * @returns {Record} + */ +export function loadUsage(store) { + const raw = read(store, KEYS.usage); + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; + + const counts = {}; + for (const [key, value] of Object.entries(raw)) { + if (typeof value === "number" && Number.isFinite(value) && value >= 0) counts[key] = value; + } + return counts; +} + +/** + * @param {Store} store + * @param {Record} counts - the key of the catalog, without + * the slash: "review", not "/review" + * @returns {void} + */ +export function saveUsage(store, counts) { + if (!counts || typeof counts !== "object" || Array.isArray(counts)) return; + + const clean = {}; + for (const [key, value] of Object.entries(counts)) { + if (typeof value === "number" && Number.isFinite(value) && value >= 0) clean[key] = value; + } + // Counts that are not counts are rubbish - they do not wipe the counters + // that are there. An empty map on purpose still clears them. + if (Object.keys(counts).length > 0 && Object.keys(clean).length === 0) return; + + write(store, KEYS.usage, clean); +} + +/** + * Read a list, dropping what is not a list, what is not an entry and what the + * limit leaves out. The oldest entries drop out - the list is chronological. + * + * @param {Store} store + * @param {string} key + * @param {number} limit - 0 for a list without a limit + * @param {(entry:Record) => boolean} isValid + * @returns {any[]} + */ +function readList(store, key, limit, isValid) { + const list = toList(read(store, key), isValid); + if (!list) return []; + return limit > 0 ? list.slice(-limit) : list; +} + +/** + * Write a list, dropping what is not an entry and what the limit leaves out. + * + * @param {Store} store + * @param {string} key + * @param {unknown} items + * @param {number} limit - 0 for a list without a limit + * @param {(entry:Record) => boolean} isValid + * @returns {void} + */ +function writeList(store, key, items, limit, isValid) { + const source = listSource(items); + // Rubbish in - nothing is written, so the stored list stays as it was. + if (!source) return; + + const list = toList(source, isValid) ?? []; + // A list that lost every entry is rubbish, not an empty list - writing it + // would wipe what is there. + if (source.length > 0 && list.length === 0) return; + + write(store, key, limit > 0 ? list.slice(-limit) : list); +} + +/** + * The list in a value, or nothing when the value is not a list. The entries + * that are not entries of this kind are rubbish and go. + * + * The entries keep the shape the caller wrote - what a history entry and what + * a queue entry look like is the caller's business, not the store's. + * + * @param {unknown} value + * @param {(entry:Record) => boolean} isValid + * @returns {any[]|null} + */ +function toList(value, isValid) { + const source = listSource(value); + if (!source) return null; + + return source.filter((entry) => isEntry(entry, isValid)); +} + +/** + * Is this an entry of the kind the list holds? An entry that lost a field on + * the way to the disk does not come back - the view and the state model would + * have to guess what is missing. + * + * @param {unknown} entry + * @param {(entry:Record) => boolean} isValid + * @returns {boolean} + */ +function isEntry(entry, isValid) { + if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return false; + return isValid(/** @type {Record} */ (entry)); +} + +/** + * An entry the view can show - a history entry and a favourite have the same + * shape: a text and a moment. + * + * @param {Record} entry + * @returns {boolean} + */ +function isTextEntry(entry) { + return isText(entry.id) && isText(entry.text) && isTime(entry.at); +} + +/** + * A queue entry the state model can take. + * + * `createdAt` is what state.js insists on - without it the model throws - and + * the state has to be one it knows: an entry with a state of its own would + * wait for ever, and one that lost its state could be sent a second time. + * + * @param {Record} entry + * @returns {boolean} + */ +function isQueueEntry(entry) { + return ( + isText(entry.id) && + isText(entry.text) && + isTime(entry.createdAt) && + QUEUE_STATES.has(entry.state) + ); +} + +/** Is this a text? */ +function isText(value) { + return typeof value === "string"; +} + +/** Is this a moment in time (epoch ms)? */ +function isTime(value) { + return typeof value === "number" && Number.isFinite(value); +} + +/** + * The list a value holds: the value itself, or the `items` of the envelope + * the design wrote down (`{ items: [ … ] }`). + * + * @param {unknown} value + * @returns {unknown[]|null} + */ +function listSource(value) { + if (Array.isArray(value)) return value; + if (!value || typeof value !== "object") return null; + + const envelope = /** @type {{items?: unknown}} */ (value); + return Array.isArray(envelope.items) ? envelope.items : null; +} + +/** + * Read a value from the store. A store that fails gives nothing. + * + * @param {Store} store + * @param {string} key + * @returns {unknown} + */ +function read(store, key) { + try { + if (!store || typeof store.get !== "function") return null; + const value = store.get(key); + return value ?? null; + } catch { + return null; + } +} + +/** + * Write a value into the store. A store that cannot be written to throws - + * the queue on disk is what keeps a crash from sending a message twice. + * + * @param {Store} store + * @param {string} key + * @param {unknown} value + * @returns {void} + */ +function write(store, key, value) { + if (!store || typeof store.set !== "function") { + throw new TypeError(`brak magazynu dla klucza ${key}`); + } + store.set(key, value); +} diff --git a/mod/ovis-composer/suggest.js b/mod/ovis-composer/suggest.js new file mode 100644 index 0000000..d5a5251 --- /dev/null +++ b/mod/ovis-composer/suggest.js @@ -0,0 +1,189 @@ +// suggest.js - when the composer offers suggestions and which ones. +// +// Pure: no GPUI, no herdr, no IO, no clock. The module answers three +// questions - is the caret inside a `/` or `@` token (detect), which items fit +// what was typed (rank), and how the items sit in groups when nothing was +// typed (merge) - so it runs in plain Node (tests/suggest.test.mjs). +// +// The rules are the design's (§5): four levels of matching, ties broken by how +// often the item was used and then by its name. A `/` opens the menu only at +// the start of a line or after a space, so a path like /tmp/x is left alone; +// an `@` opens the file menu anywhere. + +/** + * @typedef {object} Item + * @property {string} key - the name the needle is matched against + * @property {string} desc - one line about the item + * @property {string} [group] - Wbudowane | Projekt | Użytkownik | Terminal + * @property {string} insert - the text put into the field ("/review ") + * @property {number} [uses] - how often the person picked the item + */ + +/** The built-in commands of the agent. */ +export const GROUP_BUILTIN = "Wbudowane"; +/** The commands of the project the pane sits in. */ +export const GROUP_PROJECT = "Projekt"; +/** The person's own saved snippets. */ +export const GROUP_USER = "Użytkownik"; +/** The commands the terminal itself understands. */ +export const GROUP_TERMINAL = "Terminal"; + +/** The groups, in the order the menu shows them. */ +export const GROUPS = [GROUP_BUILTIN, GROUP_PROJECT, GROUP_USER, GROUP_TERMINAL]; + +/** A name may start a word after one of these. */ +const BOUNDARY = new Set([":", "-", "_", ".", "/"]); + +/** A command name holds no space and no path separator - "/tmp/x" is a path. */ +const COMMAND_QUERY = /^[^\s/\\]*$/; + +/** A file name holds no space and is not empty. */ +const FILE_QUERY = /^\S+$/; + +/** + * The token at the caret: `null` when the caret is not inside one. + * + * A `/` counts only at the start of a line or after a space, and only when + * what follows can be a command name - a slash in the middle of a word (the + * second slash of /tmp/x) is a path, not a command. An `@` counts anywhere, + * but it needs at least one character of a name to complete. + * + * @param {string} text + * @param {number} caret - where the cursor is, between characters + * @returns {{trigger:"/"|"@", needle:string, start:number}|null} + */ +export function detect(text, caret) { + if (typeof text !== "string") return null; + if (!Number.isInteger(caret) || caret < 0 || caret > text.length) return null; + + const lineStart = text.lastIndexOf("\n", Math.max(0, caret - 1)) + 1; + + const slash = text.lastIndexOf("/", Math.max(0, caret - 1)); + if (slash >= lineStart && (slash === lineStart || /\s/.test(text[slash - 1] ?? ""))) { + const needle = text.slice(slash + 1, caret); + if (COMMAND_QUERY.test(needle)) return { trigger: "/", needle, start: slash }; + } + + const at = text.lastIndexOf("@", Math.max(0, caret - 1)); + if (at >= lineStart) { + const needle = text.slice(at + 1, caret); + if (FILE_QUERY.test(needle)) return { trigger: "@", needle, start: at }; + } + + return null; +} + +/** + * Does this token start a line? The fuzzy levels of the ranking are for the + * start of a line only - in the middle of one a name is matched by its + * beginning or by a word boundary, so the composer never rewrites a path. + * + * @param {string} text + * @param {number} index - where the trigger sits + * @returns {boolean} + */ +export function startsLine(text, index) { + if (typeof text !== "string") return true; + if (!Number.isInteger(index) || index <= 0) return true; + return text[index - 1] === "\n"; +} + +/** + * The items that fit the needle, best first. + * + * Four levels: the name begins with the needle (0), the needle sits at a + * word boundary of the name (1), the needle is somewhere in the name (2), + * the needle is in the description and is at least two characters long (3). + * Ties go to the item used more often, then to the name. + * + * The fuzzy levels (2 and 3) belong to a trigger at the start of a line - + * in the middle of one a name is matched by its beginning or by a word + * boundary, so the composer never rewrites a path. `atLineStart` says which + * of the two it is, and the caller has to say: without it the levels are off. + * + * @param {Item[]} items + * @param {string} needle + * @param {{atLineStart?:boolean}} [options] - `atLineStart: true` lets the + * fuzzy levels (2 and 3) in, for a trigger at the start of a line + * @returns {Item[]} + */ +export function rank(items, needle, options = {}) { + const atLineStart = options.atLineStart === true; + const query = typeof needle === "string" ? needle.toLowerCase() : ""; + const list = Array.isArray(items) ? items : []; + + const scored = []; + for (const item of list) { + if (!item) continue; + const level = levelOf(item, query); + if (level === null) continue; + if (!atLineStart && level > 1) continue; + scored.push({ item, level }); + } + + scored.sort((a, b) => { + if (a.level !== b.level) return a.level - b.level; + const used = (b.item.uses ?? 0) - (a.item.uses ?? 0); + if (used !== 0) return used; + return byName(a.item.key, b.item.key); + }); + + return scored.map((entry) => entry.item); +} + +/** + * The items of every group in one list, the groups in the order the design + * names them. Used when nothing was typed - with a needle the list is flat. + * + * @param {Record} groups + * @returns {Item[]} + */ +export function merge(groups) { + const source = groups && typeof groups === "object" ? groups : {}; + const names = [...GROUPS, ...Object.keys(source).filter((name) => !GROUPS.includes(name))]; + + const merged = []; + for (const name of names) { + const list = source[name]; + if (!Array.isArray(list)) continue; + for (const item of list) { + if (!item) continue; + merged.push({ ...item, group: item.group ?? name }); + } + } + return merged; +} + +/** + * How well an item matches the needle; lower is better, `null` is no match. + */ +function levelOf(item, query) { + const name = String(item.key ?? "").toLowerCase(); + const desc = String(item.desc ?? "").toLowerCase(); + + if (query === "") return 0; + if (name.startsWith(query)) return 0; + if (atBoundary(name, query)) return 1; + if (name.includes(query)) return 2; + if (query.length >= 2 && desc.includes(query)) return 3; + return null; +} + +/** Does the needle sit after a word boundary anywhere in the name? */ +function atBoundary(name, query) { + let at = name.indexOf(query); + while (at > 0) { + if (BOUNDARY.has(name[at - 1])) return true; + at = name.indexOf(query, at + 1); + } + return false; +} + +/** Names in alphabetical order, the case not counting. */ +function byName(a, b) { + const left = String(a ?? "").toLowerCase(); + const right = String(b ?? "").toLowerCase(); + if (left < right) return -1; + if (left > right) return 1; + return 0; +} diff --git a/mod/ovis-composer/view.js b/mod/ovis-composer/view.js new file mode 100644 index 0000000..9970b02 --- /dev/null +++ b/mod/ovis-composer/view.js @@ -0,0 +1,464 @@ +// view.js - the parts of the composer that need no GPUI and no app. +// +// Pure: no gpui-kit, no herdr, no IO, no clock. The view (main.js) asks its +// questions here, so that Node can check the answers (tests/main.test.mjs) +// without a running Herdr. +// +// The composer talks to one agent at a time - the focused one. Everything that +// belongs to an agent (the draft, the queue, the attachments) is keyed by the +// agent's address, so two Claude Code agents never share a draft. + +import { drain, gateAfter } from "./delivery.js"; +import { LIMITS } from "./attachments.js"; + +/** + * The agent the composer talks to. + * + * The focused terminal's agent first - that is the pane the person is + * looking at. An agent block that is shown (a layout that draws one agent) + * counts when no terminal has the focus. Without either there is nobody to + * write to, and the composer stays inactive. + * + * @param {object[]} agents - the live agents of the app + * @param {object|null} focused - the live focus of the window + * @returns {object|null} the agent, or null + */ +export function targetAgent(agents, focused) { + const list = Array.isArray(agents) ? agents : []; + if (!focused || typeof focused !== "object") return null; + + const byTerminal = list.find((agent) => agent && agent.address === focused.terminal); + if (byTerminal) return byTerminal; + + const byAgent = list.find((agent) => agent && agent.address === focused.agent); + return byAgent ?? null; +} + +/** + * The key a draft, a queue and a set of attachments belong to. + * + * The address of the agent, not the name of its program: two Claude Code + * agents are two agents, and their drafts and queues must not mix. + * + * @param {object} agent + * @returns {string} + */ +export function agentKey(agent) { + if (!agent || typeof agent !== "object") return ""; + const address = typeof agent.address === "string" ? agent.address.trim() : ""; + if (address) return address; + return agentName(agent); +} + +/** + * The name of the agent's program ("claude-code") - what the catalog of the + * built-in commands knows. + * + * @param {object} agent + * @returns {string} + */ +export function agentName(agent) { + if (!agent || typeof agent !== "object") return "default"; + const app = typeof agent.app === "string" ? agent.app.trim() : ""; + if (app) return app; + const key = typeof agent.program?.key === "string" ? agent.program.key.trim() : ""; + return key || "default"; +} + +/** + * The status of an agent: "idle" when there is none to be had. + * + * @param {object} agent + * @returns {string} + */ +export function agentStatus(agent) { + const status = agent && typeof agent.status === "string" ? agent.status.trim() : ""; + return status || "idle"; +} + +/** + * The turn gate of one agent. + * + * @returns {{sawWorking:boolean, open:boolean}} + */ +export function createGate() { + return { sawWorking: false, open: false }; +} + +/** + * May the next message go out? + * + * The gate opens after a whole turn was seen - the agent was working and came + * back to idle. A send outside a turn (the "Wyślij teraz" button) opens it + * outright, because it does not wait for a turn at all. + * + * @param {{sawWorking?:boolean, open?:boolean}} gate + * @param {string} status + * @returns {boolean} + */ +export function gatePasses(gate, status) { + if (!gate || typeof gate !== "object") return false; + if (gate.open === true) return true; + return gateAfter(status, gate.sawWorking === true); +} + +/** + * The gate of an agent with the turn step aside. + * + * @param {{sawWorking?:boolean, open?:boolean}} gate + * @returns {{sawWorking:boolean, open:boolean}} + */ +export function openGate(gate) { + return { ...(gate ?? createGate()), open: true }; +} + +/** + * The gate closes again: the next message waits for the next turn. + * + * @param {{sawWorking?:boolean, open?:boolean}} gate + * @returns {{sawWorking:boolean, open:boolean}} + */ +export function closeGate(gate) { + return { ...(gate ?? createGate()), sawWorking: false, open: false }; +} + +/** + * Is this the Enter that sends the message? + * + * Shift+Enter is a new line. The secondary Enter - the one an IME sends when + * it confirms a composition - does not send either (Ovis: "IME Enter ignored"). + * + * @param {{shift?:boolean, secondary?:boolean}} event + * @returns {boolean} + */ +export function isPlainEnter(event) { + if (!event) return false; + if (event.shift === true) return false; + if (event.secondary === true) return false; + return true; +} + +/** + * The caret one line up or down. + * + * The field of this app version (gpui-base in herdr-app 0.1.16) does not move + * the cursor up and down by itself, so the composer does it: the caret goes to + * the same column of the line above (or below) and never leaves the text. + * + * @param {string} text + * @param {number} caret + * @param {number} step - negative for up, positive for down + * @returns {number} the new caret + */ +export function moveCaret(text, caret, step) { + const source = typeof text === "string" ? text : ""; + const at = Number.isInteger(caret) ? caret : 0; + const here = Math.max(0, Math.min(at, source.length)); + + const lineStart = source.lastIndexOf("\n", here - 1) + 1; + const column = here - lineStart; + + if (step < 0) { + if (lineStart === 0) return here; // there is no line above + const aboveEnd = lineStart - 1; // the newline of the line above + const aboveStart = source.lastIndexOf("\n", aboveEnd - 1) + 1; + return aboveStart + Math.min(column, aboveEnd - aboveStart); + } + + const lineEnd = source.indexOf("\n", here); + if (lineEnd < 0) return here; // there is no line below + const belowStart = lineEnd + 1; + const nextBreak = source.indexOf("\n", belowStart); + const belowEnd = nextBreak < 0 ? source.length : nextBreak; + return belowStart + Math.min(column, belowEnd - belowStart); +} + +/** + * What a key of the menu does. + * + * "none" — the composer does not touch the key: another field of the app has + * the keyboard, or there is no menu to move. + * "menu" — the arrows move the menu. + * "accept" — Tab takes the picked row. + * + * @param {boolean} hasKeyboard - does the composer's own field have the keyboard? + * @param {object|null} menu + * @param {string} key - "up", "down" or "tab" + * @returns {"none"|"menu"|"accept"} + */ +export function menuAction(hasKeyboard, menu, key) { + if (!hasKeyboard) return "none"; + if (!menu || !(menu.items ?? []).length) return "none"; + if (key === "up" || key === "down") return "menu"; + if (key === "tab") return "accept"; + return "none"; +} + +/** + * The JSON of a `--json` payload, or null when it is not JSON at all. + * + * @param {string} text + * @returns {object|null} + */ +export function parseJson(text) { + if (typeof text !== "string" || text.trim() === "") return null; + try { + const value = JSON.parse(text); + return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null; + } catch { + return null; + } +} + +/** + * May the composer count on this result of `hc`? + * + * `hc` exits 0 even when it fails, so the payload decides - and a payload + * that is not JSON at all is an unknown result, not a success (the same rule + * the delivery layer follows). + * + * @param {{code?:number, stdout?:string}|null} result + * @returns {boolean} + */ +export function hcOk(result) { + if (!result || result.code !== 0) return false; + const payload = parseJson(result.stdout); + return payload !== null && !payload.error; +} + +/** + * What a send whose hook failed means. + * + * The hook of the delivery reports the states of the queue; a failure in it + * after the message went on the wire must not send the message again. The + * entry left the queue, so it is sent; an entry that is still there is + * uncertain. + * + * @param {object[]} queue - the queue of the agent + * @param {string} id + * @returns {"sent"|"uncertain"} + */ +export function failedHookOutcome(queue, id) { + const still = (Array.isArray(queue) ? queue : []).some((item) => item.id === id); + return still ? "uncertain" : "sent"; +} + +/** + * The queue goes out - one message after another, while the gate is open. + * + * `drain` sends one entry and leaves the gate as it was; the loop asks for the + * next one until the queue is empty or the gate closes. The caller keeps the + * "one drain in flight" flag for the whole loop: two drains on the same state + * would send the same message twice. + * + * @param {object} ctx - the ctx of `delivery.drain` + * @param {object} state + * @returns {Promise<{state:object, sent:number}>} + */ +export async function drainAll(ctx, state) { + let current = state; + let sent = 0; + + for (;;) { + const result = await drain(ctx, current); + current = result.state; + if (!result.sent) break; + sent += 1; + } + + return { state: current, sent }; +} + +/** + * What the composer says about an agent's status. + * + * @param {string} status + * @returns {string} + */ +export function statusText(status) { + switch (status) { + case "working": + return "pracuje"; + case "blocked": + return "czeka na Ciebie"; + case "done": + return "skończył"; + default: + return "gotowy"; + } +} + +/** + * The label of a queue row. + * + * @param {{state?:string}} item + * @returns {string} + */ +export function queueLabel(item) { + switch (item?.state) { + case "queued": + return "Następna tura"; + case "held": + return "Do wysłania teraz"; + case "sending": + return "Wysyłanie…"; + case "uncertain": + return "Niepotwierdzone"; + default: + return ""; + } +} + +/** + * The text and the caret after a suggestion is accepted. + * + * The token at the caret is replaced by what the item inserts; the caret lands + * behind it, so the next word continues where the person was typing. + * + * @param {string} text + * @param {number} caret + * @param {{start?:number}} token - the trigger of the suggestion + * @param {string} insert + * @returns {{value:string, caret:number}} + */ +export function applySuggestion(text, caret, token, insert) { + const source = typeof text === "string" ? text : ""; + const at = Number.isInteger(caret) ? caret : 0; + const start = Number.isInteger(token?.start) ? token.start : at; + const value = source.slice(0, start) + String(insert ?? "") + source.slice(at); + return { value, caret: start + String(insert ?? "").length }; +} + +/** + * The newline that Enter put into the field. + * + * The composer sends on Enter, and the field puts a newline in before the + * submit arrives. The message is the text as it was before that newline - and + * the caret is where the newline went in. + * + * @param {string} previous - the text before the change + * @param {string} next - the text after the change + * @returns {{index:number}|null} where the newline went in, or null + */ +export function insertedNewline(previous, next) { + if (typeof previous !== "string" || typeof next !== "string") return null; + if (next.length !== previous.length + 1) return null; + + for (let index = 0; index < next.length; index += 1) { + if (next[index] !== "\n") continue; + if (next.slice(0, index) + next.slice(index + 1) === previous) return { index }; + } + return null; +} + +/** + * The mentions of the files, at the start of the message. + * + * A leading command keeps the first place - the mentions follow it. + * + * @param {string} text + * @param {string[]} tokens - the mentions ("@src/a.rs") + * @returns {{value:string, caret:number}} + */ +export function insertMentions(text, tokens) { + const source = typeof text === "string" ? text : ""; + const list = (Array.isArray(tokens) ? tokens : []).filter(Boolean); + if (list.length === 0) return { value: source, caret: source.length }; + + const command = /^\/[^\s]*\s*/.exec(source); + const at = command ? command[0].length : 0; + const mentions = list.map((token) => `${token} `).join(""); + + return { + value: source.slice(0, at) + mentions + source.slice(at), + caret: at + mentions.length, + }; +} + +/** + * The items of the catalog, grouped by their group. + * + * @param {object[]} items + * @returns {Record} + */ +export function groupItems(items) { + const groups = {}; + for (const item of Array.isArray(items) ? items : []) { + if (!item) continue; + const name = typeof item.group === "string" && item.group !== "" ? item.group : ""; + if (!groups[name]) groups[name] = []; + groups[name].push(item); + } + return groups; +} + +/** + * The folder and the branch of the pane the composer talks to. + * + * @param {object[]} panes + * @param {string} terminal + * @returns {{cwd:string|null, branch:string|null}} + */ +export function paneContext(panes, terminal) { + const list = Array.isArray(panes) ? panes : []; + const pane = list.find((entry) => entry && entry.terminal === terminal); + return { cwd: pane?.cwd ?? null, branch: pane?.branch ?? null }; +} + +/** + * The last parts of a path - the folder the person knows by heart. + * + * @param {string} path + * @returns {string} + */ +export function shortPath(path) { + const parts = String(path ?? "") + .split(/[\\/]/) + .filter(Boolean); + if (parts.length <= 2) return parts.join("/"); + return parts.slice(-2).join("/"); +} + +/** + * A store that never writes back a list it failed to read. + * + * The reader of storage.js swallows a failing read and answers with an empty + * list - writing that list back would wipe what is really there. The store + * remembers which keys failed and refuses to write them. + * + * @param {{get:(key:string)=>unknown, set:(key:string, value:unknown)=>unknown}} raw + * @returns {{get:(key:string)=>unknown, set:(key:string, value:unknown)=>void, failed:(key:string)=>boolean}} + */ +export function guardedStore(raw) { + const failed = new Set(); + + return { + get(key) { + try { + const value = raw.get(key); + return value ?? null; + } catch { + failed.add(key); + return null; + } + }, + set(key, value) { + if (failed.has(key)) return; + raw.set(key, value); + }, + failed(key) { + return failed.has(key); + }, + }; +} + +/** + * How many characters the text has over the limit (0 when it fits). + * + * @param {string} text + * @returns {number} + */ +export function overLimit(text) { + const length = typeof text === "string" ? text.length : 0; + return Math.max(0, length - LIMITS.messageChars); +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..d410951 --- /dev/null +++ b/package.json @@ -0,0 +1 @@ +{"type":"module","private":true,"scripts":{"test":"node --test tests/*.test.mjs"}} diff --git a/scripts/install.ps1 b/scripts/install.ps1 new file mode 100644 index 0000000..a98ad89 --- /dev/null +++ b/scripts/install.ps1 @@ -0,0 +1,97 @@ +# install.ps1 - link the repo's ovis-composer mod into the Herdr config. +# +# .\scripts\install.ps1 install (idempotent) +# .\scripts\install.ps1 -Uninstall remove the junction, restore backups +# +# Works on Windows PowerShell 5. + +[CmdletBinding()] +param([switch]$Uninstall) + +$ErrorActionPreference = 'Stop' + +$Stamp = '20261119' +$Repo = Split-Path -Parent $PSScriptRoot +$HerdrDir = Join-Path $env:USERPROFILE '.config\herdr-app' +$ModsDir = Join-Path $HerdrDir 'mods' +$Junction = Join-Path $ModsDir 'ovis-composer' +$ModBackup = "$Junction.bak-$Stamp" +$ModSource = Join-Path $Repo 'mod\ovis-composer' +$LayoutSrc = Join-Path $Repo 'layouts\ovis-composer.json' +$LayoutDst = Join-Path $HerdrDir 'layouts\ovis-composer.json' +$LayoutBak = "$LayoutDst.bak-$Stamp" +$KeysFile = Join-Path $HerdrDir 'keys.json' +$KeysBak = "$KeysFile.bak-$Stamp" + +function Test-Junction([string]$Path) { + if (-not (Test-Path -LiteralPath $Path)) { return $false } + $item = Get-Item -LiteralPath $Path -Force + return [bool]($item.Attributes -band [IO.FileAttributes]::ReparsePoint) +} + +function Remove-Junction([string]$Path) { + # rmdir on a junction removes only the link, never the target's contents. + cmd /c rmdir "`"$Path`"" | Out-Null + if ($LASTEXITCODE -ne 0) { throw "rmdir failed for $Path" } +} + +# Task 2 adds the key binding here (keys.json.bak-$Stamp is taken first). +function Install-KeyEntry { + # TODO(Task 2): back up keys.json once as $KeysBak, then add the entry. +} + +if ($Uninstall) { + if (Test-Junction $Junction) { + Remove-Junction $Junction + if (-not (Test-Path -LiteralPath (Join-Path $ModSource 'main.js'))) { + throw 'Repo files vanished after removing the junction - aborting.' + } + Write-Host "Removed junction $Junction" + } + if ((Test-Path -LiteralPath $ModBackup) -and -not (Test-Path -LiteralPath $Junction)) { + Move-Item -LiteralPath $ModBackup -Destination $Junction + Write-Host "Restored $Junction" + } + if (Test-Path -LiteralPath $LayoutBak) { + Copy-Item -LiteralPath $LayoutBak -Destination $LayoutDst -Force + Write-Host "Restored layout" + } + if (Test-Path -LiteralPath $KeysBak) { + Copy-Item -LiteralPath $KeysBak -Destination $KeysFile -Force + Write-Host "Restored keys.json" + } + herdr-app do layout.switch '{"name":"main"}' + exit 0 +} + +# 1. Mod directory -> junction to the repo. +if (Test-Junction $Junction) { + Write-Host "Junction already in place: $Junction" +} else { + if (Test-Path -LiteralPath $Junction) { + if (Test-Path -LiteralPath $ModBackup) { throw "$ModBackup already exists - resolve by hand." } + Move-Item -LiteralPath $Junction -Destination $ModBackup + Write-Host "Backed up to $ModBackup" + } + cmd /c mklink /J "`"$Junction`"" "`"$ModSource`"" | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'mklink /J failed' } + Write-Host "Junction: $Junction -> $ModSource" +} + +# gpui-kit.d.ts is git-ignored; keep a copy next to the sources for the editor. +$kitDst = Join-Path $ModSource 'gpui-kit.d.ts' +$kitSrc = if (Test-Path -LiteralPath (Join-Path $ModBackup 'gpui-kit.d.ts')) { Join-Path $ModBackup 'gpui-kit.d.ts' } else { Join-Path $HerdrDir 'gpui-kit.d.ts' } +if (-not (Test-Path -LiteralPath $kitDst) -and (Test-Path -LiteralPath $kitSrc)) { + Copy-Item -LiteralPath $kitSrc -Destination $kitDst +} + +# 2. Layout (back up the existing file once). +if ((Test-Path -LiteralPath $LayoutDst) -and -not (Test-Path -LiteralPath $LayoutBak)) { + Copy-Item -LiteralPath $LayoutDst -Destination $LayoutBak + Write-Host "Backed up layout to $LayoutBak" +} +Copy-Item -LiteralPath $LayoutSrc -Destination $LayoutDst -Force +Write-Host "Layout copied" + +# 3. Key binding (Task 2). +Install-KeyEntry diff --git a/tests/attachments.test.mjs b/tests/attachments.test.mjs new file mode 100644 index 0000000..fc6f750 --- /dev/null +++ b/tests/attachments.test.mjs @@ -0,0 +1,38 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { LIMITS, validate, validateMany, mention, removeMention } from "../mod/ovis-composer/attachments.js"; + +test("validate rejects over 32 MiB", () => { + const r = validate({ bytes: 33 * 2 ** 20 }); + assert.equal(r.ok, false); + assert.equal(r.reason, "Plik przekracza limit 32 MiB"); +}); + +test("validate accepts a normal file and an image", () => { + assert.deepEqual(validate({ name: "a.txt", bytes: 10 }), { ok: true }); + assert.deepEqual(validate({ name: "a.png", bytes: 10 }), { ok: true }); +}); + +test("validate rejects junk and unknown kind", () => { + assert.equal(validate(null).ok, false); + assert.equal(validate({ bytes: NaN }).ok, false); + assert.equal(validate({ kind: "video", bytes: 1 }).ok, false); +}); + +test("validateMany enforces count limit", () => { + assert.equal(LIMITS.filesPerAction, 100); + const files = Array.from({ length: 101 }, () => ({ name: "a", bytes: 1 })); + assert.equal(validateMany(files).ok, false); + assert.equal(validateMany(files.slice(0, 100)).ok, true); +}); + +test("mention", () => { + assert.equal(mention(" /a/b "), "@/a/b"); + assert.equal(mention(""), ""); + assert.equal(mention(5), ""); +}); + +test("removeMention removes only the standalone token", () => { + assert.equal(removeMention("see @src/a.rs now", "src/a.rs"), "see now"); + assert.equal(removeMention("see @src/a.rsx now", "src/a.rs"), "see @src/a.rsx now"); +}); diff --git a/tests/delivery.test.mjs b/tests/delivery.test.mjs new file mode 100644 index 0000000..f5395b5 --- /dev/null +++ b/tests/delivery.test.mjs @@ -0,0 +1,37 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { decide, gateAfter, onRestart } from "../mod/ovis-composer/delivery.js"; + +test("decide idle/done -> send", () => { + assert.equal(decide("idle").kind, "send"); + assert.equal(decide("done").kind, "send"); +}); + +test("decide working -> queue, blocked -> hold", () => { + assert.equal(decide("working").kind, "queue"); + assert.equal(decide("blocked").kind, "hold"); +}); + +test("decide unknown status -> queue", () => { + assert.equal(decide("error").kind, "queue"); +}); + +test("gateAfter needs a seen working turn", () => { + assert.equal(gateAfter("idle", false), false); + assert.equal(gateAfter("idle", true), true); + assert.equal(gateAfter("done", true), true); + assert.equal(gateAfter("working", true), false); +}); + +test("onRestart sending -> uncertain, others untouched", () => { + const out = onRestart([ + { id: "1", state: "sending" }, + { id: "2", state: "queued" }, + { id: "3", state: "held" }, + ]); + assert.deepEqual(out.map((i) => i.state), ["uncertain", "queued", "held"]); +}); + +test("onRestart tolerates non-array", () => { + assert.deepEqual(onRestart(null), []); +}); diff --git a/tests/state.test.mjs b/tests/state.test.mjs new file mode 100644 index 0000000..8cdf76c --- /dev/null +++ b/tests/state.test.mjs @@ -0,0 +1,60 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createState, reduce, isSending } from "../mod/ovis-composer/state.js"; + +test("createState starts empty", () => { + const s = createState(); + assert.deepEqual(s.drafts, {}); + assert.deepEqual(s.queue, {}); + assert.equal(s.menu, null); +}); + +test("draft then send clears the draft", () => { + let s = reduce(createState(), { type: "draft", agent: "a", text: "hi" }); + assert.equal(s.drafts.a, "hi"); + s = reduce(s, { type: "send", agent: "a" }); + assert.equal(s.drafts.a, ""); +}); + +test("reduce never mutates", () => { + const s = createState(); + const n = reduce(s, { type: "draft", agent: "a", text: "x" }); + assert.notEqual(s, n); + assert.deepEqual(s.drafts, {}); +}); + +test("queue adds item and isSending sees only sending state", () => { + let s = reduce(createState(), { type: "queue", agent: "a", item: { id: "1", text: "t", createdAt: 1 } }); + assert.equal(s.queue.a[0].state, "queued"); + assert.equal(isSending(s, "a"), false); + s = reduce(s, { type: "restore", agent: "a", items: [{ id: "2", text: "t", state: "sending", createdAt: 2 }] }); + assert.equal(isSending(s, "a"), true); + assert.equal(isSending(s, "b"), false); +}); + +test("queue without createdAt throws", () => { + assert.throws(() => reduce(createState(), { type: "queue", agent: "a", item: { id: "1", text: "t" } }), TypeError); +}); + +test("restart turns sending into uncertain for that agent only", () => { + let s = reduce(createState(), { type: "restore", agent: "a", items: [{ id: "1", text: "t", state: "sending", createdAt: 1 }] }); + s = reduce(s, { type: "restore", agent: "b", items: [{ id: "2", text: "t", state: "sending", createdAt: 1 }] }); + s = reduce(s, { type: "restart", agent: "a" }); + assert.equal(s.queue.a[0].state, "uncertain"); + assert.equal(s.queue.b[0].state, "sending"); +}); + +test("attach and removeAttachment", () => { + let s = reduce(createState(), { type: "attach", agent: "a", file: { id: "f", name: "x", path: "/x", bytes: 1 } }); + assert.equal(s.attachments.a[0].kind, "file"); + assert.equal(s.attachments.a[0].state, "ready"); + s = reduce(s, { type: "removeAttachment", agent: "a", id: "f" }); + assert.deepEqual(s.attachments.a, []); +}); + +test("notice sets and clears", () => { + let s = reduce(createState(), { type: "notice", notice: { text: "x" } }); + assert.deepEqual(s.notice, { text: "x" }); + s = reduce(s, { type: "notice", notice: null }); + assert.equal(s.notice, null); +}); diff --git a/tests/storage.test.mjs b/tests/storage.test.mjs new file mode 100644 index 0000000..d0a19c8 --- /dev/null +++ b/tests/storage.test.mjs @@ -0,0 +1,58 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + HISTORY_LIMIT, queueKey, loadHistory, saveHistory, loadQueue, saveQueue, loadUsage, saveUsage, +} from "../mod/ovis-composer/storage.js"; + +const memStore = () => { + const m = new Map(); + return { get: (k) => m.get(k), set: (k, v) => void m.set(k, v) }; +}; + +test("saveHistory truncates to 500, keeping the newest", () => { + const store = memStore(); + const items = Array.from({ length: 520 }, (_, i) => ({ id: `i${i}`, text: `t${i}`, at: i })); + saveHistory(store, items); + const out = loadHistory(store); + assert.equal(HISTORY_LIMIT, 500); + assert.equal(out.length, 500); + assert.equal(out[0].id, "i20"); + assert.equal(out[499].id, "i519"); +}); + +test("history drops invalid entries on load", () => { + const store = memStore(); + store.set("ovis-composer.history", [{ id: "a", text: "x", at: 1 }, { id: "b" }, null]); + assert.equal(loadHistory(store).length, 1); +}); + +test("queueKey is per agent", () => { + assert.equal(queueKey("a1"), "ovis-composer.queue:a1"); +}); + +test("queue roundtrip; keeps sending state as written", () => { + const store = memStore(); + const q = [{ id: "1", text: "t", state: "sending", createdAt: 5 }]; + saveQueue(store, "a", q); + assert.deepEqual(loadQueue(store, "a"), q); + assert.deepEqual(loadQueue(store, "b"), []); +}); + +test("saveQueue ignores empty agent", () => { + const store = memStore(); + saveQueue(store, "", [{ id: "1", text: "t", state: "queued", createdAt: 1 }]); + assert.equal(store.get("ovis-composer.queue:"), undefined); +}); + +test("usage keeps only non-negative finite numbers", () => { + const store = memStore(); + saveUsage(store, { review: 3, bad: -1, worse: "x" }); + assert.deepEqual(loadUsage(store), { review: 3 }); +}); + +test("rubbish list does not wipe stored history", () => { + const store = memStore(); + saveHistory(store, [{ id: "a", text: "x", at: 1 }]); + saveHistory(store, [{ nope: 1 }]); + assert.equal(loadHistory(store).length, 1); +}); diff --git a/tests/suggest.test.mjs b/tests/suggest.test.mjs new file mode 100644 index 0000000..8e2b745 --- /dev/null +++ b/tests/suggest.test.mjs @@ -0,0 +1,42 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { detect, startsLine, rank, merge, GROUPS } from "../mod/ovis-composer/suggest.js"; + +test("detect finds a slash command at caret", () => { + assert.deepEqual(detect("ala /re", 7), { trigger: "/", needle: "re", start: 4 }); +}); + +test("detect ignores slash inside a path", () => { + assert.equal(detect("see /tmp/x", 10), null); +}); + +test("detect finds @ file token anywhere", () => { + assert.deepEqual(detect("open @src/a", 11), { trigger: "@", needle: "src/a", start: 5 }); +}); + +test("detect rejects bad caret / non-string", () => { + assert.equal(detect(null, 0), null); + assert.equal(detect("abc", 99), null); +}); + +test("startsLine", () => { + assert.equal(startsLine("a\n/x", 2), true); + assert.equal(startsLine("a /x", 2), false); + assert.equal(startsLine("/x", 0), true); +}); + +test("rank orders by level then uses; fuzzy only at line start", () => { + const items = [ + { key: "review", uses: 0 }, + { key: "preview", uses: 0 }, + { key: "revert", uses: 5 }, + ]; + assert.deepEqual(rank(items, "rev").map((i) => i.key), ["revert", "review"]); + assert.deepEqual(rank(items, "rev", { atLineStart: true }).map((i) => i.key), ["revert", "review", "preview"]); +}); + +test("merge orders groups as the design names them", () => { + const out = merge({ [GROUPS[1]]: [{ key: "b" }], [GROUPS[0]]: [{ key: "a" }] }); + assert.deepEqual(out.map((i) => i.key), ["a", "b"]); + assert.equal(out[0].group, GROUPS[0]); +}); diff --git a/tests/view.test.mjs b/tests/view.test.mjs new file mode 100644 index 0000000..2c62726 --- /dev/null +++ b/tests/view.test.mjs @@ -0,0 +1,55 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + targetAgent, agentKey, agentName, agentStatus, createGate, gatePasses, openGate, closeGate, + isPlainEnter, statusText, queueLabel, applySuggestion, insertedNewline, +} from "../mod/ovis-composer/view.js"; + +const agents = [{ address: "t1", app: "claude-code" }, { address: "a2" }]; + +test("targetAgent picks by focused.terminal, then focused.agent", () => { + assert.equal(targetAgent(agents, { terminal: "t1" }), agents[0]); + assert.equal(targetAgent(agents, { agent: "a2" }), agents[1]); + assert.equal(targetAgent(agents, { terminal: "zz" }), null); + assert.equal(targetAgent(agents, null), null); +}); + +test("agentKey/agentName/agentStatus", () => { + assert.equal(agentKey({ address: " x " }), "x"); + assert.equal(agentName({ program: { key: "k" } }), "k"); + assert.equal(agentName(null), "default"); + assert.equal(agentStatus({}), "idle"); +}); + +test("gate: opens after a seen turn, or outright", () => { + let g = createGate(); + assert.equal(gatePasses(g, "idle"), false); + assert.equal(gatePasses({ sawWorking: true }, "done"), true); + g = openGate(g); + assert.equal(gatePasses(g, "working"), true); + g = closeGate(g); + assert.equal(gatePasses(g, "idle"), false); +}); + +test("isPlainEnter", () => { + assert.equal(isPlainEnter({}), true); + assert.equal(isPlainEnter({ shift: true }), false); + assert.equal(isPlainEnter({ secondary: true }), false); + assert.equal(isPlainEnter(null), false); +}); + +test("labels", () => { + assert.equal(statusText("working"), "pracuje"); + assert.equal(statusText("x"), "gotowy"); + assert.equal(queueLabel({ state: "queued" }), "Następna tura"); + assert.equal(queueLabel({}), ""); +}); + +test("applySuggestion replaces token and places caret", () => { + assert.deepEqual(applySuggestion("ala /re", 7, { start: 4 }, "/review "), { value: "ala /review ", caret: 12 }); +}); + +test("insertedNewline finds the index", () => { + assert.deepEqual(insertedNewline("ab", "a\nb"), { index: 1 }); + assert.equal(insertedNewline("ab", "abc"), null); +});