From 7ec0cdf877de2c8f379053f2c32d77846331c90c Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Sat, 28 Nov 2026 04:33:03 +0200 Subject: [PATCH 1/3] Studio: an OpenCode wake-up names the subagents whose results it took, and a failed one ends failed (#779) The plugin reads OpenCode's inbox: a subagent's result (`session.inbox.enqueued`, `metadata.source` "subagent") delivered into a turn (`session.inbox.delivered`). It holds a wake-up until its turn's first step and sends it with the results the turn took (`reported`); a result delivered later goes on a line of its own. Shell and other jobs' results are not sent. The core reads `reported` as `TasksReported`: each child ends with its result's status (`error` failed, `cancelled` interrupted), over its status-less run end, and a wake-up names every child it took, "workers A and B returned", or "background job returned" for none. A result in a turn Daniel prompted leaves his prompt. A log from before has no `reported` and replays as before. Research: docs/studio/research/opencode-background-results.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CVqACdVnKiSXskgVojtEiA --- core/src/opencode.rs | 47 ++++++- core/src/saved.rs | 2 +- core/src/session.rs | 30 +++++ core/src/studio/take.rs | 30 +++++ core/tests/opencode.rs | 126 ++++++++++++++++++ core/tests/wake_ups.rs | 23 ++-- docs/studio/plugin.md | 4 +- .../research/opencode-background-results.md | 79 +++++++++++ plugin-opencode/plotkeeper.js | 60 +++++++-- ui/tests/opencode-plugin.test.mjs | 121 +++++++++++++++++ 10 files changed, 496 insertions(+), 26 deletions(-) create mode 100644 docs/studio/research/opencode-background-results.md create mode 100644 ui/tests/opencode-plugin.test.mjs diff --git a/core/src/opencode.rs b/core/src/opencode.rs index f45010e1..ee712a66 100644 --- a/core/src/opencode.rs +++ b/core/src/opencode.rs @@ -9,8 +9,10 @@ //! `tool.execute.after`, with the tool's name, call id and input, and at the end its `status`, //! error and a shell's `exit`), and from its event stream `permission.asked` and a turn's end //! (`session.execution.succeeded`, `.failed` or `.interrupted`; `.started` only for a turn that -//! starts with no prompt, as when a background subagent's result wakes its parent), which carries -//! the model the turn's steps named and the turn's last text. OpenCode reports no session start or end. A subagent is a +//! starts with no prompt, as when a background subagent's result wakes its parent, with the subagent +//! results its turn took, `reported`), which carries the model the turn's steps named and the turn's +//! last text; a subagent's result delivered into a running turn comes as `session.inbox.delivered` +//! (#779). OpenCode reports no session start or end. A subagent is a //! child session that always runs in the background (#718): its `subagent` call's end names it //! (`spawned_session_id`), and the plugin puts its calls, asks and the end of each of its runs //! under the session that spawned it, with its own id (`subagent_session_id`). The tool names @@ -81,6 +83,10 @@ struct Raw { subagent_session_id: Option, /// The child session a `subagent` call started, on its end. spawned_session_id: Option, + /// The subagent results a turn took (#779): on a wake-up, those it took before its first step, + /// empty when none was a subagent's, as a shell job's; on `session.inbox.delivered`, one that + /// joined a running turn. A log from the plugin before #779 has none. + reported: Option>, /// When the plugin sent the line (#717); a log from the plugin before it has none. sent_ms: Option, #[serde(default)] @@ -97,9 +103,44 @@ struct Raw { studio_touched_roots: Option>, } +/// A subagent's result, from OpenCode's `session.inbox.enqueued` item (`metadata.childID` and +/// `metadata.state`). +#[derive(Deserialize)] +struct Reported { + subagent_session_id: String, + /// `completed`, `error` or `cancelled` + /// (`docs/studio/research/opencode-background-results.md`, section 1). + state: String, +} + +impl Reported { + /// The child and the status it ends with, in the studio's words: an `error` failed, and + /// `cancelled` is `interrupted`, as a Claude subagent's are. + fn task(&self) -> (String, String) { + let status = match self.state.as_str() { + "error" => "failed", + "cancelled" => "interrupted", + other => other, + }; + (self.subagent_session_id.clone(), status.into()) + } +} + +/// The tasks a line reports on, each with how it ended. +fn reported(reported: Option<&[Reported]>) -> Option { + let tasks = reported?.iter().map(Reported::task); + Some(Happened::TasksReported(tasks.collect())) +} + /// The event of OpenCode plugin line `line`; an error when it has no such line's shape. pub(crate) fn parse(line: &str) -> Result { - serde_json::from_str::(line).map(adapt) + let raw = serde_json::from_str::(line)?; + let tasks = reported(raw.reported.as_deref()); + let mut event = adapt(raw); + // The subagent results a wake-up took, or one a running turn took on a line of its own, + // `session.inbox.delivered` (#779). + event.happened.extend(tasks); + Ok(event) } /// What a call of tool `name` is. diff --git a/core/src/saved.rs b/core/src/saved.rs index b64abeae..6fc360af 100644 --- a/core/src/saved.rs +++ b/core/src/saved.rs @@ -10,7 +10,7 @@ use std::{cell::Cell, collections::BTreeMap, fmt}; /// The saved state's format. Bump it when a saved field changes meaning or a field the pane's JSON /// leaves out is added, so an older file is not read as the new shape: a field the old file lacks /// makes it unreadable anyway, unless it has a default. -const FORMAT: u32 = 9; +const FORMAT: u32 = 10; thread_local! { static SAVING: Cell = const { Cell::new(false) }; diff --git a/core/src/session.rs b/core/src/session.rs index b28aff2f..db7d8ecd 100644 --- a/core/src/session.rs +++ b/core/src/session.rs @@ -290,6 +290,10 @@ pub struct Turn { /// by", never as Daniel's. A turn stored before it reads as his. #[serde(default)] pub wake_up: bool, + /// The tasks a wake-up's turn took the results of, in order, for an agent that says which + /// (OpenCode, #779); empty for any other turn. + #[serde(skip_serializing_if = "crate::saved::unsaved", default)] + pub(crate) woken_by: Vec, /// The id its `Stop` gives a card or a summary on it (`Stopped::card`); `None` until it stopped. pub id: Option, /// The first line of its final reply, from its `Stop`. @@ -1078,6 +1082,32 @@ impl Session { last.map(|a| a.agent.id.clone()).unwrap_or_default() } + /// Names the latest turn, a wake-up's, after `tasks` too, whose results it took (#779): "worker + /// A returned", "workers A and B returned", or "background job returned" when it took none of a + /// subagent's. A turn Daniel prompted keeps its prompt. + pub(crate) fn wake_up_took(&mut self, tasks: &[String]) { + let Some(turn) = self.turns.last_mut().filter(|t| t.wake_up) else { + return; + }; + for task in tasks { + if !turn.woken_by.contains(task) { + turn.woken_by.push(task.clone()); + } + } + let woken_by = turn.woken_by.clone(); + let names: Vec<&str> = woken_by.iter().map(|id| self.agent_name(id)).collect(); + let label = match names.as_slice() { + [] => "background job returned".into(), + [name] => format!("worker {name} returned"), + [first @ .., last] => format!("workers {} and {last} returned", first.join(", ")), + }; + let turn = self.turns.last_mut().expect("found above"); + turn.prompt.clone_from(&label); + if self.returned.is_some() { + self.returned = Some(label); + } + } + /// Who sent `prompt`. A wake-up names a known task id of the session in markup the studio /// knows: `` or `…`. A known id in other markup is /// drift, and one in plain text is Daniel's. diff --git a/core/src/studio/take.rs b/core/src/studio/take.rs index 09d54145..a44b4eaa 100644 --- a/core/src/studio/take.rs +++ b/core/src/studio/take.rs @@ -517,6 +517,15 @@ impl Take<'_> { self.blocked_answered(tool, id, answer); } Happened::TurnStart { prompt, origin } => self.turn_start(prompt, origin.as_ref()), + // A result that joins a running turn names its task on a wake-up's (#779); one the hook + // took late, or that lands after its turn's end, is of a turn already past. + Happened::TasksReported(_) + if self.session.in_turn() + && !event.has(|h| matches!(h, Happened::TurnStart { .. } | Happened::Late)) => + { + let tasks = self.reported_tasks(); + self.session.wake_up_took(&tasks); + } // A reply in an event of its own waits for its turn's end (#362). Only the main agent's: a // subagent's reply (Claude Code's `SubagentStop`) is never its parent turn's. Happened::Reply(reply) @@ -666,10 +675,18 @@ impl Take<'_> { /// A prompt opens a wait, also after an interrupt, which fires no `Stop`. fn turn_start(&mut self, prompt: &str, origin: Option<&Origin>) { + let reported = self.reported_tasks(); + // An adapter's wake-up that says which tasks it took names them all, the first as its sender + // (#779). + let told = origin == Some(&Origin::WakeUp) + && self.event.has(|h| matches!(h, Happened::TasksReported(_))); let session = &mut *self.session; session.reply.clear(); let sender = match origin { Some(Origin::Daniel) => Sender::Daniel, + Some(Origin::WakeUp) if told => { + Sender::WakeUp(reported.first().cloned().unwrap_or_default()) + } Some(Origin::WakeUp) => Sender::WakeUp(session.woken_by()), None => session.sender(prompt), }; @@ -712,9 +729,22 @@ impl Take<'_> { session.unblock(); } session.reopen_turn(); + // Claude Code's wake-ups keep the name its markup gives. + if told { + session.wake_up_took(&reported); + } } } + /// The ids of the tasks the event reports on. + fn reported_tasks(&self) -> Vec { + self.event + .reported() + .iter() + .map(|(id, _)| id.clone()) + .collect() + } + /// A background retry ends at the notification that names its task, one of perhaps several in /// the wake-up. fn background_retries_reported(&mut self, prompt: &str) { diff --git a/core/tests/opencode.rs b/core/tests/opencode.rs index 551111ec..ad369677 100644 --- a/core/tests/opencode.rs +++ b/core/tests/opencode.rs @@ -324,3 +324,129 @@ fn opencode_lines_the_hook_took_late_end_no_turn_and_their_calls_are_the_turn_be [("call_0".into(), "write".into(), Some(0))] ); } + +/// A line of `HELLO`'s, sent and received at `at`. +fn hello(name: &str, at: u64, fields: Value) -> String { + let mut line = json!({ + "session_id": HELLO, "cwd": "/Users/me/work/hello", "hook_event_name": name, "sent_ms": at, + "studio_agent": "opencode", "studio_received_ms": at, + }); + line.as_object_mut() + .unwrap() + .extend(fields.as_object().unwrap().clone()); + line.to_string() +} + +/// The `reported` of a line of the plugin since #779: each child with OpenCode's `state`. +fn reported(pairs: &[(&str, &str)]) -> Value { + let each = pairs + .iter() + .map(|(child, state)| json!({ "subagent_session_id": child, "state": state })); + json!({ "reported": Value::Array(each.collect()) }) +} + +/// The end of `HELLO`'s turn, or of subagent `child`'s run, at `at`. +fn run_end(at: u64, child: Option<&str>) -> String { + let mut fields = json!({ "last_assistant_message": "Done." }); + if let Some(child) = child { + fields["subagent_session_id"] = child.into(); + } + hello("session.execution.succeeded", at, fields) +} + +/// A turn of `HELLO`'s that spawns two background subagents, A (`ses_aaaaa`) and B (`ses_bbbbb`), +/// each of which then reads a file, A last. +fn two_children() -> Vec { + let spawn = |at: u64, call: &str, child: &str, description: &str| { + let input = json!({ "description": description, "prompt": "Go.", "agent": "general" }); + let call = json!({ "tool_name": "subagent", "tool_use_id": call, "tool_input": input }); + let mut ended = call.clone(); + ended["status"] = "completed".into(); + ended["spawned_session_id"] = child.into(); + [ + hello("tool.execute.before", at, call), + hello("tool.execute.after", at + 5, ended), + ] + }; + let read = |at: u64, child: &str| { + let fields = json!({ "tool_name": "read", "tool_use_id": format!("read-{child}"), "tool_input": { "path": "f" }, "subagent_session_id": child }); + hello("tool.execute.before", at, fields) + }; + let prompt = json!({ "prompt_id": "msg_0", "prompt": "Spawn two." }); + let mut lines = vec![hello("session.prompt", 100, prompt)]; + lines.extend(spawn(110, "call_a", "ses_aaaaa", "A")); + lines.extend(spawn(130, "call_b", "ses_bbbbb", "B")); + lines.extend([ + run_end(150, None), + read(200, "ses_bbbbb"), + read(300, "ses_aaaaa"), + ]); + lines +} + +/// What a wake-up's turn took (#779): the plugin sends with a wake-up the subagent results its turn +/// took before its first step (`reported`, each child with OpenCode's `state`), and a result +/// delivered into a running turn on a line of its own (`session.inbox.delivered`). Two children, +/// A and B, run in the background; A has the latest event, and both children's end lines land +/// after the wake-up. A turn names, in delivery order, every child whose result it took, and each +/// such child ends with its result's status, whatever its status-less end says. +#[test] +fn a_wake_up_names_the_subagents_whose_results_its_turn_took_and_each_ends_with_its_status() { + let (a, b) = ("ses_aaaaa", "ses_bbbbb"); + let wake = |pairs: Option<&[(&str, &str)]>| { + let fields = pairs.map_or(json!({}), reported); + hello("session.execution.started", 900, fields) + }; + let prompt = hello( + "session.prompt", + 900, + json!({ "prompt_id": "msg_1", "prompt": "And now?" }), + ); + let delivered = |pairs: &[(&str, &str)]| hello("session.inbox.delivered", 950, reported(pairs)); + let completed = Status::Completed; + let failed = Status::Ended("failed".into()); + let interrupted = Status::Ended("interrupted".into()); + // Each case: the lines after the two children's, its turn's label and whether it is a + // wake-up's, and how A and B end. + #[rustfmt::skip] + let cases = [ + ("B's result alone names B, though A has the latest event", + vec![wake(Some(&[(b, "completed")]))], "worker B returned", true, [completed.clone(), completed.clone()]), + ("two results name both, each child ending with its own status", + vec![wake(Some(&[(a, "error"), (b, "cancelled")]))], "workers A and B returned", true, [failed.clone(), interrupted.clone()]), + ("a result that joins the running wake-up names its child after the first", + vec![wake(Some(&[(b, "completed")])), delivered(&[(a, "error")])], "workers B and A returned", true, [failed.clone(), completed.clone()]), + ("a wake-up whose turn took no subagent's result, as a shell job's, names none", + vec![wake(Some(&[]))], "background job returned", true, [completed.clone(), completed.clone()]), + ("a log from before #779 names the child with the latest event, and its children end completed", + vec![wake(None)], "worker A returned", true, [completed.clone(), completed.clone()]), + ("a result delivered into a turn Daniel prompted ends its child and leaves his prompt", + vec![prompt, delivered(&[(a, "cancelled")])], "And now?", false, [interrupted.clone(), completed.clone()]), + ("a result after its child's end, OpenCode's own order, still ends it with its status", + vec![run_end(800, Some(b)), wake(Some(&[(b, "error")]))], "worker B returned", true, [completed.clone(), failed.clone()]), + ]; + for (case, after, label, wake_up, statuses) in cases { + let mut lines = two_children(); + lines.extend(after); + lines.extend([ + run_end(1000, Some(b)), + run_end(1010, Some(a)), + run_end(1100, None), + ]); + let studio = Studio::replayed(&lines); + let session = studio.session(HELLO).unwrap(); + + let turn = &session.turns[1]; + assert_eq!( + (turn.prompt.as_str(), turn.wake_up), + (label, wake_up), + "{case}" + ); + let status = |id: &str| { + let agent = session.agents.iter().find(|s| s.agent.id == id).unwrap(); + agent.status.clone() + }; + assert_eq!([status(a), status(b)], statuses, "{case}"); + assert_eq!(session.turns.len(), 2, "{case}"); + } +} diff --git a/core/tests/wake_ups.rs b/core/tests/wake_ups.rs index 278cdba6..bc6ab3fe 100644 --- a/core/tests/wake_ups.rs +++ b/core/tests/wake_ups.rs @@ -50,16 +50,21 @@ fn prompt(prompt: &str) -> String { #[test] fn a_wake_up_from_a_task_with_no_subagent_names_it_by_its_short_id() { - let mut studio = replay(DAY); + // `brh86k1fz` is the day's background command, which no subagent record names. A Claude Code + // wake-up that reports two tasks still names the first its markup knows, as OpenCode's names + // all it took (#779) only from its own lines. + let notification = common::task_notification("brh86k1fz", "completed"); + let two = notification.clone() + &common::task_notification("zzzzzzzzz", "completed"); + for (case, text) in [("one task", notification), ("two tasks", two)] { + let mut studio = replay(DAY); + studio.apply(&prompt(&text)); - // `brh86k1fz` is the day's background command, which no subagent record names. - studio.apply(&prompt(&common::task_notification( - "brh86k1fz", - "completed", - ))); - - let session = studio.session(IMPLEMENT_SPEC).unwrap(); - assert_eq!(session.returned.as_deref(), Some("worker brh86 returned")); + let session = studio.session(IMPLEMENT_SPEC).unwrap(); + let returned = Some("worker brh86 returned"); + assert_eq!(session.returned.as_deref(), returned, "{case}"); + let turn = session.turns.last().unwrap(); + assert_eq!(Some(turn.prompt.as_str()), returned, "{case}"); + } } /// The senders of the prompts after the day's 18. diff --git a/docs/studio/plugin.md b/docs/studio/plugin.md index fc3adc29..437830aa 100644 --- a/docs/studio/plugin.md +++ b/docs/studio/plugin.md @@ -46,13 +46,13 @@ Qwen Code's payloads are near Claude Code's, read by `core/src/qwen.rs` from lin ## What OpenCode's plugin records -OpenCode 2 runs its plugins in one background service (`opencode serve --service`) that every OpenCode window and `opencode run` talks to, and loads a plugin once for each folder a session runs in. The plugin's hooks see only that folder's sessions, but its event stream is the whole service's, so it records the stream's events only for the sessions its own hooks saw, and each event is recorded once. `core/src/opencode.rs` reads its lines: each prompt (the `session` `prompt` hook) starts a turn, tool calls come from the `tool` hooks (`shell` as commands, `write`, `edit` and `patch` as edits, with paths made absolute from the session's folder, and a call that errs or a shell that exits non-zero as failed, with its exit code), `permission.asked` waits on you until its call ends (the plugin sends an ask with its call's tool and input, holding one that comes before its call starts, as OpenCode asks a `write` call's permission as an `edit`), and a turn ends with `session.execution.succeeded`, `.failed` or `.interrupted`, carrying the turn's last text as its reply and the model its steps named. A subagent is a child session of its own, which OpenCode always runs in the background (#718): it shows as a subagent of the session that spawned it, named by its `subagent` call's description, with its type (such as `general`), its calls and asks, and its reply. Its spawn's end names the child (`spawned_session_id`, from the call's `metadata.sessionID`), each of its lines names it (`subagent_session_id`), and each of its runs ends with its last text as its reply, a `.failed` or `.interrupted` run ending it as completed too; its prompt is its spawn's and is not recorded. A background subagent's result starts a turn of its parent's with no prompt, which shows as a wake-up, `worker returned`, naming the subagent with the latest event. The plugin sends a child's end before the wake-up it causes, but each line is appended by a hook process of its own, so with two subagents running a wake-up that lands before its child's end can name the other one. A log from the plugin before #718 has no `spawned_session_id` and no child's end, so its children show unattached, named by the first characters of their id, and stay running; an ask of a child's call in such a log, which names no subagent, waits until its turn ends. +OpenCode 2 runs its plugins in one background service (`opencode serve --service`) that every OpenCode window and `opencode run` talks to, and loads a plugin once for each folder a session runs in. The plugin's hooks see only that folder's sessions, but its event stream is the whole service's, so it records the stream's events only for the sessions its own hooks saw, and each event is recorded once. `core/src/opencode.rs` reads its lines: each prompt (the `session` `prompt` hook) starts a turn, tool calls come from the `tool` hooks (`shell` as commands, `write`, `edit` and `patch` as edits, with paths made absolute from the session's folder, and a call that errs or a shell that exits non-zero as failed, with its exit code), `permission.asked` waits on you until its call ends (the plugin sends an ask with its call's tool and input, holding one that comes before its call starts, as OpenCode asks a `write` call's permission as an `edit`), and a turn ends with `session.execution.succeeded`, `.failed` or `.interrupted`, carrying the turn's last text as its reply and the model its steps named. A subagent is a child session of its own, which OpenCode always runs in the background (#718): it shows as a subagent of the session that spawned it, named by its `subagent` call's description, with its type (such as `general`), its calls and asks, and its reply. Its spawn's end names the child (`spawned_session_id`, from the call's `metadata.sessionID`), each of its lines names it (`subagent_session_id`), and each of its runs ends with its last text as its reply; its prompt is its spawn's and is not recorded. When a child's run ends, OpenCode puts its result in its parent's inbox (`session.inbox.enqueued`, an item whose `metadata` names the child and its `state`, `completed`, `error` or `cancelled`) and delivers it into the turn that takes it (`session.inbox.delivered`): a turn it starts with no prompt, a wake-up, or one already running, and one turn can take several (#779; [OpenCode's background results](research/opencode-background-results.md)). The plugin holds a wake-up until its turn's first step, or its turn's next line, and sends it with the subagent results the turn took by then (`reported`, each a `subagent_session_id` and its `state`); a result delivered later in a turn goes on a line of its own, `session.inbox.delivered`, with the same `reported`. A shell, image, video or Code Mode job's result is not sent. A wake-up shows as `worker returned`, or `workers A and B returned` for several, naming in delivery order each subagent whose result its turn took, one that joined it later included; a wake-up that took none, as a shell job's, shows as `background job returned`. A result delivered into a turn Daniel prompted leaves his prompt as it is, and one whose line lands after its turn ended names no one. Each result ends its child with its status, in the studio's words: `completed`, `failed` for `error` and `interrupted` for `cancelled`, as a Claude subagent's are; it overrides the end of the child's run, which carries no status and ends it as completed, whichever line lands first. A child that reports again after later work keeps its first end. A log from the plugin before #779 has no `reported`: its wake-up names the subagent with the latest event, so with two subagents running a wake-up that lands before its child's end can name the other one, and its children end completed. A log from the plugin before #718 has no `spawned_session_id` and no child's end, so its children show unattached, named by the first characters of their id, and stay running; an ask of a child's call in such a log, which names no subagent, waits until its turn ends. OpenCode reports no session start or end, and its plugin runs in the shared service, not in the session's terminal. So an OpenCode line records no pid (`studio_pid`): the process check cannot end an OpenCode session, which takes the idle path, as Codex's do (#369). Its transcript is not read, so a session shows no context size. An OpenCode turn lists the files it changed (#717). The hook records each turn's trees as it does Codex's and Cursor's: it maps a prompt or a wake-up to a turn's start, a call's start and end to its steps (a `write`, `edit` or `patch` editing its `path`, relative to the session's folder, and a `shell` running its command), and a run's end to the turn's end, or with `subagent_session_id` to that subagent's, whose touches are a worker's. The plugin spawns one hook an event and never waits for it, so a session's lines reach the hook in any order: each line carries when the plugin sent it (`sent_ms`; a log from the plugin before #717 has none, and the hook takes when it got the line), and the hook leaves out of the turns a line sent before the turn it is in began, or a start sent before the last end it took. A turn whose end reached the hook before its start then records no trees, and lists no files, rather than another turn's. The hook keeps the session's record locked until the line is in the log, so the log holds a session's lines in the order the hook took them, and marks a line it left out of the turns as late (`studio_late`, #744). The core reads a late line as one of a turn already past: its end ends no turn and its reply is dropped, as the next start already ended its turn, its start has no prompt id, so it neither ends the running turn nor starts one of its own while that turn runs, and a call it starts or ends is the previous turn's. A wake-up's prompt id is when it was sent, as in the hook, so a wake-up that lands before the last turn's end still ends that turn and starts its own. As with Codex's async hooks, a call's start may record the start tree of a worktree other than the session folder's after the call changed it. -The adapter's fixtures are real runs of OpenCode 2.4.1 (`core/tests/fixtures/opencode/run.jsonl` and `asks.jsonl`, from the plugin before #718, and `subagent.jsonl`, a background subagent); #372's trial by hand (OpenCode 2.4.2) recorded each event once under `opencode`, with a written summary, and a run with two subagents at once, whose two wake-ups each named the subagent that had just ended, as each child's end reached the log before its wake-up on that run; the race above stays open (#779). +The adapter's fixtures are real runs of OpenCode 2.4.1 (`core/tests/fixtures/opencode/run.jsonl` and `asks.jsonl`, from the plugin before #718, and `subagent.jsonl`, a background subagent); #372's trial by hand (OpenCode 2.4.2) recorded each event once under `opencode`, with a written summary, and a run with two subagents at once, whose two wake-ups each named the subagent that had just ended, as each child's end reached the log before its wake-up on that run, from the plugin before #779. No real run has shown a result in state `error` or `cancelled` yet: those come from OpenCode's code and tests. ## What Cline's plugin records diff --git a/docs/studio/research/opencode-background-results.md b/docs/studio/research/opencode-background-results.md new file mode 100644 index 00000000..474060da --- /dev/null +++ b/docs/studio/research/opencode-background-results.md @@ -0,0 +1,79 @@ +# OpenCode's background-subagent results: states, delivery and ordering + +Research for #779 (an OpenCode wake-up names its own subagent, and a failed subagent ends failed), 28 November 2026. Questions: which `state` values a `` inbox item can carry, how `delivery: "steer"` reaches a busy or idle parent, and whether one wake-up can take several results. + +Every claim is marked **verified** (read in the code, with its link) or **inferred** (put together from code that was read, but not seen in a test or a run), with a confidence. + +## How this was read + +- **Source.** `anomalyco/opencode` at tag `v2.4.2` (commit `fc31a48`, 25 Nov 2026), cloned shallow into a scratch folder and read with grep and sed; nothing was installed, built or run. Links below point at that commit. +- **v2.4.1** (tag `v2.4.1`, commit `6f05140`) was compared file by file. `execution.ts`, `execution/subagent-report.ts`, `run-coordinator.ts`, `bus.ts`, `session-event.ts`, `session-interrupt.ts`, `subagent-job.ts` and `session.ts` are identical. `subagent-completion.ts`, `inbox.ts`, `job.ts`, `runner/llm.ts` and `schema/session-inbox.ts` differ only by refactors: a helper pulled out, the inbox lock moved into the service, an import renamed, a doc string added. Nothing in this note differs between the two versions. Verified. +- **The captures.** `local-evidence/2026-11-27-issue-370-opencode-runs/oc-a/capture.jsonl` line 145, the shape quoted in #779. Every capture we have shows only `state="completed"`. + +## 1. The `state` values + +The subagent's report is built in [`SubagentCompletion.deliver`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/subagent-completion.ts#L66-L95). Its status is a job status, one of `"running"`, `"completed"`, `"error"`, `"cancelled"` ([`job.ts:41`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/job.ts#L41)); a `"running"` status sends nothing ([`subagent-completion.ts:73`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/subagent-completion.ts#L73)). Verified. + +The child's execution outcome maps to a status in [`resolveBody`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution/subagent-report.ts#L56-L73). Verified, high confidence: + +- **Fails** (`session.execution.failed`): `"error"`, and the body is the error message ([`subagent-report.ts:62`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution/subagent-report.ts#L62)). A test expects `state="error"` with the transport error's text ([`subagent-report.test.ts:378-380`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/test/subagent-report.test.ts#L378-L380)). +- **Interrupted** (`session.execution.interrupted`, reason `user`): `"cancelled"`, body `Subagent cancelled` ([`subagent-report.ts:63`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution/subagent-report.ts#L63)). Tests expect `state="cancelled"` when the child is interrupted ([`subagent-report.test.ts:384-391`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/test/subagent-report.test.ts#L384-L391)), when its job is cancelled before it starts ([`subagent-report.test.ts:396-436`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/test/subagent-report.test.ts#L396-L436)), and when the child session is deleted mid-run ([`subagent-idle-e2e.test.ts:789-821`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/test/subagent-idle-e2e.test.ts#L789-L821)). There is no separate "aborted" or "interrupted" string. +- **Interrupted by a server shutdown**: no report at all. The shutdown branch publishes `session.execution.interrupted` with reason `shutdown`, keeps the job running for the next server start, and returns before any report is prepared ([`execution.ts:161-166`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution.ts#L161-L166)). Verified, high. +- **Succeeds**: `"completed"`, with the child's last assistant text as the body, or `Subagent completed without a text response.` ([`subagent-report.ts:65-71`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution/subagent-report.ts#L65-L71)). A corrupt message row also turns into `"error"` (line 66). Verified. +- **Resume given up after a restart**: when a child was interrupted repeatedly and won't be resumed, the restart sweep reports `"error"` with `Execution was interrupted repeatedly and will not be resumed automatically.` ([`restart.ts:33-36`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution/restart.ts#L33-L36), [`restart.ts:408-415`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution/restart.ts#L408-L415)). Verified. +- **No timeout state.** The status set has no "timed out" value (`job.ts:41`), and the subagent tool, report and completion code contain no timeout (grep for `timeout`/`timed` in those three files). Verified, high. + +**`state=` and `metadata.state` can differ.** The attribute in the text is `"running"` when the child completed but still has background work running (its own shells or subagents). `metadata.state` always keeps the job status, `"completed"` in that case ([`subagent-completion.ts:82-92`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/subagent-completion.ts#L82-L92)). A test expects `state="running"` in the text for such a child ([`subagent-report.test.ts:200`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/test/subagent-report.test.ts#L200)). So `metadata.state` is one of `completed`, `error`, `cancelled`; the attribute is one of those or `running`. Verified, high. + +**One child can report many times.** The tool tells the model that it gets a `` "each time the child goes idle, including after later work" ([`subagent.ts:53`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/tool/plugin/subagent.ts#L53)). A busy period without a background job still reports to the parent, under a fresh id ([`subagent-report.ts:169-180`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution/subagent-report.ts#L169-L180)). Verified. So a `completed` item doesn't mean the child is finished for good, and a later item for the same child can follow. + +**When the parent cancels a child.** There are three paths: + +- **The `interrupt` tool.** It exists only with the `full_codemode` flag. It cancels the child's jobs, then interrupts the child and its descendants ([`session-interrupt.ts:28-35`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/tool/plugin/session-interrupt.ts#L28-L35)). Its comment says "Cancelled jobs send no completion notice" (line 26). But reading the report code, the child's interruption still reports: `cancelSession` drops the job entry ([`job.ts:597-615`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/job.ts#L597-L615)), so `prepareSubagentReport` returns mode `none`. A child that has a parent is reported anyway ([`subagent-report.ts:140-145`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution/subagent-report.ts#L140-L145)), and `resolveBody` gives `"cancelled"` for any interruption, in either mode (line 63). Inferred, medium confidence: no test of the tool was found (`grep -rl session-interrupt packages/core/test` is empty). +- **The child's session is deleted.** It reports `"cancelled"`, per the e2e test above. Verified. +- **The user interrupts the parent.** This doesn't cancel its children. The parent's settlement cancels only the job whose id is the parent itself, its own job as a child ([`execution.ts:169`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution.ts#L169)). `Session.interrupt` interrupts only that session ([`session/session.ts:290-292`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/session.ts#L290-L292)). So the children run on and report later. Inferred, medium. + +**Not only subagents wake the parent.** Shell, image, video and Code Mode jobs send their own `` items. A shell item has `metadata.source: "shell"` ([`shell/result.ts:86-90`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/shell/result.ts#L86-L90)). They go through the same synthetic steer-and-wake path ([`synthetic.ts:30-47`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/synthetic.ts#L30-L47)), so a wake-up can come from a non-subagent job. Filter on `metadata.source === "subagent"`. Verified. + +## 2. `delivery: "steer"` and when a wake-up follows + +**Delivery values.** Only `"steer"` and `"queue"` exist. The schema's own description: "steer delivers before the agent's next model call, even mid-work. queue waits until the agent finishes its current work, then delivers one queued item at a time. Sending defaults to steer." ([`schema/session-inbox.ts:11-15`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/schema/src/session-inbox.ts#L11-L15)). Subagent reports are always admitted as `steer` ([`subagent-report.ts:94`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution/subagent-report.ts#L94)). A pending item can be switched between the two (`session.inbox.delivery.changed`, [`inbox.ts:269-289`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/inbox.ts#L269-L289)). Verified, high. + +**After admission the parent is always woken**, unless it is in a revert ([`subagent-report.ts:126-128`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution/subagent-report.ts#L126-L128)). It is also not woken when the admission conflicted on its id (line 104-111) or the parent was deleted (lines 77-80, 114-124). Verified. + +**Busy parent: no new execution.** `wake` on a session with an active execution only rings its doorbell (`pendingWake`); it does not start one ([`run-coordinator.ts:135-144`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/run-coordinator.ts#L135-L144)). The `started` hook, which publishes `session.execution.started`, runs once per busy period ([`run-coordinator.ts:96-99`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/run-coordinator.ts#L96-L99), [`execution.ts:139-152`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution.ts#L139-L152)). Inside the running drain, every step boundary promotes pending steers ([`llm.ts:197-210`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/runner/llm.ts#L197-L210)). When the model would end its turn, a pending steer keeps the drain going instead ([`llm.ts:101-106`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/runner/llm.ts#L101-L106), [`llm.ts:183-196`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/runner/llm.ts#L183-L196)). If the drain had already decided to end, the doorbell makes the same execution drain again ([`run-coordinator.ts:73-84`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/run-coordinator.ts#L73-L84)). So the result joins the running turn with no new `session.execution.started`. Verified, high. + +**One edge.** If the wake lands after the parent's execution fiber has exited but while its settle hook still runs, `settle` starts a successor execution. That publishes a fresh `session.execution.started`, right after the parent's own terminal event ([`run-coordinator.ts:113-119`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/run-coordinator.ts#L113-L119)). Verified. + +**Idle parent: always a new execution.** `wake` on an idle session calls `start`, which forks the execution and publishes `session.execution.started` before its first drain (`run-coordinator.ts:86-111`, `execution.ts:146`). The drain finds the pending steer and runs the model. Verified, high. So with the exceptions above (revert, conflict, deleted parent), an idle parent always gets a wake-up after a subagent's report. + +**`queue` behaves differently.** A queued item is taken only at an idle boundary, one at a time (`inbox.ts:586-590`, below). A drain that was woken with scope `steer` stops before queued input ([`llm.ts:77-82`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/runner/llm.ts#L77-L82)). Verified. Subagent results never use it. + +## 3. Several items per wake-up, and the order of events + +**One execution can take several items.** A promotion with steers pending delivers all of them at once, up to the first control item (compaction or move) ([`inbox.ts:573-591`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/inbox.ts#L573-L591), [`inbox.ts:609-614`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/inbox.ts#L609-L614)). Wakes that arrive while the execution exists coalesce into its doorbell (`run-coordinator.ts:135-144`). Verified, high. + +Two children finishing close together therefore give one `session.execution.started`. Their two items are delivered either in the same promotion (if both were admitted before the first step's promote) or the second at a later step of the same execution. Inferred from the code above, high confidence; no test of exactly two sibling reports was found. A plugin can't assume one inbox item per wake-up, nor that the item enqueued just before a `started` is the only one it takes. + +**Order on the bus, for an idle parent.** Verified, high. The child's settle hook runs these steps in sequence on one fiber: + +1. `publishTerminal` publishes the child's `session.execution.succeeded`, `.failed` or `.interrupted`. Its commit callback writes the report to the job outbox in the same transaction ([`execution.ts:168-170`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution.ts#L168-L170), [`execution.ts:211-222`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution.ts#L211-L222)). +2. `settlement.deliver` calls `inbox.admit`, which publishes the parent's `session.inbox.enqueued` ([`execution.ts:173-175`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution.ts#L173-L175), [`inbox.ts:205-210`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/inbox.ts#L205-L210)). +3. `wake(parent)` runs only after `admit` returns (`subagent-report.ts:81-128`). +4. The parent's new execution yields once, then publishes `session.execution.started` (`run-coordinator.ts:96-98`). +5. When the drain promotes the item, the parent's `session.inbox.delivered` follows. + +Each `bus.publish` of a durable event commits, then notifies listeners and the live PubSub inline before it returns ([`bus.ts:470-478`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/bus.ts#L470-L478), [`bus.ts:495-508`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/bus.ts#L495-L508)). So steps 1 and 2 reach subscribers in that order, synchronously on the child's fiber. Steps 4 and 5 run on the parent's forked fiber. They are asynchronous, but can only start after step 3, so they follow. + +Other events can fall between these steps. Examples are `job.updated` and other sessions' events, and events of the parent itself if it was busy. Inferred, medium. The plugin receives the stream through `bus.subscribe` ([`plugin/host.ts:275-283`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/plugin/host.ts#L275-L283)), a PubSub that keeps publish order. Inferred from the PubSub use, medium-high. + +**What a restart replays.** A report already in the outbox, from a crash between steps 1 and 2, is replayed by the restart sweep with the same id ([`restart.ts:346-387`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution/restart.ts#L346-L387), [`restart.ts:401-405`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/execution/restart.ts#L401-L405)). There the child's terminal event belongs to the previous server run. Verified. + +## Events that mark an inbox item's fate + +All four are durable and carry `sessionID` and `inboxID` ([`session-event.ts:208-242`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/schema/src/session-event.ts#L208-L242)). Verified: + +- **`session.inbox.enqueued`** carries the `item`. It is published once per admission; a re-admission of the same id is reconciled without a new event ([`inbox.ts:198-204`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/inbox.ts#L198-L204)). +- **`session.inbox.delivered`** marks the item consumed into the transcript. It is published once per row at promotion ([`inbox.ts:541-571`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/inbox.ts#L541-L571)), and its projector deletes the pending row ([`inbox.ts:371-383`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/inbox.ts#L371-L383)). It fires inside the parent's running execution, after its `session.execution.started`. So pairing `inboxID` from `enqueued` with `delivered` ties an item to the execution that took it, including one delivered mid-turn without a new `started`. Inferred as a pairing method, high confidence on the event order. +- **`session.inbox.cancelled`** marks a pending item that was removed before delivery ([`inbox.ts:259-267`](https://github.com/anomalyco/opencode/blob/fc31a485317970bcf6be7b431a9830aaef875731/packages/core/src/session/inbox.ts#L259-L267)). +- **`session.inbox.delivery.changed`** marks a switch between steer and queue. diff --git a/plugin-opencode/plotkeeper.js b/plugin-opencode/plotkeeper.js index f1fd2bb1..bb55f83a 100644 --- a/plugin-opencode/plotkeeper.js +++ b/plugin-opencode/plotkeeper.js @@ -9,7 +9,8 @@ // A subagent is a child session of its own (#718): its spawn's end names it (`spawned_session_id`), its tool calls, // permission asks and the end of each of its runs, with its reply, go under the session it was spawned from with its // own id (`subagent_session_id`), and its prompt is not recorded. A background subagent's result starts its parent's -// next turn with no prompt, which is sent as `session.execution.started`, a wake-up. +// next turn with no prompt, which is sent as `session.execution.started`, a wake-up, with the subagent results the turn +// took (#779). import { spawn } from "node:child_process"; @@ -59,6 +60,22 @@ function recorder(ctx) { calls: new Map(), // A permission ask whose call has not started yet, by its call id. asks: new Map(), + // Each top-level session's subagent result not yet delivered, by its inbox id: the child and how it ended. + results: new Map(), + // Each top-level session's wake-up, held until its turn's first step with the results the turn took by then. + waking: new Map(), + /** Sends `line`, a top-level session's after its held wake-up, which comes before it; a subagent's goes on its + * own, as it is no line of its parent's turn. */ + send(line) { + if (!line.subagent_session_id) this.flush(line.session_id); + send(line); + }, + /** Sends `session`'s held wake-up. */ + flush(session) { + const held = this.waking.get(session); + this.waking.delete(session); + if (held) send(held); + }, // When the line was sent: each goes through a hook process of its own, all in parallel, so the lines land in any // order, and the hook orders a turn's lines by it (#717). line: (name, session, fields) => ({ hook_event_name: name, session_id: session, cwd, sent_ms: Date.now(), ...fields }), @@ -75,7 +92,7 @@ function recordPrompts(ctx, r) { const top = await r.root(event.sessionID); if (top !== event.sessionID) return void r.prompted.delete(event.sessionID); r.turns.set(top, { model: r.turns.get(top)?.model, reply: "" }); - send(r.line("session.prompt", top, { prompt_id: event.messageID, prompt: event.prompt?.text ?? "" })); + r.send(r.line("session.prompt", top, { prompt_id: event.messageID, prompt: event.prompt?.text ?? "" })); }); } @@ -94,14 +111,14 @@ function recordTools(ctx, r) { const tool = async (name, event, fields) => { const top = await r.root(event.sessionID); const subagent = r.subagent(top, event.sessionID); - send(r.line(name, top, { tool_name: event.tool, tool_use_id: event.id, tool_input: event.input ?? {}, ...subagent, ...fields })); + r.send(r.line(name, top, { tool_name: event.tool, tool_use_id: event.id, tool_input: event.input ?? {}, ...subagent, ...fields })); }; ctx.tool.hook("execute.before", async (event) => { r.calls.set(event.id, { tool: event.tool, input: event.input ?? {} }); await tool("tool.execute.before", event, {}); const ask = r.asks.get(event.id); r.asks.delete(event.id); - if (ask) send(ask(r.calls.get(event.id))); + if (ask) r.send(ask(r.calls.get(event.id))); }); ctx.tool.hook("execute.after", (event) => { r.calls.delete(event.id); @@ -119,6 +136,7 @@ function recordTools(ctx, r) { * subagent's runs end under its top-level session, with its own reply and no model. */ async function recordEvents(ctx, r, signal) { const types = ["session.execution.started", "session.step.started", "session.text.ended", "permission.asked", ...TURN_ENDS]; + types.push("session.inbox.enqueued", "session.inbox.delivered"); for await (const event of ctx.event.subscribe({ types, signal })) { const data = event.data ?? {}; if (!r.seen(data.sessionID)) continue; @@ -128,24 +146,44 @@ async function recordEvents(ctx, r, signal) { const id = data.source?.type === "tool" ? data.source.id : undefined; const call = r.calls.get(id); if (id && !call) r.asks.set(id, (started) => askLine(r, top, data, started)); - else send(askLine(r, top, data, call ?? {})); + else r.send(askLine(r, top, data, call ?? {})); continue; } const own = data.sessionID; const child = top !== own; + // A background job's result reaches its parent's inbox when it ends, and is delivered into the turn that takes + // it: a wake-up it starts, or one running. Only a subagent's is sent; a shell, image, video or Code Mode job's + // names no one (`docs/studio/research/opencode-background-results.md`). + if (event.type === "session.inbox.enqueued") { + const metadata = data.item?.payload?.metadata; + const result = { subagent_session_id: metadata?.childID, state: metadata?.state }; + if (!child && metadata?.source === "subagent") r.results.set(data.inboxID, result); + continue; + } + if (event.type === "session.inbox.delivered") { + const result = r.results.get(data.inboxID); + r.results.delete(data.inboxID); + if (result && r.waking.has(top)) r.waking.get(top).reported.push(result); + else if (result) r.send(r.line(event.type, top, { reported: [result] })); + continue; + } const turn = r.turns.get(own) ?? { reply: "" }; r.turns.set(own, turn); if (event.type === "session.execution.started") { - // A top-level turn with no prompt is a wake-up; a subagent's run is never sent. + // A top-level turn with no prompt is a wake-up; a subagent's run is never sent. Its results are delivered + // before its first step. const wakeUp = !child && !r.prompted.delete(top); if (child || wakeUp) turn.reply = ""; - if (wakeUp) send(r.line(event.type, top, {})); - } else if (event.type === "session.step.started") turn.model = data.model?.id; - else if (event.type === "session.text.ended") turn.reply = data.text ?? ""; + if (!child) r.flush(top); + if (wakeUp) r.waking.set(top, r.line(event.type, top, { reported: [] })); + } else if (event.type === "session.step.started") { + turn.model = data.model?.id; + if (!child) r.flush(top); + } else if (event.type === "session.text.ended") turn.reply = data.text ?? ""; else if (child) { - send(r.line(event.type, top, { last_assistant_message: turn.reply, ...r.subagent(top, own) })); + r.send(r.line(event.type, top, { last_assistant_message: turn.reply, ...r.subagent(top, own) })); r.turns.delete(own); - } else send(r.line(event.type, top, { model: turn.model ?? null, last_assistant_message: turn.reply })); + } else r.send(r.line(event.type, top, { model: turn.model ?? null, last_assistant_message: turn.reply })); } } diff --git a/ui/tests/opencode-plugin.test.mjs b/ui/tests/opencode-plugin.test.mjs new file mode 100644 index 00000000..a6a56b4e --- /dev/null +++ b/ui/tests/opencode-plugin.test.mjs @@ -0,0 +1,121 @@ +// plotkeeper's OpenCode plugin (`plugin-opencode/plotkeeper.js`), loaded as OpenCode loads it, with a fake OpenCode +// context and a fake `plotkeeper-hook` that appends each line it gets to a file. These tests run no OpenCode. Run: +// `npm test`. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { chmodSync, existsSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; + +const source = join(import.meta.dirname, "../../plugin-opencode/plotkeeper.js"); + +/** The plugin rendered as install renders it, its hook a script that appends each line to `lines.jsonl`. */ +async function loadPlugin() { + const bin = realpathSync(mkdtempSync(join(tmpdir(), "opencode-plugin-test-"))); + const out = join(bin, "lines.jsonl"); + writeFileSync(join(bin, "plotkeeper-hook"), `#!/bin/sh\nline=$(cat)\nprintf '%s\\n' "$line" >> "${out}"\n`); + chmodSync(join(bin, "plotkeeper-hook"), 0o755); + const rendered = join(bin, "plotkeeper.js"); + writeFileSync(rendered, readFileSync(source, "utf8").replaceAll("__PLOTKEEPER_BIN__", bin)); + const plugin = (await import(pathToFileURL(rendered).href)).default; + const lines = () => (existsSync(out) ? readFileSync(out, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l)) : []); + return { plugin, lines }; +} + +/** A fake OpenCode context: sessions by parent, the hooks the plugin adds, and an event stream fed by `emit`. */ +function fakeContext(parents) { + const hooks = {}; + const queue = []; + let wake = () => {}; + const ctx = { + location: { directory: "/Users/me/work/hello" }, + session: { + get: async ({ sessionID }) => ({ id: sessionID, parentID: parents[sessionID] }), + hook: (name, fn) => (hooks[`session.${name}`] = fn), + }, + tool: { hook: (name, fn) => (hooks[`tool.${name}`] = fn) }, + event: { + subscribe: ({ types }) => ({ + async *[Symbol.asyncIterator]() { + for (;;) { + while (queue.length) { + const event = queue.shift(); + if (event === null) return; + if (types.includes(event.type)) yield event; + } + await new Promise((resolve) => (wake = () => resolve(undefined))); + } + }, + }), + }, + }; + const emit = (type, data) => { + queue.push({ type, data }); + wake(); + }; + const end = () => { + queue.push(null); + wake(); + }; + return { ctx, hooks, emit, end }; +} + +/** Waits until `lines` holds `count` lines, then a little longer, so a line too many shows. */ +async function settled(lines, count) { + const until = Date.now() + 10_000; + while (lines().length < count && Date.now() < until) await new Promise((r) => setTimeout(r, 25)); + await new Promise((r) => setTimeout(r, 300)); + return lines(); +} + +const P = "ses_parent"; +const result = (inboxID, source, metadata) => ({ + sessionID: P, + inboxID, + item: { type: "synthetic", payload: { text: "", metadata: { source, ...metadata } }, delivery: "steer" }, +}); + +// #779: a wake-up waits for its turn's first step and carries the subagent results the turn took by then, by +// `inbox.delivered`; a result delivered later in a turn goes on a line of its own; a shell job's result names no one. +test("a wake-up carries the subagent results its turn took, and a later one its own line", async () => { + const { plugin, lines } = await loadPlugin(); + const { ctx, hooks, emit, end } = fakeContext({ ses_a: P, ses_b: P }); + const stop = plugin.setup(ctx); + await hooks["session.prompt"]({ sessionID: P, messageID: "msg_0", prompt: { text: "Spawn two." } }); + emit("session.execution.started", { sessionID: P }); + emit("session.execution.succeeded", { sessionID: P }); + // B's and a shell job's results wake the session; A's joins its turn after its first step. + emit("session.inbox.enqueued", result("in_b", "subagent", { childID: "ses_b", state: "error" })); + emit("session.inbox.enqueued", result("in_sh", "shell", {})); + emit("session.execution.started", { sessionID: P }); + emit("session.inbox.delivered", { sessionID: P, inboxID: "in_b" }); + emit("session.inbox.delivered", { sessionID: P, inboxID: "in_sh" }); + emit("session.step.started", { sessionID: P, model: { id: "big-pickle" } }); + emit("session.inbox.enqueued", result("in_a", "subagent", { childID: "ses_a", state: "completed" })); + emit("session.inbox.delivered", { sessionID: P, inboxID: "in_a" }); + emit("session.execution.succeeded", { sessionID: P }); + // A shell job alone wakes it: the wake-up names no one, and goes at the turn's end when no step came. + emit("session.inbox.enqueued", result("in_sh2", "shell", {})); + emit("session.execution.started", { sessionID: P }); + emit("session.inbox.delivered", { sessionID: P, inboxID: "in_sh2" }); + emit("session.execution.succeeded", { sessionID: P }); + end(); + + const got = await settled(lines, 7); + stop(); + const shape = got + .map((l) => ({ name: l.hook_event_name, sent: l.sent_ms, reported: l.reported })) + .sort((x, y) => x.sent - y.sent) + .map(({ name, reported }) => (reported === undefined ? name : `${name} ${JSON.stringify(reported)}`)); + const bError = '[{"subagent_session_id":"ses_b","state":"error"}]'; + const aCompleted = '[{"subagent_session_id":"ses_a","state":"completed"}]'; + assert.deepEqual(new Set(shape), new Set([ + "session.prompt", + "session.execution.succeeded", + `session.execution.started ${bError}`, + `session.inbox.delivered ${aCompleted}`, + "session.execution.started []", + ])); + assert.equal(got.length, 7, JSON.stringify(shape)); +}); From d1dde144caf238d344842cc9cdbf307ec8a40c26 Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Sat, 28 Nov 2026 04:40:54 +0200 Subject: [PATCH 2/3] Studio: a late OpenCode wake-up names no one, and review fixes (#779) A wake-up the hook took late no longer renames the running wake-up's turn; its children still end with their results' status. The plugin keeps only results that name their child. plugin.md says a child that reports again after later work ends again with its new status, and CONTEXT.md's Wake-up covers OpenCode's. Turn.woken_by is renamed results_of, apart from Session::woken_by. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CVqACdVnKiSXskgVojtEiA --- core/src/opencode.rs | 4 ++-- core/src/session.rs | 10 +++++----- core/src/studio/take.rs | 6 ++++-- core/tests/opencode.rs | 7 +++++++ docs/studio/CONTEXT.md | 2 +- docs/studio/plugin.md | 2 +- plugin-opencode/plotkeeper.js | 2 +- 7 files changed, 21 insertions(+), 12 deletions(-) diff --git a/core/src/opencode.rs b/core/src/opencode.rs index ee712a66..3389cfb7 100644 --- a/core/src/opencode.rs +++ b/core/src/opencode.rs @@ -127,8 +127,8 @@ impl Reported { } /// The tasks a line reports on, each with how it ended. -fn reported(reported: Option<&[Reported]>) -> Option { - let tasks = reported?.iter().map(Reported::task); +fn reported(results: Option<&[Reported]>) -> Option { + let tasks = results?.iter().map(Reported::task); Some(Happened::TasksReported(tasks.collect())) } diff --git a/core/src/session.rs b/core/src/session.rs index db7d8ecd..f9239877 100644 --- a/core/src/session.rs +++ b/core/src/session.rs @@ -293,7 +293,7 @@ pub struct Turn { /// The tasks a wake-up's turn took the results of, in order, for an agent that says which /// (OpenCode, #779); empty for any other turn. #[serde(skip_serializing_if = "crate::saved::unsaved", default)] - pub(crate) woken_by: Vec, + pub(crate) results_of: Vec, /// The id its `Stop` gives a card or a summary on it (`Stopped::card`); `None` until it stopped. pub id: Option, /// The first line of its final reply, from its `Stop`. @@ -1090,12 +1090,12 @@ impl Session { return; }; for task in tasks { - if !turn.woken_by.contains(task) { - turn.woken_by.push(task.clone()); + if !turn.results_of.contains(task) { + turn.results_of.push(task.clone()); } } - let woken_by = turn.woken_by.clone(); - let names: Vec<&str> = woken_by.iter().map(|id| self.agent_name(id)).collect(); + let results_of = turn.results_of.clone(); + let names: Vec<&str> = results_of.iter().map(|id| self.agent_name(id)).collect(); let label = match names.as_slice() { [] => "background job returned".into(), [name] => format!("worker {name} returned"), diff --git a/core/src/studio/take.rs b/core/src/studio/take.rs index a44b4eaa..9525267f 100644 --- a/core/src/studio/take.rs +++ b/core/src/studio/take.rs @@ -678,8 +678,10 @@ impl Take<'_> { let reported = self.reported_tasks(); // An adapter's wake-up that says which tasks it took names them all, the first as its sender // (#779). + // A wake-up the hook took late is of a turn already past, and names none. let told = origin == Some(&Origin::WakeUp) - && self.event.has(|h| matches!(h, Happened::TasksReported(_))); + && self.event.has(|h| matches!(h, Happened::TasksReported(_))) + && !self.event.has(|h| matches!(h, Happened::Late)); let session = &mut *self.session; session.reply.clear(); let sender = match origin { @@ -729,7 +731,7 @@ impl Take<'_> { session.unblock(); } session.reopen_turn(); - // Claude Code's wake-ups keep the name its markup gives. + // Named after every task it took; Claude Code's wake-ups keep the name their markup gives. if told { session.wake_up_took(&reported); } diff --git a/core/tests/opencode.rs b/core/tests/opencode.rs index ad369677..628127ee 100644 --- a/core/tests/opencode.rs +++ b/core/tests/opencode.rs @@ -403,6 +403,11 @@ fn a_wake_up_names_the_subagents_whose_results_its_turn_took_and_each_ends_with_ json!({ "prompt_id": "msg_1", "prompt": "And now?" }), ); let delivered = |pairs: &[(&str, &str)]| hello("session.inbox.delivered", 950, reported(pairs)); + let late_wake = |pairs: &[(&str, &str)]| { + let mut fields = reported(pairs); + fields["studio_late"] = true.into(); + hello("session.execution.started", 850, fields) + }; let completed = Status::Completed; let failed = Status::Ended("failed".into()); let interrupted = Status::Ended("interrupted".into()); @@ -424,6 +429,8 @@ fn a_wake_up_names_the_subagents_whose_results_its_turn_took_and_each_ends_with_ vec![prompt, delivered(&[(a, "cancelled")])], "And now?", false, [interrupted.clone(), completed.clone()]), ("a result after its child's end, OpenCode's own order, still ends it with its status", vec![run_end(800, Some(b)), wake(Some(&[(b, "error")]))], "worker B returned", true, [completed.clone(), failed.clone()]), + ("a wake-up the hook took late ends its child but leaves the running wake-up's name", + vec![wake(Some(&[(b, "completed")])), late_wake(&[(a, "error")])], "worker B returned", true, [failed.clone(), completed.clone()]), ]; for (case, after, label, wake_up, statuses) in cases { let mut lines = two_children(); diff --git a/docs/studio/CONTEXT.md b/docs/studio/CONTEXT.md index 1a9a5d6b..1e0a54f1 100644 --- a/docs/studio/CONTEXT.md +++ b/docs/studio/CONTEXT.md @@ -234,7 +234,7 @@ A subagent spawned with its own git worktree, or one that changes files. A helpe A subagent that is not a worker, such as a review or a search. It shows as one line under the agent that spawned it. **Wake-up**: -A prompt that Claude Code sends, not Daniel, to wake an agent when a subagent or a background command it started returns. It names the returning task's id in markup. It never counts as Daniel's prompt: the turn it opens, also when it was queued, is marked as a wake-up's, and the rail labels it "Woken by" with the returning task ("worker returned"), never "You asked" (#675). A turn recorded before that mark reads as Daniel's. +A prompt that Claude Code sends, not Daniel, to wake an agent when a subagent or a background command it started returns. It names the returning task's id in markup. OpenCode's wake-up is a turn its plugin sees start with no prompt, named after every subagent whose result the turn took ("workers A and B returned"), or "background job returned" when it took none (#779). It never counts as Daniel's prompt: the turn it opens, also when it was queued, is marked as a wake-up's, and the rail labels it "Woken by" with the returning task ("worker returned"), never "You asked" (#675). A turn recorded before that mark reads as Daniel's. **Session list**: The list at the page's right, beside the **Map view**: every live agent session, one row each, in one group per **Project**. Every saved project keeps its header, even with no live session: those groups come after the ones with sessions, as their header only. A saved project that is gone or temporary has a header only while it has a live session. A header's name is the project switcher: a press always shows that project's map, the shown project's included, and a chevron before the name, on a project with live sessions only, folds and unfolds its group (named "Sessions of ", with `aria-expanded`); for a project with no live session, its "⋯" holds Remove project. It shows the project's name, even folded its most urgent state (needs you over running), and the project's quiet dot, drawn as the map's mist, which lights for fog on a Core part, a broken law or a PR brief waiting, its hover naming which. Inside it the sessions are by state (needs you, running, your turn, then idle sessions collapsed last), then the project's **Workspaces** rows. A session belongs, for its whole life, to the project it started in: the git repository of the first folder it got (its main checkout, for a task's worktree), else that folder when it is not in git, set once by the core, so a `cd` never moves it ([sessions](behaviour/sessions.md), "A session's project"). Its row carries a token for its workspace and branch (the main checkout's branch, or the task's name and branch), with no project badge. A project with no name is named `~`. Ended sessions are not in it: a "History · N" link at its end opens **History**. A row is one line, its name then its state's shape: a "Needs you" pill (the only colour), a spinner while running, a dot at your turn (filled, with a bold name, while **unseen**), a ring when idle or ended, a check mark instead when its task is **landed**; a live session whose PR has a **PR brief** waiting adds a quiet mark in the map's mist beside its row, its hover "PR #N · brief waiting", whose press opens that brief. Only a needs-you, running or unseen row adds a second line, muted, one line cut with an ellipsis: its question's first line, its **Intention** (else its current step), or its last turn's **Headline**. Hovering a row makes it the **Spotlit session**. A quiet "Clear landed" at the list's end, shown only while a landed session shows, hides every landed row with an Undo for a few seconds, then deletes them. Running subagents nest under the agent that spawned them. When the window is narrow, or `[` folds the list in a wide window, the list is a **strip** of the same shapes, each with a short label from the session's name, distinct between sessions; hovering or pressing it opens the list over the map. `[` again brings the full list back; the fold is not saved. The top bar's needs-you chip counts the sessions that need Daniel; the top bar has no unseen chip, since the list's unseen rows say it. A finished subagent leaves the list and counts in its parent's "N done"; a failed one stays until Daniel opens it. Each row leads with its agent's logo, in one muted colour so "Needs you" stays the only colour, in every state and beside the running spinner, not instead of it; the same logo leads a row in History, and the session's header in its story. A plain terminal shows a terminal glyph. The strip, a project's header and a subagent's row carry no logo. Hovering the header's logo shows the model running the session with its agent ("Claude · Opus 5.5", "agy · Flash high"), and for an agent that reports no context size, such as agy, a note saying so, so a missing size reads as expected. Only Daniel's own actions change the session he looks at: a click or key on a row, which opens its story in the left panel and shows its project's map, or a click on the list's empty space, a second click on the same row or Esc, which close the panel and leave the bare map. diff --git a/docs/studio/plugin.md b/docs/studio/plugin.md index 437830aa..e27e63b4 100644 --- a/docs/studio/plugin.md +++ b/docs/studio/plugin.md @@ -46,7 +46,7 @@ Qwen Code's payloads are near Claude Code's, read by `core/src/qwen.rs` from lin ## What OpenCode's plugin records -OpenCode 2 runs its plugins in one background service (`opencode serve --service`) that every OpenCode window and `opencode run` talks to, and loads a plugin once for each folder a session runs in. The plugin's hooks see only that folder's sessions, but its event stream is the whole service's, so it records the stream's events only for the sessions its own hooks saw, and each event is recorded once. `core/src/opencode.rs` reads its lines: each prompt (the `session` `prompt` hook) starts a turn, tool calls come from the `tool` hooks (`shell` as commands, `write`, `edit` and `patch` as edits, with paths made absolute from the session's folder, and a call that errs or a shell that exits non-zero as failed, with its exit code), `permission.asked` waits on you until its call ends (the plugin sends an ask with its call's tool and input, holding one that comes before its call starts, as OpenCode asks a `write` call's permission as an `edit`), and a turn ends with `session.execution.succeeded`, `.failed` or `.interrupted`, carrying the turn's last text as its reply and the model its steps named. A subagent is a child session of its own, which OpenCode always runs in the background (#718): it shows as a subagent of the session that spawned it, named by its `subagent` call's description, with its type (such as `general`), its calls and asks, and its reply. Its spawn's end names the child (`spawned_session_id`, from the call's `metadata.sessionID`), each of its lines names it (`subagent_session_id`), and each of its runs ends with its last text as its reply; its prompt is its spawn's and is not recorded. When a child's run ends, OpenCode puts its result in its parent's inbox (`session.inbox.enqueued`, an item whose `metadata` names the child and its `state`, `completed`, `error` or `cancelled`) and delivers it into the turn that takes it (`session.inbox.delivered`): a turn it starts with no prompt, a wake-up, or one already running, and one turn can take several (#779; [OpenCode's background results](research/opencode-background-results.md)). The plugin holds a wake-up until its turn's first step, or its turn's next line, and sends it with the subagent results the turn took by then (`reported`, each a `subagent_session_id` and its `state`); a result delivered later in a turn goes on a line of its own, `session.inbox.delivered`, with the same `reported`. A shell, image, video or Code Mode job's result is not sent. A wake-up shows as `worker returned`, or `workers A and B returned` for several, naming in delivery order each subagent whose result its turn took, one that joined it later included; a wake-up that took none, as a shell job's, shows as `background job returned`. A result delivered into a turn Daniel prompted leaves his prompt as it is, and one whose line lands after its turn ended names no one. Each result ends its child with its status, in the studio's words: `completed`, `failed` for `error` and `interrupted` for `cancelled`, as a Claude subagent's are; it overrides the end of the child's run, which carries no status and ends it as completed, whichever line lands first. A child that reports again after later work keeps its first end. A log from the plugin before #779 has no `reported`: its wake-up names the subagent with the latest event, so with two subagents running a wake-up that lands before its child's end can name the other one, and its children end completed. A log from the plugin before #718 has no `spawned_session_id` and no child's end, so its children show unattached, named by the first characters of their id, and stay running; an ask of a child's call in such a log, which names no subagent, waits until its turn ends. +OpenCode 2 runs its plugins in one background service (`opencode serve --service`) that every OpenCode window and `opencode run` talks to, and loads a plugin once for each folder a session runs in. The plugin's hooks see only that folder's sessions, but its event stream is the whole service's, so it records the stream's events only for the sessions its own hooks saw, and each event is recorded once. `core/src/opencode.rs` reads its lines: each prompt (the `session` `prompt` hook) starts a turn, tool calls come from the `tool` hooks (`shell` as commands, `write`, `edit` and `patch` as edits, with paths made absolute from the session's folder, and a call that errs or a shell that exits non-zero as failed, with its exit code), `permission.asked` waits on you until its call ends (the plugin sends an ask with its call's tool and input, holding one that comes before its call starts, as OpenCode asks a `write` call's permission as an `edit`), and a turn ends with `session.execution.succeeded`, `.failed` or `.interrupted`, carrying the turn's last text as its reply and the model its steps named. A subagent is a child session of its own, which OpenCode always runs in the background (#718): it shows as a subagent of the session that spawned it, named by its `subagent` call's description, with its type (such as `general`), its calls and asks, and its reply. Its spawn's end names the child (`spawned_session_id`, from the call's `metadata.sessionID`), each of its lines names it (`subagent_session_id`), and each of its runs ends with its last text as its reply; its prompt is its spawn's and is not recorded. When a child's run ends, OpenCode puts its result in its parent's inbox (`session.inbox.enqueued`, an item whose `metadata` names the child and its `state`, `completed`, `error` or `cancelled`) and delivers it into the turn that takes it (`session.inbox.delivered`): a turn it starts with no prompt, a wake-up, or one already running, and one turn can take several (#779; [OpenCode's background results](research/opencode-background-results.md)). The plugin holds a wake-up until its turn's first step, or its turn's next line, and sends it with the subagent results the turn took by then (`reported`, each a `subagent_session_id` and its `state`); a result delivered later in a turn goes on a line of its own, `session.inbox.delivered`, with the same `reported`. A shell, image, video or Code Mode job's result is not sent. A wake-up shows as `worker returned`, or `workers A and B returned` for several, naming in delivery order each subagent whose result its turn took, one that joined it later included; a wake-up that took none, as a shell job's, shows as `background job returned`. A result delivered into a turn Daniel prompted leaves his prompt as it is, and one whose line lands after its turn ended, or a wake-up the hook took late, names no one. Each result ends its child with its status, in the studio's words: `completed`, `failed` for `error` and `interrupted` for `cancelled`, as a Claude subagent's are; it overrides the end of the child's run, which carries no status and ends it as completed, whichever line lands first. A child that reports again after later work, whose first call after its end runs it again, ends again with its new result's status. A log from the plugin before #779 has no `reported`: its wake-up names the subagent with the latest event, so with two subagents running a wake-up that lands before its child's end can name the other one, and its children end completed. A log from the plugin before #718 has no `spawned_session_id` and no child's end, so its children show unattached, named by the first characters of their id, and stay running; an ask of a child's call in such a log, which names no subagent, waits until its turn ends. OpenCode reports no session start or end, and its plugin runs in the shared service, not in the session's terminal. So an OpenCode line records no pid (`studio_pid`): the process check cannot end an OpenCode session, which takes the idle path, as Codex's do (#369). Its transcript is not read, so a session shows no context size. diff --git a/plugin-opencode/plotkeeper.js b/plugin-opencode/plotkeeper.js index bb55f83a..2a57e24e 100644 --- a/plugin-opencode/plotkeeper.js +++ b/plugin-opencode/plotkeeper.js @@ -157,7 +157,7 @@ async function recordEvents(ctx, r, signal) { if (event.type === "session.inbox.enqueued") { const metadata = data.item?.payload?.metadata; const result = { subagent_session_id: metadata?.childID, state: metadata?.state }; - if (!child && metadata?.source === "subagent") r.results.set(data.inboxID, result); + if (!child && metadata?.source === "subagent" && metadata.childID) r.results.set(data.inboxID, result); continue; } if (event.type === "session.inbox.delivered") { From f7f11b0d0553f6150ec026e306f585bd26e30e42 Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Sat, 28 Nov 2026 12:40:32 +0200 Subject: [PATCH 3/3] Studio: a late OpenCode wake-up leaves the running turn's row name (#779) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The outside review found that a wake-up the hook took late still set the row's "worker … returned" from the latest-event fallback. The table test now checks the row's name too; the late row went red, then green. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CVqACdVnKiSXskgVojtEiA --- core/src/studio/take.rs | 10 ++++++---- core/tests/opencode.rs | 2 ++ 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/core/src/studio/take.rs b/core/src/studio/take.rs index 9525267f..2978848e 100644 --- a/core/src/studio/take.rs +++ b/core/src/studio/take.rs @@ -679,9 +679,10 @@ impl Take<'_> { // An adapter's wake-up that says which tasks it took names them all, the first as its sender // (#779). // A wake-up the hook took late is of a turn already past, and names none. + let late = self.event.has(|h| matches!(h, Happened::Late)); let told = origin == Some(&Origin::WakeUp) && self.event.has(|h| matches!(h, Happened::TasksReported(_))) - && !self.event.has(|h| matches!(h, Happened::Late)); + && !late; let session = &mut *self.session; session.reply.clear(); let sender = match origin { @@ -696,8 +697,9 @@ impl Take<'_> { self.background_retries_reported(prompt); let session = &mut *self.session; match &sender { - // The row says which worker returned until the session's next step. - Sender::WakeUp(task_id) => { + // The row says which worker returned until the session's next step; a late wake-up + // leaves the running turn's. + Sender::WakeUp(task_id) if !late => { let returned = format!("worker {} returned", session.agent_name(task_id)); session.returned = Some(returned); } @@ -705,7 +707,7 @@ impl Take<'_> { session_id: self.event.session_id.clone(), task_id: task_id.clone(), }), - Sender::Daniel => {} + Sender::WakeUp(_) | Sender::Daniel => {} } if sender.is_daniels() { self.ask_name(prompt); diff --git a/core/tests/opencode.rs b/core/tests/opencode.rs index 628127ee..48288fee 100644 --- a/core/tests/opencode.rs +++ b/core/tests/opencode.rs @@ -455,5 +455,7 @@ fn a_wake_up_names_the_subagents_whose_results_its_turn_took_and_each_ends_with_ }; assert_eq!([status(a), status(b)], statuses, "{case}"); assert_eq!(session.turns.len(), 2, "{case}"); + let row = wake_up.then(|| label.to_owned()); + assert_eq!(session.returned, row, "{case}: the row's name"); } }