// state.js - the composer's state model. // // Pure: no GPUI, no herdr, no IO, no clock. `reduce` returns a new state and // never mutates the one it was given, so the model can be tested in plain Node // (tests/state.test.mjs) and reasoned about without a running app. // // Drafts, attachments and the queue are keyed by agent name ("claude-code", // "codex"): each belongs to the agent it was written for, and switching agents // must not lose any of them. import { onRestart } from "./delivery.js"; /** * @typedef {"image"|"file"} AttachmentKind * @typedef {"ready"|"error"} AttachmentState * @typedef {object} Attachment * @property {string} id * @property {string} name * @property {string} path * @property {number} bytes * @property {AttachmentKind} kind * @property {AttachmentState} state * @property {string} [error] * * @typedef {"queued"|"sending"|"held"|"uncertain"} QueueItemState * @typedef {object} QueueItem * @property {string} id * @property {string} text * @property {QueueItemState} state * @property {number} createdAt * @property {string} [reason] * * @typedef {object} Notice * @property {string} text * @property {string} [level] * * @typedef {object} MenuState * @property {boolean} open * @property {string|null} trigger * @property {object[]} items * @property {number} index * * @typedef {object} State * @property {Record} drafts * @property {Record} carets * @property {Record} attachments * @property {Record} queue * @property {Notice|null} notice * @property {MenuState|null} menu * @property {null} conflict */ /** @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 "send": return { ...state, drafts: { ...state.drafts, [action.agent]: "" } }; case "attach": return { ...state, attachments: { ...state.attachments, [action.agent]: [...list(state.attachments, action.agent), toAttachment(action.file)], }, }; case "removeAttachment": return { ...state, attachments: { ...state.attachments, [action.agent]: list(state.attachments, action.agent).filter((a) => a.id !== action.id), }, }; case "queue": return { ...state, queue: { ...state.queue, [action.agent]: [...list(state.queue, action.agent), toQueueItem(action.item)], }, }; case "restore": return restore(state, action); case "discard": return discard(state, action); case "requeue": return requeue(state, action); case "claim": return claim(state, action); case "settle": return settle(state, action); case "restart": return restart(state, action); case "notice": return { ...state, notice: action.notice ?? null }; default: return state; } } /** * The 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, [agent]: (draft.attachments ?? []).map((file) => ({ ...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. */ function holdQueue(state, agent) { const items = list(state.queue, agent); if (!items.some((item) => item.state !== "uncertain" && item.state !== "held")) return state; return { ...state, queue: { ...state.queue, [agent]: items.map((item) => item.state === "uncertain" || item.state === "held" ? item : { ...item, state: "held" }, ), }, }; } /** * The queue of an agent comes back from the disk. * * The entries are put back as they were written - in the state they were in * when the app went down. The `restart` action turns the ones that were on * the wire into `uncertain`. */ function restore(state, action) { const items = Array.isArray(action.items) ? action.items : []; return { ...state, queue: { ...state.queue, [action.agent]: items.map((item) => ({ ...item })), }, }; } /** * The entry is dropped: the person does not want it any more. * * Nothing is sent and nothing is written to the terminal - the entry only * leaves the queue. */ function discard(state, action) { const items = list(state.queue, action.agent); if (!items.some((item) => item.id === action.id)) return state; return { ...state, queue: { ...state.queue, [action.agent]: items.filter((item) => item.id !== action.id), }, }; } /** * A held entry goes back to the queue. * * The hold said "the agent is waiting for you"; the person answered by asking * for the message to go out anyway. The entry waits in the queue like any * other and its reason goes with the hold. The turn gate of the agent is the * view's business - it steps aside for a send outside a turn. */ function requeue(state, action) { const items = list(state.queue, action.agent); const item = items.find((entry) => entry.id === action.id); if (!item || item.state !== "held") return state; return { ...state, queue: { ...state.queue, [action.agent]: items.map((entry) => entry.id === action.id ? withoutReason({ ...entry, state: "queued" }) : entry, ), }, }; } /** The entry without its reason - the reason belonged to the hold. */ function withoutReason(item) { const { reason, ...rest } = item; return rest; } /** * The entry goes on the wire: a `queued` entry becomes `sending`, and the * composer shows it as in flight. * * Only `queued` entries are claimed. A `held` entry waits for the user and an * `uncertain` one may already have reached the agent - claiming either of * them would send the same message twice, so they stay as they are. */ function claim(state, action) { const items = list(state.queue, action.agent); const item = items.find((entry) => entry.id === action.id); if (!item || item.state !== "queued") return state; return { ...state, queue: { ...state.queue, [action.agent]: items.map((entry) => entry.id === action.id ? { ...entry, state: "sending" } : entry, ), }, }; } /** * The entry's fate is known: `sent` drops it from the queue, `held` and * `uncertain` keep it with a reason to show. */ function settle(state, action) { const items = list(state.queue, action.agent); if (!items.some((item) => item.id === action.id)) return state; if (action.outcome === "sent") { return { ...state, queue: { ...state.queue, [action.agent]: items.filter((item) => item.id !== action.id) }, }; } if (action.outcome !== "held" && action.outcome !== "uncertain") return state; return { ...state, queue: { ...state.queue, [action.agent]: items.map((item) => item.id === action.id ? { ...item, state: action.outcome, ...(action.reason ? { reason: action.reason } : {}) } : item, ), }, }; } /** * The app restarted: an entry that was on the wire may or may not have reached * the agent, so it becomes `uncertain` - it is never sent again on its own. * Only the queue of that agent is touched. */ function restart(state, action) { const items = list(state.queue, action.agent); if (items.length === 0) return state; return { ...state, queue: { ...state.queue, [action.agent]: onRestart(items), }, }; } /** The list of one agent - an agent without entries yet has an empty list. */ function list(map, agent) { return map[agent] ?? []; } /** The caller names the file; the model only fills in the defaults. */ function toAttachment(file) { return { id: file.id, name: file.name, path: file.path, bytes: file.bytes, kind: file.kind ?? "file", state: file.state ?? "ready", ...(file.error !== undefined ? { error: file.error } : {}), }; } /** The caller names the entry and stamps it; the model defaults the rest. */ function toQueueItem(item) { if (!item || !Number.isFinite(item.createdAt)) { // A missing timestamp would sort as epoch 0 and silently misorder the // queue - the caller has to say when the entry was written. throw new TypeError("queue entry needs a createdAt timestamp"); } return { id: item.id, text: item.text, state: item.state ?? "queued", createdAt: item.createdAt, ...(item.reason !== undefined ? { reason: item.reason } : {}), }; }