fix: start queue countdown from state, clear stale stop flag, drop dead watch code

Co-Authored-By: Ovis Fast (Claude) <[email protected]>
This commit is contained in:
FactorandOvis Fast committed 2026-11-19 11:28:25 +01:00
1 parent 7ec35215c6
commit 86ca415d96
3 files changed
+111 -68

No files matched your search

+21
View File
@@ -109,6 +109,27 @@ export function shouldDrain(prev, next, stoppedByComposer) {
return was && is;
}
/**
* Does the queue start counting down now? A rule of the state, not of a
* change: a turn that ended unseen (shorter than one poll) or a status that
* was unknown for a while must not leave a message waiting for ever.
*
* Yes when the agent is idle or done, an entry waits in the queue (`queued`;
* a `held` one does not count, an `uncertain` one in front of it does not
* block), nothing counts down or is on the wire, the turn gate is open and the
* composer did not stop the agent itself.
*
* @param {{status:Status|string, queue:QueueItem[], gateOpen:boolean, stopped:boolean}} input
* @returns {boolean}
*/
export function shouldStartCountdown({ status, queue, gateOpen, stopped }) {
if (stopped || !gateOpen) return false;
if (!ready(status)) return false;
if (!Array.isArray(queue)) return false;
if (queue.some((item) => item.state === "countdown" || item.state === "sending")) return false;
return queue.some((item) => item.state === "queued");
}
/**
* 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
+54 -67
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, shouldDrain, sendNow as sendToTerminal } from "./delivery.js";
import { decide, shouldDrain, shouldStartCountdown, 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";
@@ -87,17 +87,15 @@ export default class Composer extends View {
this.state = createState();
this.store = guardedStore({ get: shared, set: setShared });
// Per agent: the turn gate, whether a drain is in flight, whether the
// core is already waiting for the agent, and whether the queue of that
// agent was read from the disk.
// Per agent: the turn gate, whether a drain is in flight, and whether the
// queue of that agent was read from the disk.
this.gates = new Map();
this.draining = new Set();
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.
// The queue counts down when the agent is idle (see `tickQueues`): the
// last status seen per agent, and the agents the composer stopped itself
// (Stop, Esc) - until their turn is over, the queue does not start.
this.prevStatus = new Map();
this.stopped = new Set();
@@ -107,8 +105,6 @@ export default class Composer extends View {
this.identities = new Map();
this.draftReady = new Set();
this.draftLoading = new Set();
// Agents whose queue wanted to drain before their identity was checked.
this.pendingDrain = new Set();
this.draftTimer = null;
// The menu of suggestions: what it shows, which row is picked.
@@ -286,7 +282,6 @@ export default class Composer extends View {
this.draftReady.add(key);
// 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();
});
@@ -666,12 +661,16 @@ export default class Composer extends View {
const decision =
mode === "now" ? { kind: "send" } : mode === "hold" ? { kind: "hold" } : decide(this.statusOf(agent));
// A message that is already on the wire: the new one waits in the queue
// instead of vanishing.
// Not before the draft and the identity of the agent were checked - the
// person's own "send now" (Ctrl+Enter) is the exception.
const allowed = mode === "now" || canAutoSend(this.draftReady, key);
if (decision.kind === "send" && allowed && !this.draining.has(key)) {
// A message that is on the wire, or one that counts down, goes first: the
// new one waits behind it in the queue instead of vanishing or jumping
// the line (Ctrl+Enter is the person's own order and does jump).
const busy =
this.draining.has(key) ||
(mode !== "now" && (this.state.queue[key] ?? []).some((entry) => entry.state === "countdown"));
if (decision.kind === "send" && allowed && !busy) {
this.sendNow(agent, message, cx);
return;
}
@@ -687,6 +686,17 @@ export default class Composer extends View {
this.state = reduce(this.state, { type: "queue", agent: key, item });
this.persistQueue(key);
if (!held) {
// A new message after a stop is not the stopped one: it waits for the
// agent like any other.
this.stopped.delete(key);
// It waits because the agent is not ready: once it is, the message may
// go (the gate counts a status that was not "working" too).
if (decision.kind === "queue") {
this.gates.set(key, { ...this.gateFor(key), sawWorking: true });
}
}
if (held) {
this.notice(
mode === "hold"
@@ -696,7 +706,6 @@ export default class Composer extends View {
);
} else {
this.notice("Wiadomość w kolejce — następna tura.");
this.watch(agent, cx);
}
cx.notify();
}
@@ -746,27 +755,10 @@ export default class Composer extends View {
}
} finally {
this.draining.delete(key);
this.watchAgain(agent, cx);
cx.notify();
}
}
/**
* The queue is watched again.
*
* A message that waited for a send to finish would sit in the queue for
* ever: the watch that was waiting for the agent has already returned. The
* composer starts a new one - but only when the agent is working, so an idle
* agent does not spin the wait in a loop.
*/
watchAgain(agent, cx) {
const key = agentKey(agent);
const waiting = (this.state.queue[key] ?? []).some((item) => item.state === "queued");
if (!waiting) return;
if (this.statusOf(agent) !== "working") return;
this.watch(agent, cx);
}
/** Did the entry go on the wire? An entry that did not must not be sent. */
claimed(key, id) {
const item = (this.state.queue[key] ?? []).find((entry) => entry.id === id);
@@ -774,17 +766,11 @@ export default class Composer extends View {
}
/**
* 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.
* Once a second: the status of every agent is read, the stop flag is kept
* honest, and the queue counts down when the state says so
* (`shouldStartCountdown`) - not only when a change was seen, so a turn that
* was too short for the poll does not leave a message waiting for ever.
*/
watch(agent, cx) {
const key = agentKey(agent);
if (!this.prevStatus.has(key)) this.prevStatus.set(key, this.statusOf(agent));
}
/** Once a second: the ends of turns, and the countdowns. */
tickQueues(cx) {
if (this.closed) return;
for (const agent of liveAgents()) {
@@ -795,13 +781,24 @@ export default class Composer extends View {
const prev = this.prevStatus.get(key);
this.prevStatus.set(key, status);
// A turn the composer stopped itself is used up by this change.
// The flag is read before it is cleared: the change that ends the
// stopped turn still counts as stopped.
const stopped = this.stopped.has(key);
const ended = (prev === "working" || prev === "blocked") && (status === "idle" || status === "done");
if (ended) this.stopped.delete(key);
if (stopped) {
// The turn the composer stopped is over (shouldDrain without the
// flag says so), or a new turn began after it: either way the flag
// is used up.
const over = shouldDrain(prev, status, false);
const again = status === "working" && prev !== undefined && prev !== "working" && prev !== "blocked";
if (over || again) this.stopped.delete(key);
}
if ((this.state.queue[key] ?? []).length === 0) continue;
if (shouldDrain(prev, status, stopped)) this.beginCountdown(agent, key, cx);
const queue = this.state.queue[key] ?? [];
if (queue.length === 0) continue;
const open = gatePasses(this.gateFor(key), status);
if (canAutoSend(this.draftReady, key) && shouldStartCountdown({ status, queue, gateOpen: open, stopped })) {
this.beginCountdown(agent, key, cx);
}
this.advanceCountdown(agent, key, status, cx);
}
}
@@ -820,9 +817,6 @@ export default class Composer extends View {
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();
}
@@ -870,7 +864,12 @@ export default class Composer extends View {
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);
if (status === "idle" || status === "done") {
// After a restart no turn was seen - the restored queue is trusted, so
// the gate steps aside for this one send.
this.gates.set(key, openGate(this.gateFor(key)));
this.beginCountdown(agent, key, cx);
}
}
/**
@@ -879,18 +878,11 @@ export default class Composer extends View {
*/
async drainQueue(agent, cx) {
const key = agentKey(agent);
// The queue came back from the disk, but whose is it? Wait for the check.
if (!canAutoSend(this.draftReady, key)) {
this.pendingDrain.add(key);
return;
}
// The queue came back from the disk, but whose is it? Not before the check.
if (!canAutoSend(this.draftReady, key)) return;
// One drain at a time per agent: the state it works on is immutable, so
// two of them would send the same message twice. The queue is watched
// anyway - the drain that is in flight will not empty it.
if (this.draining.has(key)) {
this.watchAgain(agent, cx);
return;
}
// two of them would send the same message twice.
if (this.draining.has(key)) return;
this.draining.add(key);
let claimed = "";
@@ -969,10 +961,6 @@ export default class Composer extends View {
}
} finally {
this.draining.delete(key);
// The agent may have gone back to work with the queue not empty - the
// queue is watched again, so it empties itself.
const waiting = (this.state.queue[key] ?? []).some((item) => item.state === "queued");
if (waiting && this.statusOf(agent) === "working") this.watch(agent, cx);
cx.notify();
}
}
@@ -1031,7 +1019,6 @@ export default class Composer extends View {
}
} finally {
this.draining.delete(key);
this.watchAgain(agent, cx);
cx.notify();
}
}