feat: history and favorites model

Co-Authored-By: Ovis Fast (Claude) <[email protected]>
This commit is contained in:
FactorandOvis Fast committed 2026-11-19 11:31:37 +01:00
1 parent 86ca415d96
commit c655e46dbf
4 files changed
+353 -25

No files matched your search

+143
View File
@@ -0,0 +1,143 @@
// 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;
}
+41 -3
View File
@@ -41,6 +41,7 @@ import { detect as detectTrigger, rank, merge, startsLine } from "./suggest.js";
import * as catalog from "./catalog.js";
import { LIMITS, validateMany, mention, removeMention } from "./attachments.js";
import * as storage from "./storage.js";
import { record } from "./history.js";
import {
agentKey,
agentName,
@@ -87,6 +88,11 @@ export default class Composer extends View {
this.state = createState();
this.store = guardedStore({ get: shared, set: setShared });
// The one place every send of a message passes: the direct send, the
// queue, the countdown and "Wyślij teraz" all call `hc send` through it,
// so the history gets exactly one entry per send that `hc` accepted.
this.sendHc = (args) => this.runSend(args);
// Per agent: the turn gate, whether a drain is in flight, and whether the
// queue of that agent was read from the disk.
this.gates = new Map();
@@ -736,7 +742,7 @@ export default class Composer extends View {
this.persistQueue(key);
try {
const result = await sendToTerminal({ terminal: agent.address, hc }, message);
const result = await sendToTerminal({ terminal: agent.address, hc: this.sendHc }, message);
if (result.ok) {
this.state = reduce(this.state, { type: "settle", agent: key, id, outcome: "sent" });
this.persistQueue(key);
@@ -892,7 +898,7 @@ export default class Composer extends View {
{
agent: key,
terminal: agent.address,
hc,
hc: this.sendHc,
status: () => this.statusOf(agent),
// One message per turn: after the first send the gate is shut.
gate: () => !sent && gatePasses(this.gateFor(key), this.statusOf(agent)),
@@ -997,7 +1003,7 @@ export default class Composer extends View {
this.persistQueue(key);
try {
const result = await sendToTerminal({ terminal: agent.address, hc }, item.text);
const result = await sendToTerminal({ terminal: agent.address, hc: this.sendHc }, item.text);
if (result.ok) {
this.state = reduce(this.state, { type: "settle", agent: key, id, outcome: "sent" });
this.persistQueue(key);
@@ -1294,6 +1300,38 @@ export default class Composer extends View {
// --- the state on the disk -----------------------------------------------
/**
* `hc` for the sends: runs the call and, when it was a `send` that `hc`
* accepted (exit code 0 and no "error" in the JSON - `hcOk`), writes the
* message into the history. A history that cannot be written does not
* change the result of the send.
*/
async runSend(args) {
const res = await hc(args);
if (args[0] === "send" && hcOk(res)) this.recordSent(String(args[1]), String(args[2] ?? ""));
return res;
}
/** The history gets the message that went to the terminal. */
recordSent(address, text) {
try {
const agent = liveAgents().find((entry) => entry.address === address);
const entry = {
id: this.newId(),
text,
sentAt: Date.now(),
agent: address,
agentName: agent ? agentName(agent) : "",
space: agent?.space ?? "",
spaceName: agent?.space_name ?? "",
tabName: agent?.tab_name ?? "",
};
storage.saveHistory(this.store, record(storage.loadHistory(this.store), entry));
} catch (err) {
this.notice(`Nie udało się zapisać historii: ${errorText(err)}`, "error");
}
}
/** The queue of an agent goes to the disk at once - a crash must not send a message twice. */
persistQueue(key) {
try {
+61 -22
View File
@@ -35,22 +35,17 @@
* @typedef {object} HistoryEntry
* @property {string} id
* @property {string} text
* @property {number} at
* @property {number} sentAt
* @property {string} agent
* @property {string} agentName
* @property {string} space
* @property {string} spaceName
* @property {string} tab
* @property {string} pane
* @property {string|null} machine
* @property {string[]} attachments
* @property {"sent"|"queued"|"failed"} outcome
* @property {string} [tabName]
*
* @typedef {object} FavoriteEntry
* @property {string} id
* @property {string} text
* @property {number} at
* @property {string} agent
* @property {"history"|"manual"} source
* @property {number} createdAt
*
* @typedef {object} QueueEntry
* @property {string} id
@@ -101,7 +96,7 @@ export function queueKey(agent) {
* @returns {HistoryEntry[]}
*/
export function loadHistory(store) {
return readList(store, KEYS.history, HISTORY_LIMIT, isTextEntry);
return readList(store, KEYS.history, HISTORY_LIMIT, isHistoryEntry, toHistoryEntry);
}
/**
@@ -110,7 +105,7 @@ export function loadHistory(store) {
* @returns {void}
*/
export function saveHistory(store, items) {
writeList(store, KEYS.history, items, HISTORY_LIMIT, isTextEntry);
writeList(store, KEYS.history, items, HISTORY_LIMIT, isHistoryEntry, toHistoryEntry);
}
/**
@@ -121,7 +116,7 @@ export function saveHistory(store, items) {
* @returns {FavoriteEntry[]}
*/
export function loadFavorites(store) {
return readList(store, KEYS.favorites, FAVORITES_LIMIT, isTextEntry);
return readList(store, KEYS.favorites, FAVORITES_LIMIT, isFavoriteEntry, toFavoriteEntry);
}
/**
@@ -130,7 +125,7 @@ export function loadFavorites(store) {
* @returns {void}
*/
export function saveFavorites(store, items) {
writeList(store, KEYS.favorites, items, FAVORITES_LIMIT, isTextEntry);
writeList(store, KEYS.favorites, items, FAVORITES_LIMIT, isFavoriteEntry, toFavoriteEntry);
}
/**
@@ -302,11 +297,14 @@ export function saveUsage(store, counts) {
* @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) {
const list = toList(read(store, key), isValid);
if (!list) return [];
function readList(store, key, limit, isValid, shape) {
const found = toList(read(store, key), isValid);
if (!found) return [];
const list = shape ? found.map(shape) : found;
return limit > 0 ? list.slice(-limit) : list;
}
@@ -318,14 +316,16 @@ function readList(store, key, limit, isValid) {
* @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) {
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 list = toList(source, isValid) ?? [];
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;
@@ -366,14 +366,53 @@ function isEntry(entry, isValid) {
}
/**
* An entry the view can show - a history entry and a favourite have the same
* shape: a text and a moment.
* 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 isTextEntry(entry) {
return isText(entry.id) && isText(entry.text) && isTime(entry.at);
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 };
}
/**
+108
View File
@@ -0,0 +1,108 @@
import test from "node:test";
import assert from "node:assert/strict";
import { record, search, toggleFavorite, isFavorite } from "../mod/ovis-composer/history.js";
import { loadHistory, saveHistory, loadFavorites, saveFavorites, KEYS } from "../mod/ovis-composer/storage.js";
const memStore = () => {
const m = new Map();
return { get: (k) => m.get(k), set: (k, v) => void m.set(k, v) };
};
const entry = (i, text = `t${i}`, over = {}) => ({
id: `h${i}`, text, sentAt: i, agent: "t2", agentName: "claude-code", space: "s1", spaceName: "herdr", ...over,
});
test("record keeps duplicates", () => {
let list = record([], entry(1, "same"));
list = record(list, entry(2, "same"));
assert.equal(list.length, 2);
assert.deepEqual(list.map((e) => e.id), ["h1", "h2"]);
});
test("record keeps 500, the oldest drop out, and does not mutate", () => {
let list = [];
for (let i = 0; i < 500; i++) list.push(entry(i));
const before = list.length;
const out = record(list, entry(500));
assert.equal(list.length, before);
assert.equal(out.length, 500);
assert.equal(out[0].id, "h1");
assert.equal(out[499].id, "h500");
});
test("search is case-insensitive and returns ranges", () => {
const out = search([entry(1, "uruchom testy")], "TEST");
assert.equal(out.length, 1);
assert.deepEqual(out[0].ranges, [[8, 12]]);
assert.equal(out[0].item.text, "uruchom testy");
});
test("search finds every occurrence", () => {
const out = search([entry(1, "test a test")], "test");
assert.deepEqual(out[0].ranges, [[0, 4], [7, 11]]);
});
test("search folds Polish letters by case", () => {
assert.equal(search([entry(1, "jedziemy do łódź")], "ŁÓDŹ").length, 1);
assert.equal(search([entry(1, "JEDZIEMY DO ŁÓDŹ")], "łódź").length, 1);
assert.deepEqual(search([entry(1, "do ŁÓDŹ")], "łódź")[0].ranges, [[3, 7]]);
});
test("search: newest first; empty query gives everything; no match gives nothing", () => {
const list = [entry(1, "a"), entry(3, "b"), entry(2, "c")];
assert.deepEqual(search(list, "").map((r) => r.item.id), ["h3", "h2", "h1"]);
assert.deepEqual(search(list, " ").map((r) => r.item.id), ["h3", "h2", "h1"]);
assert.deepEqual(search(list, "").map((r) => r.ranges), [[], [], []]);
assert.deepEqual(search(list, "zzz"), []);
assert.deepEqual(search([], "x"), []);
});
test("search orders favourites by createdAt", () => {
const favs = [{ id: "a", text: "x", createdAt: 1 }, { id: "b", text: "x2", createdAt: 5 }];
assert.deepEqual(search(favs, "x").map((r) => r.item.id), ["b", "a"]);
});
test("toggleFavorite adds by trimmed text, removes on a second toggle", () => {
let favs = toggleFavorite([], " hello ", 10);
assert.equal(favs.length, 1);
assert.equal(favs[0].text, "hello");
assert.equal(favs[0].createdAt, 10);
assert.equal(isFavorite(favs, "hello "), true);
favs = toggleFavorite(favs, "hello", 20);
assert.deepEqual(favs, []);
assert.equal(isFavorite(favs, "hello"), false);
});
test("toggleFavorite: empty text changes nothing; limit 100 drops the oldest; ids are unique", () => {
const empty = [];
assert.equal(toggleFavorite(empty, " ", 1), empty);
let favs = [];
for (let i = 0; i < 101; i++) favs = toggleFavorite(favs, `f${i}`, 1000);
assert.equal(favs.length, 100);
assert.equal(favs[0].text, "f1");
assert.equal(new Set(favs.map((f) => f.id)).size, 100);
});
test("storage: old history entries load with empty space/agentName", () => {
const store = memStore();
store.set(KEYS.history, [{ id: "a", text: "old", at: 7, agent: "t2" }]);
const [e] = loadHistory(store);
assert.equal(e.sentAt, 7);
assert.equal(e.agentName, "");
assert.equal(e.space, "");
assert.equal(e.spaceName, "");
});
test("storage: history and favourites roundtrip in the new shape", () => {
const store = memStore();
saveHistory(store, [entry(1)]);
assert.deepEqual(loadHistory(store), [entry(1)]);
const fav = { id: "f", text: "x", createdAt: 3 };
saveFavorites(store, [fav]);
assert.deepEqual(loadFavorites(store), [fav]);
});
test("storage: old favourites (at) load as createdAt", () => {
const store = memStore();
store.set(KEYS.favorites, [{ id: "f", text: "x", at: 4 }]);
assert.equal(loadFavorites(store)[0].createdAt, 4);
});