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

+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") {