Files
herdrMario/herdr/herdr-composer/mods/herdr-composer/storage.js
T
2026-11-19 15:57:40 +01:00

605 lines
19 KiB
JavaScript

// 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 {import("./dock.js").DockButton} DockButton
*
* @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]
*/
import { normalize as normalizeDock } from "./dock.js";
/** 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",
/** The buttons of the dock (dock.js). New in herdr-composer: no legacy key. */
dock: "herdr-composer.dock",
};
/** 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 buttons of the dock. Only what is a button comes back (dock.js
* `normalize`). The dock is new, so there is no `ovis-composer.dock` to read.
*
* @param {Store} store
* @returns {DockButton[]}
*/
export function loadDock(store) {
return normalizeDock(read(store, KEYS.dock));
}
/**
* @param {Store} store
* @param {DockButton[]} items
* @returns {void}
*/
export function saveDock(store, items) {
write(store, KEYS.dock, normalizeDock(items));
}
/**
* 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);
}