feat: persistent per-agent drafts with identity check

Co-Authored-By: Ovis Fast (Claude) <[email protected]>
This commit is contained in:
FactorandOvis Fast committed 2026-11-19 11:14:54 +01:00
1 parent 187a385f6f
commit 2ce1b45ee4
5 files changed
+367 -10

No files matched your search

+128 -9
View File
@@ -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();
}
+52 -1
View File
@@ -42,6 +42,7 @@ import { onRestart } from "./delivery.js";
*
* @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
@@ -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.
*
+88
View File
@@ -70,6 +70,8 @@ export const KEYS = {
usage: "ovis-composer.usage",
/** The queue is per agent: `ovis-composer.queue:<agent>`. */
queue: "ovis-composer.queue",
/** The draft is per agent: `ovis-composer.draft:<agent>`. */
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<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,
};
}
/**
* How often each command was used - the numbers the ranking of the
* suggestions breaks its ties with (`suggest.rank` reads `item.uses`).