Work a session still has out is not lost: subagents, jobs, notes and steers
ci / check (push) Canceled after 0s

Seven findings of a review of the wake-turn work, each with a test that
failed before (tests/acp-outstanding.test.ts).

1. A session whose subagents work, or whose background command runs, with no
   turn running was idle to the service: an update restarted it under them
   and a terminal opening the session stopped them, so no report came. It is
   occupied now (acp/agent.ts occupied, keeps; hub.busy): no restart, no
   close of the link, and a terminal is refused in words that name what runs
   — also while no link is up, when nothing judged it at all.
2. A scheduled run that used a team answered with the reply that ended the
   main agent's first turn, and the real answer came in a turn report_write
   was not offered in. The run's turn now waits for its subagents and takes
   their reports in (engine awaitReports, EngineOptions.hold): one turn, the
   answer and the report from its last reply.
3. Stop while a turn waited for a model slot lost the note that started it
   (and a person's own message, and whatever waited to go in with it): the
   message is in the conversation now, under the turn's id.
4. A steer a harness turn never took in, with no client listening, stayed in
   memory: lost by a restart, and in queue mode handed back with a later
   prompt. It is kept with the session (CARRIED_META) and taken in at the
   next turn's first step in every mode, said with its id.
5. A wake refused for an interactive-only model left the main agent marked
   working, holding its slot, and dropped the report: the session is idle
   again and the note is kept for the next message.
6. Stop on a scheduled run stops its subagents, as does any other end of the
   run's turn with subagents out. In a chat Stop stops the turn and no
   subagent, as the terminal's Esc does: pinned by a test, not changed.
7. The task end that carries unsent is said before the inbox event that
   empties the queue.

Notes left after a Stop are kept with the session too (engine.keepNote), so
a restart does not lose them. AcpAgent.holding, anyBusy and drop had no
caller left and are gone.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-23 15:26:42 +00:00
1 parent 1f3eb92666
commit 87ecaca6db
7 files changed
+623 -39

No files matched your search

+24
View File
@@ -27,6 +27,30 @@ Harness spec 3.10.0: a turn the harness starts by itself is a turn like any othe
- **Compacting or rewinding a session is refused while such a turn runs**, and the service no - **Compacting or rewinding a session is refused while such a turn runs**, and the service no
longer lets go of the session, or closes the link for a change of `remote:` settings, under it. longer lets go of the session, or closes the link for a change of `remote:` settings, under it.
- **A schedule that uses subagents now reports its real answer.** A scheduled run on this
computer used to answer as soon as the main agent had started its subagents ("they are on
it"), and the result arrived later in a turn that could not file a report. The run now stays
open until its subagents have reported, shows *Waiting for subagents* meanwhile, and its answer
and its report come from the last reply. Stopping the run stops its subagents too.
- **Subagents and background jobs are no longer cut off by the service.** While a session's
subagents were working and the main agent was idle, the service counted the session as idle: an
update restarted it under them, and opening the session in a terminal stopped them without a
word, so their reports never came. The service now waits for them before it restarts or
redials, and a terminal that opens such a session is told what still runs and how to stop it.
- **Stopping a turn that was waiting for a free model slot no longer loses what started it.** A
finished job's note, or your own message, stays in the conversation and the model reads it with
the next message.
- **A message sent from the web while the link drops is not lost.** If the agent was answering a
subagent's report and finished before taking your message in, with no connection to hand it
back over, the message is kept with the session — also across a restart of the service — and
the agent reads it at the start of its next turn. It used to wait in memory, and with
`busy_input: queue` came back attached to an unrelated later prompt.
- **A job's or subagent's note that arrives after you pressed Stop survives a restart** and goes
in with your next message, as before.
- **In a schedule's chat on a model for interactive use only**, a subagent's report that may not
start a turn by itself no longer leaves the main agent marked as working: the session is idle
and the report goes in with your next message.
### Changed ### Changed
- **The main agent is told plainly how reports reach it** (`blocks/team_lead.md`): it does not - **The main agent is told plainly how reports reach it** (`blocks/team_lead.md`): it does not
+29 -24
View File
@@ -47,6 +47,7 @@ import type { Hub } from "./hub.ts"
import { INVALID_PARAMS, METHOD_NOT_FOUND, RpcError, type Peer } from "./rpc.ts" import { INVALID_PARAMS, METHOD_NOT_FOUND, RpcError, type Peer } from "./rpc.ts"
import { jobList, jobOutput, jobSend, jobStop, jobTranscript, storedJobs, teamFindings, teamStop, teamTranscript, teamView, treeOf } from "./jobs.ts" import { jobList, jobOutput, jobSend, jobStop, jobTranscript, storedJobs, teamFindings, teamStop, teamTranscript, teamView, treeOf } from "./jobs.ts"
import { isNote } from "../session/prefix.ts" import { isNote } from "../session/prefix.ts"
import { outstandingReason } from "../session/outstanding.ts"
import { deniedText, finalReply, judgeMonitor, monitorTimeout, notifyOf, permissionFor, refusalText, runMonitor, runOutcome, SCHEDULED, scheduledMode, type Report, type ScheduledTurn } from "./scheduled.ts" import { deniedText, finalReply, judgeMonitor, monitorTimeout, notifyOf, permissionFor, refusalText, runMonitor, runOutcome, SCHEDULED, scheduledMode, type Report, type ScheduledTurn } from "./scheduled.ts"
export const ACP_VERSION = 1 export const ACP_VERSION = 1
@@ -202,6 +203,19 @@ export interface Session {
* harness's own (a note waking it). What status, steer, compact, rewind and letting go ask. */ * harness's own (a note waking it). What status, steer, compact, rewind and letting go ask. */
export const working = (s: Session): boolean => s.prompting || s.own !== undefined export const working = (s: Session): boolean => s.prompting || s.own !== undefined
/** Whether the session is anything but idle: a turn runs or waits its turn — or none does, and
* work of it is still out: a subagent that works or waits, a report about to wake it, a
* background command (session/outstanding.ts; acp.md, *A session that still has work out*). What
* the service asks before it starts again for an update, closes the link for a change of limits,
* or lets a terminal have the session: each of those would lose that work. */
export const occupied = (s: Session): boolean => working(s) || s.queue !== undefined || s.app.out().has_work
/** Why a terminal may not have this session now, in words — or undefined when it may. */
export function keeps(s: Session): string | undefined {
if (working(s) || s.queue !== undefined) return "this session is working on a prompt from the web UI — wait for it to finish, then open it"
return outstandingReason(s.app.out())
}
/** A `task` event of a turn no prompt of the client's began — the harness's own. It is kept in the /** A `task` event of a turn no prompt of the client's began — the harness's own. It is kept in the
* session's turn log as a terminal's turns are (running, then the last one finished, with no * session's turn log as a terminal's turns are (running, then the last one finished, with no
* answer of this side's), and it holds the queue: a prompt that arrives meanwhile runs after it, * answer of this side's), and it holds the queue: a prompt that arrives meanwhile runs after it,
@@ -1012,25 +1026,6 @@ export class AcpAgent {
} }
private store?: Store private store?: Store
/** Whether a session runs here, and whether it is working (the hub, before a terminal opens it). */
holding(id: string): "busy" | "idle" | undefined {
const s = this.sessions.get(id)
return s ? (working(s) ? "busy" : "idle") : undefined
}
/** Whether any session this link runs is working, or has prompts waiting. */
anyBusy(): boolean {
return [...this.sessions.values()].some((s) => working(s) || s.queue)
}
/** Let go of an idle session: a terminal carries it on from the store. */
drop(id: string) {
const s = this.sessions.get(id)
if (!s || working(s)) return
this.sessions.delete(id)
void s.app.close()
}
notifyInstance(method: string, params: unknown) { notifyInstance(method: string, params: unknown) {
this.peer.notify(method, params) this.peer.notify(method, params)
} }
@@ -1261,6 +1256,10 @@ export class AcpAgent {
off() off()
if (prepared.model) app.returnModel(prev) if (prepared.model) app.returnModel(prev)
app.engine.mode = turn.mode app.engine.mode = turn.mode
// Nothing of a run's subagents works after its answer: by a turn that ended as meant they
// have all reported (the turn waited for them); one that was stopped, failed or ran out of
// steps or budget takes them with it — nobody would read what they report.
if (app.out().run_waits) app.stopSubagents()
} }
} }
@@ -1563,13 +1562,19 @@ export class AcpAgent {
// provider's now (`deepseek/x`), so the ref alone no longer tells. // provider's now (`deepseek/x`), so the ref alone no longer tells.
let event: Event | Record<string, unknown> = e.type === "model" ? { ...e, instance: this.isInstance(e.connection) } : e.type === "team" ? { ...e, tree: treeOf(s.app) } : e let event: Event | Record<string, unknown> = e.type === "model" ? { ...e, instance: this.isInstance(e.connection) } : e.type === "team" ? { ...e, tree: treeOf(s.app) } : e
// The end of a turn the harness started has no prompt's answer to carry what was steered into // The end of a turn the harness started has no prompt's answer to carry what was steered into
// it too late: it goes back on the event (`unsent`, as in a prompt's answer) — to a client // it too late. To a client that hears events it goes back on the event (`unsent`, as in a
// that hears events; otherwise it stays for the next turn's first step. // prompt's answer) — said before the queue is said to be empty, so an emptied queue is never
if (own && e.type === "task" && e.state === "end" && this.lembas && !this.peer.isClosed) { // read as messages taken in. With nobody listening it is kept with the session and goes in at
const unsent = s.app.engine.takeInbox() // the next turn's first step (engine.carry): one or the other, never both.
if (unsent.length) event = { ...e, unsent } let handedBack = false
if (own && e.type === "task" && e.state === "end") {
if (this.lembas && !this.peer.isClosed) {
const unsent = s.app.engine.unsent
if (unsent.length) (event = { ...e, unsent }), (handedBack = true)
} else s.app.engine.carry()
} }
if (this.lembas) this.peer.notify("_lembas/event", { sessionId: s.id, event }) if (this.lembas) this.peer.notify("_lembas/event", { sessionId: s.id, event })
if (handedBack) s.app.engine.takeInbox()
switch (e.type) { switch (e.type) {
case "text": case "text":
return this.update(s, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: e.text } }) return this.update(s, { sessionUpdate: "agent_message_chunk", content: { type: "text", text: e.text } })
+15 -6
View File
@@ -23,7 +23,7 @@ import { join } from "node:path"
import { isLocal, paths } from "../config/paths.ts" import { isLocal, paths } from "../config/paths.ts"
import type { Mode } from "../config/schema.ts" import type { Mode } from "../config/schema.ts"
import type { CommandInfo } from "../session/commands.ts" import type { CommandInfo } from "../session/commands.ts"
import { clampMode, refusalFor, type AcpAgent, type Limits } from "./agent.ts" import { clampMode, keeps, occupied, refusalFor, type AcpAgent, type Limits } from "./agent.ts"
import { addPendingDeleted } from "./pending.ts" import { addPendingDeleted } from "./pending.ts"
import { INVALID_PARAMS, Peer, RpcError, type Transport } from "./rpc.ts" import { INVALID_PARAMS, Peer, RpcError, type Transport } from "./rpc.ts"
@@ -178,9 +178,12 @@ export class Hub {
if (this.agent === agent) this.agent = undefined if (this.agent === agent) this.agent = undefined
} }
/** Whether anything works here now: a session the link runs, or one a terminal shares mid-turn. */ /** Whether anything works here now: a session the link runs — a turn of it, or with none
* running its subagents and background jobs, which live in this process — or one a terminal
* shares mid-turn. While it is true the service does not start again for an update and the
* link is not closed for a change of limits. */
busy(): boolean { busy(): boolean {
return [...this.held.values()].some((s) => s.prompting || s.own || s.queue) || [...this.shared.values()].some((s) => s.busy) return [...this.held.values()].some(occupied) || [...this.shared.values()].some((s) => s.busy)
} }
private announce(s: Shared) { private announce(s: Shared) {
@@ -202,9 +205,15 @@ export class Hub {
private releaseFor(peer: Peer, id: string): void { private releaseFor(peer: Peer, id: string): void {
const other = this.shared.get(id) const other = this.shared.get(id)
if (other && other.client !== peer && !other.client.isClosed) throw new RpcError(INVALID_PARAMS, `this session is open in another terminal (pid ${other.pid})`) if (other && other.client !== peer && !other.client.isClosed) throw new RpcError(INVALID_PARAMS, `this session is open in another terminal (pid ${other.pid})`)
const held = this.agent?.holding(id) // The hub's own copy — whether a link is up or not: it is let go of only when nothing of it
if (held === "busy") throw new RpcError(INVALID_PARAMS, "this session is working on a prompt from the web UI — wait for it to finish, then open it") // works here. A terminal cannot take over a turn, a subagent or a background job that runs in
if (held) this.agent!.drop(id) // this process, and closing the copy would stop them; so it is refused, in words.
const held = this.held.get(id)
if (!held) return
const why = keeps(held)
if (why) throw new RpcError(INVALID_PARAMS, why)
this.held.delete(id)
void held.app.close()
} }
private accept(peer: Peer) { private accept(peer: Peer) {
+38 -2
View File
@@ -29,6 +29,7 @@ import type { SubagentResult } from "./tool/task.ts"
import type { Client, ResolvedModel } from "./provider/types.ts" import type { Client, ResolvedModel } from "./provider/types.ts"
import { modelTitle, firstReply, promptTitle } from "./session/title.ts" import { modelTitle, firstReply, promptTitle } from "./session/title.ts"
import { Turns } from "./session/turns.ts" import { Turns } from "./session/turns.ts"
import { outstanding, type Outstanding } from "./session/outstanding.ts"
import { Snapshots } from "./git/snapshot.ts" import { Snapshots } from "./git/snapshot.ts"
import { CWD_META, REMOTE_META, SCHEDULED_META, SCHEDULED_MODEL_META, Store } from "./session/store.ts" import { CWD_META, REMOTE_META, SCHEDULED_META, SCHEDULED_MODEL_META, Store } from "./session/store.ts"
import { BUILTIN_TOOLS } from "./tool/registry.ts" import { BUILTIN_TOOLS } from "./tool/registry.ts"
@@ -174,6 +175,12 @@ export interface App {
jobsSessionId(): string jobsSessionId(): string
/** The open session's jobs, running first. */ /** The open session's jobs, running first. */
jobs(): Job[] jobs(): Job[]
/** What the session still has out when no turn of it runs (session/outstanding.ts): subagents
* that work or wait, a report waiting for the main agent, background commands. */
out(): Outstanding
/** Stop every subagent of the session — a team's members, background `task` subagents — without
* a note: a schedule's run that ended leaves none working (acp.md, *Scheduled work*). */
stopSubagents(): void
/** A note for the open session (a job's end, a subagent's message), beginning with its mark: to /** A note for the open session (a job's end, a subagent's message), beginning with its mark: to
* the model's next step while a turn runs, else a turn of its own marked `machine`. `shown`: * the model's next step while a turn runs, else a turn of its own marked `machine`. `shown`:
* the line a transcript shows for it. */ * the line a transcript shows for it. */
@@ -501,7 +508,14 @@ export function createApp(o: AppOptions): App {
if (turns.current || engine.busy) return engine.note(text) if (turns.current || engine.busy) return engine.note(text)
// A turn a schedule's job wakes is the schedule's: not run on an interactive-only model. // A turn a schedule's job wakes is the schedule's: not run on an interactive-only model.
const no = kind === "scheduled" ? notAutomated(engine.model) : undefined const no = kind === "scheduled" ? notAutomated(engine.model) : undefined
if (no) return void bus.emit({ type: "notice", level: "warn", message: `a job's note did not start a turn: ${no}` }) if (no) {
// No turn — so the note waits for the person's next message, kept with the session, and the
// main agent is idle again: a team that woke it gave it a slot for a turn that will not run
// (it would hold the slot, and every later report would be handed to that turn).
engine.keepNote(text)
teamRt.leadDone()
return void bus.emit({ type: "notice", level: "warn", message: `a job's note did not start a turn: ${no} It goes in with your next message.` })
}
void turns.prompt(text, [], shown, { machine: true }).catch((e) => bus.emit({ type: "notice", level: "warn", message: `a job's note could not start a turn: ${(e as Error).message}` })) void turns.prompt(text, [], shown, { machine: true }).catch((e) => bus.emit({ type: "notice", level: "warn", message: `a job's note could not start a turn: ${(e as Error).message}` }))
} }
const detach = registry.attach({ sessionId: jobsSessionId, bus, wake, store, runningMax: () => loaded.config.limits?.jobs ?? registry.limits.runningMax }) const detach = registry.attach({ sessionId: jobsSessionId, bus, wake, store, runningMax: () => loaded.config.limits?.jobs ?? registry.limits.runningMax })
@@ -512,7 +526,7 @@ export function createApp(o: AppOptions): App {
if (e.type !== "done") return if (e.type !== "done") return
const left = engine.takeNotes() const left = engine.takeNotes()
if (!left.length) return if (!left.length) return
if (e.reason === "cancelled") return void engine.pendingContext.push(...left) if (e.reason === "cancelled") return void left.forEach((n) => engine.keepNote(n))
setTimeout(() => { setTimeout(() => {
for (const n of left) wake(n, shownLine(n)) for (const n of left) wake(n, shownLine(n))
}, 0) }, 0)
@@ -766,6 +780,9 @@ export function createApp(o: AppOptions): App {
forget: () => teamRt.team.forgetTold(), forget: () => teamRt.team.forgetTold(),
beforeTurn: (signal) => teamRt.beforeLeadTurn(signal), beforeTurn: (signal) => teamRt.beforeLeadTurn(signal),
}, },
// A schedule's run is not over while its subagents work (acp.md, *Scheduled work*): the run's
// turn waits for their reports. Any other turn ends, and a report wakes the session.
hold: { out: () => (automated && kind === "scheduled" && out().run_waits ? Math.max(1, out().subagents.length) : 0), rest: () => teamRt.leadDone() },
changing: () => changing(), changing: () => changing(),
modeText: modeNote, modeText: modeNote,
// The configured MCP servers, up to loop.json's wait: their tools in the first list. // The configured MCP servers, up to loop.json's wait: their tools in the first list.
@@ -835,6 +852,14 @@ export function createApp(o: AppOptions): App {
}) })
// The lead's turn ended: it is idle, and its slot frees (team.md §8). // The lead's turn ended: it is idle, and its slot frees (team.md §8).
bus.on((e) => e.type === "done" && teamRt.leadDone()) bus.on((e) => e.type === "done" && teamRt.leadDone())
/** What the session still has out (session/outstanding.ts): its subagents, its background jobs. */
const out = (): Outstanding =>
outstanding({
agents: teamRt.team.tree().map((a) => ({ name: a.name, state: a.state })),
jobs: registry.running(jobsSessionId()).filter((j) => !j.team).map((j) => ({ id: j.id, kind: j.kind, state: j.state })),
})
// A turn that waits for its subagents looks again when one of them changes or ends.
bus.on((e) => (e.type === "team" || e.type === "job") && engine.poke())
// Spec 3.4.0: the main agent's mode reaches down the tree; its progress and context are in it. // Spec 3.4.0: the main agent's mode reaches down the tree; its progress and context are in it.
bus.on((e) => { bus.on((e) => {
if (e.type === "mode") teamRt.mainMode(e.mode) if (e.type === "mode") teamRt.mainMode(e.mode)
@@ -1150,6 +1175,17 @@ export function createApp(o: AppOptions): App {
registry, registry,
jobsSessionId, jobsSessionId,
jobs: () => registry.list(jobsSessionId()), jobs: () => registry.list(jobsSessionId()),
out,
stopSubagents() {
// The team's members leave it, with no note about it (stopAll); a background `task`
// subagent ends without one too — nobody is left to read either.
teamRt.stopAll()
for (const j of registry.running(jobsSessionId())) {
if (j.kind !== "subagent") continue
j.quiet = true
registry.stop(j)
}
},
wake, wake,
team: teamRt, team: teamRt,
get context() { get context() {
+3 -1
View File
@@ -496,6 +496,7 @@ export class JobRegistry {
job.ended = undefined job.ended = undefined
job.exit = undefined job.exit = undefined
job.lastError = undefined job.lastError = undefined
job.quiet = undefined
this.persist(job) this.persist(job)
this.emit(job, "start") this.emit(job, "start")
} }
@@ -526,7 +527,8 @@ export class JobRegistry {
this.persist(job) this.persist(job)
this.forget(job.sessionId) this.forget(job.sessionId)
this.emit(job, "end") this.emit(job, "end")
if (!job.silent) this.deliver(job, text) // `quiet`: stopped with nobody left to read its note (a schedule's run that ended).
if (!job.silent && !job.quiet) this.deliver(job, text)
return { text, stopped } return { text, stopped }
} }
+140 -6
View File
@@ -103,6 +103,11 @@ export interface EngineOptions {
/** Spec 3.4.0, a subagent: it ended by its own call (team_finish): the turn stops after this step. */ /** Spec 3.4.0, a subagent: it ended by its own call (team_finish): the turn stops after this step. */
ended?(): boolean ended?(): boolean
} }
/** A turn with nobody at it — a schedule's run (acp.md, *Scheduled work*) — does not end while
* subagents it started still work: their reports come into the same turn. `out`: how many are
* still out, 0 when the turn may end (and always 0 for any other turn); `rest`: the agent gives
* up its model slot while it waits. `poke()` says that the answer may have changed. */
hold?: { out(): number; rest?(): void }
} }
/** What a prompt carries besides its text. */ /** What a prompt carries besides its text. */
@@ -152,6 +157,13 @@ const wrapUpText = (limit: string) => fillPrompt(LOOP.wrap_up.message, { limit }
export const PLAN_META = "plan" export const PLAN_META = "plan"
/** How the session's last turn ended when it did not finish (display.md §4): `{ reason, error? }`. */ /** How the session's last turn ended when it did not finish (display.md §4): `{ reason, error? }`. */
export const END_META = "ended" export const END_META = "ended"
/** What was meant for the model and has not reached it, kept with the session so that a restart
* does not lose it: `notes` — the harness's notes that started no turn (the turn was stopped, or
* might not start), which go in with the next message; `steers` — messages steered into a turn
* the harness started that ended before taking them in, with nobody listening to hand them back
* to, which go in at the next turn's first step. */
export const CARRIED_META = "carried"
type Carried = { notes: string[]; steers: { text: string; id?: string }[] }
export class Engine { export class Engine {
messages: Message[] = [] messages: Message[] = []
@@ -181,6 +193,10 @@ export class Engine {
private notes: string[] = [] private notes: string[] = []
/** Those given to the model in this turn: kept word for word through a compaction, like the prompt. */ /** Those given to the model in this turn: kept word for word through a compaction, like the prompt. */
private turnSteers: string[] = [] private turnSteers: string[] = []
/** Kept with the session (CARRIED_META) until the model has them. */
private carried: Carried = { notes: [], steers: [] }
/** The turn waits for its subagents' reports (EngineOptions.hold): what ends the wait. */
private poked: (() => void) | undefined
/** busy_input: steer — the inbox goes in at the next step; queue — it waits for the task to end. */ /** busy_input: steer — the inbox goes in at the next step; queue — it waits for the task to end. */
busyInput: "steer" | "queue" = "steer" busyInput: "steer" | "queue" = "steer"
/** The session's plan (plan_write / plan_update), kept with the session and put into the /** The session's plan (plan_write / plan_update), kept with the session and put into the
@@ -248,6 +264,51 @@ export class Engine {
this.plan = this.storedPlan() this.plan = this.storedPlan()
this.results = this.resultsFor(o.sessionId) this.results = this.resultsFor(o.sessionId)
this.kept = this.storedPrefix() this.kept = this.storedPrefix()
this.carried = this.storedCarried()
}
/** What the store holds for this session that the model has not been given yet. */
private storedCarried(): Carried {
const none: Carried = { notes: [], steers: [] }
if (!this.o.store || !this.sessionId) return none
try {
const c = this.o.store.meta<Partial<Carried> | null>(this.sessionId, CARRIED_META)
if (!c || typeof c !== "object") return none
return {
notes: Array.isArray(c.notes) ? c.notes.filter((n): n is string => typeof n === "string") : [],
steers: Array.isArray(c.steers) ? c.steers.filter((x) => x && typeof x.text === "string").map((x) => ({ text: x.text, ...(typeof x.id === "string" ? { id: x.id } : {}) })) : [],
}
} catch {
return none
}
}
private saveCarried() {
if (!this.o.store || !this.sessionId) return
try {
this.o.store.setMeta(this.sessionId, CARRIED_META, this.carried.notes.length || this.carried.steers.length ? this.carried : null)
} catch {}
}
/** A note of the harness's that starts no turn — the turn it was for was stopped, or may not
* start: kept with the session, and given to the model with the next message. */
keepNote(text: string) {
this.carried.notes.push(text)
this.saveCarried()
}
/** Messages steered into this turn that it ended before taking in, with nobody to hand them
* back to: kept with the session, and given to the model at the next turn's first step — in
* every `busy_input` mode, since nobody will send them again. Emptied from the inbox, so they
* are never handed back as well. */
carry(): number {
const texts = this.inbox.splice(0)
const ids = this.inboxIds.splice(0)
if (!texts.length) return 0
this.carried.steers.push(...texts.map((text, i) => ({ text, ...(ids[i] ? { id: ids[i] } : {}) })))
this.saveCarried()
this.o.bus.emit({ type: "inbox", texts: [], mode: this.busyInput })
return texts.length
} }
/** The prefix the store holds for this session, if any: a resumed session sends what it kept. */ /** The prefix the store holds for this session, if any: a resumed session sends what it kept. */
@@ -534,6 +595,7 @@ export class Engine {
this.keptBase = undefined this.keptBase = undefined
this.lastRequest = undefined this.lastRequest = undefined
this.kept = this.storedPrefix() this.kept = this.storedPrefix()
this.carried = this.storedCarried()
this.o.bus.emit({ type: "plan", plan: this.plan }) this.o.bus.emit({ type: "plan", plan: this.plan })
this.o.toolCtx.readFiles.clear() this.o.toolCtx.readFiles.clear()
this.o.toolCtx.fileStamps.clear() this.o.toolCtx.fileStamps.clear()
@@ -724,6 +786,7 @@ export class Engine {
this.inbox.push(text) this.inbox.push(text)
this.inboxIds.push(id) this.inboxIds.push(id)
this.o.bus.emit({ type: "inbox", texts: [...this.inbox], mode: this.busyInput }) this.o.bus.emit({ type: "inbox", texts: [...this.inbox], mode: this.busyInput })
this.poke()
} }
/** How many messages wait. */ /** How many messages wait. */
@@ -731,6 +794,11 @@ export class Engine {
return this.inbox.length return this.inbox.length
} }
/** The messages that wait, left where they are. */
get unsent(): string[] {
return [...this.inbox]
}
/** Take one waiting message out (↑ in the box, to look at or edit it); `putBack` returns it. */ /** Take one waiting message out (↑ in the box, to look at or edit it); `putBack` returns it. */
unqueue(index: number): string | undefined { unqueue(index: number): string | undefined {
if (index < 0 || index >= this.inbox.length) return undefined if (index < 0 || index >= this.inbox.length) return undefined
@@ -759,6 +827,45 @@ export class Engine {
* carries its own mark. */ * carries its own mark. */
note(text: string) { note(text: string) {
this.notes.push(text) this.notes.push(text)
this.poke()
}
/** Something a waiting turn waits on may have changed (EngineOptions.hold): a note came, a
* subagent ended or was stopped. */
poke() {
const p = this.poked
this.poked = undefined
p?.()
}
/** Whether something waits to go to the model at the next step. */
private hasInput(): boolean {
return this.notes.length > 0 || this.carried.steers.length > 0 || (this.busyInput === "steer" && this.inbox.length > 0)
}
/** The reply is done and subagents of this turn are still out (EngineOptions.hold): wait for
* what they send. True: something came, and the turn goes on with it. False: nothing is out
* any more, or the turn was stopped (`signal`). */
private async awaitReports(signal: AbortSignal): Promise<boolean> {
const hold = this.o.hold
if (!hold || hold.out() === 0) return false
// Its slot goes to whoever waits for one: the reports are what it waits for.
hold.rest?.()
while (!signal.aborted && !this.hasInput() && hold.out() > 0) {
this.progress.set({ phase: "waiting_for_subagents", running: hold.out() })
await new Promise<void>((resolve) => {
const done = () => {
signal.removeEventListener("abort", done)
if (this.poked === done) this.poked = undefined
resolve()
}
this.poked = done
signal.addEventListener("abort", done, { once: true })
})
}
if (signal.aborted || !this.hasInput()) return false
// A slot again before it goes on (team.md §8) — it may wait for one, and be stopped waiting.
return this.o.team?.beforeTurn ? await this.o.team.beforeTurn(signal) : true
} }
/** Notes the task ended before delivering. */ /** Notes the task ended before delivering. */
@@ -777,13 +884,18 @@ export class Engine {
const said = notes.map((n) => n.split("\n").find((l, i) => i > 0 && l.trim()) ?? n.split("\n")[0]!).join("; ") const said = notes.map((n) => n.split("\n").find((l, i) => i > 0 && l.trim()) ?? n.split("\n")[0]!).join("; ")
this.o.bus.emit({ type: "notice", level: noteNeedsAttention(said) ? "warn" : "info", message: said }) this.o.bus.emit({ type: "notice", level: noteNeedsAttention(said) ? "warn" : "info", message: said })
} }
if (this.busyInput !== "steer" || !this.inbox.length) return notes.length > 0 // What an earlier turn left (carry) goes in whatever the mode; the inbox only when steering.
const texts = this.inbox.splice(0) const late = this.carried.steers.splice(0)
const ids = this.inboxIds.splice(0).filter((i): i is string => typeof i === "string") if (late.length) this.saveCarried()
const now = this.busyInput === "steer" ? this.inbox.splice(0) : []
const nowIds = this.busyInput === "steer" ? this.inboxIds.splice(0) : []
if (!late.length && !now.length) return notes.length > 0
const texts = [...late.map((x) => x.text), ...now]
const ids = [...late.map((x) => x.id), ...nowIds].filter((i): i is string => typeof i === "string")
this.turnSteers.push(...texts) this.turnSteers.push(...texts)
this.push({ role: "user", parts: [{ type: "text", text: `${this.o.steerMark ?? STEER_MARK}\n${texts.join("\n\n")}` }], turn: false }) this.push({ role: "user", parts: [{ type: "text", text: `${this.o.steerMark ?? STEER_MARK}\n${texts.join("\n\n")}` }], turn: false })
this.o.bus.emit({ type: "steered", texts, ...(ids.length ? { ids } : {}) }) this.o.bus.emit({ type: "steered", texts, ...(ids.length ? { ids } : {}) })
this.o.bus.emit({ type: "inbox", texts: [], mode: this.busyInput }) this.o.bus.emit({ type: "inbox", texts: [...this.inbox], mode: this.busyInput })
return true return true
} }
@@ -810,7 +922,9 @@ export class Engine {
this.busy = true this.busy = true
this.o.bus.emit({ type: "prompt", text: shown, ...(meta.turnId ? { turnId: meta.turnId } : {}), ...(meta.attachments?.length ? { attachments: meta.attachments } : {}), ...(meta.machine ? { machine: true as const } : {}) }) this.o.bus.emit({ type: "prompt", text: shown, ...(meta.turnId ? { turnId: meta.turnId } : {}), ...(meta.attachments?.length ? { attachments: meta.attachments } : {}), ...(meta.machine ? { machine: true as const } : {}) })
try { try {
return await this.run(text, [...this.pendingContext.splice(0), ...extra], meta.turnId, meta.machine, meta.maxSteps) const kept = this.carried.notes.splice(0)
if (kept.length) this.saveCarried()
return await this.run(text, [...kept, ...this.pendingContext.splice(0), ...extra], meta.turnId, meta.machine, meta.maxSteps)
} finally { } finally {
this.busy = false this.busy = false
} }
@@ -825,6 +939,17 @@ export class Engine {
if (!this.kept || this.kept.model !== this.model.ref) await this.o.beforeFirst?.() if (!this.kept || this.kept.model !== this.model.ref) await this.o.beforeFirst?.()
// A team's lead holds a slot of its model while its turn runs (team.md §8): it may wait for one. // A team's lead holds a slot of its model while its turn runs (team.md §8): it may wait for one.
if (this.o.team?.beforeTurn && !(await this.o.team.beforeTurn(signal))) { if (this.o.team?.beforeTurn && !(await this.o.team.beforeTurn(signal))) {
// Stopped while it waited for a slot. The turn has begun for everyone who listens — its
// `task` start and its `prompt` were said — so its message is in the conversation as any
// stopped turn's is, under the turn's id: a note that started it is not lost with it (and
// what was waiting to go in with it, `extra`, is not either), and the model reads it with
// the next message.
this.push({
role: "user",
parts: [{ type: "text", text }, ...extra.map((t) => (typeof t === "string" ? { type: "text" as const, text: t } : t))],
...(turnId ? { turnId } : {}),
...(machine ? { machine } : {}),
})
bus.emit({ type: "done", reason: "cancelled" }) bus.emit({ type: "done", reason: "cancelled" })
return "cancelled" return "cancelled"
} }
@@ -975,7 +1100,16 @@ export class Engine {
bus.emit({ type: "notice", level: "warn", message: `the reply hit the output limit${limit} while writing a tool call; a call cut short is not run, and the model is told to split it` }) bus.emit({ type: "notice", level: "warn", message: `the reply hit the output limit${limit} while writing a tool call; a call cut short is not run, and the model is told to split it` })
// The model is done, but the user said something meanwhile: it carries on with that, in the // The model is done, but the user said something meanwhile: it carries on with that, in the
// same task. // same task.
if (calls.length === 0 && !wrapUp && (this.notes.length || (this.busyInput === "steer" && this.inbox.length))) continue if (calls.length === 0 && !wrapUp && this.hasInput()) continue
// A run with nobody at it is not over while its subagents work: it waits for their reports,
// which come in at this step boundary, and answers after the last one.
if (calls.length === 0 && !wrapUp && this.o.hold) {
if (await this.awaitReports(signal)) continue
if (signal.aborted) {
bus.emit({ type: "done", reason: "cancelled" })
return "cancelled"
}
}
if (calls.length === 0 || wrapUp) { if (calls.length === 0 || wrapUp) {
const reason = wrapUp ? (ranOut ? "budget" : "steps") : "stop" const reason = wrapUp ? (ranOut ? "budget" : "steps") : "stop"
bus.emit({ type: "done", reason }) bus.emit({ type: "done", reason })
+374
View File
@@ -0,0 +1,374 @@
// What a session still has out after its turn's reply (harness/acp.md: *A turn the harness starts*,
// *Scheduled work on a linked computer*; spec 3.10.0): subagents that work, background jobs, a
// note or a steered message that has not reached the model. None of it is lost — not to a terminal
// opening the session, not to the service starting again, not to Stop, and not to a restart — and
// a schedule's run is not over while its subagents work.
import { afterEach, expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { AcpAgent, type Limits } from "../src/acp/agent.ts"
import { Hub } from "../src/acp/hub.ts"
import { Peer, type Transport } from "../src/acp/rpc.ts"
import { releaseForResume } from "../src/acp/share.ts"
import { createApp, type App } from "../src/app.ts"
import type { AskReply } from "../src/bus/index.ts"
import { paths } from "../src/config/paths.ts"
import { LOOP } from "../src/harness.ts"
import { MARKS } from "../src/jobs/note.ts"
import { setTrust } from "../src/project/root.ts"
import { delta, fakeProvider, toolCall, type Fake, type Scripted } from "./fake-provider.ts"
let fake: Fake | undefined
const stops: (() => unknown)[] = []
const roots: string[] = []
afterEach(async () => {
// Whatever a test left waiting for its flag ends now: no loop outlives the test, pass or fail.
for (const root of roots.splice(0)) for (const flag of ["f1", "f-api", "f-web"]) writeFileSync(join(root, flag), "")
for (const s of stops.splice(0).reverse()) await s()
fake?.stop()
})
function pair(): [Transport, Transport] {
const make = () => ({ msg: (_: string) => {}, end: () => {} })
const a = make()
const b = make()
const side = (me: typeof a, o: typeof a): Transport => ({
send: (t) => queueMicrotask(() => o.msg(t)),
onMessage: (fn) => (me.msg = fn),
onClose: (fn) => (me.end = fn),
close: () => (me.end(), o.end()),
})
return [side(a, b), side(b, a)]
}
const SLOW = 30_000
const say = (text: string): Scripted => ({ chunks: [delta({ content: text }, "stop")] })
const call = (id: string, name: string, args: unknown): Scripted => ({ chunks: [toolCall(0, id, name, JSON.stringify(args)), delta({}, "tool_calls")] })
/** A reply that stays open for `ms` after its first words: time to look at the turn while it runs. */
const slow = (text: string, ms = 2500): Scripted => ({ chunks: [delta({ content: "… " }), delta({ content: text })], gapMs: ms })
const system = (body: any): string => body.messages[0].content
const memberName = (body: any): string | undefined => /You are "([a-z0-9-]+)" \(s\d+\), a subagent/.exec(system(body))?.[1]
const users = (body: any): string => body.messages.filter((m: any) => m.role === "user").map((m: any) => (typeof m.content === "string" ? m.content : m.content.map((p: any) => p.text ?? "").join("\n"))).join("\n")
const leads = () => fake!.requests.filter((r) => !memberName(r))
/** The lead's script — its replies in order — and each member's by its name. A member that has
* said all it has says it is done. */
function scripted(lead: Scripted[], members: Record<string, Scripted[]> = {}) {
const at: Record<string, number> = {}
return (body: any): Scripted => {
const who = memberName(body) ?? "lead"
const list = who === "lead" ? lead : (members[who] ?? [])
const n = (at[who] = (at[who] ?? -1) + 1)
return list[n] ?? say(`${who} has nothing more.`)
}
}
/** A command that ends when the test lets it (`release`): never before, however slow the machine. */
const waitFor = (flag: string) => `until [ -e ${flag} ]; do sleep 0.05; done`
const add = (name: string, id = `add-${name}`) => call(id, "team_add", { name, role: `the ${name}`, task: `Do the ${name}.`, goal: "a service" })
/** A member that works until its flag is there, then reports. */
const member = (name: string, report = `The ${name} is done.`): Scripted[] => [call(`w-${name}`, "bash", { command: waitFor(`f-${name}`) }), say(report)]
function setup(script: Scripted[] | ((body: any, n: number) => Scripted | undefined), o: { config?: string; model?: string; models?: string } = {}) {
fake = fakeProvider(script)
mkdirSync(paths.config, { recursive: true })
writeFileSync(join(paths.config, "connections.yaml"), `connections:\n f:\n type: webui\n url: ${fake.url}\n models: ${o.models ?? "{ f/m: {} }"}\n`, { mode: 0o600 })
writeFileSync(join(paths.config, "config.yaml"), `model: ${o.model ?? "f/m"}\nmode: auto\n${o.config ?? ""}`)
const dir = realpathSync(mkdtempSync(join(tmpdir(), "ph-out-")))
Bun.spawnSync(["git", "init", "-q", dir])
setTrust(dir, "trusted")
roots.push(dir)
return dir
}
const limitsFor = (root: string, extra: Partial<Limits> = {}): Limits => ({ roots: [root], maxMode: "auto", approvalTimeoutMs: 3000, requireTrust: true, enabled: true, scheduled: true, ...extra })
/** A fake LLeMbas on a link of its own — to `hub`'s sessions when there is one. */
async function link(root: string, hub?: Hub) {
const [ta, tb] = pair()
new AcpAgent(new Peer(ta), limitsFor(root), undefined, hub)
const c = new Peer(tb)
const events: any[] = []
c.on("_lembas/event", (p) => void events.push(p.event))
c.handle("session/request_permission", () => ({ outcome: { outcome: "selected", optionId: "once" } }))
await c.request("initialize", { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { protocol: 3 } } } })
const machine = () => events.filter((e) => e.type === "prompt" && e.machine === true)
const ended = (turnId: string) => events.some((e) => e.type === "task" && e.state === "end" && e.turnId === turnId)
const texts = () => events.filter((e) => e.type === "text").map((e) => e.text).join("")
return { c, events, machine, ended, texts, drop: () => tb.close() }
}
async function service(root: string) {
const hub = new Hub({ service: true, limits: { ...limitsFor(root), enabled: true } })
expect(await hub.listen()).toBe(true)
stops.push(async () => {
for (const s of hub.held.values()) await s.app.close().catch(() => {})
hub.close()
})
return hub
}
const until = async (ok: () => boolean, ms = 10_000) => {
const end = Date.now() + ms
while (Date.now() < end && !ok()) await Bun.sleep(20)
return ok()
}
const go = (c: Peer, sid: string, text = "go", meta: Record<string, unknown> = {}) => c.request<any>("session/prompt", { sessionId: sid, prompt: [{ type: "text", text }], ...(Object.keys(meta).length ? { _meta: { lembas: meta } } : {}) })
const sched = (extra: Record<string, unknown> = {}) => ({ schedule_id: "sched1", run_id: "run7", title: "Check", mode: "auto", ...extra })
const waitingForSubagents = (events: any[]) => events.some((e) => e.type === "phase" && !e.agent && e.progress?.phase === "waiting_for_subagents")
// ── 1. A session with subagents or jobs out is not let go of ─────────────────────────────────
test("a subagent still works after the lead's turn: the service is busy, a terminal is refused in words, and the report still comes", async () => {
const root = setup(scripted([add("api"), say("api is on it."), say("All done.")], { api: member("api") }))
const hub = await service(root)
const { c, machine, ended, texts } = await link(root, hub)
const s: any = await c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
expect((await go(c, sid)).stopReason).toBe("end_turn")
// No turn runs — and the session is not idle: its subagent works.
expect((await c.request<any>("_lembas/session/status", { sessionId: sid })).busy).toBe(false)
expect(hub.busy()).toBe(true)
const why = await releaseForResume(sid)
expect(why).toContain("api")
expect(why).toContain("subagent")
// Nothing was stopped by the asking: the member reports, and the lead answers.
writeFileSync(join(root, "f-api"), "")
expect(await until(() => machine().length === 1 && ended(machine()[0].turnId))).toBe(true)
expect(texts()).toContain("All done.")
expect(users(leads().at(-1))).toContain("[Team report from api to lead:]\nThe api is done.")
// Now it is idle, and a terminal may have it.
expect(await until(() => !hub.busy())).toBe(true)
expect(await releaseForResume(sid)).toBeUndefined()
expect(hub.held.has(sid)).toBe(false)
}, SLOW)
test("a background command still runs after the turn: busy, and a terminal is told which job", async () => {
const root = setup([call("j1", "bash", { command: waitFor("f1"), background: true, description: "wait for f1" }), say("Started."), say("Seen the end.")])
const hub = await service(root)
const { c, machine, ended } = await link(root, hub)
const s: any = await c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
await go(c, sid)
expect(hub.busy()).toBe(true)
const why = await releaseForResume(sid)
expect(why).toContain("job1")
expect(hub.held.has(sid)).toBe(true)
writeFileSync(join(root, "f1"), "")
expect(await until(() => machine().length === 1 && ended(machine()[0].turnId))).toBe(true)
expect(await until(() => !hub.busy())).toBe(true)
expect(await releaseForResume(sid)).toBeUndefined()
}, SLOW)
// ── 2. A schedule's run is not over while its subagents work ─────────────────────────────────
test("a scheduled run that uses a team: one turn, the answer and the report from its last reply — after the member reported", async () => {
const report = { title: "The API", summary: "The API is written.", body: "## Done\n\nsrc/api.ts" }
const root = setup(scripted([add("api"), say("api is on it."), call("r1", "report_write", report), say("Filed: the API is done.")], { api: member("api") }))
const { c, events, machine } = await link(root)
const meta = { scheduled: sched({ notify: "always" }) }
const s: any = await c.request("session/new", { cwd: root, mcpServers: [], _meta: { lembas: meta } })
const sid = s.sessionId as string
let answered = false
const run = go(c, sid, "check", { turnId: "run7", ...meta }).then((r) => ((answered = true), r))
await until(() => answered || waitingForSubagents(events))
// The lead's reply has ended and the member works: the run has not answered.
expect(answered).toBe(false)
expect(await c.request<any>("_lembas/session/status", { sessionId: sid })).toMatchObject({ busy: true, turnId: "run7" })
writeFileSync(join(root, "f-api"), "")
const r = await run
expect(r.stopReason).toBe("end_turn")
expect(r._meta.lembas.scheduled).toEqual({ run_id: "run7", status: "ok", text: "Filed: the API is done.", error: null, report: { ...report, importance: "normal" } })
// One turn from start to end: the report came in at a step, not as a turn of its own.
expect(events.filter((e) => e.type === "task").map((e) => `${e.state} ${e.turnId}`)).toEqual(["start run7", "end run7"])
expect(machine()).toHaveLength(0)
expect(users(leads()[2])).toContain("[Team report from api to lead:]\nThe api is done.")
// A schedule's session is offered a team, and its run report_write.
const tools = leads()[0].tools.map((t: any) => t.function.name)
expect(tools).toEqual(expect.arrayContaining(["team_add", "report_write"]))
// Nothing of the run is left working.
const after = await c.request<any>("_lembas/session/status", { sessionId: sid })
expect(after.busy).toBe(false)
expect(after.tree.agents.filter((a: any) => a.state === "working" || a.state === "waiting").map((a: any) => a.name)).toEqual([])
}, SLOW)
test("a waiting run holds no slot: with two slots and two subagents both work at once, and each report comes into the one turn", async () => {
const root = setup(scripted([add("api"), add("web"), say("Both are on it."), say("One is in."), say("Both are in.")], { api: member("api"), web: member("web") }), { models: "{ f/m: { parallel: 2 } }" })
const { c, events, machine } = await link(root)
const meta = { scheduled: sched() }
const s: any = await c.request("session/new", { cwd: root, mcpServers: [], _meta: { lembas: meta } })
const sid = s.sessionId as string
let answered = false
const run = go(c, sid, "check", { turnId: "run7", ...meta }).then((r) => ((answered = true), r))
await until(() => answered || waitingForSubagents(events))
expect(answered).toBe(false)
// While the main agent's own turn ran, web waited for a slot; now it has the main agent's.
const states = async () => Object.fromEntries((await c.request<any>("_lembas/session/status", { sessionId: sid })).tree.agents.map((a: any) => [a.name, a.state]))
expect(await states()).toEqual({ lead: "idle", api: "working", web: "working" })
writeFileSync(join(root, "f-api"), "")
expect(await until(() => answered || leads().length === 4)).toBe(true)
expect(answered).toBe(false)
writeFileSync(join(root, "f-web"), "")
const r = await run
expect(r._meta.lembas.scheduled).toMatchObject({ status: "ok", text: "Both are in." })
expect(events.filter((e) => e.type === "task").map((e) => `${e.state} ${e.turnId}`)).toEqual(["start run7", "end run7"])
expect(machine()).toHaveLength(0)
expect(users(leads()[3])).toContain("[Team report from api to lead:]")
expect(users(leads()[4])).toContain("[Team report from web to lead:]")
expect(await states()).toEqual({ lead: "idle", api: "finished", web: "finished" })
}, SLOW)
// ── 6. Stop ──────────────────────────────────────────────────────────────────────────────────
test("Stop on a scheduled run stops the run: the turn, and the subagent still working for it", async () => {
const root = setup(scripted([add("api"), say("api is on it.")], { api: member("api") }))
const { c, events, machine } = await link(root)
const meta = { scheduled: sched() }
const s: any = await c.request("session/new", { cwd: root, mcpServers: [], _meta: { lembas: meta } })
const sid = s.sessionId as string
let answered = false
const run = go(c, sid, "check", { turnId: "run7", ...meta }).then((r) => ((answered = true), r))
await until(() => answered || waitingForSubagents(events))
expect(answered).toBe(false)
c.notify("session/cancel", { sessionId: sid })
const r = await run
expect(r.stopReason).toBe("cancelled")
expect(r._meta.lembas.scheduled.status).toBe("cancelled")
// The member left with the run: stopped, and nothing of it starts a turn afterwards.
const tree = (await c.request<any>("_lembas/session/status", { sessionId: sid })).tree
expect(tree.agents.map((a: any) => a.name)).toEqual(["lead"])
expect(tree.ended.map((a: any) => `${a.name} ${a.state}`)).toEqual(["api stopped"])
const asked = fake!.requests.length
writeFileSync(join(root, "f-api"), "")
await Bun.sleep(300)
expect(fake!.requests).toHaveLength(asked)
expect(machine()).toHaveLength(0)
}, SLOW)
test("Stop in a chat stops the turn that runs and no subagent: the next report starts a turn as any does", async () => {
const root = setup(scripted([add("api"), add("web"), say("Both are on it."), slow("Looking at the API.", 5000), say("And the web is in.")], { api: member("api"), web: member("web") }))
const { c, events, machine, ended } = await link(root)
const s: any = await c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
await go(c, sid)
writeFileSync(join(root, "f-api"), "")
// Stopped once its reply has begun: the model was asked, so the next turn gets the next reply.
expect(await until(() => machine().length === 1 && events.some((e) => e.type === "text" && e.text === "… "))).toBe(true)
c.notify("session/cancel", { sessionId: sid })
expect(await until(() => ended(machine()[0].turnId))).toBe(true)
expect(events.some((e) => e.type === "done" && e.reason === "cancelled")).toBe(true)
// web was not stopped with the lead's turn.
const tree = (await c.request<any>("_lembas/session/status", { sessionId: sid })).tree
expect(tree.agents.find((a: any) => a.name === "web").state).toBe("working")
writeFileSync(join(root, "f-web"), "")
expect(await until(() => machine().length === 2 && ended(machine()[1].turnId))).toBe(true)
expect(machine()[1].text).toBe("⏎ [Team report from web to lead:]")
}, SLOW)
// ── 3. Stop while a wake turn waits for a model slot ─────────────────────────────────────────
test("Stop while a wake turn waits for a slot: its note stays in the history under the turn's id, and the model reads it next", async () => {
const root = setup(
scripted([call("j1", "bash", { command: waitFor("f1"), background: true, description: "wait for f1" }), add("api"), add("web"), say("Waiting."), say("All in.")], { api: member("api"), web: member("web") }),
{ models: "{ f/m: { parallel: 2 } }" },
)
const { c, events, machine, ended } = await link(root)
const s: any = await c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
await go(c, sid, "go", { turnId: "web-1" })
// Both slots are the members'. The job ends: its note wakes the lead, which waits for a slot.
writeFileSync(join(root, "f1"), "")
expect(await until(() => machine().length === 1 && events.some((e) => e.type === "notice" && String(e.message).startsWith("waiting for a free slot")))).toBe(true)
const m = machine()[0]
c.notify("session/cancel", { sessionId: sid })
expect(await until(() => ended(m.turnId))).toBe(true)
// The client was told the turn began: the history has it, as it has any stopped turn.
const h: any = await c.request("_lembas/session/history", { sessionId: sid })
const note = h.turns.find((t: any) => t.turnId === m.turnId)
expect(note).toBeDefined()
expect(note.machine).toBe(true)
expect(note.text).toStartWith(`${MARKS.command}\njob1 (${waitFor("f1")}) exited with 0`)
// …and the model reads it with what comes next.
writeFileSync(join(root, "f-api"), "")
writeFileSync(join(root, "f-web"), "")
expect(await until(() => leads().some((r) => users(r).includes("[Team report from")))).toBe(true)
expect(users(leads().at(-1))).toContain(`job1 (${waitFor("f1")}) exited with 0`)
}, SLOW)
// ── 4, 7. A message steered into a turn the harness started ──────────────────────────────────
test("a steer a wake turn never took in comes back on the turn's end — said before the queue is said empty", async () => {
const root = setup([call("j1", "bash", { command: waitFor("f1"), background: true, description: "wait for f1" }), say("Started."), slow("Never finished.", 5000)])
const { c, events, machine, ended } = await link(root)
const s: any = await c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
await go(c, sid)
writeFileSync(join(root, "f1"), "")
expect(await until(() => machine().length === 1)).toBe(true)
const m = machine()[0]
await c.request("_lembas/steer", { sessionId: sid, text: "one more thing" })
const steered = events.length
c.notify("session/cancel", { sessionId: sid })
expect(await until(() => ended(m.turnId), 3000)).toBe(true)
await Bun.sleep(50)
const end = events.findIndex((e) => e.type === "task" && e.state === "end" && e.turnId === m.turnId)
expect(events[end].unsent).toEqual(["one more thing"])
const emptied = events.findIndex((e, i) => i >= steered && e.type === "inbox" && e.texts.length === 0)
expect(emptied === -1 || emptied > end).toBe(true)
}, SLOW)
test("a steer left over with no client listening is kept with the session — across a restart — and goes in at the next turn's first step, once", async () => {
// busy_input: queue — the mode in which nothing went in at a step by itself.
const root = setup([call("j1", "bash", { command: waitFor("f1"), background: true, description: "wait for f1" }), say("Started."), slow("Seen the end.", 1500), say("And that too.")], { config: "busy_input: queue\n" })
const hub = await service(root)
const first = await link(root, hub)
const s: any = await first.c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
await go(first.c, sid, "go", { turnId: "web-1" })
writeFileSync(join(root, "f1"), "")
expect(await until(() => first.machine().length === 1)).toBe(true)
expect(await first.c.request<any>("_lembas/steer", { sessionId: sid, text: "and one more thing", messageId: "web-2" })).toEqual({ queued: 1 })
// The link goes; the turn ends with nobody to hand the message back to.
first.drop()
const held = hub.held.get(sid)!
expect(await until(() => held.own === undefined && !held.app.engine.busy)).toBe(true)
// The device starts again: the session is opened from the store, by another process's agent.
await held.app.close()
hub.held.delete(sid)
const again = await link(root)
const r = await go(again.c, sid, "next", { turnId: "web-3" })
expect(r.stopReason).toBe("end_turn")
// In at the first step of the next turn, said with its id — and not handed back as well.
expect(again.events.find((e) => e.type === "steered")).toMatchObject({ texts: ["and one more thing"], ids: ["web-2"] })
expect(users(fake!.requests.at(-1))).toContain("and one more thing")
expect(r._meta.lembas.unsent).toBeUndefined()
// Once: the turn after it does not carry it again.
const h: any = await again.c.request("_lembas/session/history", { sessionId: sid })
expect(JSON.stringify(h.turns).split("and one more thing")).toHaveLength(2)
// The harness's turn is still marked as one after the restart (the store keeps `machine`).
expect(h.turns.filter((t: any) => t.machine).map((t: any) => t.turnId)).toEqual([first.machine()[0].turnId])
}, SLOW)
// ── 5. A wake that is refused leaves the lead idle, and the note waits ───────────────────────
test("a report that may not start a turn (a schedule's session on an interactive-only model): the lead is idle again, and the report goes in with the person's next message", async () => {
const root = setup(scripted([add("api"), say("api is on it."), say("Here it is.")], { api: member("api") }), { model: "open/flash", models: "{ open/flash: {}, plan/coder: { interactive_only: true } }" })
const yes = { ask: async (): Promise<AskReply> => ({ kind: "once" }) }
const app: App = createApp({ cwd: root, asker: yes, snapshots: false, modelTitles: false, kind: "scheduled" })
stops.push(() => app.close())
const notices: string[] = []
app.bus.on((e) => e.type === "notice" && notices.push(e.message))
// The person writes into the run's chat, and the lead starts a subagent.
await app.turns.prompt("build it")
// Between turns the session's model is changed to the plan's.
app.chooseModel("plan/coder")
writeFileSync(join(root, "f-api"), "")
expect(await until(() => notices.some((n) => n.includes("did not start a turn")))).toBe(true)
expect(app.engine.busy).toBe(false)
expect(app.team.team.get("lead")!.state).toBe("idle")
// The person's next turn carries the report.
await app.turns.prompt("and?")
expect(users(leads().at(-1))).toContain("[Team report from api to lead:]\nThe api is done.")
expect(LOOP.interactive.texts.scheduled).toContain("interactive use only")
}, SLOW)