session/cancel may name its turn: a queued prompt is taken back, the running turn left alone
ci / check (push) Canceled after 0s

A prompt can wait behind a turn its client did not start, and ACP's cancel
names no turn: a client stopping a reply whose prompt still waited stopped
whatever ran instead, and its own prompt ran later with nobody following.

Spec (3.10.0, unreleased; part of capability harness_turns): an optional
_meta.lembas.turnId on session/cancel. Running: stopped. Queued: taken out
of the queue, its session/prompt answered stopReason "cancelled" at once (a
scheduled one with scheduled.status "cancelled"), the running turn not
touched, the id still known. Neither: nothing. Without the id: the running
turn, as before. Sent as a request, the cancel is answered
{ cancelled: "running" | "queued" | "none" }. conformance/cancel.json, 7
cases (acp/turns.ts cancelOf).

Device: acp/agent.ts (a prompt that waits can be withdrawn), and for a
session a terminal runs acp/share.ts (hub/cancel as a request with the
turn; a web prompt not yet started there is withdrawn, and nothing is sent
when its place comes). A terminal of a build without that request is not
told to stop whatever runs.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-23 16:09:21 +00:00
1 parent 87ecaca6db
commit 9f26316a49
9 files changed
+396 -17

No files matched your search

+4
View File
@@ -45,6 +45,10 @@ Harness spec 3.10.0: a turn the harness starts by itself is a turn like any othe
back over, the message is kept with the session — also across a restart of the service — and 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 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. `busy_input: queue` came back attached to an unrelated later prompt.
- **Stop in the web UI stops the reply you stopped.** If your message was still waiting behind a
turn the agent had started by itself (answering a finished job or a subagent), Stop used to end
that turn instead and your message ran afterwards anyway. A server that names the turn
(harness spec 3.10.0) now gets exactly that turn stopped, or taken out of the queue.
- **A job's or subagent's note that arrives after you pressed Stop survives a restart** and goes - **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 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 - **In a schedule's chat on a model for interactive use only**, a subagent's report that may not
+8
View File
@@ -134,6 +134,14 @@ follows 3.10.0 as first written follows this.
comes before the `inbox` event that says the queue is empty. comes before the `inbox` event that says the queue is empty.
- **A wake that may not start a turn** (a schedule's session on an interactive-only model): the - **A wake that may not start a turn** (a schedule's session on an interactive-only model): the
session is idle again and the note is kept for the person's next message. session is idle again and the note is kept for the person's next message.
- **`session/cancel` may name its turn** (`_meta.lembas.turnId`; part of `harness_turns`, which no
release has carried yet; `conformance/cancel.json`, 7 cases). A prompt can now wait behind a
turn its client did not start, and a cancel that names no turn stops whatever runs: a client
stopping a reply whose prompt still waited stopped the harness's turn instead, and its own
prompt ran later with nobody following. With the id: the turn is stopped if it runs; taken out
of the queue if it waits — its `session/prompt` answered `cancelled`, the running turn left
alone; nothing if it is neither. Sent as a request, the cancel is answered
`{ cancelled: "running" | "queued" | "none" }`. Without the id, as before.
## 3.9.0 ## 3.9.0
+34 -5
View File
@@ -69,7 +69,7 @@ change to the protocol is a change here first, then in both projects.
| `tree` | spec 3.4.0 (`subagents.md` §5–§13): the `team` event; `_lembas/team`, `_lembas/team/transcript`, `_lembas/team/findings`, `_lembas/team/stop`; `subagent` on `session/request_permission` | | `tree` | spec 3.4.0 (`subagents.md` §5–§13): the `team` event; `_lembas/team`, `_lembas/team/transcript`, `_lembas/team/findings`, `_lembas/team/stop`; `subagent` on `session/request_permission` |
| `scheduled` | spec 3.5.0 (*Scheduled work on a linked computer*, below): `scheduled` in `_meta.lembas` of `session/new` and `session/prompt` read, and the run's outcome in the prompt's answer; `scheduled` on `session/request_permission`; `_lembas/monitor`; `limits.scheduled` in `_lembas/hello` and `initialize`. Listed by every build that has it, whatever the setting says: whether this device *accepts* scheduled work is `limits.scheduled` | | `scheduled` | spec 3.5.0 (*Scheduled work on a linked computer*, below): `scheduled` in `_meta.lembas` of `session/new` and `session/prompt` read, and the run's outcome in the prompt's answer; `scheduled` on `session/request_permission`; `_lembas/monitor`; `limits.scheduled` in `_lembas/hello` and `initialize`. Listed by every build that has it, whatever the setting says: whether this device *accepts* scheduled work is `limits.scheduled` |
| `directory_model` | spec 3.9.0 (*The model last used in a directory*, below): `model` on a `Dir` of `_lembas/directories`' answer; `list: false` in its params | | `directory_model` | spec 3.9.0 (*The model last used in a directory*, below): `model` on a `Dir` of `_lembas/directories`' answer; `list: false` in its params |
| `harness_turns` | spec 3.10.0 (*A turn the harness starts*, below): such a turn is a turn in `_lembas/session/status` (`busy`, `turnId`, then `lastTurnId`), takes `_lembas/steer`, hands back `unsent` on its `task` end, makes a prompt wait, and is in `_lembas/session/history` as a user turn with `machine` | | `harness_turns` | spec 3.10.0 (*A turn the harness starts*, below): such a turn is a turn in `_lembas/session/status` (`busy`, `turnId`, then `lastTurnId`), takes `_lembas/steer`, hands back `unsent` on its `task` end, makes a prompt wait, and is in `_lembas/session/history` as a user turn with `machine`; and — since prompts now wait behind turns the client did not start — `_meta.lembas.turnId` on `session/cancel` names the turn to stop or to take out of the queue, and `session/cancel` sent as a request is answered |
| `reports` | spec 3.8.0 (`reports.md` §6): `scheduled.notify` in `_meta.lembas` of `session/new` and `session/prompt` read; `report_write` offered to the model of a schedule's run that notifies; the report the run wrote carried in the prompt's answer (`scheduled.report`); the status `silent` no longer given to a turn whose request said `notify` | | `reports` | spec 3.8.0 (`reports.md` §6): `scheduled.notify` in `_meta.lembas` of `session/new` and `session/prompt` read; `report_write` offered to the model of a schedule's run that notifies; the report the run wrote carried in the prompt's answer (`scheduled.report`); the status `silent` no longer given to a turn whose request said `notify` |
## Standard ACP, as used here ## Standard ACP, as used here
@@ -216,10 +216,38 @@ where `_meta.lembas` may also carry:
Params: `{ sessionId, modeId }`, lowered to `remote.max_mode`. Result `{}`. Params: `{ sessionId, modeId }`, lowered to `remote.max_mode`. Result `{}`.
### `session/cancel` — client → agent (notification) ### `session/cancel` — client → agent (notification, or a request)
Params: `{ sessionId }`. Stops the running turn, whoever started it: the client's prompt, a turn Params: `{ sessionId, _meta?: { lembas?: { turnId?: string } } }`.
typed in a terminal, or one the harness started. Prompts waiting behind it still run. **It stops
**Without a `turnId`** — ACP's own cancel, and all a device before 3.10.0 knows: stops the running
turn, whoever started it: the client's prompt, a turn typed in a terminal, or one the harness
started. Prompts waiting behind it still run.
**With `_meta.lembas.turnId`** (spec 3.10.0, capability `harness_turns`; `conformance/cancel.json`)
the client says **which turn it means** — where `session/prompt` carries the same id, in
`_meta.lembas` like every other extension of an ACP method — and only that turn is touched:
| The turn named is | The device |
|---|---|
| **running** | stops it, as a cancel without an id does |
| **queued** (its `session/prompt` waits behind another turn) | takes it out of the queue: it never runs, its `session/prompt` is answered at once with `stopReason: "cancelled"` (a scheduled one with `scheduled.status: "cancelled"`), and **the turn that runs is not touched**. The id stays known: the same prompt sent again gets that answer and does not run |
| **neither** (finished already, or never heard of) | does nothing |
Without the id a client that stops a reply whose prompt still waits on the device stops whatever
runs there instead — the harness's own turn, a terminal's — and its own prompt runs afterwards
with nobody following it. A client sends the id whenever it knows the turn it means and the
device lists `harness_turns`; a device without the capability ignores `_meta` and stops the
running turn, so to such a device a client sends a cancel only when its own turn is the one
running (`_lembas/session/status`).
**The answer.** As a notification it is answered with nothing, as ACP has it. Sent as a
**request** (the same method and params, with an id) a device with the capability answers
`{ cancelled: "running" | "queued" | "none" }` — what it found the turn to be, or for a cancel
without an id whether a turn ran — so a client that needs to know whether anything was stopped
asks, and one that does not need not wait.
**It stops
the turn, not the team**: subagents that work go on, and a report that arrives later starts a turn the turn, not the team**: subagents that work go on, and a report that arrives later starts a turn
as any does (*A turn the harness starts*) — a subagent is stopped by `_lembas/team/stop`. The one as any does (*A turn the harness starts*) — a subagent is stopped by `_lembas/team/stop`. The one
exception is a scheduled turn, where Stop stops the run and its subagents with it (*Scheduled exception is a scheduled turn, where Stop stops the run and its subagents with it (*Scheduled
@@ -684,7 +712,8 @@ with the note as its user message (`loop.json` `jobs`, `team.md` §7). Nobody ty
stopped turn like any other: its user turn is in the history under its id, the note with it, stopped turn like any other: its user turn is in the history under its id, the note with it,
and the model reads it with the next message. Nothing of it is lost. and the model reads it with the next message. Nothing of it is lost.
- **A prompt** (`session/prompt`) that arrives while it runs waits its turn — it is in `queued` — - **A prompt** (`session/prompt`) that arrives while it runs waits its turn — it is in `queued` —
and runs after the turn's `task` end. A prompt carrying the harness turn's own id does not run: and runs after the turn's `task` end; the client that no longer wants it takes it back with
`session/cancel` and its `turnId`, which leaves this turn alone. A prompt carrying the harness turn's own id does not run:
the id is known, and the answer is `null` (the turn has none of this side's). the id is known, and the answer is `null` (the turn has none of this side's).
- **Compacting and rewinding** (`_lembas/session/compact`, `_lembas/session/rewind`) are refused - **Compacting and rewinding** (`_lembas/session/compact`, `_lembas/session/rewind`) are refused
while it runs, as during any turn. Once it has ended it is rewound by its id like any turn. while it runs, as during any turn. Once it has ended it is rewound by its id like any turn.
+77
View File
@@ -0,0 +1,77 @@
{
"about": "Spec 3.10.0 (acp.md, `session/cancel`): which turn a cancel touches. `turn`: the `_meta.lembas.turnId` the cancel carries, absent for ACP's own cancel; `running`: the id of the turn that runs in the session now, absent when none does; `queued`: the ids of the prompts waiting their turn. The result `cancelled` is what the device answers a cancel sent as a request: `running` — the running turn is stopped; `queued` — that prompt is taken out of the queue and answered `cancelled`, and the running turn is not touched; `none` — nothing is done. `stops`: the id of the turn stopped, `withdraws`: the id taken out of the queue (each absent when none). LLeMbas: what it may expect of a device with `harness_turns`; CLI: acp/turns.ts `cancelOf`.",
"cases": [
{
"about": "No id, a turn runs: ACP's cancel — the running turn, whoever started it.",
"running": "h2",
"queued": [
"t8"
],
"expect": {
"cancelled": "running",
"stops": "h2"
}
},
{
"about": "No id, nothing runs: nothing to stop.",
"queued": [],
"expect": {
"cancelled": "none"
}
},
{
"about": "The turn named is the one that runs: stopped.",
"turn": "t7",
"running": "t7",
"queued": [],
"expect": {
"cancelled": "running",
"stops": "t7"
}
},
{
"about": "The turn named waits behind a harness turn: taken out of the queue; the harness turn is not touched.",
"turn": "t8",
"running": "h2",
"queued": [
"t8"
],
"expect": {
"cancelled": "queued",
"withdraws": "t8"
}
},
{
"about": "Two prompts wait; the second is named: only it goes.",
"turn": "t9",
"running": "h2",
"queued": [
"t8",
"t9"
],
"expect": {
"cancelled": "queued",
"withdraws": "t9"
}
},
{
"about": "The turn named finished already, while another runs: nothing is done — the running turn is somebody else's.",
"turn": "t6",
"running": "h2",
"queued": [
"t8"
],
"expect": {
"cancelled": "none"
}
},
{
"about": "An id the session never heard of, nothing running: nothing is done.",
"turn": "x1",
"queued": [],
"expect": {
"cancelled": "none"
}
}
]
}
+54 -8
View File
@@ -33,7 +33,7 @@ import { dropAttachments, preparePrompt, storedAttachments } from "./prompt.ts"
import { addPendingDeleted, clearPendingDeleted, pendingDeleted } from "./pending.ts" import { addPendingDeleted, clearPendingDeleted, pendingDeleted } from "./pending.ts"
import { pickShell, shellLaunch } from "./shellrc.ts" import { pickShell, shellLaunch } from "./shellrc.ts"
import { callTitle } from "../session/display.ts" import { callTitle } from "../session/display.ts"
import { sessionTurnFile, sessionTurns, TurnLog } from "./turns.ts" import { cancelOf, sessionTurnFile, sessionTurns, TurnLog } from "./turns.ts"
import { expandHome } from "../config/paths.ts" import { expandHome } from "../config/paths.ts"
import { asMode, MODES, type Mode } from "../config/schema.ts" import { asMode, MODES, type Mode } from "../config/schema.ts"
import { isLevel, readLevel, type Level } from "../provider/effort.ts" import { isLevel, readLevel, type Level } from "../provider/effort.ts"
@@ -188,6 +188,9 @@ export interface Session {
own?: { turnId: string; end: () => void } own?: { turnId: string; end: () => void }
/** Its turns by id: a prompt sent twice runs once. */ /** Its turns by id: a prompt sent twice runs once. */
turns: TurnLog<PromptResult> turns: TurnLog<PromptResult>
/** The prompts waiting their turn, by id: what takes one out of the queue (`session/cancel`
* with its turnId) — it is answered as cancelled then, and never runs. */
waiting?: Map<string, () => void>
/** The command set last sent to the client, to send it again only when it changed. */ /** The command set last sent to the client, to send it again only when it changed. */
commands?: string commands?: string
/** Spec 3.8.0: the report the run under way has written (the last one), for its answer. */ /** Spec 3.8.0: the report the run under way has written (the last one), for its answer. */
@@ -564,7 +567,10 @@ export class AcpAgent {
peer.on("_lembas/terminal/input", (p) => this.terminalInput(p)) peer.on("_lembas/terminal/input", (p) => this.terminalInput(p))
peer.on("_lembas/terminal/resize", (p) => this.terminalResize(p)) peer.on("_lembas/terminal/resize", (p) => this.terminalResize(p))
peer.on("_lembas/terminal/close", (p) => this.terminalClose(String(p?.terminalId ?? ""))) peer.on("_lembas/terminal/close", (p) => this.terminalClose(String(p?.terminalId ?? "")))
peer.on("session/cancel", (p) => this.cancel(p)) // ACP's notification, answered with nothing — and the same as a request, answered with what
// was found (acp.md `session/cancel`).
peer.on("session/cancel", (p) => void this.cancel(p).catch(() => {}))
peer.handle("session/cancel", (p) => this.cancel(p))
// With the hub (the service), the sessions are its, not this link's: a link that drops // With the hub (the service), the sessions are its, not this link's: a link that drops
// and comes back -- the instance updated, the network blinked -- finds them still working, and // and comes back -- the instance updated, the network blinked -- finds them still working, and
// the instance follows them again instead of losing the turn. Without it (`serve --stdio`), the // the instance follows them again instead of losing the turn. Without it (`serve --stdio`), the
@@ -1153,15 +1159,30 @@ export class AcpAgent {
s.app.setAutomated(false) s.app.setAutomated(false)
} }
} }
return s.turns.run(turnId, (started) => { /** The queue's tail is this turn until it is over. */
// Idle: it starts now, in this tick — a steer sent right after it must find the session working. const chain = (next: Promise<PromptResult>): Promise<PromptResult> => {
const next = s.queue ? s.queue.then(() => run(started), () => run(started)) : run(started)
const tail = next.catch(() => {}) const tail = next.catch(() => {})
s.queue = tail s.queue = tail
void tail.then(() => { void tail.then(() => {
if (s.queue === tail) s.queue = undefined if (s.queue === tail) s.queue = undefined
}) })
return next return next
}
return s.turns.run(turnId, (started) => {
// Idle: it starts now, in this tick — a steer sent right after it must find the session working.
if (!s.queue) return chain(run(started))
// It waits its turn — and may be taken back while it does (`session/cancel` with its id):
// answered as cancelled at once, and when its place in the queue comes nothing runs.
let withdrawn = false
let bail!: (r: PromptResult) => void
const gone = new Promise<PromptResult>((r) => (bail = r))
const cancelled: PromptResult = { stopReason: "cancelled", _meta: { lembas: { turnId, ...(scheduled ? { scheduled: runOutcome({ runId: scheduled.runId, reason: "cancelled", text: "" }) } : {}) } } }
const waiting = (s.waiting ??= new Map())
waiting.set(turnId, () => ((withdrawn = true), waiting.delete(turnId), bail(cancelled)))
const turn = () => (waiting.delete(turnId), withdrawn ? Promise.resolve(cancelled) : run(started))
const ran = chain(s.queue.then(turn, turn))
ran.catch(() => {})
return Promise.race([ran, gone])
}) })
} }
@@ -1547,10 +1568,35 @@ export class AcpAgent {
return {} return {}
} }
private cancel(p: any) { /** `session/cancel`: stop the running turn — or, with `_meta.lembas.turnId`, that turn and no
* other: stopped when it runs, taken out of the queue when it waits (its prompt is answered as
* cancelled and never runs), nothing when it is neither. What was found is the answer. */
private async cancel(p: any): Promise<{ cancelled: "running" | "queued" | "none" }> {
const named = p?._meta?.lembas?.turnId
const turn = typeof named === "string" && named.trim() ? named.trim().slice(0, 100) : undefined
const t = this.terminalFor(p) const t = this.terminalFor(p)
if (t) return t.client.notify("hub/cancel", { sessionId: t.sessionId }) if (t) {
this.sessions.get(String(p?.sessionId ?? ""))?.app.cancel() // The terminal knows its turns. One named is asked of it; a terminal of a build that has no
// such request is not told to stop whatever runs there.
if (turn !== undefined) return t.client.request<{ cancelled: "running" | "queued" | "none" }>("hub/cancel", { sessionId: t.sessionId, turnId: turn }, 15_000).catch(() => ({ cancelled: "none" as const }))
t.client.notify("hub/cancel", { sessionId: t.sessionId })
return { cancelled: t.busy ? "running" : "none" }
}
const s = this.sessions.get(String(p?.sessionId ?? ""))
if (!s) return { cancelled: "none" }
// ACP's own cancel: whatever runs, as ever.
if (turn === undefined) {
const ran = working(s)
s.app.cancel()
return { cancelled: ran ? "running" : "none" }
}
const found = cancelOf({ turn, ...(s.turns.running ? { running: s.turns.running } : {}), queued: s.turns.queued() })
if (found.withdraws !== undefined) {
const take = s.waiting?.get(found.withdraws)
if (!take) return { cancelled: "none" }
take()
} else if (found.stops !== undefined) s.app.cancel()
return { cancelled: found.cancelled }
} }
private update(s: Session, update: Record<string, unknown>) { private update(s: Session, update: Record<string, unknown>) {
+35 -3
View File
@@ -18,7 +18,7 @@ import { readLevel } from "../provider/effort.ts"
import { clampMode, effortOf, markRemote, permissionParams, planParams, planReplyFrom, questionParams, questionReplyFrom, replyFrom, STOP, type PromptResult } from "./agent.ts" import { clampMode, effortOf, markRemote, permissionParams, planParams, planReplyFrom, questionParams, questionReplyFrom, replyFrom, STOP, type PromptResult } from "./agent.ts"
import { jobList, jobOutput, jobSend, jobStop, jobTranscript, teamFindings, teamStop, teamTranscript, teamView, treeOf } from "./jobs.ts" import { jobList, jobOutput, jobSend, jobStop, jobTranscript, teamFindings, teamStop, teamTranscript, teamView, treeOf } from "./jobs.ts"
import type { SessionContext } from "../app.ts" import type { SessionContext } from "../app.ts"
import { sessionTurnFile, sessionTurns, type TurnLog } from "./turns.ts" import { cancelOf, sessionTurnFile, sessionTurns, type TurnLog } from "./turns.ts"
import { dropAttachments, preparePrompt } from "./prompt.ts" import { dropAttachments, preparePrompt } from "./prompt.ts"
import { connectHub, Hub } from "./hub.ts" import { connectHub, Hub } from "./hub.ts"
import { isLocal } from "../config/paths.ts" import { isLocal } from "../config/paths.ts"
@@ -459,6 +459,9 @@ export class Share {
} }
} }
/** The web UI's prompts that have not started here yet, by turn id: what takes one back. */
private waiting = new Map<string, () => void>()
private mine(p: any) { private mine(p: any) {
if (!this.sharedId || p?.sessionId !== this.sharedId) throw new RpcError(INVALID_PARAMS, "that session is not open in this terminal any more") if (!this.sharedId || p?.sessionId !== this.sharedId) throw new RpcError(INVALID_PARAMS, "that session is not open in this terminal any more")
} }
@@ -496,8 +499,28 @@ export class Share {
// A command's mode from the web never goes past remote.max_mode in a session shared under // A command's mode from the web never goes past remote.max_mode in a session shared under
// the device's limits (not by name), as in a session the service runs. // the device's limits (not by name), as in a session the service runs.
if (input.mode && !this.explicit) input.mode = clampMode(input.mode, limits.maxMode) if (input.mode && !this.explicit) input.mode = clampMode(input.mode, limits.maxMode)
const reason = await this.hooks.prompt({ ...input, turnId }, started) // Until it starts it may be taken back (`session/cancel` with its id): answered as
return { stopReason: STOP[reason] ?? "end_turn", _meta: { lembas: { turnId, ...(command ? { command } : {}) } } } // cancelled now, and when the terminal comes to it nothing is sent.
let withdrawn = false
let bail!: (r: PromptResult) => void
const gone = new Promise<PromptResult>((r) => (bail = r))
this.waiting.set(turnId, () => ((withdrawn = true), this.waiting.delete(turnId), bail({ stopReason: "cancelled", _meta: { lembas: { turnId } } })))
const begin = () => {
this.waiting.delete(turnId)
if (withdrawn) throw new Error("withdrawn")
started()
}
// A hook may call `begin` before it returns its promise: its throw is the promise's.
let asked: Promise<string>
try {
asked = this.hooks.prompt({ ...input, turnId }, begin)
} catch (e) {
asked = Promise.reject(e)
}
const ran = asked
.then((reason): PromptResult => ({ stopReason: STOP[reason] ?? "end_turn", _meta: { lembas: { turnId, ...(command ? { command } : {}) } } }))
ran.catch(() => {})
return Promise.race([ran, gone]).finally(() => this.waiting.delete(turnId))
}) })
}) })
// The terminal's turns: `_lembas/session/status` for a shared session asks here. // The terminal's turns: `_lembas/session/status` for a shared session asks here.
@@ -591,6 +614,15 @@ export class Share {
peer.on("hub/cancel", (p) => { peer.on("hub/cancel", (p) => {
if (this.sharedId && p?.sessionId === this.sharedId) this.app.cancel() if (this.sharedId && p?.sessionId === this.sharedId) this.app.cancel()
}) })
// The same with the turn named (acp.md `session/cancel`): that turn and no other.
peer.handle("hub/cancel", (p) => {
this.mine(p)
const running = this.app.turns.current?.turnId
const found = cancelOf({ turn: String(p?.turnId ?? ""), ...(running ? { running } : {}), queued: [...this.waiting.keys()] })
if (found.withdraws !== undefined) this.waiting.get(found.withdraws)?.()
else if (found.stops !== undefined) this.app.cancel()
return { cancelled: found.cancelled }
})
peer.handle("hub/mode", (p) => { peer.handle("hub/mode", (p) => {
this.mine(p) this.mine(p)
const mode = asMode(p?.mode) const mode = asMode(p?.mode)
+11
View File
@@ -127,6 +127,17 @@ export function reattach(o: { turn: string; machine?: boolean; status: { turnId?
return { do: "resend" } return { do: "resend" }
} }
/** Which turn a `session/cancel` touches (harness/acp.md; conformance/cancel.json). `turn`: the id
* it names (`_meta.lembas.turnId`), absent for ACP's own cancel, which means the running turn.
* A turn that is named and waits is taken out of the queue and the running one left alone; one
* that is neither running nor waiting is nobody's to stop. */
export function cancelOf(o: { turn?: string; running?: string; queued?: readonly string[] }): { cancelled: "running" | "queued" | "none"; stops?: string; withdraws?: string } {
if (o.turn === undefined) return o.running !== undefined ? { cancelled: "running", stops: o.running } : { cancelled: "none" }
if (o.running === o.turn) return { cancelled: "running", stops: o.turn }
if (o.queued?.includes(o.turn)) return { cancelled: "queued", withdraws: o.turn }
return { cancelled: "none" }
}
export class TurnLog<R = unknown> { export class TurnLog<R = unknown> {
private entries = new Map<string, Entry<R>>() private entries = new Map<string, Entry<R>>()
private values = new Map<string, R | null>() private values = new Map<string, R | null>()
+170
View File
@@ -0,0 +1,170 @@
// `session/cancel` with the turn named (harness/acp.md; spec 3.10.0, capability harness_turns): a
// prompt that waits behind a turn its client did not start is taken out of the queue — answered as
// cancelled, never run — and the turn that runs is not touched. Without the id, the running turn.
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 { Share } from "../src/acp/share.ts"
import { createApp } from "../src/app.ts"
import { paths } from "../src/config/paths.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 () => {
for (const root of roots.splice(0)) writeFileSync(join(root, "f1"), "")
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")] })
/** A reply that stays open for `ms` after its first words. */
const slow = (text: string, ms: number): Scripted => ({ chunks: [delta({ content: "… " }), delta({ content: text })], gapMs: ms })
const waitFor = (flag: string) => `until [ -e ${flag} ]; do sleep 0.05; done`
function setup(script: Scripted[]) {
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: { f/m: {} }\n`, { mode: 0o600 })
writeFileSync(join(paths.config, "config.yaml"), "model: f/m\nmode: auto\n")
const dir = realpathSync(mkdtempSync(join(tmpdir(), "ph-cancel-")))
setTrust(dir, "trusted")
roots.push(dir)
return dir
}
const limitsFor = (root: string): Limits => ({ roots: [root], maxMode: "auto", approvalTimeoutMs: 3000, requireTrust: true, enabled: true, scheduled: true })
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.on("_lembas/session/announce", () => {})
c.handle("session/request_permission", () => ({ outcome: { outcome: "selected", optionId: "once" } }))
await c.request("initialize", { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { protocol: 3 } } } })
return { c, events }
}
const until = async (ok: () => boolean | Promise<boolean>, ms = 10_000) => {
const end = Date.now() + ms
while (Date.now() < end && !(await ok())) await Bun.sleep(20)
return ok()
}
const go = (c: Peer, sid: string, text: string, meta: Record<string, unknown>) => c.request<any>("session/prompt", { sessionId: sid, prompt: [{ type: "text", text }], _meta: { lembas: meta } })
const cancel = (c: Peer, sid: string, turnId?: string) => c.request<any>("session/cancel", { sessionId: sid, ...(turnId ? { _meta: { lembas: { turnId } } } : {}) })
test("a queued prompt named by its turn is taken out of the queue; the harness turn that runs is not touched", async () => {
const root = setup([{ chunks: [toolCall(0, "j1", "bash", JSON.stringify({ command: waitFor("f1"), background: true, description: "wait for f1" })), delta({}, "tool_calls")] }, say("Started."), slow("Seen the end.", 4000)])
const { c, events } = await link(root)
const s: any = await c.request("session/new", { cwd: root, mcpServers: [] })
const sid = s.sessionId as string
const status = () => c.request<any>("_lembas/session/status", { sessionId: sid })
await go(c, sid, "go", { turnId: "web-1" })
writeFileSync(join(root, "f1"), "")
// The harness's turn runs, and its reply has begun.
expect(await until(() => events.some((e) => e.type === "prompt" && e.machine) && events.some((e) => e.type === "text" && e.text === "… "))).toBe(true)
const m = events.find((e) => e.type === "prompt" && e.machine)
let answer: any
const second = go(c, sid, "and now this", { turnId: "web-2" }).then((r) => (answer = r))
expect(await until(async () => (await status()).queued.includes("web-2"))).toBe(true)
// An id nobody has, and one that finished: nothing is done.
expect(await cancel(c, sid, "nobody")).toEqual({ cancelled: "none" })
expect(await cancel(c, sid, "web-1")).toEqual({ cancelled: "none" })
expect(await status()).toMatchObject({ busy: true, turnId: m.turnId, queued: ["web-2"] })
// The queued one: out of the queue, answered as cancelled now — while the other turn still runs.
expect(await cancel(c, sid, "web-2")).toEqual({ cancelled: "queued" })
await second
expect(answer).toEqual({ stopReason: "cancelled", _meta: { lembas: { turnId: "web-2" } } })
expect(await status()).toMatchObject({ busy: true, turnId: m.turnId, queued: [] })
expect(events.some((e) => e.type === "done" && e.reason === "cancelled")).toBe(false)
// The harness turn, named: stopped.
expect(await cancel(c, sid, m.turnId)).toEqual({ cancelled: "running" })
expect(await until(() => events.some((e) => e.type === "task" && e.state === "end" && e.turnId === m.turnId))).toBe(true)
expect(await until(async () => !(await status()).busy)).toBe(true)
// The withdrawn prompt never ran — not then, and not when its place in the queue came; sent
// again, its id is known and it is answered as cancelled.
expect(fake!.requests).toHaveLength(3)
expect(events.filter((e) => e.type === "prompt").map((e) => e.turnId)).toEqual(["web-1", m.turnId])
expect(await go(c, sid, "and now this", { turnId: "web-2" })).toEqual({ stopReason: "cancelled", _meta: { lembas: { turnId: "web-2" } } })
expect(fake!.requests).toHaveLength(3)
// Nothing runs now: ACP's own cancel finds nothing either.
expect(await cancel(c, sid)).toEqual({ cancelled: "none" })
}, SLOW)
test("a queued scheduled run taken back answers as a cancelled run", async () => {
const root = setup([slow("First.", 3000)])
const { c, events } = await link(root)
const meta = { scheduled: { schedule_id: "sched1", run_id: "run8", title: "Check", mode: "auto" } }
const s: any = await c.request("session/new", { cwd: root, mcpServers: [], _meta: { lembas: meta } })
const sid = s.sessionId as string
// The person writes into the run's chat; the next run arrives meanwhile and waits.
const first = go(c, sid, "hello", { turnId: "web-1" })
expect(await until(() => events.some((e) => e.type === "text" && e.text === "… "))).toBe(true)
const run = go(c, sid, "check", { turnId: "run8", ...meta })
expect(await until(async () => (await c.request<any>("_lembas/session/status", { sessionId: sid })).queued.includes("run8"))).toBe(true)
expect(await cancel(c, sid, "run8")).toEqual({ cancelled: "queued" })
expect(await run).toEqual({ stopReason: "cancelled", _meta: { lembas: { turnId: "run8", scheduled: { run_id: "run8", status: "cancelled", text: "", error: null } } } })
expect((await first).stopReason).toBe("end_turn")
expect(fake!.requests).toHaveLength(1)
}, SLOW)
test("in a session a terminal runs: a web prompt that has not started there is taken back, and nothing is sent when its turn comes", async () => {
const root = setup([say("typed here")])
const hub = new Hub({ service: true, limits: { ...limitsFor(root), enabled: true } })
expect(await hub.listen()).toBe(true)
stops.push(() => hub.close())
const { c } = await link(root, hub)
// The terminal is busy with something of its own until the test lets it go on.
let free!: () => void
const busy = new Promise<void>((r) => (free = r))
let begun = 0
const app = createApp({ cwd: root, modelTitles: false, asker: { ask: async () => ({ kind: "once" as const }) } })
const share = new Share(app, {
prompt: async (r, started) => {
await busy
started()
begun++
return app.turns.prompt(r.prompt, r.extra, r.shown, { turnId: r.turnId, attachments: r.attachments })
},
compact: () => app.engine.compact(),
deleted: () => app.newSession(),
notice: () => {},
changed: () => {},
})
stops.push(() => share.close())
await share.start()
const sid = app.engine.sessionId!
expect(await until(() => hub.shared.has(sid))).toBe(true)
const sent = go(c, sid, "from the web", { turnId: "web-1" })
expect(await until(async () => (await c.request<any>("_lembas/session/status", { sessionId: sid })).queued.includes("web-1"))).toBe(true)
expect(await cancel(c, sid, "nobody")).toEqual({ cancelled: "none" })
expect(await cancel(c, sid, "web-1")).toEqual({ cancelled: "queued" })
expect(await sent).toEqual({ stopReason: "cancelled", _meta: { lembas: { turnId: "web-1" } } })
// The terminal comes to it: it is gone.
free()
await busy
await Bun.sleep(0)
expect(begun).toBe(0)
expect(fake!.requests).toHaveLength(0)
expect(app.turns.current).toBeUndefined()
}, SLOW)
+3 -1
View File
@@ -39,7 +39,7 @@ import { fillPrompt as fillText } from "../src/prompt/fill.ts"
import { isSilent, judgeCase, monitorHash, notifyInstruction, reportResult, reportTool, runLeaves, scheduledMode, stripSentinel } from "../src/acp/scheduled.ts" import { isSilent, judgeCase, monitorHash, notifyInstruction, reportResult, reportTool, runLeaves, scheduledMode, stripSentinel } from "../src/acp/scheduled.ts"
import { clientModel, records, startModel, type SessionKind } from "../src/session/lastmodel.ts" import { clientModel, records, startModel, type SessionKind } from "../src/session/lastmodel.ts"
import { reattach } from "../src/acp/turns.ts" import { cancelOf, reattach } from "../src/acp/turns.ts"
import { outstanding, type OutstandingInput } from "../src/session/outstanding.ts" import { outstanding, type OutstandingInput } from "../src/session/outstanding.ts"
import { background, scheduledRefusal, twin, type BackgroundCall, type Listed } from "../src/provider/interactive.ts" import { background, scheduledRefusal, twin, type BackgroundCall, type Listed } from "../src/provider/interactive.ts"
@@ -58,6 +58,8 @@ function readableUnder(grants: Record<string, string> | undefined, path: string)
} }
export const AREAS: Record<string, (c: Case) => unknown> = { export const AREAS: Record<string, (c: Case) => unknown> = {
// Spec 3.10.0: which turn a `session/cancel` touches (src/acp/turns.ts).
cancel: (c) => cancelOf({ turn: c.turn as string | undefined, running: c.running as string | undefined, queued: c.queued as string[] | undefined }),
// Spec 3.10.0: what a session still has out when no turn of it runs (src/session/outstanding.ts). // Spec 3.10.0: what a session still has out when no turn of it runs (src/session/outstanding.ts).
outstanding: (c) => outstanding(c as unknown as OutstandingInput), outstanding: (c) => outstanding(c as unknown as OutstandingInput),
// Spec 3.10.0: a row reattached after a restart or a dropped link — the client's rule (src/acp/turns.ts). // Spec 3.10.0: a row reattached after a restart or a dropped link — the client's rule (src/acp/turns.ts).