Skip to main content

rinne_workers/
mock.rs

1//! The mock worker (`CONTEXT.md` §14, §21).
2//!
3//! Replays a canned script — a sequence of streamed events plus a final result
4//! — without spawning any process or making any network call. This is what lets
5//! the loop engine be integration-tested (loop-backs, stuck-detection, resume)
6//! deterministically, without burning tokens or depending on a flaky beta CLI.
7
8use std::time::Instant;
9
10use async_trait::async_trait;
11use serde::{Deserialize, Serialize};
12use tokio_util::sync::CancellationToken;
13
14use rinne_core::worker::{
15    emit, AuthMode, Capability, EventSink, ExecStatus, ExecuteRequest, ExecuteResult,
16    LatencyProfile, QuotaModel, Transport, Worker, WorkerDescriptor, WorkerEvent, WorkerFamily,
17};
18use rinne_core::Result;
19
20/// A canned scenario the mock replays. Deserializable so tests can load
21/// transcripts from JSON fixtures on disk.
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct MockScript {
24    pub descriptor: WorkerDescriptor,
25    /// Events streamed before the result, in order. A trailing
26    /// [`WorkerEvent::Done`] is appended automatically if absent.
27    #[serde(default)]
28    pub events: Vec<WorkerEvent>,
29    /// The final normalized result.
30    pub result: ExecuteResult,
31    /// Optional delay between streamed events, to simulate real streaming and
32    /// give cancellation a window to fire.
33    #[serde(default)]
34    pub per_event_ms: u64,
35}
36
37impl MockScript {
38    /// A minimal successful script with a sensible default descriptor.
39    pub fn success(name: &str, result_text: &str) -> Self {
40        Self {
41            descriptor: default_descriptor(name),
42            events: vec![
43                WorkerEvent::Message(format!("{name}: starting")),
44                WorkerEvent::Message(format!("{name}: done")),
45            ],
46            result: ExecuteResult {
47                result: result_text.to_string(),
48                file_diff: None,
49                transcript: format!("[mock {name}] {result_text}"),
50                status: ExecStatus::Success,
51                usage: rinne_core::Usage {
52                    prompt_tokens: 100,
53                    completion_tokens: 50,
54                    wall_ms: 0,
55                },
56                session_id: None,
57            },
58            per_event_ms: 0,
59        }
60    }
61
62    /// A failing script (worker ran but reported failure).
63    pub fn failure(name: &str, reason: &str) -> Self {
64        let mut s = Self::success(name, "");
65        s.result.status = ExecStatus::Failed(reason.to_string());
66        s.result.result = format!("failed: {reason}");
67        s
68    }
69
70    /// Attach a unified diff to the result, e.g. for generator scripts.
71    pub fn with_diff(mut self, diff: &str) -> Self {
72        self.result.file_diff = Some(diff.to_string());
73        self
74    }
75
76    /// Replace the streamed events.
77    pub fn with_events(mut self, events: Vec<WorkerEvent>) -> Self {
78        self.events = events;
79        self
80    }
81}
82
83/// A default descriptor for a mock worker: capable of everything, free, fast.
84fn default_descriptor(name: &str) -> WorkerDescriptor {
85    WorkerDescriptor {
86        name: name.to_string(),
87        family: WorkerFamily::Harness,
88        capabilities: vec![
89            Capability::CodeEdit,
90            Capability::RepoAware,
91            Capability::ToolRun,
92            Capability::CodeReview,
93            Capability::Reasoning,
94            Capability::Writing,
95            Capability::LongContext,
96        ],
97        auth_mode: AuthMode::Free,
98        quota: QuotaModel::unlimited(),
99        latency: LatencyProfile::Fast,
100        transport: Transport::SubprocessJson,
101        models: Vec::new(),
102    }
103}
104
105/// A worker that replays a [`MockScript`].
106pub struct MockWorker {
107    script: MockScript,
108}
109
110impl MockWorker {
111    pub fn new(script: MockScript) -> Self {
112        Self { script }
113    }
114
115    /// Convenience constructor for a simple successful worker.
116    pub fn success(name: &str, result_text: &str) -> Self {
117        Self::new(MockScript::success(name, result_text))
118    }
119}
120
121#[async_trait]
122impl Worker for MockWorker {
123    fn descriptor(&self) -> &WorkerDescriptor {
124        &self.script.descriptor
125    }
126
127    async fn execute(
128        &self,
129        _request: ExecuteRequest,
130        events: EventSink,
131        cancel: CancellationToken,
132    ) -> Result<ExecuteResult> {
133        let started = Instant::now();
134
135        for event in &self.script.events {
136            if cancel.is_cancelled() {
137                return Ok(cancelled_result(started));
138            }
139            if self.script.per_event_ms > 0 {
140                // Race the delay against cancellation so `/pause` is responsive.
141                let sleep =
142                    tokio::time::sleep(std::time::Duration::from_millis(self.script.per_event_ms));
143                tokio::select! {
144                    _ = sleep => {}
145                    _ = cancel.cancelled() => return Ok(cancelled_result(started)),
146                }
147            }
148            emit(&events, event.clone());
149        }
150        emit(&events, WorkerEvent::Done);
151
152        let mut result = self.script.result.clone();
153        result.usage.wall_ms = started.elapsed().as_millis() as u64;
154        Ok(result)
155    }
156}
157
158fn cancelled_result(started: Instant) -> ExecuteResult {
159    ExecuteResult {
160        result: String::new(),
161        file_diff: None,
162        transcript: "[mock] cancelled".to_string(),
163        status: ExecStatus::Cancelled,
164        usage: rinne_core::Usage {
165            prompt_tokens: 0,
166            completion_tokens: 0,
167            wall_ms: started.elapsed().as_millis() as u64,
168        },
169        session_id: None,
170    }
171}