A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
pin the thinking channel behavior and capture request payloads (#3168)
kt883b5a1f603f
diff --git a/crates/pa-agent/src/agent.rs b/crates/pa-agent/src/agent.rsindex 69c317c3c8..1d14cfe799 100644--- a/crates/pa-agent/src/agent.rs+++ b/crates/pa-agent/src/agent.rs@@ -894,6 +894,16 @@ impl Agent {self.inner.shared.lock().await.state.thinking_level = level;}+ /// Set the model and the requested reasoning level in ONE state-lock+ /// acquisition: a model switch re-syncs the request's carried level+ /// (the loop snapshots both fields together), so a turn admitted+ /// mid-switch can never observe the new model with the old level.+ pub async fn set_model_and_thinking_level(&self, model: Model, thinking_level: ThinkingLevel) {+ let mut shared = self.inner.shared.lock().await;+ shared.state.model = model;+ shared.state.thinking_level = thinking_level;+ }+/// Per-run model override (TS `Agent.modelOverride`): `Some` serves/// every LLM request of the runs started while it is set on the/// override model (with its own thinking level), `None` returns to the@@ -1565,4 +1575,76 @@ mod tests {assert_eq!(failure.model, "image-model");assert_eq!(failure.stop_reason, crate::types::StopReason::Error);}++ // A model switch re-syncs the request's carried level in ONE+ // agent-lock acquisition: the loop snapshots model and thinking+ // level together (the same lock), so a concurrently admitted turn+ // must never observe the new model with the old level — the mixed+ // state only exists between two separate acquisitions.+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]+ async fn a_model_switch_updates_the_model_and_level_atomically() {+ fn model(id: &str) -> Model {+ Model {+ id: id.to_string(),+ name: id.to_string(),+ api: "anthropic-messages".to_string(),+ provider: "anthropic".to_string(),+ base_url: String::new(),+ reasoning: true,+ cost: crate::types::UsageCost::default(),+ context_window: 200_000,+ max_tokens: 8_192,+ }+ }++ // The initial pair matches the writer's first target pair, so a+ // reader that samples before the writer's first update observes+ // a consistent state, not the boot default.+ let agent = Arc::new(Agent::new(AgentOptions {+ initial_state: AgentInitialState {+ model: Some(model("model-a")),+ thinking_level: Some(crate::types::ThinkingLevel::High),+ ..Default::default()+ },+ ..Default::default()+ }));+ let writer = Arc::clone(&agent);+ let switcher = tokio::spawn(async move {+ for _ in 0..2_000 {+ writer+ .set_model_and_thinking_level(+ model("model-a"),+ crate::types::ThinkingLevel::High,+ )+ .await;+ writer+ .set_model_and_thinking_level(+ model("model-b"),+ crate::types::ThinkingLevel::Off,+ )+ .await;+ }+ });+ let reader = Arc::clone(&agent);+ let observed = tokio::spawn(async move {+ let mut mixed = 0u64;+ let mut samples = 0u64;+ while samples < 20_000 {+ let state = reader.state().await;+ let mixed_state = (state.model.id == "model-a"+ && state.thinking_level != crate::types::ThinkingLevel::High)+ || (state.model.id == "model-b"+ && state.thinking_level != crate::types::ThinkingLevel::Off);+ mixed += u64::from(mixed_state);+ samples += 1;+ }+ mixed+ });+ switcher.await.unwrap();+ let mixed = observed.await.unwrap();+ assert_eq!(+ mixed, 0,+ "every snapshot carries a consistent (model, level) pair"+ );+ }}diff --git a/crates/pa-ai/src/providers/openai_completions/stream.rs b/crates/pa-ai/src/providers/openai_completions/stream.rsindex 90243173ba..45a6f68083 100644--- a/crates/pa-ai/src/providers/openai_completions/stream.rs+++ b/crates/pa-ai/src/providers/openai_completions/stream.rs@@ -715,6 +715,11 @@ mod tests {use std::net::SocketAddr;use tokio::io::{AsyncReadExt, AsyncWriteExt};+ // The thinking-channel pins (the two provider envelopes) live in+ // their own child module with this file's test harness.+ #[path = "stream_pins.rs"]+ mod stream_pins;+/// Serve one SSE response body for the provider's POST and return the/// bound address.async fn serve_sse(body: String) -> SocketAddr {diff --git a/crates/pa-ai/src/providers/openai_completions/stream/tests/stream_pins.rs b/crates/pa-ai/src/providers/openai_completions/stream/tests/stream_pins.rsnew file mode 100644index 0000000000..e63cfdff87--- /dev/null+++ b/crates/pa-ai/src/providers/openai_completions/stream/tests/stream_pins.rs@@ -0,0 +1,215 @@+//! The thinking-channel pins: a GLM-5.3-style response arrives either with+//! its reasoning in `delta.reasoning_content` (the healthy envelope —+//! the thinking block's signature is the field name) or with its+//! reasoning merged into `delta.content` (the content-only envelope —+//! no thinking block at all, the reasoning rides the text block). The+//! stream maps whichever envelope the provider sends; these two pins+//! document that BOTH assemblies are faithful, so stored rows whose+//! reasoning rides the text block are the provider's envelope, not a+//! local reclassification of a thinking stream.++use super::*;++/// The diagnosed session's model entry (the internal GLM-5.3 fast+/// route: reasoning mandatory, catalog `reasoning: true`).+fn glm_fast_model() -> Value {+ json!({+ "id": "internal/glm-5.3-fast",+ "name": "GLM 5.3 Fast",+ "api": "openai-completions",+ "provider": "prime-inference",+ "reasoning": true,+ "input": ["text"],+ "cost": { "input": 0.0, "output": 0.0, "cacheRead": 0.0, "cacheWrite": 0.0 },+ "contextWindow": 262_144,+ "maxTokens": 65_536,+ })+}++/// Stream one SSE body end-to-end, collecting every event plus the+/// final assistant message.+async fn stream_events(+ model: Value,+ body: String,+) -> (Vec<AssistantMessageEvent>, AssistantMessage) {+ let addr = serve_sse(body).await;+ let mut model = model;+ model["baseUrl"] = json!(format!("http://{addr}"));+ let model: Model = serde_json::from_value(model).unwrap();+ let options = OpenAICompletionsOptions::from_base(crate::types::StreamOptions {+ api_key: Some("test".into()),+ ..Default::default()+ });+ let mut reader = stream_openai_completions(+ &model,+ &Context {+ system_prompt: None,+ messages: vec![],+ tools: None,+ },+ Some(&options),+ );+ let mut events = Vec::new();+ loop {+ let event = reader.next_event().await.unwrap();+ let terminal = match &event {+ AssistantMessageEvent::Done { message, .. } => Some(message.clone()),+ AssistantMessageEvent::Error { error, .. } => {+ panic!("stream failed: {:?}", error.error_message)+ }+ _ => None,+ };+ events.push(event);+ if let Some(message) = terminal {+ return (events, message);+ }+ }+}++fn sse_body(chunks: &[Value]) -> String {+ use std::fmt::Write as _;+ let mut body = String::new();+ for chunk in chunks {+ let _ = write!(body, "data: {chunk}\n\n");+ }+ let _ = write!(body, "data: [DONE]\n\n");+ body+}++/// THE CONTENT-ONLY ENVELOPE: the reasoning arrives ONLY inside `content`+/// deltas — no `reasoning_content` delta — so the assembled message+/// carries no thinking block and the text block holds the reasoning+/// merged with the response. No thinking events fire: the stored rows+/// this assembly produces are the store being faithful to the envelope,+/// not a misclassification.+#[tokio::test]+async fn reasoning_in_content_deltas_assembles_no_thinking_block() {+ let reasoning_prose = "The domain-flip PR (#3142) is green. The plan:\n1. Create the worktree.\n2. Start the rebase.\nActually — the smarter route: let me execute.";+ let response_tail = "Now the fold takeover, executing directly:";+ let body = sse_body(&[+ json!({+ "id": "a42da6520be8102f-HEL", "object": "chat.completion.chunk",+ "model": "internal/glm-5.3-fast",+ "choices": [{ "index": 0, "delta": { "role": "assistant", "content": reasoning_prose } }]+ }),+ json!({+ "id": "a42da6520be8102f-HEL", "object": "chat.completion.chunk",+ "model": "internal/glm-5.3-fast",+ "choices": [{ "index": 0, "delta": { "content": response_tail } }]+ }),+ json!({+ "id": "a42da6520be8102f-HEL", "object": "chat.completion.chunk",+ "model": "internal/glm-5.3-fast",+ "choices": [{ "index": 0, "delta": {}, "finish_reason": "stop" }],+ "usage": { "prompt_tokens": 244_064, "completion_tokens": 800, "total_tokens": 244_864 }+ }),+ ]);+ let (events, message) = stream_events(glm_fast_model(), body).await;+ // No thinking block: the reasoning channel never arrived.+ let [AssistantContent::Text(text)] = &message.content[..] else {+ panic!(+ "the content-only envelope assembles one text block: {:?}",+ message.content+ );+ };+ assert_eq!(+ text.text,+ format!("{reasoning_prose}{response_tail}"),+ "the reasoning prose merges with the response tail into the single text block"+ );+ assert!(+ !message+ .content+ .iter()+ .any(|block| matches!(block, AssistantContent::Thinking(_))),+ "no thinking block exists: {:?}",+ message.content+ );+ // No thinking events: the reasoning channel never announced itself.+ assert!(+ events.iter().all(|event| !matches!(+ event,+ AssistantMessageEvent::ThinkingStart { .. }+ | AssistantMessageEvent::ThinkingDelta { .. }+ | AssistantMessageEvent::ThinkingEnd { .. }+ )),+ "no thinking events fire for a content-only envelope: {events:?}"+ );+ // The text channel streamed the merged prose as plain text.+ let text_deltas: Vec<&str> = events+ .iter()+ .filter_map(|event| match event {+ AssistantMessageEvent::TextDelta { delta, .. } => Some(delta.as_str()),+ _ => None,+ })+ .collect();+ assert_eq!(text_deltas, [reasoning_prose, response_tail]);+ assert_eq!(message.stop_reason, StopReason::Stop);+ assert_eq!(message.usage.input, 244_064);+}++/// THE HEALTHY ENVELOPE: the reasoning arrives in `delta.reasoning_content`,+/// the answer in `delta.content`, and the assembled message carries the+/// thinking block whose signature is the field name (the wire shape the+/// session rows' `thinkingSignature: "reasoning_content"` records),+/// followed by the text block. Thinking events fire.+#[tokio::test]+async fn reasoning_content_deltas_assemble_the_thinking_block_with_the_field_signature() {+ let thinking_a = "The operator asks: why do we need the nightly cron again?";+ let thinking_b = " It is the rehearsal for the release machinery itself.";+ let answer = "**The nightly cron exists for three reasons.**";+ let body = sse_body(&[+ json!({+ "id": "a42da4e81901102f-HEL", "object": "chat.completion.chunk",+ "model": "internal/glm-5.3-fast",+ "choices": [{ "index": 0, "delta": { "role": "assistant", "reasoning_content": thinking_a } }]+ }),+ json!({+ "id": "a42da4e81901102f-HEL", "object": "chat.completion.chunk",+ "model": "internal/glm-5.3-fast",+ "choices": [{ "index": 0, "delta": { "reasoning_content": thinking_b } }]+ }),+ json!({+ "id": "a42da4e81901102f-HEL", "object": "chat.completion.chunk",+ "model": "internal/glm-5.3-fast",+ "choices": [{ "index": 0, "delta": { "content": answer } }]+ }),+ json!({+ "id": "a42da4e81901102f-HEL", "object": "chat.completion.chunk",+ "model": "internal/glm-5.3-fast",+ "choices": [{ "index": 0, "delta": {}, "finish_reason": "stop" }],+ "usage": { "prompt_tokens": 244_064, "completion_tokens": 800, "total_tokens": 244_864 }+ }),+ ]);+ let (events, message) = stream_events(glm_fast_model(), body).await;+ // The thinking block carries the field name as its signature.+ let [AssistantContent::Thinking(thinking), AssistantContent::Text(text)] = &message.content[..]+ else {+ panic!(+ "the healthy envelope assembles thinking then text: {:?}",+ message.content+ );+ };+ assert_eq!(thinking.thinking, format!("{thinking_a}{thinking_b}"));+ assert_eq!(+ thinking.thinking_signature.as_deref(),+ Some("reasoning_content")+ );+ assert_eq!(text.text, answer);+ // The thinking events announce the channel.+ let thinking_deltas: Vec<&str> = events+ .iter()+ .filter_map(|event| match event {+ AssistantMessageEvent::ThinkingDelta { delta, .. } => Some(delta.as_str()),+ _ => None,+ })+ .collect();+ assert_eq!(thinking_deltas, [thinking_a, thinking_b]);+ assert!(+ events+ .iter()+ .any(|event| matches!(event, AssistantMessageEvent::ThinkingStart { .. })),+ "the thinking channel announces its start: {events:?}"+ );+ assert_eq!(message.stop_reason, StopReason::Stop);+}diff --git a/crates/pa-core/src/session_engine/engine.rs b/crates/pa-core/src/session_engine/engine.rsindex d2c310ada8..cf760a1e12 100644--- a/crates/pa-core/src/session_engine/engine.rs+++ b/crates/pa-core/src/session_engine/engine.rs@@ -601,13 +601,21 @@ pub async fn create_session(mut config: SessionEngineConfig) -> anyhow::Result<S// JSONL log, and the prompt-build correlation state. The wrappers pass// straight through while the flag is off — no timestamps, no payload// serialization, no entries.- let request_timing_wiring =- std::sync::Arc::new(super::request_timing::RequestTimingWiring::new(+ let request_timing_wiring = std::sync::Arc::new(+ super::request_timing::RequestTimingWiring::new(std::sync::Arc::new(move || {super::request_timing::is_request_timing_enabled(request_timing_settings)}),super::request_timing::RequestTimingLog::new(&config.agent_dir),- ));+ )+ // The outbound body capture rides the same flag: while request+ // timing is on, every session — the daemon workers' included,+ // this is the one build path they all share — records each+ // request's final outbound body.+ .with_payload_capture(super::request_timing::RequestPayloadCapture::new(+ &config.agent_dir,+ )),+ );let agent = Agent::new(AgentOptions {initial_state: AgentInitialState {system_prompt: Some(system_prompt.clone()),diff --git a/crates/pa-core/src/session_engine/mod.rs b/crates/pa-core/src/session_engine/mod.rsindex da47f18ff0..d64c637684 100644--- a/crates/pa-core/src/session_engine/mod.rs+++ b/crates/pa-core/src/session_engine/mod.rs@@ -353,6 +353,36 @@ impl AgentSession {Ok(())}+ /// The atomic model-and-level switch: one agent-lock acquisition+ /// updates both fields (the loop snapshots them together), so a+ /// concurrently admitted turn never observes the new model with the+ /// old level mid-switch. The durable `model_change` row is the same+ /// bookkeeping as [`AgentSession::set_model`]; the thinking level's+ /// intent row belongs to the explicit `/thinking` path.+ ///+ /// # Errors+ ///+ /// Returns an error when the model cannot be converted to the loop+ /// wire shape, or when the model-change row cannot be persisted.+ pub async fn set_model_and_thinking_level(+ &self,+ model: &pa_types::ai::Model,+ provider: &str,+ model_id: &str,+ thinking_level: ThinkingLevel,+ ) -> anyhow::Result<()> {+ let wire: pa_agent::types::Model = serde_json::from_value(+ serde_json::to_value(model).map_err(|error| anyhow::anyhow!(error.to_string()))?,+ )+ .map_err(|error| anyhow::anyhow!(error.to_string()))?;+ self.agent+ .set_model_and_thinking_level(wire, thinking_level)+ .await;+ let mut session = self.session.lock().await;+ session.append_model_change(provider, model_id)?;+ Ok(())+ }+/// Thinking level bookkeeping (mirrors appendThinkingLevelChange).////// # Errorsdiff --git a/crates/pa-core/src/session_engine/request_timing.rs b/crates/pa-core/src/session_engine/request_timing.rsindex dc0b7f877d..03a21f3c8c 100644--- a/crates/pa-core/src/session_engine/request_timing.rs+++ b/crates/pa-core/src/session_engine/request_timing.rs@@ -72,7 +72,9 @@ mod tests;// pa_agent::types use row drops Usage (its only user moved - the child// binds its own).mod clock;+mod payload;use clock::{Outcome, RequestTiming};+pub(crate) use payload::RequestPayloadCapture;/// TS `REQUEST_TIMING_ENV`: the env override (inherited by daemon workers).const REQUEST_TIMING_ENV: &str = "PI_REQUEST_TIMING";@@ -237,6 +239,9 @@ struct PromptBuildTiming {pub struct RequestTimingWiring {enabled: RequestTimingEnabled,log: RequestTimingLog,+ /// The outbound body capture; `None` captures nothing (the timeline+ /// stays at phases and byte counts).+ payload_capture: Option<RequestPayloadCapture>,dispatch: Mutex<Option<Instant>>,prompt_build: Mutex<Option<PromptBuildTiming>>,request_seq: AtomicU64,@@ -249,12 +254,22 @@ impl RequestTimingWiring {Self {enabled,log,+ payload_capture: None,dispatch: Mutex::new(None),prompt_build: Mutex::new(None),request_seq: AtomicU64::new(0),}}+ /// Arm the outbound body capture: while the flag is on, the+ /// instrumented payload hook hands each request's final body to the+ /// capture's bounded writer.+ #[must_use]+ pub(crate) fn with_payload_capture(mut self, capture: RequestPayloadCapture) -> Self {+ self.payload_capture = Some(capture);+ self+ }+/// The JSONL log the entries go to.fn log(&self) -> &RequestTimingLog {&self.log@@ -466,6 +481,8 @@ pub fn instrument_stream_fn(wiring: Arc<RequestTimingWiring>, stream_fn: StreamF// not to request-sent -> first-byte.let inner_payload: Option<OnPayloadHook> = options.on_payload.take();let timing_for_payload = Arc::clone(&timing);+ let capture_for_payload = wiring.payload_capture.clone();+ let session_id = options.session_id.clone();options.on_payload = Some(Arc::new(move |payload, model| {let next = inner_payload.as_ref()@@ -473,6 +490,9 @@ pub fn instrument_stream_fn(wiring: Arc<RequestTimingWiring>, stream_fn: StreamF.unwrap_or(payload);timing_for_payload.record_request_bytes(measure_request_bytes(&next));timing_for_payload.mark_request_sent();+ if let Some(capture) = capture_for_payload.as_ref() {+ capture.record(&next, model, session_id.as_deref(), request_seq);+ }Some(next)}));// The response hook marks first-byte before delegating.diff --git a/crates/pa-core/src/session_engine/request_timing/payload.rs b/crates/pa-core/src/session_engine/request_timing/payload.rsnew file mode 100644index 0000000000..481234459a--- /dev/null+++ b/crates/pa-core/src/session_engine/request_timing/payload.rs@@ -0,0 +1,484 @@+//! The outbound request-body capture: while request timing is on, the+//! instrumented payload hook hands each request's final outbound body —+//! after every transform, exactly what the provider sees, the wire shape+//! that answers which request fields the provider actually received — to+//! one bounded background writer that persists it under+//! `<agentDir>/logs/request-payloads/` (one file per request, newest-`keep`+//! ring, owner-only modes, best-effort throughout: a read-only or missing+//! dir never breaks the request it observes).+//!+//! One writer serves the whole process: a single thread with a single+//! bounded queue, armed on the first recorded capture, so the footprint+//! is one thread, at most [`WRITE_QUEUE_CAPACITY`] queued jobs, and at+//! most [`REQUEST_PAYLOAD_BUDGET_BYTES`] retained payload bytes, no+//! matter how many sessions are live. [`RequestPayloadCapture::record`]+//! never touches the filesystem and reserves its queue slot before the+//! payload clone: a saturated queue drops the capture at O(1) instead+//! of paying a copy it would reject; a queue whose retained bytes are+//! over budget walks the payload once (without allocating) to price it,+//! then drops without cloning. The writer owns the serialization, the+//! file writes, and the prune.+//!+//! # The confidentiality boundary+//!+//! The captured bodies are complete request transcripts, so the capture+//! refuses rather than leak: on Unix the ring's directory and files are+//! owner-only through the platform wall (re-applied on every write, even+//! onto a pre-existing permissive directory), and every path component+//! from the agent dir down must be a real directory — a symlinked+//! component would redirect the private-mode writes, so the capture+//! disables itself instead of following it. On Windows the platform+//! wall's restriction helpers are inherited-ACL no-ops: rather than+//! write complete bodies through a possibly permissive inherited ACL,+//! the capture is disabled there (a documented limitation until the+//! platform wall gains a restrictive DACL).++use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};+use std::sync::mpsc::{Receiver, SyncSender};+use std::sync::{Arc, OnceLock};++use serde_json::{json, Map, Value};++use crate::platform::perms;+use crate::session::manager::format_iso;++/// The capture's own battery: the capture is Unix-only (the+/// confidentiality boundary is not enforceable elsewhere), so its tests+/// are too.+#[cfg(all(test, unix))]+pub(crate) mod tests;++/// Serializes the tests that record through the process's one writer:+/// the queue is a shared bound, so concurrent recording tests would+/// saturate each other's queues and drop each other's expected bodies.+/// A tokio mutex so the async integration tests hold it across awaits+/// (`lock().await`) while the sync unit tests take `blocking_lock()`.+#[cfg(all(test, unix))]+pub(crate) static WRITER_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());++/// The newest-body ring the capture keeps: one file per request, so+/// long-context payloads never grow without bound in an always-on+/// daemon's diagnostics dir.+pub(crate) const REQUEST_PAYLOAD_CAPTURE_KEEP: usize = 64;++/// The one write queue's capacity: a writer that falls behind drops the+/// overflow instead of growing the footprint.+const WRITE_QUEUE_CAPACITY: usize = REQUEST_PAYLOAD_CAPTURE_KEEP;++/// The retained-bytes bound of the queue: handed-off payloads (and the+/// one the writer holds) stay resident until serialized and written, so+/// a stalled writer must not accumulate unbounded memory — a+/// long-context or large-image request can carry tens of MiB, and the+/// queue drops anything that would push the retained bytes past this+/// budget instead of cloning it.+pub(crate) const REQUEST_PAYLOAD_BUDGET_BYTES: u64 = 64 * 1024 * 1024;++/// The process-global capture counter: every handed-off body gets its+/// own file name regardless of which session wiring recorded it (the+/// wire sequence numbers restart per wiring, and sessions share the+/// agent dir).+static CAPTURE_SEQ: AtomicU64 = AtomicU64::new(0);++/// One queued capture, as the dispatch path hands it off.+struct CaptureJob {+ root: PathBuf,+ dir: PathBuf,+ keep: usize,+ payload: Value,+ model: pa_agent::types::Model,+ session_id: Option<String>,+ request_seq: u64,+ now_ms: u128,+ /// The process-unique file-name counter (see [`CAPTURE_SEQ`]).+ capture_seq: u64,+ /// The payload's byte estimate (see [`payload_bytes`]): the budget+ /// the writer releases once the body is written.+ estimate: u64,+}++/// The process's single capture writer handle: the bounded queue, the+/// reserve counter of jobs still queued, and the retained-bytes budget.+struct CaptureWriter {+ sender: SyncSender<CaptureJob>,+ /// Reserved slots: handed-off jobs the writer has not taken yet. The+ /// reservation (`fetch_update`) precedes the payload clone, the+ /// writer's `recv` releases each slot, and a rejected handoff+ /// releases its own — the counter never underflows and never reports+ /// saturation without a full queue behind it.+ queued: Arc<AtomicUsize>,+ /// The retained payload bytes: queued jobs plus the writer's in-flight+ /// body. The budget reservation precedes the clone; the writer+ /// releases each body's estimate once its write settles.+ retained: Arc<AtomicU64>,+}++/// The one writer, armed on the first recorded capture. The thread is+/// process-owned and detached by design: it lives until process exit,+/// and an orderly shutdown never waits on it — captures still queued at+/// exit are lost best-effort (a partial temp file ages out with the+/// ring), the same contract as the rotating log.+static CAPTURE_WRITER: OnceLock<Option<CaptureWriter>> = OnceLock::new();++/// The process's capture writer, arming it on first use: one thread, one+/// bounded queue. `None` (cached) when the thread cannot spawn — the+/// capture stays disabled for the process, best-effort by contract.+fn capture_writer() -> Option<&'static CaptureWriter> {+ CAPTURE_WRITER+ .get_or_init(|| {+ // The confidentiality boundary is only enforceable where the+ // platform wall can enforce owner-only modes: the wall's+ // Windows arms are inherited-ACL no-ops, so rather than write+ // complete request bodies through a possibly permissive+ // inherited ACL, the capture stays disabled there (see the+ // module doc).+ #[cfg(not(unix))]+ {+ tracing::debug!(+ "payload capture disabled: owner-only modes are not enforceable on this platform"+ );+ return None;+ }+ #[cfg(unix)]+ {+ let (sender, receiver) = std::sync::mpsc::sync_channel(WRITE_QUEUE_CAPACITY.max(1));+ let queued = Arc::new(AtomicUsize::new(0));+ let retained = Arc::new(AtomicU64::new(0));+ let writer_queued = Arc::clone(&queued);+ let writer_retained = Arc::clone(&retained);+ std::thread::Builder::new()+ .name("request-payload-capture".to_string())+ .spawn(move || {+ let writer_queued = writer_queued;+ let writer_retained = writer_retained;+ let receiver = receiver;+ drain_writer(&writer_queued, &writer_retained, &receiver);+ })+ .map(|_| CaptureWriter {+ sender,+ queued,+ retained,+ })+ .map_err(|error| {+ tracing::debug!(%error, "payload capture writer thread failed to spawn");+ })+ .ok()+ }+ })+ .as_ref()+}++/// The outbound request-body capture: the capture's configuration — which+/// ring directory each body lands in, how many files it keeps, and the+/// trust root (`agentDir`) whose path components must all be real+/// directories before the capture will write — handed to the process's+/// single writer by the request-timing payload hook.+#[derive(Debug, Clone)]+pub(crate) struct RequestPayloadCapture {+ root: PathBuf,+ dir: PathBuf,+ keep: usize,+}++impl RequestPayloadCapture {+ /// The capture under `<agentDir>/logs/request-payloads/`, keeping the+ /// newest [`REQUEST_PAYLOAD_CAPTURE_KEEP`] bodies. `agent_dir` is the+ /// trust root: every component below it must be a real directory (a+ /// symlinked `logs` or ring dir would redirect the private-mode+ /// writes, and the capture refuses to follow it).+ #[must_use]+ pub(crate) fn new(agent_dir: &Path) -> Self {+ Self::at_rooted(+ agent_dir,+ agent_dir.join("logs").join("request-payloads"),+ REQUEST_PAYLOAD_CAPTURE_KEEP,+ )+ }++ /// The capture at an explicit directory and ring size (tests): the+ /// directory's parent is the trust root.+ #[cfg(test)]+ #[must_use]+ pub(crate) fn at(dir: impl Into<PathBuf>, keep: usize) -> Self {+ let dir: PathBuf = dir.into();+ let root = dir.parent().map_or_else(|| dir.clone(), Path::to_path_buf);+ Self::at_rooted(root, dir, keep)+ }++ /// The capture at an explicit directory under an explicit trust root.+ #[must_use]+ pub(crate) fn at_rooted(+ root: impl Into<PathBuf>,+ dir: impl Into<PathBuf>,+ keep: usize,+ ) -> Self {+ Self {+ root: root.into(),+ dir: dir.into(),+ keep,+ }+ }++ /// Hand one request's final outbound body to the writer. Bounded and+ /// non-blocking: the queue slot is reserved BEFORE the payload clone+ /// (a saturated queue drops the capture at O(1)), a reservation whose+ /// handoff the queue rejects is released immediately, and the+ /// dispatch path never touches the filesystem.+ pub(crate) fn record(+ &self,+ payload: &Value,+ model: &pa_agent::types::Model,+ session_id: Option<&str>,+ request_seq: u64,+ ) {+ let Some(writer) = capture_writer() else {+ return;+ };+ // Reserve the slot first: the counter is the bound the writer+ // releases from, so it must never depend on the send's+ // completion (the writer can take the job before any post-send+ // accounting runs).+ let reserved = writer+ .queued+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |queued| {+ (queued < WRITE_QUEUE_CAPACITY).then_some(queued + 1)+ })+ .is_ok();+ if !reserved {+ return;+ }+ // Reserve the payload's bytes before cloning it: a stalled+ // writer must not accumulate unbounded resident memory. The+ // estimate walks the value once without allocating; a body that+ // would push the retained bytes past the budget drops here —+ // its slot releases and no copy is made.+ let estimate = payload_bytes(payload);+ let budgeted = writer+ .retained+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |retained| {+ retained+ .checked_add(estimate)+ .filter(|total| *total <= REQUEST_PAYLOAD_BUDGET_BYTES)+ })+ .is_ok();+ if !budgeted {+ writer.queued.fetch_sub(1, Ordering::Relaxed);+ return;+ }+ let now_ms = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis();+ let job = CaptureJob {+ root: self.root.clone(),+ dir: self.dir.clone(),+ keep: self.keep,+ payload: payload.clone(),+ model: model.clone(),+ session_id: session_id.map(ToString::to_string),+ request_seq,+ now_ms,+ capture_seq: CAPTURE_SEQ.fetch_add(1, Ordering::Relaxed) + 1,+ estimate,+ };+ if writer.sender.try_send(job).is_err() {+ // The queue filled inside the reservation window: the job+ // never queued, so its slot and its bytes free for the next+ // handoff.+ writer.queued.fetch_sub(1, Ordering::Relaxed);+ writer.retained.fetch_sub(estimate, Ordering::Relaxed);+ }+ }+}++/// The writer thread: release the job's queue slot as it is taken, then+/// serialize the capture, write it through a private temp file, rename it+/// into place (a reader never sees a partial body), and prune the ring.+/// The body's retained bytes release once its write settles (the job's+/// payload is dropped right after).+fn drain_writer(queued: &Arc<AtomicUsize>, retained: &Arc<AtomicU64>, jobs: &Receiver<CaptureJob>) {+ while let Ok(job) = jobs.recv() {+ queued.fetch_sub(1, Ordering::Relaxed);+ let result = write_capture(&job.root, &job.dir, job.keep, &job);+ retained.fetch_sub(job.estimate, Ordering::Relaxed);+ if let Err(error) = result {+ tracing::debug!(dir = %job.dir.display(), %error, "payload capture write failed");+ }+ }+}++/// The payload's byte estimate: an UPPER BOUND on what one accepted+/// capture allocates — the queue's clone, the envelope's re-clone, and+/// the serialized bytes — walked once without allocating. Every node+/// pays its own enum footprint (plus the collection slots), and the+/// total carries the transient-copies multiplier: the budget is an OOM+/// guard, so overcounting is the point.+pub(crate) fn payload_bytes(value: &Value) -> u64 {+ /// One `Value` node's own footprint (the enum's size).+ const NODE: u64 = 32;+ /// The transient full-body copies one accepted capture allocates:+ /// the queued clone, the envelope's clone, and the serialization+ /// buffer.+ const TRANSIENT_COPIES: u64 = 3;+ fn tree(value: &Value) -> u64 {+ match value {+ Value::Null | Value::Bool(_) | Value::Number(_) => NODE,+ Value::String(text) => NODE + text.len() as u64,+ Value::Array(items) => NODE + items.iter().map(|item| tree(item) + NODE).sum::<u64>(),+ Value::Object(map) => {+ NODE + map+ .iter()+ .map(|(key, item)| key.len() as u64 + tree(item) + NODE + 64)+ .sum::<u64>()+ }+ }+ }+ tree(value).saturating_mul(TRANSIENT_COPIES)+}++/// The capture file's correlation envelope: the same identity fields the+/// request-timing entries carry, so a capture correlates with its+/// timeline by sequence number; empty or absent fields stay omitted.+fn capture_envelope(job: &CaptureJob) -> Value {+ let mut envelope = Map::new();+ envelope.insert("ts".to_string(), json!(format_iso(job.now_ms as i64)));+ if let Some(session_id) = &job.session_id {+ envelope.insert("sessionId".to_string(), json!(session_id));+ }+ envelope.insert("model".to_string(), json!(job.model.id));+ if !job.model.provider.is_empty() {+ envelope.insert("provider".to_string(), json!(job.model.provider));+ }+ if !job.model.api.is_empty() {+ envelope.insert("api".to_string(), json!(job.model.api));+ }+ envelope.insert("requestSeq".to_string(), json!(job.request_seq));+ if let Some(request_bytes) = super::measure_request_bytes(&job.payload) {+ envelope.insert("requestBytes".to_string(), json!(request_bytes));+ }+ envelope.insert("payload".to_string(), job.payload.clone());+ Value::Object(envelope)+}++/// Persist one capture: refuse any symlinked path component from the+/// trust root down (a redirected private-mode write is a disclosure, not+/// a diagnostic), owner-only directory and file modes (a shared or+/// permissively created agent dir must not expose the request bodies to+/// other local users), the durable rename through the platform wall,+/// then the ring prune. Best-effort: every failure is the caller's to+/// swallow — and a failed write takes its temp file with it.+fn write_capture(root: &Path, dir: &Path, keep: usize, job: &CaptureJob) -> std::io::Result<()> {+ use std::io::Write;+ refuse_symlinked_components(root, dir)?;+ perms::create_dir_all_private(dir)?;+ // The directory can pre-exist with permissive modes (a shared+ // agentDir, a different umask): the restriction re-applies every+ // write, not only at creation.+ perms::restrict_dir(dir)?;+ let bytes = serde_json::to_vec_pretty(&capture_envelope(job))+ .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string()))?;+ // The epoch lead keeps lexical order chronological (the prune's+ // eviction order); the process-unique counter makes the name unique+ // across every session wiring sharing the dir.+ let name = format!(+ "{}-{}-{:08}.json",+ job.now_ms,+ std::process::id(),+ job.capture_seq+ );+ let target = dir.join(&name);+ let temp = dir.join(format!("{name}.tmp"));+ let mut options = std::fs::OpenOptions::new();+ // Exclusive creation: a pre-existing path (an attacker's symlink at+ // the predictable name) fails the open instead of being followed.+ options.write(true).create_new(true);+ perms::set_private_mode(&mut options);+ let write = (|| -> std::io::Result<()> {+ {+ let mut file = options.open(&temp)?;+ file.write_all(&bytes)?;+ file.flush()?;+ }+ perms::restrict_file(&temp)?;+ crate::platform::rename_onto(&temp, &target)+ })();+ if write.is_err() {+ // The ring ages crash-leftover temps; a failed write cleans up+ // after itself so repeated failures do not accumulate partial+ // bodies.+ let _ = std::fs::remove_file(&temp);+ }+ write?;+ prune(dir, keep);+ Ok(())+}++/// Refuse any symlinked path component from `root` down to `dir`: the+/// capture's owner-only modes are path-based, so a symlinked `logs` or+/// ring directory would redirect the private writes into an+/// attacker-owned tree. `symlink_metadata` inspects each component+/// without following it; a missing component is fine (the create below+/// makes it, privately), but a symlink ends the capture.+fn refuse_symlinked_components(root: &Path, dir: &Path) -> std::io::Result<()> {+ // Only the components below the trust root are walked: the root+ // itself is the user's configured agent dir (its own symlinks are+ // the user's choice); anything not under it is not the capture's+ // tree and is refused outright. A missing component is fine — the+ // private create below makes it; a symlinked one is not.+ let mut current = root.to_path_buf();+ for component in dir.strip_prefix(root).map_err(|_| {+ std::io::Error::new(+ std::io::ErrorKind::InvalidInput,+ format!(+ "{}: the capture directory is not under its trust root",+ dir.display()+ ),+ )+ })? {+ current = current.join(component);+ match std::fs::symlink_metadata(¤t) {+ Ok(metadata) => {+ if metadata.is_symlink() {+ return Err(std::io::Error::new(+ std::io::ErrorKind::InvalidInput,+ format!(+ "{}: refusing the capture: a symlinked path component redirects private writes",+ current.display()+ ),+ ));+ }+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(error) => return Err(error),+ }+ }+ Ok(())+}++/// Keep only the newest `keep` files: names sort chronologically (the+/// epoch-ms lead), so the oldest leave first. A stale temp file (a+/// crashed write's leftover) counts as one of the ring's files and ages+/// out the same way; a mid-write temp file carries the newest name and+/// never evicts.+fn prune(dir: &Path, keep: usize) {+ let Ok(entries) = std::fs::read_dir(dir) else {+ return;+ };+ let mut names: Vec<String> = entries+ .flatten()+ .map(|entry| entry.file_name().to_string_lossy().into_owned())+ .filter(|name| {+ let extension = Path::new(name)+ .extension()+ .map(|ext| ext.to_string_lossy().into_owned());+ extension.is_some_and(|extension| {+ extension.eq_ignore_ascii_case("json") || extension.eq_ignore_ascii_case("tmp")+ })+ })+ .collect();+ names.sort();+ let excess = names.len().saturating_sub(keep);+ for name in &names[..excess] {+ let _ = std::fs::remove_file(dir.join(name));+ }+}diff --git a/crates/pa-core/src/session_engine/request_timing/payload/tests.rs b/crates/pa-core/src/session_engine/request_timing/payload/tests.rsnew file mode 100644index 0000000000..6701fc1698--- /dev/null+++ b/crates/pa-core/src/session_engine/request_timing/payload/tests.rs@@ -0,0 +1,695 @@+//! The payload capture's own battery: the exact-body + envelope contract,+//! the owner-only permission boundary, the symlink refusal, the+//! retained-bytes budget, the temp-file cleanup, the ring bound, the+//! name uniqueness across wirings sharing one directory, and the+//! dispatch-path contract (record never touches the filesystem; a slow+//! or failing writer never delays the request it observes).++use super::*;+use serde_json::json;+use std::path::Path;+use std::sync::atomic::Ordering;+use std::sync::Arc;++/// The capture files' names, oldest first (the epoch-lead name order).+pub(crate) fn payload_files(dir: &Path) -> Vec<String> {+ let mut names: Vec<String> = std::fs::read_dir(dir)+ .map(|entries| {+ entries+ .flatten()+ .filter(|entry| entry.file_type().is_ok_and(|file_type| file_type.is_file()))+ .map(|entry| entry.file_name().to_string_lossy().into_owned())+ .filter(|name| Path::new(name).extension().is_some_and(|ext| ext == "json"))+ .collect()+ })+ .unwrap_or_default();+ names.sort();+ names+}++/// Wait until the writer thread landed `count` capture files: the file is+/// the observable, the deadline bounds failure (a timeout fails the+/// test, never passes it).+pub(crate) fn wait_for_payload_files(dir: &Path, count: usize) {+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);+ loop {+ let files = payload_files(dir);+ if files.len() >= count {+ return;+ }+ assert!(+ std::time::Instant::now() <= deadline,+ "the capture files never landed: have {files:?}, want {count}"+ );+ std::thread::sleep(std::time::Duration::from_millis(10));+ }+}++/// Wait until the writer's queue is empty (every reservation released).+pub(crate) fn wait_for_drained_queue() {+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);+ loop {+ let queued = super::CAPTURE_WRITER+ .get()+ .and_then(|writer| {+ writer+ .as_ref()+ .map(|writer| writer.queued.load(Ordering::Relaxed))+ })+ .expect("the writer is armed");+ if queued == 0 {+ return;+ }+ assert!(+ std::time::Instant::now() <= deadline,+ "the writer queue never drained: {queued} jobs remain"+ );+ std::thread::sleep(std::time::Duration::from_millis(10));+ }+}++/// One capture file's parsed envelope.+pub(crate) fn payload_envelope(dir: &Path, name: &str) -> Value {+ let content = std::fs::read_to_string(dir.join(name)).expect("the capture file reads");+ serde_json::from_str(&content).expect("the capture file is one complete JSON object")+}++fn agent_model() -> pa_agent::types::Model {+ pa_agent::types::Model {+ id: "bench/bench-model".to_string(),+ name: "Bench".to_string(),+ api: "openai-completions".to_string(),+ provider: "bench".to_string(),+ base_url: "https://bench.test/v1".to_string(),+ reasoning: true,+ cost: pa_agent::types::UsageCost::default(),+ context_window: 1_000_000,+ max_tokens: 128_000,+ }+}++fn job(+ root: &Path,+ dir: &Path,+ keep: usize,+ payload: Value,+ request_seq: u64,+ capture_seq: u64,+) -> CaptureJob {+ let estimate = payload_bytes(&payload);+ CaptureJob {+ root: root.to_path_buf(),+ dir: dir.to_path_buf(),+ keep,+ payload,+ model: agent_model(),+ session_id: Some("sess-timing".to_string()),+ request_seq,+ now_ms: 1_700_000_000_000,+ capture_seq,+ estimate,+ }+}++/// Fill the process writer's queue until the reserve counter reports it+/// full, whatever the writer's drain pace: the counter (read directly)+/// is the saturation observable, so the probe or storm below races a+/// provably-full queue instead of a serialization-time assumption.+fn fill_until_saturated(capture: &RequestPayloadCapture, marker_prefix: &str) -> usize {+ let writer = super::CAPTURE_WRITER+ .get()+ .and_then(|writer| writer.as_ref())+ .expect("the writer is armed");+ let mut fills = 0;+ while fills < 2 * REQUEST_PAYLOAD_CAPTURE_KEEP {+ if writer.queued.load(Ordering::Relaxed) >= WRITE_QUEUE_CAPACITY {+ break;+ }+ capture.record(+ &json!({ "marker": format!("{marker_prefix}-{fills}") }),+ &agent_model(),+ Some("sess-timing"),+ fills as u64 + 2,+ );+ fills += 1;+ }+ assert!(+ writer.queued.load(Ordering::Relaxed) >= WRITE_QUEUE_CAPACITY,+ "the fill loop never saturated the queue"+ );+ fills+}++#[test]+fn the_capture_writes_the_exact_body_and_envelope() {+ let _writer_lock = super::WRITER_TEST_LOCK.blocking_lock();+ let dir = tempfile::tempdir().unwrap();+ let dir_path = dir.path().join("request-payloads");+ let payload = json!({"messages": [{"role": "user", "content": "hello \u{1F680}"}]});+ write_capture(+ dir.path(),+ &dir_path,+ 64,+ &job(dir.path(), &dir_path, 64, payload, 7, 1),+ )+ .expect("the write persists");+ let names = payload_files(&dir_path);+ assert_eq!(names.len(), 1, "one file per request: {names:?}");+ let envelope = payload_envelope(&dir_path, &names[0]);+ assert_eq!(+ envelope.get("payload"),+ Some(&json!({"messages": [{"role": "user", "content": "hello \u{1F680}"}]})),+ "the file carries the exact outbound body: {envelope}"+ );+ assert_eq!(+ envelope.get("model").and_then(Value::as_str),+ Some("bench/bench-model")+ );+ assert_eq!(+ envelope.get("provider").and_then(Value::as_str),+ Some("bench")+ );+ assert_eq!(envelope.get("sessionId"), Some(&json!("sess-timing")));+ assert_eq!(envelope.get("requestSeq"), Some(&json!(7)));+ assert_eq!(+ envelope.get("requestBytes"),+ Some(&json!(+ serde_json::to_vec(&envelope["payload"]).unwrap().len() as u64+ )),+ "UTF-8 bytes, not a code-unit count: {envelope}"+ );+ assert!(+ envelope.get("ts").and_then(Value::as_str).is_some(),+ "the envelope carries the ISO timestamp: {envelope}"+ );+}++/// The capture is a confidentiality boundary, not just a diagnostic: the+/// request bodies carry the whole transcript (system prompt, messages,+/// tool output), so the ring's directory and every file are owner-only —+/// including when the directory already exists with permissive modes (a+/// shared or different-umask agent dir).+#[cfg(unix)]+#[test]+fn the_capture_writes_owner_only_modes_even_into_an_existing_dir() {+ use std::os::unix::fs::PermissionsExt;+ let _writer_lock = super::WRITER_TEST_LOCK.blocking_lock();+ let dir = tempfile::tempdir().unwrap();+ let dir_path = dir.path().join("request-payloads");+ std::fs::create_dir_all(&dir_path).unwrap();+ std::fs::set_permissions(&dir_path, std::fs::Permissions::from_mode(0o755)).unwrap();+ write_capture(+ dir.path(),+ &dir_path,+ 64,+ &job(dir.path(), &dir_path, 64, json!({"a": 1}), 1, 1),+ )+ .expect("the write persists");+ assert_eq!(+ perms::file_mode(&dir_path),+ Some(perms::PRIVATE_DIR_MODE),+ "the existing permissive dir is restricted"+ );+ let name = &payload_files(&dir_path)[0];+ assert_eq!(+ perms::file_mode(&dir_path.join(name)),+ Some(perms::PRIVATE_FILE_MODE),+ "the capture file is owner-only"+ );+}++/// A symlinked path component would redirect the private-mode writes+/// into an attacker-owned tree, so the capture refuses: both a symlinked+/// `logs` and a symlinked ring directory end the write before anything+/// is created or restricted.+#[cfg(unix)]+#[test]+fn symlinked_components_end_the_capture_before_any_write() {+ let _writer_lock = super::WRITER_TEST_LOCK.blocking_lock();+ let dir = tempfile::tempdir().unwrap();+ // A symlinked ring directory: <agent>/request-payloads -> <attacker>.+ let attacker = dir.path().join("attacker");+ std::fs::create_dir_all(&attacker).unwrap();+ let symlinked_ring = dir.path().join("request-payloads");+ std::os::unix::fs::symlink(&attacker, &symlinked_ring).unwrap();+ let error = write_capture(+ dir.path(),+ &symlinked_ring,+ 64,+ &job(dir.path(), &symlinked_ring, 64, json!({"a": 1}), 1, 1),+ )+ .expect_err("the symlinked ring is refused");+ assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);+ assert!(+ payload_files(&attacker).is_empty(),+ "nothing reached the symlink target"+ );++ // A symlinked intermediate component (the `logs` tree): the ring+ // directory is never created through the link.+ let logs_link = dir.path().join("logs");+ std::os::unix::fs::symlink(&attacker, &logs_link).unwrap();+ let through_link = logs_link.join("request-payloads");+ let error = write_capture(+ dir.path(),+ &through_link,+ 64,+ &job(dir.path(), &through_link, 64, json!({"b": 2}), 1, 2),+ )+ .expect_err("the symlinked logs component is refused");+ assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);+ assert!(+ payload_files(&attacker).is_empty(),+ "nothing reached the symlink target"+ );+}++/// A failed write takes its temp file with it: the temp is created+/// exclusively, and any failure after its creation (here: the rename onto+/// a pre-existing directory) cleans it up instead of accumulating+/// partial bodies.+#[test]+fn a_failed_write_takes_its_temp_file_with_it() {+ let _writer_lock = super::WRITER_TEST_LOCK.blocking_lock();+ let dir = tempfile::tempdir().unwrap();+ let dir_path = dir.path().join("request-payloads");+ std::fs::create_dir_all(&dir_path).unwrap();+ // The known-name target exists as a directory: the rename fails+ // after the temp file was written.+ let target = dir_path.join(format!(+ "1700000000000-{}-00000007.json",+ std::process::id()+ ));+ std::fs::create_dir_all(&target).unwrap();+ let payload = json!({"messages": [{"role": "user", "content": "hello"}]});+ let error = write_capture(+ dir.path(),+ &dir_path,+ 64,+ &job(dir.path(), &dir_path, 64, payload, 7, 7),+ )+ .expect_err("the blocked rename fails the write");+ assert_ne!(error.kind(), std::io::ErrorKind::InvalidInput);+ let temps: Vec<String> = std::fs::read_dir(&dir_path)+ .unwrap()+ .flatten()+ .map(|entry| entry.file_name().to_string_lossy().into_owned())+ .filter(|name| Path::new(name).extension().is_some_and(|ext| ext == "tmp"))+ .collect();+ assert!(+ temps.is_empty(),+ "the failed write cleaned up its temp: {temps:?}"+ );+ assert_eq!(+ payload_files(&dir_path).len(),+ 0,+ "no capture landed through the failure"+ );+}++/// The retained-bytes budget: the queue bounds the COUNT, the budget+/// bounds the BYTES — a body that would push the retained bytes past+/// the budget drops without cloning, and the budget recovers once the+/// writer drains (a fresh handoff lands afterwards).+#[test]+fn an_over_budget_body_drops_without_cloning() {+ let _writer_lock = super::WRITER_TEST_LOCK.blocking_lock();+ let dir = tempfile::tempdir().unwrap();+ let dir_path = dir.path().join("request-payloads");+ let capture = RequestPayloadCapture::at(&dir_path, 8);+ // The stall: a many-node body the writer serializes for far longer+ // than the three records below take, so the earlier bodies'+ // reservations hold while the third is priced — the drop is the+ // budget's, not the drain's timing.+ let stall = json!({+ "marker": "stall",+ "messages": (0..20_000_u32).map(|seq| json!({ "seq": seq })).collect::<Vec<_>>()+ });+ // Three bodies that each estimate near a third of the budget: the+ // third would cross it and drops at the budget gate (the estimate+ // already carries the transient-copies multiplier).+ let body_x = json!({ "marker": "budget-x", "body": "x".repeat(8 * 1024 * 1024) });+ let body_y = json!({ "marker": "budget-y", "body": "y".repeat(8 * 1024 * 1024) });+ let body_z = json!({ "marker": "budget-z", "body": "z".repeat(8 * 1024 * 1024) });+ assert!(payload_bytes(&body_x) * 2 < REQUEST_PAYLOAD_BUDGET_BYTES);+ assert!(payload_bytes(&body_x) * 3 > REQUEST_PAYLOAD_BUDGET_BYTES);+ capture.record(&stall, &agent_model(), Some("sess-timing"), 0);+ capture.record(&body_x, &agent_model(), Some("sess-timing"), 1);+ capture.record(&body_y, &agent_model(), Some("sess-timing"), 2);+ capture.record(&body_z, &agent_model(), Some("sess-timing"), 3);+ // The drain lands the stall and the first two bodies only.+ wait_for_payload_files(&dir_path, 3);+ wait_for_drained_queue();+ capture.record(+ &json!({ "marker": "recovered" }),+ &agent_model(),+ Some("sess-timing"),+ 4,+ );+ wait_for_payload_files(&dir_path, 4);+ let files = payload_files(&dir_path);+ let landed = files+ .iter()+ .map(|name| {+ payload_envelope(&dir_path, name)["payload"]["marker"]+ .as_str()+ .expect("the envelope carries the marker")+ .to_string()+ })+ .collect::<Vec<_>>();+ assert_eq!(+ landed,+ ["stall", "budget-x", "budget-y", "recovered"],+ "the over-budget body never landed; the recovered handoff did"+ );+ assert!(+ !files.iter().any(|name| {+ std::fs::read_to_string(dir_path.join(name))+ .is_ok_and(|content| content.contains("budget-z"))+ }),+ "the dropped body exists nowhere in the ring"+ );+}++#[test]+fn the_ring_keeps_the_newest_bodies() {+ let _writer_lock = super::WRITER_TEST_LOCK.blocking_lock();+ let dir = tempfile::tempdir().unwrap();+ let dir_path = dir.path().join("request-payloads");+ for seq in 1..=3u64 {+ write_capture(+ dir.path(),+ &dir_path,+ 2,+ &job(+ dir.path(),+ &dir_path,+ 2,+ json!({ "request": seq }),+ seq,+ seq,+ ),+ )+ .expect("the write persists");+ }+ let names = payload_files(&dir_path);+ assert_eq!(names.len(), 2, "the ring keeps the configured size");+ let bodies: Vec<u64> = names+ .iter()+ .map(|name| {+ payload_envelope(&dir_path, name)["payload"]["request"]+ .as_u64()+ .expect("the parsed envelope carries the body")+ })+ .collect();+ assert_eq!(bodies, [2, 3], "the oldest body left first: {bodies:?}");+}++/// Two session wirings share one agent dir and both restart their wire+/// sequence at 1: the capture's file names stay unique (the process-wide+/// counter), so neither body truncates the other.+#[test]+fn two_wirings_sharing_one_dir_each_keep_their_capture() {+ let _writer_lock = super::WRITER_TEST_LOCK.blocking_lock();+ let dir = tempfile::tempdir().unwrap();+ let dir_path = dir.path().join("request-payloads");+ let wiring_a = RequestPayloadCapture::at(&dir_path, 64);+ let wiring_b = RequestPayloadCapture::at(&dir_path, 64);+ wiring_a.record(&json!({"wiring": "a"}), &agent_model(), Some("sess-a"), 1);+ wiring_b.record(&json!({"wiring": "b"}), &agent_model(), Some("sess-b"), 1);+ wait_for_payload_files(&dir_path, 2);+ let names = payload_files(&dir_path);+ let mut wirings = names+ .iter()+ .map(|name| {+ payload_envelope(&dir_path, name)["payload"]["wiring"]+ .as_str()+ .expect("the parsed envelope carries the body")+ .to_string()+ })+ .collect::<Vec<_>>();+ wirings.sort();+ assert_eq!(wirings, ["a", "b"], "both captures survived intact");+}++/// One writer serves the whole process: two sessions' captures (two+/// rings, two directories) hand off to the same bounded writer and each+/// owns its own directory — no cross-writes, no per-session thread.+#[test]+fn two_sessions_captures_own_their_directories() {+ let _writer_lock = super::WRITER_TEST_LOCK.blocking_lock();+ let dir = tempfile::tempdir().unwrap();+ let dir_a = dir.path().join("agent-a").join("request-payloads");+ let dir_b = dir.path().join("agent-b").join("request-payloads");+ let capture_a = RequestPayloadCapture::at(&dir_a, 8);+ let capture_b = RequestPayloadCapture::at(&dir_b, 8);+ for seq in 0..3 {+ capture_a.record(+ &json!({"session": "a", "seq": seq}),+ &agent_model(),+ Some("sess-a"),+ seq,+ );+ capture_b.record(+ &json!({"session": "b", "seq": seq}),+ &agent_model(),+ Some("sess-b"),+ seq,+ );+ }+ wait_for_payload_files(&dir_a, 3);+ wait_for_payload_files(&dir_b, 3);+ for (path, session) in [(&dir_a, "a"), (&dir_b, "b")] {+ let envelopes: Vec<Value> = payload_files(path)+ .iter()+ .map(|name| payload_envelope(path, name))+ .collect();+ assert_eq!(+ envelopes.len(),+ 3,+ "each ring holds exactly its own captures"+ );+ for envelope in &envelopes {+ assert_eq!(envelope["payload"]["session"], json!(session));+ assert_eq!(envelope["sessionId"], json!(format!("sess-{session}")));+ }+ }+}++/// A capture whose directory cannot exist (a file sits on the path) is+/// silently disabled: the handoffs succeed, nothing panics, and the+/// request-timing integration (the failing-capture wiring test) keeps+/// the request itself untouched.+#[test]+fn an_unwritable_target_disables_the_capture_silently() {+ let _writer_lock = super::WRITER_TEST_LOCK.blocking_lock();+ let dir = tempfile::tempdir().unwrap();+ // A FILE where the capture's directory would be: every write fails.+ let blocker = dir.path().join("request-payloads");+ std::fs::write(&blocker, "a file, not a directory").unwrap();+ let capture = RequestPayloadCapture::at(&blocker, 64);+ capture.record(&json!({"a": 1}), &agent_model(), Some("sess-timing"), 1);+ capture.record(&json!({"a": 2}), &agent_model(), Some("sess-timing"), 2);+ // The handoffs succeeded and nothing can ever appear on the blocker:+ // a failed capture stays silent (the integration test proves the+ // request path is unaffected).+ assert_eq!(+ std::fs::read_to_string(&blocker).unwrap(),+ "a file, not a directory",+ "the capture never replaces the blocker with a directory"+ );+}++/// The dispatch-path contract: [`RequestPayloadCapture::record`] never+/// touches the filesystem — the writer thread owns the serialization and+/// the writes — so a slow writer can never delay the request that handed+/// the body off. The observable: the file does not exist yet when record+/// returns for a body this large, and lands afterwards.+#[test]+fn a_record_hands_off_without_waiting_for_the_write() {+ let _writer_lock = super::WRITER_TEST_LOCK.blocking_lock();+ let dir = tempfile::tempdir().unwrap();+ let dir_path = dir.path().join("request-payloads");+ let capture = RequestPayloadCapture::at(&dir_path, 64);+ let big = "x".repeat(8 * 1024 * 1024);+ let payload = json!({"messages": [{"role": "user", "content": big}]});+ let started = std::time::Instant::now();+ capture.record(&payload, &agent_model(), Some("sess-timing"), 1);+ let handed_off = started.elapsed();+ // The clone on the dispatch path is bounded by memory, not by the+ // disk: handing this body off costs milliseconds.+ assert!(+ handed_off < std::time::Duration::from_secs(2),+ "the handoff is memory-bounded: {handed_off:?}"+ );+ assert!(+ payload_files(&dir_path).is_empty(),+ "the write happens on the writer thread, after record returns"+ );+ wait_for_payload_files(&dir_path, 1);+ let names = payload_files(&dir_path);+ let envelope = payload_envelope(&dir_path, &names[0]);+ assert_eq!(+ envelope.get("requestBytes"),+ Some(&json!(serde_json::to_vec(&payload).unwrap().len() as u64)),+ "the writer persisted the whole body: {envelope:?}"+ );+}++/// The saturated-queue handoff stays O(1): the queue's slot reserve+/// precedes the payload clone, so a writer stalled on a full queue drops+/// the next capture without paying the copy. The queue is saturated+/// deterministically (the reserve counter itself is the observable), and+/// the self-calibrating bound compares the probe's handoff against the+/// same body's directly measured clone cost.+#[test]+fn a_saturated_queue_drops_without_cloning() {+ let _writer_lock = super::WRITER_TEST_LOCK.blocking_lock();+ let dir = tempfile::tempdir().unwrap();+ let dir_path = dir.path().join("request-payloads");+ // The ring keeps every body: the count assertions need no eviction.+ let capture = RequestPayloadCapture::at(&dir_path, 4 * REQUEST_PAYLOAD_CAPTURE_KEEP);+ // The stall body: a many-node body the writer serializes for far+ // longer than the whole test window, so no slot frees mid-probe.+ let stall = json!({+ "marker": "stall",+ "messages": (0..100_000_u32).map(|seq| json!({ "seq": seq })).collect::<Vec<_>>()+ });+ capture.record(&stall, &agent_model(), Some("sess-timing"), 1);+ // The fill: the queue is saturated against the reserve counter.+ let fills = fill_until_saturated(&capture, "fill");+ // The probe: the same shape as the calibration body — its clone is+ // measurably slow, its reserve-check drop is not.+ let big = "x".repeat(128 * 1024 * 1024);+ let probe = json!({ "messages": [{"role": "user", "content": big}] });+ let clone_started = std::time::Instant::now();+ let calibration = probe.clone();+ let clone_cost = clone_started.elapsed();+ drop(calibration);+ let probe_started = std::time::Instant::now();+ capture.record(&probe, &agent_model(), Some("sess-timing"), 99);+ let probe_cost = probe_started.elapsed();+ assert!(+ probe_cost + probe_cost < clone_cost,+ "the saturated handoff must not pay the clone: probe {probe_cost:?} vs clone {clone_cost:?}"+ );+ // The drain lands the stall body and every fill; the probe never+ // queued, so it never lands. A fresh handoff after the drain still+ // reserves and lands (no reservation leak).+ wait_for_drained_queue();+ capture.record(+ &json!({ "marker": "recovered" }),+ &agent_model(),+ Some("sess-timing"),+ u64::MAX,+ );+ wait_for_payload_files(&dir_path, fills + 2);+ let landed = payload_files(&dir_path);+ let fill_count = landed+ .iter()+ .filter(|name| {+ std::fs::read_to_string(dir_path.join(name))+ .is_ok_and(|content| content.contains("fill-"))+ })+ .count();+ assert_eq!(+ fill_count, fills,+ "every fill landed (the fills are part of the saturated queue's content)"+ );+ assert_eq!(+ landed.len(),+ fill_count + 2,+ "the stall body, every fill, and the recovery — the probe exists nowhere"+ );+ assert!(+ !landed.iter().any(|name| {+ std::fs::metadata(dir_path.join(name)).is_ok_and(|meta| meta.len() > 16 * 1024 * 1024)+ }),+ "no probe-sized body landed"+ );+}++/// The concurrent-producers pin: a barrier of producers racing a+/// pre-saturated queue — every one of them drops at the reserve check,+/// without paying a payload copy (the queue is saturated against the+/// reserve counter itself, not a serialization-time assumption), the+/// counter never exceeds the capacity, and a fresh handoff still+/// reserves after the storm (no reservation leak).+#[test]+fn concurrent_producers_drop_at_the_reserve_when_the_queue_is_full() {+ let _writer_lock = super::WRITER_TEST_LOCK.blocking_lock();+ let dir = tempfile::tempdir().unwrap();+ let dir_path = dir.path().join("request-payloads");+ // The ring keeps every body: the count assertions need no eviction.+ let capture = RequestPayloadCapture::at(&dir_path, 4 * REQUEST_PAYLOAD_CAPTURE_KEEP);+ // The stall body: a many-node body the writer serializes for far+ // longer than the whole storm window, so no queue slot frees mid+ // storm.+ let stall = json!({+ "marker": "stall",+ "messages": (0..100_000_u32).map(|seq| json!({ "seq": seq })).collect::<Vec<_>>()+ });+ capture.record(&stall, &agent_model(), Some("sess-timing"), 1);+ let fills = fill_until_saturated(&capture, "fill");+ // The storm: many concurrent producers, each with its own marker,+ // racing the full queue. Every one drops at the reserve check —+ // the assertions below are the observable: none of their bodies+ // exists anywhere afterwards.+ let producers = 4 * REQUEST_PAYLOAD_CAPTURE_KEEP;+ let barrier = Arc::new(std::sync::Barrier::new(producers + 1));+ let mut handles = Vec::new();+ for producer in 0..producers {+ let capture = capture.clone();+ let barrier = Arc::clone(&barrier);+ handles.push(std::thread::spawn(move || {+ barrier.wait();+ capture.record(+ &json!({ "marker": format!("storm-{producer}") }),+ &agent_model(),+ Some("sess-timing"),+ u64::MAX,+ );+ }));+ }+ barrier.wait();+ for handle in handles {+ handle.join().expect("the producer finishes");+ }+ // The counter never exceeded the capacity and leaked nothing.+ let queued_after = super::CAPTURE_WRITER+ .get()+ .and_then(|writer| {+ writer+ .as_ref()+ .map(|writer| writer.queued.load(Ordering::Relaxed))+ })+ .expect("the writer is armed");+ assert!(+ queued_after <= REQUEST_PAYLOAD_CAPTURE_KEEP,+ "the reserve counter stays within the capacity: {queued_after}"+ );+ // The drain lands the stall body and every fill, and a fresh+ // handoff still reserves after the storm — a leaked reservation+ // would report saturation forever.+ wait_for_drained_queue();+ capture.record(+ &json!({ "marker": "recovered" }),+ &agent_model(),+ Some("sess-timing"),+ u64::MAX,+ );+ wait_for_payload_files(&dir_path, fills + 2);+ let landed = payload_files(&dir_path);+ let storm_body = landed.iter().any(|name| {+ std::fs::read_to_string(dir_path.join(name)).is_ok_and(|content| content.contains("storm-"))+ });+ assert!(+ !storm_body,+ "no storm body may land: every storm producer dropped at the reserve"+ );+ assert_eq!(+ landed.len(),+ fills + 2,+ "the stall body, every fill, and the recovery body: the queue bound held"+ );+}diff --git a/crates/pa-core/src/session_engine/request_timing/tests.rs b/crates/pa-core/src/session_engine/request_timing/tests.rsindex da20cf7681..abcc06bcf4 100644--- a/crates/pa-core/src/session_engine/request_timing/tests.rs+++ b/crates/pa-core/src/session_engine/request_timing/tests.rs@@ -849,3 +849,196 @@ async fn engine_sessions_emit_the_timeline_only_when_the_flag_is_on() {None => std::env::remove_var(REQUEST_TIMING_ENV),}}++/// A provider seam that invokes the payload hook once with the TS+/// `PAYLOAD` fixture, then settles with a zero-usage message (the pin is+/// the capture, not the turn).+fn payload_calling_provider() -> StreamFn {+ Arc::new(move |model, _context, options| {+ Box::pin(async move {+ if let Some(on_payload) = options.on_payload.as_ref() {+ let _ = on_payload(payload(), &model);+ }+ let (handle, consumer) = event_stream();+ let final_msg = empty_partial(&model);+ tokio::spawn(async move {+ handle.push(AssistantMessageEvent::Start {+ partial: final_msg.clone(),+ });+ handle.push(AssistantMessageEvent::Done {+ reason: StopReason::Stop,+ message: final_msg,+ });+ });+ Ok(Box::new(consumer) as Box<dyn ModelStream>)+ })+ })+}++/// The capture integration: while the flag is on, the instrumented+/// payload hook hands the request's final outbound body — after every+/// transform, exactly what the provider sees — to the capture's writer,+/// with the identity fields the timeline entries correlate by.+#[cfg(unix)]+#[tokio::test]+async fn the_payload_capture_writes_the_exact_outbound_body() {+ let _writer_lock = super::payload::WRITER_TEST_LOCK.lock().await;+ let dir = tempfile::tempdir().unwrap();+ let log_path = dir.path().join("agent.jsonl");+ let capture_dir = dir.path().join("request-payloads");+ let wiring = Arc::new(+ RequestTimingWiring::new(Arc::new(|| true), RequestTimingLog::at(&log_path))+ .with_payload_capture(RequestPayloadCapture::at(&capture_dir, 64)),+ );+ let stream = run_timed_request(+ Arc::clone(&wiring),+ scripted_provider(test_model(), gate().1, gate().1, gate().1, false),+ )+ .await+ .unwrap();+ drain(stream).await;++ super::payload::tests::wait_for_payload_files(&capture_dir, 1);+ let names = super::payload::tests::payload_files(&capture_dir);+ let envelope = super::payload::tests::payload_envelope(&capture_dir, &names[0]);+ assert_eq!(+ envelope.get("payload"),+ Some(&payload()),+ "the file carries the exact outbound body: {envelope}"+ );+ assert_eq!(+ envelope.get("model").and_then(Value::as_str),+ Some("bench/bench-model")+ );+ assert_eq!(+ envelope.get("provider").and_then(Value::as_str),+ Some("bench")+ );+ assert_eq!(envelope.get("sessionId"), Some(&json!("sess-timing")));+ assert_eq!(envelope.get("requestSeq"), Some(&json!(1)));+ assert_eq!(+ envelope.get("requestBytes"),+ Some(&json!(serde_json::to_vec(&payload()).unwrap().len() as u64)),+ "UTF-8 bytes, not a code-unit count: {envelope}"+ );+ // The timeline still emits: the capture rides the same flag.+ assert!(+ timing_entries(&log_path)+ .iter()+ .any(|entry| { entry.get("phase").and_then(Value::as_str) == Some("request-sent") }),+ "the phase timeline is unchanged"+ );+}++/// The capture rides the request-timing flag: disabled, the same request+/// hands off no body (and writes no timeline entry).+#[cfg(unix)]+#[tokio::test]+async fn the_payload_capture_writes_nothing_when_the_flag_is_off() {+ let dir = tempfile::tempdir().unwrap();+ let log_path = dir.path().join("agent.jsonl");+ let capture_dir = dir.path().join("request-payloads");+ let wiring = Arc::new(+ RequestTimingWiring::new(Arc::new(|| false), RequestTimingLog::at(&log_path))+ .with_payload_capture(RequestPayloadCapture::at(&capture_dir, 64)),+ );+ let stream = run_timed_request(+ Arc::clone(&wiring),+ scripted_provider(test_model(), gate().1, gate().1, gate().1, false),+ )+ .await+ .unwrap();+ drain(stream).await;+ assert!(+ super::payload::tests::payload_files(&capture_dir).is_empty(),+ "flag off captures no bodies"+ );+ assert!(+ timing_entries(&log_path).is_empty(),+ "flag off writes no entries"+ );+}++/// The engine path (the daemon workers' session build is this same+/// `create_session`): the wiring the engine installs captures while the+/// flag is on, and writes nothing while it is off.+#[cfg(unix)]+#[tokio::test]+async fn engine_sessions_capture_the_outbound_payload_when_the_flag_is_on() {+ use crate::session_engine::engine::{create_session, SessionEngineConfig};++ // Both shared-process locks: the env pin and the writer queue.+ let _writer_lock = super::payload::WRITER_TEST_LOCK.lock().await;+ let _env = REQUEST_TIMING_ENV_LOCK.lock().await;+ let previous_env = std::env::var(REQUEST_TIMING_ENV).ok();+ std::env::remove_var(REQUEST_TIMING_ENV);++ let dir = tempfile::tempdir().unwrap();+ let agent_dir = dir.path().join("agent");+ std::fs::create_dir_all(&agent_dir).unwrap();+ std::fs::write(+ agent_dir.join("settings.json"),+ r#"{"requestTiming": true}"#,+ )+ .unwrap();++ let engine = create_session(SessionEngineConfig {+ cwd: dir.path().to_path_buf(),+ agent_dir: agent_dir.clone(),+ model: Some(test_model()),+ stream_fn: Some(payload_calling_provider()),+ tools: Vec::new(),+ ..Default::default()+ })+ .await+ .unwrap();+ engine+ .session+ .prompt("hello", crate::session_engine::PromptOptions::default())+ .await+ .unwrap();+ engine.session.agent().wait_for_idle().await;++ let capture_dir = agent_dir.join("logs").join("request-payloads");+ super::payload::tests::wait_for_payload_files(&capture_dir, 1);+ let names = super::payload::tests::payload_files(&capture_dir);+ let envelope = super::payload::tests::payload_envelope(&capture_dir, &names[0]);+ assert_eq!(+ envelope.get("payload"),+ Some(&payload()),+ "the engine's capture carries the exact outbound body: {envelope}"+ );+ assert_eq!(+ envelope.get("model").and_then(Value::as_str),+ Some("bench/bench-model")+ );++ // Flag off: no capture directory at all (the wrapper passes+ // straight through with no serialization and no writes).+ let off_dir = tempfile::tempdir().unwrap();+ let engine = create_session(SessionEngineConfig {+ cwd: off_dir.path().to_path_buf(),+ agent_dir: off_dir.path().to_path_buf(),+ model: Some(test_model()),+ stream_fn: Some(payload_calling_provider()),+ tools: Vec::new(),+ ..Default::default()+ })+ .await+ .unwrap();+ engine+ .session+ .prompt("hello", crate::session_engine::PromptOptions::default())+ .await+ .unwrap();+ engine.session.agent().wait_for_idle().await;+ let off_capture = off_dir.path().join("logs").join("request-payloads");+ assert!(+ super::payload::tests::payload_files(&off_capture).is_empty() && !off_capture.exists(),+ "flag off leaves no capture"+ );+ match previous_env {+ Some(value) => std::env::set_var(REQUEST_TIMING_ENV, value),+ None => std::env::remove_var(REQUEST_TIMING_ENV),+ }+}diff --git a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs b/crates/pa-daemon/src/agent_engine/session_engine_impl.rsindex 5ab78cdbc5..d0356bd214 100644--- a/crates/pa-daemon/src/agent_engine/session_engine_impl.rs+++ b/crates/pa-daemon/src/agent_engine/session_engine_impl.rs@@ -506,9 +506,20 @@ impl SessionEngine for AgentSessionEngine {if let Some(core) = session.as_deref() {let provider = model.provider.clone();let model_id = model.id.clone();- let _ = self- .runtime- .block_on(core.session.set_model(&model, &provider, &model_id));+ // TS `setModel` re-applies the thinking level after the+ // model swap: the agent slot (the level the request carries)+ // must equal the level `configure_model` re-clamped above.+ // ONE agent-lock acquisition updates model and level+ // together — the loop snapshots both fields under the same+ // lock, so a turn admitted mid-switch never observes the+ // new model with the old level. No durable+ // `thinking_level_change` row: TS `setModel` records only+ // the model row; `/thinking` owns the intent row.+ let level = map_thinking_level(self.effective_thinking());+ let _ = self.runtime.block_on(+ core.session+ .set_model_and_thinking_level(&model, &provider, &model_id, level),+ );}// The children registry's inherited parent model follows the// switch (the build-time stamp alone would go stale): an inheriteddiff --git a/crates/pa-daemon/src/agent_engine/tests/model_resolution.rs b/crates/pa-daemon/src/agent_engine/tests/model_resolution.rsindex 313e344a0a..384b1790be 100644--- a/crates/pa-daemon/src/agent_engine/tests/model_resolution.rs+++ b/crates/pa-daemon/src/agent_engine/tests/model_resolution.rs@@ -1263,3 +1263,90 @@ async fn a_pre_read_saved_context_restores_like_the_file_read() {"the pre-read path restores the saved level, not the default");}++/// The engine/agent thinking-level sync pin: the engine's+/// `effective_thinking` (what `get_connection_state` reports) and the+/// built session's agent slot (what the request carries) must stay+/// equal across a model switch — TS `setModel` re-applies the level+/// after the swap (`_getThinkingLevelForModelSwitch` ++/// `setThinkingLevel`). The requested level survives the round trip+/// (high -> clamped off on the plain model -> high again).+#[test]+fn a_model_switch_keeps_the_agent_slot_in_sync_with_the_reported_level() {+ let dir = tempfile::TempDir::new().unwrap();+ let agent_dir = dir.path().join("agent");+ write_thinking_pair_models_json(&agent_dir, "http://127.0.0.1:9");+ let engine = AgentSessionEngine::new(AgentEngineConfig {+ cwd: dir.path().to_path_buf(),+ agent_dir,+ provider: Some("battery".to_string()),+ model: Some("mock-reason".to_string()),+ api_key: None,+ thinking: Some(pa_types::ai::ModelThinkingLevel::High),+ session_dir: None,+ session_file: None,+ faux_script: None,+ supervisor_link: None,+ telemetry_disabled: Some(true),+ cron_store: None,+ queued_steering_probe: None,+ })+ .unwrap();+ // Build the session: the agent's slot is seeded from the engine's+ // effective level (high on the reasoning model).+ let model = engine.resolve_model().expect("resolves mock-reason");+ engine+ .ensure_core_session(&model)+ .expect("the session builds");+ let agent_wire_level = |engine: &AgentSessionEngine| {+ let session = engine.session.blocking_lock();+ let core = session.as_deref().expect("the built session");+ let state = engine+ .runtime+ .block_on(async { core.session.agent().state().await });+ pa_core::session_engine::provider_adapter::model_thinking_level(state.thinking_level)+ .wire_name()+ .to_string()+ };+ assert_eq!(engine.effective_thinking_level().as_deref(), Some("high"));+ assert_eq!(agent_wire_level(&engine), "high");++ // The switch onto the plain model clamps the effective level to off:+ // the agent slot must follow (the request stops carrying a level the+ // switched-to model cannot serve).+ assert!(engine.switch_model(EngineModelSelection {+ provider: Some("battery".to_string()),+ model: Some("mock-plain".to_string()),+ api_key: None,+ thinking: None,+ }));+ assert_eq!(+ engine.effective_thinking_level().as_deref(),+ Some("off"),+ "the plain model clamps the requested high to off"+ );+ assert_eq!(+ agent_wire_level(&engine),+ "off",+ "the agent slot re-syncs to the re-clamped reported level"+ );++ // The requested level survives the round trip: switching back+ // re-clamps the SAME request (high) onto the reasoning model.+ assert!(engine.switch_model(EngineModelSelection {+ provider: Some("battery".to_string()),+ model: Some("mock-reason".to_string()),+ api_key: None,+ thinking: None,+ }));+ assert_eq!(+ engine.effective_thinking_level().as_deref(),+ Some("high"),+ "the requested level survives the round trip"+ );+ assert_eq!(+ agent_wire_level(&engine),+ "high",+ "the agent slot re-syncs to the restored level"+ );+}diff --git a/crates/pa-tui/src/snapshot/tests.rs b/crates/pa-tui/src/snapshot/tests.rsindex 3025edfb04..6436455828 100644--- a/crates/pa-tui/src/snapshot/tests.rs+++ b/crates/pa-tui/src/snapshot/tests.rs@@ -2286,3 +2286,7 @@ fn elided_image_tool_results_render_their_marker_metadata() {"Loaded 1 image(s) into context: /tmp/shot.png\n[Image: [image/png]]");}++/// The thinking-channel render pins (the two provider envelopes' stored+/// row shapes) live in their own child module with this file's harness.+mod thinking_pins;diff --git a/crates/pa-tui/src/snapshot/tests/thinking_pins.rs b/crates/pa-tui/src/snapshot/tests/thinking_pins.rsnew file mode 100644index 0000000000..d0b04eb41c--- /dev/null+++ b/crates/pa-tui/src/snapshot/tests/thinking_pins.rs@@ -0,0 +1,130 @@+//! The thinking-channel render pins: the two stored row shapes a+//! GLM-5.3-style session produces — the healthy row (a `thinking` block+//! plus a `text` block) and the content-only row (the reasoning merged+//! into the text block, no thinking block at all) — decode and render+//! faithfully. The thinking block is the only collapsible, detail-gated+//! surface; the content-only row's text renders as plain assistant output+//! at every detail level (nothing to widen: no predicate can reclassify+//! plain text).++use super::*;++#[test]+fn the_two_stored_row_shapes_render_their_channels_faithfully() {+ // The healthy row (trimmed): the reasoning rides a `thinking` block+ // with the reasoning_content signature.+ let healthy_row = json!({+ "role": "assistant",+ "model": "internal/glm-5.3-fast",+ "stopReason": "stop",+ "content": [+ { "type": "thinking", "thinking": "The operator asks: why do we need the nightly cron again?", "thinkingSignature": "reasoning_content" },+ { "type": "text", "text": "**The nightly cron exists for three reasons.**" }+ ]+ });+ // The content-only row (trimmed): the reasoning prose merged into the+ // text block — no thinking block at all.+ let leak_row = json!({+ "role": "assistant",+ "model": "internal/glm-5.3-fast",+ "stopReason": "stop",+ "content": [+ { "type": "text", "text": "The domain-flip PR is green. The plan: let me execute." }+ ]+ });+ // The decode (the store-row classifier): the healthy row keeps both+ // blocks, the content-only row only the text.+ let (healthy_blocks, healthy_calls) = assistant_message_parts(&healthy_row);+ assert_eq!(+ healthy_blocks,+ vec![+ MessageBlock::Thinking(+ "The operator asks: why do we need the nightly cron again?".to_string()+ ),+ MessageBlock::Text("**The nightly cron exists for three reasons.**".to_string()),+ ],+ "the healthy row decodes to its thinking and text blocks"+ );+ assert!(healthy_calls.is_empty());+ let (leak_blocks, leak_calls) = assistant_message_parts(&leak_row);+ assert_eq!(+ leak_blocks,+ vec![MessageBlock::Text(+ "The domain-flip PR is green. The plan: let me execute.".to_string()+ )],+ "the content-only row decodes to a single text block"+ );+ assert!(leak_calls.is_empty());++ let frame_text = |view: &mut crate::view::AgentView| -> Vec<String> {+ view.render_frame(80, 30).iter().map(line_text).collect()+ };++ // The healthy row renders the thinking block collapsible and+ // detail-gated: hidden at the collapsed default level, visible once+ // the detail cycle reveals thinking.+ let mut view = test_view();+ for entry in assistant_value_to_entries(&healthy_row) {+ view.push_entry(entry);+ }+ view.detail = crate::chat::Detail::Overview;+ let collapsed = frame_text(&mut view);+ assert!(+ !collapsed+ .iter()+ .any(|row| row.contains("nightly cron again")),+ "the thinking row is hidden at the collapsed level: {collapsed:?}"+ );+ assert!(+ collapsed+ .iter()+ .any(|row| row.contains("nightly cron exists for three reasons")),+ "the text block renders at every level: {collapsed:?}"+ );+ view.detail = crate::chat::Detail::Details;+ let expanded = frame_text(&mut view);+ assert!(+ expanded+ .iter()+ .any(|row| row.contains("nightly cron again")),+ "the thinking row renders once the detail level reveals it: {expanded:?}"+ );+ assert!(+ expanded+ .iter()+ .any(|row| row.contains("nightly cron exists for three reasons")),+ "the text block stays rendered at the revealed level: {expanded:?}"+ );++ // The content-only row renders as plain assistant text at EVERY+ // detail level: there is no thinking block to gate, so the frames+ // are identical.+ let mut leak_view = test_view();+ for entry in assistant_value_to_entries(&leak_row) {+ leak_view.push_entry(entry);+ }+ leak_view.detail = crate::chat::Detail::Overview;+ let leak_collapsed = frame_text(&mut leak_view);+ assert!(+ leak_collapsed+ .iter()+ .any(|row| row.contains("The domain-flip PR is green")),+ "the merged reasoning renders as plain assistant text: {leak_collapsed:?}"+ );+ leak_view.detail = crate::chat::Detail::All;+ let leak_expanded = frame_text(&mut leak_view);+ // The prompt-context row carries the detail label (the only frame+ // element that changes with the level): the transcript itself is+ // byte-identical — the text-only row has no gated content at all.+ let strip_label = |rows: &[String]| -> Vec<String> {+ rows.iter()+ .filter(|row| !row.contains(" mode ("))+ .cloned()+ .collect()+ };+ assert_eq!(+ strip_label(&leak_collapsed),+ strip_label(&leak_expanded),+ "the text-only row renders identically at every detail level"+ );+}