From 3d52c049a607ad33cf666df9db4950e44f0a7720 Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Sat, 28 Nov 2026 04:13:41 +0200 Subject: [PATCH 1/2] Studio: an OpenCode session shows its context size (#719) OpenCode's plugin keeps the latest step's input tokens (session.step.ended's input + cache.read + cache.write) on each top-level turn and sends them on the turn's end as context_tokens. The adapter reads them into the session's context; a subagent's or a late end, and an end without a count, keep it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CVqACdAVieHSJNHrmEc2Xd --- core/src/event.rs | 10 ++ core/src/opencode.rs | 58 +++++++----- core/src/studio/take.rs | 3 + core/tests/fixtures/opencode/context.jsonl | 17 ++++ core/tests/opencode.rs | 104 +++++++++++++++++++++ docs/studio/plugin.md | 6 +- plugin-opencode/plotkeeper.js | 17 +++- 7 files changed, 185 insertions(+), 30 deletions(-) create mode 100644 core/tests/fixtures/opencode/context.jsonl diff --git a/core/src/event.rs b/core/src/event.rs index 9389d50c..b2e2b058 100644 --- a/core/src/event.rs +++ b/core/src/event.rs @@ -70,6 +70,9 @@ pub(crate) enum Happened { SubagentEnd, /// The model the session runs at, as the agent last said. Model(String), + /// How full the session's context is, in tokens, where its agent's hooks say (OpenCode's, #719); + /// Claude Code's comes from its transcript. + Context(u64), /// The git branch of the session's workspace. Branch(String), @@ -452,6 +455,13 @@ impl Event { }) } + pub(crate) fn context(&self) -> Option { + self.find(|h| match h { + Happened::Context(tokens) => Some(*tokens), + _ => None, + }) + } + pub(crate) fn branch(&self) -> Option<&str> { self.find(|h| match h { Happened::Branch(branch) => Some(branch.as_str()), diff --git a/core/src/opencode.rs b/core/src/opencode.rs index f45010e1..8f6b19a1 100644 --- a/core/src/opencode.rs +++ b/core/src/opencode.rs @@ -10,7 +10,9 @@ //! 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 +//! the model the turn's steps named, the turn's last text and, on a top-level turn's, its latest +//! step's input tokens (`context_tokens`: `session.step.ended`'s `input + cache.read + +//! cache.write`, #719). 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 @@ -29,10 +31,10 @@ use std::collections::BTreeMap; /// The name OpenCode's plugin passes (`--agent opencode`), which its lines carry. pub(crate) const OPENCODE: &str = "opencode"; -/// What OpenCode reports: a permission that waits on Daniel, the model a turn ran at, a -/// subagent's reply, and the trees the hook records of each turn (#717). Its transcript has no -/// reader here, so no version or context size; no background task ids, no permission mode and no -/// durations. +/// What OpenCode reports: a permission that waits on Daniel, the model a turn ran at, the context +/// size its latest step ended at (#719), a subagent's reply, and the trees the hook records of each +/// turn (#717). Its transcript has no reader here, so no version; no background task ids, no +/// permission mode and no durations. pub const CAPABILITIES: Capabilities = Capabilities { agent: OPENCODE, asks: true, @@ -42,7 +44,7 @@ pub const CAPABILITIES: Capabilities = Capabilities { durations: false, transcript_version: false, transcript_model: false, - context: false, + context: true, turn_trees: true, empty_window_starts: false, transcript_format: TranscriptFormat::Unread, @@ -75,6 +77,9 @@ struct Raw { permission: Value, /// On a turn's end. model: Option, + /// On a top-level turn's end, its latest step's input tokens (#719); none before the plugin of + /// #719, or when the turn ended before any step did. + context_tokens: Option, #[serde(default)] last_assistant_message: String, /// The subagent's own session, on a line of a subagent's. @@ -137,11 +142,33 @@ fn tool(name: &str, input: &Value, cwd: &str) -> Tool { } } +/// What a turn's end, or a subagent's run's end, reports: its reply, and a turn's model and context +/// size; a subagent's names neither. The end of a turn already past when the hook took it would end +/// the turn running now, so it ends none, and its reply, of a turn the next start ended, is not this +/// one's, nor its count, which may be older than the one the turn after it ended with. +fn ended(raw: &Raw) -> Vec { + let mut happened = Vec::new(); + let subagent = raw.subagent_session_id.is_some(); + if subagent { + happened.push(Happened::SubagentEnd); + } else if !raw.studio_late { + happened.push(Happened::TurnEnd); + } + if !raw.studio_late { + happened.push(Happened::Reply(raw.last_assistant_message.clone())); + } + happened.extend(raw.model.clone().map(Happened::Model)); + if !subagent && !raw.studio_late { + happened.extend(raw.context_tokens.map(Happened::Context)); + } + happened +} + fn adapt(raw: Raw) -> Event { let id = raw.tool_use_id.clone(); let call = || tool(&raw.tool_name, &raw.tool_input, &raw.cwd); let mut happened = Vec::new(); - let mut prompt_id = raw.prompt_id; + let mut prompt_id = raw.prompt_id.clone(); match raw.hook_event_name.as_str() { "session.prompt" => happened.push(Happened::TurnStart { prompt: raw.prompt.clone(), @@ -158,24 +185,9 @@ fn adapt(raw: Raw) -> Event { origin: Some(Origin::WakeUp), }); } - // A turn's end, or a subagent's run's end, with its reply; a subagent's names no model. The - // end of a turn already past when the hook took it would end the turn running now, so it - // ends none, and its reply, of a turn the next start ended, is not this one's. "session.execution.succeeded" | "session.execution.failed" - | "session.execution.interrupted" => { - if raw.subagent_session_id.is_some() { - happened.push(Happened::SubagentEnd); - } else if !raw.studio_late { - happened.push(Happened::TurnEnd); - } - if !raw.studio_late { - happened.push(Happened::Reply(raw.last_assistant_message.clone())); - } - if let Some(model) = raw.model.clone() { - happened.push(Happened::Model(model)); - } - } + | "session.execution.interrupted" => happened = ended(&raw), "tool.execute.before" => happened.push(Happened::ToolStart { tool: call(), id: id.clone(), diff --git a/core/src/studio/take.rs b/core/src/studio/take.rs index 09d54145..d5e1c8f7 100644 --- a/core/src/studio/take.rs +++ b/core/src/studio/take.rs @@ -188,6 +188,9 @@ impl Take<'_> { if let Some(branch) = event.branch() { session.transcript.branch = Some(branch.into()); } + if let Some(tokens) = event.context() { + session.transcript.context = Some(transcript::Context { tokens }); + } session.transcript_file.format = event.capabilities.transcript_format; } diff --git a/core/tests/fixtures/opencode/context.jsonl b/core/tests/fixtures/opencode/context.jsonl new file mode 100644 index 00000000..45c5b982 --- /dev/null +++ b/core/tests/fixtures/opencode/context.jsonl @@ -0,0 +1,17 @@ +{"cwd":"/Users/me/work/hello","hook_event_name":"session.prompt","prompt":"Read README.md, then write notes.txt containing only its second line, then run cat notes.txt. Reply in one short sentence.","prompt_id":"msg_21fe7f01d001ysG7ArSdusep7P","sent_ms":1795831623846,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831623855,"studio_touched_roots":["/Users/me/work/hello"],"studio_turn_start":{"/Users/me/work/hello":"94543e80539b6f9c169849ae8a16f8b642d281fa"}} +{"cwd":"/Users/me/work/hello","hook_event_name":"tool.execute.before","sent_ms":1795831626389,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831626396,"studio_touched_roots":["/Users/me/work/hello"],"tool_input":{"path":"README.md"},"tool_name":"read","tool_use_id":"chatcmpl-tool-87c3fbae8134bbe2"} +{"cwd":"/Users/me/work/hello","error":null,"exit":null,"hook_event_name":"tool.execute.after","sent_ms":1795831626393,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","status":"completed","studio_agent":"opencode","studio_received_ms":1795831626399,"studio_touched_roots":["/Users/me/work/hello"],"tool_input":{"path":"README.md"},"tool_name":"read","tool_use_id":"chatcmpl-tool-87c3fbae8134bbe2"} +{"cwd":"/Users/me/work/hello","hook_event_name":"tool.execute.before","sent_ms":1795831628961,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831628966,"studio_touched_roots":["/Users/me/work/hello"],"tool_input":{"content":"second line\n","path":"notes.txt"},"tool_name":"write","tool_use_id":"chatcmpl-tool-b08bf788d4909d9d"} +{"cwd":"/Users/me/work/hello","error":null,"exit":null,"hook_event_name":"tool.execute.after","sent_ms":1795831628962,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","status":"completed","studio_agent":"opencode","studio_received_ms":1795831628968,"studio_touched_roots":["/Users/me/work/hello"],"tool_input":{"content":"second line\n","path":"notes.txt"},"tool_name":"write","tool_use_id":"chatcmpl-tool-b08bf788d4909d9d"} +{"cwd":"/Users/me/work/hello","hook_event_name":"tool.execute.before","sent_ms":1795831630853,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831630860,"studio_touched_roots":["/Users/me/work/hello"],"tool_input":{"command":"cat notes.txt"},"tool_name":"shell","tool_use_id":"chatcmpl-tool-a190b1ec91f1f266"} +{"cwd":"/Users/me/work/hello","error":null,"exit":0,"hook_event_name":"tool.execute.after","sent_ms":1795831630862,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","status":"completed","studio_agent":"opencode","studio_received_ms":1795831630870,"studio_touched_roots":["/Users/me/work/hello"],"tool_input":{"command":"cat notes.txt"},"tool_name":"shell","tool_use_id":"chatcmpl-tool-a190b1ec91f1f266"} +{"context_tokens":11215,"cwd":"/Users/me/work/hello","hook_event_name":"session.execution.succeeded","last_assistant_message":"Wrote the README's second line to notes.txt and confirmed it with cat.","model":"big-pickle","sent_ms":1795831632916,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831632921,"studio_turn_end":{"/Users/me/work/hello":"d985af22f43627f8691cf7d1ca262c8c68b9f836"}} +{"cwd":"/Users/me/work/hello","hook_event_name":"session.prompt","prompt":"Use the subagent tool to start a general subagent that reads README.md and reports its first line. Then reply with that line.","prompt_id":"msg_21fe83569001dfmCc0LHxXuVl9","sent_ms":1795831641450,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831641458,"studio_touched_roots":["/Users/me/work/hello"],"studio_turn_start":{"/Users/me/work/hello":"d985af22f43627f8691cf7d1ca262c8c68b9f836"}} +{"cwd":"/Users/me/work/hello","hook_event_name":"tool.execute.before","sent_ms":1795831643666,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831643670,"studio_touched_roots":["/Users/me/work/hello"],"tool_input":{"agent":"general","description":"Read README first line","prompt":"Read the file README.md in the working directory /Users/me/work/hello and report its first line exactly. Do not modify any files. Reply with only that line."},"tool_name":"subagent","tool_use_id":"chatcmpl-tool-837891808d081697"} +{"cwd":"/Users/me/work/hello","error":null,"exit":null,"hook_event_name":"tool.execute.after","sent_ms":1795831643678,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","spawned_session_id":"ses_de017c1ecffee7use05OD8E0Il","status":"completed","studio_agent":"opencode","studio_received_ms":1795831643682,"studio_touched_roots":["/Users/me/work/hello"],"tool_input":{"agent":"general","description":"Read README first line","prompt":"Read the file README.md in the working directory /Users/me/work/hello and report its first line exactly. Do not modify any files. Reply with only that line."},"tool_name":"subagent","tool_use_id":"chatcmpl-tool-837891808d081697"} +{"context_tokens":11516,"cwd":"/Users/me/work/hello","hook_event_name":"session.execution.succeeded","last_assistant_message":"I've launched the subagent; I'll reply with the first line as soon as it reports back.","model":"big-pickle","sent_ms":1795831646316,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831646324,"studio_turn_end":{"/Users/me/work/hello":"d985af22f43627f8691cf7d1ca262c8c68b9f836"}} +{"cwd":"/Users/me/work/hello","hook_event_name":"tool.execute.before","sent_ms":1795831646398,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831646405,"studio_touched_roots":["/Users/me/work/hello"],"studio_turn_start":{"/Users/me/work/hello":"d985af22f43627f8691cf7d1ca262c8c68b9f836"},"subagent_session_id":"ses_de017c1ecffee7use05OD8E0Il","tool_input":{"limit":1,"path":"README.md"},"tool_name":"read","tool_use_id":"chatcmpl-tool-b6ab4a1106c82378"} +{"cwd":"/Users/me/work/hello","error":null,"exit":null,"hook_event_name":"tool.execute.after","sent_ms":1795831646402,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","status":"completed","studio_agent":"opencode","studio_received_ms":1795831646411,"studio_touched_roots":["/Users/me/work/hello"],"subagent_session_id":"ses_de017c1ecffee7use05OD8E0Il","tool_input":{"limit":1,"path":"README.md"},"tool_name":"read","tool_use_id":"chatcmpl-tool-b6ab4a1106c82378"} +{"cwd":"/Users/me/work/hello","hook_event_name":"session.execution.succeeded","last_assistant_message":"# Hello","sent_ms":1795831648919,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831648927,"studio_turn_end":{"/Users/me/work/hello":"d985af22f43627f8691cf7d1ca262c8c68b9f836"},"subagent_session_id":"ses_de017c1ecffee7use05OD8E0Il"} +{"cwd":"/Users/me/work/hello","hook_event_name":"session.execution.started","sent_ms":1795831648932,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831648941,"studio_touched_roots":["/Users/me/work/hello"],"studio_turn_start":{"/Users/me/work/hello":"d985af22f43627f8691cf7d1ca262c8c68b9f836"}} +{"context_tokens":11689,"cwd":"/Users/me/work/hello","hook_event_name":"session.execution.succeeded","last_assistant_message":"# Hello","model":"big-pickle","sent_ms":1795831651370,"session_id":"ses_de0180feeffehT93YWrZ2rP3WY","studio_agent":"opencode","studio_received_ms":1795831651376,"studio_turn_end":{"/Users/me/work/hello":"d985af22f43627f8691cf7d1ca262c8c68b9f836"}} diff --git a/core/tests/opencode.rs b/core/tests/opencode.rs index 551111ec..ee4b9079 100644 --- a/core/tests/opencode.rs +++ b/core/tests/opencode.rs @@ -62,6 +62,8 @@ fn the_recorded_run_replays_into_its_sessions_turns_and_tools() { ); assert!(hello.turns.iter().all(|t| t.ended_at.is_some())); assert_eq!(hello.state, State::YourTurn); + // The plugin before #719 sent no context size. + assert_eq!(hello.transcript.context, None); let id = |s: &str| format!("chatcmpl-tool-{s}"); assert_eq!( calls(&studio, HELLO), @@ -324,3 +326,105 @@ 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 top-level turn's end carries its latest step's input tokens (`context_tokens`, #719), which are +/// the session's context size. An end without the field (a turn that ended before any step did, or +/// the plugin before #719), a subagent's run's end and a late end leave it as it was. +#[test] +fn a_turn_ends_count_is_the_sessions_context_size_and_an_end_without_one_keeps_it() { + let line = |name: &str, at: u64, fields: Value| { + let mut line = json!({ + "session_id": HELLO, "cwd": "/Users/me/work/hello", "hook_event_name": name, + "studio_agent": "opencode", "studio_received_ms": at, + }); + line.as_object_mut() + .unwrap() + .extend(fields.as_object().unwrap().clone()); + line.to_string() + }; + let prompt = |at: u64| { + line( + "session.prompt", + at, + json!({ "prompt_id": format!("msg_{at}") }), + ) + }; + let end = |at: u64, fields: Value| line("session.execution.succeeded", at, fields); + let first = [prompt(10), end(20, json!({ "context_tokens": 12_091 }))]; + let cases = [ + ( + "a later end's count", + vec![prompt(30), end(40, json!({ "context_tokens": 13_000 }))], + 13_000, + ), + ( + "an end without a count", + vec![prompt(30), end(40, json!({}))], + 12_091, + ), + ( + "a subagent's end", + vec![ + prompt(30), + end( + 40, + json!({ "subagent_session_id": "ses_child", "context_tokens": 99 }), + ), + ], + 12_091, + ), + ( + "a late end", + vec![ + prompt(30), + end(40, json!({ "studio_late": true, "context_tokens": 99 })), + ], + 12_091, + ), + ]; + for (case, then, tokens) in cases { + let lines: Vec<_> = first.iter().cloned().chain(then).collect(); + let studio = Studio::replayed(&lines); + let context = studio.session(HELLO).unwrap().transcript.context.clone(); + assert_eq!(context.map(|c| c.tokens), Some(tokens), "{case}"); + } +} + +/// `fixtures/opencode/context.jsonl`, a real run (2026-11-28, OpenCode 2.4.2's service) of the +/// plugin since #719: a first turn read, wrote and ran a command; a second, by `opencode run -s`, +/// started a background subagent that read a file, whose result woke the session. A scratch plugin +/// beside it logged each `session.step.ended`, whose `input + cache.read + cache.write` was 11,215, +/// 11,516 and 11,689 at the session's three turn ends, and 10,180 and 10,239 at its subagent's steps. +/// The session's context size is its last top-level step's, from each turn's end; its subagent's +/// steps never set it, as its run's end carries no count. +#[test] +fn an_opencode_sessions_context_size_is_its_last_top_level_steps_input_tokens() { + let lines: Vec<_> = include_str!("fixtures/opencode/context.jsonl") + .lines() + .collect(); + let id = "ses_de0180feeffehT93YWrZ2rP3WY"; + let tokens_after = |n: usize| { + let studio = Studio::replayed(&lines[..n]); + let session = studio.session(id).unwrap(); + session.transcript.context.as_ref().map(|c| c.tokens) + }; + // Each turn's end, the subagent's run's end, the wake-up's start and its end. + let tokens: Vec<_> = [7, 8, 12, 15, 16, 17].map(tokens_after).into(); + assert_eq!( + tokens, + [ + None, + Some(11_215), + Some(11_516), + Some(11_516), + Some(11_516), + Some(11_689) + ] + ); + let studio = Studio::replayed(&lines); + let session = studio.session(id).unwrap(); + assert!(session.capabilities.context); + assert_eq!(session.turns.len(), 3); + assert_eq!(session.agents.len(), 1); + assert_eq!(session.state, State::YourTurn); +} diff --git a/docs/studio/plugin.md b/docs/studio/plugin.md index fc3adc29..9e74e59d 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 top-level turn's end also carries the session's context size (`context_tokens`, #719): the input tokens of the turn's latest `session.step.ended`, its `input + cache.read + cache.write`, the same measure as Claude Code's, so the header shows it as it does a Claude Code session's. It updates when a turn ends, not at each step. A subagent's steps never set it, and its run's end carries no count; an end without one (a turn that ended before any step did, or a log from the plugin before #719) keeps the size the session last had. 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 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. +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; its context size comes from its turns' ends, above. 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) and of OpenCode 2.4.2 (`context.jsonl`, the plugin since #719, with 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). ## What Cline's plugin records diff --git a/plugin-opencode/plotkeeper.js b/plugin-opencode/plotkeeper.js index f1fd2bb1..b93ef69e 100644 --- a/plugin-opencode/plotkeeper.js +++ b/plugin-opencode/plotkeeper.js @@ -51,7 +51,7 @@ function recorder(ctx) { return { seen: (sessionID) => roots.has(sessionID), root, - // The model and the last reply text of each top-level session's turn, for its end. + // The model, the last reply text and the latest step's input tokens of each top-level session's turn, for its end. turns: new Map(), // The sessions prompted since their last turn started. prompted: new Set(), @@ -115,10 +115,14 @@ function recordTools(ctx, r) { }); } +/** A step's input tokens, the size of its prompt: fresh, cache-read and cache-written, as Claude Code's context (#719). */ +const inputTokens = (tokens) => tokens && (tokens.input ?? 0) + (tokens.cache?.read ?? 0) + (tokens.cache?.write ?? 0); + /** The event stream's permission asks and turn starts and ends, of the sessions this instance's hooks saw: a - * subagent's runs end under its top-level session, with its own reply and no model. */ + * subagent's runs end under its top-level session, with its own reply and no model or context size. */ async function recordEvents(ctx, r, signal) { - const types = ["session.execution.started", "session.step.started", "session.text.ended", "permission.asked", ...TURN_ENDS]; + const steps = ["session.step.started", "session.step.ended"]; + const types = ["session.execution.started", ...steps, "session.text.ended", "permission.asked", ...TURN_ENDS]; for await (const event of ctx.event.subscribe({ types, signal })) { const data = event.data ?? {}; if (!r.seen(data.sessionID)) continue; @@ -141,11 +145,16 @@ async function recordEvents(ctx, r, signal) { 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; + // A subagent's steps count on its own turn, whose end sends no count: they are not the session's context. + else if (event.type === "session.step.ended") turn.context = inputTokens(data.tokens) ?? turn.context; 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.turns.delete(own); - } else send(r.line(event.type, top, { model: turn.model ?? null, last_assistant_message: turn.reply })); + } else { + const fields = { model: turn.model ?? null, last_assistant_message: turn.reply, context_tokens: turn.context ?? null }; + send(r.line(event.type, top, fields)); + } } } From 203f4afbf8a867a8f5aa893eba9a06d745648b61 Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Sat, 28 Nov 2026 04:18:16 +0200 Subject: [PATCH 2/2] Studio: review fixes for #719's OpenCode context size A step with zero or no tokens keeps the turn's last count; the dev and vocabulary docs and follow_process's comment name the new source; the new test reuses server_line. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01CVqACdAVieHSJNHrmEc2Xd --- core/src/studio/take.rs | 3 ++- core/tests/opencode.rs | 13 ++++--------- docs/studio/CONTEXT.md | 2 +- docs/studio/development.md | 2 +- plugin-opencode/plotkeeper.js | 5 +++-- 5 files changed, 11 insertions(+), 14 deletions(-) diff --git a/core/src/studio/take.rs b/core/src/studio/take.rs index d5e1c8f7..1b1adb1c 100644 --- a/core/src/studio/take.rs +++ b/core/src/studio/take.rs @@ -167,7 +167,8 @@ struct Take<'a> { } impl Take<'_> { - /// The process facts every event carries: its pid, mode, model, branch and transcript format. + /// The process facts every event carries: its pid, mode, model, branch, context size and + /// transcript format. fn follow_process(&mut self) { let (session, event) = (&mut *self.session, self.event); // A deleted session that starts again, by a resume, is back in the list; a late end is not. diff --git a/core/tests/opencode.rs b/core/tests/opencode.rs index ee4b9079..bf101056 100644 --- a/core/tests/opencode.rs +++ b/core/tests/opencode.rs @@ -332,15 +332,10 @@ fn opencode_lines_the_hook_took_late_end_no_turn_and_their_calls_are_the_turn_be /// the plugin before #719), a subagent's run's end and a late end leave it as it was. #[test] fn a_turn_ends_count_is_the_sessions_context_size_and_an_end_without_one_keeps_it() { - let line = |name: &str, at: u64, fields: Value| { - let mut line = json!({ - "session_id": HELLO, "cwd": "/Users/me/work/hello", "hook_event_name": name, - "studio_agent": "opencode", "studio_received_ms": at, - }); - line.as_object_mut() - .unwrap() - .extend(fields.as_object().unwrap().clone()); - line.to_string() + let line = |name: &str, at: u64, mut fields: Value| { + fields["cwd"] = "/Users/me/work/hello".into(); + fields["studio_agent"] = OPENCODE_CAPABILITIES.agent.into(); + server_line(HELLO, name, at, fields) }; let prompt = |at: u64| { line( diff --git a/docs/studio/CONTEXT.md b/docs/studio/CONTEXT.md index 1a9a5d6b..32780873 100644 --- a/docs/studio/CONTEXT.md +++ b/docs/studio/CONTEXT.md @@ -181,7 +181,7 @@ What the list and the rail call an agent session: the name Daniel gave it, else _Avoid_: Title **Context size**: -How many tokens an agent session's context holds: the input tokens of its latest message, read from its transcript, shown in its row as "85k". The control room knows no window size, so it shows no share of it. +How many tokens an agent session's context holds: the input tokens of its latest message, read from its transcript (an OpenCode session's from its turns' ends, #719), shown in its row as "85k". The control room knows no window size, so it shows no share of it. **Context share** (retired): Retired with the status line snapshots that measured it (#416); its code is in `archive/`. How much of its context window an agent session used, as a percentage, from the session's status line snapshot: its tokens, its window size, and Claude Code's own percent used and left. Only sessions the desktop app started saved a snapshot. diff --git a/docs/studio/development.md b/docs/studio/development.md index 9535ac92..781f8cd1 100644 --- a/docs/studio/development.md +++ b/docs/studio/development.md @@ -27,7 +27,7 @@ - `system-map/tests/`: the library's two entry points and the binary, on temporary git repositories the tests build (also the lenient parser that the Map view reads with, and the law tags' resolver that tells which test follows each `@law` tag): each failure of the check with a repository that causes it and one that does not, ownership (the last match winning, `ignored` winning, the three pattern forms) through `touched`, which still answers a map over a cap, law tags, each extractor on a small tree, a link's kind and reason and the pass line's counts of proven and unproven import links (`edges.rs`), a part's purpose and held items, their caps and messages, and a version 1 map's conversion (`parts.rs`), the imports' counts, hubs and the `imports` command (`imports.rs`), and the binary's exit status, output and `--json`; - the unit tests of `system-map/src/extract/`: the contract cases each registered extractor runs through its fixture kit (the anchor case, a file that is not UTF-8, a missing and a malformed config, each skipped case printing its reason), and the core's rules on fake extractors (untracked and self pairs dropped, duplicates kept once with their lowest line, ignored files, declaration pairs, problem order); - the unit tests of the Map view's modules in `server/src/`, on temporary repositories and a temporary data folder: the fetch cooldown and in-flight lock, also after a panic, and a merge fetching only on its transition (`map`); the fog walk, its strengths, a walk overtaken by another not filed twice and "I know this" (`fog`); a part's history, the map at a commit and a commit's files (`history`); the failed log's tests read for `cargo nextest` and Node's runner, the law each failure holds, the last finished result kept across a restart (`ci_laws`); and the usage log's append after a torn line, tolerance of older and newer lines and the counts of the one-time review (`stop_rules`); -- `core/tests/agents.rs`: a line read by the agent its hook entry names, and a line that names none read by its shape; `core/tests/codex.rs`, `qwen.rs`, `cursor.rs` and `copilot.rs`: each adapter's run, built from its hook docs (`opencode.rs`: real runs of OpenCode 2.4.1 through its plugin, two folders at once with a subagent's wake-up, asks before an edit and a command, and a turn that wrote a file by a relative path listing it; `cline.rs`: a real run of Cline CLI 3.0.76 through its plugin), replayed into sessions, turns and calls, its own turn ends (Codex's `Interrupt`, Cursor's aborted `stop`), a Codex and a Cursor turn from wave 1's trial (`fixtures/codex/trial.jsonl`, `fixtures/cursor/trial.jsonl`) listing the file it changed and its summary's facts carrying it, Cursor.app's empty-window `sessionStart` adding no row and a prompt in that window showing its session from its start (`cursor.rs`), an IDE-hosted session with no pid going idle, and a session ended by the process check or a `StudioInterrupted` line keeping its agent; +- `core/tests/agents.rs`: a line read by the agent its hook entry names, and a line that names none read by its shape; `core/tests/codex.rs`, `qwen.rs`, `cursor.rs` and `copilot.rs`: each adapter's run, built from its hook docs (`opencode.rs`: real runs of OpenCode 2.4.1 and 2.4.2 through its plugin, two folders at once with a subagent's wake-up, asks before an edit and a command, a turn that wrote a file by a relative path listing it, and the context size each turn's end carries, which a subagent's end and an end without one keep; `cline.rs`: a real run of Cline CLI 3.0.76 through its plugin), replayed into sessions, turns and calls, its own turn ends (Codex's `Interrupt`, Cursor's aborted `stop`), a Codex and a Cursor turn from wave 1's trial (`fixtures/codex/trial.jsonl`, `fixtures/cursor/trial.jsonl`) listing the file it changed and its summary's facts carrying it, Cursor.app's empty-window `sessionStart` adding no row and a prompt in that window showing its session from its start (`cursor.rs`), an IDE-hosted session with no pid going idle, and a session ended by the process check or a `StudioInterrupted` line keeping its agent; - `core/tests/interrupted.rs`: a `StudioInterrupted` line ends its turn live and through a replay, never a later turn, and a late hook event or `Stop` of that turn does not reopen it; a first turn cancelled before any call is named again from the next prompt; - `core/tests/close_rename.rs`: a rename line keeps the session's name through a replay, as at a restart; a delete line hides the row through a replay, until the session starts again; - `core/tests/blocked_commands.rs`: blocked commands replayed through the core: the command's fields, block order, a subagent's block, needs you until the session moves on (the agent's next call, Daniel's next prompt, a subagent's end, not the turn's end), which blocks count as waiting, and an older log's Allow, Decline, decision and retry. diff --git a/plugin-opencode/plotkeeper.js b/plugin-opencode/plotkeeper.js index b93ef69e..19fc3601 100644 --- a/plugin-opencode/plotkeeper.js +++ b/plugin-opencode/plotkeeper.js @@ -145,8 +145,9 @@ async function recordEvents(ctx, r, signal) { 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; - // A subagent's steps count on its own turn, whose end sends no count: they are not the session's context. - else if (event.type === "session.step.ended") turn.context = inputTokens(data.tokens) ?? turn.context; + // A subagent's steps count on its own turn, whose end sends no count: they are not the session's context. A step + // that names no tokens, or none at all, keeps the last count. + else if (event.type === "session.step.ended") turn.context = inputTokens(data.tokens) || turn.context; 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) }));