Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

449 KB
Raw Blame
mod background_continuations;
mod background_jobs;
mod computer_rpc;
mod config_sync_rpc;
mod file_batches;
mod gen_ui;
mod market_browse_rpc;
mod modes_rpc;
mod plugin_reviews_rpc;
mod remote_tools;
mod review_actions_rpc;
mod scheduled_rpc;
mod scheduled_settings;
mod scheduled_tools;
mod session_configuration;
mod session_display;
mod todos;
mod window_corner_rpc;
mod window_owner;
mod window_snap_rpc;
mod worktree_rpc;

#[cfg(test)]
mod session_mode_create_tests;

#[cfg(test)]
mod session_mode_migration_tests;

#[cfg(test)]
mod market_browse_rpc_tests;
#[cfg(test)]
mod plugin_reviews_rpc_tests;
#[cfg(test)]
mod review_rpc_tests;
#[cfg(test)]
mod turn_permission_tests;
#[cfg(test)]
mod visualization_tests;
#[cfg(test)]
mod write_scope_tests;

use std::io::{self, BufRead, BufReader as StdBufReader, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};

use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use tokio::sync::{mpsc, oneshot, Mutex, Semaphore};

use crate::agent_capabilities::CapabilityLevel;
use crate::artifacts;
use crate::audit;
use crate::background_tasks;
use crate::notifications;
use crate::permissions::{PermissionDecision, PermissionEvaluationParams, PermissionManager};
use crate::plans;
use crate::plugin_sessions;
use crate::plugin_usage;
use crate::providers::{self, DiscoveredModelInput, ProviderCreateInput, ProviderUpdateInput};
use crate::review;
use crate::scratch;
use crate::sessions::{self, UiMessage};
use crate::state::{AppState, HOST_VERSION, PROTOCOL_VERSION};
use crate::tools::{self, ToolsExecuteParams};
use crate::transcripts::{self, CompactionRecord};
use crate::turn_permissions;
use crate::turn_queue;
use crate::visualizations;
use crate::workspace::{self, ContainedRoots, ToolRoot};

#[derive(Debug, Deserialize)]
struct JsonRpcRequest {
    id: Option<Value>,
    method: String,
    params: Option<Value>,
}

#[derive(Debug, Serialize)]
struct JsonRpcResponse {
    jsonrpc: &'static str,
    id: Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    result: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<JsonRpcError>,
}

#[derive(Debug, Serialize)]
struct JsonRpcError {
    code: i64,
    message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    data: Option<Value>,
}

#[derive(Debug, Serialize)]
struct JsonRpcNotification {
    jsonrpc: &'static str,
    method: String,
    params: Value,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct CacheModelsParams {
    #[serde(default)]
    complete: bool,
    provider_id: String,
    models: Vec<DiscoveredModelInput>,
    endpoint: Option<ModelDiscoveryEndpoint>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ModelDiscoveryEndpoint {
    base_url: String,
    api_style: String,
}

impl ModelDiscoveryEndpoint {
    fn matches(&self, db: &crate::db::Database, provider_id: &str) -> rusqlite::Result<bool> {
        db.conn().query_row(
            "SELECT EXISTS(SELECT 1 FROM providers WHERE id = ?1
             AND COALESCE(base_url, '') = ?2 AND COALESCE(api_style, '') = ?3)",
            rusqlite::params![provider_id, self.base_url, self.api_style],
            |row| row.get(0),
        )
    }
}

#[derive(Debug)]
enum StdinEvent {
    Line(String),
    Oversize { id: Value },
    Error(String),
}

/// Best-effort JSON-RPC id from a possibly truncated NDJSON prefix.
///
/// Electron matches host replies by id. A `LIMIT_EXCEEDED` reply with a null
/// id is treated as a notification and the caller waits out the 130 s deadline.
fn peek_jsonrpc_id(prefix: &str) -> Value {
    let window = prefix.get(..prefix.len().min(2048)).unwrap_or(prefix);
    if let Ok(value) = serde_json::from_str::<Value>(window) {
        return value.get("id").cloned().unwrap_or(Value::Null);
    }
    let bytes = window.as_bytes();
    let mut i = 0;
    while i + 4 < bytes.len() {
        if &bytes[i..i + 4] != b"\"id\"" {
            i += 1;
            continue;
        }
        let mut j = i + 4;
        while j < bytes.len() && bytes[j].is_ascii_whitespace() {
            j += 1;
        }
        if j >= bytes.len() || bytes[j] != b':' {
            i += 1;
            continue;
        }
        j += 1;
        while j < bytes.len() && bytes[j].is_ascii_whitespace() {
            j += 1;
        }
        if j >= bytes.len() {
            return Value::Null;
        }
        if bytes[j] == b'"' {
            j += 1;
            let start = j;
            while j < bytes.len() {
                if bytes[j] == b'\\' {
                    j = (j + 2).min(bytes.len());
                    continue;
                }
                if bytes[j] == b'"' {
                    return std::str::from_utf8(&bytes[start..j])
                        .map(|text| Value::String(text.to_string()))
                        .unwrap_or(Value::Null);
                }
                j += 1;
            }
            return Value::Null;
        }
        if bytes.get(j..j + 4) == Some(&b"null"[..]) {
            return Value::Null;
        }
        let start = j;
        if bytes[j] == b'-' {
            j += 1;
        }
        while j < bytes.len() && bytes[j].is_ascii_digit() {
            j += 1;
        }
        if j > start {
            if let Ok(text) = std::str::from_utf8(&bytes[start..j]) {
                if let Ok(n) = text.parse::<i64>() {
                    return json!(n);
                }
            }
        }
        return Value::Null;
    }
    Value::Null
}

const STDOUT_WRITER_SHUTDOWN: Duration = Duration::from_secs(5);

/// Tokio's stdio adapter delegates every read/write to the blocking pool. If
/// the OS temporarily refuses another worker thread, Tokio panics instead of
/// returning an error. The host's control pipe must not share that failure
/// mode, so it uses two fixed, explicitly named threads instead.
fn is_transient_io_error(error: &io::Error) -> bool {
    matches!(
        error.kind(),
        io::ErrorKind::Interrupted | io::ErrorKind::WouldBlock
    ) || matches!(error.raw_os_error(), Some(11) | Some(35))
}

/// Largest single NDJSON request line the host accepts. A Write payload of a
/// few megabytes fits comfortably; anything past this is a framing fault, not
/// a request, and must not be buffered into memory line by line.
const MAX_STDIN_LINE_BYTES: u64 = 64 * 1024 * 1024;

fn spawn_stdin_reader(tx: mpsc::UnboundedSender<StdinEvent>) -> io::Result<thread::JoinHandle<()>> {
    thread::Builder::new()
        .name("pi-host-stdin".into())
        .spawn(move || {
            let stdin = io::stdin();
            let mut reader = StdBufReader::new(stdin.lock());
            let mut line = String::new();

            loop {
                let read = (&mut reader)
                    .take(MAX_STDIN_LINE_BYTES + 1)
                    .read_line(&mut line);
                match read {
                    Ok(0) => break,
                    Ok(_) if line.len() as u64 > MAX_STDIN_LINE_BYTES => {
                        // Drain the rest of this NDJSON record so a too-large
                        // replaceMessages cannot kill the control pipe. The
                        // serve loop answers LIMIT_EXCEEDED and keeps running.
                        if !line.ends_with('\n') {
                            let mut discard = [0u8; 8192];
                            loop {
                                match reader.read(&mut discard) {
                                    Ok(0) => break,
                                    Ok(n) if discard[..n].contains(&b'\n') => break,
                                    Ok(_) => {}
                                    Err(error) if error.kind() == io::ErrorKind::Interrupted => {
                                        continue;
                                    }
                                    Err(error) if is_transient_io_error(&error) => {
                                        thread::sleep(Duration::from_millis(10));
                                    }
                                    Err(error) => {
                                        let _ = tx.send(StdinEvent::Error(error.to_string()));
                                        return;
                                    }
                                }
                            }
                        }
                        let id = peek_jsonrpc_id(&line);
                        line.clear();
                        if tx.send(StdinEvent::Oversize { id }).is_err() {
                            break;
                        }
                    }

                    Ok(_) => {
                        if tx
                            .send(StdinEvent::Line(std::mem::take(&mut line)))
                            .is_err()
                        {
                            break;
                        }
                    }
                    Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
                    Err(error) if is_transient_io_error(&error) => {
                        thread::sleep(Duration::from_millis(10));
                    }
                    Err(error) => {
                        let _ = tx.send(StdinEvent::Error(error.to_string()));
                        break;
                    }
                }
            }
        })
}

fn write_stdout_message(writer: &mut impl Write, message: &str) -> io::Result<()> {
    let bytes = message.as_bytes();
    let mut offset = 0;

    while offset < bytes.len() {
        match writer.write(&bytes[offset..]) {
            Ok(0) => {
                return Err(io::Error::new(
                    io::ErrorKind::WriteZero,
                    "stdout writer made no progress",
                ));
            }
            Ok(written) => offset += written,
            Err(error) if is_transient_io_error(&error) => {
                thread::sleep(Duration::from_millis(10));
            }
            Err(error) => return Err(error),
        }
    }

    loop {
        match writer.flush() {
            Ok(()) => return Ok(()),
            Err(error) if is_transient_io_error(&error) => {
                thread::sleep(Duration::from_millis(10));
            }
            Err(error) => return Err(error),
        }
    }
}

fn spawn_stdout_writer(
    mut rx: mpsc::UnboundedReceiver<String>,
    done_tx: oneshot::Sender<Option<String>>,
) -> io::Result<thread::JoinHandle<()>> {
    thread::Builder::new()
        .name("pi-host-stdout".into())
        .spawn(move || {
            let stdout = io::stdout();
            let mut writer = stdout.lock();
            let mut writer_error = None;

            while let Some(message) = rx.blocking_recv() {
                if let Err(error) = write_stdout_message(&mut writer, &message) {
                    writer_error = Some(error.to_string());
                    break;
                }
            }

            let _ = done_tx.send(writer_error);
        })
}

pub async fn serve(state: Arc<Mutex<AppState>>) -> Result<()> {
    let (tx, rx) = mpsc::unbounded_channel::<String>();
    // Keep request tasks bounded as well as tool executions. Tool calls have
    // their own class/session budgets below; this cap protects the host from
    // non-tool RPC bursts and prevents an unbounded tokio task fan-out.
    const MAX_IN_FLIGHT_RPC: usize = 32;
    let request_slots = Arc::new(Semaphore::new(MAX_IN_FLIGHT_RPC));
    let mut request_tasks = tokio::task::JoinSet::new();

    // Keep stdio off Tokio's blocking pool. Under process/thread pressure,
    // Tokio's stdio adapter can panic while trying to create a worker thread;
    // these two dedicated threads instead report startup errors or stop on a
    // closed pipe without taking down the async request dispatcher.
    let (writer_done_tx, mut writer_done_rx) = oneshot::channel::<Option<String>>();
    let _writer = spawn_stdout_writer(rx, writer_done_tx)
        .map_err(|error| anyhow!("host stdout writer unavailable: {error}"))?;
    // Electron's RegisterHotKey cannot claim Windows' Alt+Space system-menu
    // chord. Keep the native fallback beside the host transport so it remains
    // active even when PI-Desktop is unfocused.
    crate::keyboard::start(tx.clone());
    // Fan background-task state changes out to the renderer. The supervisors
    // bump a static counter (no AppState lock involved); this loop watches it
    // and emits `backgroundTasks.changed` so the composer bar stays current.
    let background_change_task = {
        let tx = tx.clone();
        tokio::spawn(async move {
            let mut seen = background_tasks::change_counter();
            loop {
                tokio::time::sleep(std::time::Duration::from_millis(250)).await;
                let current = background_tasks::change_counter();
                if current != seen {
                    seen = current;
                    send_notification(
                        &tx,
                        "backgroundTasks.changed",
                        json!({ "version": current }),
                    );
                }
            }
        })
    };
    let (input_tx, mut input_rx) = mpsc::unbounded_channel::<StdinEvent>();
    let _stdin_reader = match spawn_stdin_reader(input_tx) {
        Ok(handle) => handle,
        Err(error) => {
            drop(tx);
            let _ = writer_done_rx.await;
            return Err(anyhow!("host stdin reader unavailable: {error}"));
        }
    };
    let config_sync_scheduler = tokio::spawn({
        let state = state.clone();
        let tx = tx.clone();
        async move {
            // The host owns a short local debounce clock; remote polling is
            // gated inside the engine to five minutes when no local change is
            // pending. This lets a quiet app settle filesystem edits without
            // turning every tick into a WebDAV request.
            let mut interval = tokio::time::interval(Duration::from_secs(30));
            interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
            loop {
                interval.tick().await;
                let _ =
                    crate::config_sync::engine::sync_if_enabled(state.clone(), tx.clone()).await;
            }
        }
    });

    let mut input_error = None;
    let mut writer_done = false;
    'serve: loop {
        tokio::select! {
            event = input_rx.recv() => {
                let Some(event) = event else {
                    break 'serve;
                };
                let line = match event {
                    StdinEvent::Line(line) => line,
                    StdinEvent::Oversize { id } => {
                        let response = JsonRpcResponse {
                            jsonrpc: "2.0",
                            id,
                            result: None,
                            error: Some(rpc_err(
                                1002,
                                "request line exceeds 64 MiB",
                                "LIMIT_EXCEEDED",
                            )),
                        };
                        if let Ok(raw) = serde_json::to_string(&response) {
                            let _ = tx.send(format!("{raw}\n"));
                        }
                        continue 'serve;
                    }
                    StdinEvent::Error(error) => {
                        input_error = Some(format!("host stdin read failed: {error}"));
                        break 'serve;
                    }
                };

                let trimmed = line.trim();
                if trimmed.is_empty() {
                    continue 'serve;
                }

                let req: JsonRpcRequest = match serde_json::from_str(trimmed) {
                    Ok(r) => r,
                    Err(e) => {
                        let resp = JsonRpcResponse {
                            jsonrpc: "2.0",
                            id: Value::Null,
                            result: None,
                            error: Some(JsonRpcError {
                                code: -32700,
                                message: format!("parse error: {e}"),
                                data: None,
                            }),
                        };
                        let _ = tx.send(format!("{}\n", serde_json::to_string(&resp)?));
                        continue 'serve;
                    }
                };

                if req.id.is_none() {
                    continue 'serve;
                }

                let id = req.id.clone().unwrap_or(Value::Null);
                let method = req.method.clone();
                let params = req.params.unwrap_or(json!({}));
                let state = state.clone();
                let tx = tx.clone();
                let permit = match request_slots.clone().try_acquire_owned() {
                    Ok(permit) => permit,
                    Err(_) => {
                        let response = JsonRpcResponse {
                            jsonrpc: "2.0",
                            id,
                            result: None,
                            error: Some(rpc_err(
                                -32029,
                                "host RPC capacity is exhausted",
                                "HOST_OVERLOADED",
                            )),
                        };
                        if let Ok(raw) = serde_json::to_string(&response) {
                            let _ = tx.send(format!("{raw}\n"));
                        }
                        continue 'serve;
                    }
                };

                request_tasks.spawn(async move {
                    let _permit = permit;
                    let budget = request_budget_ms(&method, &params);
                    // Deferred checkpoint writes are committed after the
                    // handler releases the state lock and before the response
                    // leaves. Transcript appends are synced inside their write
                    // path before derived SQLite rows are committed.
                    let (handled, committed) = transcripts::commit_writes_of(
                        with_request_budget(
                            budget,
                            handle_request(state, &method, params, tx.clone()),
                        ),
                    )
                    .await;
                    let out = response_for(id, handled, committed);
                    if let Ok(raw) = serde_json::to_string(&out) {
                        let _ = tx.send(format!("{raw}\n"));
                    }
                });
            }
            result = &mut writer_done_rx => {
                writer_done = true;
                input_error = match result {
                    Ok(Some(error)) => Some(format!("host stdout write failed: {error}")),
                    Ok(None) => Some("host stdout writer stopped".to_string()),
                    Err(_) => Some("host stdout writer status unavailable".to_string()),
                };
                break 'serve;
            }
            completed = request_tasks.join_next(), if !request_tasks.is_empty() => {
                if let Some(Err(error)) = completed {
                    tracing::warn!(error = %error, "RPC request task failed");
                }
            }
        }
    }

    config_sync_scheduler.abort();
    let _ = config_sync_scheduler.await;
    background_change_task.abort();
    let _ = background_change_task.await;
    {
        let mut st = state.lock().await;
        st.shutdown();
    }
    while let Some(result) = request_tasks.join_next().await {
        if let Err(error) = result {
            tracing::warn!(error = %error, "RPC request task failed during shutdown");
        }
    }
    drop(tx);
    if !writer_done {
        input_error = match tokio::time::timeout(STDOUT_WRITER_SHUTDOWN, writer_done_rx).await {
            Ok(Ok(Some(error))) => Some(format!("host stdout write failed: {error}")),
            Ok(Ok(None)) => input_error,
            Ok(Err(_)) => Some("host stdout writer status unavailable".to_string()),
            Err(_) => {
                tracing::warn!("host stdout writer did not stop after stdin closed");
                input_error.or_else(|| {
                    Some("host stdout writer did not stop after stdin closed".to_string())
                })
            }
        };
    }
    input_error
        .map(|error| Err(anyhow!("{error}")))
        .unwrap_or(Ok(()))
}

/// Wall-clock budget for ordinary non-tool RPC requests. The long-running
/// `configSync.syncNow` is explicitly exempt below; other handlers stuck on the
/// global state lock must release their in-flight slot rather than accumulate.
/// Keep this slightly beyond the shared 130s client deadline (issue #1071).
const RPC_REQUEST_BUDGET_MS: u64 = 135_000;

/// Grace window added on top of a tool's own effective timeout. A
/// `tools.execute` may legitimately run for hours (Bash allows up to 6h), so
/// its budget is derived from the tool timeout rather than the fixed budget;
/// the grace covers host-side bookkeeping around the actual execution.
const RPC_TOOL_BUDGET_GRACE_MS: u64 = 90_000;

/// Cap added to the `tools.execute` budget for the permission prompt. Before
/// the tool runs, the handler may legitimately wait for the user to answer an
/// ask prompt for tens of seconds — that wait must not eat the tool's own
/// execution budget, or "slow approval + full-length Bash" would be killed
/// mid-execution. Unattended callers reject at their own ask budget (~120s),
/// so the cap matches that order.
const RPC_PERMISSION_WAIT_CAP_MS: u64 = 120_000;

/// Budget for one request. `configSync.syncNow` has no aggregate wall-clock
/// deadline because the Host owns a multi-step cloud operation. `tools.execute`
/// follows its own effective tool timeout (plus permission cap and grace); all
/// other methods use the fixed budget.
fn request_budget_ms(method: &str, params: &Value) -> Option<u64> {
    if method == "configSync.syncNow" {
        // One sync may contain arbitrarily many individually bounded S3
        // requests. Keep the Host-owned workflow alive across renderer routes.
        return None;
    }
    if !matches!(method, "tools.execute" | "tools.workspaceExecute") {
        return Some(RPC_REQUEST_BUDGET_MS);
    }
    // A background Bash call returns as soon as the process is spawned; the
    // task lives in the registry, not in this request. The sidecar relay must
    // not budget it like a foreground execution or the turn's abort path
    // would race the spawn.
    let run_in_background = params
        .get("runInBackground")
        .or_else(|| params.get("run_in_background"))
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    if run_in_background {
        return Some(RPC_REQUEST_BUDGET_MS + RPC_TOOL_BUDGET_GRACE_MS);
    }
    // `ToolsExecuteParams` is `#[serde(rename_all = "camelCase")]`, so the wire
    // carries `toolName` / `timeoutMs`. Reading the snake_case spellings here
    // would see an empty tool name and no timeout on every real request,
    // leaving tools.execute unbounded again (review on #1208). Accept the
    // snake_case spelling as a fallback so the helper stays honest about both
    // shapes.
    let tool_name = params
        .get("toolName")
        .or_else(|| params.get("tool_name"))
        .and_then(|v| v.as_str())
        .unwrap_or("");
    let timeout_ms = params
        .get("timeoutMs")
        .or_else(|| params.get("timeout_ms"))
        .and_then(|v| v.as_u64());
    crate::tools::effective_timeout_ms(tool_name, timeout_ms).map(|timeout| {
        timeout
            .saturating_add(RPC_PERMISSION_WAIT_CAP_MS)
            .saturating_add(RPC_TOOL_BUDGET_GRACE_MS)
    })
}

/// Wrap one request's handler future in its wall-clock budget (issue #1071).
///
/// The timeout can only fire at an `await` point, so a handler stuck inside a
/// long *synchronous* call is not interrupted — that class needs the sync work
/// moved off the async workers instead. What this does guarantee is that a
/// handler waiting on the global state lock (the dominant queueing case) is
/// cut loose with its slot, and that one wedged request can no longer hold
/// every other caller forever: each waiting request fails with its own
/// `HOST_RPC_TIMEOUT` instead of piling up until `HOST_OVERLOADED`.
async fn with_request_budget<F>(budget: Option<u64>, fut: F) -> Result<Value, JsonRpcError>
where
    F: std::future::Future<Output = Result<Value, JsonRpcError>>,
{
    let Some(budget) = budget else {
        return fut.await;
    };
    match tokio::time::timeout(Duration::from_millis(budget), fut).await {
        Ok(result) => result,
        Err(_) => {
            tracing::warn!(
                budget_ms = budget,
                "rpc request exceeded its wall-clock budget; slot released"
            );
            Err(JsonRpcError {
                code: -32030,
                message: format!("host rpc budget of {budget}ms exceeded"),
                data: Some(json!({ "errorCode": "HOST_RPC_TIMEOUT" })),
            })
        }
    }
}

fn rpc_err(code: i64, message: impl Into<String>, error_code: &str) -> JsonRpcError {
    JsonRpcError {
        code,
        message: message.into(),
        data: Some(json!({ "errorCode": error_code })),
    }
}

/// The response for one handled request, given the handler's own outcome and
/// the outcome of committing deferred checkpoint writes.
///
/// Transcript append failures reach the client directly from the handler,
/// before the SQLite index update. A deferred checkpoint failure is returned
/// here. If the handler already failed, its error remains the response and the
/// checkpoint failure is logged because a response carries one error.
fn response_for(
    id: Value,
    handled: Result<Value, JsonRpcError>,
    committed: anyhow::Result<()>,
) -> JsonRpcResponse {
    let error = match (handled, committed) {
        (Ok(result), Ok(())) => {
            return JsonRpcResponse {
                jsonrpc: "2.0",
                id,
                result: Some(result),
                error: None,
            }
        }
        (Ok(_), Err(device)) => rpc_err(1000, device.to_string(), "INTERNAL"),
        (Err(error), Ok(())) => error,
        (Err(error), Err(device)) => {
            tracing::error!(
                error = %device,
                "transcript device flush failed behind a request that failed anyway"
            );
            error
        }
    };
    JsonRpcResponse {
        jsonrpc: "2.0",
        id,
        result: None,
        error: Some(error),
    }
}

fn config_sync_rpc_err(error: impl ToString) -> JsonRpcError {
    let message = error.to_string();
    let error_code = message
        .split_once(':')
        .map(|(code, _)| code.trim())
        .unwrap_or("INTERNAL")
        .to_string();
    let code = match error_code.as_str() {
        "CONFIG_SYNC_INVALID" | "CONFIG_SYNC_LIMIT_EXCEEDED" => 1002,
        "CONFIG_SYNC_LOCKED" => 1001,
        "CONFIG_SYNC_CONFLICT" => 1008,
        "CONFIG_SYNC_UNSUPPORTED" => 1002,
        "CONFIG_SYNC_SECURITY" => 1003,
        "CONFIG_SYNC_CRYPTO" | "CONFIG_SYNC_MAPPING_REQUIRED" => 1002,
        "CONFIG_SYNC_REMOTE" => 1000,
        _ => 1000,
    };
    rpc_err(code, message, &error_code)
}

fn provider_rpc_err(error: impl ToString) -> JsonRpcError {
    let message = error.to_string();
    for error_code in ["MODEL_ALIAS_TOO_LONG", "MODEL_BINDINGS_DEGRADED"] {
        if message.starts_with(&format!("{error_code}:")) {
            return rpc_err(1002, message, error_code);
        }
    }
    rpc_err(1000, message, "INTERNAL")
}

fn session_collaboration_rpc_err(error: impl ToString) -> JsonRpcError {
    let message = error.to_string();
    let code = message.split(':').next().unwrap_or("INTERNAL").trim();
    let rpc_code = match code {
        "INVALID_ARGUMENT" | "INVALID_PARAMS" | "LIMIT_EXCEEDED" => 1002,
        "PERMISSION_DENIED" => 1003,
        "NOT_FOUND" => 1007,
        "CONFLICT" | "IDEMPOTENCY_CONFLICT" | "AGENT_BUSY" => 1008,
        _ => return rpc_err(1000, message, "INTERNAL"),
    };
    rpc_err(rpc_code, message.clone(), code)
}

fn plugin_session_rpc_err(error: impl ToString) -> JsonRpcError {
    let message = error.to_string();
    let code = message
        .split_once(':')
        .map(|(code, _)| code.to_string())
        .unwrap_or_else(|| "INTERNAL".to_string());
    let rpc_code = match code.as_str() {
        "INVALID_PARAMS" | "LIMIT_EXCEEDED" => 1002,
        "PERMISSION_DENIED" => 1003,
        "NOT_FOUND" => 1007,
        "CONFLICT" | "TURN_RUNNING" => 1008,
        "RATE_LIMITED" => 1006,
        _ => 1000,
    };
    rpc_err(rpc_code, message, &code)
}

/// Every `plugin.session.*` arm needs the calling plugin; Electron main is the
/// only caller that can supply it (ADR 0200).
fn plugin_session_plugin_id(params: &Value) -> Result<&str, JsonRpcError> {
    params
        .get("pluginId")
        .and_then(Value::as_str)
        .ok_or_else(|| rpc_err(1002, "pluginId required", "INVALID_PARAMS"))
}

/// The access scope Electron main resolved from the plugin's grants (ADR 0339).
/// Host-core holds no permission data, so it enforces exactly what it is handed.
fn plugin_session_scope(params: &Value) -> Result<plugin_sessions::SessionScope, JsonRpcError> {
    plugin_sessions::SessionScope::from_params(params).map_err(plugin_session_rpc_err)
}

/// Optional session `/fast` switch (ADR 0334). Absent or null leaves the
/// stored value; anything but a boolean is rejected rather than coerced.
fn fast_mode_param(params: &Value) -> Result<Option<bool>, JsonRpcError> {
    match params.get("fastMode") {
        None | Some(Value::Null) => Ok(None),
        Some(Value::Bool(value)) => Ok(Some(*value)),
        Some(_) => Err(rpc_err(
            1002,
            "fastMode must be a boolean",
            "INVALID_PARAMS",
        )),
    }
}

/// Parse the optional session thinking selector at the RPC boundary.  A
/// missing/null value keeps the backwards-compatible default; present values
/// must be strings from the host's allowlist rather than being silently
/// coerced to `off`.
fn thinking_level_param(params: &Value) -> Result<Option<String>, JsonRpcError> {
    let Some(value) = params.get("thinkingLevel") else {
        return Ok(None);
    };
    if value.is_null() {
        return Ok(None);
    }
    let Some(level) = value.as_str() else {
        return Err(rpc_err(
            1002,
            "thinkingLevel must be a string",
            "INVALID_PARAMS",
        ));
    };
    if !sessions::is_valid_thinking_level(level) {
        return Err(rpc_err(
            1002,
            format!(
                "thinkingLevel must be one of {}",
                sessions::THINKING_LEVELS.join(", ")
            ),
            "INVALID_PARAMS",
        ));
    }
    Ok(Some(level.to_string()))
}

/// Parse the optional parent session used for permission inheritance. The
/// caller supplies an existing session id, never an arbitrary permission mode;
/// the host resolves the persisted mode while holding its state lock.
fn permission_parent_param(params: &Value) -> Result<Option<String>, JsonRpcError> {
    let Some(value) = params.get("inheritPermissionFromSessionId") else {
        return Ok(None);
    };
    if value.is_null() {
        return Ok(None);
    }
    let Some(parent_id) = value.as_str() else {
        return Err(rpc_err(
            1002,
            "inheritPermissionFromSessionId must be a string",
            "INVALID_PARAMS",
        ));
    };
    if parent_id.trim().is_empty() {
        return Err(rpc_err(
            1002,
            "inheritPermissionFromSessionId must not be empty",
            "INVALID_PARAMS",
        ));
    }
    Ok(Some(parent_id.to_string()))
}

/// Drop the per-session files and caches that live outside SQLite. Shared by
/// `session.delete` and `projects.remove` so removing a project cleans up
/// exactly the same side data as deleting one session.
///
/// Background tasks belong here too: a deleted session must not leave its
/// servers and watchers running, and this is the one place every deletion path
/// already goes through. The stop is a signal only — the supervisor kills and
/// reaps — so deletion neither blocks on a task settling nor fails with it.
fn drop_session_side_data(st: &AppState, id: &str) {
    st.background_tasks.stop_session_running(id);
    scratch::remove_session_dir(&st.data_dir, id);
    visualizations::remove_session_dir(&st.data_dir, id);
    review::remove_session(&st.data_dir, id);
    st.hashline.drop_session(id);
}

const DEFAULT_LARGE_PASTE_THRESHOLD: i64 = 600;
const MIN_LARGE_PASTE_THRESHOLD: i64 = 1;
const MAX_LARGE_PASTE_THRESHOLD: i64 = 1_000_000;
/// Upper bound for a legacy prompt-enhancement template, in characters. The
/// setting remains validated while older profiles and config-sync backups can
/// still contain it for the optional plugin's one-time migration.
const MAX_PROMPT_ENHANCEMENT_TEMPLATE_CHARS: usize = 8000;
/// The placeholder a usable user template must carry.
const PROMPT_ENHANCEMENT_DRAFT_VARIABLE: &str = "{{draft}}";

/// A template override is either absent, blank (meaning "use the default"), or
/// a non-blank string within the length bound; a user template must also carry
/// the draft variable, or the draft never reaches the model.
fn prompt_enhancement_template_error(field: &str, value: &Value) -> Option<String> {
    let Some(text) = value.as_str() else {
        return Some(format!("{field} must be a string"));
    };
    if text.trim().is_empty() {
        return None;
    }
    if text.chars().count() > MAX_PROMPT_ENHANCEMENT_TEMPLATE_CHARS {
        return Some(format!(
            "{field} must not exceed {MAX_PROMPT_ENHANCEMENT_TEMPLATE_CHARS} characters"
        ));
    }
    if field == "promptEnhancementUserTemplate" && !text.contains(PROMPT_ENHANCEMENT_DRAFT_VARIABLE)
    {
        return Some(format!(
            "promptEnhancementUserTemplate must contain {PROMPT_ENHANCEMENT_DRAFT_VARIABLE}"
        ));
    }
    None
}

fn normalize_settings_value(mut value: Value) -> Value {
    if let Some(object) = value.as_object_mut() {
        object.remove("planApprovalPermissionMode");
        if object.get("defaultMode").and_then(Value::as_str) == Some("chat") {
            object.insert("defaultMode".into(), Value::String("plan".into()));
        }
        let valid_command_shell = object
            .get("defaultCommandShell")
            .and_then(Value::as_str)
            .is_some_and(tools::shell::is_known_shell_id);
        if !valid_command_shell {
            object.insert(
                "defaultCommandShell".into(),
                Value::String(tools::shell::default_shell_id().into()),
            );
        }
        let valid_large_paste_threshold = object
            .get("largePasteThreshold")
            .and_then(Value::as_i64)
            .is_some_and(|threshold| {
                (MIN_LARGE_PASTE_THRESHOLD..=MAX_LARGE_PASTE_THRESHOLD).contains(&threshold)
            });
        if !valid_large_paste_threshold {
            object.insert(
                "largePasteThreshold".into(),
                Value::Number(DEFAULT_LARGE_PASTE_THRESHOLD.into()),
            );
        }
        // The network policy replaced three per-feature switches. A section that
        // is present is written back in the shape
        // `packages/shared/src/network-policy.ts` defines: a usable `mode`, plus
        // the one-time notice flag when it is set. Anything unusable falls back
        // to the documented default, `relaxed`; the plaintext flag of a build
        // before the mode existed survives as `strict`, because its `false` was
        // the user's own answer.
        let stored_policy = object
            .get("networkPolicy")
            .filter(|value| !value.is_null())
            .cloned();
        if let Some(stored_policy) = stored_policy {
            let policy = stored_policy.as_object().cloned().unwrap_or_default();
            let mode = match policy.get("mode").and_then(Value::as_str) {
                Some("relaxed") => "relaxed",
                Some("strict") => "strict",
                _ => {
                    if policy.get("allowInsecureUserEndpoints") == Some(&Value::Bool(false)) {
                        "strict"
                    } else {
                        "relaxed"
                    }
                }
            };
            let mut next = serde_json::Map::new();
            next.insert("mode".into(), Value::String(mode.into()));
            if policy.get("insecureNoticeAcknowledged") == Some(&Value::Bool(true)) {
                next.insert("insecureNoticeAcknowledged".into(), Value::Bool(true));
            }
            object.insert("networkPolicy".into(), Value::Object(next));
        }
        // A blank override means "use the built-in default", and an unusable
        // one (wrong type, oversized, or a user template without the draft
        // variable) falls back to the default too, rather than leaving a
        // prompt that would silently drop the user's draft.
        // The system prompt is part of the feature contract, not a preference:
        // an override written by an older build is dropped so the store cannot
        // hold a value that would never be read.
        object.remove("promptEnhancementSystemPrompt");
        let template_field = "promptEnhancementUserTemplate";
        let unusable_template = match object.get(template_field) {
            None => false,
            Some(value) => match prompt_enhancement_template_error(template_field, value) {
                Some(_) => true,
                None => value.as_str().is_some_and(|text| text.trim().is_empty()),
            },
        };
        if unusable_template {
            object.remove(template_field);
        }
    }
    value
}

fn merge_settings_value(stored: Option<Value>, incoming: Value) -> Value {
    let Value::Object(incoming) = incoming else {
        return incoming;
    };
    let mut merged = match stored {
        Some(Value::Object(object)) => object,
        _ => serde_json::Map::new(),
    };
    merged.extend(incoming);
    Value::Object(merged)
}

/// Drop image-generation bindings whose provider row is gone.
///
/// `settings.set` merges into the stored object and the shell writes whole
/// snapshots back, so deleting a provider row used to leave `imageGeneration`
/// naming an id that no longer resolves. Every `GenerateImages` call then
/// answered `IMAGE_MODEL_UNAVAILABLE`, and once the candidate list was empty
/// the settings row that owns the default hid itself, so the binding could
/// neither run nor be repaired from the UI. A binding that cannot resolve is
/// therefore not a preference the store keeps: the active default falls back
/// to "no default" and the candidate list loses that entry, on read and on
/// write alike. A provider that still exists but is disabled or carries no
/// credential keeps its binding — that is a state the user repairs in
/// Settings, and no reference to it is dropped here.
///
/// The same rule config sync already enforces when it applies a bundle
/// (`validate_application_references`), applied to the local settings channel
/// so a stale id cannot be written into or read out of the store.
fn prune_unresolvable_image_bindings(
    db: &crate::db::Database,
    settings: &mut Value,
) -> Result<bool> {
    let Some(object) = settings.as_object_mut() else {
        return Ok(false);
    };
    let resolves = |binding: &Value| -> Result<bool> {
        match binding.get("providerId").and_then(Value::as_str) {
            Some(provider_id) => providers::provider_exists(db, provider_id),
            None => Ok(false),
        }
    };
    let mut changed = false;
    let active_is_stale = match object.get("imageGeneration") {
        Some(binding) if !binding.is_null() => !resolves(binding)?,
        _ => false,
    };
    if active_is_stale {
        object.insert("imageGeneration".into(), Value::Null);
        changed = true;
    }
    if let Some(Value::Array(candidates)) = object.get("imageGenerationModels").cloned() {
        let mut kept = Vec::with_capacity(candidates.len());
        let mut dropped = false;
        for candidate in candidates {
            if resolves(&candidate)? {
                kept.push(candidate);
            } else {
                dropped = true;
            }
        }
        if dropped {
            object.insert("imageGenerationModels".into(), Value::Array(kept));
            changed = true;
        }
    }
    Ok(changed)
}

fn effective_command_shell_id(settings: Option<&Value>) -> Option<String> {
    let configured = settings
        .and_then(|value| value.get("defaultCommandShell"))
        .and_then(Value::as_str);
    tools::shell::catalog(configured)
        .effective
        .map(|shell| shell.id)
}

fn validate_settings_value(value: &Value) -> Result<(), JsonRpcError> {
    let Some(object) = value.as_object() else {
        return Ok(());
    };
    if object
        .get("backgroundJobContinuationEnabled")
        .is_some_and(|value| !value.is_boolean())
    {
        return Err(rpc_err(
            1002,
            "backgroundJobContinuationEnabled must be a boolean",
            "INVALID_PARAMS",
        ));
    }
    if object
        .get("scheduledTasksEnabled")
        .is_some_and(|enabled| !enabled.is_boolean())
    {
        return Err(rpc_err(
            1002,
            "scheduledTasksEnabled must be a boolean",
            "INVALID_PARAMS",
        ));
    }
    if let Some(policy) = object.get("networkPolicy").filter(|v| !v.is_null()) {
        let Some(policy) = policy.as_object() else {
            return Err(rpc_err(
                1002,
                "networkPolicy must be an object",
                "INVALID_PARAMS",
            ));
        };
        if policy
            .get("mode")
            .is_some_and(|mode| !matches!(mode.as_str(), Some("relaxed") | Some("strict")))
        {
            return Err(rpc_err(
                1002,
                "networkPolicy.mode must be relaxed or strict",
                "INVALID_PARAMS",
            ));
        }
        if policy
            .get("insecureNoticeAcknowledged")
            .is_some_and(|flag| !flag.is_boolean())
        {
            return Err(rpc_err(
                1002,
                "insecureNoticeAcknowledged must be a boolean",
                "INVALID_PARAMS",
            ));
        }
    }
    if let Some(binding) = object.get("imageGeneration").filter(|v| !v.is_null()) {
        for (key, max) in [("providerId", 128), ("modelId", 256)] {
            if !binding
                .get(key)
                .and_then(Value::as_str)
                .is_some_and(|s| !s.trim().is_empty() && s.len() <= max)
            {
                return Err(rpc_err(
                    1002,
                    "invalid image generation binding",
                    "INVALID_PARAMS",
                ));
            }
        }
    }
    if let Some(candidates) = object.get("imageGenerationModels").filter(|v| !v.is_null()) {
        let Some(candidates) = candidates.as_array() else {
            return Err(rpc_err(
                1002,
                "imageGenerationModels must be an array",
                "INVALID_PARAMS",
            ));
        };
        if candidates.len() > 128 {
            return Err(rpc_err(
                1002,
                "imageGenerationModels contains too many models",
                "INVALID_PARAMS",
            ));
        }
        for binding in candidates {
            for (key, max) in [("providerId", 128), ("modelId", 256)] {
                if !binding
                    .get(key)
                    .and_then(Value::as_str)
                    .is_some_and(|s| !s.trim().is_empty() && s.len() <= max)
                {
                    return Err(rpc_err(
                        1002,
                        "invalid image generation candidate",
                        "INVALID_PARAMS",
                    ));
                }
            }
        }
    }
    if let Some(template_value) = object.get("promptEnhancementUserTemplate") {
        if let Some(message) =
            prompt_enhancement_template_error("promptEnhancementUserTemplate", template_value)
        {
            return Err(rpc_err(1002, message, "INVALID_PARAMS"));
        }
    }
    if let Some(preference) = object.get("updatePreference") {
        if !matches!(preference.as_str(), Some("automatic") | Some("manual")) {
            return Err(rpc_err(
                1002,
                "updatePreference must be automatic or manual",
                "INVALID_PARAMS",
            ));
        }
    }
    if let Some(version) = object.get("lastNotifiedUpdateVersion") {
        let Some(version) = version.as_str() else {
            return Err(rpc_err(
                1002,
                "lastNotifiedUpdateVersion must be a non-empty string",
                "INVALID_PARAMS",
            ));
        };
        if version.trim().is_empty() || version.len() > 128 {
            return Err(rpc_err(
                1002,
                "lastNotifiedUpdateVersion must contain 1 to 128 characters",
                "INVALID_PARAMS",
            ));
        }
    }
    if let Some(version) = object.get("updateDismissedVersion") {
        match version {
            serde_json::Value::Null => {}
            serde_json::Value::String(version) => {
                if version.trim().is_empty() || version.len() > 128 {
                    return Err(rpc_err(
                        1002,
                        "updateDismissedVersion must contain 1 to 128 characters",
                        "INVALID_PARAMS",
                    ));
                }
            }
            _ => {
                return Err(rpc_err(
                    1002,
                    "updateDismissedVersion must be a string or null",
                    "INVALID_PARAMS",
                ));
            }
        }
    }
    if let Some(infinite_retry) = object.get("infiniteProviderRetry") {
        if !infinite_retry.is_boolean() {
            return Err(rpc_err(
                1002,
                "infiniteProviderRetry must be a boolean",
                "INVALID_PARAMS",
            ));
        }
    }
    if let Some(keep_awake) = object.get("keepAwakeWhileRunning") {
        if !keep_awake.is_boolean() {
            return Err(rpc_err(
                1002,
                "keepAwakeWhileRunning must be a boolean",
                "INVALID_PARAMS",
            ));
        }
    }
    if let Some(threshold_value) = object.get("largePasteThreshold") {
        let Some(threshold) = threshold_value.as_i64() else {
            return Err(rpc_err(
                1002,
                "largePasteThreshold must be an integer",
                "INVALID_PARAMS",
            ));
        };
        if !(MIN_LARGE_PASTE_THRESHOLD..=MAX_LARGE_PASTE_THRESHOLD).contains(&threshold) {
            return Err(rpc_err(
                1002,
                format!(
                    "largePasteThreshold must be between {MIN_LARGE_PASTE_THRESHOLD} and {MAX_LARGE_PASTE_THRESHOLD}"
                ),
                "INVALID_PARAMS",
            ));
        }
    }
    if let Err(message) = crate::network_proxy::validate_network_proxy(value) {
        return Err(rpc_err(1002, message, "INVALID_PARAMS"));
    }
    let Some(shell_value) = object.get("defaultCommandShell") else {
        return Ok(());
    };
    let Some(shell_id) = shell_value.as_str() else {
        return Err(rpc_err(
            1002,
            "defaultCommandShell must be a supported command shell ID",
            "COMMAND_SHELL_INVALID",
        ));
    };
    if !tools::shell::is_known_shell_id(shell_id) {
        return Err(rpc_err(
            1002,
            format!("unknown command shell ID '{shell_id}'"),
            "COMMAND_SHELL_INVALID",
        ));
    }
    let catalog = tools::shell::catalog(None);
    if !catalog
        .choices
        .iter()
        .any(|choice| choice.id == shell_id && choice.available)
    {
        return Err(rpc_err(
            1002,
            format!("command shell ID '{shell_id}' is unavailable on this platform"),
            "COMMAND_SHELL_INVALID",
        ));
    }
    Ok(())
}

fn gate_default_command_shell_setting(state: &AppState) -> Result<(), JsonRpcError> {
    plans::expire_pending_approvals(&state.db)
        .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
    let blocked: bool = state
        .db
        .conn()
        .query_row(
            "SELECT EXISTS(
                 SELECT 1 FROM turns WHERE status = 'running'
             ) OR EXISTS(
                 SELECT 1 FROM plan_approvals WHERE status = 'pending'
             ) OR EXISTS(
                 SELECT 1 FROM plan_approvals
                 WHERE execution_state IN ('queued', 'running')
             )",
            [],
            |row| row.get(0),
        )
        .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
    if blocked {
        return Err(rpc_err(
            1008,
            "defaultCommandShell can only change while all sessions are idle",
            "PLAN_CONFIGURATION_BLOCKED",
        ));
    }
    Ok(())
}

fn command_shell_catalog(state: &AppState) -> Result<tools::shell::ShellCatalog, JsonRpcError> {
    let settings = state
        .db
        .get_setting("app")
        .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
        .unwrap_or_else(|| json!({}));
    let configured_id = settings.get("defaultCommandShell").and_then(Value::as_str);
    Ok(tools::shell::catalog(configured_id))
}

fn shell_failure_result(
    p: &ToolsExecuteParams,
    error_code: &str,
    message: impl Into<String>,
    command_shell_id: Option<String>,
    started: std::time::Instant,
) -> tools::ToolsExecuteResult {
    let message = message.into();
    let mut content = json!({ "error": message, "code": error_code });
    if let Some(shell_id) = command_shell_id.as_deref() {
        content["commandShellId"] = json!(shell_id);
    }
    tools::ToolsExecuteResult {
        tool_call_id: p.tool_call_id.clone(),
        ok: false,
        is_error: Some(true),
        content,
        duration_ms: started.elapsed().as_millis() as u64,
        denied: None,
        error_code: Some(error_code.to_string()),
        command_shell_id,
    }
}

fn shell_changed_result(
    p: &ToolsExecuteParams,
    expected_shell_id: &str,
    expected_shell_dialect: Option<&str>,
    current_shell_id: Option<String>,
    current_shell_dialect: Option<&str>,
    started: std::time::Instant,
) -> tools::ToolsExecuteResult {
    let current = current_shell_id
        .clone()
        .unwrap_or_else(|| "none".to_string());
    let mut result = shell_failure_result(
        p,
        "COMMAND_SHELL_CHANGED",
        format!(
            "command shell changed: expected '{expected_shell_id}', current effective shell is '{current}'"
        ),
        current_shell_id,
        started,
    );
    let mut content = json!({
        "error": result.content["error"],
        "code": "COMMAND_SHELL_CHANGED",
        "expectedCommandShellId": expected_shell_id,
        "commandShellId": current,
    });
    if let Some(expected_shell_dialect) = expected_shell_dialect {
        content["expectedCommandShellDialect"] = json!(expected_shell_dialect);
    }
    if let Some(current_shell_dialect) = current_shell_dialect {
        content["commandShellDialect"] = json!(current_shell_dialect);
    }
    result.content = content;
    result
}

fn plan_rpc_err(error: impl ToString) -> JsonRpcError {
    let message = error.to_string();
    let error_code = message
        .split_whitespace()
        .next()
        .filter(|code| code.starts_with("PLAN_"))
        .unwrap_or("PLAN_INTERNAL")
        .to_string();
    rpc_err(1015, message, &error_code)
}

fn resolve_persisted_project_workspace(
    state: &AppState,
    session_id: &str,
) -> Result<Option<String>, JsonRpcError> {
    match sessions::session_summary(&state.db, session_id) {
        Ok(Some(summary)) => {
            if let Some(path) = summary.project_path.as_deref() {
                if state
                    .db
                    .remote_workspace_for_path(path)
                    .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?
                    .is_some()
                {
                    let scratch = scratch::session_dir(&state.data_dir, session_id)
                        .ok_or_else(|| rpc_err(1002, "invalid session id", "INVALID_PARAMS"))?;
                    std::fs::create_dir_all(&scratch)
                        .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
                    return Ok(Some(scratch.to_string_lossy().into_owned()));
                }
            }
            Ok(summary.project_path)
        }
        // A tool request must name a persisted session: an unknown id never
        // inherits the mutable global workspace.
        Ok(None) => Err(rpc_err(1007, "session not found", "SESSION_NOT_FOUND")),
        Err(error) => Err(rpc_err(1000, error.to_string(), "INTERNAL")),
    }
}

fn resolve_tool_workspace(
    state: &AppState,
    session_id: &str,
) -> Result<Option<String>, JsonRpcError> {
    match sessions::session_summary(&state.db, session_id) {
        Ok(Some(summary)) => {
            // An isolated session's root is its worktree and never falls back
            // to the main checkout (ADR 0329).
            match crate::session_worktrees::lifecycle::tool_root(&state.db, session_id) {
                Ok(Some(root)) => return Ok(Some(root.to_string_lossy().into_owned())),
                Ok(None) => {}
                Err(error) => return Err(worktree_rpc::to_rpc(error)),
            }
            if let Some(project_path) = summary.project_path {
                return Ok(Some(project_path));
            }
            let scratch = scratch::session_dir(&state.data_dir, session_id)
                .ok_or_else(|| rpc_err(1000, "temporary session has an invalid id", "INTERNAL"))?;
            std::fs::create_dir_all(&scratch)
                .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?;
            Ok(Some(scratch.to_string_lossy().into_owned()))
        }
        // A tool request must name a persisted session: an unknown id never
        // inherits the mutable global workspace.
        Ok(None) => Err(rpc_err(1007, "session not found", "SESSION_NOT_FOUND")),
        Err(error) => Err(rpc_err(1000, error.to_string(), "INTERNAL")),
    }
}

/// Select a registered logical-project root for an absolute tool path.
///
/// The active workspace remains the session's primary root by default. A path
/// inside another root of the same host-owned project group may use that root
/// as its containment base; arbitrary external paths still follow the normal
/// permission flow and never become group roots implicitly.
fn resolve_tool_workspace_for_call(
    state: &AppState,
    session_id: &str,
    args: &Value,
) -> Result<Option<String>, JsonRpcError> {
    let primary = resolve_tool_workspace(state, session_id)?;
    let Some(primary_path) = primary.as_deref() else {
        return Ok(primary);
    };
    if primary_path.starts_with(crate::db::REMOTE_PROJECT_PREFIX) {
        let remote = state
            .db
            .remote_workspace_for_path(primary_path)
            .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?
            .ok_or_else(|| rpc_err(1002, "remote workspace binding missing", "INVALID_PARAMS"))?;
        return Ok(Some(remote.path));
    }
    let Some(raw_path) = args.get("path").and_then(Value::as_str) else {
        return Ok(primary);
    };
    if !Path::new(raw_path).is_absolute() {
        return Ok(primary);
    }
    let group = state
        .db
        .project_group_for_path(primary_path)
        .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?;
    // Resolve the spelling before containment. macOS can expose the same
    // directory as `/var` and `/private/var`, while the database stores the
    // canonical spelling. Non-existent leaves are still supported by the
    // workspace resolver's existing-ancestor behavior.
    let comparable_path = workspace::resolve_external_path(Path::new(primary_path), raw_path)
        .unwrap_or_else(|_| PathBuf::from(raw_path));
    if let Some(group) = group {
        if let Some(root) = group.roots.iter().find(|root| {
            workspace::lexically_inside(Path::new(&root.path), &comparable_path.to_string_lossy())
        }) {
            return Ok(Some(root.path.clone()));
        }
    }
    Ok(primary)
}

/// Read/search tools are low risk inside their normal roots, but an explicit
/// path outside both roots is a separate capability. The check is deliberately
/// based on the same resolver used for execution so `..` and symlink escapes
/// cannot avoid the permission card. Contained roots (scratch, visualization)
/// are recognized lexically before their lazy directories exist.
fn requires_external_path_permission(
    workspace_path: Option<&str>,
    roots: &ContainedRoots,
    tool_name: &str,
    args: &Value,
) -> bool {
    if !matches!(tool_name, "Read" | "Glob" | "Grep" | "Write" | "Edit") {
        return false;
    }
    let Some(path) = args.get("path").and_then(Value::as_str) else {
        return false;
    };
    if let Some(root) = roots.lexical_root(path) {
        return !root.allows_implicit_access();
    }
    let Some(workspace_path) = workspace_path else {
        return false;
    };
    matches!(
        workspace::resolve_tool_path(Path::new(workspace_path), roots, path),
        Err(error) if error == "PATH_OUTSIDE_WORKSPACE"
    )
}

/// Contained roots of a local session: scratch (D114) then visualization
/// (D671). Remote-workspace sessions get no visualization root.
fn local_contained_roots(data_dir: &Path, session_id: &str, remote: bool) -> ContainedRoots {
    let visualization = if remote {
        None
    } else {
        visualizations::session_dir(data_dir, session_id)
    };
    ContainedRoots::scratch_only(scratch::session_dir(data_dir, session_id).as_deref())
        .with(ToolRoot::Visualization, visualization)
}

/// Whether a Write/Edit lexically targets one of the session's contained roots
/// and may skip the permission prompt. Never for remote workspaces or contract
/// modes (their hard deny is not bypassed).
fn contained_write_auto_allowed(
    remote: bool,
    durable_mode: &str,
    roots: &ContainedRoots,
    tool_name: &str,
    args: &Value,
) -> bool {
    !remote
        && !sessions::is_contract_mode(durable_mode)
        && matches!(tool_name, "Write" | "Edit")
        && args
            .get("path")
            .and_then(Value::as_str)
            .and_then(|path| roots.lexical_root(path))
            .is_some_and(|root| root.allows_implicit_access())
        && edit_move_stays_contained(roots, args)
}

/// An Edit can carry `MV <dest>`; the prompt may be skipped only when that
/// destination is inside a contained root too. Unparseable ops never reach
/// the filesystem, so they do not need a prompt.
fn edit_move_stays_contained(roots: &ContainedRoots, args: &Value) -> bool {
    let Some(ops) = args.get("ops").and_then(Value::as_str) else {
        return true;
    };
    let Ok(parsed) = crate::tools::hashline::parse_ops(ops) else {
        return true;
    };
    crate::tools::hashline::mv_dest(&parsed).is_none_or(|dest| {
        roots
            .lexical_root(dest)
            .is_some_and(|root| root.allows_implicit_access())
    })
}

/// Plans are owned by the session's persisted project. Unlike the legacy
/// tool compatibility resolver, a plan submission never inherits the mutable
/// global workspace or accepts a session-less request.
fn resolve_plan_workspace(state: &AppState, session_id: &str) -> Result<PathBuf, JsonRpcError> {
    match sessions::session_summary(&state.db, session_id) {
        Ok(Some(_)) => {}
        Ok(None) => return Err(plan_rpc_err("PLAN_SESSION_NOT_FOUND")),
        Err(error) => return Err(rpc_err(1000, error.to_string(), "INTERNAL")),
    }
    resolve_persisted_project_workspace(state, session_id)?
        .map(PathBuf::from)
        .ok_or_else(|| plan_rpc_err("PLAN_WORKSPACE_REQUIRED"))
}

fn resolve_plan_workspace_if_available(
    state: &AppState,
    session_id: &str,
) -> Result<Option<PathBuf>, JsonRpcError> {
    match sessions::session_summary(&state.db, session_id) {
        Ok(Some(_)) => {}
        Ok(None) => return Err(plan_rpc_err("PLAN_SESSION_NOT_FOUND")),
        Err(error) => return Err(rpc_err(1000, error.to_string(), "INTERNAL")),
    }
    Ok(resolve_persisted_project_workspace(state, session_id)?.map(PathBuf::from))
}

/// Push one notification line to the caller's stream.
fn send_notification(tx: &mpsc::UnboundedSender<String>, method: &str, params: Value) {
    let note = JsonRpcNotification {
        jsonrpc: "2.0",
        method: method.to_string(),
        params,
    };
    if let Ok(raw) = serde_json::to_string(&note) {
        let _ = tx.send(format!("{raw}\n"));
    }
}

async fn emit_notification(tx: &mpsc::UnboundedSender<String>, method: &str, params: Value) {
    send_notification(tx, method, params);
}

/// Reports install progress to the renderer, and reads the cancel flag.
///
/// Throttled on purpose: an install reports every chunk of bytes it sees, and
/// an interface needs a few of those per second rather than thousands. A phase
/// change and the terminal report always go through, so a dialog never misses
/// the transition it is displaying.
struct RpcInstallObserver {
    tx: mpsc::UnboundedSender<String>,
    cancel: crate::plugins::CancelToken,
    last: Option<std::time::Instant>,
    last_phase: Option<crate::plugins::InstallPhase>,
}

impl crate::plugins::InstallObserver for RpcInstallObserver {
    fn progress(&mut self, event: crate::plugins::InstallProgress) {
        const MIN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(200);
        let phase_changed = self.last_phase != Some(event.phase);
        let terminal = event.error.is_some();
        let due = self
            .last
            .map(|at| at.elapsed() >= MIN_INTERVAL)
            .unwrap_or(true);
        if !phase_changed && !terminal && !due {
            return;
        }
        self.last = Some(std::time::Instant::now());
        self.last_phase = Some(event.phase);
        let tried: Vec<Value> = event
            .tried
            .iter()
            .map(|mirror| {
                json!({
                    "source": mirror.source,
                    "url": mirror.url,
                    "error": mirror.error,
                })
            })
            .collect();
        send_notification(
            &self.tx,
            "plugin.installProgress",
            json!({
                "pluginId": event.plugin_id,
                "version": event.version,
                "phase": event.phase.as_str(),
                "source": event.source,
                "attempt": event.attempt,
                "attempts": event.attempts,
                "receivedBytes": event.received_bytes,
                "totalBytes": event.total_bytes,
                "tried": tried,
                "error": event.error,
            }),
        );
    }

    fn cancelled(&self) -> bool {
        self.cancel.is_cancelled()
    }
}

async fn wait_for_tool_cancellation(
    receiver: &mut Option<tokio::sync::watch::Receiver<bool>>,
) -> bool {
    let Some(receiver) = receiver.as_mut() else {
        return std::future::pending::<bool>().await;
    };
    if *receiver.borrow() {
        return true;
    }
    loop {
        if receiver.changed().await.is_err() {
            return std::future::pending::<bool>().await;
        }
        if *receiver.borrow() {
            return true;
        }
    }
}

fn tool_cancellation_requested(receiver: &Option<tokio::sync::watch::Receiver<bool>>) -> bool {
    receiver.as_ref().is_some_and(|receiver| *receiver.borrow())
}

async fn clear_bash_cancellation(state: &Arc<Mutex<AppState>>, p: &ToolsExecuteParams) {
    let mut st = state.lock().await;
    st.clear_bash_cancellation(&p.session_id, &p.tool_call_id);
}

async fn clear_tool_cancellation(state: &Arc<Mutex<AppState>>, p: &ToolsExecuteParams) {
    let mut st = state.lock().await;
    st.clear_tool_cancellation(&p.session_id, &p.tool_call_id, &p.tool_name);
}

async fn cancel_pending_permission(state: &Arc<Mutex<AppState>>, p: &ToolsExecuteParams) -> bool {
    let mut st = state.lock().await;
    st.cancel_pending_permission(&p.session_id, &p.tool_call_id)
}

fn tool_aborted_result(p: &ToolsExecuteParams, started: Instant) -> tools::ToolsExecuteResult {
    tools::ToolsExecuteResult {
        tool_call_id: p.tool_call_id.clone(),
        ok: false,
        is_error: Some(true),
        content: json!({ "error": "tool aborted", "code": "TOOL_ABORTED" }),
        duration_ms: started.elapsed().as_millis() as u64,
        denied: None,
        error_code: Some("TOOL_ABORTED".into()),
        command_shell_id: p.expected_command_shell_id.clone(),
    }
}

/// Dispatch a `plugin_*` tool to the desktop runner (Electron main), which
/// executes the plugin JS and answers via `plugins.resolveExecution`.
async fn execute_plugin_tool(
    state: &Arc<Mutex<AppState>>,
    tx: &mpsc::UnboundedSender<String>,
    p: &ToolsExecuteParams,
    timeout_ms: u64,
    session_mode: &str,
) -> tools::ToolsExecuteResult {
    let started = std::time::Instant::now();
    let execution_id = uuid::Uuid::new_v4().to_string();
    let (otx, orx) = tokio::sync::oneshot::channel::<Value>();
    {
        let mut st = state.lock().await;
        st.plugin_execs.insert(execution_id.clone(), otx);
    }
    emit_notification(
        tx,
        "plugins.execute",
        json!({
            "executionId": execution_id,
            "sessionId": p.session_id,
            "turnId": p.turn_id,
            "toolCallId": p.tool_call_id,
            "toolName": p.tool_name,
            "args": p.args,
            // Durable session mode, not the sidecar-supplied field: ADR 0052
            // forbids a conflicting sidecar mode from authorizing a tool
            // (ADR 0211).
            "mode": session_mode,
            "planSafeActions": p.plan_safe_actions,
        }),
    )
    .await;

    let outcome = tokio::time::timeout(std::time::Duration::from_millis(timeout_ms), orx).await;
    let duration_ms = started.elapsed().as_millis() as u64;
    match outcome {
        Ok(Ok(resp)) => {
            let ok = resp.get("ok").and_then(|v| v.as_bool()).unwrap_or(false);
            let content = resp.get("content").cloned().unwrap_or(Value::Null);
            let error_code = resp
                .get("errorCode")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string());
            tools::ToolsExecuteResult {
                tool_call_id: p.tool_call_id.clone(),
                ok,
                is_error: if ok { None } else { Some(true) },
                content,
                duration_ms,
                denied: None,
                error_code: if ok {
                    None
                } else {
                    Some(error_code.unwrap_or_else(|| "TOOL_FAILED".into()))
                },
                command_shell_id: None,
            }
        }
        _ => {
            let mut st = state.lock().await;
            st.plugin_execs.remove(&execution_id);
            tools::ToolsExecuteResult {
                tool_call_id: p.tool_call_id.clone(),
                ok: false,
                is_error: Some(true),
                content: json!({
                    "error": "plugin tool dispatch timed out or no desktop runner is attached",
                    "code": "TOOL_TIMEOUT"
                }),
                duration_ms,
                denied: None,
                error_code: Some("TOOL_TIMEOUT".into()),
                command_shell_id: None,
            }
        }
    }
}

fn plugin_err(err: impl ToString) -> JsonRpcError {
    let msg = err.to_string();
    if msg.contains("PLUGIN_INVALID") {
        rpc_err(1009, msg, "PLUGIN_INVALID")
    } else if msg.contains("PLUGIN_LOAD_FAILED") {
        rpc_err(1010, msg, "PLUGIN_LOAD_FAILED")
    } else if msg.contains("PLUGIN_INTEGRITY") {
        rpc_err(1012, msg, "PLUGIN_INTEGRITY")
    } else if msg.contains("PLUGIN_PERMISSION_DENIED") {
        rpc_err(1013, msg, "PLUGIN_PERMISSION_DENIED")
    } else if msg.contains("PLUGIN_NOT_FOUND") {
        rpc_err(1003, msg, "NOT_FOUND")
    } else if msg.contains("PLUGIN_CANCELLED") {
        // The user's own action rather than a failure: the surface closes the
        // dialog quietly instead of reporting an error.
        rpc_err(1019, msg, "PLUGIN_CANCELLED")
    } else if msg.contains("PLUGIN_MARKET_NOT_PUBLISHED") {
        // The platform has the version and is not offering it yet: a state to
        // report, not a bug to sweep into INTERNAL.
        rpc_err(1020, msg, "PLUGIN_MARKET_NOT_PUBLISHED")
    } else if msg.contains("PLUGIN_MARKET_ARCHIVED") {
        rpc_err(1021, msg, "PLUGIN_MARKET_ARCHIVED")
    } else if msg.contains("PLUGIN_MARKET_NOT_FOUND") {
        rpc_err(1022, msg, "PLUGIN_MARKET_NOT_FOUND")
    } else if msg.contains("PLUGIN_MARKET_RATE_LIMITED") {
        rpc_err(1023, msg, "PLUGIN_MARKET_RATE_LIMITED")
    } else if msg.contains("PLUGIN_MARKET_NO_SOURCE") {
        rpc_err(1024, msg, "PLUGIN_MARKET_NO_SOURCE")
    } else if msg.contains("PLUGIN_MARKET_INVALID") {
        // The center answered something this client refuses to render, which
        // is the client's contract violation, not an internal crash.
        rpc_err(1026, msg, "PLUGIN_MARKET_INVALID")
    } else if msg.contains("PLUGIN_NETWORK") {
        rpc_err(1014, msg, "PLUGIN_NETWORK")
    } else {
        rpc_err(1000, msg, "INTERNAL")
    }
}

/// Capability query failures have their own code so callers can distinguish
/// a missing project context from a malformed MCP or skill document.
fn capability_err(message: impl Into<String>) -> JsonRpcError {
    rpc_err(1018, message, "CAPABILITY_INVALID")
}

/// Validation failures from the user-owned MCP registry are the user's typo,
/// not an internal fault, so they get a distinct code the UI can show inline.
fn scope_err(err: impl ToString) -> JsonRpcError {
    let msg = err.to_string();
    if msg.contains("CAPABILITY_INVALID") {
        capability_err(msg)
    } else if msg.contains("MCP_INVALID") {
        rpc_err(1015, msg, "MCP_INVALID")
    } else {
        rpc_err(1000, msg, "INTERNAL")
    }
}

fn skill_err(err: impl ToString) -> JsonRpcError {
    let msg = err.to_string();
    if msg.contains("CAPABILITY_INVALID") {
        capability_err(msg)
    } else if msg.contains("SKILL_INVALID") {
        rpc_err(1016, msg, "SKILL_INVALID")
    } else {
        rpc_err(1000, msg, "INTERNAL")
    }
}

/// Read the create/import/update payload for a user skill. Absent fields stay
/// absent so `update` can distinguish "unchanged" from "cleared".
fn parse_skill_input(params: &Value) -> Result<crate::user_skills::UserSkillInput, JsonRpcError> {
    let raw = params
        .get("skill")
        .cloned()
        .unwrap_or_else(|| params.clone());
    serde_json::from_value(raw).map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))
}

fn subagent_err(err: impl ToString) -> JsonRpcError {
    let msg = err.to_string();
    if msg.contains("SUBAGENT_INVALID") {
        rpc_err(1017, msg, "SUBAGENT_INVALID")
    } else {
        rpc_err(1000, msg, "INTERNAL")
    }
}

/// Read the create/update payload for a user subagent. Absent fields stay absent
/// so `update` can distinguish "unchanged" from "cleared".
fn parse_subagent_input(
    params: &Value,
) -> Result<crate::user_subagents::UserSubagentInput, JsonRpcError> {
    let raw = params
        .get("subagent")
        .cloned()
        .unwrap_or_else(|| params.clone());
    serde_json::from_value(raw).map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))
}

fn require_id(params: &Value) -> Result<String, JsonRpcError> {
    params
        .get("id")
        .and_then(|v| v.as_str())
        .map(str::to_string)
        .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))
}

/// Read an `ActivationScope` from request params, accepting either a nested
/// `scope` object or the flat `mode`/`projects` pair the renderer sends.
fn parse_scope(params: &Value) -> Result<crate::activation::ActivationScope, JsonRpcError> {
    let raw = match params.get("scope") {
        Some(scope) => scope.clone(),
        None => json!({
            "mode": params.get("mode").cloned().unwrap_or(json!("global")),
            "projects": params.get("projects").cloned().unwrap_or(json!([])),
        }),
    };
    serde_json::from_value(raw).map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))
}

fn parse_capability_query(
    params: &Value,
) -> Result<(CapabilityLevel, Option<String>), JsonRpcError> {
    let level = CapabilityLevel::parse(params.get("level").and_then(Value::as_str))
        .map_err(|error| capability_err(error.to_string()))?;
    let project_path = params
        .get("projectPath")
        .and_then(Value::as_str)
        .map(str::to_string)
        .filter(|value| !value.trim().is_empty());
    if level == CapabilityLevel::Project && project_path.is_none() {
        return Err(capability_err(
            "projectPath required for project capability queries",
        ));
    }
    Ok((level, project_path))
}

/// Read one end of a move from a nested `{ level, projectPath }` object.
///
/// A move names two directories at once, so unlike the single-level queries it
/// reads a named key instead of the flat params, and the two ends can never be
/// confused for each other. `level` must be present and a string: defaulting a
/// missing or non-string level to `global` would silently write a capability
/// into the wrong directory, so it is rejected as invalid params instead.
fn parse_capability_target(
    params: &Value,
    key: &str,
) -> Result<crate::agent_capabilities::CapabilityTarget, JsonRpcError> {
    let source = params
        .get(key)
        .ok_or_else(|| rpc_err(1002, format!("{key} required"), "INVALID_PARAMS"))?;
    let level = match source.get("level") {
        Some(Value::String(level)) => CapabilityLevel::parse(Some(level))
            .map_err(|error| capability_err(error.to_string()))?,
        _ => {
            return Err(rpc_err(
                1002,
                format!("{key}.level must be 'global' or 'project'"),
                "INVALID_PARAMS",
            ))
        }
    };
    let project_path = source
        .get("projectPath")
        .and_then(Value::as_str)
        .map(str::to_string)
        .filter(|value| !value.trim().is_empty());
    crate::agent_capabilities::CapabilityTarget::new(level, project_path.as_deref())
        .map_err(|error| capability_err(error.to_string()))
}

async fn handle_request(
    state: Arc<Mutex<AppState>>,
    method: &str,
    params: Value,
    tx: mpsc::UnboundedSender<String>,
) -> Result<Value, JsonRpcError> {
    if method != "app.handshake" {
        let st = state.lock().await;
        if !st.handshook {
            return Err(rpc_err(1001, "handshake required", "UNAUTHORIZED"));
        }
        if st.shutting_down {
            return Err(rpc_err(1001, "host is shutting down", "HOST_SHUTTING_DOWN"));
        }
    }

    if method.starts_with("configSync.") {
        return config_sync_rpc::handle(state, method, params, tx)
            .await
            .map_err(config_sync_rpc_err);
    }

    if method.starts_with("backgroundContinuations.") {
        return background_continuations::handle(state, method, params).await;
    }

    if method.starts_with("backgroundJobs.") {
        return background_jobs::handle(state, method, params).await;
    }

    if method.starts_with("tools.fileBatch") {
        return file_batches::handle(state, method, params).await;
    }

    if method.starts_with("computer.") {
        return computer_rpc::handle(state, method, params).await;
    }

    if method.starts_with("modes.") {
        return modes_rpc::handle(state, &tx, method, params).await;
    }

    match method {
        "visualizations.readFragment" => gen_ui::read_fragment(state, params).await,
        "tools.remoteComplete" | "tools.workspaceExecute" | "tools.workspaceAbort" => {
            remote_tools::handle(state, method, params, tx).await
        }
        method if method.starts_with("session.collaboration.") => {
            let st = state.lock().await;
            crate::session_collaboration::handle(&st.db, method, &params)
                .map_err(session_collaboration_rpc_err)
        }
        "app.handshake" => {
            let client_version = params
                .get("protocolVersion")
                .and_then(|v| v.as_u64())
                .unwrap_or(0) as u32;
            if client_version != PROTOCOL_VERSION {
                return Err(rpc_err(
                    1011,
                    format!("protocol mismatch: client={client_version} host={PROTOCOL_VERSION}"),
                    "PROTOCOL_MISMATCH",
                ));
            }
            let mut st = state.lock().await;
            st.handshook = true;
            // Restore the current workspace from kv → projects.
            if let Ok(Some(pid)) = st.db.kv_get("app", "currentProjectId") {
                let pid = pid
                    .as_i64()
                    .or_else(|| pid.as_str().and_then(|s| s.parse::<i64>().ok()));
                if let Some(pid) = pid {
                    if let Ok(Some(path)) = st.db.project_path(pid) {
                        if !path.is_empty() {
                            if path.starts_with(crate::db::REMOTE_PROJECT_PREFIX) {
                                if let Ok(Some(group)) = st.db.project_group_for_path(&path) {
                                    st.workspace.set_remote(&group);
                                }
                            } else {
                                st.workspace.set(PathBuf::from(path));
                            }
                        }
                    }
                }
            }
            Ok(json!({
                "protocolVersion": PROTOCOL_VERSION,
                "version": HOST_VERSION,
                "capabilities": [
                    "tools", "sessions", "providers", "secrets", "plugins", "permissions",
                    "scheduled", "artifacts", "plans", "search", "turns", "notifications"
                ]
            }))
        }
        "app.health" => {
            let st = state.lock().await;
            let budget = st.tool_budget.snapshot();
            Ok(json!({
                "ok": true,
                "protocolVersion": PROTOCOL_VERSION,
                "version": HOST_VERSION,
                "uptimeMs": st.uptime_ms(),
                "toolBudget": {
                    "active": budget.active,
                    "queued": budget.queued,
                    "total": budget.total,
                    "shell": budget.shell,
                    "reads": budget.reads,
                    "mutations": budget.mutations,
                    "plugins": budget.plugins
                }
            }))
        }
        "window.setNativeCornerPreference" => window_corner_rpc::handle(params),
        "window.enableNativeSnap" => window_snap_rpc::handle(params),
        "keyboard.setGlobalShortcut" => {
            let binding = params
                .get("binding")
                .and_then(|value| value.as_str())
                .unwrap_or_default();
            let enabled = crate::keyboard::uses_windows_fallback(binding);
            crate::keyboard::set_enabled(enabled);
            Ok(json!({ "enabled": enabled }))
        }
        "app.getVersion" => Ok(json!({
            "name": "pi-desktop-host-core",
            "version": HOST_VERSION,
            "protocolVersion": PROTOCOL_VERSION
        })),

        "workspace.get" => {
            let st = state.lock().await;
            Ok(json!({ "workspace": st.workspace.get() }))
        }
        "projects.list" => {
            let st = state.lock().await;
            let projects = st
                .db
                .list_projects()
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "projects": projects }))
        }
        "project.groups.list" => {
            let st = state.lock().await;
            let groups = st
                .db
                .list_project_groups()
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "groups": groups }))
        }
        "project.group.createRemote" => {
            let name = params
                .get("name")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "name required", "INVALID_PARAMS"))?;
            let remote: crate::db::RemoteWorkspace =
                serde_json::from_value(params.get("remote").cloned().unwrap_or(Value::Null))
                    .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let group = st
                .db
                .create_remote_project_group(name, remote)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            Ok(json!({ "group": group }))
        }
        "project.group.create" => {
            let name = params
                .get("name")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "name required", "INVALID_PARAMS"))?;
            let folders = params
                .get("folders")
                .and_then(Value::as_array)
                .ok_or_else(|| rpc_err(1002, "folders required", "INVALID_PARAMS"))?
                .iter()
                .filter_map(Value::as_str)
                .map(str::to_string)
                .collect::<Vec<_>>();
            let st = state.lock().await;
            let group = st
                .db
                .create_project_group(name, &folders)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            Ok(json!({ "group": group }))
        }
        "project.group.update" => {
            let group_id = params
                .get("groupId")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "groupId required", "INVALID_PARAMS"))?;
            let name = params
                .get("name")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "name required", "INVALID_PARAMS"))?;
            let folders = params
                .get("folders")
                .and_then(Value::as_array)
                .ok_or_else(|| rpc_err(1002, "folders required", "INVALID_PARAMS"))?
                .iter()
                .filter_map(Value::as_str)
                .map(str::to_string)
                .collect::<Vec<_>>();
            let primary = params.get("primary").and_then(Value::as_str);
            let mut st = state.lock().await;
            // The active project's id survives an explicit relocation while its
            // stored path changes; detect that to follow it with the workspace.
            let active_project = match st.workspace.path.as_deref() {
                Some(path) => st
                    .db
                    .project_id_at_path(path)
                    .and_then(|id| match id {
                        Some(id) => Ok(st.db.project_path(id)?.map(|path| (id, path))),
                        None => Ok(None),
                    })
                    .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,
                None => None,
            };
            let group = st
                .db
                .update_project_group(group_id, name, &folders, primary)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            if let Some((id, before)) = active_project {
                let relocated = st
                    .db
                    .project_path(id)
                    .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                    .filter(|after| {
                        after != &before && group.roots.iter().any(|root| &root.path == after)
                    });
                if let Some(path) = relocated {
                    // Mirror `workspace.set`: hashline anchors belong to the old
                    // root, and the current project id follows the new path.
                    st.hashline.drop_all();
                    let ws = st.workspace.set(PathBuf::from(&path));
                    let pid = st
                        .db
                        .ensure_project(&ws.path, true)
                        .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
                    st.db
                        .kv_set("app", "currentProjectId", &json!(pid))
                        .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
                }
            }
            Ok(json!({ "group": group }))
        }
        "project.group.rename" => {
            let id = params
                .get("groupId")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "groupId required", "INVALID_PARAMS"))?;
            let name = params
                .get("name")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "name required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let group = st
                .db
                .rename_project_group(id, name)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            Ok(json!({ "group": group }))
        }
        "project.group.memory.get" => {
            let id = params
                .get("groupId")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "groupId required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let memory = st
                .db
                .get_project_group_memory(id)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            Ok(json!({ "memory": memory }))
        }
        "project.group.memory.set" => {
            let id = params
                .get("groupId")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "groupId required", "INVALID_PARAMS"))?;
            let entries = params
                .get("entries")
                .ok_or_else(|| rpc_err(1002, "entries required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let memory = st
                .db
                .set_project_group_memory(id, entries)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            Ok(json!({ "memory": memory }))
        }
        "project.group.instructions.get" => {
            let id = params
                .get("groupId")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "groupId required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let content = st
                .db
                .get_project_group_instructions(id)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            Ok(json!({ "content": content }))
        }
        "project.group.instructions.set" => {
            let id = params
                .get("groupId")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "groupId required", "INVALID_PARAMS"))?;
            let content = params
                .get("content")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "content required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let content = st
                .db
                .set_project_group_instructions(id, content)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            Ok(json!({ "content": content }))
        }
        "project.group.context" => {
            let path = params
                .get("path")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let context = st
                .db
                .project_group_context_for_path(path)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            Ok(json!({ "context": context }))
        }
        "projects.create" => {
            let path = params
                .get("path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let id = st
                .db
                .ensure_project(path, false)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let project = st
                .db
                .get_project(id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                .ok_or_else(|| rpc_err(1000, "project disappeared after creation", "INTERNAL"))?;
            Ok(json!({ "project": project }))
        }

        "projects.remove" => {
            let path = params
                .get("path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let path = st
                .db
                .stored_project_path(path)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                .ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?;
            if crate::scheduled::project::has_running_tasks(&st.db, &path)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
            {
                return Err(rpc_err(
                    1008,
                    "project has running scheduled tasks",
                    "CONFLICT",
                ));
            }
            let session_ids = st
                .db
                .project_session_ids(&path)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            // A running turn still owns its session's tools and working
            // directory and is still writing to that session's transcript, so
            // the bulk delete waits until every attached session is idle.
            for id in &session_ids {
                if sessions::session_has_running_turn(&st.db, id)
                    .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                {
                    return Err(rpc_err(1008, "project has running sessions", "CONFLICT"));
                }
            }
            // Check for a running session before changing group membership.
            // A busy project must remain in its original group.
            // Once the project is known to be idle, detach its root as part of
            // this delete because the group editor keeps its primary root
            // fixed and preserves chats on detached non-primary roots (#1358).
            // If the primary is removed, the first remaining root becomes primary. A
            // single-folder group is just a wrapper around one project, so
            // deleting that project also removes the now-empty group record.
            if let Some(group) = st
                .db
                .stored_project_group_for_path(&path)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
            {
                if group.roots.len() > 1 {
                    st.db
                        .remove_project_from_group(&group.id, &path)
                        .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
                } else {
                    st.db
                        .delete_project_group_record(&group.id)
                        .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
                }
            }
            crate::scheduled::project::pause(&st.db, &path)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            let mut sessions_removed = 0;
            for id in &session_ids {
                if sessions::delete_session(&st.db, id)
                    .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                {
                    drop_session_side_data(&st, id);
                    sessions_removed += 1;
                }
            }
            let removed = st
                .db
                .delete_project(&path)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            st.db
                .delete_project_memory(&path)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "removed": removed, "sessionsRemoved": sessions_removed }))
        }
        "project.memory.get" => {
            let path = params
                .get("path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let memory = st
                .db
                .get_project_memory(path)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            Ok(json!({ "memory": memory }))
        }
        "project.memory.set" => {
            let path = params
                .get("path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            if let Some(entries) = params.get("entries") {
                let memory = st
                    .db
                    .set_project_memory_entries(path, entries)
                    .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
                return Ok(json!({ "memory": memory }));
            }
            let content = params
                .get("content")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "content required", "INVALID_PARAMS"))?;
            let memory = st
                .db
                .set_project_memory(path, content)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            Ok(json!({ "memory": memory }))
        }
        "workspace.set" => {
            let path = params
                .get("path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?;
            let mut st = state.lock().await;
            st.hashline.drop_all();
            let ws = if path.starts_with(crate::db::REMOTE_PROJECT_PREFIX) {
                let group = st
                    .db
                    .project_group_for_path(path)
                    .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?
                    .filter(|group| group.remote.is_some())
                    .ok_or_else(|| rpc_err(1007, "remote project not found", "NOT_FOUND"))?;
                st.workspace.set_remote(&group)
            } else {
                st.workspace.set(PathBuf::from(path))
            };
            let pid = st
                .db
                .ensure_project(&ws.path, true)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            st.db
                .kv_set("app", "currentProjectId", &json!(pid))
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "workspace": ws }))
        }
        "workspace.clear" => {
            let mut st = state.lock().await;
            st.hashline.drop_all();
            st.workspace.clear();
            st.db
                .kv_delete("app", "currentProjectId")
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "ok": true }))
        }
        "review.turns" | "review.changes" | "review.context" => {
            let request = review::query::Request::parse(method, params)
                .map_err(|error| rpc_err(1002, error.to_string(), "INVALID_PARAMS"))?;
            let st = state.lock().await;
            if remote_tools::session_remote_workspace(&st, &request.session_id)?.is_some() {
                return Err(rpc_err(
                    1002,
                    "remote workspace review is unavailable",
                    "CAPABILITY_UNAVAILABLE",
                ));
            }
            let root = resolve_tool_workspace(&st, &request.session_id)?;
            review::query::execute(&st.db, method, request, root.as_deref().map(Path::new))
                .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))
        }
        "review.fileTarget" | "review.rollbackFile" => {
            review_actions_rpc::handle(&state, method, params).await
        }
        "review.rollback" => {
            let session_id = params
                .get("sessionId")
                .and_then(|value| value.as_str())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let snapshot_id = params
                .get("snapshotId")
                .and_then(|value| value.as_str())
                .ok_or_else(|| rpc_err(1002, "snapshotId required", "INVALID_PARAMS"))?;
            let _rollback_lease = review_actions_rpc::rollback_permit(&state, session_id).await?;
            let st = state.lock().await;
            if remote_tools::session_remote_workspace(&st, session_id)?.is_some() {
                return Err(rpc_err(
                    1002,
                    "remote workspace rollback is unavailable",
                    "CAPABILITY_UNAVAILABLE",
                ));
            }
            let workspace_root = resolve_tool_workspace(&st, session_id)?;
            let outcome = review::query::rollback(
                &st.db,
                session_id,
                snapshot_id,
                workspace_root.as_deref().map(Path::new),
            )
            .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?;
            if matches!(outcome.status, "rolledBack" | "alreadyRolledBack") {
                if let Some(root) = workspace_root.as_deref() {
                    let resolved = std::path::Path::new(root).join(&outcome.path);
                    st.hashline.invalidate_path(
                        session_id,
                        &crate::tools::hashline::canonical_key(&resolved),
                    );
                }
                sessions::update_tool_review_state(
                    &st.db,
                    session_id,
                    &outcome.message_id,
                    snapshot_id,
                    "rolledBack",
                )
                .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?;
            }
            Ok(serde_json::to_value(outcome)
                .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?)
        }

        "settings.get" => {
            let st = state.lock().await;
            let stored = st
                .db
                .get_setting("app")
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            let mut settings = normalize_settings_value(stored.unwrap_or_else(|| {
                json!({
                    "defaultMode": "agent",
                    "defaultCommandShell": tools::shell::default_shell_id(),
                    "theme": "dark",
                    "enterToSend": true,
                    "largePasteThreshold": DEFAULT_LARGE_PASTE_THRESHOLD,
                    "contextCompaction": {
                        "enabled": true,
                        "reserveTokens": 16384,
                        "keepRecentTokens": 20000
                    },
                    "onboardingDismissed": false
                })
            }));
            // Repair on read: a binding whose provider row is already gone —
            // deleted by a build that did not prune, an uninstalled plugin, or
            // synced bundle — is dropped here and the store is corrected, so
            // the shell never presents a default the runtime must reject.
            if prune_unresolvable_image_bindings(&st.db, &mut settings)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
            {
                st.db
                    .set_setting("app", &settings)
                    .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            }
            Ok(settings)
        }
        "settings.set" => {
            validate_settings_value(&params)?;
            let mut st = state.lock().await;
            let stored = st
                .db
                .get_setting("app")
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            let incoming_shell = params.get("defaultCommandShell").and_then(Value::as_str);
            let current_effective_shell = effective_command_shell_id(stored.as_ref());
            if incoming_shell.is_some_and(|shell| current_effective_shell.as_deref() != Some(shell))
            {
                gate_default_command_shell_setting(&st)?;
            }
            let mut settings = normalize_settings_value(merge_settings_value(stored, params));
            prune_unresolvable_image_bindings(&st.db, &mut settings)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            st.db
                .set_setting("app", &settings)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            if settings
                .get("backgroundJobContinuationEnabled")
                .and_then(Value::as_bool)
                != Some(true)
            {
                st.background_tasks.cancel_continuations(None, None, None);
            }
            // Keep the marketplace channel in memory aligned with settings.
            // Legacy source values are ignored, so this remains the official
            // channel; the renderer owns remote refresh timing.
            let (channel, custom_url) =
                crate::plugins::market_channel_from_settings(Some(&settings));
            st.plugins.set_market_channel(channel, custom_url);
            // A concrete app language pins the plugin display locale here, so a
            // shell that only writes settings still gets localized plugin rows.
            // `auto` is resolved by the shell and pushed through
            // `plugins.setLocale`.
            if let Some(language) = settings.get("language").and_then(Value::as_str) {
                if language != "auto" {
                    st.plugins.set_locale(language);
                }
            }
            crate::network_proxy::apply_from_settings(Some(&settings));
            crate::network_policy::apply_from_settings(Some(&settings));
            Ok(json!({ "ok": true }))
        }

        "commandShells.list" => {
            let st = state.lock().await;
            let catalog = command_shell_catalog(&st)?;
            serde_json::to_value(catalog).map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))
        }

        "secrets.set" => {
            let secret_ref = params
                .get("secretRef")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "secretRef required", "INVALID_PARAMS"))?;
            let value = params
                .get("value")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "value required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let backend = st
                .secrets
                .set(secret_ref, value)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "ok": true, "backend": backend }))
        }
        "secrets.delete" => {
            let secret_ref = params
                .get("secretRef")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "secretRef required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            st.secrets
                .delete(secret_ref)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "ok": true }))
        }
        "secrets.has" => {
            let secret_ref = params
                .get("secretRef")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "secretRef required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            Ok(json!({ "has": st.secrets.has(secret_ref) }))
        }
        "secrets.getForRuntime" => {
            let secret_ref = params
                .get("secretRef")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "secretRef required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let value = st
                .secrets
                .get(secret_ref)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "value": value }))
        }

        "providers.list" => {
            let include_disabled = params
                .get("includeDisabled")
                .and_then(|v| v.as_bool())
                .unwrap_or(true);
            let st = state.lock().await;
            let list = providers::list_providers(&st.db, &st.secrets, include_disabled)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "providers": list }))
        }
        "providers.reorder" => {
            let input: providers::ProviderReorderInput = serde_json::from_value(params)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let moved = providers::reorder_providers(&st.db, &st.secrets, input)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            if !moved {
                return Err(rpc_err(
                    1002,
                    "provider or reorder target not found",
                    "INVALID_PARAMS",
                ));
            }
            Ok(json!({ "ok": true }))
        }
        "providers.create" => {
            let input: ProviderCreateInput = serde_json::from_value(params)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let provider =
                providers::create_provider(&st.db, &st.secrets, input).map_err(provider_rpc_err)?;
            Ok(json!({ "provider": provider }))
        }
        "providers.update" => {
            let input: ProviderUpdateInput = serde_json::from_value(params)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let provider =
                providers::update_provider(&st.db, &st.secrets, input).map_err(provider_rpc_err)?;
            Ok(json!({ "provider": provider }))
        }
        "providers.delete" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let ok = providers::delete_provider(&st.db, &st.secrets, id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "ok": ok }))
        }
        "providers.get" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let provider = providers::get_provider(&st.db, &st.secrets, id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "provider": provider }))
        }
        "providers.getSecret" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let value = providers::get_secret_for_provider(&st.db, &st.secrets, id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "value": value }))
        }
        // The credential of a plugin-declared provider. `providers.update`
        // refuses that row, so this is the one path that writes the key the
        // declaration asks for without touching the declaration's own fields.
        "providers.setSecret" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let secret_value = params.get("secretValue").and_then(|v| v.as_str());
            let st = state.lock().await;
            let provider = providers::set_provider_secret(&st.db, &st.secrets, id, secret_value)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "provider": provider }))
        }
        "providers.listModels" => {
            let provider_id = params.get("providerId").and_then(|v| v.as_str());
            let endpoint: Option<ModelDiscoveryEndpoint> =
                serde_json::from_value(params.get("endpoint").cloned().unwrap_or(Value::Null))
                    .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let st = state.lock().await;
            if let Some(endpoint) = endpoint {
                if !endpoint
                    .matches(&st.db, provider_id.unwrap_or_default())
                    .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                {
                    return Ok(json!({ "models": [] }));
                }
            }
            let models = providers::list_models(&st.db, provider_id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "models": models }))
        }
        "providers.cacheModels" => {
            let input: CacheModelsParams = serde_json::from_value(params)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let st = state.lock().await;
            if let Some(endpoint) = input.endpoint {
                if !endpoint
                    .matches(&st.db, &input.provider_id)
                    .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                {
                    return Ok(json!({ "cached": 0, "models": [] }));
                }
            }
            let cached = providers::cache_discovered_models(
                &st.db,
                &input.provider_id,
                &input.models,
                input.complete,
            )
            .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            let models = providers::list_models(&st.db, Some(&input.provider_id))
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "cached": cached, "models": models }))
        }
        "providers.testConnection" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let provider = providers::get_provider(&st.db, &st.secrets, id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                .ok_or_else(|| rpc_err(1007, "provider not found", "NOT_FOUND"))?;
            Ok(json!({
                "ok": provider.has_secret || provider.auth_kind == "none",
                "provider": provider
            }))
        }

        "session.list" => {
            let st = state.lock().await;
            let sessions = sessions::list_sessions(&st.db)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            let sessions = sessions
                .into_iter()
                .map(|summary| remote_tools::session_value(&st.db, summary))
                .collect::<Result<Vec<_>, _>>()?;
            Ok(json!({ "sessions": sessions }))
        }
        "session.create" => {
            let thinking_level = thinking_level_param(&params)?;
            let fast_mode = fast_mode_param(&params)?.unwrap_or(false);
            let permission_parent = permission_parent_param(&params)?;
            // ADR 0329: an isolated session gets its own git worktree.
            let isolated = params
                .get("isolated")
                .and_then(Value::as_bool)
                .unwrap_or(false);
            let isolated_project = if isolated {
                Some(
                    params
                        .get("projectPath")
                        .and_then(|v| v.as_str())
                        .map(str::to_string)
                        .ok_or_else(|| {
                            rpc_err(
                                1002,
                                "an isolated session needs a projectPath",
                                "INVALID_PARAMS",
                            )
                        })?,
                )
            } else {
                None
            };
            let st = state.lock().await;
            if let Some(project) = isolated_project.as_deref() {
                worktree_rpc::ensure_local_project(&st.db, project)?;
            }
            // A child started during a ceiling-bound parent turn starts no broader.
            let permission_mode = if let Some(parent_id) = permission_parent {
                Some(
                    turn_permissions::inherited_mode(&st.db, &parent_id)
                        .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                        .ok_or_else(|| rpc_err(1007, "parent session not found", "NOT_FOUND"))?,
                )
            } else {
                None
            };
            let session = sessions::create_session_with_mode_snapshot(
                &st.db,
                sessions::SessionCreateOptions {
                    title: params
                        .get("title")
                        .and_then(|v| v.as_str())
                        .map(str::to_string),
                    mode: params
                        .get("mode")
                        .and_then(|v| v.as_str())
                        .map(str::to_string),
                    provider_id: params
                        .get("providerId")
                        .and_then(|v| v.as_str())
                        .map(str::to_string),
                    model_id: params
                        .get("modelId")
                        .and_then(|v| v.as_str())
                        .map(str::to_string),
                    project_path: params
                        .get("projectPath")
                        .and_then(|v| v.as_str())
                        .map(str::to_string),
                    thinking_level,
                    permission_mode,
                    fast_mode,
                },
                params.get("modeSnapshot"),
            )
            .map_err(modes_rpc::error)?;
            let Some(project) = isolated_project else {
                let session = remote_tools::decorate_session(
                    &st.db,
                    serde_json::to_value(session)
                        .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,
                )?;
                return Ok(json!({ "session": session }));
            };
            drop(st);
            let created = worktree_rpc::isolate_new_session(&state, &session.id, &project).await?;
            let st = state.lock().await;
            let session = sessions::session_summary(&st.db, &session.id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                .ok_or_else(|| rpc_err(1007, "session not found", "NOT_FOUND"))?;
            let session = remote_tools::session_value(&st.db, session)?;
            Ok(json!({ "session": session, "worktree": created }))
        }
        "session.fork" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let title = params.get("title").and_then(|v| v.as_str());
            let through_message_id = params.get("throughMessageId").and_then(|v| v.as_str());
            let st = state.lock().await;
            let session =
                match sessions::fork_session_through(&st.db, session_id, title, through_message_id)
                    .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                {
                    sessions::ForkSessionResult::Created(session) => session,
                    sessions::ForkSessionResult::NotFound => {
                        return Err(rpc_err(1007, "session not found", "NOT_FOUND"))
                    }
                    sessions::ForkSessionResult::Busy => {
                        return Err(rpc_err(1008, "session is running", "CONFLICT"))
                    }
                };
            let session = remote_tools::decorate_session(
                &st.db,
                serde_json::to_value(session)
                    .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,
            )?;
            Ok(json!({ "session": session }))
        }
        "session.moveProject" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .map(str::trim)
                .filter(|value| !value.is_empty())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            // An explicit `null` detaches the session from its project; a
            // missing key or a blank string remains a caller error.
            let project_path = match params.get("projectPath") {
                Some(Value::Null) => None,
                value => Some(
                    value
                        .and_then(|v| v.as_str())
                        .map(str::trim)
                        .filter(|value| !value.is_empty())
                        .ok_or_else(|| rpc_err(1002, "projectPath required", "INVALID_PARAMS"))?,
                ),
            };
            let st = state.lock().await;
            // An isolated session's worktree belongs to its project's repository.
            let isolated = crate::session_worktrees::registry::for_owner(&st.db, session_id, None)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                .is_some();
            if isolated {
                return Err(worktree_rpc::to_rpc(
                    crate::session_worktrees::WorktreeError::new(
                        "WORKTREE_MOVE_UNSUPPORTED",
                        "an isolated session cannot move to another project",
                    ),
                ));
            }
            let session = match sessions::move_session_project(&st.db, session_id, project_path)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
            {
                sessions::MoveSessionProjectResult::Moved(session) => session,
                sessions::MoveSessionProjectResult::NotFound => {
                    return Err(rpc_err(1007, "session not found", "NOT_FOUND"))
                }
                sessions::MoveSessionProjectResult::Busy => {
                    return Err(rpc_err(1008, "session is running", "CONFLICT"))
                }
            };
            let session = remote_tools::decorate_session(
                &st.db,
                serde_json::to_value(session)
                    .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,
            )?;
            Ok(json!({ "session": session }))
        }
        "session.get" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let message_before = params.get("messageBefore").and_then(|v| v.as_i64());
            let message_around = params
                .get("messageAround")
                .and_then(|v| v.as_str())
                .map(str::to_owned);
            let message_limit = params.get("messageLimit").and_then(|v| v.as_i64());
            if message_before.is_some_and(|value| value < 0)
                || message_limit.is_some_and(|value| value <= 0)
                || (message_around.is_some()
                    && (message_before.is_some() || message_limit.is_none()))
            {
                return Err(rpc_err(
                    1002,
                    "session read window must use non-negative messageBefore and positive messageLimit",
                    "INVALID_PARAMS",
                ));
            }
            let content_limit = params
                .get("contentLimit")
                .and_then(|v| v.as_u64())
                .map(|limit| limit.min(256 * 1024) as usize);
            if params
                .get("contentLimit")
                .and_then(|value| value.as_u64())
                .is_some_and(|value| value == 0)
            {
                return Err(rpc_err(
                    1002,
                    "session contentLimit must be positive",
                    "INVALID_PARAMS",
                ));
            }
            let st = state.lock().await;
            let session = sessions::get_session_with_options(
                &st.db,
                id,
                sessions::SessionReadOptions {
                    message_around,
                    message_before,
                    message_limit,
                    content_limit,
                },
            )
            .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            let session = remote_tools::decorate_session(
                &st.db,
                session_display::serialize(&st.db, session)?,
            )?;
            Ok(json!({ "session": session }))
        }
        "todos.get" => {
            let session_id = params
                .get("sessionId")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_ARGUMENT"))?;
            let st = state.lock().await;
            todos::get_from(&st, session_id)
        }

        "session.configure" => session_configuration::configure(&state, &tx, params).await,
        "session.delete" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            // Delete = discard for isolated sessions (ADR 0329); a git failure
            // keeps the session.
            worktree_rpc::remove_before_delete(&state, id).await?;
            let st = state.lock().await;
            let ok = sessions::delete_session(&st.db, id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            if ok {
                drop_session_side_data(&st, id);
            }
            drop(st);
            worktree_rpc::spawn_orphan_cleanup(&state);
            Ok(json!({ "ok": ok }))
        }
        "session.rename" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let title = params
                .get("title")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "title required", "INVALID_PARAMS"))?;
            let title = sessions::normalize_session_title(title)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let ok = sessions::rename_session(&st.db, id, &title)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "ok": ok }))
        }
        "session.deriveTitle" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let title = params
                .get("title")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "title required", "INVALID_PARAMS"))?;
            let title = sessions::normalize_session_title(title)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let updated = sessions::derive_session_title(&st.db, id, &title)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "updated": updated }))
        }
        "session.appendMessage" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let message: UiMessage = serde_json::from_value(
                params
                    .get("message")
                    .cloned()
                    .ok_or_else(|| rpc_err(1002, "message required", "INVALID_PARAMS"))?,
            )
            .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let turn_id = params
                .get("turnId")
                .and_then(|v| v.as_str())
                .map(str::to_string);
            let st = state.lock().await;
            let inserted_user_message_id = sessions::append_message_with_receipt(
                &st.db,
                session_id,
                &message,
                turn_id.as_deref(),
            )
            .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "ok": true, "insertedUserMessageId": inserted_user_message_id }))
        }
        "session.saveInflightMessage" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let message: UiMessage = serde_json::from_value(
                params
                    .get("message")
                    .cloned()
                    .ok_or_else(|| rpc_err(1002, "message required", "INVALID_PARAMS"))?,
            )
            .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let turn_id = params
                .get("turnId")
                .and_then(|v| v.as_str())
                .map(str::to_string);
            let st = state.lock().await;
            let saved =
                sessions::save_inflight_message(&st.db, session_id, turn_id.as_deref(), &message)
                    .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "ok": true, "saved": saved }))
        }
        "session.recoverInflightMessages" => {
            let st = state.lock().await;
            let recovered = sessions::recover_inflight_messages(&st.db, true)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "ok": true, "count": recovered.len() }))
        }
        "session.appendCompaction" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let compaction: CompactionRecord = serde_json::from_value(
                params
                    .get("compaction")
                    .cloned()
                    .ok_or_else(|| rpc_err(1002, "compaction required", "INVALID_PARAMS"))?,
            )
            .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let st = state.lock().await;
            sessions::append_compaction(&st.db, session_id, &compaction)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "ok": true }))
        }
        "session.replaceMessages" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let messages: Vec<UiMessage> = serde_json::from_value(
                params
                    .get("messages")
                    .cloned()
                    .ok_or_else(|| rpc_err(1002, "messages required", "INVALID_PARAMS"))?,
            )
            .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let st = state.lock().await;
            sessions::replace_messages(&st.db, session_id, &messages)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "ok": true }))
        }
        "session.deleteMessage" | "session.retractPendingPrompt" => {
            let session_id = params
                .get("sessionId")
                .and_then(Value::as_str)
                .filter(|id| !id.trim().is_empty())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let target_key = if method == "session.deleteMessage" {
                "messageId"
            } else {
                "userMessageId"
            };
            let target_id = params
                .get(target_key)
                .and_then(Value::as_str)
                .filter(|id| !id.trim().is_empty())
                .ok_or_else(|| rpc_err(1002, format!("{target_key} required"), "INVALID_PARAMS"))?;
            let turn_id = match params.get("turnId") {
                None | Some(Value::Null) => None,
                Some(Value::String(id)) if !id.trim().is_empty() => Some(id.as_str()),
                Some(_) => {
                    return Err(rpc_err(
                        1002,
                        "turnId must be a nonempty string",
                        "INVALID_PARAMS",
                    ))
                }
            };
            let st = state.lock().await;
            let result = if method == "session.deleteMessage" {
                sessions::delete_message(&st.db, session_id, target_id)
                    .and_then(|result| Ok(serde_json::to_value(result)?))
            } else {
                sessions::retract_pending_prompt(&st.db, session_id, target_id, turn_id)
                    .and_then(|result| Ok(serde_json::to_value(result)?))
            };
            result.map_err(|error| {
                let message = error.to_string();
                let code = if message.starts_with("NOT_FOUND") {
                    "NOT_FOUND"
                } else if message.starts_with("TURN_RUNNING") {
                    "TURN_RUNNING"
                } else if message.starts_with("PERMISSION_DENIED") {
                    "PERMISSION_DENIED"
                } else {
                    "INTERNAL"
                };
                rpc_err(if code == "NOT_FOUND" { 1007 } else { 1000 }, message, code)
            })
        }
        "session.truncateFrom" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let from_message_id = params
                .get("fromMessageId")
                .and_then(|v| v.as_str())
                .map(str::trim)
                .filter(|id| !id.is_empty());
            let truncate_before = params.get("truncateBefore").and_then(|v| v.as_i64());
            let st = state.lock().await;
            let truncated =
                sessions::truncate_from(&st.db, session_id, from_message_id, truncate_before)
                    .map_err(|e| {
                        let message = e.to_string();
                        if message.starts_with("NOT_FOUND") {
                            rpc_err(1007, message, "NOT_FOUND")
                        } else if message.starts_with("INVALID_PARAMS") {
                            rpc_err(1002, message, "INVALID_PARAMS")
                        } else {
                            rpc_err(1000, message, "INTERNAL")
                        }
                    })?;
            serde_json::to_value(truncated).map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))
        }

        "session.saveRevision" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let root_user_id = params
                .get("rootUserId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "rootUserId required", "INVALID_PARAMS"))?;
            let messages: Vec<UiMessage> = serde_json::from_value(
                params
                    .get("messages")
                    .cloned()
                    .ok_or_else(|| rpc_err(1002, "messages required", "INVALID_PARAMS"))?,
            )
            .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let make_active = params
                .get("makeActive")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            let st = state.lock().await;
            // An explicit index refreshes that revision's payload in place
            // (the branch grew since it was archived); otherwise a new index.
            let revision = match params.get("revisionIndex").and_then(|v| v.as_i64()) {
                Some(revision_index) => sessions::refresh_message_revision(
                    &st.db,
                    session_id,
                    root_user_id,
                    revision_index,
                    &messages,
                ),
                None => sessions::save_message_revision(
                    &st.db,
                    session_id,
                    root_user_id,
                    &messages,
                    make_active,
                ),
            }
            .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "revision": revision }))
        }
        "session.saveActiveRevision" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let saved = sessions::save_active_branch_revision(&st.db, session_id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "saved": saved }))
        }
        "session.listRevisions" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let root_user_id = params
                .get("rootUserId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "rootUserId required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let revisions = sessions::list_message_revisions(&st.db, session_id, root_user_id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "revisions": revisions }))
        }
        "session.activateRevision" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let root_user_id = params
                .get("rootUserId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "rootUserId required", "INVALID_PARAMS"))?;
            let revision_index = params
                .get("revisionIndex")
                .and_then(|v| v.as_i64())
                .ok_or_else(|| rpc_err(1002, "revisionIndex required", "INVALID_PARAMS"))?;
            let prefix: Vec<UiMessage> =
                serde_json::from_value(params.get("prefix").cloned().unwrap_or_else(|| json!([])))
                    .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let require_canonical = match params.get("requireCanonicalPrefix") {
                None => false,
                Some(Value::Bool(required)) => *required,
                Some(_) => {
                    return Err(rpc_err(
                        1002,
                        "requireCanonicalPrefix must be a boolean",
                        "INVALID_PARAMS",
                    ))
                }
            };
            let messages = if require_canonical {
                sessions::activate_message_revision_canonical(
                    &st.db,
                    session_id,
                    root_user_id,
                    revision_index,
                )
            } else {
                sessions::activate_message_revision(
                    &st.db,
                    session_id,
                    root_user_id,
                    revision_index,
                    &prefix,
                )
            }
            .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "messages": messages }))
        }
        "session.getScratchPath" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let path = scratch::session_dir(&st.data_dir, session_id)
                .ok_or_else(|| rpc_err(1002, "invalid session id", "INVALID_PARAMS"))?;
            Ok(json!({ "path": path.to_string_lossy() }))
        }

        "session.import" => {
            let summary: sessions::SessionSummary = serde_json::from_value(
                params
                    .get("session")
                    .cloned()
                    .ok_or_else(|| rpc_err(1002, "session required", "INVALID_PARAMS"))?,
            )
            .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let messages: Vec<UiMessage> = serde_json::from_value(
                params
                    .get("messages")
                    .cloned()
                    .ok_or_else(|| rpc_err(1002, "messages required", "INVALID_PARAMS"))?,
            )
            .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let imported = sessions::import_session(&st.db, &summary, &messages)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "ok": true, "imported": imported, "skipped": !imported }))
        }

        // Plugin sessions are a separate host-owned domain. Electron main is
        // the only caller that can supply pluginId; the plugin process never
        // receives a generic host RPC handle or SQLite access.
        "plugin.session.import" => {
            let plugin_id = params
                .get("pluginId")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "pluginId required", "INVALID_PARAMS"))?;
            let mut st = state.lock().await;
            if !st.allow_plugin_import(plugin_id, false) {
                return Err(rpc_err(1006, "plugin import rate exceeded", "RATE_LIMITED"));
            }
            let result = plugin_sessions::import(&st.db, plugin_id, &params)
                .map_err(plugin_session_rpc_err)?;
            Ok(result)
        }
        "plugin.session.importBatch" => {
            let plugin_id = params
                .get("pluginId")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "pluginId required", "INVALID_PARAMS"))?;
            let mut st = state.lock().await;
            if !st.allow_plugin_import(plugin_id, true) {
                return Err(rpc_err(
                    1006,
                    "plugin batch import rate exceeded",
                    "RATE_LIMITED",
                ));
            }
            let result = plugin_sessions::import_batch(&st.db, plugin_id, &params)
                .map_err(plugin_session_rpc_err)?;
            Ok(result)
        }
        "plugin.session.list" => {
            let plugin_id = plugin_session_plugin_id(&params)?;
            let scope = plugin_session_scope(&params)?;
            let st = state.lock().await;
            plugin_sessions::list(&st.db, plugin_id, scope, &params).map_err(plugin_session_rpc_err)
        }
        "plugin.session.get" => {
            let plugin_id = plugin_session_plugin_id(&params)?;
            let scope = plugin_session_scope(&params)?;
            let st = state.lock().await;
            plugin_sessions::get(&st.db, plugin_id, scope, &params).map_err(plugin_session_rpc_err)
        }
        "plugin.session.listMessages" => {
            let plugin_id = plugin_session_plugin_id(&params)?;
            let scope = plugin_session_scope(&params)?;
            let st = state.lock().await;
            plugin_sessions::list_messages(&st.db, plugin_id, scope, &params)
                .map_err(plugin_session_rpc_err)
        }
        "plugin.session.autoTitleContext" => {
            let plugin_id = plugin_session_plugin_id(&params)?;
            let st = state.lock().await;
            plugin_sessions::auto_title_context(&st.db, plugin_id, &params)
                .map_err(plugin_session_rpc_err)
        }
        "plugin.session.setAutoTitle" => {
            let plugin_id = plugin_session_plugin_id(&params)?;
            let st = state.lock().await;
            plugin_sessions::set_auto_title(&st.db, plugin_id, &params)
                .map_err(plugin_session_rpc_err)
        }
        "plugin.session.rename" => {
            let plugin_id = plugin_session_plugin_id(&params)?;
            let scope = plugin_session_scope(&params)?;
            let st = state.lock().await;
            plugin_sessions::rename(&st.db, plugin_id, scope, &params)
                .map_err(plugin_session_rpc_err)
        }
        "plugin.session.delete" => {
            let plugin_id = plugin_session_plugin_id(&params)?;
            let scope = plugin_session_scope(&params)?;
            let mut st = state.lock().await;
            // Ownership no longer bounds the target under `.all`, so the
            // frequency brake is what stays (ADR 0339 §5).
            if !st.allow_plugin_delete(plugin_id) {
                return Err(rpc_err(1006, "plugin delete rate exceeded", "RATE_LIMITED"));
            }
            plugin_sessions::delete(&st.db, plugin_id, scope, &params)
                .map_err(plugin_session_rpc_err)
        }

        // Message-level writes (ADR 0339). Every arm charges the shared message
        // write budget before touching a transcript, and host-core itself
        // refuses a rewrite while a turn owns the session.
        "plugin.session.appendMessage"
        | "plugin.session.replaceMessages"
        | "plugin.session.deleteMessage"
        | "plugin.session.truncateFrom" => {
            let plugin_id = plugin_session_plugin_id(&params)?;
            let scope = plugin_session_scope(&params)?;
            let mut st = state.lock().await;
            if !st.allow_plugin_message_write(plugin_id) {
                return Err(rpc_err(
                    1006,
                    "plugin message write rate exceeded",
                    "RATE_LIMITED",
                ));
            }
            match method {
                "plugin.session.appendMessage" => {
                    plugin_sessions::append_message(&st.db, plugin_id, scope, &params)
                }
                "plugin.session.replaceMessages" => {
                    plugin_sessions::replace_messages(&st.db, plugin_id, scope, &params)
                }
                "plugin.session.deleteMessage" => {
                    plugin_sessions::delete_message(&st.db, plugin_id, scope, &params)
                }
                _ => plugin_sessions::truncate_from(&st.db, plugin_id, scope, &params),
            }
            .map_err(plugin_session_rpc_err)
        }

        // Plugin usage is a read-only facts domain: a keyset page of completed
        // turns from non-deleted sessions, served to plugins that hold
        // `usage.read` (checked in Electron main before dispatch). The payload
        // carries counters and titles — never a message body — and Electron
        // main remains the only caller that can supply pluginId.
        "plugin.usage.listTurns" => {
            let plugin_id = params
                .get("pluginId")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "pluginId required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let page =
                plugin_usage::list_turns_page(&st.db, &params).map_err(plugin_session_rpc_err)?;
            tracing::debug!(
                method = "plugin.usage.listTurns",
                plugin_id,
                count = page["turns"].as_array().map(Vec::len).unwrap_or(0),
                "plugin usage rpc served"
            );
            Ok(page)
        }

        "session.beginTurn" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let ceiling = turn_permissions::parse_ceiling(params.get("permissionCeiling"))
                .map_err(|message| rpc_err(1002, message, "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let provider = params.get("providerId").and_then(Value::as_str);
            let model = params.get("modelId").and_then(Value::as_str);
            let turn_id = match params.get("sessionMessageId").and_then(Value::as_str) {
                Some(message_id) => crate::session_collaboration::begin_turn(
                    &st.db, session_id, message_id, provider, model,
                ),
                None => sessions::begin_turn(&st.db, session_id, provider, model),
            }
            .map_err(session_collaboration_rpc_err)?;
            if let Some(ceiling) = ceiling.as_deref() {
                // A turn that cannot hold its ceiling must not run at all.
                if let Err(error) = turn_permissions::record(st.db.conn(), &turn_id, ceiling) {
                    let code = "PERMISSION_CEILING_UNAVAILABLE";
                    let mut message = error.to_string();
                    if let Err(end_error) = sessions::end_turn_settling(
                        &st.db,
                        &turn_id,
                        "error",
                        Some(code),
                        None,
                        false,
                        false,
                    ) {
                        message = format!("{message}; closing the turn failed: {end_error}");
                    }
                    return Err(rpc_err(1000, message, code));
                }
            }
            Ok(json!({ "turnId": turn_id, "permissionCeiling": ceiling }))
        }
        "session.recordUsage" => {
            let session_id = params
                .get("sessionId")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let turn_id = params
                .get("turnId")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "turnId required", "INVALID_PARAMS"))?;
            let usage = params
                .get("usage")
                .ok_or_else(|| rpc_err(1002, "usage required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let recorded = sessions::record_usage(&st.db, session_id, turn_id, usage)
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            Ok(json!({ "ok": recorded }))
        }
        "session.endTurn" => {
            let turn_id = params
                .get("turnId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "turnId required", "INVALID_PARAMS"))?;
            let status = params
                .get("status")
                .and_then(|v| v.as_str())
                .unwrap_or("completed");
            let st = state.lock().await;
            let result = sessions::end_turn_settling(
                &st.db,
                turn_id,
                status,
                params.get("errorCode").and_then(|v| v.as_str()),
                params.get("usage"),
                params
                    .get("createNotification")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(true),
                params
                    .get("recoverInflight")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false),
            )
            .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            let mut response = json!({ "ok": result.updated });
            if let Some(notification) = result.notification {
                response["notification"] = json!(notification);
            }
            if let Some(recovered) = result.recovered {
                response["recovered"] = json!(recovered);
            }
            Ok(response)
        }

        // The Host-owned turn queue (D375 / ADR 0213). Entries are durable so
        // a restart restores them in order; the Agent Host decides when one
        // starts, never the store.
        "session.queuePush" => {
            let input: turn_queue::QueuedTurnInput = serde_json::from_value(params.clone())
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let entry = turn_queue::push(&st.db, input).map_err(|e| {
                let message = e.to_string();
                if message == "QUEUE_FULL" {
                    rpc_err(1008, message, "AGENT_BUSY")
                } else if message == "IDEMPOTENCY_CONFLICT" {
                    rpc_err(1008, message, "IDEMPOTENCY_CONFLICT")
                } else if message.starts_with("session not found") {
                    rpc_err(1007, message, "SESSION_NOT_FOUND")
                } else {
                    rpc_err(1000, message, "INTERNAL")
                }
            })?;
            Ok(json!({ "entry": entry }))
        }
        "session.queueList" => {
            let session_id = params.get("sessionId").and_then(|v| v.as_str());
            let st = state.lock().await;
            let entries = turn_queue::list(&st.db, session_id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "entries": entries }))
        }
        "session.queueRemove" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let removed = turn_queue::remove(&st.db, id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "removed": removed }))
        }
        "session.queuePrioritize" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let entry = turn_queue::prioritize(&st.db, id)
                .map_err(|e| {
                    let message = e.to_string();
                    if message == "ALREADY_PRIORITIZED" {
                        rpc_err(1008, message, "CONFLICT")
                    } else {
                        rpc_err(1000, message, "INTERNAL")
                    }
                })?
                .ok_or_else(|| rpc_err(1007, "queue entry not found", "NOT_FOUND"))?;
            Ok(json!({ "entry": entry }))
        }
        "session.queueReorder" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let direction = params
                .get("direction")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "direction required", "INVALID_PARAMS"))?;
            let direction = match direction {
                "up" => turn_queue::ReorderDirection::Up,
                "down" => turn_queue::ReorderDirection::Down,
                other => {
                    return Err(rpc_err(
                        1002,
                        format!("unknown direction: {other}"),
                        "INVALID_PARAMS",
                    ))
                }
            };
            let st = state.lock().await;
            let moved = turn_queue::reorder(&st.db, id, direction)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "moved": moved }))
        }

        "notification.list" => {
            let unread_only = params
                .get("unreadOnly")
                .and_then(|value| value.as_bool())
                .unwrap_or(false);
            let limit = params
                .get("limit")
                .and_then(|value| value.as_i64())
                .unwrap_or(crate::db::NOTIFICATION_KEEP);
            let st = state.lock().await;
            let (notifications, unread_count) = notifications::list(&st.db, unread_only, limit)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({
                "notifications": notifications,
                "unreadCount": unread_count
            }))
        }
        "notification.markRead" => {
            let id = params
                .get("id")
                .and_then(|value| value.as_str())
                .filter(|id| !id.trim().is_empty())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let ok = notifications::mark_read(&st.db, id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "ok": ok }))
        }
        "notification.markAllRead" => {
            let st = state.lock().await;
            notifications::mark_all_read(&st.db)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "ok": true }))
        }
        "notification.clear" => {
            let st = state.lock().await;
            notifications::clear(&st.db).map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "ok": true }))
        }

        "search.sessions" => {
            let query = params.get("query").and_then(|v| v.as_str()).unwrap_or("");
            if query.chars().count() > 500 {
                return Err(rpc_err(
                    1001,
                    "query exceeds 500 characters",
                    "INVALID_ARGUMENT",
                ));
            }
            let offset = params.get("offset").and_then(|v| v.as_i64()).unwrap_or(0);
            // The desktop merges this cursor with the sidecar's cursorless
            // native catalog, so it asks for the whole prefix in one reply
            // instead of walking the query from the beginning once per page.
            // The default keeps the thirty-row contract for every other
            // caller, and host-core clamps the request to a bounded maximum.
            let limit = params
                .get("limit")
                .and_then(|v| v.as_i64())
                .unwrap_or(crate::session_search::SEARCH_PAGE_SIZE);
            let st = state.lock().await;
            let page = crate::session_search::search(&st.db, query, offset, limit)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!(page))
        }
        "search.context" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let message_id = params
                .get("messageId")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let query = params.get("query").and_then(|v| v.as_str()).unwrap_or("");
            let direction = params
                .get("direction")
                .and_then(|v| v.as_str())
                .unwrap_or("around");
            if session_id.is_empty()
                || message_id.is_empty()
                || query.chars().count() > 500
                || !matches!(direction, "around" | "before" | "after")
            {
                return Err(rpc_err(1001, "invalid search context", "INVALID_ARGUMENT"));
            }
            let st = state.lock().await;
            let context =
                crate::session_search::context(&st.db, session_id, message_id, direction, query)
                    .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                    .ok_or_else(|| rpc_err(1007, "message not found", "NOT_FOUND"))?;
            Ok(json!(context))
        }

        "search.query" => {
            let query = params
                .get("query")
                .or_else(|| params.get("q"))
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let limit = params.get("limit").and_then(|v| v.as_i64()).unwrap_or(20);
            let st = state.lock().await;
            let hits = sessions::search_messages(&st.db, query, limit)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "hits": hits }))
        }

        "session.usageCost" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .filter(|id| !id.is_empty())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            sessions::session_usage_cost(&st.db, session_id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))
        }

        "stats.getTokenUsageHistory" => {
            let bucket = params
                .get("bucket")
                .and_then(|v| v.as_str())
                .unwrap_or("day");

            let st = state.lock().await;
            let history = sessions::get_token_usage_history(
                &st.db,
                params.get("startDate").and_then(|v| v.as_i64()),
                params.get("endDate").and_then(|v| v.as_i64()),
                bucket,
            )
            .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(history)
        }

        "artifacts.list" => {
            let session_id = params.get("sessionId").and_then(|v| v.as_str());
            let limit = params.get("limit").and_then(|v| v.as_i64()).unwrap_or(200);
            let st = state.lock().await;
            let artifacts = artifacts::list(&st.db, session_id, limit)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "artifacts": artifacts }))
        }

        "plans.pending" => {
            let session_id = params.get("sessionId").and_then(|v| v.as_str());
            let st = state.lock().await;
            let (pending, planning_state, kind) = {
                let crate::state::AppState { db, plans, .. } = &*st;
                let pending = plans
                    .pending_for_session(db, session_id)
                    .map_err(plan_rpc_err)?;
                let planning_state = session_id
                    .map(|id| plans.state_for_session(db, id))
                    .transpose()
                    .map_err(plan_rpc_err)?;
                // The session's own mode names the contract being authored even
                // when no proposal exists yet (Plan/Goal `planning`).
                let kind = session_id
                    .map(|id| plans.active_kind(db, id))
                    .transpose()
                    .map_err(plan_rpc_err)?
                    .flatten();
                (pending, planning_state, kind)
            };
            Ok(json!({ "plans": pending, "state": planning_state, "kind": kind }))
        }
        "plans.enter" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .filter(|id| !id.trim().is_empty())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let turn_id = params
                .get("turnId")
                .and_then(|id| id.as_str())
                .filter(|id| !id.trim().is_empty())
                .ok_or_else(|| rpc_err(1002, "turnId required", "INVALID_PARAMS"))?;
            let tool_call_id = params
                .get("toolCallId")
                .and_then(|id| id.as_str())
                .filter(|id| !id.trim().is_empty())
                .ok_or_else(|| rpc_err(1002, "toolCallId required", "INVALID_PARAMS"))?;
            // Older sidecars only knew Plan; absent means Plan (D198).
            let kind = params
                .get("kind")
                .and_then(|v| v.as_str())
                .unwrap_or(plans::KIND_PLAN);
            let kind = plans::normalize_kind(kind)
                .ok_or_else(|| rpc_err(1002, "kind must be 'plan' or 'goal'", "INVALID_PARAMS"))?;
            modes_rpc::reject_goal_activation(kind)?;
            let st = state.lock().await;
            let planning_state = {
                let crate::state::AppState { db, plans, .. } = &*st;
                plans
                    .enter(db, session_id, turn_id, tool_call_id, kind)
                    .map_err(plan_rpc_err)?;
                plans
                    .state_for_session(db, session_id)
                    .map_err(plan_rpc_err)?
            };
            emit_notification(
                &tx,
                "plans.changed",
                json!({
                    "sessionId": session_id,
                    "state": planning_state,
                    "kind": kind,
                }),
            )
            .await;
            Ok(json!({ "ok": true, "state": planning_state, "kind": kind }))
        }
        "plans.submit" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .filter(|id| !id.trim().is_empty())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let title = params
                .get("title")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "title required", "INVALID_PARAMS"))?;
            let markdown = params
                .get("markdown")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "markdown required", "INVALID_PARAMS"))?;
            let question = params
                .get("question")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "question required", "INVALID_PARAMS"))?;
            let turn_id = params
                .get("turnId")
                .and_then(|v| v.as_str())
                .filter(|id| !id.trim().is_empty())
                .ok_or_else(|| rpc_err(1002, "turnId required", "INVALID_PARAMS"))?;
            let tool_call_id = params
                .get("toolCallId")
                .and_then(|v| v.as_str())
                .filter(|id| !id.trim().is_empty())
                .ok_or_else(|| rpc_err(1002, "toolCallId required", "INVALID_PARAMS"))?;
            let kind = params
                .get("kind")
                .and_then(|v| v.as_str())
                .unwrap_or(plans::KIND_PLAN);
            let kind = plans::normalize_kind(kind)
                .ok_or_else(|| rpc_err(1002, "kind must be 'plan' or 'goal'", "INVALID_PARAMS"))?;
            modes_rpc::reject_goal_activation(kind)?;
            let proposal = {
                let guard = state.lock().await;
                let st = &*guard;
                let workspace = resolve_plan_workspace(st, session_id)?;
                st.plans
                    .submit(
                        &st.db,
                        crate::plans::PlanSubmitParams {
                            workspace_root: &workspace,
                            session_id,
                            turn_id,
                            tool_call_id,
                            kind,
                            title,
                            markdown,
                            question,
                        },
                    )
                    .map_err(plan_rpc_err)?
            };
            emit_notification(
                &tx,
                "plans.changed",
                json!({
                    "sessionId": session_id,
                    "state": "awaiting_approval",
                    "kind": proposal.kind,
                    "proposalId": proposal.id,
                    "proposal": proposal
                }),
            )
            .await;
            Ok(json!({ "status": "pending", "proposal": proposal }))
        }
        "plans.resolve" => {
            let proposal_id = params
                .get("proposalId")
                .and_then(|v| v.as_str())
                .filter(|id| !id.trim().is_empty())
                .ok_or_else(|| rpc_err(1002, "proposalId required", "INVALID_PARAMS"))?;
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .filter(|id| !id.trim().is_empty())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let turn_id = params
                .get("turnId")
                .and_then(|v| v.as_str())
                .filter(|id| !id.trim().is_empty())
                .ok_or_else(|| rpc_err(1002, "turnId required", "INVALID_PARAMS"))?;
            let tool_call_id = params
                .get("toolCallId")
                .and_then(|v| v.as_str())
                .filter(|id| !id.trim().is_empty())
                .ok_or_else(|| rpc_err(1002, "toolCallId required", "INVALID_PARAMS"))?;
            let action = params.get("action").and_then(|v| v.as_str()).unwrap_or("");
            let version = params.get("version").and_then(|v| v.as_i64());
            let target = params.get("targetPermissionMode").and_then(|v| v.as_str());
            let resolution = {
                let guard = state.lock().await;
                let st = &*guard;
                let workspace = if action == "approve" {
                    resolve_plan_workspace_if_available(st, session_id)?
                } else {
                    None
                };
                st.plans
                    .resolve(
                        &st.db,
                        crate::plans::PlanResolveParams {
                            workspace_root: workspace.as_deref(),
                            proposal_id,
                            session_id,
                            turn_id,
                            tool_call_id,
                            version,
                            action,
                            target_permission_mode: target,
                        },
                    )
                    .map_err(plan_rpc_err)?
            };
            let state_name = if resolution.status == plans::STATUS_APPROVED {
                "inactive"
            } else {
                "planning"
            };
            emit_notification(
                &tx,
                "plans.changed",
                json!({
                    "sessionId": resolution.proposal.session_id,
                    "state": state_name,
                    "kind": resolution.proposal.kind,
                    "proposalId": resolution.proposal.id,
                    "proposal": resolution.proposal,
                    "action": resolution.action,
                    "targetPermissionMode": resolution.target_permission_mode,
                    "execution": resolution.execution
                }),
            )
            .await;
            Ok(json!({
                "ok": true,
                "proposal": resolution.proposal,
                "state": state_name,
                "action": resolution.action,
                "targetPermissionMode": resolution.target_permission_mode,
                "execution": resolution.execution
            }))
        }
        "plans.queuedExecutions" => {
            let session_id = params.get("sessionId").and_then(|v| v.as_str());
            let st = state.lock().await;
            let executions = st
                .plans
                .queued_executions(&st.db, session_id)
                .map_err(plan_rpc_err)?;
            Ok(json!({ "executions": executions }))
        }
        "plans.claimExecution" => {
            let execution_id = params
                .get("executionId")
                .and_then(|v| v.as_str())
                .filter(|id| !id.trim().is_empty())
                .ok_or_else(|| rpc_err(1002, "executionId required", "INVALID_PARAMS"))?;
            let execution = {
                let st = state.lock().await;
                st.plans
                    .claim_execution(&st.db, execution_id)
                    .map_err(plan_rpc_err)?
            };
            emit_notification(
                &tx,
                "plans.changed",
                json!({
                    "sessionId": execution.session_id,
                    "proposalId": execution.proposal_id,
                    "state": "inactive",
                    "kind": execution.kind,
                    "execution": execution,
                }),
            )
            .await;
            Ok(json!({ "execution": execution }))
        }
        "plans.finishExecution" => {
            let execution_id = params
                .get("executionId")
                .and_then(|v| v.as_str())
                .filter(|id| !id.trim().is_empty())
                .ok_or_else(|| rpc_err(1002, "executionId required", "INVALID_PARAMS"))?;
            let status = params
                .get("status")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "status required", "INVALID_PARAMS"))?;
            let execution = {
                let st = state.lock().await;
                st.plans
                    .finish_execution(
                        &st.db,
                        execution_id,
                        status,
                        params.get("errorCode").and_then(|v| v.as_str()),
                    )
                    .map_err(plan_rpc_err)?
            };
            emit_notification(
                &tx,
                "plans.changed",
                json!({
                    "sessionId": execution.session_id,
                    "proposalId": execution.proposal_id,
                    "state": "inactive",
                    "kind": execution.kind,
                    "execution": execution,
                }),
            )
            .await;
            Ok(json!({ "execution": execution }))
        }
        "plans.abort" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .filter(|id| !id.trim().is_empty())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let (changed, kind) = {
                let st = state.lock().await;
                let changed = st
                    .plans
                    .abort_session(&st.db, session_id)
                    .map_err(plan_rpc_err)?;
                // Only a session that still exists can name the contract it
                // returns to, and only such a session can have changed here.
                let kind = if changed {
                    st.plans
                        .active_kind(&st.db, session_id)
                        .map_err(plan_rpc_err)?
                } else {
                    None
                };
                (changed, kind)
            };
            if changed {
                emit_notification(
                    &tx,
                    "plans.changed",
                    json!({ "sessionId": session_id, "state": "planning", "kind": kind }),
                )
                .await;
            }
            Ok(json!({ "ok": true, "changed": changed }))
        }

        method if method.starts_with("scheduled.") => {
            let st = state.lock().await;
            scheduled_rpc::handle(&st, method, params)
        }

        method if method.starts_with("worktree.") => {
            worktree_rpc::handle(&state, method, params).await
        }

        "tools.list" => {
            let mut definitions = tools::builtin_tool_defs();
            let st = state.lock().await;
            if scheduled_settings::enabled(&st)? {
                if let Some(items) = definitions.as_array_mut() {
                    items.extend(scheduled_tools::definitions());
                }
            }
            Ok(json!({ "tools": definitions }))
        }
        "backgroundTasks.list" => {
            let st = state.lock().await;
            Ok(json!({
                "tasks": st.background_tasks.summaries(),
                // The change counter is the single version source: supervisors
                // bump it on every transition and the renderer re-lists on the
                // matching notification.
                "version": background_tasks::change_counter(),
            }))
        }
        "backgroundTasks.output" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            match background_tasks::task_output(&st.background_tasks, id).await {
                Ok(Some(output)) => Ok(output),
                // `NOT_FOUND` is the registered, documented code for an unknown
                // entity id; a dedicated TASK_NOT_FOUND would be a new contract
                // (ErrorCodes + 08-error-codes) for no behavioural gain.
                Ok(None) => Err(rpc_err(1007, "task not found", "NOT_FOUND")),
                Err(message) => Err(rpc_err(1000, message, "INTERNAL")),
            }
        }
        "backgroundTasks.stop" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let mut st = state.lock().await;
            st.background_tasks
                .cancel_continuations(None, None, Some(id));
            // Signalling is enough: the supervisor kills the tree, records the
            // terminal state, and bumps the change counter, which fans out the
            // `backgroundTasks.changed` notification for this same task.
            let found = background_tasks::stop_task(&st.background_tasks, id)
                .await
                .map_err(|message| rpc_err(1000, message, "INTERNAL"))?;
            Ok(json!({ "ok": true, "found": found }))
        }
        "tools.execute" => {
            let call_started = std::time::Instant::now();
            let p: ToolsExecuteParams = serde_json::from_value(params.clone())
                .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            if p.write_scope.is_some() && !crate::file_resources::is_write(&p.tool_name) {
                return Err(rpc_err(
                    1002,
                    "writeScope is only valid on Write and Edit",
                    "INVALID_PARAMS",
                ));
            }
            let workspace_only = p.tool_name == "Read" && p.workspace_only;
            let _pending_file_call = if let Some(ticket) = p.file_batch_ticket.as_deref() {
                Some(
                    state
                        .lock()
                        .await
                        .tool_budget
                        .begin_file_call(
                            ticket,
                            &p.session_id,
                            p.delegation_id.as_deref(),
                            &p.tool_call_id,
                            &p.tool_name,
                            &p.args,
                        )
                        .map_err(|e| rpc_err(1002, e, "INVALID_PARAMS"))?,
                )
            } else {
                None
            };
            let notify_on_exit = p.tool_name == "Bash"
                && p.args.get("notifyOnExit").and_then(Value::as_bool) == Some(true);
            if p.tool_name == "Bash"
                && p.args
                    .get("notifyOnExit")
                    .is_some_and(|value| !value.is_boolean())
            {
                return Err(rpc_err(
                    1002,
                    "notifyOnExit must be a boolean",
                    "INVALID_PARAMS",
                ));
            }
            if notify_on_exit {
                let st = state.lock().await;
                if p.tool_name != "Bash"
                    || !p.run_in_background
                    || p.delegation_id.is_some()
                    || p.permission_scope.is_some()
                    || sessions::tool_policy(&st.db, &p.session_id)
                        .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                        != Some(sessions::ToolPolicy::Agent)
                    || remote_tools::session_remote_workspace(&st, &p.session_id)?.is_some()
                {
                    return Err(rpc_err(
                        1001,
                        "notifyOnExit requires a local parent Agent background Bash job",
                        "PERMISSION_DENIED",
                    ));
                }
                let turn_id = p.turn_id.as_deref().ok_or_else(|| {
                    rpc_err(1002, "notifyOnExit requires a turn", "INVALID_PARAMS")
                })?;
                background_tasks::continuations::authorize_registration(
                    &st,
                    &p.session_id,
                    turn_id,
                )
                .map_err(|(code, message)| rpc_err(1001, message, &code))?;
            }
            let execution_timeout_ms = tools::effective_timeout_ms(&p.tool_name, p.timeout_ms);

            let remote_workspace = {
                let st = state.lock().await;
                // A session the store does not have keeps the local tool path
                // and its tool-level failure instead of becoming an RPC error.
                remote_tools::session_remote_workspace_optional(&st, &p.session_id)?
            };
            let command_shell_id = if p.tool_name == "Bash" && remote_workspace.is_none() {
                let catalog = {
                    let st = state.lock().await;
                    command_shell_catalog(&st)?
                };
                let effective_id = catalog.effective.as_ref().map(|shell| shell.id.clone());
                let shell_id = effective_id
                    .clone()
                    .or_else(|| Some(catalog.configured_id.clone()));
                let Some(effective) = catalog.effective.as_ref() else {
                    let result = shell_failure_result(
                        &p,
                        "SHELL_NOT_FOUND",
                        tools::shell::SHELL_MISSING_GUIDANCE,
                        shell_id,
                        call_started,
                    );
                    return serde_json::to_value(result)
                        .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"));
                };
                let Some(expected) = p.expected_command_shell_id.as_deref() else {
                    let result = shell_failure_result(
                        &p,
                        "COMMAND_SHELL_CHANGED",
                        "expectedCommandShellId is required for Bash execution",
                        Some(effective.id.clone()),
                        call_started,
                    );
                    return serde_json::to_value(result)
                        .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"));
                };
                let expected_dialect = p.expected_command_shell_dialect.as_deref();
                if expected_dialect != Some(effective.dialect.as_str()) || expected != effective.id
                {
                    let result = shell_changed_result(
                        &p,
                        expected,
                        expected_dialect,
                        Some(effective.id.clone()),
                        Some(effective.dialect.as_str()),
                        call_started,
                    );
                    return serde_json::to_value(result)
                        .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"));
                }
                effective_id
            } else {
                None
            };

            // Authorization follows the Host's own record of the session's
            // mode, run stage and snapshot (ADR mode-definitions), never the
            // mode the sidecar reports.
            let authorization = {
                let st = state.lock().await;
                if st.shutting_down {
                    return Err(rpc_err(1001, "host is shutting down", "HOST_SHUTTING_DOWN"));
                }
                let authorization = crate::mode_runs::authorization(&st.db, &p.session_id)
                    .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                    .ok_or_else(|| rpc_err(1007, "session not found", "SESSION_NOT_FOUND"))?;
                modes_rpc::verify_gate_call(&st, &p, remote_workspace.is_some())?;
                authorization
            };
            let durable_mode = authorization.mode.clone();
            // The current relay does not negotiate scoped-write enforcement with
            // the remote Host. Never forward the mutation without its boundary.
            if p.write_scope.is_some() && remote_workspace.is_some() {
                return Err(remote_tools::unsupported_write_scope());
            }

            // Register before permission evaluation so tools.abort can cancel
            // an approval wait even when the tool does not own a process.
            // Bash and image generation retain their existing process registry;
            // all other calls use a typed registry to avoid cross-tool ID reuse.
            let cancellation_receiver = if matches!(p.tool_name.as_str(), "Bash" | "GenerateImages")
            {
                // Background Bash tasks are detached from the turn and must
                // outlive a later Stop request.
                if remote_workspace.is_none() && p.tool_name == "Bash" && p.run_in_background {
                    None
                } else {
                    let mut st = state.lock().await;
                    match st.register_bash_cancellation(&p.session_id, &p.tool_call_id) {
                        Ok(receiver) => Some(receiver),
                        Err(error_code) => {
                            let result = shell_failure_result(
                                &p,
                                &error_code,
                                "another Bash call is already active for this tool call ID",
                                command_shell_id.clone(),
                                call_started,
                            );
                            return serde_json::to_value(result)
                                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"));
                        }
                    }
                }
            } else {
                let mut st = state.lock().await;
                match st.register_tool_cancellation(&p.session_id, &p.tool_call_id, &p.tool_name) {
                    Ok(receiver) => Some(receiver),
                    Err(error_code) => {
                        return Err(rpc_err(1008, "tool already executing", &error_code));
                    }
                }
            };

            let outcome: Result<Value, JsonRpcError> = async {
                let (
                    auto_decision,
                    workspace_path,
                    scratch_path,
                    external_path_permission,
                    pending_rx,
                    request_opt,
                    permission_shell_id,
                ) = {
                    let mut st = state.lock().await;
                    if st.shutting_down {
                        return Err(rpc_err(1001, "host is shutting down", "HOST_SHUTTING_DOWN"));
                    }
                    // Effective permission mode (D115): the session mode, or a
                    // subagent's own scope (ADR 0089), then the ceiling of the
                    // turn the call belongs to. External-path gating and the
                    // contract modes' hard deny are untouched by either.
                    let effective_pm = turn_permissions::effective_tool_mode(
                        &st.db,
                        &p.session_id,
                        p.turn_id.as_deref(),
                        p.permission_scope.as_deref(),
                        &authorization,
                    )
                    .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
                    let (ws, _) = file_batches::resolve_root(&st, &p)?;
                    let scratch = scratch::session_dir(&st.data_dir, &p.session_id);
                    let contained_roots = if workspace_only {
                        ContainedRoots::new()
                    } else {
                        local_contained_roots(
                            &st.data_dir,
                            &p.session_id,
                            remote_workspace.is_some(),
                        )
                    };
                    let external_path_permission = if remote_workspace.is_some() {
                        remote_tools::requires_external_permission(
                            ws.as_deref(),
                            &p.tool_name,
                            &p.args,
                        )
                    } else {
                        requires_external_path_permission(
                            ws.as_deref(),
                            &contained_roots,
                            &p.tool_name,
                            &p.args,
                        )
                    };
                    if workspace_only
                        && (remote_workspace.is_some()
                            || ws.is_none()
                            || ws.as_deref().map(Path::new) == scratch.as_deref()
                            || external_path_permission)
                    {
                        return Err(rpc_err(
                            1003,
                            "File line references require a local project path",
                            "PATH_OUTSIDE_WORKSPACE",
                        ));
                    }
                    let mut auto = st
                        .permissions
                        .evaluate_auto_with_permission_mode_and_risk_and_path(
                            PermissionEvaluationParams {
                                session_id: &p.session_id,
                                tool_name: &p.tool_name,
                                mode: authorization.permission_mode(),
                                permission_mode: &effective_pm,
                                session_grants: &st.session_grants,
                                declared_risk: p.declared_risk.as_deref(),
                                requires_external_path_permission: external_path_permission,
                                plan_safe_actions: p.plan_safe_actions.as_deref(),
                            },
                        );
                    // Write/Edit targeting the session scratch dir (D114) or
                    // visualization dir (D671) never touch the user's project —
                    // skip the prompt only while those roots remain valid.
                    // Execution revalidates visualization roots and runs the
                    // symlink-aware path resolver; root identity is not cached.
                    // A contract mode's hard deny is never bypassed.
                    if auto.is_none()
                        && contained_write_auto_allowed(
                            remote_workspace.is_some(),
                            authorization.permission_mode(),
                            &contained_roots,
                            &p.tool_name,
                            &p.args,
                        )
                    {
                        auto = Some(PermissionDecision::AllowOnce);
                    }
                    if let Some(decision) = auto {
                        (
                            Some(decision),
                            ws,
                            scratch,
                            external_path_permission,
                            None,
                            None,
                            command_shell_id.clone(),
                        )
                    } else {
                        let reason = if external_path_permission {
                            "Accesses a path outside the session workspace"
                        } else {
                            match p.tool_name.as_str() {
                                "Write" | "Edit" => "Modifies files in your workspace",
                                "Bash" => "Runs a shell command in your workspace",
                                name if name.starts_with("mcp_") => {
                                    "MCP server tool requires approval"
                                }
                                name if name.starts_with("plugin_") => {
                                    "Plugin-provided tool requires approval"
                                }
                                _ => "High-risk tool requires approval",
                            }
                        };
                        let (req, rx) = st.permissions.create_request_with_risk_and_shell(
                            crate::permissions::PermissionRequestParams {
                                session_id: &p.session_id,
                                tool_call_id: &p.tool_call_id,
                                tool_name: &p.tool_name,
                                args_preview: p.args.clone(),
                                reason,
                                declared_risk: p.declared_risk.as_deref(),
                                command_shell_id: command_shell_id.as_deref(),
                            },
                        );
                        st.register_pending_permission(
                            &req.request_id,
                            &req.session_id,
                            &req.tool_call_id,
                        );
                        (
                            None,
                            ws,
                            scratch,
                            external_path_permission,
                            Some(rx),
                            Some(req),
                            command_shell_id.clone(),
                        )
                    }
                };

                let prompted = request_opt.is_some();
                let mut permission_cancellation = cancellation_receiver.clone();
                let mut cancelled = tool_cancellation_requested(&permission_cancellation);
                if cancelled {
                    let _ = cancel_pending_permission(&state, &p).await;
                }
                if !cancelled {
                    if let Some(req) = request_opt {
                        let mut permission_params = json!({
                            "requestId": req.request_id,
                            "sessionId": req.session_id,
                            "toolCallId": req.tool_call_id,
                            "toolName": req.tool_name,
                            "risk": req.risk,
                            "argsPreview": req.args_preview,
                            "reason": req.reason
                        });
                        if let Some(shell_id) = req.command_shell_id.as_deref() {
                            permission_params["commandShellId"] = json!(shell_id);
                        }
                        emit_notification(&tx, "permissions.request", permission_params).await;
                        tracing::info!(
                            request_id = %req.request_id,
                            tool = %req.tool_name,
                            command_shell_id = permission_shell_id.as_deref(),
                            "permission required"
                        );
                    }
                }

                let final_decision = if cancelled {
                    PermissionDecision::Deny
                } else if let Some(d) = auto_decision {
                    cancelled = tool_cancellation_requested(&permission_cancellation);
                    if cancelled {
                        let _ = cancel_pending_permission(&state, &p).await;
                        PermissionDecision::Deny
                    } else {
                        d
                    }
                } else if let Some(rx) = pending_rx {
                    tokio::select! {
                        outcome = rx => match outcome {
                            Ok(d) => d,
                            _ => PermissionDecision::Deny,
                        },
                        _ = wait_for_tool_cancellation(&mut permission_cancellation) => {
                            let _ = cancel_pending_permission(&state, &p).await;
                            cancelled = true;
                            PermissionDecision::Deny
                        },
                    }
                } else {
                    PermissionDecision::Deny
                };
                cancelled = cancelled || tool_cancellation_requested(&permission_cancellation);
                if cancelled {
                    let _ = cancel_pending_permission(&state, &p).await;
                }
                // Everything up to here is approval: the auto-decision path costs
                // microseconds, the prompt path costs however long the user took.
                let permission_wait_ms = call_started.elapsed().as_millis() as u64;

                if matches!(final_decision, PermissionDecision::Deny) {
                    let _ = cancel_pending_permission(&state, &p).await;
                    let st = state.lock().await;
                    let mut denied_audit = json!({
                        "toolName": p.tool_name,
                        "toolCallId": p.tool_call_id,
                        "mode": durable_mode,
                        "externalPathPermission": external_path_permission,
                        "prompted": prompted,
                        "permissionWaitMs": permission_wait_ms,
                        "totalMs": call_started.elapsed().as_millis() as u64
                    });
                    if let Some(shell_id) = permission_shell_id.as_deref() {
                        denied_audit["commandShellId"] = json!(shell_id);
                    }
                    let _ = audit::append(
                        &st.db,
                        if cancelled {
                            "tool_aborted"
                        } else {
                            "tool_denied"
                        },
                        Some(&p.session_id),
                        denied_audit,
                    );
                    let error_code = if cancelled {
                        "TOOL_ABORTED"
                    } else if sessions::is_contract_mode(authorization.permission_mode())
                        && !PermissionManager::plan_mode_allows(&p.tool_name)
                    {
                        match p.tool_name.as_str() {
                            "Write" => "WRITE_DISABLED_IN_PLAN",
                            "Edit" => "EDIT_DISABLED_IN_PLAN",
                            name if name.starts_with("plugin_") => "PLUGIN_DISABLED_IN_PLAN",
                            _ => "TOOL_DISABLED_IN_PLAN",
                        }
                    } else {
                        "TOOL_DENIED"
                    };
                    let mut denied_result = json!({
                        "toolCallId": p.tool_call_id,
                        "ok": false,
                        "isError": true,
                        "content": {
                            "error": if cancelled { "tool aborted" } else { "permission denied" },
                            "code": error_code
                        },
                        "durationMs": 0,
                        "denied": !cancelled,
                        "errorCode": error_code
                    });
                    if let Some(shell_id) = permission_shell_id.as_deref() {
                        denied_result["commandShellId"] = json!(shell_id);
                    }
                    return Ok(denied_result);
                }

                if p.write_scope.is_none()
                    && matches!(final_decision, PermissionDecision::AllowSession)
                {
                    let mut st = state.lock().await;
                    st.session_grants
                        .entry(p.session_id.clone())
                        .or_default()
                        .push(p.tool_name.clone());
                }

                // Admission follows permission so approval waits do not occupy
                // execution capacity. Keep this permit through review, the
                // runner, and bookkeeping so every accepted call is bounded.
                // A subagent working in its own worktree (ADR 0329) is not
                // stopped while its session's worktree is held for a merge.
                let (tool_budget, own_worktree) = {
                    let st = state.lock().await;
                    let own = if remote_workspace.is_none()
                        && crate::file_resources::is_file_tool(&p.tool_name)
                    {
                        file_batches::verify_root(&st, &p, workspace_path.as_deref())?
                    } else {
                        matches!(
                            crate::session_worktrees::delegate::tool_root(
                                &st.db,
                                &p.session_id,
                                p.delegation_id.as_deref(),
                            ),
                            Ok(Some(_))
                        )
                    };
                    (st.tool_budget.clone(), own)
                };
                let file_resources = if remote_workspace.is_none()
                    && crate::file_resources::is_file_tool(&p.tool_name)
                {
                    let root = workspace_path.clone().map(PathBuf::from);
                    let roots = {
                        let st = state.lock().await;
                        local_contained_roots(&st.data_dir, &p.session_id, false)
                    };
                    let name = p.tool_name.clone();
                    let args = p.args.clone();
                    Some(
                        tokio::task::spawn_blocking(move || {
                            crate::file_resources::FileResources::resolve(
                                root.as_deref(),
                                &roots,
                                &name,
                                &args,
                                external_path_permission,
                            )
                        })
                        .await
                        .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,
                    )
                } else {
                    None
                };
                let mut admission_cancellation = cancellation_receiver.clone();
                let admitted = tokio::select! {
                    result = async {
                        if let Some(resources) = &file_resources {
                            tool_budget.acquire_files(&p.session_id, &p.tool_name, own_worktree,
                                resources.clone(), p.file_batch_ticket.clone()).await
                        } else if own_worktree {
                            tool_budget
                                .acquire_in_own_worktree(&p.session_id, &p.tool_name)
                                .await
                        } else {
                            tool_budget.acquire(&p.session_id, &p.tool_name).await
                        }
                    } => result,
                    _ = wait_for_tool_cancellation(&mut admission_cancellation) => {
                        return serde_json::to_value(tool_aborted_result(&p, call_started))
                            .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"));
                    }
                };
                let tool_permit = match admitted {
                    Ok(permit) => Arc::new(permit),
                    Err(error) => {
                        tracing::warn!(
                            tool = %p.tool_name,
                            session_id = %p.session_id,
                            error_code = error.code(),
                            "tool admission rejected"
                        );
                        let mut result = json!({
                            "toolCallId": p.tool_call_id,
                            "ok": false,
                            "isError": true,
                            "content": {
                                "error": error.message(),
                                "code": error.code()
                            },
                            "durationMs": call_started.elapsed().as_millis() as u64,
                            "denied": false,
                            "errorCode": error.code()
                        });
                        if let Some(shell_id) = permission_shell_id.as_deref() {
                            result["commandShellId"] = json!(shell_id);
                        }
                        return Ok(result);
                    }
                };

                let ws_path = workspace_path.map(PathBuf::from);
                tracing::debug!(tool = %p.tool_name, admission_wait_ms = tool_permit.wait_ms,
                    initial_wait_reason = tool_permit.initial_wait_reason, "tool admitted");
                if let Some(resources) = &file_resources {
                    let roots = {
                        let st = state.lock().await;
                        file_batches::verify_root(
                            &st,
                            &p,
                            ws_path.as_deref().and_then(Path::to_str),
                        )?;
                        if p.write_scope.is_some()
                            && crate::mode_runs::authorization(&st.db, &p.session_id)
                                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                                .as_ref()
                                != Some(&authorization)
                        {
                            return Err(rpc_err(
                                1002,
                                "Session mode changed before the scoped write ran",
                                "TOOL_CONTEXT_CHANGED",
                            ));
                        }
                        local_contained_roots(&st.data_dir, &p.session_id, false)
                    };
                    resources
                        .validate(
                            ws_path.as_deref(),
                            &roots,
                            &p.tool_name,
                            &p.args,
                            external_path_permission,
                        )
                        .map_err(|e| rpc_err(1000, e, "TOOL_FAILED"))?;
                }
                let (data_dir, hashline_store, worktree_env) = {
                    let st = state.lock().await;
                    (
                        st.data_dir.clone(),
                        st.hashline.clone(),
                        crate::session_worktrees::delegate::tool_env(
                            &st.db,
                            &p.session_id,
                            p.delegation_id.as_deref(),
                        ),
                    )
                };
                let write_scope = p
                    .write_scope
                    .as_ref()
                    .map(|scope| {
                        ws_path
                            .as_deref()
                            .and_then(|root| scope.bind(root))
                            .ok_or_else(|| {
                                rpc_err(
                                    1003,
                                    "Cannot verify the local workspace for this write scope",
                                    "WRITE_SCOPE_UNAVAILABLE",
                                )
                            })
                    })
                    .transpose()?;
                let hashline_ctx = tools::HashlineContext {
                    session_id: p.session_id.as_str(),
                    store: &hashline_store,
                };
                // Remote-workspace sessions get no visualization root (D671).
                let visualization_path = if remote_workspace.is_some() {
                    None
                } else {
                    visualizations::session_dir(&data_dir, &p.session_id)
                };
                let review_roots = if write_scope.is_some() {
                    ContainedRoots::new()
                } else {
                    local_contained_roots(&data_dir, &p.session_id, false)
                };
                let pending_review = if remote_workspace.is_some()
                    || write_scope.as_ref().is_some_and(|scope| {
                        !tools::can_review_scoped_write(
                            ws_path.as_deref(),
                            &review_roots,
                            &p.args,
                            scope,
                        )
                    }) {
                    None
                } else {
                    review::prepare_change(
                        &data_dir,
                        &p.session_id,
                        &p.tool_call_id,
                        ws_path.as_deref(),
                        &review_roots,
                        &p.tool_name,
                        &p.args,
                        write_scope.is_none() && external_path_permission,
                    )
                    .unwrap_or_else(|error| {
                        tracing::warn!(
                            session_id = %p.session_id,
                            tool_call_id = %p.tool_call_id,
                            error = %error,
                            "review snapshot preparation failed"
                        );
                        None
                    })
                };
                if tool_cancellation_requested(&cancellation_receiver) {
                    if let Some(pending) = pending_review {
                        review::discard_change(pending);
                    }
                    return serde_json::to_value(tool_aborted_result(&p, call_started))
                        .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"));
                }
                let mut bash_options = None;
                if p.tool_name == "Bash" && remote_workspace.is_none() {
                    let (shell_id, cancellation) = {
                        let st = state.lock().await;
                        let catalog = command_shell_catalog(&st)?;
                        let Some(effective) = catalog.effective.as_ref() else {
                            let result = shell_failure_result(
                                &p,
                                "SHELL_NOT_FOUND",
                                tools::shell::SHELL_MISSING_GUIDANCE,
                                Some(catalog.configured_id.clone()),
                                call_started,
                            );
                            return serde_json::to_value(result)
                                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"));
                        };
                        let Some(expected) = p.expected_command_shell_id.as_deref() else {
                            let result = shell_failure_result(
                                &p,
                                "COMMAND_SHELL_CHANGED",
                                "expectedCommandShellId is required for Bash execution",
                                Some(effective.id.clone()),
                                call_started,
                            );
                            return serde_json::to_value(result)
                                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"));
                        };
                        let expected_dialect = p.expected_command_shell_dialect.as_deref();
                        if expected_dialect != Some(effective.dialect.as_str())
                            || expected != effective.id
                        {
                            let result = shell_changed_result(
                                &p,
                                expected,
                                expected_dialect,
                                Some(effective.id.clone()),
                                Some(effective.dialect.as_str()),
                                call_started,
                            );
                            return serde_json::to_value(result)
                                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"));
                        }
                        (effective.id.clone(), cancellation_receiver.clone())
                    };
                    bash_options = Some(tools::BashExecutionOptions {
                        session_id: p.session_id.clone(),
                        tool_call_id: p.tool_call_id.clone(),
                        command_shell_id: shell_id,
                        timeout_ms: execution_timeout_ms,
                        cancellation,
                        output_tx: Some(tx.clone()),
                        extra_env: worktree_env.clone(),
                        run_in_background: p.run_in_background,
                        yield_after_initial_wait: p.yield_after_initial_wait
                            && p.turn_id.is_some()
                            && p.delegation_id.is_none()
                            && p.permission_scope.is_none()
                            && p.mode_gate.is_none()
                            && remote_workspace.is_none(),
                        continuation_turn_id: if notify_on_exit {
                            p.turn_id.clone()
                        } else {
                            None
                        },
                        app_state: Some(state.clone()),
                    });
                }

                let mut result = if p.tool_name == "TodoWrite" {
                    // The checklist body owns its own trusted-transport checks,
                    // the atomic write, and the after-commit notification.
                    todos::execute_write(&state, &tx, &p, call_started).await?
                } else if tools::is_desktop_dispatched(&p.tool_name) {
                    // Plugin and MCP dispatch has its own bounded default, sized
                    // to outlast Electron's budgets; command-shell timeout
                    // semantics apply only to Bash.
                    execute_plugin_tool(
                        &state,
                        &tx,
                        &p,
                        tools::desktop_dispatch_timeout_ms(p.timeout_ms),
                        authorization.plugin_mode(),
                    )
                    .await
                } else if scheduled_tools::recognizes(&p.tool_name) {
                    let st = state.lock().await;
                    scheduled_tools::execute(&st, &p)
                } else if let Some(remote) = remote_workspace.clone() {
                    remote_tools::execute_remote_tool(
                        &state,
                        &tx,
                        &p,
                        remote,
                        cancellation_receiver.clone(),
                    )
                    .await
                } else {
                    let execute = tools::execute_tool_with_file_lease(
                        ws_path.as_deref(),
                        scratch_path.as_deref().filter(|_| !workspace_only),
                        &p.tool_name,
                        &p.args,
                        tools::ToolExecutionOptions {
                            timeout_ms: execution_timeout_ms,
                            bash_options,
                            allow_external_paths: external_path_permission && !workspace_only,
                            hashline: Some(hashline_ctx),
                            visualization_root: visualization_path
                                .as_deref()
                                .filter(|_| !workspace_only),
                            write_scope,
                        },
                        Some(tool_permit.clone()),
                        file_resources.clone(),
                    );
                    if matches!(p.tool_name.as_str(), "Read" | "Glob" | "Grep") {
                        let mut read_cancellation = cancellation_receiver.clone();
                        tokio::select! {
                            result = execute => result,
                            _ = wait_for_tool_cancellation(&mut read_cancellation) => {
                                tool_aborted_result(&p, call_started)
                            }
                        }
                    } else {
                        execute.await
                    }
                };
                result.tool_call_id = p.tool_call_id.clone();

                if let Some(pending) = pending_review {
                    if result.ok {
                        match review::finalize_change(&pending) {
                            Ok(change) => {
                                if let Some(object) = result.content.as_object_mut() {
                                    object.insert(
                                        "review".to_string(),
                                        serde_json::to_value(change).map_err(|error| {
                                            rpc_err(1000, error.to_string(), "INTERNAL")
                                        })?,
                                    );
                                }
                            }
                            Err(error) => {
                                tracing::warn!(
                                    session_id = %p.session_id,
                                    tool_call_id = %p.tool_call_id,
                                    error = %error,
                                    "review snapshot finalization failed"
                                );
                                review::discard_change(pending);
                            }
                        }
                    } else {
                        review::discard_change(pending);
                    }
                }

                // ADR 0329: a session that resolved its merge conflict (or
                // aborted the merge) drops its conflict badge before the turn
                // ends and the sidebar refreshes.
                if p.delegation_id.is_none()
                    && matches!(p.tool_name.as_str(), "Write" | "Edit" | "Bash")
                {
                    crate::session_worktrees::lifecycle::refresh_conflict_status(
                        &state,
                        &crate::session_worktrees::git::GitRunner::default(),
                        &p.session_id,
                    )
                    .await;
                }

                let mut st = state.lock().await;
                // A request rejected by its one-shot boundary cannot leave
                // behind a session-wide grant. Explicit approvals for writes
                // that landed still follow the ordinary permission contract.
                if p.write_scope.is_some()
                    && result.ok
                    && matches!(final_decision, PermissionDecision::AllowSession)
                {
                    st.session_grants
                        .entry(p.session_id.clone())
                        .or_default()
                        .push(p.tool_name.clone());
                }
                // Scratch files are temp by definition: keep them out of the
                // artifacts table so the work panel file list only shows
                // workspace deliverables (D114).
                let result_root = result.content.get("root").and_then(|v| v.as_str());
                if remote_workspace.is_none()
                    && result.ok
                    && result_root == Some("workspace")
                    && matches!(p.tool_name.as_str(), "Write" | "Edit")
                {
                    if let Some(rel) = result.content.get("path").and_then(|v| v.as_str()) {
                        let abs = match ws_path.as_deref() {
                            Some(root) => root.join(rel).to_string_lossy().to_string(),
                            None => rel.to_string(),
                        };
                        let op = if p.tool_name == "Write" {
                            "write"
                        } else {
                            "edit"
                        };
                        let _ = artifacts::record(
                            &st.db,
                            &p.session_id,
                            &abs,
                            op,
                            p.turn_id.as_deref(),
                        );
                    }
                }
                // `overhead_ms` is the host's own share outside approval and the
                // tool body: workspace resolution, the state lock, artifacts and
                // audit writes. It should stay near zero; if it does not, the
                // bottleneck is host-core itself rather than the user or the model.
                let total_ms = call_started.elapsed().as_millis() as u64;
                let overhead_ms =
                    total_ms.saturating_sub(permission_wait_ms.saturating_add(result.duration_ms));
                let mut execute_audit = json!({
                    "toolName": p.tool_name,
                    "toolCallId": p.tool_call_id,
                    "externalPathPermission": external_path_permission,
                    "ok": result.ok,
                    "durationMs": result.duration_ms,
                    "errorCode": result.error_code,
                    "prompted": prompted,
                    "permissionWaitMs": permission_wait_ms,
                    "admissionWaitMs": tool_permit.wait_ms,
                    "admissionInitialWaitReason": tool_permit.initial_wait_reason,
                    "overheadMs": overhead_ms,
                    "totalMs": total_ms
                });
                if let Some(shell_id) = result.command_shell_id.as_deref() {
                    execute_audit["commandShellId"] = json!(shell_id);
                }
                let _ = audit::append(&st.db, "tool_execute", Some(&p.session_id), execute_audit);

                serde_json::to_value(result).map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))
            }
            .await;
            clear_bash_cancellation(&state, &p).await;
            clear_tool_cancellation(&state, &p).await;
            modes_rpc::record_gate_call(&state, &p, &outcome).await;
            outcome
        }

        "tools.abort" => {
            let session_id = params
                .get("sessionId")
                .and_then(|value| value.as_str())
                .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
            let tool_call_id = params
                .get("toolCallId")
                .and_then(|value| value.as_str())
                .ok_or_else(|| rpc_err(1002, "toolCallId required", "INVALID_PARAMS"))?;
            let tool_name = params.get("toolName").and_then(Value::as_str);
            let mut st = state.lock().await;
            let permission_found = st.cancel_pending_permission(session_id, tool_call_id);
            let (cancellation_found, queued) = match tool_name {
                Some("Bash" | "GenerateImages") => st.abort_or_queue_bash(session_id, tool_call_id),
                Some(name) => st.abort_or_queue_tool(session_id, tool_call_id, name),
                None => {
                    let active_tool = st.abort_active_tool(session_id, tool_call_id);
                    if active_tool {
                        (true, false)
                    } else {
                        st.abort_or_queue_bash(session_id, tool_call_id)
                    }
                }
            };
            let remote = match sessions::session_summary(&st.db, session_id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
            {
                Some(_) => remote_tools::session_remote_workspace(&st, session_id)?.is_some(),
                None => false,
            };
            if remote {
                send_notification(
                    &tx,
                    "tools.remoteAbort",
                    json!({ "sessionId": session_id, "toolCallId": tool_call_id }),
                );
            }
            let found = cancellation_found || permission_found;
            Ok(json!({
                "ok": true,
                "found": found,
                "queued": queued,
                "aborted": found || queued
            }))
        }

        "permissions.evaluate" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let tool_name = params
                .get("toolName")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let declared_risk = params.get("declaredRisk").and_then(|v| v.as_str());
            let plan_safe_actions: Option<Vec<String>> = params
                .get("planSafeActions")
                .and_then(|v| v.as_array())
                .map(|items| {
                    items
                        .iter()
                        .filter_map(|item| item.as_str().map(str::to_string))
                        .collect()
                })
                .filter(|items: &Vec<String>| !items.is_empty());
            let st = state.lock().await;
            let Some(authorization) = crate::mode_runs::authorization(&st.db, session_id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
            else {
                return Err(rpc_err(1007, "session not found", "SESSION_NOT_FOUND"));
            };
            let effective_pm = turn_permissions::effective_tool_mode(
                &st.db,
                session_id,
                params.get("turnId").and_then(Value::as_str),
                None,
                &authorization,
            )
            .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            let args = params.get("args").cloned().unwrap_or_else(|| json!({}));
            let workspace_path = resolve_tool_workspace_for_call(&st, session_id, &args)?;
            let external_path_permission =
                if remote_tools::session_remote_workspace(&st, session_id)?.is_some() {
                    remote_tools::requires_external_permission(
                        workspace_path.as_deref(),
                        tool_name,
                        &args,
                    )
                } else {
                    requires_external_path_permission(
                        workspace_path.as_deref(),
                        &local_contained_roots(&st.data_dir, session_id, false),
                        tool_name,
                        &args,
                    )
                };
            let decision = st
                .permissions
                .evaluate_auto_with_permission_mode_and_risk_and_path(PermissionEvaluationParams {
                    session_id,
                    tool_name,
                    mode: authorization.permission_mode(),
                    permission_mode: &effective_pm,
                    session_grants: &st.session_grants,
                    declared_risk,
                    requires_external_path_permission: external_path_permission,
                    plan_safe_actions: plan_safe_actions.as_deref(),
                });
            Ok(json!({
                "decision": decision,
                "risk": PermissionManager::tool_risk_with_declared(tool_name, declared_risk),
                "externalPathPermission": external_path_permission
            }))
        }
        "permissions.resolve" => {
            let request_id = params
                .get("requestId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "requestId required", "INVALID_PARAMS"))?;
            let decision_raw = params
                .get("decision")
                .and_then(|v| v.as_str())
                .unwrap_or("deny");
            let decision = match decision_raw {
                "allow-once" => PermissionDecision::AllowOnce,
                "allow-session" => PermissionDecision::AllowSession,
                _ => PermissionDecision::Deny,
            };
            let mut st = state.lock().await;
            st.resolve_permission(request_id, decision)
                .map_err(|code| {
                    let c = if code == "NOT_FOUND" { 1007 } else { 1000 };
                    rpc_err(c, code.clone(), &code)
                })?;
            Ok(json!({ "ok": true }))
        }
        "permissions.listSessionGrants" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let st = state.lock().await;
            Ok(json!({
                "grants": st.session_grants.get(session_id).cloned().unwrap_or_default()
            }))
        }
        "permissions.clearSessionGrants" => {
            let session_id = params
                .get("sessionId")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let mut st = state.lock().await;
            st.session_grants.remove(session_id);
            Ok(json!({ "ok": true }))
        }
        "permissions.pending" => {
            // Pending requests are Host state (D374/D375): a client that
            // attaches after `permissions.request` was emitted reads the open
            // set here and answers through the unchanged `permissions.resolve`.
            let session_id = params.get("sessionId").and_then(|v| v.as_str());
            let st = state.lock().await;
            Ok(json!({ "requests": st.permissions.pending_requests(session_id) }))
        }

        "plugins.setLocale" => {
            // The desktop shell owns the app language — `settings.language`, or
            // the OS locale while that is `auto` — so it pushes the resolved
            // locale here whenever it changes. Rows then read their display
            // strings from the matching `i18n` entry, and a locale change needs
            // no registry rewrite.
            let locale = params.get("locale").and_then(Value::as_str).unwrap_or("");
            let mut st = state.lock().await;
            st.plugins.set_locale(locale);
            Ok(json!({ "ok": true, "locale": st.plugins.locale() }))
        }

        "plugins.list" => {
            let st = state.lock().await;
            Ok(json!({ "plugins": st.plugins.list() }))
        }
        "plugins.resolveExecution" => {
            let execution_id = params
                .get("executionId")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "executionId required", "INVALID_PARAMS"))?;
            let sender = {
                let mut st = state.lock().await;
                st.plugin_execs.remove(execution_id)
            };
            match sender {
                Some(sender) => {
                    let _ = sender.send(params.clone());
                    Ok(json!({ "ok": true }))
                }
                None => Err(rpc_err(1003, "unknown executionId", "NOT_FOUND")),
            }
        }
        "plugins.loadDev" => {
            let path = params
                .get("path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?;
            let mut st = state.lock().await;
            let plugin = st.plugins.load_dev(path).map_err(|e| {
                let msg = e.to_string();
                if msg.contains("PLUGIN_INVALID") {
                    rpc_err(1009, msg, "PLUGIN_INVALID")
                } else {
                    rpc_err(1010, msg, "PLUGIN_LOAD_FAILED")
                }
            })?;
            // A development plugin owns its declared provider rows the same way
            // an installed one does.
            if let Err(error) =
                crate::plugins::reconcile_plugin(&st.db, &st.secrets, &st.plugins, &plugin.id, true)
            {
                tracing::warn!(plugin = %plugin.id, %error, "plugin provider sync failed");
            }
            Ok(json!({ "plugin": plugin }))
        }
        "plugins.enable" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let mut st = state.lock().await;
            let plugin = st
                .plugins
                .set_enabled(id, true)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            if let Some(current) = plugin.as_ref() {
                if let Err(error) = crate::plugins::reconcile_plugin(
                    &st.db,
                    &st.secrets,
                    &st.plugins,
                    &current.id,
                    true,
                ) {
                    tracing::warn!(plugin = %current.id, %error, "plugin provider sync failed");
                }
            }
            Ok(json!({ "plugin": plugin }))
        }
        "plugins.disable" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let mut st = state.lock().await;
            let plugin = st
                .plugins
                .set_enabled(id, false)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            // The declaration still exists, so the rows stay and are turned
            // off: a re-enable restores the credential the user already gave.
            if plugin.is_some() {
                if let Err(error) = crate::plugins::set_plugin_providers_enabled(&st.db, id, false)
                {
                    tracing::warn!(plugin = id, %error, "plugin provider disable failed");
                }
            }
            Ok(json!({ "plugin": plugin }))
        }
        "plugins.uninstall" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let mut st = state.lock().await;
            let ok = st
                .plugins
                .uninstall(id)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            if ok {
                if let Err(error) = crate::plugins::remove_plugin_providers(&st.db, &st.secrets, id)
                {
                    tracing::warn!(plugin = id, %error, "plugin provider removal failed");
                }
            }
            Ok(json!({ "ok": ok }))
        }
        "plugins.getPermissions" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let plugin = st.plugins.list().into_iter().find(|p| p.id == id);
            Ok(json!({
                "permissions": plugin.map(|p| p.permissions).unwrap_or_default()
            }))
        }
        "plugins.installFromPath" => {
            let path = params
                .get("path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?;
            let enable = params
                .get("enable")
                .and_then(|v| v.as_bool())
                .unwrap_or(true);
            let granted = params
                .get("grantedPermissions")
                .cloned()
                .and_then(|v| serde_json::from_value::<Vec<String>>(v).ok());
            let mut st = state.lock().await;
            let result = st
                .plugins
                .install_from_path(
                    path,
                    crate::plugins::InstallOptions {
                        source: "installed".into(),
                        enable,
                        marketplace: None,
                        expected_shasum: None,
                        auto_update: false,
                        granted_permissions: granted,
                    },
                )
                .map_err(plugin_err)?;
            Ok(json!({ "result": result }))
        }
        "plugins.installFromPackage" => {
            let path = params
                .get("path")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?;
            let enable = params
                .get("enable")
                .and_then(|v| v.as_bool())
                .unwrap_or(true);
            let granted = params
                .get("grantedPermissions")
                .cloned()
                .and_then(|v| serde_json::from_value::<Vec<String>>(v).ok());
            let expected_shasum = params
                .get("expectedShasum")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string());
            let mut st = state.lock().await;
            let result = st
                .plugins
                .install_from_package(
                    path,
                    crate::plugins::InstallOptions {
                        source: "installed".into(),
                        enable,
                        marketplace: None,
                        expected_shasum,
                        auto_update: false,
                        granted_permissions: granted,
                    },
                )
                .map_err(plugin_err)?;
            Ok(json!({ "result": result }))
        }
        "plugins.grantPermissions" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let permissions = params
                .get("permissions")
                .cloned()
                .and_then(|v| serde_json::from_value::<Vec<String>>(v).ok())
                .unwrap_or_default();
            let mut st = state.lock().await;
            let plugin = st
                .plugins
                .grant_permissions(id, permissions)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "plugin": plugin }))
        }
        "plugins.revokePermissions" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let permissions = params
                .get("permissions")
                .cloned()
                .and_then(|v| serde_json::from_value::<Vec<String>>(v).ok())
                .unwrap_or_default();
            let mut st = state.lock().await;
            let plugin = st
                .plugins
                .revoke_permissions(id, permissions)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "plugin": plugin }))
        }
        "plugins.setAutoUpdate" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let enabled = params
                .get("enabled")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            let mut st = state.lock().await;
            let plugin = st
                .plugins
                .set_auto_update(id, enabled)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "plugin": plugin }))
        }
        "plugins.setScope" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let scope = parse_scope(&params)?;
            let mut st = state.lock().await;
            let plugin = st
                .plugins
                .set_scope(id, scope)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "plugin": plugin }))
        }

        "mcp.list" => {
            let (level, project_path) = parse_capability_query(&params)?;
            let mut st = state.lock().await;
            let servers = st
                .mcp_servers
                .list(level, project_path.as_deref())
                .map_err(scope_err)?;
            Ok(json!({ "servers": servers, "statuses": [] }))
        }
        "mcp.active" => {
            let project_path = params.get("projectPath").and_then(Value::as_str);
            let mut st = state.lock().await;
            let servers = st.mcp_servers.active_for(project_path).map_err(scope_err)?;
            Ok(json!({ "servers": servers, "statuses": [] }))
        }
        "mcp.upsert" => {
            let input: crate::mcp_servers::McpServerInput =
                serde_json::from_value(params.get("server").cloned().unwrap_or(params.clone()))
                    .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
            let mut st = state.lock().await;
            let server = st.mcp_servers.upsert(input).map_err(scope_err)?;
            Ok(json!({ "server": server }))
        }
        "mcp.remove" => {
            let id = require_id(&params)?;
            let (level, project_path) = parse_capability_query(&params)?;
            let mut st = state.lock().await;
            let ok = st
                .mcp_servers
                .remove(&id, Some(level), project_path.as_deref())
                .map_err(scope_err)?;
            Ok(json!({ "ok": ok }))
        }
        "mcp.setEnabled" => {
            let id = require_id(&params)?;
            let enabled = params
                .get("enabled")
                .and_then(Value::as_bool)
                .unwrap_or(false);
            let (level, project_path) = parse_capability_query(&params)?;
            let mut st = state.lock().await;
            let server = st
                .mcp_servers
                .set_enabled(&id, enabled, Some(level), project_path.as_deref())
                .map_err(scope_err)?;
            Ok(json!({ "server": server }))
        }
        "mcp.setScope" => {
            let id = require_id(&params)?;
            let scope = parse_scope(&params)?;
            let mut st = state.lock().await;
            let server = st.mcp_servers.set_scope(&id, scope).map_err(scope_err)?;
            Ok(json!({ "server": server }))
        }
        "mcp.transfer" => {
            let id = require_id(&params)?;
            let from = parse_capability_target(&params, "from")?;
            let to = parse_capability_target(&params, "to")?;
            let mut st = state.lock().await;
            let server = st
                .mcp_servers
                .transfer(&id, &from, &to)
                .map_err(scope_err)?;
            Ok(json!({ "server": server }))
        }

        "skills.list" => {
            let (level, project_path) = parse_capability_query(&params)?;
            let mut st = state.lock().await;
            let skills = st
                .user_skills
                .list(level, project_path.as_deref())
                .map_err(skill_err)?;
            Ok(json!({ "skills": skills }))
        }
        "skills.active" => {
            let project_path = params.get("projectPath").and_then(Value::as_str);
            let mut st = state.lock().await;
            let skills = st.user_skills.active_for(project_path).map_err(skill_err)?;
            Ok(json!({ "skills": skills }))
        }
        "skills.disabledBuiltins" => {
            let st = state.lock().await;
            Ok(json!({ "disabled": st.user_skills.disabled_builtins() }))
        }
        "skills.setBuiltinEnabled" => {
            let id = require_id(&params)?;
            let enabled = params
                .get("enabled")
                .and_then(Value::as_bool)
                .unwrap_or(false);
            let mut st = state.lock().await;
            let id = st
                .user_skills
                .set_builtin_enabled(&id, enabled)
                .map_err(skill_err)?;
            Ok(json!({ "id": id, "enabled": enabled }))
        }
        "skills.create" => {
            let input = parse_skill_input(&params)?;
            let mut st = state.lock().await;
            let skill = st.user_skills.create(input).map_err(skill_err)?;
            Ok(json!({ "skill": skill }))
        }
        "skills.import" => {
            let source = params
                .get("path")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?
                .to_string();
            let input = parse_skill_input(&params)?;
            let mut st = state.lock().await;
            let skill = st.user_skills.import(&source, input).map_err(skill_err)?;
            Ok(json!({ "skill": skill }))
        }
        "skills.update" => {
            let id = require_id(&params)?;
            let input = parse_skill_input(&params)?;
            let mut st = state.lock().await;
            let skill = st.user_skills.update(&id, input).map_err(skill_err)?;
            Ok(json!({ "skill": skill }))
        }
        "skills.read" => {
            let id = require_id(&params)?;
            let level = params
                .get("level")
                .and_then(Value::as_str)
                .map(|value| CapabilityLevel::parse(Some(value)))
                .transpose()
                .map_err(|error| rpc_err(1002, error.to_string(), "INVALID_PARAMS"))?;
            let project_path = params.get("projectPath").and_then(Value::as_str);
            let mut st = state.lock().await;
            match st
                .user_skills
                .read(&id, level, project_path)
                .map_err(skill_err)?
            {
                Some((skill, body)) => Ok(json!({ "skill": skill, "body": body })),
                None => Ok(json!({ "skill": null, "body": null })),
            }
        }
        "skills.remove" => {
            let id = require_id(&params)?;
            let level = params
                .get("level")
                .and_then(Value::as_str)
                .map(|value| CapabilityLevel::parse(Some(value)))
                .transpose()
                .map_err(|error| rpc_err(1002, error.to_string(), "INVALID_PARAMS"))?;
            let project_path = params.get("projectPath").and_then(Value::as_str);
            let mut st = state.lock().await;
            let ok = st
                .user_skills
                .remove(&id, level, project_path)
                .map_err(skill_err)?;
            Ok(json!({ "ok": ok }))
        }
        "skills.setEnabled" => {
            let id = require_id(&params)?;
            let enabled = params
                .get("enabled")
                .and_then(Value::as_bool)
                .unwrap_or(false);
            let (level, project_path) = parse_capability_query(&params)?;
            let mut st = state.lock().await;
            let skill = st
                .user_skills
                .set_enabled(&id, enabled, Some(level), project_path.as_deref())
                .map_err(skill_err)?;
            Ok(json!({ "skill": skill }))
        }
        "skills.setScope" => {
            let id = require_id(&params)?;
            let scope = parse_scope(&params)?;
            let mut st = state.lock().await;
            let skill = st.user_skills.set_scope(&id, scope).map_err(skill_err)?;
            Ok(json!({ "skill": skill }))
        }
        "skills.transfer" => {
            let id = require_id(&params)?;
            let from = parse_capability_target(&params, "from")?;
            let to = parse_capability_target(&params, "to")?;
            let mut st = state.lock().await;
            let skill = st
                .user_skills
                .transfer(&id, &from, &to)
                .map_err(skill_err)?;
            Ok(json!({ "skill": skill }))
        }

        "agents.list" => {
            let mut st = state.lock().await;
            Ok(json!({ "subagents": st.user_subagents.list().map_err(subagent_err)? }))
        }
        "agents.active" => {
            let project_path = params.get("projectPath").and_then(Value::as_str);
            let mut st = state.lock().await;
            Ok(
                json!({ "subagents": st.user_subagents.active_for(project_path).map_err(subagent_err)? }),
            )
        }
        "agents.create" => {
            let input = parse_subagent_input(&params)?;
            let mut st = state.lock().await;
            let subagent = st.user_subagents.create(input).map_err(subagent_err)?;
            Ok(json!({ "subagent": subagent }))
        }
        "agents.update" => {
            let id = require_id(&params)?;
            let input = parse_subagent_input(&params)?;
            let mut st = state.lock().await;
            let subagent = st.user_subagents.update(&id, input).map_err(subagent_err)?;
            Ok(json!({ "subagent": subagent }))
        }
        "agents.read" => {
            let id = require_id(&params)?;
            let mut st = state.lock().await;
            match st.user_subagents.read(&id).map_err(subagent_err)? {
                Some((subagent, body)) => Ok(json!({ "subagent": subagent, "body": body })),
                None => Ok(json!({ "subagent": null, "body": null })),
            }
        }
        "agents.remove" => {
            let id = require_id(&params)?;
            let mut st = state.lock().await;
            let ok = st.user_subagents.remove(&id).map_err(subagent_err)?;
            Ok(json!({ "ok": ok }))
        }
        "agents.setEnabled" => {
            let id = require_id(&params)?;
            let enabled = params
                .get("enabled")
                .and_then(Value::as_bool)
                .unwrap_or(false);
            let mut st = state.lock().await;
            let subagent = st
                .user_subagents
                .set_enabled(&id, enabled)
                .map_err(subagent_err)?;
            Ok(json!({ "subagent": subagent }))
        }
        "agents.setScope" => {
            let id = require_id(&params)?;
            let scope = parse_scope(&params)?;
            let mut st = state.lock().await;
            let subagent = st
                .user_subagents
                .set_scope(&id, scope)
                .map_err(subagent_err)?;
            Ok(json!({ "subagent": subagent }))
        }
        "agents.disabledBuiltins" => {
            let st = state.lock().await;
            Ok(json!({ "disabled": st.user_subagents.disabled_builtins() }))
        }
        "agents.setBuiltinEnabled" => {
            let id = require_id(&params)?;
            let enabled = params
                .get("enabled")
                .and_then(Value::as_bool)
                .unwrap_or(false);
            let mut st = state.lock().await;
            let id = st
                .user_subagents
                .set_builtin_enabled(&id, enabled)
                .map_err(subagent_err)?;
            Ok(json!({ "id": id, "enabled": enabled }))
        }

        "network.configureSystemProxyRelay" => {
            let url = params
                .get("url")
                .and_then(Value::as_str)
                .ok_or_else(|| rpc_err(1002, "url required", "INVALID_PARAMS"))?;
            crate::network_proxy::set_system_proxy_relay(url)
                .map_err(|message| rpc_err(1002, message, "INVALID_PARAMS"))?;
            Ok(json!({ "ok": true }))
        }
        "market.reviewSummaries" | "market.reviewTickers" | "market.reviews" => {
            plugin_reviews_rpc::handle(&state, method, params).await
        }
        "market.refresh" => {
            let force = params
                .get("force")
                .and_then(|v| v.as_bool())
                .unwrap_or(true);
            let st = state.lock().await;
            let meta = st.plugins.refresh_market(force).map_err(plugin_err)?;
            Ok(meta)
        }
        "market.browse" => market_browse_rpc::browse(&state, params).await,
        "market.search" => {
            let query = params.get("query").and_then(|v| v.as_str());
            let category = params.get("category").and_then(|v| v.as_str());
            let st = state.lock().await;
            let plugins = st
                .plugins
                .market_search(query, category)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({
                "plugins": plugins,
                "providerId": "official",
                "sourceUrl": st.plugins.market_source_url(),
            }))
        }
        "market.getDetail" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let st = state.lock().await;
            let plugin = st.plugins.market_get(id).map_err(plugin_err)?;
            Ok(json!({ "plugin": plugin }))
        }
        "market.install" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            let version = params.get("version").and_then(|v| v.as_str());
            let enable = params
                .get("enable")
                .and_then(|v| v.as_bool())
                .unwrap_or(true);
            let auto_update = params
                .get("autoUpdate")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            let granted = params
                .get("grantedPermissions")
                .cloned()
                .and_then(|v| serde_json::from_value::<Vec<String>>(v).ok());
            // An install outlives one request from the interface's point of
            // view: it resolves where the package is, downloads it from one
            // mirror after another, verifies it and registers it. Every one of
            // those steps is worth showing, which is what the observer does,
            // and the token is what the cancel channel flips.
            let cancel = crate::plugins::CancelToken::default();
            // Armed outside AppState: cancelInstall must flip this flag while
            // install still holds the state lock for the download.
            crate::plugins::progress::arm_active_cancel(&cancel);
            let mut observer = RpcInstallObserver {
                tx: tx.clone(),
                cancel: cancel.clone(),
                last: None,
                last_phase: None,
            };
            let mut st = state.lock().await;
            st.plugins.set_install_cancel(Some(cancel));
            let outcome = st.plugins.install_from_market_observed(
                id,
                version,
                enable,
                auto_update,
                granted,
                &mut observer,
            );
            // Whatever happened, nothing is cancellable any more: a token left
            // in place would answer the next cancel for an install that is
            // already over.
            st.plugins.set_install_cancel(None);
            let result = outcome.map_err(plugin_err)?;
            Ok(json!({ "result": result }))
        }
        "market.cancelInstall" => {
            let id = params
                .get("id")
                .and_then(|v| v.as_str())
                .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
            // Do not take AppState: the install holds that lock while bytes
            // arrive, and waiting on it would make cancel a no-op.
            let cancelled = crate::plugins::progress::cancel_active_install();
            Ok(json!({ "cancelled": cancelled, "id": id }))
        }
        "market.checkUpdates" => {
            let refresh_remote = params
                .get("refreshRemote")
                .and_then(|v| v.as_bool())
                .unwrap_or(true);
            let mut st = state.lock().await;
            let updates = st
                .plugins
                .check_updates(refresh_remote)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "updates": updates, "plugins": st.plugins.list() }))
        }
        "market.applyUpdates" => {
            let only_auto = params
                .get("onlyAuto")
                .and_then(|v| v.as_bool())
                .unwrap_or(true);
            let mut st = state.lock().await;
            let results = st.plugins.apply_updates(only_auto).map_err(plugin_err)?;
            Ok(json!({ "results": results, "plugins": st.plugins.list() }))
        }

        "app.getOnboarding" => {
            let st = state.lock().await;
            let settings = st
                .db
                .get_setting("app")
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
                .unwrap_or_else(|| json!({}));
            let dismissed = settings
                .get("onboardingDismissed")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            let providers = providers::list_providers(&st.db, &st.secrets, true)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            let has_provider = !providers.is_empty();
            let has_secret = providers.iter().any(|p| p.has_secret);
            let has_project = st.workspace.get().is_some();
            let session_count = sessions::session_count(&st.db)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            let has_session = session_count > 0;
            let steps = vec![
                json!({"id":"provider","title":"Add a model provider","done": has_provider, "action":"settings.providers"}),
                json!({"id":"secret","title":"Save your API key","done": has_secret, "action":"settings.providers"}),
                json!({"id":"project","title":"Open a project folder","done": has_project, "action":"project.open"}),
                json!({"id":"prompt","title":"Send your first prompt","done": has_session, "action":"chat.focus"}),
                json!({"id":"plugin","title":"Load a development plugin (optional)","done": !st.plugins.list().is_empty(), "action":"plugins.open"}),
            ];
            let critical_incomplete = !has_provider || !has_secret || !has_session;
            Ok(json!({
                "showChecklist": critical_incomplete && !dismissed,
                "steps": steps
            }))
        }

        "audit.append" => {
            let kind = params
                .get("kind")
                .and_then(|v| v.as_str())
                .unwrap_or("custom");
            let session_id = params.get("sessionId").and_then(|v| v.as_str());
            let payload = params.get("payload").cloned().unwrap_or(json!({}));
            let st = state.lock().await;
            audit::append(&st.db, kind, session_id, payload)
                .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
            Ok(json!({ "ok": true }))
        }

        _ => Err(rpc_err(
            -32601,
            format!("method not found: {method}"),
            "NOT_FOUND",
        )),
    }
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::io::{self, Write};
    use std::path::{Path, PathBuf};
    use std::sync::Arc;

    use serde_json::{json, Value};
    use tokio::sync::{mpsc, Mutex};

    use super::{
        capability_err, handle_request, parse_capability_query, parse_capability_target,
        peek_jsonrpc_id, provider_rpc_err, request_budget_ms, resolve_plan_workspace,
        resolve_tool_workspace, resolve_tool_workspace_for_call, response_for, rpc_err, scope_err,
        skill_err, with_request_budget, JsonRpcError, RPC_REQUEST_BUDGET_MS,
    };
    use crate::agent_capabilities::CapabilityLevel;
    use crate::plans::{PlanResolveParams, PlanSubmitParams};
    use crate::scheduled;
    use crate::sessions;
    use crate::state::AppState;
    use std::time::Duration;

    #[tokio::test]
    async fn bounded_history_mutation_rpcs_return_only_mutation_metadata() {
        let dir = tempfile::tempdir().unwrap();
        let mut app = AppState::open(dir.path()).unwrap();
        app.handshook = true;
        let session = sessions::create_session(&app.db, None, None, None, None, None).unwrap();
        let message: sessions::UiMessage = serde_json::from_value(json!({
            "id": "pending", "role": "user", "content": "hello",
            "createdAt": "2026-10-26T00:00:00Z"
        }))
        .unwrap();
        let turn = sessions::begin_turn(&app.db, &session.id, None, None).unwrap();
        sessions::append_message(&app.db, &session.id, &message, Some(&turn)).unwrap();
        sessions::end_turn(&app.db, &turn, "aborted", None, None, false).unwrap();
        let state = Arc::new(Mutex::new(app));
        let tx = mpsc::unbounded_channel().0;
        let result = handle_request(
            state.clone(),
            "session.retractPendingPrompt",
            json!({
                "sessionId": session.id, "userMessageId": "pending", "turnId": turn
            }),
            tx.clone(),
        )
        .await;
        assert!(result.is_ok(), "bounded retract must exist: {result:?}");
        assert_eq!(
            result.unwrap(),
            json!({"ok": true, "retracted": true, "removedCount": 1})
        );
        let deleted = handle_request(
            state,
            "session.deleteMessage",
            json!({
                "sessionId": session.id, "messageId": "pending"
            }),
            tx,
        )
        .await
        .unwrap();
        assert_eq!(
            deleted,
            json!({"ok": true, "deleted": false, "deletedCount": 0})
        );
    }

    #[tokio::test]
    async fn canonical_activation_rpc_rejects_missing_anchor_and_keeps_legacy_prefix() {
        let dir = tempfile::tempdir().unwrap();
        let mut app = AppState::open(dir.path()).unwrap();
        app.handshook = true;
        let session = sessions::create_session(&app.db, None, None, None, None, None).unwrap();
        let root = json!({"id":"root", "role":"user", "content":"archived", "createdAt":"2026-10-26T00:00:00Z"});
        let message = serde_json::from_value(root.clone()).unwrap();
        sessions::save_message_revision(&app.db, &session.id, "root", &[message], false).unwrap();
        let state = Arc::new(Mutex::new(app));
        let tx = mpsc::unbounded_channel().0;
        let strict = handle_request(
            state.clone(),
            "session.activateRevision",
            json!({
                "sessionId":session.id, "rootUserId":"root", "revisionIndex":1,
                "requireCanonicalPrefix":true
            }),
            tx.clone(),
        )
        .await
        .unwrap_err();
        assert!(strict.message.contains("anchor missing"));
        let prefix = json!({"id":"legacy-prefix", "role":"user", "content":"prefix", "createdAt":"2026-10-26T00:00:00Z"});
        let legacy = handle_request(
            state.clone(),
            "session.activateRevision",
            json!({
                "sessionId":session.id, "rootUserId":"root", "revisionIndex":1, "prefix":[prefix]
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(legacy["messages"][0]["id"], "legacy-prefix");
        let canonical = handle_request(
            state,
            "session.activateRevision",
            json!({
                "sessionId":session.id, "rootUserId":"root", "revisionIndex":1,
                "requireCanonicalPrefix":true
            }),
            tx,
        )
        .await
        .unwrap();
        assert_eq!(canonical["messages"][0]["id"], "legacy-prefix");
    }

    #[tokio::test]
    async fn builtin_skill_activation_rpc_round_trips() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let tx = mpsc::unbounded_channel().0;

        let initial = handle_request(
            state.clone(),
            "skills.disabledBuiltins",
            json!({}),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(initial, json!({ "disabled": [] }));

        let disabled = handle_request(
            state.clone(),
            "skills.setBuiltinEnabled",
            json!({ "id": "pi-desktop/imagegen", "enabled": false }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(
            disabled,
            json!({ "id": "pi-desktop/imagegen", "enabled": false })
        );

        let current = handle_request(
            state.clone(),
            "skills.disabledBuiltins",
            json!({}),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(current, json!({ "disabled": ["pi-desktop/imagegen"] }));

        let enabled = handle_request(
            state.clone(),
            "skills.setBuiltinEnabled",
            json!({ "id": "pi-desktop/imagegen", "enabled": true }),
            tx,
        )
        .await
        .unwrap();
        assert_eq!(
            enabled,
            json!({ "id": "pi-desktop/imagegen", "enabled": true })
        );
        let current = handle_request(
            state,
            "skills.disabledBuiltins",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(current, json!({ "disabled": [] }));
    }

    // Issue #1071: the per-request wall-clock budget must cut loose requests
    // stuck on the global state lock (the dominant queueing case) so their
    // in-flight slots come back, without ever shortening a legitimate
    // long-running tool execution.

    #[test]
    fn request_budget_is_fixed_for_non_tool_methods() {
        assert_eq!(
            request_budget_ms("session.get", &json!({})),
            Some(RPC_REQUEST_BUDGET_MS)
        );
        assert_eq!(
            request_budget_ms("providers.list", &json!({})),
            Some(RPC_REQUEST_BUDGET_MS)
        );
    }

    #[test]
    fn config_sync_request_has_no_wall_clock_budget() {
        assert_eq!(request_budget_ms("configSync.syncNow", &json!({})), None);
    }
    #[test]
    fn request_budget_for_tools_execute_follows_tool_timeout() {
        // The real wire shape: ToolsExecuteParams is serde-renamed to
        // camelCase, so the runtime sends toolName / timeoutMs (review on
        // #1208 — the snake_case spellings are never on the wire).
        let bash = json!({"toolName": "Bash", "timeoutMs": 60000});
        assert_eq!(
            request_budget_ms("tools.execute", &bash),
            Some(60_000 + 120_000 + 90_000)
        );
        // Bash without an explicit timeout falls back to the Bash default.
        let bash_default = json!({"toolName": "Bash"});
        assert_eq!(
            request_budget_ms("tools.execute", &bash_default),
            Some(60_000 + 120_000 + 90_000)
        );
        // A tool with no effective timeout keeps the old unbounded behavior.
        let read = json!({"toolName": "Read"});
        assert_eq!(request_budget_ms("tools.execute", &read), None);
    }

    #[test]
    fn request_budget_reads_the_camel_case_wire_shape_regression_1208() {
        // Regression for the #1208 review: the runtime's real Bash payload —
        // `toolName` / `timeoutMs` — must produce the tool-timeout budget,
        // not an unbounded one. A 6h Bash must never be clipped to the fixed
        // budget, and an unknown snake/camel mixture must still resolve.
        let six_hours = json!({"toolName": "Bash", "timeoutMs": 21600000});
        assert_eq!(
            request_budget_ms("tools.execute", &six_hours),
            Some(21_600_000 + 120_000 + 90_000)
        );
        // The snake_case fallback keeps hand-rolled callers honest.
        let snake = json!({"tool_name": "Bash", "timeout_ms": 60000});
        assert_eq!(
            request_budget_ms("tools.execute", &snake),
            Some(60_000 + 120_000 + 90_000)
        );
    }

    #[tokio::test]
    async fn budget_passes_fast_results_through() {
        let result = with_request_budget(Some(1_000), async {
            Ok::<_, JsonRpcError>(json!({"ok": true}))
        })
        .await
        .expect("fast future must pass through untouched");
        assert_eq!(result, json!({"ok": true}));
    }

    #[tokio::test]
    async fn budget_ends_slow_request_with_host_rpc_timeout() {
        let started = std::time::Instant::now();
        let error = with_request_budget(Some(50), async {
            tokio::time::sleep(Duration::from_secs(5)).await;
            Ok::<_, JsonRpcError>(json!(null))
        })
        .await
        .expect_err("a future past its budget must end with HOST_RPC_TIMEOUT");
        assert_eq!(error.code, -32030);
        assert_eq!(
            error
                .data
                .as_ref()
                .and_then(|d| d.get("errorCode"))
                .and_then(|c| c.as_str()),
            Some("HOST_RPC_TIMEOUT")
        );
        assert!(
            started.elapsed() < Duration::from_secs(2),
            "timeout must fire at the budget, not the inner future's own duration"
        );
    }

    #[tokio::test]
    async fn budget_cuts_loose_a_request_waiting_on_the_global_lock() {
        let state = Arc::new(Mutex::new(()));
        // Hold the global lock like a wedged handler would.
        let holder = state.clone();
        let guard = holder.lock().await;

        // A queued request waiting for that lock: with the budget it fails
        // on its own instead of piling up behind the wedged holder.
        let waiter_state = state.clone();
        let error = with_request_budget(Some(50), async move {
            let _st = waiter_state.lock().await;
            Ok::<_, JsonRpcError>(json!(null))
        })
        .await
        .expect_err("a lock waiter past its budget must fail with HOST_RPC_TIMEOUT");
        assert_eq!(error.code, -32030);

        // The cancelled waiter held no guard: once the wedged holder lets go,
        // the lock is immediately available again for everyone else.
        drop(guard);
        let lock_state = state.clone();
        let acquired = tokio::time::timeout(Duration::from_millis(500), lock_state.lock()).await;
        assert!(
            acquired.is_ok(),
            "lock must be acquirable right after the holder drops; a cancelled waiter must not be holding it"
        );
    }

    // Deep-dive: issue #1071's failure mode is many requests queueing on one
    // wedged handler. Every queued request must time out **independently** —
    // one waiter's timeout must not extend or reset another's — and after the
    // wedged holder lets go, a fresh request must go straight through.

    #[tokio::test]
    async fn budget_times_out_concurrent_lock_waiters_independently() {
        let state = Arc::new(Mutex::new(()));
        let holder = state.clone();
        let guard = holder.lock().await;

        let mut handles = Vec::new();
        for _ in 0..10 {
            let waiter_state = state.clone();
            handles.push(tokio::spawn(with_request_budget(Some(60), async move {
                let _st = waiter_state.lock().await;
                Ok::<_, JsonRpcError>(json!(null))
            })));
        }
        for (index, handle) in handles.into_iter().enumerate() {
            let result = handle.await.expect("budgeted task must not panic");
            assert_eq!(
                result.as_ref().err().map(|e| e.code),
                Some(-32030),
                "waiter #{index} must fail with HOST_RPC_TIMEOUT, got {:?}",
                result
            );
        }
        drop(guard);
        let lock_state = state.clone();
        let acquired = tokio::time::timeout(Duration::from_millis(500), lock_state.lock()).await;
        assert!(acquired.is_ok(), "lock must be free after holder drops");
    }

    #[tokio::test]
    async fn budget_recovery_lets_a_fresh_request_through_after_the_holder_releases() {
        let state = Arc::new(Mutex::new(()));
        let holder = state.clone();

        // First: a wedged holder starves one budgeted request.
        {
            let _guard = holder.lock().await;
            let waiter_state = state.clone();
            let error = with_request_budget(Some(40), async move {
                let _st = waiter_state.lock().await;
                Ok::<_, JsonRpcError>(json!(null))
            })
            .await
            .expect_err("starved while the holder wedges the lock");
            assert_eq!(error.code, -32030);
        }

        // Then the holder releases: the very next request must succeed on the
        // normal path — the budget must not have left any lingering damage.
        let recovered = {
            let request_state = state.clone();
            with_request_budget(Some(1_000), async move {
                let _st = request_state.lock().await;
                Ok::<_, JsonRpcError>(json!({ "recovered": true }))
            })
            .await
            .expect("a request after the holder releases must succeed")
        };
        assert_eq!(recovered, json!({ "recovered": true }));
    }

    #[test]
    fn tools_execute_budget_covers_bash_max_and_unbounded_tools() {
        // Bash may legally run up to 6h: the budget must never clip it to the
        // fixed 135s, only pad the tool's own timeout with grace. Wire shape
        // is camelCase (see the #1208 regression test).
        let six_hours = json!({"toolName": "Bash", "timeoutMs": 21600000});
        assert_eq!(
            request_budget_ms("tools.execute", &six_hours),
            Some(21_600_000 + 120_000 + 90_000)
        );
        // A tool without an effective timeout stays unbounded (None), exactly
        // like before this change.
        let unbounded = json!({"toolName": "Glob"});
        assert_eq!(request_budget_ms("tools.execute", &unbounded), None);
    }

    #[test]
    fn capability_errors_keep_their_protocol_code() {
        let missing_project = parse_capability_query(&json!({ "level": "project" }))
            .expect_err("project queries require a project path");
        assert_eq!(
            missing_project.data.unwrap()["errorCode"],
            "CAPABILITY_INVALID"
        );

        let unknown_level = parse_capability_query(&json!({ "level": "workspace" }))
            .expect_err("unknown capability levels are invalid");
        assert_eq!(
            unknown_level.data.unwrap()["errorCode"],
            "CAPABILITY_INVALID"
        );
        assert_eq!(
            scope_err("CAPABILITY_INVALID: missing project")
                .data
                .unwrap()["errorCode"],
            "CAPABILITY_INVALID"
        );
        assert_eq!(
            skill_err("CAPABILITY_INVALID: missing project")
                .data
                .unwrap()["errorCode"],
            "CAPABILITY_INVALID"
        );
        assert_eq!(
            capability_err("missing project").data.unwrap()["errorCode"],
            "CAPABILITY_INVALID"
        );
    }

    /// A request whose transcript lines never reached the device must not answer
    /// success, and a handler that failed anyway keeps its own error.
    #[test]
    fn a_request_that_could_not_flush_its_transcript_does_not_answer_success() {
        let device = Err(anyhow::anyhow!(
            "flush /data/sessions/s1.jsonl: Input/output error"
        ));
        let unflushed = response_for(Value::Null, Ok(json!({ "ok": true })), device);
        assert!(
            unflushed.result.is_none(),
            "a request whose bytes never reached the device cannot succeed"
        );
        assert_eq!(unflushed.error.unwrap().code, 1000);

        let handler_error = || rpc_err(1000, "db is locked", "INTERNAL");
        let handler_failed = response_for(Value::Null, Err(handler_error()), Ok(()));
        assert_eq!(handler_failed.error.unwrap().message, "db is locked");

        // Only one error fits in a response; the device error is logged rather
        // than answered, and the request still does not report success.
        let both_failed = response_for(
            Value::Null,
            Err(handler_error()),
            Err(anyhow::anyhow!("flush failed")),
        );
        assert!(both_failed.result.is_none());
        assert_eq!(both_failed.error.unwrap().message, "db is locked");

        let answered = response_for(Value::Null, Ok(json!({ "ok": true })), Ok(()));
        assert!(answered.error.is_none());
        assert_eq!(answered.result.unwrap()["ok"], true);
    }

    #[test]
    fn capability_target_requires_an_explicit_string_level() {
        // A missing or non-string level must not fall back to `global`: that
        // would write the capability into the wrong directory without telling
        // the caller.
        let missing = parse_capability_target(&json!({ "to": { "projectPath": "/p" } }), "to")
            .expect_err("a target without a level is invalid");
        assert_eq!(missing.code, 1002);
        assert_eq!(
            missing.data.as_ref().unwrap()["errorCode"],
            json!("INVALID_PARAMS")
        );

        let wrong_type = parse_capability_target(&json!({ "to": { "level": 5 } }), "to")
            .expect_err("a non-string level is invalid");
        assert_eq!(wrong_type.code, 1002);
        assert_eq!(
            wrong_type.data.as_ref().unwrap()["errorCode"],
            json!("INVALID_PARAMS")
        );

        let absent = parse_capability_target(&json!({}), "from")
            .expect_err("the named end of a move is required");
        assert_eq!(absent.code, 1002);

        let project = parse_capability_target(
            &json!({ "to": { "level": "project", "projectPath": "/p" } }),
            "to",
        )
        .unwrap();
        assert_eq!(project.level, CapabilityLevel::Project);
        let global =
            parse_capability_target(&json!({ "to": { "level": "global" } }), "to").unwrap();
        assert_eq!(global.level, CapabilityLevel::Global);
    }

    #[test]
    fn peek_jsonrpc_id_reads_a_string_id_from_a_truncated_prefix() {
        let prefix =
            r#"{"jsonrpc":"2.0","id":"abc-123","method":"session.replaceMessages","params":{"#;
        assert_eq!(peek_jsonrpc_id(prefix), json!("abc-123"));
    }

    #[test]
    fn peek_jsonrpc_id_reads_a_numeric_id() {
        assert_eq!(
            peek_jsonrpc_id(r#"{"jsonrpc":"2.0","id":7,"method":"x"}"#),
            json!(7)
        );
    }

    #[test]
    fn peek_jsonrpc_id_is_null_when_the_prefix_has_no_id() {
        assert_eq!(peek_jsonrpc_id("not json"), Value::Null);
        assert_eq!(peek_jsonrpc_id(""), Value::Null);
    }

    #[test]
    fn provider_alias_validation_keeps_a_stable_error_code() {
        let error = provider_rpc_err("MODEL_ALIAS_TOO_LONG: alias is too long");
        assert_eq!(error.code, 1002);
        assert_eq!(
            error.data.as_ref().and_then(|data| data.get("errorCode")),
            Some(&json!("MODEL_ALIAS_TOO_LONG"))
        );
    }

    #[tokio::test]
    async fn project_create_returns_an_id_without_switching_workspace() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();
        let path = data_dir.path().to_string_lossy().to_string();

        let result = handle_request(
            state.clone(),
            "projects.create",
            json!({ "path": path }),
            tx,
        )
        .await
        .unwrap();
        let project_id = result["project"]["id"].as_i64().unwrap();
        // A stored project path has one canonical spelling: resolved, with
        // forward slashes. Comparing against the raw platform spelling only
        // holds where the separator happens to be `/`.
        let canonical_path =
            crate::db::canonical_project_path(&path).expect("canonical project path");
        assert_eq!(result["project"]["path"], canonical_path.as_str());
        assert!(project_id > 0);

        let workspace = handle_request(
            state,
            "workspace.get",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(workspace["workspace"], Value::Null);
    }

    #[tokio::test]
    async fn project_group_update_rpc_adjusts_folders() {
        let data_dir = tempfile::tempdir().unwrap();
        let primary = data_dir.path().join("primary");
        let extra = data_dir.path().join("extra");
        fs::create_dir_all(&primary).unwrap();
        fs::create_dir_all(&extra).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let created = handle_request(
            state.clone(),
            "project.group.create",
            json!({ "name": "Editable", "folders": [primary] }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        let group_id = created["group"]["id"].as_str().unwrap();
        let updated = handle_request(
            state,
            "project.group.update",
            json!({
                "groupId": group_id,
                "name": "Adjusted",
                "folders": [created["group"]["primaryPath"], extra]
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(updated["group"]["name"], "Adjusted");
        assert_eq!(updated["group"]["roots"].as_array().unwrap().len(), 2);
    }

    #[tokio::test]
    async fn project_group_update_rpc_relocates_the_active_single_root_workspace() {
        let data_dir = tempfile::tempdir().unwrap();
        let old = data_dir.path().join("old");
        let new = data_dir.path().join("new");
        fs::create_dir(&old).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        app_state.workspace.set(&old);
        let state = Arc::new(Mutex::new(app_state));
        let created = handle_request(
            state.clone(),
            "project.group.create",
            json!({ "name": "Movable", "folders": [old] }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        let group_id = created["group"]["id"].as_str().unwrap();
        fs::rename(&old, &new).unwrap();

        handle_request(
            state.clone(),
            "project.group.update",
            json!({
                "groupId": group_id,
                "name": "Movable",
                "folders": [new],
                "primary": new,
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        let workspace = handle_request(
            state,
            "workspace.get",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(
            workspace["workspace"]["path"],
            json!(crate::db::canonical_project_path(&new.to_string_lossy()).unwrap())
        );
    }

    #[tokio::test]
    async fn project_group_update_rpc_follows_a_two_step_relocation() {
        let data_dir = tempfile::tempdir().unwrap();
        let old = data_dir.path().join("old");
        let new = data_dir.path().join("new");
        fs::create_dir(&old).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        app_state.workspace.set(&old);
        let state = Arc::new(Mutex::new(app_state));
        let send = |method: &'static str, params: Value| {
            let state = state.clone();
            async move {
                handle_request(state, method, params, mpsc::unbounded_channel().0)
                    .await
                    .unwrap()
            }
        };
        let created = send(
            "project.group.create",
            json!({ "name": "Movable", "folders": [old] }),
        )
        .await;
        let group_id = created["group"]["id"].as_str().unwrap().to_string();
        let old_path = created["group"]["primaryPath"]
            .as_str()
            .unwrap()
            .to_string();
        {
            let st = state.lock().await;
            crate::sessions::create_session(
                &st.db,
                Some("Existing chat".into()),
                Some("agent".into()),
                None,
                None,
                Some(old_path.clone()),
            )
            .unwrap();
        }
        fs::rename(&old, &new).unwrap();
        let new_path = crate::db::canonical_project_path(&new.to_string_lossy()).unwrap();

        send(
            "project.group.update",
            json!({
                "groupId": group_id,
                "name": "Movable",
                "folders": [old_path, new],
                "primary": new,
            }),
        )
        .await;
        let workspace = send("workspace.get", json!({})).await;
        assert_eq!(workspace["workspace"]["path"], json!(old_path));

        send(
            "project.group.update",
            json!({
                "groupId": group_id,
                "name": "Movable",
                "folders": [new],
                "primary": new,
            }),
        )
        .await;
        let workspace = send("workspace.get", json!({})).await;
        assert_eq!(workspace["workspace"]["path"], json!(new_path));
    }

    #[tokio::test]
    async fn project_group_update_rpc_keeps_workspace_when_the_old_folder_exists() {
        let data_dir = tempfile::tempdir().unwrap();
        let old = data_dir.path().join("old");
        let other = data_dir.path().join("other");
        fs::create_dir(&old).unwrap();
        fs::create_dir(&other).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let before = app_state.workspace.set(&old).path;
        let state = Arc::new(Mutex::new(app_state));
        let created = handle_request(
            state.clone(),
            "project.group.create",
            json!({ "name": "Swap", "folders": [old] }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        handle_request(
            state.clone(),
            "project.group.update",
            json!({
                "groupId": created["group"]["id"],
                "name": "Swap",
                "folders": [other],
                "primary": other,
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        let workspace = handle_request(
            state,
            "workspace.get",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(workspace["workspace"]["path"], json!(before));
    }

    #[tokio::test]
    async fn project_group_update_rpc_switches_the_primary_folder() {
        let data_dir = tempfile::tempdir().unwrap();
        let primary = data_dir.path().join("primary");
        let extra = data_dir.path().join("extra");
        fs::create_dir_all(&primary).unwrap();
        fs::create_dir_all(&extra).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let created = handle_request(
            state.clone(),
            "project.group.create",
            json!({ "name": "Switchable", "folders": [primary, extra] }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        let group_id = created["group"]["id"].as_str().unwrap().to_string();
        let primary_path = created["group"]["primaryPath"]
            .as_str()
            .unwrap()
            .to_string();
        let extra_path = created["group"]["roots"][1]["path"]
            .as_str()
            .unwrap()
            .to_string();

        let switched = handle_request(
            state.clone(),
            "project.group.update",
            json!({
                "groupId": group_id,
                "name": "Switchable",
                "folders": [primary_path, extra_path],
                "primary": extra_path,
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .expect("a member folder can be promoted to primary");
        assert_eq!(switched["group"]["primaryPath"], json!(extra_path));
        assert_eq!(switched["group"]["roots"][0]["path"], json!(extra_path));
        assert_eq!(switched["group"]["roots"][1]["path"], json!(primary_path));

        // The stored record keeps the promoted folder as primary.
        let listed = handle_request(
            state.clone(),
            "project.groups.list",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(
            listed["groups"][0]["primaryPath"],
            json!(switched["group"]["primaryPath"])
        );
    }
    #[tokio::test]
    async fn grouped_folder_with_chats_can_be_detached_and_deleted_separately() {
        let data_dir = tempfile::tempdir().unwrap();
        let primary = data_dir.path().join("primary");
        let member = data_dir.path().join("member");
        fs::create_dir_all(&primary).unwrap();
        fs::create_dir_all(&member).unwrap();
        let primary_input = primary.to_string_lossy().to_string();
        let member_input = member.to_string_lossy().to_string();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));

        let group_response = handle_request(
            state.clone(),
            "project.group.create",
            json!({ "name": "Grouped", "folders": [primary_input, member_input] }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        let group_id = group_response["group"]["id"].as_str().unwrap().to_string();
        let primary_path = group_response["group"]["primaryPath"]
            .as_str()
            .unwrap()
            .to_string();
        let member_path = group_response["group"]["roots"][1]["path"]
            .as_str()
            .unwrap()
            .to_string();

        // This chat predates removing the member from the group.
        let session_id = {
            let st = state.lock().await;
            sessions::create_session_with_options(
                &st.db,
                sessions::SessionCreateOptions {
                    project_path: Some(member_path.clone()),
                    ..Default::default()
                },
            )
            .unwrap()
            .id
        };

        let updated = handle_request(
            state.clone(),
            "project.group.update",
            json!({ "groupId": group_id, "name": "Grouped", "folders": [primary_path] }),
            mpsc::unbounded_channel().0,
        )
        .await
        .expect("a member with chats can be detached from the group");
        assert_eq!(updated["group"]["roots"].as_array().unwrap().len(), 1);

        let detached_groups = handle_request(
            state.clone(),
            "project.groups.list",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert!(detached_groups["groups"]
            .as_array()
            .unwrap()
            .iter()
            .any(|group| {
                group["legacy"] == json!(true) && group["roots"][0]["path"] == json!(member_path)
            }));

        let removed = handle_request(
            state.clone(),
            "projects.remove",
            json!({ "path": member_path }),
            mpsc::unbounded_channel().0,
        )
        .await
        .expect("the detached project can then be deleted through the project action");
        assert_eq!(removed["removed"], json!(true));
        assert_eq!(removed["sessionsRemoved"], json!(1));
        assert!(member.exists());

        let groups_after_delete = handle_request(
            state.clone(),
            "project.groups.list",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(groups_after_delete["groups"].as_array().unwrap().len(), 1);
        assert_eq!(
            groups_after_delete["groups"][0]["roots"][0]["path"],
            json!(primary_path)
        );

        let sessions_after_delete = handle_request(
            state,
            "session.list",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert!(sessions_after_delete["sessions"]
            .as_array()
            .unwrap()
            .iter()
            .all(|session| session["id"] != json!(session_id)));
    }

    #[tokio::test]
    async fn project_group_rpc_roundtrips_context_and_roots() {
        let data_dir = tempfile::tempdir().unwrap();
        let primary = data_dir.path().join("primary");
        let member = data_dir.path().join("member");
        fs::create_dir_all(&primary).unwrap();
        fs::create_dir_all(&member).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let created = handle_request(
            state.clone(),
            "project.group.create",
            json!({
                "name": "A named project",
                "folders": [primary, member]
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        let group_id = created["group"]["id"].as_str().unwrap();
        assert_eq!(created["group"]["roots"].as_array().unwrap().len(), 2);

        let context = handle_request(
            state,
            "project.group.context",
            json!({ "path": created["group"]["primaryPath"] }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(context["context"]["groupId"], group_id);
        assert_eq!(context["context"]["roots"].as_array().unwrap().len(), 2);
    }

    #[tokio::test]
    async fn project_memory_rpc_roundtrips_without_switching_workspace() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let path = data_dir.path().to_string_lossy().to_string();

        let saved = handle_request(
            state.clone(),
            "project.memory.set",
            json!({ "path": path, "content": "Use the staging database." }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(saved["memory"]["content"], "Use the staging database.");

        let loaded = handle_request(
            state.clone(),
            "project.memory.get",
            json!({ "path": data_dir.path() }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(loaded["memory"]["content"], "Use the staging database.");

        let structured = handle_request(
            state,
            "project.memory.set",
            json!({
                "path": path,
                "entries": [{
                    "id": "deployment",
                    "title": "Deployment",
                    "content": "Use the staging database."
                }]
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(
            structured["memory"]["content"],
            "## Deployment\n\nUse the staging database."
        );
        assert_eq!(structured["memory"]["entries"][0]["id"], "deployment");
    }

    /// Append a user message through the RPC so the session's transcript file
    /// exists on disk, mirroring a renderer outbox append.
    async fn append_test_message(state: Arc<Mutex<AppState>>, session_id: &str, message_id: &str) {
        handle_request(
            state,
            "session.appendMessage",
            json!({
                "sessionId": session_id,
                "message": {
                    "id": message_id,
                    "role": "user",
                    "content": "hello",
                    "createdAt": "2025-05-01T00:00:00Z"
                }
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn projects_remove_deletes_project_sessions_and_transcripts() {
        let data_dir = tempfile::tempdir().unwrap();
        let project_dir = data_dir.path().join("project");
        fs::create_dir_all(&project_dir).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let project_path = project_dir.to_string_lossy().to_string();
        let first = sessions::create_session_with_options(
            &app_state.db,
            sessions::SessionCreateOptions {
                project_path: Some(project_path.clone()),
                ..Default::default()
            },
        )
        .unwrap()
        .id;
        let second = sessions::create_session_with_options(
            &app_state.db,
            sessions::SessionCreateOptions {
                project_path: Some(project_path.clone()),
                ..Default::default()
            },
        )
        .unwrap()
        .id;
        let state = Arc::new(Mutex::new(app_state));

        let mut transcripts = Vec::new();
        for (index, id) in [&first, &second].into_iter().enumerate() {
            append_test_message(state.clone(), id, &format!("message-{index}")).await;
            let transcript = crate::transcripts::transcript_path(data_dir.path(), id).unwrap();
            assert!(transcript.exists());
            transcripts.push(transcript);
        }

        let saved_memory = handle_request(
            state.clone(),
            "project.memory.set",
            json!({ "path": project_path, "content": "Use the staging database." }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(
            saved_memory["memory"]["content"],
            "Use the staging database."
        );

        let result = handle_request(
            state.clone(),
            "projects.remove",
            json!({ "path": project_path }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(result["removed"], json!(true));
        assert_eq!(result["sessionsRemoved"], json!(2));

        let canonical =
            crate::db::canonical_project_path(&project_path).expect("canonical project path");
        let projects = handle_request(
            state.clone(),
            "projects.list",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert!(projects["projects"]
            .as_array()
            .unwrap()
            .iter()
            .all(|project| project["path"].as_str() != Some(canonical.as_str())));

        let listed = handle_request(
            state.clone(),
            "session.list",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        for id in [&first, &second] {
            assert!(listed["sessions"]
                .as_array()
                .unwrap()
                .iter()
                .all(|session| session["id"].as_str() != Some(id.as_str())));
        }

        let memory = handle_request(
            state,
            "project.memory.get",
            json!({ "path": project_path }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(memory["memory"]["content"], "");

        for transcript in transcripts {
            assert!(!transcript.exists());
        }
        assert!(project_dir.exists());
    }

    #[tokio::test]
    async fn projects_remove_keeps_sessions_of_other_projects() {
        let data_dir = tempfile::tempdir().unwrap();
        let removed_dir = data_dir.path().join("removed-project");
        let kept_dir = data_dir.path().join("kept-project");
        fs::create_dir_all(&removed_dir).unwrap();
        fs::create_dir_all(&kept_dir).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let removed_path = removed_dir.to_string_lossy().to_string();
        let kept_path = kept_dir.to_string_lossy().to_string();
        let removed_session = sessions::create_session_with_options(
            &app_state.db,
            sessions::SessionCreateOptions {
                project_path: Some(removed_path.clone()),
                ..Default::default()
            },
        )
        .unwrap()
        .id;
        let kept_session = sessions::create_session_with_options(
            &app_state.db,
            sessions::SessionCreateOptions {
                project_path: Some(kept_path.clone()),
                ..Default::default()
            },
        )
        .unwrap()
        .id;
        let state = Arc::new(Mutex::new(app_state));

        append_test_message(state.clone(), &removed_session, "removed-message").await;
        append_test_message(state.clone(), &kept_session, "kept-message").await;
        let kept_transcript =
            crate::transcripts::transcript_path(data_dir.path(), &kept_session).unwrap();
        assert!(kept_transcript.exists());

        let result = handle_request(
            state.clone(),
            "projects.remove",
            json!({ "path": removed_path }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(result["removed"], json!(true));
        assert_eq!(result["sessionsRemoved"], json!(1));

        let listed = handle_request(
            state.clone(),
            "session.list",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        let listed_sessions = listed["sessions"].as_array().unwrap();
        assert!(listed_sessions
            .iter()
            .any(|session| session["id"].as_str() == Some(kept_session.as_str())));
        assert!(!listed_sessions
            .iter()
            .any(|session| session["id"].as_str() == Some(removed_session.as_str())));
        assert!(kept_transcript.exists());

        let canonical_kept =
            crate::db::canonical_project_path(&kept_path).expect("canonical project path");
        let projects = handle_request(
            state,
            "projects.list",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert!(projects["projects"]
            .as_array()
            .unwrap()
            .iter()
            .any(|project| project["path"].as_str() == Some(canonical_kept.as_str())));
    }

    #[tokio::test]
    async fn projects_remove_unknown_path_is_idempotent() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));

        let blank = handle_request(
            state.clone(),
            "projects.remove",
            json!({ "path": "   " }),
            mpsc::unbounded_channel().0,
        )
        .await
        .expect_err("a blank project path is invalid");
        assert_eq!(blank.code, 1002);
        assert_eq!(
            blank.data.as_ref().and_then(|data| data.get("errorCode")),
            Some(&json!("INVALID_PARAMS"))
        );

        let missing = data_dir
            .path()
            .join("missing")
            .to_string_lossy()
            .to_string();
        let result = handle_request(
            state,
            "projects.remove",
            json!({ "path": missing }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(result["removed"], json!(false));
        assert_eq!(result["sessionsRemoved"], json!(0));
    }

    #[tokio::test]
    async fn projects_remove_detaches_stored_group_root_and_promotes_next_root() {
        let data_dir = tempfile::tempdir().unwrap();
        let grouped_dir = data_dir.path().join("grouped");
        let extra_dir = data_dir.path().join("extra");
        fs::create_dir_all(&grouped_dir).unwrap();
        fs::create_dir_all(&extra_dir).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let grouped_path = grouped_dir.to_string_lossy().to_string();
        let extra_path = extra_dir.to_string_lossy().to_string();
        app_state
            .db
            .create_project_group("Grouped", &[grouped_path.clone(), extra_path.clone()])
            .unwrap();
        let state = Arc::new(Mutex::new(app_state));

        let removed = handle_request(
            state.clone(),
            "projects.remove",
            json!({ "path": grouped_path.clone() }),
            mpsc::unbounded_channel().0,
        )
        .await
        .expect("deleting a grouped project root also detaches it");
        assert_eq!(removed["removed"], json!(true));

        let canonical_grouped =
            crate::db::canonical_project_path(&grouped_path).expect("deleted project path");
        let canonical_extra =
            crate::db::canonical_project_path(&extra_path).expect("remaining project path");
        let projects = handle_request(
            state.clone(),
            "projects.list",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert!(!projects["projects"]
            .as_array()
            .unwrap()
            .iter()
            .any(|project| project["path"].as_str() == Some(canonical_grouped.as_str())));
        assert!(projects["projects"]
            .as_array()
            .unwrap()
            .iter()
            .any(|project| project["path"].as_str() == Some(canonical_extra.as_str())));

        let groups = handle_request(
            state,
            "project.groups.list",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(groups["groups"].as_array().unwrap().len(), 1);
        assert_eq!(groups["groups"][0]["primaryPath"], json!(canonical_extra));
        assert_eq!(groups["groups"][0]["roots"].as_array().unwrap().len(), 1);
    }

    /// A single-folder stored project group is just a wrapper around one
    /// project. Removing that project must succeed and delete the now-empty
    /// group record instead of locking the project in place (issue #572).
    #[tokio::test]
    async fn projects_remove_deletes_single_folder_stored_group() {
        let data_dir = tempfile::tempdir().unwrap();
        let solo_dir = data_dir.path().join("solo");
        fs::create_dir_all(&solo_dir).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let solo_path = solo_dir.to_string_lossy().to_string();
        let group = app_state
            .db
            .create_project_group("Solo", std::slice::from_ref(&solo_path))
            .unwrap();
        assert!(!group.legacy);
        assert_eq!(group.roots.len(), 1);
        let state = Arc::new(Mutex::new(app_state));

        let result = handle_request(
            state.clone(),
            "projects.remove",
            json!({ "path": solo_path }),
            mpsc::unbounded_channel().0,
        )
        .await
        .expect("a single-folder stored group must be removable");
        assert_eq!(result["removed"], json!(true));

        let canonical =
            crate::db::canonical_project_path(&solo_path).expect("canonical project path");
        let st = state.lock().await;
        assert!(st
            .db
            .stored_project_group_for_path(&canonical)
            .unwrap()
            .is_none());
        assert!(st
            .db
            .list_projects()
            .unwrap()
            .iter()
            .all(|project| project.path != canonical));
    }

    /// A running turn owns its session's tools, working directory, and
    /// transcript writes, so the bulk delete waits until the project is idle.
    #[tokio::test]
    async fn projects_remove_refuses_while_a_session_is_running_without_detaching_group() {
        let data_dir = tempfile::tempdir().unwrap();
        let project_dir = data_dir.path().join("busy-project");
        let remaining_dir = data_dir.path().join("remaining-project");
        fs::create_dir_all(&project_dir).unwrap();
        fs::create_dir_all(&remaining_dir).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let project_path = project_dir.to_string_lossy().to_string();
        let remaining_path = remaining_dir.to_string_lossy().to_string();
        app_state
            .db
            .create_project_group(
                "Busy group",
                &[project_path.clone(), remaining_path.clone()],
            )
            .unwrap();
        let session_id = sessions::create_session_with_options(
            &app_state.db,
            sessions::SessionCreateOptions {
                project_path: Some(project_path.clone()),
                ..Default::default()
            },
        )
        .unwrap()
        .id;
        let state = Arc::new(Mutex::new(app_state));

        let started = handle_request(
            state.clone(),
            "session.beginTurn",
            json!({ "sessionId": session_id }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        let turn_id = started["turnId"].as_str().unwrap().to_string();

        let error = handle_request(
            state.clone(),
            "projects.remove",
            json!({ "path": project_path }),
            mpsc::unbounded_channel().0,
        )
        .await
        .expect_err("a running turn blocks the project delete");
        assert_eq!(error.code, 1008);
        assert_eq!(
            error.data.as_ref().and_then(|data| data.get("errorCode")),
            Some(&json!("CONFLICT"))
        );

        let canonical =
            crate::db::canonical_project_path(&project_path).expect("canonical project path");
        let projects = handle_request(
            state.clone(),
            "projects.list",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert!(projects["projects"]
            .as_array()
            .unwrap()
            .iter()
            .any(|project| project["path"].as_str() == Some(canonical.as_str())));
        let groups_while_busy = handle_request(
            state.clone(),
            "project.groups.list",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(
            groups_while_busy["groups"][0]["roots"]
                .as_array()
                .unwrap()
                .len(),
            2
        );
        assert_eq!(
            groups_while_busy["groups"][0]["primaryPath"],
            json!(canonical)
        );
        let listed = handle_request(
            state.clone(),
            "session.list",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert!(listed["sessions"]
            .as_array()
            .unwrap()
            .iter()
            .any(|session| session["id"].as_str() == Some(session_id.as_str())));

        handle_request(
            state.clone(),
            "session.endTurn",
            json!({ "turnId": turn_id, "status": "completed" }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        let removed = handle_request(
            state.clone(),
            "projects.remove",
            json!({ "path": project_path }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(removed["removed"], json!(true));
        assert_eq!(removed["sessionsRemoved"], json!(1));
        let groups_after_delete = handle_request(
            state,
            "project.groups.list",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        let remaining_canonical =
            crate::db::canonical_project_path(&remaining_path).expect("remaining project path");
        assert_eq!(groups_after_delete["groups"].as_array().unwrap().len(), 1);
        assert_eq!(
            groups_after_delete["groups"][0]["roots"]
                .as_array()
                .unwrap()
                .len(),
            1
        );
        assert_eq!(
            groups_after_delete["groups"][0]["primaryPath"],
            json!(remaining_canonical)
        );
    }

    /// ADR 0334: `fastMode` is an optional boolean on create and configure;
    /// an absent value keeps the stored switch and a non-boolean is rejected.
    #[tokio::test]
    async fn session_fast_mode_rpc_is_optional_boolean_and_preserved() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();
        let call = |method: &'static str, params: Value| {
            handle_request(state.clone(), method, params, tx.clone())
        };

        let legacy = call("session.create", json!({ "mode": "agent" }))
            .await
            .unwrap();
        assert_eq!(legacy["session"]["fastMode"], false);
        let created = call(
            "session.create",
            json!({ "mode": "agent", "fastMode": true }),
        )
        .await
        .unwrap();
        assert_eq!(created["session"]["fastMode"], true);
        let id = created["session"]["id"].as_str().unwrap().to_string();

        let kept = call(
            "session.configure",
            json!({ "id": id, "mode": "plan", "thinkingLevel": "high" }),
        )
        .await
        .unwrap();
        assert_eq!(kept["session"]["fastMode"], true);
        let off = call(
            "session.configure",
            json!({ "id": id, "mode": "agent", "fastMode": false }),
        )
        .await
        .unwrap();
        assert_eq!(off["session"]["fastMode"], false);

        for method in ["session.create", "session.configure"] {
            let error = call(
                method,
                json!({ "id": id, "mode": "agent", "fastMode": "yes" }),
            )
            .await
            .unwrap_err();
            assert_eq!(error.data.unwrap()["errorCode"], "INVALID_PARAMS");
        }
    }

    #[tokio::test]
    async fn session_create_rpc_inherits_optional_permission_mode() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let parent_id = sessions::create_session_with_options(
            &app_state.db,
            sessions::SessionCreateOptions {
                permission_mode: Some("ask".into()),
                ..Default::default()
            },
        )
        .unwrap()
        .id;
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();

        let explicit = handle_request(
            state.clone(),
            "session.create",
            json!({
                "mode": "agent",
                "thinkingLevel": "high",
                "inheritPermissionFromSessionId": parent_id
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(explicit["session"]["thinkingLevel"], "high");
        assert_eq!(explicit["session"]["permissionMode"], "ask");

        let legacy = handle_request(
            state.clone(),
            "session.create",
            json!({ "mode": "agent" }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(legacy["session"]["permissionMode"], "inherit");

        let arbitrary_permission = handle_request(
            state.clone(),
            "session.create",
            json!({ "mode": "agent", "permissionMode": "auto" }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(arbitrary_permission["session"]["permissionMode"], "inherit");

        let invalid = handle_request(
            state.clone(),
            "session.create",
            json!({ "inheritPermissionFromSessionId": true }),
            tx.clone(),
        )
        .await
        .unwrap_err();
        assert_eq!(invalid.data.unwrap()["errorCode"], "INVALID_PARAMS");

        let malformed = handle_request(
            state,
            "session.create",
            json!({ "inheritPermissionFromSessionId": "" }),
            tx,
        )
        .await
        .unwrap_err();
        assert_eq!(malformed.data.unwrap()["errorCode"], "INVALID_PARAMS");
    }

    #[tokio::test]
    async fn plugin_session_rpc_routes_the_full_p0_p1_surface() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();
        let item = |external_id: &str| {
            json!({
                "externalId": external_id,
                "title": "Imported",
                "createdAt": "2026-01-01T00:00:00Z",
                "updatedAt": "2026-01-01T00:00:01Z",
                "messages": [{
                    "role": "user",
                    "content": "hello",
                    "createdAt": "2026-01-01T00:00:00Z"
                }]
            })
        };

        let imported = handle_request(
            state.clone(),
            "plugin.session.import",
            json!({
                "pluginId": "plugin.one",
                "source": "legacy",
                "sourceLabel": "Legacy",
                "externalId": "one",
                "title": "Imported",
                "createdAt": "2026-01-01T00:00:00Z",
                "updatedAt": "2026-01-01T00:00:01Z",
                "messages": [{
                    "role": "user",
                    "content": "hello",
                    "createdAt": "2026-01-01T00:00:00Z"
                }]
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        let session_id = imported["sessionId"].as_str().unwrap().to_string();

        let batch = handle_request(
            state.clone(),
            "plugin.session.importBatch",
            json!({
                "pluginId": "plugin.one",
                "source": "legacy",
                "sessions": [item("two"), item("three")]
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(batch["imported"], 2);

        let listed = handle_request(
            state.clone(),
            "plugin.session.list",
            json!({ "pluginId": "plugin.one", "source": "legacy" }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(listed["items"].as_array().unwrap().len(), 3);

        let detail = handle_request(
            state.clone(),
            "plugin.session.get",
            json!({ "pluginId": "plugin.one", "sessionId": session_id }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(detail["originKind"], "imported");

        let messages = handle_request(
            state.clone(),
            "plugin.session.listMessages",
            json!({ "pluginId": "plugin.one", "sessionId": session_id }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(messages["items"][0]["origin"], "external");

        handle_request(
            state.clone(),
            "plugin.session.rename",
            json!({ "pluginId": "plugin.one", "sessionId": session_id, "title": "Renamed" }),
            tx.clone(),
        )
        .await
        .unwrap();
        handle_request(
            state.clone(),
            "plugin.session.delete",
            json!({ "pluginId": "plugin.one", "sessionId": session_id, "mode": "trash" }),
            tx.clone(),
        )
        .await
        .unwrap();
        let denied = handle_request(
            state.clone(),
            "plugin.session.get",
            json!({ "pluginId": "plugin.two", "sessionId": session_id }),
            tx.clone(),
        )
        .await
        .unwrap_err();
        assert_eq!(denied.code, 1007);
        handle_request(
            state,
            "plugin.session.delete",
            json!({ "pluginId": "plugin.one", "sessionId": session_id, "mode": "purge" }),
            tx,
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn plugin_session_rpc_serves_all_scope_and_message_writes() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();

        // A user-created conversation carries no import origin row, so `.own` can
        // never reach it and `.all` is the only path (ADR 0339).
        let session_id = {
            let st = state.lock().await;
            sessions::create_session_with_options(
                &st.db,
                sessions::SessionCreateOptions {
                    provider_id: Some("provider".into()),
                    model_id: Some("model".into()),
                    ..Default::default()
                },
            )
            .unwrap()
            .id
        };

        // `.own` reports the row as missing, which is exactly today's behaviour.
        let hidden = handle_request(
            state.clone(),
            "plugin.session.get",
            json!({ "pluginId": "plugin.one", "sessionId": session_id }),
            tx.clone(),
        )
        .await
        .unwrap_err();
        assert_eq!(hidden.code, 1007);

        let detail = handle_request(
            state.clone(),
            "plugin.session.get",
            json!({ "pluginId": "plugin.one", "scope": "all", "sessionId": session_id }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(detail["originKind"], "created");
        assert_eq!(detail["source"], "desktop");
        assert_eq!(detail["externalId"], Value::Null);
        assert_eq!(detail["modelId"], "model");

        // An unknown scope is a client error rather than a silent widening.
        let unknown = handle_request(
            state.clone(),
            "plugin.session.list",
            json!({ "pluginId": "plugin.one", "scope": "everything" }),
            tx.clone(),
        )
        .await
        .unwrap_err();
        assert_eq!(unknown.code, 1002);

        let appended = handle_request(
            state.clone(),
            "plugin.session.appendMessage",
            json!({
                "pluginId": "plugin.one",
                "scope": "all",
                "sessionId": session_id,
                "message": {
                    "role": "user",
                    "content": "hello from a plugin",
                    "createdAt": "2026-01-01T00:00:01Z"
                }
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert!(appended["messageId"]
            .as_str()
            .is_some_and(|id| !id.is_empty()));

        let replaced = handle_request(
            state.clone(),
            "plugin.session.replaceMessages",
            json!({
                "pluginId": "plugin.one",
                "scope": "all",
                "sessionId": session_id,
                "messages": [
                    { "role": "user", "content": "rewritten", "createdAt": "2026-01-01T00:00:01Z" },
                    { "role": "assistant", "content": "reply", "createdAt": "2026-01-01T00:00:02Z" }
                ]
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(replaced["messageCount"], 2);

        let messages = handle_request(
            state.clone(),
            "plugin.session.listMessages",
            json!({ "pluginId": "plugin.one", "scope": "all", "sessionId": session_id }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(messages["items"][0]["origin"], "desktop");
        let ids = messages["items"]
            .as_array()
            .unwrap()
            .iter()
            .map(|item| item["id"].as_str().unwrap_or_default().to_string())
            .collect::<Vec<_>>();
        assert_eq!(ids.len(), 2);

        let deleted = handle_request(
            state.clone(),
            "plugin.session.deleteMessage",
            json!({
                "pluginId": "plugin.one",
                "scope": "all",
                "sessionId": session_id,
                "messageId": ids[1]
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(deleted["deleted"], true);
        assert_eq!(deleted["deletedCount"], 1);

        let truncated = handle_request(
            state,
            "plugin.session.truncateFrom",
            json!({
                "pluginId": "plugin.one",
                "scope": "all",
                "sessionId": session_id,
                "keepCount": 0
            }),
            tx,
        )
        .await
        .unwrap();
        assert_eq!(truncated["keptCount"], 0);
        assert_eq!(truncated["discardedCount"], 1);
    }

    #[tokio::test]
    async fn session_usage_cost_rpc_requires_a_session_and_sums_its_ledger() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();
        let session_id = {
            let st = state.lock().await;
            let session = sessions::create_session(&st.db, None, None, None, None, None).unwrap();
            let turn = sessions::begin_turn(&st.db, &session.id, None, None).unwrap();
            let usage = json!({"operationId": "op", "usageOrigin": "pi", "providerId": "p",
                "inputTokens": 3, "outputTokens": 1, "totalTokens": 4, "costStatus": "estimated",
                "cost": {"input": 0.01, "output": 0.02, "cacheRead": 0, "cacheWrite": 0, "total": 0.03}});
            sessions::record_usage(&st.db, &session.id, &turn, &usage).unwrap();
            session.id
        };
        for params in [json!({}), json!({ "sessionId": "" })] {
            let error = handle_request(state.clone(), "session.usageCost", params, tx.clone())
                .await
                .unwrap_err();
            assert_eq!(error.code, 1002);
            assert_eq!(error.data.unwrap()["errorCode"], "INVALID_PARAMS");
        }
        let summary = handle_request(
            state.clone(),
            "session.usageCost",
            json!({ "sessionId": session_id }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(summary["requestCount"], 1);
        assert_eq!(summary["providers"][0]["providerId"], "p");
        assert_eq!(summary["providers"][0]["total"], 0.03);
        assert_eq!(summary["providers"][0]["reportedRequests"], 0);
    }

    #[tokio::test]
    async fn plugin_usage_rpc_serves_read_only_fact_rows() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();

        // Three completed turns across two sessions: t2 carries all three
        // usage_json token kinds, t1 carries none (zeros), and t4 belongs to a
        // soft-deleted session so it must never appear. Different ended_at
        // values make the ASC ordering and the cursor page observable.
        let now = chrono::Utc::now().timestamp_millis();
        {
            let st = state.lock().await;
            let conn = st.db.conn();
            for (project_id, path, name) in [(1, "/tmp/p1", "P1"), (2, "/tmp/p2", "P2")] {
                conn.execute(
                    "INSERT INTO projects (id, path, name, created_at, last_opened_at) VALUES (?1, ?2, ?3, ?4, ?4)",
                    rusqlite::params![project_id, path, name, now],
                )
                .unwrap();
            }
            for (id, title, project) in [("s1", "", 1), ("s2", "Big", 2), ("s3", "Trashed", 1)] {
                conn.execute(
                    "INSERT INTO sessions (id, title, project_id, created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?4)",
                    rusqlite::params![id, title, project, now],
                )
                .unwrap();
            }
            conn.execute(
                "UPDATE sessions SET deleted_at = ?1 WHERE id = 's3'",
                rusqlite::params![now],
            )
            .unwrap();
            // (id, session, ended, input, output, usage_json)
            let turn = |id: &str, session: &str, ended: i64, usage: Option<&str>| {
                conn.execute(
                    "INSERT INTO turns (id, session_id, status, provider_id, model_id, input_tokens, output_tokens, usage_json, started_at, ended_at)
                     VALUES (?1, ?2, 'completed', 'prov', 'model-a', ?3, ?4, ?5, ?6, ?7)",
                    rusqlite::params![id, session, 100, 200, usage, ended - 1_000, ended],
                )
                .unwrap();
            };
            turn("t1", "s1", now - 3_000, None);
            turn(
                "t2",
                "s2",
                now - 2_000,
                Some(
                    serde_json::json!({
                        "cacheReadTokens": 300,
                        "cacheWriteTokens": 400,
                        "reasoningTokens": 500
                    })
                    .to_string(),
                )
                .as_deref(),
            );
            turn(
                "t3",
                "s2",
                now - 1_000,
                Some(r#"{"cacheReadTokens":"bad"}"#),
            );
            turn("t4", "s3", now - 500, None);
        }

        const METHOD: &str = "plugin.usage.listTurns";

        // Missing pluginId is a client error, same as the session domain.
        let missing = handle_request(state.clone(), METHOD, json!({}), tx.clone())
            .await
            .unwrap_err();
        assert_eq!(missing.code, 1002);
        assert_eq!(missing.data.unwrap()["errorCode"], "INVALID_PARAMS");

        // Default window covers every turn; ordering is ended_at ASC and the
        // soft-deleted session's turn is absent.
        let page = handle_request(
            state.clone(),
            METHOD,
            json!({ "pluginId": "plugin.one" }),
            tx.clone(),
        )
        .await
        .unwrap();
        let turns = page["turns"].as_array().unwrap();
        assert_eq!(turns.len(), 3, "t4 belongs to a trashed session");
        assert_eq!(turns[0]["turnId"], "t1");
        assert_eq!(turns[1]["turnId"], "t2");
        assert_eq!(turns[2]["turnId"], "t3");
        assert!(page["nextCursor"].is_null(), "no more rows, no cursor");
        // Row shape: counters and titles only, camelCase, no message fields.
        assert!(
            turns[0]["sessionTitle"].is_null(),
            "empty title maps to null"
        );
        assert_eq!(turns[1]["sessionTitle"], "Big");
        assert_eq!(turns[1]["sessionId"], "s2");
        assert_eq!(turns[1]["projectId"], 2);
        assert_eq!(turns[1]["providerId"], "prov");
        assert_eq!(turns[1]["modelId"], "model-a");
        assert_eq!(turns[1]["inputTokens"], 100);
        assert_eq!(turns[1]["outputTokens"], 200);
        assert_eq!(turns[1]["cacheReadTokens"], 300);
        assert_eq!(turns[1]["cacheWriteTokens"], 400);
        assert_eq!(turns[1]["reasoningTokens"], 500);
        // Missing usage_json yields zeros; a malformed one also yields zeros.
        assert_eq!(turns[0]["cacheReadTokens"], 0);
        assert_eq!(turns[0]["reasoningTokens"], 0);
        assert_eq!(turns[2]["cacheReadTokens"], 0);
        assert!(turns[0].get("content").is_none());
        assert!(turns[0].get("messages").is_none());

        // limit truncates and the returned cursor fetches exactly the rest.
        let page1 = handle_request(
            state.clone(),
            METHOD,
            json!({ "pluginId": "plugin.one", "limit": 2 }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(page1["turns"].as_array().unwrap().len(), 2);
        let cursor1 = page1["nextCursor"].as_str().unwrap();
        let page2 = handle_request(
            state.clone(),
            METHOD,
            json!({ "pluginId": "plugin.one", "limit": 2, "cursor": cursor1 }),
            tx.clone(),
        )
        .await
        .unwrap();
        let rest = page2["turns"].as_array().unwrap();
        assert_eq!(rest.len(), 1, "exactly the remaining row");
        assert_eq!(rest[0]["turnId"], "t3");
        assert!(page2["nextCursor"].is_null());

        // Filtering: sessionId and projectId narrow the facts.
        let only_s2 = handle_request(
            state.clone(),
            METHOD,
            json!({ "pluginId": "plugin.one", "sessionId": "s2" }),
            tx.clone(),
        )
        .await
        .unwrap();
        let s2_turns = only_s2["turns"].as_array().unwrap();
        assert_eq!(s2_turns.len(), 2);
        assert!(s2_turns.iter().all(|t| t["sessionId"] == "s2"));

        let only_p1 = handle_request(
            state.clone(),
            METHOD,
            json!({ "pluginId": "plugin.one", "projectId": 1 }),
            tx.clone(),
        )
        .await
        .unwrap();
        let p1_turns = only_p1["turns"].as_array().unwrap();
        assert_eq!(p1_turns.len(), 1);
        assert_eq!(p1_turns[0]["sessionId"], "s1");

        // Explicit bounds exclude out-of-window turns.
        let windowed = handle_request(
            state.clone(),
            METHOD,
            json!({ "pluginId": "plugin.one", "fromMs": now - 1_500, "toMs": now }),
            tx.clone(),
        )
        .await
        .unwrap();
        let w = windowed["turns"].as_array().unwrap();
        assert_eq!(w.len(), 1, "only t3 ended inside the window");
        assert_eq!(w[0]["turnId"], "t3");

        // Client errors the host must reject: bad cursor, bad limit, bad
        // window, wrong types.
        for bad in [
            json!({ "pluginId": "p", "cursor": "not-a-cursor" }),
            json!({ "pluginId": "p", "limit": 0 }),
            json!({ "pluginId": "p", "limit": 501 }),
            json!({ "pluginId": "p", "limit": "ten" }),
            json!({ "pluginId": "p", "fromMs": -1 }),
            json!({ "pluginId": "p", "toMs": "now" }),
            json!({ "pluginId": "p", "fromMs": now, "toMs": now - 1_000 }),
            json!({
                "pluginId": "p",
                "fromMs": now - 366 * 24 * 3600 * 1000,
                "toMs": now
            }),
            json!({ "pluginId": "p", "fromMs": 0 }),
            json!({ "pluginId": "p", "sessionId": 7 }),
            json!({ "pluginId": "p", "sessionId": "" }),
            json!({ "pluginId": "p", "projectId": "seven" }),
        ] {
            let error = handle_request(state.clone(), METHOD, bad.clone(), tx.clone())
                .await
                .unwrap_err();
            assert_eq!(error.code, 1002, "{bad}");
            assert_eq!(error.data.unwrap()["errorCode"], "INVALID_PARAMS", "{bad}");
        }

        // Null bounds match omitted bounds; the 365-day window edge is accepted.
        let null_bounds = handle_request(
            state.clone(),
            METHOD,
            json!({ "pluginId": "plugin.one", "fromMs": null, "toMs": null }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(null_bounds["turns"].as_array().unwrap().len(), 3);
        let edge = handle_request(
            state.clone(),
            METHOD,
            json!({
                "pluginId": "plugin.one",
                "fromMs": now - 365 * 24 * 3600 * 1000,
                "toMs": now
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(edge["turns"].as_array().unwrap().len(), 3);
    }

    fn available_test_shell_id() -> Option<String> {
        crate::tools::shell::catalog(None)
            .effective
            .map(|shell| shell.id)
    }

    fn alternate_available_test_shell_id(current: &str) -> Option<String> {
        crate::tools::shell::catalog(None)
            .choices
            .into_iter()
            .find(|shell| shell.available && shell.id != current)
            .map(|shell| shell.id)
    }

    #[cfg(windows)]
    fn sleeping_bash_command() -> &'static str {
        "Start-Sleep -Seconds 30"
    }

    #[cfg(not(windows))]
    fn sleeping_bash_command() -> &'static str {
        "sleep 30"
    }

    #[cfg(windows)]
    fn descendant_marker_bash_command(started: &Path, late: &Path) -> String {
        format!(
            "$null = Start-Process -FilePath powershell.exe -ArgumentList @('-NoLogo','-NoProfile','-Command',\"Start-Sleep -Milliseconds 1000; [IO.File]::WriteAllText('{}', 'late')\") -WindowStyle Hidden; [IO.File]::WriteAllText('{}', 'started'); Start-Sleep -Seconds 30",
            late.display(),
            started.display()
        )
    }

    #[cfg(not(windows))]
    fn descendant_marker_bash_command(started: &Path, late: &Path) -> String {
        format!(
            "(sleep 1; printf late > '{}') & printf started > '{}'; sleep 30",
            late.display(),
            started.display()
        )
    }

    #[cfg(windows)]
    fn output_bash_command() -> &'static str {
        "[Console]::Out.Write('out-π'); [Console]::Error.Write('err-π')"
    }

    #[cfg(not(windows))]
    fn output_bash_command() -> &'static str {
        "printf 'out-π'; printf 'err-π' >&2"
    }

    async fn wait_for_bash_registration(
        state: &Arc<Mutex<AppState>>,
        session_id: &str,
        tool_call_id: &str,
    ) {
        for _ in 0..500 {
            if state
                .lock()
                .await
                .active_bash_cancellations
                .contains_key(&(session_id.to_string(), tool_call_id.to_string()))
            {
                return;
            }
            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
        }
        panic!("Bash cancellation was not registered");
    }

    async fn wait_for_tool_registration(
        state: &Arc<Mutex<AppState>>,
        session_id: &str,
        tool_call_id: &str,
        tool_name: &str,
    ) {
        for _ in 0..500 {
            if state.lock().await.active_tool_cancellations.contains_key(&(
                session_id.to_string(),
                tool_call_id.to_string(),
                tool_name.to_string(),
            )) {
                return;
            }
            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
        }
        panic!("{tool_name} cancellation was not registered");
    }

    async fn assert_bash_registry_empty(state: &Arc<Mutex<AppState>>) {
        assert!(state.lock().await.active_bash_cancellations.is_empty());
    }

    #[test]
    fn control_stdio_treats_os_resource_pressure_as_transient() {
        assert!(super::is_transient_io_error(&io::Error::from(
            io::ErrorKind::WouldBlock
        )));
        assert!(super::is_transient_io_error(&io::Error::from(
            io::ErrorKind::Interrupted
        )));
        assert!(super::is_transient_io_error(&io::Error::from_raw_os_error(
            11
        )));
        assert!(super::is_transient_io_error(&io::Error::from_raw_os_error(
            35
        )));
        assert!(!super::is_transient_io_error(&io::Error::from(
            io::ErrorKind::BrokenPipe
        )));
    }

    #[test]
    fn stdout_message_retries_partial_writes_without_duplication() {
        struct PartialWriter {
            bytes: Vec<u8>,
            blocked: bool,
        }

        impl Write for PartialWriter {
            fn write(&mut self, input: &[u8]) -> io::Result<usize> {
                if self.blocked {
                    self.blocked = false;
                    return Err(io::Error::from(io::ErrorKind::WouldBlock));
                }
                let written = input.len().min(2);
                self.bytes.extend_from_slice(&input[..written]);
                Ok(written)
            }

            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }

        let mut writer = PartialWriter {
            bytes: Vec::new(),
            blocked: true,
        };
        assert!(super::write_stdout_message(&mut writer, "hello").is_ok());
        assert_eq!(writer.bytes, b"hello");
    }

    #[test]
    fn tool_workspace_follows_the_persisted_session_project() {
        let data_dir = tempfile::tempdir().unwrap();
        let project_a = data_dir.path().join("project-a");
        let project_b = data_dir.path().join("project-b");
        fs::create_dir_all(&project_a).unwrap();
        fs::create_dir_all(&project_b).unwrap();
        let mut state = AppState::open(data_dir.path()).unwrap();
        state.workspace.set(&project_b);
        let session = sessions::create_session(
            &state.db,
            Some("Project A".into()),
            Some("agent".into()),
            None,
            None,
            Some(project_a.to_string_lossy().into_owned()),
        )
        .unwrap();

        let resolved = PathBuf::from(
            resolve_tool_workspace(&state, &session.id)
                .unwrap()
                .unwrap(),
        );

        assert_eq!(
            crate::workspace::simple_canonicalize(&resolved).unwrap(),
            crate::workspace::simple_canonicalize(&project_a).unwrap()
        );
    }

    #[test]
    fn group_member_absolute_paths_use_only_registered_group_roots() {
        let data_dir = tempfile::tempdir().unwrap();
        let primary = data_dir.path().join("primary");
        let member = data_dir.path().join("member");
        fs::create_dir_all(&primary).unwrap();
        fs::create_dir_all(&member).unwrap();
        let state = AppState::open(data_dir.path()).unwrap();
        let group = state
            .db
            .create_project_group(
                "Grouped project",
                &[
                    primary.to_string_lossy().into(),
                    member.to_string_lossy().into(),
                ],
            )
            .unwrap();
        let session = sessions::create_session(
            &state.db,
            Some("Grouped task".into()),
            Some("agent".into()),
            None,
            None,
            Some(primary.to_string_lossy().into_owned()),
        )
        .unwrap();

        let member_file = member.join("README.md");
        let resolved =
            resolve_tool_workspace_for_call(&state, &session.id, &json!({ "path": member_file }))
                .unwrap()
                .unwrap();
        assert_eq!(
            crate::workspace::simple_canonicalize(Path::new(&resolved)).unwrap(),
            crate::workspace::simple_canonicalize(&member).unwrap()
        );
        assert_eq!(
            state
                .db
                .project_group_for_path(&resolved)
                .unwrap()
                .unwrap()
                .id,
            group.id
        );

        let outside = data_dir.path().join("outside").join("file.txt");
        let fallback =
            resolve_tool_workspace_for_call(&state, &session.id, &json!({ "path": outside }))
                .unwrap()
                .unwrap();
        assert_eq!(
            crate::workspace::simple_canonicalize(Path::new(&fallback)).unwrap(),
            crate::workspace::simple_canonicalize(&primary).unwrap()
        );
    }

    #[test]
    fn temporary_session_uses_its_own_scratch_workspace() {
        let data_dir = tempfile::tempdir().unwrap();
        let active_project = data_dir.path().join("active-project");
        fs::create_dir_all(&active_project).unwrap();
        let mut state = AppState::open(data_dir.path()).unwrap();
        state.workspace.set(&active_project);
        let session = sessions::create_session(
            &state.db,
            Some("Temporary".into()),
            Some("agent".into()),
            None,
            None,
            None,
        )
        .unwrap();

        let resolved = PathBuf::from(
            resolve_tool_workspace(&state, &session.id)
                .unwrap()
                .unwrap(),
        );
        let expected = data_dir.path().join("scratch").join(&session.id);
        assert_eq!(resolved, expected);
        assert!(resolved.is_dir());
        assert_ne!(resolved, active_project);
        assert_eq!(
            resolve_plan_workspace(&state, &session.id)
                .expect_err("temporary sessions must not enter Plan/Goal workspaces")
                .data
                .unwrap()["errorCode"],
            "PLAN_WORKSPACE_REQUIRED"
        );
        assert_eq!(
            resolve_tool_workspace(&state, "legacy-missing-session")
                .expect_err("unknown sessions must not inherit the global workspace")
                .data
                .unwrap()["errorCode"],
            "SESSION_NOT_FOUND"
        );
    }

    #[tokio::test]
    async fn temporary_session_reads_and_writes_inside_its_scratch_workspace() {
        let data_dir = tempfile::tempdir().unwrap();
        let active_project = data_dir.path().join("active-project");
        fs::create_dir_all(&active_project).unwrap();
        let mut state = AppState::open(data_dir.path()).unwrap();
        state.workspace.set(&active_project);
        let session = sessions::create_session(
            &state.db,
            Some("Temporary".into()),
            Some("agent".into()),
            None,
            None,
            None,
        )
        .unwrap();
        let root = PathBuf::from(
            resolve_tool_workspace(&state, &session.id)
                .unwrap()
                .unwrap(),
        );
        let scratch = crate::scratch::session_dir(data_dir.path(), &session.id).unwrap();

        let written = crate::tools::execute_tool_with_path_access(
            Some(&root),
            Some(&scratch),
            "Write",
            &json!({ "path": "notes.txt", "content": "temporary" }),
            crate::tools::ToolExecutionOptions {
                timeout_ms: None,
                bash_options: None,
                allow_external_paths: false,
                hashline: None,
                visualization_root: None,
                write_scope: None,
            },
        )
        .await;
        assert!(written.ok);
        assert_eq!(written.content["root"], "workspace");
        assert_eq!(
            fs::read_to_string(root.join("notes.txt")).unwrap(),
            "temporary"
        );

        let read = crate::tools::execute_tool_with_path_access(
            Some(&root),
            Some(&scratch),
            "Read",
            &json!({ "path": "notes.txt" }),
            crate::tools::ToolExecutionOptions {
                timeout_ms: None,
                bash_options: None,
                allow_external_paths: false,
                hashline: None,
                visualization_root: None,
                write_scope: None,
            },
        )
        .await;
        assert!(read.ok);
        let content = read.content["content"].as_str().unwrap();
        assert!(content.contains("temporary"), "{content}");
        assert_eq!(read.content["tag"].as_str().unwrap().len(), 4);
        assert!(!active_project.join("notes.txt").exists());
    }

    #[tokio::test]
    async fn command_shell_settings_and_catalog_roundtrip() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();

        let settings = handle_request(state.clone(), "settings.get", json!({}), tx.clone())
            .await
            .unwrap();
        assert_eq!(
            settings["defaultCommandShell"],
            crate::tools::shell::default_shell_id()
        );
        assert_eq!(settings["largePasteThreshold"], 600);

        handle_request(
            state.clone(),
            "settings.set",
            json!({ "largePasteThreshold": 801 }),
            tx.clone(),
        )
        .await
        .unwrap();
        let updated = handle_request(state.clone(), "settings.get", json!({}), tx.clone())
            .await
            .unwrap();
        assert_eq!(updated["largePasteThreshold"], 801);

        handle_request(
            state.clone(),
            "settings.set",
            json!({ "infiniteProviderRetry": true }),
            tx.clone(),
        )
        .await
        .unwrap();
        let retry_settings = handle_request(state.clone(), "settings.get", json!({}), tx.clone())
            .await
            .unwrap();
        assert_eq!(retry_settings["infiniteProviderRetry"], true);

        handle_request(
            state.clone(),
            "settings.set",
            json!({ "keepAwakeWhileRunning": true }),
            tx.clone(),
        )
        .await
        .unwrap();
        let power_settings = handle_request(state.clone(), "settings.get", json!({}), tx.clone())
            .await
            .unwrap();
        assert_eq!(power_settings["keepAwakeWhileRunning"], true);

        let invalid_power = handle_request(
            state.clone(),
            "settings.set",
            json!({ "keepAwakeWhileRunning": "yes" }),
            tx.clone(),
        )
        .await
        .unwrap_err();
        assert_eq!(invalid_power.data.unwrap()["errorCode"], "INVALID_PARAMS");

        let invalid_retry = handle_request(
            state.clone(),
            "settings.set",
            json!({ "infiniteProviderRetry": "yes" }),
            tx.clone(),
        )
        .await
        .unwrap_err();
        assert_eq!(invalid_retry.data.unwrap()["errorCode"], "INVALID_PARAMS");

        let invalid_threshold = handle_request(
            state.clone(),
            "settings.set",
            json!({ "largePasteThreshold": 0 }),
            tx.clone(),
        )
        .await
        .unwrap_err();
        assert_eq!(
            invalid_threshold.data.unwrap()["errorCode"],
            "INVALID_PARAMS"
        );

        let invalid = handle_request(
            state.clone(),
            "settings.set",
            json!({ "defaultCommandShell": "not-a-shell" }),
            tx.clone(),
        )
        .await
        .unwrap_err();
        assert_eq!(invalid.data.unwrap()["errorCode"], "COMMAND_SHELL_INVALID");

        let catalog = handle_request(state.clone(), "commandShells.list", json!({}), tx)
            .await
            .unwrap();
        assert_eq!(
            catalog["configuredId"],
            crate::tools::shell::default_shell_id()
        );
        assert!(catalog["choices"].is_array());
        assert!(catalog["effective"].is_object() || catalog["effective"].is_null());
    }

    #[tokio::test]
    async fn prompt_enhancement_templates_round_trip_and_validate() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();

        // Nothing stored yet: the field is absent, so the renderer falls back
        // to the built-in default.
        let settings = handle_request(state.clone(), "settings.get", json!({}), tx.clone())
            .await
            .unwrap();
        assert!(settings.get("promptEnhancementUserTemplate").is_none());

        // A custom template and its switch persist unchanged.
        handle_request(
            state.clone(),
            "settings.set",
            json!({
                "promptEnhancementCustomTemplate": true,
                "promptEnhancementUserTemplate": "before {{draft}} after",
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        let stored = handle_request(state.clone(), "settings.get", json!({}), tx.clone())
            .await
            .unwrap();
        assert_eq!(
            stored["promptEnhancementUserTemplate"],
            "before {{draft}} after"
        );
        assert_eq!(stored["promptEnhancementCustomTemplate"], true);

        // A user template without the draft variable would silently drop the
        // draft, so the write is rejected rather than normalized.
        let missing_variable = handle_request(
            state.clone(),
            "settings.set",
            json!({ "promptEnhancementUserTemplate": "no placeholder" }),
            tx.clone(),
        )
        .await
        .unwrap_err();
        assert_eq!(
            missing_variable.data.unwrap()["errorCode"],
            "INVALID_PARAMS"
        );

        // An oversized template is rejected too.
        let oversized = handle_request(
            state.clone(),
            "settings.set",
            json!({ "promptEnhancementUserTemplate": "x".repeat(8001) }),
            tx.clone(),
        )
        .await
        .unwrap_err();
        assert_eq!(oversized.data.unwrap()["errorCode"], "INVALID_PARAMS");

        // The system prompt is not overridable: a write carrying one is dropped
        // by normalization, so the store cannot hold a value that would never
        // be read.
        handle_request(
            state.clone(),
            "settings.set",
            json!({ "promptEnhancementSystemPrompt": "custom system" }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert!(
            handle_request(state.clone(), "settings.get", json!({}), tx.clone())
                .await
                .unwrap()
                .get("promptEnhancementSystemPrompt")
                .is_none()
        );

        // Writing a blank value means "restore the default": the override is
        // dropped rather than persisted as an empty string.
        handle_request(
            state.clone(),
            "settings.set",
            json!({ "promptEnhancementUserTemplate": "   " }),
            tx,
        )
        .await
        .unwrap();
        let cleared = handle_request(
            state,
            "settings.get",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert!(cleared.get("promptEnhancementUserTemplate").is_none());
    }

    #[tokio::test]
    async fn settings_set_round_trips_an_explicitly_disabled_shortcut() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let tx = mpsc::unbounded_channel().0;

        handle_request(
            state.clone(),
            "settings.set",
            json!({ "keybindings": { "openSearch": null } }),
            tx.clone(),
        )
        .await
        .unwrap();
        let disabled = handle_request(state.clone(), "settings.get", json!({}), tx.clone())
            .await
            .unwrap();
        assert_eq!(disabled["keybindings"]["openSearch"], Value::Null);

        handle_request(
            state.clone(),
            "settings.set",
            json!({ "theme": "light" }),
            tx.clone(),
        )
        .await
        .unwrap();
        let preserved = handle_request(state, "settings.get", json!({}), tx)
            .await
            .unwrap();
        assert_eq!(preserved["keybindings"]["openSearch"], Value::Null);
    }

    #[tokio::test]
    async fn settings_set_round_trips_live_voice_without_changing_dictation_settings() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let tx = mpsc::unbounded_channel().0;
        let live_voice = json!({
            "enabled": false,
            "selectedBindingId": "codex-main",
            "bindings": [{
                "id": "codex-main",
                "adapterId": "codex-live",
                "providerId": "codex-account-a",
                "voice": "cove"
            }]
        });
        let dictation = json!({
            "enabled": true,
            "deviceId": "microphone-1",
            "languages": ["en"],
            "chineseVariant": "simplified",
            "modelId": "local-model"
        });

        handle_request(
            state.clone(),
            "settings.set",
            json!({ "liveVoice": live_voice, "voice": dictation }),
            tx.clone(),
        )
        .await
        .unwrap();
        handle_request(
            state.clone(),
            "settings.set",
            json!({ "theme": "light" }),
            tx.clone(),
        )
        .await
        .unwrap();
        let stored = handle_request(state, "settings.get", json!({}), tx)
            .await
            .unwrap();

        assert_eq!(stored["liveVoice"], live_voice);
        assert_eq!(stored["voice"], dictation);
        assert_eq!(stored["theme"], "light");
    }

    #[tokio::test]
    async fn settings_set_preserves_stored_shell_when_shell_is_omitted() {
        let Some(current_shell) = available_test_shell_id() else {
            return;
        };
        let Some(stored_shell) = alternate_available_test_shell_id(&current_shell) else {
            return;
        };
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let tx = mpsc::unbounded_channel().0;

        handle_request(
            state.clone(),
            "settings.set",
            json!({ "defaultCommandShell": stored_shell.clone() }),
            tx.clone(),
        )
        .await
        .unwrap();
        handle_request(
            state.clone(),
            "settings.set",
            json!({ "theme": "light" }),
            tx.clone(),
        )
        .await
        .unwrap();

        let settings = handle_request(state, "settings.get", json!({}), tx)
            .await
            .unwrap();
        assert_eq!(settings["defaultCommandShell"], stored_shell);
        assert_eq!(settings["theme"], "light");
    }

    /// Creates a provider row through the RPC surface the shell uses.
    async fn create_test_provider(
        state: Arc<Mutex<AppState>>,
        tx: mpsc::UnboundedSender<String>,
    ) -> String {
        let created = handle_request(
            state,
            "providers.create",
            json!({
                "name": "Image service",
                "baseUrl": "http://localhost:8080/v1",
                "authKind": "none",
                "defaultModelId": "gpt-image-2.5"
            }),
            tx,
        )
        .await
        .unwrap();
        created["provider"]["id"].as_str().unwrap().to_string()
    }

    #[tokio::test]
    async fn settings_set_drops_image_bindings_whose_provider_is_gone() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();
        let provider_id = create_test_provider(state.clone(), tx.clone()).await;

        // The shell writes whole snapshots back, so a binding for a row that no
        // longer exists can arrive through an ordinary settings write.
        handle_request(
            state.clone(),
            "settings.set",
            json!({
                "imageGeneration": { "providerId": provider_id, "modelId": "gpt-image-2.5" },
                "imageGenerationModels": [
                    { "providerId": provider_id, "modelId": "gpt-image-2.5" },
                    { "providerId": "removed-service", "modelId": "gpt-image-2.5" }
                ]
            }),
            tx.clone(),
        )
        .await
        .unwrap();

        let settings = handle_request(state.clone(), "settings.get", json!({}), tx.clone())
            .await
            .unwrap();
        assert_eq!(
            settings["imageGeneration"],
            json!({ "providerId": provider_id, "modelId": "gpt-image-2.5" })
        );
        assert_eq!(
            settings["imageGenerationModels"],
            json!([{ "providerId": provider_id, "modelId": "gpt-image-2.5" }])
        );

        let stored = state.lock().await.db.get_setting("app").unwrap().unwrap();
        assert_eq!(stored["imageGenerationModels"].as_array().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn settings_get_repairs_a_binding_left_by_a_deleted_provider() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();
        let provider_id = create_test_provider(state.clone(), tx.clone()).await;

        handle_request(
            state.clone(),
            "settings.set",
            json!({
                "imageGeneration": { "providerId": provider_id, "modelId": "gpt-image-2.5" },
                "imageGenerationModels": [
                    { "providerId": provider_id, "modelId": "gpt-image-2.5" }
                ]
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        let deleted = handle_request(
            state.clone(),
            "providers.delete",
            json!({ "id": provider_id }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(deleted["ok"], true);

        // Reading the settings repairs what the deletion left behind, so a
        // binding the runtime would reject never reaches the shell again.
        let settings = handle_request(state.clone(), "settings.get", json!({}), tx.clone())
            .await
            .unwrap();
        assert!(settings["imageGeneration"].is_null());
        assert_eq!(settings["imageGenerationModels"], json!([]));

        let stored = state.lock().await.db.get_setting("app").unwrap().unwrap();
        assert!(stored["imageGeneration"].is_null());
        assert_eq!(stored["imageGenerationModels"], json!([]));
    }

    #[tokio::test]
    async fn settings_keep_image_bindings_for_a_disabled_provider() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();
        let provider_id = create_test_provider(state.clone(), tx.clone()).await;
        let disabled = handle_request(
            state.clone(),
            "providers.update",
            json!({ "id": provider_id, "enabled": false }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(disabled["provider"]["enabled"], false);

        // A row that still exists keeps its binding: an unavailable but
        // present provider is a state the user repairs in Settings, and
        // pruning it would silently discard the user's choice.
        handle_request(
            state.clone(),
            "settings.set",
            json!({
                "imageGeneration": { "providerId": provider_id, "modelId": "gpt-image-2.5" }
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        let settings = handle_request(state, "settings.get", json!({}), tx)
            .await
            .unwrap();
        assert_eq!(
            settings["imageGeneration"],
            json!({ "providerId": provider_id, "modelId": "gpt-image-2.5" })
        );
    }

    #[tokio::test]
    async fn settings_set_same_shell_is_idempotent_during_an_active_turn() {
        let Some(current_shell) = available_test_shell_id() else {
            return;
        };
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Active settings".into()),
            Some("agent".into()),
            None,
            None,
            None,
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let tx = mpsc::unbounded_channel().0;
        let full_settings = handle_request(state.clone(), "settings.get", json!({}), tx.clone())
            .await
            .unwrap();
        let turn_id = {
            let st = state.lock().await;
            sessions::begin_turn(&st.db, &session.id, None, None).unwrap()
        };

        let mut idempotent = full_settings;
        idempotent["defaultCommandShell"] = json!(current_shell.clone());
        idempotent["theme"] = json!("light");
        handle_request(state.clone(), "settings.set", idempotent, tx.clone())
            .await
            .unwrap();

        let settings = handle_request(state.clone(), "settings.get", json!({}), tx)
            .await
            .unwrap();
        assert_eq!(settings["defaultCommandShell"], current_shell);
        assert_eq!(settings["theme"], "light");

        let st = state.lock().await;
        sessions::end_turn(&st.db, &turn_id, "completed", None, None, false).unwrap();
    }

    #[tokio::test]
    async fn settings_set_rejects_a_genuine_shell_change_during_an_active_turn() {
        let Some(current_shell) = available_test_shell_id() else {
            return;
        };
        let Some(changed_shell) = alternate_available_test_shell_id(&current_shell) else {
            return;
        };
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Shell settings".into()),
            Some("agent".into()),
            None,
            None,
            None,
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let tx = mpsc::unbounded_channel().0;
        handle_request(
            state.clone(),
            "settings.set",
            json!({ "defaultCommandShell": current_shell }),
            tx.clone(),
        )
        .await
        .unwrap();
        let turn_id = {
            let st = state.lock().await;
            sessions::begin_turn(&st.db, &session.id, None, None).unwrap()
        };

        let error = handle_request(
            state.clone(),
            "settings.set",
            json!({ "defaultCommandShell": changed_shell }),
            tx,
        )
        .await
        .unwrap_err();
        assert_eq!(
            error.data.unwrap()["errorCode"],
            "PLAN_CONFIGURATION_BLOCKED"
        );

        let st = state.lock().await;
        sessions::end_turn(&st.db, &turn_id, "completed", None, None, false).unwrap();
    }

    #[tokio::test]
    async fn settings_set_allows_a_genuine_shell_change_when_idle() {
        let Some(current_shell) = available_test_shell_id() else {
            return;
        };
        let Some(changed_shell) = alternate_available_test_shell_id(&current_shell) else {
            return;
        };
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let tx = mpsc::unbounded_channel().0;

        handle_request(
            state.clone(),
            "settings.set",
            json!({ "defaultCommandShell": current_shell }),
            tx.clone(),
        )
        .await
        .unwrap();
        handle_request(
            state.clone(),
            "settings.set",
            json!({ "defaultCommandShell": changed_shell.clone() }),
            tx.clone(),
        )
        .await
        .unwrap();

        let settings = handle_request(state, "settings.get", json!({}), tx)
            .await
            .unwrap();
        assert_eq!(settings["defaultCommandShell"], changed_shell);
    }

    #[tokio::test]
    async fn settings_rejects_unavailable_or_cross_platform_shell() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();
        let shell_id = crate::tools::shell::catalog(None)
            .choices
            .into_iter()
            .find(|choice| !choice.available)
            .map(|choice| choice.id)
            .unwrap_or_else(|| {
                if cfg!(windows) {
                    crate::tools::shell::BASH_ID.into()
                } else {
                    crate::tools::shell::WINDOWS_POWERSHELL_ID.into()
                }
            });

        let error = handle_request(
            state,
            "settings.set",
            json!({ "defaultCommandShell": shell_id }),
            tx,
        )
        .await
        .unwrap_err();
        assert_eq!(error.data.unwrap()["errorCode"], "COMMAND_SHELL_INVALID");
    }

    #[tokio::test]
    async fn default_shell_setting_is_idle_only_across_turn_and_plan_work() {
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        fs::create_dir_all(&project).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let agent = sessions::create_session(
            &app_state.db,
            Some("Agent".into()),
            Some("agent".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        let active_turn = sessions::begin_turn(&app_state.db, &agent.id, None, None).unwrap();
        let Some(current_shell) = available_test_shell_id() else {
            return;
        };
        let Some(changed_shell) = alternate_available_test_shell_id(&current_shell) else {
            return;
        };
        let state = Arc::new(Mutex::new(app_state));

        let active_error = handle_request(
            state.clone(),
            "settings.set",
            json!({ "defaultCommandShell": changed_shell.clone() }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap_err();
        assert_eq!(
            active_error.data.unwrap()["errorCode"],
            "PLAN_CONFIGURATION_BLOCKED"
        );

        {
            let st = state.lock().await;
            sessions::end_turn(&st.db, &active_turn, "completed", None, None, false).unwrap();
        }
        handle_request(
            state.clone(),
            "settings.set",
            json!({ "defaultCommandShell": changed_shell.clone() }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();

        let plan = {
            let st = state.lock().await;
            let plan_session = sessions::create_session(
                &st.db,
                Some("Plan".into()),
                Some("plan".into()),
                None,
                None,
                Some(project.to_string_lossy().into_owned()),
            )
            .unwrap();
            let turn = sessions::begin_turn(&st.db, &plan_session.id, None, None).unwrap();
            let proposal = st
                .plans
                .submit(
                    &st.db,
                    PlanSubmitParams {
                        workspace_root: &project,
                        session_id: &plan_session.id,
                        turn_id: &turn,
                        tool_call_id: "submit-shell-gate",
                        kind: crate::plans::KIND_PLAN,
                        title: "Plan",
                        markdown: "# Plan",
                        question: "Proceed?",
                    },
                )
                .unwrap();
            (plan_session.id, turn, proposal)
        };

        let pending_error = handle_request(
            state.clone(),
            "settings.set",
            json!({ "defaultCommandShell": current_shell.clone() }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap_err();
        assert_eq!(
            pending_error.data.unwrap()["errorCode"],
            "PLAN_CONFIGURATION_BLOCKED"
        );

        let execution_id = {
            let st = state.lock().await;
            sessions::end_turn(&st.db, &plan.1, "completed", None, None, false).unwrap();
            let resolution = st
                .plans
                .resolve(
                    &st.db,
                    PlanResolveParams {
                        workspace_root: Some(&project),
                        proposal_id: &plan.2.id,
                        session_id: &plan.0,
                        turn_id: &plan.1,
                        tool_call_id: &plan.2.tool_call_id,
                        version: Some(plan.2.version),
                        action: "approve",
                        target_permission_mode: Some("ask"),
                    },
                )
                .unwrap();
            resolution.execution.unwrap().id
        };

        let queued_error = handle_request(
            state.clone(),
            "settings.set",
            json!({ "defaultCommandShell": current_shell.clone() }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap_err();
        assert_eq!(
            queued_error.data.unwrap()["errorCode"],
            "PLAN_CONFIGURATION_BLOCKED"
        );

        {
            let st = state.lock().await;
            st.plans.claim_execution(&st.db, &execution_id).unwrap();
        }
        let running_error = handle_request(
            state.clone(),
            "settings.set",
            json!({ "defaultCommandShell": current_shell.clone() }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap_err();
        assert_eq!(
            running_error.data.unwrap()["errorCode"],
            "PLAN_CONFIGURATION_BLOCKED"
        );

        {
            let st = state.lock().await;
            st.plans
                .finish_execution(&st.db, &execution_id, "completed", None)
                .unwrap();
        }
        handle_request(
            state,
            "settings.set",
            json!({ "defaultCommandShell": current_shell }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn bash_rejects_a_changed_shell_before_running_the_command() {
        let Some(current_shell_id) = available_test_shell_id() else {
            return;
        };
        let expected_shell_id = [
            crate::tools::shell::WINDOWS_POWERSHELL_ID,
            crate::tools::shell::CMD_ID,
            crate::tools::shell::GIT_BASH_ID,
            crate::tools::shell::BASH_ID,
        ]
        .into_iter()
        .find(|shell_id| *shell_id != current_shell_id)
        .unwrap();
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        fs::create_dir_all(&project).unwrap();
        let marker = project.join("must-not-run.txt");
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Shell mismatch".into()),
            Some("agent".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        sessions::configure_session_with_thinking(
            &app_state.db,
            &session.id,
            "agent",
            None,
            None,
            None,
            Some("auto"),
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();
        #[cfg(windows)]
        let command = format!("[IO.File]::WriteAllText('{}', 'ran')", marker.display());
        #[cfg(not(windows))]
        let command = format!("touch '{}'", marker.display());

        let result = handle_request(
            state,
            "tools.execute",
            json!({
                "sessionId": session.id,
                "toolCallId": "mismatch-call",
                "toolName": "Bash",
                "args": { "command": command },
                "expectedCommandShellId": expected_shell_id,
                "expectedCommandShellDialect": crate::tools::shell::dialect_for_id(expected_shell_id),
                "mode": "agent"
            }),
            tx,
        )
        .await
        .unwrap();
        assert_eq!(result["errorCode"], "COMMAND_SHELL_CHANGED");
        assert_eq!(result["commandShellId"], current_shell_id);
        assert!(!marker.exists());
    }

    #[tokio::test]
    async fn bash_rejects_a_stale_shell_dialect_before_permission_or_spawn() {
        let Some(current_shell_id) = available_test_shell_id() else {
            return;
        };
        let current_dialect = crate::tools::shell::dialect_for_id(&current_shell_id).unwrap();
        let stale_dialect = if current_dialect == "posix" {
            "powershell"
        } else {
            "posix"
        };
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        fs::create_dir_all(&project).unwrap();
        let marker = project.join("must-not-run-dialect.txt");
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Shell dialect mismatch".into()),
            Some("agent".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let command = if cfg!(windows) {
            format!("[IO.File]::WriteAllText('{}', 'ran')", marker.display())
        } else {
            format!("touch '{}'", marker.display())
        };

        let result = handle_request(
            state,
            "tools.execute",
            json!({
                "sessionId": session.id,
                "toolCallId": "dialect-mismatch",
                "toolName": "Bash",
                "args": { "command": command },
                "expectedCommandShellId": current_shell_id,
                "expectedCommandShellDialect": stale_dialect,
                "mode": "agent"
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(result["errorCode"], "COMMAND_SHELL_CHANGED");
        assert_eq!(
            result["content"]["expectedCommandShellDialect"],
            stale_dialect
        );
        assert_eq!(result["content"]["commandShellDialect"], current_dialect);
        assert!(!marker.exists());
    }

    #[tokio::test]
    async fn tools_abort_before_approval_cleans_the_cancellation_registry() {
        let Some(shell_id) = available_test_shell_id() else {
            return;
        };
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        fs::create_dir_all(&project).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Abort before approval".into()),
            Some("agent".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        sessions::configure_session_with_thinking(
            &app_state.db,
            &session.id,
            "agent",
            None,
            None,
            None,
            Some("ask"),
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();
        let session_id = session.id.clone();
        let pending_state = state.clone();
        let pending_task = tokio::spawn(async move {
            handle_request(
                pending_state,
                "tools.execute",
                json!({
                    "sessionId": session_id,
                    "toolCallId": "abort-before-approval",
                    "toolName": "Bash",
                    "args": { "command": sleeping_bash_command() },
                    "expectedCommandShellId": shell_id,
                    "expectedCommandShellDialect": crate::tools::shell::dialect_for_id(&shell_id),
                    "mode": "agent"
                }),
                tx,
            )
            .await
        });
        wait_for_bash_registration(&state, &session.id, "abort-before-approval").await;

        let aborted = handle_request(
            state.clone(),
            "tools.abort",
            json!({
                "sessionId": session.id,
                "toolCallId": "abort-before-approval"
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(aborted["found"], true);
        let result = tokio::time::timeout(std::time::Duration::from_secs(2), pending_task)
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        assert_eq!(result["errorCode"], "TOOL_ABORTED");
        assert_eq!(result["content"]["code"], "TOOL_ABORTED");
        assert_bash_registry_empty(&state).await;

        let second = handle_request(
            state,
            "tools.abort",
            json!({
                "sessionId": session.id,
                "toolCallId": "abort-before-approval"
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(second["found"], false);
    }

    #[tokio::test]
    async fn permissions_pending_lists_the_open_request_until_resolved() {
        let Some(shell_id) = available_test_shell_id() else {
            return;
        };
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        fs::create_dir_all(&project).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Pending permission read".into()),
            Some("agent".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        sessions::configure_session_with_thinking(
            &app_state.db,
            &session.id,
            "agent",
            None,
            None,
            None,
            Some("ask"),
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (tx, mut rx) = mpsc::unbounded_channel();
        let session_id = session.id.clone();
        let pending_state = state.clone();
        let pending_task = tokio::spawn(async move {
            handle_request(
                pending_state,
                "tools.execute",
                json!({
                    "sessionId": session_id,
                    "toolCallId": "pending-read",
                    "toolName": "Bash",
                    "args": { "command": sleeping_bash_command() },
                    "expectedCommandShellId": shell_id,
                    "expectedCommandShellDialect": crate::tools::shell::dialect_for_id(&shell_id),
                    "mode": "agent"
                }),
                tx,
            )
            .await
        });
        let permission = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
            .await
            .unwrap()
            .unwrap();
        let permission: Value = serde_json::from_str(&permission).unwrap();
        assert_eq!(permission["method"], "permissions.request");
        assert!(permission["params"].get("timeoutMs").is_none());
        let request_id = permission["params"]["requestId"]
            .as_str()
            .unwrap()
            .to_string();

        let listed = handle_request(
            state.clone(),
            "permissions.pending",
            json!({ "sessionId": session.id }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        let requests = listed["requests"].as_array().unwrap();
        assert_eq!(requests.len(), 1);
        assert_eq!(requests[0]["requestId"], request_id);
        assert_eq!(requests[0]["sessionId"], session.id);
        assert_eq!(requests[0]["toolName"], "Bash");
        assert!(requests[0].get("timeoutMs").is_none());
        assert!(requests[0].get("expiresAt").is_none());
        assert!(requests[0].get("remainingMs").is_none());

        let other = handle_request(
            state.clone(),
            "permissions.pending",
            json!({ "sessionId": "another-session" }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert!(other["requests"].as_array().unwrap().is_empty());

        handle_request(
            state.clone(),
            "permissions.resolve",
            json!({ "requestId": request_id, "decision": "deny" }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        let result = pending_task.await.unwrap().unwrap();
        assert_eq!(result["errorCode"], "TOOL_DENIED");

        let after = handle_request(
            state.clone(),
            "permissions.pending",
            json!({}),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert!(after["requests"].as_array().unwrap().is_empty());
        assert_bash_registry_empty(&state).await;
    }

    #[tokio::test]
    async fn tools_abort_cancels_a_pending_write_approval_before_it_can_mutate_files() {
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        fs::create_dir_all(&project).unwrap();
        let destination = project.join("must-not-exist.txt");
        let destination_for_tool = destination.to_string_lossy().into_owned();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Abort pending Write".into()),
            Some("agent".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        sessions::configure_session_with_thinking(
            &app_state.db,
            &session.id,
            "agent",
            None,
            None,
            None,
            Some("ask"),
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (tx, mut rx) = mpsc::unbounded_channel();
        let pending_state = state.clone();
        let pending_session_id = session.id.clone();
        let pending = tokio::spawn(async move {
            handle_request(
                pending_state,
                "tools.execute",
                json!({
                    "sessionId": pending_session_id,
                    "toolCallId": "write-stop-pending-approval",
                    "toolName": "Write",
                    "args": {
                        "path": destination_for_tool,
                        "content": "must not be written"
                    },
                    "mode": "agent"
                }),
                tx,
            )
            .await
        });
        wait_for_tool_registration(&state, &session.id, "write-stop-pending-approval", "Write")
            .await;
        let permission: Value = serde_json::from_str(
            &tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
                .await
                .unwrap()
                .unwrap(),
        )
        .unwrap();
        assert_eq!(permission["method"], "permissions.request");

        let aborted = handle_request(
            state.clone(),
            "tools.abort",
            json!({
                "sessionId": session.id,
                "toolCallId": "write-stop-pending-approval",
                "toolName": "Write"
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(aborted["found"], true);
        let result = tokio::time::timeout(std::time::Duration::from_secs(2), pending)
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        assert_eq!(result["errorCode"], "TOOL_ABORTED");
        assert!(!destination.exists());
        assert_bash_registry_empty(&state).await;
        assert!(state.lock().await.active_tool_cancellations.is_empty());
        assert!(state.lock().await.pending_tool_aborts.is_empty());

        let late_resolution = handle_request(
            state,
            "permissions.resolve",
            json!({
                "requestId": permission["params"]["requestId"],
                "decision": "allow-once"
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap_err();
        assert_eq!(late_resolution.data.unwrap()["errorCode"], "NOT_FOUND");
    }

    #[tokio::test]
    async fn tools_abort_during_permission_removes_the_pending_request() {
        let Some(shell_id) = available_test_shell_id() else {
            return;
        };
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        fs::create_dir_all(&project).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Abort during approval".into()),
            Some("agent".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        sessions::configure_session_with_thinking(
            &app_state.db,
            &session.id,
            "agent",
            None,
            None,
            None,
            Some("ask"),
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (tx, mut rx) = mpsc::unbounded_channel();
        let session_id = session.id.clone();
        let pending_state = state.clone();
        let pending_task = tokio::spawn(async move {
            handle_request(
                pending_state,
                "tools.execute",
                json!({
                    "sessionId": session_id,
                    "toolCallId": "abort-during-approval",
                    "toolName": "Bash",
                    "args": { "command": sleeping_bash_command() },
                    "expectedCommandShellId": shell_id,
                    "expectedCommandShellDialect": crate::tools::shell::dialect_for_id(&shell_id),
                    "mode": "agent"
                }),
                tx,
            )
            .await
        });
        let permission = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
            .await
            .unwrap()
            .unwrap();
        let permission: Value = serde_json::from_str(&permission).unwrap();
        assert_eq!(permission["method"], "permissions.request");
        assert_eq!(
            permission["params"]["commandShellId"],
            crate::tools::shell::catalog(None).effective.unwrap().id
        );
        let request_id = permission["params"]["requestId"]
            .as_str()
            .unwrap()
            .to_string();

        let aborted = handle_request(
            state.clone(),
            "tools.abort",
            json!({
                "sessionId": session.id,
                "toolCallId": "abort-during-approval"
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(aborted["aborted"], true);
        let result = pending_task.await.unwrap().unwrap();
        assert_eq!(result["errorCode"], "TOOL_ABORTED");

        let late_resolution = handle_request(
            state.clone(),
            "permissions.resolve",
            json!({ "requestId": request_id, "decision": "allow-once" }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap_err();
        assert_eq!(late_resolution.data.unwrap()["errorCode"], "NOT_FOUND");
        assert_bash_registry_empty(&state).await;
    }

    #[tokio::test]
    async fn tools_abort_during_execution_kills_bash_and_cleans_registry() {
        let Some(shell_id) = available_test_shell_id() else {
            return;
        };
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        fs::create_dir_all(&project).unwrap();
        let started_marker = project.join("started.txt");
        let late_marker = project.join("late.txt");
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Abort execution".into()),
            Some("agent".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        sessions::configure_session_with_thinking(
            &app_state.db,
            &session.id,
            "agent",
            None,
            None,
            None,
            Some("auto"),
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();
        let started_command = descendant_marker_bash_command(&started_marker, &late_marker);
        let session_id = session.id.clone();
        let pending_state = state.clone();
        let pending_task = tokio::spawn(async move {
            handle_request(
                pending_state,
                "tools.execute",
                json!({
                    "sessionId": session_id,
                    "toolCallId": "abort-during-execution",
                    "toolName": "Bash",
                    "args": { "command": started_command },
                    "expectedCommandShellId": shell_id,
                    "expectedCommandShellDialect": crate::tools::shell::dialect_for_id(&shell_id),
                    "mode": "agent"
                }),
                tx,
            )
            .await
        });
        wait_for_bash_registration(&state, &session.id, "abort-during-execution").await;
        for _ in 0..100 {
            if started_marker.exists() {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
        assert!(
            started_marker.exists(),
            "the command should have started before abort"
        );

        let aborted = handle_request(
            state.clone(),
            "tools.abort",
            json!({
                "sessionId": session.id,
                "toolCallId": "abort-during-execution"
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(aborted["found"], true);
        let result = tokio::time::timeout(std::time::Duration::from_secs(5), pending_task)
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        assert_eq!(result["errorCode"], "TOOL_ABORTED");
        tokio::time::sleep(std::time::Duration::from_millis(1_500)).await;
        assert!(
            !late_marker.exists(),
            "aborted descendants must not write later"
        );
        assert_bash_registry_empty(&state).await;
    }

    #[tokio::test]
    async fn bash_timeout_and_early_session_error_clean_the_registry() {
        let Some(shell_id) = available_test_shell_id() else {
            return;
        };
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        fs::create_dir_all(&project).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Timeout".into()),
            Some("agent".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        sessions::configure_session_with_thinking(
            &app_state.db,
            &session.id,
            "agent",
            None,
            None,
            None,
            Some("auto"),
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();
        let timeout_started = project.join("timeout-started.txt");
        let timeout_late = project.join("timeout-late.txt");
        let timeout_command = descendant_marker_bash_command(&timeout_started, &timeout_late);
        let timeout_result = handle_request(
            state.clone(),
            "tools.execute",
            json!({
                "sessionId": session.id,
                "toolCallId": "timeout-call",
                "toolName": "Bash",
                "args": { "command": timeout_command },
                "expectedCommandShellId": shell_id,
                "expectedCommandShellDialect": crate::tools::shell::dialect_for_id(&shell_id),
                "timeoutMs": 1000,
                "mode": "agent"
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(timeout_result["errorCode"], "TOOL_TIMEOUT");
        tokio::time::sleep(std::time::Duration::from_millis(1_500)).await;
        assert!(
            !timeout_late.exists(),
            "timed-out descendants must not write later"
        );
        assert_bash_registry_empty(&state).await;

        let early = handle_request(
            state.clone(),
            "tools.execute",
            json!({
                "sessionId": "missing-session",
                "toolCallId": "early-error",
                "toolName": "Bash",
                "args": { "command": sleeping_bash_command() },
                "expectedCommandShellId": shell_id,
                "expectedCommandShellDialect": crate::tools::shell::dialect_for_id(&shell_id),
                "mode": "agent"
            }),
            tx,
        )
        .await
        .unwrap_err();
        assert_eq!(early.data.unwrap()["errorCode"], "SESSION_NOT_FOUND");
        assert_bash_registry_empty(&state).await;
    }

    #[tokio::test]
    async fn bash_output_is_streamed_with_shell_identity_and_unicode() {
        let Some(shell_id) = available_test_shell_id() else {
            return;
        };
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        fs::create_dir_all(&project).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Output".into()),
            Some("agent".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        sessions::configure_session_with_thinking(
            &app_state.db,
            &session.id,
            "agent",
            None,
            None,
            None,
            Some("auto"),
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (tx, mut rx) = mpsc::unbounded_channel();
        let result = handle_request(
            state.clone(),
            "tools.execute",
            json!({
                "sessionId": session.id,
                "toolCallId": "output-call",
                "toolName": "Bash",
                "args": { "command": output_bash_command() },
                "expectedCommandShellId": shell_id,
                "expectedCommandShellDialect": crate::tools::shell::dialect_for_id(&shell_id),
                "mode": "agent"
            }),
            tx,
        )
        .await
        .unwrap();
        assert_eq!(result["ok"], true);
        assert_eq!(result["commandShellId"], shell_id);
        assert!(result["content"]["stdout"]
            .as_str()
            .unwrap()
            .contains("out-π"));
        assert!(result["content"]["stderr"]
            .as_str()
            .unwrap()
            .contains("err-π"));

        let mut streams = Vec::new();
        while let Ok(raw) = rx.try_recv() {
            let notification: Value = serde_json::from_str(&raw).unwrap();
            if notification["method"] == "tools.output" {
                assert_eq!(notification["params"]["commandShellId"], shell_id);
                streams.push(notification["params"]["stream"].clone());
            }
        }
        assert!(streams.iter().any(|stream| stream == "stdout"));
        assert!(streams.iter().any(|stream| stream == "stderr"));
        assert_bash_registry_empty(&state).await;
    }

    #[tokio::test]
    async fn bash_mismatch_does_not_register_a_cancellation() {
        let Some(current_shell_id) = available_test_shell_id() else {
            return;
        };
        let expected_shell_id = if current_shell_id == crate::tools::shell::BASH_ID {
            crate::tools::shell::CMD_ID
        } else {
            crate::tools::shell::BASH_ID
        };
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();
        let result = handle_request(
            state.clone(),
            "tools.execute",
            json!({
                "sessionId": "missing-session",
                "toolCallId": "mismatch-no-register",
                "toolName": "Bash",
                "args": { "command": "should-not-run" },
                "expectedCommandShellId": expected_shell_id,
                "expectedCommandShellDialect": crate::tools::shell::dialect_for_id(expected_shell_id),
                "mode": "agent"
            }),
            tx,
        )
        .await
        .unwrap();
        assert_eq!(result["errorCode"], "COMMAND_SHELL_CHANGED");
        assert_bash_registry_empty(&state).await;
    }

    #[tokio::test]
    async fn plan_rpc_submits_immediately_and_roundtrips_execution_outbox() {
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        fs::create_dir_all(&project).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        app_state.workspace.set(data_dir.path().join("other"));
        let session = sessions::create_session(
            &app_state.db,
            Some("Plan".into()),
            Some("plan".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        let turn_id = sessions::begin_turn(&app_state.db, &session.id, None, None).unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (tx, mut notifications) = mpsc::unbounded_channel();
        let markdown = "  # Plan\n- implement  \n";

        let submitted = handle_request(
            state.clone(),
            "plans.submit",
            json!({
                "sessionId": session.id,
                "turnId": turn_id,
                "toolCallId": "submit-call",
                "title": "Build API",
                "markdown": markdown,
                "question": "Proceed?"
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(submitted["status"], "pending");
        assert_eq!(submitted["proposal"]["title"], "Build API");
        assert_eq!(submitted["proposal"]["markdown"], markdown);
        assert_eq!(submitted["proposal"]["plan"], markdown);
        assert_eq!(submitted["proposal"]["question"], "Proceed?");
        assert_eq!(
            submitted["proposal"]["artifact"]["sizeBytes"],
            json!(markdown.len())
        );
        let artifact_path = submitted["proposal"]["artifact"]["relativePath"]
            .as_str()
            .unwrap();
        assert_eq!(
            fs::read(project.join(artifact_path)).unwrap(),
            markdown.as_bytes()
        );
        assert!(submitted["proposal"].get("expiresAt").is_some());
        let _submit_event: Value =
            serde_json::from_str(&notifications.recv().await.unwrap()).unwrap();
        let proposal_id = submitted["proposal"]["id"].as_str().unwrap();
        let version = submitted["proposal"]["version"].as_i64().unwrap();

        let configure_error = handle_request(
            state.clone(),
            "session.configure",
            json!({
                "id": session.id,
                "mode": "agent",
                "permissionMode": "auto"
            }),
            tx.clone(),
        )
        .await
        .unwrap_err();
        assert_eq!(
            configure_error.data.unwrap()["errorCode"],
            "PLAN_CONFIGURATION_BLOCKED"
        );

        let pending = handle_request(
            state.clone(),
            "plans.pending",
            json!({ "sessionId": session.id }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(pending["plans"].as_array().unwrap().len(), 1);

        let resolved = handle_request(
            state.clone(),
            "plans.resolve",
            json!({
                "proposalId": proposal_id,
                "sessionId": session.id,
                "turnId": turn_id,
                "toolCallId": "submit-call",
                "version": version,
                "action": "approve",
                "targetPermissionMode": "auto"
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(resolved["proposal"]["status"], "approved");
        assert_eq!(resolved["execution"]["state"], "queued");
        let execution_id = resolved["execution"]["id"].as_str().unwrap();

        let queued = handle_request(
            state.clone(),
            "plans.queuedExecutions",
            json!({}),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(queued["executions"].as_array().unwrap().len(), 1);
        let claimed = handle_request(
            state.clone(),
            "plans.claimExecution",
            json!({ "executionId": execution_id }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(claimed["execution"]["state"], "running");
        let finished = handle_request(
            state,
            "plans.finishExecution",
            json!({ "executionId": execution_id, "status": "completed" }),
            tx,
        )
        .await
        .unwrap();
        assert_eq!(finished["execution"]["state"], "completed");
    }

    #[tokio::test]
    async fn plan_enter_rpc_accepts_the_active_agent_turn() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Agent".into()),
            Some("agent".into()),
            None,
            None,
            None,
        )
        .unwrap();
        let turn_id = sessions::begin_turn(&app_state.db, &session.id, None, None).unwrap();
        let state = Arc::new(Mutex::new(app_state));

        let entered = handle_request(
            state.clone(),
            "plans.enter",
            json!({
                "sessionId": session.id,
                "turnId": turn_id,
                "toolCallId": "enter-call"
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(entered["state"], "planning");
        assert_eq!(
            sessions::session_mode(&state.lock().await.db, &session.id)
                .unwrap()
                .as_deref(),
            Some("plan")
        );
    }

    #[tokio::test]
    async fn scheduled_run_rejects_contract_modes_before_creating_session_or_run() {
        // Plan and Goal both need a human to approve their proposal (D198), so
        // neither can be launched by the scheduler.
        for mode in ["plan", "goal"] {
            let data_dir = tempfile::tempdir().unwrap();
            let mut app_state = AppState::open(data_dir.path()).unwrap();
            app_state.handshook = true;
            let task = scheduled::create_task(
                &app_state.db,
                &json!({
                    "title": format!("{mode} schedule"),
                    "prompt": "run this",
                    "mode": mode
                }),
            )
            .unwrap();
            assert_eq!(task.mode, mode);
            app_state
                .db
                .set_setting("app", &json!({ "defaultMode": "agent" }))
                .unwrap();
            let state = Arc::new(Mutex::new(app_state));
            let (tx, _rx) = mpsc::unbounded_channel();

            let error =
                handle_request(state.clone(), "scheduled.run", json!({ "id": task.id }), tx)
                    .await
                    .unwrap_err();
            assert_eq!(
                error.data.unwrap()["errorCode"],
                "PLAN_REQUIRES_INTERACTIVE_SESSION",
                "{mode}"
            );

            let st = state.lock().await;
            let session_count: i64 = st
                .db
                .conn()
                .query_row("SELECT COUNT(*) FROM sessions", [], |row| row.get(0))
                .unwrap();
            let run_count: i64 = st
                .db
                .conn()
                .query_row("SELECT COUNT(*) FROM task_runs", [], |row| row.get(0))
                .unwrap();
            assert_eq!(session_count, 0, "{mode}");
            assert_eq!(run_count, 0, "{mode}");
        }
    }

    #[tokio::test]
    async fn scheduled_agent_task_ignores_global_plan_default() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let task = scheduled::create_task(
            &app_state.db,
            &json!({ "title": "Agent schedule", "prompt": "run this" }),
        )
        .unwrap();
        app_state
            .db
            .set_setting("app", &json!({ "defaultMode": "plan" }))
            .unwrap();
        let state = Arc::new(Mutex::new(app_state));

        let result = handle_request(
            state.clone(),
            "scheduled.run",
            json!({ "id": task.id }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(result["task"]["mode"], "agent");
        let st = state.lock().await;
        let mode = sessions::session_mode(&st.db, result["sessionId"].as_str().unwrap()).unwrap();
        assert_eq!(mode.as_deref(), Some("agent"));
        assert!(result["runId"].as_str().is_some());
    }

    #[tokio::test]
    async fn begin_turn_reports_agent_busy_without_creating_a_duplicate() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Busy".into()),
            Some("agent".into()),
            None,
            None,
            None,
        )
        .unwrap();
        let first = sessions::begin_turn(&app_state.db, &session.id, None, None).unwrap();
        let state = Arc::new(Mutex::new(app_state));

        let (tx, _rx) = mpsc::unbounded_channel();
        let error = handle_request(
            state.clone(),
            "session.beginTurn",
            json!({ "sessionId": session.id }),
            tx,
        )
        .await
        .unwrap_err();
        assert_eq!(error.data.unwrap()["errorCode"], "AGENT_BUSY");

        let st = state.lock().await;
        let running: i64 = st
            .db
            .conn()
            .query_row(
                "SELECT COUNT(*) FROM turns
                 WHERE session_id = ?1 AND status = 'running'",
                [&session.id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(running, 1);
        drop(st);
        let st = state.lock().await;
        sessions::end_turn(&st.db, &first, "aborted", None, None, false).unwrap();
    }

    #[tokio::test]
    async fn truncate_from_rpc_cuts_without_shipping_the_kept_prefix() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Large".into()),
            Some("agent".into()),
            None,
            None,
            None,
        )
        .unwrap();
        let turn = sessions::begin_turn(&app_state.db, &session.id, None, None).unwrap();
        let prefix: sessions::UiMessage = serde_json::from_value(json!({
            "id": "u0",
            "role": "user",
            "content": "earlier",
            "createdAt": "2025-05-01T00:00:00Z"
        }))
        .unwrap();
        let root: sessions::UiMessage = serde_json::from_value(json!({
            "id": "u1",
            "role": "user",
            "content": "retry me",
            "createdAt": "2025-05-01T00:00:01Z"
        }))
        .unwrap();
        sessions::append_message(&app_state.db, &session.id, &prefix, Some(&turn)).unwrap();
        sessions::append_message(&app_state.db, &session.id, &root, Some(&turn)).unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();

        let result = handle_request(
            state.clone(),
            "session.truncateFrom",
            json!({ "sessionId": session.id, "fromMessageId": "u1" }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(result["ok"], json!(true));
        assert_eq!(result["keptCount"], json!(1));
        assert_eq!(result["discardedCount"], json!(1));
        assert_eq!(result["abortedTurnId"], json!(turn));

        let detail = handle_request(
            state.clone(),
            "session.get",
            json!({ "id": session.id, "messageLimit": 10 }),
            tx,
        )
        .await
        .unwrap();
        let messages = detail["session"]["messages"].as_array().unwrap();
        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0]["id"], json!("u0"));

        let missing = handle_request(
            state,
            "session.truncateFrom",
            json!({ "sessionId": session.id, "fromMessageId": "gone" }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap_err();
        assert_eq!(missing.data.unwrap()["errorCode"], "NOT_FOUND");
    }

    #[tokio::test]
    async fn edit_self_move_rpc_preserves_file_and_read_provenance() {
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        fs::create_dir_all(&project).unwrap();
        let source = project.join("source.txt");
        fs::write(&source, "original\n").unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Self move".into()),
            Some("agent".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        sessions::configure_session_with_thinking(
            &app_state.db,
            &session.id,
            "agent",
            None,
            None,
            None,
            Some("auto"),
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();
        let read = handle_request(
            state.clone(),
            "tools.execute",
            json!({"sessionId": session.id, "toolCallId": "read-source",
                "toolName": "Read", "args": {"path": "source.txt"}, "mode": "agent"}),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(read["ok"], true, "{read}");
        let tag = &read["content"]["tag"];
        let rejected = handle_request(
            state.clone(),
            "tools.execute",
            json!({"sessionId": session.id, "toolCallId": "self-move",
                "toolName": "Edit", "args": {"path": "source.txt", "tag": tag,
                    "ops": "PUT 1.=1:\n+must not land\nMV ./source.txt\n"}, "mode": "agent"}),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(rejected["ok"], false, "{rejected}");
        assert_eq!(rejected["errorCode"], "EDIT_NO_CHANGE", "{rejected}");
        assert_eq!(fs::read(&source).unwrap(), b"original\n");
        // Failure must not invalidate the Read snapshot or poison later edits.
        let edited = handle_request(
            state,
            "tools.execute",
            json!({"sessionId": session.id, "toolCallId": "valid-edit",
                "toolName": "Edit", "args": {"path": "source.txt", "tag": tag,
                    "ops": "PUT 1.=1:\n+changed\n"}, "mode": "agent"}),
            tx,
        )
        .await
        .unwrap();
        assert_eq!(edited["ok"], true, "{edited}");
        assert_eq!(fs::read(&source).unwrap(), b"changed\n");
    }

    /// D137: the audit row for a tool call must carry the three segments
    /// separately, so "the tool was slow" can be told apart from "the user
    /// took 20s to approve it".
    #[tokio::test]
    async fn tool_execute_audit_records_segmented_timing() {
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        fs::create_dir_all(&project).unwrap();
        fs::write(project.join("note.txt"), "hello").unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Timing".into()),
            Some("agent".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();

        // Read is low risk, so it auto-allows and never prompts — the run
        // therefore has a zero approval segment by construction.
        let result = handle_request(
            state.clone(),
            "tools.execute",
            json!({
                "sessionId": session.id,
                "toolCallId": "tc-1",
                "toolName": "Read",
                "args": { "path": "note.txt" },
                "mode": "agent"
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(result["ok"], json!(true), "read succeeded: {result}");

        let st = state.lock().await;
        let payload: String = st
            .db
            .conn()
            .query_row(
                "SELECT payload_json FROM audit_log WHERE kind = 'tool_execute' ORDER BY id DESC LIMIT 1",
                [],
                |r| r.get(0),
            )
            .unwrap();
        let payload: serde_json::Value = serde_json::from_str(&payload).unwrap();
        assert_eq!(payload["toolName"], json!("Read"));
        assert_eq!(payload["prompted"], json!(false));
        // Auto-allowed, so the approval segment is bookkeeping only: assert it
        // is negligible rather than exactly zero, since a loaded test runner
        // can still spend a millisecond there.
        let permission_wait_ms = payload["permissionWaitMs"].as_u64().unwrap();
        assert!(
            permission_wait_ms < 100,
            "auto-allow does not wait: {permission_wait_ms}ms"
        );
        let execute_ms = payload["durationMs"].as_u64().unwrap();
        let overhead_ms = payload["overheadMs"].as_u64().unwrap();
        let total_ms = payload["totalMs"].as_u64().unwrap();
        assert!(
            total_ms >= execute_ms,
            "total {total_ms} covers execution {execute_ms}"
        );
        assert_eq!(
            overhead_ms,
            total_ms - execute_ms - permission_wait_ms,
            "segments add up to the total"
        );
    }

    #[tokio::test]
    async fn outside_paths_prompt_in_plan_and_auto_allows_after_mode_switch() {
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        let outside = data_dir.path().join("outside");
        fs::create_dir_all(&project).unwrap();
        fs::create_dir_all(&outside).unwrap();
        let outside_file = outside.join("note.txt");
        fs::write(&outside_file, "outside content").unwrap();

        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("External path permission".into()),
            Some("plan".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        sessions::configure_session_with_thinking(
            &app_state.db,
            &session.id,
            "plan",
            None,
            None,
            None,
            Some("ask"),
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (notify_tx, mut notify_rx) = mpsc::unbounded_channel();
        let request_state = state.clone();
        let session_id = session.id.clone();
        let path = outside_file.to_string_lossy().into_owned();
        let path_for_request = path.clone();
        let pending = tokio::spawn(async move {
            handle_request(
                request_state,
                "tools.execute",
                json!({
                    "sessionId": session_id,
                    "toolCallId": "outside-plan-read",
                    "toolName": "Read",
                    "args": { "path": path_for_request },
                    "mode": "agent"
                }),
                notify_tx,
            )
            .await
        });

        let notification = notify_rx.recv().await.unwrap();
        let notification: Value = serde_json::from_str(&notification).unwrap();
        assert_eq!(notification["method"], "permissions.request");
        assert_eq!(
            notification["params"]["reason"],
            "Accesses a path outside the session workspace"
        );
        assert_eq!(notification["params"]["argsPreview"]["path"], path);
        let request_id = notification["params"]["requestId"].as_str().unwrap();
        handle_request(
            state.clone(),
            "permissions.resolve",
            json!({ "requestId": request_id, "decision": "deny" }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        let denied = pending.await.unwrap().unwrap();
        assert_eq!(denied["ok"], false);
        assert_eq!(denied["errorCode"], "TOOL_DENIED");

        let request_state = state.clone();
        let session_id = session.id.clone();
        let path_for_request = path.clone();
        let (notify_tx2, mut notify_rx2) = mpsc::unbounded_channel();
        let allowed_pending = tokio::spawn(async move {
            handle_request(
                request_state,
                "tools.execute",
                json!({
                    "sessionId": session_id,
                    "toolCallId": "outside-plan-read-allowed",
                    "toolName": "Read",
                    "args": { "path": path_for_request },
                    "mode": "agent"
                }),
                notify_tx2,
            )
            .await
        });
        let notification = notify_rx2.recv().await.unwrap();
        let notification: Value = serde_json::from_str(&notification).unwrap();
        let request_id = notification["params"]["requestId"].as_str().unwrap();
        handle_request(
            state.clone(),
            "permissions.resolve",
            json!({ "requestId": request_id, "decision": "allow-once" }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        let allowed = allowed_pending.await.unwrap().unwrap();
        assert_eq!(allowed["ok"], true);
        assert_eq!(allowed["content"]["root"], "external");
        let allowed_content = allowed["content"]["content"].as_str().unwrap();
        assert!(
            allowed_content.contains("outside content"),
            "{allowed_content}"
        );
        assert_eq!(allowed["content"]["tag"].as_str().unwrap().len(), 4);

        sessions::configure_session_with_thinking(
            &state.lock().await.db,
            &session.id,
            "plan",
            None,
            None,
            None,
            Some("auto"),
        )
        .unwrap();
        let auto = handle_request(
            state.clone(),
            "tools.execute",
            json!({
                "sessionId": session.id,
                "toolCallId": "outside-plan-auto-read",
                "toolName": "Read",
                "args": { "path": outside_file.to_string_lossy() },
                "mode": "agent"
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(auto["ok"], true);
        assert_eq!(auto["content"]["root"], "external");

        let scoped = handle_request(
            state.clone(),
            "tools.execute",
            json!({
                "sessionId": session.id,
                "toolCallId": "outside-composer-read",
                "toolName": "Read",
                "args": { "path": outside_file.to_string_lossy(), "offset": 0, "limit": 1 },
                "workspaceOnly": true,
                "mode": "agent"
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap_err();
        assert_eq!(
            scoped.message,
            "File line references require a local project path"
        );

        let project_file = project.join("note.txt");
        fs::write(&project_file, "before\nselected line\nafter\n").unwrap();
        let scoped = handle_request(
            state,
            "tools.execute",
            json!({
                "sessionId": session.id,
                "toolCallId": "inside-composer-read",
                "toolName": "Read",
                "args": { "path": project_file.to_string_lossy(), "offset": 1, "limit": 1 },
                "workspaceOnly": true,
                "mode": "agent"
            }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(scoped["ok"], true);
        let content = scoped["content"]["content"].as_str().unwrap();
        assert!(content.contains("selected line"), "{content}");
        assert!(
            !content.contains("before") && !content.contains("after"),
            "{content}"
        );
    }

    #[tokio::test]
    async fn delegate_permission_scope_overrides_session_mode_without_opening_external_paths() {
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        let outside = data_dir.path().join("outside");
        fs::create_dir_all(&project).unwrap();
        fs::create_dir_all(&outside).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Delegate scope".into()),
            Some("agent".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        // Session mode is `ask`: without a scope, Write prompts (ADR 0089).
        sessions::configure_session_with_thinking(
            &app_state.db,
            &session.id,
            "agent",
            None,
            None,
            None,
            Some("ask"),
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let session_id = session.id.clone();
        let outside_path = outside.join("note.txt").to_string_lossy().into_owned();

        // 1. In-workspace Write under `permissionScope: accept-edits` resolves
        //    without a permission request, despite the session being in `ask`.
        let (notify_tx, mut notify_rx) = mpsc::unbounded_channel();
        let allowed = handle_request(
            state.clone(),
            "tools.execute",
            json!({
                "sessionId": session_id.clone(),
                "toolCallId": "delegate-write-scoped",
                "toolName": "Write",
                "args": { "path": "file.txt", "content": "delegated" },
                "mode": "agent",
                "permissionScope": "accept-edits"
            }),
            notify_tx,
        )
        .await
        .unwrap();
        assert_eq!(allowed["ok"], true);
        assert_eq!(allowed["content"]["root"], "workspace");
        // No permission request may arrive: the scope auto-allowed the write.
        // The channel is dropped with the request, so Ok(None) counts as clean.
        let stray =
            tokio::time::timeout(std::time::Duration::from_millis(100), notify_rx.recv()).await;
        match stray {
            Err(_) | Ok(None) => {}
            Ok(Some(text)) => {
                panic!("scoped in-workspace Write raised an unexpected notification: {text}")
            }
        }

        // 2. The same call without a scope prompts under the session's `ask`.
        let (notify_tx, mut notify_rx) = mpsc::unbounded_channel();
        let pending_state = state.clone();
        let pending_session_id = session_id.clone();
        let pending = tokio::spawn(async move {
            handle_request(
                pending_state,
                "tools.execute",
                json!({
                    "sessionId": pending_session_id,
                    "toolCallId": "delegate-write-unscoped",
                    "toolName": "Write",
                    "args": { "path": "file2.txt", "content": "delegated" },
                    "mode": "agent"
                }),
                notify_tx,
            )
            .await
        });
        let notification = notify_rx.recv().await.unwrap();
        let notification: Value = serde_json::from_str(&notification).unwrap();
        assert_eq!(notification["method"], "permissions.request");
        assert_eq!(
            notification["params"]["reason"],
            "Modifies files in your workspace"
        );
        let request_id = notification["params"]["requestId"].as_str().unwrap();
        handle_request(
            state.clone(),
            "permissions.resolve",
            json!({ "requestId": request_id, "decision": "allow-once" }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        assert_eq!(pending.await.unwrap().unwrap()["ok"], true);

        // 3. An external-path Write keeps prompting even under the scope: the
        //    scope only relaxes the session mode, never the path gate.
        let (notify_tx, mut notify_rx) = mpsc::unbounded_channel();
        let pending_state = state.clone();
        let pending_session_id = session_id.clone();
        let pending_outside_path = outside_path.clone();
        let pending = tokio::spawn(async move {
            handle_request(
                pending_state,
                "tools.execute",
                json!({
                    "sessionId": pending_session_id,
                    "toolCallId": "delegate-write-external",
                    "toolName": "Write",
                    "args": { "path": pending_outside_path, "content": "delegated" },
                    "mode": "agent",
                    "permissionScope": "accept-edits"
                }),
                notify_tx,
            )
            .await
        });
        let notification = notify_rx.recv().await.unwrap();
        let notification: Value = serde_json::from_str(&notification).unwrap();
        assert_eq!(notification["method"], "permissions.request");
        assert_eq!(
            notification["params"]["reason"],
            "Accesses a path outside the session workspace"
        );
        let request_id = notification["params"]["requestId"].as_str().unwrap();
        handle_request(
            state.clone(),
            "permissions.resolve",
            json!({ "requestId": request_id, "decision": "allow-once" }),
            mpsc::unbounded_channel().0,
        )
        .await
        .unwrap();
        let allowed = pending.await.unwrap().unwrap();
        assert_eq!(allowed["ok"], true);
        assert_eq!(allowed["content"]["root"], "external");
    }

    #[tokio::test]
    async fn builtin_delegate_without_permission_scope_inherits_auto_for_external_glob() {
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        let outside = data_dir.path().join("outside");
        fs::create_dir_all(&project).unwrap();
        fs::create_dir_all(&outside).unwrap();
        let outside_file = outside.join("delegate-note.txt");
        fs::write(&outside_file, "outside content").unwrap();

        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Auto delegate external glob".into()),
            Some("agent".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        let session_id = session.id.clone();
        sessions::configure_session_with_thinking(
            &app_state.db,
            &session_id,
            "agent",
            None,
            None,
            None,
            Some("auto"),
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (notify_tx, mut notify_rx) = mpsc::unbounded_channel();
        let outside_path = outside.to_string_lossy().into_owned();

        // A builtin fixer inherits the parent mode, so the same external Glob
        // that triggered the reported card is allowed in auto without a scope.
        let result = handle_request(
            state,
            "tools.execute",
            json!({
                "sessionId": session_id,
                "toolCallId": "delegate-external-glob-auto",
                "toolName": "Glob",
                "args": { "path": outside_path, "pattern": "**/*", "limit": 10 },
                "mode": "agent"
            }),
            notify_tx,
        )
        .await
        .unwrap();
        assert_eq!(result["ok"], true, "external auto Glob failed: {result}");
        // External Glob results are absolute rather than carrying a root field.
        let canonical_outside_file = crate::workspace::simple_canonicalize(&outside_file).unwrap();
        assert_eq!(
            result["content"]["matches"][0],
            json!(canonical_outside_file.to_string_lossy()),
        );

        let stray =
            tokio::time::timeout(std::time::Duration::from_millis(100), notify_rx.recv()).await;
        match stray {
            Err(_) | Ok(None) => {}
            Ok(Some(text)) => {
                panic!("auto external Glob raised an unexpected notification: {text}")
            }
        }
    }

    #[tokio::test]
    async fn plan_authorization_uses_durable_mode_and_keeps_bash_permission_semantics() {
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        fs::create_dir_all(&project).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Plan".into()),
            Some("plan".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        let session_id = session.id.clone();
        sessions::configure_session_with_thinking(
            &app_state.db,
            &session_id,
            "plan",
            None,
            None,
            None,
            Some("auto"),
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();
        let command_shell_id = crate::tools::shell::default_shell_id();
        #[cfg(windows)]
        let plan_bash_command = "[Console]::Out.Write('plan-bash')";
        #[cfg(not(windows))]
        let plan_bash_command = "printf plan-bash";

        for (tool_name, args, expected) in [
            (
                "Write",
                json!({ "path": "ignored.txt", "content": "no" }),
                "WRITE_DISABLED_IN_PLAN",
            ),
            (
                "Edit",
                json!({ "path": "ignored.txt", "tag": "ABCD", "ops": "PUT 1.=1:\n+b\n" }),
                "EDIT_DISABLED_IN_PLAN",
            ),
            ("plugin_demo_run", json!({}), "PLUGIN_DISABLED_IN_PLAN"),
            ("UnknownTool", json!({}), "TOOL_DISABLED_IN_PLAN"),
        ] {
            let result = handle_request(
                state.clone(),
                "tools.execute",
                json!({
                    "sessionId": session_id,
                    "toolCallId": format!("{tool_name}-call"),
                    "toolName": tool_name,
                    "args": args,
                    "mode": "agent"
                }),
                tx.clone(),
            )
            .await
            .unwrap();
            assert_eq!(result["errorCode"], expected, "{tool_name}");
            assert_eq!(result["ok"], false);
        }

        let bash = handle_request(
            state.clone(),
            "tools.execute",
            json!({
                "sessionId": session_id,
                "toolCallId": "bash-auto",
                "toolName": "Bash",
                "args": { "command": plan_bash_command },
                "expectedCommandShellId": command_shell_id,
                "expectedCommandShellDialect": crate::tools::shell::dialect_for_id(command_shell_id),
                "mode": "agent"
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(bash["ok"], true);
        assert_eq!(bash["content"]["stdout"], "plan-bash");

        sessions::configure_session_with_thinking(
            &state.lock().await.db,
            &session_id,
            "plan",
            None,
            None,
            None,
            Some("ask"),
        )
        .unwrap();
        #[cfg(windows)]
        let ask_bash_command = "[Console]::Out.Write('ask-bash')";
        #[cfg(not(windows))]
        let ask_bash_command = "printf ask-bash";
        let (notify_tx, mut notify_rx) = mpsc::unbounded_channel();
        let pending_state = state.clone();
        let pending_task = tokio::spawn(async move {
            handle_request(
                pending_state,
                "tools.execute",
                json!({
                    "sessionId": session_id,
                    "toolCallId": "bash-ask",
                    "toolName": "Bash",
                    "args": { "command": ask_bash_command },
                    "expectedCommandShellId": command_shell_id,
                    "expectedCommandShellDialect": crate::tools::shell::dialect_for_id(command_shell_id),
                    "mode": "agent"
                }),
                notify_tx,
            )
            .await
        });
        let notification = notify_rx.recv().await.unwrap();
        let notification: Value = serde_json::from_str(&notification).unwrap();
        assert_eq!(notification["method"], "permissions.request");
        let request_id = notification["params"]["requestId"].as_str().unwrap();
        handle_request(
            state,
            "permissions.resolve",
            json!({ "requestId": request_id, "decision": "allow-once" }),
            tx,
        )
        .await
        .unwrap();
        let pending_result = pending_task.await.unwrap().unwrap();
        assert_eq!(pending_result["ok"], true);
    }

    #[tokio::test]
    async fn goal_authorization_reuses_the_durable_contract_mode_hard_deny() {
        let data_dir = tempfile::tempdir().unwrap();
        let project = data_dir.path().join("project");
        fs::create_dir_all(&project).unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("Goal".into()),
            Some("goal".into()),
            None,
            None,
            Some(project.to_string_lossy().into_owned()),
        )
        .unwrap();
        let session_id = session.id.clone();
        // `auto` is the strongest permission mode; the deny must still win.
        sessions::configure_session_with_thinking(
            &app_state.db,
            &session_id,
            "goal",
            None,
            None,
            None,
            Some("auto"),
        )
        .unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();

        for (tool_name, args, expected) in [
            (
                "Write",
                json!({ "path": "ignored.txt", "content": "no" }),
                "WRITE_DISABLED_IN_PLAN",
            ),
            (
                "Edit",
                json!({ "path": "ignored.txt", "tag": "ABCD", "ops": "PUT 1.=1:\n+b\n" }),
                "EDIT_DISABLED_IN_PLAN",
            ),
            ("plugin_demo_run", json!({}), "PLUGIN_DISABLED_IN_PLAN"),
            ("UnknownTool", json!({}), "TOOL_DISABLED_IN_PLAN"),
        ] {
            let result = handle_request(
                state.clone(),
                "tools.execute",
                json!({
                    "sessionId": session_id,
                    "toolCallId": format!("goal-{tool_name}-call"),
                    "toolName": tool_name,
                    "args": args,
                    // A sidecar claiming Agent cannot widen the durable mode.
                    "mode": "agent"
                }),
                tx.clone(),
            )
            .await
            .unwrap();
            assert_eq!(result["errorCode"], expected, "{tool_name}");
            assert_eq!(result["ok"], false);
        }

        // Bash still follows the permission mode rather than the allowlist.
        #[cfg(windows)]
        let goal_bash_command = "[Console]::Out.Write('goal-bash')";
        #[cfg(not(windows))]
        let goal_bash_command = "printf goal-bash";
        let command_shell_id = crate::tools::shell::default_shell_id();
        let bash = handle_request(
            state.clone(),
            "tools.execute",
            json!({
                "sessionId": session_id,
                "toolCallId": "goal-bash-auto",
                "toolName": "Bash",
                "args": { "command": goal_bash_command },
                "expectedCommandShellId": command_shell_id,
                "expectedCommandShellDialect": crate::tools::shell::dialect_for_id(command_shell_id),
                "mode": "agent"
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(bash["ok"], true);
        assert_eq!(bash["content"]["stdout"], "goal-bash");
    }

    #[tokio::test]
    async fn provider_model_cache_roundtrips_through_rpc() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();

        let created = handle_request(
            state.clone(),
            "providers.create",
            json!({
                "name": "Local catalog",
                "baseUrl": "http://localhost:11434/v1",
                "authKind": "none",
                "defaultModelId": "model-a"
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        let provider_id = created["provider"]["id"].as_str().unwrap();
        let endpoint = json!({ "baseUrl": "http://localhost:11434/v1", "apiStyle": "" });

        let cached = handle_request(
            state.clone(),
            "providers.cacheModels",
            json!({
                "providerId": provider_id,
                "endpoint": endpoint,
                "models": [
                    {
                        "modelId": "model-a",
                        "displayName": "Model A",
                        "capabilities": ["text"],
                        "contextWindow": 500000,
                        "reportedContextWindow": 500000
                    },
                    {
                        "modelId": "model-b",
                        "displayName": "Model B",
                        "capabilities": ["text", "reasoning"],
                        "contextWindow": 128000
                    }
                ]
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(cached["cached"], 2);

        let listed = handle_request(
            state.clone(),
            "providers.listModels",
            json!({ "providerId": provider_id, "endpoint": endpoint }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(listed["models"].as_array().unwrap().len(), 2);
        assert_eq!(listed["models"][1]["modelId"], "model-b");
        assert_eq!(listed["models"][1]["capabilities"][1], "reasoning");
        assert_eq!(listed["models"][0]["reportedContextWindow"], 500000);
        assert_eq!(listed["models"][1]["contextWindow"], 128000);
        assert!(listed["models"][1].get("reportedContextWindow").is_none());

        handle_request(
            state.clone(),
            "providers.update",
            json!({ "id": provider_id, "baseUrl": "http://localhost:11435/v1" }),
            tx.clone(),
        )
        .await
        .unwrap();
        let rejected = handle_request(
            state.clone(),
            "providers.cacheModels",
            json!({ "providerId": provider_id, "endpoint": endpoint, "models": [
                { "modelId": "stale", "displayName": "Stale", "reportedContextWindow": 500000 }
            ] }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(rejected["cached"], 0);
        let stale_read = handle_request(
            state,
            "providers.listModels",
            json!({ "providerId": provider_id, "endpoint": endpoint }),
            tx,
        )
        .await
        .unwrap();
        assert_eq!(stale_read["models"], json!([]));
    }

    #[tokio::test]
    async fn inflight_checkpoint_rpc_lifecycle() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session =
            sessions::create_session(&app_state.db, None, None, None, None, None).unwrap();
        let turn = sessions::begin_turn(&app_state.db, &session.id, None, None).unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();

        let saved = handle_request(
            state.clone(),
            "session.saveInflightMessage",
            json!({
                "sessionId": session.id,
                "turnId": turn,
                "message": {
                    "id": "a1",
                    "role": "assistant",
                    "content": "partial reply",
                    "createdAt": "2026-09-04T00:00:00.000Z",
                    "status": "streaming"
                }
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(saved, json!({ "ok": true, "saved": true }));

        // The sidecar is gone: the turn end promotes the checkpoint.
        let ended = handle_request(
            state.clone(),
            "session.endTurn",
            json!({
                "turnId": turn,
                "status": "aborted",
                "errorCode": "TURN_ABORTED",
                "createNotification": false,
                "recoverInflight": true
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(ended["ok"], json!(true));
        assert_eq!(ended["recovered"]["id"], json!("a1"));
        assert_eq!(ended["recovered"]["status"], json!("aborted"));
        assert_eq!(ended["recovered"]["content"], json!("partial reply"));

        let detail = handle_request(
            state.clone(),
            "session.get",
            json!({ "id": session.id }),
            tx.clone(),
        )
        .await
        .unwrap();
        let messages = detail["session"]["messages"].as_array().unwrap();
        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0]["status"], json!("aborted"));
    }

    #[tokio::test]
    async fn notification_rpc_lifecycle() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let session = sessions::create_session(
            &app_state.db,
            Some("RPC task".into()),
            None,
            None,
            None,
            None,
        )
        .unwrap();
        let turn = sessions::begin_turn(&app_state.db, &session.id, None, None).unwrap();
        sessions::end_turn(&app_state.db, &turn, "completed", None, None, true).unwrap();
        let visible_turn = sessions::begin_turn(&app_state.db, &session.id, None, None).unwrap();
        let state = Arc::new(Mutex::new(app_state));
        let (tx, _rx) = mpsc::unbounded_channel();

        let ended_visible = handle_request(
            state.clone(),
            "session.endTurn",
            json!({
                "turnId": visible_turn,
                "status": "completed",
                "createNotification": false
            }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(ended_visible, json!({ "ok": true }));

        let listed = handle_request(
            state.clone(),
            "notification.list",
            json!({ "unreadOnly": true, "limit": 10 }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(listed["unreadCount"], 1);
        assert_eq!(listed["notifications"][0]["kind"], "task.completed");
        assert_eq!(listed["notifications"][0]["sessionTitle"], "RPC task");
        let id = listed["notifications"][0]["id"]
            .as_str()
            .unwrap()
            .to_string();

        let marked = handle_request(
            state.clone(),
            "notification.markRead",
            json!({ "id": id }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(marked, json!({ "ok": true }));
        let marked_all = handle_request(
            state.clone(),
            "notification.markAllRead",
            json!({}),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(marked_all, json!({ "ok": true }));
        let cleared = handle_request(state.clone(), "notification.clear", json!({}), tx)
            .await
            .unwrap();
        assert_eq!(cleared, json!({ "ok": true }));

        let remaining: i64 = state
            .lock()
            .await
            .db
            .conn()
            .query_row("SELECT COUNT(*) FROM notifications", [], |row| row.get(0))
            .unwrap();
        assert_eq!(remaining, 0);
    }

    #[tokio::test]
    async fn plugin_labels_follow_the_pushed_app_language() {
        let data_dir = tempfile::tempdir().unwrap();
        let mut app_state = AppState::open(data_dir.path()).unwrap();
        app_state.handshook = true;
        let state = Arc::new(Mutex::new(app_state));
        let tx = mpsc::unbounded_channel().0;

        // A concrete app language in settings pins the locale even before the
        // shell pushes one.
        handle_request(
            state.clone(),
            "settings.set",
            json!({ "language": "zh-CN" }),
            tx.clone(),
        )
        .await
        .unwrap();
        {
            let st = state.lock().await;
            assert_eq!(st.plugins.locale(), "zh-CN");
        }

        // `auto` is a setting, not a locale: the shell resolves it, and the
        // host must not start reading `zh-CN` off the raw value.
        handle_request(
            state.clone(),
            "settings.set",
            json!({ "language": "auto" }),
            tx.clone(),
        )
        .await
        .unwrap();
        {
            let st = state.lock().await;
            assert_eq!(st.plugins.locale(), "zh-CN");
        }

        let pushed = handle_request(
            state.clone(),
            "plugins.setLocale",
            json!({ "locale": "en-US" }),
            tx.clone(),
        )
        .await
        .unwrap();
        assert_eq!(pushed["locale"], "en-US");
        {
            let st = state.lock().await;
            assert_eq!(st.plugins.locale(), "en-US");
        }

        // Neither an empty value nor `auto` overwrites the resolved locale.
        for value in [
            json!({ "locale": "" }),
            json!({ "locale": "auto" }),
            json!({}),
        ] {
            handle_request(state.clone(), "plugins.setLocale", value, tx.clone())
                .await
                .unwrap();
        }
        let st = state.lock().await;
        assert_eq!(st.plugins.locale(), "en-US");
    }
}

#[cfg(test)]
mod image_generation_settings_tests {
    use super::*;
    #[test]
    fn validates_optional_image_binding() {
        for value in [
            json!({}),
            json!({"imageGeneration": null}),
            json!({"imageGeneration": {"providerId": "p", "modelId": "image"}}),
            json!({"imageGenerationModels": null}),
            json!({"imageGenerationModels": []}),
            json!({"imageGenerationModels": [
                {"providerId": "p", "modelId": "image-one"},
                {"providerId": "q", "modelId": "image-two"}
            ]}),
        ] {
            assert!(validate_settings_value(&value).is_ok());
        }
        for value in [
            json!(false),
            json!({}),
            json!({"providerId": "p", "modelId": " "}),
        ] {
            assert!(validate_settings_value(&json!({"imageGeneration": value})).is_err());
        }
        for value in [
            json!(false),
            json!({}),
            json!([{"providerId": "p", "modelId": " "}]),
        ] {
            assert!(validate_settings_value(&json!({"imageGenerationModels": value})).is_err());
        }
    }
}

#[cfg(test)]
mod update_settings_tests {
    use super::*;

    #[test]
    fn validates_update_preference_and_reminder_version() {
        for value in [
            json!({}),
            json!({"updatePreference": "automatic"}),
            json!({"updatePreference": "manual"}),
            json!({"lastNotifiedUpdateVersion": "0.15.9"}),
            json!({"updateDismissedVersion": "0.15.9"}),
            json!({"updateDismissedVersion": null}),
        ] {
            assert!(validate_settings_value(&value).is_ok(), "{value}");
        }
        for value in [
            json!({"updatePreference": "sometimes"}),
            json!({"updatePreference": null}),
            json!({"lastNotifiedUpdateVersion": "  "}),
            json!({"lastNotifiedUpdateVersion": 12}),
            json!({"lastNotifiedUpdateVersion": "x".repeat(129)}),
            json!({"updateDismissedVersion": "  "}),
            json!({"updateDismissedVersion": 12}),
            json!({"updateDismissedVersion": "x".repeat(129)}),
        ] {
            assert!(validate_settings_value(&value).is_err(), "{value}");
        }
    }
}