Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Keep ACP history replay out of new turns (#550)

Afloat303de0a43851
diff --git a/crates/ai/src/cli_agents/acp.rs b/crates/ai/src/cli_agents/acp.rs
index 22235af1..0b0a6f6b 100644
--- a/crates/ai/src/cli_agents/acp.rs
+++ b/crates/ai/src/cli_agents/acp.rs
@@ -198,6 +198,8 @@ impl AcpCore {
let method = msg.get("method").and_then(Value::as_str);
match (method, msg.get("id")) {
(Some(m), Some(id)) => self.agent_request(m, id.clone(), msg.get("params").unwrap_or(&Value::Null)),
+ // session/load replays history before its response, not activity in the new turn.
+ (Some("session/update"), None) if self.pending.values().any(|p| *p == Pending::LoadSession) => Vec::new(),
(Some("session/update"), None) => self.update(msg.get("params").and_then(|p| p.get("update")).unwrap_or(&Value::Null)),
(Some(_), None) => Vec::new(),
(None, Some(id)) => self.response(id.as_u64().unwrap_or(0), &msg),
@@ -711,6 +713,74 @@ mod tests {
assert_eq!(sent(&c.line(r#"{"jsonrpc":"2.0","id":1,"result":{}}"#))[0]["method"], "session/new");
}
+ fn update(c: &mut AcpCore, value: Value) -> Vec<Out> {
+ c.line(&json!({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "old", "update": value}}).to_string())
+ }
+
+ #[test]
+ fn loading_a_session_keeps_replayed_messages_and_tools_out_of_the_new_turn() {
+ let mut c = core(Some("old"));
+ c.start();
+ c.prompt("Continue here.");
+ c.line(r#"{"jsonrpc":"2.0","id":1,"result":{"agentCapabilities":{"loadSession":true}}}"#);
+ let history = [
+ json!({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "Earlier answer"}}),
+ json!({"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": "Earlier thought"}}),
+ json!({"sessionUpdate": "plan", "entries": [{"content": "Earlier plan"}]}),
+ json!({"sessionUpdate": "tool_call", "toolCallId": "old-tool", "title": "Earlier tool", "status": "completed"}),
+ json!({"sessionUpdate": "tool_call_update", "toolCallId": "old-tool", "status": "completed"}),
+ ];
+ for notification in &history {
+ assert!(update(&mut c, notification.clone()).is_empty(), "history must not appear as current activity: {notification}");
+ }
+ assert!(c.tools.is_empty(), "replay must not populate the live tool-title map");
+ assert!(c.line(r#"{"jsonrpc":"2.0","id":99,"result":{}}"#).is_empty());
+ assert!(update(&mut c, history[0].clone()).is_empty(), "an unrelated response does not finish loading");
+
+ let prompt = sent(&c.line(r#"{"jsonrpc":"2.0","id":2,"result":{}}"#));
+ assert_eq!(prompt[0]["method"], "session/prompt");
+ assert_eq!(prompt[0]["params"]["sessionId"], "old");
+ assert_eq!(prompt[0]["params"]["prompt"][0]["text"], "Continue here.");
+ assert_eq!(
+ events(update(&mut c, history[0].clone())),
+ [AgentEvent::TextDelta { text: "Earlier answer".into() }],
+ "the same text after loading is live"
+ );
+ let live = events(update(&mut c, json!({"sessionUpdate": "tool_call", "toolCallId": "live-tool", "title": "Current tool", "status": "pending"})));
+ assert!(matches!(&live[..], [AgentEvent::ToolStarted { tool, .. }] if tool == "Current tool"));
+ let done = events(update(&mut c, json!({"sessionUpdate": "tool_call_update", "toolCallId": "live-tool", "status": "completed"})));
+ assert!(matches!(&done[..], [AgentEvent::ToolFinished { tool, ok: true, .. }] if tool == "Current tool"));
+ assert_eq!(c.tools.len(), 1);
+ }
+
+ #[test]
+ fn a_failed_load_does_not_suppress_the_replacement_sessions_updates() {
+ let mut c = core(Some("old"));
+ c.start();
+ c.prompt("Try again.");
+ c.line(r#"{"jsonrpc":"2.0","id":1,"result":{"agentCapabilities":{"loadSession":true}}}"#);
+ let message = json!({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "Answer"}});
+ assert!(update(&mut c, message.clone()).is_empty());
+ let new = sent(&c.line(r#"{"jsonrpc":"2.0","id":2,"error":{"code":-32603,"message":"load failed"}}"#));
+ assert_eq!(new[0]["method"], "session/new");
+ let prompt = sent(&c.line(r#"{"jsonrpc":"2.0","id":3,"result":{"sessionId":"replacement"}}"#));
+ assert_eq!(prompt[0]["params"]["sessionId"], "replacement");
+ let live = c.line(&json!({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "replacement", "update": message}}).to_string());
+ assert_eq!(events(live), [AgentEvent::TextDelta { text: "Answer".into() }]);
+ }
+
+ #[test]
+ fn cancelling_a_loading_session_does_not_publish_replay_or_send_the_cancelled_prompt() {
+ let mut c = core(Some("old"));
+ c.start();
+ c.prompt("Stop this.");
+ c.line(r#"{"jsonrpc":"2.0","id":1,"result":{"agentCapabilities":{"loadSession":true}}}"#);
+ assert!(c.cancel().contains(&Out::TurnEnded));
+ assert!(update(&mut c, json!({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "History"}})).is_empty());
+ assert!(c.line(r#"{"jsonrpc":"2.0","id":2,"result":{}}"#).is_empty(), "the cancelled prompt stays cancelled when loading finishes");
+ assert_eq!(sent(&c.prompt("A new request."))[0]["params"]["prompt"][0]["text"], "A new request.");
+ }
+
#[test]
fn permission_requests_become_consent_and_are_answered_once() {
let mut c = core(None);
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index 60c5fe79..a0c27d31 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -351,8 +351,9 @@ Owner: open · Status: in progress
**ACP:**
- [ ] Gemini CLI, opencode, goose via ACP or native adapters; each verified live, then turn ACP on
by default for the ones that pass
-- [ ] Over ACP, a continued session shows the earlier conversation again: `session/load` replays it
- as `session/update`s, which we show as new; drop updates until the load answers
+- [x] Over ACP, suppress `session/update` notifications until `session/load` answers, keeping
+ replayed messages and tool activity out of the current turn
+ — commit `38ffc39be084`
- [ ] Over ACP, turns report 0 tokens: the protocol sends only `usage_update` (context used and
size). Read real counts where an agent keeps them (Maki: `token_usage` in its session file
under `~/.local/state/maki/sessions/`) or say the count is unknown instead of 0
diff --git a/docs/STATUS.md b/docs/STATUS.md
index d5ed1dde..a5ae02cc 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -30,7 +30,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi
| Auto mode | Settings → Safety, on by default. Builder actions go ahead without asking, except a fixed set that is never done unasked (deleting outside the project, system changes, publishing…); questions get "decide yourself"; asset spending stops at the budget | Unit tests |
| Generated assets | Off until the person turns them on for a game (the switch on Make and on the project, `project_assets_allow`, `rebuild --generate-assets`, saved in craft.json; turning it on without a fal.ai key asks for one); the brief and the asset tools need both that and a key. `assets_image_generate` (Nano Banana Pro by default) and `assets_model_generate` (picture → Tripo P1 low-poly GLB with a face limit) through the person's key for each asset provider (fal.ai today); per-project budget, $5 by default (`[assets] budget_usd` in config.toml); models and prices from the `assets.toml` table (picture model selectable: Nano Banana Pro, FLUX dev or schnell; priced per picture or per megapixel); every call reports its cost | Unit tests; a live 3D generation with a real key (picture, then model) with FLUX dev; Nano Banana Pro not yet run with a real key |
| Claude Code builder | Runs the person's own `claude` in headless mode (Opus 5.5, high effort unless configured) with our MCP server, a permission-prompt tool and `core_person_ask`; preflights for our CLI (a build stops plainly if it's missing or won't start) and sign-in | Argument and stream-parser tests; live preflight; live builder turns; see [claude-code.md](claude-code.md) |
-| Agents over ACP | Opt-in per backend (`acp = true`): Gemini CLI, Qwen Code, opencode, goose, Hermes and Maki in their ACP mode, one agent process per chat or build with our MCP server; Maki's ACP mode takes the backend's model (`cli_model`). In chat, permission requests become consent questions; in builds they go through the same approval policy as Claude Code's (inbox, Auto mode) | Protocol unit tests against scripted agent messages and an approval-policy test. Run live with Maki 0.7.0 only (2026-11-02, Linux, headless CLI): a static page built to Ready in 38 s, a follow-up continued the same session with `session/load`, and with Auto mode off its command and tool requests were refused in an unattended run. Turns report 0 tokens over ACP, and a continued session shows the earlier conversation again |
+| Agents over ACP | Opt-in per backend (`acp = true`): Gemini CLI, Qwen Code, opencode, goose, Hermes and Maki in their ACP mode, one agent process per chat or build with our MCP server; Maki's ACP mode takes the backend's model (`cli_model`). In chat, permission requests become consent questions; in builds they go through the same approval policy as Claude Code's (inbox, Auto mode). While a saved session loads, replayed updates are withheld from the new turn | Protocol unit tests against scripted agent messages and an approval-policy test. Run live with Maki 0.7.0 only (2026-11-02, Linux, headless CLI): a static page built to Ready in 38 s, a follow-up continued the same session with `session/load`, and with Auto mode off its command and tool requests were refused in an unattended run. Replay suppression passes scripted load-history, success/error and cancellation tests; this correction has not been rerun with a live agent. Turns report 0 tokens over ACP |
| WASM plugins | With `--features wasm-plugins`: `[[plugins.wasm]]` components exporting `craft-anything:plugin/tools` add tools, and ones exporting `craft-anything:plugin/checks` add checks run after each kind's own (they get the build's file list as JSON) (added, listed, turned on or off and removed in Settings → Plugins or with `plugins_add`/`plugins_remove`/`plugins_list`); no imports, fresh instance per call, fuel and memory limits | Tests with components written in WAT (describe, call, checks, a looping call stopped, imports refused, end to end through the engine); `examples/wasm-plugin-wordcount` built from Rust and loaded |
| WebAssembly tag interfaces | `formats_wasm_compare` resolves retained imported and defined tag exports to their declared parameter types. Identical unresolved or invalid diagnostics may still count as unchanged; those counts do not establish interface compatibility, and invalid/partial limitations remain present | Synthetic core modules with tag changes and re-exports, mixed index spaces, import/tag limits, and missing or non-function type references; formats and engine tests. No real module corpus or WebAssembly execution was used for this correction |
| Questions and approvals | A file inbox per project; `core_person_ask`, `core_action_approve` and MCP consent requests become cards in the app | Cross-handle round-trip tests, a full approval round trip through the engine |