From 2ce1b45ee4c13164cffd3124c42f88443bd472fa Mon Sep 17 00:00:00 2001 From: Factor Date: Thu, 19 Nov 2026 11:14:54 +0100 Subject: [PATCH] feat: persistent per-agent drafts with identity check Co-Authored-By: Ovis Fast (Claude) --- mod/ovis-composer/main.js | 137 ++++++++++++++++++++++++++++++++--- mod/ovis-composer/state.js | 53 +++++++++++++- mod/ovis-composer/storage.js | 88 ++++++++++++++++++++++ tests/state.test.mjs | 41 +++++++++++ tests/storage.test.mjs | 58 +++++++++++++++ 5 files changed, 367 insertions(+), 10 deletions(-) diff --git a/mod/ovis-composer/main.js b/mod/ovis-composer/main.js index 5549abe..9e98f54 100644 --- a/mod/ovis-composer/main.js +++ b/mod/ovis-composer/main.js @@ -94,6 +94,14 @@ export default class Composer extends View { this.waiting = new Set(); this.restored = new Set(); + // Drafts: the identity of each terminal (`hc get`, cached per address), + // the agents whose draft was read from the disk (or is being read), and + // the timer that writes the draft 500 ms after the last change. + this.identities = new Map(); + this.draftReady = new Set(); + this.draftLoading = new Set(); + this.draftTimer = null; + // The menu of suggestions: what it shows, which row is picked. this.menu = null; this.debounce = null; @@ -178,6 +186,7 @@ export default class Composer extends View { /** The copy is gone - it must not take the keyboard with it. */ close(cx) { this.closed = true; + this.saveDraftNow(); } // --- the agent ----------------------------------------------------------- @@ -199,24 +208,124 @@ export default class Composer extends View { const key = agent ? agentKey(agent) : ""; if (key === this.currentKey) return; - if (this.currentKey) { - this.state = reduce(this.state, { - type: "draft", - agent: this.currentKey, - text: this.textarea.value(), - }); - } + // The draft of the agent we leave goes to the disk at once. + this.saveDraftNow(); this.currentKey = key; if (!key) return; this.restoreQueue(key); + this.showDraft(key); + this.restoreDraft(agent, key, cx); + cx.notify(); + } + /** The draft of the agent (and its caret) goes into the field. */ + showDraft(key) { const draft = this.state.drafts[key] ?? ""; if (draft !== this.textarea.value()) { this.textarea.set_value(draft); this.value = draft; } - cx.notify(); + const caret = this.state.carets?.[key]; + this.restoreCaret(Number.isInteger(caret) ? Math.min(caret, draft.length) : draft.length); + } + + /** + * The draft of an agent comes back from the disk - once per address. + * + * The identity of the terminal (`created_ms` from `hc get`) says whether it + * is the terminal the draft was written for. Nothing is written to the disk + * for the agent before this is done: a draft written with an identity that + * is not known yet would wipe the one that is waiting there. + */ + restoreDraft(agent, key, cx) { + if (this.draftReady.has(key) || this.draftLoading.has(key)) return; + this.draftLoading.add(key); + + cx.spawn(async (cx) => { + try { + const identity = await this.fetchIdentity(agent); + this.identities.set(key, identity); + + const stored = storage.loadDraft(this.store, key); + const here = key === this.currentKey; + const typed = here ? this.textarea.value() : (this.state.drafts[key] ?? ""); + const untouched = typed === "" && (this.state.attachments[key] ?? []).length === 0; + + // What the person typed while the identity was read is not + // overwritten. + if (stored && untouched) { + this.state = reduce(this.state, { type: "restore_draft", agent: key, draft: stored, identity }); + this.persistQueue(key); + if (here) this.showDraft(key); + } + } catch { + // The draft stays on the disk; the next switch to this agent tries again. + this.draftLoading.delete(key); + return; + } + this.draftLoading.delete(key); + this.draftReady.add(key); + cx.notify(); + }); + } + + /** Who the terminal is: when it was created (`hc get`) and its program. */ + async fetchIdentity(agent) { + const app = typeof agent.app === "string" && agent.app.trim() !== "" ? agent.app.trim() : null; + try { + const res = await hc(["get", agent.address, "--json"]); + const payload = hcOk(res) ? parseJson(res.stdout) : null; + const created = payload && Number.isFinite(payload.created_ms) ? payload.created_ms : null; + return { created_ms: created, app }; + } catch { + return { created_ms: null, app }; + } + } + + /** The draft goes to the disk 500 ms after the last change. */ + scheduleDraftSave(cx) { + if (this.draftTimer) { + this.draftTimer.cancel(); + this.draftTimer = null; + } + this.draftTimer = cx.timer.after(500, () => { + this.draftTimer = null; + this.saveDraftNow(); + }); + } + + /** The draft of the agent under the focus goes to the disk now. */ + saveDraftNow() { + if (this.draftTimer) { + this.draftTimer.cancel(); + this.draftTimer = null; + } + const key = this.currentKey; + if (!key) return; + + // The field is the truth: the state follows it. + this.state = reduce(this.state, { + type: "draft", + agent: key, + text: this.textarea.value(), + caret: this.caret(), + }); + + const identity = this.identities.get(key); + if (!identity || !this.draftReady.has(key)) return; + + try { + storage.saveDraft(this.store, key, { + text: this.state.drafts[key] ?? "", + caret: this.state.carets?.[key] ?? 0, + attachments: this.state.attachments[key] ?? [], + identity, + savedAt: Date.now(), + }); + } catch (err) { + this.notice(`Nie udało się zapisać szkicu: ${errorText(err)}`, "error"); + } } /** The queue of an agent comes back from the disk; what was on the wire is uncertain. */ @@ -276,7 +385,13 @@ export default class Composer extends View { const agent = this.target(); if (agent) { - this.state = reduce(this.state, { type: "draft", agent: agentKey(agent), text: next }); + this.state = reduce(this.state, { + type: "draft", + agent: agentKey(agent), + text: next, + caret: this.caret(), + }); + this.scheduleDraftSave(cx); } // The newline of the keyboard does not move the menu. @@ -500,6 +615,8 @@ export default class Composer extends View { this.value = ""; this.enterText = null; this.closeMenu(); + // A sent draft must not come back after a restart. + this.scheduleDraftSave(cx); cx.notify(); } @@ -1023,6 +1140,7 @@ export default class Composer extends View { ); this.textarea.set_value(result.value); this.value = result.value; + this.scheduleDraftSave(cx); cx.notify(); }); } @@ -1040,6 +1158,7 @@ export default class Composer extends View { this.textarea.set_value(text); this.value = text; } + this.scheduleDraftSave(cx); cx.notify(); } diff --git a/mod/ovis-composer/state.js b/mod/ovis-composer/state.js index dfd3ae5..71c0a00 100644 --- a/mod/ovis-composer/state.js +++ b/mod/ovis-composer/state.js @@ -42,6 +42,7 @@ import { onRestart } from "./delivery.js"; * * @typedef {object} State * @property {Record} drafts + * @property {Record} carets * @property {Record} attachments * @property {Record} queue * @property {Notice|null} notice @@ -53,6 +54,7 @@ import { onRestart } from "./delivery.js"; export function createState() { return { drafts: {}, + carets: {}, attachments: {}, queue: {}, notice: null, @@ -84,7 +86,16 @@ export function isSending(state, agent) { export function reduce(state, action) { switch (action.type) { case "draft": - return { ...state, drafts: { ...state.drafts, [action.agent]: action.text } }; + 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 "send": return { ...state, drafts: { ...state.drafts, [action.agent]: "" } }; @@ -142,6 +153,46 @@ export function reduce(state, action) { } } +/** + * 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: when the + * start time differs, the draft is still restored - the text is the person's + * - but it says so, and the whole queue of that address is held, so nothing + * goes on its own to an agent it was not written for. An `uncertain` entry + * stays `uncertain`: it has no "send now" button, and "held" has. + */ +function restoreDraft(state, action) { + const draft = action.draft; + if (!draft || typeof draft.text !== "string") return state; + + const agent = action.agent; + const same = (draft.identity?.created_ms ?? null) === (action.identity?.created_ms ?? null); + + const 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 })), + }, + }; + if (same) return next; + + return { + ...next, + notice: { text: "Szkic z poprzedniej sesji agenta", level: "warn" }, + queue: { + ...next.queue, + [agent]: list(next.queue, agent).map((item) => + item.state === "uncertain" || item.state === "held" ? item : { ...item, state: "held" }, + ), + }, + }; +} + /** * The queue of an agent comes back from the disk. * diff --git a/mod/ovis-composer/storage.js b/mod/ovis-composer/storage.js index 0ca0082..af4b789 100644 --- a/mod/ovis-composer/storage.js +++ b/mod/ovis-composer/storage.js @@ -70,6 +70,8 @@ export const KEYS = { usage: "ovis-composer.usage", /** The queue is per agent: `ovis-composer.queue:`. */ queue: "ovis-composer.queue", + /** The draft is per agent: `ovis-composer.draft:`. */ + draft: "ovis-composer.draft", }; /** How many entries the history keeps. */ @@ -157,6 +159,92 @@ export function saveQueue(store, agent, items) { 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 toDraft(read(store, draftKey(agent))); +} + +/** + * 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; + 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} */ (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, + }; +} + /** * How often each command was used - the numbers the ranking of the * suggestions breaks its ties with (`suggest.rank` reads `item.uses`). diff --git a/tests/state.test.mjs b/tests/state.test.mjs index 8cdf76c..7b103b5 100644 --- a/tests/state.test.mjs +++ b/tests/state.test.mjs @@ -58,3 +58,44 @@ test("notice sets and clears", () => { s = reduce(s, { type: "notice", notice: null }); assert.equal(s.notice, null); }); + +const dr = (created_ms, text = "szkic") => ({ + text, caret: 2, attachments: [], identity: { created_ms, app: "codex" }, savedAt: 1, +}); + +test("restore_draft with the same identity restores silently", () => { + const s = reduce(createState(), { type: "restore_draft", agent: "t2", draft: dr(5), identity: { created_ms: 5, app: "codex" } }); + assert.equal(s.drafts.t2, "szkic"); + assert.equal(s.carets.t2, 2); + assert.equal(s.notice, null); +}); + +test("restore_draft with other created_ms holds the whole queue and warns", () => { + let s = reduce(createState(), { type: "restore", agent: "t2", items: [ + { id: "1", text: "a", state: "queued", createdAt: 1 }, + { id: "2", text: "b", state: "held", createdAt: 2 }, + { id: "3", text: "c", state: "uncertain", createdAt: 3 }, + ] }); + s = reduce(s, { type: "restore_draft", agent: "t2", draft: dr(5), identity: { created_ms: 9, app: "codex" } }); + assert.equal(s.drafts.t2, "szkic"); + assert.deepEqual(s.notice, { text: "Szkic z poprzedniej sesji agenta", level: "warn" }); + assert.deepEqual(s.queue.t2.map((i) => i.state), ["held", "held", "uncertain"]); +}); + +test("restore_draft restores attachments and never mutates", () => { + const before = createState(); + const att = { id: "a", name: "f", path: "p", bytes: 1, kind: "file", state: "ready" }; + const s = reduce(before, { type: "restore_draft", agent: "t2", draft: { ...dr(5), attachments: [att] }, identity: { created_ms: 5, app: null } }); + assert.deepEqual(s.attachments.t2, [att]); + assert.deepEqual(before.drafts, {}); +}); + +test("restore_draft without a draft changes nothing", () => { + const s = createState(); + assert.equal(reduce(s, { type: "restore_draft", agent: "t2", draft: null, identity: { created_ms: 1, app: null } }), s); +}); + +test("draft action keeps the caret", () => { + const s = reduce(createState(), { type: "draft", agent: "a", text: "hi", caret: 1 }); + assert.equal(s.carets.a, 1); +}); diff --git a/tests/storage.test.mjs b/tests/storage.test.mjs index d0a19c8..43b9520 100644 --- a/tests/storage.test.mjs +++ b/tests/storage.test.mjs @@ -2,6 +2,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { HISTORY_LIMIT, queueKey, loadHistory, saveHistory, loadQueue, saveQueue, loadUsage, saveUsage, + KEYS, draftKey, loadDraft, saveDraft, } from "../mod/ovis-composer/storage.js"; const memStore = () => { @@ -56,3 +57,60 @@ test("rubbish list does not wipe stored history", () => { saveHistory(store, [{ nope: 1 }]); assert.equal(loadHistory(store).length, 1); }); + +const draft = (over = {}) => ({ + text: "hello", caret: 3, attachments: [], + identity: { created_ms: 1794818438639, app: "claude-code" }, savedAt: 10, ...over, +}); + +test("draftKey is per agent", () => { + assert.equal(KEYS.draft, "ovis-composer.draft"); + assert.equal(draftKey("t2"), "ovis-composer.draft:t2"); +}); + +test("draft roundtrip", () => { + const store = memStore(); + const d = draft({ attachments: [{ id: "a", name: "f.txt", path: "C:/f.txt", bytes: 3, kind: "file", state: "ready" }] }); + saveDraft(store, "t2", d); + assert.deepEqual(loadDraft(store, "t2"), d); + assert.equal(loadDraft(store, "t3"), null); +}); + +test("loadDraft: rubbish in store gives null", () => { + const store = memStore(); + for (const bad of ["x", [], 5, { text: 1 }]) { + store.set(draftKey("t2"), bad); + assert.equal(loadDraft(store, "t2"), null); + } +}); + +test("draft keeps text over 20000 chars whole", () => { + const store = memStore(); + const text = "a".repeat(25000); + saveDraft(store, "t2", draft({ text, caret: 25000 })); + assert.equal(loadDraft(store, "t2").text.length, 25000); +}); + +test("saveDraft ignores rubbish and empty agent", () => { + const store = memStore(); + saveDraft(store, "t2", draft()); + saveDraft(store, "t2", "x"); + saveDraft(store, "", draft()); + assert.equal(loadDraft(store, "t2").text, "hello"); + assert.equal(store.get("ovis-composer.draft:"), undefined); +}); + +test("empty draft overwrites the old one", () => { + const store = memStore(); + saveDraft(store, "t2", draft()); + saveDraft(store, "t2", draft({ text: "", caret: 0 })); + assert.equal(loadDraft(store, "t2").text, ""); +}); + +test("loadDraft: text-only draft still loads, with defaults", () => { + const store = memStore(); + store.set(draftKey("t2"), { text: "a" }); + assert.deepEqual(loadDraft(store, "t2"), { + text: "a", caret: 1, attachments: [], identity: { created_ms: null, app: null }, savedAt: 0, + }); +});