Files
herdrMario/mod/ovis-composer/state.js
T
2026-11-19 12:10:53 +01:00

486 lines
15 KiB
JavaScript

// 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 } : {}),
};
}