refactor: restructure into herdr/herdr-composer, rename ovis-composer -> herdr-composer, migrate stored data
Co-Authored-By: Ovis Fast (Claude) <[email protected]>
This commit is contained in:
1 parent
6beecaac83
commit
74c1dfaeb8
27 files changed
+253
-97
No files matched your search
@@ -0,0 +1,217 @@
|
||||
// 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,
|
||||
};
|
||||
|
||||
/** A character that can be part of a path (letters of any alphabet too: "ęą"). */
|
||||
const PATH_CHAR = /[\p{L}\p{N}_/\\-]/u;
|
||||
|
||||
/** 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.
|
||||
*
|
||||
* A path with whitespace in it is quoted - `@"/a b/c.png"` - or the agent
|
||||
* would read only the part up to the first space; any other path stays bare
|
||||
* (`@/a/c.png`). `removeMention` takes out exactly the form built here.
|
||||
*
|
||||
* @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();
|
||||
if (clean === "") return "";
|
||||
return /\s/.test(clean) ? `@"${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}
|
||||
*/
|
||||
export 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 !== "" && PATH_CHAR.test(before)) return false;
|
||||
if (after !== "" && PATH_CHAR.test(after)) return false;
|
||||
if (after === "." && PATH_CHAR.test(afterNext)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* A size for a tile: `512 B`, `1,5 KB`, `5 MB`.
|
||||
*
|
||||
* @param {number|undefined|null} bytes
|
||||
* @returns {string} nothing when the size is not known
|
||||
*/
|
||||
export function formatBytes(bytes) {
|
||||
if (!Number.isFinite(bytes) || bytes < 0) return "";
|
||||
const unit = (value, name) => `${String(Math.round(value * 10) / 10).replace(".", ",")} ${name}`;
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return unit(bytes / 1024, "KB");
|
||||
if (bytes < 1024 * 1024 * 1024) return unit(bytes / 1024 / 1024, "MB");
|
||||
return unit(bytes / 1024 / 1024 / 1024, "GB");
|
||||
}
|
||||
|
||||
/**
|
||||
* The path of a file relative to a folder - or nothing when the file is not
|
||||
* inside it.
|
||||
*
|
||||
* `image()` draws only files of the application's own folder, and wants their
|
||||
* path relative to it (forward slashes). Windows paths compare without regard
|
||||
* to case and to the kind of slash.
|
||||
*
|
||||
* @param {string} base - the folder (`appHome()`)
|
||||
* @param {string} path - the file
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function relativeTo(base, path) {
|
||||
if (typeof base !== "string" || typeof path !== "string" || base === "" || path === "") return null;
|
||||
const clean = (text) => text.replace(/\\/g, "/").replace(/\/+$/, "");
|
||||
const root = clean(base);
|
||||
const file = clean(path);
|
||||
if (file.length <= root.length + 1) return null;
|
||||
if (file.slice(0, root.length).toLowerCase() !== root.toLowerCase()) return null;
|
||||
if (file[root.length] !== "/") return null;
|
||||
return file.slice(root.length + 1);
|
||||
}
|
||||
@@ -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<ExecResult>} 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<Item[]>}
|
||||
*/
|
||||
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<Item[]>}
|
||||
*/
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
// clipboard.js - what the composer asks the system for: the clipboard, the
|
||||
// file picker, the sizes of files, and the old files of the paste folder.
|
||||
//
|
||||
// Pure: no gpui-kit, no gpui-base, no herdr. The scripts are PowerShell text
|
||||
// (run by main.js with `exec("powershell", ["-NoProfile", "-STA", "-Command",
|
||||
// script])` - `-Command`, because running script files is off on this
|
||||
// machine), and the parsers read what the scripts print, so both halves are
|
||||
// tested in plain Node (tests/clipboard.test.mjs).
|
||||
//
|
||||
// The mods have no `stat` (fs/promises: no size, no mtime), so the SIZE of
|
||||
// every file comes from PowerShell, in the same call that finds the file.
|
||||
//
|
||||
// The scripts print one fact per line, the fields separated by a tab:
|
||||
// FILES<TAB><path><TAB><bytes> (one line per file) - files from the Explorer
|
||||
// IMAGE<TAB><path><TAB><bytes> - an image, saved as a PNG
|
||||
// DIR<TAB><path> - a folder (not carried)
|
||||
// NONE - nothing to paste
|
||||
// An empty or missing <bytes> means the size could not be read: the caller
|
||||
// does not let such a file through (fail closed).
|
||||
|
||||
/** How long a pasted image stays in the paste folder. */
|
||||
export const PASTE_MAX_AGE_MS = 7 * 864e5;
|
||||
|
||||
/** The programs that take an image (Global Constraints). */
|
||||
const IMAGE_APPS = new Set(["claude-code", "codex", "gemini", "opencode"]);
|
||||
|
||||
/**
|
||||
* The PowerShell that reads the clipboard: files first (folders apart), then
|
||||
* an image (saved as `<outDir>\paste-<stamp>.png`), otherwise `NONE`.
|
||||
*
|
||||
* @param {string} outDir - where a pasted image is saved
|
||||
* @param {string} stamp - what makes the file name its own (a moment)
|
||||
* @returns {string}
|
||||
*/
|
||||
export function clipboardScript(outDir, stamp) {
|
||||
const dir = decode(outDir);
|
||||
const name = `paste-${String(stamp).replace(/[^\w-]/g, "")}.png`;
|
||||
|
||||
return [
|
||||
"Add-Type -AssemblyName System.Windows.Forms",
|
||||
"Add-Type -AssemblyName System.Drawing",
|
||||
"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8",
|
||||
"$tab = [char]9",
|
||||
"$files = [System.Windows.Forms.Clipboard]::GetFileDropList()",
|
||||
"if ($files -ne $null -and $files.Count -gt 0) {",
|
||||
" foreach ($f in $files) {",
|
||||
" if (Test-Path -LiteralPath $f -PathType Container) {",
|
||||
' Write-Output ("DIR" + $tab + $f)',
|
||||
" } else {",
|
||||
" $len = ''",
|
||||
" try { $len = (Get-Item -LiteralPath $f -ErrorAction Stop).Length } catch { }",
|
||||
' Write-Output ("FILES" + $tab + $f + $tab + $len)',
|
||||
" }",
|
||||
" }",
|
||||
" exit 0",
|
||||
"}",
|
||||
"$img = [System.Windows.Forms.Clipboard]::GetImage()",
|
||||
"if ($img -ne $null) {",
|
||||
` $dir = ${dir}`,
|
||||
" New-Item -ItemType Directory -Force -Path $dir | Out-Null",
|
||||
` $path = Join-Path $dir '${name}'`,
|
||||
" $img.Save($path, [System.Drawing.Imaging.ImageFormat]::Png)",
|
||||
" $len = ''",
|
||||
" try { $len = (Get-Item -LiteralPath $path -ErrorAction Stop).Length } catch { }",
|
||||
' Write-Output ("IMAGE" + $tab + $path + $tab + $len)',
|
||||
" exit 0",
|
||||
"}",
|
||||
"Write-Output 'NONE'",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* What the clipboard script printed.
|
||||
*
|
||||
* `files` are the things to attach (an image comes as one file); `dirs` are
|
||||
* folders, which are not carried. Only folders: `{kind:"dirs"}`.
|
||||
*
|
||||
* @param {{code?:number, stdout?:string, stderr?:string}|null} res
|
||||
* @returns {{kind:"image"|"files", files:{path:string, bytes:number|null}[], dirs:string[]}
|
||||
* | {kind:"dirs", dirs:string[]} | {kind:"none"} | {kind:"error", message:string}}
|
||||
*/
|
||||
export function parseClipboardResult(res) {
|
||||
if (!res || typeof res !== "object") return { kind: "error", message: "Brak wyniku z PowerShell" };
|
||||
|
||||
if (res.code !== 0) {
|
||||
const stderr = String(res.stderr ?? "").trim();
|
||||
return { kind: "error", message: stderr || `PowerShell zakończył się kodem ${res.code}` };
|
||||
}
|
||||
|
||||
const files = [];
|
||||
const dirs = [];
|
||||
let image = null;
|
||||
for (const line of lines(res.stdout)) {
|
||||
const [kind, path, size] = fields(line);
|
||||
if (!path) continue;
|
||||
if (kind === "FILES") files.push({ path, bytes: toBytes(size) });
|
||||
if (kind === "IMAGE" && image === null) image = { path, bytes: toBytes(size) };
|
||||
if (kind === "DIR") dirs.push(path);
|
||||
}
|
||||
|
||||
if (files.length > 0) return { kind: "files", files, dirs };
|
||||
if (image) return { kind: "image", files: [image], dirs };
|
||||
if (dirs.length > 0) return { kind: "dirs", dirs };
|
||||
return { kind: "none" };
|
||||
}
|
||||
|
||||
/**
|
||||
* The PowerShell that opens the file dialog (several files may be picked) and
|
||||
* prints `<path><TAB><bytes>` per line. Cancel prints nothing.
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
export function pickerScript() {
|
||||
return [
|
||||
"Add-Type -AssemblyName System.Windows.Forms",
|
||||
"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8",
|
||||
"$tab = [char]9",
|
||||
"$dialog = New-Object System.Windows.Forms.OpenFileDialog",
|
||||
"$dialog.Multiselect = $true",
|
||||
"$dialog.Title = 'Wybierz pliki'",
|
||||
"if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {",
|
||||
" foreach ($f in $dialog.FileNames) {",
|
||||
" $len = ''",
|
||||
" try { $len = (Get-Item -LiteralPath $f -ErrorAction Stop).Length } catch { }",
|
||||
' Write-Output ($f + $tab + $len)',
|
||||
" }",
|
||||
"}",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* The files the dialog printed; cancel, or a failed run, is no file at all.
|
||||
*
|
||||
* @param {{code?:number, stdout?:string}|null} res
|
||||
* @returns {{path:string, bytes:number|null}[]}
|
||||
*/
|
||||
export function parsePickerResult(res) {
|
||||
if (!res || typeof res !== "object" || res.code !== 0) return [];
|
||||
return lines(res.stdout).map((line) => {
|
||||
const [path, size] = fieldsLast(line);
|
||||
return { path, bytes: toBytes(size) };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The PowerShell that measures a batch of paths in one call: `SIZE` for a
|
||||
* file, `DIR` for a folder, `MISSING` for what is not there.
|
||||
*
|
||||
* @param {string[]} paths
|
||||
* @returns {string}
|
||||
*/
|
||||
export function sizeScript(paths) {
|
||||
const list = (Array.isArray(paths) ? paths : []).map(String).join("\n");
|
||||
return [
|
||||
"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8",
|
||||
"$tab = [char]9",
|
||||
// One path per line (a file name has no newline), as Base64: no byte of
|
||||
// a name is ever part of the script itself.
|
||||
`$paths = @(${decode(list)}.Split([char]10) | Where-Object { $_ -ne '' })`,
|
||||
"foreach ($p in $paths) {",
|
||||
" if (Test-Path -LiteralPath $p -PathType Container) {",
|
||||
' Write-Output ("DIR" + $tab + $p)',
|
||||
" } elseif (Test-Path -LiteralPath $p -PathType Leaf) {",
|
||||
" $len = ''",
|
||||
" try { $len = (Get-Item -LiteralPath $p -ErrorAction Stop).Length } catch { }",
|
||||
' Write-Output ("SIZE" + $tab + $p + $tab + $len)',
|
||||
" } else {",
|
||||
' Write-Output ("MISSING" + $tab + $p)',
|
||||
" }",
|
||||
"}",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* What `sizeScript` printed. A run that failed has no sizes at all: `error`
|
||||
* says why, and the caller does not attach anything on a guess.
|
||||
*
|
||||
* @param {{code?:number, stdout?:string, stderr?:string}|null} res
|
||||
* @returns {{files:{path:string, bytes:number|null}[], dirs:string[], missing:string[], error:string|null}}
|
||||
*/
|
||||
export function parseSizeResult(res) {
|
||||
const empty = { files: [], dirs: [], missing: [], error: null };
|
||||
if (!res || typeof res !== "object") return { ...empty, error: "Brak wyniku z PowerShell" };
|
||||
if (res.code !== 0) {
|
||||
const stderr = String(res.stderr ?? "").trim();
|
||||
return { ...empty, error: stderr || `PowerShell zakończył się kodem ${res.code}` };
|
||||
}
|
||||
|
||||
const out = { files: [], dirs: [], missing: [], error: null };
|
||||
for (const line of lines(res.stdout)) {
|
||||
const [kind, path, size] = fields(line);
|
||||
if (!path) continue;
|
||||
if (kind === "SIZE") out.files.push({ path, bytes: toBytes(size) });
|
||||
if (kind === "DIR") out.dirs.push(path);
|
||||
if (kind === "MISSING") out.missing.push(path);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which files of the paste folder are old enough to go.
|
||||
*
|
||||
* @param {{path:string, mtimeMs:number}[]} entries
|
||||
* @param {number} now
|
||||
* @param {number} [maxAgeMs] - 7 days by default
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function staleFiles(entries, now, maxAgeMs = PASTE_MAX_AGE_MS) {
|
||||
if (!Array.isArray(entries)) return [];
|
||||
return entries
|
||||
.filter((entry) => entry && Number.isFinite(entry.mtimeMs) && now - entry.mtimeMs > maxAgeMs)
|
||||
.map((entry) => entry.path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Does the agent's program take an image?
|
||||
*
|
||||
* @param {string|null} app - `AgentInfo.app`
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function supportsImages(app) {
|
||||
return typeof app === "string" && IMAGE_APPS.has(app.trim());
|
||||
}
|
||||
|
||||
/** The non-empty lines of an output; a BOM in front of it is not part of it. */
|
||||
function lines(text) {
|
||||
return String(text ?? "")
|
||||
.replace(/^/, "")
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.replace(/\r$/, ""))
|
||||
.filter((line) => line.trim() !== "");
|
||||
}
|
||||
|
||||
/** `KIND<TAB>path<TAB>size` -> [kind, path, size]. */
|
||||
function fields(line) {
|
||||
const first = line.indexOf("\t");
|
||||
if (first < 0) return [line, "", ""];
|
||||
const rest = line.slice(first + 1);
|
||||
const second = rest.indexOf("\t");
|
||||
return second < 0
|
||||
? [line.slice(0, first), rest.trim(), ""]
|
||||
: [line.slice(0, first), rest.slice(0, second).trim(), rest.slice(second + 1).trim()];
|
||||
}
|
||||
|
||||
/** `path<TAB>size` -> [path, size] (the size is behind the last tab). */
|
||||
function fieldsLast(line) {
|
||||
const at = line.lastIndexOf("\t");
|
||||
return at < 0 ? [line.trim(), ""] : [line.slice(0, at).trim(), line.slice(at + 1).trim()];
|
||||
}
|
||||
|
||||
/** A size in bytes, or null when it is not a size. */
|
||||
function toBytes(text) {
|
||||
if (typeof text !== "string" || text.trim() === "") return null;
|
||||
const value = Number(text);
|
||||
return Number.isFinite(value) && value >= 0 ? value : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* PowerShell that yields `text` - without the text itself being in the
|
||||
* script.
|
||||
*
|
||||
* A path or a name comes from the outside, and PowerShell reads more than the
|
||||
* ASCII apostrophe as a quote (U+2018, U+2019, U+201A, U+201B too), so no
|
||||
* quoting is safe enough. The text goes in as Base64 of its UTF-8 bytes - an
|
||||
* alphabet with no quote, no `$`, no space - and is decoded by PowerShell.
|
||||
*
|
||||
* @param {string} text
|
||||
* @returns {string}
|
||||
*/
|
||||
function decode(text) {
|
||||
return `[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64(utf8(text))}'))`;
|
||||
}
|
||||
|
||||
/** The UTF-8 bytes of a text (a lone surrogate becomes U+FFFD). */
|
||||
function utf8(text) {
|
||||
const bytes = [];
|
||||
for (const char of String(text)) {
|
||||
let code = char.codePointAt(0);
|
||||
if (code >= 0xd800 && code <= 0xdfff) code = 0xfffd;
|
||||
if (code < 0x80) {
|
||||
bytes.push(code);
|
||||
} else if (code < 0x800) {
|
||||
bytes.push(0xc0 | (code >> 6), 0x80 | (code & 63));
|
||||
} else if (code < 0x10000) {
|
||||
bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 63), 0x80 | (code & 63));
|
||||
} else {
|
||||
bytes.push(0xf0 | (code >> 18), 0x80 | ((code >> 12) & 63), 0x80 | ((code >> 6) & 63), 0x80 | (code & 63));
|
||||
}
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
/** Base64 of bytes (no Buffer, no btoa: the mods do not have to have them). */
|
||||
function base64(bytes) {
|
||||
let out = "";
|
||||
for (let i = 0; i < bytes.length; i += 3) {
|
||||
const a = bytes[i];
|
||||
const b = bytes[i + 1];
|
||||
const c = bytes[i + 2];
|
||||
out += BASE64[a >> 2];
|
||||
out += BASE64[((a & 3) << 4) | ((b ?? 0) >> 4)];
|
||||
out += b === undefined ? "=" : BASE64[((b & 15) << 2) | ((c ?? 0) >> 6)];
|
||||
out += c === undefined ? "=" : BASE64[c & 63];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
// 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 <t> --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<HcResult>} hc
|
||||
*
|
||||
* @typedef {object} DrainCtx
|
||||
* @property {string} agent - whose queue this is; the queue is `state.queue[agent]`
|
||||
* @property {string} terminal
|
||||
* @property {(args:string[]) => Promise<HcResult>} 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"|"countdown"|"sending"|"held"|"uncertain"} state
|
||||
* @property {number} createdAt
|
||||
* @property {number} [left] - seconds to the send, while the state is "countdown"
|
||||
* @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":
|
||||
// The agent waits for an answer: what the person writes IS the answer,
|
||||
// so it goes out at once. (The queue does not start on its own while
|
||||
// the agent is blocked - see `shouldDrain`.)
|
||||
return { kind: "send" };
|
||||
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" };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Does a change of the agent's status start the queue (the countdown)?
|
||||
*
|
||||
* Only the end of a turn does: the agent was working (or waiting for the
|
||||
* person) and is idle or done now. A turn that the composer stopped itself
|
||||
* (the Stop button, Esc) never starts anything.
|
||||
*
|
||||
* @param {Status|string} prev
|
||||
* @param {Status|string} next
|
||||
* @param {boolean} stoppedByComposer
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function shouldDrain(prev, next, stoppedByComposer) {
|
||||
if (stoppedByComposer) return false;
|
||||
const was = prev === "working" || prev === "blocked";
|
||||
const is = next === "idle" || next === "done";
|
||||
return was && is;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does the queue start counting down now? A rule of the state, not of a
|
||||
* change: a turn that ended unseen (shorter than one poll) or a status that
|
||||
* was unknown for a while must not leave a message waiting for ever.
|
||||
*
|
||||
* Yes when the agent is idle or done, an entry waits in the queue (`queued`;
|
||||
* a `held` one does not count, an `uncertain` one in front of it does not
|
||||
* block), nothing counts down or is on the wire, the turn gate is open and the
|
||||
* composer did not stop the agent itself.
|
||||
*
|
||||
* @param {{status:Status|string, queue:QueueItem[], gateOpen:boolean, stopped:boolean}} input
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function shouldStartCountdown({ status, queue, gateOpen, stopped }) {
|
||||
if (stopped || !gateOpen) return false;
|
||||
if (!ready(status)) return false;
|
||||
if (!Array.isArray(queue)) return false;
|
||||
if (queue.some((item) => item.state === "countdown" || item.state === "sending")) return false;
|
||||
return queue.some((item) => item.state === "queued");
|
||||
}
|
||||
|
||||
/**
|
||||
* Does a message wait in the queue (`queued`, or counting down)? Then a new
|
||||
* message does not go out ahead of it - it takes its place at the end.
|
||||
*
|
||||
* @param {QueueItem[]|undefined} queue
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function queueBlocksDirectSend(queue) {
|
||||
return (Array.isArray(queue) ? queue : []).some((item) => item.state === "queued" || item.state === "countdown");
|
||||
}
|
||||
|
||||
/**
|
||||
* 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";
|
||||
}
|
||||
|
||||
/**
|
||||
* The arguments of `hc send`.
|
||||
*
|
||||
* The text goes after `--`: a message that starts with a dash ("- fix bug",
|
||||
* "--help") would otherwise be read by hc as an option and fail with a usage
|
||||
* error. Everything after `--` is the text, whatever it looks like.
|
||||
*
|
||||
* `force` is `--force`: "type even if the program is blocked" (hc 0.1.21).
|
||||
* Only the person's own Enter, answering an agent that waits for them, asks
|
||||
* for it - the queue never does.
|
||||
*
|
||||
* @param {string} terminal
|
||||
* @param {string} text
|
||||
* @param {{force?:boolean}} [options]
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function sendArgs(terminal, text, { force = false } = {}) {
|
||||
return ["send", "--json", ...(force ? ["--force"] : []), terminal, "--", text];
|
||||
}
|
||||
|
||||
/**
|
||||
* The fields of the arguments `sendArgs` built - so a caller that watches
|
||||
* the calls (the history) reads them by name, not by position.
|
||||
*
|
||||
* @param {unknown} args
|
||||
* @returns {{terminal:string, text:string, force:boolean}|null} null when this is not a send
|
||||
*/
|
||||
export function parseSendArgs(args) {
|
||||
if (!Array.isArray(args) || args[0] !== "send") return null;
|
||||
const dashes = args.indexOf("--");
|
||||
if (dashes < 0 || args.length !== dashes + 2) return null;
|
||||
|
||||
const terminal = args.slice(1, dashes).find((arg) => typeof arg === "string" && !arg.startsWith("-"));
|
||||
if (typeof terminal !== "string" || typeof args[dashes + 1] !== "string") return null;
|
||||
return { terminal, text: args[dashes + 1], force: args.slice(1, dashes).includes("--force") };
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @param {{force?:boolean}} [options] - `force`: type even if the agent is blocked
|
||||
* @returns {Promise<Result>}
|
||||
*/
|
||||
export async function sendNow(ctx, text, options = {}) {
|
||||
const res = await callHc(ctx, sendArgs(ctx.terminal, text, options));
|
||||
|
||||
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<DrainResult>}
|
||||
*/
|
||||
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) => {
|
||||
if (item.state === "sending") return { ...item, state: "uncertain" };
|
||||
if (item.state === "countdown") {
|
||||
// Nothing goes out on its own after a restart.
|
||||
const { left, ...rest } = item;
|
||||
return { ...rest, state: "held" };
|
||||
}
|
||||
return 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, or whose countdown ran out, may go out. */
|
||||
function sendable(item) {
|
||||
if (item?.state === "queued") return true;
|
||||
return item?.state === "countdown" && !(item.left > 0);
|
||||
}
|
||||
|
||||
/** 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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
// history.js - the model of the history and the favourites.
|
||||
//
|
||||
// Pure: no GPUI, no herdr, no IO. Every function returns a new list and never
|
||||
// touches the one it was given. What is kept on the disk is storage.js; the
|
||||
// panel that shows it is Task 7.
|
||||
|
||||
import { HISTORY_LIMIT, FAVORITES_LIMIT } from "./storage.js";
|
||||
|
||||
/**
|
||||
* @typedef {object} HistoryEntry
|
||||
* @property {string} id
|
||||
* @property {string} text
|
||||
* @property {number} sentAt
|
||||
* @property {string} agent - the address of the agent (`t2`)
|
||||
* @property {string} agentName
|
||||
* @property {string} space
|
||||
* @property {string} spaceName
|
||||
* @property {string} [tabName]
|
||||
*
|
||||
* @typedef {object} Favorite
|
||||
* @property {string} id
|
||||
* @property {string} text
|
||||
* @property {number} createdAt
|
||||
*
|
||||
* @typedef {object} Hit
|
||||
* @property {HistoryEntry|Favorite} item
|
||||
* @property {[number, number][]} ranges - where the query was found: [start, end)
|
||||
*/
|
||||
|
||||
/**
|
||||
* A message was sent: it goes to the end of the history.
|
||||
*
|
||||
* Duplicates are kept - the same text sent twice is two entries. The oldest
|
||||
* entries drop out over the limit (500).
|
||||
*
|
||||
* @param {HistoryEntry[]} list - chronological, the oldest first
|
||||
* @param {HistoryEntry} entry
|
||||
* @returns {HistoryEntry[]}
|
||||
*/
|
||||
export function record(list, entry) {
|
||||
return [...(Array.isArray(list) ? list : []), entry].slice(-HISTORY_LIMIT);
|
||||
}
|
||||
|
||||
/**
|
||||
* What matches the query - newest first.
|
||||
*
|
||||
* The query is a fragment, found without regard to case (Polish letters too),
|
||||
* every occurrence. An empty query (or one of spaces only) gives everything.
|
||||
*
|
||||
* @param {(HistoryEntry|Favorite)[]} list
|
||||
* @param {string} query
|
||||
* @returns {Hit[]}
|
||||
*/
|
||||
export function search(list, query) {
|
||||
const needle = fold(String(query ?? "").trim());
|
||||
const items = (Array.isArray(list) ? list : [])
|
||||
.map((item, index) => ({ item, index }))
|
||||
.sort((a, b) => momentOf(b.item) - momentOf(a.item) || b.index - a.index);
|
||||
|
||||
if (needle === "") return items.map(({ item }) => ({ item, ranges: [] }));
|
||||
|
||||
const hits = [];
|
||||
for (const { item } of items) {
|
||||
const ranges = occurrences(fold(String(item.text ?? "")), needle);
|
||||
if (ranges.length > 0) hits.push({ item, ranges });
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
|
||||
/**
|
||||
* The favourite is added, or removed when it is there already. Texts are
|
||||
* compared after `trim()`; the oldest favourites drop out over the limit
|
||||
* (100). Nothing but spaces is not a favourite - the same list comes back.
|
||||
*
|
||||
* @param {Favorite[]} favs
|
||||
* @param {string} text
|
||||
* @param {number} now
|
||||
* @returns {Favorite[]}
|
||||
*/
|
||||
export function toggleFavorite(favs, text, now) {
|
||||
const list = Array.isArray(favs) ? favs : [];
|
||||
const clean = String(text ?? "").trim();
|
||||
if (clean === "") return favs;
|
||||
|
||||
if (list.some((fav) => fav.text.trim() === clean)) {
|
||||
return list.filter((fav) => fav.text.trim() !== clean);
|
||||
}
|
||||
return [...list, { id: freshId(list, now), text: clean, createdAt: now }].slice(-FAVORITES_LIMIT);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Favorite[]} favs
|
||||
* @param {string} text
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isFavorite(favs, text) {
|
||||
const clean = String(text ?? "").trim();
|
||||
if (clean === "") return false;
|
||||
return (Array.isArray(favs) ? favs : []).some((fav) => fav.text.trim() === clean);
|
||||
}
|
||||
|
||||
/** The moment an entry was made - a history entry or a favourite. */
|
||||
function momentOf(item) {
|
||||
const value = item.sentAt ?? item.createdAt;
|
||||
return Number.isFinite(value) ? value : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The text in the form the comparison uses: every letter in lower case, one
|
||||
* character for one character - so a position in the folded text is a position
|
||||
* in the original (a letter that would change the length stays as it is).
|
||||
*/
|
||||
function fold(text) {
|
||||
return text
|
||||
.split("")
|
||||
.map((char) => {
|
||||
const lower = char.toLowerCase();
|
||||
return lower.length === 1 ? lower : char;
|
||||
})
|
||||
.join("");
|
||||
}
|
||||
|
||||
/** Where `needle` is in `text`: every place, none overlapping. */
|
||||
function occurrences(text, needle) {
|
||||
const ranges = [];
|
||||
let from = 0;
|
||||
for (;;) {
|
||||
const at = text.indexOf(needle, from);
|
||||
if (at < 0) break;
|
||||
ranges.push([at, at + needle.length]);
|
||||
from = at + needle.length;
|
||||
}
|
||||
return ranges;
|
||||
}
|
||||
|
||||
/** An id that no favourite has yet. */
|
||||
function freshId(list, now) {
|
||||
const taken = new Set(list.map((fav) => fav.id));
|
||||
let n = 0;
|
||||
let id = `f${now}`;
|
||||
while (taken.has(id)) id = `f${now}-${(n += 1)}`;
|
||||
return id;
|
||||
}
|
||||
|
||||
// --- what the panel shows ---------------------------------------------------
|
||||
//
|
||||
// The panel (panel.js) only draws. What it draws - which rows, which part of a
|
||||
// row is lit, the line under the text, which empty state - is decided here, so
|
||||
// it is tested in plain Node.
|
||||
|
||||
/**
|
||||
* A text cut into the parts that match the query and the parts that do not.
|
||||
*
|
||||
* @param {string} text
|
||||
* @param {[number, number][]} ranges - as `search` returns them
|
||||
* @returns {{text:string, hit:boolean}[]}
|
||||
*/
|
||||
export function segments(text, ranges) {
|
||||
const source = String(text ?? "");
|
||||
const out = [];
|
||||
let at = 0;
|
||||
for (const [start, end] of Array.isArray(ranges) ? ranges : []) {
|
||||
const from = Math.max(at, Math.min(start, source.length));
|
||||
const to = Math.min(end, source.length);
|
||||
if (to <= from) continue;
|
||||
if (from > at) out.push({ text: source.slice(at, from), hit: false });
|
||||
out.push({ text: source.slice(from, to), hit: true });
|
||||
at = to;
|
||||
}
|
||||
if (at < source.length) out.push({ text: source.slice(at), hit: false });
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A moment as `DD.MM HH:MM`, in the time of this computer.
|
||||
*
|
||||
* @param {number} ms
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatMoment(ms) {
|
||||
if (!Number.isFinite(ms)) return "";
|
||||
const date = new Date(ms);
|
||||
const two = (n) => String(n).padStart(2, "0");
|
||||
return `${two(date.getDate())}.${two(date.getMonth() + 1)} ${two(date.getHours())}:${two(date.getMinutes())}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The line under the text of a row: when, in which space, to which agent - or,
|
||||
* for a favourite, when it was saved.
|
||||
*
|
||||
* @param {HistoryEntry|Favorite} item
|
||||
* @param {"history"|"favorites"} tab
|
||||
* @returns {string}
|
||||
*/
|
||||
export function entryMeta(item, tab) {
|
||||
if (tab === "favorites") return `zapisano ${formatMoment(item.createdAt)}`;
|
||||
const space = item.spaceName || "?";
|
||||
const agent = item.tabName || item.agentName || "?";
|
||||
return `${formatMoment(item.sentAt)} · ${space} · ${agent}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything the panel draws, for one tab and one query.
|
||||
*
|
||||
* `empty` says which empty state to show: the whole list is empty
|
||||
* (`"history"` / `"favorites"`), or only the query found nothing (`"query"`).
|
||||
*
|
||||
* @param {{history:HistoryEntry[], favorites:Favorite[], tab:"history"|"favorites", query:string}} input
|
||||
* @returns {{tab:string, counts:{history:number, favorites:number}, hits:Hit[], empty:null|"history"|"favorites"|"query"}}
|
||||
*/
|
||||
export function panelState({ history, favorites, tab, query }) {
|
||||
const source = tab === "favorites" ? favorites : history;
|
||||
const hits = search(source, query);
|
||||
let empty = null;
|
||||
if (!source || source.length === 0) empty = tab === "favorites" ? "favorites" : "history";
|
||||
else if (hits.length === 0) empty = "query";
|
||||
return { tab, counts: { history: history.length, favorites: favorites.length }, hits, empty };
|
||||
}
|
||||
|
||||
/**
|
||||
* The row after a step up or down - past the end it comes round.
|
||||
*
|
||||
* @param {number} index
|
||||
* @param {number} step
|
||||
* @param {number} count
|
||||
* @returns {number}
|
||||
*/
|
||||
export function moveIndex(index, step, count) {
|
||||
if (count <= 0) return 0;
|
||||
return (index + step + count) % count;
|
||||
}
|
||||
|
||||
/** The other tab. */
|
||||
export function otherTab(tab) {
|
||||
return tab === "history" ? "favorites" : "history";
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
// Pure key intents of the composer: what a key press means, given the state of
|
||||
// the composer. No gpui, no herdr - main.js acts on the answer.
|
||||
|
||||
/**
|
||||
* @typedef {"none"|"send"|"send_now"|"hold"|"newline"|"interrupt"|"close_menu"|"close_panel"|"open_panel"|"menu_up"|"menu_down"|"menu_accept"} Intent
|
||||
*/
|
||||
|
||||
/**
|
||||
* What a key press means.
|
||||
*
|
||||
* @param {{key:string, shift?:boolean, ctrl?:boolean, alt?:boolean, composing?:boolean}} e
|
||||
* @param {{hasKeyboard:boolean, menuOpen:boolean, panelOpen:boolean, empty:boolean, status:string|null}} ctx
|
||||
* @returns {Intent}
|
||||
*/
|
||||
export function keyIntent(e, ctx) {
|
||||
// Only the copy whose own field has the keyboard acts; an IME in the middle
|
||||
// of a composition owns the key.
|
||||
if (!e || !ctx || !ctx.hasKeyboard || e.composing) return "none";
|
||||
|
||||
const key = String(e.key ?? "").toLowerCase();
|
||||
|
||||
if (key === "enter") {
|
||||
if (e.ctrl) return "send_now";
|
||||
if (e.alt) return "hold";
|
||||
if (e.shift) return "newline";
|
||||
return "send";
|
||||
}
|
||||
|
||||
if (key === "escape") {
|
||||
if (ctx.menuOpen) return "close_menu";
|
||||
if (ctx.panelOpen) return "close_panel";
|
||||
if (ctx.empty && ctx.status === "working") return "interrupt";
|
||||
return "none";
|
||||
}
|
||||
|
||||
if (key === "r" && e.ctrl && !e.alt && !e.shift) return "open_panel";
|
||||
|
||||
if (ctx.menuOpen) {
|
||||
if (key === "tab") return "menu_accept";
|
||||
if (key === "up" || key === "arrowup") return "menu_up";
|
||||
if (key === "down" || key === "arrowdown") return "menu_down";
|
||||
}
|
||||
|
||||
return "none";
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"place": "none",
|
||||
"focusable": true
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
// panel.js - the view of the History | Favourites panel and of the image
|
||||
// preview. GPUI only: no logic, no state of its own. main.js owns the state and
|
||||
// hands in what to draw (`view`) and what to do (`on`); what a row says and
|
||||
// which parts of it are lit is decided in history.js.
|
||||
//
|
||||
// The look follows docs/mockups/herdr-unified-prompt.html (`.pop.hist`,
|
||||
// `.hrow`, `.hfoot`, `.empty`). The colors come from `theme()`.
|
||||
//
|
||||
// Limit of the list: rows of a `v_virtual_list` cannot carry their own click
|
||||
// handlers (the host refuses a handler inside the item renderer) - one
|
||||
// `on_item_click` serves the whole list and names the row by its key. So a row
|
||||
// click inserts the text; the star of a row is a sign, not a button (the
|
||||
// favourites are toggled with Ctrl+D or a right click - `on_item_secondary_click`).
|
||||
|
||||
import { div, image } from "gpui-kit";
|
||||
import { v_flex, h_flex, Input, Scrollbar, v_virtual_list } from "gpui-base";
|
||||
import { segments, entryMeta } from "./history.js";
|
||||
|
||||
/** The height of one row - the list is virtual, so every row has the same. */
|
||||
export const ROW_HEIGHT = 56;
|
||||
|
||||
/** The text lines of a row (the rest is cut). */
|
||||
const TEXT_HEIGHT = 34;
|
||||
|
||||
/**
|
||||
* The panel.
|
||||
*
|
||||
* @param {Record<string,string>} t - theme()
|
||||
* @param {{
|
||||
* tab: "history"|"favorites",
|
||||
* state: {counts:{history:number, favorites:number}, hits:{item:any, ranges:[number,number][]}[], empty:null|string},
|
||||
* query: string,
|
||||
* index: number,
|
||||
* input: object,
|
||||
* searchFocused: boolean,
|
||||
* fieldBackground: string,
|
||||
* scroll: object,
|
||||
* isFavorite: (text:string) => boolean,
|
||||
* }} view
|
||||
* @param {{
|
||||
* key: (event:any, cx:any) => void,
|
||||
* tab: (tab:string, cx:any) => void,
|
||||
* pick: (key:string, cx:any) => void,
|
||||
* toggle: (key:string, cx:any) => void,
|
||||
* clear: (cx:any) => void,
|
||||
* close: (cx:any) => void,
|
||||
* }} on
|
||||
*/
|
||||
export function renderPanel(t, view, on) {
|
||||
const { state } = view;
|
||||
|
||||
return v_flex()
|
||||
.id("composer-panel")
|
||||
.key_context("herdr-composer-panel")
|
||||
.on_key_down((event, cx) => on.key(event, cx))
|
||||
.size_full()
|
||||
.rounded(12)
|
||||
.border(1)
|
||||
.border_color(t.border)
|
||||
.bg(t.popover)
|
||||
.overflow_hidden()
|
||||
.children([
|
||||
renderTop(t, view, on),
|
||||
v_flex()
|
||||
.id("composer-panel-body")
|
||||
.flex_1()
|
||||
.min_h(0)
|
||||
.relative()
|
||||
.child(state.empty ? renderEmpty(t, view, on) : renderList(t, view, on)),
|
||||
renderFoot(t),
|
||||
]);
|
||||
}
|
||||
|
||||
/** The tabs and the search field. */
|
||||
function renderTop(t, view, on) {
|
||||
const { counts } = view.state;
|
||||
|
||||
return h_flex()
|
||||
.id("composer-panel-top")
|
||||
.gap(6)
|
||||
.items_center()
|
||||
.px(8)
|
||||
.py(8)
|
||||
.border_b(1)
|
||||
.border_color(t.border)
|
||||
.children([
|
||||
renderTab(t, "history", `Historia ${counts.history}`, view.tab === "history", on),
|
||||
renderTab(t, "favorites", `Ulubione ${counts.favorites}`, view.tab === "favorites", on),
|
||||
// The search field: a darker recess with a border that lights up while
|
||||
// the field has the keyboard (the `.hsearch` of the mockup).
|
||||
h_flex()
|
||||
.id("composer-panel-search")
|
||||
.flex_1()
|
||||
.min_w(0)
|
||||
.h(30)
|
||||
.px(10)
|
||||
.items_center()
|
||||
.gap(6)
|
||||
.rounded(8)
|
||||
.bg(view.fieldBackground)
|
||||
.border_1()
|
||||
.border_color(view.searchFocused ? t.accent : t.input)
|
||||
.child(div().flex_none().text_size(13).text_color(t.dim).child("⌕"))
|
||||
.child(Input.new(view.input).flex_1().min_w(0).text_size(12.5))
|
||||
.when(view.query !== "", (el) =>
|
||||
el.child(
|
||||
div()
|
||||
.id("composer-panel-clear")
|
||||
.px(6)
|
||||
.text_size(12)
|
||||
.text_color(t.dim)
|
||||
.cursor_pointer()
|
||||
.hover((s) => s.text_color(t.foreground))
|
||||
.on_click((event, cx) => on.clear(cx))
|
||||
.child("✕"),
|
||||
),
|
||||
),
|
||||
// Close the panel - the same road as Esc.
|
||||
div()
|
||||
.id("composer-panel-close")
|
||||
.size(28)
|
||||
.flex_none()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.rounded(6)
|
||||
.text_size(13)
|
||||
.text_color(t.dim)
|
||||
.cursor_pointer()
|
||||
.hover((s) => s.bg(t.hover).text_color(t.foreground))
|
||||
.on_click((event, cx) => on.close(cx))
|
||||
.child("✕"),
|
||||
]);
|
||||
}
|
||||
|
||||
/** One tab. */
|
||||
function renderTab(t, name, label, on, handlers) {
|
||||
return div()
|
||||
.id(`composer-panel-tab-${name}`)
|
||||
.px(10)
|
||||
.h(26)
|
||||
.flex()
|
||||
.items_center()
|
||||
.flex_none()
|
||||
.rounded(6)
|
||||
.text_size(12.5)
|
||||
.text_color(on ? t.foreground : t.dim)
|
||||
.when(on, (el) => el.bg(t.hover))
|
||||
.cursor_pointer()
|
||||
.on_click((event, cx) => handlers.tab(name, cx))
|
||||
.child(label);
|
||||
}
|
||||
|
||||
/** The list - virtual, so five hundred rows cost what twenty do. */
|
||||
function renderList(t, view, on) {
|
||||
const hits = view.state.hits;
|
||||
|
||||
return v_flex()
|
||||
.size_full()
|
||||
.relative()
|
||||
.child(
|
||||
v_virtual_list(
|
||||
"composer-panel-list",
|
||||
hits.length,
|
||||
ROW_HEIGHT,
|
||||
(index) => String(hits[index].item.id),
|
||||
(range) => hits.slice(range.start, range.end).map((hit, i) => renderRow(t, view, hit, range.start + i)),
|
||||
)
|
||||
.track_scroll(view.scroll)
|
||||
.size_full()
|
||||
.on_item_click((key, cx) => on.pick(key, cx))
|
||||
.on_item_secondary_click((key, event, cx) => on.toggle(key, cx)),
|
||||
)
|
||||
.child(Scrollbar.vertical("composer-panel-list").absolute().inset_0());
|
||||
}
|
||||
|
||||
/** One row: the text with the match lit, the line under it, the star. */
|
||||
function renderRow(t, view, hit, index) {
|
||||
const on = index === view.index;
|
||||
const fav = view.isFavorite(hit.item.text);
|
||||
|
||||
return h_flex()
|
||||
.id(`composer-panel-row-${hit.item.id}`)
|
||||
.h(ROW_HEIGHT)
|
||||
.gap(10)
|
||||
.px(10)
|
||||
.py(7)
|
||||
.items_start()
|
||||
.rounded(7)
|
||||
.when(on, (el) => el.bg(t.hover))
|
||||
.child(
|
||||
v_flex()
|
||||
.flex_1()
|
||||
.min_w(0)
|
||||
.gap(2)
|
||||
.child(renderText(t, hit))
|
||||
.child(
|
||||
div()
|
||||
.text_size(11.5)
|
||||
.text_color(t.dim)
|
||||
.truncate()
|
||||
.child(entryMeta(hit.item, view.tab)),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.flex_none()
|
||||
.size(24)
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.text_size(14)
|
||||
.text_color(fav ? t.working : t.dim)
|
||||
.child(fav ? "★" : "☆"),
|
||||
);
|
||||
}
|
||||
|
||||
/** The text of a row: two lines, the parts that match the query lit. */
|
||||
function renderText(t, hit) {
|
||||
const parts = [];
|
||||
for (const part of segments(hit.item.text, hit.ranges)) {
|
||||
// Words are separate children so the line breaks between words; a newline
|
||||
// in the message is one space here.
|
||||
for (const word of part.text.replace(/\s+/g, " ").match(/\S+\s*|\s+/g) ?? []) {
|
||||
parts.push(
|
||||
div()
|
||||
.flex_none()
|
||||
.text_size(12.8)
|
||||
.text_color(t.foreground)
|
||||
.when(part.hit, (el) => el.bg(t.selected).rounded(2))
|
||||
.child(word),
|
||||
);
|
||||
}
|
||||
}
|
||||
return h_flex().flex_wrap().h(TEXT_HEIGHT).overflow_hidden().children(parts);
|
||||
}
|
||||
|
||||
/** What is said when there is nothing to list. */
|
||||
function renderEmpty(t, view, on) {
|
||||
const { empty } = view.state;
|
||||
const [title, body] =
|
||||
empty === "history"
|
||||
? ["Historia jest pusta", "Wysłane wiadomości pojawią się tutaj — z każdej przestrzeni i od każdego agenta."]
|
||||
: empty === "favorites"
|
||||
? ["Brak ulubionych", "Kliknij ☆ przy edytorze, aby zapisać prompt na stałe."]
|
||||
: [`Brak wyników dla „${view.query.trim()}”`, "Spróbuj krótszego fragmentu albo"];
|
||||
|
||||
return v_flex()
|
||||
.id("composer-panel-empty")
|
||||
.size_full()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap(4)
|
||||
.px(16)
|
||||
.child(div().text_size(13).text_color(t.foreground).child(title))
|
||||
.child(div().text_size(12).text_color(t.dim).child(body))
|
||||
.when(empty === "query", (el) =>
|
||||
el.child(
|
||||
div()
|
||||
.id("composer-panel-clear-query")
|
||||
.mt(4)
|
||||
.px(10)
|
||||
.h(26)
|
||||
.flex()
|
||||
.items_center()
|
||||
.rounded(6)
|
||||
.bg(t.chrome)
|
||||
.text_size(12)
|
||||
.text_color(t.muted)
|
||||
.cursor_pointer()
|
||||
.hover((s) => s.bg(t.hover).text_color(t.foreground))
|
||||
.on_click((event, cx) => on.clear(cx))
|
||||
.child("wyczyść wyszukiwanie"),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** The line of keys at the bottom. */
|
||||
function renderFoot(t) {
|
||||
const keys = [
|
||||
"↑↓ wybór",
|
||||
"Enter wstaw w miejscu kursora (nie wysyła)",
|
||||
"Tab Historia/Ulubione",
|
||||
"Ctrl+D ulubiony",
|
||||
"Esc wróć do edytora",
|
||||
];
|
||||
|
||||
return h_flex()
|
||||
.id("composer-panel-foot")
|
||||
.gap(14)
|
||||
.flex_wrap()
|
||||
.px(12)
|
||||
.py(6)
|
||||
.border_t(1)
|
||||
.border_color(t.border)
|
||||
.text_size(11.5)
|
||||
.text_color(t.dim)
|
||||
.children(keys.map((text) => div().child(text)));
|
||||
}
|
||||
|
||||
/**
|
||||
* The preview of an image: the whole image on a dark scrim, its name and size
|
||||
* under it. A click or Esc closes it (main.js).
|
||||
*
|
||||
* @param {Record<string,string>} t
|
||||
* @param {{path:string, caption:string}} preview
|
||||
* @param {object} handle - FocusHandle of the overlay
|
||||
* @param {{close: (cx:any) => void}} on
|
||||
*/
|
||||
export function renderPreview(t, preview, handle, on) {
|
||||
return v_flex()
|
||||
.id("composer-preview")
|
||||
.track_focus(handle)
|
||||
.key_context("herdr-composer-preview")
|
||||
.on_key_down((event, cx) => {
|
||||
if (String(event.key).toLowerCase() === "escape") {
|
||||
on.close(cx);
|
||||
cx.stop_propagation();
|
||||
}
|
||||
})
|
||||
.absolute()
|
||||
.inset_0()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.gap(8)
|
||||
.p(16)
|
||||
.bg("#000000cc")
|
||||
.cursor_pointer()
|
||||
.on_click((event, cx) => on.close(cx))
|
||||
.child(image(preview.path).max_w("90%").max_h("80%").rounded(8))
|
||||
.child(div().text_size(12).text_color(t.muted).child(preview.caption));
|
||||
}
|
||||
@@ -0,0 +1,485 @@
|
||||
// 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 the address of the agent
|
||||
// (`AgentInfo.address`, e.g. "t2"): 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 {"adding"|"ready"|"error"} AttachmentState
|
||||
* @typedef {object} Attachment
|
||||
* @property {string} id
|
||||
* @property {string} name
|
||||
* @property {string} path
|
||||
* @property {string} [remotePath] - the path the agent sees (`hc put`)
|
||||
* @property {number} bytes
|
||||
* @property {AttachmentKind} kind
|
||||
* @property {AttachmentState} state
|
||||
* @property {string} [error]
|
||||
*
|
||||
* @typedef {"queued"|"countdown"|"sending"|"held"|"uncertain"} QueueItemState
|
||||
* @typedef {object} QueueItem
|
||||
* @property {string} id
|
||||
* @property {string} text
|
||||
* @property {QueueItemState} state
|
||||
* @property {number} createdAt
|
||||
* @property {number} [left]
|
||||
* @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<string,string>} drafts
|
||||
* @property {Record<string,number>} carets
|
||||
* @property {Record<string,Attachment[]>} attachments
|
||||
* @property {Record<string,QueueItem[]>} queue
|
||||
* @property {Notice|null} notice
|
||||
* @property {MenuState|null} menu
|
||||
* @property {null} conflict
|
||||
*/
|
||||
|
||||
/** Seconds between the end of the agent's turn and the send of the queue. */
|
||||
export const COUNTDOWN_SECONDS = 3;
|
||||
|
||||
/** @returns {State} */
|
||||
export function createState() {
|
||||
return {
|
||||
drafts: {},
|
||||
carets: {},
|
||||
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 },
|
||||
...(Number.isInteger(action.caret)
|
||||
? { carets: { ...(state.carets ?? {}), [action.agent]: action.caret } }
|
||||
: {}),
|
||||
};
|
||||
|
||||
case "restore_draft":
|
||||
return restoreDraft(state, action);
|
||||
|
||||
case "hold_queue":
|
||||
return holdQueue(state, action.agent);
|
||||
|
||||
case "countdown_start":
|
||||
return countdownStart(state, action);
|
||||
|
||||
case "countdown_tick":
|
||||
return mapItem(state, action, (item) =>
|
||||
item.state === "countdown" ? { ...item, left: Math.max(0, (item.left ?? 0) - 1) } : item,
|
||||
);
|
||||
|
||||
case "countdown_cancel":
|
||||
return mapItem(state, action, (item) => (item.state === "countdown" ? toState(item, "held") : item));
|
||||
|
||||
case "countdown_reset":
|
||||
return mapItem(state, action, (item) => (item.state === "countdown" ? toState(item, "queued") : item));
|
||||
|
||||
case "hold_all":
|
||||
return holdQueue(state, action.agent, { sending: false });
|
||||
|
||||
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 "attachment_update":
|
||||
return attachmentUpdate(state, action);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One attachment changes: it was added to the agent (`ready` with the path
|
||||
* the agent sees), it failed (`error`), or it is tried again (`adding`). An
|
||||
* `error` text belongs to the `error` state only.
|
||||
*/
|
||||
function attachmentUpdate(state, action) {
|
||||
const files = list(state.attachments, action.agent);
|
||||
const file = files.find((entry) => entry.id === action.id);
|
||||
if (!file) return state;
|
||||
|
||||
const { error, ...rest } = file;
|
||||
const next = { ...rest, ...action.patch };
|
||||
if (next.state === "error") next.error = action.patch?.error ?? error ?? "";
|
||||
else delete next.error;
|
||||
|
||||
return {
|
||||
...state,
|
||||
attachments: {
|
||||
...state.attachments,
|
||||
[action.agent]: files.map((entry) => (entry.id === action.id ? next : entry)),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The draft of an agent comes back from the disk.
|
||||
*
|
||||
* The draft carries the identity of the terminal it was written for. The
|
||||
* address (`t2`) can be reused by another terminal after a restart, so the
|
||||
* identity is compared EVERY time - also when the person already typed
|
||||
* something (`keepCurrent`: the text and the files they have now are not
|
||||
* overwritten) and also when there is no draft at all.
|
||||
*
|
||||
* The queue is trusted only when the live `created_ms` is known and equals the
|
||||
* saved one. Otherwise the whole queue is held, so nothing goes on its own to
|
||||
* an agent it was not written for: an unknown live identity counts as a
|
||||
* mismatch. The notice appears when the two identities differ (null/null is
|
||||
* "cannot tell": the queue is held, but there is nothing to say). An
|
||||
* `uncertain` entry stays `uncertain`: it has no "send now" button, and
|
||||
* "held" has.
|
||||
*/
|
||||
function restoreDraft(state, action) {
|
||||
const draft = action.draft && typeof action.draft.text === "string" ? action.draft : null;
|
||||
const agent = action.agent;
|
||||
const live = action.identity?.created_ms ?? null;
|
||||
|
||||
let next = state;
|
||||
if (draft && !action.keepCurrent) {
|
||||
next = {
|
||||
...state,
|
||||
drafts: { ...state.drafts, [agent]: draft.text },
|
||||
carets: { ...(state.carets ?? {}), [agent]: Number.isInteger(draft.caret) ? draft.caret : draft.text.length },
|
||||
attachments: {
|
||||
...state.attachments,
|
||||
// A file that was still being added when the app went down is not on
|
||||
// the agent: the tile says so and can be tried again.
|
||||
[agent]: (draft.attachments ?? []).map((file) =>
|
||||
file.state === "adding"
|
||||
? { ...file, state: "error", error: "Dodawanie przerwane — ponów." }
|
||||
: { ...file },
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Without a draft there is no saved identity to compare - only an unknown
|
||||
// live identity is a reason to hold.
|
||||
const saved = draft ? (draft.identity?.created_ms ?? null) : live;
|
||||
if (live !== null && live === saved) return next;
|
||||
|
||||
const held = holdQueue(next, agent);
|
||||
if (draft && saved !== live) {
|
||||
return { ...held, notice: { text: "Szkic z poprzedniej sesji agenta", level: "warn" } };
|
||||
}
|
||||
return held;
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything that could go out on its own waits for the person.
|
||||
*
|
||||
* `hold_queue` (identity doubt) also takes the entry that is on the wire;
|
||||
* `hold_all` (the person stopped the agent) leaves `sending` alone - its fate
|
||||
* is not known yet and `settle` decides it.
|
||||
*/
|
||||
function holdQueue(state, agent, { sending = true } = {}) {
|
||||
const items = list(state.queue, agent);
|
||||
const holdable = (item) =>
|
||||
item.state === "queued" || item.state === "countdown" || (sending && item.state === "sending");
|
||||
if (!items.some(holdable)) return state;
|
||||
return {
|
||||
...state,
|
||||
queue: {
|
||||
...state.queue,
|
||||
[agent]: items.map((item) => (holdable(item) ? toState(item, "held") : item)),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The entry in another state, without the seconds of a countdown. */
|
||||
function toState(item, next) {
|
||||
const { left, ...rest } = item;
|
||||
return { ...rest, state: next };
|
||||
}
|
||||
|
||||
/** One entry of the queue changes; the rest stays. Nothing changes - same state back. */
|
||||
function mapItem(state, action, change) {
|
||||
const items = list(state.queue, action.agent);
|
||||
const item = items.find((entry) => entry.id === action.id);
|
||||
if (!item) return state;
|
||||
const changed = change(item);
|
||||
if (changed === item) return state;
|
||||
return {
|
||||
...state,
|
||||
queue: { ...state.queue, [action.agent]: items.map((entry) => (entry.id === action.id ? changed : entry)) },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The countdown starts for the first `queued` entry - and only when no other
|
||||
* entry is counting or on the wire. An `uncertain` entry before it does not
|
||||
* matter: it is never sent on its own and is left as it is.
|
||||
*/
|
||||
function countdownStart(state, action) {
|
||||
const items = list(state.queue, action.agent);
|
||||
if (items.some((item) => item.state === "countdown" || item.state === "sending")) return state;
|
||||
const first = items.find((item) => item.state === "queued");
|
||||
if (!first || first.id !== action.id) return state;
|
||||
return mapItem(state, action, (item) => ({ ...item, state: "countdown", left: COUNTDOWN_SECONDS }));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 - and so does an `uncertain` one: the
|
||||
* person looked at "Nie potwierdzono" and chose "Ponów", knowing the message
|
||||
* may have reached the agent. Only their click does this; nothing else ever
|
||||
* sends an uncertain entry again.
|
||||
*
|
||||
* 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" && item.state !== "uncertain")) 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" && item.state !== "countdown")) return state;
|
||||
return {
|
||||
...state,
|
||||
queue: {
|
||||
...state.queue,
|
||||
[action.agent]: items.map((entry) =>
|
||||
entry.id === action.id ? { ...toState(entry, "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.remotePath !== undefined ? { remotePath: file.remotePath } : {}),
|
||||
...(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 } : {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,578 @@
|
||||
// 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} sentAt
|
||||
* @property {string} agent
|
||||
* @property {string} agentName
|
||||
* @property {string} space
|
||||
* @property {string} spaceName
|
||||
* @property {string} [tabName]
|
||||
*
|
||||
* @typedef {object} FavoriteEntry
|
||||
* @property {string} id
|
||||
* @property {string} text
|
||||
* @property {number} createdAt
|
||||
*
|
||||
* @typedef {object} QueueEntry
|
||||
* @property {string} id
|
||||
* @property {string} text
|
||||
* @property {"queued"|"countdown"|"sending"|"held"|"uncertain"} state
|
||||
* @property {number} createdAt
|
||||
* @property {number} [left]
|
||||
* @property {string} [reason]
|
||||
*/
|
||||
|
||||
/** The states a queue entry may be in (the ones state.js knows). */
|
||||
const QUEUE_STATES = new Set(["queued", "countdown", "sending", "held", "uncertain"]);
|
||||
|
||||
/**
|
||||
* The composer used to be called `ovis-composer`, and what it kept lives under
|
||||
* keys with that prefix. Every `load*` reads the new key first; when there is
|
||||
* none it reads the old one and - if there is something worth keeping - writes
|
||||
* it under the new key. The old keys are never touched.
|
||||
*/
|
||||
const PREFIX = "herdr-composer.";
|
||||
export const LEGACY_PREFIX = "ovis-composer.";
|
||||
|
||||
/** The keys the composer writes into the shared store. */
|
||||
export const KEYS = {
|
||||
history: "herdr-composer.history",
|
||||
favorites: "herdr-composer.favorites",
|
||||
usage: "herdr-composer.usage",
|
||||
/** The height (layout px) the person dragged the composer to; 0 or none: not set. */
|
||||
userMin: "herdr-composer.userMin",
|
||||
/** The queue is per agent: `herdr-composer.queue:<agent>`. */
|
||||
queue: "herdr-composer.queue",
|
||||
/** The draft is per agent: `herdr-composer.draft:<agent>`. */
|
||||
draft: "herdr-composer.draft",
|
||||
};
|
||||
|
||||
/** 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, isHistoryEntry, toHistoryEntry);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Store} store
|
||||
* @param {HistoryEntry[]} items
|
||||
* @returns {void}
|
||||
*/
|
||||
export function saveHistory(store, items) {
|
||||
writeList(store, KEYS.history, items, HISTORY_LIMIT, isHistoryEntry, toHistoryEntry);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, isFavoriteEntry, toFavoriteEntry);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Store} store
|
||||
* @param {FavoriteEntry[]} items
|
||||
* @returns {void}
|
||||
*/
|
||||
export function saveFavorites(store, items) {
|
||||
writeList(store, KEYS.favorites, items, FAVORITES_LIMIT, isFavoriteEntry, toFavoriteEntry);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* The key of one agent's draft.
|
||||
*
|
||||
* @param {string} agent
|
||||
* @returns {string}
|
||||
*/
|
||||
export function draftKey(agent) {
|
||||
return `${KEYS.draft}:${agent}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef {object} DraftIdentity
|
||||
* @property {number|null} created_ms - when the terminal was created (`hc get`)
|
||||
* @property {string|null} app
|
||||
*
|
||||
* @typedef {object} Draft
|
||||
* @property {string} text
|
||||
* @property {number} caret
|
||||
* @property {object[]} attachments
|
||||
* @property {DraftIdentity} identity - who the draft was written for: the
|
||||
* address can be reused by another terminal after a restart
|
||||
* @property {number} savedAt
|
||||
*/
|
||||
|
||||
/**
|
||||
* The draft of one agent, or nothing when there is none (or it is rubbish).
|
||||
*
|
||||
* The text is kept whole: the limit of 20 000 characters is a limit of the
|
||||
* send, not of the draft - a long text must survive a restart.
|
||||
*
|
||||
* @param {Store} store
|
||||
* @param {string} agent
|
||||
* @returns {Draft|null}
|
||||
*/
|
||||
export function loadDraft(store, agent) {
|
||||
if (typeof agent !== "string" || agent === "") return null;
|
||||
return loadMigrating(store, draftKey(agent), toDraft, (draft) => draft !== null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the draft of one agent. An empty draft is written too - it replaces
|
||||
* the one that was sent. What is not a draft is not written.
|
||||
*
|
||||
* @param {Store} store
|
||||
* @param {string} agent
|
||||
* @param {Draft} draft
|
||||
* @returns {void}
|
||||
*/
|
||||
export function saveDraft(store, agent, draft) {
|
||||
if (typeof agent !== "string" || agent === "") return;
|
||||
const clean = toDraft(draft);
|
||||
if (!clean) return;
|
||||
// A terminal whose start time could not be read must not wipe the start
|
||||
// time that is already on the disk: the next restart compares against it.
|
||||
if (clean.identity.created_ms === null) {
|
||||
const stored = toDraft(read(store, draftKey(agent)));
|
||||
if (stored && stored.identity.created_ms !== null) clean.identity = stored.identity;
|
||||
}
|
||||
write(store, draftKey(agent), clean);
|
||||
}
|
||||
|
||||
/**
|
||||
* A draft in the shape the composer insists on, or null.
|
||||
*
|
||||
* @param {unknown} value
|
||||
* @returns {Draft|null}
|
||||
*/
|
||||
function toDraft(value) {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
const raw = /** @type {Record<string, any>} */ (value);
|
||||
if (typeof raw.text !== "string") return null;
|
||||
|
||||
const caret = isTime(raw.caret) ? Math.max(0, Math.min(Math.trunc(raw.caret), raw.text.length)) : raw.text.length;
|
||||
const attachments = Array.isArray(raw.attachments)
|
||||
? raw.attachments.filter(
|
||||
(file) => file && typeof file === "object" && isText(file.id) && isText(file.name) && isText(file.path),
|
||||
)
|
||||
: [];
|
||||
const id = raw.identity && typeof raw.identity === "object" ? raw.identity : {};
|
||||
|
||||
return {
|
||||
text: raw.text,
|
||||
caret,
|
||||
attachments,
|
||||
identity: {
|
||||
created_ms: isTime(id.created_ms) ? id.created_ms : null,
|
||||
app: typeof id.app === "string" ? id.app : null,
|
||||
},
|
||||
savedAt: isTime(raw.savedAt) ? raw.savedAt : 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The height the person dragged the composer block to (layout px). 0 is "not
|
||||
* set"; anything that is not a positive number is not a height.
|
||||
*
|
||||
* @param {Store} store
|
||||
* @returns {number}
|
||||
*/
|
||||
export function loadUserMin(store) {
|
||||
return loadMigrating(
|
||||
store,
|
||||
KEYS.userMin,
|
||||
(value) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0),
|
||||
(px) => px > 0,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Store} store
|
||||
* @param {number} px - 0 clears it; what is not a number is not written
|
||||
* @returns {void}
|
||||
*/
|
||||
export function saveUserMin(store, px) {
|
||||
if (typeof px !== "number" || !Number.isFinite(px) || px < 0) return;
|
||||
write(store, KEYS.userMin, Math.round(px));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<string, number>}
|
||||
*/
|
||||
export function loadUsage(store) {
|
||||
return loadMigrating(
|
||||
store,
|
||||
KEYS.usage,
|
||||
(raw) => {
|
||||
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;
|
||||
},
|
||||
(counts) => Object.keys(counts).length > 0,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Store} store
|
||||
* @param {Record<string, number>} 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<string, unknown>) => boolean} isValid
|
||||
* @param {(entry:any) => any} [shape] - the entry in the shape the composer
|
||||
* uses today (an old entry gets what it lacks)
|
||||
* @returns {any[]}
|
||||
*/
|
||||
function readList(store, key, limit, isValid, shape) {
|
||||
return loadMigrating(
|
||||
store,
|
||||
key,
|
||||
(raw) => {
|
||||
const found = toList(raw, isValid);
|
||||
if (!found) return [];
|
||||
const list = shape ? found.map(shape) : found;
|
||||
return limit > 0 ? list.slice(-limit) : list;
|
||||
},
|
||||
(list) => list.length > 0,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a value under its key; when the key was never written, under the key
|
||||
* the composer had before it was renamed (`ovis-composer.*`).
|
||||
*
|
||||
* What is found under the old key is parsed like anything else (rubbish gives
|
||||
* the default), and only when the result is worth keeping the old value is
|
||||
* written under the new key. A store that cannot be written to does not break
|
||||
* the read. The old key stays as it was.
|
||||
*
|
||||
* @template T
|
||||
* @param {Store} store
|
||||
* @param {string} key - the new key (`herdr-composer.*`)
|
||||
* @param {(raw:unknown) => T} parse - the value as the composer uses it; `null` gives the default
|
||||
* @param {(parsed:T) => boolean} worthKeeping
|
||||
* @returns {T}
|
||||
*/
|
||||
function loadMigrating(store, key, parse, worthKeeping) {
|
||||
const current = read(store, key);
|
||||
if (current !== null && current !== undefined) return parse(current);
|
||||
if (!key.startsWith(PREFIX)) return parse(null);
|
||||
|
||||
const old = read(store, LEGACY_PREFIX + key.slice(PREFIX.length));
|
||||
if (old === null || old === undefined) return parse(null);
|
||||
|
||||
const parsed = parse(old);
|
||||
if (worthKeeping(parsed)) {
|
||||
try {
|
||||
write(store, key, old);
|
||||
} catch {
|
||||
// The data is read; it is written under the new key next time.
|
||||
}
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<string, unknown>) => boolean} isValid
|
||||
* @param {(entry:any) => any} [shape]
|
||||
* @returns {void}
|
||||
*/
|
||||
function writeList(store, key, items, limit, isValid, shape) {
|
||||
const source = listSource(items);
|
||||
// Rubbish in - nothing is written, so the stored list stays as it was.
|
||||
if (!source) return;
|
||||
|
||||
const valid = toList(source, isValid) ?? [];
|
||||
const list = shape ? valid.map(shape) : valid;
|
||||
// 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<string, unknown>) => 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<string, unknown>) => boolean} isValid
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isEntry(entry, isValid) {
|
||||
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return false;
|
||||
return isValid(/** @type {Record<string, unknown>} */ (entry));
|
||||
}
|
||||
|
||||
/**
|
||||
* A history entry the view can show: a text and the moment it was sent.
|
||||
* Entries from before the panel have the moment in `at`.
|
||||
*
|
||||
* @param {Record<string, unknown>} entry
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isHistoryEntry(entry) {
|
||||
return isText(entry.id) && isText(entry.text) && (isTime(entry.sentAt) || isTime(entry.at));
|
||||
}
|
||||
|
||||
/**
|
||||
* A favourite the view can show: a text and the moment it was marked
|
||||
* (`createdAt`, or `at` in the older entries).
|
||||
*
|
||||
* @param {Record<string, unknown>} entry
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isFavoriteEntry(entry) {
|
||||
return isText(entry.id) && isText(entry.text) && (isTime(entry.createdAt) || isTime(entry.at));
|
||||
}
|
||||
|
||||
/**
|
||||
* The history entry as it is kept today. An old entry lacks the names of the
|
||||
* agent and the space - they become empty texts, and `at` becomes `sentAt`.
|
||||
*
|
||||
* @param {any} entry
|
||||
* @returns {object}
|
||||
*/
|
||||
function toHistoryEntry(entry) {
|
||||
const { at, ...rest } = entry;
|
||||
return {
|
||||
...rest,
|
||||
sentAt: isTime(entry.sentAt) ? entry.sentAt : at,
|
||||
agent: isText(entry.agent) ? entry.agent : "",
|
||||
agentName: isText(entry.agentName) ? entry.agentName : "",
|
||||
space: isText(entry.space) ? entry.space : "",
|
||||
spaceName: isText(entry.spaceName) ? entry.spaceName : "",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {any} entry
|
||||
* @returns {object}
|
||||
*/
|
||||
function toFavoriteEntry(entry) {
|
||||
const { at, ...rest } = entry;
|
||||
return { ...rest, createdAt: isTime(entry.createdAt) ? entry.createdAt : 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<string, unknown>} 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);
|
||||
}
|
||||
@@ -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<string, Item[]>} 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;
|
||||
}
|
||||
@@ -0,0 +1,611 @@
|
||||
// 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, queueBlocksDirectSend } 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 "Wstrzymana — wyślij ręcznie";
|
||||
case "sending":
|
||||
return "Wysyłanie…";
|
||||
case "uncertain":
|
||||
return "Nie potwierdzono";
|
||||
case "countdown":
|
||||
return `Wysyłam za ${item.left} s`;
|
||||
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<string, object[]>}
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* May the composer send on its own for this agent? Only after its draft and
|
||||
* the identity of its terminal were checked (see main.js `restoreDraft`): the
|
||||
* queue comes back from the disk before that, and an address can belong to a
|
||||
* different terminal now.
|
||||
*
|
||||
* @param {Set<string>|null} ready - the agents whose check is done
|
||||
* @param {string} key
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function canAutoSend(ready, key) {
|
||||
return ready instanceof Set && ready.has(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the composer still talking to the agent whose draft the field shows?
|
||||
*
|
||||
* The field shows the draft of `before` (the agent the composer was synced to
|
||||
* when an event began). After a sync the focus may have moved: then the event
|
||||
* belongs to an agent that is not the target any more, and it must not touch
|
||||
* the draft or the queue of the new one.
|
||||
*
|
||||
* @param {{before:string, after:string, target:string}} keys - `before`: the
|
||||
* key the composer had before the sync; `after`: the key it has now;
|
||||
* `target`: the key of the agent under the focus ("" for none)
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function stillSameAgent({ before, after, target }) {
|
||||
return before !== "" && before === after && before === target;
|
||||
}
|
||||
|
||||
/**
|
||||
* Must a message that could go out now wait behind what is already in flight
|
||||
* or in the queue?
|
||||
*
|
||||
* - a message on the wire always goes first (`draining`);
|
||||
* - Ctrl+Enter (`mode "now"`) is the person's own order and does not wait;
|
||||
* - an answer to an agent that is `blocked` does not wait either: the queue
|
||||
* does not start while the agent waits for the person, so queueing the
|
||||
* answer would leave the agent waiting for ever - it goes ahead (with
|
||||
* `--force`) and the queue stays as it is;
|
||||
* - otherwise it waits when a message is queued or counting down.
|
||||
*
|
||||
* @param {{draining:boolean, mode:string, status:string, queue:object[]|undefined}} input
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function directSendBlocked({ draining, mode, status, queue }) {
|
||||
if (draining) return true;
|
||||
if (mode === "now" || status === "blocked") return false;
|
||||
return queueBlocksDirectSend(queue);
|
||||
}
|
||||
|
||||
// --- the height of the composer block ----------------------------------------
|
||||
//
|
||||
// The block is as tall as its content (menu, queue, notices, card, strip),
|
||||
// unless the person dragged its border: then that height is the floor.
|
||||
|
||||
/**
|
||||
* The height the block should have, in the pixels of the layout.
|
||||
*
|
||||
* What the content measures is in logical pixels (layout px times the zoom of
|
||||
* the app), plus the padding of the root; the floor is what the person dragged
|
||||
* the block to (`userMin`, 0 for none); the result stays inside the range the
|
||||
* layout allows.
|
||||
*
|
||||
* @param {{contentHeight:number, padding:number, zoom:number, userMin:number, min:number, max:number}} input
|
||||
* @returns {number}
|
||||
*/
|
||||
export function blockTargetPx({ contentHeight, padding, zoom, userMin, min, max }) {
|
||||
const factor = Number.isFinite(zoom) && zoom > 0 ? zoom : 1;
|
||||
const need = Math.ceil((contentHeight + padding) / factor);
|
||||
const wanted = Math.max(need, Number.isFinite(userMin) ? userMin : 0);
|
||||
return Math.round(Math.min(max, Math.max(min, wanted)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the difference worth a `layout.resize`? Under 5 px it is not: typing and
|
||||
* the growing of the field must not make the block twitch.
|
||||
*
|
||||
* @param {number|null|undefined} current
|
||||
* @param {number|null|undefined} target
|
||||
* @param {number} [threshold]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function shouldResize(current, target, threshold = 4) {
|
||||
if (!Number.isFinite(current) || !Number.isFinite(target)) return false;
|
||||
return Math.abs(current - target) > threshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is a reported height the person's drag?
|
||||
*
|
||||
* The composer keeps the height it ordered last (`orderedPx`); a height it did
|
||||
* not order is somebody dragging the border. Before anything was ordered the
|
||||
* first height is the layout's own, not a drag.
|
||||
*
|
||||
* @param {{reportedPx:number, orderedPx:number|null, tolerance?:number}} input
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isManualResize({ reportedPx, orderedPx, tolerance = 3 }) {
|
||||
if (!Number.isFinite(reportedPx) || !Number.isFinite(orderedPx)) return false;
|
||||
return Math.abs(reportedPx - orderedPx) > tolerance;
|
||||
}
|
||||
|
||||
// --- colors from the theme -----------------------------------------------------
|
||||
|
||||
/**
|
||||
* How light a color is (0 dark .. 1 light), from `#rgb`, `#rrggbb` or
|
||||
* `#rrggbbaa`; nothing for what is not such a color.
|
||||
*
|
||||
* @param {unknown} color
|
||||
* @returns {number|null}
|
||||
*/
|
||||
export function luminance(color) {
|
||||
if (typeof color !== "string") return null;
|
||||
let hex = color.trim();
|
||||
if (!/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(hex)) return null;
|
||||
hex = hex.slice(1);
|
||||
if (hex.length === 3) hex = hex.replace(/./g, "$&$&");
|
||||
const channel = (at) => parseInt(hex.slice(at, at + 2), 16) / 255;
|
||||
return 0.2126 * channel(0) + 0.7152 * channel(2) + 0.0722 * channel(4);
|
||||
}
|
||||
|
||||
/**
|
||||
* The background of an input field set into a panel: the darkest color the
|
||||
* theme names among the usual surfaces, so the field reads as a recess in the
|
||||
* panel whatever the theme. A theme with none to offer leaves the panel's own.
|
||||
*
|
||||
* @param {Record<string,string>} theme - `theme()`
|
||||
* @param {string} panelBackground - the background of the panel
|
||||
* @returns {string}
|
||||
*/
|
||||
export function fieldBackground(theme, panelBackground) {
|
||||
let best = null;
|
||||
let bestLight = Infinity;
|
||||
for (const key of ["background", "canvas", "pane", "surface", "chrome"]) {
|
||||
const light = luminance(theme?.[key]);
|
||||
if (light !== null && light < bestLight) {
|
||||
best = theme[key];
|
||||
bestLight = light;
|
||||
}
|
||||
}
|
||||
return best ?? panelBackground;
|
||||
}
|
||||
Reference in new issue
Block a user