feat: queue countdown, hold on stop, reply when blocked

Co-Authored-By: Ovis Fast (Claude) <[email protected]>
This commit is contained in:
FactorandOvis Fast committed 2026-11-19 11:22:30 +01:00
1 parent 0558449439
commit 7ec35215c6
9 files changed
+361 -44

No files matched your search

+37 -5
View File
@@ -59,8 +59,9 @@ import { reduce } from "./state.js";
* @typedef {object} QueueItem
* @property {string} id
* @property {string} text
* @property {"queued"|"sending"|"held"|"uncertain"} state
* @property {"queued"|"countdown"|"sending"|"held"|"uncertain"} state
* @property {number} createdAt
* @property {number} [left] - seconds to the send, while the state is "countdown"
* @property {string} [reason]
*/
@@ -78,7 +79,10 @@ export function decide(status) {
case "working":
return { kind: "queue" };
case "blocked":
return { kind: "hold" };
// The agent waits for an answer: what the person writes IS the answer,
// so it goes out at once. (The queue does not start on its own while
// the agent is blocked - see `shouldDrain`.)
return { kind: "send" };
default:
// A status we do not know (the core also reports "error") - wait for a
// known one instead of pasting into an agent that may not be there.
@@ -86,6 +90,25 @@ export function decide(status) {
}
}
/**
* Does a change of the agent's status start the queue (the countdown)?
*
* Only the end of a turn does: the agent was working (or waiting for the
* person) and is idle or done now. A turn that the composer stopped itself
* (the Stop button, Esc) never starts anything.
*
* @param {Status|string} prev
* @param {Status|string} next
* @param {boolean} stoppedByComposer
* @returns {boolean}
*/
export function shouldDrain(prev, next, stoppedByComposer) {
if (stoppedByComposer) return false;
const was = prev === "working" || prev === "blocked";
const is = next === "idle" || next === "done";
return was && is;
}
/**
* The turn gate: the next message goes out only after a whole turn was seen -
* the agent was working and then came back to idle/done. Without that
@@ -205,7 +228,15 @@ export async function drain(ctx, state) {
*/
export function onRestart(queue) {
if (!Array.isArray(queue)) return [];
return queue.map((item) => (item.state === "sending" ? { ...item, state: "uncertain" } : item));
return queue.map((item) => {
if (item.state === "sending") return { ...item, state: "uncertain" };
if (item.state === "countdown") {
// Nothing goes out on its own after a restart.
const { left, ...rest } = item;
return { ...rest, state: "held" };
}
return item;
});
}
/** The agent can take the next message when it is not working and not blocked. */
@@ -217,9 +248,10 @@ function ready(status) {
return status === "idle" || status === "done";
}
/** Only an entry that waits in the queue may go out. */
/** Only an entry that waits in the queue, or whose countdown ran out, may go out. */
function sendable(item) {
return item?.state === "queued";
if (item?.state === "queued") return true;
return item?.state === "countdown" && !(item.left > 0);
}
/** Run `hc` and normalize what comes back. */
+144 -23
View File
@@ -36,7 +36,7 @@ import * as fs from "fs/promises";
import { createState, reduce } from "./state.js";
import { keyIntent } from "./keys.js";
import { decide, sendNow as sendToTerminal } from "./delivery.js";
import { decide, shouldDrain, sendNow as sendToTerminal } from "./delivery.js";
import { detect as detectTrigger, rank, merge, startsLine } from "./suggest.js";
import * as catalog from "./catalog.js";
import { LIMITS, validateMany, mention, removeMention } from "./attachments.js";
@@ -95,6 +95,12 @@ export default class Composer extends View {
this.waiting = new Set();
this.restored = new Set();
// The queue starts when a turn ends: the last status seen per agent, and
// the agents the composer stopped itself (Stop, Esc) - the turn that
// ends because of that does not start the queue.
this.prevStatus = new Map();
this.stopped = 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.
@@ -169,6 +175,11 @@ export default class Composer extends View {
cx.timer.every(500, (cx) => {
this.syncAgent(cx);
});
// Once a second: the end of a turn starts the countdown of the queue and
// the countdown counts down.
cx.timer.every(1000, (cx) => {
this.tickQueues(cx);
});
cx.spawn(async (cx) => {
for (;;) {
@@ -273,8 +284,10 @@ export default class Composer extends View {
}
this.draftLoading.delete(key);
this.draftReady.add(key);
// The sending that waited for the check goes on.
if (this.pendingDrain.delete(key)) this.drainQueue(agent, cx);
// The queue that came back from the disk and was trusted goes on: after
// the turn of the agent, or at once when the agent is idle.
this.pendingDrain.delete(key);
this.resumeRestored(agent, key, cx);
cx.notify();
});
}
@@ -760,27 +773,104 @@ export default class Composer extends View {
return Boolean(item && item.state === "sending");
}
/** The core tells us when the agent stops working - then the queue may go out. */
/**
* The agent's turn is followed: its status is read once a second (`tickQueues`),
* and the end of a turn - working or blocked, then idle or done - starts the
* countdown of the queue (`shouldDrain`). The status that is seen now is the
* point to compare with.
*/
watch(agent, cx) {
const key = agentKey(agent);
if (this.waiting.has(key)) return;
this.waiting.add(key);
if (!this.prevStatus.has(key)) this.prevStatus.set(key, this.statusOf(agent));
}
cx.spawn(async (cx) => {
try {
const res = await hc(["wait", agent.address, "--json"]);
if (!hcOk(res)) {
// The core did not wait for anything - the queue stays where it is.
return;
}
} catch {
// The core is gone - the queue stays where it is.
return;
} finally {
this.waiting.delete(key);
}
await this.drainQueue(agent, cx);
});
/** Once a second: the ends of turns, and the countdowns. */
tickQueues(cx) {
if (this.closed) return;
for (const agent of liveAgents()) {
const key = agentKey(agent);
if (!key) continue;
const status = this.statusOf(agent);
const prev = this.prevStatus.get(key);
this.prevStatus.set(key, status);
// A turn the composer stopped itself is used up by this change.
const stopped = this.stopped.has(key);
const ended = (prev === "working" || prev === "blocked") && (status === "idle" || status === "done");
if (ended) this.stopped.delete(key);
if ((this.state.queue[key] ?? []).length === 0) continue;
if (shouldDrain(prev, status, stopped)) this.beginCountdown(agent, key, cx);
this.advanceCountdown(agent, key, status, cx);
}
}
/**
* The first queued message starts to count down: it goes out in a few
* seconds unless the person cancels it. Only when the queue is known to
* belong to this agent (`canAutoSend`).
*/
beginCountdown(agent, key, cx) {
if (!canAutoSend(this.draftReady, key)) return;
const first = (this.state.queue[key] ?? []).find((item) => item.state === "queued");
if (!first) return;
const before = this.state;
this.state = reduce(this.state, { type: "countdown_start", agent: key, id: first.id });
if (this.state === before) return;
// A turn was seen to end (or the agent is idle): the gate steps aside for
// this one send.
this.gates.set(key, openGate(this.gateFor(key)));
this.persistQueue(key);
cx.notify();
}
/** A second passes; at 0 the message goes through the usual drain. */
advanceCountdown(agent, key, status, cx) {
const item = (this.state.queue[key] ?? []).find((entry) => entry.state === "countdown");
if (!item) return;
if (status !== "idle" && status !== "done") {
// The agent went back to work - the message waits for the next turn.
this.state = reduce(this.state, { type: "countdown_reset", agent: key, id: item.id });
this.gates.set(key, closeGate(this.gateFor(key)));
this.persistQueue(key);
cx.notify();
return;
}
if (!canAutoSend(this.draftReady, key)) return;
if (item.left > 0) {
this.state = reduce(this.state, { type: "countdown_tick", agent: key, id: item.id });
cx.notify();
}
const now = (this.state.queue[key] ?? []).find((entry) => entry.id === item.id);
if (now && now.state === "countdown" && !(now.left > 0)) this.drainQueue(agent, cx);
}
/** The person does not want the message that counts down - it is held. */
cancelCountdown(agent, id, cx) {
const key = agentKey(agent);
this.state = reduce(this.state, { type: "countdown_cancel", agent: key, id });
this.gates.set(key, closeGate(this.gateFor(key)));
this.persistQueue(key);
cx.notify();
}
/**
* The queue that came back from the disk is followed again.
*
* Entries that are still `queued` here passed the identity check (the others
* were held). An idle agent starts the countdown at once, a working one
* after its turn.
*/
resumeRestored(agent, key, cx) {
if (!(this.state.queue[key] ?? []).some((item) => item.state === "queued")) return;
const status = this.statusOf(agent);
this.prevStatus.set(key, status);
if (status === "idle" || status === "done") this.beginCountdown(agent, key, cx);
}
/**
@@ -812,7 +902,8 @@ export default class Composer extends View {
terminal: agent.address,
hc,
status: () => this.statusOf(agent),
gate: () => gatePasses(this.gateFor(key), this.statusOf(agent)),
// One message per turn: after the first send the gate is shut.
gate: () => !sent && gatePasses(this.gateFor(key), this.statusOf(agent)),
onState: (next) => {
const items = next.queue?.[key] ?? [];
const sending = items.find((item) => item.state === "sending");
@@ -984,16 +1075,35 @@ export default class Composer extends View {
});
}
/** The stop key of the agent's program. */
/**
* The stop key of the agent's program.
*
* The queue is held first (nothing goes out on its own to an agent the
* person just stopped), and the turn that ends because of the stop does not
* start it again.
*/
interrupt(agent, cx) {
const key = agentKey(agent);
const status = this.statusOf(agent);
const flagged = status === "working" || status === "blocked";
if (flagged) this.stopped.add(key);
this.state = reduce(this.state, { type: "hold_all", agent: key });
this.gates.set(key, closeGate(this.gateFor(key)));
this.persistQueue(key);
this.notice("Przerwano agenta. Kolejka wstrzymana — nic nie wyśle się samo.");
cx.notify();
cx.spawn(async (cx) => {
try {
const res = await hc(["interrupt", agent.address, "--json"]);
const payload = parseJson(res.stdout);
if (res.code !== 0 || (payload && payload.error)) {
if (flagged) this.stopped.delete(key);
this.notice(`Nie udało się zatrzymać agenta: ${resultError(res, payload)}`, "error");
}
} catch (err) {
if (flagged) this.stopped.delete(key);
this.notice(`Nie udało się zatrzymać agenta: ${errorText(err)}`, "error");
}
cx.notify();
@@ -1388,6 +1498,17 @@ export default class Composer extends View {
return div().text_size(11).text_color(t.dim).child("wysyłanie…");
}
if (item.state === "countdown") {
return h_flex()
.gap(6)
.flex_none()
.child(
this.renderButton(t, "Anuluj", `cancel-${item.id}`, (event, cx) =>
this.cancelCountdown(agent, item.id, cx),
),
);
}
const buttons = [];
// An uncertain entry may have reached the agent - it is not sent again.
if (item.state !== "uncertain") {
+68 -9
View File
@@ -22,12 +22,13 @@ import { onRestart } from "./delivery.js";
* @property {AttachmentState} state
* @property {string} [error]
*
* @typedef {"queued"|"sending"|"held"|"uncertain"} QueueItemState
* @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
@@ -50,6 +51,9 @@ import { onRestart } from "./delivery.js";
* @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 {
@@ -100,6 +104,23 @@ export function reduce(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]: "" } };
@@ -203,21 +224,59 @@ function restoreDraft(state, action) {
return held;
}
/** Everything that could go out on its own waits for the person. */
function holdQueue(state, agent) {
/**
* 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);
if (!items.some((item) => item.state !== "uncertain" && item.state !== "held")) return state;
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) =>
item.state === "uncertain" || item.state === "held" ? item : { ...item, state: "held" },
),
[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.
*
@@ -294,13 +353,13 @@ function withoutReason(item) {
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;
if (!item || (item.state !== "queued" && item.state !== "countdown")) return state;
return {
...state,
queue: {
...state.queue,
[action.agent]: items.map((entry) =>
entry.id === action.id ? { ...entry, state: "sending" } : entry,
entry.id === action.id ? { ...toState(entry, "sending") } : entry,
),
},
};
+3 -2
View File
@@ -55,13 +55,14 @@
* @typedef {object} QueueEntry
* @property {string} id
* @property {string} text
* @property {"queued"|"sending"|"held"|"uncertain"} state
* @property {"queued"|"countdown"|"sending"|"held"|"uncertain"} state
* @property {number} createdAt
* @property {number} [left]
* @property {string} [reason]
*/
/** The states a queue entry may be in (the ones state.js knows). */
const QUEUE_STATES = new Set(["queued", "sending", "held", "uncertain"]);
const QUEUE_STATES = new Set(["queued", "countdown", "sending", "held", "uncertain"]);
/** The keys the composer writes into the shared store. */
export const KEYS = {
+4 -2
View File
@@ -299,11 +299,13 @@ export function queueLabel(item) {
case "queued":
return "Następna tura";
case "held":
return "Do wysłania teraz";
return "Wstrzymana — wyślij ręcznie";
case "sending":
return "Wysyłanie…";
case "uncertain":
return "Niepotwierdzone";
return "Nie potwierdzono";
case "countdown":
return `Wysyłam za ${item.left} s`;
default:
return "";
}